Spaces:
Running
Running
File size: 10,586 Bytes
76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a ffb11e9 76c374a d1f1e83 76c374a f19dcec 76c374a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
import os
import torch
import gradio as gr
from PIL import Image
import numpy as np
from typing import Optional
# Import your custom modules
from load_model import preload_models_from_standard_weights
from utils import to_pil_image
from CatVTON_model import CatVTONPix2PixPipeline
import os
import torch
import urllib.request
def load_models():
try:
print("π Starting model loading process...")
# Check and download model files if missing
ckpt_path = "instruct-pix2pix-00-22000.ckpt"
finetune_path = "maskfree_finetuned_weights.safetensors"
if not os.path.exists(ckpt_path):
print(f"β¬οΈ Downloading {ckpt_path}...")
url = "https://huggingface.co/timbrooks/instruct-pix2pix/resolve/main/instruct-pix2pix-00-22000.ckpt"
urllib.request.urlretrieve(url, ckpt_path)
print("β
Download complete.")
else:
print("β
Checkpoint already exists.")
if not os.path.exists(finetune_path):
print(f"β Finetune weights file not found: {finetune_path}")
return None, None
# Check CUDA availability
cuda_available = torch.cuda.is_available()
print(f"CUDA available: {cuda_available}")
if cuda_available:
print(f"CUDA device: {torch.cuda.get_device_name()}")
free_memory = torch.cuda.get_device_properties(0).total_memory - torch.cuda.memory_allocated(0)
print(f"Available CUDA memory: {free_memory / 1e9:.2f} GB")
device = "cuda" if cuda_available else "cpu"
print("π¦ Loading models from weights...")
models = preload_models_from_standard_weights(
ckpt_path=ckpt_path,
device=device,
finetune_weights_path=finetune_path
)
if not models:
print("β Failed to load models")
return None, None
weight_dtype = torch.float32
print(f"Converting models to {weight_dtype}...")
for model_name, model in models.items():
if model is not None:
try:
model = model.to(dtype=weight_dtype)
models[model_name] = model
print(f"β
{model_name} converted to {weight_dtype}")
except Exception as e:
print(f"β οΈ Could not convert {model_name} to {weight_dtype}: {e}")
print("π§ Initializing pipeline...")
pipeline = CatVTONPix2PixPipeline(
weight_dtype=weight_dtype,
device=device,
skip_safety_check=True,
models=models,
)
print("β
Models and pipeline loaded successfully!")
return models, pipeline
except Exception as e:
print(f"β Error in load_models: {e}")
import traceback
traceback.print_exc()
return None, None
def person_example_fn(image_path):
"""Handle person image examples"""
if image_path:
return image_path
return None
def create_demo(pipeline=None):
"""Create the Gradio interface"""
def submit_function_p2p(
person_image_path: Optional[str],
cloth_image_path: Optional[str],
num_inference_steps: int = 50,
guidance_scale: float = 2.5,
seed: int = 42,
) -> Optional[Image.Image]:
"""Process virtual try-on inference"""
try:
if not person_image_path or not cloth_image_path:
gr.Warning("Please upload both person and cloth images!")
return None
if not os.path.exists(person_image_path):
gr.Error("Person image file not found!")
return None
if not os.path.exists(cloth_image_path):
gr.Error("Cloth image file not found!")
return None
if pipeline is None:
gr.Error("Models not loaded! Please restart the application.")
return None
# Load images
try:
person_image = Image.open(person_image_path).convert('RGB')
cloth_image = Image.open(cloth_image_path).convert('RGB')
except Exception as e:
gr.Error(f"Error loading images: {str(e)}")
return None
# Set up generator
generator = torch.Generator(device=pipeline.device)
if seed != -1:
generator.manual_seed(seed)
print("π Processing virtual try-on...")
# Run inference
with torch.no_grad():
results = pipeline(
person_image,
cloth_image,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
height=512,
width=384,
generator=generator,
)
# Process results
if isinstance(results, list) and len(results) > 0:
result = results[0]
else:
result = results
return result
except Exception as e:
print(f"β Error in submit_function_p2p: {e}")
import traceback
traceback.print_exc()
gr.Error(f"Error during inference: {str(e)}")
return None
# Custom CSS for better styling
css = """
.gradio-container {
max-width: 1200px !important;
}
.image-container {
max-height: 600px;
}
"""
with gr.Blocks(css=css, title="Virtual Try-On") as demo:
gr.HTML("""
<div style="text-align: center; margin-bottom: 20px;">
<h1>π§₯ Virtual Try-On with CatVTON</h1>
<p>Upload a person image and a clothing item to see how they look together!</p>
</div>
""")
with gr.Tab("Mask-Free Virtual Try-On"):
with gr.Row():
with gr.Column(scale=1, min_width=350):
with gr.Row():
image_path_p2p = gr.Image(
type="filepath",
interactive=True,
visible=False,
)
person_image_p2p = gr.Image(
interactive=True,
label="Person Image",
type="filepath",
elem_classes=["image-container"]
)
with gr.Row():
cloth_image_p2p = gr.Image(
interactive=True,
label="Clothing Image",
type="filepath",
elem_classes=["image-container"]
)
submit_p2p = gr.Button("β¨ Generate Try-On", variant="primary", size="lg")
gr.Markdown(
'<center><span style="color: #FF6B6B; font-weight: bold;">β οΈ Click only once and wait for processing!</span></center>'
)
with gr.Accordion("π§ Advanced Options", open=False):
num_inference_steps_p2p = gr.Slider(
label="Inference Steps",
minimum=10,
maximum=100,
step=5,
value=50,
info="More steps = better quality but slower"
)
guidance_scale_p2p = gr.Slider(
label="Guidance Scale",
minimum=0.0,
maximum=7.5,
step=0.5,
value=2.5,
info="Higher values = stronger conditioning"
)
seed_p2p = gr.Slider(
label="Seed",
minimum=-1,
maximum=10000,
step=1,
value=42,
info="Use -1 for random seed"
)
with gr.Column(scale=2, min_width=500):
result_image_p2p = gr.Image(
interactive=False,
label="Result (Person | Clothing | Generated)",
elem_classes=["image-container"]
)
gr.Markdown("""
### π Instructions:
1. Upload a **person image** (front-facing works best)
2. Upload a **clothing item** you want to try on
3. Adjust advanced settings if needed
4. Click "Generate Try-On" and wait
### π‘ Tips:
- Use clear, high-resolution images
- Person should be facing forward
- Clothing items work best when laid flat or on a model
- Try different seeds if you're not satisfied with results
""")
# Event handlers
image_path_p2p.change(
person_example_fn,
inputs=image_path_p2p,
outputs=person_image_p2p
)
submit_p2p.click(
submit_function_p2p,
inputs=[
person_image_p2p,
cloth_image_p2p,
num_inference_steps_p2p,
guidance_scale_p2p,
seed_p2p,
],
outputs=result_image_p2p,
)
# gr.DeepLinkButton()
return demo
def app_gradio():
"""Main application function"""
# Load models at startup
print("π Loading models...")
models, pipeline = load_models()
if not models or not pipeline:
print("β Failed to load models. Please check your model files.")
return
# Create and launch demo
demo = create_demo(pipeline=pipeline)
demo.launch(
share=True
)
if __name__ == "__main__":
app_gradio() |