Views
No views yet
sentence and path fields:1
2import torch
3import torchaudio
4from datasets import load_dataset
5from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
6
7# test_dataset = #TODO: WRITE YOUR CODE TO LOAD THE TEST DATASET. For a sample, see the Colab link in Training Section.
8
9processor = Wav2Vec2Processor.from_pretrained("amoghsgopadi/wav2vec2-large-xlsr-kn")
10model = Wav2Vec2ForCTC.from_pretrained("amoghsgopadi/wav2vec2-large-xlsr-kn")
11resampler = torchaudio.transforms.Resample(48_000, 16_000) # The original data was with 48,000 sampling rate. You can change it according to your input.
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["speech"][:2], 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])
301
2import torch
3import torchaudio
4from datasets import load_dataset, load_metric
5from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
6import re
7
8# test_dataset = #TODO: WRITE YOUR CODE TO LOAD THE TEST DATASET. For sample see the Colab link in Training Section.
9
10wer = load_metric("wer")
11
12processor = Wav2Vec2Processor.from_pretrained("amoghsgopadi/wav2vec2-large-xlsr-kn")
13model = Wav2Vec2ForCTC.from_pretrained("amoghsgopadi/wav2vec2-large-xlsr-kn")
14model.to("cuda")
15
16chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\–\…]'
17resampler = torchaudio.transforms.Resample(48_000, 16_000)
18
19# Preprocessing the datasets.
20# We need to read the aduio files as arrays
21def speech_file_to_array_fn(batch):
22 batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower()
23 speech_array, sampling_rate = torchaudio.load(batch["path"])
24 batch["speech"] = resampler(speech_array).squeeze().numpy()
25 return batch
26
27test_dataset = test_dataset.map(speech_file_to_array_fn)
28
29# Preprocessing the datasets.
30# We need to read the aduio files as arrays
31def evaluate(batch):
32 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
33 with torch.no_grad():
34 logits = model(inputs.input_values.to("cuda"),
35 attention_mask=inputs.attention_mask.to("cuda")).logits
36 pred_ids = torch.argmax(logits, dim=-1)
37 batch["pred_strings"] = processor.batch_decode(pred_ids)
38 return batch
39
40result = test_dataset.map(evaluate, batched=True, batch_size=8)
41print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["sentence"])))
42