Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
os.system("pip install gradio==2.4.6")
|
3 |
+
os.system('pip freeze')
|
4 |
+
import torch
|
5 |
+
torch.hub.download_url_to_file('https://heibox.uni-heidelberg.de/d/a7530b09fed84f80a887/files/?p=%2Fconfigs%2Fmodel.yaml&dl=1', 'vqgan_imagenet_f16_16384.yaml')
|
6 |
+
torch.hub.download_url_to_file('https://heibox.uni-heidelberg.de/d/a7530b09fed84f80a887/files/?p=%2Fckpts%2Flast.ckpt&dl=1', 'vqgan_imagenet_f16_16384.ckpt')
|
7 |
+
import argparse
|
8 |
+
import math
|
9 |
+
from pathlib import Path
|
10 |
+
import sys
|
11 |
+
sys.path.insert(1, './taming-transformers')
|
12 |
+
from base64 import b64encode
|
13 |
+
from omegaconf import OmegaConf
|
14 |
+
from PIL import Image
|
15 |
+
from taming.models import cond_transformer, vqgan
|
16 |
+
import taming.modules
|
17 |
+
from torch import nn, optim
|
18 |
+
from torch.nn import functional as F
|
19 |
+
from torchvision import transforms
|
20 |
+
from torchvision.transforms import functional as TF
|
21 |
+
from tqdm.notebook import tqdm
|
22 |
+
from CLIP import clip
|
23 |
+
import kornia.augmentation as K
|
24 |
+
import numpy as np
|
25 |
+
import imageio
|
26 |
+
from PIL import ImageFile, Image
|
27 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
28 |
+
import gradio as gr
|
29 |
+
import nvidia_smi
|
30 |
+
nvidia_smi.nvmlInit()
|
31 |
+
handle = nvidia_smi.nvmlDeviceGetHandleByIndex(0)
|
32 |
+
# card id 0 hardcoded here, there is also a call to get all available card ids, so we could iterate
|
33 |
+
torch.hub.download_url_to_file('https://images.pexels.com/photos/158028/bellingrath-gardens-alabama-landscape-scenic-158028.jpeg', 'garden.jpeg')
|
34 |
+
torch.hub.download_url_to_file('https://images.pexels.com/photos/68767/divers-underwater-ocean-swim-68767.jpeg', 'coralreef.jpeg')
|
35 |
+
torch.hub.download_url_to_file('https://images.pexels.com/photos/803975/pexels-photo-803975.jpeg', 'cabin.jpeg')
|
36 |
+
def sinc(x):
|
37 |
+
return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([]))
|
38 |
+
def lanczos(x, a):
|
39 |
+
cond = torch.logical_and(-a < x, x < a)
|
40 |
+
out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([]))
|
41 |
+
return out / out.sum()
|
42 |
+
def ramp(ratio, width):
|
43 |
+
n = math.ceil(width / ratio + 1)
|
44 |
+
out = torch.empty([n])
|
45 |
+
cur = 0
|
46 |
+
for i in range(out.shape[0]):
|
47 |
+
out[i] = cur
|
48 |
+
cur += ratio
|
49 |
+
return torch.cat([-out[1:].flip([0]), out])[1:-1]
|
50 |
+
def resample(input, size, align_corners=True):
|
51 |
+
n, c, h, w = input.shape
|
52 |
+
dh, dw = size
|
53 |
+
input = input.view([n * c, 1, h, w])
|
54 |
+
if dh < h:
|
55 |
+
kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype)
|
56 |
+
pad_h = (kernel_h.shape[0] - 1) // 2
|
57 |
+
input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect')
|
58 |
+
input = F.conv2d(input, kernel_h[None, None, :, None])
|
59 |
+
if dw < w:
|
60 |
+
kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype)
|
61 |
+
pad_w = (kernel_w.shape[0] - 1) // 2
|
62 |
+
input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect')
|
63 |
+
input = F.conv2d(input, kernel_w[None, None, None, :])
|
64 |
+
input = input.view([n, c, h, w])
|
65 |
+
return F.interpolate(input, size, mode='bicubic', align_corners=align_corners)
|
66 |
+
class ReplaceGrad(torch.autograd.Function):
|
67 |
+
@staticmethod
|
68 |
+
def forward(ctx, x_forward, x_backward):
|
69 |
+
ctx.shape = x_backward.shape
|
70 |
+
return x_forward
|
71 |
+
@staticmethod
|
72 |
+
def backward(ctx, grad_in):
|
73 |
+
return None, grad_in.sum_to_size(ctx.shape)
|
74 |
+
replace_grad = ReplaceGrad.apply
|
75 |
+
class ClampWithGrad(torch.autograd.Function):
|
76 |
+
@staticmethod
|
77 |
+
def forward(ctx, input, min, max):
|
78 |
+
ctx.min = min
|
79 |
+
ctx.max = max
|
80 |
+
ctx.save_for_backward(input)
|
81 |
+
return input.clamp(min, max)
|
82 |
+
@staticmethod
|
83 |
+
def backward(ctx, grad_in):
|
84 |
+
input, = ctx.saved_tensors
|
85 |
+
return grad_in * (grad_in * (input - input.clamp(ctx.min, ctx.max)) >= 0), None, None
|
86 |
+
clamp_with_grad = ClampWithGrad.apply
|
87 |
+
def vector_quantize(x, codebook):
|
88 |
+
d = x.pow(2).sum(dim=-1, keepdim=True) + codebook.pow(2).sum(dim=1) - 2 * x @ codebook.T
|
89 |
+
indices = d.argmin(-1)
|
90 |
+
x_q = F.one_hot(indices, codebook.shape[0]).to(d.dtype) @ codebook
|
91 |
+
return replace_grad(x_q, x)
|
92 |
+
class Prompt(nn.Module):
|
93 |
+
def __init__(self, embed, weight=1., stop=float('-inf')):
|
94 |
+
super().__init__()
|
95 |
+
self.register_buffer('embed', embed)
|
96 |
+
self.register_buffer('weight', torch.as_tensor(weight))
|
97 |
+
self.register_buffer('stop', torch.as_tensor(stop))
|
98 |
+
def forward(self, input):
|
99 |
+
input_normed = F.normalize(input.unsqueeze(1), dim=2)
|
100 |
+
embed_normed = F.normalize(self.embed.unsqueeze(0), dim=2)
|
101 |
+
dists = input_normed.sub(embed_normed).norm(dim=2).div(2).arcsin().pow(2).mul(2)
|
102 |
+
dists = dists * self.weight.sign()
|
103 |
+
return self.weight.abs() * replace_grad(dists, torch.maximum(dists, self.stop)).mean()
|
104 |
+
def parse_prompt(prompt):
|
105 |
+
vals = prompt.rsplit(':', 2)
|
106 |
+
vals = vals + ['', '1', '-inf'][len(vals):]
|
107 |
+
return vals[0], float(vals[1]), float(vals[2])
|
108 |
+
class MakeCutouts(nn.Module):
|
109 |
+
def __init__(self, cut_size, cutn, cut_pow=1.):
|
110 |
+
super().__init__()
|
111 |
+
self.cut_size = cut_size
|
112 |
+
self.cutn = cutn
|
113 |
+
self.cut_pow = cut_pow
|
114 |
+
self.augs = nn.Sequential(
|
115 |
+
# K.RandomHorizontalFlip(p=0.5),
|
116 |
+
# K.RandomVerticalFlip(p=0.5),
|
117 |
+
# K.RandomSolarize(0.01, 0.01, p=0.7),
|
118 |
+
# K.RandomSharpness(0.3,p=0.4),
|
119 |
+
# K.RandomResizedCrop(size=(self.cut_size,self.cut_size), scale=(0.1,1), ratio=(0.75,1.333), cropping_mode='resample', p=0.5),
|
120 |
+
# K.RandomCrop(size=(self.cut_size,self.cut_size), p=0.5),
|
121 |
+
K.RandomAffine(degrees=15, translate=0.1, p=0.7, padding_mode='border'),
|
122 |
+
K.RandomPerspective(0.7,p=0.7),
|
123 |
+
K.ColorJitter(hue=0.1, saturation=0.1, p=0.7),
|
124 |
+
K.RandomErasing((.1, .4), (.3, 1/.3), same_on_batch=True, p=0.7),
|
125 |
+
|
126 |
+
)
|
127 |
+
self.noise_fac = 0.1
|
128 |
+
self.av_pool = nn.AdaptiveAvgPool2d((self.cut_size, self.cut_size))
|
129 |
+
self.max_pool = nn.AdaptiveMaxPool2d((self.cut_size, self.cut_size))
|
130 |
+
def forward(self, input):
|
131 |
+
sideY, sideX = input.shape[2:4]
|
132 |
+
max_size = min(sideX, sideY)
|
133 |
+
min_size = min(sideX, sideY, self.cut_size)
|
134 |
+
cutouts = []
|
135 |
+
|
136 |
+
for _ in range(self.cutn):
|
137 |
+
# size = int(torch.rand([])**self.cut_pow * (max_size - min_size) + min_size)
|
138 |
+
# offsetx = torch.randint(0, sideX - size + 1, ())
|
139 |
+
# offsety = torch.randint(0, sideY - size + 1, ())
|
140 |
+
# cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size]
|
141 |
+
# cutouts.append(resample(cutout, (self.cut_size, self.cut_size)))
|
142 |
+
# cutout = transforms.Resize(size=(self.cut_size, self.cut_size))(input)
|
143 |
+
|
144 |
+
cutout = (self.av_pool(input) + self.max_pool(input))/2
|
145 |
+
cutouts.append(cutout)
|
146 |
+
batch = self.augs(torch.cat(cutouts, dim=0))
|
147 |
+
if self.noise_fac:
|
148 |
+
facs = batch.new_empty([self.cutn, 1, 1, 1]).uniform_(0, self.noise_fac)
|
149 |
+
batch = batch + facs * torch.randn_like(batch)
|
150 |
+
return batch
|
151 |
+
def load_vqgan_model(config_path, checkpoint_path):
|
152 |
+
config = OmegaConf.load(config_path)
|
153 |
+
if config.model.target == 'taming.models.vqgan.VQModel':
|
154 |
+
model = vqgan.VQModel(**config.model.params)
|
155 |
+
model.eval().requires_grad_(False)
|
156 |
+
model.init_from_ckpt(checkpoint_path)
|
157 |
+
elif config.model.target == 'taming.models.vqgan.GumbelVQ':
|
158 |
+
model = vqgan.GumbelVQ(**config.model.params)
|
159 |
+
model.eval().requires_grad_(False)
|
160 |
+
model.init_from_ckpt(checkpoint_path)
|
161 |
+
elif config.model.target == 'taming.models.cond_transformer.Net2NetTransformer':
|
162 |
+
parent_model = cond_transformer.Net2NetTransformer(**config.model.params)
|
163 |
+
parent_model.eval().requires_grad_(False)
|
164 |
+
parent_model.init_from_ckpt(checkpoint_path)
|
165 |
+
model = parent_model.first_stage_model
|
166 |
+
else:
|
167 |
+
raise ValueError(f'unknown model type: {config.model.target}')
|
168 |
+
del model.loss
|
169 |
+
return model
|
170 |
+
def resize_image(image, out_size):
|
171 |
+
ratio = image.size[0] / image.size[1]
|
172 |
+
area = min(image.size[0] * image.size[1], out_size[0] * out_size[1])
|
173 |
+
size = round((area * ratio)**0.5), round((area / ratio)**0.5)
|
174 |
+
return image.resize(size, Image.LANCZOS)
|
175 |
+
model_name = "vqgan_imagenet_f16_16384"
|
176 |
+
images_interval = 50
|
177 |
+
width = 280
|
178 |
+
height = 280
|
179 |
+
init_image = ""
|
180 |
+
seed = 42
|
181 |
+
args = argparse.Namespace(
|
182 |
+
noise_prompt_seeds=[],
|
183 |
+
noise_prompt_weights=[],
|
184 |
+
size=[width, height],
|
185 |
+
init_image=init_image,
|
186 |
+
init_weight=0.,
|
187 |
+
clip_model='ViT-B/32',
|
188 |
+
vqgan_config=f'{model_name}.yaml',
|
189 |
+
vqgan_checkpoint=f'{model_name}.ckpt',
|
190 |
+
step_size=0.15,
|
191 |
+
cutn=4,
|
192 |
+
cut_pow=1.,
|
193 |
+
display_freq=images_interval,
|
194 |
+
seed=seed,
|
195 |
+
)
|
196 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
197 |
+
print('Using device:', device)
|
198 |
+
model = load_vqgan_model(args.vqgan_config, args.vqgan_checkpoint).to(device)
|
199 |
+
perceptor = clip.load(args.clip_model, jit=False)[0].eval().requires_grad_(False).to(device)
|
200 |
+
def inference(text, seed, step_size, max_iterations, width, height, init_image, init_weight, target_images, cutn, cut_pow):
|
201 |
+
torch.cuda.empty_cache()
|
202 |
+
torch.cuda.memory_summary(device=None, abbreviated=False)
|
203 |
+
all_frames = []
|
204 |
+
size=[width, height]
|
205 |
+
texts = text
|
206 |
+
init_weight=init_weight
|
207 |
+
if init_image:
|
208 |
+
init_image = init_image.name
|
209 |
+
else:
|
210 |
+
init_image = ""
|
211 |
+
if target_images:
|
212 |
+
target_images = target_images.name
|
213 |
+
else:
|
214 |
+
target_images = ""
|
215 |
+
max_iterations = max_iterations
|
216 |
+
model_names={"vqgan_imagenet_f16_16384": 'ImageNet 16384',"vqgan_imagenet_f16_1024":"ImageNet 1024", 'vqgan_openimages_f16_8192':'OpenImages 8912',
|
217 |
+
"wikiart_1024":"WikiArt 1024", "wikiart_16384":"WikiArt 16384", "coco":"COCO-Stuff", "faceshq":"FacesHQ", "sflckr":"S-FLCKR"}
|
218 |
+
name_model = model_names[model_name]
|
219 |
+
if target_images == "None" or not target_images:
|
220 |
+
target_images = []
|
221 |
+
else:
|
222 |
+
target_images = target_images.split("|")
|
223 |
+
target_images = [image.strip() for image in target_images]
|
224 |
+
texts = [phrase.strip() for phrase in texts.split("|")]
|
225 |
+
if texts == ['']:
|
226 |
+
texts = []
|
227 |
+
from urllib.request import urlopen
|
228 |
+
if texts:
|
229 |
+
print('Using texts:', texts)
|
230 |
+
if target_images:
|
231 |
+
print('Using image prompts:', target_images)
|
232 |
+
if seed is None or seed == -1:
|
233 |
+
seed = torch.seed()
|
234 |
+
else:
|
235 |
+
seed = seed
|
236 |
+
torch.manual_seed(seed)
|
237 |
+
print('Using seed:', seed)
|
238 |
+
# clock=deepcopy(perceptor.visual.positional_embedding.data)
|
239 |
+
# perceptor.visual.positional_embedding.data = clock/clock.max()
|
240 |
+
# perceptor.visual.positional_embedding.data=clamp_with_grad(clock,0,1)
|
241 |
+
cut_size = perceptor.visual.input_resolution
|
242 |
+
f = 2**(model.decoder.num_resolutions - 1)
|
243 |
+
make_cutouts = MakeCutouts(cut_size, cutn, cut_pow=cut_pow)
|
244 |
+
toksX, toksY = size[0] // f, size[1] // f
|
245 |
+
sideX, sideY = toksX * f, toksY * f
|
246 |
+
if args.vqgan_checkpoint == 'vqgan_openimages_f16_8192.ckpt':
|
247 |
+
e_dim = 256
|
248 |
+
n_toks = model.quantize.n_embed
|
249 |
+
z_min = model.quantize.embed.weight.min(dim=0).values[None, :, None, None]
|
250 |
+
z_max = model.quantize.embed.weight.max(dim=0).values[None, :, None, None]
|
251 |
+
else:
|
252 |
+
e_dim = model.quantize.e_dim
|
253 |
+
n_toks = model.quantize.n_e
|
254 |
+
z_min = model.quantize.embedding.weight.min(dim=0).values[None, :, None, None]
|
255 |
+
z_max = model.quantize.embedding.weight.max(dim=0).values[None, :, None, None]
|
256 |
+
# z_min = model.quantize.embedding.weight.min(dim=0).values[None, :, None, None]
|
257 |
+
# z_max = model.quantize.embedding.weight.max(dim=0).values[None, :, None, None]
|
258 |
+
# normalize_imagenet = transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
259 |
+
# std=[0.229, 0.224, 0.225])
|
260 |
+
if init_image:
|
261 |
+
if 'http' in init_image:
|
262 |
+
img = Image.open(urlopen(init_image))
|
263 |
+
else:
|
264 |
+
img = Image.open(init_image)
|
265 |
+
pil_image = img.convert('RGB')
|
266 |
+
pil_image = pil_image.resize((sideX, sideY), Image.LANCZOS)
|
267 |
+
pil_tensor = TF.to_tensor(pil_image)
|
268 |
+
z, *_ = model.encode(pil_tensor.to(device).unsqueeze(0) * 2 - 1)
|
269 |
+
else:
|
270 |
+
one_hot = F.one_hot(torch.randint(n_toks, [toksY * toksX], device=device), n_toks).float()
|
271 |
+
# z = one_hot @ model.quantize.embedding.weight
|
272 |
+
if args.vqgan_checkpoint == 'vqgan_openimages_f16_8192.ckpt':
|
273 |
+
z = one_hot @ model.quantize.embed.weight
|
274 |
+
else:
|
275 |
+
z = one_hot @ model.quantize.embedding.weight
|
276 |
+
z = z.view([-1, toksY, toksX, e_dim]).permute(0, 3, 1, 2)
|
277 |
+
z = torch.rand_like(z)*2
|
278 |
+
z_orig = z.clone()
|
279 |
+
z.requires_grad_(True)
|
280 |
+
opt = optim.Adam([z], lr=step_size)
|
281 |
+
normalize = transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073],
|
282 |
+
std=[0.26862954, 0.26130258, 0.27577711])
|
283 |
+
pMs = []
|
284 |
+
for prompt in texts:
|
285 |
+
txt, weight, stop = parse_prompt(prompt)
|
286 |
+
embed = perceptor.encode_text(clip.tokenize(txt).to(device)).float()
|
287 |
+
pMs.append(Prompt(embed, weight, stop).to(device))
|
288 |
+
for prompt in target_images:
|
289 |
+
path, weight, stop = parse_prompt(prompt)
|
290 |
+
img = Image.open(path)
|
291 |
+
pil_image = img.convert('RGB')
|
292 |
+
img = resize_image(pil_image, (sideX, sideY))
|
293 |
+
batch = make_cutouts(TF.to_tensor(img).unsqueeze(0).to(device))
|
294 |
+
embed = perceptor.encode_image(normalize(batch)).float()
|
295 |
+
pMs.append(Prompt(embed, weight, stop).to(device))
|
296 |
+
for seed, weight in zip(args.noise_prompt_seeds, args.noise_prompt_weights):
|
297 |
+
gen = torch.Generator().manual_seed(seed)
|
298 |
+
embed = torch.empty([1, perceptor.visual.output_dim]).normal_(generator=gen)
|
299 |
+
pMs.append(Prompt(embed, weight).to(device))
|
300 |
+
def synth(z):
|
301 |
+
if args.vqgan_checkpoint == 'vqgan_openimages_f16_8192.ckpt':
|
302 |
+
z_q = vector_quantize(z.movedim(1, 3), model.quantize.embed.weight).movedim(3, 1)
|
303 |
+
else:
|
304 |
+
z_q = vector_quantize(z.movedim(1, 3), model.quantize.embedding.weight).movedim(3, 1)
|
305 |
+
return clamp_with_grad(model.decode(z_q).add(1).div(2), 0, 1)
|
306 |
+
@torch.no_grad()
|
307 |
+
def checkin(i, losses):
|
308 |
+
losses_str = ', '.join(f'{loss.item():g}' for loss in losses)
|
309 |
+
tqdm.write(f'i: {i}, loss: {sum(losses).item():g}, losses: {losses_str}')
|
310 |
+
out = synth(z)
|
311 |
+
# TF.to_pil_image(out[0].cpu()).save('progress.png')
|
312 |
+
# display.display(display.Image('progress.png'))
|
313 |
+
res = nvidia_smi.nvmlDeviceGetUtilizationRates(handle)
|
314 |
+
print(f'gpu: {res.gpu}%, gpu-mem: {res.memory}%')
|
315 |
+
def ascend_txt():
|
316 |
+
# global i
|
317 |
+
out = synth(z)
|
318 |
+
iii = perceptor.encode_image(normalize(make_cutouts(out))).float()
|
319 |
+
|
320 |
+
result = []
|
321 |
+
if init_weight:
|
322 |
+
result.append(F.mse_loss(z, z_orig) * init_weight / 2)
|
323 |
+
#result.append(F.mse_loss(z, torch.zeros_like(z_orig)) * ((1/torch.tensor(i*2 + 1))*init_weight) / 2)
|
324 |
+
for prompt in pMs:
|
325 |
+
result.append(prompt(iii))
|
326 |
+
img = np.array(out.mul(255).clamp(0, 255)[0].cpu().detach().numpy().astype(np.uint8))[:,:,:]
|
327 |
+
img = np.transpose(img, (1, 2, 0))
|
328 |
+
# imageio.imwrite('./steps/' + str(i) + '.png', np.array(img))
|
329 |
+
img = Image.fromarray(img).convert('RGB')
|
330 |
+
all_frames.append(img)
|
331 |
+
return result, np.array(img)
|
332 |
+
def train(i):
|
333 |
+
opt.zero_grad()
|
334 |
+
lossAll, image = ascend_txt()
|
335 |
+
if i % args.display_freq == 0:
|
336 |
+
checkin(i, lossAll)
|
337 |
+
|
338 |
+
loss = sum(lossAll)
|
339 |
+
loss.backward()
|
340 |
+
opt.step()
|
341 |
+
with torch.no_grad():
|
342 |
+
z.copy_(z.maximum(z_min).minimum(z_max))
|
343 |
+
return image
|
344 |
+
i = 0
|
345 |
+
try:
|
346 |
+
with tqdm() as pbar:
|
347 |
+
while True:
|
348 |
+
image = train(i)
|
349 |
+
if i == max_iterations:
|
350 |
+
break
|
351 |
+
i += 1
|
352 |
+
pbar.update()
|
353 |
+
except KeyboardInterrupt:
|
354 |
+
pass
|
355 |
+
writer = imageio.get_writer('test.mp4', fps=20)
|
356 |
+
for im in all_frames:
|
357 |
+
writer.append_data(np.array(im))
|
358 |
+
writer.close()
|
359 |
+
# all_frames[0].save('out.gif',
|
360 |
+
# save_all=True, append_images=all_frames[1:], optimize=False, duration=80, loop=0)
|
361 |
+
return image, 'test.mp4'
|
362 |
+
|
363 |
+
def load_image( infilename ) :
|
364 |
+
img = Image.open( infilename )
|
365 |
+
img.load()
|
366 |
+
data = np.asarray( img, dtype="int32" )
|
367 |
+
return data
|
368 |
+
title = "VQGAN + CLIP"
|
369 |
+
description = "Gradio demo for VQGAN + CLIP. To use it, simply add your text, or click one of the examples to load them. Read more at the links below."
|
370 |
+
article = "<p style='text-align: center'>Originally made by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). The original BigGAN+CLIP method was by https://twitter.com/advadnoun. Added some explanations and modifications by Eleiber#8347, pooling trick by Crimeacs#8222 (https://twitter.com/EarthML1) and the GUI was made with the help of Abulafia#3734. | <a href='https://colab.research.google.com/drive/1ZAus_gn2RhTZWzOWUpPERNC0Q8OhZRTZ'>Colab</a> | <a href='https://github.com/CompVis/taming-transformers'>Taming Transformers Github Repo</a> | <a href='https://github.com/openai/CLIP'>CLIP Github Repo</a> | Special thanks to BoneAmputee (https://twitter.com/BoneAmputee) for suggestions and advice</p>"
|
371 |
+
gr.Interface(
|
372 |
+
inference,
|
373 |
+
[gr.inputs.Textbox(label="Text Input"),
|
374 |
+
gr.inputs.Number(default=42, label="seed"),
|
375 |
+
gr.inputs.Slider(minimum=0.1, maximum=0.9, default=0.6, label='step size'),
|
376 |
+
gr.inputs.Slider(minimum=1, maximum=500, default=100, label='max iterations', step=1),
|
377 |
+
gr.inputs.Slider(minimum=200, maximum=600, default=256, label='width', step=1),
|
378 |
+
gr.inputs.Slider(minimum=200, maximum=600, default=256, label='height', step=1),
|
379 |
+
gr.inputs.Image(type="file", label="Initial Image (Optional)", optional=True),
|
380 |
+
gr.inputs.Slider(minimum=0.0, maximum=15.0, default=0.0, label='Initial Weight', step=1.0),
|
381 |
+
gr.inputs.Image(type="file", label="Target Image (Optional)", optional=True),
|
382 |
+
gr.inputs.Slider(minimum=1, maximum=40, default=1, label='cutn', step=1),
|
383 |
+
gr.inputs.Slider(minimum=1.0, maximum=40.0, default=1.0, label='cut_pow', step=1.0)
|
384 |
+
],
|
385 |
+
[gr.outputs.Image(type="numpy", label="Output Image"),gr.outputs.Video(label="Output Video")],
|
386 |
+
title=title,
|
387 |
+
description=description,
|
388 |
+
article=article,
|
389 |
+
examples=[
|
390 |
+
['a garden by james gurney',42,0.6, 100, 256, 256, 'garden.jpeg', 0.0, 'garden.jpeg',1,1.0],
|
391 |
+
['coral reef city artstationHQ',1000,0.6, 110, 200, 200, 'coralreef.jpeg', 0.0, 'coralreef.jpeg',1,1.0],
|
392 |
+
['a cabin in the mountains unreal engine',98,0.6, 120, 280, 280, 'cabin.jpeg', 0.0, 'cabin.jpeg',1,1.0]
|
393 |
+
],
|
394 |
+
enable_queue=True
|
395 |
+
).launch(debug=True)
|