Bagus commited on
Commit
b21fb94
1 Parent(s): a0518cd

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +69 -0
README.md CHANGED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ~~~
2
+ # requirement packages
3
+ !pip install git+https://github.com/huggingface/datasets.git
4
+ !pip install git+https://github.com/huggingface/transformers.git
5
+ !pip install torchaudio
6
+ !pip install librosa
7
+ !git clone https://github.com/m3hrdadfi/soxan
8
+ cd soxan
9
+ ~~~
10
+
11
+
12
+ # prediction
13
+ ~~
14
+ import torch
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ import torchaudio
18
+ from transformers import AutoConfig, Wav2Vec2FeatureExtractor
19
+
20
+ import librosa
21
+ import IPython.display as ipd
22
+ import numpy as np
23
+ import pandas as pd
24
+ ~~~
25
+
26
+ ~~~
27
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
28
+ model_name_or_path = "Bagus/wav2vec2-xlsr-greek-speech-emotion-recognition"
29
+ config = AutoConfig.from_pretrained(model_name_or_path)
30
+ feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(model_name_or_path)
31
+ sampling_rate = feature_extractor.sampling_rate
32
+ model = Wav2Vec2ForSpeechClassification.from_pretrained(model_name_or_path).to(device)
33
+ ~~~
34
+
35
+ ~~~
36
+ def speech_file_to_array_fn(path, sampling_rate):
37
+ speech_array, _sampling_rate = torchaudio.load(path)
38
+ resampler = torchaudio.transforms.Resample(_sampling_rate)
39
+ speech = resampler(speech_array).squeeze().numpy()
40
+ return speech
41
+
42
+
43
+ def predict(path, sampling_rate):
44
+ speech = speech_file_to_array_fn(path, sampling_rate)
45
+ inputs = feature_extractor(speech, sampling_rate=sampling_rate, return_tensors="pt", padding=True)
46
+ inputs = {key: inputs[key].to(device) for key in inputs}
47
+
48
+ with torch.no_grad():
49
+ logits = model(**inputs).logits
50
+
51
+ scores = F.softmax(logits, dim=1).detach().cpu().numpy()[0]
52
+ outputs = [{"Emotion": config.id2label[i], "Score": f"{round(score * 100, 3):.1f}%"} for i, score in enumerate(scores)]
53
+ return outputs
54
+ ~~~
55
+
56
+ # prediction
57
+ ~~~
58
+ # path for a sample
59
+ path = '/data/jtes_v1.1/wav/f01/ang/f01_ang_01.wav'
60
+ outputs = predict(path, sampling_rate)
61
+ ~~~
62
+
63
+ ~~~
64
+ [{'Emotion': 'anger', 'Score': '98.3%'},
65
+ {'Emotion': 'disgust', 'Score': '0.0%'},
66
+ {'Emotion': 'fear', 'Score': '0.4%'},
67
+ {'Emotion': 'happiness', 'Score': '0.7%'},
68
+ {'Emotion': 'sadness', 'Score': '0.5%'}]
69
+ ~~~