Views
No views yet
1# requirement packages
2!pip install git+https://github.com/huggingface/datasets.git
3!pip install git+https://github.com/huggingface/transformers.git
4!pip install torchaudio
5!pip install librosa1import torch
2import torch.nn as nn
3import torch.nn.functional as F
4import torchaudio
5from transformers import AutoConfig, Wav2Vec2FeatureExtractor
6
7import librosa
8import IPython.display as ipd
9import numpy as np
10import pandas as pd1device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
2model_name_or_path = "m3hrdadfi/wav2vec2-xlsr-greek-speech-emotion-recognition"
3config = AutoConfig.from_pretrained(model_name_or_path)
4feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_name_or_path)
5sampling_rate = feature_extractor.sampling_rate
6model = Wav2Vec2ForSpeechClassification.from_pretrained(model_name_or_path).to(device)1def speech_file_to_array_fn(path, sampling_rate):
2 speech_array, _sampling_rate = torchaudio.load(path)
3 resampler = torchaudio.transforms.Resample(_sampling_rate)
4 speech = resampler(speech_array).squeeze().numpy()
5 return speech
6
7
8def predict(path, sampling_rate):
9 speech = speech_file_to_array_fn(path, sampling_rate)
10 inputs = feature_extractor(speech, sampling_rate=sampling_rate, return_tensors="pt", padding=True)
11 inputs = {key: inputs[key].to(device) for key in inputs}
12
13 with torch.no_grad():
14 logits = model(**inputs).logits
15
16 scores = F.softmax(logits, dim=1).detach().cpu().numpy()[0]
17 outputs = [{"Emotion": config.id2label[i], "Score": f"{round(score * 100, 3):.1f}%"} for i, score in enumerate(scores)]
18 return outputs1path = "/path/to/disgust.wav"
2outputs = predict(path, sampling_rate)1[
2{'Emotion': 'anger', 'Score': '0.0%'},
3{'Emotion': 'disgust', 'Score': '99.2%'},
4{'Emotion': 'fear', 'Score': '0.1%'},
5{'Emotion': 'happiness', 'Score': '0.3%'},
6{'Emotion': 'sadness', 'Score': '0.5%'}
7]| Emotions | precision | recall | f1-score | accuracy |
|---|---|---|---|---|
| anger | 0.92 | 1.00 | 0.96 | |
| disgust | 0.85 | 0.96 | 0.90 | |
| fear | 0.88 | 0.88 | 0.88 | |
| happiness | 0.94 | 0.71 | 0.81 | |
| sadness | 0.96 | 1.00 | 0.98 | |
| Overal | 0.91 |