ppu-indra-ocr 0.1.2 → 0.2.1
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-STATUS.md +15 -7
- package/README.md +105 -68
- package/cli/commands.js +2 -2
- package/cli/help.d.ts +1 -1
- package/cli/help.js +3 -2
- package/cli/options.d.ts +3 -0
- package/cli/options.js +1 -1
- package/core/indra-ocr.service.d.ts +19 -7
- package/core/indra-ocr.service.js +1 -1
- package/core/opencv-image-ops.js +1 -1
- package/core/platform.d.ts +2 -0
- package/exports.d.ts +2 -2
- package/exports.js +1 -1
- package/indra/assemble.d.ts +38 -13
- package/indra/assemble.js +2 -2
- package/indra/document.d.ts +0 -4
- package/indra/document.js +1 -1
- package/indra/image.d.ts +2 -2
- package/indra/layer-check.d.ts +26 -0
- package/indra/layer-check.js +1 -0
- package/indra/lines.d.ts +8 -3
- package/indra/lines.js +1 -1
- package/indra/lm.d.ts +51 -0
- package/indra/lm.js +1 -0
- package/indra/npz.d.ts +14 -0
- package/indra/npz.js +1 -0
- package/indra/order-post.d.ts +9 -0
- package/indra/order-post.js +1 -1
- package/indra/pipeline.d.ts +33 -17
- package/indra/pipeline.js +1 -1
- package/indra/rec-preproc.d.ts +14 -2
- package/indra/rec-preproc.js +1 -1
- package/indra/recognize.d.ts +44 -6
- package/indra/recognize.js +1 -1
- package/indra/recognizers.d.ts +52 -0
- package/indra/recognizers.js +1 -0
- package/indra/rtl.d.ts +34 -0
- package/indra/rtl.js +1 -0
- package/indra/text-runs.d.ts +35 -0
- package/indra/text-runs.js +2 -0
- package/indra/textlayer.d.ts +46 -16
- package/indra/textlayer.js +1 -2
- package/indra/ts-image-ops.js +1 -1
- package/indra/types.d.ts +39 -7
- package/indra/unicode-data.d.ts +4 -0
- package/indra/unicode-data.js +1 -0
- package/indra/unicode.d.ts +24 -0
- package/indra/unicode.js +1 -0
- package/indra/upright.d.ts +13 -2
- package/indra/upright.js +1 -1
- package/indra/vocab.d.ts +3 -1
- package/indra/vocab.js +1 -1
- package/interface.d.ts +13 -2
- package/mobile/platform.mobile.d.ts +1 -0
- package/mobile/platform.mobile.js +1 -1
- package/model-catalogue.d.ts +76 -20
- package/model-catalogue.js +1 -1
- package/package.json +1 -1
- package/pdf/index.js +1 -1
- package/pdf/pdfium.d.ts +2 -0
- package/pdf/pdfium.js +1 -1
- package/processor/indra-ocr.service.d.ts +7 -2
- package/processor/indra-ocr.service.js +1 -1
- package/processor/platform.node.d.ts +1 -0
- package/processor/platform.node.js +1 -1
- package/web/platform.web.d.ts +1 -0
- package/web/platform.web.js +1 -1
package/LICENSE-STATUS.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> **Subject to change.** This page records where this project stands on the
|
|
4
4
|
> license of the Indra OCR model weights. It changes when Datalab answers us
|
|
5
|
-
> or when Datalab changes its license. Last updated: 2026-10-
|
|
5
|
+
> or when Datalab changes its license. Last updated: 2026-10-20.
|
|
6
6
|
>
|
|
7
7
|
> This page is not legal advice. Read the license yourself before you use the
|
|
8
8
|
> weights.
|
|
@@ -69,7 +69,7 @@ written answer on four points:
|
|
|
69
69
|
statement that Datalab does not endorse the project?
|
|
70
70
|
4. Does Section 8 apply to the OCR text that users get from the model?
|
|
71
71
|
|
|
72
|
-
As of 2026-10-
|
|
72
|
+
As of 2026-10-20, we have no reply. We do not read silence as permission.
|
|
73
73
|
Datalab has not approved or endorsed this project.
|
|
74
74
|
|
|
75
75
|
## What this project does with the weights
|
|
@@ -77,13 +77,21 @@ Datalab has not approved or endorsed this project.
|
|
|
77
77
|
- **Default download.** The library downloads the weights from Datalab's own
|
|
78
78
|
repository,
|
|
79
79
|
[datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr),
|
|
80
|
-
pinned to commit `
|
|
80
|
+
pinned to one commit per model preset: `a1283c4b42a273c09480ad50e71461daff50fcc7`
|
|
81
|
+
(tag v1.1.0, Indra OCR 1.1, the default) and
|
|
82
|
+
`d7c839c892bfe4b8993373db64c62f154d05d70b` (tag v3.1, Indra OCR 1.0).
|
|
83
|
+
- **Same license in 1.1.** The license file of tag v1.1.0 is byte for byte
|
|
84
|
+
the license file of tag v3.1 (sha256
|
|
85
|
+
`50c88a018a7ee322e89f6b09401b237beb0cd331685879405b3db48993950a5f`). Indra OCR 1.1
|
|
86
|
+
changed the weights, not the terms.
|
|
81
87
|
- **No weights in the package.** The npm and JSR packages contain the code
|
|
82
88
|
only.
|
|
83
|
-
- **Mirrors.**
|
|
84
|
-
Datalab's license and attribution: [models/](models/)
|
|
85
|
-
and the Hugging Face
|
|
86
|
-
|
|
89
|
+
- **Mirrors.** Unmodified copies of the pinned weights exist, each with
|
|
90
|
+
Datalab's license and attribution: [models/](models/) (v3.1) and
|
|
91
|
+
[models/v1.1/](models/v1.1/) in this repository, and the Hugging Face
|
|
92
|
+
repository
|
|
93
|
+
[snowfluke/ppu-indra-ocr-models](https://huggingface.co/snowfluke/ppu-indra-ocr-models)
|
|
94
|
+
(v3.1 at its root, v1.1 in `v1.1/`).
|
|
87
95
|
The library uses the GitHub copy only when you set
|
|
88
96
|
`PPU_INDRA_OCR_MODEL_MIRROR=1` and Hugging Face fails. It does not use the
|
|
89
97
|
Hugging Face copy.
|
package/README.md
CHANGED
|
@@ -65,6 +65,7 @@ await service.destroy();
|
|
|
65
65
|
- [Multithreaded WASM (Cross-Origin Isolation)](#multithreaded-wasm-cross-origin-isolation)
|
|
66
66
|
- [React Native (Mobile)](#react-native-mobile)
|
|
67
67
|
- [Models and Language Support](#models-and-language-support)
|
|
68
|
+
- [Model Presets](#model-presets)
|
|
68
69
|
- [Indra OCR Models](#indra-ocr-models)
|
|
69
70
|
- [Cache Location](#cache-location-node--bun)
|
|
70
71
|
- [Languages](#languages)
|
|
@@ -86,9 +87,9 @@ await service.destroy();
|
|
|
86
87
|
|
|
87
88
|
## Why ppu-indra-ocr?
|
|
88
89
|
|
|
89
|
-
- **The whole page, not just the text.** Orientation, deskew, line detection, Latin and
|
|
90
|
+
- **The whole page, not just the text.** Orientation (vertical writing too), deskew up to 45 degrees, line detection, recognizers for Latin, CJK, right-to-left and other scripts, reading order, layout labels, and markdown with headings, lists and tables, in one `convert()` call.
|
|
90
91
|
- **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
|
|
92
|
+
- **Small models.** About 9 MB of ONNX models load at start; the other script recognizers and the language models load when a page needs them. Pinned to one upstream revision per [model preset](#model-presets): `v1.1` (Indra OCR 1.1, the default) or `v3.1` (the first release).
|
|
92
93
|
- **Matches the reference.** On the `opencv` engine, line text, layout blocks and markdown match the Python `indra-ocr` exactly on every test page. See [How the Port Is Checked](#how-the-port-is-checked).
|
|
93
94
|
- **Runs everywhere**, Node.js, Bun, Deno, web browsers, web workers, browser extensions, and React Native (iOS/Android), on the same runtime adapters as [ppu-paddle-ocr](https://github.com/PT-Perkasa-Pilar-Utama/ppu-paddle-ocr).
|
|
94
95
|
- **Composable.** Every stage is a method, so you can run one stage, swap a stage, or chain your own pipeline.
|
|
@@ -117,7 +118,7 @@ npm install ppu-indra-ocr onnxruntime-node onnxruntime-web
|
|
|
117
118
|
|
|
118
119
|
Omit `onnxruntime-node` or `onnxruntime-web` depending on your target environment (Node/Bun vs browser). Add `@embedpdf/pdfium` for PDF input.
|
|
119
120
|
|
|
120
|
-
The first `initialize()` downloads the models (about
|
|
121
|
+
The first `initialize()` downloads the base models (about 9 MB, 29 MB with math) from Datalab's Hugging Face repository, pinned to one revision, and caches them in `~/.cache/ppu-indra-ocr` on Node and Bun. The CJK, right-to-left and other-script recognizers (5 to 10 MB each) and the language models (12 to 19 MB each) download the first time a page needs them. That can happen on the first page: on a Latin receipt, one unsure line can pull `rec_rtl.onnx` and `lm.npz` (about 20 MB) in the middle of `convert()`. `IndraOcrService.downloadModels()` (or `ppu-indra-ocr download-models`) fetches them all up front.
|
|
121
122
|
|
|
122
123
|
**When the models download, you accept Datalab's license for the weights.**
|
|
123
124
|
Check [LICENSE-STATUS.md](LICENSE-STATUS.md) first.
|
|
@@ -162,7 +163,7 @@ Intel Macs and Alpine (musl) are not covered, onnxruntime ships no darwin-x64 or
|
|
|
162
163
|
<details>
|
|
163
164
|
<summary>Size, slim variant, and OS warnings</summary>
|
|
164
165
|
|
|
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
|
|
166
|
+
- **Size and first run.** 53-69 MB download depending on the platform, about 165 MB extracted on macOS (the executable embeds the Bun runtime, ONNX Runtime, pdfium and the image engines). Models still download to `~/.cache/ppu-indra-ocr` on first run, exactly like the npm CLI.
|
|
166
167
|
- **Slim variant.** Each target also ships a `-slim` archive (e.g. `ppu-indra-ocr-linux-x64-slim.tar.gz`) that excludes the OpenCV engine: about 30 MB smaller extracted, 4-5 MB smaller to download. It always uses the `canvas-native` engine and rejects `--engine opencv`. Pick slim for disk and memory footprint; pick full if you want results that match the Python reference exactly.
|
|
167
168
|
- **macOS Gatekeeper.** The binaries are ad-hoc signed but not Apple-notarized. If macOS blocks a downloaded binary, clear the quarantine flag: `xattr -d com.apple.quarantine ./ppu-indra-ocr-darwin-arm64` (or right-click, Open, once).
|
|
168
169
|
- **Windows SmartScreen.** Unrecognized-app warning on first run: "More info", then "Run anyway".
|
|
@@ -235,7 +236,7 @@ Block labels: `Text`, `Section-Header`, `Page-Header`, `Page-Footer`, `List-Grou
|
|
|
235
236
|
### Running the Stages Yourself
|
|
236
237
|
|
|
237
238
|
```ts
|
|
238
|
-
const { turns } = await service.orient(image); // quarter turns,
|
|
239
|
+
const { turns } = await service.orient(image); // quarter turns, or 4 for vertical writing
|
|
239
240
|
const { image: upright, skew } = await service.straighten(image, turns);
|
|
240
241
|
const boxes = (await service.detect(upright)).map(([x0, y0, x1, y1]) => [x0, y0, x1, y1] as const);
|
|
241
242
|
const lines = await service.recognize(upright, boxes); // text, confidence, character positions
|
|
@@ -243,7 +244,7 @@ const texts = lines.map((l) => l.text);
|
|
|
243
244
|
const { order, cls, same } = await service.order(boxes, texts, upright.width, upright.height);
|
|
244
245
|
```
|
|
245
246
|
|
|
246
|
-
`recognize` takes boxes from any detector, one line per box. Boxes should hug the text: the recognizer
|
|
247
|
+
`recognize` takes boxes from any detector, one line per box. Boxes should hug the text: the recognizer crops 0.3 x the box height on each side and 0.2 x above and below (on v1.1 the main recognizer also sees 1.6 x the height above and below as context). Trim boxes that carry their own padding first; PaddleOCR's boxes, for example, are padded to 1.8 x the text height. For a vertical page, pass the page turned by `straighten(image, 4)` and `recognize(image, boxes, true)`.
|
|
247
248
|
|
|
248
249
|
`toMarkdown`, `joinLines` and `orderXYCut` are exported as plain functions. `service.pipeline` gives the lower-level stages (line splitting, assembly) when you need them. `readMath(image, boxes)` reads boxes as text with inline LaTeX on a service created with `math: true`.
|
|
249
250
|
|
|
@@ -267,7 +268,7 @@ const local = new IndraOcrService({
|
|
|
267
268
|
});
|
|
268
269
|
```
|
|
269
270
|
|
|
270
|
-
Roles: `det`, `rec`, `
|
|
271
|
+
Roles: `det`, `rec`, `script`, `orient`, `order`, `meta`; the script recognizers `recCjk`, `recRtl`, `recWorld`; the language models `lm`, `lmCjk`, `lmWorld`; and with math `mathCls`, `mathEnc`, `mathDecInit`, `mathDecStep`, `mathMeta`. `MODEL_FILES` maps each role to its file name, `MODEL_PRESETS` holds each preset's pinned commit and file list, and `defaultModelUrl(role, preset)` gives the default URL. A role the preset does not have (v3.1 has no `recRtl`) and that you do not pass stays off.
|
|
271
272
|
|
|
272
273
|
### Detection Only
|
|
273
274
|
|
|
@@ -303,20 +304,25 @@ bunx ppu-indra-ocr detect receipt.jpg
|
|
|
303
304
|
# zero-install (no local ppu-indra-ocr): npx can pull both packages
|
|
304
305
|
npx -p onnxruntime-node -p ppu-indra-ocr ppu-indra-ocr convert scan.png
|
|
305
306
|
|
|
306
|
-
#
|
|
307
|
+
# the smaller first-release models, or no language models
|
|
308
|
+
bunx ppu-indra-ocr convert scan.png --model v3.1
|
|
309
|
+
bunx ppu-indra-ocr convert scan.png --no-lm
|
|
310
|
+
|
|
311
|
+
# pre-warm / clear the model cache, list the model presets and files
|
|
307
312
|
bunx ppu-indra-ocr download-models
|
|
308
313
|
bunx ppu-indra-ocr clear-cache
|
|
309
314
|
bunx ppu-indra-ocr models
|
|
310
315
|
```
|
|
311
316
|
|
|
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
|
-
| `--
|
|
318
|
-
| `--model
|
|
319
|
-
|
|
|
317
|
+
| Flags | Applies to | Purpose |
|
|
318
|
+
| :-------------------------------------------------------------- | :----------- | :---------------------------------------------------------- |
|
|
319
|
+
| `--format md\|text\|json`, `--out <dir>` | `convert` | Output format; one file per input (`.md`, `.txt`, `.jsonl`) |
|
|
320
|
+
| `--math`, `--keep-furniture`, `--engine`, `--timings` | `convert` | Math as LaTeX, keep headers and footers, engine, timings |
|
|
321
|
+
| `--mode auto\|ocr\|text`, `--dpi`, `--max-pages`, `--password` | PDFs | Text layer or OCR, render resolution, page cap, password |
|
|
322
|
+
| `--no-image-ocr` | PDFs | Skip OCR inside images on text-layer pages |
|
|
323
|
+
| `--model v1.1\|v3.1`, `--no-lm` | all commands | Model preset; no language models |
|
|
324
|
+
| `--model-dir <dir>`, `--execution-providers <list>` | all commands | Read models from a folder; ONNX providers (e.g. `cuda,cpu`) |
|
|
325
|
+
| `-o`/`--output <file>`, `--pretty`, `-q`/`--quiet`, `--verbose` | all commands | Output destination and format, logging |
|
|
320
326
|
|
|
321
327
|
Converted text goes to **stdout**; progress and logs go to **stderr**, so output pipes cleanly. Exit codes: `0` success, `1` runtime error, `2` usage error.
|
|
322
328
|
|
|
@@ -391,12 +397,11 @@ const pages = isPdf(bytes)
|
|
|
391
397
|
| ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
|
392
398
|
| `mode` | `"auto"` | `auto`: the text layer where it passes the checks, OCR elsewhere. `ocr`: always OCR. `text`: the text layer even when the checks fail |
|
|
393
399
|
| `dpi` | `200` | Render resolution for OCR |
|
|
394
|
-
| `pdfOrder` | `true` | Keep the PDF content order when it is coherent |
|
|
395
400
|
| `imageOcr` | `true` | On text-layer pages, OCR lines with no text-layer characters (text in images) |
|
|
396
401
|
| `maxPages` | all | Read at most this many pages |
|
|
397
402
|
| `password` | - | Password of an encrypted PDF |
|
|
398
403
|
|
|
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`.
|
|
404
|
+
The text layer is checked first: invisible text (an OCR layer), broken font maps, right-to-left letters stored in visual order, and runs with no ink under them send the page to OCR. So does a legacy-font layer (Kruti Dev or DevLys for Hindi, Bijoy for Bangla) that stores Latin codes while the page shows another script: the script model checks up to six of its lines against their images (upstream measures about 5 ms a page). A table set sideways, a page turned by its `/Rotate`, and vertical writing are read upright from the text layer; sideways labels inside a page become their own lines. A page that fails comes back with `source: "error"` and the reason in `note`; a file that cannot be opened throws. pdfium runs as WebAssembly (`@embedpdf/pdfium`); a browser fetches its wasm from jsDelivr unless you pass `pdfium: await loadPdfium(wasmBytesOrUrl)`. `isPdf(bytes)` is exported from every entry to route files without loading pdfium. On Node and Bun, set `PPU_INDRA_OCR_PDFIUM_WASM` to a local `pdfium.wasm` path to load it from there instead of `node_modules`.
|
|
400
405
|
|
|
401
406
|
## Math
|
|
402
407
|
|
|
@@ -408,7 +413,7 @@ A classifier finds lines that hold math, and an attention decoder reads them as
|
|
|
408
413
|
|
|
409
414
|
## Orientation and Deskew
|
|
410
415
|
|
|
411
|
-
There is nothing to compose: `convert()` turns the page upright with `orient.onnx` (90, 180 and 270 degree turns) and
|
|
416
|
+
There is nothing to compose: `convert()` measures the tilt on a page preview, turns the page upright with `orient.onnx` (90, 180 and 270 degree turns) and straightens tilts up to 45 degrees before detection, on both presets. `page.rotation` and `page.skew` report what was undone, and boxes come back in the upright page's pixels. A page set in vertical columns (Chinese, Japanese) is read turned, columns as lines, with `page.vertical` set and boxes on the page as it is. Call `service.orient()` and `service.straighten()` directly when you want those stages alone. For general image preprocessing (grayscale, thresholding, contours), see [ppu-ocv](https://github.com/PT-Perkasa-Pilar-Utama/ppu-ocv).
|
|
412
417
|
|
|
413
418
|
## Processing Engine
|
|
414
419
|
|
|
@@ -590,23 +595,48 @@ new IndraOcrService({ session: { executionProviders: ["nnapi"] } });
|
|
|
590
595
|
|
|
591
596
|
## Models and Language Support
|
|
592
597
|
|
|
598
|
+
### Model Presets
|
|
599
|
+
|
|
600
|
+
A preset is one pinned revision of [datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr) and the files it holds. Both run on the same pipeline, ported from `indra-ocr` 1.1.2.
|
|
601
|
+
|
|
602
|
+
| Preset | Hugging Face tag | Base download | What it reads |
|
|
603
|
+
| :--------------- | :--------------- | :------------ | :------------------------------------------------------------------------------------------------------------ |
|
|
604
|
+
| `v1.1` (default) | `v1.1.0` | 9 MB | Handwriting, 80+ languages (CJK, right-to-left and other script recognizers), language models, vertical pages |
|
|
605
|
+
| `v3.1` | `v3.1` | 18 MB | The first release (Indra OCR 1.0): Latin, Cyrillic, Greek, Devanagari, Bengali and Chinese |
|
|
606
|
+
|
|
607
|
+
```ts
|
|
608
|
+
import { IndraOcrService, MODEL_PRESETS } from "ppu-indra-ocr";
|
|
609
|
+
|
|
610
|
+
const service = new IndraOcrService({ model: "v3.1" }); // the first release
|
|
611
|
+
const noLm = new IndraOcrService({ lm: false }); // v1.1 without the language models
|
|
612
|
+
|
|
613
|
+
console.log(MODEL_PRESETS["v1.1"].revision); // the pinned commit
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
The language models (`lm`) re-read lines a recognizer is unsure of with a beam search, which mostly helps handwriting. They are on by default on Node and Bun and off on the web and React Native, where each is a 12 to 19 MB download. React Native has no `DecompressionStream`, which reading them needs.
|
|
617
|
+
|
|
593
618
|
### Indra OCR Models
|
|
594
619
|
|
|
595
|
-
Indra OCR is a small CPU pipeline with a 1M-parameter line recognizer. The
|
|
620
|
+
Indra OCR is a small CPU pipeline with a 1M-parameter line recognizer. The `v1.1` files, downloaded and cached on first use:
|
|
596
621
|
|
|
597
|
-
| Role
|
|
598
|
-
|
|
|
599
|
-
| `det`
|
|
600
|
-
| `rec`
|
|
601
|
-
| `
|
|
602
|
-
| `
|
|
603
|
-
| `
|
|
604
|
-
| `
|
|
605
|
-
| `
|
|
622
|
+
| Role | File | Size | Loads | What it does |
|
|
623
|
+
| :--------- | :--------------- | :------ | :------------------------ | :------------------------------------------------------------------------------ |
|
|
624
|
+
| `det` | `det.onnx` | 0.4 MB | at start | Text line detection |
|
|
625
|
+
| `rec` | `rec.onnx` | 5.0 MB | at start | Main recognizer: Latin, Cyrillic, Greek, Latin handwriting |
|
|
626
|
+
| `script` | `script.onnx` | 0.2 MB | at start | Script classifier: routes each line to its recognizer |
|
|
627
|
+
| `orient` | `orient.onnx` | 0.4 MB | at start | Page orientation and vertical writing |
|
|
628
|
+
| `order` | `order.onnx` | 3.0 MB | at start | Reading order, layout labels and blocks |
|
|
629
|
+
| `meta` | `meta.json` | 0.2 MB | at start | Vocabularies and input settings |
|
|
630
|
+
| `recCjk` | `rec_cjk.onnx` | 10.2 MB | first CJK line | Chinese, Japanese, Korean |
|
|
631
|
+
| `recRtl` | `rec_rtl.onnx` | 4.8 MB | first RTL line | Arabic, Persian, Urdu, Pashto, Hebrew |
|
|
632
|
+
| `recWorld` | `rec_world.onnx` | 5.6 MB | first line of its scripts | Indic scripts, Thai, Lao, Khmer, Myanmar, Sinhala, Georgian, Armenian, Ethiopic |
|
|
633
|
+
| `lm` | `lm.npz` | 15.7 MB | first unsure line | Language model of the main recognizer (with `lm`) |
|
|
634
|
+
| `lmCjk` | `lm_cjk.npz` | 19.0 MB | first unsure line | Language model of the CJK recognizer (with `lm`) |
|
|
635
|
+
| `lmWorld` | `lm_world.npz` | 11.6 MB | first unsure line | Language model of the other-script recognizer (with `lm`) |
|
|
606
636
|
|
|
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).
|
|
637
|
+
`v3.1` has `det`, `rec`, `recCjk` (9.3 MB, Chinese only), `script`, `orient`, `order` and `meta`. With `math: true`, five more files load in either preset: `mathcls.onnx`, `math_enc.onnx`, `math_dec_init.onnx`, `math_dec_step.onnx` and `math_meta.json` (about 20 MB).
|
|
608
638
|
|
|
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.
|
|
639
|
+
The weights are Datalab's, under their own license. Unmodified mirrors with the license and attribution: `models/` (v3.1) and `models/v1.1/` in this repository, and [snowfluke/ppu-indra-ocr-models](https://huggingface.co/snowfluke/ppu-indra-ocr-models) on Hugging Face.
|
|
610
640
|
|
|
611
641
|
### Cache Location (Node / Bun)
|
|
612
642
|
|
|
@@ -621,8 +651,8 @@ Models are cached under `~/.cache/ppu-indra-ocr`:
|
|
|
621
651
|
Each file lands in a subdirectory named after a digest of its source URL, so two models that share a file name never collide.
|
|
622
652
|
|
|
623
653
|
```ts
|
|
624
|
-
// Warm the cache (e.g. in CI or Docker builds)
|
|
625
|
-
await IndraOcrService.downloadModels({ math: false });
|
|
654
|
+
// Warm the cache (e.g. in CI or Docker builds): every file the preset can load
|
|
655
|
+
await IndraOcrService.downloadModels({ model: "v1.1", math: false, lm: true });
|
|
626
656
|
```
|
|
627
657
|
|
|
628
658
|
Clear it with `ppu-indra-ocr clear-cache`.
|
|
@@ -631,16 +661,17 @@ Clear it with `ppu-indra-ocr clear-cache`.
|
|
|
631
661
|
|
|
632
662
|
### Languages
|
|
633
663
|
|
|
634
|
-
There is no language option:
|
|
664
|
+
There is no language option: the script model routes each line to the recognizer of its script group, and a line it is unsure of is read by the main recognizer too, the more confident reading winning.
|
|
635
665
|
|
|
636
|
-
- **OCR (scans and images):** Latin (
|
|
666
|
+
- **OCR on v1.1 (scans and images):** Latin (Hausa, Fula, Akan, Azerbaijani, Uzbek, Vietnamese and Yoruba tone marks included), Cyrillic, Greek, Chinese, Japanese, Korean, Arabic, Persian, Urdu, Pashto, Hebrew, the Indic scripts, Thai, Lao, Khmer, Myanmar, Sinhala, Georgian, Armenian and Ethiopic. Right-to-left lines come out in logical order, and right-to-left pages read their right column first.
|
|
667
|
+
- **OCR on v3.1:** Latin, Cyrillic, Greek, Devanagari, Bengali and Chinese.
|
|
637
668
|
- **PDF text layer:** any script.
|
|
638
669
|
|
|
639
670
|
### Model Output Limitations
|
|
640
671
|
|
|
641
|
-
From the upstream model card: Indra OCR is built for speed on clean print. Complex tables (merged or spanning cells, no ruling lines),
|
|
672
|
+
From the upstream model card: Indra OCR is built for speed on clean print. Complex tables (merged or spanning cells, no ruling lines), cursive and faint pencil handwriting, degraded scans and very wide pages read poorly.
|
|
642
673
|
|
|
643
|
-
|
|
674
|
+
Upstream's picture regions (`Page.pictures`, `` in the markdown) need a detector with a picture channel. The v1.1 detector has none, so this port leaves them out.
|
|
644
675
|
|
|
645
676
|
## Configuration Reference
|
|
646
677
|
|
|
@@ -650,7 +681,9 @@ In this port, the right-to-left check for PDF text-layer lines uses script range
|
|
|
650
681
|
import type { IndraOptions } from "ppu-indra-ocr";
|
|
651
682
|
|
|
652
683
|
export type IndraOptions = {
|
|
684
|
+
model?: "v1.1" | "v3.1";
|
|
653
685
|
models?: ModelSources;
|
|
686
|
+
lm?: boolean;
|
|
654
687
|
math?: boolean;
|
|
655
688
|
furniture?: boolean;
|
|
656
689
|
adaptive?: boolean;
|
|
@@ -660,23 +693,27 @@ export type IndraOptions = {
|
|
|
660
693
|
};
|
|
661
694
|
```
|
|
662
695
|
|
|
663
|
-
| Property | Type | Default | Description
|
|
664
|
-
| :---------- | :---------------------------: | :--------------------------------------------: |
|
|
665
|
-
| `
|
|
666
|
-
| `
|
|
667
|
-
| `
|
|
668
|
-
| `
|
|
669
|
-
| `
|
|
670
|
-
| `
|
|
671
|
-
| `
|
|
696
|
+
| Property | Type | Default | Description |
|
|
697
|
+
| :---------- | :---------------------------: | :--------------------------------------------: | :------------------------------------------------ |
|
|
698
|
+
| `model` | `"v1.1" \| "v3.1"` | `"v1.1"` | Model preset, see [Model Presets](#model-presets) |
|
|
699
|
+
| `models` | `ModelSources` | Datalab's repository, pinned | Per-file sources, see below |
|
|
700
|
+
| `lm` | `boolean` | `true` on Node/Bun, `false` web and mobile | Re-read unsure lines with the language models |
|
|
701
|
+
| `math` | `boolean` | `false` | Read math lines as LaTeX (four more models) |
|
|
702
|
+
| `furniture` | `boolean` | `false` | Keep page headers and footers in the markdown |
|
|
703
|
+
| `adaptive` | `boolean` | `true` | Second detection pass on pages with small text |
|
|
704
|
+
| `engine` | `"opencv" \| "canvas-native"` | `"opencv"` on Node/Bun, else `"canvas-native"` | Image engine (see above) |
|
|
705
|
+
| `session` | `SessionOptions` | CPU, CPU memory arena off | ONNX Runtime session options |
|
|
706
|
+
| `verbose` | `boolean` | `false` | Log loading and stage steps to the console |
|
|
672
707
|
|
|
673
708
|
### `ModelSources`
|
|
674
709
|
|
|
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)`.
|
|
710
|
+
A partial map from file role to a source: a URL, a file path (Node/Bun only), or an `ArrayBuffer`. Roles left out use `defaultModelUrl(role, preset)`.
|
|
676
711
|
|
|
677
712
|
| Property | Type | Default | Description |
|
|
678
713
|
| :------------------------------------------------------------- | :---------------------: | :------------: | :--------------------------- |
|
|
679
|
-
| `det`, `rec`, `
|
|
714
|
+
| `det`, `rec`, `script`, `orient`, `order`, `meta` | `string \| ArrayBuffer` | pinned default | The base files |
|
|
715
|
+
| `recCjk`, `recRtl`, `recWorld` | `string \| ArrayBuffer` | pinned default | Script recognizers (on use) |
|
|
716
|
+
| `lm`, `lmCjk`, `lmWorld` | `string \| ArrayBuffer` | pinned default | Language models (with `lm`) |
|
|
680
717
|
| `mathCls`, `mathEnc`, `mathDecInit`, `mathDecStep`, `mathMeta` | `string \| ArrayBuffer` | pinned default | The math files (with `math`) |
|
|
681
718
|
|
|
682
719
|
### `BatchOptions`
|
|
@@ -692,7 +729,7 @@ Options of `convertBatch()` / `convertStream()`.
|
|
|
692
729
|
|
|
693
730
|
### `ConvertPdfOptions`
|
|
694
731
|
|
|
695
|
-
Options of `convertPdf()`: `mode`, `dpi`, `
|
|
732
|
+
Options of `convertPdf()`: `mode`, `dpi`, `imageOcr`, `maxPages` and `password` (see [PDF Input](#pdf-input)), plus `pdfium`, a module from `loadPdfium()` that is otherwise loaded once and reused. `PDFIUM_VERSION` names the `@embedpdf/pdfium` release the package is tested with.
|
|
696
733
|
|
|
697
734
|
### `SessionOptions`
|
|
698
735
|
|
|
@@ -726,7 +763,7 @@ It can fire once per model session.
|
|
|
726
763
|
|
|
727
764
|
Built-in models download from Datalab's Hugging Face repository. That host rate-limits by IP, which shows up as `HTTP 429 Too Many Requests` from shared addresses such as CI runners.
|
|
728
765
|
|
|
729
|
-
Set `PPU_INDRA_OCR_MODEL_MIRROR=1` and a download that exhausts its retries falls back to the GitHub copy in `models/`, which
|
|
766
|
+
Set `PPU_INDRA_OCR_MODEL_MIRROR=1` and a download that exhausts its retries falls back to the GitHub copy in `models/` (v3.1) or `models/v1.1/`, which serve byte-identical files:
|
|
730
767
|
|
|
731
768
|
```sh
|
|
732
769
|
PPU_INDRA_OCR_MODEL_MIRROR=1 bun run your-script.ts
|
|
@@ -738,39 +775,39 @@ It is off by default. GitHub LFS bandwidth is a monthly budget, so turn it on wh
|
|
|
738
775
|
|
|
739
776
|
Benches use a small zero-dependency harness (`bench/harness.ts`): in-process timing, round-robin scheduling across rounds so thermal/GC drift hits every task equally, reporting the median plus min/max/stddev. Run `bun task bench`.
|
|
740
777
|
|
|
741
|
-
Representative results on Apple M1 / Bun 1.4.2 (9 rounds) at the shipped defaults, `convert()` per page, opencv and canvas-native:
|
|
778
|
+
Representative results on Apple M1 / Bun 1.4.2 (9 rounds) at the shipped defaults (`v1.1` models), `convert()` per page, opencv and canvas-native:
|
|
742
779
|
|
|
743
780
|
```bash
|
|
744
781
|
task median +/-stddev min max
|
|
745
|
-
|
|
746
|
-
opencv two-column
|
|
747
|
-
opencv table
|
|
748
|
-
opencv receipt
|
|
749
|
-
canvas-native two-column
|
|
750
|
-
canvas-native table
|
|
751
|
-
canvas-native receipt
|
|
782
|
+
----------------------------------------------------------------------
|
|
783
|
+
opencv two-column 396.9 ms 90.4 ms 382.7 ms 597.1 ms
|
|
784
|
+
opencv table 309.9 ms 23.4 ms 295.3 ms 350.9 ms
|
|
785
|
+
opencv receipt 203.0 ms 36.9 ms 195.8 ms 282.8 ms
|
|
786
|
+
canvas-native two-column 768.9 ms 16.9 ms 740.7 ms 786.4 ms
|
|
787
|
+
canvas-native table 571.1 ms 28.0 ms 553.6 ms 624.6 ms
|
|
788
|
+
canvas-native receipt 309.2 ms 15.4 ms 302.8 ms 340.9 ms
|
|
752
789
|
```
|
|
753
790
|
|
|
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.
|
|
791
|
+
`two-column` and `table` are 1700 x 2200 test pages (US letter at 200 dpi); `receipt` is `assets/receipt.jpg`, a 720 x 1280 phone photo. Times include orientation, deskew, detection, recognition, reading order and markdown. The 1.1 pipeline costs 50 to 180 ms more per page than 0.1.x: its skew search covers 45 degrees in some 80 image rotations (about 115 ms on opencv), and the main recognizer reads a window three lines tall.
|
|
755
792
|
|
|
756
793
|
### Against ppu-paddle-ocr
|
|
757
794
|
|
|
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.
|
|
795
|
+
`bench/vs-paddle.ts` runs both libraries with their default options, each alone in its own process, and scores the output against transcripts. Apple M1 / Bun 1.4.2, ppu-paddle-ocr 6.6.1, Indra on the `v1.1` models. Three accuracy measures, because they disagree for good reasons: **char-F1** counts the characters read and ignores order and spacing; **token-F1** counts whole words, so a dropped space costs; **CER** ignores case and spaces but counts order.
|
|
759
796
|
|
|
760
797
|
**Document pages** (`bun bench/vs-paddle.ts`: the test pages plus the receipt, 5 rounds each):
|
|
761
798
|
|
|
762
799
|
| Page | ms Indra / Paddle | char-F1 | token-F1 | CER |
|
|
763
800
|
| :-------------- | :---------------- | :------------ | :------------ | :------------ |
|
|
764
|
-
| two-column.png |
|
|
765
|
-
| rotated-90.png |
|
|
766
|
-
| rotated-180.png |
|
|
767
|
-
| table.png |
|
|
768
|
-
| chinese.png |
|
|
769
|
-
| receipt.jpg |
|
|
801
|
+
| two-column.png | 415 / 582 | 1.000 / 1.000 | 1.000 / 0.972 | 0.001 / 0.683 |
|
|
802
|
+
| rotated-90.png | 493 / 418 | 1.000 / 0.000 | 1.000 / 0.000 | 0.001 / 1.000 |
|
|
803
|
+
| rotated-180.png | 386 / 506 | 1.000 / 0.579 | 1.000 / 0.016 | 0.001 / 0.784 |
|
|
804
|
+
| table.png | 309 / 323 | 1.000 / 1.000 | 1.000 / 1.000 | 0.033 / 0.007 |
|
|
805
|
+
| chinese.png | 318 / 249 | 1.000 / 1.000 | 1.000 / 1.000 | 0.000 / 0.000 |
|
|
806
|
+
| receipt.jpg | 214 / 148 | 0.985 / 0.997 | 0.835 / 0.954 | 0.015 / 0.003 |
|
|
770
807
|
|
|
771
808
|
Paddle reads across both columns on one line (CER 0.683 on two-column) and does not turn pages upright by default. On the real receipt photo, Paddle reads a few characters Indra misses.
|
|
772
809
|
|
|
773
|
-
**SROIE receipts** (`SROIE_DIR=... bun bench/vs-paddle.ts`: 50 receipts, every 12th of the ICDAR 2019 SROIE set):
|
|
810
|
+
**SROIE receipts** (`SROIE_DIR=... bun bench/vs-paddle.ts`: 50 receipts, every 12th of the ICDAR 2019 SROIE set; measured with 0.1.2 on the `v3.1` models, not yet re-run on `v1.1`):
|
|
774
811
|
|
|
775
812
|
| Library | median ms | p90 ms | peak RSS | char-F1 | token-F1 | CER |
|
|
776
813
|
| :------ | :-------- | :----- | :------- | :------ | :------- | :---- |
|
|
@@ -781,7 +818,7 @@ Both read the characters equally well. Indra keeps the spaces between words (tok
|
|
|
781
818
|
|
|
782
819
|
## How the Port Is Checked
|
|
783
820
|
|
|
784
|
-
`scripts/golden/` renders test pages and records every stage of the Python reference (`indra-ocr`
|
|
821
|
+
`scripts/golden/` renders test pages and records every stage of the Python reference (`indra-ocr` 1.1.2) on them, once on each preset's models: orientation, skew, detection, recognition, script routing, language-model beam search, reading order, the text layer and the final page. The pages cover every script group, a light-on-dark title, a right-to-left page, a vertical page, a page tilted 30 degrees, and PDFs with a sideways table, a `/Rotate` page, Hebrew and vertical text layers, and a Hindi page whose text layer stores Latin codes. The tests compare this package with those goldens. On the opencv engine the line text, blocks and markdown match exactly, and the line boxes agree to an IoU of 0.98 or better (0.9 on deskewed pages, where the reference's cv2 warps through a platform-specific code path). The canvas-native engine stays within a token-F1 of 0.98.
|
|
785
822
|
|
|
786
823
|
## Ecosystem
|
|
787
824
|
|
package/cli/commands.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdirSync,rmSync}from"node:fs";import{basename,extname,join}from"node:path";import{isPdf}from"../indra/document.js";import{
|
|
1
|
+
import{mkdirSync,rmSync}from"node:fs";import{basename,extname,join}from"node:path";import{isPdf}from"../indra/document.js";import{DEFAULT_PRESET,MATH_FILES,MODEL_FILES,MODEL_PRESETS,defaultModelUrl}from"../model-catalogue.js";import{CACHE_DIR}from"../processor/model-cache.js";import{IndraOcrService}from"../processor/indra-ocr.service.js";import{CliError,expandPatterns,isMissingLocalFile,loadImageInput,logStderr,writeOutput}from"./io.js";import{buildIndraOptions,buildPdfOptions,format,preset,str}from"./options.js";let EXTENSIONS={md:".md",text:".txt",json:".jsonl"};function errMessage(reason){return reason instanceof Error?reason.message:String(reason)}export function renderPages(pages,fmt,pretty){if(fmt==="text")return pages.map((p)=>p.text).join(`
|
|
2
2
|
`);if(fmt==="json")return pages.map((p,page)=>JSON.stringify({page,...p},null,pretty?2:undefined)).join(`
|
|
3
3
|
`);return pages.map((p)=>p.markdown??p.text).join(`
|
|
4
4
|
|
|
@@ -7,5 +7,5 @@ import{mkdirSync,rmSync}from"node:fs";import{basename,extname,join}from"node:pat
|
|
|
7
7
|
`)}}});if(!outDir&&outputs.length)writeOutput(outputs.join(fmt==="md"?`
|
|
8
8
|
|
|
9
9
|
`:`
|
|
10
|
-
`),str(values,"output"));if(failed)throw new CliError(`${failed} of ${files.length} file(s) failed`)}export async function runDetect(images,values){const[image]=images;if(!image||images.length!==1)throw new CliError("detect takes exactly one image",2);if(isMissingLocalFile(image))throw new CliError(`No such file: ${image}`);let boxes=await withService(values,async(service)=>service.detect(await loadImageInput(image)));let out=boxes.map(([x0,y0,x1,y1,score])=>({box:[x0,y0,x1,y1],score}));writeOutput(JSON.stringify(out,null,values.pretty?2:undefined),str(values,"output"))}export async function runDownloadModels(values){await
|
|
10
|
+
`),str(values,"output"));if(failed)throw new CliError(`${failed} of ${files.length} file(s) failed`)}export async function runDetect(images,values){const[image]=images;if(!image||images.length!==1)throw new CliError("detect takes exactly one image",2);if(isMissingLocalFile(image))throw new CliError(`No such file: ${image}`);let boxes=await withService(values,async(service)=>service.detect(await loadImageInput(image)));let out=boxes.map(([x0,y0,x1,y1,score])=>({box:[x0,y0,x1,y1],score}));writeOutput(JSON.stringify(out,null,values.pretty?2:undefined),str(values,"output"))}export async function runDownloadModels(values){let model=preset(values)??DEFAULT_PRESET;await IndraOcrService.downloadModels({model,math:Boolean(values.math),lm:!values["no-lm"],verbose:Boolean(values.verbose)});logStderr(`Models (${model}) cached in ${CACHE_DIR}`,Boolean(values.quiet))}export function runClearCache(values){rmSync(CACHE_DIR,{recursive:true,force:true});logStderr(`Removed ${CACHE_DIR}`,Boolean(values.quiet))}export function runModels(values){let names=Object.keys(MODEL_PRESETS);let presets=names.map((name)=>({name,default:name===DEFAULT_PRESET,revision:MODEL_PRESETS[name].revision,tag:MODEL_PRESETS[name].tag,models:MODEL_PRESETS[name].files.map((role)=>({role,file:MODEL_FILES[role],url:defaultModelUrl(role,name),math:MATH_FILES.includes(role)}))}));if(format(values)==="json"){writeOutput(JSON.stringify({default:DEFAULT_PRESET,cache:CACHE_DIR,presets},null,values.pretty?2:undefined));return}let lines=presets.flatMap((p)=>[`${p.name}${p.default?" (default)":""}: revision ${p.revision} (tag ${p.tag})`,...p.models.map((m)=>` ${m.file.padEnd(20)}${m.math?" (--math)":""}`)]);writeOutput(["Indra OCR model presets (datalab-to/indra-ocr)",`Cache: ${CACHE_DIR}`,...lines,"","Weights: Datalab, modified OpenRAIL-M license with use restrictions."].join(`
|
|
11
11
|
`),str(values,"output"))}
|
package/cli/help.d.ts
CHANGED
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
* Usage text for the `ppu-indra-ocr` CLI. Printed to stdout for `help` /
|
|
3
3
|
* `--help`, and to stderr (followed by a non-zero exit) on usage errors.
|
|
4
4
|
*/
|
|
5
|
-
export declare const USAGE = "ppu-indra-ocr - Indra OCR on the command line\n\nUsage:\n ppu-indra-ocr <command> [args] [flags]\n\nCommands:\n convert <file...> OCR images and PDFs (paths, globs, or http(s) URLs)\n detect <image> Detect text lines only (JSON boxes to stdout)\n download-models Pre-warm the model cache (~/.cache/ppu-indra-ocr)\n clear-cache Delete the cached model files\n models Print the model
|
|
5
|
+
export declare const USAGE = "ppu-indra-ocr - Indra OCR on the command line\n\nUsage:\n ppu-indra-ocr <command> [args] [flags]\n\nCommands:\n convert <file...> OCR images and PDFs (paths, globs, or http(s) URLs)\n detect <image> Detect text lines only (JSON boxes to stdout)\n download-models Pre-warm the model cache (~/.cache/ppu-indra-ocr)\n clear-cache Delete the cached model files\n models Print the model presets, their files, URLs and revisions\n help Show this help\n version Show the installed version\n\nConvert flags:\n --format <f> md | text | json (default md; json is one object per page)\n --out <dir> write one file per input (.md, .txt or .jsonl)\n --math write math as LaTeX (loads 4 more models)\n --keep-furniture keep page headers and footers in the markdown\n --engine <e> opencv | canvas-native (default opencv)\n --timings print per-page source and time to stderr\n\nPDF flags:\n --mode <m> auto | ocr | text (default auto: text layer where sound, OCR elsewhere)\n --dpi <n> render resolution for OCR (default 200)\n --max-pages <n> read at most n pages per PDF\n --password <p> password for encrypted PDFs\n --no-image-ocr on text-layer pages, do not OCR text inside images\n\nModels and session:\n --model <preset> v1.1 | v3.1 (default v1.1; v3.1 is the smaller first release)\n --no-lm do not re-read unsure lines with the language models\n --model-dir <dir> read the model files from a folder instead of downloading\n --execution-providers <list> comma-separated, e.g. cpu or cuda,cpu (default cpu)\n\nOutput:\n -o, --output <file> write everything to one file instead of stdout\n --pretty indent JSON output\n -q, --quiet suppress progress on stderr\n --verbose log each step to stderr\n\nExamples:\n ppu-indra-ocr convert paper.pdf\n ppu-indra-ocr convert \"scans/*.png\" --out results/\n ppu-indra-ocr convert scan.png --format json --pretty\n ppu-indra-ocr convert paper.pdf --mode ocr --math --timings\n ppu-indra-ocr detect receipt.jpg\n\nThe model weights are Datalab's (https://huggingface.co/datalab-to/indra-ocr),\nunder a modified OpenRAIL-M license with use restrictions.\n";
|
package/cli/help.js
CHANGED
|
@@ -8,7 +8,7 @@ Commands:
|
|
|
8
8
|
detect <image> Detect text lines only (JSON boxes to stdout)
|
|
9
9
|
download-models Pre-warm the model cache (~/.cache/ppu-indra-ocr)
|
|
10
10
|
clear-cache Delete the cached model files
|
|
11
|
-
models Print the model
|
|
11
|
+
models Print the model presets, their files, URLs and revisions
|
|
12
12
|
help Show this help
|
|
13
13
|
version Show the installed version
|
|
14
14
|
|
|
@@ -25,10 +25,11 @@ PDF flags:
|
|
|
25
25
|
--dpi <n> render resolution for OCR (default 200)
|
|
26
26
|
--max-pages <n> read at most n pages per PDF
|
|
27
27
|
--password <p> password for encrypted PDFs
|
|
28
|
-
--model-order order text-layer lines with the order model, not the PDF content order
|
|
29
28
|
--no-image-ocr on text-layer pages, do not OCR text inside images
|
|
30
29
|
|
|
31
30
|
Models and session:
|
|
31
|
+
--model <preset> v1.1 | v3.1 (default v1.1; v3.1 is the smaller first release)
|
|
32
|
+
--no-lm do not re-read unsure lines with the language models
|
|
32
33
|
--model-dir <dir> read the model files from a folder instead of downloading
|
|
33
34
|
--execution-providers <list> comma-separated, e.g. cpu or cuda,cpu (default cpu)
|
|
34
35
|
|
package/cli/options.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ParseArgsConfig } from "node:util";
|
|
2
2
|
import type { PdfPageOptions } from "../indra/document.js";
|
|
3
3
|
import type { IndraOptions } from "../interface.js";
|
|
4
|
+
import type { ModelPreset } from "../model-catalogue.js";
|
|
4
5
|
/** `parseArgs` option spec shared by every command. */
|
|
5
6
|
export declare const PARSE_OPTIONS: NonNullable<ParseArgsConfig["options"]>;
|
|
6
7
|
/** Shape of `parseArgs().values` for the spec above. */
|
|
@@ -10,6 +11,8 @@ export type OutputFormat = "md" | "text" | "json";
|
|
|
10
11
|
export declare function str(values: CliValues, key: string): string | undefined;
|
|
11
12
|
/** Output format; md by default. */
|
|
12
13
|
export declare function format(values: CliValues): OutputFormat;
|
|
14
|
+
/** The model preset flag. */
|
|
15
|
+
export declare function preset(values: CliValues): ModelPreset | undefined;
|
|
13
16
|
/** The service options from parsed flags. */
|
|
14
17
|
export declare function buildIndraOptions(values: CliValues): IndraOptions;
|
|
15
18
|
/** The PDF options from parsed flags. */
|
package/cli/options.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join}from"node:path";import{MODEL_FILES}from"../model-catalogue.js";import{usageError}from"./io.js";export let PARSE_OPTIONS={format:{type:"string"},out:{type:"string"},mode:{type:"string"},math:{type:"boolean"},"keep-furniture":{type:"boolean"},dpi:{type:"string"},"max-pages":{type:"string"},password:{type:"string"},"
|
|
1
|
+
import{existsSync}from"node:fs";import{join}from"node:path";import{MODEL_FILES,MODEL_PRESETS,isModelPreset}from"../model-catalogue.js";import{usageError}from"./io.js";export let PARSE_OPTIONS={format:{type:"string"},out:{type:"string"},mode:{type:"string"},math:{type:"boolean"},"keep-furniture":{type:"boolean"},dpi:{type:"string"},"max-pages":{type:"string"},password:{type:"string"},"no-image-ocr":{type:"boolean"},engine:{type:"string"},model:{type:"string"},"no-lm":{type:"boolean"},"model-dir":{type:"string"},"execution-providers":{type:"string"},timings:{type:"boolean"},output:{type:"string",short:"o"},pretty:{type:"boolean"},quiet:{type:"boolean",short:"q"},verbose:{type:"boolean"},help:{type:"boolean",short:"h"},version:{type:"boolean",short:"v"}};export function str(values,key){let raw=values[key];return typeof raw==="string"?raw:undefined}function num(values,key){let raw=str(values,key);if(raw===undefined)return;let n=Number(raw);if(!Number.isFinite(n)||n<0)usageError(`--${key} must be a non-negative number, got "${raw}"`);return n}function oneOf(values,key,allowed){let raw=str(values,key);if(raw===undefined)return;let hit=allowed.find((a)=>a===raw);if(!hit)usageError(`--${key} must be one of ${allowed.join(" | ")}`);return hit}let ENGINES=["opencv","canvas-native"];let MODES=["auto","ocr","text"];let FORMATS=["md","text","json"];export function format(values){return oneOf(values,"format",FORMATS)??"md"}function modelDir(values){let dir=str(values,"model-dir");if(dir===undefined)return;let entries=Object.entries(MODEL_FILES).flatMap(([role,file])=>existsSync(join(dir,file))?[[role,join(dir,file)]]:[]);return Object.fromEntries(entries)}export function preset(values){let raw=str(values,"model");if(raw===undefined)return;if(!isModelPreset(raw))usageError(`--model must be one of ${Object.keys(MODEL_PRESETS).join(" | ")}`);return raw}function engine(values){let chosen=oneOf(values,"engine",ENGINES);if(!process.env.PPU_BINARY_SLIM)return chosen;if(chosen==="opencv")usageError("this slim binary has no OpenCV: use --engine canvas-native or the full binary");return"canvas-native"}export function buildIndraOptions(values){let providers=str(values,"execution-providers");return{model:preset(values),models:modelDir(values),lm:values["no-lm"]?false:undefined,math:Boolean(values.math),furniture:Boolean(values["keep-furniture"]),engine:engine(values),session:providers?{executionProviders:providers.split(",").map((p)=>p.trim())}:undefined,verbose:Boolean(values.verbose)}}export function buildPdfOptions(values){return{mode:oneOf(values,"mode",MODES),dpi:num(values,"dpi"),imageOcr:!values["no-image-ocr"],maxPages:num(values,"max-pages"),password:str(values,"password")}}
|
|
@@ -5,6 +5,7 @@ import { IndraPipeline } from "../indra/pipeline.js";
|
|
|
5
5
|
import type { Box } from "../indra/rec-preproc.js";
|
|
6
6
|
import type { Orientation, Page, ReadingOrder, RecLine, Straightened } from "../indra/types.js";
|
|
7
7
|
import type { BatchOptions, IndraOptions, ProcessingEngine } from "../interface.js";
|
|
8
|
+
import type { ModelPreset } from "../model-catalogue.js";
|
|
8
9
|
import type { BatchItemResult } from "./batch.js";
|
|
9
10
|
import type { CoreCanvas, PlatformProvider } from "./platform.js";
|
|
10
11
|
/** An image to read: encoded bytes (PNG, JPEG, ...), a platform canvas, or 8-bit gray pixels. */
|
|
@@ -27,7 +28,15 @@ export declare abstract class BaseIndraOcrService<TCanvas = CoreCanvas> {
|
|
|
27
28
|
get engine(): ProcessingEngine | null;
|
|
28
29
|
/** The stage pipeline. Throws before initialize(). */
|
|
29
30
|
get pipeline(): IndraPipeline;
|
|
30
|
-
/**
|
|
31
|
+
/** The model preset in use. */
|
|
32
|
+
get preset(): ModelPreset;
|
|
33
|
+
/** Whether a model file comes from the options or the preset. */
|
|
34
|
+
private has;
|
|
35
|
+
/**
|
|
36
|
+
* Load the models (and OpenCV for the opencv engine). Safe to call twice.
|
|
37
|
+
* The script groups' recognizers and the language models load later, on
|
|
38
|
+
* the first line that needs them.
|
|
39
|
+
*/
|
|
31
40
|
initialize(): Promise<void>;
|
|
32
41
|
private load;
|
|
33
42
|
private imageOps;
|
|
@@ -45,19 +54,22 @@ export declare abstract class BaseIndraOcrService<TCanvas = CoreCanvas> {
|
|
|
45
54
|
/** Convert many images, yielding each result as it finishes (completion order). */
|
|
46
55
|
convertStream(images: Iterable<ImageInput<TCanvas>> | AsyncIterable<ImageInput<TCanvas>>, options?: BatchOptions): AsyncGenerator<BatchItemResult<Page>>;
|
|
47
56
|
private poolOptions;
|
|
48
|
-
/** Quarter turns (counter-clockwise) the content is turned by, from orient.onnx. */
|
|
57
|
+
/** Quarter turns (counter-clockwise) the content is turned by, or 4 for vertical writing, from orient.onnx. */
|
|
49
58
|
orient(image: ImageInput<TCanvas>): Promise<Orientation>;
|
|
50
|
-
/** The page turned upright by `turns` quarter turns and deskewed. */
|
|
59
|
+
/** The page turned upright by `turns` quarter turns (4: vertical writing, columns become lines) and deskewed. */
|
|
51
60
|
straighten(image: ImageInput<TCanvas>, turns?: number): Promise<Straightened>;
|
|
52
61
|
/** Line boxes (x0, y0, x1, y1, score) in image pixels. */
|
|
53
62
|
detect(image: ImageInput<TCanvas>): Promise<DetBox[]>;
|
|
54
63
|
/**
|
|
55
64
|
* Text, confidence and character positions of each box, one line per box.
|
|
56
|
-
* Boxes should hug the text: the recognizer
|
|
57
|
-
*
|
|
58
|
-
*
|
|
65
|
+
* Boxes should hug the text: the recognizer crops 0.3 x the box height on
|
|
66
|
+
* each side and 0.2 x above and below (v1.1's main recognizer also sees
|
|
67
|
+
* 1.6 x the height above and below as context). A box from another detector
|
|
68
|
+
* that carries its own padding shrinks the text and reads worse; trim it
|
|
69
|
+
* first. `vertical`: the image is a vertical page turned a quarter turn
|
|
70
|
+
* counter-clockwise, every line a column of CJK characters.
|
|
59
71
|
*/
|
|
60
|
-
recognize(image: ImageInput<TCanvas>, boxes: readonly Box[]): Promise<RecLine[]>;
|
|
72
|
+
recognize(image: ImageInput<TCanvas>, boxes: readonly Box[], vertical?: boolean): Promise<RecLine[]>;
|
|
61
73
|
/** Reading order of lines, with the layout heads' class and same-block logits. */
|
|
62
74
|
order(boxes: readonly Box[], texts: readonly string[], width: number, height: number): Promise<ReadingOrder>;
|
|
63
75
|
/** Math readings (text with inline LaTeX, mean token probability) of the boxes. Needs `math: true`. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export class BaseIndraOcrService{platform;options;indra=null;sessions=[];engineInUse=null;constructor(platform,options={}){this.platform=platform;this.options={...options}}log(message){if(this.options.verbose)console.log(`[IndraOcrService] ${message}`)}isInitialized(){return this.indra!==null}get engine(){return this.engineInUse}get pipeline(){if(!this.indra)throw new Error("IndraOcrService is not initialized: call initialize() first");return this.indra}async initialize(){if(this.indra)return;let roles=this.options.math?[...BASE_FILES,...MATH_FILES]:BASE_FILES;let bytes=new Map(await Promise.all(roles.map(async(role)=>[role,await this.load(role)])));let text=(role)=>new TextDecoder().decode(bytes.get(role));let session=async(role)=>{let s=await createSessionWithFallback(this.platform.ort,new Uint8Array(bytes.get(role)??
|
|
1
|
+
export class BaseIndraOcrService{platform;options;indra=null;sessions=[];engineInUse=null;constructor(platform,options={}){this.platform=platform;this.options={...options}}log(message){if(this.options.verbose)console.log(`[IndraOcrService] ${message}`)}isInitialized(){return this.indra!==null}get engine(){return this.engineInUse}get pipeline(){if(!this.indra)throw new Error("IndraOcrService is not initialized: call initialize() first");return this.indra}get preset(){return this.options.model??DEFAULT_PRESET}has(role){return this.options.models?.[role]!==undefined||MODEL_PRESETS[this.preset].files.includes(role)}async initialize(){if(this.indra)return;let roles=this.options.math?[...BASE_FILES,...MATH_FILES]:BASE_FILES;let bytes=new Map(await Promise.all(roles.map(async(role)=>[role,await this.load(role)])));let text=(role)=>new TextDecoder().decode(bytes.get(role));let session=async(role)=>{let s=await createSessionWithFallback(this.platform.ort,new Uint8Array(bytes.get(role)??await this.load(role)),this.options.session,(msg)=>this.log(msg),(next)=>this.options.session=next);this.sessions.push(s);return s};let ops=await this.imageOps();let meta=JSON.parse(text("meta"));let math=this.options.math?new MathReader(this.platform.ort.Tensor,{cls:await session("mathCls"),enc:await session("mathEnc"),init:await session("mathDecInit"),step:await session("mathDecStep")},JSON.parse(text("mathMeta")),ops):undefined;let lazy=(role,open)=>async()=>{this.log(`loading ${MODEL_FILES[role]} on first use`);return open()};let groups=Object.fromEntries(Object.entries(GROUP_FILES).flatMap(([name,role])=>this.has(role)?[[name,lazy(role,()=>session(role))]]:[]));let lm=this.options.lm??this.platform.defaultLm;let lms=Object.fromEntries(Object.entries(LM_FILES).flatMap(([name,role])=>lm&&this.has(role)?[[name,lazy(role,async()=>NgramLM.fromNpz(new Uint8Array(await this.load(role))))]]:[]));this.indra=new IndraPipeline(this.platform.ort.Tensor,{det:await session("det"),rec:await session("rec"),script:await session("script"),orient:await session("orient"),order:await session("order"),groups,lms},meta,ops,{furniture:this.options.furniture,adaptive:this.options.adaptive,math,lm});this.log(`ready: model ${this.preset}, ${roles.length} model files, engine ${this.engineInUse}`)}async load(role){let source=this.options.models?.[role];let url=source===undefined?defaultModelUrl(role,this.preset):"";try{return await this.platform.loadResource(source,url)}catch(err){let from=source instanceof ArrayBuffer?"the given bytes":source??url;let msg=err instanceof Error?err.message:String(err);throw new Error(`could not load ${MODEL_FILES[role]} from ${from}: ${msg}`,{cause:err})}}async imageOps(){let opencv=this.platform.opencv;let engine=this.options.engine??this.platform.defaultEngine;this.engineInUse=engine;if(engine==="canvas-native")return tsImageOps;if(!opencv)throw new Error('the "opencv" engine is not available on this platform');return opencvImageOps(await opencv())}async destroy(){await Promise.all(this.sessions.map((s)=>s.release()));this.sessions=[];this.indra=null}async toGray(image){if(isGray(image))return image;if(this.platform.isCanvas(image))return grayFromRgba(this.platform.pixels(image));if(image instanceof ArrayBuffer||image instanceof Uint8Array){let buf=image instanceof Uint8Array?image.buffer.slice(image.byteOffset,image.byteOffset+image.byteLength):image;let canvas=await this.platform.decodeImage(buf);return grayFromRgba(this.platform.pixels(canvas))}throw new TypeError("image must be encoded bytes, a canvas, or { data, width, height } gray pixels")}async convert(image){return this.pipeline.page(await this.toGray(image))}async convertBatch(images,options={}){let collected=[];await runPool(images,this.poolOptions(images,options),(image)=>this.convert(image),(r)=>{collected[r.index]=r});if(options.settle)return collected;return collected.flatMap((r)=>r.status==="fulfilled"?[r.value]:[])}async*convertStream(images,options={}){let queue=createAsyncQueue();let pump=(async()=>{try{await runPool(images,this.poolOptions(images,options),(image)=>this.convert(image),(r)=>queue.push(r));queue.close()}catch(error){queue.fail(error)}})();yield*queue.drain();await pump}poolOptions(images,options){return{concurrency:options.concurrency??1,settle:options.settle??false,signal:options.signal,onProgress:options.onProgress,total:Array.isArray(images)?images.length:undefined}}async orient(image){return this.pipeline.orient(await this.toGray(image))}async straighten(image,turns=0){return this.pipeline.straighten(await this.toGray(image),turns)}async detect(image){return this.pipeline.detect(await this.toGray(image))}async recognize(image,boxes,vertical=false){return this.pipeline.recognize(await this.toGray(image),boxes,64,vertical)}async order(boxes,texts,width,height){return this.pipeline.readingOrder(boxes,texts,width,height)}async readMath(image,boxes){let math=this.pipeline.mathReader;if(!math)throw new Error("readMath needs the service created with { math: true }");return math.read(await this.toGray(image),boxes)}}import{grayFromRgba}from"../indra/image.js";import{NgramLM}from"../indra/lm.js";import{MathReader}from"../indra/math.js";import{IndraPipeline}from"../indra/pipeline.js";import{tsImageOps}from"../indra/ts-image-ops.js";import{BASE_FILES,DEFAULT_PRESET,GROUP_FILES,LM_FILES,MATH_FILES,MODEL_FILES,MODEL_PRESETS,defaultModelUrl}from"../model-catalogue.js";import{createAsyncQueue,runPool}from"./batch.js";import{opencvImageOps}from"./opencv-image-ops.js";import{createSessionWithFallback}from"./session-factory.js";function isGray(image){return typeof image==="object"&&image!==null&&"data"in image&&image.data instanceof Uint8Array&&"width"in image&&"height"in image&&image.data.length===Number(image.width)*Number(image.height)}
|