TrendSurfer / app.py
drvsbrkcn's picture
Upload 3 files
ec6ad32 verified
import gradio as gr
from transformers import BlipProcessor, BlipForConditionalGeneration
from PIL import Image
import torch
import re
from urllib.parse import quote
# Model yükleme (BLIP-2 detaylı görsel açıklama için)
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large")
# Desteklenen markalar ve arama URL'leri
BRANDS = {
"Zara": "https://www.zara.com/tr/en/search?searchTerm=",
"Mango": "https://shop.mango.com/tr/kadin/arama?q=",
"H&M": "https://www2.hm.com/tr_tr/search-results.html?q=",
"Bershka": "https://www.bershka.com/tr/search?searchTerm=",
"Pull&Bear": "https://www.pullandbear.com/tr/search?searchTerm="
}
# Kıyafet kategorileri ve anahtar kelimeler
CLOTHING_KEYWORDS = {
'jacket': ['jacket', 'blazer', 'coat', 'cardigan', 'bomber'],
'top': ['shirt', 'blouse', 't-shirt', 'top', 'sweater', 'hoodie'],
'pants': ['pants', 'trousers', 'jeans', 'shorts'],
'skirt': ['skirt', 'mini skirt', 'maxi skirt'],
'dress': ['dress', 'gown'],
'shoes': ['shoes', 'boots', 'sneakers', 'heels', 'sandals'],
'accessories': ['bag', 'purse', 'hat', 'scarf', 'belt', 'sunglasses']
}
def analyze_fashion_image(image):
"""Görseli analiz edip detaylı kıyafet açıklaması çıkarır"""
if image is None:
return "❌ Lütfen bir görsel yükleyin", ""
# Görseli işle
inputs = processor(image, return_tensors="pt")
# Detaylı açıklama üret
with torch.no_grad():
out = model.generate(**inputs, max_length=100, num_beams=5)
description = processor.decode(out[0], skip_special_tokens=True)
# Kıyafet parçalarını tespit et
detected_items = extract_clothing_items(description)
if not detected_items:
detected_items = [description] # Eğer spesifik parça bulunamazsa genel açıklamayı kullan
# Sonuçları formatla
result_html = create_fashion_cards(detected_items)
return f"🔍 **Analiz Sonucu:** {description}", result_html
def extract_clothing_items(description):
"""Açıklamadan kıyafet parçalarını çıkarır"""
items = []
description_lower = description.lower()
# Her kategori için kontrol et
for category, keywords in CLOTHING_KEYWORDS.items():
for keyword in keywords:
if keyword in description_lower:
# Kelime çevresindeki bağlamı al
start_idx = max(0, description_lower.index(keyword) - 20)
end_idx = min(len(description), description_lower.index(keyword) + len(keyword) + 30)
context = description[start_idx:end_idx].strip()
# Renkler ve stili bul
colors = extract_colors(context)
item_desc = f"{colors} {keyword}".strip() if colors else keyword
if item_desc not in items:
items.append(item_desc)
break
return items if items else [description]
def extract_colors(text):
"""Metinden renk bilgilerini çıkarır"""
colors = ['black', 'white', 'blue', 'red', 'green', 'yellow', 'pink', 'purple',
'brown', 'gray', 'grey', 'beige', 'navy', 'cream', 'olive', 'burgundy',
'siyah', 'beyaz', 'mavi', 'kırmızı', 'yeşil', 'sarı', 'pembe', 'mor',
'kahverengi', 'gri', 'bej', 'lacivert', 'krem']
text_lower = text.lower()
found_colors = [color for color in colors if color in text_lower]
return ' '.join(found_colors) if found_colors else ''
def create_fashion_cards(items):
"""Instagram-style kıyafet kartları oluşturur"""
cards_html = '<div style="display: flex; flex-direction: column; gap: 20px; margin-top: 20px;">'
for idx, item in enumerate(items, 1):
search_query = quote(item)
# Her kıyafet parçası için kart
card_html = f'''
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 15px; padding: 20px; color: white;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);">
<h3 style="margin: 0 0 15px 0; font-size: 18px; text-transform: uppercase;
letter-spacing: 1px;">
👔 {item}
</h3>
<div style="display: flex; flex-wrap: wrap; gap: 10px;">
'''
# Her marka için buton
for brand, base_url in BRANDS.items():
brand_url = f"{base_url}{search_query}"
card_html += f'''
<a href="{brand_url}" target="_blank"
style="background: rgba(255,255,255,0.2); border: 2px solid white;
color: white; padding: 10px 20px; border-radius: 25px;
text-decoration: none; font-weight: bold;
transition: all 0.3s; display: inline-block;
backdrop-filter: blur(10px);">
{brand} 🔗
</a>
'''
card_html += '''
</div>
</div>
'''
cards_html += card_html
cards_html += '</div>'
return cards_html
# Gradio Arayüzü
with gr.Blocks(css="""
.gradio-container {
font-family: 'Arial', sans-serif;
max-width: 1200px;
margin: auto;
}
.title {
text-align: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 48px;
font-weight: bold;
margin-bottom: 10px;
}
.subtitle {
text-align: center;
color: #666;
font-size: 18px;
margin-bottom: 30px;
}
""") as demo:
gr.HTML("""
<div class="title">✨ TrendSurfer AI</div>
<div class="subtitle">
Zaratrendsetter tarzında kıyafet analizi 🎯<br>
Fotoğraf yükleyin, trendleri keşfedin!
</div>
""")
with gr.Row():
with gr.Column(scale=1):
image_input = gr.Image(type="pil", label="📸 Kombin Fotoğrafı Yükleyin")
analyze_btn = gr.Button("🔍 Analiz Et", variant="primary", size="lg")
with gr.Column(scale=1):
result_text = gr.Markdown(label="Analiz Sonucu")
result_html = gr.HTML(label="Ürün Linkleri")
analyze_btn.click(
fn=analyze_fashion_image,
inputs=image_input,
outputs=[result_text, result_html]
)
# Örnek görseller
gr.Examples(
examples=[
["https://images.unsplash.com/photo-1490481651871-ab68de25d43d?w=400"],
["https://images.unsplash.com/photo-1487222477894-8943e31ef7b2?w=400"],
],
inputs=image_input,
label="Örnek Görseller"
)
# Uygulamayı başlat
if __name__ == "__main__":
demo.launch()