Files
stemengine_old/backend/services_root_backup/aspiration_separator.py
T
2026-03-03 14:52:19 +09:00

145 lines
5.4 KiB
Python
Executable File

"""
Aspiration separator - Breath/aspiration removal from vocals
Models from MVSEP-Central-Backup: https://huggingface.co/miercolesv/MVSEP-Central-Backup
"""
import os
import torch
from pathlib import Path
from typing import Dict
from ..config import ASPIRATION_MODEL_DIR, CPU_SEPARATION
# Model configurations
ASPIRATION_MODELS = {
"aspiration_full": {
"model_path": "aspiration_mel_band_roformer_sdr_18.9845.ckpt",
"config_path": "config_aspiration_mel_band_roformer.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Aspiration-MelBand-Sucial",
"stems": ["clean_vocals", "aspiration"],
"aggression": "full",
},
"aspiration_light": {
"model_path": "aspiration_mel_band_roformer_less_aggr_sdr_18.1201.ckpt",
"config_path": "config_aspiration_mel_band_roformer.yaml",
"hf_repo": "miercolesv/MVSEP-Central-Backup",
"hf_subfolder": "Aspiration-MelBand-Sucial",
"stems": ["clean_vocals", "aspiration"],
"aggression": "light",
},
}
class AspirationSeparator:
"""
Aspiration separator for breath/aspiration removal from vocals.
Useful for cleaning vocal recordings by separating breath sounds
from the main vocal performance.
"""
def __init__(
self,
model_id: str = "aspiration_full",
cpu_separation: bool = CPU_SEPARATION,
output_format: str = "mp3",
mp3_bitrate: str = "256k",
):
if model_id not in ASPIRATION_MODELS:
raise ValueError(f"Unknown Aspiration model: {model_id}")
self.model_id = model_id
self.model_config = ASPIRATION_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 = ASPIRATION_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
print(f"Downloading Aspiration model: {self.model_id}")
if not model_path.exists():
hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['model_path']}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
if not config_path.exists():
hf_hub_download(
repo_id=self.model_config["hf_repo"],
filename=f"{self.model_config['hf_subfolder']}/{self.model_config['config_path']}",
local_dir=model_dir,
local_dir_use_symlinks=False,
)
except Exception as e:
raise RuntimeError(f"Failed to download Aspiration model: {e}")
return str(model_path), str(config_path)
def _load_model(self):
"""Lazy-load the model."""
if self._model is None:
model_path, config_path = self._ensure_model()
self._model = None # Placeholder for actual model loading
return self._model
def separate_into_parts(self, input_path: str, output_dir: str) -> Dict[str, str]:
"""
Separate vocals into clean vocals and aspiration (breath).
Returns:
Dict mapping stem names to output file paths
"""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
try:
from audio_separator.separator import Separator
sep = Separator(
model_file_dir=str(ASPIRATION_MODEL_DIR),
output_dir=str(output_path),
output_format=self.output_format.upper(),
output_bitrate=self.mp3_bitrate if self.output_format == "mp3" else None,
)
sep.load_model()
result = sep.separate(input_path)
stems = self.model_config.get("stems", ["clean_vocals", "aspiration"])
output_paths = {}
if isinstance(result, list):
for i, path in enumerate(result):
if i < len(stems):
stem_name = stems[i]
final_path = output_path / f"{stem_name}.{self.output_format}"
Path(path).rename(final_path)
output_paths[stem_name] = str(final_path)
else:
final_path = output_path / f"clean_vocals.{self.output_format}"
Path(result).rename(final_path)
output_paths["clean_vocals"] = str(final_path)
return output_paths
except ImportError:
raise ImportError(
"audio-separator is required for Aspiration separation. "
"Install with: pip install audio-separator"
)