feat: version song analysis contract and preserve lyric lines
This commit is contained in:
@ -2,9 +2,16 @@
|
||||
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
from difflib import SequenceMatcher
|
||||
from pathlib import Path
|
||||
|
||||
SCHEMA_DIR = Path(__file__).resolve().parents[2] / "schemas" / "song-analysis-v1"
|
||||
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:
|
||||
@ -51,6 +58,66 @@ def group_words(words: list[dict], downbeats: list[float], max_chars: int = 40)
|
||||
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*$')
|
||||
|
||||
|
||||
@ -88,8 +155,13 @@ def validate_json(kind: str, value: object) -> None:
|
||||
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 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:
|
||||
|
||||
Reference in New Issue
Block a user