Views
No views yet
train splits of Common Voice
and Arabic Speech Corpus.
When using this model, make sure that your speech input is sampled at 16kHz.1%%capture
2!pip install datasets
3!pip install transformers==4.4.0
4!pip install torchaudio
5!pip install jiwer
6!pip install tnkeeh
7
8import torch
9import torchaudio
10from datasets import load_dataset
11from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
12
13test_dataset = load_dataset("common_voice", "ar", split="test[:2%]")
14
15
16processor = Wav2Vec2Processor.from_pretrained("mohammed/wav2vec2-large-xlsr-arabic")
17model = Wav2Vec2ForCTC.from_pretrained("mohammed/wav2vec2-large-xlsr-arabic")
18
19resampler = torchaudio.transforms.Resample(48_000, 16_000)
20
21# Preprocessing the datasets.
22# We need to read the audio files as arrays
23def speech_file_to_array_fn(batch):
24 speech_array, sampling_rate = torchaudio.load(batch["path"])
25 batch["speech"] = resampler(speech_array).squeeze().numpy()
26 return batch
27
28test_dataset = test_dataset.map(speech_file_to_array_fn)
29inputs = processor(test_dataset["speech"][:2], sampling_rate=16_000, return_tensors="pt", padding=True)
30
31with torch.no_grad():
32 logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
33
34predicted_ids = torch.argmax(logits, dim=-1)
35
36print("The predicted sentence is: ", processor.batch_decode(predicted_ids))
37print("The original sentence is:", test_dataset["sentence"][:2])The predicted sentence is : ['ألديك قلم', 'ليست نارك مكسافة على هذه الأرض أبعد من يوم أمس']
The original sentence is: ['ألديك قلم ؟', 'ليست هناك مسافة على هذه الأرض أبعد من يوم أمس.']1
2import torch
3import torchaudio
4from datasets import load_dataset, load_metric
5from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
6import re
7# creating a dictionary with all diacritics
8dict = {
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'get': '',
50'؟': '',
51' ': ' ',
52'\'ۖ ': '',
53'\'': '',
54 '\'ۚ' : '',
55 ' \'': '',
56 '31': '',
57 '24': '',
58 '39': ''
59}
60
61# replacing multiple diacritics using dictionary (stackoverflow is amazing)
62def remove_special_characters(batch):
63 # Create a regular expression from the dictionary keys
64 regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
65 # For each match, look-up corresponding value in dictionary
66 batch["sentence"] = regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], batch["sentence"])
67 return batch
68
69
70test_dataset = load_dataset("common_voice", "ar", split="test")
71wer = load_metric("wer")
72
73processor = Wav2Vec2Processor.from_pretrained("mohammed/wav2vec2-large-xlsr-arabic")
74model = Wav2Vec2ForCTC.from_pretrained("mohammed/wav2vec2-large-xlsr-arabic")
75model.to("cuda")
76
77
78resampler = torchaudio.transforms.Resample(48_000, 16_000)
79
80# Preprocessing the datasets.
81# We need to read the audio files as arrays
82def speech_file_to_array_fn(batch):
83 speech_array, sampling_rate = torchaudio.load(batch["path"])
84 batch["speech"] = resampler(speech_array).squeeze().numpy()
85 return batch
86
87test_dataset = test_dataset.map(speech_file_to_array_fn)
88test_dataset = test_dataset.map(remove_special_characters)
89# Preprocessing the datasets.
90# We need to read the audio files as arrays
91def evaluate(batch):
92 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
93
94 with torch.no_grad():
95 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
96
97 pred_ids = torch.argmax(logits, dim=-1)
98 batch["pred_strings"] = processor.batch_decode(pred_ids)
99 return batch
100
101result = test_dataset.map(evaluate, batched=True, batch_size=8)
102
103print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["sentence"])))