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 librosa!git clone https://github.com/SeaBenSea/HuBERT-SER.git1import sys
2sys.path.insert(1, './HuBERT-SER/')
3import torch
4import torch.nn as nn
5import torch.nn.functional as F
6import torchaudio
7from transformers import AutoConfig, Wav2Vec2FeatureExtractor
8from src.models import Wav2Vec2ForSpeechClassification, HubertForSpeechClassification1model_name_or_path = "SeaBenSea/hubert-large-turkish-speech-emotion-recognition"
2
3device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
4config = AutoConfig.from_pretrained(model_name_or_path)
5feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_name_or_path)
6sampling_rate = feature_extractor.sampling_rate
7
8model = HubertForSpeechClassification.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, 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
18 enumerate(scores)]
19 return outputs1path = "../dataset/TurEV/Angry/1157_kz_acik.wav"
2outputs = predict(path, sampling_rate)
3outputs1[
2 {'Emotion': 'Angry', 'Score': '99.8%'},
3 {'Emotion': 'Calm', 'Score': '0.0%'},
4 {'Emotion': 'Happy', 'Score': '0.1%'},
5 {'Emotion': 'Sad', 'Score': '0.1%'}
6]| Emotions | precision | recall | f1-score | accuracy |
|---|---|---|---|---|
| Angry | 0.97 | 0.99 | 0.98 | |
| Calm | 0.89 | 0.95 | 0.92 | |
| Happy | 0.98 | 0.93 | 0.95 | |
| Sad | 0.97 | 0.93 | 0.95 | |
| Overal | 0.95 |