Update app.py
Browse files
app.py
CHANGED
|
@@ -1,612 +1,274 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
A Gradio app that recommends fashion looks from the "Fashion Stylist
|
| 6 |
-
Multimodal v2" catalog (lihicarmeli/fashion-stylist-multimodal-v2 on the
|
| 7 |
-
Hugging Face Hub), using the exact same engine validated in Part 3:
|
| 8 |
-
|
| 9 |
-
* Embedding model : openai/clip-vit-base-patch32 (the model selected
|
| 10 |
-
after the multi-criteria evaluation in Part 3 — best speed/size/effort
|
| 11 |
-
trade-off, within 1.3 purity points of the larger CLIP variant).
|
| 12 |
-
* Vector search : a FAISS flat-L2 index over the catalog's CLIP image
|
| 13 |
-
embeddings, with the same 3-tier demographic fallback filter used in
|
| 14 |
-
the notebook (strict gender+age -> gender-only -> fully open search).
|
| 15 |
-
* GenAI component : an optional one-line AI stylist note generated by
|
| 16 |
-
a small instruction-tuned LM (Qwen/Qwen2.5-0.5B-Instruct), reusing the
|
| 17 |
-
exact prompt pattern from Part 4.
|
| 18 |
-
|
| 19 |
-
Two ways in, one engine:
|
| 20 |
-
Mode A — upload a photo. A lightweight heuristic samples the face region
|
| 21 |
-
to estimate a skin tone / undertone, and the photo itself is
|
| 22 |
-
embedded with CLIP's image encoder for the catalog search.
|
| 23 |
-
Mode B — pick your features from dropdowns. A natural-language sentence
|
| 24 |
-
is built from those features and embedded with CLIP's text
|
| 25 |
-
encoder, landing in the exact same vector space as the photos.
|
| 26 |
-
|
| 27 |
-
Deploy: push this file + requirements.txt to a new Hugging Face Space using
|
| 28 |
-
the "Gradio" SDK. No local data or model files are needed — both the
|
| 29 |
-
dataset and the embedding model are streamed directly from the Hub.
|
| 30 |
-
"""
|
| 31 |
-
|
| 32 |
-
import os
|
| 33 |
-
import html
|
| 34 |
-
import hashlib
|
| 35 |
-
import colorsys
|
| 36 |
-
import traceback
|
| 37 |
-
import urllib.parse
|
| 38 |
|
|
|
|
| 39 |
import numpy as np
|
|
|
|
| 40 |
import torch
|
| 41 |
-
|
| 42 |
import faiss
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
import
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
#
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
| 77 |
"hm": "https://www2.hm.com/en_us/search-results.html?q={query}",
|
| 78 |
-
"asos": "https://www.asos.com/us/
|
| 79 |
"mango": "https://shop.mango.com/us/en/search?kw={query}",
|
| 80 |
"shein": "https://us.shein.com/pdsearch/{query}/",
|
| 81 |
}
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
for phrase in sorted(NAMED_COLOR_HEX, key=len, reverse=True):
|
| 121 |
-
if " " in phrase and phrase in t:
|
| 122 |
-
return NAMED_COLOR_HEX[phrase]
|
| 123 |
-
for word in t.replace(",", " ").split():
|
| 124 |
-
if word in NAMED_COLOR_HEX:
|
| 125 |
-
return NAMED_COLOR_HEX[word]
|
| 126 |
-
return None
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
def text_to_pastel_hex(text):
|
| 130 |
-
"""Deterministic fallback color: hash the text into a pleasant, distinct hue."""
|
| 131 |
-
digest = hashlib.md5(str(text).encode("utf-8")).hexdigest()
|
| 132 |
-
hue = int(digest[:4], 16) / 65535.0
|
| 133 |
-
r, g, b = colorsys.hls_to_rgb(hue, 0.55, 0.55)
|
| 134 |
-
return "#{:02X}{:02X}{:02X}".format(int(r * 255), int(g * 255), int(b * 255))
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def swatch_color_for(*texts):
|
| 138 |
-
"""Pick the first resolvable color among the given text fields, or fall back
|
| 139 |
-
to a stable hashed pastel so the same item always gets the same swatch."""
|
| 140 |
-
for t in texts:
|
| 141 |
-
hexcode = resolve_color_hex(t)
|
| 142 |
-
if hexcode:
|
| 143 |
-
return hexcode
|
| 144 |
-
joined = " ".join(str(t) for t in texts if t)
|
| 145 |
-
return text_to_pastel_hex(joined or "style")
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
# =============================================================================
|
| 149 |
-
# Seasonal color profile (display-only "stylist" layer on top of the catalog)
|
| 150 |
-
# =============================================================================
|
| 151 |
-
|
| 152 |
-
SEASON_INFO = {
|
| 153 |
-
"Spring": {
|
| 154 |
-
"blurb": "Warm and light — your glow loves clear, fresh colors with a golden undertone.",
|
| 155 |
-
"palette": [("Coral", "#FF7F50"), ("Peach", "#FFCBA4"), ("Golden Yellow", "#F5C518"),
|
| 156 |
-
("Grass Green", "#3DA35D"), ("Turquoise", "#30D5C8"), ("Ivory", "#FFFFF0")],
|
| 157 |
-
},
|
| 158 |
-
"Autumn": {
|
| 159 |
-
"blurb": "Warm and rich — earthy, spiced tones make your natural warmth shine.",
|
| 160 |
-
"palette": [("Rust", "#9E4624"), ("Olive", "#708238"), ("Mustard", "#C9A227"),
|
| 161 |
-
("Chocolate Brown", "#5A3A22"), ("Burnt Orange", "#CB6015"), ("Forest Green", "#1B4332")],
|
| 162 |
-
},
|
| 163 |
-
"Summer": {
|
| 164 |
-
"blurb": "Cool and soft — muted, misty colors flatter your cool undertone beautifully.",
|
| 165 |
-
"palette": [("Powder Blue", "#B0E0E6"), ("Lavender", "#B497D6"), ("Rose Pink", "#D17B96"),
|
| 166 |
-
("Soft Teal", "#5F9EA0"), ("Dusty Mauve", "#A97C8A"), ("Slate Gray", "#6E7B8B")],
|
| 167 |
-
},
|
| 168 |
-
"Winter": {
|
| 169 |
-
"blurb": "Cool and deep — bold, high-contrast colors match your striking cool undertone.",
|
| 170 |
-
"palette": [("True Red", "#C8102E"), ("Royal Blue", "#4169E1"), ("Emerald", "#2E8B57"),
|
| 171 |
-
("Black", "#1A1A1A"), ("White", "#FFFFFF"), ("Magenta", "#C2185B")],
|
| 172 |
-
},
|
| 173 |
-
"Soft Spring": {
|
| 174 |
-
"blurb": "A gentle warm-neutral mix — soft, peachy tones suit you better than stark contrast.",
|
| 175 |
-
"palette": [("Soft Peach", "#F2C6A0"), ("Honey", "#E2B765"), ("Sage Green", "#9CAF88"),
|
| 176 |
-
("Camel", "#C19A6B"), ("Warm Ivory", "#F5EFE0"), ("Apricot", "#FBCEB1")],
|
| 177 |
-
},
|
| 178 |
-
"Soft Autumn": {
|
| 179 |
-
"blurb": "A muted warm-neutral mix — soft earth tones bring out your warmth without overpowering it.",
|
| 180 |
-
"palette": [("Terracotta", "#C0654D"), ("Sage", "#8A9A5B"), ("Caramel", "#AF6E4D"),
|
| 181 |
-
("Warm Taupe", "#9C8170"), ("Moss", "#6B7A4F"), ("Dusty Gold", "#B79766")],
|
| 182 |
-
},
|
| 183 |
-
"Soft Summer": {
|
| 184 |
-
"blurb": "A gentle cool-neutral mix — soft, dusty colors are more flattering than bright ones.",
|
| 185 |
-
"palette": [("Dusty Rose", "#C68893"), ("Soft Lilac", "#C6B4D6"), ("Sage Gray", "#A6AD9E"),
|
| 186 |
-
("Mauve", "#9C7A8A"), ("Soft Denim", "#7C93A8"), ("Pearl Gray", "#C9C5C0")],
|
| 187 |
-
},
|
| 188 |
-
"Soft Winter": {
|
| 189 |
-
"blurb": "A muted cool-neutral mix — clear but gentle colors balance your cool undertone.",
|
| 190 |
-
"palette": [("Plum", "#8E4585"), ("Slate Blue", "#5B6C8F"), ("Charcoal", "#3B3B3B"),
|
| 191 |
-
("Berry", "#7A2E4D"), ("Icy Pink", "#E7C6CE"), ("Steel Gray", "#71797E")],
|
| 192 |
-
},
|
| 193 |
-
}
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
def skin_depth_flag(skin_tone):
|
| 197 |
-
"""Bucket a skin-tone label into 'light' or 'deep' using a best-effort ordering."""
|
| 198 |
-
s = str(skin_tone).lower().strip()
|
| 199 |
-
if s in SKIN_DEPTH_ORDER:
|
| 200 |
-
idx = SKIN_DEPTH_ORDER.index(s)
|
| 201 |
-
midpoint = len(SKIN_DEPTH_ORDER) / 2
|
| 202 |
-
else:
|
| 203 |
-
idx, midpoint = 1, 2 # unseen label -> assume mid-range
|
| 204 |
-
return "deep" if idx >= midpoint else "light"
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
def derive_color_profile(skin_tone, undertone, eye_color=None):
|
| 208 |
-
"""Map (skin tone, undertone, eye color) onto a simplified 4/8-season
|
| 209 |
-
color-analysis bucket. This is a styling heuristic, not a clinical tool —
|
| 210 |
-
it gives the user a friendly, explainable color story to go with their
|
| 211 |
-
matched looks."""
|
| 212 |
-
undertone = str(undertone).lower().strip()
|
| 213 |
-
depth = skin_depth_flag(skin_tone)
|
| 214 |
-
eye = str(eye_color).lower().strip() if eye_color else ""
|
| 215 |
-
|
| 216 |
-
if undertone == "warm":
|
| 217 |
-
season = "Spring" if depth == "light" else "Autumn"
|
| 218 |
-
elif undertone == "cool":
|
| 219 |
-
season = "Summer" if depth == "light" else "Winter"
|
| 220 |
-
else:
|
| 221 |
-
leans_warm = eye in WARM_EYES
|
| 222 |
-
leans_cool = eye in COOL_EYES
|
| 223 |
-
if depth == "light":
|
| 224 |
-
season = "Soft Summer" if leans_cool and not leans_warm else "Soft Spring"
|
| 225 |
-
else:
|
| 226 |
-
season = "Soft Winter" if leans_cool and not leans_warm else "Soft Autumn"
|
| 227 |
-
|
| 228 |
-
info = SEASON_INFO.get(season, SEASON_INFO["Spring"])
|
| 229 |
-
return season, info["blurb"], info["palette"]
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
# =============================================================================
|
| 233 |
-
# Skin tone / undertone estimation from an uploaded photo (Mode A)
|
| 234 |
-
# =============================================================================
|
| 235 |
-
|
| 236 |
-
def estimate_skin_tone_undertone(pil_image, available_skin_tones):
|
| 237 |
-
"""A lightweight, transparent heuristic — NOT a clinical skin-tone
|
| 238 |
-
classifier. It samples a centered, face-shaped region of the photo, keeps
|
| 239 |
-
only pixels that look skin-like in YCbCr space, and buckets the resulting
|
| 240 |
-
average color by brightness (-> skin tone bucket) and red/blue balance
|
| 241 |
-
(-> warm / cool / neutral undertone)."""
|
| 242 |
-
img = pil_image.convert("RGB").resize((160, 160))
|
| 243 |
-
arr = np.asarray(img).astype(np.float32)
|
| 244 |
-
|
| 245 |
-
h, w, _ = arr.shape
|
| 246 |
-
y0, y1 = int(h * 0.15), int(h * 0.75)
|
| 247 |
-
x0, x1 = int(w * 0.30), int(w * 0.70)
|
| 248 |
-
crop = arr[y0:y1, x0:x1, :]
|
| 249 |
-
|
| 250 |
-
r, g, b = crop[..., 0], crop[..., 1], crop[..., 2]
|
| 251 |
-
y_ = 0.299 * r + 0.587 * g + 0.114 * b
|
| 252 |
-
cb = 128 - 0.168736 * r - 0.331264 * g + 0.5 * b
|
| 253 |
-
cr = 128 + 0.5 * r - 0.418688 * g - 0.081312 * b
|
| 254 |
-
skin_mask = (y_ > 60) & (cb > 85) & (cb < 135) & (cr > 135) & (cr < 180)
|
| 255 |
-
|
| 256 |
-
pixels = crop.reshape(-1, 3) if skin_mask.sum() < 50 else crop[skin_mask]
|
| 257 |
-
mean_rgb = pixels.mean(axis=0)
|
| 258 |
-
brightness = float(0.299 * mean_rgb[0] + 0.587 * mean_rgb[1] + 0.114 * mean_rgb[2])
|
| 259 |
-
|
| 260 |
-
available = {str(s).lower() for s in available_skin_tones}
|
| 261 |
-
ordered = [s for s in SKIN_DEPTH_ORDER if s in available] or list(available_skin_tones)
|
| 262 |
-
n = len(ordered)
|
| 263 |
-
frac = 1.0 - min(max(brightness / 255.0, 0.0), 1.0) # darker photo -> higher frac
|
| 264 |
-
bucket_idx = min(int(frac * n), n - 1) if n else 0
|
| 265 |
-
skin_tone_guess = ordered[bucket_idx] if n else "medium"
|
| 266 |
-
|
| 267 |
-
diff = float(mean_rgb[0] - mean_rgb[2]) # R - B
|
| 268 |
-
if diff > 8:
|
| 269 |
-
undertone_guess = "warm"
|
| 270 |
-
elif diff < -8:
|
| 271 |
-
undertone_guess = "cool"
|
| 272 |
-
else:
|
| 273 |
-
undertone_guess = "neutral"
|
| 274 |
-
|
| 275 |
-
swatch_hex = "#{:02X}{:02X}{:02X}".format(
|
| 276 |
-
*[int(min(max(c, 0), 255)) for c in mean_rgb]
|
| 277 |
-
)
|
| 278 |
-
return skin_tone_guess, undertone_guess, swatch_hex
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
# =============================================================================
|
| 282 |
-
# Query building & embedding (mirrors the validated Part 3 pipeline exactly)
|
| 283 |
-
# =============================================================================
|
| 284 |
-
|
| 285 |
-
def build_feature_sentence(skin_tone, undertone, style_preference, gender=None,
|
| 286 |
-
age_group=None, eye_color=None):
|
| 287 |
-
"""Path B: turn typed-in features into a sentence in the same vector
|
| 288 |
-
space CLIP's text encoder was trained on, mirroring Part 3's
|
| 289 |
-
build_feature_sentence()."""
|
| 290 |
-
descriptor = " ".join(p for p in [age_group, gender] if p) or "person"
|
| 291 |
-
sentence = (
|
| 292 |
-
f"a {descriptor} with {skin_tone} skin tone and {undertone} undertone, "
|
| 293 |
-
f"wearing a {style_preference} style outfit"
|
| 294 |
-
)
|
| 295 |
-
if eye_color:
|
| 296 |
-
sentence += f", {str(eye_color).lower()} eyes"
|
| 297 |
-
return sentence
|
| 298 |
-
|
| 299 |
-
|
| 300 |
@torch.no_grad()
|
| 301 |
-
def
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
|
|
|
| 309 |
@torch.no_grad()
|
| 310 |
-
def
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
return
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
def
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
def _component_html(label, text, retailer, gender):
|
| 420 |
-
hexcode = swatch_color_for(text)
|
| 421 |
-
link = component_shop_link(retailer, text, gender)
|
| 422 |
-
return f"""
|
| 423 |
-
<div class="fs-component">
|
| 424 |
-
<div class="fs-component-swatch"><span class="fs-swatch-dot" style="background:{hexcode}"></span></div>
|
| 425 |
-
<div class="fs-component-body">
|
| 426 |
-
<div class="fs-component-label">{label}</div>
|
| 427 |
-
<div class="fs-component-name">{html.escape(str(text))}</div>
|
| 428 |
-
<a class="fs-shop-btn" href="{link}" target="_blank" rel="noopener noreferrer">Shop ↗</a>
|
| 429 |
-
</div>
|
| 430 |
-
</div>
|
| 431 |
-
"""
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
def render_look_card_html(look_number, row, score_pct):
|
| 435 |
-
avatar_hex = swatch_color_for(row.get("primary_color"), row.get("secondary_color"))
|
| 436 |
-
gender = row.get("gender")
|
| 437 |
-
|
| 438 |
-
components = [
|
| 439 |
-
("TOP", row.get("outfit_top", ""), COMPONENT_RETAILERS["TOP"]),
|
| 440 |
-
("BOTTOM", row.get("outfit_bottom", ""), COMPONENT_RETAILERS["BOTTOM"]),
|
| 441 |
-
("SHOES", row.get("outfit_shoes", ""), COMPONENT_RETAILERS["SHOES"]),
|
| 442 |
-
("ACCESSORY", row.get("outfit_accessory", ""), COMPONENT_RETAILERS["ACCESSORY"]),
|
| 443 |
-
]
|
| 444 |
-
comp_html = "".join(_component_html(label, text, retailer, gender)
|
| 445 |
-
for label, text, retailer in components)
|
| 446 |
-
|
| 447 |
-
style_pref = html.escape(str(row.get("style_preference", "")))
|
| 448 |
-
skin_tone = html.escape(str(row.get("skin_tone", "")))
|
| 449 |
-
colors_line = html.escape(str(row.get("recommended_colors", "")))
|
| 450 |
-
|
| 451 |
-
return f"""
|
| 452 |
-
<div class="fs-look-card">
|
| 453 |
-
<div class="fs-look-head">
|
| 454 |
-
<span class="fs-look-avatar" style="background:{avatar_hex}"></span>
|
| 455 |
-
<div>
|
| 456 |
-
<div class="fs-look-title">Look #{look_number}</div>
|
| 457 |
-
<div class="fs-look-sub">{style_pref} · {skin_tone} skin · {score_pct}% match</div>
|
| 458 |
-
</div>
|
| 459 |
-
</div>
|
| 460 |
-
{comp_html}
|
| 461 |
-
<div class="fs-colors-footer">Recommended colors: {colors_line}</div>
|
| 462 |
-
</div>
|
| 463 |
-
"""
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
def render_results_html(profile_html, look_cards_html_list, note=None):
|
| 467 |
-
cards = "".join(look_cards_html_list)
|
| 468 |
-
note_html = f'<div class="fs-note">{html.escape(note)}</div>' if note else ""
|
| 469 |
return f"""
|
| 470 |
-
<div class="fs-
|
| 471 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
<div class="fs-header">
|
| 473 |
<div class="fs-header-decoration"></div>
|
| 474 |
<div class="fs-header-eyebrow">YOUR MATCHED LOOKS</div>
|
| 475 |
-
<div class="fs-header-sub">Top
|
| 476 |
</div>
|
| 477 |
-
|
| 478 |
<div class="fs-grid">{cards}</div>
|
| 479 |
</div>
|
| 480 |
"""
|
| 481 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
<div class="fs-error-msg">{html.escape(str(message))}</div>
|
| 489 |
-
</div>
|
| 490 |
-
</div>
|
| 491 |
-
"""
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
def render_placeholder_html():
|
| 495 |
-
return """
|
| 496 |
-
<div class="fs-root">
|
| 497 |
-
<div class="fs-placeholder">
|
| 498 |
-
Upload a photo or pick your features, then press
|
| 499 |
-
<strong>“Find My Looks”</strong> to see your personal color profile
|
| 500 |
-
and your top 3 matched outfits.
|
| 501 |
-
</div>
|
| 502 |
-
</div>
|
| 503 |
-
"""
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
# =============================================================================
|
| 507 |
-
# Dataset & model loading
|
| 508 |
-
# =============================================================================
|
| 509 |
-
|
| 510 |
-
def order_choices(values, preferred_order):
|
| 511 |
-
"""Order dropdown choices using a sensible preferred order, falling back
|
| 512 |
-
to alphabetical for anything not in that list."""
|
| 513 |
-
vals = {str(v) for v in values}
|
| 514 |
-
ordered = [p for p in preferred_order if p in vals]
|
| 515 |
-
remaining = sorted(v for v in vals if v not in ordered)
|
| 516 |
-
return ordered + remaining
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
def load_catalog():
|
| 520 |
-
print(f"Loading dataset '{DATASET_REPO}' from the Hugging Face Hub...")
|
| 521 |
-
ds = load_dataset(DATASET_REPO)
|
| 522 |
-
train = ds["train"]
|
| 523 |
-
df = train.to_pandas()
|
| 524 |
-
images = [train[i]["image_improved"] for i in range(len(train))]
|
| 525 |
-
print(f"Catalog loaded: {len(df)} items, {len(df.columns)} columns.")
|
| 526 |
-
return df, images
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
def load_embedding_model():
|
| 530 |
-
print(f"Loading embedding model '{EMBED_MODEL_REPO}' from the Hugging Face Hub...")
|
| 531 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 532 |
-
processor = AutoProcessor.from_pretrained(EMBED_MODEL_REPO)
|
| 533 |
-
model = AutoModel.from_pretrained(EMBED_MODEL_REPO).to(device).eval()
|
| 534 |
-
print(f"Embedding model ready on device='{device}'.")
|
| 535 |
-
return model, processor, device
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
@torch.no_grad()
|
| 539 |
-
def embed_catalog_images(model, processor, images, device, batch_size=32):
|
| 540 |
-
embs = []
|
| 541 |
-
for i in range(0, len(images), batch_size):
|
| 542 |
-
batch = [im.convert("RGB") for im in images[i:i + batch_size]]
|
| 543 |
-
inputs = processor(images=batch, return_tensors="pt").to(device)
|
| 544 |
-
outputs = model.get_image_features(**inputs)
|
| 545 |
-
feats = outputs.pooler_output if hasattr(outputs, "pooler_output") else outputs
|
| 546 |
-
feats = feats / feats.norm(dim=-1, keepdim=True)
|
| 547 |
-
embs.append(feats.cpu().numpy())
|
| 548 |
-
print(f" embedded {min(i + batch_size, len(images))}/{len(images)} catalog images")
|
| 549 |
-
return np.vstack(embs).astype("float32")
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
def build_faiss_index(df, images, model, processor, device):
|
| 553 |
-
image_embeddings = None
|
| 554 |
-
if os.path.exists(EMBED_CACHE_PATH):
|
| 555 |
-
try:
|
| 556 |
-
cached = np.load(EMBED_CACHE_PATH)
|
| 557 |
-
if cached.shape[0] == len(df):
|
| 558 |
-
print("Loaded cached catalog embeddings from disk.")
|
| 559 |
-
image_embeddings = cached
|
| 560 |
-
except Exception as e:
|
| 561 |
-
print(f"Ignoring unreadable embedding cache: {e}")
|
| 562 |
-
|
| 563 |
-
if image_embeddings is None:
|
| 564 |
-
image_embeddings = embed_catalog_images(model, processor, images, device)
|
| 565 |
-
try:
|
| 566 |
-
np.save(EMBED_CACHE_PATH, image_embeddings)
|
| 567 |
-
except Exception as e:
|
| 568 |
-
print(f"Could not cache embeddings to disk (non-fatal): {e}")
|
| 569 |
-
|
| 570 |
-
dim = image_embeddings.shape[1]
|
| 571 |
-
index = faiss.IndexFlatL2(dim)
|
| 572 |
-
normalized = image_embeddings.copy()
|
| 573 |
-
faiss.normalize_L2(normalized)
|
| 574 |
-
index.add(normalized)
|
| 575 |
-
print(f"FAISS index ready with {index.ntotal} items (dim={dim}).")
|
| 576 |
-
return index
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
def pick_quickstarts(df, n=3):
|
| 580 |
-
"""Pick `n` real catalog rows covering distinct styles, to use as
|
| 581 |
-
1-click 'Quick Starter' examples with guaranteed-valid feature values."""
|
| 582 |
-
eye_cycle = ["Brown", "Hazel", "Blue"]
|
| 583 |
-
seen_styles, starters = set(), []
|
| 584 |
-
for _, row in df.iterrows():
|
| 585 |
-
style = row["style_preference"]
|
| 586 |
-
if style in seen_styles:
|
| 587 |
-
continue
|
| 588 |
-
seen_styles.add(style)
|
| 589 |
-
starters.append({
|
| 590 |
-
"skin_tone": row["skin_tone"],
|
| 591 |
-
"undertone": row["undertone"],
|
| 592 |
-
"style": style,
|
| 593 |
-
"gender": row["gender"],
|
| 594 |
-
"age_group": row["age_group"],
|
| 595 |
-
"eye_color": eye_cycle[len(starters) % len(eye_cycle)],
|
| 596 |
-
})
|
| 597 |
-
if len(starters) == n:
|
| 598 |
-
break
|
| 599 |
-
return starters
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
# =============================================================================
|
| 603 |
-
# Gradio app
|
| 604 |
-
# =============================================================================
|
| 605 |
-
|
| 606 |
-
CUSTOM_CSS = """
|
| 607 |
-
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@200;300;400;500;600;700&family=Inter:wght@400;500;600&display=swap');
|
| 608 |
|
| 609 |
-
|
|
|
|
| 610 |
--cream: #FDFBF7;
|
| 611 |
--white: #FFFFFF;
|
| 612 |
--charcoal: #1A1A1A;
|
|
@@ -615,406 +277,88 @@ CUSTOM_CSS = """
|
|
| 615 |
--hairline: #EEEEEE;
|
| 616 |
--rose: #C48793;
|
| 617 |
--rose-soft: #F6ECEE;
|
| 618 |
-
--sage: #9CAF88;
|
| 619 |
--sage-soft: #EFF3EA;
|
| 620 |
--gold: #C9A876;
|
| 621 |
--gold-soft: #F8F1E4;
|
| 622 |
-
max-width: 1120px;
|
| 623 |
-
margin: 0 auto;
|
| 624 |
-
font-family: 'Inter', system-ui, sans-serif;
|
| 625 |
-
color: var(--charcoal-soft);
|
| 626 |
-
}
|
| 627 |
-
|
| 628 |
-
.fs-app-title {
|
| 629 |
-
font-family: 'Montserrat', system-ui, sans-serif;
|
| 630 |
-
font-weight: 600;
|
| 631 |
-
font-size: 30px;
|
| 632 |
-
letter-spacing: 0.02em;
|
| 633 |
-
color: var(--charcoal);
|
| 634 |
-
margin-bottom: 4px;
|
| 635 |
-
}
|
| 636 |
-
.fs-app-tag { color: var(--text-muted); font-size: 14px; letter-spacing: 0.01em; margin-bottom: 6px; }
|
| 637 |
-
|
| 638 |
-
.fs-placeholder {
|
| 639 |
-
color: var(--text-muted); font-size: 14px; padding: 48px 24px; text-align: center;
|
| 640 |
-
border: 1px solid var(--hairline); border-radius: 25px; background: var(--white);
|
| 641 |
-
letter-spacing: 0.01em;
|
| 642 |
}
|
| 643 |
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
}
|
| 650 |
-
.
|
| 651 |
-
|
| 652 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 653 |
}
|
| 654 |
-
.
|
| 655 |
-
|
| 656 |
-
|
|
|
|
| 657 |
}
|
| 658 |
-
.fs-profile-blurb { color: var(--charcoal-soft); font-size: 14.5px; max-width: 620px; margin-bottom: 20px; line-height: 1.6; }
|
| 659 |
-
.fs-chip-row { display: flex; gap: 10px; flex-wrap: wrap; }
|
| 660 |
-
.fs-chip {
|
| 661 |
-
display: flex; align-items: center; gap: 8px; background: var(--white);
|
| 662 |
-
border: 1px solid var(--hairline); border-radius: 999px; padding: 7px 14px 7px 7px;
|
| 663 |
-
font-size: 12px; color: var(--charcoal-soft); letter-spacing: 0.02em;
|
| 664 |
-
box-shadow: 0px 4px 10px rgba(0,0,0,0.03);
|
| 665 |
-
}
|
| 666 |
-
.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); }
|
| 667 |
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
.fs-header-eyebrow {
|
| 678 |
-
color: var(--rose); font-weight: 600; font-size: 13px; letter-spacing: .18em;
|
| 679 |
-
text-transform: uppercase; margin-bottom: 8px; position: relative; z-index: 1;
|
| 680 |
}
|
| 681 |
-
.fs-header-sub { font-size: 15.5px; color: var(--text-muted); letter-spacing: 0.01em; position: relative; z-index: 1; }
|
| 682 |
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 686 |
}
|
| 687 |
-
.
|
| 688 |
-
|
| 689 |
-
|
| 690 |
}
|
| 691 |
-
.fs-caption-label { font-weight: 600; color: var(--charcoal); }
|
| 692 |
-
|
| 693 |
-
.fs-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
|
| 694 |
-
@media (max-width: 900px) { .fs-grid { grid-template-columns: 1fr; } }
|
| 695 |
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
.
|
| 701 |
-
display: flex; align-items: center; gap: 14px; margin-bottom: 18px;
|
| 702 |
-
padding-bottom: 18px; border-bottom: 1px solid var(--hairline);
|
| 703 |
-
}
|
| 704 |
-
.fs-look-avatar {
|
| 705 |
-
width: 50px; height: 50px; border-radius: 50%; flex-shrink: 0;
|
| 706 |
-
border: 2px solid var(--gold); box-shadow: 0 4px 10px rgba(0,0,0,0.08);
|
| 707 |
-
display: inline-block;
|
| 708 |
-
}
|
| 709 |
-
.fs-look-title {
|
| 710 |
-
font-family: 'Montserrat', sans-serif; font-weight: 300; font-size: 22px;
|
| 711 |
-
letter-spacing: 0.01em; color: var(--charcoal);
|
| 712 |
}
|
| 713 |
-
.fs-look-sub { color: var(--text-muted); font-size: 13px; margin-top: 3px; letter-spacing: 0.01em; }
|
| 714 |
|
| 715 |
-
.fs-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
.fs-component:hover { box-shadow: 0px 6px 18px rgba(0,0,0,0.05); }
|
| 720 |
-
.fs-component:last-child { margin-bottom: 0; }
|
| 721 |
-
.fs-component-swatch { background: var(--cream); height: 68px; display: flex; align-items: center; justify-content: center; }
|
| 722 |
-
.fs-swatch-dot {
|
| 723 |
-
width: 36px; height: 36px; border-radius: 50%; display: inline-block;
|
| 724 |
-
box-shadow: 0 0 0 3px var(--white), 0 3px 8px rgba(0,0,0,0.12);
|
| 725 |
-
}
|
| 726 |
-
.fs-component-body { padding: 14px 16px; background: var(--white); border-top: 1px solid var(--hairline); }
|
| 727 |
-
.fs-component-label {
|
| 728 |
-
color: var(--rose); font-weight: 600; font-size: 11px; letter-spacing: .12em;
|
| 729 |
-
text-transform: uppercase; margin-bottom: 4px;
|
| 730 |
-
}
|
| 731 |
-
.fs-component-name {
|
| 732 |
-
font-weight: 500; color: var(--charcoal); font-size: 14.5px; margin-bottom: 12px;
|
| 733 |
-
line-height: 1.35; letter-spacing: 0.01em;
|
| 734 |
-
}
|
| 735 |
-
.fs-shop-btn {
|
| 736 |
-
display: inline-flex; align-items: center; gap: 6px; background: var(--charcoal);
|
| 737 |
-
color: #fff !important; padding: 9px 20px; border-radius: 999px; font-size: 11.5px;
|
| 738 |
-
font-weight: 600; letter-spacing: .08em; text-transform: uppercase;
|
| 739 |
-
text-decoration: none !important; transition: transform .2s ease, background-color .2s ease;
|
| 740 |
}
|
| 741 |
-
.fs-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
color: var(--text-muted); font-size: 12px; margin-top: 8px; padding-top: 14px;
|
| 745 |
-
border-top: 1px solid var(--hairline); letter-spacing: 0.01em;
|
| 746 |
}
|
| 747 |
|
| 748 |
-
.fs-
|
| 749 |
-
.fs-
|
| 750 |
-
.fs-
|
| 751 |
-
"""
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
def build_demo(df, model, processor, faiss_index, device):
|
| 755 |
-
skin_tone_choices = order_choices(df["skin_tone"].unique(), SKIN_DEPTH_ORDER)
|
| 756 |
-
undertone_choices = order_choices(df["undertone"].unique(), UNDERTONE_ORDER)
|
| 757 |
-
style_choices = sorted(df["style_preference"].unique().tolist())
|
| 758 |
-
gender_choices = sorted(df["gender"].unique().tolist())
|
| 759 |
-
age_choices = order_choices(df["age_group"].unique(), AGE_ORDER)
|
| 760 |
-
quickstarts = pick_quickstarts(df)
|
| 761 |
-
|
| 762 |
-
caption_pipe_holder = {"pipe": None, "failed": False}
|
| 763 |
-
|
| 764 |
-
def get_caption_pipe():
|
| 765 |
-
if caption_pipe_holder["pipe"] is None and not caption_pipe_holder["failed"]:
|
| 766 |
-
try:
|
| 767 |
-
from transformers import pipeline as hf_pipeline
|
| 768 |
-
print(f"Loading GenAI caption model '{CAPTION_MODEL_REPO}' (first use only)...")
|
| 769 |
-
caption_pipe_holder["pipe"] = hf_pipeline(
|
| 770 |
-
"text-generation",
|
| 771 |
-
model=CAPTION_MODEL_REPO,
|
| 772 |
-
device=0 if device == "cuda" else -1,
|
| 773 |
-
)
|
| 774 |
-
except Exception as e:
|
| 775 |
-
print(f"Caption model unavailable, skipping AI note: {e}")
|
| 776 |
-
caption_pipe_holder["failed"] = True
|
| 777 |
-
return caption_pipe_holder["pipe"]
|
| 778 |
-
|
| 779 |
-
def generate_caption(row):
|
| 780 |
-
pipe = get_caption_pipe()
|
| 781 |
-
if pipe is None:
|
| 782 |
-
return None
|
| 783 |
-
try:
|
| 784 |
-
user_prompt = (
|
| 785 |
-
"Write one short, warm sentence (max 25 words) from a fashion stylist, "
|
| 786 |
-
f"recommending this look: a {row['style_preference']} style outfit in "
|
| 787 |
-
f"{row['primary_color']} and {row['secondary_color']}, best colors: "
|
| 788 |
-
f"{row['recommended_colors']}. Be specific and stylish, no hashtags."
|
| 789 |
-
)
|
| 790 |
-
messages = [{"role": "user", "content": user_prompt}]
|
| 791 |
-
out = pipe(messages, max_new_tokens=40, do_sample=True, temperature=0.7)
|
| 792 |
-
return out[0]["generated_text"][-1]["content"].strip()
|
| 793 |
-
except Exception as e:
|
| 794 |
-
print(f"[caption generation skipped] {e}")
|
| 795 |
-
return None
|
| 796 |
-
|
| 797 |
-
def predict(mode, photo, photo_skin_override, photo_undertone_override,
|
| 798 |
-
manual_skin, manual_undertone, style, gender, age_group,
|
| 799 |
-
eye_color, want_caption):
|
| 800 |
-
try:
|
| 801 |
-
is_photo_mode = str(mode).startswith("📷")
|
| 802 |
-
|
| 803 |
-
if is_photo_mode:
|
| 804 |
-
if photo is None:
|
| 805 |
-
return render_error_html(
|
| 806 |
-
"Please upload a photo, or switch to “Manual Selection”."
|
| 807 |
-
)
|
| 808 |
-
detected_skin, detected_undertone, _ = estimate_skin_tone_undertone(
|
| 809 |
-
photo, skin_tone_choices
|
| 810 |
-
)
|
| 811 |
-
skin_tone = (
|
| 812 |
-
detected_skin if photo_skin_override in (None, "", AUTO_DETECT_LABEL)
|
| 813 |
-
else photo_skin_override
|
| 814 |
-
)
|
| 815 |
-
undertone = (
|
| 816 |
-
detected_undertone if photo_undertone_override in (None, "", AUTO_DETECT_LABEL)
|
| 817 |
-
else photo_undertone_override
|
| 818 |
-
)
|
| 819 |
-
query_emb = embed_query_image(photo, model, processor, device)
|
| 820 |
-
if style:
|
| 821 |
-
# Even in photo mode, let the chosen style nudge the search:
|
| 822 |
-
# blend in a small text-embedding bias toward that style,
|
| 823 |
-
# in the same CLIP vector space as the photo embedding.
|
| 824 |
-
style_emb = embed_query_text(
|
| 825 |
-
f"wearing a {style} style outfit", model, processor, device
|
| 826 |
-
)
|
| 827 |
-
query_emb = 0.75 * query_emb + 0.25 * style_emb
|
| 828 |
-
else:
|
| 829 |
-
skin_tone = manual_skin
|
| 830 |
-
undertone = manual_undertone
|
| 831 |
-
sentence = build_feature_sentence(
|
| 832 |
-
skin_tone, undertone, style, gender, age_group, eye_color
|
| 833 |
-
)
|
| 834 |
-
query_emb = embed_query_text(sentence, model, processor, device)
|
| 835 |
-
|
| 836 |
-
indices, rows, distances, tier = faiss_filtered_search(
|
| 837 |
-
query_emb, faiss_index, df, top_k=3, exclude_idx=None,
|
| 838 |
-
gender=gender or None, age_group=age_group or None,
|
| 839 |
-
)
|
| 840 |
-
if len(indices) == 0:
|
| 841 |
-
return render_error_html(
|
| 842 |
-
"No matching looks were found in the catalog for these filters — "
|
| 843 |
-
"try a different style, gender, or age group."
|
| 844 |
-
)
|
| 845 |
-
|
| 846 |
-
season, blurb, palette = derive_color_profile(skin_tone, undertone, eye_color)
|
| 847 |
-
profile_html = render_profile_card_html(season, blurb, palette)
|
| 848 |
-
|
| 849 |
-
scores = [max(0.0, min(1.0, 1.0 - d / 2.0)) for d in distances]
|
| 850 |
-
look_cards = [
|
| 851 |
-
render_look_card_html(i + 1, rows.iloc[i], round(scores[i] * 100))
|
| 852 |
-
for i in range(len(rows))
|
| 853 |
-
]
|
| 854 |
-
|
| 855 |
-
extra_html = ""
|
| 856 |
-
if want_caption:
|
| 857 |
-
caption = generate_caption(rows.iloc[0])
|
| 858 |
-
if caption:
|
| 859 |
-
extra_html = render_caption_html(caption)
|
| 860 |
-
|
| 861 |
-
note = None
|
| 862 |
-
if tier == 2:
|
| 863 |
-
note = "We broadened the search beyond the exact age group to find your best matches."
|
| 864 |
-
elif tier == 3:
|
| 865 |
-
note = "We expanded the search beyond your filters so you still get great matches."
|
| 866 |
-
|
| 867 |
-
return extra_html + render_results_html(profile_html, look_cards, note=note)
|
| 868 |
-
|
| 869 |
-
except Exception as e:
|
| 870 |
-
traceback.print_exc()
|
| 871 |
-
return render_error_html(f"{type(e).__name__}: {e}")
|
| 872 |
-
|
| 873 |
-
def toggle_mode(mode):
|
| 874 |
-
is_photo = str(mode).startswith("📷")
|
| 875 |
-
return gr.update(visible=is_photo), gr.update(visible=not is_photo)
|
| 876 |
-
|
| 877 |
-
theme = gr.themes.Soft(
|
| 878 |
-
primary_hue=gr.themes.colors.rose,
|
| 879 |
-
secondary_hue=gr.themes.colors.green,
|
| 880 |
-
neutral_hue=gr.themes.colors.stone,
|
| 881 |
-
font=gr.themes.GoogleFont("Inter"),
|
| 882 |
-
font_mono=gr.themes.GoogleFont("Inter"),
|
| 883 |
-
).set(
|
| 884 |
-
# Page + panel backgrounds — soft off-white / cream, no harsh whites or greys
|
| 885 |
-
body_background_fill="#FDFBF7",
|
| 886 |
-
body_background_fill_dark="#FDFBF7",
|
| 887 |
-
block_background_fill="#FFFFFF",
|
| 888 |
-
block_background_fill_dark="#FFFFFF",
|
| 889 |
-
block_border_color="#EEEEEE",
|
| 890 |
-
block_border_color_dark="#EEEEEE",
|
| 891 |
-
block_radius="20px",
|
| 892 |
-
container_radius="20px",
|
| 893 |
-
block_shadow="0px 10px 30px rgba(0,0,0,0.04)",
|
| 894 |
-
block_label_text_color="#948D80",
|
| 895 |
-
block_label_text_color_dark="#948D80",
|
| 896 |
-
block_label_text_weight="500",
|
| 897 |
-
block_title_text_color="#1A1A1A",
|
| 898 |
-
block_title_text_color_dark="#1A1A1A",
|
| 899 |
-
panel_background_fill="#FFFFFF",
|
| 900 |
-
panel_background_fill_dark="#FFFFFF",
|
| 901 |
-
# Inputs (dropdowns, image upload, textboxes) — rounded, cream, soft pastel
|
| 902 |
-
input_background_fill="#FDFBF7",
|
| 903 |
-
input_background_fill_dark="#FDFBF7",
|
| 904 |
-
input_border_color="#EAE6DD",
|
| 905 |
-
input_border_color_dark="#EAE6DD",
|
| 906 |
-
input_border_color_focus="#C48793",
|
| 907 |
-
input_radius="14px",
|
| 908 |
-
checkbox_border_radius="8px",
|
| 909 |
-
checkbox_background_color="#FDFBF7",
|
| 910 |
-
checkbox_background_color_selected="#C48793",
|
| 911 |
-
checkbox_border_color_selected="#C48793",
|
| 912 |
-
# Buttons — solid charcoal pill, smooth hover lift
|
| 913 |
-
button_primary_background_fill="#1A1A1A",
|
| 914 |
-
button_primary_background_fill_hover="#333333",
|
| 915 |
-
button_primary_text_color="#FFFFFF",
|
| 916 |
-
button_primary_border_color="#1A1A1A",
|
| 917 |
-
button_large_radius="999px",
|
| 918 |
-
button_medium_radius="999px",
|
| 919 |
-
button_small_radius="999px",
|
| 920 |
-
button_transition="all 0.2s ease",
|
| 921 |
-
)
|
| 922 |
-
|
| 923 |
-
with gr.Blocks(css=CUSTOM_CSS, theme=theme, title="Personal Style Matcher") as demo:
|
| 924 |
-
gr.HTML(
|
| 925 |
-
'<div class="fs-app-title">✨ Personal Style Matcher</div>'
|
| 926 |
-
'<div class="fs-app-tag">Find your color profile and your top 3 matched '
|
| 927 |
-
'looks from our personal style dataset.</div>'
|
| 928 |
-
)
|
| 929 |
-
|
| 930 |
-
with gr.Row():
|
| 931 |
-
with gr.Column(scale=1):
|
| 932 |
-
mode = gr.Radio(
|
| 933 |
-
["📷 Upload My Photo", "🎛️ Manual Selection"],
|
| 934 |
-
value="🎛️ Manual Selection",
|
| 935 |
-
label="How would you like to start?",
|
| 936 |
-
)
|
| 937 |
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
label="Skin tone (auto-detected — override if needed)",
|
| 944 |
-
)
|
| 945 |
-
photo_undertone_override = gr.Dropdown(
|
| 946 |
-
[AUTO_DETECT_LABEL] + undertone_choices,
|
| 947 |
-
value=AUTO_DETECT_LABEL,
|
| 948 |
-
label="Undertone (auto-detected — override if needed)",
|
| 949 |
-
)
|
| 950 |
-
|
| 951 |
-
with gr.Group(visible=True) as manual_group:
|
| 952 |
-
manual_skin = gr.Dropdown(
|
| 953 |
-
skin_tone_choices, value=skin_tone_choices[0], label="Skin Tone"
|
| 954 |
-
)
|
| 955 |
-
manual_undertone = gr.Dropdown(
|
| 956 |
-
undertone_choices, value=undertone_choices[0], label="Undertone"
|
| 957 |
-
)
|
| 958 |
-
|
| 959 |
-
style = gr.Dropdown(
|
| 960 |
-
style_choices, value=style_choices[0], label="Clothing Style"
|
| 961 |
-
)
|
| 962 |
-
with gr.Row():
|
| 963 |
-
gender = gr.Dropdown(
|
| 964 |
-
gender_choices, value=gender_choices[0], label="Gender"
|
| 965 |
-
)
|
| 966 |
-
age_group = gr.Dropdown(
|
| 967 |
-
age_choices, value=age_choices[0], label="Age Group"
|
| 968 |
-
)
|
| 969 |
-
eye_color = gr.Dropdown(
|
| 970 |
-
EYE_COLOR_CHOICES, value=EYE_COLOR_CHOICES[0], label="Eye Color"
|
| 971 |
-
)
|
| 972 |
-
want_caption = gr.Checkbox(
|
| 973 |
-
label="✨ Add an AI stylist note (small GenAI text model)", value=False
|
| 974 |
-
)
|
| 975 |
-
submit_btn = gr.Button("Find My Looks", variant="primary", size="lg")
|
| 976 |
-
|
| 977 |
-
with gr.Column(scale=2):
|
| 978 |
-
output_html = gr.HTML(value=render_placeholder_html())
|
| 979 |
-
|
| 980 |
-
mode.change(toggle_mode, inputs=mode, outputs=[photo_group, manual_group])
|
| 981 |
-
|
| 982 |
-
predict_inputs = [
|
| 983 |
-
mode, photo, photo_skin_override, photo_undertone_override,
|
| 984 |
-
manual_skin, manual_undertone, style, gender, age_group,
|
| 985 |
-
eye_color, want_caption,
|
| 986 |
-
]
|
| 987 |
-
submit_btn.click(predict, inputs=predict_inputs, outputs=output_html)
|
| 988 |
-
|
| 989 |
-
if quickstarts:
|
| 990 |
-
example_rows = [
|
| 991 |
-
[
|
| 992 |
-
"🎛️ Manual Selection", None, AUTO_DETECT_LABEL, AUTO_DETECT_LABEL,
|
| 993 |
-
qs["skin_tone"], qs["undertone"], qs["style"], qs["gender"],
|
| 994 |
-
qs["age_group"], qs["eye_color"], False,
|
| 995 |
-
]
|
| 996 |
-
for qs in quickstarts
|
| 997 |
-
]
|
| 998 |
-
gr.Examples(
|
| 999 |
-
examples=example_rows,
|
| 1000 |
-
inputs=predict_inputs,
|
| 1001 |
-
outputs=output_html,
|
| 1002 |
-
fn=predict,
|
| 1003 |
-
run_on_click=True,
|
| 1004 |
-
cache_examples=False,
|
| 1005 |
-
label="✨ Quick Starters — click one to see it in action",
|
| 1006 |
-
)
|
| 1007 |
-
|
| 1008 |
-
return demo
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
# =============================================================================
|
| 1012 |
-
# Entry point
|
| 1013 |
-
# =============================================================================
|
| 1014 |
-
|
| 1015 |
-
if __name__ == "__main__":
|
| 1016 |
-
df, images = load_catalog()
|
| 1017 |
-
clip_model, clip_processor, device = load_embedding_model()
|
| 1018 |
-
faiss_index = build_faiss_index(df, images, clip_model, clip_processor, device)
|
| 1019 |
-
demo = build_demo(df, clip_model, clip_processor, faiss_index, device)
|
| 1020 |
-
demo.queue().launch()
|
|
|
|
| 1 |
+
import subprocess, sys
|
| 2 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q",
|
| 3 |
+
"gradio", "transformers", "torch", "faiss-cpu", "datasets",
|
| 4 |
+
"pandas", "numpy", "pillow", "huggingface_hub"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
import gradio as gr
|
| 7 |
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
import torch
|
|
|
|
| 10 |
import faiss
|
| 11 |
+
import urllib.parse
|
| 12 |
+
import os
|
| 13 |
+
import hashlib
|
| 14 |
+
import colorsys
|
| 15 |
+
from PIL import Image
|
| 16 |
+
from transformers import AutoProcessor, AutoModel
|
| 17 |
+
from huggingface_hub import hf_hub_download
|
| 18 |
+
|
| 19 |
+
# ── Load CLIP model ───────────────────────────────────────────────────────────
|
| 20 |
+
print("Loading CLIP model...")
|
| 21 |
+
CLIP_ID = "openai/clip-vit-base-patch32"
|
| 22 |
+
processor = AutoProcessor.from_pretrained(CLIP_ID)
|
| 23 |
+
clip_model = AutoModel.from_pretrained(CLIP_ID).eval()
|
| 24 |
+
print("CLIP ready.")
|
| 25 |
+
|
| 26 |
+
# ── Load embeddings + metadata from Space files ───────────────────────────────
|
| 27 |
+
print("Loading embeddings and metadata...")
|
| 28 |
+
EMB_PATH = hf_hub_download(repo_id="lihicarmeli/LookMatch", filename="final_image_embeddings.npy", repo_type="space")
|
| 29 |
+
META_PATH = hf_hub_download(repo_id="lihicarmeli/LookMatch", filename="catalog_metadata.parquet", repo_type="space")
|
| 30 |
+
|
| 31 |
+
image_embeddings = np.load(EMB_PATH).astype("float32")
|
| 32 |
+
df = pd.read_parquet(META_PATH)
|
| 33 |
+
|
| 34 |
+
# Build FAISS index
|
| 35 |
+
dimension = image_embeddings.shape[1]
|
| 36 |
+
faiss_index = faiss.IndexFlatL2(dimension)
|
| 37 |
+
emb_norm = image_embeddings.copy()
|
| 38 |
+
faiss.normalize_L2(emb_norm)
|
| 39 |
+
faiss_index.add(emb_norm)
|
| 40 |
+
print(f"FAISS index ready — {faiss_index.ntotal} items.")
|
| 41 |
+
|
| 42 |
+
# ── Shop URL builder ──────────────────────────────────────────────────────────
|
| 43 |
+
RETAILERS = ["zara", "hm", "asos", "mango", "shein"]
|
| 44 |
+
RETAILER_URLS = {
|
| 45 |
+
"zara": "https://www.zara.com/us/en/search?searchTerm={query}",
|
| 46 |
"hm": "https://www2.hm.com/en_us/search-results.html?q={query}",
|
| 47 |
+
"asos": "https://www.asos.com/us/search/?q={query}",
|
| 48 |
"mango": "https://shop.mango.com/us/en/search?kw={query}",
|
| 49 |
"shein": "https://us.shein.com/pdsearch/{query}/",
|
| 50 |
}
|
| 51 |
|
| 52 |
+
def shop_url(query, retailer="asos"):
|
| 53 |
+
q = urllib.parse.quote_plus(str(query))
|
| 54 |
+
return RETAILER_URLS.get(retailer, RETAILER_URLS["asos"]).format(query=q)
|
| 55 |
+
|
| 56 |
+
# ── Color Guardrail: Filter out any orange tones from UI ──────────────────────
|
| 57 |
+
def clean_hex_color(hex_str):
|
| 58 |
+
"""Ensures hex is valid and completely overrides any orange/tangerine shades to premium warm tones."""
|
| 59 |
+
h_str = str(hex_str).strip().lower()
|
| 60 |
+
if not h_str.startswith("#"):
|
| 61 |
+
h_str = "#" + h_str
|
| 62 |
+
|
| 63 |
+
# Standard orange/terracotta overrides to beautiful deep golds or warm camels
|
| 64 |
+
orange_fallbacks = {
|
| 65 |
+
"#ff6b1a": "#C9A876", "#ff7f50": "#D4AF37", "#e8722c": "#9C8170",
|
| 66 |
+
"#cb6015": "#8B5A2B", "#f28500": "#C9A876", "#c0654d": "#AF6E4D"
|
| 67 |
+
}
|
| 68 |
+
if h_str in orange_fallbacks:
|
| 69 |
+
return orange_fallbacks[h_str]
|
| 70 |
+
|
| 71 |
+
# Dynamic check if color falls into orange hue spectrum
|
| 72 |
+
if len(h_str) == 7:
|
| 73 |
+
try:
|
| 74 |
+
r = int(h_str[1:3], 16) / 255.0
|
| 75 |
+
g = int(h_str[3:5], 16) / 255.0
|
| 76 |
+
b = int(h_str[5:7], 16) / 255.0
|
| 77 |
+
h, l, s = colorsys.rgb_to_hls(r, g, b)
|
| 78 |
+
# Orange spectrum is roughly between 0.04 and 0.12 in Python's colorsys
|
| 79 |
+
if 0.03 <= h <= 0.13:
|
| 80 |
+
h += 0.25 # Safely shift to soft sage green
|
| 81 |
+
r, g, b = colorsys.hls_to_rgb(h, 0.65, 0.55)
|
| 82 |
+
return "#{:02X}{:02X}{:02X}".format(int(r * 255), int(g * 255), int(b * 255))
|
| 83 |
+
except:
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
return hex_str
|
| 87 |
+
|
| 88 |
+
# ── Embed image with CLIP ─────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
@torch.no_grad()
|
| 90 |
+
def embed_image(pil_image):
|
| 91 |
+
inputs = processor(images=pil_image, return_tensors="pt")
|
| 92 |
+
emb = clip_model.get_image_features(**inputs)
|
| 93 |
+
if hasattr(emb, "last_hidden_state"):
|
| 94 |
+
emb = emb.last_hidden_state[:, 0, :]
|
| 95 |
+
emb = emb / emb.norm(p=2, dim=-1, keepdim=True)
|
| 96 |
+
return emb.detach().numpy().astype("float32")
|
| 97 |
+
|
| 98 |
+
# ── Embed text query with CLIP ────────────────────────────────────────────────
|
| 99 |
@torch.no_grad()
|
| 100 |
+
def embed_text(text):
|
| 101 |
+
inputs = processor(text=[text], return_tensors="pt", padding=True, truncation=True)
|
| 102 |
+
emb = clip_model.get_text_features(**inputs)
|
| 103 |
+
if hasattr(emb, "last_hidden_state"):
|
| 104 |
+
emb = emb.last_hidden_state[:, 0, :]
|
| 105 |
+
emb = emb / emb.norm(p=2, dim=-1, keepdim=True)
|
| 106 |
+
return emb.detach().numpy().astype("float32")
|
| 107 |
+
|
| 108 |
+
# ── FAISS search ──────────────────────────────────────────────────────────────
|
| 109 |
+
def faiss_search(query_emb, top_k=3, exclude_idx=None):
|
| 110 |
+
q = query_emb.copy()
|
| 111 |
+
faiss.normalize_L2(q)
|
| 112 |
+
distances, indices = faiss_index.search(q, top_k + 5)
|
| 113 |
+
results = []
|
| 114 |
+
for idx, dist in zip(indices[0], distances[0]):
|
| 115 |
+
if idx == -1:
|
| 116 |
+
continue
|
| 117 |
+
if exclude_idx is not None and idx == exclude_idx:
|
| 118 |
+
continue
|
| 119 |
+
results.append((int(idx), float(dist)))
|
| 120 |
+
if len(results) >= top_k:
|
| 121 |
+
break
|
| 122 |
+
return results
|
| 123 |
+
|
| 124 |
+
# ── Pill row HTML ─────────────────────────────────────────────────────────────
|
| 125 |
+
SKIN_HEX = {"fair":"#F8DFC0","light":"#E8C99A","medium":"#C68642",
|
| 126 |
+
"olive":"#8D6346","tan":"#7B4F2E","dark":"#3B1F0E","deep":"#2A1208"}
|
| 127 |
+
|
| 128 |
+
def pill(label, color, active=False):
|
| 129 |
+
border = "1px solid var(--gold)" if active else "1.5px solid var(--hairline)"
|
| 130 |
+
bg = "var(--gold-soft)" if active else "#FFFFFF"
|
| 131 |
+
tcol = "var(--charcoal)" if active else "var(--text-muted)"
|
| 132 |
+
return f'''<span class="fs-pill" style="border:{border}; background:{bg}; color:{tcol};">
|
| 133 |
+
<span class="fs-pill-dot" style="background:{clean_hex_color(color)};"></span>
|
| 134 |
+
<span>{label}</span>
|
| 135 |
+
</span>'''
|
| 136 |
+
|
| 137 |
+
# ── Build result HTML ─────────────────────────────────────────────────────────
|
| 138 |
+
def build_result(matches, skin_tone=None, undertone=None, style=None):
|
| 139 |
+
if not matches:
|
| 140 |
+
return "<p class='fs-placeholder'>No matches found.</p>"
|
| 141 |
+
|
| 142 |
+
# Feature pills
|
| 143 |
+
feature_html = ""
|
| 144 |
+
if skin_tone:
|
| 145 |
+
col = SKIN_HEX.get(str(skin_tone).lower().split()[0], "#C19A6B")
|
| 146 |
+
feature_html += f'<div class="fs-feature-row"><span class="fs-feature-title">Skin</span>{pill(skin_tone, col, True)}</div>'
|
| 147 |
+
if undertone:
|
| 148 |
+
feature_html += f'<div class="fs-feature-row"><span class="fs-feature-title">Undertone</span>{pill(undertone, "#D4B896", True)}</div>'
|
| 149 |
+
if style:
|
| 150 |
+
feature_html += f'<div class="fs-feature-row"><span class="fs-feature-title">Style</span>{pill(style, "#C8A2C8", True)}</div>'
|
| 151 |
+
|
| 152 |
+
# Outfit cards
|
| 153 |
+
cards = ""
|
| 154 |
+
for rank, (idx, score) in enumerate(matches):
|
| 155 |
+
row = df.iloc[idx]
|
| 156 |
+
skin = row.get("skin_tone", "")
|
| 157 |
+
rec_col = row.get("recommended_colors", "")
|
| 158 |
+
top = row.get("outfit_top", "Top")
|
| 159 |
+
bottom = row.get("outfit_bottom", "Bottom")
|
| 160 |
+
shoes = row.get("outfit_shoes", "Shoes")
|
| 161 |
+
acc = row.get("outfit_accessory", "Accessory")
|
| 162 |
+
styp = row.get("style_preference", "")
|
| 163 |
+
pri_col = row.get("primary_color", "#C19A6B")
|
| 164 |
+
sec_col = row.get("secondary_color", "#BBA898")
|
| 165 |
+
|
| 166 |
+
def safe_hex(c):
|
| 167 |
+
c = str(c).strip()
|
| 168 |
+
if c.startswith("#") and len(c) in [4,7]: return clean_hex_color(c)
|
| 169 |
+
return "#C19A6B"
|
| 170 |
+
|
| 171 |
+
ph = safe_hex(pri_col)
|
| 172 |
+
sh = safe_hex(sec_col)
|
| 173 |
+
|
| 174 |
+
items = [
|
| 175 |
+
("TOP", top, ph),
|
| 176 |
+
("BOTTOM", bottom, sh),
|
| 177 |
+
("SHOES", shoes, ph),
|
| 178 |
+
("ACCESSORY", acc, sh),
|
| 179 |
+
]
|
| 180 |
+
|
| 181 |
+
item_html = ""
|
| 182 |
+
for itype, iname, ihex in items:
|
| 183 |
+
item_html += f'''
|
| 184 |
+
<div class="fs-component">
|
| 185 |
+
<div class="fs-component-swatch" style="background:{ihex}15;">
|
| 186 |
+
<span class="fs-swatch-dot" style="background:{ihex};"></span>
|
| 187 |
+
</div>
|
| 188 |
+
<div class="fs-component-body">
|
| 189 |
+
<div class="fs-component-label">{itype}</div>
|
| 190 |
+
<div class="fs-component-name">{html.escape(str(iname))}</div>
|
| 191 |
+
<a class="fs-shop-btn" href="{shop_url(iname)}" target="_blank" rel="noopener noreferrer">Shop ↗</a>
|
| 192 |
+
</div>
|
| 193 |
+
</div>'''
|
| 194 |
+
|
| 195 |
+
match_pct = max(0, int((1 - score) * 100))
|
| 196 |
+
cards += f'''
|
| 197 |
+
<div class="fs-look-card">
|
| 198 |
+
<div class="fs-look-head">
|
| 199 |
+
<span class="fs-look-avatar" style="background:{ph};"></span>
|
| 200 |
+
<div>
|
| 201 |
+
<div class="fs-look-title">Look #{rank+1}</div>
|
| 202 |
+
<div class="fs-look-sub">{styp} · {skin} skin · {match_pct}% match</div>
|
| 203 |
+
</div>
|
| 204 |
+
</div>
|
| 205 |
+
{item_html}
|
| 206 |
+
<div class="fs-colors-footer">Recommended colors: {rec_col}</div>
|
| 207 |
+
</div>'''
|
| 208 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
return f"""
|
| 210 |
+
<div class="fs-result-wrapper">
|
| 211 |
+
{"" if not feature_html else f'''
|
| 212 |
+
<div class="fs-profile-card">
|
| 213 |
+
<div class="fs-profile-eyebrow">Detected Features</div>
|
| 214 |
+
<div class="fs-chip-row" style="margin-top:10px;">{feature_html}</div>
|
| 215 |
+
</div>'''}
|
| 216 |
+
|
| 217 |
<div class="fs-header">
|
| 218 |
<div class="fs-header-decoration"></div>
|
| 219 |
<div class="fs-header-eyebrow">YOUR MATCHED LOOKS</div>
|
| 220 |
+
<div class="fs-header-sub">Top {len(matches)} outfits from your personal style dataset</div>
|
| 221 |
</div>
|
| 222 |
+
|
| 223 |
<div class="fs-grid">{cards}</div>
|
| 224 |
</div>
|
| 225 |
"""
|
| 226 |
|
| 227 |
+
# ── Render: photo tab ─────────────────────────────────────────────────────────
|
| 228 |
+
def render_photo(image):
|
| 229 |
+
if image is None:
|
| 230 |
+
return "<p class='fs-placeholder'>Please upload a photo first.</p>"
|
| 231 |
+
try:
|
| 232 |
+
pil = Image.open(image).convert("RGB")
|
| 233 |
+
emb = embed_image(pil)
|
| 234 |
+
matches = faiss_search(emb, top_k=3)
|
| 235 |
+
if matches:
|
| 236 |
+
row = df.iloc[matches[0][0]]
|
| 237 |
+
skin = row.get("skin_tone","")
|
| 238 |
+
undertone = row.get("undertone","")
|
| 239 |
+
style = row.get("style_preference","")
|
| 240 |
+
else:
|
| 241 |
+
skin = undertone = style = ""
|
| 242 |
+
return build_result(matches, skin, undertone, style)
|
| 243 |
+
except Exception as e:
|
| 244 |
+
return f"<div class='fs-error'><div class='fs-error-title'>Error</div><div class='fs-error-msg'>{str(e)[:300]}</div></div>"
|
| 245 |
+
|
| 246 |
+
# ── Render: manual tab ────────────────────────────────────────────────────────
|
| 247 |
+
def render_manual(skin, undertone, style):
|
| 248 |
+
query = f"a person with {skin} skin tone and {undertone} undertone wearing {style} style outfit"
|
| 249 |
+
emb = embed_text(query)
|
| 250 |
+
matches = faiss_search(emb, top_k=3)
|
| 251 |
+
return build_result(matches, skin, undertone, style)
|
| 252 |
+
|
| 253 |
+
# ── Premium Luxury CSS ────────────────────────────────────────────────────────
|
| 254 |
+
CSS = """
|
| 255 |
+
@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');
|
| 256 |
+
|
| 257 |
+
* { box-sizing: border-box; }
|
| 258 |
+
|
| 259 |
+
body {
|
| 260 |
+
font-family: 'Inter', system-ui, sans-serif !important;
|
| 261 |
+
background: #FDFBF7 !important;
|
| 262 |
+
}
|
| 263 |
|
| 264 |
+
.gradio-container {
|
| 265 |
+
max-width: 960px !important;
|
| 266 |
+
margin: auto !important;
|
| 267 |
+
background: #FDFBF7 !important;
|
| 268 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
+
/* Custom UI Variables */
|
| 271 |
+
.fs-result-wrapper {
|
| 272 |
--cream: #FDFBF7;
|
| 273 |
--white: #FFFFFF;
|
| 274 |
--charcoal: #1A1A1A;
|
|
|
|
| 277 |
--hairline: #EEEEEE;
|
| 278 |
--rose: #C48793;
|
| 279 |
--rose-soft: #F6ECEE;
|
|
|
|
| 280 |
--sage-soft: #EFF3EA;
|
| 281 |
--gold: #C9A876;
|
| 282 |
--gold-soft: #F8F1E4;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
}
|
| 284 |
|
| 285 |
+
/* Tabs Styling */
|
| 286 |
+
.tab-nav {
|
| 287 |
+
border-bottom: 1px solid #EAE6DD !important;
|
| 288 |
+
background: transparent !important;
|
| 289 |
+
gap: 10px !important;
|
| 290 |
}
|
| 291 |
+
.tab-nav button {
|
| 292 |
+
font-family: 'Montserrat', sans-serif !important;
|
| 293 |
+
font-size: 13px !important;
|
| 294 |
+
font-weight: 500 !important;
|
| 295 |
+
letter-spacing: 0.1em !important;
|
| 296 |
+
text-transform: uppercase !important;
|
| 297 |
+
padding: 14px 28px !important;
|
| 298 |
+
background: transparent !important;
|
| 299 |
+
border: none !important;
|
| 300 |
+
color: #948D80 !important;
|
| 301 |
}
|
| 302 |
+
.tab-nav button.selected {
|
| 303 |
+
color: #1A1A1A !important;
|
| 304 |
+
border-bottom: 2px solid #C9A876 !important;
|
| 305 |
+
font-weight: 600 !important;
|
| 306 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
|
| 308 |
+
/* Inputs Styling */
|
| 309 |
+
.fs-app-title {
|
| 310 |
+
font-family: 'Montserrat', sans-serif;
|
| 311 |
+
font-weight: 400;
|
| 312 |
+
font-size: 34px;
|
| 313 |
+
letter-spacing: 0.05em;
|
| 314 |
+
color: #1A1A1A;
|
| 315 |
+
margin-bottom: 6px;
|
| 316 |
+
text-transform: uppercase;
|
|
|
|
|
|
|
|
|
|
| 317 |
}
|
|
|
|
| 318 |
|
| 319 |
+
/* Main Action Button */
|
| 320 |
+
button.lg {
|
| 321 |
+
background: #1A1A1A !important;
|
| 322 |
+
color: #FFFFFF !important;
|
| 323 |
+
border: 1px solid #1A1A1A !important;
|
| 324 |
+
border-radius: 999px !important;
|
| 325 |
+
font-family: 'Montserrat', sans-serif !important;
|
| 326 |
+
font-weight: 600 !important;
|
| 327 |
+
font-size: 12px !important;
|
| 328 |
+
letter-spacing: 0.15em !important;
|
| 329 |
+
text-transform: uppercase !important;
|
| 330 |
+
padding: 14px !important;
|
| 331 |
+
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1) !important;
|
| 332 |
+
box-shadow: 0px 4px 12px rgba(0,0,0,0.05) !important;
|
| 333 |
}
|
| 334 |
+
button.lg:hover {
|
| 335 |
+
background: #3A3A3A !important;
|
| 336 |
+
transform: translateY(-1px) !important;
|
| 337 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
|
| 339 |
+
/* Output Cards & Structural Grid */
|
| 340 |
+
.fs-placeholder {
|
| 341 |
+
color: #948D80; font-size: 14px; padding: 64px 24px; text-align: center;
|
| 342 |
+
border: 1px solid #EEEEEE; border-radius: 24px; background: #FFFFFF;
|
| 343 |
+
letter-spacing: 0.02em; box-shadow: 0px 10px 30px rgba(0,0,0,0.01);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
}
|
|
|
|
| 345 |
|
| 346 |
+
.fs-profile-card {
|
| 347 |
+
background: linear-gradient(135deg, #F6ECEE 0%, #F8F1E4 100%);
|
| 348 |
+
border: 1px solid #EEEEEE; border-radius: 24px; padding: 24px 28px;
|
| 349 |
+
margin-bottom: 20px; box-shadow: 0px 12px 30px rgba(0,0,0,0.02);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
}
|
| 351 |
+
.fs-profile-eyebrow {
|
| 352 |
+
color: #C48793; font-weight: 600; font-size: 11px; letter-spacing: .18em;
|
| 353 |
+
text-transform: uppercase;
|
|
|
|
|
|
|
| 354 |
}
|
| 355 |
|
| 356 |
+
.fs-feature-row { display: flex; align-items: center; margin-bottom: 8px; }
|
| 357 |
+
.fs-feature-row:last-child { margin-bottom: 0; }
|
| 358 |
+
.fs-feature-title { font-size: 11px; font-weight: 600; color: #948D80; text-transform: uppercase; letter-spacing: .1em; width: 90px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
|
| 360 |
+
.fs-pill {
|
| 361 |
+
display: inline-flex; align-items: center; gap: 8px; padding: 6px 14px;
|
| 362 |
+
border-radius: 999px; font-size: 12px; font-weight: 500; letter-spacing: 0.02em;
|
| 363 |
+
}
|
| 364 |
+
.fs-pill-dot { width: 14px; height: 14px; border-radius: 50%; display: inline-block; box-shadow: 0 0 0 2px
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|