Datasets:
Tasks:
Text Generation
Modalities:
Text
Formats:
json
Languages:
English
Size:
10K - 100K
ArXiv:
DOI:
License:
File size: 7,178 Bytes
d09f52e 0aa87cb d09f52e 0aa87cb d09f52e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | """Deterministic scorer for Rameau predictions. Stdlib only — no dependencies.
Usage:
python eval/score.py preds.jsonl --config notes_to_rn --split test
python eval/score.py preds.jsonl --gold data/notes_to_rn/test.jsonl
Predictions file: JSONL, one object per record, with a "prediction" field.
If every object also carries "shape_id" and "key", records are joined on
(shape_id, key); otherwise predictions are matched to gold by line order.
Parsing is deliberately lenient about *wrapping* (markdown fences, prose
before the answer, unicode music symbols) and deliberately strict about the
*answer itself* (Roman numeral case and figures must match exactly).
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
# unicode variants models like to emit -> dataset ASCII conventions
_UNICODE = {
"♭": "b", # flat sign
"♯": "#", # sharp sign
"°": "o", # degree (diminished)
"ø": "%", # slashed o (half-diminished)
"∅": "%", # empty set, occasionally used for half-diminished
"–": "-", "—": "-", # dashes
"⁰": "0", "¹": "1", "²": "2", "³": "3", "⁴": "4",
"⁵": "5", "⁶": "6", "⁷": "7", "⁸": "8", "⁹": "9",
}
_SEPARATORS = {"-", "|", ",", ";", "·", "->", "→"}
_CADENCE_RE = re.compile(r"cadence\s*[:=]\s*([A-Za-z]+)", re.IGNORECASE)
_KEY_RE = re.compile(r"([A-G](?:b{1,2}|#{1,2})?)[\s-]+(major|minor)", re.IGNORECASE)
_FENCE_RE = re.compile(r"^```[a-zA-Z]*\s*$")
def normalize(text: str) -> str:
for k, v in _UNICODE.items():
text = text.replace(k, v)
lines = [ln for ln in text.splitlines() if not _FENCE_RE.match(ln.strip())]
return "\n".join(lines).strip()
def parse_rn(text: str) -> tuple[list[str] | None, str | None]:
"""Extract (labels, cadence) from a model response."""
text = normalize(text)
lines = [ln.strip().strip("`") for ln in text.splitlines() if ln.strip()]
# drop echoed format placeholders like "<Roman numerals ...>"
lines = [ln for ln in lines if not (ln.startswith("<") and ln.endswith(">"))]
if not lines:
return None, None
cadence = None
labels_line = None
cad_idx = None
for i in range(len(lines) - 1, -1, -1):
m = _CADENCE_RE.search(lines[i])
if m:
cadence = m.group(1).upper().rstrip(".")
cad_idx = i
break
if cad_idx is not None:
before = lines[cad_idx][: _CADENCE_RE.search(lines[cad_idx]).start()].strip()
if before: # single-line answer: "ii7 V7 I cadence: PAC"
labels_line = before
else:
for j in range(cad_idx - 1, -1, -1):
if lines[j]:
labels_line = lines[j]
break
else: # nothing above the cadence line: fall back to below
for j in range(cad_idx + 1, len(lines)):
if lines[j]:
labels_line = lines[j]
break
else:
labels_line = lines[-1]
if not labels_line:
return None, cadence
tokens = []
for tok in labels_line.split():
tok = tok.strip("`,.;")
if not tok or tok in _SEPARATORS:
continue
tokens.append(tok)
return (tokens or None), cadence
def parse_key(text: str) -> str | None:
"""Extract 'Tonic mode' from a model response (last match wins)."""
text = normalize(text)
last = None
for m in _KEY_RE.finditer(text):
tonic, mode = m.group(1), m.group(2)
last = f"{tonic[0].upper()}{tonic[1:].lower()} {mode.lower()}"
return last
def load_jsonl(path: Path) -> list[dict]:
with open(path, encoding="utf-8") as fh:
return [json.loads(ln) for ln in fh if ln.strip()]
def join(gold: list[dict], preds: list[dict]) -> list[tuple[dict, dict]]:
if preds and all("shape_id" in p and "key" in p for p in preds):
by_id = {(p["shape_id"], p["key"]): p for p in preds}
pairs = [(g, by_id[(g["shape_id"], g["key"])]) for g in gold
if (g["shape_id"], g["key"]) in by_id]
if len(pairs) < len(preds):
print(f"warning: {len(preds) - len(pairs)} predictions matched no gold record",
file=sys.stderr)
return pairs
if len(preds) != len(gold):
raise SystemExit(
f"positional join needs equal counts (gold {len(gold)}, preds {len(preds)}); "
"or include shape_id+key in each prediction"
)
return list(zip(gold, preds))
def score_rn(pairs: list[tuple[dict, dict]]) -> dict:
n = len(pairs)
exact = labels_exact = cad_ok = parse_fail = 0
chord_hits = chord_total = 0
for g, p in pairs:
labels, cadence = parse_rn(p.get("prediction") or "")
if labels is None:
parse_fail += 1
gl = g["labels"]
l_ok = labels == gl
c_ok = cadence == g["cadence"] # both None counts as correct
labels_exact += l_ok
cad_ok += c_ok
exact += l_ok and c_ok
chord_total += len(gl)
if labels:
chord_hits += sum(a == b for a, b in zip(labels, gl))
return {
"n": n,
"exact": round(exact / n, 4),
"labels_exact": round(labels_exact / n, 4),
"chord_acc": round(chord_hits / chord_total, 4),
"cadence_acc": round(cad_ok / n, 4),
"parse_failures": parse_fail,
}
def score_key(pairs: list[tuple[dict, dict]]) -> dict:
n = len(pairs)
exact = tonic_ok = mode_ok = parse_fail = 0
for g, p in pairs:
pred = parse_key(p.get("prediction") or "")
if pred is None:
parse_fail += 1
continue
gt, gm = g["target"].rsplit(" ", 1)
pt, pm = pred.rsplit(" ", 1)
exact += pred == g["target"]
tonic_ok += pt == gt
mode_ok += pm == gm
return {
"n": n,
"exact": round(exact / n, 4),
"tonic_acc": round(tonic_ok / n, 4),
"mode_acc": round(mode_ok / n, 4),
"parse_failures": parse_fail,
}
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("predictions", type=Path)
ap.add_argument("--config", choices=["symbol_to_rn", "notes_to_rn", "pcset_to_rn", "key_id"])
ap.add_argument("--split", default="test", choices=["train", "validation", "test"])
ap.add_argument("--gold", type=Path, help="explicit gold JSONL (overrides --config/--split)")
args = ap.parse_args()
if args.gold:
gold_path = args.gold
config = args.config or gold_path.parent.name
elif args.config:
gold_path = REPO_ROOT / "data" / args.config / f"{args.split}.jsonl"
config = args.config
else:
raise SystemExit("need --config or --gold")
gold = load_jsonl(gold_path)
preds = load_jsonl(args.predictions)
pairs = join(gold, preds)
metrics = score_key(pairs) if config == "key_id" else score_rn(pairs)
print(json.dumps({"config": config, "split": args.split, **metrics}, indent=2))
if __name__ == "__main__":
main()
|