MaxMnemonic's picture
Refine subtitle and reference-quality wording
0a92605 verified
Raw History Blame Contribute Delete
91.4 kB
const $ = id => document.getElementById(id); // A score: MODS entry, completed by the chosen TEXT measure for Text. k is its page field in scores.json. const MODS = { t: {name: 'Text', unit: 'page', def: 'How much of the reference text each model reproduces, in reading order.'}, b: {name: 'Tables', unit: 'table', k: 'b', def: 'How closely table structure and cell text match the reference, on the tables each model found.'}, l: {name: 'Layout', unit: 'page', score: 'TORE F1', long: 'layout TORE F1', k: 'l', def: 'How well the page area covered by layout regions matches the reference.', detail: 'Area overlap of layout regions, at pixel level. Precision is the share of the model output’s region area that lies inside reference regions, recall the share of the reference region area the output covers, and F1 their harmonic mean. Region types are not compared. Pages without reference regions, or without output, are left out for that model.'}, }; // Table measures, completing MODS.b: f is the build.py page field (tables_h only where build.py packed it). const TABLE = { c: {score: 'TEDS', long: 'table TEDS (structure and cell text)', f: 'tables', detail: 'Tree similarity of two tables. TEDS (tree edit distance similarity) reads each table as a tree of rows and cells and counts the edits that turn one tree into the other, relative to the larger tree. Both structure (rows, cells, merged cells) and cell text count.'}, h: {score: 'TEDS with headers', long: 'table TEDS with header cells (structure, cell text and headers)', f: 'tables_h', detail: 'Tree similarity of two tables. TEDS (tree edit distance similarity) reads each table as a tree of rows and cells and counts the edits that turn one tree into the other, relative to the larger tree. Both structure (rows, cells, merged cells) and cell text count. A header cell against a body cell counts as a changed cell.'}, }; const textMeasures = () => PUBLIC ? {edc: TEXT.edc, f1: TEXT.f1} : TEXT; const tableMeasures = () => D.pages.some(p => p.tables_h) ? TABLE : {c: TABLE.c}; const ptab = p => p[TABLE[st.bm].f]; // Text measures share the normalization described in index.html (#norm). const TEXT = { edc: {score: '1 − NED (chars)', long: 'text character edit similarity (1 − character edit distance)', k: 't_edc', detail: 'Sequence similarity at character level. Edit distance counts the character insertions, deletions and substitutions that turn the model output into the reference, divided by the longer character count. Whitespace is ignored, so spacing and word breaks cost nothing, and a word with one wrong character costs one character, not a whole word. Shown as 1 − distance, so higher is better.'}, ed: {score: '1 − NED (words)', long: 'text edit similarity (1 − edit distance)', k: 't_ed', detail: 'Sequence similarity at word level. Edit distance counts the word insertions, deletions and substitutions that turn the model output into the reference, divided by the longer word count. Shown as 1 − distance, so higher is better. Sensitive to word order.'}, f1: {score: 'F1', long: 'text F1', k: 't', detail: 'Set similarity at word level. Compares the distinct words of the model output and the reference: precision is the share of output words found in the reference, recall the share of reference words found in the output, and F1 their harmonic mean. Word order and repetition are ignored.'}, meteor: {score: 'METEOR', long: 'text METEOR', k: 't_meteor', detail: 'Word alignment score. Aligns the words of the model output with those of the reference (exact, then stems, then synonyms), combines precision and recall with more weight on recall, and applies a penalty when the aligned words are out of order.'}, bleu: {score: 'BLEU', long: 'text BLEU', k: 't_bleu', detail: 'N-gram precision at word level. The share of the model output’s sequences of one to four words that also occur in the reference, with a penalty for output shorter than the reference. Sensitive to word order.'}, }; // Text with build.py EVAL_TARGET doclang (scores.json "eval_target"): a Text chooser, All content // (text.content.all) or a Matched tab with a coverage bar in reference characters, every page weighted by // the characters it scores (build.py w). Without it (markdown) Text renders as before. const CT = () => D.eval_target === 'doclang'; const CONTENT = {all: () => `How closely each model reproduces the reference text. Missed reference text and extra output count against the score. ${pagesCount('text')}`, matched: () => `How closely each model reproduces the reference ${tyWord()}text it matched; the bar shows how much that is. ${pagesCount('matched text')}`,}; // The matching explainer (#match), per score: Text with eval target doclang, and Tables. const MATCHING = { t: `<p>The reference and the model output (the model’s prediction for the page) are each split into spans in reading order: one span per paragraph, heading, list item, formula or table (as its cell text).</p> <p>Every reference span is compared with every output span, wherever they sit on the page; each such combination is a candidate pair. A candidate pair becomes a <b>match</b> only if its two texts are similar enough to be the same content. Each span belongs to at most one match, and the most similar candidates are taken first. A match also takes in a neighbouring span when that makes its two sides more alike, so a paragraph that one side splits into two spans is still matched as a whole.</p> <p>Spans left without a match are unmatched: a reference span is <b>not matched</b> (missed text), an output span is <b>extra</b>.</p> <p>The measure is computed on matches only, one value per match. The <b>Matched</b> tabs average just those, so they show how well a model reproduces what it found; the bar under each score shows how much reference text was matched or not, and how much output is extra. <b>All content</b> also counts not matched and extra spans, at the worst score.</p>`, b: `<p>Each reference table is matched with at most one table of the model output (the model’s prediction for the page): the one that overlaps it on the page, if the overlap is large enough. A reference table without such a counterpart is <b>not matched</b>; an output table matched with no reference table is <b>extra</b>.</p> <p>TEDS is computed and averaged on matched tables only, so read it with the two numbers beside it: the share of reference tables matched, and the output tables that are extra. A table that is split, merged with a neighbour or placed away from its reference counts as both not matched and extra.</p>`, }; // The Text chooser: All content (the page's own scores), then the Matched tabs (build.py ty): all types, and // the benchmark's text_types where some page has them. typed() = a Matched tab. const TYPE_TABS = {formula: 'Matched formulas', code: 'Matched code'}; const tabs = () => Object.fromEntries([['all', 'All content'], ['matched', 'Matched content'], ...(D.text_types || []).map(t => [t, TYPE_TABS[t] || `Matched ${t}`])] .filter(([k]) => k === 'all' || D.pages.some(p => hasType(p, k)))); // Score bar layout (trial). 'types': one Score button per kind of content (Text, each text type, Tables, // Layout), the Text chooser keeps All content | Matched content, and a score with a single measure names it // instead of offering a chooser. 'classic': Text, Tables, Layout, the text types as Matched tabs of the Text // chooser. Only the bar differs: a type button sets st.mod 't' and st.ty as its Matched tab does. // Revert by changing the default below; ?scorebar=classic|types overrides it per page load. const SCOREBAR = new URLSearchParams(globalThis.location?.search).get('scorebar') || 'types'; const TYPE_NAMES = {formula: 'Formulas', code: 'Code'}; const isType = t => t !== 'all' && t !== 'matched'; // [mod, text type or '', name] per Score button const scoreButtons = () => SCOREBAR === 'classic' || !CT() ? Object.keys(MODS).map(k => [k, '', MODS[k].name]) : [['t', '', MODS.t.name], ...Object.keys(tabs()).filter(isType).map(t => ['t', t, TYPE_NAMES[t] || t]), ['b', '', MODS.b.name], ['l', '', MODS.l.name]]; const typed = () => st.mod === 't' && CT() && st.ty !== 'all'; const tyWord = () => typed() && st.ty !== 'matched' ? st.ty + ' ' : ''; // Options (#opt-pop): st.eq counts every page equally where pages are weighted by characters (canWeigh); // a page's own score stays as scored, and pages with no characters to score stay out (their value is null). const canWeigh = () => st.mod === 't' && CT(); const weighted = () => canWeigh() && !st.eq; const pagesCount = what => st.eq ? 'Every page counts equally.' : `Each page counts by its amount of ${what}.`; const AVERAGES = () => st.eq ? 'Within a page, averages are weighted by characters, so long spans count more. Across pages, every page counts equally (Options).' : 'Averages are weighted by characters, so long spans and dense pages count more.'; const hasType = (p, t) => !!p.ty?.[t]?.c.some(c => c[1] > 0); const measure = k => k === 'b' ? {...MODS.b, ...TABLE[st.bm]} : k !== 't' ? MODS[k] : !CT() ? {...MODS.t, ...TEXT[st.tm]} : {...MODS.t, ...TEXT[st.tm], def: typed() ? CONTENT.matched() : CONTENT.all(), long: `${typed() ? `matched ${tyWord()}` : ''}${TEXT[st.tm].long}`}; const M = () => measure(st.mod); const available = (p, i) => !p.u?.includes(sys(i).key); const pairedUnits = () => U.filter(p => available(p, st.a) && available(p, st.b)); const sourceOf = p => D.aggregate ? D.sources[p.bench] : D; const heldPage = p => !!D.heldout || !!sourceOf(p).heldout; const sourceSystem = (p, i) => D.aggregate ? sourceOf(p).systems[sys(i).key] : sys(i); function pageFile(p, side) { if (heldPage(p)) return null; const source = sourceOf(p), folder = side === 'gt' ? source.ref : sourceSystem(p, side)?.dir; return folder ? `data/${p.bench || st.bench}/${folder}/${encodeURIComponent(p.doc ?? p.id)}` : null; } const VIEWS = [['page', 'Page'], ['markup', 'DocLang'], ['reading', 'Reading']]; // Text views, shown only when build.py's EVIDENCE switch packed their files (scores.json "evidence"). const TEXT_VIEWS = [['scored', 'Scored text'], ['raw', 'Raw model output']]; const views = () => D.evidence ? [...VIEWS, ...TEXT_VIEWS] : VIEWS; const NB = 20, TIE = .02; // a: a Docling model (vertical axis), b: a compared model (horizontal axis). Only Docling-vs-other pairs. // sp: Scores by category. k: the facet whose values are the axes; no: values switched off; off: hidden models; // view: the spider chart or its value table, shown one at a time. // tt: the last of All content | Matched content chosen under Text, restored when Text is chosen again const st = {bench: null, mod: 't', tm: 'edc', bm: 'c', ty: 'all', tt: 'all', eq: false, f: {}, a: 0, b: 1, d: {view: 'page', referencePage: false}, sp: {k: null, no: new Set(), off: new Set(), stat: 'mean', fit: true, view: 'chart'}}; let D = null, BENCHES = [], PUBLIC = false, focused = ''; // Set by render(): score field, units with that score, units scored for both compared models, // their scatter tiles, and per-model statistics. let K = 't', U = [], P = [], TL = new Map(), ROWS = []; const pc1 = v => (v * 100).toFixed(1), pc0 = v => v == null ? '—' : (v * 100).toFixed(0), pct = x => x > 0 && x < .01 ? '<1%' : Math.round(x * 100) + '%'; const esc = s => String(s).replace(/[&<>"']/g, c => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'}[c])); const sys = i => D.systems[i]; // Editorial reference-quality labels only; keep benchmark identities and all score data unchanged. const REFERENCE_QUALITY = { gold: {emoji: '🥇', label: 'Gold'}, silver: {emoji: '🥈', label: 'Silver'}, bronze: {emoji: '🥉', label: 'Bronze'}, }; const referenceQuality = b => REFERENCE_QUALITY[b?.reference_quality]; // registry reference_quality, via benchmarks.json const benchmarkLabel = b => `${referenceQuality(b)?.emoji ? referenceQuality(b).emoji + ' ' : ''}${b.name}`; const qualityTitle = b => referenceQuality(b) ? `${referenceQuality(b).label} reference quality` : ''; const facetName = (k, v) => k === 'benchmark' ? benchmarkLabel(BENCHES.find(b => b.name === v) || {name: v}) : vname(v); // Page filters (build.py facets, p.a): st.f maps a facet to its selected values; OR within a facet, AND // across facets. Contains does not apply under Tables, where every unit has a table. const active = () => Object.entries(st.f).filter(([k, vs]) => vs.length && !(st.mod === 'b' && k === 'contains')); const passes = (p, skip) => active().every(([k, vs]) => k === skip || vs.some(v => p.a[k].includes(v))); const subsetPages = () => D.pages.filter(p => passes(p)); // facet counts: pages with value v that pass every other facet const valueCount = (k, v) => D.pages.filter(p => p.a[k].includes(v) && passes(p, k)).length; const shownFacets = () => D.facets.filter(f => !(st.mod === 'b' && f.k === 'contains')); const vname = v => v.replace(/_/g, ' '); const noun = () => M().unit + 's'; // A unit is what docling-inner-eval averages over: a page, or for tables one reference table (a page // copy carrying that table's scores as .b). null = excluded by the evaluator for that system (build.py); // for a table, not matched by that system. Every reference table is a unit, matched by anyone or not. // A text type: pages whose reference has that type, carrying its scores (build.py ty) under the page's // own score fields, and the page itself as .page. const units = () => st.mod === 'b' ? subsetPages().flatMap(p => ptab(p).map((b, tix) => ({...p, b, tix, tn: p.tables.length}))) : typed() ? subsetPages().filter(p => hasType(p, st.ty)).map(p => { const y = p.ty[st.ty]; // not .x/.c: p.x is a flag return {...p, ...Object.fromEntries(Object.values(TEXT).map(({k}) => [k, y[k]])), w: y.w, page: p}; }) : subsetPages().filter(u => u[K].some(v => v != null)); // Coverage of model i, R reference units (tables, or text characters) of which it matched `matched`, plus // its `extra` of `predicted` that matched nothing. pages: the pages with not matched or extra content, // most (not matched + extra) first; the bar's two segments open this one set. // Tables: reference tables it did not match, plus its tables on the page that matched no reference // table (build.py xt). Text (a Matched tab): in-scope characters over the subset's pages (the tab's c and // x), not matched plus extra characters. function coverage(i) { const rank = rows => rows.filter(r => r[1] > 0).sort((a, b) => b[1] - a[1]).map(r => r[0]); if (st.mod === 't') { const cnt = p => [...(p.ty?.[st.ty]?.c[i] || [0, 0]), ...(p.ty?.[st.ty]?.x[i] || [0, 0])]; const rows = subsetPages().map(p => [p, cnt(p)]), sum = j => rows.reduce((a, r) => a + r[1][j], 0); return {pages: rank(rows.map(([p, c]) => [p, c[1] - c[0] + c[2]])), R: sum(1), matched: sum(0), extra: sum(2), predicted: sum(3)}; } const pages = subsetPages().filter(p => available(p, i)), population = U.filter(p => available(p, i)).length, lost = p => p.tables.filter(t => t[i] == null).length, xt = p => p.xt?.[i] || 0; const extra = pages.reduce((a, p) => a + xt(p), 0), matched = population - pages.reduce((a, p) => a + lost(p), 0); return {pages: rank(pages.map(p => [p, lost(p) + xt(p)])), R: population, matched, extra, predicted: matched + extra}; } const hasCoverage = () => st.mod === 'b' || typed(); const chars = n => `${n.toLocaleString('en')} character${n === 1 ? '' : 's'}`; const share = (a, b) => b ? pct(a / b) : '—'; const tbl = n => `${n} table${n === 1 ? '' : 's'}`; // registry.aggregate: statistics.fmean and statistics.pstdev (population std) over the non-null values; // with weights (weighted()) their weighted forms and registry._weighted_percentile // Mean plot mode. 'tukey' = box plot with Tukey whiskers: the furthest score within 1.5 × IQR of // the box (trial); 'box' = box plot with whiskers min–max; both draw a Q1–Q3 box, a median line // and the mean dot. 'q' = whiskers 5th–95th percentile; 'std' = whiskers mean ± one std. // Revert by changing the default below; ?whisker=tukey|box|q|std overrides it per page load. const WHISKER = new URLSearchParams(globalThis.location?.search).get('whisker') || 'tukey'; const WH = { tukey: {box: 1, lo: x => x.tlo, hi: x => x.thi, head: 'Box plot', note: x => `median ${pc1(x.q50)} · IQR ${pc0(x.q25)}–${pc0(x.q75)}`}, box: {box: 1, lo: x => x.min, hi: x => x.max, head: 'Box plot', note: x => `median ${pc1(x.q50)} · IQR ${pc0(x.q25)}–${pc0(x.q75)}`}, q: {lo: x => x.q05, hi: x => x.q95, head: '5–95%', note: x => `std ${pc1(x.std)} · 5–95% ${pc0(x.q05)}–${pc0(x.q95)}`}, std: {lo: x => Math.max(0, x.mean - x.std), hi: x => Math.min(1, x.mean + x.std), head: 'Mean ± std', note: x => `std ${pc1(x.std)}`}, }[WHISKER]; // numpy's default (linear) percentile on sorted values, for unweighted scores const quantile = (s, p) => { const h = (s.length - 1) * p, k = Math.floor(h); return s[k] + (h - k) * (s[Math.min(k + 1, s.length - 1)] - s[k]); }; // registry._weighted_percentile: the first value whose cumulative weight reaches p of the total (pairs sorted) const wquantile = (s, T, p) => { let c = 0; for (const [v, w] of s) if ((c += w) >= p * T) return v; return s.at(-1)[0]; }; // model i's [value, weight] pairs over the units it has a score for, sorted by value const scored = (us, i) => us.filter(u => u[K][i] != null).map(u => [u[K][i], weighted() ? u.w[i] : 1]).sort((a, b) => a[0] - b[0]); // over [value, weight] pairs function stats(s) { const n = s.length, T = s.reduce((a, x) => a + x[1], 0), mean = s.reduce((a, [v, w]) => a + v * w, 0) / T, std = Math.sqrt(s.reduce((a, [v, w]) => a + w * (v - mean) ** 2, 0) / T); return {n, T, mean, std}; } // Clamped: table TEDS with cell text can fall just below 0 (docling_metrics_table); the value itself is // averaged as the evaluator does, only its bin is the lowest one. const binOf = v => Math.max(0, Math.min(NB - 1, Math.floor(v * NB))); function tip(e, html) { const t = $('tip'); t.hidden = !html; if (!html) return; t.innerHTML = html; t.style.left = Math.min(e.clientX + 14, innerWidth - t.offsetWidth - 8) + 'px'; t.style.top = e.clientY + 16 + 'px'; } // A model's identity line, and the marks beside its name: parameter count, and multi-pass inference apart from single-pass. const about = s => `${esc(s.maker)} · ${s.output_syntax === 'doctags' ? 'DocTags → DocLang' : s.docling ? 'native DocLang' : 'mapped to DocLang'}`; const tags = s => (s.params ? ` <span class="size" title="${esc(s.params)} parameters">${esc(s.params)}</span>` : '') + (s.passes > 1 ? ` <span class="passes" title="${s.passes} inference passes per page; the other models use one">${s.passes}-pass</span>` : ''); /* ---------- benchmark × model coverage, independent of the selected page filters ---------- */ // Keep small summaries, not every benchmark's page/evidence data, after the disclosure loads. const realBenchmarks = () => BENCHES.filter(b => !b.aggregate); const COVERAGE = new Map(); let coverageLoading = null; function coverageSummary(data) { return {total: data.dataset_pages ?? data.pages.length, systems: data.systems.map(s => ({key: s.key, label: s.label, usable: data.pages.filter(p => !p.u?.includes(s.key) && !p.f?.includes(s.key) && !p.x?.includes(s.key)).length}))}; } function renderCoverage() { const benchmarks = realBenchmarks(); if (!benchmarks.length || benchmarks.some(b => !COVERAGE.has(b.id))) return; const models = new Map(); for (const b of benchmarks) for (const s of COVERAGE.get(b.id).systems) if (!models.has(s.key)) models.set(s.key, s); let gaps = 0, partial = 0; const gapCounts = benchmarks.map(() => 0); const rows = [...models.values()].map(model => `<tr><th scope="row">${esc(model.label)}</th>${benchmarks.map((b, i) => { const d = COVERAGE.get(b.id), s = d.systems.find(s => s.key === model.key); if (!s) { gaps++; gapCounts[i]++; return '<td class="cov-gap"><span>— Gap</span></td>'; } const incomplete = s.usable < d.total, ready = s.usable * 100 >= d.total * 95; if (!ready) partial++; return `<td class="cov-${ready ? 'ready' : 'partial'}"><span>${ready ? '✓ Ready' : '◐ Partial'}</span><small${incomplete ? ' class="cov-incomplete"' : ''}>${s.usable.toLocaleString('en')} / ${d.total.toLocaleString('en')}</small></td>`; }).join('')}</tr>`).join(''); const total = benchmarks.length * models.size; $('coverage').innerHTML = `<p class="coverage-summary"><b>${total - gaps} of ${total}</b> combinations have results · <b>${gaps} ${gaps === 1 ? 'gap' : 'gaps'}</b> · ${partial} partial</p> <p class="note" id="coverage-key">Ready: usable output for at least 95% of reference pages. Yellow counts mark missing or unreadable outputs. Partial: coverage below 95%. Gap: no evaluated run is included here; raw predictions may exist elsewhere. Each experimental model version has its own row.</p> <div class="coverage-scroll" role="region" aria-label="Prediction coverage matrix" tabindex="0"><table aria-describedby="coverage-key"> <caption>Usable outputs / reference pages, before page filters</caption> <thead><tr><th scope="col">Model / benchmark</th>${benchmarks.map(b => `<th scope="col" title="${esc(qualityTitle(b))}">${esc(benchmarkLabel(b))}</th>`).join('')}</tr></thead> <tbody>${rows}</tbody><tfoot><tr><th scope="row">Missing combinations</th>${gapCounts.map(n => `<td>${n} ${n === 1 ? 'gap' : 'gaps'}</td>`).join('')}</tr></tfoot> </table></div>`; } // scores.json.gz (aggregate.write_metadata): http.server serves it as plain bytes, so the page unpacks it async function fetchScores(id) { const response = await fetch(`data/${id}/scores.json.gz`, {cache: 'no-cache'}); if (!response.ok) throw new Error(`scores ${response.status}`); return new Response(response.body.pipeThrough(new DecompressionStream('gzip'))).json(); } async function loadCoverage() { const benchmarks = realBenchmarks(); if (!benchmarks.length || coverageLoading) return; $('coverage').innerHTML = '<p class="note">Loading coverage…</p>'; coverageLoading = Promise.all(benchmarks.map(async b => { if (COVERAGE.has(b.id)) return; COVERAGE.set(b.id, coverageSummary(await fetchScores(b.id))); })); try { await coverageLoading; renderCoverage(); } catch { $('coverage').innerHTML = '<p class="note">Could not load coverage for every benchmark. <button type="button" class="link" data-coverage-retry>Try again</button></p>'; } finally { coverageLoading = null; } } $('comparison-context').addEventListener('toggle', () => { if (!PUBLIC && $('comparison-context').open) loadCoverage(); }); $('coverage').onclick = e => { if (e.target.closest('[data-coverage-retry]')) loadCoverage(); }; /* ---------- control row: the count here is the population of every chart below ---------- */ function renderBar() { const m = M(), T = D.pages.length, S = subsetPages().length, n = U.length; const bm = BENCHES.find(b => b.id === st.bench); // check.cjs loads no benchmarks.json if (bm) { const q = referenceQuality(bm); $('s0').textContent = benchmarkLabel(bm); $('reference-quality').hidden = !q; $('reference-quality').textContent = q ? `Reference quality: ${q.label}` : ''; $('about').textContent = bm.description; } const opt = b => `<option value="${b.id}" title="${esc(qualityTitle(b))}" ${b.id === st.bench ? 'selected' : ''}>${esc(benchmarkLabel(b))}</option>`, group = (label, l) => `<optgroup label="${label}">${l.map(opt).join('')}</optgroup>`; // held-out benchmarks (build.py heldout) under their own header: scores only, no pages to open const own = BENCHES.filter(b => !b.aggregate), held = own.filter(b => b.heldout); $('bench').innerHTML = !held.length ? BENCHES.map(opt).join('') : BENCHES.filter(b => b.aggregate).map(opt).join('') + group('Public', own.filter(b => !b.heldout)) + group('Held out', held); $('held').hidden = !D.heldout; // in About, under the reference quality const types = SCOREBAR === 'types'; $('mod').innerHTML = scoreButtons().map(([k, t, name]) => `<button type="button" data-m="${k}" data-t="${t}" aria-pressed="${k === st.mod && (k !== 't' || !types || (t ? st.ty === t : !isType(st.ty)))}">${name}</button>`).join(''); $('tm').innerHTML = Object.entries(textMeasures()).map(([k, t]) => `<option value="${k}" ${k === st.tm ? 'selected' : ''}>${t.score}</option>`).join(''); $('d-tm').innerHTML = $('tm').innerHTML; const tms = tableMeasures(), bms = st.mod === 'b' && Object.keys(tms).length > 1; // Tables: a chooser once tables_h exists if (bms) $('tm').innerHTML = Object.entries(tms).map(([k, t]) => `<option value="${k}" ${k === st.bm ? 'selected' : ''}>${t.score}</option>`).join(''); $('tm-field').hidden = !types && st.mod !== 't' && !bms; $('tm').hidden = st.mod !== 't' && !bms; $('tm').ariaLabel = bms ? 'Table measure' : 'Text measure'; $('tm-one').hidden = st.mod === 't' || bms; $('tm-one').textContent = m.score; $('words').hidden = st.tm === 'edc'; // the character measure does not split into words // types bar: "measured as … on All content | Matched content"; the type scores and Tables are matched only, // so they show Matched content pressed and All content disabled. Layout matches nothing. const only = types && (st.mod === 'b' || isType(st.ty)), what = st.mod === 'b' ? 'Tables' : TYPE_NAMES[st.ty] || st.ty; $('ty-field').hidden = !CT() || (types ? st.mod === 'l' : st.mod !== 't'); $('ty-label').textContent = types ? 'on' : 'Text'; $('ty-label').className = types ? 'tm' : 'label'; $('ty').innerHTML = Object.entries(tabs()).filter(([k]) => !types || !isType(k)).map(([k, name]) => only ? `<button type="button" data-t="${k}" aria-pressed="${k === 'matched'}" ${k === 'all' ? `disabled title="${what} are scored on matches only; ${st.mod === 'b' ? 'their cell text counts' : 'they count'} in Text, All content"` : ''}>${name}</button>` : `<button type="button" data-t="${k}" aria-pressed="${k === st.ty}">${name}</button>`).join(''); renderFilters(S, T); renderOptions(); const num = v => v.toLocaleString('en'), tp = new Set(U.map(u => u.id)).size; $('count').textContent = num(n); $('count-what').textContent = st.mod === 'b' ? `reference tables, on ${num(tp)} of ${num(S)} pages` : `${noun()} with ${typed() ? `${tyWord()}text in the reference` : 'a score'}${S - n ? `; the other ${num(S - n)} have ${typed() ? 'none' : 'nothing to score'}` : ''}`; $('scope').innerHTML = leftOut(); } // build.py: only pages every model has a result for are test pages; the reference's other pages (dataset_pages) // are left out, and each system's `missing` counts those it has no result for. function leftOut() { const T = D.pages.length, n = (D.dataset_pages ?? T) - T; return n > 0 ? `${n} more benchmark page${n === 1 ? ' is' : 's are'} left out: not every model has a result for ${n === 1 ? 'it' : 'them'}.` : ''; } // The Pages button, its popover (one fieldset per facet, checkboxes with counts) and a pill per active value. function renderFilters(S, T) { const nv = active().reduce((a, [, vs]) => a + vs.length, 0), pop = $('pf-pop'); $('pf-btn').textContent = nv ? `${nv} filter${nv === 1 ? '' : 's'} · ${S} pages` : `All ${T} pages`; // keep focus and scroll on the checkbox just toggled const had = document.activeElement?.closest?.('#pf-pop') && document.activeElement.dataset, top = pop.scrollTop; pop.innerHTML = shownFacets().map(({k, label, values}) => { const sel = st.f[k] || []; return `<fieldset><legend><span class="label">${esc(label)}</span>${sel.length ? `<button type="button" class="link" data-clear="${k}">Clear</button>` : ''}</legend>${values.map(v => { const on = sel.includes(v), c = valueCount(k, v); return `<label class="chk"><input type="checkbox" data-k="${k}" data-v="${esc(v)}" ${on ? 'checked' : ''} ${c || on ? '' : 'disabled'}>${esc(facetName(k, v))} <small class="num">${c}</small></label>`; }).join('')}</fieldset>`; }).join('') + `<p class="pf-foot"><button type="button" class="link" data-clear="" ${nv ? '' : 'disabled'}>Clear all</button><button type="button" class="link" popovertarget="pf-pop" popovertargetaction="hide">Done</button></p>`; pop.scrollTop = top; if (had) pop.querySelector(`input[data-k="${had.k}"][data-v="${CSS.escape(had.v)}"]`)?.focus(); const eq = st.eq && canWeigh(); $('pills').hidden = !nv && !eq; $('pills').innerHTML = (eq ? '<button type="button" data-eq aria-label="Remove option: every page counts equally"><span>Average</span> every page counts equally <span aria-hidden="true">×</span></button>' : '') + active().flatMap(([k, vs]) => vs.map(v => { const l = esc(D.facets.find(f => f.k === k).label); return `<button type="button" data-k="${k}" data-v="${esc(v)}" aria-label="Remove filter ${l}: ${esc(facetName(k, v))}"><span>${l}</span> ${esc(facetName(k, v))} <span aria-hidden="true">×</span></button>`; })).join(''); } const toggleValue = (k, v, on) => { const vs = (st.f[k] || []).filter(x => x !== v); st.f[k] = on ? [...vs, v] : vs; render(); }; $('pf-pop').onchange = e => { const i = e.target.closest('input[data-k]'); if (i) toggleValue(i.dataset.k, i.dataset.v, i.checked); }; $('pf-pop').onclick = e => { const b = e.target.closest('[data-clear]'); if (!b) return; if (b.dataset.clear) st.f[b.dataset.clear] = []; else st.f = {}; render(); }; $('pills').onclick = e => { if (e.target.closest('[data-eq]')) { st.eq = false; return render(); } const b = e.target.closest('button[data-k]'); if (b) toggleValue(b.dataset.k, b.dataset.v, false); }; function renderOptions() { const on = canWeigh(), pop = $('opt-pop'), had = document.activeElement?.closest?.('#opt-pop'); $('opt-btn').hidden = PUBLIC; $('opt-btn').textContent = st.eq && on ? 'Options · 1' : 'Options'; pop.innerHTML = `<fieldset><legend><span class="label">Average over pages</span></legend>${[['by their amount of text', 'default'], ['every page equally', '']].map(([name, d], v) => `<label class="chk"><input type="radio" name="eq" value="${v}" ${!!v === st.eq ? 'checked' : ''} ${on ? '' : 'disabled'}>${name}${d && ` <small>${d}</small>`}</label>`).join('')}</fieldset> <p class="note">${on ? 'Changes the mean, the spread and the box plot under Score distribution. A page’s own score is not changed, and pages with no text to score stay out.' : 'These scores already count every page or table equally.'}</p> <p class="pf-foot"><span></span><button type="button" class="link" popovertarget="opt-pop" popovertargetaction="hide">Done</button></p>`; if (had) pop.querySelector('input:checked')?.focus(); } $('opt-pop').onchange = e => { if (e.target.name === 'eq') { st.eq = e.target.value === '1'; render(); } }; // a popover opens under its button, inside the viewport const under = (btn, pop, max) => e => { if (e.newState !== 'open') return; // client size, not inner: the visible viewport even when the page is wider than it const {clientWidth: vw, clientHeight: vh} = document.documentElement; const r = $(btn).getBoundingClientRect(), s = $(pop).style, w = Math.min(max, vw - 32); Object.assign(s, {top: `${r.bottom + 6}px`, left: `${Math.max(16, Math.min(r.left, vw - 16 - w))}px`, width: `${w}px`, maxHeight: `${vh - r.bottom - 22}px`}); }; $('pf-pop').onbeforetoggle = under('pf-btn', 'pf-pop', 600); $('opt-pop').onbeforetoggle = under('opt-btn', 'opt-pop', 360); $('about-pop').onbeforetoggle = under('about-btn', 'about-pop', 480); // the address follows the selector, so a reload stays on the chosen benchmark $('bench').onchange = e => { history.replaceState(null, '', '#' + new URLSearchParams({b: e.target.value})); load(e.target.value); }; // The bar's section links scroll rather than set #anchors: the address hash carries the benchmark and deep // links. The target lands below the bar while it is sticky (its height changes with pills and the scope line). $('jump').onclick = e => { const b = e.target.closest('[data-jump]'), bar = $('jump').closest('.bar'); if (!b) return; document.documentElement.style.scrollPaddingTop = getComputedStyle(bar).position === 'sticky' ? `${bar.offsetHeight - 24}px` : ''; $(b.dataset.jump).scrollIntoView(); }; $('mod').onclick = e => { const b = e.target.closest('button'); if (!b) return; st.mod = b.dataset.m; // types bar: a type button opens its Matched tab, Text returns from one to the last Text choice if (SCOREBAR === 'types' && st.mod === 't' && CT()) st.ty = b.dataset.t || (isType(st.ty) ? st.tt : st.ty); render(); }; $('tm').onchange = $('d-tm').onchange = e => { if (e.target.id === 'tm' && st.mod === 'b') { st.bm = e.target.value; render(); return; } st.tm = e.target.value; render(); if (!$('dlg').open) return; const p = st.d.list[st.d.pos]; if (matchedOn()) { overlayRequest++; matchedView(p); } else for (const pane of $('panes').querySelectorAll('.pane[data-side]')) { const scores = pane.querySelector('.scores'); if (scores) scores.outerHTML = pageScores(p, +pane.dataset.side); } }; $('ty').onclick = e => { const b = e.target.closest('button'); if (b && !(SCOREBAR === 'types' && (st.mod === 'b' || isType(st.ty)))) { st.ty = st.tt = b.dataset.t; render(); } }; // matched only: nothing to switch /* ---------- section 1: compact mean, and where page scores fall ---------- */ // Yellow (fewest pages) -> purple (most) in light mode, reversed in dark mode, shows density, independently of score quality. Positions run on a // log scale from the view's smallest count to its largest, and the stops are evenly spaced on it, so every // color step is the same ratio of page counts, then pulled down by STOP_SHIFT so slightly more of the range // is purple. The sparsest end fades in up to the first stop. Both constants are design choices. const LOW_END_OPACITY = .5, STOP_SHIFT = .75; const COUNT_STOP_COLORS = [ {at: 0, color: '--count-orange-high', alpha: LOW_END_OPACITY}, {at: .25 * STOP_SHIFT, color: '--distribution-orange-rich'}, {at: .5 * STOP_SHIFT, color: '--count-orange-low'}, {at: .75 * STOP_SHIFT, color: '--distribution-purple-rich'}, {at: 1, color: '--count-purple-low'}, ]; // dark is the default theme (index.html), light the media-query override const darkMode = () => !globalThis.matchMedia?.('(prefers-color-scheme:light)').matches; const countStops = () => darkMode() ? COUNT_STOP_COLORS.map((p, i, a) => ({...p, color: a[a.length - 1 - i].color})) : COUNT_STOP_COLORS; // a stop's colour, faded to its alpha when it has one const stopColor = p => p.alpha == null ? `var(${p.color})` : `color-mix(in oklab,var(${p.color}) ${p.alpha * 100}%,transparent)`; // floor: the smallest count the scale starts at (yellow); the strips use the view's smallest non-empty bin const countColor = (c, peak, profile, floor = 1) => { if (!c) return 'transparent'; const t = peak > floor ? Math.max(0, Math.min(1, Math.log(c / floor) / Math.log(peak / floor))) : 1; const stops = countStops(); if (!t) return stopColor(stops[0]); const i = stops.findIndex(p => t <= p.at), a = stops[i - 1], b = stops[i]; const mix = Math.round((t - a.at) / (b.at - a.at) * 1000) / 10; return `color-mix(in oklab,${stopColor(b)} ${mix}%,${stopColor(a)})`; }; // Legends use the exact same interpolation stops as the cells and tiles. const countGradient = profile => `linear-gradient(to right in oklab,${countStops().map(p => `${stopColor(p)} ${+(p.at * 100).toFixed(2)}%`).join(',')})`; const countRanges = (peak, profile, floor = 1) => `Continuous ${darkMode() ? 'purple → yellow' : 'yellow → purple'} gradient: ${floor}–${peak} ${noun()}${profile === 'comparison' ? ' per tile' : ''} (log scale)`; // Per model: evaluator statistics over its non-null values in the selected units, plus strip bins (pages). function rowStats() { return D.systems.map((s, i) => { const pw = scored(U, i); const v = pw.map(x => x[0]), n = v.length; if (!n) return null; const x = stats(pw), q = p => weighted() ? wquantile(pw, x.T, p) : quantile(v, p), q25 = q(.25), q75 = q(.75), f = 1.5 * (q75 - q25); const inner = v.filter(y => y >= q25 - f && y <= q75 + f), bins = Array(NB).fill(0); for (const y of v) bins[binOf(y)]++; return {s, i, ...x, min: v[0], max: v[n - 1], q05: q(.05), q25, q50: q(.5), q75, q95: q(.95), tlo: inner[0], thi: inner.at(-1), bins}; }).filter(Boolean); } function renderRows() { const m = M(), n = U.length; $('s1-sub').textContent = `${m.def} Scores in percent, higher is better.`; $('metric-title').textContent = `About ${m.long}`; // a type tab's mean leans on its densest pages const dense = tyWord() && weighted() && U.length && (r => `${pct(r.slice(0, 10).reduce((a, c) => a + c, 0) / r.reduce((a, c) => a + c, 0))} of the reference ${tyWord()}text is on the ${Math.min(10, r.length)} densest of these ${r.length} pages, so they carry about that share of the mean.`)(U.map(u => u.page.ty[st.ty].c[0][1]).sort((a, b) => b - a)); $('metric-body').innerHTML = `<p>${m.detail}${st.mod === 't' && !CT() ? ' An empty output scores 0.' : ''}</p>${dense ? `<p>${dense}</p>` : ''}`; const how = st.mod !== 't' ? MATCHING[st.mod] || '' : CT() ? `${MATCHING.t}<p>${AVERAGES()}</p>` : ''; $('match').hidden = !how; $('match-body').innerHTML = how; $('norm').hidden = st.mod !== 't'; for (const e of document.querySelectorAll('#norm [data-target]')) e.hidden = e.dataset.target !== (CT() ? 'doclang' : 'markdown'); ROWS = n ? rowStats() : []; if (!ROWS.length) { $('rows').innerHTML = '<p class="empty-result">No page in this selection has this score. Change the page filters or the score.</p>'; return; } const peak = Math.max(...ROWS.flatMap(x => x.bins)), floor = Math.min(...ROWS.flatMap(x => x.bins).filter(Boolean)); const matchedShares = new Map(); const span = hasCoverage() ? Math.max(0, ...D.systems.map((_, i) => { const c = coverage(i); matchedShares.set(i, c.R ? c.matched / c.R : 0); return c.R ? 1 + c.extra / c.R : 0; })) : 0; // coverage gets its own column and axis (share of the reference), apart from the box plot's zoomed score axis const c4 = hasCoverage() ? ' c4' : '', cv = i => hasCoverage() ? `<div class="cv">${covBar(i, span)}</div>` : ''; const mn = Math.min(...ROWS.map(WH.lo)), mx = Math.max(...ROWS.map(WH.hi)); const step = mx - mn > .25 ? .1 : mx - mn > .08 ? .05 : .02; const lo = Math.max(0, Math.floor((mn - step * .5) / step) * step), hi = Math.min(1, Math.ceil((mx + step * .5) / step) * step), X = v => (v - lo) / (hi - lo) * 100; // the plot's own axis: a baseline with a tick per step, every other one labelled when they would crowd const at = Array.from({length: Math.round((hi - lo) / step) + 1}, (_, j) => lo + j * step), every = at.length > 7 ? 2 : 1; const gx = (hi - lo) / step; // box plot gridlines, one per axis tick let h = `<div class="r hd${c4}" style="--g:${100 / gx}%"><div class="label">Model</div><div class="mean"><span class="label">Mean</span><div><span class="label">${WH.head}</span><div class="ticks mean-ax">${at.map((v, j) => `<i style="left:${X(v)}%"></i>${j % every ? '' : `<span style="left:${X(v)}%">${pc0(v)}</span>`}`).join('')}</div></div></div>${c4 && `<div><span class="label">Matched · extra</span>${span ? `<div class="ticks mean-ax"><i style="left:0"></i><span style="left:0">0</span>${[.5, 1].map(t => `<i style="left:${t / span * 100}%"></i><span style="left:${t / span * 100}%">${t * 100}${t === 1 ? '%' : ''}</span>`).join('')}</div>` : ''}</div>`} <div class="dist"><span class="label">Where ${m.unit} scores fall</span><div class="ticks">${[0, .25, .5, .75, 1].map(t => `<span style="left:${t * 100}%">${t * 100}</span>`).join('')}</div></div></div>`; // Tie at the displayed precision, using the same coverage totals as the bars. // Keep the full means for every statistic, plot, and the final tie-break. const byScore = (a, b) => (typed() && pc1(a.mean) === pc1(b.mean) ? matchedShares.get(b.i) - matchedShares.get(a.i) : 0) || b.mean - a.mean; for (const x of ROWS.sort(byScore)) { const wl = WH.lo(x), wh = WH.hi(x); h += `<div class="r sys${c4} ${x.s.docling ? 'dl' : ''}" style="--g:${100 / gx}%" data-i="${x.i}"><div class="who"><b><i class="mk"></i><span>${esc(x.s.label)}${tags(x.s)}</span></b><small>${about(x.s)}</small></div> <div class="mean"><b>${pc1(x.mean)}</b><div class="wh" role="img" aria-label="${esc(x.s.label)} mean ${pc1(x.mean)}, median ${pc1(x.q50)}, quartiles ${pc1(x.q25)} to ${pc1(x.q75)}, whiskers ${pc1(wl)} to ${pc1(wh)}, std ${pc1(x.std)}"><i style="left:${X(wl)}%;width:${X(wh) - X(wl)}%"></i>${WH.box ? `<span class="box" style="left:${X(x.q25)}%;width:${X(x.q75) - X(x.q25)}%"></span><span class="med" style="left:${X(x.q50)}%"></span>` : ''}<u style="left:${X(x.mean)}%"></u></div><small>${WH.note(x)}</small></div>${cv(x.i)} <div class="dist"><div class="strip" data-i="${x.i}">${x.bins.map((c, k) => `<button type="button" data-b="${k}" ${c ? '' : 'disabled'} aria-label="${esc(x.s.label)}: ${c} ${noun()} scored ${pc0(k / NB)}–${pc0((k + 1) / NB)}"${c ? ` style="background:${countColor(c, peak, 'distribution', floor)}"` : ''}></button>`).join('')}<i class="m" style="left:${x.mean * 100}%"></i></div></div></div>`; } // a model with no score here keeps its row: under Tables it matched no reference table, its bar shows its extra const none = st.mod === 'b' ? 'matched no reference table' : typed() ? `matched no reference ${tyWord()}text` : `no ${m.long} score`; for (const [i, s] of D.systems.entries()) if (!ROWS.some(x => x.i === i)) h += `<div class="r sys${c4} ${s.docling ? 'dl' : ''}" data-i="${i}"><div class="who"><b><i class="mk"></i><span>${esc(s.label)}${tags(s)}</span></b><small>${about(s)}</small></div> <div class="mean"><b>—</b><small>${none}</small></div>${cv(i)}<div class="dist"></div></div>`; const passes = Math.max(...D.systems.map(s => s.passes || 1)); h += `<p class="key"><span class="ramp temperature" title="${esc(countRanges(peak, 'distribution', floor))}"><s></s>0<i style="background:${countGradient('distribution')}"></i>${peak} ${noun()}</span>${WH.box ? `<span class="bxkey"><u></u>mean<span class="med"></span>median<span class="box"></span>IQR (Q1–Q3)<i></i>${WHISKER === 'box' ? 'min–max' : 'within 1.5 × IQR'}</span>` : ''}<span><i class="mline"></i>mean</span>${hasCoverage() && ROWS.length ? `<span class="ckey"><i class="mt"></i>matched<i class="miss"></i>not matched: no counterpart in the output<i class="xp"></i>extra: no counterpart in the reference</span>` : ''}${ passes > 1 ? `<span><span class="passes">${passes}-pass</span> needs ${passes} prediction passes to produce a complete page result</span>` : ''}</p>`; $('rows').innerHTML = h; } // One bar per model, in shares of its own reference (tables, or text characters), on a scale shared by all // rows: the line at 100% is the reference. Left of it: matched (what the mean averages), then not matched. // Past it: its extra. The // not matched and extra segments open the same pages, most affected first; hover gives the exact counts. function covBar(i, span) { const c = coverage(i), s = sys(i).label, R = c.R, miss = R - c.matched, w = n => `${n / R / span * 100}%`; if (!R) return `<small class="cov">no reference ${st.mod === 'b' ? 'tables' : 'text'} here</small>`; const ty = tyWord(), np = c.pages.length, open = opens(`click to open the ${np} page${np === 1 ? '' : 's'} with not matched or extra ${st.mod === 'b' ? 'tables' : 'text'}`); const tips = st.mod === 'b' ? {miss: `${miss} of ${R} reference tables not matched`, mt: `${c.matched} of ${R} reference tables matched (${pct(c.matched / R)}); the mean covers these`, xp: `${c.extra} extra: ${pct(c.extra / c.predicted)} of its ${tbl(c.predicted)} match no reference table`} : {miss: `${chars(miss)} of ${R.toLocaleString('en')} in the reference ${ty}text not matched`, mt: `${chars(c.matched)} of ${R.toLocaleString('en')} in the reference ${ty}text matched (${share(c.matched, R)}); the mean covers these`, xp: `${chars(c.extra)} extra: ${share(c.extra, c.predicted)} of its ${chars(c.predicted)} of ${ty}output text match no reference text`}; const seg = (k, left, n) => n ? `<button type="button" class="${k}" data-cov data-i="${i}" data-cov-tip="${esc(tips[k] + (open && `<br>${open}`))}" style="left:${w(left)};width:${w(n)}" aria-label="${esc(s)}: ${esc(tips[k] + (open && `; ${open}`))}"></button>` : ''; return `<div class="cbar"><span class="mt" data-cov-tip="${esc(tips.mt)}" style="left:0;width:${w(c.matched)}"></span>${seg('miss', c.matched, miss)}${seg('xp', R, c.extra)}<i class="ref" style="left:${w(R)}"></i></div> <small class="cov">${st.mod === 'b' ? `${pct(c.matched / R)} matched · +${c.extra} extra${c.extra ? ` (${pct(c.extra / c.predicted)})` : ''}` : `${share(c.matched, R)} matched · +${share(c.extra, c.predicted)} extra`}</small>`; } const binPages = (i, b) => U.filter(u => u[K][i] != null && binOf(u[K][i]) === b); const cellOf = e => { const b = e.target.closest('.strip button'); return b && !b.disabled ? [+b.parentElement.dataset.i, +b.dataset.b] : null; }; $('rows').onclick = e => { const v = e.target.closest('button[data-cov]'); if (v) { const i = +v.dataset.i; return openPages(coverage(i).pages, i); } const c = cellOf(e); if (c) openPages(binPages(...c), c[0]); }; $('rows').onmousemove = e => { const v = e.target.closest('.cbar [data-cov-tip]'); if (v) return tip(e, `${esc(sys(+v.closest('.r').dataset.i).label)}<br>${v.dataset.covTip}`); const c = cellOf(e); if (!c) return tip(); const [i, k] = c, x = ROWS.find(r => r.i === i), N = x.bins[k]; const Noun = noun()[0].toUpperCase() + noun().slice(1); tip(e, `<b class="tip-h">${esc(x.s.label)}</b><span class="tip-kv"><span>${esc(M().score)}</span><span>${pc0(k / NB)}–${pc0((k + 1) / NB)}</span><span>${Noun}</span><span><b>${N.toLocaleString('en')}</b> of ${x.n.toLocaleString('en')} (${pct(N / x.n)})</span></span>${opens('<small>click to open</small>')}`); }; $('rows').onmouseleave = () => tip(); /* ---------- section 2: scores by category, one area per model on a spider chart ---------- */ // The axes are the values of one page-filter facet (st.sp.k) that are not switched off (st.sp.no) and have // units. Every page filter applies, as to the other sections, so the bar's count stays the population of // all of them: a filter on the axes' own facet leaves only the axes of its values (and says so if too few). // Each model's fixed colour across benchmarks, never by score rank: its configs/models.yaml `color` (--s0 … --s10) const hue = i => `var(--s${sys(i).color})`; const SPW = 780, SPH = 620, SPR = 205; const STAT = {mean: 'Mean', median: 'Median'}; let SP = []; const spFacet = () => D.facets.find(f => f.k === st.sp.k) || D.facets.find(f => f.k !== 'contains') || D.facets[0]; // Per value of the facet: its units and, per model, the mean or median over the units it has a score for, // computed as rowStats() does (so an axis equals the row of that model with the pages filtered to the value). function spiderCells() { const k = spFacet().k; return spFacet().values.map(v => { const us = U.filter(u => u.a[k].includes(v)); return {v, us, m: D.systems.map((_, i) => { const pw = scored(us, i), n = pw.length; if (!n) return {n, y: null}; return {n, y: st.sp.stat === 'mean' ? stats(pw).mean : weighted() ? wquantile(pw, stats(pw).T, .5) : quantile(pw.map(x => x[0]), .5)}; })}; }); } function renderSpider() { const F = spFacet(), sp = st.sp; $('by-category').hidden = $('j-by-category').hidden = !F; if (!F) return; const m = M(), all = spiderCells(), shown = [...D.systems.keys()].filter(i => !sp.off.has(i)); const seg = (opts, cur) => opts.map(([k, name]) => `<button type="button" data-v="${k}" aria-pressed="${k === cur}">${name}</button>`).join(''); $('sp-k').innerHTML = D.facets.map(f => `<option value="${f.k}" ${f === F ? 'selected' : ''}>${esc(f.label)}</option>`).join(''); $('sp-stat').innerHTML = seg(Object.entries(STAT), sp.stat); $('sp-fit').innerHTML = seg([['', '0–1'], ['1', 'Fit to data']], sp.fit ? '1' : ''); $('sp-view').innerHTML = seg([['chart', 'Chart'], ['table', 'Table']], sp.view); const table = sp.view === 'table'; $('sp-fit').hidden = $('sp-fit-l').hidden = table; // the scale only shapes the chart $('sp-chart').hidden = table; $('sp-tbl').hidden = !table; // keep focus on the checkbox just toggled const had = document.activeElement?.closest?.('#sp-side') && document.activeElement.dataset; $('sp-side').innerHTML = `<fieldset><legend><span class="label">${esc(F.label)}</span><button type="button" class="link" data-all="1">All</button><button type="button" class="link" data-all="">None</button></legend>${ all.map(c => `<label class="chk"><input type="checkbox" data-v="${esc(c.v)}" ${sp.no.has(c.v) ? '' : 'checked'} ${c.us.length ? '' : 'disabled'}>${esc(facetName(F.k, c.v))} <small class="num">${c.us.length}</small></label>`).join('')}</fieldset> <fieldset class="mdls"><legend><span class="label">Models</span></legend>${D.systems.map((s, i) => `<label class="mdl" data-i="${i}"><input type="checkbox" data-i="${i}" ${sp.off.has(i) ? '' : 'checked'}><i class="sw" style="background:${hue(i)}"></i><span>${esc(s.label)}${tags(s)}</span><small>${esc(s.maker)}</small></label>`).join('')}</fieldset>`; if (had) $('sp-side').querySelector(had.v != null ? `input[data-v="${CSS.escape(had.v)}"]` : `input[data-i="${had.i}"]`)?.focus(); SP = all.filter(c => !sp.no.has(c.v) && c.us.length); const own = active().find(([k]) => k === F.k)?.[1], ys = SP.flatMap(c => shown.map(i => c.m[i].y)).filter(y => y != null); $('s3-sub').textContent = `${STAT[sp.stat]} score of each model per ${F.label.toLowerCase()}; n is the number of ${noun()} on each axis.`; const N = SP.length; if (N < 3 || !ys.length) { // too few axes because of the page filter on this facet, not the chips: name it, and offer to lift it const left = all.filter(c => c.us.length).length; $('sp-chart').innerHTML = `<p class="empty-result">${N >= 3 ? 'No shown model has this score on these axes.' : own && left < 3 ? `The Pages filter keeps only ${esc(own.map(v => facetName(F.k, v)).join(', '))} of ${esc(F.label)}, which leaves ${left === 1 ? 'one axis' : `${left} axes`}; a spider chart needs three. <button type="button" class="link" data-clear-own>Clear the ${esc(F.label)} filter</button>, or choose another category for the axes.` : `A spider chart needs three axes or more. Select more ${esc(F.label)} values, or change the page filters.`}</p>`; $('sp-tbl').innerHTML = ''; $('sp-chart').hidden = false; return; } // radial range: 0–1, or the plotted values rounded outwards to a step (the centre is then not 0) let lo = 0, hi = 1; if (sp.fit) { const mn = Math.min(...ys), mx = Math.max(...ys), s = mx - mn > .25 ? .1 : mx - mn > .08 ? .05 : .02; lo = Math.max(0, Math.floor(mn / s - .5) * s); hi = Math.max(lo + s, Math.min(1, Math.ceil(mx / s) * s)); } const ts = [.02, .05, .1, .25].find(s => (hi - lo) / s <= 5.001) || .25, ticks = []; for (let t = lo + ts; t < hi + 1e-9; t += ts) ticks.push(t); // Clamped: table TEDS can fall just below 0 (see binOf); the value itself is kept const rad = y => SPR * Math.max(0, Math.min(1, (y - lo) / (hi - lo))), ang = j => -Math.PI / 2 + 2 * Math.PI * j / N; const pt = (j, r) => [SPW / 2 + r * Math.cos(ang(j)), SPH / 2 + r * Math.sin(ang(j))], xy = p => p.map(v => v.toFixed(1)).join(','); const ring = r => SP.map((_, j) => xy(pt(j, r))).join(' '); // label spacing follows the label font, which index.html enlarges by this factor on phones const k = matchMedia('(max-width:520px)').matches ? 1.6 : 1; const labels = SP.map((c, j) => { const co = Math.cos(ang(j)), si = Math.sin(ang(j)), [x, y0] = pt(j, SPR + 14 * k), y = y0 + (si < -.3 ? -14 : si > .3 ? 10 : -2) * k; return `<text class="axl" data-j="${j}" x="${x.toFixed(1)}" y="${y.toFixed(1)}" text-anchor="${co > .2 ? 'start' : co < -.2 ? 'end' : 'middle'}">${esc(facetName(F.k, c.v))}<tspan class="n" x="${x.toFixed(1)}" dy="${13 * k}">n = ${c.us.length}</tspan></text>`; }).join(''); // a model without a score on an axis has no vertex there; its outline runs straight between its neighbours const verts = i => SP.map((c, j) => c.m[i].y == null ? null : [j, pt(j, rad(c.m[i].y))]).filter(Boolean); const series = shown.map(i => `<g class="s" data-i="${i}"><polygon points="${verts(i).map(v => xy(v[1])).join(' ')}" style="fill:${hue(i)};stroke:${hue(i)}"/>${ verts(i).map(([, p]) => `<circle cx="${p[0].toFixed(1)}" cy="${p[1].toFixed(1)}" r="4" style="fill:${hue(i)}"/>`).join('')}</g>`).join(''); const hits = shown.flatMap(i => verts(i).map(([j, p]) => `<circle class="hit" data-j="${j}" data-i="${i}" cx="${p[0].toFixed(1)}" cy="${p[1].toFixed(1)}" r="9"/>`)).join(''); $('sp-chart').innerHTML = `<svg viewBox="0 0 ${SPW} ${SPH}" role="img" aria-label="${STAT[sp.stat]} ${esc(m.long)} per ${esc(F.label)}, one area per model; the Table view lists the values"> ${ticks.map(t => `<polygon class="ring ${t > hi - 1e-9 ? 'out' : ''}" points="${ring(rad(t))}"/>`).join('')} ${SP.map((_, j) => `<line class="spoke" x1="${SPW / 2}" y1="${SPH / 2}" x2="${pt(j, SPR)[0].toFixed(1)}" y2="${pt(j, SPR)[1].toFixed(1)}"/>`).join('')} ${series} ${[lo, ...ticks].map(t => `<text class="tk" x="${SPW / 2 + 5}" y="${(SPH / 2 - rad(t) - 3).toFixed(1)}">${pc0(t)}</text>`).join('')} ${labels}${hits}</svg>${lo ? `<p class="note">The centre is ${pc0(lo)}, not 0, so the areas exaggerate differences.</p>` : ''}`; $('sp-tbl').innerHTML = `<table><thead><tr><th>${esc(F.label)}</th><th>n</th>${shown.map(i => `<th><i class="sw" style="background:${hue(i)}"></i>${esc(sys(i).label)}</th>`).join('')}</tr></thead><tbody>${ SP.map(c => { const best = Math.max(...shown.map(i => c.m[i].y ?? -Infinity)); return `<tr><td>${esc(facetName(F.k, c.v))}</td><td class="num">${c.us.length}</td>${shown.map(i => `<td class="num ${c.m[i].y === best ? 'top' : ''}">${c.m[i].y == null ? '—' : pc1(c.m[i].y)}</td>`).join('')}</tr>`; }).join('')}</tbody></table>`; } // highlight one model's area, from its vertices or its row in the Models list function spFocus(i) { const svg = $('sp-chart').querySelector('svg'); if (!svg) return; svg.classList.toggle('focus', i != null); for (const g of svg.querySelectorAll('.s')) g.classList.toggle('on', g.dataset.i === String(i)); } $('sp-chart').onmousemove = e => { const h = e.target.closest('[data-j]'); if (!h) { spFocus(null); return tip(); } const c = SP[+h.dataset.j], on = h.dataset.i; spFocus(on); tip(e, `${esc(spFacet().label)}: ${esc(facetName(spFacet().k, c.v))} · ${c.us.length} ${noun()}<br>` + c.m.map((x, i) => [x, i]).filter(([x, i]) => !st.sp.off.has(i) && x.y != null).sort((a, b) => b[0].y - a[0].y) .map(([x, i]) => { const row = `<i class="sw" style="background:${hue(i)}"></i>${esc(sys(i).label)} ${pc1(x.y)}${x.n < c.us.length ? ` (n = ${x.n})` : ''}`; return String(i) === on ? `<b>${row}</b>` : row; }).join('<br>') + (on != null ? opens('<br>click to open its pages, lowest score first') : '')); }; $('sp-chart').onmouseleave = () => { spFocus(null); tip(); }; $('sp-chart').onclick = e => { if (e.target.closest('[data-clear-own]')) { st.f[spFacet().k] = []; return render(); } const h = e.target.closest('.hit'); if (!h) return; const i = +h.dataset.i; openPages(SP[+h.dataset.j].us.filter(u => u[K][i] != null).sort((a, b) => a[K][i] - b[K][i]), i); }; $('sp-side').onmouseover = e => { const l = e.target.closest('.mdl'); spFocus(l && !st.sp.off.has(+l.dataset.i) ? l.dataset.i : null); }; $('sp-side').onmouseleave = () => spFocus(null); $('sp-side').onchange = e => { const d = e.target.dataset, [set, k] = d.v != null ? [st.sp.no, d.v] : [st.sp.off, +d.i]; e.target.checked ? set.delete(k) : set.add(k); renderSpider(); }; $('sp-side').onclick = e => { const b = e.target.closest('[data-all]'); if (b) { st.sp.no = new Set(b.dataset.all ? [] : spFacet().values); renderSpider(); } }; $('sp-k').onchange = e => { st.sp.k = e.target.value; st.sp.no = new Set(); renderSpider(); }; $('sp-stat').onclick = e => { const b = e.target.closest('button'); if (b) { st.sp.stat = b.dataset.v; renderSpider(); } }; $('sp-view').onclick = e => { const b = e.target.closest('button'); if (b) { st.sp.view = b.dataset.v; renderSpider(); } }; $('sp-fit').onclick = e => { const b = e.target.closest('button'); if (b) { st.sp.fit = !!b.dataset.v; renderSpider(); } }; /* ---------- section 3: one Docling model against one other model ---------- */ // corner labels sit in the margins, outside the frame; H keeps the plot area square const W = 460, PL = 46, PB = 62, PT = 42, PR = 14, H = W - PL - PR + PT + PB; const sx = v => PL + v * (W - PL - PR), sy = v => H - PB - v * (H - PB - PT); // Fixed 2D bins instead of one dot per page, as in the comparison report: G×G tiles on 0–1 × 0–1, // shaded by page count with the same ramp as the strips. One tile spans the ±TIE band's width. const G = 50, gbin = v => Math.max(0, Math.min(G - 1, Math.floor(v * G))); function tiles(keep = () => true) { const t = new Map(); for (const p of P) if (keep(p)) { const k = `${gbin(p[K][st.b])},${gbin(p[K][st.a])}`; (t.get(k) || t.set(k, []).get(k)).push(p); } return t; } const gapOf = p => p[K][st.a] - p[K][st.b]; const groupOf = p => gapOf(p) > TIE ? 'a' : gapOf(p) < -TIE ? 'b' : 't'; function groups() { const g = {a: [], t: [], b: []}; for (const p of P) g[groupOf(p)].push(p); g.a.sort((x, y) => gapOf(y) - gapOf(x)); g.b.sort((x, y) => gapOf(x) - gapOf(y)); g.t.sort((x, y) => Math.abs(gapOf(y)) - Math.abs(gapOf(x))); return g; } const GROUP = {a: () => `${sys(st.a).label} better`, t: () => `Within ±${pc0(TIE)}`, b: () => `${sys(st.b).label} better`}; const SW = {a: 'var(--accent)', t: 'var(--border-accent)', b: 'var(--text-secondary)'}; function renderH2H() { $('comparison').hidden = $('j-comparison').hidden = !D.systems.some(s => s.docling) || !D.systems.some(s => !s.docling); if ($('comparison').hidden) return; const opts = (k, dl) => D.systems.map((s, i) => s.docling === dl ? `<option value="${i}" ${i === k ? 'selected' : ''}>${esc(s.label)}</option>` : '').join(''); $('pa').innerHTML = opts(st.a, true); $('pb').innerHTML = opts(st.b, false); const m = M(), A = esc(sys(st.a).label), B = esc(sys(st.b).label), n = P.length, left = (st.mod === 'b' ? pairedUnits() : U).length - n; $('s2-sub').textContent = `Each ${st.mod === 'b' ? 'reference table both models matched' : m.unit} is placed by its score for ${sys(st.a).label} (up) and ${sys(st.b).label} (across); tile color shows how many. Above the diagonal the Docling model scores higher.${st.mod === 'b' && left ? ` The other ${tbl(left)} are listed below.` : ''}`; focused = ''; TL = tiles(); if (!n) { $('scatter').innerHTML = ''; $('tally').innerHTML = `<p class="empty-result">${st.mod === 'b' && U.length ? `No reference table is matched by both ${A} and ${B}.` : `No ${noun()} to compare.`}</p>` + (U.length ? outside() : ''); return; } const peak = Math.max(...[...TL.values()].map(l => l.length)), floor = Math.min(...[...TL.values()].map(l => l.length)); const rects = [...TL].map(([k, l]) => { const [ix, iy] = k.split(',').map(Number); return `<rect class="c" data-k="${k}" x="${sx(ix / G)}" y="${sy((iy + 1) / G)}" width="${sx(1 / G) - sx(0)}" height="${sy(0) - sy(1 / G)}" style="fill:${countColor(l.length, peak, 'comparison', floor)}"/>`; }).join(''); const tk = [0, .25, .5, .75, 1], line = (x1, y1, x2, y2, c) => `<line class="${c}" x1="${sx(x1)}" y1="${sy(y1)}" x2="${sx(x2)}" y2="${sy(y2)}"/>`; const band = [[0, 0], [TIE, 0], [1, 1 - TIE], [1, 1], [1 - TIE, 1], [0, TIE]].map(([x, y]) => `${sx(x)},${sy(y)}`).join(' '); $('scatter').innerHTML = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${m.name} score per page, ${A} against ${B}"> ${tk.map(t => `${line(t, 0, t, 1, 'gl')}${line(0, t, 1, t, 'gl')} <text class="t" x="${sx(t)}" y="${sy(0) + 18}" text-anchor="middle">${t * 100}</text><text class="t" x="${sx(0) - 8}" y="${sy(t) + 4}" text-anchor="end">${t * 100}</text>`).join('')} <polygon class="tie" points="${band}"/><g class="tiles">${rects}</g> ${line(0, 0, 1, 1, 'diag')} <rect class="frame" x="${sx(0)}" y="${sy(1)}" width="${sx(1) - sx(0)}" height="${sy(0) - sy(1)}"/> <text class="corner dl" x="${sx(0)}" y="${sy(1) - 24}">↑ ${A} better</text> <text class="corner" x="${sx(1)}" y="${H - 6}" text-anchor="end">${B} better →</text> <text class="corner" x="${sx(0)}" y="${H - 6}">↙ both low</text> <text class="corner" x="${sx(1)}" y="${sy(1) - 8}" text-anchor="end">both high ↗</text> <text class="ax" x="${(sx(0) + sx(1)) / 2}" y="${sy(0) + 38}" text-anchor="middle">${B}</text> <text class="ax" transform="translate(13 ${(sy(0) + sy(1)) / 2}) rotate(-90)" text-anchor="middle">${A}</text></svg> <p class="key"><span class="ramp temperature" title="${esc(countRanges(peak, 'comparison', floor))}"><s></s>0<i style="background:${countGradient('comparison')}"></i>${peak} ${noun()} per tile</span></p>`; // One control: the bar's segments and the columns below are the same three groups, left to right. const g = groups(); const seg = k => g[k].length ? `<button type="button" data-g="${k}" style="flex:${g[k].length};background-color:${SW[k]}" aria-label="${esc(GROUP[k]())}: ${g[k].length}"></button>` : ''; $('tally').innerHTML = `<div class="total"><b>${n}</b><span>${noun()}</span></div> <div class="tcard"><div class="split">${['a', 't', 'b'].map(seg).join('')}</div><div class="cols">` + ['a', 't', 'b'].map(k => `<div class="col col-${k}"><button type="button" data-g="${k}" ${g[k].length ? '' : 'disabled'}> <span class="what"><i class="sw" style="background:${SW[k]}"></i>${esc(GROUP[k]())}</span><small>${k === 't' ? 'on the shaded diagonal band' : `by more than ${pc0(TIE)} points`}</small> <span class="cnt">${g[k].length} <small>${pct(g[k].length / n)}</small></span></button> </div>`).join('') + `</div></div><p class="note">Hover a group to find its pages in the plot${opens('; click to compare the reference with both outputs, largest gaps first')}.</p>` + outside(); } // Tables only: what the plot cannot show, as lists that open both models side by side. function outside() { if (st.mod !== 'b') return ''; const O = outsideLists(), A = esc(sys(st.a).label), B = esc(sys(st.b).label); const btn = (k, n, extra = '') => `<button type="button" class="link num" data-out="${k}" ${n ? '' : 'disabled'}>${n}</button>${extra}`; const xt = k => { const n = O[k].reduce((a, p) => a + p.xt[st[k[1]]], 0); return btn(k, n, n ? ` <small>on ${O[k].length} page${O[k].length === 1 ? '' : 's'}</small>` : ''); }; // One column per model, so each long model name appears once; "neither" spans both. return `<div class="outside"><table><thead><tr><th><span class="label">Not in the plot</span></th> <th><i class="sw" style="background:${SW.a}"></i>${A}</th><th><i class="sw" style="background:${SW.b}"></i>${B}</th></tr></thead><tbody> <tr><th>Reference tables only this model matched</th><td>${btn('a', O.a.length)}</td><td>${btn('b', O.b.length)}</td></tr> <tr><th>Reference tables neither matched</th><td colspan="2">${btn('n', O.n.length)}</td></tr> <tr><th>Extra tables, matching no reference</th><td>${xt('xa')}</td><td>${xt('xb')}</td></tr></tbody></table> <p class="note">${opens('Click a count to open those tables with both outputs side by side. ')}A split or misplaced table counts both as not matched and as extra.</p></div>`; } function outsideLists() { const has = (u, s) => u.b[s] != null, pages = subsetPages().filter(p => available(p, st.a) && available(p, st.b)), units = pairedUnits(); return {a: units.filter(u => has(u, st.a) && !has(u, st.b)), b: units.filter(u => !has(u, st.a) && has(u, st.b)), n: units.filter(u => !has(u, st.a) && !has(u, st.b)), xa: pages.filter(p => p.xt?.[st.a]), xb: pages.filter(p => p.xt?.[st.b])}; } const pickGroup = e => { const b = e.target.closest('#tally button[data-g]'); return b && !b.disabled ? b.dataset.g : null; }; // Tiles holding none of the group's pages turn a light neutral; nothing is removed or redrawn. function focusGroup(sel) { if ((sel || '') === focused) return; focused = sel || ''; const on = sel && tiles(p => groupOf(p) === sel); for (const r of $('scatter').querySelectorAll('rect.c')) r.classList.toggle('off', !!on && !on.has(r.dataset.k)); $('tally').classList.toggle('focus', !!sel); for (const b of $('tally').querySelectorAll('button[data-g]')) b.classList.toggle('on', !!sel && b.dataset.g === sel); } // gaps between buttons keep the current focus; only leaving the tally clears it $('tally').onmouseover = $('tally').onfocusin = e => { const s = pickGroup(e); if (s) focusGroup(s); }; $('tally').onmouseleave = $('tally').onfocusout = () => focusGroup(null); $('tally').onclick = e => { const o = e.target.closest('[data-out]'); if (o) return openPages(outsideLists()[o.dataset.out], st.a, st.b); const s = pickGroup(e); if (s) openPages(groups()[s], st.a, st.b); }; const tileAt = e => { const r = e.target.closest?.('rect.c'); return r ? [r.dataset.k, TL.get(r.dataset.k)] : null; }; $('scatter').onmousemove = e => { const t = tileAt(e); if (!t) return tip(); const [ix, iy] = t[0].split(',').map(Number); tip(e, `${esc(sys(st.a).label)} ${pc0(iy / G)}–${pc0((iy + 1) / G)}<br>${esc(sys(st.b).label)} ${pc0(ix / G)}–${pc0((ix + 1) / G)}<br><b>${t[1].length}</b> ${noun()}${opens(' · click to open')}`); }; $('scatter').onmouseleave = () => tip(); $('scatter').onclick = e => { const t = tileAt(e); if (t) openPages([...t[1]].sort((x, y) => gapOf(y) - gapOf(x)), st.a, st.b); }; $('pa').onchange = e => { st.a = +e.target.value; render(); }; $('pb').onchange = e => { st.b = +e.target.value; render(); }; /* ---------- page view: reference and models in the DocLang viewer ---------- */ // The reference always shows on the left, the chosen models beside it. A held-out benchmark // (build.py heldout) has no pages to show: nothing opens, and opens() drops every hint that something would. const opens = s => D.heldout ? '' : s; function openPages(list, ...models) { list = list.filter(p => !heldPage(p)); if (!list.length) return; tip(); Object.assign(st.d, {list, pos: 0, sides: ['gt', ...models]}); renderPage(); if (!$('dlg').open) $('dlg').showModal(); } // d.sides in display order (Reference first), with s added const withSide = s => ['gt', ...D.systems.keys()].filter(k => k === s || st.d.sides.includes(k)); // Every score of this page for one system; Text in the measure and type chosen on the page. Tables are // scored per reference table: a table unit shows its own, a page shows each of its tables. function pageScores(p, s) { const cell = (name, v, sub = '') => `<div class="ps"${sub ? ` title="${esc(sub)}"` : ''}><span class="label">${name}</span><b class="num">${v}</b></div>`; const tb = p.b ? [p.b[s]] : ptab(p).map(t => t[s]), xt = p.xt?.[s] ? ` · +${p.xt[s]} extra` : ''; // Text follows the chosen measure and tab: a Matched tab's scores (build.py ty) or the page's. Derived from // the page, not the unit: coverage() lists open plain pages. A Matched-tab unit carries its page as .page. const q = p.page || p, m = TEXT[st.tm], ty = tyWord(), yt = typed() && q.ty?.[st.ty]; const v = typed() ? yt || {} : q, val = k => pc0(v[k]?.[s]), name = `Text ${ty}${m.score}`; const tc = typed() && (yt ? [...yt.c[s], ...yt.x[s]] : [0, 0, 0, 0]); const others = Object.entries(textMeasures()).filter(([k]) => k !== st.tm).map(([, t]) => `${t.score} ${val(t.k)}`).join(' · '); const text = !tc ? cell(name, val(m.k), others) : cell(`${name} · matched`, `${val(m.k)} · ${share(tc[0], tc[1])} matched · +${share(tc[2], tc[3])} extra`, [others, `${tc[0].toLocaleString('en')} of ${chars(tc[1])} of reference ${ty}text matched; ${tc[2].toLocaleString('en')} of ${chars(tc[3])} of ${ty}output extra`, ...Object.entries(q.ty || {}).filter(([t, y]) => t !== 'matched' && (y.c[s][1] || y.x[s][1])).map(([t, y]) => `${t}: ${m.score} ${pc0(y[m.k][s])}${y.c[s][1] ? ` · ${share(y.c[s][0], y.c[s][1])} matched` : ''}${y.x[s][1] ? ` · +${share(y.x[s][0], y.x[s][1])} extra` : ''}`)].join('\n')); return `<div class="scores">${text}${ cell(`Tables ${TABLE[st.bm].score}`, (tb.length ? tb.map(v => v == null ? 'not matched' : pc0(v)).join(' · ') : '—') + xt, [p.b ? `table ${p.tix + 1} of ${p.tn}` : tb.length ? (tb.length > 1 ? `${tb.length} reference tables` : '') : 'no reference table', xt && `${p.xt[s]} output table${p.xt[s] > 1 ? 's' : ''} on this page matched no reference table`].filter(Boolean).join('; '))}${ cell('Layout TORE F1', pc0(p.l[s]))}</div>`; } // A text view's pane: a caption and the file, fetched by fillText; `none` shows if the file is absent. const textPane = (src, cap, none) => `<p class="cap">${cap}</p><pre class="txt" data-src="${src}" data-none="${esc(none)}">Loading…</pre>`; // Report an issue: opens the benchmark-feedback issue form for this pane, prefilled with what the viewer knows. // The reference pane reports a wrong reference, a model pane a wrong DocLang mapping of that model's native output. const FEEDBACK = 'https://github.com/docling-project/benchmark-feedback/issues/new'; const reportBtn = (s, p) => heldPage(p) ? '' : `<button type="button" class="report" data-report="${s}" title="${s === 'gt' ? 'Report an error in this reference' : 'Report a wrong DocLang mapping of this model’s output'}">Report issue</button>`; function reportUrl(s) { const d = st.d, p = d.list[d.pos], gt = s === 'gt', bench = p.bench || st.bench; const sample = (p.id.startsWith(bench + '/') ? p.id.slice(bench.length + 1) : p.id) + (p.tix != null ? ` (table ${p.tix + 1})` : ''); return `${FEEDBACK}?` + new URLSearchParams({template: gt ? 'reference-error.yml' : 'mapping-error.yml', title: `[${gt ? 'Reference' : 'Mapping'}] ${bench} / ${sample}${gt ? '' : ` / ${sys(s).label}`}`, benchmark: bench, sample_id: sample, ...(!gt && {model: sys(s).label}), viewer_link: linkBase() + linkHash()}); } $('dlg').addEventListener('click', e => { const b = e.target.closest('[data-report]'); if (b) open(reportUrl(b.dataset.report === 'gt' ? 'gt' : +b.dataset.report), '_blank', 'noopener'); }); function paneMarkup(s, p, v = st.d.view) { const gt = s === 'gt', name = gt ? 'Reference' : sys(s).label, key = gt ? '' : sys(s).key; const head = gt ? '<span class="note">Ground truth · not scored</span>' : pageScores(p, s); // the id is a file name: encoded, as ids hold `%` (`scihub_gbe%2Fevaa098.pdf_0`) that a server would decode const file = pageFile(p, s); if (!file) return `<div class="pane" data-side="${s}"><div class="p-head"><b>${esc(name)}</b>${head}${reportBtn(s, p)}</div><p class="empty">${heldPage(p) ? 'Held out: scores only, no page view.' : 'No evaluated output for this benchmark.'}</p></div>`; const packedEvidence = D.evidence && sourceOf(p).evidence; if ((v === 'raw' || v === 'scored') && !packedEvidence) return `<div class="pane" data-side="${s}"><div class="p-head"><b>${esc(name)}</b>${head}${reportBtn(s, p)}</div><p class="empty">No text evidence packed for this benchmark.</p></div>`; const src = encodeURIComponent(`../${file}.dclx`); const failed = p.f?.includes(key) ? '<p class="empty">This output could not be read as DocLang, so it scores 0.</p>' : ''; const body = v === 'raw' ? (gt ? textPane(`${file}.raw.txt`, 'The reference’s DocLang, exactly as stored in the dataset.', 'No DocLang for this page') : !sourceSystem(p, s)?.raw ? '<p class="empty">No raw output for this system</p>' : textPane(`${file}.raw.txt`, 'The model’s verbatim output, exactly as emitted. <b>Not scored.</b>', 'No raw output for this page')) : v === 'scored' ? failed || textPane(`${file}.scored.txt`, gt // markdown target; doclang: matchedView ? 'The reference text the text metrics compare against, after normalization.' : 'The exact text the text metrics compared with the reference, after normalization.', 'No scored text for this page') : p.x?.includes(key) ? '<p class="empty">No output for this page</p>' : failed || `<iframe src="doclang/index.html?src=${src}&view=${v}" title="${esc(name)}, ${v} view"></iframe>`; return `<div class="pane" data-side="${s}"><div class="p-head"><b>${esc(name)}</b>${head}${reportBtn(s, p)}</div>${body}</div>`; } function fillText(root) { for (const pre of root.querySelectorAll('pre[data-src]')) { const src = pre.dataset.src; delete pre.dataset.src; fetch(src, {cache: 'no-cache'}).then(r => r.ok ? r.text() : Promise.reject(r.status)) .then(t => { pre.textContent = t; }, e => { pre.previousElementSibling?.remove(); // the caption describes text that is not there pre.outerHTML = `<p class="empty">${e === 404 ? pre.dataset.none : 'This text did not load.'}</p>`; }); } } const step = k => { const d = st.d, i = d.pos + k; if (i >= 0 && i < d.list.length) { d.pos = i; renderPage(); } }; $('d-prev').onclick = () => step(-1); $('d-next').onclick = () => step(1); for (const b of document.querySelectorAll('.cp')) b.onclick = async () => { await navigator.clipboard?.writeText(b.dataset.cp === 'link' ? linkBase() + linkHash() : st.d.list[st.d.pos][b.dataset.cp] || ''); b.classList.add('ok'); setTimeout(() => b.classList.remove('ok'), 800); }; // Deep link to the page view: the hash carries what the dialog shows. Framed (the Space page, or the // profile's link), the link points at that page, which hands its hash to this app on load. deploy.sh sets SPACE. const SPACE = 'https://docling.ai/benchmarks/'; const linkBase = () => self === top || !SPACE ? location.href.split('#')[0] : SPACE; const sideKey = s => s === 'gt' ? s : sys(s).key; function linkHash() { const d = st.d, p = d.list[d.pos]; return '#' + new URLSearchParams({b: st.bench, p: p.id, ...(p.tix != null && {t: p.tix}), s: d.sides.map(sideKey).join(' '), v: d.view, ...(d.referencePage && {rp: 1}), mod: st.mod, tm: st.tm, bm: st.bm, ty: st.ty, ...(st.eq && {eq: 1})}); } // Sets the state a link carries, after load() of its benchmark; every value is checked against the loaded // data. The page list is that one page. Returns whether there is a page to open. function applyLink(q) { const p = D.pages.find(p => p.id === q.get('p') && !heldPage(p)); if (!p) return false; for (const [k, among] of [['mod', MODS], ['tm', textMeasures()], ['bm', tableMeasures()], ['ty', tabs()]]) if (Object.hasOwn(among, q.get(k))) st[k] = q.get(k); st.eq = !PUBLIC && q.get('eq') === '1'; const side = k => k === 'gt' ? k : D.systems.findIndex(s => s.key === k), t = +q.get('t'); const sides = (q.get('s') || '').split(' ').map(side).filter(s => s !== -1 && s !== 'gt'); Object.assign(st.d, {list: [q.has('t') && p.tables[t] ? {...p, b: ptab(p)[t], tix: t, tn: p.tables.length} : p], pos: 0, sides: ['gt', ...sides], view: q.get('v'), referencePage: q.get('rp') === '1'}); return true; } $('d-close').onclick = () => $('dlg').close(); $('d-view').onclick = e => { const b = e.target.closest('button'); if (b) { st.d.view = b.dataset.v; renderPage(); } }; $('d-page-image').onchange = e => { st.d.referencePage = e.target.checked; renderReferencePage(st.d.list[st.d.pos]); }; $('d-sys').onclick = e => { const b = e.target.closest('button'); if (!b) return; const s = +b.dataset.s, d = st.d; d.sides = d.sides.includes(s) ? d.sides.filter(x => x !== s) : withSide(s); renderPage(); }; document.addEventListener('keydown', e => { if (!$('dlg').open || e.target.closest('select')) return; if (e.key === 'ArrowLeft') step(-1); else if (e.key === 'ArrowRight') step(1); }); /* ---------- Scored text, DocLang target: the reference spans with each model's matched text beside them ---------- */ // build.py match_json per page: spans [{type, layer, in_scope, tokens}] (the metric's tokens, space-joined), // and per model groups [{gt, pred, ops, cost, in_scope}] (span indices; ops over the groups' joined tokens: // = same, ~ substituted, - reference only, + output only), unmatched_gt, unmatched_pred. const matchedOn = () => st.d.view === 'scored' && CT(); const MT = {cache: new Map(), changed: false, heat: true, plain: false, pin: null, byW: {}}; const mtJson = url => { if (!MT.cache.has(url)) MT.cache.set(url, fetch(url, {cache: 'no-cache'}).then(r => r.ok ? r.json() : null, () => null)); return MT.cache.get(url); }; const toks = s => s ? s.split(' ') : []; const CJK = /[ -〿぀-ヿ㐀-鿿豈-﫿＀-￯]/; // Scored words are shown with a gap between them, except next to a CJK character (one word each). const wgap = (x, y) => x && y && !CJK.test(x.at(-1)) && !CJK.test(y[0]) ? ' ' : ''; const wjoin = ws => ws.map((w, k) => wgap(ws[k - 1], w) + w).join(''); // Why a run of changed words differs, from its characters: whitespace (the same characters split into // other words), case, markup ($, \mathrm, braces, thin spaces) or content. const MARKUP = /\$|\\mathrm|\\,|\\!|[{}\s]/g; const CAUSES = {content: 'content differs', case: 'case only', markup: 'markup only', split: 'same characters, other word split'}; function cause(a, b) { const A = a.join(''), B = b.join(''); if (A === B) return 'split'; if (A.toLowerCase() === B.toLowerCase()) return 'case'; return A.replace(MARKUP, '').toLowerCase() === B.replace(MARKUP, '').toLowerCase() ? 'markup' : 'content'; } // [op, reference word position [span, index] | null, output word | null] -> {eq, w} | {a, b, ws, k} function mtSegments(steps, R) { const out = []; let run = null; for (const [o, p, w] of steps) { if (o === '=') { if (run) out.push(run), run = null; out.push({eq: w, w: p.join('.')}); continue; } run ??= {a: [], b: [], ws: []}; if (p) run.a.push(R[p[0]].w[p[1]]), run.ws.push(p.join('.')); if (w != null) run.b.push(w); } if (run) out.push(run); for (const s of out) if (s.a) s.k = cause(s.a, s.b); return out; } // One model against the reference: its alignment cut at reference span boundaries, so each reference row // shows the output words aligned to it (output words between two reference spans go with the first). function mtModel(R, md) { const P = md.spans.map(s => toks(s.tokens)), part = {}, wrong = new Set(), tally = {content: 0, case: 0, markup: 0, split: 0}; let last = -1; md.groups.forEach((g, gi) => { const pos = g.gt.flatMap(i => R[i].w.map((_, t) => [i, t])), b = g.pred.flatMap(j => P[j]), steps = {}; let i = 0, j = 0, cur = g.gt[0]; for (const o of g.ops) { if (o !== '+') cur = pos[i][0]; (steps[cur] ??= []).push([o, o !== '+' ? pos[i] : null, o !== '-' ? b[j] : null]); if (o !== '+') i++; if (o !== '-') j++; } const moved = g.pred[0] < last; last = Math.max(last, ...g.pred); for (const s of g.gt) { const segs = mtSegments(steps[s] || [], R); part[s] = {g, gi, moved, segs}; if (g.in_scope) for (const x of segs) if (x.k) { tally[x.k] += Math.max(x.a.length, x.b.length); if (x.k === 'content') x.ws.forEach(w => wrong.add(w)); } } }); const owner = {}; md.groups.forEach(g => g.pred.forEach(j => { owner[j] = g; })); const extras = md.unmatched_pred.map(j => { let k = j - 1; while (k >= 0 && !owner[k]) k--; return {after: k < 0 ? -1 : owner[k].gt.at(-1), span: j, w: P[j], in_scope: md.spans[j].in_scope}; }); const missed = new Set(md.unmatched_gt); for (const i of missed) if (R[i].in_scope) R[i].w.forEach((_, t) => wrong.add(`${i}.${t}`)); return {part, wrong, tally, extras, missed}; } const mtCell = (cls, rows, body) => `<div class="mt-c ${cls}" data-rows="${rows}">${body}</div>`; function mtDiff(segs) { let h = '', prev = ''; for (const s of segs) { if (s.eq != null) { h += wgap(prev, s.eq) + `<span data-w="${s.w}">${esc(s.eq)}</span>`; prev = s.eq; continue; } const A = wjoin(s.a), B = wjoin(s.b); h += wgap(prev, A || B) + `<span class="k-${s.k}" data-w="${s.ws.join(' ')}" title="${esc(`reference: ${A || '∅'}\noutput: ${B || '∅'}\n${CAUSES[s.k]}`)}">${A ? `<s>${esc(A)}</s>` : ''}${A && B ? ' ' : ''}${B ? `<ins>${esc(B)}</ins>` : ''}</span>`; prev = B || A; } return h; } async function matchedView(p) { const d = st.d, req = overlayRequest, models = d.sides.filter(s => s !== 'gt'), m = TEXT[st.tm]; const evidence = side => { const file = pageFile(p, side); return file && D.evidence && sourceOf(p).evidence ? mtJson(`${file}.match.json`) : null; }; const [ref, ...mds] = await Promise.all([evidence('gt'), ...models.map(evidence)]); if (req !== overlayRequest || !matchedOn()) return; const box = $('panes'); if (!ref) { box.innerHTML = '<p class="empty">No scored text for this page.</p>'; return; } const R = ref.spans.map(s => ({...s, w: toks(s.tokens)})), n = R.length; const A = mds.map(md => md && mtModel(R, md)); const why = s => p.f?.includes(sys(s).key) ? 'This output could not be read as DocLang, so it scores 0.' : p.x?.includes(sys(s).key) ? 'No output for this page' : 'No scored text for this page'; const rows = [], hasExtra = i => A.some(a => a?.extras.some(x => x.after === i)); const differs = i => A.some(a => a && (a.missed.has(i) ? R[i].in_scope : a.part[i]?.segs.some(x => x.k))); for (let i = -1; i < n; i++) { if (i >= 0 && (!MT.changed || differs(i))) rows.push(i); if (hasExtra(i)) rows.push(`x${i}`); } const N = models.length; let h = `<div class="mt-c mt-hd"><b>Reference</b><span class="note">Ground truth, normalized · ${n} spans in reading order</span></div>`; models.forEach((s, c) => { const a = A[c], t = a?.tally, tot = t ? Object.values(t).reduce((x, y) => x + y, 0) || 1 : 1; h += `<div class="mt-c mt-hd"><b>${esc(sys(s).label)}</b>${pageScores(p, s)}${a ? `<span class="mt-tally" title="Changed words by cause: ${t.content} content · ${t.case} case · ${t.markup} markup · ${t.split} other word split">${ Object.keys(t).map(k => `<i class="t-${k}" style="width:${t[k] / tot * 100}%"></i>`).join('')}</span><span class="note">${t.content} content · ${t.case} case · ${t.markup} markup · ${t.split} split</span>` : ''}</div>`; }); rows.forEach((r, k) => { if (typeof r === 'string') { // output text that matched nothing, after the reference span it follows const i = +r.slice(1); h += mtCell('mt-x', r, '<span class="mt-m">no reference text</span>'); A.forEach(a => { const xs = a ? a.extras.filter(x => x.after === i) : []; h += mtCell(`mt-x${xs.length ? ' extra' : ''}`, r, xs.map(x => `<span class="mt-m">extra${x.in_scope ? '' : ' · not scored'}</span><span class="k-content"><ins>${esc(wjoin(x.w))}</ins></span>`).join('<br>')); }); return; } const sp = R[r], words = sp.w.map((w, t) => { const id = `${r}.${t}`, bad = MT.heat && !MT.plain ? A.filter(a => a?.wrong.has(id)).length : 0; return wgap(sp.w[t - 1], w) + `<span data-w="${id}"${bad ? ` class="heat" style="--h:${bad / N * 45}%" title="${bad} of ${N} models got this wrong"` : ''}>${esc(w)}</span>`; }).join(''); h += mtCell(`gt${sp.in_scope ? '' : ' off'}`, r, `<span class="mt-m">${sp.type}${sp.layer !== 'body' ? ' · ' + sp.layer : ''}${sp.in_scope ? '' : ' · not scored'}</span>${words}`); models.forEach((s, c) => { const a = A[c], q = a?.part[r]; if (!a) h += mtCell('off', r, k ? '' : `<span class="mt-m">${why(s)}</span>`); else if (q) h += mtCell(`${MT.plain ? 'plain' : ''}${q.g.in_scope ? '' : ' off'}`, q.g.gt.join(' '), `<span class="mt-m">${q.g.in_scope ? `${m.score} ${pc0(q.g.s[m.k])} · ` : ''}match cost ${q.g.cost.toFixed(2)}${q.g.gt.length > 1 ? ` · match of ${q.g.gt.length} reference spans` : ''}${q.g.in_scope ? '' : ' · not scored'}${q.moved ? ' · <span class="moved" title="This output comes earlier in the model’s reading order than output matched to earlier reference spans">out of order</span>' : ''}</span>${mtDiff(q.segs)}`); else h += mtCell(sp.in_scope ? 'miss' : 'off', r, sp.in_scope ? 'not matched: no output text for this reference text' : '<span class="mt-m">not matched · not scored</span>'); }); }); box.innerHTML = `<div class="mt-bar"><span class="note">The text the text metrics compared, after normalization, split into the words they count.${st.tm === 'edc' ? ` Highlighting and change counts are word-level diagnostics: ${m.score} compares characters with whitespace removed, so “other word split” differences cost nothing in it.` : ''} Hover a word or cell to see what it matched; click to pin.</span> <label><input type="checkbox" data-mt="changed"${MT.changed ? ' checked' : ''}> Only spans with differences</label> <label><input type="checkbox" data-mt="heat"${MT.heat ? ' checked' : ''}> Reference heat</label> <label><input type="checkbox" data-mt="plain"${MT.plain ? ' checked' : ''}> Plain text</label></div> <p class="mt-key note"><span class="k-content"><s>ref</s> <ins>output</ins></span> content differs · <span class="k-case"><ins>o</ins></span> case only · <span class="k-markup"><s>$</s> <ins>\\mathrm</ins></span> markup only · <span class="k-split"><ins>word split</ins></span> same characters, other word split (whitespace) · <span class="heat" style="--h:30%">reference</span> words some shown models got wrong</p> <div class="mt-scroll"><div class="mt-grid" style="grid-template-columns:repeat(${N + 1},minmax(0,1fr))">${h}</div></div>`; MT.byW = {}; MT.pin = null; for (const e of box.querySelectorAll('[data-w]')) for (const w of e.dataset.w.split(' ')) (MT.byW[w] ??= []).push(e); } // Hover a word: it, the reference words it stands for, and every model's words for those. Hover elsewhere in // a cell: every cell on the reference spans it covers. Click pins the highlight; click again releases it. function mtLight(t) { const g = $('panes').querySelector('.mt-grid'); if (!g) return; for (const x of g.querySelectorAll('.hl, .wl')) x.classList.remove('hl', 'wl'); const w = t?.closest?.('[data-w]'), c = t?.closest?.('.mt-c[data-rows]'); if (w) { for (const id of w.dataset.w.split(' ')) for (const e of MT.byW[id] || []) e.classList.add('wl'); w.classList.add('wl'); } if (c?.dataset.rows) { const rs = new Set(c.dataset.rows.split(' ')); for (const x of g.querySelectorAll('.mt-c[data-rows]')) if (x.dataset.rows.split(' ').some(r => rs.has(r))) x.classList.add('hl'); } } $('panes').addEventListener('mouseover', e => { if (matchedOn() && !MT.pin) mtLight(e.target); }); $('panes').addEventListener('mouseleave', () => { if (matchedOn() && !MT.pin) mtLight(null); }); $('panes').addEventListener('click', e => { if (!matchedOn() || !e.target.closest('.mt-grid')) return; MT.pin = MT.pin ? null : e.target; $('panes').querySelector('.mt-scroll').classList.toggle('pinned', !!MT.pin); mtLight(MT.pin || e.target); }); $('panes').addEventListener('change', e => { const k = e.target.dataset.mt; if (k) { MT[k] = e.target.checked; matchedView(st.d.list[st.d.pos]); } }); let overlayRequest = 0; // bumped per render; a stale matchedView drops its result // A separate host keeps the image and its zoom/pan intact when the comparison's view or text changes. // Page view needs none: the reference pane there already is the page image. function renderReferencePage(p) { const host = $('reference-page'), on = st.d.referencePage && st.d.view !== 'page'; $('d-page-image-field').hidden = st.d.view === 'page'; $('d-page-image').checked = st.d.referencePage; host.hidden = !on; $('viewer-body').classList.toggle('with-reference', on); if (!on) return; const file = pageFile(p, 'gt'); if (host.dataset.file !== file || !host.innerHTML) { host.innerHTML = paneMarkup('gt', p, 'page'); // titled apart from the Reference pane beside it, which shows the same page in the chosen view const head = host.querySelector('.p-head'); if (head) head.innerHTML = '<b>Page image</b><span class="note">The reference page in Page view</span>'; host.dataset.file = file; } } function renderPage() { overlayRequest++; const d = st.d, p = d.list[d.pos], mt = matchedOn(); $('d-title').textContent = p.title + (p.tix != null ? ` · table ${p.tix + 1} of ${p.tn}` : ''); $('d-hash').textContent = p.id + '.dclx'; $('d-pos').textContent = `${d.pos + 1} of ${d.list.length}`; $('d-prev').disabled = d.pos === 0; $('d-next').disabled = d.pos === d.list.length - 1; if (!views().some(([v]) => v === d.view)) d.view = 'page'; renderReferencePage(p); $('d-view').innerHTML = views().map(([v, n]) => `<button type="button" data-v="${v}" aria-pressed="${v === d.view}">${n}</button>`).join(''); $('d-sys').innerHTML = '<span class="label">Models</span>' + [...D.systems.keys()].map(s => `<button type="button" data-s="${s}" aria-pressed="${d.sides.includes(s)}">${esc(sys(s).label)}</button>`).join(''); $('panes').classList.toggle('mtv', mt); if (mt) { $('panes').innerHTML = '<p class="empty">Loading…</p>'; matchedView(p); } else { $('panes').innerHTML = d.sides.map(s => paneMarkup(s, p)).join(''); fillText($('panes')); } } /* ---------- data ---------- */ function render() { K = M().k; U = units(); P = U.filter(u => u[K][st.a] != null && u[K][st.b] != null); renderBar(); renderRows(); renderSpider(); renderH2H(); } globalThis.matchMedia?.('(prefers-color-scheme:light)').addEventListener('change', () => D && render()); async function load(id) { D = await fetchScores(id); if (D.aggregate) for (const [key, summary] of Object.entries(D.source_coverage)) COVERAGE.set(key, summary); else COVERAGE.set(id, coverageSummary(D)); st.bench = id; st.f = {}; st.ty = st.tt = 'all'; Object.assign(st.sp, {k: null, no: new Set(), off: new Set()}); // defaults follow config order, never the scores: first Docling model against the first other model st.a = Math.max(0, D.systems.findIndex(s => s.docling)); st.b = Math.max(0, D.systems.findIndex(s => !s.docling)); if (!tableMeasures()[st.bm]) st.bm = 'c'; render(); if (!PUBLIC && $('comparison-context').open) loadCoverage(); } fetch('data/version.json').then(r => r.json()) // the small print; the board works without it .then(v => { $('version').textContent = `Scoring v${v.scoring}` + (v.docling ? ` · ${v.docling} maps the model outputs` : ''); }, () => {}); fetch(`data/benchmarks.json`, {cache: 'no-cache'}).then(r => r.json()).then(async b => { BENCHES = b; PUBLIC = b.some(x => x.public); $('coverage-box').hidden = PUBLIC; const q = new URLSearchParams(location.hash.slice(1)); await load(b.find(x => x.id === q.get('b'))?.id || (b.find(x => x.id === 'all') || b[0]).id); // only a known benchmark: its id goes into markup if (applyLink(q)) { render(); renderPage(); $('dlg').showModal(); } }) .catch(() => { $('app').innerHTML = '<p class="fail">Could not load data/. Serve this folder over HTTP, e.g. python3 -m http.server, and open it (see README.md).</p>'; });
const $ = id => document.getElementById(id);
// A score: MODS entry, completed by the chosen TEXT measure for Text. k is its page field in scores.json.
const MODS = {
t: {name: 'Text', unit: 'page', def: 'How much of the reference text each model reproduces, in reading order.'},
b: {name: 'Tables', unit: 'table', k: 'b',
def: 'How closely table structure and cell text match the reference, on the tables each model found.'},
l: {name: 'Layout', unit: 'page', score: 'TORE F1', long: 'layout TORE F1', k: 'l',
def: 'How well the page area covered by layout regions matches the reference.',
detail: 'Area overlap of layout regions, at pixel level. Precision is the share of the model output’s region area that lies inside reference regions, recall the share of the reference region area the output covers, and F1 their harmonic mean. Region types are not compared. Pages without reference regions, or without output, are left out for that model.'},
};
// Table measures, completing MODS.b: f is the build.py page field (tables_h only where build.py packed it).
const TABLE = {
c: {score: 'TEDS', long: 'table TEDS (structure and cell text)', f: 'tables',
detail: 'Tree similarity of two tables. TEDS (tree edit distance similarity) reads each table as a tree of rows and cells and counts the edits that turn one tree into the other, relative to the larger tree. Both structure (rows, cells, merged cells) and cell text count.'},
h: {score: 'TEDS with headers', long: 'table TEDS with header cells (structure, cell text and headers)', f: 'tables_h',
detail: 'Tree similarity of two tables. TEDS (tree edit distance similarity) reads each table as a tree of rows and cells and counts the edits that turn one tree into the other, relative to the larger tree. Both structure (rows, cells, merged cells) and cell text count. A header cell against a body cell counts as a changed cell.'},
};
const textMeasures = () => PUBLIC ? {edc: TEXT.edc, f1: TEXT.f1} : TEXT;
const tableMeasures = () => D.pages.some(p => p.tables_h) ? TABLE : {c: TABLE.c};
const ptab = p => p[TABLE[st.bm].f];
// Text measures share the normalization described in index.html (#norm).
const TEXT = {
edc: {score: '1 − NED (chars)', long: 'text character edit similarity (1 − character edit distance)', k: 't_edc',
detail: 'Sequence similarity at character level. Edit distance counts the character insertions, deletions and substitutions that turn the model output into the reference, divided by the longer character count. Whitespace is ignored, so spacing and word breaks cost nothing, and a word with one wrong character costs one character, not a whole word. Shown as 1 − distance, so higher is better.'},
ed: {score: '1 − NED (words)', long: 'text edit similarity (1 − edit distance)', k: 't_ed',
detail: 'Sequence similarity at word level. Edit distance counts the word insertions, deletions and substitutions that turn the model output into the reference, divided by the longer word count. Shown as 1 − distance, so higher is better. Sensitive to word order.'},
f1: {score: 'F1', long: 'text F1', k: 't',
detail: 'Set similarity at word level. Compares the distinct words of the model output and the reference: precision is the share of output words found in the reference, recall the share of reference words found in the output, and F1 their harmonic mean. Word order and repetition are ignored.'},
meteor: {score: 'METEOR', long: 'text METEOR', k: 't_meteor',
detail: 'Word alignment score. Aligns the words of the model output with those of the reference (exact, then stems, then synonyms), combines precision and recall with more weight on recall, and applies a penalty when the aligned words are out of order.'},
bleu: {score: 'BLEU', long: 'text BLEU', k: 't_bleu',
detail: 'N-gram precision at word level. The share of the model output’s sequences of one to four words that also occur in the reference, with a penalty for output shorter than the reference. Sensitive to word order.'},
};
// Text with build.py EVAL_TARGET doclang (scores.json "eval_target"): a Text chooser, All content
// (text.content.all) or a Matched tab with a coverage bar in reference characters, every page weighted by
// the characters it scores (build.py w). Without it (markdown) Text renders as before.
const CT = () => D.eval_target === 'doclang';
const CONTENT = {all: () => `How closely each model reproduces the reference text. Missed reference text and extra output count against the score. ${pagesCount('text')}`,
matched: () => `How closely each model reproduces the reference ${tyWord()}text it matched; the bar shows how much that is. ${pagesCount('matched text')}`,};
// The matching explainer (#match), per score: Text with eval target doclang, and Tables.
const MATCHING = {
t: `<p>The reference and the model output (the model’s prediction for the page) are each split into spans in reading order: one span per paragraph, heading, list item, formula or table (as its cell text).</p>
<p>Every reference span is compared with every output span, wherever they sit on the page; each such combination is a candidate pair. A candidate pair becomes a <b>match</b> only if its two texts are similar enough to be the same content. Each span belongs to at most one match, and the most similar candidates are taken first. A match also takes in a neighbouring span when that makes its two sides more alike, so a paragraph that one side splits into two spans is still matched as a whole.</p>
<p>Spans left without a match are unmatched: a reference span is <b>not matched</b> (missed text), an output span is <b>extra</b>.</p>
<p>The measure is computed on matches only, one value per match. The <b>Matched</b> tabs average just those, so they show how well a model reproduces what it found; the bar under each score shows how much reference text was matched or not, and how much output is extra. <b>All content</b> also counts not matched and extra spans, at the worst score.</p>`,
b: `<p>Each reference table is matched with at most one table of the model output (the model’s prediction for the page): the one that overlaps it on the page, if the overlap is large enough. A reference table without such a counterpart is <b>not matched</b>; an output table matched with no reference table is <b>extra</b>.</p>
<p>TEDS is computed and averaged on matched tables only, so read it with the two numbers beside it: the share of reference tables matched, and the output tables that are extra. A table that is split, merged with a neighbour or placed away from its reference counts as both not matched and extra.</p>`,
};
// The Text chooser: All content (the page's own scores), then the Matched tabs (build.py ty): all types, and
// the benchmark's text_types where some page has them. typed() = a Matched tab.
const TYPE_TABS = {formula: 'Matched formulas', code: 'Matched code'};
const tabs = () => Object.fromEntries([['all', 'All content'], ['matched', 'Matched content'], ...(D.text_types || []).map(t => [t, TYPE_TABS[t] || `Matched ${t}`])]
.filter(([k]) => k === 'all' || D.pages.some(p => hasType(p, k))));
// Score bar layout (trial). 'types': one Score button per kind of content (Text, each text type, Tables,
// Layout), the Text chooser keeps All content | Matched content, and a score with a single measure names it
// instead of offering a chooser. 'classic': Text, Tables, Layout, the text types as Matched tabs of the Text
// chooser. Only the bar differs: a type button sets st.mod 't' and st.ty as its Matched tab does.
// Revert by changing the default below; ?scorebar=classic|types overrides it per page load.
const SCOREBAR = new URLSearchParams(globalThis.location?.search).get('scorebar') || 'types';
const TYPE_NAMES = {formula: 'Formulas', code: 'Code'};
const isType = t => t !== 'all' && t !== 'matched';
// [mod, text type or '', name] per Score button
const scoreButtons = () => SCOREBAR === 'classic' || !CT() ? Object.keys(MODS).map(k => [k, '', MODS[k].name])
: [['t', '', MODS.t.name], ...Object.keys(tabs()).filter(isType).map(t => ['t', t, TYPE_NAMES[t] || t]), ['b', '', MODS.b.name], ['l', '', MODS.l.name]];
const typed = () => st.mod === 't' && CT() && st.ty !== 'all';
const tyWord = () => typed() && st.ty !== 'matched' ? st.ty + ' ' : '';
// Options (#opt-pop): st.eq counts every page equally where pages are weighted by characters (canWeigh);
// a page's own score stays as scored, and pages with no characters to score stay out (their value is null).
const canWeigh = () => st.mod === 't' && CT();
const weighted = () => canWeigh() && !st.eq;
const pagesCount = what => st.eq ? 'Every page counts equally.' : `Each page counts by its amount of ${what}.`;
const AVERAGES = () => st.eq ? 'Within a page, averages are weighted by characters, so long spans count more. Across pages, every page counts equally (Options).'
: 'Averages are weighted by characters, so long spans and dense pages count more.';
const hasType = (p, t) => !!p.ty?.[t]?.c.some(c => c[1] > 0);
const measure = k => k === 'b' ? {...MODS.b, ...TABLE[st.bm]} : k !== 't' ? MODS[k] : !CT() ? {...MODS.t, ...TEXT[st.tm]}
: {...MODS.t, ...TEXT[st.tm], def: typed() ? CONTENT.matched() : CONTENT.all(), long: `${typed() ? `matched ${tyWord()}` : ''}${TEXT[st.tm].long}`};
const M = () => measure(st.mod);
const available = (p, i) => !p.u?.includes(sys(i).key);
const pairedUnits = () => U.filter(p => available(p, st.a) && available(p, st.b));
const sourceOf = p => D.aggregate ? D.sources[p.bench] : D;
const heldPage = p => !!D.heldout || !!sourceOf(p).heldout;
const sourceSystem = (p, i) => D.aggregate ? sourceOf(p).systems[sys(i).key] : sys(i);
function pageFile(p, side) {
if (heldPage(p)) return null;
const source = sourceOf(p), folder = side === 'gt' ? source.ref : sourceSystem(p, side)?.dir;
return folder ? `data/${p.bench || st.bench}/${folder}/${encodeURIComponent(p.doc ?? p.id)}` : null;
}
const VIEWS = [['page', 'Page'], ['markup', 'DocLang'], ['reading', 'Reading']];
// Text views, shown only when build.py's EVIDENCE switch packed their files (scores.json "evidence").
const TEXT_VIEWS = [['scored', 'Scored text'], ['raw', 'Raw model output']];
const views = () => D.evidence ? [...VIEWS, ...TEXT_VIEWS] : VIEWS;
const NB = 20, TIE = .02;
// a: a Docling model (vertical axis), b: a compared model (horizontal axis). Only Docling-vs-other pairs.
// sp: Scores by category. k: the facet whose values are the axes; no: values switched off; off: hidden models;
// view: the spider chart or its value table, shown one at a time.
// tt: the last of All content | Matched content chosen under Text, restored when Text is chosen again
const st = {bench: null, mod: 't', tm: 'edc', bm: 'c', ty: 'all', tt: 'all', eq: false, f: {}, a: 0, b: 1, d: {view: 'page', referencePage: false},
sp: {k: null, no: new Set(), off: new Set(), stat: 'mean', fit: true, view: 'chart'}};
let D = null, BENCHES = [], PUBLIC = false, focused = '';
// Set by render(): score field, units with that score, units scored for both compared models,