Spaces:
Runtime error
Runtime error
Create new file
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
from transformers import AutoConfig, Wav2Vec2FeatureExtractor
|
| 4 |
+
from src.models import Wav2Vec2ForSpeechClassification #imported from https://github.com/m3hrdadfi/soxan
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import librosa
|
| 7 |
+
|
| 8 |
+
device = torch.device("cpu")
|
| 9 |
+
model_name_or_path = "harshit345/xlsr-wav2vec-speech-emotion-recognition"
|
| 10 |
+
config = AutoConfig.from_pretrained(model_name_or_path)
|
| 11 |
+
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_name_or_path)
|
| 12 |
+
sampling_rate = feature_extractor.sampling_rate
|
| 13 |
+
model = Wav2Vec2ForSpeechClassification.from_pretrained(model_name_or_path)
|
| 14 |
+
|
| 15 |
+
#load input file and resample to 16kHz
|
| 16 |
+
def load_data(path):
|
| 17 |
+
speech, sampling_rate = librosa.load(path)
|
| 18 |
+
if len(speech.shape) > 1:
|
| 19 |
+
speech = speech[:,0] + speech[:,1]
|
| 20 |
+
if sampling_rate != 16000:
|
| 21 |
+
speech = librosa.resample(speech, sampling_rate,16000)
|
| 22 |
+
return speech
|
| 23 |
+
|
| 24 |
+
#modified version of predict function from https://github.com/m3hrdadfi/soxan
|
| 25 |
+
def inference(path):
|
| 26 |
+
speech = load_data(path)
|
| 27 |
+
inputs = feature_extractor(speech, return_tensors="pt").input_values
|
| 28 |
+
with torch.no_grad():
|
| 29 |
+
logits = model(inputs).logits
|
| 30 |
+
scores = F.softmax(logits, dim=1).detach().cpu().numpy()[0]
|
| 31 |
+
outputs = {config.id2label[i]: float(round(score,2)) for i, score in enumerate(scores)}
|
| 32 |
+
return outputs
|
| 33 |
+
|
| 34 |
+
inputs = gr.inputs.Audio(label="Input Audio", type="filepath", source="microphone")
|
| 35 |
+
outputs = gr.outputs.Label(type="confidences", label = "Output Scores")
|
| 36 |
+
title = "Wav2Vec2 Speech Emotion Recognition"
|
| 37 |
+
description = "This is a demo of the Wav2Vec2 Speech Emotion Recognition model. Record an audio file and the top emotions inferred will be displayed."
|
| 38 |
+
examples = ['data/heart.wav', 'data/happy26.wav', 'data/jm24.wav', 'data/newton.wav', 'data/speeding.wav']
|
| 39 |
+
article = "<a href = 'https://github.com/m3hrdadfi/soxan'> Wav2Vec2 Speech Classification Github Repository"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
iface = gr.Interface(inference, inputs, outputs, title=title, description=description, article=article, theme="peach", examples=examples)
|
| 43 |
+
iface.launch(debug=True)
|