Skip to content
FileSherlockPublic

About

Read government documents at tolerance 0 — every line certified, never sampled.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

tol0

Read government documents at tolerance 0 — every line certified, never sampled.

This is not fuzzy OCR. It re-renders candidate glyphs with a byte-exact clone of the producer's rasterizer and demands the pixels match exactly. When they do, the read comes with a certificate: every non-object ink pixel of the line was explained by the proven blend law, so the transcript is not a guess. Unread ink becomes an honest □ with coordinates — errors cannot pass silently.

The honest limit is the same sentence: a document that will not read at tolerance 0 is one this toolkit says no to, loudly, rather than guessing at.

To read a document this way you must first know its (face, size, pen lattice, blend law) — so the other half of the toolkit is machinery for identifying that tuple from pixels alone.

Where to read next

docs/LAWS.md the measured physics every claim rests on — pen lattice, blend, producer post-laws, colour
docs/METHOD.md how this kind of problem is worked: eight rules that cost real time
docs/FONTS.md what ships, what you regenerate, and why a fresh clone has 13 of 77 glyph sets
fixtures/gate-ref/README.md the gate's expected numbers, and every □ looked at one by one
synth/README.md example PDFs whose every answer is known — and how to make your own when a document goes wrong
lab/README.md the other half — finding the producer of a document nobody has read yet

What runs with nothing installed

npm install
npm run certify:ftclone   # the rasterizer clone vs the real mupdf
npm run certify:render    # the forward renderer (lattice + blend, whole lines) vs the real mupdf
npm test                  # engine primitives, render round trip, and the example PDFs in synth/ held to their answers
npm run synth:check       # those PDFs are still what mupdf draws from their specs
npm run rust:build && npm run rust:certify   # the lab's fast engine (needs cargo)
pen lattice, measured now: x 5 distinct rasters per px (4 phases of 1/4 px + the 1-px shift), y 2 (integer rounding — no subpixel y)

CERTIFIED TTF y-phase  0/64 — 0 diffs over 1128 renders
CERTIFIED CFF y-phase  0/64 — 0 diffs over 1128 renders

None of those needs a corpus document or a system font — a deliberate constraint, not a convenience; the PDFs npm test reads are drawn here by mupdf from the free faces this repo ships, every answer known (synth/). ftclone/ is a JS port of the glyph pipeline inside mupdf 1.28 wasm (FreeType 2.13 smooth rasterizer, integer 26.6 throughout); everything else depends on it, so it certifies itself against the real thing, in two pipelines that share almost no code below the outline. The third line holds the same line one level further out: lab/rust/ is a port of that port, and it proves itself against it over 3,000 seeded tuples and two whole control sweeps drawn from the faces this repo ships.

A read, end to end

node tools/rasterize-mupdf.mjs --pdf fixtures/corpus/nimbus791/EFTA00751637.pdf
node tools/blind-read.mjs --pdf fixtures/corpus/nimbus791/EFTA00751637.pdf \
     --page 1 --pool nimbus791 --truth fixtures/corpus/nimbus791/EFTA00751637.txt \
     --json p1.json
  page 1: 76 bands

76 lines, 4612 glyphs, 0 unreadable clusters (□), 0.4s
vs truth: 76 rows letter-exact (76 also space-exact), 0 rows differ

--pool names a certified family read command — the glyph sets, tolerance and blend flags that family was actually proven with, taken from tools/glyph-registry.mjs so it cannot drift. --truth is a check, not an input: the reader never sees it.

One line of p1.json, which is where the certificate lives:

{ "baseline": 101, "phy": 0, "font": "nimbus791", "fails": 0,
  "text": "Received: by 10.229.235.4 with SMTP id ke4mr6853629qcb.201.1291165934346;",
  "glyphs": [["R", 37.25], ["e", 44.5], ["c", 52], ["e", 59.5], ["i", 66.75], … ] }

"fails": 0 is the claim: every ink pixel of that band was reproduced exactly. Note the pens — 37.25, 44.5, 66.75. Nobody told the reader that this producer places pens on a ¼-px lattice; it fell out of the search, and it is law §1 turning up in a real document. Word spacing is measured the same way: the space advance here is 7.4077 px, self-calibrated from the gap histogram rather than assumed, which is how narrow styled spaces become measurements instead of errors.

No corpus on this machine? The same read runs on a page drawn here with the same set, whose truth was computed as it was drawn (the bundle first: node tools/export-glyphs.mjs builds it from the committed sets):

node tools/rasterize-mupdf.mjs --pdf synth/out/email.pdf
node tools/blind-read.mjs --pdf synth/out/email.pdf --all --pool nimbus791 --truth synth/out/email.truth.txt
71 lines, 4127 glyphs, 0 unreadable clusters (□), 0.5s
vs truth: 71 rows letter-exact (71 also space-exact), 0 rows differ

Reading is not rendering: the rasterizer decodes the producer's own embedded page image, because rendering would invent pixels and leave nothing to certify against (law §7).

A corpus, not a document

blind-read.mjs is one document in one process. A corpus of half a million is tools/bulk.mjs: persistent workers on every core (the glyph sets are loaded once per worker, not once per document), results written by one process into a run directory you can kill and restart at will, and a page read straight from the PDF's embedded image — no raster cache in between.

node tools/bulk.mjs inventory --in <dir of PDFs> --out bulk-out/inventory     # what every page IS: ms a page
node tools/bulk/inventory-report.mjs bulk-out/inventory                      # …read as the questions that steer a year
node tools/bulk.mjs read --in <dir> --out bulk-out/read-app --roster app      # the certified read, kept slim and lossless
node tools/bulk.mjs status --out bulk-out/read-app

A bulk read is blind-read's read — both stand on tools/read-core.mjs, and test/bulk.test.js holds a gate document to byte-identical JSON. It is also built for a machine someone is sitting at: the run lives in a systemd scope the kernel caps at half the RAM, workers are niced, replaced when they grow, and huge files take a lane of their own — the reasons are in tools/bulk/pool.mjs, and one of them is a desktop session that did not survive the first attempt.

Attachments printed as base64

An e-mail printed to PDF often carries its attachments as base64 text — a PDF, a photo, an audio file, typed out as 76-character lines over hundreds of pages. A tolerance-0 read of those lines is the file, byte for byte; one misread character would cost its three bytes and, inside compressed data, everything after them. tools/b64/ turns certified reads into files:

node tools/bulk.mjs b64scan --in <dir of PDFs> --out bulk-out/b64scan     # where the base64 is (text layer, ms a page)
node tools/b64/plan.mjs --scan bulk-out/b64scan --out bulk-out/b64/plan   # which pool reads each flagged document (R1 left out)
node tools/b64/read.mjs --plan bulk-out/b64/plan/plan.json --out bulk-out/b64/read   # the certified read, page-parallel
node tools/b64/decode.mjs --run bulk-out/b64/read [--alt <tolerant read>] [--pdf <dir of the PDFs>] --out <archive>

decode.mjs finds each body (MIME declarations above it, a printer's wrapped lines summed back to the body's width; base64 sharing a line with an armor line, an XML tag or an HTML attribute; a printer's soft hyphen at the end of a line and its spaces inside one), decodes it, types it from its bytes, checks it with the format's own reader (gs, Pillow, ffmpeg, unzip, DER's nested lengths) and writes manifest.json / index.tsv beside the files:

status meaning
exact every character certified, and the file known to be whole: its reader accepts it, or both ends of the body are proven (a marker, MIME headers, a magic number; padding, a closing marker, a MIME boundary, a short last line, a declared size)
incomplete certified, but cut short: a reader refuses it, it holds less than its declared size, it is a fragment, its last base64 group is not whole
unproven certified, and nothing says whether that is the whole file
damaged some characters were not read; the byte ranges are listed

An attachment in an InfoPath form takes its name and size from the form's own header, and a file that holds more base64 (an image in an element of the XML, a data: URI) gives files of its own, judged the same way. CMS EnvelopedData is an exact envelope, marked encrypted. Not every base64 value is a file: mail header values (header-value) and a web form's hidden fields (form-data: VIEWSTATE, EVENTVALIDATION) are listed and not written.

A certified line can still be wrong where the read took a pixel subset of a glyph for the glyph — an I inside an L whose foot was too light to count as unexplained ink. Base64 has no spaces, so every pen step is an advance: an I followed by an L's step is a wide glyph (blocks.mjs), and a character lost at an unexplained cluster is narrowed to those whose advance fills its gap. With --pdf, each is read again on the page: the candidate's raster must match exactly where the character stands (glyphcheck.mjs). What is left is put back when the file's own checksum can prove it — zlib's Adler-32 in a PDF stream, a ZIP member's CRC-32 (a stored member's lost bits solved by elimination over GF(2)), a PNG chunk's — and only when exactly one candidate verifies (repair.mjs). A CCITT G4 page (ccitt.mjs) only confirms: a wrong character can still decode to a valid page. Every stream check a file carries is run on the result.

The gate

The gate is what makes this repo trustworthy. It re-reads a fixed set of documents and byte-compares whole transcripts against committed references: the expected numbers are the files in fixtures/gate-ref/, not prose, so any change in any number is the signal.

npm run gate
gate: 18/18 ok, 55s total

18 documents · 33,736 lines · 2,436,383 glyphs · 177 □, of which 149 are coloured ink (blue headings and links the sets cannot read yet — visible since law §9 stopped whitening them; 28 are neutral text). The 11 nimbus791 documents also carry truth transcripts and match 5,028 of 5,028 rows, spacing included. All 40 neutral □ of the first census have been looked at rather than assumed away — 24 are ordinary black text, i.e. a face missing from a pool, which is a hunt and a winnable one; the rest is colour and graphics the reader is right to refuse. Census, and what the reference has already caught: fixtures/gate-ref/README.md.

The documents are real government PDFs and are not distributed (gitignored fixtures/corpus/), and most pools need glyph sets whose faces are not redistributable either — so a fresh clone runs 0 of 18, and says so per document, naming the missing fixture or set. Skipping is loud, and it is not a pass. The nimbus791 block is the cheap way in: its pool is entirely free.

Recto — the same bytes, in a browser

Recto is a Django PDF editor whose ocr_tool plugin runs this engine client-side. It has no copy of the engine; it has these files:

npm run sync:recto           # -> ../Recto/ocr_tool (default; --recto <path>)
npm run sync:recto:check     # report stale, write nothing, exit 1 if stale
npm run recto-test           # end-to-end: Django + headless Chrome + a real upload

The direction is the whole point: the engine is developed only here, where the gate can certify it, so a read in the browser is the read the gate proved. --check makes that auditable instead of assumed — it byte-compares and exits non-zero. Two things the sync refuses to do quietly:

  • push an incomplete glyphs.bin. The bundle holds whatever .npz you have locally, so a fresh clone would push 13 of 77 sets and swap Recto's dictionary for a smaller one with no error and no crash. The gate cannot catch it either — it reads through named pools, never the whole bundle. So the sync names the missing sets and stops (--allow-partial if you mean it).
  • let a UI bug hide. recto-test uploads a gate document through the real file input and clicks the real buttons; a programmatic call would mask dead wiring, and that bug has happened. It is the only thing here that needs a browser, which is why puppeteer-core is a devDependency.

Layout

ftclone/    the rasterizer clone's certification (vs mupdf: glyphs, render, rectangles) and
            its path-taking wrappers — the code itself is engine/ftraster.js
engine/     the DOM-free matcher: ink bands, baseline pin, the composite-aware
            scan, object/redaction detection, the per-line certificate;
            render.js runs the same laws FORWARDS (layout → composite → diff);
            set-fonts.js (generated from the registry) names every set's face
            ftraster.js is the certified rasterizer + font parsers (bytes in, so a
            browser runs what is certified) and makes glyph sets on demand
tools/      fontgen · glyph registry/bundle · rasterizer · reader CLI · gate · sync ·
            b64 (tools/b64/: base64 attachments — read, decode, repair, archive) ·
            bulk (tools/bulk/: the corpus runner — pool, sink, inventory and read jobs) ·
            the clip and hypothesis benches · the Recto verifiers
            · ladder-bench (Recto's escalating read, timed per rung — the speed bench)
lab/        the other half: what produced these pixels? (see lab/README.md)
lab/rust/   optional: that half's exhaustive search, 40–45× and certified against it
fixtures/   gate documents (gitignored) + the reference transcripts
fonts/      the source faces this repo may legally ship
docs/       the laws, the method, the font/licence story

ftclone/ is a top-level package rather than a detail of either half, and that is load-bearing: tools/ and lab/ both need it, and neither may import the other. npm test asserts that boundary instead of describing it. Since 2026-09-18 the rasterizer's code lives in engine/ftraster.js so the browser can make glyph sets itself; ftclone/*.mjs wrap it, which means the lab now reaches one engine file through ftclone/ — and that file is exactly the one npm run certify:ftclone holds still.

engine/ is shared verbatim by the CLI and the browser app, so the scanning physics has exactly one implementation; test/engine.test.js covers it on synthetic pages only — 43 tests, ~40 ms, no assets, which is why they run before the slow document gate.

Status

Ported from a larger private working repo, one certified layer at a time.

  • 1. ftclone — the rasterizer clone + font parsers, self-certifying
  • 2. engine — the reader core + unit suite
  • 3. glyph pipeline — registry · bundle · fontgen, with the licence split
  • 4. reader CLI + the byte-identical gate — 18 documents, 2.44 M glyphs; Chrome dropped
  • 5. sync:recto — this repo is now the source of the engine Recto runs
  • 6. docs — the laws, the method, one worked example
  • 7. lab/ — the hunt half in 8 files, with its own end-to-end gate: a gate document is re-identified blind, 93/107 targets, every other family flat zero
  • 8. lab/rust/ — the sweep at 40–45×, the anisotropic probe and the connected-component harvester, certified against the JS as its oracle and running that gate with no corpus at all
  • 9. glyphs fused to redaction bars — a quote mark or < flush against a bar used to be bridged into the bar's dark run, slice the box into rule-typed slivers and vanish under their padding; the bar body is now bounded by its column profile, so those glyphs read (To: " " < > on Recto's startup document, residual 0) and the gate re-recorded exactly four gained glyphs, every other transcript byte-identical
  • 10. glyphs clipped by redaction boxes — the box is black inside and keeps a glyph as a composite in its anti-aliased edge (law §8); a glyph mostly under a box now reads when every visible pixel is exact and it is the only character in the pool that fits (including S████ on report, an a and a J on one Courier document), and is refused as ambiguous otherwise. The JSON marks such glyphs with the count of pixels the box destroyed. A bar always splits a line: one separator space in the transcript, two text boxes in Recto, the same boxBetween rule in both. tools/clip-bench.mjs measures the rule on certified pages (158 right, 0 wrong, 1,777 refused over two pages); shadow-only reads under boxes are opt-in (--shadow) because on real boxes they came back wrong more often than right.
  • 11. string hypotheses under a bar — engine/hypothesis.js draws a candidate name where a redaction hid one, composites the bar over it (law §8, bar last) and lets the page outside the body return consistent, contradicted or no-evidence; the producer's advances and kern pairs are measured from the page's own pens (pageMetrics). Certified by tools/hypothesis-bench.mjs (truth contradicted 0 on a Courier and a Times page over 960 trials, dark edges judged with a byte of slack); Recto's redaction_matching shows the verdict on every candidate chip and tools/verify-redactions.mjs reports the corpus; tools/hypothesis-truth.mjs runs the tester on real bars with known text (two Calibri memos: the truth never contradicted, and the bars — the names' advance boxes — leave no shadow to read).
  • 11. coloured ink is coverage — a blue glyph is its black twin seen through the pen (law §9), so coloured text is recovered and read with the sets the reader has instead of being whitened away; rasters carry RGB (mode 4). What is nobody's pen is still whitened, and coloured ink that stays unread is an honest □, counted apart. On a page the producer quantized, a coverage is a range rather than a byte, so the reader compares in colour space and the links read: email's 37 coloured □ became 14, and 137 glyphs of URLs and addresses came back.
  • 12. which dark boxes are bars — detectObjects types by height alone, so logos, plates of white lettering, bullets, thick rules and page borders arrived as boxes beside the redactions; barShapes (law §8) judges each by its shape — a filled rectangle on paper, at the text it covers — and says why when it is not (sliver, page edge, dark shape, lone rule). The detector found too little as well: a bar over 8-pt text (39 × 7) was under both of its size rules, a bar fused to a taller one beside it was absorbed, a glyph peeking out of a bar made a box that cut the bar in three, a dark run reaching the page's right or bottom edge was never closed, and vertical rules merged with a block's columns masked whole page regions. On 2,617 corpus pages about one box in ten is now told apart as no bar.
  • 13. pages whose every answer is known — synth/ draws example PDFs with mupdf in the free faces, the way the corpus producers drew theirs: text at float pens, bars over words, logos, plates of white lettering, rules, bands — and computes what the reader must make of them, row for row and box by box. npm test reads them on a fresh clone; the gate carries them as synth_*, and they took over eight of the eleven nimbus791 documents (same set, every glyph at every pen phase). A spec is a JSON file: copy a case that went wrong onto a page and it is a test. The first three found two engine bugs — a Times = masked as a short underline, a seal's piece called a bar — both fixed.

Open, and known: most of the reader's gate still needs documents that cannot be shipped, so a stranger runs 3 of its 14 entries — the synth_* pages, whose transcripts are known because they were drawn here (synth/). What those cannot stand in for yet is a producer's post-law: mupdf draws the plain blend law only, so the linear and palette families (fbimemo, nimbusrom, report) still need their real documents. Also unsettled: whether ftclone still certifies against a different mupdf build — i.e. what exactly the compatibility claim is.

About

Read government documents at tolerance 0 — every line certified, never sampled.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages