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

368 lines
14 KiB
Python
Executable File

"""
Apollo separator - Vocal enhancement and reverb removal.
Uses `audio-separator`, but now binds deterministically to the downloaded
checkpoint/config pair instead of relying on package defaults.
"""
import shutil
import logging
import urllib.request
from pathlib import Path
from typing import Dict
from ..config import APOLLO_MODEL_DIR, CPU_SEPARATION
from .audio_separator_util import create_separator, load_explicit_model, map_and_rename_outputs
log = logging.getLogger(__name__)
_AUDIO_SEPARATOR_COMPAT_ALIAS_CKPT = "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
_AUDIO_SEPARATOR_COMPAT_ALIAS_YAML = "model_bs_roformer_ep_317_sdr_12.9755.yaml"
# Model configurations
APOLLO_MODELS = {
"apollo_lq": {
"model_path": "pytorch_model.bin",
"config_path": "config_apollo.yaml",
"hf_repo": "JusperLee/Apollo",
"hf_model_filename": "pytorch_model.bin",
"model_url": "https://huggingface.co/JusperLee/Apollo/resolve/main/pytorch_model.bin",
"config_url": "https://raw.githubusercontent.com/ZFTurbo/Music-Source-Separation-Training/refs/heads/main/configs/config_apollo.yaml",
"stems": ["vocals", "instrumental"],
"description": "Apollo LQ MP3 restoration (JusperLee)",
},
"apollo_vocal_enhancer": {
"model_path": "apollo_model.ckpt",
"config_path": "config_apollo_vocal.yaml",
"hf_repo": "jarredou/lew_apollo_vocal_enhancer",
"hf_model_filename": "apollo_model.ckpt",
"hf_config_filename": "config_apollo_vocal.yaml",
"stems": ["dry_vocals", "reverb"],
"description": "Apollo Vocal Enhancer (lew)",
},
"apollo_vocal_enhancer_v2": {
"model_path": "apollo_model_v2.ckpt",
"config_path": "config_apollo_vocal_v2.yaml",
"model_url": "https://shared.multimedia.workers.dev/download/1/other/apollo_model_v2.ckpt",
"config_url": "https://shared.multimedia.workers.dev/download/1/other/config_apollo_vocal_v2.yaml",
"stems": ["dry_vocals", "reverb"],
"description": "Apollo Vocal Enhancer V2 (WIP) (lew)",
},
}
class ApolloSeparator:
"""
Apollo separator for vocal enhancement and reverb removal.
Apollo models separate vocals into dry vocals and reverb,
useful for cleaning up vocal recordings.
"""
def __init__(
self,
model_id: str = "apollo_vocal_enhancer",
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if model_id not in APOLLO_MODELS:
raise ValueError(f"Unknown Apollo model: {model_id}")
self.model_id = model_id
self.model_config = APOLLO_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):
"""Ensure model and config exist locally (HuggingFace and/or direct URL)."""
model_dir = APOLLO_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 model_path.exists() and config_path.exists():
return str(model_path), str(config_path)
log.info("Downloading Apollo model: %s", self.model_id)
try:
if not model_path.exists():
self._download_artifact(
dest=model_path,
hf_repo=self.model_config.get("hf_repo"),
hf_filename=self.model_config.get("hf_model_filename"),
url=self.model_config.get("model_url"),
)
if not config_path.exists():
self._download_artifact(
dest=config_path,
hf_repo=self.model_config.get("hf_repo"),
hf_filename=self.model_config.get("hf_config_filename"),
url=self.model_config.get("config_url"),
)
except Exception as e:
raise RuntimeError(f"Failed to download Apollo model: {e}")
return str(model_path), str(config_path)
def _download_artifact(
self,
*,
dest: Path,
hf_repo: str | None,
hf_filename: str | None,
url: str | None,
) -> None:
"""Download one artifact either from HuggingFace or direct URL."""
if hf_repo and hf_filename:
try:
from huggingface_hub import hf_hub_download
cached = hf_hub_download(repo_id=hf_repo, filename=hf_filename)
shutil.copy2(cached, dest)
return
except Exception as exc:
if not url:
raise
log.warning(
"Apollo HF download failed for %s (%s); falling back to direct URL",
dest.name,
exc,
)
if url:
with urllib.request.urlopen(url, timeout=120) as resp, open(dest, "wb") as out:
shutil.copyfileobj(resp, out)
return
raise RuntimeError(
f"No download source configured for {dest.name} in model '{self.model_id}'"
)
def _convert_bin_to_ckpt(self, model_path: Path) -> Path:
"""
Convert a PyTorch .bin checkpoint into a ckpt-like container.
Some audio-separator Apollo runtimes accept only ckpt-oriented payloads.
This creates a deterministic sidecar file next to the original model.
"""
if model_path.suffix.lower() != ".bin":
raise ValueError(f"Expected .bin model path, got: {model_path.name}")
# Keep a deterministic filename for the known Apollo LQ case so logs,
# caches, and runbooks can reference one stable artifact path.
if self.model_id == "apollo_lq":
converted_path = model_path.with_name("apollo_lq_converted.ckpt")
else:
converted_path = model_path.with_suffix(".converted.ckpt")
if converted_path.exists():
return converted_path
try:
import torch
except Exception as exc:
raise RuntimeError(
"Unable to convert .bin model to .ckpt because torch is unavailable"
) from exc
obj = torch.load(str(model_path), map_location="cpu")
state_dict = None
if isinstance(obj, dict):
for key in ("state_dict", "model_state_dict", "model", "weights"):
candidate = obj.get(key)
if isinstance(candidate, dict) and candidate:
state_dict = candidate
break
if state_dict is None and obj:
# Common case: raw state_dict saved directly as the top-level dict.
state_dict = obj
else:
raise RuntimeError(
f"Unsupported .bin checkpoint payload type: {type(obj).__name__}"
)
payload = {"state_dict": state_dict}
if isinstance(obj, dict) and "hyper_parameters" in obj:
payload["hyper_parameters"] = obj.get("hyper_parameters")
torch.save(payload, str(converted_path))
return converted_path
def _verify_loaded_model_path(
self,
separator,
intended_model_path: Path,
*,
allowed_model_names: set[str] | None = None,
) -> None:
"""Verify the runtime actually bound to the intended checkpoint file."""
model_instance = getattr(separator, "model_instance", None)
loaded_path = getattr(model_instance, "model_path", None)
if not loaded_path:
raise RuntimeError(
"Apollo separator loaded without model_instance.model_path; "
"cannot verify bound checkpoint"
)
loaded = Path(str(loaded_path))
intended = intended_model_path
if loaded.name != intended.name and (
not allowed_model_names or loaded.name not in allowed_model_names
):
raise RuntimeError(
"Apollo separator bound a different checkpoint than requested: "
f"requested={intended.name} loaded={loaded.name}"
)
log.info(
"Apollo model binding verified: requested=%s loaded=%s",
intended.name,
loaded.name,
)
def _load_model_with_fallback(self, separator, model_path: Path, config_path: Path):
"""
Load model explicitly; if .bin fails, convert once to .converted.ckpt and retry.
"""
try:
load_explicit_model(
separator,
model_path=model_path,
config_path=config_path,
model_id=self.model_id,
)
self._verify_loaded_model_path(separator, model_path)
return model_path
except Exception as exc:
if model_path.suffix.lower() != ".bin":
raise
log.warning(
"Apollo model load failed for %s (%s); attempting .bin -> .ckpt fallback",
model_path.name,
exc,
)
converted = self._convert_bin_to_ckpt(model_path)
try:
load_explicit_model(
separator,
model_path=converted,
config_path=config_path,
model_id=self.model_id,
allowed_model_names={model_path.name},
)
self._verify_loaded_model_path(
separator,
converted,
allowed_model_names={model_path.name},
)
log.info("Apollo .bin fallback succeeded using converted checkpoint: %s", converted.name)
return converted
except Exception as converted_exc:
log.warning(
"Apollo converted checkpoint explicit-load failed (%s); attempting audio-separator compatibility alias",
converted_exc,
)
return self._load_model_via_compat_alias(
separator,
converted_model_path=converted,
config_path=config_path,
)
def _load_model_via_compat_alias(
self,
separator,
*,
converted_model_path: Path,
config_path: Path,
) -> Path:
"""
Fallback for audio-separator runtimes that only accept registered model filenames.
We materialize Apollo files under a known supported filename pair in this model's
isolated directory, then load by that filename.
"""
alias_model_path = converted_model_path.with_name(_AUDIO_SEPARATOR_COMPAT_ALIAS_CKPT)
alias_config_path = converted_model_path.with_name(_AUDIO_SEPARATOR_COMPAT_ALIAS_YAML)
if not alias_model_path.exists():
shutil.copy2(converted_model_path, alias_model_path)
if not alias_config_path.exists():
shutil.copy2(config_path, alias_config_path)
try:
separator.load_model(model_filename=_AUDIO_SEPARATOR_COMPAT_ALIAS_CKPT)
except TypeError:
separator.load_model(_AUDIO_SEPARATOR_COMPAT_ALIAS_CKPT)
self._verify_loaded_model_path(
separator,
alias_model_path,
allowed_model_names={converted_model_path.name, _AUDIO_SEPARATOR_COMPAT_ALIAS_CKPT},
)
log.info(
"Apollo compatibility alias load succeeded using %s",
alias_model_path.name,
)
return alias_model_path
def _get_separator(self, output_dir: Path):
"""Create and explicitly load the requested audio-separator model."""
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,
)
self._load_model_with_fallback(
separator,
model_path=Path(model_path),
config_path=Path(config_path),
)
return separator
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Separate vocals into dry vocals and reverb.
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", ["dry_vocals", "reverb"])
aliases = {
"dry_vocals": ["dry", "vocals", "no_reverb", "clean_vocals"],
"vocals": ["vocals", "restored", "enhanced", "clean", "dry"],
"instrumental": ["instrumental", "residual", "other", "noise", "reverb"],
"restored": ["restored", "enhanced", "vocals", "clean"],
"reverb": ["reverb", "fx", "wet", "residual"],
"enhanced": ["enhanced", "vocals", "dry"],
"residual": ["residual", "other", "noise", "reverb"],
}
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 Apollo separation. "
"Install with: pip install audio-separator"
)