Views
No views yet
1import torch
2import torchaudio
3import pydub
4from pydub.utils import mediainfo
5import array
6from pydub import AudioSegment
7from pydub.utils import get_array_type
8import numpy as np
9
10from datasets import load_dataset
11from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
12test_dataset = load_dataset("common_voice", "tr", split="test[:2%]")
13processor = Wav2Vec2Processor.from_pretrained("gorkemgoknar/wav2vec2-large-xlsr-53-turkish")
14model = Wav2Vec2ForCTC.from_pretrained("gorkemgoknar/wav2vec2-large-xlsr-53-turkish")
15
16
17
18new_sample_rate = 16000
19
20def audio_resampler(batch, new_sample_rate = 16000):
21
22 #not working without complex library compilation in windows for mp3
23 #speech_array, sampling_rate = torchaudio.load(batch["path"])
24 #speech_array, sampling_rate = librosa.load(batch["path"])
25
26 #sampling_rate = pydub.utils.info['sample_rate'] ##gets current samplerate
27
28 sound = pydub.AudioSegment.from_file(file=batch["path"])
29 sampling_rate = new_sample_rate
30 sound = sound.set_frame_rate(new_sample_rate)
31 left = sound.split_to_mono()[0]
32 bit_depth = left.sample_width * 8
33 array_type = pydub.utils.get_array_type(bit_depth)
34
35 numeric_array = np.array(array.array(array_type, left._data) )
36
37 speech_array = torch.FloatTensor(numeric_array)
38
39 batch["speech"] = numeric_array
40 batch["sampling_rate"] = sampling_rate
41 #batch["target_text"] = batch["sentence"]
42
43 return batch
44
45
46# Preprocessing the datasets.
47# We need to read the aduio files as arrays
48def speech_file_to_array_fn(batch):
49 batch = audio_resampler(batch, new_sample_rate = new_sample_rate)
50 return batch
51
52test_dataset = test_dataset.map(speech_file_to_array_fn)
53inputs = processor(test_dataset["speech"][:2], sampling_rate=16_000, return_tensors="pt", padding=True)
54with torch.no_grad():
55 logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
56predicted_ids = torch.argmax(logits, dim=-1)
57print("Prediction:", processor.batch_decode(predicted_ids))
58print("Reference:", test_dataset["sentence"][:2])1import torch
2import torchaudio
3from datasets import load_dataset, load_metric
4from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
5import re
6import pydub
7import array
8import numpy as np
9
10test_dataset = load_dataset("common_voice", "tr", split="test")
11wer = load_metric("wer")
12processor = Wav2Vec2Processor.from_pretrained("gorkemgoknar/wav2vec2-large-xlsr-53-turkish")
13model = Wav2Vec2ForCTC.from_pretrained("gorkemgoknar/wav2vec2-large-xlsr-53-turkish")
14model.to("cuda")
15
16#Note: Not ignoring "'" on this one
17#Note: Not ignoring "'" on this one
18chars_to_ignore_regex = '[\\,\\?\\.\\!\\-\\;\\:\\"\\“\\%\\‘\\”\\�\\#\\>\\<\\_\\’\\[\\]\\{\\}]'
19
20
21#resampler = torchaudio.transforms.Resample(48_000, 16_000)
22#using custom load and transformer for audio -> see audio_resampler
23new_sample_rate = 16000
24
25def audio_resampler(batch, new_sample_rate = 16000):
26
27 #not working without complex library compilation in windows for mp3
28 #speech_array, sampling_rate = torchaudio.load(batch["path"])
29 #speech_array, sampling_rate = librosa.load(batch["path"])
30 #sampling_rate = pydub.utils.info['sample_rate'] ##gets current samplerate
31
32 sound = pydub.AudioSegment.from_file(file=batch["path"])
33
34 sound = sound.set_frame_rate(new_sample_rate)
35 left = sound.split_to_mono()[0]
36 bit_depth = left.sample_width * 8
37 array_type = pydub.utils.get_array_type(bit_depth)
38
39 numeric_array = np.array(array.array(array_type, left._data) )
40
41 speech_array = torch.FloatTensor(numeric_array)
42
43
44 return speech_array, new_sample_rate
45
46def remove_special_characters(batch):
47
48 ##this one comes from subtitles if additional timestamps not processed -> 00:01:01 00:01:01,33
49 batch["sentence"] = re.sub('\\b\\d{2}:\\d{2}:\\d{2}(,+\\d{2})?\\b', ' ', batch["sentence"])
50 ##remove all caps in text [AÇIKLAMA] etc, do it before..
51 batch["sentence"] = re.sub('\\[(\\b[A-Z]+\\])', '', batch["sentence"])
52 ##replace three dots (that are inside string with single)
53 batch["sentence"] = re.sub("([a-zA-Z]+)\\.\\.\\.", r"\\1.", batch["sentence"])
54 #standart ignore list
55 batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower() + " "
56
57 return batch
58
59
60# Preprocessing the datasets.
61# We need to read the aduio files as arrays
62new_sample_rate = 16000
63def speech_file_to_array_fn(batch):
64 batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower()
65 ##speech_array, sampling_rate = torchaudio.load(batch["path"])
66 ##load and conversion done in resampler , takes and returns batch
67 speech_array, sampling_rate = audio_resampler(batch, new_sample_rate = new_sample_rate)
68 batch["speech"] = speech_array
69 batch["sampling_rate"] = sampling_rate
70 batch["target_text"] = batch["sentence"]
71
72 return batch
73
74test_dataset = test_dataset.map(speech_file_to_array_fn)
75# Preprocessing the datasets.
76# We need to read the aduio files as arrays
77def evaluate(batch):
78
79 inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
80 with torch.no_grad():
81 logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
82 pred_ids = torch.argmax(logits, dim=-1)
83 batch["pred_strings"] = processor.batch_decode(pred_ids)
84 return batch
85
86print("EVALUATING:")
87
88##for 8GB RAM on GPU best is batch_size 2 for windows, 4 may fit in linux only
89result = test_dataset.map(evaluate, batched=True, batch_size=2)
90print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["sentence"])))
91train and validation datasets were used for training. Additional 5 Turkish movies with subtitles also used for training.
Similar training model used as base fine-tuning, additional audio resampler is on above code.1import pandas as pd
2from datasets import load_dataset, load_metric
3
4import os
5from pathlib import Path
6from datasets import Dataset
7import csv
8
9#Walk all subdirectories of base_set_path and find csv files
10base_set_path = r'C:\\dataset_extracts'
11csv_files = []
12for path, subdirs, files in os.walk(base_set_path):
13 for name in files:
14 if name.endswith(".csv"):
15 deckfile= os.path.join(path, name)
16 csv_files.append(deckfile)
17
18def get_dataset_from_csv_file(csvfilename,names=['sentence', 'path']):
19 path = Path(csvfilename)
20 csv_delimiter="\\t" ##tab seperated, change if something else
21
22 ##Pandas has bug reading non-ascii file names, make sure use open with encoding
23 df=pd.read_csv(open(path, 'r', encoding='utf-8'), delimiter=csv_delimiter,header=None , names=names, encoding='utf8')
24 return Dataset.from_pandas(df)
25
26custom_datasets= []
27for csv_file in csv_files:
28 this_dataset=get_dataset_from_csv_file(csv_file)
29 custom_datasets.append(this_dataset)
30
31
32
33
34from datasets import concatenate_datasets, load_dataset
35from datasets import load_from_disk
36
37# Merge datasets together (from csv files)
38dataset_file_path = ".\\dataset_file"
39custom_datasets_concat = concatenate_datasets( [dset for dset in custom_datasets] )
40
41#save this one to disk
42custom_datasets_concat.save_to_disk( dataset_file_path )
43
44#load back from disk
45custom_datasets_from_disk = load_from_disk(dataset_file_path)