@3sln/emon 0.3.0-preview.1 → 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/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);
@@ -1,7 +1,8 @@
1
1
  // Type declarations of `@3sln/emon/tesseract` (P11.4, D542).
2
- import type { OcrPort } from './index.js';
2
+ import type { OcrAdapter } from './index.js';
3
3
 
4
- export function tesseractPort(options: {
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
- }): OcrPort & { terminate(): Promise<void>; producer: Record<string, string> };
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 `ocr` PORT (DEVLOG P9.3, SPEC 7.3, D211-D214): the browser's OCR engine, fulfilling `ocr` requests through
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 { tesseractPort } from '@3sln/emon/tesseract';
7
+ // import { tesseractAdapter } from '@3sln/emon/tesseract';
8
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();
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
@@ -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 {((request: object) => Promise<object>) & { terminate(): Promise<void>, producer: object }}
70
+ * @returns an adapter for `emon.engines().add(...)`: `{ name: 'tesseract', engine: 1, needs, producer, read(request), close() }`
69
71
  */
70
- export function tesseractPort({ createWorker, languages = ['eng'], oem = 1, workerOptions = {}, workers = 1 }) {
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,8 +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 port = async (req) => {
92
- if (req.engine !== undefined && req.engine !== 1) return null;
93
+ const read = async (req) => {
93
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
94
95
  // read it, one with no model is dropped, none left is every model (D038, P10.7)
95
96
  const langs = req.models(languages).map((i) => languages[i]);
@@ -106,10 +107,11 @@ export function tesseractPort({ createWorker, languages = ['eng'], oem = 1, work
106
107
  s.busy -= 1;
107
108
  }
108
109
  };
109
- port.terminate = async () => {
110
+ const close = async () => {
110
111
  for (const pool of pools.values()) for (const s of pool) await (await s.promise).terminate();
111
112
  pools.clear();
112
113
  };
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;
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 };
115
117
  }
package/src/wasm.js CHANGED
@@ -69,6 +69,79 @@ export class Wasm {
69
69
  return n < 0 ? [] : Array.from(out);
70
70
  }
71
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
+
72
145
  /** The language a model read a word in, as a request packs it. */
73
146
  ocrWordLang(model) {
74
147
  const cps = Int32Array.from(Array.from(model, (c) => c.codePointAt(0)));