rairo commited on
Commit
603ff25
·
verified ·
1 Parent(s): d1d8db7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -30
app.py CHANGED
@@ -32,14 +32,18 @@ llm_flash_exp = ChatGoogleGenerativeAI(
32
  class SmartShoppingAssistant:
33
  def __init__(self, products_df):
34
  self.df = products_df
 
 
 
35
  self.memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
36
  self.setup_agent()
37
-
38
- def find_closest_product(self, product_name, threshold=0.6):
 
39
  matches = get_close_matches(
40
- product_name.upper(),
41
- self.df['ProductName'].str.upper().tolist(),
42
- n=3, # Increased to get more potential matches
43
  cutoff=threshold
44
  )
45
  return matches if matches else []
@@ -75,26 +79,29 @@ class SmartShoppingAssistant:
75
  return f"Error matching products: {str(e)}"
76
 
77
  def search_products_fuzzy(self, product_names_with_quantities):
78
- """Search for products using fuzzy matching with quantity information"""
79
  results = pd.DataFrame()
 
 
80
  for item in product_names_with_quantities:
81
  product_info = item.split('quantity:')
82
- product_name = product_info[0].strip()
83
  quantity = int(product_info[1].strip()) if len(product_info) > 1 else 1
84
-
85
- # Clean up product name
86
- if 'ProductName ==' in product_name:
87
- product_name = product_name.split('==')[1].strip(' "\'')
88
-
89
- closest_matches = self.find_closest_product(product_name)
90
  for match in closest_matches:
91
- matched_products = self.df[self.df['ProductName'].str.upper() == match.upper()]
92
- if not matched_products.empty:
93
- matched_products['Quantity'] = quantity
94
- results = pd.concat([results, matched_products])
95
- break
 
 
96
 
97
- return results
98
 
99
  def setup_agent(self):
100
  """Set up the LangChain agent with necessary tools"""
@@ -180,14 +187,50 @@ class SmartShoppingAssistant:
180
  except Exception as e:
181
  return f"Error processing PDF: {str(e)}"
182
 
183
- # Main function remains the same
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  def main():
185
  st.set_page_config(page_title="Smart Shopping Assistant", layout="wide")
186
  st.title("🛒 Smart Shopping Assistant")
187
 
188
  @st.cache_data
189
  def load_product_data():
190
- return pd.read_csv('supermarket4.csv')
191
 
192
  df = load_product_data()
193
  assistant = SmartShoppingAssistant(df)
@@ -220,24 +263,56 @@ def main():
220
  query = st.text_area(
221
  "Describe what you're looking for (include quantities if needed):",
222
  height=100,
223
- placeholder="Example: 2 boxes of healthy breakfast cereals under $5, 1 gallon of milk",
224
  value=st.session_state.get('query', '')
225
  )
226
 
227
  if st.button("Search"):
228
  if query:
229
- with st.spinner("Searching for products..."):
230
  results = assistant.process_natural_language_query(query)
231
- st.write("### Results")
232
- st.write(results)
233
- else:
234
- st.warning("Please enter a search query or upload a shopping list.")
 
 
 
 
 
 
 
 
 
 
235
 
236
  with col2:
237
  st.header("Shopping Cart")
238
- if 'cart' not in st.session_state:
239
- st.session_state.cart = []
240
- st.write("Your cart is empty" if not st.session_state.cart else "Cart items here")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
 
242
  if __name__ == "__main__":
243
  main()
 
32
  class SmartShoppingAssistant:
33
  def __init__(self, products_df):
34
  self.df = products_df
35
+ # Preprocess product names for faster matching
36
+ self.df['CleanName'] = self.df['ProductName'].str.upper().str.strip().str.replace(r'\s+', ' ', regex=True)
37
+ self.product_names = self.df['CleanName'].tolist()
38
  self.memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
39
  self.setup_agent()
40
+
41
+ def find_closest_product(self, product_name, threshold=0.7): # Increased threshold
42
+ product_name = product_name.upper().strip()
43
  matches = get_close_matches(
44
+ product_name,
45
+ self.product_names,
46
+ n=3,
47
  cutoff=threshold
48
  )
49
  return matches if matches else []
 
79
  return f"Error matching products: {str(e)}"
80
 
81
  def search_products_fuzzy(self, product_names_with_quantities):
82
+ """Improved fuzzy search with batch processing"""
83
  results = pd.DataFrame()
84
+ matched_products = set()
85
+
86
  for item in product_names_with_quantities:
87
  product_info = item.split('quantity:')
88
+ clean_name = product_info[0].strip().upper().replace('PRODUCTNAME ==', '').strip(' "\'')
89
  quantity = int(product_info[1].strip()) if len(product_info) > 1 else 1
90
+
91
+ if clean_name in matched_products:
92
+ continue # Skip already matched products
93
+
94
+ closest_matches = self.find_closest_product(clean_name)
 
95
  for match in closest_matches:
96
+ matched = self.df[self.df['CleanName'] == match]
97
+ if not matched.empty:
98
+ matched = matched.copy()
99
+ matched['Quantity'] = quantity
100
+ results = pd.concat([results, matched])
101
+ matched_products.add(clean_name)
102
+ break # Take first good match
103
 
104
+ return results.drop_duplicates(subset=['CleanName'])
105
 
106
  def setup_agent(self):
107
  """Set up the LangChain agent with necessary tools"""
 
187
  except Exception as e:
188
  return f"Error processing PDF: {str(e)}"
189
 
190
+
191
+ # Add cart management functions
192
+ def add_to_cart(product):
193
+ if 'cart' not in st.session_state:
194
+ st.session_state.cart = []
195
+
196
+ # Check if product exists in cart
197
+ existing = next((item for item in st.session_state.cart if item['ProductName'] == product['ProductName']), None)
198
+ if existing:
199
+ existing['Quantity'] += product['Quantity']
200
+ else:
201
+ st.session_state.cart.append(product)
202
+
203
+ def remove_from_cart(product_name):
204
+ st.session_state.cart = [item for item in st.session_state.cart if item['ProductName'] != product_name]
205
+
206
+ def generate_receipt():
207
+ from fpdf import FPDF
208
+ pdf = FPDF()
209
+ pdf.add_page()
210
+ pdf.set_font("Arial", size=12)
211
+
212
+ pdf.cell(200, 10, txt="Bon Marche Receipt", ln=1, align='C')
213
+ pdf.cell(200, 10, txt=f"Date: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M')}", ln=1)
214
+
215
+ total = 0
216
+ for item in st.session_state.cart:
217
+ price = item['RetailPrice'] * item['Quantity']
218
+ pdf.cell(200, 10,
219
+ txt=f"{item['ProductName']} x{item['Quantity']} - ${price:.2f}",
220
+ ln=1)
221
+ total += price
222
+
223
+ pdf.cell(200, 10, txt=f"Total: ${total:.2f}", ln=1)
224
+ return pdf.output(dest='S').encode('latin1')
225
+
226
+ # Update main function
227
  def main():
228
  st.set_page_config(page_title="Smart Shopping Assistant", layout="wide")
229
  st.title("🛒 Smart Shopping Assistant")
230
 
231
  @st.cache_data
232
  def load_product_data():
233
+ return pd.read_csv('supermarket4i.csv') # Ensure correct filename
234
 
235
  df = load_product_data()
236
  assistant = SmartShoppingAssistant(df)
 
263
  query = st.text_area(
264
  "Describe what you're looking for (include quantities if needed):",
265
  height=100,
 
266
  value=st.session_state.get('query', '')
267
  )
268
 
269
  if st.button("Search"):
270
  if query:
271
+ with st.spinner("Searching..."):
272
  results = assistant.process_natural_language_query(query)
273
+ st.session_state.last_results = results
274
+
275
+ # Display results with add to cart buttons
276
+ if isinstance(results, str):
277
+ st.write(results)
278
+ else:
279
+ for _, row in results.iterrows():
280
+ cola, colb = st.columns([3,1])
281
+ with cola:
282
+ st.write(f"**{row['ProductName']}**")
283
+ st.write(f"Price: ${row['RetailPrice']} | Qty: {row['Quantity']}")
284
+ with colb:
285
+ if st.button("Add", key=row['ProductName']):
286
+ add_to_cart(row.to_dict())
287
 
288
  with col2:
289
  st.header("Shopping Cart")
290
+ if 'cart' in st.session_state and st.session_state.cart:
291
+ total = 0
292
+ for item in st.session_state.cart:
293
+ cols = st.columns([3,1,1])
294
+ with cols[0]:
295
+ st.write(f"{item['ProductName']} x{item['Quantity']}")
296
+ with cols[1]:
297
+ st.write(f"${item['RetailPrice'] * item['Quantity']:.2f}")
298
+ with cols[2]:
299
+ if st.button("❌", key=f"del_{item['ProductName']}"):
300
+ remove_from_cart(item['ProductName'])
301
+ st.rerun()
302
+ total += item['RetailPrice'] * item['Quantity']
303
+ st.divider()
304
+ st.write(f"**Total: ${total:.2f}**")
305
+
306
+ if st.button("Checkout"):
307
+ receipt = generate_receipt()
308
+ st.download_button(
309
+ label="Download Receipt",
310
+ data=receipt,
311
+ file_name="bon_marche_receipt.pdf",
312
+ mime="application/pdf"
313
+ )
314
+ else:
315
+ st.write("Your cart is empty")
316
 
317
  if __name__ == "__main__":
318
  main()