-
Notifications
You must be signed in to change notification settings - Fork 487
/
extract_feats.py
1462 lines (1225 loc) · 55.1 KB
/
extract_feats.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function
import os
import shutil
import stat
import subprocess
import time
import numpy as np
from scipy.io import wavfile
import re
import glob
# File to extract features (mostly) automatically using the merlin speech
# pipeline
# example tts_env.sh file , written out by installer script install_tts.py
# https://gist.github.com/kastnerkyle/001a58a58d090658ee5350cb6129f857
"""
export ESTDIR=/Tmp/kastner/speech_synthesis/speech_tools/
export FESTDIR=/Tmp/kastner/speech_synthesis/festival/
export FESTVOXDIR=/Tmp/kastner/speech_synthesis/festvox/
export VCTKDIR=/Tmp/kastner/vctk/VCTK-Corpus/
export HTKDIR=/Tmp/kastner/speech_synthesis/htk/
export SPTKDIR=/Tmp/kastner/speech_synthesis/SPTK-3.9/
export HTSENGINEDIR=/Tmp/kastner/speech_synthesis/hts_engine_API-1.10/
export HTSDEMODIR=/Tmp/kastner/speech_synthesis/HTS-demo_CMU-ARCTIC-SLT/
export HTSPATCHDIR=/Tmp/kastner/speech_synthesis/HTS-2.3_for_HTL-3.4.1/
export MERLINDIR=/Tmp/kastner/speech_synthesis/latest_features/merlin/
"""
# Not currently needed...
def subfolder_select(subfolders):
r = [sf for sf in subfolders if sf == "p294"]
if len(r) == 0:
raise ValueError("Error: subfolder_select failed")
return r
# Need to edit the conf...
def replace_conflines(conf, match, sub, replace_line="%s: %s\n"):
replace = None
for n, l in enumerate(conf):
if l[:len(match)] == match:
replace = n
break
conf[replace] = replace_line % (match, sub)
return conf
def replace_write(fpath, match, sub, replace_line="%s: %s\n"):
with open(fpath, "r") as f:
conf = f.readlines()
conf = replace_conflines(conf, match, sub, replace_line=replace_line)
with open(fpath, "w") as f:
f.writelines(conf)
def copytree(src, dst, symlinks=False, ignore=None):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
for item in lst:
s = os.path.join(src, item)
d = os.path.join(dst, item)
if symlinks and os.path.islink(s):
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d)
# Convenience function to reuse the defined env
def pwrap(args, shell=False):
p = subprocess.Popen(args, shell=shell, stdout=subprocess.PIPE,
stdin=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True)
return p
# Print output
# http://stackoverflow.com/questions/4417546/constantly-print-subprocess-output-while-process-is-running
def execute(cmd, shell=False):
popen = pwrap(cmd, shell=shell)
for stdout_line in iter(popen.stdout.readline, ""):
yield stdout_line
popen.stdout.close()
return_code = popen.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, cmd)
def pe(cmd, shell=False):
"""
Print and execute command on system
"""
ret = []
for line in execute(cmd, shell=shell):
ret.append(line)
print(line, end="")
return ret
# from merlin
def load_binary_file(file_name, dimension):
fid_lab = open(file_name, 'rb')
features = np.fromfile(fid_lab, dtype=np.float32)
fid_lab.close()
assert features.size % float(
dimension) == 0.0, 'specified dimension %s not compatible with data' % (dimension)
features = features[:(dimension * (features.size / dimension))]
features = features.reshape((-1, dimension))
return features
def array_to_binary_file(data, output_file_name):
data = np.array(data, 'float32')
fid = open(output_file_name, 'wb')
data.tofile(fid)
fid.close()
def load_binary_file_frame(file_name, dimension):
fid_lab = open(file_name, 'rb')
features = np.fromfile(fid_lab, dtype=np.float32)
fid_lab.close()
assert features.size % float(
dimension) == 0.0, 'specified dimension %s not compatible with data' % (dimension)
frame_number = features.size / dimension
features = features[:(dimension * frame_number)]
features = features.reshape((-1, dimension))
return features, frame_number
# Source the tts_env_script
env_script = "tts_env.sh"
if os.path.isfile(env_script):
command = 'env -i bash -c "source %s && env"' % env_script
for line in execute(command, shell=True):
key, value = line.split("=")
# remove newline
value = value.strip()
os.environ[key] = value
else:
raise IOError("Cannot find file %s" % env_script)
festdir = os.environ["FESTDIR"]
festvoxdir = os.environ["FESTVOXDIR"]
estdir = os.environ["ESTDIR"]
sptkdir = os.environ["SPTKDIR"]
# generalize to more than VCTK when this is done...
vctkdir = os.environ["VCTKDIR"]
htkdir = os.environ["HTKDIR"]
merlindir = os.environ["MERLINDIR"]
def extract_intermediate_features(wav_path, txt_path, keep_silences=False,
full_features=False, ehmm_max_n_itr=1):
basedir = os.getcwd()
latest_feature_dir = "latest_features"
if not os.path.exists(latest_feature_dir):
os.mkdir(latest_feature_dir)
os.chdir(latest_feature_dir)
latest_feature_dir = os.getcwd()
if not os.path.exists("merlin"):
clone_cmd = "git clone https://github.com/kastnerkyle/merlin"
pe(clone_cmd, shell=True)
if keep_silences:
# REMOVE SILENCES TO MATCH JOSE PREPROC
os.chdir("merlin/src")
pe("sed -i.bak -e '708,712d;' run_merlin.py", shell=True)
pe("sed -i.bak -e '695,706d;' run_merlin.py", shell=True)
os.chdir(latest_feature_dir)
os.chdir("merlin")
merlin_dir = os.getcwd()
os.chdir("egs/build_your_own_voice/s1")
experiment_dir = os.getcwd()
if not os.path.exists("database"):
print("Creating database and copying in files")
pe("bash -x 01_setup.sh my_new_voice 2>&1", shell=True)
# Copy in wav files
wav_partial_path = wav_path # vctkdir + "wav48/"
"""
subfolders = sorted(os.listdir(wav_partial_path))
# only p294 for now...
subfolders = subfolder_select(subfolders)
os.chdir("database/wav")
for sf in subfolders:
wav_path = wav_partial_path + sf + "/*.wav"
pe("cp %s ." % wav_path, shell=True)
"""
to_copy = os.listdir(wav_partial_path)
if len([tc for tc in to_copy if tc[-4:] == ".wav"]) == 0:
raise IOError(
"Unable to find any wav files in %s, make sure the filenames end in .wav!" % wav_partial_path)
os.chdir("database/wav")
if wav_partial_path[-1] != "/":
wav_partial_path = wav_partial_path + "/"
wav_match_path = wav_partial_path + "*.wav"
for fi in glob.glob(wav_match_path):
pe("echo %s; cp %s ." % (fi, fi), shell=True)
# THIS MAY FAIL IF TOO MANY WAV FILES
# pe("cp %s ." % wav_match_path, shell=True)
for f in os.listdir("."):
# This is only necessary because of corrupted files...
fs, d = wavfile.read(f)
wavfile.write(f, fs, d)
# downsample the files
get_sr_cmd = 'file `ls *.wav | head -n 1` | cut -d " " -f 12'
sr = pe(get_sr_cmd, shell=True)
sr_int = int(sr[0].strip())
print("Got samplerate {}, converting to 16000".format(sr_int))
# was assuming all were 48000
convert = estdir + \
"bin/ch_wave $i -o tmp_$i -itype wav -otype wav -F 16000 -f {}".format(sr_int)
pe("for i in *.wav; do echo %s; %s; mv tmp_$i $i; done" % (convert, convert), shell=True)
os.chdir(experiment_dir)
txt_partial_path = txt_path # vctkdir + "txt/"
"""
subfolders = sorted(os.listdir(txt_partial_path))
# only p294 for now...
subfolders = subfolder_select(subfolders)
os.chdir("database/txt")
for sf in subfolders:
txt_path = txt_partial_path + sf + "/*.txt"
pe("cp %s ." % txt_path, shell=True)
"""
os.chdir("database/txt")
to_copy = os.listdir(txt_partial_path)
if len([tc for tc in to_copy if tc[-4:] == ".txt"]) == 0:
raise IOError(
"Unable to find any txt files in %s. Be sure the filenames end in .txt!" % txt_partial_path)
txt_match_path = txt_partial_path + "/*.txt"
for fi in glob.glob(txt_match_path):
# escape string...
fi = re.escape(fi)
try:
pe("echo %s; cp %s ." % (fi, fi), shell=True)
except:
from IPython import embed
embed()
raise ValueError()
#pe("cp %s ." % txt_match_path, shell=True)
do_state_align = False
if do_state_align:
raise ValueError("Replace these lies with something that points at the right place")
os.chdir(merlin_dir)
os.chdir("misc/scripts/alignment/state_align")
pe("bash -x setup.sh 2>&1", shell=True)
with open("config.cfg", "r") as f:
config_lines = f.readlines()
# replace FESTDIR with the correct path
festdir_replace_line = None
for n, l in enumerate(config_lines):
if "FESTDIR=" in l:
festdir_replace_line = n
break
config_lines[festdir_replace_line] = "FESTDIR=%s\n" % festdir
# replace HTKDIR with the correct path
htkdir_replace_line = None
for n, l in enumerate(config_lines):
if "HTKDIR=" in l:
htkdir_replace_line = n
break
config_lines[htkdir_replace_line] = "HTKDIR=%s\n" % htkdir
with open("config.cfg", "w") as f:
f.writelines(config_lines)
pe("bash -x run_aligner.sh config.cfg 2>&1", shell=True)
else:
os.chdir(merlin_dir)
if not os.path.exists("misc/scripts/alignment/phone_align/full-context-labels/full"):
os.chdir("misc/scripts/alignment/phone_align")
pe("bash -x setup.sh 2>&1", shell=True)
with open("config.cfg", "r") as f:
config_lines = f.readlines()
# replace ESTDIR with the correct path
estdir_replace_line = None
for n, l in enumerate(config_lines):
if "ESTDIR=" in l and l[0] == "E":
estdir_replace_line = n
break
config_lines[estdir_replace_line] = "ESTDIR=%s\n" % estdir
# replace FESTDIR with the correct path
festdir_replace_line = None
for n, l in enumerate(config_lines):
# EST/FEST
if "FESTDIR=" in l and l[0] == "F":
festdir_replace_line = n
break
config_lines[festdir_replace_line] = "FESTDIR=%s\n" % festdir
# replace FESTVOXDIR with the correct path
festvoxdir_replace_line = None
for n, l in enumerate(config_lines):
if "FESTVOXDIR=" in l:
festvoxdir_replace_line = n
break
config_lines[festvoxdir_replace_line] = "FESTVOXDIR=%s\n" % festvoxdir
with open("config.cfg", "w") as f:
f.writelines(config_lines)
with open("run_aligner.sh", "r") as f:
run_aligner_lines = f.readlines()
replace_line = None
for n, l in enumerate(run_aligner_lines):
if "cp ../cmuarctic.data" in l:
replace_line = n
break
run_aligner_lines[replace_line] = "cp ../txt.done.data etc/txt.done.data\n"
# Make the txt.done.data file
def format_info_tup(info_tup):
return "( " + str(info_tup[0]) + ' "' + info_tup[1] + '" )\n'
# Now we need to get the text info
txt_partial_path = txt_path # vctkdir + "txt/"
cwd = os.getcwd()
out_path = "txt.done.data"
out_file = open(out_path, "w")
"""
subfolders = sorted(os.listdir(txt_partial_path))
# TODO: Avoid this truncation and have an option to select subfolder(s)...
subfolders = subfolder_select(subfolders)
txt_ids = []
for sf in subfolders:
print("Processing subfolder %s" % sf)
txt_sf_path = txt_partial_path + sf + "/"
for txtpath in os.listdir(txt_sf_path):
full_txtpath = txt_sf_path + txtpath
with open(full_txtpath, 'r') as f:
r = f.readlines()
assert len(r) == 1
# remove txt extension
name = txtpath.split(".")[0]
text = r[0].strip()
info_tup = (name, text)
txt_ids.append(name)
out_file.writelines(format_info_tup(info_tup))
"""
txt_ids = []
txt_l_path = txt_partial_path
for txtpath in os.listdir(txt_l_path):
print("Processing %s" % txtpath)
full_txtpath = txt_l_path + txtpath
name = txtpath.split(".")[0]
wavpath_matches = [fname.split(".")[0] for fname in os.listdir(wav_partial_path)
if name in fname]
for name in wavpath_matches:
# Need an extra level here for pavoque :/
with open(full_txtpath, 'r') as f:
r = f.readlines()
if len(r) == 0:
continue
if len(r) != 1:
new_r = []
for ri in r:
if ri != "\n":
new_r.append(ri)
r = new_r
if len(r) != 1:
print("Something wrong in text extraction, cowardly bailing to IPython")
from IPython import embed
embed()
raise ValueError()
assert len(r) == 1
# remove txt extension
text = r[0].strip()
info_tup = (name, text)
txt_ids.append(name)
out_file.writelines(format_info_tup(info_tup))
out_file.close()
pe("cp %s %s/txt.done.data" % (out_path, latest_feature_dir),
shell=True)
os.chdir(cwd)
replace_line = None
for n, l in enumerate(run_aligner_lines):
if "cp ../slt_wav/*.wav" in l:
replace_line = n
break
run_aligner_lines[replace_line] = "cp ../wav/*.wav wav\n"
# Put wav file in the correct place
wav_partial_path = experiment_dir + "/database/wav"
"""
subfolders = sorted(os.listdir(wav_partial_path))
"""
if not os.path.exists("wav"):
os.mkdir("wav")
cwd = os.getcwd()
os.chdir("wav")
"""
for sf in subfolders:
wav_path = wav_partial_path + "/*.wav"
pe("cp %s ." % wav_path, shell=True)
"""
wav_match_path = wav_partial_path + "/*.wav"
for fi in glob.glob(wav_match_path):
fi = re.escape(fi)
try:
pe("echo %s; cp %s ." % (fi, fi), shell=True)
except:
from IPython import embed
embed()
raise ValueError()
#pe("echo %s; cp %s ." % (fi, fi), shell=True)
#pe("cp %s ." % wav_match_path, shell=True)
os.chdir(cwd)
replace_line = None
for n, l in enumerate(run_aligner_lines):
if "cat cmuarctic.data |" in l:
replace_line = n
break
run_aligner_lines[replace_line] = 'cat txt.done.data | cut -d " " -f 2 > file_id_list.scp\n'
# FIXME
# Hackaround to avoid harcoded 30 in festivox do_ehmm
if not full_features:
bdir = os.getcwd()
# need to hack up run_aligner more..
# do setup manually
pe("mkdir cmu_us_slt_arctic", shell=True)
os.chdir("cmu_us_slt_arctic")
pe("%s/src/clustergen/setup_cg cmu us slt_arctic" % festvoxdir, shell=True)
pe("cp ../txt.done.data etc/txt.done.data", shell=True)
wmp = "../wav/*.wav"
for fi in glob.glob(wmp):
fi = re.escape(fi)
try:
pe("echo %s; cp %s wav/" % (fi, fi), shell=True)
except:
from IPython import embed
embed()
raise ValueError()
#pe("echo %s; cp %s wav/" % (fi, fi), shell=True)
#pe("cp ../wav/*.wav wav/", shell=True)
# remove top part but keep cd call
run_aligner_lines = run_aligner_lines[:13] + \
["cd cmu_us_slt_arctic\n"] + run_aligner_lines[35:]
'''
# need to change do_build
# NO LONGER NECESSARY DUE TO FESTIVAL DEPENDENCE ON FILENAME
os.chdir("bin")
with open("do_build", "r") as f:
do_build_lines = f.readlines()
replace_line = None
for n, l in enumerate(do_build_lines):
if "$FESTVOXDIR/src/ehmm/bin/do_ehmm" in l:
replace_line = n
break
do_build_lines[replace_line] = " $FESTVOXDIR/src/ehmm/bin/do_ehmm\n"
# FIXME Why does this hang when not overwritten???
with open("edit_do_build", "w") as f:
f.writelines(do_build_lines)
'''
# need to change do_ehmm
os.chdir(festvoxdir)
os.chdir("src/ehmm/bin/")
# this is to fix festival if we somehow kill in the middle of training :(
# all due to festival's apparent dependence on name of script!
# really, really, REALLY weird
if os.path.exists("do_ehmm.bak"):
with open("do_ehmm.bak", "r") as f:
fix = f.readlines()
with open("do_ehmm", "w") as f:
f.writelines(fix)
with open("do_ehmm", "r") as f:
do_ehmm_lines = f.readlines()
with open("do_ehmm.bak", "w") as f:
f.writelines(do_ehmm_lines)
replace_line = None
for n, l in enumerate(do_ehmm_lines):
if "$EHMMDIR/bin/ehmm ehmm/etc/ph_list.int" in l:
replace_line = n
break
max_n_itr = ehmm_max_n_itr
do_ehmm_lines[replace_line] = " $EHMMDIR/bin/ehmm ehmm/etc/ph_list.int ehmm/etc/txt.phseq.data.int 1 0 ehmm/binfeat scaledft ehmm/mod 0 0 0 %s $num_cpus\n" % str(
max_n_itr)
# depends on *name* of the script?????????
with open("do_ehmm", "w") as f:
f.writelines(do_ehmm_lines)
# need to edit run_aligner....
dbn = "do_build"
# FIXME
# WHY DOES IT DEPEND ON FILENAME????!!!!!??????
# should be able to call only edit_do_build label
# but hangs indefinitely...
replace_line = None
for n, l in enumerate(run_aligner_lines):
if "./bin/do_build build_prompts" in l:
replace_line = n
break
run_aligner_lines[replace_line] = "./bin/%s build_prompts\n" % dbn
replace_line = None
for n, l in enumerate(run_aligner_lines):
if "./bin/do_build label" in l:
replace_line = n
break
run_aligner_lines[replace_line] = "./bin/%s label\n" % dbn
replace_line = None
for n, l in enumerate(run_aligner_lines):
if "./bin/do_build build_utts" in l:
replace_line = n
break
run_aligner_lines[replace_line] = "./bin/%s build_utts\n" % dbn
os.chdir(bdir)
with open("edit_run_aligner.sh", "w") as f:
f.writelines(run_aligner_lines)
# 2>&1 needed to make it work?? really sketchy
pe("bash -x edit_run_aligner.sh config.cfg 2>&1", shell=True)
# compile vocoder
os.chdir(merlin_dir)
# set it to run on cpu
pe("sed -i.bak -e s/MERLIN_THEANO_FLAGS=.*/MERLIN_THEANO_FLAGS='device=cpu,floatX=float32,on_unused_input=ignore'/g src/setup_env.sh", shell=True)
os.chdir("tools")
if not os.path.exists("SPTK-3.9"):
pe("bash -x compile_tools.sh 2>&1", shell=True)
# slt_arctic stuff
os.chdir(merlin_dir)
os.chdir("egs/slt_arctic/s1")
# This madness due to autogen configs...
pe("bash -x scripts/setup.sh slt_arctic_full 2>&1", shell=True)
global_config_file = "conf/global_settings.cfg"
replace_write(global_config_file, "Labels", "phone_align", replace_line="%s=%s\n")
replace_write(global_config_file, "Train", "1132", replace_line="%s=%s\n")
replace_write(global_config_file, "Valid", "0", replace_line="%s=%s\n")
replace_write(global_config_file, "Test", "0", replace_line="%s=%s\n")
pe("bash -x scripts/prepare_config_files.sh %s 2>&1" % global_config_file, shell=True)
pe("bash -x scripts/prepare_config_files_for_synthesis.sh %s 2>&1" % global_config_file, shell=True)
# delete the setup lines from run_full_voice.sh
pe("sed -i.bak -e '11d;12d;13d' run_full_voice.sh", shell=True)
pushd = os.getcwd()
os.chdir("conf")
acoustic_conf = "acoustic_slt_arctic_full.conf"
replace_write(acoustic_conf, "train_file_number", "1132")
replace_write(acoustic_conf, "valid_file_number", "0")
replace_write(acoustic_conf, "test_file_number", "0")
replace_write(acoustic_conf, "label_type", "phone_align")
replace_write(acoustic_conf, "subphone_feats", "coarse_coding")
replace_write(acoustic_conf, "dmgc", "60")
replace_write(acoustic_conf, "dbap", "1")
# hack this to add an extra line in the config
replace_write(acoustic_conf, "dlf0", "1\ndo_MLPG: False")
if not full_features:
replace_write(acoustic_conf, "warmup_epoch", "1")
replace_write(acoustic_conf, "training_epochs", "1")
replace_write(acoustic_conf, "TRAINDNN", "False")
replace_write(acoustic_conf, "DNNGEN", "False")
replace_write(acoustic_conf, "GENWAV", "False")
replace_write(acoustic_conf, "CALMCD", "False")
duration_conf = "duration_slt_arctic_full.conf"
replace_write(duration_conf, "train_file_number", "1132")
replace_write(duration_conf, "valid_file_number", "0")
replace_write(duration_conf, "test_file_number", "0")
replace_write(duration_conf, "label_type", "phone_align")
replace_write(duration_conf, "dur", "1")
if not full_features:
replace_write(duration_conf, "warmup_epoch", "1")
replace_write(duration_conf, "training_epochs", "1")
replace_write(duration_conf, "TRAINDNN", "False")
replace_write(duration_conf, "DNNGEN", "False")
replace_write(duration_conf, "CALMCD", "False")
os.chdir(pushd)
if not os.path.exists("slt_arctic_full_data"):
pe("bash -x run_full_voice.sh 2>&1", shell=True)
pe("mv run_full_voice.sh.bak run_full_voice.sh", shell=True)
os.chdir(merlin_dir)
os.chdir("misc/scripts/vocoder/world")
with open("extract_features_for_merlin.sh", "r") as f:
ex_lines = f.readlines()
ex_line_replace = None
for n, l in enumerate(ex_lines):
if "merlin_dir=" in l:
ex_line_replace = n
break
ex_lines[ex_line_replace] = 'merlin_dir="%s"' % merlin_dir
ex_line_replace = None
for n, l in enumerate(ex_lines):
if "wav_dir=" in l:
ex_line_replace = n
break
ex_lines[ex_line_replace] = 'wav_dir="%s"' % (experiment_dir + "/database/wav")
with open("edit_extract_features_for_merlin.sh", "w") as f:
f.writelines(ex_lines)
pe("bash -x edit_extract_features_for_merlin.sh 2>&1", shell=True)
os.chdir(basedir)
os.chdir("latest_features")
os.symlink(merlin_dir + "/egs/slt_arctic/s1/slt_arctic_full_data/feat", "audio_feat")
os.symlink(merlin_dir + "/misc/scripts/alignment/phone_align/full-context-labels/full", "text_feat")
print("Audio features in %s (and %s)" % (os.getcwd() + "/audio_feat",
merlin_dir + "/egs/slt_arctic/s1/slt_arctic_full_data/feat"))
print("Text features in %s (and %s)" % (os.getcwd() + "/text_feat", merlin_dir +
"/misc/scripts/alignment/phone_align/full-context-labels/full"))
os.chdir(basedir)
def extract_final_features():
launchdir = os.getcwd()
os.chdir("latest_features")
basedir = os.path.abspath(os.getcwd()) + "/"
text_files = os.listdir("text_feat")
audio_files = os.listdir("audio_feat/bap")
os.chdir("merlin/egs/build_your_own_voice/s1")
expdir = os.getcwd()
# make the file list
file_list_base = "experiments/my_new_voice/duration_model/data/"
if not os.path.exists(file_list_base):
os.mkdir(file_list_base)
file_list_path = file_list_base + "file_id_list_full.scp"
with open(file_list_path, "w") as f:
f.writelines([tef.split(".")[0] + "\n" for tef in text_files])
if not os.path.exists(basedir + "file_id_list_full.scp"):
os.symlink(os.path.abspath(file_list_path),
os.path.abspath(basedir + "file_id_list_full.scp"))
# make the file list
file_list_base = "experiments/my_new_voice/acoustic_model/data/"
if not os.path.exists(file_list_base):
os.mkdir(file_list_base)
file_list_path = file_list_base + "file_id_list_full.scp"
with open(file_list_path, "w") as f:
f.writelines([tef.split(".")[0] + "\n" for tef in text_files])
if not os.path.exists(basedir + "file_id_list_full.scp"):
os.symlink(os.path.abspath(file_list_path),
os.path.abspath(basedir + "file_id_list_full.scp"))
file_list_base = "experiments/my_new_voice/test_synthesis/"
if not os.path.exists(file_list_base):
os.mkdir(file_list_base)
file_list_path = file_list_base + "test_id_list.scp"
# debug with no test utterances
with open(file_list_path, "w") as f:
# f.writelines(["\n",])
f.writelines([tef.split(".")[0] + "\n" for tef in text_files[:20]])
if not os.path.exists(basedir + "test_id_list.scp"):
os.symlink(os.path.abspath(file_list_path), os.path.abspath(basedir + "test_id_list.scp"))
# now copy in the data - don't symlink due to possibilities of inplace
# modification
os.chdir(expdir)
basedatadir = "experiments/my_new_voice/"
os.chdir(basedatadir)
labeldatadir = "duration_model/data/label_phone_align"
if not os.path.exists(labeldatadir):
os.mkdir(labeldatadir)
# IT USES HTS STYLE LABELS
copytree(basedir + "text_feat", labeldatadir)
labeldatadir = "acoustic_model/data/label_phone_align"
if not os.path.exists(labeldatadir):
os.mkdir(labeldatadir)
bapdatadir = "acoustic_model/data/bap"
if not os.path.exists(bapdatadir):
os.mkdir(bapdatadir)
lf0datadir = "acoustic_model/data/lf0"
if not os.path.exists(lf0datadir):
os.mkdir(lf0datadir)
mgcdatadir = "acoustic_model/data/mgc"
if not os.path.exists(mgcdatadir):
os.mkdir(mgcdatadir)
# IT USES HTS STYLE LABELS
copytree(basedir + "text_feat", labeldatadir)
copytree(basedir + "audio_feat/bap", bapdatadir)
copytree(basedir + "audio_feat/lf0", lf0datadir)
copytree(basedir + "audio_feat/mgc", mgcdatadir)
#pe("cp %s acoustic_model/data" % "label_norm_HTS_420.dat")
while len(os.listdir(mgcdatadir)) < len(os.listdir(basedir + "audio_feat/mgc")):
print("waiting for mgc file copy to complete...")
time.sleep(3)
while len(os.listdir(lf0datadir)) < len(os.listdir(basedir + "audio_feat/lf0")):
print("waiting for lf0 file copy to complete...")
time.sleep(3)
while len(os.listdir(bapdatadir)) < len(os.listdir(basedir + "audio_feat/bap")):
print("waiting for bap file copy to complete...")
time.sleep(3)
num_audio_files = len(os.listdir(mgcdatadir))
num_label_files = len(os.listdir(labeldatadir))
num_files = min([num_audio_files, num_label_files])
os.chdir(expdir)
global_config_file = "conf/global_settings.cfg"
pe("bash -x scripts/prepare_config_files.sh %s 2>&1" % global_config_file, shell=True)
pe("bash -x scripts/prepare_config_files_for_synthesis.sh %s 2>&1" % global_config_file, shell=True)
# this actally won't matter I don't think...
replace_write(global_config_file, "Train", str(num_files), replace_line="%s=%s\n")
replace_write(global_config_file, "Valid", "0", replace_line="%s=%s\n")
replace_write(global_config_file, "Test", "0", replace_line="%s=%s\n")
acoustic_conf = "conf/acoustic_my_new_voice.conf"
replace_write(acoustic_conf, "train_file_number", str(num_files))
replace_write(acoustic_conf, "valid_file_number", "0")
replace_write(acoustic_conf, "test_file_number", "0")
replace_write(acoustic_conf, "label_type", "phone_align")
replace_write(acoustic_conf, "subphone_feats", "coarse_coding")
replace_write(acoustic_conf, "dmgc", "60")
replace_write(acoustic_conf, "dbap", "1")
# hack this to add an extra line in the config
replace_write(acoustic_conf, "dlf0", "1\ndo_MLPG: False")
if not full_features:
replace_write(acoustic_conf, "warmup_epoch", "1")
replace_write(acoustic_conf, "training_epochs", "1")
replace_write(acoustic_conf, "TRAINDNN", "False")
replace_write(acoustic_conf, "DNNGEN", "False")
replace_write(acoustic_conf, "GENWAV", "False")
replace_write(acoustic_conf, "CALMCD", "False")
duration_conf = "conf/duration_my_new_voice.conf"
replace_write(duration_conf, "train_file_number", str(num_files))
replace_write(duration_conf, "valid_file_number", "0")
replace_write(duration_conf, "test_file_number", "0")
replace_write(duration_conf, "label_type", "phone_align")
replace_write(duration_conf, "dur", "1")
if not full_features:
replace_write(duration_conf, "warmup_epoch", "1")
replace_write(duration_conf, "training_epochs", "1")
'''
replace_write("conf/acoustic_my_new_voice.conf", "train_file_number", str(num_files))
replace_write("conf/acoustic_my_new_voice.conf", "valid_file_number", "0")
replace_write("conf/acoustic_my_new_voice.conf", "test_file_number", "0")
replace_write("conf/acoustic_my_new_voice.conf", "dmgc", "60")
replace_write("conf/acoustic_my_new_voice.conf", "dbap", "1")
# hack this to add an extra line in the config
replace_write("conf/acoustic_my_new_voice.conf", "dlf0", "1\ndo_MLPG: False")
replace_write("conf/acoustic_my_new_voice.conf", "TRAINDNN", "False")
replace_write("conf/acoustic_my_new_voice.conf", "DNNGEN", "False")
replace_write("conf/acoustic_my_new_voice.conf", "GENWAV", "False")
replace_write("conf/acoustic_my_new_voice.conf", "CALMCD", "False")
replace_write("conf/duration_my_new_voice.conf", "train_file_number", str(num_files))
replace_write("conf/duration_my_new_voice.conf", "valid_file_number", "0")
replace_write("conf/duration_my_new_voice.conf", "test_file_number", "0")
replace_write("conf/duration_my_new_voice.conf", "TRAINDNN", "False")
replace_write("conf/duration_my_new_voice.conf", "DNNGEN", "False")
replace_write("conf/duration_my_new_voice.conf", "CALMCD", "False")
'''
pe("sed -i.bak -e '19,20d;30,39d' 03_run_merlin.sh", shell=True)
pe("bash -x 03_run_merlin.sh 2>&1", shell=True)
pe("mv 03_run_merlin.sh.bak 03_run_merlin.sh", shell=True)
if not os.path.exists(basedir + "final_acoustic_data"):
os.symlink(os.path.abspath("experiments/my_new_voice/acoustic_model/data"),
basedir + "final_acoustic_data")
if not os.path.exists(basedir + "final_duration_data"):
os.symlink(os.path.abspath("experiments/my_new_voice/duration_model/data"),
basedir + "final_duration_data")
os.chdir(launchdir)
def save_numpy_features():
n_ins = 420
n_outs = 63 # 187
feature_dir = "latest_features/"
with open(feature_dir + "file_id_list_full.scp") as f:
file_list = [l.strip() for l in f.readlines()]
norm_info_dir = os.path.abspath("latest_features/norm_info/") + "/"
if not os.path.exists(norm_info_dir):
os.mkdir(norm_info_dir)
acoustic_dir = os.path.abspath(feature_dir + "final_acoustic_data/") + "/"
audio_norm_file = "norm_info_mgc_lf0_vuv_bap_%s_MVN.dat" % str(n_outs)
audio_norm_source = acoustic_dir + audio_norm_file
audio_norm_dest = norm_info_dir + audio_norm_file
shutil.copy2(audio_norm_source, audio_norm_dest)
with open(audio_norm_source) as fid:
cmp_info = np.fromfile(fid, dtype=np.float32)
cmp_info = cmp_info.reshape((2, -1))
audio_norm = cmp_info
label_norm_file = "label_norm_HTS_%s.dat" % n_ins
label_norm_source = acoustic_dir + label_norm_file
label_norm_dest = norm_info_dir + label_norm_file
shutil.copy2(label_norm_source, label_norm_dest)
with open(label_norm_source) as fid:
cmp_info = np.fromfile(fid, dtype=np.float32)
cmp_info = cmp_info.reshape((2, -1))
label_norm = cmp_info
text_file = feature_dir + 'txt.done.data'
with open(text_file) as f:
text_data = [l.strip() for l in f.readlines()]
monophone_path = os.path.abspath("latest_features/monophones") + "/"
if not os.path.exists(monophone_path):
# Trailing "/" causes issues
os.symlink(os.path.abspath(
"latest_features/merlin/misc/scripts/alignment/phone_align/cmu_us_slt_arctic/lab"), monophone_path[:-1])
launchdir = os.getcwd()
phone_files = {gl[:-4]: monophone_path + gl for gl in os.listdir(monophone_path)
if gl[-4:] == ".lab"}
text_ids = [td.split(" ")[1] for td in text_data]
label_files_path = os.path.abspath(
"latest_features/final_acoustic_data/nn_no_silence_lab_420") + "/"
# still has silence in it?
#audio_files_path = os.path.abspath("latest_features/final_acoustic_data/nn_mgc_lf0_vuv_bap_63") + "/"
audio_files_path = os.path.abspath(
"latest_features/final_acoustic_data/nn_norm_mgc_lf0_vuv_bap_63") + "/"
label_files = {lf[:-4]: label_files_path +
lf for lf in os.listdir(label_files_path) if lf[-4:] == ".lab"}
audio_files = {af[:-4]: audio_files_path +
af for af in os.listdir(audio_files_path) if af[-4:] == ".cmp"}
error_files = [
(i, x) for i, x in enumerate(text_ids) if x not in file_list]
# Solve corrupted files issues
for i, x in error_files:
try:
text_ids.remove(x)
except ValueError:
pass
try:
file_list.remove(x)
except ValueError:
pass
text_data = [td for td in text_data if td.split(" ")[1] != x]
text_utts = [td.split('"')[1] for td in text_data]
text_tups = list(zip(text_ids, text_utts))
text_lu = {k: v for k, v in text_tups}
text_rlu = {v: k for k, v in text_lu.items()}
# take only valid subset.... ?
new_file_list = []
text_tup_fnames = [tt[0] for tt in text_tups]
for n, fname in enumerate(file_list):
if fname in text_tup_fnames:
new_file_list.append(fname)
file_list = new_file_list
new_text_tups = []
for n, ttup in enumerate(text_tups):
if ttup[0] in file_list:
new_text_tups.append(ttup)
text_tups = new_text_tups
# why on earth should this fail
#assert len(text_tups) == len(file_list)
assert sum([ti not in file_list for ti in text_ids]) == 0
char_set = sorted(list(set(''.join(text_utts).lower())))
char2code = {x: i for i, x in enumerate(char_set)}
code2char = {v: k for k, v in char2code.items()}
phone_set = tuple('sil',)
for fid in file_list:
with open(phone_files[fid]) as f:
phonemes = [p.strip() for p in f.readlines()]
# FIXME: Bug here that allows filenames in
phonemes = [x.strip().split(' ') for x in phonemes[1:]]
durations, phonemes = zip(*[[float(x), z] for x, y, z in phonemes])
phone_set = tuple(sorted(list(set(phone_set + phonemes))))
phone2code = {x: i for i, x in enumerate(phone_set)}
code2phone = {v: k for k, v in phone2code.items()}
order = range(len(file_list))
np.random.seed(1)
np.random.shuffle(order)
all_in_features = []
all_out_features = []
all_phonemes = []
all_durations = []
all_text = []
all_ids = []
for i, idx in enumerate(order):
fid = file_list[idx]
# if i % 100 == 0:
# print(i)
in_features, lab_frame_number = load_binary_file_frame(
label_files[fid], n_ins)
out_features, out_frame_number = load_binary_file_frame(
audio_files[fid], n_outs)