@d0paminedriven/pdfdown-ocr 0.10.0 → 0.11.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/README.md +73 -24
- package/index.d.ts +1019 -15
- package/index.js +8 -857
- package/package.json +7 -5
- package/pdfdown_ocr.napi.js +884 -0
package/README.md
CHANGED
|
@@ -33,7 +33,7 @@ Verify with `tesseract --version` -- you should see 5.x.
|
|
|
33
33
|
|
|
34
34
|
The package automatically detects the tessdata directory at runtime by parsing the output of `tesseract --list-langs`. The detected path is cached for the lifetime of the process using a `OnceLock<Option<String>>` -- no global environment mutation, fully thread-safe.
|
|
35
35
|
|
|
36
|
-
**Resolution order:**
|
|
36
|
+
**Resolution order:**
|
|
37
37
|
|
|
38
38
|
1. `TESSDATA_PREFIX` environment variable (if set, used as-is -- no auto-detection runs)
|
|
39
39
|
2. Auto-detection via `tesseract --list-langs` (parses the path from `List of available languages in "/path/to/tessdata/"`)
|
|
@@ -53,36 +53,34 @@ export TESSDATA_PREFIX="/opt/custom/tessdata"
|
|
|
53
53
|
|
|
54
54
|
## API
|
|
55
55
|
|
|
56
|
-
This package exports everything from `@d0paminedriven/pdfdown` (text, images, annotations, structured text, metadata -- both sync and async), plus the OCR-specific APIs below. See the [base package docs](https://www.npmjs.com/package/@d0paminedriven/pdfdown) for the full base API.
|
|
56
|
+
This package exports everything from `@d0paminedriven/pdfdown` (text, images, annotations, AcroForm fields, attachments, embedded e-invoice extraction, structured text, metadata -- both sync and async), plus the OCR-specific APIs below. `PdfDocumentOcr` carries the same `form`, `formFields`, `totalFormFields` and `formFieldPages` aggregates as `PdfDocument`; form extraction is read-only and needs neither Tesseract nor PDFium. See the [base package docs](https://www.npmjs.com/package/@d0paminedriven/pdfdown) for the full base API.
|
|
57
57
|
|
|
58
58
|
### OCR standalone functions
|
|
59
59
|
|
|
60
60
|
```typescript
|
|
61
61
|
// Per-page OCR text extraction
|
|
62
|
-
export declare function extractTextWithOcrPerPage(
|
|
63
|
-
buffer: Buffer,
|
|
64
|
-
opts?: OcrOptions,
|
|
65
|
-
): Array<OcrPageText>;
|
|
62
|
+
export declare function extractTextWithOcrPerPage(buffer: Buffer, opts?: OcrOptions): Array<OcrPageText>;
|
|
66
63
|
|
|
67
|
-
export declare function extractTextWithOcrPerPageAsync(
|
|
68
|
-
buffer: Buffer,
|
|
69
|
-
opts?: OcrOptions,
|
|
70
|
-
): Promise<Array<OcrPageText>>;
|
|
64
|
+
export declare function extractTextWithOcrPerPageAsync(buffer: Buffer, opts?: OcrOptions): Promise<Array<OcrPageText>>;
|
|
71
65
|
|
|
72
66
|
// Full document extraction with OCR text fallback
|
|
73
67
|
export declare function pdfDocumentOcr(buffer: Buffer, opts?: OcrOptions): PdfDocumentOcr;
|
|
74
68
|
|
|
75
|
-
export declare function pdfDocumentOcrAsync(
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
):
|
|
69
|
+
export declare function pdfDocumentOcrAsync(buffer: Buffer, opts?: OcrOptions): Promise<PdfDocumentOcr>;
|
|
70
|
+
|
|
71
|
+
// Positioned words and lines with the same three-tier cascade
|
|
72
|
+
export declare function extractLayoutWithOcrPerPage(buffer: Buffer, opts?: OcrOptions): Array<PageLayout>;
|
|
73
|
+
|
|
74
|
+
export declare function extractLayoutWithOcrPerPageAsync(buffer: Buffer, opts?: OcrOptions): Promise<Array<PageLayout>>;
|
|
79
75
|
```
|
|
80
76
|
|
|
81
77
|
### `PdfDown` class (includes OCR methods)
|
|
82
78
|
|
|
83
79
|
```typescript
|
|
84
80
|
export declare class PdfDown {
|
|
85
|
-
constructor(buffer: Buffer);
|
|
81
|
+
constructor(buffer: Buffer); // a PDF or an .xlsx workbook
|
|
82
|
+
static openAsync(buffer: Buffer): Promise<PdfDown>;
|
|
83
|
+
readonly format: DocumentFormat; // "Pdf" | "Xlsx"
|
|
86
84
|
|
|
87
85
|
// ── Base methods ──
|
|
88
86
|
textPerPage(): Array<PageText>;
|
|
@@ -91,28 +89,39 @@ export declare class PdfDown {
|
|
|
91
89
|
imagesPerPageAsync(): Promise<Array<PageImage>>;
|
|
92
90
|
annotationsPerPage(): Array<PageAnnotation>;
|
|
93
91
|
annotationsPerPageAsync(): Promise<Array<PageAnnotation>>;
|
|
92
|
+
attachments(): Array<Attachment>;
|
|
93
|
+
attachmentsAsync(): Promise<Array<Attachment>>;
|
|
94
|
+
invoice(opts?: InvoiceOptions): InvoiceResult;
|
|
95
|
+
invoiceAsync(opts?: InvoiceOptions): Promise<InvoiceResult>;
|
|
96
|
+
layout(opts?: SpreadsheetOptions): Array<PageLayout>; // a PDF ignores opts; a workbook yields one logical page per sheet
|
|
97
|
+
layoutAsync(opts?: SpreadsheetOptions): Promise<Array<PageLayout>>;
|
|
98
|
+
spreadsheetCells(opts?: SpreadsheetOptions): Array<SheetCells>; // workbooks only
|
|
99
|
+
spreadsheetCellsAsync(opts?: SpreadsheetOptions): Promise<Array<SheetCells>>;
|
|
94
100
|
structuredText(): Array<StructuredPageText>;
|
|
95
101
|
structuredTextAsync(): Promise<Array<StructuredPageText>>;
|
|
96
102
|
metadata(): PdfMeta;
|
|
97
103
|
metadataAsync(): Promise<PdfMeta>;
|
|
98
104
|
document(): PdfDocument;
|
|
99
105
|
documentAsync(): Promise<PdfDocument>;
|
|
106
|
+
formFieldsPerPage(): Array<PageFormField>;
|
|
107
|
+
formFieldsPerPageAsync(): Promise<Array<PageFormField>>;
|
|
100
108
|
|
|
101
109
|
// ── OCR methods ──
|
|
102
110
|
textWithOcrPerPage(opts?: OcrOptions): Array<OcrPageText>;
|
|
103
111
|
textWithOcrPerPageAsync(opts?: OcrOptions): Promise<Array<OcrPageText>>;
|
|
104
112
|
documentOcr(opts?: OcrOptions): PdfDocumentOcr;
|
|
105
113
|
documentOcrAsync(opts?: OcrOptions): Promise<PdfDocumentOcr>;
|
|
114
|
+
layoutWithOcr(opts?: OcrOptions): Array<PageLayout>;
|
|
115
|
+
layoutWithOcrAsync(opts?: OcrOptions): Promise<Array<PageLayout>>;
|
|
106
116
|
}
|
|
107
117
|
```
|
|
108
118
|
|
|
109
119
|
### Types
|
|
110
120
|
|
|
111
121
|
```typescript
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
122
|
+
// The deepest cascade tier that produced a page's text, or the logical page of a workbook sheet.
|
|
123
|
+
// Spreadsheet pages carry `PageLayout.sheet` and every word carries `TextWord.cell` ("C3").
|
|
124
|
+
export type TextSource = "Native" | "Ocr" | "Rendered" | "Spreadsheet";
|
|
116
125
|
|
|
117
126
|
export interface OcrPageText {
|
|
118
127
|
page: number;
|
|
@@ -150,6 +159,10 @@ export interface PdfDocumentOcr {
|
|
|
150
159
|
structuredText: Array<OcrStructuredPageText>;
|
|
151
160
|
images: Array<PageImage>;
|
|
152
161
|
annotations: Array<PageAnnotation>;
|
|
162
|
+
form?: FormInfo;
|
|
163
|
+
formFields: Array<PageFormField>;
|
|
164
|
+
totalFormFields: number;
|
|
165
|
+
formFieldPages: Array<number>;
|
|
153
166
|
}
|
|
154
167
|
```
|
|
155
168
|
|
|
@@ -161,6 +174,7 @@ export interface PdfDocumentOcr {
|
|
|
161
174
|
|
|
162
175
|
```typescript
|
|
163
176
|
import { readFile } from "fs/promises";
|
|
177
|
+
|
|
164
178
|
import { extractTextWithOcrPerPageAsync } from "@d0paminedriven/pdfdown-ocr";
|
|
165
179
|
|
|
166
180
|
const pdf = await readFile("scanned-document.pdf");
|
|
@@ -175,6 +189,7 @@ for (const { page, text, source } of pages) {
|
|
|
175
189
|
|
|
176
190
|
```typescript
|
|
177
191
|
import { readFile } from "fs/promises";
|
|
192
|
+
|
|
178
193
|
import { PdfDown } from "@d0paminedriven/pdfdown-ocr";
|
|
179
194
|
|
|
180
195
|
const pdf = new PdfDown(await readFile("scanned-document.pdf"));
|
|
@@ -191,6 +206,7 @@ const meta = pdf.metadata();
|
|
|
191
206
|
|
|
192
207
|
```typescript
|
|
193
208
|
import { readFile } from "fs/promises";
|
|
209
|
+
|
|
194
210
|
import { PdfDown } from "@d0paminedriven/pdfdown-ocr";
|
|
195
211
|
|
|
196
212
|
const pdf = new PdfDown(await readFile("scanned-document.pdf"));
|
|
@@ -207,13 +223,14 @@ const result = await pdf.documentOcrAsync({ minTextLength: 10 });
|
|
|
207
223
|
|
|
208
224
|
```typescript
|
|
209
225
|
import { readFile } from "fs/promises";
|
|
226
|
+
|
|
210
227
|
import { PdfDown } from "@d0paminedriven/pdfdown-ocr";
|
|
211
228
|
|
|
212
229
|
const pdf = new PdfDown(await readFile("scanned-document.pdf"));
|
|
213
230
|
|
|
214
231
|
const [ocrText, images] = await Promise.all([
|
|
215
232
|
pdf.textWithOcrPerPageAsync({ minTextLength: 10 }),
|
|
216
|
-
pdf.imagesPerPageAsync()
|
|
233
|
+
pdf.imagesPerPageAsync()
|
|
217
234
|
]);
|
|
218
235
|
|
|
219
236
|
const imagesByPage = Map.groupBy(images, (img) => img.page);
|
|
@@ -222,7 +239,7 @@ for (const { page, text, source } of ocrText) {
|
|
|
222
239
|
const pageImages = (imagesByPage.get(page) ?? []).map((img) => ({
|
|
223
240
|
dataUrl: `data:image/png;base64,${img.data.toString("base64")}`,
|
|
224
241
|
width: img.width,
|
|
225
|
-
height: img.height
|
|
242
|
+
height: img.height
|
|
226
243
|
}));
|
|
227
244
|
// Send { page, text, source, images: pageImages } to your embedding pipeline
|
|
228
245
|
}
|
|
@@ -237,15 +254,47 @@ Both methods extract everything from a PDF in a single call. The difference is h
|
|
|
237
254
|
| `document()` / `documentAsync()` | Native PDF text only | `PdfDocument` | PDF has selectable text |
|
|
238
255
|
| `documentOcr()` / `documentOcrAsync()` | Native with OCR fallback | `PdfDocumentOcr` | PDF may contain scanned/image-only pages |
|
|
239
256
|
|
|
240
|
-
`PdfDocumentOcr` uses `OcrPageText` (with `source: 'Native' | 'Ocr'`) and `OcrStructuredPageText` (with header/body/footer split plus source) instead of the base `PageText` and `StructuredPageText` types. Images, annotations, and
|
|
257
|
+
`PdfDocumentOcr` uses `OcrPageText` (with `source: 'Native' | 'Ocr'`) and `OcrStructuredPageText` (with header/body/footer split plus source) instead of the base `PageText` and `StructuredPageText` types. Images, annotations, metadata and the read-only AcroForm data (`form`, `formFields`, `totalFormFields`, `formFieldPages`; see the base package docs) are identical in both.
|
|
258
|
+
|
|
259
|
+
### Positioned text with OCR
|
|
260
|
+
|
|
261
|
+
`extractLayoutWithOcrPerPage` returns the base package's `PageLayout` shape (words, lines and image placements with boxes in PDF points) for every page, choosing the source per page exactly like the text cascade:
|
|
262
|
+
|
|
263
|
+
1. **Native** -- glyphs placed from the content stream, with `fontName` / `fontSize` / `bold` on every word.
|
|
264
|
+
2. **Ocr** -- the page's embedded raster images are OCR'd and each Tesseract word box is mapped through the image's `Do` placement onto the page. Words carry `confidence` (0..1) instead of font metadata.
|
|
265
|
+
3. **Rendered** -- with PDFium, the page is rasterised as displayed at `renderDpi` and OCR'd; word boxes are mapped back onto the page box in the page's own frame, the one native words use, and `contentRotation` includes `/Rotate`.
|
|
266
|
+
|
|
267
|
+
Copier and fax scans (`CCITTFaxDecode`, Group 3 and Group 4) are decoded in pure Rust, so they are read at tier 2 without PDFium. When the upright pass scores a mean Tesseract confidence under 55 (a landscape sheet scanned in portrait comes back as punctuation at 35-45), the raster is OCR'd again turned 90°, 270° and 180° and the best orientation wins. The page then reports `contentRotation`, the turn carrying the most confident OCR text across its images (the tiles of a tiled scan vote together), and every word, line and image placement is expressed in that turned frame, with `width`/`height` swapped for a quarter turn. A warning names each turned image with more than a few words and who decided the turn (the orientation detector or the confidence retry); such an image that reads upright at a different turn than the page is named too, since its words read sideways in the page frame. The render tier reads the page as displayed, so on a `/Rotate` page its `contentRotation` includes `/Rotate`; for any page, displayed coordinates are the reported frame turned clockwise by `rotate - contentRotation`. The same retry applies to `extractTextWithOcrPerPage`.
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
import { readFileSync } from "fs";
|
|
271
|
+
|
|
272
|
+
import { extractLayoutWithOcrPerPage } from "@d0paminedriven/pdfdown-ocr";
|
|
273
|
+
|
|
274
|
+
for (const page of extractLayoutWithOcrPerPage(readFileSync("scan.pdf"), { render: "Auto" })) {
|
|
275
|
+
console.log(`page ${page.page} (${page.source})`);
|
|
276
|
+
for (const line of page.lines) {
|
|
277
|
+
const confidence = page.words.slice(line.firstWord, line.firstWord + line.wordCount).map((w) => w.confidence ?? 1);
|
|
278
|
+
console.log(` ${Math.min(...confidence).toFixed(2)} ${line.text}`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
## Invoices from scans
|
|
284
|
+
|
|
285
|
+
`invoice()` and `invoiceAsync()` read the header fields of a PDF from its pages (see the base README's "Invoices" section). In this package they run the OCR cascade with default options on the **first and the last page only**, the two pages the header track reads, so a long scan does not cost a whole-document OCR; `source` then reports `Ocr`, `Rendered` or `Mixed` and every OCR'd field's confidence is scaled by its words' Tesseract confidence. For other OCR options, call `layoutWithOcr(opts)` yourself and hand the pages to `invoiceFromLayout(pages)`.
|
|
286
|
+
|
|
287
|
+
## Workbooks
|
|
288
|
+
|
|
289
|
+
This package inherits the base package's workbook support: `detectFormat`, `PdfDown.openAsync`, `format`, `spreadsheetCells`, `layout` on a workbook and the standalone `layoutFromXlsx`, with the same options, number-format subset, logical-page contract and limits (see the base README's "Workbooks" section). A workbook's text is already text, so it never needs OCR: the OCR methods read PDFs, and on a workbook `textWithOcrPerPage`, `documentOcr` and `layoutWithOcr` fail with `unsupported operation: <method> reads a PDF; this document is a workbook` (the sync methods throw it, the async ones reject with it).
|
|
241
290
|
|
|
242
291
|
## How it works
|
|
243
292
|
|
|
244
|
-
1. **Text extraction:** Each page is first
|
|
293
|
+
1. **Text extraction (the cascade):** Each page is read natively first. A page goes to OCR when its native text is under `minTextLength` non-whitespace characters, or when its native words cover under 2% of the page while images cover more than half of it or the content stream paints 200 or more path operators (a scan with a stamp on it, or text printed as outlines); a few words on an otherwise empty cover sheet stay native. Tier 2 decodes the embedded rasters and feeds them to Tesseract; tier 3, with PDFium, renders the page when the page has no rasters but painted paths, or when tier 2 found nothing or only a weak result on a path-heavy page. On a hybrid page the native words stay and OCR adds only what they do not cover (duplicates dropped at IoU > 0.5); `source` reports the deepest tier that ran (`Native`, `Ocr` or `Rendered`), even when OCR added no words; OCR words carry `confidence`, native words do not, and a warning counts the native words kept. Orientation is decided per raster: an upright pass with a mean Tesseract confidence of 80 or more stands; below that the raster is shown to Tesseract's orientation detector (OSD), and only when OSD cannot decide and the upright pass scored under 55 is the raster read again at 90°, 270° and 180° with the best score winning.
|
|
245
294
|
|
|
246
295
|
2. **Structured text:** After text extraction, repeated header/footer lines are detected across pages using frequency analysis (requires 3+ pages). Each page's text is split into `header`, `body`, and `footer` sections. For OCR results, the `source` tag is preserved so you know whether each page's content came from native extraction or OCR.
|
|
247
296
|
|
|
248
|
-
3. **Parallelism:** OCR runs on a dedicated capped Rayon thread pool (default 4 threads, configurable via `maxThreads`) to prevent CPU oversubscription. Text extraction, image extraction, and annotation extraction run concurrently via `rayon::join` when using `documentOcr` / `documentOcrAsync`.
|
|
297
|
+
3. **Parallelism:** OCR runs on a dedicated capped Rayon thread pool (default 4 threads, configurable via `maxThreads`) to prevent CPU oversubscription. Text extraction, image extraction, and annotation extraction run concurrently via `rayon::join` when using `documentOcr` / `documentOcrAsync`. The package entry point also sets `OMP_THREAD_LIMIT=1` before the native module loads, because Ubuntu's libtesseract otherwise starts one OpenMP thread per core inside every recognise call and four workers on an eight-core box thrash it (measured: 7.8 s per page down to 0.6 s). Parallelism therefore comes from `maxThreads`, not from OpenMP; set `OMP_THREAD_LIMIT` or `OMP_NUM_THREADS` yourself before requiring the package to override this.
|
|
249
298
|
|
|
250
299
|
4. **Tessdata discovery:** On first OCR invocation, the tessdata path is resolved once and cached in a `OnceLock`. The `TESSDATA_PREFIX` environment variable is checked first; if unset, `tesseract --list-langs` is executed and its output is parsed to extract the path. No environment variables are mutated -- the path is passed directly to Tesseract's init function.
|
|
251
300
|
|