chaoxu commited on
Commit
aa1245a
1 Parent(s): b722467

add share btn and duplicate btn

Browse files
Files changed (3) hide show
  1. gradio_app.py +30 -11
  2. share_btn.py +84 -0
  3. style.css +17 -0
gradio_app.py CHANGED
@@ -5,6 +5,7 @@ import gradio as gr
5
  from PIL import Image
6
  from functools import partial
7
  from diffusers import DiffusionPipeline, EulerAncestralDiscreteScheduler
 
8
 
9
  import cv2
10
  import time
@@ -117,11 +118,16 @@ def gen_multiview(pipeline, predictor, input_image, scale_slider, steps_slider,
117
  subimages = [image.crop((x, y, x + side_len, y+side_len)) for y in range(0, image.height, side_len) for x in range(0, image.width, side_len)]
118
  if "Background Removal" in output_processing:
119
  out_images = []
120
- for sub_image in subimages:
 
121
  sub_image, _ = preprocess(predictor, sub_image.convert('RGB'), segment=True, rescale=False)
122
  out_images.append(sub_image)
123
- return out_images
124
- return subimages
 
 
 
 
125
 
126
 
127
  def run_demo():
@@ -141,18 +147,18 @@ def run_demo():
141
  custom_theme = gr.themes.Soft(primary_hue="blue").set(
142
  button_secondary_background_fill="*neutral_100",
143
  button_secondary_background_fill_hover="*neutral_200")
144
- custom_css = '''#disp_image {
145
- text-align: center; /* Horizontally center the content */
146
- }'''
147
 
148
- with gr.Blocks(title=_TITLE, theme=custom_theme, css=custom_css) as demo:
149
  with gr.Row():
150
  with gr.Column(scale=1):
151
  gr.Markdown('# ' + _TITLE)
 
 
 
152
  gr.Markdown(_DESCRIPTION)
153
  with gr.Row(variant='panel'):
154
  with gr.Column(scale=1):
155
- input_image = gr.Image(type='pil', image_mode='RGBA', height=320, label='Input image', tool=None)
156
 
157
  example_folder = os.path.join(os.path.dirname(__file__), "./resources/examples")
158
  example_fns = [os.path.join(example_folder, example) for example in os.listdir(example_folder)]
@@ -171,11 +177,13 @@ def run_demo():
171
  with gr.Column():
172
  output_processing = gr.CheckboxGroup(['Background Removal'], label='Output Image Postprocessing', value=[])
173
  scale_slider = gr.Slider(1, 10, value=4, step=1,
 
174
  label='Classifier Free Guidance Scale')
175
  steps_slider = gr.Slider(15, 100, value=75, step=1,
176
  label='Number of Diffusion Inference Steps',
 
177
  info="For general real or synthetic objects, around 28 is enough. For objects with delicate details such as faces (either realistic or illustration), you may need 75 or more steps.")
178
- seed = gr.Number(42, label='Seed')
179
  run_btn = gr.Button('Generate', variant='primary', interactive=True)
180
  with gr.Column(scale=1):
181
  processed_image = gr.Image(type='pil', label="Processed Image", interactive=False, height=320, tool=None, image_mode='RGBA', elem_id="disp_image")
@@ -188,15 +196,26 @@ def run_demo():
188
  view_4 = gr.Image(interactive=False, height=240, show_label=False)
189
  view_5 = gr.Image(interactive=False, height=240, show_label=False)
190
  view_6 = gr.Image(interactive=False, height=240, show_label=False)
 
 
 
 
 
191
 
 
 
192
 
193
- run_btn.click(fn=partial(preprocess, predictor),
 
 
194
  inputs=[input_image, input_processing],
195
  outputs=[processed_image_highres, processed_image], queue=True
196
  ).success(fn=partial(gen_multiview, pipeline, predictor),
197
  inputs=[processed_image_highres, scale_slider, steps_slider, seed, output_processing],
198
- outputs=[view_1, view_2, view_3, view_4, view_5, view_6])
 
199
 
 
200
  demo.queue().launch(share=False, max_threads=80, server_name="0.0.0.0", server_port=7860)
201
 
202
 
 
5
  from PIL import Image
6
  from functools import partial
7
  from diffusers import DiffusionPipeline, EulerAncestralDiscreteScheduler
8
+ from share_btn import community_icon_html, loading_icon_html, share_js
9
 
10
  import cv2
11
  import time
 
118
  subimages = [image.crop((x, y, x + side_len, y+side_len)) for y in range(0, image.height, side_len) for x in range(0, image.width, side_len)]
119
  if "Background Removal" in output_processing:
120
  out_images = []
121
+ merged_image = Image.new('RGB', (640, 960))
122
+ for i, sub_image in enumerate(subimages):
123
  sub_image, _ = preprocess(predictor, sub_image.convert('RGB'), segment=True, rescale=False)
124
  out_images.append(sub_image)
125
+ # Merge into a 2x3 grid
126
+ x = 0 if i < 3 else 320
127
+ y = (i % 3) * 320
128
+ merged_image.paste(sub_image, (x, y))
129
+ return out_images + [merged_image]
130
+ return subimages + [image]
131
 
132
 
133
  def run_demo():
 
147
  custom_theme = gr.themes.Soft(primary_hue="blue").set(
148
  button_secondary_background_fill="*neutral_100",
149
  button_secondary_background_fill_hover="*neutral_200")
 
 
 
150
 
151
+ with gr.Blocks(title=_TITLE, theme=custom_theme, css="style.css") as demo:
152
  with gr.Row():
153
  with gr.Column(scale=1):
154
  gr.Markdown('# ' + _TITLE)
155
+ with gr.Column(scale=0):
156
+ gr.DuplicateButton(value='Duplicate Space for private use',
157
+ elem_id='duplicate-button')
158
  gr.Markdown(_DESCRIPTION)
159
  with gr.Row(variant='panel'):
160
  with gr.Column(scale=1):
161
+ input_image = gr.Image(type='pil', image_mode='RGBA', height=320, label='Input image', tool=None, elem_id="input_image")
162
 
163
  example_folder = os.path.join(os.path.dirname(__file__), "./resources/examples")
164
  example_fns = [os.path.join(example_folder, example) for example in os.listdir(example_folder)]
 
177
  with gr.Column():
178
  output_processing = gr.CheckboxGroup(['Background Removal'], label='Output Image Postprocessing', value=[])
179
  scale_slider = gr.Slider(1, 10, value=4, step=1,
180
+ elem_id="scale",
181
  label='Classifier Free Guidance Scale')
182
  steps_slider = gr.Slider(15, 100, value=75, step=1,
183
  label='Number of Diffusion Inference Steps',
184
+ elem_id="num_steps",
185
  info="For general real or synthetic objects, around 28 is enough. For objects with delicate details such as faces (either realistic or illustration), you may need 75 or more steps.")
186
+ seed = gr.Number(42, label='Seed', elem_id="seed")
187
  run_btn = gr.Button('Generate', variant='primary', interactive=True)
188
  with gr.Column(scale=1):
189
  processed_image = gr.Image(type='pil', label="Processed Image", interactive=False, height=320, tool=None, image_mode='RGBA', elem_id="disp_image")
 
196
  view_4 = gr.Image(interactive=False, height=240, show_label=False)
197
  view_5 = gr.Image(interactive=False, height=240, show_label=False)
198
  view_6 = gr.Image(interactive=False, height=240, show_label=False)
199
+ full_view = gr.Image(visible=False, interactive=False, elem_id="six_view")
200
+ with gr.Group(elem_id="share-btn-container", visible=False) as share_group:
201
+ community_icon = gr.HTML(community_icon_html)
202
+ loading_icon = gr.HTML(loading_icon_html)
203
+ share_button = gr.Button("Share to community", elem_id="share-btn")
204
 
205
+ show_share_btn = lambda: gr.Group(visible=True)
206
+ hide_share_btn = lambda: gr.Group(visible=False)
207
 
208
+ input_image.change(hide_share_btn, outputs=share_group, queue=False)
209
+ run_btn.click(hide_share_btn, outputs=share_group, queue=False
210
+ ).success(fn=partial(preprocess, predictor),
211
  inputs=[input_image, input_processing],
212
  outputs=[processed_image_highres, processed_image], queue=True
213
  ).success(fn=partial(gen_multiview, pipeline, predictor),
214
  inputs=[processed_image_highres, scale_slider, steps_slider, seed, output_processing],
215
+ outputs=[view_1, view_2, view_3, view_4, view_5, view_6, full_view], queue=True
216
+ ).success(show_share_btn, outputs=share_group, queue=False)
217
 
218
+ share_button.click(None, [], [], _js=share_js)
219
  demo.queue().launch(share=False, max_threads=80, server_name="0.0.0.0", server_port=7860)
220
 
221
 
share_btn.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
+ <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
+ <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
+ style="color: #ffffff;
8
+ "
9
+ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
10
+
11
+ share_js = """async () => {
12
+ async function uploadFile(file){
13
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
14
+ const response = await fetch(UPLOAD_URL, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': file.type,
18
+ 'X-Requested-With': 'XMLHttpRequest',
19
+ },
20
+ body: file, /// <- File inherits from Blob
21
+ });
22
+ const url = await response.text();
23
+ return url;
24
+ }
25
+
26
+ async function getInputImgFile(imgEl){
27
+ const res = await fetch(imgEl.src);
28
+ const blob = await res.blob();
29
+ const imgId = Date.now() % 200;
30
+ const isPng = imgEl.src.startsWith(`data:image/png`);
31
+ if(isPng){
32
+ const fileName = `sd-perception-${{imgId}}.png`;
33
+ return new File([blob], fileName, { type: 'image/png' });
34
+ }else{
35
+ const fileName = `sd-perception-${{imgId}}.jpg`;
36
+ return new File([blob], fileName, { type: 'image/jpeg' });
37
+ }
38
+ }
39
+
40
+ const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app');
41
+
42
+ const seed = gradioEl.querySelector('#seed input[type="number"]').value;
43
+ const scale = gradioEl.querySelector('#scale input[type="number"]').value;
44
+ const num_steps = gradioEl.querySelector('#num_steps input[type="number"]').value;
45
+ const controlImage = gradioEl.querySelector('#input_image img');
46
+ const outputImgEl = gradioEl.querySelector('#six_view img');
47
+
48
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
49
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
50
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
51
+
52
+ shareBtnEl.style.pointerEvents = 'none';
53
+ shareIconEl.style.display = 'none';
54
+ loadingIconEl.style.removeProperty('display');
55
+
56
+ const outputFile = await getInputImgFile(outputImgEl);
57
+ const urlOutputImg = await uploadFile(outputFile);
58
+
59
+ const controlFile = await getInputImgFile(controlImage);
60
+ const urlControlImg = await uploadFile(controlFile);
61
+
62
+ const descriptionMd = `
63
+ #### Generated Multiviews:
64
+ <img src="${urlOutputImg}" />
65
+
66
+ #### Input Image:
67
+ <img src="${urlControlImg}" />
68
+
69
+ #### Parameters:
70
+ - *Seed*: ${seed}
71
+ - *Classifier Free Guidance Scale*: ${scale}
72
+ - *Number of Diffusion Inference Steps*: ${num_steps}
73
+ `;
74
+ const params = new URLSearchParams({
75
+ title: inputPrompt,
76
+ description: descriptionMd,
77
+ preview: true
78
+ });
79
+ const paramsStr = params.toString();
80
+ window.open(`https://huggingface.co/spaces/sudo-ai/zero123plus-demo-space/discussions/new?${paramsStr}`, '_blank');
81
+ shareBtnEl.style.removeProperty('pointer-events');
82
+ shareIconEl.style.removeProperty('display');
83
+ loadingIconEl.style.display = 'none';
84
+ }"""
style.css ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #disp_image {
2
+ text-align: center; /* Horizontally center the content */
3
+ }
4
+ #share-btn-container {padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; max-width: 13rem; margin-left: auto;}
5
+ div#share-btn-container > div {flex-direction: row;background: black;align-items: center}
6
+ #share-btn-container:hover {background-color: #060606}
7
+ #share-btn {all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.5rem !important; padding-bottom: 0.5rem !important;right:0;}
8
+ #share-btn * {all: unset}
9
+ #share-btn-container div:nth-child(-n+2){width: auto !important;min-height: 0px !important;}
10
+ #share-btn-container .wrap {display: none !important}
11
+ #share-btn-container.hidden {display: none!important}
12
+
13
+ #duplicate-button {
14
+ margin-left: auto;
15
+ color: #fff;
16
+ background: #1565c0;
17
+ }