-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalign.py
68 lines (54 loc) · 2.43 KB
/
align.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from download import *
from split_audio_from_vtt import make_corpus
import os,sys
import subprocess
from corpus_to_tuples import get_tuples
import h5py
import numpy as np
import argparse
MFA_ALIGNER = 'montreal-forced-aligner/bin/'
G2P_MODEL = 'spanish_g2p.zip'
LANG_MODEL = 'spanish.zip'
def output_h5py(intervals, work_dir, video_id, name):
data = {}
data[video_id] = {}
data[video_id]['intervals'] = np.array([[a[0][0], a[0][1]] for a in intervals])
data[video_id]['features'] = np.array([[a[1].encode('utf-8')] for a in intervals],dtype="a32")
write5Handle=h5py.File(os.path.join(work_dir, video_id + "_" + name + ".h5py"),'w')
vidHandle=write5Handle.create_group(video_id)
vidHandle.create_dataset("features",data=data[video_id]["features"])
vidHandle.create_dataset("intervals",data=data[video_id]["intervals"])
write5Handle.close()
def align(video_id,lang):
try:
os.mkdir(video_id)
except Exception as e:
print(video_id + " folder already found. Quitting.")
sys.exit(0)
work_dir = video_id
# Download the video, wav, and transcription
dwnld(video_id, work_dir)
transcription = os.path.join(work_dir,video_id + '.' + lang + '.vtt')
wav = os.path.join(work_dir,video_id + '.wav')
unaligned = os.path.join(work_dir,video_id + '_unaligned')
# Split and assemble data into corpus accepted by MFA
make_corpus(wav,transcription,unaligned)
corpus = unaligned
video_dict = os.path.join(work_dir,video_id + '_dict.txt')
# Generate dictionary
subprocess.check_call(MFA_ALIGNER + 'mfa_generate_dictionary ' + G2P_MODEL + ' ' + corpus + ' ' + video_dict,shell=True)
# Run the alignment tool
output_dir = os.path.join(work_dir,video_id + '_aligned')
align_call = MFA_ALIGNER + 'mfa_align ' + corpus + ' ' + video_dict + ' ' + LANG_MODEL + ' ' + output_dir
subprocess.check_call(align_call,shell=True)
word_intervals,phone_intervals = get_tuples(output_dir)
# Assemble the h5py files
output_h5py(word_intervals, work_dir, video_id, "words")
output_h5py(word_intervals, work_dir, video_id, "phones")
#print(word_intervals)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('video_id', type=str, help='The youtube ID of the video to be aligned.')
parser.add_argument('lang', type=str, help='The language code of the video.')
args = parser.parse_args()
align(args.video_id, args.lang)