"""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)