HaryaniAnjali commited on
Commit
5d7352c
·
verified ·
1 Parent(s): 5e04a20

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -0
app.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline, AutoFeatureExtractor, AutoModelForAudioClassification
3
+ import torch
4
+ import librosa
5
+ import numpy as np
6
+
7
+ # Load model and feature extractor
8
+ model_id = "your-username/speech-emotion-recognition-model"
9
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
10
+ model = AutoModelForAudioClassification.from_pretrained(model_id)
11
+
12
+ # Define emotions
13
+ emotions = ["neutral", "happy", "sad", "angry", "fearful", "disgust", "surprised"]
14
+
15
+ def predict_emotion(audio_path):
16
+ # Load audio
17
+ audio, sampling_rate = librosa.load(audio_path, sr=16000)
18
+
19
+ # Process through feature extractor
20
+ inputs = feature_extractor(audio, sampling_rate=sampling_rate, return_tensors="pt", padding=True)
21
+
22
+ # Get prediction
23
+ with torch.no_grad():
24
+ outputs = model(**inputs)
25
+ probs = torch.nn.functional.softmax(outputs.logits, dim=1)
26
+ predicted_class_id = torch.argmax(probs, dim=1).item()
27
+ predicted_label = emotions[predicted_class_id]
28
+ confidence = probs[0][predicted_class_id].item()
29
+
30
+ # Return result
31
+ result = {emotion: float(probs[0][i].item()) for i, emotion in enumerate(emotions)}
32
+ return result
33
+
34
+ # Create Gradio interface
35
+ demo = gr.Interface(
36
+ fn=predict_emotion,
37
+ inputs=gr.Audio(source="microphone", type="filepath"),
38
+ outputs=gr.Label(num_top_classes=7),
39
+ title="Speech Emotion Recognition",
40
+ description="Upload audio or record your voice to identify the emotion. This model can detect neutral, happy, sad, angry, fearful, disgust, and surprised emotions."
41
+ )
42
+
43
+ demo.launch()