@molecule/api-ocr-tesseract 1.0.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 +115 -0
- package/README.md +109 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +47 -0
- package/dist/provider.d.ts +25 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +121 -0
- package/dist/types.d.ts +28 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/package.json +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work.
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
AUTO-GENERATED — DO NOT EDIT THIS FILE.
|
|
3
|
+
Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
|
|
4
|
+
Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
|
|
5
|
+
To change this document, edit the module-level JSDoc in src/index.ts.
|
|
6
|
+
Generated: 2026-09-26T03:23:35.151Z
|
|
7
|
+
-->
|
|
8
|
+
|
|
9
|
+
# @molecule/api-ocr-tesseract
|
|
10
|
+
|
|
11
|
+
> **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
|
|
12
|
+
> It is written to be read by coding agents as much as by people, and is generated from this
|
|
13
|
+
> package's source — edit `src/index.ts` JSDoc, not this file.
|
|
14
|
+
|
|
15
|
+
Self-hosted Tesseract OCR provider for molecule.dev — text extraction from images in your own process, no vendor account, no per-call cost
|
|
16
|
+
|
|
17
|
+
## Type
|
|
18
|
+
|
|
19
|
+
`provider`
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @molecule/api-ocr-tesseract @molecule/api-ocr tesseract.js
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## API
|
|
28
|
+
|
|
29
|
+
### Interfaces
|
|
30
|
+
|
|
31
|
+
#### `TesseractOcrConfig`
|
|
32
|
+
|
|
33
|
+
Options for {@link createProvider}. Tesseract runs entirely in your process
|
|
34
|
+
(a WASM worker thread) — no API key, no egress except the first download of
|
|
35
|
+
a language's traineddata unless you point `langPath` at a local copy.
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
interface TesseractOcrConfig {
|
|
39
|
+
/** Default Tesseract language code(s), `+`-joined (e.g. `eng`, `eng+deu`). Default `eng`. */
|
|
40
|
+
language?: string
|
|
41
|
+
/**
|
|
42
|
+
* Where traineddata files are downloaded from. Defaults to the tessdata CDN
|
|
43
|
+
* the library ships with. Point it at your own mirror or a local directory
|
|
44
|
+
* (`file://…` or a path the worker can read) for offline installs.
|
|
45
|
+
*/
|
|
46
|
+
langPath?: string
|
|
47
|
+
/** Directory to cache downloaded traineddata in. Default: the OS temp dir. */
|
|
48
|
+
cachePath?: string
|
|
49
|
+
/**
|
|
50
|
+
* Whether to fetch `.traineddata.gz` (compressed). Default true; set false
|
|
51
|
+
* for a `langPath` that only serves uncompressed files.
|
|
52
|
+
*/
|
|
53
|
+
gzip?: boolean
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Functions
|
|
58
|
+
|
|
59
|
+
#### `createProvider(config)`
|
|
60
|
+
|
|
61
|
+
Creates a self-hosted Tesseract OCR provider.
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
function createProvider(config?: TesseractOcrConfig): OcrProvider
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
- `config` — Default language and traineddata source.
|
|
68
|
+
|
|
69
|
+
**Returns:** An `OcrProvider` backed by Tesseract in a worker thread.
|
|
70
|
+
|
|
71
|
+
### Constants
|
|
72
|
+
|
|
73
|
+
#### `provider`
|
|
74
|
+
|
|
75
|
+
The provider implementation.
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
const provider: OcrProvider
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Core Interface
|
|
82
|
+
|
|
83
|
+
Implements `@molecule/api-ocr` interface.
|
|
84
|
+
|
|
85
|
+
## Bond Wiring
|
|
86
|
+
|
|
87
|
+
Setup function to register this provider with the core interface:
|
|
88
|
+
|
|
89
|
+
```typescript
|
|
90
|
+
import { setProvider } from '@molecule/api-ocr'
|
|
91
|
+
import { provider } from '@molecule/api-ocr-tesseract'
|
|
92
|
+
|
|
93
|
+
export function setupOcrTesseract(): void {
|
|
94
|
+
setProvider(provider)
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Injection Notes
|
|
99
|
+
|
|
100
|
+
### Requirements
|
|
101
|
+
|
|
102
|
+
Peer dependencies:
|
|
103
|
+
|
|
104
|
+
- `@molecule/api-ocr` >=1.0.0
|
|
105
|
+
|
|
106
|
+
### Runtime Dependencies
|
|
107
|
+
|
|
108
|
+
- `@molecule/api-ocr`
|
|
109
|
+
- `tesseract.js`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser guard — `@molecule/api-ocr-tesseract` is SERVER-ONLY.
|
|
3
|
+
*
|
|
4
|
+
* Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
|
|
5
|
+
* Evaluating a server package in a browser bundle is always an import-graph mistake
|
|
6
|
+
* (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
|
|
7
|
+
* ("Buffer is not defined") far from the culprit. Throwing here names the package and
|
|
8
|
+
* the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
|
|
9
|
+
* unaffected: the throw requires browser globals AND the absence of a node runtime.
|
|
10
|
+
*/
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
|
|
13
|
+
throw new Error('@molecule/api-ocr-tesseract is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
|
|
14
|
+
'from server code (a server route/function or your API), or dynamic-import it inside ' +
|
|
15
|
+
'the server handler — never from components or shared client modules, and never ' +
|
|
16
|
+
'polyfill Buffer/process to silence this.');
|
|
17
|
+
}
|
|
18
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-hosted Tesseract OCR provider for molecule.dev.
|
|
3
|
+
*
|
|
4
|
+
* Implements the `@molecule/api-ocr` contract with Tesseract running in a
|
|
5
|
+
* worker thread inside your own process — no vendor account, no per-call cost,
|
|
6
|
+
* no egress after a language's traineddata is downloaded once. The eject path
|
|
7
|
+
* when a hosted or model-based OCR bond is more than a high-volume scan job
|
|
8
|
+
* needs.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* import { setProvider, requireProvider } from '@molecule/api-ocr'
|
|
13
|
+
* import { createProvider } from '@molecule/api-ocr-tesseract'
|
|
14
|
+
*
|
|
15
|
+
* setProvider(createProvider({ language: 'eng' }))
|
|
16
|
+
*
|
|
17
|
+
* const result = await requireProvider().recognize({
|
|
18
|
+
* data: new Uint8Array(scanBytes),
|
|
19
|
+
* mimeType: 'image/png',
|
|
20
|
+
* })
|
|
21
|
+
* console.log(result.pages[0].confidence) // Tesseract's own 0–1 mean score
|
|
22
|
+
* await requireProvider().dispose?.() // end of the batch: free the workers
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @remarks
|
|
26
|
+
* - **CPU-heavy work belongs in a worker process, not your request handler.**
|
|
27
|
+
* Tesseract runs in its own worker THREAD, so the event loop is not blocked,
|
|
28
|
+
* a recognition pass still takes seconds of CPU. For a high-volume API, put
|
|
29
|
+
* the work behind a queue (e.g. `@molecule/api-cron` + a job table), not the
|
|
30
|
+
* create/update handler.
|
|
31
|
+
* - **`language` is a TESSERACT code, not a BCP-47 tag** — `eng`, `deu`,
|
|
32
|
+
* `eng+deu`. `en` fails traineddata lookup on first use. The first call in a
|
|
33
|
+
* new language downloads its traineddata (a few MB, cached in `cachePath`);
|
|
34
|
+
* point `langPath` at your own mirror for offline installs.
|
|
35
|
+
* - **Recognize at real size.** Tesseract wants ~300 DPI grayscale input; a
|
|
36
|
+
* 200×40 thumbnail of a word returns garbage. Do not downscale before this
|
|
37
|
+
* bond the way you would before a vision model.
|
|
38
|
+
* - `confidence` is Tesseract's own mean over the page (0–1). Gate on it with
|
|
39
|
+
* a threshold you calibrated on YOUR scans — clean screenshots score 0.9+,
|
|
40
|
+
* photos of crumpled paper can score 0.4 and still be mostly right.
|
|
41
|
+
* - No layout model: column order, tables and multi-column pages come out in
|
|
42
|
+
* reading-order guesses. For table structure, crop cells or use a
|
|
43
|
+
* vision-model bond and compare.
|
|
44
|
+
*/
|
|
45
|
+
export * from './browser-guard.js';
|
|
46
|
+
export * from './provider.js';
|
|
47
|
+
export * from './types.js';
|
|
48
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-hosted Tesseract OCR provider for molecule.dev.
|
|
3
|
+
*
|
|
4
|
+
* Implements the `@molecule/api-ocr` contract with Tesseract running in a
|
|
5
|
+
* worker thread inside your own process — no vendor account, no per-call cost,
|
|
6
|
+
* no egress after a language's traineddata is downloaded once. The eject path
|
|
7
|
+
* when a hosted or model-based OCR bond is more than a high-volume scan job
|
|
8
|
+
* needs.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* import { setProvider, requireProvider } from '@molecule/api-ocr'
|
|
13
|
+
* import { createProvider } from '@molecule/api-ocr-tesseract'
|
|
14
|
+
*
|
|
15
|
+
* setProvider(createProvider({ language: 'eng' }))
|
|
16
|
+
*
|
|
17
|
+
* const result = await requireProvider().recognize({
|
|
18
|
+
* data: new Uint8Array(scanBytes),
|
|
19
|
+
* mimeType: 'image/png',
|
|
20
|
+
* })
|
|
21
|
+
* console.log(result.pages[0].confidence) // Tesseract's own 0–1 mean score
|
|
22
|
+
* await requireProvider().dispose?.() // end of the batch: free the workers
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @remarks
|
|
26
|
+
* - **CPU-heavy work belongs in a worker process, not your request handler.**
|
|
27
|
+
* Tesseract runs in its own worker THREAD, so the event loop is not blocked,
|
|
28
|
+
* a recognition pass still takes seconds of CPU. For a high-volume API, put
|
|
29
|
+
* the work behind a queue (e.g. `@molecule/api-cron` + a job table), not the
|
|
30
|
+
* create/update handler.
|
|
31
|
+
* - **`language` is a TESSERACT code, not a BCP-47 tag** — `eng`, `deu`,
|
|
32
|
+
* `eng+deu`. `en` fails traineddata lookup on first use. The first call in a
|
|
33
|
+
* new language downloads its traineddata (a few MB, cached in `cachePath`);
|
|
34
|
+
* point `langPath` at your own mirror for offline installs.
|
|
35
|
+
* - **Recognize at real size.** Tesseract wants ~300 DPI grayscale input; a
|
|
36
|
+
* 200×40 thumbnail of a word returns garbage. Do not downscale before this
|
|
37
|
+
* bond the way you would before a vision model.
|
|
38
|
+
* - `confidence` is Tesseract's own mean over the page (0–1). Gate on it with
|
|
39
|
+
* a threshold you calibrated on YOUR scans — clean screenshots score 0.9+,
|
|
40
|
+
* photos of crumpled paper can score 0.4 and still be mostly right.
|
|
41
|
+
* - No layout model: column order, tables and multi-column pages come out in
|
|
42
|
+
* reading-order guesses. For table structure, crop cells or use a
|
|
43
|
+
* vision-model bond and compare.
|
|
44
|
+
*/
|
|
45
|
+
export * from './browser-guard.js';
|
|
46
|
+
export * from './provider.js';
|
|
47
|
+
export * from './types.js';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-hosted Tesseract implementation of OcrProvider.
|
|
3
|
+
*
|
|
4
|
+
* Runs Tesseract (Apache-2.0, code and traineddata weights) in a WASM worker
|
|
5
|
+
* thread inside your own process — no vendor account, no per-call egress after
|
|
6
|
+
* the first use of a language downloads its traineddata. Workers are created
|
|
7
|
+
* lazily per language (LSTM engine) and reused across calls; `dispose()`
|
|
8
|
+
* terminates them.
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import type { OcrProvider } from '@molecule/api-ocr';
|
|
13
|
+
import type { TesseractOcrConfig } from './types.js';
|
|
14
|
+
/**
|
|
15
|
+
* Creates a self-hosted Tesseract OCR provider.
|
|
16
|
+
*
|
|
17
|
+
* @param config - Default language and traineddata source.
|
|
18
|
+
* @returns An `OcrProvider` backed by Tesseract in a worker thread.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createProvider(config?: TesseractOcrConfig): OcrProvider;
|
|
21
|
+
/**
|
|
22
|
+
* The provider implementation.
|
|
23
|
+
*/
|
|
24
|
+
export declare const provider: OcrProvider;
|
|
25
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,OAAO,KAAK,EAAwB,WAAW,EAAa,MAAM,mBAAmB,CAAA;AAErF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAuFpD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,kBAAkB,GAAG,WAAW,CAEvE;AAID;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,WASrB,CAAA"}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Self-hosted Tesseract implementation of OcrProvider.
|
|
3
|
+
*
|
|
4
|
+
* Runs Tesseract (Apache-2.0, code and traineddata weights) in a WASM worker
|
|
5
|
+
* thread inside your own process — no vendor account, no per-call egress after
|
|
6
|
+
* the first use of a language downloads its traineddata. Workers are created
|
|
7
|
+
* lazily per language (LSTM engine) and reused across calls; `dispose()`
|
|
8
|
+
* terminates them.
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import { createWorker } from 'tesseract.js';
|
|
13
|
+
/**
|
|
14
|
+
* OCR provider backed by self-hosted Tesseract.
|
|
15
|
+
*/
|
|
16
|
+
class TesseractOcrProvider {
|
|
17
|
+
config;
|
|
18
|
+
name = 'tesseract';
|
|
19
|
+
workers = new Map();
|
|
20
|
+
/**
|
|
21
|
+
* Creates a new Tesseract OCR provider.
|
|
22
|
+
*
|
|
23
|
+
* @param config - Default language and where traineddata comes from.
|
|
24
|
+
*/
|
|
25
|
+
constructor(config = {}) {
|
|
26
|
+
this.config = config;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Recognize text in one image.
|
|
30
|
+
*
|
|
31
|
+
* @param input - The image bytes and MIME type.
|
|
32
|
+
* @param options - Language hint as Tesseract traineddata code(s), e.g. `eng`
|
|
33
|
+
* or `eng+deu` — a BCP-47 tag like `en` fails traineddata lookup.
|
|
34
|
+
* @returns One page with Tesseract's text and its own mean confidence.
|
|
35
|
+
*/
|
|
36
|
+
async recognize(input, options) {
|
|
37
|
+
const language = options?.language ?? this.config.language ?? 'eng';
|
|
38
|
+
const worker = await this.worker(language);
|
|
39
|
+
const { data } = await worker.recognize(Buffer.from(input.data));
|
|
40
|
+
const text = data.text ?? '';
|
|
41
|
+
return {
|
|
42
|
+
text,
|
|
43
|
+
pages: [
|
|
44
|
+
{
|
|
45
|
+
pageNumber: 1,
|
|
46
|
+
text,
|
|
47
|
+
...(typeof data.confidence === 'number' ? { confidence: data.confidence / 100 } : {}),
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Terminates every worker thread this provider started.
|
|
54
|
+
*/
|
|
55
|
+
async dispose() {
|
|
56
|
+
const pending = [...this.workers.values()];
|
|
57
|
+
this.workers.clear();
|
|
58
|
+
await Promise.allSettled(pending.map(async (p) => {
|
|
59
|
+
try {
|
|
60
|
+
await (await p).terminate();
|
|
61
|
+
}
|
|
62
|
+
catch (_error) {
|
|
63
|
+
// Intentional noop: a worker that already died is disposed as far as
|
|
64
|
+
// the caller cares — dispose() must not fail because one did.
|
|
65
|
+
}
|
|
66
|
+
}));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The worker for one language, created once and reused. A failed creation is
|
|
70
|
+
* dropped so the next call retries instead of caching the rejection.
|
|
71
|
+
*
|
|
72
|
+
* @param language - Tesseract language code(s).
|
|
73
|
+
* @returns The running worker.
|
|
74
|
+
*/
|
|
75
|
+
worker(language) {
|
|
76
|
+
const existing = this.workers.get(language);
|
|
77
|
+
if (existing)
|
|
78
|
+
return existing;
|
|
79
|
+
// OEM 1 = LSTM-only: faster and more accurate than the legacy engine on
|
|
80
|
+
// the tessdata_fast/best packs.
|
|
81
|
+
const created = createWorker(language, 1, {
|
|
82
|
+
...(this.config.langPath ? { langPath: this.config.langPath } : {}),
|
|
83
|
+
...(this.config.cachePath ? { cachePath: this.config.cachePath } : {}),
|
|
84
|
+
...(this.config.gzip !== undefined ? { gzip: this.config.gzip } : {}),
|
|
85
|
+
});
|
|
86
|
+
this.workers.set(language, created);
|
|
87
|
+
created.catch((_error) => {
|
|
88
|
+
// Intentional noop: a worker whose creation failed is dropped so the
|
|
89
|
+
// next call retries from scratch; the rejection already surfaced to the
|
|
90
|
+
// caller that triggered it.
|
|
91
|
+
this.workers.delete(language);
|
|
92
|
+
});
|
|
93
|
+
return created;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Creates a self-hosted Tesseract OCR provider.
|
|
98
|
+
*
|
|
99
|
+
* @param config - Default language and traineddata source.
|
|
100
|
+
* @returns An `OcrProvider` backed by Tesseract in a worker thread.
|
|
101
|
+
*/
|
|
102
|
+
export function createProvider(config) {
|
|
103
|
+
return new TesseractOcrProvider(config);
|
|
104
|
+
}
|
|
105
|
+
/** Lazily-initialized provider singleton. */
|
|
106
|
+
let _provider = null;
|
|
107
|
+
/**
|
|
108
|
+
* The provider implementation.
|
|
109
|
+
*/
|
|
110
|
+
export const provider = new Proxy({}, {
|
|
111
|
+
get(_, prop, receiver) {
|
|
112
|
+
if (!_provider)
|
|
113
|
+
_provider = createProvider();
|
|
114
|
+
return Reflect.get(_provider, prop, receiver);
|
|
115
|
+
},
|
|
116
|
+
set(_, prop, value) {
|
|
117
|
+
if (!_provider)
|
|
118
|
+
_provider = createProvider();
|
|
119
|
+
return Reflect.set(_provider, prop, value);
|
|
120
|
+
},
|
|
121
|
+
});
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration types for the self-hosted Tesseract OCR provider.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Options for {@link createProvider}. Tesseract runs entirely in your process
|
|
8
|
+
* (a WASM worker thread) — no API key, no egress except the first download of
|
|
9
|
+
* a language's traineddata unless you point `langPath` at a local copy.
|
|
10
|
+
*/
|
|
11
|
+
export interface TesseractOcrConfig {
|
|
12
|
+
/** Default Tesseract language code(s), `+`-joined (e.g. `eng`, `eng+deu`). Default `eng`. */
|
|
13
|
+
language?: string;
|
|
14
|
+
/**
|
|
15
|
+
* Where traineddata files are downloaded from. Defaults to the tessdata CDN
|
|
16
|
+
* the library ships with. Point it at your own mirror or a local directory
|
|
17
|
+
* (`file://…` or a path the worker can read) for offline installs.
|
|
18
|
+
*/
|
|
19
|
+
langPath?: string;
|
|
20
|
+
/** Directory to cache downloaded traineddata in. Default: the OS temp dir. */
|
|
21
|
+
cachePath?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Whether to fetch `.traineddata.gz` (compressed). Default true; set false
|
|
24
|
+
* for a `langPath` that only serves uncompressed files.
|
|
25
|
+
*/
|
|
26
|
+
gzip?: boolean;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,6FAA6F;IAC7F,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,8EAA8E;IAC9E,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB;;;OAGG;IACH,IAAI,CAAC,EAAE,OAAO,CAAA;CACf"}
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@molecule/api-ocr-tesseract",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Self-hosted Tesseract OCR provider for molecule.dev — text extraction from images in your own process, no vendor account, no per-call cost",
|
|
5
|
+
"homepage": "https://www.molecule.dev/packages/api-ocr-tesseract",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"scripts": {
|
|
10
|
+
"build": "tsc",
|
|
11
|
+
"test": "vitest run",
|
|
12
|
+
"test:watch": "vitest"
|
|
13
|
+
},
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"README.md"
|
|
23
|
+
],
|
|
24
|
+
"keywords": [
|
|
25
|
+
"molecule",
|
|
26
|
+
"ocr",
|
|
27
|
+
"tesseract",
|
|
28
|
+
"self-hosted",
|
|
29
|
+
"text-recognition"
|
|
30
|
+
],
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"tesseract.js": "7.0.0"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@molecule/api-ocr": ">=1.0.0"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@molecule/api-ocr": "1.0.0",
|
|
40
|
+
"@types/node": "26.1.2",
|
|
41
|
+
"typescript": "6.0.3",
|
|
42
|
+
"vitest": "4.1.11"
|
|
43
|
+
},
|
|
44
|
+
"repository": {
|
|
45
|
+
"type": "git",
|
|
46
|
+
"url": "https://github.com/molecule-dev/molecule.git",
|
|
47
|
+
"directory": "packages/api/bonds/ocr/tesseract"
|
|
48
|
+
},
|
|
49
|
+
"author": "Molecule Dev, Inc. (https://molecule.dev)"
|
|
50
|
+
}
|