RetailGenie / app.py
Parishri07's picture
Update app.py
d1068de verified
raw
history blame
6.02 kB
import gradio as gr
import os
import pandas as pd
from PIL import Image
# ----- Config -----
BASE_DIR = "data"
ASSETS_DIR = "assets"
DEFAULT_MAP = os.path.join(ASSETS_DIR, "default_map.jpg")
PRODUCT_IMAGE_MAP = {
"shampoo": os.path.join(ASSETS_DIR, "shampoo_map.jpg"),
"curd": os.path.join(ASSETS_DIR, "curd_map.jpg"),
"ghee": os.path.join(ASSETS_DIR, "ghee_map.jpg")
}
# ----- Utilities -----
def get_subfolders(path):
try:
return sorted([f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))])
except Exception as e:
print(f"❌ Error reading subfolders from {path}: {e}")
return []
def get_csv_files(path):
try:
return sorted([f[:-4] for f in os.listdir(path) if f.endswith(".csv")])
except Exception as e:
print(f"❌ Error reading CSVs from {path}: {e}")
return []
def get_quantities_from_csv(path):
try:
df = pd.read_csv(path)
if df.empty or "Quantity" not in df.columns:
return gr.update(choices=[], visible=False), {}
return gr.update(choices=df["Quantity"].dropna().tolist(), visible=True), df.to_dict()
except Exception as e:
print(f"❌ Error loading CSV: {e}")
return gr.update(choices=[], visible=False), {}
def display_quantity_info(quantity, data_dict):
try:
df = pd.DataFrame(data_dict)
row = df[df["Quantity"] == quantity].iloc[0]
if str(row["In Stock"]).strip().lower() == "yes":
msg = (
f"βœ… {quantity} is available!\n"
f"β€’ Floor: {row['Floor']}\n"
f"β€’ Aisle: {row['Aisle']}\n"
f"β€’ Price: β‚Ή{row['Price']}"
)
if "Offer" in row and pd.notna(row["Offer"]) and row["Offer"].strip():
msg += f"\nβ€’ πŸŽ‰ Offer: {row['Offer']}"
return msg
else:
return f"❌ Sorry, {quantity} is currently not in stock."
except Exception as e:
return f"⚠️ Error: {e}"
def get_product_image(product_name):
lower_name = product_name.strip().lower()
return Image.open(PRODUCT_IMAGE_MAP.get(lower_name, DEFAULT_MAP))
def reset_all():
return (
None, None, None, None, None, None, None,
gr.update(choices=[], visible=False), "", {}, Image.open(DEFAULT_MAP)
)
# ----- UI -----
with gr.Blocks(title="RetailGenie") as demo:
gr.Markdown("# πŸ§žβ€β™‚οΈ RetailGenie – In-Store Smart Assistant")
with gr.Tabs():
with gr.TabItem("🧭 Navigator"):
with gr.Row():
country = gr.Dropdown(label="🌍 Country", choices=get_subfolders(BASE_DIR), interactive=True)
state = gr.Dropdown(label="πŸ™οΈ State", choices=[], interactive=True)
city = gr.Dropdown(label="🏘️ City", choices=[], interactive=True)
store = gr.Dropdown(label="πŸͺ Store", choices=[], interactive=True)
category = gr.Dropdown(label="πŸ›οΈ Category", choices=[], interactive=True)
product = gr.Dropdown(label="πŸ“¦ Product", choices=[], interactive=True)
brand = gr.Dropdown(label="🏷️ Brand", choices=[], interactive=True)
quantity = gr.Dropdown(label="πŸ”’ Quantity", visible=False, interactive=True)
result = gr.Textbox(label="πŸ” Product Info", lines=5)
data_state = gr.State()
store_map = gr.Image(value=Image.open(DEFAULT_MAP), type="pil", label="πŸ—ΊοΈ Store Map")
reset_btn = gr.Button("πŸ”„ Reset All")
# Dropdown chaining
country.change(lambda c: gr.update(choices=get_subfolders(os.path.join(BASE_DIR, c)) if c else [], value=None), inputs=country, outputs=state)
state.change(lambda c, s: gr.update(choices=get_subfolders(os.path.join(BASE_DIR, c, s)) if c and s else [], value=None), inputs=[country, state], outputs=city)
city.change(lambda c, s, ci: gr.update(choices=get_subfolders(os.path.join(BASE_DIR, c, s, ci)) if c and s and ci else [], value=None), inputs=[country, state, city], outputs=store)
store.change(lambda c, s, ci, st: gr.update(choices=get_subfolders(os.path.join(BASE_DIR, c, s, ci, st)) if all([c, s, ci, st]) else [], value=None), inputs=[country, state, city, store], outputs=category)
category.change(lambda c, s, ci, st, cat: gr.update(choices=get_subfolders(os.path.join(BASE_DIR, c, s, ci, st, cat)) if all([c, s, ci, st, cat]) else [], value=None), inputs=[country, state, city, store, category], outputs=product)
product.change(lambda c, s, ci, st, cat, prod: gr.update(choices=get_csv_files(os.path.join(BASE_DIR, c, s, ci, st, cat, prod)) if all([c, s, ci, st, cat, prod]) else [], value=None), inputs=[country, state, city, store, category, product], outputs=brand)
brand.change(lambda c, s, ci, st, cat, prod, b: get_quantities_from_csv(os.path.join(BASE_DIR, c, s, ci, st, cat, prod, f"{b}.csv")) if all([c, s, ci, st, cat, prod, b]) else (gr.update(choices=[], visible=False), {}), inputs=[country, state, city, store, category, product, brand], outputs=[quantity, data_state])
quantity.change(display_quantity_info, inputs=[quantity, data_state], outputs=result)
product.change(fn=get_product_image, inputs=product, outputs=store_map)
reset_btn.click(reset_all, inputs=[], outputs=[country, state, city, store, category, product, brand, quantity, result, data_state, store_map])
with gr.TabItem("🎁 Smart Suggestions"):
gr.Markdown("### πŸ€– Ask RetailGenie for Recommendations")
suggestion_input = gr.Textbox(label="Ask something like:", placeholder="Gift items under 500", lines=1)
suggest_btn = gr.Button("πŸ’‘ Get Suggestions")
suggestions_output = gr.Textbox(label="πŸ“ Suggestions", lines=10)
suggest_btn.click(suggest_items, inputs=suggestion_input, outputs=suggestions_output)
demo.launch()