diff --git a/.gitignore b/.gitignore index ddac29e..1758845 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,9 @@ songs/ *.wav *.zip tools/.venv/ +tools/song_analysis/.venv/ +tools/song_analysis/.cache/ +tools/song_analysis/.python/ +tools/song_analysis/vamp/ +tools/song_analysis/.models/ +__pycache__/ diff --git a/schemas/song-analysis-v1/beats.schema.json b/schemas/song-analysis-v1/beats.schema.json new file mode 100644 index 0000000..117dd00 --- /dev/null +++ b/schemas/song-analysis-v1/beats.schema.json @@ -0,0 +1 @@ +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Beat times v1","type":"object","required":["beats","downbeats"],"properties":{"beats":{"type":"array","items":{"type":"number","minimum":0}},"downbeats":{"type":"array","items":{"type":"number","minimum":0}}},"additionalProperties":false} diff --git a/schemas/song-analysis-v1/chords.schema.json b/schemas/song-analysis-v1/chords.schema.json new file mode 100644 index 0000000..71cd5af --- /dev/null +++ b/schemas/song-analysis-v1/chords.schema.json @@ -0,0 +1 @@ +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Chord spans v1","type":"array","items":{"type":"object","required":["chord","start","end","conf"],"properties":{"chord":{"type":"string","minLength":1},"start":{"type":"number","minimum":0},"end":{"type":"number","minimum":0},"conf":{"type":["number","null"],"minimum":0,"maximum":1}},"additionalProperties":false}} diff --git a/schemas/song-analysis-v1/lyrics.schema.json b/schemas/song-analysis-v1/lyrics.schema.json new file mode 100644 index 0000000..5b5d51d --- /dev/null +++ b/schemas/song-analysis-v1/lyrics.schema.json @@ -0,0 +1 @@ +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Aligned lyrics v1","type":"object","required":["verified","lines"],"properties":{"verified":{"type":"boolean"},"lines":{"type":"array","items":{"type":"object","required":["start","end","words"],"properties":{"start":{"type":"number","minimum":0},"end":{"type":"number","minimum":0},"words":{"type":"array","minItems":1,"items":{"type":"object","required":["w","start","end","conf"],"properties":{"w":{"type":"string","minLength":1},"start":{"type":"number","minimum":0},"end":{"type":"number","minimum":0},"conf":{"type":["number","null"],"minimum":0,"maximum":1}},"additionalProperties":false}}},"additionalProperties":false}}},"additionalProperties":false} diff --git a/schemas/song-analysis-v1/meta.schema.json b/schemas/song-analysis-v1/meta.schema.json new file mode 100644 index 0000000..0dbe92c --- /dev/null +++ b/schemas/song-analysis-v1/meta.schema.json @@ -0,0 +1 @@ +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Song analysis meta v1","type":"object","required":["title","bpm","key","duration","schema_version","errors"],"properties":{"title":{"type":"string"},"bpm":{"type":["number","null"],"exclusiveMinimum":0},"key":{"type":["string","null"]},"duration":{"type":"number","minimum":0},"schema_version":{"const":1},"errors":{"type":"object","additionalProperties":{"type":"string"}}},"additionalProperties":false} diff --git a/schemas/song-analysis-v1/pitch.schema.json b/schemas/song-analysis-v1/pitch.schema.json new file mode 100644 index 0000000..9b55ade --- /dev/null +++ b/schemas/song-analysis-v1/pitch.schema.json @@ -0,0 +1 @@ +{"$schema":"https://json-schema.org/draft/2020-12/schema","title":"Pitch curve v1","type":"object","required":["hop_ms","hz","conf"],"properties":{"hop_ms":{"const":10},"hz":{"type":"array","items":{"type":"number","minimum":0}},"conf":{"type":"array","items":{"type":"number","minimum":0,"maximum":1}}},"additionalProperties":false} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..b90b90e --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,2 @@ +//! Stable file contract for external song-analysis tools. +pub mod song_analysis; diff --git a/src/song_analysis.rs b/src/song_analysis.rs new file mode 100644 index 0000000..5615286 --- /dev/null +++ b/src/song_analysis.rs @@ -0,0 +1,130 @@ +//! Version 1 of `schemas/song-analysis-v1/`, with seconds relative to the normalized mix. + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Meta { + pub title: String, + pub bpm: Option, + pub key: Option, + pub duration: f64, + pub schema_version: u32, + pub errors: BTreeMap, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Pitch { + pub hop_ms: u32, + pub hz: Vec, + pub conf: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Chord { + pub chord: String, + pub start: f64, + pub end: f64, + pub conf: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Beats { + pub beats: Vec, + pub downbeats: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Word { + pub w: String, + pub start: f64, + pub end: f64, + pub conf: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Line { + pub start: f64, + pub end: f64, + pub words: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Lyrics { + pub verified: bool, + pub lines: Vec, +} + +#[derive(Debug)] +pub struct Analysis { + pub meta: Meta, + pub pitch: Option, + pub chords: Option>, + pub beats: Option, + pub lyrics: Option, + pub vocals: Option, + pub drums: Option, + pub bass: Option, + pub other: Option, + pub melody_midi: Option, + pub guitar_midi: Option, +} + +fn existing(dir: &Path, name: &str) -> Option { + let path = dir.join(name); + path.is_file().then_some(path) +} + +fn read_optional(dir: &Path, name: &str) -> Result> { + let path = dir.join(name); + if !path.exists() { + return Ok(None); + } + let bytes = std::fs::read(&path).with_context(|| format!("{} lesen", path.display()))?; + let value = + serde_json::from_slice(&bytes).with_context(|| format!("{} parsen", path.display()))?; + Ok(Some(value)) +} + +/// Reads only the analysis output directory. Missing outputs are allowed after a failed step. +pub fn load_analysis(dir: &Path) -> Result { + let path = dir.join("meta.json"); + let meta: Meta = serde_json::from_slice( + &std::fs::read(&path).with_context(|| format!("{} lesen", path.display()))?, + )?; + if meta.schema_version != 1 { + bail!( + "Unbekannte song-analysis schema_version {}", + meta.schema_version + ); + } + let pitch: Option = read_optional(dir, "pitch.json")?; + if pitch + .as_ref() + .is_some_and(|p| p.hop_ms != 10 || p.hz.len() != p.conf.len()) + { + bail!("Ungültige pitch.json"); + } + Ok(Analysis { + meta, + pitch, + chords: read_optional(dir, "chords.json")?, + beats: read_optional(dir, "beats.json")?, + lyrics: read_optional(dir, "lyrics.json")?, + vocals: existing(dir, "stems/vocals.wav"), + drums: existing(dir, "stems/drums.wav"), + bass: existing(dir, "stems/bass.wav"), + other: existing(dir, "stems/other.wav"), + melody_midi: existing(dir, "melody.mid"), + guitar_midi: existing(dir, "guitar.mid"), + }) +} diff --git a/tests/song_analysis_contract.rs b/tests/song_analysis_contract.rs new file mode 100644 index 0000000..580aae5 --- /dev/null +++ b/tests/song_analysis_contract.rs @@ -0,0 +1,27 @@ +use singtrainer::song_analysis::{Analysis, load_analysis}; + +#[test] +fn reads_optional_outputs_from_one_folder() { + let dir = std::env::temp_dir().join(format!("song-analysis-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("meta.json"), r#"{"title":"Example","bpm":120.0,"key":null,"duration":3.0,"schema_version":1,"errors":{}}"#).unwrap(); + std::fs::write( + dir.join("beats.json"), + r#"{"beats":[0.0,0.5],"downbeats":[0.0]}"#, + ) + .unwrap(); + let value: Analysis = load_analysis(&dir).unwrap(); + assert_eq!(value.meta.title, "Example"); + assert_eq!(value.beats.unwrap().downbeats, vec![0.0]); + assert!(value.pitch.is_none()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn rejects_unknown_schema_version() { + let dir = std::env::temp_dir().join(format!("song-analysis-version-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("meta.json"), r#"{"title":"Example","bpm":null,"key":null,"duration":3.0,"schema_version":2,"errors":{}}"#).unwrap(); + assert!(load_analysis(&dir).is_err()); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/tools/analyze b/tools/analyze new file mode 100755 index 0000000..2e77fb9 --- /dev/null +++ b/tools/analyze @@ -0,0 +1,4 @@ +#!/usr/bin/env python3 +from song_analysis.cli import main + +raise SystemExit(main()) diff --git a/tools/song_analysis/README.md b/tools/song_analysis/README.md new file mode 100644 index 0000000..4a474d1 --- /dev/null +++ b/tools/song_analysis/README.md @@ -0,0 +1,48 @@ +# Song-Analyse (eigenständiges Werkzeug) + +Die CLI erzeugt aus einer Audiodatei einen versionierten Ausgabeordner. Die Rust-Anwendung muss dafür keine Python-Pakete laden; `src/song_analysis.rs` kann die JSON-Dateien aus dem Ordner lesen. Das Werkzeug ändert keine Charts. + +## Installation + +Python 3.11, `ffmpeg`, `ffprobe` und `vamp-simple-host` mit dem Vamp-Plugin **NNLS Chroma/Chordino** werden benötigt. Die Modellgewichte werden beim ersten Einsatz von den jeweiligen Bibliotheken geladen. Eine eigene virtuelle Umgebung vermeidet Konflikte mit den vorhandenen Werkzeugen: + +Ein lokal gebautes `nnls-chroma.so` kann unter `tools/song_analysis/vamp/` liegen. Die Pipeline findet es dort automatisch. Der Ordner bleibt aus Git ausgeschlossen. Der [Quellcode von Chordino](https://github.com/c4dm/nnls-chroma) steht unter GPL-2.0. + +```bash +uv venv --seed --python 3.11 tools/song_analysis/.venv +uv pip install --python tools/song_analysis/.venv/bin/python \ + --index https://download.pytorch.org/whl/cpu \ + 'torch==2.5.1+cpu' 'torchaudio==2.5.1+cpu' 'torchvision==0.20.1+cpu' +tools/song_analysis/.venv/bin/pip install -r tools/song_analysis/requirements.txt +``` + +Auf Linux-Systemen, die bei `import whisperx` das Laden von `libctranslate2` wegen eines ausführbaren Stacks verweigern, hilft einmalig in dieser Umgebung: + +```bash +tools/song_analysis/.venv/bin/patchelf --clear-execstack \ + tools/song_analysis/.venv/lib/python3.11/site-packages/ctranslate2.libs/libctranslate2*.so* +``` + +Die obigen PyTorch-Builds laufen auf der CPU. Für GPU-Betrieb ist ein zur Grafikkarte passender PyTorch-Build nötig; die Pipeline erkennt ihn dann automatisch. + +Aufruf (mit dieser Umgebung): + +```bash +tools/song_analysis/.venv/bin/python tools/analyze song.mp3 --out songs/song/ --lyrics lyrics.txt +tools/song_analysis/.venv/bin/python tools/analyze song.mp3 --out songs/song/ --force +``` + +Optionen: `--language en` für die WhisperX-Sprache, `--whisper-model large-v3`, `--separator-bin /pfad/audio-separator`, `--model-dir /pfad/modelle`, `--roformer-model DATEI`. Wenn der BS-RoFormer bereits unter `~/AI/models/maestro/ckpts/roformer/` liegt, kann dieser Ordner mit `--model-dir` verwendet werden. Das Demucs-Modell heißt `htdemucs_ft.yaml`. + +## Ablauf und Dateien + +1. ffmpeg erzeugt `_cache/original.wav` mit 44,1 kHz und Stereo. Dessen Beginn ist für alle Zeiten Sekunde 0. +2. `audio-separator` trennt Vocals und Instrumental mit BS-RoFormer; `htdemucs_ft` trennt das Instrumental in Drums, Bass und Other. Die vier Stems liegen unter `stems/`. `_cache/instrumental.wav` ist ein Zwischenprodukt für Wiederaufnahmen. +3. madmom Downbeat Tracking berechnet `beats.json` und BPM. `vamp-simple-host` mit Chordino berechnet `chords.json`. Chordino liefert keine Kalibrierung der Akkordsicherheit; `conf` ist deshalb `null`. +4. torchcrepe (PyTorch-Implementierung von CREPE) liefert `pitch.json` mit 10-ms-Raster. Frequenzen unter 0,5 Konfidenz werden als 0 Hz (unvoiced) geschrieben; die tatsächliche Konfidenz bleibt in `conf`. Basic Pitch verarbeitet denselben Vocal-Stem separat für `melody.mid` und den Other-Stem für `guitar.mid`. +5. WhisperX richtet den gelieferten Text wortweise aus. Ohne `--lyrics` transkribiert WhisperX selbst, und `lyrics.json` trägt `verified: false`. Wörter ohne Zeiten werden ausgelassen. Die Zeilen entstehen aus Pausen über 0,6 s, Taktgrenzen und etwa 40 Zeichen. +6. madmom schätzt die Tonart für `meta.json`; bei fehlender Erkennung ist `key` null. Alle JSON-Dateien werden gegen `schemas/song-analysis-v1/` geprüft. + +Jeder Schritt prüft seine Ausgabedateien. Ein normaler erneuter Lauf lässt vorhandene Dateien unverändert, einschließlich manueller Korrekturen. `--force` berechnet sie neu. Fehlgeschlagene Schritte stehen unter `meta.json.errors`; die CLI beendet sich dann mit Status 1. Unabhängige Schritte laufen weiter. `meta.json` wird für den aktuellen Fehlerstatus aktualisiert; seine manuell gesetzten Werte für `title`, `bpm`, `key` und `duration` bleiben ohne `--force` erhalten. + +Die JSON-Strukturen haben `schema_version: 1` in `meta.json`. Alle Zeiten sind Sekunden als Fließkommazahlen. Für das Tool sind `conf: null` und fehlende Dateien mögliche Zustände. MIDI enthält normale Noten-Events; insbesondere die Gitarrentranskription ist keine Tabulatur. Die genannten Qualitätszahlen hängen stark vom Material ab und sind keine vom Werkzeug garantierten Fehlerschranken. diff --git a/tools/song_analysis/__init__.py b/tools/song_analysis/__init__.py new file mode 100644 index 0000000..707058f --- /dev/null +++ b/tools/song_analysis/__init__.py @@ -0,0 +1 @@ +"""Standalone song analysis pipeline; no dependency on the Rust application.""" diff --git a/tools/song_analysis/backends.py b/tools/song_analysis/backends.py new file mode 100644 index 0000000..3b62ee4 --- /dev/null +++ b/tools/song_analysis/backends.py @@ -0,0 +1,184 @@ +"""Adapters for the optional audio models and command-line tools.""" + +import json +import os +import statistics +import subprocess +import tempfile +from pathlib import Path + +from .core import parse_chordino + + +def command(args: list[str], *, capture: bool = False, env: dict[str, str] | None = None) -> str: + try: + result = subprocess.run([str(a) for a in args], check=True, text=True, + stdout=subprocess.PIPE if capture else None, + stderr=subprocess.PIPE if capture else None, env=env) + except subprocess.CalledProcessError as exc: + message = (exc.stderr or "").strip().splitlines() + raise RuntimeError(f"{args[0]} fehlgeschlagen: {message[-1] if message else exc}") from exc + return result.stdout or "" + + +def duration_of(audio: Path) -> float: + result = command(["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "default=noprint_wrappers=1:nokey=1", audio], capture=True) + return float(result.strip()) + + +def normalize(source: Path, target: Path, duration: float | None = None) -> None: + target.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=target.parent) as tmp: + staged = Path(tmp) / "audio.wav" + args = ["ffmpeg", "-nostdin", "-y", "-v", "error", "-i", source, + "-ar", "44100", "-ac", "2"] + if duration is not None: + args += ["-af", "apad", "-t", str(duration)] + command(args + [staged]) + staged.replace(target) + + +def separate(audio: Path, target_dir: Path, stems: list[str], model: str, + separator_bin: str, model_dir: Path | None, duration: float, + force: bool = False) -> None: + with tempfile.TemporaryDirectory(dir=target_dir.parent) as tmp: + tmpdir = Path(tmp) + args = [separator_bin, str(audio), "--model_filename", model, + "--output_dir", str(tmpdir), "--output_format", "WAV", + "--custom_output_names", json.dumps({s.title(): s for s in stems})] + if model_dir: + args += ["--model_file_dir", str(model_dir)] + command(args) + missing = [s for s in stems if not (tmpdir / f"{s}.wav").exists()] + if missing: + raise RuntimeError("Separator lieferte keine Stems: " + ", ".join(missing)) + target_dir.mkdir(parents=True, exist_ok=True) + for stem in stems: + target = target_dir / f"{stem}.wav" + if force or not target.exists(): + normalize(tmpdir / f"{stem}.wav", target, duration) + + +def detect_beats(audio: Path) -> tuple[dict, float | None]: + try: + from madmom_infer.features.downbeats import RNNDownBeatProcessor, DBNDownBeatTrackingProcessor + except ImportError: + from madmom.features.downbeats import RNNDownBeatProcessor, DBNDownBeatTrackingProcessor + + activations = RNNDownBeatProcessor()(str(audio)) + positions = DBNDownBeatTrackingProcessor(beats_per_bar=[3, 4], fps=100)(activations) + beats = [float(row[0]) for row in positions] + downbeats = [float(row[0]) for row in positions if int(row[1]) == 1] + gaps = [b - a for a, b in zip(beats, beats[1:]) if 0.2 <= b - a <= 2] + bpm = round(60 / statistics.median(gaps), 2) if gaps else None + return {"beats": beats, "downbeats": downbeats}, bpm + + +def detect_key(audio: Path) -> str: + try: + from madmom_infer.features.key import CNNKeyRecognitionProcessor, key_prediction_to_label + except ImportError: + from madmom.features.key import CNNKeyRecognitionProcessor, key_prediction_to_label + return str(key_prediction_to_label(CNNKeyRecognitionProcessor()(str(audio)))) + + +def detect_chords(audio: Path, duration: float) -> list[dict]: + env = os.environ.copy() + local_vamp = Path(__file__).resolve().parent / "vamp" + if (local_vamp / "nnls-chroma.so").is_file(): + env["VAMP_PATH"] = str(local_vamp) + (os.pathsep + env["VAMP_PATH"] if env.get("VAMP_PATH") else "") + output = command(["vamp-simple-host", "nnls-chroma:chordino:simplechord", audio], capture=True, env=env) + chords = parse_chordino(output, duration) + if not chords: + raise RuntimeError("Chordino lieferte keine Akkorde; ist das Vamp-Plugin nnls-chroma installiert?") + return chords + + +def detect_pitch(audio: Path) -> dict: + import numpy as np + import soundfile as sf + import torch + import torchcrepe + from scipy.signal import resample_poly + + samples, rate = sf.read(audio, dtype="float32", always_2d=True) + mono = samples.mean(axis=1) + # CREPE arbeitet bei 16 kHz; scipy vermeidet eine zweite Audiodekodierung. + from math import gcd + divisor = gcd(rate, 16000) + mono = resample_poly(mono, 16000 // divisor, rate // divisor) + signal = torch.from_numpy(np.asarray(mono, dtype="float32")).unsqueeze(0) + devices = ["cuda", "cpu"] if torch.cuda.is_available() else ["cpu"] + for device in devices: + try: + hz, confidence = torchcrepe.predict(signal, 16000, hop_length=160, + fmin=50, fmax=1000, model="full", + device=device, return_periodicity=True, + batch_size=512) + break + except RuntimeError: + if device == "cpu": + raise + torch.cuda.empty_cache() + hz = hz.squeeze(0).cpu().numpy() + confidence = np.clip(confidence.squeeze(0).cpu().numpy(), 0, 1) + return {"hop_ms": 10, "hz": [round(float(f), 3) if c >= 0.5 else 0.0 + for f, c in zip(hz, confidence)], + "conf": [round(float(c), 4) for c in confidence]} + + +def transcribe_midi(audio: Path, target: Path) -> None: + from basic_pitch.inference import predict + + _, midi, _ = predict(str(audio)) + with tempfile.TemporaryDirectory(dir=target.parent) as tmp: + staged = Path(tmp) / target.name + midi.write(str(staged)) + staged.replace(target) + + +def lyrics_words(audio: Path, lyrics: Path | None, language: str, + model_name: str) -> tuple[list[dict], bool]: + import torch + import whisperx + + audio_data = whisperx.load_audio(str(audio)) + devices = ["cuda", "cpu"] if torch.cuda.is_available() else ["cpu"] + last_error = None + for device in devices: + try: + if lyrics: + text = " ".join(line.strip() for line in lyrics.read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith(("#", "["))) + if not text: + raise ValueError("Liedtext enthält keine Wörter") + segments = [{"start": 0.0, "end": len(audio_data) / 16000, "text": text}] + verified = True + else: + model = whisperx.load_model(model_name, device, compute_type="float16" if device == "cuda" else "int8") + result = model.transcribe(audio_data, batch_size=8 if device == "cuda" else 2, + language=language) + segments = result["segments"] + verified = False + del model + aligner, metadata = whisperx.load_align_model(language_code=language, device=device) + aligned = whisperx.align(segments, aligner, metadata, audio_data, device, + return_char_alignments=False) + words = [] + for item in aligned.get("word_segments", []): + if "start" not in item or "end" not in item or not item.get("word", "").strip(): + continue + words.append({"w": item["word"].strip(), "start": float(item["start"]), + "end": float(item["end"]), + "conf": float(item["score"]) if item.get("score") is not None else None}) + if not words: + raise RuntimeError("WhisperX lieferte keine ausgerichteten Wörter") + return words, verified + except (RuntimeError, MemoryError) as exc: + last_error = exc + if device == "cuda": + torch.cuda.empty_cache() + continue + raise + raise RuntimeError(f"WhisperX fehlgeschlagen: {last_error}") diff --git a/tools/song_analysis/cli.py b/tools/song_analysis/cli.py new file mode 100644 index 0000000..497ba94 --- /dev/null +++ b/tools/song_analysis/cli.py @@ -0,0 +1,164 @@ +"""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 diff --git a/tools/song_analysis/core.py b/tools/song_analysis/core.py new file mode 100644 index 0000000..f4d6920 --- /dev/null +++ b/tools/song_analysis/core.py @@ -0,0 +1,105 @@ +"""Output contract, caching and timeline utilities for song analysis.""" + +import json +import re +from pathlib import Path + +SCHEMA_DIR = Path(__file__).resolve().parents[2] / "schemas" / "song-analysis-v1" + + +def write_json(path: Path, value: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(path.name + ".tmp") + temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8") + temporary.replace(path) + + +def run_step(name: str, outputs: list[Path], action, errors: dict[str, str], force: bool) -> bool: + """Run an independent step; never destroy existing results on an ordinary rerun.""" + if outputs and all(path.exists() for path in outputs) and not force: + return True + try: + action() + missing = [str(path) for path in outputs if not path.exists()] + if missing: + raise RuntimeError("outputs missing: " + ", ".join(missing)) + errors.pop(name, None) + return True + except Exception as exc: + errors[name] = f"{type(exc).__name__}: {exc}" + return False + + +def group_words(words: list[dict], downbeats: list[float], max_chars: int = 40) -> list[dict]: + """Split aligned words on long pauses, bar lines and display length.""" + lines: list[dict] = [] + current: list[dict] = [] + downbeats = sorted(downbeats) + for word in words: + if not word.get("w") or "start" not in word or "end" not in word: + continue + if current: + prior = current[-1] + bar = any(prior["end"] < beat <= word["start"] for beat in downbeats) + length = len(" ".join(w["w"] for w in current)) + 1 + len(word["w"]) + if word["start"] - prior["end"] > 0.6 or bar or length > max_chars: + lines.append({"start": current[0]["start"], "end": prior["end"], "words": current}) + current = [] + current.append(word) + if current: + lines.append({"start": current[0]["start"], "end": current[-1]["end"], "words": current}) + return lines + + +_CHORD_EVENT = re.compile(r'^\s*([0-9]+(?:\.[0-9]+)?)\s*:\s*"?([^"\r\n]+?)"?\s*$') + + +def parse_chordino(output: str, duration: float) -> list[dict]: + events = [] + for line in output.splitlines(): + match = _CHORD_EVENT.match(line) + if match: + time = float(match.group(1)) + chord = match.group(2).strip() + if 0 <= time < duration and chord: + events.append((time, chord)) + events = sorted(set(events)) + return [ + {"chord": chord, "start": start, "end": end, "conf": None} + for (start, chord), end in zip(events, [e[0] for e in events[1:]] + [duration]) + if end > start + ] + + +def validate_json(kind: str, value: object) -> None: + """Validate against the checked-in JSON Schema, plus cross-field constraints.""" + schema = json.loads((SCHEMA_DIR / f"{kind}.schema.json").read_text(encoding="utf-8")) + try: + import jsonschema + except ImportError as exc: + raise RuntimeError("jsonschema fehlt: pip install -r tools/song_analysis/requirements.txt") from exc + try: + jsonschema.validate(value, schema) + except jsonschema.ValidationError as exc: + raise ValueError(f"{kind}: {exc.message}") from exc + if kind == "pitch" and len(value["hz"]) != len(value["conf"]): + raise ValueError("pitch: hz und conf haben unterschiedliche Längen") + if kind == "beats" and any(b < a for a, b in zip(value["beats"], value["beats"][1:])): + raise ValueError("beats: Zeiten sind nicht sortiert") + if kind in ("chords", "lyrics"): + spans = value if kind == "chords" else value["lines"] + if any(item["end"] < item["start"] for item in spans): + raise ValueError(f"{kind}: negativer Zeitbereich") + + +def validate_outputs(out: Path, errors: dict[str, str]) -> None: + for kind in ("pitch", "chords", "beats", "lyrics"): + path = out / f"{kind}.json" + if not path.exists(): + continue + try: + validate_json(kind, json.loads(path.read_text(encoding="utf-8"))) + except Exception as exc: + errors[f"validate_{kind}"] = str(exc) + else: + errors.pop(f"validate_{kind}", None) diff --git a/tools/song_analysis/requirements.txt b/tools/song_analysis/requirements.txt new file mode 100644 index 0000000..86a47f2 --- /dev/null +++ b/tools/song_analysis/requirements.txt @@ -0,0 +1,17 @@ +# Python 3.11 (Basic Pitch's documented supported range ends at 3.11). +setuptools<81 # resampy/torchcrepe importieren pkg_resources +jsonschema>=4.20,<5 +numpy>=1.26,<2 # TensorFlow 2.14 / Basic Pitch benötigt die NumPy-1-ABI +ml-dtypes==0.2.0 # TensorFlow 2.14 erwartet die ältere float8-ABI +torch==2.5.1 +torchaudio==2.5.1 +torchvision==0.20.1 +transformers>=4.40,<5 # Version 5 deaktiviert PyTorch 2.5 +patchelf>=0.19.1 # Repariert bei Bedarf das GNU_STACK-Flag von CTranslate2 4.4 +scipy>=1.10 +soundfile>=0.12 +madmom-infer @ git+https://github.com/openmirlab/madmom-infer.git +torchcrepe>=0.0.24 +basic-pitch>=0.4 +whisperx>=3.3 +audio-separator>=0.29 diff --git a/tools/test_song_analysis.py b/tools/test_song_analysis.py new file mode 100644 index 0000000..9b38998 --- /dev/null +++ b/tools/test_song_analysis.py @@ -0,0 +1,137 @@ +import json +import tempfile +import types +import unittest +from pathlib import Path +from unittest.mock import patch + +from song_analysis.core import group_words, parse_chordino, run_step, validate_json +from song_analysis.cli import analyze, resolve_separator_bin +from song_analysis.backends import detect_beats, detect_pitch + + +class SongAnalysisTests(unittest.TestCase): + def test_lines_split_at_pause_downbeat_and_length(self): + words = [ + {"w": "Hello", "start": 0.1, "end": 0.3, "conf": 0.9}, + {"w": "there", "start": 0.4, "end": 0.6, "conf": 0.8}, + {"w": "again", "start": 1.4, "end": 1.7, "conf": 0.7}, + {"w": "friend", "start": 2.1, "end": 2.4, "conf": 0.6}, + ] + lines = group_words(words, [2.0], max_chars=40) + self.assertEqual([[w["w"] for w in line["words"]] for line in lines], + [["Hello", "there"], ["again"], ["friend"]]) + self.assertEqual(lines[0]["start"], 0.1) + + def test_chordino_events_end_at_next_event_or_duration(self): + text = '0.000000: "C"\n1.250000: "Am"\n2.000000: "N"\n' + self.assertEqual(parse_chordino(text, 3.0), [ + {"chord": "C", "start": 0.0, "end": 1.25, "conf": None}, + {"chord": "Am", "start": 1.25, "end": 2.0, "conf": None}, + {"chord": "N", "start": 2.0, "end": 3.0, "conf": None}, + ]) + + def test_cached_step_preserves_manual_edit_and_force_replaces_it(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "beats.json" + path.write_text('{"manual":true}') + calls = [] + errors = {} + def produce(): + calls.append(1) + path.write_text('{"beats":[],"downbeats":[]}') + run_step("beats", [path], produce, errors, force=False) + self.assertEqual(calls, []) + self.assertEqual(json.loads(path.read_text()), {"manual": True}) + run_step("beats", [path], produce, errors, force=True) + self.assertEqual(len(calls), 1) + self.assertEqual(json.loads(path.read_text())["beats"], []) + + def test_failed_step_records_error_without_blocking_next_step(self): + with tempfile.TemporaryDirectory() as d: + out = Path(d) + errors = {} + def fail(): + raise RuntimeError("model unavailable") + run_step("stems", [out / "vocals.wav"], fail, errors, force=False) + run_step("beats", [out / "beats.json"], lambda: (out / "beats.json").write_text("{}"), errors, force=False) + self.assertIn("model unavailable", errors["stems"]) + self.assertTrue((out / "beats.json").exists()) + + def test_schema_rejects_invalid_pitch_lengths(self): + with self.assertRaises(ValueError): + validate_json("pitch", {"hop_ms": 10, "hz": [440, 441], "conf": [0.9]}) + + def test_pitch_inference_limits_batch_size(self): + import numpy as np + import soundfile as sf + import torch + + with tempfile.TemporaryDirectory() as d: + audio = Path(d) / "vocals.wav" + sf.write(audio, np.zeros(16000, dtype=np.float32), 16000) + def predict(signal, sample_rate, **kwargs): + self.assertEqual(sample_rate, 16000) + self.assertLessEqual(kwargs["batch_size"], 512) + frames = 1 + signal.shape[1] // kwargs["hop_length"] + return torch.zeros((1, frames)), torch.ones((1, frames)) + with patch("torchcrepe.predict", side_effect=predict): + result = detect_pitch(audio) + self.assertEqual(len(result["hz"]), 101) + self.assertEqual(len(result["conf"]), 101) + + def test_madmom_decoder_receives_its_100_hz_frame_rate(self): + module = types.ModuleType("madmom_infer.features.downbeats") + class Activations: + def __call__(self, _): + return "activations" + class Decoder: + def __init__(self, *, beats_per_bar, fps=None): + if fps != 100: + raise TypeError("fps required") + def __call__(self, _): + return [(0.0, 1), (0.5, 2), (1.0, 3)] + module.RNNDownBeatProcessor = Activations + module.DBNDownBeatTrackingProcessor = Decoder + with patch.dict("sys.modules", {"madmom_infer": types.ModuleType("madmom_infer"), + "madmom_infer.features": types.ModuleType("madmom_infer.features"), + "madmom_infer.features.downbeats": module}): + result, bpm = detect_beats(Path("unused.wav")) + self.assertEqual(result, {"beats": [0.0, 0.5, 1.0], "downbeats": [0.0]}) + self.assertEqual(bpm, 120.0) + + def test_default_separator_comes_from_current_python_environment(self): + with tempfile.TemporaryDirectory() as d: + exe = Path(d) / "audio-separator" + exe.write_text("#!/bin/sh\n") + with patch("song_analysis.cli.sys.executable", str(Path(d) / "python")): + self.assertEqual(resolve_separator_bin("audio-separator"), str(exe)) + self.assertEqual(resolve_separator_bin("/custom/sep"), "/custom/sep") + + def test_meta_keeps_manual_values_while_updating_errors(self): + with tempfile.TemporaryDirectory() as d: + source = Path(d) / "song.wav" + source.write_bytes(b"audio") + out = Path(d) / "out" + def fake_normalize(_, target): + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(b"wav") + with patch("song_analysis.backends.normalize", side_effect=fake_normalize), \ + patch("song_analysis.backends.duration_of", return_value=3.0), \ + patch("song_analysis.backends.separate", side_effect=RuntimeError("separator fehlt")), \ + patch("song_analysis.backends.detect_beats", side_effect=RuntimeError("beats fehlen")), \ + patch("song_analysis.backends.detect_chords", side_effect=RuntimeError("chords fehlen")), \ + patch("song_analysis.backends.detect_key", side_effect=RuntimeError("key fehlt")): + analyze(source, out) + meta_path = out / "meta.json" + meta = json.loads(meta_path.read_text()) + meta.update(title="Mein Titel", bpm=97.0, key="G major", duration=2.9) + meta_path.write_text(json.dumps(meta)) + result = analyze(source, out) + self.assertEqual((result["title"], result["bpm"], result["key"], result["duration"]), + ("Mein Titel", 97.0, "G major", 2.9)) + self.assertIn("separator fehlt", result["errors"]["vocals"]) + + +if __name__ == "__main__": + unittest.main()