"""Output contract, caching and timeline utilities for song analysis.""" import json import re import statistics from difflib import SequenceMatcher from pathlib import Path SCHEMA_DIR = Path(__file__).resolve().parents[2] / "schemas" / "song-analysis-v2" def bpm_from_beats(beats: list[float]) -> float | None: gaps = [b - a for a, b in zip(beats, beats[1:]) if 0.2 <= b - a <= 2] return round(60 / statistics.median(gaps), 2) if gaps else None 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 def parse_lyrics(text: str) -> list[dict]: """Preserve sung line numbers and the most recent bracketed section label.""" lines = [] section = None for number, raw in enumerate(text.splitlines(), 1): stripped = raw.strip() if stripped.startswith("#") or not stripped: continue if stripped.startswith("[") and stripped.endswith("]"): section = stripped[1:-1].strip() or None continue lines.append({"text": stripped, "source_line": number, "section": section}) return lines def match_lyric_windows(lines: list[dict], phrases: list[dict]) -> list[tuple[float, float] | None]: """Match each input line to a later ASR phrase; leave uncertain lines unmatched.""" windows = [] cursor_phrase = 0 cursor_word = 0 for line in lines: target = re.findall(r"\w+", line["text"].casefold()) best = (0.0, None) for index in range(cursor_phrase, len(phrases)): candidate = re.findall(r"\w+", phrases[index].get("text", "").casefold()) for start in range(cursor_word if index == cursor_phrase else 0, len(candidate)): for length in range(max(1, len(target) - 2), len(target) + 3): end = min(len(candidate), start + length) score = SequenceMatcher(None, target, candidate[start:end]).ratio() if score > best[0]: best = (score, (index, start, end, len(candidate))) if best[0] >= 0.55 and best[1] is not None: index, start_word, end_word, count = best[1] phrase = phrases[index] start_time, end_time = float(phrase["start"]), float(phrase["end"]) span = end_time - start_time windows.append((max(start_time, start_time + span * start_word / count - 0.3), min(end_time, start_time + span * end_word / count + 0.3))) cursor_phrase, cursor_word = index, end_word else: windows.append(None) return windows def make_aligned_line(source: dict, aligned: list[dict]) -> dict: words = [{"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} for item in aligned if item.get("word", "").strip() and item.get("start") is not None and item.get("end") is not None] scores = [word["conf"] for word in words if word["conf"] is not None] source_count = len(re.findall(r"\w+", source["text"])) coverage = min(1.0, len(words) / source_count) if source_count else 0.0 return {"start": words[0]["start"] if words else None, "end": words[-1]["end"] if words else None, "source_line": source["source_line"], "section": source["section"], "alignment_conf": round(sum(scores) / len(scores) * coverage, 4) if scores else None, "words": words} _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 if item["start"] is not None and item["end"] is not None): raise ValueError(f"{kind}: negativer Zeitbereich") if kind == "lyrics" and any((line["start"] is None) != (line["end"] is None) or (line["start"] is None and line["words"]) for line in value["lines"]): raise ValueError("lyrics: nicht ausgerichtete Zeile braucht null-Zeiten und leere Wörter") 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)