ppu-indra-ocr 0.0.0-stage → 0.1.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.
Files changed (95) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-STATUS.md +112 -0
  3. package/NOTICE +20 -0
  4. package/README.md +830 -2
  5. package/cli/commands.d.ts +9 -0
  6. package/cli/commands.js +11 -0
  7. package/cli/help.d.ts +5 -0
  8. package/cli/help.js +50 -0
  9. package/cli/index.d.ts +2 -0
  10. package/cli/index.js +6 -0
  11. package/cli/io.d.ts +27 -0
  12. package/cli/io.js +6 -0
  13. package/cli/options.d.ts +19 -0
  14. package/cli/options.js +1 -0
  15. package/cli/run.d.ts +1 -0
  16. package/cli/run.js +9 -0
  17. package/coi-serviceworker.js +130 -0
  18. package/core/batch.d.ts +53 -0
  19. package/core/batch.js +1 -0
  20. package/core/indra-ocr.service.d.ts +65 -0
  21. package/core/indra-ocr.service.js +1 -0
  22. package/core/one-shot.d.ts +5 -0
  23. package/core/one-shot.js +1 -0
  24. package/core/opencv-image-ops.d.ts +10 -0
  25. package/core/opencv-image-ops.js +1 -0
  26. package/core/platform.d.ts +40 -0
  27. package/core/session-factory.d.ts +23 -0
  28. package/core/session-factory.js +1 -0
  29. package/exports.d.ts +15 -0
  30. package/exports.js +1 -0
  31. package/index.d.ts +11 -0
  32. package/index.js +1 -0
  33. package/indra/assemble.d.ts +22 -0
  34. package/indra/assemble.js +3 -0
  35. package/indra/det-post.d.ts +34 -0
  36. package/indra/det-post.js +1 -0
  37. package/indra/document.d.ts +36 -0
  38. package/indra/document.js +1 -0
  39. package/indra/image.d.ts +43 -0
  40. package/indra/image.js +1 -0
  41. package/indra/layout-post.d.ts +35 -0
  42. package/indra/layout-post.js +9 -0
  43. package/indra/lines.d.ts +19 -0
  44. package/indra/lines.js +1 -0
  45. package/indra/math.d.ts +54 -0
  46. package/indra/math.js +1 -0
  47. package/indra/numeric.d.ts +9 -0
  48. package/indra/numeric.js +1 -0
  49. package/indra/order-post.d.ts +37 -0
  50. package/indra/order-post.js +1 -0
  51. package/indra/pipeline.d.ts +65 -0
  52. package/indra/pipeline.js +1 -0
  53. package/indra/rec-preproc.d.ts +28 -0
  54. package/indra/rec-preproc.js +1 -0
  55. package/indra/recognize.d.ts +29 -0
  56. package/indra/recognize.js +1 -0
  57. package/indra/textlayer.d.ts +72 -0
  58. package/indra/textlayer.js +2 -0
  59. package/indra/ts-image-ops.d.ts +3 -0
  60. package/indra/ts-image-ops.js +1 -0
  61. package/indra/types.d.ts +101 -0
  62. package/indra/upright.d.ts +28 -0
  63. package/indra/upright.js +1 -0
  64. package/indra/util.d.ts +14 -0
  65. package/indra/util.js +1 -0
  66. package/indra/vocab.d.ts +14 -0
  67. package/indra/vocab.js +1 -0
  68. package/interface.d.ts +61 -0
  69. package/mobile/index.d.ts +26 -0
  70. package/mobile/index.js +1 -0
  71. package/mobile/indra-ocr.service.mobile.d.ts +11 -0
  72. package/mobile/indra-ocr.service.mobile.js +1 -0
  73. package/mobile/platform.mobile.d.ts +16 -0
  74. package/mobile/platform.mobile.js +1 -0
  75. package/model-catalogue.d.ts +38 -0
  76. package/model-catalogue.js +1 -0
  77. package/package.json +109 -4
  78. package/pdf/index.d.ts +31 -0
  79. package/pdf/index.js +1 -0
  80. package/pdf/pdfium.d.ts +27 -0
  81. package/pdf/pdfium.js +1 -0
  82. package/processor/indra-ocr.service.d.ts +28 -0
  83. package/processor/indra-ocr.service.js +1 -0
  84. package/processor/model-cache.d.ts +17 -0
  85. package/processor/model-cache.js +2 -0
  86. package/processor/platform.node.d.ts +13 -0
  87. package/processor/platform.node.js +1 -0
  88. package/utils.d.ts +36 -0
  89. package/utils.js +2 -0
  90. package/web/index.d.ts +26 -0
  91. package/web/index.js +1 -0
  92. package/web/indra-ocr.service.web.d.ts +15 -0
  93. package/web/indra-ocr.service.web.js +1 -0
  94. package/web/platform.web.d.ts +32 -0
  95. package/web/platform.web.js +1 -0
@@ -0,0 +1,101 @@
1
+ import type { InferenceSession, Tensor } from "onnxruntime-common";
2
+ import type { DetBox } from "./det-post.js";
3
+ import type { Gray } from "./image.js";
4
+ import type { LayoutBlock } from "./layout-post.js";
5
+ import type { MathReader } from "./math.js";
6
+ import type { Box } from "./rec-preproc.js";
7
+ /**
8
+ * One recognized character position: a class id (Latin recognizer) or a
9
+ * character (CJK recognizer, PDF text layer, math), its page x, and for text
10
+ * layer characters their index in the PDF content stream.
11
+ */
12
+ export type Tok = readonly [id: number | string, x: number, contentIndex?: number];
13
+ /** Text, confidence and character positions of one detected line. */
14
+ export type RecLine = {
15
+ text: string;
16
+ conf: number;
17
+ toks: readonly Tok[];
18
+ };
19
+ /** One output line, in reading order. */
20
+ export type Line = {
21
+ box: Box;
22
+ text: string;
23
+ conf: number;
24
+ };
25
+ /** Where a page's text came from. */
26
+ export type PageSource = "ocr" | "text" | "hybrid" | "error";
27
+ /** The result for one page. Boxes are in the upright page (after any quarter turn). */
28
+ export type Page = {
29
+ /** Lines in reading order. */
30
+ lines: Line[];
31
+ /** All lines, one per row, in reading order. */
32
+ text: string;
33
+ /** Headings, paragraphs, lists, and tables as HTML. Page headers and footers are left out by default. */
34
+ markdown: string | null;
35
+ /** Layout blocks in reading order. */
36
+ blocks: LayoutBlock[];
37
+ source: PageSource;
38
+ /** Why the page took its path. */
39
+ note: string;
40
+ /** Degrees counter-clockwise the input was turned. */
41
+ rotation: number;
42
+ /** Degrees of small tilt undone; boxes are mapped back to the turned page. */
43
+ skew: number;
44
+ /** Milliseconds per stage, with total_ms. */
45
+ timings: Record<string, number>;
46
+ };
47
+ /** Reading order, and the layout head outputs when the order model has them. */
48
+ export type ReadingOrder = {
49
+ order: number[];
50
+ cls?: Float32Array;
51
+ same?: Float32Array;
52
+ logits?: Float32Array;
53
+ };
54
+ /** A piece of a split line: its box, text and tokens. */
55
+ export type LinePart = {
56
+ box: Box;
57
+ text: string;
58
+ toks: readonly Tok[];
59
+ };
60
+ /** One detector pass: boxes in detector-input pixels, and the page scale. */
61
+ export type DetectPass = {
62
+ boxes: DetBox[];
63
+ scale: number;
64
+ };
65
+ /** orient.onnx's verdict: quarter turns (counter-clockwise) the content is turned by, and the class probabilities. */
66
+ export type Orientation = {
67
+ turns: number;
68
+ probs: number[];
69
+ };
70
+ /** A page turned upright and deskewed, with the turns and degrees undone. */
71
+ export type Straightened = {
72
+ image: Gray;
73
+ turns: number;
74
+ skew: number;
75
+ };
76
+ /** The `meta.json` that ships with the models. */
77
+ export type IndraMeta = {
78
+ vocab: string;
79
+ vocab_cjk?: string;
80
+ rec_height: number;
81
+ det_long_side: number;
82
+ };
83
+ /** ONNX Runtime sessions of the Indra models. Optional ones switch a stage off. */
84
+ export type IndraSessions = {
85
+ det: InferenceSession;
86
+ rec: InferenceSession;
87
+ order?: InferenceSession;
88
+ orient?: InferenceSession;
89
+ script?: InferenceSession;
90
+ recCjk?: InferenceSession;
91
+ };
92
+ export type TensorCtor = typeof Tensor;
93
+ /** Pipeline settings beyond the models. */
94
+ export type PipelineOptions = {
95
+ /** Keep page headers and footers in the markdown. Default false. */
96
+ furniture?: boolean;
97
+ /** Run a second detection pass on pages with small text. Default true. */
98
+ adaptive?: boolean;
99
+ /** Read lines with math as LaTeX. Off unless given. */
100
+ math?: MathReader;
101
+ };
@@ -0,0 +1,28 @@
1
+ import type { Gray, ImageOps } from "./image.js";
2
+ import type { Box } from "./rec-preproc.js";
3
+ export declare const ORIENT_SIDE = 768;
4
+ /**
5
+ * A turn is applied only above this probability: real pages are almost all
6
+ * upright, and a wrong turn loses the page.
7
+ */
8
+ export declare const ORIENT_MIN = 0.95;
9
+ export declare const DESKEW_MIN = 0.3;
10
+ /** The orient.onnx input: [side, side] ink map, long side scaled to `side`, padded with 0. */
11
+ export declare function orientInput(gray: Gray, ops: ImageOps, side?: number): Float32Array;
12
+ /**
13
+ * Degrees (counter-clockwise) that straighten the text rows of a page: the
14
+ * angle whose horizontal ink profile changes most sharply row to row, on a
15
+ * page thumbnail, searched in 0.5 degree steps and then 0.1 degree steps.
16
+ */
17
+ export declare function estimateSkew(gray: Gray, ops: ImageOps, side?: number): number;
18
+ /** The page rotated by `degrees` counter-clockwise about its center (same size, edges replicated). */
19
+ export declare function rotatePage(gray: Gray, degrees: number, ops: ImageOps): Gray;
20
+ /** The page turned clockwise by `k` quarter turns (`np.rot90(gray, -k)`). */
21
+ export declare function rot90(gray: Gray, k: number): Gray;
22
+ /**
23
+ * A box of the page that rotatePage(.., degrees) made, mapped back to the
24
+ * page before it: the bounding box of the four mapped corners, clipped to it.
25
+ */
26
+ export declare function unrotateBox(box: Box, degrees: number, width: number, height: number): Box;
27
+ /** Python's round(x, digits): nearest, exact ties to even. */
28
+ export declare function roundTo(x: number, digits: number): number;
@@ -0,0 +1 @@
1
+ import{pyRound}from"./det-post.js";import{inkOf,rotationMatrix}from"./image.js";import{meanF32,sumF32}from"./numeric.js";export let ORIENT_SIDE=768;export let ORIENT_MIN=0.95;let DESKEW_MAX=5;export let DESKEW_MIN=0.3;let SKEW_SIDE=800;let f=Math.fround;function thumbnail(gray,side,ops){let s=side/Math.max(gray.height,gray.width);let w=Math.max(1,pyRound(gray.width*s));let h=Math.max(1,pyRound(gray.height*s));return ops.resize(gray,w,h,"area")}export function orientInput(gray,ops,side=ORIENT_SIDE){let small=inkOf(thumbnail(gray,side,ops));let out=new Float32Array(side*side);for(let y=0;y<small.height;y++){out.set(small.data.subarray(y*small.width,(y+1)*small.width),y*side)}return out}export function estimateSkew(gray,ops,side=SKEW_SIDE){let small=thumbnail(gray,side,ops);let data=new Float32Array(small.data.length);for(let i=0;i<data.length;i++)data[i]=f(f(255-(small.data[i]??0))/255);if(meanF32(data)<0.003)return 0;let ink={data,width:small.width,height:small.height};let cx=small.width/2;let cy=small.height/2;let sharpness=(a)=>{let r=ops.warpFloat(ink,rotationMatrix(cx,cy,a),small.width,small.height);let rows=new Float32Array(r.height);for(let y=0;y<r.height;y++)rows[y]=sumF32(r.data,y*r.width,(y+1)*r.width);let sq=new Float32Array(Math.max(0,r.height-1));for(let y=1;y<r.height;y++){let d=f((rows[y]??0)-(rows[y-1]??0));sq[y-1]=f(d*d)}return sumF32(sq)};let best=argmax(arange(-DESKEW_MAX,DESKEW_MAX+0.000001,0.5),sharpness);return argmax(arange(best-0.5,best+0.5+0.000001,0.1),sharpness)}function arange(start,stop,step){let n=Math.ceil((stop-start)/step);let delta=start+step-start;return Array.from({length:Math.max(0,n)},(_,i)=>start+i*delta)}function argmax(values,key){let best=values[0]??0;let bestKey=-1/0;for(let v of values){let k=key(v);if(k>bestKey){best=v;bestKey=k}}return best}export function rotatePage(gray,degrees,ops){let m=rotationMatrix(gray.width/2,gray.height/2,degrees);return ops.warpReplicate(gray,m,gray.width,gray.height)}export function rot90(gray,k){let out=gray;for(let t=0;t<(k%4+4)%4;t++){const{width:w,height:h,data}=out;let next=new Uint8Array(w*h);for(let y=0;y<w;y++){for(let x=0;x<h;x++)next[y*h+x]=data[(h-1-x)*w+y]??0}out={data:next,width:h,height:w}}return out}export function unrotateBox(box,degrees,width,height){const[a,b,c,d,e,g]=rotationMatrix(width/2,height/2,-degrees);const[x0,y0,x1,y1]=box;let xs=[x0,x1,x0,x1];let ys=[y0,y0,y1,y1];let mx=xs.map((x,i)=>a*x+b*(ys[i]??0)+c);let my=xs.map((x,i)=>d*x+e*(ys[i]??0)+g);let clip=(v,hi)=>roundTo(Math.min(Math.max(v,0),hi),1);return[clip(Math.min(...mx),width),clip(Math.min(...my),height),clip(Math.max(...mx),width),clip(Math.max(...my),height)]}export function roundTo(x,digits){let p=10**digits;let t=x*p;if(Math.abs(t-Math.trunc(t))===0.5)return pyRound(t)/p;return Number(x.toFixed(digits))}
@@ -0,0 +1,14 @@
1
+ import type { InferenceSession, Tensor } from "onnxruntime-common";
2
+ /** `arr[i]`, or a RangeError: for indices the algorithm guarantees are in range. */
3
+ export declare function item<T>(arr: ArrayLike<T>, i: number): T;
4
+ /** A named model output, or an error naming the missing output. */
5
+ export declare function output(res: InferenceSession.OnnxValueMapType, name: string): Tensor;
6
+ /** A float32 tensor's data. */
7
+ export declare function floats(t: Tensor): Float32Array;
8
+ /** An integer tensor's data as numbers (int64 ids and lengths fit in 2^53). */
9
+ export declare function ints(t: Tensor): number[];
10
+ /**
11
+ * Python's str.isspace for one character: JS \s, plus U+001C..U+001F and U+0085,
12
+ * minus U+FEFF (which JS counts as whitespace and Python does not).
13
+ */
14
+ export declare function isPySpace(c: string): boolean;
package/indra/util.js ADDED
@@ -0,0 +1 @@
1
+ export function item(arr,i){let v=arr[i];if(v===undefined)throw new RangeError(`index ${i} out of range (length ${arr.length})`);return v}export function output(res,name){let t=res[name];if(!t)throw new Error(`model output "${name}" is missing`);return t}export function floats(t){if(t.type!=="float32")throw new Error(`expected a float32 tensor, got ${t.type}`);return t.data}export function ints(t){if(t.type!=="int64"&&t.type!=="int32"){throw new Error(`expected an integer tensor, got ${t.type}`)}return Array.from(t.data,Number)}export function isPySpace(c){let o=c.codePointAt(0)??0;if(o===65279)return false;return o>=28&&o<=31||o===133||/^\s$/u.test(c)}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Token vocabulary of a line recognizer. Class 0 is the CTC blank; class i + 1
3
+ * is `chars[i]`. A token is one character, or one LaTeX command inside math.
4
+ */
5
+ export declare class Vocab {
6
+ readonly chars: readonly string[];
7
+ readonly index: ReadonlyMap<string, number>;
8
+ readonly hasCommands: boolean;
9
+ constructor(chars: readonly string[]);
10
+ /** A vocabulary from the `vocab` / `vocab_cjk` JSON string in meta.json. */
11
+ static fromJson(json: string): Vocab;
12
+ /** Text of class ids. A space goes back between a command and a following letter. */
13
+ decode(ids: readonly number[]): string;
14
+ }
package/indra/vocab.js ADDED
@@ -0,0 +1 @@
1
+ export class Vocab{chars;index;hasCommands;constructor(chars){this.chars=chars;this.index=new Map(chars.map((c,i)=>[c,i+1]));this.hasCommands=chars.some((c)=>[...c].length>1)}static fromJson(json){let data=JSON.parse(json);if((data.blank??0)!==0)throw new Error("only blank=0 vocabularies are supported");if(!Array.isArray(data.chars)||!data.chars.every((c)=>typeof c==="string")){throw new Error("vocab JSON has no chars array")}return new Vocab(data.chars)}decode(ids){let toks=[];for(let id of ids){let tok=this.chars[id-1];if(id>0&&tok!==undefined)toks.push(tok)}if(!this.hasCommands)return toks.join("");let out="";for(const[k,t]of toks.entries()){out+=t;let next=toks[k+1]??"";if(t.length>2&&t[0]==="\\"&&LETTERS.test(t.slice(1))&&LETTERS.test([...next][0]??"")){out+=" "}}return out}}let LETTERS=/^\p{L}+$/u;
package/interface.d.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type { InferenceSession } from "onnxruntime-common";
2
+ import type { ModelFile } from "./model-catalogue.js";
3
+ /**
4
+ * The image engine for resizing and warping.
5
+ *
6
+ * - `"opencv"` - OpenCV.js through ppu-ocv: the same OpenCV release as the
7
+ * Python reference, so results match it. **(default on Node and Bun)**
8
+ * - `"canvas-native"` - plain TypeScript, no OpenCV: smaller and runs
9
+ * anywhere, results within a token or two of the reference.
10
+ */
11
+ export type ProcessingEngine = "opencv" | "canvas-native";
12
+ /**
13
+ * Where to read each model file from: a URL, a file path (Node), or the bytes.
14
+ * Files left out come from the default model repository.
15
+ */
16
+ export type ModelSources = Partial<Record<ModelFile, string | ArrayBuffer>>;
17
+ /** ONNX Runtime session options, plus a hook for a silent provider fallback. */
18
+ export type SessionOptions = InferenceSession.SessionOptions & {
19
+ /**
20
+ * Execution providers to use (for example "cpu", "cuda", "webgpu", "wasm").
21
+ * @default ['cpu']
22
+ */
23
+ executionProviders?: InferenceSession.SessionOptions["executionProviders"];
24
+ /**
25
+ * Called when session creation with the requested execution providers fails
26
+ * and the service retries with a safe provider (`cpu` or `wasm`). Receives
27
+ * the original error. Never forwarded to ONNX Runtime.
28
+ */
29
+ onSessionFallback?: (error: unknown) => void;
30
+ };
31
+ /** Options of an IndraOcrService. */
32
+ export type IndraOptions = {
33
+ /** Per-file model sources. Default: Datalab's repository at the pinned revision. */
34
+ models?: ModelSources;
35
+ /** Read lines with math as LaTeX. Loads four more models. Default false. */
36
+ math?: boolean;
37
+ /** Keep page headers and footers in the markdown. Default false. */
38
+ furniture?: boolean;
39
+ /** Run a second detection pass on pages with small text. Default true. */
40
+ adaptive?: boolean;
41
+ /** Image engine. Default "opencv" on Node and Bun, "canvas-native" on web and mobile. */
42
+ engine?: ProcessingEngine;
43
+ /** ONNX Runtime session options for every model. */
44
+ session?: SessionOptions;
45
+ /** Log loading and stage steps to the console. Default false. */
46
+ verbose?: boolean;
47
+ };
48
+ /** Options of convertBatch and convertStream. */
49
+ export type BatchOptions = {
50
+ /**
51
+ * Pages in flight at once. Default 1: each page allocates large tensors,
52
+ * so more pages at once mostly add memory.
53
+ */
54
+ concurrency?: number;
55
+ /** Report a failed image as a rejected item instead of failing the whole batch. Default false. */
56
+ settle?: boolean;
57
+ /** Stops scheduling further images; the batch rejects with an AbortError. */
58
+ signal?: AbortSignal;
59
+ /** Called after each image settles, with the done count and the total when known. */
60
+ onProgress?: (done: number, total: number | undefined) => void;
61
+ };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @module
3
+ *
4
+ * Indra OCR for React Native (iOS and Android).
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { IndraOcrService } from "ppu-indra-ocr/mobile";
9
+ *
10
+ * const service = new IndraOcrService();
11
+ * await service.initialize();
12
+ * const page = await service.convert(imageBytes);
13
+ * ```
14
+ */
15
+ import type { ImageInput } from "../core/indra-ocr.service.js";
16
+ import type { DetBox } from "../indra/det-post.js";
17
+ import type { Page } from "../indra/types.js";
18
+ import type { IndraOptions } from "../interface.js";
19
+ import { IndraOcrService } from "./indra-ocr.service.mobile.js";
20
+ export * from "../exports.js";
21
+ export { IndraOcrService };
22
+ export { getDefaultMobileExecutionProviders } from "./platform.mobile.js";
23
+ /** OCR one image without managing a service: load the models, convert, release. */
24
+ export declare function ocr(image: ImageInput, options?: IndraOptions): Promise<Page>;
25
+ /** Detect the text lines of one image without managing a service. */
26
+ export declare function detect(image: ImageInput, options?: IndraOptions): Promise<DetBox[]>;
@@ -0,0 +1 @@
1
+ import{runOneShot}from"../core/one-shot.js";import{IndraOcrService}from"./indra-ocr.service.mobile.js";export*from"../exports.js";export{IndraOcrService};export{getDefaultMobileExecutionProviders}from"./platform.mobile.js";export function ocr(image,options){return runOneShot(()=>new IndraOcrService(options),(service)=>service.convert(image))}export function detect(image,options){return runOneShot(()=>new IndraOcrService(options),(service)=>service.detect(image))}
@@ -0,0 +1,11 @@
1
+ import { BaseIndraOcrService } from "../core/indra-ocr.service.js";
2
+ import type { CoreCanvas } from "../core/platform.js";
3
+ import type { IndraOptions } from "../interface.js";
4
+ /**
5
+ * Indra OCR for React Native (Expo or bare) on iOS and Android, with
6
+ * onnxruntime-react-native and @shopify/react-native-skia. The engine is
7
+ * canvas-native: OpenCV.js does not run on React Native.
8
+ */
9
+ export declare class IndraOcrService extends BaseIndraOcrService<CoreCanvas> {
10
+ constructor(options?: IndraOptions);
11
+ }
@@ -0,0 +1 @@
1
+ import{BaseIndraOcrService}from"../core/indra-ocr.service.js";import{MobilePlatformProvider}from"./platform.mobile.js";export class IndraOcrService extends BaseIndraOcrService{constructor(options={}){super(new MobilePlatformProvider,options)}}
@@ -0,0 +1,16 @@
1
+ import * as ort from "onnxruntime-react-native";
2
+ import type { CoreCanvas, PlatformProvider, Rgba } from "../core/platform.js";
3
+ /**
4
+ * Default execution providers for React Native: CPU. NNAPI (Android) and
5
+ * CoreML (iOS) can be opted into through `session.executionProviders`.
6
+ */
7
+ export declare function getDefaultMobileExecutionProviders(): ort.InferenceSession.SessionOptions["executionProviders"];
8
+ /** React Native: onnxruntime-react-native and Skia canvases. No OpenCV: the engine is canvas-native. */
9
+ export declare class MobilePlatformProvider implements PlatformProvider<CoreCanvas> {
10
+ readonly ort: PlatformProvider["ort"];
11
+ readonly defaultEngine: "canvas-native";
12
+ isCanvas(image: unknown): image is CoreCanvas;
13
+ decodeImage(bytes: ArrayBuffer): Promise<CoreCanvas>;
14
+ pixels(canvas: CoreCanvas): Rgba;
15
+ loadResource(source: string | ArrayBuffer | undefined, defaultUrl: string): Promise<ArrayBuffer>;
16
+ }
@@ -0,0 +1 @@
1
+ export class MobilePlatformProvider{ort=ort;defaultEngine="canvas-native";isCanvas(image){return getPlatform().isCanvas(image)}async decodeImage(bytes){return CanvasProcessor.prepareCanvas(bytes)}pixels(canvas){let ctx=canvas.getContext("2d");if(!hasImageData(ctx))throw new Error("canvas has no 2D context");return ctx.getImageData(0,0,canvas.width,canvas.height)}async loadResource(source,defaultUrl){if(source instanceof ArrayBuffer)return source;return fetchArrayBufferWithRetry(source??defaultUrl)}}import*as ort from"onnxruntime-react-native";import{CanvasProcessor,getPlatform}from"ppu-ocv/canvas-mobile";import{fetchArrayBufferWithRetry}from"../utils.js";export function getDefaultMobileExecutionProviders(){return["cpu"]}function hasImageData(ctx){return typeof ctx==="object"&&ctx!==null&&"getImageData"in ctx}
@@ -0,0 +1,38 @@
1
+ /** The model files of Indra OCR, by role. */
2
+ export type ModelFile = "det" | "rec" | "recCjk" | "script" | "orient" | "order" | "meta" | "mathCls" | "mathEnc" | "mathDecInit" | "mathDecStep" | "mathMeta";
3
+ /** File name of each model in the Indra OCR model repository. */
4
+ export declare const MODEL_FILES: Readonly<Record<ModelFile, string>>;
5
+ /** The files every service loads. */
6
+ export declare const BASE_FILES: readonly ModelFile[];
7
+ /** The math files: downloaded only when math is on. */
8
+ export declare const MATH_FILES: readonly ModelFile[];
9
+ /**
10
+ * The model revision this package is built and tested against: commit
11
+ * d7c839c of datalab-to/indra-ocr (tag v3.1). Pinned to the commit, so an
12
+ * upstream change (meta.json holds the vocabulary) cannot change results.
13
+ */
14
+ export declare const MODEL_REVISION = "d7c839c892bfe4b8993373db64c62f154d05d70b";
15
+ /**
16
+ * Base URL for model files: Datalab's Hugging Face repository at
17
+ * {@link MODEL_REVISION}. The weights are Datalab's, under their modified
18
+ * OpenRAIL-M license, not this package's license.
19
+ */
20
+ export declare const MODEL_BASE_URL: string;
21
+ /**
22
+ * Mirror of {@link MODEL_BASE_URL} in this repository's models/ folder (git
23
+ * LFS), used only when `PPU_INDRA_OCR_MODEL_MIRROR` is set.
24
+ *
25
+ * It must be the `github.com/<owner>/<repo>/raw/<ref>` form: that one
26
+ * redirects to the LFS media host. `raw.githubusercontent.com` serves the LFS
27
+ * pointer text instead. Off by default: LFS bandwidth has a monthly budget.
28
+ */
29
+ export declare const MODEL_MIRROR_BASE_URL = "https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/raw/main/models";
30
+ /** Default URL of a model file. */
31
+ export declare function defaultModelUrl(role: ModelFile): string;
32
+ /**
33
+ * Rewrite a built-in model URL onto {@link MODEL_MIRROR_BASE_URL}. Returns
34
+ * null when the mirror is off, or when the URL is not on the primary host: a
35
+ * caller's own model URL is never redirected. The environment is read on
36
+ * every call, so a test can flip it.
37
+ */
38
+ export declare function mirrorUrl(url: string): string | null;
@@ -0,0 +1 @@
1
+ export let MODEL_FILES={det:"det.onnx",rec:"rec.onnx",recCjk:"rec_cjk.onnx",script:"script.onnx",orient:"orient.onnx",order:"order.onnx",meta:"meta.json",mathCls:"mathcls.onnx",mathEnc:"math_enc.onnx",mathDecInit:"math_dec_init.onnx",mathDecStep:"math_dec_step.onnx",mathMeta:"math_meta.json"};export let BASE_FILES=["det","rec","recCjk","script","orient","order","meta"];export let MATH_FILES=["mathCls","mathEnc","mathDecInit","mathDecStep","mathMeta"];export let MODEL_REVISION="d7c839c892bfe4b8993373db64c62f154d05d70b";export let MODEL_BASE_URL=`https://huggingface.co/datalab-to/indra-ocr/resolve/${MODEL_REVISION}`;export let MODEL_MIRROR_BASE_URL="https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/raw/main/models";export function defaultModelUrl(role){return`${MODEL_BASE_URL}/${MODEL_FILES[role]}`}export function mirrorUrl(url){let enabled=globalThis.process?.env?.PPU_INDRA_OCR_MODEL_MIRROR;if(!enabled||enabled==="0"||enabled==="false")return null;if(!url.startsWith(MODEL_BASE_URL))return null;return MODEL_MIRROR_BASE_URL+url.slice(MODEL_BASE_URL.length)}
package/package.json CHANGED
@@ -1,6 +1,111 @@
1
1
  {
2
2
  "name": "ppu-indra-ocr",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "TypeScript SDK for Datalab's Indra OCR models: page orientation, line detection, recognition (Latin, Cyrillic, Greek, Devanagari, Bengali, Chinese), reading order, layout blocks, markdown, optional math, and PDF text layers. Runs on Node.js, Bun, Deno, browsers, web workers and React Native via ONNX Runtime.",
5
+ "keywords": [
6
+ "accurate-ocr",
7
+ "browser-ocr",
8
+ "bun-compatible",
9
+ "bun-ocr",
10
+ "computer-vision",
11
+ "document-ai",
12
+ "document-analysis",
13
+ "document-processing",
14
+ "fast-ocr",
15
+ "image-processing",
16
+ "image-text-extraction",
17
+ "image-to-text",
18
+ "invoice-processing",
19
+ "javascript-ocr",
20
+ "lightweight-ocr",
21
+ "node-ocr",
22
+ "nodejs-ocr",
23
+ "ocr",
24
+ "ocr-engine",
25
+ "ocr-library",
26
+ "onnx",
27
+ "onnx-ocr",
28
+ "onnxruntime",
29
+ "optical-character-recognition",
30
+ "receipt-scanner",
31
+ "text-detection",
32
+ "text-extraction",
33
+ "text-from-image",
34
+ "text-recognition",
35
+ "typescript-ocr",
36
+ "web-ocr",
37
+ "docker-ocr",
38
+ "cli-ocr",
39
+ "react-native",
40
+ "react-native-ocr",
41
+ "web-worker-ocr",
42
+ "indra-ocr",
43
+ "layout-analysis",
44
+ "reading-order",
45
+ "pdf-to-markdown",
46
+ "document-parsing",
47
+ "markdown"
48
+ ],
49
+ "author": "snowfluke",
50
+ "license": "Apache-2.0",
51
+ "type": "module",
52
+ "main": "./index.js",
53
+ "types": "./index.d.ts",
54
+ "bin": {
55
+ "ppu-indra-ocr": "cli/index.js"
56
+ },
57
+ "exports": {
58
+ ".": {
59
+ "types": "./index.d.ts",
60
+ "default": "./index.js"
61
+ },
62
+ "./web": {
63
+ "types": "./web/index.d.ts",
64
+ "default": "./web/index.js"
65
+ },
66
+ "./mobile": {
67
+ "types": "./mobile/index.d.ts",
68
+ "default": "./mobile/index.js"
69
+ },
70
+ "./pdf": {
71
+ "types": "./pdf/index.d.ts",
72
+ "default": "./pdf/index.js"
73
+ },
74
+ "./coi-serviceworker.js": "./coi-serviceworker.js"
75
+ },
76
+ "repository": {
77
+ "type": "git",
78
+ "url": "git+https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr.git"
79
+ },
80
+ "homepage": "https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr#readme",
81
+ "dependencies": {
82
+ "ppu-ocv": "^4.0.0"
83
+ },
84
+ "peerDependencies": {
85
+ "@embedpdf/pdfium": "^2.15.1",
86
+ "@shopify/react-native-skia": ">=1.0.0",
87
+ "onnxruntime-node": "^1.23.2",
88
+ "onnxruntime-react-native": "^1.23.2",
89
+ "onnxruntime-web": "^1.23.2"
90
+ },
91
+ "peerDependenciesMeta": {
92
+ "@embedpdf/pdfium": {
93
+ "optional": true
94
+ },
95
+ "@shopify/react-native-skia": {
96
+ "optional": true
97
+ },
98
+ "onnxruntime-node": {
99
+ "optional": true
100
+ },
101
+ "onnxruntime-react-native": {
102
+ "optional": true
103
+ },
104
+ "onnxruntime-web": {
105
+ "optional": true
106
+ }
107
+ },
108
+ "overrides": {
109
+ "adm-zip": "^0.6.1"
110
+ }
111
+ }
package/pdf/index.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
2
+ import type { PdfPageOptions } from "../indra/document.js";
3
+ import type { IndraPipeline } from "../indra/pipeline.js";
4
+ import type { Page } from "../indra/types.js";
5
+ export type { PdfMode, PdfPageOptions } from "../indra/document.js";
6
+ export { isPdf } from "../indra/document.js";
7
+ export { PdfiumDocument, PdfiumPage } from "./pdfium.js";
8
+ /** The @embedpdf/pdfium release this package is tested with (its wasm is fetched from a CDN in browsers). */
9
+ export declare const PDFIUM_VERSION = "2.15.1";
10
+ export type ConvertPdfOptions = PdfPageOptions & {
11
+ /** Read at most this many pages (0: all). */
12
+ maxPages?: number;
13
+ /** Password of an encrypted PDF. */
14
+ password?: string;
15
+ /** A pdfium module from loadPdfium(); loaded once and reused when omitted. */
16
+ pdfium?: WrappedPdfiumModule;
17
+ };
18
+ /**
19
+ * Load pdfium (WebAssembly). `wasm` is the pdfium.wasm bytes or URL; by
20
+ * default Node reads it from the installed package and a browser fetches it
21
+ * from jsDelivr.
22
+ */
23
+ export declare function loadPdfium(wasm?: ArrayBuffer | string): Promise<WrappedPdfiumModule>;
24
+ /**
25
+ * Every page of a PDF, in order. A page that fails comes back with
26
+ * `source: "error"` and the reason in `note`; a file that cannot be opened
27
+ * (not a PDF, corrupt, or locked) throws.
28
+ */
29
+ export declare function convertPdf(service: {
30
+ readonly pipeline: IndraPipeline;
31
+ }, bytes: ArrayBuffer | Uint8Array, options?: ConvertPdfOptions): Promise<Page[]>;
package/pdf/index.js ADDED
@@ -0,0 +1 @@
1
+ import{init}from"@embedpdf/pdfium";import{isPdf,pdfPage}from"../indra/document.js";import{PdfiumDocument}from"./pdfium.js";export{isPdf}from"../indra/document.js";export{PdfiumDocument,PdfiumPage}from"./pdfium.js";export let PDFIUM_VERSION="2.15.1";let shared;export async function loadPdfium(wasm){let bytes=wasm instanceof ArrayBuffer?wasm:await fetchWasm(wasm);let module=await init({wasmBinary:bytes});module.PDFiumExt_Init();return module}async function fetchWasm(url){if(!url&&globalThis.process?.versions?.node){const{createRequire}=await import("module");const{readFile}=await import("fs/promises");let file=await readFile(process.env.PPU_INDRA_OCR_PDFIUM_WASM||createRequire(import.meta.url).resolve("@embedpdf/pdfium/pdfium.wasm"));return file.buffer.slice(file.byteOffset,file.byteOffset+file.byteLength)}let src=url??`https://cdn.jsdelivr.net/npm/@embedpdf/pdfium@${PDFIUM_VERSION}/dist/pdfium.wasm`;let res=await fetch(src);if(!res.ok)throw new Error(`could not fetch pdfium.wasm from ${src}: HTTP ${res.status}`);return res.arrayBuffer()}function errorPage(err){let name=err instanceof Error?err.name:"Error";let message=err instanceof Error?err.message:String(err);return{lines:[],text:"",markdown:"",blocks:[],source:"error",note:`${name}: ${message}`,rotation:0,skew:0,timings:{total_ms:0}}}export async function convertPdf(service,bytes,options={}){if(!isPdf(bytes))throw new Error("not a PDF: no %PDF- header in the first 1024 bytes");let pdfium=options.pdfium??await(shared??=loadPdfium());let doc=new PdfiumDocument(pdfium,bytes instanceof Uint8Array?bytes:new Uint8Array(bytes),options.password);try{let n=options.maxPages?Math.min(doc.pageCount,options.maxPages):doc.pageCount;let pages=[];for(let i=0;i<n;i++){try{let page=doc.page(i);try{pages.push(await pdfPage(service.pipeline,page,options))}finally{page.close()}}catch(err){pages.push(errorPage(err))}}return pages}finally{doc.close()}}
@@ -0,0 +1,27 @@
1
+ import type { WrappedPdfiumModule } from "@embedpdf/pdfium";
2
+ import type { Gray } from "../indra/image.js";
3
+ import type { PdfChar, PdfPageSource } from "../indra/textlayer.js";
4
+ /** A PDF opened in pdfium (WebAssembly). Close it to free its memory. */
5
+ export declare class PdfiumDocument {
6
+ private readonly p;
7
+ private readonly doc;
8
+ private readonly buffer;
9
+ constructor(p: WrappedPdfiumModule, bytes: Uint8Array, password?: string);
10
+ get pageCount(): number;
11
+ /** Page `index` (0-based). Close it after use. */
12
+ page(index: number): PdfiumPage;
13
+ close(): void;
14
+ }
15
+ /** One loaded pdfium page, as the text-layer code reads it. */
16
+ export declare class PdfiumPage implements PdfPageSource {
17
+ private readonly p;
18
+ private readonly handle;
19
+ constructor(p: WrappedPdfiumModule, handle: number);
20
+ size(): readonly [number, number];
21
+ /** Grayscale render, as pypdfium2's render(scale, grayscale=True): white fill, annotations drawn. */
22
+ render(scale: number): Gray;
23
+ chars(): PdfChar[];
24
+ pageToDevice(width: number, height: number, x: number, y: number): readonly [number, number];
25
+ textRenderModes(): number[];
26
+ close(): void;
27
+ }
package/pdf/pdfium.js ADDED
@@ -0,0 +1 @@
1
+ export class PdfiumDocument{p;doc;buffer;constructor(p,bytes,password=""){this.p=p;this.buffer=p.pdfium.wasmExports.malloc(bytes.length);heaps(p).HEAPU8.set(bytes,this.buffer);this.doc=p.FPDF_LoadMemDocument(this.buffer,bytes.length,password);if(!this.doc){p.pdfium.wasmExports.free(this.buffer);let err=p.FPDF_GetLastError();throw new Error(err===4?"password-protected PDF (pass a password)":`cannot open the PDF (pdfium error ${err})`)}}get pageCount(){return this.p.FPDF_GetPageCount(this.doc)}page(index){let page=this.p.FPDF_LoadPage(this.doc,index);if(!page)throw new Error(`cannot load page ${index}`);return new PdfiumPage(this.p,page)}close(){this.p.FPDF_CloseDocument(this.doc);this.p.pdfium.wasmExports.free(this.buffer)}}export class PdfiumPage{p;handle;constructor(p,handle){this.p=p;this.handle=handle}size(){return[this.p.FPDF_GetPageWidthF(this.handle),this.p.FPDF_GetPageHeightF(this.handle)]}render(scale){const[w,h]=this.size();let width=Math.ceil(w*scale);let height=Math.ceil(h*scale);let bmp=this.p.FPDFBitmap_CreateEx(width,height,FPDFBITMAP_GRAY,0,0);if(!bmp)throw new Error(`cannot allocate a ${width}x${height} bitmap`);try{this.p.FPDFBitmap_FillRect(bmp,0,0,width,height,4294967295);this.p.FPDF_RenderPageBitmap(bmp,this.handle,0,0,width,height,0,FPDF_GRAYSCALE|FPDF_ANNOT);let stride=this.p.FPDFBitmap_GetStride(bmp);let ptr=this.p.FPDFBitmap_GetBuffer(bmp);let heap=heaps(this.p).HEAPU8;let data=new Uint8Array(width*height);for(let y=0;y<height;y++)data.set(heap.subarray(ptr+y*stride,ptr+y*stride+width),y*width);return{data,width,height}}finally{this.p.FPDFBitmap_Destroy(bmp)}}chars(){let tp=this.p.FPDFText_LoadPage(this.handle);if(!tp)return[];let out=this.p.pdfium.wasmExports.malloc(32);try{let n=this.p.FPDFText_CountChars(tp);return Array.from({length:Math.max(0,n)},(_,i)=>{let ok=this.p.FPDFText_GetCharBox(tp,i,out,out+8,out+16,out+24);let f64=heaps(this.p).HEAPF64;const[l=0,r=0,b=0,t=0]=f64.subarray(out/8,out/8+4);return{unit:this.p.FPDFText_GetUnicode(tp,i),angle:this.p.FPDFText_GetCharAngle(tp,i),box:ok?[l,b,r,t]:undefined}})}finally{this.p.pdfium.wasmExports.free(out);this.p.FPDFText_ClosePage(tp)}}pageToDevice(width,height,x,y){let out=this.p.pdfium.wasmExports.malloc(8);try{this.p.FPDF_PageToDevice(this.handle,0,0,width,height,0,x,y,out,out+4);let i32=heaps(this.p).HEAP32;return[i32[out/4]??0,i32[out/4+1]??0]}finally{this.p.pdfium.wasmExports.free(out)}}textRenderModes(){let modes=[];let walk=(count,get,level)=>{for(let i=0;i<count;i++){let obj=get(i);if(!obj)throw new Error("Failed to get pageobject.");let type=this.p.FPDFPageObj_GetType(obj);if(type===FPDF_PAGEOBJ_TEXT)modes.push(this.p.FPDFTextObj_GetTextRenderMode(obj));if(type===FPDF_PAGEOBJ_FORM&&level<MAX_OBJECT_DEPTH-1){walk(this.p.FPDFFormObj_CountObjects(obj),(k)=>this.p.FPDFFormObj_GetObject(obj,k),level+1)}}};walk(this.p.FPDFPage_CountObjects(this.handle),(i)=>this.p.FPDFPage_GetObject(this.handle,i),0);return modes}close(){this.p.FPDF_ClosePage(this.handle)}}let FPDFBITMAP_GRAY=1;let FPDF_ANNOT=1;let FPDF_GRAYSCALE=8;let FPDF_PAGEOBJ_TEXT=1;let FPDF_PAGEOBJ_FORM=5;let MAX_OBJECT_DEPTH=4;function heaps(p){let m=p.pdfium;if(typeof m==="object"&&m!==null&&"HEAPU8"in m&&"HEAP32"in m&&"HEAPF64"in m){return m}throw new Error("the pdfium module exposes no heap views")}
@@ -0,0 +1,28 @@
1
+ import { BaseIndraOcrService } from "../core/indra-ocr.service.js";
2
+ import type { CoreCanvas } from "../core/platform.js";
3
+ import type { IndraOptions } from "../interface.js";
4
+ /**
5
+ * Indra OCR for Node.js and Bun.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { IndraOcrService } from "ppu-indra-ocr";
10
+ *
11
+ * const service = new IndraOcrService();
12
+ * await service.initialize();
13
+ * const page = await service.convert(await Bun.file("scan.png").arrayBuffer());
14
+ * console.log(page.markdown);
15
+ * await service.destroy();
16
+ * ```
17
+ */
18
+ export declare class IndraOcrService extends BaseIndraOcrService<CoreCanvas> {
19
+ constructor(options?: IndraOptions);
20
+ /**
21
+ * Download the default model files into the disk cache (~/.cache/ppu-indra-ocr)
22
+ * without loading them. `math` adds the four math models and math_meta.json.
23
+ */
24
+ static downloadModels(options?: {
25
+ math?: boolean;
26
+ verbose?: boolean;
27
+ }): Promise<void>;
28
+ }
@@ -0,0 +1 @@
1
+ import{BaseIndraOcrService}from"../core/indra-ocr.service.js";import{BASE_FILES,MATH_FILES,defaultModelUrl}from"../model-catalogue.js";import{fetchAndCacheResource}from"./model-cache.js";import{NodePlatformProvider}from"./platform.node.js";export class IndraOcrService extends BaseIndraOcrService{constructor(options={}){super(new NodePlatformProvider(options.verbose),options)}static async downloadModels(options={}){let roles=options.math?[...BASE_FILES,...MATH_FILES]:BASE_FILES;await Promise.all(roles.map((role)=>fetchAndCacheResource(defaultModelUrl(role),options.verbose)))}}
@@ -0,0 +1,17 @@
1
+ /** On-disk directory for cached model and dictionary files. */
2
+ export declare const CACHE_DIR: string;
3
+ /**
4
+ * Cache path for `url`: the file name under a directory named after a digest
5
+ * of the whole URL.
6
+ *
7
+ * The digest is what keeps two resources that share a file name apart. Model
8
+ * file names repeat across hosts and directories, so keying on the name alone
9
+ * would serve one URL's bytes for another's request - a custom model shadowed
10
+ * by a preset, or a host swap that silently keeps reading the old host's copy.
11
+ */
12
+ export declare function cachePathFor(url: string): string;
13
+ /**
14
+ * Downloads a resource from `url` and writes it to {@link CACHE_DIR}, or reads
15
+ * from the cache if the file already exists.
16
+ */
17
+ export declare function fetchAndCacheResource(url: string, verbose?: boolean): Promise<ArrayBuffer>;
@@ -0,0 +1,2 @@
1
+ import{createHash}from"crypto";import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import*as os from"os";import*as path from"path";import{fetchArrayBufferWithRetry}from"../utils.js";export let CACHE_DIR=path.join(os.homedir(),".cache","ppu-indra-ocr");export function cachePathFor(url){let fileName=path.basename(new URL(url).pathname);let digest=createHash("sha256").update(url).digest("hex").slice(0,12);return path.join(CACHE_DIR,digest,fileName)}export async function fetchAndCacheResource(url,verbose){let fileName=path.basename(new URL(url).pathname);let cachePath=cachePathFor(url);if(existsSync(cachePath)){if(verbose)console.log(`[IndraOcrService] Loading cached resource from: ${cachePath}`);let buf=readFileSync(cachePath);return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}console.log(`[IndraOcrService] Downloading resource: ${fileName}
2
+ `+` Cached at: ${CACHE_DIR}`);if(verbose)console.log(`[IndraOcrService] Fetching resource from URL: ${url}`);let arrayBuffer=await fetchArrayBufferWithRetry(url);mkdirSync(path.dirname(cachePath),{recursive:true});writeFileSync(cachePath,Buffer.from(arrayBuffer));return arrayBuffer}
@@ -0,0 +1,13 @@
1
+ import type { CoreCanvas, Cv, PlatformProvider, Rgba } from "../core/platform.js";
2
+ /** Node and Bun: onnxruntime-node, node canvas decoding, OpenCV.js, and a disk cache for downloads. */
3
+ export declare class NodePlatformProvider implements PlatformProvider<CoreCanvas> {
4
+ private readonly verbose;
5
+ readonly ort: PlatformProvider["ort"];
6
+ readonly defaultEngine: "opencv";
7
+ constructor(verbose?: boolean);
8
+ isCanvas(image: unknown): image is CoreCanvas;
9
+ decodeImage(bytes: ArrayBuffer): Promise<CoreCanvas>;
10
+ pixels(canvas: CoreCanvas): Rgba;
11
+ loadResource(source: string | ArrayBuffer | undefined, defaultUrl: string): Promise<ArrayBuffer>;
12
+ readonly opencv: () => Promise<Cv>;
13
+ }
@@ -0,0 +1 @@
1
+ export class NodePlatformProvider{verbose;ort=ort;defaultEngine="opencv";constructor(verbose=false){this.verbose=verbose}isCanvas(image){return image instanceof Canvas}async decodeImage(bytes){return CanvasProcessor.prepareCanvas(bytes)}pixels(canvas){if(!(canvas instanceof Canvas))throw new TypeError("expected a node canvas");return canvas.getContext("2d").getImageData(0,0,canvas.width,canvas.height)}async loadResource(source,defaultUrl){if(source instanceof ArrayBuffer)return source;let target=source??defaultUrl;if(/^https?:\/\//.test(target))return fetchAndCacheResource(target,this.verbose);let buf=await readFile(path.resolve(process.cwd(),target));return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}opencv=async()=>{await ImageProcessor.initRuntime();return cv}}import{readFile}from"fs/promises";import*as ort from"onnxruntime-node";import*as path from"path";import{Canvas,ImageProcessor,cv}from"ppu-ocv";import{CanvasProcessor}from"ppu-ocv/canvas";import{fetchAndCacheResource}from"./model-cache.js";