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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import einops
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
import random
|
| 8 |
+
from huggingface_hub import hf_hub_download
|
| 9 |
+
|
| 10 |
+
from pytorch_lightning import seed_everything
|
| 11 |
+
from utils.resize import resize_image, HWC3
|
| 12 |
+
from cldm.model import create_model, load_state_dict
|
| 13 |
+
from cldm.ddim_lle import DDIMSampler as DDIMSampler_LLE
|
| 14 |
+
from cldm.ddim_hlg import DDIMSampler as DDIMSampler_HLG
|
| 15 |
+
from automation_pose_mask.openpose import OpenposeDetector
|
| 16 |
+
from automation_pose_mask.auto_mask import MaskDetector
|
| 17 |
+
from PIL import Image
|
| 18 |
+
from rembg import remove
|
| 19 |
+
|
| 20 |
+
from utils.config import (
|
| 21 |
+
model_yaml,
|
| 22 |
+
category_dict,
|
| 23 |
+
attribute_dict
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
##########################################
|
| 27 |
+
# Download model files from HF Hub
|
| 28 |
+
##########################################
|
| 29 |
+
|
| 30 |
+
MODEL_REPO = "NguyenDinhHieu/EquiFashionModel"
|
| 31 |
+
|
| 32 |
+
openpose_body_model_path = hf_hub_download(MODEL_REPO, filename="body_pose_model.pth")
|
| 33 |
+
openpose_hand_model_path = hf_hub_download(MODEL_REPO, filename="hand_pose_model.pth")
|
| 34 |
+
sam_model_path = hf_hub_download(MODEL_REPO, filename="open_clip_pytorch_model.bin")
|
| 35 |
+
my_model_path = hf_hub_download(MODEL_REPO, filename="eqf_final.ckpt")
|
| 36 |
+
|
| 37 |
+
##########################################
|
| 38 |
+
# Initialize model on GPU once
|
| 39 |
+
##########################################
|
| 40 |
+
|
| 41 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 42 |
+
|
| 43 |
+
apply_openpose = OpenposeDetector(
|
| 44 |
+
body_model_path=openpose_body_model_path,
|
| 45 |
+
hand_model_path=openpose_hand_model_path
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
apply_mask = MaskDetector(sam_model_path=sam_model_path)
|
| 49 |
+
|
| 50 |
+
model = create_model(model_yaml).to(device)
|
| 51 |
+
model.load_state_dict(load_state_dict(my_model_path, location=device))
|
| 52 |
+
model.eval()
|
| 53 |
+
|
| 54 |
+
hlg_sampler = DDIMSampler_HLG(model)
|
| 55 |
+
lle_sampler = DDIMSampler_LLE(model)
|
| 56 |
+
|
| 57 |
+
##########################################
|
| 58 |
+
# Example images
|
| 59 |
+
##########################################
|
| 60 |
+
|
| 61 |
+
example_path = os.path.join(os.path.dirname(__file__), "preselected_images")
|
| 62 |
+
example_image_list = [os.path.join(example_path, x) for x in os.listdir(example_path)]
|
| 63 |
+
|
| 64 |
+
##########################################
|
| 65 |
+
# Utility functions
|
| 66 |
+
##########################################
|
| 67 |
+
|
| 68 |
+
def pil_to_binary_mask(pil_image, threshold=0):
|
| 69 |
+
np_image = np.array(pil_image)
|
| 70 |
+
grayscale_image = Image.fromarray(np_image).convert("L")
|
| 71 |
+
binary_mask = (np.array(grayscale_image) > threshold).astype(np.uint8) * 255
|
| 72 |
+
return Image.fromarray(binary_mask)
|
| 73 |
+
|
| 74 |
+
def add_white_background(image):
|
| 75 |
+
image = image.convert("RGBA")
|
| 76 |
+
white_bg = Image.new("RGBA", image.size, "WHITE")
|
| 77 |
+
white_bg.paste(image, (0, 0), image)
|
| 78 |
+
return white_bg.convert("RGB")
|
| 79 |
+
|
| 80 |
+
##########################################
|
| 81 |
+
# HLG PROCESS
|
| 82 |
+
##########################################
|
| 83 |
+
|
| 84 |
+
def hlg_process(hlg_prompt, input_image, category, a_prompt, n_prompt,
|
| 85 |
+
num_samples, image_resolution, detect_resolution, ddim_steps,
|
| 86 |
+
guess_mode, strength, scale, seed, eta):
|
| 87 |
+
|
| 88 |
+
with torch.no_grad():
|
| 89 |
+
input_image = HWC3(input_image)
|
| 90 |
+
detected_map, _ = apply_openpose(resize_image(input_image, detect_resolution))
|
| 91 |
+
detected_map = HWC3(detected_map)
|
| 92 |
+
img = resize_image(input_image, image_resolution)
|
| 93 |
+
H, W, C = img.shape
|
| 94 |
+
|
| 95 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
|
| 96 |
+
|
| 97 |
+
control = torch.from_numpy(detected_map).float().to(device) / 255.0
|
| 98 |
+
control = torch.stack([control for _ in range(num_samples)], dim=0)
|
| 99 |
+
control = einops.rearrange(control, 'b h w c -> b c h w')
|
| 100 |
+
|
| 101 |
+
if seed == -1:
|
| 102 |
+
seed = random.randint(0, 4294967294)
|
| 103 |
+
seed_everything(seed)
|
| 104 |
+
|
| 105 |
+
cond = {
|
| 106 |
+
"c_concat": [control],
|
| 107 |
+
"c_crossattn": [model.get_learned_conditioning([hlg_prompt + ', ' + a_prompt] * num_samples)]
|
| 108 |
+
}
|
| 109 |
+
un_cond = {
|
| 110 |
+
"c_concat": None if guess_mode else [control],
|
| 111 |
+
"c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]
|
| 112 |
+
}
|
| 113 |
+
shape = (4, H // 8, W // 8)
|
| 114 |
+
|
| 115 |
+
model.control_scales = ([strength] * 13)
|
| 116 |
+
|
| 117 |
+
samples, _ = hlg_sampler.sample(ddim_steps, num_samples, shape, cond,
|
| 118 |
+
verbose=False, eta=eta,
|
| 119 |
+
unconditional_guidance_scale=scale,
|
| 120 |
+
unconditional_conditioning=un_cond)
|
| 121 |
+
|
| 122 |
+
x_samples = model.decode_first_stage(samples)
|
| 123 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c')
|
| 124 |
+
* 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
| 125 |
+
|
| 126 |
+
results = [Image.fromarray(x_samples[i]) for i in range(num_samples)]
|
| 127 |
+
return [add_white_background(remove(img)) for img in results]
|
| 128 |
+
|
| 129 |
+
##########################################
|
| 130 |
+
# LLE PROCESS
|
| 131 |
+
##########################################
|
| 132 |
+
|
| 133 |
+
def lle_process(lle_prompt, dict_img_mask, category, a_prompt, n_prompt,
|
| 134 |
+
num_samples, image_resolution, detect_resolution, ddim_steps,
|
| 135 |
+
guess_mode, strength, scale, seed, eta, attribute, selection_mode):
|
| 136 |
+
|
| 137 |
+
input_image = dict_img_mask["background"].convert("RGB")
|
| 138 |
+
input_image = HWC3(np.array(input_image))
|
| 139 |
+
|
| 140 |
+
detected_map, keypoints = apply_openpose(resize_image(input_image, detect_resolution))
|
| 141 |
+
detected_map = HWC3(detected_map)
|
| 142 |
+
|
| 143 |
+
if selection_mode == "Automatically recognize":
|
| 144 |
+
mask = apply_mask(resize_image(input_image, detect_resolution), keypoints,
|
| 145 |
+
category=category, attribute=attribute, sam_mode=True)
|
| 146 |
+
else:
|
| 147 |
+
mask = pil_to_binary_mask(dict_img_mask['layers'][0].convert("RGB"))
|
| 148 |
+
|
| 149 |
+
if mask is not None:
|
| 150 |
+
mask = torch.from_numpy(np.array(mask.convert("L"))).float().to(device) / 255.0
|
| 151 |
+
mask = mask.unsqueeze(0).unsqueeze(0)
|
| 152 |
+
|
| 153 |
+
img = resize_image(input_image, image_resolution)
|
| 154 |
+
H, W, C = img.shape
|
| 155 |
+
|
| 156 |
+
init_img = torch.from_numpy(img).float().to(device) / 127.0 - 1.0
|
| 157 |
+
init_img = einops.rearrange(init_img, 'h w c -> 1 c h w')
|
| 158 |
+
init_img = torch.stack([init_img] * num_samples)
|
| 159 |
+
|
| 160 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_NEAREST)
|
| 161 |
+
control = torch.from_numpy(detected_map).float().to(device) / 255.0
|
| 162 |
+
control = torch.stack([control]*num_samples)
|
| 163 |
+
control = einops.rearrange(control, 'b h w c -> b c h w')
|
| 164 |
+
|
| 165 |
+
if seed == -1:
|
| 166 |
+
seed = random.randint(0, 4294967294)
|
| 167 |
+
seed_everything(seed)
|
| 168 |
+
|
| 169 |
+
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([lle_prompt + ', ' + a_prompt] * num_samples)]}
|
| 170 |
+
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
|
| 171 |
+
shape = (4, H // 8, W // 8)
|
| 172 |
+
|
| 173 |
+
samples, _ = lle_sampler.sample(ddim_steps, num_samples, shape, cond,
|
| 174 |
+
verbose=False, eta=eta,
|
| 175 |
+
unconditional_guidance_scale=scale,
|
| 176 |
+
unconditional_conditioning=un_cond,
|
| 177 |
+
init_img=init_img, mask=mask,
|
| 178 |
+
english_attribute=attribute)
|
| 179 |
+
|
| 180 |
+
x_samples = model.decode_first_stage(samples)
|
| 181 |
+
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c')
|
| 182 |
+
* 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
|
| 183 |
+
|
| 184 |
+
return [Image.fromarray(x_samples[i]) for i in range(num_samples)]
|
| 185 |
+
|
| 186 |
+
##########################################
|
| 187 |
+
# Send result to attribute editor
|
| 188 |
+
##########################################
|
| 189 |
+
|
| 190 |
+
def result2input(images):
|
| 191 |
+
return {"background": images[-1], "layers": None, "composite": None}
|
| 192 |
+
|
| 193 |
+
##########################################
|
| 194 |
+
# FULL UI
|
| 195 |
+
##########################################
|
| 196 |
+
|
| 197 |
+
def create_hfddm():
|
| 198 |
+
with gr.Blocks().queue() as app:
|
| 199 |
+
|
| 200 |
+
category = gr.Radio(list(category_dict.values()), value=list(category_dict.values())[0], label="Clothing Category")
|
| 201 |
+
|
| 202 |
+
with gr.Row():
|
| 203 |
+
with gr.Column():
|
| 204 |
+
with gr.Tab("Draft Design"):
|
| 205 |
+
hlg_prompt = gr.Textbox(label="High-level design prompt")
|
| 206 |
+
hlg_input_image = gr.Image(sources=("upload", "webcam"), type="numpy", value=example_image_list[0], label="Reference pose")
|
| 207 |
+
gr.Examples(inputs=hlg_input_image, examples=example_image_list)
|
| 208 |
+
hlg_run = gr.Button("Generate")
|
| 209 |
+
|
| 210 |
+
with gr.Tab("Attribute Editing"):
|
| 211 |
+
lle_prompt = gr.Textbox(label="Attribute prompt")
|
| 212 |
+
lle_input_image = gr.ImageEditor(sources='upload', type="pil", label="Edit regions", value=example_image_list[0])
|
| 213 |
+
gr.Examples(inputs=lle_input_image, examples=example_image_list)
|
| 214 |
+
selection_mode = gr.Radio(["Automatically recognize", "User interface"], label="Mask Selection", value="Automatically recognize")
|
| 215 |
+
|
| 216 |
+
current_tab = {}
|
| 217 |
+
lle_run = {}
|
| 218 |
+
for tab_elem in attribute_dict.values():
|
| 219 |
+
with gr.Tab(tab_elem):
|
| 220 |
+
current_tab[tab_elem] = gr.Label(value=tab_elem, visible=False)
|
| 221 |
+
lle_run[tab_elem] = gr.Button("Generate")
|
| 222 |
+
|
| 223 |
+
with gr.Column():
|
| 224 |
+
result_gallery = gr.Gallery(label="Result", show_label=False, elem_id="gallery", selected_index=0, interactive=False)
|
| 225 |
+
send2llg = gr.Button("Send to Attribute Editing")
|
| 226 |
+
|
| 227 |
+
with gr.Accordion("Advanced Options", open=False):
|
| 228 |
+
num_samples = gr.Slider(label="Images", minimum=1, maximum=4, value=2, step=1)
|
| 229 |
+
image_resolution = gr.Slider(label="Resolution", minimum=256, maximum=768, value=512, step=64)
|
| 230 |
+
strength = gr.Slider(label="Control Strength", minimum=0.0, maximum=2.0, value=1.0, step=0.01)
|
| 231 |
+
guess_mode = gr.Checkbox(label='Guess Mode', value=False)
|
| 232 |
+
detect_resolution = gr.Slider(label="Pose Detection Resolution", minimum=128, maximum=1024, value=512, step=1)
|
| 233 |
+
ddim_steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=10, step=1, visible=False)
|
| 234 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=30.0, value=9.0, step=0.1)
|
| 235 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=4294967294, value=11, step=1)
|
| 236 |
+
eta = gr.Number(label="ETA (DDIM)", value=0.0)
|
| 237 |
+
a_prompt = gr.Textbox(label="Added Prompt", value='best quality, extremely detailed, masterpiece, 8k, white background')
|
| 238 |
+
n_prompt = gr.Textbox(label="Negative Prompt", value='worst quality, low quality, bad anatomy, watermark, signature, blurry')
|
| 239 |
+
|
| 240 |
+
hlg_run.click(fn=hlg_process, inputs=[hlg_prompt, hlg_input_image, category, a_prompt, n_prompt,
|
| 241 |
+
num_samples, image_resolution, detect_resolution, ddim_steps,
|
| 242 |
+
guess_mode, strength, scale, seed, eta], outputs=[result_gallery])
|
| 243 |
+
|
| 244 |
+
for tab_elem in attribute_dict.values():
|
| 245 |
+
lle_run[tab_elem].click(fn=lle_process, inputs=[lle_prompt, lle_input_image, category, a_prompt, n_prompt,
|
| 246 |
+
num_samples, image_resolution, detect_resolution,
|
| 247 |
+
ddim_steps, guess_mode, strength, scale, seed, eta,
|
| 248 |
+
current_tab[tab_elem], selection_mode], outputs=[result_gallery])
|
| 249 |
+
|
| 250 |
+
send2llg.click(fn=result2input, inputs=result_gallery, outputs=lle_input_image)
|
| 251 |
+
|
| 252 |
+
return app
|
| 253 |
+
|
| 254 |
+
hfddm_block = create_hfddm()
|
| 255 |
+
|
| 256 |
+
demo = gr.Blocks(title="AI Fashion Design", theme=gr.themes.Monochrome(secondary_hue="orange", neutral_hue="gray")).queue()
|
| 257 |
+
|
| 258 |
+
with demo:
|
| 259 |
+
gr.Markdown("# **AI Fashion Design** 👗")
|
| 260 |
+
with gr.Tab("Fashion Design"):
|
| 261 |
+
hfddm_block.render()
|
| 262 |
+
|
| 263 |
+
demo.launch()
|