File size: 11,797 Bytes
8ff978e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
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: </>, <space>, <_>, <.>
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)
# 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: </>, <space>, <_>, <.>
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
|