Massively improved model handling, dropdown options

This commit is contained in:
oitsjustjose 2025-03-29 20:37:52 -05:00
commit b8ae1a6cf1
4 changed files with 175 additions and 63 deletions

View file

@ -2,12 +2,22 @@ import sys
from src.messaging import CliOutput from src.messaging import CliOutput
from src.processor import FolderProcessor from src.processor import FolderProcessor
from src.music_file import MODEL_CHOICES
if __name__ == "__main__": if __name__ == "__main__":
output = CliOutput() output = CliOutput()
if len(sys.argv) == 3: if len(sys.argv) >= 3:
processor = FolderProcessor(sys.argv[1], sys.argv[2], output) ## 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,
)
processor.process_directory() processor.process_directory()
else: else:
warning_str = [ warning_str = [

View file

@ -1,9 +1,11 @@
import sys import sys
from pathlib import Path
from typing import Callable from typing import Callable
from PyQt6.QtCore import QThread from PySide6.QtCore import QThread
from PyQt6.QtWidgets import ( from PySide6.QtWidgets import (
QApplication, QApplication,
QComboBox,
QFileDialog, QFileDialog,
QHBoxLayout, QHBoxLayout,
QLabel, QLabel,
@ -15,6 +17,7 @@ from PyQt6.QtWidgets import (
) )
from src.messaging import MessageInterface from src.messaging import MessageInterface
from src.music_file import MODEL_CHOICES
from src.processor import FolderProcessor from src.processor import FolderProcessor
@ -29,11 +32,14 @@ class MainWindow(QMainWindow):
self.setWindowTitle("Drum Track Converter by oitsjustjose") self.setWindowTitle("Drum Track Converter by oitsjustjose")
self.__setup_layout() self.__setup_layout()
self.__center() self.__center()
# Set fixed size only once we've established the contents of the window
self.setMaximumSize(self.size())
# Variables for the actual processing flow # Variables for the actual processing flow
self.input_dir: str = "" self.input_dir: str = ""
self.output_dir: str = "" self.output_dir: str = ""
self._thread: QThread = None self.model_name: str = list(MODEL_CHOICES.values())[0]
self._thread: OffThreadProcessor = None
def __center(self) -> None: def __center(self) -> None:
"""Centers the window to the middle of the Screen""" """Centers the window to the middle of the Screen"""
@ -53,6 +59,30 @@ class MainWindow(QMainWindow):
def __setup_children(self): def __setup_children(self):
"""Sets up the children of the main window element using [nested] HBox and VBox layouts""" """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)
# Logging region appears automatically
self.logging_region = QTextEdit()
self.logging_region.setReadOnly(True)
self.logging_region.setVisible(False)
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(self.logging_region)
def __make_io_buttons(self) -> QWidget:
"""Makes the Input and Output Folder Buttons
Returns:
QWidget: The VBox widget created
"""
def create_io_button_group( def create_io_button_group(
self: MainWindow, label_text: str, on_click: Callable self: MainWindow, label_text: str, on_click: Callable
@ -74,7 +104,7 @@ class MainWindow(QMainWindow):
label = self.__create_label(label_text) label = self.__create_label(label_text)
button = QPushButton("Choose Folder...") button = QPushButton("Choose Folder...")
button.clicked.connect(on_click) button.clicked.connect(lambda: on_click(button))
layout.addWidget(label) layout.addWidget(label)
layout.addWidget(button) layout.addWidget(button)
@ -83,31 +113,40 @@ class MainWindow(QMainWindow):
return vbox return vbox
# Input and Output directory items # Input and Output directory items
io_btns = QWidget() widget = QWidget()
io_btns_layout = QHBoxLayout() layout = QHBoxLayout()
io_btns_layout.addWidget( layout.addWidget(
create_io_button_group(self, "Select Input Folder", self.on_input_clicked) create_io_button_group(self, "Select Input Folder", self.on_input_clicked)
) )
io_btns_layout.addWidget( layout.addWidget(
create_io_button_group(self, "Select Output Folder", self.on_output_clicked) create_io_button_group(self, "Select Output Folder", self.on_output_clicked)
) )
io_btns.setLayout(io_btns_layout) widget.setLayout(layout)
return widget
# Start Button def __make_model_combobox(self) -> QWidget:
self.start_button = QPushButton("Start") """Makes a Combobox to choose which demucs model to use
self.start_button.setEnabled(False)
self.start_button.adjustSize()
self.start_button.clicked.connect(self.on_start_clicked)
# Logging region appears automatically Returns:
self.logging_region = QTextEdit() QWidget: The VBox widget created
self.logging_region.setReadOnly(True) """
self.logging_region.setVisible(False) widget = QWidget()
self.logging_region.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap) layout = QHBoxLayout()
self.layout.addWidget(io_btns) label = self.__create_label(
self.layout.addWidget(self.start_button) 'Demucs Model <a style="text-decoration: none !important;" href="https://github.com/facebookresearch/demucs?tab=readme-ov-file#separating-tracks">ℹ️</a>'
self.layout.addWidget(self.logging_region) )
label.setOpenExternalLinks(True)
combo_box = QComboBox()
combo_box.currentTextChanged.connect(self.on_model_changed)
for model_name in MODEL_CHOICES:
combo_box.addItem(model_name)
layout.addWidget(label)
layout.addWidget(combo_box)
widget.setLayout(layout)
return widget
def __create_label(self, text: str) -> QLabel: def __create_label(self, text: str) -> QLabel:
"""Creates a label in a single call that is horizontally centered and automatically sized, with the provided text and pos. """Creates a label in a single call that is horizontally centered and automatically sized, with the provided text and pos.
@ -124,17 +163,50 @@ class MainWindow(QMainWindow):
label.adjustSize() label.adjustSize()
return label return label
def on_input_clicked(self): def __common_io_clicked(self, button_ref: QPushButton, path: str) -> None:
"""Sets the input directory from a FileDialog, enables the start button if conditions are met""" """Performs a common set of actions for both on_input_clicked and on_output_clicked
self.input_dir = QFileDialog.getExistingDirectory(None, "Select Input Folder") 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
path (str): The path chosen by the click event
"""
display_path: Path = Path(path).resolve()
button_ref.setText(f"Set: '{display_path.stem}'")
enabled = bool(self.input_dir and self.output_dir) enabled = bool(self.input_dir and self.output_dir)
self.start_button.setEnabled(enabled) self.start_button.setEnabled(enabled)
def on_output_clicked(self): def on_input_clicked(self, button_ref: QPushButton):
"""Sets the output directory from a FileDialog, enables the start button if conditions are met""" """Sets the output directory to the selected value from a QFileDialog
self.output_dir = QFileDialog.getExistingDirectory(None, "Select Input Folder") Mutates the button_ref's text to reflect the selected folder
enabled = bool(self.input_dir and self.output_dir) If Input and Output are set, enables the Start button
self.start_button.setEnabled(enabled)
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): def on_start_clicked(self):
"""Passes through basic assertions, spins up thread to process files from the input and output params""" """Passes through basic assertions, spins up thread to process files from the input and output params"""
@ -157,39 +229,35 @@ class MainWindow(QMainWindow):
if not self._thread: if not self._thread:
return return
if self._thread.isRunning(): self._thread.stop()
self._thread.requestInterruption()
self._thread.quit()
self._thread.wait()
self._thread.deleteLater() self._thread.deleteLater()
self._thread = None
class OffThreadProcessor(QThread): class OffThreadProcessor(QThread):
def __init__(self, parent: MainWindow): def __init__(self, parent: MainWindow):
super().__init__(parent) super().__init__(parent)
self.running = False
self.main_window: MainWindow = parent self.main_window: MainWindow = parent
self.setTerminationEnabled(True)
self.gui_output = GuiOutput(self.main_window) self.gui_output = GuiOutput(self.main_window)
self.processor = FolderProcessor( self.processor = FolderProcessor(
parent.input_dir, parent.output_dir, self.gui_output parent.input_dir, parent.output_dir, self.gui_output, parent.model_name
) )
def run(self) -> None: def run(self) -> None:
self.running = True try:
self.processor.process_directory() 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 # 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.logging_region.append("✅ Done!")
self.main_window.start_button.setText("Start") self.main_window.start_button.setText("Start")
self.main_window.start_button.setEnabled(True) self.main_window.start_button.setEnabled(True)
self.running = False except Exception as e:
self.processor.msg_interface.error(f"Failed: {e}")
def isRunning(self): def stop(self) -> None:
return self.running self.terminate()
def requestInterruption(self):
self.processor.quit()
return super().requestInterruption()
class GuiOutput(MessageInterface): class GuiOutput(MessageInterface):

View file

@ -11,19 +11,27 @@ from eyed3.id3 import ID3_V2_4, Tag
from tinytag import TinyTag from tinytag import TinyTag
from wavinfo import WavInfoReader from wavinfo import WavInfoReader
MODEL_NAME = "htdemucs" # "htdemucs_ft"
SUPPORTED_EXTS = [".mp3", ".m4a", ".wav"] SUPPORTED_EXTS = [".mp3", ".m4a", ".wav"]
MODEL_CHOICES = {
"Hybrid Transformer Demucs (Fine-Tuned)": "htdemucs_ft",
"Hybrid Transformer Demucs": "htdemucs",
"Hybrid Transformer Demucs v3": "hdemucs_mmi",
"Model Trained with MusDB HQ": "mdx",
"Model Trained with MusDB HQ & Extra Training Data": "mdx_extra",
"Model Trained with MusDB HQ (Quantized)": "mdx_q",
"Model Trained with MusDB HQ (Extra Quantized)": "mdx_extra_q",
}
class MusicFile: class MusicFile:
def __init__(self, path: Path): def __init__(self, path: Path, model_name: str):
"""A music file wrapper for most containers """A music file wrapper for most containers
Args: Args:
path (Path): The path of the music file path (Path): The path of the music file
""" """
self.file_path = path self.file_path = path
self.model_name = model_name
def separate(self) -> Path: def separate(self) -> Path:
"""_summary_ """_summary_
@ -43,13 +51,13 @@ class MusicFile:
"--filename", # Set the file format for easier automation "--filename", # Set the file format for easier automation
"{stem}.{ext}", # Again, easier to automate "drums.mp3" than others.. "{stem}.{ext}", # Again, easier to automate "drums.mp3" than others..
"--name", # Model Name -- including this prevents output spam and removes unpredictability "--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 self.model_name,
f"{str(self.file_path.resolve())}", f"{str(self.file_path.resolve())}",
] ]
) )
just_drums = Path(MODEL_NAME).joinpath("drums.mp3") just_drums = Path(self.model_name).joinpath("drums.mp3")
no_drums = Path(MODEL_NAME).joinpath("no_drums.mp3") no_drums = Path(self.model_name).joinpath("no_drums.mp3")
if os.path.exists(just_drums): if os.path.exists(just_drums):
os.unlink(just_drums) os.unlink(just_drums)

View file

@ -1,17 +1,22 @@
import os import os
import shutil import shutil
import subprocess
from pathlib import Path from pathlib import Path
import eyed3 import eyed3
from eyed3.id3 import ID3_V2_4, Tag from eyed3.id3 import ID3_V2_4, Tag
from src.music_file import MODEL_NAME, SUPPORTED_EXTS, MusicFile
from src.messaging import MessageInterface, NoPrintStatements from src.messaging import MessageInterface, NoPrintStatements
from src.music_file import SUPPORTED_EXTS, MusicFile
class FolderProcessor: class FolderProcessor:
def __init__( def __init__(
self, input_dir: str, output_dir: str, msg_interface: MessageInterface self,
input_dir: str,
output_dir: str,
msg_interface: MessageInterface,
model_name: str,
): ):
"""_summary_ """_summary_
@ -23,8 +28,24 @@ class FolderProcessor:
self.input_dir: str = input_dir self.input_dir: str = input_dir
self.output_dir: str = output_dir self.output_dir: str = output_dir
self.msg_interface: MessageInterface = msg_interface self.msg_interface: MessageInterface = msg_interface
self.model_name = model_name
self.should_stop = False self.should_stop = False
def _is_ffmpeg_present(self) -> bool:
"""Determines if ffmpeg is installed and accessible
Returns:
bool: True if ffmpeg is installed and accessible, false otherwise.
When returning false, no processing should be permitted.
"""
try:
exit_code = subprocess.call(
["ffmpeg"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
return exit_code == 1
except FileNotFoundError:
return False
def quit(self) -> None: def quit(self) -> None:
"""Tells the ongoing process to quit on next iteration""" """Tells the ongoing process to quit on next iteration"""
self.should_stop = True self.should_stop = True
@ -37,6 +58,11 @@ class FolderProcessor:
Also ensures that metadata is copied from the old file to the new one to provide the best user experience in the end Also ensures that metadata is copied from the old file to the new one to provide the best user experience in the end
""" """
if not self._is_ffmpeg_present():
raise Exception(
"FFMpeg is not installed! Please install it from here: https://www.ffmpeg.org/download.html"
)
src: Path = Path(self.input_dir) src: Path = Path(self.input_dir)
dest: Path = Path(self.output_dir) dest: Path = Path(self.output_dir)
cur_dir: Path = Path(".").resolve() # Used just for logging cur_dir: Path = Path(".").resolve() # Used just for logging
@ -53,7 +79,7 @@ class FolderProcessor:
) )
continue continue
# Create a "MusicFile" from the full path of the original file # Create a "MusicFile" from the full path of the original file
original_file = MusicFile(original_path) original_file = MusicFile(original_path, self.model_name)
self.msg_interface.info( self.msg_interface.info(
f"Splitting drum tracks from {original_path.name}:" f"Splitting drum tracks from {original_path.name}:"
@ -87,8 +113,8 @@ class FolderProcessor:
break break
# Remove the model output since we don't need it anymore # Remove the model output since we don't need it anymore
if os.path.exists(MODEL_NAME): if os.path.exists(self.model_name):
shutil.rmtree(MODEL_NAME) shutil.rmtree(self.model_name)
def __copy_metadata(self, original_file: MusicFile, no_drums_path: Path) -> bool: def __copy_metadata(self, original_file: MusicFile, no_drums_path: Path) -> bool:
""" """