Files
2026-04-14 16:32:36 +09:00

151 lines
5.4 KiB
Python
Executable File

"""
Bandit-v2 separator - Multi-language/multi-stem separation.
Uses `audio-separator`, but now binds deterministically to the requested
checkpoint/config pair instead of relying on package defaults.
"""
import shutil
import logging
from pathlib import Path
from typing import Dict
from ..config import BANDIT_MODEL_DIR, CPU_SEPARATION
from .audio_separator_util import create_separator, load_explicit_model, map_and_rename_outputs
log = logging.getLogger(__name__)
# Model configurations
BANDIT_MODELS = {
"bandit_v2_multi": {
"model_path": "checkpoint-multi_state_dict.ckpt",
"config_path": "config_dnr_bandit_v2_mus64.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Bandit-v2",
"stems": ["vocals", "drums", "bass", "other"],
"language": "multi",
},
"bandit_v2_eng": {
"model_path": "checkpoint-eng_state_dict.ckpt",
"config_path": "config_dnr_bandit_v2_mus64.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Bandit-v2",
"stems": ["vocals", "drums", "bass", "other"],
"language": "english",
},
# Additional language models available:
# - checkpoint-cmn_state_dict.ckpt (Chinese)
# - checkpoint-deu_state_dict.ckpt (German)
# - checkpoint-fao_state_dict.ckpt (Faroese)
# - checkpoint-fra_state_dict.ckpt (French)
# - checkpoint-spa_state_dict.ckpt (Spanish)
}
class BanditSeparator:
"""
Bandit-v2 separator for multi-language/multi-stem separation.
Bandit models are trained on different languages and provide
high-quality separation optimized for specific language characteristics.
"""
def __init__(
self,
model_id: str = "bandit_v2_multi",
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if model_id not in BANDIT_MODELS:
raise ValueError(f"Unknown Bandit model: {model_id}")
self.model_id = model_id
self.model_config = BANDIT_MODELS[model_id]
self.cpu_separation = cpu_separation
self.output_format = output_format
self.mp3_bitrate = mp3_bitrate
self._model = None
def _ensure_model(self):
"""Download model from HuggingFace if not present."""
model_dir = BANDIT_MODEL_DIR / self.model_id
model_dir.mkdir(parents=True, exist_ok=True)
model_path = model_dir / self.model_config["model_path"]
config_path = model_dir / self.model_config["config_path"]
if not model_path.exists() or not config_path.exists():
try:
from huggingface_hub import hf_hub_download
log.info("Downloading Bandit model: %s", self.model_id)
if not model_path.exists():
cached = hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['model_path']}",
)
shutil.copy2(cached, model_path)
if not config_path.exists():
cached = hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['config_path']}",
)
shutil.copy2(cached, config_path)
except Exception as e:
raise RuntimeError(f"Failed to download Bandit model: {e}")
return str(model_path), str(config_path)
def _get_separator(self, output_dir: Path):
model_path, config_path = self._ensure_model()
separator = create_separator(
model_dir=Path(model_path).parent,
output_dir=output_dir,
output_format=self.output_format,
mp3_bitrate=self.mp3_bitrate,
)
load_explicit_model(
separator,
model_path=Path(model_path),
config_path=Path(config_path),
model_id=self.model_id,
)
return separator
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Separate audio into stems using Bandit-v2.
Returns:
Dict mapping stem names to output file paths
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
try:
sep = self._get_separator(output_path)
result = sep.separate(input_path)
stems = self.model_config.get("stems", ["vocals", "drums", "bass", "other"])
aliases = {
"vocals": ["vocals", "vocal", "voice"],
"drums": ["drums", "drum", "percussion"],
"bass": ["bass"],
"other": ["other", "accompaniment", "instrum", "instrumental"],
}
return map_and_rename_outputs(
result,
output_dir=output_path,
expected_stems=stems,
output_format=self.output_format,
aliases=aliases,
)
except ImportError:
raise ImportError(
"audio-separator is required for Bandit separation. "
"Install with: pip install audio-separator"
)