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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import yt_dlp
|
| 3 |
+
import ffmpeg
|
| 4 |
+
import subprocess
|
| 5 |
+
import numpy as np
|
| 6 |
+
import librosa
|
| 7 |
+
import soundfile
|
| 8 |
+
from __future__ import unicode_literals
|
| 9 |
+
|
| 10 |
+
class Slicer:
|
| 11 |
+
def __init__(self, sr, threshold=-40., min_length=5000, min_interval=300, hop_size=20, max_sil_kept=5000):
|
| 12 |
+
if not min_length >= min_interval >= hop_size:
|
| 13 |
+
raise ValueError('The following condition must be satisfied: min_length >= min_interval >= hop_size')
|
| 14 |
+
if not max_sil_kept >= hop_size:
|
| 15 |
+
raise ValueError('The following condition must be satisfied: max_sil_kept >= hop_size')
|
| 16 |
+
min_interval = sr * min_interval / 1000
|
| 17 |
+
self.threshold = 10 ** (threshold / 20.)
|
| 18 |
+
self.hop_size = round(sr * hop_size / 1000)
|
| 19 |
+
self.win_size = min(round(min_interval), 4 * self.hop_size)
|
| 20 |
+
self.min_length = round(sr * min_length / 1000 / self.hop_size)
|
| 21 |
+
self.min_interval = round(min_interval / self.hop_size)
|
| 22 |
+
self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
|
| 23 |
+
|
| 24 |
+
def _apply_slice(self, waveform, begin, end):
|
| 25 |
+
if len(waveform.shape) > 1:
|
| 26 |
+
return waveform[:, begin * self.hop_size: min(waveform.shape[1], end * self.hop_size)]
|
| 27 |
+
else:
|
| 28 |
+
return waveform[begin * self.hop_size: min(waveform.shape[0], end * self.hop_size)]
|
| 29 |
+
|
| 30 |
+
def slice(self, waveform):
|
| 31 |
+
if len(waveform.shape) > 1:
|
| 32 |
+
samples = waveform.mean(axis=0)
|
| 33 |
+
else:
|
| 34 |
+
samples = waveform
|
| 35 |
+
if samples.shape[0] <= self.min_length:
|
| 36 |
+
return [waveform]
|
| 37 |
+
rms_list = get_rms(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0)
|
| 38 |
+
sil_tags = []
|
| 39 |
+
silence_start = None
|
| 40 |
+
clip_start = 0
|
| 41 |
+
for i, rms in enumerate(rms_list):
|
| 42 |
+
if rms < self.threshold:
|
| 43 |
+
if silence_start is None:
|
| 44 |
+
silence_start = i
|
| 45 |
+
continue
|
| 46 |
+
if silence_start is None:
|
| 47 |
+
continue
|
| 48 |
+
is_leading_silence = silence_start == 0 and i > self.max_sil_kept
|
| 49 |
+
need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length
|
| 50 |
+
if not is_leading_silence and not need_slice_middle:
|
| 51 |
+
silence_start = None
|
| 52 |
+
continue
|
| 53 |
+
if i - silence_start <= self.max_sil_kept:
|
| 54 |
+
pos = rms_list[silence_start: i + 1].argmin() + silence_start
|
| 55 |
+
if silence_start == 0:
|
| 56 |
+
sil_tags.append((0, pos))
|
| 57 |
+
else:
|
| 58 |
+
sil_tags.append((pos, pos))
|
| 59 |
+
clip_start = pos
|
| 60 |
+
elif i - silence_start <= self.max_sil_kept * 2:
|
| 61 |
+
pos = rms_list[i - self.max_sil_kept: silence_start + self.max_sil_kept + 1].argmin()
|
| 62 |
+
pos += i - self.max_sil_kept
|
| 63 |
+
pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
|
| 64 |
+
pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
|
| 65 |
+
if silence_start == 0:
|
| 66 |
+
sil_tags.append((0, pos_r))
|
| 67 |
+
clip_start = pos_r
|
| 68 |
+
else:
|
| 69 |
+
sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
|
| 70 |
+
clip_start = max(pos_r, pos)
|
| 71 |
+
else:
|
| 72 |
+
pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
|
| 73 |
+
pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
|
| 74 |
+
if silence_start == 0:
|
| 75 |
+
sil_tags.append((0, pos_r))
|
| 76 |
+
else:
|
| 77 |
+
sil_tags.append((pos_l, pos_r))
|
| 78 |
+
clip_start = pos_r
|
| 79 |
+
silence_start = None
|
| 80 |
+
total_frames = rms_list.shape[0]
|
| 81 |
+
if silence_start is not None and total_frames - silence_start >= self.min_interval:
|
| 82 |
+
silence_end = min(total_frames, silence_start + self.max_sil_kept)
|
| 83 |
+
pos = rms_list[silence_start: silence_end + 1].argmin() + silence_start
|
| 84 |
+
sil_tags.append((pos, total_frames + 1))
|
| 85 |
+
if len(sil_tags) == 0:
|
| 86 |
+
return [waveform]
|
| 87 |
+
else:
|
| 88 |
+
chunks = []
|
| 89 |
+
if sil_tags[0][0] > 0:
|
| 90 |
+
chunks.append(self._apply_slice(waveform, 0, sil_tags[0][0]))
|
| 91 |
+
for i in range(len(sil_tags) - 1):
|
| 92 |
+
chunks.append(self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0]))
|
| 93 |
+
if sil_tags[-1][1] < total_frames:
|
| 94 |
+
chunks.append(self._apply_slice(waveform, sil_tags[-1][1], total_frames))
|
| 95 |
+
return chunks
|
| 96 |
+
|
| 97 |
+
def get_rms(y, frame_length=2048, hop_length=512, pad_mode="constant"):
|
| 98 |
+
padding = (int(frame_length // 2), int(frame_length // 2))
|
| 99 |
+
y = np.pad(y, padding, mode=pad_mode)
|
| 100 |
+
axis = -1
|
| 101 |
+
out_strides = y.strides + tuple([y.strides[axis]])
|
| 102 |
+
x_shape_trimmed = list(y.shape)
|
| 103 |
+
x_shape_trimmed[axis] -= frame_length - 1
|
| 104 |
+
out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
|
| 105 |
+
xw = np.lib.stride_tricks.as_strided(y, shape=out_shape, strides=out_strides)
|
| 106 |
+
if axis < 0:
|
| 107 |
+
target_axis = axis - 1
|
| 108 |
+
else:
|
| 109 |
+
target_axis = axis + 1
|
| 110 |
+
xw = np.moveaxis(xw, -1, target_axis)
|
| 111 |
+
slices = [slice(None)] * xw.ndim
|
| 112 |
+
slices[axis] = slice(0, None, hop_length)
|
| 113 |
+
x = xw[tuple(slices)]
|
| 114 |
+
power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
|
| 115 |
+
return np.sqrt(power)
|
| 116 |
+
|
| 117 |
+
def download_audio(dataset, url, drive_path, audio_name):
|
| 118 |
+
if dataset == "Drive":
|
| 119 |
+
return "Dataset is set to Drive. Skipping download."
|
| 120 |
+
elif dataset == "Youtube":
|
| 121 |
+
ydl_opts = {
|
| 122 |
+
'format': 'bestaudio/best',
|
| 123 |
+
'postprocessors': [{
|
| 124 |
+
'key': 'FFmpegExtractAudio',
|
| 125 |
+
'preferredcodec': 'wav',
|
| 126 |
+
}],
|
| 127 |
+
"outtmpl": f'/content/youtubeaudio/{audio_name}',
|
| 128 |
+
}
|
| 129 |
+
def download_from_url(url):
|
| 130 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 131 |
+
ydl.download([url])
|
| 132 |
+
|
| 133 |
+
download_from_url(url)
|
| 134 |
+
return f'Audio downloaded and saved as /content/youtubeaudio/{audio_name}.wav'
|
| 135 |
+
|
| 136 |
+
def separate_audio(dataset, audio_name, drive_path):
|
| 137 |
+
if dataset == "Drive":
|
| 138 |
+
audio_input = drive_path
|
| 139 |
+
elif dataset == "Youtube":
|
| 140 |
+
audio_input = f"/content/youtubeaudio/{audio_name}.wav"
|
| 141 |
+
command = f"demucs --two-stems=vocals {audio_input}"
|
| 142 |
+
result = subprocess.run(command.split(), stdout=subprocess.PIPE)
|
| 143 |
+
subprocess.run(f"!mkdir -p /content/audio/{audio_name}", shell=True)
|
| 144 |
+
subprocess.run(f"!cp -r /content/separated/htdemucs/{audio_name}/* /content/audio/{audio_name}", shell=True)
|
| 145 |
+
if dataset == "Youtube":
|
| 146 |
+
subprocess.run(f"!cp -r /content/youtubeaudio/{audio_name}.wav /content/audio/{audio_name}", shell=True)
|
| 147 |
+
return result.stdout.decode()
|
| 148 |
+
|
| 149 |
+
def split_audio(audio_name):
|
| 150 |
+
audio, sr = librosa.load(f'/content/separated/htdemucs/{audio_name}/vocals.wav', sr=None, mono=False)
|
| 151 |
+
slicer = Slicer(
|
| 152 |
+
sr=sr,
|
| 153 |
+
threshold=-40,
|
| 154 |
+
min_length=5000,
|
| 155 |
+
min_interval=500,
|
| 156 |
+
hop_size=10,
|
| 157 |
+
max_sil_kept=500
|
| 158 |
+
)
|
| 159 |
+
chunks = slicer.slice(audio)
|
| 160 |
+
subprocess.run(f"!mkdir -p /content/dataset/{audio_name}", shell=True)
|
| 161 |
+
for i, chunk in enumerate(chunks):
|
| 162 |
+
if len(chunk.shape) > 1:
|
| 163 |
+
chunk = chunk.T
|
| 164 |
+
soundfile.write(f'/content/dataset/{audio_name}/split_{i}.wav', chunk, sr)
|
| 165 |
+
subprocess.run(f"!mkdir -p /content/dataset/{audio_name}", shell=True)
|
| 166 |
+
subprocess.run(f"!cp -r /content/dataset/{audio_name}/* /content/dataset/{audio_name}", shell=True)
|
| 167 |
+
return "Audio split into chunks and saved."
|
| 168 |
+
|
| 169 |
+
def process_audio(mode, dataset, url, drive_path, audio_name):
|
| 170 |
+
download_result = download_audio(dataset, url, drive_path, audio_name)
|
| 171 |
+
if "Skipping download" not in download_result:
|
| 172 |
+
separate_result = separate_audio(dataset, audio_name, drive_path)
|
| 173 |
+
if mode == "Splitting":
|
| 174 |
+
split_result = split_audio(audio_name)
|
| 175 |
+
return f"{download_result}\n{separate_result}\n{split_result}"
|
| 176 |
+
else:
|
| 177 |
+
return f"{download_result}\n{separate_result}\nMode is set to Separate. Skipping splitting."
|
| 178 |
+
else:
|
| 179 |
+
return download_result
|
| 180 |
+
|
| 181 |
+
demo = gr.Interface(
|
| 182 |
+
fn=process_audio,
|
| 183 |
+
inputs=[
|
| 184 |
+
gr.Dropdown(choices=["Splitting", "Separate"], label="Mode"),
|
| 185 |
+
gr.Dropdown(choices=["Youtube", "Drive"], label="Dataset"),
|
| 186 |
+
gr.Textbox(label="URL"),
|
| 187 |
+
gr.Textbox(label="Drive Path"),
|
| 188 |
+
gr.Textbox(label="Audio Name"),
|
| 189 |
+
],
|
| 190 |
+
outputs="text",
|
| 191 |
+
title="Dataset Maker",
|
| 192 |
+
description="Process audio from Youtube or Drive and split it based on silence detection."
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
demo.launch()
|