Views
No views yet
1import torch
2import torchaudio
3from datasets import load_dataset
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5test_dataset = load_dataset("common_voice", "hsb", split="test[:2%]")
6processor = Wav2Vec2Processor.from_pretrained("anuragshas/wav2vec2-large-xlsr-53-hsb")
7model = Wav2Vec2ForCTC.from_pretrained("anuragshas/wav2vec2-large-xlsr-53-hsb")
8resampler = torchaudio.transforms.Resample(48_000, 16_000)
9# Preprocessing the datasets.
10# We need to read the aduio files as arrays
11def speech_file_to_array_fn(batch):
12 speech_array, sampling_rate = torchaudio.load(batch["path"])
13 batch["speech"] = resampler(speech_array).squeeze().numpy()
14 return batch
15test_dataset = test_dataset.map(speech_file_to_array_fn)
16inputs = processor(test_dataset["speech"][:2], sampling_rate=16_000, return_tensors="pt", padding=True)
17with torch.no_grad():
18 logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
19predicted_ids = torch.argmax(logits, dim=-1)
20print("Prediction:", processor.batch_decode(predicted_ids))
21print("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", "hsb", split="test")
7wer = load_metric("wer")
8processor = Wav2Vec2Processor.from_pretrained("anuragshas/wav2vec2-large-xlsr-53-hsb")
9model = Wav2Vec2ForCTC.from_pretrained("anuragshas/wav2vec2-large-xlsr-53-hsb")
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.