romi2001 commited on
Commit
81262b5
·
verified ·
1 Parent(s): fcb5431

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +668 -194
app.py CHANGED
@@ -1,214 +1,688 @@
1
- import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import numpy as np
 
 
 
 
 
3
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- # ==========================================
6
- # 1. DYNAMIC COLOR PROFILE & STORE INTEGRATION
7
- # ==========================================
8
-
9
- COLOR_PALETTES = {
10
- "Light-Black-Brown": {
11
- "name": "WARM AUTUMN AMBER",
12
- "description": "Light Skin · Black Hair · Brown Eyes",
13
- "swatches": [
14
- {"name": "Peach", "hex": "#FBC299"},
15
- {"name": "Warm Camel", "hex": "#C69E6E"},
16
- {"name": "Coral", "hex": "#F27E73"},
17
- {"name": "Ivory", "hex": "#FAF9ED"}
18
- ],
19
- "tip": "Warm peachy tones are universally flattering on you."
20
- }
21
  }
22
 
23
- # קישורים ישירים לעמודי החיפוש והסינון לפי הצבע המדויק של הפרופיל
24
- RECOMMENDED_LOOKS = {
25
- "Light-Black-Brown": [
26
- {"category": "TOP", "name": "Rust Wrap Blouse", "brand": "SHEIN", "hex": "#C64614", "bg": "#F5E6E1", "url": "https://www.shein.com/alls/Rust-Blouse-vc-29505.html"},
27
- {"category": "TROUSERS", "name": "Camel Wide-Leg Trousers", "brand": "ASOS", "hex": "#C69E6E", "bg": "#F3EFE3", "url": "https://www.asos.com/search/?q=camel+wide+leg+trousers"},
28
- {"category": "SHOES", "name": "Cognac Leather Mules", "brand": "Zara", "hex": "#9B4E2E", "bg": "#EDE3DD", "url": "https://www.zara.com/search?searchTerm=cognac+leather"},
29
- {"category": "JACKET", "name": "Olive Linen Blazer", "brand": "H&M", "hex": "#8FA160", "bg": "#E9ECE1", "url": "https://2.hm.com/search?q=olive+linen+blazer"},
30
- {"category": "BAG", "name": "Tan Structured Tote", "brand": "SHEIN", "hex": "#D3B287", "bg": "#F4ECE2", "url": "https://www.shein.com/alls/Tan-Bag-vc-32759.html"},
31
- {"category": "DRESS", "name": "Terracotta Midi Slip Dress", "brand": "ASOS", "hex": "#CD6A46", "bg": "#F5E6E1", "url": "https://www.asos.com/search/?q=terracotta+midi+dress"}
32
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  }
34
 
35
- def build_product_card(item):
36
- card_html = '<div class="product-card">'
37
- card_html += f'<div class="card-color-header" style="background-color: {item["bg"]};">'
38
- card_html += f'<div class="prod-bubble" style="background-color: {item["hex"]};"></div>'
39
- card_html += '</div>'
40
- card_html += '<div class="prod-meta">'
41
- card_html += f'<span class="prod-cat">{item["category"]}</span>'
42
- card_html += f'<p class="prod-title">{item["name"]}</p>'
43
- card_html += f'<span class="prod-brand">{item["brand"]}</span>'
44
- card_html += f'<a href="{item["url"]}" target="_blank" rel="noopener noreferrer" class="shop-btn">Shop ↗</a>'
45
- card_html += '</div>'
46
- card_html += '</div>'
47
- return card_html
48
-
49
- def analyze_and_recommend(image, skin, hair, eye, choice_method):
50
- if choice_method == "Upload a photo" and image is not None:
51
- skin_tone, hair_color, eye_color = "Light", "Black", "Brown"
52
- else:
53
- skin_tone, hair_color, eye_color = skin, hair, eye
54
-
55
- palette_key = f"{skin_tone}-{hair_color}-{eye_color}"
56
-
57
- palette = COLOR_PALETTES.get(palette_key, COLOR_PALETTES["Light-Black-Brown"])
58
- look_items = RECOMMENDED_LOOKS.get(palette_key, RECOMMENDED_LOOKS["Light-Black-Brown"])
59
-
60
- swatches_html = "".join([
61
- f'<div class="swatch-card"><div class="color-bubble" style="background-color: {s["hex"]};"></div><p>{s["name"]}</p></div>'
62
- for s in palette["swatches"]
63
- ])
64
-
65
- outfit_html = "".join([build_product_card(item) for item in look_items])
66
-
67
- palette_results = f"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  <div class="section-split">
69
- <div class="results-box">
70
- <h3>COLORS FOR YOU</h3>
71
- <div class="swatch-grid">{swatches_html}</div>
72
- </div>
73
- <div class="results-box">
74
- <h3>STYLIST TIP</h3>
75
- <p class="tip-text">{palette["tip"]}</p>
76
- </div>
77
  </div>
78
  """
79
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  return (
81
- gr.update(value=skin_tone),
82
- gr.update(value=hair_color),
83
- gr.update(value=eye_color),
84
- palette_results,
85
- outfit_html,
86
- gr.update(visible=True)
87
  )
88
 
89
- # ==========================================
90
- # 2. EXACT ORIGINAL LOOKMATCH PILL & GRID STYLES
91
- # ==========================================
92
- lookmatch_css = """
93
- body, .gradio-container { background-color: #F8F5F5 !important; font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
94
- .gradio-container { max-width: 850px !important; margin: 0 auto !important; padding-top: 20px !important; }
95
- .center-text { text-align: center; }
96
-
97
- /* כותרות ומלל */
98
- .prod-cat { font-size: 11px; font-weight: 700; color: #D2527F !important; letter-spacing: 1.5px; text-transform: uppercase; }
99
- .title-main { font-size: 42px; font-weight: 800; color: #111111 !important; margin-bottom: 2px; letter-spacing: -1px; }
100
- .subtitle-main { font-size: 15px; color: #888888 !important; margin-bottom: 30px; }
101
- h3 { font-size: 12px; font-weight: 700; color: #A4A1A1 !important; letter-spacing: 1px; margin-top: 0; margin-bottom: 16px; }
102
-
103
- /* תיקון קריטי: מניעת כיתוב לבן נעלם בגרדיו 6 */
104
- input, select, textarea, .secondary, .wrap, .slots, .single-select, .select-wrap, span, label, button, p {
105
- color: #111111 !important;
106
- font-family: -apple-system, BlinkMacSystemFont, sans-serif !important;
107
- }
108
- .gr-box, input, select {
109
- background-color: #FFFFFF !important;
110
- border: 1px solid #E2DFDA !important;
111
- }
112
- div.form { background: transparent !important; border: none !important; box-shadow: none !important; }
113
-
114
- /* יישור טאבים */
115
- fieldset { display: flex !important; justify-content: center !important; gap: 24px !important; border: none !important; background: transparent !important; }
116
-
117
- /* קופסאות בלוק תוצאה */
118
- .section-split { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-top: 24px; width: 100% !important; }
119
- @media (max-width: 768px) { .section-split { grid-template-columns: 1fr; } }
120
- .results-box { background: #FFFFFF; border-radius: 16px; padding: 24px; border: 1px solid #EFECE8; }
121
- .swatch-grid { display: flex; gap: 20px; justify-content: flex-start; }
122
- .swatch-card { text-align: center; font-size: 12px; color: #666666 !important; width: 64px; }
123
- .color-bubble { width: 48px; height: 48px; border-radius: 50%; margin: 0 auto 8px auto; border: 1px solid rgba(0,0,0,0.05); }
124
- .tip-text { font-size: 16px; color: #222222 !important; line-height: 1.5; margin: 0; }
125
-
126
- /* תיקון גריד מלא: מניעת דחיסה הצידה וחיתוכים */
127
- .outfit-grid {
128
- display: grid !important;
129
- grid-template-columns: repeat(3, 1fr) !important;
130
- gap: 20px !important;
131
- margin-top: 20px !important;
132
- width: 100% !important;
133
- }
134
- @media (max-width: 768px) { .outfit-grid { grid-template-columns: repeat(2, 1fr) !important; } }
135
- @media (max-width: 480px) { .outfit-grid { grid-template-columns: 1fr !important; } }
136
-
137
- /* עיצוב כרטיסיות הלבוש */
138
- .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; }
139
- .card-color-header { width: 100%; height: 95px; display: flex; align-items: center; justify-content: center; }
140
- .prod-bubble { width: 46px; height: 46px; border-radius: 50%; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
141
- .prod-meta { padding: 20px; display: flex; flex-direction: column; align-items: flex-start; text-align: left; width: 100%; }
142
- .prod-meta .prod-cat { font-size: 11px; font-weight: 700; color: #D2527F !important; letter-spacing: 0.5px; text-transform: uppercase; margin-bottom: 4px; }
143
- .prod-title { font-size: 16px; font-weight: 700; color: #111111 !important; margin: 0 0 4px 0; line-height: 1.3; min-height: 42px; display: flex; align-items: center; }
144
- .prod-brand { font-size: 14px; color: #999999 !important; margin-bottom: 16px; display: block; }
145
-
146
- /* כפתורי הרכישה - שחור בולט וברור */
147
- .shop-btn { display: block; width: 100%; background: #161617; color: #FFFFFF !important; text-align: center; padding: 12px 0; border-radius: 8px; font-size: 14px; font-weight: 700; text-decoration: none !important; letter-spacing: 0.5px; box-sizing: border-box; }
148
- .shop-btn:hover { background: #2D2D2F; }
149
-
150
- /* כפתור הפעולה הראשי */
151
- .primary-action-btn { background: #161617 !important; color: #FFFFFF !important; border: none !important; border-radius: 8px !important; font-weight: 700 !important; font-size: 15px !important; padding: 12px 0 !important; text-transform: uppercase; margin-top: 10px; width: 100% !important; }
152
-
153
- /* פילטרים תחתונים */
154
- .pill-container button { background: #FFFFFF !important; border: 1px solid #E3DFDA !important; border-radius: 4px !important; font-size: 11px !important; font-weight: 700 !important; color: #555555 !important; text-transform: uppercase; letter-spacing: 0.5px; }
155
- .footer-note { font-size: 13px; color: #A0A0A0 !important; text-align: center; margin-top: 20px; margin-bottom: 30px; }
156
- """
157
 
158
- # ==========================================
159
- # 3. INTERFACE BUILD
160
- # ==========================================
161
- with gr.Blocks(css=lookmatch_css) as demo:
162
-
163
- with gr.Group(elem_classes="center-text"):
164
- gr.Markdown("PERSONAL COLOR STYLING", show_label=False)
165
- gr.Markdown("# LookMatch", elem_classes="title-main")
166
- gr.Markdown("Discover your perfect color palette and outfit", elem_classes="subtitle-main")
167
-
168
- choice_method = gr.Radio(
169
- ["Upload a photo", "Choose manually"],
170
- value="Upload a photo",
171
- show_label=False,
172
- interactive=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  )
 
174
 
175
- with gr.Row():
176
- with gr.Column() as upload_col:
177
- image_input = gr.Image(label="Upload your photo — Gemini AI will detect your features", type="pil")
178
-
179
- with gr.Column(visible=False) as manual_col:
180
- skin_dropdown = gr.Dropdown(["Fair", "Light", "Medium", "Olive", "Tan", "Deep"], value="Light", label="Skin tone")
181
- hair_dropdown = gr.Dropdown(["Blonde", "Auburn/Red", "Brunette", "Black", "Grey/White"], value="Black", label="Hair color")
182
- eye_dropdown = gr.Dropdown(["Blue", "Green", "Hazel", "Brown", "Dark brown/Black"], value="Brown", label="Eye color")
183
-
184
- submit_btn = gr.Button("Get my look ✨", elem_classes="primary-action-btn")
185
-
186
- # הסרת המיקום בעמודות פנימיות כדי למנוע את החיתוך הצידה
187
- with gr.Column(visible=False) as output_dashboard:
188
- gr.Markdown("### YOUR FEATURES")
189
- with gr.Row(elem_classes="pill-container"):
190
- skin_tag = gr.Button(value="Light", size="sm")
191
- hair_tag = gr.Button(value="Black", size="sm")
192
- eye_tag = gr.Button(value="Brown", size="sm")
193
-
194
- palette_output = gr.HTML()
195
-
196
- gr.Markdown("### OUTFIT PICKS")
197
- outfit_output = gr.HTML(elem_classes="outfit-grid")
198
- gr.Markdown("Links open in a new tab", elem_classes="footer-note")
199
-
200
- def toggle_input_ui(choice):
201
- if choice == "Choose manually":
202
- return gr.update(visible=False), gr.update(visible=True)
203
- return gr.update(visible=True), gr.update(visible=False)
204
-
205
- choice_method.change(toggle_input_ui, inputs=choice_method, outputs=[upload_col, manual_col])
206
-
207
- submit_btn.click(
208
- fn=analyze_and_recommend,
209
- inputs=[image_input, skin_dropdown, hair_dropdown, eye_dropdown, choice_method],
210
- outputs=[skin_tag, hair_tag, eye_tag, palette_output, outfit_output, output_dashboard]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  )
212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  if __name__ == "__main__":
214
  demo.launch()
 
1
+ """
2
+ AI Fashion Stylist — Hugging Face Space app
3
+ Combines: CLIP recommendation engine (Part 3) + 3 GenAI patterns (Part 4):
4
+ 1. Small Language Model -> generates text (Qwen2.5-0.5B-Instruct)
5
+ 2. Small Vision-Language Model -> answers questions (BLIP-VQA-base)
6
+ 3. Small Vision-Language pipeline -> generates an image (clothing segmentation + SD inpainting)
7
+
8
+ Deploy notes:
9
+ - Upload this file + requirements.txt + final_image_embeddings.npy + catalog_metadata.parquet
10
+ to your HF Space repo root.
11
+ - Update HF_DATASET_REPO / HF_WINNING_MODEL below if your repo names differ.
12
+ - Quick Starter sample photos are generated automatically from the dataset at startup -
13
+ no manual file upload needed.
14
+ """
15
+
16
+ import base64
17
+ import os
18
+ import urllib.parse
19
+ from io import BytesIO
20
+
21
  import numpy as np
22
+ import pandas as pd
23
+ import torch
24
+ import gradio as gr
25
+ import faiss
26
+ from datasets import load_dataset
27
  from PIL import Image
28
+ from scipy import ndimage
29
+ from transformers import (
30
+ CLIPModel, CLIPProcessor, pipeline as hf_pipeline,
31
+ BlipProcessor, BlipForQuestionAnswering,
32
+ SegformerImageProcessor, AutoModelForSemanticSegmentation,
33
+ )
34
+ from diffusers import StableDiffusionInpaintPipeline
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # CONFIG — update these to match your own HF repos
38
+ # ---------------------------------------------------------------------------
39
+ HF_DATASET_REPO = "lihicarmeli/fashion-stylist-multimodal-v2" # your HF dataset repo
40
+ HF_WINNING_MODEL = "openai/clip-vit-base-patch32" # winning embedding model (Part 3)
41
+ EMBEDDINGS_FILE = "final_image_embeddings.npy" # uploaded next to this app.py
42
+ METADATA_FILE = "catalog_metadata.parquet" # uploaded next to this app.py
43
+
44
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
45
+
46
+ # ---------------------------------------------------------------------------
47
+ # LOAD DATA + WINNING EMBEDDING MODEL (runs once, on Space startup)
48
+ # ---------------------------------------------------------------------------
49
+ print("Loading dataset from HF Hub...")
50
+ ds = load_dataset(HF_DATASET_REPO)
51
+ df = ds["train"].to_pandas()
52
+ images = [ds["train"][i]["image_improved"] for i in range(len(ds["train"]))]
53
+
54
+ print("Generating Quick Starter sample photos from the dataset...")
55
+ SAMPLES_DIR = "samples_cache"
56
+ os.makedirs(SAMPLES_DIR, exist_ok=True)
57
+
58
+
59
+ def _pick_index(filter_fn, fallback_idx=0):
60
+ matches = df[df.apply(filter_fn, axis=1)]
61
+ return int(matches.index[0]) if len(matches) else fallback_idx
62
+
63
+
64
+ _sample_specs = [
65
+ ("demo_woman.jpg", lambda r: r["gender"] == "woman"),
66
+ ("demo_man.jpg", lambda r: r["gender"] == "man"),
67
+ ("demo_teen.jpg", lambda r: r["age_group"] == "teen"),
68
+ ]
69
+
70
+ SAMPLE_PHOTOS = []
71
+ for _filename, _filt in _sample_specs:
72
+ _idx = _pick_index(_filt, fallback_idx=len(SAMPLE_PHOTOS))
73
+ _path = os.path.join(SAMPLES_DIR, _filename)
74
+ images[_idx].convert("RGB").save(_path)
75
+ SAMPLE_PHOTOS.append(_path)
76
+ print(f" -> {len(SAMPLE_PHOTOS)} sample photos ready: {SAMPLE_PHOTOS}")
77
+
78
+ print("Loading precomputed embeddings...")
79
+ image_embeddings = np.load(EMBEDDINGS_FILE).astype("float32")
80
+
81
+ print("Loading winning embedding model (CLIP) from HF Hub...")
82
+ win_model = CLIPModel.from_pretrained(HF_WINNING_MODEL).to(DEVICE).eval()
83
+ win_processor = CLIPProcessor.from_pretrained(HF_WINNING_MODEL)
84
+
85
+ print("Building FAISS index...")
86
+ dimension = image_embeddings.shape[1]
87
+ faiss_img_index = faiss.IndexFlatL2(dimension)
88
+ faiss.normalize_L2(image_embeddings)
89
+ faiss_img_index.add(image_embeddings)
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # GENERATION MODELS — the 3 "Good Examples" patterns
93
+ # ---------------------------------------------------------------------------
94
+ print("Loading small language model for text generation (Qwen2.5-0.5B-Instruct)...")
95
+ caption_gen_pipe = hf_pipeline(
96
+ "text-generation",
97
+ model="Qwen/Qwen2.5-0.5B-Instruct",
98
+ device=0 if DEVICE == "cuda" else -1,
99
+ )
100
+
101
+ print("Loading small vision-language model for VQA (BLIP-VQA-base)...")
102
+ vqa_processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
103
+ vqa_model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(DEVICE)
104
+
105
+ print("Loading clothing segmentation model (helper - finds where the clothes are)...")
106
+ seg_processor = SegformerImageProcessor.from_pretrained("mattmdjaga/segformer_b2_clothes")
107
+ seg_model = AutoModelForSemanticSegmentation.from_pretrained("mattmdjaga/segformer_b2_clothes").to(DEVICE)
108
+
109
+ print("Loading image-generation model for the new outfit (Stable Diffusion Inpainting)...")
110
+ inpaint_pipe = StableDiffusionInpaintPipeline.from_pretrained(
111
+ "runwayml/stable-diffusion-inpainting",
112
+ torch_dtype=torch.float16 if DEVICE == "cuda" else torch.float32,
113
+ safety_checker=None,
114
+ ).to(DEVICE)
115
+
116
+ GENDERS = sorted(df["gender"].unique().tolist())
117
+ AGE_GROUPS = sorted(df["age_group"].unique().tolist())
118
+ SKIN_TONES = sorted(df["skin_tone"].unique().tolist())
119
+ UNDERTONES = sorted(df["undertone"].unique().tolist())
120
+ STYLES = sorted(df["style_preference"].unique().tolist())
121
+
122
+ print("Space ready.")
123
+
124
+
125
+ # ---------------------------------------------------------------------------
126
+ # EMBEDDING + SEARCH (Part 3 logic, unchanged)
127
+ # ---------------------------------------------------------------------------
128
+ @torch.no_grad()
129
+ def embed_query_image(pil_image):
130
+ inputs = win_processor(images=pil_image, return_tensors="pt").to(DEVICE)
131
+ feats = win_model.get_image_features(**inputs)
132
+ feats = feats.pooler_output if hasattr(feats, "pooler_output") else feats
133
+ return feats.cpu().numpy().astype("float32")
134
+
135
+
136
+ @torch.no_grad()
137
+ def embed_query_text(sentence):
138
+ inputs = win_processor(text=[sentence], return_tensors="pt", padding=True, truncation=True).to(DEVICE)
139
+ feats = win_model.get_text_features(**inputs)
140
+ feats = feats.pooler_output if hasattr(feats, "pooler_output") else feats
141
+ return feats.cpu().numpy().astype("float32")
142
+
143
+
144
+ def build_feature_sentence(skin_tone, undertone, style_preference, gender=None, age_group=None):
145
+ descriptor = " ".join(p for p in [age_group, gender] if p) or "person"
146
+ return (
147
+ f"a {descriptor} with {skin_tone} skin tone and {undertone} undertone, "
148
+ f"wearing a {style_preference} style outfit"
149
+ )
150
+
151
+
152
+ def faiss_filtered_search(query_emb, top_k=3, exclude_idx=None, gender=None, age_group=None):
153
+ faiss.normalize_L2(query_emb)
154
+ k = len(df)
155
+ distances, indices = faiss_img_index.search(query_emb, k)
156
+ distances, indices = distances[0], indices[0]
157
+
158
+ def collect(require_gender, require_age):
159
+ kept_i, kept_d = [], []
160
+ for idx, dist in zip(indices, distances):
161
+ if idx == -1 or (exclude_idx is not None and idx == exclude_idx):
162
+ continue
163
+ row = df.iloc[idx]
164
+ if require_gender and gender and str(row["gender"]).lower() != str(gender).lower():
165
+ continue
166
+ if require_age and age_group and str(row["age_group"]).lower() != str(age_group).lower():
167
+ continue
168
+ kept_i.append(idx)
169
+ kept_d.append(dist)
170
+ if len(kept_i) == top_k:
171
+ break
172
+ return kept_i, kept_d
173
+
174
+ kept_i, kept_d = collect(True, True)
175
+ if len(kept_i) < top_k:
176
+ kept_i, kept_d = collect(True, False)
177
+ if len(kept_i) < top_k:
178
+ kept_i, kept_d = collect(False, False)
179
+
180
+ return np.array(kept_i), df.iloc[kept_i], np.array(kept_d)
181
+
182
+
183
+ # ---------------------------------------------------------------------------
184
+ # GENERATION — 3 "Good Examples" patterns (Part 4)
185
+ # ---------------------------------------------------------------------------
186
+
187
+ # --- Pattern 1: small Language Model -> generate text ---
188
+ def generate_stylist_caption(row):
189
+ user_prompt = (
190
+ f"Write one short, warm sentence (max 25 words) from a fashion stylist, recommending this look: "
191
+ f"a {row['style_preference']} style outfit in {row['primary_color']} and {row['secondary_color']}, "
192
+ f"best colors: {row['recommended_colors']}. Be specific and stylish, no hashtags."
193
+ )
194
+ messages = [{"role": "user", "content": user_prompt}]
195
+ output = caption_gen_pipe(messages, max_new_tokens=40, do_sample=True, temperature=0.7)
196
+ return output[0]["generated_text"][-1]["content"].strip()
197
+
198
+
199
+ # --- Pattern 2: small Vision-Language Model -> answer questions about an image ---
200
+ @torch.no_grad()
201
+ def answer_question_about_image(pil_image, question):
202
+ inputs = vqa_processor(pil_image.convert("RGB"), question, return_tensors="pt").to(DEVICE)
203
+ output_ids = vqa_model.generate(**inputs, max_new_tokens=20)
204
+ return vqa_processor.decode(output_ids[0], skip_special_tokens=True)
205
+
206
+
207
+ # --- Pattern 3: small Vision-Language Model -> generate the FULL LOOK (full-body image) ---
208
+ FACE_LABEL_ID = 11
209
+ HAIR_LABEL_ID = 2
210
+
211
+
212
+ @torch.no_grad()
213
+ def get_face_protect_mask(pil_image, use_geometric_fallback=True):
214
+ """Returns a boolean mask (True = protect) covering the face + hair, at pil_image's own
215
+ resolution. Combines the segmentation model's prediction with a fixed geometric ellipse
216
+ (centered, where a face statistically sits in a headshot crop) as a safety net - so even
217
+ if segmentation misclassifies an unusual headwear/turban, the visible face is still
218
+ guaranteed to be protected."""
219
+ inputs = seg_processor(images=pil_image, return_tensors="pt").to(DEVICE)
220
+ logits = seg_model(**inputs).logits
221
+ upsampled = torch.nn.functional.interpolate(
222
+ logits, size=pil_image.size[::-1], mode="bilinear", align_corners=False
223
+ )
224
+ pred_seg = upsampled.argmax(dim=1)[0].cpu().numpy()
225
+ seg_protect = np.isin(pred_seg, [FACE_LABEL_ID, HAIR_LABEL_ID])
226
+
227
+ if not use_geometric_fallback:
228
+ return seg_protect
229
+
230
+ h, w = seg_protect.shape
231
+ yy, xx = np.mgrid[0:h, 0:w]
232
+ cy, cx = h * 0.42, w * 0.5 # face center: slightly above vertical middle of a headshot
233
+ ry, rx = h * 0.30, w * 0.22 # ellipse radii tuned for a tight headshot/bust crop
234
+ geometric_protect = (((xx - cx) / rx) ** 2 + ((yy - cy) / ry) ** 2) <= 1.0
235
+
236
+ return seg_protect | geometric_protect
237
+
238
+
239
+ def build_full_look_prompt(row):
240
+ gender_word = "man" if str(row["gender"]).lower() in ("man", "male") else "woman"
241
+ return (
242
+ f"full body fashion photo of a {row['age_group']} {gender_word}, standing, "
243
+ f"wearing a {row['style_preference']} style outfit: {row['outfit_top']}, "
244
+ f"{row['outfit_bottom']}, {row['outfit_shoes']}, {row['outfit_accessory']}, "
245
+ f"in {row['primary_color']} and {row['secondary_color']}, "
246
+ f"studio lighting, plain background, head to toe, high quality fashion photography"
247
+ )
248
+
249
+
250
+ def generate_new_outfit_image(pil_image, row, target_gender=None, canvas_size=(512, 1024),
251
+ head_width_frac=0.45, steps=40, guidance_scale=8.0):
252
+ """Generates the FULL LOOK: keeps the original face pixel-identical (scaled down to a
253
+ realistic head-to-body proportion) and generates the rest of a standing figure wearing
254
+ the complete recommended outfit (top, bottom, shoes, accessory) around it."""
255
+ if target_gender is not None and str(row["gender"]).lower() != str(target_gender).lower():
256
+ print(f"⚠️ Warning: recommended row gender ({row['gender']}) != expected gender "
257
+ f"({target_gender}) - double-check which matched_rows was passed in.")
258
+
259
+ base = pil_image.convert("RGB")
260
+ protect = get_face_protect_mask(base) # (H, W) bool, at base's own resolution
261
+
262
+ canvas_w, canvas_h = canvas_size
263
+ head_w = int(canvas_w * head_width_frac)
264
+ scale = head_w / base.width
265
+ head_h = int(base.height * scale)
266
+
267
+ resized_face_crop = base.resize((head_w, head_h))
268
+ resized_protect_img = Image.fromarray(protect.astype(np.uint8) * 255).resize(
269
+ (head_w, head_h), resample=Image.NEAREST
270
+ )
271
+
272
+ canvas = Image.new("RGB", canvas_size, color=(128, 128, 128))
273
+ paste_x = (canvas_w - head_w) // 2
274
+ paste_y = int(canvas_h * 0.03)
275
+ canvas.paste(resized_face_crop, (paste_x, paste_y))
276
+
277
+ mask_arr = np.full((canvas_h, canvas_w), 255, dtype=np.uint8) # 255 = let the model generate
278
+ protect_resized_arr = np.array(resized_protect_img) > 127
279
+ mask_arr[paste_y:paste_y + head_h, paste_x:paste_x + head_w][protect_resized_arr] = 0
280
+ mask = Image.fromarray(mask_arr).convert("L")
281
+
282
+ prompt = build_full_look_prompt(row)
283
+ generated = inpaint_pipe(
284
+ prompt=prompt,
285
+ image=canvas,
286
+ mask_image=mask,
287
+ num_inference_steps=steps,
288
+ guidance_scale=guidance_scale,
289
+ height=canvas_h,
290
+ width=canvas_w,
291
+ ).images[0]
292
 
293
+ # Hard-composite: guarantees zero change on the protected face/hair pixels
294
+ final_image = Image.composite(generated, canvas, mask)
295
+ return final_image, prompt
296
+
297
+
298
+ # ---------------------------------------------------------------------------
299
+ # SHOP LINKS (Part 3 logic, unchanged)
300
+ # ---------------------------------------------------------------------------
301
+ RETAILER_SEARCH_URLS = {
302
+ "zara": "https://www.zara.com/us/en/search?searchTerm={query}&section={section}",
303
+ "hm": "https://www2.hm.com/en_us/search-results.html?q={query}",
304
+ "asos": "https://www.asos.com/us/{dept}/search/?q={query}",
305
+ "mango": "https://shop.mango.com/us/en/search?kw={query}",
306
+ "shein": "https://us.shein.com/pdsearch/{query}/",
 
 
307
  }
308
 
309
+
310
+ def normalize_gender(gender):
311
+ g = str(gender).strip().lower() if gender is not None else ""
312
+ return "men" if g in ("male", "man", "men", "m") else "women"
313
+
314
+
315
+ def to_shop_link(retailer, value, gender=None):
316
+ dept = normalize_gender(gender)
317
+ if retailer == "zara":
318
+ section = "MAN" if dept == "men" else "WOMAN"
319
+ return RETAILER_SEARCH_URLS["zara"].format(query=urllib.parse.quote(str(value)), section=section)
320
+ if retailer == "asos":
321
+ return RETAILER_SEARCH_URLS["asos"].format(query=urllib.parse.quote(str(value)), dept=dept)
322
+ gender_word = "men's" if dept == "men" else "women's"
323
+ return RETAILER_SEARCH_URLS[retailer].format(query=urllib.parse.quote(f"{gender_word} {value}"))
324
+
325
+
326
+ def shop_links_markdown(row):
327
+ lines = []
328
+ for retailer, col in [("zara", "search_query_zara"), ("hm", "search_query_hm"),
329
+ ("asos", "search_query_asos"), ("mango", "search_query_mango"),
330
+ ("shein", "search_query_shein")]:
331
+ link = to_shop_link(retailer, row[col], gender=row["gender"])
332
+ lines.append(f"- **{retailer.upper()}**: [{row[col]}]({link})")
333
+ return "\n".join(lines)
334
+
335
+
336
+ # ---------------------------------------------------------------------------
337
+ # UI CARDS — original visual layer, built on top of the same Part 3+4 data
338
+ # ---------------------------------------------------------------------------
339
+ _SWATCH_CSS = {
340
+ "ice white": "#f4f3ee", "bold blue": "#1d4ed8", "royal blue": "#1e3a8a",
341
+ "fuchsia": "#c026d3", "cool red": "#dc2626", "deep teal": "#0f766e",
342
+ "plum": "#6b21a8", "silver": "#cbd5e1", "bright pink": "#ec4899",
343
+ "deep jewel tones": "#581c87", "rust": "#b45309", "camel": "#c19a6b",
344
+ "coral": "#fb7185", "ivory": "#fffff0", "olive": "#65730a",
345
+ "terracotta": "#c2643a",
346
+ }
347
+
348
+
349
+ def _swatch_color(name):
350
+ key = name.strip().lower()
351
+ if key in _SWATCH_CSS:
352
+ return _SWATCH_CSS[key]
353
+ # generic fallback so unseen color names still render *something* sensible
354
+ palette = ["#b45309", "#1d4ed8", "#c026d3", "#0f766e", "#dc2626", "#6b21a8"]
355
+ return palette[hash(key) % len(palette)]
356
+
357
+
358
+ def _lighten_hex(hex_color, factor=0.82):
359
+ hex_color = hex_color.lstrip("#")
360
+ r, g, b = int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
361
+ r = int(r + (255 - r) * factor)
362
+ g = int(g + (255 - g) * factor)
363
+ b = int(b + (255 - b) * factor)
364
+ return f"#{r:02x}{g:02x}{b:02x}"
365
+
366
+
367
+ _PALETTE_NAMES = {
368
+ "fair": {"cool": "Frost Bloom", "warm": "Sunlit Honey", "neutral": "Soft Linen"},
369
+ "light": {"cool": "Moonlit Rose", "warm": "Amber Glow", "neutral": "Quiet Dawn"},
370
+ "medium": {"cool": "Dusty Orchid", "warm": "Spiced Caramel", "neutral": "Warm Clay"},
371
+ "olive": {"cool": "Sage Twilight", "warm": "Bronzed Olive", "neutral": "Earth Tone"},
372
+ "tan": {"cool": "Copper Mist", "warm": "Golden Sand", "neutral": "Desert Bloom"},
373
+ "deep": {"cool": "Midnight Jewel", "warm": "Mahogany Sun", "neutral": "Onyx Velvet"},
374
  }
375
 
376
+
377
+ def get_palette_name(skin_tone, undertone):
378
+ return _PALETTE_NAMES.get(str(skin_tone).strip().lower(), {}).get(
379
+ str(undertone).strip().lower(), "Signature Palette"
380
+ )
381
+
382
+
383
+ def pil_to_base64(img, max_size=420):
384
+ img = img.convert("RGB").copy()
385
+ img.thumbnail((max_size, max_size))
386
+ buf = BytesIO()
387
+ img.save(buf, format="JPEG", quality=85)
388
+ return base64.b64encode(buf.getvalue()).decode("utf-8")
389
+
390
+
391
+ def build_feature_pills_html(labels, selected, title):
392
+ """Pill-style recap row (her visual pattern) - but built from your real, actually-used
393
+ attributes (skin tone / undertone / style), not placeholder categories."""
394
+ pills = ""
395
+ for label in labels:
396
+ active = label == selected
397
+ border = "2px solid #D2527F" if active else "1.5px solid #E8E0E8"
398
+ bg = "#FFF0F5" if active else "#FFFFFF"
399
+ tcol = "#D2527F" if active else "#444"
400
+ dot = _swatch_color(label) if title != "Style" else "#C19A6B"
401
+ pills += (
402
+ f'<div style="display:inline-flex;align-items:center;gap:7px;padding:8px 14px;'
403
+ f'border-radius:30px;border:{border};background:{bg};margin:4px;">'
404
+ f'<div style="width:14px;height:14px;border-radius:50%;background:{dot};'
405
+ f'border:1px solid rgba(0,0,0,.12);"></div>'
406
+ f'<span style="font-size:13px;font-weight:500;color:{tcol};">{label.title()}</span></div>'
407
+ )
408
+ return (
409
+ f'<div style="margin-bottom:14px;"><div style="font-size:11px;font-weight:600;color:#aaa;'
410
+ f'text-transform:uppercase;letter-spacing:.1em;margin-bottom:8px;">{title}</div>'
411
+ f'<div style="display:flex;flex-wrap:wrap;margin:-4px;">{pills}</div></div>'
412
+ )
413
+
414
+
415
+ def build_features_recap_html(skin_tone, undertone, style):
416
+ return (
417
+ '<div style="background:#fff;border-radius:16px;padding:18px 20px;'
418
+ 'margin-bottom:14px;border:1px solid #F0E8F0;">'
419
+ '<div style="font-size:11px;font-weight:600;color:#D2527F;text-transform:uppercase;'
420
+ 'letter-spacing:.1em;margin-bottom:14px;">Your Features</div>'
421
+ + build_feature_pills_html(SKIN_TONES, skin_tone, "Skin tone")
422
+ + build_feature_pills_html(UNDERTONES, undertone, "Undertone")
423
+ + build_feature_pills_html(STYLES, style, "Style")
424
+ + "</div>"
425
+ )
426
+ colors = [c.strip() for c in str(row["recommended_colors"]).split(",") if c.strip()][:4]
427
+ swatches = "".join(
428
+ f'<div class="swatch-card"><div class="color-bubble" style="background-color:{_swatch_color(c)};">'
429
+ f'</div><p>{c.title()}</p></div>'
430
+ for c in colors
431
+ )
432
+ palette_name = get_palette_name(row["skin_tone"], row["undertone"])
433
+ return f"""
434
+ <div style="position:relative;overflow:hidden;background:#161617;color:white;
435
+ border-radius:18px;padding:24px 28px;margin-bottom:16px;">
436
+ <div style="position:absolute;top:-40px;right:-40px;width:150px;height:150px;border-radius:50%;
437
+ background:rgba(210,82,127,.25);"></div>
438
+ <div style="font-size:11px;letter-spacing:1.5px;color:#D2527F;font-weight:700;">YOUR COLOR PALETTE</div>
439
+ <div style="font-size:30px;font-weight:800;margin:6px 0 4px;">{palette_name}</div>
440
+ <div style="font-size:13px;color:#bdb8c9;">
441
+ {row['skin_tone'].title()} skin · {row['undertone'].title()} undertone · {row['style_preference'].title()} style
442
+ </div>
443
+ </div>
444
  <div class="section-split">
445
+ <div class="results-box">
446
+ <h3>COLORS FOR YOU</h3>
447
+ <div class="swatch-grid">{swatches}</div>
448
+ </div>
449
+ <div class="results-box">
450
+ <h3>STYLIST TIP</h3>
451
+ <p class="tip-text">{caption}</p>
452
+ </div>
453
  </div>
454
  """
455
+
456
+
457
+ def build_outfit_component_cards_html(row):
458
+ """One card per garment piece of the TOP match (top/bottom/shoes/accessory) -
459
+ mirrors a 'your outfit, broken into shoppable pieces' layout."""
460
+ colors = [c.strip() for c in str(row["recommended_colors"]).split(",") if c.strip()] or ["neutral"]
461
+ components = [
462
+ ("TOP", row.get("outfit_top", "Top"), "zara", "search_query_zara"),
463
+ ("BOTTOM", row.get("outfit_bottom", "Bottom"), "hm", "search_query_hm"),
464
+ ("SHOES", row.get("outfit_shoes", "Shoes"), "asos", "search_query_asos"),
465
+ ("ACCESSORY", row.get("outfit_accessory", "Accessory"), "mango", "search_query_mango"),
466
+ ]
467
+ cards = []
468
+ for i, (label, item_name, retailer, col) in enumerate(components):
469
+ dot_color = _swatch_color(colors[i % len(colors)])
470
+ banner_color = _lighten_hex(dot_color)
471
+ link = to_shop_link(retailer, row[col], row["gender"])
472
+ cards.append(f"""
473
+ <div class="product-card">
474
+ <div class="card-color-header" style="background-color:{banner_color};">
475
+ <div class="prod-bubble" style="background-color:{dot_color};"></div>
476
+ </div>
477
+ <div class="prod-meta">
478
+ <span class="prod-cat">{label}</span>
479
+ <p class="prod-title">{str(item_name).title()}</p>
480
+ <span class="prod-brand">{retailer.upper()}</span>
481
+ <a href="{link}" target="_blank" class="shop-btn">Shop ↗</a>
482
+ </div>
483
+ </div>
484
+ """)
485
+ return f'<div class="outfit-grid">{"".join(cards)}</div>'
486
+
487
+
488
+ def build_more_matches_html(matched_indices, matched_rows, similarities, skip_first=True):
489
+ """Smaller secondary row: the other catalog matches, as full-look thumbnails
490
+ (keeps the '3 similar items' requirement visible alongside the per-garment cards above)."""
491
+ items = list(zip(matched_indices, similarities))[1:] if skip_first else list(zip(matched_indices, similarities))
492
+ if not items:
493
+ return ""
494
+ cards = []
495
+ for idx, sim in items:
496
+ row = df.iloc[idx]
497
+ img_b64 = pil_to_base64(images[idx])
498
+ link = to_shop_link("zara", row["search_query_zara"], row["gender"])
499
+ cards.append(f"""
500
+ <div class="product-card">
501
+ <img src="data:image/jpeg;base64,{img_b64}" style="width:100%;height:150px;object-fit:cover;display:block;"/>
502
+ <div class="prod-meta">
503
+ <span class="prod-brand">Match score: {sim}</span>
504
+ <a href="{link}" target="_blank" class="shop-btn">Shop ↗</a>
505
+ </div>
506
+ </div>
507
+ """)
508
  return (
509
+ '<div class="more-matches-label">MORE MATCHES LIKE THIS</div>'
510
+ f'<div class="outfit-grid">{"".join(cards)}</div>'
 
 
 
 
511
  )
512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
 
514
+ # ---------------------------------------------------------------------------
515
+ # MAIN PIPELINE — shared by both input paths, runs all 3 GenAI patterns
516
+ # ---------------------------------------------------------------------------
517
+ def run_pipeline(matched_indices, matched_rows, matched_scores, base_image=None, question=None,
518
+ expected_gender=None):
519
+ if len(matched_indices) == 0:
520
+ return "<i>No matches found — try different filters.</i>", None, "", "<div></div>"
521
+
522
+ similarity = [round(1.0 - (d / 2.0), 3) for d in matched_scores]
523
+
524
+ top_row = matched_rows.iloc[0]
525
+ # Pattern 3 needs a base photo: the user's own photo (Path A) or the top catalog match (Path B)
526
+ edit_base_image = base_image if base_image is not None else images[matched_indices[0]]
527
+ # If no explicit gender filter was given, fall back to the matched row's own gender, so
528
+ # the generated outfit's wording always matches the person actually shown in the photo.
529
+ gender_for_generation = expected_gender or top_row["gender"]
530
+
531
+ caption = generate_stylist_caption(top_row) # Pattern 1
532
+ new_image, _prompt = generate_new_outfit_image(
533
+ edit_base_image, top_row, target_gender=gender_for_generation
534
+ ) # Pattern 3
535
+
536
+ answer = ""
537
+ if question:
538
+ answer = answer_question_about_image(edit_base_image, question) # Pattern 2
539
+
540
+ style_card_html = build_style_card_html(top_row, caption)
541
+ outfit_cards_html = (
542
+ build_outfit_component_cards_html(top_row)
543
+ + build_more_matches_html(matched_indices, matched_rows, similarity)
544
  )
545
+ return style_card_html, new_image, answer, outfit_cards_html
546
 
547
+
548
+ def recommend_from_photo(photo, gender, age_group, question):
549
+ if photo is None:
550
+ return "<i>Please upload a photo or pick a Quick Starter.</i>", None, "", "<div></div>"
551
+ query_emb = embed_query_image(photo)
552
+ idx, rows, scores = faiss_filtered_search(query_emb, gender=gender or None, age_group=age_group or None)
553
+ return run_pipeline(idx, rows, scores, base_image=photo, question=question, expected_gender=gender)
554
+
555
+
556
+ def recommend_from_features(skin_tone, undertone, style, gender, age_group, question):
557
+ sentence = build_feature_sentence(skin_tone, undertone, style, gender, age_group)
558
+ query_emb = embed_query_text(sentence)
559
+ idx, rows, scores = faiss_filtered_search(query_emb, gender=gender or None, age_group=age_group or None)
560
+ return run_pipeline(idx, rows, scores, base_image=None, question=question, expected_gender=gender)
561
+
562
+
563
+ # ---------------------------------------------------------------------------
564
+ # GRADIO UI
565
+ # ---------------------------------------------------------------------------
566
+ CUSTOM_CSS = """
567
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
568
+ body, .gradio-container {background-color: #F8F5F5 !important;
569
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;}
570
+ .gradio-container {max-width: 850px !important; margin: 0 auto !important;}
571
+ footer {display: none !important;}
572
+
573
+ .tab-nav button {font-size: 15px !important; font-weight: 600 !important; padding: 12px 24px !important;}
574
+ .tab-nav button.selected {color: #D2527F !important; border-bottom: 2px solid #D2527F !important;}
575
+
576
+ #find-btn, .big-btn {background: #161617 !important; color: #fff !important; border: none !important;
577
+ border-radius: 8px !important; font-weight: 700 !important; font-size: 15px !important;
578
+ padding: 13px !important; text-transform: uppercase; transition: background .2s !important;}
579
+ #find-btn:hover, .big-btn:hover {background: #2D2D2F !important;}
580
+
581
+ .dark-panel {background: #161617 !important; border-radius: 16px !important; padding: 18px !important;}
582
+ .dark-panel label, .dark-panel span {color: #f0e6ea !important;}
583
+
584
+ /* Results layout */
585
+ .section-split {display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; margin-bottom: 14px;}
586
+ .results-box {background: #FFFFFF; border-radius: 16px; padding: 22px; border: 1px solid #EFECE8;}
587
+ .results-box h3 {font-size: 11px; font-weight: 700; color: #A4A1A1; letter-spacing: 1.2px;
588
+ text-transform: uppercase; margin: 0 0 14px;}
589
+ .swatch-grid {display: flex; gap: 18px; flex-wrap: wrap;}
590
+ .swatch-card {text-align: center; font-size: 11px; color: #666; width: 58px;}
591
+ .color-bubble {width: 44px; height: 44px; border-radius: 50%; margin: 0 auto 6px; border: 1px solid rgba(0,0,0,.06);}
592
+ .tip-text {font-size: 14px; color: #222; line-height: 1.55; margin: 0;}
593
+
594
+ /* Outfit / product cards */
595
+ .outfit-grid {display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px;}
596
+ @media (max-width: 700px) {.outfit-grid {grid-template-columns: repeat(2, 1fr);}}
597
+ .product-card {background: #fff; border: 1px solid #EFECE8; border-radius: 16px; overflow: hidden;}
598
+ .card-color-header {width: 100%; height: 80px; display: flex; align-items: center; justify-content: center;}
599
+ .prod-bubble {width: 40px; height: 40px; border-radius: 50%; box-shadow: 0 2px 8px rgba(0,0,0,.05);}
600
+ .prod-meta {padding: 16px;}
601
+ .prod-cat {font-size: 10px; font-weight: 700; color: #D2527F; letter-spacing: 1px; text-transform: uppercase;}
602
+ .prod-title {font-size: 14px; font-weight: 700; color: #111; margin: 4px 0 2px; line-height: 1.3;}
603
+ .prod-brand {font-size: 11px; color: #999; display: block; margin-bottom: 10px;}
604
+ .shop-btn {display: block; text-align: center; padding: 9px 0; background: #161617; color: #fff !important;
605
+ text-decoration: none !important; border-radius: 8px; font-size: 12px; font-weight: 700;}
606
+ .shop-btn:hover {background: #2D2D2F;}
607
+ .more-matches-label {font-size: 11px; font-weight: 700; color: #A4A1A1; letter-spacing: 1.2px;
608
+ text-transform: uppercase; margin: 18px 0 8px;}
609
+ """
610
+
611
+ with gr.Blocks(title="AI Fashion Stylist", css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="purple")) as demo:
612
+ gr.Markdown(
613
+ "# 👗 AI Fashion Stylist\n"
614
+ "Upload a photo **or** describe your style — get real catalog matches, shop links, "
615
+ "a brand-new AI-generated full-look photo, and a personal stylist note."
616
  )
617
 
618
+ with gr.Tab("📸 Upload a Photo"):
619
+ with gr.Row():
620
+ photo_in = gr.Image(type="pil", label="Your photo")
621
+ with gr.Column():
622
+ gender_a = gr.Dropdown(GENDERS, label="Gender (optional)")
623
+ age_a = gr.Dropdown(AGE_GROUPS, label="Age group (optional)")
624
+ question_a = gr.Textbox(label="Ask the stylist a question about your photo (optional)",
625
+ placeholder="e.g. What style would suit me best?")
626
+ btn_a = gr.Button("Get My Look ✨", elem_id="find-btn", variant="primary")
627
+ style_card_a = gr.HTML(label="Style Profile")
628
+ new_img_a = gr.Image(label="✨ Your New AI-Generated Look")
629
+ answer_a = gr.Textbox(label="Answer to your question")
630
+ outfit_cards_a = gr.HTML(label="Outfit Picks")
631
+ btn_a.click(
632
+ recommend_from_photo,
633
+ [photo_in, gender_a, age_a, question_a],
634
+ [style_card_a, new_img_a, answer_a, outfit_cards_a],
635
+ )
636
+
637
+ gr.Examples(
638
+ examples=[[p, None, None, "What style would suit me best?"] for p in SAMPLE_PHOTOS],
639
+ inputs=[photo_in, gender_a, age_a, question_a],
640
+ outputs=[style_card_a, new_img_a, answer_a, outfit_cards_a],
641
+ fn=recommend_from_photo,
642
+ cache_examples=True, # precomputed at Space startup -> truly "1-click and see a result"
643
+ label="Quick Starters",
644
+ )
645
+
646
+ with gr.Tab("🎨 Choose Manually"):
647
+ gr.Markdown("Select your skin tone, undertone and style below.")
648
+ with gr.Group(elem_classes="dark-panel"):
649
+ with gr.Row():
650
+ skin_b = gr.Dropdown(SKIN_TONES, label="Skin tone", value=SKIN_TONES[0])
651
+ undertone_b = gr.Dropdown(UNDERTONES, label="Undertone", value=UNDERTONES[0])
652
+ style_b = gr.Dropdown(STYLES, label="Style preference", value=STYLES[0])
653
+ with gr.Row():
654
+ gender_b = gr.Dropdown(GENDERS, label="Gender", value=GENDERS[0])
655
+ age_b = gr.Dropdown(AGE_GROUPS, label="Age group", value=AGE_GROUPS[0])
656
+ question_b = gr.Textbox(label="Ask the stylist a question about the top match (optional)",
657
+ placeholder="e.g. Is this outfit formal or casual?")
658
+ btn_b = gr.Button("Get My Look ✨", elem_id="find-btn", elem_classes="big-btn", variant="primary")
659
+ features_recap_b = gr.HTML(build_features_recap_html(SKIN_TONES[0], UNDERTONES[0], STYLES[0]))
660
+ for _dropdown in (skin_b, undertone_b, style_b):
661
+ _dropdown.change(
662
+ build_features_recap_html, [skin_b, undertone_b, style_b], features_recap_b
663
+ )
664
+ style_card_b = gr.HTML(label="Style Profile")
665
+ new_img_b = gr.Image(label="✨ Your New AI-Generated Look")
666
+ answer_b = gr.Textbox(label="Answer to your question")
667
+ outfit_cards_b = gr.HTML(label="Outfit Picks")
668
+ btn_b.click(
669
+ recommend_from_features,
670
+ [skin_b, undertone_b, style_b, gender_b, age_b, question_b],
671
+ [style_card_b, new_img_b, answer_b, outfit_cards_b],
672
+ )
673
+
674
+ gr.Examples(
675
+ examples=[
676
+ ["deep", "cool", "boho", "woman", "young adult", "Is this outfit formal or casual?"],
677
+ ["tan", "warm", "elegant", "man", "adult", "What occasion suits this outfit?"],
678
+ ["fair", "neutral", "minimalist", "woman", "teen", "What season is this outfit best for?"],
679
+ ],
680
+ inputs=[skin_b, undertone_b, style_b, gender_b, age_b, question_b],
681
+ outputs=[style_card_b, new_img_b, answer_b, outfit_cards_b],
682
+ fn=recommend_from_features,
683
+ cache_examples=True, # precomputed at Space startup -> truly "1-click and see a result"
684
+ label="Quick Starters",
685
+ )
686
+
687
  if __name__ == "__main__":
688
  demo.launch()