JingyeChen22 commited on
Commit
0c06605
·
1 Parent(s): c947ade
Files changed (1) hide show
  1. app.py +534 -0
app.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import zipfile
4
+ import torch
5
+ import gradio as gr
6
+ import time
7
+ from transformers import CLIPTextModel, CLIPTokenizer
8
+ from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel, DiffusionPipeline, LCMScheduler
9
+ from tqdm import tqdm
10
+ from PIL import Image
11
+ from PIL import Image, ImageDraw, ImageFont
12
+ import random
13
+ import copy
14
+
15
+ import string
16
+ alphabet = string.digits + string.ascii_lowercase + string.ascii_uppercase + string.punctuation + ' ' # len(aphabet) = 95
17
+ '''alphabet
18
+ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~
19
+ '''
20
+
21
+ if not os.path.exists('images2'):
22
+ os.system('wget https://huggingface.co/datasets/JingyeChen22/TextDiffuser/resolve/main/images2.zip')
23
+ with zipfile.ZipFile('images2.zip', 'r') as zip_ref:
24
+ zip_ref.extractall('.')
25
+
26
+ # os.system('nvidia-smi')
27
+ os.system('ls')
28
+
29
+ #### import m1
30
+ from fastchat.model import load_model, get_conversation_template
31
+ from transformers import AutoTokenizer, AutoModelForCausalLM
32
+ m1_model_path = 'JingyeChen22/textdiffuser2_layout_planner'
33
+ # m1_model, m1_tokenizer = load_model(
34
+ # m1_model_path,
35
+ # 'cuda',
36
+ # 1,
37
+ # None,
38
+ # False,
39
+ # False,
40
+ # revision="main",
41
+ # debug=False,
42
+ # )
43
+
44
+ m1_tokenizer = AutoTokenizer.from_pretrained(m1_model_path, use_fast=False)
45
+ m1_model = AutoModelForCausalLM.from_pretrained(
46
+ m1_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True
47
+ ).cuda()
48
+
49
+ #### import diffusion models
50
+ text_encoder = CLIPTextModel.from_pretrained(
51
+ 'JingyeChen22/textdiffuser2-full-ft', subfolder="text_encoder"
52
+ ).cuda().half()
53
+ tokenizer = CLIPTokenizer.from_pretrained(
54
+ 'runwayml/stable-diffusion-v1-5', subfolder="tokenizer"
55
+ )
56
+
57
+ #### additional tokens are introduced, including coordinate tokens and character tokens
58
+ print('***************')
59
+ print(len(tokenizer))
60
+ for i in range(520):
61
+ tokenizer.add_tokens(['l' + str(i) ]) # left
62
+ tokenizer.add_tokens(['t' + str(i) ]) # top
63
+ tokenizer.add_tokens(['r' + str(i) ]) # width
64
+ tokenizer.add_tokens(['b' + str(i) ]) # height
65
+ for c in alphabet:
66
+ tokenizer.add_tokens([f'[{c}]'])
67
+ print(len(tokenizer))
68
+ print('***************')
69
+
70
+ vae = AutoencoderKL.from_pretrained('runwayml/stable-diffusion-v1-5', subfolder="vae").half().cuda()
71
+ unet = UNet2DConditionModel.from_pretrained(
72
+ 'JingyeChen22/textdiffuser2-full-ft', subfolder="unet"
73
+ ).half().cuda()
74
+ text_encoder.resize_token_embeddings(len(tokenizer))
75
+
76
+
77
+ #### load lcm components
78
+ model_id = "lambdalabs/sd-pokemon-diffusers"
79
+ lcm_lora_id = "latent-consistency/lcm-lora-sdv1-5"
80
+ pipe = DiffusionPipeline.from_pretrained(model_id, unet=copy.deepcopy(unet), tokenizer=tokenizer, text_encoder=copy.deepcopy(text_encoder), torch_dtype=torch.float16)
81
+ pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config)
82
+ pipe.load_lora_weights(lcm_lora_id)
83
+ pipe.to(device="cuda")
84
+
85
+
86
+ #### for interactive
87
+ stack = []
88
+ state = 0
89
+ font = ImageFont.truetype("./Arial.ttf", 32)
90
+
91
+ def skip_fun(i, t):
92
+ global state
93
+ state = 0
94
+
95
+
96
+ def exe_undo(i, t):
97
+ global stack
98
+ global state
99
+ state = 0
100
+ stack = []
101
+ image = Image.open(f'./gray256.jpg')
102
+ print('stack', stack)
103
+ return image
104
+
105
+
106
+ def exe_redo(i, t):
107
+ global state
108
+ state = 0
109
+
110
+ if len(stack) > 0:
111
+ stack.pop()
112
+ image = Image.open(f'./gray256.jpg')
113
+ draw = ImageDraw.Draw(image)
114
+
115
+ for items in stack:
116
+ # print('now', items)
117
+ text_position, t = items
118
+ if len(text_position) == 2:
119
+ x, y = text_position
120
+ text_color = (255, 0, 0)
121
+ draw.text((x+2, y), t, font=font, fill=text_color)
122
+ r = 4
123
+ leftUpPoint = (x-r, y-r)
124
+ rightDownPoint = (x+r, y+r)
125
+ draw.ellipse((leftUpPoint,rightDownPoint), fill='red')
126
+ elif len(text_position) == 4:
127
+ x0, y0, x1, y1 = text_position
128
+ text_color = (255, 0, 0)
129
+ draw.text((x0+2, y0), t, font=font, fill=text_color)
130
+ r = 4
131
+ leftUpPoint = (x0-r, y0-r)
132
+ rightDownPoint = (x0+r, y0+r)
133
+ draw.ellipse((leftUpPoint,rightDownPoint), fill='red')
134
+ draw.rectangle((x0,y0,x1,y1), outline=(255, 0, 0) )
135
+
136
+ print('stack', stack)
137
+ return image
138
+
139
+ def get_pixels(i, t, evt: gr.SelectData):
140
+ global state
141
+
142
+ text_position = evt.index
143
+
144
+ if state == 0:
145
+ stack.append(
146
+ (text_position, t)
147
+ )
148
+ print(text_position, stack)
149
+ state = 1
150
+ else:
151
+
152
+ (_, t) = stack.pop()
153
+ x, y = _
154
+ stack.append(
155
+ ((x,y,text_position[0],text_position[1]), t)
156
+ )
157
+ state = 0
158
+
159
+
160
+ image = Image.open(f'./gray256.jpg')
161
+ draw = ImageDraw.Draw(image)
162
+
163
+ for items in stack:
164
+ # print('now', items)
165
+ text_position, t = items
166
+ if len(text_position) == 2:
167
+ x, y = text_position
168
+ text_color = (255, 0, 0)
169
+ draw.text((x+2, y), t, font=font, fill=text_color)
170
+ r = 4
171
+ leftUpPoint = (x-r, y-r)
172
+ rightDownPoint = (x+r, y+r)
173
+ draw.ellipse((leftUpPoint,rightDownPoint), fill='red')
174
+ elif len(text_position) == 4:
175
+ x0, y0, x1, y1 = text_position
176
+ text_color = (255, 0, 0)
177
+ draw.text((x0+2, y0), t, font=font, fill=text_color)
178
+ r = 4
179
+ leftUpPoint = (x0-r, y0-r)
180
+ rightDownPoint = (x0+r, y0+r)
181
+ draw.ellipse((leftUpPoint,rightDownPoint), fill='red')
182
+ draw.rectangle((x0,y0,x1,y1), outline=(255, 0, 0) )
183
+
184
+ print('stack', stack)
185
+
186
+ return image
187
+
188
+
189
+ font_layout = ImageFont.truetype('./Arial.ttf', 16)
190
+
191
+ def get_layout_image(ocrs):
192
+
193
+ blank = Image.new('RGB', (256,256), (0,0,0))
194
+ draw = ImageDraw.ImageDraw(blank)
195
+
196
+ for line in ocrs.split('\n'):
197
+ line = line.strip()
198
+
199
+ if len(line) == 0:
200
+ break
201
+
202
+ pred = ' '.join(line.split()[:-1])
203
+ box = line.split()[-1]
204
+ l, t, r, b = [int(i)*2 for i in box.split(',')] # the size of canvas is 256x256
205
+ draw.rectangle([(l, t), (r, b)], outline ="red")
206
+ draw.text((l, t), pred, font=font_layout)
207
+
208
+ return blank
209
+
210
+
211
+
212
+ def text_to_image(prompt,keywords,positive_prompt,radio,slider_step,slider_guidance,slider_batch,slider_temperature,slider_natural):
213
+
214
+ global stack
215
+ global state
216
+
217
+ if len(positive_prompt.strip()) != 0:
218
+ prompt += positive_prompt
219
+
220
+ with torch.no_grad():
221
+ time1 = time.time()
222
+ user_prompt = prompt
223
+
224
+ if slider_natural:
225
+ user_prompt = f'{user_prompt}'
226
+ composed_prompt = user_prompt
227
+ prompt = tokenizer.encode(user_prompt)
228
+ layout_image = None
229
+ else:
230
+ if len(stack) == 0:
231
+
232
+ if len(keywords.strip()) == 0:
233
+ template = f'Given a prompt that will be used to generate an image, plan the layout of visual text for the image. The size of the image is 128x128. Therefore, all properties of the positions should not exceed 128, including the coordinates of top, left, right, and bottom. All keywords are included in the caption. You dont need to specify the details of font styles. At each line, the format should be keyword left, top, right, bottom. So let us begin. Prompt: {user_prompt}'
234
+ else:
235
+ keywords = keywords.split('/')
236
+ keywords = [i.strip() for i in keywords]
237
+ template = f'Given a prompt that will be used to generate an image, plan the layout of visual text for the image. The size of the image is 128x128. Therefore, all properties of the positions should not exceed 128, including the coordinates of top, left, right, and bottom. In addition, we also provide all keywords at random order for reference. You dont need to specify the details of font styles. At each line, the format should be keyword left, top, right, bottom. So let us begin. Prompt: {prompt}. Keywords: {str(keywords)}'
238
+
239
+ msg = template
240
+ conv = get_conversation_template(m1_model_path)
241
+ conv.append_message(conv.roles[0], msg)
242
+ conv.append_message(conv.roles[1], None)
243
+ prompt = conv.get_prompt()
244
+ inputs = m1_tokenizer([prompt], return_token_type_ids=False)
245
+ inputs = {k: torch.tensor(v).to('cuda') for k, v in inputs.items()}
246
+ output_ids = m1_model.generate(
247
+ **inputs,
248
+ do_sample=True,
249
+ temperature=slider_temperature,
250
+ repetition_penalty=1.0,
251
+ max_new_tokens=512,
252
+ )
253
+
254
+ if m1_model.config.is_encoder_decoder:
255
+ output_ids = output_ids[0]
256
+ else:
257
+ output_ids = output_ids[0][len(inputs["input_ids"][0]) :]
258
+ outputs = m1_tokenizer.decode(
259
+ output_ids, skip_special_tokens=True, spaces_between_special_tokens=False
260
+ )
261
+ print(f"[{conv.roles[0]}]\n{msg}")
262
+ print(f"[{conv.roles[1]}]\n{outputs}")
263
+ layout_image = get_layout_image(outputs)
264
+
265
+ ocrs = outputs.split('\n')
266
+ time2 = time.time()
267
+ print(time2-time1)
268
+
269
+ # user_prompt = prompt
270
+ current_ocr = ocrs
271
+
272
+
273
+ ocr_ids = []
274
+ print('user_prompt', user_prompt)
275
+ print('current_ocr', current_ocr)
276
+
277
+
278
+ for ocr in current_ocr:
279
+ ocr = ocr.strip()
280
+
281
+ if len(ocr) == 0 or '###' in ocr or '.com' in ocr:
282
+ continue
283
+
284
+ items = ocr.split()
285
+ pred = ' '.join(items[:-1])
286
+ box = items[-1]
287
+
288
+ l,t,r,b = box.split(',')
289
+ l,t,r,b = int(l), int(t), int(r), int(b)
290
+ ocr_ids.extend(['l'+str(l), 't'+str(t), 'r'+str(r), 'b'+str(b)])
291
+
292
+ char_list = list(pred)
293
+ char_list = [f'[{i}]' for i in char_list]
294
+ ocr_ids.extend(char_list)
295
+ ocr_ids.append(tokenizer.eos_token_id)
296
+
297
+ caption_ids = tokenizer(
298
+ user_prompt, truncation=True, return_tensors="pt"
299
+ ).input_ids[0].tolist()
300
+
301
+ try:
302
+ ocr_ids = tokenizer.encode(ocr_ids)
303
+ prompt = caption_ids + ocr_ids
304
+ except:
305
+ prompt = caption_ids
306
+
307
+ user_prompt = tokenizer.decode(prompt)
308
+ composed_prompt = tokenizer.decode(prompt)
309
+
310
+ else:
311
+ user_prompt += ' <|endoftext|>'
312
+ layout_image = None
313
+
314
+ for items in stack:
315
+ position, text = items
316
+
317
+
318
+ if len(position) == 2:
319
+ x, y = position
320
+ x = x // 4
321
+ y = y // 4
322
+ text_str = ' '.join([f'[{c}]' for c in list(text)])
323
+ user_prompt += f'<|startoftext|> l{x} t{y} {text_str} <|endoftext|>'
324
+ elif len(position) == 4:
325
+ x0, y0, x1, y1 = position
326
+ x0 = x0 // 4
327
+ y0 = y0 // 4
328
+ x1 = x1 // 4
329
+ y1 = y1 // 4
330
+ text_str = ' '.join([f'[{c}]' for c in list(text)])
331
+ user_prompt += f'<|startoftext|> l{x0} t{y0} r{x1} b{y1} {text_str} <|endoftext|>'
332
+
333
+ # composed_prompt = user_prompt
334
+ prompt = tokenizer.encode(user_prompt)
335
+ composed_prompt = tokenizer.decode(prompt)
336
+
337
+ prompt = prompt[:77]
338
+ while len(prompt) < 77:
339
+ prompt.append(tokenizer.pad_token_id)
340
+
341
+ if radio == 'TextDiffuser-2':
342
+
343
+ prompts_cond = prompt
344
+ prompts_nocond = [tokenizer.pad_token_id]*77
345
+
346
+ prompts_cond = [prompts_cond] * slider_batch
347
+ prompts_nocond = [prompts_nocond] * slider_batch
348
+
349
+ prompts_cond = torch.Tensor(prompts_cond).long().cuda()
350
+ prompts_nocond = torch.Tensor(prompts_nocond).long().cuda()
351
+
352
+ scheduler = DDPMScheduler.from_pretrained('runwayml/stable-diffusion-v1-5', subfolder="scheduler")
353
+ scheduler.set_timesteps(slider_step)
354
+ noise = torch.randn((slider_batch, 4, 64, 64)).to("cuda").half()
355
+ input = noise
356
+
357
+ encoder_hidden_states_cond = text_encoder(prompts_cond)[0].half()
358
+ encoder_hidden_states_nocond = text_encoder(prompts_nocond)[0].half()
359
+
360
+
361
+ for t in tqdm(scheduler.timesteps):
362
+ with torch.no_grad(): # classifier free guidance
363
+ noise_pred_cond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states_cond[:slider_batch]).sample # b, 4, 64, 64
364
+ noise_pred_uncond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states_nocond[:slider_batch]).sample # b, 4, 64, 64
365
+ noisy_residual = noise_pred_uncond + slider_guidance * (noise_pred_cond - noise_pred_uncond) # b, 4, 64, 64
366
+ input = scheduler.step(noisy_residual, t, input).prev_sample
367
+ del noise_pred_cond
368
+ del noise_pred_uncond
369
+
370
+ torch.cuda.empty_cache()
371
+
372
+ # decode
373
+ input = 1 / vae.config.scaling_factor * input
374
+ images = vae.decode(input, return_dict=False)[0]
375
+ width, height = 512, 512
376
+ results = []
377
+ new_image = Image.new('RGB', (2*width, 2*height))
378
+ for index, image in enumerate(images.cpu().float()):
379
+ image = (image / 2 + 0.5).clamp(0, 1).unsqueeze(0)
380
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
381
+ image = Image.fromarray((image * 255).round().astype("uint8")).convert('RGB')
382
+ results.append(image)
383
+ row = index // 2
384
+ col = index % 2
385
+ new_image.paste(image, (col*width, row*height))
386
+ # os.system('nvidia-smi')
387
+ torch.cuda.empty_cache()
388
+ # os.system('nvidia-smi')
389
+ return tuple(results), composed_prompt, layout_image
390
+
391
+ elif radio == 'TextDiffuser-2-LCM':
392
+ generator = torch.Generator(device=pipe.device).manual_seed(random.randint(0,1000))
393
+ image = pipe(
394
+ prompt=user_prompt,
395
+ generator=generator,
396
+ # negative_prompt=negative_prompt,
397
+ num_inference_steps=slider_step,
398
+ guidance_scale=1,
399
+ # num_images_per_prompt=slider_batch,
400
+ ).images
401
+ # os.system('nvidia-smi')
402
+ torch.cuda.empty_cache()
403
+ # os.system('nvidia-smi')
404
+ return tuple(image), composed_prompt, layout_image
405
+
406
+ with gr.Blocks() as demo:
407
+
408
+ gr.HTML(
409
+ """
410
+ <div style="text-align: center; max-width: 1600px; margin: 20px auto;">
411
+ <h2 style="font-weight: 900; font-size: 2.3rem; margin: 0rem">
412
+ TextDiffuser-2: Unleashing the Power of Language Models for Text Rendering
413
+ </h2>
414
+ <h2 style="font-weight: 460; font-size: 1.1rem; margin: 0rem">
415
+ <a href="https://jingyechen.github.io/">Jingye Chen</a>, <a href="https://hypjudy.github.io/website/">Yupan Huang</a>, <a href="https://scholar.google.com/citations?user=0LTZGhUAAAAJ&hl=en">Tengchao Lv</a>, <a href="https://www.microsoft.com/en-us/research/people/lecu/">Lei Cui</a>, <a href="https://cqf.io/">Qifeng Chen</a>, <a href="https://thegenerality.com/">Furu Wei</a>
416
+ </h2>
417
+ <h2 style="font-weight: 460; font-size: 1.1rem; margin: 0rem">
418
+ HKUST, Sun Yat-sen University, Microsoft Research
419
+ </h2>
420
+ <h3 style="font-weight: 450; font-size: 1rem; margin: 0rem">
421
+ [<a href="https://arxiv.org/abs/2311.16465" style="color:blue;">arXiv</a>]
422
+ [<a href="https://github.com/microsoft/unilm/tree/master/textdiffuser-2" style="color:blue;">Code</a>]
423
+ </h3>
424
+ <h2 style="text-align: left; font-weight: 450; font-size: 1rem; margin-top: 0.5rem; margin-bottom: 0.5rem">
425
+ We propose <b>TextDiffuser-2</b>, aiming at unleashing the power of language models for text rendering. Specifically, we <b>tame a language model into a layout planner</b> to transform user prompt into a layout using the caption-OCR pairs. The language model demonstrates flexibility and automation by inferring keywords from user prompts or incorporating user-specified keywords to determine their positions. Secondly, we <b>leverage the language model in the diffusion model as the layout encoder</b> to represent the position and content of text at the line level. This approach enables diffusion models to generate text images with broader diversity.
426
+ </h2>
427
+ <h2 style="text-align: left; font-weight: 450; font-size: 1rem; margin-top: 0.5rem; margin-bottom: 0.5rem">
428
+ 👀 <b>Tips for using this demo</b>: <b>(1)</b> Please carefully read the disclaimer in the below. Current verison can only support English. <b>(2)</b> The specification of keywords is optional. If provided, the language model will do its best to plan layouts using the given keywords. <b>(3)</b> If a template is given, the layout planner (M1) is not used. <b>(4)</b> Three operations, including redo, undo, and skip are provided. When using skip, only the left-top point of a keyword will be recorded, resulting in more diversity but sometimes decreasing the accuracy. <b>(5)</b> The layout planner can produce different layouts. You can increase the temperature to enhance the diversity. ✨ <b>(6)</b> We also provide the experimental demo combining <b>TextDiffuser-2</b> and <b>LCM</b>. The inference is fast using less sampling steps, although the precision in text rendering might decrease.
429
+ </h2>
430
+ <style>
431
+ .scaled-image {
432
+ transform: scale(1);
433
+ }
434
+ </style>
435
+
436
+ <img src="https://i.ibb.co/56JVg5j/architecture.jpg" alt="textdiffuser-2" class="scaled-image">
437
+ </div>
438
+ """)
439
+
440
+ with gr.Tab("Text-to-Image"):
441
+ with gr.Row():
442
+ with gr.Column(scale=1):
443
+ prompt = gr.Textbox(label="Prompt. You can let language model automatically identify keywords, or provide them below", placeholder="A beautiful city skyline stamp of Shanghai")
444
+ keywords = gr.Textbox(label="(Optional) Keywords. Should be seperated by / (e.g., keyword1/keyword2/...)", placeholder="keyword1/keyword2")
445
+ positive_prompt = gr.Textbox(label="(Optional) Positive prompt", value=", digital art, very detailed, fantasy, high definition, cinematic light, dnd, trending on artstation")
446
+
447
+ with gr.Accordion("(Optional) Template - Click to paint", open=False):
448
+ with gr.Row():
449
+ with gr.Column(scale=1):
450
+ i = gr.Image(label="Canvas", type='filepath', value=f'./gray256.jpg', height=256, width=256)
451
+ with gr.Column(scale=1):
452
+ t = gr.Textbox(label="Keyword", value='input_keyword')
453
+ redo = gr.Button(value='Redo - Cancel the last keyword')
454
+ undo = gr.Button(value='Undo - Clear the canvas')
455
+ skip_button = gr.Button(value='Skip - Operate the next keyword')
456
+
457
+ i.select(get_pixels,[i,t],[i])
458
+ redo.click(exe_redo, [i,t],[i])
459
+ undo.click(exe_undo, [i,t],[i])
460
+ skip_button.click(skip_fun, [i,t])
461
+
462
+ radio = gr.Radio(["TextDiffuser-2", "TextDiffuser-2-LCM"], label="Choice of models", value="TextDiffuser-2")
463
+ slider_natural = gr.Checkbox(label="Natural image generation", value=False, info="The text position and content info will not be incorporated.")
464
+ slider_step = gr.Slider(minimum=1, maximum=50, value=20, step=1, label="Sampling step", info="The sampling step for TextDiffuser-2. You may decease the step to 4 when using LCM.")
465
+ slider_guidance = gr.Slider(minimum=1, maximum=13, value=7.5, step=0.5, label="Scale of classifier-free guidance", info="The scale of cfg and is set to 7.5 in default. When using LCM, cfg is set to 1.")
466
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=4, step=1, label="Batch size", info="The number of images to be sampled.")
467
+ slider_temperature = gr.Slider(minimum=0.1, maximum=2, value=1.4, step=0.1, label="Temperature", info="Control the diversity of layout planner. Higher value indicates more diversity.")
468
+ # slider_seed = gr.Slider(minimum=1, maximum=10000, label="Seed", randomize=True)
469
+ button = gr.Button("Generate")
470
+
471
+ with gr.Column(scale=1):
472
+ output = gr.Gallery(label='Generated image')
473
+
474
+ with gr.Accordion("Intermediate results", open=False):
475
+ gr.Markdown("Composed prompt")
476
+ composed_prompt = gr.Textbox(label='')
477
+ gr.Markdown("Layout visualization")
478
+ layout = gr.Image(height=256, width=256)
479
+
480
+
481
+ button.click(text_to_image, inputs=[prompt,keywords,positive_prompt, radio,slider_step,slider_guidance,slider_batch,slider_temperature,slider_natural], outputs=[output, composed_prompt, layout])
482
+
483
+ gr.Markdown("## Prompt Examples")
484
+ gr.Examples(
485
+ [
486
+ ["A beautiful city skyline stamp of Shanghai", "", False],
487
+ ["A logo of superman", "", False],
488
+ ["A pencil sketch of a tree with the title nothing to tree here", "", False],
489
+ ["handwritten signature of peter", "", False],
490
+ ["Delicate greeting card of happy birthday to xyz", "", False],
491
+ ["Book cover of good morning baby ", "", False],
492
+ ["The handwritten words Hello World displayed on a wall in a neon light effect", "", False],
493
+ ["Logo of winter in artistic font, made by snowflake", "", False],
494
+ ["A book cover named summer vibe", "", False],
495
+ ["Newspaper with the title Love Story", "", False],
496
+ ["A logo for the company EcoGrow, where the letters look like plants", "EcoGrow", False],
497
+ ["A poster titled 'Quails of North America', showing different kinds of quails.", "Quails/of/North/America", False],
498
+ ["A detailed portrait of a fox guardian with a shield with Kung Fu written on it, by victo ngai and justin gerard, digital art, realistic painting", "kung/fu", False],
499
+ ["A stamp of breath of the wild", "breath/of/the/wild", False],
500
+ ["Poster of the incoming movie Transformers", "Transformers", False],
501
+ ["Some apples are on a table", "", True],
502
+ ["a hotdog with mustard and other toppings on it", "", True],
503
+ ["a bathroom that has a slanted ceiling and a large bath tub", "", True],
504
+ ["a man holding a tennis racquet on a tennis court", "", True],
505
+ ["hamburger with bacon, lettuce, tomato and cheese| promotional image| hyperquality| products shot| full - color| extreme render| mouthwatering", "", True],
506
+ ],
507
+ [
508
+ prompt,
509
+ keywords,
510
+ slider_natural
511
+ ],
512
+ examples_per_page=20
513
+ )
514
+
515
+ gr.HTML(
516
+ """
517
+ <div style="text-align: justify; max-width: 1100px; margin: 20px auto;">
518
+ <h3 style="font-weight: 450; font-size: 0.8rem; margin: 0rem">
519
+ <b>Version</b>: 1.0
520
+ </h3>
521
+ <h3 style="font-weight: 450; font-size: 0.8rem; margin: 0rem">
522
+ <b>Contact</b>:
523
+ For help or issues using TextDiffuser-2, please email Jingye Chen <a href="mailto:[email protected]">([email protected])</a>, Yupan Huang <a href="mailto:[email protected]">([email protected])</a> or submit a GitHub issue. For other communications related to TextDiffuser-2, please contact Lei Cui <a href="mailto:[email protected]">([email protected])</a> or Furu Wei <a href="mailto:[email protected]">([email protected])</a>.
524
+ </h3>
525
+ <h3 style="font-weight: 450; font-size: 0.8rem; margin: 0rem">
526
+ <b>Disclaimer</b>:
527
+ Please note that the demo is intended for academic and research purposes <b>ONLY</b>. Any use of the demo for generating inappropriate content is strictly prohibited. The responsibility for any misuse or inappropriate use of the demo lies solely with the users who generated such content, and this demo shall not be held liable for any such use.
528
+ </h3>
529
+ </div>
530
+ """
531
+ )
532
+
533
+
534
+ demo.launch()