Views
No views yet
1import torch
2import torchaudio
3from datasets import load_dataset
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5
6test_dataset = <load-test-split-of-combined-dataset> # Details on loading this dataset in the evaluation section
7
8processor = Wav2Vec2Processor.from_pretrained("gvs/wav2vec2-large-xlsr-malayalam")
9model = Wav2Vec2ForCTC.from_pretrained("gvs/wav2vec2-large-xlsr-malayalam")
10
11resampler = torchaudio.transforms.Resample(48_000, 16_000)
12
13# Preprocessing the datasets.
14# We need to read the audio files as arrays
15def speech_file_to_array_fn(batch):
16 speech_array, sampling_rate = torchaudio.load(batch["path"])
17 batch["speech"] = resampler(speech_array).squeeze().numpy()
18 return batch
19
20test_dataset = test_dataset.map(speech_file_to_array_fn)
21inputs = processor(test_dataset["speech"][:2], sampling_rate=16_000, return_tensors="pt", padding=True)
22
23with torch.no_grad():
24 logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
25
26predicted_ids = torch.argmax(logits, dim=-1)
27
28print("Prediction:", processor.batch_decode(predicted_ids))
29print("Reference:", test_dataset["sentence"])1import torch
2import torchaudio
3from datasets import load_dataset, load_metric
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5import re
6from datasets import load_dataset, load_metric
7from pathlib import Path
8
9# The custom dataset needs to be created using notebook mentioned at the end of this file
10data_dir = Path('<path-to-custom-dataset>')
11
12dataset_folders = {
13 'iiit': 'iiit_mal_abi',
14 'openslr': 'openslr',
15 'indic-tts': 'indic-tts-ml',
16 'msc-reviewed': 'msc-reviewed-speech-v1.0+20200825',
17}
18
19# Set directories for datasets
20openslr_male_dir = data_dir / dataset_folders['openslr'] / 'male'
21openslr_female_dir = data_dir / dataset_folders['openslr'] / 'female'
22iiit_dir = data_dir / dataset_folders['iiit']
23indic_tts_male_dir = data_dir / dataset_folders['indic-tts'] / 'male'
24indic_tts_female_dir = data_dir / dataset_folders['indic-tts'] / 'female'
25msc_reviewed_dir = data_dir / dataset_folders['msc-reviewed']
26
27# Load the datasets
28openslr_male = load_dataset("json", data_files=[f"{str(openslr_male_dir.absolute())}/sample_{i}.json" for i in range(2023)], split="train")
29openslr_female = load_dataset("json", data_files=[f"{str(openslr_female_dir.absolute())}/sample_{i}.json" for i in range(2103)], split="train")
30iiit = load_dataset("json", data_files=[f"{str(iiit_dir.absolute())}/sample_{i}.json" for i in range(1000)], split="train")
31indic_tts_male = load_dataset("json", data_files=[f"{str(indic_tts_male_dir.absolute())}/sample_{i}.json" for i in range(5649)], split="train")
32indic_tts_female = load_dataset("json", data_files=[f"{str(indic_tts_female_dir.absolute())}/sample_{i}.json" for i in range(2950)], split="train")
33msc_reviewed = load_dataset("json", data_files=[f"{str(msc_reviewed_dir.absolute())}/sample_{i}.json" for i in range(1541)], split="train")
34
35# Create test split as 20%, set random seed as well.
36test_size = 0.2
37random_seed=1
38openslr_male_splits = openslr_male.train_test_split(test_size=test_size, seed=random_seed)
39openslr_female_splits = openslr_female.train_test_split(test_size=test_size, seed=random_seed)
40iiit_splits = iiit.train_test_split(test_size=test_size, seed=random_seed)
41indic_tts_male_splits = indic_tts_male.train_test_split(test_size=test_size, seed=random_seed)
42indic_tts_female_splits = indic_tts_female.train_test_split(test_size=test_size, seed=random_seed)
43msc_reviewed_splits = msc_reviewed.train_test_split(test_size=test_size, seed=random_seed)
44
45# Get combined test dataset
46split_list = [openslr_male_splits, openslr_female_splits, indic_tts_male_splits, indic_tts_female_splits, msc_reviewed_splits, iiit_splits]
47test_dataset = datasets.concatenate_datasets([split['test'] for split in split_list)
48
49wer = load_metric("wer")
50
51processor = Wav2Vec2Processor.from_pretrained("gvs/wav2vec2-large-xlsr-malayalam")
52model = Wav2Vec2ForCTC.from_pretrained("gvs/wav2vec2-large-xlsr-malayalam")
53model.to("cuda")
54
55resamplers = {
56 48000: torchaudio.transforms.Resample(48_000, 16_000),
57}
58
59chars_to_ignore_regex = '[\\\\,\\\\?\\\\.\\\\!\\\\-\\\\;\\\\:\\\\"\\\\“\\\\%\\\\‘\\\\”\\\\�Utrnle\\\\_]'
60unicode_ignore_regex = r'[\\\\u200e]'
61
62# Preprocessing the datasets.
63# We need to read the audio files as arrays
64def speech_file_to_array_fn(batch):
65 batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"])
66 batch["sentence"] = re.sub(unicode_ignore_regex, '', batch["sentence"])
67 speech_array, sampling_rate = torchaudio.load(batch["path"])
68 # Resample if its not in 16kHz
69 if sampling_rate != 16000:
70 batch["speech"] = resamplers[sampling_rate](speech_array).squeeze().numpy()
71 else:
72 batch["speech"] = speech_array.squeeze().numpy()
73 # If more than one dimension is present, pick first one
74 if batch["speech"].ndim > 1:
75 batch["speech"] = batch["speech"][0]
76 return batch
77
78test_dataset = test_dataset.map(speech_file_to_array_fn)
79
80# Preprocessing the datasets.
81# We need to read the audio files as arrays
82def evaluate(batch):
83 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
84
85 with torch.no_grad():
86 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
87
88 pred_ids = torch.argmax(logits, dim=-1)
89 batch["pred_strings"] = processor.batch_decode(pred_ids)
90 return batch
91
92result = test_dataset.map(evaluate, batched=True, batch_size=8)
93
94print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["sentence"])))