Spaces:
Sleeping
Sleeping
File size: 3,029 Bytes
6b8ff54 | 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 | 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()
|