Datasets:
File size: 12,443 Bytes
a97edac b078167 a97edac | 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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | const TEXT_ALIASES = [
[/\bdouble[- ]?bass(?:es)?\b/gu, "contrabass"],
[/\bcontrabass(?:es)?\b/gu, "contrabass"],
[/\bvioloncellos?\b/gu, "cello"],
[/\bcellos?\b/gu, "cello"],
[/\bkettledrums?\b/gu, "timpani"],
[/\btimpanis?\b/gu, "timpani"],
[/\beighth[- ]note triplets?\b/gu, "triplet eighth note"],
[/\btriplet eighth[- ]notes?\b/gu, "triplet eighth note"],
];
const INSTRUMENT_ALIASES = [
[/\b(?:double[- ]?basses|double[- ]?bass|contrabasses|contrabass)\b/gu, "contrabass"],
[/\b(?:violoncellos?|cellos?)\b/gu, "cello"],
[/\b(?:kettle\s*drums?|kettledrums?|timpani)\b/gu, "timpani"],
[/\b(?:english horns?|cor anglais)\b/gu, "english horn"],
[/\b(?:bass clarinets?)\b/gu, "bass clarinet"],
[/\b(?:double bassoons?|contrabassoons?)\b/gu, "contrabassoon"],
[/\b(?:french horns?|horns?)\b/gu, "horn"],
[/\bpiccolos?\b/gu, "piccolo"],
[/\bflutes?\b/gu, "flute"],
[/\boboes?\b/gu, "oboe"],
[/\bclarinets?\b/gu, "clarinet"],
[/\bbassoons?\b/gu, "bassoon"],
[/\btrumpets?\b/gu, "trumpet"],
[/\btrombones?\b/gu, "trombone"],
[/\btubas?\b/gu, "tuba"],
[/\bpercussions?\b/gu, "percussion"],
[/\bharps?\b/gu, "harp"],
[/\bpianos?\b/gu, "piano"],
[/\bcelestas?\b/gu, "celesta"],
[/\borgans?\b/gu, "organ"],
[/\bviolins?\b/gu, "violin"],
[/\bviolas?\b/gu, "viola"],
];
const DIATONIC_PITCH_CLASS = Object.freeze({
c: 0,
d: 2,
e: 4,
f: 5,
g: 7,
a: 9,
b: 11,
});
const ACCIDENTAL_OFFSET = Object.freeze({
"": 0,
"#": 1,
"##": 2,
b: -1,
bb: -2,
x: 2,
});
export const PITCH_SEQUENCE_NORMALIZATION = Object.freeze({
system: "chromatic-semitone-v1",
diatonicPitchClass: DIATONIC_PITCH_CLASS,
accidentalOffset: ACCIDENTAL_OFFSET,
octaveConvention: "midi-c-minus-1-is-0",
});
function normalizeMusicalSymbols(value, { preserveStandaloneNatural = false } = {}) {
let normalized = String(value ?? "")
.normalize("NFKC")
.replaceAll("𝄪", "##")
.replaceAll("𝄫", "bb")
.replaceAll("♯", "#")
.replaceAll("♭", "b");
if (preserveStandaloneNatural) {
normalized = normalized
.replace(/\b([A-Ga-g])♮(?=-?\d|(?:\s|[,.;:)\]}]|$))/gu, "$1")
.replaceAll("♮", "natural");
} else {
normalized = normalized.replaceAll("♮", "");
}
return normalized
.replace(/\b([A-Ga-g])[-\s]+double[- ]?sharp(?=\d|\b)/giu, "$1##")
.replace(/\b([A-Ga-g])[-\s]+double[- ]?flat(?=\d|\b)/giu, "$1bb")
.replace(/\b([A-Ga-g])[-\s]+sharp(?=\d|\b)/giu, "$1#")
.replace(/\b([A-Ga-g])[-\s]+flat(?=\d|\b)/giu, "$1b")
.replace(/\b([A-Ga-g])[-\s]+natural(?=\d|\b)/giu, "$1");
}
function pitchNumber(letter, accidental = "", octave) {
const unbounded = DIATONIC_PITCH_CLASS[letter.toLocaleLowerCase("en-US")]
+ ACCIDENTAL_OFFSET[accidental];
return octave === undefined
? `pc${((unbounded % 12) + 12) % 12}`
: `n${(Number(octave) + 1) * 12 + unbounded}`;
}
/**
* Return an ordered seconds key when the complete answer is a timestamp or
* timestamp sequence. This makes 00:30, 0:30, 30s, and 30 seconds equal while
* retaining order and sub-second precision for lists and ranges.
*/
export function canonicalizeTimestampSequence(value) {
const times = [];
const source = String(value ?? "").normalize("NFKC").toLocaleLowerCase("en-US");
const remainder = source.replace(
/\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,
(match, namedSeconds, minutes, seconds, suffixedSeconds) => {
const total = namedSeconds !== undefined
? Number(namedSeconds)
: (suffixedSeconds !== undefined
? Number(suffixedSeconds)
: Number(minutes) * 60 + Number(seconds));
if (!Number.isFinite(total)) return match;
times.push(Number(total.toFixed(6)).toString());
return " ";
},
);
if (!times.length) return null;
const unsupported = remainder
.replace(/\b(?:at|from|to|until|through|and)\b/giu, " ")
.replace(/[\s,;\/–—-]+/gu, "");
if (unsupported) return null;
return `times:${times.join("|")}`;
}
/** Canonicalize accidental-bearing or octave-bearing pitch tokens in mixed text. */
export function canonicalizeEmbeddedPitchTokens(value) {
return normalizeMusicalSymbols(value, { preserveStandaloneNatural: true }).replace(
/\b([A-Ga-g])(##|bb|#|b|x)?(-?\d+)?(?![\p{L}\p{N}_#])/gu,
(token, letter, accidental = "", octave) => {
// Plain note letters are handled by canonicalizePitchSequence when the
// complete answer is a pitch list. In prose, leave them untouched to
// avoid interpreting the article "A" as a pitch.
if (!accidental && octave === undefined) return token;
return `pitch${pitchNumber(letter, accidental, octave)}`;
},
);
}
/**
* Return an ordered numeric key when the complete answer is a pitch sequence.
* Pitch classes are represented modulo 12; octave-bearing pitches use their
* absolute MIDI-style semitone number, so B#3 and C4 also compare equally.
*/
export function canonicalizePitchSequence(value) {
let source = normalizeMusicalSymbols(value)
.trim()
.replace(/[.!?]+$/gu, "")
.trim();
if (!source) return null;
const tokens = source.split(/[\s,;]+/gu).filter(Boolean);
if (!tokens.length) return null;
const numbers = [];
for (const token of tokens) {
const match = /^([A-Ga-g])(##|bb|#|b|x)?(-?\d+)?$/u.exec(token);
if (!match) return null;
const [, letter, accidental = "", octave] = match;
numbers.push(pitchNumber(letter, accidental, octave));
}
return `pitches:${numbers.join("|")}`;
}
/** Return a sorted, de-duplicated instrument-family key for an instrument-only answer. */
export function canonicalizeInstrumentAnswer(value) {
let remainder = String(value ?? "")
.normalize("NFKC")
.replaceAll("𝄪", "##")
.replaceAll("𝄫", "bb")
.replaceAll("♯", "#")
.replaceAll("♭", "b")
.toLocaleLowerCase("en-US");
// Orchestral part labels can include a transposition or tuning after the
// instrument name (for example, "Timpani in D, A"). It identifies no
// additional instrument and must not become a spurious list item.
remainder = remainder.replace(
/\bin\s+[a-g](?:[#b])?(?:\s*,\s*[a-g](?:[#b])?)*\b/gu,
" ",
);
const instruments = new Set();
for (const [pattern, canonicalName] of INSTRUMENT_ALIASES) {
remainder = remainder.replace(pattern, () => {
instruments.add(canonicalName);
return " ";
});
}
if (!instruments.size) return null;
// Accept conventional numbered score labels ("Flute 1, Flute 2") as the
// same family-level list as "flute". Do not discard arbitrary numbers:
// mixed answers can contain a semantically required bar, count, or time.
remainder = remainder
.replace(/\b(?:part\s*)?(?:[1-4]|i{1,4}|iv)\b/gu, " ")
.replace(/\b(?:and|the|instrument|instruments)\b/gu, " ")
.replace(/[\s,&+\/;:()[\]{}<>"'`‘’“”.!?\-]+/gu, "");
if (remainder) return null;
return `instruments:${[...instruments].sort().join("|")}`;
}
/**
* Remove observed provider/parser wrapper residue without unwrapping a real
* JSON response envelope. Examples: ":68} {" -> "68", ":-2" -> "-2",
* and ":[2,3,1]" -> "[2,3,1]". Residue with no answer becomes empty.
*/
export function stripResponseWrapperResidue(value) {
const source = String(value ?? "").trim();
if (!source) return "";
// A JSON object is a wrong-schema response envelope, not punctuation around
// an answer. Preserve it so the validity gate can reject it explicitly.
if (/^\{/u.test(source)) {
try {
const parsed = JSON.parse(source);
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return source;
} catch {
return source;
}
}
const stripped = source
.replace(/^\s*:\s*/u, "")
.replace(/[{}]/gu, "")
.trim();
return /^(?:\[|\])$/u.test(stripped) ? "" : stripped;
}
/** Return false for missing, stored-error, malformed-envelope, or placeholder output. */
export function isValidModelAnswer(value) {
const source = String(value ?? "").trim();
const normalized = stripResponseWrapperResidue(source);
if (!normalized) return false;
if (
/^(?:error|failed|failure|null|undefined)\b/iu.test(normalized)
|| /(?:request failed|internal server error|invalid json|parse error)/iu.test(normalized)
) return false;
// Observed provider/parser failure markers. They are non-empty strings but
// contain no answer and must not be scored as valid model output.
if (/^(?::\[|\[:)$/u.test(normalized)) return false;
if (/^\[\s*(?:your answer|insert answer|answer here|placeholder)\s*\]$/iu.test(normalized)) return false;
// The stored answer field must contain the answer itself. A raw JSON object
// means the response envelope/schema was not parsed successfully.
if (/^\{/u.test(normalized)) {
try {
const parsed = JSON.parse(normalized);
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return false;
} catch {
return false;
}
}
return true;
}
/** Normalize formatting plus conservative musical/instrument synonyms. */
export function normalizeAnswer(value) {
value = stripResponseWrapperResidue(value);
// Models also use vertical bars as list delimiters. Canonicalize before
// pitch/timestamp parsing, retaining list order and repeated entries.
value = value.replaceAll("|", ",");
const timestampSequence = canonicalizeTimestampSequence(value);
if (timestampSequence !== null) return timestampSequence;
const pitchSequence = canonicalizePitchSequence(value);
if (pitchSequence !== null) return pitchSequence;
const instrumentAnswer = canonicalizeInstrumentAnswer(value);
if (instrumentAnswer !== null) return instrumentAnswer;
let normalized = canonicalizeEmbeddedPitchTokens(value)
.normalize("NFKC")
// An explicit natural sign does not change pitch identity. Strip it when
// it qualifies a pitch so that E♮5 and E5 compare equally, while keeping
// standalone accidental answers such as "♮, ♮" equivalent to
// "natural, natural" below.
.replace(/\b([A-Ga-g])(?:♮|\s+natural\s*)(?=-?\d|(?:\s|[,.;:)\]}]|$))/gu, "$1")
.replaceAll("𝄪", "##")
.replaceAll("𝄫", "bb")
.replaceAll("♯", "#")
.replaceAll("♭", "b")
.replaceAll("♮", "natural")
.toLocaleLowerCase("en-US");
for (const [pattern, replacement] of TEXT_ALIASES) {
normalized = normalized.replace(pattern, replacement);
}
// V4/2 and V2 are equivalent labels for a third-inversion seventh chord.
normalized = normalized.replace(/\bv4\s*\/\s*2(?=\s*\/|\b)/gu, "v2");
return normalized.replace(/[\s,.;:()[\]{}<>"'`‘’“”!?]+/gu, "");
}
const WORK_TITLE_QUESTION = /\btitle\s+of\s+(?:this|the)\s+(?:work|piece|composition)\b/iu;
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;
/**
* Remove a trailing movement (and any following tempo) from a work title.
* The qualifier is optional identifying detail for a title-of-work answer,
* rather than part of the work's core title.
*/
export function workTitleCore(value) {
const source = String(value ?? "").normalize("NFKC");
const movement = MOVEMENT_QUALIFIER.exec(source);
if (!movement) return source;
return source.slice(0, movement.index).replace(/[\s,;:—–-]+$/gu, "");
}
/**
* Compare an answer to one accepted answer using question-aware rules.
* Normalized exact equality is always preferred. For a title-of-work
* question, a response that gives the complete core work title may omit an
* accepted answer's trailing movement/tempo qualifier. The relaxed rule is
* deliberately one-way: a response containing a movement qualifier must
* match exactly, so a contradictory movement is never ignored.
*/
export function matchesAcceptedAnswer(modelAnswer, acceptedAnswer, { fullQuestion = "" } = {}) {
if (normalizeAnswer(modelAnswer) === normalizeAnswer(acceptedAnswer)) return true;
if (!WORK_TITLE_QUESTION.test(String(fullQuestion))) return false;
if (MOVEMENT_QUALIFIER.test(String(modelAnswer))) return false;
if (!MOVEMENT_QUALIFIER.test(String(acceptedAnswer))) return false;
return normalizeAnswer(modelAnswer) === normalizeAnswer(workTitleCore(acceptedAnswer));
}
|