Views
No views yet
1import numpy as np
2import torch
3import torchaudio
4from datasets import load_dataset
5from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
6
7test_dataset = load_dataset("common_voice", "fi", split="test[:2%]")
8
9processor = Wav2Vec2Processor.from_pretrained("Tommi/wav2vec2-large-xlsr-53-finnish")
10model = Wav2Vec2ForCTC.from_pretrained("Tommi/wav2vec2-large-xlsr-53-finnish")
11
12resampler = lambda sr, y: librosa.resample(y.squeeze(), sr, 16_000)
13
14# Preprocessing the datasets.
15# We need to read the aduio files as arrays
16def speech_file_to_array_fn(batch):
17 speech_array, sampling_rate = torchaudio.load(batch["path"])
18 batch["speech"] = resampler(sampling_rate, speech_array.numpy()).squeeze()
19 return batch
20
21test_dataset = test_dataset.map(speech_file_to_array_fn)
22inputs = processor(test_dataset["speech"][:2], sampling_rate=16_000, return_tensors="pt", padding=True)
23
24with torch.no_grad():
25 logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
26
27predicted_ids = torch.argmax(logits, dim=-1)
28
29print("Prediction:", processor.batch_decode(predicted_ids))
30print("Reference:", test_dataset["sentence"][:2])1import librosa
2import torch
3import torchaudio
4from datasets import load_dataset, load_metric
5from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
6import re
7
8test_dataset = load_dataset("common_voice", "fi", split="test")
9wer = load_metric("wer")
10
11processor = Wav2Vec2Processor.from_pretrained("Tommi/wav2vec2-large-xlsr-53-finnish")
12model = Wav2Vec2ForCTC.from_pretrained("Tommi/wav2vec2-large-xlsr-53-finnish")
13model.to("cuda")
14
15chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\"\%\'\"\�\'\...\…\–\é]'
16
17resampler = lambda sr, y: librosa.resample(y.numpy().squeeze(), sr, 16_000)
18
19# Preprocessing the datasets.
20# We need to read the audio 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(sampling_rate, speech_array).squeeze()
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 audio files as arrays
31def evaluate(batch):
32 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
33
34 with torch.no_grad():
35 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
36
37 pred_ids = torch.argmax(logits, dim=-1)
38 batch["pred_strings"] = processor.batch_decode(pred_ids)
39
40 return batch
41
42result = test_dataset.map(evaluate, batched=True, batch_size=8)
43
44print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["sentence"])))train, validation, and other datasets were used for training as well as CSS10 and Finnish parliament session 2