@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/emon.wasm
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@3sln/emon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0-preview.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "emon's JavaScript SDK: PDFs and images to semantic HTML in the browser, over the WASM binding (DEVLOG P9.3). The library has no dependencies; the devDependencies are the browser test harness and the tesseract.js engine the OCR adapter drives.",
|
|
6
6
|
"keywords": ["pdf", "html", "semantic-html", "ocr", "document-conversion", "scraping", "wasm", "webassembly", "tables"],
|
|
@@ -15,21 +15,25 @@
|
|
|
15
15
|
".": "./src/index.js",
|
|
16
16
|
"./tesseract": "./src/tesseract.js",
|
|
17
17
|
"./pdfium": "./src/pdfium.js",
|
|
18
|
+
"./node-pack-cache": { "types": "./node/pack-cache.d.ts", "browser": "./node/unavailable.js", "default": "./node/pack-cache.js" },
|
|
19
|
+
"./deno-pack-cache": { "types": "./node/pack-cache-deno.d.ts", "browser": "./node/unavailable.js", "default": "./node/pack-cache-deno.js" },
|
|
18
20
|
"./emon.wasm": "./emon.wasm",
|
|
19
21
|
"./package.json": "./package.json"
|
|
20
22
|
},
|
|
21
|
-
"files": ["src", "emon.wasm", "LICENSE", "THIRD_PARTY_NOTICES.md", "README.md"],
|
|
23
|
+
"files": ["src", "node", "emon.wasm", "LICENSE", "THIRD_PARTY_NOTICES.md", "README.md"],
|
|
22
24
|
"sideEffects": false,
|
|
23
25
|
"publishConfig": { "access": "public" },
|
|
24
26
|
"engines": { "node": ">=22" },
|
|
25
27
|
"peerDependencies": {
|
|
26
|
-
"@3sln/pdfium-wasm": "^0.
|
|
28
|
+
"@3sln/pdfium-wasm": "^0.3.0-preview.2"
|
|
27
29
|
},
|
|
28
30
|
"peerDependenciesMeta": {
|
|
29
31
|
"@3sln/pdfium-wasm": { "optional": true }
|
|
30
32
|
},
|
|
31
33
|
"devDependencies": {
|
|
32
34
|
"puppeteer-core": "25.12.0",
|
|
35
|
+
"onnxruntime-web": "1.22.0",
|
|
36
|
+
"wabt": "1.0.39",
|
|
33
37
|
"tesseract.js": "7.0.0",
|
|
34
38
|
"@tesseract.js-data/eng": "1.0.0"
|
|
35
39
|
}
|
package/src/engines.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// THE ENGINE REGISTRY, JavaScript host (DEVLOG D925, K3; the twin of `host/go/engines.go` and `host/rust/src/adapter.rs`: read those for the reasoning).
|
|
2
|
+
//
|
|
3
|
+
// An OCR engine is an ADAPTER that is registered, never wired. `emon.engines()` is an empty registry bound to the loaded module; `engines.add(adapter)` registers one
|
|
4
|
+
// (`tesseractAdapter` of `@3sln/emon/tesseract`, `ppocrEngine` of `@3sln/emon/ppocr`, or the embedder's own), and `engines.port()` is the `ports.ocr` of a conversion: the registry
|
|
5
|
+
// routes each request to the adapter registered for the engine it names. Kin decides every rule and this file asks the module for them: what an adapter may declare
|
|
6
|
+
// (`ad-register-check`, against the engine table) and which adapter a request goes to (`ad-route`: the first registered for the OIL engine the request names). An engine nobody
|
|
7
|
+
// registered answers `unsupported`; a rejection from an adapter answers `failed`, and either way the page is unread, never blank.
|
|
8
|
+
//
|
|
9
|
+
// An adapter is an object:
|
|
10
|
+
//
|
|
11
|
+
// { name: 'tesseract', // the engine's name in kin's table, or the embedder's own
|
|
12
|
+
// engine: 1, // the OIL engine it answers as: 1 tesseract, 2 ppocr, 3 apple-vision, 4 mlkit-text, 5 windows-media-ocr
|
|
13
|
+
// caps, measured, needs, flags, // optional (0): what it declares, what it measures, the pack kinds it reads with (1 recognizer, 2 osd, 4 detector, 8 classifier), its flags
|
|
14
|
+
// producer: { engine: '...' }, // optional: what the transcript says produced it
|
|
15
|
+
// read(request, { signal, packs }) { ... }, // `ocr.js`'s port form: a result, `null` (unsupported) or a rejection (failed)
|
|
16
|
+
// close() { ... } } // optional
|
|
17
|
+
//
|
|
18
|
+
// A result here is `ocr.js`'s form, which the module's own builders turn into the OIL record (so its layout is held by kin, not by this file); the canonical answers of the
|
|
19
|
+
// Rust-built PP-OCR module come back through `canonicalOcr` and are checked by the module. Every adapter here answers with a Promise, so `read` is async by nature; the flag `1`
|
|
20
|
+
// (async) says that it may take a while, and `2` (remote: the pixels leave the device; app code, usually a `fetch`, this library does none) is refused unless `allowRemote(true)` came
|
|
21
|
+
// first (D935). An adapter that says `1` or `2` is held to `setTimeout(ms)` (kin's `ocr.timeout-ms`, default 60 s) and `cancel()`: its second argument holds `signal`, an `AbortSignal`
|
|
22
|
+
// that aborts at the timeout or the cancel (pass it to `fetch`), the request is left unread (`failed timeout`, `failed cancelled` noted) and the adapter's late answer is dropped. Adapters in this host are in-process values: there are no adapter libraries to load, so there is no `defaults()`; a page that registers
|
|
23
|
+
// no Tesseract adapter has none (D920).
|
|
24
|
+
|
|
25
|
+
import { EmonError } from './sources.js';
|
|
26
|
+
import { Packs } from './packs.js';
|
|
27
|
+
import { httpPackFetcher } from './packfetch.js';
|
|
28
|
+
|
|
29
|
+
const ASYNC = 1;
|
|
30
|
+
const REMOTE = 2;
|
|
31
|
+
const DEFAULT_TIMEOUT_MS = 60000;
|
|
32
|
+
|
|
33
|
+
export class Engines {
|
|
34
|
+
#w;
|
|
35
|
+
#entries = [];
|
|
36
|
+
#allowRemote = false;
|
|
37
|
+
#notes = [];
|
|
38
|
+
#timeoutMs = DEFAULT_TIMEOUT_MS;
|
|
39
|
+
#flights = new Set();
|
|
40
|
+
#optionLines;
|
|
41
|
+
/** The packs (D896, P13.16): the mode, the app's hook, download and events, `ensure`. See `packs.js`. */
|
|
42
|
+
packs;
|
|
43
|
+
|
|
44
|
+
/** @param w the loaded module (`emon.w`): use `emon.engines()`. */
|
|
45
|
+
constructor(w, optionLines = () => '') {
|
|
46
|
+
this.#w = w;
|
|
47
|
+
this.#optionLines = optionLines;
|
|
48
|
+
this.packs = new Packs(w, (line) => this.#notes.push(line));
|
|
49
|
+
// D933: the turnkey downloads with the platform's `fetch` unless the app sets a fetcher of its own (`packs.setFetcher(fn)`; `null` for none). The mode is still `never` until the app says otherwise.
|
|
50
|
+
this.packs.setFetcher(httpPackFetcher(this.packs, { note: (l) => this.#notes.push(l) }));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** D933: whether the engine (kin's name: `tesseract`, `ppocr`) can read now: registered, and its packs here (its state is `built-in` or `installed`). The signal behind an "OCR ready" indicator. */
|
|
54
|
+
engineReady(name, { renderer = false } = {}) {
|
|
55
|
+
const e = this.state({ renderer }).engines.find((x) => x.name === name);
|
|
56
|
+
return !!e && (e.state === 'built-in' || e.state === 'installed');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** D896's `engines()`: every engine of kin's table that runs here, with its state (`built-in`, `installed`, `downloadable` or `unavailable`) and why, as the C ABI's `emon_engines_describe` JSON
|
|
60
|
+
* (`{ platform, mode, offline, store, engines: [{ name, kind, impl, state, registered, calibrated, caps, oen, role, needs, download_bytes, reason }] }`). `renderer`: say a renderer port is in use. */
|
|
61
|
+
state({ renderer = false } = {}) {
|
|
62
|
+
const p = this.packs;
|
|
63
|
+
const cat = p.catalogue.pfetch;
|
|
64
|
+
return this.#w.packDescribe(this.#entries.map((e) => e.engine | 0), renderer, p.installed(), cat[p.mode], p.offline, 'memory');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** D896's `prepare(options)`: the packs a conversion with these options (`ocr`, `ocrEngine`, `locale`) needs and which are missing, as the C ABI's `emon_prepare` JSON
|
|
68
|
+
* (`{ verdict, mode, offline, engines, languages, osd, packs, unsupported, missing, missing_bytes, conditional, conditional_bytes }`). */
|
|
69
|
+
prepare(options = {}) {
|
|
70
|
+
const p = this.packs;
|
|
71
|
+
return this.#w.packPrepare(this.#optionLines(options), p.installed(), p.catalogue.pfetch[p.mode], p.offline);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The packs a request needs, made present or refused (D896), for an adapter that reads its models from them (`adapter.packs: true`): `{ ok: adapter }`, `{ ok: other }` (the app's substitute)
|
|
75
|
+
// or `{ unread: reason }`. An adapter without `packs: true` brings its own models (tesseract.js's `langPath`, PP-OCR's URLs) and no pack is asked for.
|
|
76
|
+
async #ensure(adapter, req) {
|
|
77
|
+
if (!adapter.packs || !(adapter.needs | 0)) return { ok: adapter };
|
|
78
|
+
const w = this.#w;
|
|
79
|
+
const eng = w.packOenEng(adapter.engine | 0);
|
|
80
|
+
if (eng < 0) return { ok: adapter };
|
|
81
|
+
const packs = this.packs;
|
|
82
|
+
const langs = adapter.engine === 1 ? (req.langs ?? []).filter((l) => /^[a-z]{3}$/.test(l)).map((l) => ((l.charCodeAt(0) << 24) | (l.charCodeAt(1) << 16) | (l.charCodeAt(2) << 8)) | 0) : [];
|
|
83
|
+
const osd = !!req.osd && ((adapter.needs | 0) & 2) !== 0;
|
|
84
|
+
let rows;
|
|
85
|
+
try {
|
|
86
|
+
rows = w.packResolve(osd, langs, [eng], packs.installed());
|
|
87
|
+
} catch (e) {
|
|
88
|
+
return { unread: `engine-unavailable: ${e.message}` };
|
|
89
|
+
}
|
|
90
|
+
const c = packs.catalogue;
|
|
91
|
+
const unreadable = rows.filter((r) => r[0] === c.pstate.unsupported);
|
|
92
|
+
if (langs.length && unreadable.length >= langs.length) return { unread: `lang-unavailable:${req.langs[0]}` };
|
|
93
|
+
const engineName = adapter.name ?? 'adapter';
|
|
94
|
+
const kindOf = (code) => packs.catalogue.packs.find((x) => x.code === code)?.kind;
|
|
95
|
+
for (const r of rows.filter((x) => x[0] === c.pstate.missing)) {
|
|
96
|
+
const got = await packs.need(r[2], 'conversion', engineName);
|
|
97
|
+
if (got.ready) continue;
|
|
98
|
+
// orientation detection degrades to kin's own policy without its model; it never leaves the page unread
|
|
99
|
+
if (got.unread !== undefined && kindOf(r[2]) === 'osd') continue;
|
|
100
|
+
if (got.unread !== undefined) return { unread: got.unread };
|
|
101
|
+
// another engine would answer under its own name: kin's plan chose this engine, so the request stays unread
|
|
102
|
+
const named = this.#entries.find((e) => (e.name ?? 'adapter') === got.substitute);
|
|
103
|
+
if (named && named.engine !== adapter.engine) return { unread: `pack-substitute-differs:${got.substitute}` };
|
|
104
|
+
const other = this.#entries.find((e) => e !== adapter && e.packs && e.engine === adapter.engine && (!named || e === named));
|
|
105
|
+
return other ? { ok: other } : { unread: `pack-substitute-unavailable:${got.substitute}` };
|
|
106
|
+
}
|
|
107
|
+
return { ok: adapter };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** How long a request waits for an async or remote adapter (kin's `ocr.timeout-ms`; default 60 s; `0` restores it). A request that ran out of time is unread, never blank. */
|
|
111
|
+
setTimeout(ms) {
|
|
112
|
+
this.#timeoutMs = ms > 0 ? ms : DEFAULT_TIMEOUT_MS;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Ends every request now waiting for an async or remote adapter: each is unread (`failed cancelled`) and its `signal` aborts. Later requests are not affected. */
|
|
116
|
+
cancel() {
|
|
117
|
+
for (const abort of [...this.#flights]) abort('cancelled');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// One read of an adapter that may take a while: its `signal` aborts at the timeout or a cancel, and the request stops waiting then.
|
|
121
|
+
async #guarded(adapter, req, context) {
|
|
122
|
+
const ac = new AbortController();
|
|
123
|
+
let abort;
|
|
124
|
+
const gone = new Promise((_, reject) => {
|
|
125
|
+
abort = (why) => {
|
|
126
|
+
ac.abort(new Error(why));
|
|
127
|
+
reject(new Error(why));
|
|
128
|
+
};
|
|
129
|
+
});
|
|
130
|
+
gone.catch(() => {});
|
|
131
|
+
this.#flights.add(abort);
|
|
132
|
+
const timer = setTimeout(() => abort('timeout'), this.#timeoutMs);
|
|
133
|
+
try {
|
|
134
|
+
const reading = Promise.resolve(adapter.read(req, { ...context, signal: ac.signal }));
|
|
135
|
+
reading.catch(() => {}); // a late rejection, after the request gave up, is nobody's
|
|
136
|
+
return await Promise.race([reading, gone]);
|
|
137
|
+
} finally {
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
this.#flights.delete(abort);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Lets adapters that send the pixels off the device register (default no: documents may hold personal data). Call it before registering them. */
|
|
144
|
+
allowRemote(allow) {
|
|
145
|
+
this.#allowRemote = !!allow;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Registers an adapter, held to kin's engine table; it is closed when refused, and the error's message is the refusal's name and sentence. */
|
|
149
|
+
async add(adapter) {
|
|
150
|
+
const { name = 'adapter', engine, caps = 0, measured = 0, needs = 0, flags = 0 } = adapter;
|
|
151
|
+
const code = this.#w.adapterCheck(1, engine | 0, caps | 0, measured | 0, needs | 0, flags | 0);
|
|
152
|
+
const refuse = async (reason, sentence) => {
|
|
153
|
+
try { await adapter.close?.(); } catch { /* the adapter is refused whatever it says */ }
|
|
154
|
+
throw new EmonError('usage', `${reason}: ${name}${sentence ? ` ${sentence}` : ''} (engine ${engine}, caps ${caps}, needs ${needs}, flags ${flags})`);
|
|
155
|
+
};
|
|
156
|
+
if (typeof adapter.read !== 'function') await refuse('adapter-abi-unsupported', 'has no `read`');
|
|
157
|
+
if (code !== 0) await refuse(this.#w.adapterReason(code));
|
|
158
|
+
if (flags & REMOTE && !this.#allowRemote) await refuse('adapter-remote-refused', 'sends the pixels off the device; call allowRemote(true) first');
|
|
159
|
+
this.#entries.push(adapter);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The registered adapters, in registration order. */
|
|
163
|
+
describe() {
|
|
164
|
+
return this.#entries.map(({ name = 'adapter', engine, caps = 0, measured = 0, needs = 0, flags = 0, producer = {} }) => ({ name, engine, caps, measured, needs, flags, producer: { ...producer } }));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Why requests were left unread since the last call, one line each. */
|
|
168
|
+
notes() {
|
|
169
|
+
return this.#notes.splice(0);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The first adapter's pairs, the combined engine name when there are several (`tesseract+ppocr`), then the other adapters' further keys. */
|
|
173
|
+
producer() {
|
|
174
|
+
const out = {};
|
|
175
|
+
const combined = this.#entries.length > 1 ? this.#entries.map((e) => e.name ?? 'adapter').join('+') : null;
|
|
176
|
+
this.#entries.forEach((e, i) => {
|
|
177
|
+
for (const [k, v] of Object.entries(e.producer ?? {})) if (!(combined && k === 'ocr-engine') && !(k in out)) out[k] = v;
|
|
178
|
+
if (i === 0 && combined) out['ocr-engine'] = combined;
|
|
179
|
+
});
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The `ports.ocr` of a conversion: routes each request by the engine it names. */
|
|
184
|
+
port() {
|
|
185
|
+
const port = async (req) => {
|
|
186
|
+
const at = this.#w.adapterRoute(req.engine ?? 0, this.#entries.map((e) => e.engine | 0));
|
|
187
|
+
if (at < 0) return null;
|
|
188
|
+
let adapter = this.#entries[at];
|
|
189
|
+
try {
|
|
190
|
+
const got = await this.#ensure(adapter, req);
|
|
191
|
+
if (got.unread !== undefined) {
|
|
192
|
+
this.#notes.push(`${adapter.name ?? 'adapter'}: unsupported ${got.unread}`);
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
adapter = got.ok;
|
|
196
|
+
const context = adapter.packs ? { packs: this.packs.view(adapter.name ?? 'adapter') } : undefined;
|
|
197
|
+
const r = (adapter.flags | 0) & (ASYNC | REMOTE) ? await this.#guarded(adapter, req, context) : await adapter.read(req, context);
|
|
198
|
+
if (r === null || r === undefined) this.#notes.push(`${adapter.name ?? 'adapter'}: unsupported`);
|
|
199
|
+
return r;
|
|
200
|
+
} catch (e) {
|
|
201
|
+
this.#notes.push(`${adapter.name ?? 'adapter'}: failed ${(e && e.message) || e}`);
|
|
202
|
+
throw e;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
Object.defineProperty(port, 'producer', { get: () => this.producer(), enumerable: true });
|
|
206
|
+
port.terminate = () => this.close();
|
|
207
|
+
return port;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Closes every adapter; the registry is empty after it. */
|
|
211
|
+
async close() {
|
|
212
|
+
this.cancel();
|
|
213
|
+
const es = this.#entries.splice(0);
|
|
214
|
+
for (const e of es) await e.close?.();
|
|
215
|
+
}
|
|
216
|
+
}
|
package/src/index.d.ts
CHANGED
|
@@ -36,10 +36,13 @@ export function urlSource(
|
|
|
36
36
|
url: string | URL,
|
|
37
37
|
options?: { fetch?: typeof fetch; headers?: Record<string, string>; signal?: AbortSignal; fetchOptions?: RequestInit },
|
|
38
38
|
): Promise<ByteSource>;
|
|
39
|
-
export function toSource(input: Input, options?: { lazy?: boolean; max?: number }): Promise<ByteSource>;
|
|
39
|
+
export function toSource(input: Input | readonly Input[], options?: { lazy?: boolean; max?: number }): Promise<ByteSource>;
|
|
40
40
|
|
|
41
41
|
/** A request for the OCR port (`ports.ocr`): see `@3sln/emon/tesseract`. */
|
|
42
42
|
export interface OcrRequest {
|
|
43
|
+
engine?: number;
|
|
44
|
+
configuration?: string;
|
|
45
|
+
record?: Int32Array;
|
|
43
46
|
id: number;
|
|
44
47
|
psm: number;
|
|
45
48
|
flags: number;
|
|
@@ -55,6 +58,102 @@ export interface OcrRequest {
|
|
|
55
58
|
/** An OCR port: `null` or `undefined` answers `unsupported`; a rejection answers `failed`. */
|
|
56
59
|
export type OcrPort = (request: OcrRequest) => Promise<object | null | undefined>;
|
|
57
60
|
|
|
61
|
+
/**
|
|
62
|
+
* An OCR engine, registered with `emon.engines().add(...)` (D925): the OIL engine it answers as (1 tesseract, 2 ppocr, 3 apple-vision, 4 mlkit-text, 5 windows-media-ocr), what it
|
|
63
|
+
* declares, and `read`, in the OCR port's form. `@3sln/emon/tesseract` and `@3sln/emon/ppocr` make them.
|
|
64
|
+
*/
|
|
65
|
+
export interface OcrAdapter {
|
|
66
|
+
name?: string;
|
|
67
|
+
engine: number;
|
|
68
|
+
caps?: number;
|
|
69
|
+
measured?: number;
|
|
70
|
+
/** the pack kinds it reads with: 1 recognizer, 2 osd, 4 detector, 8 classifier */
|
|
71
|
+
needs?: number;
|
|
72
|
+
/** 1: may take a while; 2: sends the pixels off the device (refused unless `allowRemote(true)`). An adapter that sets either is held to `setTimeout` and `cancel` and gets `signal` in `read`'s second argument. */
|
|
73
|
+
flags?: number;
|
|
74
|
+
/** true: the adapter reads its models from packs (`engines.packs`): a request that needs one the app has not provided or fetched is left unread (`pack-missing:<id>`), and `read`'s second argument holds the verified files. Default false: the adapter brings its own models. */
|
|
75
|
+
packs?: boolean;
|
|
76
|
+
producer?: Record<string, string>;
|
|
77
|
+
read(request: OcrRequest, context?: { packs?: Map<string, Uint8Array>; signal?: AbortSignal }): Promise<object | null | undefined>;
|
|
78
|
+
close?(): void | Promise<void>;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** What the library tells the app's hook about a pack a conversion needs. */
|
|
82
|
+
export interface PackNeed { pack: string; rev: number; engine: string; kind: string; licence: string; bytes: number; reason: string; requestEngine: string; files: PackFileNeed[] }
|
|
83
|
+
/** One file of a requested pack (D933): its plain name, SHA-256 (lower-case hex), size and the known URLs in priority order (the default mirror, the GitHub `packs` release asset, then the app's mirrors). */
|
|
84
|
+
export interface PackFileNeed { name: string; sha256: string; bytes: number; urls: string[] }
|
|
85
|
+
export type PackState = 'missing' | 'queued' | 'downloading' | 'verifying' | 'ready' | 'failed';
|
|
86
|
+
/** The state of one pack. `done`/`total` are bytes of the whole pack; `mirror` the URL being downloaded from; `reason` why, when failed; `willRetry`: failed, and the next request that needs the pack tries again. */
|
|
87
|
+
export interface PackStatus { id: string; rev: number; engine: string; state: PackState; done: number; total: number; mirror: string; reason: string; willRetry: boolean; byApp: boolean }
|
|
88
|
+
export interface PackSummary { busy: boolean; activeDownloads: number; queued: number; done: number; total: number; progress: number }
|
|
89
|
+
/** What the hook decides: fetch (the app's `fetcher`), provide bytes (a one-file pack) or `{ [fileName]: bytes }`, decline (unread, `pack-missing:<id>`), or substitute another adapter of the same engine. */
|
|
90
|
+
export type PackDecision = { action: 'fetch' } | { action: 'provide'; data: Uint8Array | Record<string, Uint8Array> } | { action: 'decline' } | { action: 'substitute'; engine: string };
|
|
91
|
+
export interface PackFile { name: string; bytes: number; sha: string }
|
|
92
|
+
export interface PackEvent { kind: 'start' | 'progress' | 'done' | 'failed' | 'cancelled'; pack: string; engine: string; done: number; total: number; initiator: 'library' | 'app'; message: string }
|
|
93
|
+
/** Packs (D896, P13.16): verified model bytes, the app's hook, download and progress events. The library ships no HTTP client: `setFetcher` is the app's download. */
|
|
94
|
+
export interface Packs {
|
|
95
|
+
readonly catalogue: { class: string; packs: Array<{ code: number; id: string; rev: number; engine: string; kind: string; licence: string; bytes: number; files: PackFile[] }> };
|
|
96
|
+
setMode(mode: 'never' | 'cache' | 'auto'): void;
|
|
97
|
+
readonly mode: 'never' | 'cache' | 'auto';
|
|
98
|
+
/** `EMON_OFFLINE=1` in Node. */
|
|
99
|
+
readonly offline: boolean;
|
|
100
|
+
onPackNeeded(hook: ((need: PackNeed) => PackDecision | Promise<PackDecision>) | null): void;
|
|
101
|
+
/** The app's download. The turnkey installs `httpPackFetcher` (the platform's `fetch`, the file's URLs in order, Cache Storage where the page has it); `null` removes it. */
|
|
102
|
+
setFetcher(fetcher: ((pack: { id: string; rev: number; files: PackFile[] }, file: PackFile, progress: (done: number) => boolean) => Promise<Uint8Array>) | null): void;
|
|
103
|
+
/** The app's own mirrors, each a base URL (`<base>/sha256/<hex>`) or a template with `{sha}` `{id}` `{rev}` `{file}`: after the default ones, or instead of them with `replace`. */
|
|
104
|
+
setMirrors(list: string[], options?: { replace?: boolean }): void;
|
|
105
|
+
/** The known URLs of one file of a pack, best first. */
|
|
106
|
+
urls(pack: string, file: string | { name: string }): string[];
|
|
107
|
+
/** Records the URL a pack is being downloaded from (for a downloader of your own). */
|
|
108
|
+
noteMirror(pack: string, url: string): void;
|
|
109
|
+
/** The state of every pack, or of one by id. */
|
|
110
|
+
status(): PackStatus[];
|
|
111
|
+
status(id: string): PackStatus;
|
|
112
|
+
/** The aggregate over the packs in flight. */
|
|
113
|
+
summary(): PackSummary;
|
|
114
|
+
/** Listens to every state change of any pack; answers the function that removes the listener. */
|
|
115
|
+
onPackStatus(listener: (status: PackStatus) => void): () => void;
|
|
116
|
+
statusEvents(signal?: AbortSignal): AsyncIterable<PackStatus>;
|
|
117
|
+
/** Gets a `status` event (`event.detail`: the `PackStatus`) for every change. */
|
|
118
|
+
readonly statusTarget: EventTarget;
|
|
119
|
+
onPackEvent(listener: (event: PackEvent) => boolean | void): () => void;
|
|
120
|
+
events(signal?: AbortSignal): AsyncIterable<PackEvent>;
|
|
121
|
+
cancel(): void;
|
|
122
|
+
/** Verifies and keeps the app's bytes for a pack; rejects `pack-hash-mismatch:<id>` / `pack-provide-failed:<id>`. */
|
|
123
|
+
install(id: string, data: Uint8Array | Record<string, Uint8Array>): Promise<void>;
|
|
124
|
+
/** Fetches packs ahead of time (mode `auto`, not offline, a fetcher set). */
|
|
125
|
+
ensure(ids: string[]): Promise<void>;
|
|
126
|
+
installed(): number[];
|
|
127
|
+
files(id: string): Map<string, Uint8Array> | null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The engine registry: kin's rules (`ad-register-check`, `ad-route`) over the adapters you register. */
|
|
131
|
+
export class Engines {
|
|
132
|
+
/** Lets adapters that send the pixels off the device register (default no). Call it before registering them. */
|
|
133
|
+
allowRemote(allow: boolean): void;
|
|
134
|
+
/** How long a request waits for an async or remote adapter (kin's `ocr.timeout-ms`; default 60 s; `0` restores it). */
|
|
135
|
+
setTimeout(ms: number): void;
|
|
136
|
+
/** Ends every request now waiting for an async or remote adapter: each is unread and its `signal` aborts. */
|
|
137
|
+
cancel(): void;
|
|
138
|
+
/** The pack mode, hook, download and events. */
|
|
139
|
+
readonly packs: Packs;
|
|
140
|
+
/** Whether the engine can read now: registered, and its packs here. */
|
|
141
|
+
engineReady(name: string, options?: { renderer?: boolean }): boolean;
|
|
142
|
+
/** D896's `engines()`: every engine of kin's table with its state and why (the C ABI's JSON shape). */
|
|
143
|
+
state(options?: { renderer?: boolean }): { platform: string; mode: string; offline: boolean; store: string; engines: Array<{ name: string; kind: string; impl: string; state: string; registered: boolean; calibrated: boolean; caps: number; oen: number; role: string; needs: Array<{ id: string; kind: string; bytes: number; licence: string; installed: boolean }>; download_bytes: number; reason: string }> };
|
|
144
|
+
/** D896's `prepare(options)`: the packs a conversion needs and which are missing (the C ABI's JSON shape). */
|
|
145
|
+
prepare(options?: { ocr?: string; ocrEngine?: string; locale?: string }): { verdict: string; mode: string; offline: boolean; engines: string[]; languages: string[]; osd: boolean; packs: object[]; unsupported: object[]; missing: number; missing_bytes: number; conditional: number; conditional_bytes: number };
|
|
146
|
+
/** Registers an adapter, held to kin's engine table; rejects with `usage` and the refusal's name (`adapter-engine-unknown`, `adapter-caps-beyond-engine`, ...). */
|
|
147
|
+
add(adapter: OcrAdapter): Promise<void>;
|
|
148
|
+
describe(): Array<{ name: string; engine: number; caps: number; measured: number; needs: number; flags: number; producer: Record<string, string> }>;
|
|
149
|
+
/** Why requests were left unread since the last call. */
|
|
150
|
+
notes(): string[];
|
|
151
|
+
producer(): Record<string, string>;
|
|
152
|
+
/** The `ports.ocr` of a conversion: routes each request by the engine it names. */
|
|
153
|
+
port(): OcrPort & { terminate(): Promise<void>; readonly producer: Record<string, string> };
|
|
154
|
+
close(): Promise<void>;
|
|
155
|
+
}
|
|
156
|
+
|
|
58
157
|
/** One page of a renderer's document. */
|
|
59
158
|
export interface Rendered {
|
|
60
159
|
width: number;
|
|
@@ -87,6 +186,8 @@ export interface Renderer {
|
|
|
87
186
|
export interface ConvertOptions {
|
|
88
187
|
locale?: string;
|
|
89
188
|
ocr?: 'always' | 'auto' | 'never' | string;
|
|
189
|
+
/** Experimental PP-OCR needs the optional wasm build and @3sln/emon/ppocr port. Tesseract is the default. */
|
|
190
|
+
ocrEngine?: 'tesseract' | 'ppocr' | string;
|
|
90
191
|
furniture?: 'policy' | 'keep' | 'drop' | string;
|
|
91
192
|
assets?: 'none' | 'images' | 'figures' | string;
|
|
92
193
|
assetDpi?: number;
|
|
@@ -95,6 +196,11 @@ export interface ConvertOptions {
|
|
|
95
196
|
assetsBytes?: number;
|
|
96
197
|
assetSignatures?: boolean | 'on' | 'off';
|
|
97
198
|
ocrScope?: 'full' | 'witness' | string;
|
|
199
|
+
capture?: 'auto' | 'scan' | 'photos';
|
|
200
|
+
/** Where engines that read a page disagree, whether the Model says so (P13.9): `disagree` (the default), `off`, or `all` (adds segmentation-only differences). */
|
|
201
|
+
ocrReadings?: 'disagree' | 'off' | 'all';
|
|
202
|
+
/** Whether the composition of the engines' readings changes the page (P13.9): `keep` (the default) or `vote`. */
|
|
203
|
+
ocrCompose?: 'keep' | 'vote';
|
|
98
204
|
keepEvidence?: boolean;
|
|
99
205
|
maxRounds?: number;
|
|
100
206
|
fetchRounds?: number;
|
|
@@ -123,6 +229,8 @@ export interface HtmlOptions {
|
|
|
123
229
|
milestones?: boolean;
|
|
124
230
|
initialsPlain?: boolean;
|
|
125
231
|
alignStyle?: boolean;
|
|
232
|
+
/** Writes the readings that disagree as inert `<template>`s inside a `variant` span (P13.9). */
|
|
233
|
+
readings?: boolean;
|
|
126
234
|
assets?: 'inline' | 'external' | 'omit';
|
|
127
235
|
assetPrefix?: string;
|
|
128
236
|
}
|
|
@@ -187,7 +295,29 @@ export class Emon {
|
|
|
187
295
|
defaults?: { chunk?: number },
|
|
188
296
|
): Promise<Emon>;
|
|
189
297
|
readonly defaults: { chunk?: number };
|
|
190
|
-
convert(input: Input | InputWithPassword, options?: ConvertOptions): Promise<Model>;
|
|
298
|
+
convert(input: Input | InputWithPassword | readonly Input[], options?: ConvertOptions): Promise<Model>;
|
|
299
|
+
/** An empty engine registry bound to this module; register each OCR engine with `add`, then pass `engines.port()` as `ports.ocr`. */
|
|
300
|
+
engines(): Engines;
|
|
191
301
|
/** Stage 0 of each input, cheap. */
|
|
192
302
|
intake(inputs: Input | InputWithPassword | Array<Input | InputWithPassword>, options?: ConvertOptions): Promise<IntakeResult[]>;
|
|
193
303
|
}
|
|
304
|
+
|
|
305
|
+
/** An injected pack store of standard types: bytes in and out by the pack's id and rev and the file's name. What `get` returns is verified again; a failed `put` is not a failed download. */
|
|
306
|
+
export interface PackCache {
|
|
307
|
+
get(pack: { id: string; rev: number; files: { name: string; bytes: number; sha: string }[] }, file: { name: string; bytes: number; sha: string }): Promise<Uint8Array | null>;
|
|
308
|
+
put(pack: { id: string; rev: number; files: { name: string; bytes: number; sha: string }[] }, file: { name: string; bytes: number; sha: string }, bytes: Uint8Array): Promise<void>;
|
|
309
|
+
}
|
|
310
|
+
/** A pack cache over Cache Storage (`caches`): one Response per file, older revisions dropped once a new one is whole. `null` where there is no Cache Storage. */
|
|
311
|
+
export function cacheStoragePackCache(name?: string, storage?: CacheStorage): PackCache | null;
|
|
312
|
+
/** The default pack loader (D933): downloads with `fetch`, trying the file's URLs in order, verifying, and keeping files in `cache` (default: `detectPackCache()`; `null` for none; the file stores are the optional `@3sln/emon/node-pack-cache` and `@3sln/emon/deno-pack-cache`). */
|
|
313
|
+
/** A pack cache over IndexedDB; null where there is none. */
|
|
314
|
+
export function indexedDBPackCache(idb?: IDBFactory, name?: string): PackCache | null;
|
|
315
|
+
/** The default store by what the runtime has: Cache Storage, IndexedDB, Deno's or Node/Bun's file system (optional modules), else none. */
|
|
316
|
+
export function detectPackCache(env?: object, load?: (kind: 'node' | 'deno') => Promise<{ packCache?: (env?: object) => PackCache | null }>): Promise<{ kind: 'cache-storage' | 'indexeddb' | 'deno' | 'node' | 'none'; cache: PackCache | null }>;
|
|
317
|
+
export function httpPackFetcher(packs: Packs, options?: { cache?: PackCache | null; fetch?: typeof fetch; note?: (line: string) => void }): NonNullable<Parameters<Packs['setFetcher']>[0]>;
|
|
318
|
+
/** The default places a pack file can be downloaded from (one definition for every host). */
|
|
319
|
+
export const MIRROR_R2: string;
|
|
320
|
+
export const MIRROR_GITHUB: string;
|
|
321
|
+
export function fileUrls(id: string, rev: number, file: string, shaHex: string, app?: string[], replace?: boolean): string[];
|
|
322
|
+
export function mirrorUrl(mirror: string, id: string, rev: number, file: string, shaHex: string): string;
|
|
323
|
+
export function parseMirrors(text: string): string[];
|
package/src/index.js
CHANGED
|
@@ -25,9 +25,12 @@
|
|
|
25
25
|
|
|
26
26
|
import { Wasm } from './wasm.js';
|
|
27
27
|
import { toSource, bytesSource, blobSource, urlSource, streamSource, SourceChangedError, EmonError } from './sources.js';
|
|
28
|
-
import { ocrRequest, encodeOcr } from './ocr.js';
|
|
28
|
+
import { ocrRequest, encodeOcr, canonicalOcr } from './ocr.js';
|
|
29
|
+
import { Engines } from './engines.js';
|
|
29
30
|
|
|
30
|
-
export {
|
|
31
|
+
export { httpPackFetcher, cacheStoragePackCache, indexedDBPackCache, detectPackCache } from './packfetch.js';
|
|
32
|
+
export { MIRROR_R2, MIRROR_GITHUB, fileUrls, mirrorUrl, parseMirrors } from './packs.js';
|
|
33
|
+
export { bytesSource, blobSource, urlSource, streamSource, toSource, SourceChangedError, EmonError, Engines };
|
|
31
34
|
|
|
32
35
|
// The WASM instance (`w`), a Model's handle (`h`) and an Asset's Model (`model`) are NOT public API (P11.4, D542): they are defined
|
|
33
36
|
// non-enumerable, so they are not in `Object.keys`, a spread, `JSON.stringify` or a `for...in`, and `index.d.ts` does not declare them.
|
|
@@ -43,6 +46,7 @@ const optionLines = (o, chunk, record) => {
|
|
|
43
46
|
const put = (k, v) => v !== undefined && v !== null && L.push(`${k}=${v}`);
|
|
44
47
|
put('locale', o.locale);
|
|
45
48
|
put('ocr', o.ocr);
|
|
49
|
+
put('ocr-engine', o.ocrEngine);
|
|
46
50
|
put('furniture', o.furniture);
|
|
47
51
|
put('assets', o.assets);
|
|
48
52
|
put('asset-dpi', o.assetDpi);
|
|
@@ -52,6 +56,9 @@ const optionLines = (o, chunk, record) => {
|
|
|
52
56
|
if (o.assetSignatures !== undefined) put('asset-signatures', o.assetSignatures === true || o.assetSignatures === 'on' ? 'on' : 'off');
|
|
53
57
|
if (o.keepEvidence) put('keep-evidence', 1);
|
|
54
58
|
put('ocr-scope', o.ocrScope);
|
|
59
|
+
put('capture', o.capture);
|
|
60
|
+
put('ocr-readings', o.ocrReadings);
|
|
61
|
+
put('ocr-compose', o.ocrCompose);
|
|
55
62
|
put('max-rounds', o.maxRounds);
|
|
56
63
|
put('fetch-rounds', o.fetchRounds);
|
|
57
64
|
for (const [k, v] of Object.entries(o.limits || {})) put(`limit.${k}`, v);
|
|
@@ -59,6 +66,7 @@ const optionLines = (o, chunk, record) => {
|
|
|
59
66
|
for (const [k, v] of Object.entries(o.producer || {})) put(`producer.${k}`, v);
|
|
60
67
|
// what the renderer says produced its pixels (`pdfium.js`'s `producer`), after the embedder's own
|
|
61
68
|
for (const [k, v] of Object.entries((o.ports && o.ports.render && o.ports.render.producer) || {})) put(`producer.${k}`, v);
|
|
69
|
+
for (const [k, v] of Object.entries(o.ports?.ocr?.producer || {})) put(`producer.${k}`, v);
|
|
62
70
|
if (o.ports && o.ports.ocr) put('js-ocr', 1);
|
|
63
71
|
if (o.ports && o.ports.render) put('js-render', 1);
|
|
64
72
|
return L.join('\n');
|
|
@@ -137,7 +145,7 @@ export class Model {
|
|
|
137
145
|
|
|
138
146
|
/**
|
|
139
147
|
* SPEC 5: HTML. Options: `ids`, `geometry`, `confidenceBelow` (0..1000), `ledger`, `pretty`, `furnitureDrop`, `milestones`
|
|
140
|
-
* (default true), `initialsPlain`, `alignStyle`, `assets`: `inline` (data: URIs, the default), `external` (the HTML names each
|
|
148
|
+
* (default true), `initialsPlain`, `alignStyle`, `readings`, `assets`: `inline` (data: URIs, the default), `external` (the HTML names each
|
|
141
149
|
* asset file by `assetPrefix + name`, and the caller serves them: `model.assets[i].blob()`) or `omit`; `assetPrefix`.
|
|
142
150
|
*/
|
|
143
151
|
html(o = {}) {
|
|
@@ -151,6 +159,7 @@ export class Model {
|
|
|
151
159
|
if (o.milestones === false) L.push('no-milestones');
|
|
152
160
|
if (o.initialsPlain) L.push('initials-plain');
|
|
153
161
|
if (o.alignStyle) L.push('align-style');
|
|
162
|
+
if (o.readings) L.push('readings');
|
|
154
163
|
if (o.assets) L.push(`assets=${o.assets}`);
|
|
155
164
|
if (o.assetPrefix) L.push(`prefix=${o.assetPrefix}`);
|
|
156
165
|
const w = this.w;
|
|
@@ -227,6 +236,14 @@ export class Emon {
|
|
|
227
236
|
this.defaults = defaults;
|
|
228
237
|
}
|
|
229
238
|
|
|
239
|
+
/**
|
|
240
|
+
* An empty engine registry bound to this module (D925): `await engines.add(adapter)` for each OCR engine (`tesseractAdapter`, `ppocrEngine`, your own), then
|
|
241
|
+
* `{ ports: { ocr: engines.port() } }`. Nothing is registered unless you add it.
|
|
242
|
+
*/
|
|
243
|
+
engines() {
|
|
244
|
+
return new Engines(this.w, (o) => optionLines(o ?? {}, this.defaults?.chunk ?? 65536, false));
|
|
245
|
+
}
|
|
246
|
+
|
|
230
247
|
_open(source, password, mode, options) {
|
|
231
248
|
const w = this.w;
|
|
232
249
|
const chunk = options.chunk ?? this.defaults.chunk ?? 65536;
|
|
@@ -315,7 +332,18 @@ export class Emon {
|
|
|
315
332
|
failed(w.status.unsupported);
|
|
316
333
|
return;
|
|
317
334
|
}
|
|
335
|
+
if (result[canonicalOcr]) {
|
|
336
|
+
const answer = result[canonicalOcr];
|
|
337
|
+
if (!(answer instanceof Int32Array) || answer.length < 4 || answer[0] !== answer.length || answer[1] !== kind || answer[2] !== rec[2]) {
|
|
338
|
+
throw new EmonError('internal', 'invalid canonical OCR answer');
|
|
339
|
+
}
|
|
340
|
+
const rc = w.withBytes(new Uint8Array(answer.buffer, answer.byteOffset, answer.byteLength), p => w.x.emon_answer(h, p, answer.length));
|
|
341
|
+
if (rc < 0) throw this._error(rc);
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
318
344
|
const cells = encodeOcr(result, w.ocrWord);
|
|
345
|
+
const observed = w.ocrObserved(result.observed ?? ports.ocr.producer?.observed ?? ports.ocr.producer?.engine ?? 'external');
|
|
346
|
+
cells[2] = observed[0]; cells[3] = observed[1];
|
|
319
347
|
const rc = w.withBytes(new Uint8Array(cells.buffer), (p) => w.x.emon_answer_ocr(h, rec[2], p, cells.length));
|
|
320
348
|
if (rc < 0) throw this._error(rc);
|
|
321
349
|
return;
|
package/src/ocr.js
CHANGED
|
@@ -42,6 +42,8 @@ export const unpack4 = (v) => {
|
|
|
42
42
|
};
|
|
43
43
|
|
|
44
44
|
const cps = (s) => Array.from(s || '', (c) => c.codePointAt(0));
|
|
45
|
+
// Private handshake for the optional Rust-built canonical answer.
|
|
46
|
+
export const canonicalOcr = Symbol('emon canonical OCR answer');
|
|
45
47
|
|
|
46
48
|
/**
|
|
47
49
|
* The request's fields from kin's record `[len kind id bitmap psm flags x y w h lang... status?]`. WHERE the languages are, which
|
|
@@ -53,8 +55,10 @@ export function ocrRequest(rec, bitmap, w) {
|
|
|
53
55
|
const args = rec.slice(3);
|
|
54
56
|
const flags = args[2];
|
|
55
57
|
const langs = [];
|
|
56
|
-
|
|
58
|
+
const marker = w.ocrIdentityAt(rec);
|
|
59
|
+
for (let k = w.ocrLangFirst(rec); k < (marker < 0 ? args.length : marker - 3); k++) langs.push(unpack4(args[k]));
|
|
57
60
|
return {
|
|
61
|
+
...(marker >= 0 ? { record: Int32Array.from(rec), engine: rec[marker + 2], configuration: String.fromCodePoint(...rec.slice(marker + 4)) } : {}),
|
|
58
62
|
models: (installed) => w.ocrModels(rec, installed),
|
|
59
63
|
wordLang: (model) => unpack4(w.ocrWordLang(model)),
|
|
60
64
|
blockType: (polyBlockType) => w.ocrBlockType(polyBlockType),
|
|
@@ -70,36 +74,60 @@ export function ocrRequest(rec, bitmap, w) {
|
|
|
70
74
|
};
|
|
71
75
|
}
|
|
72
76
|
|
|
73
|
-
/** The integer form `emon_answer_ocr` reads (its layout is `
|
|
77
|
+
/** The integer form `emon_answer_ocr` reads (its layout is `oil-flat` in `kin/oil.kin`); `c` is the module's `ocrWord` constants. */
|
|
74
78
|
export function encodeOcr(r, c) {
|
|
75
|
-
const o = r.orientation
|
|
79
|
+
const o = r.orientation;
|
|
76
80
|
const osd = r.osd;
|
|
77
81
|
const blocks = r.blocks || [];
|
|
78
82
|
const lines = r.lines || [];
|
|
79
83
|
const words = r.words || [];
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
84
|
+
const baseline = lines.length > 0 && lines.every(l => l.baseline?.length === 4 && l.baseline.every(Number.isFinite));
|
|
85
|
+
const symbols = words.some(w => w.symbols?.length);
|
|
86
|
+
const alts = words.some(w => w.symbols?.some(s => s.alts?.length));
|
|
87
|
+
const lexicon = words.length > 0 && words.every(w => typeof w.dict === 'boolean');
|
|
88
|
+
let caps = 256 | 2097152;
|
|
89
|
+
if (blocks.length) caps |= 1 | 4;
|
|
90
|
+
if (lines.some(l => l.paragraph !== undefined)) caps |= 2;
|
|
91
|
+
if (baseline) caps |= 8;
|
|
92
|
+
if (osd) caps |= 512 | 2048;
|
|
93
|
+
if (o?.deskew !== undefined) caps |= 1024;
|
|
94
|
+
if (o?.writingDirection !== undefined) caps |= 4096;
|
|
95
|
+
if (words.some(w => w.lang)) caps |= 8192;
|
|
96
|
+
if (lexicon) caps |= 16384;
|
|
97
|
+
if (words.some(w => w.flags !== undefined)) caps |= 32768;
|
|
98
|
+
if (words.some(w => w.pointSize >= 0)) caps |= 65536;
|
|
99
|
+
if (symbols) caps |= 131072 | 262144;
|
|
100
|
+
if (alts) caps |= 524288;
|
|
101
|
+
const v = [1, r.engine ?? 1, 0, 0, caps, r.native ?? (caps & ~(r.inferred ?? 0)), r.seg ?? 1, 1, 1000,
|
|
102
|
+
osd ? osd.degrees / 90 : 0, osd?.orientationConfidence ?? 0,
|
|
103
|
+
o?.deskew ?? 0, osd ? pack4(osd.script || '') : 0, osd?.scriptConfidence ?? 0,
|
|
104
|
+
o?.writingDirection ?? 0, o?.textlineOrder ?? 0, 0, r.granularity ?? 0,
|
|
105
|
+
blocks.length, lines.length, words.length, 0, 0, 0];
|
|
106
|
+
for (let bi = 0; bi < blocks.length; bi++) {
|
|
107
|
+
const b = blocks[bi];
|
|
108
|
+
v.push(...b.box, -1);
|
|
109
|
+
if (caps & 4096) v.push(b.orient ?? 0, b.writingDirection ?? 0, b.textlineOrder ?? 0);
|
|
110
|
+
if (caps & 4) v.push(lines.find(l => l.block === bi)?.type ?? 0);
|
|
111
|
+
}
|
|
112
|
+
for (let li = 0; li < lines.length; li++) {
|
|
113
|
+
const l = lines[li];
|
|
114
|
+
v.push(...l.box, blocks.length ? l.block : -1, words.filter(w => w.line === li).length);
|
|
115
|
+
if (caps & 2) v.push(l.paragraph ?? -1);
|
|
116
|
+
if (baseline) v.push(...l.baseline);
|
|
87
117
|
}
|
|
88
|
-
for (const b of blocks) v.push(...b.box, b.orient ?? 0, b.writingDirection ?? 0, b.textlineOrder ?? 2);
|
|
89
118
|
for (const w of words) {
|
|
90
119
|
const t = cps(w.text);
|
|
91
|
-
v.push(...w.box, w.
|
|
120
|
+
v.push(...w.box, w.line, w.conf);
|
|
121
|
+
if (caps & 8192) v.push(w.lang ? pack4(w.lang) : 0);
|
|
122
|
+
if (caps & 32768) v.push(w.flags ?? 0);
|
|
123
|
+
if (caps & 65536) v.push(w.pointSize ?? -1);
|
|
124
|
+
if (lexicon) v.push(1 | (w.dict ? 2 : 0));
|
|
92
125
|
const syms = w.symbols || [];
|
|
93
|
-
v.push(syms.length);
|
|
126
|
+
v.push(syms.length, t.length, ...t);
|
|
94
127
|
for (const s of syms) {
|
|
95
|
-
const st = cps(s.text);
|
|
96
|
-
v.push(...s.box, s.conf, st.length, ...st);
|
|
97
|
-
const
|
|
98
|
-
v.push(alts.length);
|
|
99
|
-
for (const a of alts) {
|
|
100
|
-
const at = cps(a.text);
|
|
101
|
-
v.push(a.conf, at.length, ...at);
|
|
102
|
-
}
|
|
128
|
+
const st = cps(s.text), choices = s.alts || [];
|
|
129
|
+
v.push(...s.box, s.conf, st.length, choices.length, ...st);
|
|
130
|
+
for (const a of choices) { const text = cps(a.text); v.push(text.length, a.conf, ...text); }
|
|
103
131
|
}
|
|
104
132
|
}
|
|
105
133
|
return Int32Array.from(v);
|