Datasets:
Download evaluation/answer-normalization.mjs from bryel-labs/MuSP-Bench: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/datasets/bryel-labs/MuSP-Bench/resolve/main/evaluation/answer-normalization.mjs
- Command line
-
hf download hf://datasets/bryel-labs/MuSP-Bench/evaluation/answer-normalization.mjs
-
curl -L -o answer-normalization.mjs https://huggingface.co/datasets/bryel-labs/MuSP-Bench/resolve/main/evaluation/answer-normalization.mjs
12.4 kB
| 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)); | |
| } | |