import gradio as gr import joblib import librosa import numpy as np import soundfile as sf import tempfile import os # --- Load Model --- MODEL_PATH = "emotion_model_lgbm.pkl" emotion_map = { 0: "neutral", 1: "calm", 2: "happy", 3: "sad", 4: "angry", 5: "fearful", 6: "disgust", 7: "surprised" } try: model = joblib.load(MODEL_PATH) print("Model loaded successfully.") except Exception as e: print(f"Failed to load model: {e}") model = None # --- Feature Extraction (EXACTLY 100 FEATURES) --- def extract_features(file_path): try: y, sr = librosa.load(file_path, sr=16000, mono=True) if y.size < 1000: raise ValueError("Audio signal is too short.") # Extract only the number of features that match model input size (100) mfccs = np.mean(librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40), axis=1) # 40 chroma = np.mean(librosa.feature.chroma_stft(y=y, sr=sr), axis=1) # 12 contrast = np.mean(librosa.feature.spectral_contrast(y=y, sr=sr), axis=1) # 7 mel = np.mean(librosa.feature.melspectrogram(y=y, sr=sr), axis=1) # usually 128 dims mel_trimmed = mel[:41] # ✂️ Only keep first 41 to make total = 100 features = np.hstack([mfccs, chroma, contrast, mel_trimmed]) # 40+12+7+41 = 100 ✅ return features except Exception as e: raise RuntimeError(f"Feature extraction failed: {e}") # --- Prediction Logic --- def predict_emotion(audio): if model is None: return "Model not loaded." if audio is None: return "No audio input received." try: sr, y = audio # Write audio to temp wav file with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpfile: sf.write(tmpfile.name, y, sr) features = extract_features(tmpfile.name) os.remove(tmpfile.name) print(f"📊 Feature shape: {features.shape}") # should be (100,) if features.shape[0] != model.n_features_in_: return ( f"Feature count mismatch: model expects {model.n_features_in_} features, " f"but got {features.shape[0]}" ) # Reshape for prediction features = features.reshape(1, -1) pred = model.predict(features)[0] print("Prediction:", pred) emotion = emotion_map.get(int(pred), "unknown") return f"🎧 Predicted Emotion: {emotion.capitalize()}" except Exception as e: print("Exception during prediction:", str(e)) return f"Error during prediction: {str(e)}" # --- Gradio UI --- demo = gr.Interface( fn=predict_emotion, inputs=gr.Audio(type="numpy", label="🎙 Upload Your Voice (WAV)"), outputs=gr.Textbox(label="🧠 Detected Emotion"), title="🎤 Emotion Recognition from Audio", description="Upload a short WAV file (3–10 sec) and this model will analyze and predict the speaker's emotion.", ) if __name__ == "__main__": demo.launch()