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,70 @@
1
+ import type { Tok } from "./types.js";
2
+ import type { Vocab } from "./vocab.js";
3
+ /**
4
+ * Does a PDF text layer say what its page shows? A legacy font (Kruti Dev,
5
+ * Bijoy, VNI) stores Latin codes for another script, a broken ToUnicode map
6
+ * writes other letters, and a layer can hold syllables in visual order; the
7
+ * ink checks in textlayer.ts do not see this. The check reads a few short
8
+ * pieces of layer lines from the page image and asks how likely each
9
+ * recognizer finds the layer's text (a forced CTC alignment) compared with its
10
+ * own best reading. The gap is near 0 where the layer is the page's text, also
11
+ * where the recognizer is unsure, and large where the layer's characters are
12
+ * not in the image.
13
+ */
14
+ /** The class ids that may write one layer character; empty for one the recognizer cannot write. */
15
+ export type TargetAlts = readonly number[];
16
+ /** One line's recognizer outputs and the layer text's target ids, for forcedGaps. */
17
+ export type GapItem = {
18
+ /** The blank's log-probability per frame [T]. */
19
+ blank: ArrayLike<number>;
20
+ /** The top-k classes' log-probabilities [T, k], best first. */
21
+ topv: ArrayLike<number>;
22
+ topi: ArrayLike<number | bigint>;
23
+ k: number;
24
+ ids: readonly TargetAlts[];
25
+ };
26
+ /** The start of a line's layer tokens, and the x where it is cut (undefined: the whole line). */
27
+ export type Snippet = {
28
+ toks: Tok[];
29
+ cut?: number;
30
+ };
31
+ /**
32
+ * The start (leftmost by x) of a detected line's layer tokens: about `n`
33
+ * non-space characters, cut at the first word gap after them when one comes
34
+ * within 2n characters. Returns those tokens and the cut x (undefined: the
35
+ * whole line).
36
+ */
37
+ export declare function snippet(tokens: readonly Tok[], n: number): Snippet;
38
+ /**
39
+ * The text of layer tokens as a recognizer reads the line: each word (a
40
+ * text-layer run's characters between spaces) keeps the layer's order, and
41
+ * the words go left to right on the line (right to left for a recognizer of
42
+ * right-to-left text, which reads the logical order flipped). A layer can
43
+ * store a line's words in another order than they stand, so the order of the
44
+ * layer's words is no evidence against it.
45
+ */
46
+ export declare function layerText(tokens: readonly Tok[], rtl: boolean): string;
47
+ /** Whether a recognizer can write at least `share` of the text's letters. */
48
+ export declare function writes(text: string, vocab: Vocab, share?: number): boolean;
49
+ /** The letter a precomposed character is built on (a letter and combining marks), else undefined. */
50
+ export declare function baseLetter(c: string): string | undefined;
51
+ /**
52
+ * The recognizer's class ids for a layer text: per token, the ids that write
53
+ * it (the character in either case: small capitals and text set in capitals
54
+ * draw another case than the layer stores; and a precomposed letter's base
55
+ * letter: a recognizer that misses a mark the layer has is no evidence
56
+ * against the layer), empty for a character the recognizer cannot write.
57
+ * `visual`: the recognizer reads right-to-left text in visual order.
58
+ */
59
+ export declare function targetIds(text: string, vocab: Vocab, visual: boolean): TargetAlts[];
60
+ /**
61
+ * Per item: the log-probability per token by which the best CTC alignment of
62
+ * its ids falls below the recognizer's best path. A class outside the top k
63
+ * counts 1 nat under the k-th, as does a character the recognizer cannot
64
+ * write. 0 for no ids, Infinity when the ids cannot fit the frames.
65
+ *
66
+ * The reference aligns every item in one padded batch; the path sums run over
67
+ * the batch's longest frame count (padding adds zeros), so the sums here do
68
+ * too: numpy's pairwise sum rounds by the array's length.
69
+ */
70
+ export declare function forcedGaps(items: readonly GapItem[]): number[];
package/indra/agree.js ADDED
@@ -0,0 +1 @@
1
+ import{sumF64}from"./numeric.js";import{isAlpha,isCategoryM}from"./py-unicode.js";import{flip,hasRtl,normalize as rtlNormalize}from"./rtl.js";import{isPySpace,item}from"./util.js";function cmpStr(a,b){if(a===b)return 0;return a<b?-1:1}export function snippet(tokens,n){let chars=tokens.filter((t)=>!isPySpace(String(t[0]))).map((t)=>[t[1],String(t[0])]).toSorted((a,b)=>a[0]-b[0]||cmpStr(a[1],b[1]));let xs=chars.map(([x])=>x);if(xs.length<=n)return{toks:[...tokens]};let spaces=tokens.filter((t)=>isPySpace(String(t[0]))).map((t)=>t[1]);let k=n;for(let j=n;j<Math.min(xs.length,2*n);j++){if(spaces.some((s)=>item(xs,j-1)<=s&&s<item(xs,j))){k=j;break}}while(k<xs.length&&isCategoryM(Array.from(item(chars,k)[1])[0]??" "))k++;if(k>=xs.length)return{toks:[...tokens]};let cut=(item(xs,k-1)+item(xs,k))/2;return{toks:tokens.filter((t)=>t[1]<cut),cut}}export function layerText(tokens,rtl){let words=[];for(let t of tokens){if(isPySpace(String(t[0]))){if(words.at(-1)?.length)words.push([]);continue}let last=words.at(-1);if(!last||last.length&&item(last,0)[2]!==t[2])words.push([t]);else last.push(t)}let kept=words.filter((w)=>w.length);let key=(w)=>rtl?-Math.max(...w.map((t)=>t[1])):Math.min(...w.map((t)=>t[1]));return kept.toSorted((a,b)=>key(a)-key(b)).map((w)=>w.map((t)=>String(t[0])).join("")).join(" ")}function knows(vocab,c){return vocab.index.has(c)||vocab.jamo&&Array.from(c.normalize("NFD")).every((j)=>vocab.index.has(j))}export function writes(text,vocab,share=0.9){let letters=Array.from(vocab.normalize(text)).filter(isAlpha);if(!letters.length)return true;return letters.filter((c)=>knows(vocab,c)).length>=share*letters.length}export function baseLetter(c){let d=Array.from(c.normalize("NFD"));const[first,...marks]=d;return first!==undefined&&marks.length&&isAlpha(first)&&marks.every(isCategoryM)?first:undefined}export function targetIds(text,vocab,visual){let t=hasRtl(text)?rtlNormalize(text):text;t=vocab.normalize(t);if(visual)t=flip(t);let ids=[];for(let c of vocab.tokenize(t)){let forms=[c,c.toUpperCase(),c.toLowerCase()];let b=baseLetter(c);if(b)forms.push(b,b.toUpperCase(),b.toLowerCase());let alts=[...new Set(forms.flatMap((x)=>vocab.index.get(x)??[]))];let jamo=Array.from(c.normalize("NFD"));if(alts.length){ids.push(alts)}else if(vocab.jamo&&jamo.every((j)=>vocab.index.has(j))){for(let j of jamo)ids.push([vocab.index.get(j)??0])}else{ids.push([])}}return ids}function tokenLogp(it,t,alts){let best=-1/0;let hit=false;for(let kk=0;kk<it.k;kk++){let cls=Number(it.topi[t*it.k+kk]??-1);if(!alts.includes(cls))continue;hit=true;best=Math.max(best,Number(it.topv[t*it.k+kk]??-1/0))}return hit?best:Number(it.topv[t*it.k+it.k-1]??-1/0)-1}export function forcedGaps(items){let out=items.map(()=>0);let run=items.flatMap((it,i)=>it.ids.length&&it.blank.length?[i]:[]);if(!run.length)return out;let T=Math.max(...run.map((i)=>item(items,i).blank.length));for(let i of run){let it=item(items,i);let n=it.blank.length;let L=it.ids.length;let S=2*L+1;let skip=new Uint8Array(S);for(let j=1;j<L;j++){let prev=new Set(item(it.ids,j-1));skip[2*j+1]=item(it.ids,j).some((c)=>prev.has(c))?0:1}let lp=(t,s)=>s%2===0?Number(it.blank[t]):tokenLogp(it,t,item(it.ids,(s-1)/2));let a=new Float64Array(S).fill(-1/0);a[0]=lp(0,0);if(S>1)a[1]=lp(0,1);let best=-1/0;if(n-1===0)best=Math.max(a[2*L]??-1/0,a[2*L-1]??-1/0);for(let t=1;t<n;t++){let nxt=a.slice();for(let s=1;s<S;s++)nxt[s]=Math.max(nxt[s]??-1/0,a[s-1]??-1/0);for(let s=2;s<S;s++){if(skip[s])nxt[s]=Math.max(nxt[s]??-1/0,a[s-2]??-1/0)}for(let s=0;s<S;s++)nxt[s]=(nxt[s]??-1/0)+lp(t,s);a=nxt;if(t===n-1)best=Math.max(a[2*L]??-1/0,a[2*L-1]??-1/0)}let top=new Float64Array(T);for(let t=0;t<n;t++){let v=Number(it.topv[t*it.k]??-1/0);top[t]=Number.isFinite(v)?v:0}out[i]=Number.isFinite(best)?(sumF64(top)-best)/L:1/0}return out}
@@ -1,9 +1,14 @@
1
+ import type { Cell, TableMap } from "./layout-post.js";
1
2
  import type { Box } from "./rec-preproc.js";
2
- import type { LinePart, Page, ReadingOrder, RecLine } from "./types.js";
3
+ import type { LinePart, MathAccepted, Page, ReadingOrder, RecLine, Tok } from "./types.js";
3
4
  import type { Vocab } from "./vocab.js";
4
- /** A line part with the confidence of the line it came from. */
5
+ /**
6
+ * A line part with the confidence of the line it came from, and for a line a
7
+ * math reading replaced (one token: never split), that reading's record.
8
+ */
5
9
  export type Part = LinePart & {
6
10
  conf: number;
11
+ math?: MathAccepted;
7
12
  };
8
13
  /**
9
14
  * Whether a page reads right to left: more right-to-left letters than other
@@ -38,10 +43,16 @@ export declare function mirrorBox([x0, y0, x1, y1]: Box, width: number): Box;
38
43
  * no line gets a grid class (Table, Form, Table-Of-Contents).
39
44
  */
40
45
  export declare function verticalOrder(boxes: readonly Box[], ro: ReadingOrder): ReadingOrder;
46
+ /**
47
+ * Each part split into table cells at CELL_GAP (inside tables, lines split at
48
+ * smaller gaps), with boxes on the page as the layout sees it (mirrored on a
49
+ * right-to-left page). `toksOf` picks the tokens to split (default: the part's).
50
+ */
51
+ export declare function partCells(vocab: Vocab, parts: readonly Part[], pageRtl: boolean, width: number, toksOf?: (p: Part) => readonly Tok[]): Map<number, Cell[]>;
41
52
  /**
42
53
  * The page from ordered line parts: output lines, blocks and markdown. On a
43
54
  * right-to-left page (`pageRtl`), blocks and markdown work on the page
44
55
  * mirrored left to right, so the first column is the right one; output boxes
45
56
  * stay on the page as it is.
46
57
  */
47
- export declare function buildPage(vocab: Vocab, parts: readonly Part[], { order, cls, same }: ReadingOrder, note: string, furniture: boolean, t: Record<string, number>, pageRtl?: boolean, width?: number): Page;
58
+ export declare function buildPage(vocab: Vocab, parts: readonly Part[], { order, cls, same }: ReadingOrder, note: string, furniture: boolean, t: Record<string, number>, pageRtl?: boolean, width?: number, tables?: TableMap): Page;
package/indra/assemble.js CHANGED
@@ -1,3 +1,3 @@
1
- import{pageBlocks,pageMarkdown}from"./layout-post.js";import{CELL_GAP,SPLIT_GAP,gutterCuts,splitLine}from"./lines.js";import{BLOCK_CLASSES,GRID_CLASSES,xycutBlocks}from"./order-post.js";import{isRtl}from"./rtl.js";import{roundTo}from"./upright.js";import{isPySpace,item}from"./util.js";let f=Math.fround;function f32Box([x0,y0,x1,y1]){return[f(x0),f(y0),f(x1),f(y1)]}let LETTER=/^\p{L}$/u;export function pageIsRtl(rec){let rtl=0;let all=0;for(let r of rec){for(let c of r.text){if(!LETTER.test(c))continue;all++;if(isRtl(c))rtl++}}return rtl>all-rtl}export function splitParts(vocab,boxes,rec,pageRtl=false){let cuts=gutterCuts(vocab,boxes,rec);let parts=boxes.flatMap((b,i)=>splitLine(vocab,b,item(rec,i).toks,SPLIT_GAP,item(cuts,i),pageRtl).map((p)=>({...p,box:f32Box(p.box),conf:item(rec,i).conf})));return tidyLines(parts,pageRtl,vocab.index.get(" "))}function pyStrip(s){let cps=[...s];let a=0;let b=cps.length;while(a<b&&isPySpace(item(cps,a)))a++;while(b>a&&isPySpace(item(cps,b-1)))b--;return cps.slice(a,b).join("")}let LEADER_CHARS=new Set([..."._-=",...[183,8230,8229,8211,8212].map((c)=>String.fromCharCode(c))]);let DASHES=new Set(["-",...[8211,8212].map((c)=>String.fromCharCode(c))]);let BULLETS=new Set([8226,9702,9642,9643,9679,9675,9632,9633,8227,8259,8729,42].map((c)=>String.fromCharCode(c)));let ENUMERATOR=/^(?:(?:\p{Nd}{1,3}|[A-Za-z])[.)]|\((?:\p{Nd}{1,3}|[A-Za-z]|[ivxlcIVXLC]{1,5})\))$/u;let MARKER_GAP=2.5;export function tidyLines(parts,rtl=false,space){let keep=parts.map(()=>true);let out=[...parts];let h=parts.map((p)=>f(p.box[3]-p.box[1]));let w=parts.map((p)=>f(p.box[2]-p.box[0]));for(const[i,p]of parts.entries()){let core=new Set(p.text.replaceAll(" ",""));if(core.size&&[...core].every((c)=>LEADER_CHARS.has(c))){let wide=item(w,i)>=f(3*item(h,i));let n=[...p.text.replaceAll(" ","")].length;if(n>=3||wide||![...core].some((c)=>DASHES.has(c)))keep[i]=false}}for(let i of parts.keys()){let cur=item(out,i);let t=pyStrip(cur.text);if(!keep[i]||!(BULLETS.has(t)||ENUMERATOR.test(t)))continue;let bi=cur.box;let hi=item(h,i);let best=-1;let bestGap=0;for(const[j,other]of out.entries()){if(j===i||!keep[j]||!pyStrip(other.text))continue;let bj=other.box;let hj=item(h,j);let ov=f(Math.min(bi[3],bj[3])-Math.max(bi[1],bj[1]));if(ov<f(0.5*Math.min(hi,hj)))continue;let gap=f(rtl?bi[0]-bj[2]:bj[0]-bi[2]);if(f(f(-0.3)*hi)<=gap&&gap<=f(MARKER_GAP*Math.max(hi,hj))&&(best<0||gap<bestGap)){best=j;bestGap=gap}}if(best<0)continue;let target=item(out,best);let toks=target.toks;let chars=toks.length>0&&typeof item(toks,0)[0]==="string";let sp=chars?" ":space;if(!rtl&&cur.toks.length&&toks.length&&sp!==undefined){if(typeof item(cur.toks,0)[0]==="string"===chars){let x=f(bi[2]+target.box[0])/2;let last=item(cur.toks,cur.toks.length-1);let join=last.length>2?[sp,x,last[2]]:[sp,x];toks=[...cur.toks,join,...toks]}}out[best]={box:[Math.min(bi[0],target.box[0]),Math.min(bi[1],target.box[1]),Math.max(bi[2],target.box[2]),Math.max(bi[3],target.box[3])],text:`${t} ${pyStrip(target.text)}`,toks,conf:target.conf};keep[i]=false}return out.filter((_,i)=>keep[i])}export function mirrorBox([x0,y0,x1,y1],width){return[f(width-x1),f(y0),f(width-x0),f(y1)]}export function verticalOrder(boxes,ro){if(!ro.cls)return ro;let n=boxes.length;let blocks=xycutBlocks(boxes);let same=new Float32Array(n*n).fill(-1);for(let b of blocks)for(let i of b)for(let j of b)same[i*n+j]=1;let cls=ro.cls.slice();for(let i=0;i<n;i++)for(let c of GRID_CLASSES)cls[i*BLOCK_CLASSES.length+c]=-1e4;return{order:blocks.flat(),cls,same,logits:ro.logits}}export function buildPage(vocab,parts,{order,cls,same},note,furniture,t,pageRtl=false,width=0){t["total_ms"]=Object.entries(t).reduce((sum,[k,v])=>k==="total_ms"?sum:sum+v,0);let geo=(b)=>pageRtl?mirrorBox(b,width):b;let boxes=parts.map((p)=>p.box);let texts=parts.map((p)=>p.text);let lines=order.map((i)=>{let p=item(parts,i);const[x0,y0,x1,y1]=p.box;return{box:[roundTo(x0,1),roundTo(y0,1),roundTo(x1,1),roundTo(y1,1)],text:p.text,conf:roundTo(p.conf,4)}});let markdown=null;let blocks=[];if(cls&&same){let mirrored=boxes.map(geo);blocks=pageBlocks(mirrored,texts,order,cls,same).map((b)=>{const[x0,y0,x1,y1]=geo(b.bbox);return{...b,bbox:[roundTo(x0,1),roundTo(y0,1),roundTo(x1,1),roundTo(y1,1)]}});let cells=new Map(parts.map((p,i)=>[i,splitLine(vocab,p.box,p.toks,CELL_GAP,[],pageRtl).map(({box,text})=>({box:geo(f32Box(box)),text}))]));markdown=pageMarkdown(mirrored,texts,order,cls,same,furniture,cells)}else if(parts.length<2){markdown=texts.join(`
1
+ import{pageBlocks,pageMarkdown}from"./layout-post.js";import{CELL_GAP,SPLIT_GAP,gutterCuts,splitLine}from"./lines.js";import{BLOCK_CLASSES,GRID_CLASSES,xycutBlocks}from"./order-post.js";import{isRtl}from"./rtl.js";import{roundTo}from"./upright.js";import{pyStrip}from"./py-unicode.js";import{item}from"./util.js";let f=Math.fround;function f32Box([x0,y0,x1,y1]){return[f(x0),f(y0),f(x1),f(y1)]}let LETTER=/^\p{L}$/u;export function pageIsRtl(rec){let rtl=0;let all=0;for(let r of rec){for(let c of r.text){if(!LETTER.test(c))continue;all++;if(isRtl(c))rtl++}}return rtl>all-rtl}export function splitParts(vocab,boxes,rec,pageRtl=false){let cuts=gutterCuts(vocab,boxes,rec);let parts=boxes.flatMap((b,i)=>{let r=item(rec,i);let pieces=splitLine(vocab,b,r.toks,SPLIT_GAP,item(cuts,i),pageRtl);return pieces.map((p)=>{let part={...p,box:f32Box(p.box),conf:r.conf};return r.math&&pieces.length===1?{...part,math:r.math}:part})});return tidyLines(parts,pageRtl,vocab.index.get(" "))}let LEADER_CHARS=new Set([..."._-=",...[183,8230,8229,8211,8212].map((c)=>String.fromCharCode(c))]);let DASHES=new Set(["-",...[8211,8212].map((c)=>String.fromCharCode(c))]);let BULLETS=new Set([8226,9702,9642,9643,9679,9675,9632,9633,8227,8259,8729,42].map((c)=>String.fromCharCode(c)));let ENUMERATOR=/^(?:(?:\p{Nd}{1,3}|[A-Za-z])[.)]|\((?:\p{Nd}{1,3}|[A-Za-z]|[ivxlcIVXLC]{1,5})\))$/u;let MARKER_GAP=2.5;export function tidyLines(parts,rtl=false,space){let keep=parts.map(()=>true);let out=[...parts];let h=parts.map((p)=>f(p.box[3]-p.box[1]));let w=parts.map((p)=>f(p.box[2]-p.box[0]));for(const[i,p]of parts.entries()){let core=new Set(p.text.replaceAll(" ",""));if(core.size&&[...core].every((c)=>LEADER_CHARS.has(c))){let wide=item(w,i)>=f(3*item(h,i));let n=[...p.text.replaceAll(" ","")].length;if(n>=3||wide||![...core].some((c)=>DASHES.has(c)))keep[i]=false}}for(let i of parts.keys()){let cur=item(out,i);let t=pyStrip(cur.text);if(!keep[i]||!(BULLETS.has(t)||ENUMERATOR.test(t)))continue;let bi=cur.box;let hi=item(h,i);let best=-1;let bestGap=0;for(const[j,other]of out.entries()){if(j===i||!keep[j]||!pyStrip(other.text))continue;let bj=other.box;let hj=item(h,j);let ov=f(Math.min(bi[3],bj[3])-Math.max(bi[1],bj[1]));if(ov<f(0.5*Math.min(hi,hj)))continue;let gap=f(rtl?bi[0]-bj[2]:bj[0]-bi[2]);if(f(f(-0.3)*hi)<=gap&&gap<=f(MARKER_GAP*Math.max(hi,hj))&&(best<0||gap<bestGap)){best=j;bestGap=gap}}if(best<0)continue;let target=item(out,best);let toks=target.toks;let chars=toks.length>0&&typeof item(toks,0)[0]==="string";let sp=chars?" ":space;if(!rtl&&cur.toks.length&&toks.length&&sp!==undefined){if(typeof item(cur.toks,0)[0]==="string"===chars){let x=f(bi[2]+target.box[0])/2;let last=item(cur.toks,cur.toks.length-1);let join=last[2]!==undefined?[sp,x,last[2]]:[sp,x];toks=[...cur.toks,join,...toks]}}out[best]={box:[Math.min(bi[0],target.box[0]),Math.min(bi[1],target.box[1]),Math.max(bi[2],target.box[2]),Math.max(bi[3],target.box[3])],text:`${t} ${pyStrip(target.text)}`,toks,conf:target.conf};keep[i]=false}return out.filter((_,i)=>keep[i])}export function mirrorBox([x0,y0,x1,y1],width){return[f(width-x1),f(y0),f(width-x0),f(y1)]}export function verticalOrder(boxes,ro){if(!ro.cls)return ro;let n=boxes.length;let blocks=xycutBlocks(boxes);let same=new Float32Array(n*n).fill(-1);for(let b of blocks)for(let i of b)for(let j of b)same[i*n+j]=1;let cls=ro.cls.slice();for(let i=0;i<n;i++)for(let c of GRID_CLASSES)cls[i*BLOCK_CLASSES.length+c]=-1e4;return{order:blocks.flat(),cls,same,logits:ro.logits}}export function partCells(vocab,parts,pageRtl,width,toksOf=(p)=>p.toks){let geo=(b)=>pageRtl?mirrorBox(b,width):b;return new Map(parts.map((p,i)=>[i,splitLine(vocab,p.box,toksOf(p),CELL_GAP,[],pageRtl).map(({box,text})=>({box:geo(f32Box(box)),text}))]))}export function buildPage(vocab,parts,{order,cls,same},note,furniture,t,pageRtl=false,width=0,tables){t["total_ms"]=Object.entries(t).reduce((sum,[k,v])=>k==="total_ms"?sum:sum+v,0);let geo=(b)=>pageRtl?mirrorBox(b,width):b;let boxes=parts.map((p)=>p.box);let texts=parts.map((p)=>p.text);let lines=order.map((i)=>{let p=item(parts,i);const[x0,y0,x1,y1]=p.box;return{box:[roundTo(x0,1),roundTo(y0,1),roundTo(x1,1),roundTo(y1,1)],text:p.text,conf:roundTo(p.conf,4)}});let markdown=null;let blocks=[];if(cls&&same){let mirrored=boxes.map(geo);blocks=pageBlocks(mirrored,texts,order,cls,same).map((b)=>{const[x0,y0,x1,y1]=geo(b.bbox);return{...b,bbox:[roundTo(x0,1),roundTo(y0,1),roundTo(x1,1),roundTo(y1,1)]}});let cells=partCells(vocab,parts,pageRtl,width);markdown=pageMarkdown(mirrored,texts,order,cls,same,furniture,cells,tables)}else if(parts.length<2){markdown=texts.join(`
2
2
  `)}return{lines,text:lines.map((l)=>l.text).join(`
3
3
  `),markdown,blocks,source:"ocr",note,rotation:0,skew:0,vertical:false,timings:t}}
package/indra/ctc.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /** Classes per step for the beam search (the older graphs' TopK). */
2
+ export declare const TOPK = 8;
3
+ /** The LM inputs of one line: blank log-probability [T], top-k values and classes [T, k]. */
4
+ export type LmInputs = {
5
+ blank: Float32Array;
6
+ topv: Float32Array;
7
+ topi: Int32Array;
8
+ k: number;
9
+ };
10
+ /** The probability of the best class at each of the `rows` steps (`steps` index rows of `logits`). */
11
+ export declare function peakProb(logits: Float32Array, v: number, steps: readonly number[]): Float32Array;
12
+ /**
13
+ * Steps [0, n) of one line's logits (row-major [T, V] from `offset`) -> the
14
+ * blank log-probability and the k best classes' log-probabilities, best
15
+ * first. Equal values keep the lower class first, as ONNX Runtime's TopK
16
+ * does. With `floor` (a probability) only classes at or over it are kept;
17
+ * the other places hold class 0 at -inf, which beamSearch skips, and its
18
+ * candidates are the same as long as its own floor is at least this one.
19
+ */
20
+ export declare function lmInputs(logits: Float32Array, offset: number, n: number, v: number, floor: number, k?: number): LmInputs;
21
+ /**
22
+ * The blank's log-probability and the k most likely classes (log-probabilities,
23
+ * best first) per frame, for frames [0, n) of each of B lines' logits
24
+ * ([B, T, V] row-major): the text-layer check's view of a recognizer. Unlike
25
+ * lmInputs, the log-softmax is `x - (max + log(sum(exp(x - max))))`, as the
26
+ * reference computes it here.
27
+ */
28
+ export declare function topKLogits(logits: Float32Array, B: number, T: number, v: number, n: number, k?: number): LmInputs[];
package/indra/ctc.js ADDED
@@ -0,0 +1 @@
1
+ import{sumF32}from"./numeric.js";let f=Math.fround;export let TOPK=8;function rowMax(logits,t,v){let m=-1/0;for(let c=0;c<v;c++){let x=logits[t*v+c]??-1/0;if(x>m)m=x}return m}function rowExp(logits,t,v,m,out){for(let c=0;c<v;c++)out[c]=f(Math.exp(f((logits[t*v+c]??0)-m)))}export function peakProb(logits,v,steps){let out=new Float32Array(steps.length);let e=new Float32Array(v);for(const[i,t]of steps.entries()){rowExp(logits,t,v,rowMax(logits,t,v),e);out[i]=f(1/sumF32(e))}return out}export function lmInputs(logits,offset,n,v,floor,k=TOPK){let kk=Math.min(k,v);let blank=new Float32Array(n);let topv=new Float32Array(n*kk).fill(-1/0);let topi=new Int32Array(n*kk);let row=logits.subarray(offset,offset+n*v);let e=new Float32Array(v);let lf=Math.log(floor);for(let t=0;t<n;t++){let m=rowMax(row,t,v);rowExp(row,t,v,m,e);let logs=f(Math.log(sumF32(e)));blank[t]=f(f((row[t*v]??0)-m)-logs);let cut=floor>0?f(logs+f(lf-0.001)):-1/0;let cand=[];for(let c=0;c<v;c++){let d=f((row[t*v+c]??0)-m);if(floor>0&&d<cut)continue;let val=f(d-logs);if(floor>0&&val<lf)continue;cand.push([val,c])}if(floor<=0&&cand.length>kk){let kth=cand.map(([val])=>val).toSorted((a,b)=>b-a)[kk-1]??-1/0;for(let i=cand.length-1;i>=0;i--)if((cand[i]?.[0]??0)<kth)cand.splice(i,1)}cand.sort((a,b)=>b[0]-a[0]||a[1]-b[1]);for(let i=0;i<Math.min(kk,cand.length);i++){const[val,c]=cand[i]??[-1/0,0];topv[t*kk+i]=val;topi[t*kk+i]=c}}return{blank,topv,topi,k:kk}}export function topKLogits(logits,B,T,v,n,k=TOPK){let out=[];let e=new Float32Array(v);for(let b=0;b<B;b++){let blank=new Float32Array(n);let topv=new Float32Array(n*k);let topi=new Int32Array(n*k);for(let t=0;t<n;t++){let row=logits.subarray((b*T+t)*v,(b*T+t+1)*v);let m=rowMax(row,0,v);rowExp(row,0,v,m,e);let lse=f(m+f(Math.log(sumF32(e))));blank[t]=f((row[0]??0)-lse);let best=[];for(let c=0;c<v;c++){let x=row[c]??-1/0;if(best.length===k&&x<=(row[best[k-1]??0]??-1/0))continue;let p=best.length;while(p>0&&(row[best[p-1]??0]??-1/0)<x)p--;best.splice(p,0,c);if(best.length>k)best.pop()}for(const[i,c]of best.entries()){topv[t*k+i]=f((row[c]??0)-lse);topi[t*k+i]=c}}out.push({blank,topv,topi,k})}return out}
package/indra/document.js CHANGED
@@ -1 +1 @@
1
- import{decodeToks}from"./lines.js";import{MATH_MIN_CONF}from"./math.js";import{cropLine}from"./rec-preproc.js";import{BROKEN_FONT_MAP,uprightTextLayer}from"./textlayer.js";import{NOT_THE_PAGE,layerMatches,readable}from"./layer-check.js";import{isStrongL}from"./unicode.js";import{isRtl}from"./rtl.js";import{rot90}from"./upright.js";import{isPySpace,item}from"./util.js";let CHECK_DPI=72;let MAX_PAGE_PIXELS=1e8;export function rightToLeft(tokens){let rtl=0;let ltr=0;for(const[c]of tokens){if(typeof c!=="string"||[...c].length!==1)continue;if(isRtl(c))rtl++;else if(isStrongL(c))ltr++}return rtl>ltr}function covered(box,boxes,frac=0.5){let f=Math.fround;let area=Math.max(f(f(box[2]-box[0])*f(box[3]-box[1])),0.000001);return boxes.some((b)=>{let ix=Math.max(f(Math.min(box[2],b[2])-Math.max(box[0],b[0])),0);let iy=Math.max(f(Math.min(box[3],b[3])-Math.max(box[1],b[1])),0);return f(f(ix*iy)/area)>frac})}export function assignRuns(runs,boxes,k){if(!boxes.length){return{toks:[],lost:runs.reduce((n,r)=>n+r.chars.filter(([c])=>!isPySpace(c)).length,0)}}let f=Math.fround;let area=boxes.map(([x0,y0,x1,y1])=>f(f(x1-x0)*f(y1-y0)));let parts=boxes.map(()=>new Map);let lost=0;for(let run of runs){let idx=run.seq;let j;for(const[c,b]of run.chars){if(!isPySpace(c)){let cx=(b[0]+b[2])/2*k;let cy=(b[1]+b[3])/2*k;let fx=f(cx);let fy=f(cy);let best;for(const[i,[x0,y0,x1,y1]]of boxes.entries()){if(x0<=fx&&fx<=x1&&y0<=fy&&fy<=y1&&(best===undefined||item(area,i)<item(area,best))){best=i}}j=best;if(j===undefined){lost++;continue}let line=item(parts,j);line.set(idx,[...line.get(idx)??[],[c,cx,idx]])}else if(j!==undefined){let part=item(parts,j).get(idx)??[];part.push([c,part.at(-1)?.[1]??0,idx])}}}let toks=parts.map((line)=>{let all=[...line.values()].flat();let rtl=rightToLeft(all);let key=(toksOf)=>rtl?-Math.max(...toksOf.map((t)=>t[1])):Math.min(...toksOf.map((t)=>t[1]));let order=[...line.keys()].toSorted((a,b)=>key(line.get(a)??[])-key(line.get(b)??[]));let tk=[];for(let idx of order){let last=tk.at(-1);if(last)tk.push([" ",last[1],idx]);tk.push(...line.get(idx)??[])}return tk});return{toks,lost}}function pageScale(page,dpi){const[w,h]=page.size();return Math.min(dpi/72,Math.sqrt(MAX_PAGE_PIXELS/Math.max(w*h,1)))}function timed(t,key,run){let t0=performance.now();let out=run();t[key]=performance.now()-t0;return out}export async function pdfPage(pipeline,page,options={}){const{mode="auto",dpi=200,imageOcr=true}=options;let t={};let note="mode=ocr";let turn=true;if(mode!=="ocr"){let s=CHECK_DPI/72;let t0=performance.now();let read=await uprightTextLayer(page,page.render(s),s,mode,async(up)=>{t["text_ms"]=performance.now()-t0;return textPage(pipeline,page,up,t,dpi,imageOcr,mode==="auto")});if(read.page)return read.page;const{tl}=read;t["text_ms"]=performance.now()-t0;let unreadable=tl.reason!==BROKEN_FONT_MAP&&!readable(pipeline,tl.lines);note=tl.reason;if(tl.lines.length&&(tl.trusted||mode==="text"||unreadable)){let check=mode==="auto"&&tl.trusted&&!unreadable;let out=await textPage(pipeline,page,tl,t,dpi,imageOcr,check);if(out)return out;note=NOT_THE_PAGE}turn=!(tl.reason===BROKEN_FONT_MAP&&tl.stats.rotated<0.5*tl.stats.chars)}let gray=timed(t,"render_ms",()=>page.render(pageScale(page,dpi)));let out=await pipeline.page(gray,turn);out.timings={...t,...out.timings};out.timings["total_ms"]=Object.entries(out.timings).reduce((n,[k,v])=>k==="total_ms"?n:n+v,0);out.note=`${note}; ${out.note}`;return out}async function textPage(pipeline,page,tl,t,dpi,imageOcr,check=false){let k=pageScale(page,dpi);let turn=tl.stats.turn??0;let frame=tl.stats.frame??turn;let vertical=Boolean(tl.stats.vertical);let rendered=timed(t,"render_ms",()=>page.render(k));let gray=frame?rot90(rendered,frame):rendered;let t0=performance.now();let boxes=(await pipeline.detect(gray)).map(([x0,y0,x1,y1])=>[x0,y0,x1,y1]);t["det_ms"]=performance.now()-t0;const{toks,lost}=assignRuns(tl.lines,boxes,k);let rec=toks.map((tk)=>{let text=tk.length?decodeToks(pipeline.vocab,tk):"";return text?{text,conf:1,toks:tk}:undefined});if(check&&!await layerMatches(pipeline,gray,boxes,rec,t))return;let empty=rec.flatMap((r,i)=>r?[]:[i]);let source="text";let side=tl.rotated.filter((r)=>r.text.trim());let f=Math.fround;let sideBoxes=side.map((r)=>[f(r.bbox[0]*k),f(r.bbox[1]*k),f(r.bbox[2]*k),f(r.bbox[3]*k)]);if(side.length&&empty.length){empty=empty.filter((i)=>!covered(item(boxes,i),sideBoxes))}if(empty.length&&imageOcr&&readable(pipeline,tl.lines)){t0=performance.now();let read=await pipeline.recognize(gray,empty.map((i)=>item(boxes,i)),64,vertical);for(const[n,i]of empty.entries()){let r=item(read,n);if(r.text.trim()){rec[i]=r;source="hybrid"}}t["rec_ms"]=performance.now()-t0}if(pipeline.mathReader){t0=performance.now();await readMath(pipeline,gray,boxes,rec);t["math_ms"]=performance.now()-t0}let keep=rec.flatMap((r,i)=>r?[i]:[]);let keptBoxes=keep.map((i)=>item(boxes,i));let keptRec=keep.map((i)=>item(rec,i)??{text:"",conf:0,toks:[]});for(const[n,r]of side.entries()){let b=item(sideBoxes,n);keptBoxes.push(b);let cx=f(b[0]+b[2])/2;keptRec.push({text:r.text,conf:1,toks:[...r.text].map((c)=>[c,cx,r.seq])})}let out=await pipeline.assemble(gray.width,gray.height,keptBoxes,keptRec,t,vertical);out.source=source;out.rotation=90*turn;if(vertical){let w=gray.height;let back=([x0,y0,x1,y1])=>[w-y1,x0,w-y0,x1];out.lines=out.lines.map((ln)=>({...ln,box:back(ln.box)}));out.blocks=out.blocks.map((b)=>({...b,bbox:back(b.bbox)}));out.vertical=true}if(lost)out.note+=`; ${lost} chars outside detected lines`;return out}async function readMath(pipeline,gray,boxes,rec){let math=pipeline.mathReader;if(!math)return;let idx=rec.flatMap((r,i)=>{let first=r?.toks[0];return first&&typeof first[0]==="string"&&first.length>2?[i]:[]});if(!idx.length)return;let crops=idx.map((i)=>cropLine(gray,item(boxes,i),pipeline.height,pipeline.imageOps));let flagged=(await math.flags(crops)).flatMap((fl,n)=>fl?[item(idx,n)]:[]);if(!flagged.length)return;let readings=await math.read(gray,flagged.map((i)=>item(boxes,i)));for(const[n,i]of flagged.entries()){const{text,conf}=item(readings,n);let r=rec[i];if(!r||!text.includes("$")||conf<MATH_MIN_CONF)continue;let first=Math.min(...r.toks.flatMap((tk)=>tk[2]===undefined?[]:[tk[2]]));const[x0,,x1]=item(boxes,i);rec[i]={text,conf:1,toks:[[text,Math.fround(x0+x1)/2,first]]}}}export function isPdf(bytes){let view=bytes instanceof Uint8Array?bytes.subarray(0,1024):new Uint8Array(bytes,0,Math.min(1024,bytes.byteLength));for(let i=0;i+5<=view.length;i++){if(view[i]===37&&view[i+1]===80&&view[i+2]===68&&view[i+3]===70&&view[i+4]===45){return true}}return false}
1
+ import{decodeToks}from"./lines.js";import{BROKEN_FONT_MAP,uprightTextLayer}from"./textlayer.js";import{NOT_THE_PAGE,layerChecks,readable}from"./layer-check.js";import{readLayerMath}from"./layer-math.js";import{fixSymbolDigits}from"./symbol-digits.js";import{isStrongL}from"./unicode.js";import{isRtl}from"./rtl.js";import{rot90}from"./upright.js";import{isPySpace,item}from"./util.js";let CHECK_DPI=72;let MAX_PAGE_PIXELS=1e8;export function rightToLeft(tokens){let rtl=0;let ltr=0;for(const[c]of tokens){if(typeof c!=="string"||[...c].length!==1)continue;if(isRtl(c))rtl++;else if(isStrongL(c))ltr++}return rtl>ltr}function covered(box,boxes,frac=0.5){let f=Math.fround;let area=Math.max(f(f(box[2]-box[0])*f(box[3]-box[1])),0.000001);return boxes.some((b)=>{let ix=Math.max(f(Math.min(box[2],b[2])-Math.max(box[0],b[0])),0);let iy=Math.max(f(Math.min(box[3],b[3])-Math.max(box[1],b[1])),0);return f(f(ix*iy)/area)>frac})}export function assignRuns(runs,boxes,k){if(!boxes.length){return{toks:[],lost:runs.reduce((n,r)=>n+r.chars.filter(([c])=>!isPySpace(c)).length,0)}}let f=Math.fround;let area=boxes.map(([x0,y0,x1,y1])=>f(f(x1-x0)*f(y1-y0)));let parts=boxes.map(()=>new Map);let lost=0;for(let run of runs){let idx=run.seq;let j;for(const[c,b]of run.chars){if(!isPySpace(c)){let cx=(b[0]+b[2])/2*k;let cy=(b[1]+b[3])/2*k;let fx=f(cx);let fy=f(cy);let best;for(const[i,[x0,y0,x1,y1]]of boxes.entries()){if(x0<=fx&&fx<=x1&&y0<=fy&&fy<=y1&&(best===undefined||item(area,i)<item(area,best))){best=i}}j=best;if(j===undefined){lost++;continue}let line=item(parts,j);line.set(idx,[...line.get(idx)??[],[c,cx,idx]])}else if(j!==undefined){let part=item(parts,j).get(idx)??[];part.push([c,part.at(-1)?.[1]??0,idx])}}}let toks=parts.map((line)=>{let all=[...line.values()].flat();let rtl=rightToLeft(all);let key=(toksOf)=>rtl?-Math.max(...toksOf.map((t)=>t[1])):Math.min(...toksOf.map((t)=>t[1]));let order=[...line.keys()].toSorted((a,b)=>key(line.get(a)??[])-key(line.get(b)??[]));let tk=[];for(let idx of order){let last=tk.at(-1);if(last)tk.push([" ",last[1],idx]);tk.push(...line.get(idx)??[])}return tk});return{toks,lost}}function pageScale(page,dpi){const[w,h]=page.size();return Math.min(dpi/72,Math.sqrt(MAX_PAGE_PIXELS/Math.max(w*h,1)))}function timed(t,key,run){let t0=performance.now();let out=run();t[key]=performance.now()-t0;return out}export async function pdfPage(pipeline,page,options={}){const{mode="auto",dpi=200,imageOcr=true}=options;let t={};let note="mode=ocr";let turn=true;if(mode!=="ocr"){let s=CHECK_DPI/72;let t0=performance.now();let read=await uprightTextLayer(page,page.render(s),s,mode,async(up)=>{t["text_ms"]=performance.now()-t0;return textPage(pipeline,page,up,t,dpi,imageOcr,mode==="auto")});if(read.page)return read.page;const{tl}=read;t["text_ms"]=performance.now()-t0;let unreadable=tl.reason!==BROKEN_FONT_MAP&&!readable(pipeline,tl.lines);note=tl.reason;if(tl.lines.length&&(tl.trusted||mode==="text"||unreadable)){let check=mode==="auto"&&tl.trusted&&!unreadable;let out=await textPage(pipeline,page,tl,t,dpi,imageOcr,check);if(out)return out;note=NOT_THE_PAGE}turn=!(tl.reason===BROKEN_FONT_MAP&&tl.stats.rotated<0.5*tl.stats.chars)}let gray=timed(t,"render_ms",()=>page.render(pageScale(page,dpi)));let out=await pipeline.page(gray,turn);out.timings={...t,...out.timings};out.timings["total_ms"]=Object.entries(out.timings).reduce((n,[k,v])=>k==="total_ms"?n:n+v,0);out.note=`${note}; ${out.note}`;return out}async function textPage(pipeline,page,tl,t,dpi,imageOcr,check=false){let k=pageScale(page,dpi);let turn=tl.stats.turn??0;let frame=tl.stats.frame??turn;let vertical=Boolean(tl.stats.vertical);let rendered=timed(t,"render_ms",()=>page.render(k));let gray=frame?rot90(rendered,frame):rendered;let t0=performance.now();let boxes=(await pipeline.detect(gray)).map(([x0,y0,x1,y1])=>[x0,y0,x1,y1]);t["det_ms"]=performance.now()-t0;const{toks,lost}=assignRuns(tl.lines,boxes,k);let repair=new Set;if(tl.rejected.length){for(const[i,tk]of assignRuns(tl.rejected,boxes,k).toks.entries())if(tk.length)repair.add(i);if(repair.size&&(!imageOcr||!readable(pipeline,tl.lines)))return}if(tl.symbolBoxes.length&&imageOcr&&!vertical){t0=performance.now();let f32=Math.fround;let sym=tl.symbolBoxes.map((b)=>[f32(b[0]*k),f32(b[1]*k),f32(b[2]*k),f32(b[3]*k)]);tl.stats.symbol_fixed=await fixSymbolDigits(pipeline,gray,boxes,toks,sym,repair);t["symbol_ms"]=performance.now()-t0}let rec=toks.map((tk,i)=>{let text=tk.length&&!repair.has(i)?decodeToks(pipeline.vocab,tk):"";return text?{text,conf:1,toks:tk}:undefined});if(check&&!vertical&&!await layerChecks(pipeline,gray,boxes,toks,rec,tl,t)){return}let empty=rec.flatMap((r,i)=>r?[]:[i]);let source="text";let side=tl.rotated.filter((r)=>r.text.trim());let f=Math.fround;let sideBoxes=side.map((r)=>[f(r.bbox[0]*k),f(r.bbox[1]*k),f(r.bbox[2]*k),f(r.bbox[3]*k)]);if(side.length&&empty.length){empty=empty.filter((i)=>repair.has(i)||!covered(item(boxes,i),sideBoxes))}if(empty.length&&imageOcr&&readable(pipeline,tl.lines)){t0=performance.now();let read=await pipeline.recognize(gray,empty.map((i)=>item(boxes,i)),64,vertical);for(const[n,i]of empty.entries()){let r=item(read,n);if(r.text.trim()){rec[i]=r;source="hybrid"}}t["rec_ms"]=performance.now()-t0}if(pipeline.mathReader){t0=performance.now();await readLayerMath(pipeline,gray,boxes,rec,source);t["math_ms"]=performance.now()-t0}let keep=rec.flatMap((r,i)=>r?[i]:[]);let keptBoxes=keep.map((i)=>item(boxes,i));let keptRec=keep.map((i)=>item(rec,i)??{text:"",conf:0,toks:[]});for(const[n,r]of side.entries()){let b=item(sideBoxes,n);keptBoxes.push(b);let cx=f(b[0]+b[2])/2;keptRec.push({text:r.text,conf:1,toks:[...r.text].map((c)=>[c,cx,r.seq])})}let out=await pipeline.assemble(gray,keptBoxes,keptRec,t,vertical,true);out.source=source;out.rotation=90*turn;if(vertical){let w=gray.height;let back=([x0,y0,x1,y1])=>[w-y1,x0,w-y0,x1];out.lines=out.lines.map((ln)=>({...ln,box:back(ln.box)}));out.blocks=out.blocks.map((b)=>({...b,bbox:back(b.bbox)}));out.vertical=true}if(lost)out.note+=`; ${lost} chars outside detected lines`;return out}export function isPdf(bytes){let view=bytes instanceof Uint8Array?bytes.subarray(0,1024):new Uint8Array(bytes,0,Math.min(1024,bytes.byteLength));for(let i=0;i+5<=view.length;i++){if(view[i]===37&&view[i+1]===80&&view[i+2]===68&&view[i+3]===70&&view[i+4]===45){return true}}return false}
package/indra/image.d.ts CHANGED
@@ -22,6 +22,8 @@ export type Interpolation = "area" | "linear";
22
22
  export type ImageOps = {
23
23
  /** `cv2.resize(src, (width, height), interpolation)` on uint8. */
24
24
  resize(src: Gray, width: number, height: number, interpolation: Interpolation): Gray;
25
+ /** `cv2.resize(src, (width, height), INTER_LINEAR)` on float32 (ink maps). */
26
+ resizeFloat(src: FloatImage, width: number, height: number): FloatImage;
25
27
  /** `cv2.warpAffine(src, m, (width, height), INTER_LINEAR, BORDER_REPLICATE)` on uint8. */
26
28
  warpReplicate(src: Gray, m: Affine, width: number, height: number): Gray;
27
29
  /** `cv2.warpAffine(src, m, (width, height))` on uint8: linear, zero border. */
@@ -1,26 +1,40 @@
1
1
  import type { Gray } from "./image.js";
2
+ import type { LayerRead } from "./layer-gaps.js";
2
3
  import type { IndraPipeline } from "./pipeline.js";
3
4
  import type { Box } from "./rec-preproc.js";
4
- import type { TextLine } from "./textlayer.js";
5
- import type { RecLine } from "./types.js";
6
- /** Page.note when the script check sends a page to OCR. */
5
+ import type { TextLayer, TextLine } from "./textlayer.js";
6
+ import type { RecLine, Tok } from "./types.js";
7
+ /** Text-layer lines whose start is read from the page image (agree.ts). */
8
+ export declare const CHECK_LINES = 6;
9
+ /** About this many characters from the start of each, cut at a word gap. */
10
+ export declare const CHECK_CHARS = 24;
11
+ /** The first line read at most this far off: the layer matches, the rest is not read. */
12
+ export declare const EASY_GAP = 0.25;
13
+ /** Page.note when the check sends a page to OCR. */
7
14
  export declare const NOT_THE_PAGE = "text layer does not match the page";
8
- /** Share of the letters in `text` that are basic Latin (a-z, A-Z). */
9
- export declare function latinShare(text: string): number;
10
- /**
11
- * Whether a text layer matches its page: at least AGREE_SHARE of the checked
12
- * lines agree. A legacy font (Kruti Dev and DevLys for Hindi, Bijoy for
13
- * Bangla) stores Latin codes for another script, so almost every line disagrees.
14
- */
15
- export declare function layerAgrees(agree: readonly boolean[]): boolean;
16
15
  /**
17
16
  * Whether the recognizers know at least READABLE_MIN of the letters in these
18
17
  * runs. A recognizer that reads Hangul as jamo knows a syllable by its jamo.
19
18
  */
20
19
  export declare function readable(pipeline: IndraPipeline, runs: readonly TextLine[]): boolean;
21
20
  /**
22
- * A line agrees unless its layer text is Latin while the script classifier
23
- * is sure its image is another script. Up to AGREE_LINES lines with four
24
- * letters or more are checked, spread over the page.
21
+ * The page score's inputs from the checked lines (a math line, gap null, is
22
+ * left out); undefined when no line counts. Gaps are capped at GAP_CAP; the
23
+ * trimmed mean leaves out the largest.
24
+ */
25
+ export declare function layerFeatures(reads: readonly LayerRead[]): number[] | undefined;
26
+ /**
27
+ * Whether a text layer is its page's text: the page score over the checked
28
+ * lines is at most 0. A legacy font or a broken ToUnicode map gives most
29
+ * lines a gap of 2 to 20; a map that breaks only some letters (Thai tone
30
+ * marks, Arabic lam-alef, Indic vowel signs) gives some lines a gap of 0.5 to
31
+ * 3; a sound layer gives about 0, also where the recognizer is unsure.
32
+ */
33
+ export declare function layerMatches(reads: readonly LayerRead[]): boolean;
34
+ /**
35
+ * Whether the text layer is the page's text: the start of up to CHECK_LINES
36
+ * of its lines is read from the page image (agree.ts). The line halfway down
37
+ * goes first; the others only when it does not clearly match, or when the
38
+ * layer dropped runs with bad codes (a font map that may break other runs too).
25
39
  */
26
- export declare function layerMatches(pipeline: IndraPipeline, gray: Gray, boxes: readonly Box[], rec: readonly (RecLine | undefined)[], t: Record<string, number>): Promise<boolean>;
40
+ export declare function layerChecks(pipeline: IndraPipeline, gray: Gray, boxes: readonly Box[], toks: readonly Tok[][], rec: readonly (RecLine | undefined)[], tl: TextLayer, t: Record<string, number>): Promise<boolean>;
@@ -1 +1 @@
1
- import{item}from"./util.js";let LETTER=/^\p{L}$/u;let READABLE_MIN=0.9;let AGREE_LINES=6;let AGREE_SHARE=0.25;let LATIN_CODES=0.9;export let NOT_THE_PAGE="text layer does not match the page";export function latinShare(text){let letters=[...text].filter((c)=>LETTER.test(c));return letters.filter((c)=>c.charCodeAt(0)<128).length/Math.max(letters.length,1)}export function layerAgrees(agree){return!agree.length||agree.filter(Boolean).length>=AGREE_SHARE*agree.length}export function readable(pipeline,runs){let letters=runs.flatMap((r)=>[...r.text].filter((c)=>LETTER.test(c)));if(!letters.length)return true;let vocabs=pipeline.vocabs.map((v)=>v.index);let known=letters.filter((c)=>vocabs.some((v)=>v.has(c)||[...c.normalize("NFD")].every((j)=>v.has(j)))).length;return known>=READABLE_MIN*letters.length}export async function layerMatches(pipeline,gray,boxes,rec,t){let full=rec.flatMap((r,i)=>r&&[...r.text].filter((c)=>LETTER.test(c)).length>=4?[i]:[]);let step=Math.max(1,Math.floor(full.length/AGREE_LINES));let pick=full.filter((_,n)=>n%step===0).slice(0,AGREE_LINES);if(!pick.length)return true;let t0=performance.now();const{names,sure}=await pipeline.boxGroups(gray,pick.map((i)=>item(boxes,i)));let agree=pick.map((i,n)=>!(latinShare(item(rec,i)?.text??"")>=LATIN_CODES&&names[n]!=="base"&&sure[n]));t["check_ms"]=performance.now()-t0;return layerAgrees(agree)}
1
+ import{snippet}from"./agree.js";import{isAlpha}from"./py-unicode.js";import{item}from"./util.js";let LETTER=/^\p{L}$/u;let READABLE_MIN=0.9;export let CHECK_LINES=6;export let CHECK_CHARS=24;let GAP_CAP=10;export let EASY_GAP=0.25;let SURE_CONF=0.97;let LAYER_GROUPS=["world","rtl","cjk"];let LAYER_WEIGHTS=[0.06462,0.07808,-0.1493,0.3135,1.514,1.05,7.785,2.993,3.216,5.219,3.738];let LAYER_BIAS=-9.334;export let NOT_THE_PAGE="text layer does not match the page";export function readable(pipeline,runs){let letters=runs.flatMap((r)=>[...r.text].filter((c)=>LETTER.test(c)));if(!letters.length)return true;let vocabs=pipeline.vocabs.map((v)=>v.index);let known=letters.filter((c)=>vocabs.some((v)=>v.has(c)||[...c.normalize("NFD")].every((j)=>v.has(j)))).length;return known>=READABLE_MIN*letters.length}function median(sorted){let n=sorted.length;let mid=Math.floor(n/2);return n%2?item(sorted,mid):(item(sorted,mid-1)+item(sorted,mid))/2}export function layerFeatures(reads){let lines=reads.flatMap((r)=>r.gap===null?[]:[{gap:Math.min(r.gap,GAP_CAP),conf:r.conf,group:r.group}]);if(!lines.length)return;let gaps=lines.map((l)=>l.gap).toSorted((a,b)=>a-b);let kept=gaps.length>2?gaps.slice(0,-1):gaps;let n=gaps.length;let share=(pred)=>gaps.filter(pred).length/n;let over=share((g)=>g>0.5);return[kept.reduce((a,b)=>a+b,0)/kept.length,median(gaps),...[0.5,1,2,4].map((t)=>share((g)=>g>t)),lines.reduce((a,l)=>a+l.conf,0)/n,...LAYER_GROUPS.map((name)=>over*lines.filter((l)=>l.group===name).length/n),lines.filter((l)=>l.gap>1&&l.conf>=SURE_CONF).length/n]}export function layerMatches(reads){let x=layerFeatures(reads);if(!x)return true;return LAYER_BIAS+x.reduce((s,v,i)=>s+(LAYER_WEIGHTS[i]??0)*v,0)<=0}export async function layerChecks(pipeline,gray,boxes,toks,rec,tl,t){let t0=performance.now();let full=rec.flatMap((r,i)=>r&&Array.from(r.text).filter(isAlpha).length>=4?[i]:[]);let step=Math.max(1,Math.floor(full.length/CHECK_LINES));let pick=full.filter((_,n)=>n%step===0).slice(0,CHECK_LINES);if(!pick.length)return true;let first=Math.floor(pick.length/2);let reads=await startGaps(pipeline,gray,boxes,toks,[item(pick,first)]);let ok=true;if(tl.stats.bad_runs||reads.some((r)=>r.gap!==null&&r.gap>EASY_GAP)){reads.push(...await startGaps(pipeline,gray,boxes,toks,pick.filter((_,j)=>j!==first)));ok=layerMatches(reads)}t["check_ms"]=performance.now()-t0;return ok}async function startGaps(pipeline,gray,boxes,toks,lines){if(!lines.length)return[];let cut=lines.map((i)=>snippet(item(toks,i),CHECK_CHARS));let sb=lines.map((i,n)=>{const[x0,y0,x1,y1]=item(boxes,i);let x=item(cut,n).cut;return[x0,y0,x===undefined?x1:Math.fround(Math.min(x1,x)),y1]});return pipeline.layerGaps(gray,sb,cut.map((c)=>c.toks))}
@@ -0,0 +1,23 @@
1
+ import type { Gray, ImageOps } from "./image.js";
2
+ import type { Box } from "./rec-preproc.js";
3
+ import type { Recognizers } from "./recognizers.js";
4
+ import type { TensorCtor, Tok } from "./types.js";
5
+ /**
6
+ * One checked line: the log-probability per token by which the line's
7
+ * recognizer finds the layer's text less likely than its own best reading
8
+ * (null for a line read as math: the recognizer writes LaTeX where the layer
9
+ * holds Unicode symbols, so the two do not compare), that recognizer's
10
+ * confidence in its own reading, and the recognizer ("base" or a group).
11
+ */
12
+ export type LayerRead = {
13
+ gap: number | null;
14
+ conf: number;
15
+ group: string;
16
+ };
17
+ /**
18
+ * Per line box and its text-layer tokens: the gap, confidence and recognizer
19
+ * (LayerRead). script.onnx routes each crop; a line the router is not sure of
20
+ * is also read by each other recognizer that writes the layer's letters, and
21
+ * the smallest gap counts.
22
+ */
23
+ export declare function layerGaps(Tensor: TensorCtor, recs: Recognizers, ops: ImageOps, gray: Gray, boxes: readonly Box[], tokens: readonly (readonly Tok[])[]): Promise<LayerRead[]>;
@@ -0,0 +1 @@
1
+ import{forcedGaps,layerText,targetIds,writes}from"./agree.js";import{topKLogits}from"./ctc.js";import{meanF32}from"./numeric.js";import{padBatch,widen}from"./rec-preproc.js";import{hasLogits,lmReady}from"./recognize.js";import{floats,ints,item,output}from"./util.js";export async function layerGaps(Tensor,recs,ops,gray,boxes,tokens){if(!boxes.length)return[];let readers=recs.readers();let main=item(readers,0);if(!lmReady(await main.session())){return boxes.map(()=>({gap:null,conf:0,group:"base"}))}const{crops,tall}=recs.lineCrops(gray,boxes);const{names,sure}=await recs.cropGroups(crops);let texts=new Map(readers.map((r)=>[r.name,tokens.map((t)=>layerText(t,r.name==="rtl"))]));let textOf=(name,j)=>item(texts.get(name)??[],j);let cands=names.map((g,j)=>{let c=new Set([g]);if(!sure[j]){for(let r of readers)if(writes(textOf(r.name,j),r.vocab))c.add(r.name)}return c});let mathLines=new Set;let todo=[];for(let r of readers){let sel=cands.flatMap((c,j)=>c.has(r.name)?[j]:[]);if(!sel.length)continue;let sess=await r.session();let src=sel.map((j)=>item(r.main?tall:crops,j));const{data,dims,widths}=padBatch(widen(src,r.xscale,ops));let feed={x:new Tensor("float32",data,dims),widths:new Tensor("int64",widths,[sel.length])};let logitsOut=hasLogits(sess);let res=await sess.run(feed,logitsOut?["ids","lengths","logits"]:["ids","conf","lengths","blank","topv","topi"]);let ids=output(res,"ids");let best=ints(ids);let steps=ids.dims[1]??0;let lengths=ints(output(res,"lengths"));let lines;if(logitsOut){let logits=output(res,"logits");let v=logits.dims[2]??0;lines=topKLogits(floats(logits),sel.length,steps,v,Math.max(...lengths))}else{let topvT=output(res,"topv");let K=topvT.dims[2]??0;let blank=floats(output(res,"blank"));let topv=floats(topvT);let topi=Int32Array.from(ints(output(res,"topi")));lines=sel.map((_,k)=>({blank:blank.subarray(k*steps,(k+1)*steps),topv:topv.subarray(k*steps*K,(k+1)*steps*K),topi:topi.subarray(k*steps*K,(k+1)*steps*K),k:K}))}let dollar=r.vocab.index.get("$");for(const[k,j]of sel.entries()){let n=item(lengths,k);let seq=best.slice(k*steps,k*steps+n);if(dollar!==undefined&&seq.includes(dollar)){mathLines.add(j);continue}const{blank,topv,topi,k:K}=item(lines,k);let peaks=[];for(let t=0;t<n;t++){if(seq[t]===0||t>0&&seq[t]===seq[t-1])continue;peaks.push(Math.fround(Math.exp(Math.max(blank[t]??0,topv[t*K]??0))))}let conf=peaks.length?meanF32(peaks):0;let target=targetIds(textOf(r.name,j),r.vocab,r.name==="rtl");let gapItem={blank:blank.subarray(0,n),topv:topv.subarray(0,n*K),topi:topi.subarray(0,n*K),k:K,ids:target};todo.push({j,conf,name:r.name,item:gapItem})}}let out=names.map((g)=>({gap:1/0,conf:0,group:g}));let gaps=forcedGaps(todo.map((t)=>t.item));for(const[i,{j,conf,name}]of todo.entries()){let g=item(gaps,i);if(g<(item(out,j).gap??1/0))out[j]={gap:g,conf,group:name}}for(let j of mathLines)out[j]={gap:null,conf:0,group:item(names,j)};return out}
@@ -0,0 +1,13 @@
1
+ import type { Gray } from "./image.js";
2
+ import type { IndraPipeline } from "./pipeline.js";
3
+ import type { Box } from "./rec-preproc.js";
4
+ import type { RecLine } from "./types.js";
5
+ /**
6
+ * Text-layer lines that hold math (the classifier, on their crops) are read
7
+ * by the math reader: the layer has the symbols but not the LaTeX. Only lines
8
+ * whose letters are mostly Latin go (MathRec writes Latin letters); a learned
9
+ * gate may skip some, weighing text-layer and hybrid pages apart. An accepted
10
+ * reading takes the layer's accents in its prose, and the line keeps its
11
+ * place in the content order (its first character's index).
12
+ */
13
+ export declare function readLayerMath(pipeline: IndraPipeline, gray: Gray, boxes: readonly Box[], rec: (RecLine | undefined)[], source: "text" | "hybrid"): Promise<void>;
@@ -0,0 +1 @@
1
+ import{latinLine}from"./math-text.js";import{cropLine}from"./rec-preproc.js";import{item}from"./util.js";export async function readLayerMath(pipeline,gray,boxes,rec,source){let math=pipeline.mathReader;if(!math)return;let idx=rec.flatMap((r,i)=>{let first=r?.toks[0];return r&&first&&typeof first[0]==="string"&&first[2]!==undefined&&latinLine(r.text)?[i]:[]});if(!idx.length)return;let crops=idx.map((i)=>cropLine(gray,item(boxes,i),pipeline.height,pipeline.imageOps));const{flags,probs}=await math.flags(crops);let flagged=idx.filter((_,n)=>flags[n]);let draftOf=(i)=>item(rec,i)?.text??"";if(flagged.length&&math.hasGate){let keep=math.gate(probs.filter((_,n)=>flags[n]),flagged.map(draftOf),idx.length,source);flagged=flagged.filter((_,n)=>keep[n])}if(!flagged.length)return;let readings=await math.read(gray,flagged.map((i)=>item(boxes,i)));for(const[n,i]of flagged.entries()){const{text,conf}=item(readings,n);let r=rec[i];if(!r)continue;let merged=math.accept(text,conf,r.text,1);if(merged===null)continue;let first=Math.min(...r.toks.flatMap((tk)=>tk[2]===undefined?[]:[tk[2]]));const[x0,,x1]=item(boxes,i);rec[i]={text:merged,conf:1,toks:[[merged,Math.fround(x0+x1)/2,first]],math:{plain:r,reading:text,conf,draft:r.text,rconf:1}}}}
@@ -1,5 +1,7 @@
1
1
  import type { BlockLabel } from "./order-post.js";
2
2
  import type { Box } from "./rec-preproc.js";
3
+ /** Index of "Table" in BLOCK_CLASSES. */
4
+ export declare const TABLE = 5;
3
5
  /** A layout block: its label, the union of its line boxes, and its lines' text. */
4
6
  export type LayoutBlock = {
5
7
  label: BlockLabel;
@@ -11,6 +13,10 @@ export type Cell = {
11
13
  box: Box;
12
14
  text: string;
13
15
  };
16
+ /** HTML read by tsr_rel.onnx per table block, keyed by `blockKey` of the block's line indices. */
17
+ export type TableMap = ReadonlyMap<string, string>;
18
+ /** The key of a block in a `TableMap`: its line indices, comma-joined (the reference keys by tuple). */
19
+ export declare function blockKey(blk: readonly number[]): string;
14
20
  /**
15
21
  * Join the lines of one paragraph. "tumori-" + "genesis" -> "tumorigenesis";
16
22
  * a line break between two CJK characters takes no space.
@@ -26,10 +32,19 @@ export declare function splitBlocks(order: readonly number[], same: Float32Array
26
32
  export declare function tableHtml(boxes: readonly Box[], texts: readonly string[]): string;
27
33
  /** The layout blocks behind pageMarkdown, in reading order. */
28
34
  export declare function pageBlocks(boxes: readonly Box[], texts: readonly string[], order: readonly number[], cls: Float32Array, same: Float32Array): LayoutBlock[];
35
+ /**
36
+ * Markdown of one block, or undefined for a block that writes nothing (page
37
+ * furniture left out). `cells` maps a line to its table cells when the line
38
+ * holds several; `tab` [3, n, n] (n = all lines) builds a table from the order
39
+ * model's heads when they are plausible.
40
+ */
41
+ export declare function blockPart(blk: readonly number[], boxes: readonly Box[], texts: readonly string[], cls: Float32Array, keepFurniture: boolean, cells?: ReadonlyMap<number, readonly Cell[]>, tab?: Float32Array): string | undefined;
29
42
  /**
30
43
  * Markdown for one page: section headers as "## ", paragraphs joined, lists one
31
44
  * item per line, tables as HTML from their cell lines, display math as $$...$$.
32
45
  * Page headers and footers are left out unless `keepFurniture`. `cells` maps a
33
- * line to its table cells when the line holds several.
46
+ * line to its table cells when the line holds several. `tables` holds HTML read
47
+ * by tsr_rel.onnx for table blocks (see `TableReader`); a block in it is written
48
+ * as given. `tab` is the order model's table heads (see `blockPart`).
34
49
  */
35
- export declare function pageMarkdown(boxes: readonly Box[], texts: readonly string[], order: readonly number[], cls: Float32Array, same: Float32Array, keepFurniture?: boolean, cells?: ReadonlyMap<number, readonly Cell[]>): string;
50
+ export declare function pageMarkdown(boxes: readonly Box[], texts: readonly string[], order: readonly number[], cls: Float32Array, same: Float32Array, keepFurniture?: boolean, cells?: ReadonlyMap<number, readonly Cell[]>, tables?: TableMap, tab?: Float32Array): string;
@@ -1,9 +1,9 @@
1
- import{meanF32}from"./numeric.js";import{BLOCK_CLASSES,blockClass,medianF32}from"./order-post.js";import{roundTo}from"./upright.js";import{item}from"./util.js";let f=Math.fround;let HEADER=2;let FOOTER=3;let SECTION=1;let LIST=4;let TABLE=5;let WHOLE_MATH=/^\$[^$]+\$$/;let ITEM=new RegExp("^\\s*([\\u2022\\-\\u2013\\u25aa\\u25e6*\\u00b7\\u2192]|\\(?\\p{Nd}{1,3}[.)]|\\(?[a-zA-Z][.)])(\\s|$)","u");let ALPHA=/^\p{L}$/u;let LOWER=/^\p{Lowercase}$/u;function isCjk(c){let o=c.codePointAt(0)??0;return o>=12288&&o<=12543||o>=13312&&o<=40959||o>=63744&&o<=64255||o>=65280&&o<=65519||o>=131072&&o<=195103}export function joinLines(texts){let out=[];for(let raw of texts){let t=[...raw.trim()];if(!t.length)continue;let first=item(t,0);if(out.length>1&&out.at(-1)==="-"&&ALPHA.test(out.at(-2)??"")&&ALPHA.test(first)&&LOWER.test(first)){out=[...out.slice(0,-1),...t]}else if(out.length&&isCjk(out.at(-1)??"")&&isCjk(first)){out.push(...t)}else{out=out.length?[...out," ",...t]:t}}return out.join("")}export function splitBlocks(order,same,n){let blocks=[];for(let i of order){let last=blocks.at(-1);if(last&&(same[(last.at(-1)??0)*n+i]??0)>0)last.push(i);else blocks.push([i])}return blocks}function tableRows(boxes){let cy=boxes.map(([,y0,,y1])=>f(f(y0+y1)/2));let h=medianF32(boxes.map(([,y0,,y1])=>f(y1-y0)));let rows=[];for(let i of cy.map((_,k)=>k).toSorted((p,q)=>item(cy,p)-item(cy,q))){let last=rows.at(-1);if(last&&Math.abs(f(item(cy,i)-meanF32(last.map((k)=>item(cy,k)))))<0.5*h)last.push(i);else rows.push([i])}return rows.map((r)=>r.toSorted((p,q)=>item(boxes,p)[0]-item(boxes,q)[0]))}function median64(values){let v=values.toSorted((a,b)=>a-b);let m=Math.floor(v.length/2);return v.length%2?item(v,m):(item(v,m-1)+item(v,m))/2}function mergeWrapped(rows,boxes){if(rows.length<3)return rows;let h=medianF32(boxes.map(([,y0,,y1])=>f(y1-y0)));let gaps=rows.slice(0,-1).map((cur,k)=>{let next=item(rows,k+1);let top=Math.min(...next.map((i)=>item(boxes,i)[1]));let bottom=Math.max(...cur.map((i)=>item(boxes,i)[3]));return f(top-bottom)});let med=median64(gaps);let out=[[...item(rows,0)]];let prev=item(rows,0);for(const[k,g]of gaps.entries()){let r=item(rows,k+1);if(g<0.5*med&&g<0.6*h&&r.length<prev.length)out.at(-1)?.push(...r);else out.push([...r]);prev=r}return out}let escapeHtml=(s)=>s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");export function tableHtml(boxes,texts){let rows=tableRows(boxes);let spanX=f(Math.max(...boxes.map((b)=>b[2]))-Math.min(...boxes.map((b)=>b[0])));let top=item(item(rows,0),0);const[tx0,,tx1]=item(boxes,top);if(rows.length>2&&item(rows,0).length===1&&Math.max(...rows.map((r)=>r.length))>1&&f(tx1-tx0)>f(f(0.6)*spanX)){let keep=texts.map((_,k)=>k).filter((k)=>k!==top);return`${item(texts,top)}
1
+ import{meanF32}from"./numeric.js";import{BLOCK_CLASSES,blockClass,medianF32}from"./order-post.js";import{pyHtmlEscape}from"./py-text.js";import{headsPlausible,subTab,tableHtmlHeads}from"./table-heads.js";import{roundTo}from"./upright.js";import{item}from"./util.js";let f=Math.fround;let HEADER=2;let FOOTER=3;let SECTION=1;let LIST=4;export let TABLE=5;let WHOLE_MATH=/^\$[^$]+\$$/;let ITEM=new RegExp("^\\s*([\\u2022\\-\\u2013\\u25aa\\u25e6*\\u00b7\\u2192]|\\(?\\p{Nd}{1,3}[.)]|\\(?[a-zA-Z][.)])(\\s|$)","u");let ALPHA=/^\p{L}$/u;let LOWER=/^\p{Lowercase}$/u;export function blockKey(blk){return blk.join(",")}function isCjk(c){let o=c.codePointAt(0)??0;return o>=12288&&o<=12543||o>=13312&&o<=40959||o>=63744&&o<=64255||o>=65280&&o<=65519||o>=131072&&o<=195103}export function joinLines(texts){let out=[];for(let raw of texts){let t=[...raw.trim()];if(!t.length)continue;let first=item(t,0);if(out.length>1&&out.at(-1)==="-"&&ALPHA.test(out.at(-2)??"")&&ALPHA.test(first)&&LOWER.test(first)){out=[...out.slice(0,-1),...t]}else if(out.length&&isCjk(out.at(-1)??"")&&isCjk(first)){out.push(...t)}else{out=out.length?[...out," ",...t]:t}}return out.join("")}export function splitBlocks(order,same,n){let blocks=[];for(let i of order){let last=blocks.at(-1);if(last&&(same[(last.at(-1)??0)*n+i]??0)>0)last.push(i);else blocks.push([i])}return blocks}function tableRows(boxes){let cy=boxes.map(([,y0,,y1])=>f(f(y0+y1)/2));let h=medianF32(boxes.map(([,y0,,y1])=>f(y1-y0)));let rows=[];for(let i of cy.map((_,k)=>k).toSorted((p,q)=>item(cy,p)-item(cy,q))){let last=rows.at(-1);if(last&&Math.abs(f(item(cy,i)-meanF32(last.map((k)=>item(cy,k)))))<0.5*h)last.push(i);else rows.push([i])}return rows.map((r)=>r.toSorted((p,q)=>item(boxes,p)[0]-item(boxes,q)[0]))}function median64(values){let v=values.toSorted((a,b)=>a-b);let m=Math.floor(v.length/2);return v.length%2?item(v,m):(item(v,m-1)+item(v,m))/2}function mergeWrapped(rows,boxes){if(rows.length<3)return rows;let h=medianF32(boxes.map(([,y0,,y1])=>f(y1-y0)));let gaps=rows.slice(0,-1).map((cur,k)=>{let next=item(rows,k+1);let top=Math.min(...next.map((i)=>item(boxes,i)[1]));let bottom=Math.max(...cur.map((i)=>item(boxes,i)[3]));return f(top-bottom)});let med=median64(gaps);let out=[[...item(rows,0)]];let prev=item(rows,0);for(const[k,g]of gaps.entries()){let r=item(rows,k+1);if(g<0.5*med&&g<0.6*h&&r.length<prev.length)out.at(-1)?.push(...r);else out.push([...r]);prev=r}return out}export function tableHtml(boxes,texts){let rows=tableRows(boxes);let spanX=f(Math.max(...boxes.map((b)=>b[2]))-Math.min(...boxes.map((b)=>b[0])));let top=item(item(rows,0),0);const[tx0,,tx1]=item(boxes,top);if(rows.length>2&&item(rows,0).length===1&&Math.max(...rows.map((r)=>r.length))>1&&f(tx1-tx0)>f(f(0.6)*spanX)){let keep=texts.map((_,k)=>k).filter((k)=>k!==top);return`${item(texts,top)}
2
2
 
3
- ${tableHtml(keep.map((k)=>item(boxes,k)),keep.map((k)=>item(texts,k)))}`}let width=Math.max(...rows.map((r)=>r.length));let full=rows.filter((r)=>r.length===width);rows=mergeWrapped(rows,boxes);let bands=Array.from({length:width},(_,c)=>[medianF32(full.map((r)=>item(boxes,item(r,c))[0])),medianF32(full.map((r)=>item(boxes,item(r,c))[2]))]);let edges=[-1/0,...bands.slice(0,-1).map((b,c)=>f(f(b[1]+item(bands,c+1)[0])/2)),1/0];let bandOf=(x)=>edges.filter((e)=>e<=x).length-1;let out=["<table>"];for(const[ri,r]of rows.entries()){let tag=ri===0&&rows.length>1?"th":"td";let cells=new Map;let byPos=r.toSorted((p,q)=>item(boxes,p)[1]-item(boxes,q)[1]||item(boxes,p)[0]-item(boxes,q)[0]);for(let k of byPos){const[x0,,x1]=item(boxes,k);let first=bandOf(x0);let last=bandOf(x1);let span=[];for(let c=Math.max(first,0);c<=Math.min(last,width-1);c++){const[b0,b1]=item(bands,c);if(f(Math.min(x1,b1)-Math.max(x0,b0))>f(0.5*f(b1-b0)))span.push(c)}if(!span.length)span.push(Math.min(Math.max(first,0),width-1));let c0=item(span,0);let prev=cells.get(c0);cells.set(c0,prev?{span:Math.max(prev.span,span.length),text:`${prev.text} ${item(texts,k)}`}:{span:span.length,text:item(texts,k)})}let tds="";for(let c=0;c<width;){let cell=cells.get(c);if(cell){let attr=cell.span>1?` colspan="${cell.span}"`:"";tds+=`<${tag}${attr}>${escapeHtml(cell.text)}</${tag}>`;c+=cell.span}else{tds+=`<${tag}></${tag}>`;c+=1}}out.push(`<tr>${tds}</tr>`)}out.push("</table>");return out.join(`
3
+ ${tableHtml(keep.map((k)=>item(boxes,k)),keep.map((k)=>item(texts,k)))}`}let width=Math.max(...rows.map((r)=>r.length));let full=rows.filter((r)=>r.length===width);rows=mergeWrapped(rows,boxes);let bands=Array.from({length:width},(_,c)=>[medianF32(full.map((r)=>item(boxes,item(r,c))[0])),medianF32(full.map((r)=>item(boxes,item(r,c))[2]))]);let edges=[-1/0,...bands.slice(0,-1).map((b,c)=>f(f(b[1]+item(bands,c+1)[0])/2)),1/0];let bandOf=(x)=>edges.filter((e)=>e<=x).length-1;let out=["<table>"];for(const[ri,r]of rows.entries()){let tag=ri===0&&rows.length>1?"th":"td";let cells=new Map;let byPos=r.toSorted((p,q)=>item(boxes,p)[1]-item(boxes,q)[1]||item(boxes,p)[0]-item(boxes,q)[0]);for(let k of byPos){const[x0,,x1]=item(boxes,k);let first=bandOf(x0);let last=bandOf(x1);let span=[];for(let c=Math.max(first,0);c<=Math.min(last,width-1);c++){const[b0,b1]=item(bands,c);if(f(Math.min(x1,b1)-Math.max(x0,b0))>f(0.5*f(b1-b0)))span.push(c)}if(!span.length)span.push(Math.min(Math.max(first,0),width-1));let c0=item(span,0);let prev=cells.get(c0);cells.set(c0,prev?{span:Math.max(prev.span,span.length),text:`${prev.text} ${item(texts,k)}`}:{span:span.length,text:item(texts,k)})}let tds="";for(let c=0;c<width;){let cell=cells.get(c);if(cell){let attr=cell.span>1?` colspan="${cell.span}"`:"";tds+=`<${tag}${attr}>${pyHtmlEscape(cell.text)}</${tag}>`;c+=cell.span}else{tds+=`<${tag}></${tag}>`;c+=1}}out.push(`<tr>${tds}</tr>`)}out.push("</table>");return out.join(`
4
4
  `)}export function pageBlocks(boxes,texts,order,cls,same){return splitBlocks(order,same,boxes.length).map((blk)=>{let b=blk.map((i)=>item(boxes,i));return{label:item(BLOCK_CLASSES,blockClass(cls,blk)),bbox:[roundTo(Math.min(...b.map((x)=>x[0])),1),roundTo(Math.min(...b.map((x)=>x[1])),1),roundTo(Math.max(...b.map((x)=>x[2])),1),roundTo(Math.max(...b.map((x)=>x[3])),1)],text:blk.map((i)=>item(texts,i)).join(`
5
- `)}})}export function pageMarkdown(boxes,texts,order,cls,same,keepFurniture=false,cells){let parts=[];for(let blk of splitBlocks(order,same,boxes.length)){let c=blockClass(cls,blk);let textsB=blk.map((i)=>item(texts,i));if((c===HEADER||c===FOOTER)&&!keepFurniture)continue;if(textsB.every((t)=>WHOLE_MATH.test(t.trim()))){parts.push(textsB.map((t)=>`$$${t.trim().slice(1,-1)}$$`).join(`
6
- `));continue}if(c===SECTION){parts.push(`## ${joinLines(textsB)}`)}else if(c===TABLE&&blk.length>1){let cb=[];let ct=[];for(let i of blk){let lineCells=cells?.get(i);for(let cell of lineCells?.length?lineCells:[{box:item(boxes,i),text:item(texts,i)}]){const[x0,y0,x1,y1]=cell.box;cb.push([f(x0),f(y0),f(x1),f(y1)]);ct.push(cell.text)}}parts.push(tableHtml(cb,ct))}else if(c===LIST){let items=[];for(let t of textsB){let last=items.at(-1);if(!last||ITEM.test(t))items.push([t]);else last.push(t)}parts.push(items.map(joinLines).join(`
7
- `))}else{parts.push(joinLines(textsB))}}return parts.filter((p)=>p).join(`
5
+ `)}})}export function blockPart(blk,boxes,texts,cls,keepFurniture,cells,tab){let c=blockClass(cls,blk);let textsB=blk.map((i)=>item(texts,i));if((c===HEADER||c===FOOTER)&&!keepFurniture)return;if(textsB.every((t)=>WHOLE_MATH.test(t.trim()))){return textsB.map((t)=>`$$${t.trim().slice(1,-1)}$$`).join(`
6
+ `)}if(c===SECTION)return`## ${joinLines(textsB)}`;if(c===TABLE&&blk.length>1){if(tab){let lineBoxes=blk.map((i)=>item(boxes,i));let sub=subTab(tab,boxes.length,blk);if(headsPlausible(lineBoxes,sub))return tableHtmlHeads(lineBoxes,textsB,sub)}let cb=[];let ct=[];for(let i of blk){let lineCells=cells?.get(i);for(let cell of lineCells?.length?lineCells:[{box:item(boxes,i),text:item(texts,i)}]){const[x0,y0,x1,y1]=cell.box;cb.push([f(x0),f(y0),f(x1),f(y1)]);ct.push(cell.text)}}return tableHtml(cb,ct)}if(c===LIST){let items=[];for(let t of textsB){let last=items.at(-1);if(!last||ITEM.test(t))items.push([t]);else last.push(t)}return items.map(joinLines).join(`
7
+ `)}return joinLines(textsB)}export function pageMarkdown(boxes,texts,order,cls,same,keepFurniture=false,cells,tables,tab){let parts=[];for(let blk of splitBlocks(order,same,boxes.length)){let read=tables?.get(blockKey(blk));let part=read===undefined?blockPart(blk,boxes,texts,cls,keepFurniture,cells,tab):read;if(part!==undefined)parts.push(part)}return parts.filter((p)=>p).join(`
8
8
 
9
9
  `)}
@@ -0,0 +1,34 @@
1
+ import type { InferenceSession, Tensor } from "onnxruntime-common";
2
+ import type { Gray, ImageOps, Interpolation } from "./image.js";
3
+ import type { Box } from "./rec-preproc.js";
4
+ import type { TensorCtor } from "./types.js";
5
+ /** The thumbnail size and resize mode an order model reads. */
6
+ export type ThumbSpec = {
7
+ height: number;
8
+ width: number;
9
+ interp: Interpolation;
10
+ };
11
+ /**
12
+ * The thumbnail spec of an order model that reads line thumbnails (an input
13
+ * named "thumbs"), or undefined for one that does not. The size comes from
14
+ * the input's shape, the resize mode from meta.json (default area).
15
+ */
16
+ export declare function thumbSpec(order: InferenceSession, interp: Interpolation | undefined): ThumbSpec | undefined;
17
+ /**
18
+ * [N, 1, h, w] float32 thumbnails of line boxes (pixels of `gray`): the box
19
+ * with THUMB_CTX line heights above and below, scaled to h rows with its
20
+ * aspect kept (cut at w), ink = 1. The order model expects exactly these.
21
+ */
22
+ export declare function lineThumbs(gray: Gray, boxes: readonly Box[], { height: th, width: tw, interp }: ThumbSpec, ops: ImageOps): Float32Array;
23
+ /** The order model's thumbnail inputs. */
24
+ export type ThumbFeed = {
25
+ thumbs: Tensor;
26
+ has_img: Tensor;
27
+ };
28
+ /**
29
+ * The line thumbnails of an order model that reads them, from the page image
30
+ * at `imgBoxes` (the boxes on the page as it is; the order model's boxes are
31
+ * mirrored on a right-to-left page); without the image the lines have none
32
+ * (has_img 0).
33
+ */
34
+ export declare function thumbFeed(Tensor: TensorCtor, ops: ImageOps, spec: ThumbSpec, n: number, gray: Gray | undefined, imgBoxes: readonly Box[]): ThumbFeed;
@@ -0,0 +1 @@
1
+ import{pyRound}from"./det-post.js";import{inputShape}from"./util.js";let THUMB_H=16;let THUMB_W=64;let THUMB_CTX=0.25;export function thumbSpec(order,interp){if(!order.inputNames.includes("thumbs"))return;let shape=inputShape(order,"thumbs")??[];let h=shape.at(-2);let w=shape.at(-1);return typeof h==="number"&&typeof w==="number"?{height:h,width:w,interp:interp??"area"}:{height:THUMB_H,width:THUMB_W,interp:interp??"area"}}export function lineThumbs(gray,boxes,{height:th,width:tw,interp},ops){let out=new Float32Array(boxes.length*th*tw);const{width:W,height:H}=gray;for(const[i,[x0,y0,x1,y1]]of boxes.entries()){let h=Math.max(2,y1-y0);let a=Math.trunc(Math.max(0,y0-THUMB_CTX*h));let z=Math.trunc(Math.min(H,y1+THUMB_CTX*h));let c=Math.trunc(Math.max(0,x0));let d=Math.trunc(Math.min(W,x1));if(z-a<2||d-c<1)continue;let crop=new Uint8Array((z-a)*(d-c));for(let y=a;y<z;y++){crop.set(gray.data.subarray(y*W+c,y*W+d),(y-a)*(d-c))}let w=Math.max(1,Math.min(tw,pyRound((d-c)*th/(z-a))));let r=ops.resize({data:crop,width:d-c,height:z-a},w,th,interp);for(let y=0;y<th;y++){for(let x=0;x<w;x++){out[(i*th+y)*tw+x]=(255-(r.data[y*w+x]??0))/255}}}return out}export function thumbFeed(Tensor,ops,spec,n,gray,imgBoxes){const{height:th,width:tw}=spec;let thumbs=gray?lineThumbs(gray,imgBoxes,spec,ops):new Float32Array(n*th*tw);return{thumbs:new Tensor("float32",thumbs,[1,n,1,th,tw]),has_img:new Tensor("float32",new Float32Array(n).fill(gray?1:0),[1,n])}}
package/indra/lines.d.ts CHANGED
@@ -12,7 +12,7 @@ export declare function gutterCuts(vocab: Vocab, boxes: readonly Box[], rec: rea
12
12
  export declare function isSpace(vocab: Vocab, tok: number | string): boolean;
13
13
  /**
14
14
  * Text of tokens: class ids from the main recognizer, characters from a group
15
- * recognizer or math (two fields), or text-layer characters (three fields).
15
+ * recognizer or math (no content index), or text-layer characters (with one).
16
16
  * A group recognizer reads in visual order: its right-to-left text is turned
17
17
  * into logical order, by the page direction when `pageRtl` is set.
18
18
  */
package/indra/lines.js CHANGED
@@ -1 +1 @@
1
- import{flip,hasRtl}from"./rtl.js";import{item}from"./util.js";let PY_WHITESPACE=/(?:[^\S\ufeff]|[\x1c-\x1f\x85])+/u;export let SPLIT_GAP=3;export let CELL_GAP=1.8;let GUTTER_GAP=1.6;let GUTTER_EDGES=3;export function gutterCuts(vocab,boxes,rec){let f=Math.fround;return boxes.map((b,i)=>{let h=Math.max(1,f(b[3]-b[1]));let xs=item(rec,i).toks.filter((tk)=>!isSpace(vocab,tk[0])).map((tk)=>tk[1]);let mine=[];for(let k=1;k<xs.length;k++){let a=item(xs,k-1);let c=item(xs,k);if(c-a<=GUTTER_GAP*h)continue;let gl=f(a+0.35*h);let gr=f(c-0.35*h);let tol=f(0.5*h);let near=0;for(const[j,o]of boxes.entries()){if(j!==i&&(Math.abs(f(o[2]-gl))<tol||Math.abs(f(o[0]-gr))<tol))near++}if(near>=GUTTER_EDGES)mine.push((a+c)/2)}return mine})}export function isSpace(vocab,tok){return tok===" "||tok===vocab.index.get(" ")}export function decodeToks(vocab,toks,pageRtl=false){if(!toks.length)return vocab.decode([]);let first=item(toks,0);if(typeof first[0]==="string"){let text=toks.map((tk)=>String(tk[0])).join("").split(PY_WHITESPACE).filter(Boolean).join(" ");if(first.length===2){text=text.normalize("NFC");if(hasRtl(text))text=flip(text,true,pageRtl||null)}return text}return vocab.decode(toks.map((tk)=>Number(tk[0])))}export function splitLine(vocab,box,toks,gap,at=[],pageRtl=false){let h=Math.max(1,Math.fround(box[3]-box[1]));let cutsAt=at.toSorted((p,q)=>p-q);let segs=[[]];let prev;for(let tk of toks){let x=tk[1];if(!isSpace(vocab,tk[0])){if(prev!==undefined&&(x-prev>gap*h||cutsAt.some((c)=>prev!==undefined&&prev<c&&c<x))){segs.push([])}prev=x}segs.at(-1)?.push(tk)}if(segs.length===1)return[{box,text:decodeToks(vocab,toks,pageRtl),toks}];let out=[];for(let sg of segs){let text=decodeToks(vocab,sg,pageRtl).trim();let xs=sg.filter((tk)=>!isSpace(vocab,tk[0])).map((tk)=>tk[1]);if(text&&xs.length){out.push({box:[Math.max(box[0],Math.min(...xs)-0.35*h),box[1],Math.min(box[2],Math.max(...xs)+0.35*h),box[3]],text,toks:sg})}}return out}
1
+ import{flip,hasRtl}from"./rtl.js";import{item}from"./util.js";let PY_WHITESPACE=/(?:[^\S\ufeff]|[\x1c-\x1f\x85])+/u;export let SPLIT_GAP=3;export let CELL_GAP=1.8;let GUTTER_GAP=1.6;let GUTTER_EDGES=3;export function gutterCuts(vocab,boxes,rec){let f=Math.fround;return boxes.map((b,i)=>{let h=Math.max(1,f(b[3]-b[1]));let xs=item(rec,i).toks.filter((tk)=>!isSpace(vocab,tk[0])).map((tk)=>tk[1]);let mine=[];for(let k=1;k<xs.length;k++){let a=item(xs,k-1);let c=item(xs,k);if(c-a<=GUTTER_GAP*h)continue;let gl=f(a+0.35*h);let gr=f(c-0.35*h);let tol=f(0.5*h);let near=0;for(const[j,o]of boxes.entries()){if(j!==i&&(Math.abs(f(o[2]-gl))<tol||Math.abs(f(o[0]-gr))<tol))near++}if(near>=GUTTER_EDGES)mine.push((a+c)/2)}return mine})}export function isSpace(vocab,tok){return tok===" "||tok===vocab.index.get(" ")}export function decodeToks(vocab,toks,pageRtl=false){if(!toks.length)return vocab.decode([]);let first=item(toks,0);if(typeof first[0]==="string"){let forms=[];let text=toks.map((tk)=>{if(tk[3]?.kind!=="formula")return String(tk[0]);forms.push(String(tk[0]));return String.fromCharCode(57344+forms.length-1)}).join("").split(PY_WHITESPACE).filter(Boolean).join(" ");if(first[2]===undefined){text=text.normalize("NFC");if(hasRtl(text))text=flip(text,true,pageRtl||null)}for(const[i,form]of forms.entries()){text=text.replaceAll(String.fromCharCode(57344+i),form)}return text}return vocab.decode(toks.map((tk)=>Number(tk[0])))}export function splitLine(vocab,box,toks,gap,at=[],pageRtl=false){let h=Math.max(1,Math.fround(box[3]-box[1]));let cutsAt=at.toSorted((p,q)=>p-q);let segs=[[]];let prev;for(let tk of toks){let x=tk[1];if(!isSpace(vocab,tk[0])){if(prev!==undefined&&(x-prev>gap*h||cutsAt.some((c)=>prev!==undefined&&prev<c&&c<x))){segs.push([])}prev=x}segs.at(-1)?.push(tk)}if(segs.length===1)return[{box,text:decodeToks(vocab,toks,pageRtl),toks}];let out=[];for(let sg of segs){let text=decodeToks(vocab,sg,pageRtl).trim();let xs=sg.filter((tk)=>!isSpace(vocab,tk[0])).map((tk)=>tk[1]);if(text&&xs.length){out.push({box:[Math.max(box[0],Math.min(...xs)-0.35*h),box[1],Math.min(box[2],Math.max(...xs)+0.35*h),box[3]],text,toks:sg})}}return out}
@@ -0,0 +1,16 @@
1
+ import type { InferenceSession, Tensor } from "onnxruntime-common";
2
+ import type { TensorCtor } from "./types.js";
3
+ /** Only the inputs a graph declares: exports drop unused ones (init does not read the mask). */
4
+ export declare function declared(sess: InferenceSession, feeds: Record<string, Tensor>): Record<string, Tensor>;
5
+ /**
6
+ * `t` with only the rows `rows` along `axis` (the batch axis), as numpy's
7
+ * `x[rows]` / `x[:, rows]`: finished lines leave the decoding batch.
8
+ */
9
+ export declare function takeRows(Tensor: TensorCtor, t: Tensor, rows: readonly number[], axis: number): Tensor;
10
+ /** A LaTeX command token: a backslash and a letter. */
11
+ export declare function isCommand(t: string): boolean;
12
+ /** Per row: the argmax token and its softmax probability, in float32 as numpy computes it. */
13
+ export declare function topTokens(logits: Float32Array, rows: number, n: number): {
14
+ id: number;
15
+ top: number;
16
+ }[];
@@ -0,0 +1 @@
1
+ import{sumF32}from"./numeric.js";import{floats}from"./util.js";export function declared(sess,feeds){return Object.fromEntries(Object.entries(feeds).filter(([k])=>sess.inputNames.includes(k)))}export function takeRows(Tensor,t,rows,axis){let dims=[...t.dims];let outer=dims.slice(0,axis).reduce((a,b)=>a*b,1);let n=dims[axis]??0;let inner=dims.slice(axis+1).reduce((a,b)=>a*b,1);dims[axis]=rows.length;if(t.type==="float32"){let src=floats(t);let out=new Float32Array(outer*rows.length*inner);for(let o=0;o<outer;o++){for(const[r,row]of rows.entries()){let from=(o*n+row)*inner;out.set(src.subarray(from,from+inner),(o*rows.length+r)*inner)}}return new Tensor("float32",out,dims)}if(t.type==="bool"){let src=t.data;let out=new Uint8Array(outer*rows.length*inner);for(let o=0;o<outer;o++){for(const[r,row]of rows.entries()){let from=(o*n+row)*inner;out.set(src.subarray(from,from+inner),(o*rows.length+r)*inner)}}return new Tensor("bool",out,dims)}throw new Error(`cannot take rows of a ${t.type} tensor`)}let LETTER=/^\p{L}$/u;export function isCommand(t){return t.length>1&&t[0]==="\\"&&LETTER.test(t[1]??"")}export function topTokens(logits,rows,n){let f=Math.fround;return Array.from({length:rows},(_,b)=>{let row=logits.subarray(b*n,(b+1)*n);let id=0;for(let j=1;j<n;j++)if((row[j]??0)>(row[id]??0))id=j;let max=row[id]??0;let e=row.map((v)=>f(Math.exp(f(v-max))));return{id,top:f(1/sumF32(e))}})}
@@ -0,0 +1,61 @@
1
+ import type { InferenceSession } from "onnxruntime-common";
2
+ import type { FloatImage } from "./image.js";
3
+ import type { Box } from "./rec-preproc.js";
4
+ import type { TensorCtor, Tok } from "./types.js";
5
+ /**
6
+ * Inline math inside lines that MathRec does not read whole. A Cyrillic,
7
+ * Korean, Arabic or Devanagari line with inline math stays with its script
8
+ * recognizer, which reads the formula as plain characters. A small image
9
+ * tagger marks the columns of such a line that hold math; MathRec reads each
10
+ * marked run's crop, and a confident reading replaces the characters that the
11
+ * recognizer read there.
12
+ */
13
+ /** `math_span_img.json`. */
14
+ export type SpanImgMeta = {
15
+ height: number;
16
+ stride: number;
17
+ threshold?: number;
18
+ /** A shorter run is noise. */
19
+ min_cols?: number;
20
+ /** A shorter gap joins two runs. */
21
+ merge_cols?: number;
22
+ /**
23
+ * A confident reading without structure ("$a = 0$") also replaces the run:
24
+ * the script recognizer reads Latin letters as its own look-alikes.
25
+ */
26
+ accept_plain?: boolean;
27
+ };
28
+ /** A run of crop pixel columns [a, b). */
29
+ export type ColumnRun = readonly [a: number, b: number];
30
+ /** The image tagger of math columns (math_span_img.onnx). */
31
+ export declare class SpanImgTagger {
32
+ private readonly Tensor;
33
+ private readonly sess;
34
+ readonly height: number;
35
+ readonly acceptPlain: boolean;
36
+ private readonly stride;
37
+ private readonly threshold;
38
+ private readonly minCols;
39
+ private readonly mergeCols;
40
+ constructor(Tensor: TensorCtor, sess: InferenceSession, meta: SpanImgMeta);
41
+ /** Column runs [a, b) at or above the threshold, short gaps joined. */
42
+ runs(prob: ArrayLike<number>, n: number): ColumnRun[];
43
+ /** Per ink map [height, W]: column runs that hold math, in crop pixels. */
44
+ spans(crops: readonly FloatImage[], batch?: number): Promise<ColumnRun[][]>;
45
+ }
46
+ /** Crop pixel columns -> page x (the crop's padding and scale, as the recognizer's character positions). */
47
+ export declare function pageX([x0, y0, x1, y1]: Box, cropW: number, [a, b]: ColumnRun): [number, number];
48
+ /** Whether a token is the formula of a splice. */
49
+ export declare function isFormula(t: Tok): boolean;
50
+ /**
51
+ * The line's (char, x) tokens with those inside [x0, x1] replaced by one
52
+ * formula token; a space token on each side keeps the formula a word. Each
53
+ * replaced character stays as an empty token at its x: the gaps between
54
+ * characters (cell and column cuts) are the same as before.
55
+ */
56
+ export declare function splice(toks: readonly Tok[], x0: number, x1: number, latex: string): Tok[];
57
+ /**
58
+ * The tokens as the recognizer read them, before any splice (the table model
59
+ * reads words and their characters: a formula word changes its structure).
60
+ */
61
+ export declare function unspliced(toks: readonly Tok[]): readonly Tok[];
@@ -0,0 +1 @@
1
+ export class SpanImgTagger{Tensor;sess;height;acceptPlain;stride;threshold;minCols;mergeCols;constructor(Tensor,sess,meta){this.Tensor=Tensor;this.sess=sess;this.height=meta.height;this.stride=meta.stride;this.threshold=meta.threshold??0.5;this.minCols=meta.min_cols??2;this.mergeCols=meta.merge_cols??1;this.acceptPlain=meta.accept_plain??false}runs(prob,n){let out=[];let a;for(let i=0;i<=n;i++){let p=i<n?prob[i]??0:0;if(p>=this.threshold&&a===undefined){a=i}else if(p<this.threshold&&a!==undefined){let last=out.at(-1);if(last&&a-last[1]<=this.mergeCols)last[1]=i;else out.push([a,i]);a=undefined}}return out.filter(([x,y])=>y-x>=this.minCols)}async spans(crops,batch=64){let out=crops.map(()=>[]);for(let idx of widthBatches(crops.map((c)=>c.width),batch)){const{data,dims,widths}=padBatch(idx.map((j)=>item(crops,j)));let res=await this.sess.run({x:new this.Tensor("float32",data,dims),widths:new this.Tensor("int64",widths,[idx.length])});let prob=output(res,"prob");let c=prob.dims[1]??0;let p=floats(prob);for(const[k,j]of idx.entries()){let n=Math.floor(item(crops,j).width/this.stride);let row=p.subarray(k*c,k*c+Math.min(n,c));out[j]=this.runs(row,row.length).map(([a,b])=>[a*this.stride,b*this.stride])}}return out}}import{PAD_X,padBatch,widthBatches}from"./rec-preproc.js";import{floats,item,output}from"./util.js";export function pageX([x0,y0,x1,y1],cropW,[a,b]){let h=Math.max(1,y1-y0);let ix0=Math.floor(x0-PAD_X*h);let f=(Math.ceil(x1+PAD_X*h)-ix0)/cropW;return[ix0+a*f,ix0+b*f]}export function isFormula(t){return t[3]?.kind==="formula"}export function splice(toks,x0,x1,latex){let xc=(x0+x1)/2;let left=toks.filter((t)=>t[1]<x0);let right=toks.filter((t)=>t[1]>x1);let inside=toks.filter((t)=>x0<=t[1]&&t[1]<=x1);let pad=(s,x)=>[s,x,undefined,{kind:"pad"}];let held=inside.filter((t)=>t[0]!==" ").map((t)=>pad("",t[1]));let middle=[...held,[latex,xc,undefined,{kind:"formula",held:inside}]].toSorted((a,b)=>a[1]-b[1]);let mid=[pad(" ",x0),...middle,pad(" ",x1)];if(left.at(-1)?.[0]===" ")mid=mid.slice(1);if(right[0]?.[0]===" ")mid=mid.slice(0,-1);return[...left,...mid,...right]}export function unspliced(toks){if(!toks.some(isFormula))return toks;let out=toks.filter((t)=>t[3]===undefined);for(let t of toks)if(t[3]?.kind==="formula")out.push(...t[3].held);return out.toSorted((a,b)=>a[1]-b[1])}