Datasets:
Add offline MuSP scorer and usage instructions
Browse filesPublish the reference and optional task-dependent scorers, CLI, regression tests, and instructions for using the existing public question CSV. No answer keys, predictions, or musical inputs are uploaded.
- README.md +4 -0
- evaluation/README.md +41 -0
- evaluation/answer-normalization.mjs +314 -0
- evaluation/evaluate.mjs +65 -0
- evaluation/normalization-guards.mjs +29 -0
- evaluation/pitch-name-normalization.test.mjs +26 -0
- evaluation/typed-normalization.mjs +187 -0
README.md
CHANGED
|
@@ -112,6 +112,10 @@ ABC, ABC+MIDI, score images, and a metadata-removed PDF. The `audio` field is a
|
|
| 112 |
relative local path for bundled recordings and an official source URL for the
|
| 113 |
three externally hosted BSED recordings.
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
## Ablation
|
| 116 |
|
| 117 |
The `ablation` configuration compares MIDI1, which uses named pitches, with
|
|
|
|
| 112 |
relative local path for bundled recordings and an official source URL for the
|
| 113 |
three externally hosted BSED recordings.
|
| 114 |
|
| 115 |
+
## Scorer
|
| 116 |
+
|
| 117 |
+
The [offline scorer and usage instructions](evaluation/README.md) are available in `evaluation/`. The package includes the reference normalizer, an optional task-dependent normalizer, a JSONL scoring CLI, and regression tests. The instructions show how to use the existing public question CSV and your own predictions. Scoring requires no model API calls. Report the dataset revision and selected scorer policy with your results.
|
| 118 |
+
|
| 119 |
## Ablation
|
| 120 |
|
| 121 |
The `ablation` configuration compares MIDI1, which uses named pitches, with
|
evaluation/README.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MuSP offline scorer
|
| 2 |
+
|
| 3 |
+
This directory contains the reference answer normalizer, an optional task-dependent normalizer, a scoring CLI, and regression tests. It uses Node.js 20 or later, with no npm dependencies or model API calls.
|
| 4 |
+
|
| 5 |
+
## Use the existing public question table
|
| 6 |
+
|
| 7 |
+
The CLI reads JSONL. Convert the existing `data/questions.csv` into a local answer-key JSONL file with Python's standard library. This preserves the public question IDs and accepted answers in that CSV:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
python - <<'PYTHON'
|
| 11 |
+
import csv, json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
with Path("data/questions.csv").open(newline="", encoding="utf-8") as source, Path("questions-for-scoring.jsonl").open("w", encoding="utf-8") as output:
|
| 14 |
+
for row in csv.DictReader(source):
|
| 15 |
+
row["question_id"] = row.get("question_id") or row["id"]
|
| 16 |
+
row["answers"] = json.loads(row["answers"])
|
| 17 |
+
output.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 18 |
+
PYTHON
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Use predictions in JSONL format, with one object per answer. Each row needs `id` or `question_id` and `answer`. Use IDs from the same question-file revision and `null` for a missing response. Include the full `question` text to enable stale-prompt checks. Optional `model`, `representation`, and `collection` fields distinguish multiple conditions. Do not supply both an editor question ID and a public ID from a different revision.
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
node evaluation/evaluate.mjs --questions questions-for-scoring.jsonl --predictions your-predictions.jsonl --output scored.jsonl --report scored.md
|
| 25 |
+
node evaluation/evaluate.mjs --questions questions-for-scoring.jsonl --predictions your-predictions.jsonl --scorer typed --output scored-typed.jsonl
|
| 26 |
+
node --test evaluation/pitch-name-normalization.test.mjs
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
If a release already supplies `data/questions.jsonl`, use it directly with `--questions`. Saved model predictions and a replacement answer key are not included in this scorer upload. Provide your own prediction file explicitly.
|
| 30 |
+
|
| 31 |
+
## Scoring policies
|
| 32 |
+
|
| 33 |
+
The default `reference` matcher reproduces the existing deterministic normalization policy, including the hyphenated pitch-name correction. It supports pitch identity, conventional instrument aliases, timestamp spellings, response-wrapper cleanup, and a limited work-title rule. General-text fallback can erase meaningful case and punctuation.
|
| 34 |
+
|
| 35 |
+
The optional `typed` matcher uses answer-format-specific normalization for supported formats, preserving Roman-numeral/chord-quality case, numeric values, and ordered boundaries while retaining the established enharmonic policy. Other formats use the guarded reference matcher. Neither policy provides automatic timestamp tolerance, partial credit, or general semantic judgment. State the scorer policy and dataset revision when reporting results.
|
| 36 |
+
|
| 37 |
+
Blank reference entries are ignored. Explicit null predictions count as incorrect; omitted rows are not automatically added. Duplicate prediction rows and mismatched supplied question text are rejected. Include all expected rows, with nulls for missing responses, when comparing against a published denominator. The report prints full questions, IDs, modalities, reference answers, model answers, and correctness.
|
| 38 |
+
|
| 39 |
+
`--compare-typed` reports the number of judgments that differ and exits nonzero when they differ; it is a consistency check, not a requirement that future outputs receive identical grades. Before publication, both matchers agreed on all 5,842 locally saved answer slots in the corrected 2026-10-16 snapshot. Those predictions are not part of this upload, and this check does not establish equivalence on new outputs or other answer-key revisions.
|
| 40 |
+
|
| 41 |
+
This scorer upload does not change the dataset CSV, musical inputs, or historical results table. Rescoring runs locally and incurs no model inference cost.
|
evaluation/answer-normalization.mjs
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
const TEXT_ALIASES = [
|
| 2 |
+
[/\bdouble[- ]?bass(?:es)?\b/gu, "contrabass"],
|
| 3 |
+
[/\bcontrabass(?:es)?\b/gu, "contrabass"],
|
| 4 |
+
[/\bvioloncellos?\b/gu, "cello"],
|
| 5 |
+
[/\bcellos?\b/gu, "cello"],
|
| 6 |
+
[/\bkettledrums?\b/gu, "timpani"],
|
| 7 |
+
[/\btimpanis?\b/gu, "timpani"],
|
| 8 |
+
[/\beighth[- ]note triplets?\b/gu, "triplet eighth note"],
|
| 9 |
+
[/\btriplet eighth[- ]notes?\b/gu, "triplet eighth note"],
|
| 10 |
+
];
|
| 11 |
+
|
| 12 |
+
const INSTRUMENT_ALIASES = [
|
| 13 |
+
[/\b(?:double[- ]?basses|double[- ]?bass|contrabasses|contrabass)\b/gu, "contrabass"],
|
| 14 |
+
[/\b(?:violoncellos?|cellos?)\b/gu, "cello"],
|
| 15 |
+
[/\b(?:kettle\s*drums?|kettledrums?|timpani)\b/gu, "timpani"],
|
| 16 |
+
[/\b(?:english horns?|cor anglais)\b/gu, "english horn"],
|
| 17 |
+
[/\b(?:bass clarinets?)\b/gu, "bass clarinet"],
|
| 18 |
+
[/\b(?:double bassoons?|contrabassoons?)\b/gu, "contrabassoon"],
|
| 19 |
+
[/\b(?:french horns?|horns?)\b/gu, "horn"],
|
| 20 |
+
[/\bpiccolos?\b/gu, "piccolo"],
|
| 21 |
+
[/\bflutes?\b/gu, "flute"],
|
| 22 |
+
[/\boboes?\b/gu, "oboe"],
|
| 23 |
+
[/\bclarinets?\b/gu, "clarinet"],
|
| 24 |
+
[/\bbassoons?\b/gu, "bassoon"],
|
| 25 |
+
[/\btrumpets?\b/gu, "trumpet"],
|
| 26 |
+
[/\btrombones?\b/gu, "trombone"],
|
| 27 |
+
[/\btubas?\b/gu, "tuba"],
|
| 28 |
+
[/\bpercussions?\b/gu, "percussion"],
|
| 29 |
+
[/\bharps?\b/gu, "harp"],
|
| 30 |
+
[/\bpianos?\b/gu, "piano"],
|
| 31 |
+
[/\bcelestas?\b/gu, "celesta"],
|
| 32 |
+
[/\borgans?\b/gu, "organ"],
|
| 33 |
+
[/\bviolins?\b/gu, "violin"],
|
| 34 |
+
[/\bviolas?\b/gu, "viola"],
|
| 35 |
+
];
|
| 36 |
+
|
| 37 |
+
const DIATONIC_PITCH_CLASS = Object.freeze({
|
| 38 |
+
c: 0,
|
| 39 |
+
d: 2,
|
| 40 |
+
e: 4,
|
| 41 |
+
f: 5,
|
| 42 |
+
g: 7,
|
| 43 |
+
a: 9,
|
| 44 |
+
b: 11,
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
const ACCIDENTAL_OFFSET = Object.freeze({
|
| 48 |
+
"": 0,
|
| 49 |
+
"#": 1,
|
| 50 |
+
"##": 2,
|
| 51 |
+
b: -1,
|
| 52 |
+
bb: -2,
|
| 53 |
+
x: 2,
|
| 54 |
+
});
|
| 55 |
+
|
| 56 |
+
export const PITCH_SEQUENCE_NORMALIZATION = Object.freeze({
|
| 57 |
+
system: "chromatic-semitone-v1",
|
| 58 |
+
diatonicPitchClass: DIATONIC_PITCH_CLASS,
|
| 59 |
+
accidentalOffset: ACCIDENTAL_OFFSET,
|
| 60 |
+
octaveConvention: "midi-c-minus-1-is-0",
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
function normalizeMusicalSymbols(value, { preserveStandaloneNatural = false } = {}) {
|
| 64 |
+
let normalized = String(value ?? "")
|
| 65 |
+
.normalize("NFKC")
|
| 66 |
+
.replaceAll("𝄪", "##")
|
| 67 |
+
.replaceAll("𝄫", "bb")
|
| 68 |
+
.replaceAll("♯", "#")
|
| 69 |
+
.replaceAll("♭", "b");
|
| 70 |
+
if (preserveStandaloneNatural) {
|
| 71 |
+
normalized = normalized
|
| 72 |
+
.replace(/\b([A-Ga-g])♮(?=-?\d|(?:\s|[,.;:)\]}]|$))/gu, "$1")
|
| 73 |
+
.replaceAll("♮", "natural");
|
| 74 |
+
} else {
|
| 75 |
+
normalized = normalized.replaceAll("♮", "");
|
| 76 |
+
}
|
| 77 |
+
return normalized
|
| 78 |
+
.replace(/\b([A-Ga-g])[-\s]+double[- ]?sharp(?=\d|\b)/giu, "$1##")
|
| 79 |
+
.replace(/\b([A-Ga-g])[-\s]+double[- ]?flat(?=\d|\b)/giu, "$1bb")
|
| 80 |
+
.replace(/\b([A-Ga-g])[-\s]+sharp(?=\d|\b)/giu, "$1#")
|
| 81 |
+
.replace(/\b([A-Ga-g])[-\s]+flat(?=\d|\b)/giu, "$1b")
|
| 82 |
+
.replace(/\b([A-Ga-g])[-\s]+natural(?=\d|\b)/giu, "$1");
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
function pitchNumber(letter, accidental = "", octave) {
|
| 86 |
+
const unbounded = DIATONIC_PITCH_CLASS[letter.toLocaleLowerCase("en-US")]
|
| 87 |
+
+ ACCIDENTAL_OFFSET[accidental];
|
| 88 |
+
return octave === undefined
|
| 89 |
+
? `pc${((unbounded % 12) + 12) % 12}`
|
| 90 |
+
: `n${(Number(octave) + 1) * 12 + unbounded}`;
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
/**
|
| 94 |
+
* Return an ordered seconds key when the complete answer is a timestamp or
|
| 95 |
+
* timestamp sequence. This makes 00:30, 0:30, 30s, and 30 seconds equal while
|
| 96 |
+
* retaining order and sub-second precision for lists and ranges.
|
| 97 |
+
*/
|
| 98 |
+
export function canonicalizeTimestampSequence(value) {
|
| 99 |
+
const times = [];
|
| 100 |
+
const source = String(value ?? "").normalize("NFKC").toLocaleLowerCase("en-US");
|
| 101 |
+
const remainder = source.replace(
|
| 102 |
+
/\b(?:at\s+)?second\s+(\d+(?:\.\d+)?)\b|\b(\d{1,3}):([0-5]\d(?:\.\d+)?)\b|\b(\d+(?:\.\d+)?)\s*(?:s|secs?|seconds?)\b/giu,
|
| 103 |
+
(match, namedSeconds, minutes, seconds, suffixedSeconds) => {
|
| 104 |
+
const total = namedSeconds !== undefined
|
| 105 |
+
? Number(namedSeconds)
|
| 106 |
+
: (suffixedSeconds !== undefined
|
| 107 |
+
? Number(suffixedSeconds)
|
| 108 |
+
: Number(minutes) * 60 + Number(seconds));
|
| 109 |
+
if (!Number.isFinite(total)) return match;
|
| 110 |
+
times.push(Number(total.toFixed(6)).toString());
|
| 111 |
+
return " ";
|
| 112 |
+
},
|
| 113 |
+
);
|
| 114 |
+
if (!times.length) return null;
|
| 115 |
+
const unsupported = remainder
|
| 116 |
+
.replace(/\b(?:at|from|to|until|through|and)\b/giu, " ")
|
| 117 |
+
.replace(/[\s,;\/–—-]+/gu, "");
|
| 118 |
+
if (unsupported) return null;
|
| 119 |
+
return `times:${times.join("|")}`;
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
/** Canonicalize accidental-bearing or octave-bearing pitch tokens in mixed text. */
|
| 123 |
+
export function canonicalizeEmbeddedPitchTokens(value) {
|
| 124 |
+
return normalizeMusicalSymbols(value, { preserveStandaloneNatural: true }).replace(
|
| 125 |
+
/\b([A-Ga-g])(##|bb|#|b|x)?(-?\d+)?(?![\p{L}\p{N}_#])/gu,
|
| 126 |
+
(token, letter, accidental = "", octave) => {
|
| 127 |
+
// Plain note letters are handled by canonicalizePitchSequence when the
|
| 128 |
+
// complete answer is a pitch list. In prose, leave them untouched to
|
| 129 |
+
// avoid interpreting the article "A" as a pitch.
|
| 130 |
+
if (!accidental && octave === undefined) return token;
|
| 131 |
+
return `pitch${pitchNumber(letter, accidental, octave)}`;
|
| 132 |
+
},
|
| 133 |
+
);
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
/**
|
| 137 |
+
* Return an ordered numeric key when the complete answer is a pitch sequence.
|
| 138 |
+
* Pitch classes are represented modulo 12; octave-bearing pitches use their
|
| 139 |
+
* absolute MIDI-style semitone number, so B#3 and C4 also compare equally.
|
| 140 |
+
*/
|
| 141 |
+
export function canonicalizePitchSequence(value) {
|
| 142 |
+
let source = normalizeMusicalSymbols(value)
|
| 143 |
+
.trim()
|
| 144 |
+
.replace(/[.!?]+$/gu, "")
|
| 145 |
+
.trim();
|
| 146 |
+
|
| 147 |
+
if (!source) return null;
|
| 148 |
+
const tokens = source.split(/[\s,;]+/gu).filter(Boolean);
|
| 149 |
+
if (!tokens.length) return null;
|
| 150 |
+
const numbers = [];
|
| 151 |
+
for (const token of tokens) {
|
| 152 |
+
const match = /^([A-Ga-g])(##|bb|#|b|x)?(-?\d+)?$/u.exec(token);
|
| 153 |
+
if (!match) return null;
|
| 154 |
+
const [, letter, accidental = "", octave] = match;
|
| 155 |
+
numbers.push(pitchNumber(letter, accidental, octave));
|
| 156 |
+
}
|
| 157 |
+
return `pitches:${numbers.join("|")}`;
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
/** Return a sorted, de-duplicated instrument-family key for an instrument-only answer. */
|
| 161 |
+
export function canonicalizeInstrumentAnswer(value) {
|
| 162 |
+
let remainder = String(value ?? "")
|
| 163 |
+
.normalize("NFKC")
|
| 164 |
+
.replaceAll("𝄪", "##")
|
| 165 |
+
.replaceAll("𝄫", "bb")
|
| 166 |
+
.replaceAll("♯", "#")
|
| 167 |
+
.replaceAll("♭", "b")
|
| 168 |
+
.toLocaleLowerCase("en-US");
|
| 169 |
+
|
| 170 |
+
// Orchestral part labels can include a transposition or tuning after the
|
| 171 |
+
// instrument name (for example, "Timpani in D, A"). It identifies no
|
| 172 |
+
// additional instrument and must not become a spurious list item.
|
| 173 |
+
remainder = remainder.replace(
|
| 174 |
+
/\bin\s+[a-g](?:[#b])?(?:\s*,\s*[a-g](?:[#b])?)*\b/gu,
|
| 175 |
+
" ",
|
| 176 |
+
);
|
| 177 |
+
|
| 178 |
+
const instruments = new Set();
|
| 179 |
+
for (const [pattern, canonicalName] of INSTRUMENT_ALIASES) {
|
| 180 |
+
remainder = remainder.replace(pattern, () => {
|
| 181 |
+
instruments.add(canonicalName);
|
| 182 |
+
return " ";
|
| 183 |
+
});
|
| 184 |
+
}
|
| 185 |
+
if (!instruments.size) return null;
|
| 186 |
+
|
| 187 |
+
// Accept conventional numbered score labels ("Flute 1, Flute 2") as the
|
| 188 |
+
// same family-level list as "flute". Do not discard arbitrary numbers:
|
| 189 |
+
// mixed answers can contain a semantically required bar, count, or time.
|
| 190 |
+
remainder = remainder
|
| 191 |
+
.replace(/\b(?:part\s*)?(?:[1-4]|i{1,4}|iv)\b/gu, " ")
|
| 192 |
+
.replace(/\b(?:and|the|instrument|instruments)\b/gu, " ")
|
| 193 |
+
.replace(/[\s,&+\/;:()[\]{}<>"'`‘’“”.!?\-]+/gu, "");
|
| 194 |
+
if (remainder) return null;
|
| 195 |
+
|
| 196 |
+
return `instruments:${[...instruments].sort().join("|")}`;
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
/**
|
| 200 |
+
* Remove observed provider/parser wrapper residue without unwrapping a real
|
| 201 |
+
* JSON response envelope. Examples: ":68} {" -> "68", ":-2" -> "-2",
|
| 202 |
+
* and ":[2,3,1]" -> "[2,3,1]". Residue with no answer becomes empty.
|
| 203 |
+
*/
|
| 204 |
+
export function stripResponseWrapperResidue(value) {
|
| 205 |
+
const source = String(value ?? "").trim();
|
| 206 |
+
if (!source) return "";
|
| 207 |
+
|
| 208 |
+
// A JSON object is a wrong-schema response envelope, not punctuation around
|
| 209 |
+
// an answer. Preserve it so the validity gate can reject it explicitly.
|
| 210 |
+
if (/^\{/u.test(source)) {
|
| 211 |
+
try {
|
| 212 |
+
const parsed = JSON.parse(source);
|
| 213 |
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return source;
|
| 214 |
+
} catch {
|
| 215 |
+
return source;
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
const stripped = source
|
| 220 |
+
.replace(/^\s*:\s*/u, "")
|
| 221 |
+
.replace(/[{}]/gu, "")
|
| 222 |
+
.trim();
|
| 223 |
+
return /^(?:\[|\])$/u.test(stripped) ? "" : stripped;
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
/** Return false for missing, stored-error, malformed-envelope, or placeholder output. */
|
| 227 |
+
export function isValidModelAnswer(value) {
|
| 228 |
+
const source = String(value ?? "").trim();
|
| 229 |
+
const normalized = stripResponseWrapperResidue(source);
|
| 230 |
+
if (!normalized) return false;
|
| 231 |
+
if (
|
| 232 |
+
/^(?:error|failed|failure|null|undefined)\b/iu.test(normalized)
|
| 233 |
+
|| /(?:request failed|internal server error|invalid json|parse error)/iu.test(normalized)
|
| 234 |
+
) return false;
|
| 235 |
+
// Observed provider/parser failure markers. They are non-empty strings but
|
| 236 |
+
// contain no answer and must not be scored as valid model output.
|
| 237 |
+
if (/^(?::\[|\[:)$/u.test(normalized)) return false;
|
| 238 |
+
if (/^\[\s*(?:your answer|insert answer|answer here|placeholder)\s*\]$/iu.test(normalized)) return false;
|
| 239 |
+
// The stored answer field must contain the answer itself. A raw JSON object
|
| 240 |
+
// means the response envelope/schema was not parsed successfully.
|
| 241 |
+
if (/^\{/u.test(normalized)) {
|
| 242 |
+
try {
|
| 243 |
+
const parsed = JSON.parse(normalized);
|
| 244 |
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return false;
|
| 245 |
+
} catch {
|
| 246 |
+
return false;
|
| 247 |
+
}
|
| 248 |
+
}
|
| 249 |
+
return true;
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
/** Normalize formatting plus conservative musical/instrument synonyms. */
|
| 253 |
+
export function normalizeAnswer(value) {
|
| 254 |
+
value = stripResponseWrapperResidue(value);
|
| 255 |
+
const timestampSequence = canonicalizeTimestampSequence(value);
|
| 256 |
+
if (timestampSequence !== null) return timestampSequence;
|
| 257 |
+
|
| 258 |
+
const pitchSequence = canonicalizePitchSequence(value);
|
| 259 |
+
if (pitchSequence !== null) return pitchSequence;
|
| 260 |
+
|
| 261 |
+
const instrumentAnswer = canonicalizeInstrumentAnswer(value);
|
| 262 |
+
if (instrumentAnswer !== null) return instrumentAnswer;
|
| 263 |
+
|
| 264 |
+
let normalized = canonicalizeEmbeddedPitchTokens(value)
|
| 265 |
+
.normalize("NFKC")
|
| 266 |
+
// An explicit natural sign does not change pitch identity. Strip it when
|
| 267 |
+
// it qualifies a pitch so that E♮5 and E5 compare equally, while keeping
|
| 268 |
+
// standalone accidental answers such as "♮, ♮" equivalent to
|
| 269 |
+
// "natural, natural" below.
|
| 270 |
+
.replace(/\b([A-Ga-g])(?:♮|\s+natural\s*)(?=-?\d|(?:\s|[,.;:)\]}]|$))/gu, "$1")
|
| 271 |
+
.replaceAll("𝄪", "##")
|
| 272 |
+
.replaceAll("𝄫", "bb")
|
| 273 |
+
.replaceAll("♯", "#")
|
| 274 |
+
.replaceAll("♭", "b")
|
| 275 |
+
.replaceAll("♮", "natural")
|
| 276 |
+
.toLocaleLowerCase("en-US");
|
| 277 |
+
for (const [pattern, replacement] of TEXT_ALIASES) {
|
| 278 |
+
normalized = normalized.replace(pattern, replacement);
|
| 279 |
+
}
|
| 280 |
+
// V4/2 and V2 are equivalent labels for a third-inversion seventh chord.
|
| 281 |
+
normalized = normalized.replace(/\bv4\s*\/\s*2(?=\s*\/|\b)/gu, "v2");
|
| 282 |
+
return normalized.replace(/[\s,.;:()[\]{}<>"'`‘’“”!?]+/gu, "");
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
const WORK_TITLE_QUESTION = /\btitle\s+of\s+(?:this|the)\s+(?:work|piece|composition)\b/iu;
|
| 286 |
+
const MOVEMENT_QUALIFIER = /(?:^|[\s,;:—–-])(?:movement|mov\.?|mvt\.?)\s+(?:\d+(?:st|nd|rd|th)?|[ivxlcdm]+|first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth)\b/iu;
|
| 287 |
+
|
| 288 |
+
/**
|
| 289 |
+
* Remove a trailing movement (and any following tempo) from a work title.
|
| 290 |
+
* The qualifier is optional identifying detail for a title-of-work answer,
|
| 291 |
+
* rather than part of the work's core title.
|
| 292 |
+
*/
|
| 293 |
+
export function workTitleCore(value) {
|
| 294 |
+
const source = String(value ?? "").normalize("NFKC");
|
| 295 |
+
const movement = MOVEMENT_QUALIFIER.exec(source);
|
| 296 |
+
if (!movement) return source;
|
| 297 |
+
return source.slice(0, movement.index).replace(/[\s,;:—–-]+$/gu, "");
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
/**
|
| 301 |
+
* Compare an answer to one accepted answer using question-aware rules.
|
| 302 |
+
* Normalized exact equality is always preferred. For a title-of-work
|
| 303 |
+
* question, a response that gives the complete core work title may omit an
|
| 304 |
+
* accepted answer's trailing movement/tempo qualifier. The relaxed rule is
|
| 305 |
+
* deliberately one-way: a response containing a movement qualifier must
|
| 306 |
+
* match exactly, so a contradictory movement is never ignored.
|
| 307 |
+
*/
|
| 308 |
+
export function matchesAcceptedAnswer(modelAnswer, acceptedAnswer, { fullQuestion = "" } = {}) {
|
| 309 |
+
if (normalizeAnswer(modelAnswer) === normalizeAnswer(acceptedAnswer)) return true;
|
| 310 |
+
if (!WORK_TITLE_QUESTION.test(String(fullQuestion))) return false;
|
| 311 |
+
if (MOVEMENT_QUALIFIER.test(String(modelAnswer))) return false;
|
| 312 |
+
if (!MOVEMENT_QUALIFIER.test(String(acceptedAnswer))) return false;
|
| 313 |
+
return normalizeAnswer(modelAnswer) === normalizeAnswer(workTitleCore(acceptedAnswer));
|
| 314 |
+
}
|
evaluation/evaluate.mjs
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env node
|
| 2 |
+
/** Offline scorer. No network, providers, or model generation. */
|
| 3 |
+
import fs from 'node:fs';
|
| 4 |
+
import {fileURLToPath} from 'node:url';
|
| 5 |
+
import {resolve,dirname} from 'node:path';
|
| 6 |
+
import {execFileSync} from 'node:child_process';
|
| 7 |
+
import assert from 'node:assert/strict';
|
| 8 |
+
import {isValidModelAnswer,matchesAcceptedAnswer,stripResponseWrapperResidue} from './answer-normalization.mjs';
|
| 9 |
+
import {taskMatch} from './typed-normalization.mjs';
|
| 10 |
+
|
| 11 |
+
const root=resolve(dirname(fileURLToPath(import.meta.url)),'..');
|
| 12 |
+
const args=process.argv.slice(2);
|
| 13 |
+
const opt=(name,fallback)=>{const i=args.indexOf(name);return i<0?fallback:args[i+1];};
|
| 14 |
+
const input=opt('--predictions',resolve(root,'results/predictions.jsonl'));
|
| 15 |
+
const questionFile=opt('--questions',resolve(root,'data/questions.jsonl'));
|
| 16 |
+
const output=opt('--output',null),report=opt('--report',null),db=opt('--live-database',null);
|
| 17 |
+
const scorer=opt('--scorer','reference');
|
| 18 |
+
assert(['reference','typed'].includes(scorer),'Choose --scorer reference or typed');
|
| 19 |
+
const readLines=p=>fs.readFileSync(p,'utf8').split('\n').filter(l=>l.trim()).map(l=>JSON.parse(l));
|
| 20 |
+
const release=readLines(questionFile);
|
| 21 |
+
let authoritative=release;
|
| 22 |
+
if(db){
|
| 23 |
+
assert(fs.statSync(db).size>0);
|
| 24 |
+
assert.equal(fs.readFileSync(db).subarray(0,16).toString(),'SQLite format 3\0');
|
| 25 |
+
const sql=s=>JSON.parse(execFileSync('sqlite3',['-readonly','-json',db,s],{encoding:'utf8',maxBuffer:30e6}));
|
| 26 |
+
assert.equal(sql("SELECT name FROM sqlite_master WHERE type='table' AND name='questions'").length,1);
|
| 27 |
+
const rows=sql("SELECT * FROM questions WHERE status IN ('Final','Approved')");
|
| 28 |
+
const byId=new Map(rows.map(q=>[q.id,q]));assert.equal(rows.length,release.length);
|
| 29 |
+
authoritative=release.map(r=>{
|
| 30 |
+
const q=byId.get(r.question_id);assert(q,'Release question absent from live database');
|
| 31 |
+
assert.equal(r.question,q.full_question,'Release text differs from live editor');
|
| 32 |
+
assert.deepEqual(r.answers,JSON.parse(q.answers),'Release references differ from live editor');
|
| 33 |
+
return {...r,question:q.full_question,modality:q.modality,answers:JSON.parse(q.answers),
|
| 34 |
+
answer_format:q.answer_format,answer_quantity:q.answer_quantity};
|
| 35 |
+
});
|
| 36 |
+
}
|
| 37 |
+
const byId=new Map(authoritative.flatMap(q=>[[q.id,q],[q.question_id,q]]));
|
| 38 |
+
const seen=new Set(),rows=[];let disagreements=0;
|
| 39 |
+
for(const p of readLines(input)){
|
| 40 |
+
const q=byId.get(p.question_id??p.id);assert(q,'Prediction does not identify a question in this release');
|
| 41 |
+
if(p.question!==undefined)assert.equal(p.question,q.question,`Question text differs: ${q.question_id} — ${q.question}`);
|
| 42 |
+
const key=[p.collection??'evaluation',p.model??'unspecified',p.representation??'unspecified',q.question_id].join('\t');
|
| 43 |
+
assert(!seen.has(key),`Duplicate prediction: ${q.question_id} — ${q.question}`);seen.add(key);
|
| 44 |
+
const answer=p.answer===null||p.answer===undefined?null:stripResponseWrapperResidue(p.answer);
|
| 45 |
+
const valid=answer!==null&&isValidModelAnswer(answer);
|
| 46 |
+
const references=q.answers.filter(a=>typeof a==='string'&&a.trim());
|
| 47 |
+
const context={...q,full_question:q.question};
|
| 48 |
+
const referenceCorrect=valid&&references.some(a=>matchesAcceptedAnswer(answer,a,{fullQuestion:q.question}));
|
| 49 |
+
const typedCorrect=valid&&references.some(a=>taskMatch(answer,a,context));
|
| 50 |
+
disagreements+=+(referenceCorrect!==typedCorrect);
|
| 51 |
+
rows.push({...p,id:q.id,question_id:q.question_id,question:q.question,modality:q.modality,
|
| 52 |
+
accepted_answers:q.answers,answer,correct:scorer==='typed'?typedCorrect:referenceCorrect,missing:answer===null});
|
| 53 |
+
}
|
| 54 |
+
if(output)fs.writeFileSync(output,rows.map(r=>JSON.stringify(r)).join('\n')+'\n');
|
| 55 |
+
if(report){
|
| 56 |
+
const esc=s=>String(s??'(missing response)').replaceAll('|','\\|').replaceAll('\n','<br>');
|
| 57 |
+
const groups=new Map();for(const r of rows){const k=[r.collection,r.model,r.representation].join(' · ');if(!groups.has(k))groups.set(k,[]);groups.get(k).push(r);}
|
| 58 |
+
const parts=[`# Scored answers (${scorer})`,'','Denominators count supplied prediction rows, including explicit null answers. Include a null row for every missing expected prediction; omitted rows are not silently imputed. New model cost: $0.',''];
|
| 59 |
+
for(const [label,rs] of groups){parts.push(`## ${label}`,'','| Question ID | Question | Modality | Correct answer | Model answer | Correct |','|---|---|---|---|---|---|',...rs.map(r=>'| '+[r.question_id,r.question,r.modality,r.accepted_answers.filter(Boolean).join(' OR '),r.answer,r.correct?'✅':'❌'].map(esc).join(' | ')+' |'),'');}
|
| 60 |
+
fs.writeFileSync(report,parts.join('\n')+'\n');
|
| 61 |
+
}
|
| 62 |
+
console.log(JSON.stringify({scorer,provided_prediction_slots:rows.length,available:rows.filter(r=>!r.missing).length,
|
| 63 |
+
missing:rows.filter(r=>r.missing).length,correct:rows.filter(r=>r.correct).length,
|
| 64 |
+
...(args.includes('--compare-typed')?{reference_vs_typed_disagreements:disagreements}:{}),new_model_calls:0,new_cost_usd:0},null,2));
|
| 65 |
+
if(args.includes('--compare-typed'))assert.equal(disagreements,0,'The two scorers differ; inspect changed judgments before using shared tables');
|
evaluation/normalization-guards.mjs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Diagnostic only: do not import this into production evaluation.
|
| 2 |
+
// A loss-only experiment isolates false positives caused by the named bugs.
|
| 3 |
+
// Existing matches remain necessary: no synonyms or tolerances are added.
|
| 4 |
+
import {matchesAcceptedAnswer, stripResponseWrapperResidue} from './answer-normalization.mjs';
|
| 5 |
+
|
| 6 |
+
export const numericFormats=new Set([
|
| 7 |
+
'Positive integer','Signed integer','Integer','Bar number (digits)',
|
| 8 |
+
'Bar number (digits) or NA','Bar range (N-N)','Bar and beat',
|
| 9 |
+
'Beat number (digits)','Beat number (fraction)',
|
| 10 |
+
'Fractional beat number with optional beat prefix','Fraction written as N/N',
|
| 11 |
+
'Count in quarter notes','Count of eighth-note durations','Count and ornamentation',
|
| 12 |
+
'Count followed by note value','Count in number of beats (according to applicable meter)',
|
| 13 |
+
'Ratio','Section label followed by start-bar number','Bar number, yes-or-no',
|
| 14 |
+
]);
|
| 15 |
+
|
| 16 |
+
export function romanSignature(value){
|
| 17 |
+
return [...stripResponseWrapperResidue(value).normalize('NFKC').matchAll(/(?<![A-Za-z])[#b♯♭]?[IViv]+(?![A-Za-z])/gu)].map(m=>m[0]);
|
| 18 |
+
}
|
| 19 |
+
export function numberSignature(value){
|
| 20 |
+
return [...stripResponseWrapperResidue(value).normalize('NFKC').matchAll(/[+-]?\d+(?:\.\d+)?/gu)].map(m=>String(Number(m[0])));
|
| 21 |
+
}
|
| 22 |
+
export function diagnosticMatch(answer, reference, question, {roman=true,numeric=true}={}){
|
| 23 |
+
if(!matchesAcceptedAnswer(answer,reference,{fullQuestion:question.full_question}))return false;
|
| 24 |
+
if(roman&&question.answer_format==='Roman-numeral chord symbol'
|
| 25 |
+
&&JSON.stringify(romanSignature(answer))!==JSON.stringify(romanSignature(reference)))return false;
|
| 26 |
+
if(numeric&&numericFormats.has(question.answer_format)
|
| 27 |
+
&&JSON.stringify(numberSignature(answer))!==JSON.stringify(numberSignature(reference)))return false;
|
| 28 |
+
return true;
|
| 29 |
+
}
|
evaluation/pitch-name-normalization.test.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import test from 'node:test';
|
| 2 |
+
import assert from 'node:assert/strict';
|
| 3 |
+
import {matchesAcceptedAnswer,canonicalizePitchSequence} from './answer-normalization.mjs';
|
| 4 |
+
|
| 5 |
+
test('hyphenated and spaced accidental names retain pitch identity',()=>{
|
| 6 |
+
for(const [answer,reference] of [['E-flat','D#'],['E flat','Eb'],['F-sharp','Gb'],['C-double-sharp','D'],['E-double-flat','D'],['E-natural','E']]) {
|
| 7 |
+
assert.equal(matchesAcceptedAnswer(answer,reference),true,`${answer} / ${reference}`);
|
| 8 |
+
}
|
| 9 |
+
});
|
| 10 |
+
test('named accidentals preserve octave and pitch differences',()=>{
|
| 11 |
+
assert.equal(matchesAcceptedAnswer('E-flat4','D#4'),true);
|
| 12 |
+
assert.equal(matchesAcceptedAnswer('B-sharp3','C4'),true);
|
| 13 |
+
assert.equal(matchesAcceptedAnswer('E-flat5','D#4'),false);
|
| 14 |
+
assert.equal(matchesAcceptedAnswer('E-flat','E'),false);
|
| 15 |
+
assert.equal(matchesAcceptedAnswer('E-natural4','Eb4'),false);
|
| 16 |
+
});
|
| 17 |
+
test('pitch lists preserve ordering and repeated notes',()=>{
|
| 18 |
+
assert.equal(matchesAcceptedAnswer('E-flat4, F-sharp4','D#4, Gb4'),true);
|
| 19 |
+
assert.equal(matchesAcceptedAnswer('E-flat4, F-sharp4','Gb4, D#4'),false);
|
| 20 |
+
assert.equal(matchesAcceptedAnswer('E-flat4, E-flat4','D#4'),false);
|
| 21 |
+
});
|
| 22 |
+
test('negative octaves and non-pitch words are not accidental names',()=>{
|
| 23 |
+
assert.equal(canonicalizePitchSequence('C-1'),'pitches:n0');
|
| 24 |
+
assert.equal(canonicalizePitchSequence('E-flatness'),null);
|
| 25 |
+
assert.equal(canonicalizePitchSequence('A-sharpener'),null);
|
| 26 |
+
});
|
evaluation/typed-normalization.mjs
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import {
|
| 2 |
+
matchesAcceptedAnswer, isValidModelAnswer, stripResponseWrapperResidue,
|
| 3 |
+
canonicalizePitchSequence, canonicalizeTimestampSequence,
|
| 4 |
+
} from './answer-normalization.mjs';
|
| 5 |
+
import {diagnosticMatch} from './normalization-guards.mjs';
|
| 6 |
+
|
| 7 |
+
// Offline, versioned experiment. Dispatch uses the editor's answer format;
|
| 8 |
+
// no question IDs, model names, predictions, or reference-specific aliases.
|
| 9 |
+
export const VERSION = 'task-dependent-experiment-v2';
|
| 10 |
+
const symbols = x => String(x ?? '').replaceAll('º','°').normalize('NFKC')
|
| 11 |
+
.replaceAll('♯','#').replaceAll('♭','b').replaceAll('𝄪','##').replaceAll('𝄫','bb')
|
| 12 |
+
.replaceAll('−','-').replaceAll('–','-').replaceAll('—','-')
|
| 13 |
+
.replace(/\b([A-Ga-g])[- ]+double[- ]?sharp(?=\d|\b)/giu,'$1##')
|
| 14 |
+
.replace(/\b([A-Ga-g])[- ]+double[- ]?flat(?=\d|\b)/giu,'$1bb')
|
| 15 |
+
.replace(/\b([A-Ga-g])[- ]+sharp(?=\d|\b)/giu,'$1#')
|
| 16 |
+
.replace(/\b([A-Ga-g])[- ]+flat(?=\d|\b)/giu,'$1b')
|
| 17 |
+
.replace(/\b([A-Ga-g])(?:♮|[- ]+natural\b)/giu,'$1');
|
| 18 |
+
function clean(x) {
|
| 19 |
+
let s = symbols(stripResponseWrapperResidue(x)).trim().replace(/[.!]+$/u,'').trim();
|
| 20 |
+
// Only remove whole-answer wrappers. Internal delimiters remain significant.
|
| 21 |
+
for (let i=0;i<3;i++) {
|
| 22 |
+
const pairs = {'[':']','(':')','"':'"',"'":"'",'`':'`','“':'”','‘':'’'};
|
| 23 |
+
if (s.length>1 && pairs[s[0]]===s.at(-1)) s=s.slice(1,-1).trim(); else break;
|
| 24 |
+
}
|
| 25 |
+
return s;
|
| 26 |
+
}
|
| 27 |
+
function sequence(s, item) {
|
| 28 |
+
const parts=clean(s).split(/\s*[,;]\s*/u);
|
| 29 |
+
const keys=parts.map(p=>item(clean(p)));
|
| 30 |
+
return keys.length && keys.every(k=>k!==null) ? JSON.stringify(keys) : null;
|
| 31 |
+
}
|
| 32 |
+
function rational(s) {
|
| 33 |
+
const m=/^([+-]?\d+(?:\.\d+)?)(?:\s*\/\s*(\d+))?$/u.exec(s);
|
| 34 |
+
if(!m || (m[2]!==undefined && Number(m[2])===0))return null;
|
| 35 |
+
// Decimal numerator converted exactly to integer numerator/denominator.
|
| 36 |
+
const places=m[1].split('.')[1]?.length??0;
|
| 37 |
+
let n=BigInt(m[1].replace('.','')),d=10n**BigInt(places)*BigInt(m[2]??1);
|
| 38 |
+
let a=n<0n?-n:n,b=d;while(b){[a,b]=[b,a%b];}
|
| 39 |
+
n/=a;d/=a;return `${n}/${d}`;
|
| 40 |
+
}
|
| 41 |
+
const numberFormats=new Set([
|
| 42 |
+
'Positive integer','Signed integer','Integer','Bar number (digits)',
|
| 43 |
+
'Bar number (digits) or NA','Beat number (digits)','Beat number (fraction)',
|
| 44 |
+
'Fractional beat number with optional beat prefix',
|
| 45 |
+
'Count in quarter notes','Count of eighth-note durations',
|
| 46 |
+
'Count in number of beats (according to applicable meter)',
|
| 47 |
+
]);
|
| 48 |
+
function numeric(s,format) {
|
| 49 |
+
let v=clean(s).toLowerCase();
|
| 50 |
+
if(format==='Bar number (digits) or NA' && /^(?:na|n\/a)$/u.test(v))return 'NA';
|
| 51 |
+
if(format.startsWith('Bar number'))v=v.replace(/\b(?:bars?|measures?)\b/gu,'');
|
| 52 |
+
if(/beat/iu.test(format))v=v.replace(/\bbeats?\b/gu,'');
|
| 53 |
+
if(format==='Count in quarter notes')v=v.replace(/\bquarter[- ]notes?(?:\s+durations?)?\b/gu,'');
|
| 54 |
+
if(format==='Count of eighth-note durations')v=v.replace(/\beighth[- ]notes?(?:\s+durations?)?\b/gu,'');
|
| 55 |
+
v=v.replace(/\band\b/gu,',').replace(/\s*\/\s*/gu,'/').trim()
|
| 56 |
+
.replace(/\s*[,;|]\s*/gu,',').replace(/\s+/gu,',');
|
| 57 |
+
return sequence(v,rational);
|
| 58 |
+
}
|
| 59 |
+
function range(s) {
|
| 60 |
+
const m=/^(?:bars?\s+|measures?\s+)?(\d+)\s*(?:-|to|through)\s*(\d+)$/iu.exec(clean(s));
|
| 61 |
+
return m?`${BigInt(m[1])}:${BigInt(m[2])}`:null;
|
| 62 |
+
}
|
| 63 |
+
function barBeat(s) {
|
| 64 |
+
return sequence(s,p=>{
|
| 65 |
+
const m=/^bar\s+(\d+)\s*[, :]?\s*beat\s+(\d+(?:\.\d+)?(?:\/\d+)?)$/iu.exec(p);
|
| 66 |
+
return m?`${BigInt(m[1])}:${rational(m[2])}`:null;
|
| 67 |
+
});
|
| 68 |
+
}
|
| 69 |
+
function pitch(s,octave) {
|
| 70 |
+
const v=clean(s).replace(/\band\b/giu,',');
|
| 71 |
+
const k=canonicalizePitchSequence(v);
|
| 72 |
+
if(k===null)return null;
|
| 73 |
+
if(octave && k.includes('pc'))return null;
|
| 74 |
+
if(!octave && /(?:^pitches:|\|)n/u.test(k))return null;
|
| 75 |
+
return k;
|
| 76 |
+
}
|
| 77 |
+
const pitchFormats=new Map([
|
| 78 |
+
['Pitch with octave number',true],['Pitch class without octave number',false],
|
| 79 |
+
['Pitch without octave number',false],['Tonic pitch class without mode',false],
|
| 80 |
+
['Pairs of pitch classes without octave numbers',false],
|
| 81 |
+
]);
|
| 82 |
+
function keyOrScale(s,{exactKeySpelling=false}={}) {
|
| 83 |
+
return sequence(s,p=>{
|
| 84 |
+
const m=/^([A-Ga-g](?:##|bb|#|b)?)[ -]+((?:(?:harmonic|melodic|natural)\s+)?(?:major|minor))(?:\s+(?:key|scale))?$/iu.exec(p);
|
| 85 |
+
// Retain the benchmark's existing enharmonic equivalence. Exact spelling
|
| 86 |
+
// is a separately reported policy sensitivity, not a normalization repair.
|
| 87 |
+
const tonic=m?(exactKeySpelling?m[1][0].toUpperCase()+m[1].slice(1):canonicalizePitchSequence(m[1])):null;
|
| 88 |
+
return m?tonic+':'+m[2].toLowerCase():null;
|
| 89 |
+
});
|
| 90 |
+
}
|
| 91 |
+
const ordinal={unison:1,first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,octave:8,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15};
|
| 92 |
+
function interval(s) {
|
| 93 |
+
return sequence(s,p=>{
|
| 94 |
+
const short=/^([mMPAd])\s*(\d+)$/u.exec(p);
|
| 95 |
+
if(short)return `${{m:'minor',M:'major',P:'perfect',A:'augmented',d:'diminished'}[short[1]]}:${BigInt(short[2])}`;
|
| 96 |
+
const m=/^(major|minor|perfect|augmented|diminished)\s+([a-z]+|\d+(?:st|nd|rd|th)?)$/iu.exec(p);
|
| 97 |
+
if(!m)return null;
|
| 98 |
+
const n=ordinal[m[2].toLowerCase()]??Number(m[2].replace(/(?:st|nd|rd|th)$/iu,''));
|
| 99 |
+
return Number.isInteger(n)&&n>0?`${m[1].toLowerCase()}:${n}`:null;
|
| 100 |
+
});
|
| 101 |
+
}
|
| 102 |
+
function roman(s) {
|
| 103 |
+
return sequence(s,p=>{
|
| 104 |
+
let v=p.replaceAll('º','°').replace(/\s+/gu,'');
|
| 105 |
+
v=v.replace(/(6)\/([45])(?=$|\/)/gu,'$1$2').replace(/4\/3(?=$|\/)/gu,'43').replace(/4\/2(?=$|\/)/gu,'2');
|
| 106 |
+
if(!/^(?:[#b]?[IViv]+[°ø+]?\d*(?:\/[#b]?[IViv]+)?|It\+?6|cad(?:ential)?64)$/u.test(v))return null;
|
| 107 |
+
return v;
|
| 108 |
+
});
|
| 109 |
+
}
|
| 110 |
+
function chord(s) {
|
| 111 |
+
return sequence(s,p=>{
|
| 112 |
+
const m=/^([A-Ga-g](?:##|bb|#|b)?)(.*)$/u.exec(p);
|
| 113 |
+
if(!m)return null;
|
| 114 |
+
const root=canonicalizePitchSequence(m[1]);
|
| 115 |
+
let suffix=m[2].replace(/\s+/gu,'').replaceAll('Δ','maj').replaceAll('°','dim').replaceAll('º','dim');
|
| 116 |
+
suffix=suffix.replace(/^M(?=\d|$)/u,'maj').replace(/^major/iu,'maj').replace(/^minor/iu,'m').replace(/^min/iu,'m');
|
| 117 |
+
const bass=/\/([A-Ga-g](?:##|bb|#|b)?)$/u.exec(suffix);
|
| 118 |
+
if(bass)suffix=suffix.slice(0,bass.index);
|
| 119 |
+
if(suffix==='maj')suffix='';
|
| 120 |
+
if(!/^(?:m|maj|dim|aug|sus[24]?|add\d+|\+)?\d*(?:[#b]\d+|add\d+|sus[24])*(?:\([#b]\d+\))?$/u.test(suffix))return null;
|
| 121 |
+
return root+':'+suffix+':'+(bass?canonicalizePitchSequence(bass[1]):'');
|
| 122 |
+
});
|
| 123 |
+
}
|
| 124 |
+
function noteValue(s) {
|
| 125 |
+
return sequence(s,p=>p.toLowerCase().replace(/-/gu,' ')
|
| 126 |
+
.replace(/\bsemibreve\b/gu,'whole note').replace(/\bminim\b/gu,'half note')
|
| 127 |
+
.replace(/\bcrotchet\b/gu,'quarter note').replace(/\bquaver\b/gu,'eighth note')
|
| 128 |
+
.replace(/\bsemiquaver\b/gu,'sixteenth note')
|
| 129 |
+
.replace(/\beighth note triplet\b/gu,'triplet eighth note').replace(/\s+/gu,' ').trim());
|
| 130 |
+
}
|
| 131 |
+
function fraction(s,reduce) {
|
| 132 |
+
return sequence(s,p=>{
|
| 133 |
+
const m=/^(\d+)\s*[/:]\s*(\d+)$/u.exec(p);
|
| 134 |
+
return m&&BigInt(m[2])!==0n?(reduce?rational(`${m[1]}/${m[2]}`):`${BigInt(m[1])}/${BigInt(m[2])}`):null;
|
| 135 |
+
});
|
| 136 |
+
}
|
| 137 |
+
export function family(q) {
|
| 138 |
+
const f=q.answer_format;
|
| 139 |
+
if(numberFormats.has(f))return 'number';
|
| 140 |
+
if(pitchFormats.has(f))return 'pitch';
|
| 141 |
+
if(f.startsWith('Timestamp'))return 'timestamp';
|
| 142 |
+
if(f==='Roman-numeral chord symbol')return 'roman';
|
| 143 |
+
if(f.startsWith('Lead-sheet chord symbol'))return 'chord';
|
| 144 |
+
if(['Key (pitch class and mode)','Scale (pitch class and mode)','Tonic and mode with accidentals'].includes(f))return 'key-scale';
|
| 145 |
+
if(f==='Interval quality and size')return 'interval';
|
| 146 |
+
if(f==='Bar range (N-N)')return 'range';
|
| 147 |
+
if(f==='Bar and beat')return 'bar-beat';
|
| 148 |
+
if(['Time signature (N/N)','Fraction written as N/N','Ratio'].includes(f))return 'fraction-ratio-meter';
|
| 149 |
+
if(['Note value written in full','Rest value'].includes(f))return 'note-value';
|
| 150 |
+
return 'legacy-guarded';
|
| 151 |
+
}
|
| 152 |
+
export function typedKey(value,q,options={}) {
|
| 153 |
+
const f=q.answer_format;
|
| 154 |
+
switch(family(q)) {
|
| 155 |
+
case 'number':return numeric(value,f);
|
| 156 |
+
case 'pitch':return pitch(value,pitchFormats.get(f));
|
| 157 |
+
case 'timestamp':return canonicalizeTimestampSequence(clean(value));
|
| 158 |
+
case 'roman':return roman(value);
|
| 159 |
+
case 'chord':return chord(value);
|
| 160 |
+
case 'key-scale':return keyOrScale(value,options);
|
| 161 |
+
case 'interval':return interval(value);
|
| 162 |
+
case 'range':return range(value);
|
| 163 |
+
case 'bar-beat':return barBeat(value);
|
| 164 |
+
case 'fraction-ratio-meter':return fraction(value,f==='Ratio');
|
| 165 |
+
case 'note-value':return noteValue(value);
|
| 166 |
+
default:return null;
|
| 167 |
+
}
|
| 168 |
+
}
|
| 169 |
+
export function taskMatch(answer,reference,q,options={}) {
|
| 170 |
+
if(!isValidModelAnswer(answer)||!String(reference??'').trim())return false;
|
| 171 |
+
const fam=family(q);
|
| 172 |
+
if(fam!=='legacy-guarded'){
|
| 173 |
+
const a=typedKey(answer,q,options),b=typedKey(reference,q,options);
|
| 174 |
+
if(a!==null&&b!==null)return a===b;
|
| 175 |
+
// Fail closed for semantic-case notation, numeric structure and lists.
|
| 176 |
+
// A literal match still handles reference-specific phrases such as NA or
|
| 177 |
+
// "tonally ambiguous" without trying to interpret their meaning.
|
| 178 |
+
if(fam==='roman'||fam==='chord')return clean(answer)===clean(reference);
|
| 179 |
+
return clean(answer).toLowerCase()===clean(reference).toLowerCase();
|
| 180 |
+
}
|
| 181 |
+
// Preserve existing free-text/title policy: no new fuzzy aliases or grading.
|
| 182 |
+
// The separate earlier experiment supplies the targeted collision guards.
|
| 183 |
+
return diagnosticMatch(answer,reference,q);
|
| 184 |
+
}
|
| 185 |
+
export function legacyMatch(answer,reference,q) {
|
| 186 |
+
return isValidModelAnswer(answer)&&matchesAcceptedAnswer(answer,reference,{fullQuestion:q.full_question});
|
| 187 |
+
}
|