"""Stage 1: original file (uploaded, or downloaded from YouTube first) -> source.wav -> 7 base stems that sum exactly to the source.""" from __future__ import annotations import json import logging import os import shutil from dataclasses import dataclass from pathlib import Path import numpy as np from sqlmodel import Session from stemdeck.audio_io import AudioError, convert_to_master, fit_length, read_audio, snr_db, write_float_wav from stemdeck.db import get_engine from stemdeck.models import Job, Song from stemdeck.pipeline.analysis import analyse from stemdeck.pipeline.assets import save_stem, update_peaks from stemdeck.pipeline.progress import JobReporter from stemdeck.pipeline.separator import AudioSeparatorEngine, pick_output from stemdeck.settings import AppConfig, Settings from stemdeck.youtube import download_audio log = logging.getLogger(__name__) INSTRUMENT_STEMS = ("drums", "bass", "guitar", "piano") DOWNLOAD_WEIGHT_SEC = 20.0 # typical YouTube audio download, for the progress bar and ETA @dataclass(frozen=True) class JobContext: job_id: str song_id: str settings: Settings config: AppConfig device: str @property def song_folder(self) -> Path: return self.settings.songs_dir / self.song_id @property def work_dir(self) -> Path: return self.song_folder / "work" / self.job_id def run_split(ctx: JobContext, quality: str, source_url: str | None = None) -> None: profile = ctx.config.qualities.get(quality) or ctx.config.qualities[ctx.config.default_quality] folder = ctx.song_folder original = next(folder.glob("original.*"), None) if original is None and not source_url: raise AudioError("The uploaded file is missing. Please upload it again.") with Session(get_engine()) as session: song = session.get(Song, ctx.song_id) duration = (song.duration_sec or 240.0) if song else 240.0 engine = AudioSeparatorEngine(ctx.settings.models_dir, ctx.device, duration) weights = { "converting": 3.0, "separating_vocals": engine.expected_seconds(profile.vocals) + 15, "separating_lead_backing": engine.expected_seconds(profile.karaoke) + 15, "separating_instruments": engine.expected_seconds(profile.instruments) + 15, "assembling": 5.0, "analysing": 15.0, "building_assets": 3.0, } if original is None: weights = {"downloading": DOWNLOAD_WEIGHT_SEC, **weights} rep = JobReporter(ctx.job_id, weights) work = ctx.work_dir work.mkdir(parents=True, exist_ok=True) if original is None: rep.stage("downloading") original = _download(ctx, str(source_url), rep) rep.stage("converting") source_path = folder / "source.wav" convert_to_master(original, source_path) source = read_audio(source_path) n = len(source) _set_song(ctx.song_id, duration_sec=round(n / 44100, 3), device_used=ctx.device) rep.stage("separating_vocals") out_a = engine.separate(source_path, profile.vocals, work / "a", rep.update) vocals = fit_length(read_audio(pick_output(out_a, "vocals")), n) instrumental = source - vocals # exact residual keeps everything consistent downstream vocals_path, inst_path = work / "vocals.wav", work / "instrumental.wav" write_float_wav(vocals_path, vocals) write_float_wav(inst_path, instrumental) rep.stage("separating_lead_backing") out_b = engine.separate(vocals_path, profile.karaoke, work / "b", rep.update) lead = fit_length(read_audio(pick_output(out_b, "vocals", "lead", "karaoke")), n) log.info("karaoke outputs: %s", sorted(out_b)) rep.stage("separating_instruments") out_c = engine.separate(inst_path, profile.instruments, work / "c", rep.update) log.info("instrument outputs: %s", sorted(out_c)) rep.stage("assembling") stems: dict[str, np.ndarray] = {"lead_vocals": lead, "backing_vocals": vocals - lead} for name in INSTRUMENT_STEMS: stems[name] = fit_length(read_audio(pick_output(out_c, name)), n) named_sum = np.sum(list(stems.values()), axis=0) stems["other"] = source - named_sum # everything the models did not claim (incl. vocal leakage) null_snr = snr_db(source, np.sum(list(stems.values()), axis=0)) log.info("null test %.1f dB, other rms share computed for song %s", null_snr, ctx.song_id) with Session(get_engine()) as session: song = session.get(Song, ctx.song_id) assert song is not None for name, audio in stems.items(): save_stem(session, ctx.settings.songs_dir, song, name, audio, ctx.config.silence_threshold_db) song.null_test_snr_db = round(null_snr, 1) session.add(song) session.commit() rep.stage("analysing") try: result = analyse(source_path, source - stems["drums"], ctx.device) (folder / "analysis.json").write_text(json.dumps(result.to_dict()), encoding="utf-8") except Exception: # noqa: BLE001 - analysis is a nice-to-have; never fail the split for it log.exception("analysis failed for song %s", ctx.song_id) rep.stage("building_assets") update_peaks(folder, stems, ctx.config.peaks_points, round(n / 44100, 3)) _set_song(ctx.song_id, status="ready") shutil.rmtree(work, ignore_errors=True) def _download(ctx: JobContext, url: str, rep: JobReporter) -> Path: """Fetch the YouTube audio into the song folder as original.. A retry after an interrupted download resumes the partial file, which lives in its own folder so it is never mistaken for a finished original.""" partial_dir = ctx.song_folder / "download" path = download_audio(url, partial_dir, ctx.settings, ctx.config.max_duration_sec, ctx.config.max_upload_mb * 1024 * 1024, rep.update) original = ctx.song_folder / f"original{path.suffix.lower()}" os.replace(path, original) shutil.rmtree(partial_dir, ignore_errors=True) log.info("downloaded %s for song %s (%.1f MB)", url, ctx.song_id, original.stat().st_size / 1e6) return original def _set_song(song_id: str, **fields: object) -> None: with Session(get_engine()) as session: song = session.get(Song, song_id) if song is None: return for key, value in fields.items(): setattr(song, key, value) session.add(song) session.commit() def job_params(job_id: str) -> dict[str, object]: with Session(get_engine()) as session: job = session.get(Job, job_id) return dict(job.params) if job else {}