From 2707eac861b25063ef7c7ee0853f933224076aab Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Sat, 22 Mar 2025 12:03:34 -0500 Subject: [PATCH] File prep for GUI --- .gitignore | 1 + main.py | 88 ----------------------- requirements.txt | Bin 1189 -> 1798 bytes src/cli.py | 19 +++++ src/gui.py | 0 src/messaging.py | 96 +++++++++++++++++++++++++ music_file.py => src/music_file.py | 31 ++++---- src/processor.py | 111 +++++++++++++++++++++++++++++ 8 files changed, 244 insertions(+), 102 deletions(-) delete mode 100644 main.py create mode 100644 src/cli.py create mode 100644 src/gui.py create mode 100644 src/messaging.py rename music_file.py => src/music_file.py (83%) create mode 100644 src/processor.py diff --git a/.gitignore b/.gitignore index cedaf31..aa5f5ba 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +/.venv /Python /input /output diff --git a/main.py b/main.py deleted file mode 100644 index 63ea353..0000000 --- a/main.py +++ /dev/null @@ -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]) diff --git a/requirements.txt b/requirements.txt index 17a8c8641bb9b12d12acb40efd3412cf4c575356..94e4ca8d3f9abef9f80fe8cd894e3231da2a990e 100644 GIT binary patch literal 1798 zcmZux%Wm615Sw#>eoBf+cAVyrL$5^xwCJg)K(^P;M%JU2lGH!nmKQi;(e{q7 zfR%XGj&D)9vYpkAm7e_>=(VFepm9d|zQA)kV;#Eh!AUWvi2*w>u9)IFRO!H>0>{ex zTmvP~%^dNHTt*zH8aF_19NpthgFZVbN&1+t>O^~F2H+KxMt6pB)JPUmvIla)hX}LD z@ouUwZjY!RP~(hBPjj4flpYySqecCGV!}G|giZ%cCcur=oXaW5tAlqB?nClgE@iJ% z%!oQYDv>F>Q-?Gh(06cb=V*!dC0vpk#Y99<&*%}v3fC$HU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ev/null +++ b/src/cli.py @@ -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)) diff --git a/src/gui.py b/src/gui.py new file mode 100644 index 0000000..e69de29 diff --git a/src/messaging.py b/src/messaging.py new file mode 100644 index 0000000..49b2c7f --- /dev/null +++ b/src/messaging.py @@ -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 diff --git a/music_file.py b/src/music_file.py similarity index 83% rename from music_file.py rename to src/music_file.py index 8934329..7e6e66a 100644 --- a/music_file.py +++ b/src/music_file.py @@ -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 diff --git a/src/processor.py b/src/processor.py new file mode 100644 index 0000000..9ab6545 --- /dev/null +++ b/src/processor.py @@ -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