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ydub
|
3 |
+
###########################################################################def
|
4 |
+
|
5 |
+
import os
|
6 |
+
import glob
|
7 |
+
import re
|
8 |
+
import random
|
9 |
+
import string
|
10 |
+
|
11 |
+
import json
|
12 |
+
from tqdm.contrib.concurrent import process_map # or thread_map
|
13 |
+
|
14 |
+
from pydub import AudioSegment
|
15 |
+
from pydub.effects import strip_silence
|
16 |
+
|
17 |
+
import IPython.display as ipd
|
18 |
+
from IPython.display import Audio
|
19 |
+
|
20 |
+
import subprocess
|
21 |
+
from concurrent.futures import ProcessPoolExecutor
|
22 |
+
from multiprocessing import Pool
|
23 |
+
from tqdm import tqdm
|
24 |
+
|
25 |
+
import IPython.display as ipd
|
26 |
+
from IPython.display import Audio
|
27 |
+
|
28 |
+
import soundfile as sf
|
29 |
+
import librosa
|
30 |
+
|
31 |
+
###########################################################################def
|
32 |
+
def pydub_play(sound_file,start_time,end_time):
|
33 |
+
"""
|
34 |
+
start_time, end_time = ms
|
35 |
+
pydub_play('/content/songs/Anh_Cho_Em_Mùa_Xuân_ZZEB7E0F.mp3',37390,39250)
|
36 |
+
|
37 |
+
"""
|
38 |
+
#from pydub import AudioSegment
|
39 |
+
#import IPython.display as ipd
|
40 |
+
#from IPython.display import Audio
|
41 |
+
|
42 |
+
ext = sound_file[-3:]
|
43 |
+
audio_file = AudioSegment.from_file(sound_file, format=ext)
|
44 |
+
audio = audio_file[start_time:end_time]
|
45 |
+
audio.export(f'demo.{ext}',format=ext)
|
46 |
+
ipd.display(ipd.Audio(f'demo.{ext}'))
|
47 |
+
|
48 |
+
|
49 |
+
def torch_play(sound_file,start_time,end_time):
|
50 |
+
"""
|
51 |
+
start_time, end_time = ms
|
52 |
+
torch_play('/content/songs/Anh_Cho_Em_Mùa_Xuân_ZZEB7E0F.mp3',37390,39250)
|
53 |
+
|
54 |
+
"""
|
55 |
+
import torchaudio
|
56 |
+
import IPython.display as ipd
|
57 |
+
from IPython.display import Audio
|
58 |
+
|
59 |
+
waveform, sample_rate = torchaudio.load(sound_file)
|
60 |
+
|
61 |
+
start_sample = int(start_time / 1000 * sample_rate)
|
62 |
+
end_sample = int(end_time / 1000 * sample_rate)
|
63 |
+
audio_to_play = waveform[:, start_sample:end_sample]
|
64 |
+
torchaudio.save('output.wav', audio_to_play, sample_rate)
|
65 |
+
ipd.display(Audio('output.wav'))
|
66 |
+
|
67 |
+
|
68 |
+
|
69 |
+
###########################################################################def
|
70 |
+
|
71 |
+
def file_wav_16k(args):
|
72 |
+
"""
|
73 |
+
use for MFA alignment
|
74 |
+
|
75 |
+
"""
|
76 |
+
|
77 |
+
input_sound, out_dir = args
|
78 |
+
|
79 |
+
os.makedirs(out_dir, exist_ok=True)
|
80 |
+
name = os.path.basename(input_sound)
|
81 |
+
name = os.path.splitext(name)[0]
|
82 |
+
output_sound= f'{out_dir}/{name}.wav'
|
83 |
+
|
84 |
+
command = [
|
85 |
+
"ffmpeg",
|
86 |
+
"-y", "-i", input_sound,
|
87 |
+
"-ar", "16000", # Set sample rate to 16000 Hz
|
88 |
+
"-ac", "1", # Set number of channels to 2 (stereo)
|
89 |
+
"-acodec", "pcm_s16le", # Use WAV encoder
|
90 |
+
output_sound
|
91 |
+
]
|
92 |
+
|
93 |
+
try:
|
94 |
+
subprocess.run(command, check=True,stderr=subprocess.DEVNULL)
|
95 |
+
except subprocess.CalledProcessError as error:
|
96 |
+
print(f"Conversion failed: {error}")
|
97 |
+
|
98 |
+
|
99 |
+
|
100 |
+
def folder_to_wav_16k(in_dir, out_dir):
|
101 |
+
""" """
|
102 |
+
os.makedirs(out_dir, exist_ok=True)
|
103 |
+
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
|
104 |
+
|
105 |
+
with Pool() as pool:
|
106 |
+
with tqdm(total=len(files), desc="Converting MP3 to WAV") as pbar:
|
107 |
+
for _ in pool.imap_unordered(file_wav_16k, zip(files, [out_dir] * len(files))): # Pass arguments as tuples
|
108 |
+
pbar.update()
|
109 |
+
|
110 |
+
###########################################################################def
|
111 |
+
|
112 |
+
|
113 |
+
def check_file(filepath):
|
114 |
+
"""
|
115 |
+
Hàm kiểm tra file âm thanh, nếu không hợp lệ thì xóa file đó.
|
116 |
+
"""
|
117 |
+
try:
|
118 |
+
# Đọc dữ liệu âm thanh với soundfile (sf)
|
119 |
+
data, sample_rate = sf.read(filepath)
|
120 |
+
return True # Nếu file hợp lệ
|
121 |
+
except Exception as e:
|
122 |
+
# Nếu có lỗi, xóa file và thông báo lỗi
|
123 |
+
os.remove(filepath)
|
124 |
+
print(f"Removed {filepath} due to error: {e}")
|
125 |
+
return False
|
126 |
+
|
127 |
+
def remove_invalid_sound(in_dir):
|
128 |
+
"""
|
129 |
+
Hàm quét các file âm thanh trong thư mục, kiểm tra và xóa những file không hợp lệ.
|
130 |
+
"""
|
131 |
+
# Lấy danh sách các file âm thanh trong thư mục
|
132 |
+
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
|
133 |
+
|
134 |
+
print('Start multiprocessing')
|
135 |
+
|
136 |
+
# Sử dụng multiprocessing Pool để xử lý nhiều file cùng lúc
|
137 |
+
with Pool() as pool:
|
138 |
+
results = []
|
139 |
+
for file in files:
|
140 |
+
# Đảm bảo args là một tuple (file,)
|
141 |
+
result = pool.apply_async(check_file, args=(file,))
|
142 |
+
results.append(result)
|
143 |
+
|
144 |
+
pool.close()
|
145 |
+
|
146 |
+
# Sử dụng tqdm để hiển thị thanh tiến độ
|
147 |
+
for _ in tqdm(results, desc="Processing files"):
|
148 |
+
_.get()
|
149 |
+
|
150 |
+
pool.join()
|
151 |
+
|
152 |
+
|
153 |
+
|
154 |
+
def remove_bad_sound(x_files):
|
155 |
+
"""
|
156 |
+
remove invalid/bad sound files in list x_files
|
157 |
+
x_files = get_audio_files('/content/raw_data')
|
158 |
+
remove_bad_sound(x_files)
|
159 |
+
|
160 |
+
"""
|
161 |
+
#import os
|
162 |
+
|
163 |
+
for filepath in tqdm(x_files):
|
164 |
+
if not is_valid_sound(filepath):
|
165 |
+
os.remove(filepath)
|
166 |
+
print(f"\tDeleted invalid sound file: {filepath}")
|
167 |
+
|
168 |
+
###########################################################################def
|
169 |
+
def name_no_ext(folder,ext='txt'):
|
170 |
+
""" """
|
171 |
+
import os
|
172 |
+
x_name = []
|
173 |
+
files = os.listdir(folder)
|
174 |
+
for file in files:
|
175 |
+
if file.endswith(f'.{ext}'):
|
176 |
+
name = os.path.splitext(file)[0]
|
177 |
+
x_name.append(name)
|
178 |
+
return x_name
|
179 |
+
|
180 |
+
|
181 |
+
def the_same_name(dir_1,dir_2,ext1,ext2):
|
182 |
+
"""
|
183 |
+
the_same_name(dir_1,dir_2,'TextGrid','mp3')
|
184 |
+
|
185 |
+
"""
|
186 |
+
x1_name = name_no_ext(dir_1,ext1)
|
187 |
+
x2_name = name_no_ext(dir_2,ext2)
|
188 |
+
common = set(x1_name) & set(x2_name)
|
189 |
+
return list(common)
|
190 |
+
|
191 |
+
|
192 |
+
|
193 |
+
def get_pair_files(dir_1,dir_2,ext1,ext2):
|
194 |
+
"""
|
195 |
+
get_pair_files(dir_1,dir_2,'TextGrid','mp3')
|
196 |
+
|
197 |
+
"""
|
198 |
+
x1_name = name_no_ext(dir_1,ext1)
|
199 |
+
x2_name = name_no_ext(dir_2,ext2)
|
200 |
+
common = set(x1_name) & set(x2_name)
|
201 |
+
return list(common)
|
202 |
+
|
203 |
+
|
204 |
+
|
205 |
+
def remove_unpaired_files(folder_path,ext1,ext2):
|
206 |
+
"""
|
207 |
+
remove_unpaired_files('/content/songs','mp3','lrc')
|
208 |
+
|
209 |
+
"""
|
210 |
+
x_common = the_same_name(folder_path,folder_path,ext1,ext2)
|
211 |
+
|
212 |
+
files = glob.glob(f'{folder_path}/*')
|
213 |
+
len(files)
|
214 |
+
for file in files:
|
215 |
+
name = os.path.basename(file)
|
216 |
+
name = os.path.splitext(name)[0]
|
217 |
+
if name not in x_common:
|
218 |
+
print(file)
|
219 |
+
os.system(f'rm -f "{file}"')
|
220 |
+
|
221 |
+
###########################################################################def
|
222 |
+
|
223 |
+
time_lyric_regex = r"[\[|<](\d\d):(\d\d.\d\d)[\]|>](.*)"
|
224 |
+
time_regex = r"[\[|<](\d\d):(\d\d.\d\d)[\]|>]"
|
225 |
+
|
226 |
+
def ignore_line(text):
|
227 |
+
text_lower = text.lower().replace(' ', '').strip(' -.?!,)("\'…“”*_[]')
|
228 |
+
if text_lower.startswith('bàihát:') or text_lower.startswith('casĩ:') or text_lower.startswith('cakhúc:') or text_lower.startswith('sángtác:') or text_lower.startswith('trìnhbày:') or text_lower.startswith('lyricby:') or text_lower.startswith('đk') :
|
229 |
+
return True
|
230 |
+
if len(text.strip(' -.?!,)("\'…“”*_[]')) == 0:
|
231 |
+
return True
|
232 |
+
return False
|
233 |
+
|
234 |
+
def ignore_file(text):
|
235 |
+
matches = list(re.finditer(time_regex, text, re.MULTILINE))
|
236 |
+
if len(matches) > 0:
|
237 |
+
return True
|
238 |
+
|
239 |
+
|
240 |
+
def handle_lrc(file_path):
|
241 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
242 |
+
lines = file.read().strip().split('\n')
|
243 |
+
|
244 |
+
timestamp = []
|
245 |
+
text = []
|
246 |
+
|
247 |
+
label = []
|
248 |
+
try:
|
249 |
+
for line in lines:
|
250 |
+
matches = list(re.finditer(time_lyric_regex, line, re.MULTILINE))
|
251 |
+
if len(matches) > 0:
|
252 |
+
if ignore_file(matches[0].group(3)):
|
253 |
+
return
|
254 |
+
if not ignore_line(matches[0].group(3)):
|
255 |
+
start_time = int(float(matches[0].group(1)) * 60 * 1000) + int(float(matches[0].group(2)) * 1000)
|
256 |
+
timestamp.append(start_time)
|
257 |
+
text.append(matches[0].group(3).strip())
|
258 |
+
|
259 |
+
except:
|
260 |
+
print(file_path)
|
261 |
+
return
|
262 |
+
|
263 |
+
timestamp = timestamp[3:]
|
264 |
+
text = text[3:]
|
265 |
+
# print(len(text),len(timestamp))
|
266 |
+
return text, timestamp
|
267 |
+
|
268 |
+
###########################################################################def
|
269 |
+
def random_name(num_letters=5):
|
270 |
+
"""
|
271 |
+
"""
|
272 |
+
#import random
|
273 |
+
#import string
|
274 |
+
|
275 |
+
random_letters = random.choices(string.ascii_lowercase, k=num_letters)
|
276 |
+
random_string = ''.join(random_letters)
|
277 |
+
|
278 |
+
random_number = random.randint(10000, 99999)
|
279 |
+
out = f'{random_string}_{random_number}'
|
280 |
+
return out
|
281 |
+
|
282 |
+
###########################################################################def
|
283 |
+
# 3 parameters
|
284 |
+
# args = sound_file,out_dir,num_seq
|
285 |
+
|
286 |
+
def pydub_split(args):
|
287 |
+
"""
|
288 |
+
start_time, end_time = ms
|
289 |
+
args = sound_file,out_dir,num_seq
|
290 |
+
|
291 |
+
"""
|
292 |
+
import os
|
293 |
+
from pydub import AudioSegment
|
294 |
+
|
295 |
+
sound_file,out_dir,num_seq = args # 3 parameters
|
296 |
+
|
297 |
+
os.makedirs(out_dir, exist_ok=True)
|
298 |
+
|
299 |
+
subtile_file = f'{sound_file[:-4]}.lrc'
|
300 |
+
text, timestamp = handle_lrc(subtile_file)
|
301 |
+
|
302 |
+
ext = sound_file[-3:]
|
303 |
+
audio_file = AudioSegment.from_file(sound_file, format=ext)
|
304 |
+
|
305 |
+
for k in range(len(text)):
|
306 |
+
#print(k)
|
307 |
+
if k+num_seq < len(text):
|
308 |
+
sentence = " ".join(text[k:k+num_seq])
|
309 |
+
dur = timestamp[k+num_seq] - timestamp[k]
|
310 |
+
len_text = len(sentence.split())
|
311 |
+
if dur < 20000:
|
312 |
+
new_name = random_name(5)
|
313 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seq]]
|
314 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
315 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
316 |
+
f.write(sentence.lower())
|
317 |
+
else:
|
318 |
+
sentence = " ".join(text[k:k+num_seq-1])
|
319 |
+
dur = timestamp[k+num_seq-1] - timestamp[k]
|
320 |
+
if dur < 20000:
|
321 |
+
new_name = random_name(5)
|
322 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seq-1]]
|
323 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
324 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
325 |
+
f.write(sentence.lower())
|
326 |
+
# the last
|
327 |
+
elif k+num_seq == len(text):
|
328 |
+
sentence = " ".join(text[k:k+num_seq])
|
329 |
+
dur = timestamp[-1] - timestamp[k]
|
330 |
+
len_text = len(sentence.split())
|
331 |
+
if dur < 20000:
|
332 |
+
new_name = random_name(5)
|
333 |
+
audio = audio_file[timestamp[k]:timestamp[-1]]
|
334 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
335 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
336 |
+
f.write(sentence.lower())
|
337 |
+
|
338 |
+
|
339 |
+
def _zing_split(in_dir, out_dir,num_seq=4):
|
340 |
+
""" """
|
341 |
+
os.makedirs(out_dir, exist_ok=True)
|
342 |
+
files = glob.glob(f'{in_dir}/*.mp3')
|
343 |
+
|
344 |
+
with Pool() as pool:
|
345 |
+
with tqdm(total=len(files), desc="Split pair files: mp3+lab") as pbar:
|
346 |
+
for _ in pool.imap_unordered(pydub_split, zip(files, [out_dir] * len(files), [num_seq] * len(files))):
|
347 |
+
pbar.update()
|
348 |
+
|
349 |
+
###########################################################################def
|
350 |
+
def remove_bad_lrc(lrc_dir):
|
351 |
+
"""
|
352 |
+
"""
|
353 |
+
import os
|
354 |
+
import glob
|
355 |
+
from tqdm import tqdm
|
356 |
+
|
357 |
+
files = glob.glob(f'{lrc_dir}/*.lrc')
|
358 |
+
print(f'num_files: {len(files)}')
|
359 |
+
for file in tqdm(files):
|
360 |
+
try:
|
361 |
+
text, timestamp = handle_lrc(file)
|
362 |
+
except Exception as e:
|
363 |
+
print(f"Error in splitting files: {e}")
|
364 |
+
os.remove(file)
|
365 |
+
print(f'removed {file}')
|
366 |
+
|
367 |
+
###########################################################################def
|
368 |
+
def _split_1(args):
|
369 |
+
"""
|
370 |
+
start_time, end_time = ms
|
371 |
+
slide window + overlay
|
372 |
+
|
373 |
+
"""
|
374 |
+
#import os
|
375 |
+
#from pydub import AudioSegment
|
376 |
+
|
377 |
+
sound_file,out_dir,num_seg = args # 3 parameters
|
378 |
+
|
379 |
+
#os.makedirs(out_dir, exist_ok=True)
|
380 |
+
|
381 |
+
subtile_file = f'{sound_file[:-4]}.lrc'
|
382 |
+
text, timestamp = handle_lrc(subtile_file)
|
383 |
+
|
384 |
+
ext = sound_file[-3:]
|
385 |
+
audio_file = AudioSegment.from_file(sound_file, format=ext)
|
386 |
+
|
387 |
+
for k in range(len(text)):
|
388 |
+
if k+num_seg < len(text):
|
389 |
+
sentence = " ".join(text[k:k+num_seg])
|
390 |
+
#print(sentence)
|
391 |
+
dur = timestamp[k+num_seg] - timestamp[k]
|
392 |
+
len_text = len(sentence.split())
|
393 |
+
if dur < 30000:
|
394 |
+
new_name = random_name(5)
|
395 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
|
396 |
+
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
397 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
398 |
+
f.write(sentence.lower())
|
399 |
+
else:
|
400 |
+
sentence = " ".join(text[k:k+num_seg-1])
|
401 |
+
#print(sentence)
|
402 |
+
dur = timestamp[k+num_seg-1] - timestamp[k]
|
403 |
+
if dur < 30000:
|
404 |
+
new_name = random_name(5)
|
405 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
|
406 |
+
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
407 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
408 |
+
f.write(sentence.lower())
|
409 |
+
# the last
|
410 |
+
elif k+num_seg == len(text):
|
411 |
+
sentence = " ".join(text[k:k+num_seg])
|
412 |
+
#print(sentence)
|
413 |
+
dur = timestamp[-1] - timestamp[k]
|
414 |
+
len_text = len(sentence.split())
|
415 |
+
if dur < 30000:
|
416 |
+
new_name = random_name(5)
|
417 |
+
audio = audio_file[timestamp[k]:timestamp[-1]]
|
418 |
+
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
419 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
420 |
+
f.write(sentence.lower())
|
421 |
+
|
422 |
+
|
423 |
+
def _split_2(args):
|
424 |
+
"""
|
425 |
+
start_time, end_time = ms
|
426 |
+
slide window, no overlay
|
427 |
+
|
428 |
+
"""
|
429 |
+
#import os
|
430 |
+
#from pydub import AudioSegment
|
431 |
+
|
432 |
+
sound_file,out_dir,num_seg = args # 3 parameters
|
433 |
+
|
434 |
+
#os.makedirs(out_dir, exist_ok=True)
|
435 |
+
|
436 |
+
subtile_file = f'{sound_file[:-4]}.lrc'
|
437 |
+
text, timestamp = handle_lrc(subtile_file)
|
438 |
+
|
439 |
+
ext = sound_file[-3:]
|
440 |
+
audio_file = AudioSegment.from_file(sound_file, format=ext)
|
441 |
+
|
442 |
+
for k in range(0,len(text),num_seg):
|
443 |
+
#print(k)
|
444 |
+
if k + num_seg < len(text):
|
445 |
+
sentence = " ".join(text[k:k+num_seg])
|
446 |
+
#print(sentence)
|
447 |
+
dur = timestamp[k+num_seg] - timestamp[k]
|
448 |
+
len_text = len(sentence.split())
|
449 |
+
if dur < 30000:
|
450 |
+
new_name = random_name(5)
|
451 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
|
452 |
+
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
453 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
454 |
+
f.write(sentence.lower())
|
455 |
+
else:
|
456 |
+
sentence = " ".join(text[k:k+num_seg-1])
|
457 |
+
#print(sentence)
|
458 |
+
dur = timestamp[k+num_seg-1] - timestamp[k]
|
459 |
+
if dur < 30000:
|
460 |
+
new_name = random_name(5)
|
461 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
|
462 |
+
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
463 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
464 |
+
f.write(sentence.lower())
|
465 |
+
else: # the last
|
466 |
+
sentence = " ".join(text[k:])
|
467 |
+
#print(sentence)
|
468 |
+
dur = timestamp[-1] - timestamp[k]
|
469 |
+
len_text = len(sentence.split())
|
470 |
+
if dur < 30000:
|
471 |
+
new_name = random_name(5)
|
472 |
+
audio = audio_file[timestamp[k]:timestamp[-1]]
|
473 |
+
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
474 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
475 |
+
f.write(sentence.lower())
|
476 |
+
|
477 |
+
|
478 |
+
|
479 |
+
def _zing_split(in_dir, out_dir,num_seg=4,overlay='yes'):
|
480 |
+
""" """
|
481 |
+
import os
|
482 |
+
import glob
|
483 |
+
|
484 |
+
os.makedirs(out_dir, exist_ok=True)
|
485 |
+
files = glob.glob(f'{in_dir}/*.mp3')
|
486 |
+
|
487 |
+
with Pool() as pool:
|
488 |
+
with tqdm(total=len(files), desc="Split pair files: mp3+lab") as pbar:
|
489 |
+
if overlay.lower() == 'yes':
|
490 |
+
for _ in pool.imap_unordered(split_1, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
|
491 |
+
pbar.update()
|
492 |
+
else:
|
493 |
+
for _ in pool.imap_unordered(split_2, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
|
494 |
+
pbar.update()
|
495 |
+
|
496 |
+
|
497 |
+
def _zing_split(in_dir, out_dir,num_seg=4,overlay='yes'):
|
498 |
+
""" """
|
499 |
+
import os
|
500 |
+
import glob
|
501 |
+
|
502 |
+
os.makedirs(out_dir, exist_ok=True)
|
503 |
+
files = glob.glob(f'{in_dir}/*.mp3')
|
504 |
+
|
505 |
+
with Pool() as pool:
|
506 |
+
with tqdm(total=len(files), desc="Split pair files: mp3+lab") as pbar:
|
507 |
+
try:
|
508 |
+
if overlay.lower() == 'yes':
|
509 |
+
for _ in pool.imap_unordered(split_1, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
|
510 |
+
pbar.update()
|
511 |
+
else:
|
512 |
+
for _ in pool.imap_unordered(split_2, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
|
513 |
+
pbar.update()
|
514 |
+
except:
|
515 |
+
pass
|
516 |
+
###########################################################################def
|
517 |
+
|
518 |
+
def check_and_remove_empty_folder(folder_path):
|
519 |
+
"""
|
520 |
+
"""
|
521 |
+
if os.path.exists(folder_path):
|
522 |
+
if not os.listdir(folder_path):
|
523 |
+
os.rmdir(folder_path)
|
524 |
+
print(f"Removed empty directory: {folder_path}")
|
525 |
+
|
526 |
+
|
527 |
+
def split_one(sound_file,out_dir,num_seg):
|
528 |
+
"""
|
529 |
+
This use for manual transcription checking, augmentation
|
530 |
+
|
531 |
+
"""
|
532 |
+
import os
|
533 |
+
|
534 |
+
song_name = random_name(5)
|
535 |
+
out_dir = f'{out_dir}/{song_name}'
|
536 |
+
os.makedirs(out_dir, exist_ok=True)
|
537 |
+
|
538 |
+
try:
|
539 |
+
subtile_file = f'{sound_file[:-4]}.lrc'
|
540 |
+
text, timestamp = handle_lrc(subtile_file)
|
541 |
+
|
542 |
+
ext = sound_file[-3:]
|
543 |
+
audio_file = AudioSegment.from_file(sound_file, format=ext)
|
544 |
+
|
545 |
+
for k in range(len(text)):
|
546 |
+
if k+num_seg < len(text):
|
547 |
+
sentence = " ".join(text[k:k+num_seg])
|
548 |
+
#print(sentence)
|
549 |
+
dur = timestamp[k+num_seg] - timestamp[k]
|
550 |
+
len_text = len(sentence.split())
|
551 |
+
if dur < 30000:
|
552 |
+
#print(k)
|
553 |
+
new_name = f'{song_name}_{k:02d}'
|
554 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
|
555 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
556 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
557 |
+
#f.write(sentence.lower())
|
558 |
+
f.write(sentence)
|
559 |
+
else:
|
560 |
+
sentence = " ".join(text[k:k+num_seg-1])
|
561 |
+
#print(sentence)
|
562 |
+
dur = timestamp[k+num_seg-1] - timestamp[k]
|
563 |
+
if dur < 30000:
|
564 |
+
#print(k)
|
565 |
+
new_name = f'{song_name}_{k:02d}'
|
566 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
|
567 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
568 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
569 |
+
#f.write(sentence.lower())
|
570 |
+
f.write(sentence)
|
571 |
+
# the last
|
572 |
+
elif k+num_seg == len(text):
|
573 |
+
sentence = " ".join(text[k:k+num_seg])
|
574 |
+
#print(sentence)
|
575 |
+
dur = timestamp[-1] - timestamp[k]
|
576 |
+
len_text = len(sentence.split())
|
577 |
+
if dur < 30000:
|
578 |
+
#print(k)
|
579 |
+
new_name = f'{song_name}_{k:02d}'
|
580 |
+
audio = audio_file[timestamp[k]:timestamp[-1]]
|
581 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
582 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
583 |
+
#f.write(sentence.lower())
|
584 |
+
f.write(sentence)
|
585 |
+
|
586 |
+
except Exception as e:
|
587 |
+
print(f"\nError processing {sound_file}: {e}")
|
588 |
+
|
589 |
+
check_and_remove_empty_folder(out_dir)
|
590 |
+
# Finished
|
591 |
+
|
592 |
+
|
593 |
+
def mp_split_one(in_dir,out_dir):
|
594 |
+
"""
|
595 |
+
"""
|
596 |
+
import os
|
597 |
+
import glob
|
598 |
+
|
599 |
+
from tqdm import tqdm
|
600 |
+
from multiprocessing import Pool
|
601 |
+
|
602 |
+
os.makedirs(out_dir, exist_ok=True)
|
603 |
+
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
|
604 |
+
|
605 |
+
print('Start multiprocessing')
|
606 |
+
|
607 |
+
with Pool() as pool:
|
608 |
+
results = [pool.apply_async(split_one, args=(file, out_dir, 1)) for file in files]
|
609 |
+
|
610 |
+
# Dùng tqdm để hiển thị tiến trình
|
611 |
+
for result in tqdm(results, desc="Processing files"):
|
612 |
+
result.get() # Đảm bảo chờ quá trình hoàn thành
|
613 |
+
|
614 |
+
|
615 |
+
###########################################################################def
|
616 |
+
# Split sounds from Audacity transcription
|
617 |
+
|
618 |
+
def audacity_split_one(audio_file,out_dir):
|
619 |
+
"""
|
620 |
+
"""
|
621 |
+
import os
|
622 |
+
|
623 |
+
song_name = random_name(5)
|
624 |
+
out_dir = f'{out_dir}/{song_name}'
|
625 |
+
os.makedirs(out_dir, exist_ok=True)
|
626 |
+
|
627 |
+
# Đọc file âm thanh
|
628 |
+
y, sr = librosa.load(audio_file, sr=None)
|
629 |
+
|
630 |
+
# Đọc nội dung từ file text
|
631 |
+
subtile_file = f'{audio_file[:-4]}.txt'
|
632 |
+
with open(subtile_file, 'r', encoding='utf-8') as f:
|
633 |
+
lines = f.readlines()
|
634 |
+
|
635 |
+
# Lặp qua từng dòng trong file transcription để cắt và lưu file
|
636 |
+
for i, line in enumerate(lines):
|
637 |
+
parts = line.strip().split('\t')
|
638 |
+
start_time = float(parts[0])
|
639 |
+
end_time = float(parts[1])
|
640 |
+
content = parts[2] if len(parts) > 2 else ""
|
641 |
+
#print(content)
|
642 |
+
|
643 |
+
start_sample = int(start_time * sr)
|
644 |
+
end_sample = int(end_time * sr)
|
645 |
+
|
646 |
+
# Cắt đoạn âm thanh
|
647 |
+
segment = y[start_sample:end_sample]
|
648 |
+
|
649 |
+
# Tạo tên file cho đoạn âm thanh
|
650 |
+
segment_file = f'{out_dir}/{song_name}_{i+1:02d}.mp3'
|
651 |
+
|
652 |
+
# Lưu đoạn âm thanh
|
653 |
+
sf.write(segment_file, segment, sr)
|
654 |
+
#print(f'Saved: {segment_file}')
|
655 |
+
|
656 |
+
# Tạo file lab tương ứng
|
657 |
+
with open(f'{out_dir}/{song_name}_{i+1:02d}.lab', 'w', encoding='utf-8') as lab_file:
|
658 |
+
lab_file.write(content)
|
659 |
+
print(f'\nSaved to {out_dir}')
|
660 |
+
|
661 |
+
|
662 |
+
|
663 |
+
def mp_audacity(in_dir,out_dir):
|
664 |
+
"""
|
665 |
+
"""
|
666 |
+
import os
|
667 |
+
import glob
|
668 |
+
|
669 |
+
from tqdm import tqdm
|
670 |
+
from multiprocessing import Pool
|
671 |
+
|
672 |
+
os.makedirs(out_dir, exist_ok=True)
|
673 |
+
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
|
674 |
+
|
675 |
+
print('Start multiprocessing')
|
676 |
+
|
677 |
+
with Pool() as pool:
|
678 |
+
results = [pool.apply_async(audacity_split_one, args=(file, out_dir)) for file in files]
|
679 |
+
|
680 |
+
# Dùng tqdm để hiển thị tiến trình
|
681 |
+
for result in tqdm(results, desc="Processing files"):
|
682 |
+
result.get() # Đảm bảo chờ quá trình hoàn thành
|
683 |
+
|
684 |
+
|
685 |
+
|
686 |
+
###########################################################################def
|
687 |
+
|
688 |
+
def split_1(sound_file,out_dir,num_seg):
|
689 |
+
"""
|
690 |
+
start_time, end_time = ms
|
691 |
+
slide window + overlay
|
692 |
+
|
693 |
+
"""
|
694 |
+
try:
|
695 |
+
subtile_file = f'{sound_file[:-4]}.lrc'
|
696 |
+
text, timestamp = handle_lrc(subtile_file)
|
697 |
+
|
698 |
+
ext = sound_file[-3:]
|
699 |
+
audio_file = AudioSegment.from_file(sound_file, format=ext)
|
700 |
+
|
701 |
+
for k in range(len(text)):
|
702 |
+
if k+num_seg < len(text):
|
703 |
+
sentence = " ".join(text[k:k+num_seg])
|
704 |
+
#print(sentence)
|
705 |
+
dur = timestamp[k+num_seg] - timestamp[k]
|
706 |
+
len_text = len(sentence.split())
|
707 |
+
if dur < 30000:
|
708 |
+
new_name = random_name(5)
|
709 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
|
710 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
711 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
712 |
+
#f.write(sentence.lower())
|
713 |
+
f.write(sentence)
|
714 |
+
else:
|
715 |
+
sentence = " ".join(text[k:k+num_seg-1])
|
716 |
+
#print(sentence)
|
717 |
+
dur = timestamp[k+num_seg-1] - timestamp[k]
|
718 |
+
if dur < 30000:
|
719 |
+
new_name = random_name(5)
|
720 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
|
721 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
722 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
723 |
+
#f.write(sentence.lower())
|
724 |
+
f.write(sentence)
|
725 |
+
# the last
|
726 |
+
elif k+num_seg == len(text):
|
727 |
+
sentence = " ".join(text[k:k+num_seg])
|
728 |
+
#print(sentence)
|
729 |
+
dur = timestamp[-1] - timestamp[k]
|
730 |
+
len_text = len(sentence.split())
|
731 |
+
if dur < 30000:
|
732 |
+
new_name = random_name(5)
|
733 |
+
audio = audio_file[timestamp[k]:timestamp[-1]]
|
734 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
735 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
736 |
+
#f.write(sentence.lower())
|
737 |
+
f.write(sentence)
|
738 |
+
|
739 |
+
except Exception as e:
|
740 |
+
print(f"\nError processing {sound_file}: {e}")
|
741 |
+
|
742 |
+
|
743 |
+
|
744 |
+
def split_2(sound_file,out_dir,num_seg):
|
745 |
+
"""
|
746 |
+
start_time, end_time = ms
|
747 |
+
slide window, no overlay
|
748 |
+
|
749 |
+
"""
|
750 |
+
|
751 |
+
try:
|
752 |
+
subtile_file = f'{sound_file[:-4]}.lrc'
|
753 |
+
text, timestamp = handle_lrc(subtile_file)
|
754 |
+
|
755 |
+
ext = sound_file[-3:]
|
756 |
+
audio_file = AudioSegment.from_file(sound_file, format=ext)
|
757 |
+
|
758 |
+
for k in range(0,len(text),num_seg):
|
759 |
+
#print(k)
|
760 |
+
if k + num_seg < len(text):
|
761 |
+
sentence = " ".join(text[k:k+num_seg])
|
762 |
+
#print(sentence)
|
763 |
+
dur = timestamp[k+num_seg] - timestamp[k]
|
764 |
+
len_text = len(sentence.split())
|
765 |
+
if dur < 30000:
|
766 |
+
new_name = random_name(5)
|
767 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
|
768 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
769 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
770 |
+
#f.write(sentence.lower())
|
771 |
+
f.write(sentence)
|
772 |
+
else:
|
773 |
+
sentence = " ".join(text[k:k+num_seg-1])
|
774 |
+
#print(sentence)
|
775 |
+
dur = timestamp[k+num_seg-1] - timestamp[k]
|
776 |
+
if dur < 30000:
|
777 |
+
new_name = random_name(5)
|
778 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
|
779 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
780 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
781 |
+
#f.write(sentence.lower())
|
782 |
+
f.write(sentence)
|
783 |
+
else: # the last
|
784 |
+
sentence = " ".join(text[k:])
|
785 |
+
#print(sentence)
|
786 |
+
dur = timestamp[-1] - timestamp[k]
|
787 |
+
len_text = len(sentence.split())
|
788 |
+
if dur < 30000:
|
789 |
+
new_name = random_name(5)
|
790 |
+
audio = audio_file[timestamp[k]:timestamp[-1]]
|
791 |
+
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
792 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
793 |
+
#f.write(sentence.lower())
|
794 |
+
f.write(sentence)
|
795 |
+
|
796 |
+
except Exception as e:
|
797 |
+
print(f"\nError processing {sound_file}: {e}")
|
798 |
+
|
799 |
+
|
800 |
+
|
801 |
+
def zing_split(in_dir, out_dir, num_seg=4, overlay='yes'):
|
802 |
+
"""Split audio files into multiple segments using multiprocessing."""
|
803 |
+
import os
|
804 |
+
import glob
|
805 |
+
|
806 |
+
from tqdm import tqdm
|
807 |
+
from multiprocessing import Pool
|
808 |
+
|
809 |
+
|
810 |
+
os.makedirs(out_dir, exist_ok=True)
|
811 |
+
files = glob.glob(f'{in_dir}/*.mp3')
|
812 |
+
|
813 |
+
print('Multiprocessing...')
|
814 |
+
with Pool() as pool:
|
815 |
+
results = []
|
816 |
+
for file in files:
|
817 |
+
if overlay.lower() == 'yes':
|
818 |
+
result = pool.apply_async(split_1, args=(file, out_dir, num_seg))
|
819 |
+
else:
|
820 |
+
result = pool.apply_async(split_2, args=(file, out_dir, num_seg))
|
821 |
+
results.append(result)
|
822 |
+
|
823 |
+
pool.close()
|
824 |
+
|
825 |
+
# Use tqdm to display the progress bar
|
826 |
+
for _ in tqdm(results, desc="Processing files"):
|
827 |
+
_.get()
|
828 |
+
|
829 |
+
pool.join()
|
830 |
+
|
831 |
+
|
832 |
+
###########################################################################def
|
833 |
+
|
834 |
+
def trim_head_tail(sound,head_threshold=-30, tail_threshold=-40, chunk_size=10):
|
835 |
+
"""
|
836 |
+
sound = AudioSegment.from_file(wav_in)
|
837 |
+
|
838 |
+
"""
|
839 |
+
#from pydub import AudioSegment
|
840 |
+
|
841 |
+
forward = sound
|
842 |
+
reverse = sound.reverse()
|
843 |
+
dur1 = 0 # ms
|
844 |
+
dur2 = 0 # ms
|
845 |
+
sound_len = len(sound)
|
846 |
+
|
847 |
+
assert chunk_size > 0 # to avoid infinite loop
|
848 |
+
while forward[dur1:dur1+chunk_size].dBFS < head_threshold and dur1 < len(forward):
|
849 |
+
dur1 += chunk_size
|
850 |
+
forward = sound[dur1:]
|
851 |
+
|
852 |
+
while reverse[dur2:dur2+chunk_size].dBFS < tail_threshold and dur2 < len(reverse):
|
853 |
+
dur2 += chunk_size
|
854 |
+
reverse = sound[dur2:]
|
855 |
+
|
856 |
+
#print(dur1,dur2)
|
857 |
+
sound = sound[dur1:sound_len-dur2]
|
858 |
+
#print(f"trim: heading={dur1}ms, tail={dur2}ms")
|
859 |
+
return sound
|
860 |
+
|
861 |
+
def trim_middle(sound,silence_len=250, silence_thresh=-35, padding=100):
|
862 |
+
"""
|
863 |
+
sound = AudioSegment.from_file(sound_file)
|
864 |
+
if found silence_len(ms) < silence_thresh(dB) will be replace with padding(ms)
|
865 |
+
"""
|
866 |
+
#from pydub.effects import strip_silence
|
867 |
+
#before_len = len(sound)
|
868 |
+
trimed_sound = strip_silence(sound, silence_len=silence_len, silence_thresh=silence_thresh, padding=padding)
|
869 |
+
#after_len = len(trimed_sound)
|
870 |
+
#print(f'trimed: {before_len - after_len}ms')
|
871 |
+
return trimed_sound
|
872 |
+
|
873 |
+
|
874 |
+
def _del_silence_file(args):
|
875 |
+
""" """
|
876 |
+
sound_file, out_folder = args
|
877 |
+
|
878 |
+
try:
|
879 |
+
sound = AudioSegment.from_file(sound_file)
|
880 |
+
trim1 = trim_middle(sound, silence_len=150, silence_thresh=-35, padding=5)
|
881 |
+
trim2 = trim_head_tail(trim1, head_threshold=-30, tail_threshold=-50, chunk_size=10)
|
882 |
+
trim2.export(f"{out_folder}/{os.path.basename(sound_file)}", format=sound_file[-3:],bitrate='256k')
|
883 |
+
except Exception as e:
|
884 |
+
#print(f"Error processing {sound_file}: {e}")
|
885 |
+
pass
|
886 |
+
|
887 |
+
|
888 |
+
def del_silence_file(sound_file, out_folder):
|
889 |
+
""" """
|
890 |
+
#sound_file, out_folder = args
|
891 |
+
|
892 |
+
try:
|
893 |
+
sound = AudioSegment.from_file(sound_file)
|
894 |
+
trim1 = trim_middle(sound, silence_len=200, silence_thresh=-35, padding=100)
|
895 |
+
trim2 = trim_head_tail(trim1, head_threshold=-30, tail_threshold=-50, chunk_size=10)
|
896 |
+
#trim2.export(f"{out_folder}/{os.path.basename(sound_file)}", format=sound_file[-3:],bitrate='256k')
|
897 |
+
trim2.set_channels(1).export(f"{out_folder}/{os.path.basename(sound_file)}", format=sound_file[-3:], bitrate='256k')
|
898 |
+
|
899 |
+
except Exception as e:
|
900 |
+
#print(f"Error processing {sound_file}: {e}")
|
901 |
+
pass
|
902 |
+
|
903 |
+
|
904 |
+
|
905 |
+
def _del_silence_folder(in_dir, out_dir):
|
906 |
+
""" """
|
907 |
+
os.makedirs(out_dir, exist_ok=True)
|
908 |
+
files = glob.glob(f'{in_dir}/*.mp3')
|
909 |
+
|
910 |
+
with Pool() as pool:
|
911 |
+
with tqdm(total=len(files), desc="Remove silence") as pbar:
|
912 |
+
for _ in pool.imap_unordered(del_silence_file, zip(files, [out_dir] * len(files))): # Pass arguments as tuples
|
913 |
+
pbar.update()
|
914 |
+
|
915 |
+
|
916 |
+
def _del_silence_folder(in_dir, out_dir):
|
917 |
+
""" """
|
918 |
+
os.makedirs(out_dir, exist_ok=True)
|
919 |
+
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
|
920 |
+
|
921 |
+
for file in tqdm(files):
|
922 |
+
del_silence_file(file, out_dir)
|
923 |
+
|
924 |
+
|
925 |
+
|
926 |
+
def del_silence_folder(in_dir,out_dir):
|
927 |
+
"""
|
928 |
+
"""
|
929 |
+
import os
|
930 |
+
import glob
|
931 |
+
|
932 |
+
from tqdm import tqdm
|
933 |
+
from multiprocessing import Pool
|
934 |
+
|
935 |
+
|
936 |
+
os.makedirs(out_dir, exist_ok=True)
|
937 |
+
files = glob.glob(f'{in_dir}/*.mp3')
|
938 |
+
|
939 |
+
print('Multiprocessing...')
|
940 |
+
with Pool() as pool:
|
941 |
+
results = []
|
942 |
+
for file in files:
|
943 |
+
result = pool.apply_async(del_silence_file, args=(file, out_dir))
|
944 |
+
results.append(result)
|
945 |
+
|
946 |
+
pool.close()
|
947 |
+
|
948 |
+
# Use tqdm to display the progress bar
|
949 |
+
for _ in tqdm(results, desc="Processing files"):
|
950 |
+
_.get()
|
951 |
+
|
952 |
+
pool.join()
|
953 |
+
|
954 |
+
###########################################################################def
|
955 |
+
|
956 |
+
def play_pair(audio_file,lab_ext='lab'):
|
957 |
+
""" """
|
958 |
+
#import IPython.display as ipd
|
959 |
+
#from IPython.display import Audio
|
960 |
+
text = open(f'{audio_file[:-4]}.{lab_ext}').read()
|
961 |
+
print(text)
|
962 |
+
ipd.display(ipd.Audio(audio_file))
|
963 |
+
|
964 |
+
|
965 |
+
def play_random(sound_dir,num_sound=5):
|
966 |
+
"""
|
967 |
+
play random sounds in folder
|
968 |
+
|
969 |
+
"""
|
970 |
+
import glob
|
971 |
+
import random
|
972 |
+
|
973 |
+
files = glob.glob(f'{sound_dir}/*.mp3') + glob.glob(f'{sound_dir}/*.wav')
|
974 |
+
print(f'Number of sound files: {len(files)}\n')
|
975 |
+
k = random.randint(0,len(files)-num_sound)
|
976 |
+
|
977 |
+
for file in files[k:k+num_sound]:
|
978 |
+
print(file)
|
979 |
+
play_pair(file)
|
980 |
+
|
981 |
+
|
982 |
+
|
983 |
+
|
984 |
+
|
985 |
+
def test_subtitle(sound_file,num_seq=4):
|
986 |
+
"""
|
987 |
+
files = glob.glob('/content/Hà_Trần_Vocals/*.mp3')
|
988 |
+
files.sort()
|
989 |
+
for file in files[:5]:
|
990 |
+
print(file)
|
991 |
+
test_subtitle(file,3)
|
992 |
+
|
993 |
+
"""
|
994 |
+
import os
|
995 |
+
import random
|
996 |
+
from pydub import AudioSegment
|
997 |
+
|
998 |
+
out_dir = "tmp_dir"
|
999 |
+
os.makedirs(out_dir, exist_ok=True)
|
1000 |
+
os.system(f"rm -f {out_dir}/*")
|
1001 |
+
|
1002 |
+
|
1003 |
+
subtile_file = f'{sound_file[:-4]}.lrc'
|
1004 |
+
text, timestamp = handle_lrc(subtile_file)
|
1005 |
+
|
1006 |
+
ext = sound_file[-3:]
|
1007 |
+
audio_file = AudioSegment.from_file(sound_file, format=ext)
|
1008 |
+
|
1009 |
+
for k in range(5):
|
1010 |
+
#print(k)
|
1011 |
+
if k+num_seq < len(text):
|
1012 |
+
sentence = " ".join(text[k:k+num_seq])
|
1013 |
+
dur = timestamp[k+num_seq] - timestamp[k]
|
1014 |
+
len_text = len(sentence.split())
|
1015 |
+
if dur < 20000:
|
1016 |
+
new_name = random_name(5)
|
1017 |
+
audio = audio_file[timestamp[k]:timestamp[k+num_seq]]
|
1018 |
+
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
|
1019 |
+
with open(f'{out_dir}/{new_name}.lab','w') as f:
|
1020 |
+
f.write(sentence.lower())
|
1021 |
+
|
1022 |
+
files = glob.glob(f'{out_dir}/*.mp3')
|
1023 |
+
print(f'num_samples: {len(files)}')
|
1024 |
+
k = random.randint(0,2)
|
1025 |
+
play_pair(files[k])
|
1026 |
+
#for file in files[:1]:
|
1027 |
+
# play_pair(file)
|
1028 |
+
|
1029 |
+
|
1030 |
+
###########################################################################def
|
1031 |
+
def _split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20):
|
1032 |
+
"""
|
1033 |
+
in_dir = '/content/Thu_Phuong_clean'
|
1034 |
+
out_dir = '/content/Thu_Phuong_recheck'
|
1035 |
+
split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20)
|
1036 |
+
|
1037 |
+
"""
|
1038 |
+
import glob
|
1039 |
+
from tqdm import tqdm
|
1040 |
+
import shutil
|
1041 |
+
|
1042 |
+
ext1 = pair_ext[0] # mp3/wav
|
1043 |
+
ext2 = pair_ext[1] # lab/txt
|
1044 |
+
|
1045 |
+
files = glob.glob(f'{in_dir}/*.{ext1}')
|
1046 |
+
print(f'Number of files: {len(files)}')
|
1047 |
+
|
1048 |
+
for i in tqdm(range(len(files) // window)):
|
1049 |
+
move_files = files[i * window: (i + 1) * window]
|
1050 |
+
dir_name = f"{out_dir}/{i:04d}"
|
1051 |
+
os.makedirs(dir_name, exist_ok=True)
|
1052 |
+
for file in move_files:
|
1053 |
+
shutil.copy(file,dir_name)
|
1054 |
+
shutil.copy(f'{file[:-4]}.{ext2}',dir_name)
|
1055 |
+
|
1056 |
+
|
1057 |
+
|
1058 |
+
def split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20):
|
1059 |
+
"""
|
1060 |
+
in_dir = '/content/Thu_Phuong_clean'
|
1061 |
+
out_dir = '/content/Thu_Phuong_recheck'
|
1062 |
+
split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20)
|
1063 |
+
split_folder(in_dir,out_dir,pair_ext=['mp3','lab'],window=20)
|
1064 |
+
|
1065 |
+
"""
|
1066 |
+
import glob
|
1067 |
+
from tqdm import tqdm
|
1068 |
+
import shutil
|
1069 |
+
|
1070 |
+
ext1 = pair_ext[0] # mp3/wav
|
1071 |
+
ext2 = pair_ext[1] # lab/txt
|
1072 |
+
|
1073 |
+
pair_files = get_pair_files(in_dir,in_dir,ext1,ext2)
|
1074 |
+
for i in tqdm(range(len(pair_files) // window)):
|
1075 |
+
copy_files = pair_files[i * window: (i + 1) * window]
|
1076 |
+
|
1077 |
+
dir_name = f"{out_dir}/{i:04d}"
|
1078 |
+
os.makedirs(dir_name, exist_ok=True)
|
1079 |
+
for name in copy_files:
|
1080 |
+
file1 = f'{in_dir}/{name}.{ext1}'
|
1081 |
+
file2 = f'{in_dir}/{name}.{ext2}'
|
1082 |
+
shutil.copy(file1,dir_name)
|
1083 |
+
shutil.copy(file2,dir_name)
|
1084 |
+
|
1085 |
+
|
1086 |
+
def combine_pair(in_dir,out_dir):
|
1087 |
+
"""
|
1088 |
+
copy all files in subfolders to a target folder
|
1089 |
+
make pair files (mp3+lab), remove unpaired files
|
1090 |
+
|
1091 |
+
"""
|
1092 |
+
import os
|
1093 |
+
import shutil
|
1094 |
+
from tqdm import tqdm
|
1095 |
+
|
1096 |
+
os.makedirs(out_dir, exist_ok=True)
|
1097 |
+
|
1098 |
+
x_files = []
|
1099 |
+
for path, subdirs, files in os.walk(in_dir):
|
1100 |
+
for file in files:
|
1101 |
+
full_path = os.path.join(path, file)
|
1102 |
+
x_files.append(full_path)
|
1103 |
+
|
1104 |
+
for file in tqdm(x_files):
|
1105 |
+
shutil.copy(file,out_dir)
|
1106 |
+
print(f"\nCopied {len(x_files)} files to {out_dir}")
|
1107 |
+
|
1108 |
+
# make pair files
|
1109 |
+
remove_unpaired_files(f'{out_dir}','mp3','lab')
|
1110 |
+
files = glob.glob(f'{out_dir}/*.mp3')
|
1111 |
+
print('-'*100)
|
1112 |
+
print(f'Final number of MP3 files: {len(files)}')
|
1113 |
+
print('-'*100)
|
1114 |
+
|
1115 |
+
|
1116 |
+
|
1117 |
+
###########################################################################def
|
1118 |
+
# Check and delete bad files with: play_wav, checkbox, text/lab
|
1119 |
+
|
1120 |
+
def show_audio(folder_path,start_id,end_id):
|
1121 |
+
"""
|
1122 |
+
"""
|
1123 |
+
import os
|
1124 |
+
import glob
|
1125 |
+
|
1126 |
+
from IPython.display import Audio, display
|
1127 |
+
import ipywidgets as widgets
|
1128 |
+
|
1129 |
+
files = [file for file in os.listdir(folder_path) if file.endswith('.mp3') or file.endswith('.wav')]
|
1130 |
+
files.sort()
|
1131 |
+
delete_checkboxes = [widgets.Checkbox(description=file, value=False) for file in files[start_id:end_id]]
|
1132 |
+
|
1133 |
+
for checkbox, file in zip(delete_checkboxes, files[start_id:end_id]):
|
1134 |
+
name = os.path.splitext(file)[0]
|
1135 |
+
text = open(f'{folder_path}/{name}.lab').read()
|
1136 |
+
print('-'*100)
|
1137 |
+
print(text)
|
1138 |
+
display(checkbox, Audio(folder_path + '/' + file))
|
1139 |
+
|
1140 |
+
return delete_checkboxes,files[start_id:end_id]
|
1141 |
+
|
1142 |
+
|
1143 |
+
def remove_files(folder_path, delete_checkboxes, files):
|
1144 |
+
"""
|
1145 |
+
"""
|
1146 |
+
import os
|
1147 |
+
from tqdm import tqdm
|
1148 |
+
|
1149 |
+
files_to_delete = [file for checkbox, file in zip(delete_checkboxes, files) if checkbox.value]
|
1150 |
+
for file in tqdm(files_to_delete):
|
1151 |
+
file_path = f'{folder_path}/' + file
|
1152 |
+
print(file_path)
|
1153 |
+
os.remove(file_path)
|
1154 |
+
|
1155 |
+
###########################################################################def
|
1156 |
+
|
1157 |
+
def get_audio_files(folder_path):
|
1158 |
+
"""
|
1159 |
+
x_files = get_audio_files('/content/raw_data')
|
1160 |
+
|
1161 |
+
"""
|
1162 |
+
import os
|
1163 |
+
|
1164 |
+
audio_files = []
|
1165 |
+
for root, _, files in os.walk(folder_path):
|
1166 |
+
for filename in files:
|
1167 |
+
if filename.endswith(".mp3") or filename.endswith(".wav"):
|
1168 |
+
filepath = os.path.join(root, filename)
|
1169 |
+
audio_files.append(filepath)
|
1170 |
+
return audio_files
|
1171 |
+
|
1172 |
+
def get_dur(sound_file):
|
1173 |
+
""" """
|
1174 |
+
x,sr = sf.read(sound_file)
|
1175 |
+
dur = x.size/sr # unit = senconds(s)
|
1176 |
+
return dur
|
1177 |
+
|
1178 |
+
|
1179 |
+
def total_time(elapsed_time):
|
1180 |
+
"""
|
1181 |
+
total_dur = 0
|
1182 |
+
for file in tqdm(x_files):
|
1183 |
+
dur = get_dur(file)
|
1184 |
+
total_dur = total_dur + dur
|
1185 |
+
|
1186 |
+
total_time(int(total_dur))
|
1187 |
+
> 15h:17m:50s
|
1188 |
+
|
1189 |
+
"""
|
1190 |
+
if elapsed_time < 60:
|
1191 |
+
print(f"\n{elapsed_time:02d}s")
|
1192 |
+
|
1193 |
+
elif elapsed_time >=60 and elapsed_time < 3600:
|
1194 |
+
minutes, seconds = divmod(elapsed_time, 60)
|
1195 |
+
print(f"\n{minutes:02d}m:{seconds:02d}s")
|
1196 |
+
|
1197 |
+
else:
|
1198 |
+
hours, remainder = divmod(elapsed_time, 3600)
|
1199 |
+
minutes, seconds = divmod(remainder, 60)
|
1200 |
+
print(f"\nTotal time: {hours}h:{minutes:02d}m:{seconds:02d}s")
|
1201 |
+
|
1202 |
+
|
1203 |
+
def report_time(folder):
|
1204 |
+
"""
|
1205 |
+
report_time('/content/Ha_Tran_clean_small_dirs/0000')
|
1206 |
+
> Total time: 2h:40m:33s
|
1207 |
+
|
1208 |
+
"""
|
1209 |
+
x_files = get_audio_files(folder)
|
1210 |
+
|
1211 |
+
total_dur = 0
|
1212 |
+
for file in tqdm(x_files):
|
1213 |
+
dur = get_dur(file)
|
1214 |
+
total_dur = total_dur + dur
|
1215 |
+
|
1216 |
+
total_time(int(total_dur))
|
1217 |
+
|
1218 |
+
###########################################################################def
|
1219 |
+
|
1220 |
+
def clean_lab(lab_dir,min_len=8,max_len=25):
|
1221 |
+
"""
|
1222 |
+
"""
|
1223 |
+
import glob
|
1224 |
+
from tqdm import tqdm
|
1225 |
+
import os
|
1226 |
+
|
1227 |
+
count = 0
|
1228 |
+
files = glob.glob(f'{lab_dir}/*.lab')
|
1229 |
+
print(f'num_files: {len(files)}')
|
1230 |
+
for file in tqdm(files):
|
1231 |
+
words =open(file).read()
|
1232 |
+
words = words.split()
|
1233 |
+
if len(words) > max_len or len(words) < min_len:
|
1234 |
+
os.remove(file)
|
1235 |
+
count = count + 1
|
1236 |
+
print(f'\nDeleted {count} files')
|
1237 |
+
|
1238 |
+
|
1239 |
+
###########################################################################def
|
1240 |
+
|
1241 |
+
|
1242 |
+
|
1243 |
+
|
1244 |
+
|
1245 |
+
|