Views
No views yet
1import torch
2import torchaudio
3from datasets import load_dataset
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5test_dataset = load_dataset("common_voice", "el", split="test[:2%]")
6
7processor = Wav2Vec2Processor.from_pretrained("skylord/greek_lsr_1")
8model = Wav2Vec2ForCTC.from_pretrained("skylord/greek_lsr_1")
9
10resampler = torchaudio.transforms.Resample(48_000, 16_000)
11
12# Preprocessing the datasets.
13# We need to read the aduio files as arrays
14def speech_file_to_array_fn(batch):
15 speech_array, sampling_rate = torchaudio.load(batch["path"])
16 batch["speech"] = resampler(speech_array).squeeze().numpy()
17 return batch
18
19test_dataset = test_dataset.map(speech_file_to_array_fn)
20inputs = processor(test_dataset["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)
26print("Prediction:", processor.batch_decode(predicted_ids))
27print("Reference:", test_dataset["sentence"][:2])1import torch
2import torchaudio
3from datasets import load_dataset, load_metric
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5import re
6
7test_dataset = load_dataset("common_voice", "el", split="test")
8wer = load_metric("wer")
9
10processor = Wav2Vec2Processor.from_pretrained("skylord/greek_lsr_1")
11model = Wav2Vec2ForCTC.from_pretrained("skylord/greek_lsr_1")
12model.to("cuda")
13
14chars_to_ignore_regex = '[\\\\\\\\,\\\\\\\\?\\\\\\\\.\\\\\\\\!\\\\\\\\-\\\\\\\\;\\\\\\\\:\\\\\\\\"\\\\\\\\“]'
15resampler = torchaudio.transforms.Resample(48_000, 16_000)
16
17# Preprocessing the datasets.
18# We need to read the aduio files as arrays
19
20def speech_file_to_array_fn(batch):
21 batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower()
22 speech_array, sampling_rate = torchaudio.load(batch["path"])
23 batch["speech"] = resampler(speech_array).squeeze().numpy()
24 return batch
25
26test_dataset = test_dataset.map(speech_file_to_array_fn)
27
28# Preprocessing the datasets.
29# We need to read the aduio files as arrays
30
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"), attention_mask=inputs.attention_mask.to("cuda")).logits
35 pred_ids = torch.argmax(logits, dim=-1)
36 batch["pred_strings"] = processor.batch_decode(pred_ids)
37 return batch
38
39result = test_dataset.map(evaluate, batched=True, batch_size=8)
40print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["sentence"])))train, validation, datasets were used for training as well as