Files
stemengine_old/backend/services/stem_finalize_service.py
2026-04-04 11:01:11 +09:00

112 lines
3.3 KiB
Python

from __future__ import annotations
import logging
import os
from pathlib import Path
from typing import Callable, Optional
log = logging.getLogger(__name__)
SILENT_STEM_PEAK_THRESHOLD = 1e-4
SILENT_STEM_RMS_THRESHOLD = 1e-5
def finalize_generated_stems(
stem_files: dict[str, str],
*,
stems_dir: Path,
stem_prefix: str,
job_id: str | None = None,
update_job_fn: Optional[Callable[..., None]] = None,
) -> tuple[dict[str, str], dict[str, object]]:
"""Canonically rename generated stems and delete effectively silent ones."""
from .separation.output_layout import stem_filename
final_stems: dict[str, str] = {}
renamed: list[dict[str, str]] = []
removed_silent: list[dict[str, object]] = []
for stem_name, raw_path in sorted(stem_files.items()):
path = Path(raw_path)
if not path.exists():
continue
canonical_path = stems_dir / stem_filename(stem_prefix, stem_name, path.suffix)
if path != canonical_path:
canonical_path.parent.mkdir(parents=True, exist_ok=True)
os.replace(str(path), str(canonical_path))
renamed.append(
{
"stem": stem_name,
"old_path": str(path),
"new_path": str(canonical_path),
}
)
path = canonical_path
is_silent, stats = _is_effectively_silent(path)
if is_silent:
try:
path.unlink(missing_ok=True)
except Exception:
log.debug("Failed to delete silent stem %s", path, exc_info=True)
removed_silent.append(
{
"stem": stem_name,
"path": str(path),
**stats,
}
)
if update_job_fn is not None and job_id:
update_job_fn(job_id, progress=f"Removed silent stem '{stem_name}'.")
continue
final_stems[stem_name] = str(path)
summary = {
"renamed": renamed,
"removed_silent": removed_silent,
"kept": sorted(final_stems.keys()),
}
return final_stems, summary
def _is_effectively_silent(path: Path) -> tuple[bool, dict[str, float]]:
import numpy as np
audio = _load_audio_array(path)
if audio.size == 0:
return True, {"peak": 0.0, "rms": 0.0}
peak = float(np.max(np.abs(audio)))
rms = float(np.sqrt(np.mean(np.square(audio, dtype=np.float32), dtype=np.float32)))
is_silent = peak < SILENT_STEM_PEAK_THRESHOLD and rms < SILENT_STEM_RMS_THRESHOLD
return is_silent, {"peak": peak, "rms": rms}
def _load_audio_array(path: Path):
import numpy as np
try:
import soundfile as sf
data, _sample_rate = sf.read(str(path), always_2d=True, dtype="float32")
return np.asarray(data, dtype=np.float32)
except Exception:
pass
from pydub import AudioSegment
audio = AudioSegment.from_file(str(path))
samples = np.array(audio.get_array_of_samples(), dtype=np.float32)
channels = max(1, int(audio.channels or 1))
if channels > 1:
samples = samples.reshape((-1, channels))
else:
samples = samples.reshape((-1, 1))
max_possible = float(1 << max(1, (8 * int(audio.sample_width)) - 1))
if max_possible > 0:
samples /= max_possible
return samples