ToletiSri commited on
Commit
c9f5f86
1 Parent(s): d3b2e42

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +207 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from base64 import b64encode
3
+
4
+ import numpy
5
+ import torch
6
+ from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel, StableDiffusionPipeline
7
+ from huggingface_hub import notebook_login
8
+
9
+ # For video display:
10
+ from IPython.display import HTML
11
+ from matplotlib import pyplot as plt
12
+ from pathlib import Path
13
+ from PIL import Image
14
+ from torch import autocast
15
+ from torchvision import transforms as tfms
16
+ from tqdm.auto import tqdm
17
+ from transformers import CLIPTextModel, CLIPTokenizer, logging
18
+ import os
19
+
20
+ torch.manual_seed(1)
21
+ if not (Path.home()/'.cache/huggingface'/'token').exists(): notebook_login()
22
+
23
+ # Supress some unnecessary warnings when loading the CLIPTextModel
24
+ logging.set_verbosity_error()
25
+
26
+ # Set device
27
+ torch_device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
28
+ if "mps" == torch_device: os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = "1"
29
+
30
+ model_nm = "CompVis/stable-diffusion-v1-4"
31
+
32
+ output_dir="sd-concept-output"
33
+ pipe = StableDiffusionPipeline.from_pretrained(model_nm).to(torch_device)
34
+
35
+ # Load the autoencoder model which will be used to decode the latents into image space.
36
+ vae = pipe.vae
37
+ tokenizer = pipe.tokenizer
38
+
39
+ # Load the tokenizer and text encoder to tokenize and encode the text.
40
+ #tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14", torch_dtype=torch.float16)
41
+ text_encoder =pipe.text_encoder
42
+
43
+ # The UNet model for generating the latents.
44
+ unet = pipe.unet
45
+
46
+ # The noise scheduler
47
+ scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
48
+
49
+ # To the GPU we go!
50
+ vae = vae.to(torch_device)
51
+ text_encoder = text_encoder.to(torch_device)
52
+ unet = unet.to(torch_device);
53
+
54
+ pipe.load_textual_inversion("sd-concepts-library/madhubani-art")
55
+ pipe.load_textual_inversion("sd-concepts-library/line-art")
56
+ pipe.load_textual_inversion("sd-concepts-library/cat-toy")
57
+ pipe.load_textual_inversion("sd-concepts-library/concept-art")
58
+
59
+ def pil_to_latent(input_im):
60
+ # Single image -> single latent in a batch (so size 1, 4, 64, 64)
61
+ with torch.no_grad():
62
+ latent = vae.encode(tfms.ToTensor()(input_im).unsqueeze(0).to(torch_device)*2-1) # Note scaling
63
+ return 0.18215 * latent.latent_dist.sample()
64
+
65
+ def latents_to_pil(latents):
66
+ # bath of latents -> list of images
67
+ latents = (1 / 0.18215) * latents
68
+ with torch.no_grad():
69
+ image = vae.decode(latents).sample
70
+ image = (image / 2 + 0.5).clamp(0, 1)
71
+ image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
72
+ images = (image * 255).round().astype("uint8")
73
+ pil_images = [Image.fromarray(image) for image in images]
74
+ return pil_images
75
+
76
+ # Prep Scheduler
77
+ def set_timesteps(scheduler, num_inference_steps):
78
+ scheduler.set_timesteps(num_inference_steps)
79
+ scheduler.timesteps = scheduler.timesteps.to(torch.float32) # minor fix to ensure MPS compatibility, fixed in diffusers
80
+
81
+ def saturation_loss(images):
82
+ # Calculate saturation for each pixel in the input image tensor
83
+ max_vals, _ = torch.max(images, dim=1, keepdim=True)
84
+ min_vals, _ = torch.min(images, dim=1, keepdim=True)
85
+ saturation = (max_vals - min_vals) / max_vals.clamp(min=1e-7) # Avoid division by zero
86
+
87
+ # Calculate mean saturation across the image
88
+ mean_saturation = torch.mean(saturation, dim=(2, 3)) # Average over width and height
89
+
90
+ # Calculate the loss as the negative mean saturation (proportional to saturation)
91
+ #loss = torch.abs(saturation - 0.9).mean()
92
+
93
+ return mean_saturation/10000
94
+
95
+ def generateImage(prompt, lossScale):
96
+ #prompt = 'a puppy in <cat-toy> style' #@param
97
+ height = 512 # default height of Stable Diffusion
98
+ width = 512 # default width of Stable Diffusion
99
+ num_inference_steps = 200 #@param # Number of denoising steps
100
+ guidance_scale = 8 #@param # Scale for classifier-free guidance
101
+ generator = torch.manual_seed(32) # Seed generator to create the inital latent noise
102
+ batch_size = 1
103
+ saturation_loss_Scale = lossScale #@param
104
+
105
+ # Prep text
106
+ text_input = tokenizer([prompt], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
107
+ with torch.no_grad():
108
+ text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]
109
+
110
+ # And the uncond. input as before:
111
+ max_length = text_input.input_ids.shape[-1]
112
+ uncond_input = tokenizer(
113
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
114
+ )
115
+ with torch.no_grad():
116
+ uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]
117
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
118
+
119
+ # Prep Scheduler
120
+ set_timesteps(scheduler, num_inference_steps)
121
+
122
+ # Prep latents
123
+ latents = torch.randn(
124
+ (batch_size, unet.in_channels, height // 8, width // 8),
125
+ generator=generator,
126
+ )
127
+ latents = latents.to(torch_device)
128
+ latents = latents * scheduler.init_noise_sigma
129
+
130
+ # Loop
131
+ for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
132
+ # expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
133
+ latent_model_input = torch.cat([latents] * 2)
134
+ sigma = scheduler.sigmas[i]
135
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
136
+
137
+ # predict the noise residual
138
+ with torch.no_grad():
139
+ noise_pred = unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
140
+
141
+ # perform CFG
142
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
143
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
144
+
145
+ #### ADDITIONAL GUIDANCE ###
146
+ if i%5 == 0:
147
+ # Requires grad on the latents
148
+ latents = latents.detach().requires_grad_()
149
+
150
+ # Get the predicted x0:
151
+ # latents_x0 = latents - sigma * noise_pred
152
+ latents_x0 = scheduler.step(noise_pred, t, latents).pred_original_sample
153
+ scheduler._step_index = scheduler._step_index - 1
154
+
155
+ # Decode to image space
156
+ denoised_images = vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5 # range (0, 1)
157
+
158
+ # Calculate loss
159
+ loss = saturation_loss(denoised_images) * saturation_loss_Scale
160
+ #loss = loss.detach().requires_grad_()
161
+ #print('loss.grad_fn = {}'.format(grad_fn))
162
+
163
+ # Occasionally print it out
164
+ if i%10==0:
165
+ print(i, 'loss:', loss.item())
166
+
167
+ # Get gradient
168
+ cond_grad = torch.autograd.grad(loss, latents)[0]
169
+
170
+ # Modify the latents based on this gradient
171
+ latents = latents.detach() - cond_grad * sigma**2
172
+
173
+ # Now step with scheduler
174
+ latents = scheduler.step(noise_pred, t, latents).prev_sample
175
+
176
+
177
+ custom_loss_image = latents_to_pil(latents)[0]
178
+ return custom_loss_image
179
+
180
+ def inference(imgText, style, customLoss="no"):
181
+ prompt = f'a {imgText} in <{style}> style'
182
+ if (customLoss == "yes") :
183
+ outImage = generateImage(prompt, 2)
184
+ return outImage
185
+ else:
186
+ outImage = generateImage(prompt, 0)
187
+ return outImage
188
+
189
+
190
+ title = "TSAI S20 Assignment: Use a pretrained Sstable Diffusion model and give a demo on its workig"
191
+ description = "A simple Gradio interface that accepts a text and style, and generated an image using stable diffusion pipeline"
192
+
193
+ examples = [["puppy","cat-toy","yes"]]
194
+
195
+ demo = gr.Interface(
196
+ inference,
197
+ inputs = [gr.Textbox("Enter an image you want to generate"),
198
+ gr.Dropdown(["madhubani-art", "line-art", "cat-toy","concept-art"], label="Choose your style"),
199
+ gr.Radio(["yes", "no"], label="Add custom saturation loss?")
200
+ ],
201
+ outputs = [gr.Image(shape=(512, 512), label="Generated Image")],
202
+ title = title,
203
+ description = description,
204
+ examples = examples,
205
+ )
206
+ demo.launch()
207
+
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ torch
2
+ numpy