@3sln/emon 0.1.0 → 0.3.0-preview.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/THIRD_PARTY_NOTICES.md +9025 -1313
- package/emon.wasm +0 -0
- package/package.json +7 -3
- package/src/engines.js +216 -0
- package/src/index.d.ts +132 -2
- package/src/index.js +31 -3
- package/src/ocr.js +49 -21
- package/src/packfetch.js +203 -0
- package/src/packs.js +460 -0
- package/src/sources.js +38 -0
- package/src/tesseract.d.ts +4 -3
- package/src/tesseract.js +17 -14
- package/src/wasm.js +92 -6
package/src/sources.js
CHANGED
|
@@ -140,6 +140,44 @@ export async function urlSource(url, { fetch: f = globalThis.fetch.bind(globalTh
|
|
|
140
140
|
* `URL`), a `ReadableStream`, or any `{ size, read }`.
|
|
141
141
|
*/
|
|
142
142
|
export async function toSource(x, opts = {}) {
|
|
143
|
+
if (Array.isArray(x)) {
|
|
144
|
+
const max = Math.min(opts.max ?? 2 ** 31 - 1, 2 ** 31 - 1);
|
|
145
|
+
if (!x.length) throw new TypeError('emon: expected a nonempty list of single-frame images');
|
|
146
|
+
let size = 12 + 4 * x.length;
|
|
147
|
+
if (size > max) throw new EmonError('input-bytes', 'image list exceeds the input-bytes limit');
|
|
148
|
+
const header = new Uint8Array(size);
|
|
149
|
+
header.set(new TextEncoder().encode('EMONIMG1'));
|
|
150
|
+
const lengths = new DataView(header.buffer);
|
|
151
|
+
lengths.setUint32(8, x.length, true);
|
|
152
|
+
const parts = [{ start: 0, source: bytesSource(header) }];
|
|
153
|
+
for (let i = 0; i < x.length; i++) {
|
|
154
|
+
if (Array.isArray(x[i])) throw new TypeError('emon: each member must be a single-frame image');
|
|
155
|
+
const source = await toSource(x[i], { ...opts, max: max - size });
|
|
156
|
+
if (!Number.isSafeInteger(source.size) || source.size < 4) throw new TypeError('emon: invalid image size');
|
|
157
|
+
if (source.size > max - size) throw new EmonError('input-bytes', 'image list exceeds the input-bytes limit');
|
|
158
|
+
lengths.setUint32(12 + 4 * i, source.size, true);
|
|
159
|
+
parts.push({ start: size, source });
|
|
160
|
+
size += source.size;
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
size,
|
|
164
|
+
async read(offset, length) {
|
|
165
|
+
const end = Math.min(size, offset + length);
|
|
166
|
+
const bytes = new Uint8Array(Math.max(0, end - offset));
|
|
167
|
+
let written = 0;
|
|
168
|
+
for (const { start, source } of parts) {
|
|
169
|
+
const from = Math.max(offset, start);
|
|
170
|
+
const to = Math.min(end, start + source.size);
|
|
171
|
+
if (from >= to) continue;
|
|
172
|
+
const chunk = asU8(await source.read(from - start, to - from));
|
|
173
|
+
if (chunk.length !== to - from) throw new SourceChangedError('an image changed while it was being read');
|
|
174
|
+
bytes.set(chunk, written);
|
|
175
|
+
written += chunk.length;
|
|
176
|
+
}
|
|
177
|
+
return bytes;
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
}
|
|
143
181
|
if (x && typeof x === 'object' && typeof x.read === 'function' && typeof x.size === 'number') return x;
|
|
144
182
|
if (x instanceof ArrayBuffer || ArrayBuffer.isView(x)) return bytesSource(x, opts);
|
|
145
183
|
if (typeof Blob !== 'undefined' && x instanceof Blob) return blobSource(x);
|
package/src/tesseract.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Type declarations of `@3sln/emon/tesseract` (P11.4, D542).
|
|
2
|
-
import type {
|
|
2
|
+
import type { OcrAdapter } from './index.js';
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
/** tesseract.js as a registered adapter (D925): `await emon.engines().add(tesseractAdapter({ createWorker }))`. */
|
|
5
|
+
export function tesseractAdapter(options: {
|
|
5
6
|
/** tesseract.js's `createWorker` */
|
|
6
7
|
createWorker: (...args: any[]) => Promise<any>;
|
|
7
8
|
/** the models the engine loads (tesseract.js's names); default `['eng']` */
|
|
@@ -11,4 +12,4 @@ export function tesseractPort(options: {
|
|
|
11
12
|
workerOptions?: object;
|
|
12
13
|
/** workers per language set (default 1) */
|
|
13
14
|
workers?: number;
|
|
14
|
-
}):
|
|
15
|
+
}): OcrAdapter & { name: 'tesseract'; engine: 1; producer: Record<string, string>; close(): Promise<void> };
|
package/src/tesseract.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
// tesseract.js AS emon's
|
|
1
|
+
// tesseract.js AS a REGISTERED ADAPTER of emon's engine registry (DEVLOG P9.3, SPEC 7.3, D211-D214, D925): the browser's OCR engine, fulfilling `ocr` requests through
|
|
2
2
|
// plan/fulfil. `tesseract.js` is not a dependency of the SDK: the embedder imports it and hands over `createWorker`, which keeps
|
|
3
3
|
// the engine's code, its core WebAssembly and its language data (large, and the embedder's to host or cache) out of the library.
|
|
4
4
|
//
|
|
5
5
|
// import { createWorker } from 'tesseract.js';
|
|
6
6
|
// import { Emon } from '@3sln/emon';
|
|
7
|
-
// import {
|
|
7
|
+
// import { tesseractAdapter } from '@3sln/emon/tesseract';
|
|
8
8
|
//
|
|
9
|
-
// const
|
|
10
|
-
// const
|
|
11
|
-
// await
|
|
9
|
+
// const emon = await Emon.load(...);
|
|
10
|
+
// const engines = emon.engines();
|
|
11
|
+
// await engines.add(tesseractAdapter({ createWorker, languages: ['eng'], workerOptions: { langPath: '/tessdata', corePath: '/tesseract-core' } }));
|
|
12
|
+
// const model = await emon.convert(scan, { ports: { ocr: engines.port() } });
|
|
13
|
+
// await engines.close();
|
|
12
14
|
//
|
|
13
15
|
// WHAT IT GIVES AND WHAT IT CANNOT. tesseract.js reports the page as blocks, paragraphs, lines (with their baselines), words and
|
|
14
16
|
// symbols, each with a box and a confidence, and a block's type: that is the answer, in the form `ocr.js` documents. It does not
|
|
@@ -24,7 +26,7 @@ const x10 = (c) => Math.round((c ?? 0) * 10);
|
|
|
24
26
|
|
|
25
27
|
/** tesseract.js's `blocks` of one recognition as the `ocr.js` result (not exported since P11.4, D542: it was a helper for a test, and no test used it). */
|
|
26
28
|
function resultOf(blocks, { wantSymbols, lang, blockType }) {
|
|
27
|
-
const out = {
|
|
29
|
+
const out = { inferred: 8192, blocks: [], lines: [], words: [] };
|
|
28
30
|
let par = -1;
|
|
29
31
|
(blocks || []).forEach((b, bi) => {
|
|
30
32
|
out.blocks.push({ box: box(b.bbox), orient: 0, writingDirection: 0, textlineOrder: 2 });
|
|
@@ -35,7 +37,7 @@ function resultOf(blocks, { wantSymbols, lang, blockType }) {
|
|
|
35
37
|
const bl = l.baseline || {};
|
|
36
38
|
out.lines.push({
|
|
37
39
|
box: box(l.bbox),
|
|
38
|
-
baseline: [bl.x0
|
|
40
|
+
baseline: [bl.x0, bl.y0, bl.x1, bl.y1].every(Number.isFinite) ? [bl.x0, bl.y0, bl.x1, bl.y1] : undefined,
|
|
39
41
|
block: bi,
|
|
40
42
|
paragraph: par,
|
|
41
43
|
type: blockType(b.blocktype),
|
|
@@ -43,7 +45,7 @@ function resultOf(blocks, { wantSymbols, lang, blockType }) {
|
|
|
43
45
|
for (const w of l.words || []) {
|
|
44
46
|
const text = (w.text || '').trim();
|
|
45
47
|
if (!text) continue;
|
|
46
|
-
const word = { box: box(w.bbox), conf: x10(w.confidence), line: li, block: bi, text,
|
|
48
|
+
const word = { box: box(w.bbox), conf: x10(w.confidence), line: li, block: bi, text, lang };
|
|
47
49
|
if (wantSymbols) {
|
|
48
50
|
word.symbols = (w.symbols || []).map((s) => ({ box: box(s.bbox), conf: x10(s.confidence), text: s.text || '', alts: [] }));
|
|
49
51
|
// the symbols must spell the word, as the engine's own do
|
|
@@ -65,9 +67,9 @@ function resultOf(blocks, { wantSymbols, lang, blockType }) {
|
|
|
65
67
|
* @param {number} [o.oem] the engine mode (1: LSTM, the default)
|
|
66
68
|
* @param {object} [o.workerOptions] tesseract.js's `createWorker` options (`langPath`, `corePath`, `workerPath`, `logger`, ...)
|
|
67
69
|
* @param {number} [o.workers] workers per language set, so recognitions of one round run side by side (default 1)
|
|
68
|
-
* @returns
|
|
70
|
+
* @returns an adapter for `emon.engines().add(...)`: `{ name: 'tesseract', engine: 1, needs, producer, read(request), close() }`
|
|
69
71
|
*/
|
|
70
|
-
export function
|
|
72
|
+
export function tesseractAdapter({ createWorker, languages = ['eng'], oem = 1, workerOptions = {}, workers = 1 }) {
|
|
71
73
|
const pools = new Map(); // language key -> [{ promise, busy }]
|
|
72
74
|
const slot = (key) => {
|
|
73
75
|
let pool = pools.get(key);
|
|
@@ -88,7 +90,7 @@ export function tesseractPort({ createWorker, languages = ['eng'], oem = 1, work
|
|
|
88
90
|
}
|
|
89
91
|
return s || pool.reduce((a, b) => (a.busy <= b.busy ? a : b));
|
|
90
92
|
};
|
|
91
|
-
const
|
|
93
|
+
const read = async (req) => {
|
|
92
94
|
// which of the engine's models read the request is kin's (`emon.ocrport`): a language is its model, a script (`Cyrl`) the models that
|
|
93
95
|
// read it, one with no model is dropped, none left is every model (D038, P10.7)
|
|
94
96
|
const langs = req.models(languages).map((i) => languages[i]);
|
|
@@ -105,10 +107,11 @@ export function tesseractPort({ createWorker, languages = ['eng'], oem = 1, work
|
|
|
105
107
|
s.busy -= 1;
|
|
106
108
|
}
|
|
107
109
|
};
|
|
108
|
-
|
|
110
|
+
const close = async () => {
|
|
109
111
|
for (const pool of pools.values()) for (const s of pool) await (await s.promise).terminate();
|
|
110
112
|
pools.clear();
|
|
111
113
|
};
|
|
112
|
-
|
|
113
|
-
|
|
114
|
+
// needs: a recognizer (1); no orientation model (2) is loaded, so a request for OSD is answered without one. The registry routes by engine, so a request for another engine never arrives.
|
|
115
|
+
const producer = { observed: `tesseract.js;oem=${oem};models=${languages.join('+')};core=${workerOptions.corePath ?? 'bundled'}`, engine: 'tesseract.js', 'engine-mode': oem === 1 ? 'default (LSTM)' : String(oem), 'lstm-choice-mode': '2', models: languages.join(' '), host: 'host/js/src/tesseract.js' };
|
|
116
|
+
return { name: 'tesseract', engine: 1, caps: 0, measured: 0, needs: 1, flags: 0, producer, read, close };
|
|
114
117
|
}
|
package/src/wasm.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
// The WASM binding's wrapper (DEVLOG P9.3): the module's C ABI (`host/wasm/src/wasm.rs`) as methods. The module has no imports
|
|
2
|
-
//
|
|
1
|
+
// The WASM binding's wrapper (DEVLOG P9.3): the module's C ABI (`host/wasm/src/wasm.rs`) as methods. The default module has no imports.
|
|
2
|
+
// The optional PP build imports one direct wasm dictionary function; its Engine instance never calls it, while the PP port binds
|
|
3
|
+
// it to Tesseract wasm. The default throwing stub prevents accidental inference on an unlinked instance. No filesystem or network
|
|
4
|
+
// is provided here. Everything here is integers and byte ranges
|
|
3
5
|
// of the module's memory; `memory.buffer` is re-read after every call because a call may grow it.
|
|
4
6
|
|
|
5
7
|
export class Wasm {
|
|
@@ -22,17 +24,17 @@ export class Wasm {
|
|
|
22
24
|
* Instantiate the module from bytes, a compiled module, a `Response` (streamed), a promise of one, or a URL.
|
|
23
25
|
* @param {ArrayBuffer|Uint8Array|WebAssembly.Module|Response|Promise<Response>|string|URL} src
|
|
24
26
|
*/
|
|
25
|
-
static async instantiate(src) {
|
|
27
|
+
static async instantiate(src, imports = { ppocr: { valid_word() { throw new Error('ppocr-lexicon-not-linked'); } } }) {
|
|
26
28
|
if (typeof src === 'string' || src instanceof URL) src = fetch(src);
|
|
27
29
|
src = await src;
|
|
28
|
-
if (src instanceof WebAssembly.Module) return new Wasm(await WebAssembly.instantiate(src,
|
|
30
|
+
if (src instanceof WebAssembly.Module) return new Wasm(await WebAssembly.instantiate(src, imports));
|
|
29
31
|
if (typeof Response !== 'undefined' && src instanceof Response) {
|
|
30
32
|
if (WebAssembly.instantiateStreaming && (src.headers.get('content-type') || '').startsWith('application/wasm')) {
|
|
31
|
-
return new Wasm((await WebAssembly.instantiateStreaming(src,
|
|
33
|
+
return new Wasm((await WebAssembly.instantiateStreaming(src, imports)).instance);
|
|
32
34
|
}
|
|
33
35
|
src = await src.arrayBuffer();
|
|
34
36
|
}
|
|
35
|
-
return new Wasm((await WebAssembly.instantiate(src,
|
|
37
|
+
return new Wasm((await WebAssembly.instantiate(src, imports)).instance);
|
|
36
38
|
}
|
|
37
39
|
|
|
38
40
|
// THE OCR POLICY IS KIN'S (`emon.ocrport`, P10.7, D396): these ask the module what an `ocr` request means.
|
|
@@ -41,6 +43,17 @@ export class Wasm {
|
|
|
41
43
|
return this.withBytes(new Uint8Array(Int32Array.from(rec).buffer), (p) => this.x.emon_ocr_lang_first(p, rec.length));
|
|
42
44
|
}
|
|
43
45
|
|
|
46
|
+
/** Requested engine trailer, through kin, in every build. */
|
|
47
|
+
ocrIdentityAt(rec) {
|
|
48
|
+
return this.withBytes(new Uint8Array(Int32Array.from(rec).buffer), (p, n) => this.x.emon_ocr_identity_at(p, rec.length));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
ocrObserved(identity) {
|
|
52
|
+
const cps = Int32Array.from(Array.from(identity, ch => ch.codePointAt(0)));
|
|
53
|
+
const hash = this.withBytes(new Uint8Array(cps.buffer), p => this.x.emon_ocr_observed(p, cps.length));
|
|
54
|
+
return [Number(BigInt.asIntN(32, hash >> 32n)), Number(BigInt.asIntN(32, hash))];
|
|
55
|
+
}
|
|
56
|
+
|
|
44
57
|
/** Which of the `installed` model names read the request record: indices into `installed` (all of them when it names none). */
|
|
45
58
|
ocrModels(rec, installed) {
|
|
46
59
|
const names = [];
|
|
@@ -56,6 +69,79 @@ export class Wasm {
|
|
|
56
69
|
return n < 0 ? [] : Array.from(out);
|
|
57
70
|
}
|
|
58
71
|
|
|
72
|
+
// THE ADAPTER REGISTRY'S RULES ARE KIN'S (`emon.adapters`, D925): `Engines` asks the module.
|
|
73
|
+
/** 0 when an adapter of that shape may register (kin's `ad-register-check`), else the reason's code. */
|
|
74
|
+
adapterCheck(abi, oen, caps, measured, needs, flags) {
|
|
75
|
+
return this.x.emon_adapter_check(abi, oen, caps, measured, needs, flags);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The reason's name for a refusal code (`adapter-engine-unknown`, ...). */
|
|
79
|
+
adapterReason(code) {
|
|
80
|
+
this.x.emon_adapter_reason(code);
|
|
81
|
+
const t = this.outText();
|
|
82
|
+
this.outFree();
|
|
83
|
+
return t;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The index, among the OIL engines `oens` (in registration order), of the adapter a request of the OIL engine `oen` goes to, or -1 (kin's `ad-route`). */
|
|
87
|
+
adapterRoute(oen, oens) {
|
|
88
|
+
return this.withBytes(new Uint8Array(Int32Array.from(oens).buffer), (p) => this.x.emon_adapter_route(oen, p, oens.length));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// THE PACK RULES ARE KIN'S TOO (`emon.engines`, `emon.adapters`, P13.16): the catalogue and what to do about a pack are asked of the module.
|
|
92
|
+
/** The pack catalogue (`pack_catalogue` of the module): the platform class, kin's codes and every pack with its files' SHA-256. */
|
|
93
|
+
packCatalogue() {
|
|
94
|
+
this.x.emon_pack_catalogue();
|
|
95
|
+
const t = this.outText();
|
|
96
|
+
this.outFree();
|
|
97
|
+
return JSON.parse(t);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** `ad-pack-action` (and `ad-asks-hook`): `{ action, asks }` for a pack that is `present`, under `mode`, `offline`, a hook or none, and what the hook decided (0: nothing). */
|
|
101
|
+
packAction(present, mode, offline, hook, decision) {
|
|
102
|
+
const r = this.x.emon_pack_action(present ? 1 : 0, mode, offline ? 1 : 0, hook ? 1 : 0, decision | 0);
|
|
103
|
+
return { action: r & 255, asks: (r >> 8) === 1 };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The kin engine an OIL engine answers as, or -1. */
|
|
107
|
+
packOenEng(oen) {
|
|
108
|
+
return this.x.emon_pack_oen_eng(oen);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
#i32s(a) {
|
|
112
|
+
return new Uint8Array(Int32Array.from(a).buffer);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
#json(n) {
|
|
116
|
+
const t = this.outText();
|
|
117
|
+
this.outFree();
|
|
118
|
+
return n < 0 ? Object.assign(new Error(t), { packError: true }) : JSON.parse(t);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** `pk-resolve`: rows `[state, engine, pack, lang]` for the kin engines, packed languages and held pack codes; throws kin's explanation. */
|
|
122
|
+
packResolve(osd, langs, engines, installed) {
|
|
123
|
+
const n = this.withBytes(this.#i32s(langs), (lp) => this.withBytes(this.#i32s(engines), (ep) => this.withBytes(this.#i32s(installed), (ip) => this.x.emon_pack_resolve(osd ? 1 : 0, lp, langs.length, ep, engines.length, ip, installed.length))));
|
|
124
|
+
const r = this.#json(n);
|
|
125
|
+
if (r.error !== undefined) throw new Error(r.error);
|
|
126
|
+
return r.rows;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** `engines()` as the module's JSON (the shape of the C ABI's `emon_engines_describe`). */
|
|
130
|
+
packDescribe(oens, renderer, installed, mode, offline, store) {
|
|
131
|
+
const sb = new TextEncoder().encode(store);
|
|
132
|
+
const n = this.withBytes(this.#i32s(oens), (op) => this.withBytes(this.#i32s(installed), (ip) => this.withBytes(sb, (sp) => this.x.emon_pack_describe(op, oens.length, renderer ? 1 : 0, ip, installed.length, mode, offline ? 1 : 0, sp, sb.length))));
|
|
133
|
+
return this.#json(n);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** `prepare(options)` over the option lines, as the module's JSON (the shape of the C ABI's `emon_prepare`); throws the options' error. */
|
|
137
|
+
packPrepare(optionLines, installed, mode, offline) {
|
|
138
|
+
const tb = new TextEncoder().encode(optionLines);
|
|
139
|
+
const n = this.withBytes(tb, (tp) => this.withBytes(this.#i32s(installed), (ip) => this.x.emon_pack_prepare(tp, tb.length, ip, installed.length, mode, offline ? 1 : 0)));
|
|
140
|
+
const r = this.#json(n);
|
|
141
|
+
if (r instanceof Error) throw r;
|
|
142
|
+
return r;
|
|
143
|
+
}
|
|
144
|
+
|
|
59
145
|
/** The language a model read a word in, as a request packs it. */
|
|
60
146
|
ocrWordLang(model) {
|
|
61
147
|
const cps = Int32Array.from(Array.from(model, (c) => c.codePointAt(0)));
|