@3sln/emon 0.0.0-stage → 0.3.0-preview.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +113 -2
- package/THIRD_PARTY_NOTICES.md +13158 -0
- package/emon.wasm +0 -0
- package/package.json +36 -4
- package/src/index.d.ts +198 -0
- package/src/index.js +590 -0
- package/src/ocr.js +134 -0
- package/src/pdfium.d.ts +12 -0
- package/src/pdfium.js +287 -0
- package/src/render.js +55 -0
- package/src/sources.js +149 -0
- package/src/tesseract.d.ts +14 -0
- package/src/tesseract.js +115 -0
- package/src/wasm.js +124 -0
package/src/tesseract.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// tesseract.js AS emon's `ocr` PORT (DEVLOG P9.3, SPEC 7.3, D211-D214): the browser's OCR engine, fulfilling `ocr` requests through
|
|
2
|
+
// plan/fulfil. `tesseract.js` is not a dependency of the SDK: the embedder imports it and hands over `createWorker`, which keeps
|
|
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
|
+
//
|
|
5
|
+
// import { createWorker } from 'tesseract.js';
|
|
6
|
+
// import { Emon } from '@3sln/emon';
|
|
7
|
+
// import { tesseractPort } from '@3sln/emon/tesseract';
|
|
8
|
+
//
|
|
9
|
+
// const ocr = tesseractPort({ createWorker, languages: ['eng'], workerOptions: { langPath: '/tessdata', corePath: '/tesseract-core' } });
|
|
10
|
+
// const model = await emon.convert(scan, { ports: { ocr } });
|
|
11
|
+
// await ocr.terminate();
|
|
12
|
+
//
|
|
13
|
+
// WHAT IT GIVES AND WHAT IT CANNOT. tesseract.js reports the page as blocks, paragraphs, lines (with their baselines), words and
|
|
14
|
+
// 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
|
|
15
|
+
// report what the native C API does (D213): a block's orientation and writing direction (answered as page up, left to right, top
|
|
16
|
+
// to bottom: the engine is not run with orientation detection here, so a request for OSD, bit 2 of the flags, is answered without
|
|
17
|
+
// one), a word's language, dictionary and numeric flags, font attributes and point size (answered as the request's first language,
|
|
18
|
+
// not in the dictionary, not numeric, no style, size unknown), a symbol's alternatives (its `choices` are not in the JSON), and
|
|
19
|
+
// the engine's thresholded image (the answer says it has none). A line's x-height, ascenders and descenders are answered as -1:
|
|
20
|
+
// kin then measures them from the symbols' boxes, as it does for the native engine (D213). None of that is guessed.
|
|
21
|
+
|
|
22
|
+
const box = (b) => [b.x0, b.y0, b.x1 - b.x0, b.y1 - b.y0];
|
|
23
|
+
const x10 = (c) => Math.round((c ?? 0) * 10);
|
|
24
|
+
|
|
25
|
+
/** 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
|
+
function resultOf(blocks, { wantSymbols, lang, blockType }) {
|
|
27
|
+
const out = { inferred: 8192, blocks: [], lines: [], words: [] };
|
|
28
|
+
let par = -1;
|
|
29
|
+
(blocks || []).forEach((b, bi) => {
|
|
30
|
+
out.blocks.push({ box: box(b.bbox), orient: 0, writingDirection: 0, textlineOrder: 2 });
|
|
31
|
+
for (const p of b.paragraphs || []) {
|
|
32
|
+
par += 1;
|
|
33
|
+
for (const l of p.lines || []) {
|
|
34
|
+
const li = out.lines.length;
|
|
35
|
+
const bl = l.baseline || {};
|
|
36
|
+
out.lines.push({
|
|
37
|
+
box: box(l.bbox),
|
|
38
|
+
baseline: [bl.x0, bl.y0, bl.x1, bl.y1].every(Number.isFinite) ? [bl.x0, bl.y0, bl.x1, bl.y1] : undefined,
|
|
39
|
+
block: bi,
|
|
40
|
+
paragraph: par,
|
|
41
|
+
type: blockType(b.blocktype),
|
|
42
|
+
});
|
|
43
|
+
for (const w of l.words || []) {
|
|
44
|
+
const text = (w.text || '').trim();
|
|
45
|
+
if (!text) continue;
|
|
46
|
+
const word = { box: box(w.bbox), conf: x10(w.confidence), line: li, block: bi, text, lang };
|
|
47
|
+
if (wantSymbols) {
|
|
48
|
+
word.symbols = (w.symbols || []).map((s) => ({ box: box(s.bbox), conf: x10(s.confidence), text: s.text || '', alts: [] }));
|
|
49
|
+
// the symbols must spell the word, as the engine's own do
|
|
50
|
+
if (word.symbols.map((s) => s.text).join('') !== text) word.symbols = [];
|
|
51
|
+
}
|
|
52
|
+
out.words.push(word);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* @param {object} o
|
|
62
|
+
* @param {Function} o.createWorker tesseract.js's `createWorker`
|
|
63
|
+
* @param {string[]} [o.languages] the models the engine loads (tesseract.js's names: `eng`, `deu`, `chi_sim`); a request that names
|
|
64
|
+
* languages is served by those of them it names, one that names none by all of them (D038). Default `['eng']`.
|
|
65
|
+
* @param {number} [o.oem] the engine mode (1: LSTM, the default)
|
|
66
|
+
* @param {object} [o.workerOptions] tesseract.js's `createWorker` options (`langPath`, `corePath`, `workerPath`, `logger`, ...)
|
|
67
|
+
* @param {number} [o.workers] workers per language set, so recognitions of one round run side by side (default 1)
|
|
68
|
+
* @returns {((request: object) => Promise<object>) & { terminate(): Promise<void>, producer: object }}
|
|
69
|
+
*/
|
|
70
|
+
export function tesseractPort({ createWorker, languages = ['eng'], oem = 1, workerOptions = {}, workers = 1 }) {
|
|
71
|
+
const pools = new Map(); // language key -> [{ promise, busy }]
|
|
72
|
+
const slot = (key) => {
|
|
73
|
+
let pool = pools.get(key);
|
|
74
|
+
if (!pool) pools.set(key, (pool = []));
|
|
75
|
+
// an idle worker, a new one while the pool has room, else the least busy
|
|
76
|
+
let s = pool.find((x) => x.busy === 0);
|
|
77
|
+
if (!s && pool.length < workers) {
|
|
78
|
+
s = {
|
|
79
|
+
busy: 0,
|
|
80
|
+
promise: (async () => {
|
|
81
|
+
const w = await createWorker(key, oem, workerOptions);
|
|
82
|
+
// the final candidates of the beam search, not one per timestep: the native adapter's setting (D213)
|
|
83
|
+
await w.setParameters({ lstm_choice_mode: '2' });
|
|
84
|
+
return w;
|
|
85
|
+
})(),
|
|
86
|
+
};
|
|
87
|
+
pool.push(s);
|
|
88
|
+
}
|
|
89
|
+
return s || pool.reduce((a, b) => (a.busy <= b.busy ? a : b));
|
|
90
|
+
};
|
|
91
|
+
const port = async (req) => {
|
|
92
|
+
if (req.engine !== undefined && req.engine !== 1) return null;
|
|
93
|
+
// 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
|
|
94
|
+
// read it, one with no model is dropped, none left is every model (D038, P10.7)
|
|
95
|
+
const langs = req.models(languages).map((i) => languages[i]);
|
|
96
|
+
if (!langs.length) return null;
|
|
97
|
+
const s = slot(langs.join('+'));
|
|
98
|
+
s.busy += 1;
|
|
99
|
+
try {
|
|
100
|
+
const w = await s.promise;
|
|
101
|
+
await w.setParameters({ tessedit_pageseg_mode: String(req.psm), user_defined_dpi: req.dpi > 0 ? String(req.dpi) : '' });
|
|
102
|
+
const opts = req.rect ? { rectangle: { left: req.rect.x, top: req.rect.y, width: req.rect.w, height: req.rect.h } } : {};
|
|
103
|
+
const { data } = await w.recognize(req.bitmap(), opts, { text: false, blocks: true });
|
|
104
|
+
return resultOf(data.blocks, { wantSymbols: req.symbols, lang: req.wordLang(langs[0]), blockType: req.blockType });
|
|
105
|
+
} finally {
|
|
106
|
+
s.busy -= 1;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
port.terminate = async () => {
|
|
110
|
+
for (const pool of pools.values()) for (const s of pool) await (await s.promise).terminate();
|
|
111
|
+
pools.clear();
|
|
112
|
+
};
|
|
113
|
+
port.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' };
|
|
114
|
+
return port;
|
|
115
|
+
}
|
package/src/wasm.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
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
|
|
5
|
+
// of the module's memory; `memory.buffer` is re-read after every call because a call may grow it.
|
|
6
|
+
|
|
7
|
+
export class Wasm {
|
|
8
|
+
/** @param {WebAssembly.Instance} instance */
|
|
9
|
+
constructor(instance) {
|
|
10
|
+
this.x = instance.exports;
|
|
11
|
+
this.kind = { render: this.x.emon_const(0), decode: this.x.emon_const(1), ocr: this.x.emon_const(2), bytes: this.x.emon_const(3), crop: this.x.emon_const(4), decodeImg: this.x.emon_const(5) };
|
|
12
|
+
this.status = { ok: this.x.emon_const(10), failed: this.x.emon_const(11), unsupported: this.x.emon_const(12), limit: this.x.emon_const(13) };
|
|
13
|
+
this.ocrWord = { dict: this.x.emon_const(14), numeric: this.x.emon_const(15) };
|
|
14
|
+
// the argument indices of a `render` / `crop` request (kin's `rd-*`; the record is `[len kind id arg...]`): read a request by these, never by a literal offset
|
|
15
|
+
this.rd = { input: this.x.emon_const(16), page: this.x.emon_const(17), dpi: this.x.emon_const(18), layer: this.x.emon_const(19), x: this.x.emon_const(20), y: this.x.emon_const(21), w: this.x.emon_const(22), h: this.x.emon_const(23) };
|
|
16
|
+
// kin's table of limits, by its kind: `emon_const(100 + K)` is the default of limit K (`input-bytes` is 0), so no default is typed here
|
|
17
|
+
this.inputBytes = this.x.emon_const(100);
|
|
18
|
+
// the kind (the row of kin's table of limits, `kin/limits.kin`) of `pixels`, the bound a renderer's bitmap keeps: `emon_limit(h, pixelsKind)` is the
|
|
19
|
+
// conversion's own (the default or its `limit.pixels`). A kind is a row index, not a default; `bb embedders` holds this to the table.
|
|
20
|
+
this.pixelsKind = 9;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Instantiate the module from bytes, a compiled module, a `Response` (streamed), a promise of one, or a URL.
|
|
25
|
+
* @param {ArrayBuffer|Uint8Array|WebAssembly.Module|Response|Promise<Response>|string|URL} src
|
|
26
|
+
*/
|
|
27
|
+
static async instantiate(src, imports = { ppocr: { valid_word() { throw new Error('ppocr-lexicon-not-linked'); } } }) {
|
|
28
|
+
if (typeof src === 'string' || src instanceof URL) src = fetch(src);
|
|
29
|
+
src = await src;
|
|
30
|
+
if (src instanceof WebAssembly.Module) return new Wasm(await WebAssembly.instantiate(src, imports));
|
|
31
|
+
if (typeof Response !== 'undefined' && src instanceof Response) {
|
|
32
|
+
if (WebAssembly.instantiateStreaming && (src.headers.get('content-type') || '').startsWith('application/wasm')) {
|
|
33
|
+
return new Wasm((await WebAssembly.instantiateStreaming(src, imports)).instance);
|
|
34
|
+
}
|
|
35
|
+
src = await src.arrayBuffer();
|
|
36
|
+
}
|
|
37
|
+
return new Wasm((await WebAssembly.instantiate(src, imports)).instance);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// THE OCR POLICY IS KIN'S (`emon.ocrport`, P10.7, D396): these ask the module what an `ocr` request means.
|
|
41
|
+
/** The argument index of the request record's first language. */
|
|
42
|
+
ocrLangFirst(rec) {
|
|
43
|
+
return this.withBytes(new Uint8Array(Int32Array.from(rec).buffer), (p) => this.x.emon_ocr_lang_first(p, rec.length));
|
|
44
|
+
}
|
|
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
|
+
|
|
57
|
+
/** Which of the `installed` model names read the request record: indices into `installed` (all of them when it names none). */
|
|
58
|
+
ocrModels(rec, installed) {
|
|
59
|
+
const names = [];
|
|
60
|
+
installed.forEach((s, i) => {
|
|
61
|
+
if (i) names.push(0);
|
|
62
|
+
for (const ch of s) names.push(ch.codePointAt(0));
|
|
63
|
+
});
|
|
64
|
+
const n = this.withBytes(new Uint8Array(Int32Array.from(rec).buffer), (p) =>
|
|
65
|
+
this.withBytes(new Uint8Array(Int32Array.from(names).buffer), (ip) => this.x.emon_ocr_models(p, rec.length, ip, names.length)),
|
|
66
|
+
);
|
|
67
|
+
const out = this.outI32();
|
|
68
|
+
this.outFree();
|
|
69
|
+
return n < 0 ? [] : Array.from(out);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The language a model read a word in, as a request packs it. */
|
|
73
|
+
ocrWordLang(model) {
|
|
74
|
+
const cps = Int32Array.from(Array.from(model, (c) => c.codePointAt(0)));
|
|
75
|
+
return this.withBytes(new Uint8Array(cps.buffer), (p) => this.x.emon_ocr_word_lang(p, cps.length));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A line's type (0 text, 1 table, 2 image, 3 rule, 4 other) from Tesseract's PolyBlockType. */
|
|
79
|
+
ocrBlockType(poly) {
|
|
80
|
+
return this.x.emon_ocr_block_type(poly | 0);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
get mem() {
|
|
84
|
+
return new Uint8Array(this.x.memory.buffer);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Copy `u8` into the module's memory and run `f(ptr, len)`; the copy is freed after. */
|
|
88
|
+
withBytes(u8, f) {
|
|
89
|
+
const p = this.x.emon_alloc(u8.length);
|
|
90
|
+
try {
|
|
91
|
+
this.mem.set(u8, p);
|
|
92
|
+
return f(p, u8.length);
|
|
93
|
+
} finally {
|
|
94
|
+
this.x.emon_free(p, u8.length);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
withText(s, f) {
|
|
99
|
+
return this.withBytes(new TextEncoder().encode(s), f);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The shared output buffer, as a view of the module's memory (valid until the next call) */
|
|
103
|
+
outView() {
|
|
104
|
+
return new Uint8Array(this.x.memory.buffer, this.x.emon_out_ptr(), this.x.emon_out_len());
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The output as bytes in the JS heap (a copy). */
|
|
108
|
+
outBytes() {
|
|
109
|
+
return this.outView().slice();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
outText() {
|
|
113
|
+
return new TextDecoder().decode(this.outView());
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
outI32() {
|
|
117
|
+
const v = this.outView();
|
|
118
|
+
return new Int32Array(v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
outFree() {
|
|
122
|
+
this.x.emon_out_free();
|
|
123
|
+
}
|
|
124
|
+
}
|