romi2001 commited on
Commit
969f42e
·
verified ·
1 Parent(s): 9add904

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -534
app.py DELETED
@@ -1,534 +0,0 @@
1
- import base64
2
- import os
3
- import urllib.parse
4
- from io import BytesIO
5
-
6
- import numpy as np
7
- import pandas as pd
8
- import torch
9
- import gradio as gr
10
- import faiss
11
- from datasets import load_dataset
12
- from PIL import Image
13
- from transformers import (
14
- CLIPModel, CLIPProcessor, pipeline as hf_pipeline,
15
- BlipProcessor, BlipForQuestionAnswering,
16
- SegformerImageProcessor, AutoModelForSemanticSegmentation,
17
- )
18
- from diffusers import StableDiffusionInpaintPipeline
19
-
20
- # ---------------------------------------------------------------------------
21
- # CONFIG
22
- # ---------------------------------------------------------------------------
23
- HF_DATASET_REPO = "lihicarmeli/fashion-stylist-multimodal-v2"
24
- HF_WINNING_MODEL = "openai/clip-vit-base-patch32"
25
- EMBEDDINGS_FILE = "final_image_embeddings.npy"
26
- METADATA_FILE = "catalog_metadata.parquet"
27
-
28
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
29
-
30
- # ---------------------------------------------------------------------------
31
- # LOAD DATA + WINNING EMBEDDING MODEL
32
- # ---------------------------------------------------------------------------
33
- print("Loading dataset from HF Hub...")
34
- ds = load_dataset(HF_DATASET_REPO)
35
- df = ds["train"].to_pandas()
36
- images = [ds["train"][i]["image_improved"] for i in range(len(ds["train"]))]
37
-
38
- print("Generating Quick Starter sample photos...")
39
- SAMPLES_DIR = "samples_cache"
40
- os.makedirs(SAMPLES_DIR, exist_ok=True)
41
-
42
- def _pick_index(filter_fn, fallback_idx=0):
43
- matches = df[df.apply(filter_fn, axis=1)]
44
- return int(matches.index[0]) if len(matches) else fallback_idx
45
-
46
- _sample_specs = [
47
- ("demo_woman.jpg", lambda r: r["gender"] == "woman"),
48
- ("demo_man.jpg", lambda r: r["gender"] == "man"),
49
- ("demo_teen.jpg", lambda r: r["age_group"] == "teen"),
50
- ]
51
-
52
- SAMPLE_PHOTOS = []
53
- for _filename, _filt in _sample_specs:
54
- _idx = _pick_index(_filt, fallback_idx=len(SAMPLE_PHOTOS))
55
- _path = os.path.join(SAMPLES_DIR, _filename)
56
- images[_idx].convert("RGB").save(_path)
57
- SAMPLE_PHOTOS.append(_path)
58
-
59
- print("Loading precomputed embeddings...")
60
- image_embeddings = np.load(EMBEDDINGS_FILE).astype("float32")
61
-
62
- print("Loading winning embedding model (CLIP)...")
63
- win_model = CLIPModel.from_pretrained(HF_WINNING_MODEL).to(DEVICE).eval()
64
- win_processor = CLIPProcessor.from_pretrained(HF_WINNING_MODEL)
65
-
66
- print("Building FAISS index...")
67
- dimension = image_embeddings.shape[1]
68
- faiss_img_index = faiss.IndexFlatL2(dimension)
69
- faiss.normalize_L2(image_embeddings)
70
- faiss_img_index.add(image_embeddings)
71
-
72
- # ---------------------------------------------------------------------------
73
- # GENERATION MODELS
74
- # ---------------------------------------------------------------------------
75
- print("Loading text and VQA generation pipelines...")
76
- caption_gen_pipe = hf_pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct", device=0 if DEVICE == "cuda" else -1)
77
- vqa_processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
78
- vqa_model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(DEVICE)
79
-
80
- print("Loading clothing segmentation and Stable Diffusion pipelines...")
81
- seg_processor = SegformerImageProcessor.from_pretrained("mattmdjaga/segformer_b2_clothes")
82
- seg_model = AutoModelForSemanticSegmentation.from_pretrained("mattmdjaga/segformer_b2_clothes").to(DEVICE)
83
- inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained(
84
- "runwayml/stable-diffusion-inpainting",
85
- torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
86
- safety_checker=None,
87
- ).to(DEVICE)
88
-
89
- GENDERS = sorted(df["gender"].unique().tolist())
90
- AGE_GROUPS = sorted(df["age_group"].unique().tolist())
91
- SKIN_TONES = sorted(df["skin_tone"].unique().tolist())
92
- UNDERTONES = sorted(df["undertone"].unique().tolist())
93
- STYLES = sorted(df["style_preference"].unique().tolist())
94
-
95
- # ---------------------------------------------------------------------------
96
- # UTILS & VISUAL CONFIG
97
- # ---------------------------------------------------------------------------
98
- _SWATCH_CSS = {
99
- "ice white": "#f4f3ee", "bold blue": "#1d4ed8", "royal blue": "#1e3a8a",
100
- "fuchsia": "#c026d3", "cool red": "#dc2626", "deep teal": "#0f766e",
101
- "plum": "#6b21a8", "silver": "#cbd5e1", "bright pink": "#ec4899",
102
- "deep jewel tones": "#581c87", "rust": "#b45309", "camel": "#c19a6b",
103
- "coral": "#fb7185", "ivory": "#fffff0", "olive": "#65730a",
104
- "terracotta": "#c2643a", "peach": "#FBC299", "warm camel": "#C69E6E"
105
- }
106
-
107
- def _swatch_color(name):
108
- key = str(name).strip().lower()
109
- if key in _SWATCH_CSS:
110
- return _SWATCH_CSS[key]
111
- palette = ["#b45309", "#1d4ed8", "#c026d3", "#0f766e", "#dc2626", "#6b21a8"]
112
- return palette[hash(key) % len(palette)]
113
-
114
- def _lighten_hex(hex_color, factor=0.85):
115
- hex_color = hex_color.lstrip("#")
116
- if len(hex_color) != 6:
117
- return "#F5E6E1"
118
- r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
119
- r = int(r + (255 - r) * factor)
120
- g = int(g + (255 - g) * factor)
121
- b = int(b + (255 - b) * factor)
122
- return f"#{r:02x}{g:02x}{b:02x}"
123
-
124
- _PALETTE_NAMES = {
125
- "fair": {"cool": "Porcelain Frost", "warm": "Champagne Silk", "neutral": "Pale Linen"},
126
- "light": {"cool": "Moonlit Pearl", "warm": "Gilded Honey", "neutral": "Quiet Ivory"},
127
- "medium": {"cool": "Dusk Orchid", "warm": "Spiced Amber", "neutral": "Warm Alabaster"},
128
- "olive": {"cool": "Sage Noir", "warm": "Burnished Olive", "neutral": "Terracotta Earth"},
129
- "tan": {"cool": "Copper Veil", "warm": "Gilded Sand", "neutral": "Desert Rosé"},
130
- "deep": {"cool": "Midnight Sapphire", "warm": "Mahogany Gold", "neutral": "Onyx Velvet"},
131
- }
132
-
133
- def get_palette_name(skin_tone, undertone):
134
- return _PALETTE_NAMES.get(str(skin_tone).strip().lower(), {}).get(
135
- str(undertone).strip().lower(), "Signature Palette"
136
- )
137
-
138
- def pil_to_base64(img, max_size=280):
139
- img = img.convert("RGB").copy()
140
- img.thumbnail((max_size, max_size))
141
- buf = BytesIO()
142
- img.save(buf, format="JPEG", quality=85)
143
- return base64.b64encode(buf.getvalue()).decode("utf-8")
144
-
145
- # ---------------------------------------------------------------------------
146
- # EMBEDDING + FAISS SEARCH
147
- # ---------------------------------------------------------------------------
148
- @torch.no_grad()
149
- def embed_query_image(pil_image):
150
- inputs = win_processor(images=pil_image, return_tensors="pt").to(DEVICE)
151
- outputs = win_model(**inputs)
152
-
153
- if hasattr(outputs, "image_embeds") and outputs.image_embeds is not None:
154
- feats = outputs.image_embeds
155
- elif hasattr(outputs, "pooler_output") and outputs.pooler_output is not None:
156
- feats = outputs.pooler_output
157
- elif isinstance(outputs, tuple) or isinstance(outputs, list):
158
- feats = outputs[0]
159
- else:
160
- feats = outputs
161
-
162
- if hasattr(feats, "detach"):
163
- feats = feats.detach()
164
- return feats.cpu().numpy().astype("float32")
165
-
166
- @torch.no_grad()
167
- def embed_query_text(sentence):
168
- inputs = win_processor(text=[sentence], return_tensors="pt", padding=True, truncation=True).to(DEVICE)
169
- outputs = win_model(**inputs)
170
-
171
- if hasattr(outputs, "text_embeds") and outputs.text_embeds is not None:
172
- feats = outputs.text_embeds
173
- elif hasattr(outputs, "pooler_output") and outputs.pooler_output is not None:
174
- feats = outputs.pooler_output
175
- elif isinstance(outputs, tuple) or isinstance(outputs, list):
176
- feats = outputs[0]
177
- else:
178
- feats = outputs
179
-
180
- if hasattr(feats, "detach"):
181
- feats = feats.detach()
182
- return feats.cpu().numpy().astype("float32")
183
-
184
- def build_feature_sentence(skin_tone, undertone, style_preference, gender=None, age_group=None):
185
- descriptor = " ".join(p for p in [age_group, gender] if p) or "person"
186
- return f"a {descriptor} with {skin_tone} skin tone and {undertone} undertone, wearing a {style_preference} style outfit"
187
-
188
- def faiss_filtered_search(query_emb, top_k=3, exclude_idx=None, gender=None, age_group=None):
189
- faiss.normalize_L2(query_emb)
190
- k = len(df)
191
- distances, indices = faiss_img_index.search(query_emb, k)
192
- distances, indices = distances[0], indices[0]
193
-
194
- def collect(require_gender, require_age):
195
- kept_i, kept_d = [], []
196
- for idx, dist in zip(indices, distances):
197
- if idx == -1 or (exclude_idx is not None and idx == exclude_idx):
198
- continue
199
- row = df.iloc[idx]
200
- # תיקון השגיאה: החלפת ה-&& ב-and פייתון תקני לחלוטין
201
- if require_gender and gender and str(row["gender"]).lower() != str(gender).lower():
202
- continue
203
- if require_age and age_group and str(row["age_group"]).lower() != str(age_group).lower():
204
- continue
205
- kept_i.append(idx)
206
- kept_d.append(dist)
207
- if len(kept_i) == top_k:
208
- break
209
- return kept_i, kept_d
210
-
211
- kept_i, kept_d = collect(True, True)
212
- if len(kept_i) < top_k:
213
- kept_i, kept_d = collect(True, False)
214
- if len(kept_i) < top_k:
215
- kept_i, kept_d = collect(False, False)
216
-
217
- return np.array(kept_i), df.iloc[kept_i], np.array(kept_d)
218
-
219
- # ---------------------------------------------------------------------------
220
- # PATTERN LOGIC & COMPONENT BUILDERS
221
- # ---------------------------------------------------------------------------
222
- def generate_stylist_caption(row):
223
- user_prompt = (
224
- f"Write one short, warm sentence (max 25 words) from a fashion stylist, recommending this look: "
225
- f"a {row['style_preference']} style outfit in {row['primary_color']} and {row['secondary_color']}. "
226
- f"Be specific and stylish, no hashtags."
227
- )
228
- messages = [{"role": "user", "content": user_prompt}]
229
- output = caption_gen_pipe(messages, max_new_tokens=40, do_sample=True, temperature=0.7)
230
- return output[0]["generated_text"][-1]["content"].strip()
231
-
232
- @torch.no_grad()
233
- def answer_question_about_image(pil_image, question):
234
- inputs = vqa_processor(pil_image.convert("RGB"), question, return_tensors="pt").to(DEVICE)
235
- output_ids = vqa_model.generate(**inputs, max_new_tokens=20)
236
- return vqa_processor.decode(output_ids[0], skip_special_tokens=True)
237
-
238
- @torch.no_grad()
239
- def get_face_protect_mask(pil_image, use_geometric_fallback=True):
240
- inputs = seg_processor(images=pil_image, return_tensors="pt").to(DEVICE)
241
- logits = seg_model(**inputs).logits
242
- upsampled = torch.nn.functional.interpolate(logits, size=pil_image.size[::-1], mode="bilinear", align_corners=False)
243
- pred_seg = upsampled.argmax(dim=1)[0].cpu().numpy()
244
- seg_protect = np.isin(pred_seg, [11, 2])
245
- if not use_geometric_fallback:
246
- return seg_protect
247
- h, w = seg_protect.shape
248
- yy, xx = np.mgrid[0:h, 0:w]
249
- geometric_protect = (((xx - w*0.5) / (w*0.22)) ** 2 + ((yy - h*0.42) / (h*0.30)) ** 2) <= 1.0
250
- return seg_protect | geometric_protect
251
-
252
- def generate_new_outfit_image(pil_image, row, target_gender=None):
253
- base = pil_image.convert("RGB")
254
- protect = get_face_protect_mask(base)
255
- canvas_w, canvas_h = 512, 1024
256
- head_w = int(canvas_w * 0.45)
257
- scale = head_w / base.width
258
- head_h = int(base.height * scale)
259
-
260
- resized_face_crop = base.resize((head_w, head_h))
261
- resized_protect_img = Image.fromarray(protect.astype(np.uint8) * 255).resize((head_w, head_h), resample=Image.NEAREST)
262
-
263
- # תיקון סדר שורות: המיקומים paste_x ו-paste_y מוגדרים כאן לפני השימוש בהם
264
- paste_x = (canvas_w - head_w) // 2
265
- paste_y = int(canvas_h * 0.03)
266
-
267
- canvas = Image.new("RGB", (canvas_w, canvas_h), color=(240, 238, 235))
268
- canvas.paste(resized_face_crop, (paste_x, paste_y))
269
-
270
- mask_arr = np.full((canvas_h, canvas_w), 255, dtype=np.uint8)
271
- mask_arr[paste_y:paste_y + head_h, paste_x:paste_x + head_w][np.array(resized_protect_img) > 127] = 0
272
- mask = Image.fromarray(mask_arr).convert("L")
273
-
274
- gender_word = "man" if str(row["gender"]).lower() in ("man", "male") else "woman"
275
- prompt = (
276
- f"full body fashion photo of a {row['age_group']} {gender_word}, standing, wearing a {row['style_preference']} style outfit: "
277
- f"{row['outfit_top']}, {row['outfit_bottom']}, {row['outfit_shoes']}, in {row['primary_color']}, quality photography"
278
- )
279
- generated = inpaint_pipe(prompt=prompt, image=canvas, mask_image=mask, num_inference_steps=25, height=canvas_h, width=canvas_w).images[0]
280
- return Image.composite(generated, canvas, mask), prompt
281
-
282
- def build_style_card_html(row, caption):
283
- colors = [c.strip() for c in str(row["recommended_colors"]).split(",") if c.strip()][:4]
284
- swatches = "".join(
285
- f'<div class="swatch-card"><div class="color-bubble" style="background-color:{_swatch_color(c)};"></div><p>{c.title()}</p></div>'
286
- for c in colors
287
- )
288
- palette_name = get_palette_name(row["skin_tone"], row["undertone"])
289
-
290
- html = f'<div class="palette-premium-banner">'
291
- html += f'<div style="font-size:11px; letter-spacing:2px; color:#9C7A4E; font-weight:700; text-transform:uppercase;">YOUR COLOR PALETTE</div>'
292
- html += f'<div class="palette-name" style="font-size:32px; font-weight:700; margin:6px 0; color:#1B1814;">{palette_name}</div>'
293
- html += f'<div style="font-size:13px; color:#666;">{str(row["skin_tone"]).title()} Skin · {str(row["undertone"]).title()} Undertone · {str(row["style_preference"]).title()} Style</div>'
294
- html += f'</div>'
295
- html += f'<div class="section-split">'
296
- html += f'<div class="results-box"><h3>COLORS FOR YOU</h3><div class="swatch-grid">{swatches}</div></div>'
297
- html += f'<div class="results-box"><h3>STYLIST TIP</h3><p class="tip-text">{caption}</p></div>'
298
- html += f'</div>'
299
- return html
300
-
301
- def build_outfit_component_cards_html(row):
302
- colors = [c.strip() for c in str(row["recommended_colors"]).split(",") if c.strip()] or ["neutral"]
303
- components = [
304
- ("TOP", row.get("outfit_top", "Top"), "zara", "search_query_zara"),
305
- ("TROUSERS", row.get("outfit_bottom", "Trousers"), "asos", "search_query_asos"),
306
- ("SHOES", row.get("outfit_shoes", "Shoes"), "zara", "search_query_zara"),
307
- ("JACKET", "Tailored Jacket Profile", "hm", "search_query_hm"),
308
- {"category": "BAG", "name": "Minimalist Tote Bag", "retailer": "asos", "query": "structured tan tote bag"},
309
- {"category": "DRESS", "name": "Classic Slip Midi Dress", "retailer": "zara", "query": "terracotta slip midi dress"}
310
- ]
311
-
312
- cards = []
313
- for i, comp in enumerate(components):
314
- if isinstance(comp, dict):
315
- label, item_name, retailer = comp["category"], comp["name"], comp["retailer"]
316
- link = to_shop_link(retailer, comp["query"], row["gender"])
317
- else:
318
- label, item_name, retailer, col = comp
319
- link = to_shop_link(retailer, row.get(col, item_name), row["gender"])
320
-
321
- raw_color = _swatch_color(colors[i % len(colors)])
322
- banner_color = _lighten_hex(raw_color, 0.88)
323
-
324
- card_html = f'<div class="product-card">'
325
- card_html += f'<div class="card-color-header" style="background-color:{banner_color};">'
326
- card_html += f'<div class="prod-bubble" style="background-color:{raw_color};"></div>'
327
- card_html += f'</div>'
328
- card_html += f'<div class="prod-meta">'
329
- card_html += f'<span class="prod-cat">{label}</span>'
330
- card_html += f'<p class="prod-title">{str(item_name).title()}</p>'
331
- card_html += f'<span class="prod-brand">{retailer.upper()}</span>'
332
- card_html += f'<a href="{link}" target="_blank" rel="noopener noreferrer" class="shop-btn">Shop ↗</a>'
333
- card_html += f'</div>'
334
- card_html += f'</div>'
335
- cards.append(card_html)
336
-
337
- return f'<div class="outfit-grid">{"".join(cards)}</div>'
338
-
339
- def build_more_matches_html(matched_indices, similarities):
340
- cards = []
341
- for idx, sim in list(zip(matched_indices, similarities))[1:4]:
342
- row = df.iloc[idx]
343
- img_b64 = pil_to_base64(images[idx])
344
- link = to_shop_link("zara", row.get("search_query_zara", "clothing"), row["gender"])
345
- card_html = f'<div class="product-card">'
346
- card_html += f'<img src="data:image/jpeg;base64,{img_b64}" style="width:100%;height:150px;object-fit:cover;display:block;"/>'
347
- card_html += f'<div class="prod-meta">'
348
- card_html += f'<span class="prod-brand">Match score: {sim}</span>'
349
- card_html += f'<a href="{link}" target="_blank" rel="noopener noreferrer" class="shop-btn">Shop ↗</a>'
350
- card_html += f'</div></div>'
351
- cards.append(card_html)
352
- return f'<div class="more-matches-label">MORE MATCHES LIKE THIS</div><div class="outfit-grid">{"".join(cards)}</div>'
353
-
354
- # ---------------------------------------------------------------------------
355
- # MAIN PIPELINES
356
- # ---------------------------------------------------------------------------
357
- def run_pipeline(matched_indices, matched_rows, matched_scores, base_image=None, question=None, expected_gender=None):
358
- if len(matched_indices) == 0:
359
- return "<i>No matches found — try different filters.</i>", None, "", "<div></div>"
360
- similarity = [round(1.0 - (d / 2.0), 3) for d in matched_scores]
361
- top_row = matched_rows.iloc[0]
362
- edit_base_image = base_image if base_image is not None else images[matched_indices[0]]
363
- gender_for_generation = expected_gender or top_row["gender"]
364
-
365
- caption = generate_stylist_caption(top_row)
366
- new_image, _ = generate_new_outfit_image(edit_base_image, top_row, target_gender=gender_for_generation)
367
- answer = answer_question_about_image(edit_base_image, question) if question else ""
368
-
369
- style_card_html = build_style_card_html(top_row, caption)
370
- outfit_cards_html = build_outfit_component_cards_html(top_row) + build_more_matches_html(matched_indices, similarity)
371
- return style_card_html, new_image, answer, outfit_cards_html
372
-
373
- def recommend_from_photo(photo, gender, age_group, question):
374
- if photo is None:
375
- return "<i>Please upload a photo or pick a Quick Starter.</i>", None, "", "<div></div>"
376
- query_emb = embed_query_image(photo)
377
- idx, rows, scores = faiss_filtered_search(query_emb, gender=gender or None, age_group=age_group or None)
378
- return run_pipeline(idx, rows, scores, base_image=photo, question=question, expected_gender=gender)
379
-
380
- def recommend_from_features(skin_tone, undertone, style, gender, age_group, question):
381
- sentence = build_feature_sentence(skin_tone, undertone, style, gender, age_group)
382
- query_emb = embed_query_text(sentence)
383
- idx, rows, scores = faiss_filtered_search(query_emb, gender=gender or None, age_group=age_group or None)
384
- return run_pipeline(idx, rows, scores, base_image=None, question=question, expected_gender=gender)
385
-
386
- def build_feature_pills_html(labels, selected, title):
387
- pills = ""
388
- for label in labels:
389
- active = str(label).strip().lower() == str(selected).strip().lower()
390
- border = "2px solid #D2527F" if active else "1.5px solid #ECE4D6"
391
- bg = "#FFF0F5" if active else "#FFFFFF"
392
- tcol = "#D2527F" if active else "#2C2A29"
393
- dot = _swatch_color(label) if title != "Style" else "#C69E6E"
394
- pills += f'<div style="display:inline-flex;align-items:center;gap:7px;padding:8px 14px;border-radius:30px;border:{border};background:{bg};margin:4px;"><div style="width:12px;height:12px;border-radius:50%;background:{dot};border:1px solid rgba(0,0,0,.1);"></div><span style="font-size:13px;font-weight:600;color:{tcol};">{str(label).title()}</span></div>'
395
- return f'<div style="margin-bottom:14px;"><div style="font-size:11px;font-weight:700;color:#8A7F6E;text-transform:uppercase;letter-spacing:.1em;margin-bottom:8px;">{title}</div><div style="display:flex;flex-wrap:wrap;margin:-4px;">{pills}</div></div>'
396
-
397
- def build_features_recap_html(skin_tone, undertone, style):
398
- return f'<div style="background:#fff;border-radius:16px;padding:24px;margin-bottom:20px;border:1px solid #ECE4D6;"><div style="font-size:12px;font-weight:700;color:#D2527F;text-transform:uppercase;letter-spacing:.1em;margin-bottom:16px;">Your Selected Specifications</div>{build_feature_pills_html(SKIN_TONES, skin_tone, "Skin tone")}{build_feature_pills_html(UNDERTONES, undertone, "Undertone")}{build_feature_pills_html(STYLES, style, "Style")}</div>'
399
-
400
- # ---------------------------------------------------------------------------
401
- # FIXED GRADIO 6 COMPLIANT LUXURY THEME
402
- # ---------------------------------------------------------------------------
403
- CUSTOM_CSS = """
404
- @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght=600;700&family=Inter:wght=400;500;600;700&display=swap');
405
- body, .gradio-container { background-color: #F8F5F5 !important; font-family: 'Inter', sans-serif !important; }
406
- .gradio-container { max-width: 850px !important; margin: 0 auto !important; padding-top: 20px !important; }
407
- footer { display: none !important; }
408
-
409
- h1, h2, h3, p, span, label, input, select, textarea, button { color: #2C2A29 !important; }
410
-
411
- .tab-nav button { font-size: 14px !important; font-weight: 600 !important; padding: 14px 24px !important; color: #555 !important; }
412
- .tab-nav button.selected { color: #D2527F !important; border-bottom: 2px solid #D2527F !important; }
413
-
414
- #find-btn, .big-btn { background: #161617 !important; color: #FFFFFF !important; border: none !important; border-radius: 8px !important; font-weight: 700 !important; font-size: 14px !important; padding: 14px !important; text-transform: uppercase; letter-spacing: .08em !important; width: 100% !important; margin-top: 10px; }
415
- #find-btn:hover, .big-btn:hover { background: #2D2D2F !important; }
416
-
417
- .dark-panel { background: #FFFFFF !important; border-radius: 16px !important; padding: 24px !important; border: 1px solid #ECE4D6 !important; margin-bottom: 20px; }
418
- .dark-panel label, .dark-panel span { color: #2C2A29 !important; font-weight: 600; }
419
-
420
- input, select, .secondary, .wrap, .slots, .single-select, .select-wrap {
421
- color: #2C2A29 !important;
422
- background-color: #FFFFFF !important;
423
- border: 1px solid #E3DFDA !important;
424
- border-radius: 4px !important;
425
- }
426
- div.form { background: transparent !important; border: none !important; box-shadow: none !important; }
427
- fieldset { display: flex !important; justify-content: center !important; gap: 24px !important; border: none !important; background: transparent !important; }
428
-
429
- .palette-premium-banner { background: #FAF3ED; padding: 24px; border-radius: 12px; margin-bottom: 20px; border-left: 5px solid #C69E6E; }
430
- .section-split { display: grid !important; grid-template-columns: repeat(2, 1fr) !important; gap: 20px !important; margin-top: 20px !important; width: 100% !important; }
431
- @media (max-width: 768px) { .section-split { grid-template-columns: 1fr !important; } }
432
-
433
- .results-box { background: #FFFFFF; border-radius: 16px; padding: 24px; border: 1px solid #EFECE8; }
434
- .results-box h3 { font-size: 11px; font-weight: 700; color: #9C8E82 !important; letter-spacing: 1.5px; text-transform: uppercase; margin: 0 0 14px; }
435
- .swatch-grid { display: flex; gap: 16px; flex-wrap: wrap; }
436
- .swatch-card { text-align: center; font-size: 12px; color: #666666 !important; width: 60px; }
437
- .color-bubble { width: 44px; height: 44px; border-radius: 50%; margin: 0 auto 6px; border: 1px solid rgba(0,0,0,.06); box-shadow: inset 0 0 0 2px #FFF; }
438
- .tip-text { font-size: 15px; color: #222222 !important; line-height: 1.6; margin: 0; font-style: italic; }
439
-
440
- .outfit-grid { display: grid !important; grid-template-columns: repeat(3, 1fr) !important; gap: 20px !important; margin-top: 20px !important; width: 100% !important; }
441
- @media (max-width: 768px) { .outfit-grid { grid-template-columns: repeat(2, 1fr) !important; } }
442
- @media (max-width: 480px) { .outfit-grid { grid-template-columns: 1fr !important; } }
443
-
444
- .product-card { background: #FFFFFF; border: 1px solid #EFECE8; border-radius: 16px; overflow: hidden; display: flex; flex-direction: column; box-shadow: 0 4px 12px rgba(0,0,0,0.01); width: 100% !important; }
445
- .card-color-header { width: 100%; height: 95px; display: flex; align-items: center; justify-content: center; }
446
- .prod-bubble { width: 46px; height: 46px; border-radius: 50%; box-shadow: 0 2px 8px rgba(0,0,0,0.04); }
447
- .prod-meta { padding: 20px; display: flex; flex-direction: column; align-items: flex-start; text-align: left; width: 100%; }
448
- .prod-cat { font-size: 11px; font-weight: 700; color: #D2527F !important; letter-spacing: 0.5px; text-transform: uppercase; margin-bottom: 4px; }
449
- .prod-title { font-size: 15px; font-weight: 700; color: #111111 !important; margin: 0 0 4px 0; line-height: 1.3; min-height: 40px; display: flex; align-items: center; }
450
- .prod-brand { font-size: 13px; color: #999999 !important; margin-bottom: 14px; display: block; }
451
-
452
- .shop-btn { display: block; width: 100%; background: #161617; color: #FFFFFF !important; text-align: center; padding: 11px 0; border-radius: 8px; font-size: 13px; font-weight: 700; text-decoration: none !important; letter-spacing: 0.5px; }
453
- .shop-btn:hover { background: #2D2D2F; color: #FFFFFF !important; }
454
- .more-matches-label { font-size: 11px; font-weight: 700; color: #9C8E82 !important; letter-spacing: 1.6px; text-transform: uppercase; margin: 24px 0 12px; }
455
- .palette-name { font-family: 'Playfair Display', serif !important; }
456
- """
457
-
458
- # ---------------------------------------------------------------------------
459
- # INTERFACE BUILD
460
- # ---------------------------------------------------------------------------
461
- with gr.Blocks(title="Personal Color Styling") as demo:
462
- gr.HTML("""
463
- <div style="text-align:center; padding:24px 20px 10px;">
464
- <div style="font-size:11px; font-weight:700; color:#D2527F; letter-spacing:.18em; text-transform:uppercase; margin-bottom:8px;">Personal Color Styling</div>
465
- <div class="palette-name" style="font-size:38px; font-weight:700; color:#111; margin-bottom:6px;">LookMatch</div>
466
- <div style="font-size:14px; color:#666; max-width:480px; margin:0 auto; line-height:1.6;">
467
- Upload a photo or describe your features — receive a curated palette, a personal stylist note, and a brand-new look generated just for you.
468
- </div>
469
- </div>
470
- """)
471
-
472
- with gr.Tab("📸 Upload a Photo"):
473
- with gr.Row():
474
- photo_in = gr.Image(type="pil", label="Your photo")
475
- with gr.Column():
476
- gender_a = gr.Dropdown(GENDERS, label="Gender (optional)")
477
- age_a = gr.Dropdown(AGE_GROUPS, label="Age group (optional)")
478
- question_a = gr.Textbox(label="Ask the stylist a question about your photo (optional)", placeholder="e.g. What style would suit me best?")
479
- btn_a = gr.Button("Get my look ✨", elem_id="find-btn", variant="primary")
480
-
481
- style_card_a = gr.HTML()
482
- new_img_a = gr.Image(label="✨ Your New AI-Generated Look")
483
- answer_a = gr.Textbox(label="Answer to your question")
484
- outfit_cards_a = gr.HTML()
485
-
486
- btn_a.click(
487
- recommend_from_photo,
488
- [photo_in, gender_a, age_a, question_a],
489
- [style_card_a, new_img_a, answer_a, outfit_cards_a],
490
- )
491
-
492
- gr.Examples(
493
- examples=[
494
- [SAMPLE_PHOTOS[0], "woman", "adult", "What style would suit me best?"],
495
- [SAMPLE_PHOTOS[1], "man", "adult", "What style would suit me best?"],
496
- [SAMPLE_PHOTOS[2], "woman", "teen", "What style would suit me best?"]
497
- ],
498
- inputs=[photo_in, gender_a, age_a, question_a],
499
- outputs=[style_card_a, new_img_a, answer_a, outfit_cards_a],
500
- fn=recommend_from_photo,
501
- cache_examples=False,
502
- label="Quick Starters",
503
- )
504
-
505
- with gr.Tab("🎨 Choose Manually"):
506
- gr.Markdown("Select your skin tone, undertone and style below.")
507
- with gr.Group(elem_classes="dark-panel"):
508
- with gr.Row():
509
- skin_b = gr.Dropdown(SKIN_TONES, label="Skin tone", value=SKIN_TONES[0])
510
- undertone_b = gr.Dropdown(UNDERTONES, label="Undertone", value=UNDERTONES[0])
511
- style_b = gr.Dropdown(STYLES, label="Style preference", value=STYLES[0])
512
- with gr.Row():
513
- gender_b = gr.Dropdown(GENDERS, label="Gender", value=GENDERS[0])
514
- age_b = gr.Dropdown(AGE_GROUPS, label="Age group", value=AGE_GROUPS[0])
515
- question_b = gr.Textbox(label="Ask the stylist a question about the top match (optional)", placeholder="e.g. Is this outfit formal or casual?")
516
- btn_b = gr.Button("Get my look ✨", elem_id="find-btn", variant="primary")
517
-
518
- features_recap_b = gr.HTML(build_features_recap_html(SKIN_TONES[0], UNDERTONES[0], STYLES[0]))
519
- for _dropdown in (skin_b, undertone_b, style_b):
520
- _dropdown.change(build_features_recap_html, [skin_b, undertone_b, style_b], features_recap_b)
521
-
522
- style_card_b = gr.HTML()
523
- new_img_b = gr.Image(label="✨ Your New AI-Generated Look")
524
- answer_b = gr.Textbox(label="Answer to your question")
525
- outfit_cards_b = gr.HTML()
526
-
527
- btn_b.click(
528
- recommend_from_features,
529
- [skin_b, undertone_b, style_b, gender_b, age_b, question_b],
530
- [style_card_b, new_img_b, answer_b, outfit_cards_b],
531
- )
532
-
533
- if __name__ == "__main__":
534
- demo.launch(css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="amber"))