rairo commited on
Commit
dd3822b
·
verified ·
1 Parent(s): e1d5ce2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -31
app.py CHANGED
@@ -22,7 +22,7 @@ def configure_gemini(api_key):
22
  return genai.GenerativeModel('gemini-2.0-flash-thinking-exp')
23
 
24
  model = configure_gemini(os.environ['GOOGLE_API_KEY'])
25
-
26
  # Initialize Gemini models
27
  llm_flash_exp = ChatGoogleGenerativeAI(
28
  model="gemini-2.0-flash-exp",
@@ -92,7 +92,6 @@ class SmartShoppingAssistant:
92
  except Exception:
93
  quantity = 1
94
 
95
- # Avoid duplicates by checking the cleaned product name
96
  if clean_name in matched_products:
97
  continue
98
 
@@ -110,15 +109,11 @@ class SmartShoppingAssistant:
110
 
111
  def setup_agent(self):
112
  """Set up the LangChain agent with necessary tools (if needed)"""
113
- # In this revised version we will directly call our fuzzy search function,
114
- # so the tool is not used to convert to a string.
115
  def search_products(query):
116
  try:
117
- # Split into individual product entries
118
  product_entries = [entry.strip() for entry in query.split('or')]
119
  results = self.search_products_fuzzy(product_entries)
120
  if not results.empty:
121
- # Create a formatted string with each product’s quantity and price
122
  formatted_results = results.apply(
123
  lambda x: f"{x['ProductName']} (Quantity: {x['Quantity']}) - Price: ${x['RetailPrice']:.2f}",
124
  axis=1
@@ -153,7 +148,6 @@ class SmartShoppingAssistant:
153
  can be displayed and the total computed.
154
  """
155
  try:
156
- # Step 1: Extract items and quantities from the query.
157
  extraction_prompt = f"""
158
  Extract the products and their quantities from this shopping request.
159
  If a quantity is not specified, assume 1.
@@ -165,11 +159,8 @@ class SmartShoppingAssistant:
165
  """
166
 
167
  extracted_items = llm_flash_exp.predict(extraction_prompt)
168
- # Step 2: Match the extracted items with your catalogue.
169
  matched_products_str = self.match_products_with_catalogue(extracted_items)
170
- # Parse the matched products string into a list of entries.
171
  product_entries = [line.strip() for line in matched_products_str.splitlines() if line.strip()]
172
- # Step 3: Do a fuzzy search and get the DataFrame result.
173
  results_df = self.search_products_fuzzy(product_entries)
174
  return results_df
175
  except Exception as e:
@@ -205,7 +196,7 @@ class SmartShoppingAssistant:
205
  def add_to_cart(product):
206
  if 'cart' not in st.session_state:
207
  st.session_state.cart = []
208
- # Check if product exists in the cart
209
  existing = next((item for item in st.session_state.cart if item['ProductName'] == product['ProductName']), None)
210
  if existing:
211
  existing['Quantity'] += product['Quantity']
@@ -242,13 +233,22 @@ def main():
242
  st.set_page_config(page_title="Smart Shopping Assistant", layout="wide")
243
  st.title("🛒 Smart Shopping Assistant")
244
 
 
245
  @st.cache_data
246
  def load_product_data():
247
- return pd.read_csv('supermarket4i.csv') # Adjust filename/path as needed
248
 
249
  df = load_product_data()
250
  assistant = SmartShoppingAssistant(df)
251
 
 
 
 
 
 
 
 
 
252
  with st.sidebar:
253
  st.header("Upload Shopping List")
254
  uploaded_file = st.file_uploader(
@@ -269,45 +269,50 @@ def main():
269
  st.session_state.query = extracted_text
270
  except Exception as e:
271
  st.error(f"Error processing file: {str(e)}")
272
-
273
  col1, col2 = st.columns([2, 1])
274
 
275
  with col1:
276
  st.header("Search Products")
 
277
  query = st.text_area(
278
  "Describe what you're looking for (include quantities if needed):",
279
  height=100,
280
- value=st.session_state.get('query', '')
281
  )
282
 
283
- if st.button("Search"):
284
  if query:
285
  with st.spinner("Searching..."):
286
  results = assistant.process_natural_language_query(query)
287
  st.session_state.last_results = results
288
-
289
- # If results is a string (an error message), show it.
290
- if isinstance(results, str):
291
- st.write(results)
292
- else:
293
- st.subheader("Results")
294
- # Display each product with its quantity, price and an Add to Cart button.
295
- for index, row in results.iterrows():
296
- cola, colb = st.columns([3, 1])
297
- with cola:
 
 
 
298
  st.write(f"**{row['ProductName']}**")
299
  st.write(f"Price: ${row['RetailPrice']:.2f} | Qty: {row['Quantity']}")
300
- with colb:
 
301
  if st.button("Add", key=f"add_{index}"):
302
  add_to_cart(row.to_dict())
303
-
304
- # Show the total cost for the search results
305
- total_search = (results['RetailPrice'] * results['Quantity']).sum()
306
- st.markdown(f"**Total for these items: ${total_search:.2f}**")
307
 
308
  with col2:
309
  st.header("Shopping Cart")
310
- if 'cart' in st.session_state and st.session_state.cart:
311
  total_cart = 0
312
  for item in st.session_state.cart:
313
  cols = st.columns([3, 1, 1])
@@ -319,6 +324,7 @@ def main():
319
  with cols[2]:
320
  if st.button("❌", key=f"del_{item['ProductName']}"):
321
  remove_from_cart(item['ProductName'])
 
322
  st.experimental_rerun()
323
  total_cart += item['RetailPrice'] * item['Quantity']
324
  st.divider()
 
22
  return genai.GenerativeModel('gemini-2.0-flash-thinking-exp')
23
 
24
  model = configure_gemini(os.environ['GOOGLE_API_KEY'])
25
+
26
  # Initialize Gemini models
27
  llm_flash_exp = ChatGoogleGenerativeAI(
28
  model="gemini-2.0-flash-exp",
 
92
  except Exception:
93
  quantity = 1
94
 
 
95
  if clean_name in matched_products:
96
  continue
97
 
 
109
 
110
  def setup_agent(self):
111
  """Set up the LangChain agent with necessary tools (if needed)"""
 
 
112
  def search_products(query):
113
  try:
 
114
  product_entries = [entry.strip() for entry in query.split('or')]
115
  results = self.search_products_fuzzy(product_entries)
116
  if not results.empty:
 
117
  formatted_results = results.apply(
118
  lambda x: f"{x['ProductName']} (Quantity: {x['Quantity']}) - Price: ${x['RetailPrice']:.2f}",
119
  axis=1
 
148
  can be displayed and the total computed.
149
  """
150
  try:
 
151
  extraction_prompt = f"""
152
  Extract the products and their quantities from this shopping request.
153
  If a quantity is not specified, assume 1.
 
159
  """
160
 
161
  extracted_items = llm_flash_exp.predict(extraction_prompt)
 
162
  matched_products_str = self.match_products_with_catalogue(extracted_items)
 
163
  product_entries = [line.strip() for line in matched_products_str.splitlines() if line.strip()]
 
164
  results_df = self.search_products_fuzzy(product_entries)
165
  return results_df
166
  except Exception as e:
 
196
  def add_to_cart(product):
197
  if 'cart' not in st.session_state:
198
  st.session_state.cart = []
199
+ # Check if product exists in the cart and update quantity if so.
200
  existing = next((item for item in st.session_state.cart if item['ProductName'] == product['ProductName']), None)
201
  if existing:
202
  existing['Quantity'] += product['Quantity']
 
233
  st.set_page_config(page_title="Smart Shopping Assistant", layout="wide")
234
  st.title("🛒 Smart Shopping Assistant")
235
 
236
+ # Load product data only once.
237
  @st.cache_data
238
  def load_product_data():
239
+ return pd.read_csv('supermarket4i.csv')
240
 
241
  df = load_product_data()
242
  assistant = SmartShoppingAssistant(df)
243
 
244
+ # Initialize session state variables if not present.
245
+ if 'query' not in st.session_state:
246
+ st.session_state.query = ""
247
+ if 'last_results' not in st.session_state:
248
+ st.session_state.last_results = None
249
+ if 'cart' not in st.session_state:
250
+ st.session_state.cart = []
251
+
252
  with st.sidebar:
253
  st.header("Upload Shopping List")
254
  uploaded_file = st.file_uploader(
 
269
  st.session_state.query = extracted_text
270
  except Exception as e:
271
  st.error(f"Error processing file: {str(e)}")
272
+
273
  col1, col2 = st.columns([2, 1])
274
 
275
  with col1:
276
  st.header("Search Products")
277
+ # Use session_state query so that we can clear it after search if desired.
278
  query = st.text_area(
279
  "Describe what you're looking for (include quantities if needed):",
280
  height=100,
281
+ value=st.session_state.query
282
  )
283
 
284
+ if st.button("Search", key="search_button"):
285
  if query:
286
  with st.spinner("Searching..."):
287
  results = assistant.process_natural_language_query(query)
288
  st.session_state.last_results = results
289
+ # Optionally clear the query after search:
290
+ st.session_state.query = ""
291
+
292
+ # Display search results if available.
293
+ if st.session_state.last_results is not None:
294
+ if isinstance(st.session_state.last_results, str):
295
+ st.write(st.session_state.last_results)
296
+ else:
297
+ st.subheader("Results")
298
+ for index, row in st.session_state.last_results.iterrows():
299
+ with st.container():
300
+ cols = st.columns([3, 1])
301
+ with cols[0]:
302
  st.write(f"**{row['ProductName']}**")
303
  st.write(f"Price: ${row['RetailPrice']:.2f} | Qty: {row['Quantity']}")
304
+ with cols[1]:
305
+ # When a product is added, update the cart state without forcing a full rerun.
306
  if st.button("Add", key=f"add_{index}"):
307
  add_to_cart(row.to_dict())
308
+ st.success(f"Added {row['ProductName']} to cart")
309
+
310
+ total_search = (st.session_state.last_results['RetailPrice'] * st.session_state.last_results['Quantity']).sum()
311
+ st.markdown(f"**Total for these items: ${total_search:.2f}**")
312
 
313
  with col2:
314
  st.header("Shopping Cart")
315
+ if st.session_state.cart:
316
  total_cart = 0
317
  for item in st.session_state.cart:
318
  cols = st.columns([3, 1, 1])
 
324
  with cols[2]:
325
  if st.button("❌", key=f"del_{item['ProductName']}"):
326
  remove_from_cart(item['ProductName'])
327
+ # We use experimental_rerun here so that the cart updates immediately.
328
  st.experimental_rerun()
329
  total_cart += item['RetailPrice'] * item['Quantity']
330
  st.divider()