Views
No views yet
1#!/usr/bin/env python
2# coding: utf-8
3
4# Loading dependencies and defining preprocessing functions
5
6from transformers import Wav2Vec2ForCTC
7from transformers import Wav2Vec2Processor
8from datasets import load_dataset, load_metric
9import re
10import torchaudio
11import librosa
12import numpy as np
13from datasets import load_dataset, load_metric
14import torch
15
16chars_to_ignore_regex = '[\\\\\\\\,\\\\\\\\?\\\\\\\\.\\\\\\\\!\\\\\\\\-\\\\\\\\;\\\\\\\\:\\\\\\\\"\\\\\\\\“\\\\\\\\%\\\\\\\\‘\\\\\\\\”\\\\\\\\�]'
17
18def remove_special_characters(batch):
19 batch["text"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower() + " "
20 return batch
21
22def speech_file_to_array_fn(batch):
23 speech_array, sampling_rate = torchaudio.load(batch["path"])
24 batch["speech"] = speech_array[0].numpy()
25 batch["sampling_rate"] = sampling_rate
26 batch["target_text"] = batch["text"]
27 return batch
28
29def resample(batch):
30 batch["speech"] = librosa.resample(np.asarray(batch["speech"]), 48_000, 16_000)
31 batch["sampling_rate"] = 16_000
32 return batch
33
34def prepare_dataset(batch):
35 # check that all files have the correct sampling rate
36 assert (
37 len(set(batch["sampling_rate"])) == 1
38 ), f"Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."
39
40 batch["input_values"] = processor(batch["speech"], sampling_rate=batch["sampling_rate"][0]).input_values
41
42 with processor.as_target_processor():
43 batch["labels"] = processor(batch["target_text"]).input_ids
44 return batch
45
46
47# Loading model and dataset processor
48
49model = Wav2Vec2ForCTC.from_pretrained("lighteternal/wav2vec2-large-xlsr-53-greek").to("cuda")
50processor = Wav2Vec2Processor.from_pretrained("lighteternal/wav2vec2-large-xlsr-53-greek")
51
52
53# Preparing speech dataset to be suitable for inference
54
55common_voice_test = load_dataset("common_voice", "el", split="test")
56
57common_voice_test = common_voice_test.remove_columns(["accent", "age", "client_id", "down_votes", "gender", "locale", "segment", "up_votes"])
58
59common_voice_test = common_voice_test.map(remove_special_characters, remove_columns=["sentence"])
60
61common_voice_test = common_voice_test.map(speech_file_to_array_fn, remove_columns=common_voice_test.column_names)
62
63common_voice_test = common_voice_test.map(resample, num_proc=8)
64
65common_voice_test = common_voice_test.map(prepare_dataset, remove_columns=common_voice_test.column_names, batch_size=8, num_proc=8, batched=True)
66
67
68# Loading test dataset
69
70common_voice_test_transcription = load_dataset("common_voice", "el", split="test")
71
72
73#Performing inference on a random sample. Change the "example" value to try inference on different CommonVoice extracts
74
75example = 123
76
77input_dict = processor(common_voice_test["input_values"][example], return_tensors="pt", sampling_rate=16_000, padding=True)
78
79logits = model(input_dict.input_values.to("cuda")).logits
80
81pred_ids = torch.argmax(logits, dim=-1)
82
83print("Prediction:")
84print(processor.decode(pred_ids[0]))
85# πού θέλεις να πάμε ρώτησε φοβισμένα ο βασιλιάς
86
87print("\\\\
88Reference:")
89print(common_voice_test_transcription["sentence"][example].lower())
90# πού θέλεις να πάμε; ρώτησε φοβισμένα ο βασιλιάς.
911import 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("lighteternal/wav2vec2-large-xlsr-53-greek")
11model = Wav2Vec2ForCTC.from_pretrained("lighteternal/wav2vec2-large-xlsr-53-greek")
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"])))| Metric | Value |
|---|---|
| Training Loss | 0.0545 |
| Validation Loss | 0.1661 |
| CER on CommonVoice Test (%) * | 2.8753 |
| WER on CommonVoice Test (%) * | 10.4976 |
| * Reference transcripts were lower-cased and striped of punctuation and special characters. |