aradhyapavan commited on
Commit
7e0ac7c
·
verified ·
1 Parent(s): 540412a

Update app.py

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