brianlorenzo Linoy Tsaban commited on
Commit
7d10a55
·
0 Parent(s):

Duplicate from editing-images/ledits

Browse files

Co-authored-by: Linoy Tsaban <[email protected]>

Files changed (34) hide show
  1. .gitattributes +37 -0
  2. LEDITS_ddpm_inversion_x_sega.ipynb +0 -0
  3. README.md +20 -0
  4. app.py +850 -0
  5. constants.py +26 -0
  6. examples/butterfly_input.jpg +0 -0
  7. examples/butterfly_output.jpg +0 -0
  8. examples/ddpm_a_cat_sitting_next_to_a_mirror.png +0 -0
  9. examples/ddpm_a_robot_wearing_a_brown_hoodie_in_a_crowded_street.png +0 -0
  10. examples/ddpm_glass_walls.png +0 -0
  11. examples/ddpm_sega_glass_walls_gian_elephant.png +0 -0
  12. examples/ddpm_sega_painting_of_a_robot_wearing_a_brown_hoodie_in_a_crowded_street.png +0 -0
  13. examples/ddpm_sega_plus_pink_drawings_of_muffins.png +0 -0
  14. examples/ddpm_sega_watercolor_painting_a_cat_sitting_next_to_a_mirror_plus_dog_minus_cat.png +0 -0
  15. examples/ddpm_wall_with_framed_photos.png +0 -0
  16. examples/ddpm_watercolor_painting_a_cat_sitting_next_to_a_mirror.png +0 -0
  17. examples/flower_field_input.jpg +0 -0
  18. examples/flower_field_output.jpg +0 -0
  19. examples/flower_field_output_2.jpg +0 -0
  20. examples/girl_with_pearl_earring_input.png +0 -0
  21. examples/girl_with_pearl_earring_output.png +0 -0
  22. examples/lemons_input.jpg +0 -0
  23. examples/lemons_output.jpg +0 -0
  24. examples/rockey_shore_input.jpg +0 -0
  25. examples/rockey_shore_output.jpg +0 -0
  26. examples/source_a_cat_sitting_next_to_a_mirror.jpeg +0 -0
  27. examples/source_a_man_wearing_a_brown_hoodie_in_a_crowded_street.jpeg +3 -0
  28. examples/source_an_empty_room_with_concrete_walls.jpg +0 -0
  29. examples/source_wall_with_framed_photos.jpeg +3 -0
  30. inversion_utils.py +275 -0
  31. modified_pipeline_semantic_stable_diffusion.py +753 -0
  32. requirements.txt +5 -0
  33. style.css +77 -0
  34. utils.py +114 -0
.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
35
+ exmaples/source_a_man_wearing_a_brown_hoodie_in_a_crowded_street.jpeg filter=lfs diff=lfs merge=lfs -text
36
+ examples/source_a_man_wearing_a_brown_hoodie_in_a_crowded_street.jpeg filter=lfs diff=lfs merge=lfs -text
37
+ examples/source_wall_with_framed_photos.jpeg filter=lfs diff=lfs merge=lfs -text
LEDITS_ddpm_inversion_x_sega.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
README.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: LEDITS
3
+ emoji: ✏️
4
+ colorFrom: gray
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 3.35.2
8
+ app_file: app.py
9
+ pinned: true
10
+ duplicated_from: editing-images/ledits
11
+ ---
12
+
13
+ This is the repository for [LEDITS - Real Image Latent Editing with Edit Friendly DDPM and Semantic Guidance](arxiv.org/abs/2307.00522). More information about the technique [here](https://editing-images-project.hf.space)
14
+
15
+ This repository contains the following relevant files:
16
+ - `app.py` - Gradio application for the inversion technique combining uploading an image, captioning it, doing the DDPM Inversion and applying SEGA concepts to the editing.
17
+ - `constants.py` - default config values for the `app.py`
18
+ - `inversion_utils.py` - utilities for providing the DDPM Inversion
19
+ - `modified_pipeline_semantic_stable_diffusion.py` - modified pipeline of SEGA for the purposes of LEDITS
20
+ - `utils.py` - generic useful utils for the app
app.py ADDED
@@ -0,0 +1,850 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import numpy as np
4
+ import requests
5
+ import random
6
+ from io import BytesIO
7
+ from utils import *
8
+ from constants import *
9
+ from inversion_utils import *
10
+ from modified_pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
11
+ from torch import autocast, inference_mode
12
+ from diffusers import StableDiffusionPipeline
13
+ from diffusers import DDIMScheduler
14
+ from transformers import AutoProcessor, BlipForConditionalGeneration
15
+
16
+ # load pipelines
17
+ sd_model_id = "stabilityai/stable-diffusion-2-1-base"
18
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
+ sd_pipe = StableDiffusionPipeline.from_pretrained(sd_model_id,torch_dtype=torch.float16).to(device)
20
+ sd_pipe.scheduler = DDIMScheduler.from_config(sd_model_id, subfolder = "scheduler")
21
+ sem_pipe = SemanticStableDiffusionPipeline.from_pretrained(sd_model_id, torch_dtype=torch.float16).to(device)
22
+ blip_processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
23
+ blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base",torch_dtype=torch.float16).to(device)
24
+
25
+
26
+
27
+ ## IMAGE CPATIONING ##
28
+ def caption_image(input_image):
29
+ inputs = blip_processor(images=input_image, return_tensors="pt").to(device, torch.float16)
30
+ pixel_values = inputs.pixel_values
31
+
32
+ generated_ids = blip_model.generate(pixel_values=pixel_values, max_length=50)
33
+ generated_caption = blip_processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
34
+ return generated_caption, generated_caption
35
+
36
+
37
+
38
+ ## DDPM INVERSION AND SAMPLING ##
39
+ def invert(x0, prompt_src="", num_diffusion_steps=100, cfg_scale_src = 3.5, eta = 1):
40
+
41
+ # inverts a real image according to Algorihm 1 in https://arxiv.org/pdf/2304.06140.pdf,
42
+ # based on the code in https://github.com/inbarhub/DDPM_inversion
43
+
44
+ # returns wt, zs, wts:
45
+ # wt - inverted latent
46
+ # wts - intermediate inverted latents
47
+ # zs - noise maps
48
+
49
+ sd_pipe.scheduler.set_timesteps(num_diffusion_steps)
50
+
51
+ # vae encode image
52
+ with inference_mode():
53
+ w0 = (sd_pipe.vae.encode(x0).latent_dist.mode() * 0.18215)
54
+
55
+ # find Zs and wts - forward process
56
+ wt, zs, wts = inversion_forward_process(sd_pipe, w0, etas=eta, prompt=prompt_src, cfg_scale=cfg_scale_src, prog_bar=True, num_inference_steps=num_diffusion_steps)
57
+ return zs, wts
58
+
59
+
60
+ def sample(zs, wts, prompt_tar="", cfg_scale_tar=15, skip=36, eta = 1):
61
+
62
+ # reverse process (via Zs and wT)
63
+ w0, _ = inversion_reverse_process(sd_pipe, xT=wts[skip], etas=eta, prompts=[prompt_tar], cfg_scales=[cfg_scale_tar], prog_bar=True, zs=zs[skip:])
64
+
65
+ # vae decode image
66
+ with inference_mode():
67
+ x0_dec = sd_pipe.vae.decode(1 / 0.18215 * w0).sample
68
+ if x0_dec.dim()<4:
69
+ x0_dec = x0_dec[None,:,:,:]
70
+ img = image_grid(x0_dec)
71
+ return img
72
+
73
+
74
+ def reconstruct(tar_prompt,
75
+ image_caption,
76
+ tar_cfg_scale,
77
+ skip,
78
+ wts, zs,
79
+ do_reconstruction,
80
+ reconstruction,
81
+ reconstruct_button
82
+ ):
83
+
84
+ if reconstruct_button == "Hide Reconstruction":
85
+ return reconstruction.value, reconstruction, ddpm_edited_image.update(visible=False), do_reconstruction, "Show Reconstruction"
86
+
87
+ else:
88
+ if do_reconstruction:
89
+ if image_caption.lower() == tar_prompt.lower(): # if image caption was not changed, run actual reconstruction
90
+ tar_prompt = ""
91
+ reconstruction_img = sample(zs.value, wts.value, prompt_tar=tar_prompt, skip=skip, cfg_scale_tar=tar_cfg_scale)
92
+ reconstruction = gr.State(value=reconstruction_img)
93
+ do_reconstruction = False
94
+ return reconstruction.value, reconstruction, ddpm_edited_image.update(visible=True), do_reconstruction, "Hide Reconstruction"
95
+
96
+
97
+ def load_and_invert(
98
+ input_image,
99
+ do_inversion,
100
+ seed, randomize_seed,
101
+ wts, zs,
102
+ src_prompt ="",
103
+ tar_prompt="",
104
+ steps=100,
105
+ src_cfg_scale = 3.5,
106
+ skip=36,
107
+ tar_cfg_scale=15,
108
+ progress=gr.Progress(track_tqdm=True)
109
+
110
+ ):
111
+
112
+
113
+ x0 = load_512(input_image, device=device).to(torch.float16)
114
+
115
+ if do_inversion or randomize_seed:
116
+ # invert and retrieve noise maps and latent
117
+ zs_tensor, wts_tensor = invert(x0 =x0 , prompt_src=src_prompt, num_diffusion_steps=steps, cfg_scale_src=src_cfg_scale)
118
+ wts = gr.State(value=wts_tensor)
119
+ zs = gr.State(value=zs_tensor)
120
+ do_inversion = False
121
+
122
+ return wts, zs, do_inversion, inversion_progress.update(visible=False)
123
+
124
+ ## SEGA ##
125
+
126
+ def edit(input_image,
127
+ wts, zs,
128
+ tar_prompt,
129
+ image_caption,
130
+ steps,
131
+ skip,
132
+ tar_cfg_scale,
133
+ edit_concept_1,edit_concept_2,edit_concept_3,
134
+ guidnace_scale_1,guidnace_scale_2,guidnace_scale_3,
135
+ warmup_1, warmup_2, warmup_3,
136
+ neg_guidance_1, neg_guidance_2, neg_guidance_3,
137
+ threshold_1, threshold_2, threshold_3,
138
+ do_reconstruction,
139
+ reconstruction,
140
+
141
+ # for inversion in case it needs to be re computed (and avoid delay):
142
+ do_inversion,
143
+ seed,
144
+ randomize_seed,
145
+ src_prompt,
146
+ src_cfg_scale):
147
+
148
+ if do_inversion or randomize_seed:
149
+ x0 = load_512(input_image, device=device).to(torch.float16)
150
+ # invert and retrieve noise maps and latent
151
+ zs_tensor, wts_tensor = invert(x0 =x0 , prompt_src=src_prompt, num_diffusion_steps=steps, cfg_scale_src=src_cfg_scale)
152
+ wts = gr.State(value=wts_tensor)
153
+ zs = gr.State(value=zs_tensor)
154
+ do_inversion = False
155
+
156
+ if image_caption.lower() == tar_prompt.lower(): # if image caption was not changed, run pure sega
157
+ tar_prompt = ""
158
+
159
+ if edit_concept_1 != "" or edit_concept_2 != "" or edit_concept_3 != "":
160
+ editing_args = dict(
161
+ editing_prompt = [edit_concept_1,edit_concept_2,edit_concept_3],
162
+ reverse_editing_direction = [ neg_guidance_1, neg_guidance_2, neg_guidance_3,],
163
+ edit_warmup_steps=[warmup_1, warmup_2, warmup_3,],
164
+ edit_guidance_scale=[guidnace_scale_1,guidnace_scale_2,guidnace_scale_3],
165
+ edit_threshold=[threshold_1, threshold_2, threshold_3],
166
+ edit_momentum_scale=0.3,
167
+ edit_mom_beta=0.6,
168
+ eta=1,)
169
+
170
+ latnets = wts.value[skip].expand(1, -1, -1, -1)
171
+ sega_out = sem_pipe(prompt=tar_prompt, latents=latnets, guidance_scale = tar_cfg_scale,
172
+ num_images_per_prompt=1,
173
+ num_inference_steps=steps,
174
+ use_ddpm=True, wts=wts.value, zs=zs.value[skip:], **editing_args)
175
+
176
+ return sega_out.images[0], reconstruct_button.update(visible=True), do_reconstruction, reconstruction, wts, zs, do_inversion
177
+
178
+ else: # if sega concepts were not added, performs regular ddpm sampling
179
+
180
+ if do_reconstruction: # if ddpm sampling wasn't computed
181
+ pure_ddpm_img = sample(zs.value, wts.value, prompt_tar=tar_prompt, skip=skip, cfg_scale_tar=tar_cfg_scale)
182
+ reconstruction = gr.State(value=pure_ddpm_img)
183
+ do_reconstruction = False
184
+ return pure_ddpm_img, reconstruct_button.update(visible=False), do_reconstruction, reconstruction, wts, zs, do_inversion
185
+
186
+ return reconstruction.value, reconstruct_button.update(visible=False), do_reconstruction, reconstruction, wts, zs, do_inversion
187
+
188
+
189
+ def randomize_seed_fn(seed, randomize_seed):
190
+ if randomize_seed:
191
+ seed = random.randint(0, np.iinfo(np.int32).max)
192
+ torch.manual_seed(seed)
193
+ return seed
194
+
195
+
196
+
197
+
198
+ def get_example():
199
+ case = [
200
+ [
201
+ 'examples/lemons_input.jpg',
202
+ # '',
203
+ 'apples', 'lemons',
204
+ 'a ceramic bowl',
205
+ 'examples/lemons_output.jpg',
206
+
207
+
208
+ 7,7,
209
+ 1,1,
210
+ False, True,
211
+ 100,
212
+ 36,
213
+ 15,
214
+
215
+ ],
216
+ [
217
+ 'examples/girl_with_pearl_earring_input.png',
218
+ # '',
219
+ 'glasses', '',
220
+ '',
221
+ 'examples/girl_with_pearl_earring_output.png',
222
+
223
+
224
+ 3,7,
225
+ 3,2,
226
+ False,False,
227
+ 100,
228
+ 36,
229
+ 15,
230
+
231
+ ],
232
+ [
233
+ 'examples/rockey_shore_input.jpg',
234
+ # '',
235
+ 'sea turtle', '',
236
+ 'watercolor painting',
237
+ 'examples/rockey_shore_output.jpg',
238
+
239
+
240
+ 7,7,
241
+ 1,2,
242
+ False,False,
243
+ 100,
244
+ 36,
245
+ 15,
246
+ ],
247
+ [
248
+ 'examples/flower_field_input.jpg',
249
+ # '',
250
+ 'wheat', 'red flowers',
251
+ 'oil painting',
252
+ 'examples/flower_field_output_2.jpg',
253
+
254
+
255
+ 20,7,
256
+ 1,1,
257
+ False,True,
258
+ 100,
259
+ 36,
260
+ 15,
261
+
262
+ ],
263
+ [
264
+ 'examples/butterfly_input.jpg',
265
+ # '',
266
+ 'bee', 'butterfly',
267
+ 'oil painting',
268
+ 'examples/butterfly_output.jpg',
269
+ 7, 7,
270
+ 1,1,
271
+ False, True,
272
+ 100,
273
+ 36,
274
+ 15,
275
+ ]
276
+ ]
277
+ return case
278
+
279
+
280
+ def swap_visibilities(input_image,
281
+ edit_concept_1,
282
+ edit_concept_2,
283
+ tar_prompt,
284
+ sega_edited_image,
285
+ guidnace_scale_1,
286
+ guidnace_scale_2,
287
+ warmup_1,
288
+ warmup_2,
289
+ neg_guidance_1,
290
+ neg_guidance_2,
291
+ steps,
292
+ skip,
293
+ tar_cfg_scale,
294
+ sega_concepts_counter
295
+
296
+ ):
297
+ sega_concepts_counter=0
298
+ concept1_update = update_display_concept("Remove" if neg_guidance_1 else "Add", edit_concept_1, neg_guidance_1, sega_concepts_counter)
299
+ if(edit_concept_2 != ""):
300
+ concept2_update = update_display_concept("Remove" if neg_guidance_2 else "Add", edit_concept_2, neg_guidance_2, sega_concepts_counter+1)
301
+ else:
302
+ concept2_update = gr.update(visible=False), gr.update(visible=False),gr.update(visible=False), gr.update(value=neg_guidance_2),gr.update(visible=True),gr.update(visible=False),sega_concepts_counter+1
303
+ return (*concept1_update[:-1], *concept2_update)
304
+
305
+
306
+
307
+ ########
308
+ # demo #
309
+ ########
310
+
311
+
312
+ intro = """
313
+ <h1 style="font-weight: 1400; text-align: center; margin-bottom: 7px;">
314
+ LEDITS - Pipeline for editing images
315
+ </h1>
316
+ <h3 style="font-weight: 600; text-align: center;">
317
+ Real Image Latent Editing with Edit Friendly DDPM and Semantic Guidance
318
+ </h3>
319
+ <h4 style="text-align: center; margin-bottom: 7px;">
320
+ <a href="https://editing-images-project.hf.space/" style="text-decoration: underline;" target="_blank">Project Page</a> | <a href="https://arxiv.org/abs/2307.00522" style="text-decoration: underline;" target="_blank">ArXiv</a>
321
+ </h4>
322
+
323
+ <p style="font-size: 0.9rem; margin: 0rem; line-height: 1.2em; margin-top:1em">
324
+ <a href="https://huggingface.co/spaces/editing-images/edit_friendly_ddpm_x_sega?duplicate=true">
325
+ <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3CWLGkA" alt="Duplicate Space"></a>
326
+ <p/>"""
327
+
328
+ help_text = """
329
+ - **Getting Started - edit images with DDPM X SEGA:**
330
+
331
+ The are 3 general setting options you can play with -
332
+
333
+ 1. **Pure DDPM Edit -** Describe the desired edited output image in detail
334
+ 2. **Pure SEGA Edit -** Keep the target prompt empty ***or*** with a description of the original image and add editing concepts for Semantic Gudiance editing
335
+ 3. **Combined -** Describe the desired edited output image in detail and add additional SEGA editing concepts on top
336
+ - **Getting Started - Tips**
337
+
338
+ While the best approach depends on your editing objective and source image, we can layout a few guiding tips to use as a starting point -
339
+
340
+ 1. **DDPM** is usually more suited for scene/style changes and major subject changes (for example ) while **SEGA** allows for more fine grained control, changes are more delicate, more suited for adding details (for example facial expressions and attributes, subtle style modifications, object adding/removing)
341
+ 2. The more you describe the scene in the target prompt (both the parts and details you wish to keep the same and those you wish to change), the better the result
342
+ 3. **Combining DDPM Edit with SEGA -**
343
+ Try dividing your editing objective to more significant scene/style/subject changes and detail adding/removing and more moderate changes. Then describe the major changes in a detailed target prompt and add the more fine grained details as SEGA concepts.
344
+ 4. **Reconstruction:** Using an empty source prompt + target prompt will lead to a perfect reconstruction
345
+ - **Fidelity vs creativity**:
346
+
347
+ Bigger values → more fidelity, smaller values → more creativity
348
+
349
+ 1. `Skip Steps`
350
+ 2. `Warmup` (SEGA)
351
+ 3. `Threshold` (SEGA)
352
+
353
+ Bigger values → more creativity, smaller values → more fidelity
354
+
355
+ 1. `Guidance Scale`
356
+ 2. `Concept Guidance Scale` (SEGA)
357
+ """
358
+
359
+ with gr.Blocks(css="style.css") as demo:
360
+ def update_counter(sega_concepts_counter, concept1, concept2, concept3):
361
+ if sega_concepts_counter == "":
362
+ sega_concepts_counter = sum(1 for concept in (concept1, concept2, concept3) if concept != '')
363
+ return sega_concepts_counter
364
+ def remove_concept(sega_concepts_counter, row_triggered):
365
+ sega_concepts_counter -= 1
366
+ rows_visibility = [gr.update(visible=False) for _ in range(4)]
367
+
368
+ if(row_triggered-1 > sega_concepts_counter):
369
+ rows_visibility[sega_concepts_counter] = gr.update(visible=True)
370
+ else:
371
+ rows_visibility[row_triggered-1] = gr.update(visible=True)
372
+
373
+ row1_visibility, row2_visibility, row3_visibility, row4_visibility = rows_visibility
374
+
375
+ guidance_scale_label = "Concept Guidance Scale"
376
+ # enable_interactive = gr.update(interactive=True)
377
+ return (gr.update(visible=False),
378
+ gr.update(visible=False, value="",),
379
+ gr.update(interactive=True, value=""),
380
+ gr.update(visible=False,label = guidance_scale_label),
381
+ gr.update(interactive=True, value =False),
382
+ gr.update(value=DEFAULT_WARMUP_STEPS),
383
+ gr.update(value=DEFAULT_THRESHOLD),
384
+ gr.update(visible=True),
385
+ gr.update(interactive=True, value="custom"),
386
+ row1_visibility,
387
+ row2_visibility,
388
+ row3_visibility,
389
+ row4_visibility,
390
+ sega_concepts_counter
391
+ )
392
+
393
+
394
+
395
+ def update_display_concept(button_label, edit_concept, neg_guidance, sega_concepts_counter):
396
+ sega_concepts_counter += 1
397
+ guidance_scale_label = "Concept Guidance Scale"
398
+ if(button_label=='Remove'):
399
+ neg_guidance = True
400
+ guidance_scale_label = "Negative Guidance Scale"
401
+
402
+ return (gr.update(visible=True), #boxn
403
+ gr.update(visible=True, value=edit_concept), #concept_n
404
+ gr.update(visible=True,label = guidance_scale_label), #guidance_scale_n
405
+ gr.update(value=neg_guidance),#neg_guidance_n
406
+ gr.update(visible=False), #row_n
407
+ gr.update(visible=True), #row_n+1
408
+ sega_concepts_counter
409
+ )
410
+
411
+
412
+ def display_editing_options(run_button, clear_button, sega_tab):
413
+ return run_button.update(visible=True), clear_button.update(visible=True), sega_tab.update(visible=True)
414
+
415
+ def update_interactive_mode(add_button_label):
416
+ if add_button_label == "Clear":
417
+ return gr.update(interactive=False), gr.update(interactive=False)
418
+ else:
419
+ return gr.update(interactive=True), gr.update(interactive=True)
420
+
421
+ def update_dropdown_parms(dropdown):
422
+ if dropdown == 'custom':
423
+ return DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,DEFAULT_WARMUP_STEPS, DEFAULT_THRESHOLD
424
+ elif dropdown =='style':
425
+ return STYLE_SEGA_CONCEPT_GUIDANCE_SCALE,STYLE_WARMUP_STEPS, STYLE_THRESHOLD
426
+ elif dropdown =='object':
427
+ return OBJECT_SEGA_CONCEPT_GUIDANCE_SCALE,OBJECT_WARMUP_STEPS, OBJECT_THRESHOLD
428
+ elif dropdown =='faces':
429
+ return FACE_SEGA_CONCEPT_GUIDANCE_SCALE,FACE_WARMUP_STEPS, FACE_THRESHOLD
430
+
431
+
432
+ def reset_do_inversion():
433
+ return True
434
+
435
+ def reset_do_reconstruction():
436
+ do_reconstruction = True
437
+ return do_reconstruction
438
+
439
+ def reset_image_caption():
440
+ return ""
441
+
442
+ def update_inversion_progress_visibility(input_image, do_inversion):
443
+ if do_inversion and not input_image is None:
444
+ return inversion_progress.update(visible=True)
445
+ else:
446
+ return inversion_progress.update(visible=False)
447
+
448
+ def update_edit_progress_visibility(input_image, do_inversion):
449
+ # if do_inversion and not input_image is None:
450
+ # return inversion_progress.update(visible=True)
451
+ # else:
452
+ return inversion_progress.update(visible=True)
453
+
454
+
455
+ gr.HTML(intro)
456
+ wts = gr.State()
457
+ zs = gr.State()
458
+ reconstruction = gr.State()
459
+ do_inversion = gr.State(value=True)
460
+ do_reconstruction = gr.State(value=True)
461
+ sega_concepts_counter = gr.State(0)
462
+ image_caption = gr.State(value="")
463
+
464
+
465
+
466
+ with gr.Row():
467
+ input_image = gr.Image(label="Input Image", interactive=True)
468
+ ddpm_edited_image = gr.Image(label=f"Pure DDPM Inversion Image", interactive=False, visible=False)
469
+ sega_edited_image = gr.Image(label=f"LEDITS Edited Image", interactive=False)
470
+ input_image.style(height=365, width=365)
471
+ ddpm_edited_image.style(height=365, width=365)
472
+ sega_edited_image.style(height=365, width=365)
473
+
474
+ with gr.Row():
475
+ with gr.Box(visible=False) as box1:
476
+ with gr.Row():
477
+ concept_1 = gr.Button(scale=3)
478
+ remove_concept1 = gr.Button("x", scale=1, min_width=10)
479
+ with gr.Row():
480
+ guidnace_scale_1 = gr.Slider(label='Concept Guidance Scale', minimum=1, maximum=30,
481
+ info="How strongly the concept should modify the image",
482
+ value=DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,
483
+ step=0.5, interactive=True)
484
+ with gr.Box(visible=False) as box2:
485
+ with gr.Row():
486
+ concept_2 = gr.Button(scale=3)
487
+ remove_concept2 = gr.Button("x", scale=1, min_width=10)
488
+ with gr.Row():
489
+ guidnace_scale_2 = gr.Slider(label='Concept Guidance Scale', minimum=1, maximum=30,
490
+ info="How strongly the concept should modify the image",
491
+ value=DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,
492
+ step=0.5, interactive=True)
493
+ with gr.Box(visible=False) as box3:
494
+ with gr.Row():
495
+ concept_3 = gr.Button(visible=False, scale=3)
496
+ remove_concept3 = gr.Button("x", scale=1, min_width=10)
497
+ with gr.Row():
498
+ guidnace_scale_3 = gr.Slider(label='Concept Guidance Scale', minimum=1, maximum=30,
499
+ info="How strongly the concept should modify the image",
500
+ value=DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,
501
+ step=0.5, interactive=True,visible=False)
502
+
503
+
504
+ with gr.Row():
505
+ inversion_progress = gr.Textbox(visible=False, label="Inversion progress")
506
+
507
+
508
+ with gr.Box():
509
+ intro_segs = gr.Markdown("Add/Remove Concepts from your Image <span style=\"font-size: 12px; color: rgb(156, 163, 175)\">with Semantic Guidance</span>")
510
+ # 1st SEGA concept
511
+ with gr.Row().style(mobile_collapse=False) as row1:
512
+ with gr.Column(scale=3, min_width=100):
513
+ with gr.Row().style(mobile_collapse=True):
514
+ # with gr.Column(scale=3, min_width=100):
515
+ edit_concept_1 = gr.Textbox(
516
+ label="Concept",
517
+ show_label=True,
518
+ max_lines=1, value="",
519
+ placeholder="E.g.: Sunglasses",
520
+ )
521
+ # with gr.Column(scale=2, min_width=100):# better mobile ui
522
+ dropdown1 = gr.Dropdown(label = "Edit Type", value ='custom' , choices=['custom','style', 'object', 'faces'])
523
+
524
+
525
+ with gr.Column(scale=1, min_width=100, visible=False):
526
+ neg_guidance_1 = gr.Checkbox(
527
+ label='Remove Concept?')
528
+
529
+ with gr.Column(scale=1, min_width=100):
530
+ with gr.Row().style(mobile_collapse=False): # better mobile ui
531
+ with gr.Column():
532
+ add_1 = gr.Button('Add')
533
+ remove_1 = gr.Button('Remove')
534
+
535
+
536
+ # 2nd SEGA concept
537
+ with gr.Row(visible=False).style(equal_height=True) as row2:
538
+ with gr.Column(scale=3, min_width=100):
539
+ with gr.Row().style(mobile_collapse=True): #better mobile UI
540
+ # with gr.Column(scale=3, min_width=100):
541
+ edit_concept_2 = gr.Textbox(
542
+ label="Concept",
543
+ show_label=True,
544
+ max_lines=1,
545
+ placeholder="E.g.: Realistic",
546
+ )
547
+ # with gr.Column(scale=2, min_width=100):# better mobile ui
548
+ dropdown2 = gr.Dropdown(label = "Edit Type", value ='custom' , choices=['custom','style', 'object', 'faces'])
549
+
550
+ with gr.Column(scale=1, min_width=100, visible=False):
551
+ neg_guidance_2 = gr.Checkbox(
552
+ label='Remove Concept?')
553
+
554
+ with gr.Column(scale=1, min_width=100):
555
+ with gr.Row().style(mobile_collapse=False): # better mobile ui
556
+ with gr.Column():
557
+ add_2 = gr.Button('Add')
558
+ remove_2 = gr.Button('Remove')
559
+
560
+ # 3rd SEGA concept
561
+ with gr.Row(visible=False).style(equal_height=True) as row3:
562
+ with gr.Column(scale=3, min_width=100):
563
+ with gr.Row().style(mobile_collapse=True): #better mobile UI
564
+ # with gr.Column(scale=3, min_width=100):
565
+ edit_concept_3 = gr.Textbox(
566
+ label="Concept",
567
+ show_label=True,
568
+ max_lines=1,
569
+ placeholder="E.g.: orange",
570
+ )
571
+ # with gr.Column(scale=2, min_width=100):
572
+ dropdown3 = gr.Dropdown(label = "Edit Type", value ='custom' , choices=['custom','style', 'object', 'faces'])
573
+
574
+ with gr.Column(scale=1, min_width=100, visible=False):
575
+ neg_guidance_3 = gr.Checkbox(
576
+ label='Remove Concept?',visible=True)
577
+
578
+ with gr.Column(scale=1, min_width=100):
579
+ with gr.Row().style(mobile_collapse=False): # better mobile ui
580
+ with gr.Column():
581
+ add_3 = gr.Button('Add')
582
+ remove_3 = gr.Button('Remove')
583
+
584
+ with gr.Row(visible=False).style(equal_height=True) as row4:
585
+ gr.Markdown("### Max of 3 concepts reached. Remove a concept to add more")
586
+
587
+ #with gr.Row(visible=False).style(mobile_collapse=False, equal_height=True):
588
+ # add_concept_button = gr.Button("+1 concept")
589
+
590
+
591
+
592
+ with gr.Row().style(mobile_collapse=False, equal_height=True):
593
+ tar_prompt = gr.Textbox(
594
+ label="Describe your edited image (optional)",
595
+ # show_label=False,
596
+ max_lines=1, value="", scale=3,
597
+ placeholder="Target prompt, DDPM Inversion", info = "DDPM Inversion Prompt. Can help with global changes, modify to what you would like to see"
598
+ )
599
+ # caption_button = gr.Button("Caption Image", scale=1)
600
+
601
+
602
+ with gr.Row():
603
+ run_button = gr.Button("Edit your image!", visible=True)
604
+
605
+
606
+ with gr.Accordion("Advanced Options", open=False):
607
+ with gr.Tabs() as tabs:
608
+
609
+ with gr.TabItem('General options', id=2):
610
+ with gr.Row():
611
+ with gr.Column(min_width=100):
612
+ clear_button = gr.Button("Clear", visible=True)
613
+ src_prompt = gr.Textbox(lines=1, label="Source Prompt", interactive=True, placeholder="")
614
+ steps = gr.Number(value=100, precision=0, label="Num Diffusion Steps", interactive=True)
615
+ src_cfg_scale = gr.Number(value=3.5, label=f"Source Guidance Scale", interactive=True)
616
+
617
+
618
+ with gr.Column(min_width=100):
619
+ reconstruct_button = gr.Button("Show Reconstruction", visible=False)
620
+ skip = gr.Slider(minimum=0, maximum=60, value=36, label="Skip Steps", interactive=True, info = "At which step to start denoising. Bigger values increase fidelity to input image")
621
+ tar_cfg_scale = gr.Slider(minimum=7, maximum=30,value=15, label=f"Guidance Scale", interactive=True)
622
+ seed = gr.Number(value=0, precision=0, label="Seed", interactive=True)
623
+ randomize_seed = gr.Checkbox(label='Randomize seed', value=False)
624
+
625
+ with gr.TabItem('SEGA options', id=3) as sega_advanced_tab:
626
+ # 1st SEGA concept
627
+ gr.Markdown("1st concept")
628
+ with gr.Row().style(mobile_collapse=False, equal_height=True):
629
+ warmup_1 = gr.Slider(label='Warmup', minimum=0, maximum=50,
630
+ value=DEFAULT_WARMUP_STEPS,
631
+ step=1, interactive=True, info="At which step to start applying semantic guidance. Bigger values reduce edit concept's effect")
632
+ threshold_1 = gr.Slider(label='Threshold', minimum=0.5, maximum=0.99,
633
+ value=DEFAULT_THRESHOLD, step=0.01, interactive=True,
634
+ info = "Lower the threshold for more effect (e.g. ~0.9 for style transfer)")
635
+
636
+ # 2nd SEGA concept
637
+ gr.Markdown("2nd concept")
638
+ with gr.Row() as row2_advanced:
639
+ warmup_2 = gr.Slider(label='Warmup', minimum=0, maximum=50,
640
+ value=DEFAULT_WARMUP_STEPS,
641
+ step=1, interactive=True, info="At which step to start applying semantic guidance. Bigger values reduce edit concept's effect")
642
+ threshold_2 = gr.Slider(label='Threshold', minimum=0.5, maximum=0.99,
643
+ value=DEFAULT_THRESHOLD,
644
+ step=0.01, interactive=True,
645
+ info = "Lower the threshold for more effect (e.g. ~0.9 for style transfer)")
646
+ # 3rd SEGA concept
647
+ gr.Markdown("3rd concept")
648
+ with gr.Row() as row3_advanced:
649
+ warmup_3 = gr.Slider(label='Warmup', minimum=0, maximum=50,
650
+ value=DEFAULT_WARMUP_STEPS, step=1,
651
+ interactive=True, info="At which step to start applying semantic guidance. Bigger values reduce edit concept's effect")
652
+ threshold_3 = gr.Slider(label='Threshold', minimum=0.5, maximum=0.99,
653
+ value=DEFAULT_THRESHOLD, step=0.01,
654
+ interactive=True,
655
+ info = "Lower the threshold for more effect (e.g. ~0.9 for style transfer)")
656
+
657
+ # caption_button.click(
658
+ # fn = caption_image,
659
+ # inputs = [input_image],
660
+ # outputs = [tar_prompt]
661
+ # )
662
+ #neg_guidance_1.change(fn = update_label, inputs=[neg_guidance_1], outputs=[add_1])
663
+ #neg_guidance_2.change(fn = update_label, inputs=[neg_guidance_2], outputs=[add_2])
664
+ #neg_guidance_3.change(fn = update_label, inputs=[neg_guidance_3], outputs=[add_3])
665
+ add_1.click(fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(fn = update_display_concept, inputs=[add_1, edit_concept_1, neg_guidance_1, sega_concepts_counter], outputs=[box1, concept_1, guidnace_scale_1,neg_guidance_1,row1, row2, sega_concepts_counter],queue=False)
666
+ add_2.click(fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(fn = update_display_concept, inputs=[add_2, edit_concept_2, neg_guidance_2, sega_concepts_counter], outputs=[box2, concept_2, guidnace_scale_2,neg_guidance_2,row2, row3, sega_concepts_counter],queue=False)
667
+ add_3.click(fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(fn = update_display_concept, inputs=[add_3, edit_concept_3, neg_guidance_3, sega_concepts_counter], outputs=[box3, concept_3, guidnace_scale_3,neg_guidance_3,row3, row4, sega_concepts_counter],queue=False)
668
+
669
+ remove_1.click(fn = update_display_concept, inputs=[remove_1, edit_concept_1, neg_guidance_1, sega_concepts_counter], outputs=[box1, concept_1, guidnace_scale_1,neg_guidance_1,row1, row2, sega_concepts_counter],queue=False)
670
+ remove_2.click(fn = update_display_concept, inputs=[remove_2, edit_concept_2, neg_guidance_2 ,sega_concepts_counter], outputs=[box2, concept_2, guidnace_scale_2,neg_guidance_2,row2, row3,sega_concepts_counter],queue=False)
671
+ remove_3.click(fn = update_display_concept, inputs=[remove_3, edit_concept_3, neg_guidance_3, sega_concepts_counter], outputs=[box3, concept_3, guidnace_scale_3,neg_guidance_3, row3, row4, sega_concepts_counter],queue=False)
672
+
673
+ remove_concept1.click(
674
+ fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(
675
+ fn = remove_concept, inputs=[sega_concepts_counter,gr.State(1)], outputs= [box1, concept_1, edit_concept_1, guidnace_scale_1,neg_guidance_1,warmup_1, threshold_1, add_1, dropdown1, row1, row2, row3, row4, sega_concepts_counter],queue=False)
676
+ remove_concept2.click(
677
+ fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(
678
+ fn = remove_concept, inputs=[sega_concepts_counter,gr.State(2)], outputs=[box2, concept_2, edit_concept_2, guidnace_scale_2,neg_guidance_2, warmup_2, threshold_2, add_2 , dropdown2, row1, row2, row3, row4, sega_concepts_counter],queue=False)
679
+ remove_concept3.click(
680
+ fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(
681
+ fn = remove_concept,inputs=[sega_concepts_counter,gr.State(3)], outputs=[box3, concept_3, edit_concept_3, guidnace_scale_3,neg_guidance_3,warmup_3, threshold_3, add_3, dropdown3, row1, row2, row3, row4, sega_concepts_counter],queue=False)
682
+
683
+ #add_concept_button.click(fn = update_display_concept, inputs=sega_concepts_counter,
684
+ # outputs= [row2, row2_advanced, row3, row3_advanced, add_concept_button, sega_concepts_counter], queue = False)
685
+
686
+ run_button.click(
687
+ fn=edit,
688
+ inputs=[input_image,
689
+ wts, zs,
690
+ tar_prompt,
691
+ image_caption,
692
+ steps,
693
+ skip,
694
+ tar_cfg_scale,
695
+ edit_concept_1,edit_concept_2,edit_concept_3,
696
+ guidnace_scale_1,guidnace_scale_2,guidnace_scale_3,
697
+ warmup_1, warmup_2, warmup_3,
698
+ neg_guidance_1, neg_guidance_2, neg_guidance_3,
699
+ threshold_1, threshold_2, threshold_3, do_reconstruction, reconstruction,
700
+ do_inversion,
701
+ seed,
702
+ randomize_seed,
703
+ src_prompt,
704
+ src_cfg_scale
705
+
706
+
707
+ ],
708
+ outputs=[sega_edited_image, reconstruct_button, do_reconstruction, reconstruction, wts, zs, do_inversion])
709
+ # .success(fn=update_gallery_display, inputs= [prev_output_image, sega_edited_image], outputs = [gallery, gallery, prev_output_image])
710
+
711
+
712
+ input_image.change(
713
+ fn = reset_do_inversion,
714
+ outputs = [do_inversion],
715
+ queue = False)
716
+ # Automatically start inverting upon input_image change
717
+ input_image.upload(
718
+ fn = reset_do_inversion,
719
+ outputs = [do_inversion],
720
+ queue = False).then(fn = caption_image,
721
+ inputs = [input_image],
722
+ outputs = [tar_prompt, image_caption]).then(fn = update_inversion_progress_visibility, inputs =[input_image,do_inversion],
723
+ outputs=[inversion_progress],queue=False).then(
724
+ fn=load_and_invert,
725
+ inputs=[input_image,
726
+ do_inversion,
727
+ seed, randomize_seed,
728
+ wts, zs,
729
+ src_prompt,
730
+ tar_prompt,
731
+ steps,
732
+ src_cfg_scale,
733
+ skip,
734
+ tar_cfg_scale,
735
+ ],
736
+ # outputs=[ddpm_edited_image, wts, zs, do_inversion],
737
+ outputs=[wts, zs, do_inversion, inversion_progress],
738
+ ).then(fn = update_inversion_progress_visibility, inputs =[input_image,do_inversion],
739
+ outputs=[inversion_progress],queue=False).then(
740
+ lambda: reconstruct_button.update(visible=False),
741
+ outputs=[reconstruct_button]).then(
742
+ fn = reset_do_reconstruction,
743
+ outputs = [do_reconstruction],
744
+ queue = False)
745
+
746
+
747
+ # Repeat inversion (and reconstruction) when these params are changed:
748
+ src_prompt.change(
749
+ fn = reset_do_inversion,
750
+ outputs = [do_inversion], queue = False).then(
751
+ fn = reset_do_reconstruction,
752
+ outputs = [do_reconstruction], queue = False)
753
+
754
+ steps.change(
755
+ fn = reset_do_inversion,
756
+ outputs = [do_inversion], queue = False).then(
757
+ fn = reset_do_reconstruction,
758
+ outputs = [do_reconstruction], queue = False)
759
+
760
+
761
+ src_cfg_scale.change(
762
+ fn = reset_do_inversion,
763
+ outputs = [do_inversion], queue = False).then(
764
+ fn = reset_do_reconstruction,
765
+ outputs = [do_reconstruction], queue = False)
766
+
767
+ # Repeat only reconstruction these params are changed:
768
+
769
+ tar_prompt.change(
770
+ fn = reset_do_reconstruction,
771
+ outputs = [do_reconstruction], queue = False)
772
+
773
+ tar_cfg_scale.change(
774
+ fn = reset_do_reconstruction,
775
+ outputs = [do_reconstruction], queue = False)
776
+
777
+ skip.change(
778
+ fn = reset_do_reconstruction,
779
+ outputs = [do_reconstruction], queue = False)
780
+
781
+ dropdown1.change(fn=update_dropdown_parms, inputs = [dropdown1], outputs = [guidnace_scale_1,warmup_1, threshold_1])
782
+ dropdown2.change(fn=update_dropdown_parms, inputs = [dropdown2], outputs = [guidnace_scale_2,warmup_2, threshold_2])
783
+ dropdown3.change(fn=update_dropdown_parms, inputs = [dropdown3], outputs = [guidnace_scale_3,warmup_3, threshold_3])
784
+
785
+ clear_components = [input_image,ddpm_edited_image,ddpm_edited_image,sega_edited_image, do_inversion,
786
+ src_prompt, steps, src_cfg_scale, seed,
787
+ tar_prompt, skip, tar_cfg_scale, reconstruct_button,reconstruct_button,
788
+ edit_concept_1, guidnace_scale_1,guidnace_scale_1,warmup_1, threshold_1, neg_guidance_1,dropdown1, concept_1, concept_1, row1,
789
+ edit_concept_2, guidnace_scale_2,guidnace_scale_2,warmup_2, threshold_2, neg_guidance_2,dropdown2, concept_2, concept_2, row2,
790
+ edit_concept_3, guidnace_scale_3,guidnace_scale_3,warmup_3, threshold_3, neg_guidance_3,dropdown3, concept_3,concept_3, row3,
791
+ row4,sega_concepts_counter, box1, box2, box3 ]
792
+
793
+ clear_components_output_vals = [None, None,ddpm_edited_image.update(visible=False), None, True,
794
+ "", DEFAULT_DIFFUSION_STEPS, DEFAULT_SOURCE_GUIDANCE_SCALE, DEFAULT_SEED,
795
+ "", DEFAULT_SKIP_STEPS, DEFAULT_TARGET_GUIDANCE_SCALE, reconstruct_button.update(value="Show Reconstruction"),reconstruct_button.update(visible=False),
796
+ "", DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,guidnace_scale_1.update(visible=False), DEFAULT_WARMUP_STEPS, DEFAULT_THRESHOLD, DEFAULT_NEGATIVE_GUIDANCE, "custom","", concept_1.update(visible=False), row1.update(visible=True),
797
+ "", DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,guidnace_scale_2.update(visible=False), DEFAULT_WARMUP_STEPS, DEFAULT_THRESHOLD, DEFAULT_NEGATIVE_GUIDANCE, "custom","", concept_2.update(visible=False), row2.update(visible=False),
798
+ "", DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,guidnace_scale_3.update(visible=False), DEFAULT_WARMUP_STEPS, DEFAULT_THRESHOLD, DEFAULT_NEGATIVE_GUIDANCE, "custom","",concept_3.update(visible=False), row3.update(visible=False), row4.update(visible=False), gr.update(value=0),
799
+ box1.update(visible=False), box2.update(visible=False), box3.update(visible=False)]
800
+
801
+
802
+ clear_button.click(lambda: clear_components_output_vals, outputs =clear_components)
803
+
804
+ reconstruct_button.click(lambda: ddpm_edited_image.update(visible=True), outputs=[ddpm_edited_image]).then(fn = reconstruct,
805
+ inputs = [tar_prompt,
806
+ image_caption,
807
+ tar_cfg_scale,
808
+ skip,
809
+ wts, zs,
810
+ do_reconstruction,
811
+ reconstruction,
812
+ reconstruct_button],
813
+ outputs = [ddpm_edited_image,reconstruction, ddpm_edited_image, do_reconstruction, reconstruct_button])
814
+
815
+ randomize_seed.change(
816
+ fn = randomize_seed_fn,
817
+ inputs = [seed, randomize_seed],
818
+ outputs = [seed],
819
+ queue = False)
820
+
821
+
822
+
823
+ gr.Examples(
824
+ label='Examples',
825
+ fn=swap_visibilities,
826
+ run_on_click=True,
827
+ examples=get_example(),
828
+ inputs=[input_image,
829
+ edit_concept_1,
830
+ edit_concept_2,
831
+ tar_prompt,
832
+ sega_edited_image,
833
+ guidnace_scale_1,
834
+ guidnace_scale_2,
835
+ warmup_1,
836
+ warmup_2,
837
+ neg_guidance_1,
838
+ neg_guidance_2,
839
+ steps,
840
+ skip,
841
+ tar_cfg_scale,
842
+ sega_concepts_counter
843
+ ],
844
+ outputs=[box1, concept_1, guidnace_scale_1,neg_guidance_1, row1, row2,box2, concept_2, guidnace_scale_2,neg_guidance_2,row2, row3,sega_concepts_counter],
845
+ cache_examples=True
846
+ )
847
+
848
+
849
+ demo.queue()
850
+ demo.launch()
constants.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ###############
2
+ # conststants #
3
+ ###############
4
+ DEFAULT_TARGET_GUIDANCE_SCALE = 15
5
+ DEFAULT_SOURCE_GUIDANCE_SCALE = 3.5
6
+ DEFAULT_DIFFUSION_STEPS = 100
7
+ DEFAULT_SKIP_STEPS = 36
8
+ DEFAULT_SEED = 0
9
+
10
+
11
+ DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE = 7
12
+ DEFAULT_WARMUP_STEPS = 2
13
+ DEFAULT_THRESHOLD = 0.95
14
+ DEFAULT_NEGATIVE_GUIDANCE=False
15
+
16
+ STYLE_SEGA_CONCEPT_GUIDANCE_SCALE = 8
17
+ STYLE_WARMUP_STEPS = 2
18
+ STYLE_THRESHOLD = 0.92
19
+
20
+ FACE_SEGA_CONCEPT_GUIDANCE_SCALE = 5
21
+ FACE_WARMUP_STEPS = 2
22
+ FACE_THRESHOLD = 0.95
23
+
24
+ OBJECT_SEGA_CONCEPT_GUIDANCE_SCALE = 15
25
+ OBJECT_WARMUP_STEPS = 5
26
+ OBJECT_THRESHOLD = 0.95
examples/butterfly_input.jpg ADDED
examples/butterfly_output.jpg ADDED
examples/ddpm_a_cat_sitting_next_to_a_mirror.png ADDED
examples/ddpm_a_robot_wearing_a_brown_hoodie_in_a_crowded_street.png ADDED
examples/ddpm_glass_walls.png ADDED
examples/ddpm_sega_glass_walls_gian_elephant.png ADDED
examples/ddpm_sega_painting_of_a_robot_wearing_a_brown_hoodie_in_a_crowded_street.png ADDED
examples/ddpm_sega_plus_pink_drawings_of_muffins.png ADDED
examples/ddpm_sega_watercolor_painting_a_cat_sitting_next_to_a_mirror_plus_dog_minus_cat.png ADDED
examples/ddpm_wall_with_framed_photos.png ADDED
examples/ddpm_watercolor_painting_a_cat_sitting_next_to_a_mirror.png ADDED
examples/flower_field_input.jpg ADDED
examples/flower_field_output.jpg ADDED
examples/flower_field_output_2.jpg ADDED
examples/girl_with_pearl_earring_input.png ADDED
examples/girl_with_pearl_earring_output.png ADDED
examples/lemons_input.jpg ADDED
examples/lemons_output.jpg ADDED
examples/rockey_shore_input.jpg ADDED
examples/rockey_shore_output.jpg ADDED
examples/source_a_cat_sitting_next_to_a_mirror.jpeg ADDED
examples/source_a_man_wearing_a_brown_hoodie_in_a_crowded_street.jpeg ADDED

Git LFS Details

  • SHA256: 8897301992b63b4cfb7f67c9a7313e3ce97d3fa96d11fc29e4c70eb7e96fc610
  • Pointer size: 132 Bytes
  • Size of remote file: 2.49 MB
examples/source_an_empty_room_with_concrete_walls.jpg ADDED
examples/source_wall_with_framed_photos.jpeg ADDED

Git LFS Details

  • SHA256: 1c21bd9f28e775a2b4de9aaa8fe8aaa8ed7f064f7b0ef5f415e2152d427f5daa
  • Pointer size: 132 Bytes
  • Size of remote file: 5.72 MB
inversion_utils.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import os
3
+ from tqdm import tqdm
4
+ from PIL import Image, ImageDraw ,ImageFont
5
+ from matplotlib import pyplot as plt
6
+ import torchvision.transforms as T
7
+ import os
8
+ import yaml
9
+ import numpy as np
10
+
11
+
12
+ def load_512(image_path, left=0, right=0, top=0, bottom=0, device=None):
13
+ if type(image_path) is str:
14
+ image = np.array(Image.open(image_path).convert('RGB'))[:, :, :3]
15
+ else:
16
+ image = image_path
17
+ h, w, c = image.shape
18
+ left = min(left, w-1)
19
+ right = min(right, w - left - 1)
20
+ top = min(top, h - left - 1)
21
+ bottom = min(bottom, h - top - 1)
22
+ image = image[top:h-bottom, left:w-right]
23
+ h, w, c = image.shape
24
+ if h < w:
25
+ offset = (w - h) // 2
26
+ image = image[:, offset:offset + h]
27
+ elif w < h:
28
+ offset = (h - w) // 2
29
+ image = image[offset:offset + w]
30
+ image = np.array(Image.fromarray(image).resize((512, 512)))
31
+ image = torch.from_numpy(image).float() / 127.5 - 1
32
+ image = image.permute(2, 0, 1).unsqueeze(0).to(device, dtype =torch.float16)
33
+
34
+ return image
35
+
36
+
37
+
38
+ def mu_tilde(model, xt,x0, timestep):
39
+ "mu_tilde(x_t, x_0) DDPM paper eq. 7"
40
+ prev_timestep = timestep - model.scheduler.config.num_train_timesteps // model.scheduler.num_inference_steps
41
+ alpha_prod_t_prev = model.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else model.scheduler.final_alpha_cumprod
42
+ alpha_t = model.scheduler.alphas[timestep]
43
+ beta_t = 1 - alpha_t
44
+ alpha_bar = model.scheduler.alphas_cumprod[timestep]
45
+ return ((alpha_prod_t_prev ** 0.5 * beta_t) / (1-alpha_bar)) * x0 + ((alpha_t**0.5 *(1-alpha_prod_t_prev)) / (1- alpha_bar))*xt
46
+
47
+ def sample_xts_from_x0(model, x0, num_inference_steps=50):
48
+ """
49
+ Samples from P(x_1:T|x_0)
50
+ """
51
+ # torch.manual_seed(43256465436)
52
+ alpha_bar = model.scheduler.alphas_cumprod
53
+ sqrt_one_minus_alpha_bar = (1-alpha_bar) ** 0.5
54
+ alphas = model.scheduler.alphas
55
+ betas = 1 - alphas
56
+ variance_noise_shape = (
57
+ num_inference_steps,
58
+ model.unet.in_channels,
59
+ model.unet.sample_size,
60
+ model.unet.sample_size)
61
+
62
+ timesteps = model.scheduler.timesteps.to(model.device)
63
+ t_to_idx = {int(v):k for k,v in enumerate(timesteps)}
64
+ xts = torch.zeros(variance_noise_shape).to(x0.device, dtype =torch.float16)
65
+ for t in reversed(timesteps):
66
+ idx = t_to_idx[int(t)]
67
+ xts[idx] = x0 * (alpha_bar[t] ** 0.5) + torch.randn_like(x0, dtype =torch.float16) * sqrt_one_minus_alpha_bar[t]
68
+ xts = torch.cat([xts, x0 ],dim = 0)
69
+
70
+ return xts
71
+
72
+ def encode_text(model, prompts):
73
+ text_input = model.tokenizer(
74
+ prompts,
75
+ padding="max_length",
76
+ max_length=model.tokenizer.model_max_length,
77
+ truncation=True,
78
+ return_tensors="pt",
79
+ )
80
+ with torch.no_grad():
81
+ text_encoding = model.text_encoder(text_input.input_ids.to(model.device))[0]
82
+ return text_encoding
83
+
84
+ def forward_step(model, model_output, timestep, sample):
85
+ next_timestep = min(model.scheduler.config.num_train_timesteps - 2,
86
+ timestep + model.scheduler.config.num_train_timesteps // model.scheduler.num_inference_steps)
87
+
88
+ # 2. compute alphas, betas
89
+ alpha_prod_t = model.scheduler.alphas_cumprod[timestep]
90
+ # alpha_prod_t_next = self.scheduler.alphas_cumprod[next_timestep] if next_ltimestep >= 0 else self.scheduler.final_alpha_cumprod
91
+
92
+ beta_prod_t = 1 - alpha_prod_t
93
+
94
+ # 3. compute predicted original sample from predicted noise also called
95
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
96
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
97
+
98
+ # 5. TODO: simple noising implementatiom
99
+ next_sample = model.scheduler.add_noise(pred_original_sample,
100
+ model_output,
101
+ torch.LongTensor([next_timestep]))
102
+ return next_sample
103
+
104
+
105
+ def get_variance(model, timestep): #, prev_timestep):
106
+ prev_timestep = timestep - model.scheduler.config.num_train_timesteps // model.scheduler.num_inference_steps
107
+ alpha_prod_t = model.scheduler.alphas_cumprod[timestep]
108
+ alpha_prod_t_prev = model.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else model.scheduler.final_alpha_cumprod
109
+ beta_prod_t = 1 - alpha_prod_t
110
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
111
+ variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
112
+ return variance
113
+
114
+ def inversion_forward_process(model, x0,
115
+ etas = None,
116
+ prog_bar = False,
117
+ prompt = "",
118
+ cfg_scale = 3.5,
119
+ num_inference_steps=50, eps = None):
120
+
121
+ if not prompt=="":
122
+ text_embeddings = encode_text(model, prompt)
123
+ uncond_embedding = encode_text(model, "")
124
+ timesteps = model.scheduler.timesteps.to(model.device)
125
+ variance_noise_shape = (
126
+ num_inference_steps,
127
+ model.unet.in_channels,
128
+ model.unet.sample_size,
129
+ model.unet.sample_size)
130
+ if etas is None or (type(etas) in [int, float] and etas == 0):
131
+ eta_is_zero = True
132
+ zs = None
133
+ else:
134
+ eta_is_zero = False
135
+ if type(etas) in [int, float]: etas = [etas]*model.scheduler.num_inference_steps
136
+ xts = sample_xts_from_x0(model, x0, num_inference_steps=num_inference_steps)
137
+ alpha_bar = model.scheduler.alphas_cumprod
138
+ zs = torch.zeros(size=variance_noise_shape, device=model.device, dtype =torch.float16)
139
+
140
+ t_to_idx = {int(v):k for k,v in enumerate(timesteps)}
141
+ xt = x0
142
+ op = tqdm(reversed(timesteps), desc= "Inverting...") if prog_bar else reversed(timesteps)
143
+
144
+ for t in op:
145
+ idx = t_to_idx[int(t)]
146
+ # 1. predict noise residual
147
+ if not eta_is_zero:
148
+ xt = xts[idx][None]
149
+
150
+ with torch.no_grad():
151
+ out = model.unet.forward(xt, timestep = t, encoder_hidden_states = uncond_embedding)
152
+ if not prompt=="":
153
+ cond_out = model.unet.forward(xt, timestep=t, encoder_hidden_states = text_embeddings)
154
+
155
+ if not prompt=="":
156
+ ## classifier free guidance
157
+ noise_pred = out.sample + cfg_scale * (cond_out.sample - out.sample)
158
+ else:
159
+ noise_pred = out.sample
160
+
161
+ if eta_is_zero:
162
+ # 2. compute more noisy image and set x_t -> x_t+1
163
+ xt = forward_step(model, noise_pred, t, xt)
164
+
165
+ else:
166
+ xtm1 = xts[idx+1][None]
167
+ # pred of x0
168
+ pred_original_sample = (xt - (1-alpha_bar[t]) ** 0.5 * noise_pred ) / alpha_bar[t] ** 0.5
169
+
170
+ # direction to xt
171
+ prev_timestep = t - model.scheduler.config.num_train_timesteps // model.scheduler.num_inference_steps
172
+ alpha_prod_t_prev = model.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else model.scheduler.final_alpha_cumprod
173
+
174
+ variance = get_variance(model, t)
175
+ pred_sample_direction = (1 - alpha_prod_t_prev - etas[idx] * variance ) ** (0.5) * noise_pred
176
+
177
+ mu_xt = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
178
+
179
+ z = (xtm1 - mu_xt ) / ( etas[idx] * variance ** 0.5 )
180
+ zs[idx] = z
181
+
182
+ # correction to avoid error accumulation
183
+ xtm1 = mu_xt + ( etas[idx] * variance ** 0.5 )*z
184
+ xts[idx+1] = xtm1
185
+
186
+ if not zs is None:
187
+ zs[-1] = torch.zeros_like(zs[-1])
188
+
189
+ return xt, zs, xts
190
+
191
+
192
+ def reverse_step(model, model_output, timestep, sample, eta = 0, variance_noise=None):
193
+ # 1. get previous step value (=t-1)
194
+ prev_timestep = timestep - model.scheduler.config.num_train_timesteps // model.scheduler.num_inference_steps
195
+ # 2. compute alphas, betas
196
+ alpha_prod_t = model.scheduler.alphas_cumprod[timestep]
197
+ alpha_prod_t_prev = model.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else model.scheduler.final_alpha_cumprod
198
+ beta_prod_t = 1 - alpha_prod_t
199
+ # 3. compute predicted original sample from predicted noise also called
200
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
201
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
202
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
203
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
204
+ # variance = self.scheduler._get_variance(timestep, prev_timestep)
205
+ variance = get_variance(model, timestep) #, prev_timestep)
206
+ std_dev_t = eta * variance ** (0.5)
207
+ # Take care of asymetric reverse process (asyrp)
208
+ model_output_direction = model_output
209
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
210
+ # pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output_direction
211
+ pred_sample_direction = (1 - alpha_prod_t_prev - eta * variance) ** (0.5) * model_output_direction
212
+ # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
213
+ prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
214
+ # 8. Add noice if eta > 0
215
+ if eta > 0:
216
+ if variance_noise is None:
217
+ variance_noise = torch.randn(model_output.shape, device=model.device, dtype =torch.float16)
218
+ sigma_z = eta * variance ** (0.5) * variance_noise
219
+ prev_sample = prev_sample + sigma_z
220
+
221
+ return prev_sample
222
+
223
+ def inversion_reverse_process(model,
224
+ xT,
225
+ etas = 0,
226
+ prompts = "",
227
+ cfg_scales = None,
228
+ prog_bar = False,
229
+ zs = None,
230
+ controller=None,
231
+ asyrp = False):
232
+
233
+ batch_size = len(prompts)
234
+
235
+ cfg_scales_tensor = torch.Tensor(cfg_scales).view(-1,1,1,1).to(model.device, dtype=torch.float16)
236
+
237
+ text_embeddings = encode_text(model, prompts)
238
+ uncond_embedding = encode_text(model, [""] * batch_size)
239
+
240
+ if etas is None: etas = 0
241
+ if type(etas) in [int, float]: etas = [etas]*model.scheduler.num_inference_steps
242
+ assert len(etas) == model.scheduler.num_inference_steps
243
+ timesteps = model.scheduler.timesteps.to(model.device)
244
+
245
+ xt = xT.expand(batch_size, -1, -1, -1)
246
+ op = tqdm(timesteps[-zs.shape[0]:]) if prog_bar else timesteps[-zs.shape[0]:]
247
+
248
+ t_to_idx = {int(v):k for k,v in enumerate(timesteps[-zs.shape[0]:])}
249
+
250
+ for t in op:
251
+ idx = t_to_idx[int(t)]
252
+ ## Unconditional embedding
253
+ with torch.no_grad():
254
+ uncond_out = model.unet.forward(xt, timestep = t,
255
+ encoder_hidden_states = uncond_embedding)
256
+
257
+ ## Conditional embedding
258
+ if prompts:
259
+ with torch.no_grad():
260
+ cond_out = model.unet.forward(xt, timestep = t,
261
+ encoder_hidden_states = text_embeddings)
262
+
263
+
264
+ z = zs[idx] if not zs is None else None
265
+ z = z.expand(batch_size, -1, -1, -1)
266
+ if prompts:
267
+ ## classifier free guidance
268
+ noise_pred = uncond_out.sample + cfg_scales_tensor * (cond_out.sample - uncond_out.sample)
269
+ else:
270
+ noise_pred = uncond_out.sample
271
+ # 2. compute less noisy image and set x_t -> x_t-1
272
+ xt = reverse_step(model, noise_pred, t, xt, eta = etas[idx], variance_noise = z)
273
+ if controller is not None:
274
+ xt = controller.step_callback(xt)
275
+ return xt, zs
modified_pipeline_semantic_stable_diffusion.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import inspect
3
+ import warnings
4
+ from itertools import repeat
5
+ from typing import Callable, List, Optional, Union
6
+
7
+ import torch
8
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers.image_processor import VaeImageProcessor
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
12
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
13
+ from diffusers.schedulers import KarrasDiffusionSchedulers
14
+ from diffusers.utils import logging, randn_tensor
15
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
16
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
17
+ # from . import SemanticStableDiffusionPipelineOutput
18
+
19
+
20
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
21
+
22
+
23
+ class SemanticStableDiffusionPipeline(DiffusionPipeline):
24
+ r"""
25
+ Pipeline for text-to-image generation with latent editing.
26
+
27
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
28
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
29
+
30
+ This model builds on the implementation of ['StableDiffusionPipeline']
31
+
32
+ Args:
33
+ vae ([`AutoencoderKL`]):
34
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
35
+ text_encoder ([`CLIPTextModel`]):
36
+ Frozen text-encoder. Stable Diffusion uses the text portion of
37
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
38
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
39
+ tokenizer (`CLIPTokenizer`):
40
+ Tokenizer of class
41
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
42
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
43
+ scheduler ([`SchedulerMixin`]):
44
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
45
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
46
+ safety_checker ([`Q16SafetyChecker`]):
47
+ Classification module that estimates whether generated images could be considered offensive or harmful.
48
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
49
+ feature_extractor ([`CLIPImageProcessor`]):
50
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
51
+ """
52
+
53
+ _optional_components = ["safety_checker", "feature_extractor"]
54
+
55
+ def __init__(
56
+ self,
57
+ vae: AutoencoderKL,
58
+ text_encoder: CLIPTextModel,
59
+ tokenizer: CLIPTokenizer,
60
+ unet: UNet2DConditionModel,
61
+ scheduler: KarrasDiffusionSchedulers,
62
+ safety_checker: StableDiffusionSafetyChecker,
63
+ feature_extractor: CLIPImageProcessor,
64
+ requires_safety_checker: bool = True,
65
+ ):
66
+ super().__init__()
67
+
68
+ if safety_checker is None and requires_safety_checker:
69
+ logger.warning(
70
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
71
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
72
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
73
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
74
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
75
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
76
+ )
77
+
78
+ if safety_checker is not None and feature_extractor is None:
79
+ raise ValueError(
80
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
81
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
82
+ )
83
+
84
+ self.register_modules(
85
+ vae=vae,
86
+ text_encoder=text_encoder,
87
+ tokenizer=tokenizer,
88
+ unet=unet,
89
+ scheduler=scheduler,
90
+ safety_checker=safety_checker,
91
+ feature_extractor=feature_extractor,
92
+ )
93
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
94
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
95
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
96
+
97
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
98
+ def run_safety_checker(self, image, device, dtype):
99
+ if self.safety_checker is None:
100
+ has_nsfw_concept = None
101
+ else:
102
+ if torch.is_tensor(image):
103
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
104
+ else:
105
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
106
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
107
+ image, has_nsfw_concept = self.safety_checker(
108
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
109
+ )
110
+ return image, has_nsfw_concept
111
+
112
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
113
+ def decode_latents(self, latents):
114
+ warnings.warn(
115
+ "The decode_latents method is deprecated and will be removed in a future version. Please"
116
+ " use VaeImageProcessor instead",
117
+ FutureWarning,
118
+ )
119
+ latents = 1 / self.vae.config.scaling_factor * latents
120
+ image = self.vae.decode(latents, return_dict=False)[0]
121
+ image = (image / 2 + 0.5).clamp(0, 1)
122
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
123
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
124
+ return image
125
+
126
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
127
+ def prepare_extra_step_kwargs(self, generator, eta):
128
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
129
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
130
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
131
+ # and should be between [0, 1]
132
+
133
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
134
+ extra_step_kwargs = {}
135
+ if accepts_eta:
136
+ extra_step_kwargs["eta"] = eta
137
+
138
+ # check if the scheduler accepts generator
139
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
140
+ if accepts_generator:
141
+ extra_step_kwargs["generator"] = generator
142
+ return extra_step_kwargs
143
+
144
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
145
+ def check_inputs(
146
+ self,
147
+ prompt,
148
+ height,
149
+ width,
150
+ callback_steps,
151
+ negative_prompt=None,
152
+ prompt_embeds=None,
153
+ negative_prompt_embeds=None,
154
+ ):
155
+ if height % 8 != 0 or width % 8 != 0:
156
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
157
+
158
+ if (callback_steps is None) or (
159
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
160
+ ):
161
+ raise ValueError(
162
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
163
+ f" {type(callback_steps)}."
164
+ )
165
+
166
+ if prompt is not None and prompt_embeds is not None:
167
+ raise ValueError(
168
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
169
+ " only forward one of the two."
170
+ )
171
+ elif prompt is None and prompt_embeds is None:
172
+ raise ValueError(
173
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
174
+ )
175
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
176
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
177
+
178
+ if negative_prompt is not None and negative_prompt_embeds is not None:
179
+ raise ValueError(
180
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
181
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
182
+ )
183
+
184
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
185
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
186
+ raise ValueError(
187
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
188
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
189
+ f" {negative_prompt_embeds.shape}."
190
+ )
191
+
192
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
193
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
194
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
195
+ if isinstance(generator, list) and len(generator) != batch_size:
196
+ raise ValueError(
197
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
198
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
199
+ )
200
+
201
+ if latents is None:
202
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
203
+ else:
204
+ latents = latents.to(device)
205
+
206
+ # scale the initial noise by the standard deviation required by the scheduler
207
+ latents = latents * self.scheduler.init_noise_sigma
208
+ return latents
209
+
210
+ @torch.no_grad()
211
+ def __call__(
212
+ self,
213
+ prompt: Union[str, List[str]],
214
+ height: Optional[int] = None,
215
+ width: Optional[int] = None,
216
+ num_inference_steps: int = 50,
217
+ guidance_scale: float = 7.5,
218
+ negative_prompt: Optional[Union[str, List[str]]] = None,
219
+ num_images_per_prompt: int = 1,
220
+ eta: float = 0.0,
221
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
222
+ latents: Optional[torch.FloatTensor] = None,
223
+ output_type: Optional[str] = "pil",
224
+ return_dict: bool = True,
225
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
226
+ callback_steps: int = 1,
227
+ editing_prompt: Optional[Union[str, List[str]]] = None,
228
+ editing_prompt_embeddings: Optional[torch.Tensor] = None,
229
+ reverse_editing_direction: Optional[Union[bool, List[bool]]] = False,
230
+ edit_guidance_scale: Optional[Union[float, List[float]]] = 5,
231
+ edit_warmup_steps: Optional[Union[int, List[int]]] = 10,
232
+ edit_cooldown_steps: Optional[Union[int, List[int]]] = None,
233
+ edit_threshold: Optional[Union[float, List[float]]] = 0.9,
234
+ edit_momentum_scale: Optional[float] = 0.1,
235
+ edit_mom_beta: Optional[float] = 0.4,
236
+ edit_weights: Optional[List[float]] = None,
237
+ sem_guidance: Optional[List[torch.Tensor]] = None,
238
+
239
+ # DDPM additions
240
+ use_ddpm: bool = False,
241
+ wts: Optional[List[torch.Tensor]] = None,
242
+ zs: Optional[List[torch.Tensor]] = None
243
+ ):
244
+ r"""
245
+ Function invoked when calling the pipeline for generation.
246
+
247
+ Args:
248
+ prompt (`str` or `List[str]`):
249
+ The prompt or prompts to guide the image generation.
250
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
251
+ The height in pixels of the generated image.
252
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
253
+ The width in pixels of the generated image.
254
+ num_inference_steps (`int`, *optional*, defaults to 50):
255
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
256
+ expense of slower inference.
257
+ guidance_scale (`float`, *optional*, defaults to 7.5):
258
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
259
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
260
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
261
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
262
+ usually at the expense of lower image quality.
263
+ negative_prompt (`str` or `List[str]`, *optional*):
264
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
265
+ if `guidance_scale` is less than `1`).
266
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
267
+ The number of images to generate per prompt.
268
+ eta (`float`, *optional*, defaults to 0.0):
269
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
270
+ [`schedulers.DDIMScheduler`], will be ignored for others.
271
+ generator (`torch.Generator`, *optional*):
272
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
273
+ to make generation deterministic.
274
+ latents (`torch.FloatTensor`, *optional*):
275
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
276
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
277
+ tensor will ge generated by sampling using the supplied random `generator`.
278
+ output_type (`str`, *optional*, defaults to `"pil"`):
279
+ The output format of the generate image. Choose between
280
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
281
+ return_dict (`bool`, *optional*, defaults to `True`):
282
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
283
+ plain tuple.
284
+ callback (`Callable`, *optional*):
285
+ A function that will be called every `callback_steps` steps during inference. The function will be
286
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
287
+ callback_steps (`int`, *optional*, defaults to 1):
288
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
289
+ called at every step.
290
+ editing_prompt (`str` or `List[str]`, *optional*):
291
+ The prompt or prompts to use for Semantic guidance. Semantic guidance is disabled by setting
292
+ `editing_prompt = None`. Guidance direction of prompt should be specified via
293
+ `reverse_editing_direction`.
294
+ editing_prompt_embeddings (`torch.Tensor>`, *optional*):
295
+ Pre-computed embeddings to use for semantic guidance. Guidance direction of embedding should be
296
+ specified via `reverse_editing_direction`.
297
+ reverse_editing_direction (`bool` or `List[bool]`, *optional*, defaults to `False`):
298
+ Whether the corresponding prompt in `editing_prompt` should be increased or decreased.
299
+ edit_guidance_scale (`float` or `List[float]`, *optional*, defaults to 5):
300
+ Guidance scale for semantic guidance. If provided as list values should correspond to `editing_prompt`.
301
+ `edit_guidance_scale` is defined as `s_e` of equation 6 of [SEGA
302
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
303
+ edit_warmup_steps (`float` or `List[float]`, *optional*, defaults to 10):
304
+ Number of diffusion steps (for each prompt) for which semantic guidance will not be applied. Momentum
305
+ will still be calculated for those steps and applied once all warmup periods are over.
306
+ `edit_warmup_steps` is defined as `delta` (δ) of [SEGA Paper](https://arxiv.org/pdf/2301.12247.pdf).
307
+ edit_cooldown_steps (`float` or `List[float]`, *optional*, defaults to `None`):
308
+ Number of diffusion steps (for each prompt) after which semantic guidance will no longer be applied.
309
+ edit_threshold (`float` or `List[float]`, *optional*, defaults to 0.9):
310
+ Threshold of semantic guidance.
311
+ edit_momentum_scale (`float`, *optional*, defaults to 0.1):
312
+ Scale of the momentum to be added to the semantic guidance at each diffusion step. If set to 0.0
313
+ momentum will be disabled. Momentum is already built up during warmup, i.e. for diffusion steps smaller
314
+ than `sld_warmup_steps`. Momentum will only be added to latent guidance once all warmup periods are
315
+ finished. `edit_momentum_scale` is defined as `s_m` of equation 7 of [SEGA
316
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
317
+ edit_mom_beta (`float`, *optional*, defaults to 0.4):
318
+ Defines how semantic guidance momentum builds up. `edit_mom_beta` indicates how much of the previous
319
+ momentum will be kept. Momentum is already built up during warmup, i.e. for diffusion steps smaller
320
+ than `edit_warmup_steps`. `edit_mom_beta` is defined as `beta_m` (β) of equation 8 of [SEGA
321
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
322
+ edit_weights (`List[float]`, *optional*, defaults to `None`):
323
+ Indicates how much each individual concept should influence the overall guidance. If no weights are
324
+ provided all concepts are applied equally. `edit_mom_beta` is defined as `g_i` of equation 9 of [SEGA
325
+ Paper](https://arxiv.org/pdf/2301.12247.pdf).
326
+ sem_guidance (`List[torch.Tensor]`, *optional*):
327
+ List of pre-generated guidance vectors to be applied at generation. Length of the list has to
328
+ correspond to `num_inference_steps`.
329
+
330
+ Returns:
331
+ [`~pipelines.semantic_stable_diffusion.SemanticStableDiffusionPipelineOutput`] or `tuple`:
332
+ [`~pipelines.semantic_stable_diffusion.SemanticStableDiffusionPipelineOutput`] if `return_dict` is True,
333
+ otherwise a `tuple. When returning a tuple, the first element is a list with the generated images, and the
334
+ second element is a list of `bool`s denoting whether the corresponding generated image likely represents
335
+ "not-safe-for-work" (nsfw) content, according to the `safety_checker`.
336
+ """
337
+ # 0. Default height and width to unet
338
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
339
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
340
+
341
+ # 1. Check inputs. Raise error if not correct
342
+ self.check_inputs(prompt, height, width, callback_steps)
343
+
344
+ # 2. Define call parameters
345
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
346
+
347
+ if editing_prompt:
348
+ enable_edit_guidance = True
349
+ if isinstance(editing_prompt, str):
350
+ editing_prompt = [editing_prompt]
351
+ enabled_editing_prompts = len(editing_prompt)
352
+ elif editing_prompt_embeddings is not None:
353
+ enable_edit_guidance = True
354
+ enabled_editing_prompts = editing_prompt_embeddings.shape[0]
355
+ else:
356
+ enabled_editing_prompts = 0
357
+ enable_edit_guidance = False
358
+
359
+ # get prompt text embeddings
360
+ text_inputs = self.tokenizer(
361
+ prompt,
362
+ padding="max_length",
363
+ max_length=self.tokenizer.model_max_length,
364
+ return_tensors="pt",
365
+ )
366
+ text_input_ids = text_inputs.input_ids
367
+
368
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
369
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
370
+ logger.warning(
371
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
372
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
373
+ )
374
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
375
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
376
+
377
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
378
+ bs_embed, seq_len, _ = text_embeddings.shape
379
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
380
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
381
+
382
+ if enable_edit_guidance:
383
+ # get safety text embeddings
384
+ if editing_prompt_embeddings is None:
385
+ edit_concepts_input = self.tokenizer(
386
+ [x for item in editing_prompt for x in repeat(item, batch_size)],
387
+ padding="max_length",
388
+ max_length=self.tokenizer.model_max_length,
389
+ return_tensors="pt",
390
+ )
391
+
392
+ edit_concepts_input_ids = edit_concepts_input.input_ids
393
+
394
+ if edit_concepts_input_ids.shape[-1] > self.tokenizer.model_max_length:
395
+ removed_text = self.tokenizer.batch_decode(
396
+ edit_concepts_input_ids[:, self.tokenizer.model_max_length :]
397
+ )
398
+ logger.warning(
399
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
400
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
401
+ )
402
+ edit_concepts_input_ids = edit_concepts_input_ids[:, : self.tokenizer.model_max_length]
403
+ edit_concepts = self.text_encoder(edit_concepts_input_ids.to(self.device))[0]
404
+ else:
405
+ edit_concepts = editing_prompt_embeddings.to(self.device).repeat(batch_size, 1, 1)
406
+
407
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
408
+ bs_embed_edit, seq_len_edit, _ = edit_concepts.shape
409
+ edit_concepts = edit_concepts.repeat(1, num_images_per_prompt, 1)
410
+ edit_concepts = edit_concepts.view(bs_embed_edit * num_images_per_prompt, seq_len_edit, -1)
411
+
412
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
413
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
414
+ # corresponds to doing no classifier free guidance.
415
+ do_classifier_free_guidance = guidance_scale > 1.0
416
+ # get unconditional embeddings for classifier free guidance
417
+
418
+ if do_classifier_free_guidance:
419
+ uncond_tokens: List[str]
420
+ if negative_prompt is None:
421
+ uncond_tokens = [""]
422
+ elif type(prompt) is not type(negative_prompt):
423
+ raise TypeError(
424
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
425
+ f" {type(prompt)}."
426
+ )
427
+ elif isinstance(negative_prompt, str):
428
+ uncond_tokens = [negative_prompt]
429
+ elif batch_size != len(negative_prompt):
430
+ raise ValueError(
431
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
432
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
433
+ " the batch size of `prompt`."
434
+ )
435
+ else:
436
+ uncond_tokens = negative_prompt
437
+
438
+ max_length = text_input_ids.shape[-1]
439
+ uncond_input = self.tokenizer(
440
+ uncond_tokens,
441
+ padding="max_length",
442
+ max_length=max_length,
443
+ truncation=True,
444
+ return_tensors="pt",
445
+ )
446
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
447
+
448
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
449
+ seq_len = uncond_embeddings.shape[1]
450
+ uncond_embeddings = uncond_embeddings.repeat(batch_size, num_images_per_prompt, 1)
451
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
452
+
453
+ # For classifier free guidance, we need to do two forward passes.
454
+ # Here we concatenate the unconditional and text embeddings into a single batch
455
+ # to avoid doing two forward passes
456
+ if enable_edit_guidance:
457
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings, edit_concepts])
458
+ else:
459
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
460
+ # get the initial random noise unless the user supplied it
461
+
462
+ # 4. Prepare timesteps
463
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
464
+ timesteps = self.scheduler.timesteps
465
+ if use_ddpm:
466
+ t_to_idx = {int(v):k for k,v in enumerate(timesteps[-zs.shape[0]:])}
467
+ timesteps = timesteps[-zs.shape[0]:]
468
+
469
+ # 5. Prepare latent variables
470
+ num_channels_latents = self.unet.config.in_channels
471
+ latents = self.prepare_latents(
472
+ batch_size * num_images_per_prompt,
473
+ num_channels_latents,
474
+ height,
475
+ width,
476
+ text_embeddings.dtype,
477
+ self.device,
478
+ generator,
479
+ latents,
480
+ )
481
+
482
+ # 6. Prepare extra step kwargs.
483
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
484
+
485
+ # Initialize edit_momentum to None
486
+ edit_momentum = None
487
+
488
+ self.uncond_estimates = None
489
+ self.text_estimates = None
490
+ self.edit_estimates = None
491
+ self.sem_guidance = None
492
+
493
+ for i, t in enumerate(self.progress_bar(timesteps)):
494
+ # expand the latents if we are doing classifier free guidance
495
+ latent_model_input = (
496
+ torch.cat([latents] * (2 + enabled_editing_prompts)) if do_classifier_free_guidance else latents
497
+ )
498
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
499
+
500
+ # predict the noise residual
501
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
502
+
503
+ # perform guidance
504
+ if do_classifier_free_guidance:
505
+ noise_pred_out = noise_pred.chunk(2 + enabled_editing_prompts) # [b,4, 64, 64]
506
+ noise_pred_uncond, noise_pred_text = noise_pred_out[0], noise_pred_out[1]
507
+ noise_pred_edit_concepts = noise_pred_out[2:]
508
+
509
+ # default text guidance
510
+ noise_guidance = guidance_scale * (noise_pred_text - noise_pred_uncond)
511
+ # noise_guidance = (noise_pred_text - noise_pred_edit_concepts[0])
512
+
513
+ if self.uncond_estimates is None:
514
+ self.uncond_estimates = torch.zeros((num_inference_steps + 1, *noise_pred_uncond.shape))
515
+ self.uncond_estimates[i] = noise_pred_uncond.detach().cpu()
516
+
517
+ if self.text_estimates is None:
518
+ self.text_estimates = torch.zeros((num_inference_steps + 1, *noise_pred_text.shape))
519
+ self.text_estimates[i] = noise_pred_text.detach().cpu()
520
+
521
+ if self.edit_estimates is None and enable_edit_guidance:
522
+ self.edit_estimates = torch.zeros(
523
+ (num_inference_steps + 1, len(noise_pred_edit_concepts), *noise_pred_edit_concepts[0].shape)
524
+ )
525
+
526
+ if self.sem_guidance is None:
527
+ self.sem_guidance = torch.zeros((num_inference_steps + 1, *noise_pred_text.shape))
528
+
529
+ if edit_momentum is None:
530
+ edit_momentum = torch.zeros_like(noise_guidance)
531
+
532
+ if enable_edit_guidance:
533
+ concept_weights = torch.zeros(
534
+ (len(noise_pred_edit_concepts), noise_guidance.shape[0]),
535
+ device=self.device,
536
+ dtype=noise_guidance.dtype,
537
+ )
538
+ noise_guidance_edit = torch.zeros(
539
+ (len(noise_pred_edit_concepts), *noise_guidance.shape),
540
+ device=self.device,
541
+ dtype=noise_guidance.dtype,
542
+ )
543
+ # noise_guidance_edit = torch.zeros_like(noise_guidance)
544
+ warmup_inds = []
545
+ for c, noise_pred_edit_concept in enumerate(noise_pred_edit_concepts):
546
+ self.edit_estimates[i, c] = noise_pred_edit_concept
547
+ if isinstance(edit_guidance_scale, list):
548
+ edit_guidance_scale_c = edit_guidance_scale[c]
549
+ else:
550
+ edit_guidance_scale_c = edit_guidance_scale
551
+
552
+ if isinstance(edit_threshold, list):
553
+ edit_threshold_c = edit_threshold[c]
554
+ else:
555
+ edit_threshold_c = edit_threshold
556
+ if isinstance(reverse_editing_direction, list):
557
+ reverse_editing_direction_c = reverse_editing_direction[c]
558
+ else:
559
+ reverse_editing_direction_c = reverse_editing_direction
560
+ if edit_weights:
561
+ edit_weight_c = edit_weights[c]
562
+ else:
563
+ edit_weight_c = 1.0
564
+ if isinstance(edit_warmup_steps, list):
565
+ edit_warmup_steps_c = edit_warmup_steps[c]
566
+ else:
567
+ edit_warmup_steps_c = edit_warmup_steps
568
+
569
+ if isinstance(edit_cooldown_steps, list):
570
+ edit_cooldown_steps_c = edit_cooldown_steps[c]
571
+ elif edit_cooldown_steps is None:
572
+ edit_cooldown_steps_c = i + 1
573
+ else:
574
+ edit_cooldown_steps_c = edit_cooldown_steps
575
+ if i >= edit_warmup_steps_c:
576
+ warmup_inds.append(c)
577
+ if i >= edit_cooldown_steps_c:
578
+ noise_guidance_edit[c, :, :, :, :] = torch.zeros_like(noise_pred_edit_concept)
579
+ continue
580
+
581
+ noise_guidance_edit_tmp = noise_pred_edit_concept - noise_pred_uncond
582
+ # tmp_weights = (noise_pred_text - noise_pred_edit_concept).sum(dim=(1, 2, 3))
583
+ tmp_weights = (noise_guidance - noise_pred_edit_concept).sum(dim=(1, 2, 3))
584
+
585
+ tmp_weights = torch.full_like(tmp_weights, edit_weight_c) # * (1 / enabled_editing_prompts)
586
+ if reverse_editing_direction_c:
587
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * -1
588
+ concept_weights[c, :] = tmp_weights
589
+
590
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp * edit_guidance_scale_c
591
+
592
+ # torch.quantile function expects float32
593
+ if noise_guidance_edit_tmp.dtype == torch.float32:
594
+ tmp = torch.quantile(
595
+ torch.abs(noise_guidance_edit_tmp).flatten(start_dim=2),
596
+ edit_threshold_c,
597
+ dim=2,
598
+ keepdim=False,
599
+ )
600
+ else:
601
+ tmp = torch.quantile(
602
+ torch.abs(noise_guidance_edit_tmp).flatten(start_dim=2).to(torch.float32),
603
+ edit_threshold_c,
604
+ dim=2,
605
+ keepdim=False,
606
+ ).to(noise_guidance_edit_tmp.dtype)
607
+
608
+ noise_guidance_edit_tmp = torch.where(
609
+ torch.abs(noise_guidance_edit_tmp) >= tmp[:, :, None, None],
610
+ noise_guidance_edit_tmp,
611
+ torch.zeros_like(noise_guidance_edit_tmp),
612
+ )
613
+ noise_guidance_edit[c, :, :, :, :] = noise_guidance_edit_tmp
614
+
615
+ # noise_guidance_edit = noise_guidance_edit + noise_guidance_edit_tmp
616
+
617
+ warmup_inds = torch.tensor(warmup_inds).to(self.device)
618
+ if len(noise_pred_edit_concepts) > warmup_inds.shape[0] > 0:
619
+ concept_weights = concept_weights.to("cpu") # Offload to cpu
620
+ noise_guidance_edit = noise_guidance_edit.to("cpu")
621
+
622
+ concept_weights_tmp = torch.index_select(concept_weights.to(self.device), 0, warmup_inds)
623
+ concept_weights_tmp = torch.where(
624
+ concept_weights_tmp < 0, torch.zeros_like(concept_weights_tmp), concept_weights_tmp
625
+ )
626
+ concept_weights_tmp = concept_weights_tmp / concept_weights_tmp.sum(dim=0)
627
+ # concept_weights_tmp = torch.nan_to_num(concept_weights_tmp)
628
+
629
+ noise_guidance_edit_tmp = torch.index_select(
630
+ noise_guidance_edit.to(self.device), 0, warmup_inds
631
+ )
632
+ noise_guidance_edit_tmp = torch.einsum(
633
+ "cb,cbijk->bijk", concept_weights_tmp, noise_guidance_edit_tmp
634
+ )
635
+ noise_guidance_edit_tmp = noise_guidance_edit_tmp
636
+ noise_guidance = noise_guidance + noise_guidance_edit_tmp
637
+
638
+ self.sem_guidance[i] = noise_guidance_edit_tmp.detach().cpu()
639
+
640
+ del noise_guidance_edit_tmp
641
+ del concept_weights_tmp
642
+ concept_weights = concept_weights.to(self.device)
643
+ noise_guidance_edit = noise_guidance_edit.to(self.device)
644
+
645
+ concept_weights = torch.where(
646
+ concept_weights < 0, torch.zeros_like(concept_weights), concept_weights
647
+ )
648
+
649
+ concept_weights = torch.nan_to_num(concept_weights)
650
+
651
+ noise_guidance_edit = torch.einsum("cb,cbijk->bijk", concept_weights, noise_guidance_edit)
652
+
653
+ noise_guidance_edit = noise_guidance_edit + edit_momentum_scale * edit_momentum
654
+
655
+ edit_momentum = edit_mom_beta * edit_momentum + (1 - edit_mom_beta) * noise_guidance_edit
656
+
657
+ if warmup_inds.shape[0] == len(noise_pred_edit_concepts):
658
+ noise_guidance = noise_guidance + noise_guidance_edit
659
+ self.sem_guidance[i] = noise_guidance_edit.detach().cpu()
660
+
661
+ if sem_guidance is not None:
662
+ edit_guidance = sem_guidance[i].to(self.device)
663
+ noise_guidance = noise_guidance + edit_guidance
664
+
665
+ noise_pred = noise_pred_uncond + noise_guidance
666
+ ## ddpm ###########################################################
667
+ if use_ddpm:
668
+
669
+ idx = t_to_idx[int(t)]
670
+ z = zs[idx] if not zs is None else None
671
+
672
+ # 1. get previous step value (=t-1)
673
+ prev_timestep = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
674
+ # 2. compute alphas, betas
675
+ alpha_prod_t = self.scheduler.alphas_cumprod[t]
676
+ alpha_prod_t_prev = self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod
677
+ beta_prod_t = 1 - alpha_prod_t
678
+
679
+ # 3. compute predicted original sample from predicted noise also called
680
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
681
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
682
+
683
+
684
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
685
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
686
+ # variance = self.scheduler._get_variance(timestep, prev_timestep)
687
+ # variance = get_variance(model, t) #, prev_timestep)
688
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
689
+ variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
690
+
691
+
692
+
693
+ std_dev_t = eta * variance ** (0.5)
694
+ # Take care of asymetric reverse process (asyrp)
695
+ noise_pred_direction = noise_pred
696
+
697
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
698
+ # pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output_direction
699
+ pred_sample_direction = (1 - alpha_prod_t_prev - eta * variance) ** (0.5) * noise_pred_direction
700
+
701
+ # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
702
+ prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
703
+ # 8. Add noice if eta > 0
704
+ if eta > 0:
705
+ if z is None:
706
+ z = torch.randn(noise_pred.shape, device=self.device)
707
+ sigma_z = eta * variance ** (0.5) * z
708
+ latents = prev_sample + sigma_z
709
+
710
+ ## ddpm ##########################################################
711
+ # compute the previous noisy sample x_t -> x_t-1
712
+ else: #if not use_ddpm:
713
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
714
+
715
+ # call the callback, if provided
716
+ if callback is not None and i % callback_steps == 0:
717
+ callback(i, t, latents)
718
+
719
+
720
+ # # 8. Post-processing
721
+ # image = self.decode_latents(latents)
722
+
723
+ # # 9. Run safety checker
724
+ # image, has_nsfw_concept = self.run_safety_checker(image, self.device, text_embeddings.dtype)
725
+
726
+ # # 10. Convert to PIL
727
+ # if output_type == "pil":
728
+ # image = self.numpy_to_pil(image)
729
+
730
+ # if not return_dict:
731
+ # return (image, has_nsfw_concept)
732
+
733
+ # return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
734
+
735
+ # 8. Post-processing
736
+ if not output_type == "latent":
737
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
738
+ image, has_nsfw_concept = self.run_safety_checker(image, self.device, text_embeddings.dtype)
739
+ else:
740
+ image = latents
741
+ has_nsfw_concept = None
742
+
743
+ if has_nsfw_concept is None:
744
+ do_denormalize = [True] * image.shape[0]
745
+ else:
746
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
747
+
748
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
749
+
750
+ if not return_dict:
751
+ return (image, has_nsfw_concept)
752
+
753
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ diffusers
2
+ accelerate
3
+ transformers
4
+ torch
5
+ torchvision
style.css ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ This CSS file is modified from:
3
+ https://huggingface.co/spaces/DeepFloyd/IF/blob/main/style.css
4
+ */
5
+
6
+ h1 {
7
+ text-align: center;
8
+ }
9
+
10
+ .gradio-container {
11
+ font-family: 'IBM Plex Sans', sans-serif;
12
+ }
13
+
14
+ .gr-button {
15
+ color: white;
16
+ border-color: black;
17
+ background: black;
18
+ }
19
+
20
+ input[type='range'] {
21
+ accent-color: black;
22
+ }
23
+
24
+ .dark input[type='range'] {
25
+ accent-color: #dfdfdf;
26
+ }
27
+
28
+ .container {
29
+ max-width: 730px;
30
+ margin: auto;
31
+ padding-top: 1.5rem;
32
+ }
33
+
34
+
35
+ .gr-button:focus {
36
+ border-color: rgb(147 197 253 / var(--tw-border-opacity));
37
+ outline: none;
38
+ box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
39
+ --tw-border-opacity: 1;
40
+ --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
41
+ --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
42
+ --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
43
+ --tw-ring-opacity: .5;
44
+ }
45
+
46
+ .gr-form {
47
+ flex: 1 1 50%;
48
+ border-top-right-radius: 0;
49
+ border-bottom-right-radius: 0;
50
+ }
51
+
52
+ #prompt-container {
53
+ gap: 0;
54
+ }
55
+
56
+ #prompt-text-input,
57
+ #negative-prompt-text-input {
58
+ padding: .45rem 0.625rem
59
+ }
60
+
61
+ /* #component-16 {
62
+ border-top-width: 1px !important;
63
+ margin-top: 1em
64
+ } */
65
+
66
+ .image_duplication {
67
+ position: absolute;
68
+ width: 100px;
69
+ left: 50px
70
+ }
71
+
72
+ #component-0 {
73
+ max-width: 730px;
74
+ margin: auto;
75
+ padding-top: 1.5rem;
76
+ }
77
+
utils.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import PIL
2
+ from PIL import Image, ImageDraw ,ImageFont
3
+ from matplotlib import pyplot as plt
4
+ import torchvision.transforms as T
5
+ import os
6
+ import torch
7
+ import yaml
8
+
9
+ def show_torch_img(img):
10
+ img = to_np_image(img)
11
+ plt.imshow(img)
12
+ plt.axis("off")
13
+
14
+ def to_np_image(all_images):
15
+ all_images = (all_images.permute(0, 2, 3, 1) * 127.5 + 128).clamp(0, 255).to(torch.uint8).cpu().numpy()[0]
16
+ return all_images
17
+
18
+ def tensor_to_pil(tensor_imgs):
19
+ if type(tensor_imgs) == list:
20
+ tensor_imgs = torch.cat(tensor_imgs)
21
+ tensor_imgs = (tensor_imgs / 2 + 0.5).clamp(0, 1)
22
+ to_pil = T.ToPILImage()
23
+ pil_imgs = [to_pil(img) for img in tensor_imgs]
24
+ return pil_imgs
25
+
26
+ def pil_to_tensor(pil_imgs):
27
+ to_torch = T.ToTensor()
28
+ if type(pil_imgs) == PIL.Image.Image:
29
+ tensor_imgs = to_torch(pil_imgs).unsqueeze(0)*2-1
30
+ elif type(pil_imgs) == list:
31
+ tensor_imgs = torch.cat([to_torch(pil_imgs).unsqueeze(0)*2-1 for img in pil_imgs]).to(device)
32
+ else:
33
+ raise Exception("Input need to be PIL.Image or list of PIL.Image")
34
+ return tensor_imgs
35
+
36
+
37
+ ## TODO implement this
38
+ # n = 10
39
+ # num_rows = 4
40
+ # num_col = n // num_rows
41
+ # num_col = num_col + 1 if n % num_rows else num_col
42
+ # num_col
43
+ def add_margin(pil_img, top = 0, right = 0, bottom = 0,
44
+ left = 0, color = (255,255,255)):
45
+ width, height = pil_img.size
46
+ new_width = width + right + left
47
+ new_height = height + top + bottom
48
+ result = Image.new(pil_img.mode, (new_width, new_height), color)
49
+
50
+ result.paste(pil_img, (left, top))
51
+ return result
52
+
53
+ def image_grid(imgs, rows = 1, cols = None,
54
+ size = None,
55
+ titles = None, text_pos = (0, 0)):
56
+ if type(imgs) == list and type(imgs[0]) == torch.Tensor:
57
+ imgs = torch.cat(imgs)
58
+ if type(imgs) == torch.Tensor:
59
+ imgs = tensor_to_pil(imgs)
60
+
61
+ if not size is None:
62
+ imgs = [img.resize((size,size)) for img in imgs]
63
+ if cols is None:
64
+ cols = len(imgs)
65
+ assert len(imgs) >= rows*cols
66
+
67
+ top=20
68
+ w, h = imgs[0].size
69
+ delta = 0
70
+ if len(imgs)> 1 and not imgs[1].size[1] == h:
71
+ delta = top
72
+ h = imgs[1].size[1]
73
+ if not titles is None:
74
+ font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMono.ttf",
75
+ size = 20, encoding="unic")
76
+ h = top + h
77
+ grid = Image.new('RGB', size=(cols*w, rows*h+delta))
78
+ for i, img in enumerate(imgs):
79
+
80
+ if not titles is None:
81
+ img = add_margin(img, top = top, bottom = 0,left=0)
82
+ draw = ImageDraw.Draw(img)
83
+ draw.text(text_pos, titles[i],(0,0,0),
84
+ font = font)
85
+ if not delta == 0 and i > 0:
86
+ grid.paste(img, box=(i%cols*w, i//cols*h+delta))
87
+ else:
88
+ grid.paste(img, box=(i%cols*w, i//cols*h))
89
+
90
+ return grid
91
+
92
+
93
+ """
94
+ input_folder - dataset folder
95
+ """
96
+ def load_dataset(input_folder):
97
+ # full_file_names = glob.glob(input_folder)
98
+ # class_names = [x[0] for x in os.walk(input_folder)]
99
+ class_names = next(os.walk(input_folder))[1]
100
+ class_names[:] = [d for d in class_names if not d[0] == '.']
101
+ file_names=[]
102
+ for class_name in class_names:
103
+ cur_path = os.path.join(input_folder, class_name)
104
+ filenames = next(os.walk(cur_path), (None, None, []))[2]
105
+ filenames = [f for f in filenames if not f[0] == '.']
106
+ file_names.append(filenames)
107
+ return class_names, file_names
108
+
109
+
110
+ def dataset_from_yaml(yaml_location):
111
+ with open(yaml_location, 'r') as stream:
112
+ data_loaded = yaml.safe_load(stream)
113
+
114
+ return data_loaded