Spaces:
Paused
Paused
Commit Β·
d55fbec
1
Parent(s): 540133c
feat: garment type dropdown with CLIP auto-detect
Browse files
app.py
CHANGED
|
@@ -255,6 +255,74 @@ def classify_garment(img_pil: Image.Image) -> str:
|
|
| 255 |
return label
|
| 256 |
|
| 257 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
# ---------------------------------------------------------------------------
|
| 259 |
# Setup β split into two parts:
|
| 260 |
# setup_env() : clone repos, install packages, download models (no GPU needed)
|
|
@@ -334,7 +402,7 @@ def start_comfyui():
|
|
| 334 |
# Inference
|
| 335 |
# ---------------------------------------------------------------------------
|
| 336 |
@spaces.GPU(duration=180)
|
| 337 |
-
def generate(target_img, clothing_img, progress=gr.Progress(track_tqdm=True)):
|
| 338 |
if target_img is None or clothing_img is None:
|
| 339 |
raise gr.Error("Please upload both images before generating.")
|
| 340 |
|
|
@@ -382,17 +450,39 @@ def generate(target_img, clothing_img, progress=gr.Progress(track_tqdm=True)):
|
|
| 382 |
_prep(target_img).save(f"{COMFYUI_INPUT}/{target_name}")
|
| 383 |
clothing_pil.save(f"{COMFYUI_INPUT}/{clothing_name}")
|
| 384 |
|
| 385 |
-
#
|
| 386 |
-
|
| 387 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
|
| 389 |
-
# Load workflow and inject filenames, seed, and
|
| 390 |
with open("workflow_api.json") as f:
|
| 391 |
workflow = json.load(f)
|
| 392 |
workflow["76"]["inputs"]["image"] = target_name
|
| 393 |
workflow["81"]["inputs"]["image"] = clothing_name
|
| 394 |
workflow["104"]["inputs"]["noise_seed"] = int(time.time() * 1000) % (2 ** 32)
|
| 395 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
|
| 397 |
# If garment is already on a plain background, bypass SAM3 + PersonMaskUltra.
|
| 398 |
# First strip the background with rembg so the garment is on clean white β
|
|
@@ -651,6 +741,14 @@ with gr.Blocks(title="Virtual Try On", theme=gr.themes.Soft(), js=_gate_js) as d
|
|
| 651 |
examples_per_page=12,
|
| 652 |
)
|
| 653 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 654 |
garment_label = gr.Markdown(visible=False)
|
| 655 |
btn = gr.Button("β¨ Generate", variant="primary", size="lg")
|
| 656 |
output = gr.Image(label="Result", height=500)
|
|
@@ -661,7 +759,19 @@ with gr.Blocks(title="Virtual Try On", theme=gr.themes.Soft(), js=_gate_js) as d
|
|
| 661 |
"Each run uses a different random seed so you may get a better result on the next try.*"
|
| 662 |
)
|
| 663 |
|
| 664 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 665 |
gen_model_btn.click(fn=generate_model, inputs=[model_prompt], outputs=[target_input])
|
| 666 |
|
| 667 |
# Unlock is handled entirely client-side via _gate_js β no server call needed.
|
|
|
|
| 255 |
return label
|
| 256 |
|
| 257 |
|
| 258 |
+
_SPECIFIC_GARMENTS = [
|
| 259 |
+
"shirt", "t-shirt", "blouse", "top",
|
| 260 |
+
"cardigan", "sweater", "hoodie",
|
| 261 |
+
"coat", "jacket", "blazer",
|
| 262 |
+
"dress", "jumpsuit", "romper",
|
| 263 |
+
"skirt", "skort",
|
| 264 |
+
"jeans", "pants", "trousers", "shorts",
|
| 265 |
+
]
|
| 266 |
+
|
| 267 |
+
# Maps specific garment β upper/lower/full category (overrides CLIP body-part classifier)
|
| 268 |
+
_GARMENT_CATEGORY = {
|
| 269 |
+
"shirt": "upper", "t-shirt": "upper", "blouse": "upper", "top": "upper",
|
| 270 |
+
"cardigan": "upper", "sweater": "upper", "hoodie": "upper",
|
| 271 |
+
"coat": "upper", "jacket": "upper", "blazer": "upper",
|
| 272 |
+
"dress": "full", "jumpsuit": "full", "romper": "full",
|
| 273 |
+
"skirt": "lower", "skort": "lower",
|
| 274 |
+
"jeans": "lower", "pants": "lower", "trousers": "lower", "shorts": "lower",
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
def detect_specific_garment(img_pil: Image.Image) -> str:
|
| 278 |
+
"""Use CLIP to identify the specific garment type (shirt, skirt, jeans, etc.).
|
| 279 |
+
Runs on CPU β no GPU needed."""
|
| 280 |
+
model, processor = _load_clip()
|
| 281 |
+
texts = [f"a photo of a {g}" for g in _SPECIFIC_GARMENTS]
|
| 282 |
+
inputs = processor(text=texts, images=img_pil, return_tensors="pt", padding=True)
|
| 283 |
+
with torch.no_grad():
|
| 284 |
+
logits = model(**inputs).logits_per_image[0]
|
| 285 |
+
detected = _SPECIFIC_GARMENTS[logits.argmax().item()]
|
| 286 |
+
print(f"Specific garment detected: {detected}")
|
| 287 |
+
return detected
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
_COLOR_CANDIDATES = [
|
| 291 |
+
"black", "white", "grey", "beige", "cream", "brown", "navy blue",
|
| 292 |
+
"red", "orange", "yellow", "green", "teal", "blue", "purple",
|
| 293 |
+
"pink", "coral", "olive", "burgundy", "light blue", "dark green",
|
| 294 |
+
]
|
| 295 |
+
_PATTERN_CANDIDATES = [
|
| 296 |
+
"solid plain color", "stripes", "plaid or checkered", "floral print",
|
| 297 |
+
"polka dots", "geometric pattern", "animal print", "abstract print",
|
| 298 |
+
"camouflage", "color block", "embroidered", "lace",
|
| 299 |
+
]
|
| 300 |
+
|
| 301 |
+
def describe_garment(img_pil: Image.Image) -> str:
|
| 302 |
+
"""Use CLIP to detect the dominant color and pattern of a garment.
|
| 303 |
+
Returns a short description like 'green plaid' or 'white floral print'
|
| 304 |
+
that gets injected into the generation prompt for better adherence."""
|
| 305 |
+
model, processor = _load_clip()
|
| 306 |
+
|
| 307 |
+
def _best(candidates, prompt_template):
|
| 308 |
+
texts = [prompt_template.format(c) for c in candidates]
|
| 309 |
+
inputs = processor(text=texts, images=img_pil, return_tensors="pt", padding=True)
|
| 310 |
+
with torch.no_grad():
|
| 311 |
+
logits = model(**inputs).logits_per_image[0]
|
| 312 |
+
return candidates[logits.argmax().item()]
|
| 313 |
+
|
| 314 |
+
color = _best(_COLOR_CANDIDATES, "a {} colored piece of clothing")
|
| 315 |
+
pattern = _best(_PATTERN_CANDIDATES, "a {} fabric or textile")
|
| 316 |
+
|
| 317 |
+
# Don't say "green solid plain color" β drop pattern when it adds nothing
|
| 318 |
+
if "solid" in pattern or "plain" in pattern:
|
| 319 |
+
desc = color
|
| 320 |
+
else:
|
| 321 |
+
desc = f"{color} {pattern}"
|
| 322 |
+
print(f"Garment description: {desc}")
|
| 323 |
+
return desc
|
| 324 |
+
|
| 325 |
+
|
| 326 |
# ---------------------------------------------------------------------------
|
| 327 |
# Setup β split into two parts:
|
| 328 |
# setup_env() : clone repos, install packages, download models (no GPU needed)
|
|
|
|
| 402 |
# Inference
|
| 403 |
# ---------------------------------------------------------------------------
|
| 404 |
@spaces.GPU(duration=180)
|
| 405 |
+
def generate(target_img, clothing_img, garment_type_override=None, progress=gr.Progress(track_tqdm=True)):
|
| 406 |
if target_img is None or clothing_img is None:
|
| 407 |
raise gr.Error("Please upload both images before generating.")
|
| 408 |
|
|
|
|
| 450 |
_prep(target_img).save(f"{COMFYUI_INPUT}/{target_name}")
|
| 451 |
clothing_pil.save(f"{COMFYUI_INPUT}/{clothing_name}")
|
| 452 |
|
| 453 |
+
# Garment type: use dropdown override if set, else fall back to CLIP body-part classifier
|
| 454 |
+
product_photo = is_product_photo(clothing_pil)
|
| 455 |
+
if garment_type_override and garment_type_override in _GARMENT_CATEGORY:
|
| 456 |
+
specific_type = garment_type_override
|
| 457 |
+
garment_type = _GARMENT_CATEGORY[specific_type]
|
| 458 |
+
print(f"Using user-selected garment type: {specific_type} β {garment_type}")
|
| 459 |
+
else:
|
| 460 |
+
specific_type = detect_specific_garment(clothing_pil)
|
| 461 |
+
garment_type = _GARMENT_CATEGORY.get(specific_type) or classify_garment(clothing_pil)
|
| 462 |
+
print(f"Auto-detected garment type: {specific_type} β {garment_type}")
|
| 463 |
+
|
| 464 |
+
garment_desc = f"{describe_garment(clothing_pil)} {specific_type}" # e.g. "green plaid shirt"
|
| 465 |
|
| 466 |
+
# Load workflow and inject filenames, seed, and description-enriched prompt
|
| 467 |
with open("workflow_api.json") as f:
|
| 468 |
workflow = json.load(f)
|
| 469 |
workflow["76"]["inputs"]["image"] = target_name
|
| 470 |
workflow["81"]["inputs"]["image"] = clothing_name
|
| 471 |
workflow["104"]["inputs"]["noise_seed"] = int(time.time() * 1000) % (2 ** 32)
|
| 472 |
+
|
| 473 |
+
# Inject garment description into prompt so the model knows what to copy
|
| 474 |
+
base_prompt = _PROMPTS[garment_type]
|
| 475 |
+
enriched_prompt = base_prompt.replace(
|
| 476 |
+
"the garment from Picture 2",
|
| 477 |
+
f"the {garment_desc} garment from Picture 2"
|
| 478 |
+
).replace(
|
| 479 |
+
"the cloth from Picture 2",
|
| 480 |
+
f"the {garment_desc} garment from Picture 2"
|
| 481 |
+
).replace(
|
| 482 |
+
"the exact garment shown in Picture 2",
|
| 483 |
+
f"the exact {garment_desc} garment shown in Picture 2"
|
| 484 |
+
)
|
| 485 |
+
workflow["107"]["inputs"]["text"] = enriched_prompt
|
| 486 |
|
| 487 |
# If garment is already on a plain background, bypass SAM3 + PersonMaskUltra.
|
| 488 |
# First strip the background with rembg so the garment is on clean white β
|
|
|
|
| 741 |
examples_per_page=12,
|
| 742 |
)
|
| 743 |
|
| 744 |
+
garment_type_dd = gr.Dropdown(
|
| 745 |
+
choices=_SPECIFIC_GARMENTS,
|
| 746 |
+
value=None,
|
| 747 |
+
label="Garment type (auto-detected β correct if wrong)",
|
| 748 |
+
interactive=True,
|
| 749 |
+
allow_custom_value=False,
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
garment_label = gr.Markdown(visible=False)
|
| 753 |
btn = gr.Button("β¨ Generate", variant="primary", size="lg")
|
| 754 |
output = gr.Image(label="Result", height=500)
|
|
|
|
| 759 |
"Each run uses a different random seed so you may get a better result on the next try.*"
|
| 760 |
)
|
| 761 |
|
| 762 |
+
def _auto_detect_garment_type(clothing_arr):
|
| 763 |
+
if clothing_arr is None:
|
| 764 |
+
return gr.update()
|
| 765 |
+
img_pil = Image.fromarray(clothing_arr)
|
| 766 |
+
return gr.update(value=detect_specific_garment(img_pil))
|
| 767 |
+
|
| 768 |
+
clothing_input.change(
|
| 769 |
+
fn=_auto_detect_garment_type,
|
| 770 |
+
inputs=[clothing_input],
|
| 771 |
+
outputs=[garment_type_dd],
|
| 772 |
+
)
|
| 773 |
+
|
| 774 |
+
btn.click(fn=generate, inputs=[target_input, clothing_input, garment_type_dd], outputs=[output, download, garment_label])
|
| 775 |
gen_model_btn.click(fn=generate_model, inputs=[model_prompt], outputs=[target_input])
|
| 776 |
|
| 777 |
# Unlock is handled entirely client-side via _gate_js β no server call needed.
|