ppu-indra-ocr 0.1.1 → 0.2.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.
Files changed (65) hide show
  1. package/LICENSE-STATUS.md +15 -7
  2. package/README.md +719 -193
  3. package/cli/commands.js +2 -2
  4. package/cli/help.d.ts +1 -1
  5. package/cli/help.js +3 -2
  6. package/cli/options.d.ts +3 -0
  7. package/cli/options.js +1 -1
  8. package/core/indra-ocr.service.d.ts +19 -7
  9. package/core/indra-ocr.service.js +1 -1
  10. package/core/opencv-image-ops.js +1 -1
  11. package/core/platform.d.ts +2 -0
  12. package/exports.d.ts +2 -2
  13. package/exports.js +1 -1
  14. package/indra/assemble.d.ts +38 -13
  15. package/indra/assemble.js +2 -2
  16. package/indra/document.d.ts +4 -3
  17. package/indra/document.js +1 -1
  18. package/indra/image.d.ts +2 -2
  19. package/indra/lines.d.ts +8 -3
  20. package/indra/lines.js +1 -1
  21. package/indra/lm.d.ts +51 -0
  22. package/indra/lm.js +1 -0
  23. package/indra/npz.d.ts +14 -0
  24. package/indra/npz.js +1 -0
  25. package/indra/order-post.d.ts +9 -0
  26. package/indra/order-post.js +1 -1
  27. package/indra/pipeline.d.ts +30 -17
  28. package/indra/pipeline.js +1 -1
  29. package/indra/rec-preproc.d.ts +14 -2
  30. package/indra/rec-preproc.js +1 -1
  31. package/indra/recognize.d.ts +44 -6
  32. package/indra/recognize.js +1 -1
  33. package/indra/recognizers.d.ts +45 -0
  34. package/indra/recognizers.js +1 -0
  35. package/indra/rtl.d.ts +34 -0
  36. package/indra/rtl.js +1 -0
  37. package/indra/text-runs.d.ts +35 -0
  38. package/indra/text-runs.js +2 -0
  39. package/indra/textlayer.d.ts +43 -16
  40. package/indra/textlayer.js +1 -2
  41. package/indra/ts-image-ops.js +1 -1
  42. package/indra/types.d.ts +39 -7
  43. package/indra/unicode-data.d.ts +4 -0
  44. package/indra/unicode-data.js +1 -0
  45. package/indra/unicode.d.ts +24 -0
  46. package/indra/unicode.js +1 -0
  47. package/indra/upright.d.ts +13 -2
  48. package/indra/upright.js +1 -1
  49. package/indra/vocab.d.ts +3 -1
  50. package/indra/vocab.js +1 -1
  51. package/interface.d.ts +13 -2
  52. package/mobile/platform.mobile.d.ts +1 -0
  53. package/mobile/platform.mobile.js +1 -1
  54. package/model-catalogue.d.ts +76 -20
  55. package/model-catalogue.js +1 -1
  56. package/package.json +1 -1
  57. package/pdf/index.js +1 -1
  58. package/pdf/pdfium.d.ts +2 -0
  59. package/pdf/pdfium.js +1 -1
  60. package/processor/indra-ocr.service.d.ts +7 -2
  61. package/processor/indra-ocr.service.js +1 -1
  62. package/processor/platform.node.d.ts +1 -0
  63. package/processor/platform.node.js +1 -1
  64. package/web/platform.web.d.ts +1 -0
  65. package/web/platform.web.js +1 -1
package/indra/types.d.ts CHANGED
@@ -2,12 +2,13 @@ import type { InferenceSession, Tensor } from "onnxruntime-common";
2
2
  import type { DetBox } from "./det-post.js";
3
3
  import type { Gray } from "./image.js";
4
4
  import type { LayoutBlock } from "./layout-post.js";
5
+ import type { NgramLM } from "./lm.js";
5
6
  import type { MathReader } from "./math.js";
6
7
  import type { Box } from "./rec-preproc.js";
7
8
  /**
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.
9
+ * One recognized character position: a class id (main recognizer) or a
10
+ * character (group recognizer, PDF text layer, math), its page x, and for
11
+ * text-layer characters their index in the PDF content stream.
11
12
  */
12
13
  export type Tok = readonly [id: number | string, x: number, contentIndex?: number];
13
14
  /** Text, confidence and character positions of one detected line. */
@@ -41,6 +42,11 @@ export type Page = {
41
42
  rotation: number;
42
43
  /** Degrees of small tilt undone; boxes are mapped back to the turned page. */
43
44
  skew: number;
45
+ /**
46
+ * Set in vertical columns (Chinese, Japanese): read turned a quarter turn,
47
+ * columns as lines. Boxes are on the page as it is (rotation stays 0).
48
+ */
49
+ vertical: boolean;
44
50
  /** Milliseconds per stage, with total_ms. */
45
51
  timings: Record<string, number>;
46
52
  };
@@ -62,7 +68,11 @@ export type DetectPass = {
62
68
  boxes: DetBox[];
63
69
  scale: number;
64
70
  };
65
- /** orient.onnx's verdict: quarter turns (counter-clockwise) the content is turned by, and the class probabilities. */
71
+ /**
72
+ * orient.onnx's verdict: quarter turns (counter-clockwise) the content is
73
+ * turned by, or VERTICAL (4) for a page set in vertical columns, and the
74
+ * class probabilities.
75
+ */
66
76
  export type Orientation = {
67
77
  turns: number;
68
78
  probs: number[];
@@ -73,21 +83,41 @@ export type Straightened = {
73
83
  turns: number;
74
84
  skew: number;
75
85
  };
86
+ /** Per-group language model settings in meta.json (`lm_params`). */
87
+ export type LmParams = {
88
+ alpha?: number;
89
+ beta?: number;
90
+ gate?: number;
91
+ };
76
92
  /** The `meta.json` that ships with the models. */
77
93
  export type IndraMeta = {
78
94
  vocab: string;
79
- vocab_cjk?: string;
80
95
  rec_height: number;
81
96
  det_long_side: number;
97
+ /** rec.onnx reads a window this many line heights tall (the line and the page around it). */
98
+ rec_window?: number;
99
+ /** script.onnx's class order (default base, cjk, rtl, other). */
100
+ script_groups?: string[];
101
+ lm_params?: Record<string, LmParams>;
102
+ } & {
103
+ [group: `vocab_${string}`]: string | undefined;
82
104
  };
83
- /** ONNX Runtime sessions of the Indra models. Optional ones switch a stage off. */
105
+ /** A model that loads on its first use. */
106
+ export type Lazy<T> = () => Promise<T>;
107
+ /**
108
+ * ONNX Runtime sessions of the Indra models. Optional ones switch a stage
109
+ * off. `groups` holds the recognizer of each script group (cjk, rtl, world),
110
+ * `lms` the language model of a recognizer ("base" is rec.onnx); both load on
111
+ * the first line that needs them.
112
+ */
84
113
  export type IndraSessions = {
85
114
  det: InferenceSession;
86
115
  rec: InferenceSession;
87
116
  order?: InferenceSession;
88
117
  orient?: InferenceSession;
89
118
  script?: InferenceSession;
90
- recCjk?: InferenceSession;
119
+ groups?: Record<string, Lazy<InferenceSession>>;
120
+ lms?: Record<string, Lazy<NgramLM>>;
91
121
  };
92
122
  export type TensorCtor = typeof Tensor;
93
123
  /** Pipeline settings beyond the models. */
@@ -98,4 +128,6 @@ export type PipelineOptions = {
98
128
  adaptive?: boolean;
99
129
  /** Read lines with math as LaTeX. Off unless given. */
100
130
  math?: MathReader;
131
+ /** Re-read unsure lines with the language models (when given). Default true. */
132
+ lm?: boolean;
101
133
  };
@@ -0,0 +1,4 @@
1
+ /** Classes: 1 right to left (R, AL), 2 L, 3 digit (EN, AN), 4 mark (Mn, Me). */
2
+ export declare const BIDI_TABLE: string;
3
+ /** East Asian width W or F, class 1. */
4
+ export declare const WIDE_TABLE: string;
@@ -0,0 +1 @@
1
+ export let BIDI_TABLE="1c 9 3 7 p 2 6 p 2 1b 0 2 7 1 3 1 0 2 3 0 3 0 0 2 5 m 2 1 u 2 1 cg 2 2 6 2 e 1 2 e 4 2 9"+" 0 2 h 33 4 0 3 2 2 1 2 2 3 2 1 0 2 6 0 2 1 2 2 1 0 2 1 j 2 1 2a 2 1 3v 2 0 6 4 0 4l 2 1"+" 11 2 2 1c 2 7 18 4 0 0 1 0 0 4 0 0 1 0 1 4 0 0 1 0 1 4 0 0 1 0 0 4 8 q 1 4 5 1 b 5 3 2 "+"0 1 2 0 1 1 0 1 2 a 4 0 1b 1 0 k 4 0 9 3 1 1 3 0 2 1 0 0 4 0 2s 1 0 6 4 0 0 3 1 5 4 0 1 "+"1 0 1 4 1 3 4 0 1 1 0 9 3 0 j 1 1 1 1 0 0 4 0 t 1 0 q 4 2 2g 1 0 a 4 0 0 1 e 16 1 0 8 4 "+"0 1 1 4 0 1 2 0 4 0 n 1 0 3 4 0 0 1 0 8 4 0 0 1 0 2 4 0 0 1 0 4 4 2 e 1 1 o 1 0 2 4 2 0 "+"1 1 a 1 5 u 1 1 1 3 6 7 4 0 15 1 0 n 4 0 0 3 0 v 4 0 1i 2 0 0 4 0 0 2 0 0 4 0 3 2 0 7 4 "+"0 3 2 0 0 4 0 2 2 0 6 4 0 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ekd 2";export let WIDE_TABLE="3cw 2n 1 3i2 1 1 d 1 1 5a 3 1 3 0 1 2 0 1 eh 1 1 l 1 1 1e b 1 17 0 1 j 0 1 d 0 1 8 1 1 h"+" 1 1 5 1 1 8 0 1 5 0 1 l 0 1 7 1 1 1 0 1 4 0 1 2 0 1 7 0 1 4 1 1 s 0 1 z 0 1 1 0 1 4 2 1"+" 1 0 1 1p 2 1 o 0 1 e 0 1 nv 1 1 1f 0 1 4 0 1 mi p 1 1 2g 1 c 5x 1 q b 1 4 1q 1 2 2d 1 2"+" 2u 1 5 16 1 1 2l 1 1 2b 1 c 1a 1 1 13 1 8 5f3 1 1s h3g 1 3 1i 1 wp s 1 hv 8mb 1 6l8 e7 "+"1 ls 9 1 m y 1 1 i 1 1 3 1 45 2n 1 3j 6 1 m49 4 1 b 1 1 e 4qf 1 8 yd 1 16 8 1 6w7 3 1 1 "+"6 1 1 1 1 1 82 1 f 0 1 t 2 1 2 0 1 e 3 1 8 az 1 c20 0 1 5m 0 1 5a 0 1 2 9 1 2t 2 1 d 17 "+"1 4 8 1 7 1 1 e 5 1 4a w 1 c 8 1 1 1x 1 1 l 1 c 16 1 4 4 1 c g 1 3 0 1 3 1y 1 1 0 1 1 56"+" 1 2 1q 1 d 3 1 1 n 1 i 0 1 q 1 1 d 0 1 2e 2c 1 1c 1x 1 6 0 1 3 2 1 2 2 1 4 3 1 b 1 1 7 "+"8 1 6b b 1 4 0 1 7v 1a 1 1 9 1 1 54 1 34 c 1 3 8 1 7 19 1 1 6 1 8 d 1 4 8 1 7 8 1 zr 1ek"+"d 1 2 1ekd 1";
@@ -0,0 +1,24 @@
1
+ /** Bidi classes the port tells apart; everything else is `OTHER`. */
2
+ export declare const OTHER = 0;
3
+ /** R or AL. */
4
+ export declare const RTL = 1;
5
+ /** L. */
6
+ export declare const LTR = 2;
7
+ /** EN or AN. */
8
+ export declare const DIGIT = 3;
9
+ /** General category Mn or Me. */
10
+ export declare const MARK = 4;
11
+ /** `RTL`, `LTR`, `DIGIT`, `MARK` or `OTHER` for a code point. */
12
+ export declare function bidiClass(cp: number): number;
13
+ /** Whether East Asian width is W or F. */
14
+ export declare function eastAsianWide(cp: number): boolean;
15
+ /** Strong right-to-left (bidi R or AL) for the first code point of `c`. */
16
+ export declare function isRtl(c: string): boolean;
17
+ /** Reads left to right inside RTL text: bidi L, EN or AN. */
18
+ export declare function isLtr(c: string): boolean;
19
+ /** Bidi class L only (letters, not digits). */
20
+ export declare function isStrongL(c: string): boolean;
21
+ /** Combining mark (Mn or Me). */
22
+ export declare function isMark(c: string): boolean;
23
+ /** Length in code points with East Asian wide characters counted twice. */
24
+ export declare function displayLen(text: string): number;
@@ -0,0 +1 @@
1
+ import{BIDI_TABLE,WIDE_TABLE}from"./unicode-data.js";import{item}from"./util.js";export let OTHER=0;export let RTL=1;export let LTR=2;export let DIGIT=3;export let MARK=4;function decode(table){let t=table.split(" ").map((s)=>Number.parseInt(s,36));let n=t.length/3;let starts=new Uint32Array(n);let ends=new Uint32Array(n);let classes=new Uint8Array(n);let end=-1;for(let i=0;i<n;i++){let start=end+1+(t[3*i]??0);end=start+(t[3*i+1]??0);starts[i]=start;ends[i]=end;classes[i]=t[3*i+2]??0}return{starts,ends,classes}}let bidi;let wide;function lookup(r,cp){let lo=0;let hi=r.starts.length-1;while(lo<=hi){let mid=lo+hi>>1;if(cp<item(r.starts,mid))hi=mid-1;else if(cp>item(r.ends,mid))lo=mid+1;else return item(r.classes,mid)}return 0}export function bidiClass(cp){bidi??=decode(BIDI_TABLE);return lookup(bidi,cp)}export function eastAsianWide(cp){wide??=decode(WIDE_TABLE);return lookup(wide,cp)===1}let cpOf=(c)=>c.codePointAt(0)??0;export function isRtl(c){return bidiClass(cpOf(c))===RTL}export function isLtr(c){let k=bidiClass(cpOf(c));return k===LTR||k===DIGIT}export function isStrongL(c){return bidiClass(cpOf(c))===LTR}export function isMark(c){return bidiClass(cpOf(c))===MARK}export function displayLen(text){let n=0;for(let c of text)n+=eastAsianWide(cpOf(c))?2:1;return n}
@@ -6,13 +6,24 @@ export declare const ORIENT_SIDE = 768;
6
6
  * upright, and a wrong turn loses the page.
7
7
  */
8
8
  export declare const ORIENT_MIN = 0.95;
9
+ /** orient.onnx class (5-class models): the page is set in vertical columns. */
10
+ export declare const VERTICAL = 4;
9
11
  export declare const DESKEW_MIN = 0.3;
12
+ /** The skew search and orient.onnx read this shrunk copy of the page, not the full scan. */
13
+ export declare const PREVIEW_SIDE = 1600;
10
14
  /** The orient.onnx input: [side, side] ink map, long side scaled to `side`, padded with 0. */
11
15
  export declare function orientInput(gray: Gray, ops: ImageOps, side?: number): Float32Array;
16
+ /**
17
+ * The page shrunk once to at most `side` pixels a side (area averaging); a
18
+ * smaller page is returned as is.
19
+ */
20
+ export declare function preview(gray: Gray, ops: ImageOps, side?: number): Gray;
12
21
  /**
13
22
  * 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.
23
+ * angle whose horizontal ink profile changes most sharply row to row. Searched
24
+ * over +-DESKEW_MAX in 2 degree steps on a half-size thumbnail; the two best
25
+ * angles and 0 are then refined in 0.5 and 0.1 degree steps on the full
26
+ * thumbnail (`side` pixels), where small text rows are still resolved.
16
27
  */
17
28
  export declare function estimateSkew(gray: Gray, ops: ImageOps, side?: number): number;
18
29
  /** The page rotated by `degrees` counter-clockwise about its center (same size, edges replicated). */
package/indra/upright.js CHANGED
@@ -1 +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))}
1
+ import{pyRound}from"./det-post.js";import{inkOf,rotationMatrix}from"./image.js";export let ORIENT_SIDE=768;export let ORIENT_MIN=0.95;export let VERTICAL=4;let DESKEW_MAX=45;export let DESKEW_MIN=0.3;let SKEW_SIDE=800;export let PREVIEW_SIDE=1600;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 preview(gray,ops,side=PREVIEW_SIDE){return side/Math.max(gray.height,gray.width)>=1?gray:thumbnail(gray,side,ops)}function inkThumb(gray,side,ops){let small=thumbnail(gray,side,ops);let data=new Uint8Array(small.data.length);for(let i=0;i<data.length;i++)data[i]=255-(small.data[i]??0);return{data,width:small.width,height:small.height}}function rowSharpness(ink,a,ops){const{width:w,height:h}=ink;let r=ops.warpZero(ink,rotationMatrix(w/2,h/2,a),w,h);let total=0;let prev=0;for(let y=0;y<h;y++){let row=0;for(let x=0;x<w;x++)row+=r.data[y*w+x]??0;if(y)total+=(row-prev)*(row-prev);prev=row}return total}export function estimateSkew(gray,ops,side=SKEW_SIDE){let fine=inkThumb(gray,side,ops);let sum=0;for(let v of fine.data)sum+=v;if(sum/fine.data.length<0.003*255)return 0;let coarse=inkThumb(gray,Math.floor(side/2),ops);let grid=arange(-DESKEW_MAX,DESKEW_MAX+0.000001,2);let scores=grid.map((a)=>rowSharpness(coarse,a,ops));let top=grid.map((_,i)=>i).toSorted((i,j)=>(scores[i]??0)-(scores[j]??0)).slice(-2);let starts=[0,...top.map((i)=>grid[i]??0)];let near=starts.flatMap((a0)=>arange(a0-2,a0+2+0.000001,0.5));let seen=new Map;for(let a of near)if(!seen.has(a))seen.set(a,rowSharpness(fine,a,ops));let a1=argmax(near,(a)=>seen.get(a)??-1/0);return argmax(arange(a1-0.5,a1+0.5+0.000001,0.1),(a)=>rowSharpness(fine,a,ops))}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))}
package/indra/vocab.d.ts CHANGED
@@ -6,8 +6,10 @@ export declare class Vocab {
6
6
  readonly chars: readonly string[];
7
7
  readonly index: ReadonlyMap<string, number>;
8
8
  readonly hasCommands: boolean;
9
+ /** Hangul syllables are read as jamo and composed back (NFC) on decode. */
10
+ readonly jamo: boolean;
9
11
  constructor(chars: readonly string[]);
10
- /** A vocabulary from the `vocab` / `vocab_cjk` JSON string in meta.json. */
12
+ /** A vocabulary from a `vocab` / `vocab_<group>` JSON string in meta.json. */
11
13
  static fromJson(json: string): Vocab;
12
14
  /** Text of class ids. A space goes back between a command and a following letter. */
13
15
  decode(ids: readonly number[]): string;
package/indra/vocab.js CHANGED
@@ -1 +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;
1
+ export class Vocab{chars;index;hasCommands;jamo;constructor(chars){this.chars=chars;this.index=new Map(chars.map((c,i)=>[c,i+1]));this.hasCommands=chars.some((c)=>[...c].length>1);this.jamo=this.index.has(String.fromCharCode(4352))}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.jamo)return toks.join("").normalize("NFC");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 CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { InferenceSession } from "onnxruntime-common";
2
- import type { ModelFile } from "./model-catalogue.js";
2
+ import type { ModelFile, ModelPreset } from "./model-catalogue.js";
3
3
  /**
4
4
  * The image engine for resizing and warping.
5
5
  *
@@ -30,8 +30,19 @@ export type SessionOptions = InferenceSession.SessionOptions & {
30
30
  };
31
31
  /** Options of an IndraOcrService. */
32
32
  export type IndraOptions = {
33
- /** Per-file model sources. Default: Datalab's repository at the pinned revision. */
33
+ /**
34
+ * The model set: "v1.1" (Indra OCR 1.1, the default) or "v3.1" (the first
35
+ * release, smaller and Latin, Cyrillic, Greek and Chinese only).
36
+ */
37
+ model?: ModelPreset;
38
+ /** Per-file model sources. Default: Datalab's repository at the preset's pinned revision. */
34
39
  models?: ModelSources;
40
+ /**
41
+ * Re-read lines the recognizer is unsure of with the n-gram language models
42
+ * (v1.1). Each model loads on the first such line: 16 to 19 MB each.
43
+ * Default true on Node and Bun, false on web and mobile.
44
+ */
45
+ lm?: boolean;
35
46
  /** Read lines with math as LaTeX. Loads four more models. Default false. */
36
47
  math?: boolean;
37
48
  /** Keep page headers and footers in the markdown. Default false. */
@@ -9,6 +9,7 @@ export declare function getDefaultMobileExecutionProviders(): ort.InferenceSessi
9
9
  export declare class MobilePlatformProvider implements PlatformProvider<CoreCanvas> {
10
10
  readonly ort: PlatformProvider["ort"];
11
11
  readonly defaultEngine: "canvas-native";
12
+ readonly defaultLm = false;
12
13
  isCanvas(image: unknown): image is CoreCanvas;
13
14
  decodeImage(bytes: ArrayBuffer): Promise<CoreCanvas>;
14
15
  pixels(canvas: CoreCanvas): Rgba;
@@ -1 +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}
1
+ export class MobilePlatformProvider{ort=ort;defaultEngine="canvas-native";defaultLm=false;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}
@@ -1,38 +1,94 @@
1
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";
2
+ export type ModelFile = "det" | "rec" | "recCjk" | "recRtl" | "recWorld" | "script" | "orient" | "order" | "meta" | "lm" | "lmCjk" | "lmWorld" | "mathCls" | "mathEnc" | "mathDecInit" | "mathDecStep" | "mathMeta";
3
3
  /** File name of each model in the Indra OCR model repository. */
4
4
  export declare const MODEL_FILES: Readonly<Record<ModelFile, string>>;
5
- /** The files every service loads. */
5
+ /** The files every service loads when it starts. */
6
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
7
  /**
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.
8
+ * The recognizer of each script group, by the group name in meta.json
9
+ * (`vocab_<group>`). One loads on the first line routed to its group.
13
10
  */
14
- export declare const MODEL_REVISION = "d7c839c892bfe4b8993373db64c62f154d05d70b";
11
+ /** The recognizer file of each script group. */
12
+ export type GroupFiles = {
13
+ cjk: "recCjk";
14
+ rtl: "recRtl";
15
+ world: "recWorld";
16
+ };
17
+ export declare const GROUP_FILES: Readonly<GroupFiles>;
15
18
  /**
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
+ * The n-gram language model of each recognizer ("base" is rec.onnx). One
20
+ * loads on the first line its recognizer is unsure of, when `lm` is on.
19
21
  */
20
- export declare const MODEL_BASE_URL: string;
22
+ /** The language model file of each recognizer. */
23
+ export type LmFiles = {
24
+ base: "lm";
25
+ cjk: "lmCjk";
26
+ world: "lmWorld";
27
+ };
28
+ export declare const LM_FILES: Readonly<LmFiles>;
29
+ /** The math files: downloaded only when math is on. */
30
+ export declare const MATH_FILES: readonly ModelFile[];
31
+ /** A model set by its Indra OCR release: the default and the legacy one. */
32
+ export type ModelPreset = "v1.1" | "v3.1";
33
+ /** Where a preset's files live and which files it has. */
34
+ export type PresetInfo = {
35
+ /** Commit of datalab-to/indra-ocr, pinned so an upstream change cannot change results. */
36
+ revision: string;
37
+ /** The Hugging Face tag at that commit. */
38
+ tag: string;
39
+ /** Datalab's repository at the revision. */
40
+ baseUrl: string;
41
+ /** This repository's git LFS mirror of the same files (see MODEL_MIRROR_BASE_URL). */
42
+ mirrorUrl: string;
43
+ /** The files the preset has, math included. */
44
+ files: readonly ModelFile[];
45
+ };
21
46
  /**
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.
47
+ * Mirror of the model files in this repository's models/ folder (git LFS),
48
+ * used only when `PPU_INDRA_OCR_MODEL_MIRROR` is set.
24
49
  *
25
50
  * It must be the `github.com/<owner>/<repo>/raw/<ref>` form: that one
26
51
  * redirects to the LFS media host. `raw.githubusercontent.com` serves the LFS
27
52
  * pointer text instead. Off by default: LFS bandwidth has a monthly budget.
28
53
  */
29
54
  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
55
  /**
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.
56
+ * The model sets, by Indra OCR release:
57
+ *
58
+ * - `v1.1` (default): Indra OCR 1.1, Hugging Face tag v1.1.0. Handwriting,
59
+ * 80+ languages (recognizers for CJK, right-to-left and other scripts),
60
+ * pages at any angle, vertical writing, and language models for unsure
61
+ * lines. About 30 MB of networks, plus 46 MB of language models.
62
+ * - `v3.1`: the first release (Indra OCR 1.0), Hugging Face tag v3.1. Latin,
63
+ * Cyrillic, Greek and Chinese. About 18 MB.
64
+ */
65
+ export declare const MODEL_PRESETS: Readonly<Record<ModelPreset, PresetInfo>>;
66
+ /** The preset a service uses when the options name none. */
67
+ export declare const DEFAULT_PRESET: ModelPreset;
68
+ /** The model revision of the default preset (commit of datalab-to/indra-ocr). */
69
+ export declare const MODEL_REVISION: string;
70
+ /**
71
+ * Base URL for the default preset's files: Datalab's Hugging Face repository
72
+ * at {@link MODEL_REVISION}. The weights are Datalab's, under their modified
73
+ * OpenRAIL-M license, not this package's license.
74
+ */
75
+ export declare const MODEL_BASE_URL: string;
76
+ /** Whether a name is a model preset. */
77
+ export declare function isModelPreset(name: string): name is ModelPreset;
78
+ /**
79
+ * The files of a preset a service can load: without the math models unless
80
+ * `math`, and without the language models when `lm` is false.
81
+ */
82
+ export declare function presetFiles(preset?: ModelPreset, { math, lm }?: {
83
+ math?: boolean;
84
+ lm?: boolean;
85
+ }): ModelFile[];
86
+ /** Default URL of a model file in a preset. Throws for a file the preset does not have. */
87
+ export declare function defaultModelUrl(role: ModelFile, preset?: ModelPreset): string;
88
+ /**
89
+ * Rewrite a built-in model URL onto the preset's mirror folder. Returns null
90
+ * when the mirror is off, or when the URL is not a preset's: a caller's own
91
+ * model URL is never redirected. The environment is read on every call, so a
92
+ * test can flip it.
37
93
  */
38
94
  export declare function mirrorUrl(url: string): string | null;
@@ -1 +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)}
1
+ export let MODEL_FILES={det:"det.onnx",rec:"rec.onnx",recCjk:"rec_cjk.onnx",recRtl:"rec_rtl.onnx",recWorld:"rec_world.onnx",script:"script.onnx",orient:"orient.onnx",order:"order.onnx",meta:"meta.json",lm:"lm.npz",lmCjk:"lm_cjk.npz",lmWorld:"lm_world.npz",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","script","orient","order","meta"];export let GROUP_FILES={cjk:"recCjk",rtl:"recRtl",world:"recWorld"};export let LM_FILES={base:"lm",cjk:"lmCjk",world:"lmWorld"};export let MATH_FILES=["mathCls","mathEnc","mathDecInit","mathDecStep","mathMeta"];let HF="https://huggingface.co/datalab-to/indra-ocr/resolve";export let MODEL_MIRROR_BASE_URL="https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/raw/main/models";export let MODEL_PRESETS={"v1.1":{revision:"a1283c4b42a273c09480ad50e71461daff50fcc7",tag:"v1.1.0",baseUrl:`${HF}/a1283c4b42a273c09480ad50e71461daff50fcc7`,mirrorUrl:`${MODEL_MIRROR_BASE_URL}/v1.1`,files:[...BASE_FILES,"recCjk","recRtl","recWorld","lm","lmCjk","lmWorld",...MATH_FILES]},"v3.1":{revision:"d7c839c892bfe4b8993373db64c62f154d05d70b",tag:"v3.1",baseUrl:`${HF}/d7c839c892bfe4b8993373db64c62f154d05d70b`,mirrorUrl:MODEL_MIRROR_BASE_URL,files:[...BASE_FILES,"recCjk",...MATH_FILES]}};export let DEFAULT_PRESET="v1.1";export let MODEL_REVISION=MODEL_PRESETS[DEFAULT_PRESET].revision;export let MODEL_BASE_URL=MODEL_PRESETS[DEFAULT_PRESET].baseUrl;export function isModelPreset(name){return Object.hasOwn(MODEL_PRESETS,name)}export function presetFiles(preset=DEFAULT_PRESET,{math=false,lm=true}={}){let lms=new Set(Object.values(LM_FILES));return MODEL_PRESETS[preset].files.filter((role)=>(math||!MATH_FILES.includes(role))&&(lm||!lms.has(role)))}export function defaultModelUrl(role,preset=DEFAULT_PRESET){let info=MODEL_PRESETS[preset];if(!info.files.includes(role)){throw new Error(`model preset ${preset} has no ${MODEL_FILES[role]}`)}return`${info.baseUrl}/${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;for(let info of Object.values(MODEL_PRESETS)){if(url.startsWith(`${info.baseUrl}/`))return info.mirrorUrl+url.slice(info.baseUrl.length)}return null}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ppu-indra-ocr",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
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
5
  "keywords": [
6
6
  "accurate-ocr",
package/pdf/index.js CHANGED
@@ -1 +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(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()}}
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,vertical:false,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()}}
package/pdf/pdfium.d.ts CHANGED
@@ -23,5 +23,7 @@ export declare class PdfiumPage implements PdfPageSource {
23
23
  chars(): PdfChar[];
24
24
  pageToDevice(width: number, height: number, x: number, y: number): readonly [number, number];
25
25
  textRenderModes(): number[];
26
+ rotation(): number;
27
+ setRotation(degrees: number): void;
26
28
  close(): void;
27
29
  }
package/pdf/pdfium.js CHANGED
@@ -1 +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")}
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}rotation(){return 90*this.p.FPDFPage_GetRotation(this.handle)}setRotation(degrees){this.p.FPDFPage_SetRotation(this.handle,(degrees/90%4+4)%4)}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")}
@@ -1,6 +1,7 @@
1
1
  import { BaseIndraOcrService } from "../core/indra-ocr.service.js";
2
2
  import type { CoreCanvas } from "../core/platform.js";
3
3
  import type { IndraOptions } from "../interface.js";
4
+ import type { ModelPreset } from "../model-catalogue.js";
4
5
  /**
5
6
  * Indra OCR for Node.js and Bun.
6
7
  *
@@ -18,11 +19,15 @@ import type { IndraOptions } from "../interface.js";
18
19
  export declare class IndraOcrService extends BaseIndraOcrService<CoreCanvas> {
19
20
  constructor(options?: IndraOptions);
20
21
  /**
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.
22
+ * Download a preset's model files (default v1.1) into the disk cache
23
+ * (~/.cache/ppu-indra-ocr) without loading them, so later runs need no
24
+ * network. `math` adds the four math models and math_meta.json; `lm: false`
25
+ * leaves out the language models.
23
26
  */
24
27
  static downloadModels(options?: {
28
+ model?: ModelPreset;
25
29
  math?: boolean;
30
+ lm?: boolean;
26
31
  verbose?: boolean;
27
32
  }): Promise<void>;
28
33
  }
@@ -1 +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)))}}
1
+ import{BaseIndraOcrService}from"../core/indra-ocr.service.js";import{DEFAULT_PRESET,defaultModelUrl,presetFiles}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 preset=options.model??DEFAULT_PRESET;for(let role of presetFiles(preset,options)){await fetchAndCacheResource(defaultModelUrl(role,preset),options.verbose)}}}
@@ -4,6 +4,7 @@ export declare class NodePlatformProvider implements PlatformProvider<CoreCanvas
4
4
  private readonly verbose;
5
5
  readonly ort: PlatformProvider["ort"];
6
6
  readonly defaultEngine: "opencv";
7
+ readonly defaultLm = true;
7
8
  constructor(verbose?: boolean);
8
9
  isCanvas(image: unknown): image is CoreCanvas;
9
10
  decodeImage(bytes: ArrayBuffer): Promise<CoreCanvas>;
@@ -1 +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";
1
+ export class NodePlatformProvider{verbose;ort=ort;defaultEngine="opencv";defaultLm=true;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";
@@ -24,6 +24,7 @@ export declare function getDefaultWebExecutionProviders(): Promise<ort.Inference
24
24
  export declare class WebPlatformProvider implements PlatformProvider<CoreCanvas> {
25
25
  readonly ort: PlatformProvider["ort"];
26
26
  readonly defaultEngine: "canvas-native";
27
+ readonly defaultLm = false;
27
28
  isCanvas(image: unknown): image is CoreCanvas;
28
29
  decodeImage(bytes: ArrayBuffer): Promise<CoreCanvas>;
29
30
  pixels(canvas: CoreCanvas): Rgba;
@@ -1 +1 @@
1
- export class WebPlatformProvider{ort=ort;defaultEngine="canvas-native";isCanvas(image){return typeof image==="object"&&image!==null&&"getContext"in image&&typeof image.getContext==="function"}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)}opencv=async()=>{if(!("cv"in globalThis)){throw new Error('the "opencv" engine needs OpenCV.js on globalThis.cv: load @techstark/opencv-js '+"with a <script> tag, or assign globalThis.cv, before initialize()")}await ImageProcessor.initRuntime();return cv}}import*as ort from"onnxruntime-web";import{CanvasProcessor}from"ppu-ocv/canvas-web";import{ImageProcessor,cv}from"ppu-ocv/web";import{fetchArrayBufferWithRetry}from"../utils.js";function defaultWasmPaths(){let version=ort.env.versions.web??ort.env.versions.common;return`https://cdn.jsdelivr.net/npm/onnxruntime-web@${version}/dist/`}export function isWebWorker(){return typeof globalThis.WorkerGlobalScope==="function"}export function applyDefaultWasmPaths(){let inBrowser=typeof window!=="undefined"||isWebWorker();if(!inBrowser||ort.env.wasm.wasmPaths)return;ort.env.wasm.wasmPaths=defaultWasmPaths()}applyDefaultWasmPaths();export async function isWebGpuAvailable(){if(typeof navigator==="undefined")return false;let nav=navigator;if(!nav.gpu||typeof nav.gpu.requestAdapter!=="function")return false;try{let adapter=await nav.gpu.requestAdapter();return adapter!==null&&adapter!==undefined}catch{return false}}export async function getDefaultWebExecutionProviders(){if(await isWebGpuAvailable()){return["webgpu","wasm"]}return["wasm"]}function hasImageData(ctx){return typeof ctx==="object"&&ctx!==null&&"getImageData"in ctx}
1
+ export class WebPlatformProvider{ort=ort;defaultEngine="canvas-native";defaultLm=false;isCanvas(image){return typeof image==="object"&&image!==null&&"getContext"in image&&typeof image.getContext==="function"}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)}opencv=async()=>{if(!("cv"in globalThis)){throw new Error('the "opencv" engine needs OpenCV.js on globalThis.cv: load @techstark/opencv-js '+"with a <script> tag, or assign globalThis.cv, before initialize()")}await ImageProcessor.initRuntime();return cv}}import*as ort from"onnxruntime-web";import{CanvasProcessor}from"ppu-ocv/canvas-web";import{ImageProcessor,cv}from"ppu-ocv/web";import{fetchArrayBufferWithRetry}from"../utils.js";function defaultWasmPaths(){let version=ort.env.versions.web??ort.env.versions.common;return`https://cdn.jsdelivr.net/npm/onnxruntime-web@${version}/dist/`}export function isWebWorker(){return typeof globalThis.WorkerGlobalScope==="function"}export function applyDefaultWasmPaths(){let inBrowser=typeof window!=="undefined"||isWebWorker();if(!inBrowser||ort.env.wasm.wasmPaths)return;ort.env.wasm.wasmPaths=defaultWasmPaths()}applyDefaultWasmPaths();export async function isWebGpuAvailable(){if(typeof navigator==="undefined")return false;let nav=navigator;if(!nav.gpu||typeof nav.gpu.requestAdapter!=="function")return false;try{let adapter=await nav.gpu.requestAdapter();return adapter!==null&&adapter!==undefined}catch{return false}}export async function getDefaultWebExecutionProviders(){if(await isWebGpuAvailable()){return["webgpu","wasm"]}return["wasm"]}function hasImageData(ctx){return typeof ctx==="object"&&ctx!==null&&"getImageData"in ctx}