Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import joblib
|
| 3 |
+
import librosa
|
| 4 |
+
import numpy as np
|
| 5 |
+
import soundfile as sf
|
| 6 |
+
import tempfile
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# --- Load Model ---
|
| 10 |
+
MODEL_PATH = "emotion_model_lgbm.pkl"
|
| 11 |
+
|
| 12 |
+
emotion_map = {
|
| 13 |
+
0: "neutral", 1: "calm", 2: "happy", 3: "sad",
|
| 14 |
+
4: "angry", 5: "fearful", 6: "disgust", 7: "surprised"
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
model = joblib.load(MODEL_PATH)
|
| 19 |
+
print("Model loaded successfully.")
|
| 20 |
+
except Exception as e:
|
| 21 |
+
print(f"Failed to load model: {e}")
|
| 22 |
+
model = None
|
| 23 |
+
|
| 24 |
+
# --- Feature Extraction (EXACTLY 100 FEATURES) ---
|
| 25 |
+
def extract_features(file_path):
|
| 26 |
+
try:
|
| 27 |
+
y, sr = librosa.load(file_path, sr=16000, mono=True)
|
| 28 |
+
if y.size < 1000:
|
| 29 |
+
raise ValueError("Audio signal is too short.")
|
| 30 |
+
|
| 31 |
+
# Extract only the number of features that match model input size (100)
|
| 32 |
+
mfccs = np.mean(librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40), axis=1) # 40
|
| 33 |
+
chroma = np.mean(librosa.feature.chroma_stft(y=y, sr=sr), axis=1) # 12
|
| 34 |
+
contrast = np.mean(librosa.feature.spectral_contrast(y=y, sr=sr), axis=1) # 7
|
| 35 |
+
mel = np.mean(librosa.feature.melspectrogram(y=y, sr=sr), axis=1) # usually 128 dims
|
| 36 |
+
mel_trimmed = mel[:41] # βοΈ Only keep first 41 to make total = 100
|
| 37 |
+
|
| 38 |
+
features = np.hstack([mfccs, chroma, contrast, mel_trimmed]) # 40+12+7+41 = 100 β
|
| 39 |
+
return features
|
| 40 |
+
except Exception as e:
|
| 41 |
+
raise RuntimeError(f"Feature extraction failed: {e}")
|
| 42 |
+
|
| 43 |
+
# --- Prediction Logic ---
|
| 44 |
+
def predict_emotion(audio):
|
| 45 |
+
if model is None:
|
| 46 |
+
return "Model not loaded."
|
| 47 |
+
|
| 48 |
+
if audio is None:
|
| 49 |
+
return "No audio input received."
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
sr, y = audio
|
| 53 |
+
|
| 54 |
+
# Write audio to temp wav file
|
| 55 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpfile:
|
| 56 |
+
sf.write(tmpfile.name, y, sr)
|
| 57 |
+
features = extract_features(tmpfile.name)
|
| 58 |
+
os.remove(tmpfile.name)
|
| 59 |
+
|
| 60 |
+
print(f"π Feature shape: {features.shape}") # should be (100,)
|
| 61 |
+
if features.shape[0] != model.n_features_in_:
|
| 62 |
+
return (
|
| 63 |
+
f"Feature count mismatch: model expects {model.n_features_in_} features, "
|
| 64 |
+
f"but got {features.shape[0]}"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Reshape for prediction
|
| 68 |
+
features = features.reshape(1, -1)
|
| 69 |
+
pred = model.predict(features)[0]
|
| 70 |
+
print("Prediction:", pred)
|
| 71 |
+
|
| 72 |
+
emotion = emotion_map.get(int(pred), "unknown")
|
| 73 |
+
return f"π§ Predicted Emotion: {emotion.capitalize()}"
|
| 74 |
+
|
| 75 |
+
except Exception as e:
|
| 76 |
+
print("Exception during prediction:", str(e))
|
| 77 |
+
return f"Error during prediction: {str(e)}"
|
| 78 |
+
|
| 79 |
+
# --- Gradio UI ---
|
| 80 |
+
demo = gr.Interface(
|
| 81 |
+
fn=predict_emotion,
|
| 82 |
+
inputs=gr.Audio(type="numpy", label="π Upload Your Voice (WAV)"),
|
| 83 |
+
outputs=gr.Textbox(label="π§ Detected Emotion"),
|
| 84 |
+
title="π€ Emotion Recognition from Audio",
|
| 85 |
+
description="Upload a short WAV file (3β10 sec) and this model will analyze and predict the speaker's emotion.",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
demo.launch()
|