share-link-community

#7
by radames - opened
Files changed (2) hide show
  1. app.py +79 -33
  2. share_btn.py +114 -0
app.py CHANGED
@@ -16,6 +16,7 @@ from utils.richtext_utils import seed_everything, parse_json, get_region_diffusi
16
 
17
  import gradio as gr
18
  from PIL import Image, ImageOps
 
19
 
20
 
21
  help_text = """
@@ -43,6 +44,21 @@ async (text_input) => {
43
  }
44
  """
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  def main():
48
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
@@ -67,6 +83,8 @@ def main():
67
  guidance_weight = 8.5 if not guidance_weight else guidance_weight
68
  text_input = rich_text_input if rich_text_input != '' else text_input
69
  print('text_input', text_input)
 
 
70
  # parse json to span attributes
71
  base_text_prompt, style_text_prompts, footnote_text_prompts, footnote_target_tokens,\
72
  color_text_prompts, color_names, color_rgbs, size_text_prompts_and_sizes, use_grad_guidance = parse_json(
@@ -96,7 +114,8 @@ def main():
96
  plain_img = model.produce_attn_maps([base_text_prompt], [negative_text],
97
  height=height, width=width, num_inference_steps=steps,
98
  guidance_scale=guidance_weight)
99
- print('time lapses to get attention maps: %.4f' % (time.time()-begin_time))
 
100
  color_obj_masks, _ = get_token_maps(
101
  model.attention_maps, run_dir, width//8, height//8, color_target_token_ids, seed)
102
  model.masks, token_maps = get_token_maps(
@@ -104,7 +123,7 @@ def main():
104
  color_obj_masks = [transforms.functional.resize(color_obj_mask, (height, width),
105
  interpolation=transforms.InterpolationMode.BICUBIC,
106
  antialias=True)
107
- for color_obj_mask in color_obj_masks]
108
  text_format_dict['color_obj_atten'] = color_obj_masks
109
  model.remove_evaluation_hooks()
110
 
@@ -112,14 +131,15 @@ def main():
112
  begin_time = time.time()
113
  seed_everything(seed)
114
  rich_img = model.prompt_to_img(region_text_prompts, [negative_text],
115
- height=height, width=width, num_inference_steps=steps,
116
- guidance_scale=guidance_weight, use_grad_guidance=use_grad_guidance,
117
- text_format_dict=text_format_dict)
118
  print('time lapses to generate image from rich text: %.4f' %
119
- (time.time()-begin_time))
120
  return [plain_img[0], rich_img[0], token_maps]
121
 
122
- with gr.Blocks() as demo:
 
123
  gr.HTML("""<h1 style="font-weight: 900; margin-bottom: 7px;">Expressive Text-to-Image Generation with Rich Text</h1>
124
  <p> <a href="https://songweige.github.io/">Songwei Ge</a>, <a href="https://taesung.me/">Taesung Park</a>, <a href="https://www.cs.cmu.edu/~junyanz/">Jun-Yan Zhu</a>, <a href="https://jbhuang0604.github.io/">Jia-Bin Huang</a> <p/>
125
  <p> UMD, Adobe, CMU <p/>
@@ -133,16 +153,22 @@ def main():
133
  label='Rich-text JSON Input',
134
  visible=False,
135
  max_lines=1,
136
- placeholder='Example: \'{"ops":[{"insert":"a Gothic "},{"attributes":{"color":"#b26b00"},"insert":"church"},{"insert":" in a the sunset with a beautiful landscape in the background.\n"}]}\'')
 
 
137
  negative_prompt = gr.Textbox(
138
  label='Negative Prompt',
139
  max_lines=1,
140
- placeholder='Example: poor quality, blurry, dark, low resolution, low quality, worst quality')
 
 
141
  seed = gr.Slider(label='Seed',
142
  minimum=0,
143
  maximum=100000,
144
  step=1,
145
- value=6)
 
 
146
  color_guidance_weight = gr.Slider(label='Color weight lambda',
147
  minimum=0,
148
  maximum=2,
@@ -150,35 +176,44 @@ def main():
150
  value=0.5)
151
  with gr.Accordion('Other Parameters', open=False):
152
  steps = gr.Slider(label='Number of Steps',
153
- minimum=0,
154
- maximum=100,
155
- step=1,
156
- value=41)
157
  guidance_weight = gr.Slider(label='CFG weight',
158
- minimum=0,
159
- maximum=50,
160
- step=0.1,
161
- value=8.5)
162
  width = gr.Dropdown(choices=[512],
163
- value=512,
164
- label='Width',
165
- visible=True)
166
  height = gr.Dropdown(choices=[512],
167
- value=512,
168
- label='height',
169
- visible=True)
170
-
171
  with gr.Row():
172
  with gr.Column(scale=1, min_width=100):
173
  generate_button = gr.Button("Generate")
174
-
 
175
  with gr.Column():
176
- richtext_result = gr.Image(label='Rich-text')
 
177
  richtext_result.style(height=512)
178
  with gr.Row():
179
- plaintext_result = gr.Image(label='Plain-text')
 
180
  token_map = gr.Image(label='Token Maps')
181
-
 
 
 
 
 
 
182
  with gr.Row():
183
  gr.Markdown(help_text)
184
 
@@ -261,7 +296,7 @@ def main():
261
  None
262
  ],
263
  ]
264
-
265
  gr.Examples(examples=footnote_examples,
266
  label='Footnote examples',
267
  inputs=[
@@ -379,7 +414,7 @@ def main():
379
  fn=generate,
380
  # cache_examples=True,
381
  examples_per_page=20)
382
- generate_button.click(
383
  fn=generate,
384
  inputs=[
385
  text_input,
@@ -394,11 +429,22 @@ def main():
394
  ],
395
  outputs=[plaintext_result, richtext_result, token_map],
396
  _js=get_js_data
 
 
 
 
 
 
 
 
 
 
 
 
397
  )
398
- text_input.change(fn=None, inputs=[text_input], outputs=None, _js=set_js_data, queue=False)
399
  demo.queue(concurrency_count=1)
400
  demo.launch(share=False)
401
 
402
 
403
  if __name__ == "__main__":
404
- main()
 
16
 
17
  import gradio as gr
18
  from PIL import Image, ImageOps
19
+ from share_btn import community_icon_html, loading_icon_html, share_js, css
20
 
21
 
22
  help_text = """
 
44
  }
45
  """
46
 
47
+ get_window_url_params = """
48
+ async (url_params) => {
49
+ const params = new URLSearchParams(window.location.search);
50
+ url_params = Object.fromEntries(params);
51
+ return [url_params];
52
+ }
53
+ """
54
+
55
+
56
+ def load_url_params(url_params):
57
+ if 'prompt' in url_params:
58
+ return gr.update(visible=True), url_params
59
+ else:
60
+ return gr.update(visible=False), url_params
61
+
62
 
63
  def main():
64
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
 
83
  guidance_weight = 8.5 if not guidance_weight else guidance_weight
84
  text_input = rich_text_input if rich_text_input != '' else text_input
85
  print('text_input', text_input)
86
+ if (text_input == '' or rich_text_input == ''):
87
+ raise gr.Error("Please enter some text.")
88
  # parse json to span attributes
89
  base_text_prompt, style_text_prompts, footnote_text_prompts, footnote_target_tokens,\
90
  color_text_prompts, color_names, color_rgbs, size_text_prompts_and_sizes, use_grad_guidance = parse_json(
 
114
  plain_img = model.produce_attn_maps([base_text_prompt], [negative_text],
115
  height=height, width=width, num_inference_steps=steps,
116
  guidance_scale=guidance_weight)
117
+ print('time lapses to get attention maps: %.4f' %
118
+ (time.time()-begin_time))
119
  color_obj_masks, _ = get_token_maps(
120
  model.attention_maps, run_dir, width//8, height//8, color_target_token_ids, seed)
121
  model.masks, token_maps = get_token_maps(
 
123
  color_obj_masks = [transforms.functional.resize(color_obj_mask, (height, width),
124
  interpolation=transforms.InterpolationMode.BICUBIC,
125
  antialias=True)
126
+ for color_obj_mask in color_obj_masks]
127
  text_format_dict['color_obj_atten'] = color_obj_masks
128
  model.remove_evaluation_hooks()
129
 
 
131
  begin_time = time.time()
132
  seed_everything(seed)
133
  rich_img = model.prompt_to_img(region_text_prompts, [negative_text],
134
+ height=height, width=width, num_inference_steps=steps,
135
+ guidance_scale=guidance_weight, use_grad_guidance=use_grad_guidance,
136
+ text_format_dict=text_format_dict)
137
  print('time lapses to generate image from rich text: %.4f' %
138
+ (time.time()-begin_time))
139
  return [plain_img[0], rich_img[0], token_maps]
140
 
141
+ with gr.Blocks(css=css) as demo:
142
+ url_params = gr.JSON({}, visible=False, label="URL Params")
143
  gr.HTML("""<h1 style="font-weight: 900; margin-bottom: 7px;">Expressive Text-to-Image Generation with Rich Text</h1>
144
  <p> <a href="https://songweige.github.io/">Songwei Ge</a>, <a href="https://taesung.me/">Taesung Park</a>, <a href="https://www.cs.cmu.edu/~junyanz/">Jun-Yan Zhu</a>, <a href="https://jbhuang0604.github.io/">Jia-Bin Huang</a> <p/>
145
  <p> UMD, Adobe, CMU <p/>
 
153
  label='Rich-text JSON Input',
154
  visible=False,
155
  max_lines=1,
156
+ placeholder='Example: \'{"ops":[{"insert":"a Gothic "},{"attributes":{"color":"#b26b00"},"insert":"church"},{"insert":" in a the sunset with a beautiful landscape in the background.\n"}]}\'',
157
+ elem_id="text_input"
158
+ )
159
  negative_prompt = gr.Textbox(
160
  label='Negative Prompt',
161
  max_lines=1,
162
+ placeholder='Example: poor quality, blurry, dark, low resolution, low quality, worst quality',
163
+ elem_id="negative_prompt"
164
+ )
165
  seed = gr.Slider(label='Seed',
166
  minimum=0,
167
  maximum=100000,
168
  step=1,
169
+ value=6,
170
+ elem_id="seed"
171
+ )
172
  color_guidance_weight = gr.Slider(label='Color weight lambda',
173
  minimum=0,
174
  maximum=2,
 
176
  value=0.5)
177
  with gr.Accordion('Other Parameters', open=False):
178
  steps = gr.Slider(label='Number of Steps',
179
+ minimum=0,
180
+ maximum=100,
181
+ step=1,
182
+ value=41)
183
  guidance_weight = gr.Slider(label='CFG weight',
184
+ minimum=0,
185
+ maximum=50,
186
+ step=0.1,
187
+ value=8.5)
188
  width = gr.Dropdown(choices=[512],
189
+ value=512,
190
+ label='Width',
191
+ visible=True)
192
  height = gr.Dropdown(choices=[512],
193
+ value=512,
194
+ label='height',
195
+ visible=True)
196
+
197
  with gr.Row():
198
  with gr.Column(scale=1, min_width=100):
199
  generate_button = gr.Button("Generate")
200
+ load_params_button = gr.Button(
201
+ "Load from URL Params", visible=True)
202
  with gr.Column():
203
+ richtext_result = gr.Image(
204
+ label='Rich-text', elem_id="rich-text-image")
205
  richtext_result.style(height=512)
206
  with gr.Row():
207
+ plaintext_result = gr.Image(
208
+ label='Plain-text', elem_id="plain-text-image")
209
  token_map = gr.Image(label='Token Maps')
210
+ with gr.Row(visible=False) as share_row:
211
+ with gr.Group(elem_id="share-btn-container"):
212
+ community_icon = gr.HTML(community_icon_html)
213
+ loading_icon = gr.HTML(loading_icon_html)
214
+ share_button = gr.Button(
215
+ "Share to community", elem_id="share-btn")
216
+ share_button.click(None, [], [], _js=share_js)
217
  with gr.Row():
218
  gr.Markdown(help_text)
219
 
 
296
  None
297
  ],
298
  ]
299
+
300
  gr.Examples(examples=footnote_examples,
301
  label='Footnote examples',
302
  inputs=[
 
414
  fn=generate,
415
  # cache_examples=True,
416
  examples_per_page=20)
417
+ generate_button.click(fn=lambda: gr.update(visible=False), inputs=None, outputs=share_row, queue=False).then(
418
  fn=generate,
419
  inputs=[
420
  text_input,
 
429
  ],
430
  outputs=[plaintext_result, richtext_result, token_map],
431
  _js=get_js_data
432
+ ).then(
433
+ fn=lambda: gr.update(visible=True), inputs=None, outputs=share_row, queue=False)
434
+ text_input.change(
435
+ fn=None, inputs=[text_input], outputs=None, _js=set_js_data, queue=False)
436
+ # load url param prompt to textinput
437
+ load_params_button.click(fn=lambda x: x['prompt'], inputs=[
438
+ url_params], outputs=[text_input], queue=False)
439
+ demo.load(
440
+ fn=load_url_params,
441
+ inputs=[url_params],
442
+ outputs=[load_params_button, url_params],
443
+ _js=get_window_url_params
444
  )
 
445
  demo.queue(concurrency_count=1)
446
  demo.launch(share=False)
447
 
448
 
449
  if __name__ == "__main__":
450
+ main()
share_btn.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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" style="color: #ffffff;" 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>"""
7
+
8
+ share_js = """async () => {
9
+ async function uploadFile(file){
10
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
11
+ const response = await fetch(UPLOAD_URL, {
12
+ method: 'POST',
13
+ headers: {
14
+ 'Content-Type': file.type,
15
+ 'X-Requested-With': 'XMLHttpRequest',
16
+ },
17
+ body: file, /// <- File inherits from Blob
18
+ });
19
+ const url = await response.text();
20
+ return url;
21
+ }
22
+ async function getInputImageFile(imageEl){
23
+ const res = await fetch(imageEl.src);
24
+ const blob = await res.blob();
25
+ const imageId = Date.now();
26
+ const fileName = `rich-text-image-${{imageId}}.png`;
27
+ return new File([blob], fileName, { type: 'image/png'});
28
+ }
29
+ const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app');
30
+ const text_input = gradioEl.querySelector('#text_input input').value;
31
+ const negative_prompt = gradioEl.querySelector('#negative_prompt input').value;
32
+ const seed = gradioEl.querySelector('#seed input').value;
33
+ const richTextImg = gradioEl.querySelector('#rich-text-image img');
34
+ const plainTextImg = gradioEl.querySelector('#plain-text-image img');
35
+ const text_input_obj = JSON.parse(text_input);
36
+ const plain_prompt = text_input_obj.ops.map(e=> e.insert).join('');
37
+ const linkSrc = `https://huggingface.co/spaces/songweig/rich-text-to-image?prompt=${encodeURIComponent(text_input)}`;
38
+
39
+ const titleTxt = `RT2I: ${plain_prompt.slice(0, 50)}...`;
40
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
41
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
42
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
43
+ if(!richTextImg){
44
+ return;
45
+ };
46
+ shareBtnEl.style.pointerEvents = 'none';
47
+ shareIconEl.style.display = 'none';
48
+ loadingIconEl.style.removeProperty('display');
49
+
50
+ const richImgFile = await getInputImageFile(richTextImg);
51
+ const plainImgFile = await getInputImageFile(plainTextImg);
52
+ const richImgURL = await uploadFile(richImgFile);
53
+ const plainImgURL = await uploadFile(plainImgFile);
54
+
55
+ const descriptionMd = `
56
+ ### Plain Prompt
57
+ ${plain_prompt}
58
+
59
+ 🔗 Shareable Link + Params: [here](${linkSrc})
60
+
61
+ ### Rich Tech Image
62
+ <img src="${richImgURL}">
63
+
64
+ ### Plain Text Image
65
+ <img src="${plainImgURL}">
66
+
67
+ `;
68
+ const params = new URLSearchParams({
69
+ title: titleTxt,
70
+ description: descriptionMd,
71
+ });
72
+ const paramsStr = params.toString();
73
+ window.open(`https://huggingface.co/spaces/songweig/rich-text-to-image/discussions/new?${paramsStr}`, '_blank');
74
+ shareBtnEl.style.removeProperty('pointer-events');
75
+ shareIconEl.style.removeProperty('display');
76
+ loadingIconEl.style.display = 'none';
77
+ }"""
78
+
79
+ css = """
80
+ #share-btn-container {
81
+ display: flex;
82
+ padding-left: 0.5rem !important;
83
+ padding-right: 0.5rem !important;
84
+ background-color: #000000;
85
+ justify-content: center;
86
+ align-items: center;
87
+ border-radius: 9999px !important;
88
+ width: 13rem;
89
+ margin-top: 10px;
90
+ margin-left: auto;
91
+ flex: unset !important;
92
+ }
93
+ #share-btn {
94
+ all: initial;
95
+ color: #ffffff;
96
+ font-weight: 600;
97
+ cursor: pointer;
98
+ font-family: 'IBM Plex Sans', sans-serif;
99
+ margin-left: 0.5rem !important;
100
+ padding-top: 0.25rem !important;
101
+ padding-bottom: 0.25rem !important;
102
+ right:0;
103
+ }
104
+ #share-btn * {
105
+ all: unset !important;
106
+ }
107
+ #share-btn-container div:nth-child(-n+2){
108
+ width: auto !important;
109
+ min-height: 0px !important;
110
+ }
111
+ #share-btn-container .wrap {
112
+ display: none !important;
113
+ }
114
+ """