kennsluromur / prep_for_training.py
rkjaran's picture
Initial commit with version 22.01
73dc787 verified
raw
history blame contribute delete
No virus
5.78 kB
#!/usr/bin/env python3
# Tiro.ehf - 2021 David Erik Mollberg (tiro@tiro.is)
# This is an example data preperation script for the Icelandic lecture corpus build for Kaldi
import re
import os
from collections import defaultdict
OUT_DIR = '.'
PHONEMES = ['[a]','[ai]','[au]','[c]','[ç]','[cʰ]','[ð]','[ei]','[ɛ]','[f]','[ɣ]','[i]',\
'[ɪi]','[j]','[n]','[n̥]','[ɲ]','[ŋ]','[œi]','[oi]','[ou]','[ɔ]','[pʰ]','[r]',\
'[r̥]','[s]','[u]','[ui]','[uɪ]','[v]','[x]','[ʏi]','[θ]','[p]','[l]', '[m̥]', \
'[l̥]', '[œ]', '[œy]', '[ʏ]', '[g]', '[z]', '[tʰ]', '[ɪ]','[h]', '[ə]', '[y]',\
'[e]', '[kʰ]', '[k]', '[m]', '[ʀ]','[æ]', '[a:]', '[i:]', '[u:]', '[t]']
def open_lecture_file(file_path:str) -> list:
'''
Returns the content of the LECTUREs.tsv file as a list of lists
with the first line omitted.
'''
assert os.path.exists(file_path), 'expected the file LECTURES.tsv to exsist'
return [line.rstrip().split('\t') for line in open(file_path)][1:]
def init_folders(dir:str) -> None:
'''
Creates the output folders
'''
for s in ['train', 'dev','eval']:
if not os.path.exists(os.path.join(dir, s)):
os.makedirs(os.path.join(dir, s), exist_ok=True)
def convert_milli_to_secs(ms:str) -> str:
'''
Convers milliseonds to seconds
e.g.
47683 -> 47.68
'''
return str(round(float(ms)/1000.0, 2))
def remove_puncuation(s:str, c) -> str:
'''
An example of how to prepare the text for use in ASR training
'''
for p in PHONEMES:
if p in s:
s = s.replace(p, '<unk>')
s = s.lower()
s = re.sub('\[hik:{0,1}\s{0,1}(.+?)\]', r"\1", s)
s = re.sub('\[unk:\s(.+?)\]', r"\1", s)
s = re.sub('[-/]', ' ', s)
s = re.sub('[,„“;":\.\'\?\!]','', s)
s = re.sub('\[unk\]', '<unk>', s)
s = re.sub('[\[\]]', '', s)
s = re.sub('µ', 'mu', s)
s = re.sub('ü', 'ú', s)
return s
def create_spk2utt(out_dir, utt2spk:str) -> None:
'''
Reads the utt2spk file and creates spk2utt
'''
content = {}
for line in utt2spk:
line = line.split(' ')
if line[1] not in content:
content[line[1]] = [line[0]]
else:
content[line[1]].append(line[0])
with open(out_dir, 'w') as f_out:
for spkd_id, segments in sorted(content.items()):
f_out.write(spkd_id)
for segment in sorted(segments):
f_out.write(' ' + segment)
f_out.write('\n')
def write_to_file(filename, the_list):
'''
Takes in a file name and list of strings and writes out
'''
with open(filename, 'w') as f_out:
for line in the_list:
f_out.write(line+'\n')
def prep_data() -> None:
info = open_lecture_file('LECTURES.tsv')
data = defaultdict(lambda: defaultdict(list))
for line in info:
text_file_path = os.path.join(line[1], line[0]+'.txt')
assert text_file_path, f'expected {text_file_path} to exsist'
file_content = [line.rstrip().split('\t') for line in open(text_file_path, encoding='UTF-8')][1:]
recording_id = f"{line[0]}"
for segment in file_content:
segment_id = f"{line[1]}_{segment[0]}"
'''
Create utt2spk
segment id - speaker id
e.g.
c7a5ce8b-a2ff-4c08-8668-0687fc0f6e97_00013 00003
c7a5ce8b-a2ff-4c08-8668-0687fc0f6e97_00014 00003
...
'''
data[segment[3]]['utt2spk'].append(f"{segment_id} {line[1]}")
'''
Create text
segment id - text
e.g.
c7a5ce8b-a2ff-4c08-8668-0687fc0f6e97_00013 góðan dag
c7a5ce8b-a2ff-4c08-8668-0687fc0f6e97_00014 Í þessum fyrirlestri er fjallað um lágmarkspör,
...
'''
data[segment[3]]['text'].append(f"{segment_id} {remove_puncuation(segment[4], segment)}")
'''
Create segments
segment id - recording id - start time [sek] - end time [sek]
e.g.
c7a5ce8b-a2ff-4c08-8668-0687fc0f6e97_00013 c7a5ce8b-a2ff-4c08-8668-0687fc0f6e97 20.99 23.34
c7a5ce8b-a2ff-4c08-8668-0687fc0f6e97_00014 c7a5ce8b-a2ff-4c08-8668-0687fc0f6e97 24.03 36.88
...
'''
data[segment[3]]['segments'].append(f"{segment_id} {recording_id} {convert_milli_to_secs(segment[1])} {convert_milli_to_secs(segment[2])}")
'''
Create wavscp
segment_id - sox coversion - full path to audio file
9daf46dc-3ae1-4faa-8546-dbca49f48a22_00070 sox - -c1 -esigned -r 16000 -twav - < ~/kennsluromur-ltp-lectures-new/dev/9daf46dc-3ae1-4faa-8546-dbca49f48a22.wav |
9daf46dc-3ae1-4faa-8546-dbca49f48a22_00076 sox - -c1 -esigned -r 16000 -twav - < ~/kennsluromur-ltp-lectures-new/dev/9daf46dc-3ae1-4faa-8546-dbca49f48a22.wav |
'''
data[segment[3]]['wav.scp'].append(f"{recording_id} sox - -c1 -esigned -r 16000 -twav - < {os.path.join(os.getcwd(), line[1], recording_id+'.wav')} |")
init_folders(OUT_DIR)
for the_set in data.keys():
data[the_set]['wav.scp'] = list(set(data[the_set]['wav.scp']))
for file in data[the_set].keys():
sorted_list = sorted(data[the_set][file])
data[the_set][file] = sorted_list
write_to_file(os.path.join(OUT_DIR, the_set, file), sorted_list)
create_spk2utt(os.path.join(OUT_DIR, the_set, 'spk2utt'), data[the_set]['utt2spk'])
if __name__ == '__main__':
prep_data()