Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,227 +1,228 @@
|
|
1 |
-
"""
|
2 |
-
Train a diffusion model on images.
|
3 |
-
"""
|
4 |
-
import gradio as gr
|
5 |
-
import argparse
|
6 |
-
from einops import rearrange
|
7 |
-
from glide_text2im import dist_util, logger
|
8 |
-
from torchvision.utils import make_grid
|
9 |
-
from glide_text2im.script_util import (
|
10 |
-
model_and_diffusion_defaults,
|
11 |
-
create_model_and_diffusion,
|
12 |
-
args_to_dict,
|
13 |
-
add_dict_to_argparser,
|
14 |
-
)
|
15 |
-
from glide_text2im.image_datasets_sketch import get_tensor
|
16 |
-
from glide_text2im.train_util import TrainLoop
|
17 |
-
from glide_text2im.glide_util import sample
|
18 |
-
import torch
|
19 |
-
import os
|
20 |
-
import torch as th
|
21 |
-
import torchvision.utils as tvu
|
22 |
-
import torch.distributed as dist
|
23 |
-
from PIL import Image
|
24 |
-
import cv2
|
25 |
-
import numpy as np
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
args.
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
args.
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
args.
|
49 |
-
args.
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
pil_image = image
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
im_dist = np.
|
96 |
-
im_dist =
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
grid =
|
166 |
-
grid =
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
defaults
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
gr.
|
217 |
-
gr.inputs.
|
218 |
-
gr.inputs.Slider(label="
|
219 |
-
gr.inputs.Slider(label="Number of
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
|
|
|
1 |
+
"""
|
2 |
+
Train a diffusion model on images.
|
3 |
+
"""
|
4 |
+
import gradio as gr
|
5 |
+
import argparse
|
6 |
+
from einops import rearrange
|
7 |
+
from glide_text2im import dist_util, logger
|
8 |
+
from torchvision.utils import make_grid
|
9 |
+
from glide_text2im.script_util import (
|
10 |
+
model_and_diffusion_defaults,
|
11 |
+
create_model_and_diffusion,
|
12 |
+
args_to_dict,
|
13 |
+
add_dict_to_argparser,
|
14 |
+
)
|
15 |
+
from glide_text2im.image_datasets_sketch import get_tensor
|
16 |
+
from glide_text2im.train_util import TrainLoop
|
17 |
+
from glide_text2im.glide_util import sample
|
18 |
+
import torch
|
19 |
+
import os
|
20 |
+
import torch as th
|
21 |
+
import torchvision.utils as tvu
|
22 |
+
import torch.distributed as dist
|
23 |
+
from PIL import Image
|
24 |
+
import cv2
|
25 |
+
import numpy as np
|
26 |
+
from huggingface_hub import hf_hub_download
|
27 |
+
|
28 |
+
def run(image, mode, sample_c=1.3, num_samples=3, sample_step=100):
|
29 |
+
parser, parser_up = create_argparser()
|
30 |
+
|
31 |
+
args = parser.parse_args()
|
32 |
+
args_up = parser_up.parse_args()
|
33 |
+
dist_util.setup_dist()
|
34 |
+
|
35 |
+
if mode == 'sketch':
|
36 |
+
args.mode = 'coco-edge'
|
37 |
+
args_up.mode = 'coco-edge'
|
38 |
+
args.model_path = hf_hub_download(repo_id="tfwang/PITI", filename="base_edge.pt")
|
39 |
+
args.sr_model_path = hf_hub_download(repo_id="tfwang/PITI", filename="upsample_edge.pt")
|
40 |
+
|
41 |
+
elif mode == 'mask':
|
42 |
+
args.mode = 'coco'
|
43 |
+
args_up.mode = 'coco'
|
44 |
+
args.model_path = hf_hub_download(repo_id="tfwang/PITI", filename="base_mask.pt")
|
45 |
+
args.sr_model_path = hf_hub_download(repo_id="tfwang/PITI", filename="upsample_mask.pt")
|
46 |
+
|
47 |
+
|
48 |
+
args.val_data_dir = image
|
49 |
+
args.sample_c = sample_c
|
50 |
+
args.num_samples = num_samples
|
51 |
+
|
52 |
+
|
53 |
+
options=args_to_dict(args, model_and_diffusion_defaults(0.).keys())
|
54 |
+
model, diffusion = create_model_and_diffusion(**options)
|
55 |
+
|
56 |
+
options_up=args_to_dict(args_up, model_and_diffusion_defaults(True).keys())
|
57 |
+
model_up, diffusion_up = create_model_and_diffusion(**options_up)
|
58 |
+
|
59 |
+
|
60 |
+
if args.model_path:
|
61 |
+
print('loading model')
|
62 |
+
model_ckpt = dist_util.load_state_dict(args.model_path, map_location="cpu")
|
63 |
+
|
64 |
+
model.load_state_dict(
|
65 |
+
model_ckpt , strict=True )
|
66 |
+
|
67 |
+
if args.sr_model_path:
|
68 |
+
print('loading sr model')
|
69 |
+
model_ckpt2 = dist_util.load_state_dict(args.sr_model_path, map_location="cpu")
|
70 |
+
|
71 |
+
model_up.load_state_dict(
|
72 |
+
model_ckpt2 , strict=True )
|
73 |
+
|
74 |
+
|
75 |
+
model.to(dist_util.dev())
|
76 |
+
model_up.to(dist_util.dev())
|
77 |
+
model.eval()
|
78 |
+
model_up.eval()
|
79 |
+
|
80 |
+
########### dataset
|
81 |
+
# logger.log("creating data loader...")
|
82 |
+
|
83 |
+
if args.mode == 'coco':
|
84 |
+
pil_image = image
|
85 |
+
label_pil = pil_image.convert("RGB").resize((256, 256), Image.NEAREST)
|
86 |
+
label_tensor = get_tensor()(label_pil)
|
87 |
+
|
88 |
+
data_dict = {"ref":label_tensor.unsqueeze(0).repeat(args.num_samples, 1, 1, 1)}
|
89 |
+
|
90 |
+
elif args.mode == 'coco-edge':
|
91 |
+
# pil_image = Image.open(image)
|
92 |
+
pil_image = image
|
93 |
+
label_pil = pil_image.convert("L").resize((256, 256), Image.NEAREST)
|
94 |
+
|
95 |
+
im_dist = cv2.distanceTransform(255-np.array(label_pil), cv2.DIST_L1, 3)
|
96 |
+
im_dist = np.clip((im_dist) , 0, 255).astype(np.uint8)
|
97 |
+
im_dist = Image.fromarray(im_dist).convert("RGB")
|
98 |
+
|
99 |
+
label_tensor = get_tensor()(im_dist)[:1]
|
100 |
+
|
101 |
+
data_dict = {"ref":label_tensor.unsqueeze(0).repeat(args.num_samples, 1, 1, 1)}
|
102 |
+
|
103 |
+
|
104 |
+
|
105 |
+
print("sampling...")
|
106 |
+
|
107 |
+
|
108 |
+
sampled_imgs = []
|
109 |
+
grid_imgs = []
|
110 |
+
img_id = 0
|
111 |
+
while (True):
|
112 |
+
if img_id >= args.num_samples:
|
113 |
+
break
|
114 |
+
|
115 |
+
model_kwargs = data_dict
|
116 |
+
with th.no_grad():
|
117 |
+
samples_lr =sample(
|
118 |
+
glide_model= model,
|
119 |
+
glide_options= options,
|
120 |
+
side_x= 64,
|
121 |
+
side_y= 64,
|
122 |
+
prompt=model_kwargs,
|
123 |
+
batch_size= args.num_samples,
|
124 |
+
guidance_scale=args.sample_c,
|
125 |
+
device=dist_util.dev(),
|
126 |
+
prediction_respacing= str(sample_step),
|
127 |
+
upsample_enabled= False,
|
128 |
+
upsample_temp=0.997,
|
129 |
+
mode = args.mode,
|
130 |
+
)
|
131 |
+
|
132 |
+
samples_lr = samples_lr.clamp(-1, 1)
|
133 |
+
|
134 |
+
tmp = (127.5*(samples_lr + 1.0)).int()
|
135 |
+
model_kwargs['low_res'] = tmp/127.5 - 1.
|
136 |
+
|
137 |
+
samples_hr =sample(
|
138 |
+
glide_model= model_up,
|
139 |
+
glide_options= options_up,
|
140 |
+
side_x=256,
|
141 |
+
side_y=256,
|
142 |
+
prompt=model_kwargs,
|
143 |
+
batch_size=args.num_samples,
|
144 |
+
guidance_scale=1,
|
145 |
+
device=dist_util.dev(),
|
146 |
+
prediction_respacing= "fast27",
|
147 |
+
upsample_enabled=True,
|
148 |
+
upsample_temp=0.997,
|
149 |
+
mode = args.mode,
|
150 |
+
)
|
151 |
+
|
152 |
+
|
153 |
+
samples_hr = samples_hr
|
154 |
+
|
155 |
+
|
156 |
+
for hr in samples_hr:
|
157 |
+
|
158 |
+
hr = 255. * rearrange((hr.cpu().numpy()+1.0)*0.5, 'c h w -> h w c')
|
159 |
+
sample_img = Image.fromarray(hr.astype(np.uint8))
|
160 |
+
sampled_imgs.append(sample_img)
|
161 |
+
img_id += 1
|
162 |
+
|
163 |
+
grid_imgs.append(samples_hr)
|
164 |
+
|
165 |
+
grid = torch.stack(grid_imgs, 0)
|
166 |
+
grid = rearrange(grid, 'n b c h w -> (n b) c h w')
|
167 |
+
grid = make_grid(grid, nrow=2)
|
168 |
+
# to image
|
169 |
+
grid = 255. * rearrange((grid+1.0)*0.5, 'c h w -> h w c').cpu().numpy()
|
170 |
+
|
171 |
+
return Image.fromarray(grid.astype(np.uint8))
|
172 |
+
|
173 |
+
|
174 |
+
def create_argparser():
|
175 |
+
defaults = dict(
|
176 |
+
data_dir="",
|
177 |
+
val_data_dir="",
|
178 |
+
model_path="./base_edge.pt",
|
179 |
+
sr_model_path="./upsample_edge.pt",
|
180 |
+
encoder_path="",
|
181 |
+
schedule_sampler="uniform",
|
182 |
+
lr=1e-4,
|
183 |
+
weight_decay=0.0,
|
184 |
+
lr_anneal_steps=0,
|
185 |
+
batch_size=2,
|
186 |
+
microbatch=-1, # -1 disables microbatches
|
187 |
+
ema_rate="0.9999", # comma-separated list of EMA values
|
188 |
+
log_interval=100,
|
189 |
+
save_interval=20000,
|
190 |
+
resume_checkpoint="",
|
191 |
+
use_fp16=False,
|
192 |
+
fp16_scale_growth=1e-3,
|
193 |
+
sample_c=1.,
|
194 |
+
sample_respacing="100",
|
195 |
+
uncond_p=0.2,
|
196 |
+
num_samples=3,
|
197 |
+
finetune_decoder = False,
|
198 |
+
mode = '',
|
199 |
+
)
|
200 |
+
|
201 |
+
defaults_up = defaults
|
202 |
+
defaults.update(model_and_diffusion_defaults())
|
203 |
+
parser = argparse.ArgumentParser()
|
204 |
+
add_dict_to_argparser(parser, defaults)
|
205 |
+
|
206 |
+
defaults_up.update(model_and_diffusion_defaults(True))
|
207 |
+
parser_up = argparse.ArgumentParser()
|
208 |
+
add_dict_to_argparser(parser_up, defaults_up)
|
209 |
+
|
210 |
+
return parser, parser_up
|
211 |
+
|
212 |
+
image = gr.outputs.Image(type="pil", label="Sampled results")
|
213 |
+
css = ".output-image{height: 528px !important} .output-carousel .output-image{height:272px !important} a{text-decoration: underline}"
|
214 |
+
demo = gr.Interface(fn=run, inputs=[
|
215 |
+
gr.inputs.Image(type="pil", label="Input Sketch" ) ,
|
216 |
+
# gr.Image(image_mode="L", source="canvas", type="pil", shape=(256,256), invert_colors=False, tool="editor"),
|
217 |
+
gr.inputs.Radio(label="Input Mode - The type of your input", choices=["mask", "sketch"],default="sketch"),
|
218 |
+
gr.inputs.Slider(label="sample_c - The strength of classifier-free guidance",default=1.4, minimum=1.0, maximum=2.0),
|
219 |
+
gr.inputs.Slider(label="Number of samples - How many samples you wish to generate", default=4, step=1, minimum=1, maximum=16),
|
220 |
+
gr.inputs.Slider(label="Number of Steps - How many steps you want to use", default=100, step=10, minimum=50, maximum=1000),
|
221 |
+
],
|
222 |
+
outputs=[image],
|
223 |
+
css=css,
|
224 |
+
title="Generate images from sketches with PITI",
|
225 |
+
description="<div>By uploading a sketch map or a semantic map and pressing submit, you can generate images based on your input.</div>")
|
226 |
+
|
227 |
+
demo.launch(enable_queue=True)
|
228 |
+
|