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

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

127
src/music_file.py Normal file
View file

@ -0,0 +1,127 @@
"""
@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" # "htdemucs_ft"
SUPPORTED_EXTS = [".mp3", ".m4a", ".wav"]
class MusicFile:
def __init__(self, path: Path):
"""A music file wrapper for most containers
Args:
path (Path): The path of the music file
"""
self.file_path = 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.file_path.resolve())}",
]
)
just_drums = Path(MODEL_NAME).joinpath("drums.mp3")
no_drums = Path(MODEL_NAME).joinpath("no_drums.mp3")
if os.path.exists(just_drums):
os.unlink(just_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.file_path.suffix == ".mp3":
return self.__get_mp3_tag()
if self.file_path.suffix == ".m4a":
return self.__get_m4a_tag()
if self.file_path.suffix == ".wav":
return self.__get_wav_tag()
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.file_path))
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.file_path))
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.file_path))
if not audio_file:
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