|
|
|
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')
|
|
|
|
|
|
now_dir = os.getcwd()
|
|
sys.path.append(now_dir)
|
|
|
|
|
|
|
|
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
|
|
|
|
|
|
|
|
|
|
|
valid_chars = '/abcdđefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _aàáảãạăằắẳẵặâầấẩẫậeèéẻẽẹêềếểễệiìíỉĩịoòóỏõọôồốổỗộơờớởỡợuùúủũụưừứửữựyỳýỷỹỵ'
|
|
|
|
def rename_file(file_path,valid_chars):
|
|
"""
|
|
valid_chars includes: </>, <space>, <_>, <.>
|
|
valid_chars = '/abcdđefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _aàáảãạăằắẳẵặâầấẩẫậeèéẻẽẹêềếểễệiìíỉĩịoòóỏõọôồốổỗộơờớởỡợuùúủũụưừứửữựyỳýỷỹỵ'
|
|
|
|
"""
|
|
try:
|
|
name, ext = os.path.splitext(file_path)
|
|
|
|
|
|
new_name = ''.join([char if char.lower() in valid_chars else '' for char in name])
|
|
|
|
new_name = new_name.replace(' ', '_')
|
|
|
|
new_file_path = new_name + ext
|
|
|
|
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: </>, <space>, <_>, <.>
|
|
valid_chars = '/abcdđefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _aàáảãạăằắẳẵặâầấẩẫậeèéẻẽẹêềếểễệiìíỉĩịoòóỏõọôồốổỗộơờớởỡợuùúủũụưừứửữựyỳýỷỹỵ'
|
|
|
|
"""
|
|
import os
|
|
import glob
|
|
|
|
from tqdm import tqdm
|
|
from multiprocessing import Pool
|
|
|
|
|
|
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]
|
|
|
|
|
|
for result in tqdm(results, desc="Processing files"):
|
|
result.get()
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
print("After: ",torch.hub.get_dir())
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
import logging as logging
|
|
logger = logging.getLogger(__name__)
|
|
logging.disable(logging.INFO)
|
|
|
|
from spleeter.separator import Separator
|
|
|
|
|
|
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
|
|
|
|
"""
|
|
|
|
|
|
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'
|
|
|
|
wav2mp3(vocal_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)
|
|
|
|
|
|
|
|
|
|
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_vocal(stems2,file,dst_dir)
|
|
|
|
|
|
|
|
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')
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
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 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'
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
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'")
|
|
|
|
|
|
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 saxophone(separator,song_file,out_dir):
|
|
"""
|
|
stems = 'bass'|'drums'|'piano'|'vocals'|'other'
|
|
saxophone = other + vocals
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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/*.*')
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
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 combine_audio(input_file1, input_file2, output_file):
|
|
"""
|
|
"""
|
|
ffmpeg_command = [
|
|
'ffmpeg',
|
|
'-y',
|
|
'-i', input_file1,
|
|
'-i', input_file2,
|
|
'-filter_complex', '[0:0][1:0]amerge=inputs=2',
|
|
'-ac', '1',
|
|
'-ar', '44100',
|
|
'-codec:a', 'libmp3lame',
|
|
'-vol', '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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|