Datasets:
Download evaluation/typed-normalization.mjs from bryel-labs/MuSP-Bench: direct link, hf CLI and curl.
- Browser
- Download file 9.46 kB
-
https://huggingface.co/datasets/bryel-labs/MuSP-Bench/resolve/main/evaluation/typed-normalization.mjs
- Command line
-
hf download hf://datasets/bryel-labs/MuSP-Bench/evaluation/typed-normalization.mjs
-
curl -L -o typed-normalization.mjs https://huggingface.co/datasets/bryel-labs/MuSP-Bench/resolve/main/evaluation/typed-normalization.mjs
9.46 kB
| import { | |
| matchesAcceptedAnswer, isValidModelAnswer, stripResponseWrapperResidue, | |
| canonicalizePitchSequence, canonicalizeTimestampSequence, | |
| } from './answer-normalization.mjs'; | |
| import {diagnosticMatch} from './normalization-guards.mjs'; | |
| // Offline, versioned experiment. Dispatch uses the editor's answer format; | |
| // no question IDs, model names, predictions, or reference-specific aliases. | |
| export const VERSION = 'task-dependent-experiment-v3-list-separators'; | |
| const symbols = x => String(x ?? '').replaceAll('º','°').normalize('NFKC') | |
| .replaceAll('♯','#').replaceAll('♭','b').replaceAll('𝄪','##').replaceAll('𝄫','bb') | |
| .replaceAll('−','-').replaceAll('–','-').replaceAll('—','-') | |
| .replace(/\b([A-Ga-g])[- ]+double[- ]?sharp(?=\d|\b)/giu,'$1##') | |
| .replace(/\b([A-Ga-g])[- ]+double[- ]?flat(?=\d|\b)/giu,'$1bb') | |
| .replace(/\b([A-Ga-g])[- ]+sharp(?=\d|\b)/giu,'$1#') | |
| .replace(/\b([A-Ga-g])[- ]+flat(?=\d|\b)/giu,'$1b') | |
| .replace(/\b([A-Ga-g])(?:♮|[- ]+natural\b)/giu,'$1'); | |
| function clean(x) { | |
| let s = symbols(stripResponseWrapperResidue(x)).trim().replace(/[.!]+$/u,'').trim(); | |
| // Only remove whole-answer wrappers. Internal delimiters remain significant. | |
| for (let i=0;i<3;i++) { | |
| const pairs = {'[':']','(':')','"':'"',"'":"'",'`':'`','“':'”','‘':'’'}; | |
| if (s.length>1 && pairs[s[0]]===s.at(-1)) s=s.slice(1,-1).trim(); else break; | |
| } | |
| return s; | |
| } | |
| function sequence(s, item) { | |
| const parts=clean(s).split(/\s*[,;]\s*/u); | |
| const keys=parts.map(p=>item(clean(p))); | |
| return keys.length && keys.every(k=>k!==null) ? JSON.stringify(keys) : null; | |
| } | |
| function rational(s) { | |
| const m=/^([+-]?\d+(?:\.\d+)?)(?:\s*\/\s*(\d+))?$/u.exec(s); | |
| if(!m || (m[2]!==undefined && Number(m[2])===0))return null; | |
| // Decimal numerator converted exactly to integer numerator/denominator. | |
| const places=m[1].split('.')[1]?.length??0; | |
| let n=BigInt(m[1].replace('.','')),d=10n**BigInt(places)*BigInt(m[2]??1); | |
| let a=n<0n?-n:n,b=d;while(b){[a,b]=[b,a%b];} | |
| n/=a;d/=a;return `${n}/${d}`; | |
| } | |
| const numberFormats=new Set([ | |
| 'Positive integer','Signed integer','Integer','Bar number (digits)', | |
| 'Bar number (digits) or NA','Beat number (digits)','Beat number (fraction)', | |
| 'Fractional beat number with optional beat prefix', | |
| 'Count in quarter notes','Count of eighth-note durations', | |
| 'Count in number of beats (according to applicable meter)', | |
| ]); | |
| function numeric(s,format) { | |
| let v=clean(s).toLowerCase(); | |
| if(format==='Bar number (digits) or NA' && /^(?:na|n\/a)$/u.test(v))return 'NA'; | |
| if(format.startsWith('Bar number'))v=v.replace(/\b(?:bars?|measures?)\b/gu,''); | |
| if(/beat/iu.test(format))v=v.replace(/\bbeats?\b/gu,''); | |
| if(format==='Count in quarter notes')v=v.replace(/\bquarter[- ]notes?(?:\s+durations?)?\b/gu,''); | |
| if(format==='Count of eighth-note durations')v=v.replace(/\beighth[- ]notes?(?:\s+durations?)?\b/gu,''); | |
| v=v.replace(/\band\b/gu,',').replace(/\s*\/\s*/gu,'/').trim() | |
| .replace(/\s*[,;|]\s*/gu,',').replace(/\s+/gu,','); | |
| return sequence(v,rational); | |
| } | |
| function range(s) { | |
| const m=/^(?:bars?\s+|measures?\s+)?(\d+)\s*(?:-|to|through)\s*(\d+)$/iu.exec(clean(s)); | |
| return m?`${BigInt(m[1])}:${BigInt(m[2])}`:null; | |
| } | |
| function barBeat(s) { | |
| return sequence(s,p=>{ | |
| const m=/^bar\s+(\d+)\s*[, :]?\s*beat\s+(\d+(?:\.\d+)?(?:\/\d+)?)$/iu.exec(p); | |
| return m?`${BigInt(m[1])}:${rational(m[2])}`:null; | |
| }); | |
| } | |
| function pitch(s,octave) { | |
| const v=clean(s).replace(/\band\b/giu,','); | |
| const k=canonicalizePitchSequence(v); | |
| if(k===null)return null; | |
| if(octave && k.includes('pc'))return null; | |
| if(!octave && /(?:^pitches:|\|)n/u.test(k))return null; | |
| return k; | |
| } | |
| const pitchFormats=new Map([ | |
| ['Pitch with octave number',true],['Pitch class without octave number',false], | |
| ['Pitch without octave number',false],['Tonic pitch class without mode',false], | |
| ['Pairs of pitch classes without octave numbers',false], | |
| ]); | |
| function keyOrScale(s,{exactKeySpelling=false}={}) { | |
| return sequence(s,p=>{ | |
| const m=/^([A-Ga-g](?:##|bb|#|b)?)[ -]+((?:(?:harmonic|melodic|natural)\s+)?(?:major|minor))(?:\s+(?:key|scale))?$/iu.exec(p); | |
| // Retain the benchmark's existing enharmonic equivalence. Exact spelling | |
| // is a separately reported policy sensitivity, not a normalization repair. | |
| const tonic=m?(exactKeySpelling?m[1][0].toUpperCase()+m[1].slice(1):canonicalizePitchSequence(m[1])):null; | |
| return m?tonic+':'+m[2].toLowerCase():null; | |
| }); | |
| } | |
| 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}; | |
| function interval(s) { | |
| return sequence(s,p=>{ | |
| const short=/^([mMPAd])\s*(\d+)$/u.exec(p); | |
| if(short)return `${{m:'minor',M:'major',P:'perfect',A:'augmented',d:'diminished'}[short[1]]}:${BigInt(short[2])}`; | |
| const m=/^(major|minor|perfect|augmented|diminished)\s+([a-z]+|\d+(?:st|nd|rd|th)?)$/iu.exec(p); | |
| if(!m)return null; | |
| const n=ordinal[m[2].toLowerCase()]??Number(m[2].replace(/(?:st|nd|rd|th)$/iu,'')); | |
| return Number.isInteger(n)&&n>0?`${m[1].toLowerCase()}:${n}`:null; | |
| }); | |
| } | |
| function roman(s) { | |
| return sequence(s,p=>{ | |
| let v=p.replaceAll('º','°').replace(/\s+/gu,''); | |
| v=v.replace(/(6)\/([45])(?=$|\/)/gu,'$1$2').replace(/4\/3(?=$|\/)/gu,'43').replace(/4\/2(?=$|\/)/gu,'2'); | |
| if(!/^(?:[#b]?[IViv]+[°ø+]?\d*(?:\/[#b]?[IViv]+)?|It\+?6|cad(?:ential)?64)$/u.test(v))return null; | |
| return v; | |
| }); | |
| } | |
| function chord(s) { | |
| return sequence(s,p=>{ | |
| const m=/^([A-Ga-g](?:##|bb|#|b)?)(.*)$/u.exec(p); | |
| if(!m)return null; | |
| const root=canonicalizePitchSequence(m[1]); | |
| let suffix=m[2].replace(/\s+/gu,'').replaceAll('Δ','maj').replaceAll('°','dim').replaceAll('º','dim'); | |
| suffix=suffix.replace(/^M(?=\d|$)/u,'maj').replace(/^major/iu,'maj').replace(/^minor/iu,'m').replace(/^min/iu,'m'); | |
| const bass=/\/([A-Ga-g](?:##|bb|#|b)?)$/u.exec(suffix); | |
| if(bass)suffix=suffix.slice(0,bass.index); | |
| if(suffix==='maj')suffix=''; | |
| if(!/^(?:m|maj|dim|aug|sus[24]?|add\d+|\+)?\d*(?:[#b]\d+|add\d+|sus[24])*(?:\([#b]\d+\))?$/u.test(suffix))return null; | |
| return root+':'+suffix+':'+(bass?canonicalizePitchSequence(bass[1]):''); | |
| }); | |
| } | |
| function noteValue(s) { | |
| return sequence(s,p=>p.toLowerCase().replace(/-/gu,' ') | |
| .replace(/\bsemibreve\b/gu,'whole note').replace(/\bminim\b/gu,'half note') | |
| .replace(/\bcrotchet\b/gu,'quarter note').replace(/\bquaver\b/gu,'eighth note') | |
| .replace(/\bsemiquaver\b/gu,'sixteenth note') | |
| .replace(/\beighth note triplet\b/gu,'triplet eighth note').replace(/\s+/gu,' ').trim()); | |
| } | |
| function fraction(s,reduce) { | |
| return sequence(s,p=>{ | |
| const m=/^(\d+)\s*[/:]\s*(\d+)$/u.exec(p); | |
| return m&&BigInt(m[2])!==0n?(reduce?rational(`${m[1]}/${m[2]}`):`${BigInt(m[1])}/${BigInt(m[2])}`):null; | |
| }); | |
| } | |
| export function family(q) { | |
| const f=q.answer_format; | |
| if(numberFormats.has(f))return 'number'; | |
| if(pitchFormats.has(f))return 'pitch'; | |
| if(f.startsWith('Timestamp'))return 'timestamp'; | |
| if(f==='Roman-numeral chord symbol')return 'roman'; | |
| if(f.startsWith('Lead-sheet chord symbol'))return 'chord'; | |
| if(['Key (pitch class and mode)','Scale (pitch class and mode)','Tonic and mode with accidentals'].includes(f))return 'key-scale'; | |
| if(f==='Interval quality and size')return 'interval'; | |
| if(f==='Bar range (N-N)')return 'range'; | |
| if(f==='Bar and beat')return 'bar-beat'; | |
| if(['Time signature (N/N)','Fraction written as N/N','Ratio'].includes(f))return 'fraction-ratio-meter'; | |
| if(['Note value written in full','Rest value'].includes(f))return 'note-value'; | |
| return 'legacy-guarded'; | |
| } | |
| export function typedKey(value,q,options={}) { | |
| const f=q.answer_format; | |
| switch(family(q)) { | |
| case 'number':return numeric(value,f); | |
| case 'pitch':return pitch(value,pitchFormats.get(f)); | |
| case 'timestamp':return canonicalizeTimestampSequence(clean(value)); | |
| case 'roman':return roman(value); | |
| case 'chord':return chord(value); | |
| case 'key-scale':return keyOrScale(value,options); | |
| case 'interval':return interval(value); | |
| case 'range':return range(value); | |
| case 'bar-beat':return barBeat(value); | |
| case 'fraction-ratio-meter':return fraction(value,f==='Ratio'); | |
| case 'note-value':return noteValue(value); | |
| default:return null; | |
| } | |
| } | |
| export function taskMatch(answer,reference,q,options={}) { | |
| answer = String(answer ?? '').replaceAll('|', ','); | |
| reference = String(reference ?? '').replaceAll('|', ','); | |
| if(!isValidModelAnswer(answer)||!String(reference??'').trim())return false; | |
| const fam=family(q); | |
| if(fam!=='legacy-guarded'){ | |
| const a=typedKey(answer,q,options),b=typedKey(reference,q,options); | |
| if(a!==null&&b!==null)return a===b; | |
| // Fail closed for semantic-case notation, numeric structure and lists. | |
| // A literal match still handles reference-specific phrases such as NA or | |
| // "tonally ambiguous" without trying to interpret their meaning. | |
| if(fam==='roman'||fam==='chord')return clean(answer)===clean(reference); | |
| return clean(answer).toLowerCase()===clean(reference).toLowerCase(); | |
| } | |
| // Preserve existing free-text/title policy: no new fuzzy aliases or grading. | |
| // The separate earlier experiment supplies the targeted collision guards. | |
| return diagnosticMatch(answer,reference,q); | |
| } | |
| export function legacyMatch(answer,reference,q) { | |
| return isValidModelAnswer(answer)&&matchesAcceptedAnswer(answer,reference,{fullQuestion:q.full_question}); | |
| } | |