ppu-indra-ocr 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE-STATUS.md +15 -7
  2. package/README.md +719 -193
  3. package/cli/commands.js +2 -2
  4. package/cli/help.d.ts +1 -1
  5. package/cli/help.js +3 -2
  6. package/cli/options.d.ts +3 -0
  7. package/cli/options.js +1 -1
  8. package/core/indra-ocr.service.d.ts +19 -7
  9. package/core/indra-ocr.service.js +1 -1
  10. package/core/opencv-image-ops.js +1 -1
  11. package/core/platform.d.ts +2 -0
  12. package/exports.d.ts +2 -2
  13. package/exports.js +1 -1
  14. package/indra/assemble.d.ts +38 -13
  15. package/indra/assemble.js +2 -2
  16. package/indra/document.d.ts +4 -3
  17. package/indra/document.js +1 -1
  18. package/indra/image.d.ts +2 -2
  19. package/indra/lines.d.ts +8 -3
  20. package/indra/lines.js +1 -1
  21. package/indra/lm.d.ts +51 -0
  22. package/indra/lm.js +1 -0
  23. package/indra/npz.d.ts +14 -0
  24. package/indra/npz.js +1 -0
  25. package/indra/order-post.d.ts +9 -0
  26. package/indra/order-post.js +1 -1
  27. package/indra/pipeline.d.ts +30 -17
  28. package/indra/pipeline.js +1 -1
  29. package/indra/rec-preproc.d.ts +14 -2
  30. package/indra/rec-preproc.js +1 -1
  31. package/indra/recognize.d.ts +44 -6
  32. package/indra/recognize.js +1 -1
  33. package/indra/recognizers.d.ts +45 -0
  34. package/indra/recognizers.js +1 -0
  35. package/indra/rtl.d.ts +34 -0
  36. package/indra/rtl.js +1 -0
  37. package/indra/text-runs.d.ts +35 -0
  38. package/indra/text-runs.js +2 -0
  39. package/indra/textlayer.d.ts +43 -16
  40. package/indra/textlayer.js +1 -2
  41. package/indra/ts-image-ops.js +1 -1
  42. package/indra/types.d.ts +39 -7
  43. package/indra/unicode-data.d.ts +4 -0
  44. package/indra/unicode-data.js +1 -0
  45. package/indra/unicode.d.ts +24 -0
  46. package/indra/unicode.js +1 -0
  47. package/indra/upright.d.ts +13 -2
  48. package/indra/upright.js +1 -1
  49. package/indra/vocab.d.ts +3 -1
  50. package/indra/vocab.js +1 -1
  51. package/interface.d.ts +13 -2
  52. package/mobile/platform.mobile.d.ts +1 -0
  53. package/mobile/platform.mobile.js +1 -1
  54. package/model-catalogue.d.ts +76 -20
  55. package/model-catalogue.js +1 -1
  56. package/package.json +1 -1
  57. package/pdf/index.js +1 -1
  58. package/pdf/pdfium.d.ts +2 -0
  59. package/pdf/pdfium.js +1 -1
  60. package/processor/indra-ocr.service.d.ts +7 -2
  61. package/processor/indra-ocr.service.js +1 -1
  62. package/processor/platform.node.d.ts +1 -0
  63. package/processor/platform.node.js +1 -1
  64. package/web/platform.web.d.ts +1 -0
  65. package/web/platform.web.js +1 -1
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # ppu-indra-ocr
2
2
 
3
- TypeScript SDK for [Indra OCR](https://github.com/datalab-to/indra) by
4
- Datalab. It reads images and PDFs into markdown, plain text, or JSON with
5
- line boxes and layout blocks, on ONNX Runtime.
3
+ [![NPM](https://img.shields.io/npm/dw/ppu-indra-ocr)](https://www.npmjs.com/package/ppu-indra-ocr) [![npm version](https://img.shields.io/npm/v/ppu-indra-ocr)](https://www.npmjs.com/package/ppu-indra-ocr) [![JSR](https://jsr.io/badges/@snowfluke/ppu-indra-ocr)](https://jsr.io/@snowfluke/ppu-indra-ocr) [![Provenance](https://img.shields.io/badge/npm-signed%20provenance-blue?logo=npm)](https://www.npmjs.com/package/ppu-indra-ocr#provenance) [![License: Apache-2.0](https://img.shields.io/npm/l/ppu-indra-ocr)](./LICENSE) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/badge)](https://scorecard.dev/viewer/?uri=github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr) [![Socket Badge](https://socket.dev/api/badge/npm/package/ppu-indra-ocr)](https://socket.dev/npm/package/ppu-indra-ocr)
6
4
 
7
- > **Status: early development (0.x).** The API may change between minor versions.
5
+ Indra OCR in TypeScript. Images and PDFs in; markdown, plain text, line boxes and layout blocks out. The whole [Indra OCR](https://github.com/datalab-to/indra) pipeline by Datalab runs on ONNX Runtime: page orientation, deskew, line detection, recognition, reading order, layout and markdown. Runs anywhere JavaScript runs: Node.js, Bun, Deno, web browsers, web workers, browser extensions, and React Native (iOS/Android). Docker & CLI supported. [Try it in your browser](https://ppu-indra-ocr.snowfluke.workers.dev/).
6
+
7
+ Need it as an HTTP service? Dockerized? Spin up the REST API here: [apps/serve](/apps/serve/README.md). Need a CLI instead? See [Command Line](#command-line). Are you an AI agent? Learn the API quickly with the skill in the `skill-ppu-indra-ocr` folder.
8
8
 
9
9
  > [!WARNING]
10
10
  > **Read Datalab's license before you use this package.**
@@ -24,92 +24,189 @@ line boxes and layout blocks, on ONNX Runtime.
24
24
  > Datalab, and what may change. This is a community project. Datalab does not
25
25
  > endorse it.
26
26
 
27
- ## Table of contents
27
+ ![ppu-indra-ocr demo](https://raw.githubusercontent.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/refs/heads/main/assets/ppu-indra-ocr-demo.jpg)
28
28
 
29
- - [What it does](#what-it-does)
30
- - [Runtime support](#runtime-support)
31
- - [Installation](#installation)
32
- - [Usage](#usage)
33
- - [The page result](#the-page-result)
34
- - [Running the stages yourself](#running-the-stages-yourself)
35
- - [PDF input](#pdf-input)
36
- - [Batches](#batches)
37
- - [Math](#math)
38
- - [Processing engine](#processing-engine)
39
- - [Web and browser](#web-and-browser)
40
- - [React Native](#react-native)
41
- - [Command line](#command-line)
42
- - [REST server](#rest-server)
43
- - [Models and languages](#models-and-languages)
44
- - [Configuration reference](#configuration-reference)
45
- - [Limitations](#limitations)
46
- - [How the port is checked](#how-the-port-is-checked)
47
- - [License and credits](#license-and-credits)
29
+ ```ts
30
+ import { IndraOcrService } from "ppu-indra-ocr";
48
31
 
49
- ## What it does
32
+ const service = new IndraOcrService();
33
+ await service.initialize();
50
34
 
51
- Indra OCR is a small CPU OCR pipeline: about 18 MB of ONNX models, with a
52
- 1M-parameter line recognizer. This package runs the whole pipeline in
53
- TypeScript:
35
+ const page = await service.convert(await Bun.file("scan.png").arrayBuffer());
36
+ console.log(page.markdown);
54
37
 
38
+ await service.destroy();
55
39
  ```
56
- orient.onnx (page upright?) -> skew fix -> det.onnx (text lines)
57
- -> script.onnx (Chinese line?) -> rec.onnx | rec_cjk.onnx (text)
58
- -> order.onnx (reading order, layout labels, blocks) -> markdown
59
- [math: true] mathcls -> math encoder -> decoder (LaTeX)
60
- [PDF] the PDF's text layer where it can be trusted, OCR elsewhere
61
- ```
62
-
63
- Each stage is also a method, so you can run the whole page with one call or
64
- chain the stages yourself.
65
40
 
66
- ## Runtime support
41
+ ## Table of Contents
67
42
 
68
- | Runtime | Entry | ONNX Runtime | Status |
69
- | -------------------------- | ---------------------- | -------------------------- | -------------------------------------- |
70
- | Node.js, Bun | `ppu-indra-ocr` | `onnxruntime-node` | Tested |
71
- | Browsers, web workers | `ppu-indra-ocr/web` | `onnxruntime-web` (wasm) | Tested in Bun; run by hand in Chromium |
72
- | React Native (iOS/Android) | `ppu-indra-ocr/mobile` | `onnxruntime-react-native` | Type-checked, not run on a device yet |
73
- | PDF input (any of above) | `ppu-indra-ocr/pdf` | - | Tested in Bun |
43
+ - [Why ppu-indra-ocr?](#why-ppu-indra-ocr)
44
+ - [Runtime Support](#runtime-support)
45
+ - [Installation](#installation)
46
+ - [CLI (global install)](#cli-global-install)
47
+ - [Standalone Binaries](#standalone-binaries)
48
+ - [Core Usage](#core-usage)
49
+ - [Basic Conversion](#basic-conversion)
50
+ - [The Page Result](#the-page-result)
51
+ - [Running the Stages Yourself](#running-the-stages-yourself)
52
+ - [Custom Models](#custom-models)
53
+ - [Detection Only](#detection-only)
54
+ - [Command Line](#command-line)
55
+ - [Batch Conversion](#batch-conversion)
56
+ - [PDF Input](#pdf-input)
57
+ - [Math](#math)
58
+ - [Orientation and Deskew](#orientation-and-deskew)
59
+ - [Processing Engine](#processing-engine)
60
+ - [Web / Browser Support](#web--browser-support)
61
+ - [Using a Bundler](#using-a-bundler-vite-webpack-etc)
62
+ - [Web Workers](#web-workers)
63
+ - [CDN (No Bundler)](#cdn-no-bundler)
64
+ - [WebGPU Acceleration](#webgpu-acceleration)
65
+ - [Multithreaded WASM (Cross-Origin Isolation)](#multithreaded-wasm-cross-origin-isolation)
66
+ - [React Native (Mobile)](#react-native-mobile)
67
+ - [Models and Language Support](#models-and-language-support)
68
+ - [Model Presets](#model-presets)
69
+ - [Indra OCR Models](#indra-ocr-models)
70
+ - [Cache Location](#cache-location-node--bun)
71
+ - [Languages](#languages)
72
+ - [Model Output Limitations](#model-output-limitations)
73
+ - [Configuration Reference](#configuration-reference)
74
+ - [IndraOptions](#indraoptions)
75
+ - [ModelSources](#modelsources)
76
+ - [BatchOptions](#batchoptions)
77
+ - [ConvertPdfOptions](#convertpdfoptions)
78
+ - [SessionOptions](#sessionoptions)
79
+ - [Model host mirror](#model-host-mirror)
80
+ - [Benchmark](#benchmark)
81
+ - [How the Port Is Checked](#how-the-port-is-checked)
82
+ - [Ecosystem](#ecosystem)
83
+ - [Contributing](#contributing)
84
+ - [License](#license)
85
+ - [Support](#support)
86
+ - [Scripts](#scripts)
87
+
88
+ ## Why ppu-indra-ocr?
89
+
90
+ - **The whole page, not just the text.** Orientation (vertical writing too), deskew up to 45 degrees, line detection, recognizers for Latin, CJK, right-to-left and other scripts, reading order, layout labels, and markdown with headings, lists and tables, in one `convert()` call.
91
+ - **PDFs too.** Uses a PDF's text layer where it can be trusted and OCR where it cannot, page by page.
92
+ - **Small models.** About 9 MB of ONNX models load at start; the other script recognizers and the language models load when a page needs them. Pinned to one upstream revision per [model preset](#model-presets): `v1.1` (Indra OCR 1.1, the default) or `v3.1` (the first release).
93
+ - **Matches the reference.** On the `opencv` engine, line text, layout blocks and markdown match the Python `indra-ocr` exactly on every test page. See [How the Port Is Checked](#how-the-port-is-checked).
94
+ - **Runs everywhere**, Node.js, Bun, Deno, web browsers, web workers, browser extensions, and React Native (iOS/Android), on the same runtime adapters as [ppu-paddle-ocr](https://github.com/PT-Perkasa-Pilar-Utama/ppu-paddle-ocr).
95
+ - **Composable.** Every stage is a method, so you can run one stage, swap a stage, or chain your own pipeline.
96
+ - **TypeScript**, full type definitions.
97
+
98
+ ## Runtime Support
99
+
100
+ The same package, the same API, every JavaScript runtime:
101
+
102
+ | Runtime | How to install | Try it |
103
+ | -------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
104
+ | **Node.js** | `npm install ppu-indra-ocr onnxruntime-node` | [npm package](https://www.npmjs.com/package/ppu-indra-ocr) |
105
+ | **Bun** | `bun add ppu-indra-ocr onnxruntime-node` | [npm package](https://www.npmjs.com/package/ppu-indra-ocr) |
106
+ | **Deno** | `deno add jsr:@snowfluke/ppu-indra-ocr` | [JSR package](https://jsr.io/@snowfluke/ppu-indra-ocr) |
107
+ | **Web browser** | `npm install ppu-indra-ocr onnxruntime-web` (import `/web` subpath) | [Live demo](https://ppu-indra-ocr.snowfluke.workers.dev/) |
108
+ | **Web worker** | Same as web; the `/web` subpath runs in workers. | [Web Workers](#web-workers) |
109
+ | **Browser extension** | Same as web; bundle `ppu-indra-ocr/web` with your extension's bundler. | [Web / Browser Support](#web--browser-support) |
110
+ | **Mobile (React Native)** | `npm install ppu-indra-ocr onnxruntime-react-native @shopify/react-native-skia` (import `/mobile` subpath) | [React Native](#react-native-mobile) |
111
+ | **PDF input** (any of the above) | `npm install @embedpdf/pdfium` (import `/pdf` subpath) | [PDF Input](#pdf-input) |
74
112
 
75
113
  ## Installation
76
114
 
77
115
  ```bash
78
- bun add ppu-indra-ocr onnxruntime-node
79
- # PDF input (optional):
80
- bun add @embedpdf/pdfium
116
+ npm install ppu-indra-ocr onnxruntime-node onnxruntime-web
81
117
  ```
82
118
 
83
- ONNX Runtime and pdfium are peer dependencies: install the ones your runtime
84
- needs (`onnxruntime-web` in a browser, `onnxruntime-react-native` and
85
- `@shopify/react-native-skia` on React Native).
119
+ Omit `onnxruntime-node` or `onnxruntime-web` depending on your target environment (Node/Bun vs browser). Add `@embedpdf/pdfium` for PDF input.
86
120
 
87
- The first `initialize()` downloads the models (about 18 MB, 38 MB with math)
88
- from Datalab's Hugging Face repository, pinned to one revision, and caches
89
- them in `~/.cache/ppu-indra-ocr` on Node.
121
+ The first `initialize()` downloads the base models (about 9 MB, 29 MB with math) from Datalab's Hugging Face repository, pinned to one revision, and caches them in `~/.cache/ppu-indra-ocr` on Node and Bun. The CJK, right-to-left and other-script recognizers (5 to 10 MB each) and the language models (12 to 19 MB each) download the first time a page needs them. That can happen on the first page: on a Latin receipt, one unsure line can pull `rec_rtl.onnx` and `lm.npz` (about 20 MB) in the middle of `convert()`. `IndraOcrService.downloadModels()` (or `ppu-indra-ocr download-models`) fetches them all up front.
90
122
 
91
123
  **When the models download, you accept Datalab's license for the weights.**
92
124
  Check [LICENSE-STATUS.md](LICENSE-STATUS.md) first.
93
125
 
94
- ## Usage
126
+ ### CLI (global install)
127
+
128
+ ```bash
129
+ npm install -g ppu-indra-ocr onnxruntime-node # or: bun add -g ppu-indra-ocr onnxruntime-node
130
+ ppu-indra-ocr convert scan.png
131
+ ```
132
+
133
+ This puts a `ppu-indra-ocr` command on your `PATH`. See [Command Line](#command-line) for all commands.
134
+
135
+ <details>
136
+ <summary>Notes on the global install</summary>
137
+
138
+ - **`onnxruntime-node` is required.** It is an optional peer dependency (native binaries), so install it alongside the CLI. Add `@embedpdf/pdfium` globally too if you want PDF input.
139
+ - **bun**: ensure `~/.bun/bin` is on your `PATH` (npm's global bin usually already is).
140
+ - **Updates are manual.** Re-run the install with `@latest` to upgrade.
141
+ - **Node or Bun must be present.** This is the Node/Bun build, not a standalone binary. For that, see [Standalone Binaries](#standalone-binaries) below.
142
+
143
+ </details>
144
+
145
+ ### Standalone Binaries
146
+
147
+ Every release attaches self-contained executables, no Node, Bun, or `npm install` required. Download, extract, run:
148
+
149
+ ```bash
150
+ curl -L https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/releases/latest/download/ppu-indra-ocr-linux-x64.tar.gz | tar xz
151
+ ./ppu-indra-ocr-linux-x64 convert scan.png
152
+ ```
153
+
154
+ | Asset | Platform |
155
+ | :---------------------------------- | :------------------------------------------------------------- |
156
+ | `ppu-indra-ocr-linux-x64.tar.gz` | Linux x86-64 (glibc; Debian, Ubuntu, Fedora, ...) |
157
+ | `ppu-indra-ocr-linux-arm64.tar.gz` | Linux ARM64 (glibc; Raspberry Pi OS 64-bit, AWS Graviton, ...) |
158
+ | `ppu-indra-ocr-darwin-arm64.tar.gz` | macOS on Apple Silicon |
159
+ | `ppu-indra-ocr-windows-x64.zip` | Windows x86-64 (contains the `.exe`) |
160
+
161
+ Intel Macs and Alpine (musl) are not covered, onnxruntime ships no darwin-x64 or musl builds; use `npx`/`bunx` there.
162
+
163
+ <details>
164
+ <summary>Size, slim variant, and OS warnings</summary>
165
+
166
+ - **Size and first run.** 53-69 MB download depending on the platform, about 165 MB extracted on macOS (the executable embeds the Bun runtime, ONNX Runtime, pdfium and the image engines). Models still download to `~/.cache/ppu-indra-ocr` on first run, exactly like the npm CLI.
167
+ - **Slim variant.** Each target also ships a `-slim` archive (e.g. `ppu-indra-ocr-linux-x64-slim.tar.gz`) that excludes the OpenCV engine: about 30 MB smaller extracted, 4-5 MB smaller to download. It always uses the `canvas-native` engine and rejects `--engine opencv`. Pick slim for disk and memory footprint; pick full if you want results that match the Python reference exactly.
168
+ - **macOS Gatekeeper.** The binaries are ad-hoc signed but not Apple-notarized. If macOS blocks a downloaded binary, clear the quarantine flag: `xattr -d com.apple.quarantine ./ppu-indra-ocr-darwin-arm64` (or right-click, Open, once).
169
+ - **Windows SmartScreen.** Unrecognized-app warning on first run: "More info", then "Run anyway".
170
+
171
+ </details>
172
+
173
+ <details>
174
+ <summary>Verify a download (Sigstore + SLSA)</summary>
175
+
176
+ Both checks run against the archive, before extraction; both artifacts are attached per release.
177
+
178
+ ```bash
179
+ # Sigstore signature (bundle is attached next to each archive)
180
+ cosign verify-blob ppu-indra-ocr-linux-x64.tar.gz \
181
+ --bundle ppu-indra-ocr-linux-x64.tar.gz.sigstore.json \
182
+ --certificate-identity-regexp "github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr" \
183
+ --certificate-oidc-issuer https://token.actions.githubusercontent.com
184
+
185
+ # GitHub build provenance (SLSA)
186
+ gh attestation verify ppu-indra-ocr-linux-x64.tar.gz --repo PT-Perkasa-Pilar-Utama/ppu-indra-ocr
187
+ ```
188
+
189
+ </details>
190
+
191
+ ## Core Usage
192
+
193
+ ### Basic Conversion
95
194
 
96
195
  ```ts
97
196
  import { IndraOcrService } from "ppu-indra-ocr";
98
197
 
99
- const service = new IndraOcrService();
198
+ const service = new IndraOcrService({ verbose: true });
100
199
  await service.initialize();
101
200
 
102
- const page = await service.convert(await Bun.file("scan.png").arrayBuffer());
201
+ const page = await service.convert(await Bun.file("./assets/receipt.jpg").arrayBuffer());
103
202
  console.log(page.markdown);
104
203
 
105
204
  await service.destroy();
106
205
  ```
107
206
 
108
- `convert` takes encoded image bytes (`ArrayBuffer` or `Uint8Array`: PNG, JPEG,
109
- WebP and the other formats your canvas decodes), a canvas, or gray pixels
110
- `{ data: Uint8Array, width, height }`.
207
+ `convert` takes encoded image bytes (`ArrayBuffer` or `Uint8Array`: PNG, JPEG, WebP and the other formats your canvas decodes), a canvas, or gray pixels `{ data: Uint8Array, width, height }`.
111
208
 
112
- For one image, the one-shot functions load the models, run, and release them:
209
+ For a single image, `ocr()` and `detect()` manage a short-lived service for you. Create an `IndraOcrService` when processing more than one image so the models remain initialized between calls.
113
210
 
114
211
  ```ts
115
212
  import { detect, ocr } from "ppu-indra-ocr";
@@ -118,7 +215,7 @@ const page = await ocr(imageBytes);
118
215
  const boxes = await detect(imageBytes); // [x0, y0, x1, y1, score][]
119
216
  ```
120
217
 
121
- ## The page result
218
+ ### The Page Result
122
219
 
123
220
  ```ts
124
221
  type Page = {
@@ -134,15 +231,12 @@ type Page = {
134
231
  };
135
232
  ```
136
233
 
137
- Block labels: `Text`, `Section-Header`, `Page-Header`, `Page-Footer`,
138
- `List-Group`, `Table`, `Caption`, `Footnote`, `Table-Of-Contents`, `Form`.
139
- Page headers and footers are left out of the markdown unless you pass
140
- `furniture: true`. Boxes are in the upright page's pixels.
234
+ Block labels: `Text`, `Section-Header`, `Page-Header`, `Page-Footer`, `List-Group`, `Table`, `Caption`, `Footnote`, `Table-Of-Contents`, `Form`. Page headers and footers are left out of the markdown unless you pass `furniture: true`; they stay in `lines` and `blocks`. Boxes are in the upright page's pixels.
141
235
 
142
- ## Running the stages yourself
236
+ ### Running the Stages Yourself
143
237
 
144
238
  ```ts
145
- const { turns } = await service.orient(image); // quarter turns, from orient.onnx
239
+ const { turns } = await service.orient(image); // quarter turns, or 4 for vertical writing
146
240
  const { image: upright, skew } = await service.straighten(image, turns);
147
241
  const boxes = (await service.detect(upright)).map(([x0, y0, x1, y1]) => [x0, y0, x1, y1] as const);
148
242
  const lines = await service.recognize(upright, boxes); // text, confidence, character positions
@@ -150,193 +244,625 @@ const texts = lines.map((l) => l.text);
150
244
  const { order, cls, same } = await service.order(boxes, texts, upright.width, upright.height);
151
245
  ```
152
246
 
153
- `recognize` takes boxes from any detector, one line per box. Boxes should hug
154
- the text: the recognizer adds 0.2 x the box height above and below and 0.3 x
155
- on each side. Trim boxes that carry their own padding first. PaddleOCR's
156
- boxes, for example, are padded to 1.8 x the text height.
247
+ `recognize` takes boxes from any detector, one line per box. Boxes should hug the text: the recognizer crops 0.3 x the box height on each side and 0.2 x above and below (on v1.1 the main recognizer also sees 1.6 x the height above and below as context). Trim boxes that carry their own padding first; PaddleOCR's boxes, for example, are padded to 1.8 x the text height. For a vertical page, pass the page turned by `straighten(image, 4)` and `recognize(image, boxes, true)`.
248
+
249
+ `toMarkdown`, `joinLines` and `orderXYCut` are exported as plain functions. `service.pipeline` gives the lower-level stages (line splitting, assembly) when you need them. `readMath(image, boxes)` reads boxes as text with inline LaTeX on a service created with `math: true`.
250
+
251
+ ### Custom Models
252
+
253
+ Every model file has a role. Pass `models` to read some or all of them from file paths (Node/Bun), URLs, or `ArrayBuffer`s; files you leave out come from the default repository:
254
+
255
+ ```ts
256
+ import { IndraOcrService, MODEL_FILES } from "ppu-indra-ocr";
257
+
258
+ // One file from elsewhere
259
+ const service = new IndraOcrService({
260
+ models: { det: "./models/det.onnx" },
261
+ });
262
+
263
+ // Every file from a local folder (air-gapped hosts)
264
+ const local = new IndraOcrService({
265
+ models: Object.fromEntries(
266
+ Object.entries(MODEL_FILES).map(([role, file]) => [role, `/opt/indra-models/${file}`])
267
+ ),
268
+ });
269
+ ```
270
+
271
+ Roles: `det`, `rec`, `script`, `orient`, `order`, `meta`; the script recognizers `recCjk`, `recRtl`, `recWorld`; the language models `lm`, `lmCjk`, `lmWorld`; and with math `mathCls`, `mathEnc`, `mathDecInit`, `mathDecStep`, `mathMeta`. `MODEL_FILES` maps each role to its file name, `MODEL_PRESETS` holds each preset's pinned commit and file list, and `defaultModelUrl(role, preset)` gives the default URL. A role the preset does not have (v3.1 has no `recRtl`) and that you do not pass stays off.
272
+
273
+ ### Detection Only
274
+
275
+ `detect()` runs only the detection model, no recognition, and returns the line boxes it finds with their scores. Useful when you only need layout (where the text is), or want to feed the boxes into your own pipeline.
276
+
277
+ ```ts
278
+ const boxes = await service.detect(imageBytes);
279
+ // boxes: [x0, y0, x1, y1, score][] in image pixels
280
+ ```
281
+
282
+ `detect()` runs on the image as given. Run `orient` and `straighten` first when the input may be turned or tilted. Also available as the CLI `detect` command and the serve app's `POST /v1/detect`, see [Command Line](#command-line) and [`apps/serve`](/apps/serve/README.md).
283
+
284
+ ## Command Line
285
+
286
+ The package ships a `bin`, so you can OCR without writing any code. In a project that has `ppu-indra-ocr` and `onnxruntime-node` installed, `bunx`/`npx` resolve the local install directly; for zero-install runs use `npx -p onnxruntime-node -p ppu-indra-ocr ppu-indra-ocr <args>` or a [global install](#cli-global-install):
287
+
288
+ ```bash
289
+ # one image or PDF -> markdown on stdout
290
+ bunx ppu-indra-ocr convert paper.pdf
291
+
292
+ # many images (glob), one output file per input
293
+ bunx ppu-indra-ocr convert "scans/*.png" --out results/
294
+
295
+ # structured JSON, one object per page
296
+ bunx ppu-indra-ocr convert scan.png --format json --pretty
297
+
298
+ # force OCR on a PDF, read math as LaTeX, print per-page timings
299
+ bunx ppu-indra-ocr convert paper.pdf --mode ocr --math --timings
300
+
301
+ # detection only: line boxes as JSON
302
+ bunx ppu-indra-ocr detect receipt.jpg
303
+
304
+ # zero-install (no local ppu-indra-ocr): npx can pull both packages
305
+ npx -p onnxruntime-node -p ppu-indra-ocr ppu-indra-ocr convert scan.png
306
+
307
+ # the smaller first-release models, or no language models
308
+ bunx ppu-indra-ocr convert scan.png --model v3.1
309
+ bunx ppu-indra-ocr convert scan.png --no-lm
310
+
311
+ # pre-warm / clear the model cache, list the model presets and files
312
+ bunx ppu-indra-ocr download-models
313
+ bunx ppu-indra-ocr clear-cache
314
+ bunx ppu-indra-ocr models
315
+ ```
316
+
317
+ | Flags | Applies to | Purpose |
318
+ | :-------------------------------------------------------------- | :----------- | :---------------------------------------------------------- |
319
+ | `--format md\|text\|json`, `--out <dir>` | `convert` | Output format; one file per input (`.md`, `.txt`, `.jsonl`) |
320
+ | `--math`, `--keep-furniture`, `--engine`, `--timings` | `convert` | Math as LaTeX, keep headers and footers, engine, timings |
321
+ | `--mode auto\|ocr\|text`, `--dpi`, `--max-pages`, `--password` | PDFs | Text layer or OCR, render resolution, page cap, password |
322
+ | `--no-image-ocr` | PDFs | Skip OCR inside images on text-layer pages |
323
+ | `--model v1.1\|v3.1`, `--no-lm` | all commands | Model preset; no language models |
324
+ | `--model-dir <dir>`, `--execution-providers <list>` | all commands | Read models from a folder; ONNX providers (e.g. `cuda,cpu`) |
325
+ | `-o`/`--output <file>`, `--pretty`, `-q`/`--quiet`, `--verbose` | all commands | Output destination and format, logging |
326
+
327
+ Converted text goes to **stdout**; progress and logs go to **stderr**, so output pipes cleanly. Exit codes: `0` success, `1` runtime error, `2` usage error.
328
+
329
+ Run `bunx ppu-indra-ocr help` for the full reference.
330
+
331
+ ## Batch Conversion
332
+
333
+ `convertBatch()` runs `convert()` over many images with **bounded concurrency**: at most `concurrency` images are decoded and in flight at once, so memory stays in check. Results come back **index-aligned** to the inputs, whatever order they finish in.
334
+
335
+ ```ts
336
+ const pages = await service.convertBatch([buf1, buf2, buf3]);
337
+ pages.forEach((p, i) => console.log(i, p.markdown));
338
+ ```
339
+
340
+ | You want | Use |
341
+ | :---------------------------------- | :------------------------------------ |
342
+ | More images in flight | `{ concurrency: 2 }` |
343
+ | One bad image not to kill the batch | `{ settle: true }` |
344
+ | Progress or cancellation | `{ onProgress, signal }` |
345
+ | Results as they finish | `convertStream()` |
346
+ | An input list too big for memory | pass an `Iterable` or `AsyncIterable` |
347
+
348
+ Full surface: [`BatchOptions`](#batchoptions).
349
+
350
+ **Concurrency.** Defaults to `1`. Each page allocates large tensors (a whole page goes through detection at a 1024 px long side, then layout and reading order), so more pages at once mostly add memory. Raise it only after measuring on your hardware.
351
+
352
+ **Failures.** With `settle: true` the call never rejects; each slot becomes `{ index, status, value | reason }`:
353
+
354
+ ```ts
355
+ const results = await service.convertBatch(images, { settle: true });
356
+ for (const r of results) {
357
+ if (r.status === "fulfilled") console.log(r.value.markdown);
358
+ else console.error("failed:", r.reason);
359
+ }
360
+ ```
361
+
362
+ **Progress and cancellation** use the usual primitives:
363
+
364
+ ```ts
365
+ const ac = new AbortController();
366
+ await service.convertBatch(images, {
367
+ signal: ac.signal,
368
+ onProgress: (done, total) => console.log(`${done}/${total}`),
369
+ });
370
+ ```
371
+
372
+ **Streaming.** `convertStream()` yields each result as it finishes, so the whole batch is never buffered. Each item carries its input `index` for reordering:
373
+
374
+ ```ts
375
+ for await (const item of service.convertStream(images)) {
376
+ if (item.status === "fulfilled") console.log(item.index, item.value.markdown);
377
+ }
378
+ ```
157
379
 
158
- `toMarkdown`, `joinLines` and `orderXYCut` are exported as plain functions.
159
- `service.pipeline` gives the lower-level stages (line splitting, assembly)
160
- when you need them.
380
+ Both methods accept any `Iterable` or `AsyncIterable` of inputs, so a directory walk or a queue never has to be materialized in memory at once.
161
381
 
162
- ## PDF input
382
+ ## PDF Input
163
383
 
164
384
  ```ts
165
385
  import { IndraOcrService } from "ppu-indra-ocr";
166
- import { convertPdf } from "ppu-indra-ocr/pdf";
386
+ import { convertPdf, isPdf } from "ppu-indra-ocr/pdf";
167
387
 
168
388
  const service = new IndraOcrService();
169
389
  await service.initialize();
170
- const pages = await convertPdf(service, pdfBytes, { mode: "auto" });
390
+
391
+ const pages = isPdf(bytes)
392
+ ? await convertPdf(service, bytes, { mode: "auto" })
393
+ : [await service.convert(bytes)];
171
394
  ```
172
395
 
173
396
  | Option | Default | Meaning |
174
397
  | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
175
398
  | `mode` | `"auto"` | `auto`: the text layer where it passes the checks, OCR elsewhere. `ocr`: always OCR. `text`: the text layer even when the checks fail |
176
399
  | `dpi` | `200` | Render resolution for OCR |
177
- | `pdfOrder` | `true` | Keep the PDF content order when it is coherent |
178
400
  | `imageOcr` | `true` | On text-layer pages, OCR lines with no text-layer characters (text in images) |
179
401
  | `maxPages` | all | Read at most this many pages |
180
402
  | `password` | - | Password of an encrypted PDF |
181
403
 
182
- The text layer is checked first: invisible text (an OCR layer), broken font
183
- maps, and runs with no ink under them send the page to OCR. A page that fails
184
- comes back with `source: "error"` and the reason in `note`; a file that cannot
185
- be opened throws. pdfium runs as WebAssembly (`@embedpdf/pdfium`); a browser
186
- fetches its wasm from jsDelivr unless you pass `loadPdfium(wasmBytesOrUrl)`.
187
- `isPdf(bytes)` is exported from every entry to route files without loading
188
- pdfium.
404
+ The text layer is checked first: invisible text (an OCR layer), broken font maps, right-to-left letters stored in visual order, and runs with no ink under them send the page to OCR. A table set sideways, a page turned by its `/Rotate`, and vertical writing are read upright from the text layer; sideways labels inside a page become their own lines. A page that fails comes back with `source: "error"` and the reason in `note`; a file that cannot be opened throws. pdfium runs as WebAssembly (`@embedpdf/pdfium`); a browser fetches its wasm from jsDelivr unless you pass `pdfium: await loadPdfium(wasmBytesOrUrl)`. `isPdf(bytes)` is exported from every entry to route files without loading pdfium. On Node and Bun, set `PPU_INDRA_OCR_PDFIUM_WASM` to a local `pdfium.wasm` path to load it from there instead of `node_modules`.
189
405
 
190
- ## Batches
406
+ ## Math
191
407
 
192
408
  ```ts
193
- const pages = await service.convertBatch(images, { concurrency: 1 });
194
- const settled = await service.convertBatch(images, { settle: true }); // { index, status, value | reason }[]
195
-
196
- for await (const r of service.convertStream(images)) console.log(r.index, r.status);
409
+ const service = new IndraOcrService({ math: true });
197
410
  ```
198
411
 
199
- `concurrency` defaults to 1: each page allocates large tensors, so more pages
200
- at once mostly add memory. `signal` aborts, `onProgress` reports each image.
412
+ A classifier finds lines that hold math, and an attention decoder reads them as text with inline LaTeX (`we have $x _ { i } \leq 1$`). A reading replaces a line only when it holds math and its mean token probability is 0.9 or more. Math loads four more models and is slower on pages that have it.
201
413
 
202
- ## Math
414
+ ## Orientation and Deskew
415
+
416
+ There is nothing to compose: `convert()` measures the tilt on a page preview, turns the page upright with `orient.onnx` (90, 180 and 270 degree turns) and straightens tilts up to 45 degrees before detection, on both presets. `page.rotation` and `page.skew` report what was undone, and boxes come back in the upright page's pixels. A page set in vertical columns (Chinese, Japanese) is read turned, columns as lines, with `page.vertical` set and boxes on the page as it is. Call `service.orient()` and `service.straighten()` directly when you want those stages alone. For general image preprocessing (grayscale, thresholding, contours), see [ppu-ocv](https://github.com/PT-Perkasa-Pilar-Utama/ppu-ocv).
417
+
418
+ ## Processing Engine
419
+
420
+ Two image processing backends are available for resizing and warping:
421
+
422
+ | Engine | Default | OpenCV Required | Notes |
423
+ | :---------------- | :----------: | :-------------: | :--------------------------------------------------------------------- |
424
+ | `"opencv"` | Node and Bun | Yes | OpenCV.js through `ppu-ocv`. Results match the Python reference. |
425
+ | `"canvas-native"` | Web, mobile | No | Plain TypeScript. Smaller; within a token-F1 of 0.98 of the reference. |
203
426
 
204
427
  ```ts
205
- const service = new IndraOcrService({ math: true });
428
+ // OpenCV (default on Node and Bun)
429
+ const service = new IndraOcrService();
430
+
431
+ // Canvas-native (no OpenCV dependency)
432
+ const service = new IndraOcrService({ engine: "canvas-native" });
206
433
  ```
207
434
 
208
- A classifier finds lines that hold math, and an attention decoder reads them
209
- as text with inline LaTeX (`we have $x _ { i } \leq 1$`). A reading replaces a
210
- line only when it holds math and its mean token probability is 0.9 or more.
211
- Math loads four more models and is slower on pages that have it.
435
+ The opencv engine runs the same OpenCV release (5.0) as the reference. On the web, `engine: "opencv"` needs OpenCV.js on the page first; the library does not fetch it (about 10 MB):
436
+
437
+ ```html
438
+ <script src="https://cdn.jsdelivr.net/npm/@techstark/opencv-js@5.0.0-release.1/dist/opencv.js"></script>
439
+ ```
212
440
 
213
- ## Processing engine
441
+ Without OpenCV.js on `globalThis.cv`, `initialize()` throws and says so.
214
442
 
215
- | Engine | Image operations | Results | Default on |
216
- | ----------------- | ----------------------------- | ------------------------------------- | ----------- |
217
- | `"opencv"` | OpenCV.js (through `ppu-ocv`) | Match the Python reference | Node, Bun |
218
- | `"canvas-native"` | Plain TypeScript, no OpenCV | Within token-F1 0.98 of the reference | Web, mobile |
443
+ ## Web / Browser Support
219
444
 
220
- The opencv engine runs the same OpenCV release (5.0) as the reference. The
221
- canvas-native engine is smaller and runs anywhere, with slightly different
222
- resampling.
445
+ Import from `ppu-indra-ocr/web` for browser-native capabilities (`HTMLCanvasElement`, `OffscreenCanvas`, `fetch` buffering).
223
446
 
224
- ## Web and browser
447
+ ### Using a Bundler (Vite, Webpack, etc.)
225
448
 
226
449
  ```ts
227
450
  import { IndraOcrService } from "ppu-indra-ocr/web";
228
451
 
229
452
  const service = new IndraOcrService(); // canvas-native, wasm
230
453
  await service.initialize();
454
+
455
+ const file = document.getElementById("upload").files[0];
231
456
  const page = await service.convert(await file.arrayBuffer());
457
+ console.log(page.markdown);
458
+ ```
459
+
460
+ Models are fetched from the default URLs or from `models`.
461
+
462
+ ### Web Workers
463
+
464
+ Keep the service inside a worker and send image bytes across the boundary, so inference never blocks the main thread:
465
+
466
+ ```ts
467
+ // worker.ts
468
+ import { IndraOcrService } from "ppu-indra-ocr/web";
469
+
470
+ const service = new IndraOcrService();
471
+ const ready = service.initialize();
472
+
473
+ self.onmessage = async (event: MessageEvent<ArrayBuffer>) => {
474
+ await ready;
475
+ const page = await service.convert(event.data);
476
+ self.postMessage(page);
477
+ };
478
+ ```
479
+
480
+ ```ts
481
+ // main.ts
482
+ const worker = new Worker(new URL("./worker.ts", import.meta.url), {
483
+ type: "module",
484
+ });
485
+ worker.onmessage = (event) => console.log(event.data.markdown);
486
+
487
+ const bytes = await file.arrayBuffer();
488
+ worker.postMessage(bytes, [bytes]); // transferred, not copied
489
+ ```
490
+
491
+ Notes:
492
+
493
+ - A worker is the right home for OCR. On the main thread, inference blocks the page until the whole image is done.
494
+ - Cross-origin isolation still governs WASM threading, see [Multithreaded WASM](#multithreaded-wasm-cross-origin-isolation). It is a property of the page, not of the worker.
495
+ - `isWebWorker()` is exported if you need to branch on the scope yourself.
496
+
497
+ ```ts
498
+ import { isWebWorker } from "ppu-indra-ocr/web";
232
499
  ```
233
500
 
234
- Models are fetched from the default URLs or from `models`. ONNX Runtime runs
235
- on wasm unless `session.executionProviders` asks for more; WebGPU is untested
236
- with these models.
501
+ ### CDN (No Bundler)
237
502
 
238
- `engine: "opencv"` matches the reference exactly, but the page must load
239
- OpenCV.js first. The library does not fetch it (about 10 MB):
503
+ See the [live demo](https://ppu-indra-ocr.snowfluke.workers.dev/) for a complete ESM/CDN setup with an import map.
504
+
505
+ ### WebGPU Acceleration
506
+
507
+ ONNX Runtime runs on WASM unless you ask for more. To try WebGPU, opt in with the providers the browser supports:
508
+
509
+ ```ts
510
+ import {
511
+ IndraOcrService,
512
+ getDefaultWebExecutionProviders,
513
+ isWebGpuAvailable,
514
+ } from "ppu-indra-ocr/web";
515
+
516
+ if (await isWebGpuAvailable()) console.log("WebGPU supported");
517
+
518
+ const service = new IndraOcrService({
519
+ session: { executionProviders: await getDefaultWebExecutionProviders() }, // ["webgpu", "wasm"] or ["wasm"]
520
+ });
521
+ ```
522
+
523
+ If session creation with the requested providers fails, the service rebuilds the session on `wasm`; pass `session.onSessionFallback` to be told.
524
+
525
+ **The WASM binaries are always required**, even when WebGPU is the primary provider. When `ort.env.wasm.wasmPaths` is unset, pages and workers load the jsDelivr copy of the exact `onnxruntime-web` version you loaded, so the loader and the binaries never disagree. To self-host them, set it before `initialize()`:
526
+
527
+ ```ts
528
+ ort.env.wasm.wasmPaths = "/ort/"; // your copy of the onnxruntime-web dist files
529
+ ```
530
+
531
+ ### Multithreaded WASM (Cross-Origin Isolation)
532
+
533
+ ONNX Runtime runs WASM multithreaded only if the page is [cross-origin isolated](https://developer.mozilla.org/en-US/docs/Web/API/Window/crossOriginIsolated); otherwise `numThreads` is pinned to 1. Isolation needs two response headers:
534
+
535
+ ```http
536
+ Cross-Origin-Opener-Policy: same-origin
537
+ Cross-Origin-Embedder-Policy: require-corp
538
+ ```
539
+
540
+ **If you can set those headers server-side, do that.** It is the correct fix and needs nothing from this package.
541
+
542
+ For static hosts that cannot (e.g. GitHub Pages), the package ships an opt-in [coi-serviceworker](https://github.com/gzuidhof/coi-serviceworker) that injects the headers client-side. Copy it to your served root and load it **before** anything else:
240
543
 
241
544
  ```html
242
- <script src="https://cdn.jsdelivr.net/npm/@techstark/opencv-js@5.0.0-release.1/dist/opencv.js"></script>
545
+ <script src="/coi-serviceworker.js"></script>
546
+ ```
547
+
548
+ Resolve the shipped copy from the package, e.g. in a build step:
549
+
550
+ ```ts
551
+ // path on disk: node_modules/ppu-indra-ocr/coi-serviceworker.js
552
+ const swPath = import.meta.resolve("ppu-indra-ocr/coi-serviceworker.js");
243
553
  ```
244
554
 
245
- Only the script tag is tested. Without OpenCV.js on `globalThis.cv`,
246
- `initialize()` throws and says so.
555
+ > The service worker reloads the page once on first visit to apply the headers, and rewrites all fetch responses. Don't use it if you already control your headers or run another service worker that conflicts.
556
+
557
+ ## React Native (Mobile)
247
558
 
248
- The automated web tests run in Bun with a canvas polyfill. The
249
- [playground](playground) runs the web and PDF entries in a real browser; it
250
- was checked by hand in headless Chromium (images, PDFs, both engines).
559
+ Run the same OCR pipeline on iOS and Android via the `ppu-indra-ocr/mobile` entry. It uses `onnxruntime-react-native` (native JSI inference) and `ppu-ocv/canvas-mobile` (Skia-backed canvas) instead of their web counterparts, with the `canvas-native` engine.
251
560
 
252
- ## React Native
561
+ ```bash
562
+ npm install ppu-indra-ocr onnxruntime-react-native @shopify/react-native-skia
563
+ ```
253
564
 
254
565
  ```ts
255
566
  import { IndraOcrService } from "ppu-indra-ocr/mobile";
567
+
568
+ const service = new IndraOcrService();
569
+ await service.initialize();
570
+
571
+ // `imageBuffer` is an ArrayBuffer e.g. from a captured frame or a bundled asset.
572
+ const page = await service.convert(imageBuffer);
573
+ console.log(page.markdown);
574
+
575
+ await service.destroy();
256
576
  ```
257
577
 
258
- Uses `onnxruntime-react-native` and Skia (through `ppu-ocv/canvas-mobile`)
259
- with the canvas-native engine. This entry is type-checked but has not run on
260
- a device yet.
578
+ **Requirements.** RN >= 0.74 / Expo SDK >= 51 (Hermes). Both peer packages ship native code, so you need a dev client or `expo prebuild`. **Expo Go is not supported.**
261
579
 
262
- ## Command line
580
+ **Hardware acceleration is opt-in**, mobile inference runs on CPU by default. There is no WebGPU on React Native:
263
581
 
264
- ```bash
265
- ppu-indra-ocr convert paper.pdf # markdown to stdout
266
- ppu-indra-ocr convert "scans/*.png" --out results/ # one file per input
267
- ppu-indra-ocr convert scan.png --format json --pretty
268
- ppu-indra-ocr convert paper.pdf --mode ocr --math --timings
269
- ppu-indra-ocr detect receipt.jpg # line boxes as JSON
270
- ppu-indra-ocr download-models # also: clear-cache, models
582
+ ```ts
583
+ // Android: ["nnapi"]. iOS: ["coreml"].
584
+ new IndraOcrService({ session: { executionProviders: ["nnapi"] } });
585
+ ```
586
+
587
+ **Camera capture is out of scope.** Pass a decoded frame from `react-native-vision-camera` or `expo-camera` as an `ArrayBuffer`.
588
+
589
+ <details>
590
+ <summary>Why the mobile entry is on npm but not JSR</summary>
591
+
592
+ `onnxruntime-react-native` and `@shopify/react-native-skia` are native React Native modules that only resolve through npm/Metro, and JSR's Deno-based publish cannot resolve them (React Native itself cannot consume JSR packages). So the mobile entry is excluded from the JSR package. Install via npm/yarn/bun as shown above.
593
+
594
+ </details>
595
+
596
+ ## Models and Language Support
597
+
598
+ ### Model Presets
599
+
600
+ A preset is one pinned revision of [datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr) and the files it holds. Both run on the same pipeline, ported from `indra-ocr` 1.1.1.
601
+
602
+ | Preset | Hugging Face tag | Base download | What it reads |
603
+ | :--------------- | :--------------- | :------------ | :------------------------------------------------------------------------------------------------------------ |
604
+ | `v1.1` (default) | `v1.1.0` | 9 MB | Handwriting, 80+ languages (CJK, right-to-left and other script recognizers), language models, vertical pages |
605
+ | `v3.1` | `v3.1` | 18 MB | The first release (Indra OCR 1.0): Latin, Cyrillic, Greek, Devanagari, Bengali and Chinese |
606
+
607
+ ```ts
608
+ import { IndraOcrService, MODEL_PRESETS } from "ppu-indra-ocr";
609
+
610
+ const service = new IndraOcrService({ model: "v3.1" }); // the first release
611
+ const noLm = new IndraOcrService({ lm: false }); // v1.1 without the language models
612
+
613
+ console.log(MODEL_PRESETS["v1.1"].revision); // the pinned commit
271
614
  ```
272
615
 
273
- Run `ppu-indra-ocr help` for every flag (`--keep-furniture`, `--engine`,
274
- `--dpi`, `--max-pages`, `--password`, `--model-order`, `--no-image-ocr`,
275
- `--model-dir`, `--execution-providers`).
616
+ The language models (`lm`) re-read lines a recognizer is unsure of with a beam search, which mostly helps handwriting. They are on by default on Node and Bun and off on the web and React Native, where each is a 12 to 19 MB download. React Native has no `DecompressionStream`, which reading them needs.
276
617
 
277
- ## REST server
618
+ ### Indra OCR Models
278
619
 
279
- [apps/serve](apps/serve) wraps the service as an HTTP API (Hono + Bun):
280
- `POST /v1/ocr` for an image or a PDF, `/v1/detect`, batch, stream and async
281
- endpoints, a bounded inference queue, auth, metrics and OpenAPI docs. A hosted
282
- service counts as distribution under the weights' license; see its README.
620
+ Indra OCR is a small CPU pipeline with a 1M-parameter line recognizer. The `v1.1` files, downloaded and cached on first use:
283
621
 
284
- ## Models and languages
622
+ | Role | File | Size | Loads | What it does |
623
+ | :--------- | :--------------- | :------ | :------------------------ | :------------------------------------------------------------------------------ |
624
+ | `det` | `det.onnx` | 0.4 MB | at start | Text line detection |
625
+ | `rec` | `rec.onnx` | 5.0 MB | at start | Main recognizer: Latin, Cyrillic, Greek, Latin handwriting |
626
+ | `script` | `script.onnx` | 0.2 MB | at start | Script classifier: routes each line to its recognizer |
627
+ | `orient` | `orient.onnx` | 0.4 MB | at start | Page orientation and vertical writing |
628
+ | `order` | `order.onnx` | 3.0 MB | at start | Reading order, layout labels and blocks |
629
+ | `meta` | `meta.json` | 0.2 MB | at start | Vocabularies and input settings |
630
+ | `recCjk` | `rec_cjk.onnx` | 10.2 MB | first CJK line | Chinese, Japanese, Korean |
631
+ | `recRtl` | `rec_rtl.onnx` | 4.8 MB | first RTL line | Arabic, Persian, Urdu, Pashto, Hebrew |
632
+ | `recWorld` | `rec_world.onnx` | 5.6 MB | first line of its scripts | Indic scripts, Thai, Lao, Khmer, Myanmar, Sinhala, Georgian, Armenian, Ethiopic |
633
+ | `lm` | `lm.npz` | 15.7 MB | first unsure line | Language model of the main recognizer (with `lm`) |
634
+ | `lmCjk` | `lm_cjk.npz` | 19.0 MB | first unsure line | Language model of the CJK recognizer (with `lm`) |
635
+ | `lmWorld` | `lm_world.npz` | 11.6 MB | first unsure line | Language model of the other-script recognizer (with `lm`) |
285
636
 
286
- The models come from
287
- [datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr), pinned to
288
- commit `d7c839c` (tag v3.1). `models/` in this repository holds an unmodified
289
- mirror, checked file by file against upstream. Set
290
- `PPU_INDRA_OCR_MODEL_MIRROR=1` to fall back to it when Hugging Face fails.
291
- Pass `models` to read some or all files from paths, URLs or bytes.
637
+ `v3.1` has `det`, `rec`, `recCjk` (9.3 MB, Chinese only), `script`, `orient`, `order` and `meta`. With `math: true`, five more files load in either preset: `mathcls.onnx`, `math_enc.onnx`, `math_dec_init.onnx`, `math_dec_step.onnx` and `math_meta.json` (about 20 MB).
292
638
 
293
- - **OCR (scans and images):** Latin (about 50 languages), Cyrillic, Greek,
294
- Devanagari, Bengali, and Chinese (simplified and traditional).
639
+ The weights are Datalab's, under their own license. Unmodified mirrors with the license and attribution: `models/` (v3.1) and `models/v1.1/` in this repository, and [snowfluke/ppu-indra-ocr-models](https://huggingface.co/snowfluke/ppu-indra-ocr-models) on Hugging Face.
640
+
641
+ ### Cache Location (Node / Bun)
642
+
643
+ Models are cached under `~/.cache/ppu-indra-ocr`:
644
+
645
+ | OS | Path |
646
+ | :------ | :----------------------------------------- |
647
+ | macOS | `~/.cache/ppu-indra-ocr` |
648
+ | Linux | `~/.cache/ppu-indra-ocr` |
649
+ | Windows | `C:\Users\<username>\.cache\ppu-indra-ocr` |
650
+
651
+ Each file lands in a subdirectory named after a digest of its source URL, so two models that share a file name never collide.
652
+
653
+ ```ts
654
+ // Warm the cache (e.g. in CI or Docker builds): every file the preset can load
655
+ await IndraOcrService.downloadModels({ model: "v1.1", math: false, lm: true });
656
+ ```
657
+
658
+ Clear it with `ppu-indra-ocr clear-cache`.
659
+
660
+ > In the browser, model files are fetched via `fetch()` on every page load and rely on the browser's HTTP cache. For persistent offline caching, use a Service Worker or store the `ArrayBuffer` in IndexedDB and pass it through `models`.
661
+
662
+ ### Languages
663
+
664
+ There is no language option: the script model routes each line to the recognizer of its script group, and a line it is unsure of is read by the main recognizer too, the more confident reading winning.
665
+
666
+ - **OCR on v1.1 (scans and images):** Latin (Hausa, Fula, Akan, Azerbaijani, Uzbek, Vietnamese and Yoruba tone marks included), Cyrillic, Greek, Chinese, Japanese, Korean, Arabic, Persian, Urdu, Pashto, Hebrew, the Indic scripts, Thai, Lao, Khmer, Myanmar, Sinhala, Georgian, Armenian and Ethiopic. Right-to-left lines come out in logical order, and right-to-left pages read their right column first.
667
+ - **OCR on v3.1:** Latin, Cyrillic, Greek, Devanagari, Bengali and Chinese.
295
668
  - **PDF text layer:** any script.
296
669
 
297
- ## Configuration reference
298
-
299
- | Option | Default | Meaning |
300
- | ----------- | ------------------------- | ------------------------------------------------------------------------------------------------- |
301
- | `models` | Datalab's repo, pinned | Per-file sources: `det`, `rec`, `recCjk`, `script`, `orient`, `order`, `meta`, and the math files |
302
- | `math` | `false` | Read math lines as LaTeX |
303
- | `furniture` | `false` | Keep page headers and footers in the markdown |
304
- | `adaptive` | `true` | Second detection pass on pages with small text |
305
- | `engine` | `"opencv"` on Node | `"opencv"` or `"canvas-native"` |
306
- | `session` | CPU, CPU memory arena off | ONNX Runtime session options; `onSessionFallback` hook |
307
- | `verbose` | `false` | Log loading steps |
308
-
309
- ## Limitations
310
-
311
- From the upstream model card: Indra OCR is built for speed on clean print.
312
- Complex tables (merged or spanning cells, no ruling lines), handwriting,
313
- scripts outside the OCR list (Arabic, Hebrew, Thai, Japanese kana, Korean on
314
- scans), degraded scans, vertical text and very wide pages read poorly.
315
-
316
- In this port, the right-to-left check for PDF text-layer lines uses script
317
- ranges instead of Unicode bidi classes.
318
-
319
- ## How the port is checked
320
-
321
- `scripts/golden/` renders test pages and records every stage of the Python
322
- reference (`indra-ocr` 0.3.1) on them: orientation, skew, detection,
323
- recognition, reading order, the text layer and the final page. The tests
324
- compare this package with those goldens. On the opencv engine the line text,
325
- blocks and markdown match exactly, and the line boxes agree to an IoU of 0.98
326
- or better. The canvas-native engine stays within a token-F1 of 0.98.
327
-
328
- ## License and credits
329
-
330
- - **Code:** Apache-2.0, see [LICENSE](LICENSE) and [NOTICE](NOTICE). The
331
- pipeline is a TypeScript port of
332
- [datalab-to/indra](https://github.com/datalab-to/indra) (Apache-2.0). The
333
- library scaffold comes from
334
- [ppu-paddle-ocr](https://github.com/PT-Perkasa-Pilar-Utama/ppu-paddle-ocr).
335
- - **Model weights:** Datalab, modified OpenRAIL-M, see
336
- [models/LICENSE](models/LICENSE) and [models/README.md](models/README.md).
337
- The license's use restrictions apply to you and to anyone you pass the
338
- weights or a service on them to.
339
- - **License status:** [LICENSE-STATUS.md](LICENSE-STATUS.md) records our
340
- request to Datalab and what may change. It is subject to change.
341
- - Indra OCR is made by [Datalab](https://www.datalab.to). For commercial use
342
- beyond the license, or the highest accuracy, see their platform.
670
+ ### Model Output Limitations
671
+
672
+ From the upstream model card: Indra OCR is built for speed on clean print. Complex tables (merged or spanning cells, no ruling lines), cursive and faint pencil handwriting, degraded scans and very wide pages read poorly.
673
+
674
+ Upstream's picture regions (`Page.pictures`, `![](picture-k)` in the markdown) need a detector with a picture channel. The v1.1 detector has none, so this port leaves them out.
675
+
676
+ ## Configuration Reference
677
+
678
+ ### `IndraOptions`
679
+
680
+ ```ts
681
+ import type { IndraOptions } from "ppu-indra-ocr";
682
+
683
+ export type IndraOptions = {
684
+ model?: "v1.1" | "v3.1";
685
+ models?: ModelSources;
686
+ lm?: boolean;
687
+ math?: boolean;
688
+ furniture?: boolean;
689
+ adaptive?: boolean;
690
+ engine?: "opencv" | "canvas-native";
691
+ session?: SessionOptions;
692
+ verbose?: boolean;
693
+ };
694
+ ```
695
+
696
+ | Property | Type | Default | Description |
697
+ | :---------- | :---------------------------: | :--------------------------------------------: | :------------------------------------------------ |
698
+ | `model` | `"v1.1" \| "v3.1"` | `"v1.1"` | Model preset, see [Model Presets](#model-presets) |
699
+ | `models` | `ModelSources` | Datalab's repository, pinned | Per-file sources, see below |
700
+ | `lm` | `boolean` | `true` on Node/Bun, `false` web and mobile | Re-read unsure lines with the language models |
701
+ | `math` | `boolean` | `false` | Read math lines as LaTeX (four more models) |
702
+ | `furniture` | `boolean` | `false` | Keep page headers and footers in the markdown |
703
+ | `adaptive` | `boolean` | `true` | Second detection pass on pages with small text |
704
+ | `engine` | `"opencv" \| "canvas-native"` | `"opencv"` on Node/Bun, else `"canvas-native"` | Image engine (see above) |
705
+ | `session` | `SessionOptions` | CPU, CPU memory arena off | ONNX Runtime session options |
706
+ | `verbose` | `boolean` | `false` | Log loading and stage steps to the console |
707
+
708
+ ### `ModelSources`
709
+
710
+ A partial map from file role to a source: a URL, a file path (Node/Bun only), or an `ArrayBuffer`. Roles left out use `defaultModelUrl(role, preset)`.
711
+
712
+ | Property | Type | Default | Description |
713
+ | :------------------------------------------------------------- | :---------------------: | :------------: | :--------------------------- |
714
+ | `det`, `rec`, `script`, `orient`, `order`, `meta` | `string \| ArrayBuffer` | pinned default | The base files |
715
+ | `recCjk`, `recRtl`, `recWorld` | `string \| ArrayBuffer` | pinned default | Script recognizers (on use) |
716
+ | `lm`, `lmCjk`, `lmWorld` | `string \| ArrayBuffer` | pinned default | Language models (with `lm`) |
717
+ | `mathCls`, `mathEnc`, `mathDecInit`, `mathDecStep`, `mathMeta` | `string \| ArrayBuffer` | pinned default | The math files (with `math`) |
718
+
719
+ ### `BatchOptions`
720
+
721
+ Options of `convertBatch()` / `convertStream()`.
722
+
723
+ | Property | Type | Default | Description |
724
+ | :------------ | :----------------------: | :-----: | :--------------------------------------------------------------------------------------- |
725
+ | `concurrency` | `number` | `1` | Max images in flight. |
726
+ | `settle` | `boolean` | `false` | When `true`, a failed image yields `{ status: "rejected", reason }` instead of throwing. |
727
+ | `signal` | `AbortSignal` | - | Cancels the batch; pending images are not scheduled and the call rejects. |
728
+ | `onProgress` | `(done, total?) => void` | - | Called after each image settles, with the running count and total (if known). |
729
+
730
+ ### `ConvertPdfOptions`
731
+
732
+ Options of `convertPdf()`: `mode`, `dpi`, `imageOcr`, `maxPages` and `password` (see [PDF Input](#pdf-input)), plus `pdfium`, a module from `loadPdfium()` that is otherwise loaded once and reused. `PDFIUM_VERSION` names the `@embedpdf/pdfium` release the package is tested with.
733
+
734
+ ### `SessionOptions`
735
+
736
+ Any valid ONNX Runtime `InferenceSession.SessionOptions` property is accepted. ppu-indra-ocr changes one default:
737
+
738
+ | Property | Type | Default | Description |
739
+ | :------------------- | :-------------------------------------: | :-----: | :----------------------------------------------------------------------------------- |
740
+ | `executionProviders` | `string[] \| ExecutionProviderConfig[]` | ORT's | Execution providers for inference (CPU on Node/Bun, WASM on the web). |
741
+ | `enableCpuMemArena` | `boolean` | `false` | Off: the arena keeps each page's peak memory; turning it on trades memory for speed. |
742
+ | `onSessionFallback` | `(error: unknown) => void` | - | Called when the requested providers fail and the session is rebuilt on `cpu`/`wasm`. |
743
+
744
+ `onSessionFallback` is the only non-ORT property. It is stripped before the options reach ONNX Runtime. Use it when you run your own accelerator ladder and need to know that a GPU provider was dropped instead of reading a log line:
745
+
746
+ ```ts
747
+ let degraded: unknown = null;
748
+ const service = new IndraOcrService({
749
+ session: {
750
+ executionProviders: [{ name: "cuda", deviceId: 0 }, "cpu"],
751
+ onSessionFallback: (error) => (degraded ||= error),
752
+ },
753
+ });
754
+ await service.initialize();
755
+ if (degraded) {
756
+ // Acceleration was dropped. Fail over to your own runtime profile.
757
+ }
758
+ ```
759
+
760
+ It can fire once per model session.
761
+
762
+ ### Model host mirror
763
+
764
+ Built-in models download from Datalab's Hugging Face repository. That host rate-limits by IP, which shows up as `HTTP 429 Too Many Requests` from shared addresses such as CI runners.
765
+
766
+ Set `PPU_INDRA_OCR_MODEL_MIRROR=1` and a download that exhausts its retries falls back to the GitHub copy in `models/` (v3.1) or `models/v1.1/`, which serve byte-identical files:
767
+
768
+ ```sh
769
+ PPU_INDRA_OCR_MODEL_MIRROR=1 bun run your-script.ts
770
+ ```
771
+
772
+ It is off by default. GitHub LFS bandwidth is a monthly budget, so turn it on where request volume is bounded and known. A model URL you pass yourself is never rewritten.
773
+
774
+ ## Benchmark
775
+
776
+ Benches use a small zero-dependency harness (`bench/harness.ts`): in-process timing, round-robin scheduling across rounds so thermal/GC drift hits every task equally, reporting the median plus min/max/stddev. Run `bun task bench`.
777
+
778
+ Representative results on Apple M1 / Bun 1.4.2 (9 rounds) at the shipped defaults (`v1.1` models), `convert()` per page, opencv and canvas-native:
779
+
780
+ ```bash
781
+ task median +/-stddev min max
782
+ ----------------------------------------------------------------------
783
+ opencv two-column 396.9 ms 90.4 ms 382.7 ms 597.1 ms
784
+ opencv table 309.9 ms 23.4 ms 295.3 ms 350.9 ms
785
+ opencv receipt 203.0 ms 36.9 ms 195.8 ms 282.8 ms
786
+ canvas-native two-column 768.9 ms 16.9 ms 740.7 ms 786.4 ms
787
+ canvas-native table 571.1 ms 28.0 ms 553.6 ms 624.6 ms
788
+ canvas-native receipt 309.2 ms 15.4 ms 302.8 ms 340.9 ms
789
+ ```
790
+
791
+ `two-column` and `table` are 1700 x 2200 test pages (US letter at 200 dpi); `receipt` is `assets/receipt.jpg`, a 720 x 1280 phone photo. Times include orientation, deskew, detection, recognition, reading order and markdown. The 1.1 pipeline costs 50 to 180 ms more per page than 0.1.x: its skew search covers 45 degrees in some 80 image rotations (about 115 ms on opencv), and the main recognizer reads a window three lines tall.
792
+
793
+ ### Against ppu-paddle-ocr
794
+
795
+ `bench/vs-paddle.ts` runs both libraries with their default options, each alone in its own process, and scores the output against transcripts. Apple M1 / Bun 1.4.2, ppu-paddle-ocr 6.6.1, Indra on the `v1.1` models. Three accuracy measures, because they disagree for good reasons: **char-F1** counts the characters read and ignores order and spacing; **token-F1** counts whole words, so a dropped space costs; **CER** ignores case and spaces but counts order.
796
+
797
+ **Document pages** (`bun bench/vs-paddle.ts`: the test pages plus the receipt, 5 rounds each):
798
+
799
+ | Page | ms Indra / Paddle | char-F1 | token-F1 | CER |
800
+ | :-------------- | :---------------- | :------------ | :------------ | :------------ |
801
+ | two-column.png | 415 / 582 | 1.000 / 1.000 | 1.000 / 0.972 | 0.001 / 0.683 |
802
+ | rotated-90.png | 493 / 418 | 1.000 / 0.000 | 1.000 / 0.000 | 0.001 / 1.000 |
803
+ | rotated-180.png | 386 / 506 | 1.000 / 0.579 | 1.000 / 0.016 | 0.001 / 0.784 |
804
+ | table.png | 309 / 323 | 1.000 / 1.000 | 1.000 / 1.000 | 0.033 / 0.007 |
805
+ | chinese.png | 318 / 249 | 1.000 / 1.000 | 1.000 / 1.000 | 0.000 / 0.000 |
806
+ | receipt.jpg | 214 / 148 | 0.985 / 0.997 | 0.835 / 0.954 | 0.015 / 0.003 |
807
+
808
+ Paddle reads across both columns on one line (CER 0.683 on two-column) and does not turn pages upright by default. On the real receipt photo, Paddle reads a few characters Indra misses.
809
+
810
+ **SROIE receipts** (`SROIE_DIR=... bun bench/vs-paddle.ts`: 50 receipts, every 12th of the ICDAR 2019 SROIE set; measured with 0.1.2 on the `v3.1` models, not yet re-run on `v1.1`):
811
+
812
+ | Library | median ms | p90 ms | peak RSS | char-F1 | token-F1 | CER |
813
+ | :------ | :-------- | :----- | :------- | :------ | :------- | :---- |
814
+ | Indra | 188 | 822 | 1162 MB | 0.973 | 0.848 | 0.156 |
815
+ | Paddle | 220 | 434 | 1368 MB | 0.972 | 0.753 | 0.123 |
816
+
817
+ Both read the characters equally well. Indra keeps the spaces between words (token-F1 better on 40 of 50 receipts, worse on 7); Paddle's lower CER comes from line order, because SROIE transcripts move values away from their labels. Indra's slow tail is the 35-megapixel scans in the set, where shrinking the full image dominates.
818
+
819
+ ## How the Port Is Checked
820
+
821
+ `scripts/golden/` renders test pages and records every stage of the Python reference (`indra-ocr` 1.1.1) on them, once on each preset's models: orientation, skew, detection, recognition, script routing, language-model beam search, reading order, the text layer and the final page. The pages cover every script group, a light-on-dark title, a right-to-left page, a vertical page, a page tilted 30 degrees, and PDFs with a sideways table, a `/Rotate` page and Hebrew and vertical text layers. The tests compare this package with those goldens. On the opencv engine the line text, blocks and markdown match exactly, and the line boxes agree to an IoU of 0.98 or better (0.9 on deskewed pages, where the reference's cv2 warps through a platform-specific code path). The canvas-native engine stays within a token-F1 of 0.98.
822
+
823
+ ## Ecosystem
824
+
825
+ ppu-indra-ocr is part of a family of document-processing libraries for JavaScript runtimes, all from [PT Perkasa Pilar Utama](https://github.com/PT-Perkasa-Pilar-Utama):
826
+
827
+ | Library | What it does |
828
+ | :------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- |
829
+ | [ppu-paddle-ocr](https://github.com/PT-Perkasa-Pilar-Utama/ppu-paddle-ocr) | PaddleOCR (PP-OCRv6) text detection and recognition in every JavaScript runtime; the scaffold of this library. |
830
+ | [ppu-ocv](https://github.com/PT-Perkasa-Pilar-Utama/ppu-ocv) | Chainable image processing on OpenCV.js, plus canvas utilities that run in Node, Bun, browsers, and extensions. |
831
+ | [ppu-pdf](https://github.com/PT-Perkasa-Pilar-Utama/ppu-pdf) | PDF text extraction (digital and scanned) with coordinates, line grouping, and page-to-canvas/PNG rendering. |
832
+ | [ppu-doclayout](https://github.com/PT-Perkasa-Pilar-Utama/ppu-doclayout) | Document layout analysis with PaddlePaddle PP-DocLayout (tables, figures, text regions). |
833
+ | [ppu-doc-correction](https://github.com/PT-Perkasa-Pilar-Utama/ppu-doc-correction) | Document image correction: page orientation, geometric unwarping (UVDoc), and text-line orientation. |
834
+ | [ppu-uniface](https://github.com/PT-Perkasa-Pilar-Utama/ppu-uniface) | Face detection, recognition, verification, alignment, and anti-spoofing (a port of Python's Uniface). |
835
+ | [ppu-yolo-onnx-inference](https://github.com/PT-Perkasa-Pilar-Utama/ppu-yolo-onnx-inference) | YOLOv11 object detection in Bun/Node and browsers; no Python or PyTorch required. |
836
+
837
+ ## Contributing
838
+
839
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions, code-quality requirements, and the pull request process.
840
+
841
+ ## License
842
+
843
+ - **Code:** Apache-2.0, see [LICENSE](LICENSE) and [NOTICE](NOTICE). The pipeline is a TypeScript port of [datalab-to/indra](https://github.com/datalab-to/indra) (Apache-2.0). The library scaffold comes from [ppu-paddle-ocr](https://github.com/PT-Perkasa-Pilar-Utama/ppu-paddle-ocr).
844
+ - **Model weights:** Datalab, modified OpenRAIL-M, see [models/LICENSE](models/LICENSE) and [models/README.md](models/README.md). The license's use restrictions apply to you and to anyone you pass the weights or a service on them to.
845
+ - **License status:** [LICENSE-STATUS.md](LICENSE-STATUS.md) records our request to Datalab and what may change. It is subject to change.
846
+ - Indra OCR is made by [Datalab](https://www.datalab.to). For commercial use beyond the license, or the highest accuracy, see their platform.
847
+
848
+ ## Support
849
+
850
+ [Open an issue](https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/issues).
851
+
852
+ ## Scripts
853
+
854
+ Recommended development environment is Linux-based. Library template: https://github.com/aquapi/lib-template
855
+
856
+ | Script | Command | Description |
857
+ | :------------------------- | :----------------------------------- | :--------------------------------------------------------- |
858
+ | `bun task build` | `bun run scripts/build.ts` | Emit `.js` and `.d.ts` to `lib/`. |
859
+ | `bun task prepare-publish` | `bun run scripts/prepare-publish.ts` | Stage `package.json`, `README.md` and notices into `lib/`. |
860
+ | `bun task bench` | `bun run scripts/bench.ts` | Run `*.bench.ts` files. |
861
+ | `bun bench/vs-paddle.ts` | - | Compare with ppu-paddle-ocr on document pages or SROIE. |
862
+ | `bun run build:pages` | build + `playground/build-pages.ts` | Assemble the playground for Cloudflare. |
863
+
864
+ To run a specific benchmark file:
865
+
866
+ ```bash
867
+ bun task bench index # Run bench/index.bench.ts
868
+ ```