File size: 9,795 Bytes
55efe31
 
 
 
11bca8b
55efe31
 
 
 
 
 
 
11bca8b
55efe31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcfdc88
55efe31
 
 
 
 
 
 
 
 
98eef82
55efe31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fed5a6
 
 
 
55efe31
 
 
 
 
 
98eef82
55efe31
 
 
 
 
 
 
 
98eef82
 
7fed5a6
 
55efe31
bcfdc88
 
55efe31
489c772
 
55efe31
 
 
 
 
98eef82
 
 
 
 
 
55efe31
 
 
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
7fed5a6
55efe31
 
 
 
 
 
 
 
 
 
 
 
 
 
98eef82
55efe31
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
---
language: ru
datasets:
- SberDevices/Golos
- common_voice
metrics:
- wer
- cer
tags:
- audio
- automatic-speech-recognition
- speech
- common_voice
- SberDevices/Golos
license: apache-2.0
model-index:
- name: XLSR Wav2Vec2 Russian with Language Model by Ivan Bondarenko
  results:
  - task:
      name: Speech Recognition
      type: automatic-speech-recognition
    dataset:
      name: Sberdevices Golos (crowd)
      type: SberDevices/Golos
      args: ru
    metrics:
       - name: Test WER
         type: wer
         value: 7.42
       - name: Test CER
         type: cer
         value: 1.85
  - task:
      name: Speech Recognition
      type: automatic-speech-recognition
    dataset:
      name: Sberdevices Golos (farfield)
      type: SberDevices/Golos
      args: ru
    metrics:
       - name: Test WER
         type: wer
         value: 16.08
       - name: Test CER
         type: cer
         value: 5.27
  - task:
      name: Automatic Speech Recognition
      type: automatic-speech-recognition
    dataset:
      name: Common Voice ru
      type: common_voice
      args: ru
    metrics:
    - name: Test WER
      type: wer
      value: 29.75
    - name: Test CER
      type: cer
      value: 8.15
---
# Wav2Vec2-Large-Ru-Golos-With-LM

Fine-tuned [facebook/wav2vec2-large-xlsr-53](https://huggingface.co/facebook/wav2vec2-large-xlsr-53) on Russian using the [Sberdevices Golos](https://huggingface.co/datasets/SberDevices/Golos). The language model is based on [the Russian National Corpus](https://ruscorpora.ru/), and this model includes unigrams, bigrams and trigrams.

## Usage

When using this model, make sure that your speech input is sampled at 16kHz.

You can use this model by writing your own inference script:

```python
import os
import warnings

import librosa
import nltk
import numpy as np

import torch
from datasets import load_dataset
from transformers import Wav2Vec2ForCTC, Wav2Vec2ProcessorWithLM

LANG_ID = "ru"
MODEL_ID = "bond005/wav2vec2-large-ru-golos-with-lm"
SAMPLES = 20

nltk.download('punkt')
num_processes = max(1, os.cpu_count())

test_dataset = load_dataset(
    "common_voice",
    LANG_ID, split=f"test[:{SAMPLES}]"
)
processor = Wav2Vec2ProcessorWithLM.from_pretrained(MODEL_ID)
model = Wav2Vec2ForCTC.from_pretrained(MODEL_ID)

# Preprocessing the datasets.
# We need to read the audio files as arrays
def speech_file_to_array_fn(batch):
    speech_array, sampling_rate = librosa.load(batch["path"], sr=16_000)
    prepared_sentence = ' '.join(list(filter(
        lambda it: it.isalpha(),
        nltk.wordpunct_tokenize(batch["sentence"].lower().replace('ё', 'е'))
    )))
    batch["speech"] = np.asarray(speech_array, dtype=np.float32)
    batch["sentence"] = prepared_sentence
    return batch

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    test_dataset = test_dataset.map(speech_file_to_array_fn,
                                    num_proc=num_processes)

inputs = processor(test_dataset["speech"], sampling_rate=16_000,
                   return_tensors="pt", padding=True)
with torch.no_grad():
    logits = model(inputs.input_values,
                   attention_mask=inputs.attention_mask).logits
predicted_sentences = processor.batch_decode(
    logits=logits.numpy(),
    num_processes=num_processes
).text

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    for i, predicted_sentence in enumerate(predicted_sentences):
        print("-" * 100)
        print("Reference:", test_dataset[i]["sentence"])
        print("Prediction:", predicted_sentence)
```

```text
----------------------------------------------------------------------------------------------------
Reference:  я беру маленький кусочек бумажки
Prediction: либерман чик сочи бумажки
----------------------------------------------------------------------------------------------------
Reference:  о потерях пока не сообщается
Prediction: о потерях пока не сообщается оооо
----------------------------------------------------------------------------------------------------
Reference:  ваша воля
Prediction: ваша воля
----------------------------------------------------------------------------------------------------
Reference:  мы высоко ценим ее роль в этом отношении
Prediction: урс ока цене не роль в этом отношении
----------------------------------------------------------------------------------------------------
Reference:  вот это вызывало у нас жуткое отторжение
Prediction: от это вызвал у нас жутко отторжения
----------------------------------------------------------------------------------------------------
Reference:  он положил ей букет на книгу
Prediction: он положил букет на книгу
----------------------------------------------------------------------------------------------------
Reference:  ну и положу обиделась женя
Prediction: ну я положу обиделась женя
----------------------------------------------------------------------------------------------------
Reference:  благодарю представителя австралии за ее заявление
Prediction: богатырю представитель австралии зае заявления
----------------------------------------------------------------------------------------------------
Reference:  для меня это не было неожиданностью
Prediction: дай мне это не было неожиданностью
----------------------------------------------------------------------------------------------------
Reference:  поздняя ночь
Prediction: поздняя ночь
----------------------------------------------------------------------------------------------------
Reference:  тем не менее нужно вновь вычленить некоторые элементы наших политических установок
Prediction: тем не менее нужно мыслить снег корыэлементанажихпалиотических установок
----------------------------------------------------------------------------------------------------
Reference:  мы не можем позволить себе упустить эту возможность
Prediction: мы не можем под болить чи опустить эту возможность
----------------------------------------------------------------------------------------------------
Reference:  в предстоящие месяцы суд примет решение по ордеру на арест министра обороны хусейна
Prediction: в предстоящие месяцы суд примет решение по ордеру на арест министра обороны хусейна
----------------------------------------------------------------------------------------------------
Reference:  валерия живет в старом панельном доме советских времен
Prediction: валерия живето в старом панель тона советских времян
----------------------------------------------------------------------------------------------------
Reference:  я вернусь скоро
Prediction: я вернусь скоро
----------------------------------------------------------------------------------------------------
Reference:  слово предоставляется его превосходительству принцу зайду
Prediction: слово предоставляется его превосходительство принцу зайду
----------------------------------------------------------------------------------------------------
Reference:  ну конечно тебе бы этого хотелось
Prediction: ну конечно тебе этого хотелось
----------------------------------------------------------------------------------------------------
Reference:  общественные объединения равны перед законом
Prediction: общественные объединения равны перед законом
----------------------------------------------------------------------------------------------------
Reference:  ну что же нету этики эстетики
Prediction: ну что же не то натеки невротики
----------------------------------------------------------------------------------------------------
Reference:  сразу же она легла в постель
Prediction: сразу же она легла в пасти
```


The Google Colab version of [this script](https://colab.research.google.com/drive/1SnQmrt6HmMNV-zK-UCPajuwl1JvoCqbX?usp=sharing) is available too.

## Evaluation
This model was evaluated on the test subsets of [SberDevices Golos](https://huggingface.co/datasets/SberDevices/Golos) and [Common Voice 6.0](https://huggingface.co/datasets/common_voice) (Russian part), but it was trained on the train subset of SberDevices Golos only.

## Citation
If you want to cite this model you can use this:

```bibtex
@misc{bondarenko2022wav2vec2-large-ru-golos,
  title={XLSR Wav2Vec2 Russian with 3-gram Language Model by Ivan Bondarenko},
  author={Bondarenko, Ivan},
  publisher={Hugging Face},
  journal={Hugging Face Hub},
  howpublished={\url{https://huggingface.co/bond005/wav2vec2-large-ru-golos-with-lm}},
  year={2022}
}
```