imjunaidafzal JingyeChen22 commited on
Commit
bb90efe
0 Parent(s):

Duplicate from JingyeChen22/TextDiffuser

Browse files

Co-authored-by: JingyeChen22 <[email protected]>

.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
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 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ---
2
+ sdk: gradio
3
+ app_file: app.py
4
+ pinned: false
5
+ duplicated_from: JingyeChen22/TextDiffuser
6
+ ---
app.py ADDED
@@ -0,0 +1,1067 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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://huggingface.co/datasets/JingyeChen22/TextDiffuser/resolve/main/textdiffuser-ckpt.zip')
15
+ with zipfile.ZipFile('textdiffuser-ckpt.zip', 'r') as zip_ref:
16
+ zip_ref.extractall('.')
17
+
18
+ if not os.path.exists('images'):
19
+ os.system('wget https://huggingface.co/datasets/JingyeChen22/TextDiffuser/resolve/main/images.zip')
20
+ with zipfile.ZipFile('images.zip', 'r') as zip_ref:
21
+ zip_ref.extractall('.')
22
+
23
+ os.system('wget https://huggingface.co/datasets/JingyeChen22/TextDiffuser/resolve/main/404.jpg')
24
+
25
+
26
+ if not os.path.exists('Arial.ttf'):
27
+ os.system('wget https://huggingface.co/datasets/JingyeChen22/TextDiffuser/resolve/main/Arial.ttf')
28
+
29
+ import cv2
30
+ import random
31
+ import logging
32
+ import argparse
33
+ import numpy as np
34
+
35
+ from pathlib import Path
36
+ from tqdm.auto import tqdm
37
+ from typing import Optional
38
+ from packaging import version
39
+ from termcolor import colored
40
+ from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageEnhance # import for visualization
41
+ from huggingface_hub import HfFolder, Repository, create_repo, whoami
42
+
43
+ import datasets
44
+ from datasets import load_dataset
45
+ from datasets import disable_caching
46
+
47
+ import torch
48
+ import torch.utils.checkpoint
49
+ import torch.nn.functional as F
50
+
51
+ import accelerate
52
+ from accelerate import Accelerator
53
+ from accelerate.logging import get_logger
54
+ from accelerate.utils import ProjectConfiguration, set_seed
55
+
56
+ import diffusers
57
+ from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
58
+ from diffusers.optimization import get_scheduler
59
+ from diffusers.training_utils import EMAModel
60
+ from diffusers.utils import check_min_version, deprecate
61
+ from diffusers.utils.import_utils import is_xformers_available
62
+
63
+ import transformers
64
+ from transformers import CLIPTextModel, CLIPTokenizer
65
+
66
+ from util import segmentation_mask_visualization, make_caption_pil, combine_image, transform_mask_pil, filter_segmentation_mask, inpainting_merge_image
67
+ from model.layout_generator import get_layout_from_prompt
68
+ from model.text_segmenter.unet import UNet
69
+
70
+
71
+ disable_caching()
72
+ check_min_version("0.15.0.dev0")
73
+ logger = get_logger(__name__, log_level="INFO")
74
+
75
+
76
+ def parse_args():
77
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
78
+ parser.add_argument(
79
+ "--pretrained_model_name_or_path",
80
+ type=str,
81
+ default='runwayml/stable-diffusion-v1-5', # no need to modify this
82
+ help="Path to pretrained model or model identifier from huggingface.co/models. Please do not modify this.",
83
+ )
84
+ parser.add_argument(
85
+ "--revision",
86
+ type=str,
87
+ default=None,
88
+ required=False,
89
+ help="Revision of pretrained model identifier from huggingface.co/models.",
90
+ )
91
+ parser.add_argument(
92
+ "--mode",
93
+ type=str,
94
+ default="text-to-image",
95
+ # required=True,
96
+ choices=["text-to-image", "text-to-image-with-template", "text-inpainting"],
97
+ help="Three modes can be used.",
98
+ )
99
+ parser.add_argument(
100
+ "--prompt",
101
+ type=str,
102
+ default="",
103
+ # required=True,
104
+ help="The text prompts provided by users.",
105
+ )
106
+ parser.add_argument(
107
+ "--template_image",
108
+ type=str,
109
+ default="",
110
+ help="The template image should be given when using 【text-to-image-with-template】 mode.",
111
+ )
112
+ parser.add_argument(
113
+ "--original_image",
114
+ type=str,
115
+ default="",
116
+ help="The original image should be given when using 【text-inpainting】 mode.",
117
+ )
118
+ parser.add_argument(
119
+ "--text_mask",
120
+ type=str,
121
+ default="",
122
+ help="The text mask should be given when using 【text-inpainting】 mode.",
123
+ )
124
+ parser.add_argument(
125
+ "--output_dir",
126
+ type=str,
127
+ default="output",
128
+ help="The output directory where the model predictions and checkpoints will be written.",
129
+ )
130
+ parser.add_argument(
131
+ "--cache_dir",
132
+ type=str,
133
+ default=None,
134
+ help="The directory where the downloaded models and datasets will be stored.",
135
+ )
136
+ parser.add_argument(
137
+ "--seed",
138
+ type=int,
139
+ default=None,
140
+ help="A seed for reproducible training."
141
+ )
142
+ parser.add_argument(
143
+ "--resolution",
144
+ type=int,
145
+ default=512,
146
+ help=(
147
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
148
+ " resolution"
149
+ ),
150
+ )
151
+ parser.add_argument(
152
+ "--classifier_free_scale",
153
+ type=float,
154
+ default=7.5, # following stable diffusion (https://github.com/CompVis/stable-diffusion)
155
+ help="Classifier free scale following https://arxiv.org/abs/2207.12598.",
156
+ )
157
+ parser.add_argument(
158
+ "--drop_caption",
159
+ action="store_true",
160
+ help="Whether to drop captions during training following https://arxiv.org/abs/2207.12598.."
161
+ )
162
+ parser.add_argument(
163
+ "--dataloader_num_workers",
164
+ type=int,
165
+ default=0,
166
+ help="Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
167
+ )
168
+ parser.add_argument(
169
+ "--push_to_hub",
170
+ action="store_true",
171
+ help="Whether or not to push the model to the Hub."
172
+ )
173
+ parser.add_argument(
174
+ "--hub_token",
175
+ type=str,
176
+ default=None,
177
+ help="The token to use to push to the Model Hub."
178
+ )
179
+ parser.add_argument(
180
+ "--hub_model_id",
181
+ type=str,
182
+ default=None,
183
+ help="The name of the repository to keep in sync with the local `output_dir`.",
184
+ )
185
+ parser.add_argument(
186
+ "--logging_dir",
187
+ type=str,
188
+ default="logs",
189
+ help=(
190
+ "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
191
+ " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
192
+ ),
193
+ )
194
+ parser.add_argument(
195
+ "--mixed_precision",
196
+ type=str,
197
+ default='fp16',
198
+ choices=["no", "fp16", "bf16"],
199
+ help=(
200
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
201
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
202
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
203
+ ),
204
+ )
205
+ parser.add_argument(
206
+ "--report_to",
207
+ type=str,
208
+ default="tensorboard",
209
+ help=(
210
+ 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
211
+ ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
212
+ ),
213
+ )
214
+ parser.add_argument(
215
+ "--local_rank",
216
+ type=int,
217
+ default=-1,
218
+ help="For distributed training: local_rank"
219
+ )
220
+ parser.add_argument(
221
+ "--checkpointing_steps",
222
+ type=int,
223
+ default=500,
224
+ help=(
225
+ "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
226
+ " training using `--resume_from_checkpoint`."
227
+ ),
228
+ )
229
+ parser.add_argument(
230
+ "--checkpoints_total_limit",
231
+ type=int,
232
+ default=5,
233
+ help=(
234
+ "Max number of checkpoints to store. Passed as `total_limit` to the `Accelerator` `ProjectConfiguration`."
235
+ " See Accelerator::save_state https://huggingface.co/docs/accelerate/package_reference/accelerator#accelerate.Accelerator.save_state"
236
+ " for more docs"
237
+ ),
238
+ )
239
+ parser.add_argument(
240
+ "--resume_from_checkpoint",
241
+ type=str,
242
+ default='textdiffuser-ckpt/diffusion_backbone', # should be specified during inference
243
+ help=(
244
+ "Whether training should be resumed from a previous checkpoint. Use a path saved by"
245
+ ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
246
+ ),
247
+ )
248
+ parser.add_argument(
249
+ "--enable_xformers_memory_efficient_attention",
250
+ action="store_true",
251
+ help="Whether or not to use xformers."
252
+ )
253
+ parser.add_argument(
254
+ "--font_path",
255
+ type=str,
256
+ default='Arial.ttf',
257
+ help="The path of font for visualization."
258
+ )
259
+ parser.add_argument(
260
+ "--sample_steps",
261
+ type=int,
262
+ default=50, # following stable diffusion (https://github.com/CompVis/stable-diffusion)
263
+ help="Diffusion steps for sampling."
264
+ )
265
+ parser.add_argument(
266
+ "--vis_num",
267
+ type=int,
268
+ default=4, # please decreases the number if out-of-memory error occurs
269
+ help="Number of images to be sample. Please decrease it when encountering out of memory error."
270
+ )
271
+ parser.add_argument(
272
+ "--binarization",
273
+ action="store_true",
274
+ help="Whether to binarize the template image."
275
+ )
276
+ parser.add_argument(
277
+ "--use_pillow_segmentation_mask",
278
+ type=bool,
279
+ default=True,
280
+ help="In the 【text-to-image】 mode, please specify whether to use the segmentation masks provided by PILLOW"
281
+ )
282
+ parser.add_argument(
283
+ "--character_segmenter_path",
284
+ type=str,
285
+ default='textdiffuser-ckpt/text_segmenter.pth',
286
+ help="checkpoint of character-level segmenter"
287
+ )
288
+ args = parser.parse_args()
289
+
290
+ print(f'{colored("[√]", "green")} Arguments are loaded.')
291
+ print(args)
292
+
293
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
294
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
295
+ args.local_rank = env_local_rank
296
+
297
+ return args
298
+
299
+
300
+
301
+ def get_full_repo_name(model_id: str, organization: Optional[str] = None, token: Optional[str] = None):
302
+ if token is None:
303
+ token = HfFolder.get_token()
304
+ if organization is None:
305
+ username = whoami(token)["name"]
306
+ return f"{username}/{model_id}"
307
+ else:
308
+ return f"{organization}/{model_id}"
309
+
310
+
311
+
312
+ args = parse_args()
313
+ logging_dir = os.path.join(args.output_dir, args.logging_dir)
314
+
315
+ print(f'{colored("[√]", "green")} Logging dir is set to {logging_dir}.')
316
+
317
+ accelerator_project_config = ProjectConfiguration(total_limit=args.checkpoints_total_limit)
318
+
319
+ accelerator = Accelerator(
320
+ gradient_accumulation_steps=1,
321
+ mixed_precision=args.mixed_precision,
322
+ log_with=args.report_to,
323
+ logging_dir=logging_dir,
324
+ project_config=accelerator_project_config,
325
+ )
326
+
327
+ # Make one log on every process with the configuration for debugging.
328
+ logging.basicConfig(
329
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
330
+ datefmt="%m/%d/%Y %H:%M:%S",
331
+ level=logging.INFO,
332
+ )
333
+ logger.info(accelerator.state, main_process_only=False)
334
+ if accelerator.is_local_main_process:
335
+ datasets.utils.logging.set_verbosity_warning()
336
+ transformers.utils.logging.set_verbosity_warning()
337
+ diffusers.utils.logging.set_verbosity_info()
338
+ else:
339
+ datasets.utils.logging.set_verbosity_error()
340
+ transformers.utils.logging.set_verbosity_error()
341
+ diffusers.utils.logging.set_verbosity_error()
342
+
343
+ # Handle the repository creation
344
+ if accelerator.is_main_process:
345
+ if args.push_to_hub:
346
+ if args.hub_model_id is None:
347
+ repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token)
348
+ else:
349
+ repo_name = args.hub_model_id
350
+ create_repo(repo_name, exist_ok=True, token=args.hub_token)
351
+ repo = Repository(args.output_dir, clone_from=repo_name, token=args.hub_token)
352
+
353
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
354
+ if "step_*" not in gitignore:
355
+ gitignore.write("step_*\n")
356
+ if "epoch_*" not in gitignore:
357
+ gitignore.write("epoch_*\n")
358
+ elif args.output_dir is not None:
359
+ os.makedirs(args.output_dir, exist_ok=True)
360
+ print(args.output_dir)
361
+
362
+ # Load scheduler, tokenizer and models.
363
+ tokenizer15 = CLIPTokenizer.from_pretrained(
364
+ 'runwayml/stable-diffusion-v1-5', subfolder="tokenizer", revision=args.revision
365
+ )
366
+ tokenizer21 = CLIPTokenizer.from_pretrained(
367
+ 'stabilityai/stable-diffusion-2-1', subfolder="tokenizer", revision=args.revision
368
+ )
369
+
370
+ text_encoder15 = CLIPTextModel.from_pretrained(
371
+ 'runwayml/stable-diffusion-v1-5', subfolder="text_encoder", revision=args.revision
372
+ )
373
+ text_encoder21 = CLIPTextModel.from_pretrained(
374
+ 'stabilityai/stable-diffusion-2-1', subfolder="text_encoder", revision=args.revision
375
+ )
376
+
377
+ vae15 = AutoencoderKL.from_pretrained('runwayml/stable-diffusion-v1-5', subfolder="vae", revision=args.revision).cuda()
378
+ unet15 = UNet2DConditionModel.from_pretrained(
379
+ './textdiffuser-ckpt/diffusion_backbone_1.5', subfolder="unet", revision=None
380
+ ).cuda()
381
+
382
+ vae21 = AutoencoderKL.from_pretrained('stabilityai/stable-diffusion-2-1', subfolder="vae", revision=args.revision).cuda()
383
+ unet21 = UNet2DConditionModel.from_pretrained(
384
+ './textdiffuser-ckpt/diffusion_backbone_2.1', subfolder="unet", revision=None
385
+ ).cuda()
386
+
387
+ scheduler15 = DDPMScheduler.from_pretrained('runwayml/stable-diffusion-v1-5', subfolder="scheduler")
388
+ scheduler21 = DDPMScheduler.from_pretrained('stabilityai/stable-diffusion-2-1', subfolder="scheduler")
389
+
390
+
391
+
392
+ # Freeze vae and text_encoder
393
+ vae15.requires_grad_(False)
394
+ vae21.requires_grad_(False)
395
+ text_encoder15.requires_grad_(False)
396
+ text_encoder21.requires_grad_(False)
397
+
398
+ if args.enable_xformers_memory_efficient_attention:
399
+ if is_xformers_available():
400
+ import xformers
401
+
402
+ xformers_version = version.parse(xformers.__version__)
403
+ if xformers_version == version.parse("0.0.16"):
404
+ logger.warn(
405
+ "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."
406
+ )
407
+ unet.enable_xformers_memory_efficient_attention()
408
+ else:
409
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
410
+
411
+ # `accelerate` 0.16.0 will have better support for customized saving
412
+ if version.parse(accelerate.__version__) >= version.parse("0.16.0"):
413
+ # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format
414
+ def save_model_hook(models, weights, output_dir):
415
+
416
+ for i, model in enumerate(models):
417
+ model.save_pretrained(os.path.join(output_dir, "unet"))
418
+
419
+ # make sure to pop weight so that corresponding model is not saved again
420
+ weights.pop()
421
+
422
+ def load_model_hook(models, input_dir):
423
+
424
+ for i in range(len(models)):
425
+ # pop models so that they are not loaded again
426
+ model = models.pop()
427
+
428
+ # load diffusers style into model
429
+ load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet")
430
+ model.register_to_config(**load_model.config)
431
+
432
+ model.load_state_dict(load_model.state_dict())
433
+ del load_model
434
+
435
+ accelerator.register_save_state_pre_hook(save_model_hook)
436
+ accelerator.register_load_state_pre_hook(load_model_hook)
437
+
438
+
439
+ # setup schedulers
440
+ # sample_num = args.vis_num
441
+
442
+ def to_tensor(image):
443
+ if isinstance(image, Image.Image):
444
+ image = np.array(image)
445
+ elif not isinstance(image, np.ndarray):
446
+ raise TypeError("Error")
447
+
448
+ image = image.astype(np.float32) / 255.0
449
+ image = np.transpose(image, (2, 0, 1))
450
+ tensor = torch.from_numpy(image)
451
+
452
+ return tensor
453
+
454
+
455
+ import unicodedata
456
+
457
+
458
+ def full2half(text):
459
+ half = []
460
+ for char in text:
461
+ code = ord(char)
462
+ if code == 0x3000:
463
+ half.append(chr(0x0020))
464
+ elif 0xFF01 <= code <= 0xFF5E:
465
+ half.append(chr(code - 0xFEE0))
466
+ else:
467
+ half.append(char)
468
+ return ''.join(half)
469
+
470
+ def has_chinese_char(string):
471
+ pattern = re.compile('[\u4e00-\u9fa5]')
472
+ if pattern.search(string):
473
+ return True
474
+ else:
475
+ return False
476
+
477
+ image_404 = Image.open('404.jpg')
478
+
479
+ def text_to_image(prompt,slider_step,slider_guidance,slider_batch, version):
480
+ print(f'【version】{version}')
481
+ if version == 'Stable Diffusion v2.1':
482
+ vae = vae21
483
+ unet = unet21
484
+ text_encoder = text_encoder21
485
+ tokenizer = tokenizer21
486
+ scheduler = scheduler21
487
+ slider_batch = min(slider_batch, 1)
488
+ size = 768
489
+ elif version == 'Stable Diffusion v1.5':
490
+ vae = vae15
491
+ unet = unet15
492
+ text_encoder = text_encoder15
493
+ tokenizer = tokenizer15
494
+ scheduler = scheduler15
495
+ size = 512
496
+ else:
497
+ assert False, 'Version Not Found'
498
+
499
+ if has_chinese_char(prompt):
500
+ print('trigger')
501
+ return image_404, None
502
+
503
+ prompt = full2half(prompt)
504
+ prompt = prompt.replace('"', "'")
505
+ prompt = prompt.replace('‘', "'")
506
+ prompt = prompt.replace('’', "'")
507
+ prompt = prompt.replace('“', "'")
508
+ prompt = prompt.replace('”', "'")
509
+ prompt = re.sub(r"[^a-zA-Z0-9'\" ]+", "", prompt)
510
+
511
+ if slider_step>=50:
512
+ slider_step = 50
513
+
514
+ args.prompt = prompt
515
+ sample_num = slider_batch
516
+ seed = random.randint(0, 10000000)
517
+ set_seed(seed)
518
+ scheduler.set_timesteps(slider_step)
519
+
520
+ noise = torch.randn((sample_num, 4, size//8, size//8)).to("cuda") # (b, 4, 64, 64)
521
+ input = noise # (b, 4, 64, 64)
522
+
523
+ captions = [args.prompt] * sample_num
524
+ captions_nocond = [""] * sample_num
525
+ print(f'{colored("[√]", "green")} Prompt is loaded: {args.prompt}.')
526
+
527
+ # encode text prompts
528
+ inputs = tokenizer(
529
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
530
+ ).input_ids # (b, 77)
531
+ encoder_hidden_states = text_encoder(inputs)[0].cuda() # (b, 77, 768)
532
+ print(f'{colored("[√]", "green")} encoder_hidden_states: {encoder_hidden_states.shape}.')
533
+
534
+ inputs_nocond = tokenizer(
535
+ captions_nocond, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
536
+ ).input_ids # (b, 77)
537
+ encoder_hidden_states_nocond = text_encoder(inputs_nocond)[0].cuda() # (b, 77, 768)
538
+ print(f'{colored("[√]", "green")} encoder_hidden_states_nocond: {encoder_hidden_states_nocond.shape}.')
539
+
540
+ #### text-to-image ####
541
+ render_image, segmentation_mask_from_pillow = get_layout_from_prompt(args)
542
+
543
+ segmentation_mask = torch.Tensor(np.array(segmentation_mask_from_pillow)).cuda() # (512, 512)
544
+
545
+ segmentation_mask = filter_segmentation_mask(segmentation_mask)
546
+ segmentation_mask = torch.nn.functional.interpolate(segmentation_mask.unsqueeze(0).unsqueeze(0).float(), size=(size//2, size//2), mode='nearest')
547
+ segmentation_mask = segmentation_mask.squeeze(1).repeat(sample_num, 1, 1).long().to('cuda') # (1, 1, 256, 256)
548
+ print(f'{colored("[√]", "green")} character-level segmentation_mask: {segmentation_mask.shape}.')
549
+
550
+ feature_mask = torch.ones(sample_num, 1, size//8, size//8).to('cuda') # (b, 1, 64, 64)
551
+ masked_image = torch.zeros(sample_num, 3, size, size).to('cuda') # (b, 3, 512, 512)
552
+ masked_feature = vae.encode(masked_image).latent_dist.sample() # (b, 4, 64, 64)
553
+ masked_feature = masked_feature * vae.config.scaling_factor
554
+ print(f'{colored("[√]", "green")} feature_mask: {feature_mask.shape}.')
555
+ print(f'{colored("[√]", "green")} masked_feature: {masked_feature.shape}.')
556
+
557
+ # diffusion process
558
+ intermediate_images = []
559
+ for t in tqdm(scheduler.timesteps):
560
+ with torch.no_grad():
561
+ 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
562
+ 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
563
+ noisy_residual = noise_pred_uncond + slider_guidance * (noise_pred_cond - noise_pred_uncond) # b, 4, 64, 64
564
+ prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
565
+ input = prev_noisy_sample
566
+ intermediate_images.append(prev_noisy_sample)
567
+
568
+ # decode and visualization
569
+ input = 1 / vae.config.scaling_factor * input
570
+ sample_images = vae.decode(input.float(), return_dict=False)[0] # (b, 3, 512, 512)
571
+
572
+ image_pil = render_image.resize((size,size))
573
+ segmentation_mask = segmentation_mask[0].squeeze().cpu().numpy()
574
+ character_mask_pil = Image.fromarray(((segmentation_mask!=0)*255).astype('uint8')).resize((size,size))
575
+ character_mask_highlight_pil = segmentation_mask_visualization(args.font_path,segmentation_mask)
576
+ character_mask_highlight_pil = character_mask_highlight_pil.resize((size, size))
577
+ caption_pil = make_caption_pil(args.font_path, captions)
578
+
579
+ # save pred_img
580
+ pred_image_list = []
581
+ for image in sample_images.float():
582
+ image = (image / 2 + 0.5).clamp(0, 1).unsqueeze(0)
583
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
584
+ image = Image.fromarray((image * 255).round().astype("uint8")).convert('RGB')
585
+ pred_image_list.append(image)
586
+
587
+ blank_pil = combine_image(args, size, None, pred_image_list, image_pil, character_mask_pil, character_mask_highlight_pil, caption_pil)
588
+
589
+ intermediate_result = Image.new('RGB', (size*3, size))
590
+ intermediate_result.paste(image_pil, (0, 0))
591
+ intermediate_result.paste(character_mask_pil, (size, 0))
592
+ intermediate_result.paste(character_mask_highlight_pil, (size*2, 0))
593
+
594
+ return blank_pil, intermediate_result
595
+
596
+
597
+ # load character-level segmenter
598
+ segmenter = UNet(3, 96, True).cuda()
599
+ segmenter = torch.nn.DataParallel(segmenter)
600
+ segmenter.load_state_dict(torch.load(args.character_segmenter_path))
601
+ segmenter.eval()
602
+ print(f'{colored("[√]", "green")} Text segmenter is successfully loaded.')
603
+
604
+
605
+
606
+
607
+ def text_to_image_with_template(prompt,template_image,slider_step,slider_guidance,slider_batch, binary, version):
608
+
609
+ if version == 'Stable Diffusion v2.1':
610
+ vae = vae21
611
+ unet = unet21
612
+ text_encoder = text_encoder21
613
+ tokenizer = tokenizer21
614
+ scheduler = scheduler21
615
+ slider_batch = min(slider_batch, 1)
616
+ size = 768
617
+ elif version == 'Stable Diffusion v1.5':
618
+ vae = vae15
619
+ unet = unet15
620
+ text_encoder = text_encoder15
621
+ tokenizer = tokenizer15
622
+ scheduler = scheduler15
623
+ size = 512
624
+ else:
625
+ assert False, 'Version Not Found'
626
+
627
+ if has_chinese_char(prompt):
628
+ print('trigger')
629
+ return image_404, None
630
+
631
+ if slider_step>=50:
632
+ slider_step = 50
633
+
634
+ orig_template_image = template_image.resize((size,size)).convert('RGB')
635
+ args.prompt = prompt
636
+ sample_num = slider_batch
637
+ # If passed along, set the training seed now.
638
+ # seed = slider_seed
639
+ seed = random.randint(0, 10000000)
640
+ set_seed(seed)
641
+ scheduler.set_timesteps(slider_step)
642
+
643
+ noise = torch.randn((sample_num, 4, size//8, size//8)).to("cuda") # (b, 4, 64, 64)
644
+ input = noise # (b, 4, 64, 64)
645
+
646
+ captions = [args.prompt] * sample_num
647
+ captions_nocond = [""] * sample_num
648
+ print(f'{colored("[√]", "green")} Prompt is loaded: {args.prompt}.')
649
+
650
+ # encode text prompts
651
+ inputs = tokenizer(
652
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
653
+ ).input_ids # (b, 77)
654
+ encoder_hidden_states = text_encoder(inputs)[0].cuda() # (b, 77, 768)
655
+ print(f'{colored("[√]", "green")} encoder_hidden_states: {encoder_hidden_states.shape}.')
656
+
657
+ inputs_nocond = tokenizer(
658
+ captions_nocond, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
659
+ ).input_ids # (b, 77)
660
+ encoder_hidden_states_nocond = text_encoder(inputs_nocond)[0].cuda() # (b, 77, 768)
661
+ print(f'{colored("[√]", "green")} encoder_hidden_states_nocond: {encoder_hidden_states_nocond.shape}.')
662
+
663
+ #### text-to-image-with-template ####
664
+ template_image = template_image.resize((256,256)).convert('RGB')
665
+
666
+ # whether binarization is needed
667
+ print(f'{colored("[Warning]", "red")} args.binarization is set to {binary}. You may need it when using handwritten images as templates.')
668
+
669
+ if binary:
670
+ gray = ImageOps.grayscale(template_image)
671
+ binary = gray.point(lambda x: 255 if x > 96 else 0, '1')
672
+ template_image = binary.convert('RGB')
673
+
674
+ # to_tensor = transforms.ToTensor()
675
+ image_tensor = to_tensor(template_image).unsqueeze(0).cuda().sub_(0.5).div_(0.5) # (b, 3, 256, 256)
676
+
677
+ with torch.no_grad():
678
+ segmentation_mask = segmenter(image_tensor) # (b, 96, 256, 256)
679
+ segmentation_mask = segmentation_mask.max(1)[1].squeeze(0) # (256, 256)
680
+ segmentation_mask = filter_segmentation_mask(segmentation_mask) # (256, 256)
681
+
682
+ segmentation_mask = torch.nn.functional.interpolate(segmentation_mask.unsqueeze(0).unsqueeze(0).float(), size=(size//2, size//2), mode='nearest') # (b, 1, 256, 256)
683
+ segmentation_mask = segmentation_mask.squeeze(1).repeat(sample_num, 1, 1).long().to('cuda') # (b, 1, 256, 256)
684
+ print(f'{colored("[√]", "green")} Character-level segmentation_mask: {segmentation_mask.shape}.')
685
+
686
+ feature_mask = torch.ones(sample_num, 1, size//8, size//8).to('cuda') # (b, 1, 64, 64)
687
+ masked_image = torch.zeros(sample_num, 3, size, size).to('cuda') # (b, 3, 512, 512)
688
+ masked_feature = vae.encode(masked_image).latent_dist.sample() # (b, 4, 64, 64)
689
+ masked_feature = masked_feature * vae.config.scaling_factor # (b, 4, 64, 64)
690
+
691
+ # diffusion process
692
+ intermediate_images = []
693
+ for t in tqdm(scheduler.timesteps):
694
+ with torch.no_grad():
695
+ 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
696
+ 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
697
+ noisy_residual = noise_pred_uncond + slider_guidance * (noise_pred_cond - noise_pred_uncond) # b, 4, 64, 64
698
+ prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
699
+ input = prev_noisy_sample
700
+ intermediate_images.append(prev_noisy_sample)
701
+
702
+ # decode and visualization
703
+ input = 1 / vae.config.scaling_factor * input
704
+ sample_images = vae.decode(input.float(), return_dict=False)[0] # (b, 3, 512, 512)
705
+
706
+ image_pil = None
707
+ segmentation_mask = segmentation_mask[0].squeeze().cpu().numpy()
708
+ character_mask_pil = Image.fromarray(((segmentation_mask!=0)*255).astype('uint8')).resize((size,size))
709
+ character_mask_highlight_pil = segmentation_mask_visualization(args.font_path,segmentation_mask)
710
+ character_mask_highlight_pil = character_mask_highlight_pil.resize((size, size))
711
+ caption_pil = make_caption_pil(args.font_path, captions)
712
+
713
+ # save pred_img
714
+ pred_image_list = []
715
+ for image in sample_images.float():
716
+ image = (image / 2 + 0.5).clamp(0, 1).unsqueeze(0)
717
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
718
+ image = Image.fromarray((image * 255).round().astype("uint8")).convert('RGB')
719
+ pred_image_list.append(image)
720
+
721
+ blank_pil = combine_image(args, size, None, pred_image_list, image_pil, character_mask_pil, character_mask_highlight_pil, caption_pil)
722
+
723
+ intermediate_result = Image.new('RGB', (size*3, size))
724
+ intermediate_result.paste(orig_template_image, (0, 0))
725
+ intermediate_result.paste(character_mask_pil, (size, 0))
726
+ intermediate_result.paste(character_mask_highlight_pil, (size*2, 0))
727
+
728
+ return blank_pil, intermediate_result
729
+
730
+
731
+ def text_inpainting(prompt,orig_image,mask_image,slider_step,slider_guidance,slider_batch, version):
732
+
733
+ if version == 'Stable Diffusion v2.1':
734
+ vae = vae21
735
+ unet = unet21
736
+ text_encoder = text_encoder21
737
+ tokenizer = tokenizer21
738
+ scheduler = scheduler21
739
+ slider_batch = min(slider_batch, 1)
740
+ size = 768
741
+ elif version == 'Stable Diffusion v1.5':
742
+ vae = vae15
743
+ unet = unet15
744
+ text_encoder = text_encoder15
745
+ tokenizer = tokenizer15
746
+ scheduler = scheduler15
747
+ size = 512
748
+ else:
749
+ assert False, 'Version Not Found'
750
+
751
+ if has_chinese_char(prompt):
752
+ print('trigger')
753
+ return image_404, None
754
+
755
+ if slider_step>=50:
756
+ slider_step = 50
757
+
758
+ args.prompt = prompt
759
+ sample_num = slider_batch
760
+ # If passed along, set the training seed now.
761
+ # seed = slider_seed
762
+ seed = random.randint(0, 10000000)
763
+ set_seed(seed)
764
+ scheduler.set_timesteps(slider_step)
765
+
766
+ noise = torch.randn((sample_num, 4, size//8, size//8)).to("cuda") # (b, 4, 64, 64)
767
+ input = noise # (b, 4, 64, 64)
768
+
769
+ captions = [args.prompt] * sample_num
770
+ captions_nocond = [""] * sample_num
771
+ print(f'{colored("[√]", "green")} Prompt is loaded: {args.prompt}.')
772
+
773
+ # encode text prompts
774
+ inputs = tokenizer(
775
+ captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
776
+ ).input_ids # (b, 77)
777
+ encoder_hidden_states = text_encoder(inputs)[0].cuda() # (b, 77, 768)
778
+ print(f'{colored("[√]", "green")} encoder_hidden_states: {encoder_hidden_states.shape}.')
779
+
780
+ inputs_nocond = tokenizer(
781
+ captions_nocond, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
782
+ ).input_ids # (b, 77)
783
+ encoder_hidden_states_nocond = text_encoder(inputs_nocond)[0].cuda() # (b, 77, 768)
784
+ print(f'{colored("[√]", "green")} encoder_hidden_states_nocond: {encoder_hidden_states_nocond.shape}.')
785
+
786
+ mask_image = cv2.resize(mask_image, (size,size))
787
+ # mask_image = mask_image.resize((512,512)).convert('RGB')
788
+ text_mask = np.array(mask_image)
789
+ threshold = 128
790
+ _, text_mask = cv2.threshold(text_mask, threshold, 255, cv2.THRESH_BINARY)
791
+ text_mask = Image.fromarray(text_mask).convert('RGB').resize((256,256))
792
+ text_mask.save('text_mask.png')
793
+ text_mask_tensor = to_tensor(text_mask).unsqueeze(0).cuda().sub_(0.5).div_(0.5)
794
+ with torch.no_grad():
795
+ segmentation_mask = segmenter(text_mask_tensor)
796
+
797
+ segmentation_mask = segmentation_mask.max(1)[1].squeeze(0)
798
+ segmentation_mask = filter_segmentation_mask(segmentation_mask)
799
+ segmentation_mask = torch.nn.functional.interpolate(segmentation_mask.unsqueeze(0).unsqueeze(0).float(), size=(size//2, size//2), mode='nearest')
800
+
801
+ image_mask = transform_mask_pil(mask_image, size)
802
+ image_mask = torch.from_numpy(image_mask).cuda().unsqueeze(0).unsqueeze(0)
803
+
804
+ orig_image = orig_image.convert('RGB').resize((size,size))
805
+ image = orig_image
806
+ image_tensor = to_tensor(image).unsqueeze(0).cuda().sub_(0.5).div_(0.5)
807
+ masked_image = image_tensor * (1-image_mask)
808
+ masked_feature = vae.encode(masked_image).latent_dist.sample().repeat(sample_num, 1, 1, 1)
809
+ masked_feature = masked_feature * vae.config.scaling_factor
810
+
811
+ image_mask = torch.nn.functional.interpolate(image_mask, size=(size//2, size//2), mode='nearest').repeat(sample_num, 1, 1, 1)
812
+ segmentation_mask = segmentation_mask * image_mask
813
+ feature_mask = torch.nn.functional.interpolate(image_mask, size=(size//8, size//8), mode='nearest')
814
+
815
+ # diffusion process
816
+ intermediate_images = []
817
+ for t in tqdm(scheduler.timesteps):
818
+ with torch.no_grad():
819
+ 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
820
+ 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
821
+ noisy_residual = noise_pred_uncond + slider_guidance * (noise_pred_cond - noise_pred_uncond) # b, 4, 64, 64
822
+ prev_noisy_sample = scheduler.step(noisy_residual, t, input).prev_sample
823
+ input = prev_noisy_sample
824
+ intermediate_images.append(prev_noisy_sample)
825
+
826
+ # decode and visualization
827
+ input = 1 / vae.config.scaling_factor * input
828
+ sample_images = vae.decode(input.float(), return_dict=False)[0] # (b, 3, 512, 512)
829
+
830
+ image_pil = None
831
+ segmentation_mask = segmentation_mask[0].squeeze().cpu().numpy()
832
+ character_mask_pil = Image.fromarray(((segmentation_mask!=0)*255).astype('uint8')).resize((512,512))
833
+ character_mask_highlight_pil = segmentation_mask_visualization(args.font_path,segmentation_mask)
834
+ character_mask_highlight_pil = character_mask_highlight_pil.resize((size, size))
835
+ caption_pil = make_caption_pil(args.font_path, captions)
836
+
837
+ # save pred_img
838
+ pred_image_list = []
839
+ for image in sample_images.float():
840
+ image = (image / 2 + 0.5).clamp(0, 1).unsqueeze(0)
841
+ image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
842
+ image = Image.fromarray((image * 255).round().astype("uint8")).convert('RGB')
843
+
844
+ # need to merge
845
+
846
+ # image = inpainting_merge_image(orig_image, Image.fromarray(mask_image).convert('L'), image)
847
+
848
+ pred_image_list.append(image)
849
+
850
+ character_mask_pil.save('character_mask_pil.png')
851
+ character_mask_highlight_pil.save('character_mask_highlight_pil.png')
852
+
853
+
854
+ blank_pil = combine_image(args, size, None, pred_image_list, image_pil, character_mask_pil, character_mask_highlight_pil, caption_pil)
855
+
856
+
857
+ background = orig_image.resize((512, 512))
858
+ alpha = Image.new('L', background.size, int(255 * 0.2))
859
+ background.putalpha(alpha)
860
+ # foreground
861
+ foreground = Image.fromarray(mask_image).convert('L').resize((512, 512))
862
+ threshold = 200
863
+ alpha = foreground.point(lambda x: 0 if x > threshold else 255, '1')
864
+ foreground.putalpha(alpha)
865
+ merge_image = Image.alpha_composite(foreground.convert('RGBA'), background.convert('RGBA')).convert('RGB')
866
+
867
+ intermediate_result = Image.new('RGB', (512*3, 512))
868
+ intermediate_result.paste(merge_image, (0, 0))
869
+ intermediate_result.paste(character_mask_pil, (512, 0))
870
+ intermediate_result.paste(character_mask_highlight_pil, (512*2, 0))
871
+
872
+ return blank_pil, intermediate_result
873
+
874
+ import gradio as gr
875
+
876
+ with gr.Blocks() as demo:
877
+
878
+ gr.HTML(
879
+ """
880
+ <div style="text-align: center; max-width: 1200px; margin: 20px auto;">
881
+ <h1 style="font-weight: 900; font-size: 3rem; margin: 0rem">
882
+ TextDiffuser: Diffusion Models as Text Painters
883
+ </h1>
884
+ <h3 style="font-weight: 450; font-size: 1rem; margin: 0rem">
885
+ [<a href="https://arxiv.org/abs/2305.10855" style="color:blue;">arXiv</a>]
886
+ [<a href="https://github.com/microsoft/unilm/tree/master/textdiffuser" style="color:blue;">Code</a>]
887
+ [<a href="https://jingyechen.github.io/textdiffuser/" style="color:blue;">ProjectPage</a>]
888
+ </h3>
889
+ <h2 style="text-align: left; font-weight: 450; font-size: 1rem; margin-top: 0.5rem; margin-bottom: 0.5rem">
890
+ We propose <b>TextDiffuser</b>, a flexible and controllable framework to generate images with visually appealing text that is coherent with backgrounds.
891
+ 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.
892
+ </h2>
893
+ <h2 style="text-align: left; font-weight: 450; font-size: 1rem; margin-top: 0.5rem; margin-bottom: 0.5rem">
894
+ 🔥 <b>News</b>: We further trained TextDiffuser based on <b>Stable Diffusion v2.1</b> pre-trained model, enlarging the resolution from 512x512 to <b>768x768</b> to enhance the legibility of small text. Additionally, we fine-tuned the model with images with <b>high aesthetical score</b>, enabling generating images with richer details.
895
+ </h2>
896
+
897
+
898
+ <img src="file/images/huggingface_blank.jpg" alt="textdiffuser">
899
+ </div>
900
+ """)
901
+
902
+ with gr.Tab("Text-to-Image"):
903
+ with gr.Row():
904
+ with gr.Column(scale=1):
905
+ 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")
906
+ radio = gr.Radio(["Stable Diffusion v2.1", "Stable Diffusion v1.5"], label="Pre-trained Model", value="Stable Diffusion v1.5")
907
+ slider_step = gr.Slider(minimum=1, maximum=50, value=20, step=1, label="Sampling step", info="The sampling step for TextDiffuser.")
908
+ 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.")
909
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=4, step=1, label="Batch size", info="The number of images to be sampled. Maximum number is set to 1 for SD v2.1 to avoid OOM.")
910
+ # slider_seed = gr.Slider(minimum=1, maximum=10000, label="Seed", randomize=True)
911
+ button = gr.Button("Generate")
912
+
913
+ with gr.Column(scale=1):
914
+ output = gr.Image(label='Generated image')
915
+
916
+ with gr.Accordion("Intermediate results", open=False):
917
+ gr.Markdown("Layout, segmentation mask, and details of segmentation mask from left to right.")
918
+ intermediate_results = gr.Image(label='')
919
+
920
+ gr.Markdown("## Prompt Examples")
921
+ gr.Examples(
922
+ [
923
+ ["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"],
924
+ ["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"],
925
+ ["portrait of a 'dragon', concept art, sumi - e style, intricate linework, green smoke, artstation, trending, highly detailed, smooth, focus, art by yoji shinkawa,"],
926
+ ["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"],
927
+ ["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"],
928
+ ["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"],
929
+ ["A poster of 'AI BABY'. Cute and adorable cartoon it baby, fantasy, dreamlike, surrealism, super cute, trending on artstation"],
930
+ ["'Team' hat"],
931
+ ["Thanksgiving 'Fam' Mens T Shirt"],
932
+ ["A storefront with 'Hello World' written on it."],
933
+ ["A poster titled 'Quails of North America', showing different kinds of quails."],
934
+ ["A storefront with 'Deep Learning' written on it."],
935
+ ["An antique bottle labeled 'Energy Tonic'"],
936
+ ["A TV show poster titled 'Tango argentino'"],
937
+ ["A TV show poster with logo 'The Dry' on it"],
938
+ ["Stupid 'History' eBook Tales of Stupidity Strangeness"],
939
+ ["Photos of 'Sampa Hostel'"],
940
+ ["A large recipe book titled 'Recipes from Peru'."],
941
+ ["New York Skyline with 'Diffusion' written with fireworks on the sky"],
942
+ ["Books with the word 'Science' printed on them"],
943
+ ["A globe with the words 'Planet Earth' written in bold letters with continents in bright colors"],
944
+ ["A logo for the company 'EcoGrow', where the letters look like plants"],
945
+ ],
946
+ prompt,
947
+ examples_per_page=100
948
+ )
949
+
950
+ button.click(text_to_image, inputs=[prompt,slider_step,slider_guidance,slider_batch,radio], outputs=[output,intermediate_results])
951
+
952
+ with gr.Tab("Text-to-Image-with-Template"):
953
+ with gr.Row():
954
+ with gr.Column(scale=1):
955
+ prompt = gr.Textbox(label='Input your prompt here.')
956
+ template_image = gr.Image(label='Template image', type="pil")
957
+ radio = gr.Radio(["Stable Diffusion v2.1", "Stable Diffusion v1.5"], label="Pre-trained Model", value="Stable Diffusion v1.5")
958
+ slider_step = gr.Slider(minimum=1, maximum=50, value=20, step=1, label="Sampling step", info="The sampling step for TextDiffuser.")
959
+ 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.")
960
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=4, step=1, label="Batch size", info="The number of images to be sampled. Maximum number is set to 1 for SD v2.1 to avoid OOM.")
961
+ # binary = gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?")
962
+ binary = gr.Checkbox(label="Binarization", bool=True, info="Whether to binarize the template image? You may need it when using handwritten images as templates.")
963
+ button = gr.Button("Generate")
964
+
965
+ with gr.Column(scale=1):
966
+ output = gr.Image(label='Generated image')
967
+
968
+ with gr.Accordion("Intermediate results", open=False):
969
+ gr.Markdown("Template image, segmentation mask, and details of segmentation mask from left to right.")
970
+ intermediate_results = gr.Image(label='')
971
+
972
+ gr.Markdown("## Prompt and Template-Image Examples")
973
+ gr.Examples(
974
+ [
975
+ ["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],
976
+ ["a hand-drawn blueprint for a time machine with the caption 'Time traveling device'", './images/text-to-image-with-template/5.jpg', False],
977
+ ["a book called summer vibe written by diffusion model", './images/text-to-image-with-template/7.jpg', False],
978
+ ["a work company", './images/text-to-image-with-template/8.jpg', False],
979
+ ["a book of AI in next century written by AI robot ", './images/text-to-image-with-template/9.jpg', False],
980
+ ["A board saying having a dog named shark at the beach was a mistake", './images/text-to-image-with-template/1.jpg', False],
981
+ ["an elephant holds a newspaper that is written elephant take over the world", './images/text-to-image-with-template/2.jpg', False],
982
+ ["a mouse with a flashlight saying i am afraid of the dark", './images/text-to-image-with-template/4.jpg', False],
983
+ ["a birthday cake of happy birthday to xyz", './images/text-to-image-with-template/10.jpg', False],
984
+ ["a poster of monkey music festival", './images/text-to-image-with-template/11.jpg', False],
985
+ ["a meme of are you kidding", './images/text-to-image-with-template/12.jpg', False],
986
+ ["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],
987
+ ["a board of hello world", './images/text-to-image-with-template/15.jpg', True],
988
+ ["a microsoft bag", './images/text-to-image-with-template/16.jpg', True],
989
+ ["a dog holds a paper saying please adopt me", './images/text-to-image-with-template/17.jpg', False],
990
+ ["a hello world banner", './images/text-to-image-with-template/18.jpg', False],
991
+ ["a stop pizza", './images/text-to-image-with-template/19.jpg', False],
992
+ ["a dress with text do not read the next sentence", './images/text-to-image-with-template/20.jpg', False],
993
+ ],
994
+ [prompt,template_image, binary],
995
+ examples_per_page=100
996
+ )
997
+
998
+ button.click(text_to_image_with_template, inputs=[prompt,template_image,slider_step,slider_guidance,slider_batch,binary,radio], outputs=[output,intermediate_results])
999
+
1000
+ with gr.Tab("Text-Inpainting"):
1001
+ with gr.Row():
1002
+ with gr.Column(scale=1):
1003
+ prompt = gr.Textbox(label='Input your prompt here.')
1004
+ with gr.Row():
1005
+ orig_image = gr.Image(label='Original image', type="pil")
1006
+ mask_image = gr.Image(label='Mask image', type="numpy")
1007
+ radio = gr.Radio(["Stable Diffusion v2.1", "Stable Diffusion v1.5"], label="Pre-trained Model", value="Stable Diffusion v1.5")
1008
+ slider_step = gr.Slider(minimum=1, maximum=50, value=20, step=1, label="Sampling step", info="The sampling step for TextDiffuser.")
1009
+ 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.")
1010
+ slider_batch = gr.Slider(minimum=1, maximum=4, value=4, step=1, label="Batch size", info="The number of images to be sampled. Maximum number is set to 1 for SD v2.1 to avoid OOM.")
1011
+ button = gr.Button("Generate")
1012
+ with gr.Column(scale=1):
1013
+ output = gr.Image(label='Generated image')
1014
+ with gr.Accordion("Intermediate results", open=False):
1015
+ gr.Markdown("Masked image, segmentation mask, and details of segmentation mask from left to right.")
1016
+ intermediate_results = gr.Image(label='')
1017
+
1018
+ gr.Markdown("## Prompt, Original Image, and Mask Examples")
1019
+ gr.Examples(
1020
+ [
1021
+ ["eye on security protection", './images/text-inpainting/1.jpg', './images/text-inpainting/1mask.jpg'],
1022
+ ["a logo of poppins", './images/text-inpainting/2.jpg', './images/text-inpainting/2mask.jpg'],
1023
+ ["tips for middle space living ", './images/text-inpainting/3.jpg', './images/text-inpainting/3mask.jpg'],
1024
+ ["george is a proud big sister", './images/text-inpainting/5.jpg', './images/text-inpainting/5mask.jpg'],
1025
+ ["we are the great people", './images/text-inpainting/6.jpg', './images/text-inpainting/6mask.jpg'],
1026
+ ["tech house interesting terrace party", './images/text-inpainting/7.jpg', './images/text-inpainting/7mask.jpg'],
1027
+ ["2023", './images/text-inpainting/8.jpg', './images/text-inpainting/8mask.jpg'],
1028
+ ["wear protective equipment necessary", './images/text-inpainting/9.jpg', './images/text-inpainting/9mask.jpg'],
1029
+ ["a good day in the hometown", './images/text-inpainting/10.jpg', './images/text-inpainting/10mask.jpg'],
1030
+ ["a boy paints good morning on a board", './images/text-inpainting/11.jpg', './images/text-inpainting/11mask.jpg'],
1031
+ ["the word my gift on a basketball", './images/text-inpainting/13.jpg', './images/text-inpainting/13mask.jpg'],
1032
+ ["a logo of mono", './images/text-inpainting/14.jpg', './images/text-inpainting/14mask.jpg'],
1033
+ ["a board saying assyrian on unflagging fry devastates", './images/text-inpainting/15.jpg', './images/text-inpainting/15mask.jpg'],
1034
+ ["a board saying session", './images/text-inpainting/16.jpg', './images/text-inpainting/16mask.jpg'],
1035
+ ["rankin dork", './images/text-inpainting/17mask.jpg', './images/text-inpainting/17.jpg'],
1036
+ ["a coin of mem", './images/text-inpainting/18mask.jpg', './images/text-inpainting/18.jpg'],
1037
+ ["a board without text", './images/text-inpainting/19.jpg', './images/text-inpainting/19mask.jpg'],
1038
+ ["a board without text", './images/text-inpainting/20.jpg', './images/text-inpainting/20mask.jpg'],
1039
+
1040
+ ],
1041
+ [prompt,orig_image,mask_image],
1042
+ )
1043
+
1044
+
1045
+ button.click(text_inpainting, inputs=[prompt,orig_image,mask_image,slider_step,slider_guidance,slider_batch,radio], outputs=[output, intermediate_results])
1046
+
1047
+
1048
+
1049
+ gr.HTML(
1050
+ """
1051
+ <div style="text-align: justify; max-width: 1200px; margin: 20px auto;">
1052
+ <h3 style="font-weight: 450; font-size: 0.8rem; margin: 0rem">
1053
+ <b>Version</b>: 1.0
1054
+ </h3>
1055
+ <h3 style="font-weight: 450; font-size: 0.8rem; margin: 0rem">
1056
+ <b>Contact</b>:
1057
+ 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>.
1058
+ </h3>
1059
+ <h3 style="font-weight: 450; font-size: 0.8rem; margin: 0rem">
1060
+ <b>Disclaimer</b>:
1061
+ Please note that the demo is intended for academic and research purposes <b>ONLY</b>. Any use of the demo for generating inappropriate content is strictly prohibited. The responsibility for any misuse or inappropriate use of the demo lies solely with the users who generated such content, and this demo shall not be held liable for any such use.
1062
+ </h3>
1063
+ </div>
1064
+ """
1065
+ )
1066
+
1067
+ 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,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, size):
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, (size, size), 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, size):
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, (size, size), 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, resolution, 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
+
142
+ size = len(pred_image_list)
143
+
144
+ if size == 1:
145
+ return pred_image_list[0]
146
+ elif size == 2:
147
+ blank = Image.new('RGB', (resolution*2, resolution), (0,0,0))
148
+ blank.paste(pred_image_list[0],(0,0))
149
+ blank.paste(pred_image_list[1],(resolution,0))
150
+ elif size == 3:
151
+ blank = Image.new('RGB', (resolution*3, resolution), (0,0,0))
152
+ blank.paste(pred_image_list[0],(0,0))
153
+ blank.paste(pred_image_list[1],(resolution,0))
154
+ blank.paste(pred_image_list[2],(resolution*2,0))
155
+ elif size == 4:
156
+ blank = Image.new('RGB', (resolution*2, resolution*2), (0,0,0))
157
+ blank.paste(pred_image_list[0],(0,0))
158
+ blank.paste(pred_image_list[1],(resolution,0))
159
+ blank.paste(pred_image_list[2],(0,resolution))
160
+ blank.paste(pred_image_list[3],(resolution,resolution))
161
+
162
+
163
+ return blank
164
+
165
+
166
+ def combine_image_gradio(args, size, sub_output_dir: str, pred_image_list: List, image_pil: Image, character_mask_pil: Image, character_mask_highlight_pil: Image, caption_pil_list: List):
167
+ """
168
+ This function combines all the outputs and useful inputs together.
169
+
170
+ Args:
171
+ args (argparse.ArgumentParser): The arguments.
172
+ pred_image_list (List): List of predicted images.
173
+ image_pil (Image): The original image.
174
+ character_mask_pil (Image): The character-level segmentation mask.
175
+ character_mask_highlight_pil (Image): The character-level segmentation mask highlighting character regions with green color.
176
+ caption_pil_list (List): List of captions.
177
+ """
178
+
179
+ size = len(pred_image_list)
180
+
181
+ if size == 1:
182
+ return pred_image_list[0]
183
+ elif size == 2:
184
+ blank = Image.new('RGB', (size*2, size), (0,0,0))
185
+ blank.paste(pred_image_list[0],(0,0))
186
+ blank.paste(pred_image_list[1],(size,0))
187
+ elif size == 3:
188
+ blank = Image.new('RGB', (size*3, size), (0,0,0))
189
+ blank.paste(pred_image_list[0],(0,0))
190
+ blank.paste(pred_image_list[1],(size,0))
191
+ blank.paste(pred_image_list[2],(size*2,0))
192
+ elif size == 4:
193
+ blank = Image.new('RGB', (size*2, size*2), (0,0,0))
194
+ blank.paste(pred_image_list[0],(0,0))
195
+ blank.paste(pred_image_list[1],(size,0))
196
+ blank.paste(pred_image_list[2],(0,size))
197
+ blank.paste(pred_image_list[3],(size,size))
198
+
199
+
200
+ return blank
201
+
202
+ def get_width(font_path, text):
203
+ """
204
+ This function calculates the width of the text.
205
+
206
+ Args:
207
+ font_path (str): user prompt.
208
+ text (str): user prompt.
209
+ """
210
+ font = ImageFont.truetype(font_path, 24)
211
+ width, _ = font.getsize(text)
212
+ return width
213
+
214
+
215
+
216
+ def get_key_words(text: str):
217
+ """
218
+ This function detect keywords (enclosed by quotes) from user prompts. The keywords are used to guide the layout generation.
219
+
220
+ Args:
221
+ text (str): user prompt.
222
+ """
223
+
224
+ words = []
225
+ text = text
226
+ matches = re.findall(r"'(.*?)'", text) # find the keywords enclosed by ''
227
+ if matches:
228
+ for match in matches:
229
+ words.extend(match.split())
230
+
231
+ if len(words) >= 8:
232
+ return []
233
+
234
+ return words
235
+
236
+
237
+ def adjust_overlap_box(box_output, current_index):
238
+ """
239
+ This function adjust the overlapping boxes.
240
+
241
+ Args:
242
+ box_output (List): List of predicted boxes.
243
+ current_index (int): the index of current box.
244
+ """
245
+
246
+ if current_index == 0:
247
+ return box_output
248
+ else:
249
+ # judge whether it contains overlap with the last output
250
+ last_box = box_output[0, current_index-1, :]
251
+ xmin_last, ymin_last, xmax_last, ymax_last = last_box
252
+
253
+ current_box = box_output[0, current_index, :]
254
+ xmin, ymin, xmax, ymax = current_box
255
+
256
+ if xmin_last <= xmin <= xmax_last and ymin_last <= ymin <= ymax_last:
257
+ print('adjust overlapping')
258
+ distance_x = xmax_last - xmin
259
+ distance_y = ymax_last - ymin
260
+ if distance_x <= distance_y:
261
+ # avoid overlap
262
+ new_x_min = xmax_last + 0.025
263
+ new_x_max = xmax - xmin + xmax_last + 0.025
264
+ box_output[0,current_index,0] = new_x_min
265
+ box_output[0,current_index,2] = new_x_max
266
+ else:
267
+ new_y_min = ymax_last + 0.025
268
+ new_y_max = ymax - ymin + ymax_last + 0.025
269
+ box_output[0,current_index,1] = new_y_min
270
+ box_output[0,current_index,3] = new_y_max
271
+
272
+ elif xmin_last <= xmin <= xmax_last and ymin_last <= ymax <= ymax_last:
273
+ print('adjust overlapping')
274
+ new_x_min = xmax_last + 0.05
275
+ new_x_max = xmax - xmin + xmax_last + 0.05
276
+ box_output[0,current_index,0] = new_x_min
277
+ box_output[0,current_index,2] = new_x_max
278
+
279
+ return box_output
280
+
281
+
282
+ def shrink_box(box, scale_factor = 0.9):
283
+ """
284
+ This function shrinks the box.
285
+
286
+ Args:
287
+ box (List): List of predicted boxes.
288
+ scale_factor (float): The scale factor of shrinking.
289
+ """
290
+
291
+ x1, y1, x2, y2 = box
292
+ x1_new = x1 + (x2 - x1) * (1 - scale_factor) / 2
293
+ y1_new = y1 + (y2 - y1) * (1 - scale_factor) / 2
294
+ x2_new = x2 - (x2 - x1) * (1 - scale_factor) / 2
295
+ y2_new = y2 - (y2 - y1) * (1 - scale_factor) / 2
296
+ return (x1_new, y1_new, x2_new, y2_new)
297
+
298
+
299
+ def adjust_font_size(args, width, height, draw, text):
300
+ """
301
+ This function adjusts the font size.
302
+
303
+ Args:
304
+ args (argparse.ArgumentParser): The arguments.
305
+ width (int): The width of the text.
306
+ height (int): The height of the text.
307
+ draw (ImageDraw): The ImageDraw object.
308
+ text (str): The text.
309
+ """
310
+
311
+ size_start = height
312
+ while True:
313
+ font = ImageFont.truetype(args.font_path, size_start)
314
+ text_width, _ = draw.textsize(text, font=font)
315
+ if text_width >= width:
316
+ size_start = size_start - 1
317
+ else:
318
+ return size_start
319
+
320
+
321
+ def inpainting_merge_image(original_image, mask_image, inpainting_image):
322
+ """
323
+ This function merges the original image, mask image and inpainting image.
324
+
325
+ Args:
326
+ original_image (PIL.Image): The original image.
327
+ mask_image (PIL.Image): The mask images.
328
+ inpainting_image (PIL.Image): The inpainting images.
329
+ """
330
+
331
+ original_image = original_image.resize((512, 512))
332
+ mask_image = mask_image.resize((512, 512))
333
+ inpainting_image = inpainting_image.resize((512, 512))
334
+ mask_image.convert('L')
335
+ threshold = 250
336
+ table = []
337
+ for i in range(256):
338
+ if i < threshold:
339
+ table.append(1)
340
+ else:
341
+ table.append(0)
342
+ mask_image = mask_image.point(table, "1")
343
+ merged_image = Image.composite(inpainting_image, original_image, mask_image)
344
+ return merged_image