Hunsain Mazhar commited on
Commit Β·
3327fc9
1
Parent(s): d0be949
Refactor README and app.py for improved clarity; updated title, emoji, and SDK version, added HF OAuth support, enhanced model downloading logic, and improved error handling.
Browse files
README.md
CHANGED
|
@@ -1,13 +1,14 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji: π
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 4.
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
-
license:
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: IDM VTON
|
| 3 |
+
emoji: πππ
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: red
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 4.24.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: cc-by-nc-sa-4.0
|
| 11 |
+
short_description: High-fidelity Virtual Try-on
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
CHANGED
|
@@ -2,21 +2,16 @@ import sys
|
|
| 2 |
import os
|
| 3 |
import gc
|
| 4 |
import shutil
|
| 5 |
-
import huggingface_hub
|
| 6 |
|
| 7 |
-
# ---
|
| 8 |
-
#
|
| 9 |
-
token = os.getenv("HF_TOKEN")
|
| 10 |
-
if token:
|
| 11 |
-
print("π Authenticating with Secret Token...")
|
| 12 |
-
huggingface_hub.login(token=token)
|
| 13 |
-
|
| 14 |
-
# --- Install Detectron2 if missing ---
|
| 15 |
try:
|
| 16 |
import detectron2
|
| 17 |
except ImportError:
|
|
|
|
| 18 |
os.system('pip install git+https://github.com/facebookresearch/detectron2.git')
|
| 19 |
|
|
|
|
| 20 |
import gradio as gr
|
| 21 |
import spaces
|
| 22 |
from PIL import Image
|
|
@@ -28,7 +23,7 @@ from huggingface_hub import hf_hub_download
|
|
| 28 |
|
| 29 |
sys.path.append('./')
|
| 30 |
|
| 31 |
-
#
|
| 32 |
try:
|
| 33 |
from utils_mask import get_mask_location
|
| 34 |
from src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipeline
|
|
@@ -39,7 +34,7 @@ try:
|
|
| 39 |
from detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientation
|
| 40 |
import apply_net
|
| 41 |
except ImportError as e:
|
| 42 |
-
raise ImportError(f"CRITICAL ERROR: Missing core modules. {e}")
|
| 43 |
|
| 44 |
from transformers import (
|
| 45 |
CLIPImageProcessor, CLIPVisionModelWithProjection, CLIPTextModel,
|
|
@@ -47,31 +42,72 @@ from transformers import (
|
|
| 47 |
)
|
| 48 |
from diffusers import DDPMScheduler, AutoencoderKL
|
| 49 |
|
| 50 |
-
# ---
|
|
|
|
|
|
|
| 51 |
def download_model_robust(repo_id, filename, local_path):
|
| 52 |
-
if os.path.exists(local_path)
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
try:
|
|
|
|
| 55 |
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
except Exception as e:
|
| 61 |
-
print(f"Failed download {filename}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
def check_and_download_models():
|
|
|
|
|
|
|
|
|
|
| 64 |
download_model_robust("camenduru/IDM-VTON", "humanparsing/parsing_atr.onnx", "ckpt/humanparsing/parsing_atr.onnx")
|
| 65 |
download_model_robust("camenduru/IDM-VTON", "humanparsing/parsing_lip.onnx", "ckpt/humanparsing/parsing_lip.onnx")
|
| 66 |
download_model_robust("camenduru/IDM-VTON", "densepose/model_final_162be9.pkl", "ckpt/densepose/model_final_162be9.pkl")
|
| 67 |
download_model_robust("camenduru/IDM-VTON", "openpose/ckpts/body_pose_model.pth", "ckpt/openpose/ckpts/body_pose_model.pth")
|
|
|
|
|
|
|
| 68 |
download_model_robust("h94/IP-Adapter", "sdxl_models/ip-adapter-plus_sdxl_vit-h.bin", "ckpt/ip_adapter/ip-adapter-plus_sdxl_vit-h.bin")
|
| 69 |
download_model_robust("h94/IP-Adapter", "models/image_encoder/config.json", "ckpt/image_encoder/config.json")
|
| 70 |
download_model_robust("h94/IP-Adapter", "models/image_encoder/pytorch_model.bin", "ckpt/image_encoder/pytorch_model.bin")
|
| 71 |
|
|
|
|
| 72 |
check_and_download_models()
|
| 73 |
|
| 74 |
-
# ---
|
|
|
|
|
|
|
| 75 |
base_path = 'yisol/IDM-VTON'
|
| 76 |
def load_models():
|
| 77 |
unet = UNet2DConditionModel.from_pretrained(base_path, subfolder="unet", torch_dtype=torch.float16)
|
|
@@ -84,9 +120,11 @@ def load_models():
|
|
| 84 |
vae = AutoencoderKL.from_pretrained(base_path, subfolder="vae", torch_dtype=torch.float16)
|
| 85 |
UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(base_path, subfolder="unet_encoder", torch_dtype=torch.float16)
|
| 86 |
|
|
|
|
| 87 |
parsing_model = Parsing(0)
|
| 88 |
openpose_model = OpenPose(0)
|
| 89 |
|
|
|
|
| 90 |
UNet_Encoder.requires_grad_(False)
|
| 91 |
image_encoder.requires_grad_(False)
|
| 92 |
vae.requires_grad_(False)
|
|
@@ -106,23 +144,20 @@ def load_models():
|
|
| 106 |
pipe, openpose_model, parsing_model = load_models()
|
| 107 |
tensor_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])
|
| 108 |
|
| 109 |
-
# ---
|
|
|
|
|
|
|
| 110 |
@spaces.GPU(duration=120)
|
| 111 |
-
def start_tryon(human_img, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed
|
| 112 |
-
# CRITICAL: If OAuth is enabled, we verify the user here
|
| 113 |
-
if profile is None:
|
| 114 |
-
# It will still run, but this log helps debug
|
| 115 |
-
print("β οΈ User running without OAuth Profile (might hit limits)")
|
| 116 |
-
else:
|
| 117 |
-
print(f"β
Pro User Detected: {profile.name}")
|
| 118 |
-
|
| 119 |
device = "cuda"
|
|
|
|
| 120 |
try:
|
| 121 |
openpose_model.preprocessor.body_estimation.model.to(device)
|
| 122 |
pipe.to(device)
|
| 123 |
pipe.unet_encoder.to(device)
|
| 124 |
|
| 125 |
-
if not human_img or not garm_img:
|
|
|
|
| 126 |
|
| 127 |
garm_img = garm_img.convert("RGB").resize((768, 1024))
|
| 128 |
human_img_orig = human_img.convert("RGB")
|
|
@@ -146,7 +181,7 @@ def start_tryon(human_img, garm_img, garment_des, is_checked, is_checked_crop, d
|
|
| 146 |
model_parse, _ = parsing_model(human_img.resize((384, 512)))
|
| 147 |
mask, mask_gray = get_mask_location('hd', "upper_body", model_parse, keypoints)
|
| 148 |
mask = mask.resize((768, 1024))
|
| 149 |
-
|
| 150 |
mask_gray = (1 - transforms.ToTensor()(mask)) * tensor_transform(human_img)
|
| 151 |
mask_gray = to_pil_image((mask_gray + 1.0) / 2.0)
|
| 152 |
|
|
@@ -161,9 +196,13 @@ def start_tryon(human_img, garm_img, garment_des, is_checked, is_checked_crop, d
|
|
| 161 |
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
| 162 |
|
| 163 |
with torch.cuda.amp.autocast():
|
| 164 |
-
(prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds) = pipe.encode_prompt(
|
|
|
|
|
|
|
| 165 |
prompt_c = "a photo of " + garment_des
|
| 166 |
-
(prompt_embeds_c, _, _, _) = pipe.encode_prompt(
|
|
|
|
|
|
|
| 167 |
|
| 168 |
pose_img = tensor_transform(pose_img).unsqueeze(0).to(device, torch.float16)
|
| 169 |
garm_tensor = tensor_transform(garm_img).unsqueeze(0).to(device, torch.float16)
|
|
@@ -188,23 +227,26 @@ def start_tryon(human_img, garm_img, garment_des, is_checked, is_checked_crop, d
|
|
| 188 |
final_result = human_img_orig
|
| 189 |
else:
|
| 190 |
final_result = images[0]
|
| 191 |
-
|
| 192 |
return final_result, mask_gray
|
| 193 |
|
| 194 |
except Exception as e:
|
| 195 |
raise gr.Error(f"Error: {e}")
|
|
|
|
| 196 |
finally:
|
| 197 |
-
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
| 199 |
gc.collect()
|
| 200 |
torch.cuda.empty_cache()
|
| 201 |
|
| 202 |
-
# ---
|
|
|
|
|
|
|
| 203 |
with gr.Blocks(theme=gr.themes.Soft(), title="Tryonnix Engine") as demo:
|
| 204 |
-
gr.Markdown("# β¨ Tryonnix 2D Engine")
|
| 205 |
-
# LOGIN BUTTON: This is the fix. It forces the Pro Token to be sent.
|
| 206 |
-
gr.LoginButton()
|
| 207 |
-
|
| 208 |
with gr.Row():
|
| 209 |
with gr.Column():
|
| 210 |
img_human = gr.Image(label="Human", type="pil", height=400)
|
|
@@ -219,7 +261,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="Tryonnix Engine") as demo:
|
|
| 219 |
out = gr.Image(label="Result", type="pil", height=600)
|
| 220 |
mask_out = gr.Image(label="Mask", type="pil", visible=False)
|
| 221 |
|
| 222 |
-
btn.click(fn=start_tryon, inputs=[img_human, img_garm, desc, chk1, chk2, steps, seed], outputs=[out, mask_out])
|
| 223 |
|
| 224 |
if __name__ == "__main__":
|
| 225 |
demo.queue(max_size=10).launch()
|
|
|
|
| 2 |
import os
|
| 3 |
import gc
|
| 4 |
import shutil
|
|
|
|
| 5 |
|
| 6 |
+
# --- 1. System Setup & Error Handling ---
|
| 7 |
+
# Force install detectron2 if missing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
try:
|
| 9 |
import detectron2
|
| 10 |
except ImportError:
|
| 11 |
+
print("β οΈ Detectron2 missing. Installing...")
|
| 12 |
os.system('pip install git+https://github.com/facebookresearch/detectron2.git')
|
| 13 |
|
| 14 |
+
import requests
|
| 15 |
import gradio as gr
|
| 16 |
import spaces
|
| 17 |
from PIL import Image
|
|
|
|
| 23 |
|
| 24 |
sys.path.append('./')
|
| 25 |
|
| 26 |
+
# Import Local Modules
|
| 27 |
try:
|
| 28 |
from utils_mask import get_mask_location
|
| 29 |
from src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipeline
|
|
|
|
| 34 |
from detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientation
|
| 35 |
import apply_net
|
| 36 |
except ImportError as e:
|
| 37 |
+
raise ImportError(f"CRITICAL ERROR: Missing core modules. Error: {e}")
|
| 38 |
|
| 39 |
from transformers import (
|
| 40 |
CLIPImageProcessor, CLIPVisionModelWithProjection, CLIPTextModel,
|
|
|
|
| 42 |
)
|
| 43 |
from diffusers import DDPMScheduler, AutoencoderKL
|
| 44 |
|
| 45 |
+
# ---------------------------------------------------------
|
| 46 |
+
# 2. ROBUST MODEL DOWNLOADER (The Fix)
|
| 47 |
+
# ---------------------------------------------------------
|
| 48 |
def download_model_robust(repo_id, filename, local_path):
|
| 49 |
+
if os.path.exists(local_path):
|
| 50 |
+
# Quick size check to ensure it's not an empty corrupt file
|
| 51 |
+
if os.path.getsize(local_path) > 1000:
|
| 52 |
+
print(f"β
Found {local_path}")
|
| 53 |
+
return
|
| 54 |
+
else:
|
| 55 |
+
print(f"β οΈ Corrupt file found at {local_path}, redownloading...")
|
| 56 |
+
os.remove(local_path)
|
| 57 |
+
|
| 58 |
+
print(f"β¬οΈ Downloading {filename} to {local_path}...")
|
| 59 |
try:
|
| 60 |
+
# Create directory
|
| 61 |
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
| 62 |
+
|
| 63 |
+
# Download using Hugging Face Hub (Fast & Cached)
|
| 64 |
+
downloaded_file = hf_hub_download(
|
| 65 |
+
repo_id=repo_id,
|
| 66 |
+
filename=filename,
|
| 67 |
+
local_dir=os.path.dirname(local_path),
|
| 68 |
+
local_dir_use_symlinks=False
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# If the filename in repo is different from target, rename it
|
| 72 |
+
# (hf_hub_download saves to local_dir/filename)
|
| 73 |
+
actual_download_path = os.path.join(os.path.dirname(local_path), filename)
|
| 74 |
+
if actual_download_path != local_path:
|
| 75 |
+
# Move it to the exact expected path if different
|
| 76 |
+
if os.path.exists(actual_download_path):
|
| 77 |
+
shutil.move(actual_download_path, local_path)
|
| 78 |
+
|
| 79 |
+
print(f"β
Successfully downloaded {local_path}")
|
| 80 |
+
|
| 81 |
except Exception as e:
|
| 82 |
+
print(f"β Failed to download {filename}: {e}")
|
| 83 |
+
# Manual Fallback for complex paths
|
| 84 |
+
try:
|
| 85 |
+
url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"
|
| 86 |
+
print(f"π Trying direct URL fallback: {url}")
|
| 87 |
+
os.system(f"wget -O {local_path} {url}")
|
| 88 |
+
except:
|
| 89 |
+
pass
|
| 90 |
|
| 91 |
def check_and_download_models():
|
| 92 |
+
print("β³ VALIDATING MODELS...")
|
| 93 |
+
|
| 94 |
+
# 1. Parsing & OpenPose (From Camenduru)
|
| 95 |
download_model_robust("camenduru/IDM-VTON", "humanparsing/parsing_atr.onnx", "ckpt/humanparsing/parsing_atr.onnx")
|
| 96 |
download_model_robust("camenduru/IDM-VTON", "humanparsing/parsing_lip.onnx", "ckpt/humanparsing/parsing_lip.onnx")
|
| 97 |
download_model_robust("camenduru/IDM-VTON", "densepose/model_final_162be9.pkl", "ckpt/densepose/model_final_162be9.pkl")
|
| 98 |
download_model_robust("camenduru/IDM-VTON", "openpose/ckpts/body_pose_model.pth", "ckpt/openpose/ckpts/body_pose_model.pth")
|
| 99 |
+
|
| 100 |
+
# 2. IP Adapter (From h94)
|
| 101 |
download_model_robust("h94/IP-Adapter", "sdxl_models/ip-adapter-plus_sdxl_vit-h.bin", "ckpt/ip_adapter/ip-adapter-plus_sdxl_vit-h.bin")
|
| 102 |
download_model_robust("h94/IP-Adapter", "models/image_encoder/config.json", "ckpt/image_encoder/config.json")
|
| 103 |
download_model_robust("h94/IP-Adapter", "models/image_encoder/pytorch_model.bin", "ckpt/image_encoder/pytorch_model.bin")
|
| 104 |
|
| 105 |
+
# EXECUTE DOWNLOAD BEFORE LOADING ANYTHING
|
| 106 |
check_and_download_models()
|
| 107 |
|
| 108 |
+
# ---------------------------------------------------------
|
| 109 |
+
# 3. LOAD MODELS
|
| 110 |
+
# ---------------------------------------------------------
|
| 111 |
base_path = 'yisol/IDM-VTON'
|
| 112 |
def load_models():
|
| 113 |
unet = UNet2DConditionModel.from_pretrained(base_path, subfolder="unet", torch_dtype=torch.float16)
|
|
|
|
| 120 |
vae = AutoencoderKL.from_pretrained(base_path, subfolder="vae", torch_dtype=torch.float16)
|
| 121 |
UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(base_path, subfolder="unet_encoder", torch_dtype=torch.float16)
|
| 122 |
|
| 123 |
+
# Initialize Preprocessors
|
| 124 |
parsing_model = Parsing(0)
|
| 125 |
openpose_model = OpenPose(0)
|
| 126 |
|
| 127 |
+
# Freeze Weights
|
| 128 |
UNet_Encoder.requires_grad_(False)
|
| 129 |
image_encoder.requires_grad_(False)
|
| 130 |
vae.requires_grad_(False)
|
|
|
|
| 144 |
pipe, openpose_model, parsing_model = load_models()
|
| 145 |
tensor_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5], [0.5])])
|
| 146 |
|
| 147 |
+
# ---------------------------------------------------------
|
| 148 |
+
# 4. INFERENCE
|
| 149 |
+
# ---------------------------------------------------------
|
| 150 |
@spaces.GPU(duration=120)
|
| 151 |
+
def start_tryon(human_img, garm_img, garment_des, is_checked, is_checked_crop, denoise_steps, seed):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
device = "cuda"
|
| 153 |
+
|
| 154 |
try:
|
| 155 |
openpose_model.preprocessor.body_estimation.model.to(device)
|
| 156 |
pipe.to(device)
|
| 157 |
pipe.unet_encoder.to(device)
|
| 158 |
|
| 159 |
+
if not human_img or not garm_img:
|
| 160 |
+
raise gr.Error("Please upload both Human and Garment images.")
|
| 161 |
|
| 162 |
garm_img = garm_img.convert("RGB").resize((768, 1024))
|
| 163 |
human_img_orig = human_img.convert("RGB")
|
|
|
|
| 181 |
model_parse, _ = parsing_model(human_img.resize((384, 512)))
|
| 182 |
mask, mask_gray = get_mask_location('hd', "upper_body", model_parse, keypoints)
|
| 183 |
mask = mask.resize((768, 1024))
|
| 184 |
+
|
| 185 |
mask_gray = (1 - transforms.ToTensor()(mask)) * tensor_transform(human_img)
|
| 186 |
mask_gray = to_pil_image((mask_gray + 1.0) / 2.0)
|
| 187 |
|
|
|
|
| 196 |
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
| 197 |
|
| 198 |
with torch.cuda.amp.autocast():
|
| 199 |
+
(prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds) = pipe.encode_prompt(
|
| 200 |
+
prompt, num_images_per_prompt=1, do_classifier_free_guidance=True, negative_prompt=negative_prompt
|
| 201 |
+
)
|
| 202 |
prompt_c = "a photo of " + garment_des
|
| 203 |
+
(prompt_embeds_c, _, _, _) = pipe.encode_prompt(
|
| 204 |
+
prompt_c, num_images_per_prompt=1, do_classifier_free_guidance=False, negative_prompt=negative_prompt
|
| 205 |
+
)
|
| 206 |
|
| 207 |
pose_img = tensor_transform(pose_img).unsqueeze(0).to(device, torch.float16)
|
| 208 |
garm_tensor = tensor_transform(garm_img).unsqueeze(0).to(device, torch.float16)
|
|
|
|
| 227 |
final_result = human_img_orig
|
| 228 |
else:
|
| 229 |
final_result = images[0]
|
| 230 |
+
|
| 231 |
return final_result, mask_gray
|
| 232 |
|
| 233 |
except Exception as e:
|
| 234 |
raise gr.Error(f"Error: {e}")
|
| 235 |
+
|
| 236 |
finally:
|
| 237 |
+
# Memory Cleanup
|
| 238 |
+
try:
|
| 239 |
+
del keypoints, model_parse, mask, pose_img, prompt_embeds, garm_tensor
|
| 240 |
+
except:
|
| 241 |
+
pass
|
| 242 |
gc.collect()
|
| 243 |
torch.cuda.empty_cache()
|
| 244 |
|
| 245 |
+
# ---------------------------------------------------------
|
| 246 |
+
# 5. UI
|
| 247 |
+
# ---------------------------------------------------------
|
| 248 |
with gr.Blocks(theme=gr.themes.Soft(), title="Tryonnix Engine") as demo:
|
| 249 |
+
gr.Markdown("# β¨ Tryonnix 2D Engine (Stable)")
|
|
|
|
|
|
|
|
|
|
| 250 |
with gr.Row():
|
| 251 |
with gr.Column():
|
| 252 |
img_human = gr.Image(label="Human", type="pil", height=400)
|
|
|
|
| 261 |
out = gr.Image(label="Result", type="pil", height=600)
|
| 262 |
mask_out = gr.Image(label="Mask", type="pil", visible=False)
|
| 263 |
|
| 264 |
+
btn.click(fn=start_tryon, inputs=[img_human, img_garm, desc, chk1, chk2, steps, seed], outputs=[out, mask_out], api_name="tryon")
|
| 265 |
|
| 266 |
if __name__ == "__main__":
|
| 267 |
demo.queue(max_size=10).launch()
|