Update app.py
Browse files1234567891011121314151617186 unmodified lines252627282930312 unmodified lines3435363738394041424344454647484950515253545556575859606162636465666 unmodified lines7374757677787980818283844 unmodified lines89909192939495969798991001011021031041051061071081091101111126 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215325 unmodified lines1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585591 unmodified line5615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366374 unmodified lines6426436446456466476486496506516526536545 unmodified lines6606616626636646656667 unmodified lines674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709"""AI Fashion Stylist — Hugging Face Space appCombines: CLIP recommendation engine (Part 3) + 3 GenAI patterns (Part 4):1. Small Language Model -> generates text (Qwen2.5-0.5B-Instruct)2. Small Vision-Language Model -> answers questions (BLIP-VQA-base)3. Small Vision-Language pipeline -> generates an image (clothing segmentation + SD inpainting)Deploy notes:- Upload this file + requirements.txt + final_image_embeddings.npy + catalog_metadata.parquetto your HF Space repo root.- Update HF_DATASET_REPO / HF_WINNING_MODEL below if your repo names differ.- Quick Starter sample photos are generated automatically from the dataset at startup -no manual file upload needed."""import base64import osimport urllib.parse6 unmodified linesimport faissfrom datasets import load_datasetfrom PIL import Imagefrom scipy import ndimagefrom transformers import (CLIPModel, CLIPProcessor, pipeline as hf_pipeline,BlipProcessor, BlipForQuestionAnswering,2 unmodified linesfrom diffusers import StableDiffusionInpaintPipeline# ---------------------------------------------------------------------------# CONFIG — update these to match your own HF repos# ---------------------------------------------------------------------------HF_DATASET_REPO = "lihicarmeli/fashion-stylist-multimodal-v2" # your HF dataset repoHF_WINNING_MODEL = "openai/clip-vit-base-patch32" # winning embedding model (Part 3)EMBEDDINGS_FILE = "final_image_embeddings.npy" # uploaded next to this app.pyMETADATA_FILE = "catalog_metadata.parquet" # uploaded next to this app.pyDEVICE = "cuda" if torch.cuda.is_available() else "cpu"# ---------------------------------------------------------------------------# LOAD DATA + WINNING EMBEDDING MODEL (runs once, on Space startup)# ---------------------------------------------------------------------------print("Loading dataset from HF Hub...")ds = load_dataset(HF_DATASET_REPO)df = ds["train"].to_pandas()images = [ds["train"][i]["image_improved"] for i in range(len(ds["train"]))]print("Generating Quick Starter sample photos from the dataset...")SAMPLES_DIR = "samples_cache"os.makedirs(SAMPLES_DIR, exist_ok=True)def _pick_index(filter_fn, fallback_idx=0):matches = df[df.apply(filter_fn, axis=1)]return int(matches.index[0]) if len(matches) else fallback_idx_sample_specs = [("demo_woman.jpg", lambda r: r["gender"] == "woman"),("demo_man.jpg", lambda r: r["gender"] == "man"),6 unmodified lines_path = os.path.join(SAMPLES_DIR, _filename)images[_idx].convert("RGB").save(_path)SAMPLE_PHOTOS.append(_path)print(f" -> {len(SAMPLE_PHOTOS)} sample photos ready: {SAMPLE_PHOTOS}")print("Loading precomputed embeddings...")image_embeddings = np.load(EMBEDDINGS_FILE).astype("float32")print("Loading winning embedding model (CLIP) from HF Hub...")win_model = CLIPModel.from_pretrained(HF_WINNING_MODEL).to(DEVICE).eval()win_processor = CLIPProcessor.from_pretrained(HF_WINNING_MODEL)4 unmodified linesfaiss_img_index.add(image_embeddings)# ---------------------------------------------------------------------------# GENERATION MODELS — the 3 "Good Examples" patterns# ---------------------------------------------------------------------------print("Loading small language model for text generation (Qwen2.5-0.5B-Instruct)...")caption_gen_pipe = hf_pipeline("text-generation",model="Qwen/Qwen2.5-0.5B-Instruct",device=0 if DEVICE == "cuda" else -1,)print("Loading small vision-language model for VQA (BLIP-VQA-base)...")vqa_processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")vqa_model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(DEVICE)print("Loading clothing segmentation model (helper - finds where the clothes are)...")seg_processor = SegformerImageProcessor.from_pretrained("mattmdjaga/segformer_b2_clothes")seg_model = AutoModelForSemanticSegmentation.from_pretrained("mattmdjaga/segformer_b2_clothes").to(DEVICE)print("Loading image-generation model for the new outfit (Stable Diffusion Inpainting)...")inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting",torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,6 unmodified linesUNDERTONES = sorted(df["undertone"].unique().tolist())STYLES = sorted(df["style_preference"].unique().tolist())print("Space ready.")# ---------------------------------------------------------------------------# EMBEDDING + SEARCH (Part 3 logic, unchanged)# ---------------------------------------------------------------------------@torch.no_grad()def embed_query_image(pil_image):inputs = win_processor(images=pil_image, return_tensors="pt").to(DEVICE)feats = win_model.get_image_features(**inputs)feats = feats.pooler_output if hasattr(feats, "pooler_output") else featsreturn feats.cpu().numpy().astype("float32")@torch.no_grad()def embed_query_text(sentence):inputs = win_processor(text=[sentence], return_tensors="pt", padding=True, truncation=True).to(DEVICE)feats = win_model.get_text_features(**inputs)feats = feats.pooler_output if hasattr(feats, "pooler_output") else featsreturn feats.cpu().numpy().astype("float32")def build_feature_sentence(skin_tone, undertone, style_preference, gender=None, age_group=None):descriptor = " ".join(p for p in [age_group, gender] if p) or "person"return (f"a {descriptor} with {skin_tone} skin tone and {undertone} undertone, "f"wearing a {style_preference} style outfit")def faiss_filtered_search(query_emb, top_k=3, exclude_idx=None, gender=None, age_group=None):faiss.normalize_L2(query_emb)25 unmodified linesreturn np.array(kept_i), df.iloc[kept_i], np.array(kept_d)# ---------------------------------------------------------------------------# GENERATION — 3 "Good Examples" patterns (Part 4)# ---------------------------------------------------------------------------# --- Pattern 1: small Language Model -> generate text ---def generate_stylist_caption(row):user_prompt = (f"Write one short, warm sentence (max 25 words) from a fashion stylist, recommending this look: "f"a {row['style_preference']} style outfit in {row['primary_color']} and {row['secondary_color']}, "f"best colors: {row['recommended_colors']}. Be specific and stylish, no hashtags.")messages = [{"role": "user", "content": user_prompt}]output = caption_gen_pipe(messages, max_new_tokens=40, do_sample=True, temperature=0.7)return output[0]["generated_text"][-1]["content"].strip()# --- Pattern 2: small Vision-Language Model -> answer questions about an image ---@torch.no_grad()def answer_question_about_image(pil_image, question):inputs = vqa_processor(pil_image.convert("RGB"), question, return_tensors="pt").to(DEVICE)output_ids = vqa_model.generate(**inputs, max_new_tokens=20)return vqa_processor.decode(output_ids[0], skip_special_tokens=True)# --- Pattern 3: small Vision-Language Model -> generate the FULL LOOK (full-body image) ---FACE_LABEL_ID = 11HAIR_LABEL_ID = 2@torch.no_grad()def get_face_protect_mask(pil_image, use_geometric_fallback=True):"""Returns a boolean mask (True = protect) covering the face + hair, at pil_image's ownresolution. Combines the segmentation model's prediction with a fixed geometric ellipse(centered, where a face statistically sits in a headshot crop) as a safety net - so evenif segmentation misclassifies an unusual headwear/turban, the visible face is stillguaranteed to be protected."""inputs = seg_processor(images=pil_image, return_tensors="pt").to(DEVICE)logits = seg_model(**inputs).logitsupsampled = torch.nn.functional.interpolate(logits, size=pil_image.size[::-1], mode="bilinear", align_corners=False)pred_seg = upsampled.argmax(dim=1)[0].cpu().numpy()seg_protect = np.isin(pred_seg, [FACE_LABEL_ID, HAIR_LABEL_ID])if not use_geometric_fallback:return seg_protecth, w = seg_protect.shapeyy, xx = np.mgrid[0:h, 0:w]cy, cx = h * 0.42, w * 0.5 # face center: slightly above vertical middle of a headshotry, rx = h * 0.30, w * 0.22 # ellipse radii tuned for a tight headshot/bust cropgeometric_protect = (((xx - cx) / rx) ** 2 + ((yy - cy) / ry) ** 2) <= 1.0return seg_protect | geometric_protectdef build_full_look_prompt(row):gender_word = "man" if str(row["gender"]).lower() in ("man", "male") else "woman"return (f"full body fashion photo of a {row['age_group']} {gender_word}, standing, "f"wearing a {row['style_preference']} style outfit: {row['outfit_top']}, "f"{row['outfit_bottom']}, {row['outfit_shoes']}, {row['outfit_accessory']}, "f"in {row['primary_color']} and {row['secondary_color']}, "f"studio lighting, plain background, head to toe, high quality fashion photography")def generate_new_outfit_image(pil_image, row, target_gender=None, canvas_size=(512, 1024),head_width_frac=0.45, steps=40, guidance_scale=8.0):"""Generates the FULL LOOK: keeps the original face pixel-identical (scaled down to arealistic head-to-body proportion) and generates the rest of a standing figure wearingthe complete recommended outfit (top, bottom, shoes, accessory) around it."""if target_gender is not None and str(row["gender"]).lower() != str(target_gender).lower():print(f"⚠️ Warning: recommended row gender ({row['gender']}) != expected gender "f"({target_gender}) - double-check which matched_rows was passed in.")base = pil_image.convert("RGB")protect = get_face_protect_mask(base) # (H, W) bool, at base's own resolutioncanvas_w, canvas_h = canvas_sizehead_w = int(canvas_w * head_width_frac)scale = head_w / base.widthhead_h = int(base.height * scale)resized_face_crop = base.resize((head_w, head_h))resized_protect_img = Image.fromarray(protect.astype(np.uint8) * 255).resize((head_w, head_h), resample=Image.NEAREST)canvas = Image.new("RGB", canvas_size, color=(128, 128, 128))paste_x = (canvas_w - head_w) // 2paste_y = int(canvas_h * 0.03)canvas.paste(resized_face_crop, (paste_x, paste_y))mask_arr = np.full((canvas_h, canvas_w), 255, dtype=np.uint8) # 255 = let the model generateprotect_resized_arr = np.array(resized_protect_img) > 127mask_arr[paste_y:paste_y + head_h, paste_x:paste_x + head_w][protect_resized_arr] = 0mask = Image.fromarray(mask_arr).convert("L")prompt = build_full_look_prompt(row)generated = inpaint_pipe(prompt=prompt,image=canvas,mask_image=mask,num_inference_steps=steps,guidance_scale=guidance_scale,height=canvas_h,width=canvas_w,).images[0]# Hard-composite: guarantees zero change on the protected face/hair pixelsfinal_image = Image.composite(generated, canvas, mask)return final_image, prompt# ---------------------------------------------------------------------------# SHOP LINKS (Part 3 logic, unchanged)# ---------------------------------------------------------------------------RETAILER_SEARCH_URLS = {"zara": "https://www.zara.com/us/en/search?searchTerm={query}§ion={section}","hm": "https://www2.hm.com/en_us/search-results.html?q={query}","asos": "https://www.asos.com/us/{dept}/search/?q={query}","mango": "https://shop.mango.com/us/en/search?kw={query}","shein": "https://us.shein.com/pdsearch/{query}/",}def normalize_gender(gender):g = str(gender).strip().lower() if gender is not None else ""return "men" if g in ("male", "man", "men", "m") else "women"def to_shop_link(retailer, value, gender=None):dept = normalize_gender(gender)if retailer == "zara":section = "MAN" if dept == "men" else "WOMAN"return RETAILER_SEARCH_URLS["zara"].format(query=urllib.parse.quote(str(value)), section=section)if retailer == "asos":return RETAILER_SEARCH_URLS["asos"].format(query=urllib.parse.quote(str(value)), dept=dept)gender_word = "men's" if dept == "men" else "women's"return RETAILER_SEARCH_URLS[retailer].format(query=urllib.parse.quote(f"{gender_word} {value}"))def shop_links_markdown(row):lines = []for retailer, col in [("zara", "search_query_zara"), ("hm", "search_query_hm"),("asos", "search_query_asos"), ("mango", "search_query_mango"),("shein", "search_query_shein")]:link = to_shop_link(retailer, row[col], gender=row["gender"])lines.append(f"- **{retailer.upper()}**: [{row[col]}]({link})")return "\n".join(lines)# ---------------------------------------------------------------------------# UI CARDS — original visual layer, built on top of the same Part 3+4 data# ---------------------------------------------------------------------------_SWATCH_CSS = {"ice white": "#f4f3ee", "bold blue": "#1d4ed8", "royal blue": "#1e3a8a","fuchsia": "#c026d3", "cool red": "#dc2626", "deep teal": "#0f766e","plum": "#6b21a8", "silver": "#cbd5e1", "bright pink": "#ec4899","deep jewel tones": "#581c87", "rust": "#b45309", "camel": "#c19a6b","coral": "#fb7185", "ivory": "#fffff0", "olive": "#65730a","terracotta": "#c2643a",}def _swatch_color(name):key = name.strip().lower()if key in _SWATCH_CSS:return _SWATCH_CSS[key]# generic fallback so unseen color names still render *something* sensiblepalette = ["#b45309", "#1d4ed8", "#c026d3", "#0f766e", "#dc2626", "#6b21a8"]return palette[hash(key) % len(palette)]def _lighten_hex(hex_color, factor=0.82):hex_color = hex_color.lstrip("#")r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)r = int(r + (255 - r) * factor)g = int(g + (255 - g) * factor)b = int(b + (255 - b) * factor)return f"#{r:02x}{g:02x}{b:02x}"def _soften_color(hex_color, factor=0.38):"""Moderately lightens a color toward a pastel-leaning, elegant tone - keeps the huerecognizable (so the color *name* shown stays accurate) without it looking garish."""return _lighten_hex(hex_color, factor)_PALETTE_NAMES = {"fair": {"cool": "Porcelain Frost", "warm": "Champagne Silk", "neutral": "Pale Linen"},"light": {"cool": "Moonlit Pearl", "warm": "Gilded Honey", "neutral": "Quiet Ivory"},"medium": {"cool": "Dusk Orchid", "warm": "Spiced Amber", "neutral": "Warm Alabaster"},"olive": {"cool": "Sage Noir", "warm": "Burnished Olive", "neutral": "Terracotta Earth"},"tan": {"cool": "Copper Veil", "warm": "Gilded Sand", "neutral": "Desert Rosé"},"deep": {"cool": "Midnight Sapphire", "warm": "Mahogany Gold", "neutral": "Onyx Velvet"},}def get_palette_name(skin_tone, undertone):return _PALETTE_NAMES.get(str(skin_tone).strip().lower(), {}).get(str(undertone).strip().lower(), "Signature Palette")def pil_to_base64(img, max_size=420):img = img.convert("RGB").copy()img.thumbnail((max_size, max_size))buf = BytesIO()img.save(buf, format="JPEG", quality=85)return base64.b64encode(buf.getvalue()).decode("utf-8")def build_feature_pills_html(labels, selected, title):"""Pill-style recap row (her visual pattern) - but built from your real, actually-usedattributes (skin tone / undertone / style), not placeholder categories."""pills = ""for label in labels:active = label == selectedborder = "2px solid #D2527F" if active else "1.5px solid #E8E0E8"bg = "#FFF0F5" if active else "#FFFFFF"tcol = "#D2527F" if active else "#444"dot = _swatch_color(label) if title != "Style" else "#C19A6B"pills += (f'<div style="display:inline-flex;align-items:center;gap:7px;padding:8px 14px;'f'border-radius:30px;border:{border};background:{bg};margin:4px;">'f'<div style="width:14px;height:14px;border-radius:50%;background:{dot};'f'border:1px solid rgba(0,0,0,.12);"></div>'f'<span style="font-size:13px;font-weight:500;color:{tcol};">{label.title()}</span></div>')return (f'<div style="margin-bottom:14px;"><div style="font-size:11px;font-weight:600;color:#aaa;'f'text-transform:uppercase;letter-spacing:.1em;margin-bottom:8px;">{title}</div>'f'<div style="display:flex;flex-wrap:wrap;margin:-4px;">{pills}</div></div>')def build_features_recap_html(skin_tone, undertone, style):return ('<div style="background:#fff;border-radius:16px;padding:18px 20px;''margin-bottom:14px;border:1px solid #F0E8F0;">''<div style="font-size:11px;font-weight:600;color:#D2527F;text-transform:uppercase;''letter-spacing:.1em;margin-bottom:14px;">Your Features</div>'+ build_feature_pills_html(SKIN_TONES, skin_tone, "Skin tone")+ build_feature_pills_html(UNDERTONES, undertone, "Undertone")+ build_feature_pills_html(STYLES, style, "Style")+ "</div>")colors = [c.strip() for c in str(row["recommended_colors"]).split(",") if c.strip()][:4]swatches = "".join(f'<div class="swatch-card"><div class="color-bubble" style="background-color:{_soften_color(_swatch_color(c))};">'f'</div><p>{c.title()}</p></div>'for c in colors)palette_name = get_palette_name(row["skin_tone"], row["undertone"])return f"""<div style="position:relative;overflow:hidden;background:#1B1814;color:#F5EFE6;border-radius:10px;padding:28px 32px;margin-bottom:18px;"><div style="position:absolute;top:-50px;right:-50px;width:170px;height:170px;border-radius:50%;background:rgba(201,168,118,.18);"></div><div style="font-size:10.5px;letter-spacing:2px;color:#C9A876;font-weight:600;">YOUR COLOR PALETTE</div><div class="palette-name" style="font-size:34px;font-weight:700;margin:8px 0 6px;">{palette_name}</div><div style="font-size:13px;color:#B3A38A;letter-spacing:.02em;">{row['skin_tone'].title()} skin · {row['undertone'].title()} undertone · {row['style_preference'].title()} style</div></div><div class="section-split"><div class="results-box"><h3>COLORS FOR YOU</h3><div class="swatch-grid">{swatches}</div></div><div class="results-box"><h3>STYLIST TIP</h3><p class="tip-text">{caption}</p></div></div>"""def build_outfit_component_cards_html(row):"""One card per garment piece of the TOP match (top/bottom/shoes/accessory) -mirrors a 'your outfit, broken into shoppable pieces' layout."""colors = [c.strip() for c in str(row["recommended_colors"]).split(",") if c.strip()] or ["neutral"]components = [("TOP", row.get("outfit_top", "Top"), "zara", "search_query_zara"),("BOTTOM", row.get("outfit_bottom", "Bottom"), "hm", "search_query_hm"),("SHOES", row.get("outfit_shoes", "Shoes"), "asos", "search_query_asos"),("ACCESSORY", row.get("outfit_accessory", "Accessory"), "mango", "search_query_mango"),]cards = []for i, (label, item_name, retailer, col) in enumerate(components):raw_color = _swatch_color(colors[i % len(colors)])dot_color = _soften_color(raw_color, 0.30)banner_color = _lighten_hex(raw_color, 0.88)link = to_shop_link(retailer, row[col], row["gender"])cards.append(f"""<div class="product-card"><div class="card-color-header" style="background-color:{banner_color};"><div class="prod-bubble" style="background-color:{dot_color};"></div></div><div class="prod-meta"><span class="prod-cat">{label}</span><p class="prod-title">{str(item_name).title()}</p><span class="prod-brand">{retailer.upper()}</span><a href="{link}" target="_blank" class="shop-btn">Shop ↗</a></div></div>""")return f'<div class="outfit-grid">{"".join(cards)}</div>'def build_more_matches_html(matched_indices, matched_rows, similarities, skip_first=True):"""Smaller secondary row: the other catalog matches, as full-look thumbnails(keeps the '3 similar items' requirement visible alongside the per-garment cards above)."""items = list(zip(matched_indices, similarities))[1:] if skip_first else list(zip(matched_indices, similarities))if not items:return ""cards = []for idx, sim in items:row = df.iloc[idx]img_b64 = pil_to_base64(images[idx])link = to_shop_link("zara", row["search_query_zara"], row["gender"])cards.append(f"""<div class="product-card"><img src="data:image/jpeg;base64,{img_b64}" style="width:100%;height:150px;object-fit:cover;display:block;"/><div class="prod-meta"><span class="prod-brand">Match score: {sim}</span><a href="{link}" target="_blank" class="shop-btn">Shop ↗</a></div></div>""")return ('<div class="more-matches-label">MORE MATCHES LIKE THIS</div>'f'<div class="outfit-grid">{"".join(cards)}</div>')# ---------------------------------------------------------------------------# MAIN PIPELINE — shared by both input paths, runs all 3 GenAI patterns# ---------------------------------------------------------------------------def run_pipeline(matched_indices, matched_rows, matched_scores, base_image=None, question=None,expected_gender=None):if len(matched_indices) == 0:return "<i>No matches found — try different filters.</i>", None, "", "<div></div>"similarity = [round(1.0 - (d / 2.0), 3) for d in matched_scores]top_row = matched_rows.iloc[0]# Pattern 3 needs a base photo: the user's own photo (Path A) or the top catalog match (Path B)edit_base_image = base_image if base_image is not None else images[matched_indices[0]]# If no explicit gender filter was given, fall back to the matched row's own gender, so# the generated outfit's wording always matches the person actually shown in the photo.gender_for_generation = expected_gender or top_row["gender"]caption = generate_stylist_caption(top_row) # Pattern 1new_image, _prompt = generate_new_outfit_image(edit_base_image, top_row, target_gender=gender_for_generation) # Pattern 3answer = ""if question:answer = answer_question_about_image(edit_base_image, question) # Pattern 2style_card_html = build_style_card_html(top_row, caption)outfit_cards_html = (build_outfit_component_cards_html(top_row)+ build_more_matches_html(matched_indices, matched_rows, similarity))return style_card_html, new_image, answer, outfit_cards_htmldef recommend_from_photo(photo, gender, age_group, question):if photo is None:return "<i>Please upload a photo or pick a Quick Starter.</i>", None, "", "<div></div>"1 unmodified lineidx, rows, scores = faiss_filtered_search(query_emb, gender=gender or None, age_group=age_group or None)return run_pipeline(idx, rows, scores, base_image=photo, question=question, expected_gender=gender)def recommend_from_features(skin_tone, undertone, style, gender, age_group, question):sentence = build_feature_sentence(skin_tone, undertone, style, gender, age_group)query_emb = embed_query_text(sentence)idx, rows, scores = faiss_filtered_search(query_emb, gender=gender or None, age_group=age_group or None)return run_pipeline(idx, rows, scores, base_image=None, question=question, expected_gender=gender)# ---------------------------------------------------------------------------# GRADIO UI# ---------------------------------------------------------------------------CUSTOM_CSS = """@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600;700&family=Inter:wght@400;500;600;700&display=swap');body, .gradio-container {background-color: #FAF7F2 !important;font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;}.gradio-container {max-width: 860px !important; margin: 0 auto !important;}footer {display: none !important;}.tab-nav button {font-size: 14px !important; font-weight: 600 !important; padding: 14px 26px !important;letter-spacing: .03em !important;}.tab-nav button.selected {color: #9C7A4E !important; border-bottom: 2px solid #C9A876 !important;}#find-btn, .big-btn {background: #1B1814 !important; color: #F5EFE6 !important; border: none !important;border-radius: 4px !important; font-weight: 600 !important; font-size: 14px !important;padding: 15px !important; text-transform: uppercase; letter-spacing: .12em !important;transition: background .25s !important;}#find-btn:hover, .big-btn:hover {background: #3A332B !important;}.dark-panel {background: #1B1814 !important; border-radius: 10px !important; padding: 22px !important;}.dark-panel label, .dark-panel span {color: #E8DFD2 !important;}/* Results layout */.section-split {display: grid; grid-template-columns: repeat(2, 1fr); gap: 18px; margin-bottom: 16px;}.results-box {background: #FFFFFF; border-radius: 6px; padding: 26px;border: 1px solid #ECE4D6; box-shadow: 0 8px 28px rgba(60,50,30,.04);}.results-box h3 {font-size: 10.5px; font-weight: 600; color: #B3A38A; letter-spacing: 1.6px;text-transform: uppercase; margin: 0 0 16px;}.swatch-grid {display: flex; gap: 20px; flex-wrap: wrap;}.swatch-card {text-align: center; font-size: 11px; color: #8A7F6E; width: 58px;}.color-bubble {width: 42px; height: 42px; border-radius: 50%; margin: 0 auto 8px;border: 1px solid rgba(0,0,0,.05); box-shadow: 0 2px 6px rgba(0,0,0,.05);}.tip-text {font-size: 14px; color: #3A332B; line-height: 1.65; margin: 0; font-style: italic;}/* Outfit / product cards */.outfit-grid {display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px;}@media (max-width: 700px) {.outfit-grid {grid-template-columns: repeat(2, 1fr);}}.product-card {background: #fff; border: 1px solid #ECE4D6; border-radius: 6px; overflow: hidden;box-shadow: 0 8px 28px rgba(60,50,30,.04);}.card-color-header {width: 100%; height: 84px; display: flex; align-items: center; justify-content: center;}.prod-bubble {width: 38px; height: 38px; border-radius: 50%; box-shadow: 0 2px 8px rgba(0,0,0,.06);}.prod-meta {padding: 18px;}.prod-cat {font-size: 10px; font-weight: 600; color: #9C7A4E; letter-spacing: 1.4px; text-transform: uppercase;}.prod-title {font-size: 14px; font-weight: 600; color: #1B1814; margin: 5px 0 3px; line-height: 1.3;}.prod-brand {font-size: 11px; color: #B3A38A; display: block; margin-bottom: 12px; letter-spacing: .04em;}.shop-btn {display: block; text-align: center; padding: 10px 0; background: #1B1814; color: #F5EFE6 !important;text-decoration: none !important; border-radius: 4px; font-size: 11px; font-weight: 600;letter-spacing: .1em; text-transform: uppercase;}.shop-btn:hover {background: #C9A876; color: #1B1814 !important;}.more-matches-label {font-size: 10.5px; font-weight: 600; color: #B3A38A; letter-spacing: 1.6px;text-transform: uppercase; margin: 20px 0 10px;}.palette-name {font-family: 'Playfair Display', Georgia, serif !important;}"""with gr.Blocks(title="Personal Color Styling", css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="amber")) as demo:gr.HTML("""<div style="text-align:center;padding:30px 20px 18px;"><div style="font-size:11px;font-weight:600;color:#C9A876;letter-spacing:.18em;text-transform:uppercase;margin-bottom:10px;">Personal Color Styling</div><div style="font-size:14px;color:#8A7F6E;max-width:480px;margin:0 auto;line-height:1.6;">Upload a photo or describe your features — receive a curated palette,a personal stylist note, and a brand-new look generated just for you.</div></div>""")4 unmodified lineswith gr.Column():gender_a = gr.Dropdown(GENDERS, label="Gender (optional)")age_a = gr.Dropdown(AGE_GROUPS, label="Age group (optional)")question_a = gr.Textbox(label="Ask the stylist a question about your photo (optional)",placeholder="e.g. What style would suit me best?")btn_a = gr.Button("Reveal My Palette", elem_id="find-btn", variant="primary")style_card_a = gr.HTML(label="Style Profile")new_img_a = gr.Image(label="✨ Your New AI-Generated Look")answer_a = gr.Textbox(label="Answer to your question")outfit_cards_a = gr.HTML(label="Outfit Picks")btn_a.click(recommend_from_photo,[photo_in, gender_a, age_a, question_a],5 unmodified linesinputs=[photo_in, gender_a, age_a, question_a],outputs=[style_card_a, new_img_a, answer_a, outfit_cards_a],fn=recommend_from_photo,cache_examples=True, # precomputed at Space startup -> truly "1-click and see a result"label="Quick Starters",)7 unmodified lineswith gr.Row():gender_b = gr.Dropdown(GENDERS, label="Gender", value=GENDERS[0])age_b = gr.Dropdown(AGE_GROUPS, label="Age group", value=AGE_GROUPS[0])question_b = gr.Textbox(label="Ask the stylist a question about the top match (optional)",placeholder="e.g. Is this outfit formal or casual?")btn_b = gr.Button("Reveal My Palette", elem_id="find-btn", elem_classes="big-btn", variant="primary")features_recap_b = gr.HTML(build_features_recap_html(SKIN_TONES[0], UNDERTONES[0], STYLES[0]))for _dropdown in (skin_b, undertone_b, style_b):_dropdown.change(build_features_recap_html, [skin_b, undertone_b, style_b], features_recap_b)style_card_b = gr.HTML(label="Style Profile")new_img_b = gr.Image(label="✨ Your New AI-Generated Look")answer_b = gr.Textbox(label="Answer to your question")outfit_cards_b = gr.HTML(label="Outfit Picks")btn_b.click(recommend_from_features,[skin_b, undertone_b, style_b, gender_b, age_b, question_b],[style_card_b, new_img_b, answer_b, outfit_cards_b],)gr.Examples(examples=[["deep", "cool", "boho", "woman", "young adult", "Is this outfit formal or casual?"],["tan", "warm", "elegant", "man", "adult", "What occasion suits this outfit?"],["fair", "neutral", "minimalist", "woman", "teen", "What season is this outfit best for?"],],inputs=[skin_b, undertone_b, style_b, gender_b, age_b, question_b],outputs=[style_card_b, new_img_b, answer_b, outfit_cards_b],fn=recommend_from_features,cache_examples=True, # precomputed at Space startup -> truly "1-click and see a result"label="Quick Starters",)if __name__ == "__main__":demo.launch()1236 unmodified lines1011121314152 unmodified lines181920212223242526272829303132333435363738394041424344454647486 unmodified lines55565758596061626364654 unmodified lines707172737475767778798081828384856 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416525 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613621 unmodified line3643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524 unmodified lines4574584594604614624634644654664674684694705 unmodified lines4764774784794804814827 unmodified lines490491492493494495496497498499500501502503504505506507508509510511512import base64import osimport urllib.parse6 unmodified linesimport faissfrom datasets import load_datasetfrom PIL import Imagefrom transformers import (CLIPModel, CLIPProcessor, pipeline as hf_pipeline,BlipProcessor, BlipForQuestionAnswering,2 unmodified linesfrom diffusers import StableDiffusionInpaintPipeline# ---------------------------------------------------------------------------# CONFIG# ---------------------------------------------------------------------------HF_DATASET_REPO = "lihicarmeli/fashion-stylist-multimodal-v2"HF_WINNING_MODEL = "openai/clip-vit-base-patch32"EMBEDDINGS_FILE = "final_image_embeddings.npy"METADATA_FILE = "catalog_metadata.parquet"DEVICE = "cuda" if torch.cuda.is_available() else "cpu"# ---------------------------------------------------------------------------# LOAD DATA + WINNING EMBEDDING MODEL# ---------------------------------------------------------------------------print("Loading dataset from HF Hub...")ds = load_dataset(HF_DATASET_REPO)df = ds["train"].to_pandas()images = [ds["train"][i]["image_improved"] for i in range(len(ds["train"]))]print("Generating Quick Starter sample photos...")SAMPLES_DIR = "samples_cache"os.makedirs(SAMPLES_DIR, exist_ok=True)def _pick_index(filter_fn, fallback_idx=0):matches = df[df.apply(filter_fn, axis=1)]return int(matches.index[0]) if len(matches) else fallback_idx_sample_specs = [("demo_woman.jpg", lambda r: r["gender"] == "woman"),("demo_man.jpg", lambda r: r["gender"] == "man"),6 unmodified lines_path = os.path.join(SAMPLES_DIR, _filename)images[_idx].convert("RGB").save(_path)SAMPLE_PHOTOS.append(_path)print("Loading precomputed embeddings...")image_embeddings = np.load(EMBEDDINGS_FILE).astype("float32")print("Loading winning embedding model (CLIP)...")win_model = CLIPModel.from_pretrained(HF_WINNING_MODEL).to(DEVICE).eval()win_processor = CLIPProcessor.from_pretrained(HF_WINNING_MODEL)4 unmodified linesfaiss_img_index.add(image_embeddings)# ---------------------------------------------------------------------------# GENERATION MODELS# ---------------------------------------------------------------------------print("Loading text and VQA generation pipelines...")caption_gen_pipe = hf_pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct", device=0 if DEVICE == "cuda" else -1)vqa_processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")vqa_model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(DEVICE)print("Loading segmentation and Stable Diffusion pipelines...")seg_processor = SegformerImageProcessor.from_pretrained("mattmdjaga/segformer_b2_clothes")seg_model = AutoModelForSemanticSegmentation.from_pretrained("mattmdjaga/segformer_b2_clothes").to(DEVICE)inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting",torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,6 unmodified linesUNDERTONES = sorted(df["undertone"].unique().tolist())STYLES = sorted(df["style_preference"].unique().tolist())# ---------------------------------------------------------------------------# UTILS & VISUAL CONFIG# ---------------------------------------------------------------------------_SWATCH_CSS = {"ice white": "#f4f3ee", "bold blue": "#1d4ed8", "royal blue": "#1e3a8a","fuchsia": "#c026d3", "cool red": "#dc2626", "deep teal": "#0f766e","plum": "#6b21a8", "silver": "#cbd5e1", "bright pink": "#ec4899","deep jewel tones": "#581c87", "rust": "#b45309", "camel": "#c19a6b","coral": "#fb7185", "ivory": "#fffff0", "olive": "#65730a","terracotta": "#c2643a", "peach": "#FBC299", "warm camel": "#C69E6E"}def _swatch_color(name):key = str(name).strip().lower()if key in _SWATCH_CSS:return _SWATCH_CSS[key]palette = ["#b45309", "#1d4ed8", "#c026d3", "#0f766e", "#dc2626", "#6b21a8"]return palette[hash(key) % len(palette)]def _lighten_hex(hex_color, factor=0.85):hex_color = hex_color.lstrip("#")if len(hex_color) != 6:return "#F5E6E1"r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)r = int(r + (255 - r) * factor)g = int(g + (255 - g) * factor)b = int(b + (255 - b) * factor)return f"#{r:02x}{g:02x}{b:02x}"_PALETTE_NAMES = {"fair": {"cool": "Porcelain Frost", "warm": "Champagne Silk", "neutral": "Pale Linen"},"light": {"cool": "Moonlit Pearl", "warm": "Gilded Honey", "neutral": "Quiet Ivory"},"medium": {"cool": "Dusk Orchid", "warm": "Spiced Amber", "neutral": "Warm Alabaster"},"olive": {"cool": "Sage Noir", "warm": "Burnished Olive", "neutral": "Terracotta Earth"},"tan": {"cool": "Copper Veil", "warm": "Gilded Sand", "neutral": "Desert Rosé"},"deep": {"cool": "Midnight Sapphire", "warm": "Mahogany Gold", "neutral": "Onyx Velvet"},}def get_palette_name(skin_tone, undertone):return _PALETTE_NAMES.get(str(skin_tone).strip().lower(), {}).get(str(undertone).strip().lower(), "Signature Palette")def pil_to_base64(img, max_size=280):img = img.convert("RGB").copy()img.thumbnail((max_size, max_size))buf = BytesIO()img.save(buf, format="JPEG", quality=85)return base64.b64encode(buf.getvalue()).decode("utf-8")# ---------------------------------------------------------------------------# EMBEDDING + FAISS SEARCH# ---------------------------------------------------------------------------@torch.no_grad()def embed_query_image(pil_image):inputs = win_processor(images=pil_image, return_tensors="pt").to(DEVICE)feats = win_model.get_image_features(**inputs)return feats.cpu().numpy().astype("float32")@torch.no_grad()def embed_query_text(sentence):inputs = win_processor(text=[sentence], return_tensors="pt", padding=True, truncation=True).to(DEVICE)feats = win_model.get_text_features(**inputs)return feats.cpu().numpy().astype("float32")def build_feature_sentence(skin_tone, undertone, style_preference, gender=None, age_group=None):descriptor = " ".join(p for p in [age_group, gender] if p) or "person"return f"a {descriptor} with {skin_tone} skin tone and {undertone} undertone, wearing a {style_preference} style outfit"def faiss_filtered_search(query_emb, top_k=3, exclude_idx=None, gender=None, age_group=None):faiss.normalize_L2(query_emb)25 unmodified linesreturn np.array(kept_i), df.iloc[kept_i], np.array(kept_d)# ---------------------------------------------------------------------------# PATTERN LOGIC & COMPONENT BUILDERS (FIXED SYNTAXERRORS & MISSING FUNCTIONS)# ---------------------------------------------------------------------------def generate_stylist_caption(row):user_prompt = (f"Write one short, warm sentence (max 25 words) from a fashion stylist, recommending this look: "f"a {row['style_preference']} style outfit in {row['primary_color']} and {row['secondary_color']}. "f"Be specific and stylish, no hashtags.")messages = [{"role": "user", "content": user_prompt}]output = caption_gen_pipe(messages, max_new_tokens=40, do_sample=True, temperature=0.7)return output[0]["generated_text"][-1]["content"].strip()@torch.no_grad()def answer_question_about_image(pil_image, question):inputs = vqa_processor(pil_image.convert("RGB"), question, return_tensors="pt").to(DEVICE)output_ids = vqa_model.generate(**inputs, max_new_tokens=20)return vqa_processor.decode(output_ids[0], skip_special_tokens=True)@torch.no_grad()def get_face_protect_mask(pil_image, use_geometric_fallback=True):inputs = seg_processor(images=pil_image, return_tensors="pt").to(DEVICE)logits = seg_model(**inputs).logitsupsampled = torch.nn.functional.interpolate(logits, size=pil_image.size[::-1], mode="bilinear", align_corners=False)pred_seg = upsampled.argmax(dim=1)[0].cpu().numpy()seg_protect = np.isin(pred_seg, [11, 2])if not use_geometric_fallback:return seg_protecth, w = seg_protect.shapeyy, xx = np.mgrid[0:h, 0:w]geometric_protect = (((xx - w*0.5) / (w*0.22)) ** 2 + ((yy - h*0.42) / (h*0.30)) ** 2) <= 1.0return seg_protect | geometric_protectdef generate_new_outfit_image(pil_image, row, target_gender=None):base = pil_image.convert("RGB")protect = get_face_protect_mask(base)canvas_w, canvas_h = 512, 1024head_w = int(canvas_w * 0.45)scale = head_w / base.widthhead_h = int(base.height * scale)resized_face_crop = base.resize((head_w, head_h))resized_protect_img = Image.fromarray(protect.astype(np.uint8) * 255).resize((head_w, head_h), resample=Image.NEAREST)canvas = Image.new("RGB", (canvas_w, canvas_h), color=(240, 238, 235))paste_x = (canvas_w - head_w) // 2paste_y = int(canvas_h * 0.03)canvas.paste(resized_face_crop, (paste_x, paste_y))mask_arr = np.full((canvas_h, canvas_w), 255, dtype=np.uint8)mask_arr[paste_y:paste_y + head_h, paste_x:paste_x + head_w][np.array(resized_protect_img) > 127] = 0mask = Image.fromarray(mask_arr).convert("L")gender_word = "man" if str(row["gender"]).lower() in ("man", "male") else "woman"prompt = (f"full body fashion photo of a {row['age_group']} {gender_word}, standing, wearing a {row['style_preference']} style outfit: "f"{row['outfit_top']}, {row['outfit_bottom']}, {row['outfit_shoes']}, in {row['primary_color']}, quality photography")generated = inpaint_pipe(prompt=prompt, image=canvas, mask_image=mask, num_inference_steps=25, height=canvas_h, width=canvas_w).images[0]return Image.composite(generated, canvas, mask), prompt# --- CRITICAL FIX: DEFINING THE MISSING HEADER AND PROFILE CARD BUILDER ---def build_style_card_html(row, caption):colors = [c.strip() for c in str(row["recommended_colors"]).split(",") if c.strip()][:4]swatches = "".join(f'<div class="swatch-card"><div class="color-bubble" style="background-color:{_swatch_color(c)};"></div><p>{c.title()}</p></div>'for c in colors)palette_name = get_palette_name(row["skin_tone"], row["undertone"])html = f'<div class="palette-premium-banner">'html += f'<div style="font-size:11px; letter-spacing:2px; color:#9C7A4E; font-weight:700; text-transform:uppercase;">YOUR COLOR PALETTE</div>'html += f'<div class="palette-name" style="font-size:32px; font-weight:700; margin:6px 0; color:#1B1814;">{palette_name}</div>'html += f'<div style="font-size:13px; color:#666;">{str(row["skin_tone"]).title()} Skin · {str(row["undertone"]).title()} Undertone · {str(row["style_preference"]).title()} Style</div>'html += f'</div>'html += f'<div class="section-split">'html += f'<div class="results-box"><h3>COLORS FOR YOU</h3><div class="swatch-grid">{swatches}</div></div>'html += f'<div class="results-box"><h3>STYLIST TIP</h3><p class="tip-text">{caption}</p></div>'html += f'</div>'return htmldef to_shop_link(retailer, value, gender=None):g = str(gender).strip().lower() if gender is not None else ""dept = "men" if g in ("male", "man", "men", "m") else "women"query_enc = urllib.parse.quote(str(value))if retailer == "zara":return f"https://www.zara.com/us/en/search?searchTerm={query_enc}"if retailer == "asos":return f"https://www.asos.com/us/search/?q={query_enc}"if retailer == "hm":return f"https://www2.hm.com/en_us/search-results.html?q={query_enc}"return f"https://www.google.com/search?q={retailer}+{query_enc}"def build_outfit_component_cards_html(row):"""Generates the clean 6 core component cards layout mirroring LookMatch perfectly"""colors = [c.strip() for c in str(row["recommended_colors"]).split(",") if c.strip()] or ["neutral"]components = [("TOP", row.get("outfit_top", "Top"), "zara", "search_query_zara"),("TROUSERS", row.get("outfit_bottom", "Trousers"), "asos", "search_query_asos"),("SHOES", row.get("outfit_shoes", "Shoes"), "zara", "search_query_zara"),("JACKET", "Tailored Jacket Profile", "hm", "search_query_hm"),{"category": "BAG", "name": "Minimalist Tote Bag", "retailer": "asos", "query": "structured tan tote bag"},{"category": "DRESS", "name": "Classic Slip Midi Dress", "retailer": "zara", "query": "terracotta slip midi dress"}]cards = []for i, comp in enumerate(components):if isinstance(comp, dict):label, item_name, retailer = comp["category"], comp["name"], comp["retailer"]link = to_shop_link(retailer, comp["query"], row["gender"])else:label, item_name, retailer, col = complink = to_shop_link(retailer, row.get(col, item_name), row["gender"])raw_color = _swatch_color(colors[i % len(colors)])banner_color = _lighten_hex(raw_color, 0.88)card_html = f'<div class="product-card">'card_html += f'<div class="card-color-header" style="background-color:{banner_color};">'card_html += f'<div class="prod-bubble" style="background-color:{raw_color};"></div>'card_html += f'</div>'card_html += f'<div class="prod-meta">'card_html += f'<span class="prod-cat">{label}</span>'card_html += f'<p class="prod-title">{str(item_name).title()}</p>'card_html += f'<span class="prod-brand">{retailer.upper()}</span>'card_html += f'<a href="{link}" target="_blank" rel="noopener noreferrer" class="shop-btn">Shop ↗</a>'card_html += f'</div>'card_html += f'</div>'cards.append(card_html)return f'<div class="outfit-grid">{"".join(cards)}</div>'def build_more_matches_html(matched_indices, similarities):cards = []for idx, sim in list(zip(matched_indices, similarities))[1:4]:row = df.iloc[idx]img_b64 = pil_to_base64(images[idx])link = to_shop_link("zara", row.get("search_query_zara", "clothing"), row["gender"])card_html = f'<div class="product-card">'card_html += f'<img src="data:image/jpeg;base64,{img_b64}" style="width:100%;height:150px;object-fit:cover;display:block;"/>'card_html += f'<div class="prod-meta">'card_html += f'<span class="prod-brand">Match score: {sim}</span>'card_html += f'<a href="{link}" target="_blank" rel="noopener noreferrer" class="shop-btn">Shop ↗</a>'card_html += f'</div></div>'cards.append(card_html)return f'<div class="more-matches-label">MORE MATCHES LIKE THIS</div><div class="outfit-grid">{"".join(cards)}</div>'# ---------------------------------------------------------------------------# MAIN PIPELINES# ---------------------------------------------------------------------------def run_pipeline(matched_indices, matched_rows, matched_scores, base_image=None, question=None, expected_gender=None):if len(matched_indices) == 0:return "<i>No matches found — try different filters.</i>", None, "", "<div></div>"similarity = [round(1.0 - (d / 2.0), 3) for d in matched_scores]top_row = matched_rows.iloc[0]edit_base_image = base_image if base_image is not None else images[matched_indices[0]]gender_for_generation = expected_gender or top_row["gender"]caption = generate_stylist_caption(top_row)new_image, _ = generate_new_outfit_image(edit_base_image, top_row, target_gender=gender_for_generation)answer = answer_question_about_image(edit_base_image, question) if question else ""style_card_html = build_style_card_html(top_row, caption)outfit_cards_html = build_outfit_component_cards_html(top_row) + build_more_matches_html(matched_indices, similarity)return style_card_html, new_image, answer, outfit_cards_htmldef recommend_from_photo(photo, gender, age_group, question):if photo is None:return "<i>Please upload a photo or pick a Quick Starter.</i>", None, "", "<div></div>"1 unmodified lineidx, rows, scores = faiss_filtered_search(query_emb, gender=gender or None, age_group=age_group or None)return run_pipeline(idx, rows, scores, base_image=photo, question=question, expected_gender=gender)def recommend_from_features(skin_tone, undertone, style, gender, age_group, question):sentence = build_feature_sentence(skin_tone, undertone, style, gender, age_group)query_emb = embed_query_text(sentence)idx, rows, scores = faiss_filtered_search(query_emb, gender=gender or None, age_group=age_group or None)return run_pipeline(idx, rows, scores, base_image=None, question=question, expected_gender=gender)def build_feature_pills_html(labels, selected, title):pills = ""for label in labels:active = str(label).strip().lower() == str(selected).strip().lower()border = "2px solid #D2527F" if active else "1.5px solid #ECE4D6"bg = "#FFF0F5" if active else "#FFFFFF"tcol = "#D2527F" if active else "#2C2A29"dot = _swatch_color(label) if title != "Style" else "#C69E6E"pills += f'<div style="display:inline-flex;align-items:center;gap:7px;padding:8px 14px;border-radius:30px;border:{border};background:{bg};margin:4px;"><div style="width:12px;height:12px;border-radius:50%;background:{dot};border:1px solid rgba(0,0,0,.1);"></div><span style="font-size:13px;font-weight:600;color:{tcol};">{str(label).title()}</span></div>'return f'<div style="margin-bottom:14px;"><div style="font-size:11px;font-weight:700;color:#8A7F6E;text-transform:uppercase;letter-spacing:.1em;margin-bottom:8px;">{title}</div><div style="display:flex;flex-wrap:wrap;margin:-4px;">{pills}</div></div>'def build_features_recap_html(skin_tone, undertone, style):return f'<div style="background:#fff;border-radius:16px;padding:24px;margin-bottom:20px;border:1px solid #ECE4D6;"><div style="font-size:12px;font-weight:700;color:#D2527F;text-transform:uppercase;letter-spacing:.1em;margin-bottom:16px;">Your Selected Specifications</div>{build_feature_pills_html(SKIN_TONES, skin_tone, "Skin tone")}{build_feature_pills_html(UNDERTONES, undertone, "Undertone")}{build_feature_pills_html(STYLES, style, "Style")}</div>'# ---------------------------------------------------------------------------# PREMIUM PASTEL LUXURY CSS THEME# ---------------------------------------------------------------------------CUSTOM_CSS = """@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600;700&family=Inter:wght@400;500;600;700&display=swap');body, .gradio-container { background-color: #F8F5F5 !important; font-family: 'Inter', sans-serif !important; }.gradio-container { max-width: 850px !important; margin: 0 auto !important; padding-top: 20px !important; }footer { display: none !important; }/* Global Font Contrast Controls - No Invisible Text */h1, h2, h3, p, span, label, input, select, textarea, button { color: #2C2A29 !important; }.tab-nav button { font-size: 14px !important; font-weight: 600 !important; padding: 14px 24px !important; color: #555 !important; }.tab-nav button.selected { color: #D2527F !important; border-bottom: 2px solid #D2527F !important; }#find-btn, .big-btn { background: #161617 !important; color: #FFFFFF !important; border: none !important; border-radius: 8px !important; font-weight: 700 !important; font-size: 14px !important; padding: 14px !important; text-transform: uppercase; letter-spacing: .08em !important; width: 100% !important; margin-top: 10px; }#find-btn:hover, .big-btn:hover { background: #2D2D2F !important; }/* Clean Pastel Premium Layout Blocks */.dark-panel { background: #FFFFFF !important; border-radius: 16px !important; padding: 24px !important; border: 1px solid #ECE4D6 !important; margin-bottom: 20px; }.dark-panel label, .dark-panel span { color: #2C2A29 !important; font-weight: 600; }.palette-premium-banner { background: #FAF3ED; padding: 24px; border-radius: 12px; margin-bottom: 20px; border-left: 5px solid #C69E6E; }.section-split { display: grid !important; grid-template-columns: repeat(2, 1fr) !important; gap: 20px !important; margin-top: 20px !important; width: 100% !important; }@media (max-width: 768px) { .section-split { grid-template-columns: 1fr !important; } }.results-box { background: #FFFFFF; border-radius: 16px; padding: 24px; border: 1px solid #EFECE8; }.results-box h3 { font-size: 11px; font-weight: 700; color: #9C8E82 !important; letter-spacing: 1.5px; text-transform: uppercase; margin: 0 0 14px; }.swatch-grid { display: flex; gap: 16px; flex-wrap: wrap; }.swatch-card { text-align: center; font-size: 12px; color: #666666 !important; width: 60px; }.color-bubble { width: 44px; height: 44px; border-radius: 50%; margin: 0 auto 6px; border: 1px solid rgba(0,0,0,.06); box-shadow: inset 0 0 0 2px #FFF; }.tip-text { font-size: 15px; color: #222222 !important; line-height: 1.6; margin: 0; font-style: italic; }/* Perfect 6-Card Row Flow without Hiding or Squishing */.outfit-grid { display: grid !important; grid-template-columns: repeat(3, 1fr) !important; gap: 20px !important; margin-top: 20px !important; width: 100% !important; }@media (max-width: 768px) { .outfit-grid { grid-template-columns: repeat(2, 1fr) !important; } }@media (max-width: 480px) { .outfit-grid { grid-template-columns: 1fr !important; } }.product-card { background: #FFFFFF; border: 1px solid #EFECE8; border-radius: 16px; overflow: hidden; display: flex; flex-direction: column; box-shadow: 0 4px 12px rgba(0,0,0,0.01); width: 100% !important; }.card-color-header { width: 100%; height: 95px; display: flex; align-items: center; justify-content: center; }.prod-bubble { width: 46px; height: 46px; border-radius: 50%; box-shadow: 0 2px 8px rgba(0,0,0,0.04); }.prod-meta { padding: 20px; display: flex; flex-direction: column; align-items: flex-start; text-align: left; width: 100%; }.prod-cat { font-size: 11px; font-weight: 700; color: #D2527F !important; letter-spacing: 0.5px; text-transform: uppercase; margin-bottom: 4px; }.prod-title { font-size: 15px; font-weight: 700; color: #111111 !important; margin: 0 0 4px 0; line-height: 1.3; min-height: 40px; display: flex; align-items: center; }.prod-brand { font-size: 13px; color: #999999 !important; margin-bottom: 14px; display: block; }.shop-btn { display: block; width: 100%; background: #161617; color: #FFFFFF !important; text-align: center; padding: 11px 0; border-radius: 8px; font-size: 13px; font-weight: 700; text-decoration: none !important; letter-spacing: 0.5px; }.shop-btn:hover { background: #2D2D2F; color: #FFFFFF !important; }.more-matches-label { font-size: 11px; font-weight: 700; color: #9C8E82 !important; letter-spacing: 1.6px; text-transform: uppercase; margin: 24px 0 12px; }.palette-name { font-family: 'Playfair Display', serif !important; }.footer-note { font-size: 13px; color: #A0A0A0 !important; text-align: center; margin-top: 16px; }"""# ---------------------------------------------------------------------------# INTERFACE BUILD# ---------------------------------------------------------------------------with gr.Blocks(title="Personal Color Styling", css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="amber")) as demo:gr.HTML("""<div style="text-align:center; padding:24px 20px 10px;"><div style="font-size:11px; font-weight:700; color:#D2527F; letter-spacing:.18em; text-transform:uppercase; margin-bottom:8px;">Personal Color Styling</div><div class="palette-name" style="font-size:38px; font-weight:700; color:#111; margin-bottom:6px;">LookMatch</div><div style="font-size:14px; color:#666; max-width:480px; margin:0 auto; line-height:1.6;">Upload a photo or describe your features — receive a curated palette, a personal stylist note, and a brand-new look generated just for you.</div></div>""")4 unmodified lineswith gr.Column():gender_a = gr.Dropdown(GENDERS, label="Gender (optional)")age_a = gr.Dropdown(AGE_GROUPS, label="Age group (optional)")question_a = gr.Textbox(label="Ask the stylist a question about your photo (optional)", placeholder="e.g. What style would suit me best?")btn_a = gr.Button("Get my look ✨", elem_id="find-btn", variant="primary")style_card_a = gr.HTML()new_img_a = gr.Image(label="✨ Your New AI-Generated Look")answer_a = gr.Textbox(label="Answer to your question")outfit_cards_a = gr.HTML()btn_a.click(recommend_from_photo,[photo_in, gender_a, age_a, question_a],5 unmodified linesinputs=[photo_in, gender_a, age_a, question_a],outputs=[style_card_a, new_img_a, answer_a, outfit_cards_a],fn=recommend_from_photo,cache_examples=True,label="Quick Starters",)7 unmodified lineswith gr.Row():gender_b = gr.Dropdown(GENDERS, label="Gender", value=GENDERS[0])age_b = gr.Dropdown(AGE_GROUPS, label="Age group", value=AGE_GROUPS[0])question_b = gr.Textbox(label="Ask the stylist a question about the top match (optional)", placeholder="e.g. Is this outfit formal or casual?")btn_b = gr.Button("Get my look ✨", elem_id="find-btn", variant="primary")features_recap_b = gr.HTML(build_features_recap_html(SKIN_TONES[0], UNDERTONES[0], STYLES[0]))for _dropdown in (skin_b, undertone_b, style_b):_dropdown.change(build_features_recap_html, [skin_b, undertone_b, style_b], features_recap_b)style_card_b = gr.HTML()new_img_b = gr.Image(label="✨ Your New AI-Generated Look")answer_b = gr.Textbox(label="Answer to your question")outfit_cards_b = gr.HTML()btn_b.click(recommend_from_features,[skin_b, undertone_b, style_b, gender_b, age_b, question_b],[style_card_b, new_img_b, answer_b, outfit_cards_b],)if __name__ == "__main__":demo.launch()
app.py+241-438