shivanis14 commited on
Commit
57ee4ec
1 Parent(s): c8edada

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -156
app.py CHANGED
@@ -451,175 +451,171 @@ def chatbot_response(image_urls_str, product_name_by_user, data_extractor_url, s
451
  else:
452
  return [], "I'm here to analyze food products. Please provide an image URL (Example : http://example.com/image.jpg) or product name (Example : Harvest Gold Bread)"
453
 
454
- # Initialize session state variables
455
- if "messages" not in st.session_state:
456
- st.session_state.messages = []
457
- if "product_selected" not in st.session_state:
458
- st.session_state.product_selected = False
459
- if "product_shared" not in st.session_state:
460
- st.session_state.product_shared = False
461
- if "analyze_more" not in st.session_state:
462
- st.session_state.analyze_more = True
463
- if "welcome_shown" not in st.session_state:
464
- st.session_state.welcome_shown = False
465
- if "yes_no_choice" not in st.session_state:
466
- st.session_state.yes_no_choice = None
467
- if "welcome_msg" not in st.session_state:
468
- st.session_state.welcome_msg = "Welcome to ConsumeWise! What product would you like me to analyze today?"
469
- if "system_prompt" not in st.session_state:
470
- st.session_state.system_prompt = ""
471
- if "similar_products" not in st.session_state:
472
- st.session_state.similar_products = []
473
- if "awaiting_selection" not in st.session_state:
474
- st.session_state.awaiting_selection = False
475
- if "current_user_input" not in st.session_state:
476
- st.session_state.current_user_input = ""
477
- if "selected_product" not in st.session_state:
478
- st.session_state.selected_product = None
479
-
480
- # Sidebar input for system prompt with an 'Apply' button
481
- st.sidebar.header("System Prompt")
482
- system_prompt = st.sidebar.text_area(
483
- "Enter your system prompt here (required):",
484
- value=st.session_state.system_prompt,
485
- height=150,
486
- key="system_prompt_input"
487
- )
488
-
489
- # Apply button to trigger system prompt update
490
- if st.sidebar.button("Submit Prompt"):
491
- if system_prompt.strip():
492
- st.session_state.system_prompt = system_prompt
493
- # Reset session state when system prompt is changed
494
- st.session_state.product_selected = False
495
- st.session_state.analyze_more = True
496
- st.session_state.welcome_shown = False
497
- st.session_state.yes_no_choice = None
498
- st.session_state.product_shared = False
499
- st.session_state.welcome_msg = "Welcome to ConsumeWise! What product would you like me to analyze today?"
500
- st.session_state.messages = []
501
- st.session_state.similar_products = []
502
- st.session_state.awaiting_selection = False
503
- st.session_state.current_user_input = ""
504
- st.session_state.selected_product = None
505
- st.rerun()
506
- else:
507
- st.sidebar.error("Please enter a valid system prompt.")
508
-
509
- # Display the title
510
- st.title("ConsumeWise - Your Food Product Analysis Assistant")
511
-
512
- def show_welcome_message():
513
- if not st.session_state.welcome_shown:
514
- st.session_state.messages.append({"role": "assistant", "content": st.session_state.welcome_msg})
515
- st.session_state.welcome_shown = True
516
-
517
- def handle_product_selection():
518
- print(f"DEBUG Inside handle_product_selection: st.session_state.similar_products : {st.session_state.similar_products}")
519
- print(f"DEBUG Inside handle_product_selection: st.session_state.awaiting_selection : {st.session_state.awaiting_selection}")
520
-
521
- if st.session_state.similar_products and st.session_state.awaiting_selection:
522
- choice = st.radio(
523
- "Select a product:",
524
- st.session_state.similar_products + ["None of the above"],
525
- key="product_choice"
526
  )
527
 
528
- # Add a confirm button
529
- if st.button("Confirm Selection"):
530
- if choice != "None of the above":
531
- print(f"Selected choice : {choice}")
532
- st.session_state.product_selected = True
533
- st.session_state.awaiting_selection = False
534
- st.session_state.selected_product = choice
535
- _, msg = chatbot_response("", choice, data_extractor_url, system_prompt, extract_info=True)
536
- st.session_state.messages.append({"role": "assistant", "content": msg})
537
  else:
538
- st.session_state.awaiting_selection = False
539
- st.session_state.messages.append(
540
- {"role": "assistant", "content": "Please provide the image URL of the product."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
541
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
 
543
- st.session_state.similar_products = [] # Clear the products list
544
- #print("DEBUG : Re-running the code")
545
- #st.rerun()
546
-
547
- def chat_response(user_input, system_prompt):
548
- if not st.session_state.product_selected:
549
- if "http:/" not in user_input and "https:/" not in user_input:
550
- st.session_state.product_shared = True
551
- st.session_state.current_user_input = user_input
552
- similar_products, _ = chatbot_response("", user_input, data_extractor_url, system_prompt, extract_info=False)
553
 
554
- if len(similar_products) > 0:
555
- st.session_state.similar_products = similar_products
556
- st.session_state.awaiting_selection = True
557
- return "Here are some similar products. Please select:"
558
- else:
559
- return "Product not found in our database. Please provide the image URL of the product."
560
-
561
- else:
562
- if ("http:/" in user_input or "https:/" in user_input) and (".jpeg" in user_input or ".jpg" in user_input) and st.session_state.product_shared:
563
- _, msg = chatbot_response(user_input, "", data_extractor_url, system_prompt, extract_info=True)
564
- st.session_state.product_selected = True
565
- return msg
566
  else:
567
- if not st.session_state.product_shared:
568
- return "Please provide the product name first"
569
- else:
570
- return "Please provide valid image URL of the product."
571
- else:
572
  return "Next Product"
573
 
574
- # Show warning if system prompt is empty and disable chat input
575
- if not st.session_state.system_prompt.strip():
576
- st.sidebar.error("Please enter a system prompt in the sidebar before starting the conversation.")
577
- st.warning("⚠️ Please enter a system prompt in the sidebar before proceeding.")
578
- st.chat_input("Enter your message:", disabled=True)
579
- else:
580
- # Show the welcome message at the start
581
- show_welcome_message()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
582
 
583
  # Display chat history
584
  for message in st.session_state.messages:
585
  with st.chat_message(message["role"]):
586
  st.markdown(message["content"])
587
 
588
- # Input Box for User Interaction
589
- user_input = st.chat_input("Enter your message:", key="user_input")
590
-
591
- if user_input:
592
- st.session_state.messages.append({"role": "user", "content": user_input})
593
- with st.chat_message("user"):
594
- st.markdown(user_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595
 
596
- response = chat_response(user_input, system_prompt)
597
-
598
- if response != "Next Product":
599
- st.session_state.messages.append({"role": "assistant", "content": response})
600
- with st.chat_message("assistant"):
601
- st.markdown(response)
602
-
603
- # Handle product selection if awaiting
604
- print(f"Are you awaiting_selection ?? : {st.session_state.awaiting_selection}")
605
- if st.session_state.awaiting_selection:
606
- handle_product_selection()
607
- print("After executing handle_product_selection")
608
-
609
- else:
610
- st.session_state.product_selected = False
611
- st.session_state.analyze_more = True
612
- st.session_state.welcome_shown = False
613
- st.session_state.yes_no_choice = None
614
- st.session_state.product_shared = False
615
- st.session_state.welcome_msg = "What is the next product you would like me to analyze today?"
616
- st.session_state.similar_products = []
617
- st.session_state.awaiting_selection = False
618
- st.session_state.current_user_input = ""
619
- st.session_state.selected_product = None
620
- st.rerun()
621
-
622
- # Option to Clear Chat History
623
- if st.button("Clear Chat History"):
624
- st.session_state.clear()
625
- st.rerun()
 
451
  else:
452
  return [], "I'm here to analyze food products. Please provide an image URL (Example : http://example.com/image.jpg) or product name (Example : Harvest Gold Bread)"
453
 
454
+ class SessionState:
455
+ """Handles all session state variables in a centralized way"""
456
+ @staticmethod
457
+ def initialize():
458
+ initial_states = {
459
+ "messages": [],
460
+ "product_selected": False,
461
+ "product_shared": False,
462
+ "analyze_more": True,
463
+ "welcome_shown": False,
464
+ "yes_no_choice": None,
465
+ "welcome_msg": "Welcome to ConsumeWise! What product would you like me to analyze today?",
466
+ "system_prompt": "",
467
+ "similar_products": [],
468
+ "awaiting_selection": False,
469
+ "current_user_input": "",
470
+ "selected_product": None
471
+ }
472
+
473
+ for key, value in initial_states.items():
474
+ if key not in st.session_state:
475
+ st.session_state[key] = value
476
+
477
+ class SystemPromptManager:
478
+ """Manages the system prompt input and related functionality"""
479
+ @staticmethod
480
+ def render_sidebar():
481
+ st.sidebar.header("System Prompt")
482
+ system_prompt = st.sidebar.text_area(
483
+ "Enter your system prompt here (required):",
484
+ value=st.session_state.system_prompt,
485
+ height=150,
486
+ key="system_prompt_input"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487
  )
488
 
489
+ if st.sidebar.button("Submit Prompt"):
490
+ if system_prompt.strip():
491
+ st.session_state.system_prompt = system_prompt
492
+ SessionState.initialize() # Reset all states
493
+ st.rerun()
 
 
 
 
494
  else:
495
+ st.sidebar.error("Please enter a valid system prompt.")
496
+
497
+ return system_prompt.strip()
498
+
499
+ class ProductSelector:
500
+ """Handles product selection logic"""
501
+ @staticmethod
502
+ def handle_selection():
503
+ if st.session_state.similar_products:
504
+ # Create a container for the selection UI
505
+ selection_container = st.container()
506
+
507
+ with selection_container:
508
+ # Radio button for product selection
509
+ choice = st.radio(
510
+ "Select a product:",
511
+ st.session_state.similar_products + ["None of the above"],
512
+ key="product_choice"
513
  )
514
+
515
+ # Confirm button
516
+ confirm_clicked = st.button("Confirm Selection")
517
+
518
+ # Only process the selection when confirm is clicked
519
+ if confirm_clicked:
520
+ if choice != "None of the above":
521
+ st.session_state.product_selected = True
522
+ st.session_state.awaiting_selection = False
523
+ st.session_state.selected_product = choice
524
+ _, msg = chatbot_response("", choice, data_extractor_url,
525
+ st.session_state.system_prompt, extract_info=True)
526
+ st.session_state.messages.append({"role": "assistant", "content": msg})
527
+ else:
528
+ st.session_state.awaiting_selection = False
529
+ st.session_state.messages.append(
530
+ {"role": "assistant", "content": "Please provide the image URL of the product."}
531
+ )
532
+
533
+ st.session_state.similar_products = []
534
+ st.rerun()
535
+
536
+ # Prevent further chat input while awaiting selection
537
+ return True # Indicates selection is in progress
538
 
539
+ return False # Indicates no selection in progress
540
+
541
+ class ChatManager:
542
+ """Manages chat interactions and responses"""
543
+ @staticmethod
544
+ def process_response(user_input):
545
+ # First, check if we're awaiting selection
546
+ if st.session_state.awaiting_selection:
547
+ return None # Don't process new input while awaiting selection
 
548
 
549
+ if not st.session_state.product_selected:
550
+ if "http:/" not in user_input and "https:/" not in user_input:
551
+ return ChatManager._handle_product_name(user_input)
 
 
 
 
 
 
 
 
 
552
  else:
553
+ return ChatManager._handle_product_url(user_input)
 
 
 
 
554
  return "Next Product"
555
 
556
+ # ... (rest of ChatManager remains the same)
557
+
558
+ def main():
559
+ # Initialize session state
560
+ SessionState.initialize()
561
+
562
+ # Display title
563
+ st.title("ConsumeWise - Your Food Product Analysis Assistant")
564
+
565
+ # Handle system prompt
566
+ system_prompt = SystemPromptManager.render_sidebar()
567
+
568
+ if not system_prompt:
569
+ st.warning("⚠️ Please enter a system prompt in the sidebar before proceeding.")
570
+ st.chat_input("Enter your message:", disabled=True)
571
+ return
572
+
573
+ # Show welcome message
574
+ if not st.session_state.welcome_shown:
575
+ st.session_state.messages.append({
576
+ "role": "assistant",
577
+ "content": st.session_state.welcome_msg
578
+ })
579
+ st.session_state.welcome_shown = True
580
 
581
  # Display chat history
582
  for message in st.session_state.messages:
583
  with st.chat_message(message["role"]):
584
  st.markdown(message["content"])
585
 
586
+ # Handle product selection if awaiting
587
+ selection_in_progress = False
588
+ if st.session_state.awaiting_selection:
589
+ selection_in_progress = ProductSelector.handle_selection()
590
+
591
+ # Only show chat input if not awaiting selection
592
+ if not selection_in_progress:
593
+ user_input = st.chat_input("Enter your message:", key="user_input")
594
+ if user_input:
595
+ # Add user message to chat
596
+ st.session_state.messages.append({"role": "user", "content": user_input})
597
+ with st.chat_message("user"):
598
+ st.markdown(user_input)
599
+
600
+ # Process response
601
+ response = ChatManager.process_response(user_input)
602
+
603
+ if response == "Next Product":
604
+ SessionState.initialize() # Reset states for next product
605
+ st.session_state.welcome_msg = "What is the next product you would like me to analyze today?"
606
+ st.rerun()
607
+ elif response: # Only add response if it's not None
608
+ st.session_state.messages.append({"role": "assistant", "content": response})
609
+ with st.chat_message("assistant"):
610
+ st.markdown(response)
611
+ else:
612
+ # Disable chat input while selection is in progress
613
+ st.chat_input("Please confirm your selection above first...", disabled=True)
614
+
615
+ # Clear chat history button
616
+ if st.button("Clear Chat History"):
617
+ st.session_state.clear()
618
+ st.rerun()
619
 
620
+ if __name__ == "__main__":
621
+ main()