Parishri07 commited on
Commit
c872642
Β·
verified Β·
1 Parent(s): 080994c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -25
app.py CHANGED
@@ -1,33 +1,165 @@
1
  import gradio as gr
2
- from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- STORE_MAP_FILE = "assets/store_map_clinicplus.png"
5
 
6
  def reset_all():
7
  return (
8
- None, None, None, None, None, None, None,
9
- gr.update(choices=[], visible=False),
10
- "", {}, Image.open(STORE_MAP_FILE)
 
 
 
 
 
 
 
 
11
  )
12
 
13
- with gr.Blocks() as demo:
14
- country = gr.Dropdown(choices=["A"], value="A")
15
- state = gr.Dropdown(choices=["B"], value="B")
16
- city = gr.Dropdown(choices=["C"], value="C")
17
- store = gr.Dropdown(choices=["D"], value="D")
18
- category = gr.Dropdown(choices=["E"], value="E")
19
- product = gr.Dropdown(choices=["F"], value="F")
20
- brand = gr.Dropdown(choices=["G"], value="G")
21
- quantity = gr.Dropdown(choices=["1"], value="1", visible=True)
22
- result = gr.Textbox("", lines=2)
23
- data_state = gr.State(value={"x": 1})
24
- store_map = gr.Image(value=Image.open(STORE_MAP_FILE), type="pil")
25
- reset_btn = gr.Button("Reset")
26
-
27
- reset_btn.click(
28
- reset_all,
29
- inputs=[],
30
- outputs=[country, state, city, store, category, product, brand, quantity, result, data_state, store_map]
31
- )
32
 
33
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ import pandas as pd
4
+ from PIL import Image, ImageDraw
5
+
6
+ BASE_DIR = "data"
7
+ ASSETS_DIR = "assets"
8
+ STORE_MAP_FILE = os.path.join(ASSETS_DIR, "store_map_clinicplus.png")
9
+
10
+
11
+ # Approximate mapping from Aisle number to bounding box on the store map
12
+ AISLE_TO_BOX = {
13
+ # Example: '14': (x, y, width, height) - you can later load this from config
14
+ "14": (220, 150, 40, 120),
15
+ "15": (270, 150, 40, 120),
16
+ "16": (320, 150, 40, 120),
17
+ # Add more as needed...
18
+ }
19
+
20
+
21
+ def get_subfolders(path):
22
+ try:
23
+ return sorted([f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))])
24
+ except Exception as e:
25
+ print(f"❌ Error reading subfolders from {path}: {e}")
26
+ return []
27
+
28
+
29
+ def get_csv_files(path):
30
+ try:
31
+ return sorted([f[:-4] for f in os.listdir(path) if f.endswith(".csv")])
32
+ except Exception as e:
33
+ print(f"❌ Error reading CSVs from {path}: {e}")
34
+ return []
35
+
36
+
37
+ def get_quantities_from_csv(path):
38
+ try:
39
+ df = pd.read_csv(path)
40
+ if df.empty or "Quantity" not in df.columns:
41
+ return gr.update(choices=[], visible=False), {}
42
+ return gr.update(choices=df["Quantity"].dropna().tolist(), visible=True), df.to_dict()
43
+ except Exception as e:
44
+ print(f"❌ Error loading CSV: {e}")
45
+ return gr.update(choices=[], visible=False), {}
46
+
47
+
48
+ def display_quantity_info(quantity, data_dict):
49
+ try:
50
+ df = pd.DataFrame(data_dict)
51
+ row = df[df["Quantity"] == quantity].iloc[0]
52
+
53
+ if str(row["In Stock"]).strip().lower() == "yes":
54
+ msg = (
55
+ f"βœ… {quantity} is available!\n"
56
+ f"β€’ Floor: {row['Floor']}\n"
57
+ f"β€’ Aisle: {row['Aisle']}\n"
58
+ f"β€’ Price: β‚Ή{row['Price']}"
59
+ )
60
+ if "Offer" in row and pd.notna(row["Offer"]) and row["Offer"].strip():
61
+ msg += f"\nβ€’ πŸŽ‰ Offer: {row['Offer']}"
62
+ return msg
63
+ else:
64
+ return f"❌ Sorry, {quantity} is currently not in stock."
65
+ except Exception as e:
66
+ return f"⚠️ Error: {e}"
67
+
68
+
69
+ def generate_map_with_highlight(quantity, data_dict):
70
+ try:
71
+ df = pd.DataFrame(data_dict)
72
+ row = df[df["Quantity"] == quantity].iloc[0]
73
+ aisle = str(row.get("Aisle", "")).strip()
74
+
75
+ image = Image.open(STORE_MAP_FILE).convert("RGBA")
76
+ draw = ImageDraw.Draw(image)
77
+
78
+ if aisle in AISLE_TO_BOX:
79
+ x, y, w, h = AISLE_TO_BOX[aisle]
80
+ draw.rectangle([x, y, x + w, y + h], outline="red", width=5)
81
+
82
+ return image
83
+ except Exception as e:
84
+ print(f"⚠️ Map render error: {e}")
85
+ return Image.open(STORE_MAP_FILE)
86
+
87
+
88
+ def suggest_items(query):
89
+ query = query.lower()
90
+ if "gift" in query and "500" in query:
91
+ return (
92
+ "🎁 Gift Suggestions under β‚Ή500:\n"
93
+ "1. Bath & Body Gift Set - β‚Ή499\n"
94
+ "2. Mini Perfume Pack - β‚Ή349\n"
95
+ "3. Skin Care Hamper - β‚Ή399\n"
96
+ "4. Chocolates Gift Box - β‚Ή299"
97
+ )
98
+ if "shampoo" in query and "dry" in query:
99
+ return (
100
+ "🧴 Shampoos for Dry Hair:\n"
101
+ "1. Dove 500 ml - β‚Ή325\n"
102
+ "2. Clinic Plus 500 ml - β‚Ή680"
103
+ )
104
+ return "🀷 Sorry, no smart suggestions found. Try asking: 'Gift items under 500' or 'Shampoo for dry hair'"
105
 
 
106
 
107
  def reset_all():
108
  return (
109
+ None, # country - Dropdown
110
+ None, # state - Dropdown
111
+ None, # city - Dropdown
112
+ None, # store - Dropdown
113
+ None, # category - Dropdown
114
+ None, # product - Dropdown
115
+ None, # brand - Dropdown
116
+ gr.update(choices=[], visible=False), # quantity - Dropdown
117
+ "", # result - Textbox
118
+ {}, # data_state - State (MUST be a raw dict or string, not gr.update)
119
+ Image.open(STORE_MAP_FILE) # store_map - Image (if using type="pil")
120
  )
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
+
124
+ with gr.Blocks(title="RetailGenie") as demo:
125
+ gr.Markdown("# πŸ§žβ€β™‚οΈ RetailGenie – In-Store Smart Assistant")
126
+
127
+ with gr.Tabs():
128
+ with gr.TabItem("🧭 Navigator"):
129
+ with gr.Row():
130
+ country = gr.Dropdown(label="🌍 Country", choices=get_subfolders(BASE_DIR), value=None)
131
+ state = gr.Dropdown(label="πŸ™οΈ State", choices=[], interactive=False)
132
+ city = gr.Dropdown(label="🏘️ City", choices=[], interactive=False)
133
+ store = gr.Dropdown(label="πŸͺ Store", choices=[], interactive=False)
134
+ category = gr.Dropdown(label="πŸ›οΈ Category", choices=[], interactive=False)
135
+ product = gr.Dropdown(label="πŸ“¦ Product", choices=[], interactive=False)
136
+ brand = gr.Dropdown(label="🏷️ Brand", choices=[], interactive=False)
137
+ quantity = gr.Dropdown(label="πŸ”’ Quantity", visible=False)
138
+
139
+ result = gr.Textbox(label="πŸ” Product Info", lines=5)
140
+ store_map = gr.Image(label="πŸ—ΊοΈ Store Map", value=Image.open(STORE_MAP_FILE), type="pil")
141
+ data_state = gr.State(value={})
142
+ reset_btn = gr.Button("πŸ”„ Reset All")
143
+
144
+ country.change(lambda c: gr.update(choices=get_subfolders(os.path.join(BASE_DIR, c)) if c else [], value=None, interactive=True), inputs=country, outputs=state)
145
+ state.change(lambda c, s: gr.update(choices=get_subfolders(os.path.join(BASE_DIR, c, s)) if c and s else [], value=None, interactive=True), inputs=[country, state], outputs=city)
146
+ 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, interactive=True), inputs=[country, state, city], outputs=store)
147
+ 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, interactive=True), inputs=[country, state, city, store], outputs=category)
148
+ 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, interactive=True), inputs=[country, state, city, store, category], outputs=product)
149
+ 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, interactive=True), inputs=[country, state, city, store, category, product], outputs=brand)
150
+
151
+ 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])
152
+
153
+ quantity.change(display_quantity_info, inputs=[quantity, data_state], outputs=result)
154
+ quantity.change(generate_map_with_highlight, inputs=[quantity, data_state], outputs=store_map)
155
+ reset_btn.click(reset_all, inputs=[], outputs=[country, state, city, store, category, product, brand, quantity, result, data_state, store_map])
156
+
157
+ with gr.TabItem("🎁 Smart Suggestions"):
158
+ gr.Markdown("### πŸ€– Ask RetailGenie for Recommendations")
159
+ suggestion_input = gr.Textbox(label="Ask something like:", placeholder="Gift items under 500", lines=1)
160
+ suggest_btn = gr.Button("πŸ’‘ Get Suggestions")
161
+ suggestions_output = gr.Textbox(label="πŸ“ Suggestions", lines=10)
162
+
163
+ suggest_btn.click(suggest_items, inputs=suggestion_input, outputs=suggestions_output)
164
+
165
+ demo.launch()