@3sln/emon 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,12 @@
1
+ // Type declarations of `@3sln/emon/pdfium` (P11.4, D542).
2
+ import type { Renderer } from './index.js';
3
+
4
+ export function pdfiumRenderer(options?: {
5
+ /** pdfium's factory (`lib/pdfium.mjs`'s default export), a function that returns it, or a promise of either: called once, on the first render.
6
+ * Omitted: the package `@3sln/pdfium-wasm` (an optional peer dependency), imported on the first render; its .wasm is then the default `wasm`. */
7
+ module?: Function | Promise<unknown>;
8
+ /** `pdfium.wasm`: its bytes, its URL, or a `Response` */
9
+ wasm?: ArrayBuffer | Uint8Array | string | URL | Response | Promise<unknown>;
10
+ /** the largest page, in pixels, this renderer will make (default 64 Mpx) */
11
+ maxPixels?: number;
12
+ }): Renderer & { layers: number; producer: Record<string, string>; terminate(): Promise<void> };
package/src/pdfium.js ADDED
@@ -0,0 +1,287 @@
1
+ // pdfium's WEBASSEMBLY BUILD AS emon's `render` PORT (DEVLOG P11.4c, SPEC 7.2, 7.3, 13.1): the browser's renderer, fulfilling `render` and `crop` requests
2
+ // through plan/fulfil, as `tesseract.js` fulfils `ocr`. pdfium is not a dependency of the SDK: the embedder hands over the build (bblanchon/pdfium-binaries'
3
+ // `pdfium-wasm`, the version `tools/pdfium/pdfium.edn` pins, which `bb pdfium-fetch --platform wasm` installs), which keeps its code and its 5 MiB of
4
+ // WebAssembly (the embedder's to host or cache) out of the library, and a born-digital document that asks for no raster never loads it.
5
+ //
6
+ // import { Emon } from '@3sln/emon';
7
+ // import { pdfiumRenderer } from '@3sln/emon/pdfium';
8
+ //
9
+ // const render = pdfiumRenderer({ module: () => import('./vendor/pdfium/pdfium.mjs'), wasm: './vendor/pdfium/pdfium.wasm' });
10
+ // const model = await emon.convert(scan, { ports: { render } });
11
+ // await render.terminate();
12
+ //
13
+ // WITHOUT `module`, `pdfiumRenderer()` imports the package `@3sln/pdfium-wasm` (npm install @3sln/pdfium-wasm; an optional peer dependency, imported on the
14
+ // first render): that package IS this build, `pdfium.mjs` and `pdfium.wasm`, pinned to the version `tools/pdfium/pdfium.edn` names (D553).
15
+ //
16
+ // THE BUILD. The archive's `lib/pdfium.js` is a classic script (no export; it fills a global `Module` and starts itself). `bb pdfium-fetch` wraps it,
17
+ // text unchanged, as `lib/pdfium.mjs`: `export default function pdfium(Module, node)`. `module` is that factory (or a function that returns it, as
18
+ // `() => import(...)` does, or a promise of either); it is called once, with `{ wasmBinary, print, printErr }`, and gives the instantiated
19
+ // module (`_malloc`, `_FPDF_*`, `HEAPU8`). `wasm` is the `.wasm`: bytes, a URL (fetched), or a `Response`.
20
+ //
21
+ // A PORT OF `host/rust/src/pdfium.rs`, call for call, so that the two builds agree on what they can: the same size (`W = floor(wpt * dpi / 72 + 1/2)`),
22
+ // the same bitmap (BGRX, filled white, `FPDF_ANNOT` and `FPDF_REVERSE_BYTE_ORDER`, 3 bytes kept a pixel), the same layers (no-text and text-only are made
23
+ // by removing page objects, recursively through forms; the watermark layers are `unsupported`), the same failures as answers. The document is
24
+ // reopened for each render, as natively (pruning edits the page, so a layer must not leak into the next render).
25
+ //
26
+ // WHAT IS THE BROWSER'S OWN. (1) The document is read whole on the first render (SPEC 13.1's one exception): pdfium's in-memory loader wants the file in its
27
+ // heap (`FPDF_LoadMemDocument64`); the engine's reads stay range reads. (2) `maxPixels` (default 64 Mpx, 192 MiB of RGB) bounds a page more tightly than
28
+ // the `pixels` limit (kin's 268 Mpx) because a browser tab has less memory than a native process; the smaller of the two applies.
29
+ // (3) An abort or a trap inside pdfium answers `failed` for that request and discards the instance; the next conversion instantiates a fresh one.
30
+
31
+ const FPDF_ANNOT = 0x01;
32
+ const FPDF_REVERSE_BYTE_ORDER = 0x10;
33
+ const BITMAP_BGRX = 3;
34
+ const OBJ_TEXT = 1;
35
+ const OBJ_FORM = 5;
36
+ const I32_MAX = 2147483647;
37
+
38
+ const REQUIRED = [
39
+ '_malloc', '_free', '_FPDF_InitLibrary', '_FPDF_GetLastError', '_FPDF_LoadMemDocument64', '_FPDF_CloseDocument', '_FPDF_GetPageCount', '_FPDF_LoadPage', '_FPDF_ClosePage',
40
+ '_FPDF_GetPageWidthF', '_FPDF_GetPageHeightF', '_FPDFBitmap_CreateEx', '_FPDFBitmap_FillRect', '_FPDFBitmap_Destroy', '_FPDF_RenderPageBitmap', '_FPDFPage_CountObjects',
41
+ '_FPDFPage_GetObject', '_FPDFPage_RemoveObject', '_FPDFPageObj_Destroy', '_FPDFPageObj_GetType', '_FPDFFormObj_CountObjects', '_FPDFFormObj_GetObject', '_FPDFFormObj_RemoveObject',
42
+ ];
43
+
44
+ // pdfium's last error, in words (the same table as the native binding)
45
+ const lastError = (f) => {
46
+ const e = f._FPDF_GetLastError() >>> 0;
47
+ switch (e) {
48
+ case 0: return 'no error';
49
+ case 2: return 'file not found or could not be opened';
50
+ case 3: return 'not a PDF, or its structure is damaged';
51
+ case 4: return 'password required or incorrect';
52
+ case 5: return 'unsupported security scheme';
53
+ case 6: return 'page not found or content error';
54
+ default: return `pdfium error ${e}`;
55
+ }
56
+ };
57
+
58
+ // the size in pixels of `pt` points at `dpi`: floor(pt * dpi / 72 + 1/2), at least 1 (and Rust's `as i32`, which makes NaN 0)
59
+ const pixelsOf = (pt, dpi) => {
60
+ const v = Math.floor((pt * dpi) / 72 + 0.5);
61
+ if (Number.isNaN(v)) return 0;
62
+ if (v < 1) return 1;
63
+ if (v > I32_MAX) return I32_MAX;
64
+ return v;
65
+ };
66
+
67
+ // Does `layer` keep this object? null for a form object: it is walked, its contents decide.
68
+ const keeps = (f, layer, o) => {
69
+ const ty = f._FPDFPageObj_GetType(o);
70
+ if (ty === OBJ_FORM) return null;
71
+ if (layer === 1) return ty !== OBJ_TEXT;
72
+ if (layer === 2) return ty === OBJ_TEXT;
73
+ return true;
74
+ };
75
+
76
+ const pruneForm = (f, layer, form) => {
77
+ for (let i = f._FPDFFormObj_CountObjects(form) - 1; i >= 0; i--) {
78
+ const o = f._FPDFFormObj_GetObject(form, i);
79
+ if (!o) continue;
80
+ const k = keeps(f, layer, o);
81
+ if (k === false) {
82
+ if (f._FPDFFormObj_RemoveObject(form, o) !== 0) f._FPDFPageObj_Destroy(o);
83
+ } else if (k === null) pruneForm(f, layer, o);
84
+ }
85
+ };
86
+
87
+ const prunePage = (f, layer, page) => {
88
+ for (let i = f._FPDFPage_CountObjects(page) - 1; i >= 0; i--) {
89
+ const o = f._FPDFPage_GetObject(page, i);
90
+ if (!o) continue;
91
+ const k = keeps(f, layer, o);
92
+ if (k === false) {
93
+ if (f._FPDFPage_RemoveObject(page, o) !== 0) f._FPDFPageObj_Destroy(o);
94
+ } else if (k === null) pruneForm(f, layer, o);
95
+ }
96
+ };
97
+
98
+ const failed = (reason) => ({ status: 'failed', reason });
99
+ const unsupported = (reason) => ({ status: 'unsupported', reason });
100
+
101
+ /**
102
+ * @param {object} [o]
103
+ * @param {Function|Promise} [o.module] pdfium's factory (`lib/pdfium.mjs`'s default export), a function that returns it (`() => import('./pdfium.mjs')`), or a
104
+ * promise of either: called once, on the first render. Without it: the package `@3sln/pdfium-wasm` (an optional peer dependency), whose .wasm is the default `wasm`
105
+ * @param {ArrayBuffer|Uint8Array|string|URL|Response|Promise} [o.wasm] `pdfium.wasm`: its bytes, its URL, or a `Response` (with your own `module`, without it the
106
+ * factory looks for the file beside ITS OWN script, which in a Worker is the Worker's: pass it)
107
+ * @param {number} [o.maxPixels] the largest page, in pixels, this renderer will make (default 64 Mpx); the conversion's `pixels` limit applies too
108
+ * @returns {{ layers: number, producer: object, open(doc: object, limits: object): Promise<object>, terminate(): Promise<void> }} a Renderer (`render.js`)
109
+ */
110
+ export function pdfiumRenderer({ module, wasm, maxPixels = 64 * 2 ** 20 } = {}) {
111
+ let ready = null; // Promise<module> of the instantiated library; null before the first use and after an abort
112
+
113
+ const instantiate = async () => {
114
+ let factory = module;
115
+ let wasmSrc = wasm;
116
+ if (!factory) {
117
+ // THE DEFAULT (D553): the package @3sln/pdfium-wasm, an OPTIONAL peer dependency, imported only now, on the first render, so that this package stays
118
+ // dependency-free and a document that asks for no raster never loads it. Its default export is the factory and `wasmBinary()` the bytes of the .wasm
119
+ // (the package reads them, so this SDK names no file and no Node module, D058).
120
+ let pkg;
121
+ try {
122
+ pkg = await import('@3sln/pdfium-wasm');
123
+ } catch (e) {
124
+ throw new Error(`pdfiumRenderer() without \`module\` uses the package @3sln/pdfium-wasm, which cannot be imported (npm install @3sln/pdfium-wasm; or pass \`module\` and \`wasm\`): ${e && e.message}`);
125
+ }
126
+ factory = pkg;
127
+ if (wasmSrc === undefined) wasmSrc = pkg.wasmBinary();
128
+ }
129
+ const arg = { print() {}, printErr() {} };
130
+ if (wasmSrc !== undefined) {
131
+ let src = await wasmSrc;
132
+ if (typeof src === 'string' || src instanceof URL) src = await fetch(src);
133
+ if (typeof Response !== 'undefined' && src instanceof Response) {
134
+ if (!src.ok) throw new Error(`pdfium.wasm: HTTP ${src.status}`);
135
+ src = await src.arrayBuffer();
136
+ }
137
+ arg.wasmBinary = src instanceof Uint8Array ? src : new Uint8Array(src);
138
+ }
139
+ let m = await factory;
140
+ // `() => import(...)`, a factory, or the namespace itself: the factory is the function that takes the module's arguments and gives the module
141
+ if (typeof m === 'function') {
142
+ const r = await m(arg);
143
+ m = r && typeof r === 'object' && typeof r.default === 'function' ? await r.default(arg) : r;
144
+ } else if (m && typeof m.default === 'function') {
145
+ m = await m.default(arg);
146
+ }
147
+ if (!m || typeof m._malloc !== 'function') throw new Error('pdfium: the factory did not give a module (lib/pdfium.mjs, from `bb pdfium-fetch --platform wasm`)');
148
+ const missing = REQUIRED.filter((n) => typeof m[n] !== 'function');
149
+ if (missing.length) throw new Error(`pdfium: this build lacks ${missing.join(', ')}`);
150
+ m._FPDF_InitLibrary();
151
+ return m;
152
+ };
153
+
154
+ const load = () => {
155
+ if (!ready) {
156
+ const p = instantiate();
157
+ ready = p;
158
+ // a failed load is tried again by the next conversion, not remembered
159
+ p.catch(() => {
160
+ if (ready === p) ready = null;
161
+ });
162
+ }
163
+ return ready;
164
+ };
165
+
166
+ const renderer = {
167
+ // the layers pdfium separates: full, without text, text only (the watermark layers are kin's to separate, SPEC 8.1)
168
+ layers: 0b00111,
169
+ // what a transcript says made its pixels; the version is the build `tools/pdfium/pdfium.edn` pins
170
+ producer: { renderer: 'pdfium-wasm', 'pdfium-version': 'chromium/8076', 'render-host': 'host/js/src/pdfium.js' },
171
+
172
+ async open(doc, limits) {
173
+ const f = await load();
174
+ const bytes = doc.bytes || (await doc.read(0, doc.size));
175
+ const n = bytes.length;
176
+ const ptr = f._malloc(Math.max(1, n));
177
+ if (!ptr) throw new Error(`pdfium: no memory for the ${n}-byte document`);
178
+ f.HEAPU8.set(bytes, ptr);
179
+ // the password is a C string
180
+ let pw = 0;
181
+ let pwBad = false;
182
+ if (doc.password && doc.password.length) {
183
+ pwBad = doc.password.includes(0);
184
+ pw = f._malloc(doc.password.length + 1);
185
+ if (pw) {
186
+ f.HEAPU8.set(doc.password, pw);
187
+ f.HEAPU8[pw + doc.password.length] = 0;
188
+ }
189
+ }
190
+ const max = Math.min(limits && Number.isFinite(limits.pixels) ? limits.pixels : maxPixels, maxPixels);
191
+ let dead = null; // set when pdfium trapped under this document: the instance is gone
192
+ let closed = false;
193
+
194
+ const poison = (e) => {
195
+ dead = (e && e.message) || String(e);
196
+ ready = null; // the next conversion instantiates afresh
197
+ };
198
+
199
+ return {
200
+ async render({ page, dpi, layer }, sink) {
201
+ if (layer === 3 || layer === 4) return unsupported("pdfium's mark API cannot read /Artifact /Subtype (a name)");
202
+ if (!Number.isInteger(layer) || layer < 0 || layer > 4) return unsupported(`layer ${layer}`);
203
+ if (!Number.isInteger(dpi) || dpi < 1 || dpi > 4800) return failed(`dpi ${dpi}`);
204
+ if (closed) return failed('the document is closed');
205
+ if (dead) return failed(`pdfium stopped: ${dead}`);
206
+ if (pwBad) return failed('a password with a NUL');
207
+ try {
208
+ return renderOne(f, ptr, n, pw, max, page, dpi, layer, sink);
209
+ } catch (e) {
210
+ poison(e);
211
+ return failed(`pdfium stopped: ${dead}`);
212
+ }
213
+ },
214
+ close() {
215
+ if (closed) return;
216
+ closed = true;
217
+ if (!dead) {
218
+ f._free(ptr);
219
+ if (pw) f._free(pw);
220
+ }
221
+ },
222
+ };
223
+ },
224
+
225
+ async terminate() {
226
+ // the instance is dropped; its memory goes with the last reference (WebAssembly memory cannot be returned any other way)
227
+ ready = null;
228
+ },
229
+ };
230
+ return renderer;
231
+ }
232
+
233
+ // One render: the port of `Pdfium::render` and `render_doc` / `render_page` (host/rust/src/pdfium.rs). Synchronous: pdfium is single-threaded, and no
234
+ // other call of this renderer can run between its first call and its last.
235
+ function renderOne(f, ptr, n, pw, max, page, dpi, layer, sink) {
236
+ const doc = f._FPDF_LoadMemDocument64(ptr, n, pw);
237
+ if (!doc) return failed(lastError(f));
238
+ try {
239
+ const pages = f._FPDF_GetPageCount(doc);
240
+ if (page < 0 || page >= pages) return failed(`page ${page} of ${pages}`);
241
+ const pg = f._FPDF_LoadPage(doc, page);
242
+ if (!pg) return failed(lastError(f));
243
+ try {
244
+ return renderPage(f, pg, max, dpi, layer, sink);
245
+ } finally {
246
+ f._FPDF_ClosePage(pg);
247
+ }
248
+ } finally {
249
+ f._FPDF_CloseDocument(doc);
250
+ }
251
+ }
252
+
253
+ function renderPage(f, pg, max, dpi, layer, sink) {
254
+ const [wpt, hpt] = [f._FPDF_GetPageWidthF(pg), f._FPDF_GetPageHeightF(pg)];
255
+ const [w, h] = [pixelsOf(wpt, dpi), pixelsOf(hpt, dpi)];
256
+ if (w * h > max) return failed(`${w}x${h} pixels is over the limit of ${max}`);
257
+ let flags = FPDF_REVERSE_BYTE_ORDER;
258
+ if (layer === 0) flags |= FPDF_ANNOT;
259
+ else if (layer === 1) {
260
+ prunePage(f, layer, pg);
261
+ flags |= FPDF_ANNOT;
262
+ } else prunePage(f, layer, pg);
263
+ const stride = w * 4;
264
+ const size = stride * h;
265
+ if (w < 1 || h < 1 || size > I32_MAX) return failed('the bitmap could not be created');
266
+ const buf = f._malloc(size);
267
+ if (!buf) return failed('the bitmap could not be created');
268
+ try {
269
+ const bm = f._FPDFBitmap_CreateEx(w, h, BITMAP_BGRX, buf, stride);
270
+ if (!bm) return failed('the bitmap could not be created');
271
+ f._FPDFBitmap_FillRect(bm, 0, 0, w, h, 0xffffffff);
272
+ f._FPDF_RenderPageBitmap(bm, pg, 0, 0, w, h, 0, flags);
273
+ f._FPDFBitmap_Destroy(bm);
274
+ // BGRX with the byte order reversed is RGBX in memory: the first 3 bytes of each pixel are kept
275
+ const px = w * h;
276
+ const out = sink ? sink(px * 3) : new Uint8Array(px * 3);
277
+ const src = f.HEAPU8;
278
+ for (let i = 0, s = buf, d = 0; i < px; i++, s += 4, d += 3) {
279
+ out[d] = src[s];
280
+ out[d + 1] = src[s + 1];
281
+ out[d + 2] = src[s + 2];
282
+ }
283
+ return { width: w, height: h, rgb: out };
284
+ } finally {
285
+ f._free(buf);
286
+ }
287
+ }
package/src/render.js ADDED
@@ -0,0 +1,55 @@
1
+ // THE RENDER PORT'S FORM (SPEC 7.2, 7.3, 13.1; DEVLOG P11.4c): what a JS renderer answers, as `ocr.js` is the form of the OCR port. This file has no
2
+ // code and no exports: it is the contract `ports.render` is held to, and `pdfium.js` (pdfium's WebAssembly build) is its adapter.
3
+ //
4
+ // const renderer = pdfiumRenderer({ module, wasm });
5
+ // const model = await emon.convert(file, { ports: { ocr, render: renderer } });
6
+ // await renderer.terminate();
7
+ //
8
+ // WHAT IS ASKED. `render` and `crop` requests (kin's: `emon.plan`). The renderer is only ever asked for WHOLE PAGES: a crop is the cut of a
9
+ // whole-page render (SPEC 7.2: "the same pixels, cut out, never a re-fit"; a render clipped to a rectangle moves the pixels on its edge, D127),
10
+ // which the module makes (`render::cut`), so the SDK renders a page once for the page and its crops (one page is kept between requests).
11
+ //
12
+ // A Renderer:
13
+ //
14
+ // {
15
+ // layers: number the layers it can separate, a bit set over kin's `lay-*` (bit n = layer n): 0 full page, 1 without
16
+ // text, 2 text only, 3 without watermarks, 4 watermarks only. pdfium: 0b00111. The full page is always there
17
+ // producer?: { [k]: string } what a transcript says produced the pixels; merged into the conversion's `producer.NAME` lines
18
+ // open(doc, limits): Promise<RendererDocument>
19
+ // terminate?(): Promise<void>
20
+ // }
21
+ //
22
+ // doc { size, bytes?, read(offset, length): Promise<Uint8Array>, password? }
23
+ // the document the conversion reads. `bytes` is there when it is in memory. `read` is the conversion's byte source (a Blob, a URL,
24
+ // a stream's spool): it gives the whole file when asked for it (`read(0, size)`), and a source that fails or changes under the
25
+ // read ends the conversion with its typed error (`io`, `source-changed`), not a failed page. `password` is the conversion's, as bytes
26
+ // limits { pixels } the `pixels` limit in force for the conversion (kin's table, `emon_limit`): a page over it is `failed`
27
+ //
28
+ // `open` is called LAZILY, on the first `render` or `crop` request of a conversion: a born-digital document that asks for no raster never loads
29
+ // the renderer. It is called at most once a conversion, its document is closed when the conversion ends, and the renderer's calls are
30
+ // SERIALISED (the SDK awaits one before the next: a renderer need not be re-entrant).
31
+ //
32
+ // A RendererDocument:
33
+ //
34
+ // {
35
+ // render({ page, dpi, layer }, sink?): Promise<Rendered>
36
+ // close(): void
37
+ // }
38
+ //
39
+ // page 0-based dpi 1..4800 layer 0..4
40
+ // sink (n: number) => Uint8Array where to put the pixels: the SDK's own memory, so the bitmap is copied once. A renderer that
41
+ // has a `sink` calls it with the byte length (`width * height * 3`) AFTER it has the page's size and BEFORE it writes, and
42
+ // writes into the view it gets (it is valid until the renderer next awaits). One that ignores it returns its own `rgb`.
43
+ //
44
+ // and the result of a render:
45
+ //
46
+ // { width, height, rgb } RGB, 3 bytes a pixel, row-major, `width * height * 3` bytes: the view the sink gave, or the renderer's own
47
+ // (valid until the next call)
48
+ // { status: 'failed', reason } the page could not be rendered (a damaged document, a page out of range, over the `pixels` limit):
49
+ // an ANSWER, transcribed, and the page then has no text from it
50
+ // { status: 'unsupported', reason } the renderer cannot do this (a layer it cannot separate): an answer too, and kin plans around it
51
+ //
52
+ // A rejection is `failed` too (the SDK notes it in `stats.notes`). THE GEOMETRY is SPEC 7.2's, so that two engines and two hosts agree on the
53
+ // size before they disagree on a pixel: the page "as displayed" (rotation and crop box applied) is `wpt x hpt` points, and the bitmap is
54
+ // `W x H` with `W = floor(wpt * dpi / 72 + 1/2)`, `H` likewise, at least 1.
55
+ export {};
package/src/sources.js ADDED
@@ -0,0 +1,149 @@
1
+ // BYTE SOURCES (DEVLOG P9.3, SPEC 13.1, D058): a document is `{ size, read(offset, length) -> Promise<Uint8Array> }`, a Blob-like
2
+ // thing that lets the engine read slices and jump around and never promises the bytes are in memory. Every adapter below is
3
+ // that shape (an embedder may bring any other: object storage, an archive member, a database column), and the engine reads
4
+ // only what it needs of it, a chunk at a time (64 KiB by default), awaiting.
5
+ //
6
+ // bytesSource(ArrayBuffer | Uint8Array) in memory. Resident: the SDK hands the engine every byte at once (a read of bytes the
7
+ // page already holds is not a read), unless `{ lazy: true }`
8
+ // blobSource(Blob | File) `blob.slice(a, b).arrayBuffer()`: the browser reads the file lazily
9
+ // urlSource(url, opts) `fetch` with `Range`; the validator (a strong ETag, else Last-Modified) is pinned at
10
+ // open and every read must match it, else `SourceChangedError` (`source-changed`)
11
+ // streamSource(ReadableStream, { max }) forward-only: SPOOLED into memory, at most `max` bytes (the `input-bytes` limit)
12
+ // any { size, read } as it is
13
+ //
14
+ // A `read` that fails with a `SourceChangedError` (or whose `code` is `source-changed`), or that answers fewer bytes than were
15
+ // asked for, ends the conversion with `source-changed`; any other rejection with `io`.
16
+
17
+ export class SourceChangedError extends Error {
18
+ constructor(message) {
19
+ super(message);
20
+ this.name = 'SourceChangedError';
21
+ this.code = 'source-changed';
22
+ }
23
+ }
24
+
25
+ /** A named emon failure: `code` is the stable name a crawler routes on (`password-required`, `input-bytes`, ...). */
26
+ export class EmonError extends Error {
27
+ constructor(code, message) {
28
+ super(message || code);
29
+ this.name = 'EmonError';
30
+ this.code = code;
31
+ }
32
+ }
33
+
34
+ const asU8 = (b) => (b instanceof Uint8Array ? b : ArrayBuffer.isView(b) ? new Uint8Array(b.buffer, b.byteOffset, b.byteLength) : new Uint8Array(b));
35
+
36
+ export function bytesSource(buf, { lazy = false } = {}) {
37
+ const u8 = asU8(buf);
38
+ const s = {
39
+ size: u8.length,
40
+ async read(offset, length) {
41
+ return u8.subarray(offset, offset + length);
42
+ },
43
+ };
44
+ if (!lazy) s.bytes = u8;
45
+ return s;
46
+ }
47
+
48
+ export function blobSource(blob) {
49
+ return {
50
+ size: blob.size,
51
+ async read(offset, length) {
52
+ return new Uint8Array(await blob.slice(offset, offset + length).arrayBuffer());
53
+ },
54
+ };
55
+ }
56
+
57
+ export async function streamSource(stream, { max = 2 ** 31 - 1 } = {}) {
58
+ const reader = stream.getReader();
59
+ const parts = [];
60
+ let total = 0;
61
+ for (;;) {
62
+ const { done, value } = await reader.read();
63
+ if (done) break;
64
+ const u8 = asU8(value);
65
+ total += u8.length;
66
+ if (total > max) {
67
+ try {
68
+ await reader.cancel();
69
+ } catch (_) {
70
+ /* the stream is being abandoned */
71
+ }
72
+ throw new EmonError('input-bytes', `input-bytes: the stream is longer than ${max} bytes`);
73
+ }
74
+ parts.push(u8);
75
+ }
76
+ const all = new Uint8Array(total);
77
+ let at = 0;
78
+ for (const p of parts) {
79
+ all.set(p, at);
80
+ at += p.length;
81
+ }
82
+ return bytesSource(all);
83
+ }
84
+
85
+ /**
86
+ * A document at a URL, read by `Range`. `fetch`ing the first byte tells its size (`Content-Range`) and its validator; a server
87
+ * that ignores `Range` (a 200) is a spooled source, its whole body read once. Options: `fetch` (default `globalThis.fetch`),
88
+ * `headers`, `signal`, `fetchOptions` (merged into every request: credentials, mode, ...).
89
+ */
90
+ export async function urlSource(url, { fetch: f = globalThis.fetch.bind(globalThis), headers = {}, signal, fetchOptions = {} } = {}) {
91
+ const get = (range, extra = {}) => f(String(url), { cache: 'no-store', ...fetchOptions, signal, headers: { ...headers, ...(range ? { Range: range } : {}), ...extra } });
92
+ const first = await get('bytes=0-0');
93
+ if (first.status === 200) {
94
+ // no ranges: the body is the document
95
+ return bytesSource(new Uint8Array(await first.arrayBuffer()));
96
+ }
97
+ if (first.status === 416) {
98
+ // an empty document
99
+ await first.arrayBuffer();
100
+ return bytesSource(new Uint8Array(0));
101
+ }
102
+ if (first.status !== 206) throw new Error(`${url}: HTTP ${first.status}`);
103
+ await first.arrayBuffer();
104
+ const cr = /bytes\s+(\d+)-(\d+)\/(\d+)/.exec(first.headers.get('content-range') || '');
105
+ if (!cr) throw new Error(`${url}: no Content-Range in the answer to a range request`);
106
+ const size = Number(cr[3]);
107
+ const etag = first.headers.get('etag');
108
+ const lastModified = first.headers.get('last-modified');
109
+ const strong = etag && !etag.startsWith('W/') ? etag : null;
110
+ const validator = strong || lastModified || null;
111
+ const changed = (why) => new SourceChangedError(`${url} changed while it was being read: ${why}`);
112
+ const s = {
113
+ size,
114
+ url: String(url),
115
+ validator,
116
+ async read(offset, length) {
117
+ const r = await get(`bytes=${offset}-${offset + length - 1}`, validator ? { 'If-Range': validator } : {});
118
+ if (r.status === 200) {
119
+ // If-Range did not match (the document changed), or the server stopped honouring ranges
120
+ await r.arrayBuffer();
121
+ throw changed('the server answered the whole body to a range request');
122
+ }
123
+ if (r.status !== 206) {
124
+ await r.arrayBuffer();
125
+ throw new Error(`${url}: HTTP ${r.status}`);
126
+ }
127
+ const m = /bytes\s+(\d+)-(\d+)\/(\d+)/.exec(r.headers.get('content-range') || '');
128
+ const buf = new Uint8Array(await r.arrayBuffer());
129
+ if (!m || Number(m[1]) !== offset || Number(m[3]) !== size) throw changed('its length is not what it was');
130
+ if (etag && r.headers.get('etag') !== etag) throw changed(`its ETag is ${r.headers.get('etag')}, not ${etag}`);
131
+ if (!etag && lastModified && r.headers.get('last-modified') !== lastModified) throw changed('its Last-Modified moved');
132
+ return buf;
133
+ },
134
+ };
135
+ return s;
136
+ }
137
+
138
+ /**
139
+ * The source of whatever an embedder hands over: an ArrayBuffer or view, a Blob or File, a URL (a string with a scheme or a
140
+ * `URL`), a `ReadableStream`, or any `{ size, read }`.
141
+ */
142
+ export async function toSource(x, opts = {}) {
143
+ if (x && typeof x === 'object' && typeof x.read === 'function' && typeof x.size === 'number') return x;
144
+ if (x instanceof ArrayBuffer || ArrayBuffer.isView(x)) return bytesSource(x, opts);
145
+ if (typeof Blob !== 'undefined' && x instanceof Blob) return blobSource(x);
146
+ if (typeof ReadableStream !== 'undefined' && x instanceof ReadableStream) return streamSource(x, opts);
147
+ if (x instanceof URL || (typeof x === 'string' && /^[a-z][a-z0-9+.-]*:|^\//i.test(x))) return urlSource(x, opts);
148
+ throw new TypeError('emon: an input is an ArrayBuffer, a Uint8Array, a Blob or File, a URL, a ReadableStream or { size, read(offset, length) }');
149
+ }
@@ -0,0 +1,14 @@
1
+ // Type declarations of `@3sln/emon/tesseract` (P11.4, D542).
2
+ import type { OcrPort } from './index.js';
3
+
4
+ export function tesseractPort(options: {
5
+ /** tesseract.js's `createWorker` */
6
+ createWorker: (...args: any[]) => Promise<any>;
7
+ /** the models the engine loads (tesseract.js's names); default `['eng']` */
8
+ languages?: string[];
9
+ /** the engine mode (1: LSTM, the default) */
10
+ oem?: number;
11
+ workerOptions?: object;
12
+ /** workers per language set (default 1) */
13
+ workers?: number;
14
+ }): OcrPort & { terminate(): Promise<void>; producer: Record<string, string> };
@@ -0,0 +1,114 @@
1
+ // tesseract.js AS emon's `ocr` PORT (DEVLOG P9.3, SPEC 7.3, D211-D214): the browser's OCR engine, fulfilling `ocr` requests through
2
+ // plan/fulfil. `tesseract.js` is not a dependency of the SDK: the embedder imports it and hands over `createWorker`, which keeps
3
+ // the engine's code, its core WebAssembly and its language data (large, and the embedder's to host or cache) out of the library.
4
+ //
5
+ // import { createWorker } from 'tesseract.js';
6
+ // import { Emon } from '@3sln/emon';
7
+ // import { tesseractPort } from '@3sln/emon/tesseract';
8
+ //
9
+ // const ocr = tesseractPort({ createWorker, languages: ['eng'], workerOptions: { langPath: '/tessdata', corePath: '/tesseract-core' } });
10
+ // const model = await emon.convert(scan, { ports: { ocr } });
11
+ // await ocr.terminate();
12
+ //
13
+ // WHAT IT GIVES AND WHAT IT CANNOT. tesseract.js reports the page as blocks, paragraphs, lines (with their baselines), words and
14
+ // symbols, each with a box and a confidence, and a block's type: that is the answer, in the form `ocr.js` documents. It does not
15
+ // report what the native C API does (D213): a block's orientation and writing direction (answered as page up, left to right, top
16
+ // to bottom: the engine is not run with orientation detection here, so a request for OSD, bit 2 of the flags, is answered without
17
+ // one), a word's language, dictionary and numeric flags, font attributes and point size (answered as the request's first language,
18
+ // not in the dictionary, not numeric, no style, size unknown), a symbol's alternatives (its `choices` are not in the JSON), and
19
+ // the engine's thresholded image (the answer says it has none). A line's x-height, ascenders and descenders are answered as -1:
20
+ // kin then measures them from the symbols' boxes, as it does for the native engine (D213). None of that is guessed.
21
+
22
+ const box = (b) => [b.x0, b.y0, b.x1 - b.x0, b.y1 - b.y0];
23
+ const x10 = (c) => Math.round((c ?? 0) * 10);
24
+
25
+ /** tesseract.js's `blocks` of one recognition as the `ocr.js` result (not exported since P11.4, D542: it was a helper for a test, and no test used it). */
26
+ function resultOf(blocks, { wantSymbols, lang, blockType }) {
27
+ const out = { orientation: { orient: 0, writingDirection: 0, textlineOrder: 2, deskew: 0 }, blocks: [], lines: [], words: [] };
28
+ let par = -1;
29
+ (blocks || []).forEach((b, bi) => {
30
+ out.blocks.push({ box: box(b.bbox), orient: 0, writingDirection: 0, textlineOrder: 2 });
31
+ for (const p of b.paragraphs || []) {
32
+ par += 1;
33
+ for (const l of p.lines || []) {
34
+ const li = out.lines.length;
35
+ const bl = l.baseline || {};
36
+ out.lines.push({
37
+ box: box(l.bbox),
38
+ baseline: [bl.x0 ?? 0, bl.y0 ?? 0, bl.x1 ?? 0, bl.y1 ?? 0],
39
+ block: bi,
40
+ paragraph: par,
41
+ type: blockType(b.blocktype),
42
+ });
43
+ for (const w of l.words || []) {
44
+ const text = (w.text || '').trim();
45
+ if (!text) continue;
46
+ const word = { box: box(w.bbox), conf: x10(w.confidence), line: li, block: bi, text, flags: 0, lang, pointSize: -1, dict: false, numeric: false };
47
+ if (wantSymbols) {
48
+ word.symbols = (w.symbols || []).map((s) => ({ box: box(s.bbox), conf: x10(s.confidence), text: s.text || '', alts: [] }));
49
+ // the symbols must spell the word, as the engine's own do
50
+ if (word.symbols.map((s) => s.text).join('') !== text) word.symbols = [];
51
+ }
52
+ out.words.push(word);
53
+ }
54
+ }
55
+ }
56
+ });
57
+ return out;
58
+ }
59
+
60
+ /**
61
+ * @param {object} o
62
+ * @param {Function} o.createWorker tesseract.js's `createWorker`
63
+ * @param {string[]} [o.languages] the models the engine loads (tesseract.js's names: `eng`, `deu`, `chi_sim`); a request that names
64
+ * languages is served by those of them it names, one that names none by all of them (D038). Default `['eng']`.
65
+ * @param {number} [o.oem] the engine mode (1: LSTM, the default)
66
+ * @param {object} [o.workerOptions] tesseract.js's `createWorker` options (`langPath`, `corePath`, `workerPath`, `logger`, ...)
67
+ * @param {number} [o.workers] workers per language set, so recognitions of one round run side by side (default 1)
68
+ * @returns {((request: object) => Promise<object>) & { terminate(): Promise<void>, producer: object }}
69
+ */
70
+ export function tesseractPort({ createWorker, languages = ['eng'], oem = 1, workerOptions = {}, workers = 1 }) {
71
+ const pools = new Map(); // language key -> [{ promise, busy }]
72
+ const slot = (key) => {
73
+ let pool = pools.get(key);
74
+ if (!pool) pools.set(key, (pool = []));
75
+ // an idle worker, a new one while the pool has room, else the least busy
76
+ let s = pool.find((x) => x.busy === 0);
77
+ if (!s && pool.length < workers) {
78
+ s = {
79
+ busy: 0,
80
+ promise: (async () => {
81
+ const w = await createWorker(key, oem, workerOptions);
82
+ // the final candidates of the beam search, not one per timestep: the native adapter's setting (D213)
83
+ await w.setParameters({ lstm_choice_mode: '2' });
84
+ return w;
85
+ })(),
86
+ };
87
+ pool.push(s);
88
+ }
89
+ return s || pool.reduce((a, b) => (a.busy <= b.busy ? a : b));
90
+ };
91
+ const port = async (req) => {
92
+ // 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
+ // read it, one with no model is dropped, none left is every model (D038, P10.7)
94
+ const langs = req.models(languages).map((i) => languages[i]);
95
+ if (!langs.length) return null;
96
+ const s = slot(langs.join('+'));
97
+ s.busy += 1;
98
+ try {
99
+ const w = await s.promise;
100
+ await w.setParameters({ tessedit_pageseg_mode: String(req.psm), user_defined_dpi: req.dpi > 0 ? String(req.dpi) : '' });
101
+ const opts = req.rect ? { rectangle: { left: req.rect.x, top: req.rect.y, width: req.rect.w, height: req.rect.h } } : {};
102
+ const { data } = await w.recognize(req.bitmap(), opts, { text: false, blocks: true });
103
+ return resultOf(data.blocks, { wantSymbols: req.symbols, lang: req.wordLang(langs[0]), blockType: req.blockType });
104
+ } finally {
105
+ s.busy -= 1;
106
+ }
107
+ };
108
+ port.terminate = async () => {
109
+ for (const pool of pools.values()) for (const s of pool) await (await s.promise).terminate();
110
+ pools.clear();
111
+ };
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
+ return port;
114
+ }