-
Notifications
You must be signed in to change notification settings - Fork 3
/
repet.py
1545 lines (1210 loc) · 60.2 KB
/
repet.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
"""
This Python module implements a number of functions for the REpeating Pattern Extraction Technique (REPET).
Repetition is a fundamental element in generating and perceiving structure. In audio, mixtures are
often composed of structures where a repeating background signal is superimposed with a varying
foreground signal (e.g., a singer overlaying varying vocals on a repeating accompaniment or a varying
speech signal mixed up with a repeating background noise). On this basis, we present the REpeating
Pattern Extraction Technique (REPET), a simple approach for separating the repeating background from
the non-repeating foreground in an audio mixture. The basic idea is to find the repeating elements in
the mixture, derive the underlying repeating models, and extract the repeating background by comparing
the models to the mixture. Unlike other separation approaches, REPET does not depend on special
parameterizations, does not rely on complex frameworks, and does not require external information.
Because it is only based on repetition, it has the advantage of being simple, fast, blind, and
therefore completely and easily automatable.
Functions:
original - Compute the original REPET.
extended - Compute REPET extended.
adaptive - Compute the adaptive REPET.
sim - Compute REPET-SIM.
simonline - Compute the online REPET-SIM.
Other:
wavread - Read a WAVE file (using SciPy).
wavwrite - Write a WAVE file (using SciPy).
specshow - Display an spectrogram in dB, seconds, and Hz.
Author:
Zafar Rafii
http://zafarrafii.com
https://github.com/zafarrafii
https://www.linkedin.com/in/zafarrafii/
01/27/21
"""
import numpy as np
import scipy.signal
import scipy.io.wavfile
import matplotlib.pyplot as plt
# Public variables
# Define the cutoff frequency in Hz for the dual high-pass filter of the foreground (vocals are rarely below 100 Hz)
cutoff_frequency = 100
# Define the period range in seconds for the beat spectrum (for the original REPET, REPET extented, and the adaptive REPET)
period_range = [1, 10]
# Define the segment length and step in seconds (for REPET extented and the adaptive REPET)
segment_length = 10
segment_step = 5
# Define the filter order for the median filter (for the adaptive REPET)
filter_order = 5
# Define the minimal threshold for two similar frames in [0,1], minimal distance between two similar frames in seconds,
# and maximal number of similar frames for every frame (for REPET-SIM and the online REPET-SIM)
similarity_threshold = 0
similarity_distance = 1
similarity_number = 100
# Define the buffer length in seconds (for the online REPET-SIM)
buffer_length = 10
# Public functions
def original(audio_signal, sampling_frequency):
"""
Compute the original REPET.
The original REPET aims at identifying and extracting the repeating patterns in an audio mixture, by estimating
a period of the underlying repeating structure and modeling a segment of the periodically repeating background.
Inputs:
audio_signal: audio signal (number_samples, number_channels)
sampling_frequency: sampling frequency in Hz
Output
background_signal: background signal (number_samples, number_channels)
Example: Estimate the background and foreground signals, and display their spectrograms.
# Import the modules
import numpy as np
import scipy.signal
import repet
import matplotlib.pyplot as plt
# Read the audio signal (normalized) with its sampling frequency in Hz
audio_signal, sampling_frequency = repet.wavread("audio_file.wav")
# Estimate the background signal, and the foreground signal
background_signal = repet.original(audio_signal, sampling_frequency)
foreground_signal = audio_signal-background_signal
# Write the background and foreground signals
repet.wavwrite(background_signal, sampling_frequency, "background_signal.wav")
repet.wavwrite(foreground_signal, sampling_frequency, "foreground_signal.wav")
# Compute the mixture, background, and foreground spectrograms
window_length = pow(2, int(np.ceil(np.log2(0.04*sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length/2)
number_frequencies = int(window_length/2)+1
audio_spectrogram = abs(repet._stft(np.mean(audio_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
background_spectrogram = abs(repet._stft(np.mean(background_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
foreground_spectrogram = abs(repet._stft(np.mean(foreground_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
# Display the mixture, background, and foreground spectrograms in dB, seconds, and Hz
time_duration = len(audio_signal)/sampling_frequency
maximum_frequency = sampling_frequency/8
xtick_step = 1
ytick_step = 1000
plt.figure(figsize=(17, 10))
plt.subplot(3,1,1)
repet.specshow(audio_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Audio spectrogram (dB)")
plt.subplot(3,1,2)
repet.specshow(background_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Background spectrogram (dB)")
plt.subplot(3,1,3)
repet.specshow(foreground_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Foreground spectrogram (dB)")
plt.show()
"""
# Get the number of samples and channels in the audio signal
number_samples, number_channels = np.shape(audio_signal)
# Set the parameters for the STFT
# (audio stationary around 40 ms, power of 2 for fast FFT and constant overlap-add (COLA),
# periodic Hamming window for COLA, and step equal to half the window length for COLA)
window_length = pow(2, int(np.ceil(np.log2(0.04 * sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length / 2)
# Derive the number of time frames (given the zero-padding at the start and the end of the signal)
number_times = (
int(
np.ceil(
(
(number_samples + 2 * int(np.floor(window_length / 2)))
- window_length
)
/ step_length
)
)
+ 1
)
# Initialize the STFT
audio_stft = np.zeros((window_length, number_times, number_channels), dtype=complex)
# Loop over the channels
for i in range(number_channels):
# Compute the STFT of the current channel
audio_stft[:, :, i] = _stft(audio_signal[:, i], window_function, step_length)
# Derive the magnitude spectrogram (with the DC component and without the mirrored frequencies)
audio_spectrogram = abs(audio_stft[0 : int(window_length / 2) + 1, :, :])
# Compute the beat spectrum of the spectrograms averaged over the channels
# (take the square to emphasize peaks of periodicitiy)
beat_spectrum = _beatspectrum(np.power(np.mean(audio_spectrogram, axis=2), 2))
# Get the period range in time frames for the beat spectrum
period_range2 = np.round(
np.array(period_range) * sampling_frequency / step_length
).astype(int)
# Estimate the repeating period in time frames given the period range
repeating_period = _periods(beat_spectrum, period_range2)
# Get the cutoff frequency in frequency channels for the dual high-pass filter of the foreground
cutoff_frequency2 = round(cutoff_frequency * window_length / sampling_frequency)
# Initialize the background signal
background_signal = np.zeros((number_samples, number_channels))
# Loop over the channels
for i in range(number_channels):
# Compute the repeating mask for the current channel given the repeating period
repeating_mask = _mask(audio_spectrogram[:, :, i], repeating_period)
# Perform a high-pass filtering of the dual foreground
repeating_mask[1 : cutoff_frequency2 + 1, :] = 1
# Recover the mirrored frequencies
repeating_mask = np.concatenate(
(repeating_mask, repeating_mask[-2:0:-1, :]), axis=0
)
# Synthesize the repeating background for the current channel
background_signal1 = _istft(
repeating_mask * audio_stft[:, :, i],
window_function,
step_length,
)
# Truncate to the original number of samples
background_signal[:, i] = background_signal1[0:number_samples]
return background_signal
def extended(audio_signal, sampling_frequency):
"""
Compute REPET extended.
The original REPET can be easily extended to handle varying repeating structures, by simply applying the method
along time, on individual segments or via a sliding window.
Inputs:
audio_signal: audio signal (number_samples, number_channels)
sampling_frequency: sampling frequency in Hz
Output
background_signal: background signal (number_samples, number_channels)
Example: Estimate the background and foreground signals, and display their spectrograms.
# Import the modules
import numpy as np
import scipy.signal
import repet
import matplotlib.pyplot as plt
# Read the audio signal (normalized) with its sampling frequency in Hz
audio_signal, sampling_frequency = repet.wavread("audio_file.wav")
# Estimate the background signal, and the foreground signal
background_signal = repet.extended(audio_signal, sampling_frequency)
foreground_signal = audio_signal-background_signal
# Write the background and foreground signals
repet.wavwrite(background_signal, sampling_frequency, "background_signal.wav")
repet.wavwrite(foreground_signal, sampling_frequency, "foreground_signal.wav")
# Compute the mixture, background, and foreground spectrograms
window_length = pow(2, int(np.ceil(np.log2(0.04*sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length/2)
number_frequencies = int(window_length/2)+1
audio_spectrogram = abs(repet._stft(np.mean(audio_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
background_spectrogram = abs(repet._stft(np.mean(background_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
foreground_spectrogram = abs(repet._stft(np.mean(foreground_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
# Display the mixture, background, and foreground spectrograms in dB, seconds, and Hz
time_duration = len(audio_signal)/sampling_frequency
maximum_frequency = sampling_frequency/8
xtick_step = 1
ytick_step = 1000
plt.figure(figsize=(17, 10))
plt.subplot(3,1,1)
repet.specshow(audio_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Audio spectrogram (dB)")
plt.subplot(3,1,2)
repet.specshow(background_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Background spectrogram (dB)")
plt.subplot(3,1,3)
repet.specshow(foreground_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Foreground spectrogram (dB)")
plt.show()
"""
# Get the number of samples and channels in the audio signal
number_samples, number_channels = np.shape(audio_signal)
# Get the segment length, step, and overlap in samples
segment_length2 = round(segment_length * sampling_frequency)
segment_step2 = round(segment_step * sampling_frequency)
segment_overlap2 = segment_length2 - segment_step2
# Get the number of segments
if number_samples < segment_length2 + segment_step2:
# Use a single segment if the signal is too short
number_segments = 1
else:
# Use multiple segments if the signal is long enough (the last segment could be longer)
number_segments = 1 + int(
np.floor((number_samples - segment_length2) / segment_step2)
)
# Use a triangular window for the overlapping parts
segment_window = scipy.signal.triang(2 * segment_overlap2)
# Set the parameters for the STFT
# (audio stationary around 40 ms, power of 2 for fast FFT and constant overlap-add (COLA),
# periodic Hamming window for COLA, and step equal half the window length for COLA)
window_length = pow(2, int(np.ceil(np.log2(0.04 * sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length / 2)
# Get the period range in time frames for the beat spectrum
period_range2 = np.round(
np.array(period_range) * sampling_frequency / step_length
).astype(int)
# Get the cutoff frequency in frequency channels for the dual high-pass filter of the foreground
cutoff_frequency2 = round(cutoff_frequency * window_length / sampling_frequency)
# Initialize the background signal
background_signal = np.zeros((number_samples, number_channels))
# Loop over the segments
k = 0
for j in range(number_segments):
# Check if there is a single segment or multiple ones
if number_segments == 1:
# Use the whole signal as the segment
audio_segment = audio_signal
segment_length2 = number_samples
else:
# Check if it is one of the first segments (same length) or the last one (could be longer)
if j < number_segments - 1:
audio_segment = audio_signal[k : k + segment_length2, :]
elif j == number_segments - 1:
audio_segment = audio_signal[k:number_samples, :]
segment_length2 = len(audio_segment)
# Get the number of time frames
number_times = int(
np.ceil((window_length - step_length + segment_length2) / step_length)
)
# Initialize the STFT
audio_stft = np.zeros(
(window_length, number_times, number_channels), dtype=complex
)
# Loop over the channels
for i in range(number_channels):
# Compute the STFT for the current channel
audio_stft[:, :, i] = _stft(
audio_segment[:, i], window_function, step_length
)
# Derive the magnitude spectrogram (with the DC component and without the mirrored frequencies)
audio_spectrogram = abs(audio_stft[0 : int(window_length / 2) + 1, :, :])
# Compute the beat spectrum of the spectrograms averaged over the channels
# (take the square to emphasize peaks of periodicitiy)
beat_spectrum = _beatspectrum(np.power(np.mean(audio_spectrogram, axis=2), 2))
# Estimate the repeating period in time frames given the period range
repeating_period = _periods(beat_spectrum, period_range2)
# Initialize the background segment
background_segment = np.zeros((segment_length2, number_channels))
# Loop over the channels
for i in range(number_channels):
# Compute the repeating mask for the current channel given the repeating period
repeating_mask = _mask(audio_spectrogram[:, :, i], repeating_period)
# Perform a high-pass filtering of the dual foreground
repeating_mask[1 : cutoff_frequency2 + 1, :] = 1
# Recover the mirrored frequencies
repeating_mask = np.concatenate(
(repeating_mask, repeating_mask[-2:0:-1, :])
)
# Synthesize the repeating background for the current channel
background_segment1 = _istft(
repeating_mask * audio_stft[:, :, i],
window_function,
step_length,
)
# Truncate to the original number of samples
background_segment[:, i] = background_segment1[0:segment_length2]
# Check again if there is a single segment or multiple ones
if number_segments == 1:
# Use the segment as the whole signal
background_signal = background_segment
else:
# Check if it is the first segment or the following ones
if j == 0:
# Add the segment to the signal
background_signal[0:segment_length2, :] = (
background_signal[0:segment_length2, :] + background_segment
)
elif j <= number_segments - 1:
# Perform a half windowing of the overlap part of the background signal on the right
background_signal[k : k + segment_overlap2, :] = (
background_signal[k : k + segment_overlap2, :]
* segment_window[
segment_overlap2 : 2 * segment_overlap2, np.newaxis
]
)
# Perform a half windowing of the overlap part of the background segment on the left
background_segment[0:segment_overlap2, :] = (
background_segment[0:segment_overlap2, :]
* segment_window[0:segment_overlap2, np.newaxis]
)
# Add the segment to the signal
background_signal[k : k + segment_length2, :] = (
background_signal[k : k + segment_length2, :] + background_segment
)
# Update the index
k = k + segment_step2
return background_signal
def adaptive(audio_signal, sampling_frequency):
"""
Compute the adaptive REPET.
The original REPET works well when the repeating background is relatively stable (e.g., a verse or the chorus in
a song); however, the repeating background can also vary over time (e.g., a verse followed by the chorus in the
song). The adaptive REPET is an extension of the original REPET that can handle varying repeating structures, by
estimating the time-varying repeating periods and extracting the repeating background locally, without the need
for segmentation or windowing.
Inputs:
audio_signal: audio signal (number_samples, number_channels)
sampling_frequency: sampling frequency in Hz
Output
background_signal: background signal (number_samples, number_channels)
Example: Estimate the background and foreground signals, and display their spectrograms.
# Import the modules
import numpy as np
import scipy.signal
import repet
import matplotlib.pyplot as plt
# Read the audio signal (normalized) with its sampling frequency in Hz
audio_signal, sampling_frequency = repet.wavread("audio_file.wav")
# Estimate the background signal, and the foreground signal
background_signal = repet.adaptive(audio_signal, sampling_frequency)
foreground_signal = audio_signal-background_signal
# Write the background and foreground signals
repet.wavwrite(background_signal, sampling_frequency, "background_signal.wav")
repet.wavwrite(foreground_signal, sampling_frequency, "foreground_signal.wav")
# Compute the mixture, background, and foreground spectrograms
window_length = pow(2, int(np.ceil(np.log2(0.04*sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length/2)
number_frequencies = int(window_length/2)+1
audio_spectrogram = abs(repet._stft(np.mean(audio_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
background_spectrogram = abs(repet._stft(np.mean(background_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
foreground_spectrogram = abs(repet._stft(np.mean(foreground_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
# Display the mixture, background, and foreground spectrograms in dB, seconds, and Hz
time_duration = len(audio_signal)/sampling_frequency
maximum_frequency = sampling_frequency/8
xtick_step = 1
ytick_step = 1000
plt.figure(figsize=(17, 10))
plt.subplot(3,1,1)
repet.specshow(audio_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Audio spectrogram (dB)")
plt.subplot(3,1,2)
repet.specshow(background_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Background spectrogram (dB)")
plt.subplot(3,1,3)
repet.specshow(foreground_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Foreground spectrogram (dB)")
plt.show()
"""
# Get the number of samples and channels in the audio signal
number_samples, number_channels = np.shape(audio_signal)
# Set the parameters for the STFT
# (audio stationary around 40 ms, power of 2 for fast FFT and constant overlap-add (COLA),
# periodic Hamming window for COLA, and step equal to half the window length for COLA)
window_length = pow(2, int(np.ceil(np.log2(0.04 * sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length / 2)
# Derive the number of time frames (given the zero-padding at the start and the end of the signal)
number_times = (
int(
np.ceil(
(
(number_samples + 2 * int(np.floor(window_length / 2)))
- window_length
)
/ step_length
)
)
+ 1
)
# Initialize the STFT
audio_stft = np.zeros((window_length, number_times, number_channels), dtype=complex)
# Loop over the channels
for i in range(number_channels):
# Compute the STFT of the current channel
audio_stft[:, :, i] = _stft(audio_signal[:, i], window_function, step_length)
# Derive the magnitude spectrogram (with the DC component and without the mirrored frequencies)
audio_spectrogram = abs(audio_stft[0 : int(window_length / 2) + 1, :, :])
# Get the segment length and step in time frames for the beat spectrogram
segment_length2 = int(round(segment_length * sampling_frequency / step_length))
segment_step2 = int(round(segment_step * sampling_frequency / step_length))
# Compute the beat spectrogram of the spectrograms averaged over the channels
# (take the square to emphasize peaks of periodicitiy)
beat_spectrogram = _beatspectrogram(
np.power(np.mean(audio_spectrogram, axis=2), 2), segment_length2, segment_step2
)
# Get the period range in time frames
period_range2 = np.round(
np.array(period_range) * sampling_frequency / step_length
).astype(int)
# Estimate the repeating periods in time frames given the period range
repeating_periods = _periods(beat_spectrogram, period_range2)
# Get the cutoff frequency in frequency channels for the dual high-pass filter of the foreground
cutoff_frequency2 = round(cutoff_frequency * window_length / sampling_frequency)
# Initialize the background signal
background_signal = np.zeros((number_samples, number_channels))
# Loop over the channels
for i in range(number_channels):
# Compute the repeating mask for the current channel given the repeating periods
repeating_mask = _adaptivemask(
audio_spectrogram[:, :, i], repeating_periods, filter_order
)
# Perform a high-pass filtering of the dual foreground
repeating_mask[1 : cutoff_frequency2 + 1, :] = 1
# Recover the mirrored frequencies
repeating_mask = np.concatenate(
(repeating_mask, repeating_mask[-2:0:-1, :]), axis=0
)
# Synthesize the repeating background for the current channel
background_signal1 = _istft(
repeating_mask * audio_stft[:, :, i],
window_function,
step_length,
)
# Truncate to the original number of samples
background_signal[:, i] = background_signal1[0:number_samples]
return background_signal
def sim(audio_signal, sampling_frequency):
"""
Compute REPET-SIM.
The REPET methods work well when the repeating background has periodically repeating patterns (e.g., jackhammer
noise); however, the repeating patterns can also happen intermittently or without a global or local periodicity
(e.g., frogs by a pond). REPET-SIM is a generalization of REPET that can also handle non-periodically repeating
structures, by using a similarity matrix to identify the repeating elements.
Inputs:
audio_signal: audio signal (number_samples, number_channels)
sampling_frequency: sampling frequency in Hz
Output
background_signal: background signal (number_samples, number_channels)
Example: Estimate the background and foreground signals, and display their spectrograms.
# Import the modules
import numpy as np
import scipy.signal
import repet
import matplotlib.pyplot as plt
# Read the audio signal (normalized) with its sampling frequency in Hz
audio_signal, sampling_frequency = repet.wavread("audio_file.wav")
# Estimate the background signal, and the foreground signal
background_signal = repet.sim(audio_signal, sampling_frequency)
foreground_signal = audio_signal-background_signal
# Write the background and foreground signals
repet.wavwrite(background_signal, sampling_frequency, "background_signal.wav")
repet.wavwrite(foreground_signal, sampling_frequency, "foreground_signal.wav")
# Compute the mixture, background, and foreground spectrograms
window_length = pow(2, int(np.ceil(np.log2(0.04*sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length/2)
number_frequencies = int(window_length/2)+1
audio_spectrogram = abs(repet._stft(np.mean(audio_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
background_spectrogram = abs(repet._stft(np.mean(background_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
foreground_spectrogram = abs(repet._stft(np.mean(foreground_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
# Display the mixture, background, and foreground spectrograms in dB, seconds, and Hz
time_duration = len(audio_signal)/sampling_frequency
maximum_frequency = sampling_frequency/8
xtick_step = 1
ytick_step = 1000
plt.figure(figsize=(17, 10))
plt.subplot(3,1,1)
repet.specshow(audio_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Audio spectrogram (dB)")
plt.subplot(3,1,2)
repet.specshow(background_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Background spectrogram (dB)")
plt.subplot(3,1,3)
repet.specshow(foreground_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Foreground spectrogram (dB)")
plt.show()
"""
# Get the number of samples and channels in the audio signal
number_samples, number_channels = np.shape(audio_signal)
# Set the parameters for the STFT
# (audio stationary around 40 ms, power of 2 for fast FFT and constant overlap-add (COLA),
# periodic Hamming window for COLA, and step equal half the window length for COLA)
window_length = pow(2, int(np.ceil(np.log2(0.04 * sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length / 2)
# Derive the number of time frames (given the zero-padding at the start and the end of the signal)
number_times = (
int(
np.ceil(
(
(number_samples + 2 * int(np.floor(window_length / 2)))
- window_length
)
/ step_length
)
)
+ 1
)
# Initialize the STFT
audio_stft = np.zeros((window_length, number_times, number_channels), dtype=complex)
# Loop over the channels
for i in range(number_channels):
# Compute the STFT of the current channel
audio_stft[:, :, i] = _stft(audio_signal[:, i], window_function, step_length)
# Derive the magnitude spectrogram (with the DC component and without the mirrored frequencies)
audio_spectrogram = abs(audio_stft[0 : int(window_length / 2) + 1, :, :])
# Compute the self-similarity matrix of the spectrograms averaged over the channels
similarity_matrix = _selfsimilaritymatrix(np.mean(audio_spectrogram, axis=2))
# Get the similarity distance in time frames
similarity_distance2 = int(
round(similarity_distance * sampling_frequency / step_length)
)
# Estimate the similarity indices for all the frames
similarity_indices = _indices(
similarity_matrix, similarity_threshold, similarity_distance2, similarity_number
)
# Get the cutoff frequency in frequency channels for the dual high-pass filter of the foreground
cutoff_frequency2 = round(cutoff_frequency * window_length / sampling_frequency)
# Initialize the background signal
background_signal = np.zeros((number_samples, number_channels))
# Loop over the channels
for i in range(number_channels):
# Compute the repeating mask for the current channel given the similarity indices
repeating_mask = _simmask(audio_spectrogram[:, :, i], similarity_indices)
# Perform a high-pass filtering of the dual foreground
repeating_mask[1 : cutoff_frequency2 + 1, :] = 1
# Recover the mirrored frequencies
repeating_mask = np.concatenate(
(repeating_mask, repeating_mask[-2:0:-1, :]), axis=0
)
# Synthesize the repeating background for the current channel
background_signal1 = _istft(
repeating_mask * audio_stft[:, :, i],
window_function,
step_length,
)
# Truncate to the original number of samples
background_signal[:, i] = background_signal1[0:number_samples]
return background_signal
def simonline(audio_signal, sampling_frequency):
"""
Compute the online REPET-SIM.
REPET-SIM can be easily implemented online to handle real-time computing, particularly for real-time speech
enhancement. The online REPET-SIM simply processes the time frames of the mixture one after the other given a
buffer that temporally stores past frames.
Inputs:
audio_signal: audio signal (number_samples, number_channels)
sampling_frequency: sampling frequency in Hz
Output
background_signal: background signal (number_samples, number_channels)
Example: Estimate the background and foreground signals, and display their spectrograms.
# Import the modules
import numpy as np
import scipy.signal
import repet
import matplotlib.pyplot as plt
# Read the audio signal (normalized) with its sampling frequency in Hz
audio_signal, sampling_frequency = repet.wavread("audio_file.wav")
# Estimate the background signal, and the foreground signal
background_signal = repet.simonline(audio_signal, sampling_frequency)
foreground_signal = audio_signal-background_signal
# Write the background and foreground signals
repet.wavwrite(background_signal, sampling_frequency, "background_signal.wav")
repet.wavwrite(foreground_signal, sampling_frequency, "foreground_signal.wav")
# Compute the mixture, background, and foreground spectrograms
window_length = pow(2, int(np.ceil(np.log2(0.04*sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length/2)
number_frequencies = int(window_length/2)+1
audio_spectrogram = abs(repet._stft(np.mean(audio_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
background_spectrogram = abs(repet._stft(np.mean(background_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
foreground_spectrogram = abs(repet._stft(np.mean(foreground_signal, axis=1), window_function, step_length)[0:number_frequencies, :])
# Display the mixture, background, and foreground spectrograms in dB, seconds, and Hz
time_duration = len(audio_signal)/sampling_frequency
maximum_frequency = sampling_frequency/8
xtick_step = 1
ytick_step = 1000
plt.figure(figsize=(17, 10))
plt.subplot(3,1,1)
repet.specshow(audio_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Audio spectrogram (dB)")
plt.subplot(3,1,2)
repet.specshow(background_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Background spectrogram (dB)")
plt.subplot(3,1,3)
repet.specshow(foreground_spectrogram[0:int(window_length/8), :], time_duration, maximum_frequency, xtick_step, ytick_step)
plt.title("Foreground spectrogram (dB)")
plt.show()
"""
# Get the number of samples and channels in the audio signal
number_samples, number_channels = np.shape(audio_signal)
# Set the parameters for the STFT
# (audio stationary around 40 ms, power of 2 for fast FFT and constant overlap-add (COLA),
# periodic Hamming window for COLA, and step equal half the window length for COLA)
window_length = pow(2, int(np.ceil(np.log2(0.04 * sampling_frequency))))
window_function = scipy.signal.hamming(window_length, sym=False)
step_length = int(window_length / 2)
# Derive the number of time frames
number_times = int(np.ceil((number_samples - window_length) / step_length + 1))
# Derive the number of frequency channels
number_frequencies = int(window_length / 2 + 1)
# Get the buffer length in time frames
buffer_length2 = round((buffer_length * sampling_frequency) / step_length)
# Initialize the buffer spectrogram
buffer_spectrogram = np.zeros((number_frequencies, buffer_length2, number_channels))
# Loop over the time frames to compute the buffer spectrogram
# (the last frame will be the frame to be processed)
k = 0
for j in range(buffer_length2 - 1):
# Loop over the channels
for i in range(number_channels):
# Compute the FT of the segment
buffer_ft = np.fft.fft(
audio_signal[k : k + window_length, i] * window_function,
axis=0,
)
# Derive the magnitude spectrum and save it in the buffer spectrogram
buffer_spectrogram[:, j, i] = abs(buffer_ft[0:number_frequencies])
# Update the index
k = k + step_length
# Zero-pad the audio signal at the end
audio_signal = np.pad(
audio_signal,
(0, (number_times - 1) * step_length + window_length - number_samples),
"constant",
constant_values=0,
)
# Get the similarity distance in time frames
similarity_distance2 = int(
round(similarity_distance * sampling_frequency / step_length)
)
# Get the cutoff frequency in frequency channels for the dual high-pass filter of the foreground
cutoff_frequency2 = round(cutoff_frequency * window_length / sampling_frequency)
# Initialize the background signal
background_signal = np.zeros(
((number_times - 1) * step_length + window_length, number_channels)
)
# Loop over the time frames to compute the background signal
for j in range(buffer_length2 - 1, number_times):
# Get the time index of the current frame
j0 = j % buffer_length2
# Initialize the FT of the current segment
current_ft = np.zeros((window_length, number_channels), dtype=complex)
# Loop over the channels
for i in range(number_channels):
# Compute the FT of the current segment
current_ft[:, i] = np.fft.fft(
audio_signal[k : k + window_length, i] * window_function,
axis=0,
)
# Derive the magnitude spectrum and update the buffer spectrogram
buffer_spectrogram[:, j0, i] = np.abs(current_ft[0:number_frequencies, i])
# Compute the cosine similarity between the current frame and the past ones, for all the channels
similarity_vector = _similaritymatrix(
np.mean(buffer_spectrogram, axis=2),
np.mean(buffer_spectrogram[:, j0 : j0 + 1, :], axis=2),
)
# Estimate the indices of the similar frames
_, similarity_indices = _localmaxima(
similarity_vector[:, 0],
similarity_threshold,
similarity_distance2,
similarity_number,
)
# Loop over the channels
for i in range(number_channels):
# Compute the repeating spectrum for the current frame
repeating_spectrum = np.median(
buffer_spectrogram[:, similarity_indices, i], axis=1
)
# Refine the repeating spectrum
repeating_spectrum = np.minimum(
repeating_spectrum, buffer_spectrogram[:, j0, i]
)
# Derive the repeating mask for the current frame
repeating_mask = (repeating_spectrum + np.finfo(float).eps) / (
buffer_spectrogram[:, j0, i] + np.finfo(float).eps
)
# Perform a high-pass filtering of the dual foreground
repeating_mask[1 : cutoff_frequency2 + 1] = 1
# Recover the mirrored frequencies
repeating_mask = np.concatenate((repeating_mask, repeating_mask[-2:0:-1]))
# Apply the mask to the FT of the current segment
background_ft = repeating_mask * current_ft[:, i]
# Take the inverse FT of the current segment
background_signal[k : k + window_length, i] = background_signal[
k : k + window_length, i
] + np.real(np.fft.ifft(background_ft, axis=0))
# Update the index
k = k + step_length
# Truncate the signal to the original number of samples
background_signal = background_signal[0:number_samples, :]
# Normalize the signal by the gain introduced by the COLA (if any)
background_signal = background_signal / sum(
window_function[0:window_length:step_length]
)
return background_signal
def wavread(audio_file):
"""
Read a WAVE file (using SciPy).
Input:
audio_file: path to an audio file
Outputs:
audio_signal: audio signal (number_samples, number_channels)
sampling_frequency: sampling frequency in Hz
"""
# Read the audio file and return the sampling frequency in Hz and the non-normalized signal using SciPy
sampling_frequency, audio_signal = scipy.io.wavfile.read(audio_file)
# Normalize the signal by the data range given the size of an item in bytes
audio_signal = audio_signal / pow(2, audio_signal.itemsize * 8 - 1)
return audio_signal, sampling_frequency
def wavwrite(audio_signal, sampling_frequency, audio_file):
"""
Write a WAVE file (using Scipy).
Inputs:
audio_signal: audio signal (number_samples, number_channels)
sampling_frequency: sampling frequency in Hz
Output:
audio_file: path to an audio file
"""
# Write the audio signal using SciPy
scipy.io.wavfile.write(audio_file, sampling_frequency, audio_signal)
def specshow(
audio_spectrogram,
time_duration,
maximum_frequency,
xtick_step=1,
ytick_step=1000,
):
"""
Display a spectrogram in dB, seconds, and Hz.
Inputs:
audio_spectrogram: audio spectrogram (without DC and mirrored frequencies) (number_frequencies, number_times)
time_duration: time duration of the spectrogram in seconds
maximum_frequency: maximum frequency in the spectrogram in Hz
xtick_step: step for the x-axis ticks in seconds (default: 1 second)
ytick_step: step for the y-axis ticks in Hz (default: 1000 Hz)
"""
# Get the number of frequency channels and time frames
number_frequencies, number_times = np.shape(audio_spectrogram)
# Derive the number of time frames per second and the number of frequency channels per Hz
time_resolution = number_times / time_duration
frequency_resolution = number_frequencies / maximum_frequency
# Prepare the tick locations and labels for the x-axis
xtick_locations = np.arange(
xtick_step * time_resolution,
number_times,
xtick_step * time_resolution,
)
xtick_labels = np.arange(xtick_step, time_duration, xtick_step).astype(int)
# Prepare the tick locations and labels for the y-axis
ytick_locations = np.arange(
ytick_step * frequency_resolution,
number_frequencies,
ytick_step * frequency_resolution,
)
ytick_labels = np.arange(ytick_step, maximum_frequency, ytick_step).astype(int)
# Display the spectrogram in dB, seconds, and Hz
plt.imshow(
20 * np.log10(audio_spectrogram), aspect="auto", cmap="jet", origin="lower"
)
plt.xticks(ticks=xtick_locations, labels=xtick_labels)
plt.yticks(ticks=ytick_locations, labels=ytick_labels)
plt.xlabel("Time (s)")
plt.ylabel("Frequency (Hz)")
# Private functions