Files
2026-04-04 11:01:11 +09:00

294 lines
10 KiB
Python

import inspect
import logging
import shutil
from pathlib import Path
from typing import Dict, Iterable, Optional
log = logging.getLogger(__name__)
def _import_separator_class():
try:
from audio_separator.separator import Separator
except ImportError as exc:
raise ImportError(
"audio-separator is required for this separator. "
"Install with: pip install audio-separator"
) from exc
return Separator
def _filter_supported_kwargs(callable_obj, kwargs: dict) -> dict:
try:
signature = inspect.signature(callable_obj)
except (TypeError, ValueError):
return kwargs
params = signature.parameters
if any(param.kind == inspect.Parameter.VAR_KEYWORD for param in params.values()):
return kwargs
return {key: value for key, value in kwargs.items() if key in params}
def create_separator(*, model_dir: Path, output_dir: Optional[Path], output_format: str, mp3_bitrate: str):
Separator = _import_separator_class()
kwargs = {
"model_file_dir": str(model_dir),
"output_dir": str(output_dir) if output_dir is not None else None,
"output_format": output_format,
"output_bitrate": mp3_bitrate if (output_format or "").lower() == "mp3" else None,
}
filtered = _filter_supported_kwargs(Separator.__init__, kwargs)
return Separator(**filtered)
def _try_load_with_kwargs(load_model, kwargs: dict) -> bool:
filtered = _filter_supported_kwargs(load_model, kwargs)
if not filtered and kwargs:
return False
load_model(**filtered)
return True
def _loaded_model_matches(
separator,
expected_model_path: Path,
*,
allowed_model_names: Optional[set[str]] = None,
) -> bool:
model_instance = getattr(separator, "model_instance", None)
candidates = [
getattr(model_instance, "model_path", None),
getattr(model_instance, "model_file", None),
getattr(model_instance, "model_filename", None),
getattr(model_instance, "model_name", None),
getattr(separator, "model_path", None),
getattr(separator, "model_file", None),
getattr(separator, "model_filename", None),
getattr(separator, "model_name", None),
]
expected_names = {expected_model_path.name}
if allowed_model_names:
expected_names.update(allowed_model_names)
expected_names = {name for name in expected_names if name}
for raw in candidates:
if not raw:
continue
raw_str = str(raw)
path_name = Path(raw_str).name
if path_name in expected_names:
return True
if any(name in raw_str for name in expected_names):
return True
try:
actual_path = Path(raw_str).resolve()
if actual_path == expected_model_path:
return True
except Exception:
continue
return False
def load_explicit_model(
separator,
*,
model_path: Path,
config_path: Optional[Path] = None,
model_id: Optional[str] = None,
allowed_model_names: Optional[set[str]] = None,
) -> None:
load_model = separator.load_model
model_path = model_path.resolve()
config_path = config_path.resolve() if config_path is not None else None
attempts = []
if config_path is not None:
for model_key in ("model_filename", "model_file", "model_path", "model", "filename"):
for config_key in ("config_filename", "config_file", "config_path", "config"):
attempts.append({model_key: str(model_path), config_key: str(config_path)})
attempts.append({model_key: model_path.name, config_key: config_path.name})
if model_id:
for model_key in ("model_id", "model_name", "model", "model_filename"):
attempts.append({model_key: model_id})
for key in ("model_filename", "model_file", "model_path", "model", "filename"):
attempts.append({key: str(model_path)})
attempts.append({key: model_path.name})
last_error = None
for kwargs in attempts:
try:
if _try_load_with_kwargs(load_model, kwargs):
if _loaded_model_matches(
separator,
model_path,
allowed_model_names=allowed_model_names,
):
log.debug("Loaded audio-separator model using kwargs: %s", sorted(kwargs.keys()))
return
last_error = RuntimeError(
f"audio-separator loaded a different model than requested: expected '{model_path.name}'"
)
except TypeError as exc:
last_error = exc
continue
except Exception as exc:
message = str(exc).lower()
if "unexpected keyword" in message or "positional argument" in message:
last_error = exc
continue
last_error = exc
try:
load_model(str(model_path))
if _loaded_model_matches(
separator,
model_path,
allowed_model_names=allowed_model_names,
):
log.debug("Loaded audio-separator model using positional path: %s", model_path)
return
last_error = RuntimeError(
f"audio-separator loaded a different model than requested: expected '{model_path.name}'"
)
except TypeError as exc:
last_error = exc
except Exception as exc:
message = str(exc).lower()
if "no such file" not in message and "not found" not in message:
raise
last_error = exc
try:
load_model(model_path.name)
if _loaded_model_matches(
separator,
model_path,
allowed_model_names=allowed_model_names,
):
log.debug("Loaded audio-separator model using positional filename: %s", model_path.name)
return
last_error = RuntimeError(
f"audio-separator loaded a different model than requested: expected '{model_path.name}'"
)
except TypeError as exc:
last_error = exc
except Exception as exc:
message = str(exc).lower()
if "no such file" not in message and "not found" not in message:
raise
last_error = exc
try:
load_model()
if _loaded_model_matches(
separator,
model_path,
allowed_model_names=allowed_model_names,
):
log.debug("Loaded audio-separator model using no-arg fallback in %s", model_path.parent)
return
last_error = RuntimeError(
f"audio-separator defaulted to a different model than requested: expected '{model_path.name}'"
)
except Exception as exc:
last_error = exc
model_instance = getattr(separator, "model_instance", None)
observed = {
"model_instance.model_path": getattr(model_instance, "model_path", None),
"model_instance.model_file": getattr(model_instance, "model_file", None),
"model_instance.model_filename": getattr(model_instance, "model_filename", None),
"model_instance.model_name": getattr(model_instance, "model_name", None),
"separator.model_path": getattr(separator, "model_path", None),
"separator.model_file": getattr(separator, "model_file", None),
"separator.model_filename": getattr(separator, "model_filename", None),
"separator.model_name": getattr(separator, "model_name", None),
}
raise RuntimeError(
f"Unable to explicitly load audio-separator model '{model_path.name}'"
+ (f" ({last_error})" if last_error else "")
+ f" | observed={observed}"
)
def _normalise_token(value: str) -> str:
return value.lower().replace("-", "_").replace(" ", "_")
def _infer_stem_from_path(path: Path, expected_stems: Iterable[str], aliases: Optional[dict[str, list[str]]] = None) -> Optional[str]:
stem_name = _normalise_token(path.stem)
alias_map = {key: [_normalise_token(key), *[_normalise_token(alias) for alias in vals]] for key, vals in (aliases or {}).items()}
for expected in expected_stems:
expected_norm = _normalise_token(expected)
candidates = alias_map.get(expected, [expected_norm])
if any(candidate in stem_name for candidate in candidates):
return expected
return None
def map_and_rename_outputs(
result,
*,
output_dir: Path,
expected_stems: list[str],
output_format: str,
aliases: Optional[dict[str, list[str]]] = None,
) -> Dict[str, str]:
output_dir.mkdir(parents=True, exist_ok=True)
def _resolve_source_path(src: Path) -> Path:
# audio-separator may return absolute paths, output-dir-relative names,
# or bare filenames. Prefer whichever concrete path exists.
if src.exists():
return src
if not src.is_absolute():
for candidate in (output_dir / src, output_dir / src.name):
if candidate.exists():
return candidate
return src
def _move_to_final(src: Path, dst: Path) -> None:
src = _resolve_source_path(src)
if src.resolve() == dst.resolve():
return
dst.parent.mkdir(parents=True, exist_ok=True)
if dst.exists():
dst.unlink()
shutil.move(str(src), str(dst))
if isinstance(result, (str, Path)):
paths = [Path(result)]
else:
paths = [Path(path) for path in result]
assigned: Dict[str, str] = {}
remaining_paths: list[Path] = []
for path in paths:
inferred = _infer_stem_from_path(path, expected_stems, aliases=aliases)
if inferred and inferred not in assigned:
final_path = output_dir / f"{inferred}.{output_format}"
_move_to_final(path, final_path)
assigned[inferred] = str(final_path)
else:
remaining_paths.append(path)
unassigned_stems = [stem for stem in expected_stems if stem not in assigned]
for stem_name, path in zip(unassigned_stems, remaining_paths):
final_path = output_dir / f"{stem_name}.{output_format}"
_move_to_final(path, final_path)
assigned[stem_name] = str(final_path)
return assigned