File size: 3,695 Bytes
030e91f
 
 
0400359
030e91f
5e04213
 
 
030e91f
a1e1c0f
a0b8502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
030e91f
 
8efefae
 
 
 
 
 
 
b0c3b86
8efefae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56f5338
8efefae
b0c3b86
 
8efefae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
030e91f
 
da7437d
 
 
 
 
 
 
 
 
41e6fdd
da7437d
0b6fac4
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
---
language: ru
tags:
- audio-classification
- audio
- emotion
- emotion-recognition
- emotion-classification
- speech
license: mit
datasets:
- Aniemore/resd
model-index:
- name: XLS-R Wav2Vec2 For Russian Speech Emotion Classification by Nikita Davidchuk
  results:
  - task:
      name: Audio Emotion Recognition
      type: audio-emotion-recognition
    dataset:
      name: Russian Emotional Speech Dialogs
      type: Aniemore/resd
      args: ru
    metrics:
    - name: accuracy
      type: accuracy
      value: 72%
---

# Prepare and importing

```python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
from transformers import AutoConfig, AutoModel, Wav2Vec2FeatureExtractor

import librosa
import numpy as np


def speech_file_to_array_fn(path, sampling_rate):
    speech_array, _sampling_rate = torchaudio.load(path)
    resampler = torchaudio.transforms.Resample(_sampling_rate)
    speech = resampler(speech_array).squeeze().numpy()
    return speech


def predict(path, sampling_rate):
    speech = speech_file_to_array_fn(path, sampling_rate)
    inputs = feature_extractor(speech, sampling_rate=sampling_rate, return_tensors="pt", padding=True)
    inputs = {key: inputs[key].to(device) for key in inputs}

    with torch.no_grad():
        logits = model_(**inputs).logits

    scores = F.softmax(logits, dim=1).detach().cpu().numpy()[0]
    outputs = [{"Emotion": config.id2label[i], "Score": f"{round(score * 100, 3):.1f}%"} for i, score in enumerate(scores)]
    return outputs
```

# Evoking:

```python
TRUST = True

config = AutoConfig.from_pretrained('Aniemore/wav2vec2-xlsr-53-russian-emotion-recognition', trust_remote_code=TRUST)
model_ = AutoModel.from_pretrained("Aniemore/wav2vec2-xlsr-53-russian-emotion-recognition", trust_remote_code=TRUST)
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("Aniemore/wav2vec2-xlsr-53-russian-emotion-recognition")

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_.to(device)
```

# Use case

```python
result = predict("/path/to/russian_audio_speech.wav", 16000)
print(result)
```

```python
# outputs
[{'Emotion': 'anger', 'Score': '0.0%'},
 {'Emotion': 'disgust', 'Score': '100.0%'},
 {'Emotion': 'enthusiasm', 'Score': '0.0%'},
 {'Emotion': 'fear', 'Score': '0.0%'},
 {'Emotion': 'happiness', 'Score': '0.0%'},
 {'Emotion': 'neutral', 'Score': '0.0%'},
 {'Emotion': 'sadness', 'Score': '0.0%'}]
```

# Results

|              | precision | recall | f1-score | support |
|--------------|-----------|--------|----------|---------|
| anger        | 0.97      | 0.86   | 0.92     | 44      |
| disgust      | 0.71      | 0.78   | 0.74     | 37      |
| enthusiasm   | 0.51      | 0.80   | 0.62     | 40      |
| fear         | 0.80      | 0.62   | 0.70     | 45      |
| happiness    | 0.66      | 0.70   | 0.68     | 44      |
| neutral      | 0.81      | 0.66   | 0.72     | 38      |
| sadness      | 0.79      | 0.59   | 0.68     | 32      |
| accuracy     |           |        | 0.72     | 280     |
| macro avg    | 0.75      | 0.72   | 0.72     | 280     |
| weighted avg | 0.75      | 0.72   | 0.73     | 280     |

# Citations
```
@misc{Aniemore,
  author = {Артем Аментес, Илья Лубенец, Никита Давидчук},
  title = {Открытая библиотека искусственного интеллекта для анализа и выявления эмоциональных оттенков речи человека},
  year = {2022},
  publisher = {Hugging Face},
  journal = {Hugging Face Hub},
  howpublished = {\url{https://huggingface.com/aniemore/Aniemore}},
  email = {[email protected]}
}
```