Parishri07 commited on
Commit
f13d5be
Β·
verified Β·
1 Parent(s): 853b1b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -56
app.py CHANGED
@@ -1,10 +1,23 @@
1
  import gradio as gr
2
  import os
3
  import pandas as pd
 
4
 
5
  BASE_DIR = "data"
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Get subfolders
8
  def get_subfolders(path):
9
  try:
10
  return sorted([f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))])
@@ -12,7 +25,7 @@ def get_subfolders(path):
12
  print(f"❌ Error reading subfolders from {path}: {e}")
13
  return []
14
 
15
- # Get CSV files
16
  def get_csv_files(path):
17
  try:
18
  return sorted([f[:-4] for f in os.listdir(path) if f.endswith(".csv")])
@@ -20,7 +33,7 @@ def get_csv_files(path):
20
  print(f"❌ Error reading CSVs from {path}: {e}")
21
  return []
22
 
23
- # Load quantities from brand CSV
24
  def get_quantities_from_csv(path):
25
  try:
26
  df = pd.read_csv(path)
@@ -31,11 +44,12 @@ def get_quantities_from_csv(path):
31
  print(f"❌ Error loading CSV: {e}")
32
  return gr.update(choices=[], visible=False), {}
33
 
34
- # Show result based on quantity
35
  def display_quantity_info(quantity, data_dict):
36
  try:
37
  df = pd.DataFrame(data_dict)
38
  row = df[df["Quantity"] == quantity].iloc[0]
 
39
  if str(row["In Stock"]).strip().lower() == "yes":
40
  msg = (
41
  f"βœ… {quantity} is available!\n"
@@ -43,7 +57,6 @@ def display_quantity_info(quantity, data_dict):
43
  f"β€’ Aisle: {row['Aisle']}\n"
44
  f"β€’ Price: β‚Ή{row['Price']}"
45
  )
46
- # Show only Offer field if it exists and is not empty
47
  if "Offer" in row and pd.notna(row["Offer"]) and row["Offer"].strip():
48
  msg += f"\nβ€’ πŸŽ‰ Offer: {row['Offer']}"
49
  return msg
@@ -52,7 +65,26 @@ def display_quantity_info(quantity, data_dict):
52
  except Exception as e:
53
  return f"⚠️ Error: {e}"
54
 
55
- # Smart Suggestions (hardcoded logic)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  def suggest_items(query):
57
  query = query.lower()
58
  if "gift" in query and "500" in query:
@@ -71,19 +103,18 @@ def suggest_items(query):
71
  )
72
  return "🀷 Sorry, no smart suggestions found. Try asking: 'Gift items under 500' or 'Shampoo for dry hair'"
73
 
74
- # Reset logic
75
  def reset_all():
76
  return (
77
  None, None, None, None, None, None, None,
78
- gr.update(choices=[], visible=False), "", {}
79
  )
80
 
81
- # Interface
82
  with gr.Blocks(title="RetailGenie") as demo:
83
  gr.Markdown("# πŸ§žβ€β™‚οΈ RetailGenie – In-Store Smart Assistant")
84
 
85
  with gr.Tabs():
86
- # 🧭 Navigator Tab
87
  with gr.TabItem("🧭 Navigator"):
88
  with gr.Row():
89
  country = gr.Dropdown(label="🌍 Country", choices=get_subfolders(BASE_DIR), value=None)
@@ -96,58 +127,23 @@ with gr.Blocks(title="RetailGenie") as demo:
96
  quantity = gr.Dropdown(label="πŸ”’ Quantity", visible=False)
97
 
98
  result = gr.Textbox(label="πŸ” Product Info", lines=5)
 
99
  data_state = gr.State()
100
  reset_btn = gr.Button("πŸ”„ Reset All")
101
 
102
- # Dropdown chain logic
103
- country.change(
104
- lambda c: gr.update(choices=get_subfolders(os.path.join(BASE_DIR, c)) if c else [], value=None, interactive=True),
105
- inputs=country,
106
- outputs=state
107
- )
108
-
109
- state.change(
110
- lambda c, s: gr.update(choices=get_subfolders(os.path.join(BASE_DIR, c, s)) if c and s else [], value=None, interactive=True),
111
- inputs=[country, state],
112
- outputs=city
113
- )
114
-
115
- city.change(
116
- 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),
117
- inputs=[country, state, city],
118
- outputs=store
119
- )
120
 
121
- store.change(
122
- 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),
123
- inputs=[country, state, city, store],
124
- outputs=category
125
- )
126
-
127
- category.change(
128
- 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),
129
- inputs=[country, state, city, store, category],
130
- outputs=product
131
- )
132
-
133
- product.change(
134
- 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),
135
- inputs=[country, state, city, store, category, product],
136
- outputs=brand
137
- )
138
-
139
- brand.change(
140
- lambda c, s, ci, st, cat, prod, b: get_quantities_from_csv(
141
- os.path.join(BASE_DIR, c, s, ci, st, cat, prod, f"{b}.csv")
142
- ) if all([c, s, ci, st, cat, prod, b]) else (gr.update(choices=[], visible=False), {}),
143
- inputs=[country, state, city, store, category, product, brand],
144
- outputs=[quantity, data_state]
145
- )
146
 
147
  quantity.change(display_quantity_info, inputs=[quantity, data_state], outputs=result)
148
- reset_btn.click(reset_all, inputs=[], outputs=[country, state, city, store, category, product, brand, quantity, result, data_state])
 
149
 
150
- # 🎁 Suggestions Tab
151
  with gr.TabItem("🎁 Smart Suggestions"):
152
  gr.Markdown("### πŸ€– Ask RetailGenie for Recommendations")
153
  suggestion_input = gr.Textbox(label="Ask something like:", placeholder="Gift items under 500", lines=1)
@@ -156,4 +152,4 @@ with gr.Blocks(title="RetailGenie") as demo:
156
 
157
  suggest_btn.click(suggest_items, inputs=suggestion_input, outputs=suggestions_output)
158
 
159
- 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))])
 
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")])
 
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)
 
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"
 
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
 
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:
 
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, None, None, None, None, None, None,
110
+ gr.update(choices=[], visible=False), "", {}, STORE_MAP_FILE
111
  )
112
 
113
+
114
  with gr.Blocks(title="RetailGenie") as demo:
115
  gr.Markdown("# πŸ§žβ€β™‚οΈ RetailGenie – In-Store Smart Assistant")
116
 
117
  with gr.Tabs():
 
118
  with gr.TabItem("🧭 Navigator"):
119
  with gr.Row():
120
  country = gr.Dropdown(label="🌍 Country", choices=get_subfolders(BASE_DIR), value=None)
 
127
  quantity = gr.Dropdown(label="πŸ”’ Quantity", visible=False)
128
 
129
  result = gr.Textbox(label="πŸ” Product Info", lines=5)
130
+ store_map = gr.Image(label="πŸ—ΊοΈ Store Map", value=STORE_MAP_FILE, type="pil")
131
  data_state = gr.State()
132
  reset_btn = gr.Button("πŸ”„ Reset All")
133
 
134
+ 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)
135
+ 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)
136
+ 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)
137
+ 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)
138
+ 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)
139
+ 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)
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
+ 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])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
  quantity.change(display_quantity_info, inputs=[quantity, data_state], outputs=result)
144
+ quantity.change(generate_map_with_highlight, inputs=[quantity, data_state], outputs=store_map)
145
+ reset_btn.click(reset_all, inputs=[], outputs=[country, state, city, store, category, product, brand, quantity, result, data_state, store_map])
146
 
 
147
  with gr.TabItem("🎁 Smart Suggestions"):
148
  gr.Markdown("### πŸ€– Ask RetailGenie for Recommendations")
149
  suggestion_input = gr.Textbox(label="Ask something like:", placeholder="Gift items under 500", lines=1)
 
152
 
153
  suggest_btn.click(suggest_items, inputs=suggestion_input, outputs=suggestions_output)
154
 
155
+ demo.launch()