romi2001 commited on
Commit
99c91df
·
verified ·
1 Parent(s): b0d783f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +225 -2
app.py CHANGED
@@ -197,6 +197,7 @@ def faiss_filtered_search(query_emb, top_k=3, exclude_idx=None, gender=None, age
197
  if idx == -1 or (exclude_idx is not None and idx == exclude_idx):
198
  continue
199
  row = df.iloc[idx]
 
200
  if require_gender and gender and str(row["gender"]).lower() != str(gender).lower():
201
  continue
202
  if require_age and age_group and str(row["age_group"]).lower() != str(age_group).lower():
@@ -259,7 +260,7 @@ def generate_new_outfit_image(pil_image, row, target_gender=None):
259
  resized_face_crop = base.resize((head_w, head_h))
260
  resized_protect_img = Image.fromarray(protect.astype(np.uint8) * 255).resize((head_w, head_h), resample=Image.NEAREST)
261
 
262
- # תיקון הלוגיקה: הגדרת מיקומי ההדבקה מתרחשת עכשיו לפני השימוש בהם בקנבס
263
  paste_x = (canvas_w - head_w) // 2
264
  paste_y = int(canvas_h * 0.03)
265
 
@@ -308,4 +309,226 @@ def build_outfit_component_cards_html(row):
308
  {"category": "DRESS", "name": "Classic Slip Midi Dress", "retailer": "zara", "query": "terracotta slip midi dress"}
309
  ]
310
 
311
- cards = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  if idx == -1 or (exclude_idx is not None and idx == exclude_idx):
198
  continue
199
  row = df.iloc[idx]
200
+ # FIXED: Syntax error resolved from '&&' to python's standard 'and' keyword
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():
 
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
+ # FIXED: Layout initialization ordered cleanly to solve NameErrors
264
  paste_x = (canvas_w - head_w) // 2
265
  paste_y = int(canvas_h * 0.03)
266
 
 
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
+ # PREMIUM PASTEL LUXURY CSS 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"))