@3sln/emon 0.1.0 → 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/emon.wasm CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@3sln/emon",
3
- "version": "0.1.0",
3
+ "version": "0.3.0-preview.1",
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"],
@@ -23,13 +23,15 @@
23
23
  "publishConfig": { "access": "public" },
24
24
  "engines": { "node": ">=22" },
25
25
  "peerDependencies": {
26
- "@3sln/pdfium-wasm": "^0.1.0"
26
+ "@3sln/pdfium-wasm": "^0.3.0-preview.1"
27
27
  },
28
28
  "peerDependenciesMeta": {
29
29
  "@3sln/pdfium-wasm": { "optional": true }
30
30
  },
31
31
  "devDependencies": {
32
32
  "puppeteer-core": "25.12.0",
33
+ "onnxruntime-web": "1.22.0",
34
+ "wabt": "1.0.39",
33
35
  "tesseract.js": "7.0.0",
34
36
  "@tesseract.js-data/eng": "1.0.0"
35
37
  }
package/src/index.d.ts CHANGED
@@ -40,6 +40,9 @@ export function toSource(input: Input, options?: { lazy?: boolean; max?: number
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;
@@ -87,6 +90,8 @@ export interface Renderer {
87
90
  export interface ConvertOptions {
88
91
  locale?: string;
89
92
  ocr?: 'always' | 'auto' | 'never' | string;
93
+ /** Experimental PP-OCR needs the optional wasm build and @3sln/emon/ppocr port. Tesseract is the default. */
94
+ ocrEngine?: 'tesseract' | 'ppocr' | string;
90
95
  furniture?: 'policy' | 'keep' | 'drop' | string;
91
96
  assets?: 'none' | 'images' | 'figures' | string;
92
97
  assetDpi?: number;
package/src/index.js CHANGED
@@ -25,7 +25,7 @@
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
29
 
30
30
  export { bytesSource, blobSource, urlSource, streamSource, toSource, SourceChangedError, EmonError };
31
31
 
@@ -43,6 +43,7 @@ const optionLines = (o, chunk, record) => {
43
43
  const put = (k, v) => v !== undefined && v !== null && L.push(`${k}=${v}`);
44
44
  put('locale', o.locale);
45
45
  put('ocr', o.ocr);
46
+ put('ocr-engine', o.ocrEngine);
46
47
  put('furniture', o.furniture);
47
48
  put('assets', o.assets);
48
49
  put('asset-dpi', o.assetDpi);
@@ -59,6 +60,7 @@ const optionLines = (o, chunk, record) => {
59
60
  for (const [k, v] of Object.entries(o.producer || {})) put(`producer.${k}`, v);
60
61
  // what the renderer says produced its pixels (`pdfium.js`'s `producer`), after the embedder's own
61
62
  for (const [k, v] of Object.entries((o.ports && o.ports.render && o.ports.render.producer) || {})) put(`producer.${k}`, v);
63
+ for (const [k, v] of Object.entries(o.ports?.ocr?.producer || {})) put(`producer.${k}`, v);
62
64
  if (o.ports && o.ports.ocr) put('js-ocr', 1);
63
65
  if (o.ports && o.ports.render) put('js-render', 1);
64
66
  return L.join('\n');
@@ -315,7 +317,18 @@ export class Emon {
315
317
  failed(w.status.unsupported);
316
318
  return;
317
319
  }
320
+ if (result[canonicalOcr]) {
321
+ const answer = result[canonicalOcr];
322
+ if (!(answer instanceof Int32Array) || answer.length < 4 || answer[0] !== answer.length || answer[1] !== kind || answer[2] !== rec[2]) {
323
+ throw new EmonError('internal', 'invalid canonical OCR answer');
324
+ }
325
+ const rc = w.withBytes(new Uint8Array(answer.buffer, answer.byteOffset, answer.byteLength), p => w.x.emon_answer(h, p, answer.length));
326
+ if (rc < 0) throw this._error(rc);
327
+ return;
328
+ }
318
329
  const cells = encodeOcr(result, w.ocrWord);
330
+ const observed = w.ocrObserved(result.observed ?? ports.ocr.producer?.observed ?? ports.ocr.producer?.engine ?? 'external');
331
+ cells[2] = observed[0]; cells[3] = observed[1];
319
332
  const rc = w.withBytes(new Uint8Array(cells.buffer), (p) => w.x.emon_answer_ocr(h, rec[2], p, cells.length));
320
333
  if (rc < 0) throw this._error(rc);
321
334
  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
- for (let k = w.ocrLangFirst(rec); k < args.length; k++) langs.push(unpack4(args[k]));
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 `ox-flat` in `kin/ocrport.kin`); `c` is the module's `ocrWord` constants. */
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 v = [
81
- o.orient ?? 0, o.writingDirection ?? 0, o.textlineOrder ?? 2, o.deskew ?? 0,
82
- osd ? osd.degrees : -1, osd ? pack4(osd.script || '') : 0, osd ? osd.scriptConfidence : -1, osd ? osd.orientationConfidence : -1,
83
- lines.length, blocks.length, words.length, 0, 0, 0,
84
- ];
85
- for (const l of lines) {
86
- v.push(...l.box, ...l.baseline, l.block, l.paragraph, l.type ?? 0, -1, -1, -1);
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.conf, w.line, w.block, w.flags ?? 0, w.lang ? pack4(w.lang) : 0, w.pointSize ?? -1, (w.dict ? c.dict : 0) | (w.numeric ? c.numeric : 0), t.length, ...t);
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 alts = s.alts || [];
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);
package/src/tesseract.js CHANGED
@@ -24,7 +24,7 @@ const x10 = (c) => Math.round((c ?? 0) * 10);
24
24
 
25
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
26
  function resultOf(blocks, { wantSymbols, lang, blockType }) {
27
- const out = { orientation: { orient: 0, writingDirection: 0, textlineOrder: 2, deskew: 0 }, blocks: [], lines: [], words: [] };
27
+ const out = { inferred: 8192, blocks: [], lines: [], words: [] };
28
28
  let par = -1;
29
29
  (blocks || []).forEach((b, bi) => {
30
30
  out.blocks.push({ box: box(b.bbox), orient: 0, writingDirection: 0, textlineOrder: 2 });
@@ -35,7 +35,7 @@ function resultOf(blocks, { wantSymbols, lang, blockType }) {
35
35
  const bl = l.baseline || {};
36
36
  out.lines.push({
37
37
  box: box(l.bbox),
38
- baseline: [bl.x0 ?? 0, bl.y0 ?? 0, bl.x1 ?? 0, bl.y1 ?? 0],
38
+ baseline: [bl.x0, bl.y0, bl.x1, bl.y1].every(Number.isFinite) ? [bl.x0, bl.y0, bl.x1, bl.y1] : undefined,
39
39
  block: bi,
40
40
  paragraph: par,
41
41
  type: blockType(b.blocktype),
@@ -43,7 +43,7 @@ function resultOf(blocks, { wantSymbols, lang, blockType }) {
43
43
  for (const w of l.words || []) {
44
44
  const text = (w.text || '').trim();
45
45
  if (!text) continue;
46
- const word = { box: box(w.bbox), conf: x10(w.confidence), line: li, block: bi, text, flags: 0, lang, pointSize: -1, dict: false, numeric: false };
46
+ const word = { box: box(w.bbox), conf: x10(w.confidence), line: li, block: bi, text, lang };
47
47
  if (wantSymbols) {
48
48
  word.symbols = (w.symbols || []).map((s) => ({ box: box(s.bbox), conf: x10(s.confidence), text: s.text || '', alts: [] }));
49
49
  // the symbols must spell the word, as the engine's own do
@@ -89,6 +89,7 @@ export function tesseractPort({ createWorker, languages = ['eng'], oem = 1, work
89
89
  return s || pool.reduce((a, b) => (a.busy <= b.busy ? a : b));
90
90
  };
91
91
  const port = async (req) => {
92
+ if (req.engine !== undefined && req.engine !== 1) return null;
92
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
93
94
  // read it, one with no model is dropped, none left is every model (D038, P10.7)
94
95
  const langs = req.models(languages).map((i) => languages[i]);
@@ -109,6 +110,6 @@ export function tesseractPort({ createWorker, languages = ['eng'], oem = 1, work
109
110
  for (const pool of pools.values()) for (const s of pool) await (await s.promise).terminate();
110
111
  pools.clear();
111
112
  };
112
- port.producer = { engine: 'tesseract.js', 'engine-mode': oem === 1 ? 'default (LSTM)' : String(oem), 'lstm-choice-mode': '2', models: languages.join(' '), host: 'host/js/src/tesseract.js' };
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' };
113
114
  return port;
114
115
  }
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
- // so instantiating it needs nothing of the page: no filesystem, no network, no glue. Everything here is integers and byte ranges
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, {})).instance);
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, {})).instance);
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 = [];