align.py 8.8 KB
Newer Older
O
oyjxer 已提交
1 2
#!/usr/bin/env python
""" Usage:
小湉湉's avatar
小湉湉 已提交
3
    align.py wavfile trsfile outwordfile outphonefile
O
oyjxer 已提交
4
"""
小湉湉's avatar
小湉湉 已提交
5
import multiprocessing as mp
O
oyjxer 已提交
6 7 8
import os
import sys

小湉湉's avatar
小湉湉 已提交
9
from tqdm import tqdm
O
oyjxer 已提交
10 11

PHONEME = 'tools/aligner/english_envir/english2phoneme/phoneme'
小湉湉's avatar
小湉湉 已提交
12 13
MODEL_DIR_EN = 'tools/aligner/english'
MODEL_DIR_ZH = 'tools/aligner/mandarin'
O
oyjxer 已提交
14 15 16
HVITE = 'tools/htk/HTKTools/HVite'
HCOPY = 'tools/htk/HTKTools/HCopy'

小湉湉's avatar
小湉湉 已提交
17

小湉湉's avatar
小湉湉 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
def prep_txt_zh(line: str, tmpbase: str, dictfile: str):

    words = []
    line = line.strip()
    for pun in [
            ',', '.', ':', ';', '!', '?', '"', '(', ')', '--', '---', u',',
            u'。', u':', u';', u'!', u'?', u'(', u')'
    ]:
        line = line.replace(pun, ' ')
    for wrd in line.split():
        if (wrd[-1] == '-'):
            wrd = wrd[:-1]
        if (wrd[0] == "'"):
            wrd = wrd[1:]
        if wrd:
            words.append(wrd)

    ds = set([])
    with open(dictfile, 'r') as fid:
        for line in fid:
            ds.add(line.split()[0])

    unk_words = set([])
    with open(tmpbase + '.txt', 'w') as fwid:
        for wrd in words:
            if (wrd not in ds):
                unk_words.add(wrd)
            fwid.write(wrd + ' ')
        fwid.write('\n')
    return unk_words


def prep_txt_en(line: str, tmpbase, dictfile):
小湉湉's avatar
小湉湉 已提交
51

O
oyjxer 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    words = []

    line = line.strip()
    for pun in [',', '.', ':', ';', '!', '?', '"', '(', ')', '--', '---']:
        line = line.replace(pun, ' ')
    for wrd in line.split():
        if (wrd[-1] == '-'):
            wrd = wrd[:-1]
        if (wrd[0] == "'"):
            wrd = wrd[1:]
        if wrd:
            words.append(wrd)

    ds = set([])
    with open(dictfile, 'r') as fid:
        for line in fid:
            ds.add(line.split()[0])

    unk_words = set([])
    with open(tmpbase + '.txt', 'w') as fwid:
        for wrd in words:
            if (wrd.upper() not in ds):
                unk_words.add(wrd.upper())
            fwid.write(wrd + ' ')
        fwid.write('\n')

    #generate pronounciations for unknows words using 'letter to sound'
    with open(tmpbase + '_unk.words', 'w') as fwid:
        for unk in unk_words:
            fwid.write(unk + '\n')
    try:
小湉湉's avatar
小湉湉 已提交
83 84
        os.system(PHONEME + ' ' + tmpbase + '_unk.words' + ' ' + tmpbase +
                  '_unk.phons')
O
oyjxer 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    except:
        print('english2phoneme error!')
        sys.exit(1)

    #add unknown words to the standard dictionary, generate a tmp dictionary for alignment 
    fw = open(tmpbase + '.dict', 'w')
    with open(dictfile, 'r') as fid:
        for line in fid:
            fw.write(line)
    f = open(tmpbase + '_unk.words', 'r')
    lines1 = f.readlines()
    f.close()
    f = open(tmpbase + '_unk.phons', 'r')
    lines2 = f.readlines()
    f.close()
    for i in range(len(lines1)):
        wrd = lines1[i].replace('\n', '')
        phons = lines2[i].replace('\n', '').replace(' ', '')
        seq = []
        j = 0
        while (j < len(phons)):
            if (phons[j] > 'Z'):
                if (phons[j] == 'j'):
                    seq.append('JH')
                elif (phons[j] == 'h'):
                    seq.append('HH')
                else:
                    seq.append(phons[j].upper())
                j += 1
            else:
小湉湉's avatar
小湉湉 已提交
115
                p = phons[j:j + 2]
O
oyjxer 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
                if (p == 'WH'):
                    seq.append('W')
                elif (p in ['TH', 'SH', 'HH', 'DH', 'CH', 'ZH', 'NG']):
                    seq.append(p)
                elif (p == 'AX'):
                    seq.append('AH0')
                else:
                    seq.append(p + '1')
                j += 2

        fw.write(wrd + ' ')
        for s in seq:
            fw.write(' ' + s)
        fw.write('\n')
    fw.close()

小湉湉's avatar
小湉湉 已提交
132

小湉湉's avatar
小湉湉 已提交
133
def prep_mlf(txt: str, tmpbase: str):
O
oyjxer 已提交
134 135 136 137 138 139 140 141 142 143 144

    with open(tmpbase + '.mlf', 'w') as fwid:
        fwid.write('#!MLF!#\n')
        fwid.write('"' + tmpbase + '.lab"\n')
        fwid.write('sp\n')
        wrds = txt.split()
        for wrd in wrds:
            fwid.write(wrd.upper() + '\n')
            fwid.write('sp\n')
        fwid.write('.\n')

小湉湉's avatar
小湉湉 已提交
145

小湉湉's avatar
小湉湉 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
def _get_user():
    return os.path.expanduser('~').split("/")[-1]


def alignment(wav_path: str, text: str):
    tmpbase = '/tmp/' + _get_user() + '_' + str(os.getpid())

    #prepare wav and trs files
    try:
        os.system('sox ' + wav_path + ' -r 16000 ' + tmpbase + '.wav remix -')
    except:
        print('sox error!')
        return None

    #prepare clean_transcript file
    try:
        prep_txt_en(text, tmpbase, MODEL_DIR_EN + '/dict')
    except:
        print('prep_txt error!')
        return None

    #prepare mlf file
    try:
        with open(tmpbase + '.txt', 'r') as fid:
            txt = fid.readline()
        prep_mlf(txt, tmpbase)
    except:
        print('prep_mlf error!')
        return None

    #prepare scp
    try:
        os.system(HCOPY + ' -C ' + MODEL_DIR_EN + '/16000/config ' + tmpbase +
                  '.wav' + ' ' + tmpbase + '.plp')
    except:
        print('HCopy error!')
        return None

    #run alignment
    try:
        os.system(HVITE + ' -a -m -t 10000.0 10000.0 100000.0 -I ' + tmpbase +
                  '.mlf -H ' + MODEL_DIR_EN + '/16000/macros -H ' + MODEL_DIR_EN
                  + '/16000/hmmdefs -i ' + tmpbase + '.aligned ' + tmpbase +
                  '.dict ' + MODEL_DIR_EN + '/monophones ' + tmpbase +
                  '.plp 2>&1 > /dev/null')
    except:
        print('HVite error!')
        return None

O
oyjxer 已提交
195 196 197 198 199 200 201 202 203
    with open(tmpbase + '.txt', 'r') as fid:
        words = fid.readline().strip().split()
    words = txt.strip().split()
    words.reverse()

    with open(tmpbase + '.aligned', 'r') as fid:
        lines = fid.readlines()
    i = 2
    times2 = []
小湉湉's avatar
小湉湉 已提交
204 205 206
    word2phns = {}
    current_word = ''
    index = 0
O
oyjxer 已提交
207
    while (i < len(lines)):
小湉湉's avatar
小湉湉 已提交
208 209 210 211 212
        splited_line = lines[i].strip().split()
        if (len(splited_line) >= 4) and (splited_line[0] != splited_line[1]):
            phn = splited_line[2]
            pst = (int(splited_line[0]) / 1000 + 125) / 10000
            pen = (int(splited_line[1]) / 1000 + 125) / 10000
O
oyjxer 已提交
213
            times2.append([phn, pst, pen])
小湉湉's avatar
小湉湉 已提交
214 215 216 217 218 219 220
            # splited_line[-1]!='sp'
            if len(splited_line) == 5:
                current_word = str(index) + '_' + splited_line[-1]
                word2phns[current_word] = phn
                index += 1
            elif len(splited_line) == 4:
                word2phns[current_word] += ' ' + phn
O
oyjxer 已提交
221
        i += 1
小湉湉's avatar
小湉湉 已提交
222
    return times2, word2phns
小湉湉's avatar
小湉湉 已提交
223 224


小湉湉's avatar
小湉湉 已提交
225
def alignment_zh(wav_path, text_string):
小湉湉's avatar
小湉湉 已提交
226
    tmpbase = '/tmp/' + _get_user() + '_' + str(os.getpid())
O
oyjxer 已提交
227 228 229

    #prepare wav and trs files
    try:
小湉湉's avatar
小湉湉 已提交
230 231 232
        os.system('sox ' + wav_path + ' -r 16000 -b 16 ' + tmpbase +
                  '.wav remix -')

O
oyjxer 已提交
233 234 235
    except:
        print('sox error!')
        return None
小湉湉's avatar
小湉湉 已提交
236

O
oyjxer 已提交
237 238
    #prepare clean_transcript file
    try:
小湉湉's avatar
小湉湉 已提交
239 240 241 242 243
        unk_words = prep_txt_zh(text_string, tmpbase, MODEL_DIR_ZH + '/dict')
        if unk_words:
            print('Error! Please add the following words to dictionary:')
            for unk in unk_words:
                print("非法words: ", unk)
O
oyjxer 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    except:
        print('prep_txt error!')
        return None

    #prepare mlf file
    try:
        with open(tmpbase + '.txt', 'r') as fid:
            txt = fid.readline()
        prep_mlf(txt, tmpbase)
    except:
        print('prep_mlf error!')
        return None

    #prepare scp
    try:
小湉湉's avatar
小湉湉 已提交
259
        os.system(HCOPY + ' -C ' + MODEL_DIR_ZH + '/16000/config ' + tmpbase +
小湉湉's avatar
小湉湉 已提交
260
                  '.wav' + ' ' + tmpbase + '.plp')
O
oyjxer 已提交
261 262 263 264 265 266
    except:
        print('HCopy error!')
        return None

    #run alignment
    try:
小湉湉's avatar
小湉湉 已提交
267
        os.system(HVITE + ' -a -m -t 10000.0 10000.0 100000.0 -I ' + tmpbase +
小湉湉's avatar
小湉湉 已提交
268 269 270
                  '.mlf -H ' + MODEL_DIR_ZH + '/16000/macros -H ' + MODEL_DIR_ZH
                  + '/16000/hmmdefs -i ' + tmpbase + '.aligned ' + MODEL_DIR_ZH
                  + '/dict ' + MODEL_DIR_ZH + '/monophones ' + tmpbase +
小湉湉's avatar
小湉湉 已提交
271
                  '.plp 2>&1 > /dev/null')
小湉湉's avatar
小湉湉 已提交
272

O
oyjxer 已提交
273 274 275 276 277 278 279 280 281 282 283
    except:
        print('HVite error!')
        return None

    with open(tmpbase + '.txt', 'r') as fid:
        words = fid.readline().strip().split()
    words = txt.strip().split()
    words.reverse()

    with open(tmpbase + '.aligned', 'r') as fid:
        lines = fid.readlines()
小湉湉's avatar
小湉湉 已提交
284

O
oyjxer 已提交
285 286 287 288 289 290 291 292 293
    i = 2
    times2 = []
    word2phns = {}
    current_word = ''
    index = 0
    while (i < len(lines)):
        splited_line = lines[i].strip().split()
        if (len(splited_line) >= 4) and (splited_line[0] != splited_line[1]):
            phn = splited_line[2]
小湉湉's avatar
小湉湉 已提交
294 295
            pst = (int(splited_line[0]) / 1000 + 125) / 10000
            pen = (int(splited_line[1]) / 1000 + 125) / 10000
O
oyjxer 已提交
296 297
            times2.append([phn, pst, pen])
            # splited_line[-1]!='sp'
小湉湉's avatar
小湉湉 已提交
298 299
            if len(splited_line) == 5:
                current_word = str(index) + '_' + splited_line[-1]
O
oyjxer 已提交
300
                word2phns[current_word] = phn
小湉湉's avatar
小湉湉 已提交
301 302 303 304 305
                index += 1
            elif len(splited_line) == 4:
                word2phns[current_word] += ' ' + phn
        i += 1
    return times2, word2phns