import streamlit as st # Configure page st.set_page_config( page_title="E-commerce Visual Assistant", page_icon="🛍️", layout="wide" ) from streamlit_chat import message import torch from PIL import Image import requests from io import BytesIO from model import initialize_models, load_data, chatbot, cleanup_resources # Helper functions def load_image_from_url(url): try: response = requests.get(url) img = Image.open(BytesIO(response.content)) return img except Exception as e: st.error(f"Error loading image from URL: {str(e)}") return None def initialize_assistant(): if not st.session_state.models_loaded: with st.spinner("Loading models and data..."): initialize_models() load_data() st.session_state.models_loaded = True st.success("Assistant is ready!") def display_chat_history(): for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) if "image" in message: st.image(message["image"], caption="Uploaded Image", width=200) if "display_images" in message: img_data = message["display_images"][0] st.image( img_data['image'], caption=f"{img_data['product_name']}\nPrice: ${img_data['price']:.2f}", width=350 ) def handle_user_input(prompt, uploaded_image): # Add user message st.session_state.messages.append({"role": "user", "content": prompt}) # Generate response with st.spinner("Processing your request..."): try: response = chatbot(prompt, image_input=uploaded_image) if isinstance(response, dict): assistant_message = { "role": "assistant", "content": response['text'] } if 'images' in response and response['images']: assistant_message["display_images"] = response['images'] st.session_state.messages.append(assistant_message) else: st.session_state.messages.append({ "role": "assistant", "content": response }) except Exception as e: st.error(f"Error: {str(e)}") st.session_state.messages.append({ "role": "assistant", "content": f"I encountered an error: {str(e)}" }) st.rerun() # Custom CSS for enhanced styling st.markdown(""" """, unsafe_allow_html=True) # Initialize session state if 'messages' not in st.session_state: st.session_state.messages = [] if 'models_loaded' not in st.session_state: st.session_state.models_loaded = False # Main title with enhanced styling st.markdown("