Views
No views yet
1import torch
2import torchaudio
3from datasets import load_dataset
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5
6test_dataset = load_dataset("common_voice", "cs", split="test[:2%]")
7processor = Wav2Vec2Processor.from_pretrained("arampacha/wav2vec2-large-xlsr-czech")
8model = Wav2Vec2ForCTC.from_pretrained("arampacha/wav2vec2-large-xlsr-czech")
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)
26
27print("Prediction:", processor.batch_decode(predicted_ids))
28print("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", "cs", split="test")
8wer = load_metric("wer")
9
10processor = Wav2Vec2Processor.from_pretrained("arampacha/wav2vec2-large-xlsr-czech")
11model = Wav2Vec2ForCTC.from_pretrained("arampacha/wav2vec2-large-xlsr-czech")
12model.to("cuda")
13
14chars_to_ignore = [",", "?", ".", "!", "-", ";", ":", '""', "%", "'", '"', "�", '«', '»', '—', '…', '(', ')', '*', '”', '“']
15chars_to_ignore_regex = f'[{"".join(chars_to_ignore)}]'
16resampler = torchaudio.transforms.Resample(48_000, 16_000)
17
18# Preprocessing the datasets.
19# We need to read the aduio files as arrays
20# Note: this models is trained ignoring accents on letters as below
21def speech_file_to_array_fn(batch):
22 batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower().strip()
23 batch["sentence"] = re.sub(re.compile('[äá]'), 'a', batch['sentence'])
24 batch["sentence"] = re.sub(re.compile('[öó]'), 'o', batch['sentence'])
25 batch["sentence"] = re.sub(re.compile('[èé]'), 'e', batch['sentence'])
26 batch["sentence"] = re.sub(re.compile("[ïí]"), 'i', batch['sentence'])
27 batch["sentence"] = re.sub(re.compile("[üů]"), 'u', batch['sentence'])
28 batch['sentence'] = re.sub(' ', ' ', batch['sentence'])
29 speech_array, sampling_rate = torchaudio.load(batch["path"])
30 batch["speech"] = resampler(speech_array).squeeze().numpy()
31 return batch
32
33test_dataset = test_dataset.map(speech_file_to_array_fn)
34
35# Preprocessing the datasets.
36# We need to read the aduio files as arrays
37def evaluate(batch):
38 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
39
40 with torch.no_grad():
41 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
42
43 pred_ids = torch.argmax(logits, dim=-1)
44 batch["pred_strings"] = processor.batch_decode(pred_ids)
45 return batch
46
47result = test_dataset.map(evaluate, batched=True, batch_size=8)
48
49print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["sentence"])))train, validation.