-
Notifications
You must be signed in to change notification settings - Fork 412
/
noisyspeech_synthesizer_singleprocess.py
541 lines (424 loc) · 21.3 KB
/
noisyspeech_synthesizer_singleprocess.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
"""
@author: chkarada
"""
# Note: This single process audio synthesizer will attempt to use each clean
# speech sourcefile once, as it does not randomly sample from these files
import os
import sys
import glob
import argparse
import ast
import configparser as CP
from random import shuffle
import random
import librosa
import numpy as np
from scipy import signal
from audiolib import audioread, audiowrite, segmental_snr_mixer, activitydetector, is_clipped, add_clipping
import utils
import pandas as pd
from pathlib import Path
from scipy.io import wavfile
MAXTRIES = 50
MAXFILELEN = 100
np.random.seed(5)
random.seed(5)
def add_pyreverb(clean_speech, rir):
reverb_speech = signal.fftconvolve(clean_speech, rir, mode="full")
# make reverb_speech same length as clean_speech
reverb_speech = reverb_speech[0 : clean_speech.shape[0]]
return reverb_speech
def build_audio(is_clean, params, index, audio_samples_length=-1):
'''Construct an audio signal from source files'''
fs_output = params['fs']
silence_length = params['silence_length']
if audio_samples_length == -1:
audio_samples_length = int(params['audio_length']*params['fs'])
output_audio = np.zeros(0)
remaining_length = audio_samples_length
files_used = []
clipped_files = []
if is_clean:
source_files = params['cleanfilenames']
idx = index
else:
if 'noisefilenames' in params.keys():
source_files = params['noisefilenames']
idx = index
# if noise files are organized into individual subdirectories, pick a directory randomly
else:
noisedirs = params['noisedirs']
# pick a noise category randomly
idx_n_dir = np.random.randint(0, np.size(noisedirs))
source_files = glob.glob(os.path.join(noisedirs[idx_n_dir],
params['audioformat']))
shuffle(source_files)
# pick a noise source file index randomly
idx = np.random.randint(0, np.size(source_files))
# initialize silence
silence = np.zeros(int(fs_output*silence_length))
# iterate through multiple clips until we have a long enough signal
tries_left = MAXTRIES
while remaining_length > 0 and tries_left > 0:
# read next audio file and resample if necessary
idx = (idx + 1) % np.size(source_files)
input_audio, fs_input = audioread(source_files[idx])
if input_audio is None:
sys.stderr.write("WARNING: Cannot read file: %s\n" % source_files[idx])
continue
if fs_input != fs_output:
input_audio = librosa.resample(input_audio, fs_input, fs_output)
# if current file is longer than remaining desired length, and this is
# noise generation or this is training set, subsample it randomly
if len(input_audio) > remaining_length and (not is_clean or not params['is_test_set']):
idx_seg = np.random.randint(0, len(input_audio)-remaining_length)
input_audio = input_audio[idx_seg:idx_seg+remaining_length]
# check for clipping, and if found move onto next file
if is_clipped(input_audio):
clipped_files.append(source_files[idx])
tries_left -= 1
continue
# concatenate current input audio to output audio stream
files_used.append(source_files[idx])
output_audio = np.append(output_audio, input_audio)
remaining_length -= len(input_audio)
# add some silence if we have not reached desired audio length
if remaining_length > 0:
silence_len = min(remaining_length, len(silence))
output_audio = np.append(output_audio, silence[:silence_len])
remaining_length -= silence_len
if tries_left == 0 and not is_clean and 'noisedirs' in params.keys():
print("There are not enough non-clipped files in the " + noisedirs[idx_n_dir] + \
" directory to complete the audio build")
return [], [], clipped_files, idx
return output_audio, files_used, clipped_files, idx
def gen_audio(is_clean, params, index, audio_samples_length=-1):
'''Calls build_audio() to get an audio signal, and verify that it meets the
activity threshold'''
clipped_files = []
low_activity_files = []
if audio_samples_length == -1:
audio_samples_length = int(params['audio_length']*params['fs'])
if is_clean:
activity_threshold = params['clean_activity_threshold']
else:
activity_threshold = params['noise_activity_threshold']
while True:
audio, source_files, new_clipped_files, index = \
build_audio(is_clean, params, index, audio_samples_length)
clipped_files += new_clipped_files
if len(audio) < audio_samples_length:
continue
if activity_threshold == 0.0:
break
percactive = activitydetector(audio=audio)
if percactive > activity_threshold:
break
else:
low_activity_files += source_files
return audio, source_files, clipped_files, low_activity_files, index
def main_gen(params):
'''Calls gen_audio() to generate the audio signals, verifies that they meet
the requirements, and writes the files to storage'''
clean_source_files = []
clean_clipped_files = []
clean_low_activity_files = []
noise_source_files = []
noise_clipped_files = []
noise_low_activity_files = []
clean_index = 0
noise_index = 0
file_num = params['fileindex_start']
while file_num <= params['fileindex_end']:
# generate clean speech
clean, clean_sf, clean_cf, clean_laf, clean_index = \
gen_audio(True, params, clean_index)
# add reverb with selected RIR
rir_index = random.randint(0,len(params['myrir'])-1)
my_rir = os.path.normpath(os.path.join('datasets', 'impulse_responses', params['myrir'][rir_index]))
(fs_rir,samples_rir) = wavfile.read(my_rir)
my_channel = int(params['mychannel'][rir_index])
if samples_rir.ndim==1:
samples_rir_ch = np.array(samples_rir)
elif my_channel > 1:
samples_rir_ch = samples_rir[:, my_channel -1]
else:
samples_rir_ch = samples_rir[:, my_channel -1]
#print(samples_rir.shape)
#print(my_channel)
clean = add_pyreverb(clean, samples_rir_ch)
# generate noise
noise, noise_sf, noise_cf, noise_laf, noise_index = \
gen_audio(False, params, noise_index, len(clean))
clean_clipped_files += clean_cf
clean_low_activity_files += clean_laf
noise_clipped_files += noise_cf
noise_low_activity_files += noise_laf
# get rir files and config
# mix clean speech and noise
# if specified, use specified SNR value
if not params['randomize_snr']:
snr = params['snr']
# use a randomly sampled SNR value between the specified bounds
else:
snr = np.random.randint(params['snr_lower'], params['snr_upper'])
clean_snr, noise_snr, noisy_snr, target_level = segmental_snr_mixer(params=params,
clean=clean,
noise=noise,
snr=snr)
# Uncomment the below lines if you need segmental SNR and comment the above lines using snr_mixer
#clean_snr, noise_snr, noisy_snr, target_level = segmental_snr_mixer(params=params,
# clean=clean,
# noise=noise,
# snr=snr)
# unexpected clipping
if is_clipped(clean_snr) or is_clipped(noise_snr) or is_clipped(noisy_snr):
print("Warning: File #" + str(file_num) + " has unexpected clipping, " + \
"returning without writing audio to disk")
continue
clean_source_files += clean_sf
noise_source_files += noise_sf
# write resultant audio streams to files
hyphen = '-'
clean_source_filenamesonly = [i[:-4].split(os.path.sep)[-1] for i in clean_sf]
clean_files_joined = hyphen.join(clean_source_filenamesonly)[:MAXFILELEN]
noise_source_filenamesonly = [i[:-4].split(os.path.sep)[-1] for i in noise_sf]
noise_files_joined = hyphen.join(noise_source_filenamesonly)[:MAXFILELEN]
noisyfilename = clean_files_joined + '_' + noise_files_joined + '_snr' + \
str(snr) + '_tl' + str(target_level) + '_fileid_' + str(file_num) + '.wav'
cleanfilename = 'clean_fileid_'+str(file_num)+'.wav'
noisefilename = 'noise_fileid_'+str(file_num)+'.wav'
noisypath = os.path.join(params['noisyspeech_dir'], noisyfilename)
cleanpath = os.path.join(params['clean_proc_dir'], cleanfilename)
noisepath = os.path.join(params['noise_proc_dir'], noisefilename)
audio_signals = [noisy_snr, clean_snr, noise_snr]
file_paths = [noisypath, cleanpath, noisepath]
file_num += 1
for i in range(len(audio_signals)):
try:
audiowrite(file_paths[i], audio_signals[i], params['fs'])
except Exception as e:
print(str(e))
return clean_source_files, clean_clipped_files, clean_low_activity_files, \
noise_source_files, noise_clipped_files, noise_low_activity_files
def main_body():
'''Main body of this file'''
parser = argparse.ArgumentParser()
# Configurations: read noisyspeech_synthesizer.cfg and gather inputs
parser.add_argument('--cfg', default='noisyspeech_synthesizer.cfg',
help='Read noisyspeech_synthesizer.cfg for all the details')
parser.add_argument('--cfg_str', type=str, default='noisy_speech')
args = parser.parse_args()
params = dict()
params['args'] = args
cfgpath = os.path.join(os.path.dirname(__file__), args.cfg)
assert os.path.exists(cfgpath), f'No configuration file as [{cfgpath}]'
cfg = CP.ConfigParser()
cfg._interpolation = CP.ExtendedInterpolation()
cfg.read(cfgpath)
params['cfg'] = cfg._sections[args.cfg_str]
cfg = params['cfg']
clean_dir = os.path.join(os.path.dirname(__file__), 'datasets/clean')
if cfg['speech_dir'] != 'None':
clean_dir = cfg['speech_dir']
if not os.path.exists(clean_dir):
assert False, ('Clean speech data is required')
noise_dir = os.path.join(os.path.dirname(__file__), 'datasets/noise')
if cfg['noise_dir'] != 'None':
noise_dir = cfg['noise_dir']
if not os.path.exists:
assert False, ('Noise data is required')
params['fs'] = int(cfg['sampling_rate'])
params['audioformat'] = cfg['audioformat']
params['audio_length'] = float(cfg['audio_length'])
params['silence_length'] = float(cfg['silence_length'])
params['total_hours'] = float(cfg['total_hours'])
# clean singing speech
params['use_singing_data'] = int(cfg['use_singing_data'])
params['clean_singing'] = str(cfg['clean_singing'])
params['singing_choice'] = int(cfg['singing_choice'])
# clean emotional speech
params['use_emotion_data'] = int(cfg['use_emotion_data'])
params['clean_emotion'] = str(cfg['clean_emotion'])
# clean mandarin speech
params['use_mandarin_data'] = int(cfg['use_mandarin_data'])
params['clean_mandarin'] = str(cfg['clean_mandarin'])
# rir
params['rir_choice'] = int(cfg['rir_choice'])
params['lower_t60'] = float(cfg['lower_t60'])
params['upper_t60'] = float(cfg['upper_t60'])
params['rir_table_csv'] = str(cfg['rir_table_csv'])
params['clean_speech_t60_csv'] = str(cfg['clean_speech_t60_csv'])
if cfg['fileindex_start'] != 'None' and cfg['fileindex_end'] != 'None':
params['num_files'] = int(cfg['fileindex_end'])-int(cfg['fileindex_start'])
params['fileindex_start'] = int(cfg['fileindex_start'])
params['fileindex_end'] = int(cfg['fileindex_end'])
else:
params['num_files'] = int((params['total_hours']*60*60)/params['audio_length'])
params['fileindex_start'] = 0
params['fileindex_end'] = params['num_files']
print('Number of files to be synthesized:', params['num_files'])
params['is_test_set'] = utils.str2bool(cfg['is_test_set'])
params['clean_activity_threshold'] = float(cfg['clean_activity_threshold'])
params['noise_activity_threshold'] = float(cfg['noise_activity_threshold'])
params['snr_lower'] = int(cfg['snr_lower'])
params['snr_upper'] = int(cfg['snr_upper'])
params['randomize_snr'] = utils.str2bool(cfg['randomize_snr'])
params['target_level_lower'] = int(cfg['target_level_lower'])
params['target_level_upper'] = int(cfg['target_level_upper'])
if 'snr' in cfg.keys():
params['snr'] = int(cfg['snr'])
else:
params['snr'] = int((params['snr_lower'] + params['snr_upper'])/2)
params['noisyspeech_dir'] = utils.get_dir(cfg, 'noisy_destination', 'noisy')
params['clean_proc_dir'] = utils.get_dir(cfg, 'clean_destination', 'clean')
params['noise_proc_dir'] = utils.get_dir(cfg, 'noise_destination', 'noise')
if 'speech_csv' in cfg.keys() and cfg['speech_csv'] != 'None':
cleanfilenames = pd.read_csv(cfg['speech_csv'])
cleanfilenames = cleanfilenames['filename']
else:
#cleanfilenames = glob.glob(os.path.join(clean_dir, params['audioformat']))
cleanfilenames= []
for path in Path(clean_dir).rglob('*.wav'):
cleanfilenames.append(str(path.resolve()))
shuffle(cleanfilenames)
# add singing voice to clean speech
if params['use_singing_data'] ==1:
all_singing= []
for path in Path(params['clean_singing']).rglob('*.wav'):
all_singing.append(str(path.resolve()))
if params['singing_choice']==1: # male speakers
mysinging = [s for s in all_singing if ("male" in s and "female" not in s)]
elif params['singing_choice']==2: # female speakers
mysinging = [s for s in all_singing if "female" in s]
elif params['singing_choice']==3: # both male and female
mysinging = all_singing
else: # default both male and female
mysinging = all_singing
shuffle(mysinging)
if mysinging is not None:
all_cleanfiles= cleanfilenames + mysinging
else:
all_cleanfiles= cleanfilenames
# add emotion data to clean speech
if params['use_emotion_data'] ==1:
all_emotion= []
for path in Path(params['clean_emotion']).rglob('*.wav'):
all_emotion.append(str(path.resolve()))
shuffle(all_emotion)
if all_emotion is not None:
all_cleanfiles = all_cleanfiles + all_emotion
else:
print('NOT using emotion data for training!')
# add mandarin data to clean speech
if params['use_mandarin_data'] ==1:
all_mandarin= []
for path in Path(params['clean_mandarin']).rglob('*.wav'):
all_mandarin.append(str(path.resolve()))
shuffle(all_mandarin)
if all_mandarin is not None:
all_cleanfiles = all_cleanfiles + all_mandarin
else:
print('NOT using non-english (Mandarin) data for training!')
params['cleanfilenames'] = all_cleanfiles
params['num_cleanfiles'] = len(params['cleanfilenames'])
# If there are .wav files in noise_dir directory, use those
# If not, that implies that the noise files are organized into subdirectories by type,
# so get the names of the non-excluded subdirectories
if 'noise_csv' in cfg.keys() and cfg['noise_csv'] != 'None':
noisefilenames = pd.read_csv(cfg['noise_csv'])
noisefilenames = noisefilenames['filename']
else:
noisefilenames = glob.glob(os.path.join(noise_dir, params['audioformat']))
if len(noisefilenames)!=0:
shuffle(noisefilenames)
params['noisefilenames'] = noisefilenames
else:
noisedirs = glob.glob(os.path.join(noise_dir, '*'))
if cfg['noise_types_excluded'] != 'None':
dirstoexclude = cfg['noise_types_excluded'].split(',')
for dirs in dirstoexclude:
noisedirs.remove(dirs)
shuffle(noisedirs)
params['noisedirs'] = noisedirs
# rir
temp = pd.read_csv(params['rir_table_csv'], skiprows=[1], sep=',', header=None, names=['wavfile','channel','T60_WB','C50_WB','isRealRIR'])
temp.keys()
#temp.wavfile
rir_wav = temp['wavfile'][1:] # 115413
rir_channel = temp['channel'][1:]
rir_t60 = temp['T60_WB'][1:]
rir_isreal= temp['isRealRIR'][1:]
rir_wav2 = [w.replace('\\', '/') for w in rir_wav]
rir_channel2 = [w for w in rir_channel]
rir_t60_2 = [w for w in rir_t60]
rir_isreal2= [w for w in rir_isreal]
myrir =[]
mychannel=[]
myt60=[]
lower_t60= params['lower_t60']
upper_t60= params['upper_t60']
if params['rir_choice']==1: # real 3076 IRs
real_indices= [i for i, x in enumerate(rir_isreal2) if x == "1"]
chosen_i = []
for i in real_indices:
if (float(rir_t60_2[i]) >= lower_t60) and (float(rir_t60_2[i]) <= upper_t60):
chosen_i.append(i)
myrir= [rir_wav2[i] for i in chosen_i]
mychannel = [rir_channel2[i] for i in chosen_i]
myt60 = [rir_t60_2[i] for i in chosen_i]
elif params['rir_choice']==2: # synthetic 112337 IRs
synthetic_indices= [i for i, x in enumerate(rir_isreal2) if x == "0"]
chosen_i = []
for i in synthetic_indices:
if (float(rir_t60_2[i]) >= lower_t60) and (float(rir_t60_2[i]) <= upper_t60):
chosen_i.append(i)
myrir= [rir_wav2[i] for i in chosen_i]
mychannel = [rir_channel2[i] for i in chosen_i]
myt60 = [rir_t60_2[i] for i in chosen_i]
elif params['rir_choice']==3: # both real and synthetic
all_indices= [i for i, x in enumerate(rir_isreal2)]
chosen_i = []
for i in all_indices:
if (float(rir_t60_2[i]) >= lower_t60) and (float(rir_t60_2[i]) <= upper_t60):
chosen_i.append(i)
myrir= [rir_wav2[i] for i in chosen_i]
mychannel = [rir_channel2[i] for i in chosen_i]
myt60 = [rir_t60_2[i] for i in chosen_i]
else: # default both real and synthetic
all_indices= [i for i, x in enumerate(rir_isreal2)]
chosen_i = []
for i in all_indices:
if (float(rir_t60_2[i]) >= lower_t60) and (float(rir_t60_2[i]) <= upper_t60):
chosen_i.append(i)
myrir= [rir_wav2[i] for i in chosen_i]
mychannel = [rir_channel2[i] for i in chosen_i]
myt60 = [rir_t60_2[i] for i in chosen_i]
params['myrir'] = myrir
params['mychannel'] = mychannel
params['myt60'] = myt60
# Call main_gen() to generate audio
clean_source_files, clean_clipped_files, clean_low_activity_files, \
noise_source_files, noise_clipped_files, noise_low_activity_files = main_gen(params)
# Create log directory if needed, and write log files of clipped and low activity files
log_dir = utils.get_dir(cfg, 'log_dir', 'Logs')
utils.write_log_file(log_dir, 'source_files.csv', clean_source_files + noise_source_files)
utils.write_log_file(log_dir, 'clipped_files.csv', clean_clipped_files + noise_clipped_files)
utils.write_log_file(log_dir, 'low_activity_files.csv', \
clean_low_activity_files + noise_low_activity_files)
# Compute and print stats about percentange of clipped and low activity files
total_clean = len(clean_source_files) + len(clean_clipped_files) + len(clean_low_activity_files)
total_noise = len(noise_source_files) + len(noise_clipped_files) + len(noise_low_activity_files)
pct_clean_clipped = round(len(clean_clipped_files)/total_clean*100, 1)
pct_noise_clipped = round(len(noise_clipped_files)/total_noise*100, 1)
pct_clean_low_activity = round(len(clean_low_activity_files)/total_clean*100, 1)
pct_noise_low_activity = round(len(noise_low_activity_files)/total_noise*100, 1)
print("Of the " + str(total_clean) + " clean speech files analyzed, " + \
str(pct_clean_clipped) + "% had clipping, and " + str(pct_clean_low_activity) + \
"% had low activity " + "(below " + str(params['clean_activity_threshold']*100) + \
"% active percentage)")
print("Of the " + str(total_noise) + " noise files analyzed, " + str(pct_noise_clipped) + \
"% had clipping, and " + str(pct_noise_low_activity) + "% had low activity " + \
"(below " + str(params['noise_activity_threshold']*100) + "% active percentage)")
if __name__ == '__main__':
main_body()