File size: 11,605 Bytes
5b97c22 f5365fb 5b97c22 f5365fb 5b97c22 f5365fb 5b97c22 0f05b68 f5365fb 0f05b68 5b97c22 f5365fb 5b97c22 f5365fb 5b97c22 0f05b68 f5365fb 2d5ac34 f5365fb 5b97c22 f5365fb 5b97c22 f5365fb 5b97c22 f5365fb 5b97c22 f5365fb 5b97c22 f5365fb 0f05b68 f5365fb 0f05b68 f5365fb 0f05b68 5b97c22 f5365fb 5b97c22 f5365fb 5b97c22 0f05b68 f5365fb 5b97c22 f5365fb 0f05b68 5b97c22 f5365fb 058bc84 f5365fb 0f05b68 f5365fb 0f05b68 f5365fb 0f05b68 f5365fb 0f05b68 f5365fb 5b97c22 f5365fb 5b97c22 f5365fb 5b97c22 f5365fb 5b97c22 f5365fb 0f05b68 f5365fb 5b97c22 2d5ac34 f5365fb d2c31ee 2d5ac34 f5365fb d2c31ee f5365fb 2d5ac34 d2c31ee f5365fb d2c31ee f5365fb d2c31ee f5365fb 0f05b68 2d5ac34 f5365fb d2c31ee f5365fb 2d5ac34 f5365fb 2d5ac34 f5365fb 5b97c22 f5365fb 5b97c22 f5365fb |
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 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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 |
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit, join_room, leave_room
import os
import requests
import json
import uuid
from datetime import datetime
from dotenv import load_dotenv
import logging
from werkzeug.utils import secure_filename
import random
import asyncio
# Initialize Flask and configure core settings
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
# Initialize SocketIO with CORS support and logging
socketio = SocketIO(app, cors_allowed_origins="*", logger=True, engineio_logger=True, async_mode='eventlet')
# Load environment variables
load_dotenv()
MISTRAL_API_KEY = os.getenv('MISTRAL_API_KEY')
ELEVENLABS_API_KEY = os.getenv('ELEVENLABS_API_KEY')
# Configure logging with more detailed format
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class GameState:
"""Manages the state of all active game sessions."""
def __init__(self):
self.games = {}
self.cleanup_interval = 3600
def create_game(self):
"""Creates a new game session with proper initialization."""
try:
game_id = str(uuid.uuid4())
self.games[game_id] = {
'players': [],
'current_phase': 'setup',
'recordings': {},
'impostor': None,
'votes': {},
'question': None,
'impostor_answer': None,
'modified_recording': None,
'round_number': 1,
'start_time': datetime.now().isoformat(),
'completed_rounds': [],
'score': {'impostor_wins': 0, 'player_wins': 0},
'room': game_id # Add room for socket management
}
logger.info(f"Successfully created game with ID: {game_id}")
return game_id
except Exception as e:
logger.error(f"Error creating game: {str(e)}")
raise
def get_game(self, game_id):
"""Safely retrieves a game by ID."""
game = self.games.get(game_id)
if not game:
logger.error(f"Game not found: {game_id}")
raise ValueError("Game not found")
return game
def cleanup_inactive_games(self):
"""Removes inactive game sessions."""
current_time = datetime.now()
for game_id, game in list(self.games.items()):
start_time = datetime.fromisoformat(game['start_time'])
if (current_time - start_time).total_seconds() > 7200: # 2 hours
del self.games[game_id]
logger.info(f"Cleaned up inactive game: {game_id}")
# Initialize global game state
game_state = GameState()
@app.route('/')
def home():
"""Serves the main game page."""
return render_template('index.html')
@socketio.on('connect')
def handle_connect():
"""Handles client connection."""
logger.info(f"Client connected: {request.sid}")
emit('connection_success', {'status': 'connected'})
@socketio.on('disconnect')
def handle_disconnect():
"""Handles client disconnection."""
logger.info(f"Client disconnected: {request.sid}")
@socketio.on('create_game')
def handle_create_game():
"""Handles game creation request."""
try:
game_id = game_state.create_game()
join_room(game_id) # Create socket room for the game
logger.info(f"Created and joined game room: {game_id}")
emit('game_created', {
'gameId': game_id,
'status': 'success'
})
except Exception as e:
logger.error(f"Error in game creation: {str(e)}")
emit('game_error', {
'error': 'Failed to create game',
'details': str(e)
})
@socketio.on('join_game')
def handle_join_game(data):
"""Handles player joining a game."""
try:
game_id = data.get('gameId')
player_name = data.get('playerName')
if not game_id or not player_name:
raise ValueError("Missing game ID or player name")
game = game_state.get_game(game_id)
# Validate player count
if len(game['players']) >= 5:
raise ValueError("Game is full")
# Add player to game
player_id = len(game['players']) + 1
player = {
'id': player_id,
'name': player_name,
'socket_id': request.sid
}
game['players'].append(player)
# Join socket room
join_room(game_id)
logger.info(f"Player {player_name} (ID: {player_id}) joined game {game_id}")
# Broadcast to all players in the game
emit('player_joined', {
'playerId': player_id,
'playerName': player_name,
'status': 'success'
}, room=game_id)
except Exception as e:
error_msg = str(e)
logger.error(f"Error in handle_join_game: {error_msg}")
emit('game_error', {'error': error_msg})
@app.route('/api/start_game', methods=['POST'])
async def start_game():
"""Initializes a new game round."""
try:
data = request.get_json()
game_id = data.get('gameId')
if not game_id:
raise ValueError("Missing game ID")
game = game_state.get_game(game_id)
# Validate player count
if len(game['players']) < 3:
raise ValueError("Need at least 3 players to start")
# Generate question using Mistral AI
question = await generate_question()
game['question'] = question
game['current_phase'] = 'recording'
logger.info(f"Started game {game_id} with question: {question}")
# Notify all players in the game room
socketio.emit('round_started', {
'question': question
}, room=game_id)
return jsonify({
'status': 'success',
'question': question
})
except Exception as e:
error_msg = str(e)
logger.error(f"Error starting game: {error_msg}")
return jsonify({
'status': 'error',
'error': error_msg
}), 500
async def generate_question():
"""Generates an engaging question using Mistral AI."""
try:
headers = {
'Authorization': f'Bearer {MISTRAL_API_KEY}',
'Content-Type': 'application/json'
}
payload = {
'messages': [{
'role': 'user',
'content': '''Generate an engaging personal question for a social game.
The question should:
1. Encourage creative and unique responses
2. Be open-ended but not too philosophical
3. Be answerable in 15-30 seconds
4. Be appropriate for all ages
5. Spark interesting conversation
Generate only the question, without any additional text.'''
}]
}
response = requests.post(
'https://api.mistral.ai/v1/chat/completions',
headers=headers,
json=payload,
timeout=10
)
if response.status_code == 200:
question = response.json()['choices'][0]['message']['content'].strip()
logger.info(f"Generated question: {question}")
return question
logger.error(f"Mistral API error: {response.status_code}")
return random.choice([
"What's your favorite childhood memory?",
"What's the most interesting place you've ever visited?",
"What's a skill you'd love to master and why?",
"What's the best piece of advice you've ever received?"
])
except Exception as e:
logger.error(f"Error generating question: {str(e)}")
return "What is your favorite memory from your childhood?"
@app.route('/api/submit_recording', methods=['POST'])
async def submit_recording():
"""Handles voice recording submissions."""
try:
game_id = request.form.get('gameId')
player_id = request.form.get('playerId')
audio_file = request.files.get('audio')
if not all([game_id, player_id, audio_file]):
raise ValueError("Missing required data")
game = game_state.get_game(game_id)
# Save the recording
filename = secure_filename(f"recording_{game_id}_{player_id}.wav")
filepath = os.path.join('temp', filename)
audio_file.save(filepath)
game['recordings'][player_id] = filepath
logger.info(f"Saved recording for player {player_id} in game {game_id}")
# Notify all players about the new recording
socketio.emit('recording_submitted', {
'playerId': player_id,
'status': 'success'
}, room=game_id)
return jsonify({'status': 'success'})
except Exception as e:
error_msg = str(e)
logger.error(f"Error submitting recording: {error_msg}")
return jsonify({
'status': 'error',
'error': error_msg
}), 500
@socketio.on('submit_vote')
def handle_vote(data):
"""Processes player votes and determines round outcome."""
try:
game_id = data.get('gameId')
voter_id = data.get('voterId')
vote_for = data.get('voteFor')
if not all([game_id, voter_id, vote_for]):
raise ValueError("Missing vote data")
game = game_state.get_game(game_id)
game['votes'][voter_id] = vote_for
# Check if all players have voted
if len(game['votes']) == len(game['players']):
# Calculate results
votes_count = {}
for vote in game['votes'].values():
votes_count[vote] = votes_count.get(vote, 0) + 1
most_voted = max(votes_count.items(), key=lambda x: x[1])[0]
# Update scores
if most_voted == game['impostor']:
game['score']['player_wins'] += 1
result = 'players_win'
else:
game['score']['impostor_wins'] += 1
result = 'impostor_wins'
# Store round results
game['completed_rounds'].append({
'round_number': game['round_number'],
'impostor': game['impostor'],
'votes': game['votes'].copy(),
'most_voted': most_voted,
'result': result
})
# Emit results to all players
emit('round_result', {
'impostor': game['impostor'],
'most_voted': most_voted,
'votes': game['votes'],
'score': game['score'],
'result': result
}, room=game_id)
logger.info(f"Round completed for game {game_id}. Result: {result}")
except Exception as e:
error_msg = str(e)
logger.error(f"Error processing vote: {error_msg}")
emit('game_error', {'error': error_msg})
if __name__ == '__main__':
# Create temporary directory for recordings
os.makedirs('temp', exist_ok=True)
# Start the server
logger.info("Starting server...")
socketio.run(app, host='0.0.0.0', port=7860, debug=True) |