forked from espnet/espnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmcd_calculate.py
executable file
·282 lines (213 loc) · 7.14 KB
/
mcd_calculate.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
#!/usr/bin/env python3
# encoding: utf-8
# Copyright 2020 Nagoya University (Wen-Chin Huang)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
# Calculate MCD using converted waveform.
import argparse
import fnmatch
import multiprocessing as mp
import os
from fastdtw import fastdtw
import numpy as np
import pysptk
import pyworld as pw
import scipy
from scipy.io import wavfile
from scipy.signal import firwin
from scipy.signal import lfilter
def find_files(root_dir, query="*.wav", include_root_dir=True):
"""Find files recursively.
Args:
root_dir (str): Root root_dir to find.
query (str): Query to find.
include_root_dir (bool): If False, root_dir name is not included.
Returns:
list: List of found filenames.
"""
files = []
for root, dirnames, filenames in os.walk(root_dir, followlinks=True):
for filename in fnmatch.filter(filenames, query):
files.append(os.path.join(root, filename))
if not include_root_dir:
files = [file_.replace(root_dir + "/", "") for file_ in files]
return files
def low_cut_filter(x, fs, cutoff=70):
"""FUNCTION TO APPLY LOW CUT FILTER
Args:
x (ndarray): Waveform sequence
fs (int): Sampling frequency
cutoff (float): Cutoff frequency of low cut filter
Return:
(ndarray): Low cut filtered waveform sequence
"""
nyquist = fs // 2
norm_cutoff = cutoff / nyquist
# low cut filter
fil = firwin(255, norm_cutoff, pass_zero=False)
lcf_x = lfilter(fil, 1, x)
return lcf_x
def spc2npow(spectrogram):
"""Calculate normalized power sequence from spectrogram
Parameters
----------
spectrogram : array, shape (T, `fftlen / 2 + 1`)
Array of spectrum envelope
Return
------
npow : array, shape (`T`, `1`)
Normalized power sequence
"""
# frame based processing
npow = np.apply_along_axis(_spvec2pow, 1, spectrogram)
meanpow = np.mean(npow)
npow = 10.0 * np.log10(npow / meanpow)
return npow
def _spvec2pow(specvec):
"""Convert a spectrum envelope into a power
Parameters
----------
specvec : vector, shape (`fftlen / 2 + 1`)
Vector of specturm envelope |H(w)|^2
Return
------
power : scala,
Power of a frame
"""
# set FFT length
fftl2 = len(specvec) - 1
fftl = fftl2 * 2
# specvec is not amplitude spectral |H(w)| but power spectral |H(w)|^2
power = specvec[0] + specvec[fftl2]
for k in range(1, fftl2):
power += 2.0 * specvec[k]
power /= fftl
return power
def extfrm(data, npow, power_threshold=-20):
"""Extract frame over the power threshold
Parameters
----------
data: array, shape (`T`, `dim`)
Array of input data
npow : array, shape (`T`)
Vector of normalized power sequence.
power_threshold : float, optional
Value of power threshold [dB]
Default set to -20
Returns
-------
data: array, shape (`T_ext`, `dim`)
Remaining data after extracting frame
`T_ext` <= `T`
"""
T = data.shape[0]
if T != len(npow):
raise ("Length of two vectors is different.")
valid_index = np.where(npow > power_threshold)
extdata = data[valid_index]
assert extdata.shape[0] <= T
return extdata
def world_extract(wav_path, args):
fs, x = wavfile.read(wav_path)
x = np.array(x, dtype=np.float64)
x = low_cut_filter(x, fs)
# extract features
f0, time_axis = pw.harvest(
x, fs, f0_floor=args.f0min, f0_ceil=args.f0max, frame_period=args.shiftms
)
sp = pw.cheaptrick(x, f0, time_axis, fs, fft_size=args.fftl)
ap = pw.d4c(x, f0, time_axis, fs, fft_size=args.fftl)
mcep = pysptk.sp2mc(sp, args.mcep_dim, args.mcep_alpha)
npow = spc2npow(sp)
return {
"sp": sp,
"mcep": mcep,
"ap": ap,
"f0": f0,
"npow": npow,
}
def get_basename(path):
return os.path.splitext(os.path.split(path)[-1])[0]
def calculate(file_list, gt_file_list, args, MCD):
for i, cvt_path in enumerate(file_list):
corresponding_list = list(
filter(lambda gt_path: get_basename(gt_path) in cvt_path, gt_file_list)
)
assert len(corresponding_list) == 1
gt_path = corresponding_list[0]
gt_basename = get_basename(gt_path)
# extract ground truth and converted features
gt_feats = world_extract(gt_path, args)
cvt_feats = world_extract(cvt_path, args)
# VAD & DTW based on power
gt_mcep_nonsil_pow = extfrm(gt_feats["mcep"], gt_feats["npow"])
cvt_mcep_nonsil_pow = extfrm(cvt_feats["mcep"], cvt_feats["npow"])
_, path = fastdtw(
cvt_mcep_nonsil_pow,
gt_mcep_nonsil_pow,
dist=scipy.spatial.distance.euclidean,
)
twf_pow = np.array(path).T
# MCD using power-based DTW
cvt_mcep_dtw_pow = cvt_mcep_nonsil_pow[twf_pow[0]]
gt_mcep_dtw_pow = gt_mcep_nonsil_pow[twf_pow[1]]
diff2sum = np.sum((cvt_mcep_dtw_pow - gt_mcep_dtw_pow) ** 2, 1)
mcd = np.mean(10.0 / np.log(10.0) * np.sqrt(2 * diff2sum), 0)
print("{} {}".format(gt_basename, mcd))
MCD.append(mcd)
def get_parser():
parser = argparse.ArgumentParser(description="calculate MCD.")
parser.add_argument(
"--wavdir",
required=True,
type=str,
help="path of directory for converted waveforms",
)
parser.add_argument(
"--gtwavdir",
required=True,
type=str,
help="path of directory for ground truth waveforms",
)
# analysis related
parser.add_argument(
"--mcep_dim", default=41, type=int, help="dimension of mel cepstrum coefficient"
)
parser.add_argument(
"--mcep_alpha", default=0.41, type=int, help="all pass constant"
)
parser.add_argument("--fftl", default=1024, type=int, help="fft length")
parser.add_argument("--shiftms", default=5, type=int, help="frame shift (ms)")
parser.add_argument(
"--f0min", required=True, type=int, help="fo search range (min)"
)
parser.add_argument(
"--f0max", required=True, type=int, help="fo search range (max)"
)
parser.add_argument(
"--n_jobs", default=40, type=int, help="number of parallel jobs"
)
return parser
def main():
args = get_parser().parse_args()
# find files
converted_files = sorted(find_files(args.wavdir))
gt_files = sorted(find_files(args.gtwavdir))
# Get and divide list
print("number of utterances = %d" % len(converted_files))
file_lists = np.array_split(converted_files, args.n_jobs)
file_lists = [f_list.tolist() for f_list in file_lists]
# multi processing
with mp.Manager() as manager:
MCD = manager.list()
processes = []
for f in file_lists:
p = mp.Process(target=calculate, args=(f, gt_files, args, MCD))
p.start()
processes.append(p)
# wait for all process
for p in processes:
p.join()
mMCD = np.mean(np.array(MCD))
print("Mean MCD: {:.2f}".format(mMCD))
if __name__ == "__main__":
main()