homework3 / app.py
Nofarsagi123's picture
Update app.py
00cd99d verified
import gradio as gr
import pandas as pd
from PIL import Image
from io import BytesIO
import requests
from sentence_transformers import SentenceTransformer, util
import torch
# Load the dataset (מכיל מוצרים עם שם ותיאור)
df = pd.read_parquet("train-00000-of-00002-6cff4c59f91661c3.parquet")
# נניח שהעמודות החשובות הן אלה — אם צריך עדכון, שימי לב לשמות העמודות
df = df[["productDisplayName", "gender", "usage", "masterCategory", "subCategory"]].dropna()
# Create a full-text field to encode
df["full_text"] = df["productDisplayName"] + " | " + df["gender"] + " | " + df["usage"] + " | " + df["masterCategory"] + " > " + df["subCategory"]
# Load model
model = SentenceTransformer("all-MiniLM-L6-v2")
embeddings = model.encode(df["full_text"].tolist(), convert_to_tensor=True, show_progress_bar=True)
# Recommendation logic
def recommend_products(user_input, top_k=5):
if not user_input.strip():
return "⚠️ Please enter a product description.", []
user_vector = model.encode(user_input, convert_to_tensor=True)
similarities = util.cos_sim(user_vector, embeddings)[0]
top_indices = similarities.argsort(descending=True)[:top_k]
results = []
for idx in top_indices:
row = df.iloc[idx]
title = row["productDisplayName"]
description = f"{row['gender']} - {row['usage']} - {row['masterCategory']} > {row['subCategory']}"
# Placeholder image – אין תמונות מקוריות בדאטה
image_url = "https://via.placeholder.com/300x400.png?text=No+Image"
try:
response = requests.get(image_url)
img = Image.open(BytesIO(response.content)).convert("RGB")
except:
img = Image.new("RGB", (300, 400), color=(200, 200, 200))
results.append((img, f"**{title}**\n{description}"))
return "", results
# Custom CSS
custom_css = """
<style>
.gradio-container {font-family: 'Segoe UI', sans-serif;}
.gr-button {background-color: #4CAF50 !important; color: white !important; font-weight: bold;}
.gr-button:hover {background-color: #388e3c !important;}
img {border-radius: 8px;}
</style>
"""
# Example inputs
examples = [
"red summer dress",
"black leather boots",
"formal white shirt",
"cotton trousers for men",
"sports t-shirt"
]
# Build the interface
with gr.Blocks(title="Fashion Product Recommender") as demo:
gr.HTML(custom_css)
gr.Markdown("""
## 🛍️ Fashion Product Recommender
Type in a product you're looking for, and get AI-based recommendations from our fashion dataset.
Use keywords like *'summer dress'* or *'men sports shoes'* to begin.
""")
with gr.Row():
with gr.Column(scale=1):
user_input = gr.Textbox(
label="🔎 What are you looking for?",
placeholder="e.g. red formal shirt, denim jacket, kids shoes...",
lines=2
)
submit_btn = gr.Button("✨ Recommend Products")
quick_ex = gr.Examples(examples=examples, inputs=user_input, label="💡 Try these examples")
error_box = gr.Textbox(visible=False, interactive=False, show_label=False)
with gr.Column(scale=2):
output_gallery = gr.Gallery(
label="🎯 Top Matching Products",
show_label=True,
columns=2,
rows=4,
height=600,
object_fit="cover"
)
submit_btn.click(fn=recommend_products, inputs=user_input, outputs=[error_box, output_gallery])
demo.launch()