diff --git a/.dsh-version.json b/.dsh-version.json index 11edae1..013d33a 100644 --- a/.dsh-version.json +++ b/.dsh-version.json @@ -9,6 +9,13 @@ ], "comment_platforms": "The plugins are plain JavaScript and platform-neutral; the only OS-specific code is a launcher choosing the right command for the host: dsh-open-in-app's file-browser launcher (explorer.exe / open / xdg-open, WSL-aware), the run launcher's browser hand-off (Chrome on PATH / the standard install folders / the App Paths registry entry, 'open -a Google Chrome', google-chrome or chromium, else the platform default). The launchers run on Windows (install.bat / uninstall.bat, PowerShell 5.1 or 7, and the run launcher: the double-clickable batch run-web.bat at the root plus its worker scripts/run-web.ps1, because cmd's for /f reads a child's output only up to EOF and cannot watch a running harness) and on macOS/Linux (install.sh / uninstall.sh / run-web.sh, POSIX sh - never PowerShell). The run launcher is run-web.bat + run-web.sh at the repo root, and run-web.sh does the whole job itself. The ready URL reaches the browser as ONE ARGV ELEMENT - Start-Process -ArgumentList on Windows, an argument of open/xdg-open on macOS/Linux - never through a command string.", "packages": { + "dsh-tables": { + "version": "0.1.0-alpha.1", + "rows": [ + "tables" + ], + "role": "Tables a paper can print: one JSON spec (grouped headers, row spans, column spans, tinted bands, best-value emphasis, maths) compiled to LaTeX booktabs, Markdown, DOCX and CSV, plus a PNG of the LaTeX actually setting. Two tools (table_write / table_read), one skill, a three-table reference corpus. Host-only, zero dependencies, no TeX package installed on demand. See packages/dsh-tables/README.md." + }, "dsh-vn-master": { "version": "0.1.0-alpha.3", "rows": [ diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 38f1662..1aa1a6e 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -57,6 +57,7 @@ disable/replace a core row **in its own layer** — a later layer wins per row. | `dsh-video` | `video` | video player tab; the bytes stay on the host and stream through a Range route | | `dsh-media` | `media` | the pack's ffmpeg owner: `media_probe` / `media_run` / `media_frames`, the Range file route, remux jobs | | `dsh-supercollider` | `supercollider` | SuperCollider the agent can play: ten `sc_*` tools over one warm `sclang` session (~31 ms a call, state kept) and a hand-written OSC client to `scsynth`, the installed `.schelp` reference indexed for `sc_help`, the `.scd` file workflow, five skills whose every example is compiled by a check, and one small console tab | +| `dsh-tables` | `tables` | a table COMPILER: one JSON spec (grouped headers with DERIVED spans, row and column spans, tinted bands, best-value emphasis per column per family, maths) → LaTeX booktabs, Markdown, DOCX and CSV from one resolved grid, plus a PNG of the LaTeX actually setting. Two tools, one skill, a three-table reference corpus, a rung ladder `t0-spec` → `t4-drawn`. Host-only: no route, no browser half | | `dsh-diagrams` | `diagrams` | Mermaid + TikZ + the vendored **Diagram Design** kit (204 examples, 44 documented types) + a **figure compiler** (`kind:"figure"`: a JSON spec measured, laid out, routed and emitted as one vector figure at a paper's column width), the seven `diagram_*` tools, validated on the host, and a reference corpus of two published paper figures rebuilt in that grammar | | `dsh-shaders` | `shaders` | GLSL that **compiles for real**: seven `shader_*` tools over a disposable headless browser (ANGLE/SwiftShader, argv-only, `MAP * ~NOTFOUND`), a rung ladder that is always stated (`v1-static` → `v2-compiled` → `v3-drawn` → `v4-measured`), diagnostics mapped onto the author's own line numbers, five dialects kept apart (es100, es300, shadertoy, shader-skills, and desktop GLSL, which is **refused** rather than faked), emit for web / `.frag` / ISF / FFGL-scaffold / Shadertoy, a Shaders tab with a live WebGL preview and `@param` sliders, five skills whose every example a check compiles, and three vendored corpora (106 Radiant pages with 79 extracted fragments, shader-skills' 20 modules + 11 templates + 11 pieces, and a 48-link curated index) that each re-derive offline | | `dsh-frontend-craft` | `frontend-craft` | front-end design craft: Impeccable's Apache-2.0 corpus (24 commands, 41 references) vendored at a pinned commit, its 61-rule detector built to a 4.5 MB WebAssembly module shipped in the package, `fe_context` / `fe_detect` / `fe_direction` / `fe_render` / `fe_artifact`, and a **Frontend** tab of findings, artifacts, directions and rendered previews. No network, no install, no engine download | diff --git a/README.md b/README.md index 0e81b77..c08ad35 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ -![vncode: the plugin pack, a Node application - the vncode README header](./assets/vncode-banner6.png) +![vncode: the plugin pack, a Node application - the vncode README header](./assets/vncode-banner7.png) Cross-platform Node ADE with core [DSH](https://www.deepseek.com/harness/en/) for professional Engineering and Design: every plugin is **Node.js** (plain JavaScript bundles, zero npm dependencies), and so is every launcher - there is no native code in this repository and nothing to compile. The launchers run on **Windows, macOS and Linux**. @@ -61,7 +61,7 @@ way and what it touches. The exact versions are in | [`dsh-cmdbar`](packages/dsh-cmdbar/README.md) | The command bar: the agent's own commands in a bottom dock, as a read-only transcript of the conversation log. It follows whichever conversation is on screen. | | [`dsh-comfyui`](packages/dsh-comfyui/README.md) | ComfyUI as a surface the agent can build against: seven `comfy_*` tools turn a small readable project spec into the canvas the app opens and the prompt `/prompt` accepts, validate it against the server's own `/object_info` with ComfyUI's own error types, and report what a run produced. Every answer names the rung it reached (`v1-structural` to `v4-executed`), so a graph that compiles is never called one that runs, and with no server it still checks the files on disk and names a missing checkpoint beside the nearest one. `comfy_cli` drives comfy-cli as a second, independent path, and six skills teach the fundamentals, the two workflow formats and how to write a node class. | | [`dsh-deckcraft`](packages/dsh-deckcraft/README.md) | Slides from the chat: four `deck_*` tools over the DeckCraft CLI (MIT OR Apache-2.0). `deck_commands` lists the command ids the build offers, `deck_run` saves a `.deckcraft` in the workspace, `deck_export` renders the slides to PNG so you can look at them. Nothing is hardcoded: DeckCraft's "every button is a command" contract is the API. | -| [`dsh-diagrams`](packages/dsh-diagrams/README.md) | Mermaid, TikZ and the Diagram Design kit as tabs and as seven `diagram_*` tools. The kit 204 examples and 44 documented types are vendored at a pinned commit and browsable on the index page. Every write, including a self-contained HTML document, is validated before it is stored. | +| [`dsh-diagrams`](packages/dsh-diagrams/README.md) | Mermaid, TikZ and the Diagram Design kit as tabs and as seven `diagram_*` tools. The kit 204 examples and 44 documented types are vendored at a pinned commit and browsable on the index page. Every write, including a self-contained HTML document, is validated before it is stored. A fourth kind, `figure`, goes further: a JSON spec is measured, laid out and routed on the host into one vector figure at a paper's column width, and `reference/figures/` rebuilds two published figures as its benchmark. | | [`dsh-docker`](packages/dsh-docker/README.md) | Docker or Podman as a surface: nine `docker_*` tools over the machine's own CLI, argv-only, with every removal confirmed by repeating the target. `docker_start` launches Docker Desktop or a podman machine and waits for the **daemon**. A Docker tab lists containers and images with their logs, and there is no `exec`, no `system prune` and no free-form `run`. | | [`dsh-editor`](packages/dsh-editor/README.md) | Text and code tabs over a vendored CodeMirror 6, with save/create and a Markdown preview. The preview exports the file as a PDF on the Desktop (the browser on the machine does the printing). Every extension is mapped through a guard, so an older engine opens the document unhighlighted instead of killing the tab. It also backs the `.scd`, diagram-source and research-document editors. | | [`dsh-frontend-craft`](packages/dsh-frontend-craft/README.md) | Front-end design craft: Impeccable's Apache-2.0 corpus vendored at a pinned commit, plus its 61-rule detector built to WebAssembly inside the package. Five `fe_*` tools include `fe_render`, which renders a page in headless Chrome or Edge and measures contrast, tap targets and overflow. There is no `npx impeccable`, no engine download and no network. A Frontend tab shows findings, artifacts and the direction round. | @@ -86,6 +86,7 @@ way and what it touches. The exact versions are in | [`dsh-skills`](packages/dsh-skills/README.md) | The Skills browser: a header button opens every skill this conversation loads, with its markdown and inline editing. It reads the same registry the agent does, so what you see is what is in effect. | | [`dsh-sql-server`](packages/dsh-sql-server/README.md) | Seven `sql_*` tools over a container this row owns or the `sqlcmd` already on PATH. It keeps apart the four facts that fail independently: a server, a client, a listening port and the machine-wide ODBC driver. `sql_server start` waits until the server answers a statement, and `sql_script` loads a dump with BOM-aware code pages. | | [`dsh-supercollider`](packages/dsh-supercollider/README.md) | SuperCollider the agent can play: eleven `sc_*` tools over one warm `sclang` session (about 31 ms a call, with state kept) and a hand-written OSC client to `scsynth`. The installed `.schelp` reference is indexed for `sc_help`, and the `.scd` workflow opens in the editor. Five skills teach the language, SynthDefs and live coding, and every example in them is compiled by a check. | +| [`dsh-tables`](packages/dsh-tables/README.md) | Tables a paper can print: one JSON spec (grouped headers with derived spans, row and column spans, tinted bands, best-value emphasis per column per family, maths) compiles to LaTeX booktabs, Markdown, DOCX and CSV from one resolved grid, plus a PNG of the LaTeX actually setting. `table_write` states the rung it reached (`t0-spec` to `t4-drawn`), and `reference/tables/` rebuilds three published tables as its benchmark. | | [`dsh-themes`](packages/dsh-themes/README.md) | Header controls for themes (Nord, Monokai, Hacker, Cyber), screenshot and page zoom, the Markdown paper and the pack branding, the app-wide scrollbars (16px on both axes), and the left band's row of Settings, Plugins, Media, Skills, Feedback and Sign in. It also hides the shipped account-menu Feedback row, whose door the band now carries. | | [`dsh-ui-state`](packages/dsh-ui-state/README.md) | The pack's own UI state, remembered host-side: zoom, theme, dock and column widths. It outlives the process, so a restart keeps the layout you left. | | [`dsh-video`](packages/dsh-video/README.md) | A player tab that streams and seeks any container the browser can decode. An ffprobe facts panel names codec, size and frame rate, and one click remuxes when the browser cannot decode it. | diff --git a/assets/vncode-banner7.png b/assets/vncode-banner7.png new file mode 100644 index 0000000..d6dd82a Binary files /dev/null and b/assets/vncode-banner7.png differ diff --git a/packages/dsh-tables/README.md b/packages/dsh-tables/README.md new file mode 100644 index 0000000..d2d535f --- /dev/null +++ b/packages/dsh-tables/README.md @@ -0,0 +1,80 @@ +# dsh-tables (alpha.1) + +**A table compiler: one JSON spec, four artifacts, and a PNG of the LaTeX actually +setting.** Grouped headers, row and column spans, tinted bands, best-value emphasis +and maths are described once; LaTeX, Markdown, DOCX and CSV are all derived from the +same resolved grid, so they cannot disagree about a number or about a winner. + +Host-only, zero dependencies, no TeX package installed on demand: the one child +process is the `pdflatex` (and `pdftoppm`) the machine already has. + +## What it adds + +- **Two tools.** `table_write` takes a spec, resolves the grid, typesets every + format and writes them beside the spec in `tables//`, stating the rung it + reached. `table_read` lists the tables in the workspace or returns one's spec and + build receipt. +- **One skill**, `paper-tables`: the spec, the four facts that make a table, the + rung ladder, and what each output format cannot do. +- **Five artifacts per table**: `spec.json`, `table.tex` (booktabs), + `table.md` (GFM), `table.csv` (data, merged values repeated), `table.docx` (a real + OOXML table with `gridSpan`, `vMerge`, shading and horizontal rules), and + `table.png` — page 1 of the compiled PDF at 200 dpi, which is what the model + looks at. + +## The spec, in one line each + +| part | it says | +|---|---| +| `table` | id, caption, label, style, body size, notes | +| `columns` | key, title, `group` (the header span), alignment, `best: max\|min`, `digits` | +| `groups` | the row bands: a `title` (section row) and/or `band: true` (tinted rows) | +| `rows` | `cells` by column key, `group`, `emphasis: "total"`, `span`, `rowSpan` | + +**Header spans are derived** from `column.group`, never written by hand — a +hand-written `\multicolumn{6}` is the way a table silently loses a column when +someone adds one. **Best marks are computed per column per row group**, because a +2B family and an 8B family are separate races. + +## The rungs + +`t0-spec` (JSON resolved) → `t1-grid` (every row covers the header) → `t2-data` +(numbers formatted, winners resolved) → `t3-typeset` (`pdflatex` compiled it) → +`t4-drawn` (a PNG exists). A table at `t2-data` has never been SET, and the answer +says so rather than implying it is verified. + +## The reference corpus + +Three published tables, rebuilt from their structure, in `reference/tables/`: +`vqa-results` (two header levels, four family bands, best-per-family bolding), +`dataset-summary` (row spans over prose blocks, alternating bands) and +`implementation-details` (column spans in the body, maths in cells). Each carries a +target, `SOURCE.md`, `anatomy.md`, `spec.json`, `rubric.json` and its built +artifacts. `reference/THIRD-PARTY.md` records each target's licence and sha256, and +deleting a target degrades the check to its structural tier instead of breaking it. + +## Limits + +- **One line per cell in LaTeX.** This host's `colortbl` refuses paragraph columns + (`p{}`), and a band matters more than a wrap, so a cell that must wrap gets its + own row. Word wraps on its own. +- **DOCX has no maths.** A `$…$` cell is written as plain text and the result says + the DOCX degraded; a silently wrong formula would be worse. +- **No table editor, no spreadsheet import**, and nothing reads the network. +- **The preview is the tabular**, not the float: no caption, no notes in the PNG — + a standalone page sizes to its widest line, and one caption would frame a 12 cm + table in a 40 cm page. +- **One table per file.** Assembling several into a document is `dsh-research`'s + job, not this row's. + +## Verify + +```sh +node packages/dsh-tables/checks/check-tables-node.mjs +``` + +91 checks: every corpus table builds, is byte-identical twice, its committed +artifacts do not drift, every rubric row is traced to a count or a string in the +real output, the DOCX is re-read from its ZIP, both tools run through a temp +workspace, and — where `pdflatex` is installed — the table compiles to one page and +is rasterised. diff --git a/packages/dsh-tables/checks/check-tables-node.mjs b/packages/dsh-tables/checks/check-tables-node.mjs new file mode 100644 index 0000000..fa999c9 --- /dev/null +++ b/packages/dsh-tables/checks/check-tables-node.mjs @@ -0,0 +1,160 @@ +// check-tables-node.mjs — the host half of dsh-tables, and its corpus. +// +// Why this exists: a table compiler is only as good as the tables it can set. +// This check builds every reference table, requires byte-identical output twice, +// fails on drift against the committed artifacts, traces every rubric row to a +// count or a string in the real output, re-reads the DOCX package, and — where a +// TeX engine is installed — compiles the table and requires one page. +// +// It also drives the two tools through a temp workspace, so `table_write` / +// `table_read` are proven to work and not only the library under them. +// +// Run: node packages/dsh-tables/checks/check-tables-node.mjs +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { buildTable, typesetTable } from '../lib/build.js' +import { unpackZip } from '../lib/zip.js' +import { buildTools } from '../lib/index.js' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const packageRoot = path.resolve(here, '..') +const referenceRoot = path.join(packageRoot, 'reference') +const tablesRoot = path.join(referenceRoot, 'tables') + +let failures = 0 +let checked = 0 +function check(label, actual, expected = true) { + checked += 1 + const ok = actual === expected + if (!ok) failures += 1 + const shown = typeof actual === 'string' || typeof actual === 'number' ? ' "' + String(actual).slice(0, 120) + '"' : '' + console.log((ok ? 'ok ' : 'FAIL ') + label + shown) +} + +/** The document part of a DOCX, as text. */ +function docxPart(bytes) { + const files = unpackZip(bytes) + return files.get('word/document.xml').toString('utf8') +} + +/** One built artifact by format. */ +function artifact(built, format) { + if (format === 'tex') return built.tex + if (format === 'md') return built.markdown + if (format === 'csv') return built.csv + if (format === 'docx') return built.docx.toString('utf8') + return '' +} + +const folders = existsSync(tablesRoot) ? readdirSync(tablesRoot).filter((name) => statSync(path.join(tablesRoot, name)).isDirectory()).sort() : [] +check('the corpus has tables', folders.length, 3) + +for (const slug of folders) { + const folder = path.join(tablesRoot, slug) + console.log('\n# ' + slug) + const source = readFileSync(path.join(folder, 'spec.json'), 'utf8') + const first = buildTable(source) + const second = buildTable(source) + check(slug + ': compiles', first.status, 'ok') + check(slug + ': reaches t2-data', first.rung, 't2-data') + check(slug + ': no diagnostic', first.diagnostics.length, 0) + check(slug + ': determinism (LaTeX)', first.tex === second.tex) + check(slug + ': determinism (DOCX)', Buffer.compare(first.docx, second.docx), 0) + + // The DOCX is a ZIP, so it either reads back or Word will not open it. + const document = docxPart(first.docx) + check(slug + ': the DOCX package reads back', document.includes('')) + + for (const [name, format] of [['table.tex', 'tex'], ['table.md', 'md'], ['table.csv', 'csv'], ['table.docx', 'docx']]) { + const file = path.join(folder, 'out', name) + if (!existsSync(file)) { + check(slug + ': ' + name + ' is committed', false) + continue + } + const onDisk = format === 'docx' ? readFileSync(file) : readFileSync(file, 'utf8') + const expected = format === 'docx' ? first.docx : artifact(first, format) + check(slug + ': ' + name + ' matches the compiler (no drift)', format === 'docx' ? Buffer.compare(onDisk, expected) === 0 : onDisk === expected) + } + + const rubric = JSON.parse(readFileSync(path.join(folder, 'rubric.json'), 'utf8')) + check(slug + ': the rubric names a target', rubric.target.endsWith('.png')) + const targetPath = path.join(referenceRoot, 'targets', path.basename(rubric.target)) + if (existsSync(targetPath)) { + const { createHash } = await import('node:crypto') + check(slug + ': the target still hashes to the rubric', createHash('sha256').update(readFileSync(targetPath)).digest('hex'), rubric.targetSha256) + } else { + console.log('ok ' + slug + ': no target committed (structural tier only)') + } + + for (const row of rubric.checks) { + const expect = row.expect ?? {} + if (expect.columns !== undefined) check(slug + ': ' + row.id + ' columns', first.grid.columnCount, expect.columns) + if (expect.rows !== undefined) check(slug + ': ' + row.id + ' rows', first.grid.rows.length, expect.rows) + if (expect.marks !== undefined) check(slug + ': ' + row.id + ' marks', first.grid.marks.size, expect.marks) + if (expect.groups !== undefined) check(slug + ': ' + row.id + ' groups', first.spec.groups.length, expect.groups) + for (const needle of expect.texIncludes ?? []) check(slug + ': ' + row.id + ' tex has "' + needle.slice(0, 28) + '"', first.tex.includes(needle)) + for (const needle of expect.mdIncludes ?? []) check(slug + ': ' + row.id + ' md has "' + needle.slice(0, 28) + '"', first.markdown.includes(needle)) + for (const needle of expect.docxIncludes ?? []) check(slug + ': ' + row.id + ' docx has "' + needle + '"', document.includes(needle)) + } + + const metricsPath = path.join(folder, 'out', 'metrics.json') + if (existsSync(metricsPath)) { + const metrics = JSON.parse(readFileSync(metricsPath, 'utf8')) + check(slug + ': metrics columns', metrics.columns, first.grid.columnCount) + check(slug + ': metrics rows', metrics.rows, first.grid.rows.length) + } +} + +// --- the tools, through a temp workspace --------------------------------- +const workspace = mkdtempSync(path.join(os.tmpdir(), 'dsh-tables-ws-')) +try { + const log = { info() {}, warn() {} } + const tools = buildTools({ log }) + const write = tools.find((tool) => tool.name === 'table_write') + const read = tools.find((tool) => tool.name === 'table_read') + const exec = { agent: { session: { id: 'check', header: { cwd: workspace } } }, signal: new AbortController().signal } + const spec = JSON.stringify({ + table: { caption: 'A two-column test table with a caption long enough to be real.', id: 'smoke' }, + columns: [{ key: 'name', title: 'Name' }, { key: 'value', title: 'Value', align: 'right', best: 'max', digits: 1 }], + rows: [{ cells: { name: 'a', value: 1.5 } }, { cells: { name: 'b', value: 2.5 } }], + }) + const written = await write.execute({ source: spec }, exec) + check('table_write: compiles', written.status, 'ok') + check('table_write: states a rung', /^t[0-9]-/.test(written.rung), true) + check('table_write: writes the LaTeX', existsSync(path.join(workspace, 'tables', 'smoke', 'table.tex'))) + check('table_write: writes the DOCX', existsSync(path.join(workspace, 'tables', 'smoke', 'table.docx'))) + check('table_write: best value is bold in the LaTeX', readFileSync(path.join(workspace, 'tables', 'smoke', 'table.tex'), 'utf8').includes('\\textbf{2.5}')) + const listed = await read.execute({}, exec) + check('table_read: lists the table', listed.text.includes('smoke')) + const one = await read.execute({ id: 'smoke' }, exec) + check('table_read: returns the spec', one.text.includes('"name": "a"')) + const broken = await write.execute({ source: '{"columns":[],"rows":[]}' }, exec) + check('table_write: an empty spec is refused', broken.status, 'error') + + // The rung is honest: no TeX engine means t2-data, and the answer says so. + const built = buildTable(spec) + const without = await typesetTable(built, { engine: null }) + check('typeset: no engine stops at t2-data', without.rung, 't2-data') + check('typeset: no engine says why', /No TeX engine/.test(without.typeset.text), true) +} finally { + rmSync(workspace, { recursive: true, force: true }) +} + +// --- one real compile, when the host has TeX ------------------------------ +const sample = buildTable(readFileSync(path.join(tablesRoot, 'implementation-details', 'spec.json'), 'utf8')) +const typed = await typesetTable(sample) +if (typed.typeset && typed.typeset.status === 'unavailable') { + console.log('skip: no TeX engine here, so the compile rung was not reached') +} else { + check('compile: pdflatex accepts the table', typed.rung, typed.png ? 't4-drawn' : 't3-typeset') + check('compile: one page', typed.pages, 1) + check('compile: no diagnostic', (typed.diagnostics ?? []).length, 0) +} + +console.log('\n' + (failures === 0 ? 'all ' + checked + ' table check(s) passed' : failures + ' check(s) FAILED')) +process.exit(failures === 0 ? 0 : 1) + + diff --git a/packages/dsh-tables/cordis.patch.yml b/packages/dsh-tables/cordis.patch.yml new file mode 100644 index 0000000..fe8cc38 --- /dev/null +++ b/packages/dsh-tables/cordis.patch.yml @@ -0,0 +1,13 @@ +# dsh-tables bundle layer (alpha). +# +# One extra row ('tables') owns the whole plugin: its Node half registers the two +# table tools (table_write / table_read), the bundled `paper-tables` skill, and +# nothing else. There is no route and no browser half on purpose - a table is a +# file that goes into a document, and the document is where a person looks at it: +# the artifacts land in the conversation's workspace and the PNG preview is read +# back like any other picture. +# +# Nothing shipped is patched and no core row is disabled. +- insert: + - id: tables + name: 'dsh-tables' diff --git a/packages/dsh-tables/lib/build.js b/packages/dsh-tables/lib/build.js new file mode 100644 index 0000000..e6c1fcc --- /dev/null +++ b/packages/dsh-tables/lib/build.js @@ -0,0 +1,165 @@ +/** + * dsh-tables — build one table and say how far it got. + * + * The ladder is the same discipline the rest of the pack uses, and every answer + * states the rung it reached: + * + * t0-spec the JSON parsed and every column/row/span resolved + * t1-grid every row covers exactly the columns the header declares + * t2-data numeric columns formatted, and the best-value mark resolved + * t3-typeset LaTeX compiled (real `pdflatex`), DOCX packaged and re-read + * t4-drawn a PNG exists, rendered from the compiled PDF + * + * A rung is not a score: it is the last thing that was CHECKED. A table with no + * TeX engine reaches t2 and says so. + */ +import { compileLatex, compileError, emitLatex } from './latex.js' +import { emitCsv, emitMarkdown } from './text.js' +import { emitDocx } from './docx.js' +import { parseTable, resolveTable } from './spec.js' + +/** + * Everything that does not need a child process. + * + * @param source - the JSON spec. + * @returns `{ ok, rung, spec, grid, tex, document, markdown, csv, docx, diagnostics, warnings, degraded }`. + */ +export function buildTable(source) { + const started = Date.now() + const parsed = parseTable(source) + if (parsed.problems.length > 0) { + return { ok: false, status: 'error', rung: 't0-spec', diagnostics: parsed.problems, warnings: [], spec: null, grid: null, ms: Date.now() - started } + } + const spec = parsed.spec + const grid = resolveTable(spec) + const diagnostics = [] + const warnings = [] + + // t1: the grid. A row's cells must cover the header exactly; a span that does + // not add up is how a table loses a column in one renderer and not another. + for (const [index, row] of grid.rows.entries()) { + // A span covers span positions; a row-span continuation still occupies its + // column (the merge above covers it), so it counts as one. + const covered = row.cells.reduce((sum, entry) => sum + (entry.skip ? 1 : entry.span), 0) + if (covered !== grid.columnCount) { + diagnostics.push({ kind: 'grid', text: 'row ' + (index + 1) + ' covers ' + covered + ' of ' + grid.columnCount + ' columns; check its span.' }) + } + } + + // t2: the data. A numeric column that holds a string is a number the reader + // will see unformatted and the best-value mark will skip. + for (const column of spec.columns) { + if (column.digits === 0 && column.best === null) continue + for (const [index, row] of spec.rows.entries()) { + const value = row.cells[column.key] + if (value === undefined || value === null) continue + if (typeof value === 'string' && /^-?\d+(\.\d+)?$/.test(value.trim())) { + warnings.push({ kind: 'data', text: 'row ' + (index + 1) + ', column "' + column.key + '" holds the string "' + value + '"; a quoted number is not formatted and cannot win a best-value mark.' }) + } + } + } + if (!spec.table.caption) warnings.push({ kind: 'caption', text: 'The spec has no `table.caption`. A paper table is read with its caption.' }) + if (spec.table.notes.length === 0) warnings.push({ kind: 'notes', text: 'No `table.notes`: if any cell is bold, say what the bold means.' }) + + const { fragment, document } = emitLatex(spec, grid) + const markdown = emitMarkdown(spec, grid) + const csv = emitCsv(spec, grid) + const { bytes: docx, degraded } = emitDocx(spec, grid) + for (const note of degraded) warnings.push({ kind: 'degraded', text: 'DOCX: ' + note }) + + const status = diagnostics.length > 0 ? 'error' : 'ok' + return { + ok: status === 'ok', + status, + rung: status === 'ok' ? 't2-data' : 't1-grid', + spec, + grid, + tex: fragment, + document, + markdown, + csv, + docx, + diagnostics, + warnings: warnings.slice(0, 8), + ms: Date.now() - started, + } +} + +/** + * Typeset: compile the wrapper, rasterise page 1 when a rasteriser is there. + * + * @param built - the result of {@link buildTable}. + * @param options - `{ signal, engine, raster }`. + * @returns the same object with `rung`, `pdf`, `png`, `pages` and any compile diagnostic. + */ +export async function typesetTable(built, { signal = null, engine = 'pdflatex', raster = true } = {}) { + if (!built.ok || !built.document) return built + if (!engine) { + return { + ...built, + rung: built.rung, + typeset: { status: 'unavailable', text: 'No TeX engine on this host, so the LaTeX was written but not compiled. Set DSH_TABLES_ENGINE=pdflatex to enable it.' }, + } + } + const compiled = await compileLatex(built.document, { signal }) + if (!compiled.ok) { + return { + ...built, + ok: false, + status: 'error', + rung: 't2-data', + diagnostics: [...built.diagnostics, { kind: 'typeset', text: 'LaTeX refused the table: ' + compileError(compiled.log) }], + typeset: { status: 'error', ms: compiled.ms }, + } + } + const pages = /Output written on table\.pdf \((\d+) pages?/.exec(compiled.log) + const pageCount = pages ? Number(pages[1]) : null + const warnings = [...built.warnings] + if (pageCount !== null && pageCount > 1) { + warnings.push({ kind: 'width', text: 'The compiled table is ' + pageCount + ' pages wide; at this column count it will not fit a column. Drop a column, shrink the type, or split the table.' }) + } + let png = null + if (raster) png = await rasterise(compiled.pdf) + return { + ...built, + rung: png ? 't4-drawn' : 't3-typeset', + pdf: compiled.pdf, + png, + pages: pageCount, + warnings: warnings.slice(0, 8), + typeset: { status: 'ok', ms: compiled.ms }, + } +} + +/** + * Rasterise page 1 of a PDF through `pdftoppm`. + * + * @returns a PNG buffer, or null when no rasteriser is installed. + */ +export async function rasterise(pdf, { dpi = 200 } = {}) { + if (!pdf) return null + const { spawn } = await import('node:child_process') + const { mkdtemp, readFile, rm, writeFile } = await import('node:fs/promises') + const os = await import('node:os') + const path = await import('node:path') + const dir = await mkdtemp(path.join(os.tmpdir(), 'dsh-tables-png-')) + try { + const file = path.join(dir, 'table.pdf') + await writeFile(file, pdf) + const ok = await new Promise((resolve) => { + const child = spawn('pdftoppm', ['-png', '-r', String(dpi), '-f', '1', '-l', '1', '-singlefile', file, path.join(dir, 'table')], { + windowsHide: true, + stdio: ['ignore', 'ignore', 'ignore'], + }) + child.on('error', () => resolve(false)) + child.on('close', (code) => resolve(code === 0)) + }) + if (!ok) return null + return await readFile(path.join(dir, 'table.png')) + } catch (error) { + return null + } finally { + await rm(dir, { recursive: true, force: true }).catch(() => {}) + } +} + diff --git a/packages/dsh-tables/lib/docx.js b/packages/dsh-tables/lib/docx.js new file mode 100644 index 0000000..e140f55 --- /dev/null +++ b/packages/dsh-tables/lib/docx.js @@ -0,0 +1,259 @@ +/** + * dsh-tables — the DOCX emitter. + * + * A Word table is a grid of `w:tc` cells whose `w:gridSpan` and `w:vMerge` say + * what the LaTeX `\multicolumn` / `\multirow` say. This module writes that grid + * by hand into a minimal OPC package (three parts: content types, the package + * relationships and `word/document.xml`), with the same rules the LaTeX emitter + * follows: horizontal rules only, no vertical lines, a tinted band per row group, + * bold winners, and a caption above the table. + * + * What it deliberately does not do: carry `$…$` maths. Word has no LaTeX maths + * without OMML, so a maths cell is written as its plain text and the result says + * the table degraded - a silently wrong formula is worse than an honest one. + */ +import { packZip } from './zip.js' + +const NS_W = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main' +const PAGE_WIDTH = 9360 + +const TONES = { + meta: 'EAF6EF', + link: 'EAF1FB', + soft: 'F1F3F6', + none: null, +} + +/** XML-escape one text node. */ +function xml(value) { + return String(value ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') +} + +/** What a maths cell looks like in a document with no maths: its text. */ +export function docxText(value) { + return String(value ?? '').replace(/\$/g, '') +} + +/** One run with the properties this table needs. */ +function run(text, { bold = false, size = 7, mono = false, serif = true } = {}) { + const font = mono ? 'Consolas' : serif ? 'Times New Roman' : 'Arial' + return ( + '' + + (bold ? '' : '') + + '' + + '' + + '' + xml(docxText(text)) + '' + ) +} + +/** One cell, with its span, merge, shading and alignment. */ +function cell(entry, spec, { width, fill = null, merge = null, span = 1, bold = false, align = 'left', size = 7, mono = false } = {}) { + const properties = [] + if (span > 1) properties.push('') + if (merge === 'restart') properties.push('') + if (merge === 'continue') properties.push('') + if (fill) properties.push('') + if (merge) properties.push('') + if (width) properties.push('') + const paragraph = + '' + + (entry ? run(entry, { bold, size, mono }) : '') + + '' + return '' + properties.join('') + '' + paragraph + '' +} + +/** + * Every grid position of one row, and what occupies it. + * + * A `skip` in the resolved grid is one of two things, and Word needs to know + * which: covered by the `gridSpan` of a cell to its left (emit nothing), or the + * continuation of a `vMerge` started above (emit an empty merged cell). + */ +function slotsFor(spec, grid, rowIndex) { + const slots = new Array(spec.columns.length).fill(null) + const cells = grid.rows[rowIndex].cells + let cursor = 0 + for (let index = 0; index < cells.length; index += 1) { + const entry = cells[index] + if (entry.skip) { + slots[cursor] = { kind: 'covered' } + cursor += 1 + continue + } + slots[cursor] = { kind: 'cell', entry } + for (let offset = 1; offset < entry.span; offset += 1) slots[cursor + offset] = { kind: 'covered' } + cursor += entry.span + } + for (let columnIndex = 0; columnIndex < slots.length; columnIndex += 1) { + if (slots[columnIndex] === null) slots[columnIndex] = { kind: 'covered' } + const key = spec.columns[columnIndex].key + for (let earlier = rowIndex - 1; earlier >= 0; earlier -= 1) { + const height = spec.rows[earlier].rowSpan && spec.rows[earlier].rowSpan[key] + if (height !== undefined) { + if (earlier + Math.round(height) > rowIndex) slots[columnIndex] = { kind: 'merge' } + break + } + } + } + return slots +} + +/** The column widths, in twips, from the spec's weights (a label column is wider by default). */ +export function columnWidths(spec) { + const weights = spec.columns.map((column, index) => column.width || (index === 0 ? 1.6 : 1)) + const total = weights.reduce((sum, weight) => sum + weight, 0) + const widths = weights.map((weight) => Math.max(600, Math.round((PAGE_WIDTH * weight) / total))) + // The rounding leaves a few twips over; the last column absorbs them so the + // grid matches the page exactly. + const drift = PAGE_WIDTH - widths.reduce((sum, width) => sum + width, 0) + widths[widths.length - 1] += drift + return widths +} + +/** The table body: header rows, group bands, data rows. */ +function tableXml(spec, grid) { + const widths = columnWidths(spec) + const size = spec.table.size + const mono = (column) => column.mono === true + const lines = [] + lines.push('') + lines.push( + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '', + ) + lines.push('' + widths.map((width) => '').join('') + '') + + if (!spec.header.multiRow) { + const cells = spec.columns.map((column, index) => cell(column.title, spec, { width: widths[index], bold: true, align: column.align, size })) + lines.push('' + cells.join('') + '') + } else { + const first = [] + let index = 0 + for (const run of spec.header.runs) { + if (run.title === null) { + first.push(cell(spec.columns[index].title, spec, { width: widths[index], bold: true, merge: 'restart', align: spec.columns[index].align, size })) + index += 1 + continue + } + const span = run.columns.length + first.push(cell(run.title, spec, { width: widths[index], bold: true, span, align: 'center', size })) + index += span + } + lines.push('' + first.join('') + '') + const second = spec.columns.map((column, columnIndex) => + column.group === null + ? cell(null, spec, { width: widths[columnIndex], merge: 'continue', size }) + : cell(column.title, spec, { width: widths[columnIndex], bold: true, align: column.align, size }), + ) + lines.push('' + second.join('') + '') + } + + let previousGroup = null + spec.rows.forEach((row, rowIndex) => { + const group = row.group === null ? null : spec.groups[row.group] + if (group && group.title.length > 0 && row.group !== previousGroup) { + const fill = TONES[group.tone] ?? TONES.soft + lines.push( + '' + + cell('▼ ' + group.title, spec, { width: PAGE_WIDTH, span: spec.columns.length, bold: true, fill, size }) + + '', + ) + previousGroup = row.group + } + const fill = row.emphasis === 'total' ? 'F2F4F7' : group && group.band ? (TONES[group.tone] ?? TONES.soft) : null + const cells = [] + for (const [columnIndex, slot] of slotsFor(spec, grid, rowIndex).entries()) { + if (slot.kind === 'covered') continue + if (slot.kind === 'merge') { + cells.push(cell(null, spec, { width: widths[columnIndex], merge: 'continue', size })) + continue + } + const entry = slot.entry + cells.push( + cell(entry.text, spec, { + width: widths[columnIndex], + span: entry.span, + merge: entry.rowSpan > 1 ? 'restart' : null, + bold: entry.bold || row.emphasis === 'total', + fill, + align: entry.align, + size, + mono: mono(entry.column), + }), + ) + } + lines.push('' + cells.join('') + '') + }) + lines.push('') + return lines.join('') +} + +/** The document part: caption, table, notes. */ +function documentXml(spec, grid) { + const body = [] + if (spec.table.caption) { + body.push( + '' + + run(spec.table.caption, { bold: true, size: Math.max(8, spec.table.size + 1) }) + + '', + ) + } + body.push(tableXml(spec, grid)) + if (spec.table.notes.length > 0) { + body.push( + '' + + run(spec.table.notes.join(' '), { size: Math.max(6, spec.table.size - 1) }) + + '', + ) + } + body.push('') + return ( + '' + + '' + body.join('') + '' + ) +} + +const CONTENT_TYPES = + '' + + '' + + '' + + '' + + '' + + '' + +const RELS = + '' + + '' + + '' + + '' + +/** + * Build a `.docx` holding exactly this table. + * + * @returns `{ bytes, degraded }` - `degraded` is the list of things Word cannot + * carry (maths), so the caller can say so instead of implying a faithful copy. + */ +export function emitDocx(spec, grid) { + const degraded = [] + const hasMath = spec.rows.some((row) => Object.values(row.cells).some((value) => typeof value === 'string' && value.includes('$'))) + if (hasMath) degraded.push('maths in cells is written as plain text (Word has no LaTeX maths without OMML)') + const files = new Map([ + ['[Content_Types].xml', CONTENT_TYPES], + ['_rels/.rels', RELS], + ['word/document.xml', documentXml(spec, grid)], + ]) + return { bytes: packZip(files), degraded } +} + + + diff --git a/packages/dsh-tables/lib/index.js b/packages/dsh-tables/lib/index.js new file mode 100644 index 0000000..2809f5b --- /dev/null +++ b/packages/dsh-tables/lib/index.js @@ -0,0 +1,352 @@ +/** + * dsh-tables — the row. + * + * One capability: turn a table SPEC into the four artifacts a paper needs (LaTeX, + * Markdown, DOCX, CSV) plus a PNG of the LaTeX actually setting, and say which + * rung it reached. Host-only: no route, no browser half, no tab - a table is a + * file that goes into a document, and the document is where a person looks at it. + * + * Two tools, because a table has two verbs: write one, read one back. + * + * table_write spec in, files out, rung stated + * table_read what tables this workspace holds, or one table's spec and build + * + * Nothing is installed and nothing reaches the network: the one child process is + * the TeX engine (and `pdftoppm` for the preview), argv-only, with MiKTeX's + * on-demand installer disabled so a missing package fails instead of downloading. + */ +import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import path from 'node:path' + +import { buildTable, typesetTable } from './build.js' +import { parseTable } from './spec.js' + +export const name = 'dsh-tables' + +/** Services this row waits for: the tool registry only. */ +export const inject = ['tools'] + +/** What this row offers, for the README and the package check. */ +export const CAPABILITIES = { + tools: ['table_write', 'table_read'], + formats: ['tex', 'md', 'csv', 'docx', 'png'], + rungs: ['t0-spec', 't1-grid', 't2-data', 't3-typeset', 't4-drawn'], + notBuilt: ['a table editor', 'a spreadsheet import', 'a PDF of the whole paper', 'anything that reaches the network'], +} + +/** The one skill, as a file beside this module. */ +export const SKILL_FILES = [{ name: 'paper-tables', file: '../skills/paper-tables/SKILL.md' }] + +/** One source's ceiling. A table is a document, not a dataset dump. */ +export const MAX_SOURCE_BYTES = 256 * 1024 + +/** The formats `table_write` can produce. */ +const FORMATS = ['tex', 'md', 'csv', 'docx', 'png'] + +/** The folder a table lands in, relative to the workspace. */ +const ROOT = 'tables' + +/** Split a skill file's frontmatter from its body. */ +export function parseSkillFile(text) { + const raw = String(text ?? '') + const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(raw) + if (!match) return { meta: {}, content: raw.trim() } + const meta = {} + for (const line of match[1].split(/\r?\n/)) { + const pair = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line) + if (pair) meta[pair[1]] = pair[2].replace(/^["']|["']$/g, '') + } + return { meta, content: raw.slice(match[0].length).trim() } +} + +/** A slug a folder name and a LaTeX label can both carry. */ +export function slugify(value) { + const slug = String(value ?? '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 48) + return slug.length > 0 ? slug : 'table' +} + +/** The conversation's workspace root, or null. */ +function workspaceOf(exec) { + const session = exec && exec.agent && exec.agent.session + const cwd = session && session.header && typeof session.header.cwd === 'string' ? session.header.cwd : session && typeof session.cwd === 'string' ? session.cwd : null + return cwd && cwd.length > 0 ? path.resolve(cwd) : null +} + +/** Resolve a folder inside the workspace, refusing anything that escapes it. */ +function resolveInside(workspace, folder) { + const target = path.resolve(workspace, folder) + const relative = path.relative(workspace, target) + if (relative.startsWith('..') || path.isAbsolute(relative)) { + throw Object.assign(new Error('`out` must be a relative folder inside the workspace, without "..": ' + folder), { code: 'BAD_PATH' }) + } + return target +} + +/** A file's size, or null. */ +function sizeOf(file) { + try { + return statSync(file).size + } catch (error) { + return null + } +} + +/** The model-facing summary of one build. */ +function summaryText(id, folder, built, written, relativeFolder) { + const lines = [] + lines.push('Table "' + id + '" — ' + built.status + ', rung ' + built.rung + '.') + if (built.rung === 't4-drawn') lines.push('It compiled with pdflatex and was rasterised: the PNG is what LaTeX actually set, not a preview of the spec.') + else if (built.rung === 't3-typeset') lines.push('It compiled with pdflatex; there is no rasteriser (pdftoppm) on this host, so there is no PNG.') + else lines.push('It was NOT compiled: ' + ((built.typeset && built.typeset.text) || 'no TeX engine is available here. The LaTeX is written and unverified.')) + const grid = built.grid + lines.push( + grid.columnCount + + ' columns × ' + + grid.rows.length + + ' rows' + + (built.grid.marks.size > 0 ? ', ' + built.grid.marks.size + ' best-value mark(s)' : '') + + (built.spec.groups.length > 0 ? ', ' + built.spec.groups.length + ' row group(s)' : '') + + '.', + ) + lines.push('Written to ' + relativeFolder + ':') + for (const file of written) lines.push(' ' + file.name + ' ' + file.bytes + ' bytes') + if (built.pages && built.pages > 1) lines.push('The compiled table is ' + built.pages + ' pages wide — it will not fit a column as it stands.') + for (const diagnostic of built.diagnostics ?? []) lines.push(' - ' + diagnostic.text) + if ((built.warnings ?? []).length > 0) { + lines.push('Advisory (the table is valid — fix these only if they are wrong):') + for (const warning of built.warnings) lines.push(' ! ' + warning.text) + } + lines.push('Open ' + path.join(relativeFolder, 'table.png') + ' to look at it, or ' + path.join(relativeFolder, 'table.tex') + ' to include it.') + return lines.join('\n') +} + +/** + * Register the tools. + * + * @param deps - `{ log }`. + * @returns the tool definitions. + */ +export function buildTools(deps) { + const log = deps.log + const write = { + name: 'table_write', + description: [ + 'Create or replace ONE table from a JSON spec and typeset it to the four artifacts a paper needs: LaTeX (booktabs), Markdown, DOCX and CSV — plus a PNG of the LaTeX actually setting.', + '', + 'The spec is `{ "table": {...}, "columns": [...], "groups": [...], "rows": [...] }`. Columns carry a `group`, so the header spans are DERIVED, never written by hand. A column with `"best": "max"` bolds the winner of that column INSIDE each row group (a 2B family and an 8B family are separate races). `rowSpan` merges a cell down, `span` merges it across, `emphasis: "total"` bolds the whole row.', + '', + 'The answer states the rung it reached: t0-spec (parsed), t1-grid (every row covers the header), t2-data (numbers formatted, best marks resolved), t3-typeset (pdflatex compiled it), t4-drawn (a PNG exists). A table that did not compile is an error with the compiler\'s own line.', + '', + 'Files land in `tables//` unless `out` names another workspace-relative folder: spec.json, table.tex, table.md, table.csv, table.docx, table.png (and table.pdf when TeX is there).', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + source: { type: 'string', description: 'The JSON table spec.' }, + id: { type: 'string', description: 'Folder name and default LaTeX label; lower-case letters, digits and dashes. Defaults to table.id, then the caption, then "table".' }, + out: { type: 'string', description: 'Workspace-relative folder to write into. Default: tables//.' }, + formats: { type: 'array', items: { type: 'string', enum: FORMATS }, description: 'Which artifacts to write. Default: all of them.' }, + preview: { type: 'boolean', description: 'Compile and rasterise a PNG. Default true; ignored when no TeX engine is installed.' }, + }, + required: ['source'], + }, + output: { + schema: { + type: 'object', + properties: { + text: { type: 'string' }, + id: { type: 'string' }, + status: { type: 'string' }, + rung: { type: 'string' }, + files: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, bytes: { type: 'integer' } }, required: ['name', 'bytes'] } }, + diagnostics: { type: 'array', items: { type: 'object', properties: { kind: { type: 'string' }, text: { type: 'string' } }, required: ['kind', 'text'] } }, + }, + required: ['text', 'status', 'rung'], + }, + render: (_args, value) => [{ type: 'text', text: value.text }], + }, + presentCall: (args) => ({ card: 'generic', title: 'Write table' + (args && args.id ? ' "' + args.id + '"' : ''), kind: 'other' }), + presentResult: (_args, result) => ({ card: 'generic', title: 'Table ' + (result.meta && result.meta.id ? '"' + result.meta.id + '" ' : '') + (result.meta ? result.meta.status : ''), content: result.content }), + async execute(args, exec) { + const source = String(args.source ?? '') + if (Buffer.byteLength(source, 'utf8') > MAX_SOURCE_BYTES) { + throw Object.assign(new Error('The table spec is larger than ' + Math.round(MAX_SOURCE_BYTES / 1024) + ' KiB.'), { code: 'TOO_LARGE' }) + } + const built = buildTable(source) + if (!built.ok) { + const lines = ['Table NOT built: ' + built.status + ' at ' + built.rung + '.', 'Fix these and write again:'] + for (const diagnostic of built.diagnostics) lines.push(' - ' + diagnostic.text) + return { text: lines.join('\n'), status: built.status, rung: built.rung, files: [], diagnostics: built.diagnostics } + } + const workspace = workspaceOf(exec) + if (!workspace) throw Object.assign(new Error('This conversation has no workspace to write the table into.'), { code: 'NO_WORKSPACE' }) + const id = slugify(typeof args.id === 'string' && args.id.length > 0 ? args.id : built.spec.table.id ?? built.spec.table.caption ?? 'table') + const folder = typeof args.out === 'string' && args.out.length > 0 ? resolveInside(workspace, args.out) : path.join(workspace, ROOT, id) + await mkdir(folder, { recursive: true }) + + const wanted = new Set(Array.isArray(args.formats) && args.formats.length > 0 ? args.formats.filter((format) => FORMATS.includes(format)) : FORMATS) + const final = wanted.has('tex') ? await typesetTable(built, { signal: exec.signal, raster: wanted.has('png') }) : built + const written = [] + const put = async (fileName, bytes) => { + if (bytes === null || bytes === undefined) return + await writeFile(path.join(folder, fileName), bytes) + written.push({ name: fileName, bytes: Buffer.byteLength(bytes) }) + } + await put('spec.json', JSON.stringify(JSON.parse(source), null, 2) + '\n') + if (wanted.has('tex')) await put('table.tex', final.tex) + if (wanted.has('md')) await put('table.md', final.markdown) + if (wanted.has('csv')) await put('table.csv', final.csv) + if (wanted.has('docx')) await put('table.docx', final.docx) + if (wanted.has('tex') && final.pdf) await put('table.pdf', final.pdf) + if (wanted.has('png') && final.png) await put('table.png', final.png) + const build = { + id, + rung: final.rung, + status: final.status, + at: new Date().toISOString(), + caption: final.spec.table.caption, + columns: final.grid.columnCount, + rows: final.grid.rows.length, + formats: written.map((file) => path.extname(file.name).slice(1)), + pages: final.pages ?? null, + } + await writeFile(path.join(folder, 'build.json'), JSON.stringify(build, null, 2) + '\n') + const relative = path.relative(workspace, folder).split(path.sep).join('/') || '.' + log.info('table "' + id + '" written at ' + relative + ' (' + final.rung + ')') + return { + text: summaryText(id, folder, final, written, relative), + id, + status: final.status, + rung: final.rung, + files: written, + diagnostics: final.diagnostics ?? [], + } + }, + } + + const read = { + name: 'table_read', + description: [ + 'Read the tables in this workspace, or one table\'s spec and last build.', + 'Without `id`: every folder under `tables/` that holds a spec, with its caption, size, rung and files.', + 'With `id`: the spec JSON and the build receipt, so a table can be edited without re-deriving it from scratch. Read before rewriting one.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + id: { type: 'string', description: 'The table folder name. Omit to list.' }, + out: { type: 'string', description: 'List a different workspace-relative folder than tables/.' }, + includeSource: { type: 'boolean', description: 'With `id`, pass false for the receipt only. Default true.' }, + }, + }, + output: { + schema: { type: 'object', properties: { text: { type: 'string' }, id: { type: 'string' }, rung: { type: 'string' } }, required: ['text'] }, + render: (_args, value) => [{ type: 'text', text: value.text }], + }, + presentCall: (args) => ({ card: 'generic', title: 'Read table' + (args && args.id ? ' "' + args.id + '"' : ''), kind: 'other' }), + async execute(args, exec) { + const workspace = workspaceOf(exec) + if (!workspace) throw Object.assign(new Error('This conversation has no workspace.'), { code: 'NO_WORKSPACE' }) + const base = typeof args.out === 'string' && args.out.length > 0 ? resolveInside(workspace, args.out) : path.join(workspace, ROOT) + if (typeof args.id === 'string' && args.id.length > 0) { + const id = slugify(args.id) + const folder = path.join(base, id) + if (!existsSync(path.join(folder, 'spec.json'))) return { text: 'No table "' + id + '" in ' + path.relative(workspace, base) + '.', id } + const build = existsSync(path.join(folder, 'build.json')) ? JSON.parse(readFileSync(path.join(folder, 'build.json'), 'utf8')) : null + const lines = [] + lines.push('Table "' + id + '"' + (build ? ' — ' + build.status + ', rung ' + build.rung : ' (no build receipt)')) + if (build) lines.push(build.columns + ' columns × ' + build.rows + ' rows; files: ' + (build.formats ?? []).join(', ')) + if (args.includeSource === false) return { text: lines.join('\n'), id, rung: build ? build.rung : undefined } + lines.push('', await readFile(path.join(folder, 'spec.json'), 'utf8')) + return { text: lines.join('\n'), id, rung: build ? build.rung : undefined } + } + if (!existsSync(base)) return { text: 'No tables yet: ' + path.relative(workspace, base) + ' does not exist.' } + const entries = readdirSync(base, { withFileTypes: true }).filter((entry) => entry.isDirectory()) + if (entries.length === 0) return { text: 'No tables yet under ' + path.relative(workspace, base) + '.' } + const lines = ['Tables under ' + path.relative(workspace, base).split(path.sep).join('/') + ':'] + for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) { + const receipt = path.join(base, entry.name, 'build.json') + if (!existsSync(receipt)) continue + try { + const build = JSON.parse(readFileSync(receipt, 'utf8')) + lines.push(' ' + entry.name + ' — ' + (build.caption ?? '(no caption)') + ' · ' + build.columns + '×' + build.rows + ' · ' + build.rung + ' · ' + (build.formats ?? []).join('/')) + } catch (error) { + lines.push(' ' + entry.name + ' — unreadable build.json') + } + } + return { text: lines.join('\n') } + }, + } + + return [write, read] +} + +/** Register the bundled skill on the skill registry, if there is one. */ +export function registerSkills(ctx, log) { + const skills = typeof ctx.get === 'function' ? ctx.get('skills') : undefined + if (skills === null || skills === undefined || typeof skills.register !== 'function') { + log.warn('skill registry unavailable - the bundled table skill was not registered') + return 0 + } + let count = 0 + for (const entry of SKILL_FILES) { + try { + const file = new URL(entry.file, import.meta.url) + const filePath = fileURLToPath(file) + const { meta, content } = parseSkillFile(readFileSync(file, 'utf8')) + if (content.length === 0) continue + ctx.effect( + () => + skills.register({ + name: typeof meta.name === 'string' && meta.name.length > 0 ? meta.name : entry.name, + description: typeof meta.description === 'string' ? meta.description : '', + whenToUse: typeof meta.whenToUse === 'string' ? meta.whenToUse : undefined, + content, + provider: 'dsh-tables', + source: 'bundled', + path: filePath, + resourceBase: { kind: 'directory', path: path.dirname(filePath) }, + }), + 'dsh-tables: skill ' + entry.name, + ) + count += 1 + } catch (error) { + log.warn('could not register skill ' + entry.name + ': ' + (error && error.message ? error.message : String(error))) + } + } + return count +} + +/** + * The row. + * + * @param ctx - the cordis context. + */ +export function apply(ctx) { + const log = ctx.logger ? ctx.logger('dsh-tables') : { info() {}, warn() {} } + registerSkills(ctx, log) + for (const tool of buildTools({ log })) { + ctx.effect(() => ctx.tools.register(tool), 'dsh-tables: tool ' + tool.name) + } + log.info('active: table_write / table_read · LaTeX, Markdown, DOCX, CSV, PNG · nothing is installed') +} + +/** Exported for the tracked checks. */ +export const __internals = { + buildTools, + buildTable, + typesetTable, + parseTable, + parseSkillFile, + slugify, + CAPABILITIES, +} + diff --git a/packages/dsh-tables/lib/latex.js b/packages/dsh-tables/lib/latex.js new file mode 100644 index 0000000..aeff2d8 --- /dev/null +++ b/packages/dsh-tables/lib/latex.js @@ -0,0 +1,317 @@ +/** + * dsh-tables — the LaTeX emitter, and the compile that proves it. + * + * LaTeX is the PRIMARY target, not one format among five: a paper table is a + * `booktabs` table, and `pdflatex` is the only renderer on this machine that will + * tell the truth about whether the thing sets. The emitter therefore produces two + * documents from one grid: + * + * - the **fragment** (`\begin{table}…\end{table}`) that goes into the paper; + * - the **standalone wrapper** used to compile it for the preview, with the same + * packages and a page wide enough that a 12-column table is not silently + * shrunk. + * + * The rule that makes the compile meaningful: every package the fragment needs is + * declared in the wrapper, so a document that compiles here is a document that + * compiles in the paper (given the same TeX distribution). + */ +import { spawn } from 'node:child_process' +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' + +/** The packages the wrapper declares; a missing one fails fast, never at the internet. */ +export const LATEX_PACKAGES = ['booktabs', 'multirow', 'array', 'amsmath', 'amssymb'] + +/** How long one compile may take before it is killed. */ +const COMPILE_TIMEOUT_MS = 30_000 + +/** The fill used for a row group, per tone. Deliberately pale: a band is not a highlight. */ +const TONES = { + meta: 'EAF6EF', + link: 'EAF1FB', + soft: 'F1F3F6', + none: null, +} + +/** The em dash and the arrow the section headings use, as LaTeX. */ +const MARKER = '$\\blacktriangledown$' + +/** Escape everything that is text, leaving `$…$` runs as maths. */ +export function latexText(value) { + const parts = String(value ?? '').split(/(\$[^$]*\$)/g) + return parts + .map((part, index) => { + if (index % 2 === 1) return part + return part + .replace(/\\/g, '\\textbackslash{}') + .replace(/([&%#_])/g, '\\$1') + .replace(/\{/g, '\\{') + .replace(/\}/g, '\\}') + .replace(/~/g, '\\textasciitilde{}') + .replace(/\^/g, '\\textasciicircum{}') + }) + .join('') +} + +/** The size command for a body size in points, in a 10 pt document. */ +function sizeCommand(size) { + if (size <= 6) return '\\scriptsize' + if (size <= 7) return '\\footnotesize' + if (size <= 8) return '\\small' + if (size <= 9) return '\\normalsize' + return '\\large' +} + +/** The column specification: every column, with the outer padding removed. */ +function columnSpec(spec) { + // Plain l/c/r only: this host's colortbl breaks p{} paragraph columns + // outright (\\@nextchar undefined), and a table whose bands matter more than + // its wrapping is the better trade. A cell that must wrap gets its own row. + const letters = spec.columns.map((column) => (column.align === 'right' ? 'r' : column.align === 'center' ? 'c' : 'l')) + return '@{}' + letters.join('') + '@{}' +} + +/** One rendered cell. */ +function cell(spec, value, { align = null, span = 1, rowSpan = 1, bold = false, fill = null, first = false } = {}) { + const letter = align === 'right' ? 'r' : align === 'center' ? 'c' : 'l' + const alignment = span > 1 ? letter : null + // `\cellcolor`, not `\rowcolor`: the row fill is emitted per cell so a band + // survives a table whose columns are not all the same height. + const paint = fill ? '\\cellcolor[HTML]{' + fill + '}' : '' + const text = paint + (bold ? '\\textbf{' + latexText(value) + '}' : latexText(value)) + // Top-aligned, like the papers: a task label belongs to the first line of its + // block, and a centred one lands on the boundary between two lines. + const inner = rowSpan > 1 ? '\\multirow[t]{' + rowSpan + '}{*}{' + text + '}' : text + // A single-column cell needs no `\multicolumn`: the preamble already carries its + // alignment, and wrapping a `\multirow` in one breaks the vertical centring. + if (span === 1) return inner + return '\\multicolumn{' + span + '}{' + (alignment ?? 'c') + '}{' + inner + '}' +} + +/** + * The header rows. + * + * Derived, never written: the first row is one `\multicolumn` per run, the second + * is the column titles, and a run's `\cmidrule` spans exactly the columns it + * covers. Adding a column to a group widens the rule by itself. + */ +function headerLines(spec) { + const lines = [] + const titles = spec.columns.map((column) => column.title) + if (!spec.header.multiRow) { + lines.push(titles.map((title) => latexText(title)).join(' & ') + ' \\\\') + return lines + } + const first = [] + let cursor = 1 + const rules = [] + for (const run of spec.header.runs) { + if (run.title === null) { + first.push('\\multicolumn{1}{@{}l}{\\multirow{2}{*}{' + latexText(titles[spec.columns.findIndex((column) => column.key === run.columns[0])]) + '}}') + cursor += 1 + continue + } + first.push('\\multicolumn{' + run.columns.length + '}{c}{' + latexText(run.title) + '}') + if (run.columns.length > 1) rules.push('\\cmidrule(lr){' + cursor + '-' + (cursor + run.columns.length - 1) + '}') + else rules.push('\\cmidrule(lr){' + cursor + '-' + cursor + '}') + cursor += run.columns.length + } + lines.push(first.join(' & ') + ' \\\\') + if (rules.length > 0) lines.push(rules.join(' ')) + // The second row carries one title per GROUPED column, so it is built from the + // columns rather than from the runs: ungrouped columns are the blank multirow. + const row = [] + for (const column of spec.columns) row.push(column.group === null ? '' : latexText(column.title)) + lines.push(row.join(' & ') + ' \\\\') + return lines +} + +/** + * Emit the fragment a paper includes. + * + * @param spec - the parsed spec. + * @param grid - the resolved grid. + * @returns `{ fragment, document }` - the paper's bytes and a compilable wrapper. + */ +export function emitLatex(spec, grid) { + const lines = [] + lines.push('\\begin{table}[t]') + lines.push('\\centering') + if (spec.table.caption) lines.push('\\caption{' + latexText(spec.table.caption) + '}') + if (spec.table.label) lines.push('\\label{' + spec.table.label + '}') + lines.push(sizeCommand(spec.table.size)) + lines.push('\\setlength{\\tabcolsep}{4pt}') + lines.push('\\renewcommand{\\arraystretch}{1.06}') + lines.push('\\begin{tabular}{' + columnSpec(spec) + '}') + lines.push('\\toprule') + for (const line of headerLines(spec)) lines.push(line) + lines.push('\\midrule') + + let previousGroup = null + let firstRow = true + spec.rows.forEach((row, index) => { + const gridRow = grid.rows[index] + const group = row.group === null ? null : spec.groups[row.group] ?? null + const heading = group && group.title.length > 0 && row.group !== previousGroup + if (heading && !firstRow) lines.push('\\midrule') + if (heading) { + const fill = TONES[group.tone] ?? TONES.soft + const paint = fill ? '\\cellcolor[HTML]{' + fill + '}' : '' + lines.push('\\multicolumn{' + spec.columns.length + '}{@{}l}{' + paint + '\\textbf{' + MARKER + ' ' + latexText(group.title) + '}} \\\\') + previousGroup = row.group + } + const fill = row.emphasis === 'total' ? 'F2F4F7' : !heading && group && group.band ? (TONES[group.tone] ?? TONES.soft) : null + const cells = [] + let columnIndex = 0 + for (const entry of gridRow.cells) { + if (entry.skip) continue + cells.push( + cell(spec, entry.text, { + align: entry.align, + span: entry.span, + rowSpan: entry.rowSpan, + bold: entry.bold, + fill, + first: columnIndex === 0, + }), + ) + columnIndex += entry.span + } + lines.push(cells.join(' & ') + ' \\\\') + firstRow = false + }) + lines.push('\\bottomrule') + lines.push('\\end{tabular}') + if (spec.table.notes.length > 0) { + // A plain paragraph, not `flushleft`: a list environment cannot be used + // inside the standalone preview box, and one source has to serve both. + lines.push('\\par\\smallskip') + lines.push('{\\footnotesize') + lines.push(spec.table.notes.map((note) => latexText(note) + '\\par').join('\n')) + lines.push('}') + } + lines.push('\\end{table}') + const fragment = lines.join('\n') + '\n' + + // The preview is a STANDALONE document: it crops to the table instead of + // setting it on a page, which is what makes the PNG worth looking at. The + // The preview is the TABULAR only. A standalone document sizes its page to its + // widest line, and one long caption would set a 40 cm page around a 12 cm + // table; the caption and the notes are in the fragment, where the paper needs + // them, and the PNG is for looking at the grid. + const body = fragment + .replace(/^\\begin\{table\}\[t\]\n/, '') + .replace(/^\\centering\n/, '') + .replace(/^\\caption\{[^\n]*\}\n/, '') + .replace(/^\\label\{[^\n]*\}\n/, '') + .replace(/\\end\{table\}\n$/, '') + .replace(/\n\\par\\smallskip\n\{\\footnotesize\n[\s\S]*?\n\}\n$/, '\n') + const document = [ + '\\documentclass[border=8pt]{standalone}', + '\\usepackage[T1]{fontenc}', + '\\usepackage[utf8]{inputenc}', + '\\usepackage[table]{xcolor}', + '\\usepackage{colortbl}', + ...LATEX_PACKAGES.map((name) => '\\usepackage{' + name + '}'), + '\\pagestyle{empty}', + '\\begin{document}', + body, + '\\end{document}', + '', + ].join('\n') + return { fragment, document } +} + +/** + * Compile one document to PDF. + * + * Runs twice: a table with `\label` needs a second pass for the number, and the + * second pass is cheap compared with reading a "??" in the preview. + * + * @returns `{ ok, pdf, log, ms }`; `pdf` is null when the compile failed. + */ +export async function compileLatex(document, { signal = null, timeoutMs = COMPILE_TIMEOUT_MS } = {}) { + const started = Date.now() + const dir = await mkdtemp(path.join(os.tmpdir(), 'dsh-tables-')) + try { + await writeFile(path.join(dir, 'table.tex'), document, 'utf8') + let last = { code: 0, log: '' } + for (let pass = 0; pass < 2; pass += 1) { + last = await runLatex(dir, signal, timeoutMs) + if (last.code !== 0) break + } + let pdf = null + if (last.code === 0) { + try { + pdf = await readFile(path.join(dir, 'table.pdf')) + } catch (error) { + pdf = null + } + } + return { ok: last.code === 0 && pdf !== null, pdf, log: last.log, ms: Date.now() - started } + } finally { + await rm(dir, { recursive: true, force: true }).catch(() => {}) + } +} + +/** One pdflatex run, argv-only, with the network-install escape hatches closed. */ +function runLatex(dir, signal, timeoutMs) { + return new Promise((resolve) => { + const child = spawn('pdflatex', ['-interaction=nonstopmode', '-halt-on-error', '-file-line-error', '-no-shell-escape', 'table.tex'], { + cwd: dir, + env: { ...process.env, MIKTEX_AUTOINSTALL: '0', openin_any: 'p', openout_any: 'p' }, + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + }) + let log = '' + const collect = (chunk) => { + if (log.length < 200_000) log += chunk.toString('utf8') + } + child.stdout.on('data', collect) + child.stderr.on('data', collect) + const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs) + const abort = () => child.kill('SIGKILL') + if (signal) signal.addEventListener('abort', abort, { once: true }) + child.on('error', (error) => { + clearTimeout(timer) + resolve({ code: -1, log: 'pdflatex could not start: ' + String(error && error.message ? error.message : error) }) + }) + child.on('close', (code) => { + clearTimeout(timer) + if (signal) signal.removeEventListener('abort', abort) + resolve({ code, log }) + }) + }) +} + +/** + * The first thing wrong with a failed compile, in the compiler's own words. + * + * pdflatex prints a file:line: message with `-file-line-error`, and that line is + * worth more than the last forty: the model can find it in the fragment. + */ +export function compileError(log) { + const lines = String(log ?? '').split('\n') + const first = lines.find((line) => /^\.\/?table\.tex:\d+:/.test(line) || /^! /.test(line)) + if (first) return first.trim().slice(0, 300) + const missing = lines.find((line) => /File `[^']+' not found|LaTeX Error|Undefined control sequence/.test(line)) + return (missing ?? lines.filter((line) => line.trim().length > 0).slice(-3).join(' ')).trim().slice(0, 300) +} + +/** The TeX engine, or null. */ +export function probeEngine() { + return process.env.DSH_TABLES_ENGINE === undefined ? 'pdflatex' : String(process.env.DSH_TABLES_ENGINE) || null +} + + + + + + + + + + + + diff --git a/packages/dsh-tables/lib/spec.js b/packages/dsh-tables/lib/spec.js new file mode 100644 index 0000000..c408c7f --- /dev/null +++ b/packages/dsh-tables/lib/spec.js @@ -0,0 +1,313 @@ +/** + * dsh-tables — the table spec: parse, validate, resolve. + * + * A table in a paper is a GRID with a claim: grouped columns, a banded section, + * one bold winner per column, a footnote that says what the bold means. The spec + * says those things once; every emitter (LaTeX, Markdown, DOCX, CSV) is derived + * from the same resolved grid, so the four outputs cannot disagree about a number + * or about which cell is the best. + * + * The two things this module owns and no emitter may re-decide: + * + * - **the header spans** are DERIVED from `column.group`, never written by hand, + * because a hand-written `\multicolumn{6}` is the classic way a table silently + * loses a column when someone adds one; + * - **the emphasis** is computed per (column × row group), which is what the + * papers actually do: a 2B family and an 8B family are not compared to each + * other, so each block gets its own winner. + */ + +/** A number, or the fallback. */ +function num(value, fallback) { + return typeof value === 'number' && Number.isFinite(value) ? value : fallback +} + +/** One problem, shaped like every diagnostic in this pack. */ +function problem(kind, text) { + return { kind, text } +} + +/** Cell keys are ASCII so a column can be named in a CSV header and a LaTeX comment alike. */ +const KEY = /^[a-z][a-z0-9_-]{0,31}$/ + +/** The styles a spec may ask for. */ +export const STYLES = ['booktabs', 'grid'] + +/** The tone names a row group may carry, resolved by every emitter to a fill. */ +export const GROUP_TONES = ['meta', 'link', 'soft', 'none'] + +/** Digits a numeric column may claim. */ +const MAX_DIGITS = 6 + +/** + * Parse and normalise one table spec. + * + * @param source - the JSON text. + * @returns `{ spec, problems }`; a non-empty `problems` means nothing is built. + */ +export function parseTable(source) { + const text = String(source ?? '').trim() + if (text.length === 0) return { spec: null, problems: [problem('source', 'The table spec is empty. A spec is a JSON object with `columns` and `rows`.')] } + let raw + try { + raw = JSON.parse(text) + } catch (error) { + return { spec: null, problems: [problem('json', 'The spec is not valid JSON: ' + String(error.message) + '.')] } + } + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { spec: null, problems: [problem('json', 'The spec must be a JSON object.')] } + const problems = [] + const meta = raw.table && typeof raw.table === 'object' ? raw.table : {} + + const columnsRaw = Array.isArray(raw.columns) ? raw.columns : null + if (!columnsRaw || columnsRaw.length === 0) problems.push(problem('columns', 'The spec needs a non-empty `columns` array; each column is one field of every row.')) + const columns = [] + const seen = new Set() + for (const [index, column] of (columnsRaw ?? []).entries()) { + if (!column || typeof column !== 'object') { + problems.push(problem('columns', 'columns[' + index + '] is not an object.')) + continue + } + const key = String(column.key ?? '') + if (!KEY.test(key)) problems.push(problem('columns', 'columns[' + index + '].key "' + key + '" must match /^[a-z][a-z0-9_-]*$/.') ) + if (seen.has(key)) problems.push(problem('columns', 'columns[' + index + '].key "' + key + '" is used twice.')) + seen.add(key) + const align = column.align ?? 'left' + if (!['left', 'center', 'right'].includes(align)) problems.push(problem('columns', 'columns[' + index + '].align "' + align + '" is not left, center or right.')) + if (column.best !== undefined && !['max', 'min'].includes(column.best)) problems.push(problem('columns', 'columns[' + index + '].best must be "max" or "min".')) + columns.push({ + key, + title: String(column.title ?? key), + group: column.group === undefined || column.group === null ? null : String(column.group), + align, + best: column.best ?? null, + digits: Math.max(0, Math.min(MAX_DIGITS, Math.round(num(column.digits, 0)))), + width: num(column.width, 0), + wrap: num(column.wrap, 0), + mono: column.mono === true, + }) + } + + const groupsRaw = Array.isArray(raw.groups) ? raw.groups : [] + const groups = groupsRaw.map((group, index) => { + const value = typeof group === 'string' ? { title: group } : group ?? {} + const tone = String(value.tone ?? 'soft') + if (!GROUP_TONES.includes(tone)) problems.push(problem('groups', 'groups[' + index + '].tone "' + tone + '" is not one of: ' + GROUP_TONES.join(', ') + '.')) + return { title: String(value.title ?? ''), tone, band: value.band === true } + }) + if (groups.length === 0) { + // Rows may still name a group when the spec wants bands without a heading. + const used = new Set((Array.isArray(raw.rows) ? raw.rows : []).map((row) => row && row.group).filter((value) => value !== undefined)) + for (const index of used) groups.push({ title: '', tone: 'soft', band: true }) + } + for (const [index, group] of groups.entries()) if (group.title.length === 0) groups[index] = { ...group, title: '' } + + // The header: a column that names a group joins the run of columns naming the + // same group. A run may appear only once, or the header cannot be drawn. + const runs = [] + let current = null + for (const column of columns) { + if (column.group === null) { + runs.push({ title: null, columns: [column.key] }) + continue + } + if (current && current.title === column.group) current.columns.push(column.key) + else { + current = { title: column.group, columns: [column.key] } + runs.push(current) + } + } + const titles = runs.filter((run) => run.title !== null).map((run) => run.title) + for (const title of new Set(titles)) { + if (titles.filter((value) => value === title).length > 1) problems.push(problem('columns', 'the header group "' + title + '" is split into two runs; a group must cover one contiguous block of columns.')) + } + // A grouped column before an ungrouped one would need a ragged header that no + // renderer handles the same way, so it is refused rather than approximated. + let sawGroup = false + for (const run of runs) { + if (run.title !== null) sawGroup = true + else if (sawGroup) { + problems.push(problem('columns', 'column "' + run.columns[0] + '" has no group but follows a grouped column; move the ungrouped columns to the left, or give them a group.')) + break + } + } + + const rowsRaw = Array.isArray(raw.rows) ? raw.rows : null + if (!rowsRaw || rowsRaw.length === 0) problems.push(problem('rows', 'The spec needs a non-empty `rows` array.')) + const rows = [] + for (const [index, row] of (rowsRaw ?? []).entries()) { + if (!row || typeof row !== 'object') { + problems.push(problem('rows', 'rows[' + index + '] is not an object.')) + continue + } + const cells = row.cells && typeof row.cells === 'object' ? row.cells : {} + for (const key of Object.keys(cells)) { + if (!seen.has(key)) problems.push(problem('rows', 'rows[' + index + '].cells names "' + key + '", which is not a column.')) + } + const group = row.group === undefined || row.group === null ? null : Math.round(num(row.group, -1)) + if (group !== null && (group < 0 || group >= Math.max(groups.length, 1))) problems.push(problem('rows', 'rows[' + index + '].group "' + String(row.group) + '" names no entry in `groups`.')) + const span = row.span && typeof row.span === 'object' ? row.span : null + const rowSpan = row.rowSpan && typeof row.rowSpan === 'object' ? row.rowSpan : null + rows.push({ + cells, + group, + emphasis: row.emphasis === 'total' ? 'total' : 'normal', + span, + rowSpan, + }) + } + + // Spans and row spans are checked against the grid they produce, because a span + // that runs past the last column is a silent lost column in every renderer. + for (const [index, row] of rows.entries()) { + if (row.span) { + const start = columns.findIndex((column) => column.key === Object.keys(row.span)[0]) + for (const [key, width] of Object.entries(row.span)) { + const at = columns.findIndex((column) => column.key === key) + if (at < 0) { + problems.push(problem('rows', 'rows[' + index + '].span names "' + key + '", which is not a column.')) + continue + } + if (at !== start) problems.push(problem('rows', 'rows[' + index + '].span must start at the first covered column, "' + String(Object.keys(row.span)[0]) + '".')) + const count = Math.round(num(width, 1)) + if (count < 1 || at + count > columns.length) problems.push(problem('rows', 'rows[' + index + '].span "' + key + '" covers ' + count + ' columns and runs past the table.')) + for (let offset = 1; offset < count; offset += 1) { + const covered = columns[at + offset] + if (covered && row.cells[covered.key] !== undefined) problems.push(problem('rows', 'rows[' + index + '].span covers "' + covered.key + '", but that cell also has a value; a spanned cell is one cell.')) + } + } + } + if (row.rowSpan) { + for (const [key, height] of Object.entries(row.rowSpan)) { + if (!seen.has(key)) problems.push(problem('rows', 'rows[' + index + '].rowSpan names "' + key + '", which is not a column.')) + const count = Math.round(num(height, 1)) + if (count < 1) problems.push(problem('rows', 'rows[' + index + '].rowSpan "' + key + '" must be at least 1.')) + for (let offset = 1; offset < count; offset += 1) { + const next = rows[index + offset] + if (!next) problems.push(problem('rows', 'rows[' + index + '].rowSpan "' + key + '" runs past the last row.')) + else if (next.cells[key] !== undefined) problems.push(problem('rows', 'rows[' + (index + offset) + '] also sets "' + key + '", so the row span above it cannot merge.')) + } + } + } + } + + if (problems.length > 0) return { spec: null, problems } + const table = { + id: typeof meta.id === 'string' ? meta.id : null, + caption: typeof meta.caption === 'string' ? meta.caption : null, + label: typeof meta.label === 'string' ? meta.label : null, + style: STYLES.includes(meta.style) ? meta.style : 'booktabs', + font: String(meta.font ?? 'serif') === 'sans' ? 'sans' : 'serif', + size: Math.max(5, Math.min(12, num(meta.size, 7))), + align: meta.align === 'left' ? 'left' : 'center', + notes: Array.isArray(meta.notes) ? meta.notes.map(String) : [], + width: num(meta.width, 0), + } + return { spec: { table, columns, groups, rows, header: { runs, multiRow: runs.some((run) => run.title !== null) } }, problems: [] } +} + +/** One cell's text, as the spec's value and the column's format decide. */ +export function cellText(column, value) { + if (value === null || value === undefined || value === '') return '--' + if (typeof value === 'number') return value.toFixed(column.digits) + return String(value) +} + +/** Whether a cell is numeric (and so eligible for the best-value mark). */ +function isNumeric(value) { + return typeof value === 'number' && Number.isFinite(value) +} + +/** + * Resolve the spec into the grid every emitter draws. + * + * @returns `{ columns, header, groups, rows, marks, columnCount }` where each row + * is `{ kind, group, emphasis, cells: [{ text, column, align, bold, span, rowSpan, fill }] }`. + */ +export function resolveTable(spec) { + const { columns, groups, rows, header } = spec + const marks = new Set() + // Best per (column × group): a 2B family and an 8B family are separate races. + for (const column of columns) { + if (!column.best) continue + const buckets = new Map() + for (const row of rows) { + const value = row.cells[column.key] + if (!isNumeric(value)) continue + const key = row.group === null ? 'all' : String(row.group) + if (!buckets.has(key)) buckets.set(key, []) + buckets.get(key).push(value) + } + for (const [key, values] of buckets) { + const winner = column.best === 'max' ? Math.max(...values) : Math.min(...values) + rows.forEach((row, index) => { + const rowKey = row.group === null ? 'all' : String(row.group) + if (rowKey === key && row.cells[column.key] === winner) marks.add(index + ':' + column.key) + }) + } + } + + const grid = rows.map((row, index) => { + const cells = [] + const coveredBySpan = new Set() + for (let columnIndex = 0; columnIndex < columns.length; columnIndex += 1) { + const column = columns[columnIndex] + if (coveredBySpan.has(columnIndex)) continue + if (row.span && row.span[column.key] !== undefined) { + const count = Math.round(num(row.span[column.key], 1)) + cells.push({ + text: cellText(column, row.cells[column.key]), + column, + align: 'center', + bold: row.emphasis === 'total' || marks.has(index + ':' + column.key), + span: count, + rowSpan: 1, + }) + for (let offset = 1; offset < count; offset += 1) coveredBySpan.add(columnIndex + offset) + continue + } + if (row.rowSpan && row.rowSpan[column.key] !== undefined) { + cells.push({ + text: cellText(column, row.cells[column.key]), + column, + align: column.align, + bold: row.emphasis === 'total' || marks.has(index + ':' + column.key), + span: 1, + rowSpan: Math.round(num(row.rowSpan[column.key], 1)), + }) + continue + } + // A row that continues a row span above it leaves this cell empty. + const continued = rows.slice(0, index).some((earlier, earlierIndex) => { + const height = earlier.rowSpan && earlier.rowSpan[column.key] + return height !== undefined && earlierIndex + Math.round(num(height, 1)) > index + }) + if (continued) { + cells.push({ skip: true }) + continue + } + cells.push({ + text: cellText(column, row.cells[column.key]), + column, + align: column.align, + bold: row.emphasis === 'total' || marks.has(index + ':' + column.key), + span: 1, + rowSpan: 1, + }) + } + return { kind: 'row', group: row.group, emphasis: row.emphasis, cells } + }) + + return { + columns, + header, + groups, + rows: grid, + marks, + columnCount: columns.length, + } +} + + + + + diff --git a/packages/dsh-tables/lib/text.js b/packages/dsh-tables/lib/text.js new file mode 100644 index 0000000..2c9b095 --- /dev/null +++ b/packages/dsh-tables/lib/text.js @@ -0,0 +1,117 @@ +/** + * dsh-tables — the formats that cannot span a cell, and say so. + * + * Markdown and CSV are where a paper table goes to be READ rather than printed: + * a README, a review, a diff. Neither has a merged cell, so this module takes the + * same resolved grid and flattens it in the one way that keeps every number where + * a reader expects it: + * + * - a **column span** puts the text in its first column and leaves the rest + * empty, which is how a person would type it; + * - a **row span** repeats the value in the rows below, because a CSV that + * leaves it blank loses the association entirely; + * - a **row group** becomes a full-width bold row, because that is the closest + * thing a Markdown table has to a band. + * + * The degradation is stated in the result, never hidden: a caller that asked for + * DOCX and got a flattened Markdown file should know why they differ. + */ + +/** Escape a cell for a Markdown table: a pipe would split it, a newline would end it. */ +function markdownCell(value) { + return String(value ?? '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ') +} + +/** The cells of one grid row, flattened to exactly `columnCount` cells. */ +function flatCells(spec, gridRow) { + const out = [] + for (const entry of gridRow.cells) { + if (entry.skip) continue + const text = entry.span > 1 || entry.rowSpan > 1 ? entry.text : entry.text + out.push({ text, bold: entry.bold, span: entry.span }) + for (let offset = 1; offset < entry.span; offset += 1) out.push({ text: '', bold: false, span: 1 }) + } + return out +} + +/** + * A GitHub-flavoured Markdown table. + * + * @param spec - the parsed spec. + * @param grid - the resolved grid. + * @returns the markdown, with a heading when the table has a caption. + */ +export function emitMarkdown(spec, grid) { + const lines = [] + if (spec.table.caption) lines.push('**' + spec.table.caption + '**', '') + const header = spec.columns.map((column) => markdownCell(column.title)) + lines.push('| ' + header.join(' | ') + ' |') + const rules = spec.columns.map((column) => (column.align === 'right' ? '---:' : column.align === 'center' ? ':---:' : ':---')) + lines.push('| ' + rules.join(' | ') + ' |') + + let previousGroup = null + spec.rows.forEach((row, index) => { + const group = row.group === null ? null : spec.groups[row.group] + if (group && group.title.length > 0 && row.group !== previousGroup) { + const cells = ['**' + '▼ ' + group.title + '**'] + while (cells.length < spec.columns.length) cells.push('') + lines.push('| ' + cells.join(' | ') + ' |') + previousGroup = row.group + } + const cells = flatCells(spec, grid.rows[index]).map((cell) => markdownCell(cell.bold ? '**' + cell.text + '**' : cell.text)) + lines.push('| ' + cells.join(' | ') + ' |') + }) + if (spec.table.notes.length > 0) { + lines.push('') + for (const note of spec.table.notes) lines.push('> ' + note) + } + return lines.join('\n') + '\n' +} + +/** The CSV field grammar: quote when the value contains a comma, a quote or a newline. */ +function csvField(value) { + const text = String(value ?? '') + return /[",\r\n]/.test(text) ? '"' + text.replace(/"/g, '""') + '"' : text +} + +/** + * The data as CSV, one row per spec row, one column per spec column. + * + * Group headings are NOT written: a CSV is data, and a heading row would be read + * as a record. The group is available in the spec. + */ +export function emitCsv(spec, grid) { + const lines = [spec.columns.map((column) => csvField(column.title)).join(',')] + let previousGroup = null + spec.rows.forEach((row, index) => { + // A row span repeats its value in the rows it covers, so the CSV is + // self-contained when it is opened somewhere the merge cannot exist. + const values = new Map() + let cursor = 0 + for (const entry of grid.rows[index].cells) { + if (entry.skip) continue + values.set(cursor, entry.text) + cursor += entry.span + } + const fields = [] + for (let columnIndex = 0; columnIndex < spec.columns.length; columnIndex += 1) { + if (values.has(columnIndex)) { + fields.push(csvField(values.get(columnIndex))) + continue + } + const key = spec.columns[columnIndex].key + let carried = '' + for (let earlier = index - 1; earlier >= 0; earlier -= 1) { + const height = spec.rows[earlier].rowSpan && spec.rows[earlier].rowSpan[key] + if (height !== undefined && earlier + Math.round(height) > index) { + carried = String(spec.rows[earlier].cells[key] ?? '') + break + } + } + fields.push(csvField(carried)) + } + previousGroup = row.group ?? previousGroup + lines.push(fields.join(',')) + }) + return lines.join('\n') + '\n' +} diff --git a/packages/dsh-tables/lib/zip.js b/packages/dsh-tables/lib/zip.js new file mode 100644 index 0000000..3e85c82 --- /dev/null +++ b/packages/dsh-tables/lib/zip.js @@ -0,0 +1,159 @@ +/** + * dsh-tables — the ZIP container for a `.docx`, hand-written. + * + * A `.docx` is an OPC package, which is a ZIP, and this package ships no + * dependency, so the container is forty lines of little-endian fields around + * `zlib.deflateRawSync`. Duplicated from `dsh-research/lib/docx/zip.js` on + * purpose: bundles here do not import each other. + * + * The four rules that decide whether Word opens the file: + * + * 1. the CRC-32 is right, or Word says "corrupt" with no clue; + * 2. the timestamp is FIXED (the DOS epoch), so two builds are byte-identical; + * 3. the entry order is sorted by name, so the directory cannot move; + * 4. an entry claims no feature it does not use - no ZIP64, no data descriptor. + */ +import { deflateRawSync, inflateRawSync } from 'node:zlib' + +const DOS_TIME = 0 +const DOS_DATE = 0x0021 +const METHOD_DEFLATE = 8 +const LOCAL_SIGNATURE = 0x04034b50 +const CENTRAL_SIGNATURE = 0x02014b50 +const END_SIGNATURE = 0x06054b50 +const UTF8_FLAG = 0x0800 + +const CRC_TABLE = (() => { + const table = new Uint32Array(256) + for (let index = 0; index < 256; index += 1) { + let value = index + for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1 + table[index] = value >>> 0 + } + return table +})() + +/** The CRC-32 of a buffer, as the ZIP format defines it. */ +export function crc32(buffer) { + const bytes = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer) + let crc = 0xffffffff + for (let index = 0; index < bytes.length; index += 1) crc = CRC_TABLE[(crc ^ bytes[index]) & 0xff] ^ (crc >>> 8) + return (crc ^ 0xffffffff) >>> 0 +} + +/** A ZIP name: forward slashes, no leading slash. */ +function entryName(name) { + return String(name).replace(/\\/g, '/').replace(/^\/+/, '') +} + +/** + * Pack entries into a ZIP. + * + * @param entries - a Map of name to Buffer/string, or an array of `[name, content]`. + * @returns the archive. + */ +export function packZip(entries) { + const pairs = [...(entries instanceof Map ? entries.entries() : entries ?? [])].map(([name, content]) => [ + entryName(name), + Buffer.isBuffer(content) ? content : Buffer.from(content ?? ''), + ]) + pairs.sort((left, right) => (left[0] < right[0] ? -1 : left[0] > right[0] ? 1 : 0)) + + const locals = [] + const centrals = [] + let offset = 0 + for (const [name, content] of pairs) { + const compressed = deflateRawSync(content, { level: 9 }) + const header = Buffer.alloc(30) + header.writeUInt32LE(LOCAL_SIGNATURE, 0) + header.writeUInt16LE(20, 4) + header.writeUInt16LE(UTF8_FLAG, 6) + header.writeUInt16LE(METHOD_DEFLATE, 8) + header.writeUInt16LE(DOS_TIME, 10) + header.writeUInt16LE(DOS_DATE, 12) + header.writeUInt32LE(crc32(content), 14) + header.writeUInt32LE(compressed.length, 18) + header.writeUInt32LE(content.length, 22) + header.writeUInt16LE(name.length, 26) + header.writeUInt16LE(0, 28) + locals.push(header, Buffer.from(name, 'utf8'), compressed) + + const central = Buffer.alloc(46) + central.writeUInt32LE(CENTRAL_SIGNATURE, 0) + central.writeUInt16LE(20, 4) + central.writeUInt16LE(20, 6) + central.writeUInt16LE(UTF8_FLAG, 8) + central.writeUInt16LE(METHOD_DEFLATE, 10) + central.writeUInt16LE(DOS_TIME, 12) + central.writeUInt16LE(DOS_DATE, 14) + central.writeUInt32LE(crc32(content), 16) + central.writeUInt32LE(compressed.length, 20) + central.writeUInt32LE(content.length, 24) + central.writeUInt16LE(name.length, 28) + central.writeUInt16LE(0, 30) + central.writeUInt16LE(0, 32) + central.writeUInt16LE(0, 34) + central.writeUInt16LE(0, 36) + central.writeUInt32LE(0, 38) + central.writeUInt32LE(offset, 42) + centrals.push(central, Buffer.from(name, 'utf8')) + + offset += header.length + name.length + compressed.length + } + + const directory = Buffer.concat(centrals) + const end = Buffer.alloc(22) + end.writeUInt32LE(END_SIGNATURE, 0) + end.writeUInt16LE(0, 4) + end.writeUInt16LE(0, 6) + end.writeUInt16LE(pairs.length, 8) + end.writeUInt16LE(pairs.length, 10) + end.writeUInt32LE(directory.length, 12) + end.writeUInt32LE(offset, 16) + end.writeUInt16LE(0, 20) + return Buffer.concat([...locals, directory, end]) +} + +/** + * Read a ZIP back into its parts, verifying every CRC. + * + * The check uses this, and so does `table_read` when it inspects a committed + * `.docx`: a package that does not read back is a document nobody can open. + */ +export function unpackZip(buffer) { + const archive = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer ?? []) + let end = -1 + for (let index = archive.length - 22; index >= Math.max(0, archive.length - 65557); index -= 1) { + if (archive.readUInt32LE(index) === END_SIGNATURE) { + end = index + break + } + } + if (end === -1) throw new Error('not a ZIP: no end-of-central-directory record') + const count = archive.readUInt16LE(end + 10) + let cursor = archive.readUInt32LE(end + 16) + const files = new Map() + for (let index = 0; index < count; index += 1) { + if (archive.readUInt32LE(cursor) !== CENTRAL_SIGNATURE) throw new Error('not a ZIP: entry ' + index + ' has no central header') + const method = archive.readUInt16LE(cursor + 10) + const crc = archive.readUInt32LE(cursor + 16) + const compressedSize = archive.readUInt32LE(cursor + 20) + const size = archive.readUInt32LE(cursor + 24) + const nameLength = archive.readUInt16LE(cursor + 28) + const extraLength = archive.readUInt16LE(cursor + 30) + const commentLength = archive.readUInt16LE(cursor + 32) + const localOffset = archive.readUInt32LE(cursor + 42) + const name = archive.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8') + const localNameLength = archive.readUInt16LE(localOffset + 26) + const localExtraLength = archive.readUInt16LE(localOffset + 28) + const start = localOffset + 30 + localNameLength + localExtraLength + const raw = archive.subarray(start, start + compressedSize) + const bytes = method === 0 ? Buffer.from(raw) : method === METHOD_DEFLATE ? inflateRawSync(raw) : null + if (bytes === null) throw new Error('this ZIP uses compression method ' + method + ': ' + name) + if (bytes.length !== size) throw new Error('ZIP entry ' + name + ' is ' + bytes.length + ' bytes, its directory says ' + size) + if (crc32(bytes) !== crc) throw new Error('ZIP entry ' + name + ' fails its CRC-32') + files.set(name, bytes) + cursor += 46 + nameLength + extraLength + commentLength + } + return files +} diff --git a/packages/dsh-tables/package.json b/packages/dsh-tables/package.json new file mode 100644 index 0000000..f2d9967 --- /dev/null +++ b/packages/dsh-tables/package.json @@ -0,0 +1,27 @@ +{ + "name": "dsh-tables", + "version": "0.1.0-alpha.1", + "description": "Tables a paper can print: a JSON spec (grouped headers, row spans, column spans, bands, best-value emphasis) compiled to LaTeX (booktabs), Markdown, DOCX and CSV, plus a PNG of the LaTeX actually setting. Two tools, host-only, zero dependencies, no TeX package installed on demand.", + "type": "module", + "main": "lib/index.js", + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "files": [ + "lib", + "skills", + "checks", + "reference", + "cordis.patch.yml" + ], + "scripts": { + "check": "node checks/check-tables-node.mjs" + }, + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "license": "AGPL-3.0-only" +} diff --git a/packages/dsh-tables/reference/README.md b/packages/dsh-tables/reference/README.md new file mode 100644 index 0000000..5ba5b48 --- /dev/null +++ b/packages/dsh-tables/reference/README.md @@ -0,0 +1,28 @@ +# Reference tables + +Three published tables, rebuilt from their structure, as the acceptance test for +`dsh-tables`. The same shape as the figure corpus in `dsh-diagrams`: a target, a +prose decomposition, the spec, the built artifacts and an executable rubric. + +``` +reference/ + README.md + THIRD-PARTY.md provenance, licence and sha256 of every target + targets/ the published originals + tables// + SOURCE.md where it came from and what our rebuild changes + anatomy.md the decomposition: grid, spans, bands, emphasis + spec.json OUR rebuild + rubric.json the acceptance checks, one line each + out/ table.tex, table.md, table.csv, table.docx, table.png +``` + +Run the corpus: + +```sh +node packages/dsh-tables/checks/check-tables-node.mjs +``` + +Each table is built, compiled with `pdflatex`, re-read from its DOCX package, and +compared against its rubric. A machine with no TeX engine still runs every +structural check and says which rung it stopped at. diff --git a/packages/dsh-tables/reference/THIRD-PARTY.md b/packages/dsh-tables/reference/THIRD-PARTY.md new file mode 100644 index 0000000..e9d4a53 --- /dev/null +++ b/packages/dsh-tables/reference/THIRD-PARTY.md @@ -0,0 +1,26 @@ +# Third-party targets + +The files under `targets/` are **evaluation targets**: published tables this +package's compiler is measured against. They are not content this repository +distributes and they are not relicensed by it. + +| file | work | rights | sha256 | +|---|---|---|---| +| `vqa-results.png` | Single-image benchmark table, *From Pixels to Words — Towards Native Vision-Language Primitives at Scale*, Diao et al., arXiv:2510.14979v2 (ICLR 2026). | © the authors; arXiv **non-exclusive distribution** licence. Committed as an evaluation target; removed on request. | `2d84562f1fb2a4063ccbe024a415468fb1a3ee1bc6b8895e0a173b8865aa150c` | +| `dataset-summary.png` | Table 4 (dataset summary), same paper. | as above | `3aca42df0c0623dcbc3fd95150aa8061a0a6bc5bc148e771bc2207898d758897` | +| `implementation-details.png` | Table 5 (implementation details), same paper. | as above | `fdecf14e498d6ca0d3b80aa954012a7c380d904ac812719cff6825bc16377820` | + +## Removal + +Deleting a file from `targets/` breaks nothing: the corpus check drops to its +structural tier and reports which table lost its target. + +```sh +git rm packages/dsh-tables/reference/targets/dataset-summary.png +``` + +## What is ours + +`anatomy.md`, `spec.json`, `rubric.json` and `out/` are this repository's own +work (AGPL-3.0-only). The rebuild is a *description* of the target's structure - +the same numbers, the same grouping, the same emphasis - not a copy of its file. diff --git a/packages/dsh-tables/reference/tables/dataset-summary/SOURCE.md b/packages/dsh-tables/reference/tables/dataset-summary/SOURCE.md new file mode 100644 index 0000000..13d2dbd --- /dev/null +++ b/packages/dsh-tables/reference/tables/dataset-summary/SOURCE.md @@ -0,0 +1,22 @@ +# Dataset summary — provenance + +| | | +|---|---| +| target | `../../targets/dataset-summary.png` | +| sha256 | `3aca42df0c0623dcbc3fd95150aa8061a0a6bc5bc148e771bc2207898d758897` | +| origin | Table 4 of arXiv:2510.14979v2 (Diao et al., ICLR 2026). | +| rights | © the authors; arXiv non-exclusive distribution → tier 2. | + +## What it is evidence of + +That a table can be **one column of labels and one column of prose**, and still be +a table: the task cell merges down over the rows its datasets occupy, and the rows +alternate bands so the block boundaries survive a wide page. + +## What our rebuild changes + +The target wraps its dataset column to the paper's width. This host's `colortbl` +refuses paragraph columns, so the rebuild keeps one line per row and is wider; the +structure — merged task cells, bands, one dataset per line — is identical. The +vertical rule between the two columns is dropped: the house style is `booktabs`, +which has none. diff --git a/packages/dsh-tables/reference/tables/dataset-summary/anatomy.md b/packages/dsh-tables/reference/tables/dataset-summary/anatomy.md new file mode 100644 index 0000000..71c518d --- /dev/null +++ b/packages/dsh-tables/reference/tables/dataset-summary/anatomy.md @@ -0,0 +1,32 @@ +# Anatomy — dataset summary + +## The claim + +Supervised fine-tuning draws on ten task families, and the breadth is the point: +OCR alone needs four lines. + +## Structure + +| layer | what is drawn | +|---|---| +| header | `Task` and `Dataset` | +| block | a task label that spans the rows of its datasets | +| row | one line of datasets, with language and source | + +## Primitives + +- **row spans** — `rowSpan: { task: 2 }` on the first row of a block. The + following rows leave the cell empty; every emitter omits it and the renderer + draws the merge (LaTeX `\multirow[t]`, DOCX `vMerge`). +- **bands** — a group with `band: true` colours its data rows, alternating with + `tone: "none"`. The heading is empty, so the band IS the only separator. +- **no best marks** — nothing here is a race. + +## Typography + +7 pt, one line per dataset row, top-aligned merges. + +## What a rebuild must keep + +Ten task families, the merge height of each (1, 2, 1, 2, 2, 2, 4, 2, 3, 2), and the +alternating bands. Not the wrap width. diff --git a/packages/dsh-tables/reference/tables/dataset-summary/out/metrics.json b/packages/dsh-tables/reference/tables/dataset-summary/out/metrics.json new file mode 100644 index 0000000..00fe4eb --- /dev/null +++ b/packages/dsh-tables/reference/tables/dataset-summary/out/metrics.json @@ -0,0 +1,7 @@ +{ + "rung": "t4-drawn", + "columns": 2, + "rows": 21, + "marks": 0, + "pages": 1 +} diff --git a/packages/dsh-tables/reference/tables/dataset-summary/out/table.csv b/packages/dsh-tables/reference/tables/dataset-summary/out/table.csv new file mode 100644 index 0000000..0f7db4a --- /dev/null +++ b/packages/dsh-tables/reference/tables/dataset-summary/out/table.csv @@ -0,0 +1,22 @@ +Task,Dataset +Captioning,"TextCaps (en) (Sidorov et al., 2020), ShareGPT4V (en&zh) (Chen et al., 2024b)" +General QA,"VQAv2 (en) (Goyal et al., 2017), GQA (en) (Hudson & Manning, 2019), OKVQA (en) (Marino et al., 2019)," +"VSR (en) (Liu et al., 2023a), VisualDialog (en) (Das et al., 2017)", +Science,"AI2D (en) (Kembhavi et al., 2016), ScienceQA (en) (Lu et al., 2022a), TQA (en) (Kembhavi et al., 2017)" +Chart,"ChartQA (en) (Masry et al., 2022), MMC-Inst (Liu et al., 2023c), DVQA (en) (Kafle et al., 2018)," +"PlotQA (en) (Methani et al., 2020), LRV-Instruction (en) (Liu et al., 2023b)", +Mathematics,"GeoQA+ (en) (Cao & Xiao, 2022), TabMWP (en) (Lu et al., 2022b), MathQA (en) (Yu et al., 2023)," +"CLEVR-Math/Super (en) (Lindström & Abraham, 2022; Li et al., 2023c), Geometry3K (en) (Lu et al., 2021)", +Knowledge,"KVQA (en) (Shah et al., 2019), A-OKVQA (en) (Schwenk et al., 2022), ViQuAE (en) (Lerner et al., 2022)," +"Wikipedia (en&zh) (He et al., 2023)", +OCR,"OCR-VQA (en) (Mishra et al., 2019), InfoVQA (en) (Mathew et al., 2022), TextVQA (en) (Singh et al., 2019)," +"ArT (en&zh) (Chng et al., 2019), COCO-Text (en) (Veit et al., 2016), CTW (zh) (Yuan et al., 2019),", +"LSVT (zh) (Sun et al., 2019), RCTW-17 (zh) (Shi et al., 2017), ReCTs (zh) (Liu et al., 2019),", +"SynthDoG (en&zh) (Kim et al., 2022), ST-VQA (en) (Biten et al., 2019)", +Document Grounding,"DocVQA (en) (Clark & Gardner, 2018), InfographicsVQA (en) (Mathew et al., 2022)," +"RefCOCO/+/g (en) (Yu et al., 2016; Mao et al., 2016), Visual Genome (en) (Krishna et al., 2017)", +Conversation,"LLaVA-150K (en&zh) (Liu et al., 2023d), LVIS-Instruct4V (en) (Wang et al., 2023)," +"ALLaVA (en&zh) (Chen et al., 2024a), LLaVA-GPT4V (en) (LAION, 2023),", +"TextOCR-GPT4V (en) (Jimmmycarter, 2023), SVIT (en&zh) (Zhao et al., 2023)", +Text-only,"OpenHermes2.5 (en) (Teknium, 2023), Alpaca-GPT4 (en) (Taori et al., 2023), COIG-CQIA (zh) (Bai et al., 2024)," +"ShareGPT (en&zh) (Zheng et al., 2023)", diff --git a/packages/dsh-tables/reference/tables/dataset-summary/out/table.docx b/packages/dsh-tables/reference/tables/dataset-summary/out/table.docx new file mode 100644 index 0000000..629b31b Binary files /dev/null and b/packages/dsh-tables/reference/tables/dataset-summary/out/table.docx differ diff --git a/packages/dsh-tables/reference/tables/dataset-summary/out/table.md b/packages/dsh-tables/reference/tables/dataset-summary/out/table.md new file mode 100644 index 0000000..12f557e --- /dev/null +++ b/packages/dsh-tables/reference/tables/dataset-summary/out/table.md @@ -0,0 +1,27 @@ +**Dataset summary in the supervised fine-tuning stage.** + +| Task | Dataset | +| :--- | :--- | +| Captioning | TextCaps (en) (Sidorov et al., 2020), ShareGPT4V (en&zh) (Chen et al., 2024b) | +| General QA | VQAv2 (en) (Goyal et al., 2017), GQA (en) (Hudson & Manning, 2019), OKVQA (en) (Marino et al., 2019), | +| VSR (en) (Liu et al., 2023a), VisualDialog (en) (Das et al., 2017) | +| Science | AI2D (en) (Kembhavi et al., 2016), ScienceQA (en) (Lu et al., 2022a), TQA (en) (Kembhavi et al., 2017) | +| Chart | ChartQA (en) (Masry et al., 2022), MMC-Inst (Liu et al., 2023c), DVQA (en) (Kafle et al., 2018), | +| PlotQA (en) (Methani et al., 2020), LRV-Instruction (en) (Liu et al., 2023b) | +| Mathematics | GeoQA+ (en) (Cao & Xiao, 2022), TabMWP (en) (Lu et al., 2022b), MathQA (en) (Yu et al., 2023), | +| CLEVR-Math/Super (en) (Lindström & Abraham, 2022; Li et al., 2023c), Geometry3K (en) (Lu et al., 2021) | +| Knowledge | KVQA (en) (Shah et al., 2019), A-OKVQA (en) (Schwenk et al., 2022), ViQuAE (en) (Lerner et al., 2022), | +| Wikipedia (en&zh) (He et al., 2023) | +| OCR | OCR-VQA (en) (Mishra et al., 2019), InfoVQA (en) (Mathew et al., 2022), TextVQA (en) (Singh et al., 2019), | +| ArT (en&zh) (Chng et al., 2019), COCO-Text (en) (Veit et al., 2016), CTW (zh) (Yuan et al., 2019), | +| LSVT (zh) (Sun et al., 2019), RCTW-17 (zh) (Shi et al., 2017), ReCTs (zh) (Liu et al., 2019), | +| SynthDoG (en&zh) (Kim et al., 2022), ST-VQA (en) (Biten et al., 2019) | +| Document Grounding | DocVQA (en) (Clark & Gardner, 2018), InfographicsVQA (en) (Mathew et al., 2022), | +| RefCOCO/+/g (en) (Yu et al., 2016; Mao et al., 2016), Visual Genome (en) (Krishna et al., 2017) | +| Conversation | LLaVA-150K (en&zh) (Liu et al., 2023d), LVIS-Instruct4V (en) (Wang et al., 2023), | +| ALLaVA (en&zh) (Chen et al., 2024a), LLaVA-GPT4V (en) (LAION, 2023), | +| TextOCR-GPT4V (en) (Jimmmycarter, 2023), SVIT (en&zh) (Zhao et al., 2023) | +| Text-only | OpenHermes2.5 (en) (Teknium, 2023), Alpaca-GPT4 (en) (Taori et al., 2023), COIG-CQIA (zh) (Bai et al., 2024), | +| ShareGPT (en&zh) (Zheng et al., 2023) | + +> Every dataset is listed with the language(s) it covers and its source. diff --git a/packages/dsh-tables/reference/tables/dataset-summary/out/table.pdf b/packages/dsh-tables/reference/tables/dataset-summary/out/table.pdf new file mode 100644 index 0000000..b72ed79 Binary files /dev/null and b/packages/dsh-tables/reference/tables/dataset-summary/out/table.pdf differ diff --git a/packages/dsh-tables/reference/tables/dataset-summary/out/table.png b/packages/dsh-tables/reference/tables/dataset-summary/out/table.png new file mode 100644 index 0000000..dcbfab4 Binary files /dev/null and b/packages/dsh-tables/reference/tables/dataset-summary/out/table.png differ diff --git a/packages/dsh-tables/reference/tables/dataset-summary/out/table.tex b/packages/dsh-tables/reference/tables/dataset-summary/out/table.tex new file mode 100644 index 0000000..22a37d2 --- /dev/null +++ b/packages/dsh-tables/reference/tables/dataset-summary/out/table.tex @@ -0,0 +1,39 @@ +\begin{table}[t] +\centering +\caption{Dataset summary in the supervised fine-tuning stage.} +\label{tab:datasets} +\footnotesize +\setlength{\tabcolsep}{4pt} +\renewcommand{\arraystretch}{1.06} +\begin{tabular}{@{}ll@{}} +\toprule +Task & Dataset \\ +\midrule +\cellcolor[HTML]{F1F3F6}Captioning & \cellcolor[HTML]{F1F3F6}TextCaps (en) (Sidorov et al., 2020), ShareGPT4V (en\&zh) (Chen et al., 2024b) \\ +\multirow[t]{2}{*}{\cellcolor[HTML]{F1F3F6}General QA} & \cellcolor[HTML]{F1F3F6}VQAv2 (en) (Goyal et al., 2017), GQA (en) (Hudson \& Manning, 2019), OKVQA (en) (Marino et al., 2019), \\ +\cellcolor[HTML]{F1F3F6}VSR (en) (Liu et al., 2023a), VisualDialog (en) (Das et al., 2017) \\ +\cellcolor[HTML]{F1F3F6}Science & \cellcolor[HTML]{F1F3F6}AI2D (en) (Kembhavi et al., 2016), ScienceQA (en) (Lu et al., 2022a), TQA (en) (Kembhavi et al., 2017) \\ +\multirow[t]{2}{*}{\cellcolor[HTML]{F1F3F6}Chart} & \cellcolor[HTML]{F1F3F6}ChartQA (en) (Masry et al., 2022), MMC-Inst (Liu et al., 2023c), DVQA (en) (Kafle et al., 2018), \\ +\cellcolor[HTML]{F1F3F6}PlotQA (en) (Methani et al., 2020), LRV-Instruction (en) (Liu et al., 2023b) \\ +\multirow[t]{2}{*}{\cellcolor[HTML]{F1F3F6}Mathematics} & \cellcolor[HTML]{F1F3F6}GeoQA+ (en) (Cao \& Xiao, 2022), TabMWP (en) (Lu et al., 2022b), MathQA (en) (Yu et al., 2023), \\ +\cellcolor[HTML]{F1F3F6}CLEVR-Math/Super (en) (Lindström \& Abraham, 2022; Li et al., 2023c), Geometry3K (en) (Lu et al., 2021) \\ +\multirow[t]{2}{*}{\cellcolor[HTML]{F1F3F6}Knowledge} & \cellcolor[HTML]{F1F3F6}KVQA (en) (Shah et al., 2019), A-OKVQA (en) (Schwenk et al., 2022), ViQuAE (en) (Lerner et al., 2022), \\ +\cellcolor[HTML]{F1F3F6}Wikipedia (en\&zh) (He et al., 2023) \\ +\multirow[t]{4}{*}{\cellcolor[HTML]{F1F3F6}OCR} & \cellcolor[HTML]{F1F3F6}OCR-VQA (en) (Mishra et al., 2019), InfoVQA (en) (Mathew et al., 2022), TextVQA (en) (Singh et al., 2019), \\ +\cellcolor[HTML]{F1F3F6}ArT (en\&zh) (Chng et al., 2019), COCO-Text (en) (Veit et al., 2016), CTW (zh) (Yuan et al., 2019), \\ +\cellcolor[HTML]{F1F3F6}LSVT (zh) (Sun et al., 2019), RCTW-17 (zh) (Shi et al., 2017), ReCTs (zh) (Liu et al., 2019), \\ +\cellcolor[HTML]{F1F3F6}SynthDoG (en\&zh) (Kim et al., 2022), ST-VQA (en) (Biten et al., 2019) \\ +\multirow[t]{2}{*}{\cellcolor[HTML]{F1F3F6}Document Grounding} & \cellcolor[HTML]{F1F3F6}DocVQA (en) (Clark \& Gardner, 2018), InfographicsVQA (en) (Mathew et al., 2022), \\ +\cellcolor[HTML]{F1F3F6}RefCOCO/+/g (en) (Yu et al., 2016; Mao et al., 2016), Visual Genome (en) (Krishna et al., 2017) \\ +\multirow[t]{3}{*}{\cellcolor[HTML]{F1F3F6}Conversation} & \cellcolor[HTML]{F1F3F6}LLaVA-150K (en\&zh) (Liu et al., 2023d), LVIS-Instruct4V (en) (Wang et al., 2023), \\ +\cellcolor[HTML]{F1F3F6}ALLaVA (en\&zh) (Chen et al., 2024a), LLaVA-GPT4V (en) (LAION, 2023), \\ +\cellcolor[HTML]{F1F3F6}TextOCR-GPT4V (en) (Jimmmycarter, 2023), SVIT (en\&zh) (Zhao et al., 2023) \\ +\multirow[t]{2}{*}{\cellcolor[HTML]{F1F3F6}Text-only} & \cellcolor[HTML]{F1F3F6}OpenHermes2.5 (en) (Teknium, 2023), Alpaca-GPT4 (en) (Taori et al., 2023), COIG-CQIA (zh) (Bai et al., 2024), \\ +\cellcolor[HTML]{F1F3F6}ShareGPT (en\&zh) (Zheng et al., 2023) \\ +\bottomrule +\end{tabular} +\par\smallskip +{\footnotesize +Every dataset is listed with the language(s) it covers and its source.\par +} +\end{table} diff --git a/packages/dsh-tables/reference/tables/dataset-summary/rubric.json b/packages/dsh-tables/reference/tables/dataset-summary/rubric.json new file mode 100644 index 0000000..4e6ec86 --- /dev/null +++ b/packages/dsh-tables/reference/tables/dataset-summary/rubric.json @@ -0,0 +1,42 @@ +{ + "version": 1, + "table": "dataset-summary", + "claim": "Supervised fine-tuning spans ten task families, and the block structure is what makes the breadth readable.", + "target": "targets/dataset-summary.png", + "targetSha256": "3aca42df0c0623dcbc3fd95150aa8061a0a6bc5bc148e771bc2207898d758897", + "checks": [ + { + "id": "grid", + "kind": "structure", + "text": "Two columns, twenty-one rows.", + "expect": { "columns": 2, "rows": 21 } + }, + { + "id": "merges", + "kind": "structure", + "text": "The task cells merge down over their blocks, in the LaTeX and in the DOCX.", + "expect": { + "texIncludes": ["\\multirow[t]{4}{*}{\\cellcolor[HTML]{F1F3F6}OCR}", "\\multirow[t]{3}{*}{\\cellcolor[HTML]{F1F3F6}Conversation}"], + "docxIncludes": ["w:vMerge"] + } + }, + { + "id": "bands", + "kind": "colour", + "text": "Blocks alternate a tinted band with no band.", + "expect": { "texIncludes": ["\\cellcolor[HTML]{F1F3F6}Captioning"] } + }, + { + "id": "families", + "kind": "content", + "text": "All ten task families are present.", + "expect": { "mdIncludes": ["Captioning", "Document Grounding", "Text-only"] } + }, + { + "id": "caption", + "kind": "print", + "text": "The caption states what the table is.", + "expect": { "mdIncludes": ["Dataset summary in the supervised fine-tuning stage"] } + } + ] +} diff --git a/packages/dsh-tables/reference/tables/dataset-summary/spec.json b/packages/dsh-tables/reference/tables/dataset-summary/spec.json new file mode 100644 index 0000000..f1a3457 --- /dev/null +++ b/packages/dsh-tables/reference/tables/dataset-summary/spec.json @@ -0,0 +1,246 @@ +{ + "table": { + "id": "dataset-summary", + "caption": "Dataset summary in the supervised fine-tuning stage.", + "label": "tab:datasets", + "style": "booktabs", + "size": 7, + "notes": [ + "Every dataset is listed with the language(s) it covers and its source." + ] + }, + "columns": [ + { + "key": "task", + "title": "Task", + "align": "left", + "width": 1 + }, + { + "key": "dataset", + "title": "Dataset", + "align": "left", + "width": 3.2 + } + ], + "groups": [ + { + "title": "", + "tone": "soft", + "band": true + }, + { + "title": "", + "tone": "none", + "band": true + }, + { + "title": "", + "tone": "soft", + "band": true + }, + { + "title": "", + "tone": "none", + "band": true + }, + { + "title": "", + "tone": "soft", + "band": true + }, + { + "title": "", + "tone": "none", + "band": true + }, + { + "title": "", + "tone": "soft", + "band": true + }, + { + "title": "", + "tone": "none", + "band": true + }, + { + "title": "", + "tone": "soft", + "band": true + }, + { + "title": "", + "tone": "none", + "band": true + } + ], + "rows": [ + { + "group": 0, + "cells": { + "dataset": "TextCaps (en) (Sidorov et al., 2020), ShareGPT4V (en&zh) (Chen et al., 2024b)", + "task": "Captioning" + }, + "rowSpan": { + "task": 1 + } + }, + { + "group": 1, + "cells": { + "dataset": "VQAv2 (en) (Goyal et al., 2017), GQA (en) (Hudson & Manning, 2019), OKVQA (en) (Marino et al., 2019),", + "task": "General QA" + }, + "rowSpan": { + "task": 2 + } + }, + { + "group": 1, + "cells": { + "dataset": "VSR (en) (Liu et al., 2023a), VisualDialog (en) (Das et al., 2017)" + } + }, + { + "group": 2, + "cells": { + "dataset": "AI2D (en) (Kembhavi et al., 2016), ScienceQA (en) (Lu et al., 2022a), TQA (en) (Kembhavi et al., 2017)", + "task": "Science" + }, + "rowSpan": { + "task": 1 + } + }, + { + "group": 3, + "cells": { + "dataset": "ChartQA (en) (Masry et al., 2022), MMC-Inst (Liu et al., 2023c), DVQA (en) (Kafle et al., 2018),", + "task": "Chart" + }, + "rowSpan": { + "task": 2 + } + }, + { + "group": 3, + "cells": { + "dataset": "PlotQA (en) (Methani et al., 2020), LRV-Instruction (en) (Liu et al., 2023b)" + } + }, + { + "group": 4, + "cells": { + "dataset": "GeoQA+ (en) (Cao & Xiao, 2022), TabMWP (en) (Lu et al., 2022b), MathQA (en) (Yu et al., 2023),", + "task": "Mathematics" + }, + "rowSpan": { + "task": 2 + } + }, + { + "group": 4, + "cells": { + "dataset": "CLEVR-Math/Super (en) (Lindström & Abraham, 2022; Li et al., 2023c), Geometry3K (en) (Lu et al., 2021)" + } + }, + { + "group": 5, + "cells": { + "dataset": "KVQA (en) (Shah et al., 2019), A-OKVQA (en) (Schwenk et al., 2022), ViQuAE (en) (Lerner et al., 2022),", + "task": "Knowledge" + }, + "rowSpan": { + "task": 2 + } + }, + { + "group": 5, + "cells": { + "dataset": "Wikipedia (en&zh) (He et al., 2023)" + } + }, + { + "group": 6, + "cells": { + "dataset": "OCR-VQA (en) (Mishra et al., 2019), InfoVQA (en) (Mathew et al., 2022), TextVQA (en) (Singh et al., 2019),", + "task": "OCR" + }, + "rowSpan": { + "task": 4 + } + }, + { + "group": 6, + "cells": { + "dataset": "ArT (en&zh) (Chng et al., 2019), COCO-Text (en) (Veit et al., 2016), CTW (zh) (Yuan et al., 2019)," + } + }, + { + "group": 6, + "cells": { + "dataset": "LSVT (zh) (Sun et al., 2019), RCTW-17 (zh) (Shi et al., 2017), ReCTs (zh) (Liu et al., 2019)," + } + }, + { + "group": 6, + "cells": { + "dataset": "SynthDoG (en&zh) (Kim et al., 2022), ST-VQA (en) (Biten et al., 2019)" + } + }, + { + "group": 7, + "cells": { + "dataset": "DocVQA (en) (Clark & Gardner, 2018), InfographicsVQA (en) (Mathew et al., 2022),", + "task": "Document Grounding" + }, + "rowSpan": { + "task": 2 + } + }, + { + "group": 7, + "cells": { + "dataset": "RefCOCO/+/g (en) (Yu et al., 2016; Mao et al., 2016), Visual Genome (en) (Krishna et al., 2017)" + } + }, + { + "group": 8, + "cells": { + "dataset": "LLaVA-150K (en&zh) (Liu et al., 2023d), LVIS-Instruct4V (en) (Wang et al., 2023),", + "task": "Conversation" + }, + "rowSpan": { + "task": 3 + } + }, + { + "group": 8, + "cells": { + "dataset": "ALLaVA (en&zh) (Chen et al., 2024a), LLaVA-GPT4V (en) (LAION, 2023)," + } + }, + { + "group": 8, + "cells": { + "dataset": "TextOCR-GPT4V (en) (Jimmmycarter, 2023), SVIT (en&zh) (Zhao et al., 2023)" + } + }, + { + "group": 9, + "cells": { + "dataset": "OpenHermes2.5 (en) (Teknium, 2023), Alpaca-GPT4 (en) (Taori et al., 2023), COIG-CQIA (zh) (Bai et al., 2024),", + "task": "Text-only" + }, + "rowSpan": { + "task": 2 + } + }, + { + "group": 9, + "cells": { + "dataset": "ShareGPT (en&zh) (Zheng et al., 2023)" + } + } + ] +} diff --git a/packages/dsh-tables/reference/tables/implementation-details/SOURCE.md b/packages/dsh-tables/reference/tables/implementation-details/SOURCE.md new file mode 100644 index 0000000..7b3da0a --- /dev/null +++ b/packages/dsh-tables/reference/tables/implementation-details/SOURCE.md @@ -0,0 +1,27 @@ +# Implementation details — provenance + +| | | +|---|---| +| target | `../../targets/implementation-details.png` | +| sha256 | `fdecf14e498d6ca0d3b80aa954012a7c380d904ac812719cff6825bc16377820` | +| origin | Table 5 of arXiv:2510.14979v2 (Diao et al., ICLR 2026). | +| rights | © the authors; arXiv non-exclusive distribution → tier 2. | + +## What it is evidence of + +That **three of the four columns are one fact** and **one row is three facts**: + +- `AdamW` and the optimizer hyper-parameters apply to all three stages, so the + cell spans the three period columns; +- `bfloat16` likewise; +- everything else is per-stage. + +It is also the only table in the corpus with **maths in cells** — `$256^2$`, +`$\beta_1$`, `$8e^{-4}$` — which is where every non-LaTeX renderer has to admit +what it cannot do. + +## What our rebuild changes + +Nothing structural. The maths is kept as LaTeX; the DOCX output says in its own +result that it degraded it to plain text, because Word has no LaTeX maths without +OMML. diff --git a/packages/dsh-tables/reference/tables/implementation-details/anatomy.md b/packages/dsh-tables/reference/tables/implementation-details/anatomy.md new file mode 100644 index 0000000..821a675 --- /dev/null +++ b/packages/dsh-tables/reference/tables/implementation-details/anatomy.md @@ -0,0 +1,32 @@ +# Anatomy — implementation details + +## The claim + +Three training stages, and the settings that differ between them are few. The +merged rows are the argument: the optimizer is not a per-stage decision. + +## Structure + +| layer | what is drawn | +|---|---| +| header | `Configuration` + the three stages | +| row | a setting and its value per stage | +| merged row | one value across the three stage columns | + +## Primitives + +- **column spans in the body** — `span: { pretrain: 3 }` on the `AdamW` row. The + validator refuses a span whose covered columns also carry a value, because a + spanned cell is one cell. +- **maths** — a cell that contains `$...$` is passed through; everything else is + escaped. `latexText` is the only place that decides this. +- **nulls** — an empty stage renders as a dash. + +## Typography + +7 pt, no vertical rules, merged rows centred across the three columns. + +## What a rebuild must keep + +The three merged rows (optimizer, hyper-parameters, precision), the maths, and the +dash where a stage has no value. diff --git a/packages/dsh-tables/reference/tables/implementation-details/out/metrics.json b/packages/dsh-tables/reference/tables/implementation-details/out/metrics.json new file mode 100644 index 0000000..991a8b8 --- /dev/null +++ b/packages/dsh-tables/reference/tables/implementation-details/out/metrics.json @@ -0,0 +1,7 @@ +{ + "rung": "t4-drawn", + "columns": 4, + "rows": 13, + "marks": 0, + "pages": 1 +} diff --git a/packages/dsh-tables/reference/tables/implementation-details/out/table.csv b/packages/dsh-tables/reference/tables/implementation-details/out/table.csv new file mode 100644 index 0000000..09e5e83 --- /dev/null +++ b/packages/dsh-tables/reference/tables/implementation-details/out/table.csv @@ -0,0 +1,14 @@ +Configuration,Pre-Training,Mid-Training,Supervised Fine-Tuning +Resolution,"$256^{2} - 1{,}024^{2}$","$256^{2} - 2{,}048^{2}$","$256^{2} - 2{,}048^{2}$" +Optimizer,AdamW,, +Optimizer hyperparameters,"$\beta_{1} = 0.9,\ \beta_{2} = 0.999,\ eps = 1e^{-8}$",, +Learning rate schedule,cosine with min lr,cosine with min lr,cosine decay +Peak learning rate,$8e^{-4}$,$4e^{-5}$,$5e^{-5}$ +Min learning rate ratio,0.05,0.1,-- +Weight decay,--,0.01,-- +Training steps,190k,50k,6k +Warm-up steps,2k,200,200 +Max sample length,"8,192","8,192","8,192" +Global batch size,"2,560","1,200",650 +Text-only ratio,0.3,0.3,-- +Numerical precision,bfloat16,, diff --git a/packages/dsh-tables/reference/tables/implementation-details/out/table.docx b/packages/dsh-tables/reference/tables/implementation-details/out/table.docx new file mode 100644 index 0000000..f98a0e9 Binary files /dev/null and b/packages/dsh-tables/reference/tables/implementation-details/out/table.docx differ diff --git a/packages/dsh-tables/reference/tables/implementation-details/out/table.md b/packages/dsh-tables/reference/tables/implementation-details/out/table.md new file mode 100644 index 0000000..3cb4e13 --- /dev/null +++ b/packages/dsh-tables/reference/tables/implementation-details/out/table.md @@ -0,0 +1,19 @@ +**Implementation details in the pre-training, mid-training and supervised fine-tuning stages.** + +| Configuration | Pre-Training | Mid-Training | Supervised Fine-Tuning | +| :--- | ---: | ---: | ---: | +| Resolution | $256^{2} - 1{,}024^{2}$ | $256^{2} - 2{,}048^{2}$ | $256^{2} - 2{,}048^{2}$ | +| Optimizer | AdamW | | | +| Optimizer hyperparameters | $\beta_{1} = 0.9,\ \beta_{2} = 0.999,\ eps = 1e^{-8}$ | | | +| Learning rate schedule | cosine with min lr | cosine with min lr | cosine decay | +| Peak learning rate | $8e^{-4}$ | $4e^{-5}$ | $5e^{-5}$ | +| Min learning rate ratio | 0.05 | 0.1 | -- | +| Weight decay | -- | 0.01 | -- | +| Training steps | 190k | 50k | 6k | +| Warm-up steps | 2k | 200 | 200 | +| Max sample length | 8,192 | 8,192 | 8,192 | +| Global batch size | 2,560 | 1,200 | 650 | +| Text-only ratio | 0.3 | 0.3 | -- | +| Numerical precision | bfloat16 | | | + +> A merged row applies to all three stages. diff --git a/packages/dsh-tables/reference/tables/implementation-details/out/table.pdf b/packages/dsh-tables/reference/tables/implementation-details/out/table.pdf new file mode 100644 index 0000000..6921241 Binary files /dev/null and b/packages/dsh-tables/reference/tables/implementation-details/out/table.pdf differ diff --git a/packages/dsh-tables/reference/tables/implementation-details/out/table.png b/packages/dsh-tables/reference/tables/implementation-details/out/table.png new file mode 100644 index 0000000..e409680 Binary files /dev/null and b/packages/dsh-tables/reference/tables/implementation-details/out/table.png differ diff --git a/packages/dsh-tables/reference/tables/implementation-details/out/table.tex b/packages/dsh-tables/reference/tables/implementation-details/out/table.tex new file mode 100644 index 0000000..b70a1a9 --- /dev/null +++ b/packages/dsh-tables/reference/tables/implementation-details/out/table.tex @@ -0,0 +1,31 @@ +\begin{table}[t] +\centering +\caption{Implementation details in the pre-training, mid-training and supervised fine-tuning stages.} +\label{tab:implementation} +\footnotesize +\setlength{\tabcolsep}{4pt} +\renewcommand{\arraystretch}{1.06} +\begin{tabular}{@{}lrrr@{}} +\toprule +Configuration & Pre-Training & Mid-Training & Supervised Fine-Tuning \\ +\midrule +Resolution & $256^{2} - 1{,}024^{2}$ & $256^{2} - 2{,}048^{2}$ & $256^{2} - 2{,}048^{2}$ \\ +Optimizer & \multicolumn{3}{c}{AdamW} \\ +Optimizer hyperparameters & \multicolumn{3}{c}{$\beta_{1} = 0.9,\ \beta_{2} = 0.999,\ eps = 1e^{-8}$} \\ +Learning rate schedule & cosine with min lr & cosine with min lr & cosine decay \\ +Peak learning rate & $8e^{-4}$ & $4e^{-5}$ & $5e^{-5}$ \\ +Min learning rate ratio & 0.05 & 0.1 & -- \\ +Weight decay & -- & 0.01 & -- \\ +Training steps & 190k & 50k & 6k \\ +Warm-up steps & 2k & 200 & 200 \\ +Max sample length & 8,192 & 8,192 & 8,192 \\ +Global batch size & 2,560 & 1,200 & 650 \\ +Text-only ratio & 0.3 & 0.3 & -- \\ +Numerical precision & \multicolumn{3}{c}{bfloat16} \\ +\bottomrule +\end{tabular} +\par\smallskip +{\footnotesize +A merged row applies to all three stages.\par +} +\end{table} diff --git a/packages/dsh-tables/reference/tables/implementation-details/rubric.json b/packages/dsh-tables/reference/tables/implementation-details/rubric.json new file mode 100644 index 0000000..fcbccd9 --- /dev/null +++ b/packages/dsh-tables/reference/tables/implementation-details/rubric.json @@ -0,0 +1,42 @@ +{ + "version": 1, + "table": "implementation-details", + "claim": "The optimizer and the numerical precision are not per-stage decisions; the merged rows say so.", + "target": "targets/implementation-details.png", + "targetSha256": "fdecf14e498d6ca0d3b80aa954012a7c380d904ac812719cff6825bc16377820", + "checks": [ + { + "id": "grid", + "kind": "structure", + "text": "Four columns, thirteen rows.", + "expect": { "columns": 4, "rows": 13 } + }, + { + "id": "spans", + "kind": "structure", + "text": "Three rows merge across the three stage columns.", + "expect": { + "texIncludes": ["\\multicolumn{3}{c}{AdamW}", "\\multicolumn{3}{c}{bfloat16}", "\\multicolumn{3}{c}{$\\beta_{1}"], + "docxIncludes": ["w:gridSpan"] + } + }, + { + "id": "maths", + "kind": "content", + "text": "The maths survives into the LaTeX.", + "expect": { "texIncludes": ["$256^{2} - 1{,}024^{2}$", "$\\beta_{1} = 0.9", "$8e^{-4}$"] } + }, + { + "id": "stages", + "kind": "content", + "text": "The three stages are named.", + "expect": { "mdIncludes": ["Pre-Training", "Mid-Training", "Supervised Fine-Tuning"] } + }, + { + "id": "caption", + "kind": "print", + "text": "The caption states what the table is.", + "expect": { "mdIncludes": ["Implementation details in the pre-training"] } + } + ] +} diff --git a/packages/dsh-tables/reference/tables/implementation-details/spec.json b/packages/dsh-tables/reference/tables/implementation-details/spec.json new file mode 100644 index 0000000..b182a53 --- /dev/null +++ b/packages/dsh-tables/reference/tables/implementation-details/spec.json @@ -0,0 +1,145 @@ +{ + "table": { + "id": "implementation-details", + "caption": "Implementation details in the pre-training, mid-training and supervised fine-tuning stages.", + "label": "tab:implementation", + "style": "booktabs", + "size": 7, + "notes": [ + "A merged row applies to all three stages." + ] + }, + "columns": [ + { + "key": "config", + "title": "Configuration", + "align": "left", + "width": 1.5 + }, + { + "key": "pretrain", + "title": "Pre-Training", + "align": "right" + }, + { + "key": "midtrain", + "title": "Mid-Training", + "align": "right" + }, + { + "key": "sft", + "title": "Supervised Fine-Tuning", + "align": "right" + } + ], + "groups": [], + "rows": [ + { + "cells": { + "config": "Resolution", + "pretrain": "$256^{2} - 1{,}024^{2}$", + "midtrain": "$256^{2} - 2{,}048^{2}$", + "sft": "$256^{2} - 2{,}048^{2}$" + } + }, + { + "cells": { + "config": "Optimizer", + "pretrain": "AdamW" + }, + "span": { + "pretrain": 3 + } + }, + { + "cells": { + "config": "Optimizer hyperparameters", + "pretrain": "$\\beta_{1} = 0.9,\\ \\beta_{2} = 0.999,\\ eps = 1e^{-8}$" + }, + "span": { + "pretrain": 3 + } + }, + { + "cells": { + "config": "Learning rate schedule", + "pretrain": "cosine with min lr", + "midtrain": "cosine with min lr", + "sft": "cosine decay" + } + }, + { + "cells": { + "config": "Peak learning rate", + "pretrain": "$8e^{-4}$", + "midtrain": "$4e^{-5}$", + "sft": "$5e^{-5}$" + } + }, + { + "cells": { + "config": "Min learning rate ratio", + "pretrain": "0.05", + "midtrain": "0.1", + "sft": null + } + }, + { + "cells": { + "config": "Weight decay", + "pretrain": null, + "midtrain": "0.01", + "sft": null + } + }, + { + "cells": { + "config": "Training steps", + "pretrain": "190k", + "midtrain": "50k", + "sft": "6k" + } + }, + { + "cells": { + "config": "Warm-up steps", + "pretrain": "2k", + "midtrain": "200", + "sft": "200" + } + }, + { + "cells": { + "config": "Max sample length", + "pretrain": "8,192", + "midtrain": "8,192", + "sft": "8,192" + } + }, + { + "cells": { + "config": "Global batch size", + "pretrain": "2,560", + "midtrain": "1,200", + "sft": "650" + } + }, + { + "cells": { + "config": "Text-only ratio", + "pretrain": "0.3", + "midtrain": "0.3", + "sft": null + } + }, + { + "cells": { + "config": "Numerical precision", + "pretrain": "bfloat16" + }, + "span": { + "pretrain": 3 + } + } + ] +} diff --git a/packages/dsh-tables/reference/tables/vqa-results/SOURCE.md b/packages/dsh-tables/reference/tables/vqa-results/SOURCE.md new file mode 100644 index 0000000..e442a17 --- /dev/null +++ b/packages/dsh-tables/reference/tables/vqa-results/SOURCE.md @@ -0,0 +1,29 @@ +# VQA results — provenance + +| | | +|---|---| +| target | `../../targets/vqa-results.png` | +| sha256 | `2d84562f1fb2a4063ccbe024a415468fb1a3ee1bc6b8895e0a173b8865aa150c` | +| origin | *From Pixels to Words — Towards Native Vision-Language Primitives at Scale*, Diao et al., [arXiv:2510.14979v2](https://arxiv.org/abs/2510.14979), ICLR 2026. | +| rights | © the authors; arXiv non-exclusive distribution → tier 2 (evaluation target, removed on request). | + +## What it is evidence of + +That a **results table** is four design decisions, not a grid of numbers: + +1. **Two header levels** — eleven benchmarks fall under two capabilities, and the + rule under each group (`\cmidrule`) is what makes the grouping visible. +2. **Families are bands.** Four blocks (modular/native × 2B/8B), each opened by a + tinted row that says which comparison the reader is now in. +3. **The winner is local.** Bold marks the best value *within a family*: a 2B + model is never compared with an 8B one, or every 8B row would win and say + nothing. +4. **A missing number is a dash**, never a zero. + +## What our rebuild changes + +Nothing structural. The glyph in the section headings is drawn by the emitter +rather than typed into the title, the dashes are generated from `null`, and the +bold marks are computed from `best: "max"` per column per group instead of being +applied by hand — 43 of them, which is exactly the thing a hand-made table gets +wrong on the next revision. diff --git a/packages/dsh-tables/reference/tables/vqa-results/anatomy.md b/packages/dsh-tables/reference/tables/vqa-results/anatomy.md new file mode 100644 index 0000000..a742142 --- /dev/null +++ b/packages/dsh-tables/reference/tables/vqa-results/anatomy.md @@ -0,0 +1,39 @@ +# Anatomy — VQA results + +## The claim + +Ten models, eleven benchmarks, two capabilities, two parameter scales. The reader +should leave knowing that NEO-ov is competitive with the modular family at the +same size, on both capabilities. + +## Structure + +| layer | what is drawn | +|---|---| +| header row 1 | `Model` (spans both rows) + the two capability groups | +| header row 2 | the eleven benchmark names | +| section row | a tinted, bold row naming the family | +| data row | model name, eleven numbers, a bold winner per column | + +## Primitives + +- **column groups** — `group: "General VQA Understanding"` on six columns and + `"OCR Recognition"` on five. The `\multicolumn` widths and the `\cmidrule` + spans are DERIVED from those two strings; no number is typed twice. +- **row groups** — four `groups`, each a band with its own tone (green for + modular, blue for native). +- **best marks** — `"best": "max"` on the eleven numeric columns, resolved per + (column × row group). +- **nulls** — `null` renders as an en dash in every format. +- **emphasis** — `"emphasis": "total"` on the NEO-ov row: the summary line is bold + across the whole row. + +## Typography + +7 pt body, `\footnotesize`, `\arraystretch` 1.14, no vertical rules, thick top and +bottom rules. + +## What a rebuild must keep + +The four families, the eleven columns in this order, the two header groups, and one +bold winner per column per family. Not the pixel widths. diff --git a/packages/dsh-tables/reference/tables/vqa-results/out/metrics.json b/packages/dsh-tables/reference/tables/vqa-results/out/metrics.json new file mode 100644 index 0000000..c3670c0 --- /dev/null +++ b/packages/dsh-tables/reference/tables/vqa-results/out/metrics.json @@ -0,0 +1,7 @@ +{ + "rung": "t4-drawn", + "columns": 12, + "rows": 23, + "marks": 43, + "pages": 1 +} diff --git a/packages/dsh-tables/reference/tables/vqa-results/out/table.csv b/packages/dsh-tables/reference/tables/vqa-results/out/table.csv new file mode 100644 index 0000000..9dbb66e --- /dev/null +++ b/packages/dsh-tables/reference/tables/vqa-results/out/table.csv @@ -0,0 +1,24 @@ +Model,MMMU,MMB,RWQA,MMStar,SEED-I,HallB,AI2D,DocVQA,ChartQA,TextVQA,OCRBench +Qwen2-VL,41.1,74.9,62.6,48.0,--,41.7,74.7,90.1,73.5,79.7,80.9 +InternVL3,48.6,81.1,64.3,60.7,--,42.5,78.7,88.3,80.2,77.0,83.5 +InternVL3.5,53.0,78.2,62.0,62.7,75.3,48.6,78.8,89.4,80.7,76.5,83.6 +Qwen3-VL,53.4,78.4,63.9,58.3,--,51.4,76.9,93.3,79.1,--,85.8 +Mono-VL,33.7,65.5,--,--,67.4,34.8,68.6,80.0,73.7,72.6,76.7 +Mono-VL1.5,39.1,64.0,--,--,66.9,32.5,67.4,81.7,72.2,73.7,80.1 +HoVLE,32.2,73.3,--,--,70.9,38.4,73.0,86.1,78.6,70.9,74.0 +OneCAT,39.0,72.4,--,--,70.9,--,72.4,87.1,76.2,67.0,-- +NEO,48.6,76.0,63.1,54.2,74.2,43.1,80.1,89.9,81.2,74.0,77.1 +NEO-ov,54.7,80.0,64.4,58.6,76.2,54.5,81.4,91.2,83.1,77.3,81.2 +Qwen2.5-VL,55.0,83.5,68.5,63.9,--,52.9,83.9,95.7,87.3,84.9,86.4 +InternVL3,62.7,83.4,70.8,68.2,--,49.9,85.2,92.7,86.6,80.2,88.0 +InternVL3.5,68.1,82.7,67.5,69.3,--,77.1,54.5,84.0,92.3,86.7,78.2 +Qwen3-VL,69.6,84.5,71.5,70.9,--,61.1,85.7,96.1,89.6,--,89.6 +Fuyu,27.9,10.7,43.7,--,59.3,--,64.5,--,--,--,36.6 +EVE,32.6,52.3,--,--,64.6,26.4,61.0,53.0,59.1,56.8,39.8 +SOLO,--,67.7,44.7,--,64.4,--,61.4,--,--,--,12.6 +EVEv2,39.3,66.3,62.4,--,71.4,--,74.8,--,73.9,71.1,70.2 +BREEN,42.7,71.4,--,51.2,--,37.0,76.4,--,--,65.7,-- +VoRA,32.0,61.3,60.1,--,68.9,--,61.1,--,--,58.7,-- +SAIL,--,70.1,63.9,53.1,72.9,54.2,76.7,--,--,77.1,78.3 +NEO,54.6,82.1,67.3,62.4,76.3,46.4,83.1,88.6,82.1,75.0,77.7 +NEO-ov,68.1,85.1,67.8,67.3,76.6,59.8,85.4,91.9,86.2,78.5,81.6 diff --git a/packages/dsh-tables/reference/tables/vqa-results/out/table.docx b/packages/dsh-tables/reference/tables/vqa-results/out/table.docx new file mode 100644 index 0000000..a7603ac Binary files /dev/null and b/packages/dsh-tables/reference/tables/vqa-results/out/table.docx differ diff --git a/packages/dsh-tables/reference/tables/vqa-results/out/table.md b/packages/dsh-tables/reference/tables/vqa-results/out/table.md new file mode 100644 index 0000000..ea11126 --- /dev/null +++ b/packages/dsh-tables/reference/tables/vqa-results/out/table.md @@ -0,0 +1,34 @@ +**Single-image performance on general VQA understanding and OCR recognition benchmarks. Bold marks the best value of each column within a family.** + +| Model | MMMU | MMB | RWQA | MMStar | SEED-I | HallB | AI2D | DocVQA | ChartQA | TextVQA | OCRBench | +| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| **▼ Modular Vision-Language Models (Instruct-2B)** | | | | | | | | | | | | +| Qwen2-VL | 41.1 | 74.9 | 62.6 | 48.0 | -- | 41.7 | 74.7 | 90.1 | 73.5 | **79.7** | 80.9 | +| InternVL3 | 48.6 | **81.1** | **64.3** | 60.7 | -- | 42.5 | 78.7 | 88.3 | 80.2 | 77.0 | 83.5 | +| InternVL3.5 | 53.0 | 78.2 | 62.0 | **62.7** | **75.3** | 48.6 | **78.8** | 89.4 | **80.7** | 76.5 | 83.6 | +| Qwen3-VL | **53.4** | 78.4 | 63.9 | 58.3 | -- | **51.4** | 76.9 | **93.3** | 79.1 | -- | **85.8** | +| **▼ Native Vision-Language Models (Instruct-2B)** | | | | | | | | | | | | +| Mono-VL | 33.7 | 65.5 | -- | -- | 67.4 | 34.8 | 68.6 | 80.0 | 73.7 | 72.6 | 76.7 | +| Mono-VL1.5 | 39.1 | 64.0 | -- | -- | 66.9 | 32.5 | 67.4 | 81.7 | 72.2 | 73.7 | 80.1 | +| HoVLE | 32.2 | 73.3 | -- | -- | 70.9 | 38.4 | 73.0 | 86.1 | 78.6 | 70.9 | 74.0 | +| OneCAT | 39.0 | 72.4 | -- | -- | 70.9 | -- | 72.4 | 87.1 | 76.2 | 67.0 | -- | +| NEO | 48.6 | 76.0 | 63.1 | 54.2 | 74.2 | 43.1 | 80.1 | 89.9 | 81.2 | 74.0 | 77.1 | +| **NEO-ov** | **54.7** | **80.0** | **64.4** | **58.6** | **76.2** | **54.5** | **81.4** | **91.2** | **83.1** | **77.3** | **81.2** | +| **▼ Modular Vision-Language Models (Instruct-8B)** | | | | | | | | | | | | +| Qwen2.5-VL | 55.0 | 83.5 | 68.5 | 63.9 | -- | 52.9 | 83.9 | 95.7 | 87.3 | 84.9 | 86.4 | +| InternVL3 | 62.7 | 83.4 | 70.8 | 68.2 | -- | 49.9 | 85.2 | 92.7 | 86.6 | 80.2 | 88.0 | +| InternVL3.5 | 68.1 | 82.7 | 67.5 | 69.3 | -- | **77.1** | 54.5 | 84.0 | **92.3** | **86.7** | 78.2 | +| Qwen3-VL | **69.6** | **84.5** | **71.5** | **70.9** | -- | 61.1 | **85.7** | **96.1** | 89.6 | -- | **89.6** | +| **▼ Native Vision-Language Models (Instruct-8B)** | | | | | | | | | | | | +| Fuyu | 27.9 | 10.7 | 43.7 | -- | 59.3 | -- | 64.5 | -- | -- | -- | 36.6 | +| EVE | 32.6 | 52.3 | -- | -- | 64.6 | 26.4 | 61.0 | 53.0 | 59.1 | 56.8 | 39.8 | +| SOLO | -- | 67.7 | 44.7 | -- | 64.4 | -- | 61.4 | -- | -- | -- | 12.6 | +| EVEv2 | 39.3 | 66.3 | 62.4 | -- | 71.4 | -- | 74.8 | -- | 73.9 | 71.1 | 70.2 | +| BREEN | 42.7 | 71.4 | -- | 51.2 | -- | 37.0 | 76.4 | -- | -- | 65.7 | -- | +| VoRA | 32.0 | 61.3 | 60.1 | -- | 68.9 | -- | 61.1 | -- | -- | 58.7 | -- | +| SAIL | -- | 70.1 | 63.9 | 53.1 | 72.9 | 54.2 | 76.7 | -- | -- | 77.1 | 78.3 | +| NEO | 54.6 | 82.1 | 67.3 | 62.4 | 76.3 | 46.4 | 83.1 | 88.6 | 82.1 | 75.0 | 77.7 | +| **NEO-ov** | **68.1** | **85.1** | **67.8** | **67.3** | **76.6** | **59.8** | **85.4** | **91.9** | **86.2** | **78.5** | **81.6** | + +> Bold marks the best value of each column within each model family. +> A dash is a benchmark the model does not report. diff --git a/packages/dsh-tables/reference/tables/vqa-results/out/table.pdf b/packages/dsh-tables/reference/tables/vqa-results/out/table.pdf new file mode 100644 index 0000000..fc4e86b Binary files /dev/null and b/packages/dsh-tables/reference/tables/vqa-results/out/table.pdf differ diff --git a/packages/dsh-tables/reference/tables/vqa-results/out/table.png b/packages/dsh-tables/reference/tables/vqa-results/out/table.png new file mode 100644 index 0000000..da74dd9 Binary files /dev/null and b/packages/dsh-tables/reference/tables/vqa-results/out/table.png differ diff --git a/packages/dsh-tables/reference/tables/vqa-results/out/table.tex b/packages/dsh-tables/reference/tables/vqa-results/out/table.tex new file mode 100644 index 0000000..f8f30ec --- /dev/null +++ b/packages/dsh-tables/reference/tables/vqa-results/out/table.tex @@ -0,0 +1,51 @@ +\begin{table}[t] +\centering +\caption{Single-image performance on general VQA understanding and OCR recognition benchmarks. Bold marks the best value of each column within a family.} +\label{tab:single-image} +\footnotesize +\setlength{\tabcolsep}{4pt} +\renewcommand{\arraystretch}{1.06} +\begin{tabular}{@{}lrrrrrrrrrrr@{}} +\toprule +\multicolumn{1}{@{}l}{\multirow{2}{*}{Model}} & \multicolumn{6}{c}{General VQA Understanding} & \multicolumn{5}{c}{OCR Recognition} \\ +\cmidrule(lr){2-7} \cmidrule(lr){8-12} + & MMMU & MMB & RWQA & MMStar & SEED-I & HallB & AI2D & DocVQA & ChartQA & TextVQA & OCRBench \\ +\midrule +\multicolumn{12}{@{}l}{\cellcolor[HTML]{EAF6EF}\textbf{$\blacktriangledown$ Modular Vision-Language Models (Instruct-2B)}} \\ +Qwen2-VL & 41.1 & 74.9 & 62.6 & 48.0 & -- & 41.7 & 74.7 & 90.1 & 73.5 & \textbf{79.7} & 80.9 \\ +InternVL3 & 48.6 & \textbf{81.1} & \textbf{64.3} & 60.7 & -- & 42.5 & 78.7 & 88.3 & 80.2 & 77.0 & 83.5 \\ +InternVL3.5 & 53.0 & 78.2 & 62.0 & \textbf{62.7} & \textbf{75.3} & 48.6 & \textbf{78.8} & 89.4 & \textbf{80.7} & 76.5 & 83.6 \\ +Qwen3-VL & \textbf{53.4} & 78.4 & 63.9 & 58.3 & -- & \textbf{51.4} & 76.9 & \textbf{93.3} & 79.1 & -- & \textbf{85.8} \\ +\midrule +\multicolumn{12}{@{}l}{\cellcolor[HTML]{EAF1FB}\textbf{$\blacktriangledown$ Native Vision-Language Models (Instruct-2B)}} \\ +Mono-VL & 33.7 & 65.5 & -- & -- & 67.4 & 34.8 & 68.6 & 80.0 & 73.7 & 72.6 & 76.7 \\ +Mono-VL1.5 & 39.1 & 64.0 & -- & -- & 66.9 & 32.5 & 67.4 & 81.7 & 72.2 & 73.7 & 80.1 \\ +HoVLE & 32.2 & 73.3 & -- & -- & 70.9 & 38.4 & 73.0 & 86.1 & 78.6 & 70.9 & 74.0 \\ +OneCAT & 39.0 & 72.4 & -- & -- & 70.9 & -- & 72.4 & 87.1 & 76.2 & 67.0 & -- \\ +NEO & 48.6 & 76.0 & 63.1 & 54.2 & 74.2 & 43.1 & 80.1 & 89.9 & 81.2 & 74.0 & 77.1 \\ +\cellcolor[HTML]{F2F4F7}\textbf{NEO-ov} & \cellcolor[HTML]{F2F4F7}\textbf{54.7} & \cellcolor[HTML]{F2F4F7}\textbf{80.0} & \cellcolor[HTML]{F2F4F7}\textbf{64.4} & \cellcolor[HTML]{F2F4F7}\textbf{58.6} & \cellcolor[HTML]{F2F4F7}\textbf{76.2} & \cellcolor[HTML]{F2F4F7}\textbf{54.5} & \cellcolor[HTML]{F2F4F7}\textbf{81.4} & \cellcolor[HTML]{F2F4F7}\textbf{91.2} & \cellcolor[HTML]{F2F4F7}\textbf{83.1} & \cellcolor[HTML]{F2F4F7}\textbf{77.3} & \cellcolor[HTML]{F2F4F7}\textbf{81.2} \\ +\midrule +\multicolumn{12}{@{}l}{\cellcolor[HTML]{EAF6EF}\textbf{$\blacktriangledown$ Modular Vision-Language Models (Instruct-8B)}} \\ +Qwen2.5-VL & 55.0 & 83.5 & 68.5 & 63.9 & -- & 52.9 & 83.9 & 95.7 & 87.3 & 84.9 & 86.4 \\ +InternVL3 & 62.7 & 83.4 & 70.8 & 68.2 & -- & 49.9 & 85.2 & 92.7 & 86.6 & 80.2 & 88.0 \\ +InternVL3.5 & 68.1 & 82.7 & 67.5 & 69.3 & -- & \textbf{77.1} & 54.5 & 84.0 & \textbf{92.3} & \textbf{86.7} & 78.2 \\ +Qwen3-VL & \textbf{69.6} & \textbf{84.5} & \textbf{71.5} & \textbf{70.9} & -- & 61.1 & \textbf{85.7} & \textbf{96.1} & 89.6 & -- & \textbf{89.6} \\ +\midrule +\multicolumn{12}{@{}l}{\cellcolor[HTML]{EAF1FB}\textbf{$\blacktriangledown$ Native Vision-Language Models (Instruct-8B)}} \\ +Fuyu & 27.9 & 10.7 & 43.7 & -- & 59.3 & -- & 64.5 & -- & -- & -- & 36.6 \\ +EVE & 32.6 & 52.3 & -- & -- & 64.6 & 26.4 & 61.0 & 53.0 & 59.1 & 56.8 & 39.8 \\ +SOLO & -- & 67.7 & 44.7 & -- & 64.4 & -- & 61.4 & -- & -- & -- & 12.6 \\ +EVEv2 & 39.3 & 66.3 & 62.4 & -- & 71.4 & -- & 74.8 & -- & 73.9 & 71.1 & 70.2 \\ +BREEN & 42.7 & 71.4 & -- & 51.2 & -- & 37.0 & 76.4 & -- & -- & 65.7 & -- \\ +VoRA & 32.0 & 61.3 & 60.1 & -- & 68.9 & -- & 61.1 & -- & -- & 58.7 & -- \\ +SAIL & -- & 70.1 & 63.9 & 53.1 & 72.9 & 54.2 & 76.7 & -- & -- & 77.1 & 78.3 \\ +NEO & 54.6 & 82.1 & 67.3 & 62.4 & 76.3 & 46.4 & 83.1 & 88.6 & 82.1 & 75.0 & 77.7 \\ +\cellcolor[HTML]{F2F4F7}\textbf{NEO-ov} & \cellcolor[HTML]{F2F4F7}\textbf{68.1} & \cellcolor[HTML]{F2F4F7}\textbf{85.1} & \cellcolor[HTML]{F2F4F7}\textbf{67.8} & \cellcolor[HTML]{F2F4F7}\textbf{67.3} & \cellcolor[HTML]{F2F4F7}\textbf{76.6} & \cellcolor[HTML]{F2F4F7}\textbf{59.8} & \cellcolor[HTML]{F2F4F7}\textbf{85.4} & \cellcolor[HTML]{F2F4F7}\textbf{91.9} & \cellcolor[HTML]{F2F4F7}\textbf{86.2} & \cellcolor[HTML]{F2F4F7}\textbf{78.5} & \cellcolor[HTML]{F2F4F7}\textbf{81.6} \\ +\bottomrule +\end{tabular} +\par\smallskip +{\footnotesize +Bold marks the best value of each column within each model family.\par +A dash is a benchmark the model does not report.\par +} +\end{table} diff --git a/packages/dsh-tables/reference/tables/vqa-results/rubric.json b/packages/dsh-tables/reference/tables/vqa-results/rubric.json new file mode 100644 index 0000000..d6bdb7d --- /dev/null +++ b/packages/dsh-tables/reference/tables/vqa-results/rubric.json @@ -0,0 +1,50 @@ +{ + "version": 1, + "table": "vqa-results", + "claim": "NEO-ov is competitive with the modular family at the same parameter scale, on both general VQA and OCR benchmarks.", + "target": "targets/vqa-results.png", + "targetSha256": "2d84562f1fb2a4063ccbe024a415468fb1a3ee1bc6b8895e0a173b8865aa150c", + "checks": [ + { + "id": "grid", + "kind": "structure", + "text": "Twelve columns, twenty-three rows.", + "expect": { "columns": 12, "rows": 23 } + }, + { + "id": "families", + "kind": "structure", + "text": "Four family bands, each opened by its own heading row.", + "expect": { + "groups": 4, + "texIncludes": ["Modular Vision-Language Models (Instruct-2B)", "Native Vision-Language Models (Instruct-8B)"] + } + }, + { + "id": "header-groups", + "kind": "structure", + "text": "The eleven benchmarks sit under the two capabilities, and the header rule spans each group.", + "expect": { + "texIncludes": ["General VQA Understanding", "OCR Recognition", "\\cmidrule"] + } + }, + { + "id": "winners", + "kind": "data", + "text": "The best value of each column is marked inside each family.", + "expect": { "marks": 43 } + }, + { + "id": "missing", + "kind": "data", + "text": "A benchmark a model does not report is a dash, not a zero.", + "expect": { "mdIncludes": ["| -- |"] } + }, + { + "id": "caption", + "kind": "print", + "text": "The caption states the claim and the notes say what the bold means.", + "expect": { "mdIncludes": ["Single-image performance", "Bold marks the best value"] } + } + ] +} diff --git a/packages/dsh-tables/reference/tables/vqa-results/spec.json b/packages/dsh-tables/reference/tables/vqa-results/spec.json new file mode 100644 index 0000000..fda0bcb --- /dev/null +++ b/packages/dsh-tables/reference/tables/vqa-results/spec.json @@ -0,0 +1,522 @@ +{ + "table": { + "id": "vqa-results", + "caption": "Single-image performance on general VQA understanding and OCR recognition benchmarks. Bold marks the best value of each column within a family.", + "label": "tab:single-image", + "style": "booktabs", + "size": 7, + "notes": [ + "Bold marks the best value of each column within each model family.", + "A dash is a benchmark the model does not report." + ] + }, + "columns": [ + { + "key": "model", + "title": "Model", + "align": "left", + "width": 1.7 + }, + { + "key": "mmmu", + "title": "MMMU", + "group": "General VQA Understanding", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "mmb", + "title": "MMB", + "group": "General VQA Understanding", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "rwqa", + "title": "RWQA", + "group": "General VQA Understanding", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "mmstar", + "title": "MMStar", + "group": "General VQA Understanding", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "seedi", + "title": "SEED-I", + "group": "General VQA Understanding", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "hallb", + "title": "HallB", + "group": "General VQA Understanding", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "ai2d", + "title": "AI2D", + "group": "OCR Recognition", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "docvqa", + "title": "DocVQA", + "group": "OCR Recognition", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "chartqa", + "title": "ChartQA", + "group": "OCR Recognition", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "textvqa", + "title": "TextVQA", + "group": "OCR Recognition", + "align": "right", + "best": "max", + "digits": 1 + }, + { + "key": "ocrbench", + "title": "OCRBench", + "group": "OCR Recognition", + "align": "right", + "best": "max", + "digits": 1 + } + ], + "groups": [ + { + "title": "Modular Vision-Language Models (Instruct-2B)", + "tone": "meta" + }, + { + "title": "Native Vision-Language Models (Instruct-2B)", + "tone": "link" + }, + { + "title": "Modular Vision-Language Models (Instruct-8B)", + "tone": "meta" + }, + { + "title": "Native Vision-Language Models (Instruct-8B)", + "tone": "link" + } + ], + "rows": [ + { + "group": 0, + "cells": { + "model": "Qwen2-VL", + "mmmu": 41.1, + "mmb": 74.9, + "rwqa": 62.6, + "mmstar": 48, + "seedi": null, + "hallb": 41.7, + "ai2d": 74.7, + "docvqa": 90.1, + "chartqa": 73.5, + "textvqa": 79.7, + "ocrbench": 80.9 + } + }, + { + "group": 0, + "cells": { + "model": "InternVL3", + "mmmu": 48.6, + "mmb": 81.1, + "rwqa": 64.3, + "mmstar": 60.7, + "seedi": null, + "hallb": 42.5, + "ai2d": 78.7, + "docvqa": 88.3, + "chartqa": 80.2, + "textvqa": 77, + "ocrbench": 83.5 + } + }, + { + "group": 0, + "cells": { + "model": "InternVL3.5", + "mmmu": 53, + "mmb": 78.2, + "rwqa": 62, + "mmstar": 62.7, + "seedi": 75.3, + "hallb": 48.6, + "ai2d": 78.8, + "docvqa": 89.4, + "chartqa": 80.7, + "textvqa": 76.5, + "ocrbench": 83.6 + } + }, + { + "group": 0, + "cells": { + "model": "Qwen3-VL", + "mmmu": 53.4, + "mmb": 78.4, + "rwqa": 63.9, + "mmstar": 58.3, + "seedi": null, + "hallb": 51.4, + "ai2d": 76.9, + "docvqa": 93.3, + "chartqa": 79.1, + "textvqa": null, + "ocrbench": 85.8 + } + }, + { + "group": 1, + "cells": { + "model": "Mono-VL", + "mmmu": 33.7, + "mmb": 65.5, + "rwqa": null, + "mmstar": null, + "seedi": 67.4, + "hallb": 34.8, + "ai2d": 68.6, + "docvqa": 80, + "chartqa": 73.7, + "textvqa": 72.6, + "ocrbench": 76.7 + } + }, + { + "group": 1, + "cells": { + "model": "Mono-VL1.5", + "mmmu": 39.1, + "mmb": 64, + "rwqa": null, + "mmstar": null, + "seedi": 66.9, + "hallb": 32.5, + "ai2d": 67.4, + "docvqa": 81.7, + "chartqa": 72.2, + "textvqa": 73.7, + "ocrbench": 80.1 + } + }, + { + "group": 1, + "cells": { + "model": "HoVLE", + "mmmu": 32.2, + "mmb": 73.3, + "rwqa": null, + "mmstar": null, + "seedi": 70.9, + "hallb": 38.4, + "ai2d": 73, + "docvqa": 86.1, + "chartqa": 78.6, + "textvqa": 70.9, + "ocrbench": 74 + } + }, + { + "group": 1, + "cells": { + "model": "OneCAT", + "mmmu": 39, + "mmb": 72.4, + "rwqa": null, + "mmstar": null, + "seedi": 70.9, + "hallb": null, + "ai2d": 72.4, + "docvqa": 87.1, + "chartqa": 76.2, + "textvqa": 67, + "ocrbench": null + } + }, + { + "group": 1, + "cells": { + "model": "NEO", + "mmmu": 48.6, + "mmb": 76, + "rwqa": 63.1, + "mmstar": 54.2, + "seedi": 74.2, + "hallb": 43.1, + "ai2d": 80.1, + "docvqa": 89.9, + "chartqa": 81.2, + "textvqa": 74, + "ocrbench": 77.1 + } + }, + { + "group": 1, + "emphasis": "total", + "cells": { + "model": "NEO-ov", + "mmmu": 54.7, + "mmb": 80, + "rwqa": 64.4, + "mmstar": 58.6, + "seedi": 76.2, + "hallb": 54.5, + "ai2d": 81.4, + "docvqa": 91.2, + "chartqa": 83.1, + "textvqa": 77.3, + "ocrbench": 81.2 + } + }, + { + "group": 2, + "cells": { + "model": "Qwen2.5-VL", + "mmmu": 55, + "mmb": 83.5, + "rwqa": 68.5, + "mmstar": 63.9, + "seedi": null, + "hallb": 52.9, + "ai2d": 83.9, + "docvqa": 95.7, + "chartqa": 87.3, + "textvqa": 84.9, + "ocrbench": 86.4 + } + }, + { + "group": 2, + "cells": { + "model": "InternVL3", + "mmmu": 62.7, + "mmb": 83.4, + "rwqa": 70.8, + "mmstar": 68.2, + "seedi": null, + "hallb": 49.9, + "ai2d": 85.2, + "docvqa": 92.7, + "chartqa": 86.6, + "textvqa": 80.2, + "ocrbench": 88 + } + }, + { + "group": 2, + "cells": { + "model": "InternVL3.5", + "mmmu": 68.1, + "mmb": 82.7, + "rwqa": 67.5, + "mmstar": 69.3, + "seedi": null, + "hallb": 77.1, + "ai2d": 54.5, + "docvqa": 84, + "chartqa": 92.3, + "textvqa": 86.7, + "ocrbench": 78.2 + } + }, + { + "group": 2, + "cells": { + "model": "Qwen3-VL", + "mmmu": 69.6, + "mmb": 84.5, + "rwqa": 71.5, + "mmstar": 70.9, + "seedi": null, + "hallb": 61.1, + "ai2d": 85.7, + "docvqa": 96.1, + "chartqa": 89.6, + "textvqa": null, + "ocrbench": 89.6 + } + }, + { + "group": 3, + "cells": { + "model": "Fuyu", + "mmmu": 27.9, + "mmb": 10.7, + "rwqa": 43.7, + "mmstar": null, + "seedi": 59.3, + "hallb": null, + "ai2d": 64.5, + "docvqa": null, + "chartqa": null, + "textvqa": null, + "ocrbench": 36.6 + } + }, + { + "group": 3, + "cells": { + "model": "EVE", + "mmmu": 32.6, + "mmb": 52.3, + "rwqa": null, + "mmstar": null, + "seedi": 64.6, + "hallb": 26.4, + "ai2d": 61, + "docvqa": 53, + "chartqa": 59.1, + "textvqa": 56.8, + "ocrbench": 39.8 + } + }, + { + "group": 3, + "cells": { + "model": "SOLO", + "mmmu": null, + "mmb": 67.7, + "rwqa": 44.7, + "mmstar": null, + "seedi": 64.4, + "hallb": null, + "ai2d": 61.4, + "docvqa": null, + "chartqa": null, + "textvqa": null, + "ocrbench": 12.6 + } + }, + { + "group": 3, + "cells": { + "model": "EVEv2", + "mmmu": 39.3, + "mmb": 66.3, + "rwqa": 62.4, + "mmstar": null, + "seedi": 71.4, + "hallb": null, + "ai2d": 74.8, + "docvqa": null, + "chartqa": 73.9, + "textvqa": 71.1, + "ocrbench": 70.2 + } + }, + { + "group": 3, + "cells": { + "model": "BREEN", + "mmmu": 42.7, + "mmb": 71.4, + "rwqa": null, + "mmstar": 51.2, + "seedi": null, + "hallb": 37, + "ai2d": 76.4, + "docvqa": null, + "chartqa": null, + "textvqa": 65.7, + "ocrbench": null + } + }, + { + "group": 3, + "cells": { + "model": "VoRA", + "mmmu": 32, + "mmb": 61.3, + "rwqa": 60.1, + "mmstar": null, + "seedi": 68.9, + "hallb": null, + "ai2d": 61.1, + "docvqa": null, + "chartqa": null, + "textvqa": 58.7, + "ocrbench": null + } + }, + { + "group": 3, + "cells": { + "model": "SAIL", + "mmmu": null, + "mmb": 70.1, + "rwqa": 63.9, + "mmstar": 53.1, + "seedi": 72.9, + "hallb": 54.2, + "ai2d": 76.7, + "docvqa": null, + "chartqa": null, + "textvqa": 77.1, + "ocrbench": 78.3 + } + }, + { + "group": 3, + "cells": { + "model": "NEO", + "mmmu": 54.6, + "mmb": 82.1, + "rwqa": 67.3, + "mmstar": 62.4, + "seedi": 76.3, + "hallb": 46.4, + "ai2d": 83.1, + "docvqa": 88.6, + "chartqa": 82.1, + "textvqa": 75, + "ocrbench": 77.7 + } + }, + { + "group": 3, + "emphasis": "total", + "cells": { + "model": "NEO-ov", + "mmmu": 68.1, + "mmb": 85.1, + "rwqa": 67.8, + "mmstar": 67.3, + "seedi": 76.6, + "hallb": 59.8, + "ai2d": 85.4, + "docvqa": 91.9, + "chartqa": 86.2, + "textvqa": 78.5, + "ocrbench": 81.6 + } + } + ] +} diff --git a/packages/dsh-tables/reference/targets/dataset-summary.png b/packages/dsh-tables/reference/targets/dataset-summary.png new file mode 100644 index 0000000..fa7b1f5 Binary files /dev/null and b/packages/dsh-tables/reference/targets/dataset-summary.png differ diff --git a/packages/dsh-tables/reference/targets/implementation-details.png b/packages/dsh-tables/reference/targets/implementation-details.png new file mode 100644 index 0000000..2ab68f9 Binary files /dev/null and b/packages/dsh-tables/reference/targets/implementation-details.png differ diff --git a/packages/dsh-tables/reference/targets/vqa-results.png b/packages/dsh-tables/reference/targets/vqa-results.png new file mode 100644 index 0000000..8f45eee Binary files /dev/null and b/packages/dsh-tables/reference/targets/vqa-results.png differ diff --git a/packages/dsh-tables/skills/paper-tables/SKILL.md b/packages/dsh-tables/skills/paper-tables/SKILL.md new file mode 100644 index 0000000..cd4e9c6 --- /dev/null +++ b/packages/dsh-tables/skills/paper-tables/SKILL.md @@ -0,0 +1,117 @@ +--- +name: paper-tables +description: Build a publication table from a JSON spec with table_write - grouped headers, row and column spans, bands, best-value emphasis, and the LaTeX / Markdown / DOCX / CSV outputs plus a compiled PNG preview. +--- + +# Paper tables + +A table in a paper is a **grid with a claim**: which columns belong together, +which blocks are being compared, which number won, and what the bold means. Those +are four facts, not four hundred cells. The spec says them once; the compiler +emits LaTeX, Markdown, DOCX and CSV from the same resolved grid, so the four +outputs cannot disagree about a number or about a winner. + +``` +table_write({ source: , id: "vqa-results" }) +``` + +Files land in `tables//` in the workspace: `spec.json`, `table.tex`, +`table.md`, `table.csv`, `table.docx`, and `table.png` when TeX is installed. +`table_read` lists them or returns one spec. + +## The spec + +```json +{ + "table": { + "id": "vqa-results", + "caption": "Single-image performance. Bold marks the best value in each family.", + "label": "tab:single-image", + "style": "booktabs", + "size": 7, + "notes": ["A dash is a benchmark the model does not report."] + }, + "columns": [ + { "key": "model", "title": "Model", "align": "left", "width": 1.7 }, + { "key": "mmmu", "title": "MMMU", "group": "General VQA Understanding", "align": "right", "best": "max", "digits": 1 }, + { "key": "ocr", "title": "OCRBench", "group": "OCR Recognition", "align": "right", "best": "max", "digits": 1 } + ], + "groups": [ + { "title": "Modular Vision-Language Models (Instruct-2B)", "tone": "meta" } + ], + "rows": [ + { "group": 0, "cells": { "model": "Qwen2-VL", "mmmu": 41.1, "ocr": 80.9 } }, + { "group": 0, "emphasis": "total", "cells": { "model": "NEO-ov", "mmmu": 54.7, "ocr": 81.2 } } + ] +} +``` + +## The four facts + +- **Column groups** — `column.group`. The header's `\multicolumn` widths and its + `\cmidrule` spans are DERIVED from these strings. Adding a column widens its + rule by itself; no number is typed twice. +- **Row groups** — `row.group` names an entry in `groups`. A group with a `title` + gets a section row; `"band": true` tints the group's data rows instead (or as + well), which is how a table of prose blocks stays readable. +- **Spans** — `row.span` merges across (`{"pretrain": 3}` starting at a column), + `row.rowSpan` merges down (`{"task": 4}` on the first row of a block). A span + whose covered cells also carry a value is REFUSED: a spanned cell is one cell. +- **Emphasis** — `best: "max"` (or `"min"`) marks the winner of each column + **within each row group**, because a 2B family and an 8B family are separate + races. `emphasis: "total"` bolds a whole summary row. + +## What the rungs mean + +| rung | proved | +|---|---| +| `t0-spec` | the JSON parsed and every column, row and span resolved | +| `t1-grid` | every row covers exactly the columns the header declares | +| `t2-data` | numbers formatted, best marks resolved, no quoted numbers | +| `t3-typeset` | `pdflatex` compiled it (real booktabs/multirow) | +| `t4-drawn` | a PNG exists, rendered from the compiled PDF | + +A table that reaches `t2-data` is structurally sound but has never been SET. If +the host has no TeX engine the answer says so; do not describe such a table as +verified. + +## Formats, and what each one cannot do + +- **LaTeX** — the primary target. `booktabs`, `\multicolumn`, `\multirow[t]`, + `\cellcolor` bands, maths passed through `$...$`. This is what the paper takes. +- **Markdown** — flattened: a span keeps its text in the first cell, a row span + repeats, a group becomes a bold full-width row. Good for a README or a review. +- **DOCX** — a real Word table with `gridSpan`, `vMerge`, shading and horizontal + rules. Word has no LaTeX maths without OMML, so a maths cell is written as plain + text and the result SAYS the DOCX degraded. +- **CSV** — the data, with spanned values repeated so it is self-contained. + +## Rules that keep a table printable + +- **One claim per table.** If the caption needs "and", it is two tables. +- **Bold means one thing**, and the note says what. A table of bold numbers with + no note is a puzzle. +- **A missing number is `null`**, which prints as a dash — never `0`, never `""`. + An empty string is indistinguishable from a bug. +- **Do not fight the width.** A 12-column table at 7 pt fills a two-column page; + at 3.5 in it does not. The compile reports a multi-page table as a warning, and + the fix is fewer columns, not smaller type. +- **Numbers as numbers.** `"41.1"` is a string: it is not formatted and it cannot + win a best-value mark. The build warns when it sees one. + +## The corpus + +`reference/tables/` holds three published tables rebuilt from their structure, +each with a target, an `anatomy.md`, the spec, the built artifacts and an +executable rubric. Read the anatomy of the one that looks like your table before +writing a spec: + +| table | what it teaches | +|---|---| +| `vqa-results` | two header levels, four family bands, best-per-family bolding | +| `dataset-summary` | row spans over prose blocks, alternating bands | +| `implementation-details` | column spans in the body, maths in cells | + +```sh +node packages/dsh-tables/checks/check-tables-node.mjs +```