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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import spaces
|
| 3 |
+
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
from src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipeline
|
| 7 |
+
from src.unet_hacked_garmnet import UNet2DConditionModel as UNet2DConditionModel_ref
|
| 8 |
+
from src.unet_hacked_tryon import UNet2DConditionModel
|
| 9 |
+
from transformers import (
|
| 10 |
+
CLIPImageProcessor,
|
| 11 |
+
CLIPVisionModelWithProjection,
|
| 12 |
+
CLIPTextModel,
|
| 13 |
+
CLIPTextModelWithProjection,
|
| 14 |
+
)
|
| 15 |
+
from diffusers import DDPMScheduler, AutoencoderKL
|
| 16 |
+
from typing import List
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
from transformers import AutoTokenizer
|
| 20 |
+
import numpy as np
|
| 21 |
+
from utils_mask import get_mask_location
|
| 22 |
+
from torchvision import transforms
|
| 23 |
+
import apply_net
|
| 24 |
+
from preprocess.humanparsing.run_parsing import Parsing
|
| 25 |
+
from preprocess.openpose.run_openpose import OpenPose
|
| 26 |
+
from detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientation
|
| 27 |
+
from torchvision.transforms.functional import to_pil_image
|
| 28 |
+
|
| 29 |
+
# Function to convert PIL image to binary mask
|
| 30 |
+
def pil_to_binary_mask(pil_image, threshold=0):
|
| 31 |
+
np_image = np.array(pil_image)
|
| 32 |
+
grayscale_image = Image.fromarray(np_image).convert("L")
|
| 33 |
+
binary_mask = np.array(grayscale_image) > threshold
|
| 34 |
+
mask = np.zeros(binary_mask.shape, dtype=np.uint8)
|
| 35 |
+
for i in range(binary_mask.shape[0]):
|
| 36 |
+
for j in range(binary_mask.shape[1]):
|
| 37 |
+
if binary_mask[i, j]:
|
| 38 |
+
mask[i, j] = 1
|
| 39 |
+
mask = (mask * 255).astype(np.uint8)
|
| 40 |
+
output_mask = Image.fromarray(mask)
|
| 41 |
+
return output_mask
|
| 42 |
+
|
| 43 |
+
# Base path setup
|
| 44 |
+
base_path = 'yisol/IDM-VTON'
|
| 45 |
+
example_path = os.path.join(os.path.dirname(__file__), 'example')
|
| 46 |
+
|
| 47 |
+
# Model loading
|
| 48 |
+
unet = UNet2DConditionModel.from_pretrained(
|
| 49 |
+
base_path,
|
| 50 |
+
subfolder="unet",
|
| 51 |
+
torch_dtype=torch.float16,
|
| 52 |
+
)
|
| 53 |
+
unet.requires_grad_(False)
|
| 54 |
+
tokenizer_one = AutoTokenizer.from_pretrained(
|
| 55 |
+
base_path,
|
| 56 |
+
subfolder="tokenizer",
|
| 57 |
+
use_fast=False,
|
| 58 |
+
)
|
| 59 |
+
tokenizer_two = AutoTokenizer.from_pretrained(
|
| 60 |
+
base_path,
|
| 61 |
+
subfolder="tokenizer_2",
|
| 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 |
+
# Tryon pipeline setup
|
| 110 |
+
pipe = TryonPipeline.from_pretrained(
|
| 111 |
+
base_path,
|
| 112 |
+
unet=unet,
|
| 113 |
+
vae=vae,
|
| 114 |
+
feature_extractor=CLIPImageProcessor(),
|
| 115 |
+
text_encoder=text_encoder_one,
|
| 116 |
+
text_encoder_2=text_encoder_two,
|
| 117 |
+
tokenizer=tokenizer_one,
|
| 118 |
+
tokenizer_2=tokenizer_two,
|
| 119 |
+
scheduler=noise_scheduler,
|
| 120 |
+
image_encoder=image_encoder,
|
| 121 |
+
torch_dtype=torch.float16,
|
| 122 |
+
)
|
| 123 |
+
pipe.unet_encoder = UNet_Encoder
|
| 124 |
+
|
| 125 |
+
# Start try-on function
|
| 126 |
+
@spaces.GPU
|
| 127 |
+
def start_tryon(dict, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed):
|
| 128 |
+
device = "cuda"
|
| 129 |
+
|
| 130 |
+
openpose_model.preprocessor.body_estimation.model.to(device)
|
| 131 |
+
pipe.to(device)
|
| 132 |
+
pipe.unet_encoder.to(device)
|
| 133 |
+
|
| 134 |
+
garm_img = garm_img.convert("RGB").resize((768, 1024))
|
| 135 |
+
human_img_orig = dict["background"].convert("RGB")
|
| 136 |
+
|
| 137 |
+
if is_checked_crop:
|
| 138 |
+
width, height = human_img_orig.size
|
| 139 |
+
target_width = int(min(width, height * (3 / 4)))
|
| 140 |
+
target_height = int(min(height, width * (4 / 3)))
|
| 141 |
+
left = (width - target_width) / 2
|
| 142 |
+
top = (height - target_height) / 2
|
| 143 |
+
right = (width + target_width) / 2
|
| 144 |
+
bottom = (height + target_height) / 2
|
| 145 |
+
cropped_img = human_img_orig.crop((left, top, right, bottom))
|
| 146 |
+
crop_size = cropped_img.size
|
| 147 |
+
human_img = cropped_img.resize((768, 1024))
|
| 148 |
+
else:
|
| 149 |
+
human_img = human_img_orig.resize((768, 1024))
|
| 150 |
+
|
| 151 |
+
if is_checked:
|
| 152 |
+
keypoints = openpose_model(human_img.resize((384, 512)))
|
| 153 |
+
model_parse, _ = parsing_model(human_img.resize((384, 512)))
|
| 154 |
+
mask, mask_gray = get_mask_location('hd', "upper_body", model_parse, keypoints)
|
| 155 |
+
mask = mask.resize((768, 1024))
|
| 156 |
+
else:
|
| 157 |
+
mask = pil_to_binary_mask(dict['layers'][0].convert("RGB").resize((768, 1024)))
|
| 158 |
+
mask_gray = (1 - transforms.ToTensor()(mask)) * tensor_transfrom(human_img)
|
| 159 |
+
mask_gray = to_pil_image((mask_gray + 1.0) / 2.0)
|
| 160 |
+
|
| 161 |
+
human_img_arg = _apply_exif_orientation(human_img.resize((384, 512)))
|
| 162 |
+
human_img_arg = convert_PIL_to_numpy(human_img_arg, format="BGR")
|
| 163 |
+
|
| 164 |
+
args = apply_net.create_argument_parser().parse_args(
|
| 165 |
+
('show', './configs/densepose_rcnn_R_50_FPN_s1x.yaml', './ckpt/densepose/model_final_162be9.pkl', 'dp_segm', '-v', '--opts', 'MODEL.DEVICE', 'cuda')
|
| 166 |
+
)
|
| 167 |
+
pose_img = args.func(args, human_img_arg)
|
| 168 |
+
pose_img = pose_img[:, :, ::-1]
|
| 169 |
+
pose_img = Image.fromarray(pose_img).resize((768, 1024))
|
| 170 |
+
|
| 171 |
+
with torch.no_grad():
|
| 172 |
+
with torch.cuda.amp.autocast():
|
| 173 |
+
with torch.no_grad():
|
| 174 |
+
prompt = "model is wearing " + garment_des
|
| 175 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
| 176 |
+
with torch.inference_mode():
|
| 177 |
+
(
|
| 178 |
+
prompt_embeds,
|
| 179 |
+
negative_prompt_embeds,
|
| 180 |
+
pooled_prompt_embeds,
|
| 181 |
+
negative_pooled_prompt_embeds,
|
| 182 |
+
) = pipe.encode_prompt(
|
| 183 |
+
prompt,
|
| 184 |
+
num_images_per_prompt=1,
|
| 185 |
+
do_classifier_free_guidance=True,
|
| 186 |
+
negative_prompt=negative_prompt,
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
prompt = "a photo of " + garment_des
|
| 190 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
| 191 |
+
if not isinstance(prompt, List):
|
| 192 |
+
prompt = [prompt] * 1
|
| 193 |
+
if not isinstance(negative_prompt, List):
|
| 194 |
+
negative_prompt = [negative_prompt] * 1
|
| 195 |
+
with torch.inference_mode():
|
| 196 |
+
(
|
| 197 |
+
prompt_embeds_c,
|
| 198 |
+
_,
|
| 199 |
+
_,
|
| 200 |
+
_,
|
| 201 |
+
) = pipe.encode_prompt(
|
| 202 |
+
prompt,
|
| 203 |
+
num_images_per_prompt=1,
|
| 204 |
+
do_classifier_free_guidance=False,
|
| 205 |
+
negative_prompt=negative_prompt,
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
pose_img = tensor_transfrom(pose_img).unsqueeze(0).to(device, torch.float16)
|
| 209 |
+
garm_tensor = tensor_transfrom(garm_img).unsqueeze(0).to(device, torch.float16)
|
| 210 |
+
generator = torch.Generator(device).manual_seed(seed) if seed is not None else None
|
| 211 |
+
images = pipe(
|
| 212 |
+
prompt_embeds=prompt_embeds.to(device, torch.float16),
|
| 213 |
+
negative_prompt_embeds=negative_prompt_embeds.to(device, torch.float16),
|
| 214 |
+
pooled_prompt_embeds=pooled_prompt_embeds.to(device, torch.float16),
|
| 215 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds.to(device, torch.float16),
|
| 216 |
+
num_inference_steps=denoise_steps,
|
| 217 |
+
generator=generator,
|
| 218 |
+
strength=1.0,
|
| 219 |
+
pose_img=pose_img.to(device, torch.float16),
|
| 220 |
+
text_embeds_cloth=prompt_embeds_c.to(device, torch.float16),
|
| 221 |
+
cloth=garm_tensor.to(device, torch.float16),
|
| 222 |
+
mask_image=mask,
|
| 223 |
+
image=human_img,
|
| 224 |
+
height=1024,
|
| 225 |
+
width=768,
|
| 226 |
+
ip_adapter_image=garm_img.resize((768, 1024)),
|
| 227 |
+
guidance_scale=2.0,
|
| 228 |
+
)[0]
|
| 229 |
+
|
| 230 |
+
if is_checked_crop:
|
| 231 |
+
out_img = images[0].resize(crop_size)
|
| 232 |
+
human_img_orig.paste(out_img, (int(left), int(top)))
|
| 233 |
+
return human_img_orig, mask_gray
|
| 234 |
+
else:
|
| 235 |
+
return images[0], mask_gray
|
| 236 |
+
|
| 237 |
+
# Gradio Interface
|
| 238 |
+
def greet():
|
| 239 |
+
return "Hello, welcome to the virtual try-on demo!"
|
| 240 |
+
|
| 241 |
+
demo = gr.Interface(fn=greet, inputs=[], outputs=[])
|
| 242 |
+
demo.launch()
|