File prep for GUI

This commit is contained in:
oitsjustjose 2025-03-22 12:03:34 -05:00
commit 2707eac861
8 changed files with 244 additions and 102 deletions

1
.gitignore vendored
View file

@ -1,3 +1,4 @@
/.venv
/Python
/input
/output

88
main.py
View file

@ -1,88 +0,0 @@
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])

Binary file not shown.

19
src/cli.py Normal file
View file

@ -0,0 +1,19 @@
import sys
from src.messaging import CliOutput
from src.processor import FolderProcessor
if __name__ == "__main__":
output = CliOutput()
if len(sys.argv) == 3:
processor = FolderProcessor(sys.argv[1], sys.argv[2], output)
processor.process_directory()
else:
warning_str = [
"The CLI utility requires exactly two parameters:",
" • input [str] -- The directory to scan through",
" • output [str] -- The directory to output through, keeping the input directory's file structure.",
" (This directory will be made if necessary)",
]
output.error("\n".join(warning_str))

0
src/gui.py Normal file
View file

96
src/messaging.py Normal file
View file

@ -0,0 +1,96 @@
import logging
import os
import sys
class NoPrintStatements:
"""
Use in a with block to disable print statemenets within that scope
Source: https://stackoverflow.com/a/45669280
"""
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._original_stdout
class MessageInterface:
def info(input: any):
"""Displays an informational message to the preferred output method of choice
Args:
input (any): The input to display to the user (will be wrapped into a string)
"""
raise "Cannot call base class!"
def warning(input: any):
"""Displays a warning message to the preferred output method of choice
Args:
input (any): The input to display to the user (will be wrapped into a string)
"""
raise "Cannot call base class!"
def error(input: any):
"""Displays an error message to the preferred output method of choice
Args:
input (any): The input to display to the user (will be wrapped into a string)
"""
raise "Cannot call base class!"
class CustomFormatter(logging.Formatter):
"""
A logging colorator
Source: https://stackoverflow.com/a/56944256
"""
grey = "\x1b[38;20m"
info = "\x1b[32;20m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
format = "[%(levelname)s] - %(message)s"
FORMATS = {
logging.DEBUG: grey + format + reset,
logging.INFO: info + format + reset,
logging.WARNING: yellow + format + reset,
logging.ERROR: red + format + reset,
logging.CRITICAL: bold_red + format + reset,
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
class CliOutput(MessageInterface):
def __init__(self):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(CustomFormatter())
self.logger.addHandler(ch)
def info(self, input):
self.logger.info(f"{input}")
def warning(self, input):
self.logger.warning(f"{input}")
def error(self, input):
self.logger.error(f"{input}")
class GuiOutput(MessageInterface):
# TODO: this is a stub
pass

View file

@ -12,7 +12,8 @@ from tinytag import TinyTag
from wavinfo import WavInfoReader
MODEL_NAME = "htdemucs_ft"
MODEL_NAME = "htdemucs" # "htdemucs_ft"
SUPPORTED_EXTS = [".mp3", ".m4a", ".wav"]
class MusicFile:
@ -22,7 +23,7 @@ class MusicFile:
Args:
path (Path): The path of the music file
"""
self.__p = path
self.file_path = path
def separate(self) -> Path:
"""_summary_
@ -43,15 +44,15 @@ class MusicFile:
"{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())}",
f"{str(self.file_path.resolve())}",
]
)
drums = Path(MODEL_NAME).joinpath("drums.mp3")
just_drums = Path(MODEL_NAME).joinpath("drums.mp3")
no_drums = Path(MODEL_NAME).joinpath("no_drums.mp3")
if os.path.exists(drums):
os.unlink(drums)
if os.path.exists(just_drums):
os.unlink(just_drums)
return no_drums.resolve()
@ -64,20 +65,20 @@ class MusicFile:
Returns:
Tag: The ID3 V2.4 metadata tag from the music file contained
"""
if self.__p.suffix == ".mp3":
if self.file_path.suffix == ".mp3":
return self.__get_mp3_tag()
if self.__p.suffix == ".m4a":
if self.file_path.suffix == ".m4a":
return self.__get_m4a_tag()
if self.__p.suffix == ".wav":
if self.file_path.suffix == ".wav":
return self.__get_wav_tag()
raise Exception(f"Failed to determine tag type for {self.__p}")
raise Exception(f"Failed to determine tag type for {self.file_path}")
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))
tag = TinyTag.get(str(self.file_path))
ret = Tag(version=ID3_V2_4)
@ -100,7 +101,7 @@ class MusicFile:
def __get_wav_tag(self) -> Tag:
"""Gets the tag for a wav file based off of WavInfo's impl"""
tag = WavInfoReader(str(self.__p))
tag = WavInfoReader(str(self.file_path))
ret = Tag(version=ID3_V2_4)
ret.album = tag.info.album
@ -117,8 +118,10 @@ class MusicFile:
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))
audio_file = eyed3.load(str(self.file_path))
if not audio_file:
print(f"Failed to load tag from file {self.__p} -- returning empty tag")
print(
f"Failed to load tag from file {self.file_path} -- returning empty tag"
)
return Tag(version=ID3_V2_4)
return audio_file.tag

111
src/processor.py Normal file
View file

@ -0,0 +1,111 @@
import os
import shutil
from pathlib import Path
import eyed3
from eyed3.id3 import ID3_V2_4, Tag
from src.music_file import MODEL_NAME, SUPPORTED_EXTS, MusicFile
from src.messaging import MessageInterface, NoPrintStatements
class FolderProcessor:
def __init__(
self, input_dir: str, output_dir: str, msg_interface: MessageInterface
):
"""_summary_
Args:
input_dir (str): The source directory to traverse and convert
output_dir (str): The destination directory which will mirror the source, but with tracks that have no drums
msg_interface (MessageInterface): The handler for displaying output to the user
"""
self.input_dir: str = input_dir
self.output_dir: str = output_dir
self.msg_interface: MessageInterface = msg_interface
def process_directory(self) -> 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
"""
src: Path = Path(self.input_dir)
dest: Path = Path(self.output_dir)
cur_dir: Path = Path(".").resolve() # Used just for logging
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:
self.msg_interface.warning(
f"File {original_path.name} has an unsupported extension and will be skipped!"
)
continue
# Create a "MusicFile" from the full path of the original file
original_file = MusicFile(original_path)
self.msg_interface.info(
f"Splitting drum tracks from {original_path.name}:"
)
# Get the output file of drumless music
with NoPrintStatements(): # Prevent print statements from demucs
no_drums_path = original_file.separate()
# If metadata cloning fails, skip the file.
if not self.__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)
self.msg_interface.info(
f"Done processing {original_path.name} and relocated it to {file_dest.relative_to(cur_dir)}!"
)
# Remove the model output since we don't need it anymore
if os.path.exists(MODEL_NAME):
shutil.rmtree(MODEL_NAME)
def __copy_metadata(self, 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:
self.msg_interface.info(
f"Copying Metadata from {original_file.file_path.name} to {no_drums_path.name}"
)
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:
self.msg_interface.warning(
f"Failed to get the tag for {no_drums_path.name} - skipping!"
)
no_drums_path.unlink()
return False
return True