Parishri07 commited on
Commit
8fd1871
Β·
verified Β·
1 Parent(s): 252e1fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -75
app.py CHANGED
@@ -1,10 +1,21 @@
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 +23,6 @@ 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 +30,6 @@ 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 +40,11 @@ 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 +52,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,38 +60,36 @@ 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:
59
- return (
60
- "🎁 Gift Suggestions under β‚Ή500:\n"
61
- "1. Bath & Body Gift Set - β‚Ή499\n"
62
- "2. Mini Perfume Pack - β‚Ή349\n"
63
- "3. Skin Care Hamper - β‚Ή399\n"
64
- "4. Chocolates Gift Box - β‚Ή299"
65
- )
66
- if "shampoo" in query and "dry" in query:
67
- return (
68
- "🧴 Shampoos for Dry Hair:\n"
69
- "1. Dove 500 ml - β‚Ή325\n"
70
- "2. Clinic Plus 500 ml - β‚Ή680"
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 +102,25 @@ 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 +129,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
+ # ----- Config -----
7
  BASE_DIR = "data"
8
+ ASSETS_DIR = "assets"
9
+ STORE_MAP_FILE = os.path.join(ASSETS_DIR, "store_map_clinicplus.png")
10
 
11
+ AISLE_TO_BOX = {
12
+ "14": (220, 150, 40, 120),
13
+ "15": (270, 150, 40, 120),
14
+ "16": (320, 150, 40, 120),
15
+ # Add more aisles as needed
16
+ }
17
+
18
+ # ----- Utilities -----
19
  def get_subfolders(path):
20
  try:
21
  return sorted([f for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))])
 
23
  print(f"❌ Error reading subfolders from {path}: {e}")
24
  return []
25
 
 
26
  def get_csv_files(path):
27
  try:
28
  return sorted([f[:-4] for f in os.listdir(path) if f.endswith(".csv")])
 
30
  print(f"❌ Error reading CSVs from {path}: {e}")
31
  return []
32
 
 
33
  def get_quantities_from_csv(path):
34
  try:
35
  df = pd.read_csv(path)
 
40
  print(f"❌ Error loading CSV: {e}")
41
  return gr.update(choices=[], visible=False), {}
42
 
 
43
  def display_quantity_info(quantity, data_dict):
44
  try:
45
  df = pd.DataFrame(data_dict)
46
  row = df[df["Quantity"] == quantity].iloc[0]
47
+
48
  if str(row["In Stock"]).strip().lower() == "yes":
49
  msg = (
50
  f"βœ… {quantity} is available!\n"
 
52
  f"β€’ Aisle: {row['Aisle']}\n"
53
  f"β€’ Price: β‚Ή{row['Price']}"
54
  )
 
55
  if "Offer" in row and pd.notna(row["Offer"]) and row["Offer"].strip():
56
  msg += f"\nβ€’ πŸŽ‰ Offer: {row['Offer']}"
57
  return msg
 
60
  except Exception as e:
61
  return f"⚠️ Error: {e}"
62
 
63
+ def draw_bounding_box_on_map(quantity, data_dict):
64
+ try:
65
+ df = pd.DataFrame(data_dict)
66
+ row = df[df["Quantity"] == quantity].iloc[0]
67
+ aisle = str(row.get("Aisle", "")).strip()
68
+
69
+ image = Image.open(STORE_MAP_FILE).convert("RGBA")
70
+ draw = ImageDraw.Draw(image)
71
+
72
+ if aisle in AISLE_TO_BOX:
73
+ x, y, w, h = AISLE_TO_BOX[aisle]
74
+ draw.rectangle([x, y, x + w, y + h], outline="red", width=5)
75
+
76
+ return image
77
+ except Exception as e:
78
+ print(f"⚠️ Map render error: {e}")
79
+ return Image.open(STORE_MAP_FILE)
80
+
 
 
81
  def reset_all():
82
  return (
83
  None, None, None, None, None, None, None,
84
+ gr.update(choices=[], visible=False), # Quantity
85
+ "", {}, Image.open(STORE_MAP_FILE) # Info, State, Image
86
  )
87
 
88
+ # ----- UI -----
89
  with gr.Blocks(title="RetailGenie") as demo:
90
  gr.Markdown("# πŸ§žβ€β™‚οΈ RetailGenie – In-Store Smart Assistant")
91
 
92
  with gr.Tabs():
 
93
  with gr.TabItem("🧭 Navigator"):
94
  with gr.Row():
95
  country = gr.Dropdown(label="🌍 Country", choices=get_subfolders(BASE_DIR), value=None)
 
102
  quantity = gr.Dropdown(label="πŸ”’ Quantity", visible=False)
103
 
104
  result = gr.Textbox(label="πŸ” Product Info", lines=5)
105
+ store_map = gr.Image(value=Image.open(STORE_MAP_FILE), label="πŸ—ΊοΈ Store Map", type="pil")
106
+ data_state = gr.State(value={})
107
  reset_btn = gr.Button("πŸ”„ Reset All")
108
 
109
+ # Dropdown Chains
110
+ 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)
111
+ 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)
112
+ 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)
113
+ 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)
114
+ 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)
115
+ 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)
116
 
117
+ 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])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  quantity.change(display_quantity_info, inputs=[quantity, data_state], outputs=result)
120
+ quantity.change(draw_bounding_box_on_map, inputs=[quantity, data_state], outputs=store_map)
121
+
122
+ reset_btn.click(reset_all, inputs=[], outputs=[country, state, city, store, category, product, brand, quantity, result, data_state, store_map])
123
 
 
124
  with gr.TabItem("🎁 Smart Suggestions"):
125
  gr.Markdown("### πŸ€– Ask RetailGenie for Recommendations")
126
  suggestion_input = gr.Textbox(label="Ask something like:", placeholder="Gift items under 500", lines=1)
 
129
 
130
  suggest_btn.click(suggest_items, inputs=suggestion_input, outputs=suggestions_output)
131
 
132
+ demo.launch()