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