/
core.py
1716 lines (1497 loc) · 69.4 KB
/
core.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
import sox
import random
import os
import warnings
import jams
from collections import namedtuple
import logging
import tempfile
import numpy as np
import shutil
import csv
from .scaper_exceptions import ScaperError
from .scaper_warnings import ScaperWarning
from .util import _close_temp_files
from .util import _set_temp_logging_level
from .util import _get_sorted_files
from .util import _validate_folder_path
from .util import _populate_label_list
from .util import _trunc_norm
from .util import max_polyphony
from .util import polyphony_gini
from .util import is_real_number, is_real_array
from .audio import get_integrated_lufs
from .version import version as scaper_version
SUPPORTED_DIST = {"const": lambda x: x,
"choose": lambda x: random.choice(x),
"uniform": random.uniform,
"normal": random.normalvariate,
"truncnorm": _trunc_norm}
# Define single event spec as namedtuple
EventSpec = namedtuple(
'EventSpec',
['label', 'source_file', 'source_time', 'event_time', 'event_duration',
'snr', 'role', 'pitch_shift', 'time_stretch'], verbose=False)
'''
Container for storing event specifications, either probabilistic (i.e. using
distribution tuples to specify possible values) or instantiated (i.e. storing
constants directly).
'''
def generate_from_jams(jams_infile, audio_outfile, fg_path=None, bg_path=None,
jams_outfile=None):
'''
Generate a soundscape based on an existing scaper JAMS file and save to
disk.
Parameters
----------
jams_infile : str
Path to JAMS file (must be a file previously generated by Scaper).
audio_outfile : str
Path for saving the generated soundscape audio.
fg_path : str or None
Specifies a different path for foreground audio than the one stored in
the input jams file. For the reconstruction to be successful the folder
and file structure inside this path must be identical the one that was
used to create the input jams file. If None (default), the fg_path from
the input jams file will be used.
bg_path : str or None
Specifies a different path for background audio than the one stored in
the input jams file. For the reconstruction to be successful the folder
and file structure inside this path must be identical the one that was
used to create the input jams file. If None (default), the bg_path from
the input jams file will be used.
jams_outfile : str or None
Path for saving new JAMS file, if None (default) a new JAMS is not
saved. Useful when either fg_path or bg_path is not None, as it saves
a new JAMS files where the source file paths match the new fg_path
and/or bg_path.
Raises
------
ScaperError
If jams_infile does not point to a valid JAMS file that was previously
generated by Scaper and contains an annotation of the scaper
namespace.
'''
jam = jams.load(jams_infile)
anns = jam.search(namespace='scaper')
if len(anns) == 0:
raise ScaperError(
'JAMS file does not contain any annotation with namespace '
'scaper.')
ann = anns[0]
# Update paths
if fg_path is None:
new_fg_path = ann.sandbox.scaper['fg_path']
else:
new_fg_path = os.path.expanduser(fg_path)
# Update source files
for obs in ann.data:
if obs.value['role'] == 'foreground':
sourcefile = obs.value['source_file']
sourcefilename = os.path.basename(sourcefile)
parent = os.path.dirname(sourcefile)
parentname = os.path.basename(parent)
newsourcefile = os.path.join(
new_fg_path, parentname, sourcefilename)
obs.value['source_file'] = newsourcefile # hacky
# Update sandbox
ann.sandbox.scaper['fg_path'] = new_fg_path
if bg_path is None:
new_bg_path = ann.sandbox.scaper['bg_path']
else:
new_bg_path = os.path.expanduser(bg_path)
# Update source files
for obs in ann.data:
if obs.value['role'] == 'background':
sourcefile = obs.value['source_file']
sourcefilename = os.path.basename(sourcefile)
parent = os.path.dirname(sourcefile)
parentname = os.path.basename(parent)
newsourcefile = os.path.join(
new_bg_path, parentname, sourcefilename)
obs.value['source_file'] = newsourcefile # hacky
# Update sandbox
ann.sandbox.scaper['bg_path'] = new_bg_path
# Create scaper object
duration = ann.sandbox.scaper['duration']
protected_labels = ann.sandbox.scaper['protected_labels']
sc = Scaper(duration, new_fg_path, new_bg_path, protected_labels)
# Set synthesis parameters
sc.ref_db = ann.sandbox.scaper['ref_db']
sc.n_channels = ann.sandbox.scaper['n_channels']
sc.fade_in_len = ann.sandbox.scaper['fade_in_len']
sc.fade_out_len = ann.sandbox.scaper['fade_out_len']
# Generate audio and save to disk
reverb = ann.sandbox.scaper['reverb']
sc._generate_audio(audio_outfile, ann, reverb=reverb,
disable_sox_warnings=True)
# If there are slice (trim) operations, need to perform them!
if 'slice' in ann.sandbox.keys():
for sliceop in ann.sandbox['slice']:
# must use temp file in order to save to same file
tmpfiles = []
with _close_temp_files(tmpfiles):
# Create tmp file
tmpfiles.append(
tempfile.NamedTemporaryFile(suffix='.wav', delete=False))
# Save trimmed result to temp file
tfm = sox.Transformer()
tfm.trim(sliceop['slice_start'], sliceop['slice_end'])
tfm.build(audio_outfile, tmpfiles[-1].name)
# Copy result back to original file
shutil.copyfile(tmpfiles[-1].name, audio_outfile)
# Optionally save new jams file
if jams_outfile is not None:
jam.save(jams_outfile)
def trim(audio_infile, jams_infile, audio_outfile, jams_outfile, start_time,
end_time, no_audio=False):
'''
Trim and audio file and corresponding Scaper JAMS file and save to disk.
Given an input audio file and corresponding jams file, trim both the audio
and all annotations in the jams file to the time range ``[start_time,
end_time]`` and save the result to ``audio_outfile`` and ``jams_outfile``
respectively. This function uses ``jams.slice()`` for trimming the jams
file while ensuring the start times of the jam's annotations and
observations they contain match the trimmed audio file.
Parameters
----------
audio_infile : str
Path to input audio file
jams_infile : str
Path to input jams file
audio_outfile : str
Path to output trimmed audio file
jams_outfile : str
Path to output trimmed jams file
start_time : float
Start time for trimmed audio/jams
end_time : float
End time for trimmed audio/jams
no_audio : bool
If true, operates on the jams only. Audio input and output paths
don't have to point to valid files.
'''
# First trim jams (might raise an error)
jam = jams.load(jams_infile)
jam_sliced = jam.slice(start_time, end_time, strict=False)
# Special work for annotations of the scaper 'scaper' namespace
for ann in jam_sliced.annotations:
if ann.namespace == 'scaper':
# DON'T MODIFY event's value dict! Keeps original instantiated
# values for reconstruction / reproducibility.
# Count number of FG events
n_events = 0
for obs in ann.data:
if obs.value['role'] == 'foreground':
n_events += 1
# Re-compute max polyphony
poly = max_polyphony(ann)
# Re-compute polyphony gini
gini = polyphony_gini(ann)
# Update specs in sandbox
ann.sandbox.scaper['n_events'] = n_events
ann.sandbox.scaper['polyphony_max'] = poly
ann.sandbox.scaper['polyphony_gini'] = gini
ann.sandbox.scaper['duration'] = ann.duration
# Save result to output jams file
jam_sliced.save(jams_outfile)
# Next, trim audio
if not no_audio:
tfm = sox.Transformer()
tfm.trim(start_time, end_time)
if audio_outfile != audio_infile:
tfm.build(audio_infile, audio_outfile)
else:
# must use temp file in order to save to same file
tmpfiles = []
with _close_temp_files(tmpfiles):
# Create tmp file
tmpfiles.append(
tempfile.NamedTemporaryFile(
suffix='.wav', delete=False))
# Save trimmed result to temp file
tfm.build(audio_infile, tmpfiles[-1].name)
# Copy result back to original file
shutil.copyfile(tmpfiles[-1].name, audio_outfile)
def _get_value_from_dist(dist_tuple):
'''
Sample a value from the provided distribution tuple.
Given a distribution tuple, validate its format/values and then sample
and return a single value from the distribution specified by the tuple.
Parameters
----------
dist_tuple : tuple
Distribution tuple to be validated. See ``Scaper.add_event`` for
details about the expected format for the distribution tuple.
Returns
-------
value
A value from the specified distribution.
See Also
--------
Scaper.add_event : Add a foreground sound event to the foreground
specification.
_validate_distribution : Check whether a tuple specifying a parameter
distribution has a valid format, if not raise an error.
'''
# Make sure it's a valid distribution tuple
_validate_distribution(dist_tuple)
return SUPPORTED_DIST[dist_tuple[0]](*dist_tuple[1:])
def _validate_distribution(dist_tuple):
'''
Check whether a tuple specifying a parameter distribution has a valid
format, if not raise an error.
Parameters
----------
dist_tuple : tuple
Tuple specifying a distribution to sample from. See Scaper.add_event
for details about the expected format of the tuple and allowed values.
Raises
------
ScaperError
If the tuple does not have a valid format.
See Also
--------
Scaper.add_event : Add a foreground sound event to the foreground
specification.
'''
# Make sure it's a tuple
if not isinstance(dist_tuple, tuple):
raise ScaperError('Distribution tuple must be of type tuple.')
# Make sure the tuple contains at least 2 items
if len(dist_tuple) < 2:
raise ScaperError('Distribution tuple must be at least of length 2.')
# Make sure the first item is one of the supported distribution names
if dist_tuple[0] not in SUPPORTED_DIST.keys():
raise ScaperError(
"Unsupported distribution name: {:s}".format(dist_tuple[0]))
# If it's a constant distribution, tuple must be of length 2
if dist_tuple[0] == 'const':
if len(dist_tuple) != 2:
raise ScaperError('"const" distribution tuple must be of length 2')
# If it's a choose, tuple must be of length 2 and second item of type list
elif dist_tuple[0] == 'choose':
if len(dist_tuple) != 2 or not isinstance(dist_tuple[1], list):
raise ScaperError(
'The "choose" distribution tuple must be of length 2 where '
'the second item is a list.')
# If it's a uniform distribution, tuple must be of length 3, 2nd item must
# be a real number and 3rd item must be real and greater/equal to the 2nd.
elif dist_tuple[0] == 'uniform':
if (len(dist_tuple) != 3 or
not is_real_number(dist_tuple[1]) or
not is_real_number(dist_tuple[2]) or
dist_tuple[1] > dist_tuple[2]):
raise ScaperError(
'The "uniform" distribution tuple be of length 2, where the '
'2nd item is a real number and the 3rd item is a real number '
'and greater/equal to the 2nd item.')
# If it's a normal distribution, tuple must be of length 3, 2nd item must
# be a real number and 3rd item must be a non-negative real
elif dist_tuple[0] == 'normal':
if (len(dist_tuple) != 3 or
not is_real_number(dist_tuple[1]) or
not is_real_number(dist_tuple[2]) or
dist_tuple[2] < 0):
raise ScaperError(
'The "normal" distribution tuple must be of length 3, where '
'the 2nd item (mean) is a real number and the 3rd item (std '
'dev) is real and non-negative.')
elif dist_tuple[0] == 'truncnorm':
if (len(dist_tuple) != 5 or
not is_real_number(dist_tuple[1]) or
not is_real_number(dist_tuple[2]) or
not is_real_number(dist_tuple[3]) or
not is_real_number(dist_tuple[4]) or
dist_tuple[2] < 0 or
dist_tuple[4] < dist_tuple[3]):
raise ScaperError(
'The "truncnorm" distribution tuple must be of length 5, '
'where the 2nd item (mean) is a real number, the 3rd item '
'(std dev) is real and non-negative, the 4th item (trunc_min) '
'is a real number and the 5th item (trun_max) is a real '
'number that is equal to or greater than trunc_min.')
def _validate_label(label, allowed_labels):
'''
Validate that a label tuple is in the right format and that it's values
are valid.
Parameters
----------
label : tuple
Label tuple (see ```Scaper.add_event``` for required format).
allowed_labels : list
List of allowed labels.
Raises
------
ScaperError
If the validation fails.
'''
# Make sure it's a valid distribution tuple
_validate_distribution(label)
# Make sure it's one of the allowed distributions for a label and that the
# label value is one of the allowed labels.
if label[0] == "const":
if not label[1] in allowed_labels:
raise ScaperError(
'Label value must match one of the available labels: '
'{:s}'.format(str(allowed_labels)))
elif label[0] == "choose":
if label[1]: # list is not empty
if not set(label[1]).issubset(set(allowed_labels)):
raise ScaperError(
'Label list provided must be a subset of the available '
'labels: {:s}'.format(str(allowed_labels)))
else:
raise ScaperError(
'Label must be specified using a "const" or "choose" tuple.')
def _validate_source_file(source_file_tuple, label_tuple):
'''
Validate that a source_file tuple is in the right format a that it's values
are valid.
Parameters
----------
source_file : tuple
Source file tuple (see ```Scaper.add_event``` for required format).
label : str
Label tuple (see ```Scaper.add_event``` for required format).
Raises
------
ScaperError
If the validation fails.
'''
# Make sure it's a valid distribution tuple
_validate_distribution(source_file_tuple)
_validate_distribution(label_tuple)
# If source file is specified explicitly
if source_file_tuple[0] == "const":
# 1. the filepath must point to an existing file
if not os.path.isfile(source_file_tuple[1]):
raise ScaperError(
"Source file not found: {:s}".format(source_file_tuple[1]))
# 2. the label must match the file's parent folder name
parent_name = os.path.basename(os.path.dirname(source_file_tuple[1]))
if label_tuple[0] != "const" or label_tuple[1] != parent_name:
raise ScaperError(
"Source file's parent folder name does not match label.")
# Otherwise it must be specified using "choose"
elif source_file_tuple[0] == "choose":
if source_file_tuple[1]: # list is not empty
if not all(os.path.isfile(x) for x in source_file_tuple[1]):
raise ScaperError(
'Source file list must either be empty or all paths in '
'the list must point to valid files.')
else:
raise ScaperError(
'Source file must be specified using a "const" or "choose" tuple.')
def _validate_time(time_tuple):
'''
Validate that a time tuple has the right format and that the
specified distribution cannot result in a negative time.
Parameters
----------
time_tuple : tuple
Time tuple (see ```Scaper.add_event``` for required format).
Raises
------
ScaperError
If the validation fails.
'''
# Make sure it's a valid distribution tuple
_validate_distribution(time_tuple)
# Ensure the values are valid for time
if time_tuple[0] == "const":
if (time_tuple[1] is None or
not is_real_number(time_tuple[1]) or
time_tuple[1] < 0):
raise ScaperError(
'Time must be a real non-negative number.')
elif time_tuple[0] == "choose":
if (not time_tuple[1] or
not is_real_array(time_tuple[1]) or
not all(x is not None for x in time_tuple[1]) or
not all(x >= 0 for x in time_tuple[1])):
raise ScaperError(
'Time list must be a non-empty list of non-negative real '
'numbers.')
elif time_tuple[0] == "uniform":
if time_tuple[1] < 0:
raise ScaperError(
'A "uniform" distribution tuple for time must have '
'min_value >= 0')
elif time_tuple[0] == "normal":
warnings.warn(
'A "normal" distribution tuple for time can result in '
'negative values, in which case the distribution will be '
're-sampled until a positive value is returned: this can result '
'in an infinite loop!',
ScaperWarning)
elif time_tuple[0] == "truncnorm":
if time_tuple[3] < 0:
raise ScaperError(
'A "truncnorm" distirbution tuple for time must specify a non-'
'negative trunc_min value.')
def _validate_duration(duration_tuple):
'''
Validate that a duration tuple has the right format and that the
specified distribution cannot result in a negative or zero value.
Parameters
----------
duration : tuple
Duration tuple (see ```Scaper.add_event``` for required format).
Raises
------
ScaperError
If the validation fails.
'''
# Make sure it's a valid distribution tuple
_validate_distribution(duration_tuple)
# Ensure the values are valid for duration
if duration_tuple[0] == "const":
if (not is_real_number(duration_tuple[1]) or
duration_tuple[1] <= 0):
raise ScaperError(
'Duration must be a real number greater than zero.')
elif duration_tuple[0] == "choose":
if (not duration_tuple[1] or
not is_real_array(duration_tuple[1]) or
not all(x > 0 for x in duration_tuple[1])):
raise ScaperError(
'Duration list must be a non-empty list of positive real '
'numbers.')
elif duration_tuple[0] == "uniform":
if duration_tuple[1] <= 0:
raise ScaperError(
'A "uniform" distribution tuple for duration must have '
'min_value > 0')
elif duration_tuple[0] == "normal":
warnings.warn(
'A "normal" distribution tuple for duration can result in '
'non-positives values, in which case the distribution will be '
're-sampled until a positive value is returned: this can result '
'in an infinite loop!',
ScaperWarning)
elif duration_tuple[0] == "truncnorm":
if duration_tuple[3] <= 0:
raise ScaperError(
'A "truncnorm" distirbution tuple for time must specify a '
'positive trunc_min value.')
def _validate_snr(snr_tuple):
'''
Validate that an snr distribution tuple has the right format.
Parameters
----------
snr : tuple
SNR tuple (see ```Scaper.add_event``` for required format).
Raises
------
ScaperError
If the validation fails.
'''
# Make sure it's a valid distribution tuple
_validate_distribution(snr_tuple)
# Ensure the values are valid for SNR
if snr_tuple[0] == "const":
if not is_real_number(snr_tuple[1]):
raise ScaperError(
'SNR must be a real number.')
elif snr_tuple[0] == "choose":
if (not snr_tuple[1] or
not is_real_array(snr_tuple[1])):
raise ScaperError(
'SNR list must be a non-empty list of real numbers.')
# No need to check for "uniform" and "normal" since they must produce a
# real number and technically speaking any real number is a valid SNR.
# TODO: do we want to impose limits on the possible SNR values?
def _validate_pitch_shift(pitch_shift_tuple):
'''
Validate that a pitch_shift distribution tuple has the right format.
Parameters
----------
pitch_shift_tuple : tuple
Pitch shift tuple (see ```Scaper.add_event``` for required format).
Raises
------
ScaperError
If the validation fails.
'''
# If the tuple is none then it's valid
if pitch_shift_tuple is not None:
# Make sure it's a valid distribution tuple
_validate_distribution(pitch_shift_tuple)
# Ensure the values are valid for pitch shift
if pitch_shift_tuple[0] == "const":
if not is_real_number(pitch_shift_tuple[1]):
raise ScaperError(
'Pitch shift must be a real number.')
elif pitch_shift_tuple[0] == "choose":
if (not pitch_shift_tuple[1] or
not is_real_array(pitch_shift_tuple[1])):
raise ScaperError(
'Pitch shift list must be a non-empty list of real '
'numbers.')
# No need to check for "uniform" and "normal" since they must produce a
# real number and technically speaking any real number is a valid pitch
# shift
# TODO: do we want to impose limits on the possible pitch shift values?
def _validate_time_stretch(time_stretch_tuple):
'''
Validate that a time_stretch distribution tuple has the right format.
Parameters
----------
time_stretch_tuple: tuple
Time stretch tuple (see ```Scaper.add_event``` for required format).
Raises
------
ScaperError
If the validation fails.
'''
# if the tuple is none then its valid
if time_stretch_tuple is not None:
# Make sure it's a valid distribution tuple
_validate_distribution(time_stretch_tuple)
# Ensure the values are valid for time stretch
if time_stretch_tuple[0] == "const":
if (not is_real_number(time_stretch_tuple[1]) or
time_stretch_tuple[1] <= 0):
raise ScaperError(
'Time stretch must be a real number greater than zero.')
elif time_stretch_tuple[0] == "choose":
if (not time_stretch_tuple[1] or
not is_real_array(time_stretch_tuple[1]) or
not all(x > 0 for x in time_stretch_tuple[1])):
raise ScaperError(
'Time stretch list must be a non-empty list of positive '
'real numbers.')
elif time_stretch_tuple[0] == "uniform":
if time_stretch_tuple[1] <= 0:
raise ScaperError(
'A "uniform" distribution tuple for time stretch must have '
'min_value > 0')
elif time_stretch_tuple[0] == "normal":
warnings.warn(
'A "normal" distribution tuple for time stretch can result in '
'non-positives values, in which case the distribution will be '
're-sampled until a positive value is returned: this can '
'result in an infinite loop!',
ScaperWarning)
elif time_stretch_tuple[0] == "truncnorm":
if time_stretch_tuple[3] <= 0:
raise ScaperError(
'A "truncnorm" distirbution tuple for time stretch must '
'specify a positive trunc_min value.')
# TODO: do we want to impose limits on the possible time stretch
# values?
def _validate_event(label, source_file, source_time, event_time,
event_duration, snr, allowed_labels, pitch_shift,
time_stretch):
'''
Check that event parameter values are valid.
Parameters
----------
label : tuple
source_file : tuple
source_time : tuple
event_time : tuple
event_duration : tuple
snr : tuple
allowed_labels : list
List of allowed labels for the event.
pitch_shift : tuple or None
time_stretch: tuple or None
Raises
------
ScaperError :
If any of the input parameters has an invalid format or value.
See Also
--------
Scaper.add_event : Add a foreground sound event to the foreground
specification.
'''
# allowed_labels must be a list. All other parameters will be validated
# individually.
if not isinstance(allowed_labels, list):
raise ScaperError('allowed_labels must be of type list.')
# SOURCE FILE
_validate_source_file(source_file, label)
# LABEL
_validate_label(label, allowed_labels)
# SOURCE TIME
_validate_time(source_time)
# EVENT TIME
_validate_time(event_time)
# EVENT DURATION
_validate_duration(event_duration)
# SNR
_validate_snr(snr)
# Pitch shift
_validate_pitch_shift(pitch_shift)
# Time stretch
_validate_time_stretch(time_stretch)
class Scaper(object):
'''
Create a Scaper object.
Parameters
----------
duration : float
Duration of the soundscape, in seconds.
fg_path : str
Path to foreground folder.
bg_path : str
Path to background folder.
protected_labels : list
Provide a list of protected foreground labels. When a foreground
label is in the protected list it means that when a sound event
matching the label gets added to a soundscape instantiation the
duration of the source audio file cannot be altered, and the
duration value that was provided in the specification will be
ignored.
Adding labels to the protected list is useful for sound events
whose semantic validity would be lost if the sound were trimmed
before the sound event ends, for example an animal vocalization
such as a dog bark.
'''
def __init__(self, duration, fg_path, bg_path, protected_labels=[]):
'''
Create a Scaper object.
Parameters
----------
duration : float
Duration of the soundscape, in seconds.
fg_path : str
Path to foreground folder.
bg_path : str
Path to background folder.
protected_labels : list
Provide a list of protected foreground labels. When a foreground
label is in the protected list it means that when a sound event
matching the label gets added to a soundscape instantiation the
duration of the source audio file cannot be altered, and the
duration value that was provided in the specification will be
ignored.
Adding labels to the protected list is useful for sound events
whose semantic validity would be lost if the sound were trimmed
before the sound event ends, for example an animal vocalization
such as a dog bark.
'''
# Duration must be a positive real number
if np.isrealobj(duration) and duration > 0:
self.duration = duration
else:
raise ScaperError('Duration must be a positive real value')
# Initialize parameters
self.sr = 44100
self.ref_db = -12
self.n_channels = 1
self.fade_in_len = 0.01 # 10 ms
self.fade_out_len = 0.01 # 10 ms
# Start with empty specifications
self.fg_spec = []
self.bg_spec = []
# Validate paths and set
expanded_fg_path = os.path.expanduser(fg_path)
expanded_bg_path = os.path.expanduser(bg_path)
_validate_folder_path(expanded_fg_path)
_validate_folder_path(expanded_bg_path)
self.fg_path = expanded_fg_path
self.bg_path = expanded_bg_path
# Populate label lists from folder paths
self.fg_labels = []
self.bg_labels = []
_populate_label_list(self.fg_path, self.fg_labels)
_populate_label_list(self.bg_path, self.bg_labels)
# Copy list of protected labels
self.protected_labels = protected_labels[:]
def add_background(self, label, source_file, source_time):
'''
Add a background recording to the background specification.
The background duration will be equal to the duration of the
soundscape ``Scaper.duration`` specified when initializing the Scaper
object. If the source file is shorter than this duration then it will
be concatenated to itself as many times as necessary to produce the
specified duration when calling ``Scaper.generate``.
Parameters
----------
label : tuple
Specifies the label of the background. See Notes below for the
expected format of this tuple and the allowed values.
NOTE: The label specified by this tuple must match one
of the labels in the Scaper's background label list
``Scaper.bg_labels``. Furthermore, if ``source_file`` is
specified using "const" (see Notes), then ``label`` must also be
specified using "const" and its value (see Notes) must
match the source file's parent folder's name.
source_file : tuple
Specifies the audio file to use as the source. See Notes below for
the expected format of this tuple and the allowed values.
NOTE: If ``source_file`` is specified using "const" (see Notes),
then ``label`` must also be specified using "const" and its
value (see Notes) must match the source file's parent folder's
name.
source_time : tuple
Specifies the desired start time in the source file. See Notes
below for the expected format of this tuple and the allowed values.
NOTE: the source time specified by this tuple should be equal to or
smaller than ``<source file duration> - <soundscape duration>``.
Larger values will be automatically changed to fulfill this
requirement when calling ``Scaper.generate``.
Notes
-----
Each parameter of this function is set by passing a distribution
tuple, whose first item is always the distribution name and subsequent
items are distribution specific. The supported distribution tuples are:
* ``("const", value)`` : a constant, given by ``value``.
* ``("choose", valuelist)`` : choose a value from
``valuelist`` at random (uniformly). The ``label`` and
``source_file`` parameters also support providing an empty
``valuelist`` i.e. ``("choose", [])``, in which case the
value will be chosen at random from all available labels or files
as determined automatically by Scaper by examining the file
structure of ``bg_path`` provided during initialization.
* ``("uniform", min_value, max_value)`` : sample a random
value from a uniform distribution between ``min_value``
and ``max_value``.
* ``("normal", mean, stddev)`` : sample a random value from a
normal distribution defined by its mean ``mean`` and
standard deviation ``stddev``.
IMPORTANT: not all parameters support all distribution tuples. In
particular, ``label`` and ``source_file`` only support ``"const"`` and
``"choose"``, whereas ``source_time`` supports all distribution tuples.
As noted above, only ``label`` and ``source_file`` support providing an
empty ``valuelist`` with ``"choose"``.
'''
# These values are fixed for the background sound
event_time = ("const", 0)
event_duration = ("const", self.duration)
snr = ("const", 0)
role = 'background'
pitch_shift = None
time_stretch = None
# Validate parameter format and values
_validate_event(label, source_file, source_time, event_time,
event_duration, snr, self.bg_labels, None, None)
# Create background sound event
bg_event = EventSpec(label=label,
source_file=source_file,
source_time=source_time,
event_time=event_time,
event_duration=event_duration,
snr=snr,
role=role,
pitch_shift=pitch_shift,
time_stretch=time_stretch)
# Add event to background spec
self.bg_spec.append(bg_event)
def add_event(self, label, source_file, source_time, event_time,
event_duration, snr, pitch_shift, time_stretch):
'''
Add a foreground sound event to the foreground specification.
Parameters
----------
label : tuple
Specifies the label of the sound event. See Notes below for the
expected format of this tuple and the allowed values.
NOTE: The label specified by this tuple must match one
of the labels in the Scaper's foreground label list
``Scaper.fg_labels``. Furthermore, if ``source_file`` is
specified using "const" (see Notes), then ``label`` must also be
specified using "const" and its ``value `` (see Notes) must
match the source file's parent folder's name.
source_file : tuple
Specifies the audio file to use as the source. See Notes below for
the expected format of this tuple and the allowed values.
NOTE: If ``source_file`` is specified using "const" (see Notes),
then ``label`` must also be specified using "const" and its
``value`` (see Notes) must match the source file's parent
folder's name.
source_time : tuple
Specifies the desired start time in the source file. See Notes
below for the expected format of this tuple and the allowed values.
NOTE: the source time specified by this tuple should be equal to or
smaller than ``<source file duration> - event_duration``. Larger
values will be automatically changed to fulfill this requirement
when calling ``Scaper.generate``.
event_time : tuple
Specifies the desired start time of the event in the soundscape.
See Notes below for the expected format of this tuple and the
allowed values.
NOTE: The value specified by this tuple should be equal to or
smaller than ``<soundscapes duration> - event_duration``, and
larger values will be automatically changed to fulfill this
requirement when calling ``Scaper.generate``.
event_duration : tuple
Specifies the desired duration of the event. See Notes below for
the expected format of this tuple and the allowed values.
NOTE: The value specified by this tuple should be equal to or
smaller than the source file's duration, and larger values will be
automatically changed to fulfill this requirement when calling
``Scaper.generate``.
snr : tuple
Specifies the desired signal to noise ratio (SNR) between the event
and the background. See Notes below for the expected format of
this tuple and the allowed values.
pitch_shift : tuple
Specifies the number of semitones to shift the event by. None means
no pitch shift.
time_stretch: tuple
Specifies the time stretch factor (value>1 will make it slower and
longer, value<1 will makes it faster and shorter).
Notes
-----
Each parameter of this function is set by passing a distribution
tuple, whose first item is always the distribution name and subsequent
items are distribution specific. The supported distribution tuples are:
* ``("const", value)`` : a constant, given by ``value``.
* ``("choose", valuelist)`` : choose a value from
``valuelist`` at random (uniformly). The ``label`` and
``source_file`` parameters also support providing an empty
``valuelist`` i.e. ``("choose", [])``, in which case the
value will be chosen at random from all available labels or
source files as determined automatically by Scaper by examining
the file structure of ``fg_path`` provided during
initialization.
* ``("uniform", min_value, max_value)`` : sample a random
value from a uniform distribution between ``min_value``
and ``max_value`` (including ``max_value``).
* ``("normal", mean, stddev)`` : sample a random value from a
normal distribution defined by its mean ``mean`` and
standard deviation ``stddev``.
IMPORTANT: not all parameters support all distribution tuples. In
particular, ``label`` and ``source_file`` only support ``"const"`` and
``"choose"``, whereas the remaining parameters support all distribution
tuples. As noted above, only ``label`` and ``source_file`` support
providing an empty ``valuelist`` with ``"choose"``.
See Also
--------
_validate_event : Check that event parameter values are valid.
Scaper.generate : Generate a soundscape based on the current
specification and save to disk as both an audio file and a JAMS file
describing the soundscape.