watermelon23 commited on
Commit
e8dca02
1 Parent(s): e432ddd
Dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use an official Python runtime as a parent image
2
+ FROM python:3.7.4-slim
3
+
4
+ # Set the working directory to /app
5
+ WORKDIR /app
6
+
7
+ # Copy the current directory contents into the container at /app
8
+ COPY ./requirements.txt /app
9
+
10
+ # # Install any needed packages specified in requirements.txt
11
+ # RUN apt-get install libjpeg-dev
12
+ # RUN apt-get install zlib1g-dev
13
+
14
+ RUN apt-get install zip unzip cmake libtiff5-dev libjpeg8-dev libopenjp2-7-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python3-tk libharfbuzz-dev libfribidi-dev libxcb1-dev
15
+
16
+ RUN pip install -r /app/requirements.txt
17
+ RUN pip install https://download.pytorch.org/whl/Pillow-9.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
18
+ RUN pip install https://download.pytorch.org/whl/cu113/torch-1.12.1%2Bcu113-cp310-cp310-linux_x86_64.whl
19
+
20
+ # Define environment variable
21
+ ENV NAME gradio
22
+
23
+ # The default gradio port is 7860
24
+ EXPOSE 7860
25
+
26
+ # Run main.py when the container launches
27
+ CMD ["python", "text-to-image-app.py"]
28
+ ~
README.md CHANGED
@@ -1,12 +1,5 @@
1
  ---
2
- title: TextDiffuser
3
- emoji: 🚀
4
- colorFrom: green
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 3.33.1
8
  app_file: app.py
9
  pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
 
 
 
 
2
  sdk: gradio
 
3
  app_file: app.py
4
  pinned: false
5
  ---
 
 
app.py ADDED
@@ -0,0 +1,965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------
2
+ # TextDiffuser: Diffusion Models as Text Painters
3
+ # Paper Link: https://arxiv.org/abs/2305.10855
4
+ # Code Link: https://github.com/microsoft/unilm/tree/master/textdiffuser
5
+ # Copyright (c) Microsoft Corporation.
6
+ # This file provides the inference script.
7
+ # ------------------------------------------
8
+
9
+ import os
10
+ import re
11
+ import zipfile
12
+
13
+ if not os.path.exists('textdiffuser-ckpt'):
14
+ os.system('wget https://layoutlm.blob.core.windows.net/textdiffuser/textdiffuser-ckpt-new.zip')
15
+ with zipfile.ZipFile('textdiffuser-ckpt-new.zip', 'r') as zip_ref:
16
+ zip_ref.extractall('.')
17
+
18
+ if not os.path.exists('images'):
19
+ os.system('wget https://layoutlm.blob.core.windows.net/textdiffuser/images.zip')
20
+ with zipfile.ZipFile('images.zip', 'r') as zip_ref:
21
+ zip_ref.extractall('.')
22
+
23
+ if not os.path.exists('Arial.ttf'):
24
+ os.system('wget https://layoutlm.blob.core.windows.net/textdiffuser/Arial.ttf')
25
+
26
+
27
+ os.system('echo finish')
28
+ os.system('ls -a')
29
+
30
+ import cv2
31
+ import random
32
+ import logging
33
+ import argparse
34
+ import numpy as np
35
+
36
+ from pathlib import Path
37
+ from tqdm.auto import tqdm
38
+ from typing import Optional
39
+ from packaging import version
40
+ from termcolor import colored
41
+ from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageEnhance # import for visualization
42
+ from huggingface_hub import HfFolder, Repository, create_repo, whoami
43
+
44
+ import datasets
45
+ from datasets import load_dataset
46
+ from datasets import disable_caching
47
+
48
+ import torch
49
+ import torch.utils.checkpoint
50
+ import torch.nn.functional as F
51
+
52
+ import accelerate
53
+ from accelerate import Accelerator
54
+ from accelerate.logging import get_logger
55
+ from accelerate.utils import ProjectConfiguration, set_seed
56
+
57
+ import diffusers
58
+ from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
59
+ from diffusers.optimization import get_scheduler
60
+ from diffusers.training_utils import EMAModel
61
+ from diffusers.utils import check_min_version, deprecate
62
+ from diffusers.utils.import_utils import is_xformers_available
63
+
64
+ import transformers
65
+ from transformers import CLIPTextModel, CLIPTokenizer
66
+
67
+ from util import segmentation_mask_visualization, make_caption_pil, combine_image, transform_mask, transform_mask_pil, filter_segmentation_mask, inpainting_merge_image
68
+ from model.layout_generator import get_layout_from_prompt
69
+ from model.text_segmenter.unet import UNet
70
+
71
+
72
+ disable_caching()
73
+ check_min_version("0.15.0.dev0")
74
+ logger = get_logger(__name__, log_level="INFO")
75
+
76
+
77
+ def parse_args():
78
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
79
+ parser.add_argument(
80
+ "--pretrained_model_name_or_path",
81
+ type=str,
82
+ default='runwayml/stable-diffusion-v1-5', # no need to modify this
83
+ help="Path to pretrained model or model identifier from huggingface.co/models. Please do not modify this.",
84
+ )
85
+ parser.add_argument(
86
+ "--revision",
87
+ type=str,
88
+ default=None,
89
+ required=False,
90
+ help="Revision of pretrained model identifier from huggingface.co/models.",
91
+ )
92
+ parser.add_argument(
93
+ "--mode",
94
+ type=str,
95
+ default="text-to-image",
96
+ # required=True,
97
+ choices=["text-to-image", "text-to-image-with-template", "text-inpainting"],
98
+ help="Three modes can be used.",
99
+ )
100
+ parser.add_argument(
101
+ "--prompt",
102
+ type=str,
103
+ default="",
104
+ # required=True,
105
+ help="The text prompts provided by users.",
106
+ )
107
+ parser.add_argument(
108
+ "--template_image",
109
+ type=str,
110
+ default="",
111
+ help="The template image should be given when using 【text-to-image-with-template】 mode.",
112
+ )
113
+ parser.add_argument(
114
+ "--original_image",
115
+ type=str,
116
+ default="",
117
+ help="The original image should be given when using 【text-inpainting】 mode.",
118
+ )
119
+ parser.add_argument(
120
+ "--text_mask",
121
+ type=str,
122
+ default="",
123
+ help="The text mask should be given when using 【text-inpainting】 mode.",
124
+ )
125
+ parser.add_argument(
126
+ "--output_dir",
127
+ type=str,
128
+ default="output",
129
+ help="The output directory where the model predictions and checkpoints will be written.",
130
+ )
131
+ parser.add_argument(
132
+ "--cache_dir",
133
+ type=str,
134
+ default=None,
135
+ help="The directory where the downloaded models and datasets will be stored.",
136
+ )
137
+ parser.add_argument(
138
+ "--seed",
139
+ type=int,
140
+ default=None,
141
+ help="A seed for reproducible training."
142
+ )
143
+ parser.add_argument(
144
+ "--resolution",
145
+ type=int,
146
+ default=512,
147
+ help=(
148
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
149
+ " resolution"
150
+ ),
151
+ )
152
+ parser.add_argument(
153
+ "--classifier_free_scale",
154
+ type=float,
155
+ default=7.5, # following stable diffusion (https://github.com/CompVis/stable-diffusion)
156
+ help="Classifier free scale following https://arxiv.org/abs/2207.12598.",
157
+ )
158
+ parser.add_argument(
159
+ "--drop_caption",
160
+ action="store_true",
161
+ help="Whether to drop captions during training following https://arxiv.org/abs/2207.12598.."
162
+ )
163
+ parser.add_argument(
164
+ "--dataloader_num_workers",
165
+ type=int,
166
+ default=0,
167
+ help="Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
168
+ )
169
+ parser.add_argument(
170
+ "--push_to_hub",
171
+ action="store_true",
172
+ help="Whether or not to push the model to the Hub."
173
+ )
174
+ parser.add_argument(
175
+ "--hub_token",
176
+ type=str,
177
+ default=None,
178
+ help="The token to use to push to the Model Hub."
179
+ )
180
+ parser.add_argument(
181
+ "--hub_model_id",
182
+ type=str,
183
+ default=None,
184
+ help="The name of the repository to keep in sync with the local `output_dir`.",
185
+ )
186
+ parser.add_argument(
187
+ "--logging_dir",
188
+ type=str,
189
+ default="logs",
190
+ help=(
191
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
192
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
193
+ ),
194
+ )
195
+ parser.add_argument(
196
+ "--mixed_precision",
197
+ type=str,
198
+ default='fp16',
199
+ choices=["no", "fp16", "bf16"],
200
+ help=(
201
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
202
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
203
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
204
+ ),
205
+ )
206
+ parser.add_argument(
207
+ "--report_to",
208
+ type=str,
209
+ default="tensorboard",
210
+ help=(
211
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
212
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
213
+ ),
214
+ )
215
+ parser.add_argument(
216
+ "--local_rank",
217
+ type=int,
218
+ default=-1,
219
+ help="For distributed training: local_rank"
220
+ )
221
+ parser.add_argument(
222
+ "--checkpointing_steps",
223
+ type=int,
224
+ default=500,
225
+ help=(
226
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
227
+ " training using `--resume_from_checkpoint`."
228
+ ),
229
+ )
230
+ parser.add_argument(
231
+ "--checkpoints_total_limit",
232
+ type=int,
233
+ default=5,
234
+ help=(
235
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
236
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
237
+ " for more docs"
238
+ ),
239
+ )
240
+ parser.add_argument(
241
+ "--resume_from_checkpoint",
242
+ type=str,
243
+ default='textdiffuser-ckpt/diffusion_backbone', # should be specified during inference
244
+ help=(
245
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
246
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
247
+ ),
248
+ )
249
+ parser.add_argument(
250
+ "--enable_xformers_memory_efficient_attention",
251
+ action="store_true",
252
+ help="Whether or not to use xformers."
253
+ )
254
+ parser.add_argument(
255
+ "--font_path",
256
+ type=str,
257
+ default='Arial.ttf',
258
+ help="The path of font for visualization."
259
+ )
260
+ parser.add_argument(
261
+ "--sample_steps",
262
+ type=int,
263
+ default=50, # following stable diffusion (https://github.com/CompVis/stable-diffusion)
264
+ help="Diffusion steps for sampling."
265
+ )
266
+ parser.add_argument(
267
+ "--vis_num",
268
+ type=int,
269
+ default=4, # please decreases the number if out-of-memory error occurs
270
+ help="Number of images to be sample. Please decrease it when encountering out of memory error."
271
+ )
272
+ parser.add_argument(
273
+ "--binarization",
274
+ action="store_true",
275
+ help="Whether to binarize the template image."
276
+ )
277
+ parser.add_argument(
278
+ "--use_pillow_segmentation_mask",
279
+ type=bool,
280
+ default=True,
281
+ help="In the 【text-to-image】 mode, please specify whether to use the segmentation masks provided by PILLOW"
282
+ )
283
+ parser.add_argument(
284
+ "--character_segmenter_path",
285
+ type=str,
286
+ default='textdiffuser-ckpt/text_segmenter.pth',
287
+ help="checkpoint of character-level segmenter"
288
+ )
289
+ args = parser.parse_args()
290
+
291
+ print(f'{colored("[√]", "green")} Arguments are loaded.')
292
+ print(args)
293
+
294
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
295
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
296
+ args.local_rank = env_local_rank
297
+
298
+ return args
299
+
300
+
301
+
302
+ def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None):
303
+ if token is None:
304
+ token = HfFolder.get_token()
305
+ if organization is None:
306
+ username = whoami(token)["name"]
307
+ return f"{username}/{model_id}"
308
+ else:
309
+ return f"{organization}/{model_id}"
310
+
311
+
312
+
313
+ args = parse_args()
314
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
315
+
316
+ print(f'{colored("[√]", "green")} Logging dir is set to {logging_dir}.')
317
+
318
+ accelerator_project_config = ProjectConfiguration(total_limit=args.checkpoints_total_limit)
319
+
320
+ accelerator = Accelerator(
321
+ gradient_accumulation_steps=1,
322
+ mixed_precision=args.mixed_precision,
323
+ log_with=args.report_to,
324
+ logging_dir=logging_dir,
325
+ project_config=accelerator_project_config,
326
+ )
327
+
328
+ # Make one log on every process with the configuration for debugging.
329
+ logging.basicConfig(
330
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
331
+ datefmt="%m/%d/%Y %H:%M:%S",
332
+ level=logging.INFO,
333
+ )
334
+ logger.info(accelerator.state, main_process_only=False)
335
+ if accelerator.is_local_main_process:
336
+ datasets.utils.logging.set_verbosity_warning()
337
+ transformers.utils.logging.set_verbosity_warning()
338
+ diffusers.utils.logging.set_verbosity_info()
339
+ else:
340
+ datasets.utils.logging.set_verbosity_error()
341
+ transformers.utils.logging.set_verbosity_error()
342
+ diffusers.utils.logging.set_verbosity_error()
343
+
344
+ # Handle the repository creation
345
+ if accelerator.is_main_process:
346
+ if args.push_to_hub:
347
+ if args.hub_model_id is None:
348
+ repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
349
+ else:
350
+ repo_name = args.hub_model_id
351
+ create_repo(repo_name, exist_ok=True, token=args.hub_token)
352
+ repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
353
+
354
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
355
+ if "step_*" not in gitignore:
356
+ gitignore.write("step_*\n")
357
+ if "epoch_*" not in gitignore:
358
+ gitignore.write("epoch_*\n")
359
+ elif args.output_dir is not None:
360
+ os.makedirs(args.output_dir, exist_ok=True)
361
+ print(args.output_dir)
362
+
363
+ # Load scheduler, tokenizer and models.
364
+ tokenizer = CLIPTokenizer.from_pretrained(
365
+ args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
366
+ )
367
+ text_encoder = CLIPTextModel.from_pretrained(
368
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
369
+ )
370
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision).cuda()
371
+ unet = UNet2DConditionModel.from_pretrained(
372
+ args.resume_from_checkpoint, subfolder="unet", revision=None
373
+ ).cuda()
374
+
375
+ # Freeze vae and text_encoder
376
+ vae.requires_grad_(False)
377
+ text_encoder.requires_grad_(False)
378
+
379
+ if args.enable_xformers_memory_efficient_attention:
380
+ if is_xformers_available():
381
+ import xformers
382
+
383
+ xformers_version = version.parse(xformers.__version__)
384
+ if xformers_version == version.parse("0.0.16"):
385
+ logger.warn(
386
+ "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
387
+ )
388
+ unet.enable_xformers_memory_efficient_attention()
389
+ else:
390
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
391
+
392
+ # `accelerate` 0.16.0 will have better support for customized saving
393
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
394
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
395
+ def save_model_hook(models, weights, output_dir):
396
+
397
+ for i, model in enumerate(models):
398
+ model.save_pretrained(os.path.join(output_dir, "unet"))
399
+
400
+ # make sure to pop weight so that corresponding model is not saved again
401
+ weights.pop()
402
+
403
+ def load_model_hook(models, input_dir):
404
+
405
+ for i in range(len(models)):
406
+ # pop models so that they are not loaded again
407
+ model = models.pop()
408
+
409
+ # load diffusers style into model
410
+ load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
411
+ model.register_to_config(**load_model.config)
412
+
413
+ model.load_state_dict(load_model.state_dict())
414
+ del load_model
415
+
416
+ accelerator.register_save_state_pre_hook(save_model_hook)
417
+ accelerator.register_load_state_pre_hook(load_model_hook)
418
+
419
+
420
+ # setup schedulers
421
+ scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
422
+ # sample_num = args.vis_num
423
+
424
+ def to_tensor(image):
425
+ if isinstance(image, Image.Image):
426
+ image = np.array(image)
427
+ elif not isinstance(image, np.ndarray):
428
+ raise TypeError("Error")
429
+
430
+ image = image.astype(np.float32) / 255.0
431
+ image = np.transpose(image, (2, 0, 1))
432
+ tensor = torch.from_numpy(image)
433
+
434
+ return tensor
435
+
436
+
437
+ import unicodedata
438
+
439
+ def full2half(text):
440
+ half = []
441
+ for char in text:
442
+ code = ord(char)
443
+ if code == 0x3000:
444
+ half.append(chr(0x0020))
445
+ elif 0xFF01 <= code <= 0xFF5E:
446
+ half.append(chr(code - 0xFEE0))
447
+ else:
448
+ half.append(char)
449
+ return ''.join(half)
450
+
451
+ def text_to_image(prompt,slider_step,slider_guidance,slider_batch):
452
+
453
+ prompt = full2half(prompt)
454
+ prompt = prompt.replace('"', "'")
455
+ prompt = prompt.replace('‘', "'")
456
+ prompt = prompt.replace('’', "'")
457
+ prompt = prompt.replace('“', "'")
458
+ prompt = prompt.replace('”', "'")
459
+ prompt = re.sub(r"[^a-zA-Z0-9'\" ]+", "", prompt)
460
+
461
+ if slider_step>=50:
462
+ slider_step = 50
463
+
464
+ args.prompt = prompt
465
+ sample_num = slider_batch
466
+ seed = random.randint(0, 10000000)
467
+ set_seed(seed)
468
+ scheduler.set_timesteps(slider_step)
469
+
470
+ noise = torch.randn((sample_num, 4, 64, 64)).to("cuda") # (b, 4, 64, 64)
471
+ input = noise # (b, 4, 64, 64)
472
+
473
+ captions = [args.prompt] * sample_num
474
+ captions_nocond = [""] * sample_num
475
+ print(f'{colored("[√]", "green")} Prompt is loaded: {args.prompt}.')
476
+
477
+ # encode text prompts
478
+ inputs = tokenizer(
479
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
480
+ ).input_ids # (b, 77)
481
+ encoder_hidden_states = text_encoder(inputs)[0].cuda() # (b, 77, 768)
482
+ print(f'{colored("[√]", "green")} encoder_hidden_states: {encoder_hidden_states.shape}.')
483
+
484
+ inputs_nocond = tokenizer(
485
+ captions_nocond, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
486
+ ).input_ids # (b, 77)
487
+ encoder_hidden_states_nocond = text_encoder(inputs_nocond)[0].cuda() # (b, 77, 768)
488
+ print(f'{colored("[√]", "green")} encoder_hidden_states_nocond: {encoder_hidden_states_nocond.shape}.')
489
+
490
+ # load character-level segmenter
491
+ segmenter = UNet(3, 96, True).cuda()
492
+ segmenter = torch.nn.DataParallel(segmenter)
493
+ segmenter.load_state_dict(torch.load(args.character_segmenter_path))
494
+ segmenter.eval()
495
+ print(f'{colored("[√]", "green")} Text segmenter is successfully loaded.')
496
+
497
+ #### text-to-image ####
498
+ render_image, segmentation_mask_from_pillow = get_layout_from_prompt(args)
499
+
500
+ segmentation_mask = torch.Tensor(np.array(segmentation_mask_from_pillow)).cuda() # (512, 512)
501
+
502
+ segmentation_mask = filter_segmentation_mask(segmentation_mask)
503
+ segmentation_mask = torch.nn.functional.interpolate(segmentation_mask.unsqueeze(0).unsqueeze(0).float(), size=(256, 256), mode='nearest')
504
+ segmentation_mask = segmentation_mask.squeeze(1).repeat(sample_num, 1, 1).long().to('cuda') # (1, 1, 256, 256)
505
+ print(f'{colored("[√]", "green")} character-level segmentation_mask: {segmentation_mask.shape}.')
506
+
507
+ feature_mask = torch.ones(sample_num, 1, 64, 64).to('cuda') # (b, 1, 64, 64)
508
+ masked_image = torch.zeros(sample_num, 3, 512, 512).to('cuda') # (b, 3, 512, 512)
509
+ masked_feature = vae.encode(masked_image).latent_dist.sample() # (b, 4, 64, 64)
510
+ masked_feature = masked_feature * vae.config.scaling_factor
511
+ print(f'{colored("[√]", "green")} feature_mask: {feature_mask.shape}.')
512
+ print(f'{colored("[√]", "green")} masked_feature: {masked_feature.shape}.')
513
+
514
+ # diffusion process
515
+ intermediate_images = []
516
+ for t in tqdm(scheduler.timesteps):
517
+ with torch.no_grad():
518
+ noise_pred_cond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states, segmentation_mask=segmentation_mask, feature_mask=feature_mask, masked_feature=masked_feature).sample # b, 4, 64, 64
519
+ noise_pred_uncond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states_nocond, segmentation_mask=segmentation_mask, feature_mask=feature_mask, masked_feature=masked_feature).sample # b, 4, 64, 64
520
+ noisy_residual = noise_pred_uncond + slider_guidance * (noise_pred_cond - noise_pred_uncond) # b, 4, 64, 64
521
+ prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
522
+ input = prev_noisy_sample
523
+ intermediate_images.append(prev_noisy_sample)
524
+
525
+ # decode and visualization
526
+ input = 1 / vae.config.scaling_factor * input
527
+ sample_images = vae.decode(input.float(), return_dict=False)[0] # (b, 3, 512, 512)
528
+
529
+ image_pil = render_image.resize((512,512))
530
+ segmentation_mask = segmentation_mask[0].squeeze().cpu().numpy()
531
+ character_mask_pil = Image.fromarray(((segmentation_mask!=0)*255).astype('uint8')).resize((512,512))
532
+ character_mask_highlight_pil = segmentation_mask_visualization(args.font_path,segmentation_mask)
533
+ caption_pil = make_caption_pil(args.font_path, captions)
534
+
535
+ # save pred_img
536
+ pred_image_list = []
537
+ for image in sample_images.float():
538
+ image = (image / 2 + 0.5).clamp(0, 1).unsqueeze(0)
539
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
540
+ image = Image.fromarray((image * 255).round().astype("uint8")).convert('RGB')
541
+ pred_image_list.append(image)
542
+
543
+ blank_pil = combine_image(args, None, pred_image_list, image_pil, character_mask_pil, character_mask_highlight_pil, caption_pil)
544
+
545
+ intermediate_result = Image.new('RGB', (512*3, 512))
546
+ intermediate_result.paste(image_pil, (0, 0))
547
+ intermediate_result.paste(character_mask_pil, (512, 0))
548
+ intermediate_result.paste(character_mask_highlight_pil, (512*2, 0))
549
+
550
+ return blank_pil, intermediate_result
551
+
552
+
553
+ # load character-level segmenter
554
+ segmenter = UNet(3, 96, True).cuda()
555
+ segmenter = torch.nn.DataParallel(segmenter)
556
+ segmenter.load_state_dict(torch.load(args.character_segmenter_path))
557
+ segmenter.eval()
558
+ print(f'{colored("[√]", "green")} Text segmenter is successfully loaded.')
559
+
560
+
561
+
562
+
563
+ def text_to_image_with_template(prompt,template_image,slider_step,slider_guidance,slider_batch, binary):
564
+
565
+ if slider_step>=50:
566
+ slider_step = 50
567
+
568
+ orig_template_image = template_image.resize((512,512)).convert('RGB')
569
+ args.prompt = prompt
570
+ sample_num = slider_batch
571
+ # If passed along, set the training seed now.
572
+ # seed = slider_seed
573
+ seed = random.randint(0, 10000000)
574
+ set_seed(seed)
575
+ scheduler.set_timesteps(slider_step)
576
+
577
+ noise = torch.randn((sample_num, 4, 64, 64)).to("cuda") # (b, 4, 64, 64)
578
+ input = noise # (b, 4, 64, 64)
579
+
580
+ captions = [args.prompt] * sample_num
581
+ captions_nocond = [""] * sample_num
582
+ print(f'{colored("[√]", "green")} Prompt is loaded: {args.prompt}.')
583
+
584
+ # encode text prompts
585
+ inputs = tokenizer(
586
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
587
+ ).input_ids # (b, 77)
588
+ encoder_hidden_states = text_encoder(inputs)[0].cuda() # (b, 77, 768)
589
+ print(f'{colored("[√]", "green")} encoder_hidden_states: {encoder_hidden_states.shape}.')
590
+
591
+ inputs_nocond = tokenizer(
592
+ captions_nocond, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
593
+ ).input_ids # (b, 77)
594
+ encoder_hidden_states_nocond = text_encoder(inputs_nocond)[0].cuda() # (b, 77, 768)
595
+ print(f'{colored("[√]", "green")} encoder_hidden_states_nocond: {encoder_hidden_states_nocond.shape}.')
596
+
597
+ #### text-to-image-with-template ####
598
+ template_image = template_image.resize((256,256)).convert('RGB')
599
+
600
+ # whether binarization is needed
601
+ print(f'{colored("[Warning]", "red")} args.binarization is set to {binary}. You may need it when using handwritten images as templates.')
602
+
603
+ if binary:
604
+ gray = ImageOps.grayscale(template_image)
605
+ binary = gray.point(lambda x: 255 if x > 96 else 0, '1')
606
+ template_image = binary.convert('RGB')
607
+
608
+ # to_tensor = transforms.ToTensor()
609
+ image_tensor = to_tensor(template_image).unsqueeze(0).cuda().sub_(0.5).div_(0.5) # (b, 3, 256, 256)
610
+
611
+ with torch.no_grad():
612
+ segmentation_mask = segmenter(image_tensor) # (b, 96, 256, 256)
613
+ segmentation_mask = segmentation_mask.max(1)[1].squeeze(0) # (256, 256)
614
+ segmentation_mask = filter_segmentation_mask(segmentation_mask) # (256, 256)
615
+
616
+ segmentation_mask = torch.nn.functional.interpolate(segmentation_mask.unsqueeze(0).unsqueeze(0).float(), size=(256, 256), mode='nearest') # (b, 1, 256, 256)
617
+ segmentation_mask = segmentation_mask.squeeze(1).repeat(sample_num, 1, 1).long().to('cuda') # (b, 1, 256, 256)
618
+ print(f'{colored("[√]", "green")} Character-level segmentation_mask: {segmentation_mask.shape}.')
619
+
620
+ feature_mask = torch.ones(sample_num, 1, 64, 64).to('cuda') # (b, 1, 64, 64)
621
+ masked_image = torch.zeros(sample_num, 3, 512, 512).to('cuda') # (b, 3, 512, 512)
622
+ masked_feature = vae.encode(masked_image).latent_dist.sample() # (b, 4, 64, 64)
623
+ masked_feature = masked_feature * vae.config.scaling_factor # (b, 4, 64, 64)
624
+
625
+ # diffusion process
626
+ intermediate_images = []
627
+ for t in tqdm(scheduler.timesteps):
628
+ with torch.no_grad():
629
+ noise_pred_cond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states, segmentation_mask=segmentation_mask, feature_mask=feature_mask, masked_feature=masked_feature).sample # b, 4, 64, 64
630
+ noise_pred_uncond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states_nocond, segmentation_mask=segmentation_mask, feature_mask=feature_mask, masked_feature=masked_feature).sample # b, 4, 64, 64
631
+ noisy_residual = noise_pred_uncond + slider_guidance * (noise_pred_cond - noise_pred_uncond) # b, 4, 64, 64
632
+ prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
633
+ input = prev_noisy_sample
634
+ intermediate_images.append(prev_noisy_sample)
635
+
636
+ # decode and visualization
637
+ input = 1 / vae.config.scaling_factor * input
638
+ sample_images = vae.decode(input.float(), return_dict=False)[0] # (b, 3, 512, 512)
639
+
640
+ image_pil = None
641
+ segmentation_mask = segmentation_mask[0].squeeze().cpu().numpy()
642
+ character_mask_pil = Image.fromarray(((segmentation_mask!=0)*255).astype('uint8')).resize((512,512))
643
+ character_mask_highlight_pil = segmentation_mask_visualization(args.font_path,segmentation_mask)
644
+ caption_pil = make_caption_pil(args.font_path, captions)
645
+
646
+ # save pred_img
647
+ pred_image_list = []
648
+ for image in sample_images.float():
649
+ image = (image / 2 + 0.5).clamp(0, 1).unsqueeze(0)
650
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
651
+ image = Image.fromarray((image * 255).round().astype("uint8")).convert('RGB')
652
+ pred_image_list.append(image)
653
+
654
+ blank_pil = combine_image(args, None, pred_image_list, image_pil, character_mask_pil, character_mask_highlight_pil, caption_pil)
655
+
656
+ intermediate_result = Image.new('RGB', (512*3, 512))
657
+ intermediate_result.paste(orig_template_image, (0, 0))
658
+ intermediate_result.paste(character_mask_pil, (512, 0))
659
+ intermediate_result.paste(character_mask_highlight_pil, (512*2, 0))
660
+
661
+ return blank_pil, intermediate_result
662
+
663
+
664
+ def text_inpainting(prompt,orig_image,mask_image,slider_step,slider_guidance,slider_batch):
665
+
666
+ if slider_step>=50:
667
+ slider_step = 50
668
+
669
+ args.prompt = prompt
670
+ sample_num = slider_batch
671
+ # If passed along, set the training seed now.
672
+ # seed = slider_seed
673
+ seed = random.randint(0, 10000000)
674
+ set_seed(seed)
675
+ scheduler.set_timesteps(slider_step)
676
+
677
+ noise = torch.randn((sample_num, 4, 64, 64)).to("cuda") # (b, 4, 64, 64)
678
+ input = noise # (b, 4, 64, 64)
679
+
680
+ captions = [args.prompt] * sample_num
681
+ captions_nocond = [""] * sample_num
682
+ print(f'{colored("[√]", "green")} Prompt is loaded: {args.prompt}.')
683
+
684
+ # encode text prompts
685
+ inputs = tokenizer(
686
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
687
+ ).input_ids # (b, 77)
688
+ encoder_hidden_states = text_encoder(inputs)[0].cuda() # (b, 77, 768)
689
+ print(f'{colored("[√]", "green")} encoder_hidden_states: {encoder_hidden_states.shape}.')
690
+
691
+ inputs_nocond = tokenizer(
692
+ captions_nocond, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
693
+ ).input_ids # (b, 77)
694
+ encoder_hidden_states_nocond = text_encoder(inputs_nocond)[0].cuda() # (b, 77, 768)
695
+ print(f'{colored("[√]", "green")} encoder_hidden_states_nocond: {encoder_hidden_states_nocond.shape}.')
696
+
697
+ mask_image = cv2.resize(mask_image, (512,512))
698
+ # mask_image = mask_image.resize((512,512)).convert('RGB')
699
+ text_mask = np.array(mask_image)
700
+ threshold = 128
701
+ _, text_mask = cv2.threshold(text_mask, threshold, 255, cv2.THRESH_BINARY)
702
+ text_mask = Image.fromarray(text_mask).convert('RGB').resize((256,256))
703
+ text_mask.save('text_mask.png')
704
+ text_mask_tensor = to_tensor(text_mask).unsqueeze(0).cuda().sub_(0.5).div_(0.5)
705
+ with torch.no_grad():
706
+ segmentation_mask = segmenter(text_mask_tensor)
707
+
708
+ segmentation_mask = segmentation_mask.max(1)[1].squeeze(0)
709
+ segmentation_mask = filter_segmentation_mask(segmentation_mask)
710
+ segmentation_mask = torch.nn.functional.interpolate(segmentation_mask.unsqueeze(0).unsqueeze(0).float(), size=(256, 256), mode='nearest')
711
+
712
+ image_mask = transform_mask_pil(mask_image)
713
+ image_mask = torch.from_numpy(image_mask).cuda().unsqueeze(0).unsqueeze(0)
714
+
715
+ orig_image = orig_image.convert('RGB').resize((512,512))
716
+ image = orig_image
717
+ image_tensor = to_tensor(image).unsqueeze(0).cuda().sub_(0.5).div_(0.5)
718
+ masked_image = image_tensor * (1-image_mask)
719
+ masked_feature = vae.encode(masked_image).latent_dist.sample().repeat(sample_num, 1, 1, 1)
720
+ masked_feature = masked_feature * vae.config.scaling_factor
721
+
722
+ image_mask = torch.nn.functional.interpolate(image_mask, size=(256, 256), mode='nearest').repeat(sample_num, 1, 1, 1)
723
+ segmentation_mask = segmentation_mask * image_mask
724
+ feature_mask = torch.nn.functional.interpolate(image_mask, size=(64, 64), mode='nearest')
725
+
726
+ # diffusion process
727
+ intermediate_images = []
728
+ for t in tqdm(scheduler.timesteps):
729
+ with torch.no_grad():
730
+ noise_pred_cond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states, segmentation_mask=segmentation_mask, feature_mask=feature_mask, masked_feature=masked_feature).sample # b, 4, 64, 64
731
+ noise_pred_uncond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states_nocond, segmentation_mask=segmentation_mask, feature_mask=feature_mask, masked_feature=masked_feature).sample # b, 4, 64, 64
732
+ noisy_residual = noise_pred_uncond + slider_guidance * (noise_pred_cond - noise_pred_uncond) # b, 4, 64, 64
733
+ prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
734
+ input = prev_noisy_sample
735
+ intermediate_images.append(prev_noisy_sample)
736
+
737
+ # decode and visualization
738
+ input = 1 / vae.config.scaling_factor * input
739
+ sample_images = vae.decode(input.float(), return_dict=False)[0] # (b, 3, 512, 512)
740
+
741
+ image_pil = None
742
+ segmentation_mask = segmentation_mask[0].squeeze().cpu().numpy()
743
+ character_mask_pil = Image.fromarray(((segmentation_mask!=0)*255).astype('uint8')).resize((512,512))
744
+ character_mask_highlight_pil = segmentation_mask_visualization(args.font_path,segmentation_mask)
745
+ caption_pil = make_caption_pil(args.font_path, captions)
746
+
747
+ # save pred_img
748
+ pred_image_list = []
749
+ for image in sample_images.float():
750
+ image = (image / 2 + 0.5).clamp(0, 1).unsqueeze(0)
751
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
752
+ image = Image.fromarray((image * 255).round().astype("uint8")).convert('RGB')
753
+
754
+ # need to merge
755
+
756
+ # image = inpainting_merge_image(orig_image, Image.fromarray(mask_image).convert('L'), image)
757
+
758
+ pred_image_list.append(image)
759
+
760
+ character_mask_pil.save('character_mask_pil.png')
761
+ character_mask_highlight_pil.save('character_mask_highlight_pil.png')
762
+
763
+
764
+ blank_pil = combine_image(args, None, pred_image_list, image_pil, character_mask_pil, character_mask_highlight_pil, caption_pil)
765
+
766
+
767
+ background = orig_image.resize((512, 512))
768
+ alpha = Image.new('L', background.size, int(255 * 0.2))
769
+ background.putalpha(alpha)
770
+ # foreground
771
+ foreground = Image.fromarray(mask_image).convert('L').resize((512, 512))
772
+ threshold = 200
773
+ alpha = foreground.point(lambda x: 0 if x > threshold else 255, '1')
774
+ foreground.putalpha(alpha)
775
+ merge_image = Image.alpha_composite(foreground.convert('RGBA'), background.convert('RGBA')).convert('RGB')
776
+
777
+ intermediate_result = Image.new('RGB', (512*3, 512))
778
+ intermediate_result.paste(merge_image, (0, 0))
779
+ intermediate_result.paste(character_mask_pil, (512, 0))
780
+ intermediate_result.paste(character_mask_highlight_pil, (512*2, 0))
781
+
782
+ return blank_pil, intermediate_result
783
+
784
+ import gradio as gr
785
+
786
+ with gr.Blocks() as demo:
787
+
788
+ gr.HTML(
789
+ """
790
+ <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
791
+ <h1 style="font-weight: 900; font-size: 3rem; margin: 0rem">
792
+ TextDiffuser: Diffusion Models as Text Painters
793
+ </h1>
794
+ <h3 style="font-weight: 450; font-size: 1rem; margin: 0rem">
795
+ [<a href="https://arxiv.org/abs/2305.10855" style="color:blue;">arXiv</a>]
796
+ [<a href="https://github.com/microsoft/unilm/tree/master/textdiffuser" style="color:blue;">Code</a>]
797
+ [<a href="https://jingyechen.github.io/textdiffuser/" style="color:blue;">ProjectPage</a>]
798
+ </h3>
799
+ <h2 style="text-align: left; font-weight: 450; font-size: 1rem; margin-top: 0.5rem; margin-bottom: 0.5rem">
800
+ We propose <b>TextDiffuser</b>, a flexible and controllable framework to generate images with visually appealing text that is coherent with backgrounds.
801
+ Main features include: (a) <b><font color="#A52A2A">Text-to-Image</font></b>: The user provides a prompt and encloses the keywords with single quotes (e.g., a text image of ‘hello’). The model first determines the layout of the keywords and then draws the image based on the layout and prompt. (b) <b><font color="#A52A2A">Text-to-Image with Templates</font></b>: The user provides a prompt and a template image containing text, which can be a printed, handwritten, or scene text image. These template images can be used to determine the layout of the characters. (c) <b><font color="#A52A2A">Text Inpainting</font></b>: The user provides an image and specifies the region to be modified along with the desired text content. The model is able to modify the original text or add text to areas without text.
802
+ </h2>
803
+ <img src="file/images/huggingface_blank.jpg" alt="textdiffuser">
804
+ </div>
805
+ """)
806
+
807
+ with gr.Tab("Text-to-Image"):
808
+ with gr.Row():
809
+ with gr.Column(scale=1):
810
+ prompt = gr.Textbox(label="Input your prompt here. Please enclose keywords with 'single quotes', you may refer to the examples below. The current version only supports input in English characters.", placeholder="Placeholder 'Team' hat")
811
+ slider_step = gr.Slider(minimum=1, maximum=50, value=20, step=1, label="Sampling step", info="The sampling step for TextDiffuser.")
812
+ slider_guidance = gr.Slider(minimum=1, maximum=9, value=7.5, step=0.5, label="Scale of classifier-free guidance", info="The scale of classifier-free guidance and is set to 7.5 in default.")
813
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=4, step=1, label="Batch size", info="The number of images to be sampled.")
814
+ # slider_seed = gr.Slider(minimum=1, maximum=10000, label="Seed", randomize=True)
815
+ button = gr.Button("Generate")
816
+
817
+ with gr.Column(scale=1):
818
+ output = gr.Image(label='Generated image')
819
+
820
+ with gr.Accordion("Intermediate results", open=False):
821
+ gr.Markdown("Layout, segmentation mask, and details of segmentation mask from left to right.")
822
+ intermediate_results = gr.Image(label='')
823
+
824
+ gr.Markdown("## Prompt Examples")
825
+ gr.Examples(
826
+ [
827
+ ["Distinguished poster of 'SPIDERMAN'. Trending on ArtStation and Pixiv. A vibrant digital oil painting. A highly detailed fantasy character illustration by Wayne Reynolds and Charles Monet and Gustave Dore and Carl Critchlow and Bram Sels"],
828
+ ["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, very detailed, fantasy, high definition, cinematic light, dnd, trending on artstation"],
829
+ ["portrait of a 'dragon', concept art, sumi - e style, intricate linework, green smoke, artstation, trending, highly detailed, smooth, focus, art by yoji shinkawa,"],
830
+ ["elderly woman dressed in extremely colorful clothes with many strange patterns posing for a high fashion photoshoot of 'FASHION', haute couture, golden hour, artstation, by J. C. Leyendecker and Peter Paul Rubens"],
831
+ ["epic digital art of a luxury yacht named 'Time Machine' driving through very dark hard edged city towers from tron movie, faint tall mountains in background, wlop, pixiv"],
832
+ ["A poster of 'Adventurer'. A beautiful so tall boy with big eyes and small nose is in the jungle, he wears normal clothes and shows his full length, which we see from the front, unreal engine, cozy indoor lighting, artstation, detailed"],
833
+ ["A poster of 'AI BABY'. Cute and adorable cartoon it baby, fantasy, dreamlike, surrealism, super cute, trending on artstation"],
834
+ ["'Team' hat"],
835
+ ["Thanksgiving 'Fam' Mens T Shirt"],
836
+ ["A storefront with 'Hello World' written on it."],
837
+ ["A poster titled 'Quails of North America', showing different kinds of quails."],
838
+ ["A storefront with 'Deep Learning' written on it."],
839
+ ["An antique bottle labeled 'Energy Tonic'"],
840
+ ["A TV show poster titled 'Tango argentino'"],
841
+ ["A TV show poster with logo 'The Dry' on it"],
842
+ ["Stupid 'History' eBook Tales of Stupidity Strangeness"],
843
+ ["Photos of 'Sampa Hostel'"],
844
+ ["A large recipe book titled 'Recipes from Peru'."],
845
+ ["New York Skyline with 'Diffusion' written with fireworks on the sky"],
846
+ ["Books with the word 'Science' printed on them"],
847
+ ["A globe with the words 'Planet Earth' written in bold letters with continents in bright colors"],
848
+ ["A logo for the company 'EcoGrow', where the letters look like plants"],
849
+ ],
850
+ prompt,
851
+ examples_per_page=100
852
+ )
853
+
854
+ button.click(text_to_image, inputs=[prompt,slider_step,slider_guidance,slider_batch], outputs=[output,intermediate_results])
855
+
856
+ with gr.Tab("Text-to-Image-with-Template"):
857
+ with gr.Row():
858
+ with gr.Column(scale=1):
859
+ prompt = gr.Textbox(label='Input your prompt here.')
860
+ template_image = gr.Image(label='Template image', type="pil")
861
+ slider_step = gr.Slider(minimum=1, maximum=50, value=20, step=1, label="Sampling step", info="The sampling step for TextDiffuser.")
862
+ slider_guidance = gr.Slider(minimum=1, maximum=9, value=7.5, step=0.5, label="Scale of classifier-free guidance", info="The scale of classifier-free guidance and is set to 7.5 in default.")
863
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=4, step=1, label="Batch size", info="The number of images to be sampled.")
864
+ # binary = gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?")
865
+ binary = gr.Checkbox(label="Binarization", bool=True, info="Whether to binarize the template image? You may need it when using handwritten images as templates.")
866
+ button = gr.Button("Generate")
867
+
868
+ with gr.Column(scale=1):
869
+ output = gr.Image(label='Generated image')
870
+
871
+ with gr.Accordion("Intermediate results", open=False):
872
+ gr.Markdown("Template image, segmentation mask, and details of segmentation mask from left to right.")
873
+ intermediate_results = gr.Image(label='')
874
+
875
+ gr.Markdown("## Prompt and Template-Image Examples")
876
+ gr.Examples(
877
+ [
878
+ ["summer garden, artwork, highly detailed, sharp focus, realist, digital painting, artstation, concept art, art by jay oh, greg rutkowski, wlop", './images/text-to-image-with-template/6.jpg', False],
879
+ ["a hand-drawn blueprint for a time machine with the caption 'Time traveling device'", './images/text-to-image-with-template/5.jpg', False],
880
+ ["a book called summer vibe written by diffusion model", './images/text-to-image-with-template/7.jpg', False],
881
+ ["a work company", './images/text-to-image-with-template/8.jpg', False],
882
+ ["a book of AI in next century written by AI robot ", './images/text-to-image-with-template/9.jpg', False],
883
+ ["A board saying having a dog named shark at the beach was a mistake", './images/text-to-image-with-template/1.jpg', False],
884
+ ["an elephant holds a newspaper that is written elephant take over the world", './images/text-to-image-with-template/2.jpg', False],
885
+ ["a mouse with a flashlight saying i am afraid of the dark", './images/text-to-image-with-template/4.jpg', False],
886
+ ["a birthday cake of happy birthday to xyz", './images/text-to-image-with-template/10.jpg', False],
887
+ ["a poster of monkey music festival", './images/text-to-image-with-template/11.jpg', False],
888
+ ["a meme of are you kidding", './images/text-to-image-with-template/12.jpg', False],
889
+ ["a 3d model of a 1980s-style computer with the text my old habit on the screen", './images/text-to-image-with-template/13.jpg', True],
890
+ ["a board of hello world", './images/text-to-image-with-template/15.jpg', True],
891
+ ["a microsoft bag", './images/text-to-image-with-template/16.jpg', True],
892
+ ["a dog holds a paper saying please adopt me", './images/text-to-image-with-template/17.jpg', False],
893
+ ["a hello world banner", './images/text-to-image-with-template/18.jpg', False],
894
+ ["a stop pizza", './images/text-to-image-with-template/19.jpg', False],
895
+ ["a dress with text do not read the next sentence", './images/text-to-image-with-template/20.jpg', False],
896
+ ],
897
+ [prompt,template_image, binary],
898
+ examples_per_page=100
899
+ )
900
+
901
+ button.click(text_to_image_with_template, inputs=[prompt,template_image,slider_step,slider_guidance,slider_batch,binary], outputs=[output,intermediate_results])
902
+
903
+ with gr.Tab("Text-Inpainting"):
904
+ with gr.Row():
905
+ with gr.Column(scale=1):
906
+ prompt = gr.Textbox(label='Input your prompt here.')
907
+ with gr.Row():
908
+ orig_image = gr.Image(label='Original image', type="pil")
909
+ mask_image = gr.Image(label='Mask image', type="numpy")
910
+ slider_step = gr.Slider(minimum=1, maximum=50, value=20, step=1, label="Sampling step", info="The sampling step for TextDiffuser.")
911
+ slider_guidance = gr.Slider(minimum=1, maximum=9, value=7.5, step=0.5, label="Scale of classifier-free guidance", info="The scale of classifier-free guidance and is set to 7.5 in default.")
912
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=4, step=1, label="Batch size", info="The number of images to be sampled.")
913
+ button = gr.Button("Generate")
914
+ with gr.Column(scale=1):
915
+ output = gr.Image(label='Generated image')
916
+ with gr.Accordion("Intermediate results", open=False):
917
+ gr.Markdown("Masked image, segmentation mask, and details of segmentation mask from left to right.")
918
+ intermediate_results = gr.Image(label='')
919
+
920
+ gr.Markdown("## Prompt, Original Image, and Mask Examples")
921
+ gr.Examples(
922
+ [
923
+ ["eye on security protection", './images/text-inpainting/1.jpg', './images/text-inpainting/1mask.jpg'],
924
+ ["a logo of poppins", './images/text-inpainting/2.jpg', './images/text-inpainting/2mask.jpg'],
925
+ ["tips for middle space living ", './images/text-inpainting/3.jpg', './images/text-inpainting/3mask.jpg'],
926
+ ["george is a proud big sister", './images/text-inpainting/5.jpg', './images/text-inpainting/5mask.jpg'],
927
+ ["we are the great people", './images/text-inpainting/6.jpg', './images/text-inpainting/6mask.jpg'],
928
+ ["tech house interesting terrace party", './images/text-inpainting/7.jpg', './images/text-inpainting/7mask.jpg'],
929
+ ["2023", './images/text-inpainting/8.jpg', './images/text-inpainting/8mask.jpg'],
930
+ ["wear protective equipment necessary", './images/text-inpainting/9.jpg', './images/text-inpainting/9mask.jpg'],
931
+ ["a good day in the hometown", './images/text-inpainting/10.jpg', './images/text-inpainting/10mask.jpg'],
932
+ ["a boy paints good morning on a board", './images/text-inpainting/11.jpg', './images/text-inpainting/11mask.jpg'],
933
+ ["the word my gift on a basketball", './images/text-inpainting/13.jpg', './images/text-inpainting/13mask.jpg'],
934
+ ["a logo of mono", './images/text-inpainting/14.jpg', './images/text-inpainting/14mask.jpg'],
935
+ ["a board saying assyrian on unflagging fry devastates", './images/text-inpainting/15.jpg', './images/text-inpainting/15mask.jpg'],
936
+ ["a board saying session", './images/text-inpainting/16.jpg', './images/text-inpainting/16mask.jpg'],
937
+ ["rankin dork", './images/text-inpainting/17mask.jpg', './images/text-inpainting/17.jpg'],
938
+ ["a coin of mem", './images/text-inpainting/18mask.jpg', './images/text-inpainting/18.jpg'],
939
+ ["a board without text", './images/text-inpainting/19.jpg', './images/text-inpainting/19mask.jpg'],
940
+ ["a board without text", './images/text-inpainting/20.jpg', './images/text-inpainting/20mask.jpg'],
941
+
942
+ ],
943
+ [prompt,orig_image,mask_image],
944
+ )
945
+
946
+
947
+ button.click(text_inpainting, inputs=[prompt,orig_image,mask_image,slider_step,slider_guidance,slider_batch], outputs=[output, intermediate_results])
948
+
949
+
950
+
951
+ gr.HTML(
952
+ """
953
+ <div style="text-align: justify; max-width: 1200px; margin: 20px auto;">
954
+ <h3 style="font-weight: 450; font-size: 0.8rem; margin: 0rem">
955
+ <b>Version</b>: 1.0
956
+ </h3>
957
+ <h3 style="font-weight: 450; font-size: 0.8rem; margin: 0rem">
958
+ <b>Contact</b>:
959
+ For help or issues using TextDiffuser, 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, please contact Lei Cui <a href="mailto:[email protected]">([email protected])</a> or Furu Wei <a href="mailto:[email protected]">([email protected])</a>.
960
+ </h3>
961
+ </div>
962
+ """
963
+ )
964
+
965
+ demo.launch()
inference.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------
2
+ # TextDiffuser: Diffusion Models as Text Painters
3
+ # Paper Link: https://arxiv.org/abs/2305.10855
4
+ # Code Link: https://github.com/microsoft/unilm/tree/master/textdiffuser
5
+ # Copyright (c) Microsoft Corporation.
6
+ # This file provides the inference script.
7
+ # ------------------------------------------
8
+
9
+ import os
10
+ import cv2
11
+ import random
12
+ import logging
13
+ import argparse
14
+ import numpy as np
15
+
16
+ from pathlib import Path
17
+ from tqdm.auto import tqdm
18
+ from typing import Optional
19
+ from packaging import version
20
+ from termcolor import colored
21
+ from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageEnhance # import for visualization
22
+ from huggingface_hub import HfFolder, Repository, create_repo, whoami
23
+
24
+ import datasets
25
+ from datasets import load_dataset
26
+ from datasets import disable_caching
27
+
28
+ import torch
29
+ import torch.utils.checkpoint
30
+ import torch.nn.functional as F
31
+ from torchvision import transforms
32
+
33
+ import accelerate
34
+ from accelerate import Accelerator
35
+ from accelerate.logging import get_logger
36
+ from accelerate.utils import ProjectConfiguration, set_seed
37
+
38
+ import diffusers
39
+ from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
40
+ from diffusers.optimization import get_scheduler
41
+ from diffusers.training_utils import EMAModel
42
+ from diffusers.utils import check_min_version, deprecate
43
+ from diffusers.utils.import_utils import is_xformers_available
44
+
45
+ import transformers
46
+ from transformers import CLIPTextModel, CLIPTokenizer
47
+
48
+ from util import segmentation_mask_visualization, make_caption_pil, combine_image, transform_mask, filter_segmentation_mask, inpainting_merge_image
49
+ from model.layout_generator import get_layout_from_prompt
50
+ from model.text_segmenter.unet import UNet
51
+
52
+ import torchsnooper
53
+
54
+ disable_caching()
55
+ check_min_version("0.15.0.dev0")
56
+ logger = get_logger(__name__, log_level="INFO")
57
+
58
+
59
+ def parse_args():
60
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
61
+ parser.add_argument(
62
+ "--pretrained_model_name_or_path",
63
+ type=str,
64
+ default='runwayml/stable-diffusion-v1-5', # no need to modify this
65
+ help="Path to pretrained model or model identifier from huggingface.co/models. Please do not modify this.",
66
+ )
67
+ parser.add_argument(
68
+ "--revision",
69
+ type=str,
70
+ default=None,
71
+ required=False,
72
+ help="Revision of pretrained model identifier from huggingface.co/models.",
73
+ )
74
+ parser.add_argument(
75
+ "--mode",
76
+ type=str,
77
+ default=None,
78
+ required=True,
79
+ choices=["text-to-image", "text-to-image-with-template", "text-inpainting"],
80
+ help="Three modes can be used.",
81
+ )
82
+ parser.add_argument(
83
+ "--prompt",
84
+ type=str,
85
+ default="",
86
+ required=True,
87
+ help="The text prompts provided by users.",
88
+ )
89
+ parser.add_argument(
90
+ "--template_image",
91
+ type=str,
92
+ default="",
93
+ help="The template image should be given when using 【text-to-image-with-template】 mode.",
94
+ )
95
+ parser.add_argument(
96
+ "--original_image",
97
+ type=str,
98
+ default="",
99
+ help="The original image should be given when using 【text-inpainting】 mode.",
100
+ )
101
+ parser.add_argument(
102
+ "--text_mask",
103
+ type=str,
104
+ default="",
105
+ help="The text mask should be given when using 【text-inpainting】 mode.",
106
+ )
107
+ parser.add_argument(
108
+ "--output_dir",
109
+ type=str,
110
+ default="output",
111
+ help="The output directory where the model predictions and checkpoints will be written.",
112
+ )
113
+ parser.add_argument(
114
+ "--cache_dir",
115
+ type=str,
116
+ default=None,
117
+ help="The directory where the downloaded models and datasets will be stored.",
118
+ )
119
+ parser.add_argument(
120
+ "--seed",
121
+ type=int,
122
+ default=None,
123
+ help="A seed for reproducible training."
124
+ )
125
+ parser.add_argument(
126
+ "--resolution",
127
+ type=int,
128
+ default=512,
129
+ help=(
130
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
131
+ " resolution"
132
+ ),
133
+ )
134
+ parser.add_argument(
135
+ "--classifier_free_scale",
136
+ type=float,
137
+ default=7.5, # following stable diffusion (https://github.com/CompVis/stable-diffusion)
138
+ help="Classifier free scale following https://arxiv.org/abs/2207.12598.",
139
+ )
140
+ parser.add_argument(
141
+ "--drop_caption",
142
+ action="store_true",
143
+ help="Whether to drop captions during training following https://arxiv.org/abs/2207.12598.."
144
+ )
145
+ parser.add_argument(
146
+ "--dataloader_num_workers",
147
+ type=int,
148
+ default=0,
149
+ help="Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
150
+ )
151
+ parser.add_argument(
152
+ "--push_to_hub",
153
+ action="store_true",
154
+ help="Whether or not to push the model to the Hub."
155
+ )
156
+ parser.add_argument(
157
+ "--hub_token",
158
+ type=str,
159
+ default=None,
160
+ help="The token to use to push to the Model Hub."
161
+ )
162
+ parser.add_argument(
163
+ "--hub_model_id",
164
+ type=str,
165
+ default=None,
166
+ help="The name of the repository to keep in sync with the local `output_dir`.",
167
+ )
168
+ parser.add_argument(
169
+ "--logging_dir",
170
+ type=str,
171
+ default="logs",
172
+ help=(
173
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
174
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
175
+ ),
176
+ )
177
+ parser.add_argument(
178
+ "--mixed_precision",
179
+ type=str,
180
+ default='fp16',
181
+ choices=["no", "fp16", "bf16"],
182
+ help=(
183
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
184
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
185
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
186
+ ),
187
+ )
188
+ parser.add_argument(
189
+ "--report_to",
190
+ type=str,
191
+ default="tensorboard",
192
+ help=(
193
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
194
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
195
+ ),
196
+ )
197
+ parser.add_argument(
198
+ "--local_rank",
199
+ type=int,
200
+ default=-1,
201
+ help="For distributed training: local_rank"
202
+ )
203
+ parser.add_argument(
204
+ "--checkpointing_steps",
205
+ type=int,
206
+ default=500,
207
+ help=(
208
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
209
+ " training using `--resume_from_checkpoint`."
210
+ ),
211
+ )
212
+ parser.add_argument(
213
+ "--checkpoints_total_limit",
214
+ type=int,
215
+ default=5,
216
+ help=(
217
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
218
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
219
+ " for more docs"
220
+ ),
221
+ )
222
+ parser.add_argument(
223
+ "--resume_from_checkpoint",
224
+ type=str,
225
+ default=None, # should be specified during inference
226
+ help=(
227
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
228
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
229
+ ),
230
+ )
231
+ parser.add_argument(
232
+ "--enable_xformers_memory_efficient_attention",
233
+ action="store_true",
234
+ help="Whether or not to use xformers."
235
+ )
236
+ parser.add_argument(
237
+ "--font_path",
238
+ type=str,
239
+ default='assets/font/Arial.ttf',
240
+ help="The path of font for visualization."
241
+ )
242
+ parser.add_argument(
243
+ "--sample_steps",
244
+ type=int,
245
+ default=50, # following stable diffusion (https://github.com/CompVis/stable-diffusion)
246
+ help="Diffusion steps for sampling."
247
+ )
248
+ parser.add_argument(
249
+ "--vis_num",
250
+ type=int,
251
+ default=9, # please decreases the number if out-of-memory error occurs
252
+ help="Number of images to be sample. Please decrease it when encountering out of memory error."
253
+ )
254
+ parser.add_argument(
255
+ "--binarization",
256
+ action="store_true",
257
+ help="Whether to binarize the template image."
258
+ )
259
+ parser.add_argument(
260
+ "--use_pillow_segmentation_mask",
261
+ type=bool,
262
+ default=True,
263
+ help="In the 【text-to-image】 mode, please specify whether to use the segmentation masks provided by PILLOW"
264
+ )
265
+ parser.add_argument(
266
+ "--character_segmenter_path",
267
+ type=str,
268
+ default='textdiffuser-ckpt/text_segmenter.pth',
269
+ help="checkpoint of character-level segmenter"
270
+ )
271
+ args = parser.parse_args()
272
+
273
+ print(f'{colored("[√]", "green")} Arguments are loaded.')
274
+ print(args)
275
+
276
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
277
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
278
+ args.local_rank = env_local_rank
279
+
280
+ return args
281
+
282
+
283
+
284
+ def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None):
285
+ if token is None:
286
+ token = HfFolder.get_token()
287
+ if organization is None:
288
+ username = whoami(token)["name"]
289
+ return f"{username}/{model_id}"
290
+ else:
291
+ return f"{organization}/{model_id}"
292
+
293
+
294
+ # @torchsnooper.snoop()
295
+ def main():
296
+ args = parse_args()
297
+ # If passed along, set the training seed now.
298
+ seed = args.seed if args.seed is not None else random.randint(0, 1000000)
299
+ set_seed(seed)
300
+ print(f'{colored("[√]", "green")} Seed is set to {seed}.')
301
+
302
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
303
+ sub_output_dir = f"{args.prompt}_[{args.mode.upper()}]_[SEED-{seed}]"
304
+
305
+ print(f'{colored("[√]", "green")} Logging dir is set to {logging_dir}.')
306
+
307
+ accelerator_project_config = ProjectConfiguration(total_limit=args.checkpoints_total_limit)
308
+
309
+ accelerator = Accelerator(
310
+ gradient_accumulation_steps=1,
311
+ mixed_precision=args.mixed_precision,
312
+ log_with=args.report_to,
313
+ logging_dir=logging_dir,
314
+ project_config=accelerator_project_config,
315
+ )
316
+
317
+ # Make one log on every process with the configuration for debugging.
318
+ logging.basicConfig(
319
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
320
+ datefmt="%m/%d/%Y %H:%M:%S",
321
+ level=logging.INFO,
322
+ )
323
+ logger.info(accelerator.state, main_process_only=False)
324
+ if accelerator.is_local_main_process:
325
+ datasets.utils.logging.set_verbosity_warning()
326
+ transformers.utils.logging.set_verbosity_warning()
327
+ diffusers.utils.logging.set_verbosity_info()
328
+ else:
329
+ datasets.utils.logging.set_verbosity_error()
330
+ transformers.utils.logging.set_verbosity_error()
331
+ diffusers.utils.logging.set_verbosity_error()
332
+
333
+ # Handle the repository creation
334
+ if accelerator.is_main_process:
335
+ if args.push_to_hub:
336
+ if args.hub_model_id is None:
337
+ repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
338
+ else:
339
+ repo_name = args.hub_model_id
340
+ create_repo(repo_name, exist_ok=True, token=args.hub_token)
341
+ repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
342
+
343
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
344
+ if "step_*" not in gitignore:
345
+ gitignore.write("step_*\n")
346
+ if "epoch_*" not in gitignore:
347
+ gitignore.write("epoch_*\n")
348
+ elif args.output_dir is not None:
349
+ os.makedirs(args.output_dir, exist_ok=True)
350
+ print(args.output_dir)
351
+
352
+ # Load scheduler, tokenizer and models.
353
+ tokenizer = CLIPTokenizer.from_pretrained(
354
+ args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
355
+ )
356
+ text_encoder = CLIPTextModel.from_pretrained(
357
+ args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
358
+ )
359
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision).cuda()
360
+ unet = UNet2DConditionModel.from_pretrained(
361
+ args.resume_from_checkpoint, subfolder="unet", revision=None
362
+ ).cuda()
363
+
364
+ # Freeze vae and text_encoder
365
+ vae.requires_grad_(False)
366
+ text_encoder.requires_grad_(False)
367
+
368
+ if args.enable_xformers_memory_efficient_attention:
369
+ if is_xformers_available():
370
+ import xformers
371
+
372
+ xformers_version = version.parse(xformers.__version__)
373
+ if xformers_version == version.parse("0.0.16"):
374
+ logger.warn(
375
+ "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
376
+ )
377
+ unet.enable_xformers_memory_efficient_attention()
378
+ else:
379
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
380
+
381
+ # `accelerate` 0.16.0 will have better support for customized saving
382
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
383
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
384
+ def save_model_hook(models, weights, output_dir):
385
+
386
+ for i, model in enumerate(models):
387
+ model.save_pretrained(os.path.join(output_dir, "unet"))
388
+
389
+ # make sure to pop weight so that corresponding model is not saved again
390
+ weights.pop()
391
+
392
+ def load_model_hook(models, input_dir):
393
+
394
+ for i in range(len(models)):
395
+ # pop models so that they are not loaded again
396
+ model = models.pop()
397
+
398
+ # load diffusers style into model
399
+ load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
400
+ model.register_to_config(**load_model.config)
401
+
402
+ model.load_state_dict(load_model.state_dict())
403
+ del load_model
404
+
405
+ accelerator.register_save_state_pre_hook(save_model_hook)
406
+ accelerator.register_load_state_pre_hook(load_model_hook)
407
+
408
+
409
+ # setup schedulers
410
+ scheduler = DDPMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
411
+ scheduler.set_timesteps(args.sample_steps)
412
+ sample_num = args.vis_num
413
+ noise = torch.randn((sample_num, 4, 64, 64)).to("cuda") # (b, 4, 64, 64)
414
+ input = noise # (b, 4, 64, 64)
415
+
416
+ captions = [args.prompt] * sample_num
417
+ captions_nocond = [""] * sample_num
418
+ print(f'{colored("[√]", "green")} Prompt is loaded: {args.prompt}.')
419
+
420
+ # encode text prompts
421
+ inputs = tokenizer(
422
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
423
+ ).input_ids # (b, 77)
424
+ encoder_hidden_states = text_encoder(inputs)[0].cuda() # (b, 77, 768)
425
+ print(f'{colored("[√]", "green")} encoder_hidden_states: {encoder_hidden_states.shape}.')
426
+
427
+ inputs_nocond = tokenizer(
428
+ captions_nocond, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
429
+ ).input_ids # (b, 77)
430
+ encoder_hidden_states_nocond = text_encoder(inputs_nocond)[0].cuda() # (b, 77, 768)
431
+ print(f'{colored("[√]", "green")} encoder_hidden_states_nocond: {encoder_hidden_states_nocond.shape}.')
432
+
433
+ # load character-level segmenter
434
+ segmenter = UNet(3, 96, True).cuda()
435
+ segmenter = torch.nn.DataParallel(segmenter)
436
+ segmenter.load_state_dict(torch.load(args.character_segmenter_path))
437
+ segmenter.eval()
438
+ print(f'{colored("[√]", "green")} Text segmenter is successfully loaded.')
439
+
440
+ #### text-to-image ####
441
+ if args.mode == 'text-to-image':
442
+ render_image, segmentation_mask_from_pillow = get_layout_from_prompt(args)
443
+
444
+ if args.use_pillow_segmentation_mask:
445
+ segmentation_mask = torch.Tensor(np.array(segmentation_mask_from_pillow)).cuda() # (512, 512)
446
+ else:
447
+ to_tensor = transforms.ToTensor()
448
+ image_tensor = to_tensor(render_image).unsqueeze(0).cuda().sub_(0.5).div_(0.5)
449
+ with torch.no_grad():
450
+ segmentation_mask = segmenter(image_tensor)
451
+ segmentation_mask = segmentation_mask.max(1)[1].squeeze(0)
452
+
453
+ segmentation_mask = filter_segmentation_mask(segmentation_mask)
454
+ segmentation_mask = torch.nn.functional.interpolate(segmentation_mask.unsqueeze(0).unsqueeze(0).float(), size=(256, 256), mode='nearest')
455
+ segmentation_mask = segmentation_mask.squeeze(1).repeat(sample_num, 1, 1).long().to('cuda') # (1, 1, 256, 256)
456
+ print(f'{colored("[√]", "green")} character-level segmentation_mask: {segmentation_mask.shape}.')
457
+
458
+ feature_mask = torch.ones(sample_num, 1, 64, 64).to('cuda') # (b, 1, 64, 64)
459
+ masked_image = torch.zeros(sample_num, 3, 512, 512).to('cuda') # (b, 3, 512, 512)
460
+ masked_feature = vae.encode(masked_image).latent_dist.sample() # (b, 4, 64, 64)
461
+ masked_feature = masked_feature * vae.config.scaling_factor
462
+ print(f'{colored("[√]", "green")} feature_mask: {feature_mask.shape}.')
463
+ print(f'{colored("[√]", "green")} masked_feature: {masked_feature.shape}.')
464
+
465
+
466
+ #### text-to-image-with-template ####
467
+ if args.mode == 'text-to-image-with-template':
468
+ template_image = Image.open(args.template_image).resize((256,256)).convert('RGB')
469
+
470
+ # whether binarization is needed
471
+ print(f'{colored("[Warning]", "red")} args.binarization is set to {args.binarization}. You may need it when using handwritten images as templates.')
472
+ if args.binarization:
473
+ gray = ImageOps.grayscale(template_image)
474
+ binary = gray.point(lambda x: 255 if x > 96 else 0, '1')
475
+ template_image = binary.convert('RGB')
476
+
477
+ to_tensor = transforms.ToTensor()
478
+ image_tensor = to_tensor(template_image).unsqueeze(0).cuda().sub_(0.5).div_(0.5) # (b, 3, 256, 256)
479
+
480
+ with torch.no_grad():
481
+ segmentation_mask = segmenter(image_tensor) # (b, 96, 256, 256)
482
+ segmentation_mask = segmentation_mask.max(1)[1].squeeze(0) # (256, 256)
483
+ segmentation_mask = filter_segmentation_mask(segmentation_mask) # (256, 256)
484
+ segmentation_mask_pil = Image.fromarray(segmentation_mask.type(torch.uint8).cpu().numpy()).convert('RGB')
485
+
486
+ segmentation_mask = torch.nn.functional.interpolate(segmentation_mask.unsqueeze(0).unsqueeze(0).float(), size=(256, 256), mode='nearest') # (b, 1, 256, 256)
487
+ segmentation_mask = segmentation_mask.squeeze(1).repeat(sample_num, 1, 1).long().to('cuda') # (b, 1, 256, 256)
488
+ print(f'{colored("[√]", "green")} Character-level segmentation_mask: {segmentation_mask.shape}.')
489
+
490
+ feature_mask = torch.ones(sample_num, 1, 64, 64).to('cuda') # (b, 1, 64, 64)
491
+ masked_image = torch.zeros(sample_num, 3, 512, 512).to('cuda') # (b, 3, 512, 512)
492
+ masked_feature = vae.encode(masked_image).latent_dist.sample() # (b, 4, 64, 64)
493
+ masked_feature = masked_feature * vae.config.scaling_factor # (b, 4, 64, 64)
494
+ print(f'{colored("[√]", "green")} feature_mask: {feature_mask.shape}.')
495
+ print(f'{colored("[√]", "green")} masked_feature: {masked_feature.shape}.')
496
+
497
+ render_image = template_image # for visualization
498
+
499
+
500
+ #### text-inpainting ####
501
+ if args.mode == 'text-inpainting':
502
+ text_mask = cv2.imread(args.text_mask)
503
+ threshold = 128
504
+ _, text_mask = cv2.threshold(text_mask, threshold, 255, cv2.THRESH_BINARY)
505
+ text_mask = Image.fromarray(text_mask).convert('RGB').resize((256,256))
506
+ text_mask_tensor = transforms.ToTensor()(text_mask).unsqueeze(0).cuda().sub_(0.5).div_(0.5)
507
+ with torch.no_grad():
508
+ segmentation_mask = segmenter(text_mask_tensor)
509
+
510
+ segmentation_mask = segmentation_mask.max(1)[1].squeeze(0)
511
+ segmentation_mask = filter_segmentation_mask(segmentation_mask)
512
+ segmentation_mask = torch.nn.functional.interpolate(segmentation_mask.unsqueeze(0).unsqueeze(0).float(), size=(256, 256), mode='nearest')
513
+
514
+ image_mask = transform_mask(args.text_mask)
515
+ image_mask = torch.from_numpy(image_mask).cuda().unsqueeze(0).unsqueeze(0)
516
+
517
+ image = Image.open(args.original_image).convert('RGB').resize((512,512))
518
+ image_tensor = transforms.ToTensor()(image).unsqueeze(0).cuda().sub_(0.5).div_(0.5)
519
+ masked_image = image_tensor * (1-image_mask)
520
+ masked_feature = vae.encode(masked_image).latent_dist.sample().repeat(sample_num, 1, 1, 1)
521
+ masked_feature = masked_feature * vae.config.scaling_factor
522
+
523
+ image_mask = torch.nn.functional.interpolate(image_mask, size=(256, 256), mode='nearest').repeat(sample_num, 1, 1, 1)
524
+ segmentation_mask = segmentation_mask * image_mask
525
+ feature_mask = torch.nn.functional.interpolate(image_mask, size=(64, 64), mode='nearest')
526
+ print(f'{colored("[√]", "green")} feature_mask: {feature_mask.shape}.')
527
+ print(f'{colored("[√]", "green")} segmentation_mask: {segmentation_mask.shape}.')
528
+ print(f'{colored("[√]", "green")} masked_feature: {masked_feature.shape}.')
529
+
530
+ render_image = Image.open(args.original_image)
531
+
532
+
533
+
534
+ # diffusion process
535
+ intermediate_images = []
536
+ for t in tqdm(scheduler.timesteps):
537
+ with torch.no_grad():
538
+ noise_pred_cond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states, segmentation_mask=segmentation_mask, feature_mask=feature_mask, masked_feature=masked_feature).sample # b, 4, 64, 64
539
+ noise_pred_uncond = unet(sample=input, timestep=t, encoder_hidden_states=encoder_hidden_states_nocond, segmentation_mask=segmentation_mask, feature_mask=feature_mask, masked_feature=masked_feature).sample # b, 4, 64, 64
540
+ noisy_residual = noise_pred_uncond + args.classifier_free_scale * (noise_pred_cond - noise_pred_uncond) # b, 4, 64, 64
541
+ prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
542
+ input = prev_noisy_sample
543
+ intermediate_images.append(prev_noisy_sample)
544
+
545
+ # decode and visualization
546
+ input = 1 / vae.config.scaling_factor * input
547
+ sample_images = vae.decode(input.float(), return_dict=False)[0] # (b, 3, 512, 512)
548
+
549
+ image_pil = render_image.resize((512,512))
550
+ segmentation_mask = segmentation_mask[0].squeeze().cpu().numpy()
551
+ character_mask_pil = Image.fromarray(((segmentation_mask!=0)*255).astype('uint8')).resize((512,512))
552
+ character_mask_highlight_pil = segmentation_mask_visualization(args.font_path,segmentation_mask)
553
+ caption_pil = make_caption_pil(args.font_path, captions)
554
+
555
+ # save pred_img
556
+ pred_image_list = []
557
+ for image in sample_images.float():
558
+ image = (image / 2 + 0.5).clamp(0, 1).unsqueeze(0)
559
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
560
+ image = Image.fromarray((image * 255).round().astype("uint8")).convert('RGB')
561
+ pred_image_list.append(image)
562
+
563
+ os.makedirs(f'{args.output_dir}/{sub_output_dir}', exist_ok=True)
564
+
565
+ # save additional info
566
+ if args.mode == 'text-to-image':
567
+ image_pil.save(os.path.join(args.output_dir, sub_output_dir, 'render_text_image.png'))
568
+ enhancer = ImageEnhance.Brightness(segmentation_mask_from_pillow)
569
+ im_brightness = enhancer.enhance(5)
570
+ im_brightness.save(os.path.join(args.output_dir, sub_output_dir, 'segmentation_mask_from_pillow.png'))
571
+ if args.mode == 'text-to-image-with-template':
572
+ template_image.save(os.path.join(args.output_dir, sub_output_dir, 'template.png'))
573
+ enhancer = ImageEnhance.Brightness(segmentation_mask_pil)
574
+ im_brightness = enhancer.enhance(5)
575
+ im_brightness.save(os.path.join(args.output_dir, sub_output_dir, 'segmentation_mask_from_template.png'))
576
+ if args.mode == 'text-inpainting':
577
+ character_mask_highlight_pil = character_mask_pil
578
+ # background
579
+ background = Image.open(args.original_image).resize((512, 512))
580
+ alpha = Image.new('L', background.size, int(255 * 0.2))
581
+ background.putalpha(alpha)
582
+ # foreground
583
+ foreground = Image.open(args.text_mask).convert('L').resize((512, 512))
584
+ threshold = 200
585
+ alpha = foreground.point(lambda x: 0 if x > threshold else 255, '1')
586
+ foreground.putalpha(alpha)
587
+ character_mask_pil = Image.alpha_composite(foreground.convert('RGBA'), background.convert('RGBA')).convert('RGB')
588
+ # merge
589
+ pred_image_list_new = []
590
+ for pred_image in pred_image_list:
591
+ pred_image = inpainting_merge_image(Image.open(args.original_image), Image.open(args.text_mask).convert('L'), pred_image)
592
+ pred_image_list_new.append(pred_image)
593
+ pred_image_list = pred_image_list_new
594
+
595
+
596
+ combine_image(args, sub_output_dir, pred_image_list, image_pil, character_mask_pil, character_mask_highlight_pil, caption_pil)
597
+
598
+
599
+ # create a soft link
600
+ if os.path.exists(os.path.join(args.output_dir, 'latest')):
601
+ os.unlink(os.path.join(args.output_dir, 'latest'))
602
+ os.symlink(os.path.abspath(os.path.join(args.output_dir, sub_output_dir)), os.path.abspath(os.path.join(args.output_dir, 'latest/')))
603
+
604
+
605
+ color_sub_output_dir = colored(sub_output_dir, 'green')
606
+ print(f'{colored("[√]", "green")} Save successfully. Please check the output at {color_sub_output_dir} OR the latest folder')
607
+
608
+ if __name__ == "__main__":
609
+ main()
model/__pycache__/layout_generator.cpython-38.pyc ADDED
Binary file (5.25 kB). View file
 
model/__pycache__/layout_transformer.cpython-38.pyc ADDED
Binary file (3.42 kB). View file
 
model/layout_generator.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------
2
+ # TextDiffuser: Diffusion Models as Text Painters
3
+ # Paper Link: https://arxiv.org/abs/2305.10855
4
+ # Code Link: https://github.com/microsoft/unilm/tree/master/textdiffuser
5
+ # Copyright (c) Microsoft Corporation.
6
+ # This file aims to predict the layout of keywords in user prompts.
7
+ # ------------------------------------------
8
+
9
+ import warnings
10
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
11
+
12
+ import re
13
+ import numpy as np
14
+ import torch
15
+ import torch.nn as nn
16
+ from transformers import CLIPTokenizer
17
+ from PIL import Image, ImageDraw, ImageFont
18
+ from util import get_width, get_key_words, adjust_overlap_box, shrink_box, adjust_font_size, alphabet_dic
19
+ from model.layout_transformer import LayoutTransformer, TextConditioner
20
+ from termcolor import colored
21
+
22
+ # import layout transformer
23
+ model = LayoutTransformer().cuda().eval()
24
+ model.load_state_dict(torch.load('textdiffuser-ckpt/layout_transformer.pth'))
25
+
26
+ # import text encoder and tokenizer
27
+ text_encoder = TextConditioner().cuda().eval()
28
+ tokenizer = CLIPTokenizer.from_pretrained('openai/clip-vit-large-patch14')
29
+
30
+
31
+ def process_caption(font_path, caption, keywords):
32
+ # remove punctuations. please remove this statement if you want to paint punctuations
33
+ caption = re.sub(u"([^\u0041-\u005a\u0061-\u007a\u0030-\u0039])", " ", caption)
34
+
35
+ # tokenize it into ids and get length
36
+ caption_words = tokenizer([caption], truncation=True, max_length=77, return_length=True, return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
37
+ caption_words_ids = caption_words['input_ids'] # (1, 77)
38
+ length = caption_words['length'] # (1, )
39
+
40
+ # convert id to words
41
+ words = tokenizer.convert_ids_to_tokens(caption_words_ids.view(-1).tolist())
42
+ words = [i.replace('</w>', '') for i in words]
43
+ words_valid = words[:int(length)]
44
+
45
+ # store the box coordinates and state of each token
46
+ info_array = np.zeros((77,5)) # (77, 5)
47
+
48
+ # split the caption into words and convert them into lower case
49
+ caption_split = caption.split()
50
+ caption_split = [i.lower() for i in caption_split]
51
+
52
+ start_dic = {} # get the start index of each word
53
+ state_list = [] # 0: start, 1: middle, 2: special token
54
+ word_match_list = [] # the index of the word in the caption
55
+ current_caption_index = 0
56
+ current_match = ''
57
+ for i in range(length):
58
+
59
+ # the first and last token are special tokens
60
+ if i == 0 or i == length-1:
61
+ state_list.append(2)
62
+ word_match_list.append(127)
63
+ continue
64
+
65
+ if current_match == '':
66
+ state_list.append(0)
67
+ start_dic[current_caption_index] = i
68
+ else:
69
+ state_list.append(1)
70
+
71
+ current_match += words_valid[i]
72
+ word_match_list.append(current_caption_index)
73
+ if current_match == caption_split[current_caption_index]:
74
+ current_match = ''
75
+ current_caption_index += 1
76
+
77
+ while len(state_list) < 77:
78
+ state_list.append(127)
79
+ while len(word_match_list) < 77:
80
+ word_match_list.append(127)
81
+
82
+ length_list = []
83
+ width_list =[]
84
+ for i in range(len(word_match_list)):
85
+ if word_match_list[i] == 127:
86
+ length_list.append(0)
87
+ width_list.append(0)
88
+ else:
89
+ length_list.append(len(caption.split()[word_match_list[i]]))
90
+ width_list.append(get_width(font_path, caption.split()[word_match_list[i]]))
91
+
92
+ while len(length_list) < 77:
93
+ length_list.append(127)
94
+ width_list.append(0)
95
+
96
+ length_list = torch.Tensor(length_list).long() # (77, )
97
+ width_list = torch.Tensor(width_list).long() # (77, )
98
+
99
+ boxes = []
100
+ duplicate_dict = {} # some words may appear more than once
101
+ for keyword in keywords:
102
+ keyword = keyword.lower()
103
+ if keyword in caption_split:
104
+ if keyword not in duplicate_dict:
105
+ duplicate_dict[keyword] = caption_split.index(keyword)
106
+ index = caption_split.index(keyword)
107
+ else:
108
+ if duplicate_dict[keyword]+1 < len(caption_split) and keyword in caption_split[duplicate_dict[keyword]+1:]:
109
+ index = duplicate_dict[keyword] + caption_split[duplicate_dict[keyword]+1:].index(keyword)
110
+ duplicate_dict[keyword] = index
111
+ else:
112
+ continue
113
+
114
+ index = caption_split.index(keyword)
115
+ index = start_dic[index]
116
+ info_array[index][0] = 1
117
+
118
+ box = [0,0,0,0]
119
+ boxes.append(list(box))
120
+ info_array[index][1:] = box
121
+
122
+ boxes_length = len(boxes)
123
+ if boxes_length > 8:
124
+ boxes = boxes[:8]
125
+ while len(boxes) < 8:
126
+ boxes.append([0,0,0,0])
127
+
128
+ return caption, length_list, width_list, torch.from_numpy(info_array), words, torch.Tensor(state_list).long(), torch.Tensor(word_match_list).long(), torch.Tensor(boxes), boxes_length
129
+
130
+
131
+ def get_layout_from_prompt(args):
132
+
133
+ # prompt = args.prompt
134
+ font_path = args.font_path
135
+ keywords = get_key_words(args.prompt)
136
+
137
+ print(f'{colored("[!]", "red")} Detected keywords: {keywords} from prompt {args.prompt}')
138
+
139
+ text_embedding, mask = text_encoder(args.prompt) # (1, 77 768) / (1, 77)
140
+
141
+ # process all relevant info
142
+ caption, length_list, width_list, target, words, state_list, word_match_list, boxes, boxes_length = process_caption(font_path, args.prompt, keywords)
143
+ target = target.cuda().unsqueeze(0) # (77, 5)
144
+ width_list = width_list.cuda().unsqueeze(0) # (77, )
145
+ length_list = length_list.cuda().unsqueeze(0) # (77, )
146
+ state_list = state_list.cuda().unsqueeze(0) # (77, )
147
+ word_match_list = word_match_list.cuda().unsqueeze(0) # (77, )
148
+
149
+ padding = torch.zeros(1, 1, 4).cuda()
150
+ boxes = boxes.unsqueeze(0).cuda()
151
+ right_shifted_boxes = torch.cat([padding, boxes[:,0:-1,:]],1) # (1, 8, 4)
152
+
153
+ # inference
154
+ return_boxes= []
155
+ with torch.no_grad():
156
+ for box_index in range(boxes_length):
157
+
158
+ if box_index == 0:
159
+ encoder_embedding = None
160
+
161
+ output, encoder_embedding = model(text_embedding, length_list, width_list, mask, state_list, word_match_list, target, right_shifted_boxes, train=False, encoder_embedding=encoder_embedding)
162
+ output = torch.clamp(output, min=0, max=1) # (1, 8, 4)
163
+
164
+ # add overlap detection
165
+ output = adjust_overlap_box(output, box_index) # (1, 8, 4)
166
+
167
+ right_shifted_boxes[:,box_index+1,:] = output[:,box_index,:]
168
+ xmin, ymin, xmax, ymax = output[0, box_index, :].tolist()
169
+ return_boxes.append([xmin, ymin, xmax, ymax])
170
+
171
+
172
+ # print the location of keywords
173
+ print(f'index\tkeyword\tx_min\ty_min\tx_max\ty_max')
174
+ for index, keyword in enumerate(keywords):
175
+ x_min = int(return_boxes[index][0] * 512)
176
+ y_min = int(return_boxes[index][1] * 512)
177
+ x_max = int(return_boxes[index][2] * 512)
178
+ y_max = int(return_boxes[index][3] * 512)
179
+ print(f'{index}\t{keyword}\t{x_min}\t{y_min}\t{x_max}\t{y_max}')
180
+
181
+
182
+ # paint the layout
183
+ render_image = Image.new('RGB', (512, 512), (255, 255, 255))
184
+ draw = ImageDraw.Draw(render_image)
185
+ segmentation_mask = Image.new("L", (512,512), 0)
186
+ segmentation_mask_draw = ImageDraw.Draw(segmentation_mask)
187
+
188
+ for index, box in enumerate(return_boxes):
189
+ box = [int(i*512) for i in box]
190
+ xmin, ymin, xmax, ymax = box
191
+
192
+ width = xmax - xmin
193
+ height = ymax - ymin
194
+ text = keywords[index]
195
+
196
+ font_size = adjust_font_size(args, width, height, draw, text)
197
+ font = ImageFont.truetype(args.font_path, font_size)
198
+
199
+ # draw.rectangle([xmin, ymin, xmax,ymax], outline=(255,0,0))
200
+ draw.text((xmin, ymin), text, font=font, fill=(0, 0, 0))
201
+
202
+ boxes = []
203
+ for i, char in enumerate(text):
204
+
205
+ # paint character-level segmentation masks
206
+ # https://github.com/python-pillow/Pillow/issues/3921
207
+ bottom_1 = font.getsize(text[i])[1]
208
+ right, bottom_2 = font.getsize(text[:i+1])
209
+ bottom = bottom_1 if bottom_1 < bottom_2 else bottom_2
210
+ width, height = font.getmask(char).size
211
+ right += xmin
212
+ bottom += ymin
213
+ top = bottom - height
214
+ left = right - width
215
+
216
+ char_box = (left, top, right, bottom)
217
+ boxes.append(char_box)
218
+
219
+ char_index = alphabet_dic[char]
220
+ segmentation_mask_draw.rectangle(shrink_box(char_box, scale_factor = 0.9), fill=char_index)
221
+
222
+ print(f'{colored("[√]", "green")} Layout is successfully generated')
223
+ return render_image, segmentation_mask
model/layout_transformer.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------
2
+ # TextDiffuser: Diffusion Models as Text Painters
3
+ # Paper Link: https://arxiv.org/abs/2305.10855
4
+ # Code Link: https://github.com/microsoft/unilm/tree/master/textdiffuser
5
+ # Copyright (c) Microsoft Corporation.
6
+ # This file define the Layout Transformer for predicting the layout of keywords.
7
+ # ------------------------------------------
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from transformers import CLIPTokenizer, CLIPTextModel
12
+
13
+ class TextConditioner(nn.Module):
14
+
15
+ def __init__(self):
16
+ super(TextConditioner, self).__init__()
17
+ self.transformer = CLIPTextModel.from_pretrained('openai/clip-vit-large-patch14')
18
+ self.tokenizer = CLIPTokenizer.from_pretrained('openai/clip-vit-large-patch14')
19
+
20
+ # fix
21
+ self.transformer.eval()
22
+ for param in self.transformer.parameters():
23
+ param.requires_grad = False
24
+
25
+ def forward(self, prompt_list):
26
+ batch_encoding = self.tokenizer(prompt_list, truncation=True, max_length=77, return_length=True, return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
27
+ text_embedding = self.transformer(batch_encoding["input_ids"].cuda())
28
+ return text_embedding.last_hidden_state.cuda(), batch_encoding["attention_mask"].cuda() # 1, 77, 768 / 1, 768
29
+
30
+
31
+ class LayoutTransformer(nn.Module):
32
+
33
+ def __init__(self, layer_number=2):
34
+ super(LayoutTransformer, self).__init__()
35
+
36
+ self.encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8)
37
+ self.transformer = torch.nn.TransformerEncoder(
38
+ self.encoder_layer, num_layers=layer_number
39
+ )
40
+
41
+ self.decoder_layer = nn.TransformerDecoderLayer(d_model=512, nhead=8)
42
+ self.decoder_transformer = torch.nn.TransformerDecoder(
43
+ self.decoder_layer, num_layers=layer_number
44
+ )
45
+
46
+ self.mask_embedding = nn.Embedding(2,512)
47
+ self.length_embedding = nn.Embedding(256,512)
48
+ self.width_embedding = nn.Embedding(256,512)
49
+ self.position_embedding = nn.Embedding(256,512)
50
+ self.state_embedding = nn.Embedding(256,512)
51
+ self.match_embedding = nn.Embedding(256,512)
52
+
53
+ self.x_embedding = nn.Embedding(512,512)
54
+ self.y_embedding = nn.Embedding(512,512)
55
+ self.w_embedding = nn.Embedding(512,512)
56
+ self.h_embedding = nn.Embedding(512,512)
57
+
58
+ self.encoder_target_embedding = nn.Embedding(256,512)
59
+
60
+ self.input_layer = nn.Sequential(
61
+ nn.Linear(768, 512),
62
+ nn.ReLU(),
63
+ nn.Linear(512, 512),
64
+ )
65
+
66
+ self.output_layer = nn.Sequential(
67
+ nn.Linear(512, 128),
68
+ nn.ReLU(),
69
+ nn.Linear(128, 4),
70
+ )
71
+
72
+ def forward(self, x, length, width, mask, state, match, target, right_shifted_boxes, train=False, encoder_embedding=None):
73
+
74
+ # detect whether the encoder_embedding is cached
75
+ if encoder_embedding is None:
76
+ # augmentation
77
+ if train:
78
+ width = width + torch.randint(-3, 3, (width.shape[0], width.shape[1])).cuda()
79
+
80
+ x = self.input_layer(x) # (1, 77, 512)
81
+ width_embedding = self.width_embedding(torch.clamp(width, 0, 255).long()) # (1, 77, 512)
82
+ encoder_target_embedding = self.encoder_target_embedding(target[:,:,0].long()) # (1, 77, 512)
83
+ pe_embedding = self.position_embedding(torch.arange(77).cuda()).unsqueeze(0) # (1, 77, 512)
84
+ total_embedding = x + width_embedding + pe_embedding + encoder_target_embedding # combine all the embeddings (1, 77, 512)
85
+ total_embedding = total_embedding.permute(1,0,2) # (77, 1, 512)
86
+ encoder_embedding = self.transformer(total_embedding) # (77, 1, 512)
87
+
88
+ right_shifted_boxes_resize = (right_shifted_boxes * 512).long() # (1, 8, 4)
89
+ right_shifted_boxes_resize = torch.clamp(right_shifted_boxes_resize, 0, 511) # (1, 8, 4)
90
+
91
+ # decoder pe
92
+ pe_decoder = torch.arange(8).cuda() # (8, )
93
+ pe_embedding_decoder = self.position_embedding(pe_decoder).unsqueeze(0) # (1, 8, 512)
94
+ decoder_input = pe_embedding_decoder + self.x_embedding(right_shifted_boxes_resize[:,:,0]) + self.y_embedding(right_shifted_boxes_resize[:,:,1]) + self.w_embedding(right_shifted_boxes_resize[:,:,2]) + self.h_embedding(right_shifted_boxes_resize[:,:,3]) # (1, 8, 512)
95
+ decoder_input = decoder_input.permute(1,0,2) # (8, 1, 512)
96
+
97
+ # generate triangular mask
98
+ mask = nn.Transformer.generate_square_subsequent_mask(8) # (8, 8)
99
+ mask = mask.cuda() # (8, 8)
100
+ decoder_result = self.decoder_transformer(decoder_input, encoder_embedding, tgt_mask=mask) # (8, 1, 512)
101
+ decoder_result = decoder_result.permute(1,0,2) # (1, 8, 512)
102
+
103
+ box_prediction = self.output_layer(decoder_result) # (1, 8, 4)
104
+ return box_prediction, encoder_embedding
105
+
106
+
107
+
model/text_segmenter/__pycache__/unet.cpython-38.pyc ADDED
Binary file (1.46 kB). View file
 
model/text_segmenter/__pycache__/unet_parts.cpython-38.pyc ADDED
Binary file (2.8 kB). View file
 
model/text_segmenter/unet.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------
2
+ # TextDiffuser: Diffusion Models as Text Painters
3
+ # Paper Link: https://arxiv.org/abs/2305.10855
4
+ # Code Link: https://github.com/microsoft/unilm/tree/master/textdiffuser
5
+ # Copyright (c) Microsoft Corporation.
6
+ # This file define the architecture of unet.
7
+ # ------------------------------------------
8
+
9
+ import torch.nn.functional as F
10
+ from model.text_segmenter.unet_parts import *
11
+
12
+
13
+ class UNet(nn.Module):
14
+ def __init__(self, n_channels, n_classes, bilinear=True):
15
+ super(UNet, self).__init__()
16
+ self.n_channels = n_channels
17
+ self.n_classes = n_classes
18
+ self.bilinear = bilinear
19
+
20
+ self.inc = DoubleConv(n_channels, 64)
21
+ self.down1 = Down(64, 128)
22
+ self.down2 = Down(128, 256)
23
+ self.down3 = Down(256, 512)
24
+ factor = 2 if bilinear else 1
25
+ self.down4 = Down(512, 1024 // factor)
26
+ self.up1 = Up(1024, 512 // factor, bilinear)
27
+ self.up2 = Up(512, 256 // factor, bilinear)
28
+ self.up3 = Up(256, 128 // factor, bilinear)
29
+ self.up4 = Up(128, 64, bilinear)
30
+ self.outc = OutConv(64, n_classes)
31
+
32
+ def forward(self, x):
33
+ x1 = self.inc(x)
34
+ x2 = self.down1(x1)
35
+ x3 = self.down2(x2)
36
+ x4 = self.down3(x3)
37
+ x5 = self.down4(x4)
38
+ x = self.up1(x5, x4)
39
+ x = self.up2(x, x3)
40
+ x = self.up3(x, x2)
41
+ x = self.up4(x, x1)
42
+ logits = self.outc(x)
43
+ # logits = torch.sigmoid(logits)
44
+ return logits
45
+
46
+ if __name__ == '__main__':
47
+ net = UNet(39,39,True)
48
+
49
+ net = net.cuda()
50
+
51
+ image = torch.Tensor(32,39,64,64).cuda()
52
+ result = net(image)
53
+ print(result.shape)
model/text_segmenter/unet_parts.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------
2
+ # TextDiffuser: Diffusion Models as Text Painters
3
+ # Paper Link: https://arxiv.org/abs/2305.10855
4
+ # Code Link: https://github.com/microsoft/unilm/tree/master/textdiffuser
5
+ # Copyright (c) Microsoft Corporation.
6
+ # This file define the architecture of unet.
7
+ # ------------------------------------------
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+
13
+
14
+ class DoubleConv(nn.Module):
15
+ """(convolution => [BN] => ReLU) * 2"""
16
+
17
+ def __init__(self, in_channels, out_channels, mid_channels=None):
18
+ super().__init__()
19
+ if not mid_channels:
20
+ mid_channels = out_channels
21
+ self.double_conv = nn.Sequential(
22
+ nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1),
23
+ nn.BatchNorm2d(mid_channels),
24
+ nn.ReLU(inplace=True),
25
+ nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1),
26
+ nn.BatchNorm2d(out_channels),
27
+ nn.ReLU(inplace=True)
28
+ )
29
+
30
+ def forward(self, x):
31
+ return self.double_conv(x)
32
+
33
+
34
+ class Down(nn.Module):
35
+ """Downscaling with maxpool then double conv"""
36
+
37
+ def __init__(self, in_channels, out_channels):
38
+ super().__init__()
39
+ self.maxpool_conv = nn.Sequential(
40
+ nn.MaxPool2d(2),
41
+ DoubleConv(in_channels, out_channels)
42
+ )
43
+
44
+ def forward(self, x):
45
+ return self.maxpool_conv(x)
46
+
47
+
48
+ class Up(nn.Module):
49
+ """Upscaling then double conv"""
50
+
51
+ def __init__(self, in_channels, out_channels, bilinear=True):
52
+ super().__init__()
53
+
54
+ # if bilinear, use the normal convolutions to reduce the number of channels
55
+ if bilinear:
56
+ self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
57
+ self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)
58
+ else:
59
+ self.up = nn.ConvTranspose2d(in_channels , in_channels // 2, kernel_size=2, stride=2)
60
+ self.conv = DoubleConv(in_channels, out_channels)
61
+
62
+
63
+ def forward(self, x1, x2):
64
+ x1 = self.up(x1)
65
+ # input is CHW
66
+ diffY = x2.size()[2] - x1.size()[2]
67
+ diffX = x2.size()[3] - x1.size()[3]
68
+
69
+ x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
70
+ diffY // 2, diffY - diffY // 2])
71
+
72
+ x = torch.cat([x2, x1], dim=1)
73
+ return self.conv(x)
74
+
75
+
76
+ class OutConv(nn.Module):
77
+ def __init__(self, in_channels, out_channels):
78
+ super(OutConv, self).__init__()
79
+ self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
80
+
81
+ def forward(self, x):
82
+ return self.conv(x)
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ setuptools==66.0.0
2
+ datasets==2.11.0
3
+ numpy==1.24.2
4
+ tokenizers==0.13.3
5
+ transformers==4.27.4
6
+ xformers==0.0.16
7
+ accelerate==0.18.0
8
+ triton==2.0.0.post1
9
+ termcolor==2.3.0
10
+ tinydb
11
+ flask
12
+ -e git+https://github.com/JingyeChen/diffusers.git#egg=diffusers
13
+ opencv-python
test.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import os
2
+
3
+ os.system('wget https://layoutlm.blob.core.windows.net/textdiffuser/textdiffuser-ckpt.zip')
4
+ os.system('unzip textdiffuser-ckpt.zip')
5
+ os.system('finish')
test/app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import gradio as gr
3
+
4
+
5
+ def flip_text(x):
6
+ return x[::-1]
7
+
8
+
9
+ def flip_image(x):
10
+ return np.fliplr(x)
11
+
12
+
13
+ with gr.Blocks() as demo:
14
+ gr.Markdown("TextDiffuser.")
15
+ with gr.Tab("Text-to-Image"):
16
+ with gr.Row():
17
+ with gr.Column(scale=1):
18
+ text_input = gr.Textbox(label='Input your prompt here. Please enclose keywords with single quotes.')
19
+ slider_step = gr.Slider(minimum=1, maximum=1000, value=50, label="Sample Step", info="The sampling step for TextDiffuser ranging from [1,1000].")
20
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=2, label="Sample Size", info="Number of samples generated from TextDiffuser.")
21
+ slider_seed = gr.Slider(minimum=1, maximum=10000, label="Seed", info="The random seed for sampling.", randomize=True)
22
+ button = gr.Button("Generate")
23
+ with gr.Column(scale=1):
24
+ output = gr.Image()
25
+ button.click(flip_text, inputs=text_input, outputs=output)
26
+
27
+ with gr.Tab("Text-to-Image-with-Template"):
28
+ with gr.Row():
29
+ with gr.Column(scale=1):
30
+ text_input = gr.Textbox(label='Input your prompt here.')
31
+ template_image = gr.Image(label='Template image')
32
+ slider_step = gr.Slider(minimum=1, maximum=1000, value=50, label="Sample Step", info="The sampling step for TextDiffuser ranging from [1,1000].")
33
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=2, label="Sample Size", info="Number of samples generated from TextDiffuser.")
34
+ slider_seed = gr.Slider(minimum=1, maximum=10000, label="Seed", info="The random seed for sampling.", randomize=True)
35
+ button = gr.Button("Generate")
36
+ with gr.Column(scale=1):
37
+ output = gr.Image()
38
+ button.click(flip_text, inputs=text_input, outputs=output)
39
+
40
+ with gr.Tab("Text-Inpainting"):
41
+ with gr.Row():
42
+ with gr.Column(scale=1):
43
+ text_input = gr.Textbox(label='Input your prompt here.')
44
+ with gr.Row():
45
+ orig_image = gr.Image(label='Original image')
46
+ mask_image = gr.Image(label='Mask image')
47
+ slider_step = gr.Slider(minimum=1, maximum=1000, value=50, label="Sample Step", info="The sampling step for TextDiffuser ranging from [1,1000].")
48
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=2, label="Sample Size", info="Number of samples generated from TextDiffuser.")
49
+ slider_seed = gr.Slider(minimum=1, maximum=10000, label="Seed", info="The random seed for sampling.", randomize=True)
50
+ button = gr.Button("Generate")
51
+ with gr.Column(scale=1):
52
+ output = gr.Image()
53
+ button.click(flip_text, inputs=text_input, outputs=output)
54
+
55
+ demo.launch()
text-inpainting.sh ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ CUDA_VISIBLE_DEVICES=0 python inference.py \
2
+ --mode="text-inpainting" \
3
+ --resume_from_checkpoint="textdiffuser-ckpt/diffusion_backbone" \
4
+ --prompt="a boy draws good morning on a board" \
5
+ --original_image="assets/examples/text-inpainting/case2.jpg" \
6
+ --text_mask="assets/examples/text-inpainting/case2_mask.jpg" \
7
+ --output_dir="./output" \
8
+ --vis_num=4
text-to-image-with-template.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ CUDA_VISIBLE_DEVICES=0 python inference.py \
2
+ --mode="text-to-image-with-template" \
3
+ --resume_from_checkpoint="textdiffuser-ckpt/diffusion_backbone" \
4
+ --prompt="a poster of monkey music festival" \
5
+ --template_image="assets/examples/text-to-image-with-template/case2.jpg" \
6
+ --output_dir="./output" \
7
+ --vis_num=4
text-to-image.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ CUDA_VISIBLE_DEVICES=0 python inference.py \
2
+ --mode="text-to-image" \
3
+ --resume_from_checkpoint="textdiffuser-ckpt/diffusion_backbone" \
4
+ --prompt="A sign that says 'Hello'" \
5
+ --output_dir="./output" \
6
+ --vis_num=4
util.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------
2
+ # TextDiffuser: Diffusion Models as Text Painters
3
+ # Paper Link: https://arxiv.org/abs/2305.10855
4
+ # Code Link: https://github.com/microsoft/unilm/tree/master/textdiffuser
5
+ # Copyright (c) Microsoft Corporation.
6
+ # This file defines a set of commonly used utility functions.
7
+ # ------------------------------------------
8
+
9
+ import os
10
+ import re
11
+ import cv2
12
+ import math
13
+ import shutil
14
+ import string
15
+ import textwrap
16
+ import numpy as np
17
+ from PIL import Image, ImageFont, ImageDraw, ImageOps
18
+
19
+ from typing import *
20
+
21
+ # define alphabet and alphabet_dic
22
+ alphabet = string.digits + string.ascii_lowercase + string.ascii_uppercase + string.punctuation + ' ' # len(aphabet) = 95
23
+ alphabet_dic = {}
24
+ for index, c in enumerate(alphabet):
25
+ alphabet_dic[c] = index + 1 # the index 0 stands for non-character
26
+
27
+
28
+
29
+ def transform_mask_pil(mask_root):
30
+ """
31
+ This function extracts the mask area and text area from the images.
32
+
33
+ Args:
34
+ mask_root (str): The path of mask image.
35
+ * The white area is the unmasked area
36
+ * The gray area is the masked area
37
+ * The white area is the text area
38
+ """
39
+ img = np.array(mask_root)
40
+ img = cv2.resize(img, (512, 512), interpolation=cv2.INTER_NEAREST)
41
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
42
+ ret, binary = cv2.threshold(gray, 250, 255, cv2.THRESH_BINARY) # pixel value is set to 0 or 255 according to the threshold
43
+ return 1 - (binary.astype(np.float32) / 255)
44
+
45
+
46
+ def transform_mask(mask_root: str):
47
+ """
48
+ This function extracts the mask area and text area from the images.
49
+
50
+ Args:
51
+ mask_root (str): The path of mask image.
52
+ * The white area is the unmasked area
53
+ * The gray area is the masked area
54
+ * The white area is the text area
55
+ """
56
+ img = cv2.imread(mask_root)
57
+ img = cv2.resize(img, (512, 512), interpolation=cv2.INTER_NEAREST)
58
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
59
+ ret, binary = cv2.threshold(gray, 250, 255, cv2.THRESH_BINARY) # pixel value is set to 0 or 255 according to the threshold
60
+ return 1 - (binary.astype(np.float32) / 255)
61
+
62
+
63
+ def segmentation_mask_visualization(font_path: str, segmentation_mask: np.array):
64
+ """
65
+ This function visualizes the segmentaiton masks with characters.
66
+
67
+ Args:
68
+ font_path (str): The path of font. We recommand to use Arial.ttf
69
+ segmentation_mask (np.array): The character-level segmentation mask.
70
+ """
71
+ segmentation_mask = cv2.resize(segmentation_mask, (64, 64), interpolation=cv2.INTER_NEAREST)
72
+ font = ImageFont.truetype(font_path, 8)
73
+ blank = Image.new('RGB', (512,512), (0,0,0))
74
+ d = ImageDraw.Draw(blank)
75
+ for i in range(64):
76
+ for j in range(64):
77
+ if int(segmentation_mask[i][j]) == 0 or int(segmentation_mask[i][j])-1 >= len(alphabet):
78
+ continue
79
+ else:
80
+ d.text((j*8, i*8), alphabet[int(segmentation_mask[i][j])-1], font=font, fill=(0, 255, 0))
81
+ return blank
82
+
83
+
84
+ def make_caption_pil(font_path: str, captions: List[str]):
85
+ """
86
+ This function converts captions into pil images.
87
+
88
+ Args:
89
+ font_path (str): The path of font. We recommand to use Arial.ttf
90
+ captions (List[str]): List of captions.
91
+ """
92
+ caption_pil_list = []
93
+ font = ImageFont.truetype(font_path, 18)
94
+
95
+ for caption in captions:
96
+ border_size = 2
97
+ img = Image.new('RGB', (512-4,48-4), (255,255,255))
98
+ img = ImageOps.expand(img, border=(border_size, border_size, border_size, border_size), fill=(127, 127, 127))
99
+ draw = ImageDraw.Draw(img)
100
+ border_size = 2
101
+ text = caption
102
+ lines = textwrap.wrap(text, width=40)
103
+ x, y = 4, 4
104
+ line_height = font.getsize('A')[1] + 4
105
+
106
+ start = 0
107
+ for line in lines:
108
+ draw.text((x, y+start), line, font=font, fill=(200, 127, 0))
109
+ y += line_height
110
+
111
+ caption_pil_list.append(img)
112
+ return caption_pil_list
113
+
114
+
115
+ def filter_segmentation_mask(segmentation_mask: np.array):
116
+ """
117
+ This function removes some noisy predictions of segmentation masks.
118
+
119
+ Args:
120
+ segmentation_mask (np.array): The character-level segmentation mask.
121
+ """
122
+ segmentation_mask[segmentation_mask==alphabet_dic['-']] = 0
123
+ segmentation_mask[segmentation_mask==alphabet_dic[' ']] = 0
124
+ return segmentation_mask
125
+
126
+
127
+
128
+ def combine_image(args, sub_output_dir: str, pred_image_list: List, image_pil: Image, character_mask_pil: Image, character_mask_highlight_pil: Image, caption_pil_list: List):
129
+ """
130
+ This function combines all the outputs and useful inputs together.
131
+
132
+ Args:
133
+ args (argparse.ArgumentParser): The arguments.
134
+ pred_image_list (List): List of predicted images.
135
+ image_pil (Image): The original image.
136
+ character_mask_pil (Image): The character-level segmentation mask.
137
+ character_mask_highlight_pil (Image): The character-level segmentation mask highlighting character regions with green color.
138
+ caption_pil_list (List): List of captions.
139
+ """
140
+
141
+ size = len(pred_image_list)
142
+
143
+ if size == 1:
144
+ return pred_image_list[0]
145
+ elif size == 2:
146
+ blank = Image.new('RGB', (512*2, 512), (0,0,0))
147
+ blank.paste(pred_image_list[0],(0,0))
148
+ blank.paste(pred_image_list[1],(512,0))
149
+ elif size == 3:
150
+ blank = Image.new('RGB', (512*3, 512), (0,0,0))
151
+ blank.paste(pred_image_list[0],(0,0))
152
+ blank.paste(pred_image_list[1],(512,0))
153
+ blank.paste(pred_image_list[2],(1024,0))
154
+ elif size == 4:
155
+ blank = Image.new('RGB', (512*2, 512*2), (0,0,0))
156
+ blank.paste(pred_image_list[0],(0,0))
157
+ blank.paste(pred_image_list[1],(512,0))
158
+ blank.paste(pred_image_list[2],(0,512))
159
+ blank.paste(pred_image_list[3],(512,512))
160
+
161
+
162
+ return blank
163
+
164
+ def get_width(font_path, text):
165
+ """
166
+ This function calculates the width of the text.
167
+
168
+ Args:
169
+ font_path (str): user prompt.
170
+ text (str): user prompt.
171
+ """
172
+ font = ImageFont.truetype(font_path, 24)
173
+ width, _ = font.getsize(text)
174
+ return width
175
+
176
+
177
+
178
+ def get_key_words(text: str):
179
+ """
180
+ This function detect keywords (enclosed by quotes) from user prompts. The keywords are used to guide the layout generation.
181
+
182
+ Args:
183
+ text (str): user prompt.
184
+ """
185
+
186
+ words = []
187
+ text = text
188
+ matches = re.findall(r"'(.*?)'", text) # find the keywords enclosed by ''
189
+ if matches:
190
+ for match in matches:
191
+ words.extend(match.split())
192
+
193
+ if len(words) >= 8:
194
+ return []
195
+
196
+ return words
197
+
198
+
199
+ def adjust_overlap_box(box_output, current_index):
200
+ """
201
+ This function adjust the overlapping boxes.
202
+
203
+ Args:
204
+ box_output (List): List of predicted boxes.
205
+ current_index (int): the index of current box.
206
+ """
207
+
208
+ if current_index == 0:
209
+ return box_output
210
+ else:
211
+ # judge whether it contains overlap with the last output
212
+ last_box = box_output[0, current_index-1, :]
213
+ xmin_last, ymin_last, xmax_last, ymax_last = last_box
214
+
215
+ current_box = box_output[0, current_index, :]
216
+ xmin, ymin, xmax, ymax = current_box
217
+
218
+ if xmin_last <= xmin <= xmax_last and ymin_last <= ymin <= ymax_last:
219
+ print('adjust overlapping')
220
+ distance_x = xmax_last - xmin
221
+ distance_y = ymax_last - ymin
222
+ if distance_x <= distance_y:
223
+ # avoid overlap
224
+ new_x_min = xmax_last + 0.025
225
+ new_x_max = xmax - xmin + xmax_last + 0.025
226
+ box_output[0,current_index,0] = new_x_min
227
+ box_output[0,current_index,2] = new_x_max
228
+ else:
229
+ new_y_min = ymax_last + 0.025
230
+ new_y_max = ymax - ymin + ymax_last + 0.025
231
+ box_output[0,current_index,1] = new_y_min
232
+ box_output[0,current_index,3] = new_y_max
233
+
234
+ elif xmin_last <= xmin <= xmax_last and ymin_last <= ymax <= ymax_last:
235
+ print('adjust overlapping')
236
+ new_x_min = xmax_last + 0.05
237
+ new_x_max = xmax - xmin + xmax_last + 0.05
238
+ box_output[0,current_index,0] = new_x_min
239
+ box_output[0,current_index,2] = new_x_max
240
+
241
+ return box_output
242
+
243
+
244
+ def shrink_box(box, scale_factor = 0.9):
245
+ """
246
+ This function shrinks the box.
247
+
248
+ Args:
249
+ box (List): List of predicted boxes.
250
+ scale_factor (float): The scale factor of shrinking.
251
+ """
252
+
253
+ x1, y1, x2, y2 = box
254
+ x1_new = x1 + (x2 - x1) * (1 - scale_factor) / 2
255
+ y1_new = y1 + (y2 - y1) * (1 - scale_factor) / 2
256
+ x2_new = x2 - (x2 - x1) * (1 - scale_factor) / 2
257
+ y2_new = y2 - (y2 - y1) * (1 - scale_factor) / 2
258
+ return (x1_new, y1_new, x2_new, y2_new)
259
+
260
+
261
+ def adjust_font_size(args, width, height, draw, text):
262
+ """
263
+ This function adjusts the font size.
264
+
265
+ Args:
266
+ args (argparse.ArgumentParser): The arguments.
267
+ width (int): The width of the text.
268
+ height (int): The height of the text.
269
+ draw (ImageDraw): The ImageDraw object.
270
+ text (str): The text.
271
+ """
272
+
273
+ size_start = height
274
+ while True:
275
+ font = ImageFont.truetype(args.font_path, size_start)
276
+ text_width, _ = draw.textsize(text, font=font)
277
+ if text_width >= width:
278
+ size_start = size_start - 1
279
+ else:
280
+ return size_start
281
+
282
+
283
+ def inpainting_merge_image(original_image, mask_image, inpainting_image):
284
+ """
285
+ This function merges the original image, mask image and inpainting image.
286
+
287
+ Args:
288
+ original_image (PIL.Image): The original image.
289
+ mask_image (PIL.Image): The mask images.
290
+ inpainting_image (PIL.Image): The inpainting images.
291
+ """
292
+
293
+ original_image = original_image.resize((512, 512))
294
+ mask_image = mask_image.resize((512, 512))
295
+ inpainting_image = inpainting_image.resize((512, 512))
296
+ mask_image.convert('L')
297
+ threshold = 250
298
+ table = []
299
+ for i in range(256):
300
+ if i < threshold:
301
+ table.append(1)
302
+ else:
303
+ table.append(0)
304
+ mask_image = mask_image.point(table, "1")
305
+ merged_image = Image.composite(inpainting_image, original_image, mask_image)
306
+ return merged_image