-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_app.py
More file actions
713 lines (588 loc) · 31.1 KB
/
chat_app.py
File metadata and controls
713 lines (588 loc) · 31.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
import streamlit as st
import os
import ollama
import json
import glob
import uuid
from datetime import datetime
from src.embedding import FashionEmbedder
from src.vector_db import FashionVectorDB
from src.llm_service import FashionLLM
# --- SAYFA AYARLARI ---
st.set_page_config(page_title="AI Stylist Pro (Final)", layout="wide")
st.title("👗 AI Stylist: Akıllı Asistan")
st.caption("Yukledigin parca icin hizli ve dengeli kombin onerileri.")
def apply_modern_ui():
st.markdown(
"""
<style>
/* Hide Streamlit chrome */
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
/* App background and typography */
.stApp {background: #0f1117; color: #e6e6e6;}
.stMarkdown, .stText, .stCaption {color: #d6d6d6;}
/* Sidebar */
section[data-testid="stSidebar"] {background: #11151c;}
section[data-testid="stSidebar"] .stMarkdown {color: #e0e0e0;}
/* Buttons */
.stButton > button {
background: linear-gradient(135deg, #5b6cff 0%, #7a5cff 100%);
color: #ffffff;
border: 0;
border-radius: 10px;
padding: 0.5rem 0.9rem;
box-shadow: 0 6px 18px rgba(91, 108, 255, 0.25);
}
.stButton > button:hover {filter: brightness(1.05);}
/* Chat bubbles */
div[data-testid="stChatMessage"] {
background: #151a23;
border: 1px solid #202635;
border-radius: 14px;
padding: 0.25rem 0.75rem;
}
/* Expanders */
details {background: #141a24; border-radius: 12px; border: 1px solid #202635;}
details > summary {padding: 0.4rem 0.6rem;}
/* Image captions */
.stImage figcaption {color: #c7c7c7;}
</style>
""",
unsafe_allow_html=True,
)
apply_modern_ui()
# --- YOL AYARLARI ---
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMAGES_DIR = os.path.join(BASE_DIR, "archive", "data")
HISTORY_DIR = os.path.join(BASE_DIR, "data", "history")
os.makedirs(HISTORY_DIR, exist_ok=True)
def build_chat_title(session_data):
"""Sohbet basligini kisa ve ayirt edici hale getirir."""
analysis = session_data.get("current_analysis") or {}
desc = (analysis.get("description") or "").strip()
if desc and desc.lower() != "unknown":
title = desc
else:
# Ilk kullanici mesajini baslik yap
first_user = next((m for m in session_data.get("messages", []) if m.get("role") == "user"), None)
title = (first_user or {}).get("content", "Yeni Sohbet")
title = " ".join(title.split())
return title[:60]
def is_dev_mode():
return st.session_state.get("dev_mode", False)
def notify_error(user_message, exc=None):
st.error(user_message)
if exc and is_dev_mode():
st.caption(f"Detay: {exc}")
# --- 1. SOHBET YÖNETİMİ (KAYDET / YÜKLE / SİL) ---
def save_chat_session():
"""Mevcut sohbeti kaydeder."""
if not st.session_state.messages: return
session_data = {
"id": st.session_state.session_id,
"timestamp": datetime.now().isoformat(),
"messages": st.session_state.messages,
"current_plan": st.session_state.current_plan,
"locked_gender": st.session_state.locked_gender,
"last_image": st.session_state.last_uploaded_filename,
"current_analysis": st.session_state.current_analysis
}
session_data["title"] = build_chat_title(session_data)
file_path = os.path.join(HISTORY_DIR, f"chat_{st.session_state.session_id}.json")
with open(file_path, "w", encoding="utf-8") as f:
json.dump(session_data, f, ensure_ascii=False, indent=2)
def load_chat_session(file_path):
"""Seçilen sohbeti yükler."""
try:
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
st.session_state.session_id = data["id"]
st.session_state.messages = data["messages"]
st.session_state.current_plan = data.get("current_plan", [])
st.session_state.locked_gender = data.get("locked_gender")
st.session_state.last_uploaded_filename = data.get("last_image")
st.session_state.current_analysis = data.get("current_analysis")
if not st.session_state.current_analysis:
st.session_state.current_analysis = None
except Exception as e:
notify_error("Sohbet yuklenemedi. Lutfen tekrar deneyin.", e)
def delete_chat_session(file_path):
"""Sohbet dosyasını siler."""
try:
os.remove(file_path)
# Eğer silinen sohbet şu an açık olan sohbetse, ekranı sıfırla
current_file = f"chat_{st.session_state.session_id}.json"
if os.path.basename(file_path) == current_file:
create_new_chat()
return True
except Exception as e:
notify_error("Sohbet silinemedi. Lutfen tekrar deneyin.", e)
return False
def create_new_chat():
"""Yeni sohbet başlatır."""
st.session_state.session_id = str(uuid.uuid4())
st.session_state.messages = [
{"role": "assistant", "content": "Yeni sohbet başladı! Bir parça yükle, stil danışmanlığı yapayım."}]
st.session_state.current_plan = []
st.session_state.locked_gender = None
st.session_state.current_analysis = None
st.session_state.last_uploaded_filename = None
# --- 2. GÖRME AJANI ---
# --- 2. GÖRME AJANI (DEBUG MODU) ---
# --- 1. GÖRME AJANI (KESİN KATEGORİ) ---
def analyze_image_category(image_path):
try:
# Prompt'u çok netleştiriyoruz
response = ollama.chat(model='llava', messages=[{
'role': 'user',
'content': 'Analyze the MAIN clothing item. You MUST return a JSON. \
Categories allowed: ["Topwear", "Bottomwear", "Footwear", "Outerwear", "Accessories"]. \
Examples: \
- Jeans/Pants/Shorts -> "Bottomwear" \
- Shirt/T-shirt/Hoodie -> "Topwear" \
- Jacket/Coat/Blazer -> "Outerwear" \
- Shoes/Sneakers -> "Footwear" \
\
Return format: {"description": "Beige Chinos", "category": "Bottomwear"}',
'images': [image_path]
}])
content = response['message']['content'].strip()
start = content.find('{')
end = content.rfind('}') + 1
data = json.loads(content[start:end])
# Ekstra Güvenlik: Eğer açıklama 'pant' içeriyorsa kategoriyi zorla
desc = data.get("description", "").lower()
if "pant" in desc or "trouser" in desc or "jean" in desc:
data["category"] = "Bottomwear"
elif "shirt" in desc or "top" in desc or "sweater" in desc:
data["category"] = "Topwear"
return data
except:
return {"description": "Unknown", "category": "General"}
def create_default_plan(input_category, gender_prefix=""):
"""Yüklenen parçaya göre varsayılan kombin planı oluşturur."""
plan = []
if input_category == "Topwear":
plan = [
{"role": "Alt Giyim", "search_query": f"{gender_prefix}Casual Pants", "target_category": "Bottomwear"},
{"role": "Ayakkabı", "search_query": f"{gender_prefix}Casual Shoes", "target_category": "Footwear"}
]
elif input_category == "Bottomwear":
plan = [
{"role": "Üst Giyim", "search_query": f"{gender_prefix}Casual Shirt", "target_category": "Topwear"},
{"role": "Ayakkabı", "search_query": f"{gender_prefix}Casual Shoes", "target_category": "Footwear"}
]
elif input_category == "Footwear":
plan = [
{"role": "Üst Giyim", "search_query": f"{gender_prefix}Casual Top", "target_category": "Topwear"},
{"role": "Alt Giyim", "search_query": f"{gender_prefix}Casual Pants", "target_category": "Bottomwear"}
]
elif input_category == "Outerwear":
plan = [
{"role": "Alt Giyim", "search_query": f"{gender_prefix}Casual Jeans", "target_category": "Bottomwear"},
{"role": "Ayakkabı", "search_query": f"{gender_prefix}Boots", "target_category": "Footwear"}
]
else:
# Genel durum - tüm kategorilerden öner
plan = [
{"role": "Üst Giyim", "search_query": f"{gender_prefix}Stylish Top", "target_category": "Topwear"},
{"role": "Alt Giyim", "search_query": f"{gender_prefix}Casual Pants", "target_category": "Bottomwear"},
{"role": "Ayakkabı", "search_query": f"{gender_prefix}Casual Shoes", "target_category": "Footwear"}
]
return {"thought": "Varsayılan kombin planı oluşturuldu.", "plan": plan}
# --- 3. AKILLI PLANLAYICI (ANTI-ECHO MODU) ---
def stylist_planner(user_prompt, input_category, input_desc, locked_gender, previous_plan):
prev_plan_str = json.dumps(previous_plan, ensure_ascii=False) if previous_plan else "YOK"
gender_txt = f"CİNSİYET: {locked_gender}" if locked_gender else "CİNSİYET: Unisex"
gender_prefix = f"{locked_gender} " if locked_gender else ""
system_prompt = f"""
GÖREV: Moda Stilisti. Kullanıcının yüklediği parçaya uygun kombin öner.
GİRDİLER:
- Yüklenen Parça: {input_desc} ({input_category})
- {gender_txt}
- AKTİF PLAN: {prev_plan_str}
KURALLAR:
1. MUTLAKA "plan" anahtarı içeren bir JSON döndür.
2. Yüklenen parçanın kategorisini (örn: {input_category}) ÖNERİLERE EKLEME.
3. Kombin için 2-3 tamamlayıcı parça öner.
4. Her parçanın: "role" (rol adı), "search_query" (arama sorgusu), "target_category" (Topwear/Bottomwear/Footwear/Outerwear/Accessories) alanları olmalı.
ÖRNEK ÇIKTI:
{{"thought": "Beyaz t-shirt için mavi jean ve spor ayakkabı uygun olur", "plan": [{{"role": "Üst Giyim", "search_query": "White T-shirt", "target_category": "Topwear"}}, {{"role": "Ayakkabı", "search_query": "White Sneakers", "target_category": "Footwear"}}]}}
"""
full_prompt = f"KULLANICI: '{user_prompt}'\n\nJSON:"
try:
response = ollama.chat(model="llama3", messages=[
{'role': 'system', 'content': system_prompt},
{'role': 'user', 'content': full_prompt}
])
content = response['message']['content']
if is_dev_mode():
print(f"[DEBUG] LLM Yaniti: {content[:500]}")
start = content.find('{')
end = content.rfind('}') + 1
if start == -1 or end == 0:
raise ValueError("JSON bulunamadı")
data = json.loads(content[start:end])
# Plan anahtarı yoksa veya boşsa varsayılan plan oluştur
if "plan" not in data or not data["plan"]:
if is_dev_mode():
print("[DEBUG] Plan anahtari bulunamadi, varsayilan plan olusturuluyor...")
data = create_default_plan(input_category, gender_prefix)
# --- 2. PYTHON TARAFLI SERT BLOKAJ (ANTI-ECHO) ---
# LLM bazen laftan anlamaz, o yüzden Python ile sopayı gösteriyoruz.
# Kullanıcı "değiştir", "change", "yerine" DEMEDİYSE, eldeki kategoriyi yasakla.
user_wants_change = any(x in user_prompt.lower() for x in ["değiştir", "change", "yerine", "farklı"])
if not user_wants_change and "plan" in data:
cleaned_plan = []
for item in data["plan"]:
# Veri formatını düzelt (Bazen string gelir)
if isinstance(item, str): continue
target_cat = item.get("target_category", "General")
query = item.get("search_query", "").lower()
# BLOKAJ MANTIĞI:
# 1. Kategori Eşleşmesi: Input=Bottomwear ve Target=Bottomwear -> SİL
if input_category != "General" and target_cat == input_category:
if is_dev_mode():
print(f"Bloklandi (Ayni Kategori): {query}")
continue
# 2. Kelime Eşleşmesi: Input=Bottomwear ama Target=General, fakat query'de "Trouser" var -> SİL
if input_category == "Bottomwear":
forbidden_words = ["pant", "trouser", "jean", "short", "chinos", "khaki"]
if any(w in query for w in forbidden_words):
if is_dev_mode():
print(f"Bloklandi (Yasakli Kelime): {query}")
continue
elif input_category == "Topwear":
forbidden_words = ["shirt", "top", "tee", "polo", "hoodie", "sweater"]
if any(w in query for w in forbidden_words) and "shoe" not in query: # Ayakkabı karışmasın
continue
elif input_category == "Footwear":
forbidden_words = [
"shoe", "shoes", "sneaker", "boot", "sandal", "footwear", "heel",
"loafer", "trainer", "flip", "slide"
]
if any(w in query for w in forbidden_words):
if is_dev_mode():
print(f"Bloklandi (Ayakkabi Terimi): {query}")
continue
cleaned_plan.append(item)
data["plan"] = cleaned_plan
return data
except Exception as e:
if is_dev_mode():
print(f"Plan Hatasi: {e}")
gender_prefix = f"{locked_gender} " if locked_gender else ""
return create_default_plan(input_category, gender_prefix)
# --- SİSTEM YÜKLEME ---
@st.cache_resource
def load_systems():
embedder = FashionEmbedder()
vector_db = FashionVectorDB(collection_name="fashion_multimodal")
llm = FashionLLM(model_name="llama3")
return embedder, vector_db, llm
try:
embedder, vector_db, llm = load_systems()
except Exception as e:
notify_error("Sistem baslatilamadi. Lutfen sonra tekrar deneyin.", e)
st.stop()
# --- STATE BAŞLATMA ---
if "session_id" not in st.session_state: create_new_chat()
# --- SIDEBAR (SİLME ÖZELLİĞİ EKLENDİ) ---
with st.sidebar:
st.title("🗂️ Sohbetler")
if st.button("➕ Yeni Sohbet Baslat", use_container_width=True):
save_chat_session()
create_new_chat()
st.rerun()
with st.expander("Ayarlar", expanded=False):
st.toggle("Gelistirici modu", key="dev_mode")
if is_dev_mode():
st.caption("Teknik ayrintilar gorunur.")
st.divider()
st.caption("Gecmis Sohbetler")
# Dosyaları listele
files = sorted(glob.glob(os.path.join(HISTORY_DIR, "chat_*.json")), key=os.path.getmtime, reverse=True)
if not files:
st.info("Henuz kayitli sohbet yok.")
for f in files:
filename = os.path.basename(f)
# İsmi güzelleştir (Tarih/Saat)
try:
with open(f, 'r') as read_file:
meta = json.load(read_file)
# İlk mesajı başlık yap veya tarih kullan
timestamp = meta.get("timestamp", "")[:16].replace("T", " ")
title = meta.get("title") or build_chat_title(meta)
display_name = f"{title} • {timestamp}" if timestamp else title
except:
display_name = "Bilinmeyen Sohbet"
meta = {}
# --- YAN YANA BUTONLAR (THUMBNAIL + YÜKLE + SİL) ---
col_img, col1, col2 = st.columns([0.2, 0.6, 0.2])
with col_img:
thumb_path = meta.get("last_image")
if thumb_path and os.path.exists(thumb_path):
st.image(thumb_path, width=64)
else:
st.caption("🖼️")
with col1:
if st.button(f"📄 {display_name}", key=f"load_{filename}", help="Bu sohbeti yükle"):
save_chat_session() # Mevcutu kaydet
load_chat_session(f)
st.rerun()
with col2:
if st.button("🗑️", key=f"del_{filename}", help="Sohbeti sil"):
if delete_chat_session(f):
st.success("Silindi!")
st.rerun()
st.divider()
with st.expander("Urun Yukleme", expanded=True):
uploaded_file = st.file_uploader("Urun yukle", type=["jpg", "png"], key="uploader")
if uploaded_file:
# Dosya değişti mi kontrolü
if "last_uploaded_filename" not in st.session_state: st.session_state.last_uploaded_filename = None
if uploaded_file.name != st.session_state.last_uploaded_filename:
# Yeni dosya geldiyse eskileri temizle
st.session_state.current_analysis = None
st.session_state.locked_gender = None
st.session_state.last_uploaded_filename = uploaded_file.name
# Sayfayı yenilemeden önce değişkenleri sıfırla
# st.rerun() yapmıyoruz, aşağıda akış devam etsin
# --- KRİTİK DÜZELTME: BENZERSİZ DOSYA İSMİ ---
# temp.jpg yerine rastgele sayı üret: upload_12345.jpg
file_ext = uploaded_file.name.split('.')[-1]
unique_filename = f"upload_{st.session_state.session_id}_{uuid.uuid4()}.{file_ext}"
saved_path = os.path.join(HISTORY_DIR, unique_filename)
# Eski görseli temizle (bu sohbet için)
old_path = st.session_state.last_uploaded_filename
if old_path and os.path.exists(old_path) and old_path != saved_path:
try:
os.remove(old_path)
except:
pass
with open(saved_path, "wb") as f:
f.write(uploaded_file.getbuffer())
st.session_state.last_uploaded_filename = saved_path
st.image(saved_path, use_container_width=True)
# Analiz
if st.session_state.current_analysis is None:
with st.spinner("Gorsel analiz ediliyor..."):
analysis = analyze_image_category(saved_path)
st.session_state.current_analysis = analysis
desc = analysis.get("description", "")
cat = analysis.get("category", "")
if "men" in desc.lower():
st.session_state.locked_gender = "Men"
elif "women" in desc.lower():
st.session_state.locked_gender = "Women"
st.success(f"Algilanan urun: {desc}")
st.info(f"Kategori: {cat}")
save_chat_session()
else:
desc = st.session_state.current_analysis.get("description", "")
cat = st.session_state.current_analysis.get("category", "")
if not desc or desc.strip().lower() == "unknown":
st.info("Analiz sonucu bulunamadi. Lutfen resmi yeniden yukleyin.")
else:
st.success(f"Son analiz: {desc}")
if cat:
st.caption(f"Kategori: {cat}")
# --- ANA SOHBET ---
for msg in st.session_state.messages:
with st.chat_message(msg["role"]):
st.write(msg["content"])
if "outfit" in msg:
for item in msg["outfit"]:
st.markdown(f"**{item['role']}**")
cols = st.columns(len(item['products']))
for i, prod in enumerate(item['products']):
with cols[i]: st.image(prod["path"], caption=prod["name"], use_container_width=True)
st.divider()
if prompt := st.chat_input("Bir sey yaz..."):
# Kullanıcı mesajını ekle
st.session_state.messages.append({"role": "user", "content": prompt})
save_chat_session()
with st.chat_message("user"):
st.write(prompt)
with st.chat_message("assistant"):
with st.spinner("Kombin olusturuluyor..."):
# --- 1. ÖN İŞLEME: CİNSİYET DEĞİŞİMİ TESPİTİ ---
# Kullanıcı komutunda cinsiyet değişikliği var mı?
p_lower = prompt.lower()
if "erkek" in p_lower or "men" in p_lower or "man" in p_lower:
st.session_state.locked_gender = "Men"
st.toast("Mod degistirildi: ERKEK", icon="♂️")
elif "kadın" in p_lower or "bayan" in p_lower or "women" in p_lower or "woman" in p_lower:
st.session_state.locked_gender = "Women"
st.toast("Mod degistirildi: KADIN", icon="♀️")
# --- 2. BAĞLAM HAZIRLIĞI ---
input_cat = "General"
input_desc = ""
if st.session_state.current_analysis:
input_cat = st.session_state.current_analysis.get("category", "General")
input_desc = st.session_state.current_analysis.get("description", "")
# --- 3. GÜÇLENDİRİLMİŞ PLANLAYICI (MODİFİKASYON USTASI) ---
# Renk değişimlerinde eski planı koru ama güncellemeyi zorla
plan_data = stylist_planner(
prompt,
input_cat,
input_desc,
st.session_state.locked_gender,
st.session_state.current_plan
)
# Yeni planı kaydet
st.session_state.current_plan = plan_data.get("plan", [])
save_chat_session()
if is_dev_mode():
st.caption(f"Guncel plan: {[p.get('search_query') for p in st.session_state.current_plan]}")
# --- 4. İCRA (ARAMA MOTORU) ---
outfit_results = []
for item in st.session_state.current_plan:
# Tip Kontrolü
if not isinstance(item, dict): continue
target_cat = item.get("target_category", "General")
base_query = item.get("search_query", "")
role_title = item.get("role", "Öneri")
current_gender = st.session_state.locked_gender
gender_prefix = f"{current_gender} " if current_gender else ""
if input_cat == "Footwear":
footwear_terms = [
"shoe", "shoes", "sneaker", "boot", "sandal", "footwear", "heel",
"loafer", "trainer", "flip", "slide"
]
if target_cat == "Footwear" or any(t in base_query.lower() for t in footwear_terms):
continue
# --- STRATEJİ: 4 SEVİYELİ ARAMA ---
search_levels = [
# 1. SERT MOD: Tam eşleşme (Renk + Model + Cinsiyet)
{"query": f"{gender_prefix}{base_query}", "strict_color": True, "strict_cat": True},
# 2. ESNEK MOD: Sadece Model (Rengi boşver)
{"query": base_query.split()[-1] if base_query else target_cat, "strict_color": False,
"strict_cat": True},
# 3. GENİŞ MOD (GÜVENLİK AĞI): Sadece Kategori + Dışlayıcı Filtre
{"query": f"{gender_prefix}{target_cat}", "strict_color": False, "strict_cat": False},
# 4. ULTRA GENİŞ MOD: Sadece kategori, filtre yok
{"query": target_cat, "strict_color": False, "strict_cat": False, "no_filter": True}
]
found_products = []
for level in search_levels:
if len(found_products) >= 2: break
q = level["query"]
strict_color = level["strict_color"]
strict_cat = level["strict_cat"]
no_filter = level.get("no_filter", False)
print(f"\nArama basliyor ({'Sert' if strict_cat else 'Genis'}): '{q}'")
try:
text_vec = embedder.generate_text_embedding([q])[0]
# Geniş modda daha çok aday getir ki şansımız artsın
if no_filter:
k_val = 200
else:
k_val = 20 if strict_cat else 100
results = vector_db.search_similar(text_vec, k=k_val)
except Exception as e:
if is_dev_mode():
print(f"Vektor Hatasi: {e}")
continue
if results['metadatas']:
for meta in results['metadatas'][0]:
if len(found_products) >= 2: break
meta_cat = meta.get('category', '').lower()
meta_name = meta.get('name', '').lower()
# --- 1. CİNSİYET (KIRMIZI ÇİZGİ) ---
# Buradan asla taviz veremeyiz
if current_gender == "Men" and (
"women" in meta_name or "girl" in meta_name or "dress" in meta_name or "skirt" in meta_name):
continue
elif current_gender == "Women" and ("men " in meta_name or "boy" in meta_name):
continue
# --- 2. KATEGORİ DOĞRULAMA (AKILLI FİLTRE) ---
if no_filter:
is_valid = True
else:
is_valid = False
if strict_cat:
# SERT MOD: İçinde mutlaka kelime geçmeli
if target_cat == "Footwear":
valid_terms = ["shoe", "boot", "sneaker", "sandal", "footwear", "heel", "loafer",
"trainer", "flip", "slide"]
if any(t in meta_name for t in valid_terms) or any(
t in meta_cat for t in valid_terms): is_valid = True
elif target_cat == "Outerwear":
valid_terms = ["jacket", "coat", "blazer", "cardigan", "hoodie", "vest",
"sweatshirt", "overcoat", "parka"]
if any(t in meta_name for t in valid_terms) or any(
t in meta_cat for t in valid_terms): is_valid = True
elif target_cat == "Topwear":
valid_terms = ["shirt", "top", "tee", "polo", "sweater", "t-shirt", "tunic",
"blouse"]
if "shoe" not in meta_name and "pant" not in meta_name:
if any(t in meta_name for t in valid_terms) or any(
t in meta_cat for t in valid_terms): is_valid = True
elif target_cat == "Bottomwear":
valid_terms = ["pant", "trouser", "jean", "short", "jogger", "chinos", "legging",
"skirt"]
if any(t in meta_name for t in valid_terms) or any(
t in meta_cat for t in valid_terms): is_valid = True
else:
# GENİŞ MOD (DIŞLAYICI FİLTRE):
# Aradığımız kelimeyi bulamazsan, en azından YANLIŞ OLANI ele.
# Örn: Ceket ararken ayakkabı gelmesin yeter.
is_valid = True # Varsayılan olarak kabul et
if target_cat == "Footwear":
# Üst veya Alt giyim kelimeleri varsa reddet
if any(x in meta_name for x in
["shirt", "jacket", "pant", "jean", "hat", "cap"]): is_valid = False
# Ama içinde hiç ayakkabı terimi yoksa da şüpheli, yine de vektör benzerliğine güveniyoruz.
elif target_cat in ["Topwear", "Outerwear"]:
# Ayakkabı veya pantolon varsa reddet
if any(x in meta_name for x in
["shoe", "sneaker", "boot", "pant", "jean", "trouser",
"skirt"]): is_valid = False
elif target_cat == "Bottomwear":
# Ayakkabı veya üst giyim varsa reddet
if any(x in meta_name for x in
["shoe", "sneaker", "shirt", "jacket", "top", "cap"]): is_valid = False
# Kategori uymadıysa atla ve sebebini yaz (Debug)
if not is_valid:
# print(f"❌ Kategori Uyumsuz ({target_cat}): {meta_name}")
continue
# --- 3. RENK KONTROLÜ (SADECE SERT MODDA) ---
if strict_color and not no_filter:
colors = ["red", "blue", "black", "white", "green", "yellow", "beige", "brown", "navy",
"grey", "purple", "pink"]
wanted_colors = [c for c in colors if c in q.lower()]
if wanted_colors:
# Eğer isimde renk geçmiyorsa ele
if not any(c in meta_name for c in wanted_colors):
continue
# --- KAYIT ---
img_id = str(meta['image_id']).replace(".jpg", "") + ".jpg"
full_path = os.path.join(IMAGES_DIR, img_id)
if os.path.exists(full_path) and not any(p['path'] == full_path for p in found_products):
found_products.append({"name": meta['name'], "path": full_path})
if is_dev_mode():
print(f"Eklendi: {meta_name}")
if found_products:
outfit_results.append({"role": role_title, "products": found_products})
else:
# HALA BULAMADIYSA: Veritabanında gerçekten yok demektir.
pass
# 4. SUNUM
if not outfit_results:
st.warning("Uygun urun bulunamadi. Farkli bir istek deneyin.")
if is_dev_mode():
st.caption("Not: Veri setinde kriterlere uyan urun kalmamis olabilir.")
else:
st.success("Kombin onerileri hazir.")
for item in outfit_results:
st.markdown(f"### {item['role']}")
cols = st.columns(len(item['products']))
for i, prod in enumerate(item['products']):
# Streamlit yeni versiyon uyumu
with cols[i]: st.image(prod["path"], caption=prod["name"], width="content")
st.session_state.messages.append(
{"role": "assistant", "content": "Oneriler sunuldu.", "outfit": outfit_results})
save_chat_session()