Full restructure to entirely encapsulate the process

This commit is contained in:
oitsjustjose 2025-02-07 23:01:42 -06:00
commit 2128fb926b
6 changed files with 259 additions and 123 deletions

12
.gitignore vendored
View file

@ -1,7 +1,5 @@
/bin
/include
/lib
/lib64
/share
/pyvenv.cfg
/separated/**/*
/Python
/input
/output
/htdemucs_ft
__pycache__

88
main.py Normal file
View file

@ -0,0 +1,88 @@
import os
import shutil
import sys
from pathlib import Path
import eyed3
from eyed3.id3 import ID3_V2_4, Tag
from music_file import MusicFile, MODEL_NAME
SUPPORTED_EXTS = [".mp3", ".m4a", ".wav"]
def copy_metadata(original_file: MusicFile, no_drums_path: Path) -> bool:
"""
Copies the metadata from the original music file to the new drumless track
Args:
original_file (MusicFile): The MusicFile instance for the original, unmodified/unsplit son
no_drums_path (Path): The path to the drumless output file after splitting
Returns:
bool: True if the process succeeds, False if get_tag raises an exception
"""
try:
original_tag: Tag = original_file.get_tag()
no_drums_audiofile = eyed3.load(str(no_drums_path))
no_drums_audiofile.tag = original_tag
no_drums_audiofile.tag.title = f"{original_tag.title} (No Drums)"
no_drums_audiofile.tag.save(version=ID3_V2_4)
except Exception:
print(f"Failed to get the tag for {no_drums_path} - skipping!")
no_drums_path.unlink()
return False
return True
def main(src_in: str, dest_in: str) -> None:
"""
Traverses all files in the provided source directory, replicating the directory format in \
the destination directory and moving the converted file to match suit.
Also ensures that metadata is copied from the old file to the new one to provide the best user experience in the end
Args:
src_in (str): The source directory to traverse and convert
dest_in (str): The destination directory which will mirror the source, but with tracks that have no drums
"""
src: Path = Path(src_in)
dest: Path = Path(dest_in)
if not src.exists():
raise Exception("Input directory does not exist!")
for root, _, files in os.walk(src):
for file in files:
original_path = Path(root).joinpath(file)
if original_path.suffix not in SUPPORTED_EXTS:
print(f"File {file} has an unsupported extension.")
continue
# Create a "MusicFile" from the full path of the original file
original_file = MusicFile(original_path)
# Gets the output file of drumless music
no_drums_path = original_file.separate()
# If metadata cloning fails, skip the file.
if not copy_metadata(original_file, no_drums_path):
continue
# Replace the input destination with the output destination
file_output_root = root.replace(str(src), str(dest))
file_output_root = Path(file_output_root).resolve()
# We also need to replace the original {file} extension with .mp3
filename_with_mp3_ext = f"{Path(file).stem}.mp3"
file_dest = file_output_root.joinpath(filename_with_mp3_ext)
# Make the output subdir(s) and move the no-drums file from the temp output to the final destination
os.makedirs(file_output_root, exist_ok=True)
shutil.move(no_drums_path, file_dest)
# Remove the model output since we don't need it anymore
if os.path.exists(MODEL_NAME):
shutil.rmtree(MODEL_NAME)
if __name__ == "__main__":
if len(sys.argv) == 3:
main(sys.argv[1], sys.argv[2])

View file

@ -1,105 +0,0 @@
import eyed3
import sys
from pathlib import Path
import shutil
from eyed3.id3 import ID3_V2_4
from eyed3.id3 import Tag
from tinytag import TinyTag
def get_m4a_tag(orig_path: Path) -> Tag:
"""
Creates a new eyed3 Tag object from an m4a tag which is not natively supported
This implementation is based off of TinyTag's m4a support
"""
tag = TinyTag.get(orig_path)
ret = Tag(version=ID3_V2_4)
ret.album = tag.album
ret.album_artist = tag.albumartist
ret.artist = tag.artist
ret.composer = tag.composer
ret.disc_num = (int(tag.disc), int(tag.disc_total))
ret.genre = tag.genre
ret.title = tag.title
ret.track_num = (int(tag.track), int(tag.track_total))
ret.release_date = tag.year
return ret
def main(root: str):
"""
Iterates over all files in 'root' and copies the ID3 tags from the original
files to the new files now that the drum parts have been split so that
the metadata propagates correctly in foobar/iTunes/iPods everywhere
Meant to be run **AFTER** running 'run_folder.sh' and
is intended to be used with the same argument as that script.
"""
resolved_root = Path(root).resolve()
for filename in resolved_root.iterdir():
orig_path = resolved_root.joinpath(filename)
if not orig_path.exists():
print(f"No orig_path {orig_path} exists, skipping")
continue
without_drums_path = (
Path("./separated/htdemucs")
.resolve()
.joinpath(orig_path.stem)
.joinpath("no_drums.mp3")
)
if not without_drums_path.exists():
print(f"No without_drums_path {without_drums_path} exists, skipping")
continue
just_drums_path = (
Path("./separated/htdemucs")
.resolve()
.joinpath(orig_path.stem)
.joinpath("drums.mp3")
)
if not just_drums_path.exists():
print(f"No just_drums_path {just_drums_path} exists, skipping")
continue
# orig_afile = eyed3.load(str(orig_path))
original_tag: Tag = eyed3.load(str(orig_path)).tag if not orig_path.suffix.endswith('m4a') else get_m4a_tag(orig_path)
# Copy over the metadata from the original song to the one without drums
without_drums_afile = eyed3.load(str(without_drums_path))
without_drums_afile.tag = original_tag
without_drums_afile.tag.title = f"{original_tag.title} (No Drums)"
without_drums_afile.tag.save(version=ID3_V2_4)
# Reload the original audio file to make sure we revert any changes to the tag
original_tag: Tag = eyed3.load(str(orig_path)).tag if not orig_path.suffix.endswith('m4a') else get_m4a_tag(orig_path)
# Same for the one that's _JUST_ drums
just_drums_afile = eyed3.load(str(just_drums_path))
just_drums_afile.tag = original_tag
just_drums_afile.tag.title = f"{original_tag.title} (Just Drums)"
just_drums_afile.tag.save(version=ID3_V2_4)
# Now we want to move the files to a version
shutil.move(
without_drums_path,
without_drums_path.joinpath("..")
.joinpath(f"{without_drums_afile.tag.title}.mp3")
.resolve(),
)
shutil.move(
just_drums_path,
just_drums_path.joinpath("..")
.joinpath(f"{just_drums_afile.tag.title}.mp3")
.resolve(),
)
if __name__ == "__main__":
if len(sys.argv) == 2:
main(sys.argv[1])

124
music_file.py Normal file
View file

@ -0,0 +1,124 @@
"""
@author: Jose Stovall | github.com/oitsjustjose | bsky||@oitsjustjose.com
"""
import os
from pathlib import Path
import eyed3
from demucs.separate import main as Separate
from eyed3.id3 import ID3_V2_4, Tag
from tinytag import TinyTag
from wavinfo import WavInfoReader
MODEL_NAME = "htdemucs_ft"
class MusicFile:
def __init__(self, path: Path):
"""A music file wrapper for most containers
Args:
path (Path): The path of the music file
"""
self.__p = path
def separate(self) -> Path:
"""_summary_
Returns:
Path: _description_
"""
Separate(
[
"--mp3", # Saves the output file to MP3 format
"--two-stems", # Defines two stems, {stem}.mp3 and no_{stem}.mp3
"drums", # {stem} as declared above
"--jobs", # Multitasking where possible
f"{os.cpu_count() or 2}", # Try to get it dynamically, fall back to 2
"--out", # Sets the subfolder to save stems to ({ModelName}/{--out}/{stem}.mp3)
"", # Fix it to empty string for easier automation
"--filename", # Set the file format for easier automation
"{stem}.{ext}", # Again, easier to automate "drums.mp3" than others..
"--name", # Model Name -- including this prevents output spam and removes unpredictability
MODEL_NAME, # Fine tuned model is slower but sounds noticeably, but slightly, better. Remove _ft to speed up
f"{str(self.__p.resolve())}",
]
)
drums = Path(MODEL_NAME).joinpath("drums.mp3")
no_drums = Path(MODEL_NAME).joinpath("no_drums.mp3")
if os.path.exists(drums):
os.unlink(drums)
return no_drums.resolve()
def get_tag(self) -> Tag:
"""Attempts to get the ID3 V2.4 Tag from the music file
Raises:
Exception: Thrown if the container for the file is not supported
Returns:
Tag: The ID3 V2.4 metadata tag from the music file contained
"""
if self.__p.suffix == ".mp3":
return self.__get_mp3_tag()
if self.__p.suffix == ".m4a":
return self.__get_m4a_tag()
if self.__p.suffix == ".wav":
return self.__get_wav_tag()
raise Exception(f"Failed to determine tag type for {self.__p}")
def __get_m4a_tag(self) -> Tag:
"""
Creates a new eyed3 Tag object from an m4a tag which is not natively supported
This implementation is based off of TinyTag's m4a support
"""
tag = TinyTag.get(str(self.__p))
ret = Tag(version=ID3_V2_4)
disc: int = int(tag.disc or 0)
disc_total: int = int(tag.disc_total or 0)
track: int = int(tag.track or 0)
track_total: int = int(tag.track_total or 0)
ret.album = tag.album
ret.album_artist = tag.albumartist
ret.artist = tag.artist
ret.composer = tag.composer
ret.disc_num = (disc, disc_total)
ret.genre = tag.genre
ret.title = tag.title
ret.track_num = (track, track_total)
ret.release_date = tag.year
return ret
def __get_wav_tag(self) -> Tag:
"""Gets the tag for a wav file based off of WavInfo's impl"""
tag = WavInfoReader(str(self.__p))
ret = Tag(version=ID3_V2_4)
ret.album = tag.info.album
ret.album_artist = tag.info.artist
ret.artist = tag.info.artist
ret.genre = tag.info.genre
ret.title = tag.info.title
ret.release_date = tag.info.created_date
return ret
def __get_mp3_tag(self) -> Tag:
"""
Gets or creates a tag from the given file path. If the tag fails to be created,
an empty tag is made and returned
"""
audio_file = eyed3.load(str(self.__p))
if not audio_file:
print(f"Failed to load tag from file {self.__p} -- returning empty tag")
return Tag(version=ID3_V2_4)
return audio_file.tag

View file

@ -1,22 +1,63 @@
antlr4-python3-runtime==4.9.3
astroid==3.2.4
black==24.8.0
click==8.1.7
cloudpickle==3.1.1
coverage==5.5
demucs==4.0.1
deprecation==2.1.0
dill==0.3.9
dora_search==0.1.12
einops==0.8.0
eyed3==0.9.7
filelock==3.17.0
filetype==1.2.0
fsspec==2025.2.0
isort==5.13.2
Jinja2==3.1.5
julius==0.2.7
lameenc==1.8.1
lxml==5.3.0
MarkupSafe==3.0.2
mccabe==0.7.0
mpmath==1.3.0
mypy-extensions==1.0.0
networkx==3.4.2
numpy==2.2.2
nvidia-cublas-cu12==12.4.5.8
nvidia-cuda-cupti-cu12==12.4.127
nvidia-cuda-nvrtc-cu12==12.4.127
nvidia-cuda-runtime-cu12==12.4.127
nvidia-cudnn-cu12==9.1.0.70
nvidia-cufft-cu12==11.2.1.3
nvidia-curand-cu12==10.3.5.147
nvidia-cusolver-cu12==11.6.1.9
nvidia-cusparse-cu12==12.3.1.170
nvidia-cusparselt-cu12==0.6.2
nvidia-nccl-cu12==2.21.5
nvidia-nvjitlink-cu12==12.4.127
nvidia-nvtx-cu12==12.4.127
omegaconf==2.3.0
openunmix==1.3.0
packaging==24.1
pathspec==0.12.1
platformdirs==4.3.6
pylint==3.2.7
pytoolconfig==1.3.1
PyYAML==6.0.2
retrying==1.3.4
rope==1.13.0
six==1.17.0
submitit==1.5.2
sympy==1.13.1
tinytag==1.10.1
toml==0.10.2
tomli==2.0.2
tomlkit==0.13.2
typing-extensions==4.12.2
torch==2.6.0
torchaudio==2.6.0
tqdm==4.67.1
treetable==0.2.5
triton==3.2.0
typing_extensions==4.12.2
wavinfo==3.1.0

View file

@ -1,10 +0,0 @@
#!/bin/bash
SOURCE_PATH="$(realpath $1)"
echo "Working through files in $SOURCE_PATH"
for filename in "$SOURCE_PATH"/*; do
sudo python3 -m demucs --mp3 --two-stems=drums "$filename";
done
sudo chown "$USER" -R ./separated