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", "eo", split="test[:2%]")
7processor = Wav2Vec2Processor.from_pretrained("cpierse/wav2vec2-large-xlsr-53-esperanto")
8model = Wav2Vec2ForCTC.from_pretrained("cpierse/wav2vec2-large-xlsr-53-esperanto")
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
6import jiwer
7
8def chunked_wer(targets, predictions, chunk_size=None):
9 if chunk_size is None: return jiwer.wer(targets, predictions)
10 start = 0
11 end = chunk_size
12 H, S, D, I = 0, 0, 0, 0
13 while start < len(targets):
14 chunk_metrics = jiwer.compute_measures(targets[start:end], predictions[start:end])
15 H = H + chunk_metrics["hits"]
16 S = S + chunk_metrics["substitutions"]
17 D = D + chunk_metrics["deletions"]
18 I = I + chunk_metrics["insertions"]
19 start += chunk_size
20 end += chunk_size
21 return float(S + D + I) / float(H + S + D)
22
23test_dataset = load_dataset("common_voice", "eo", split="test") #TODO: replace {lang_id} in your language code here. Make sure the code is one of the *ISO codes* of [this](https://huggingface.co/languages) site.
24wer = load_metric("wer")
25
26processor = Wav2Vec2Processor.from_pretrained("cpierse/wav2vec2-large-xlsr-53-esperanto")
27model = Wav2Vec2ForCTC.from_pretrained("cpierse/wav2vec2-large-xlsr-53-esperanto")
28model.to("cuda")
29
30chars_to_ignore_regex = '[\,\?\.\!\-\;\:\"\“\%\‘\”\�\„\«\(\»\)\’\']'
31resampler = torchaudio.transforms.Resample(48_000, 16_000)
32
33# Preprocessing the datasets.
34# We need to read the aduio files as arrays
35def speech_file_to_array_fn(batch):
36 batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower()
37 speech_array, sampling_rate = torchaudio.load(batch["path"])
38 batch["speech"] = resampler(speech_array).squeeze().numpy()
39 return batch
40
41test_dataset = test_dataset.map(speech_file_to_array_fn)
42
43# Preprocessing the datasets.
44# We need to read the aduio files as arrays
45def evaluate(batch):
46 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
47
48 with torch.no_grad():
49 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
50
51 pred_ids = torch.argmax(logits, dim=-1)
52 batch["pred_strings"] = processor.batch_decode(pred_ids)
53 return batch
54
55result = test_dataset.map(evaluate, batched=True, batch_size=8)
56
57print("WER: {:2f}".format(100 * chunked_wer(predictions=result["pred_strings"], targets=result["sentence"],chunk_size=2000)))train, validation datasets were used for training.