From 9672fd2d02a9c25fd40595f5294950b440f93a47 Mon Sep 17 00:00:00 2001 From: seclusionenthusiast <117418352+seclusionenthusiast@users.noreply.github.com> Date: Tue, 3 Mar 2026 22:09:50 +0900 Subject: [PATCH] Added SepACap, SepReformer, verified power settings, slight change to settings navigation bar. --- backend/_integration_backups/config.py | 265 +++ backend/_integration_backups/models.py | 744 +++++++ .../_integration_backups/separator_service.py | 1831 +++++++++++++++++ backend/config.py | 30 + backend/routers/models.py | 9 + backend/services/sepacap_separator.py | 224 ++ backend/services/separator_service.py | 156 +- backend/services/sepreformer_separator.py | 258 +++ 8 files changed, 3516 insertions(+), 1 deletion(-) create mode 100755 backend/_integration_backups/config.py create mode 100755 backend/_integration_backups/models.py create mode 100755 backend/_integration_backups/separator_service.py create mode 100644 backend/services/sepacap_separator.py create mode 100644 backend/services/sepreformer_separator.py diff --git a/backend/_integration_backups/config.py b/backend/_integration_backups/config.py new file mode 100755 index 0000000..29e814d --- /dev/null +++ b/backend/_integration_backups/config.py @@ -0,0 +1,265 @@ +import os +from pathlib import Path + +# Base paths — each can be overridden independently via its own env var, +# or all inherit from MEDIA_DIR when left unset. +MEDIA_DIR = Path(os.environ.get("MEDIA_DIR", "/app/media")) +UPLOAD_DIR = Path(os.environ.get("UPLOAD_DIR", str(MEDIA_DIR / "uploads"))) +JOBS_DIR = Path(os.environ.get("JOBS_DIR", str(MEDIA_DIR / "jobs"))) +PROJECTS_DIR = Path(os.environ.get("PROJECTS_DIR", str(MEDIA_DIR / "projects"))) +DB_PATH = Path(os.environ.get("DB_PATH", str(MEDIA_DIR / "db" / "stemengine.db"))) +LRC_SYNC_DIR = Path(os.environ.get("LRC_SYNC_DIR", str(MEDIA_DIR / "lrc_sync"))) + +# BS-RoFormer model directory +BS_ROFORMER_MODEL_DIR = Path(os.environ.get("BS_ROFORMER_MODEL_DIR", "/opt/bs_roformer_models")) + +# MelBand RoFormer model directory +MEL_BAND_MODEL_DIR = Path(os.environ.get("MEL_BAND_MODEL_DIR", "/opt/mel_band_models")) + +# MDX-Net model directory +MDXNET_MODEL_DIR = Path(os.environ.get("MDXNET_MODEL_DIR", "/opt/mdxnet_models")) + +# SCNet XL model directory +SCNET_MODEL_DIR = Path(os.environ.get("SCNET_MODEL_DIR", "/opt/scnet_models")) + +# MedleyVox model directory +MEDLEYVOX_MODEL_DIR = Path(os.environ.get("MEDLEYVOX_MODEL_DIR", "/opt/medleyvox_models")) + +# Apollo model directory +APOLLO_MODEL_DIR = Path(os.environ.get("APOLLO_MODEL_DIR", "/opt/apollo_models")) + +# Bandit model directory +BANDIT_MODEL_DIR = Path(os.environ.get("BANDIT_MODEL_DIR", "/opt/bandit_models")) + +# Aspiration model directory +ASPIRATION_MODEL_DIR = Path(os.environ.get("ASPIRATION_MODEL_DIR", "/opt/aspiration_models")) + +# Ensemble mode cache directory +ENSEMBLE_CACHE_DIR = Path(os.environ.get("ENSEMBLE_CACHE_DIR", "/app/media/ensemble_cache")) + +# Separation models — Demucs + BS-RoFormer +DEMUCS_MODELS = [ + {"id": "htdemucs", "label": "Demucs v4", "group": "Demucs"}, + {"id": "htdemucs_ft", "label": "Demucs v4 Fine-tuned", "group": "Demucs"}, + {"id": "mdx_extra_q", "label": "Demucs v3 Extra Quantized","group": "Demucs"}, + {"id": "mdx", "label": "Demucs v3", "group": "Demucs"}, +] + +BS_ROFORMER_MODELS = [ + {"id": "bs_roformer_4stem", "label": "BS-RoFormer 4-stem", "group": "BS-RoFormer"}, + {"id": "bs_roformer_5stem_guitar", "label": "BS-RoFormer 5-stem (+ Guitar)", "group": "BS-RoFormer"}, + {"id": "bs_roformer_5stem_piano", "label": "BS-RoFormer 5-stem (+ Piano)", "group": "BS-RoFormer"}, + {"id": "bs_roformer_6stem", "label": "BS-RoFormer 6-stem (full)", "group": "BS-RoFormer"}, +] + +# MelBand RoFormer models +MEL_BAND_MODELS = [ + {"id": "mel_band_roformer_4stem", "label": "MelBand RoFormer 4-stem", "group": "MelBand RoFormer"}, + {"id": "mel_band_vocals", "label": "MelBand Vocals (2-stem)", "group": "MelBand RoFormer"}, + {"id": "mel_band_vocals_anvuew", "label": "MelBand Vocals Anvuew", "group": "MelBand RoFormer"}, + {"id": "mel_band_dereverb", "label": "MelBand Dereverb", "group": "MelBand RoFormer"}, + {"id": "mel_band_dereverb_anvuew", "label": "MelBand Dereverb Anvuew", "group": "MelBand RoFormer"}, + {"id": "mel_band_dereverb_room", "label": "MelBand Dereverb Room", "group": "MelBand RoFormer"}, + {"id": "mel_band_karaoke", "label": "MelBand Karaoke (Lead/Back)", "group": "MelBand RoFormer"}, + {"id": "mel_band_karaoke_gabox", "label": "MelBand Karaoke Gabox", "group": "MelBand RoFormer"}, + {"id": "mel_band_deux_becruily", "label": "MelBand RoFormer Deux Becruily", "group": "MelBand RoFormer"}, +] + +# BS-RoFormer specialized models +BS_ROFORMER_SPECIALIZED_MODELS = [ + {"id": "bs_roformer_chorus", "label": "BS-RoFormer Male/Female Chorus", "group": "BS-RoFormer"}, + {"id": "bs_roformer_anvuew", "label": "BS-RoFormer Anvuew (Vocals)", "group": "BS-RoFormer"}, + {"id": "bs_roformer_karaoke_anvuew", "label": "BS-RoFormer Karaoke Anvuew", "group": "BS-RoFormer"}, +] + +# MDX-Net models (from Ultimate Vocal Remover) +MDXNET_MODELS = [ + {"id": "mdxnet_voc_ft", "label": "MDX-Net Vocals FT", "group": "MDX-Net"}, + {"id": "mdxnet_inst_hq_1", "label": "MDX-Net Inst HQ 1", "group": "MDX-Net"}, + {"id": "mdxnet_inst_hq_2", "label": "MDX-Net Inst HQ 2", "group": "MDX-Net"}, + {"id": "mdxnet_karaoke", "label": "MDX-Net Karaoke", "group": "MDX-Net"}, + {"id": "mdxnet_dereverb", "label": "MDX-Net Dereverb", "group": "MDX-Net"}, + {"id": "mdxnet_drumsep", "label": "MDX-Net Drum Separation", "group": "MDX-Net"}, +] + +# SCNet XL models (state-of-the-art 2024-2025) +SCNET_MODELS = [ + {"id": "scnet_xl", "label": "SCNet XL (2-stem)", "group": "SCNet"}, + {"id": "scnet_xl_ihf", "label": "SCNet XL IHF (2-stem)", "group": "SCNet"}, + {"id": "scnet_large", "label": "SCNet Large (4-stem)", "group": "SCNet"}, + {"id": "scnet_large_starrytong", "label": "SCNet Large Starrytong", "group": "SCNet"}, +] + +# BS-RoFormer SW (Swin Transformer variant) +BS_ROFORMER_SW_MODELS = [ + {"id": "bs_roformer_sw_6stem", "label": "BS-RoFormer SW 6-stem", "group": "BS-RoFormer SW"}, +] + +# MedleyVox models (specialized vocal separation) +MEDLEYVOX_MODELS = [ + {"id": "medleyvox", "label": "MedleyVox (Vocals)", "group": "MedleyVox"}, + {"id": "medleyvox_55ep", "label": "MedleyVox 55 Epochs", "group": "MedleyVox"}, + {"id": "medleyvox_66ep", "label": "MedleyVox 66 Epochs", "group": "MedleyVox"}, + {"id": "medleyvox_88ep", "label": "MedleyVox 88 Epochs", "group": "MedleyVox"}, + {"id": "medleyvox_100ep", "label": "MedleyVox 100 Epochs", "group": "MedleyVox"}, +] + +# Apollo models (vocal enhancement/reverb removal) +APOLLO_MODELS = [ + {"id": "apollo_vocals", "label": "Apollo Vocals (Enhancement)", "group": "Apollo"}, + {"id": "apollo_edm", "label": "Apollo EDM", "group": "Apollo"}, + {"id": "apollo_edm_big", "label": "Apollo EDM Big", "group": "Apollo"}, +] + +# Aspiration models (breath/aspiration removal) +ASPIRATION_MODELS = [ + {"id": "aspiration_full", "label": "Aspiration Removal (Full)", "group": "Aspiration"}, + {"id": "aspiration_light", "label": "Aspiration Removal (Light)", "group": "Aspiration"}, +] + +# Bandit-v2 models (multi-language/multi-stem) +BANDIT_MODELS = [ + {"id": "bandit_v2_multi", "label": "Bandit v2 Multi-Language", "group": "Bandit"}, + {"id": "bandit_v2_eng", "label": "Bandit v2 English", "group": "Bandit"}, +] + +# Ensemble modes (combines multiple models for best quality) +ENSEMBLE_MODELS = [ + {"id": "ensemble_vocal_best", "label": "Ensemble - Vocal Best Quality", "group": "Ensemble"}, + {"id": "ensemble_4stem", "label": "Ensemble - 4-Stem", "group": "Ensemble"}, + {"id": "ensemble_6stem", "label": "Ensemble - 6-Stem Full", "group": "Ensemble"}, +] + +ALL_MODELS = ( + DEMUCS_MODELS + + BS_ROFORMER_MODELS + + BS_ROFORMER_SW_MODELS + + BS_ROFORMER_SPECIALIZED_MODELS + + MEL_BAND_MODELS + + MDXNET_MODELS + + SCNET_MODELS + + MEDLEYVOX_MODELS + + APOLLO_MODELS + + ASPIRATION_MODELS + + BANDIT_MODELS + + ENSEMBLE_MODELS +) +DEFAULT_DEMUCS_MODEL = "htdemucs" +DEFAULT_MODEL = DEFAULT_DEMUCS_MODEL + +ALL_MODEL_IDS = {m["id"] for m in ALL_MODELS} + +# Output formats +OUTPUT_FORMATS = [ + {"id": "mp3", "label": "MP3 (256 kbps)"}, + {"id": "mp3_320", "label": "MP3 (320 kbps)"}, + {"id": "flac", "label": "FLAC (lossless)"}, + {"id": "wav", "label": "WAV (lossless)"}, +] +DEFAULT_OUTPUT_FORMAT = "mp3" + +# basic-pitch transcription modes (mapped to inference parameter presets) +TRANSCRIBE_MODES = [ + {"id": "polyphonic", "label": "Polyphonic"}, + {"id": "melody", "label": "Melody / Vocal"}, +] +DEFAULT_TRANSCRIBE_MODE = "polyphonic" + +# basic-pitch inference parameter presets per mode +TRANSCRIBE_PRESETS = { + "polyphonic": { + "onset_threshold": 0.5, + "frame_threshold": 0.3, + "minimum_note_length": 58.0, + "melodia_trick": False, + }, + "melody": { + "onset_threshold": 0.5, + "frame_threshold": 0.3, + "minimum_note_length": 58.0, + "minimum_frequency": 65.0, # Hz — below typical singing range + "melodia_trick": True, + }, +} + +# Hardware +CPU_SEPARATION = os.environ.get("CPU_SEPARATION", "true").lower() != "false" + +# Limits +MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_MB", "500")) * 1024 * 1024 +POLL_INTERVAL_SECONDS = 5.0 + +# --------------------------------------------------------------------------- +# Presets for stem mixing +# --------------------------------------------------------------------------- + +# Available preset types +PRESET_TYPES = [ + {"id": "stems_only", "label": "Stems Only", "description": "Generate separated stems only"}, + {"id": "static", "label": "Static Mix", "description": "Remove specific elements completely"}, + {"id": "instrumental", "label": "Instrumental", "description": "Remove vocals only"}, + {"id": "dynamic", "label": "Dynamic Mix", "description": "Adjust volume levels of each element"}, +] + +# Static preset options (what to remove) +STATIC_OPTIONS = [ + {"id": "no_vocals", "label": "No Vocals", "description": "Remove vocals (keep drums, bass, other)"}, + {"id": "no_drums", "label": "No Drums", "description": "Remove drums (keep vocals, bass, other)"}, + {"id": "no_bass", "label": "No Bass", "description": "Remove bass (keep vocals, drums, other)"}, + {"id": "no_vocals_no_bass", "label": "No Vocals + No Bass", "description": "Remove vocals and bass"}, + {"id": "no_drums_no_bass", "label": "No Drums + No Bass", "description": "Remove drums and bass (vocals + other)"}, +] + +# Default volume levels for dynamic preset (0.0 to 2.0, where 1.0 = original) +DEFAULT_DYNAMIC_LEVELS = { + "vocals": 1.0, + "drums": 1.0, + "bass": 1.0, + "other": 1.0, +} + +# Available stems and their labels (varies by model) +STEM_LABELS = { + "vocals": "Vocals", + "drums": "Drums", + "bass": "Bass", + "other": "Other", + "guitar": "Guitar", + "piano": "Piano", + "lead": "Lead Vocals", + "backing": "Backing Vocals", + "male": "Male Vocals", + "female": "Female Vocals", + "instrumental": "Instrumental", + "dry_vocals": "Dry Vocals", + "reverb": "Reverb", +} + +# --------------------------------------------------------------------------- +# Project folder structure +# --------------------------------------------------------------------------- + +PROJECT_SUBFOLDERS = { + "stems": "Stems", # Always generated - contains separated stems + "instrumental": "Instrumental", # Contains instrumental mixes (no vocals) + "static": "Static", # Contains static mixes (specific elements removed) + "dynamic": "Dynamic", # Contains dynamic mixes (volume adjusted) + "transcriptions": "Transcriptions", # Contains transcription outputs + "lrc": "LRC", # Contains synced lyrics files +} + +# Subsonic integration +IMPORTS_DIR = MEDIA_DIR / "imports" +SUBSONIC_CONFIG_PATH = MEDIA_DIR / "subsonic.json" + +# Lyric transcription (Whisper models) +WHISPER_MODEL_DIR = Path(os.environ.get("WHISPER_MODEL_DIR", "/opt/whisper_models")) +DEFAULT_WHISPER_MODEL = os.environ.get("DEFAULT_WHISPER_MODEL", "large-v2") + +# Create directories on import +UPLOAD_DIR.mkdir(parents=True, exist_ok=True) +JOBS_DIR.mkdir(parents=True, exist_ok=True) +PROJECTS_DIR.mkdir(parents=True, exist_ok=True) +DB_PATH.parent.mkdir(parents=True, exist_ok=True) +LRC_SYNC_DIR.mkdir(parents=True, exist_ok=True) +IMPORTS_DIR.mkdir(parents=True, exist_ok=True) diff --git a/backend/_integration_backups/models.py b/backend/_integration_backups/models.py new file mode 100755 index 0000000..0f797f7 --- /dev/null +++ b/backend/_integration_backups/models.py @@ -0,0 +1,744 @@ +""" +Model management router — list, download, pause, cancel model downloads. +Models are downloaded from HuggingFace on-demand or pre-downloaded. +""" +import json +import shutil +import tempfile +import threading +from dataclasses import dataclass, field +from enum import Enum +from pathlib import Path +from typing import Dict, List, Optional + +from fastapi import APIRouter, HTTPException, BackgroundTasks +from pydantic import BaseModel + +from ..config import ( + ALL_MODELS, + BS_ROFORMER_MODEL_DIR, + MEL_BAND_MODEL_DIR, + MDXNET_MODEL_DIR, + SCNET_MODEL_DIR, + MEDLEYVOX_MODEL_DIR, + APOLLO_MODEL_DIR, + ASPIRATION_MODEL_DIR, + BANDIT_MODEL_DIR, +) + +router = APIRouter(prefix="/api/models", tags=["models"]) + + +# --------------------------------------------------------------------------- +# Model metadata with download info +# --------------------------------------------------------------------------- + +class ModelDownloadStatus(str, Enum): + NOT_DOWNLOADED = "not_downloaded" + DOWNLOADING = "downloading" + PAUSED = "paused" + COMPLETED = "downloaded" # matches the frontend's status === 'downloaded' checks + ERROR = "error" + CANCELLED = "cancelled" + + +@dataclass +class DownloadProgress: + model_id: str + status: ModelDownloadStatus + progress_percent: float = 0.0 + bytes_downloaded: int = 0 + total_bytes: int = 0 + speed_mbps: float = 0.0 + error_message: Optional[str] = None + + # Control flags (threading.Event so they work correctly in background threads) + _pause_event: threading.Event = field(default_factory=threading.Event) + _cancel_event: threading.Event = field(default_factory=threading.Event) + _thread: Optional[threading.Thread] = None + + def __post_init__(self): + self._pause_event.set() # Not paused by default + + def to_dict(self) -> dict: + return { + "model_id": self.model_id, + "status": self.status.value, + "progress_percent": round(self.progress_percent, 1), + "bytes_downloaded": self.bytes_downloaded, + "total_bytes": self.total_bytes, + "speed_mbps": round(self.speed_mbps, 2), + "error_message": self.error_message, + } + + +# Global download tracking +download_progress: Dict[str, DownloadProgress] = {} + + +# Model download metadata (approximate sizes from HuggingFace) +MODEL_DOWNLOAD_INFO = { + # Demucs models (downloaded automatically by the demucs library on first use via torch.hub) + "htdemucs": { + "size_mb": 80, + "description": "Demucs v4 hybrid transformer model. 4-stem separation (vocals, drums, bass, other). State-of-the-art quality; downloaded automatically on first use.", + "hf_repo": None, + "files": [], + }, + "htdemucs_ft": { + "size_mb": 400, + "description": "Fine-tuned Demucs v4 with separate per-stem models. Improved vocal and drum quality over htdemucs; downloaded automatically on first use.", + "hf_repo": None, + "files": [], + }, + "mdx_extra_q": { + "size_mb": 500, + "description": "Demucs v3 MDX Extra Quantized — quantized for faster inference and lower memory usage. Legacy model, superseded by htdemucs; downloaded automatically on first use.", + "hf_repo": None, + "files": [], + }, + "mdx": { + "size_mb": 280, + "description": "Demucs v3 baseline 4-stem model (vocals, drums, bass, other). Legacy predecessor to htdemucs; downloaded automatically on first use.", + "hf_repo": None, + "files": [], + }, + + # BS-RoFormer standard models — all share the same SW-6 weights from jarredou/BS-ROFO-SW-Fixed. + # The 4/5/6-stem "modes" are produced by merging the 6-stem outputs in bs_roformer_separator.py. + "bs_roformer_4stem": { + "size_mb": 204, + "description": "BS-RoFormer 4-stem separation (vocals, drums, bass, other). Good balance of quality and speed.", + "hf_repo": "jarredou/BS-ROFO-SW-Fixed", + "files": ["BS-Rofo-SW-Fixed.ckpt", "BS-Rofo-SW-Fixed.yaml"], + }, + "bs_roformer_5stem_guitar": { + "size_mb": 204, + "description": "BS-RoFormer 5-stem with guitar separation (vocals, drums, bass, guitar, other).", + "hf_repo": "jarredou/BS-ROFO-SW-Fixed", + "files": ["BS-Rofo-SW-Fixed.ckpt", "BS-Rofo-SW-Fixed.yaml"], + }, + "bs_roformer_5stem_piano": { + "size_mb": 204, + "description": "BS-RoFormer 5-stem with piano separation (vocals, drums, bass, piano, other).", + "hf_repo": "jarredou/BS-ROFO-SW-Fixed", + "files": ["BS-Rofo-SW-Fixed.ckpt", "BS-Rofo-SW-Fixed.yaml"], + }, + "bs_roformer_6stem": { + "size_mb": 204, + "description": "BS-RoFormer 6-stem full separation (vocals, drums, bass, guitar, piano, other).", + "hf_repo": "jarredou/BS-ROFO-SW-Fixed", + "files": ["BS-Rofo-SW-Fixed.ckpt", "BS-Rofo-SW-Fixed.yaml"], + }, + "bs_roformer_chorus": { + "size_mb": 204, + "description": "BS-RoFormer specialized for male/female chorus separation.", + "hf_repo": None, # No public download URL — install manually + "files": ["model.ckpt", "config.yaml"], + }, + "bs_roformer_anvuew": { + "size_mb": 195, + "description": "BS-RoFormer Anvuew variant optimized for vocal separation (SDR 12.45).", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["BS-RoFormer-Anvuew/bs_roformer_anvuew_sdr_12.45.ckpt", "BS-RoFormer-Anvuew/config.yaml"], + }, + "bs_roformer_karaoke_anvuew": { + "size_mb": 195, + "description": "BS-RoFormer Karaoke Anvuew for lead/backing separation.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Karaoke-BS-RoFormer-Anvuew/karaoke_bs_roformer_anvuew.ckpt", "Karaoke-BS-RoFormer-Anvuew/karaoke_bs_roformer_anvuew.yaml"], + }, + "bs_roformer_sw_6stem": { + "size_mb": 180, + "description": "BS-RoFormer SW (Swin Transformer) 6-stem variant.", + "hf_repo": None, # No public download URL — install manually + "files": ["model.ckpt"], + }, + + # MelBand RoFormer models + "mel_band_roformer_4stem": { + "size_mb": 170, + "description": "MelBand RoFormer 4-stem separation. Efficient alternative to BS-RoFormer.", + "hf_repo": None, # No public download URL — install manually + "files": ["model.ckpt", "config.yaml"], + }, + "mel_band_vocals": { + "size_mb": 170, + "description": "MelBand RoFormer optimized for 2-stem vocals/instrumental separation.", + "hf_repo": "becruily/mel-band-roformer-vocals", + "files": ["model.ckpt", "config.yaml"], + }, + "mel_band_vocals_anvuew": { + "size_mb": 195, + "description": "MelBand Vocals Anvuew variant with enhanced vocal extraction.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["BS-RoFormer-Anvuew/bs_roformer_anvuew_sdr_12.45.ckpt", "BS-RoFormer-Anvuew/config.yaml"], + }, + "mel_band_dereverb": { + "size_mb": 170, + "description": "MelBand RoFormer for reverb removal - separates dry vocals from reverb.", + "hf_repo": "anvuew/dereverb_mel_band_roformer", + "files": ["dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt", "config.yaml"], + }, + "mel_band_dereverb_anvuew": { + "size_mb": 195, + "description": "MelBand Dereverb Anvuew variant (SDR 19.17) - aggressive reverb removal.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Dereverb-MelBand-Anvuew/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt", "Dereverb-MelBand-Anvuew/dereverb_mel_band_roformer_anvuew.yaml"], + }, + "mel_band_dereverb_room": { + "size_mb": 195, + "description": "MelBand Room Dereverb for room/ambient reverb removal (SDR 13.74).", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Dereverb-Room-Anvuew/dereverb_room_anvuew_sdr_13.7432.ckpt", "Dereverb-Room-Anvuew/dereverb_room_anvuew.yaml"], + }, + "mel_band_karaoke": { + "size_mb": 170, + "description": "MelBand RoFormer for karaoke - separates lead vocals from backing+instrumental.", + "hf_repo": "becruily/mel-band-roformer-karaoke", + "files": ["model.ckpt", "config.yaml"], + }, + "mel_band_karaoke_gabox": { + "size_mb": 195, + "description": "MelBand Karaoke Gabox variant optimized for backing vocal separation.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["MelBandRoformers/bsroformers/bs_karaoke_gabox_IS.ckpt", "MelBandRoformers/bsroformers/karaoke_bs_roformer.yaml"], + }, + "mel_band_deux_becruily": { + "size_mb": 180, + "description": "MelBand RoFormer Deux Becruily - specialized 2-stem vocals model.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["MelBand-Roformer-Deux-Becruily/becruily_deux.ckpt", "MelBand-Roformer-Deux-Becruily/config_deux_becruily.yaml"], + }, + + # MDX-Net models + "mdxnet_voc_ft": { + "size_mb": 45, + "description": "MDX-Net Vocals Fine-tuned - lightweight vocals model (ONNX).", + "hf_repo": "Politrees/UVR_resources", + "files": ["models/MDXNet/UVR-MDX-NET-Voc_FT.onnx"], + }, + "mdxnet_inst_hq_1": { + "size_mb": 45, + "description": "MDX-Net Instrumental HQ 1 - focused on instrumental extraction.", + "hf_repo": "Politrees/UVR_resources", + "files": ["models/MDXNet/UVR-MDX-NET-Inst_HQ_1.onnx"], + }, + "mdxnet_inst_hq_2": { + "size_mb": 45, + "description": "MDX-Net Instrumental HQ 2 - alternative instrumental model.", + "hf_repo": "Politrees/UVR_resources", + "files": ["models/MDXNet/UVR-MDX-NET-Inst_HQ_2.onnx"], + }, + "mdxnet_karaoke": { + "size_mb": 45, + "description": "MDX-Net Karaoke - separates lead from backing vocals.", + "hf_repo": "Politrees/UVR_resources", + "files": ["models/MDXNet/UVR_MDXNET_KARA.onnx"], + }, + "mdxnet_dereverb": { + "size_mb": 195, + "description": "MDX-Net Dereverb via MelBand Anvuew architecture.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Dereverb-MelBand-Anvuew/dereverb_mel_band_roformer_anvuew_sdr_19.1729.ckpt"], + }, + "mdxnet_drumsep": { + "size_mb": 448, + "description": "MDX23C DrumSep - specialized drum separation model.", + "hf_repo": "Politrees/UVR_resources", + "files": ["models/MDX23C/MDX23C-DrumSep-aufr33-jarredou.ckpt"], + }, + + # SCNet XL models (2024-2025 state-of-the-art) + "scnet_xl": { + "size_mb": 350, + "description": "SCNet XL - State-of-the-art 2-stem separation (SDR 11.93 vocals, 18.23 instrumental).", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Politrees/UVR_resources/models/SCnet/scnet_checkpoint_musdb18.ckpt", "Politrees/UVR_resources/models/SCnet/config_musdb18_scnet_xl.yaml"], + }, + "scnet_xl_ihf": { + "size_mb": 350, + "description": "SCNet XL IHF variant - optimized for instrumental extraction.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Politrees/UVR_resources/models/SCnet/scnet_checkpoint_musdb18.ckpt", "Politrees/UVR_resources/models/SCnet/config_musdb18_scnet_xl.yaml"], + }, + "scnet_large": { + "size_mb": 200, + "description": "SCNet Large - 4-stem variant with excellent quality.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Politrees/UVR_resources/models/SCnet/SCNet-large_starrytong_fixed.ckpt", "Politrees/UVR_resources/models/SCnet/config_musdb18_scnet_large_starrytong.yaml"], + }, + "scnet_large_starrytong": { + "size_mb": 200, + "description": "SCNet Large Starrytong - fixed variant with improved stability.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Politrees/UVR_resources/models/SCnet/SCNet-large_starrytong_fixed.ckpt", "Politrees/UVR_resources/models/SCnet/config_musdb18_scnet_large_starrytong.yaml"], + }, + + # MedleyVox models + "medleyvox": { + "size_mb": 170, + "description": "MedleyVox - Multi-singer vocal separation for ensemble vocals.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["MedleyVox-MultiSinger/vocals 100.pth"], + }, + "medleyvox_55ep": { + "size_mb": 170, + "description": "MedleyVox 55 Epochs - earlier training checkpoint.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["MedleyVox-MultiSinger/vocals 55 epochs.pth"], + }, + "medleyvox_66ep": { + "size_mb": 170, + "description": "MedleyVox 66 Epochs - intermediate checkpoint.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["MedleyVox-MultiSinger/vocals 66.pth"], + }, + "medleyvox_88ep": { + "size_mb": 170, + "description": "MedleyVox 88 Epochs - near-final checkpoint.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["MedleyVox-MultiSinger/vocals 88.pth"], + }, + "medleyvox_100ep": { + "size_mb": 170, + "description": "MedleyVox 100 Epochs - final training checkpoint.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["MedleyVox-MultiSinger/vocals 100.pth"], + }, + + # Apollo models + "apollo_vocals": { + "size_mb": 400, + "description": "Apollo Vocals - Vocal enhancement and reverb removal (MSST).", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Apollo-Vocal-MSST/epoch=54-val_loss=-17.6221.ckpt", "Apollo-Vocal-MSST/config_apollo_vocals_ep_54.yaml"], + }, + "apollo_edm": { + "size_mb": 200, + "description": "Apollo EDM - Optimized for EDM vocal enhancement.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Politrees/UVR_resources/models/Apollo/apollo_edm_by_essid.ckpt", "Politrees/UVR_resources/models/Apollo/apollo_edm_by_essid.yaml"], + }, + "apollo_edm_big": { + "size_mb": 300, + "description": "Apollo EDM Big - Larger EDM vocal enhancement model.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Politrees/UVR_resources/models/Apollo/apollo_edm_big_by_essid.ckpt", "Politrees/UVR_resources/models/Apollo/apollo_edm_big_by_essid.yaml"], + }, + + # Aspiration models + "aspiration_full": { + "size_mb": 200, + "description": "Aspiration Removal (Full) - Aggressive breath/aspiration removal (SDR 18.98).", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Aspiration-MelBand-Sucial/aspiration_mel_band_roformer_sdr_18.9845.ckpt", "Aspiration-MelBand-Sucial/config_aspiration_mel_band_roformer.yaml"], + }, + "aspiration_light": { + "size_mb": 200, + "description": "Aspiration Removal (Light) - Gentler breath removal (SDR 18.12).", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Aspiration-MelBand-Sucial/aspiration_mel_band_roformer_less_aggr_sdr_18.1201.ckpt", "Aspiration-MelBand-Sucial/config_aspiration_mel_band_roformer.yaml"], + }, + + # Bandit models + "bandit_v2_multi": { + "size_mb": 250, + "description": "Bandit v2 Multi-Language - Multi-language vocal separation.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Bandit-v2/checkpoint-multi_state_dict.ckpt", "Bandit-v2/config_dnr_bandit_v2_mus64.yaml"], + }, + "bandit_v2_eng": { + "size_mb": 250, + "description": "Bandit v2 English - Optimized for English vocals.", + "hf_repo": "miercolesv/MVSEP-Central-Backup", + "files": ["Bandit-v2/checkpoint-eng_state_dict.ckpt", "Bandit-v2/config_dnr_bandit_v2_mus64.yaml"], + }, + + # Ensemble modes (no model files — combine outputs from multiple other models) + "ensemble_vocal_best": { + "size_mb": 0, + "description": "Ensemble combining multiple top vocal separators (BS-RoFormer + SCNet) for best possible vocal quality. Requires constituent models to be downloaded.", + "hf_repo": None, + "files": [], + }, + "ensemble_4stem": { + "size_mb": 0, + "description": "4-stem ensemble combining BS-RoFormer and SCNet Large outputs for vocals, drums, bass, and other. Higher quality than any single model.", + "hf_repo": None, + "files": [], + }, + "ensemble_6stem": { + "size_mb": 0, + "description": "Full 6-stem ensemble combining multiple models for vocals, drums, bass, guitar, piano, and other. Highest quality multi-instrument separation.", + "hf_repo": None, + "files": [], + }, +} + + +# Explicit mapping from model_id to the exact directory its separator service uses. +# Must stay in sync with the DEFAULT_MODEL_DIR / model_dir values in each *_separator.py. +MODEL_EXACT_DIRS: Dict[str, Path] = { + # ── BS-RoFormer standard (all share the same weights flat in the family dir) ── + "bs_roformer_4stem": BS_ROFORMER_MODEL_DIR, + "bs_roformer_5stem_guitar": BS_ROFORMER_MODEL_DIR, + "bs_roformer_5stem_piano": BS_ROFORMER_MODEL_DIR, + "bs_roformer_6stem": BS_ROFORMER_MODEL_DIR, + # ── BS-RoFormer specialized ── + "bs_roformer_chorus": BS_ROFORMER_MODEL_DIR / "chorus", + "bs_roformer_sw_6stem": BS_ROFORMER_MODEL_DIR, # flat; hf_repo=None + "bs_roformer_anvuew": MEL_BAND_MODEL_DIR / "vocals_anvuew", + "bs_roformer_karaoke_anvuew": MEL_BAND_MODEL_DIR / "karaoke_gabox", + # ── MelBand RoFormer ── + "mel_band_roformer_4stem": MEL_BAND_MODEL_DIR, # flat; hf_repo=None + "mel_band_vocals": MEL_BAND_MODEL_DIR / "vocals", + "mel_band_vocals_anvuew": MEL_BAND_MODEL_DIR / "vocals_anvuew", + "mel_band_dereverb": MEL_BAND_MODEL_DIR / "dereverb", + "mel_band_dereverb_anvuew": MEL_BAND_MODEL_DIR / "dereverb_anvuew", + "mel_band_dereverb_room": MEL_BAND_MODEL_DIR / "dereverb_room", + "mel_band_karaoke": MEL_BAND_MODEL_DIR / "karaoke", + "mel_band_karaoke_gabox": MEL_BAND_MODEL_DIR / "karaoke_gabox", + "mel_band_deux_becruily": MEL_BAND_MODEL_DIR / "deux_becruily", + # ── MDX-Net (flat family dir — separator uses basename only) ── + "mdxnet_voc_ft": MDXNET_MODEL_DIR, + "mdxnet_inst_hq_1": MDXNET_MODEL_DIR, + "mdxnet_inst_hq_2": MDXNET_MODEL_DIR, + "mdxnet_karaoke": MDXNET_MODEL_DIR, + "mdxnet_dereverb": MEL_BAND_MODEL_DIR / "dereverb", # routed to MelBand + "mdxnet_drumsep": MDXNET_MODEL_DIR, + # ── SCNet (per-model subdir) ── + "scnet_xl": SCNET_MODEL_DIR / "scnet_xl", + "scnet_xl_ihf": SCNET_MODEL_DIR / "scnet_xl_ihf", + "scnet_large": SCNET_MODEL_DIR / "scnet_large", + "scnet_large_starrytong": SCNET_MODEL_DIR / "scnet_large_starrytong", + # ── MedleyVox (per-model subdir) ── + "medleyvox": MEDLEYVOX_MODEL_DIR / "medleyvox", + "medleyvox_55ep": MEDLEYVOX_MODEL_DIR / "medleyvox_55ep", + "medleyvox_66ep": MEDLEYVOX_MODEL_DIR / "medleyvox_66ep", + "medleyvox_88ep": MEDLEYVOX_MODEL_DIR / "medleyvox_88ep", + "medleyvox_100ep": MEDLEYVOX_MODEL_DIR / "medleyvox_100ep", + # ── Apollo (per-model subdir) ── + "apollo_vocals": APOLLO_MODEL_DIR / "apollo_vocals", + "apollo_edm": APOLLO_MODEL_DIR / "apollo_edm", + "apollo_edm_big": APOLLO_MODEL_DIR / "apollo_edm_big", + # ── Aspiration (per-model subdir) ── + "aspiration_full": ASPIRATION_MODEL_DIR / "aspiration_full", + "aspiration_light": ASPIRATION_MODEL_DIR / "aspiration_light", + # ── Bandit (per-model subdir) ── + "bandit_v2_multi": BANDIT_MODEL_DIR / "bandit_v2_multi", + "bandit_v2_eng": BANDIT_MODEL_DIR / "bandit_v2_eng", +} + + +def get_model_directory(model_id: str) -> Path: + """Get the exact directory where a model's files are stored on disk.""" + return MODEL_EXACT_DIRS.get(model_id, BS_ROFORMER_MODEL_DIR / model_id) + + +def is_model_downloaded(model_id: str) -> bool: + """Check if a model is already downloaded.""" + if model_id not in MODEL_DOWNLOAD_INFO: + return False + + model_dir = get_model_directory(model_id) + info = MODEL_DOWNLOAD_INFO[model_id] + + for file_path in info["files"]: + flat = model_dir / Path(file_path).name # flat download (our convention) + deep = model_dir / file_path # subdirectory structure + if not flat.exists() and not deep.exists(): + return False + + return True + + +# --------------------------------------------------------------------------- +# API Models +# --------------------------------------------------------------------------- + +class ModelInfo(BaseModel): + id: str + label: str + group: str + description: str + size_mb: int + status: str # not_downloaded, downloaded, downloading, paused, error + progress_percent: float = 0.0 + + +class ModelDownloadRequest(BaseModel): + model_id: str + + +class ModelDownloadResponse(BaseModel): + success: bool + message: str + + +# --------------------------------------------------------------------------- +# Endpoints +# --------------------------------------------------------------------------- + +@router.get("/list", response_model=List[ModelInfo]) +def list_models(): + """List all available models with their download status.""" + result = [] + + for model in ALL_MODELS: + model_id = model["id"] + info = MODEL_DOWNLOAD_INFO.get(model_id, {}) + + # Check current download status + if model_id in download_progress: + prog = download_progress[model_id] + status = prog.status.value + progress = prog.progress_percent + elif is_model_downloaded(model_id): + status = ModelDownloadStatus.COMPLETED.value + progress = 100.0 + else: + status = ModelDownloadStatus.NOT_DOWNLOADED.value + progress = 0.0 + + result.append(ModelInfo( + id=model_id, + label=model["label"], + group=model.get("group", "Other"), + description=info.get("description", "No description available."), + size_mb=info.get("size_mb", 0), + status=status, + progress_percent=progress, + )) + + return result + + +@router.post("/download", response_model=ModelDownloadResponse) +def download_model(body: ModelDownloadRequest, background_tasks: BackgroundTasks): + """Start downloading a model in the background.""" + model_id = body.model_id + + if model_id not in MODEL_DOWNLOAD_INFO: + raise HTTPException(status_code=404, detail=f"Unknown model: {model_id}") + + # Check if already downloaded + if is_model_downloaded(model_id): + return ModelDownloadResponse(success=True, message=f"Model {model_id} is already downloaded.") + + # Check if already downloading + if model_id in download_progress: + prog = download_progress[model_id] + if prog.status == ModelDownloadStatus.DOWNLOADING: + return ModelDownloadResponse(success=True, message=f"Download already in progress for {model_id}.") + elif prog.status == ModelDownloadStatus.PAUSED: + # Resume + prog._pause_event.set() + prog.status = ModelDownloadStatus.DOWNLOADING + return ModelDownloadResponse(success=True, message=f"Resuming download for {model_id}.") + + # Start new download + progress = DownloadProgress( + model_id=model_id, + status=ModelDownloadStatus.DOWNLOADING, + total_bytes=MODEL_DOWNLOAD_INFO[model_id]["size_mb"] * 1024 * 1024, + ) + download_progress[model_id] = progress + + # Start background download + background_tasks.add_task(_download_model_task, model_id, progress) + + return ModelDownloadResponse(success=True, message=f"Started downloading {model_id}.") + + +@router.post("/pause") +def pause_download(body: ModelDownloadRequest): + """Pause an ongoing download.""" + model_id = body.model_id + + if model_id not in download_progress: + raise HTTPException(status_code=404, detail=f"No active download for {model_id}") + + prog = download_progress[model_id] + if prog.status != ModelDownloadStatus.DOWNLOADING: + raise HTTPException(status_code=400, detail=f"Download is not in progress (status: {prog.status.value})") + + prog._pause_event.clear() + prog.status = ModelDownloadStatus.PAUSED + + return {"success": True, "message": f"Paused download for {model_id}"} + + +@router.post("/resume") +def resume_download(body: ModelDownloadRequest): + """Resume a paused download.""" + model_id = body.model_id + + if model_id not in download_progress: + raise HTTPException(status_code=404, detail=f"No download to resume for {model_id}") + + prog = download_progress[model_id] + if prog.status != ModelDownloadStatus.PAUSED: + raise HTTPException(status_code=400, detail=f"Download is not paused (status: {prog.status.value})") + + prog._pause_event.set() + prog.status = ModelDownloadStatus.DOWNLOADING + + return {"success": True, "message": f"Resumed download for {model_id}"} + + +@router.post("/cancel") +def cancel_download(body: ModelDownloadRequest): + """Cancel an ongoing or paused download.""" + model_id = body.model_id + + if model_id not in download_progress: + raise HTTPException(status_code=404, detail=f"No active download for {model_id}") + + prog = download_progress[model_id] + + # Signal cancellation + prog._cancel_event.set() + prog.status = ModelDownloadStatus.CANCELLED + + # Clean up partial downloads + _cleanup_partial_download(model_id) + + return {"success": True, "message": f"Cancelled download for {model_id}"} + + +@router.get("/progress/{model_id}") +def get_progress(model_id: str): + """Get download progress for a specific model.""" + if model_id not in download_progress: + # Check if downloaded + if is_model_downloaded(model_id): + return { + "model_id": model_id, + "status": ModelDownloadStatus.COMPLETED.value, + "progress_percent": 100.0, + "bytes_downloaded": MODEL_DOWNLOAD_INFO.get(model_id, {}).get("size_mb", 0) * 1024 * 1024, + "total_bytes": MODEL_DOWNLOAD_INFO.get(model_id, {}).get("size_mb", 0) * 1024 * 1024, + "speed_mbps": 0.0, + } + raise HTTPException(status_code=404, detail=f"No download found for {model_id}") + + return download_progress[model_id].to_dict() + + +@router.get("/progress") +def get_all_progress(): + """Get download progress for all models.""" + return {model_id: prog.to_dict() for model_id, prog in download_progress.items()} + + +@router.delete("/{model_id}") +def delete_model(model_id: str): + """Delete a downloaded model to free up space.""" + if model_id not in MODEL_DOWNLOAD_INFO: + raise HTTPException(status_code=404, detail=f"Unknown model: {model_id}") + + if not is_model_downloaded(model_id): + raise HTTPException(status_code=400, detail=f"Model {model_id} is not downloaded") + + # Remove files + model_dir = get_model_directory(model_id) + info = MODEL_DOWNLOAD_INFO[model_id] + + deleted = 0 + for file_path in info["files"]: + # Try flat first (our download convention), then deep path + for candidate in (model_dir / Path(file_path).name, model_dir / file_path): + if candidate.exists(): + candidate.unlink() + deleted += 1 + break + + # Clean up progress tracking + if model_id in download_progress: + del download_progress[model_id] + + return {"success": True, "message": f"Deleted {deleted} files for {model_id}"} + + +# --------------------------------------------------------------------------- +# Background download task +# --------------------------------------------------------------------------- + +def _download_model_task(model_id: str, progress: DownloadProgress): + """Background task to download a model from HuggingFace.""" + try: + from huggingface_hub import hf_hub_download + + info = MODEL_DOWNLOAD_INFO[model_id] + hf_repo = info.get("hf_repo") + + # Reject placeholder / unconfigured repos immediately + if not hf_repo: + progress.status = ModelDownloadStatus.ERROR + progress.error_message = ( + "No download URL configured for this model. " + "Install the weights manually into the model directory." + ) + return + + model_dir = get_model_directory(model_id) + model_dir.mkdir(parents=True, exist_ok=True) + + total_files = len(info["files"]) + + for idx, file_path in enumerate(info["files"]): + # Check for cancellation + if progress._cancel_event.is_set(): + progress.status = ModelDownloadStatus.CANCELLED + return + + # Block here until resumed (threading.Event.wait() works correctly in threads) + progress._pause_event.wait() + + if progress._cancel_event.is_set(): + progress.status = ModelDownloadStatus.CANCELLED + return + + dest = model_dir / Path(file_path).name + if dest.exists(): + # Already present — count it and skip + progress.bytes_downloaded += dest.stat().st_size + progress.progress_percent = (idx + 1) / total_files * 100 + continue + + try: + # Download to a temp directory first, then move flat into model_dir. + # This ensures is_model_downloaded() finds files at the expected path + # regardless of the subdirectory structure inside the HF repo. + with tempfile.TemporaryDirectory() as tmp: + tmp_path = hf_hub_download( + repo_id=hf_repo, + filename=file_path, + local_dir=tmp, + local_dir_use_symlinks=False, + ) + shutil.copy2(tmp_path, str(dest)) + + progress.bytes_downloaded += dest.stat().st_size + progress.progress_percent = (idx + 1) / total_files * 100 + + except Exception as e: + progress.status = ModelDownloadStatus.ERROR + progress.error_message = str(e) + return + + progress.progress_percent = 100.0 + progress.status = ModelDownloadStatus.COMPLETED + + except Exception as e: + progress.status = ModelDownloadStatus.ERROR + progress.error_message = str(e) + + +def _cleanup_partial_download(model_id: str): + """Remove partially downloaded files.""" + model_dir = get_model_directory(model_id) + if model_dir.exists(): + import shutil + shutil.rmtree(model_dir, ignore_errors=True) diff --git a/backend/_integration_backups/separator_service.py b/backend/_integration_backups/separator_service.py new file mode 100755 index 0000000..92a9270 --- /dev/null +++ b/backend/_integration_backups/separator_service.py @@ -0,0 +1,1831 @@ +""" +Stem separation service with project-based folder structure and preset mixing. + - Demucs models → CLI subprocess (python -m demucs) + - BS-RoFormer → Python API (in-process, no subprocess needed) + - Presets → Instrumental, Static, Dynamic mixing via preset_service +""" +import os +import subprocess +import sys +import time +import shutil +from pathlib import Path +from typing import Dict, List, Optional + +from .. import job_manager as jm +from ..config import ( + PROJECTS_DIR, JOBS_DIR, CPU_SEPARATION, PROJECT_SUBFOLDERS, ALL_MODELS, OUTPUT_FORMATS, + MEL_BAND_MODELS, BS_ROFORMER_SPECIALIZED_MODELS, MDXNET_MODELS, + SCNET_MODELS, MEDLEYVOX_MODELS, ENSEMBLE_MODELS, APOLLO_MODELS, ASPIRATION_MODELS, BANDIT_MODELS, + BS_ROFORMER_SW_MODELS +) +from .metadata_util import copy_metadata, read_metadata +from .project_namer import project_name, make_project_dirs +from .preset_service import make_instrumental, make_static, make_dynamic +from .project_metadata import write_project_metadata + +# --------------------------------------------------------------------------- +# Stem file naming helper +# --------------------------------------------------------------------------- + +def _stem_filename(prefix: str, stem_name: str, suffix: str) -> str: + """ + Return the destination filename for a separated stem. + Format: "Artist - Title (vocals).mp3" + """ + label = stem_name.lower().replace('_', ' ') + return f"{prefix} ({label}){suffix}" + + +# Lookup maps for human-readable labels +_MODEL_LABELS = {m['id']: m['label'] for m in ALL_MODELS} +_FORMAT_LABELS = {f['id']: f['label'] for f in OUTPUT_FORMATS} + +# Model ID prefix that identifies BS-RoFormer models +BSR_PREFIX = 'bs_roformer_' + +# Map from our model ID suffix → BSRoformerSeparator stem_mode string +BSR_STEM_MODE = { + 'bs_roformer_4stem': '4stem', + 'bs_roformer_5stem_guitar': '5stem_guitar', + 'bs_roformer_5stem_piano': '5stem_piano', + 'bs_roformer_6stem': '6stem', +} + +# Model ID prefix that identifies MelBand RoFormer models +MBR_PREFIX = 'mel_band_roformer_' +MBR_VOCALS_PREFIX = 'mel_band_vocals' +MBR_DEREVERB_PREFIX = 'mel_band_dereverb' +MBR_KARAOKE_PREFIX = 'mel_band_karaoke' + +# MelBand RoFormer model IDs +MBR_MODELS = {m['id'] for m in MEL_BAND_MODELS} + +# MelBand specialized model groups +MBR_VOCALS_MODELS = {m['id'] for m in MEL_BAND_MODELS if 'vocals' in m['id']} +MBR_DEREVERB_MODELS = {m['id'] for m in MEL_BAND_MODELS if 'dereverb' in m['id']} +MBR_KARAOKE_MODELS = {m['id'] for m in MEL_BAND_MODELS if 'karaoke' in m['id']} +MBR_DEUX_BECRUILY_MODELS = {m['id'] for m in MEL_BAND_MODELS if 'deux_becruily' in m['id']} + +# BS-RoFormer specialized model IDs +BSR_CHORUS_MODELS = {m['id'] for m in BS_ROFORMER_SPECIALIZED_MODELS if 'chorus' in m['id']} +BSR_ANVUEW_MODELS = {m['id'] for m in BS_ROFORMER_SPECIALIZED_MODELS if 'anvuew' in m['id'] and 'karaoke' not in m['id']} +BSR_KARAOKE_ANVUEW_MODELS = {m['id'] for m in BS_ROFORMER_SPECIALIZED_MODELS if 'karaoke' in m['id'] and 'anvuew' in m['id']} + +# MDX-Net model IDs +MDXNET_MODEL_IDS = {m['id'] for m in MDXNET_MODELS} + +# SCNet XL model IDs +SCNET_MODEL_IDS = {m['id'] for m in SCNET_MODELS} + +# BS-RoFormer SW model IDs +BSR_SW_MODEL_IDS = {m['id'] for m in BS_ROFORMER_SW_MODELS} + +# MedleyVox model IDs +MEDLEYVOX_MODEL_IDS = {m['id'] for m in MEDLEYVOX_MODELS} + +# Apollo model IDs +APOLLO_MODEL_IDS = {m['id'] for m in APOLLO_MODELS} + +# Aspiration model IDs +ASPIRATION_MODEL_IDS = {m['id'] for m in ASPIRATION_MODELS} + +# Bandit model IDs +BANDIT_MODEL_IDS = {m['id'] for m in BANDIT_MODELS} + +# Ensemble model IDs +ENSEMBLE_MODEL_IDS = {m['id'] for m in ENSEMBLE_MODELS} + +# --------------------------------------------------------------------------- +# Separation power presets +# --------------------------------------------------------------------------- + +# Each preset maps to: +# roformer: batch_size and num_overlap overrides (None = use model config default) +# demucs: --segment and --overlap CLI flags (None = omit flag, use demucs default) +_SEP_POWER_PRESETS: Dict[str, Dict] = { + 'eco': { + 'roformer': {'batch_size': 1, 'num_overlap': 2}, + 'demucs': {'segment': 5, 'overlap': 0.1}, + }, + 'standard': { + 'roformer': {'batch_size': None, 'num_overlap': None}, + 'demucs': {'segment': None, 'overlap': None}, + }, + 'performance': { + 'roformer': {'batch_size': 8, 'num_overlap': 4}, + 'demucs': {'segment': 20, 'overlap': 0.5}, + }, +} + + +def _get_power_opts(preset: str) -> Dict: + """Resolve a power preset name to its options dict.""" + return _SEP_POWER_PRESETS.get(preset, _SEP_POWER_PRESETS['standard']) + + +def _ensure_model_available(job_id: str, model_id: str) -> bool: + """ + Download model weights if they are not already present on disk. + Demucs models are skipped — they self-download through the demucs library. + Returns True if the model is ready, False if download failed (job set to ERROR). + """ + # Demucs downloads itself via the CLI; no action needed + demucs_ids = {'htdemucs', 'htdemucs_ft', 'mdx_extra_q', 'mdx'} + if model_id in demucs_ids: + return True + + from ..routers.models import MODEL_DOWNLOAD_INFO, get_model_directory, is_model_downloaded + + if model_id not in MODEL_DOWNLOAD_INFO: + return True # Not in registry — assume bundled / self-managed + + if is_model_downloaded(model_id): + return True + + info = MODEL_DOWNLOAD_INFO[model_id] + hf_repo = info.get("hf_repo") + + if not hf_repo: + # No public download URL — the individual separator service will attempt its + # own download (snapshot_download) when it runs. Don't fail the job here. + return True + + jm.update_job(job_id, progress=f"Downloading model weights for '{model_id}'...") + + try: + import shutil as _shutil + import tempfile + from huggingface_hub import hf_hub_download + + model_dir = get_model_directory(model_id) + model_dir.mkdir(parents=True, exist_ok=True) + + for file_path in info["files"]: + dest = model_dir / Path(file_path).name + if dest.exists(): + continue + jm.update_job(job_id, progress=f"Downloading {Path(file_path).name}...") + with tempfile.TemporaryDirectory() as tmp: + tmp_path = hf_hub_download( + repo_id=hf_repo, + filename=file_path, + local_dir=tmp, + local_dir_use_symlinks=False, + ) + _shutil.copy2(tmp_path, str(dest)) + + return True + + except Exception as exc: + jm.update_job( + job_id, + status=jm.JobStatus.ERROR, + error=f"Failed to download model '{model_id}': {exc}", + progress="Error: model download failed.", + ) + return False + + +def run_separation( + job_id: str, + input_path: str, + model: str, + output_format: str, + # Preset options + preset_type: str = "stems_only", # stems_only, static, instrumental, dynamic + static_option: Optional[str] = None, # for static preset: no_vocals, no_drums, etc. + dynamic_levels: Optional[Dict[str, float]] = None, # for dynamic preset + # Project naming + project_name_override: Optional[str] = None, + # Power preset + sep_power_preset: str = 'standard', + # Reprocess mode: output stems directly into an existing project's Stems dir + output_dir_override: Optional[Path] = None, + parent_job_id: Optional[str] = None, +): + """ + Background task: separate audio into stems and apply presets. + + Creates human-readable project folder structure: + /Artist - Title/ + Stems/ (always created) + Instrumental/ (if preset includes instrumental) + Static/ (if preset is static) + Dynamic/ (if preset is dynamic) + """ + # Read metadata for project naming + jm.update_job(job_id, status=jm.JobStatus.RUNNING, progress="Reading metadata...") + metadata = read_metadata(input_path) + + # Ensure model weights are present — download automatically if missing + if not _ensure_model_available(job_id, model): + return + + # Resolve human-readable labels for tab naming + model_label = _MODEL_LABELS.get(model, model) + format_label = _FORMAT_LABELS.get(output_format, output_format) + tab_label = f"{model_label}_{format_label}" + + # Determine project name + if project_name_override: + proj_name = project_name_override + else: + filename_stem = Path(input_path).stem + proj_name = project_name( + metadata.get('albumartist') or metadata.get('artist', ''), + metadata.get('title', ''), + filename_stem, + ) + + if output_dir_override is not None: + # Reprocess mode: place stems directly in the existing project's Stems dir. + # Skip project creation and source-file copy — the folder already exists. + stems_dir = output_dir_override + project_dir = output_dir_override.parent + stems_dir.mkdir(parents=True, exist_ok=True) + dirs = {'project': project_dir, 'stems': stems_dir} + source_dest = project_dir / f"{proj_name}{Path(input_path).suffix.lower()}" + else: + # Determine which folders to create based on preset + preset_flags = { + 'instrumental': preset_type in ('instrumental',), + 'static': preset_type == 'static', + 'dynamic': preset_type == 'dynamic', + } + + # Create project directories + jm.update_job(job_id, progress=f"Creating project: {proj_name}...") + dirs = make_project_dirs(proj_name, PROJECTS_DIR, preset_flags) + + stems_dir = dirs['stems'] + project_dir = dirs['project'] + + # Copy original source file to project root with full metadata + jm.update_job(job_id, progress="Copying source file to project...") + input_ext = Path(input_path).suffix.lower() + source_dest = project_dir / f"{proj_name}{input_ext}" + try: + shutil.copy2(input_path, source_dest) + copy_metadata(input_path, str(source_dest), stem_label=None, copy_lyrics=True) + except Exception as e: + jm.update_job(job_id, progress=f"Warning: Could not copy source file: {e}") + + # Normalise mp3_320 → mp3 with explicit bitrate + mp3_bitrate = '320k' if output_format == 'mp3_320' else '256k' + normalised_format = 'mp3' if output_format == 'mp3_320' else output_format + + # Resolve power preset options + _power = _get_power_opts(sep_power_preset) + _roformer_opts = _power['roformer'] + _demucs_opts = _power['demucs'] + + # Free any cached GPU memory from previous jobs before loading a new model. + # This reduces OOM risk when Whisper or a prior separation left allocations behind. + try: + import torch + if torch.cuda.is_available() and not CPU_SEPARATION: + torch.cuda.empty_cache() + except Exception: + pass + + # Run separation + try: + if model.startswith(BSR_PREFIX): + stem_files = _run_bsroformer( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + elif model in BSR_CHORUS_MODELS: + stem_files = _run_bsroformer_chorus( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + elif model in BSR_ANVUEW_MODELS: + # Route to MelBand Vocals Anvuew since it's the same architecture + stem_files = _run_mel_band_vocals( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + elif model in BSR_KARAOKE_ANVUEW_MODELS: + # Route to Karaoke Gabox as closest match + stem_files = _run_mel_band_karaoke( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + elif model.startswith(MBR_PREFIX): + stem_files = _run_mel_band_roformer( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + elif model in MBR_VOCALS_MODELS: + stem_files = _run_mel_band_vocals( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + elif model in MBR_DEREVERB_MODELS: + stem_files = _run_mel_band_dereverb( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + elif model in MBR_KARAOKE_MODELS: + stem_files = _run_mel_band_karaoke( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + elif model in MBR_DEUX_BECRUILY_MODELS: + stem_files = _run_mel_band_deux_becruily( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + elif model in MDXNET_MODEL_IDS: + # Route MelBand-based MDX models appropriately + if model == 'mdxnet_dereverb': + stem_files = _run_mel_band_dereverb( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + batch_size_override=_roformer_opts.get('batch_size'), + num_overlap_override=_roformer_opts.get('num_overlap'), + ) + else: + stem_files = _run_mdxnet( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata + ) + elif model in SCNET_MODEL_IDS: + stem_files = _run_scnet( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + ) + elif model in BSR_SW_MODEL_IDS: + stem_files = _run_bsroformer_sw( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + ) + elif model in MEDLEYVOX_MODEL_IDS: + stem_files = _run_medleyvox( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + ) + elif model in ENSEMBLE_MODEL_IDS: + stem_files = _run_ensemble( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + ) + elif model in APOLLO_MODEL_IDS: + stem_files = _run_apollo( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + ) + elif model in ASPIRATION_MODEL_IDS: + stem_files = _run_aspiration( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + ) + elif model in BANDIT_MODEL_IDS: + stem_files = _run_bandit( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + ) + else: + stem_files = _run_demucs( + job_id, input_path, model, output_format, stems_dir, + metadata=metadata, + stem_prefix=proj_name, + segment_override=_demucs_opts.get('segment'), + overlap_override=_demucs_opts.get('overlap'), + ) + + if jm.should_cancel(job_id): + jm.update_job(job_id, status=jm.JobStatus.CANCELLED, progress="Cancelled.") + return + + # Apply presets if requested + preset_files = [] + if preset_type == 'instrumental' and 'instrumental' in dirs: + jm.update_job(job_id, progress="Creating instrumental mix...") + inst_path = dirs['instrumental'] / f"{proj_name} - Instrumental.{normalised_format}" + try: + result = make_instrumental(stem_files, inst_path, output_format) + copy_metadata(input_path, result, stem_label="Instrumental", copy_lyrics=True) + preset_files.append({ + "name": inst_path.name, + "path": result, + "type": "instrumental" + }) + except Exception as e: + jm.update_job(job_id, progress=f"Instrumental preset failed: {e}") + + elif preset_type == 'static' and 'static' in dirs: + jm.update_job(job_id, progress="Creating static mix...") + muted = _get_muted_stems(static_option) + static_name = _static_name(static_option) + static_path = dirs['static'] / f"{proj_name} - {static_name}.{normalised_format}" + try: + result = make_static(stem_files, muted, static_path, output_format) + copy_metadata(input_path, result, stem_label=static_name, copy_lyrics=True) + preset_files.append({ + "name": static_path.name, + "path": result, + "type": "static" + }) + except Exception as e: + jm.update_job(job_id, progress=f"Static preset failed: {e}") + + elif preset_type == 'dynamic' and 'dynamic' in dirs: + jm.update_job(job_id, progress="Creating dynamic mix...") + volumes = dynamic_levels or {} + dynamic_path = dirs['dynamic'] / f"{proj_name} - Dynamic Mix.{normalised_format}" + try: + result = make_dynamic(stem_files, volumes, dynamic_path, output_format) + copy_metadata(input_path, result, stem_label="Dynamic Mix", copy_lyrics=True) + preset_files.append({ + "name": dynamic_path.name, + "path": result, + "type": "dynamic" + }) + except Exception as e: + jm.update_job(job_id, progress=f"Dynamic preset failed: {e}") + + # Build result file list + all_files = [] + + # Add source file first if it exists + if source_dest.exists(): + all_files.append({ + "name": source_dest.name, + "path": str(source_dest), + "type": "source" + }) + + for stem_name, path in sorted(stem_files.items()): + all_files.append({ + "name": Path(path).name, + "path": path, + "type": "stem", + "stem": stem_name + }) + all_files.extend(preset_files) + + if output_dir_override is None: + # Normal mode: register a project record and write project.json + project = jm.find_or_create_project(proj_name, job_id, tab_label=tab_label) + try: + write_project_metadata( + project_dir, + project_id=project['id'], + name=proj_name, + artist=metadata.get('albumartist') or metadata.get('artist', ''), + title=metadata.get('title', ''), + model=model, + model_label=model_label, + format=normalised_format, + format_label=format_label, + source_file=str(source_dest) if source_dest.exists() else '', + stems=stem_files, + sep_job_id=job_id, + trans_jobs={}, + abc_jobs={}, + lrc_jobs={}, + mix_job_id=None, + ) + except Exception as meta_err: + jm.update_job(job_id, progress=f"Warning: could not write project.json: {meta_err}") + project_id_result = project['id'] + else: + # Reprocess mode: merge new stems into the parent sep job's file list + # so the project page discovers them without any extra queries. + stem_entries = [f for f in all_files if f.get("type") == "stem"] + if parent_job_id: + jm.append_job_files(parent_job_id, stem_entries) + project_id_result = None + + jm.update_job( + job_id, + status=jm.JobStatus.DONE, + progress="Separation complete.", + files=all_files, + result={ + "project_name": proj_name, + "project_path": str(dirs['project']), + "stems_dir": str(stems_dir), + "model_label": model_label, + "format_label": format_label, + "tab_label": tab_label, + "project_id": project_id_result, + } + ) + + except Exception as exc: + err_str = str(exc) + if "CUDA" in err_str or "cuda" in err_str: + # CUDA context is corrupted (typically after a prior OOM). + # Auto-reset clears allocations and re-enables GPU for the next attempt. + try: + from .lyric_transcriber_service import reset_cuda + reset_cuda() + except Exception: + try: + import torch + torch.cuda.empty_cache() + except Exception: + pass + user_msg = ( + f"GPU (CUDA) error: {err_str[:300]}\n\n" + "The GPU was automatically reset — please retry the separation. " + "If the error keeps occurring, restart the container." + ) + jm.update_job(job_id, status=jm.JobStatus.ERROR, error=user_msg, progress="GPU error — retry to use reset GPU.") + else: + jm.update_job(job_id, status=jm.JobStatus.ERROR, error=err_str, progress="Error.") + + +def _get_muted_stems(static_option: Optional[str]) -> List[str]: + """Convert static option ID to list of stem names to mute.""" + if not static_option: + return [] + + option_map = { + 'no_vocals': ['vocals'], + 'no_drums': ['drums'], + 'no_bass': ['bass'], + 'no_vocals_no_bass': ['vocals', 'bass'], + 'no_drums_no_bass': ['drums', 'bass'], + } + return option_map.get(static_option, []) + + +def _static_name(static_option: Optional[str]) -> str: + """Convert static option ID to human-readable name.""" + name_map = { + 'no_vocals': 'No Vocals', + 'no_drums': 'No Drums', + 'no_bass': 'No Bass', + 'no_vocals_no_bass': 'No Vocals No Bass', + 'no_drums_no_bass': 'No Drums No Bass', + } + return name_map.get(static_option, 'Static Mix') + + +# --------------------------------------------------------------------------- +# Demucs (CLI) +# --------------------------------------------------------------------------- + +def _run_demucs( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, + segment_override: Optional[int] = None, + overlap_override: Optional[float] = None, +) -> Dict[str, str]: + """ + Run Demucs separation. Returns dict mapping stem names to file paths. + """ + jm.update_job(job_id, progress="Starting Demucs separation...") + + ext = output_format.lower() + fmt_flag = [] + if ext == 'mp3_320': + fmt_flag = ['--mp3', '--mp3-bitrate', '320'] + ext = 'mp3' + elif ext == 'mp3': + fmt_flag = ['--mp3', '--mp3-bitrate', '256'] + elif ext == 'flac': + fmt_flag = ['--flac'] + + power_flags = [] + if segment_override is not None: + power_flags.extend(['--segment', str(segment_override)]) + if overlap_override is not None: + power_flags.extend(['--overlap', str(overlap_override)]) + + # Use a temp directory for demucs output + temp_out = JOBS_DIR / job_id / "demucs_out" + temp_out.mkdir(parents=True, exist_ok=True) + + cmd = [ + sys.executable, '-m', 'demucs', + '--name', model, + '--out', str(temp_out), + *fmt_flag, + *power_flags, + input_path, + ] + + try: + process = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + ) + + while True: + if jm.should_cancel(job_id): + process.terminate() + process.wait() + raise RuntimeError("Cancelled by user") + line = process.stdout.readline() + if line: + jm.update_job(job_id, progress=line.rstrip()) + elif process.poll() is not None: + break + else: + time.sleep(0.1) + + if process.returncode != 0: + raise RuntimeError(f"Demucs exited with code {process.returncode}") + + # Move stems to project folder + input_stem = Path(input_path).stem + _prefix = stem_prefix or input_stem + stem_dir = temp_out / model / input_stem + + stem_files = {} + if stem_dir.exists(): + for f in sorted(stem_dir.iterdir()): + if f.is_file(): + # Determine stem name from filename + stem_name = f.stem.lower() + # Clean up common demucs naming patterns + for prefix in [input_stem.lower(), 'htdemucs', 'mdx']: + stem_name = stem_name.replace(prefix, '').strip('_- ') + if not stem_name: + stem_name = f.stem + + dest = stems_dir / _stem_filename(_prefix, stem_name, f.suffix) + shutil.move(str(f), str(dest)) + copy_metadata(input_path, str(dest), stem_label=stem_name.capitalize(), copy_lyrics=True) + stem_files[stem_name] = str(dest) + + # Cleanup temp directory + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + # Cleanup on error + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# BS-RoFormer Chorus (Male/Female) (Python API) +# --------------------------------------------------------------------------- + +def _run_bsroformer_chorus( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, + batch_size_override: Optional[int] = None, + num_overlap_override: Optional[int] = None, +) -> Dict[str, str]: + """ + Run BS-RoFormer Chorus separation (male/female/instrumental). + Returns dict mapping stem names to file paths. + """ + from .bs_roformer_chorus_separator import BSRoformerChorusSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress="Loading BS-RoFormer Chorus model...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = BSRoformerChorusSeparator( + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating male/female chorus... (this may take a while)") + + temp_out = JOBS_DIR / job_id / "bsr_chorus_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts( + input_path, str(temp_out), + batch_size_override=batch_size_override, + num_overlap_override=num_overlap_override, + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=stem_name.capitalize(), copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# MelBand Vocals (Python API) +# --------------------------------------------------------------------------- + +def _run_mel_band_vocals( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, + batch_size_override: Optional[int] = None, + num_overlap_override: Optional[int] = None, +) -> Dict[str, str]: + """Run MelBand Vocals separation (vocals/instrumental).""" + # Route to appropriate separator based on model variant + if model == 'mel_band_vocals_anvuew': + from .mel_band_specialized_separator import MelBandVocalsAnvuewSeparator + sep_class = MelBandVocalsAnvuewSeparator + model_name = "MelBand Vocals Anvuew" + else: + from .mel_band_specialized_separator import MelBandVocalsSeparator + sep_class = MelBandVocalsSeparator + model_name = "MelBand Vocals" + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading {model_name} model...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = sep_class( + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating vocals with MelBand...") + + temp_out = JOBS_DIR / job_id / "mel_band_vocals_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts( + input_path, str(temp_out), + batch_size_override=batch_size_override, + num_overlap_override=num_overlap_override, + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=stem_name.capitalize(), copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# MelBand Dereverb (Python API) +# --------------------------------------------------------------------------- + +def _run_mel_band_dereverb( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, + batch_size_override: Optional[int] = None, + num_overlap_override: Optional[int] = None, +) -> Dict[str, str]: + """Run MelBand Dereverb separation (dry vocals/reverb).""" + # Route to appropriate separator based on model variant + if model == 'mel_band_dereverb_room': + from .mel_band_specialized_separator import MelBandDereverbRoomSeparator + sep_class = MelBandDereverbRoomSeparator + model_name = "MelBand Room Dereverb" + elif model == 'mel_band_dereverb_anvuew': + from .mel_band_specialized_separator import MelBandDereverbAnvuewSeparator + sep_class = MelBandDereverbAnvuewSeparator + model_name = "MelBand Dereverb Anvuew" + else: + from .mel_band_specialized_separator import MelBandDereverbSeparator + sep_class = MelBandDereverbSeparator + model_name = "MelBand Dereverb" + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading {model_name} model...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = sep_class( + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Removing reverb with MelBand...") + + temp_out = JOBS_DIR / job_id / "mel_band_dereverb_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts( + input_path, str(temp_out), + batch_size_override=batch_size_override, + num_overlap_override=num_overlap_override, + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + # Map internal names to display names + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# MelBand Karaoke (Lead/Back) (Python API) +# --------------------------------------------------------------------------- + +def _run_mel_band_karaoke( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, + batch_size_override: Optional[int] = None, + num_overlap_override: Optional[int] = None, +) -> Dict[str, str]: + """Run MelBand Karaoke separation (lead vocals/backing+instrumental).""" + # Route to appropriate separator based on model variant + if model == 'mel_band_karaoke_gabox': + from .mel_band_specialized_separator import MelBandKaraokeGaboxSeparator + sep_class = MelBandKaraokeGaboxSeparator + model_name = "MelBand Karaoke Gabox" + else: + from .mel_band_specialized_separator import MelBandKaraokeSeparator + sep_class = MelBandKaraokeSeparator + model_name = "MelBand Karaoke" + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading {model_name} model...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = sep_class( + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating lead/backing vocals...") + + temp_out = JOBS_DIR / job_id / "mel_band_karaoke_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts( + input_path, str(temp_out), + batch_size_override=batch_size_override, + num_overlap_override=num_overlap_override, + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + # Map internal names to display names + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# MDX-Net (ONNX) (Python API) +# --------------------------------------------------------------------------- + +def _run_mdxnet( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """ + Run MDX-Net separation using ONNX models. + Returns dict mapping stem names to file paths. + """ + from .mdxnet_separator import MDXNetSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading MDX-Net model ({model})...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = MDXNetSeparator( + model_id=model, + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating with MDX-Net...") + + temp_out = JOBS_DIR / job_id / "mdxnet_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# MelBand RoFormer (Python API) +# --------------------------------------------------------------------------- + +def _run_mel_band_roformer( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, + batch_size_override: Optional[int] = None, + num_overlap_override: Optional[int] = None, +) -> Dict[str, str]: + """ + Run MelBand RoFormer separation. Returns dict mapping stem names to file paths. + """ + from .mel_band_roformer_separator import MelBandRoformerSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress="Loading MelBand RoFormer model...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = MelBandRoformerSeparator( + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating with MelBand RoFormer... (this may take a while)") + + # Use a temp directory then move to project + temp_out = JOBS_DIR / job_id / "mel_band_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts( + input_path, str(temp_out), + batch_size_override=batch_size_override, + num_overlap_override=num_overlap_override, + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + # Move to project stems folder with proper naming + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=stem_name.capitalize(), copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + # Cleanup temp directory + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + # Cleanup on error + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# BS-RoFormer (Python API) +# --------------------------------------------------------------------------- + +def _run_bsroformer( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, + batch_size_override: Optional[int] = None, + num_overlap_override: Optional[int] = None, +) -> Dict[str, str]: + """ + Run BS-RoFormer separation. Returns dict mapping stem names to file paths. + """ + from .bs_roformer_separator import BSRoformerSeparator + + stem_mode = BSR_STEM_MODE.get(model, '4stem') + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading BS-RoFormer ({stem_mode}) model...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = BSRoformerSeparator( + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + stem_mode=stem_mode, + ) + + jm.update_job(job_id, progress="Separating with BS-RoFormer... (this may take a while)") + + # Use a temp directory then move to project + temp_out = JOBS_DIR / job_id / "bsr_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts( + input_path, str(temp_out), + batch_size_override=batch_size_override, + num_overlap_override=num_overlap_override, + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + # Move to project stems folder with proper naming + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=stem_name.capitalize(), copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + # Cleanup temp directory + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + # Cleanup on error + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# MelBand RoFormer Deux Becruily (Python API) +# --------------------------------------------------------------------------- + +def _run_mel_band_deux_becruily( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, + batch_size_override: Optional[int] = None, + num_overlap_override: Optional[int] = None, +) -> Dict[str, str]: + """Run MelBand RoFormer Deux Becruily separation (2-stem vocals).""" + from .mel_band_specialized_separator import MelBandDeuxBecruilySeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress="Loading MelBand Deux Becruily model...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = MelBandDeuxBecruilySeparator( + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating with Deux Becruily...") + + temp_out = JOBS_DIR / job_id / "mel_band_deux_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts( + input_path, str(temp_out), + batch_size_override=batch_size_override, + num_overlap_override=num_overlap_override, + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=stem_name.capitalize(), copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# SCNet XL (Python API) +# --------------------------------------------------------------------------- + +def _run_scnet( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """Run SCNet XL separation (state-of-the-art 2024-2025).""" + from .scnet_separator import SCNetSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading SCNet model ({model})...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = SCNetSeparator( + model_id=model, + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating with SCNet... (this may take a while)") + + temp_out = JOBS_DIR / job_id / "scnet_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# BS-RoFormer SW (Swin Transformer variant) (Python API) +# --------------------------------------------------------------------------- + +def _run_bsroformer_sw( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """Run BS-RoFormer SW (Swin Transformer) separation (6-stem).""" + from .bs_roformer_sw_separator import BSRoformerSWSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress="Loading BS-RoFormer SW model...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = BSRoformerSWSeparator( + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating with BS-RoFormer SW... (this may take a while)") + + temp_out = JOBS_DIR / job_id / "bsr_sw_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# MedleyVox (HuggingFace) (Python API) +# --------------------------------------------------------------------------- + +def _run_medleyvox( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """Run MedleyVox separation (multi-singer vocal separation).""" + from .medleyvox_separator import MedleyVoxSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading MedleyVox model ({model})...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = MedleyVoxSeparator( + model_id=model, + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating with MedleyVox...") + + temp_out = JOBS_DIR / job_id / "medleyvox_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# Apollo (Vocal Enhancement/Reverb Removal) (Python API) +# --------------------------------------------------------------------------- + +def _run_apollo( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """Run Apollo vocal enhancement/reverb removal.""" + from .apollo_separator import ApolloSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading Apollo model ({model})...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = ApolloSeparator( + model_id=model, + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Processing with Apollo...") + + temp_out = JOBS_DIR / job_id / "apollo_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# Aspiration (Breath/Aspiration Removal) (Python API) +# --------------------------------------------------------------------------- + +def _run_aspiration( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """Run Aspiration removal (breath/aspiration separation).""" + from .aspiration_separator import AspirationSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading Aspiration model ({model})...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = AspirationSeparator( + model_id=model, + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Removing aspiration with MelBand...") + + temp_out = JOBS_DIR / job_id / "aspiration_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# Bandit-v2 (Multi-Language/Multi-Stem) (Python API) +# --------------------------------------------------------------------------- + +def _run_bandit( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """Run Bandit-v2 separation (multi-language/multi-stem).""" + from .bandit_separator import BanditSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading Bandit model ({model})...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = BanditSeparator( + model_id=model, + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating with Bandit-v2...") + + temp_out = JOBS_DIR / job_id / "bandit_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise + + +# --------------------------------------------------------------------------- +# Ensemble (Combines Multiple Models) (Python API) +# --------------------------------------------------------------------------- + +def _run_ensemble( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """ + Run Ensemble separation (combines multiple models for best quality). + + Models combined: + - ensemble_vocal_best: BS Roformer x2 + MelBand Roformer ft + SCNet XL IHF + - ensemble_4stem: Multiple 4-stem models averaged + - ensemble_6stem: Multiple 6-stem models averaged + """ + from .ensemble_separator import EnsembleSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading Ensemble models ({model})...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = EnsembleSeparator( + ensemble_id=model, + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Running Ensemble separation... (this will take significantly longer)") + + temp_out = JOBS_DIR / job_id / "ensemble_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except: + pass + raise diff --git a/backend/config.py b/backend/config.py index 29e814d..afb138e 100755 --- a/backend/config.py +++ b/backend/config.py @@ -34,6 +34,12 @@ BANDIT_MODEL_DIR = Path(os.environ.get("BANDIT_MODEL_DIR", "/opt/bandit_models") # Aspiration model directory ASPIRATION_MODEL_DIR = Path(os.environ.get("ASPIRATION_MODEL_DIR", "/opt/aspiration_models")) +# SepACap model directory (a cappella multi-singer separation) +SEPACAP_MODEL_DIR = Path(os.environ.get("SEPACAP_MODEL_DIR", "/opt/sepacap_models")) + +# SepReformer model directory (2-speaker speech separation) +SEPREFORMER_MODEL_DIR = Path(os.environ.get("SEPREFORMER_MODEL_DIR", "/opt/sepreformer_models")) + # Ensemble mode cache directory ENSEMBLE_CACHE_DIR = Path(os.environ.get("ENSEMBLE_CACHE_DIR", "/app/media/ensemble_cache")) @@ -123,6 +129,19 @@ BANDIT_MODELS = [ {"id": "bandit_v2_eng", "label": "Bandit v2 English", "group": "Bandit"}, ] +# SepACap models (a cappella multi-singer vocal separation -- 7 stems) +SEPACAP_MODELS = [ + {"id": "sepacap", "label": "SepACap (7-stem A Cappella)", "group": "SepACap"}, +] + +# SepReformer models (2-speaker speech separation -- NeurIPS 2024) +SEPREFORMER_MODELS = [ + {"id": "sepreformer_base", "label": "SepReformer Base (Speech, WSJ0)", "group": "SepReformer"}, + {"id": "sepreformer_large_wsj0", "label": "SepReformer Large (Speech, WSJ0)", "group": "SepReformer"}, + {"id": "sepreformer_large_wham", "label": "SepReformer Large (Noisy Speech, WHAM)", "group": "SepReformer"}, + {"id": "sepreformer_large_whamr", "label": "SepReformer Large (Noisy+Reverb, WHAMR)", "group": "SepReformer"}, +] + # Ensemble modes (combines multiple models for best quality) ENSEMBLE_MODELS = [ {"id": "ensemble_vocal_best", "label": "Ensemble - Vocal Best Quality", "group": "Ensemble"}, @@ -142,6 +161,8 @@ ALL_MODELS = ( APOLLO_MODELS + ASPIRATION_MODELS + BANDIT_MODELS + + SEPACAP_MODELS + + SEPREFORMER_MODELS + ENSEMBLE_MODELS ) DEFAULT_DEMUCS_MODEL = "htdemucs" @@ -233,6 +254,15 @@ STEM_LABELS = { "instrumental": "Instrumental", "dry_vocals": "Dry Vocals", "reverb": "Reverb", + # SepACap a cappella stems + "alto": "Alto", + "soprano": "Soprano", + "tenor": "Tenor", + "finger_snap": "Finger Snap", + "vocal_percussion": "Vocal Percussion", + # SepReformer speech stems + "speaker_1": "Speaker 1", + "speaker_2": "Speaker 2", } # --------------------------------------------------------------------------- diff --git a/backend/routers/models.py b/backend/routers/models.py index 0f797f7..2e202ec 100755 --- a/backend/routers/models.py +++ b/backend/routers/models.py @@ -24,6 +24,8 @@ from ..config import ( APOLLO_MODEL_DIR, ASPIRATION_MODEL_DIR, BANDIT_MODEL_DIR, + SEPACAP_MODEL_DIR, + SEPREFORMER_MODEL_DIR, ) router = APIRouter(prefix="/api/models", tags=["models"]) @@ -428,6 +430,13 @@ MODEL_EXACT_DIRS: Dict[str, Path] = { # ── Bandit (per-model subdir) ── "bandit_v2_multi": BANDIT_MODEL_DIR / "bandit_v2_multi", "bandit_v2_eng": BANDIT_MODEL_DIR / "bandit_v2_eng", + # -- SepACap (flat model dir) -- + "sepacap": SEPACAP_MODEL_DIR, + # -- SepReformer (weights bundled via git-lfs in the cloned repo) -- + "sepreformer_base": SEPREFORMER_MODEL_DIR / "sepreformer_base", + "sepreformer_large_wsj0": SEPREFORMER_MODEL_DIR / "sepreformer_large_wsj0", + "sepreformer_large_wham": SEPREFORMER_MODEL_DIR / "sepreformer_large_wham", + "sepreformer_large_whamr": SEPREFORMER_MODEL_DIR / "sepreformer_large_whamr", } diff --git a/backend/services/sepacap_separator.py b/backend/services/sepacap_separator.py new file mode 100644 index 0000000..e664de7 --- /dev/null +++ b/backend/services/sepacap_separator.py @@ -0,0 +1,224 @@ +""" +SepACap separator — a cappella multi-singer vocal stem separation. + +Architecture from ETH-DISCO/SepACap (MIT licence), cloned on first use. +Weights hosted at Tino3141/sepacap on HuggingFace (161 MB). + +Separates a cappella recordings into 7 independent vocal stems: + alto, bass, finger_snap, lead_vocal, soprano, tenor, vocal_percussion + +Sample rate: 24 kHz — input audio is automatically resampled. +""" +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Dict, Optional + +import torch +import torchaudio +import yaml + +from ..config import SEPACAP_MODEL_DIR, CPU_SEPARATION + + +# Stems in the exact order the model outputs them (matches num_spks=7 in config) +SEPACAP_STEMS = [ + "alto", + "bass", + "finger_snap", + "lead_vocal", + "soprano", + "tenor", + "vocal_percussion", +] + +SAMPLE_RATE = 24_000 +HF_REPO = "Tino3141/sepacap" +CHECKPOINT = "SepACap.pth" +CONFIG_FILE = "modelMusicSep.yaml" +GITHUB_REPO = "https://github.com/ETH-DISCO/SepACap.git" +_REPO_DIR = Path("/opt/sepacap_repo") +_DEPS = ["einops", "julius", "loguru"] + + +# --------------------------------------------------------------------------- +# One-time setup helpers +# --------------------------------------------------------------------------- + +def _ensure_deps() -> None: + """Install lightweight runtime deps if not already available.""" + missing = [] + for pkg in _DEPS: + try: + __import__(pkg) + except ImportError: + missing.append(pkg) + if missing: + print(f"[SepACap] Installing missing packages: {missing}") + subprocess.run( + [sys.executable, "-m", "pip", "install", *missing], + check=True, + ) + + +def _ensure_repo() -> None: + """Shallow-clone the SepACap GitHub repo for its model architecture code.""" + if _REPO_DIR.exists(): + return + _REPO_DIR.parent.mkdir(parents=True, exist_ok=True) + print(f"[SepACap] Cloning architecture code from {GITHUB_REPO} …") + subprocess.run( + ["git", "clone", "--depth=1", GITHUB_REPO, str(_REPO_DIR)], + check=True, + ) + + +def _ensure_sys_path() -> None: + _ensure_deps() + _ensure_repo() + repo_str = str(_REPO_DIR) + if repo_str not in sys.path: + sys.path.insert(0, repo_str) + + +# --------------------------------------------------------------------------- +# Audio helpers +# --------------------------------------------------------------------------- + +def _load_audio(path: str) -> torch.Tensor: + """Load audio → mono, resample to 24 kHz. Returns (1, N) float32.""" + waveform, sr = torchaudio.load(path) + if sr != SAMPLE_RATE: + waveform = torchaudio.functional.resample(waveform, sr, SAMPLE_RATE) + if waveform.shape[0] > 1: + waveform = waveform.mean(dim=0, keepdim=True) + return waveform + + +def _save_audio(path: str, audio: torch.Tensor, fmt: str) -> None: + """Save a (1, N) CPU tensor.""" + audio = audio.cpu() + f = fmt.lower() + if f.startswith("mp3"): + torchaudio.save(path, audio, SAMPLE_RATE, format="mp3") + elif f == "flac": + torchaudio.save(path, audio, SAMPLE_RATE, format="flac") + else: + torchaudio.save(path, audio, SAMPLE_RATE) + + +# --------------------------------------------------------------------------- +# Separator +# --------------------------------------------------------------------------- + +class SepACapSeparator: + """ + Native PyTorch inference wrapper for SepACap a cappella vocal separation. + + Separates mixed a cappella recordings into 7 independent vocal stems: + alto, bass, finger snap, lead vocal, soprano, tenor, and vocal percussion. + + Architecture: adapted SepReformer with periodic activations and composite + loss — state-of-the-art on the JaCappella benchmark (NeurIPS 2025). + Architecture code is cloned from GitHub on first use (~3 MB shallow clone). + """ + + def __init__( + self, + cpu_separation: bool = CPU_SEPARATION, + output_format: str = "mp3", + mp3_bitrate: str = "256k", + ): + self.cpu_separation = cpu_separation + self.output_format = output_format + self.mp3_bitrate = mp3_bitrate + self.device = torch.device( + "cpu" if cpu_separation else ("cuda" if torch.cuda.is_available() else "cpu") + ) + self._model = None + + # ------------------------------------------------------------------ + + def _ensure_files(self) -> tuple[Path, Path]: + """Download checkpoint and config from HuggingFace if missing.""" + from huggingface_hub import hf_hub_download + + model_dir = SEPACAP_MODEL_DIR + model_dir.mkdir(parents=True, exist_ok=True) + + ckpt = model_dir / CHECKPOINT + cfg = model_dir / CONFIG_FILE + + for fname, dest in [(CHECKPOINT, ckpt), (CONFIG_FILE, cfg)]: + if not dest.exists(): + print(f"[SepACap] Downloading {fname} from {HF_REPO} …") + cached = hf_hub_download(repo_id=HF_REPO, filename=fname) + shutil.copy2(cached, dest) + + return ckpt, cfg + + def _load_model(self) -> None: + _ensure_sys_path() + ckpt, cfg_path = self._ensure_files() + + with open(cfg_path) as f: + raw = yaml.full_load(f) + model_cfg = raw["config"]["model"] + + from src.model import Model # available after sys.path insert + + model = Model(**model_cfg) + state = torch.load(str(ckpt), map_location="cpu", weights_only=False) + if isinstance(state, dict) and "model_state" in state: + state = state["model_state"] + elif isinstance(state, dict) and "state_dict" in state: + state = state["state_dict"] + model.load_state_dict(state, strict=False) + model.eval() + self._model = model.to(self.device) + + def _get_model(self): + if self._model is None: + self._load_model() + return self._model + + # ------------------------------------------------------------------ + + def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]: + """ + Separate an a cappella recording into 7 vocal stems. + + Returns: + Dict mapping stem name → absolute output file path. + """ + model = self._get_model() + audio = _load_audio(input_path).to(self.device) # (1, N) + orig_len = audio.shape[-1] + + print(f"[SepACap] Running inference on {self.device} …") + with torch.no_grad(): + separated, _ = model(audio) + # separated: list of num_spks tensors, each approx (1, N) + + out_dir = Path(output_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + ext = self.output_format.lower() + if ext.startswith("mp3"): + ext = "mp3" + + output_paths: Dict[str, str] = {} + for i, stem_name in enumerate(SEPACAP_STEMS): + if i >= len(separated): + break + stem_audio = separated[i].cpu() + # Trim to original input length + if stem_audio.shape[-1] > orig_len: + stem_audio = stem_audio[..., :orig_len] + out_path = str(out_dir / f"{stem_name}.{ext}") + _save_audio(out_path, stem_audio, ext) + output_paths[stem_name] = out_path + print(f"[SepACap] Saved {stem_name} → {out_path}") + + return output_paths diff --git a/backend/services/separator_service.py b/backend/services/separator_service.py index 92a9270..a4a35ca 100755 --- a/backend/services/separator_service.py +++ b/backend/services/separator_service.py @@ -17,7 +17,7 @@ from ..config import ( PROJECTS_DIR, JOBS_DIR, CPU_SEPARATION, PROJECT_SUBFOLDERS, ALL_MODELS, OUTPUT_FORMATS, MEL_BAND_MODELS, BS_ROFORMER_SPECIALIZED_MODELS, MDXNET_MODELS, SCNET_MODELS, MEDLEYVOX_MODELS, ENSEMBLE_MODELS, APOLLO_MODELS, ASPIRATION_MODELS, BANDIT_MODELS, - BS_ROFORMER_SW_MODELS + BS_ROFORMER_SW_MODELS, SEPACAP_MODELS, SEPREFORMER_MODELS ) from .metadata_util import copy_metadata, read_metadata from .project_namer import project_name, make_project_dirs @@ -96,6 +96,12 @@ BANDIT_MODEL_IDS = {m['id'] for m in BANDIT_MODELS} # Ensemble model IDs ENSEMBLE_MODEL_IDS = {m['id'] for m in ENSEMBLE_MODELS} +# SepACap model IDs +SEPACAP_MODEL_IDS = {m['id'] for m in SEPACAP_MODELS} + +# SepReformer model IDs +SEPREFORMER_MODEL_IDS = {m['id'] for m in SEPREFORMER_MODELS} + # --------------------------------------------------------------------------- # Separation power presets # --------------------------------------------------------------------------- @@ -421,6 +427,18 @@ def run_separation( mp3_bitrate=mp3_bitrate, metadata=metadata, stem_prefix=proj_name, ) + elif model in SEPACAP_MODEL_IDS: + stem_files = _run_sepacap( + job_id, input_path, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + ) + elif model in SEPREFORMER_MODEL_IDS: + stem_files = _run_sepreformer( + job_id, input_path, model, normalised_format, stems_dir, + mp3_bitrate=mp3_bitrate, metadata=metadata, + stem_prefix=proj_name, + ) else: stem_files = _run_demucs( job_id, input_path, model, output_format, stems_dir, @@ -1829,3 +1847,139 @@ def _run_ensemble( except: pass raise + + +# --------------------------------------------------------------------------- +# SepACap (A Cappella Multi-Singer Vocal Separation) (Python API) +# --------------------------------------------------------------------------- + +def _run_sepacap( + job_id: str, + input_path: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """Run SepACap a cappella vocal separation into 7 stems.""" + from .sepacap_separator import SepACapSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress="Loading SepACap model (clones repo + downloads weights on first use)...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = SepACapSeparator( + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating a cappella vocals with SepACap... (this may take a while)") + + temp_out = JOBS_DIR / job_id / "sepacap_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except Exception: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except Exception: + pass + raise + + +# --------------------------------------------------------------------------- +# SepReformer (2-Speaker Speech Separation) (Python API) +# --------------------------------------------------------------------------- + +def _run_sepreformer( + job_id: str, + input_path: str, + model: str, + output_format: str, + stems_dir: Path, + mp3_bitrate: str = '256k', + metadata: Optional[Dict] = None, + stem_prefix: Optional[str] = None, +) -> Dict[str, str]: + """Run SepReformer 2-speaker speech separation.""" + from .sepreformer_separator import SepReformerSeparator + + jm.update_job( + job_id, status=jm.JobStatus.RUNNING, + progress=f"Loading SepReformer model ({model}) — clones repo on first use...", + ) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + sep = SepReformerSeparator( + model_id=model, + cpu_separation=CPU_SEPARATION, + output_format=output_format, + mp3_bitrate=mp3_bitrate, + ) + + jm.update_job(job_id, progress="Separating speakers with SepReformer...") + + temp_out = JOBS_DIR / job_id / "sepreformer_out" + temp_out.mkdir(parents=True, exist_ok=True) + + try: + stem_paths = sep.separate_into_parts(input_path, str(temp_out)) + + if jm.should_cancel(job_id): + raise RuntimeError("Cancelled by user") + + _prefix = stem_prefix or Path(input_path).stem + stem_files = {} + + for stem_name, path in sorted(stem_paths.items()): + src = Path(path) + display_name = stem_name.replace('_', ' ').title() + dest = stems_dir / _stem_filename(_prefix, stem_name, src.suffix) + shutil.move(str(src), str(dest)) + copy_metadata(input_path, str(dest), stem_label=display_name, copy_lyrics=True) + stem_files[stem_name.lower()] = str(dest) + + try: + shutil.rmtree(temp_out, ignore_errors=True) + except Exception: + pass + + return stem_files + + except Exception: + try: + shutil.rmtree(temp_out, ignore_errors=True) + except Exception: + pass + raise diff --git a/backend/services/sepreformer_separator.py b/backend/services/sepreformer_separator.py new file mode 100644 index 0000000..2a9c53f --- /dev/null +++ b/backend/services/sepreformer_separator.py @@ -0,0 +1,258 @@ +""" +SepReformer separator — 2-speaker speech separation. + +Architecture and weights from dmlguq456/SepReformer (NeurIPS 2024). +Weights are bundled in the repository via Git LFS. + +Requires git-lfs to be installed in the container: + apt-get install git-lfs +Add to Dockerfile: RUN apt-get install -y git-lfs + +Separates 2-speaker mixed audio into: + speaker_1, speaker_2 + +Sample rate: 8 kHz — input audio is automatically resampled. + +Available model variants: + sepreformer_base — WSJ0-2Mix (clean speech) + sepreformer_large_wsj0 — WSJ0-2Mix large (clean speech) + sepreformer_large_wham — WHAM! (noisy speech) + sepreformer_large_whamr — WHAMR! (noisy + reverberant speech) +""" +import importlib.util +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Dict, Optional + +import torch +import torchaudio +import yaml + +from ..config import SEPREFORMER_MODEL_DIR, CPU_SEPARATION + + +SAMPLE_RATE = 8_000 +GITHUB_REPO = "https://github.com/dmlguq456/SepReformer.git" +_REPO_DIR = Path("/opt/sepreformer_repo") + +# Map our model IDs → repo directory names under models/ +_MODEL_DIRS = { + "sepreformer_base": "SepReformer_Base_WSJ0", + "sepreformer_large_wsj0": "SepReformer_Large_DM_WSJ0", + "sepreformer_large_wham": "SepReformer_Large_DM_WHAM", + "sepreformer_large_whamr": "SepReformer_Large_DM_WHAMR", +} + +_STEM_NAMES = ["speaker_1", "speaker_2"] + + +# --------------------------------------------------------------------------- +# One-time setup +# --------------------------------------------------------------------------- + +def _check_git_lfs() -> None: + try: + subprocess.run(["git", "lfs", "version"], check=True, capture_output=True) + except (subprocess.CalledProcessError, FileNotFoundError): + raise RuntimeError( + "git-lfs is required for SepReformer but is not installed.\n" + "Install it with: apt-get install git-lfs\n" + "Then add the following line to your Dockerfile:\n" + " RUN apt-get install -y git-lfs" + ) + + +def _ensure_repo() -> None: + """Clone SepReformer repo with Git LFS (includes pretrained weights).""" + if _REPO_DIR.exists(): + return + _check_git_lfs() + _REPO_DIR.parent.mkdir(parents=True, exist_ok=True) + print(f"[SepReformer] Cloning {GITHUB_REPO} with LFS weights …") + subprocess.run(["git", "lfs", "install"], check=True) + subprocess.run( + ["git", "clone", GITHUB_REPO, str(_REPO_DIR)], + check=True, + ) + + +# --------------------------------------------------------------------------- +# Dynamic model loading — each variant has its own model.py +# --------------------------------------------------------------------------- + +def _import_model_class(model_name: str): + """Import the Model class from the specific variant's model.py.""" + model_py = _REPO_DIR / "models" / model_name / "model.py" + if not model_py.exists(): + raise FileNotFoundError( + f"SepReformer model file not found: {model_py}\n" + "Ensure the repository was cloned with git-lfs." + ) + # Add both the repo root and the model-specific dir to sys.path for internal imports + for p in [str(_REPO_DIR), str(_REPO_DIR / "models" / model_name)]: + if p not in sys.path: + sys.path.insert(0, p) + + spec = importlib.util.spec_from_file_location( + f"sepreformer_{model_name}_model", str(model_py) + ) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod.Model + + +# --------------------------------------------------------------------------- +# Audio helpers +# --------------------------------------------------------------------------- + +def _load_audio_mono(path: str) -> torch.Tensor: + """Load audio, mix to mono, resample to 8 kHz. Returns (1, N) float32.""" + waveform, sr = torchaudio.load(path) + if waveform.shape[0] > 1: + waveform = waveform.mean(dim=0, keepdim=True) + if sr != SAMPLE_RATE: + waveform = torchaudio.functional.resample(waveform, sr, SAMPLE_RATE) + return waveform + + +def _save_audio(path: str, audio: torch.Tensor, fmt: str) -> None: + audio = audio.cpu() + f = fmt.lower() + if f.startswith("mp3"): + torchaudio.save(path, audio, SAMPLE_RATE, format="mp3") + elif f == "flac": + torchaudio.save(path, audio, SAMPLE_RATE, format="flac") + else: + torchaudio.save(path, audio, SAMPLE_RATE) + + +# --------------------------------------------------------------------------- +# Separator +# --------------------------------------------------------------------------- + +class SepReformerSeparator: + """ + Native PyTorch inference wrapper for SepReformer 2-speaker speech separation. + + Separates a mixed audio signal containing two speakers into individual + speaker streams. Best suited for speech signals (8 kHz). + + Architecture code and pretrained weights are cloned from GitHub on + first use (requires git-lfs). + """ + + def __init__( + self, + model_id: str = "sepreformer_base", + cpu_separation: bool = CPU_SEPARATION, + output_format: str = "mp3", + mp3_bitrate: str = "256k", + ): + if model_id not in _MODEL_DIRS: + raise ValueError( + f"Unknown SepReformer model: {model_id}. " + f"Available: {list(_MODEL_DIRS)}" + ) + self.model_id = model_id + self.model_name = _MODEL_DIRS[model_id] + self.cpu_separation = cpu_separation + self.output_format = output_format + self.mp3_bitrate = mp3_bitrate + self.device = torch.device( + "cpu" if cpu_separation else ("cuda" if torch.cuda.is_available() else "cpu") + ) + self._model = None + self._config = None + + # ------------------------------------------------------------------ + + def _load_model(self) -> None: + _ensure_repo() + cfg_path = _REPO_DIR / "models" / self.model_name / "configs.yaml" + if not cfg_path.exists(): + raise FileNotFoundError( + f"SepReformer config not found: {cfg_path}\n" + "The repository may not have cloned correctly." + ) + with open(cfg_path) as f: + config = yaml.safe_load(f) + self._config = config + + Model = _import_model_class(self.model_name) + model = Model(**config["model"]) + + # Find the checkpoint file in log/scratch_weights/ + weights_dir = _REPO_DIR / "models" / self.model_name / "log" / "scratch_weights" + ckpt_files = sorted(weights_dir.glob("*.pth")) + sorted(weights_dir.glob("*.ckpt")) + if not ckpt_files: + raise FileNotFoundError( + f"No checkpoint found in {weights_dir}.\n" + "Ensure the repo was cloned with git-lfs active (git lfs pull)." + ) + ckpt_path = ckpt_files[-1] # Use the latest checkpoint + print(f"[SepReformer] Loading checkpoint: {ckpt_path.name}") + + state = torch.load(str(ckpt_path), map_location="cpu", weights_only=False) + if isinstance(state, dict) and "model" in state: + state = state["model"] + elif isinstance(state, dict) and "state_dict" in state: + state = state["state_dict"] + model.load_state_dict(state, strict=False) + model.eval() + self._model = model.to(self.device) + + def _get_model(self): + if self._model is None: + self._load_model() + return self._model + + # ------------------------------------------------------------------ + + def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]: + """ + Separate 2-speaker mixed audio into individual speaker streams. + + Returns: + Dict mapping stem name → absolute output file path. + """ + model = self._get_model() + config = self._config + audio = _load_audio_mono(input_path).to(self.device) # (1, N) + orig_len = audio.shape[-1] + + # Pad to encoder stride boundary + stride = config["model"]["module_audio_enc"]["stride"] + remains = audio.shape[-1] % stride + if remains != 0: + audio = torch.nn.functional.pad(audio, (0, stride - remains)) + + print(f"[SepReformer] Running {self.model_name} on {self.device} …") + with torch.inference_mode(): + estim_src, _ = model(audio) + # estim_src: list of num_spks tensors + + out_dir = Path(output_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + ext = self.output_format.lower() + if ext.startswith("mp3"): + ext = "mp3" + num_spks = config["model"].get("num_spks", 2) + + output_paths: Dict[str, str] = {} + for i, stem_name in enumerate(_STEM_NAMES[:num_spks]): + if i >= len(estim_src): + break + src = estim_src[i].cpu() + if src.shape[-1] > orig_len: + src = src[..., :orig_len] + if src.dim() == 1: + src = src.unsqueeze(0) + out_path = str(out_dir / f"{stem_name}.{ext}") + _save_audio(out_path, src, ext) + output_paths[stem_name] = out_path + print(f"[SepReformer] Saved {stem_name} → {out_path}") + + return output_paths