Update app.py
Browse files
app.py
CHANGED
@@ -1,314 +1,2 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
from PIL import Image
|
3 |
-
from src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipeline
|
4 |
-
from src.unet_hacked_garmnet import UNet2DConditionModel as UNet2DConditionModel_ref
|
5 |
-
from src.unet_hacked_tryon import UNet2DConditionModel
|
6 |
-
from transformers import (
|
7 |
-
CLIPImageProcessor,
|
8 |
-
CLIPVisionModelWithProjection,
|
9 |
-
CLIPTextModel,
|
10 |
-
CLIPTextModelWithProjection,
|
11 |
-
)
|
12 |
-
from diffusers import DDPMScheduler,AutoencoderKL
|
13 |
-
from typing import List
|
14 |
-
|
15 |
-
import torch
|
16 |
import os
|
17 |
-
|
18 |
-
import spaces
|
19 |
-
import numpy as np
|
20 |
-
from utils_mask import get_mask_location
|
21 |
-
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 |
-
|
29 |
-
def pil_to_binary_mask(pil_image, threshold=0):
|
30 |
-
np_image = np.array(pil_image)
|
31 |
-
grayscale_image = Image.fromarray(np_image).convert("L")
|
32 |
-
binary_mask = np.array(grayscale_image) > threshold
|
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] == True :
|
37 |
-
mask[i,j] = 1
|
38 |
-
mask = (mask*255).astype(np.uint8)
|
39 |
-
output_mask = Image.fromarray(mask)
|
40 |
-
return output_mask
|
41 |
-
|
42 |
-
|
43 |
-
base_path = 'yisol/IDM-VTON'
|
44 |
-
example_path = os.path.join(os.path.dirname(__file__), 'example')
|
45 |
-
|
46 |
-
unet = UNet2DConditionModel.from_pretrained(
|
47 |
-
base_path,
|
48 |
-
subfolder="unet",
|
49 |
-
torch_dtype=torch.float16,
|
50 |
-
)
|
51 |
-
unet.requires_grad_(False)
|
52 |
-
tokenizer_one = AutoTokenizer.from_pretrained(
|
53 |
-
base_path,
|
54 |
-
subfolder="tokenizer",
|
55 |
-
revision=None,
|
56 |
-
use_fast=False,
|
57 |
-
)
|
58 |
-
tokenizer_two = AutoTokenizer.from_pretrained(
|
59 |
-
base_path,
|
60 |
-
subfolder="tokenizer_2",
|
61 |
-
revision=None,
|
62 |
-
use_fast=False,
|
63 |
-
)
|
64 |
-
noise_scheduler = DDPMScheduler.from_pretrained(base_path, subfolder="scheduler")
|
65 |
-
|
66 |
-
text_encoder_one = CLIPTextModel.from_pretrained(
|
67 |
-
base_path,
|
68 |
-
subfolder="text_encoder",
|
69 |
-
torch_dtype=torch.float16,
|
70 |
-
)
|
71 |
-
text_encoder_two = CLIPTextModelWithProjection.from_pretrained(
|
72 |
-
base_path,
|
73 |
-
subfolder="text_encoder_2",
|
74 |
-
torch_dtype=torch.float16,
|
75 |
-
)
|
76 |
-
image_encoder = CLIPVisionModelWithProjection.from_pretrained(
|
77 |
-
base_path,
|
78 |
-
subfolder="image_encoder",
|
79 |
-
torch_dtype=torch.float16,
|
80 |
-
)
|
81 |
-
vae = AutoencoderKL.from_pretrained(base_path,
|
82 |
-
subfolder="vae",
|
83 |
-
torch_dtype=torch.float16,
|
84 |
-
)
|
85 |
-
|
86 |
-
# "stabilityai/stable-diffusion-xl-base-1.0",
|
87 |
-
UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(
|
88 |
-
base_path,
|
89 |
-
subfolder="unet_encoder",
|
90 |
-
torch_dtype=torch.float16,
|
91 |
-
)
|
92 |
-
|
93 |
-
parsing_model = Parsing(0)
|
94 |
-
openpose_model = OpenPose(0)
|
95 |
-
|
96 |
-
UNet_Encoder.requires_grad_(False)
|
97 |
-
image_encoder.requires_grad_(False)
|
98 |
-
vae.requires_grad_(False)
|
99 |
-
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 |
-
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 |
-
@spaces.GPU
|
125 |
-
def start_tryon(dict,garm_img,garment_des,is_checked,is_checked_crop,denoise_steps,seed,area):
|
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 |
-
OUTPUT_WIDTH, OUTPUT_HEIGHT = dict.size
|
133 |
-
|
134 |
-
garm_img= garm_img.convert("RGB").resize((768,1024))
|
135 |
-
|
136 |
-
human_img_orig = dict.convert("RGB").resize((768,1024))
|
137 |
-
# human_img_orig = dict["background"].convert("RGB")
|
138 |
-
|
139 |
-
if is_checked_crop:
|
140 |
-
width, height = human_img_orig.size
|
141 |
-
target_width = int(min(width, height * (3 / 4)))
|
142 |
-
target_height = int(min(height, width * (4 / 3)))
|
143 |
-
left = (width - target_width) / 2
|
144 |
-
top = (height - target_height) / 2
|
145 |
-
right = (width + target_width) / 2
|
146 |
-
bottom = (height + target_height) / 2
|
147 |
-
cropped_img = human_img_orig.crop((left, top, right, bottom))
|
148 |
-
crop_size = cropped_img.size
|
149 |
-
human_img = cropped_img.resize((768,1024))
|
150 |
-
else:
|
151 |
-
human_img = human_img_orig.resize((768,1024))
|
152 |
-
|
153 |
-
|
154 |
-
if is_checked:
|
155 |
-
keypoints = openpose_model(human_img.resize((384,512)))
|
156 |
-
model_parse, _ = parsing_model(human_img.resize((384,512)))
|
157 |
-
mask, mask_gray = get_mask_location('hd', area, model_parse, keypoints)
|
158 |
-
mask = mask.resize((768,1024))
|
159 |
-
# else:
|
160 |
-
# mask = pil_to_binary_mask(dict['layers'][0].convert("RGB").resize((768, 1024)))
|
161 |
-
# mask = transforms.ToTensor()(mask)
|
162 |
-
# mask = mask.unsqueeze(0)
|
163 |
-
mask_gray = (1-transforms.ToTensor()(mask)) * tensor_transfrom(human_img)
|
164 |
-
mask_gray = to_pil_image((mask_gray+1.0)/2.0)
|
165 |
-
|
166 |
-
|
167 |
-
human_img_arg = _apply_exif_orientation(human_img.resize((384,512)))
|
168 |
-
human_img_arg = convert_PIL_to_numpy(human_img_arg, format="BGR")
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
args = apply_net.create_argument_parser().parse_args(('show', './configs/densepose_rcnn_R_50_FPN_s1x.yaml', './ckpt/densepose/model_final_162be9.pkl', 'dp_segm', '-v', '--opts', 'MODEL.DEVICE', 'cuda'))
|
173 |
-
# verbosity = getattr(args, "verbosity", None)
|
174 |
-
pose_img = args.func(args,human_img_arg)
|
175 |
-
pose_img = pose_img[:,:,::-1]
|
176 |
-
pose_img = Image.fromarray(pose_img).resize((768,1024))
|
177 |
-
|
178 |
-
with torch.no_grad():
|
179 |
-
# Extract the images
|
180 |
-
with torch.cuda.amp.autocast():
|
181 |
-
with torch.no_grad():
|
182 |
-
prompt = "model is wearing " + garment_des
|
183 |
-
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
184 |
-
with torch.inference_mode():
|
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=1,
|
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] * 1
|
201 |
-
if not isinstance(negative_prompt, List):
|
202 |
-
negative_prompt = [negative_prompt] * 1
|
203 |
-
with torch.inference_mode():
|
204 |
-
(
|
205 |
-
prompt_embeds_c,
|
206 |
-
_,
|
207 |
-
_,
|
208 |
-
_,
|
209 |
-
) = pipe.encode_prompt(
|
210 |
-
prompt,
|
211 |
-
num_images_per_prompt=1,
|
212 |
-
do_classifier_free_guidance=False,
|
213 |
-
negative_prompt=negative_prompt,
|
214 |
-
)
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
pose_img = tensor_transfrom(pose_img).unsqueeze(0).to(device,torch.float16)
|
219 |
-
garm_tensor = tensor_transfrom(garm_img).unsqueeze(0).to(device,torch.float16)
|
220 |
-
generator = torch.Generator(device).manual_seed(seed) if seed is not None else None
|
221 |
-
images = pipe(
|
222 |
-
prompt_embeds=prompt_embeds.to(device,torch.float16),
|
223 |
-
negative_prompt_embeds=negative_prompt_embeds.to(device,torch.float16),
|
224 |
-
pooled_prompt_embeds=pooled_prompt_embeds.to(device,torch.float16),
|
225 |
-
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds.to(device,torch.float16),
|
226 |
-
num_inference_steps=denoise_steps,
|
227 |
-
generator=generator,
|
228 |
-
strength = 1.0,
|
229 |
-
pose_img = pose_img.to(device,torch.float16),
|
230 |
-
text_embeds_cloth=prompt_embeds_c.to(device,torch.float16),
|
231 |
-
cloth = garm_tensor.to(device,torch.float16),
|
232 |
-
mask_image=mask,
|
233 |
-
image=human_img,
|
234 |
-
height=1024,
|
235 |
-
width=768,
|
236 |
-
ip_adapter_image = garm_img.resize((768,1024)),
|
237 |
-
guidance_scale=2.0,
|
238 |
-
)[0]
|
239 |
-
|
240 |
-
if is_checked_crop:
|
241 |
-
out_img = images[0].resize(crop_size)
|
242 |
-
human_img_orig.paste(out_img, (int(left), int(top)))
|
243 |
-
return human_img_orig.resize((OUTPUT_WIDTH, OUTPUT_HEIGHT))
|
244 |
-
else:
|
245 |
-
return images[0].resize((OUTPUT_WIDTH, OUTPUT_HEIGHT))
|
246 |
-
# return images[0], mask_gray
|
247 |
-
|
248 |
-
garm_list = os.listdir(os.path.join(example_path,"cloth"))
|
249 |
-
garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list]
|
250 |
-
|
251 |
-
# human_list = os.listdir(os.path.join(example_path,"human"))
|
252 |
-
# human_list_path = [os.path.join(example_path,"human",human) for human in human_list]
|
253 |
-
|
254 |
-
# human_ex_list = []
|
255 |
-
# for ex_human in human_list_path:
|
256 |
-
# ex_dict= {}
|
257 |
-
# ex_dict['background'] = ex_human
|
258 |
-
# ex_dict['layers'] = None
|
259 |
-
# ex_dict['composite'] = None
|
260 |
-
# human_ex_list.append(ex_dict)
|
261 |
-
|
262 |
-
##default human
|
263 |
-
|
264 |
-
|
265 |
-
image_blocks = gr.Blocks(css="style.css").queue()
|
266 |
-
with image_blocks as demo:
|
267 |
-
gr.Markdown("## MyFit-AI")
|
268 |
-
with gr.Row():
|
269 |
-
with gr.Column():
|
270 |
-
# imgs = gr.ImageEditor(sources='upload', type="pil", label='Human. Mask with pen or use auto-masking', interactive=True)
|
271 |
-
imgs = gr.Image(label='Human', sources='upload', type="pil")
|
272 |
-
garm_img = gr.Image(label="Garment", sources='upload', type="pil")
|
273 |
-
with gr.Row(elem_id="prompt-container"):
|
274 |
-
with gr.Row():
|
275 |
-
prompt = gr.Textbox(placeholder="Description of garment ex) Neck T-shirts", show_label=False, elem_id="prompt")
|
276 |
-
example = gr.Examples(
|
277 |
-
inputs=garm_img,
|
278 |
-
examples_per_page=8,
|
279 |
-
examples=garm_list_path)
|
280 |
-
|
281 |
-
try_button = gr.Button(value="Try-on", variant="primary")
|
282 |
-
with gr.Accordion(label="Advanced Settings", open=False):
|
283 |
-
with gr.Row():
|
284 |
-
denoise_steps = gr.Number(label="Denoising Steps", minimum=20, maximum=40, value=30, step=1)
|
285 |
-
seed = gr.Number(label="Seed", minimum=-1, maximum=2147483647, step=1, value=42)
|
286 |
-
with gr.Row():
|
287 |
-
area = gr.Dropdown(["upper_body","lower_body"], value="upper_body", label="garment zone")
|
288 |
-
with gr.Row():
|
289 |
-
is_checked = gr.Checkbox(label="Yes", info="Use auto-generated mask (Takes 5 seconds)",value=True,visible=False)
|
290 |
-
with gr.Row():
|
291 |
-
is_checked_crop = gr.Checkbox(label="Yes", info="Use auto-crop & resizing",value=True,visible=False)
|
292 |
-
|
293 |
-
# example = gr.Examples(
|
294 |
-
# inputs=imgs,
|
295 |
-
# examples_per_page=10,
|
296 |
-
# examples=human_ex_list
|
297 |
-
# )
|
298 |
-
|
299 |
-
# with gr.Column():
|
300 |
-
# # image_out = gr.Image(label="Output", elem_id="output-img", height=400)
|
301 |
-
# masked_img = gr.Image(label="Masked image output", elem_id="masked-img",show_share_button=False)
|
302 |
-
with gr.Column():
|
303 |
-
# image_out = gr.Image(label="Output", elem_id="output-img", height=400)
|
304 |
-
image_out = gr.Image(label="Output", elem_id="output-img",show_share_button=True)
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
try_button.click(fn=start_tryon, inputs=[imgs, garm_img, prompt, is_checked,is_checked_crop, denoise_steps, seed, area], outputs=[image_out], api_name='tryon')
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
image_blocks.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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