ppu-indra-ocr 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-STATUS.md +25 -9
- package/README.md +76 -65
- package/cli/commands.js +2 -2
- package/cli/help.d.ts +1 -1
- package/cli/help.js +3 -3
- package/cli/options.d.ts +2 -0
- package/cli/options.js +1 -1
- package/core/indra-ocr.service.d.ts +2 -0
- package/core/indra-ocr.service.js +1 -1
- package/core/load-math.d.ts +11 -0
- package/core/load-math.js +1 -0
- package/core/opencv-image-ops.js +1 -1
- package/core/platform.d.ts +2 -0
- package/indra/agree.d.ts +70 -0
- package/indra/agree.js +1 -0
- package/indra/assemble.d.ts +14 -3
- package/indra/assemble.js +1 -1
- package/indra/ctc.d.ts +28 -0
- package/indra/ctc.js +1 -0
- package/indra/document.js +1 -1
- package/indra/image.d.ts +2 -0
- package/indra/layer-check.d.ts +29 -15
- package/indra/layer-check.js +1 -1
- package/indra/layer-gaps.d.ts +23 -0
- package/indra/layer-gaps.js +1 -0
- package/indra/layer-math.d.ts +13 -0
- package/indra/layer-math.js +1 -0
- package/indra/layout-post.d.ts +17 -2
- package/indra/layout-post.js +5 -5
- package/indra/line-thumbs.d.ts +34 -0
- package/indra/line-thumbs.js +1 -0
- package/indra/lines.d.ts +1 -1
- package/indra/lines.js +1 -1
- package/indra/math-decoder.d.ts +16 -0
- package/indra/math-decoder.js +1 -0
- package/indra/math-span-img.d.ts +61 -0
- package/indra/math-span-img.js +1 -0
- package/indra/math-splice.d.ts +46 -0
- package/indra/math-splice.js +1 -0
- package/indra/math-text.d.ts +98 -0
- package/indra/math-text.js +1 -0
- package/indra/math.d.ts +48 -9
- package/indra/math.js +1 -1
- package/indra/numeric.d.ts +8 -0
- package/indra/numeric.js +1 -1
- package/indra/order-post.js +1 -1
- package/indra/page-layout.d.ts +22 -0
- package/indra/page-layout.js +1 -0
- package/indra/page-tables.d.ts +32 -0
- package/indra/page-tables.js +1 -0
- package/indra/pipeline.d.ts +24 -10
- package/indra/pipeline.js +1 -1
- package/indra/py-text.d.ts +14 -0
- package/indra/py-text.js +1 -0
- package/indra/py-unicode.d.ts +28 -0
- package/indra/py-unicode.js +1 -0
- package/indra/rec-preproc.d.ts +8 -1
- package/indra/rec-preproc.js +1 -1
- package/indra/recognize.d.ts +19 -8
- package/indra/recognize.js +1 -1
- package/indra/recognizers.d.ts +40 -13
- package/indra/recognizers.js +1 -1
- package/indra/sequence-matcher.d.ts +34 -0
- package/indra/sequence-matcher.js +1 -0
- package/indra/symbol-digits.d.ts +29 -0
- package/indra/symbol-digits.js +1 -0
- package/indra/table-block-features.d.ts +38 -0
- package/indra/table-block-features.js +1 -0
- package/indra/table-decode.d.ts +50 -0
- package/indra/table-decode.js +4 -0
- package/indra/table-features.d.ts +34 -0
- package/indra/table-features.js +1 -0
- package/indra/table-heads.d.ts +15 -0
- package/indra/table-heads.js +2 -0
- package/indra/table-rel.d.ts +42 -0
- package/indra/table-rel.js +1 -0
- package/indra/table-split.d.ts +44 -0
- package/indra/table-split.js +1 -0
- package/indra/table-text.d.ts +15 -0
- package/indra/table-text.js +1 -0
- package/indra/table-verify.d.ts +80 -0
- package/indra/table-verify.js +1 -0
- package/indra/text-runs.d.ts +4 -0
- package/indra/text-runs.js +1 -1
- package/indra/textlayer.d.ts +18 -0
- package/indra/textlayer.js +1 -1
- package/indra/tiles.d.ts +20 -0
- package/indra/tiles.js +1 -0
- package/indra/ts-image-ops.js +1 -1
- package/indra/turn-check.d.ts +30 -0
- package/indra/turn-check.js +1 -0
- package/indra/types.d.ts +69 -5
- package/indra/upright.d.ts +1 -1
- package/indra/upright.js +1 -1
- package/indra/util.d.ts +8 -0
- package/indra/util.js +1 -1
- package/indra/vocab.d.ts +11 -0
- package/indra/vocab.js +1 -1
- package/interface.d.ts +9 -4
- package/mobile/platform.mobile.d.ts +1 -0
- package/mobile/platform.mobile.js +1 -1
- package/model-catalogue.d.ts +23 -7
- package/model-catalogue.js +1 -1
- package/package.json +2 -2
- package/pdf/pdfium.d.ts +2 -0
- package/pdf/pdfium.js +1 -1
- package/processor/indra-ocr.service.d.ts +4 -3
- 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-
|
|
5
|
+
> or when Datalab changes its license. Last updated: 2026-11-25.
|
|
6
6
|
>
|
|
7
7
|
> This page is not legal advice. Read the license yourself before you use the
|
|
8
8
|
> weights.
|
|
@@ -23,13 +23,20 @@ who runs it.
|
|
|
23
23
|
When you download or run the weights, you are the licensee. The library
|
|
24
24
|
downloads them for you on first use. The obligations are yours, not ours.
|
|
25
25
|
|
|
26
|
-
Attachment A of the license forbids any use of the weights in these cases
|
|
26
|
+
Attachment A of the license forbids any use of the weights in these cases.
|
|
27
|
+
The limits depend on the model preset, because Datalab lowered them for the
|
|
28
|
+
Indra OCR 1.2 weights:
|
|
29
|
+
|
|
30
|
+
| Preset | Revenue and funding limit |
|
|
31
|
+
| -------------- | ------------------------- |
|
|
32
|
+
| v1.2 (default) | USD 5,000,000 |
|
|
33
|
+
| v1.1 and v3.1 | USD 20,000,000 |
|
|
27
34
|
|
|
28
35
|
- **Revenue limit.** You, your employer, or the entity you are affiliated
|
|
29
|
-
with had more than
|
|
30
|
-
|
|
31
|
-
- **Funding limit.** That entity has raised more than
|
|
32
|
-
|
|
36
|
+
with had more than the limit in gross revenue in the prior year. Personal
|
|
37
|
+
use and research are excepted.
|
|
38
|
+
- **Funding limit.** That entity has raised more than the limit in total
|
|
39
|
+
equity or debt funding. Personal use and research are excepted.
|
|
33
40
|
- **Competitors.** That entity provides or otherwise makes available any
|
|
34
41
|
product or service that competes with any product or service of Datalab or
|
|
35
42
|
its affiliates. This clause has **no** exception for personal use or
|
|
@@ -77,13 +84,20 @@ Datalab has not approved or endorsed this project.
|
|
|
77
84
|
- **Default download.** The library downloads the weights from Datalab's own
|
|
78
85
|
repository,
|
|
79
86
|
[datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr),
|
|
80
|
-
pinned to one commit per model preset: `
|
|
81
|
-
(tag v1.
|
|
87
|
+
pinned to one commit per model preset: `a04fa100e778192aa54d040a983983c6d3ee4ce5`
|
|
88
|
+
(tag v1.2.0, Indra OCR 1.2, the default),
|
|
89
|
+
`a1283c4b42a273c09480ad50e71461daff50fcc7` (tag v1.1.0, Indra OCR 1.1) and
|
|
82
90
|
`d7c839c892bfe4b8993373db64c62f154d05d70b` (tag v3.1, Indra OCR 1.0).
|
|
83
91
|
- **Same license in 1.1.** The license file of tag v1.1.0 is byte for byte
|
|
84
92
|
the license file of tag v3.1 (sha256
|
|
85
93
|
`50c88a018a7ee322e89f6b09401b237beb0cd331685879405b3db48993950a5f`). Indra OCR 1.1
|
|
86
94
|
changed the weights, not the terms.
|
|
95
|
+
- **Lower limits in 1.2.** The license file of tag v1.2.0 (sha256
|
|
96
|
+
`b6be9042dce439368b606444256cd97624a97c67dfae33957b87c3a0b461ae03`) differs
|
|
97
|
+
from the earlier one only in Attachment A 2(a) and 2(b): the revenue and
|
|
98
|
+
funding limits are USD 5,000,000 instead of USD 20,000,000. Clause 2(c),
|
|
99
|
+
the competitor ban, is unchanged. Each mirror folder holds the license of
|
|
100
|
+
its own revision.
|
|
87
101
|
- **No weights in the package.** The npm and JSR packages contain the code
|
|
88
102
|
only.
|
|
89
103
|
- **Mirrors.** Unmodified copies of the pinned weights exist, each with
|
|
@@ -91,7 +105,9 @@ Datalab has not approved or endorsed this project.
|
|
|
91
105
|
[models/v1.1/](models/v1.1/) in this repository, and the Hugging Face
|
|
92
106
|
repository
|
|
93
107
|
[snowfluke/ppu-indra-ocr-models](https://huggingface.co/snowfluke/ppu-indra-ocr-models)
|
|
94
|
-
(v3.1 at its root, v1.1 in `v1.1
|
|
108
|
+
(v3.1 at its root, v1.1 in `v1.1/`, v1.2 in `v1.2/`, the last uploaded on
|
|
109
|
+
2026-11-25 under the v1.2 license). This repository holds no v1.2 copy:
|
|
110
|
+
its git LFS budget is exhausted.
|
|
95
111
|
The library uses the GitHub copy only when you set
|
|
96
112
|
`PPU_INDRA_OCR_MODEL_MIRROR=1` and Hugging Face fails. It does not use the
|
|
97
113
|
Hugging Face copy.
|
package/README.md
CHANGED
|
@@ -14,8 +14,9 @@ Need it as an HTTP service? Dockerized? Spin up the REST API here: [apps/serve](
|
|
|
14
14
|
> modified OpenRAIL-M license, and you accept it when the library downloads
|
|
15
15
|
> them for you. You may not use the weights at all if:
|
|
16
16
|
>
|
|
17
|
-
> - your organization had more than USD
|
|
18
|
-
> raised more than USD
|
|
17
|
+
> - your organization had more than USD 5M in revenue last year, or has
|
|
18
|
+
> raised more than USD 5M, unless your use is personal or research (USD
|
|
19
|
+
> 20M for the older v1.1 and v3.1 weights); or
|
|
19
20
|
> - your organization offers any product or service that competes with
|
|
20
21
|
> Datalab. This clause has no exception for personal use or research.
|
|
21
22
|
>
|
|
@@ -89,7 +90,7 @@ await service.destroy();
|
|
|
89
90
|
|
|
90
91
|
- **The whole page, not just the text.** Orientation (vertical writing too), deskew up to 45 degrees, line detection, recognizers for Latin, CJK, right-to-left and other scripts, reading order, layout labels, and markdown with headings, lists and tables, in one `convert()` call.
|
|
91
92
|
- **PDFs too.** Uses a PDF's text layer where it can be trusted and OCR where it cannot, page by page.
|
|
92
|
-
- **Small models.** About 9 MB of ONNX models load at start; the other script recognizers and the language models load when a page needs them. Pinned to one upstream revision per [model preset](#model-presets): `v1.
|
|
93
|
+
- **Small models.** About 9 MB of ONNX models load at start (35 MB with math, on by default in Node and Bun); the other script recognizers, the handwriting recognizer, the table models and the language models load when a page needs them. Pinned to one upstream revision per [model preset](#model-presets): `v1.2` (Indra OCR 1.2, the default), `v1.1` or `v3.1` (the first release).
|
|
93
94
|
- **Matches the reference.** On the `opencv` engine, line text, layout blocks and markdown match the Python `indra-ocr` exactly on every test page. See [How the Port Is Checked](#how-the-port-is-checked).
|
|
94
95
|
- **Runs everywhere**, Node.js, Bun, Deno, web browsers, web workers, browser extensions, and React Native (iOS/Android), on the same runtime adapters as [ppu-paddle-ocr](https://github.com/PT-Perkasa-Pilar-Utama/ppu-paddle-ocr).
|
|
95
96
|
- **Composable.** Every stage is a method, so you can run one stage, swap a stage, or chain your own pipeline.
|
|
@@ -118,7 +119,7 @@ npm install ppu-indra-ocr onnxruntime-node onnxruntime-web
|
|
|
118
119
|
|
|
119
120
|
Omit `onnxruntime-node` or `onnxruntime-web` depending on your target environment (Node/Bun vs browser). Add `@embedpdf/pdfium` for PDF input.
|
|
120
121
|
|
|
121
|
-
The first `initialize()` downloads the base models (about 9 MB,
|
|
122
|
+
The first `initialize()` downloads the base models (about 9 MB, 35 MB with math, which is on by default in Node and Bun) 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), the handwriting recognizer (5 MB), the table models (8 MB) 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.
|
|
122
123
|
|
|
123
124
|
**When the models download, you accept Datalab's license for the weights.**
|
|
124
125
|
Check [LICENSE-STATUS.md](LICENSE-STATUS.md) first.
|
|
@@ -244,9 +245,9 @@ const texts = lines.map((l) => l.text);
|
|
|
244
245
|
const { order, cls, same } = await service.order(boxes, texts, upright.width, upright.height);
|
|
245
246
|
```
|
|
246
247
|
|
|
247
|
-
`recognize` takes boxes from any detector, one line per box. Boxes should hug the text: the recognizer crops 0.3 x the box height on each side and 0.2 x above and below (on v1.1 the main recognizer also sees 1.6 x the height above and below as context). Trim boxes that carry their own padding first; PaddleOCR's boxes, for example, are padded to 1.8 x the text height. For a vertical page, pass the page turned by `straighten(image, 4)` and `recognize(image, boxes, true)`.
|
|
248
|
+
`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 and v1.2 the main recognizer also sees 1.6 x the height above and below as context). Trim boxes that carry their own padding first; PaddleOCR's boxes, for example, are padded to 1.8 x the text height. For a vertical page, pass the page turned by `straighten(image, 4)` and `recognize(image, boxes, true)`.
|
|
248
249
|
|
|
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
|
|
250
|
+
`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 with math on (the default in Node and Bun).
|
|
250
251
|
|
|
251
252
|
### Custom Models
|
|
252
253
|
|
|
@@ -268,7 +269,7 @@ const local = new IndraOcrService({
|
|
|
268
269
|
});
|
|
269
270
|
```
|
|
270
271
|
|
|
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`, `
|
|
272
|
+
Roles: `det`, `rec`, `script`, `orient`, `order`, `meta`; the script recognizers `recCjk`, `recRtl`, `recWorld`; the handwriting models `hw`, `recHw` and the table models `tsrRel`, `tsrSplit`, `tsrRefine`, `tableVerify` (v1.2); the language models `lm`, `lmCjk`, `lmWorld`; and with math `mathCls`, `mathEnc`, `mathDecInit`, `mathDecStep` (v1.1, v3.1) or `mathDecStepKv` (v1.2), `mathMeta`, and on v1.2 `mathAccept`, `mathGate`, `mathSpanImg`, `mathSpanImgMeta`. `MODEL_FILES` maps each role to its file name, `MODEL_PRESETS` holds each preset's pinned commit and file list, and `defaultModelUrl(role, preset)` gives the default URL. A role the preset does not have (v3.1 has no `recRtl`) and that you do not pass stays off.
|
|
272
273
|
|
|
273
274
|
### Detection Only
|
|
274
275
|
|
|
@@ -295,8 +296,8 @@ bunx ppu-indra-ocr convert "scans/*.png" --out results/
|
|
|
295
296
|
# structured JSON, one object per page
|
|
296
297
|
bunx ppu-indra-ocr convert scan.png --format json --pretty
|
|
297
298
|
|
|
298
|
-
# force OCR on a PDF,
|
|
299
|
-
bunx ppu-indra-ocr convert paper.pdf --mode ocr --math --timings
|
|
299
|
+
# force OCR on a PDF, skip math, print per-page timings
|
|
300
|
+
bunx ppu-indra-ocr convert paper.pdf --mode ocr --no-math --timings
|
|
300
301
|
|
|
301
302
|
# detection only: line boxes as JSON
|
|
302
303
|
bunx ppu-indra-ocr detect receipt.jpg
|
|
@@ -317,10 +318,10 @@ bunx ppu-indra-ocr models
|
|
|
317
318
|
| Flags | Applies to | Purpose |
|
|
318
319
|
| :-------------------------------------------------------------- | :----------- | :---------------------------------------------------------- |
|
|
319
320
|
| `--format md\|text\|json`, `--out <dir>` | `convert` | Output format; one file per input (`.md`, `.txt`, `.jsonl`) |
|
|
320
|
-
| `--math`, `--keep-furniture`, `--engine`, `--timings`
|
|
321
|
+
| `--no-math`, `--keep-furniture`, `--engine`, `--timings` | `convert` | No math, keep headers and footers, engine, timings |
|
|
321
322
|
| `--mode auto\|ocr\|text`, `--dpi`, `--max-pages`, `--password` | PDFs | Text layer or OCR, render resolution, page cap, password |
|
|
322
323
|
| `--no-image-ocr` | PDFs | Skip OCR inside images on text-layer pages |
|
|
323
|
-
| `--model v1.1\|v3.1`, `--no-lm`
|
|
324
|
+
| `--model v1.2\|v1.1\|v3.1`, `--no-lm` | all commands | Model preset; no language models |
|
|
324
325
|
| `--model-dir <dir>`, `--execution-providers <list>` | all commands | Read models from a folder; ONNX providers (e.g. `cuda,cpu`) |
|
|
325
326
|
| `-o`/`--output <file>`, `--pretty`, `-q`/`--quiet`, `--verbose` | all commands | Output destination and format, logging |
|
|
326
327
|
|
|
@@ -406,14 +407,15 @@ The text layer is checked first: invisible text (an OCR layer), broken font maps
|
|
|
406
407
|
## Math
|
|
407
408
|
|
|
408
409
|
```ts
|
|
409
|
-
const service = new IndraOcrService(
|
|
410
|
+
const service = new IndraOcrService(); // math is on by default in Node and Bun
|
|
411
|
+
const web = new IndraOcrService({ math: true }); // off by default on the web and React Native
|
|
410
412
|
```
|
|
411
413
|
|
|
412
|
-
A classifier finds lines that hold math, and an attention decoder reads them as text with inline LaTeX (`we have $x _ { i } \leq 1$`).
|
|
414
|
+
A classifier finds lines that hold math, and an attention decoder reads them as text with inline LaTeX (`we have $x _ { i } \leq 1$`). On v1.2, a learned gate skips flagged lines whose reading would not be used, a learned head decides which readings replace a line (and looks again at lines the layout puts in a table), the replaced line keeps the recognizer's accents and letters of other scripts in its prose, and an image tagger finds inline formulas in lines the decoder does not read whole (a Cyrillic or Korean line with a formula). On v1.1 and v3.1, a reading replaces a line when it holds math and its mean token probability is 0.9 or more. Math loads the math models (about 25 MB on v1.2) and is slower on pages that have it; `math: false` (or `--no-math`) skips them.
|
|
413
415
|
|
|
414
416
|
## Orientation and Deskew
|
|
415
417
|
|
|
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
|
|
418
|
+
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 every preset. A half turn, and a page that `orient.onnx` is unsure of but sees as likely sideways, are settled by reading up to eight of the longest lines each way: the turn the recognizers read surest wins. `page.rotation` and `page.skew` report what was undone, and boxes come back in the upright page's pixels. A page set in vertical columns (Chinese, Japanese) is read turned, columns as lines, with `page.vertical` set and boxes on the page as it is. Call `service.orient()` and `service.straighten()` directly when you want those stages alone. For general image preprocessing (grayscale, thresholding, contours), see [ppu-ocv](https://github.com/PT-Perkasa-Pilar-Utama/ppu-ocv).
|
|
417
419
|
|
|
418
420
|
## Processing Engine
|
|
419
421
|
|
|
@@ -597,46 +599,55 @@ new IndraOcrService({ session: { executionProviders: ["nnapi"] } });
|
|
|
597
599
|
|
|
598
600
|
### Model Presets
|
|
599
601
|
|
|
600
|
-
A preset is one pinned revision of [datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr) and the files it holds.
|
|
602
|
+
A preset is one pinned revision of [datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr) and the files it holds. All three run on the same pipeline, ported from `indra-ocr` 1.2.0; a stage whose model a preset lacks stays off.
|
|
601
603
|
|
|
602
|
-
| Preset | Hugging Face tag | Base download | What it reads
|
|
603
|
-
| :--------------- | :--------------- | :------------ |
|
|
604
|
-
| `v1.
|
|
605
|
-
| `
|
|
604
|
+
| Preset | Hugging Face tag | Base download | What it reads |
|
|
605
|
+
| :--------------- | :--------------- | :------------ | :----------------------------------------------------------------------------------------------------------------------------------- |
|
|
606
|
+
| `v1.2` (default) | `v1.2.0` | 9 MB | v1.1 plus retrained recognizers, a handwriting recognizer, table structure models, line thumbnails for the reading order, math gates |
|
|
607
|
+
| `v1.1` | `v1.1.0` | 9 MB | Handwriting, 80+ languages (CJK, right-to-left and other script recognizers), language models, vertical pages |
|
|
608
|
+
| `v3.1` | `v3.1` | 18 MB | The first release (Indra OCR 1.0): Latin, Cyrillic, Greek, Devanagari, Bengali and Chinese |
|
|
609
|
+
|
|
610
|
+
The v1.2 weights are under a license with lower limits than the older ones: USD 5,000,000 of revenue or funding instead of USD 20,000,000. See [LICENSE-STATUS.md](LICENSE-STATUS.md).
|
|
606
611
|
|
|
607
612
|
```ts
|
|
608
613
|
import { IndraOcrService, MODEL_PRESETS } from "ppu-indra-ocr";
|
|
609
614
|
|
|
610
615
|
const service = new IndraOcrService({ model: "v3.1" }); // the first release
|
|
611
|
-
const noLm = new IndraOcrService({ lm: false }); // v1.
|
|
616
|
+
const noLm = new IndraOcrService({ lm: false }); // v1.2 without the language models
|
|
612
617
|
|
|
613
|
-
console.log(MODEL_PRESETS["v1.
|
|
618
|
+
console.log(MODEL_PRESETS["v1.2"].revision); // the pinned commit
|
|
614
619
|
```
|
|
615
620
|
|
|
616
621
|
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
622
|
|
|
618
623
|
### Indra OCR Models
|
|
619
624
|
|
|
620
|
-
Indra OCR is a small CPU pipeline with a 1M-parameter line recognizer. The `v1.
|
|
621
|
-
|
|
622
|
-
| Role
|
|
623
|
-
|
|
|
624
|
-
| `det`
|
|
625
|
-
| `rec`
|
|
626
|
-
| `script`
|
|
627
|
-
| `orient`
|
|
628
|
-
| `order`
|
|
629
|
-
| `meta`
|
|
630
|
-
| `recCjk`
|
|
631
|
-
| `recRtl`
|
|
632
|
-
| `recWorld`
|
|
633
|
-
| `
|
|
634
|
-
| `
|
|
635
|
-
| `
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
625
|
+
Indra OCR is a small CPU pipeline with a 1M-parameter line recognizer. The `v1.2` files, downloaded and cached on first use:
|
|
626
|
+
|
|
627
|
+
| Role | File | Size | Loads | What it does |
|
|
628
|
+
| :------------ | :------------------ | :------ | :------------------------ | :------------------------------------------------------------------------------ |
|
|
629
|
+
| `det` | `det.onnx` | 0.4 MB | at start | Text line detection |
|
|
630
|
+
| `rec` | `rec.onnx` | 5.0 MB | at start | Main recognizer: Latin, Cyrillic, Greek, Latin handwriting |
|
|
631
|
+
| `script` | `script.onnx` | 0.2 MB | at start | Script classifier: routes each line to its recognizer |
|
|
632
|
+
| `orient` | `orient.onnx` | 0.4 MB | at start | Page orientation and vertical writing |
|
|
633
|
+
| `order` | `order.onnx` | 3.0 MB | at start | Reading order, layout labels and blocks (reads line thumbnails) |
|
|
634
|
+
| `meta` | `meta.json` | 0.2 MB | at start | Vocabularies and input settings |
|
|
635
|
+
| `recCjk` | `rec_cjk.onnx` | 10.2 MB | first CJK line | Chinese, Japanese, Korean |
|
|
636
|
+
| `recRtl` | `rec_rtl.onnx` | 4.8 MB | first RTL line | Arabic, Persian, Urdu, Pashto, Hebrew |
|
|
637
|
+
| `recWorld` | `rec_world.onnx` | 5.6 MB | first line of its scripts | Indic scripts, Thai, Lao, Khmer, Myanmar, Sinhala, Georgian, Armenian, Ethiopic |
|
|
638
|
+
| `hw` | `hw.onnx` | 0.2 MB | at start | Printed or handwritten, per main-script line |
|
|
639
|
+
| `recHw` | `rec_hw.onnx` | 5.1 MB | first handwritten line | Handwriting recognizer for the main script |
|
|
640
|
+
| `tsrRel` | `tsr_rel.onnx` | 5.6 MB | first table | Which table words share a cell, a row or a column |
|
|
641
|
+
| `tsrSplit` | `tsr_split.onnx` | 1.5 MB | first table | Row, column and header separator maps of a table |
|
|
642
|
+
| `tsrRefine` | `tsr_refine.onnx` | 0.5 MB | first table | Header words and words outside the table |
|
|
643
|
+
| `tableVerify` | `table_verify.json` | 6 KB | at start | Relabels false tables (charts, prose) |
|
|
644
|
+
| `lm` | `lm.npz` | 15.4 MB | first unsure line | Language model of the main recognizer (with `lm`) |
|
|
645
|
+
| `lmCjk` | `lm_cjk.npz` | 19.0 MB | first unsure line | Language model of the CJK recognizer (with `lm`) |
|
|
646
|
+
| `lmWorld` | `lm_world.npz` | 11.6 MB | first unsure line | Language model of the other-script recognizer (with `lm`) |
|
|
647
|
+
|
|
648
|
+
`v1.1` has the same roles without `hw`, `recHw` and the table models. `v3.1` has `det`, `rec`, `recCjk` (9.3 MB, Chinese only), `script`, `orient`, `order` and `meta`. With math, v1.2 loads `mathcls.onnx`, `math_enc.onnx`, `math_dec_init.onnx`, `math_dec_step_kv.onnx`, `math_meta.json`, `math_accept.json`, `math_gate.json`, `math_span_img.onnx` and `math_span_img.json` (about 25 MB); v1.1 and v3.1 load the first five files with `math_dec_step.onnx` in place of `math_dec_step_kv.onnx` (about 20 MB).
|
|
649
|
+
|
|
650
|
+
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 (all three presets; v1.2 only there).
|
|
640
651
|
|
|
641
652
|
### Cache Location (Node / Bun)
|
|
642
653
|
|
|
@@ -652,7 +663,7 @@ Each file lands in a subdirectory named after a digest of its source URL, so two
|
|
|
652
663
|
|
|
653
664
|
```ts
|
|
654
665
|
// Warm the cache (e.g. in CI or Docker builds): every file the preset can load
|
|
655
|
-
await IndraOcrService.downloadModels({ model: "v1.
|
|
666
|
+
await IndraOcrService.downloadModels({ model: "v1.2", math: true, lm: true });
|
|
656
667
|
```
|
|
657
668
|
|
|
658
669
|
Clear it with `ppu-indra-ocr clear-cache`.
|
|
@@ -663,7 +674,7 @@ Clear it with `ppu-indra-ocr clear-cache`.
|
|
|
663
674
|
|
|
664
675
|
There is no language option: the script model routes each line to the recognizer of its script group, and a line it is unsure of is read by the main recognizer too, the more confident reading winning.
|
|
665
676
|
|
|
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.
|
|
677
|
+
- **OCR on v1.2 and 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
678
|
- **OCR on v3.1:** Latin, Cyrillic, Greek, Devanagari, Bengali and Chinese.
|
|
668
679
|
- **PDF text layer:** any script.
|
|
669
680
|
|
|
@@ -671,7 +682,7 @@ There is no language option: the script model routes each line to the recognizer
|
|
|
671
682
|
|
|
672
683
|
From the upstream model card: Indra OCR is built for speed on clean print. Complex tables (merged or spanning cells, no ruling lines), cursive and faint pencil handwriting, degraded scans and very wide pages read poorly.
|
|
673
684
|
|
|
674
|
-
Upstream's picture regions (`Page.pictures`, `` in the markdown) need a detector with a picture channel. The v1.1
|
|
685
|
+
Upstream's picture regions (`Page.pictures`, `` in the markdown) need a detector with a picture channel. The v1.1 and v1.2 detectors have none, so this port leaves them out.
|
|
675
686
|
|
|
676
687
|
## Configuration Reference
|
|
677
688
|
|
|
@@ -681,7 +692,7 @@ Upstream's picture regions (`Page.pictures`, `` in the markdown) n
|
|
|
681
692
|
import type { IndraOptions } from "ppu-indra-ocr";
|
|
682
693
|
|
|
683
694
|
export type IndraOptions = {
|
|
684
|
-
model?: "v1.1" | "v3.1";
|
|
695
|
+
model?: "v1.2" | "v1.1" | "v3.1";
|
|
685
696
|
models?: ModelSources;
|
|
686
697
|
lm?: boolean;
|
|
687
698
|
math?: boolean;
|
|
@@ -693,28 +704,28 @@ export type IndraOptions = {
|
|
|
693
704
|
};
|
|
694
705
|
```
|
|
695
706
|
|
|
696
|
-
| Property | Type |
|
|
697
|
-
| :---------- | :---------------------------: |
|
|
698
|
-
| `model` |
|
|
699
|
-
| `models` | `ModelSources` |
|
|
700
|
-
| `lm` | `boolean` |
|
|
701
|
-
| `math` | `boolean` |
|
|
702
|
-
| `furniture` | `boolean` |
|
|
703
|
-
| `adaptive` | `boolean` |
|
|
704
|
-
| `engine` | `"opencv" \| "canvas-native"` |
|
|
705
|
-
| `session` | `SessionOptions` |
|
|
706
|
-
| `verbose` | `boolean` |
|
|
707
|
+
| Property | Type | Default | Description |
|
|
708
|
+
| :---------- | :---------------------------: | :-----------------------------------------------: | :------------------------------------------------ |
|
|
709
|
+
| `model` | `"v1.2" \| "v1.1" \| "v3.1"` | `"v1.2"` | Model preset, see [Model Presets](#model-presets) |
|
|
710
|
+
| `models` | `ModelSources` | Datalab's repository, pinned | Per-file sources, see below |
|
|
711
|
+
| `lm` | `boolean` | `true` on Node/Bun, `false` web and mobile | Re-read unsure lines with the language models |
|
|
712
|
+
| `math` | `boolean` | `true` on Node and Bun, `false` on web and mobile | Read math lines as LaTeX (the math models) |
|
|
713
|
+
| `furniture` | `boolean` | `false` | Keep page headers and footers in the markdown |
|
|
714
|
+
| `adaptive` | `boolean` | `true` | Second detection pass on pages with small text |
|
|
715
|
+
| `engine` | `"opencv" \| "canvas-native"` | `"opencv"` on Node/Bun, else `"canvas-native"` | Image engine (see above) |
|
|
716
|
+
| `session` | `SessionOptions` | CPU, CPU memory arena off | ONNX Runtime session options |
|
|
717
|
+
| `verbose` | `boolean` | `false` | Log loading and stage steps to the console |
|
|
707
718
|
|
|
708
719
|
### `ModelSources`
|
|
709
720
|
|
|
710
721
|
A partial map from file role to a source: a URL, a file path (Node/Bun only), or an `ArrayBuffer`. Roles left out use `defaultModelUrl(role, preset)`.
|
|
711
722
|
|
|
712
|
-
| Property
|
|
713
|
-
|
|
|
714
|
-
| `det`, `rec`, `script`, `orient`, `order`, `meta`
|
|
715
|
-
| `recCjk`, `recRtl`, `recWorld`
|
|
716
|
-
| `lm`, `lmCjk`, `lmWorld`
|
|
717
|
-
| `mathCls`, `mathEnc`, `mathDecInit`, `mathDecStep`, `mathMeta` | `string \| ArrayBuffer` | pinned default | The math files (with `math`) |
|
|
723
|
+
| Property | Type | Default | Description |
|
|
724
|
+
| :-------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------: | :------------: | :--------------------------- |
|
|
725
|
+
| `det`, `rec`, `script`, `orient`, `order`, `meta` | `string \| ArrayBuffer` | pinned default | The base files |
|
|
726
|
+
| `recCjk`, `recRtl`, `recWorld` | `string \| ArrayBuffer` | pinned default | Script recognizers (on use) |
|
|
727
|
+
| `lm`, `lmCjk`, `lmWorld` | `string \| ArrayBuffer` | pinned default | Language models (with `lm`) |
|
|
728
|
+
| `mathCls`, `mathEnc`, `mathDecInit`, `mathDecStep` or `mathDecStepKv`, `mathMeta`, `mathAccept`, `mathGate`, `mathSpanImg`, `mathSpanImgMeta` | `string \| ArrayBuffer` | pinned default | The math files (with `math`) |
|
|
718
729
|
|
|
719
730
|
### `BatchOptions`
|
|
720
731
|
|
|
@@ -763,7 +774,7 @@ It can fire once per model session.
|
|
|
763
774
|
|
|
764
775
|
Built-in models download from Datalab's Hugging Face repository. That host rate-limits by IP, which shows up as `HTTP 429 Too Many Requests` from shared addresses such as CI runners.
|
|
765
776
|
|
|
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:
|
|
777
|
+
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 (v1.2 has no mirror):
|
|
767
778
|
|
|
768
779
|
```sh
|
|
769
780
|
PPU_INDRA_OCR_MODEL_MIRROR=1 bun run your-script.ts
|
|
@@ -775,7 +786,7 @@ It is off by default. GitHub LFS bandwidth is a monthly budget, so turn it on wh
|
|
|
775
786
|
|
|
776
787
|
Benches use a small zero-dependency harness (`bench/harness.ts`): in-process timing, round-robin scheduling across rounds so thermal/GC drift hits every task equally, reporting the median plus min/max/stddev. Run `bun task bench`.
|
|
777
788
|
|
|
778
|
-
Representative results on Apple M1 / Bun 1.4.2 (9 rounds) at the
|
|
789
|
+
Representative results on Apple M1 / Bun 1.4.2 (9 rounds) at the 0.2 defaults (`v1.1` models, math off; not yet re-run on `v1.2`, where math is on by default and tables, handwriting routing and the turn checks add work), `convert()` per page, opencv and canvas-native:
|
|
779
790
|
|
|
780
791
|
```bash
|
|
781
792
|
task median +/-stddev min max
|
|
@@ -818,7 +829,7 @@ Both read the characters equally well. Indra keeps the spaces between words (tok
|
|
|
818
829
|
|
|
819
830
|
## How the Port Is Checked
|
|
820
831
|
|
|
821
|
-
`scripts/golden/` renders test pages and records every stage of the Python reference (`indra-ocr` 1.
|
|
832
|
+
`scripts/golden/` renders test pages and records every stage of the Python reference (`indra-ocr` 1.2.0) on them, once on each preset's models: orientation and the turn checks, skew, detection, recognition, script and handwriting routing, language-model beam search, math gates and readings, reading order, table structure and the false-table check, the text layer and its check, 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.
|
|
822
833
|
|
|
823
834
|
## Ecosystem
|
|
824
835
|
|
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{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(`
|
|
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,mathFlag,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){let model=preset(values)??DEFAULT_PRESET;await IndraOcrService.downloadModels({model,math:
|
|
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:mathFlag(values)??true,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 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
|
|
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 --no-math do not write math as LaTeX (skips the math 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.2 | v1.1 | v3.1 (default v1.2; 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 --no-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
|
@@ -15,7 +15,7 @@ Commands:
|
|
|
15
15
|
Convert flags:
|
|
16
16
|
--format <f> md | text | json (default md; json is one object per page)
|
|
17
17
|
--out <dir> write one file per input (.md, .txt or .jsonl)
|
|
18
|
-
--math
|
|
18
|
+
--no-math do not write math as LaTeX (skips the math models)
|
|
19
19
|
--keep-furniture keep page headers and footers in the markdown
|
|
20
20
|
--engine <e> opencv | canvas-native (default opencv)
|
|
21
21
|
--timings print per-page source and time to stderr
|
|
@@ -28,7 +28,7 @@ PDF flags:
|
|
|
28
28
|
--no-image-ocr on text-layer pages, do not OCR text inside images
|
|
29
29
|
|
|
30
30
|
Models and session:
|
|
31
|
-
--model <preset> v1.1 | v3.1 (default v1.
|
|
31
|
+
--model <preset> v1.2 | v1.1 | v3.1 (default v1.2; v3.1 is the smaller first release)
|
|
32
32
|
--no-lm do not re-read unsure lines with the language models
|
|
33
33
|
--model-dir <dir> read the model files from a folder instead of downloading
|
|
34
34
|
--execution-providers <list> comma-separated, e.g. cpu or cuda,cpu (default cpu)
|
|
@@ -43,7 +43,7 @@ Examples:
|
|
|
43
43
|
ppu-indra-ocr convert paper.pdf
|
|
44
44
|
ppu-indra-ocr convert "scans/*.png" --out results/
|
|
45
45
|
ppu-indra-ocr convert scan.png --format json --pretty
|
|
46
|
-
ppu-indra-ocr convert paper.pdf --mode ocr --math --timings
|
|
46
|
+
ppu-indra-ocr convert paper.pdf --mode ocr --no-math --timings
|
|
47
47
|
ppu-indra-ocr detect receipt.jpg
|
|
48
48
|
|
|
49
49
|
The model weights are Datalab's (https://huggingface.co/datalab-to/indra-ocr),
|
package/cli/options.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ export declare function str(values: CliValues, key: string): string | undefined;
|
|
|
13
13
|
export declare function format(values: CliValues): OutputFormat;
|
|
14
14
|
/** The model preset flag. */
|
|
15
15
|
export declare function preset(values: CliValues): ModelPreset | undefined;
|
|
16
|
+
/** Math on unless --no-math: the platform default (on for the CLI) when neither flag is given. */
|
|
17
|
+
export declare function mathFlag(values: CliValues): boolean | undefined;
|
|
16
18
|
/** The service options from parsed flags. */
|
|
17
19
|
export declare function buildIndraOptions(values: CliValues): IndraOptions;
|
|
18
20
|
/** The PDF options from parsed flags. */
|
package/cli/options.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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:
|
|
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"},"no-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 mathFlag(values){if(values["no-math"])return false;return values.math?true:undefined}export function buildIndraOptions(values){let providers=str(values,"execution-providers");return{model:preset(values),models:modelDir(values),lm:values["no-lm"]?false:undefined,math:mathFlag(values),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")}}
|
|
@@ -38,6 +38,8 @@ export declare abstract class BaseIndraOcrService<TCanvas = CoreCanvas> {
|
|
|
38
38
|
* the first line that needs them.
|
|
39
39
|
*/
|
|
40
40
|
initialize(): Promise<void>;
|
|
41
|
+
/** tsr_rel.onnx (its feature width and word buckets read from its bytes), with tsr_split and tsr_refine when the preset has them. */
|
|
42
|
+
private tsrSessions;
|
|
41
43
|
private load;
|
|
42
44
|
private imageOps;
|
|
43
45
|
/** Release the models. The service can be initialized again. */
|
|
@@ -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}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
|
|
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 math=this.options.math??this.platform.defaultMath;let eager=[...BASE_FILES,...this.has("recHw")&&this.has("hw")?["hw"]:[]];let roles=math?[...eager,...MATH_FILES.filter((r)=>this.has(r))]:eager;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 reader=math?await loadMathReader(this.platform.ort.Tensor,(r)=>this.has(r),session,text,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))))]]:[]));let hw=eager.includes("hw")?{hw:{cls:await session("hw"),rec:lazy("recHw",()=>session("recHw"))}}:{};let tables=this.has("tsrRel")?{tables:lazy("tsrRel",()=>this.tsrSessions(session,bytes))}:{};let verify=eager.includes("tableVerify")?{tableVerify:JSON.parse(text("tableVerify"))}:{};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,...hw,...tables,...verify},meta,ops,{furniture:this.options.furniture,adaptive:this.options.adaptive,math:reader,lm});this.log(`ready: model ${this.preset}, ${roles.length} model files, engine ${this.engineInUse}`)}async tsrSessions(session,loaded){let buf=await this.load("tsrRel");loaded.set("tsrRel",buf);let bytes=new Uint8Array(buf);let rel=await session("tsrRel");let split=this.has("tsrSplit")?{split:await session("tsrSplit")}:{};let refine=this.has("tsrRefine")?{refine:await session("tsrRefine")}:{};return{...tsrRelInfo(rel,bytes),rel,...split,...refine}}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{tsrRelInfo}from"../indra/table-rel.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{loadMathReader}from"./load-math.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)}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { InferenceSession } from "onnxruntime-common";
|
|
2
|
+
import type { ImageOps } from "../indra/image.js";
|
|
3
|
+
import { MathReader } from "../indra/math.js";
|
|
4
|
+
import type { TensorCtor } from "../indra/types.js";
|
|
5
|
+
import type { ModelFile } from "../model-catalogue.js";
|
|
6
|
+
/**
|
|
7
|
+
* The math reader of a model set: its decoder step graph (the per-layer one
|
|
8
|
+
* when the set has it), and the accept head, read gate and inline formula
|
|
9
|
+
* tagger it has. `text` reads a JSON file the caller already loaded.
|
|
10
|
+
*/
|
|
11
|
+
export declare function loadMathReader(Tensor: TensorCtor, has: (role: ModelFile) => boolean, session: (role: ModelFile) => Promise<InferenceSession>, text: (role: ModelFile) => string, ops: ImageOps): Promise<MathReader>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SpanImgTagger}from"../indra/math-span-img.js";import{MathReader}from"../indra/math.js";export async function loadMathReader(Tensor,has,session,text,ops){let json=(role)=>JSON.parse(text(role));let spanImg=has("mathSpanImg")&&has("mathSpanImgMeta")?new SpanImgTagger(Tensor,await session("mathSpanImg"),json("mathSpanImgMeta")):undefined;return new MathReader(Tensor,{cls:await session("mathCls"),enc:await session("mathEnc"),init:await session("mathDecInit"),step:await session(has("mathDecStepKv")?"mathDecStepKv":"mathDecStep")},json("mathMeta"),ops,{...has("mathAccept")?{accept:json("mathAccept")}:{},...has("mathGate")?{gate:json("mathGate")}:{},...spanImg?{spanImg}:{}})}
|
package/core/opencv-image-ops.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function opencvImageOps(cv){let interp=(i)=>i==="area"?cv.INTER_AREA:cv.INTER_LINEAR;let grayMat=(src)=>{let mat=new cv.Mat(src.height,src.width,cv.CV_8UC1);mat.data.set(src.data);return mat};let affineMat=(m)=>cv.matFromArray(2,3,cv.CV_64FC1,m);return{resize(src,width,height,interpolation){let from=grayMat(src);let to=new cv.Mat;try{cv.resize(from,to,new cv.Size(width,height),0,0,interp(interpolation));return{data:new Uint8Array(to.data),width,height}}finally{from.delete();to.delete()}},warpReplicate(src,m,width,height){let from=grayMat(src);let to=new cv.Mat;let mat=affineMat(m);try{cv.warpAffine(from,to,mat,new cv.Size(width,height),cv.INTER_LINEAR,cv.BORDER_REPLICATE);return{data:new Uint8Array(to.data),width,height}}finally{from.delete();to.delete();mat.delete()}},warpZero(src,m,width,height){let from=grayMat(src);let to=new cv.Mat;let mat=affineMat(m);try{cv.warpAffine(from,to,mat,new cv.Size(width,height));return{data:new Uint8Array(to.data),width,height}}finally{from.delete();to.delete();mat.delete()}}}}
|
|
1
|
+
export function opencvImageOps(cv){let interp=(i)=>i==="area"?cv.INTER_AREA:cv.INTER_LINEAR;let grayMat=(src)=>{let mat=new cv.Mat(src.height,src.width,cv.CV_8UC1);mat.data.set(src.data);return mat};let affineMat=(m)=>cv.matFromArray(2,3,cv.CV_64FC1,m);return{resize(src,width,height,interpolation){let from=grayMat(src);let to=new cv.Mat;try{cv.resize(from,to,new cv.Size(width,height),0,0,interp(interpolation));return{data:new Uint8Array(to.data),width,height}}finally{from.delete();to.delete()}},resizeFloat(src,width,height){let from=new cv.Mat(src.height,src.width,cv.CV_32FC1);from.data32F.set(src.data);let to=new cv.Mat;try{cv.resize(from,to,new cv.Size(width,height),0,0,cv.INTER_LINEAR);return{data:new Float32Array(to.data32F),width,height}}finally{from.delete();to.delete()}},warpReplicate(src,m,width,height){let from=grayMat(src);let to=new cv.Mat;let mat=affineMat(m);try{cv.warpAffine(from,to,mat,new cv.Size(width,height),cv.INTER_LINEAR,cv.BORDER_REPLICATE);return{data:new Uint8Array(to.data),width,height}}finally{from.delete();to.delete();mat.delete()}},warpZero(src,m,width,height){let from=grayMat(src);let to=new cv.Mat;let mat=affineMat(m);try{cv.warpAffine(from,to,mat,new cv.Size(width,height));return{data:new Uint8Array(to.data),width,height}}finally{from.delete();to.delete();mat.delete()}}}}
|
package/core/platform.d.ts
CHANGED
|
@@ -39,4 +39,6 @@ export type PlatformProvider<TCanvas = CoreCanvas> = {
|
|
|
39
39
|
defaultEngine: ProcessingEngine;
|
|
40
40
|
/** Whether `lm` is on when the options do not say: on where the language models are a cheap read. */
|
|
41
41
|
defaultLm: boolean;
|
|
42
|
+
/** Whether math is on when the options leave it out: on servers, off where the download matters. */
|
|
43
|
+
defaultMath: boolean;
|
|
42
44
|
};
|