Views
No views yet
1import torch
2import torchaudio
3from datasets import load_dataset
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5test_dataset = load_dataset("common_voice", "or", split="test[:2%]")
6
7processor = Wav2Vec2Processor.from_pretrained("gchhablani/wav2vec2-large-xlsr-or")
8model = Wav2Vec2ForCTC.from_pretrained("gchhablani/wav2vec2-large-xlsr-or")
9resampler = torchaudio.transforms.Resample(48_000, 16_000)
10# Preprocessing the datasets.
11# We need to read the aduio files as arrays
12def speech_file_to_array_fn(batch):
13 speech_array, sampling_rate = torchaudio.load(batch["path"])
14 batch["speech"] = resampler(speech_array).squeeze().numpy()
15 return batch
16test_dataset = test_dataset.map(speech_file_to_array_fn)
17inputs = processor(test_dataset["speech"][:2], sampling_rate=16_000, return_tensors="pt", padding=True)
18with torch.no_grad():
19 logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
20predicted_ids = torch.argmax(logits, dim=-1)
21print("Prediction:", processor.batch_decode(predicted_ids))
22print("Reference:", test_dataset["sentence"][:2])1import torch
2import torchaudio
3from datasets import load_dataset, load_metric
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5import re
6test_dataset = load_dataset("common_voice", "or", split="test")
7wer = load_metric("wer")
8processor = Wav2Vec2Processor.from_pretrained("gchhablani/wav2vec2-large-xlsr-or")
9model = Wav2Vec2ForCTC.from_pretrained("gchhablani/wav2vec2-large-xlsr-or")
10model.to("cuda")
11chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\–\…\'\_\’\।\|]'
12resampler = torchaudio.transforms.Resample(48_000, 16_000)
13# Preprocessing the datasets.
14# We need to read the aduio files as arrays
15def speech_file_to_array_fn(batch):
16 batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower()
17 speech_array, sampling_rate = torchaudio.load(batch["path"])
18 batch["speech"] = resampler(speech_array).squeeze().numpy()
19 return batch
20test_dataset = test_dataset.map(speech_file_to_array_fn)
21# Preprocessing the datasets.
22# We need to read the aduio files as arrays
23def evaluate(batch):
24 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
25 with torch.no_grad():
26 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
27 pred_ids = torch.argmax(logits, dim=-1)
28 batch["pred_strings"] = processor.batch_decode(pred_ids)
29 return batch
30result = test_dataset.map(evaluate, batched=True, batch_size=8)
31print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["sentence"])))train and validation datasets were used for training.The colab notebook used can be found here.