"""Orchestrate independent, cached analysis steps.""" import argparse import json import sys from pathlib import Path from . import backends from .core import group_words, run_step, validate_json, validate_outputs, write_json def resolve_separator_bin(value: str) -> str: if value == "audio-separator": candidate = Path(sys.executable).parent / value if candidate.is_file(): return str(candidate) return value def analyze(source: Path, out: Path, lyrics: Path | None = None, *, force: bool = False, separator_bin: str = "audio-separator", model_dir: Path | None = None, roformer_model: str = "model_bs_roformer_ep_317_sdr_12.9755.ckpt", language: str = "en", whisper_model: str = "large-v3") -> dict: source = source.resolve() if not source.is_file(): raise FileNotFoundError(source) if lyrics and not lyrics.is_file(): raise FileNotFoundError(lyrics) separator_bin = resolve_separator_bin(separator_bin) out.mkdir(parents=True, exist_ok=True) previous = {} meta_path = out / "meta.json" if meta_path.exists(): try: previous = json.loads(meta_path.read_text(encoding="utf-8")) except (OSError, ValueError): previous = {} errors: dict[str, str] = {} mix = out / "_cache" / "original.wav" run_step("normalize", [mix], lambda: backends.normalize(source, mix), errors, force) duration = 0.0 if mix.exists(): try: duration = backends.duration_of(mix) except Exception as exc: errors["duration"] = f"{type(exc).__name__}: {exc}" stems = out / "stems" vocals = stems / "vocals.wav" instrumental = out / "_cache" / "instrumental.wav" if mix.exists(): def vocal_step(): with __import__("tempfile").TemporaryDirectory(dir=out) as tmp: temp_stems = Path(tmp) backends.separate(mix, temp_stems, ["vocals", "instrumental"], roformer_model, separator_bin, model_dir, duration) stems.mkdir(exist_ok=True) for name, target in (("vocals", vocals), ("instrumental", instrumental)): if force or not target.exists(): (temp_stems / f"{name}.wav").replace(target) run_step("vocals", [vocals, instrumental], vocal_step, errors, force) # The mix supports independent beat and chord analysis even when separation fails. beats_path = out / "beats.json" def beats_step(): value, _ = backends.detect_beats(mix) validate_json("beats", value) write_json(beats_path, value) run_step("beats", [beats_path], beats_step, errors, force) chords_path = out / "chords.json" def chords_step(): value = backends.detect_chords(mix, duration) validate_json("chords", value) write_json(chords_path, value) run_step("chords", [chords_path], chords_step, errors, force) if instrumental.exists(): def instrument_step(): backends.separate(instrumental, stems, ["drums", "bass", "other"], "htdemucs_ft.yaml", separator_bin, model_dir, duration, force) run_step("instruments", [stems / f"{s}.wav" for s in ("drums", "bass", "other")], instrument_step, errors, force) if vocals.exists(): pitch_path = out / "pitch.json" def pitch_step(): value = backends.detect_pitch(vocals) validate_json("pitch", value) write_json(pitch_path, value) run_step("pitch", [pitch_path], pitch_step, errors, force) run_step("melody", [out / "melody.mid"], lambda: backends.transcribe_midi(vocals, out / "melody.mid"), errors, force) lyrics_path = out / "lyrics.json" def lyrics_step(): words, verified = backends.lyrics_words(vocals, lyrics, language, whisper_model) downbeats = [] if (out / "beats.json").exists(): try: downbeats = json.loads((out / "beats.json").read_text(encoding="utf-8"))["downbeats"] except (OSError, ValueError, KeyError): pass value = {"verified": verified, "lines": group_words(words, downbeats)} validate_json("lyrics", value) write_json(lyrics_path, value) run_step("lyrics", [lyrics_path], lyrics_step, errors, force) if (stems / "other.wav").exists(): run_step("guitar", [out / "guitar.mid"], lambda: backends.transcribe_midi(stems / "other.wav", out / "guitar.mid"), errors, force) bpm = previous.get("bpm") if (out / "beats.json").exists(): try: beat_times = json.loads((out / "beats.json").read_text(encoding="utf-8"))["beats"] gaps = [b - a for a, b in zip(beat_times, beat_times[1:]) if 0.2 <= b - a <= 2] if gaps: import statistics bpm = round(60 / statistics.median(gaps), 2) except (OSError, ValueError, KeyError, TypeError): pass if not force and previous.get("bpm") is not None: bpm = previous["bpm"] validate_outputs(out, errors) key = previous.get("key") if mix.exists() and (force or key is None): try: key = backends.detect_key(mix) except Exception as exc: errors["key"] = f"{type(exc).__name__}: {exc}" meta = {"title": previous.get("title", source.stem) if not force else source.stem, "bpm": bpm, "key": key, "duration": previous.get("duration", duration) if not force and previous.get("duration", 0) > 0 else duration, "schema_version": 1, "errors": errors} try: validate_json("meta", meta) except Exception as exc: meta["errors"]["validate_meta"] = str(exc) write_json(meta_path, meta) return meta def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="analyze", description="Song in Stems, Beats, Akkorde, MIDI, Pitch und Wortzeiten zerlegen") parser.add_argument("audio", type=Path) parser.add_argument("--out", required=True, type=Path) parser.add_argument("--lyrics", type=Path) parser.add_argument("--force", action="store_true") parser.add_argument("--separator-bin", default="audio-separator") parser.add_argument("--model-dir", type=Path) parser.add_argument("--roformer-model", default="model_bs_roformer_ep_317_sdr_12.9755.ckpt") parser.add_argument("--language", default="en") parser.add_argument("--whisper-model", default="large-v3") args = parser.parse_args(argv) try: meta = analyze(args.audio, args.out, args.lyrics, force=args.force, separator_bin=args.separator_bin, model_dir=args.model_dir, roformer_model=args.roformer_model, language=args.language, whisper_model=args.whisper_model) except (OSError, ValueError) as exc: parser.error(str(exc)) print(f"Ergebnis: {args.out}") for step, message in meta["errors"].items(): print(f"{step}: {message}", file=sys.stderr) return 1 if meta["errors"] else 0