my_scripts / zingmp3_split.py
binhnx8's picture
Upload zingmp3_split.py
7b4057d verified
# Refer codes: https://github.com/nguyenvulebinh/lyric-alignment/blob/main/data_preparation/README.md
# !pip install -q pydub
###########################################################################def
import os
import glob
import re
import random
import string
import json
from tqdm.contrib.concurrent import process_map # or thread_map
from pydub import AudioSegment
from pydub.effects import strip_silence
import IPython.display as ipd
from IPython.display import Audio
import subprocess
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import Pool
from tqdm import tqdm
import IPython.display as ipd
from IPython.display import Audio
import soundfile as sf
import librosa
###########################################################################def
def pydub_play(sound_file,start_time,end_time):
"""
start_time, end_time = ms
pydub_play('/content/songs/Anh_Cho_Em_Mùa_Xuân_ZZEB7E0F.mp3',37390,39250)
"""
#from pydub import AudioSegment
#import IPython.display as ipd
#from IPython.display import Audio
ext = sound_file[-3:]
audio_file = AudioSegment.from_file(sound_file, format=ext)
audio = audio_file[start_time:end_time]
audio.export(f'demo.{ext}',format=ext)
ipd.display(ipd.Audio(f'demo.{ext}'))
def torch_play(sound_file,start_time,end_time):
"""
start_time, end_time = ms
torch_play('/content/songs/Anh_Cho_Em_Mùa_Xuân_ZZEB7E0F.mp3',37390,39250)
"""
import torchaudio
import IPython.display as ipd
from IPython.display import Audio
waveform, sample_rate = torchaudio.load(sound_file)
start_sample = int(start_time / 1000 * sample_rate)
end_sample = int(end_time / 1000 * sample_rate)
audio_to_play = waveform[:, start_sample:end_sample]
torchaudio.save('output.wav', audio_to_play, sample_rate)
ipd.display(Audio('output.wav'))
###########################################################################def
def file_wav_16k(args):
"""
use for MFA alignment
"""
input_sound, out_dir = args
os.makedirs(out_dir, exist_ok=True)
name = os.path.basename(input_sound)
name = os.path.splitext(name)[0]
output_sound= f'{out_dir}/{name}.wav'
command = [
"ffmpeg",
"-y", "-i", input_sound,
"-ar", "16000", # Set sample rate to 16000 Hz
"-ac", "1", # Set number of channels to 2 (stereo)
"-acodec", "pcm_s16le", # Use WAV encoder
output_sound
]
try:
subprocess.run(command, check=True,stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError as error:
print(f"Conversion failed: {error}")
def folder_to_wav_16k(in_dir, out_dir):
""" """
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
with Pool() as pool:
with tqdm(total=len(files), desc="Converting MP3 to WAV") as pbar:
for _ in pool.imap_unordered(file_wav_16k, zip(files, [out_dir] * len(files))): # Pass arguments as tuples
pbar.update()
###########################################################################def
def check_file(filepath):
"""
Hàm kiểm tra file âm thanh, nếu không hợp lệ thì xóa file đó.
"""
try:
# Đọc dữ liệu âm thanh với soundfile (sf)
data, sample_rate = sf.read(filepath)
return True # Nếu file hợp lệ
except Exception as e:
# Nếu có lỗi, xóa file và thông báo lỗi
os.remove(filepath)
print(f"Removed {filepath} due to error: {e}")
return False
def remove_invalid_sound(in_dir):
"""
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ệ.
"""
# Lấy danh sách các file âm thanh trong thư mục
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
print('Start multiprocessing')
# Sử dụng multiprocessing Pool để xử lý nhiều file cùng lúc
with Pool() as pool:
results = []
for file in files:
# Đảm bảo args là một tuple (file,)
result = pool.apply_async(check_file, args=(file,))
results.append(result)
pool.close()
# Sử dụng tqdm để hiển thị thanh tiến độ
for _ in tqdm(results, desc="Processing files"):
_.get()
pool.join()
def remove_bad_sound(x_files):
"""
remove invalid/bad sound files in list x_files
x_files = get_audio_files('/content/raw_data')
remove_bad_sound(x_files)
"""
#import os
for filepath in tqdm(x_files):
if not is_valid_sound(filepath):
os.remove(filepath)
print(f"\tDeleted invalid sound file: {filepath}")
###########################################################################def
def name_no_ext(folder,ext='txt'):
""" """
import os
x_name = []
files = os.listdir(folder)
for file in files:
if file.endswith(f'.{ext}'):
name = os.path.splitext(file)[0]
x_name.append(name)
return x_name
def the_same_name(dir_1,dir_2,ext1,ext2):
"""
the_same_name(dir_1,dir_2,'TextGrid','mp3')
"""
x1_name = name_no_ext(dir_1,ext1)
x2_name = name_no_ext(dir_2,ext2)
common = set(x1_name) & set(x2_name)
return list(common)
def get_pair_files(dir_1,dir_2,ext1,ext2):
"""
get_pair_files(dir_1,dir_2,'TextGrid','mp3')
"""
x1_name = name_no_ext(dir_1,ext1)
x2_name = name_no_ext(dir_2,ext2)
common = set(x1_name) & set(x2_name)
return list(common)
def remove_unpaired_files(folder_path,ext1,ext2):
"""
remove_unpaired_files('/content/songs','mp3','lrc')
"""
x_common = the_same_name(folder_path,folder_path,ext1,ext2)
files = glob.glob(f'{folder_path}/*')
len(files)
for file in files:
name = os.path.basename(file)
name = os.path.splitext(name)[0]
if name not in x_common:
print(file)
os.system(f'rm -f "{file}"')
###########################################################################def
time_lyric_regex = r"[\[|<](\d\d):(\d\d.\d\d)[\]|>](.*)"
time_regex = r"[\[|<](\d\d):(\d\d.\d\d)[\]|>]"
def ignore_line(text):
text_lower = text.lower().replace(' ', '').strip(' -.?!,)("\'…“”*_[]')
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') :
return True
if len(text.strip(' -.?!,)("\'…“”*_[]')) == 0:
return True
return False
def ignore_file(text):
matches = list(re.finditer(time_regex, text, re.MULTILINE))
if len(matches) > 0:
return True
def handle_lrc(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.read().strip().split('\n')
timestamp = []
text = []
label = []
try:
for line in lines:
matches = list(re.finditer(time_lyric_regex, line, re.MULTILINE))
if len(matches) > 0:
if ignore_file(matches[0].group(3)):
return
if not ignore_line(matches[0].group(3)):
start_time = int(float(matches[0].group(1)) * 60 * 1000) + int(float(matches[0].group(2)) * 1000)
timestamp.append(start_time)
text.append(matches[0].group(3).strip())
except:
print(file_path)
return
timestamp = timestamp[3:]
text = text[3:]
# print(len(text),len(timestamp))
return text, timestamp
###########################################################################def
def random_name(num_letters=5):
"""
"""
#import random
#import string
random_letters = random.choices(string.ascii_lowercase, k=num_letters)
random_string = ''.join(random_letters)
random_number = random.randint(10000, 99999)
out = f'{random_string}_{random_number}'
return out
###########################################################################def
# 3 parameters
# args = sound_file,out_dir,num_seq
def pydub_split(args):
"""
start_time, end_time = ms
args = sound_file,out_dir,num_seq
"""
import os
from pydub import AudioSegment
sound_file,out_dir,num_seq = args # 3 parameters
os.makedirs(out_dir, exist_ok=True)
subtile_file = f'{sound_file[:-4]}.lrc'
text, timestamp = handle_lrc(subtile_file)
ext = sound_file[-3:]
audio_file = AudioSegment.from_file(sound_file, format=ext)
for k in range(len(text)):
#print(k)
if k+num_seq < len(text):
sentence = " ".join(text[k:k+num_seq])
dur = timestamp[k+num_seq] - timestamp[k]
len_text = len(sentence.split())
if dur < 20000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seq]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
else:
sentence = " ".join(text[k:k+num_seq-1])
dur = timestamp[k+num_seq-1] - timestamp[k]
if dur < 20000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seq-1]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
# the last
elif k+num_seq == len(text):
sentence = " ".join(text[k:k+num_seq])
dur = timestamp[-1] - timestamp[k]
len_text = len(sentence.split())
if dur < 20000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[-1]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
def _zing_split(in_dir, out_dir,num_seq=4):
""" """
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3')
with Pool() as pool:
with tqdm(total=len(files), desc="Split pair files: mp3+lab") as pbar:
for _ in pool.imap_unordered(pydub_split, zip(files, [out_dir] * len(files), [num_seq] * len(files))):
pbar.update()
###########################################################################def
def remove_bad_lrc(lrc_dir):
"""
"""
import os
import glob
from tqdm import tqdm
files = glob.glob(f'{lrc_dir}/*.lrc')
print(f'num_files: {len(files)}')
for file in tqdm(files):
try:
text, timestamp = handle_lrc(file)
except Exception as e:
print(f"Error in splitting files: {e}")
os.remove(file)
print(f'removed {file}')
###########################################################################def
def _split_1(args):
"""
start_time, end_time = ms
slide window + overlay
"""
#import os
#from pydub import AudioSegment
sound_file,out_dir,num_seg = args # 3 parameters
#os.makedirs(out_dir, exist_ok=True)
subtile_file = f'{sound_file[:-4]}.lrc'
text, timestamp = handle_lrc(subtile_file)
ext = sound_file[-3:]
audio_file = AudioSegment.from_file(sound_file, format=ext)
for k in range(len(text)):
if k+num_seg < len(text):
sentence = " ".join(text[k:k+num_seg])
#print(sentence)
dur = timestamp[k+num_seg] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
else:
sentence = " ".join(text[k:k+num_seg-1])
#print(sentence)
dur = timestamp[k+num_seg-1] - timestamp[k]
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
# the last
elif k+num_seg == len(text):
sentence = " ".join(text[k:k+num_seg])
#print(sentence)
dur = timestamp[-1] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[-1]]
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
def _split_2(args):
"""
start_time, end_time = ms
slide window, no overlay
"""
#import os
#from pydub import AudioSegment
sound_file,out_dir,num_seg = args # 3 parameters
#os.makedirs(out_dir, exist_ok=True)
subtile_file = f'{sound_file[:-4]}.lrc'
text, timestamp = handle_lrc(subtile_file)
ext = sound_file[-3:]
audio_file = AudioSegment.from_file(sound_file, format=ext)
for k in range(0,len(text),num_seg):
#print(k)
if k + num_seg < len(text):
sentence = " ".join(text[k:k+num_seg])
#print(sentence)
dur = timestamp[k+num_seg] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
else:
sentence = " ".join(text[k:k+num_seg-1])
#print(sentence)
dur = timestamp[k+num_seg-1] - timestamp[k]
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
else: # the last
sentence = " ".join(text[k:])
#print(sentence)
dur = timestamp[-1] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[-1]]
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
def _zing_split(in_dir, out_dir,num_seg=4,overlay='yes'):
""" """
import os
import glob
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3')
with Pool() as pool:
with tqdm(total=len(files), desc="Split pair files: mp3+lab") as pbar:
if overlay.lower() == 'yes':
for _ in pool.imap_unordered(split_1, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
pbar.update()
else:
for _ in pool.imap_unordered(split_2, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
pbar.update()
def _zing_split(in_dir, out_dir,num_seg=4,overlay='yes'):
""" """
import os
import glob
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3')
with Pool() as pool:
with tqdm(total=len(files), desc="Split pair files: mp3+lab") as pbar:
try:
if overlay.lower() == 'yes':
for _ in pool.imap_unordered(split_1, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
pbar.update()
else:
for _ in pool.imap_unordered(split_2, zip(files, [out_dir] * len(files), [num_seg] * len(files))):
pbar.update()
except:
pass
###########################################################################def
def check_and_remove_empty_folder(folder_path):
"""
"""
if os.path.exists(folder_path):
if not os.listdir(folder_path):
os.rmdir(folder_path)
print(f"Removed empty directory: {folder_path}")
def split_one(sound_file,out_dir,num_seg):
"""
This use for manual transcription checking, augmentation
"""
import os
song_name = random_name(5)
out_dir = f'{out_dir}/{song_name}'
os.makedirs(out_dir, exist_ok=True)
try:
subtile_file = f'{sound_file[:-4]}.lrc'
text, timestamp = handle_lrc(subtile_file)
ext = sound_file[-3:]
audio_file = AudioSegment.from_file(sound_file, format=ext)
for k in range(len(text)):
if k+num_seg < len(text):
sentence = " ".join(text[k:k+num_seg])
#print(sentence)
dur = timestamp[k+num_seg] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
#print(k)
new_name = f'{song_name}_{k:02d}'
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
#f.write(sentence.lower())
f.write(sentence)
else:
sentence = " ".join(text[k:k+num_seg-1])
#print(sentence)
dur = timestamp[k+num_seg-1] - timestamp[k]
if dur < 30000:
#print(k)
new_name = f'{song_name}_{k:02d}'
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
#f.write(sentence.lower())
f.write(sentence)
# the last
elif k+num_seg == len(text):
sentence = " ".join(text[k:k+num_seg])
#print(sentence)
dur = timestamp[-1] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
#print(k)
new_name = f'{song_name}_{k:02d}'
audio = audio_file[timestamp[k]:timestamp[-1]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
#f.write(sentence.lower())
f.write(sentence)
except Exception as e:
print(f"\nError processing {sound_file}: {e}")
check_and_remove_empty_folder(out_dir)
# Finished
def mp_split_one(in_dir,out_dir):
"""
"""
import os
import glob
from tqdm import tqdm
from multiprocessing import Pool
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
print('Start multiprocessing')
with Pool() as pool:
results = [pool.apply_async(split_one, args=(file, out_dir, 1)) for file in files]
# Dùng tqdm để hiển thị tiến trình
for result in tqdm(results, desc="Processing files"):
result.get() # Đảm bảo chờ quá trình hoàn thành
###########################################################################def
# Split sounds from Audacity transcription
def audacity_split_one(audio_file,out_dir):
"""
"""
import os
song_name = random_name(5)
out_dir = f'{out_dir}/{song_name}'
os.makedirs(out_dir, exist_ok=True)
# Đọc file âm thanh
y, sr = librosa.load(audio_file, sr=None)
# Đọc nội dung từ file text
subtile_file = f'{audio_file[:-4]}.txt'
with open(subtile_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
# Lặp qua từng dòng trong file transcription để cắt và lưu file
for i, line in enumerate(lines):
parts = line.strip().split('\t')
start_time = float(parts[0])
end_time = float(parts[1])
content = parts[2] if len(parts) > 2 else ""
#print(content)
start_sample = int(start_time * sr)
end_sample = int(end_time * sr)
# Cắt đoạn âm thanh
segment = y[start_sample:end_sample]
# Tạo tên file cho đoạn âm thanh
segment_file = f'{out_dir}/{song_name}_{i+1:02d}.mp3'
# Lưu đoạn âm thanh
sf.write(segment_file, segment, sr)
#print(f'Saved: {segment_file}')
# Tạo file lab tương ứng
with open(f'{out_dir}/{song_name}_{i+1:02d}.lab', 'w', encoding='utf-8') as lab_file:
lab_file.write(content)
print(f'\nSaved to {out_dir}')
def mp_audacity(in_dir,out_dir):
"""
"""
import os
import glob
from tqdm import tqdm
from multiprocessing import Pool
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
print('Start multiprocessing')
with Pool() as pool:
results = [pool.apply_async(audacity_split_one, args=(file, out_dir)) for file in files]
# Dùng tqdm để hiển thị tiến trình
for result in tqdm(results, desc="Processing files"):
result.get() # Đảm bảo chờ quá trình hoàn thành
###########################################################################def
def split_1(sound_file,out_dir,num_seg):
"""
start_time, end_time = ms
slide window + overlay
"""
try:
subtile_file = f'{sound_file[:-4]}.lrc'
text, timestamp = handle_lrc(subtile_file)
ext = sound_file[-3:]
audio_file = AudioSegment.from_file(sound_file, format=ext)
for k in range(len(text)):
if k+num_seg < len(text):
sentence = " ".join(text[k:k+num_seg])
#print(sentence)
dur = timestamp[k+num_seg] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
#f.write(sentence.lower())
f.write(sentence)
else:
sentence = " ".join(text[k:k+num_seg-1])
#print(sentence)
dur = timestamp[k+num_seg-1] - timestamp[k]
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
#f.write(sentence.lower())
f.write(sentence)
# the last
elif k+num_seg == len(text):
sentence = " ".join(text[k:k+num_seg])
#print(sentence)
dur = timestamp[-1] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[-1]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
#f.write(sentence.lower())
f.write(sentence)
except Exception as e:
print(f"\nError processing {sound_file}: {e}")
def split_2(sound_file,out_dir,num_seg):
"""
start_time, end_time = ms
slide window, no overlay
"""
try:
subtile_file = f'{sound_file[:-4]}.lrc'
text, timestamp = handle_lrc(subtile_file)
ext = sound_file[-3:]
audio_file = AudioSegment.from_file(sound_file, format=ext)
for k in range(0,len(text),num_seg):
#print(k)
if k + num_seg < len(text):
sentence = " ".join(text[k:k+num_seg])
#print(sentence)
dur = timestamp[k+num_seg] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seg]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
#f.write(sentence.lower())
f.write(sentence)
else:
sentence = " ".join(text[k:k+num_seg-1])
#print(sentence)
dur = timestamp[k+num_seg-1] - timestamp[k]
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seg-1]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
#f.write(sentence.lower())
f.write(sentence)
else: # the last
sentence = " ".join(text[k:])
#print(sentence)
dur = timestamp[-1] - timestamp[k]
len_text = len(sentence.split())
if dur < 30000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[-1]]
audio.set_channels(1).export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
#f.write(sentence.lower())
f.write(sentence)
except Exception as e:
print(f"\nError processing {sound_file}: {e}")
def zing_split(in_dir, out_dir, num_seg=4, overlay='yes'):
"""Split audio files into multiple segments using multiprocessing."""
import os
import glob
from tqdm import tqdm
from multiprocessing import Pool
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3')
print('Multiprocessing...')
with Pool() as pool:
results = []
for file in files:
if overlay.lower() == 'yes':
result = pool.apply_async(split_1, args=(file, out_dir, num_seg))
else:
result = pool.apply_async(split_2, args=(file, out_dir, num_seg))
results.append(result)
pool.close()
# Use tqdm to display the progress bar
for _ in tqdm(results, desc="Processing files"):
_.get()
pool.join()
###########################################################################def
def trim_head_tail(sound,head_threshold=-30, tail_threshold=-40, chunk_size=10):
"""
sound = AudioSegment.from_file(wav_in)
"""
#from pydub import AudioSegment
forward = sound
reverse = sound.reverse()
dur1 = 0 # ms
dur2 = 0 # ms
sound_len = len(sound)
assert chunk_size > 0 # to avoid infinite loop
while forward[dur1:dur1+chunk_size].dBFS < head_threshold and dur1 < len(forward):
dur1 += chunk_size
forward = sound[dur1:]
while reverse[dur2:dur2+chunk_size].dBFS < tail_threshold and dur2 < len(reverse):
dur2 += chunk_size
reverse = sound[dur2:]
#print(dur1,dur2)
sound = sound[dur1:sound_len-dur2]
#print(f"trim: heading={dur1}ms, tail={dur2}ms")
return sound
def trim_middle(sound,silence_len=250, silence_thresh=-35, padding=100):
"""
sound = AudioSegment.from_file(sound_file)
if found silence_len(ms) < silence_thresh(dB) will be replace with padding(ms)
"""
#from pydub.effects import strip_silence
#before_len = len(sound)
trimed_sound = strip_silence(sound, silence_len=silence_len, silence_thresh=silence_thresh, padding=padding)
#after_len = len(trimed_sound)
#print(f'trimed: {before_len - after_len}ms')
return trimed_sound
def _del_silence_file(args):
""" """
sound_file, out_folder = args
try:
sound = AudioSegment.from_file(sound_file)
trim1 = trim_middle(sound, silence_len=150, silence_thresh=-35, padding=5)
trim2 = trim_head_tail(trim1, head_threshold=-30, tail_threshold=-50, chunk_size=10)
trim2.export(f"{out_folder}/{os.path.basename(sound_file)}", format=sound_file[-3:],bitrate='256k')
except Exception as e:
#print(f"Error processing {sound_file}: {e}")
pass
def del_silence_file(sound_file, out_folder):
""" """
#sound_file, out_folder = args
try:
sound = AudioSegment.from_file(sound_file)
trim1 = trim_middle(sound, silence_len=200, silence_thresh=-35, padding=100)
trim2 = trim_head_tail(trim1, head_threshold=-30, tail_threshold=-50, chunk_size=10)
#trim2.export(f"{out_folder}/{os.path.basename(sound_file)}", format=sound_file[-3:],bitrate='256k')
trim2.set_channels(1).export(f"{out_folder}/{os.path.basename(sound_file)}", format=sound_file[-3:], bitrate='256k')
except Exception as e:
#print(f"Error processing {sound_file}: {e}")
pass
def _del_silence_folder(in_dir, out_dir):
""" """
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3')
with Pool() as pool:
with tqdm(total=len(files), desc="Remove silence") as pbar:
for _ in pool.imap_unordered(del_silence_file, zip(files, [out_dir] * len(files))): # Pass arguments as tuples
pbar.update()
def _del_silence_folder(in_dir, out_dir):
""" """
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3') + glob.glob(f'{in_dir}/*.wav')
for file in tqdm(files):
del_silence_file(file, out_dir)
def del_silence_folder(in_dir,out_dir):
"""
"""
import os
import glob
from tqdm import tqdm
from multiprocessing import Pool
os.makedirs(out_dir, exist_ok=True)
files = glob.glob(f'{in_dir}/*.mp3')
print('Multiprocessing...')
with Pool() as pool:
results = []
for file in files:
result = pool.apply_async(del_silence_file, args=(file, out_dir))
results.append(result)
pool.close()
# Use tqdm to display the progress bar
for _ in tqdm(results, desc="Processing files"):
_.get()
pool.join()
###########################################################################def
def play_pair(audio_file,lab_ext='lab'):
""" """
#import IPython.display as ipd
#from IPython.display import Audio
text = open(f'{audio_file[:-4]}.{lab_ext}').read()
print(text)
ipd.display(ipd.Audio(audio_file))
def play_random(sound_dir,num_sound=5):
"""
play random sounds in folder
"""
import glob
import random
files = glob.glob(f'{sound_dir}/*.mp3') + glob.glob(f'{sound_dir}/*.wav')
print(f'Number of sound files: {len(files)}\n')
k = random.randint(0,len(files)-num_sound)
for file in files[k:k+num_sound]:
print(file)
play_pair(file)
def test_subtitle(sound_file,num_seq=4):
"""
files = glob.glob('/content/Hà_Trần_Vocals/*.mp3')
files.sort()
for file in files[:5]:
print(file)
test_subtitle(file,3)
"""
import os
import random
from pydub import AudioSegment
out_dir = "tmp_dir"
os.makedirs(out_dir, exist_ok=True)
os.system(f"rm -f {out_dir}/*")
subtile_file = f'{sound_file[:-4]}.lrc'
text, timestamp = handle_lrc(subtile_file)
ext = sound_file[-3:]
audio_file = AudioSegment.from_file(sound_file, format=ext)
for k in range(5):
#print(k)
if k+num_seq < len(text):
sentence = " ".join(text[k:k+num_seq])
dur = timestamp[k+num_seq] - timestamp[k]
len_text = len(sentence.split())
if dur < 20000:
new_name = random_name(5)
audio = audio_file[timestamp[k]:timestamp[k+num_seq]]
audio.export(f'{out_dir}/{new_name}.mp3',format='mp3',bitrate='256k')
with open(f'{out_dir}/{new_name}.lab','w') as f:
f.write(sentence.lower())
files = glob.glob(f'{out_dir}/*.mp3')
print(f'num_samples: {len(files)}')
k = random.randint(0,2)
play_pair(files[k])
#for file in files[:1]:
# play_pair(file)
###########################################################################def
def _split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20):
"""
in_dir = '/content/Thu_Phuong_clean'
out_dir = '/content/Thu_Phuong_recheck'
split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20)
"""
import glob
from tqdm import tqdm
import shutil
ext1 = pair_ext[0] # mp3/wav
ext2 = pair_ext[1] # lab/txt
files = glob.glob(f'{in_dir}/*.{ext1}')
print(f'Number of files: {len(files)}')
for i in tqdm(range(len(files) // window)):
move_files = files[i * window: (i + 1) * window]
dir_name = f"{out_dir}/{i:04d}"
os.makedirs(dir_name, exist_ok=True)
for file in move_files:
shutil.copy(file,dir_name)
shutil.copy(f'{file[:-4]}.{ext2}',dir_name)
def split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20):
"""
in_dir = '/content/Thu_Phuong_clean'
out_dir = '/content/Thu_Phuong_recheck'
split_folder(in_dir,out_dir,pair_ext=['mp3','lrc'],window=20)
split_folder(in_dir,out_dir,pair_ext=['mp3','lab'],window=20)
"""
import glob
from tqdm import tqdm
import shutil
ext1 = pair_ext[0] # mp3/wav
ext2 = pair_ext[1] # lab/txt
pair_files = get_pair_files(in_dir,in_dir,ext1,ext2)
for i in tqdm(range(len(pair_files) // window)):
copy_files = pair_files[i * window: (i + 1) * window]
dir_name = f"{out_dir}/{i:04d}"
os.makedirs(dir_name, exist_ok=True)
for name in copy_files:
file1 = f'{in_dir}/{name}.{ext1}'
file2 = f'{in_dir}/{name}.{ext2}'
shutil.copy(file1,dir_name)
shutil.copy(file2,dir_name)
def combine_pair(in_dir,out_dir):
"""
copy all files in subfolders to a target folder
make pair files (mp3+lab), remove unpaired files
"""
import os
import shutil
from tqdm import tqdm
os.makedirs(out_dir, exist_ok=True)
x_files = []
for path, subdirs, files in os.walk(in_dir):
for file in files:
full_path = os.path.join(path, file)
x_files.append(full_path)
for file in tqdm(x_files):
shutil.copy(file,out_dir)
print(f"\nCopied {len(x_files)} files to {out_dir}")
# make pair files
remove_unpaired_files(f'{out_dir}','mp3','lab')
files = glob.glob(f'{out_dir}/*.mp3')
print('-'*100)
print(f'Final number of MP3 files: {len(files)}')
print('-'*100)
###########################################################################def
# Check and delete bad files with: play_wav, checkbox, text/lab
def show_audio(folder_path,start_id,end_id):
"""
"""
import os
import glob
from IPython.display import Audio, display
import ipywidgets as widgets
files = [file for file in os.listdir(folder_path) if file.endswith('.mp3') or file.endswith('.wav')]
files.sort()
delete_checkboxes = [widgets.Checkbox(description=file, value=False) for file in files[start_id:end_id]]
for checkbox, file in zip(delete_checkboxes, files[start_id:end_id]):
name = os.path.splitext(file)[0]
text = open(f'{folder_path}/{name}.lab').read()
print('-'*100)
print(text)
display(checkbox, Audio(folder_path + '/' + file))
return delete_checkboxes,files[start_id:end_id]
def remove_files(folder_path, delete_checkboxes, files):
"""
"""
import os
from tqdm import tqdm
files_to_delete = [file for checkbox, file in zip(delete_checkboxes, files) if checkbox.value]
for file in tqdm(files_to_delete):
file_path = f'{folder_path}/' + file
print(file_path)
os.remove(file_path)
###########################################################################def
def get_audio_files(folder_path):
"""
x_files = get_audio_files('/content/raw_data')
"""
import os
audio_files = []
for root, _, files in os.walk(folder_path):
for filename in files:
if filename.endswith(".mp3") or filename.endswith(".wav"):
filepath = os.path.join(root, filename)
audio_files.append(filepath)
return audio_files
def get_dur(sound_file):
""" """
x,sr = sf.read(sound_file)
dur = x.size/sr # unit = senconds(s)
return dur
def total_time(elapsed_time):
"""
total_dur = 0
for file in tqdm(x_files):
dur = get_dur(file)
total_dur = total_dur + dur
total_time(int(total_dur))
> 15h:17m:50s
"""
if elapsed_time < 60:
print(f"\n{elapsed_time:02d}s")
elif elapsed_time >=60 and elapsed_time < 3600:
minutes, seconds = divmod(elapsed_time, 60)
print(f"\n{minutes:02d}m:{seconds:02d}s")
else:
hours, remainder = divmod(elapsed_time, 3600)
minutes, seconds = divmod(remainder, 60)
print(f"\nTotal time: {hours}h:{minutes:02d}m:{seconds:02d}s")
def report_time(folder):
"""
report_time('/content/Ha_Tran_clean_small_dirs/0000')
> Total time: 2h:40m:33s
"""
x_files = get_audio_files(folder)
total_dur = 0
for file in tqdm(x_files):
dur = get_dur(file)
total_dur = total_dur + dur
total_time(int(total_dur))
###########################################################################def
def clean_lab(lab_dir,min_len=8,max_len=25):
"""
"""
import glob
from tqdm import tqdm
import os
count = 0
files = glob.glob(f'{lab_dir}/*.lab')
print(f'num_files: {len(files)}')
for file in tqdm(files):
words =open(file).read()
words = words.split()
if len(words) > max_len or len(words) < min_len:
os.remove(file)
count = count + 1
print(f'\nDeleted {count} files')
###########################################################################def