-
Notifications
You must be signed in to change notification settings - Fork 0
/
wave_manipulator.py
729 lines (572 loc) · 24.8 KB
/
wave_manipulator.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
import numpy as np
import pandas as pd
import os
import librosa
from pathlib import Path
import datetime
import glob
import shutil
from audiomentations import Compose, AddGaussianNoise, TimeStretch, PitchShift, Shift
def create_pathfile(p):
'''Create a pandas frame with labels from directories and the path of the file, lots of hardcoding'''
now = datetime.datetime.now()
time = now.strftime("%H:%M:%S")
print(time, ': Creating Pandas Frame with path and labels')
pathes = []
level_1 = []
level_2 = []
level_3 = []
level_4 = []
for filename in glob.iglob(p, recursive=True):
if os.path.isfile(filename):
if filename[-4:] == '.aif' or filename[-5:] == '.aiff':
pathes.append(filename)
folder = filename.split(os.sep)
level_1.append(folder[5])
level_2.append(folder[6].split()[0])
if folder[6].split()[0] == 'Piano':
level_3.append('Piano')
level_4.append('unused')
elif folder[6].split()[0] == 'Guitar':
level_3.append('Guitar')
level_4.append('unused')
else:
level_3.append(folder[7])
if folder[8][-4:] == '.aif' or folder[8][-5:] == '.aiff':
level_4.append('unused')
else:
level_4.append(folder[8].split('.')[0])
pathfile = pd.DataFrame(list(zip(pathes, level_1, level_2, level_3, level_4)), columns = ['path', 'source', 'type', 'instrument', 'style'])
return pathfile
def create_rawfiles(pathfile, p):
now = datetime.datetime.now()
time = now.strftime("%H:%M:%S")
print(time, ': Creating Pandas Frames with raw data and write to Disc')
instruments = list(set(pathfile['instrument']))
for instrument in instruments:
recording = []
sample_rate = []
samples = []
length = []
maximum_db = []
level_1 = []
level_2 = []
level_3 = []
level_4 = []
filtered = pathfile.loc[pathfile['instrument'] == instrument]
# print(instrument)
for index, row in filtered.iterrows():
x, sr = librosa.load(row['path'], sr=None)
recording.append(x)
sample_rate.append(sr)
maximum_db.append(np.max(x))
level_1.append(row['source'])
level_2.append(row['type'])
level_3.append(row['instrument'])
level_4.append(row['style'])
length.append(len(x) / sr)
samples.append(len(x))
output = pd.DataFrame(list(zip(recording, length, samples, sample_rate, maximum_db, level_1, level_2, level_3, level_4)),
columns = ['raw_sounds', 'length', 'sample_count', 'sample_rate', 'maximum_db', 'source', 'type', 'instrument', 'style'])
output.to_pickle(p / (instrument + '.pkl'))
file_list = [p/(file + '.pkl') for file in instruments] #Create instrument list to split the amount of data into smaller frames
return file_list
def resample(file_list, p, sr):
'''Resample if required and drop to disc resampled data '''
now = datetime.datetime.now()
time = now.strftime("%H:%M:%S")
print(time, ': Resample all recordings to target sampling rate if required')
for file in file_list:
data = pd.read_pickle(file)
downsample = data.loc[data['sample_rate'] != sr]
print(file, ': Resampling records:', len(downsample.index))
resampled = []
indexes = []
length = []
srs = []
samples = []
for index, row in downsample.iterrows():
sample = row['raw_sounds']
sro = row['sample_rate']
y = librosa.resample(sample, sro, sr)
l = len(y) / sr
resampled.append(y)
indexes.append(index)
length.append(l)
samples.append(len(y))
srs.append(sr)
output = pd.DataFrame(list(zip(resampled, srs, indexes, length, samples)),
columns = ['raw_sounds', 'sample_rate', 'index', 'length', 'sample_count']).set_index('index')
data.update(output) # Join resampled recordings to raw frame
data.to_pickle(p / file.name)
file_list = [p/(file.name) for file in file_list]
return file_list
def trim_silence(file_list, p, Ignore, top_db):
'''Cut leading and trailing silence from file'''
now = datetime.datetime.now()
time = now.strftime("%H:%M:%S")
print(time, ': Trim leading and trailing silence')
for file in file_list:
data = pd.read_pickle(file)
pad = data.loc[data['sample_count'] > Ignore]
cropped = []
indexes = []
samples = []
for index, row in pad.iterrows():
sample = row['raw_sounds']
y, area = librosa.effects.trim(sample, top_db)
cropped.append(y)
indexes.append(index)
samples.append(len(y))
output = pd.DataFrame(list(zip(cropped, indexes, samples)), columns = ['raw_sounds', 'index', 'sample_count']).set_index('index')
data.update(output) # Join resampled recordings to raw frame
data.to_pickle(p / file.name)
file_list = [p/(file.name) for file in file_list]
return file_list
def increase_loudness(file_list, p, Ignore, factor, noise):
'''Increase maximum Amplitude by factor for too small values'''
now = datetime.datetime.now()
time = now.strftime("%H:%M:%S")
#print(time, ': Increase loudness for too silent values')
for file in file_list:
data = pd.read_pickle(file)
pad = data.loc[data['sample_count'] > Ignore]
boosted = []
indexes = []
maximum_db = []
for index, row in pad.iterrows():
sample = row['raw_sounds']
maximum = np.max(sample)
minimum = np.min(sample)
if maximum < abs(minimum):
maximum = abs(minimum)
if maximum > noise:
scale = factor / maximum
else:
scale = 0
#print(file.name, index, maximum, scale)
sample = sample * scale
boosted.append(sample)
indexes.append(index)
maximum_db.append(np.max(sample))
output = pd.DataFrame(list(zip(boosted, maximum_db, indexes)), columns = ['raw_sounds', 'maximum_db', 'index']).set_index('index')
data.update(output) # Join resampled recordings to raw frame
data.to_pickle(p / file.name)
file_list = [p/(file.name) for file in file_list]
return file_list
def to_wav(file_list, p, sr=44100):
'''Helper Function to create various wave files on demand with additional naming'''
shutil.rmtree(p, ignore_errors=True)
os.makedirs(p)
for file in file_list:
pad = pd.read_pickle(file)
for index, row in pad.iterrows():
play = row['raw_sounds']
folder = file.name[:-4]
if not os.path.exists(p / folder):
os.makedirs(p / folder)
if 'name' in row.index:
librosa.output.write_wav(p/folder/(row['name'] + '.wav'), play, sr)
else:
librosa.output.write_wav(p/folder /(str(index) + '.wav'), play, sr)
def slice_recording(skipfiles, file_list, p, Ignore, min_loud, top_db, no_samples):
now = datetime.datetime.now()
time = now.strftime("%H:%M:%S")
print(time, ': Slice longer recordings into single recordings')
for file in file_list:
data = pd.read_pickle(file)
raw_sounds = []
sample_count = []
sample_rate = []
source = []
types = []
instrument = []
style = []
length = []
maximum_db = []
name = []
n = 0
if file.name not in skipfiles:
#print(file.name)
for index, row in data.iterrows():
n = 0
sample = row['raw_sounds']
if len(sample) > Ignore:
intervals = librosa.effects.split(sample, top_db)
if 'name' in row.index:
old_name = row['name'].split('_')
filename = old_name[0]
fileno = int(old_name[1])
for inter in intervals:
if inter[1] - inter[0] >= no_samples:
interval = sample[inter[0]:inter[1]]
if np.max(interval) > min_loud:
raw_sounds.append(interval)
sample_count.append(len(interval))
sample_rate.append(row['sample_rate'])
source.append(row['source'])
types.append(row['type'])
instrument.append(row['instrument'])
style.append(row['style'])
length.append(len(interval) / row['sample_rate'])
maximum_db.append(np.max(interval))
if 'name' not in row.index:
name.append(str(index) + '_' + str(n))
n += 1
else:
name.append(filename + '_' + str(fileno))
fileno += 1
else:
if np.max(sample) > min_loud:
raw_sounds.append(sample)
sample_count.append(row['sample_count'])
sample_rate.append(row['sample_rate'])
source.append(row['source'])
types.append(row['type'])
instrument.append(row['instrument'])
style.append(row['style'])
length.append(len(sample) / row['sample_rate'])
maximum_db.append(np.max(sample))
if 'name' in row.index:
name.append(row['name'])
else:
name.append(str(index) + '_' + str(n))
else:
for index, row in data.iterrows():
sample = row['raw_sounds']
if np.max(sample) > min_loud:
raw_sounds.append(sample)
sample_count.append(row['sample_count'])
sample_rate.append(row['sample_rate'])
source.append(row['source'])
types.append(row['type'])
instrument.append(row['instrument'])
style.append(row['style'])
length.append(len(sample) / row['sample_rate'])
maximum_db.append(np.max(sample))
if 'name' in row.index:
name.append(row['name'])
else:
name.append(str(index) + '_' + str(n))
output = pd.DataFrame(list(zip(name, raw_sounds, maximum_db, length, sample_count, sample_rate, source, types, instrument, style)),
columns = ['name', 'raw_sounds', 'maximum_db', 'length', 'sample_count', 'sample_rate', 'source', 'type', 'instrument', 'style'])
output.to_pickle(p / file.name)
file_list = [p/(file.name) for file in file_list]
return file_list
def create_rawfiles2(pathfile, p):
# now = datetime.datetime.now()
# time = now.strftime("%H:%M:%S")
# print(time, ': Creating Pandas Frames with raw data and write to Disc')
instruments = list(set(pathfile['instrument']))
for instrument in instruments:
recording = []
sample_rate = []
samples = []
length = []
maximum_db = []
level_1 = []
level_2 = []
level_3 = []
level_4 = []
name = []
n = 0
filtered = pathfile.loc[pathfile['instrument'] == instrument]
# print(instrument)
for index, row in filtered.iterrows():
n += 1
x, sr = librosa.load(row['path'], sr=None)
recording.append(x)
sample_rate.append(sr)
maximum_db.append(np.max(x))
level_1.append(row['source'])
level_2.append(row['type'])
level_3.append(row['instrument'])
level_4.append(row['style'])
length.append(len(x) / sr)
samples.append(len(x))
name.append(str(n))
output = pd.DataFrame(list(zip(name, recording, length, samples, sample_rate,
maximum_db, level_1, level_2, level_3, level_4)),
columns = ['name', 'raw_sounds', 'length', 'sample_count',
'sample_rate', 'maximum_db', 'source', 'type', 'instrument', 'style'])
output.to_pickle(p / (instrument + '.pkl'))
def slice_recording2(data, Ignore, min_loud, top_db, no_samples):
raw_sounds = []
sample_count = []
sample_rate = []
source = []
types = []
instrument = []
style = []
length = []
maximum_db = []
name = []
for index, row in data.iterrows():
sample = row['raw_sounds']
if len(sample) > Ignore:
intervals = librosa.effects.split(sample, top_db)
for inter in intervals:
if inter[1] - inter[0] >= no_samples:
interval = sample[inter[0]:inter[1]]
if interval.shape[0] > 0:
if np.max(interval) > min_loud:
raw_sounds.append(interval)
sample_count.append(len(interval))
sample_rate.append(row['sample_rate'])
source.append(row['source'])
types.append(row['type'])
instrument.append(row['instrument'])
style.append(row['style'])
length.append(len(interval) / row['sample_rate'])
maximum_db.append(np.max(interval))
name.append(row['name'])
else:
if np.max(sample) > min_loud:
raw_sounds.append(sample)
sample_count.append(row['sample_count'])
sample_rate.append(row['sample_rate'])
source.append(row['source'])
types.append(row['type'])
instrument.append(row['instrument'])
style.append(row['style'])
length.append(len(sample) / row['sample_rate'])
maximum_db.append(np.max(sample))
name.append(row['name'])
output = pd.DataFrame(list(zip(name, raw_sounds, maximum_db, length, sample_count, sample_rate,
source, types, instrument, style)),
columns = ['name', 'raw_sounds', 'maximum_db', 'length', 'sample_count', 'sample_rate',
'source', 'type', 'instrument', 'style'])
return output
def to_wav2(files, p, sr=44100):
'''Helper Function to create various wave files on demand with additional naming'''
data1 = pd.read_pickle(files[0])
names1 = set(data1['name'])
folder = files[0].name[:-4] + '_Cut'
shutil.rmtree(p / folder, ignore_errors=True)
os.makedirs(p / folder)
for name in names1:
pad = data1.loc[data1['name'] == name]
n = 1
for index, row in pad.iterrows():
play = row['raw_sounds']
librosa.output.write_wav(p/folder/(row['name'] + '_' + str(n) + '.wav'), play, sr)
n += 1
if len(files) == 2:
data2 = pd.read_pickle(files[1])
names2 = set(data2['name'])
missing = names2 - names1
folder2 = files[1].name[:-4] + '_Original'
shutil.rmtree(p / folder2, ignore_errors=True)
os.makedirs(p / folder2)
folder3 = files[1].name[:-4] + '_Missing'
shutil.rmtree(p / folder3, ignore_errors=True)
os.makedirs(p / folder3)
for name in names2:
pad = data2.loc[data2['name'] == name]
n = 1
for index, row in pad.iterrows():
play = row['raw_sounds']
librosa.output.write_wav(p/folder2/(row['name'] + '_' + str(n) + '.wav'), play, sr)
n += 1
for name in missing:
pad = data2.loc[data2['name'] == name]
n = 1
for index, row in pad.iterrows():
play = row['raw_sounds']
librosa.output.write_wav(p/folder3/(row['name'] + '_' + str(n) + '.wav'), play, sr)
n += 1
def resample2(data, sr):
'''Resample if required and drop to disc resampled data '''
# now = datetime.datetime.now()
# time = now.strftime("%H:%M:%S")
# print(time, ': Resample all recordings to target sampling rate if required')
downsample = data.loc[data['sample_rate'] != sr]
#print(file, ': Resampling records:', len(downsample.index))
resampled = []
indexes = []
length = []
srs = []
samples = []
for index, row in downsample.iterrows():
sample = row['raw_sounds']
sro = row['sample_rate']
y = librosa.resample(sample, sro, sr)
l = len(y) / sr
resampled.append(y)
indexes.append(index)
length.append(l)
samples.append(len(y))
srs.append(sr)
output = pd.DataFrame(list(zip(resampled, srs, indexes, length, samples)),
columns = ['raw_sounds', 'sample_rate', 'index', 'length', 'sample_count']).set_index('index')
data.update(output) # Join resampled recordings to raw frame
# data.to_pickle(p / file.name)
#file_list = [p/(file.name) for file in file_list]
return data
def trim_silence2(data, Ignore, top_db):
'''Cut leading and trailing silence from file'''
# now = datetime.datetime.now()
# time = now.strftime("%H:%M:%S")
# print(time, ': Trim leading and trailing silence')
pad = data.loc[data['sample_count'] > Ignore]
cropped = []
indexes = []
samples = []
for index, row in pad.iterrows():
sample = row['raw_sounds']
y, area = librosa.effects.trim(sample, top_db)
cropped.append(y)
indexes.append(index)
samples.append(len(y))
output = pd.DataFrame(list(zip(cropped, indexes, samples)),
columns = ['raw_sounds', 'index', 'sample_count']).set_index('index')
data.update(output) # Join resampled recordings to raw frame
return data
def to_wav3(data, p, sr=44100):
'''Helper Function to create various wave files on demand with additional naming'''
direcs = set(data['directories'])
instrument = data.iloc[0].instrument
for direc in direcs:
if not os.path.exists(p / direc):
os.makedirs(p / direc)
names = set(data['name'])
for name in names:
pad = data.loc[data['name'] == name]
n = 1
for index, row in pad.iterrows():
play = row['raw_sounds']
librosa.output.write_wav(p/ row['directories'] / (instrument + '_' + row['name'] + '_' + str(n) + '.wav'), play, sr)
n += 1
def delete_trash(data, length, top_db):
data = data.drop(data[(data.maximum_db < top_db) & (data.sample_count < length)].index)
return data
def cut_end(data, length):
cropped = []
indexes = []
samples = []
pad = data.loc[data.sample_count >= length]
for index, row in pad.iterrows():
sample = row['raw_sounds']
y = librosa.util.fix_length(sample, length)
cropped.append(y)
indexes.append(index)
samples.append(len(y))
output = pd.DataFrame(list(zip(cropped, indexes, samples)),
columns = ['raw_sounds', 'index', 'sample_count']).set_index('index')
data.update(output) # Join resampled recordings to raw frame
return data
def clean_edges(data, length):
cropped = []
indexes = []
samples = []
for index, row in data.iterrows():
sample = row['raw_sounds']
z = librosa.zero_crossings(sample)
crossings = np.nonzero(z)
begin = crossings[0][0]
end = crossings[0][-1]
y = sample[begin : end + 1]
y = librosa.util.fix_length(y, length)
cropped.append(y)
indexes.append(index)
samples.append(len(y))
output = pd.DataFrame(list(zip(cropped, indexes, samples)),
columns = ['raw_sounds', 'index', 'sample_count']).set_index('index')
data.update(output) # Join resampled recordings to raw frame
return data
def pad_end(data, length):
pad = data.loc[data.sample_count < length]
cropped = []
indexes = []
samples = []
for index, row in pad.iterrows():
sample = row['raw_sounds']
l = len(sample)
z = librosa.zero_crossings(sample)
crossings = np.nonzero(z)
begin = crossings[0][0]
end = crossings[0][-1]
y = sample[begin : end + 1]
cropped.append(y)
indexes.append(index)
samples.append(len(y))
output = pd.DataFrame(list(zip(cropped, indexes, samples)),
columns = ['raw_sounds', 'index', 'sample_count']).set_index('index')
data.update(output) # Join resampled recordings to raw frame
return data
def create_dataframe(p, structure):
raw_sounds = []
sra = []
wav_path = []
names = []
instruments = []
length = []
labels = []
for index, row in structure.iterrows():
p_read = p / row.Directory
name = row.Label
print(p_read)
#instrument = row.tags
label = row.Label_int
for file in os.scandir(p_read):
if file.name[-4:] == '.wav':
x, sr = librosa.load(file, sr=None)
raw_sounds.append(x)
sra.append(sr)
wav_path.append(p_read / file.name)
#instruments.append(instrument)
names.append(name)
length.append(len(x))
labels.append(label)
output = pd.DataFrame(list(zip(wav_path, raw_sounds, sra, names, length, labels)),
columns = ['wav_path', 'raw_sounds', 'sample_rate', 'names', 'no_samples', 'labels'])
return output
def analyze(data):
tags = set(data.names)
count = []
labels = []
instruments = []
for tag in tags:
pad = data.loc[data.names == tag]
count.append(len(pad))
labels.append(pad.iloc[0]['labels'])
instruments.append(tag)
analyze = pd.DataFrame(list(zip(labels, instruments, count)), columns = ['Label', 'Instrument', 'Nos'])
Label_dict = dict(zip(instruments, labels))
return analyze, Label_dict
def sound_augmenter(data, augmentation, size=1):
sr = augmentation['sr']
augmenter = augmentation['augmenter']
loudad = augmentation['loudad']
min_loud = augmentation['min_loud']
max_loud = augmentation['max_loud']
new_sounds = []
maximum = []
if isinstance(data, pd.DataFrame):
pad = data.sample(frac=size)
for index, row in pad.iterrows():
sample = row['raw_sounds']
new_sound = augmenter(samples=sample, sample_rate=sr)
if loudad:
new_sound = new_sound / np.max(sample) * np.random.uniform(min_loud, max_loud)
new_sounds.append(new_sound)
pad['raw_sounds'] = new_sounds
augmented = pad
if isinstance(data, np.ndarray):
new_sound = augmenter(samples=data, sample_rate=sr)
if loudad:
new_sound = new_sound / np.max(data) * np.random.uniform(min_loud, max_loud)
augmented = new_sound
return new_sound
def slicer(audio, sr, hoplength):
l_predict = sr * 3 -1
hop = int(sr * hoplength)
frames = int((len(audio) - l_predict) / hop)
inter = []
srs = []
for frame in range(frames):
slices = audio[frame * hop : (frame * hop) + l_predict]
inter.append(slices)
srs.append(sr)
out = pd.DataFrame(list(zip(inter, srs)), columns = ['raw_sounds', 'sample_rate'])
return out