import uuid import shutil import tempfile from pathlib import Path from io import BytesIO import numpy as np import subprocess from fastapi import FastAPI, File, UploadFile, HTTPException, WebSocket, WebSocketDisconnect from fastapi.responses import JSONResponse from fastapi.middleware.cors import CORSMiddleware from predict import predict_emotion, _get_device, _load_model, CLASS_NAMES # ===================================================== # CONFIG # ===================================================== ALLOWED_EXTENSIONS = {".wav", ".mp3", ".ogg", ".flac", ".m4a"} MAX_FILE_SIZE_MB = 5 MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024 UPLOAD_DIR = Path("tmp_uploads") UPLOAD_DIR.mkdir(exist_ok=True) # ===================================================== # CHARGEMENT DU MODÈLE (UNE SEULE FOIS) # ===================================================== device = _get_device() model = _load_model(device) print(f"[INFO] Modèle EfficientNet-B0 chargé sur {device}") print(f"[INFO] Classes : {CLASS_NAMES}") # ===================================================== # FASTAPI APP # ===================================================== app = FastAPI( title="Emotion Detection API", description="Détecte l'émotion dans un fichier audio : Angry | Happy | Neutral | Sad", version="1.0.0", ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # ===================================================== # HEALTH CHECK # ===================================================== @app.get("/", tags=["Health"]) def root(): return {"status": "ok", "message": "Emotion Detection API is running"} # ===================================================== # FONCTION POUR SAUVER L'AUDIO SANS SOUNDFILE # ===================================================== def save_audio_to_wav(filepath: str, audio_data: np.ndarray, sample_rate: int): """Sauvegarde un tableau numpy en fichier WAV sans soundfile""" try: # Méthode 1: utiliser scipy from scipy.io import wavfile # Convertir float32 [-1,1] en int16 audio_int16 = (audio_data * 32767).astype(np.int16) wavfile.write(filepath, sample_rate, audio_int16) return True except ImportError: try: # Méthode 2: utiliser subprocess avec ffmpeg raw_path = filepath + ".raw" audio_data.tofile(raw_path) subprocess.run([ 'ffmpeg', '-y', '-f', 'f32le', '-ar', str(sample_rate), '-ac', '1', '-i', raw_path, filepath ], capture_output=True, check=True) Path(raw_path).unlink() return True except: # Méthode 3: utiliser librosa (via fichier temporaire) import librosa # Librosa ne peut pas écrire directement, on utilise une alternative raise Exception("No audio writing method available") except Exception as e: raise Exception(f"Failed to save audio: {e}") # ===================================================== # PREDICTION ENDPOINT (fichier) # ===================================================== @app.post("/predict", tags=["Prediction"]) async def predict(audio_file: UploadFile = File(...)): if not audio_file.filename: raise HTTPException(status_code=400, detail="No file provided") suffix = Path(audio_file.filename).suffix.lower() if suffix not in ALLOWED_EXTENSIONS: raise HTTPException( status_code=415, detail=f"Format non supporté : '{suffix}'. " f"Formats acceptés : {sorted(ALLOWED_EXTENSIONS)}", ) tmp_path = UPLOAD_DIR / f"{uuid.uuid4().hex}{suffix}" try: with tmp_path.open("wb") as buffer: shutil.copyfileobj(audio_file.file, buffer) file_size = tmp_path.stat().st_size if file_size == 0: raise HTTPException(status_code=400, detail="Audio file is empty") if file_size < 4096: raise HTTPException(status_code=400, detail="Audio file is too small or empty") if file_size > MAX_FILE_SIZE_BYTES: raise HTTPException( status_code=413, detail=f"File too large: {file_size / (1024*1024):.2f} MB. Maximum allowed size: {MAX_FILE_SIZE_MB} MB" ) result = predict_emotion(str(tmp_path), model, device) if "error" in result and result["error"]: raise HTTPException(status_code=422, detail=f"Prediction failed: {result['error']}") return JSONResponse( status_code=200, content={ "success": True, "filename": audio_file.filename, "prediction": result["emotion"], "confidence": result["confidence"], "details": result["all_probabilities"], }, ) except HTTPException: raise except Exception as exc: raise HTTPException(status_code=500, detail=f"Internal server error: {str(exc)}") finally: if tmp_path.exists(): tmp_path.unlink() # ===================================================== # WEBSOCKET — PRÉDICTION EN TEMPS RÉEL # ===================================================== REALTIME_SR = 16_000 SEGMENT_SECONDS = 3 OVERLAP_SECONDS = 1 MIN_SAMPLES = REALTIME_SR * SEGMENT_SECONDS OVERLAP_SAMPLES = REALTIME_SR * OVERLAP_SECONDS @app.websocket("/ws/realtime") async def websocket_realtime(websocket: WebSocket): await websocket.accept() print("[WS] Client connecté") audio_buffer: list[float] = [] try: while True: message = await websocket.receive() # Texte : ping if message.get("type") == "websocket.receive" and message.get("text"): text = message["text"] if text == "ping": await websocket.send_json({"type": "pong"}) continue # Bytes : audio raw_bytes = message.get("bytes") if not raw_bytes: continue chunk = np.frombuffer(raw_bytes, dtype=np.float32) audio_buffer.extend(chunk.tolist()) if len(audio_buffer) < MIN_SAMPLES: progress = int(len(audio_buffer) / MIN_SAMPLES * 100) await websocket.send_json({"type": "buffering", "progress": progress}) continue window = np.array(audio_buffer[:MIN_SAMPLES], dtype=np.float32) audio_buffer = audio_buffer[MIN_SAMPLES - OVERLAP_SAMPLES:] # Créer un fichier temporaire with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp: tmp_path = tmp.name try: # ✅ Remplacer sf.write par notre fonction save_audio_to_wav(tmp_path, window, REALTIME_SR) # Vérification taille file_size = Path(tmp_path).stat().st_size if file_size > MAX_FILE_SIZE_BYTES: await websocket.send_json({"type": "error", "error": f"File too large: {file_size} bytes"}) continue # Utiliser le modèle déjà chargé result = predict_emotion(tmp_path, model, device) except Exception as e: await websocket.send_json({"type": "error", "error": str(e)}) continue finally: # Nettoyer le fichier temporaire if Path(tmp_path).exists(): Path(tmp_path).unlink() if result.get("error"): await websocket.send_json({"type": "error", "error": result["error"]}) else: await websocket.send_json({ "type": "prediction", "emotion": result["emotion"], "confidence": result["confidence"], "all_probabilities": result["all_probabilities"], }) except WebSocketDisconnect: print("[WS] Client déconnecté") except Exception as e: print(f"[WS] Erreur : {e}") try: await websocket.send_json({"type": "error", "error": str(e)}) except Exception: pass