Commit
•
64e26e0
1
Parent(s):
e10fe71
Upload slicer2.py
Browse files- slicer2.py +186 -0
slicer2.py
ADDED
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
|
4 |
+
# This function is obtained from librosa.
|
5 |
+
def get_rms(
|
6 |
+
y,
|
7 |
+
*,
|
8 |
+
frame_length=2048,
|
9 |
+
hop_length=512,
|
10 |
+
pad_mode="constant",
|
11 |
+
):
|
12 |
+
padding = (int(frame_length // 2), int(frame_length // 2))
|
13 |
+
y = np.pad(y, padding, mode=pad_mode)
|
14 |
+
|
15 |
+
axis = -1
|
16 |
+
# put our new within-frame axis at the end for now
|
17 |
+
out_strides = y.strides + tuple([y.strides[axis]])
|
18 |
+
# Reduce the shape on the framing axis
|
19 |
+
x_shape_trimmed = list(y.shape)
|
20 |
+
x_shape_trimmed[axis] -= frame_length - 1
|
21 |
+
out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
|
22 |
+
xw = np.lib.stride_tricks.as_strided(
|
23 |
+
y, shape=out_shape, strides=out_strides
|
24 |
+
)
|
25 |
+
if axis < 0:
|
26 |
+
target_axis = axis - 1
|
27 |
+
else:
|
28 |
+
target_axis = axis + 1
|
29 |
+
xw = np.moveaxis(xw, -1, target_axis)
|
30 |
+
# Downsample along the target axis
|
31 |
+
slices = [slice(None)] * xw.ndim
|
32 |
+
slices[axis] = slice(0, None, hop_length)
|
33 |
+
x = xw[tuple(slices)]
|
34 |
+
|
35 |
+
# Calculate power
|
36 |
+
power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
|
37 |
+
|
38 |
+
return np.sqrt(power)
|
39 |
+
|
40 |
+
|
41 |
+
class Slicer:
|
42 |
+
def __init__(self,
|
43 |
+
sr: int,
|
44 |
+
threshold: float = -40.,
|
45 |
+
min_length: int = 5000,
|
46 |
+
min_interval: int = 300,
|
47 |
+
hop_size: int = 20,
|
48 |
+
max_sil_kept: int = 5000):
|
49 |
+
if not min_length >= min_interval >= hop_size:
|
50 |
+
raise ValueError('The following condition must be satisfied: min_length >= min_interval >= hop_size')
|
51 |
+
if not max_sil_kept >= hop_size:
|
52 |
+
raise ValueError('The following condition must be satisfied: max_sil_kept >= hop_size')
|
53 |
+
min_interval = sr * min_interval / 1000
|
54 |
+
self.threshold = 10 ** (threshold / 20.)
|
55 |
+
self.hop_size = round(sr * hop_size / 1000)
|
56 |
+
self.win_size = min(round(min_interval), 4 * self.hop_size)
|
57 |
+
self.min_length = round(sr * min_length / 1000 / self.hop_size)
|
58 |
+
self.min_interval = round(min_interval / self.hop_size)
|
59 |
+
self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
|
60 |
+
|
61 |
+
def _apply_slice(self, waveform, begin, end):
|
62 |
+
if len(waveform.shape) > 1:
|
63 |
+
return waveform[:, begin * self.hop_size: min(waveform.shape[1], end * self.hop_size)]
|
64 |
+
else:
|
65 |
+
return waveform[begin * self.hop_size: min(waveform.shape[0], end * self.hop_size)]
|
66 |
+
|
67 |
+
# @timeit
|
68 |
+
def slice(self, waveform):
|
69 |
+
if len(waveform.shape) > 1:
|
70 |
+
samples = waveform.mean(axis=0)
|
71 |
+
else:
|
72 |
+
samples = waveform
|
73 |
+
if (samples.shape[0] + self.hop_size - 1) // self.hop_size <= self.min_length:
|
74 |
+
return [waveform]
|
75 |
+
rms_list = get_rms(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0)
|
76 |
+
sil_tags = []
|
77 |
+
silence_start = None
|
78 |
+
clip_start = 0
|
79 |
+
for i, rms in enumerate(rms_list):
|
80 |
+
# Keep looping while frame is silent.
|
81 |
+
if rms < self.threshold:
|
82 |
+
# Record start of silent frames.
|
83 |
+
if silence_start is None:
|
84 |
+
silence_start = i
|
85 |
+
continue
|
86 |
+
# Keep looping while frame is not silent and silence start has not been recorded.
|
87 |
+
if silence_start is None:
|
88 |
+
continue
|
89 |
+
# Clear recorded silence start if interval is not enough or clip is too short
|
90 |
+
is_leading_silence = silence_start == 0 and i > self.max_sil_kept
|
91 |
+
need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length
|
92 |
+
if not is_leading_silence and not need_slice_middle:
|
93 |
+
silence_start = None
|
94 |
+
continue
|
95 |
+
# Need slicing. Record the range of silent frames to be removed.
|
96 |
+
if i - silence_start <= self.max_sil_kept:
|
97 |
+
pos = rms_list[silence_start: i + 1].argmin() + silence_start
|
98 |
+
if silence_start == 0:
|
99 |
+
sil_tags.append((0, pos))
|
100 |
+
else:
|
101 |
+
sil_tags.append((pos, pos))
|
102 |
+
clip_start = pos
|
103 |
+
elif i - silence_start <= self.max_sil_kept * 2:
|
104 |
+
pos = rms_list[i - self.max_sil_kept: silence_start + self.max_sil_kept + 1].argmin()
|
105 |
+
pos += i - self.max_sil_kept
|
106 |
+
pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
|
107 |
+
pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
|
108 |
+
if silence_start == 0:
|
109 |
+
sil_tags.append((0, pos_r))
|
110 |
+
clip_start = pos_r
|
111 |
+
else:
|
112 |
+
sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
|
113 |
+
clip_start = max(pos_r, pos)
|
114 |
+
else:
|
115 |
+
pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
|
116 |
+
pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
|
117 |
+
if silence_start == 0:
|
118 |
+
sil_tags.append((0, pos_r))
|
119 |
+
else:
|
120 |
+
sil_tags.append((pos_l, pos_r))
|
121 |
+
clip_start = pos_r
|
122 |
+
silence_start = None
|
123 |
+
# Deal with trailing silence.
|
124 |
+
total_frames = rms_list.shape[0]
|
125 |
+
if silence_start is not None and total_frames - silence_start >= self.min_interval:
|
126 |
+
silence_end = min(total_frames, silence_start + self.max_sil_kept)
|
127 |
+
pos = rms_list[silence_start: silence_end + 1].argmin() + silence_start
|
128 |
+
sil_tags.append((pos, total_frames + 1))
|
129 |
+
# Apply and return slices.
|
130 |
+
if len(sil_tags) == 0:
|
131 |
+
return [waveform]
|
132 |
+
else:
|
133 |
+
chunks = []
|
134 |
+
if sil_tags[0][0] > 0:
|
135 |
+
chunks.append(self._apply_slice(waveform, 0, sil_tags[0][0]))
|
136 |
+
for i in range(len(sil_tags) - 1):
|
137 |
+
chunks.append(self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0]))
|
138 |
+
if sil_tags[-1][1] < total_frames:
|
139 |
+
chunks.append(self._apply_slice(waveform, sil_tags[-1][1], total_frames))
|
140 |
+
return chunks
|
141 |
+
|
142 |
+
|
143 |
+
def main():
|
144 |
+
import os.path
|
145 |
+
from argparse import ArgumentParser
|
146 |
+
|
147 |
+
import librosa
|
148 |
+
import soundfile
|
149 |
+
|
150 |
+
parser = ArgumentParser()
|
151 |
+
parser.add_argument('audio', type=str, help='The audio to be sliced')
|
152 |
+
parser.add_argument('--out', type=str, help='Output directory of the sliced audio clips')
|
153 |
+
parser.add_argument('--db_thresh', type=float, required=False, default=-40,
|
154 |
+
help='The dB threshold for silence detection')
|
155 |
+
parser.add_argument('--min_length', type=int, required=False, default=5000,
|
156 |
+
help='The minimum milliseconds required for each sliced audio clip')
|
157 |
+
parser.add_argument('--min_interval', type=int, required=False, default=300,
|
158 |
+
help='The minimum milliseconds for a silence part to be sliced')
|
159 |
+
parser.add_argument('--hop_size', type=int, required=False, default=10,
|
160 |
+
help='Frame length in milliseconds')
|
161 |
+
parser.add_argument('--max_sil_kept', type=int, required=False, default=500,
|
162 |
+
help='The maximum silence length kept around the sliced clip, presented in milliseconds')
|
163 |
+
args = parser.parse_args()
|
164 |
+
out = args.out
|
165 |
+
if out is None:
|
166 |
+
out = os.path.dirname(os.path.abspath(args.audio))
|
167 |
+
audio, sr = librosa.load(args.audio, sr=None, mono=False)
|
168 |
+
slicer = Slicer(
|
169 |
+
sr=sr,
|
170 |
+
threshold=args.db_thresh,
|
171 |
+
min_length=args.min_length,
|
172 |
+
min_interval=args.min_interval,
|
173 |
+
hop_size=args.hop_size,
|
174 |
+
max_sil_kept=args.max_sil_kept
|
175 |
+
)
|
176 |
+
chunks = slicer.slice(audio)
|
177 |
+
if not os.path.exists(out):
|
178 |
+
os.makedirs(out)
|
179 |
+
for i, chunk in enumerate(chunks):
|
180 |
+
if len(chunk.shape) > 1:
|
181 |
+
chunk = chunk.T
|
182 |
+
soundfile.write(os.path.join(out, f'%s_%d.wav' % (os.path.basename(args.audio).rsplit('.', maxsplit=1)[0], i)), chunk, sr)
|
183 |
+
|
184 |
+
|
185 |
+
if __name__ == '__main__':
|
186 |
+
main()
|