Spaces:
Running
Running
Next
commited on
Commit
•
279af65
1
Parent(s):
1d37aeb
add daataset maker for more easy training
Browse files- app/dataset_maker.py +166 -0
app/dataset_maker.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import yt_dlp
|
2 |
+
import numpy as np
|
3 |
+
import librosa
|
4 |
+
import soundfile as sf
|
5 |
+
import os
|
6 |
+
import zipfile
|
7 |
+
|
8 |
+
|
9 |
+
# Function to download audio from YouTube and save it as a WAV file
|
10 |
+
def download_youtube_audio(url, audio_name):
|
11 |
+
ydl_opts = {
|
12 |
+
'format': 'bestaudio/best',
|
13 |
+
'postprocessors': [{
|
14 |
+
'key': 'FFmpegExtractAudio',
|
15 |
+
'preferredcodec': 'wav',
|
16 |
+
}],
|
17 |
+
"outtmpl": f'youtubeaudio/{audio_name}', # Output template
|
18 |
+
}
|
19 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
20 |
+
ydl.download([url])
|
21 |
+
return f'youtubeaudio/{audio_name}.wav'
|
22 |
+
|
23 |
+
# Function to calculate RMS
|
24 |
+
def get_rms(y, frame_length=2048, hop_length=512, pad_mode="constant"):
|
25 |
+
padding = (int(frame_length // 2), int(frame_length // 2))
|
26 |
+
y = np.pad(y, padding, mode=pad_mode)
|
27 |
+
|
28 |
+
axis = -1
|
29 |
+
out_strides = y.strides + tuple([y.strides[axis]])
|
30 |
+
x_shape_trimmed = list(y.shape)
|
31 |
+
x_shape_trimmed[axis] -= frame_length - 1
|
32 |
+
out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
|
33 |
+
xw = np.lib.stride_tricks.as_strided(
|
34 |
+
y, shape=out_shape, strides=out_strides
|
35 |
+
)
|
36 |
+
if axis < 0:
|
37 |
+
target_axis = axis - 1
|
38 |
+
else:
|
39 |
+
target_axis = axis + 1
|
40 |
+
xw = np.moveaxis(xw, -1, target_axis)
|
41 |
+
slices = [slice(None)] * xw.ndim
|
42 |
+
slices[axis] = slice(0, None, hop_length)
|
43 |
+
x = xw[tuple(slices)]
|
44 |
+
|
45 |
+
power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
|
46 |
+
return np.sqrt(power)
|
47 |
+
|
48 |
+
# Slicer class
|
49 |
+
class Slicer:
|
50 |
+
def __init__(self, sr, threshold=-40., min_length=5000, min_interval=300, hop_size=20, max_sil_kept=5000):
|
51 |
+
if not min_length >= min_interval >= hop_size:
|
52 |
+
raise ValueError('The following condition must be satisfied: min_length >= min_interval >= hop_size')
|
53 |
+
if not max_sil_kept >= hop_size:
|
54 |
+
raise ValueError('The following condition must be satisfied: max_sil_kept >= hop_size')
|
55 |
+
min_interval = sr * min_interval / 1000
|
56 |
+
self.threshold = 10 ** (threshold / 20.)
|
57 |
+
self.hop_size = round(sr * hop_size / 1000)
|
58 |
+
self.win_size = min(round(min_interval), 4 * self.hop_size)
|
59 |
+
self.min_length = round(sr * min_length / 1000 / self.hop_size)
|
60 |
+
self.min_interval = round(min_interval / self.hop_size)
|
61 |
+
self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
|
62 |
+
|
63 |
+
def _apply_slice(self, waveform, begin, end):
|
64 |
+
if len(waveform.shape) > 1:
|
65 |
+
return waveform[:, begin * self.hop_size: min(waveform.shape[1], end * self.hop_size)]
|
66 |
+
else:
|
67 |
+
return waveform[begin * self.hop_size: min(waveform.shape[0], end * self.hop_size)]
|
68 |
+
|
69 |
+
def slice(self, waveform):
|
70 |
+
if len(waveform.shape) > 1:
|
71 |
+
samples = waveform.mean(axis=0)
|
72 |
+
else:
|
73 |
+
samples = waveform
|
74 |
+
if samples.shape[0] <= self.min_length:
|
75 |
+
return [waveform]
|
76 |
+
rms_list = get_rms(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0)
|
77 |
+
sil_tags = []
|
78 |
+
silence_start = None
|
79 |
+
clip_start = 0
|
80 |
+
for i, rms in enumerate(rms_list):
|
81 |
+
if rms < self.threshold:
|
82 |
+
if silence_start is None:
|
83 |
+
silence_start = i
|
84 |
+
continue
|
85 |
+
if silence_start is None:
|
86 |
+
continue
|
87 |
+
is_leading_silence = silence_start == 0 and i > self.max_sil_kept
|
88 |
+
need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length
|
89 |
+
if not is_leading_silence and not need_slice_middle:
|
90 |
+
silence_start = None
|
91 |
+
continue
|
92 |
+
if i - silence_start <= self.max_sil_kept:
|
93 |
+
pos = rms_list[silence_start: i + 1].argmin() + silence_start
|
94 |
+
if silence_start == 0:
|
95 |
+
sil_tags.append((0, pos))
|
96 |
+
else:
|
97 |
+
sil_tags.append((pos, pos))
|
98 |
+
clip_start = pos
|
99 |
+
elif i - silence_start <= self.max_sil_kept * 2:
|
100 |
+
pos = rms_list[i - self.max_sil_kept: silence_start + self.max_sil_kept + 1].argmin()
|
101 |
+
pos += i - self.max_sil_kept
|
102 |
+
pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
|
103 |
+
pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
|
104 |
+
if silence_start == 0:
|
105 |
+
sil_tags.append((0, pos_r))
|
106 |
+
clip_start = pos_r
|
107 |
+
else:
|
108 |
+
sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
|
109 |
+
clip_start = max(pos_r, pos)
|
110 |
+
else:
|
111 |
+
pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
|
112 |
+
pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
|
113 |
+
if silence_start == 0:
|
114 |
+
sil_tags.append((0, pos_r))
|
115 |
+
else:
|
116 |
+
sil_tags.append((pos_l, pos_r))
|
117 |
+
clip_start = pos_r
|
118 |
+
silence_start = None
|
119 |
+
total_frames = rms_list.shape[0]
|
120 |
+
if silence_start is not None and total_frames - silence_start >= self.min_interval:
|
121 |
+
silence_end = min(total_frames, silence_start + self.max_sil_kept)
|
122 |
+
pos = rms_list[silence_start: silence_end + 1].argmin() + silence_start
|
123 |
+
sil_tags.append((pos, total_frames + 1))
|
124 |
+
if len(sil_tags) == 0:
|
125 |
+
return [waveform]
|
126 |
+
else:
|
127 |
+
chunks = []
|
128 |
+
if sil_tags[0][0] > 0:
|
129 |
+
chunks.append(self._apply_slice(waveform, 0, sil_tags[0][0]))
|
130 |
+
for i in range(len(sil_tags) - 1):
|
131 |
+
chunks.append(self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0]))
|
132 |
+
if sil_tags[-1][1] < total_frames:
|
133 |
+
chunks.append(self._apply_slice(waveform, sil_tags[-1][1], total_frames))
|
134 |
+
return chunks
|
135 |
+
|
136 |
+
# Function to slice and save audio chunks
|
137 |
+
def slice_audio(file_path, audio_name):
|
138 |
+
audio, sr = librosa.load(file_path, sr=None, mono=False)
|
139 |
+
os.makedirs(f'dataset/{audio_name}', exist_ok=True)
|
140 |
+
slicer = Slicer(sr=sr, threshold=-40, min_length=5000, min_interval=500, hop_size=10, max_sil_kept=500)
|
141 |
+
chunks = slicer.slice(audio)
|
142 |
+
for i, chunk in enumerate(chunks):
|
143 |
+
if len(chunk.shape) > 1:
|
144 |
+
chunk = chunk.T
|
145 |
+
sf.write(f'dataset/{audio_name}/split_{i}.wav', chunk, sr)
|
146 |
+
return f"dataset/{audio_name}"
|
147 |
+
|
148 |
+
# Function to zip the dataset directory
|
149 |
+
def zip_directory(directory_path, audio_name):
|
150 |
+
zip_file = f"dataset/{audio_name}.zip"
|
151 |
+
os.makedirs(os.path.dirname(zip_file), exist_ok=True) # Ensure the directory exists
|
152 |
+
with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
153 |
+
for root, dirs, files in os.walk(directory_path):
|
154 |
+
for file in files:
|
155 |
+
file_path = os.path.join(root, file)
|
156 |
+
arcname = os.path.relpath(file_path, start=directory_path)
|
157 |
+
zipf.write(file_path, arcname)
|
158 |
+
return zip_file
|
159 |
+
|
160 |
+
|
161 |
+
# Gradio interface
|
162 |
+
def process_audio(url, audio_name):
|
163 |
+
file_path = download_youtube_audio(url, audio_name)
|
164 |
+
dataset_path = slice_audio(file_path, audio_name)
|
165 |
+
zip_file = zip_directory(dataset_path, audio_name)
|
166 |
+
return zip_file, print(f"{zip_file} successfully processed")
|