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: ['yaherukaga gukora igitaramo y iki mu jyiwa na mul mumbiliki', 'ini rero ntibizashoboka ka nibo nkunrabibzi']
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")
13model = Wav2Vec2ForCTC.from_pretrained("lucio/wav2vec2-large-xlsr-kinyarwanda")
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"(-| ?' ?| +)", " ", batch["text"]) # treat dash and apostrophe as word boundary
22 batch["text"] = unidecode.unidecode(batch["text"]) # strip accents
23 return batch
24
25## Audio pre-processing
26resampler = torchaudio.transforms.Resample(48_000, 16_000)
27
28def speech_file_to_array_fn(batch):
29 speech_array, sampling_rate = torchaudio.load(batch["path"])
30 batch["speech"] = resampler(speech_array).squeeze().numpy()
31 batch["sampling_rate"] = 16_000
32 return batch
33
34def cv_prepare(batch):
35 batch = remove_special_characters(batch)
36 batch = speech_file_to_array_fn(batch)
37 return batch
38
39test_dataset = test_dataset.map(cv_prepare)
40
41# Preprocessing the datasets.
42# We need to read the audio files as arrays
43def evaluate(batch):
44 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
45
46 with torch.no_grad():
47 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
48
49 pred_ids = torch.argmax(logits, dim=-1)
50 batch["pred_strings"] = processor.batch_decode(pred_ids)
51 return batch
52
53result = test_dataset.map(evaluate, batched=True, batch_size=8)
54
55def chunked_wer(targets, predictions, chunk_size=None):
56 if chunk_size is None: return jiwer.wer(targets, predictions)
57 start = 0
58 end = chunk_size
59 H, S, D, I = 0, 0, 0, 0
60 while start < len(targets):
61 chunk_metrics = jiwer.compute_measures(targets[start:end], predictions[start:end])
62 H = H + chunk_metrics["hits"]
63 S = S + chunk_metrics["substitutions"]
64 D = D + chunk_metrics["deletions"]
65 I = I + chunk_metrics["insertions"]
66 start += chunk_size
67 end += chunk_size
68 return float(S + D + I) / float(H + S + D)
69
70print("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 100k examples, 20% of the available data. Training proceeded for 30k global steps, on 1 V100 GPU provided by OVHcloud. For validation, 2048 examples of the validation dataset were used.