Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116122 unmodified lines615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020"""Personal Style Matcher==================================================================================A Gradio app that recommends fashion looks from the "Fashion StylistMultimodal v2" catalog (lihicarmeli/fashion-stylist-multimodal-v2 on theHugging Face Hub), using the exact same engine validated in Part 3:* Embedding model : openai/clip-vit-base-patch32 (the model selectedafter the multi-criteria evaluation in Part 3 — best speed/size/efforttrade-off, within 1.3 purity points of the larger CLIP variant).* Vector search : a FAISS flat-L2 index over the catalog's CLIP imageembeddings, with the same 3-tier demographic fallback filter used inthe notebook (strict gender+age -> gender-only -> fully open search).* GenAI component : an optional one-line AI stylist note generated bya small instruction-tuned LM (Qwen/Qwen2.5-0.5B-Instruct), reusing theexact prompt pattern from Part 4.Two ways in, one engine:Mode A — upload a photo. A lightweight heuristic samples the face regionto estimate a skin tone / undertone, and the photo itself isembedded with CLIP's image encoder for the catalog search.Mode B — pick your features from dropdowns. A natural-language sentenceis built from those features and embedded with CLIP's textencoder, landing in the exact same vector space as the photos.Deploy: push this file + requirements.txt to a new Hugging Face Space usingthe "Gradio" SDK. No local data or model files are needed — both thedataset and the embedding model are streamed directly from the Hub."""import osimport htmlimport hashlibimport colorsysimport tracebackimport urllib.parseimport numpy as npimport torchimport faissfrom datasets import load_datasetfrom transformers import AutoModel, AutoProcessorimport gradio as gr# =============================================================================# Constants# =============================================================================DATASET_REPO = "lihicarmeli/fashion-stylist-multimodal-v2"EMBED_MODEL_REPO = "openai/clip-vit-base-patch32" # winning model from Part 3CAPTION_MODEL_REPO = "Qwen/Qwen2.5-0.5B-Instruct" # small LM from Part 4EMBED_CACHE_PATH = "catalog_image_embeddings.npy"SKIN_DEPTH_ORDER = ["fair", "light", "ivory", "porcelain", "medium","olive", "tan", "deep", "dark", "ebony"]AGE_ORDER = ["teen", "young adult", "adult", "mature"]UNDERTONE_ORDER = ["warm", "neutral", "cool"]EYE_COLOR_CHOICES = ["Brown", "Dark Brown", "Hazel", "Amber", "Green", "Blue", "Gray"]WARM_EYES = {"brown", "dark brown", "hazel", "amber"}COOL_EYES = {"green", "blue", "gray", "grey"}AUTO_DETECT_LABEL = "Auto-detect from photo"COMPONENT_RETAILERS = {"TOP": "zara","BOTTOM": "hm","SHOES": "asos","ACCESSORY": "mango",}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}/",}# =============================================================================# Color utilities — resolve a descriptive color phrase to a hex swatch# =============================================================================NAMED_COLOR_HEX = {# multi-word fashion phrases (checked first, longest match wins)"ice white": "#F5F5F0", "warm white": "#FAF3E8", "deep jewel": "#5B2C6F","bold blue": "#1E5AA8", "royal blue": "#4169E1", "cobalt blue": "#0047AB","powder blue": "#B0E0E6", "rich gold": "#C9A227", "warm beige": "#E8D9B5","warm brown": "#8B5A2B", "cool red": "#C8102E", "bright red": "#EE2C2C","brick red": "#9B3A2C", "deep teal": "#114B5F", "deep olive": "#4B5320","deep purple": "#4B1A6B", "forest green": "#1B4332", "bright orange": "#FF6B1A","bright pink": "#FF2D87", "dusty rose": "#C68893", "blush pink": "#F4C2C2","grass green": "#3DA35D", "slate gray": "#6E7B8B", "burnt orange": "#CB6015","golden yellow": "#F5C518", "true red": "#C8102E", "bright warm red": "#E0382D","very deep": "#3A2A22", "cool blue": "#3B6FCC",# single words (fallback)"white": "#FFFFFF", "black": "#1A1A1A", "ivory": "#FFFFF0", "silver": "#C0C0C0","gold": "#D4AF37", "amber": "#FFBF00", "tangerine": "#F28500", "coral": "#FF7F50","peach": "#FFCBA4", "terracotta": "#C0654D", "olive": "#708238", "beige": "#E8D9B5","tan": "#C19A6B", "khaki": "#C3B091", "emerald": "#2E8B57", "teal": "#218380","turquoise": "#30D5C8", "mint": "#98D8C8", "navy": "#1B1F3B", "blue": "#3B6FCC","lavender": "#B497D6", "plum": "#8E4585", "magenta": "#C2185B", "fuchsia": "#D6336C","purple": "#7B4397", "maroon": "#7A2E3B", "burgundy": "#6E0D25", "crimson": "#A11D33","red": "#D63447", "pink": "#E07A9E", "rose": "#D17B96", "yellow": "#F4C542","mustard": "#C9A227", "orange": "#E8722C", "brown": "#7B4B2A", "chocolate": "#5A3A22","copper": "#B6622A", "rust": "#9E4624", "green": "#3F8D5C", "grey": "#9A9A9A","gray": "#9A9A9A", "charcoal": "#3B3B3B", "cream": "#F1E8DA",}def resolve_color_hex(text):"""Return a hex color if any known color phrase appears in `text`, else None."""if not text:return Nonet = str(text).lower()for phrase in sorted(NAMED_COLOR_HEX, key=len, reverse=True):if " " in phrase and phrase in t:return NAMED_COLOR_HEX[phrase]for word in t.replace(",", " ").split():if word in NAMED_COLOR_HEX:return NAMED_COLOR_HEX[word]return Nonedef text_to_pastel_hex(text):"""Deterministic fallback color: hash the text into a pleasant, distinct hue."""digest = hashlib.md5(str(text).encode("utf-8")).hexdigest()hue = int(digest[:4], 16) / 65535.0r, g, b = colorsys.hls_to_rgb(hue, 0.55, 0.55)return "#{:02X}{:02X}{:02X}".format(int(r * 255), int(g * 255), int(b * 255))def swatch_color_for(*texts):"""Pick the first resolvable color among the given text fields, or fall backto a stable hashed pastel so the same item always gets the same swatch."""for t in texts:hexcode = resolve_color_hex(t)if hexcode:return hexcodejoined = " ".join(str(t) for t in texts if t)return text_to_pastel_hex(joined or "style")# =============================================================================# Seasonal color profile (display-only "stylist" layer on top of the catalog)# =============================================================================SEASON_INFO = {"Spring": {"blurb": "Warm and light — your glow loves clear, fresh colors with a golden undertone.","palette": [("Coral", "#FF7F50"), ("Peach", "#FFCBA4"), ("Golden Yellow", "#F5C518"),("Grass Green", "#3DA35D"), ("Turquoise", "#30D5C8"), ("Ivory", "#FFFFF0")],},"Autumn": {"blurb": "Warm and rich — earthy, spiced tones make your natural warmth shine.","palette": [("Rust", "#9E4624"), ("Olive", "#708238"), ("Mustard", "#C9A227"),("Chocolate Brown", "#5A3A22"), ("Burnt Orange", "#CB6015"), ("Forest Green", "#1B4332")],},"Summer": {"blurb": "Cool and soft — muted, misty colors flatter your cool undertone beautifully.","palette": [("Powder Blue", "#B0E0E6"), ("Lavender", "#B497D6"), ("Rose Pink", "#D17B96"),("Soft Teal", "#5F9EA0"), ("Dusty Mauve", "#A97C8A"), ("Slate Gray", "#6E7B8B")],},"Winter": {"blurb": "Cool and deep — bold, high-contrast colors match your striking cool undertone.","palette": [("True Red", "#C8102E"), ("Royal Blue", "#4169E1"), ("Emerald", "#2E8B57"),("Black", "#1A1A1A"), ("White", "#FFFFFF"), ("Magenta", "#C2185B")],},"Soft Spring": {"blurb": "A gentle warm-neutral mix — soft, peachy tones suit you better than stark contrast.","palette": [("Soft Peach", "#F2C6A0"), ("Honey", "#E2B765"), ("Sage Green", "#9CAF88"),("Camel", "#C19A6B"), ("Warm Ivory", "#F5EFE0"), ("Apricot", "#FBCEB1")],},"Soft Autumn": {"blurb": "A muted warm-neutral mix — soft earth tones bring out your warmth without overpowering it.","palette": [("Terracotta", "#C0654D"), ("Sage", "#8A9A5B"), ("Caramel", "#AF6E4D"),("Warm Taupe", "#9C8170"), ("Moss", "#6B7A4F"), ("Dusty Gold", "#B79766")],},"Soft Summer": {"blurb": "A gentle cool-neutral mix — soft, dusty colors are more flattering than bright ones.","palette": [("Dusty Rose", "#C68893"), ("Soft Lilac", "#C6B4D6"), ("Sage Gray", "#A6AD9E"),("Mauve", "#9C7A8A"), ("Soft Denim", "#7C93A8"), ("Pearl Gray", "#C9C5C0")],},"Soft Winter": {"blurb": "A muted cool-neutral mix — clear but gentle colors balance your cool undertone.","palette": [("Plum", "#8E4585"), ("Slate Blue", "#5B6C8F"), ("Charcoal", "#3B3B3B"),("Berry", "#7A2E4D"), ("Icy Pink", "#E7C6CE"), ("Steel Gray", "#71797E")],},}def skin_depth_flag(skin_tone):"""Bucket a skin-tone label into 'light' or 'deep' using a best-effort ordering."""s = str(skin_tone).lower().strip()if s in SKIN_DEPTH_ORDER:idx = SKIN_DEPTH_ORDER.index(s)midpoint = len(SKIN_DEPTH_ORDER) / 2else:idx, midpoint = 1, 2 # unseen label -> assume mid-rangereturn "deep" if idx >= midpoint else "light"def derive_color_profile(skin_tone, undertone, eye_color=None):"""Map (skin tone, undertone, eye color) onto a simplified 4/8-seasoncolor-analysis bucket. This is a styling heuristic, not a clinical tool —it gives the user a friendly, explainable color story to go with theirmatched looks."""undertone = str(undertone).lower().strip()depth = skin_depth_flag(skin_tone)eye = str(eye_color).lower().strip() if eye_color else ""if undertone == "warm":season = "Spring" if depth == "light" else "Autumn"elif undertone == "cool":season = "Summer" if depth == "light" else "Winter"else:leans_warm = eye in WARM_EYESleans_cool = eye in COOL_EYESif depth == "light":season = "Soft Summer" if leans_cool and not leans_warm else "Soft Spring"else:season = "Soft Winter" if leans_cool and not leans_warm else "Soft Autumn"info = SEASON_INFO.get(season, SEASON_INFO["Spring"])return season, info["blurb"], info["palette"]# =============================================================================# Skin tone / undertone estimation from an uploaded photo (Mode A)# =============================================================================def estimate_skin_tone_undertone(pil_image, available_skin_tones):"""A lightweight, transparent heuristic — NOT a clinical skin-toneclassifier. It samples a centered, face-shaped region of the photo, keepsonly pixels that look skin-like in YCbCr space, and buckets the resultingaverage color by brightness (-> skin tone bucket) and red/blue balance(-> warm / cool / neutral undertone)."""img = pil_image.convert("RGB").resize((160, 160))arr = np.asarray(img).astype(np.float32)h, w, _ = arr.shapey0, y1 = int(h * 0.15), int(h * 0.75)x0, x1 = int(w * 0.30), int(w * 0.70)crop = arr[y0:y1, x0:x1, :]r, g, b = crop[..., 0], crop[..., 1], crop[..., 2]y_ = 0.299 * r + 0.587 * g + 0.114 * bcb = 128 - 0.168736 * r - 0.331264 * g + 0.5 * bcr = 128 + 0.5 * r - 0.418688 * g - 0.081312 * bskin_mask = (y_ > 60) & (cb > 85) & (cb < 135) & (cr > 135) & (cr < 180)pixels = crop.reshape(-1, 3) if skin_mask.sum() < 50 else crop[skin_mask]mean_rgb = pixels.mean(axis=0)brightness = float(0.299 * mean_rgb[0] + 0.587 * mean_rgb[1] + 0.114 * mean_rgb[2])available = {str(s).lower() for s in available_skin_tones}ordered = [s for s in SKIN_DEPTH_ORDER if s in available] or list(available_skin_tones)n = len(ordered)frac = 1.0 - min(max(brightness / 255.0, 0.0), 1.0) # darker photo -> higher fracbucket_idx = min(int(frac * n), n - 1) if n else 0skin_tone_guess = ordered[bucket_idx] if n else "medium"diff = float(mean_rgb[0] - mean_rgb[2]) # R - Bif diff > 8:undertone_guess = "warm"elif diff < -8:undertone_guess = "cool"else:undertone_guess = "neutral"swatch_hex = "#{:02X}{:02X}{:02X}".format(*[int(min(max(c, 0), 255)) for c in mean_rgb])return skin_tone_guess, undertone_guess, swatch_hex# =============================================================================# Query building & embedding (mirrors the validated Part 3 pipeline exactly)# =============================================================================def build_feature_sentence(skin_tone, undertone, style_preference, gender=None,age_group=None, eye_color=None):"""Path B: turn typed-in features into a sentence in the same vectorspace CLIP's text encoder was trained on, mirroring Part 3'sbuild_feature_sentence()."""descriptor = " ".join(p for p in [age_group, gender] if p) or "person"sentence = (f"a {descriptor} with {skin_tone} skin tone and {undertone} undertone, "f"wearing a {style_preference} style outfit")if eye_color:sentence += f", {str(eye_color).lower()} eyes"return sentence@torch.no_grad()def embed_query_image(pil_image, model, processor, device):"""Path A: turn a user-uploaded photo into a CLIP image embedding."""inputs = processor(images=pil_image.convert("RGB"), return_tensors="pt").to(device)outputs = model.get_image_features(**inputs)feats = outputs.pooler_output if hasattr(outputs, "pooler_output") else outputsreturn feats.cpu().numpy().astype("float32")@torch.no_grad()def embed_query_text(sentence, model, processor, device):"""Path B: turn a feature sentence into a CLIP text embedding."""inputs = processor(text=[sentence], return_tensors="pt", padding=True,truncation=True).to(device)outputs = model.get_text_features(**inputs)feats = outputs.pooler_output if hasattr(outputs, "pooler_output") else outputsreturn feats.cpu().numpy().astype("float32")def faiss_filtered_search(query_emb, faiss_index, df_pool, top_k=3, exclude_idx=None,gender=None, age_group=None):"""Self-exclusion + graded demographic filtering fallback, identical inspirit to Part 3's faiss_filtered_search: Tier 1 (gender + age) -> Tier 2(gender only) -> Tier 3 (fully open). Returns (indices, rows, distances, tier)."""query_emb = np.array(query_emb, dtype="float32").reshape(1, -1).copy()faiss.normalize_L2(query_emb)k = min(len(df_pool), faiss_index.ntotal)distances, indices = faiss_index.search(query_emb, k)distances, indices = distances[0], indices[0]def collect(filter_fn):kept_i, kept_d = [], []for idx, dist in zip(indices, distances):if idx == -1 or (exclude_idx is not None and idx == exclude_idx):continuerow = df_pool.iloc[idx]if not filter_fn(row):continuekept_i.append(int(idx))kept_d.append(float(dist))if len(kept_i) == top_k:breakreturn kept_i, kept_ddef gender_match(row):return gender is None or str(row["gender"]).lower() == str(gender).lower()def age_match(row):return age_group is None or str(row["age_group"]).lower() == str(age_group).lower()kept_i, kept_d = collect(lambda row: gender_match(row) and age_match(row))tier = 1if len(kept_i) < top_k:kept_i, kept_d = collect(gender_match)tier = 2if len(kept_i) < top_k:kept_i, kept_d = collect(lambda row: True)tier = 3idx_arr = np.array(kept_i)rows = df_pool.iloc[idx_arr] if len(idx_arr) else df_pool.iloc[0:0]return idx_arr, rows, np.array(kept_d), tier# =============================================================================# Real, working shop links# =============================================================================def normalize_gender(gender):g = str(gender).strip().lower() if gender is not None else ""if g in ("male", "man", "men", "m"):return "men"if g in ("female", "woman", "women", "f"):return "women"return "women"def component_shop_link(retailer, item_text, gender=None):"""Build a real, live retailer search URL for one outfit component."""dept = normalize_gender(gender)text = str(item_text)if retailer == "zara":section = "MAN" if dept == "men" else "WOMAN"query = urllib.parse.quote(text)return RETAILER_SEARCH_URLS["zara"].format(query=query, section=section)if retailer == "asos":query = urllib.parse.quote(text)return RETAILER_SEARCH_URLS["asos"].format(query=query, dept=dept)gender_word = "men's" if dept == "men" else "women's"query = urllib.parse.quote(f"{gender_word} {text}")return RETAILER_SEARCH_URLS[retailer].format(query=query)# =============================================================================# HTML rendering — matches the required "YOUR MATCHED LOOKS" layout exactly# =============================================================================def render_profile_card_html(season, blurb, palette):chips = "".join(f'<div class="fs-chip"><span class="fs-chip-dot" style="background:{hexcode}"></span>{html.escape(name)}</div>'for name, hexcode in palette)return f"""<div class="fs-profile-card"><div class="fs-profile-eyebrow">YOUR COLOR PROFILE</div><div class="fs-profile-season">{html.escape(season)}</div><div class="fs-profile-blurb">{html.escape(blurb)}</div><div class="fs-chip-row">{chips}</div></div>"""def render_caption_html(caption):return ('<div class="fs-caption">🪄 <span class="fs-caption-label">AI Stylist note:</span> 'f'“{html.escape(caption)}”</div>')def _component_html(label, text, retailer, gender):hexcode = swatch_color_for(text)link = component_shop_link(retailer, text, gender)return f"""<div class="fs-component"><div class="fs-component-swatch"><span class="fs-swatch-dot" style="background:{hexcode}"></span></div><div class="fs-component-body"><div class="fs-component-label">{label}</div><div class="fs-component-name">{html.escape(str(text))}</div><a class="fs-shop-btn" href="{link}" target="_blank" rel="noopener noreferrer">Shop ↗</a></div></div>"""def render_look_card_html(look_number, row, score_pct):avatar_hex = swatch_color_for(row.get("primary_color"), row.get("secondary_color"))gender = row.get("gender")components = [("TOP", row.get("outfit_top", ""), COMPONENT_RETAILERS["TOP"]),("BOTTOM", row.get("outfit_bottom", ""), COMPONENT_RETAILERS["BOTTOM"]),("SHOES", row.get("outfit_shoes", ""), COMPONENT_RETAILERS["SHOES"]),("ACCESSORY", row.get("outfit_accessory", ""), COMPONENT_RETAILERS["ACCESSORY"]),]comp_html = "".join(_component_html(label, text, retailer, gender)for label, text, retailer in components)style_pref = html.escape(str(row.get("style_preference", "")))skin_tone = html.escape(str(row.get("skin_tone", "")))colors_line = html.escape(str(row.get("recommended_colors", "")))return f"""<div class="fs-look-card"><div class="fs-look-head"><span class="fs-look-avatar" style="background:{avatar_hex}"></span><div><div class="fs-look-title">Look #{look_number}</div><div class="fs-look-sub">{style_pref} · {skin_tone} skin · {score_pct}% match</div></div></div>{comp_html}<div class="fs-colors-footer">Recommended colors: {colors_line}</div></div>"""def render_results_html(profile_html, look_cards_html_list, note=None):cards = "".join(look_cards_html_list)note_html = f'<div class="fs-note">{html.escape(note)}</div>' if note else ""return f"""<div class="fs-root">{profile_html}<div class="fs-header"><div class="fs-header-decoration"></div><div class="fs-header-eyebrow">YOUR MATCHED LOOKS</div><div class="fs-header-sub">Top 3 outfits from your personal style dataset</div></div>{note_html}<div class="fs-grid">{cards}</div></div>"""def render_error_html(message):return f"""<div class="fs-root"><div class="fs-error"><div class="fs-error-title">Something went wrong</div><div class="fs-error-msg">{html.escape(str(message))}</div></div></div>"""def render_placeholder_html():return """<div class="fs-root"><div class="fs-placeholder">Upload a photo or pick your features, then press<strong>“Find My Looks”</strong> to see your personal color profileand your top 3 matched outfits.</div></div>"""# =============================================================================# Dataset & model loading# =============================================================================def order_choices(values, preferred_order):"""Order dropdown choices using a sensible preferred order, falling backto alphabetical for anything not in that list."""vals = {str(v) for v in values}ordered = [p for p in preferred_order if p in vals]remaining = sorted(v for v in vals if v not in ordered)return ordered + remainingdef load_catalog():print(f"Loading dataset '{DATASET_REPO}' from the Hugging Face Hub...")ds = load_dataset(DATASET_REPO)train = ds["train"]df = train.to_pandas()images = [train[i]["image_improved"] for i in range(len(train))]print(f"Catalog loaded: {len(df)} items, {len(df.columns)} columns.")return df, imagesdef load_embedding_model():print(f"Loading embedding model '{EMBED_MODEL_REPO}' from the Hugging Face Hub...")device = "cuda" if torch.cuda.is_available() else "cpu"processor = AutoProcessor.from_pretrained(EMBED_MODEL_REPO)model = AutoModel.from_pretrained(EMBED_MODEL_REPO).to(device).eval()print(f"Embedding model ready on device='{device}'.")return model, processor, device@torch.no_grad()def embed_catalog_images(model, processor, images, device, batch_size=32):embs = []for i in range(0, len(images), batch_size):batch = [im.convert("RGB") for im in images[i:i + batch_size]]inputs = processor(images=batch, return_tensors="pt").to(device)outputs = model.get_image_features(**inputs)feats = outputs.pooler_output if hasattr(outputs, "pooler_output") else outputsfeats = feats / feats.norm(dim=-1, keepdim=True)embs.append(feats.cpu().numpy())print(f" embedded {min(i + batch_size, len(images))}/{len(images)} catalog images")return np.vstack(embs).astype("float32")def build_faiss_index(df, images, model, processor, device):image_embeddings = Noneif os.path.exists(EMBED_CACHE_PATH):try:cached = np.load(EMBED_CACHE_PATH)if cached.shape[0] == len(df):print("Loaded cached catalog embeddings from disk.")image_embeddings = cachedexcept Exception as e:print(f"Ignoring unreadable embedding cache: {e}")if image_embeddings is None:image_embeddings = embed_catalog_images(model, processor, images, device)try:np.save(EMBED_CACHE_PATH, image_embeddings)except Exception as e:print(f"Could not cache embeddings to disk (non-fatal): {e}")dim = image_embeddings.shape[1]index = faiss.IndexFlatL2(dim)normalized = image_embeddings.copy()faiss.normalize_L2(normalized)index.add(normalized)print(f"FAISS index ready with {index.ntotal} items (dim={dim}).")return indexdef pick_quickstarts(df, n=3):"""Pick `n` real catalog rows covering distinct styles, to use as1-click 'Quick Starter' examples with guaranteed-valid feature values."""eye_cycle = ["Brown", "Hazel", "Blue"]seen_styles, starters = set(), []for _, row in df.iterrows():style = row["style_preference"]if style in seen_styles:continueseen_styles.add(style)starters.append({"skin_tone": row["skin_tone"],"undertone": row["undertone"],"style": style,"gender": row["gender"],"age_group": row["age_group"],"eye_color": eye_cycle[len(starters) % len(eye_cycle)],})if len(starters) == n:breakreturn starters# =============================================================================# Gradio app# =============================================================================CUSTOM_CSS = """@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@200;300;400;500;600;700&family=Inter:wght@400;500;600&display=swap');.fs-root {--cream: #FDFBF7;--white: #FFFFFF;--charcoal: #1A1A1A;2 unmodified lines--hairline: #EEEEEE;--rose: #C48793;--rose-soft: #F6ECEE;--sage: #9CAF88;--sage-soft: #EFF3EA;--gold: #C9A876;--gold-soft: #F8F1E4;max-width: 1120px;margin: 0 auto;font-family: 'Inter', system-ui, sans-serif;color: var(--charcoal-soft);}.fs-app-title {font-family: 'Montserrat', system-ui, sans-serif;font-weight: 600;font-size: 30px;letter-spacing: 0.02em;color: var(--charcoal);margin-bottom: 4px;}.fs-app-tag { color: var(--text-muted); font-size: 14px; letter-spacing: 0.01em; margin-bottom: 6px; }.fs-placeholder {color: var(--text-muted); font-size: 14px; padding: 48px 24px; text-align: center;border: 1px solid var(--hairline); border-radius: 25px; background: var(--white);letter-spacing: 0.01em;}.fs-profile-card {background: linear-gradient(135deg, var(--rose-soft) 0%, var(--sage-soft) 100%);border: 1px solid var(--hairline); border-radius: 25px; padding: 32px 34px;margin-bottom: 24px; position: relative; overflow: hidden;box-shadow: 0px 10px 30px rgba(0,0,0,0.05);}.fs-profile-eyebrow {color: var(--rose); font-weight: 600; font-size: 12px; letter-spacing: .16em;text-transform: uppercase; margin-bottom: 10px;}.fs-profile-season {font-family: 'Montserrat', sans-serif; font-weight: 300; font-size: 30px;letter-spacing: 0.01em; color: var(--charcoal); margin-bottom: 10px;}.fs-profile-blurb { color: var(--charcoal-soft); font-size: 14.5px; max-width: 620px; margin-bottom: 20px; line-height: 1.6; }.fs-chip-row { display: flex; gap: 10px; flex-wrap: wrap; }.fs-chip {display: flex; align-items: center; gap: 8px; background: var(--white);border: 1px solid var(--hairline); border-radius: 999px; padding: 7px 14px 7px 7px;font-size: 12px; color: var(--charcoal-soft); letter-spacing: 0.02em;box-shadow: 0px 4px 10px rgba(0,0,0,0.03);}.fs-chip-dot { width: 18px; height: 18px; border-radius: 50%; display: inline-block; box-shadow: 0 0 0 2px var(--white), 0 1px 4px rgba(0,0,0,.15); }.fs-header {position: relative; background: var(--white); border: 1px solid var(--hairline);border-radius: 25px; padding: 30px 34px; margin-bottom: 24px; overflow: hidden;box-shadow: 0px 10px 30px rgba(0,0,0,0.04);}.fs-header-decoration {position: absolute; top: -50px; right: -40px; width: 160px; height: 160px;border-radius: 50%; background: radial-gradient(circle, var(--gold-soft) 0%, transparent 70%);}.fs-header-eyebrow {color: var(--rose); font-weight: 600; font-size: 13px; letter-spacing: .18em;text-transform: uppercase; margin-bottom: 8px; position: relative; z-index: 1;}.fs-header-sub { font-size: 15.5px; color: var(--text-muted); letter-spacing: 0.01em; position: relative; z-index: 1; }.fs-note {background: var(--gold-soft); color: #7a5c34; border: 1px solid #EADFC4; border-radius: 14px;padding: 12px 18px; font-size: 13px; margin-bottom: 18px; letter-spacing: 0.01em;}.fs-caption {background: var(--sage-soft); border: 1px solid var(--hairline); border-radius: 18px;padding: 16px 20px; margin-bottom: 20px; font-size: 14px; color: var(--charcoal-soft);}.fs-caption-label { font-weight: 600; color: var(--charcoal); }.fs-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }@media (max-width: 900px) { .fs-grid { grid-template-columns: 1fr; } }.fs-look-card {background: var(--white); border: 1px solid var(--hairline); border-radius: 25px;padding: 22px; box-shadow: 0px 10px 30px rgba(0,0,0,0.05);}.fs-look-head {display: flex; align-items: center; gap: 14px; margin-bottom: 18px;padding-bottom: 18px; border-bottom: 1px solid var(--hairline);}.fs-look-avatar {width: 50px; height: 50px; border-radius: 50%; flex-shrink: 0;border: 2px solid var(--gold); box-shadow: 0 4px 10px rgba(0,0,0,0.08);display: inline-block;}.fs-look-title {font-family: 'Montserrat', sans-serif; font-weight: 300; font-size: 22px;letter-spacing: 0.01em; color: var(--charcoal);}.fs-look-sub { color: var(--text-muted); font-size: 13px; margin-top: 3px; letter-spacing: 0.01em; }.fs-component {border: 1px solid var(--hairline); border-radius: 18px; overflow: hidden; margin-bottom: 14px;transition: box-shadow .2s ease;}.fs-component:hover { box-shadow: 0px 6px 18px rgba(0,0,0,0.05); }.fs-component:last-child { margin-bottom: 0; }.fs-component-swatch { background: var(--cream); height: 68px; display: flex; align-items: center; justify-content: center; }.fs-swatch-dot {width: 36px; height: 36px; border-radius: 50%; display: inline-block;box-shadow: 0 0 0 3px var(--white), 0 3px 8px rgba(0,0,0,0.12);}.fs-component-body { padding: 14px 16px; background: var(--white); border-top: 1px solid var(--hairline); }.fs-component-label {color: var(--rose); font-weight: 600; font-size: 11px; letter-spacing: .12em;text-transform: uppercase; margin-bottom: 4px;}.fs-component-name {font-weight: 500; color: var(--charcoal); font-size: 14.5px; margin-bottom: 12px;line-height: 1.35; letter-spacing: 0.01em;}.fs-shop-btn {display: inline-flex; align-items: center; gap: 6px; background: var(--charcoal);color: #fff !important; padding: 9px 20px; border-radius: 999px; font-size: 11.5px;font-weight: 600; letter-spacing: .08em; text-transform: uppercase;text-decoration: none !important; transition: transform .2s ease, background-color .2s ease;}.fs-shop-btn:hover { background: #333333; transform: scale(1.05); }.fs-colors-footer {color: var(--text-muted); font-size: 12px; margin-top: 8px; padding-top: 14px;border-top: 1px solid var(--hairline); letter-spacing: 0.01em;}.fs-error { background: #FBEEEE; border: 1px solid #F0D6D6; border-radius: 18px; padding: 20px 22px; }.fs-error-title { color: #9A4A4A; font-weight: 600; margin-bottom: 4px; letter-spacing: 0.01em; }.fs-error-msg { color: #7a5c5c; font-size: 14px; }"""def build_demo(df, model, processor, faiss_index, device):skin_tone_choices = order_choices(df["skin_tone"].unique(), SKIN_DEPTH_ORDER)undertone_choices = order_choices(df["undertone"].unique(), UNDERTONE_ORDER)style_choices = sorted(df["style_preference"].unique().tolist())gender_choices = sorted(df["gender"].unique().tolist())age_choices = order_choices(df["age_group"].unique(), AGE_ORDER)quickstarts = pick_quickstarts(df)caption_pipe_holder = {"pipe": None, "failed": False}def get_caption_pipe():if caption_pipe_holder["pipe"] is None and not caption_pipe_holder["failed"]:try:from transformers import pipeline as hf_pipelineprint(f"Loading GenAI caption model '{CAPTION_MODEL_REPO}' (first use only)...")caption_pipe_holder["pipe"] = hf_pipeline("text-generation",model=CAPTION_MODEL_REPO,device=0 if device == "cuda" else -1,)except Exception as e:print(f"Caption model unavailable, skipping AI note: {e}")caption_pipe_holder["failed"] = Truereturn caption_pipe_holder["pipe"]def generate_caption(row):pipe = get_caption_pipe()if pipe is None:return Nonetry:user_prompt = ("Write one short, warm sentence (max 25 words) from a fashion stylist, "f"recommending this look: a {row['style_preference']} style outfit in "f"{row['primary_color']} and {row['secondary_color']}, best colors: "f"{row['recommended_colors']}. Be specific and stylish, no hashtags.")messages = [{"role": "user", "content": user_prompt}]out = pipe(messages, max_new_tokens=40, do_sample=True, temperature=0.7)return out[0]["generated_text"][-1]["content"].strip()except Exception as e:print(f"[caption generation skipped] {e}")return Nonedef predict(mode, photo, photo_skin_override, photo_undertone_override,manual_skin, manual_undertone, style, gender, age_group,eye_color, want_caption):try:is_photo_mode = str(mode).startswith("📷")if is_photo_mode:if photo is None:return render_error_html("Please upload a photo, or switch to “Manual Selection”.")detected_skin, detected_undertone, _ = estimate_skin_tone_undertone(photo, skin_tone_choices)skin_tone = (detected_skin if photo_skin_override in (None, "", AUTO_DETECT_LABEL)else photo_skin_override)undertone = (detected_undertone if photo_undertone_override in (None, "", AUTO_DETECT_LABEL)else photo_undertone_override)query_emb = embed_query_image(photo, model, processor, device)if style:# Even in photo mode, let the chosen style nudge the search:# blend in a small text-embedding bias toward that style,# in the same CLIP vector space as the photo embedding.style_emb = embed_query_text(f"wearing a {style} style outfit", model, processor, device)query_emb = 0.75 * query_emb + 0.25 * style_embelse:skin_tone = manual_skinundertone = manual_undertonesentence = build_feature_sentence(skin_tone, undertone, style, gender, age_group, eye_color)query_emb = embed_query_text(sentence, model, processor, device)indices, rows, distances, tier = faiss_filtered_search(query_emb, faiss_index, df, top_k=3, exclude_idx=None,gender=gender or None, age_group=age_group or None,)if len(indices) == 0:return render_error_html("No matching looks were found in the catalog for these filters — ""try a different style, gender, or age group.")season, blurb, palette = derive_color_profile(skin_tone, undertone, eye_color)profile_html = render_profile_card_html(season, blurb, palette)scores = [max(0.0, min(1.0, 1.0 - d / 2.0)) for d in distances]look_cards = [render_look_card_html(i + 1, rows.iloc[i], round(scores[i] * 100))for i in range(len(rows))]extra_html = ""if want_caption:caption = generate_caption(rows.iloc[0])if caption:extra_html = render_caption_html(caption)note = Noneif tier == 2:note = "We broadened the search beyond the exact age group to find your best matches."elif tier == 3:note = "We expanded the search beyond your filters so you still get great matches."return extra_html + render_results_html(profile_html, look_cards, note=note)except Exception as e:traceback.print_exc()return render_error_html(f"{type(e).__name__}: {e}")def toggle_mode(mode):is_photo = str(mode).startswith("📷")return gr.update(visible=is_photo), gr.update(visible=not is_photo)theme = gr.themes.Soft(primary_hue=gr.themes.colors.rose,secondary_hue=gr.themes.colors.green,neutral_hue=gr.themes.colors.stone,font=gr.themes.GoogleFont("Inter"),font_mono=gr.themes.GoogleFont("Inter"),).set(# Page + panel backgrounds — soft off-white / cream, no harsh whites or greysbody_background_fill="#FDFBF7",body_background_fill_dark="#FDFBF7",block_background_fill="#FFFFFF",block_background_fill_dark="#FFFFFF",block_border_color="#EEEEEE",block_border_color_dark="#EEEEEE",block_radius="20px",container_radius="20px",block_shadow="0px 10px 30px rgba(0,0,0,0.04)",block_label_text_color="#948D80",block_label_text_color_dark="#948D80",block_label_text_weight="500",block_title_text_color="#1A1A1A",block_title_text_color_dark="#1A1A1A",panel_background_fill="#FFFFFF",panel_background_fill_dark="#FFFFFF",# Inputs (dropdowns, image upload, textboxes) — rounded, cream, soft pastelinput_background_fill="#FDFBF7",input_background_fill_dark="#FDFBF7",input_border_color="#EAE6DD",input_border_color_dark="#EAE6DD",input_border_color_focus="#C48793",input_radius="14px",checkbox_border_radius="8px",checkbox_background_color="#FDFBF7",checkbox_background_color_selected="#C48793",checkbox_border_color_selected="#C48793",# Buttons — solid charcoal pill, smooth hover liftbutton_primary_background_fill="#1A1A1A",button_primary_background_fill_hover="#333333",button_primary_text_color="#FFFFFF",button_primary_border_color="#1A1A1A",button_large_radius="999px",button_medium_radius="999px",button_small_radius="999px",button_transition="all 0.2s ease",)with gr.Blocks(css=CUSTOM_CSS, theme=theme, title="Personal Style Matcher") as demo:gr.HTML('<div class="fs-app-title">✨ Personal Style Matcher</div>''<div class="fs-app-tag">Find your color profile and your top 3 matched ''looks from our personal style dataset.</div>')with gr.Row():with gr.Column(scale=1):mode = gr.Radio(["📷 Upload My Photo", "🎛️ Manual Selection"],value="🎛️ Manual Selection",label="How would you like to start?",)with gr.Group(visible=False) as photo_group:photo = gr.Image(label="Upload a clear, front-facing photo", type="pil")photo_skin_override = gr.Dropdown([AUTO_DETECT_LABEL] + skin_tone_choices,value=AUTO_DETECT_LABEL,label="Skin tone (auto-detected — override if needed)",)photo_undertone_override = gr.Dropdown([AUTO_DETECT_LABEL] + undertone_choices,value=AUTO_DETECT_LABEL,label="Undertone (auto-detected — override if needed)",)with gr.Group(visible=True) as manual_group:manual_skin = gr.Dropdown(skin_tone_choices, value=skin_tone_choices[0], label="Skin Tone")manual_undertone = gr.Dropdown(undertone_choices, value=undertone_choices[0], label="Undertone")style = gr.Dropdown(style_choices, value=style_choices[0], label="Clothing Style")with gr.Row():gender = gr.Dropdown(gender_choices, value=gender_choices[0], label="Gender")age_group = gr.Dropdown(age_choices, value=age_choices[0], label="Age Group")eye_color = gr.Dropdown(EYE_COLOR_CHOICES, value=EYE_COLOR_CHOICES[0], label="Eye Color")want_caption = gr.Checkbox(label="✨ Add an AI stylist note (small GenAI text model)", value=False)submit_btn = gr.Button("Find My Looks", variant="primary", size="lg")with gr.Column(scale=2):output_html = gr.HTML(value=render_placeholder_html())mode.change(toggle_mode, inputs=mode, outputs=[photo_group, manual_group])predict_inputs = [mode, photo, photo_skin_override, photo_undertone_override,manual_skin, manual_undertone, style, gender, age_group,eye_color, want_caption,]submit_btn.click(predict, inputs=predict_inputs, outputs=output_html)if quickstarts:example_rows = [["🎛️ Manual Selection", None, AUTO_DETECT_LABEL, AUTO_DETECT_LABEL,qs["skin_tone"], qs["undertone"], qs["style"], qs["gender"],qs["age_group"], qs["eye_color"], False,]for qs in quickstarts]gr.Examples(examples=example_rows,inputs=predict_inputs,outputs=output_html,fn=predict,run_on_click=True,cache_examples=False,label="✨ Quick Starters — click one to see it in action",)return demo# =============================================================================# Entry point# =============================================================================if __name__ == "__main__":df, images = load_catalog()clip_model, clip_processor, device = load_embedding_model()faiss_index = build_faiss_index(df, images, clip_model, clip_processor, device)demo = build_demo(df, clip_model, clip_processor, faiss_index, device)demo.queue().launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742 unmodified lines277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364import subprocess, syssubprocess.check_call([sys.executable, "-m", "pip", "install", "-q","gradio", "transformers", "torch", "faiss-cpu", "datasets","pandas", "numpy", "pillow", "huggingface_hub"])import gradio as grimport numpy as npimport pandas as pdimport torchimport faissimport urllib.parseimport osimport hashlibimport colorsysfrom PIL import Imagefrom transformers import AutoProcessor, AutoModelfrom huggingface_hub import hf_hub_download# ── Load CLIP model ───────────────────────────────────────────────────────────print("Loading CLIP model...")CLIP_ID = "openai/clip-vit-base-patch32"processor = AutoProcessor.from_pretrained(CLIP_ID)clip_model = AutoModel.from_pretrained(CLIP_ID).eval()print("CLIP ready.")# ── Load embeddings + metadata from Space files ───────────────────────────────print("Loading embeddings and metadata...")EMB_PATH = hf_hub_download(repo_id="lihicarmeli/LookMatch", filename="final_image_embeddings.npy", repo_type="space")META_PATH = hf_hub_download(repo_id="lihicarmeli/LookMatch", filename="catalog_metadata.parquet", repo_type="space")image_embeddings = np.load(EMB_PATH).astype("float32")df = pd.read_parquet(META_PATH)# Build FAISS indexdimension = image_embeddings.shape[1]faiss_index = faiss.IndexFlatL2(dimension)emb_norm = image_embeddings.copy()faiss.normalize_L2(emb_norm)faiss_index.add(emb_norm)print(f"FAISS index ready — {faiss_index.ntotal} items.")# ── Shop URL builder ──────────────────────────────────────────────────────────RETAILERS = ["zara", "hm", "asos", "mango", "shein"]RETAILER_URLS = {"zara": "https://www.zara.com/us/en/search?searchTerm={query}","hm": "https://www2.hm.com/en_us/search-results.html?q={query}","asos": "https://www.asos.com/us/search/?q={query}","mango": "https://shop.mango.com/us/en/search?kw={query}","shein": "https://us.shein.com/pdsearch/{query}/",}def shop_url(query, retailer="asos"):q = urllib.parse.quote_plus(str(query))return RETAILER_URLS.get(retailer, RETAILER_URLS["asos"]).format(query=q)# ── Color Guardrail: Filter out any orange tones from UI ──────────────────────def clean_hex_color(hex_str):"""Ensures hex is valid and completely overrides any orange/tangerine shades to premium warm tones."""h_str = str(hex_str).strip().lower()if not h_str.startswith("#"):h_str = "#" + h_str# Standard orange/terracotta overrides to beautiful deep golds or warm camelsorange_fallbacks = {"#ff6b1a": "#C9A876", "#ff7f50": "#D4AF37", "#e8722c": "#9C8170","#cb6015": "#8B5A2B", "#f28500": "#C9A876", "#c0654d": "#AF6E4D"}if h_str in orange_fallbacks:return orange_fallbacks[h_str]# Dynamic check if color falls into orange hue spectrumif len(h_str) == 7:try:r = int(h_str[1:3], 16) / 255.0g = int(h_str[3:5], 16) / 255.0b = int(h_str[5:7], 16) / 255.0h, l, s = colorsys.rgb_to_hls(r, g, b)# Orange spectrum is roughly between 0.04 and 0.12 in Python's colorsysif 0.03 <= h <= 0.13:h += 0.25 # Safely shift to soft sage greenr, g, b = colorsys.hls_to_rgb(h, 0.65, 0.55)return "#{:02X}{:02X}{:02X}".format(int(r * 255), int(g * 255), int(b * 255))except:passreturn hex_str# ── Embed image with CLIP ─────────────────────────────────────────────────────@torch.no_grad()def embed_image(pil_image):inputs = processor(images=pil_image, return_tensors="pt")emb = clip_model.get_image_features(**inputs)if hasattr(emb, "last_hidden_state"):emb = emb.last_hidden_state[:, 0, :]emb = emb / emb.norm(p=2, dim=-1, keepdim=True)return emb.detach().numpy().astype("float32")# ── Embed text query with CLIP ────────────────────────────────────────────────@torch.no_grad()def embed_text(text):inputs = processor(text=[text], return_tensors="pt", padding=True, truncation=True)emb = clip_model.get_text_features(**inputs)if hasattr(emb, "last_hidden_state"):emb = emb.last_hidden_state[:, 0, :]emb = emb / emb.norm(p=2, dim=-1, keepdim=True)return emb.detach().numpy().astype("float32")# ── FAISS search ──────────────────────────────────────────────────────────────def faiss_search(query_emb, top_k=3, exclude_idx=None):q = query_emb.copy()faiss.normalize_L2(q)distances, indices = faiss_index.search(q, top_k + 5)results = []for idx, dist in zip(indices[0], distances[0]):if idx == -1:continueif exclude_idx is not None and idx == exclude_idx:continueresults.append((int(idx), float(dist)))if len(results) >= top_k:breakreturn results# ── Pill row HTML ─────────────────────────────────────────────────────────────SKIN_HEX = {"fair":"#F8DFC0","light":"#E8C99A","medium":"#C68642","olive":"#8D6346","tan":"#7B4F2E","dark":"#3B1F0E","deep":"#2A1208"}def pill(label, color, active=False):border = "1px solid var(--gold)" if active else "1.5px solid var(--hairline)"bg = "var(--gold-soft)" if active else "#FFFFFF"tcol = "var(--charcoal)" if active else "var(--text-muted)"return f'''<span class="fs-pill" style="border:{border}; background:{bg}; color:{tcol};"><span class="fs-pill-dot" style="background:{clean_hex_color(color)};"></span><span>{label}</span></span>'''# ── Build result HTML ─────────────────────────────────────────────────────────def build_result(matches, skin_tone=None, undertone=None, style=None):if not matches:return "<p class='fs-placeholder'>No matches found.</p>"# Feature pillsfeature_html = ""if skin_tone:col = SKIN_HEX.get(str(skin_tone).lower().split()[0], "#C19A6B")feature_html += f'<div class="fs-feature-row"><span class="fs-feature-title">Skin</span>{pill(skin_tone, col, True)}</div>'if undertone:feature_html += f'<div class="fs-feature-row"><span class="fs-feature-title">Undertone</span>{pill(undertone, "#D4B896", True)}</div>'if style:feature_html += f'<div class="fs-feature-row"><span class="fs-feature-title">Style</span>{pill(style, "#C8A2C8", True)}</div>'# Outfit cardscards = ""for rank, (idx, score) in enumerate(matches):row = df.iloc[idx]skin = row.get("skin_tone", "")rec_col = row.get("recommended_colors", "")top = row.get("outfit_top", "Top")bottom = row.get("outfit_bottom", "Bottom")shoes = row.get("outfit_shoes", "Shoes")acc = row.get("outfit_accessory", "Accessory")styp = row.get("style_preference", "")pri_col = row.get("primary_color", "#C19A6B")sec_col = row.get("secondary_color", "#BBA898")def safe_hex(c):c = str(c).strip()if c.startswith("#") and len(c) in [4,7]: return clean_hex_color(c)return "#C19A6B"ph = safe_hex(pri_col)sh = safe_hex(sec_col)items = [("TOP", top, ph),("BOTTOM", bottom, sh),("SHOES", shoes, ph),("ACCESSORY", acc, sh),]item_html = ""for itype, iname, ihex in items:item_html += f'''<div class="fs-component"><div class="fs-component-swatch" style="background:{ihex}15;"><span class="fs-swatch-dot" style="background:{ihex};"></span></div><div class="fs-component-body"><div class="fs-component-label">{itype}</div><div class="fs-component-name">{html.escape(str(iname))}</div><a class="fs-shop-btn" href="{shop_url(iname)}" target="_blank" rel="noopener noreferrer">Shop ↗</a></div></div>'''match_pct = max(0, int((1 - score) * 100))cards += f'''<div class="fs-look-card"><div class="fs-look-head"><span class="fs-look-avatar" style="background:{ph};"></span><div><div class="fs-look-title">Look #{rank+1}</div><div class="fs-look-sub">{styp} · {skin} skin · {match_pct}% match</div></div></div>{item_html}<div class="fs-colors-footer">Recommended colors: {rec_col}</div></div>'''return f"""<div class="fs-result-wrapper">{"" if not feature_html else f'''<div class="fs-profile-card"><div class="fs-profile-eyebrow">Detected Features</div><div class="fs-chip-row" style="margin-top:10px;">{feature_html}</div></div>'''}<div class="fs-header"><div class="fs-header-decoration"></div><div class="fs-header-eyebrow">YOUR MATCHED LOOKS</div><div class="fs-header-sub">Top {len(matches)} outfits from your personal style dataset</div></div><div class="fs-grid">{cards}</div></div>"""# ── Render: photo tab ─────────────────────────────────────────────────────────def render_photo(image):if image is None:return "<p class='fs-placeholder'>Please upload a photo first.</p>"try:pil = Image.open(image).convert("RGB")emb = embed_image(pil)matches = faiss_search(emb, top_k=3)if matches:row = df.iloc[matches[0][0]]skin = row.get("skin_tone","")undertone = row.get("undertone","")style = row.get("style_preference","")else:skin = undertone = style = ""return build_result(matches, skin, undertone, style)except Exception as e:return f"<div class='fs-error'><div class='fs-error-title'>Error</div><div class='fs-error-msg'>{str(e)[:300]}</div></div>"# ── Render: manual tab ────────────────────────────────────────────────────────def render_manual(skin, undertone, style):query = f"a person with {skin} skin tone and {undertone} undertone wearing {style} style outfit"emb = embed_text(query)matches = faiss_search(emb, top_k=3)return build_result(matches, skin, undertone, style)# ── Premium Luxury CSS ────────────────────────────────────────────────────────CSS = """@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@200;300;400;500;600;700&family=Inter:wght@400;500;600;700&display=swap');* { box-sizing: border-box; }body {font-family: 'Inter', system-ui, sans-serif !important;background: #FDFBF7 !important;}.gradio-container {max-width: 960px !important;margin: auto !important;background: #FDFBF7 !important;}/* Custom UI Variables */.fs-result-wrapper {--cream: #FDFBF7;--white: #FFFFFF;--charcoal: #1A1A1A;2 unmodified lines--hairline: #EEEEEE;--rose: #C48793;--rose-soft: #F6ECEE;--sage-soft: #EFF3EA;--gold: #C9A876;--gold-soft: #F8F1E4;}/* Tabs Styling */.tab-nav {border-bottom: 1px solid #EAE6DD !important;background: transparent !important;gap: 10px !important;}.tab-nav button {font-family: 'Montserrat', sans-serif !important;font-size: 13px !important;font-weight: 500 !important;letter-spacing: 0.1em !important;text-transform: uppercase !important;padding: 14px 28px !important;background: transparent !important;border: none !important;color: #948D80 !important;}.tab-nav button.selected {color: #1A1A1A !important;border-bottom: 2px solid #C9A876 !important;font-weight: 600 !important;}/* Inputs Styling */.fs-app-title {font-family: 'Montserrat', sans-serif;font-weight: 400;font-size: 34px;letter-spacing: 0.05em;color: #1A1A1A;margin-bottom: 6px;text-transform: uppercase;}/* Main Action Button */button.lg {background: #1A1A1A !important;color: #FFFFFF !important;border: 1px solid #1A1A1A !important;border-radius: 999px !important;font-family: 'Montserrat', sans-serif !important;font-weight: 600 !important;font-size: 12px !important;letter-spacing: 0.15em !important;text-transform: uppercase !important;padding: 14px !important;transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1) !important;box-shadow: 0px 4px 12px rgba(0,0,0,0.05) !important;}button.lg:hover {background: #3A3A3A !important;transform: translateY(-1px) !important;}/* Output Cards & Structural Grid */.fs-placeholder {color: #948D80; font-size: 14px; padding: 64px 24px; text-align: center;border: 1px solid #EEEEEE; border-radius: 24px; background: #FFFFFF;letter-spacing: 0.02em; box-shadow: 0px 10px 30px rgba(0,0,0,0.01);}.fs-profile-card {background: linear-gradient(135deg, #F6ECEE 0%, #F8F1E4 100%);border: 1px solid #EEEEEE; border-radius: 24px; padding: 24px 28px;margin-bottom: 20px; box-shadow: 0px 12px 30px rgba(0,0,0,0.02);}.fs-profile-eyebrow {color: #C48793; font-weight: 600; font-size: 11px; letter-spacing: .18em;text-transform: uppercase;}.fs-feature-row { display: flex; align-items: center; margin-bottom: 8px; }.fs-feature-row:last-child { margin-bottom: 0; }.fs-feature-title { font-size: 11px; font-weight: 600; color: #948D80; text-transform: uppercase; letter-spacing: .1em; width: 90px; }.fs-pill {display: inline-flex; align-items: center; gap: 8px; padding: 6px 14px;border-radius: 999px; font-size: 12px; font-weight: 500; letter-spacing: 0.02em;}.fs-pill-dot { width: 14px; height: 14px; border-radius: 50%; display: inline-block; box-shadow: 0 0 0 2px
app.py+314-970