import os import re import sys import glob import shutil import subprocess from pathlib import Path import time import logging from tqdm import tqdm import subprocess from pydub import AudioSegment import tensorflow as tf tf.get_logger().setLevel('ERROR') ################################################################################def now_dir = os.getcwd() sys.path.append(now_dir) #os.chdir(f'{now_dir}/spleeter') # turn off tensor warning os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' ################################################################################def # valid_chars includes: , , <_>, <.> valid_chars = '/abcdđefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _aàáảãạăằắẳẵặâầấẩẫậeèéẻẽẹêềếểễệiìíỉĩịoòóỏõọôồốổỗộơờớởỡợuùúủũụưừứửữựyỳýỷỹỵ' def rename_file(file_path,valid_chars): """ valid_chars includes: , , <_>, <.> valid_chars = '/abcdđefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _aàáảãạăằắẳẵặâầấẩẫậeèéẻẽẹêềếểễệiìíỉĩịoòóỏõọôồốổỗộơờớởỡợuùúủũụưừứửữựyỳýỷỹỵ' """ try: name, ext = os.path.splitext(file_path) # Duyệt qua từng ký tự trong tên file và chỉ giữ lại các ký tự hợp lệ new_name = ''.join([char if char.lower() in valid_chars else '' for char in name]) # Thay khoảng trắng bằng '_' new_name = new_name.replace(' ', '_') # Kết hợp lại tên mới với phần mở rộng không thay đổi new_file_path = new_name + ext # Đổi tên file os.rename(file_path, new_file_path) except Exception as e: print(f"\nError processing {file_path}: {e}") def mp_rename(in_dir,valid_chars): """ valid_chars includes: , , <_>, <.> valid_chars = '/abcdđefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _aàáảãạăằắẳẵặâầấẩẫậeèéẻẽẹêềếểễệiìíỉĩịoòóỏõọôồốổỗộơờớởỡợuùúủũụưừứửữựyỳýỷỹỵ' """ 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}/*.*') print('Start multiprocessing') with Pool() as pool: results = [pool.apply_async(rename_file, args=(file, valid_chars)) 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 set_cache(cache_dir): """ 1. Backup and restore your checkpoints 2. Change cache default: /root/.cache/torch/hub set_cache('/content') -> '/content/hub' """ import os import torch print("Before: ",torch.hub.get_dir()) os.makedirs(cache_dir, exist_ok=True) os.environ['TORCH_HOME'] = cache_dir #torch.hub.set_dir(cache_dir) print("After: ",torch.hub.get_dir()) ################################################################################def def wav2mp3(input_file, output_file): """ 256kbps, os.devnull """ with open(os.devnull, 'w') as devnull: subprocess.run(['ffmpeg', '-y', '-i', input_file, "-b:a", "256k", '-ac', '1', '-ar', '44100', output_file],stdout=devnull, stderr=devnull, check=True) ################################################################################def ## disable logging from spleeter/spleeter/audio/ffmpeg.py import logging as logging logger = logging.getLogger(__name__) logging.disable(logging.INFO) from spleeter.separator import Separator #separator = Separator('spleeter:2stems') stems2 = Separator('spleeter:2stems') stems4 = Separator('spleeter:4stems') stems5 = Separator('spleeter:5stems') def get_vocal(separator,song_file,out_dir): """ spleeter_file('/content/test/wav/song_2173577437.wav','acapella') max_time = 10 minutes? longer will OOM """ # https://github.com/deezer/spleeter/wiki/4.-API-Reference os.makedirs(out_dir, exist_ok=True) filename = os.path.basename(song_file) output_file = f'{out_dir}/{filename[:-4]}.mp3' os.system(f"cp '{song_file}' current.mp3") separator.separate_to_file('current.mp3', 'temp') vocal_file = f'temp/current/vocals.wav' # clean vocal wav2mp3(vocal_file, output_file) #print(f'Output file: {output_file}') def spleeter_folder(src_dir,dst_dir): """ """ import glob from tqdm import tqdm import logging as logging logger = logging.getLogger(__name__) logging.disable(logging.INFO) # pretrained model: spleeter/pretrained_models/2stems # Extract vocal print('Note: this fixed the wrong file content.') mp3 = glob.glob(f'{src_dir}/*.mp3') wav = glob.glob(f'{src_dir}/*.wav') files = mp3 + wav files.sort() for file in tqdm(files): #print(f'music file:{file}') get_vocal(stems2,file,dst_dir) ################################################################################def def get_stems(separator,song_file,out_dir): """ max_time = 10 minutes? longer will OOM get_stems(stems2,'/content/mixed.mp3','/content/demo') get_stems(stems4,'/content/mixed.mp3','/content/demo') get_stems(stems5,'/content/mixed.mp3','/content/demo') """ # https://github.com/deezer/spleeter/wiki/4.-API-Reference #import shutil #import glob os.makedirs(out_dir, exist_ok=True) file_name = os.path.basename(song_file) input_name = os.path.splitext(file_name)[0] temp_dir = 'temp/current' if os.path.exists(temp_dir) and os.path.isdir(temp_dir): shutil.rmtree(temp_dir) os.system(f"cp '{song_file}' current.mp3") separator.separate_to_file('current.mp3', 'temp') files = glob.glob('temp/current/*.*') for stem_file in files: file_name = os.path.basename(stem_file) stem_name = os.path.splitext(file_name)[0] output_file = f"{out_dir}/{input_name}_{stem_name}.mp3" wav2mp3(stem_file, output_file) def extract_accompaniment(separator,src_dir,dst_dir): """ """ import glob from tqdm import tqdm import logging as logging logger = logging.getLogger(__name__) logging.disable(logging.INFO) # Extract all stems print('Note: this fixed the wrong file content.') mp3 = glob.glob(f"{src_dir}/*.mp3") wav = glob.glob(f"{src_dir}/*.wav") files = mp3 + wav files.sort() for file in tqdm(files): get_stems(separator,file,dst_dir) ################################################################################def def extract_stem(separator,song_file,out_dir,keep_name='vocals'): """ max_time = 10 minutes? longer will OOM extract_stem(stems2,'/content/mixed.mp3','/content/demo',keep_name='vocals') extract_stem(stems4,'/content/mixed.mp3','/content/demo',keep_name='vocals') extract_stem(stems5,'/content/mixed.mp3','/content/demo',keep_name='other') keep_name = 'bass'|'drums'|'piano'|'vocals'|'other' """ # https://github.com/deezer/spleeter/wiki/4.-API-Reference #import shutil #import glob if keep_name not in ['bass','drums','piano','vocals','other']: raise ValueError("stem name must be: 'bass', 'drums', 'piano', 'vocals', or 'other'") os.makedirs(out_dir, exist_ok=True) file_name = os.path.basename(song_file) input_name = os.path.splitext(file_name)[0] temp_dir = 'temp/current' if os.path.exists(temp_dir) and os.path.isdir(temp_dir): shutil.rmtree(temp_dir) os.system(f"cp '{song_file}' current.mp3") separator.separate_to_file('current.mp3', 'temp') files = glob.glob('temp/current/*.*') for stem_file in files: file_name = os.path.basename(stem_file) stem_name = os.path.splitext(file_name)[0] if stem_name == keep_name: output_file = f"{out_dir}/{input_name}_{stem_name}.mp3" wav2mp3(stem_file, output_file) def extract_one(separator,src_dir,dst_dir,keep_name='piano'): """ keep_name = 'bass'|'drums'|'piano'|'vocals'|'other' """ import glob from tqdm import tqdm import logging as logging logger = logging.getLogger(__name__) logging.disable(logging.INFO) if keep_name not in ['bass','drums','piano','vocals','other']: raise ValueError("stem name must be: 'bass', 'drums', 'piano', 'vocals', or 'other'") # Extract all stems print('Note: this fixed the wrong file content.') mp3 = glob.glob(f"{src_dir}/*.mp3") wav = glob.glob(f"{src_dir}/*.wav") files = mp3 + wav files.sort() for file in tqdm(files): extract_stem(separator,file,dst_dir,keep_name) ################################################################################def def saxophone(separator,song_file,out_dir): """ stems = 'bass'|'drums'|'piano'|'vocals'|'other' saxophone = other + vocals """ # https://github.com/deezer/spleeter/wiki/4.-API-Reference #import shutil #import glob os.makedirs(out_dir, exist_ok=True) file_name = os.path.basename(song_file) input_name = os.path.splitext(file_name)[0] temp_dir = 'temp/current' if os.path.exists(temp_dir) and os.path.isdir(temp_dir): shutil.rmtree(temp_dir) os.system(f"cp '{song_file}' current.mp3") separator.separate_to_file('current.mp3', 'temp') files = glob.glob('temp/current/*.*') # Load audio stems other = AudioSegment.from_file("temp/current/other.wav") vocals = AudioSegment.from_file("temp/current/vocals.wav") remix = other.overlay(vocals) remix = remix.set_frame_rate(44100).set_channels(1) remix.export(f'{out_dir}/{input_name}.mp3','MP3') def extract_saxophone(separator,src_dir,dst_dir): """ keep_name = 'bass'|'drums'|'piano'|'vocals'|'other' extract_saxophone(stems5,src_dir,dst_dir) """ import glob from tqdm import tqdm import logging as logging logger = logging.getLogger(__name__) logging.disable(logging.INFO) # Extract all stems #print('Note: this fixed the wrong file content.') mp3 = glob.glob(f"{src_dir}/*.mp3") wav = glob.glob(f"{src_dir}/*.wav") files = mp3 + wav files.sort() for file in tqdm(files): saxophone(separator,file,dst_dir) ################################################################################def def combine_audio(input_file1, input_file2, output_file): """ """ ffmpeg_command = [ 'ffmpeg', '-y', # overwrite output '-i', input_file1, '-i', input_file2, '-filter_complex', '[0:0][1:0]amerge=inputs=2', # combine two audio stream '-ac', '1', # Set the output audio channels to 1 (mono) '-ar', '44100', # Set the output audio sample rate to 44100 Hz '-codec:a', 'libmp3lame', # Set the output audio codec to libmp3lame (MP3) '-vol', '256', # range volume 0-256 '-loglevel', 'debug', output_file ] result = subprocess.run(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.returncode != 0: print(f"FFmpeg error: {result.stderr.decode()}") return ################################################################################def