renan3989 Linoy Tsaban commited on
Commit
b637f7a
·
0 Parent(s):

Duplicate from editing-images/ledits

Browse files

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

Files changed (35) hide show
  1. .gitattributes +37 -0
  2. LEDITS_ddpm_inversion_x_sega.ipynb +0 -0
  3. README.md +20 -0
  4. app.py +867 -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. share_btn.py +109 -0
  34. style.css +93 -0
  35. 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.36.1
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,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from share_btn import community_icon_html, loading_icon_html, share_js
16
+
17
+ # load pipelines
18
+ sd_model_id = "stabilityai/stable-diffusion-2-1-base"
19
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
+ sd_pipe = StableDiffusionPipeline.from_pretrained(sd_model_id,torch_dtype=torch.float16).to(device)
21
+ sd_pipe.scheduler = DDIMScheduler.from_config(sd_model_id, subfolder = "scheduler")
22
+ sem_pipe = SemanticStableDiffusionPipeline.from_pretrained(sd_model_id, torch_dtype=torch.float16).to(device)
23
+ blip_processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
24
+ blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base",torch_dtype=torch.float16).to(device)
25
+
26
+
27
+
28
+ ## IMAGE CPATIONING ##
29
+ def caption_image(input_image):
30
+ inputs = blip_processor(images=input_image, return_tensors="pt").to(device, torch.float16)
31
+ pixel_values = inputs.pixel_values
32
+
33
+ generated_ids = blip_model.generate(pixel_values=pixel_values, max_length=50)
34
+ generated_caption = blip_processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
35
+ return generated_caption, generated_caption
36
+
37
+
38
+
39
+ ## DDPM INVERSION AND SAMPLING ##
40
+ def invert(x0, prompt_src="", num_diffusion_steps=100, cfg_scale_src = 3.5, eta = 1):
41
+
42
+ # inverts a real image according to Algorihm 1 in https://arxiv.org/pdf/2304.06140.pdf,
43
+ # based on the code in https://github.com/inbarhub/DDPM_inversion
44
+
45
+ # returns wt, zs, wts:
46
+ # wt - inverted latent
47
+ # wts - intermediate inverted latents
48
+ # zs - noise maps
49
+
50
+ sd_pipe.scheduler.set_timesteps(num_diffusion_steps)
51
+
52
+ # vae encode image
53
+ with inference_mode():
54
+ w0 = (sd_pipe.vae.encode(x0).latent_dist.mode() * 0.18215)
55
+
56
+ # find Zs and wts - forward process
57
+ 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)
58
+ return zs, wts
59
+
60
+
61
+ def sample(zs, wts, prompt_tar="", cfg_scale_tar=15, skip=36, eta = 1):
62
+
63
+ # reverse process (via Zs and wT)
64
+ 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:])
65
+
66
+ # vae decode image
67
+ with inference_mode():
68
+ x0_dec = sd_pipe.vae.decode(1 / 0.18215 * w0).sample
69
+ if x0_dec.dim()<4:
70
+ x0_dec = x0_dec[None,:,:,:]
71
+ img = image_grid(x0_dec)
72
+ return img
73
+
74
+
75
+ def reconstruct(tar_prompt,
76
+ image_caption,
77
+ tar_cfg_scale,
78
+ skip,
79
+ wts, zs,
80
+ do_reconstruction,
81
+ reconstruction,
82
+ reconstruct_button
83
+ ):
84
+
85
+ if reconstruct_button == "Hide Reconstruction":
86
+ return reconstruction.value, reconstruction, ddpm_edited_image.update(visible=False), do_reconstruction, "Show Reconstruction"
87
+
88
+ else:
89
+ if do_reconstruction:
90
+ if image_caption.lower() == tar_prompt.lower(): # if image caption was not changed, run actual reconstruction
91
+ tar_prompt = ""
92
+ reconstruction_img = sample(zs.value, wts.value, prompt_tar=tar_prompt, skip=skip, cfg_scale_tar=tar_cfg_scale)
93
+ reconstruction = gr.State(value=reconstruction_img)
94
+ do_reconstruction = False
95
+ return reconstruction.value, reconstruction, ddpm_edited_image.update(visible=True), do_reconstruction, "Hide Reconstruction"
96
+
97
+
98
+ def load_and_invert(
99
+ input_image,
100
+ do_inversion,
101
+ seed, randomize_seed,
102
+ wts, zs,
103
+ src_prompt ="",
104
+ tar_prompt="",
105
+ steps=100,
106
+ src_cfg_scale = 3.5,
107
+ skip=36,
108
+ tar_cfg_scale=15,
109
+ progress=gr.Progress(track_tqdm=True)
110
+
111
+ ):
112
+
113
+
114
+ x0 = load_512(input_image, device=device).to(torch.float16)
115
+
116
+ if do_inversion or randomize_seed:
117
+ # invert and retrieve noise maps and latent
118
+ zs_tensor, wts_tensor = invert(x0 =x0 , prompt_src=src_prompt, num_diffusion_steps=steps, cfg_scale_src=src_cfg_scale)
119
+ wts = gr.State(value=wts_tensor)
120
+ zs = gr.State(value=zs_tensor)
121
+ do_inversion = False
122
+
123
+ return wts, zs, do_inversion, inversion_progress.update(visible=False)
124
+
125
+ ## SEGA ##
126
+
127
+ def edit(input_image,
128
+ wts, zs,
129
+ tar_prompt,
130
+ image_caption,
131
+ steps,
132
+ skip,
133
+ tar_cfg_scale,
134
+ edit_concept_1,edit_concept_2,edit_concept_3,
135
+ guidnace_scale_1,guidnace_scale_2,guidnace_scale_3,
136
+ warmup_1, warmup_2, warmup_3,
137
+ neg_guidance_1, neg_guidance_2, neg_guidance_3,
138
+ threshold_1, threshold_2, threshold_3,
139
+ do_reconstruction,
140
+ reconstruction,
141
+
142
+ # for inversion in case it needs to be re computed (and avoid delay):
143
+ do_inversion,
144
+ seed,
145
+ randomize_seed,
146
+ src_prompt,
147
+ src_cfg_scale):
148
+ show_share_button = gr.update(visible=True)
149
+ if do_inversion or randomize_seed:
150
+ x0 = load_512(input_image, device=device).to(torch.float16)
151
+ # invert and retrieve noise maps and latent
152
+ zs_tensor, wts_tensor = invert(x0 =x0 , prompt_src=src_prompt, num_diffusion_steps=steps, cfg_scale_src=src_cfg_scale)
153
+ wts = gr.State(value=wts_tensor)
154
+ zs = gr.State(value=zs_tensor)
155
+ do_inversion = False
156
+
157
+ if image_caption.lower() == tar_prompt.lower(): # if image caption was not changed, run pure sega
158
+ tar_prompt = ""
159
+
160
+ if edit_concept_1 != "" or edit_concept_2 != "" or edit_concept_3 != "":
161
+ editing_args = dict(
162
+ editing_prompt = [edit_concept_1,edit_concept_2,edit_concept_3],
163
+ reverse_editing_direction = [ neg_guidance_1, neg_guidance_2, neg_guidance_3,],
164
+ edit_warmup_steps=[warmup_1, warmup_2, warmup_3,],
165
+ edit_guidance_scale=[guidnace_scale_1,guidnace_scale_2,guidnace_scale_3],
166
+ edit_threshold=[threshold_1, threshold_2, threshold_3],
167
+ edit_momentum_scale=0.3,
168
+ edit_mom_beta=0.6,
169
+ eta=1,)
170
+
171
+ latnets = wts.value[skip].expand(1, -1, -1, -1)
172
+ sega_out = sem_pipe(prompt=tar_prompt, latents=latnets, guidance_scale = tar_cfg_scale,
173
+ num_images_per_prompt=1,
174
+ num_inference_steps=steps,
175
+ use_ddpm=True, wts=wts.value, zs=zs.value[skip:], **editing_args)
176
+
177
+ return sega_out.images[0], reconstruct_button.update(visible=True), do_reconstruction, reconstruction, wts, zs, do_inversion, show_share_button
178
+
179
+ else: # if sega concepts were not added, performs regular ddpm sampling
180
+
181
+ if do_reconstruction: # if ddpm sampling wasn't computed
182
+ pure_ddpm_img = sample(zs.value, wts.value, prompt_tar=tar_prompt, skip=skip, cfg_scale_tar=tar_cfg_scale)
183
+ reconstruction = gr.State(value=pure_ddpm_img)
184
+ do_reconstruction = False
185
+ return pure_ddpm_img, reconstruct_button.update(visible=False), do_reconstruction, reconstruction, wts, zs, do_inversion, show_share_button
186
+
187
+ return reconstruction.value, reconstruct_button.update(visible=False), do_reconstruction, reconstruction, wts, zs, do_inversion, show_share_button
188
+
189
+
190
+ def randomize_seed_fn(seed, randomize_seed):
191
+ if randomize_seed:
192
+ seed = random.randint(0, np.iinfo(np.int32).max)
193
+ torch.manual_seed(seed)
194
+ return seed
195
+
196
+ def crop_image(image):
197
+ h, w, c = image.shape
198
+ if h < w:
199
+ offset = (w - h) // 2
200
+ image = image[:, offset:offset + h]
201
+ elif w < h:
202
+ offset = (h - w) // 2
203
+ image = image[offset:offset + w]
204
+ image = np.array(Image.fromarray(image).resize((512, 512)))
205
+ return image
206
+
207
+
208
+ def get_example():
209
+ case = [
210
+ [
211
+ 'examples/lemons_input.jpg',
212
+ # '',
213
+ 'apples', 'lemons',
214
+ 'a ceramic bowl',
215
+ 'examples/lemons_output.jpg',
216
+
217
+
218
+ 7,7,
219
+ 1,1,
220
+ False, True,
221
+ 100,
222
+ 36,
223
+ 15,
224
+
225
+ ],
226
+ [
227
+ 'examples/girl_with_pearl_earring_input.png',
228
+ # '',
229
+ 'glasses', '',
230
+ '',
231
+ 'examples/girl_with_pearl_earring_output.png',
232
+
233
+
234
+ 3,7,
235
+ 3,2,
236
+ False,False,
237
+ 100,
238
+ 36,
239
+ 15,
240
+
241
+ ],
242
+ [
243
+ 'examples/rockey_shore_input.jpg',
244
+ # '',
245
+ 'sea turtle', '',
246
+ 'watercolor painting',
247
+ 'examples/rockey_shore_output.jpg',
248
+
249
+
250
+ 7,7,
251
+ 1,2,
252
+ False,False,
253
+ 100,
254
+ 36,
255
+ 15,
256
+ ],
257
+ [
258
+ 'examples/flower_field_input.jpg',
259
+ # '',
260
+ 'wheat', 'red flowers',
261
+ 'oil painting',
262
+ 'examples/flower_field_output_2.jpg',
263
+
264
+
265
+ 20,7,
266
+ 1,1,
267
+ False,True,
268
+ 100,
269
+ 36,
270
+ 15,
271
+
272
+ ],
273
+ [
274
+ 'examples/butterfly_input.jpg',
275
+ # '',
276
+ 'bee', 'butterfly',
277
+ 'oil painting',
278
+ 'examples/butterfly_output.jpg',
279
+ 7, 7,
280
+ 1,1,
281
+ False, True,
282
+ 100,
283
+ 36,
284
+ 15,
285
+ ]
286
+ ]
287
+ return case
288
+
289
+
290
+ def swap_visibilities(input_image,
291
+ edit_concept_1,
292
+ edit_concept_2,
293
+ tar_prompt,
294
+ sega_edited_image,
295
+ guidnace_scale_1,
296
+ guidnace_scale_2,
297
+ warmup_1,
298
+ warmup_2,
299
+ neg_guidance_1,
300
+ neg_guidance_2,
301
+ steps,
302
+ skip,
303
+ tar_cfg_scale,
304
+ sega_concepts_counter
305
+
306
+ ):
307
+ sega_concepts_counter=0
308
+ concept1_update = update_display_concept("Remove" if neg_guidance_1 else "Add", edit_concept_1, neg_guidance_1, sega_concepts_counter)
309
+ if(edit_concept_2 != ""):
310
+ concept2_update = update_display_concept("Remove" if neg_guidance_2 else "Add", edit_concept_2, neg_guidance_2, sega_concepts_counter+1)
311
+ else:
312
+ 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
313
+
314
+ return (gr.update(visible=True), *concept1_update[:-1], *concept2_update)
315
+
316
+
317
+
318
+ ########
319
+ # demo #
320
+ ########
321
+
322
+
323
+ intro = """
324
+ <h1 style="font-weight: 1400; text-align: center; margin-bottom: 7px;">
325
+ LEDITS - Pipeline for editing images
326
+ </h1>
327
+ <h3 style="font-weight: 600; text-align: center;">
328
+ Real Image Latent Editing with Edit Friendly DDPM and Semantic Guidance
329
+ </h3>
330
+ <h4 style="text-align: center; margin-bottom: 7px;">
331
+ <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>
332
+ </h4>
333
+
334
+ <p style="font-size: 0.9rem; margin: 0rem; line-height: 1.2em; margin-top:1em">
335
+ <a href="https://huggingface.co/spaces/editing-images/edit_friendly_ddpm_x_sega?duplicate=true">
336
+ <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3CWLGkA" alt="Duplicate Space"></a>
337
+ <p/>"""
338
+
339
+ help_text = """
340
+ - **Getting Started - edit images with DDPM X SEGA:**
341
+
342
+ The are 3 general setting options you can play with -
343
+
344
+ 1. **Pure DDPM Edit -** Describe the desired edited output image in detail
345
+ 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
346
+ 3. **Combined -** Describe the desired edited output image in detail and add additional SEGA editing concepts on top
347
+ - **Getting Started - Tips**
348
+
349
+ 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 -
350
+
351
+ 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)
352
+ 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
353
+ 3. **Combining DDPM Edit with SEGA -**
354
+ 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.
355
+ 4. **Reconstruction:** Using an empty source prompt + target prompt will lead to a perfect reconstruction
356
+ - **Fidelity vs creativity**:
357
+
358
+ Bigger values → more fidelity, smaller values → more creativity
359
+
360
+ 1. `Skip Steps`
361
+ 2. `Warmup` (SEGA)
362
+ 3. `Threshold` (SEGA)
363
+
364
+ Bigger values → more creativity, smaller values → more fidelity
365
+
366
+ 1. `Guidance Scale`
367
+ 2. `Concept Guidance Scale` (SEGA)
368
+ """
369
+
370
+ with gr.Blocks(css="style.css") as demo:
371
+ def update_counter(sega_concepts_counter, concept1, concept2, concept3):
372
+ if sega_concepts_counter == "":
373
+ sega_concepts_counter = sum(1 for concept in (concept1, concept2, concept3) if concept != '')
374
+ return sega_concepts_counter
375
+ def remove_concept(sega_concepts_counter, row_triggered):
376
+ sega_concepts_counter -= 1
377
+ rows_visibility = [gr.update(visible=False) for _ in range(4)]
378
+
379
+ if(row_triggered-1 > sega_concepts_counter):
380
+ rows_visibility[sega_concepts_counter] = gr.update(visible=True)
381
+ else:
382
+ rows_visibility[row_triggered-1] = gr.update(visible=True)
383
+
384
+ row1_visibility, row2_visibility, row3_visibility, row4_visibility = rows_visibility
385
+
386
+ guidance_scale_label = "Concept Guidance Scale"
387
+ # enable_interactive = gr.update(interactive=True)
388
+ return (gr.update(visible=False),
389
+ gr.update(visible=False, value="",),
390
+ gr.update(interactive=True, value=""),
391
+ gr.update(visible=False,label = guidance_scale_label),
392
+ gr.update(interactive=True, value =False),
393
+ gr.update(value=DEFAULT_WARMUP_STEPS),
394
+ gr.update(value=DEFAULT_THRESHOLD),
395
+ gr.update(visible=True),
396
+ gr.update(interactive=True, value="custom"),
397
+ row1_visibility,
398
+ row2_visibility,
399
+ row3_visibility,
400
+ row4_visibility,
401
+ sega_concepts_counter
402
+ )
403
+
404
+
405
+
406
+ def update_display_concept(button_label, edit_concept, neg_guidance, sega_concepts_counter):
407
+ sega_concepts_counter += 1
408
+ guidance_scale_label = "Concept Guidance Scale"
409
+ if(button_label=='Remove'):
410
+ neg_guidance = True
411
+ guidance_scale_label = "Negative Guidance Scale"
412
+
413
+ return (gr.update(visible=True), #boxn
414
+ gr.update(visible=True, value=edit_concept), #concept_n
415
+ gr.update(visible=True,label = guidance_scale_label), #guidance_scale_n
416
+ gr.update(value=neg_guidance),#neg_guidance_n
417
+ gr.update(visible=False), #row_n
418
+ gr.update(visible=True), #row_n+1
419
+ sega_concepts_counter
420
+ )
421
+
422
+
423
+ def display_editing_options(run_button, clear_button, sega_tab):
424
+ return run_button.update(visible=True), clear_button.update(visible=True), sega_tab.update(visible=True)
425
+
426
+ def update_interactive_mode(add_button_label):
427
+ if add_button_label == "Clear":
428
+ return gr.update(interactive=False), gr.update(interactive=False)
429
+ else:
430
+ return gr.update(interactive=True), gr.update(interactive=True)
431
+
432
+ def update_dropdown_parms(dropdown):
433
+ if dropdown == 'custom':
434
+ return DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,DEFAULT_WARMUP_STEPS, DEFAULT_THRESHOLD
435
+ elif dropdown =='style':
436
+ return STYLE_SEGA_CONCEPT_GUIDANCE_SCALE,STYLE_WARMUP_STEPS, STYLE_THRESHOLD
437
+ elif dropdown =='object':
438
+ return OBJECT_SEGA_CONCEPT_GUIDANCE_SCALE,OBJECT_WARMUP_STEPS, OBJECT_THRESHOLD
439
+ elif dropdown =='faces':
440
+ return FACE_SEGA_CONCEPT_GUIDANCE_SCALE,FACE_WARMUP_STEPS, FACE_THRESHOLD
441
+
442
+
443
+ def reset_do_inversion():
444
+ return True
445
+
446
+ def reset_do_reconstruction():
447
+ do_reconstruction = True
448
+ return do_reconstruction
449
+
450
+ def reset_image_caption():
451
+ return ""
452
+
453
+ def update_inversion_progress_visibility(input_image, do_inversion):
454
+ if do_inversion and not input_image is None:
455
+ return inversion_progress.update(visible=True)
456
+ else:
457
+ return inversion_progress.update(visible=False)
458
+
459
+ def update_edit_progress_visibility(input_image, do_inversion):
460
+ # if do_inversion and not input_image is None:
461
+ # return inversion_progress.update(visible=True)
462
+ # else:
463
+ return inversion_progress.update(visible=True)
464
+
465
+
466
+ gr.HTML(intro)
467
+ wts = gr.State()
468
+ zs = gr.State()
469
+ reconstruction = gr.State()
470
+ do_inversion = gr.State(value=True)
471
+ do_reconstruction = gr.State(value=True)
472
+ sega_concepts_counter = gr.State(0)
473
+ image_caption = gr.State(value="")
474
+
475
+ with gr.Row():
476
+ input_image = gr.Image(label="Input Image", interactive=True, elem_id="input_image")
477
+ ddpm_edited_image = gr.Image(label=f"Pure DDPM Inversion Image", interactive=False, visible=False)
478
+ sega_edited_image = gr.Image(label=f"LEDITS Edited Image", interactive=False, elem_id="output_image")
479
+ input_image.style(height=365, width=365)
480
+ ddpm_edited_image.style(height=365, width=365)
481
+ sega_edited_image.style(height=365, width=365)
482
+
483
+ with gr.Group(visible=False) as share_btn_container:
484
+ with gr.Group(elem_id="share-btn-container"):
485
+ community_icon = gr.HTML(community_icon_html, visible=True)
486
+ loading_icon = gr.HTML(loading_icon_html, visible=False)
487
+ share_button = gr.Button("Share to community", elem_id="share-btn", visible=True)
488
+
489
+ with gr.Row():
490
+ with gr.Box(visible=False, elem_id="box1") as box1:
491
+ with gr.Row():
492
+ concept_1 = gr.Button(scale=3, value="")
493
+ remove_concept1 = gr.Button("x", scale=1, min_width=10)
494
+ with gr.Row():
495
+ guidnace_scale_1 = gr.Slider(label='Concept Guidance Scale', minimum=1, maximum=30,
496
+ info="How strongly the concept should modify the image",
497
+ value=DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,
498
+ step=0.5, interactive=True)
499
+ with gr.Box(visible=False, elem_id="box2") as box2:
500
+ with gr.Row():
501
+ concept_2 = gr.Button(scale=3, value="")
502
+ remove_concept2 = gr.Button("x", scale=1, min_width=10)
503
+ with gr.Row():
504
+ guidnace_scale_2 = gr.Slider(label='Concept Guidance Scale', minimum=1, maximum=30,
505
+ info="How strongly the concept should modify the image",
506
+ value=DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,
507
+ step=0.5, interactive=True)
508
+ with gr.Box(visible=False, elem_id="box3") as box3:
509
+ with gr.Row():
510
+ concept_3 = gr.Button(scale=3, value="")
511
+ remove_concept3 = gr.Button("x", scale=1, min_width=10)
512
+ with gr.Row():
513
+ guidnace_scale_3 = gr.Slider(label='Concept Guidance Scale', minimum=1, maximum=30,
514
+ info="How strongly the concept should modify the image",
515
+ value=DEFAULT_SEGA_CONCEPT_GUIDANCE_SCALE,
516
+ step=0.5, interactive=True)
517
+
518
+
519
+ with gr.Row():
520
+ inversion_progress = gr.Textbox(visible=False, label="Inversion progress")
521
+
522
+ with gr.Box():
523
+ intro_segs = gr.Markdown("Add/Remove Concepts from your Image <span style=\"font-size: 12px; color: rgb(156, 163, 175)\">with Semantic Guidance</span>")
524
+ # 1st SEGA concept
525
+ with gr.Row().style(mobile_collapse=False) as row1:
526
+ with gr.Column(scale=3, min_width=100):
527
+ with gr.Row().style(mobile_collapse=True):
528
+ # with gr.Column(scale=3, min_width=100):
529
+ edit_concept_1 = gr.Textbox(
530
+ label="Concept",
531
+ show_label=True,
532
+ max_lines=1, value="",
533
+ placeholder="E.g.: Sunglasses",
534
+ )
535
+ # with gr.Column(scale=2, min_width=100):# better mobile ui
536
+ dropdown1 = gr.Dropdown(label = "Edit Type", value ='custom' , choices=['custom','style', 'object', 'faces'])
537
+
538
+
539
+ with gr.Column(scale=1, min_width=100, visible=False):
540
+ neg_guidance_1 = gr.Checkbox(
541
+ label='Remove Concept?')
542
+
543
+ with gr.Column(scale=1, min_width=100):
544
+ with gr.Row().style(mobile_collapse=False): # better mobile ui
545
+ with gr.Column():
546
+ add_1 = gr.Button('Add')
547
+ remove_1 = gr.Button('Remove')
548
+
549
+
550
+ # 2nd SEGA concept
551
+ with gr.Row(visible=False).style(equal_height=True) as row2:
552
+ with gr.Column(scale=3, min_width=100):
553
+ with gr.Row().style(mobile_collapse=True): #better mobile UI
554
+ # with gr.Column(scale=3, min_width=100):
555
+ edit_concept_2 = gr.Textbox(
556
+ label="Concept",
557
+ show_label=True,
558
+ max_lines=1,
559
+ placeholder="E.g.: Realistic",
560
+ )
561
+ # with gr.Column(scale=2, min_width=100):# better mobile ui
562
+ dropdown2 = gr.Dropdown(label = "Edit Type", value ='custom' , choices=['custom','style', 'object', 'faces'])
563
+
564
+ with gr.Column(scale=1, min_width=100, visible=False):
565
+ neg_guidance_2 = gr.Checkbox(
566
+ label='Remove Concept?')
567
+
568
+ with gr.Column(scale=1, min_width=100):
569
+ with gr.Row().style(mobile_collapse=False): # better mobile ui
570
+ with gr.Column():
571
+ add_2 = gr.Button('Add')
572
+ remove_2 = gr.Button('Remove')
573
+
574
+ # 3rd SEGA concept
575
+ with gr.Row(visible=False).style(equal_height=True) as row3:
576
+ with gr.Column(scale=3, min_width=100):
577
+ with gr.Row().style(mobile_collapse=True): #better mobile UI
578
+ # with gr.Column(scale=3, min_width=100):
579
+ edit_concept_3 = gr.Textbox(
580
+ label="Concept",
581
+ show_label=True,
582
+ max_lines=1,
583
+ placeholder="E.g.: orange",
584
+ )
585
+ # with gr.Column(scale=2, min_width=100):
586
+ dropdown3 = gr.Dropdown(label = "Edit Type", value ='custom' , choices=['custom','style', 'object', 'faces'])
587
+
588
+ with gr.Column(scale=1, min_width=100, visible=False):
589
+ neg_guidance_3 = gr.Checkbox(
590
+ label='Remove Concept?',visible=True)
591
+
592
+ with gr.Column(scale=1, min_width=100):
593
+ with gr.Row().style(mobile_collapse=False): # better mobile ui
594
+ with gr.Column():
595
+ add_3 = gr.Button('Add')
596
+ remove_3 = gr.Button('Remove')
597
+
598
+ with gr.Row(visible=False).style(equal_height=True) as row4:
599
+ gr.Markdown("### Max of 3 concepts reached. Remove a concept to add more")
600
+
601
+ #with gr.Row(visible=False).style(mobile_collapse=False, equal_height=True):
602
+ # add_concept_button = gr.Button("+1 concept")
603
+
604
+
605
+
606
+ with gr.Row().style(mobile_collapse=False, equal_height=True):
607
+ tar_prompt = gr.Textbox(
608
+ label="Describe your edited image (optional)",
609
+ elem_id="target_prompt",
610
+ # show_label=False,
611
+ max_lines=1, value="", scale=3,
612
+ placeholder="Target prompt, DDPM Inversion", info = "DDPM Inversion Prompt. Can help with global changes, modify to what you would like to see"
613
+ )
614
+ # caption_button = gr.Button("Caption Image", scale=1)
615
+
616
+
617
+ with gr.Row():
618
+ run_button = gr.Button("Edit your image!", visible=True)
619
+
620
+
621
+ with gr.Accordion("Advanced Options", open=False):
622
+ with gr.Tabs() as tabs:
623
+
624
+ with gr.TabItem('General options', id=2):
625
+ with gr.Row():
626
+ with gr.Column(min_width=100):
627
+ clear_button = gr.Button("Clear", visible=True)
628
+ src_prompt = gr.Textbox(lines=1, label="Source Prompt", interactive=True, placeholder="")
629
+ steps = gr.Number(value=100, precision=0, label="Num Diffusion Steps", interactive=True)
630
+ src_cfg_scale = gr.Number(value=3.5, label=f"Source Guidance Scale", interactive=True)
631
+
632
+
633
+ with gr.Column(min_width=100):
634
+ reconstruct_button = gr.Button("Show Reconstruction", visible=False)
635
+ skip = gr.Slider(minimum=0, maximum=60, value=36, step=1, label="Skip Steps", interactive=True, info = "At which step to start denoising. Bigger values increase fidelity to input image")
636
+ tar_cfg_scale = gr.Slider(minimum=1, maximum=30,value=15, label=f"Guidance Scale", interactive=True)
637
+ seed = gr.Number(value=0, precision=0, label="Seed", interactive=True)
638
+ randomize_seed = gr.Checkbox(label='Randomize seed', value=False)
639
+
640
+ with gr.TabItem('SEGA options', id=3) as sega_advanced_tab:
641
+ # 1st SEGA concept
642
+ gr.Markdown("1st concept")
643
+ with gr.Row().style(mobile_collapse=False, equal_height=True):
644
+ warmup_1 = gr.Slider(label='Warmup', minimum=0, maximum=50,
645
+ value=DEFAULT_WARMUP_STEPS,
646
+ step=1, interactive=True, info="At which step to start applying semantic guidance. Bigger values reduce edit concept's effect")
647
+ threshold_1 = gr.Slider(label='Threshold', minimum=0.5, maximum=0.99,
648
+ value=DEFAULT_THRESHOLD, step=0.01, interactive=True,
649
+ info = "Lower the threshold for more effect (e.g. ~0.9 for style transfer)")
650
+
651
+ # 2nd SEGA concept
652
+ gr.Markdown("2nd concept")
653
+ with gr.Row() as row2_advanced:
654
+ warmup_2 = gr.Slider(label='Warmup', minimum=0, maximum=50,
655
+ value=DEFAULT_WARMUP_STEPS,
656
+ step=1, interactive=True, info="At which step to start applying semantic guidance. Bigger values reduce edit concept's effect")
657
+ threshold_2 = gr.Slider(label='Threshold', minimum=0.5, maximum=0.99,
658
+ value=DEFAULT_THRESHOLD,
659
+ step=0.01, interactive=True,
660
+ info = "Lower the threshold for more effect (e.g. ~0.9 for style transfer)")
661
+ # 3rd SEGA concept
662
+ gr.Markdown("3rd concept")
663
+ with gr.Row() as row3_advanced:
664
+ warmup_3 = gr.Slider(label='Warmup', minimum=0, maximum=50,
665
+ value=DEFAULT_WARMUP_STEPS, step=1,
666
+ interactive=True, info="At which step to start applying semantic guidance. Bigger values reduce edit concept's effect")
667
+ threshold_3 = gr.Slider(label='Threshold', minimum=0.5, maximum=0.99,
668
+ value=DEFAULT_THRESHOLD, step=0.01,
669
+ interactive=True,
670
+ info = "Lower the threshold for more effect (e.g. ~0.9 for style transfer)")
671
+
672
+ # caption_button.click(
673
+ # fn = caption_image,
674
+ # inputs = [input_image],
675
+ # outputs = [tar_prompt]
676
+ # )
677
+ #neg_guidance_1.change(fn = update_label, inputs=[neg_guidance_1], outputs=[add_1])
678
+ #neg_guidance_2.change(fn = update_label, inputs=[neg_guidance_2], outputs=[add_2])
679
+ #neg_guidance_3.change(fn = update_label, inputs=[neg_guidance_3], outputs=[add_3])
680
+ add_1.click(fn=update_counter,
681
+ inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3],
682
+ 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)
683
+ 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)
684
+ 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)
685
+
686
+ 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)
687
+ 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)
688
+ 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)
689
+
690
+ remove_concept1.click(
691
+ fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(
692
+ 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)
693
+ remove_concept2.click(
694
+ fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(
695
+ 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)
696
+ remove_concept3.click(
697
+ fn=update_counter,inputs=[sega_concepts_counter,edit_concept_1,edit_concept_2,edit_concept_3], outputs=sega_concepts_counter,queue=False).then(
698
+ 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)
699
+
700
+ #add_concept_button.click(fn = update_display_concept, inputs=sega_concepts_counter,
701
+ # outputs= [row2, row2_advanced, row3, row3_advanced, add_concept_button, sega_concepts_counter], queue = False)
702
+
703
+ run_button.click(
704
+ fn=edit,
705
+ inputs=[input_image,
706
+ wts, zs,
707
+ tar_prompt,
708
+ image_caption,
709
+ steps,
710
+ skip,
711
+ tar_cfg_scale,
712
+ edit_concept_1,edit_concept_2,edit_concept_3,
713
+ guidnace_scale_1,guidnace_scale_2,guidnace_scale_3,
714
+ warmup_1, warmup_2, warmup_3,
715
+ neg_guidance_1, neg_guidance_2, neg_guidance_3,
716
+ threshold_1, threshold_2, threshold_3, do_reconstruction, reconstruction,
717
+ do_inversion,
718
+ seed,
719
+ randomize_seed,
720
+ src_prompt,
721
+ src_cfg_scale
722
+
723
+
724
+ ],
725
+ outputs=[sega_edited_image, reconstruct_button, do_reconstruction, reconstruction, wts, zs, do_inversion, share_btn_container])
726
+ # .success(fn=update_gallery_display, inputs= [prev_output_image, sega_edited_image], outputs = [gallery, gallery, prev_output_image])
727
+
728
+
729
+ input_image.change(
730
+ fn = reset_do_inversion,
731
+ outputs = [do_inversion],
732
+ queue = False)
733
+ # Automatically start inverting upon input_image change
734
+ input_image.upload(fn = crop_image, inputs = [input_image], outputs = [input_image],queue=False).then(
735
+ fn = reset_do_inversion,
736
+ outputs = [do_inversion],
737
+ queue = False).then(fn = caption_image,
738
+ inputs = [input_image],
739
+ outputs = [tar_prompt, image_caption]).then(fn = update_inversion_progress_visibility, inputs =[input_image,do_inversion],
740
+ outputs=[inversion_progress],queue=False).then(
741
+ fn=load_and_invert,
742
+ inputs=[input_image,
743
+ do_inversion,
744
+ seed, randomize_seed,
745
+ wts, zs,
746
+ src_prompt,
747
+ tar_prompt,
748
+ steps,
749
+ src_cfg_scale,
750
+ skip,
751
+ tar_cfg_scale,
752
+ ],
753
+ # outputs=[ddpm_edited_image, wts, zs, do_inversion],
754
+ outputs=[wts, zs, do_inversion, inversion_progress],
755
+ ).then(fn = update_inversion_progress_visibility, inputs =[input_image,do_inversion],
756
+ outputs=[inversion_progress],queue=False).then(
757
+ lambda: reconstruct_button.update(visible=False),
758
+ outputs=[reconstruct_button]).then(
759
+ fn = reset_do_reconstruction,
760
+ outputs = [do_reconstruction],
761
+ queue = False)
762
+
763
+
764
+ # Repeat inversion (and reconstruction) when these params are changed:
765
+ src_prompt.change(
766
+ fn = reset_do_inversion,
767
+ outputs = [do_inversion], queue = False).then(
768
+ fn = reset_do_reconstruction,
769
+ outputs = [do_reconstruction], queue = False)
770
+
771
+ steps.change(
772
+ fn = reset_do_inversion,
773
+ outputs = [do_inversion], queue = False).then(
774
+ fn = reset_do_reconstruction,
775
+ outputs = [do_reconstruction], queue = False)
776
+
777
+
778
+ src_cfg_scale.change(
779
+ fn = reset_do_inversion,
780
+ outputs = [do_inversion], queue = False).then(
781
+ fn = reset_do_reconstruction,
782
+ outputs = [do_reconstruction], queue = False)
783
+
784
+ # Repeat only reconstruction these params are changed:
785
+
786
+ tar_prompt.change(
787
+ fn = reset_do_reconstruction,
788
+ outputs = [do_reconstruction], queue = False)
789
+
790
+ tar_cfg_scale.change(
791
+ fn = reset_do_reconstruction,
792
+ outputs = [do_reconstruction], queue = False)
793
+
794
+ skip.change(
795
+ fn = reset_do_reconstruction,
796
+ outputs = [do_reconstruction], queue = False)
797
+
798
+ dropdown1.change(fn=update_dropdown_parms, inputs = [dropdown1], outputs = [guidnace_scale_1,warmup_1, threshold_1], queue=False)
799
+ dropdown2.change(fn=update_dropdown_parms, inputs = [dropdown2], outputs = [guidnace_scale_2,warmup_2, threshold_2], queue=False)
800
+ dropdown3.change(fn=update_dropdown_parms, inputs = [dropdown3], outputs = [guidnace_scale_3,warmup_3, threshold_3], queue=False)
801
+
802
+ clear_components = [input_image,ddpm_edited_image,ddpm_edited_image,sega_edited_image, do_inversion,
803
+ src_prompt, steps, src_cfg_scale, seed,
804
+ tar_prompt, skip, tar_cfg_scale, reconstruct_button,reconstruct_button,
805
+ edit_concept_1, guidnace_scale_1,guidnace_scale_1,warmup_1, threshold_1, neg_guidance_1,dropdown1, concept_1, concept_1, row1,
806
+ edit_concept_2, guidnace_scale_2,guidnace_scale_2,warmup_2, threshold_2, neg_guidance_2,dropdown2, concept_2, concept_2, row2,
807
+ edit_concept_3, guidnace_scale_3,guidnace_scale_3,warmup_3, threshold_3, neg_guidance_3,dropdown3, concept_3,concept_3, row3,
808
+ row4,sega_concepts_counter, box1, box2, box3 ]
809
+
810
+ clear_components_output_vals = [None, None,ddpm_edited_image.update(visible=False), None, True,
811
+ "", DEFAULT_DIFFUSION_STEPS, DEFAULT_SOURCE_GUIDANCE_SCALE, DEFAULT_SEED,
812
+ "", DEFAULT_SKIP_STEPS, DEFAULT_TARGET_GUIDANCE_SCALE, reconstruct_button.update(value="Show Reconstruction"),reconstruct_button.update(visible=False),
813
+ "", 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),
814
+ "", 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),
815
+ "", 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),
816
+ box1.update(visible=False), box2.update(visible=False), box3.update(visible=False)]
817
+
818
+
819
+ clear_button.click(lambda: clear_components_output_vals, outputs =clear_components)
820
+
821
+ reconstruct_button.click(lambda: ddpm_edited_image.update(visible=True), outputs=[ddpm_edited_image]).then(fn = reconstruct,
822
+ inputs = [tar_prompt,
823
+ image_caption,
824
+ tar_cfg_scale,
825
+ skip,
826
+ wts, zs,
827
+ do_reconstruction,
828
+ reconstruction,
829
+ reconstruct_button],
830
+ outputs = [ddpm_edited_image,reconstruction, ddpm_edited_image, do_reconstruction, reconstruct_button])
831
+
832
+ randomize_seed.change(
833
+ fn = randomize_seed_fn,
834
+ inputs = [seed, randomize_seed],
835
+ outputs = [seed],
836
+ queue = False)
837
+
838
+ share_button.click(None, [], [], _js=share_js)
839
+
840
+ gr.Examples(
841
+ label='Examples',
842
+ fn=swap_visibilities,
843
+ run_on_click=True,
844
+ examples=get_example(),
845
+ inputs=[input_image,
846
+ edit_concept_1,
847
+ edit_concept_2,
848
+ tar_prompt,
849
+ sega_edited_image,
850
+ guidnace_scale_1,
851
+ guidnace_scale_2,
852
+ warmup_1,
853
+ warmup_2,
854
+ neg_guidance_1,
855
+ neg_guidance_2,
856
+ steps,
857
+ skip,
858
+ tar_cfg_scale,
859
+ sega_concepts_counter
860
+ ],
861
+ outputs=[share_btn_container, 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],
862
+ cache_examples=True
863
+ )
864
+
865
+
866
+ demo.queue()
867
+ 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
share_btn.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ community_icon_html = """<svg id="share-btn-share-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32">
2
+ <path d="M20.6081 3C21.7684 3 22.8053 3.49196 23.5284 4.38415C23.9756 4.93678 24.4428 5.82749 24.4808 7.16133C24.9674 7.01707 25.4353 6.93643 25.8725 6.93643C26.9833 6.93643 27.9865 7.37587 28.696 8.17411C29.6075 9.19872 30.0124 10.4579 29.8361 11.7177C29.7523 12.3177 29.5581 12.8555 29.2678 13.3534C29.8798 13.8646 30.3306 14.5763 30.5485 15.4322C30.719 16.1032 30.8939 17.5006 29.9808 18.9403C30.0389 19.0342 30.0934 19.1319 30.1442 19.2318C30.6932 20.3074 30.7283 21.5229 30.2439 22.6548C29.5093 24.3704 27.6841 25.7219 24.1397 27.1727C21.9347 28.0753 19.9174 28.6523 19.8994 28.6575C16.9842 29.4379 14.3477 29.8345 12.0653 29.8345C7.87017 29.8345 4.8668 28.508 3.13831 25.8921C0.356375 21.6797 0.754104 17.8269 4.35369 14.1131C6.34591 12.058 7.67023 9.02782 7.94613 8.36275C8.50224 6.39343 9.97271 4.20438 12.4172 4.20438H12.4179C12.6236 4.20438 12.8314 4.2214 13.0364 4.25468C14.107 4.42854 15.0428 5.06476 15.7115 6.02205C16.4331 5.09583 17.134 4.359 17.7682 3.94323C18.7242 3.31737 19.6794 3 20.6081 3ZM20.6081 5.95917C20.2427 5.95917 19.7963 6.1197 19.3039 6.44225C17.7754 7.44319 14.8258 12.6772 13.7458 14.7131C13.3839 15.3952 12.7655 15.6837 12.2086 15.6837C11.1036 15.6837 10.2408 14.5497 12.1076 13.1085C14.9146 10.9402 13.9299 7.39584 12.5898 7.1776C12.5311 7.16799 12.4731 7.16355 12.4172 7.16355C11.1989 7.16355 10.6615 9.33114 10.6615 9.33114C10.6615 9.33114 9.0863 13.4148 6.38031 16.206C3.67434 18.998 3.5346 21.2388 5.50675 24.2246C6.85185 26.2606 9.42666 26.8753 12.0653 26.8753C14.8021 26.8753 17.6077 26.2139 19.1799 25.793C19.2574 25.7723 28.8193 22.984 27.6081 20.6107C27.4046 20.212 27.0693 20.0522 26.6471 20.0522C24.9416 20.0522 21.8393 22.6726 20.5057 22.6726C20.2076 22.6726 19.9976 22.5416 19.9116 22.222C19.3433 20.1173 28.552 19.2325 27.7758 16.1839C27.639 15.6445 27.2677 15.4256 26.746 15.4263C24.4923 15.4263 19.4358 19.5181 18.3759 19.5181C18.2949 19.5181 18.2368 19.4937 18.2053 19.4419C17.6743 18.557 17.9653 17.9394 21.7082 15.6009C25.4511 13.2617 28.0783 11.8545 26.5841 10.1752C26.4121 9.98141 26.1684 9.8956 25.8725 9.8956C23.6001 9.89634 18.2311 14.9403 18.2311 14.9403C18.2311 14.9403 16.7821 16.496 15.9057 16.496C15.7043 16.496 15.533 16.4139 15.4169 16.2112C14.7956 15.1296 21.1879 10.1286 21.5484 8.06535C21.7928 6.66715 21.3771 5.95917 20.6081 5.95917Z" fill="#FF9D00"></path>
3
+ <path d="M5.50686 24.2246C3.53472 21.2387 3.67446 18.9979 6.38043 16.206C9.08641 13.4147 10.6615 9.33111 10.6615 9.33111C10.6615 9.33111 11.2499 6.95933 12.59 7.17757C13.93 7.39581 14.9139 10.9401 12.1069 13.1084C9.29997 15.276 12.6659 16.7489 13.7459 14.713C14.8258 12.6772 17.7747 7.44316 19.304 6.44221C20.8326 5.44128 21.9089 6.00204 21.5484 8.06532C21.188 10.1286 14.795 15.1295 15.4171 16.2118C16.0391 17.2934 18.2312 14.9402 18.2312 14.9402C18.2312 14.9402 25.0907 8.49588 26.5842 10.1752C28.0776 11.8545 25.4512 13.2616 21.7082 15.6008C17.9646 17.9393 17.6744 18.557 18.2054 19.4418C18.7372 20.3266 26.9998 13.1351 27.7759 16.1838C28.5513 19.2324 19.3434 20.1173 19.9117 22.2219C20.48 24.3274 26.3979 18.2382 27.6082 20.6107C28.8193 22.9839 19.2574 25.7722 19.18 25.7929C16.0914 26.62 8.24723 28.3726 5.50686 24.2246Z" fill="#FFD21E"></path>
4
+ </svg>"""
5
+
6
+ loading_icon_html = """<svg id="share-btn-loading-icon" style="display:none;" class="animate-spin"
7
+ style="color: #ffffff;
8
+ "
9
+ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" fill="none" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><circle style="opacity: 0.25;" cx="12" cy="12" r="10" stroke="white" stroke-width="4"></circle><path style="opacity: 0.75;" fill="white" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>"""
10
+
11
+ share_js = r"""async () => {
12
+ async function uploadFile(file){
13
+ const UPLOAD_URL = 'https://huggingface.co/uploads';
14
+ const response = await fetch(UPLOAD_URL, {
15
+ method: 'POST',
16
+ headers: {
17
+ 'Content-Type': file.type,
18
+ 'X-Requested-With': 'XMLHttpRequest',
19
+ },
20
+ body: file,
21
+ });
22
+ const url = await response.text();
23
+ return url;
24
+ }
25
+
26
+ function getButtonText(componentId) {
27
+ const buttonEl = gradioEl.querySelector(`${componentId} button`);
28
+ return buttonEl ? buttonEl.textContent : '';
29
+ }
30
+
31
+ const gradioEl = document.querySelector('body > gradio-app');
32
+ const imgEls = [gradioEl.querySelector('#input_image img'), gradioEl.querySelector('#output_image img')];
33
+ const concepts = [
34
+ { value: getButtonText('#box1'), parent: gradioEl.querySelector('#box1 span[data-testid="block-info"]') },
35
+ { value: getButtonText('#box2'), parent: gradioEl.querySelector('#box2 span[data-testid="block-info"]') },
36
+ { value: getButtonText('#box3'), parent: gradioEl.querySelector('#box3 span[data-testid="block-info"]') }
37
+ ];
38
+
39
+ const promptTxt = gradioEl.querySelector('#target_prompt input').value;
40
+ const shareBtnEl = gradioEl.querySelector('#share-btn');
41
+ const shareIconEl = gradioEl.querySelector('#share-btn-share-icon');
42
+ const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon');
43
+ if(!imgEls[1]){
44
+ return;
45
+ };
46
+ shareBtnEl.style.pointerEvents = 'none';
47
+ shareIconEl.style.display = 'none';
48
+ loadingIconEl.style.removeProperty('display');
49
+
50
+ async function processImage(imgEl, imgId) {
51
+ const res = await fetch(imgEl.src);
52
+ const blob = await res.blob();
53
+ const fileType = blob.type.includes('png') ? 'png' : 'jpg';
54
+ const fileName = `diffuse-the-rest-${imgId}.${fileType}`;
55
+ return new File([blob], fileName, { type: blob.type });
56
+ }
57
+
58
+ const files = await Promise.all(imgEls.map((imgEl, index) => processImage(imgEl, Date.now() + index % 200)));
59
+ const urls = await Promise.all(files.map((file) => uploadFile(file)));
60
+
61
+ const labels = ['Source image', 'Target image'];
62
+ const htmlImgs = urls.map((url, index) => `<div>${labels[index]}: <img src='${url}' width='400' height='400' style="margin: 0"></div>`);
63
+
64
+ let descriptionMd = `<div style='display: flex; flex-wrap: wrap; column-gap: 0.75rem;'>${htmlImgs.join(`\n`)}</div>`;
65
+
66
+ if (promptTxt) {
67
+ descriptionMd += `<span style="font-size:1.2em">Target image prompt: <b>${promptTxt}</b></span><br>`;
68
+ } else {
69
+ descriptionMd += `<span style="font-size:1.2em">Target image prompt: <b>""</b></span><br>`;
70
+ }
71
+
72
+ const conceptHeaders = [];
73
+ const conceptDescriptions = [];
74
+ const conceptTableRows = [];
75
+ concepts.forEach((concept, index) => {
76
+ if (concept.value) {
77
+ const label = concept.parent.textContent.includes('Negative') ? `remove concept` : `add concept`;
78
+ conceptHeaders.push(`<th>${label}</th>`);
79
+ conceptDescriptions.push(`${label}: ${concept.value}`);
80
+ conceptTableRows.push(`<td>${concept.value}</td>`);
81
+ }
82
+ });
83
+
84
+ let title = 'Editing';
85
+ if (promptTxt) {
86
+ title += ` "${promptTxt}"`;
87
+ }
88
+ if (conceptDescriptions.length > 0) {
89
+ title += ` to ${conceptDescriptions.join(', ')}`;
90
+ descriptionMd += `<table style="font-size: 1.1em">
91
+ <tr>
92
+ ${conceptHeaders.join('\n')}
93
+ </tr>
94
+ <tr>
95
+ ${conceptTableRows.join('\n')}
96
+ </tr>
97
+ </table>`;
98
+ }
99
+
100
+ const params = new URLSearchParams({
101
+ title: title,
102
+ description: descriptionMd,
103
+ });
104
+ const paramsStr = params.toString();
105
+ window.open(`https://huggingface.co/spaces/editing-images/ledits/discussions/new?${paramsStr}`, '_blank');
106
+ shareBtnEl.style.removeProperty('pointer-events');
107
+ shareIconEl.style.removeProperty('display');
108
+ loadingIconEl.style.display = 'none';
109
+ }"""
style.css ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
78
+ #share-btn-container {
79
+ display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem; margin-left: auto;
80
+ }
81
+ #share-btn {
82
+ all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;
83
+ }
84
+ #share-btn * {
85
+ all: unset;
86
+ }
87
+ #share-btn-container div:nth-child(-n+2){
88
+ width: auto !important;
89
+ min-height: 0px !important;
90
+ }
91
+ #share-btn-container .wrap {
92
+ display: none !important;
93
+ }
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