yfyangd commited on
Commit
6b78425
1 Parent(s): d6468ff

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -0
app.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import gradio as gr
4
+ os.system('git clone https://github.com/openai/CLIP')
5
+ os.system('git clone https://github.com/Yfyangd/diffusion')
6
+ os.system('pip install -e ./CLIP')
7
+ os.system('pip install -e ./diffusion')
8
+ os.system('pip install lpips')
9
+ os.system("curl -OL 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt'")
10
+
11
+
12
+
13
+ import io
14
+ import math
15
+ import sys
16
+ import lpips
17
+ from PIL import Image
18
+ import requests
19
+ import torch
20
+ from torch import nn
21
+ from torch.nn import functional as F
22
+ from torchvision import transforms
23
+ from torchvision.transforms import functional as TF
24
+ from tqdm.notebook import tqdm
25
+ sys.path.append('./CLIP')
26
+ sys.path.append('./diffusion')
27
+ import clip
28
+ from diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults
29
+ import numpy as np
30
+ import imageio
31
+
32
+ torch.hub.download_url_to_file('https://images.pexels.com/photos/68767/divers-underwater-ocean-swim-68767.jpeg', 'coralreef.jpeg')
33
+
34
+ def fetch(url_or_path):
35
+ if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'):
36
+ r = requests.get(url_or_path)
37
+ r.raise_for_status()
38
+ fd = io.BytesIO()
39
+ fd.write(r.content)
40
+ fd.seek(0)
41
+ return fd
42
+ return open(url_or_path, 'rb')
43
+ def parse_prompt(prompt):
44
+ if prompt.startswith('http://') or prompt.startswith('https://'):
45
+ vals = prompt.rsplit(':', 2)
46
+ vals = [vals[0] + ':' + vals[1], *vals[2:]]
47
+ else:
48
+ vals = prompt.rsplit(':', 1)
49
+ vals = vals + ['', '1'][len(vals):]
50
+ return vals[0], float(vals[1])
51
+ class MakeCutouts(nn.Module):
52
+ def __init__(self, cut_size, cutn, cut_pow=1.):
53
+ super().__init__()
54
+ self.cut_size = cut_size
55
+ self.cutn = cutn
56
+ self.cut_pow = cut_pow
57
+ def forward(self, input):
58
+ sideY, sideX = input.shape[2:4]
59
+ max_size = min(sideX, sideY)
60
+ min_size = min(sideX, sideY, self.cut_size)
61
+ cutouts = []
62
+ for _ in range(self.cutn):
63
+ size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)
64
+ offsetx = torch.randint(0, sideX - size + 1, ())
65
+ offsety = torch.randint(0, sideY - size + 1, ())
66
+ cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
67
+ cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size))
68
+ return torch.cat(cutouts)
69
+ def spherical_dist_loss(x, y):
70
+ x = F.normalize(x, dim=-1)
71
+ y = F.normalize(y, dim=-1)
72
+ return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
73
+ def tv_loss(input):
74
+ """L2 total variation loss, as in Mahendran et al."""
75
+ input = F.pad(input, (0, 1, 0, 1), 'replicate')
76
+ x_diff = input[..., :-1, 1:] - input[..., :-1, :-1]
77
+ y_diff = input[..., 1:, :-1] - input[..., :-1, :-1]
78
+ return (x_diff**2 + y_diff**2).mean([1, 2, 3])
79
+ def range_loss(input):
80
+ return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3])
81
+
82
+ def inference(text, init_image, skip_timesteps, clip_guidance_scale, tv_scale, range_scale, init_scale, seed, image_prompts,timestep_respacing, cutn):
83
+ # Model settings
84
+ model_config = model_and_diffusion_defaults()
85
+ model_config.update({
86
+ 'attention_resolutions': '32, 16, 8',
87
+ 'class_cond': False,
88
+ 'diffusion_steps': 1000,
89
+ 'rescale_timesteps': True,
90
+ 'timestep_respacing': str(timestep_respacing), # Modify this value to decrease the number of
91
+ # timesteps.
92
+ 'image_size': 256,
93
+ 'learn_sigma': True,
94
+ 'noise_schedule': 'linear',
95
+ 'num_channels': 256,
96
+ 'num_head_channels': 64,
97
+ 'num_res_blocks': 2,
98
+ 'resblock_updown': True,
99
+ 'use_fp16': True,
100
+ 'use_scale_shift_norm': True,
101
+ })
102
+ # Load models
103
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
104
+ print('Using device:', device)
105
+ model, diffusion = create_model_and_diffusion(**model_config)
106
+ model.load_state_dict(torch.load('256x256_diffusion_uncond.pt', map_location='cpu'))
107
+ model.requires_grad_(False).eval().to(device)
108
+ for name, param in model.named_parameters():
109
+ if 'qkv' in name or 'norm' in name or 'proj' in name:
110
+ param.requires_grad_()
111
+ if model_config['use_fp16']:
112
+ model.convert_to_fp16()
113
+ clip_model = clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device)
114
+ clip_size = clip_model.visual.input_resolution
115
+ normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
116
+ std=[0.26862954, 0.26130258, 0.27577711])
117
+ lpips_model = lpips.LPIPS(net='vgg').to(device)
118
+
119
+ #def inference(text, init_image, skip_timesteps, clip_guidance_scale, tv_scale, range_scale, init_scale, seed, image_prompt):
120
+ all_frames = []
121
+ prompts = [text]
122
+ if image_prompts:
123
+ image_prompts = [image_prompts.name]
124
+ else:
125
+ image_prompts = []
126
+ batch_size = 1
127
+ clip_guidance_scale = clip_guidance_scale # Controls how much the image should look like the prompt.
128
+ tv_scale = tv_scale # Controls the smoothness of the final output.
129
+ range_scale = range_scale # Controls how far out of range RGB values are allowed to be.
130
+ cutn = cutn
131
+ n_batches = 1
132
+ if init_image:
133
+ init_image = init_image.name
134
+ else:
135
+ init_image = None # This can be an URL or Colab local path and must be in quotes.
136
+ skip_timesteps = skip_timesteps # This needs to be between approx. 200 and 500 when using an init image.
137
+ # Higher values make the output look more like the init.
138
+ init_scale = init_scale # This enhances the effect of the init image, a good value is 1000.
139
+ seed = seed
140
+
141
+ if seed is not None:
142
+ torch.manual_seed(seed)
143
+ make_cutouts = MakeCutouts(clip_size, cutn)
144
+ side_x = side_y = model_config['image_size']
145
+ target_embeds, weights = [], []
146
+ for prompt in prompts:
147
+ txt, weight = parse_prompt(prompt)
148
+ target_embeds.append(clip_model.encode_text(clip.tokenize(txt).to(device)).float())
149
+ weights.append(weight)
150
+ for prompt in image_prompts:
151
+ path, weight = parse_prompt(prompt)
152
+ img = Image.open(fetch(path)).convert('RGB')
153
+ img = TF.resize(img, min(side_x, side_y, *img.size), transforms.InterpolationMode.LANCZOS)
154
+ batch = make_cutouts(TF.to_tensor(img).unsqueeze(0).to(device))
155
+ embed = clip_model.encode_image(normalize(batch)).float()
156
+ target_embeds.append(embed)
157
+ weights.extend([weight / cutn] * cutn)
158
+ target_embeds = torch.cat(target_embeds)
159
+ weights = torch.tensor(weights, device=device)
160
+ if weights.sum().abs() < 1e-3:
161
+ raise RuntimeError('The weights must not sum to 0.')
162
+ weights /= weights.sum().abs()
163
+ init = None
164
+ if init_image is not None:
165
+ init = Image.open(fetch(init_image)).convert('RGB')
166
+ init = init.resize((side_x, side_y), Image.LANCZOS)
167
+ init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1)
168
+ cur_t = None
169
+ def cond_fn(x, t, y=None):
170
+ with torch.enable_grad():
171
+ x = x.detach().requires_grad_()
172
+ n = x.shape[0]
173
+ my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t
174
+ out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y})
175
+ fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t]
176
+ x_in = out['pred_xstart'] * fac + x * (1 - fac)
177
+ clip_in = normalize(make_cutouts(x_in.add(1).div(2)))
178
+ image_embeds = clip_model.encode_image(clip_in).float()
179
+ dists = spherical_dist_loss(image_embeds.unsqueeze(1), target_embeds.unsqueeze(0))
180
+ dists = dists.view([cutn, n, -1])
181
+ losses = dists.mul(weights).sum(2).mean(0)
182
+ tv_losses = tv_loss(x_in)
183
+ range_losses = range_loss(out['pred_xstart'])
184
+ loss = losses.sum() * clip_guidance_scale + tv_losses.sum() * tv_scale + range_losses.sum() * range_scale
185
+ if init is not None and init_scale:
186
+ init_losses = lpips_model(x_in, init)
187
+ loss = loss + init_losses.sum() * init_scale
188
+ return -torch.autograd.grad(loss, x)[0]
189
+ if model_config['timestep_respacing'].startswith('ddim'):
190
+ sample_fn = diffusion.ddim_sample_loop_progressive
191
+ else:
192
+ sample_fn = diffusion.p_sample_loop_progressive
193
+ for i in range(n_batches):
194
+ cur_t = diffusion.num_timesteps - skip_timesteps - 1
195
+ samples = sample_fn(
196
+ model,
197
+ (batch_size, 3, side_y, side_x),
198
+ clip_denoised=False,
199
+ model_kwargs={},
200
+ cond_fn=cond_fn,
201
+ progress=True,
202
+ skip_timesteps=skip_timesteps,
203
+ init_image=init,
204
+ randomize_class=True,
205
+ )
206
+ for j, sample in enumerate(samples):
207
+ cur_t -= 1
208
+ if j % 1 == 0 or cur_t == -1:
209
+ print()
210
+ for k, image in enumerate(sample['pred_xstart']):
211
+ #filename = f'progress_{i * batch_size + k:05}.png'
212
+ img = TF.to_pil_image(image.add(1).div(2).clamp(0, 1))
213
+ all_frames.append(img)
214
+ tqdm.write(f'Batch {i}, step {j}, output {k}:')
215
+ #display.display(display.Image(filename))
216
+ writer = imageio.get_writer('video.mp4', fps=5)
217
+ for im in all_frames:
218
+ writer.append_data(np.array(im))
219
+ writer.close()
220
+ return img, 'video.mp4'
221
+
222
+ title = "CLIP Guided Diffusion Model"
223
+ description = "Gradio demo for CLIP Guided Diffusion. To use it, simply add your text, or click one of the examples to load them. Read more at the links below."
224
+ article = "<p style='text-align: center'> By Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses OpenAI's 256x256 unconditional ImageNet diffusion model (https://github.com/openai/guided-diffusion) together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images. | <a href='https://colab.research.google.com/drive/12a_Wrfi2_gwwAuN3VvMTwVMz9TfqctNj' target='_blank'>Colab</a></p>"
225
+ iface = gr.Interface(inference, inputs=["text",gr.inputs.Image(type="file", label='initial image (optional)', optional=True),gr.inputs.Slider(minimum=0, maximum=45, step=1, default=10, label="skip_timesteps"), gr.inputs.Slider(minimum=0, maximum=3000, step=1, default=600, label="clip guidance scale (Controls how much the image should look like the prompt)"), gr.inputs.Slider(minimum=0, maximum=1000, step=1, default=0, label="tv_scale (Controls the smoothness of the final output)"), gr.inputs.Slider(minimum=0, maximum=1000, step=1, default=0, label="range_scale (Controls how far out of range RGB values are allowed to be)"), gr.inputs.Slider(minimum=0, maximum=1000, step=1, default=0, label="init_scale (This enhances the effect of the init image)"), gr.inputs.Number(default=0, label="Seed"), gr.inputs.Image(type="file", label='image prompt (optional)', optional=True), gr.inputs.Slider(minimum=50, maximum=500, step=1, default=50, label="timestep respacing"),gr.inputs.Slider(minimum=1, maximum=64, step=1, default=32, label="cutn")], outputs=["image","video"], title=title, description=description, article=article, examples=[["coral reef city by artistation artists", "coralreef.jpeg", 0, 1000, 150, 50, 0, 0, "coralreef.jpeg", 90, 32]])
226
+ iface.launch()