Added SepACap, SepReformer, verified power settings, slight change to settings navigation bar.

This commit is contained in:
seclusionenthusiast committed 2026-03-03 22:09:50 +09:00
1 parent cf4eae7847
commit 9672fd2d02
8 files changed
+3516 -1

No files matched your search

+265
View File
@@ -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)
+744
View File
@@ -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)
File diff suppressed because it is too large. Load diff
+30
View File
@@ -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",
}
# ---------------------------------------------------------------------------
+9
View File
@@ -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",
}
+224
View File
@@ -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
+155 -1
View File
@@ -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
+258
View File
@@ -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