Views
No views yet
1import torch
2import torchaudio
3from datasets import load_dataset
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5
6# WARNING! This will download and extract to use about 80GB on disk.
7test_dataset = load_dataset("common_voice", "rw", split="test[:2%]")
8
9processor = Wav2Vec2Processor.from_pretrained("lucio/wav2vec2-large-xlsr-kinyarwanda")
10model = Wav2Vec2ForCTC.from_pretrained("lucio/wav2vec2-large-xlsr-kinyarwanda")
11
12resampler = torchaudio.transforms.Resample(48_000, 16_000)
13
14# Preprocessing the datasets.
15# We need to read the audio files as arrays
16def speech_file_to_array_fn(batch):
17 speech_array, sampling_rate = torchaudio.load(batch["path"])
18 batch["speech"] = resampler(speech_array).squeeze().numpy()
19 return batch
20
21test_dataset = test_dataset.map(speech_file_to_array_fn)
22inputs = processor(test_dataset[:2]["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
23
24with torch.no_grad():
25 logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
26
27predicted_ids = torch.argmax(logits, dim=-1)
28
29print("Prediction:", processor.batch_decode(predicted_ids))
30print("Reference:", test_dataset["sentence"][:2])Prediction: ['yaherukago gukora igitaramo yiki mujyiwa na mor mu bubiligi', "ibi rero ntibizashoboka kandi n'umudabizi"]
Reference: ['Yaherukaga gukora igitaramo nk’iki mu Mujyi wa Namur mu Bubiligi.', 'Ibi rero, ntibizashoboka, kandi nawe arabizi.']chunked_wer function from pcuenq.1import jiwer
2import torch
3import torchaudio
4from datasets import load_dataset, load_metric
5from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
6import re
7import unidecode
8
9test_dataset = load_dataset("common_voice", "rw", split="test")
10wer = load_metric("wer")
11
12processor = Wav2Vec2Processor.from_pretrained("lucio/wav2vec2-large-xlsr-kinyarwanda-apostrophied")
13model = Wav2Vec2ForCTC.from_pretrained("lucio/wav2vec2-large-xlsr-kinyarwanda-apostrophied")
14model.to("cuda")
15
16chars_to_ignore_regex = r'[!"#$%&()*+,./:;<=>?@\[\]\\_{}|~£¤¨©ª«¬®¯°·¸»¼½¾ðʺ˜˝ˮ‐–—―‚“”„‟•…″‽₋€™−√�]'
17
18def remove_special_characters(batch):
19 batch["text"] = re.sub(r'[ʻʽʼ‘’´`]', r"'", batch["sentence"]) # normalize apostrophes
20 batch["text"] = re.sub(chars_to_ignore_regex, "", batch["text"]).lower().strip() # remove all other punctuation
21 batch["text"] = re.sub(r"([b-df-hj-np-tv-z])' ([aeiou])", r"\1'\2", batch["text"]) # remove spaces where apostrophe marks a deleted vowel
22 batch["text"] = re.sub(r"(-| '|' | +)", " ", batch["text"]) # treat dash and other apostrophes as word boundary
23 batch["text"] = unidecode.unidecode(batch["text"]) # strip accents from loanwords
24 return batch
25
26## Audio pre-processing
27resampler = torchaudio.transforms.Resample(48_000, 16_000)
28
29def speech_file_to_array_fn(batch):
30 speech_array, sampling_rate = torchaudio.load(batch["path"])
31 batch["speech"] = resampler(speech_array).squeeze().numpy()
32 batch["sampling_rate"] = 16_000
33 return batch
34
35def cv_prepare(batch):
36 batch = remove_special_characters(batch)
37 batch = speech_file_to_array_fn(batch)
38 return batch
39
40test_dataset = test_dataset.map(cv_prepare)
41
42# Preprocessing the datasets.
43# We need to read the audio files as arrays
44def evaluate(batch):
45 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
46
47 with torch.no_grad():
48 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
49
50 pred_ids = torch.argmax(logits, dim=-1)
51 batch["pred_strings"] = processor.batch_decode(pred_ids)
52 return batch
53
54result = test_dataset.map(evaluate, batched=True, batch_size=8)
55
56def chunked_wer(targets, predictions, chunk_size=None):
57 if chunk_size is None: return jiwer.wer(targets, predictions)
58 start = 0
59 end = chunk_size
60 H, S, D, I = 0, 0, 0, 0
61 while start < len(targets):
62 chunk_metrics = jiwer.compute_measures(targets[start:end], predictions[start:end])
63 H = H + chunk_metrics["hits"]
64 S = S + chunk_metrics["substitutions"]
65 D = D + chunk_metrics["deletions"]
66 I = I + chunk_metrics["insertions"]
67 start += chunk_size
68 end += chunk_size
69 return float(S + D + I) / float(H + S + D)
70
71print("WER: {:2f}".format(100 * chunked_wer(result["sentence"], result["pred_strings"], chunk_size=4000)))down_vote or were longer than 9.5 seconds. The data used totals about 125k examples, 25% of the available data, trained on 1 V100 GPU provided by OVHcloud, for a total of about 60 hours: 20 epochs on one block of 32k examples and then 10 epochs each on 3 more blocks of 32k examples. For validation, 2048 examples of the validation dataset were used.