@3sln/emon-ppocr 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/emon.wasm ADDED
Binary file
package/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export { ppocrPort, ppocrAdapter, ppocrLexicon } from './ppocr.js';
2
+ /** Caller-selected native release .tar.gz URL, compressed bytes or byte stream.
3
+ * The PP port and lexicon verify all returned model bytes before inference.
4
+ */
5
+ export function ppocrAssets(source: string | URL | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array>): Promise<{
6
+ models: Record<'ch_PP-OCRv5_det_mobile.onnx' | 'ch_ppocr_mobile_v2.0_cls_mobile.onnx' | 'en_PP-OCRv5_rec_mobile.onnx', Uint8Array>;
7
+ traineddata: Uint8Array;
8
+ }>;
package/index.js ADDED
@@ -0,0 +1,51 @@
1
+ // No default URLs, automatic inference downloads or required ORT dependency.
2
+ export { ppocrPort, ppocrAdapter, ppocrLexicon } from './ppocr.js';
3
+
4
+ /** Read the pinned model payload from a caller-selected native release tar.gz.
5
+ * Keep ORT's platform files out of the browser filesystem. The port and lexicon
6
+ * verify their own SHA-256 pins before using any returned bytes.
7
+ */
8
+ export async function ppocrAssets(source) {
9
+ if (typeof source === 'string' || source instanceof URL) {
10
+ const response = await fetch(source);
11
+ if (!response.ok) throw new Error(`ppocr-models-missing: ${response.status}`);
12
+ source = response.body;
13
+ }
14
+ const stream = source instanceof ReadableStream ? source : new Blob([source]).stream();
15
+ const reader = stream.pipeThrough(new DecompressionStream('gzip')).getReader();
16
+ const chunks = [];
17
+ let size = 0;
18
+ try {
19
+ for (;;) {
20
+ const { value, done } = await reader.read();
21
+ if (done) break;
22
+ size += value.byteLength;
23
+ if (size > 512 * 1024 * 1024) throw new Error('ppocr-archive-too-large');
24
+ chunks.push(value);
25
+ }
26
+ } finally { await reader.cancel(); }
27
+ const tar = new Uint8Array(size);
28
+ let offset = 0;
29
+ for (const chunk of chunks) { tar.set(chunk, offset); offset += chunk.length; }
30
+ const names = new Set(['ch_PP-OCRv5_det_mobile.onnx',
31
+ 'ch_ppocr_mobile_v2.0_cls_mobile.onnx', 'en_PP-OCRv5_rec_mobile.onnx', 'eng.traineddata']);
32
+ const files = new Map(), decoder = new TextDecoder();
33
+ const text = bytes => decoder.decode(bytes).replace(/\0.*$/s, '');
34
+ for (let pos = 0; pos + 512 <= tar.length;) {
35
+ const header = tar.subarray(pos, pos + 512);
36
+ if (header.every(x => x === 0)) break;
37
+ const name = text(header.subarray(0, 100));
38
+ const length = Number.parseInt(text(header.subarray(124, 136)).trim(), 8);
39
+ if (!Number.isSafeInteger(length) || length < 0 || pos + 512 + length > tar.length)
40
+ throw new Error('ppocr-bad-archive');
41
+ const leaf = name.split('/').pop();
42
+ if ((header[156] === 0 || header[156] === 48) && /\/models\/[^/]+$/.test(name) && names.has(leaf)) {
43
+ if (files.has(leaf)) throw new Error('ppocr-duplicate-asset');
44
+ files.set(leaf, tar.slice(pos + 512, pos + 512 + length));
45
+ }
46
+ pos += 512 + Math.ceil(length / 512) * 512;
47
+ }
48
+ if (files.size !== names.size) throw new Error('ppocr-models-missing');
49
+ const traineddata = files.get('eng.traineddata'); files.delete('eng.traineddata');
50
+ return { models: Object.fromEntries(files), traineddata };
51
+ }
package/ocr.js ADDED
@@ -0,0 +1,134 @@
1
+ // THE OCR PORT'S FORM (SPEC 7.3, `emon.ocr`, D211-D214): what a JS recogniser answers, and how it becomes the integers the WASM
2
+ // binding writes into the `ocr` answer (the kin builders write the record, so its layout exists once).
3
+ //
4
+ // A port is `async (request) => result`. The request:
5
+ //
6
+ // { id, psm, flags, dpi, rect, langs, symbols, osd, bitmap() }
7
+ //
8
+ // id the request's id (kin's)
9
+ // psm the page-segmentation mode (Tesseract's numbering)
10
+ // flags bit 1 symbols and their alternatives wanted, bit 2 orientation and script detection; above the low byte, the
11
+ // bitmap's resolution in dpi (`dpi` is that, 0 when it says none)
12
+ // rect { x, y, w, h } to read inside the bitmap, or null for all of it
13
+ // langs ISO 639-3 codes (`chs` and `cht` for the two Chinese scripts), or an ISO 15924 script (`Cyrl`) for the models that
14
+ // read it; none means every model the engine has (D038). An engine with a list of models asks `models(installed)`
15
+ // which of them read the request (indices into the list) and `wordLang(model)` what the answer calls a model's language
16
+ // bitmap() the pixels the request names, as a lossless PNG (`Uint8Array`)
17
+ //
18
+ // and the result (every box is `[x, y, w, h]` in the bitmap's pixels, every confidence 0..1000):
19
+ //
20
+ // { orientation: { orient, writingDirection, textlineOrder, deskew }, // optional; centidegrees for deskew
21
+ // osd: { degrees, script, scriptConfidence, orientationConfidence }, // optional
22
+ // blocks: [{ box, orient, writingDirection, textlineOrder }],
23
+ // lines: [{ box, baseline: [x1, y1, x2, y2], block, paragraph, type }], // type 0 text, 1 table, 2 image, 3 rule, 4 other
24
+ // words: [{ box, conf, line, block, text, flags, lang, pointSize, dict, numeric,
25
+ // symbols: [{ box, conf, text, alts: [{ text, conf }] }] }] }
26
+ //
27
+ // `null` (or `undefined`) answers `unsupported`: an answer, and the page then has no text (D038). A rejection answers `failed`.
28
+
29
+ const pack4 = (s) => {
30
+ let v = 0;
31
+ for (let i = 0; i < 4; i++) v = v * 256 + (i < s.length ? s.charCodeAt(i) & 255 : 0);
32
+ return v | 0;
33
+ };
34
+
35
+ export const unpack4 = (v) => {
36
+ let s = '';
37
+ for (let i = 0; i < 4; i++) {
38
+ const b = (v >>> (24 - 8 * i)) & 255;
39
+ if (b) s += String.fromCharCode(b);
40
+ }
41
+ return s;
42
+ };
43
+
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');
47
+
48
+ /**
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
50
+ * installed models read them and what a model's language is called in an answer are kin's (`emon.ocrport`, P10.7, D396), asked of
51
+ * the module `w`: `models(installed)` answers the indices into the `installed` model names, `wordLang(model)` the request's name
52
+ * for the language a model read a word in, `blockType(polyBlockType)` a line's `type` from Tesseract's block type.
53
+ */
54
+ export function ocrRequest(rec, bitmap, w) {
55
+ const args = rec.slice(3);
56
+ const flags = args[2];
57
+ const langs = [];
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]));
60
+ return {
61
+ ...(marker >= 0 ? { record: Int32Array.from(rec), engine: rec[marker + 2], configuration: String.fromCodePoint(...rec.slice(marker + 4)) } : {}),
62
+ models: (installed) => w.ocrModels(rec, installed),
63
+ wordLang: (model) => unpack4(w.ocrWordLang(model)),
64
+ blockType: (polyBlockType) => w.ocrBlockType(polyBlockType),
65
+ id: rec[2],
66
+ psm: args[1],
67
+ flags,
68
+ dpi: Math.floor(flags / 256),
69
+ rect: args[5] > 0 ? { x: args[3], y: args[4], w: args[5], h: args[6] } : null,
70
+ langs,
71
+ symbols: (flags & 1) !== 0,
72
+ osd: (flags & 2) !== 0,
73
+ bitmap,
74
+ };
75
+ }
76
+
77
+ /** The integer form `emon_answer_ocr` reads (its layout is `oil-flat` in `kin/oil.kin`); `c` is the module's `ocrWord` constants. */
78
+ export function encodeOcr(r, c) {
79
+ const o = r.orientation;
80
+ const osd = r.osd;
81
+ const blocks = r.blocks || [];
82
+ const lines = r.lines || [];
83
+ const words = r.words || [];
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);
117
+ }
118
+ for (const w of words) {
119
+ const t = cps(w.text);
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));
125
+ const syms = w.symbols || [];
126
+ v.push(syms.length, t.length, ...t);
127
+ for (const s of syms) {
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); }
131
+ }
132
+ }
133
+ return Int32Array.from(v);
134
+ }
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@3sln/emon-ppocr",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0-preview.1",
4
+ "description": "Experimental opt-in PP-OCR adapter; caller-provided pinned ORT Web and model URLs",
5
+ "license": "MIT",
6
+ "repository": { "type": "git", "url": "git+https://github.com/3sln/emon.git", "directory": "release/pkg/ppocr" },
7
+ "homepage": "https://github.com/3sln/emon/blob/main/docs/ppocr.md",
8
+ "type": "module",
9
+ "main": "index.js",
10
+ "types": "index.d.ts",
11
+ "exports": {
12
+ ".": { "types": "./index.d.ts", "import": "./index.js" },
13
+ "./emon.wasm": "./emon.wasm"
14
+ },
15
+ "files": ["*.js", "*.d.ts", "emon.wasm", "LICENSE", "THIRD_PARTY_NOTICES.md", "README.md"],
16
+ "sideEffects": false,
17
+ "publishConfig": { "access": "public" },
18
+ "peerDependencies": { "@3sln/emon": "^0.3.0-preview.1" },
19
+ "engines": { "node": ">=22" }
20
+ }
package/ppocr-link.js ADDED
@@ -0,0 +1,17 @@
1
+ // Generated by bb tools/ppocr/wasm_link.clj from host/wasm/src/ppocr-*.wat.
2
+ export const trampolineBytes = Uint8Array.of(
3
+ 0,97,115,109,1,0,0,0,1,7,1,96,2,127,127,1,127,2,16,1,4,108,105,110,
4
+ 107,5,99,97,108,108,115,1,112,0,1,3,2,1,0,7,14,1,10,118,97,108,105,100,
5
+ 95,119,111,114,100,0,0,10,13,1,11,0,32,0,32,1,65,0,17,0,0,11
6
+ );
7
+
8
+ export const dictionaryBytes = Uint8Array.of(
9
+ 0,97,115,109,1,0,0,0,1,16,3,96,1,127,1,127,96,1,127,0,96,2,127,127,
10
+ 1,127,2,78,6,4,108,105,110,107,4,101,109,111,110,2,0,1,4,108,105,110,107,4,
11
+ 116,101,115,115,2,0,1,4,108,105,110,107,3,97,112,105,3,127,0,4,108,105,110,107,
12
+ 6,109,97,108,108,111,99,0,0,4,108,105,110,107,4,102,114,101,101,0,1,4,108,105,
13
+ 110,107,5,118,97,108,105,100,0,2,3,2,1,2,7,14,1,10,118,97,108,105,100,95,
14
+ 119,111,114,100,0,3,10,57,1,55,1,2,127,32,1,65,1,106,16,0,34,2,69,4,
15
+ 127,65,0,5,32,2,32,0,32,1,252,10,1,0,32,2,32,1,106,65,0,58,64,1,
16
+ 0,35,0,32,2,16,2,33,3,32,2,16,1,32,3,11,11
17
+ );
package/ppocr.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import type { OcrPort } from '@3sln/emon';
2
+
3
+ type AssetSource = string | URL | Uint8Array | ArrayBuffer;
4
+ type WasmSource = AssetSource | WebAssembly.Module | Response | Promise<Response>;
5
+ type Lexicon = {
6
+ bindWasm(memory: WebAssembly.Memory): Promise<(ptr: number, len: number) => number>;
7
+ terminate?(): Promise<void>;
8
+ };
9
+ interface AdapterOptions {
10
+ wasm: WasmSource;
11
+ /** A lazy import of onnxruntime-web/wasm, exactly 1.22.0. */
12
+ loadOrt(): Promise<unknown>;
13
+ wasmPaths: string | { wasm?: string | URL; mjs?: string | URL };
14
+ /** Hash-verified ort-wasm-simd-threaded.wasm from ORT Web 1.22.0. */
15
+ ortWasm: AssetSource;
16
+ models: Record<'ch_PP-OCRv5_det_mobile.onnx' | 'ch_ppocr_mobile_v2.0_cls_mobile.onnx' | 'en_PP-OCRv5_rec_mobile.onnx', AssetSource>;
17
+ lexicon: Lexicon;
18
+ }
19
+
20
+ /** Experimental optional port; requires the optional emon wasm build. */
21
+ export function ppocrPort(options: AdapterOptions & { incumbent: OcrPort & { terminate?(): Promise<void>; producer?: Record<string, string> } }):
22
+ OcrPort & { terminate(): Promise<void>; producer: Record<string, string> };
23
+
24
+ /** Dedicated pinned English dictionary. Supply tesseract.js-core 7.0.0's
25
+ * ordinary SIMD LSTM factory and local runtime options. */
26
+ export function ppocrLexicon(options: {
27
+ createCore(options?: object): Promise<any>;
28
+ coreOptions?: object;
29
+ traineddata: AssetSource;
30
+ }): Lexicon & { terminate(): Promise<void> };
31
+
32
+ /** Low-level qualification adapter; returns canonical integer answer cells. */
33
+ export function ppocrAdapter(options: AdapterOptions):
34
+ ((request: { png: Uint8Array; id?: number; rect?: { x: number; y: number; w: number; h: number } | null; record?: Int32Array }) => Promise<Int32Array | null>) & { terminate(): Promise<void> };
package/ppocr.js ADDED
@@ -0,0 +1,173 @@
1
+ // Experimental opt-in. No imports from ORT, no model or runtime URL defaults.
2
+ import { Wasm } from './wasm.js';
3
+ import { canonicalOcr } from './ocr.js';
4
+ import { trampolineBytes, dictionaryBytes } from './ppocr-link.js';
5
+
6
+ const pins = [
7
+ ['ch_PP-OCRv5_det_mobile.onnx', '4d97c44a20d30a81aad087d6a396b08f786c4635742afc391f6621f5c6ae78ae'],
8
+ ['ch_ppocr_mobile_v2.0_cls_mobile.onnx', 'e47acedf663230f8863ff1ab0e64dd2d82b838fceb5957146dab185a89d6215c'],
9
+ ['en_PP-OCRv5_rec_mobile.onnx', 'c3461add59bb4323ecba96a492ab75e06dda42467c9e3d0c18db5d1d21924be8'],
10
+ ];
11
+ async function pinnedBytes(source, sha) {
12
+ if (typeof source === 'string' || source instanceof URL) {
13
+ const response = await fetch(source);
14
+ if (!response.ok) throw new Error(`ppocr-models-missing: ${response.status}`);
15
+ source = await response.arrayBuffer();
16
+ }
17
+ if (!source) throw new Error('ppocr-models-missing');
18
+ // Own the verified snapshot even when the caller supplies a Node Buffer.
19
+ const bytes = source instanceof Uint8Array ? new Uint8Array(source) : new Uint8Array(source).slice();
20
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
21
+ if (Array.from(hash, x => x.toString(16).padStart(2, '0')).join('') !== sha) throw new Error('ppocr-model-pin-mismatch');
22
+ return bytes;
23
+ }
24
+
25
+ /** Dedicated dictionary instance: never recognizes or adapts document words.
26
+ * Supply tesseract.js-core 7.0.0's ordinary SIMD LSTM factory and its local
27
+ * module options (locateFile/wasmBinary); traineddata is the native pinned file.
28
+ */
29
+ export function ppocrLexicon({ createCore, coreOptions, traineddata }) {
30
+ let ready;
31
+ const load = () => ready ||= (async () => {
32
+ const data = await pinnedBytes(traineddata, '7d4322bd2a7749724879683fc3912cb542f19906c83bcc1a52132556427170b2');
33
+ const binary = await pinnedBytes(coreOptions?.wasmBinary ?? coreOptions?.locateFile?.('tesseract-core-simd-lstm.wasm', ''),
34
+ '34e8d50cac216427d86bf397d610fdd9f49492539bbcdfbfccc4eda20c810bea');
35
+ let exports, rejectWasm;
36
+ const failed = new Promise((_, reject) => { rejectWasm = reject; });
37
+ const core = await Promise.race([createCore({ ...coreOptions, wasmBinary: binary,
38
+ instantiateWasm(imports, receive) {
39
+ WebAssembly.instantiate(binary, imports).then(result => {
40
+ exports = result.instance.exports;
41
+ receive(result.instance, result.module);
42
+ }).catch(rejectWasm);
43
+ return {};
44
+ },
45
+ }), failed]);
46
+ core.FS.mkdir('/ppocr');
47
+ core.FS.writeFile('/ppocr/eng.traineddata', data);
48
+ const api = new core.TessBaseAPI();
49
+ if (api.Init('/ppocr', 'eng', 1) !== 0) { core.destroy(api); throw new Error('ppocr-lexicon-init'); }
50
+ const memory = Object.values(exports).find(v => v instanceof WebAssembly.Memory);
51
+ const functions = { malloc: core._malloc, free: core._free, valid: core._emscripten_bind_TessBaseAPI_IsValidWord_1 };
52
+ if (!memory || Object.values(functions).some(fn => !Object.values(exports).includes(fn))) {
53
+ api.End(); core.destroy(api); throw new Error('ppocr-lexicon-wasm-exports');
54
+ }
55
+ return { core, api, memory, functions };
56
+ })();
57
+ const valid = {};
58
+ valid.bindWasm = async emonMemory => {
59
+ const { core, api, memory, functions } = await load();
60
+ return new WebAssembly.Instance(new WebAssembly.Module(dictionaryBytes), { link: {
61
+ emon: emonMemory, tess: memory, api: new WebAssembly.Global({ value: 'i32' }, core.getPointer(api)), ...functions,
62
+ } }).exports.valid_word;
63
+ };
64
+ valid.terminate = async () => {
65
+ if (ready) { const { core, api } = await ready; api.End(); core.destroy(api); ready = undefined; }
66
+ };
67
+ return valid;
68
+ }
69
+
70
+ /** Tensor/answer adapter used by the qualification harness. Supply an optional
71
+ * emon wasm build, loadOrt: () => import('onnxruntime-web/wasm') at exactly
72
+ * 1.22.0, caller-hosted wasmPaths, the three models by filename, and lexicon.
73
+ * The optional module is separate so ordinary emon.wasm retains its size.
74
+ */
75
+ export function ppocrAdapter({ wasm, loadOrt, wasmPaths, ortWasm, models, lexicon }) {
76
+ let ready, closed = false, chain = Promise.resolve();
77
+ const load = () => ready ||= (async () => {
78
+ const module = await loadOrt();
79
+ const ort = module.env ? module : module.default;
80
+ if (ort.env.versions.web !== '1.22.0') throw new Error('ppocr-runtime-version');
81
+ ort.env.wasm.numThreads = 1;
82
+ ort.env.wasm.simd = 'fixed';
83
+ ort.env.wasm.proxy = false;
84
+ if (!wasmPaths) throw new Error('ppocr-runtime-paths-missing');
85
+ ort.env.wasm.wasmPaths = wasmPaths;
86
+ ort.env.wasm.wasmBinary = await pinnedBytes(ortWasm, '71aef04959c5c1b6de461b6538e2058e306610034a85aad2742d0c7fd4533fe4');
87
+ const sessions = [];
88
+ try {
89
+ for (const [name, sha] of pins) {
90
+ sessions.push(await ort.InferenceSession.create(await pinnedBytes(models[name], sha), {
91
+ executionProviders: ['wasm'], graphOptimizationLevel: 'all', executionMode: 'sequential',
92
+ }));
93
+ }
94
+ const calls = new WebAssembly.Table({ initial: 1, element: 'anyfunc' });
95
+ const trampoline = new WebAssembly.Instance(new WebAssembly.Module(trampolineBytes), { link: { calls } });
96
+ const w = await Wasm.instantiate(wasm, { ppocr: { valid_word: trampoline.exports.valid_word } });
97
+ if (!lexicon?.bindWasm) throw new Error('ppocr-wasm-lexicon-required');
98
+ calls.set(0, await lexicon.bindWasm(w.x.memory));
99
+ return { ort, sessions, w };
100
+ } catch (e) { await Promise.all(sessions.map(s => s.release())); throw e; }
101
+ })();
102
+ const read = ({ png, id = 2, rect = null, record }) => {
103
+ if (closed) return Promise.reject(new Error('ppocr-port-closed'));
104
+ const job = chain.then(async () => {
105
+ const { ort, sessions, w } = await load();
106
+ if (!w.x.emon_pp_begin) throw new Error('ppocr-wasm-build-missing');
107
+ try {
108
+ if (record) {
109
+ const rc = w.withBytes(new Uint8Array(record.buffer, record.byteOffset, record.byteLength), (p, n) =>
110
+ w.withBytes(png, (bp, bn) => w.x.emon_pp_check(p, n, bp, bn)));
111
+ if (rc < 0) throw new Error('PP-OCR request engine/model identity mismatch');
112
+ if (rc === 0) throw new Error('PP-OCR request has no engine identity');
113
+ if (rc === 2) return null;
114
+ }
115
+ let status = w.withBytes(png, (p, n) => w.x.emon_pp_begin(p, n, id, rect?.x || 0, rect?.y || 0, rect?.w || 0, rect?.h || 0, record?.[5] ?? 0));
116
+ while (status > 0) {
117
+ const data = w.outBytes(); w.outFree();
118
+ const header = new DataView(data.buffer, data.byteOffset, data.byteLength);
119
+ const kind = header.getInt32(0, true);
120
+ let response, rank;
121
+ {
122
+ const session = sessions[kind];
123
+ if (!session) throw new Error('ppocr-invalid-model');
124
+ const dims = Array.from({ length: header.getInt32(4, true) }, (_, i) => header.getInt32(8 + 4 * i, true));
125
+ const values = new Float32Array(data.buffer.slice(8 + dims.length * 4));
126
+ const output = await session.run({ [session.inputNames[0]]: new ort.Tensor('float32', values, dims) });
127
+ const tensor = output[session.outputNames[0]];
128
+ if (tensor.type !== 'float32') throw new Error('ppocr-invalid-tensor');
129
+ rank = tensor.dims.length;
130
+ response = new Uint8Array((rank + tensor.data.length) * 4);
131
+ const view = new DataView(response.buffer);
132
+ tensor.dims.forEach((d, i) => view.setInt32(i * 4, d, true));
133
+ response.set(new Uint8Array(tensor.data.buffer, tensor.data.byteOffset, tensor.data.byteLength), rank * 4);
134
+ for (const t of Object.values(output)) t.dispose();
135
+ }
136
+ status = w.withBytes(response, (p, n) => w.x.emon_pp_resume(p, n, rank));
137
+ }
138
+ if (status < 0) throw new Error(w.outText());
139
+ const answer = w.outI32(); w.outFree(); return answer;
140
+ } finally { w.x.emon_pp_cancel(); }
141
+ });
142
+ chain = job.catch(() => {});
143
+ return job;
144
+ };
145
+ read.terminate = async () => {
146
+ closed = true;
147
+ await chain;
148
+ try {
149
+ if (ready) { const { sessions } = await ready; await Promise.all(sessions.map(s => s.release())); ready = undefined; }
150
+ } finally { await lexicon?.terminate?.(); }
151
+ };
152
+ return read;
153
+ }
154
+
155
+ /** Compose the optional PP fulfiller with the existing Tesseract fulfiller.
156
+ * Ordinary requests retain the incumbent. Tagged requests use Rust's complete
157
+ * canonical answer, so JS never reconstructs boxes, confidence or extensions.
158
+ */
159
+ export function ppocrPort({ incumbent, ...options }) {
160
+ const read = ppocrAdapter(options);
161
+ const port = async req => {
162
+ // kin identified the canonical trailer. A view hash may contain any cell.
163
+ if (req.engine !== 2) return incumbent(req);
164
+ const answer = await read({ png: req.bitmap(), id: req.id, rect: req.rect, record: req.record });
165
+ return answer === null ? null : { [canonicalOcr]: answer };
166
+ };
167
+ port.terminate = async () => { try { await read.terminate(); } finally { await incumbent.terminate?.(); } };
168
+ port.producer = { ...incumbent.producer, 'ocr-engine': 'tesseract+ppocr',
169
+ 'ocr-model': 'ppocr5-en-0420cd75efc786ba37d1e028a4c9396d2f17a3b4264880f1296a7f186faced7f',
170
+ 'pp-lexicon': 'tessdata_fast/eng sha256=7d4322bd2a7749724879683fc3912cb542f19906c83bcc1a52132556427170b2',
171
+ 'onnxruntime': '1.22.0 WASM fixed SIMD sequential threads=1 graph=all', host: 'host/js/src/ppocr.js' };
172
+ return port;
173
+ }
package/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
+ }