Update app.py
Browse files
app.py
CHANGED
@@ -10,7 +10,7 @@ from transformers import (
|
|
10 |
CLIPTextModel,
|
11 |
CLIPTextModelWithProjection,
|
12 |
)
|
13 |
-
from diffusers import DDPMScheduler,AutoencoderKL
|
14 |
from typing import List
|
15 |
|
16 |
import torch
|
@@ -22,7 +22,7 @@ from torchvision import transforms
|
|
22 |
import apply_net
|
23 |
from preprocess.humanparsing.run_parsing import Parsing
|
24 |
from preprocess.openpose.run_openpose import OpenPose
|
25 |
-
from detectron2.data.detection_utils import convert_PIL_to_numpy,_apply_exif_orientation
|
26 |
from torchvision.transforms.functional import to_pil_image
|
27 |
|
28 |
|
@@ -33,9 +33,9 @@ def pil_to_binary_mask(pil_image, threshold=0):
|
|
33 |
mask = np.zeros(binary_mask.shape, dtype=np.uint8)
|
34 |
for i in range(binary_mask.shape[0]):
|
35 |
for j in range(binary_mask.shape[1]):
|
36 |
-
if binary_mask[i,j]
|
37 |
-
mask[i,j] = 1
|
38 |
-
mask = (mask*255).astype(np.uint8)
|
39 |
output_mask = Image.fromarray(mask)
|
40 |
return output_mask
|
41 |
|
@@ -77,13 +77,13 @@ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
|
|
77 |
base_path,
|
78 |
subfolder="image_encoder",
|
79 |
torch_dtype=torch.float16,
|
80 |
-
|
81 |
-
vae = AutoencoderKL.from_pretrained(
|
82 |
-
|
83 |
-
|
|
|
84 |
)
|
85 |
|
86 |
-
# "stabilityai/stable-diffusion-xl-base-1.0",
|
87 |
UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(
|
88 |
base_path,
|
89 |
subfolder="unet_encoder",
|
@@ -100,38 +100,41 @@ unet.requires_grad_(False)
|
|
100 |
text_encoder_one.requires_grad_(False)
|
101 |
text_encoder_two.requires_grad_(False)
|
102 |
tensor_transfrom = transforms.Compose(
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
|
109 |
pipe = TryonPipeline.from_pretrained(
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
)
|
122 |
pipe.unet_encoder = UNet_Encoder
|
123 |
|
124 |
-
|
125 |
-
|
|
|
|
|
|
|
126 |
device = "cuda"
|
127 |
-
|
128 |
openpose_model.preprocessor.body_estimation.model.to(device)
|
129 |
pipe.to(device)
|
130 |
pipe.unet_encoder.to(device)
|
131 |
|
132 |
-
garm_img= garm_img.convert("RGB").resize((768,1024))
|
133 |
-
human_img_orig = dict["background"].convert("RGB")
|
134 |
-
|
135 |
if is_checked_crop:
|
136 |
width, height = human_img_orig.size
|
137 |
target_width = int(min(width, height * (3 / 4)))
|
@@ -142,172 +145,194 @@ def start_tryon(dict,garm_img,garment_des,is_checked,is_checked_crop,denoise_ste
|
|
142 |
bottom = (height + target_height) / 2
|
143 |
cropped_img = human_img_orig.crop((left, top, right, bottom))
|
144 |
crop_size = cropped_img.size
|
145 |
-
human_img = cropped_img.resize((768,1024))
|
146 |
else:
|
147 |
-
human_img = human_img_orig.resize((768,1024))
|
148 |
-
|
149 |
|
150 |
if is_checked:
|
151 |
-
keypoints = openpose_model(human_img.resize((384,512)))
|
152 |
-
model_parse, _ = parsing_model(human_img.resize((384,512)))
|
153 |
mask, mask_gray = get_mask_location('hd', "upper_body", model_parse, keypoints)
|
154 |
-
mask = mask.resize((768,1024))
|
155 |
else:
|
156 |
mask = pil_to_binary_mask(dict['layers'][0].convert("RGB").resize((768, 1024)))
|
157 |
-
|
158 |
-
|
159 |
-
mask_gray = (1-transforms.ToTensor()(mask)) * tensor_transfrom(human_img)
|
160 |
-
mask_gray = to_pil_image((mask_gray+1.0)/2.0)
|
161 |
-
|
162 |
|
163 |
-
human_img_arg = _apply_exif_orientation(human_img.resize((384,512)))
|
164 |
human_img_arg = convert_PIL_to_numpy(human_img_arg, format="BGR")
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
with torch.no_grad():
|
175 |
-
# Extract the images
|
176 |
with torch.cuda.amp.autocast():
|
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 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
|
|
|
|
|
|
|
|
|
|
235 |
|
236 |
if is_checked_crop:
|
237 |
-
|
238 |
-
|
239 |
-
|
|
|
|
|
|
|
240 |
else:
|
241 |
-
return images
|
242 |
-
|
243 |
|
244 |
-
garm_list = os.listdir(os.path.join(example_path,"cloth"))
|
245 |
-
garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list]
|
246 |
|
247 |
-
human_list = os.listdir(os.path.join(example_path,"human"))
|
248 |
-
human_list_path = [os.path.join(example_path,"human",human) for human in human_list]
|
249 |
|
250 |
human_ex_list = []
|
251 |
for ex_human in human_list_path:
|
252 |
-
ex_dict= {}
|
253 |
ex_dict['background'] = ex_human
|
254 |
ex_dict['layers'] = None
|
255 |
ex_dict['composite'] = None
|
256 |
human_ex_list.append(ex_dict)
|
257 |
|
258 |
-
##default human
|
259 |
-
|
260 |
-
|
261 |
image_blocks = gr.Blocks().queue()
|
262 |
with image_blocks as demo:
|
263 |
gr.Markdown("## IDM-VTON ๐๐๐")
|
264 |
-
gr.Markdown(
|
|
|
|
|
265 |
with gr.Row():
|
266 |
with gr.Column():
|
267 |
-
imgs = gr.ImageEditor(
|
|
|
|
|
|
|
|
|
|
|
268 |
with gr.Row():
|
269 |
-
is_checked = gr.Checkbox(
|
|
|
|
|
270 |
with gr.Row():
|
271 |
-
is_checked_crop = gr.Checkbox(label="Yes", info="Use auto-crop & resizing",value=False)
|
272 |
|
273 |
-
example = gr.Examples(
|
274 |
-
inputs=imgs,
|
275 |
-
examples_per_page=10,
|
276 |
-
examples=human_ex_list
|
277 |
-
)
|
278 |
|
279 |
with gr.Column():
|
280 |
garm_img = gr.Image(label="Garment", sources='upload', type="pil")
|
281 |
with gr.Row(elem_id="prompt-container"):
|
282 |
with gr.Row():
|
283 |
-
prompt = gr.Textbox(
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
|
|
288 |
with gr.Column():
|
289 |
-
|
290 |
-
masked_img = gr.Image(label="Masked image output", elem_id="masked-img",show_share_button=False)
|
291 |
with gr.Column():
|
292 |
-
|
293 |
-
image_out = gr.Image(label="Output", elem_id="output-img",show_share_button=False)
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
|
298 |
with gr.Column():
|
299 |
try_button = gr.Button(value="Try-on")
|
300 |
with gr.Accordion(label="Advanced Settings", open=False):
|
301 |
with gr.Row():
|
302 |
-
denoise_steps = gr.Number(
|
|
|
|
|
303 |
seed = gr.Number(label="Seed", minimum=-1, maximum=2147483647, step=1, value=42)
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
311 |
|
312 |
image_blocks.launch()
|
313 |
-
|
|
|
10 |
CLIPTextModel,
|
11 |
CLIPTextModelWithProjection,
|
12 |
)
|
13 |
+
from diffusers import DDPMScheduler, AutoencoderKL
|
14 |
from typing import List
|
15 |
|
16 |
import torch
|
|
|
22 |
import apply_net
|
23 |
from preprocess.humanparsing.run_parsing import Parsing
|
24 |
from preprocess.openpose.run_openpose import OpenPose
|
25 |
+
from detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientation
|
26 |
from torchvision.transforms.functional import to_pil_image
|
27 |
|
28 |
|
|
|
33 |
mask = np.zeros(binary_mask.shape, dtype=np.uint8)
|
34 |
for i in range(binary_mask.shape[0]):
|
35 |
for j in range(binary_mask.shape[1]):
|
36 |
+
if binary_mask[i, j]:
|
37 |
+
mask[i, j] = 1
|
38 |
+
mask = (mask * 255).astype(np.uint8)
|
39 |
output_mask = Image.fromarray(mask)
|
40 |
return output_mask
|
41 |
|
|
|
77 |
base_path,
|
78 |
subfolder="image_encoder",
|
79 |
torch_dtype=torch.float16,
|
80 |
+
)
|
81 |
+
vae = AutoencoderKL.from_pretrained(
|
82 |
+
base_path,
|
83 |
+
subfolder="vae",
|
84 |
+
torch_dtype=torch.float16,
|
85 |
)
|
86 |
|
|
|
87 |
UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(
|
88 |
base_path,
|
89 |
subfolder="unet_encoder",
|
|
|
100 |
text_encoder_one.requires_grad_(False)
|
101 |
text_encoder_two.requires_grad_(False)
|
102 |
tensor_transfrom = transforms.Compose(
|
103 |
+
[
|
104 |
+
transforms.ToTensor(),
|
105 |
+
transforms.Normalize([0.5], [0.5]),
|
106 |
+
]
|
107 |
+
)
|
108 |
|
109 |
pipe = TryonPipeline.from_pretrained(
|
110 |
+
base_path,
|
111 |
+
unet=unet,
|
112 |
+
vae=vae,
|
113 |
+
feature_extractor=CLIPImageProcessor(),
|
114 |
+
text_encoder=text_encoder_one,
|
115 |
+
text_encoder_2=text_encoder_two,
|
116 |
+
tokenizer=tokenizer_one,
|
117 |
+
tokenizer_2=tokenizer_two,
|
118 |
+
scheduler=noise_scheduler,
|
119 |
+
image_encoder=image_encoder,
|
120 |
+
torch_dtype=torch.float16,
|
121 |
)
|
122 |
pipe.unet_encoder = UNet_Encoder
|
123 |
|
124 |
+
|
125 |
+
@spaces.GPU(duration=50) # ๅฎ่กๆ้ใ50็งใซ่จญๅฎ
|
126 |
+
def start_tryon(
|
127 |
+
dict, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed, num_images
|
128 |
+
):
|
129 |
device = "cuda"
|
130 |
+
|
131 |
openpose_model.preprocessor.body_estimation.model.to(device)
|
132 |
pipe.to(device)
|
133 |
pipe.unet_encoder.to(device)
|
134 |
|
135 |
+
garm_img = garm_img.convert("RGB").resize((768, 1024))
|
136 |
+
human_img_orig = dict["background"].convert("RGB")
|
137 |
+
|
138 |
if is_checked_crop:
|
139 |
width, height = human_img_orig.size
|
140 |
target_width = int(min(width, height * (3 / 4)))
|
|
|
145 |
bottom = (height + target_height) / 2
|
146 |
cropped_img = human_img_orig.crop((left, top, right, bottom))
|
147 |
crop_size = cropped_img.size
|
148 |
+
human_img = cropped_img.resize((768, 1024))
|
149 |
else:
|
150 |
+
human_img = human_img_orig.resize((768, 1024))
|
|
|
151 |
|
152 |
if is_checked:
|
153 |
+
keypoints = openpose_model(human_img.resize((384, 512)))
|
154 |
+
model_parse, _ = parsing_model(human_img.resize((384, 512)))
|
155 |
mask, mask_gray = get_mask_location('hd', "upper_body", model_parse, keypoints)
|
156 |
+
mask = mask.resize((768, 1024))
|
157 |
else:
|
158 |
mask = pil_to_binary_mask(dict['layers'][0].convert("RGB").resize((768, 1024)))
|
159 |
+
mask_gray = (1 - transforms.ToTensor()(mask)) * tensor_transfrom(human_img)
|
160 |
+
mask_gray = to_pil_image((mask_gray + 1.0) / 2.0)
|
|
|
|
|
|
|
161 |
|
162 |
+
human_img_arg = _apply_exif_orientation(human_img.resize((384, 512)))
|
163 |
human_img_arg = convert_PIL_to_numpy(human_img_arg, format="BGR")
|
164 |
+
|
165 |
+
args = apply_net.create_argument_parser().parse_args(
|
166 |
+
(
|
167 |
+
'show',
|
168 |
+
'./configs/densepose_rcnn_R_50_FPN_s1x.yaml',
|
169 |
+
'./ckpt/densepose/model_final_162be9.pkl',
|
170 |
+
'dp_segm',
|
171 |
+
'-v',
|
172 |
+
'--opts',
|
173 |
+
'MODEL.DEVICE',
|
174 |
+
'cuda',
|
175 |
+
)
|
176 |
+
)
|
177 |
+
pose_img = args.func(args, human_img_arg)
|
178 |
+
pose_img = pose_img[:, :, ::-1]
|
179 |
+
pose_img = Image.fromarray(pose_img).resize((768, 1024))
|
180 |
+
|
181 |
with torch.no_grad():
|
|
|
182 |
with torch.cuda.amp.autocast():
|
183 |
+
prompt = "model is wearing " + garment_des
|
184 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
185 |
+
(
|
186 |
+
prompt_embeds,
|
187 |
+
negative_prompt_embeds,
|
188 |
+
pooled_prompt_embeds,
|
189 |
+
negative_pooled_prompt_embeds,
|
190 |
+
) = pipe.encode_prompt(
|
191 |
+
prompt,
|
192 |
+
num_images_per_prompt=num_images,
|
193 |
+
do_classifier_free_guidance=True,
|
194 |
+
negative_prompt=negative_prompt,
|
195 |
+
)
|
196 |
+
|
197 |
+
prompt = "a photo of " + garment_des
|
198 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
199 |
+
if not isinstance(prompt, List):
|
200 |
+
prompt = [prompt] * num_images
|
201 |
+
if not isinstance(negative_prompt, List):
|
202 |
+
negative_prompt = [negative_prompt] * num_images
|
203 |
+
(
|
204 |
+
prompt_embeds_c,
|
205 |
+
_,
|
206 |
+
_,
|
207 |
+
_,
|
208 |
+
) = pipe.encode_prompt(
|
209 |
+
prompt,
|
210 |
+
num_images_per_prompt=num_images,
|
211 |
+
do_classifier_free_guidance=False,
|
212 |
+
negative_prompt=negative_prompt,
|
213 |
+
)
|
214 |
+
|
215 |
+
pose_img_tensor = tensor_transfrom(pose_img).unsqueeze(0).to(device, torch.float16)
|
216 |
+
garm_tensor = tensor_transfrom(garm_img).unsqueeze(0).to(device, torch.float16)
|
217 |
+
pose_img_tensor = pose_img_tensor.repeat(num_images, 1, 1, 1)
|
218 |
+
garm_tensor = garm_tensor.repeat(num_images, 1, 1, 1)
|
219 |
+
human_imgs = [human_img] * num_images
|
220 |
+
masks = [mask] * num_images
|
221 |
+
ip_adapter_images = [garm_img.resize((768, 1024))] * num_images
|
222 |
+
|
223 |
+
if seed is not None and seed != -1:
|
224 |
+
generator = [torch.Generator(device).manual_seed(seed + i) for i in range(num_images)]
|
225 |
+
else:
|
226 |
+
generator = None
|
227 |
+
|
228 |
+
images = pipe(
|
229 |
+
prompt_embeds=prompt_embeds.to(device, torch.float16),
|
230 |
+
negative_prompt_embeds=negative_prompt_embeds.to(device, torch.float16),
|
231 |
+
pooled_prompt_embeds=pooled_prompt_embeds.to(device, torch.float16),
|
232 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds.to(device, torch.float16),
|
233 |
+
num_inference_steps=denoise_steps,
|
234 |
+
generator=generator,
|
235 |
+
strength=1.0,
|
236 |
+
pose_img=pose_img_tensor.to(device, torch.float16),
|
237 |
+
text_embeds_cloth=prompt_embeds_c.to(device, torch.float16),
|
238 |
+
cloth=garm_tensor.to(device, torch.float16),
|
239 |
+
mask_image=masks,
|
240 |
+
image=human_imgs,
|
241 |
+
height=1024,
|
242 |
+
width=768,
|
243 |
+
ip_adapter_image=ip_adapter_images,
|
244 |
+
guidance_scale=2.0,
|
245 |
+
)[0]
|
246 |
|
247 |
if is_checked_crop:
|
248 |
+
output_images = []
|
249 |
+
for img in images:
|
250 |
+
out_img = img.resize(crop_size)
|
251 |
+
human_img_orig.paste(out_img, (int(left), int(top)))
|
252 |
+
output_images.append(human_img_orig.copy())
|
253 |
+
return output_images, mask_gray
|
254 |
else:
|
255 |
+
return images, mask_gray
|
256 |
+
|
257 |
|
258 |
+
garm_list = os.listdir(os.path.join(example_path, "cloth"))
|
259 |
+
garm_list_path = [os.path.join(example_path, "cloth", garm) for garm in garm_list]
|
260 |
|
261 |
+
human_list = os.listdir(os.path.join(example_path, "human"))
|
262 |
+
human_list_path = [os.path.join(example_path, "human", human) for human in human_list]
|
263 |
|
264 |
human_ex_list = []
|
265 |
for ex_human in human_list_path:
|
266 |
+
ex_dict = {}
|
267 |
ex_dict['background'] = ex_human
|
268 |
ex_dict['layers'] = None
|
269 |
ex_dict['composite'] = None
|
270 |
human_ex_list.append(ex_dict)
|
271 |
|
|
|
|
|
|
|
272 |
image_blocks = gr.Blocks().queue()
|
273 |
with image_blocks as demo:
|
274 |
gr.Markdown("## IDM-VTON ๐๐๐")
|
275 |
+
gr.Markdown(
|
276 |
+
"Virtual Try-on with your image and garment image. Check out the [source codes](https://github.com/yisol/IDM-VTON) and the [model](https://huggingface.co/yisol/IDM-VTON)"
|
277 |
+
)
|
278 |
with gr.Row():
|
279 |
with gr.Column():
|
280 |
+
imgs = gr.ImageEditor(
|
281 |
+
sources='upload',
|
282 |
+
type="pil",
|
283 |
+
label='Human. Mask with pen or use auto-masking',
|
284 |
+
interactive=True,
|
285 |
+
)
|
286 |
with gr.Row():
|
287 |
+
is_checked = gr.Checkbox(
|
288 |
+
label="Yes", info="Use auto-generated mask (Takes 5 seconds)", value=True
|
289 |
+
)
|
290 |
with gr.Row():
|
291 |
+
is_checked_crop = gr.Checkbox(label="Yes", info="Use auto-crop & resizing", value=False)
|
292 |
|
293 |
+
example = gr.Examples(inputs=imgs, examples_per_page=10, examples=human_ex_list)
|
|
|
|
|
|
|
|
|
294 |
|
295 |
with gr.Column():
|
296 |
garm_img = gr.Image(label="Garment", sources='upload', type="pil")
|
297 |
with gr.Row(elem_id="prompt-container"):
|
298 |
with gr.Row():
|
299 |
+
prompt = gr.Textbox(
|
300 |
+
placeholder="Description of garment ex) Short Sleeve Round Neck T-shirts",
|
301 |
+
show_label=False,
|
302 |
+
elem_id="prompt",
|
303 |
+
)
|
304 |
+
example = gr.Examples(inputs=garm_img, examples_per_page=8, examples=garm_list_path)
|
305 |
with gr.Column():
|
306 |
+
masked_img = gr.Image(label="Masked image output", elem_id="masked-img", show_share_button=False)
|
|
|
307 |
with gr.Column():
|
308 |
+
image_out = gr.Gallery(label="Output", elem_id="output-img", show_share_button=False)
|
|
|
|
|
|
|
|
|
309 |
|
310 |
with gr.Column():
|
311 |
try_button = gr.Button(value="Try-on")
|
312 |
with gr.Accordion(label="Advanced Settings", open=False):
|
313 |
with gr.Row():
|
314 |
+
denoise_steps = gr.Number(
|
315 |
+
label="Denoising Steps", minimum=20, maximum=40, value=30, step=1
|
316 |
+
)
|
317 |
seed = gr.Number(label="Seed", minimum=-1, maximum=2147483647, step=1, value=42)
|
318 |
+
num_images = gr.Slider(
|
319 |
+
label="Number of Images", minimum=1, maximum=5, step=1, value=1
|
320 |
+
)
|
321 |
+
|
322 |
+
try_button.click(
|
323 |
+
fn=start_tryon,
|
324 |
+
inputs=[
|
325 |
+
imgs,
|
326 |
+
garm_img,
|
327 |
+
prompt,
|
328 |
+
is_checked,
|
329 |
+
is_checked_crop,
|
330 |
+
denoise_steps,
|
331 |
+
seed,
|
332 |
+
num_images,
|
333 |
+
],
|
334 |
+
outputs=[image_out, masked_img],
|
335 |
+
api_name='tryon',
|
336 |
+
)
|
337 |
|
338 |
image_blocks.launch()
|
|