ppu-indra-ocr 0.0.0-stage → 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.
- package/LICENSE +202 -0
- package/LICENSE-STATUS.md +112 -0
- package/NOTICE +20 -0
- package/README.md +830 -2
- package/cli/commands.d.ts +9 -0
- package/cli/commands.js +11 -0
- package/cli/help.d.ts +5 -0
- package/cli/help.js +50 -0
- package/cli/index.d.ts +2 -0
- package/cli/index.js +6 -0
- package/cli/io.d.ts +27 -0
- package/cli/io.js +6 -0
- package/cli/options.d.ts +19 -0
- package/cli/options.js +1 -0
- package/cli/run.d.ts +1 -0
- package/cli/run.js +9 -0
- package/coi-serviceworker.js +130 -0
- package/core/batch.d.ts +53 -0
- package/core/batch.js +1 -0
- package/core/indra-ocr.service.d.ts +65 -0
- package/core/indra-ocr.service.js +1 -0
- package/core/one-shot.d.ts +5 -0
- package/core/one-shot.js +1 -0
- package/core/opencv-image-ops.d.ts +10 -0
- package/core/opencv-image-ops.js +1 -0
- package/core/platform.d.ts +40 -0
- package/core/session-factory.d.ts +23 -0
- package/core/session-factory.js +1 -0
- package/exports.d.ts +15 -0
- package/exports.js +1 -0
- package/index.d.ts +11 -0
- package/index.js +1 -0
- package/indra/assemble.d.ts +22 -0
- package/indra/assemble.js +3 -0
- package/indra/det-post.d.ts +34 -0
- package/indra/det-post.js +1 -0
- package/indra/document.d.ts +36 -0
- package/indra/document.js +1 -0
- package/indra/image.d.ts +43 -0
- package/indra/image.js +1 -0
- package/indra/layout-post.d.ts +35 -0
- package/indra/layout-post.js +9 -0
- package/indra/lines.d.ts +19 -0
- package/indra/lines.js +1 -0
- package/indra/math.d.ts +54 -0
- package/indra/math.js +1 -0
- package/indra/numeric.d.ts +9 -0
- package/indra/numeric.js +1 -0
- package/indra/order-post.d.ts +37 -0
- package/indra/order-post.js +1 -0
- package/indra/pipeline.d.ts +65 -0
- package/indra/pipeline.js +1 -0
- package/indra/rec-preproc.d.ts +28 -0
- package/indra/rec-preproc.js +1 -0
- package/indra/recognize.d.ts +29 -0
- package/indra/recognize.js +1 -0
- package/indra/textlayer.d.ts +72 -0
- package/indra/textlayer.js +2 -0
- package/indra/ts-image-ops.d.ts +3 -0
- package/indra/ts-image-ops.js +1 -0
- package/indra/types.d.ts +101 -0
- package/indra/upright.d.ts +28 -0
- package/indra/upright.js +1 -0
- package/indra/util.d.ts +14 -0
- package/indra/util.js +1 -0
- package/indra/vocab.d.ts +14 -0
- package/indra/vocab.js +1 -0
- package/interface.d.ts +61 -0
- package/mobile/index.d.ts +26 -0
- package/mobile/index.js +1 -0
- package/mobile/indra-ocr.service.mobile.d.ts +11 -0
- package/mobile/indra-ocr.service.mobile.js +1 -0
- package/mobile/platform.mobile.d.ts +16 -0
- package/mobile/platform.mobile.js +1 -0
- package/model-catalogue.d.ts +38 -0
- package/model-catalogue.js +1 -0
- package/package.json +109 -4
- package/pdf/index.d.ts +31 -0
- package/pdf/index.js +1 -0
- package/pdf/pdfium.d.ts +27 -0
- package/pdf/pdfium.js +1 -0
- package/processor/indra-ocr.service.d.ts +28 -0
- package/processor/indra-ocr.service.js +1 -0
- package/processor/model-cache.d.ts +17 -0
- package/processor/model-cache.js +2 -0
- package/processor/platform.node.d.ts +13 -0
- package/processor/platform.node.js +1 -0
- package/utils.d.ts +36 -0
- package/utils.js +2 -0
- package/web/index.d.ts +26 -0
- package/web/index.js +1 -0
- package/web/indra-ocr.service.web.d.ts +15 -0
- package/web/indra-ocr.service.web.js +1 -0
- package/web/platform.web.d.ts +32 -0
- package/web/platform.web.js +1 -0
package/README.md
CHANGED
|
@@ -1,3 +1,831 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ppu-indra-ocr
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/ppu-indra-ocr) [](https://www.npmjs.com/package/ppu-indra-ocr) [](https://jsr.io/@snowfluke/ppu-indra-ocr) [](https://www.npmjs.com/package/ppu-indra-ocr#provenance) [](./LICENSE) [](https://scorecard.dev/viewer/?uri=github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr) [](https://socket.dev/npm/package/ppu-indra-ocr)
|
|
4
|
+
|
|
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
|
+
|
|
9
|
+
> [!WARNING]
|
|
10
|
+
> **Read Datalab's license before you use this package.**
|
|
11
|
+
>
|
|
12
|
+
> This package runs the Indra OCR model weights by Datalab. The weights are
|
|
13
|
+
> not under this package's Apache-2.0 license. They are under Datalab's
|
|
14
|
+
> modified OpenRAIL-M license, and you accept it when the library downloads
|
|
15
|
+
> them for you. You may not use the weights at all if:
|
|
16
|
+
>
|
|
17
|
+
> - your organization had more than USD 20M in revenue last year, or has
|
|
18
|
+
> raised more than USD 20M, unless your use is personal or research; or
|
|
19
|
+
> - your organization offers any product or service that competes with
|
|
20
|
+
> Datalab. This clause has no exception for personal use or research.
|
|
21
|
+
>
|
|
22
|
+
> You are responsible for your own compliance. Read
|
|
23
|
+
> [LICENSE-STATUS.md](LICENSE-STATUS.md) for the terms, our open request to
|
|
24
|
+
> Datalab, and what may change. This is a community project. Datalab does not
|
|
25
|
+
> endorse it.
|
|
26
|
+
|
|
27
|
+

|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { IndraOcrService } from "ppu-indra-ocr";
|
|
31
|
+
|
|
32
|
+
const service = new IndraOcrService();
|
|
33
|
+
await service.initialize();
|
|
34
|
+
|
|
35
|
+
const page = await service.convert(await Bun.file("scan.png").arrayBuffer());
|
|
36
|
+
console.log(page.markdown);
|
|
37
|
+
|
|
38
|
+
await service.destroy();
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Table of Contents
|
|
42
|
+
|
|
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) |
|
|
111
|
+
|
|
112
|
+
## Installation
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
npm install ppu-indra-ocr onnxruntime-node onnxruntime-web
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Omit `onnxruntime-node` or `onnxruntime-web` depending on your target environment (Node/Bun vs browser). Add `@embedpdf/pdfium` for PDF input.
|
|
119
|
+
|
|
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.
|
|
121
|
+
|
|
122
|
+
**When the models download, you accept Datalab's license for the weights.**
|
|
123
|
+
Check [LICENSE-STATUS.md](LICENSE-STATUS.md) first.
|
|
124
|
+
|
|
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
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
import { IndraOcrService } from "ppu-indra-ocr";
|
|
196
|
+
|
|
197
|
+
const service = new IndraOcrService({ verbose: true });
|
|
198
|
+
await service.initialize();
|
|
199
|
+
|
|
200
|
+
const page = await service.convert(await Bun.file("./assets/receipt.jpg").arrayBuffer());
|
|
201
|
+
console.log(page.markdown);
|
|
202
|
+
|
|
203
|
+
await service.destroy();
|
|
204
|
+
```
|
|
205
|
+
|
|
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 }`.
|
|
207
|
+
|
|
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.
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
import { detect, ocr } from "ppu-indra-ocr";
|
|
212
|
+
|
|
213
|
+
const page = await ocr(imageBytes);
|
|
214
|
+
const boxes = await detect(imageBytes); // [x0, y0, x1, y1, score][]
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### The Page Result
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
type Page = {
|
|
221
|
+
markdown: string | null; // headings, paragraphs, lists, tables as HTML
|
|
222
|
+
text: string; // every line, one per row, in reading order
|
|
223
|
+
lines: { box: [x0, y0, x1, y1]; text: string; conf: number }[];
|
|
224
|
+
blocks: { label: BlockLabel; bbox: [x0, y0, x1, y1]; text: string }[];
|
|
225
|
+
source: "ocr" | "text" | "hybrid" | "error"; // text / hybrid: from a PDF text layer
|
|
226
|
+
note: string; // why the page took its path
|
|
227
|
+
rotation: number; // degrees counter-clockwise the input was turned
|
|
228
|
+
skew: number; // degrees of small tilt undone
|
|
229
|
+
timings: Record<string, number>; // milliseconds per stage, with total_ms
|
|
230
|
+
};
|
|
231
|
+
```
|
|
232
|
+
|
|
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.
|
|
234
|
+
|
|
235
|
+
### Running the Stages Yourself
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
const { turns } = await service.orient(image); // quarter turns, from orient.onnx
|
|
239
|
+
const { image: upright, skew } = await service.straighten(image, turns);
|
|
240
|
+
const boxes = (await service.detect(upright)).map(([x0, y0, x1, y1]) => [x0, y0, x1, y1] as const);
|
|
241
|
+
const lines = await service.recognize(upright, boxes); // text, confidence, character positions
|
|
242
|
+
const texts = lines.map((l) => l.text);
|
|
243
|
+
const { order, cls, same } = await service.order(boxes, texts, upright.width, upright.height);
|
|
244
|
+
```
|
|
245
|
+
|
|
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.
|
|
271
|
+
|
|
272
|
+
### Detection Only
|
|
273
|
+
|
|
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
|
|
377
|
+
|
|
378
|
+
```ts
|
|
379
|
+
import { IndraOcrService } from "ppu-indra-ocr";
|
|
380
|
+
import { convertPdf, isPdf } from "ppu-indra-ocr/pdf";
|
|
381
|
+
|
|
382
|
+
const service = new IndraOcrService();
|
|
383
|
+
await service.initialize();
|
|
384
|
+
|
|
385
|
+
const pages = isPdf(bytes)
|
|
386
|
+
? await convertPdf(service, bytes, { mode: "auto" })
|
|
387
|
+
: [await service.convert(bytes)];
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
| Option | Default | Meaning |
|
|
391
|
+
| ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
|
392
|
+
| `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 |
|
|
393
|
+
| `dpi` | `200` | Render resolution for OCR |
|
|
394
|
+
| `pdfOrder` | `true` | Keep the PDF content order when it is coherent |
|
|
395
|
+
| `imageOcr` | `true` | On text-layer pages, OCR lines with no text-layer characters (text in images) |
|
|
396
|
+
| `maxPages` | all | Read at most this many pages |
|
|
397
|
+
| `password` | - | Password of an encrypted PDF |
|
|
398
|
+
|
|
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`.
|
|
400
|
+
|
|
401
|
+
## Math
|
|
402
|
+
|
|
403
|
+
```ts
|
|
404
|
+
const service = new IndraOcrService({ math: true });
|
|
405
|
+
```
|
|
406
|
+
|
|
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.
|
|
408
|
+
|
|
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. |
|
|
421
|
+
|
|
422
|
+
```ts
|
|
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" });
|
|
428
|
+
```
|
|
429
|
+
|
|
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):
|
|
431
|
+
|
|
432
|
+
```html
|
|
433
|
+
<script src="https://cdn.jsdelivr.net/npm/@techstark/opencv-js@5.0.0-release.1/dist/opencv.js"></script>
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
Without OpenCV.js on `globalThis.cv`, `initialize()` throws and says so.
|
|
437
|
+
|
|
438
|
+
## Web / Browser Support
|
|
439
|
+
|
|
440
|
+
Import from `ppu-indra-ocr/web` for browser-native capabilities (`HTMLCanvasElement`, `OffscreenCanvas`, `fetch` buffering).
|
|
441
|
+
|
|
442
|
+
### Using a Bundler (Vite, Webpack, etc.)
|
|
443
|
+
|
|
444
|
+
```ts
|
|
445
|
+
import { IndraOcrService } from "ppu-indra-ocr/web";
|
|
446
|
+
|
|
447
|
+
const service = new IndraOcrService(); // canvas-native, wasm
|
|
448
|
+
await service.initialize();
|
|
449
|
+
|
|
450
|
+
const file = document.getElementById("upload").files[0];
|
|
451
|
+
const page = await service.convert(await file.arrayBuffer());
|
|
452
|
+
console.log(page.markdown);
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
Models are fetched from the default URLs or from `models`.
|
|
456
|
+
|
|
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:
|
|
538
|
+
|
|
539
|
+
```html
|
|
540
|
+
<script src="/coi-serviceworker.js"></script>
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
Resolve the shipped copy from the package, e.g. in a build step:
|
|
544
|
+
|
|
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)
|
|
553
|
+
|
|
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
|
+
```
|
|
559
|
+
|
|
560
|
+
```ts
|
|
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();
|
|
571
|
+
```
|
|
572
|
+
|
|
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.**
|
|
574
|
+
|
|
575
|
+
**Hardware acceleration is opt-in**, mobile inference runs on CPU by default. There is no WebGPU on React Native:
|
|
576
|
+
|
|
577
|
+
```ts
|
|
578
|
+
// Android: ["nnapi"]. iOS: ["coreml"].
|
|
579
|
+
new IndraOcrService({ session: { executionProviders: ["nnapi"] } });
|
|
580
|
+
```
|
|
581
|
+
|
|
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:
|
|
596
|
+
|
|
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 |
|
|
606
|
+
|
|
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).
|
|
608
|
+
|
|
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.
|
|
610
|
+
|
|
611
|
+
### Cache Location (Node / Bun)
|
|
612
|
+
|
|
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).
|
|
637
|
+
- **PDF text layer:** any script.
|
|
638
|
+
|
|
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
|
+
```
|