This commit is contained in:
oitsjustjose 2025-03-30 14:37:22 -05:00
commit a8f88df4b7
4 changed files with 213 additions and 129 deletions

View file

@ -1,29 +1,70 @@
import sys
from argparse import ArgumentParser, RawTextHelpFormatter
from colorama import Fore
from src.messaging import CliOutput
from src.processor import FolderProcessor
from src.music_file import MODEL_CHOICES
from src.processor import FolderProcessor
def __get_parser() -> ArgumentParser:
"""Creates an arg parser for the program. Abstracted away because it's ugly like always
Returns:
ArgumentParser: The created and configured arg parser.
"""
model_choices = "\n • ".join(
# Padding in the array so the first entry starts on a newline with bullet
[""]
+ [
f"{Fore.GREEN}{MODEL_CHOICES[desc]}{Fore.RESET} - {desc}"
for desc in MODEL_CHOICES
]
)
parser = ArgumentParser(
prog="Drum Track Converter",
description="Removes the drum tracks from [almost] any song using Demucs",
formatter_class=RawTextHelpFormatter,
)
parser.add_argument(
"input_dir", help="The directory to scan for files. Scans recursively."
)
parser.add_argument(
"output_dir",
help="The directory to output drumless tracks to. Folder structure is preserved from the input.",
)
parser.add_argument(
"-m",
"--model",
help=f"What model to use. Options include: {model_choices}",
default=list(MODEL_CHOICES.values())[0],
)
parser.add_argument(
"-v",
"--verbose",
help="Show verbose print statements",
action="store_true",
default=False,
)
return parser
if __name__ == "__main__":
output = CliOutput()
logger = CliOutput()
args = __get_parser().parse_args()
if len(sys.argv) >= 3:
## TODO: CLI argparse -- this is getting messy...
model_name = (
sys.argv[3] if len(sys.argv) >= 4 else list(MODEL_CHOICES.values())[0]
)
processor = FolderProcessor(
sys.argv[1],
sys.argv[2],
output,
)
try:
processor = FolderProcessor.from_args(args, logger)
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))
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
logger.error(e)

View file

@ -1,9 +1,10 @@
import platform
import sys
from multiprocessing import Process
from pathlib import Path
from typing import Callable
from typing import Callable, List
from PySide6.QtCore import QThread
from PySide6.QtCore import QObject, Signal
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import (
QApplication,
@ -25,31 +26,116 @@ from src.processor import FolderProcessor
APP_ID = "com.oitsjustjose.drum-track-converter"
class DataBackend:
def __init__(self):
# Variables for the actual processing flow
self.input_dir: str = ""
self.output_dir: str = ""
self.model_name: str = list(MODEL_CHOICES.values())[0]
self.worker: Worker = None
self._child_proc: Process = None
class MainWindow(QMainWindow):
def __init__(self, icon: QIcon):
def __init__(self):
super().__init__()
self.setWindowIcon(icon)
# Widgets that we'll want to set throughout the runtime
# Widgets that we'll want to set & mutate throughout the runtime
self.start_button: QPushButton = None
self.logging_region: QTextEdit = None
self.interactive_elements: List[QWidget] = list()
self.setWindowTitle("Drum Track Converter by oitsjustjose")
self.__setup_layout()
self.__center()
# Set fixed size only once we've established the contents of the window
self.setMaximumSize(self.size())
# Handle data separately from the GUI
self.data_backend = DataBackend()
# Variables for the actual processing flow
self.input_dir: str = ""
self.output_dir: str = ""
self.model_name: str = list(MODEL_CHOICES.values())[0]
self._thread: OffThreadProcessor = None
def on_input_clicked(self, button_ref: QPushButton):
"""Sets the output directory to the selected value from a QFileDialog
Mutates the button_ref's text to reflect the selected folder
If Input and Output are set, enables the Start button
Args:
button_ref (QPushButton): A reference to the button pressed
"""
self.input_dir = QFileDialog.getExistingDirectory(None, "Select Input Folder")
self.__common_io_clicked(button_ref, self.input_dir)
def on_output_clicked(self, button_ref: QPushButton):
"""Sets the output directory to the selected value from a QFileDialog
Mutates the button_ref's text to reflect the selected folder
If Input and Output are set, enables the Start button
Args:
button_ref (QPushButton): A reference to the button pressed
"""
self.output_dir = QFileDialog.getExistingDirectory(None, "Select Output Folder")
self.__common_io_clicked(button_ref, self.output_dir)
def on_model_changed(self, model_display_name: str) -> None:
"""Sets the model_name to the new model_name based on the display name
Args:
model_display_name (str): The display name of the model
"""
self.model_name = MODEL_CHOICES[model_display_name]
def on_start_clicked(self):
"""Passes through basic assertions, spins up thread to process files from the input and output params"""
if not (self.input_dir and self.output_dir):
return
self.logging_region.setVisible(True)
[x.setEnabled(False) for x in self.interactive_elements]
self.worker = Worker(
FolderProcessor(
self.input_dir,
self.output_dir,
self.model_name,
GuiOutput(self),
)
)
self.worker.finished.connect(self.on_done)
self._child_proc = Process(target=self.worker.run)
self._child_proc.start()
def on_done(self, message: str):
# Reset State
self._child_proc.join(0)
self.worker.finished.disconnect()
self.worker = None
self.logging_region.append(message)
self.start_button.setText("Start")
[x.setEnabled(False) for x in self.interactive_elements]
def stop(self):
"""Stops the working thread (if it's been started) at its soonest convenience..."""
if self._child_proc:
self._child_proc.terminate()
self._child_proc.join(0)
"""~~Hidden / private methods~~"""
def __get_state__(self) -> dict:
state = self.__dict__.copy()
# TODO: delete any unpicklable entries
# del state['f'] --
return state
def __setstate__(self, state: dict):
self.__dict__.update(state)
# TODO: restore any unpicklable entries
# self.f = # manual parsing
def __center(self) -> None:
"""Centers the window to the middle of the Screen"""
# Center window
frame_geo = self.frameGeometry()
center = self.screen().availableGeometry().center()
frame_geo.moveCenter(center)
@ -65,12 +151,21 @@ class MainWindow(QMainWindow):
def __setup_children(self):
"""Sets up the children of the main window element using [nested] HBox and VBox layouts"""
# Start Button
self.start_button = QPushButton("Start")
self.start_button.setEnabled(False)
self.start_button.adjustSize()
self.start_button.clicked.connect(self.on_start_clicked)
# These should stay in the same order as intended visually, so smaller index = closer to top.
# These elements will all be disabled/enabled as the process starts & stops
self.interactive_elements = [
self.__make_io_buttons(),
self.__make_model_combobox(),
self.start_button,
]
# Logging region appears automatically
self.logging_region = QTextEdit()
self.logging_region.setReadOnly(True)
@ -78,9 +173,7 @@ class MainWindow(QMainWindow):
self.logging_region.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap)
# Add all children to the parent layout
self.layout.addWidget(self.__make_io_buttons())
self.layout.addWidget(self.__make_model_combobox())
self.layout.addWidget(self.start_button)
[self.layout.addWidget(x) for x in self.interactive_elements]
self.layout.addWidget(self.logging_region)
def __make_io_buttons(self) -> QWidget:
@ -184,86 +277,23 @@ class MainWindow(QMainWindow):
enabled = bool(self.input_dir and self.output_dir)
self.start_button.setEnabled(enabled)
def on_input_clicked(self, button_ref: QPushButton):
"""Sets the output directory to the selected value from a QFileDialog
Mutates the button_ref's text to reflect the selected folder
If Input and Output are set, enables the Start button
Args:
button_ref (QPushButton): A reference to the button pressed
"""
self.input_dir = QFileDialog.getExistingDirectory(None, "Select Input Folder")
self.__common_io_clicked(button_ref, self.input_dir)
class Worker(QObject):
finished = Signal(str, name="on_worker_finished")
def on_output_clicked(self, button_ref: QPushButton):
"""Sets the output directory to the selected value from a QFileDialog
Mutates the button_ref's text to reflect the selected folder
If Input and Output are set, enables the Start button
def __init__(self, processor: FolderProcessor):
super().__init__()
self.processor = processor
Args:
button_ref (QPushButton): A reference to the button pressed
"""
self.output_dir = QFileDialog.getExistingDirectory(None, "Select Output Folder")
self.__common_io_clicked(button_ref, self.output_dir)
def __reduce__(self):
return (Worker, (self.processor,))
def on_model_changed(self, model_display_name: str) -> None:
"""Sets the model_name to the new model_name based on the display name
Args:
model_display_name (str): The display name of the model
"""
self.model_name = MODEL_CHOICES[model_display_name]
def on_start_clicked(self):
"""Passes through basic assertions, spins up thread to process files from the input and output params"""
assert bool(self.input_dir and self.output_dir)
# Only join once we're good to go again, there's really no harm in keeping the other thread around
if self._thread and not self._thread.isRunning():
self._thread.join()
self._thread = None
self.start_button.setEnabled(False)
self.start_button.setText("Processing...")
self.logging_region.setVisible(True)
self._thread = OffThreadProcessor(self)
self._thread.start()
def stop_thread(self):
"""Stops the working thread (if it's been started) at its soonest convenience..."""
if not self._thread:
return
self._thread.stop()
self._thread.deleteLater()
self._thread = None
class OffThreadProcessor(QThread):
def __init__(self, parent: MainWindow):
super().__init__(parent)
self.main_window: MainWindow = parent
self.setTerminationEnabled(True)
self.gui_output = GuiOutput(self.main_window)
self.processor = FolderProcessor(
parent.input_dir, parent.output_dir, self.gui_output, parent.model_name
)
def run(self) -> None:
def run(self):
try:
self.processor.process_directory()
# All of this occurs here instead of on_start_clicked to keep the main GUI from being blocked on the join
self.main_window.logging_region.append("✅ Done!")
self.main_window.start_button.setText("Start")
self.main_window.start_button.setEnabled(True)
self.finished.emit("✅ Done!")
except Exception as e:
self.processor.msg_interface.error(f"Failed: {e}")
def stop(self) -> None:
self.terminate()
self.finished.emit(f"Failed: {e}")
class GuiOutput(MessageInterface):
@ -299,10 +329,10 @@ def main() -> None:
icon.addFile("assets/icon.ico")
app.setWindowIcon(icon)
window = MainWindow(icon)
window = MainWindow()
window.show()
exit_code = app.exec()
window.stop_thread()
window.stop()
sys.exit(exit_code)

View file

@ -9,11 +9,20 @@ class NoPrintStatements:
Source: https://stackoverflow.com/a/45669280
"""
def __init__(self, verbose: bool):
self.verbose = verbose
def __enter__(self):
if self.verbose:
return
self._original_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
def __exit__(self, exc_type, exc_val, exc_tb):
if self.verbose:
return
sys.stdout.close()
sys.stdout = self._original_stdout

View file

@ -2,12 +2,13 @@ import os
import shutil
import subprocess
from pathlib import Path
from argparse import Namespace as argset
import eyed3
from eyed3.id3 import ID3_V2_4, Tag
from src.messaging import MessageInterface, NoPrintStatements
from src.music_file import SUPPORTED_EXTS, MusicFile
from src.music_file import SUPPORTED_EXTS, MODEL_CHOICES, MusicFile
class FolderProcessor:
@ -15,21 +16,34 @@ class FolderProcessor:
self,
input_dir: str,
output_dir: str,
msg_interface: MessageInterface,
model_name: str,
msg_interface: MessageInterface,
verbose: bool = False,
):
"""_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
model_name (str): The name of the Demucs model to use for splitting tracks
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
self.model_name = model_name
self.should_stop = False
self.verbose: bool = verbose
@classmethod
def from_args(self, args: argset, msg_interface: MessageInterface):
"""Creates a FolderProcessor instance using an argparse argument set
Args:
args (argset): Arguments from the CLI
msg_interface (MessageInterface): The handler for displaying output to the user
"""
return FolderProcessor(
args.input_dir, args.output_dir, args.model, msg_interface, args.verbose
)
def _is_ffmpeg_present(self) -> bool:
"""Determines if ffmpeg is installed and accessible
@ -46,10 +60,6 @@ class FolderProcessor:
except FileNotFoundError:
return False
def quit(self) -> None:
"""Tells the ongoing process to quit on next iteration"""
self.should_stop = True
def process_directory(self) -> None:
"""
Traverses all files in the provided source directory, replicating the directory format in \
@ -82,11 +92,10 @@ class FolderProcessor:
original_file = MusicFile(original_path, self.model_name)
self.msg_interface.info(
f"Splitting drum tracks from {original_path.name}:"
f"Splitting drum tracks from {original_path.name} using {list(MODEL_CHOICES.keys())[list(MODEL_CHOICES.values()).index(self.model_name)]}:"
)
# Get the output file of drumless music
with NoPrintStatements(): # Prevent print statements from demucs
with NoPrintStatements(self.verbose):
no_drums_path = original_file.separate()
# If metadata cloning fails, skip the file.
@ -107,11 +116,6 @@ class FolderProcessor:
f"Done processing {original_path.name} and relocated it to {file_dest.relative_to(cur_dir)}!"
)
if self.should_stop:
break
if self.should_stop:
break
# Remove the model output since we don't need it anymore
if os.path.exists(self.model_name):
shutil.rmtree(self.model_name)