Views
No views yet
text and audio_path fields:1import torch
2import torchaudio
3import librosa
4from datasets import load_dataset
5from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
6
7# test_data = #TODO: WRITE YOUR CODE TO LOAD THE TEST DATASET. For sample see the Colab link in Training Section.
8
9processor = Wav2Vec2Processor.from_pretrained("gchhablani/wav2vec2-large-xlsr-mr-3")
10model = Wav2Vec2ForCTC.from_pretrained("gchhablani/wav2vec2-large-xlsr-mr-3")
11
12# Preprocessing the datasets.
13# We need to read the audio files as arrays
14def speech_file_to_array_fn(batch):
15 speech_array, sampling_rate = torchaudio.load(batch["audio_path"])
16 batch["speech"] = librosa.resample(speech_array[0].numpy(), sampling_rate, 16_000) # sampling_rate can vary
17 return batch
18
19test_data= test_data.map(speech_file_to_array_fn)
20inputs = processor(test_data["speech"][:2], sampling_rate=16_000, return_tensors="pt", padding=True)
21
22with torch.no_grad():
23 logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
24
25predicted_ids = torch.argmax(logits, dim=-1)
26
27print("Prediction:", processor.batch_decode(predicted_ids))
28print("Reference:", test_data["text"][:2])1import torch
2import torchaudio
3import librosa
4from datasets import load_dataset, load_metric
5from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
6import re
7
8# test_data = #TODO: WRITE YOUR CODE TO LOAD THE TEST DATASET. For sample see the Colab link in Training Section.
9
10wer = load_metric("wer")
11processor = Wav2Vec2Processor.from_pretrained("gchhablani/wav2vec2-large-xlsr-mr-3")
12model = Wav2Vec2ForCTC.from_pretrained("gchhablani/wav2vec2-large-xlsr-mr-3")
13model.to("cuda")
14
15chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\–\…]'
16
17
18# Preprocessing the datasets.
19# We need to read the audio files as arrays
20def speech_file_to_array_fn(batch):
21 batch["text"] = re.sub(chars_to_ignore_regex, '', batch["text"]).lower()
22 speech_array, sampling_rate = torchaudio.load(batch["audio_path"])
23 batch["speech"] = librosa.resample(speech_array[0].numpy(), sampling_rate, 16_000)
24 return batch
25
26test_data= test_data.map(speech_file_to_array_fn)
27
28# Preprocessing the datasets.
29# We need to read the audio files as arrays
30def evaluate(batch):
31 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
32 with torch.no_grad():
33 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
34 pred_ids = torch.argmax(logits, dim=-1)
35 batch["pred_strings"] = processor.batch_decode(pred_ids)
36 return batch
37
38result = test_data.map(evaluate, batched=True, batch_size=8)
39print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["text"])))