Update app.py
Browse files
app.py
CHANGED
|
@@ -1,257 +1,262 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Multi-Personality Chat Bot Flask Application
|
| 4 |
-
A hackathon project featuring 10 distinct AI personality types with Google AI integration.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import os
|
| 8 |
-
import logging
|
| 9 |
-
|
| 10 |
-
from
|
| 11 |
-
from
|
| 12 |
-
import
|
| 13 |
-
import
|
| 14 |
-
import
|
| 15 |
-
import
|
| 16 |
-
|
| 17 |
-
from modules.
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
logging
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
# Initialize
|
| 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 |
-
return render_template('
|
| 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 |
-
@socketio.on('
|
| 98 |
-
def
|
| 99 |
-
"""Handle
|
| 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 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Multi-Personality Chat Bot Flask Application
|
| 4 |
+
A hackathon project featuring 10 distinct AI personality types with Google AI integration.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import logging
|
| 9 |
+
import builtins
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from flask import Flask, render_template, request, jsonify, session
|
| 12 |
+
from flask_socketio import SocketIO, emit, join_room, leave_room
|
| 13 |
+
import google.generativeai as genai
|
| 14 |
+
import sqlite3
|
| 15 |
+
import json
|
| 16 |
+
import secrets
|
| 17 |
+
from modules.simple_personality_engine import PersonalityEngine
|
| 18 |
+
from modules.database import ChatDatabase
|
| 19 |
+
|
| 20 |
+
# Configure logging (reduced verbosity)
|
| 21 |
+
logging.basicConfig(level=logging.WARNING)
|
| 22 |
+
logger = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
# Optionally silence print output when QUIET=1 (default)
|
| 25 |
+
if os.getenv("QUIET", "1") == "1":
|
| 26 |
+
builtins.print = lambda *args, **kwargs: None
|
| 27 |
+
|
| 28 |
+
# Initialize Flask app
|
| 29 |
+
app = Flask(__name__)
|
| 30 |
+
# Use env var if provided; otherwise generate a secure random key at startup
|
| 31 |
+
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', secrets.token_hex(32))
|
| 32 |
+
|
| 33 |
+
# Initialize SocketIO (quiet)
|
| 34 |
+
socketio = SocketIO(app, cors_allowed_origins="*", logger=False, engineio_logger=False)
|
| 35 |
+
|
| 36 |
+
# Configure Google AI strictly via environment variable (no bundled default key)
|
| 37 |
+
GOOGLE_AI_API_KEY = os.getenv("GOOGLE_AI_API_KEY")
|
| 38 |
+
if GOOGLE_AI_API_KEY:
|
| 39 |
+
genai.configure(api_key=GOOGLE_AI_API_KEY)
|
| 40 |
+
logger.info("Google AI configured using environment variable")
|
| 41 |
+
else:
|
| 42 |
+
logger.warning("GOOGLE_AI_API_KEY not set. AI features will be unavailable.")
|
| 43 |
+
|
| 44 |
+
# Initialize components
|
| 45 |
+
personality_engine = PersonalityEngine()
|
| 46 |
+
chat_db = ChatDatabase()
|
| 47 |
+
|
| 48 |
+
@app.route('/')
|
| 49 |
+
def index():
|
| 50 |
+
"""Main personality selection page"""
|
| 51 |
+
personalities = personality_engine.get_all_personalities()
|
| 52 |
+
return render_template('index.html', personalities=personalities)
|
| 53 |
+
|
| 54 |
+
@app.route('/chat/<personality_type>')
|
| 55 |
+
def chat_personality(personality_type):
|
| 56 |
+
"""Individual personality chat interface"""
|
| 57 |
+
try:
|
| 58 |
+
personality_config = personality_engine.get_personality_config(personality_type)
|
| 59 |
+
if not personality_config:
|
| 60 |
+
return render_template('error.html',
|
| 61 |
+
error_message=f"Personality type '{personality_type}' not found"), 404
|
| 62 |
+
|
| 63 |
+
return render_template('chat_personality.html',
|
| 64 |
+
personality_type=personality_type,
|
| 65 |
+
personality_config=personality_config)
|
| 66 |
+
except Exception as e:
|
| 67 |
+
logger.error(f"Error loading personality {personality_type}: {str(e)}")
|
| 68 |
+
return render_template('error.html',
|
| 69 |
+
error_message="Failed to load personality configuration"), 500
|
| 70 |
+
|
| 71 |
+
@app.route('/test-ai')
|
| 72 |
+
def test_ai():
|
| 73 |
+
"""Test endpoint for Google AI connectivity"""
|
| 74 |
+
try:
|
| 75 |
+
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 76 |
+
response = model.generate_content("Say hello in a sarcastic way")
|
| 77 |
+
return jsonify({
|
| 78 |
+
'success': True,
|
| 79 |
+
'response': response.text,
|
| 80 |
+
'message': 'Google AI is working correctly!'
|
| 81 |
+
})
|
| 82 |
+
except Exception as e:
|
| 83 |
+
logger.error(f"AI test failed: {str(e)}")
|
| 84 |
+
return jsonify({
|
| 85 |
+
'success': False,
|
| 86 |
+
'error': str(e),
|
| 87 |
+
'message': 'Google AI connection failed'
|
| 88 |
+
}), 500
|
| 89 |
+
|
| 90 |
+
# Socket.IO Event Handlers
|
| 91 |
+
@socketio.on('connect')
|
| 92 |
+
def handle_connect():
|
| 93 |
+
"""Handle client connection"""
|
| 94 |
+
logger.info(f'Client connected: {request.sid}')
|
| 95 |
+
emit('status', {'message': 'Connected to Multi-Personality Bot!'})
|
| 96 |
+
|
| 97 |
+
@socketio.on('disconnect')
|
| 98 |
+
def handle_disconnect():
|
| 99 |
+
"""Handle client disconnection"""
|
| 100 |
+
logger.info(f'Client disconnected: {request.sid}')
|
| 101 |
+
|
| 102 |
+
@socketio.on('join_personality_room')
|
| 103 |
+
def handle_join_personality_room(data):
|
| 104 |
+
"""Handle joining a personality room"""
|
| 105 |
+
personality_type = data.get('personality')
|
| 106 |
+
username = data.get('username', 'Anonymous')
|
| 107 |
+
room = f"personality_{personality_type}"
|
| 108 |
+
join_room(room)
|
| 109 |
+
|
| 110 |
+
personality_config = personality_engine.get_personality_config(personality_type)
|
| 111 |
+
if personality_config:
|
| 112 |
+
emit('personality_ready', {
|
| 113 |
+
'personality': personality_type,
|
| 114 |
+
'config': personality_config,
|
| 115 |
+
'welcome_message': personality_config.get('welcome', 'Hello!')
|
| 116 |
+
})
|
| 117 |
+
|
| 118 |
+
@socketio.on('join_personality')
|
| 119 |
+
def handle_join_personality(data):
|
| 120 |
+
"""Handle joining a personality room (backup handler)"""
|
| 121 |
+
# Redirect to join_personality_room handler
|
| 122 |
+
handle_join_personality_room(data)
|
| 123 |
+
|
| 124 |
+
@socketio.on('personality_message')
|
| 125 |
+
def handle_personality_message(data):
|
| 126 |
+
"""Handle incoming personality chat messages"""
|
| 127 |
+
try:
|
| 128 |
+
user_message = data.get('message', '').strip()
|
| 129 |
+
personality_type = data.get('personality', 'sarcastic')
|
| 130 |
+
username = data.get('username', 'Anonymous')
|
| 131 |
+
|
| 132 |
+
if not user_message:
|
| 133 |
+
emit('error', {'message': 'Please enter a message'})
|
| 134 |
+
return
|
| 135 |
+
|
| 136 |
+
# Log and persist user message
|
| 137 |
+
logger.info(f"User message ({personality_type}): {user_message}")
|
| 138 |
+
try:
|
| 139 |
+
chat_db.save_message(username, user_message, personality_type, 'user')
|
| 140 |
+
except Exception as dberr:
|
| 141 |
+
logger.warning(f"DB save user message failed: {dberr}")
|
| 142 |
+
|
| 143 |
+
# Send typing indicator
|
| 144 |
+
emit('bot_typing', {'personality': personality_type})
|
| 145 |
+
|
| 146 |
+
# Generate AI response
|
| 147 |
+
try:
|
| 148 |
+
bot_response = personality_engine.generate_response(
|
| 149 |
+
message=user_message,
|
| 150 |
+
personality_type=personality_type,
|
| 151 |
+
context={}
|
| 152 |
+
)
|
| 153 |
+
logger.info(f"AI response ({personality_type}): {bot_response[:120]}...")
|
| 154 |
+
|
| 155 |
+
# Send response to client
|
| 156 |
+
emit('personality_response', {
|
| 157 |
+
'message': bot_response,
|
| 158 |
+
'personality': personality_type,
|
| 159 |
+
'timestamp': datetime.now().isoformat()
|
| 160 |
+
})
|
| 161 |
+
# persist bot message
|
| 162 |
+
try:
|
| 163 |
+
chat_db.save_message(username, bot_response, personality_type, 'bot')
|
| 164 |
+
except Exception as dberr2:
|
| 165 |
+
logger.warning(f"DB save bot message failed: {dberr2}")
|
| 166 |
+
|
| 167 |
+
except Exception as ai_error:
|
| 168 |
+
logger.error(f"AI generation error: {str(ai_error)}")
|
| 169 |
+
error_response = "I'm having difficulty connecting to my AI brain right now. Please try again in a moment! 🤖"
|
| 170 |
+
|
| 171 |
+
emit('personality_response', {
|
| 172 |
+
'message': error_response,
|
| 173 |
+
'personality': personality_type,
|
| 174 |
+
'timestamp': datetime.now().isoformat(),
|
| 175 |
+
'error': True
|
| 176 |
+
})
|
| 177 |
+
|
| 178 |
+
except Exception as e:
|
| 179 |
+
logger.error(f"Message handling error: {str(e)}")
|
| 180 |
+
emit('error', {'message': 'Failed to process message. Please try again.'})
|
| 181 |
+
|
| 182 |
+
@socketio.on('send_message')
|
| 183 |
+
def handle_send_message(data):
|
| 184 |
+
"""Handle send_message events (backup handler)"""
|
| 185 |
+
# Redirect to personality_message handler
|
| 186 |
+
handle_personality_message(data)
|
| 187 |
+
|
| 188 |
+
@socketio.on('get_chat_history')
|
| 189 |
+
def handle_get_chat_history(data):
|
| 190 |
+
"""Retrieve chat history for a personality"""
|
| 191 |
+
try:
|
| 192 |
+
personality_type = data.get('personality', 'sarcastic')
|
| 193 |
+
limit = data.get('limit', 50)
|
| 194 |
+
|
| 195 |
+
history = chat_db.get_recent_messages(personality_type, limit)
|
| 196 |
+
emit('chat_history', {'messages': history})
|
| 197 |
+
|
| 198 |
+
except Exception as e:
|
| 199 |
+
logger.error(f"Chat history error: {str(e)}")
|
| 200 |
+
emit('error', {'message': 'Failed to load chat history'})
|
| 201 |
+
|
| 202 |
+
@socketio.on('clear_chat')
|
| 203 |
+
def handle_clear_chat(data):
|
| 204 |
+
"""Clear chat history for a personality"""
|
| 205 |
+
try:
|
| 206 |
+
personality_type = data.get('personality', 'sarcastic')
|
| 207 |
+
username = data.get('username', 'Anonymous')
|
| 208 |
+
|
| 209 |
+
# Note: In a production app, you might want to soft-delete or archive
|
| 210 |
+
success = chat_db.clear_personality_chat(personality_type, username)
|
| 211 |
+
|
| 212 |
+
if success:
|
| 213 |
+
emit('chat_cleared', {'personality': personality_type})
|
| 214 |
+
else:
|
| 215 |
+
emit('error', {'message': 'Failed to clear chat history'})
|
| 216 |
+
|
| 217 |
+
except Exception as e:
|
| 218 |
+
logger.error(f"Clear chat error: {str(e)}")
|
| 219 |
+
emit('error', {'message': 'Failed to clear chat history'})
|
| 220 |
+
|
| 221 |
+
# Error Handlers
|
| 222 |
+
@app.errorhandler(404)
|
| 223 |
+
def not_found_error(error):
|
| 224 |
+
"""Handle 404 errors"""
|
| 225 |
+
return render_template('error.html',
|
| 226 |
+
error_message="Page not found"), 404
|
| 227 |
+
|
| 228 |
+
@app.errorhandler(500)
|
| 229 |
+
def internal_error(error):
|
| 230 |
+
"""Handle 500 errors"""
|
| 231 |
+
return render_template('error.html',
|
| 232 |
+
error_message="Internal server error"), 500
|
| 233 |
+
|
| 234 |
+
if __name__ == '__main__':
|
| 235 |
+
try:
|
| 236 |
+
# Initialize database
|
| 237 |
+
chat_db.initialize_database()
|
| 238 |
+
|
| 239 |
+
# Test Google AI connection
|
| 240 |
+
logger.info("Testing Google AI connection...")
|
| 241 |
+
api_test_success = personality_engine.test_api_connection()
|
| 242 |
+
if api_test_success:
|
| 243 |
+
logger.info("Google AI connection test successful!")
|
| 244 |
+
else:
|
| 245 |
+
logger.warning("Google AI connection test failed - app will still start but may have issues")
|
| 246 |
+
|
| 247 |
+
# Start the application
|
| 248 |
+
logger.info("Starting Multi-Personality Chat Bot...")
|
| 249 |
+
logger.info("Available personalities: " + ", ".join(personality_engine.get_personality_list()))
|
| 250 |
+
|
| 251 |
+
# Respect PORT env for platforms like Hugging Face Spaces
|
| 252 |
+
port = int(os.getenv("PORT", os.getenv("HF_PORT", 7860)))
|
| 253 |
+
socketio.run(app,
|
| 254 |
+
host='0.0.0.0',
|
| 255 |
+
port=port,
|
| 256 |
+
debug=False,
|
| 257 |
+
allow_unsafe_werkzeug=True)
|
| 258 |
+
|
| 259 |
+
except Exception as e:
|
| 260 |
+
logger.error(f"Failed to start application: {str(e)}")
|
| 261 |
+
print(f"❌ Startup Error: {str(e)}")
|
| 262 |
+
exit(1)
|