Spaces:
Build error
Build error
File size: 5,455 Bytes
738ecfc 6204fe3 7795c0b 738ecfc 6204fe3 738ecfc 7795c0b bde6f92 6204fe3 6d097e8 7795c0b 738ecfc 797d8d8 6204fe3 738ecfc 6204fe3 738ecfc 6204fe3 738ecfc 6204fe3 738ecfc 6204fe3 7795c0b 6204fe3 7795c0b 738ecfc 7795c0b 738ecfc 7795c0b 6204fe3 738ecfc 7795c0b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | 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
)
|