# Text recognition (OCR)

> The package's own OCR engine. It turns scanned pages into searchable, selectable and redactable text, runs in the browser, in a worker or in Node, and sends nothing anywhere.

`@birchui/pdf/ocr` reads the text of scanned pages, screenshots and photographed documents. It is written for this package from the ground up: page clean-up, layout analysis and a line recogniser trained on synthetic text, all in TypeScript on typed arrays. There is no third-party OCR library, model or runtime inside, and no network access.

```ts no-check
import { readFile, writeFile } from 'node:fs/promises';
import { openPdfDocument } from '@birchui/pdf/engine';
import { createOcrEngine } from '@birchui/pdf/ocr';

const pdf = openPdfDocument(await readFile('scans/delivery-notes.pdf'));
const ocr = createOcrEngine();

const pages = await ocr.recognizeDocument(pdf, {
  onProgress: ({ pageNumber = 0, pageCount = 1, stage, progress }) =>
    console.info(`page ${pageNumber + 1}/${pageCount} ${stage} ${Math.round(progress * 100)}%`),
});
console.info(pages.map((page) => `${page.pageIndex}: ${page.status}, ${page.words} words`));

await writeFile('scans/delivery-notes-searchable.pdf', (await pdf.save()).bytes);
console.info(pdf.findText('invoice').length);
```

The recognised words are written through the [text recognition hook](https://docs.birchui.com/pdf/document-tools.md) as an invisible text layer: text rendering mode 3, each word placed on and stretched to its box. The scan itself is not touched, and the save is incremental, so the original bytes stay in the file and the page renders exactly as before. After that the page is searchable, selectable, redactable by text or pattern and comparable like any other page.

## In the viewer

Pass the `ocr` option and the viewer offers **Recognize text (OCR)…** in the **Tools** tab and in the command palette (`recognizeText`). The engine and the model are loaded the first time the command runs, not with the viewer.

```ts no-check
import { createPdfViewer } from '@birchui/pdf';
import { ocrModelUrl } from '@birchui/pdf/ocr';

declare const container: HTMLElement;
declare const scanBytes: Uint8Array;

const viewer = createPdfViewer(container, {
  document: scanBytes,
  fileName: 'delivery-notes.pdf',
  ocr: {
    model: async () => new Uint8Array(await (await fetch(ocrModelUrl())).arrayBuffer()),
    worker: true,
  },
});
```

| `ocr` key | Meaning |
| --- | --- |
| `model` | The bytes of `assets/ocr/latin.lqocr` or a function that loads them. The viewer never fetches the file itself; the function is called on first use. |
| `worker` | `true` for the packaged worker, a worker running `@birchui/pdf/ocr-worker`, or a function that creates one. Without it recognition runs on the main thread. |
| `engine` | An object with `recognizePage(pdf, pageIndex, options)` used instead of the packaged engine |
| `languages` | Languages offered in the dialog; read from the model by default |
| `dpi` | Resolution a page is rendered at for recognition, 200 by default |
| `banner` | `false` hides the banner on scanned pages |

Without the `ocr` option there is no command, no banner and `viewer.recognizeText()` rejects, because the viewer has no way to get the model.

- **Banner.** When the current page has an image and no text, a bar above the page says "This page is a scan. Recognize text?" with **Recognize text** and **Dismiss**. Dismissing hides it for that document.
- **Dialog.** Page range (all, current, or a range such as `1-5, 8`), **Only pages without text**, the language, a progress bar with the page being read, and **Cancel**, which stops after the current step. The result per page is listed when the run ends.
- **Thumbnails.** Each page that was worked on gets an "OCR" badge: solid when text was recognised, dashed while it runs, red when it failed, grey when no text was found. The state is part of the thumbnail's accessible name.
- **Result.** The words become an invisible text layer, so search, text selection and copy, text markup, search-and-redact and compare work on the scan. Each page is one undo step, and `save()` writes the layer as an incremental update that leaves the original bytes in place.

`viewer.recognizeText({ pages, includePagesWithText, language, signal, onProgress })` does the same from code and resolves with `{ pageIndex, status, words }` per page; `viewer.getOcrState(pageIndex)` returns the badge state, and the `textRecognition` event fires after each run. A page is rendered by the viewer and passed to the engine; when a page cannot be rendered, the largest image on it is used.

## What it does

1. **Clean-up.** Grey conversion, light-on-dark detection for the page and for dark panels inside it, Sauvola binarisation on a tile grid, removal of scanner borders and ruling lines, skew measurement from the projection profile of the glyph feet (±15°) and correction, detection of pages turned by 90, 180 or 270 degrees, and an estimate of the resolution from the text size with rescaling of very small or very large text.
2. **Layout.** Connected components are sorted into glyphs, ruling lines, figures and borders; glyphs are chained into lines with a baseline each; a recursive X-Y cut finds columns, blocks and paragraphs and puts them in reading order. Tables are read row by row. Figures and rules are reported as non-text regions.
3. **Recognition.** Each line is scaled to 40 pixels of height and read by a small convolutional and recurrent network with CTC decoding (greedy, or a prefix beam search with an optional character prior). Every character and word carries a confidence.
4. **Output.** Words with boxes, baselines and confidences in the pixels of the image you passed, grouped into lines, paragraphs, blocks and columns; plain text; an hOCR-like JSON tree; and the invisible text layer.

## Supported scripts

One model ships: **Latin**. Its 366 characters are ASCII, Latin-1 Supplement, Latin Extended-A, `ƒ Ș ș Ț ț`, typographic quotes, dashes, bullets, ellipsis, primes, a few arrows and box marks, and the currency signs `$ ¢ £ ¤ ¥ € ₹ ₽ ₺ ₩ ₪ ₴ ₦ ₱ ₫`. That covers English and the Western and Central European languages written in Latin letters, among them German, French, Spanish, Portuguese, Italian, Dutch, the Nordic languages, Polish, Czech, Slovak, Hungarian, Romanian, Turkish, Croatian and the Baltic languages.

Accuracy was measured on English. The accented letters were trained on generated words, not on real text of those languages, so expect more mistakes on diacritics than on plain letters. Greek, Cyrillic, Arabic, Hebrew, Indic and CJK scripts are not recognised. The model file format carries its own character set and script code, so a model for another script is another file loaded by the same code; none has been trained yet.

## Accuracy

Measured on a held-out set the model never saw, with the ground truth taken from the source text: prose of this documentation and generated business text laid out by LibreOffice and Chrome and rasterised by `pdftoppm`; the same pages after blur, noise, JPEG compression and a slight turn; pages set in font families that were kept out of training; Chrome screenshots at 96 dpi; and pages under a synthetic perspective warp with uneven light. Character error rate (CER) is the edit distance divided by the length of the reference after collapsing white space; word accuracy is one minus the word error rate. Tesseract 5.5 (`tesseract page.png out -l eng`, default settings) ran on the same images as a yardstick only; it is not part of the package.

| Category | Images | CER, this engine | Word accuracy | CER, yardstick | Word accuracy, yardstick |
| --- | ---: | ---: | ---: | ---: | ---: |
| Print, 300 dpi, clean | 6 | 0.08% | 99.47% | 0.50% | 98.26% |
| Print, 200 dpi, clean | 6 | 0.09% | 99.47% | 0.44% | 98.32% |
| Print, 150 dpi, clean | 6 | 0.08% | 99.47% | 0.48% | 98.11% |
| Print, 200 dpi, degraded | 6 | 0.12% | 99.37% | 0.49% | 98.05% |
| Fonts not used in training, 300 dpi | 14 | 0.35% | 97.85% | 0.38% | 97.71% |
| Screenshots, 96 dpi (table UI, terminal, spreadsheet) | 3 | 0.17% | 98.97% | 42.32% | 41.99% |
| Photographed style, 300 dpi | 6 | 0.55% | 97.74% | 25.51% | 66.49% |
| This package's own PDF fixtures, 300 dpi | 3 | 13.99% | 79.38% | 22.89% | 68.13% |

How to read it:

- The set is small (50 images, about 84,000 characters) and synthetic in origin. It shows that the targets for printed English are met (CER at or below 1.5% at 300 dpi, at or below 4% for degraded 200 dpi); it does not show how the engine does on your scans. Measure on your own material before you rely on a number.
- The yardstick's large error rates on screenshots and photographed pages come from a few images on which it scores between 25% and 85% while scoring under 1% on similar ones. That pattern points to reading order and page segmentation under its default settings rather than to misread letters; other settings were not tried, so do not read those rows as its best.
- On unseen fonts the two are level on average, but the yardstick is ahead on 5 of the 14 pages, clearly so on Anonymous Pro (1.42% and 0.92% here against 0.24% and 0.33%) and Atkinson Hyperlegible (0.82% against 0.16%). It has a dictionary and was trained on far more fonts and real text; this engine has neither, and unfamiliar letter shapes are where that shows.
- The fixture row contains a page with Hebrew and Arabic lines and a chart, which the reference text only partly reflects; neither engine reads that page well. The engine leaves out lines it cannot read (see `minLineConfidence`) instead of emitting noise.
- Typical remaining mistakes: `O` for `0` and `l` for `1` in serials, a lost comma or period in monospaced type, a missing or extra space next to punctuation, straight for curly quotes.

The scripts that build the test set and print this table are in `packages/pdf/scripts/ocr-train/eval`.

## Speed and memory

Measured in Node 20 on one core of an Intel Core i9-14900K, A4 pages at 300 dpi (2481 x 3508 pixels, about 25 lines of 11 pt text each, 3,000 characters):

| Mode | Seconds a page | Pages a minute | Peak memory of the process |
| --- | ---: | ---: | ---: |
| Calling thread, WebAssembly kernel | 0.9 to 1.0 | 58 to 65 | 225 to 290 MB |
| Worker (`worker_threads`), WebAssembly kernel | 0.85 | 70 | 223 MB |
| Calling thread, `kernel: 'js'` | 4.2 | 14 | 231 MB |

Time grows with the amount of text, not with the page size: clean-up and layout take about 0.3 s of a page, the rest is recognition at roughly 30 ms a full-width line, so a denser page takes proportionally longer. The memory figure includes the decoded RGBA page (35 MB) and the Node runtime; the engine itself holds one grey copy, one binary copy and the component list of the page it is working on, and nothing between pages.

Three sizes of the model were trained; the middle one ships:

| Model | File | CER print 300 dpi | CER degraded 200 dpi | CER unseen fonts | CER photographed | Pages a minute |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| small, 126 k weights, 40,000 steps | 140 kB | 0.20% | 0.24% | 0.48% | 1.49% | 88 |
| medium, 245 k weights, 100,000 steps (shipped) | 262 kB | 0.08% | 0.12% | 0.35% | 0.55% | 58 to 65 |
| large, 1.02 M weights, 40,000 steps | 1.05 MB | 0.18% | 0.20% | 0.44% | 1.00% | 30 |

The large model was trained for fewer steps than the shipped one and had not converged, so its row understates what that size can do; it does show the cost in speed.

The arithmetic runs in a 2.6 kB WebAssembly kernel with 128-bit SIMD that is embedded in the entry. Where WebAssembly cannot be started, for example under a Content Security Policy without `'wasm-unsafe-eval'`, the engine falls back to plain typed-array loops by itself; `kernel: 'js'` forces that path.

## Serving the model

The model is `assets/ocr/latin.lqocr` in the package (262 kB, 8-bit weights). The engine loads it on first use, or when you call `load()`.

In Node the engine reads the file from the package by itself. In a browser it does not fetch anything on its own: you pass a loader, and the request goes to your own origin.

```ts no-check
import { createOcrEngine, ocrModelUrl } from '@birchui/pdf/ocr';

const ocr = createOcrEngine({
  worker: true,
  model: async () => new Uint8Array(await (await fetch(ocrModelUrl())).arrayBuffer()),
});
await ocr.load();
```

`ocrModelUrl()` is `new URL('../assets/ocr/latin.lqocr', import.meta.url)`, which Vite, webpack 5, Rollup and esbuild turn into the URL of a copied asset. If your bundler does not, copy `node_modules/@birchui/pdf/assets/ocr/latin.lqocr` to your static files and fetch that path instead, or pass the bytes directly as `model: bytes`. Without a model in a browser the engine rejects with an error that says what to pass.

`worker: true` starts the worker shipped as `@birchui/pdf/ocr-worker`; a `Worker` you created from that entry yourself is used as is, which is the way to go when your bundler needs to see the `new Worker(new URL(...))` call in your own code. Without `worker` the engine runs on the calling thread and yields to the event loop every 30 ms.

## Images and results

```ts no-check
import { createOcrEngine, toHocrJson, toInvisibleTextLayer, toPlainText } from '@birchui/pdf/ocr';

declare const pixels: ImageData;

const ocr = createOcrEngine();
const page = await ocr.recognizeImage(pixels, { dpi: 300 });

console.info(page.orientation, page.skew, page.dpi, page.confidence);
for (const block of page.blocks)
  for (const paragraph of block.paragraphs)
    for (const line of paragraph.lines)
      console.info(block.columnIndex, line.baseline, line.words.map((word) => `${word.text} (${word.confidence.toFixed(2)})`).join(' '));

const text = toPlainText(page);
const tree = toHocrJson(page);
const layerWords = toInvisibleTextLayer(page);
console.info(text.length, tree.children?.length, layerWords.length, page.regions);
```

- `recognizeImage` takes `{ width, height, data }` with RGBA, RGB or grey bytes, which includes `ImageData`.
- Boxes are `[x1, y1, x2, y2]` in pixels of the image you passed, also when the page was turned or deskewed internally. `orientation` is the clockwise turn that made the page upright, `skew` the angle that was corrected.
- `page.regions` lists figures, ruling lines, table frames and scanner borders that were kept out of the text.
- Words below `minConfidence` (default 0.3) are left out. `decoder: 'beam'` switches to the prefix beam search, and `beam.prior` takes a character prior of your own.

## Documents

```ts no-check
import { openPdfDocument } from '@birchui/pdf/engine';
import { createOcrEngine } from '@birchui/pdf/ocr';

declare const scanBytes: Uint8Array;

const pdf = openPdfDocument(scanBytes);
const ocr = createOcrEngine();

const first = await ocr.recognizePage(pdf, 0);
console.info(first.status, first.result?.text);

const controller = new AbortController();
const rest = await ocr.recognizeDocument(pdf, {
  signal: controller.signal,
  onPage: (page) => console.info(`page ${page.pageIndex + 1}: ${page.status}`),
});
console.info(rest.filter((page) => page.status === 'has-text').length);

const { bytes } = await ocr.makeSearchable(pdf);
console.info(bytes.length);
```

- `recognizeDocument` works on the pages without text and reports `has-text` for the others; `includePagesWithText: true` recognises them as well. `pages` limits the run. `recognizePage` is for one page you picked, so it recognises that page even when it has text; pass `includePagesWithText: false` to skip it then.
- The image of a page is its largest embedded image, which is what a scan consists of. Pass `renderPage: (pageIndex, dpi) => ({ width, height, data, matrix })` to supply a rendering of the whole page at `dpi` (default 300) instead.
- Aborting rejects with an `OcrError` whose `code` is `'aborted'`. Pages finished before that keep their text layer; each page is one undo step.
- The engine is also just the callback of the hook: `pdf.recognizeText({ recognizeText: ocr.recognizeText })`.

```ts no-check
import { openPdfDocument } from '@birchui/pdf/engine';
import { createOcrEngine } from '@birchui/pdf/ocr';

declare const scanBytes: Uint8Array;

const pdf = openPdfDocument(scanBytes);
const ocr = createOcrEngine();
const pages = await pdf.recognizeText({ recognizeText: ocr.recognizeText });
console.info(pages[0].status, pdf.markRedactions(/\b\d{3} \d{4}\b/).length);
```

## Limits

- **Handwriting** is not recognised. Fonts that imitate handwriting are read with several times the error rate of print.
- **Complex and non-Latin scripts** are not supported: see [Supported scripts](#supported-scripts).
- **Low resolution.** The measurements go down to 150 dpi print and 12 to 15 px screen text. Smaller text is enlarged before recognition, but nothing below that was measured; expect accuracy to fall off.
- **Layout.** Reading order comes from an X-Y cut. Columns whose gutter is not a clean vertical gap, for example on a page photographed at an angle, can be read in the wrong order although the words themselves are right. Text over photographs, curved text, vertical text, formulas and stamps across text are not handled. Tables come out row by row without a cell structure.
- **Look-alikes.** There is no dictionary. `O` and `0`, `l`, `I` and `1`, and upper and lower case of letters like `s`, `o`, `c` and `v` are told apart by shape and neighbours only; serial numbers and all-lower-case fragments are where mistakes cluster.
- **Geometry.** Skew is corrected up to 15°, turns by quarters are detected; perspective is not rectified. On a page turned by 90, 180 or 270 degrees the hook writes the words turned the same way, so search hits and selection follow the lines as they are displayed.
- **Text layer fonts.** The hook writes Latin text with Helvetica metrics; words with characters no font of the session can encode are counted in `skippedWords`.
- **Size.** Images above 40 megapixels or 12,000 pixels on a side are scaled down first; `maxPixels` lowers that budget.

## End-to-end check in the viewer

The browser test `e2e/tests/pdf-ocr-end-to-end.spec.ts` builds a scan the way a scanner would: ten lines of 15-point Helvetica are rendered to a 200 dpi image with `pdftoppm` and wrapped as an image-only PDF. It then runs **Recognize text** from the Tools tab in Chrome and in Firefox and uses the result:

| Step | What is checked |
| --- | --- |
| Recognize | 83 of 83 words read correctly in both browsers (100%), also on a page whose scan lies on its side and is shown turned by 90 degrees |
| Search | One hit for a word, placed on the word on the page |
| Select and copy | Dragging over a word selects it and copies it |
| Highlight | The highlight tool marks the line that was dragged over |
| Search and redact | Marking a name and applying removes it from `pdftotext`, from the bytes of the file and from the pixels of the scan |
| Cancel | Cancelling during a six-page run keeps the finished pages, leaves the last without text, and a second run completes the rest |
| Edit scanned text | The edit text tool replaces a recognised number; the saved file extracts the new text and the pixels under it changed; Undo restores it |

This file is clean print at one size, so the figure says the pipeline works end to end, not how the model does on poor scans; the [accuracy table](#accuracy) is the measure for that.

## Privacy

Recognition runs where you call it: in the page, in a worker of the page or in your Node process. The engine makes no network request of its own, loads no code at run time and keeps no copy of images or results beyond the call. Nothing leaves the browser unless your own code sends it.
