Spaces:
Build error
Build error
| from gradio import Blocks, Chatbot, TextArea, Button, Row, Column, State | |
| import os | |
| import logging | |
| import traceback | |
| from dotenv import load_dotenv | |
| from src.chat import generate_response | |
| from src.database.init_db import init_db | |
| from src.database.db_connection import get_db_engine | |
| # Set up logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # Load environment variables from .env file (if exists) | |
| load_dotenv() | |
| # Initialize database | |
| def setup_database(): | |
| """Initialize the database at application startup""" | |
| logger.info("Initializing database...") | |
| try: | |
| if init_db(): | |
| logger.info("Database initialized successfully") | |
| return True | |
| else: | |
| logger.error("Failed to initialize database") | |
| return False | |
| except Exception as e: | |
| logger.error(f"Database initialization error: {str(e)}") | |
| logger.debug(traceback.format_exc()) | |
| return False | |
| # Update chat.py to support conversation history | |
| def update_chat_for_multi_turn(): | |
| """ | |
| Helper function to handle conversation state for multi-turn chat. | |
| This handles reconstruction of conversation context for the model. | |
| """ | |
| # This is handled in the respond function below | |
| pass | |
| # Gradio UI | |
| def create_ui(): | |
| with Blocks() as app: | |
| # Initialize conversation state | |
| chat_history = State([]) | |
| with Row(): | |
| with Column(scale=6): | |
| # Replace Textbox with Chatbot for multi-turn conversation | |
| chatbot = Chatbot( | |
| label="Business Interior Design Assistant", | |
| height=500, | |
| bubble_full_width=False, | |
| show_copy_button=True | |
| ) | |
| with Row(): | |
| user_input = TextArea( | |
| placeholder="Type your message here...", | |
| lines=2, | |
| label="Your Message", | |
| scale=5 | |
| ) | |
| submit_button = Button("Send", scale=1) | |
| # Add a clear chat button for better UX | |
| clear_button = Button("Clear Conversation") | |
| def respond(message, history, chat_state): | |
| """Process user input and update conversation with error handling""" | |
| if not message.strip(): | |
| return history, chat_state, "" | |
| try: | |
| # Generate response with conversation history context | |
| try: | |
| # Check if we need to reset Gemini chat context | |
| # Currently Gemini chat manages its own state, but | |
| # we're keeping our own history for resilience | |
| response = generate_response(message) | |
| # Update the visible chat UI | |
| history.append((message, response)) | |
| except Exception as e: | |
| error_msg = f"I apologize, but I encountered an error: {str(e)}" | |
| logger.error(f"Error generating response: {str(e)}") | |
| logger.debug(traceback.format_exc()) | |
| # Add error message to chat history | |
| history.append((message, error_msg)) | |
| return history, chat_state, "" | |
| except Exception as e: | |
| logger.error(f"Error in respond function: {str(e)}") | |
| logger.debug(traceback.format_exc()) | |
| error_msg = "I apologize, but something went wrong with our conversation system." | |
| history.append((message, error_msg)) | |
| return history, chat_state, "" | |
| def clear_chat(): | |
| """Clear the conversation history""" | |
| return [], [] | |
| # Connect UI components to functions | |
| submit_button.click( | |
| respond, | |
| inputs=[user_input, chatbot, chat_history], | |
| outputs=[chatbot, chat_history, user_input], | |
| api_name="chat" | |
| ) | |
| # Enable pressing Enter to send messages | |
| user_input.submit( | |
| respond, | |
| inputs=[user_input, chatbot, chat_history], | |
| outputs=[chatbot, chat_history, user_input] | |
| ) | |
| clear_button.click( | |
| clear_chat, | |
| outputs=[chatbot, chat_history] | |
| ) | |
| return app | |
| if __name__ == "__main__": | |
| # Ensure database is set up before starting the application | |
| db_setup_success = setup_database() | |
| # Check if database connection is working | |
| engine = get_db_engine() | |
| if engine is None: | |
| logger.error("Failed to connect to database. Please check your connection settings.") | |
| logger.warning("Application will continue with limited database functionality") | |
| else: | |
| logger.info("Successfully connected to database") | |
| # Launch the Gradio app | |
| app = create_ui() | |
| # Configure for different deployment environments | |
| server_name = os.getenv("SERVER_NAME", "127.0.0.1") | |
| server_port = int(os.getenv("PORT", 7860)) | |
| share = os.getenv("SHARE_APP", "true").lower() == "true" | |
| app.launch( | |
| server_name=server_name, | |
| server_port=server_port, | |
| share=share | |
| ) | |