ppu-indra-ocr 0.2.2 → 0.3.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 (112) hide show
  1. package/LICENSE-STATUS.md +25 -9
  2. package/README.md +76 -65
  3. package/cli/commands.js +2 -2
  4. package/cli/help.d.ts +1 -1
  5. package/cli/help.js +3 -3
  6. package/cli/options.d.ts +2 -0
  7. package/cli/options.js +1 -1
  8. package/core/indra-ocr.service.d.ts +2 -0
  9. package/core/indra-ocr.service.js +1 -1
  10. package/core/load-math.d.ts +11 -0
  11. package/core/load-math.js +1 -0
  12. package/core/opencv-image-ops.js +1 -1
  13. package/core/platform.d.ts +2 -0
  14. package/indra/agree.d.ts +70 -0
  15. package/indra/agree.js +1 -0
  16. package/indra/assemble.d.ts +14 -3
  17. package/indra/assemble.js +1 -1
  18. package/indra/ctc.d.ts +28 -0
  19. package/indra/ctc.js +1 -0
  20. package/indra/document.js +1 -1
  21. package/indra/image.d.ts +2 -0
  22. package/indra/layer-check.d.ts +29 -15
  23. package/indra/layer-check.js +1 -1
  24. package/indra/layer-gaps.d.ts +23 -0
  25. package/indra/layer-gaps.js +1 -0
  26. package/indra/layer-math.d.ts +13 -0
  27. package/indra/layer-math.js +1 -0
  28. package/indra/layout-post.d.ts +17 -2
  29. package/indra/layout-post.js +5 -5
  30. package/indra/line-thumbs.d.ts +34 -0
  31. package/indra/line-thumbs.js +1 -0
  32. package/indra/lines.d.ts +1 -1
  33. package/indra/lines.js +1 -1
  34. package/indra/math-decoder.d.ts +16 -0
  35. package/indra/math-decoder.js +1 -0
  36. package/indra/math-span-img.d.ts +61 -0
  37. package/indra/math-span-img.js +1 -0
  38. package/indra/math-splice.d.ts +46 -0
  39. package/indra/math-splice.js +1 -0
  40. package/indra/math-text.d.ts +98 -0
  41. package/indra/math-text.js +1 -0
  42. package/indra/math.d.ts +48 -9
  43. package/indra/math.js +1 -1
  44. package/indra/numeric.d.ts +8 -0
  45. package/indra/numeric.js +1 -1
  46. package/indra/order-post.js +1 -1
  47. package/indra/page-layout.d.ts +22 -0
  48. package/indra/page-layout.js +1 -0
  49. package/indra/page-tables.d.ts +32 -0
  50. package/indra/page-tables.js +1 -0
  51. package/indra/pipeline.d.ts +24 -10
  52. package/indra/pipeline.js +1 -1
  53. package/indra/py-text.d.ts +14 -0
  54. package/indra/py-text.js +1 -0
  55. package/indra/py-unicode.d.ts +28 -0
  56. package/indra/py-unicode.js +1 -0
  57. package/indra/rec-preproc.d.ts +8 -1
  58. package/indra/rec-preproc.js +1 -1
  59. package/indra/recognize.d.ts +19 -8
  60. package/indra/recognize.js +1 -1
  61. package/indra/recognizers.d.ts +40 -13
  62. package/indra/recognizers.js +1 -1
  63. package/indra/sequence-matcher.d.ts +34 -0
  64. package/indra/sequence-matcher.js +1 -0
  65. package/indra/symbol-digits.d.ts +29 -0
  66. package/indra/symbol-digits.js +1 -0
  67. package/indra/table-block-features.d.ts +38 -0
  68. package/indra/table-block-features.js +1 -0
  69. package/indra/table-decode.d.ts +50 -0
  70. package/indra/table-decode.js +4 -0
  71. package/indra/table-features.d.ts +34 -0
  72. package/indra/table-features.js +1 -0
  73. package/indra/table-heads.d.ts +15 -0
  74. package/indra/table-heads.js +2 -0
  75. package/indra/table-rel.d.ts +42 -0
  76. package/indra/table-rel.js +1 -0
  77. package/indra/table-split.d.ts +44 -0
  78. package/indra/table-split.js +1 -0
  79. package/indra/table-text.d.ts +15 -0
  80. package/indra/table-text.js +1 -0
  81. package/indra/table-verify.d.ts +80 -0
  82. package/indra/table-verify.js +1 -0
  83. package/indra/text-runs.d.ts +4 -0
  84. package/indra/text-runs.js +1 -1
  85. package/indra/textlayer.d.ts +18 -0
  86. package/indra/textlayer.js +1 -1
  87. package/indra/tiles.d.ts +20 -0
  88. package/indra/tiles.js +1 -0
  89. package/indra/ts-image-ops.js +1 -1
  90. package/indra/turn-check.d.ts +30 -0
  91. package/indra/turn-check.js +1 -0
  92. package/indra/types.d.ts +69 -5
  93. package/indra/upright.d.ts +1 -1
  94. package/indra/upright.js +1 -1
  95. package/indra/util.d.ts +8 -0
  96. package/indra/util.js +1 -1
  97. package/indra/vocab.d.ts +11 -0
  98. package/indra/vocab.js +1 -1
  99. package/interface.d.ts +9 -4
  100. package/mobile/platform.mobile.d.ts +1 -0
  101. package/mobile/platform.mobile.js +1 -1
  102. package/model-catalogue.d.ts +23 -7
  103. package/model-catalogue.js +1 -1
  104. package/package.json +2 -2
  105. package/pdf/pdfium.d.ts +2 -0
  106. package/pdf/pdfium.js +1 -1
  107. package/processor/indra-ocr.service.d.ts +4 -3
  108. package/processor/indra-ocr.service.js +1 -1
  109. package/processor/platform.node.d.ts +1 -0
  110. package/processor/platform.node.js +1 -1
  111. package/web/platform.web.d.ts +1 -0
  112. package/web/platform.web.js +1 -1
@@ -0,0 +1,15 @@
1
+ export declare const N_REFINE_TEXT = 13;
2
+ /** zlib.crc32 of a byte string. */
3
+ export declare function crc32(bytes: Uint8Array): number;
4
+ /**
5
+ * Hashed word ids in [1, nVocab) (lower case NFKC, every digit 0). A word with a
6
+ * letter outside the Latin script gets id 0 (no word embedding).
7
+ */
8
+ export declare function wordIds(texts: readonly string[], nVocab: number): number[];
9
+ /**
10
+ * [N, N_REFINE_TEXT] content features of each word for tsr_refine.onnx: has a
11
+ * digit, digit share, letter share, number form, first letter upper, all upper,
12
+ * length, ends with ':', has '%', has a currency sign, has a bracket, a dash or
13
+ * n/a, a footnote mark.
14
+ */
15
+ export declare function refineTextFeatures(texts: readonly string[]): Float32Array;
@@ -0,0 +1 @@
1
+ import{LETTER,LOWER,PY_SPACE,UPPER,chars}from"./py-text.js";import{hasLatinName,isDigit,pyLen,pyStrip}from"./py-unicode.js";import{item}from"./util.js";export let N_REFINE_TEXT=13;let DECIMAL=/\p{Nd}/gu;let CRC_TABLE=Uint32Array.from({length:256},(_,n)=>{let c=n;for(let k=0;k<8;k++)c=c&1?3988292384^c>>>1:c>>>1;return c>>>0});export function crc32(bytes){let c=4294967295;for(let b of bytes)c=item(CRC_TABLE,(c^b)&255)^c>>>8;return(c^4294967295)>>>0}let utf8=new TextEncoder;export function wordIds(texts,nVocab){return texts.map((t)=>{let s=t.normalize("NFKC").toLowerCase().replace(DECIMAL,"0");for(let c of s)if(LETTER.test(c)&&!hasLatinName(c))return 0;return crc32(utf8.encode(s))%(nVocab-1)+1})}let REF_NUM=new RegExp(`^[(\\[]?[-+${chars(8722,8211)}]?[$${chars(8364,163,165)}]?[(\\[]?\\p{Nd}[\\p{Nd},.${PY_SPACE}]*[%)\\]]*\\*{0,3}$`,"u");let REF_DASH=new Set(["-",chars(8211),chars(8212),chars(8722),"n/a","na","nd","n.a.","nr",chars(8230),"...",chars(183)]);let REF_MARK=new Set(["*","**","***",chars(8224),chars(8225),chars(167),chars(182),"#"]);let CURRENCY=chars(36,8364,163,165);export function refineTextFeatures(texts){let out=new Float32Array(texts.length*N_REFINE_TEXT);for(const[i,t]of texts.entries()){let s=pyStrip(t.normalize("NFKC"));if(!s)continue;let n=pyLen(s);let cps=[...s];let nd=cps.filter(isDigit).length;let letters=cps.filter((c)=>LETTER.test(c));let row=out.subarray(i*N_REFINE_TEXT,(i+1)*N_REFINE_TEXT);row[0]=nd>0?1:0;row[1]=nd/n;row[2]=letters.length/n;row[3]=REF_NUM.test(s)?1:0;row[4]=letters.length>0&&UPPER.test(item(letters,0))?1:0;row[5]=letters.length>=2&&letters.every((c)=>UPPER.test(c))?1:0;row[6]=Math.log1p(n)/3;row[7]=s.endsWith(":")?1:0;row[8]=s.includes("%")?1:0;row[9]=cps.some((c)=>CURRENCY.includes(c))?1:0;row[10]=cps.some((c)=>"()[]".includes(c))?1:0;row[11]=REF_DASH.has(s.toLowerCase())?1:0;row[12]=REF_MARK.has(s)||n===1&&LETTER.test(s)&&LOWER.test(s)?1:0}return out}
@@ -0,0 +1,80 @@
1
+ import type { Gray } from "./image.js";
2
+ import type { Cell, TableMap } from "./layout-post.js";
3
+ import type { Box } from "./rec-preproc.js";
4
+ import type { BlockFeatures } from "./table-block-features.js";
5
+ /** What `blockFeatures` reads about one Table block. */
6
+ export type BlockInput = {
7
+ blk: readonly number[];
8
+ boxes: readonly Box[];
9
+ texts: readonly string[];
10
+ /** Class logits [n, C] of the order model, flat. */
11
+ cls: Float32Array;
12
+ /** The block's HTML table, as written. */
13
+ html: string;
14
+ gray?: Gray;
15
+ /** Table blocks on the page. */
16
+ nTables: number;
17
+ headsOk: boolean;
18
+ /** Skip the ruling features (0): `apply` computes them only when they can change the decision. */
19
+ withRuling?: boolean;
20
+ };
21
+ export declare function blockFeatures(input: BlockInput): BlockFeatures;
22
+ /** One weight set: a logistic model over named features. */
23
+ export type VerifyWeights = {
24
+ features: string[];
25
+ mean: number[];
26
+ scale: number[];
27
+ weights: number[];
28
+ bias: number;
29
+ threshold: number;
30
+ };
31
+ /** table_verify.json: the weights for pages read by OCR and, optionally, for pages read from a PDF text layer. */
32
+ export type VerifyFile = VerifyWeights & {
33
+ layer?: VerifyWeights;
34
+ };
35
+ /** What `TableVerifier.apply` reads about one page. */
36
+ export type VerifyInput = {
37
+ boxes: readonly Box[];
38
+ texts: readonly string[];
39
+ order: readonly number[];
40
+ /** Class logits [n, C], flat. */
41
+ cls: Float32Array;
42
+ /** Same-block logits [n, n], flat. */
43
+ same: Float32Array;
44
+ /** The order model's table heads [3, n, n], flat, when the page uses them. */
45
+ tab?: Float32Array;
46
+ cells?: ReadonlyMap<number, readonly Cell[]>;
47
+ /** HTML read by tsr_rel.onnx per table block. */
48
+ tables?: TableMap;
49
+ gray?: Gray;
50
+ };
51
+ /** `cls` and `tables` as given when `relabelled` is false: the same objects. */
52
+ export type VerifyResult = {
53
+ cls: Float32Array;
54
+ tables: TableMap | undefined;
55
+ relabelled: boolean;
56
+ };
57
+ /** The verifiers of a table_verify.json: for OCR pages, and for PDF text-layer pages (null when the file has none). */
58
+ export type VerifierSet = {
59
+ ocr: TableVerifier;
60
+ layer: TableVerifier | null;
61
+ };
62
+ export declare class TableVerifier {
63
+ private readonly w;
64
+ readonly threshold: number;
65
+ constructor(w: VerifyWeights);
66
+ /** The verifiers of a parsed table_verify.json. */
67
+ static load(file: VerifyFile): VerifierSet;
68
+ /**
69
+ * The decision (P(false) >= threshold) when it holds for every value of the
70
+ * ruling features (each in [0, 1]), else null: `ruling` then has to run. The same
71
+ * decisions as computing everything.
72
+ */
73
+ decided(feats: BlockFeatures): boolean | null;
74
+ pFalse(feats: BlockFeatures): number;
75
+ /**
76
+ * Every false table relabelled: its lines lose the Table class and its tsr_rel
77
+ * table is dropped. The inputs are returned unchanged when no block is relabelled.
78
+ */
79
+ apply(input: VerifyInput): VerifyResult;
80
+ }
@@ -0,0 +1 @@
1
+ export class TableVerifier{w;threshold;constructor(w){this.w=w;let n=w.features.length;if(w.mean.length!==n||w.scale.length!==n||w.weights.length!==n)throw new RangeError("table_verify weights: features, mean, scale and weights differ in length");this.threshold=w.threshold}static load(file){return{ocr:new TableVerifier(file),layer:file.layer?new TableVerifier(file.layer):null}}decided(feats){let decisions=new Set;for(let rule_h of[0,1])for(let rule_v of[0,1])decisions.add(this.pFalse({...feats,rule_h,rule_v})>=this.threshold);return decisions.size===1?decisions.values().next().value??null:null}pFalse(feats){const{features,mean:mu,scale,weights,bias}=this.w;let dot=0;for(const[k,name]of features.entries()){let v=feats[name];if(v===undefined)throw new RangeError(`table_verify: no feature "${name}"`);dot+=(finite(v)-item(mu,k))/item(scale,k)*item(weights,k)}let z=Math.min(Math.max(dot+bias,-CLIP),CLIP);return 1/(1+Math.exp(-z))}apply(input){const{boxes,texts,order,cls,same,tab,cells,tables,gray}=input;let n=boxes.length;let c=cls.length/n;let blocks=splitBlocks(order,same,n).filter((blk)=>blockClass(cls,blk)===TABLE);let outCls=cls;let dropped;for(let blk of blocks){let key=blockKey(blk);let read=tables?.get(key);let html=read??blockPart(blk,boxes,texts,cls,true,cells,tab)??"";let lineBoxes=blk.map((i)=>item(boxes,i));let headsOk=blk.length>1&&!!tab&&headsPlausible(lineBoxes,subTab(tab,n,blk));let feats=blockFeatures({blk,boxes,texts,cls,html,gray,nTables:blocks.length,headsOk,withRuling:false});feats["tsr"]=read===undefined?0:1;let isFalse=this.decided(feats);if(isFalse===null){let bb=[Math.min(...lineBoxes.map((x)=>x[0])),Math.min(...lineBoxes.map((x)=>x[1])),Math.max(...lineBoxes.map((x)=>x[2])),Math.max(...lineBoxes.map((x)=>x[3]))];[feats["rule_h"],feats["rule_v"]]=ruling(gray,bb);isFalse=this.pFalse(feats)>=this.threshold}if(!isFalse)continue;if(outCls===cls){outCls=cls.slice();if(tables?.size)dropped=new Map(tables)}for(let i of blk)outCls[i*c+TABLE]=-1e4;dropped?.delete(key)}return{cls:outCls,tables:dropped??tables,relabelled:outCls!==cls}}}import{TABLE,blockKey,blockPart,splitBlocks}from"./layout-post.js";import{sumF32}from"./numeric.js";import{blockClass,medianF32}from"./order-post.js";import{PY_SPACE,chars}from"./py-text.js";import{pyLen,pySplit,pyStrip}from"./py-unicode.js";import{alignment,parseTable,ruling,spreadF32}from"./table-block-features.js";import{headsPlausible,subTab}from"./table-heads.js";import{item}from"./util.js";let f=Math.fround;let NUM=new RegExp(`^[${PY_SPACE}$${chars(8364,163,165)}%()+\\-${chars(8211)}.,:/0-9]+$`);let MATH=new RegExp(`\\$|\\\\[A-Za-z]+|[=+${chars(215,247,177,8721,8747,8730,8734,8804,8805,8800,8776)}^_{}]`,"g");let WHOLE_MATH=/^\$[^$]+\$$/;let SENT=new RegExp(`[.!?${chars(12290,65281,65311)}]$`);let mean=(v)=>v.reduce((a,b)=>a+b,0)/v.length;function medianOfInts(v){let s=v.toSorted((a,b)=>a-b);let m=Math.floor(s.length/2);return s.length%2?item(s,m):(item(s,m-1)+item(s,m))/2}function classProbs(cls,n,blk){let c=cls.length/n;let z=Array.from({length:c},()=>0);for(let i of blk)for(let k=0;k<c;k++)z[k]=f(item(z,k)+item(cls,i*c+k));let top=Math.max(...z);let p=z.map((v)=>f(Math.exp(f(v-top))));let total=sumF32(p);return p.map((v)=>f(v/total))}export function blockFeatures(input){const{blk,boxes,texts,cls,html,gray,nTables,headsOk,withRuling=true}=input;let b=blk.map((i)=>item(boxes,i));let H=gray?gray.height:Math.max(...boxes.map((x)=>x[3]));let W=gray?gray.width:Math.max(...boxes.map((x)=>x[2]));let bb=[Math.min(...b.map((x)=>x[0])),Math.min(...b.map((x)=>x[1])),Math.max(...b.map((x)=>x[2])),Math.max(...b.map((x)=>x[3]))];let hts=b.map((x)=>f(x[3]-x[1]));let pageH=medianF32(boxes.map((x)=>f(x[3]-x[1])))||1;let rows=parseTable(html);let ncol=rows.length?rows.map((r)=>r.length):[0];let maxc=Math.max(...ncol);let cells=rows.flat();let full=cells.filter(Boolean);let lt=blk.map((i)=>pyStrip(item(texts,i)));let allTxt=lt.join(" ");let keyValue=(r)=>r.length===2&&!!r[0]&&!!r[1]&&(r[0].endsWith(":")||pyLen(r[0])<=40&&!NUM.test(r[0]));let kv=maxc===2&&rows.length?rows.filter(keyValue).length/rows.length:0;const[rh,rv]=withRuling?ruling(gray,bb):[0,0];let width=f(f(bb[2]-bb[0])/f(Math.max(1,W)));let out={lines:Math.log1p(blk.length),rows:Math.log1p(rows.length),cols:Math.log1p(medianOfInts(ncol)),maxcols:Math.log1p(maxc),cells:Math.log1p(cells.length),rows_le3:rows.length<=3?1:0,cols_2:maxc===2?1:0,fill:full.length/Math.max(1,rows.length*maxc),words_cell:Math.log1p(full.length?mean(full.map((c)=>pySplit(c).length)):0),num_cells:full.filter((c)=>NUM.test(c)).length/Math.max(1,full.length),kv2:kv,math_tok:[...allTxt.matchAll(MATH)].length/Math.max(1,pySplit(allTxt).length),whole_math:lt.filter((t)=>WHOLE_MATH.test(t)).length/Math.max(1,lt.length),sent_end:lt.filter((t)=>SENT.test(t)).length/Math.max(1,lt.length),chars_line:Math.log1p(lt.length?mean(lt.map(pyLen)):0),lh_cv:spreadF32(hts),lh_rel:f(medianF32(hts)/f(pageH)),area:f(f(f(bb[2]-bb[0])*f(bb[3]-bb[1]))/f(Math.max(1,W*H))),width,tables_page:Math.log1p(nTables),rule_h:rh,rule_v:rv,heads_ok:headsOk?1:0};for(const[k,p]of classProbs(cls,boxes.length,blk).entries())out[`cls_${k}`]=p;return{...out,...alignment(b)}}let CLIP=50;function finite(v){if(Number.isNaN(v))return 0;return Math.min(Math.max(v,-Number.MAX_VALUE),Number.MAX_VALUE)}
@@ -6,6 +6,10 @@ export type RtlPairs = {
6
6
  };
7
7
  /** Replacement, private-use, surrogate, unassigned and control characters (tab excepted). */
8
8
  export declare function badCharCount(text: string): number;
9
+ /** [2, 3] map from PDF page space to the rendered frame (points, top-left origin), from FPDF_PageToDevice. */
10
+ export declare function deviceAffine(page: PdfPageSource): number[];
11
+ /** Rendered-frame points in the frame of the page turned upright again (np.rot90(gray, -turn)). */
12
+ export declare function turnFrame(x: number, y: number, w: number, h: number, turn: number): [number, number];
9
13
  /**
10
14
  * Whether a page's upright characters run top to bottom (vertical writing):
11
15
  * most steps between neighbouring characters go down, not right.
@@ -1,2 +1,2 @@
1
- import{pyRound}from"./det-post.js";import{isRtl}from"./rtl.js";import{isPySpace,item}from"./util.js";let BAD=/^[\p{Co}\p{Cs}\p{Cn}]$/u;let CONTROL=/^\p{Cc}$/u;export function badCharCount(text){let n=0;for(let c of text){if(c.codePointAt(0)===65533||BAD.test(c)||CONTROL.test(c)&&c!=="\t")n++}return n}function deviceAffine(page){const[w,h]=page.size();let S=1000;let dw=pyRound(w*S);let dh=pyRound(h*S);let dev=(x,y)=>{const[dx,dy]=page.pageToDevice(dw,dh,x,y);return[dx/S,dy/S]};const[o0,o1]=dev(0,0);const[ex0,ex1]=dev(1,0);const[ey0,ey1]=dev(0,1);return[ex0-o0,ey0-o0,o0,ex1-o1,ey1-o1,o1]}function quarter(dx,dy){let q=Math.atan2(dy,dx)/(Math.PI/2);let k=pyRound(q);return Math.abs(q-k)<0.01?(k%4+4)%4:undefined}function turnFrame(x,y,w,h,turn){if(turn===1)return[h-y,x];if(turn===2)return[w-x,h-y];if(turn===3)return[y,w-x];return[x,y]}export function verticalLayout(stats){const[down,right]=stats.steps??[0,0];return down>=30&&down>2*right}export function pageTurn(stats){let q=stats.quarters;let k=1;for(let i of[2,3])if(q[i]>q[k])k=i;return q[k]>0.5*Math.max(stats.chars,1)?k:0}export function codePoint(u,u2=0){if(u>=55296&&u<=56319&&u2>=56320&&u2<=57343){return[String.fromCodePoint(65536+(u-55296<<10)+(u2-56320)),true]}if(u>=55296&&u<=57343)return[String.fromCharCode(65533),false];return[String.fromCharCode(u),false]}export function extractRuns(page,turn=0,frame=turn){const[a00=0,a01=0,a02=0,a10=0,a11=0,a12=0]=deviceAffine(page);let l00=a00;let l01=-a01;let l10=-a10;let l11=a11;let quarters=new Map;let chars=[];let raw=[];let breaks=[];let qs=[];let curQ=0;let stats={chars:0,rotated:0,bad:0,quarters:[0,0,0,0]};let all=page.chars();let low=false;for(const[i,ch]of all.entries()){if(low){low=false;continue}let u2=ch.unit>=55296&&ch.unit<=56319?all[i+1]?.unit??0:0;let c;[c,low]=codePoint(ch.unit,u2);if(c==="\r"||c===`
1
+ import{pyRound}from"./det-post.js";import{isRtl}from"./rtl.js";import{isPySpace,item}from"./util.js";let BAD=/^[\p{Co}\p{Cs}\p{Cn}]$/u;let CONTROL=/^\p{Cc}$/u;export function badCharCount(text){let n=0;for(let c of text){if(c.codePointAt(0)===65533||BAD.test(c)||CONTROL.test(c)&&c!=="\t")n++}return n}export function deviceAffine(page){const[w,h]=page.size();let S=1000;let dw=pyRound(w*S);let dh=pyRound(h*S);let dev=(x,y)=>{const[dx,dy]=page.pageToDevice(dw,dh,x,y);return[dx/S,dy/S]};const[o0,o1]=dev(0,0);const[ex0,ex1]=dev(1,0);const[ey0,ey1]=dev(0,1);return[ex0-o0,ey0-o0,o0,ex1-o1,ey1-o1,o1]}function quarter(dx,dy){let q=Math.atan2(dy,dx)/(Math.PI/2);let k=pyRound(q);return Math.abs(q-k)<0.01?(k%4+4)%4:undefined}export function turnFrame(x,y,w,h,turn){if(turn===1)return[h-y,x];if(turn===2)return[w-x,h-y];if(turn===3)return[y,w-x];return[x,y]}export function verticalLayout(stats){const[down,right]=stats.steps??[0,0];return down>=30&&down>2*right}export function pageTurn(stats){let q=stats.quarters;let k=1;for(let i of[2,3])if(q[i]>q[k])k=i;return q[k]>0.5*Math.max(stats.chars,1)?k:0}export function codePoint(u,u2=0){if(u>=55296&&u<=56319&&u2>=56320&&u2<=57343){return[String.fromCodePoint(65536+(u-55296<<10)+(u2-56320)),true]}if(u>=55296&&u<=57343)return[String.fromCharCode(65533),false];return[String.fromCharCode(u),false]}export function extractRuns(page,turn=0,frame=turn){const[a00=0,a01=0,a02=0,a10=0,a11=0,a12=0]=deviceAffine(page);let l00=a00;let l01=-a01;let l10=-a10;let l11=a11;let quarters=new Map;let chars=[];let raw=[];let breaks=[];let qs=[];let curQ=0;let stats={chars:0,rotated:0,bad:0,quarters:[0,0,0,0]};let all=page.chars();let low=false;for(const[i,ch]of all.entries()){if(low){low=false;continue}let u2=ch.unit>=55296&&ch.unit<=56319?all[i+1]?.unit??0:0;let c;[c,low]=codePoint(ch.unit,u2);if(c==="\r"||c===`
2
2
  `){breaks.push(chars.length);continue}if(c==="\x02")c="-";if(!isPySpace(c)){stats.chars++;stats.bad+=badCharCount(c);let q=quarters.get(ch.angle);if(!quarters.has(ch.angle)){let cos=Math.cos(ch.angle);let sin=Math.sin(ch.angle);q=quarter(l00*cos+l01*sin,l10*cos+l11*sin);quarters.set(ch.angle,q)}if(q!==undefined){stats.quarters[q]++}if(q!==turn)stats.rotated++;if(q===undefined){breaks.push(chars.length);continue}curQ=((q-turn)%4+4)%4}if(!ch.box)throw new Error("Failed to get charbox.");chars.push(c);qs.push(curQ);raw.push(ch.box)}if(!chars.length)return{runs:[],stats};const[w,h]=page.size();let corners=raw.map(([l,b,r,t])=>{let xs=[l,r,l,r];let ys=[b,b,t,t];return{px:xs.map((x,k)=>a00*x+a01*item(ys,k)+a02),py:xs.map((x,k)=>a10*x+a11*item(ys,k)+a12)}});let boxes=corners.map(({px,py})=>[Math.min(...px),Math.min(...py),Math.max(...px),Math.max(...py)]);let cx=boxes.map(([x0,,x1])=>(x0+x1)/2);let cy=boxes.map(([,y0,,y1])=>(y0+y1)/2);let visible=boxes.map((_,i)=>{let x=item(cx,i);let y=item(cy,i);return x>=0&&x<=w&&y>=0&&y<=h});stats.off_page=visible.filter((v)=>!v).length;let cut=new Set(breaks.filter((b)=>b>0&&b<chars.length).map((b)=>b-1));let down=0;let right=0;for(let i=0;i+1<chars.length;i++){if(cut.has(i)||item(qs,i)||item(qs,i+1))continue;if(isPySpace(item(chars,i))||isPySpace(item(chars,i+1)))continue;let b=item(boxes,i);let ch=Math.max(b[3]-b[1],0.001);let dx=Math.abs(item(cx,i+1)-item(cx,i));let dyRaw=item(cy,i+1)-item(cy,i);let dy=Math.abs(dyRaw);if(dx>3*ch||dy>3*ch)continue;if(dyRaw>0.3*ch&&dx<0.3*ch)down++;if(dx>0.3*ch&&dy<0.3*ch)right++}stats.steps=[down,right];if(frame){boxes=corners.map(({px,py})=>{let pts=px.map((x,k)=>turnFrame(x,item(py,k),w,h,frame));let tx=pts.map((p)=>p[0]);let ty=pts.map((p)=>p[1]);return[Math.min(...tx),Math.min(...ty),Math.max(...tx),Math.max(...ty)]})}let turns=qs.flatMap((q,i)=>i>0&&q!==qs[i-1]?[i]:[]);let runs=[];let start=0;for(let end of[...new Set([...breaks,...turns,chars.length])].toSorted((p,q)=>p-q)){let seg=[];for(let i=start;i<end;i++)if(visible[i])seg.push([item(chars,i),item(boxes,i)]);let q=start<qs.length?item(qs,start):0;start=end;let ink=seg.filter(([c])=>!isPySpace(c)).map(([,b])=>b);if(!ink.length)continue;if(frame!==turn&&!q&&ink.length>1){let first=item(ink,0);let last=item(ink,ink.length-1);let dx=Math.abs((last[0]+last[2])/2-(first[0]+first[2])/2);let dy=Math.abs((last[1]+last[3])/2-(first[1]+first[3])/2);if(dy>2*dx)q=1}runs.push({bbox:[Math.min(...ink.map((b)=>b[0])),Math.min(...ink.map((b)=>b[1])),Math.max(...ink.map((b)=>b[2])),Math.max(...ink.map((b)=>b[3]))],text:collapseSpaces(seg.map(([c])=>c).join("")),chars:seg,quarter:q,seq:runs.length})}return{runs,stats}}export function visualRtlFrac(runs){let pairs=0;let right=0;for(let r of runs){for(let i=1;i<r.chars.length;i++){const[a,ba]=item(r.chars,i-1);const[b,bb]=item(r.chars,i);if(isRtl(a)&&isRtl(b)){pairs++;if(bb[0]+bb[2]>ba[0]+ba[2])right++}}}return{pairs,share:right/Math.max(pairs,1)}}export function collapseSpaces(s){return[...s].reduce((words,c)=>{if(isPySpace(c))words.push("");else words[words.length-1]+=c;return words},[""]).filter(Boolean).join(" ")}
@@ -31,6 +31,15 @@ export type PdfPageSource = {
31
31
  rotation(): number;
32
32
  /** Set the page's /Rotate (degrees clockwise) for the reads that follow. */
33
33
  setRotation(degrees: number): void;
34
+ /**
35
+ * Boxes (x0, y0, x1, y1, page space) of the digits that may be symbol
36
+ * glyphs: an ASCII digit in a symbolic font (PDF font flag 4), or one whose
37
+ * font differs from the fonts of the characters on both sides of it in its
38
+ * word; a digit smaller than its neighbours (a superscript) is left out.
39
+ * Some fonts give a symbol glyph a digit's code and no Unicode map (one
40
+ * publisher's minus comes out '2', its plus-minus '6').
41
+ */
42
+ symbolDigitBoxes(): Box[];
34
43
  };
35
44
  /**
36
45
  * One text-layer run: its box, its text, and its characters with boxes
@@ -48,6 +57,11 @@ export type TextLayerStats = {
48
57
  chars: number;
49
58
  rotated: number;
50
59
  bad: number;
60
+ /** Runs with bad character codes set apart for OCR (the rest of the layer is sound). */
61
+ bad_runs?: number;
62
+ /** Digits that may be symbol glyphs, and how many of them the page image turned into symbols. */
63
+ symbol_boxes?: number;
64
+ symbol_fixed?: number;
51
65
  /** Characters at each quarter turn on the rendered page. */
52
66
  quarters: [number, number, number, number];
53
67
  off_page?: number;
@@ -76,6 +90,10 @@ export type TextLayer = {
76
90
  stats: TextLayerStats;
77
91
  /** Runs at other quarter turns (a sideways table head, a chart axis label). */
78
92
  rotated: TextLine[];
93
+ /** Runs with bad character codes in an otherwise sound layer: their lines are read from pixels. */
94
+ rejected: TextLine[];
95
+ /** Boxes (points, in the runs' frame) of digits that may be symbol glyphs (symbolDigitBoxes). */
96
+ symbolBoxes: Box[];
79
97
  };
80
98
  /**
81
99
  * Text-layer runs of a page and the verdict on them: invisible text marks an
@@ -1 +1 @@
1
- import{extractRuns,pageTurn,verticalLayout,visualRtlFrac}from"./text-runs.js";import{roundTo,rot90}from"./upright.js";export{badCharCount,codePoint,collapseSpaces,extractRuns,pageTurn,verticalLayout,visualRtlFrac}from"./text-runs.js";let MAX_INVISIBLE_FRAC=0.05;let MAX_BAD_CHAR_FRAC=0.005;let MAX_NO_INK_LINE_FRAC=0.03;let MAX_VISUAL_RTL_FRAC=0.25;let MIN_RTL_PAIRS=20;let DARK=160;let TEXT_RENDER_INVISIBLE=3;export let BROKEN_FONT_MAP="broken font map";export let VISUAL_RTL="right-to-left text in visual order";function invisibleTextFrac(page){let modes=page.textRenderModes();return modes.length?modes.filter((m)=>m===TEXT_RENDER_INVISIBLE).length/modes.length:0}function noInkFrac(gray,runs,scale){let empty=0;for(const{bbox:[x0,y0,x1,y1]}of runs){let r0=Math.max(0,Math.trunc(y0*scale));let r1=Math.min(gray.height,Math.trunc(y1*scale)+1);let c0=Math.max(0,Math.trunc(x0*scale));let c1=Math.min(gray.width,Math.trunc(x1*scale)+1);let ink=false;for(let y=r0;y<r1&&!ink;y++){for(let x=c0;x<c1;x++){if((gray.data[y*gray.width+x]??255)<DARK){ink=true;break}}}if(!ink)empty++}return empty/Math.max(runs.length,1)}let pct=(x)=>`${roundTo(x*100,0)}%`;export function readTextLayer(page,gray,scale,turn=0,frame=turn){const[w,h]=page.size();let size=frame%2?[h,w]:[w,h];let inv=invisibleTextFrac(page);let fail=(lines,reason,stats,rotated=[])=>({lines,size,trusted:false,reason,stats,rotated});if(inv>MAX_INVISIBLE_FRAC){return fail([],`invisible text ${pct(inv)} (OCR layer)`,{chars:0,rotated:0,bad:0,quarters:[0,0,0,0]})}const{runs:all,stats}=extractRuns(page,turn,frame);stats.turn=turn;stats.frame=frame;let rotated=all.filter((r)=>r.quarter);let runs=all.filter((r)=>!r.quarter);if(!runs.length)return fail([],"no text layer",stats,rotated);if(stats.bad>MAX_BAD_CHAR_FRAC*Math.max(stats.chars,1)){return fail(runs,BROKEN_FONT_MAP,stats,rotated)}const{pairs,share}=frame===turn?visualRtlFrac(runs):{pairs:0,share:0};if(pairs>=MIN_RTL_PAIRS&&share>MAX_VISUAL_RTL_FRAC){stats.visual_rtl=roundTo(share,3);return fail(runs,VISUAL_RTL,stats,rotated)}let empty=noInkFrac(gray,runs,scale);stats.no_ink=roundTo(empty,4);if(empty>MAX_NO_INK_LINE_FRAC){return fail(runs,`${pct(empty)} of text runs have no ink`,stats,rotated)}return{lines:runs,size,trusted:true,reason:"",stats,rotated}}export async function uprightTextLayer(page,check,scale,mode,readUpright){let tl=readTextLayer(page,check,scale);let k=pageTurn(tl.stats);let rot=page.rotation();if(k&&(rot+90*k)%360===0){page.setRotation(0);tl=readTextLayer(page,page.render(scale),scale);if(tl.lines.length&&(tl.trusted||mode==="text")){tl.stats.turn=k;let out=await readUpright(tl);if(out)return{tl,page:out}}page.setRotation(rot);tl=readTextLayer(page,rot90(check,k),scale,k)}else if(k){tl=readTextLayer(page,rot90(check,k),scale,k)}else if(verticalLayout(tl.stats)){tl=readTextLayer(page,rot90(check,3),scale,0,3);tl.stats.vertical=true}return{tl}}
1
+ import{isAlpha}from"./py-unicode.js";import{badCharCount,deviceAffine,extractRuns,pageTurn,turnFrame,verticalLayout,visualRtlFrac}from"./text-runs.js";import{roundTo,rot90}from"./upright.js";export{badCharCount,codePoint,collapseSpaces,extractRuns,pageTurn,verticalLayout,visualRtlFrac}from"./text-runs.js";let MAX_INVISIBLE_FRAC=0.05;let MAX_BAD_CHAR_FRAC=0.005;let MAX_NO_INK_LINE_FRAC=0.03;let MAX_VISUAL_RTL_FRAC=0.25;let MIN_RTL_PAIRS=20;let DARK=224;let TEXT_RENDER_INVISIBLE=3;export let BROKEN_FONT_MAP="broken font map";export let VISUAL_RTL="right-to-left text in visual order";function invisibleTextFrac(page){let modes=page.textRenderModes();return modes.length?modes.filter((m)=>m===TEXT_RENDER_INVISIBLE).length/modes.length:0}function noInkFrac(gray,runs,scale){let empty=0;for(const{bbox:[x0,y0,x1,y1]}of runs){let r0=Math.max(0,Math.trunc(y0*scale));let r1=Math.min(gray.height,Math.trunc(y1*scale)+1);let c0=Math.max(0,Math.trunc(x0*scale));let c1=Math.min(gray.width,Math.trunc(x1*scale)+1);let ink=false;for(let y=r0;y<r1&&!ink;y++){for(let x=c0;x<c1;x++){if((gray.data[y*gray.width+x]??255)<DARK){ink=true;break}}}if(!ink)empty++}return empty/Math.max(runs.length,1)}let pct=(x)=>`${roundTo(x*100,0)}%`;export function readTextLayer(page,gray,scale,turn=0,frame=turn){const[w,h]=page.size();let size=frame%2?[h,w]:[w,h];let inv=invisibleTextFrac(page);let fail=(lines,reason,stats,rotated=[])=>({lines,size,trusted:false,reason,stats,rotated,rejected:[],symbolBoxes:[]});if(inv>MAX_INVISIBLE_FRAC){return fail([],`invisible text ${pct(inv)} (OCR layer)`,{chars:0,rotated:0,bad:0,quarters:[0,0,0,0]})}const{runs:all,stats}=extractRuns(page,turn,frame);stats.turn=turn;stats.frame=frame;let rotated=all.filter((r)=>r.quarter);let runs=all.filter((r)=>!r.quarter);if(!runs.length)return fail([],"no text layer",stats,rotated);let rejected=[];if(stats.bad>MAX_BAD_CHAR_FRAC*Math.max(stats.chars,1)){rejected=runs.filter((r)=>badCharCount(r.text));let sound=runs.filter((r)=>!badCharCount(r.text));stats.bad_runs=rejected.length;if(!sound.length||rejected.some((r)=>Array.from(r.text).some(isAlpha))){return fail(runs,BROKEN_FONT_MAP,stats,rotated)}runs=sound}const{pairs,share}=frame===turn?visualRtlFrac(runs):{pairs:0,share:0};if(pairs>=MIN_RTL_PAIRS&&share>MAX_VISUAL_RTL_FRAC){stats.visual_rtl=roundTo(share,3);return fail(runs,VISUAL_RTL,stats,rotated)}let empty=noInkFrac(gray,runs,scale);stats.no_ink=roundTo(empty,4);if(empty>MAX_NO_INK_LINE_FRAC){return fail(runs,`${pct(empty)} of text runs have no ink`,stats,rotated)}let symbolBoxes=symbolBoxesInFrame(page,frame);stats.symbol_boxes=symbolBoxes.length;return{lines:runs,size,trusted:true,reason:"",stats,rotated,rejected,symbolBoxes}}function symbolBoxesInFrame(page,frame){let raw=page.symbolDigitBoxes();if(!raw.length)return[];const[a0=0,a1=0,a2=0,b0=0,b1=0,b2=0]=deviceAffine(page);const[w,h]=page.size();let f=Math.fround;return raw.map(([x0,y0,x1,y1])=>{let pts=[[x0,y0],[x1,y0],[x0,y1],[x1,y1]].map(([x=0,y=0])=>{let px=a0*x+a1*y+a2;let py=b0*x+b1*y+b2;return frame?turnFrame(px,py,w,h,frame):[px,py]});let xs=pts.map(([x=0])=>x);let ys=pts.map(([,y=0])=>y);return[f(Math.min(...xs)),f(Math.min(...ys)),f(Math.max(...xs)),f(Math.max(...ys))]})}export async function uprightTextLayer(page,check,scale,mode,readUpright){let tl=readTextLayer(page,check,scale);let k=pageTurn(tl.stats);let rot=page.rotation();if(k&&(rot+90*k)%360===0){page.setRotation(0);tl=readTextLayer(page,page.render(scale),scale);if(tl.lines.length&&(tl.trusted||mode==="text")){tl.stats.turn=k;let out=await readUpright(tl);if(out)return{tl,page:out}}page.setRotation(rot);tl=readTextLayer(page,rot90(check,k),scale,k)}else if(k){tl=readTextLayer(page,rot90(check,k),scale,k)}else if(verticalLayout(tl.stats)){tl=readTextLayer(page,rot90(check,3),scale,0,3);tl.stats.vertical=true}return{tl}}
@@ -0,0 +1,20 @@
1
+ import type { DetBox } from "./det-post.js";
2
+ import type { Gray } from "./image.js";
3
+ import type { DetectPass } from "./types.js";
4
+ /**
5
+ * Large pages (plans, posters): when the lines of a page whose long side is
6
+ * over TILE_MIN_SIDE px are still under ADAPTIVE_MIN_H after the adaptive
7
+ * pass, the page is detected again in overlapping tiles at TILE_SCALE (a
8
+ * 200 dpi render -> 150 dpi), where the whole-page pass sees small text at
9
+ * 30-60 dpi. Only tiles over text-bearing regions of the whole-page pass run
10
+ * (its text probability over TILE_REGION_P).
11
+ */
12
+ export declare const TILE_MIN_SIDE = 4096;
13
+ /**
14
+ * Line boxes in page pixels from overlapping TILE x TILE detector inputs at
15
+ * TILE_SCALE. Each tile keeps the boxes whose centre lies in its own core
16
+ * (the tile minus half the overlap on every inner side); a line cut by a
17
+ * core edge comes back in pieces from two tiles, and pieces from different
18
+ * tiles that share a text row and touch are joined.
19
+ */
20
+ export declare function detectTiled(gray: Gray, pass: DetectPass, detectAt: (gray: Gray, longSide: number) => Promise<DetectPass>): Promise<DetBox[]>;
package/indra/tiles.js ADDED
@@ -0,0 +1 @@
1
+ import{OUT_STRIDE,pyRound}from"./det-post.js";import{item}from"./util.js";export let TILE_MIN_SIDE=4096;let TILE_SCALE=0.75;let TILE=1024;let TILE_OVERLAP=128;let TILE_REGION_P=0.15;export async function detectTiled(gray,pass,detectAt){let f=Math.fround;const{logit,scale:s}=pass;let region=dilate5(textRegion(logit.data,TILE_REGION_P),logit.width,logit.height);const{width:w,height:h}=gray;let k=TILE_SCALE;let step=TILE-TILE_OVERLAP;let span=TILE/k;let sh=Math.ceil(h*k);let sw=Math.ceil(w*k);let ys=range(0,Math.max(1,sh-TILE_OVERLAP),step);let xs=range(0,Math.max(1,sw-TILE_OVERLAP),step);let found=[];for(let ty of ys){for(let tx of xs){let py0=ty/k;let px0=tx/k;let py1=Math.min(h,py0+span);let px1=Math.min(w,px0+span);let r0=Math.trunc(py0*s/OUT_STRIDE);let r1=Math.ceil(py1*s/OUT_STRIDE)+1;let c0=Math.trunc(px0*s/OUT_STRIDE);let c1=Math.ceil(px1*s/OUT_STRIDE)+1;if(!anyIn(region,logit.width,logit.height,r0,r1,c0,c1))continue;let crop=cropGray(gray,Math.trunc(px0),Math.trunc(py0),Math.ceil(px1),Math.ceil(py1));let tile=await detectAt(crop,pyRound(Math.max(crop.width,crop.height)*k));if(!tile.boxes.length)continue;let cs=tile.scale;let m=TILE_OVERLAP/2/k;let cx0=px0+(tx>0?m:-1e9);let cy0=py0+(ty>0?m:-1e9);let cx1=px1-(tx+step<sw-TILE_OVERLAP?m:-1e9);let cy1=py1-(ty+step<sh-TILE_OVERLAP?m:-1e9);for(const[bx0,by0,bx1,by1,score]of tile.boxes){let row=[f(f(bx0/cs)+px0),f(f(by0/cs)+py0),f(f(bx1/cs)+px0),f(f(by1/cs)+py0),score];let cx=f(f(row[0]+row[2])/2);let cy=f(f(row[1]+row[3])/2);if(!(cx>=f(cx0)&&cx<f(cx1)&&cy>=f(cy0)&&cy<f(cy1)))continue;let lh=f(row[3]-row[1]);let edge=row[0]<f(cx0+lh)||row[2]>f(cx1-lh)||row[1]<f(cy0+lh)||row[3]>f(cy1-lh);found.push({tile:`${ty},${tx}`,box:row,edge})}}}if(!found.length)return[];let boxes=found.map((b)=>b.box);let alive=found.map(()=>true);let edges=found.flatMap((b,i)=>b.edge?[i]:[]);for(let a of edges){if(!alive[a])continue;for(let c of edges){if(c===a||!alive[c]||item(found,c).tile===item(found,a).tile)continue;let A=item(boxes,a);let C=item(boxes,c);let hgt=Math.min(f(A[3]-A[1]),f(C[3]-C[1]));let vov=f(Math.min(A[3],C[3])-Math.max(A[1],C[1]));let gap=f(Math.max(A[0],C[0])-Math.min(A[2],C[2]));if(hgt>0&&vov>f(0.5*hgt)&&gap<hgt){boxes[a]=[Math.min(A[0],C[0]),Math.min(A[1],C[1]),Math.max(A[2],C[2]),Math.max(A[3],C[3]),Math.max(A[4],C[4])];alive[c]=false}}}let clip=(v,hi)=>Math.min(Math.max(v,0),hi);return boxes.filter((_,i)=>alive[i]).map(([x0,y0,x1,y1,score])=>[clip(x0,w),clip(y0,h),clip(x1,w),clip(y1,h),score])}function range(start,stop,step){let out=[];for(let v=start;v<stop;v+=step)out.push(v);return out}function textRegion(logit,p){let cut=Math.log(p/(1-p));let out=new Uint8Array(logit.length);for(const[i,v]of logit.entries())out[i]=v>cut?1:0;return out}function dilate5(src,w,h){let out=new Uint8Array(w*h);for(let y=0;y<h;y++){for(let x=0;x<w;x++){let v=0;for(let dy=-2;dy<=2&&!v;dy++){let yy=y+dy;if(yy<0||yy>=h)continue;for(let dx=-2;dx<=2;dx++){let xx=x+dx;if(xx>=0&&xx<w&&src[yy*w+xx]){v=1;break}}}out[y*w+x]=v}}return out}function anyIn(map,w,h,r0,r1,c0,c1){for(let y=Math.max(0,r0);y<Math.min(h,r1);y++){for(let x=Math.max(0,c0);x<Math.min(w,c1);x++)if(map[y*w+x])return true}return false}function cropGray(gray,x0,y0,x1,y1){let a=Math.max(0,x0);let b=Math.min(gray.width,x1);let c=Math.max(0,y0);let d=Math.min(gray.height,y1);let width=Math.max(0,b-a);let height=Math.max(0,d-c);let data=new Uint8Array(width*height);for(let y=0;y<height;y++){data.set(gray.data.subarray((c+y)*gray.width+a,(c+y)*gray.width+a+width),y*width)}return{data,width,height}}
@@ -1 +1 @@
1
- let clampByte=(v)=>Math.min(255,Math.max(0,Math.round(v)));function linearTaps(out,size){let scale=size/out;let i0=new Int32Array(out);let i1=new Int32Array(out);let w=new Float64Array(out);for(let d=0;d<out;d++){let s=Math.min(Math.max((d+0.5)*scale-0.5,0),size-1);let f=Math.floor(s);i0[d]=f;i1[d]=Math.min(f+1,size-1);w[d]=s-f}return{i0,i1,w}}function resizeLinear(src,width,height){let xs=linearTaps(width,src.width);let ys=linearTaps(height,src.height);let out=new Uint8Array(width*height);let s=src.data;for(let y=0;y<height;y++){let r0=(ys.i0[y]??0)*src.width;let r1=(ys.i1[y]??0)*src.width;let wy=ys.w[y]??0;for(let x=0;x<width;x++){let a=xs.i0[x]??0;let b=xs.i1[x]??0;let wx=xs.w[x]??0;let top=(s[r0+a]??0)*(1-wx)+(s[r0+b]??0)*wx;let bot=(s[r1+a]??0)*(1-wx)+(s[r1+b]??0)*wx;out[y*width+x]=clampByte(top*(1-wy)+bot*wy)}}return{data:out,width,height}}function areaSpans(out,size){let scale=size/out;return Array.from({length:out},(_,d)=>{let lo=d*scale;let hi=Math.min((d+1)*scale,size);let start=Math.floor(lo);let weights=[];for(let i=start;i<hi;i++)weights.push((Math.min(i+1,hi)-Math.max(i,lo))/(hi-lo));return{start,weights}})}function resizeArea(src,width,height){if(width>src.width||height>src.height)return resizeLinear(src,width,height);let xs=areaSpans(width,src.width);let ys=areaSpans(height,src.height);let out=new Uint8Array(width*height);let row=new Float64Array(width);for(const[y,sy]of ys.entries()){row.fill(0);for(const[k,wy]of sy.weights.entries()){let base=(sy.start+k)*src.width;for(const[x,sx]of xs.entries()){let acc=0;for(const[j,wx]of sx.weights.entries())acc+=(src.data[base+sx.start+j]??0)*wx;row[x]=(row[x]??0)+acc*wy}}for(let x=0;x<width;x++)out[y*width+x]=clampByte(row[x]??0)}return{data:out,width,height}}function invert([a,b,c,d,e,f]){let det=a*e-b*d;let ia=e/det;let ib=-b/det;let id=-d/det;let ie=a/det;return[ia,ib,-(ia*c+ib*f),id,ie,-(id*c+ie*f)]}function warp(src,m,width,height,edge){const[a,b,c,d,e,f]=invert(m);let out=new Uint8Array(width*height);const{width:sw,height:sh,data}=src;let read=(x,y)=>{if(x>=0&&x<sw&&y>=0&&y<sh)return data[y*sw+x]??0;if(edge==="zero")return 0;return data[Math.min(Math.max(y,0),sh-1)*sw+Math.min(Math.max(x,0),sw-1)]??0};for(let y=0;y<height;y++){let rowX=b*y+c;let rowY=e*y+f;let row=y*width;for(let x=0;x<width;x++){let sx=a*x+rowX;let sy=d*x+rowY;let x0=Math.floor(sx);let y0=Math.floor(sy);let wx=sx-x0;let wy=sy-y0;let v;if(x0>=0&&y0>=0&&x0+1<sw&&y0+1<sh){let i=y0*sw+x0;let top=(data[i]??0)*(1-wx)+(data[i+1]??0)*wx;let bot=(data[i+sw]??0)*(1-wx)+(data[i+sw+1]??0)*wx;v=top*(1-wy)+bot*wy}else if(edge==="zero"&&(x0+1<0||y0+1<0||x0>=sw||y0>=sh)){continue}else{v=(read(x0,y0)*(1-wx)+read(x0+1,y0)*wx)*(1-wy)+(read(x0,y0+1)*(1-wx)+read(x0+1,y0+1)*wx)*wy}out[row+x]=Math.round(v)}}return{data:out,width,height}}export let tsImageOps={resize(src,width,height,interpolation){if(width===src.width&&height===src.height)return{...src,data:src.data.slice()};return interpolation==="area"?resizeArea(src,width,height):resizeLinear(src,width,height)},warpReplicate(src,m,width,height){return warp(src,m,width,height,"replicate")},warpZero(src,m,width,height){return warp(src,m,width,height,"zero")}};
1
+ let clampByte=(v)=>Math.min(255,Math.max(0,Math.round(v)));function linearTaps(out,size){let scale=size/out;let i0=new Int32Array(out);let i1=new Int32Array(out);let w=new Float64Array(out);for(let d=0;d<out;d++){let s=Math.min(Math.max((d+0.5)*scale-0.5,0),size-1);let f=Math.floor(s);i0[d]=f;i1[d]=Math.min(f+1,size-1);w[d]=s-f}return{i0,i1,w}}function resizeLinear(src,width,height){let xs=linearTaps(width,src.width);let ys=linearTaps(height,src.height);let out=new Uint8Array(width*height);let s=src.data;for(let y=0;y<height;y++){let r0=(ys.i0[y]??0)*src.width;let r1=(ys.i1[y]??0)*src.width;let wy=ys.w[y]??0;for(let x=0;x<width;x++){let a=xs.i0[x]??0;let b=xs.i1[x]??0;let wx=xs.w[x]??0;let top=(s[r0+a]??0)*(1-wx)+(s[r0+b]??0)*wx;let bot=(s[r1+a]??0)*(1-wx)+(s[r1+b]??0)*wx;out[y*width+x]=clampByte(top*(1-wy)+bot*wy)}}return{data:out,width,height}}function areaSpans(out,size){let scale=size/out;return Array.from({length:out},(_,d)=>{let lo=d*scale;let hi=Math.min((d+1)*scale,size);let start=Math.floor(lo);let weights=[];for(let i=start;i<hi;i++)weights.push((Math.min(i+1,hi)-Math.max(i,lo))/(hi-lo));return{start,weights}})}function resizeArea(src,width,height){if(width>src.width||height>src.height)return resizeLinear(src,width,height);let xs=areaSpans(width,src.width);let ys=areaSpans(height,src.height);let out=new Uint8Array(width*height);let row=new Float64Array(width);for(const[y,sy]of ys.entries()){row.fill(0);for(const[k,wy]of sy.weights.entries()){let base=(sy.start+k)*src.width;for(const[x,sx]of xs.entries()){let acc=0;for(const[j,wx]of sx.weights.entries())acc+=(src.data[base+sx.start+j]??0)*wx;row[x]=(row[x]??0)+acc*wy}}for(let x=0;x<width;x++)out[y*width+x]=clampByte(row[x]??0)}return{data:out,width,height}}function invert([a,b,c,d,e,f]){let det=a*e-b*d;let ia=e/det;let ib=-b/det;let id=-d/det;let ie=a/det;return[ia,ib,-(ia*c+ib*f),id,ie,-(id*c+ie*f)]}function warp(src,m,width,height,edge){const[a,b,c,d,e,f]=invert(m);let out=new Uint8Array(width*height);const{width:sw,height:sh,data}=src;let read=(x,y)=>{if(x>=0&&x<sw&&y>=0&&y<sh)return data[y*sw+x]??0;if(edge==="zero")return 0;return data[Math.min(Math.max(y,0),sh-1)*sw+Math.min(Math.max(x,0),sw-1)]??0};for(let y=0;y<height;y++){let rowX=b*y+c;let rowY=e*y+f;let row=y*width;for(let x=0;x<width;x++){let sx=a*x+rowX;let sy=d*x+rowY;let x0=Math.floor(sx);let y0=Math.floor(sy);let wx=sx-x0;let wy=sy-y0;let v;if(x0>=0&&y0>=0&&x0+1<sw&&y0+1<sh){let i=y0*sw+x0;let top=(data[i]??0)*(1-wx)+(data[i+1]??0)*wx;let bot=(data[i+sw]??0)*(1-wx)+(data[i+sw+1]??0)*wx;v=top*(1-wy)+bot*wy}else if(edge==="zero"&&(x0+1<0||y0+1<0||x0>=sw||y0>=sh)){continue}else{v=(read(x0,y0)*(1-wx)+read(x0+1,y0)*wx)*(1-wy)+(read(x0,y0+1)*(1-wx)+read(x0+1,y0+1)*wx)*wy}out[row+x]=Math.round(v)}}return{data:out,width,height}}function resizeFloatLinear(src,width,height){let f=Math.fround;let xs=linearTaps(width,src.width);let ys=linearTaps(height,src.height);let out=new Float32Array(width*height);let s=src.data;for(let y=0;y<height;y++){let r0=(ys.i0[y]??0)*src.width;let r1=(ys.i1[y]??0)*src.width;let wy=f(ys.w[y]??0);for(let x=0;x<width;x++){let a=xs.i0[x]??0;let b=xs.i1[x]??0;let wx=f(xs.w[x]??0);let top=f(f((s[r0+a]??0)*f(1-wx))+f((s[r0+b]??0)*wx));let bot=f(f((s[r1+a]??0)*f(1-wx))+f((s[r1+b]??0)*wx));out[y*width+x]=f(f(top*f(1-wy))+f(bot*wy))}}return{data:out,width,height}}export let tsImageOps={resize(src,width,height,interpolation){if(width===src.width&&height===src.height)return{...src,data:src.data.slice()};return interpolation==="area"?resizeArea(src,width,height):resizeLinear(src,width,height)},resizeFloat(src,width,height){if(width===src.width&&height===src.height)return{...src,data:src.data.slice()};return resizeFloatLinear(src,width,height)},warpReplicate(src,m,width,height){return warp(src,m,width,height,"replicate")},warpZero(src,m,width,height){return warp(src,m,width,height,"zero")}};
@@ -0,0 +1,30 @@
1
+ import type { DetBox } from "./det-post.js";
2
+ import type { Gray } from "./image.js";
3
+ import type { Box } from "./rec-preproc.js";
4
+ import type { RecLine, Straightened } from "./types.js";
5
+ /**
6
+ * When orient.onnx is unsure but puts at least this much probability on
7
+ * "text runs top to bottom" (a quarter turn either way, or vertical columns),
8
+ * a few lines are read each way and the reading the recognizers are surest
9
+ * of picks the turn. At a thumbnail, vertical CJK columns and a page turned a
10
+ * quarter turn look alike: only the characters tell them apart.
11
+ */
12
+ export declare const SIDEWAYS_MASS = 0.8;
13
+ /** The pipeline stages the turn checks read lines with. */
14
+ export type LineReader = {
15
+ detect(gray: Gray): Promise<DetBox[]>;
16
+ recognize(gray: Gray, boxes: readonly Box[]): Promise<RecLine[]>;
17
+ straighten(gray: Gray, turns: number, skew: number, small?: Gray): Straightened;
18
+ };
19
+ /**
20
+ * The turn of a page orient.onnx is unsure of but sees as likely sideways
21
+ * (probabilities `probs`): up to SIDEWAYS_LINES of the longest lines are read
22
+ * as the page stands, turned counter-clockwise, and turned clockwise (the
23
+ * counter-clockwise lines turned half round); the reading the recognizers
24
+ * are surest of picks the side. On the counter-clockwise side, a quarter turn
25
+ * (3) and vertical columns (VERTICAL) give the same crops, so orient.onnx,
26
+ * which sees the characters' shape, picks between them.
27
+ */
28
+ export declare function readTurn(reader: LineReader, gray: Gray, skew: number, small: Gray, probs: readonly number[]): Promise<number>;
29
+ /** 2 when the longest lines read surer with the page turned half round than as it stands, else 0. */
30
+ export declare function readHalfTurn(reader: LineReader, gray: Gray, skew: number, small: Gray): Promise<number>;
@@ -0,0 +1 @@
1
+ import{VERTICAL,rot90}from"./upright.js";import{item}from"./util.js";export let SIDEWAYS_MASS=0.8;let SIDEWAYS_LINES=8;function longest(boxes){return boxes.map((b)=>[b[0],b[1],b[2],b[3]]).toSorted((a,b)=>Math.fround(b[2]-b[0])-Math.fround(a[2]-a[0])).slice(0,SIDEWAYS_LINES)}async function meanConf(reader,gray,boxes){if(!boxes.length)return 0;let lines=await reader.recognize(gray,boxes);return lines.reduce((s,l)=>s+l.conf,0)/lines.length}export async function readTurn(reader,gray,skew,small,probs){let up=reader.straighten(gray,0,skew,small).image;let ccw=reader.straighten(gray,3,skew,small).image;let sel=longest(await reader.detect(ccw));const{width:w,height:h}=ccw;let cw=rot90(ccw,2);let f=Math.fround;let selCw=sel.map(([x0,y0,x1,y1])=>[f(w-x1),f(h-y1),f(w-x0),f(h-y0)]);let side=probs.length>VERTICAL&&item(probs,VERTICAL)>item(probs,3)?VERTICAL:3;let scores=[[0,await meanConf(reader,up,longest(await reader.detect(up)))],[1,await meanConf(reader,cw,selCw)],[side,await meanConf(reader,ccw,sel)]];let best=item(scores,0);for(let s of scores)if(s[1]>best[1])best=s;return best[1]>0?best[0]:0}export async function readHalfTurn(reader,gray,skew,small){let conf=async(img)=>meanConf(reader,img,longest(await reader.detect(img)));let up=reader.straighten(gray,0,skew,small).image;let down=reader.straighten(gray,2,skew,small).image;return await conf(down)>await conf(up)?2:0}
package/indra/types.d.ts CHANGED
@@ -3,19 +3,47 @@ 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
5
  import type { NgramLM } from "./lm.js";
6
+ import type { TsrSessions } from "./table-rel.js";
7
+ import type { VerifyFile } from "./table-verify.js";
6
8
  import type { MathReader } from "./math.js";
7
9
  import type { Box } from "./rec-preproc.js";
10
+ /**
11
+ * What a token added by an inline formula splice (math-span-img.ts) stands
12
+ * for: the formula, with the recognizer's tokens it replaced, or padding the
13
+ * splice added (a space around the formula, an empty token at a replaced
14
+ * character's x).
15
+ */
16
+ export type Splice = {
17
+ kind: "formula";
18
+ held: readonly Tok[];
19
+ } | {
20
+ kind: "pad";
21
+ };
8
22
  /**
9
23
  * 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.
24
+ * character (group recognizer, PDF text layer, math), its page x, for
25
+ * text-layer characters their index in the PDF content stream, and for a
26
+ * token an inline formula splice added, what it stands for.
12
27
  */
13
- export type Tok = readonly [id: number | string, x: number, contentIndex?: number];
14
- /** Text, confidence and character positions of one detected line. */
28
+ export type Tok = readonly [id: number | string, x: number, contentIndex?: number, splice?: Splice];
29
+ /**
30
+ * A math reading that replaced a line, kept for the layout's second look:
31
+ * the accept head also weighs whether the line sits in a table, which only
32
+ * the reading order shows. `plain` is the line as read before.
33
+ */
34
+ export type MathAccepted = {
35
+ plain: RecLine;
36
+ reading: string;
37
+ conf: number;
38
+ draft: string;
39
+ rconf: number;
40
+ };
41
+ /** Text, confidence and character positions of one detected line; `math` when a math reading replaced it. */
15
42
  export type RecLine = {
16
43
  text: string;
17
44
  conf: number;
18
45
  toks: readonly Tok[];
46
+ math?: MathAccepted;
19
47
  };
20
48
  /** One output line, in reading order. */
21
49
  export type Line = {
@@ -63,10 +91,19 @@ export type LinePart = {
63
91
  text: string;
64
92
  toks: readonly Tok[];
65
93
  };
66
- /** One detector pass: boxes in detector-input pixels, and the page scale. */
94
+ /**
95
+ * One detector pass: boxes in detector-input pixels, the page scale, and the
96
+ * text logit map at OUT_STRIDE of the detector input (tiled detection reads
97
+ * where the page holds text from it).
98
+ */
67
99
  export type DetectPass = {
68
100
  boxes: DetBox[];
69
101
  scale: number;
102
+ logit: {
103
+ data: Float32Array;
104
+ width: number;
105
+ height: number;
106
+ };
70
107
  };
71
108
  /**
72
109
  * orient.onnx's verdict: quarter turns (counter-clockwise) the content is
@@ -99,8 +136,22 @@ export type IndraMeta = {
99
136
  /** script.onnx's class order (default base, cjk, rtl, other). */
100
137
  script_groups?: string[];
101
138
  lm_params?: Record<string, LmParams>;
139
+ /** rec_hw.onnx's input height and window (default: rec.onnx's). */
140
+ rec_hw_height?: number;
141
+ rec_hw_window?: number;
142
+ /** A base line goes to rec_hw.onnx at this hw.onnx probability or more. */
143
+ hw_route_min?: number;
144
+ /** order.onnx line thumbnails: resize mode (default area). */
145
+ order_thumbs_interp?: "area" | "linear";
146
+ /** false: PDF text-layer tables keep the geometric assembly. */
147
+ tsr_rel_layer?: boolean;
148
+ /** How a table cell's column and row spans are found ("geo", "rel", "rel2"). */
149
+ tsr_rel_span?: string;
102
150
  } & {
103
151
  [group: `vocab_${string}`]: string | undefined;
152
+ } & {
153
+ /** A group recognizer that reads lines widened by this factor. */
154
+ [group: `rec_xscale_${string}`]: number | undefined;
104
155
  };
105
156
  /** A model that loads on its first use. */
106
157
  export type Lazy<T> = () => Promise<T>;
@@ -118,6 +169,19 @@ export type IndraSessions = {
118
169
  script?: InferenceSession;
119
170
  groups?: Record<string, Lazy<InferenceSession>>;
120
171
  lms?: Record<string, Lazy<NgramLM>>;
172
+ /**
173
+ * Handwriting: hw.onnx (printed or handwritten, on the line band) and
174
+ * rec_hw.onnx, which reads the base lines hw.onnx calls handwritten. The
175
+ * recognizer loads on the first such line.
176
+ */
177
+ hw?: {
178
+ cls: InferenceSession;
179
+ rec: Lazy<InferenceSession>;
180
+ };
181
+ /** Table structure: tsr_rel.onnx with tsr_split and tsr_refine, loaded on the first table. */
182
+ tables?: Lazy<TsrSessions>;
183
+ /** The false-table verifier's weights (table_verify.json). */
184
+ tableVerify?: VerifyFile;
121
185
  };
122
186
  export type TensorCtor = typeof Tensor;
123
187
  /** Pipeline settings beyond the models. */
@@ -27,7 +27,7 @@ export declare function preview(gray: Gray, ops: ImageOps, side?: number): Gray;
27
27
  /**
28
28
  * Degrees (counter-clockwise) that straighten the text rows of a page: the
29
29
  * angle whose horizontal ink profile changes most sharply row to row. Searched
30
- * over +-DESKEW_MAX in 2 degree steps on a half-size thumbnail; the two best
30
+ * over +-DESKEW_MAX in 2 degree steps on a small thumbnail; the two best
31
31
  * angles and 0 are then refined in 0.5 and 0.1 degree steps on the full
32
32
  * thumbnail (`side` pixels), where small text rows are still resolved.
33
33
  */
package/indra/upright.js CHANGED
@@ -1 +1 @@
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 IDENTITY_TURN=0.000000001;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=Math.abs(a)<IDENTITY_TURN?ink: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))}
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 IDENTITY_TURN=0.000000001;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=Math.abs(a)<IDENTITY_TURN?ink: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*3/16),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/util.d.ts CHANGED
@@ -3,6 +3,14 @@ import type { InferenceSession, Tensor } from "onnxruntime-common";
3
3
  export declare function item<T>(arr: ArrayLike<T>, i: number): T;
4
4
  /** A named model output, or an error naming the missing output. */
5
5
  export declare function output(res: InferenceSession.OnnxValueMapType, name: string): Tensor;
6
+ /**
7
+ * The shape of a model input as the session reports it (symbolic dimensions
8
+ * as strings), or undefined for an input it does not have or that is not a
9
+ * tensor. Some runtimes have no input metadata (onnxruntime-react-native
10
+ * before 1.24.1, the WebGL backend): those throw, with the runtime's error as
11
+ * the cause, since no default size is right for every model.
12
+ */
13
+ export declare function inputShape(sess: InferenceSession, name: string): readonly (number | string)[] | undefined;
6
14
  /** A float32 tensor's data. */
7
15
  export declare function floats(t: Tensor): Float32Array;
8
16
  /** An integer tensor's data as numbers (int64 ids and lengths fit in 2^53). */
package/indra/util.js CHANGED
@@ -1 +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)}
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 inputShape(sess,name){let meta;try{meta=sess.inputMetadata}catch(err){throw new Error(`this ONNX Runtime gives no input metadata, which the "${name}" input needs `+"(onnxruntime-react-native 1.24.1 or later, or a backend other than WebGL)",{cause:err})}let input=meta.find((m)=>m.name===name);return input?.isTensor?input.shape:undefined}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)}
package/indra/vocab.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /** `vocab.canonical`: NFC, the CANON map, and leader runs cut to three. */
2
+ export declare function canonical(text: string): string;
1
3
  /**
2
4
  * Token vocabulary of a line recognizer. Class 0 is the CTC blank; class i + 1
3
5
  * is `chars[i]`. A token is one character, or one LaTeX command inside math.
@@ -11,6 +13,15 @@ export declare class Vocab {
11
13
  constructor(chars: readonly string[]);
12
14
  /** A vocabulary from a `vocab` / `vocab_<group>` JSON string in meta.json. */
13
15
  static fromJson(json: string): Vocab;
16
+ /** The text as the recognizer's targets write it (`canonical`). */
17
+ normalize(text: string): string;
18
+ /**
19
+ * Characters, with a LaTeX command as one token when the vocab has it.
20
+ * Inside a $...$ math span spaces are dropped: they are not visible in
21
+ * rendered math.
22
+ */
23
+ tokenize(text: string): string[];
24
+ private tokens;
14
25
  /** Text of class ids. A space goes back between a command and a following letter. */
15
26
  decode(ids: readonly number[]): string;
16
27
  }
package/indra/vocab.js CHANGED
@@ -1 +1 @@
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;
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)}normalize(text){return canonical(text)}tokenize(text){if(!this.hasCommands)return Array.from(text);let out=[];let pos=0;for(let m of text.matchAll(MATH_SPAN)){out.push(...this.tokens(text.slice(pos,m.index),false),...this.tokens(m[0],true));pos=m.index+m[0].length}out.push(...this.tokens(text.slice(pos),false));return out}tokens(text,math){let out=[];for(const[t]of text.matchAll(TOKEN)){if(math&&isPySpace(t))continue;if(this.index.has(t)||Array.from(t).length===1)out.push(t);else out.push(...Array.from(t))}return out}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}}import{isPySpace}from"./util.js";let LETTERS=/^\p{L}+$/u;let CANON=new Map([[536,350],[537,351],[538,354],[539,355],[9642,8226],[9679,8226],[8729,8226],[8227,8226],[8259,8226]].map(([a=0,b=0])=>[String.fromCharCode(a),String.fromCharCode(b)]));let RUNS=new RegExp("([._\\-=\\u00b7*~])\\1{3,}","gu");let DOUBLE_SINGLE=/''|``/gu;let TOKEN=/\\[A-Za-z]+|\\[{}|,;! ]|./gsu;let MATH_SPAN=/\$[^$]*[\\^_{][^$]*\$/gu;export function canonical(text){let mapped=Array.from(text.normalize("NFC"),(c)=>CANON.get(c)??c).join("");return mapped.replace(DOUBLE_SINGLE,'"').replace(RUNS,(_,c)=>c.repeat(3))}
package/interface.d.ts CHANGED
@@ -31,19 +31,24 @@ export type SessionOptions = InferenceSession.SessionOptions & {
31
31
  /** Options of an IndraOcrService. */
32
32
  export type IndraOptions = {
33
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).
34
+ * The model set: "v1.2" (Indra OCR 1.2, the default), "v1.1" (Indra OCR
35
+ * 1.1), or "v3.1" (the first release, smaller and Latin, Cyrillic, Greek
36
+ * and Chinese only). The v1.2 weights' license sets lower revenue and
37
+ * funding limits (USD 5,000,000) than the older ones (USD 20,000,000).
36
38
  */
37
39
  model?: ModelPreset;
38
40
  /** Per-file model sources. Default: Datalab's repository at the preset's pinned revision. */
39
41
  models?: ModelSources;
40
42
  /**
41
43
  * 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.
44
+ * (v1.1, v1.2). Each model loads on the first such line: 12 to 19 MB each.
43
45
  * Default true on Node and Bun, false on web and mobile.
44
46
  */
45
47
  lm?: boolean;
46
- /** Read lines with math as LaTeX. Loads four more models. Default false. */
48
+ /**
49
+ * Read lines with math as LaTeX. Loads the math models (about 25 MB for
50
+ * v1.2). Default true on Node and Bun, false on web and mobile.
51
+ */
47
52
  math?: boolean;
48
53
  /** Keep page headers and footers in the markdown. Default false. */
49
54
  furniture?: boolean;
@@ -10,6 +10,7 @@ export declare class MobilePlatformProvider implements PlatformProvider<CoreCanv
10
10
  readonly ort: PlatformProvider["ort"];
11
11
  readonly defaultEngine: "canvas-native";
12
12
  readonly defaultLm = false;
13
+ readonly defaultMath = false;
13
14
  isCanvas(image: unknown): image is CoreCanvas;
14
15
  decodeImage(bytes: ArrayBuffer): Promise<CoreCanvas>;
15
16
  pixels(canvas: CoreCanvas): Rgba;
@@ -1 +1 @@
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
+ export class MobilePlatformProvider{ort=ort;defaultEngine="canvas-native";defaultLm=false;defaultMath=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,5 +1,5 @@
1
1
  /** The model files of Indra OCR, by role. */
2
- export type ModelFile = "det" | "rec" | "recCjk" | "recRtl" | "recWorld" | "script" | "orient" | "order" | "meta" | "lm" | "lmCjk" | "lmWorld" | "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" | "mathDecStepKv" | "mathMeta" | "mathAccept" | "mathGate" | "mathSpanImg" | "mathSpanImgMeta" | "hw" | "recHw" | "tsrRel" | "tsrSplit" | "tsrRefine" | "tableVerify";
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
5
  /** The files every service loads when it starts. */
@@ -26,10 +26,17 @@ export type LmFiles = {
26
26
  world: "lmWorld";
27
27
  };
28
28
  export declare const LM_FILES: Readonly<LmFiles>;
29
- /** The math files: downloaded only when math is on. */
29
+ /**
30
+ * The math files: downloaded only when math is on. A preset has one decoder
31
+ * step graph: math_dec_step_kv.onnx (per-layer caches, v1.2) or
32
+ * math_dec_step.onnx (stacked caches). The accept head, the read gate and the
33
+ * inline formula tagger are optional.
34
+ */
30
35
  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";
36
+ /** Table structure files (v1.2): tsr_split and tsr_refine only work with tsr_rel. */
37
+ export declare const TABLE_FILES: readonly ModelFile[];
38
+ /** A model set by its Indra OCR release: the default and the legacy ones. */
39
+ export type ModelPreset = "v1.2" | "v1.1" | "v3.1";
33
40
  /** Where a preset's files live and which files it has. */
34
41
  export type PresetInfo = {
35
42
  /** Commit of datalab-to/indra-ocr, pinned so an upstream change cannot change results. */
@@ -38,8 +45,11 @@ export type PresetInfo = {
38
45
  tag: string;
39
46
  /** Datalab's repository at the revision. */
40
47
  baseUrl: string;
41
- /** This repository's git LFS mirror of the same files (see MODEL_MIRROR_BASE_URL). */
42
- mirrorUrl: string;
48
+ /**
49
+ * This repository's git LFS mirror of the same files (see
50
+ * MODEL_MIRROR_BASE_URL); none for v1.2, which the LFS budget cannot hold.
51
+ */
52
+ mirrorUrl?: string;
43
53
  /** The files the preset has, math included. */
44
54
  files: readonly ModelFile[];
45
55
  };
@@ -55,7 +65,13 @@ export declare const MODEL_MIRROR_BASE_URL = "https://github.com/PT-Perkasa-Pila
55
65
  /**
56
66
  * The model sets, by Indra OCR release:
57
67
  *
58
- * - `v1.1` (default): Indra OCR 1.1, Hugging Face tag v1.1.0. Handwriting,
68
+ * - `v1.2` (default): Indra OCR 1.2, Hugging Face tag v1.2.0. Retrained
69
+ * printed and handwriting recognizers (rec_hw.onnx for handwritten lines),
70
+ * table structure models, an order model that reads line thumbnails, and
71
+ * math gates. About 43 MB of networks (68 MB with math) plus 46 MB of
72
+ * language models. Its license sets the revenue and funding limits at
73
+ * USD 5,000,000.
74
+ * - `v1.1`: Indra OCR 1.1, Hugging Face tag v1.1.0. Handwriting,
59
75
  * 80+ languages (recognizers for CJK, right-to-left and other scripts),
60
76
  * pages at any angle, vertical writing, and language models for unsure
61
77
  * lines. About 30 MB of networks, plus 46 MB of language models.
@@ -1 +1 @@
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}
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",mathDecStepKv:"math_dec_step_kv.onnx",mathMeta:"math_meta.json",mathAccept:"math_accept.json",mathGate:"math_gate.json",mathSpanImg:"math_span_img.onnx",mathSpanImgMeta:"math_span_img.json",hw:"hw.onnx",recHw:"rec_hw.onnx",tsrRel:"tsr_rel.onnx",tsrSplit:"tsr_split.onnx",tsrRefine:"tsr_refine.onnx",tableVerify:"table_verify.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","mathDecStepKv","mathMeta","mathAccept","mathGate","mathSpanImg","mathSpanImgMeta"];export let TABLE_FILES=["tsrRel","tsrSplit","tsrRefine","tableVerify"];let HF="https://huggingface.co/datalab-to/indra-ocr/resolve";let LEGACY_MATH_FILES=["mathCls","mathEnc","mathDecInit","mathDecStep","mathMeta"];export let MODEL_MIRROR_BASE_URL="https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr/raw/main/models";export let MODEL_PRESETS={"v1.2":{revision:"a04fa100e778192aa54d040a983983c6d3ee4ce5",tag:"v1.2.0",baseUrl:`${HF}/a04fa100e778192aa54d040a983983c6d3ee4ce5`,files:[...BASE_FILES,"recCjk","recRtl","recWorld","hw","recHw","lm","lmCjk","lmWorld",...TABLE_FILES,...MATH_FILES.filter((f)=>f!=="mathDecStep")]},"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",...LEGACY_MATH_FILES]},"v3.1":{revision:"d7c839c892bfe4b8993373db64c62f154d05d70b",tag:"v3.1",baseUrl:`${HF}/d7c839c892bfe4b8993373db64c62f154d05d70b`,mirrorUrl:MODEL_MIRROR_BASE_URL,files:[...BASE_FILES,"recCjk",...LEGACY_MATH_FILES]}};export let DEFAULT_PRESET="v1.2";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===undefined?null:info.mirrorUrl+url.slice(info.baseUrl.length)}}return null}