Views
No views yet
1import torch
2import torchaudio
3from datasets import load_dataset
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5
6test_dataset = load_dataset("common_voice", "lg", split="test[:2%]")
7
8processor = Wav2Vec2Processor.from_pretrained("lucio/wav2vec2-large-xlsr-luganda")
9model = Wav2Vec2ForCTC.from_pretrained("lucio/wav2vec2-large-xlsr-luganda")
10
11resampler = torchaudio.transforms.Resample(48_000, 16_000)
12
13# Preprocessing the datasets.
14# We need to read the audio files as arrays
15def speech_file_to_array_fn(batch):
16 speech_array, sampling_rate = torchaudio.load(batch["path"])
17 batch["speech"] = resampler(speech_array).squeeze().numpy()
18 return batch
19
20test_dataset = test_dataset.map(speech_file_to_array_fn)
21inputs = processor(test_dataset[:2]["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
22
23with torch.no_grad():
24 logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
25
26predicted_ids = torch.argmax(logits, dim=-1)
27
28print("Prediction:", processor.batch_decode(predicted_ids))
29print("Reference:", test_dataset["sentence"][:2])1import torch
2import torchaudio
3from datasets import load_dataset, load_metric
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5import re
6import unidecode
7
8test_dataset = load_dataset("common_voice", "lg", split="test")
9wer = load_metric("wer")
10
11processor = Wav2Vec2Processor.from_pretrained("lucio/wav2vec2-large-xlsr-luganda")
12model = Wav2Vec2ForCTC.from_pretrained("lucio/wav2vec2-large-xlsr-luganda")
13model.to("cuda")
14
15chars_to_ignore_regex = '[\[\],?.!;:%"“”(){}‟ˮʺ″«»/…‽�–]'
16resampler = torchaudio.transforms.Resample(48_000, 16_000)
17
18# Preprocessing the datasets.
19# We need to read the audio files as arrays
20def speech_file_to_array_fn(batch):
21 speech_array, sampling_rate = torchaudio.load(batch["path"])
22 batch["speech"] = resampler(speech_array).squeeze().numpy()
23 return batch
24
25def remove_special_characters(batch):
26 # word-internal apostrophes are marking contractions
27 batch["norm_text"] = re.sub(r'[‘’´`]', r"'", batch["sentence"])
28 # most other punctuation is ignored
29 batch["norm_text"] = re.sub(chars_to_ignore_regex, "", batch["norm_text"]).lower().strip()
30 batch["norm_text"] = re.sub(r"(-|' | '| +)", " ", batch["norm_text"])
31 # remove accents from a few characters (from loanwords, not tones)
32 batch["norm_text"] = unidecode.unidecode(batch["norm_text"])
33 return batch
34
35test_dataset = test_dataset.map(speech_file_to_array_fn)
36test_dataset = test_dataset.map(remove_special_characters)
37
38def evaluate(batch):
39 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
40
41 with torch.no_grad():
42 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
43
44 pred_ids = torch.argmax(logits, dim=-1)
45 batch["pred_strings"] = processor.batch_decode(pred_ids)
46 return batch
47
48result = test_dataset.map(evaluate, batched=True, batch_size=8)
49
50print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["norm_text"])))train, validation and other datasets were used for training, excluding voices that are in both the other and test datasets. The data was augmented to twice the original size with added noise and manipulated pitch, phase and intensity.
Training proceeded for 60 epochs, on 1 V100 GPU provided by OVHcloud. The test data was used for validation.