ppu-indra-ocr 0.1.1 → 0.1.2

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 (3) hide show
  1. package/README.md +680 -191
  2. package/package.json +1 -1
  3. package/pdf/index.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,188 @@ 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
+ - [Indra OCR Models](#indra-ocr-models)
69
+ - [Cache Location](#cache-location-node--bun)
70
+ - [Languages](#languages)
71
+ - [Model Output Limitations](#model-output-limitations)
72
+ - [Configuration Reference](#configuration-reference)
73
+ - [IndraOptions](#indraoptions)
74
+ - [ModelSources](#modelsources)
75
+ - [BatchOptions](#batchoptions)
76
+ - [ConvertPdfOptions](#convertpdfoptions)
77
+ - [SessionOptions](#sessionoptions)
78
+ - [Model host mirror](#model-host-mirror)
79
+ - [Benchmark](#benchmark)
80
+ - [How the Port Is Checked](#how-the-port-is-checked)
81
+ - [Ecosystem](#ecosystem)
82
+ - [Contributing](#contributing)
83
+ - [License](#license)
84
+ - [Support](#support)
85
+ - [Scripts](#scripts)
86
+
87
+ ## Why ppu-indra-ocr?
88
+
89
+ - **The whole page, not just the text.** Orientation, deskew, line detection, Latin and Chinese recognizers, reading order, layout labels, and markdown with headings, lists and tables, in one `convert()` call.
90
+ - **PDFs too.** Uses a PDF's text layer where it can be trusted and OCR where it cannot, page by page.
91
+ - **Small models.** About 18 MB of ONNX models (38 MB with math), fetched and cached on first run, pinned to one upstream revision.
92
+ - **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).
93
+ - **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).
94
+ - **Composable.** Every stage is a method, so you can run one stage, swap a stage, or chain your own pipeline.
95
+ - **TypeScript**, full type definitions.
96
+
97
+ ## Runtime Support
98
+
99
+ The same package, the same API, every JavaScript runtime:
100
+
101
+ | Runtime | How to install | Try it |
102
+ | -------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
103
+ | **Node.js** | `npm install ppu-indra-ocr onnxruntime-node` | [npm package](https://www.npmjs.com/package/ppu-indra-ocr) |
104
+ | **Bun** | `bun add ppu-indra-ocr onnxruntime-node` | [npm package](https://www.npmjs.com/package/ppu-indra-ocr) |
105
+ | **Deno** | `deno add jsr:@snowfluke/ppu-indra-ocr` | [JSR package](https://jsr.io/@snowfluke/ppu-indra-ocr) |
106
+ | **Web browser** | `npm install ppu-indra-ocr onnxruntime-web` (import `/web` subpath) | [Live demo](https://ppu-indra-ocr.snowfluke.workers.dev/) |
107
+ | **Web worker** | Same as web; the `/web` subpath runs in workers. | [Web Workers](#web-workers) |
108
+ | **Browser extension** | Same as web; bundle `ppu-indra-ocr/web` with your extension's bundler. | [Web / Browser Support](#web--browser-support) |
109
+ | **Mobile (React Native)** | `npm install ppu-indra-ocr onnxruntime-react-native @shopify/react-native-skia` (import `/mobile` subpath) | [React Native](#react-native-mobile) |
110
+ | **PDF input** (any of the above) | `npm install @embedpdf/pdfium` (import `/pdf` subpath) | [PDF Input](#pdf-input) |
74
111
 
75
112
  ## Installation
76
113
 
77
114
  ```bash
78
- bun add ppu-indra-ocr onnxruntime-node
79
- # PDF input (optional):
80
- bun add @embedpdf/pdfium
115
+ npm install ppu-indra-ocr onnxruntime-node onnxruntime-web
81
116
  ```
82
117
 
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).
118
+ Omit `onnxruntime-node` or `onnxruntime-web` depending on your target environment (Node/Bun vs browser). Add `@embedpdf/pdfium` for PDF input.
86
119
 
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.
120
+ The first `initialize()` downloads the models (about 18 MB, 38 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.
90
121
 
91
122
  **When the models download, you accept Datalab's license for the weights.**
92
123
  Check [LICENSE-STATUS.md](LICENSE-STATUS.md) first.
93
124
 
94
- ## Usage
125
+ ### CLI (global install)
126
+
127
+ ```bash
128
+ npm install -g ppu-indra-ocr onnxruntime-node # or: bun add -g ppu-indra-ocr onnxruntime-node
129
+ ppu-indra-ocr convert scan.png
130
+ ```
131
+
132
+ This puts a `ppu-indra-ocr` command on your `PATH`. See [Command Line](#command-line) for all commands.
133
+
134
+ <details>
135
+ <summary>Notes on the global install</summary>
136
+
137
+ - **`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.
138
+ - **bun**: ensure `~/.bun/bin` is on your `PATH` (npm's global bin usually already is).
139
+ - **Updates are manual.** Re-run the install with `@latest` to upgrade.
140
+ - **Node or Bun must be present.** This is the Node/Bun build, not a standalone binary. For that, see [Standalone Binaries](#standalone-binaries) below.
141
+
142
+ </details>
143
+
144
+ ### Standalone Binaries
145
+
146
+ Every release attaches self-contained executables, no Node, Bun, or `npm install` required. Download, extract, run:
147
+
148
+ ```bash
149
+ curl -L https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/releases/latest/download/ppu-indra-ocr-linux-x64.tar.gz | tar xz
150
+ ./ppu-indra-ocr-linux-x64 convert scan.png
151
+ ```
152
+
153
+ | Asset | Platform |
154
+ | :---------------------------------- | :------------------------------------------------------------- |
155
+ | `ppu-indra-ocr-linux-x64.tar.gz` | Linux x86-64 (glibc; Debian, Ubuntu, Fedora, ...) |
156
+ | `ppu-indra-ocr-linux-arm64.tar.gz` | Linux ARM64 (glibc; Raspberry Pi OS 64-bit, AWS Graviton, ...) |
157
+ | `ppu-indra-ocr-darwin-arm64.tar.gz` | macOS on Apple Silicon |
158
+ | `ppu-indra-ocr-windows-x64.zip` | Windows x86-64 (contains the `.exe`) |
159
+
160
+ Intel Macs and Alpine (musl) are not covered, onnxruntime ships no darwin-x64 or musl builds; use `npx`/`bunx` there.
161
+
162
+ <details>
163
+ <summary>Size, slim variant, and OS warnings</summary>
164
+
165
+ - **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 (about 18 MB) still download to `~/.cache/ppu-indra-ocr` on first run, exactly like the npm CLI.
166
+ - **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.
167
+ - **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).
168
+ - **Windows SmartScreen.** Unrecognized-app warning on first run: "More info", then "Run anyway".
169
+
170
+ </details>
171
+
172
+ <details>
173
+ <summary>Verify a download (Sigstore + SLSA)</summary>
174
+
175
+ Both checks run against the archive, before extraction; both artifacts are attached per release.
176
+
177
+ ```bash
178
+ # Sigstore signature (bundle is attached next to each archive)
179
+ cosign verify-blob ppu-indra-ocr-linux-x64.tar.gz \
180
+ --bundle ppu-indra-ocr-linux-x64.tar.gz.sigstore.json \
181
+ --certificate-identity-regexp "github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr" \
182
+ --certificate-oidc-issuer https://token.actions.githubusercontent.com
183
+
184
+ # GitHub build provenance (SLSA)
185
+ gh attestation verify ppu-indra-ocr-linux-x64.tar.gz --repo PT-Perkasa-Pilar-Utama/ppu-indra-ocr
186
+ ```
187
+
188
+ </details>
189
+
190
+ ## Core Usage
191
+
192
+ ### Basic Conversion
95
193
 
96
194
  ```ts
97
195
  import { IndraOcrService } from "ppu-indra-ocr";
98
196
 
99
- const service = new IndraOcrService();
197
+ const service = new IndraOcrService({ verbose: true });
100
198
  await service.initialize();
101
199
 
102
- const page = await service.convert(await Bun.file("scan.png").arrayBuffer());
200
+ const page = await service.convert(await Bun.file("./assets/receipt.jpg").arrayBuffer());
103
201
  console.log(page.markdown);
104
202
 
105
203
  await service.destroy();
106
204
  ```
107
205
 
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 }`.
206
+ `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
207
 
112
- For one image, the one-shot functions load the models, run, and release them:
208
+ 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
209
 
114
210
  ```ts
115
211
  import { detect, ocr } from "ppu-indra-ocr";
@@ -118,7 +214,7 @@ const page = await ocr(imageBytes);
118
214
  const boxes = await detect(imageBytes); // [x0, y0, x1, y1, score][]
119
215
  ```
120
216
 
121
- ## The page result
217
+ ### The Page Result
122
218
 
123
219
  ```ts
124
220
  type Page = {
@@ -134,12 +230,9 @@ type Page = {
134
230
  };
135
231
  ```
136
232
 
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.
233
+ 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
234
 
142
- ## Running the stages yourself
235
+ ### Running the Stages Yourself
143
236
 
144
237
  ```ts
145
238
  const { turns } = await service.orient(image); // quarter turns, from orient.onnx
@@ -150,24 +243,148 @@ const texts = lines.map((l) => l.text);
150
243
  const { order, cls, same } = await service.order(boxes, texts, upright.width, upright.height);
151
244
  ```
152
245
 
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.
246
+ `recognize` takes boxes from any detector, one line per box. Boxes should hug the text: the recognizer adds 0.2 x the box height above and below and 0.3 x on each side. Trim boxes that carry their own padding first; PaddleOCR's boxes, for example, are padded to 1.8 x the text height.
247
+
248
+ `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`.
249
+
250
+ ### Custom Models
251
+
252
+ 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:
253
+
254
+ ```ts
255
+ import { IndraOcrService, MODEL_FILES } from "ppu-indra-ocr";
256
+
257
+ // One file from elsewhere
258
+ const service = new IndraOcrService({
259
+ models: { det: "./models/det.onnx" },
260
+ });
261
+
262
+ // Every file from a local folder (air-gapped hosts)
263
+ const local = new IndraOcrService({
264
+ models: Object.fromEntries(
265
+ Object.entries(MODEL_FILES).map(([role, file]) => [role, `/opt/indra-models/${file}`])
266
+ ),
267
+ });
268
+ ```
269
+
270
+ Roles: `det`, `rec`, `recCjk`, `script`, `orient`, `order`, `meta`, and with math `mathCls`, `mathEnc`, `mathDecInit`, `mathDecStep`, `mathMeta`. `MODEL_FILES` maps each role to its file name, `MODEL_REVISION` is the pinned upstream commit, and `defaultModelUrl(role)` gives the default URL.
157
271
 
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.
272
+ ### Detection Only
161
273
 
162
- ## PDF input
274
+ `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.
275
+
276
+ ```ts
277
+ const boxes = await service.detect(imageBytes);
278
+ // boxes: [x0, y0, x1, y1, score][] in image pixels
279
+ ```
280
+
281
+ `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).
282
+
283
+ ## Command Line
284
+
285
+ 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):
286
+
287
+ ```bash
288
+ # one image or PDF -> markdown on stdout
289
+ bunx ppu-indra-ocr convert paper.pdf
290
+
291
+ # many images (glob), one output file per input
292
+ bunx ppu-indra-ocr convert "scans/*.png" --out results/
293
+
294
+ # structured JSON, one object per page
295
+ bunx ppu-indra-ocr convert scan.png --format json --pretty
296
+
297
+ # force OCR on a PDF, read math as LaTeX, print per-page timings
298
+ bunx ppu-indra-ocr convert paper.pdf --mode ocr --math --timings
299
+
300
+ # detection only: line boxes as JSON
301
+ bunx ppu-indra-ocr detect receipt.jpg
302
+
303
+ # zero-install (no local ppu-indra-ocr): npx can pull both packages
304
+ npx -p onnxruntime-node -p ppu-indra-ocr ppu-indra-ocr convert scan.png
305
+
306
+ # pre-warm / clear the model cache, list the model files and revision
307
+ bunx ppu-indra-ocr download-models
308
+ bunx ppu-indra-ocr clear-cache
309
+ bunx ppu-indra-ocr models
310
+ ```
311
+
312
+ | Flags | Applies to | Purpose |
313
+ | :-------------------------------------------------------------- | :----------- | :------------------------------------------------------------ |
314
+ | `--format md\|text\|json`, `--out <dir>` | `convert` | Output format; one file per input (`.md`, `.txt`, `.jsonl`) |
315
+ | `--math`, `--keep-furniture`, `--engine`, `--timings` | `convert` | Math as LaTeX, keep headers and footers, engine, timings |
316
+ | `--mode auto\|ocr\|text`, `--dpi`, `--max-pages`, `--password` | PDFs | Text layer or OCR, render resolution, page cap, password |
317
+ | `--model-order`, `--no-image-ocr` | PDFs | Order text-layer lines with the model; skip OCR inside images |
318
+ | `--model-dir <dir>`, `--execution-providers <list>` | all commands | Read models from a folder; ONNX providers (e.g. `cuda,cpu`) |
319
+ | `-o`/`--output <file>`, `--pretty`, `-q`/`--quiet`, `--verbose` | all commands | Output destination and format, logging |
320
+
321
+ 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.
322
+
323
+ Run `bunx ppu-indra-ocr help` for the full reference.
324
+
325
+ ## Batch Conversion
326
+
327
+ `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.
328
+
329
+ ```ts
330
+ const pages = await service.convertBatch([buf1, buf2, buf3]);
331
+ pages.forEach((p, i) => console.log(i, p.markdown));
332
+ ```
333
+
334
+ | You want | Use |
335
+ | :---------------------------------- | :------------------------------------ |
336
+ | More images in flight | `{ concurrency: 2 }` |
337
+ | One bad image not to kill the batch | `{ settle: true }` |
338
+ | Progress or cancellation | `{ onProgress, signal }` |
339
+ | Results as they finish | `convertStream()` |
340
+ | An input list too big for memory | pass an `Iterable` or `AsyncIterable` |
341
+
342
+ Full surface: [`BatchOptions`](#batchoptions).
343
+
344
+ **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.
345
+
346
+ **Failures.** With `settle: true` the call never rejects; each slot becomes `{ index, status, value | reason }`:
347
+
348
+ ```ts
349
+ const results = await service.convertBatch(images, { settle: true });
350
+ for (const r of results) {
351
+ if (r.status === "fulfilled") console.log(r.value.markdown);
352
+ else console.error("failed:", r.reason);
353
+ }
354
+ ```
355
+
356
+ **Progress and cancellation** use the usual primitives:
357
+
358
+ ```ts
359
+ const ac = new AbortController();
360
+ await service.convertBatch(images, {
361
+ signal: ac.signal,
362
+ onProgress: (done, total) => console.log(`${done}/${total}`),
363
+ });
364
+ ```
365
+
366
+ **Streaming.** `convertStream()` yields each result as it finishes, so the whole batch is never buffered. Each item carries its input `index` for reordering:
367
+
368
+ ```ts
369
+ for await (const item of service.convertStream(images)) {
370
+ if (item.status === "fulfilled") console.log(item.index, item.value.markdown);
371
+ }
372
+ ```
373
+
374
+ 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.
375
+
376
+ ## PDF Input
163
377
 
164
378
  ```ts
165
379
  import { IndraOcrService } from "ppu-indra-ocr";
166
- import { convertPdf } from "ppu-indra-ocr/pdf";
380
+ import { convertPdf, isPdf } from "ppu-indra-ocr/pdf";
167
381
 
168
382
  const service = new IndraOcrService();
169
383
  await service.initialize();
170
- const pages = await convertPdf(service, pdfBytes, { mode: "auto" });
384
+
385
+ const pages = isPdf(bytes)
386
+ ? await convertPdf(service, bytes, { mode: "auto" })
387
+ : [await service.convert(bytes)];
171
388
  ```
172
389
 
173
390
  | Option | Default | Meaning |
@@ -179,164 +396,436 @@ const pages = await convertPdf(service, pdfBytes, { mode: "auto" });
179
396
  | `maxPages` | all | Read at most this many pages |
180
397
  | `password` | - | Password of an encrypted PDF |
181
398
 
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.
399
+ The text layer is checked first: invisible text (an OCR layer), broken font maps, and runs with no ink under them send the page to OCR. 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
400
 
190
- ## Batches
401
+ ## Math
191
402
 
192
403
  ```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);
404
+ const service = new IndraOcrService({ math: true });
197
405
  ```
198
406
 
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.
407
+ 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
408
 
202
- ## Math
409
+ ## Orientation and Deskew
410
+
411
+ There is nothing to compose: `convert()` turns the page upright with `orient.onnx` (90, 180 and 270 degree turns) and undoes small tilt before detection. `page.rotation` and `page.skew` report what was undone, and boxes come back in the upright page's pixels. 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).
412
+
413
+ ## Processing Engine
414
+
415
+ Two image processing backends are available for resizing and warping:
416
+
417
+ | Engine | Default | OpenCV Required | Notes |
418
+ | :---------------- | :----------: | :-------------: | :--------------------------------------------------------------------- |
419
+ | `"opencv"` | Node and Bun | Yes | OpenCV.js through `ppu-ocv`. Results match the Python reference. |
420
+ | `"canvas-native"` | Web, mobile | No | Plain TypeScript. Smaller; within a token-F1 of 0.98 of the reference. |
203
421
 
204
422
  ```ts
205
- const service = new IndraOcrService({ math: true });
423
+ // OpenCV (default on Node and Bun)
424
+ const service = new IndraOcrService();
425
+
426
+ // Canvas-native (no OpenCV dependency)
427
+ const service = new IndraOcrService({ engine: "canvas-native" });
206
428
  ```
207
429
 
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.
430
+ 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):
212
431
 
213
- ## Processing engine
432
+ ```html
433
+ <script src="https://cdn.jsdelivr.net/npm/@techstark/opencv-js@5.0.0-release.1/dist/opencv.js"></script>
434
+ ```
214
435
 
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 |
436
+ Without OpenCV.js on `globalThis.cv`, `initialize()` throws and says so.
219
437
 
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.
438
+ ## Web / Browser Support
223
439
 
224
- ## Web and browser
440
+ Import from `ppu-indra-ocr/web` for browser-native capabilities (`HTMLCanvasElement`, `OffscreenCanvas`, `fetch` buffering).
441
+
442
+ ### Using a Bundler (Vite, Webpack, etc.)
225
443
 
226
444
  ```ts
227
445
  import { IndraOcrService } from "ppu-indra-ocr/web";
228
446
 
229
447
  const service = new IndraOcrService(); // canvas-native, wasm
230
448
  await service.initialize();
449
+
450
+ const file = document.getElementById("upload").files[0];
231
451
  const page = await service.convert(await file.arrayBuffer());
452
+ console.log(page.markdown);
232
453
  ```
233
454
 
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.
455
+ Models are fetched from the default URLs or from `models`.
237
456
 
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):
457
+ ### Web Workers
458
+
459
+ Keep the service inside a worker and send image bytes across the boundary, so inference never blocks the main thread:
460
+
461
+ ```ts
462
+ // worker.ts
463
+ import { IndraOcrService } from "ppu-indra-ocr/web";
464
+
465
+ const service = new IndraOcrService();
466
+ const ready = service.initialize();
467
+
468
+ self.onmessage = async (event: MessageEvent<ArrayBuffer>) => {
469
+ await ready;
470
+ const page = await service.convert(event.data);
471
+ self.postMessage(page);
472
+ };
473
+ ```
474
+
475
+ ```ts
476
+ // main.ts
477
+ const worker = new Worker(new URL("./worker.ts", import.meta.url), {
478
+ type: "module",
479
+ });
480
+ worker.onmessage = (event) => console.log(event.data.markdown);
481
+
482
+ const bytes = await file.arrayBuffer();
483
+ worker.postMessage(bytes, [bytes]); // transferred, not copied
484
+ ```
485
+
486
+ Notes:
487
+
488
+ - A worker is the right home for OCR. On the main thread, inference blocks the page until the whole image is done.
489
+ - 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.
490
+ - `isWebWorker()` is exported if you need to branch on the scope yourself.
491
+
492
+ ```ts
493
+ import { isWebWorker } from "ppu-indra-ocr/web";
494
+ ```
495
+
496
+ ### CDN (No Bundler)
497
+
498
+ See the [live demo](https://ppu-indra-ocr.snowfluke.workers.dev/) for a complete ESM/CDN setup with an import map.
499
+
500
+ ### WebGPU Acceleration
501
+
502
+ ONNX Runtime runs on WASM unless you ask for more. To try WebGPU, opt in with the providers the browser supports:
503
+
504
+ ```ts
505
+ import {
506
+ IndraOcrService,
507
+ getDefaultWebExecutionProviders,
508
+ isWebGpuAvailable,
509
+ } from "ppu-indra-ocr/web";
510
+
511
+ if (await isWebGpuAvailable()) console.log("WebGPU supported");
512
+
513
+ const service = new IndraOcrService({
514
+ session: { executionProviders: await getDefaultWebExecutionProviders() }, // ["webgpu", "wasm"] or ["wasm"]
515
+ });
516
+ ```
517
+
518
+ If session creation with the requested providers fails, the service rebuilds the session on `wasm`; pass `session.onSessionFallback` to be told.
519
+
520
+ **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()`:
521
+
522
+ ```ts
523
+ ort.env.wasm.wasmPaths = "/ort/"; // your copy of the onnxruntime-web dist files
524
+ ```
525
+
526
+ ### Multithreaded WASM (Cross-Origin Isolation)
527
+
528
+ 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:
529
+
530
+ ```http
531
+ Cross-Origin-Opener-Policy: same-origin
532
+ Cross-Origin-Embedder-Policy: require-corp
533
+ ```
534
+
535
+ **If you can set those headers server-side, do that.** It is the correct fix and needs nothing from this package.
536
+
537
+ 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
538
 
241
539
  ```html
242
- <script src="https://cdn.jsdelivr.net/npm/@techstark/opencv-js@5.0.0-release.1/dist/opencv.js"></script>
540
+ <script src="/coi-serviceworker.js"></script>
243
541
  ```
244
542
 
245
- Only the script tag is tested. Without OpenCV.js on `globalThis.cv`,
246
- `initialize()` throws and says so.
543
+ Resolve the shipped copy from the package, e.g. in a build step:
247
544
 
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).
545
+ ```ts
546
+ // path on disk: node_modules/ppu-indra-ocr/coi-serviceworker.js
547
+ const swPath = import.meta.resolve("ppu-indra-ocr/coi-serviceworker.js");
548
+ ```
549
+
550
+ > 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.
551
+
552
+ ## React Native (Mobile)
251
553
 
252
- ## React Native
554
+ 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.
555
+
556
+ ```bash
557
+ npm install ppu-indra-ocr onnxruntime-react-native @shopify/react-native-skia
558
+ ```
253
559
 
254
560
  ```ts
255
561
  import { IndraOcrService } from "ppu-indra-ocr/mobile";
562
+
563
+ const service = new IndraOcrService();
564
+ await service.initialize();
565
+
566
+ // `imageBuffer` is an ArrayBuffer e.g. from a captured frame or a bundled asset.
567
+ const page = await service.convert(imageBuffer);
568
+ console.log(page.markdown);
569
+
570
+ await service.destroy();
256
571
  ```
257
572
 
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.
573
+ **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
574
 
262
- ## Command line
575
+ **Hardware acceleration is opt-in**, mobile inference runs on CPU by default. There is no WebGPU on React Native:
263
576
 
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
577
+ ```ts
578
+ // Android: ["nnapi"]. iOS: ["coreml"].
579
+ new IndraOcrService({ session: { executionProviders: ["nnapi"] } });
271
580
  ```
272
581
 
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`).
582
+ **Camera capture is out of scope.** Pass a decoded frame from `react-native-vision-camera` or `expo-camera` as an `ArrayBuffer`.
583
+
584
+ <details>
585
+ <summary>Why the mobile entry is on npm but not JSR</summary>
586
+
587
+ `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.
588
+
589
+ </details>
590
+
591
+ ## Models and Language Support
592
+
593
+ ### Indra OCR Models
594
+
595
+ Indra OCR is a small CPU pipeline with a 1M-parameter line recognizer. The default models come from [datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr), pinned to commit `d7c839c` (tag v3.1), downloaded and cached on first run:
276
596
 
277
- ## REST server
597
+ | Role | File | Size | What it does |
598
+ | :------- | :------------- | :----- | :---------------------------------------------- |
599
+ | `det` | `det.onnx` | 0.4 MB | Text line detection |
600
+ | `rec` | `rec.onnx` | 5.0 MB | Line recognizer (Latin, Cyrillic, Greek, Indic) |
601
+ | `recCjk` | `rec_cjk.onnx` | 9.3 MB | Chinese line recognizer |
602
+ | `script` | `script.onnx` | 0.2 MB | Script classifier (routes Chinese lines) |
603
+ | `orient` | `orient.onnx` | 0.4 MB | Page orientation |
604
+ | `order` | `order.onnx` | 3.0 MB | Reading order, layout labels and blocks |
605
+ | `meta` | `meta.json` | 0.1 MB | Vocabularies and input settings |
278
606
 
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.
607
+ With `math: true`, five more files load: `mathcls.onnx`, `math_enc.onnx`, `math_dec_init.onnx`, `math_dec_step.onnx` and `math_meta.json` (about 20 MB).
283
608
 
284
- ## Models and languages
609
+ The weights are Datalab's, under their own license. Unmodified mirrors with the license and attribution: `models/` in this repository and [snowfluke/ppu-indra-ocr-models](https://huggingface.co/snowfluke/ppu-indra-ocr-models) on Hugging Face.
285
610
 
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.
611
+ ### Cache Location (Node / Bun)
292
612
 
293
- - **OCR (scans and images):** Latin (about 50 languages), Cyrillic, Greek,
294
- Devanagari, Bengali, and Chinese (simplified and traditional).
613
+ Models are cached under `~/.cache/ppu-indra-ocr`:
614
+
615
+ | OS | Path |
616
+ | :------ | :----------------------------------------- |
617
+ | macOS | `~/.cache/ppu-indra-ocr` |
618
+ | Linux | `~/.cache/ppu-indra-ocr` |
619
+ | Windows | `C:\Users\<username>\.cache\ppu-indra-ocr` |
620
+
621
+ Each file lands in a subdirectory named after a digest of its source URL, so two models that share a file name never collide.
622
+
623
+ ```ts
624
+ // Warm the cache (e.g. in CI or Docker builds)
625
+ await IndraOcrService.downloadModels({ math: false });
626
+ ```
627
+
628
+ Clear it with `ppu-indra-ocr clear-cache`.
629
+
630
+ > 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`.
631
+
632
+ ### Languages
633
+
634
+ There is no language option: a script model routes Chinese lines to the CJK recognizer, and everything else goes to the main recognizer.
635
+
636
+ - **OCR (scans and images):** Latin (about 50 languages), Cyrillic, Greek, Devanagari, Bengali, and Chinese (simplified and traditional).
295
637
  - **PDF text layer:** any script.
296
638
 
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.
639
+ ### Model Output Limitations
640
+
641
+ From the upstream model card: Indra OCR is built for speed on clean print. Complex tables (merged or spanning cells, no ruling lines), handwriting, scripts outside the OCR list (Arabic, Hebrew, Thai, Japanese kana, Korean on scans), degraded scans, vertical text and very wide pages read poorly.
642
+
643
+ In this port, the right-to-left check for PDF text-layer lines uses script ranges instead of Unicode bidi classes.
644
+
645
+ ## Configuration Reference
646
+
647
+ ### `IndraOptions`
648
+
649
+ ```ts
650
+ import type { IndraOptions } from "ppu-indra-ocr";
651
+
652
+ export type IndraOptions = {
653
+ models?: ModelSources;
654
+ math?: boolean;
655
+ furniture?: boolean;
656
+ adaptive?: boolean;
657
+ engine?: "opencv" | "canvas-native";
658
+ session?: SessionOptions;
659
+ verbose?: boolean;
660
+ };
661
+ ```
662
+
663
+ | Property | Type | Default | Description |
664
+ | :---------- | :---------------------------: | :--------------------------------------------: | :--------------------------------------------- |
665
+ | `models` | `ModelSources` | Datalab's repository, pinned | Per-file sources, see below |
666
+ | `math` | `boolean` | `false` | Read math lines as LaTeX (four more models) |
667
+ | `furniture` | `boolean` | `false` | Keep page headers and footers in the markdown |
668
+ | `adaptive` | `boolean` | `true` | Second detection pass on pages with small text |
669
+ | `engine` | `"opencv" \| "canvas-native"` | `"opencv"` on Node/Bun, else `"canvas-native"` | Image engine (see above) |
670
+ | `session` | `SessionOptions` | CPU, CPU memory arena off | ONNX Runtime session options |
671
+ | `verbose` | `boolean` | `false` | Log loading and stage steps to the console |
672
+
673
+ ### `ModelSources`
674
+
675
+ 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)`.
676
+
677
+ | Property | Type | Default | Description |
678
+ | :------------------------------------------------------------- | :---------------------: | :------------: | :--------------------------- |
679
+ | `det`, `rec`, `recCjk`, `script`, `orient`, `order`, `meta` | `string \| ArrayBuffer` | pinned default | The base files |
680
+ | `mathCls`, `mathEnc`, `mathDecInit`, `mathDecStep`, `mathMeta` | `string \| ArrayBuffer` | pinned default | The math files (with `math`) |
681
+
682
+ ### `BatchOptions`
683
+
684
+ Options of `convertBatch()` / `convertStream()`.
685
+
686
+ | Property | Type | Default | Description |
687
+ | :------------ | :----------------------: | :-----: | :--------------------------------------------------------------------------------------- |
688
+ | `concurrency` | `number` | `1` | Max images in flight. |
689
+ | `settle` | `boolean` | `false` | When `true`, a failed image yields `{ status: "rejected", reason }` instead of throwing. |
690
+ | `signal` | `AbortSignal` | - | Cancels the batch; pending images are not scheduled and the call rejects. |
691
+ | `onProgress` | `(done, total?) => void` | - | Called after each image settles, with the running count and total (if known). |
692
+
693
+ ### `ConvertPdfOptions`
694
+
695
+ Options of `convertPdf()`: `mode`, `dpi`, `pdfOrder`, `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.
696
+
697
+ ### `SessionOptions`
698
+
699
+ Any valid ONNX Runtime `InferenceSession.SessionOptions` property is accepted. ppu-indra-ocr changes one default:
700
+
701
+ | Property | Type | Default | Description |
702
+ | :------------------- | :-------------------------------------: | :-----: | :----------------------------------------------------------------------------------- |
703
+ | `executionProviders` | `string[] \| ExecutionProviderConfig[]` | ORT's | Execution providers for inference (CPU on Node/Bun, WASM on the web). |
704
+ | `enableCpuMemArena` | `boolean` | `false` | Off: the arena keeps each page's peak memory; turning it on trades memory for speed. |
705
+ | `onSessionFallback` | `(error: unknown) => void` | - | Called when the requested providers fail and the session is rebuilt on `cpu`/`wasm`. |
706
+
707
+ `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:
708
+
709
+ ```ts
710
+ let degraded: unknown = null;
711
+ const service = new IndraOcrService({
712
+ session: {
713
+ executionProviders: [{ name: "cuda", deviceId: 0 }, "cpu"],
714
+ onSessionFallback: (error) => (degraded ||= error),
715
+ },
716
+ });
717
+ await service.initialize();
718
+ if (degraded) {
719
+ // Acceleration was dropped. Fail over to your own runtime profile.
720
+ }
721
+ ```
722
+
723
+ It can fire once per model session.
724
+
725
+ ### Model host mirror
726
+
727
+ 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.
728
+
729
+ Set `PPU_INDRA_OCR_MODEL_MIRROR=1` and a download that exhausts its retries falls back to the GitHub copy in `models/`, which serves byte-identical files:
730
+
731
+ ```sh
732
+ PPU_INDRA_OCR_MODEL_MIRROR=1 bun run your-script.ts
733
+ ```
734
+
735
+ 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.
736
+
737
+ ## Benchmark
738
+
739
+ 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`.
740
+
741
+ Representative results on Apple M1 / Bun 1.4.2 (9 rounds) at the shipped defaults, `convert()` per page, opencv and canvas-native:
742
+
743
+ ```bash
744
+ task median +/-stddev min max
745
+ --------------------------------------------------------------------
746
+ opencv two-column 290.3 ms 30.6 ms 279.8 ms 374.9 ms
747
+ opencv table 243.5 ms 9.7 ms 236.9 ms 269.1 ms
748
+ opencv receipt 155.5 ms 18.0 ms 153.6 ms 209.4 ms
749
+ canvas-native two-column 590.9 ms 29.7 ms 554.6 ms 644.4 ms
750
+ canvas-native table 498.8 ms 17.6 ms 493.0 ms 537.7 ms
751
+ canvas-native receipt 327.7 ms 24.2 ms 319.6 ms 394.8 ms
752
+ ```
753
+
754
+ `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.
755
+
756
+ ### Against ppu-paddle-ocr
757
+
758
+ `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. 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.
759
+
760
+ **Document pages** (`bun bench/vs-paddle.ts`: the test pages plus the receipt, 5 rounds each):
761
+
762
+ | Page | ms Indra / Paddle | char-F1 | token-F1 | CER |
763
+ | :-------------- | :---------------- | :------------ | :------------ | :------------ |
764
+ | two-column.png | 304 / 503 | 1.000 / 1.000 | 1.000 / 0.972 | 0.001 / 0.683 |
765
+ | rotated-90.png | 294 / 386 | 1.000 / 0.000 | 1.000 / 0.000 | 0.001 / 1.000 |
766
+ | rotated-180.png | 306 / 513 | 1.000 / 0.579 | 1.000 / 0.016 | 0.001 / 0.784 |
767
+ | table.png | 244 / 267 | 1.000 / 1.000 | 1.000 / 1.000 | 0.007 / 0.007 |
768
+ | chinese.png | 270 / 260 | 1.000 / 1.000 | 1.000 / 1.000 | 0.000 / 0.000 |
769
+ | receipt.jpg | 153 / 117 | 0.979 / 0.997 | 0.873 / 0.954 | 0.024 / 0.003 |
770
+
771
+ 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.
772
+
773
+ **SROIE receipts** (`SROIE_DIR=... bun bench/vs-paddle.ts`: 50 receipts, every 12th of the ICDAR 2019 SROIE set):
774
+
775
+ | Library | median ms | p90 ms | peak RSS | char-F1 | token-F1 | CER |
776
+ | :------ | :-------- | :----- | :------- | :------ | :------- | :---- |
777
+ | Indra | 188 | 822 | 1162 MB | 0.973 | 0.848 | 0.156 |
778
+ | Paddle | 220 | 434 | 1368 MB | 0.972 | 0.753 | 0.123 |
779
+
780
+ 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.
781
+
782
+ ## How the Port Is Checked
783
+
784
+ `scripts/golden/` renders test pages and records every stage of the Python reference (`indra-ocr` 0.3.1) on them: orientation, skew, detection, recognition, reading order, the text layer and the final page. 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. The canvas-native engine stays within a token-F1 of 0.98.
785
+
786
+ ## Ecosystem
787
+
788
+ 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):
789
+
790
+ | Library | What it does |
791
+ | :------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- |
792
+ | [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. |
793
+ | [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. |
794
+ | [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. |
795
+ | [ppu-doclayout](https://github.com/PT-Perkasa-Pilar-Utama/ppu-doclayout) | Document layout analysis with PaddlePaddle PP-DocLayout (tables, figures, text regions). |
796
+ | [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. |
797
+ | [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). |
798
+ | [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. |
799
+
800
+ ## Contributing
801
+
802
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions, code-quality requirements, and the pull request process.
803
+
804
+ ## License
805
+
806
+ - **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).
807
+ - **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.
808
+ - **License status:** [LICENSE-STATUS.md](LICENSE-STATUS.md) records our request to Datalab and what may change. It is subject to change.
809
+ - Indra OCR is made by [Datalab](https://www.datalab.to). For commercial use beyond the license, or the highest accuracy, see their platform.
810
+
811
+ ## Support
812
+
813
+ [Open an issue](https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/issues).
814
+
815
+ ## Scripts
816
+
817
+ Recommended development environment is Linux-based. Library template: https://github.com/aquapi/lib-template
818
+
819
+ | Script | Command | Description |
820
+ | :------------------------- | :----------------------------------- | :--------------------------------------------------------- |
821
+ | `bun task build` | `bun run scripts/build.ts` | Emit `.js` and `.d.ts` to `lib/`. |
822
+ | `bun task prepare-publish` | `bun run scripts/prepare-publish.ts` | Stage `package.json`, `README.md` and notices into `lib/`. |
823
+ | `bun task bench` | `bun run scripts/bench.ts` | Run `*.bench.ts` files. |
824
+ | `bun bench/vs-paddle.ts` | - | Compare with ppu-paddle-ocr on document pages or SROIE. |
825
+ | `bun run build:pages` | build + `playground/build-pages.ts` | Assemble the playground for Cloudflare. |
826
+
827
+ To run a specific benchmark file:
828
+
829
+ ```bash
830
+ bun task bench index # Run bench/index.bench.ts
831
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ppu-indra-ocr",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "TypeScript SDK for Datalab's Indra OCR models: page orientation, line detection, recognition (Latin, Cyrillic, Greek, Devanagari, Bengali, Chinese), reading order, layout blocks, markdown, optional math, and PDF text layers. Runs on Node.js, Bun, Deno, browsers, web workers and React Native via ONNX Runtime.",
5
5
  "keywords": [
6
6
  "accurate-ocr",
package/pdf/index.js CHANGED
@@ -1 +1 @@
1
- import{init}from"@embedpdf/pdfium";import{isPdf,pdfPage}from"../indra/document.js";import{PdfiumDocument}from"./pdfium.js";export{isPdf}from"../indra/document.js";export{PdfiumDocument,PdfiumPage}from"./pdfium.js";export let PDFIUM_VERSION="2.15.1";let shared;export async function loadPdfium(wasm){let bytes=wasm instanceof ArrayBuffer?wasm:await fetchWasm(wasm);let module=await init({wasmBinary:bytes});module.PDFiumExt_Init();return module}async function fetchWasm(url){if(!url&&globalThis.process?.versions?.node){const{createRequire}=await import("module");const{readFile}=await import("fs/promises");let file=await readFile(createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"));return file.buffer.slice(file.byteOffset,file.byteOffset+file.byteLength)}let src=url??`https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@${PDFIUM_VERSION}/dist/pdfium.wasm`;let res=await fetch(src);if(!res.ok)throw new Error(`could not fetch pdfium.wasm from ${src}: HTTP ${res.status}`);return res.arrayBuffer()}function errorPage(err){let name=err instanceof Error?err.name:"Error";let message=err instanceof Error?err.message:String(err);return{lines:[],text:"",markdown:"",blocks:[],source:"error",note:`${name}: ${message}`,rotation:0,skew:0,timings:{total_ms:0}}}export async function convertPdf(service,bytes,options={}){if(!isPdf(bytes))throw new Error("not a PDF: no %PDF- header in the first 1024 bytes");let pdfium=options.pdfium??await(shared??=loadPdfium());let doc=new PdfiumDocument(pdfium,bytes instanceof Uint8Array?bytes:new Uint8Array(bytes),options.password);try{let n=options.maxPages?Math.min(doc.pageCount,options.maxPages):doc.pageCount;let pages=[];for(let i=0;i<n;i++){try{let page=doc.page(i);try{pages.push(await pdfPage(service.pipeline,page,options))}finally{page.close()}}catch(err){pages.push(errorPage(err))}}return pages}finally{doc.close()}}
1
+ import{init}from"@embedpdf/pdfium";import{isPdf,pdfPage}from"../indra/document.js";import{PdfiumDocument}from"./pdfium.js";export{isPdf}from"../indra/document.js";export{PdfiumDocument,PdfiumPage}from"./pdfium.js";export let PDFIUM_VERSION="2.15.1";let shared;export async function loadPdfium(wasm){let bytes=wasm instanceof ArrayBuffer?wasm:await fetchWasm(wasm);let module=await init({wasmBinary:bytes});module.PDFiumExt_Init();return module}async function fetchWasm(url){if(!url&&globalThis.process?.versions?.node){const{createRequire}=await import("module");const{readFile}=await import("fs/promises");let file=await readFile(process.env.PPU_INDRA_OCR_PDFIUM_WASM||createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"));return file.buffer.slice(file.byteOffset,file.byteOffset+file.byteLength)}let src=url??`https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@${PDFIUM_VERSION}/dist/pdfium.wasm`;let res=await fetch(src);if(!res.ok)throw new Error(`could not fetch pdfium.wasm from ${src}: HTTP ${res.status}`);return res.arrayBuffer()}function errorPage(err){let name=err instanceof Error?err.name:"Error";let message=err instanceof Error?err.message:String(err);return{lines:[],text:"",markdown:"",blocks:[],source:"error",note:`${name}: ${message}`,rotation:0,skew:0,timings:{total_ms:0}}}export async function convertPdf(service,bytes,options={}){if(!isPdf(bytes))throw new Error("not a PDF: no %PDF- header in the first 1024 bytes");let pdfium=options.pdfium??await(shared??=loadPdfium());let doc=new PdfiumDocument(pdfium,bytes instanceof Uint8Array?bytes:new Uint8Array(bytes),options.password);try{let n=options.maxPages?Math.min(doc.pageCount,options.maxPages):doc.pageCount;let pages=[];for(let i=0;i<n;i++){try{let page=doc.page(i);try{pages.push(await pdfPage(service.pipeline,page,options))}finally{page.close()}}catch(err){pages.push(errorPage(err))}}return pages}finally{doc.close()}}