bodhisativa commited on
Commit
d6ed3bd
·
verified ·
1 Parent(s): cf32826

Mirror lj1995/VoiceConversionWebUI @ b2c8cae96e3b — slicer.py

Browse files
Files changed (1) hide show
  1. slicer.py +151 -0
slicer.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path
2
+ from argparse import ArgumentParser
3
+ import time
4
+
5
+ import librosa
6
+ import numpy as np
7
+ import soundfile
8
+ from scipy.ndimage import maximum_filter1d, uniform_filter1d
9
+
10
+
11
+ def timeit(func):
12
+ def run(*args, **kwargs):
13
+ t = time.time()
14
+ res = func(*args, **kwargs)
15
+ print('executing \'%s\' costed %.3fs' % (func.__name__, time.time() - t))
16
+ return res
17
+ return run
18
+
19
+
20
+ # @timeit
21
+ def _window_maximum(arr, win_sz):
22
+ return maximum_filter1d(arr, size=win_sz)[win_sz // 2: win_sz // 2 + arr.shape[0] - win_sz + 1]
23
+
24
+
25
+ # @timeit
26
+ def _window_rms(arr, win_sz):
27
+ filtered = np.sqrt(uniform_filter1d(np.power(arr, 2), win_sz) - np.power(uniform_filter1d(arr, win_sz), 2))
28
+ return filtered[win_sz // 2: win_sz // 2 + arr.shape[0] - win_sz + 1]
29
+
30
+
31
+ def level2db(levels, eps=1e-12):
32
+ return 20 * np.log10(np.clip(levels, a_min=eps, a_max=1))
33
+
34
+
35
+ def _apply_slice(audio, begin, end):
36
+ if len(audio.shape) > 1:
37
+ return audio[:, begin: end]
38
+ else:
39
+ return audio[begin: end]
40
+
41
+
42
+ class Slicer:
43
+ def __init__(self,
44
+ sr: int,
45
+ db_threshold: float = -40,
46
+ min_length: int = 5000,
47
+ win_l: int = 300,
48
+ win_s: int = 20,
49
+ max_silence_kept: int = 500):
50
+ self.db_threshold = db_threshold
51
+ self.min_samples = round(sr * min_length / 1000)
52
+ self.win_ln = round(sr * win_l / 1000)
53
+ self.win_sn = round(sr * win_s / 1000)
54
+ self.max_silence = round(sr * max_silence_kept / 1000)
55
+ if not self.min_samples >= self.win_ln >= self.win_sn:
56
+ raise ValueError('The following condition must be satisfied: min_length >= win_l >= win_s')
57
+ if not self.max_silence >= self.win_sn:
58
+ raise ValueError('The following condition must be satisfied: max_silence_kept >= win_s')
59
+
60
+ @timeit
61
+ def slice(self, audio):
62
+ if len(audio.shape) > 1:
63
+ samples = librosa.to_mono(audio)
64
+ else:
65
+ samples = audio
66
+ if samples.shape[0] <= self.min_samples:
67
+ return [audio]
68
+ # get absolute amplitudes
69
+ abs_amp = np.abs(samples - np.mean(samples))
70
+ # calculate local maximum with large window
71
+ win_max_db = level2db(_window_maximum(abs_amp, win_sz=self.win_ln))
72
+ sil_tags = []
73
+ left = right = 0
74
+ while right < win_max_db.shape[0]:
75
+ if win_max_db[right] < self.db_threshold:
76
+ right += 1
77
+ elif left == right:
78
+ left += 1
79
+ right += 1
80
+ else:
81
+ if left == 0:
82
+ split_loc_l = left
83
+ else:
84
+ sil_left_n = min(self.max_silence, (right + self.win_ln - left) // 2)
85
+ rms_db_left = level2db(_window_rms(samples[left: left + sil_left_n], win_sz=self.win_sn))
86
+ split_win_l = left + np.argmin(rms_db_left)
87
+ split_loc_l = split_win_l + np.argmin(abs_amp[split_win_l: split_win_l + self.win_sn])
88
+ if len(sil_tags) != 0 and split_loc_l - sil_tags[-1][1] < self.min_samples and right < win_max_db.shape[0] - 1:
89
+ right += 1
90
+ left = right
91
+ continue
92
+ if right == win_max_db.shape[0] - 1:
93
+ split_loc_r = right + self.win_ln
94
+ else:
95
+ sil_right_n = min(self.max_silence, (right + self.win_ln - left) // 2)
96
+ rms_db_right = level2db(_window_rms(samples[right + self.win_ln - sil_right_n: right + self.win_ln], win_sz=self.win_sn))
97
+ split_win_r = right + self.win_ln - sil_right_n + np.argmin(rms_db_right)
98
+ split_loc_r = split_win_r + np.argmin(abs_amp[split_win_r: split_win_r + self.win_sn])
99
+ sil_tags.append((split_loc_l, split_loc_r))
100
+ right += 1
101
+ left = right
102
+ if left != right:
103
+ sil_left_n = min(self.max_silence, (right + self.win_ln - left) // 2)
104
+ rms_db_left = level2db(_window_rms(samples[left: left + sil_left_n], win_sz=self.win_sn))
105
+ split_win_l = left + np.argmin(rms_db_left)
106
+ split_loc_l = split_win_l + np.argmin(abs_amp[split_win_l: split_win_l + self.win_sn])
107
+ sil_tags.append((split_loc_l, samples.shape[0]))
108
+ if len(sil_tags) == 0:
109
+ return [audio]
110
+ else:
111
+ chunks = []
112
+ if sil_tags[0][0] > 0:
113
+ chunks.append(_apply_slice(audio, 0, sil_tags[0][0]))
114
+ for i in range(0, len(sil_tags) - 1):
115
+ chunks.append(_apply_slice(audio, sil_tags[i][1], sil_tags[i + 1][0]))
116
+ if sil_tags[-1][1] < samples.shape[0] - 1:
117
+ chunks.append(_apply_slice(audio, sil_tags[-1][1], samples.shape[0]))
118
+ return chunks
119
+
120
+
121
+ def main():
122
+ parser = ArgumentParser()
123
+ parser.add_argument('audio', type=str, help='The audio to be sliced')
124
+ parser.add_argument('--out', type=str, help='Output directory of the sliced audio clips')
125
+ parser.add_argument('--db_thresh', type=float, required=False, default=-40, help='The dB threshold for silence detection')
126
+ parser.add_argument('--min_len', type=int, required=False, default=5000, help='The minimum milliseconds required for each sliced audio clip')
127
+ parser.add_argument('--win_l', type=int, required=False, default=300, help='Size of the large sliding window, presented in milliseconds')
128
+ parser.add_argument('--win_s', type=int, required=False, default=20, help='Size of the small sliding window, presented in milliseconds')
129
+ parser.add_argument('--max_sil_kept', type=int, required=False, default=500, help='The maximum silence length kept around the sliced audio, presented in milliseconds')
130
+ args = parser.parse_args()
131
+ out = args.out
132
+ if out is None:
133
+ out = os.path.dirname(os.path.abspath(args.audio))
134
+ audio, sr = librosa.load(args.audio, sr=None)
135
+ slicer = Slicer(
136
+ sr=sr,
137
+ db_threshold=args.db_thresh,
138
+ min_length=args.min_len,
139
+ win_l=args.win_l,
140
+ win_s=args.win_s,
141
+ max_silence_kept=args.max_sil_kept
142
+ )
143
+ chunks = slicer.slice(audio)
144
+ if not os.path.exists(args.out):
145
+ os.makedirs(args.out)
146
+ for i, chunk in enumerate(chunks):
147
+ soundfile.write(os.path.join(out, f'%s_%d.wav' % (os.path.basename(args.audio).rsplit('.', maxsplit=1)[0], i)), chunk, sr)
148
+
149
+
150
+ if __name__ == '__main__':
151
+ main()