import sys from pathlib import Path from io import BytesIO import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import librosa import librosa.display from PIL import Image import torch import torch.nn as nn from torchvision import models, transforms # ===================================================== # PARAMÈTRES # ===================================================== TARGET_SR = 16_000 TARGET_DURATION = 4 MAX_SAMPLES = TARGET_SR * TARGET_DURATION N_FFT = 1024 HOP_LENGTH = 512 IMG_SIZE = 224 CLASS_NAMES = ["Angry", "Happy", "Neutral", "Sad"] MAX_FILE_SIZE_MB = 5 MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024 BASE_DIR = Path(__file__).resolve().parent BEST_MODEL_PATH = BASE_DIR / "best_efficientnet_raw.pth" # ===================================================== # DEVICE # ===================================================== def _get_device() -> torch.device: if torch.backends.mps.is_available(): return torch.device("mps") if torch.cuda.is_available(): return torch.device("cuda") return torch.device("cpu") # ===================================================== # CHARGEMENT DU MODÈLE # ===================================================== def _load_model(device: torch.device) -> nn.Module: model = models.efficientnet_b0(weights=None) in_features = model.classifier[1].in_features model.classifier[1] = nn.Linear(in_features, len(CLASS_NAMES)) model.load_state_dict(torch.load(BEST_MODEL_PATH, map_location=device)) model.to(device) model.eval() return model # ===================================================== # VÉRIFICATION DE LA TAILLE DU FICHIER # ===================================================== def _check_file_size(audio_path: str) -> None: file_path = Path(audio_path) if not file_path.exists(): raise ValueError(f"File not found: {audio_path}") file_size = file_path.stat().st_size if file_size > MAX_FILE_SIZE_BYTES: raise ValueError( f"File too large: {file_size / (1024*1024):.2f} MB. " f"Maximum allowed size: {MAX_FILE_SIZE_MB} MB" ) # ===================================================== # CONVERSION D'AUDIO ROBUSTE # ===================================================== def _convert_to_wav(audio_path: str) -> str: """Convertit n'importe quel fichier audio en WAV temporaire""" import subprocess output_path = str(Path(audio_path).with_suffix('.converted.wav')) try: # Utiliser ffmpeg pour convertir en WAV standard subprocess.run([ 'ffmpeg', '-y', '-i', audio_path, '-ar', str(TARGET_SR), '-ac', '1', '-sample_fmt', 's16', output_path ], capture_output=True, check=True) return output_path except Exception as e: raise ValueError(f"Conversion failed: {e}") def _load_audio(audio_path: str) -> np.ndarray: try: _check_file_size(audio_path) converted_path = None audio_path_to_use = audio_path # Essayer de charger directement avec librosa try: y, sr = librosa.load(audio_path_to_use, sr=TARGET_SR, duration=TARGET_DURATION) if y is not None and len(y) > 0: print(f"[DEBUG] Direct load success: {len(y)} samples") except Exception as e: print(f"[DEBUG] Direct load failed: {e}") # Essayer de convertir en WAV d'abord try: converted_path = _convert_to_wav(audio_path) y, sr = librosa.load(converted_path, sr=TARGET_SR, duration=TARGET_DURATION) print(f"[DEBUG] Converted load success: {len(y)} samples") except Exception as e2: raise ValueError(f"Cannot load audio: {e2}") if y is None or len(y) == 0: raise ValueError("Audio file is empty or unreadable") if len(y) < 100: raise ValueError("Audio file too short") # Normaliser la longueur if len(y) < MAX_SAMPLES: y = np.pad(y, (0, MAX_SAMPLES - len(y))) else: y = y[:MAX_SAMPLES] return y.astype(np.float32) except Exception as e: raise ValueError(f"Audio loading failed: {str(e)}") finally: # Nettoyer le fichier converti if converted_path and Path(converted_path).exists(): Path(converted_path).unlink() def _audio_to_pil(audio_path: str) -> Image.Image: y = _load_audio(audio_path) # Calculer le STFT stft = librosa.stft(y, n_fft=N_FFT, hop_length=HOP_LENGTH) db = librosa.amplitude_to_db(np.abs(stft), ref=np.max) # Créer la figure fig, ax = plt.subplots(figsize=(3, 3)) librosa.display.specshow(db, sr=TARGET_SR, hop_length=HOP_LENGTH, x_axis=None, y_axis=None, ax=ax) ax.axis("off") plt.tight_layout(pad=0) # Sauvegarder en mémoire buf = BytesIO() plt.savefig(buf, format="png", bbox_inches="tight", pad_inches=0, dpi=100) plt.close(fig) buf.seek(0) return Image.open(buf).convert("RGB") # ===================================================== # TRANSFORM # ===================================================== _transform = transforms.Compose([ transforms.Resize((IMG_SIZE, IMG_SIZE)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ]) # ===================================================== # FONCTION PRINCIPALE # ===================================================== def predict_emotion(audio_path: str, model: nn.Module = None, device: torch.device = None) -> dict: try: if device is None: device = _get_device() if model is None: model = _load_model(device) image = _audio_to_pil(audio_path) tensor = _transform(image).unsqueeze(0).to(device) with torch.no_grad(): logits = model(tensor) probs = torch.softmax(logits, dim=1)[0] idx = torch.argmax(probs).item() emotion = CLASS_NAMES[idx] confidence = round(probs[idx].item() * 100, 2) all_probabilities = { CLASS_NAMES[i]: round(probs[i].item() * 100, 2) for i in range(len(CLASS_NAMES)) } return { "emotion": emotion, "confidence": confidence, "all_probabilities": all_probabilities, } except Exception as e: return { "error": str(e), "emotion": None, "confidence": None, "all_probabilities": {}, } # ===================================================== # POINT D'ENTRÉE CLI # ===================================================== if __name__ == "__main__": if len(sys.argv) != 2: print("Usage : python predict.py ") sys.exit(1) audio_path = sys.argv[1] if not Path(audio_path).exists(): print(f"Fichier introuvable : {audio_path}") sys.exit(1) result = predict_emotion(audio_path) if "error" in result and result["error"]: print(f"Erreur : {result['error']}") else: print(f"Émotion détectée : {result['emotion']} (confiance: {result['confidence']}%)")