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
@@ -1 +1 @@
1
- import{pyRound}from"./det-post.js";import{inkOf}from"./image.js";import{item}from"./util.js";export let LINE_HEIGHT=32;export let PAD_Y=0.2;export let PAD_X=0.3;let WIDTH_MULTIPLE=8;function percentiles(gray,x0,y0,x1,y1,qs=[0.02,0.5,0.98]){let cum=new Float64Array(256);for(let y=y0;y<y1;y++){for(let x=x0;x<x1;x++)cum[gray.data[y*gray.width+x]??0]++}for(let v=1;v<256;v++)cum[v]=(cum[v]??0)+(cum[v-1]??0);let n=(x1-x0)*(y1-y0);let above=(i)=>{let v=0;while(v<256&&(cum[v]??0)<=i)v++;return v};return qs.map((q)=>{let x=q*(n-1);let i=Math.floor(x);let g=x-i;let lo=above(i);let hi=above(Math.min(i+1,n-1));let d=hi-lo;return g>=0.5?hi-d*(1-g):lo+d*g})}export function isDarkLine(gray,box){const[x0,y0,x1,y1]=box;let bx0=Math.max(0,Math.trunc(x0));let by0=Math.max(0,Math.trunc(y0));let bx1=Math.min(gray.width,Math.trunc(x1)+1);let by1=Math.min(gray.height,Math.trunc(y1)+1);if(bx1<=bx0||by1<=by0)return false;const[lo=0,med=0,hi=0]=percentiles(gray,bx0,by0,bx1,by1);return hi-med>2*(med-lo)+8}export function cropLine(gray,box,height,ops,maxWidth=4096,window=1,dark){let padY=(window*(1+2*PAD_Y)-1)/2;let outH=height*window;const[x0,y0,x1,y1]=box;let h=Math.max(1,y1-y0);let ix0=Math.floor(x0-PAD_X*h);let iy0=Math.floor(y0-padY*h);let ix1=Math.ceil(x1+PAD_X*h);let iy1=Math.ceil(y1+padY*h);let cw=Math.max(1,ix1-ix0);let ch=Math.max(1,iy1-iy0);let isDark=dark??isDarkLine(gray,box);let crop=new Uint8Array(cw*ch).fill(isDark?0:255);let sx0=Math.max(0,ix0);let sy0=Math.max(0,iy0);let sx1=Math.min(gray.width,ix1);let sy1=Math.min(gray.height,iy1);if(sx1>sx0&&sy1>sy0){for(let y=sy0;y<sy1;y++){let row=gray.data.subarray(y*gray.width+sx0,y*gray.width+sx1);crop.set(row,(y-iy0)*cw+(sx0-ix0))}}let outW=Math.max(WIDTH_MULTIPLE,Math.min(maxWidth,pyRound(cw*outH/ch)));let resized=ops.resize({data:crop,width:cw,height:ch},outW,outH,ch>outH?"area":"linear");return isDark?paperOf(resized):inkOf(resized)}function paperOf(img){let data=new Float32Array(img.data.length);for(let i=0;i<data.length;i++)data[i]=Math.fround((img.data[i]??0)/255);return{data,width:img.width,height:img.height}}export function padBatch(lines){let h=item(lines,0).height;let wm=Math.ceil(Math.max(...lines.map((l)=>l.width))/WIDTH_MULTIPLE)*WIDTH_MULTIPLE;let data=new Float32Array(lines.length*h*wm);let widths=new BigInt64Array(lines.length);for(const[i,line]of lines.entries()){for(let y=0;y<h;y++){data.set(line.data.subarray(y*line.width,(y+1)*line.width),(i*h+y)*wm)}widths[i]=BigInt(line.width)}return{data,dims:[lines.length,1,h,wm],widths}}export function widthBatches(widths,maxBatch=64,maxRatio=1.3,minWidth=64,maxArea=64*640){let order=widths.map((_,i)=>i).toSorted((a,b)=>item(widths,a)-item(widths,b));let batches=[];for(let i of order){let last=batches.at(-1);let wi=Math.max(item(widths,i),minWidth);if(last&&last.length<maxBatch&&wi<=maxRatio*Math.max(item(widths,item(last,0)),minWidth)&&(last.length+1)*wi<=maxArea){last.push(i)}else{batches.push([i])}}return batches}
1
+ import{pyRound}from"./det-post.js";import{inkOf}from"./image.js";import{item}from"./util.js";export let LINE_HEIGHT=32;export let PAD_Y=0.2;export let PAD_X=0.3;let WIDTH_MULTIPLE=8;function percentiles(gray,x0,y0,x1,y1,qs=[0.02,0.5,0.98]){let cum=new Float64Array(256);for(let y=y0;y<y1;y++){for(let x=x0;x<x1;x++)cum[gray.data[y*gray.width+x]??0]++}for(let v=1;v<256;v++)cum[v]=(cum[v]??0)+(cum[v-1]??0);let n=(x1-x0)*(y1-y0);let above=(i)=>{let v=0;while(v<256&&(cum[v]??0)<=i)v++;return v};return qs.map((q)=>{let x=q*(n-1);let i=Math.floor(x);let g=x-i;let lo=above(i);let hi=above(Math.min(i+1,n-1));let d=hi-lo;return g>=0.5?hi-d*(1-g):lo+d*g})}export function isDarkLine(gray,box){const[x0,y0,x1,y1]=box;let bx0=Math.max(0,Math.trunc(x0));let by0=Math.max(0,Math.trunc(y0));let bx1=Math.min(gray.width,Math.trunc(x1)+1);let by1=Math.min(gray.height,Math.trunc(y1)+1);if(bx1<=bx0||by1<=by0)return false;const[lo=0,med=0,hi=0]=percentiles(gray,bx0,by0,bx1,by1);return hi-med>2*(med-lo)+8}export function cropLine(gray,box,height,ops,maxWidth=4096,window=1,dark){let padY=(window*(1+2*PAD_Y)-1)/2;let outH=height*window;const[x0,y0,x1,y1]=box;let h=Math.max(1,y1-y0);let ix0=Math.floor(x0-PAD_X*h);let iy0=Math.floor(y0-padY*h);let ix1=Math.ceil(x1+PAD_X*h);let iy1=Math.ceil(y1+padY*h);let cw=Math.max(1,ix1-ix0);let ch=Math.max(1,iy1-iy0);let isDark=dark??isDarkLine(gray,box);let crop=new Uint8Array(cw*ch).fill(isDark?0:255);let sx0=Math.max(0,ix0);let sy0=Math.max(0,iy0);let sx1=Math.min(gray.width,ix1);let sy1=Math.min(gray.height,iy1);if(sx1>sx0&&sy1>sy0){for(let y=sy0;y<sy1;y++){let row=gray.data.subarray(y*gray.width+sx0,y*gray.width+sx1);crop.set(row,(y-iy0)*cw+(sx0-ix0))}}let outW=Math.max(WIDTH_MULTIPLE,Math.min(maxWidth,pyRound(cw*outH/ch)));let resized=ops.resize({data:crop,width:cw,height:ch},outW,outH,ch>outH?"area":"linear");return isDark?paperOf(resized):inkOf(resized)}function paperOf(img){let data=new Float32Array(img.data.length);for(let i=0;i<data.length;i++)data[i]=Math.fround((img.data[i]??0)/255);return{data,width:img.width,height:img.height}}let MIN_BATCH_WIDTH=32;export function padBatch(lines){let h=item(lines,0).height;let wm=Math.ceil(Math.max(...lines.map((l)=>l.width),MIN_BATCH_WIDTH)/WIDTH_MULTIPLE)*WIDTH_MULTIPLE;let data=new Float32Array(lines.length*h*wm);let widths=new BigInt64Array(lines.length);for(const[i,line]of lines.entries()){for(let y=0;y<h;y++){data.set(line.data.subarray(y*line.width,(y+1)*line.width),(i*h+y)*wm)}widths[i]=BigInt(line.width)}return{data,dims:[lines.length,1,h,wm],widths}}export function widen(lines,xscale,ops){if(xscale===1)return[...lines];return lines.map((x)=>ops.resizeFloat(x,Math.max(WIDTH_MULTIPLE,pyRound(x.width*xscale)),x.height))}export function widthBatches(widths,maxBatch=64,maxRatio=1.3,minWidth=64,maxArea=64*640){let order=widths.map((_,i)=>i).toSorted((a,b)=>item(widths,a)-item(widths,b));let batches=[];for(let i of order){let last=batches.at(-1);let wi=Math.max(item(widths,i),minWidth);if(last&&last.length<maxBatch&&wi<=maxRatio*Math.max(item(widths,item(last,0)),minWidth)&&(last.length+1)*wi<=maxArea){last.push(i)}else{batches.push([i])}}return batches}
@@ -1,5 +1,5 @@
1
1
  import type { InferenceSession } from "onnxruntime-common";
2
- import type { FloatImage, Gray } from "./image.js";
2
+ import type { FloatImage, Gray, ImageOps } from "./image.js";
3
3
  import type { NgramLM } from "./lm.js";
4
4
  import type { MathReader } from "./math.js";
5
5
  import type { Box } from "./rec-preproc.js";
@@ -29,17 +29,24 @@ export type RecGroup = {
29
29
  sel: number[];
30
30
  asChars: boolean;
31
31
  lm?: LmUse;
32
+ /** The recognizer reads lines widened by this factor (meta.json `rec_xscale_<group>`). */
33
+ xscale: number;
32
34
  };
33
35
  export declare const LM_BEAM = 8;
34
36
  /** A class under this probability at a step is not tried by the beam search. */
35
37
  export declare const LM_CAND_FLOOR = 0.003;
38
+ /** Whether a recognizer ends at its logits, not at the CTC outputs. */
39
+ export declare function hasLogits(sess: InferenceSession): boolean;
40
+ /** Whether a recognizer gives what the beam search reads: top-k outputs or logits. */
41
+ export declare function lmReady(sess: InferenceSession): boolean;
36
42
  /**
37
43
  * One recognizer batch: text, confidence and character positions per crop.
38
44
  * `crops` are the recognizer inputs (a tall window for rec.onnx when its
39
- * meta says so); `bands` are the line-band crops that map CTC steps back to
40
- * page x, as the reference does for both.
45
+ * meta says so), already widened by the group's x scale; `bands` are the
46
+ * line-band crops that map CTC steps back to page x, as the reference does
47
+ * for both.
41
48
  */
42
- export declare function recognizeBatch(Tensor: TensorCtor, { sess, vocab, asChars, lm }: RecGroup, crops: readonly FloatImage[], bands: readonly FloatImage[], boxes: readonly Box[]): Promise<RecLine[]>;
49
+ export declare function recognizeBatch(Tensor: TensorCtor, { sess, vocab, asChars, lm, xscale }: RecGroup, crops: readonly FloatImage[], bands: readonly FloatImage[], boxes: readonly Box[]): Promise<RecLine[]>;
43
50
  /** Recognizer groups in script.onnx's class order, unless meta.json names them. */
44
51
  export declare const GROUPS: readonly ["base", "cjk", "rtl", "other"];
45
52
  /**
@@ -60,8 +67,12 @@ export type LineGroups = {
60
67
  */
61
68
  export declare function lineGroups(Tensor: TensorCtor, script: InferenceSession, crops: readonly FloatImage[], order: readonly string[], known: ReadonlySet<string>, batch?: number): Promise<LineGroups>;
62
69
  /**
63
- * Lines the math classifier flags are read by the math reader. A reading
64
- * replaces the line only when it holds math and is confident; one token
65
- * holds the whole line, so it is never split.
70
+ * Lines the math classifier flags are read by the math reader. MathRec reads
71
+ * a line whose reading is mostly Latin (a formula line may have gone to a
72
+ * group recognizer: Greek letters to rec_world), or one whose letters its own
73
+ * vocabulary writes; any other line keeps its reading. A reading replaces the
74
+ * line only when the accept rules take it, with the recognizer's accents in
75
+ * its prose; one token holds the whole line, so it is never split. The other
76
+ * lines get their inline formulas (readSpanImg) unless the page is vertical.
66
77
  */
67
- export declare function readMath(math: MathReader, gray: Gray, boxes: readonly Box[], crops: readonly FloatImage[], out: RecLine[]): Promise<void>;
78
+ export declare function readMath(math: MathReader, gray: Gray, boxes: readonly Box[], crops: readonly FloatImage[], out: RecLine[], vertical: boolean, ops: ImageOps, vocab: Vocab): Promise<void>;
@@ -1 +1 @@
1
- import{beamSearch}from"./lm.js";import{MATH_MIN_CONF}from"./math.js";import{meanF32}from"./numeric.js";import{PAD_X,padBatch,widthBatches}from"./rec-preproc.js";import{floats,ints,item,output}from"./util.js";export let MIN_CONF=0.5;export let LM_BEAM=8;export let LM_CAND_FLOOR=0.003;let OUT_GREEDY=["ids","conf","lengths"];let OUT_LM=["blank","topv","topi"];export async function recognizeBatch(Tensor,{sess,vocab,asChars,lm},crops,bands,boxes){const{data,dims,widths}=padBatch(crops);let res=await sess.run({x:new Tensor("float32",data,dims),widths:new Tensor("int64",widths,[crops.length])},lm?[...OUT_GREEDY,...OUT_LM]:OUT_GREEDY);let ids=output(res,"ids");let best=ints(ids);let pmax=floats(output(res,"conf"));let lengths=ints(output(res,"lengths"));let steps=ids.dims[1]??0;let stride=dims[3]/Math.max(steps,1);let out=[];for(const[k,band]of bands.entries()){let n=item(lengths,k);let seq=best.slice(k*steps,k*steps+n);let kept=[];for(let t=0;t<n;t++){if(seq[t]!==0&&(t===0||seq[t]!==seq[t-1]))kept.push(t)}let keptIds=kept.map((t)=>item(seq,t));let conf=kept.length?meanF32(kept.map((t)=>pmax[k*steps+t]??0)):0;if(lm&&MIN_CONF<=conf&&conf<lm.gate){let topv=output(res,"topv");let K=topv.dims[2]??0;let read=beamSearch(floats(output(res,"blank")).subarray(k*steps,k*steps+n),floats(topv).subarray(k*steps*K,(k*steps+n)*K),topIds(output(res,"topi")).subarray(k*steps*K,(k*steps+n)*K),n,K,await lm.lm(),lm.alpha,lm.beta,LM_BEAM,0.999,LM_CAND_FLOOR);keptIds=read.ids;kept=read.steps}const[x0,y0,x1,y1]=item(boxes,k);let h=Math.max(1,y1-y0);let ix0=Math.floor(x0-PAD_X*h);let f=(Math.ceil(x1+PAD_X*h)-ix0)/band.width;let toks=kept.map((t,i)=>{let x=ix0+(t+0.5)*stride*f;let id=item(keptIds,i);return asChars?[item(vocab.chars,id-1),x]:[id,x]});out.push(conf>=MIN_CONF?{text:vocab.decode(keptIds),conf,toks}:{text:"",conf,toks:[]})}return out}function topIds(t){if(t.type!=="int64")throw new Error(`expected an int64 tensor, got ${t.type}`);return t.data}export let GROUPS=["base","cjk","rtl","other"];export let ROUTE_SURE=0.95;export async function lineGroups(Tensor,script,crops,order,known,batch=64){let names=crops.map(()=>"base");let sure=crops.map(()=>true);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 script.run({x:new Tensor("float32",data,dims),widths:new Tensor("int64",widths,[idx.length])});let out=output(res,"p");let p=floats(out);let c=out.dims.length===1?1:out.dims[1]??1;for(const[k,j]of idx.entries()){let g;let pk;if(out.dims.length===1){let v=p[k]??0;g=v>0.5?"cjk":"base";pk=Math.max(v,1-v)}else{let a=0;for(let i=1;i<c;i++)if((p[k*c+i]??0)>(p[k*c+a]??0))a=i;g=order[a]??"base";pk=p[k*c+a]??0}names[j]=known.has(g)?g:"base";sure[j]=pk>ROUTE_SURE}}return{names,sure}}export async function readMath(math,gray,boxes,crops,out){let idx=(await math.flags(crops)).flatMap((flag,j)=>flag?[j]:[]);if(!idx.length)return;let readings=await math.read(gray,idx.map((j)=>item(boxes,j)));for(const[k,j]of idx.entries()){const{text,conf}=item(readings,k);if(!text.includes("$")||conf<MATH_MIN_CONF)continue;const[x0,,x1]=item(boxes,j);out[j]={text,conf:1,toks:[[text,Math.fround(x0+x1)/2]]}}}
1
+ import{lmInputs,peakProb}from"./ctc.js";import{beamSearch}from"./lm.js";import{pageX,splice}from"./math-span-img.js";import{MATH_MIN_CONF,hasMath,latinLine}from"./math-text.js";import{isAlpha,pyStrip}from"./py-unicode.js";import{meanF32}from"./numeric.js";import{PAD_X,cropLine,padBatch,widthBatches}from"./rec-preproc.js";import{floats,ints,item,output}from"./util.js";export let MIN_CONF=0.5;export let LM_BEAM=8;export let LM_CAND_FLOOR=0.003;let OUT_GREEDY=["ids","conf","lengths"];let OUT_LM=["blank","topv","topi"];let OUT_LOGITS=["ids","lengths","logits"];export function hasLogits(sess){return sess.outputNames.includes("logits")}export function lmReady(sess){return OUT_LM.every((o)=>sess.outputNames.includes(o))||hasLogits(sess)}export async function recognizeBatch(Tensor,{sess,vocab,asChars,lm,xscale},crops,bands,boxes){const{data,dims,widths}=padBatch(crops);let logitsOut=hasLogits(sess);let fetch=lm?[...OUT_GREEDY,...OUT_LM]:OUT_GREEDY;if(logitsOut)fetch=OUT_LOGITS;let res=await sess.run({x:new Tensor("float32",data,dims),widths:new Tensor("int64",widths,[crops.length])},fetch);let ids=output(res,"ids");let best=ints(ids);let lengths=ints(output(res,"lengths"));let steps=ids.dims[1]??0;let logits=logitsOut?output(res,"logits"):undefined;let v=logits?.dims[2]??0;let pmax=logits?undefined:floats(output(res,"conf"));let stride=dims[3]/Math.max(steps,1);let out=[];for(const[k,band]of bands.entries()){let n=item(lengths,k);let seq=best.slice(k*steps,k*steps+n);let kept=[];for(let t=0;t<n;t++){if(seq[t]!==0&&(t===0||seq[t]!==seq[t-1]))kept.push(t)}let keptIds=kept.map((t)=>item(seq,t));let peaks=logits?peakProb(floats(logits),v,kept.map((t)=>k*steps+t)):kept.map((t)=>pmax?.[k*steps+t]??0);let conf=kept.length?meanF32(peaks):0;if(lm&&MIN_CONF<=conf&&conf<lm.gate){let input=logits?lmInputs(floats(logits),k*steps*v,n,v,LM_CAND_FLOOR):topK(res,k,steps,n);let read=beamSearch(input.blank,input.topv,input.topi,n,input.k,await lm.lm(),lm.alpha,lm.beta,LM_BEAM,0.999,LM_CAND_FLOOR);keptIds=read.ids;kept=read.steps}const[x0,y0,x1,y1]=item(boxes,k);let h=Math.max(1,y1-y0);let ix0=Math.floor(x0-PAD_X*h);let f=(Math.ceil(x1+PAD_X*h)-ix0)/(band.width*xscale);let toks=kept.map((t,i)=>{let x=ix0+(t+0.5)*stride*f;let id=item(keptIds,i);return asChars?[item(vocab.chars,id-1),x]:[id,x]});out.push(conf>=MIN_CONF?{text:vocab.decode(keptIds),conf,toks}:{text:"",conf,toks:[]})}return out}function topK(res,k,steps,n){let topv=output(res,"topv");let K=topv.dims[2]??0;return{blank:floats(output(res,"blank")).subarray(k*steps,k*steps+n),topv:floats(topv).subarray(k*steps*K,(k*steps+n)*K),topi:topIds(output(res,"topi")).subarray(k*steps*K,(k*steps+n)*K),k:K}}function topIds(t){if(t.type!=="int64")throw new Error(`expected an int64 tensor, got ${t.type}`);return t.data}export let GROUPS=["base","cjk","rtl","other"];export let ROUTE_SURE=0.95;export async function lineGroups(Tensor,script,crops,order,known,batch=64){let names=crops.map(()=>"base");let sure=crops.map(()=>true);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 script.run({x:new Tensor("float32",data,dims),widths:new Tensor("int64",widths,[idx.length])});let out=output(res,"p");let p=floats(out);let c=out.dims.length===1?1:out.dims[1]??1;for(const[k,j]of idx.entries()){let g;let pk;if(out.dims.length===1){let v=p[k]??0;g=v>0.5?"cjk":"base";pk=Math.max(v,1-v)}else{let a=0;for(let i=1;i<c;i++)if((p[k*c+i]??0)>(p[k*c+a]??0))a=i;g=order[a]??"base";pk=p[k*c+a]??0}names[j]=known.has(g)?g:"base";sure[j]=pk>ROUTE_SURE}}return{names,sure}}export async function readMath(math,gray,boxes,crops,out,vertical,ops,vocab){let cand=out.flatMap((r,j)=>latinLine(r.text)||math.writes(r.text)?[j]:[]);const{flags,probs}=cand.length?await math.flags(cand.map((j)=>item(crops,j))):{flags:[],probs:[]};let idx=cand.filter((_,n)=>flags[n]);if(idx.length&&math.hasGate){let keep=math.gate(probs.filter((_,n)=>flags[n]),idx.map((j)=>item(out,j).text),cand.length,"ocr");idx=idx.filter((_,n)=>keep[n])}if(idx.length){let readings=await math.read(gray,idx.map((j)=>item(boxes,j)));for(const[k,j]of idx.entries()){const{text,conf}=item(readings,k);let plain=item(out,j);let merged=math.accept(text,conf,plain.text,plain.conf);if(merged===null)continue;const[x0,,x1]=item(boxes,j);out[j]={text:merged,conf:1,toks:[[merged,Math.fround(x0+x1)/2]],math:{plain,reading:text,conf,draft:plain.text,rconf:plain.conf}}}}if(math.spanImg&&!vertical){let seen=new Set(cand);let rest=out.flatMap((_,j)=>seen.has(j)?[]:[j]);await readSpanImg(math,math.spanImg,gray,boxes,out,rest,ops,vocab)}}async function readSpanImg(math,tagger,gray,boxes,out,idx,ops,vocab){let lines=idx.filter((j)=>{let r=item(out,j);return r.toks.length&&Array.from(r.text).some(isAlpha)});if(!lines.length)return;let crops=lines.map((j)=>cropLine(gray,item(boxes,j),tagger.height,ops));let spans=await tagger.spans(crops);let jobs=lines.flatMap((j,n)=>item(spans,n).map((xs)=>({j,x:pageX(item(boxes,j),item(crops,n).width,xs)})));if(!jobs.length)return;let f=Math.fround;let readings=await math.read(gray,jobs.map(({j,x:[x0,x1]})=>{let b=item(boxes,j);return[f(x0),b[1],f(x1),b[3]]}));for(const[n,{j,x}]of jobs.entries()){const{text,conf}=item(readings,n);let t=pyStrip(text);if(conf<MATH_MIN_CONF||t.split("$").length-1!==2||!t.startsWith("$")||!t.endsWith("$")){continue}if(!(tagger.acceptPlain||hasMath(t)))continue;let line=item(out,j);let chars=line.toks.map((tk)=>typeof tk[0]==="string"?tk:[vocab.decode([tk[0]])||" ",tk[1]]);let toks=splice(chars,x[0],x[1],t);out[j]={text:toks.map((tk)=>String(tk[0])).join(""),conf:line.conf,toks}}}
@@ -1,13 +1,32 @@
1
- import type { Gray, ImageOps } from "./image.js";
1
+ import type { InferenceSession } from "onnxruntime-common";
2
+ import type { FloatImage, Gray, ImageOps } from "./image.js";
2
3
  import type { MathReader } from "./math.js";
3
4
  import type { Box } from "./rec-preproc.js";
4
5
  import type { LineGroups } from "./recognize.js";
5
- import type { IndraMeta, IndraSessions, RecLine, TensorCtor } from "./types.js";
6
+ import type { IndraMeta, IndraSessions, Lazy, RecLine, TensorCtor } from "./types.js";
6
7
  import { Vocab } from "./vocab.js";
8
+ /** The line-band crops of some boxes, and rec.onnx's tall-window crops of them. */
9
+ export type LineCrops = {
10
+ crops: FloatImage[];
11
+ tall: FloatImage[];
12
+ };
13
+ /** One recognizer as the text-layer check reads with it. */
14
+ export type Reader = {
15
+ name: string;
16
+ vocab: Vocab;
17
+ session: Lazy<InferenceSession>;
18
+ /** Lines are widened by this factor for it. */
19
+ xscale: number;
20
+ /** rec.onnx, which reads the tall window. */
21
+ main: boolean;
22
+ };
23
+ /** A loader that runs once; a failed load is retried on the next call. */
24
+ export declare function once<T>(load: Lazy<T>): Lazy<T>;
7
25
  /**
8
- * The line recognizers of a model set: rec.onnx, and with script.onnx one
26
+ * The line recognizers of a model set: rec.onnx, with script.onnx one
9
27
  * recognizer per script group (rec_<group>.onnx with meta["vocab_<group>"]),
10
- * each with its language model when there is one.
28
+ * and with hw.onnx the handwriting recognizer rec_hw.onnx; each with its
29
+ * language model when there is one.
11
30
  */
12
31
  export declare class Recognizers {
13
32
  private readonly Tensor;
@@ -24,13 +43,19 @@ export declare class Recognizers {
24
43
  private readonly lmParams;
25
44
  private readonly scriptGroups;
26
45
  private readonly script;
46
+ private readonly hw;
47
+ private readonly hwHeight;
48
+ private readonly hwWindow;
49
+ private readonly hwRouteMin;
27
50
  constructor(Tensor: TensorCtor, sessions: IndraSessions, meta: IndraMeta, ops: ImageOps, useLm: boolean, math: MathReader | undefined);
28
51
  /** Every recognizer's vocabulary: the main one first, then each group's. */
29
52
  get vocabs(): Vocab[];
30
- /** The language model use of one recognizer, when its file is there and the model emits top-k outputs. */
53
+ /**
54
+ * The language model use of one recognizer, when its file is there and the
55
+ * model gives top-k outputs or logits. rec_hw.onnx reads with the base model.
56
+ */
31
57
  private lmUse;
32
- private base;
33
- private group;
58
+ private resolve;
34
59
  /**
35
60
  * Which recognizer reads which lines. With script.onnx, each line goes to
36
61
  * the recognizer of its script group, and a line the classifier is unsure
@@ -38,12 +63,14 @@ export declare class Recognizers {
38
63
  * columns, characters on their side: all go to the CJK recognizer.
39
64
  */
40
65
  private plan;
41
- /**
42
- * The script group of each line box and whether the classifier is sure,
43
- * from crops made as `read` makes them; every line is base without
44
- * script.onnx.
45
- */
46
- boxGroups(gray: Gray, boxes: readonly Box[]): Promise<LineGroups>;
66
+ /** Per line crop (line band, base height): whether hw.onnx calls it handwritten. */
67
+ private hwLines;
68
+ /** The main recognizer and each script group's, in meta.json order (`main`: rec.onnx). */
69
+ readers(): Reader[];
70
+ /** The line-band crops of the boxes, and rec.onnx's tall-window crops, as `read` makes them. */
71
+ lineCrops(gray: Gray, boxes: readonly Box[]): LineCrops;
72
+ /** The script group of each line crop and whether the classifier is sure; base and sure without script.onnx. */
73
+ cropGroups(crops: readonly FloatImage[]): Promise<LineGroups>;
47
74
  /**
48
75
  * Text, confidence and character positions per line; a line read twice
49
76
  * keeps the more confident reading. A line under MIN_CONF comes back empty.
@@ -1 +1 @@
1
- export class Recognizers{Tensor;sessions;ops;useLm;math;vocab;height;window;groups=new Map;lms=new Map;lmParams;scriptGroups;script;constructor(Tensor,sessions,meta,ops,useLm,math){this.Tensor=Tensor;this.sessions=sessions;this.ops=ops;this.useLm=useLm;this.math=math;this.vocab=Vocab.fromJson(meta.vocab);this.height=meta.rec_height;this.window=meta.rec_window??1;for(let key of Object.keys(meta)){if(!key.startsWith("vocab_"))continue;let name=key.slice("vocab_".length);let load=sessions.groups?.[name];let json=meta[`vocab_${name}`];if(load&&json)this.groups.set(name,{session:once(load),vocab:Vocab.fromJson(json)})}for(const[name,load]of Object.entries(sessions.lms??{}))this.lms.set(name,once(load));this.lmParams=meta.lm_params??{};this.scriptGroups=meta.script_groups??GROUPS;this.script=this.groups.size?sessions.script:undefined}get vocabs(){return[this.vocab,...[...this.groups.values()].map((g)=>g.vocab)]}lmUse(name,sess){let lm=this.lms.get(name);if(!this.useLm||!lm||!LM_OUTPUTS.every((o)=>sess.outputNames.includes(o))){return}let p=this.lmParams[name]??{};return{lm,alpha:p.alpha??LM_ALPHA,beta:p.beta??LM_BETA,gate:p.gate??LM_GATE}}base(sel){let sess=this.sessions.rec;return{sess,vocab:this.vocab,sel,asChars:false,lm:this.lmUse("base",sess)}}async group(name,sel){let g=this.groups.get(name);if(!g)throw new Error(`no recognizer for script group "${name}"`);let sess=await g.session();return{sess,vocab:g.vocab,sel,asChars:true,lm:this.lmUse(name,sess)}}async plan(crops,vertical){let all=crops.map((_,i)=>i);if(vertical&&this.groups.has("cjk"))return[()=>this.group("cjk",all)];if(!this.script||!crops.length)return[async()=>this.base(all)];const{names,sure}=await lineGroups(this.Tensor,this.script,crops,this.scriptGroups,new Set(this.groups.keys()));let plan=[async()=>this.base(all.filter((j)=>names[j]==="base"||!sure[j]))];for(let name of this.groups.keys()){let sel=all.filter((j)=>names[j]===name);if(sel.length)plan.push(()=>this.group(name,sel))}return plan}async boxGroups(gray,boxes){if(!this.script||!boxes.length){return{names:boxes.map(()=>"base"),sure:boxes.map(()=>false)}}let crops=boxes.map((b)=>cropLine(gray,b,this.height,this.ops,4096,1,isDarkLine(gray,b)));return lineGroups(this.Tensor,this.script,crops,this.scriptGroups,new Set(this.groups.keys()))}async read(gray,boxes,batch,vertical){let dark=this.window>1?boxes.map((b)=>isDarkLine(gray,b)):undefined;let crop=(b,i,window)=>cropLine(gray,b,this.height,this.ops,4096,window,dark?.[i]);let crops=boxes.map((b,i)=>crop(b,i,1));let tall=this.window>1?boxes.map((b,i)=>crop(b,i,this.window)):crops;let out=crops.map(()=>({text:"",conf:0,toks:[]}));let bestConf=crops.map(()=>-1);for(let next of await this.plan(crops,vertical)){let g=await next();let src=g.sess===this.sessions.rec?tall:crops;for(let part of widthBatches(g.sel.map((j)=>item(crops,j).width),batch)){let idx=part.map((i)=>item(g.sel,i));let lines=await recognizeBatch(this.Tensor,g,idx.map((j)=>item(src,j)),idx.map((j)=>item(crops,j)),idx.map((j)=>item(boxes,j)));for(const[k,j]of idx.entries()){let line=item(lines,k);if(line.conf<=item(bestConf,j))continue;bestConf[j]=line.conf;out[j]=line}}}if(this.math&&crops.length)await readMath(this.math,gray,boxes,crops,out);return out}}import{cropLine,isDarkLine,widthBatches}from"./rec-preproc.js";import{GROUPS,lineGroups,readMath,recognizeBatch}from"./recognize.js";import{item}from"./util.js";import{Vocab}from"./vocab.js";let LM_GATE=0.9;let LM_ALPHA=0.5;let LM_BETA=1.5;let LM_OUTPUTS=["blank","topv","topi"];function once(load){let p;return async()=>{p??=load();try{return await p}catch(e){p=undefined;throw e}}}
1
+ export class Recognizers{Tensor;sessions;ops;useLm;math;vocab;height;window;groups=new Map;lms=new Map;lmParams;scriptGroups;script;hw;hwHeight;hwWindow;hwRouteMin;constructor(Tensor,sessions,meta,ops,useLm,math){this.Tensor=Tensor;this.sessions=sessions;this.ops=ops;this.useLm=useLm;this.math=math;this.vocab=Vocab.fromJson(meta.vocab);this.height=meta.rec_height;this.window=meta.rec_window??1;for(let key of Object.keys(meta)){if(!key.startsWith("vocab_"))continue;let name=key.slice("vocab_".length);let load=sessions.groups?.[name];let json=meta[`vocab_${name}`];if(load&&json){let xscale=meta[`rec_xscale_${name}`]??1;this.groups.set(name,{session:once(load),vocab:Vocab.fromJson(json),xscale})}}for(const[name,load]of Object.entries(sessions.lms??{}))this.lms.set(name,once(load));this.lmParams=meta.lm_params??{};this.scriptGroups=meta.script_groups??GROUPS;this.script=this.groups.size?sessions.script:undefined;this.hw=sessions.hw?{cls:sessions.hw.cls,rec:once(sessions.hw.rec)}:undefined;this.hwHeight=meta.rec_hw_height??this.height;this.hwWindow=meta.rec_hw_window??this.window;this.hwRouteMin=meta.hw_route_min??HW_ROUTE_MIN}get vocabs(){return[this.vocab,...[...this.groups.values()].map((g)=>g.vocab)]}lmUse(name,sess){let lm=this.lms.get(name);if(!this.useLm||!lm||!lmReady(sess))return;let p=this.lmParams[name]??{};return{lm,alpha:p.alpha??LM_ALPHA,beta:p.beta??LM_BETA,gate:p.gate??LM_GATE}}async resolve(entry){const{sel}=entry;if(entry.kind==="base"){let sess=this.sessions.rec;return{sess,vocab:this.vocab,sel,asChars:false,lm:this.lmUse("base",sess),xscale:1}}if(entry.kind==="hw"){if(!this.hw)throw new Error("no handwriting recognizer");let sess=await this.hw.rec();return{sess,vocab:this.vocab,sel,asChars:false,lm:this.lmUse("base",sess),xscale:1}}let g=this.groups.get(entry.name);if(!g)throw new Error(`no recognizer for script group "${entry.name}"`);let sess=await g.session();let lm=this.lmUse(entry.name,sess);return{sess,vocab:g.vocab,sel,asChars:true,lm,xscale:g.xscale}}async plan(crops,vertical){let all=crops.map((_,i)=>i);if(vertical&&this.groups.has("cjk"))return[{kind:"group",name:"cjk",sel:all}];if(!this.script||!crops.length)return[{kind:"base",sel:all}];const{names,sure}=await lineGroups(this.Tensor,this.script,crops,this.scriptGroups,new Set(this.groups.keys()));let plan=[{kind:"base",sel:all.filter((j)=>names[j]==="base"||!sure[j])}];for(let name of this.groups.keys()){let sel=all.filter((j)=>names[j]===name);if(sel.length)plan.push({kind:"group",name,sel})}return plan}async hwLines(cls,crops,batch){let out=crops.map(()=>false);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 cls.run({x:new this.Tensor("float32",data,dims),widths:new this.Tensor("int64",widths,[idx.length])});let p=floats(output(res,"p"));for(const[k,j]of idx.entries())out[j]=(p[k]??0)>=this.hwRouteMin}return out}readers(){let main={name:"base",vocab:this.vocab,session:async()=>this.sessions.rec,xscale:1,main:true};return[main,...[...this.groups].map(([name,g])=>({name,vocab:g.vocab,session:g.session,xscale:g.xscale,main:false}))]}lineCrops(gray,boxes){let dark=this.window>1?boxes.map((b)=>isDarkLine(gray,b)):undefined;let crop=(b,i,window)=>cropLine(gray,b,this.height,this.ops,4096,window,dark?.[i]);let crops=boxes.map((b,i)=>crop(b,i,1));let tall=this.window>1?boxes.map((b,i)=>crop(b,i,this.window)):crops;return{crops,tall}}async cropGroups(crops){if(!this.script)return{names:crops.map(()=>"base"),sure:crops.map(()=>true)};return lineGroups(this.Tensor,this.script,crops,this.scriptGroups,new Set(this.groups.keys()))}async read(gray,boxes,batch,vertical){let dark=this.window>1?boxes.map((b)=>isDarkLine(gray,b)):undefined;let crop=(b,i,height,window)=>cropLine(gray,b,height,this.ops,4096,window,dark?.[i]);let crops=boxes.map((b,i)=>crop(b,i,this.height,1));let tall=this.window>1?boxes.map((b,i)=>crop(b,i,this.height,this.window)):crops;let plan=await this.plan(crops,vertical);let hwBands=new Map;let hwTall=new Map;let base=plan[0];if(this.hw&&!vertical&&crops.length&&base?.kind==="base"){let hw=await this.hwLines(this.hw.cls,crops,batch);let moved=base.sel.filter((j)=>hw[j]);if(moved.length){base.sel=base.sel.filter((j)=>!hw[j]);plan.push({kind:"hw",sel:moved});for(let j of moved){let band=crop(item(boxes,j),j,this.hwHeight,1);hwBands.set(j,band);hwTall.set(j,this.hwWindow>1?crop(item(boxes,j),j,this.hwHeight,this.hwWindow):band)}}}let out=crops.map(()=>({text:"",conf:0,toks:[]}));let bestConf=crops.map(()=>-1);for(let entry of plan){let g=await this.resolve(entry);let bandOf=(j)=>entry.kind==="hw"?cropOf(hwBands,j):item(crops,j);let srcOf=(j)=>{if(entry.kind==="hw")return cropOf(hwTall,j);return g.sess===this.sessions.rec?item(tall,j):item(crops,j)};for(let part of widthBatches(g.sel.map((j)=>bandOf(j).width),batch)){let idx=part.map((i)=>item(g.sel,i));let lines=await recognizeBatch(this.Tensor,g,widen(idx.map(srcOf),g.xscale,this.ops),idx.map(bandOf),idx.map((j)=>item(boxes,j)));for(const[k,j]of idx.entries()){let line=item(lines,k);if(line.conf<=item(bestConf,j))continue;bestConf[j]=line.conf;out[j]=line}}}if(this.math&&crops.length){await readMath(this.math,gray,boxes,crops,out,vertical,this.ops,this.vocab)}return out}}import{cropLine,isDarkLine,padBatch,widen,widthBatches}from"./rec-preproc.js";import{GROUPS,lineGroups,lmReady,readMath,recognizeBatch}from"./recognize.js";import{floats,item,output}from"./util.js";import{Vocab}from"./vocab.js";let LM_GATE=0.9;let LM_ALPHA=0.5;let LM_BETA=1.5;let HW_ROUTE_MIN=0.5;function cropOf(crops,j){let c=crops.get(j);if(!c)throw new Error(`no handwriting crop for line ${j}`);return c}export function once(load){let p;return async()=>{p??=load();try{return await p}catch(e){p=undefined;throw e}}}
@@ -0,0 +1,34 @@
1
+ /** A block a[a:a+size] == b[b:b+size] (CPython's Match). */
2
+ export type Match = {
3
+ readonly a: number;
4
+ readonly b: number;
5
+ readonly size: number;
6
+ };
7
+ export type OpcodeTag = "replace" | "delete" | "insert" | "equal";
8
+ /** (tag, i1, i2, j1, j2): CPython's opcode tuple. */
9
+ export type Opcode = readonly [tag: OpcodeTag, i1: number, i2: number, j1: number, j2: number];
10
+ /** A string is a sequence of its code points, as in Python. */
11
+ export type Seq = string | readonly string[];
12
+ export declare class SequenceMatcher {
13
+ private readonly a;
14
+ private readonly b;
15
+ private readonly b2j;
16
+ private blocks;
17
+ private ops;
18
+ constructor(a: Seq, b: Seq);
19
+ /**
20
+ * The longest matching block in a[alo:ahi] and b[blo:bhi]; of the longest, the
21
+ * one that starts first in a, and of those the one that starts first in b.
22
+ * With no match, (alo, blo, 0).
23
+ */
24
+ findLongestMatch(alo?: number, ahi?: number, blo?: number, bhi?: number): Match;
25
+ /**
26
+ * Maximal non-overlapping matching blocks, increasing in a and in b, with no two
27
+ * adjacent; the last one is the sentinel (len(a), len(b), 0).
28
+ */
29
+ getMatchingBlocks(): readonly Match[];
30
+ /** The edit script that turns a into b. */
31
+ getOpcodes(): readonly Opcode[];
32
+ /** 2.0 * matches / (len(a) + len(b)), or 1.0 for two empty sequences. */
33
+ ratio(): number;
34
+ }
@@ -0,0 +1 @@
1
+ export class SequenceMatcher{a;b;b2j=new Map;blocks;ops;constructor(a,b){this.a=elements(a);this.b=elements(b);this.b.forEach((elt,j)=>{let indices=this.b2j.get(elt);if(indices)indices.push(j);else this.b2j.set(elt,[j])})}findLongestMatch(alo=0,ahi=this.a.length,blo=0,bhi=this.b.length){const{a,b}=this;let besti=alo;let bestj=blo;let bestsize=0;let j2len=new Map;for(let i=alo;i<ahi;i++){let newj2len=new Map;for(let j of this.b2j.get(item(a,i))??[]){if(j<blo)continue;if(j>=bhi)break;let k=(j2len.get(j-1)??0)+1;newj2len.set(j,k);if(k>bestsize){besti=i-k+1;bestj=j-k+1;bestsize=k}}j2len=newj2len}while(besti>alo&&bestj>blo&&a[besti-1]===b[bestj-1]){besti--;bestj--;bestsize++}while(besti+bestsize<ahi&&bestj+bestsize<bhi&&a[besti+bestsize]===b[bestj+bestsize]){bestsize++}return{a:besti,b:bestj,size:bestsize}}getMatchingBlocks(){if(this.blocks)return this.blocks;let la=this.a.length;let lb=this.b.length;let queue=[[0,la,0,lb]];let found=[];for(let next=queue.pop();next;next=queue.pop()){const[alo,ahi,blo,bhi]=next;let m=this.findLongestMatch(alo,ahi,blo,bhi);if(m.size===0)continue;found.push(m);if(alo<m.a&&blo<m.b)queue.push([alo,m.a,blo,m.b]);if(m.a+m.size<ahi&&m.b+m.size<bhi){queue.push([m.a+m.size,ahi,m.b+m.size,bhi])}}found.sort((x,y)=>x.a-y.a||x.b-y.b||x.size-y.size);let blocks=[];let cur={a:0,b:0,size:0};for(let m of found){if(cur.a+cur.size===m.a&&cur.b+cur.size===m.b){cur={a:cur.a,b:cur.b,size:cur.size+m.size}}else{if(cur.size)blocks.push(cur);cur=m}}if(cur.size)blocks.push(cur);blocks.push({a:la,b:lb,size:0});this.blocks=blocks;return blocks}getOpcodes(){if(this.ops)return this.ops;let i=0;let j=0;let ops=[];for(const{a:ai,b:bj,size}of this.getMatchingBlocks()){if(i<ai&&j<bj)ops.push(["replace",i,ai,j,bj]);else if(i<ai)ops.push(["delete",i,ai,j,bj]);else if(j<bj)ops.push(["insert",i,ai,j,bj]);i=ai+size;j=bj+size;if(size)ops.push(["equal",ai,i,bj,j])}this.ops=ops;return ops}ratio(){let matches=this.getMatchingBlocks().reduce((n,m)=>n+m.size,0);let length=this.a.length+this.b.length;return length?2*matches/length:1}}import{item}from"./util.js";let elements=(s)=>typeof s==="string"?Array.from(s):s;
@@ -0,0 +1,29 @@
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 { Tok } from "./types.js";
5
+ /** A word of a line holding digits inside symbol-glyph boxes: tokens [start, end) and the digits' positions. */
6
+ export type SymbolWord = {
7
+ start: number;
8
+ end: number;
9
+ hits: number[];
10
+ };
11
+ /**
12
+ * Words of one detected line (tokens (char, x, ...), box in pixels) that hold
13
+ * a digit inside a symbol-glyph box (`sym`, pixels).
14
+ */
15
+ export declare function symbolWords(toks: readonly Tok[], box: Box, sym: readonly Box[]): SymbolWord[];
16
+ /**
17
+ * Positions (into `layer`, a line's text from its tokens) of the digits at
18
+ * `hits` that the recognizer's reading `read` has as a symbol or a dash, one
19
+ * character for one, and that character. A cut or tiny glyph reads as light
20
+ * punctuation ('.', ':', '_'), which does not count.
21
+ */
22
+ export declare function symbolCandidates(layer: string, read: string, hits: readonly number[]): Map<number, string>;
23
+ /**
24
+ * Check the layer digits that lie in a possible symbol glyph's box (`sym`,
25
+ * pixels) against the page, and put the symbol in place of a digit where the
26
+ * recognizer supports it; `toks` changes in place. Returns the number of
27
+ * digits replaced.
28
+ */
29
+ export declare function fixSymbolDigits(pipeline: IndraPipeline, gray: Gray, boxes: readonly Box[], toks: Tok[][], sym: readonly Box[], skip: ReadonlySet<number>): Promise<number>;
@@ -0,0 +1 @@
1
+ import{SequenceMatcher}from"./sequence-matcher.js";import{item}from"./util.js";let SYMBOL_MARGIN=2;let SYMBOL=/^[\p{Sm}\p{So}\p{Sk}\p{Sc}\p{Pd}]$/u;let DIGIT=/^[0-9]$/u;let f=Math.fround;function rowBoxes(sym,y0,y1){return sym.filter((s)=>{let over=f(Math.min(s[3],f(y1))-Math.max(s[1],f(y0)));return over>f(0.5*Math.min(f(s[3]-s[1]),f(f(y1)-f(y0))))})}export function symbolWords(toks,box,sym){if(!sym.length||!toks.length)return[];let rows=rowBoxes(sym,box[1],box[3]);if(!rows.length)return[];let out=[];let start;for(let j=0;j<=toks.length;j++){let space=j===toks.length||item(toks,j)[0]===" ";if(!space&&start===undefined)start=j;if(space&&start!==undefined){let hits=[];for(let p=start;p<j;p++){const[c,x]=item(toks,p);if(typeof c==="string"&&DIGIT.test(c)&&rows.some((r)=>f(r[0]-1)<=f(x)&&f(x)<=f(r[2]+1))){hits.push(p)}}if(hits.length)out.push({start,end:j,hits});start=undefined}}return out}export function symbolCandidates(layer,read,hits){let out=new Map;let hit=new Set(hits);let a=Array.from(layer);let b=Array.from(read);for(const[op,i1,i2,j1,j2]of new SequenceMatcher(a,b).getOpcodes()){if(op!=="replace"||i2-i1!==j2-j1)continue;for(let p=i1;p<i2;p++){let c=item(b,j1+p-i1);if(hit.has(p)&&SYMBOL.test(c))out.set(p,c)}}return out}export async function fixSymbolDigits(pipeline,gray,boxes,toks,sym,skip){let lines=new Map;for(const[i,tk]of toks.entries()){if(!tk.length||skip.has(i))continue;let hits=symbolWords(tk,item(boxes,i),sym).flatMap((w)=>w.hits);if(hits.length)lines.set(i,hits)}if(!lines.size)return 0;let idx=[...lines.keys()].toSorted((p,q)=>p-q);let rbox=boxes.map((b)=>[f(b[0]),f(b[1]),f(b[2]),f(b[3])]);for(let i of idx){let b=item(rbox,i);const[,y0,,y1]=b;let xs=(lines.get(i)??[]).map((p)=>f(item(item(toks,i),p)[1]));let near=rowBoxes(sym,y0,y1).filter((s)=>xs.some((x)=>f(s[0]-1)<=x&&x<=f(s[2]+1)));if(near.length){let pad=0.3*(y1-y0);b[0]=f(Math.min(b[0],Math.min(...near.map((s)=>s[0]))-pad));b[2]=f(Math.max(b[2],Math.max(...near.map((s)=>s[2]))+pad))}}for(let b of rbox){b[0]=Math.min(Math.max(b[0],0),gray.width-1);b[2]=Math.min(Math.max(b[2],0),gray.width-1)}let reads=await pipeline.recognize(gray,idx.map((i)=>item(rbox,i)));let candBoxes=[];let candToks=[];let owners=[];for(const[n,i]of idx.entries()){let tk=item(toks,i);let layer=tk.map((t)=>typeof t[0]==="string"?t[0]:" ").join("");for(const[p,c]of symbolCandidates(layer,item(reads,n).text,lines.get(i)??[])){let alt=[...tk];const[,x,...rest]=item(alt,p);alt[p]=[c,x,...rest];candBoxes.push(item(rbox,i),item(rbox,i));candToks.push(tk,alt);owners.push({i,p,c,length:layer.replaceAll(" ","").length})}}if(!owners.length)return 0;let gaps=await pipeline.layerGaps(gray,candBoxes,candToks);let fixed=0;for(const[k,{i,p,c,length}]of owners.entries()){let gLayer=item(gaps,2*k).gap;let gAlt=item(gaps,2*k+1).gap;if(gLayer===null||gAlt===null)continue;if((gLayer-gAlt)*Math.max(length,1)>=SYMBOL_MARGIN){let tk=item(toks,i);const[,x,...rest]=item(tk,p);tk[p]=[c,x,...rest];fixed++}}return fixed}
@@ -0,0 +1,38 @@
1
+ import type { Gray } from "./image.js";
2
+ import type { Box } from "./rec-preproc.js";
3
+ /** The line geometry features of `alignment`. */
4
+ export type Alignment = {
5
+ g_rows: number;
6
+ g_lines_row: number;
7
+ g_multi_rows: number;
8
+ g_gap: number;
9
+ g_gap_cv: number;
10
+ g_left_edges: number;
11
+ g_right_edges: number;
12
+ g_width_cv: number;
13
+ g_wide_lines: number;
14
+ };
15
+ /** Feature name to value: what `blockFeatures` computes and the verifier's weights read. */
16
+ export type BlockFeatures = Record<string, number>;
17
+ /** The cell texts of an HTML table, row by row; a cell with colspan n is followed by n - 1 empty cells. */
18
+ export declare function parseTable(html: string): string[][];
19
+ /**
20
+ * Per row of `ink` [h, w] (0/1): does a morphological open with a (length x 1)
21
+ * rectangle keep a pixel? The same result as cv2.morphologyEx(MORPH_OPEN) with
22
+ * OpenCV's defaults (anchor at the centre, the border counts as ink for the
23
+ * erosion): a row keeps a pixel when `length` consecutive pixels are ink, when
24
+ * its first b + 1 or last a + 1 pixels are ink (a = length // 2, b = length - 1 -
25
+ * a), or when the whole row is ink.
26
+ */
27
+ export declare function anyRun(ink: Uint8Array, h: number, w: number, length: number): boolean[];
28
+ /** Share of the block's height (width) covered by long horizontal (vertical) dark strokes. */
29
+ export declare function ruling(gray: Gray | undefined, box: Box): [number, number];
30
+ /** `std(values) / max(1e-6, mean(scale))` in float32, as the reference writes it. */
31
+ export declare function spreadF32(values: readonly number[], scale?: readonly number[]): number;
32
+ /**
33
+ * Line geometry inside the block: rows by vertical centre (overlap > half a line
34
+ * height), lines per row, the gap between neighbours in a row, and how many
35
+ * distinct left / right edges the lines use (within half a line height).
36
+ * `b` holds the block's boxes as float32 values.
37
+ */
38
+ export declare function alignment(b: readonly Box[]): Alignment;
@@ -0,0 +1 @@
1
+ import{meanF32,sumF32}from"./numeric.js";import{medianF32}from"./order-post.js";import{pyHtmlUnescape}from"./py-text.js";import{pyStrip}from"./py-unicode.js";import{item}from"./util.js";let f=Math.fround;let TR=/<tr[^>]*>(.*?)<\/tr>/gs;let TD=/<t[dh]([^>]*)>(.*?)<\/t[dh]>/gs;let SPAN=/colspan="(\d+)"/;let TAG=/<[^>]+>/g;export function parseTable(html){return[...html.matchAll(TR)].map((row)=>[...(row[1]??"").matchAll(TD)].flatMap((cell)=>{let span=Number((SPAN.exec(cell[1]??"")??[])[1]??1);let text=pyStrip(pyHtmlUnescape((cell[2]??"").replace(TAG," ")));return[text,...Array.from({length:Math.max(span-1,0)},()=>"")]}))}export function anyRun(ink,h,w,length){let a=length>>1;let b=length-1-a;return Array.from({length:h},(_,y)=>{let row=ink.subarray(y*w,(y+1)*w);let allInk=(from,to)=>row.subarray(from,to).every(Boolean);if(allInk(0,w))return true;if(b+1<=w&&allInk(0,b+1))return true;if(a+1<=w&&allInk(w-a-1,w))return true;let run=0;for(let v of row){run=v?run+1:0;if(run>=length)return true}return false})}function medianInt(values){let hist=new Int32Array(256);for(let v of values)hist[v]=(hist[v]??0)+1;let kth=(k)=>{let seen=0;for(let v=0;v<256;v++){seen+=item(hist,v);if(seen>k)return v}throw new RangeError("medianInt: empty input")};let mid=(values.length-1)/2;return Math.trunc((kth(Math.floor(mid))+kth(Math.ceil(mid)))/2)}export function ruling(gray,box){if(!gray)return[0,0];const{width:W,height:H}=gray;let x0=Math.trunc(Math.max(0,f(box[0]-4)));let y0=Math.trunc(Math.max(0,f(box[1]-4)));let x1=Math.trunc(Math.min(W,f(box[2]+4)));let y1=Math.trunc(Math.min(H,f(box[3]+4)));let cw=x1-x0;let ch=y1-y0;if(cw<=0||ch<=0||Math.min(cw,ch)<4)return[0,0];let crop=new Uint8Array(cw*ch);for(let y=0;y<ch;y++)crop.set(gray.data.subarray((y0+y)*W+x0,(y0+y)*W+x1),y*cw);let t=Math.max(0,Math.min(160,medianInt(crop)-30));let ink=crop.map((v)=>v<t?1:0);let inkT=new Uint8Array(cw*ch);for(let y=0;y<ch;y++)for(let x=0;x<cw;x++)inkT[x*ch+y]=item(ink,y*cw+x);let share=(rows)=>rows.filter(Boolean).length/rows.length;return[share(anyRun(ink,ch,cw,Math.max(8,Math.floor(cw/3)))),share(anyRun(inkT,cw,ch,Math.max(8,Math.floor(ch/3))))]}function stdF32(values){let m=meanF32(values);let sq=values.map((v)=>f(f(v-m)*f(v-m)));return f(Math.sqrt(f(sumF32(sq)/values.length)))}export function spreadF32(values,scale=values){let m=meanF32(scale);return f(stdF32(values)/f(m>0.000001?m:0.000001))}function edges(values,gap){let v=values.toSorted((p,q)=>p-q);return values.length?1+v.slice(1).filter((e,i)=>f(e-item(v,i))>gap).length:0}export function alignment(b){let h=medianF32(b.map(([,y0,,y1])=>f(y1-y0)))||1;let cy=b.map(([,y0,,y1])=>f(f(y0+y1)/2));let half=f(0.5*h);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((j)=>item(cy,j)))))<half)last.push(i);else rows.push([i])}let gaps=rows.flatMap((r)=>{let xs=r.toSorted((p,q)=>item(b,p)[0]-item(b,q)[0]);return xs.slice(1).map((k,i)=>f(f(item(b,k)[0]-item(b,item(xs,i))[2])/f(h)))});let n=b.length;let widths=b.map(([x0,,x1])=>f(x1-x0));let span=f(f(0.6)*f(Math.max(...b.map((x)=>x[2]))-Math.min(...b.map((x)=>x[0]))));return{g_rows:Math.log1p(rows.length),g_lines_row:n/Math.max(1,rows.length),g_multi_rows:rows.filter((r)=>r.length>=2).length/Math.max(1,rows.length),g_gap:gaps.length?Math.log1p(Math.max(0,medianF32(gaps))):0,g_gap_cv:gaps.length>1?spreadF32(gaps,gaps.map(Math.abs)):0,g_left_edges:edges(b.map((x)=>x[0]),half)/Math.max(1,n),g_right_edges:edges(b.map((x)=>x[2]),half)/Math.max(1,n),g_width_cv:spreadF32(widths),g_wide_lines:widths.filter((w)=>w>span).length/n}}
@@ -0,0 +1,50 @@
1
+ import type { Word } from "./table-features.js";
2
+ /** How a cell's columns (and rows) are found: see `decodeTable`. */
3
+ export type ColSpans = "geo" | "rel" | "rel2";
4
+ /**
5
+ * meta.json "tsr_rel_span" as a ColSpans: the reference takes a cell's spans
6
+ * from the model's relations for "rel" and "rel2" and from geometry otherwise.
7
+ */
8
+ export declare function colSpans(value: string | undefined): ColSpans;
9
+ /** A cell: the rows r0..r1 and columns c0..c1 it spans (inclusive), and its words. */
10
+ export type TableCell = {
11
+ r0: number;
12
+ r1: number;
13
+ c0: number;
14
+ c1: number;
15
+ words: number[];
16
+ };
17
+ /** A decoded table. `outside`: words outside the table; `nHead`: header rows. */
18
+ export type TableStruct = {
19
+ cells: TableCell[];
20
+ nHead: number;
21
+ outside: number[];
22
+ nRows: number;
23
+ nCols: number;
24
+ };
25
+ /**
26
+ * `cluster` (average linkage, merge while the mean logit is positive) run on each
27
+ * connected component of the positive pairs: two groups with no positive pair
28
+ * between them never merge, so the result is the same, at a fraction of the cost
29
+ * when positives are sparse (same cell). `L` is [n, n].
30
+ */
31
+ export declare function clusterSparse(L: Float32Array, n: number): number[][];
32
+ /**
33
+ * Mean logit between every two groups of items: [g, g] float32 with a zero
34
+ * diagonal. `L` is [n, n]; each group lists item indices.
35
+ */
36
+ export declare function meanLogit(L: Float32Array, n: number, groups: readonly number[][]): Float32Array;
37
+ /**
38
+ * Cells, rows and columns from the model's outputs for N words. `pair` is
39
+ * [3, N, N] logits, `tags` [N, 2] logits, `boxes` [N, 4] float32.
40
+ *
41
+ * `colSpans` "geo": a cell spans the columns whose band its words cover by more
42
+ * than half; "rel": the run of columns around its own with which its words have a
43
+ * positive mean "same column" logit (a narrow group header over the columns it
44
+ * heads); "rel2": "rel" for columns, and the same for rows with the "same row"
45
+ * logits (a stub header over the header rows it spans). `texts`: the words' texts.
46
+ * Null when fewer than two words are inside the table.
47
+ */
48
+ export declare function decodeTable(pair: Float32Array, tags: Float32Array, boxes: Float32Array, colSpans?: ColSpans, texts?: readonly string[]): TableStruct | null;
49
+ /** HTML for a decoded table; words outside it come before it as text. Null for a table of one row and one column. */
50
+ export declare function structHtml(struct: TableStruct, words: readonly Word[]): string | null;
@@ -0,0 +1,4 @@
1
+ import{meanF32}from"./numeric.js";import{cluster,medianF32}from"./order-post.js";import{LETTER,PY_SPACE,pyHtmlEscape}from"./py-text.js";import{item}from"./util.js";let f=Math.fround;let SAME_CELL=0;let SAME_ROW=1;let SAME_COL=2;let TAG_HEAD=0;let TAG_OUT=1;export function colSpans(value){return value==="rel"||value==="rel2"?value:"geo"}export function clusterSparse(L,n){let root=Array.from({length:n},(_,i)=>i);let find=(i)=>{let r=i;while(item(root,r)!==r)r=item(root,r);return r};for(let i=0;i<n;i++){for(let j=i+1;j<n;j++){if(item(L,i*n+j)>0){let a=find(i);let b=find(j);root[Math.max(a,b)]=Math.min(a,b)}}}let comps=new Map;for(let i=0;i<n;i++)comps.set(find(i),[...comps.get(find(i))??[],i]);let out=[];for(let members of comps.values()){if(members.length<=2){out.push(members);continue}let k=members.length;let sub=new Float32Array(k*k);for(const[a,i]of members.entries())for(const[b,j]of members.entries())sub[a*k+b]=item(L,i*n+j);for(let g of cluster(sub,k))out.push(g.map((x)=>item(members,x)))}return out}export function meanLogit(L,n,groups){let g=groups.length;let rowSums=groups.map((members)=>{let s=new Float64Array(n);for(let i of members)for(let j=0;j<n;j++)s[j]=(s[j]??0)+item(L,i*n+j);return s});let out=new Float32Array(g*g);for(let a=0;a<g;a++){for(let b=0;b<g;b++){if(a===b)continue;let sum=0;for(let j of item(groups,b))sum+=item(item(rowSums,a),j);out[a*g+b]=sum/(item(groups,a).length*item(groups,b).length)}}return out}function span(lo,hi,bands,own){let covered=new Set([own]);for(const[k,[a,b]]of bands.entries()){let top=b<hi?{v:b,f32:false}:{v:hi,f32:true};let bottom=a>lo?{v:a,f32:false}:{v:lo,f32:true};let rhs=0.5*(b-a);let wide=top.f32||bottom.f32?f(f(top.v)-f(bottom.v))>f(rhs):top.v-bottom.v>rhs;if(wide)covered.add(k)}let sorted=[...covered].toSorted((p,q)=>p-q);return[item(sorted,0),item(sorted,sorted.length-1)]}function relSpan(row,own){let lo=own;let hi=own;while(lo>0&&row[lo-1])lo--;while(hi+1<row.length&&row[hi+1])hi++;return[lo,hi]}function groupOf(of,cell){let v=of.get(cell);if(v===undefined)throw new RangeError(`cell ${cell} is in no group`);return v}export function decodeTable(pair,tags,boxes,colSpans="geo",texts){let n=boxes.length/4;if(n===0)return null;if(pair.length!==3*n*n||tags.length!==2*n)throw new RangeError(`decodeTable: pair ${pair.length}, tags ${tags.length} do not fit ${n} words`);let plane=(c)=>pair.subarray(c*n*n,(c+1)*n*n);let all=Array.from({length:n},(_,i)=>i);let outside=all.filter((i)=>item(tags,i*2+TAG_OUT)>0);let keep=all.filter((i)=>item(tags,i*2+TAG_OUT)<=0);if(keep.length<2)return null;let k=keep.length;let same=new Float32Array(k*k);let sameCell=plane(SAME_CELL);for(const[a,i]of keep.entries())for(const[b,j]of keep.entries())same[a*k+b]=item(sameCell,i*n+j);let cells=clusterSparse(same,k).map((c)=>c.map((x)=>item(keep,x)));let m=cells.length;let bx=(i,j)=>item(boxes,i*4+j);let cb=cells.map((c)=>[Math.min(...c.map((i)=>bx(i,0))),Math.min(...c.map((i)=>bx(i,1))),Math.max(...c.map((i)=>bx(i,2))),Math.max(...c.map((i)=>bx(i,3)))]);let cbAt=(c,j)=>item(item(cb,c),j);let center=(g,lo,hi)=>medianF32(g.map((c)=>f(f(cbAt(c,lo)+cbAt(c,hi))/2)));let rows=clusterSparse(meanLogit(plane(SAME_ROW),n,cells),m).toSorted((p,q)=>center(p,1,3)-center(q,1,3));let cols=clusterSparse(meanLogit(plane(SAME_COL),n,cells),m).toSorted((p,q)=>center(p,0,2)-center(q,0,2));let bandsOf=(groups,lo,hi)=>groups.map((g)=>[medianF32(g.map((c)=>cbAt(c,lo))),medianF32(g.map((c)=>cbAt(c,hi)))]);let rband=bandsOf(rows,1,3);let cband=bandsOf(cols,0,2);let rowOf=new Map(rows.flatMap((g,r)=>g.map((c)=>[c,r])));let colOf=new Map(cols.flatMap((g,c)=>g.map((x)=>[x,c])));let positive=(ml,groups)=>Array.from({length:m},(_,c)=>groups.map((g)=>meanF32(g.map((j)=>item(ml,c*m+j)))>0));let relCols=colSpans==="rel"||colSpans==="rel2";let pc=relCols?positive(meanLogit(plane(SAME_COL),n,cells),cols):[];let pr=colSpans==="rel2"?positive(meanLogit(plane(SAME_ROW),n,cells),rows):[];let out=cells.map((words,c)=>{const[r0,r1]=colSpans==="rel2"?relSpan(item(pr,c),groupOf(rowOf,c)):span(cbAt(c,1),cbAt(c,3),rband,groupOf(rowOf,c));const[c0,c1]=relCols?relSpan(item(pc,c),groupOf(colOf,c)):span(cbAt(c,0),cbAt(c,2),cband,groupOf(colOf,c));return{r0,r1,c0,c1,words}});let head=new Float64Array(rows.length);for(const{r0,words}of out){let mean=meanF32(words.map((i)=>item(tags,i*2+TAG_HEAD)));head[r0]=Math.max(head[r0]??0,mean)}let nHead=0;while(nHead<rows.length-1&&(head[nHead]??0)>0)nHead++;widenLoneCells(out,nHead,cols.length,texts);return{cells:out,nHead,outside,nRows:rows.length,nCols:cols.length}}function widenLoneCells(cells,nHead,nCols,texts){let inRow=new Map;for(const[k,{r0,r1}]of cells.entries())for(let r=r0;r<=r1;r++)inRow.set(r,[...inRow.get(r)??[],k]);for(const[r,ks]of inRow){if(r<nHead||ks.length!==1||nCols<3)continue;let k=item(ks,0);let cell=item(cells,k);if(cell.r0!==cell.r1||cell.c0===0)continue;if(!texts||cell.words.some((i)=>[...item(texts,i)].some((c)=>LETTER.test(c))))cells[k]={...cell,c0:0,c1:nCols-1}}}let LEADER_DOTS=new RegExp(`(?:[${PY_SPACE}]+[.\\u00b7\\u2026]+)+$`,"u");export function structHtml(struct,words){let R=struct.nRows;let C=struct.nCols;if(R<2&&C<2)return null;let occ=new Int32Array(R*C).fill(-1);let anchors=new Map;let taken=(r0,r1,c0,c1)=>{for(let r=r0;r<=Math.min(r1,R-1);r++)for(let c=c0;c<=Math.min(c1,C-1);c++)if(item(occ,r*C+c)>=0)return true;return false};for(const[k,cell]of struct.cells.entries()){let{r1,c1}=cell;const{r0,c0}=cell;if(taken(r0,r1,c0,c1)){r1=r0;c1=c0;let k0=item(occ,r0*C+c0);if(k0>=0){let anchor=anchors.get(k0);if(!anchor)throw new RangeError(`cell ${k0} has no anchor`);anchor.ws.push(...cell.words);continue}}for(let r=r0;r<=r1;r++)for(let c=c0;c<=c1;c++)occ[r*C+c]=k;anchors.set(k,{r:r0,c:c0,rs:r1-r0+1,cs:c1-c0+1,ws:[...cell.words]})}let text=(ws)=>{let sorted=ws.toSorted((a,b)=>item(words,a).line-item(words,b).line||item(words,a).box[0]-item(words,b).box[0]);let t=sorted.map((i)=>item(words,i).text).join(" ");return t.replace(LEADER_DOTS,"")||t};let bySlot=new Map([...anchors.values()].map((a)=>[a.r*C+a.c,a]));let out=["<table>"];for(let r=0;r<R;r++){let tag=r<struct.nHead?"th":"td";let tds="";for(let c=0;c<C;c++){let a=bySlot.get(r*C+c);if(a){let attr=(a.rs>1?` rowspan="${a.rs}"`:"")+(a.cs>1?` colspan="${a.cs}"`:"");tds+=`<${tag}${attr}>${pyHtmlEscape(text(a.ws))}</${tag}>`}else if(item(occ,r*C+c)<0){tds+=`<${tag}></${tag}>`}}out.push(`<tr>${tds}</tr>`)}out.push("</table>");let pre=struct.outside.length?text(struct.outside):"";return(pre?`${pre}
2
+
3
+ `:"")+out.join(`
4
+ `)}
@@ -0,0 +1,34 @@
1
+ import type { Gray } from "./image.js";
2
+ import type { Box } from "./rec-preproc.js";
3
+ import type { Tok } from "./types.js";
4
+ export declare const N_FEAT_BASE = 33;
5
+ /** A word of a table line. `pos`: index in its line, `n`: words in its line. */
6
+ export type Word = {
7
+ box: Box;
8
+ text: string;
9
+ line: number;
10
+ pos: number;
11
+ n: number;
12
+ };
13
+ /** A line of a table block: its box on the page and its tokens. */
14
+ export type TableLine = {
15
+ box: Box;
16
+ toks: readonly Tok[];
17
+ };
18
+ /** What the recognizer's vocabulary says about tokens. */
19
+ export type WordText = {
20
+ isSpace(id: Tok[0]): boolean;
21
+ decode(toks: readonly Tok[]): string;
22
+ };
23
+ /** A table's box on its page: x0, y0, x1, y1. */
24
+ export type TableBox = readonly [number, number, number, number];
25
+ /** Words from lines, cut at the space tokens. A word's box spans its tokens' x positions at the line's height. */
26
+ export declare function wordsOf(lines: readonly TableLine[], text: WordText): Word[];
27
+ /** The words' boxes as a float32 [n, 4] array, as the reference stores them. */
28
+ export declare function boxesF32(words: readonly Word[]): Float32Array;
29
+ /** The union of float32 [n, 4] boxes. */
30
+ export declare function unionBox(boxes: Float32Array): TableBox;
31
+ /** [N, N_FEAT_BASE] float32 features for the words of one table; `bbox` is the table's box on `gray`, the page. */
32
+ export declare function wordFeatures(words: readonly Word[], gray: Gray, bbox: TableBox): Float32Array;
33
+ /** Word boxes (float32 [N, 4], px) in median line heights from the top-left word corner: the model's box input. */
34
+ export declare function normBoxes(boxes: Float32Array): Float32Array;
@@ -0,0 +1 @@
1
+ import{medianF32}from"./order-post.js";import{LETTER,UPPER}from"./py-text.js";import{isDigit,pyLen,pyStrip}from"./py-unicode.js";import{item}from"./util.js";let f=Math.fround;export let N_FEAT_BASE=33;let PUNCT=/^\p{P}$/u;let SYMBOL=/^\p{S}$/u;export function wordsOf(lines,text){let out=[];for(const[li,{box,toks}]of lines.entries()){let h=Math.max(1,f(box[3]-box[1]));let words=[];let cur=[];for(let tk of toks){if(text.isSpace(tk[0])){if(cur.length)words.push(cur);cur=[]}else{cur.push(tk)}}if(cur.length)words.push(cur);let ws=[];for(let w of words){let xs=w.map((t)=>t[1]);let t=pyStrip(text.decode(w));if(!t)continue;let x0=Math.max(box[0],Math.min(...xs)-0.35*h);let x1=Math.min(box[2],Math.max(...xs)+0.35*h);if(x1<=x0){x0=Math.min(...xs)-0.3*h;x1=Math.max(...xs)+0.3*h}ws.push({box:[x0,box[1],x1,box[3]],text:t,line:li,pos:0,n:0})}for(const[k,w]of ws.entries()){w.pos=k;w.n=ws.length}out.push(...ws)}return out}export function boxesF32(words){let out=new Float32Array(words.length*4);for(const[i,w]of words.entries())out.set(w.box,i*4);return out}export function unionBox(boxes){let[x0,y0,x1,y1]=[1/0,1/0,-1/0,-1/0];for(let i=0;i<boxes.length;i+=4){x0=Math.min(x0,item(boxes,i));y0=Math.min(y0,item(boxes,i+1));x1=Math.max(x1,item(boxes,i+2));y1=Math.max(y1,item(boxes,i+3))}return[x0,y0,x1,y1]}function textFeatures(t){let tot=[0,0,0,0,0,0];let bump=(k,on)=>{tot[k]=(tot[k]??0)+(on?1:0)};for(let c of t||" "){bump(0,isDigit(c));bump(1,LETTER.test(c));bump(2,UPPER.test(c));bump(3,PUNCT.test(c));bump(4,SYMBOL.test(c));bump(5,(c.codePointAt(0)??0)>11903)}let n=Math.max(pyLen(t),1);return[...tot.slice(0,5).map((v)=>v/n),tot[5]?1:0]}function rule(ink,[rw,rh,ox,oy],[x0,x1,y0,y1]){let r0=Math.max(Math.trunc(y0)-oy,0);let r1=Math.min(Math.ceil(y1)-oy,rh);let c0=Math.max(Math.trunc(x0)-ox,0);let c1=Math.min(Math.ceil(x1)-ox,rw);if(r1<=r0||c1-c0<2)return null;let j=0;let best=-1;for(let r=r0;r<r1;r++){let sum=0;for(let c=c0;c<c1;c++)sum+=item(ink,r*rw+c);if(sum/(c1-c0)>best){best=sum/(c1-c0);j=r-r0}}if(best<0.7)return null;let row=new Uint8Array(rw);for(let r=Math.max(r0+j-1,0);r<Math.min(r0+j+2,rh);r++)for(let c=0;c<rw;c++)if(item(ink,r*rw+c))row[c]=1;let mid=c0+c1>>1;if(!row[mid])return null;let a=mid;while(a>0&&row[a-1])a--;let b=mid+1;while(b<rw&&row[b])b++;return[a+ox,b+ox]}export function wordFeatures(words,gray,bbox){let n=words.length;let out=new Float32Array(n*N_FEAT_BASE);if(n===0)return out;let boxes=boxesF32(words);let X0=(i)=>item(boxes,i*4);let Y0=(i)=>item(boxes,i*4+1);let X1=(i)=>item(boxes,i*4+2);let Y1=(i)=>item(boxes,i*4+3);let rawH=Array.from({length:n},(_,i)=>f(Y1(i)-Y0(i)));let hs=rawH.map((h)=>Math.max(h,1));let hm=medianF32(rawH);const[tx0,ty0,tx1,ty1]=bbox;let tw=Math.max(tx1-tx0,1);let th=Math.max(ty1-ty0,1);let set=(i,col,v)=>{out[i*N_FEAT_BASE+col]=v};for(const[i,w]of words.entries()){set(i,0,f(f(X0(i)-f(tx0))/f(tw)));set(i,1,f(f(Y0(i)-f(ty0))/f(th)));set(i,2,f(f(X1(i)-f(tx0))/f(tw)));set(i,3,f(f(Y1(i)-f(ty0))/f(th)));set(i,4,f(f(f(X0(i)-f(tx0))/hm)/50));set(i,5,f(f(f(Y0(i)-f(ty0))/hm)/50));set(i,6,f(f(f(X1(i)-X0(i))/hm)/20));set(i,7,f(item(hs,i)/hm));let t=w.text;set(i,8,Math.log1p(pyLen(t))/4);let first=[...t][0];set(i,14,first!==undefined&&isDigit(first)?1:0);set(i,15,t.endsWith(":")?1:0);set(i,16,w.pos/Math.max(w.n-1,1));set(i,17,w.pos===0?1:0);set(i,18,w.pos===w.n-1?1:0);let tf=textFeatures(t);for(let k=0;k<5;k++)set(i,9+k,item(tf,k));set(i,25,item(tf,5))}let byLine=new Map;for(const[i,w]of words.entries())byLine.set(w.line,[...byLine.get(w.line)??[],i]);for(let line of byLine.values()){for(const[k,i]of line.entries()){let h=item(hs,i);set(i,19,k>0?Math.min(f(f(X0(i)-X1(item(line,k-1)))/h),10)/10:1);set(i,20,k+1<line.length?Math.min(f(f(X0(item(line,k+1))-X1(i))/h),10)/10:1)}}addRulingFeatures(out,{boxes,hs,gray,bbox,tw});return out}function addRulingFeatures(out,{boxes,hs,gray,bbox,tw}){const[tx0,ty0,tx1,ty1]=bbox;const{width:W,height:H}=gray;let m=Math.max(...hs);let ox=Math.max(Math.trunc(tx0-m),0);let oy=Math.max(Math.trunc(ty0-m),0);let rw=Math.min(Math.ceil(tx1+m),W)-ox;let rh=Math.min(Math.ceil(ty1+m),H)-oy;if(rw<=0||rh<=0)return;let ink=new Uint8Array(rw*rh);let ii=new Int32Array((rh+1)*(rw+1));for(let y=0;y<rh;y++){let run=0;for(let x=0;x<rw;x++){let dark=item(gray.data,(oy+y)*W+ox+x)<128?1:0;ink[y*rw+x]=dark;run+=dark;ii[(y+1)*(rw+1)+x+1]=item(ii,y*(rw+1)+x+1)+run}}let clip=(v,hi)=>Math.min(Math.max(v,0),hi);let strip=(a0,b0,a1,b1)=>{let c0=clip(Math.floor(f(a0-ox)),rw);let r0=clip(Math.floor(f(b0-oy)),rh);let c1=clip(Math.ceil(f(a1-ox)),rw);let r1=clip(Math.ceil(f(b1-oy)),rh);let area=(c1-c0)*(r1-r0);let at=(r,c)=>item(ii,r*(rw+1)+c);return area>0?(at(r1,c1)-at(r0,c1)-at(r1,c0)+at(r0,c0))/area:0};let k=(c,h)=>f(f(c)*h);for(const[i,h]of hs.entries()){let x0=item(boxes,i*4);let y0=item(boxes,i*4+1);let x1=item(boxes,i*4+2);let y1=item(boxes,i*4+3);let set=(col,v)=>{out[i*N_FEAT_BASE+col]=v};set(21,strip(x0,f(y0-k(0.45,h)),x1,f(y0-k(0.1,h))));set(22,strip(x0,f(y1+k(0.1,h)),x1,f(y1+k(0.45,h))));set(23,strip(f(x0-k(0.5,h)),y0,f(x0-k(0.1,h)),y1));set(24,strip(f(x1+k(0.1,h)),y0,f(x1+k(0.5,h)),y1));set(32,1);let spans=[[f(y1+k(0.05,h)),f(y1+k(0.8,h))],[f(y0-k(0.8,h)),f(y0-k(0.05,h))]];for(const[side,[lo,hi]]of spans.entries()){let r=rule(ink,[rw,rh,ox,oy],[x0,x1,lo,hi]);if(r){set(26+3*side,1);set(27+3*side,Math.min((x0-r[0])/tw,1));set(28+3*side,Math.min((r[1]-x1)/tw,1))}}}}export function normBoxes(boxes){let n=boxes.length/4;if(n===0)return new Float32Array(0);let heights=Array.from({length:n},(_,i)=>f(item(boxes,i*4+3)-item(boxes,i*4+1)));let hm=Math.max(medianF32(heights),1);const[ox,oy]=unionBox(boxes);return boxes.map((v,k)=>f(f(v-(k%2===0?ox:oy))/f(hm)))}
@@ -0,0 +1,15 @@
1
+ import type { Box } from "./rec-preproc.js";
2
+ /** The N x N matrices (same row, column, cell) of the lines `blk`, from `tab` [3, n, n]. */
3
+ export declare function subTab(tab: Float32Array, n: number, blk: readonly number[]): Float32Array;
4
+ /**
5
+ * The lines of one cell are stacked (they overlap horizontally). When the cell
6
+ * head joins side-by-side lines in more than 10% of its cells, it has failed on
7
+ * this table and the geometric assembly is used instead. `tab` is [3, k, k] for
8
+ * the k lines of `boxes`.
9
+ */
10
+ export declare function headsPlausible(boxes: readonly Box[], tab: Float32Array): boolean;
11
+ /**
12
+ * An HTML table from the order model's table heads. `tab` [3, k, k] holds the
13
+ * logits same row, same column, same cell for the k lines of one table block.
14
+ */
15
+ export declare function tableHtmlHeads(boxes: readonly Box[], texts: readonly string[], tab: Float32Array): string;
@@ -0,0 +1,2 @@
1
+ import{meanF32}from"./numeric.js";import{cluster,medianF32}from"./order-post.js";import{pyHtmlEscape}from"./py-text.js";import{item}from"./util.js";let f=Math.fround;function mapAt(m,key){let v=m.get(key);if(v===undefined)throw new RangeError(`no entry for ${String(key)}`);return v}export function subTab(tab,n,blk){if(tab.length!==3*n*n)throw new RangeError(`tab holds ${tab.length} values, want 3 * ${n} * ${n}`);let k=blk.length;let out=new Float32Array(3*k*k);for(let m=0;m<3;m++)for(const[a,i]of blk.entries())for(const[b,j]of blk.entries())out[(m*k+a)*k+b]=item(tab,(m*n+i)*n+j);return out}export function headsPlausible(boxes,tab){let k=boxes.length;let cells=cluster(tab.subarray(2*k*k,3*k*k),k);let bad=0;for(let c of cells){if(c.length<2)continue;let x0=c.map((i)=>item(boxes,i)[0]);let x1=c.map((i)=>item(boxes,i)[2]);let min=1/0;for(const[a,p]of x1.entries())for(const[b,q]of x1.entries())min=Math.min(min,f(Math.min(p,q)-Math.max(item(x0,a),item(x0,b))));if(min<0)bad++}return bad<=0.1*cells.length}export function tableHtmlHeads(boxes,texts,tab){let k=boxes.length;let cells=cluster(tab.subarray(2*k*k,3*k*k),k);let cb=cells.map((c)=>[Math.min(...c.map((i)=>item(boxes,i)[0])),Math.min(...c.map((i)=>item(boxes,i)[1])),Math.max(...c.map((i)=>item(boxes,i)[2])),Math.max(...c.map((i)=>item(boxes,i)[3]))]);let ctext=cells.map((c)=>c.toSorted((p,q)=>item(boxes,p)[1]-item(boxes,q)[1]||item(boxes,p)[0]-item(boxes,q)[0]).map((i)=>item(texts,i)).join(" "));let m=cells.length;let cellLogits=(plane)=>{let out=new Float32Array(m*m);for(let a=0;a<m;a++){for(let b=a+1;b<m;b++){let vals=[];for(let i of item(cells,a))for(let j of item(cells,b))vals.push(item(tab,(plane*k+i)*k+j));out[a*m+b]=out[b*m+a]=meanF32(vals)}}return out};let byMin=(axis)=>(g)=>Math.min(...g.map((i)=>item(cb,i)[axis]));let rows=cluster(cellLogits(0),m).toSorted((p,q)=>byMin(1)(p)-byMin(1)(q));let cols=cluster(cellLogits(1),m).toSorted((p,q)=>byMin(0)(p)-byMin(0)(q));let rowOf=new Map(rows.flatMap((g,r)=>g.map((c)=>[c,r])));let colOf=new Map(cols.flatMap((g,c)=>g.map((i)=>[i,c])));let centers=cols.map((g)=>medianF32(g.map((i)=>f(f(item(cb,i)[0]+item(cb,i)[2])/2))));let h=medianF32(boxes.map(([,y0,,y1])=>f(y1-y0)));let grid=new Map;for(let c=0;c<m;c++){let c0=mapAt(colOf,c);const[bx0,,bx2]=item(cb,c);let span=1;while(c0+span<cols.length&&f(bx0-f(h))<=item(centers,c0+span)&&item(centers,c0+span)<=f(bx2+f(h)))span++;let key=`${mapAt(rowOf,c)},${c0}`;let prev=grid.get(key);grid.set(key,prev?{span:Math.max(prev.span,span),text:`${prev.text} ${item(ctext,c)}`}:{span,text:item(ctext,c)})}let out=["<table>"];for(let r=0;r<rows.length;r++){let tag=r===0&&rows.length>1?"th":"td";let tds="";for(let c=0;c<cols.length;){let cell=grid.get(`${r},${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(`
2
+ `)}
@@ -0,0 +1,42 @@
1
+ import type { InferenceSession } from "onnxruntime-common";
2
+ import type { Gray, ImageOps } from "./image.js";
3
+ import type { ColSpans } from "./table-decode.js";
4
+ import type { TableLine, WordText } from "./table-features.js";
5
+ import type { TensorCtor } from "./types.js";
6
+ /** The feature count the port builds for tsr_rel.onnx: the word features and the split features. */
7
+ export declare const N_FEAT: number;
8
+ /** The key-value pairs of an ONNX model's `metadata_props` (ModelProto field 14), read from the file's bytes. */
9
+ export declare function onnxMetadata(bytes: Uint8Array): Map<string, string>;
10
+ /** The feature count of a tsr_rel model and its word-id buckets (0 when it has no word-text input). */
11
+ export type TsrRelInfo = {
12
+ nFeat: number;
13
+ nVocab: number;
14
+ };
15
+ /**
16
+ * What the reference reads from the session: the model's "feat" width, and the
17
+ * "n_vocab" metadata when the model has a "wid" input. onnxruntime-node does not
18
+ * expose model metadata, so the model file's bytes are read for it.
19
+ */
20
+ export declare function tsrRelInfo(rel: InferenceSession, modelBytes: Uint8Array): TsrRelInfo;
21
+ /** The tsr_rel session with what `tsrRelInfo` read from it, and the optional tsr_split and tsr_refine sessions. */
22
+ export type TsrSessions = TsrRelInfo & {
23
+ rel: InferenceSession;
24
+ split?: InferenceSession;
25
+ refine?: InferenceSession;
26
+ };
27
+ /** Reads tables with tsr_rel.onnx; `colSpans` is meta.json's "tsr_rel_span" (default "geo"). */
28
+ export declare class TableReader {
29
+ private readonly Tensor;
30
+ private readonly sessions;
31
+ private readonly ops;
32
+ private readonly colSpans;
33
+ constructor(Tensor: TensorCtor, sessions: TsrSessions, ops: ImageOps, colSpans?: ColSpans);
34
+ /**
35
+ * HTML for one table block, or null when it has fewer than two words or two
36
+ * rows and columns. `lines`: the block's lines on `gray`; `mirror`: a
37
+ * right-to-left page, whose table is read mirrored, as a left-to-right one.
38
+ */
39
+ read(gray: Gray, lines: readonly TableLine[], text: WordText, mirror?: boolean): Promise<string | null>;
40
+ /** The feature and box inputs of tsr_rel.onnx: split features only for a model that takes more than the word features. */
41
+ private inputs;
42
+ }
@@ -0,0 +1 @@
1
+ export class TableReader{Tensor;sessions;ops;colSpans;constructor(Tensor,sessions,ops,colSpans="geo"){this.Tensor=Tensor;this.sessions=sessions;this.ops=ops;this.colSpans=colSpans}async read(gray,lines,text,mirror=false){let words=wordsOf(lines,text);if(words.length<2)return null;let page=mirror?mirrorWords(words,gray):gray;let boxes=boxesF32(words);let inputs=await this.inputs(words,page,boxes);const{rel,refine}=this.sessions;const{nVocab}=this.sessions;const{feat,box,texts}=inputs;let ids=nVocab?BigInt64Array.from(wordIds(texts,nVocab),BigInt):undefined;let wid=ids&&new this.Tensor("int64",ids,[1,words.length]);let res=await rel.run(wid?{feat,box,wid}:{feat,box});let pair=output(res,"pair");let tag=output(res,"tag");if(refine){let tfeat=refineTextFeatures(inputs.texts);let out=await refine.run({pair,tag,box:inputs.box,feat:inputs.feat,tfeat:new this.Tensor("float32",tfeat,[1,words.length,N_REFINE_TEXT])});tag=output(out,"tag_out")}let struct=decodeTable(floats(pair),floats(tag),boxes,this.colSpans,inputs.texts);return struct?structHtml(struct,words):null}async inputs(words,page,boxes){let n=words.length;const{nFeat,split}=this.sessions;if(nFeat>N_FEAT)throw new RangeError(`tsr_rel.onnx takes ${nFeat} features, the port builds ${N_FEAT}`);let bbox=unionBox(boxes);let base=wordFeatures(words,page,bbox);let feat=base;let width=N_FEAT_BASE;if(nFeat>N_FEAT_BASE){let heights=Array.from({length:n},(_,i)=>f(item(boxes,i*4+3)-item(boxes,i*4+1)));let maps=split?await splitMaps(split,this.Tensor,this.ops,page,bbox,medianF32(heights)):null;let extra=splitFeatures(boxes,maps);width=N_FEAT;feat=new Float32Array(n*width);for(let i=0;i<n;i++){feat.set(base.subarray(i*N_FEAT_BASE,(i+1)*N_FEAT_BASE),i*width);feat.set(extra.subarray(i*N_SPLIT,(i+1)*N_SPLIT),i*width+N_FEAT_BASE)}}if(nFeat<width){let cut=new Float32Array(n*nFeat);for(let i=0;i<n;i++)cut.set(feat.subarray(i*width,i*width+nFeat),i*nFeat);feat=cut;width=nFeat}return{feat:new this.Tensor("float32",feat,[1,n,width]),box:new this.Tensor("float32",normBoxes(boxes),[1,n,4]),texts:words.map((w)=>w.text)}}}import{medianF32}from"./order-post.js";import{decodeTable,structHtml}from"./table-decode.js";import{N_FEAT_BASE,boxesF32,normBoxes,unionBox,wordFeatures,wordsOf}from"./table-features.js";import{N_SPLIT,splitFeatures,splitMaps}from"./table-split.js";import{N_REFINE_TEXT,refineTextFeatures,wordIds}from"./table-text.js";import{floats,inputShape,item,output}from"./util.js";let f=Math.fround;export let N_FEAT=N_FEAT_BASE+N_SPLIT;export function onnxMetadata(bytes){let text=new TextDecoder;let out=new Map;let varint=(from)=>{let v=0;for(let p=from,shift=0;p<bytes.length;p++,shift+=7){let b=item(bytes,p);v+=(b&127)*2**shift;if(!(b&128))return[v,p+1]}throw new RangeError("onnxMetadata: truncated varint")};let fields=(from,to,visit)=>{let p=from;while(p<to){const[tag,afterTag]=varint(p);p=afterTag;let wire=tag&7;if(wire===0){p=varint(p)[1]}else if(wire===1||wire===5){p+=wire===1?8:4}else if(wire===2){const[len,start]=varint(p);if(start+len>to)throw new RangeError("onnxMetadata: a field runs past the end");visit(Math.floor(tag/8),start,start+len);p=start+len}else{throw new RangeError(`onnxMetadata: wire type ${wire}`)}}};fields(0,bytes.length,(field,start,end)=>{if(field!==14)return;let entry={key:"",value:""};fields(start,end,(inner,s,e)=>{if(inner===1)entry.key=text.decode(bytes.subarray(s,e));if(inner===2)entry.value=text.decode(bytes.subarray(s,e))});out.set(entry.key,entry.value)});return out}export function tsrRelInfo(rel,modelBytes){let nFeat=inputShape(rel,"feat")?.at(-1);if(typeof nFeat!=="number")throw new Error("tsr_rel.onnx: the feat input has no fixed width");let nVocab=rel.inputNames.length<3?0:Number(onnxMetadata(modelBytes).get("n_vocab")??0);return{nFeat,nVocab}}function mirrorWords(words,gray){const{width:W,height:H}=gray;let flipped=new Uint8Array(gray.data.length);for(let y=0;y<H;y++)for(let x=0;x<W;x++)flipped[y*W+x]=item(gray.data,y*W+(W-1-x));for(let w of words){const[x0,y0,x1,y1]=w.box;w.box=[W-x1,y0,W-x0,y1]}let sorted=words.toSorted((a,b)=>a.line-b.line||a.box[0]-b.box[0]);words.splice(0,words.length,...sorted);let byLine=new Map;for(let w of words)byLine.set(w.line,[...byLine.get(w.line)??[],w]);for(let ws of byLine.values()){for(const[k,w]of ws.entries()){w.pos=k;w.n=ws.length}}return{data:flipped,width:W,height:H}}
@@ -0,0 +1,44 @@
1
+ import type { InferenceSession } from "onnxruntime-common";
2
+ import type { Gray, ImageOps } from "./image.js";
3
+ import type { TableBox } from "./table-features.js";
4
+ import type { TensorCtor } from "./types.js";
5
+ export declare const N_SPLIT = 8;
6
+ /**
7
+ * The model's row separator, column separator and header probability maps, each
8
+ * [h, w] at 1/2 of the scaled crop, stacked: `prob` is [3, h, w]. `scale` is
9
+ * map px per page px; `origin` the crop's top-left corner in page px.
10
+ */
11
+ export type SplitMaps = {
12
+ prob: Float32Array;
13
+ h: number;
14
+ w: number;
15
+ scale: number;
16
+ origin: readonly [number, number];
17
+ };
18
+ /** The model's input: the table crop scaled to text 12 px high, as ink, padded to a multiple of 32. */
19
+ export type SplitInput = {
20
+ x: Float32Array;
21
+ /** The padded size. */
22
+ ph: number;
23
+ pw: number;
24
+ /** The scaled crop's size. */
25
+ nh: number;
26
+ nw: number;
27
+ /** Scaled px per page px. */
28
+ scale: number;
29
+ origin: readonly [number, number];
30
+ };
31
+ /**
32
+ * The tsr_split.onnx input for the table at `bbox` (page px) of `gray`, or null
33
+ * for a crop too small to read. `lineH` is the median word height.
34
+ */
35
+ export declare function splitInput(ops: ImageOps, gray: Gray, bbox: TableBox, lineH: number): SplitInput | null;
36
+ /** tsr_split.onnx on the table at `bbox` (page px) of `gray`, or null for a crop too small to read. */
37
+ export declare function splitMaps(session: InferenceSession, Tensor: TensorCtor, ops: ImageOps, gray: Gray, bbox: TableBox, lineH: number): Promise<SplitMaps | null>;
38
+ /**
39
+ * [N, N_SPLIT] features of word `boxes` (float32 [N, 4], page px) from
40
+ * `splitMaps`: row separator just below / above the word, column separator just
41
+ * left / right of it, a row (column) separator through it, its mean header
42
+ * probability, and 1 (present). Zeros (absent) when `maps` is null.
43
+ */
44
+ export declare function splitFeatures(boxes: Float32Array, maps: SplitMaps | null): Float32Array;
@@ -0,0 +1 @@
1
+ import{pyRound}from"./det-post.js";import{inkOf}from"./image.js";import{floats,item,output}from"./util.js";let f=Math.fround;export let N_SPLIT=8;let SPLIT_TEXT_PX=12;let SPLIT_MAX_SIDE=1024;let SPLIT_PAD_TO=32;let SPLIT_STRIDE=2;let ceilDiv=(a,b)=>-Math.floor(-a/b);export function splitInput(ops,gray,bbox,lineH){const{width:W,height:H}=gray;let m=1.5*lineH;let x0=Math.max(Math.trunc(f(bbox[0]-f(m))),0);let y0=Math.max(Math.trunc(f(bbox[1]-f(m))),0);let x1=Math.min(Math.ceil(f(bbox[2]+f(m))),W);let y1=Math.min(Math.ceil(f(bbox[3]+f(m))),H);let cw=x1-x0;let ch=y1-y0;if(cw<=0||ch<=0)return null;let s=SPLIT_TEXT_PX/Math.max(lineH,1);if(Math.max(cw,ch)*s>SPLIT_MAX_SIDE)s=SPLIT_MAX_SIDE/Math.max(cw,ch);let nh=Math.max(1,pyRound(ch*s));let nw=Math.max(1,pyRound(cw*s));if(Math.min(nh,nw)<16)return null;let crop=new Uint8Array(cw*ch);for(let y=0;y<ch;y++)crop.set(gray.data.subarray((y0+y)*W+x0,(y0+y)*W+x1),y*cw);let small=ops.resize({data:crop,width:cw,height:ch},nw,nh,s<1?"area":"linear");let ph=ceilDiv(nh,SPLIT_PAD_TO)*SPLIT_PAD_TO;let pw=ceilDiv(nw,SPLIT_PAD_TO)*SPLIT_PAD_TO;let x=new Float32Array(ph*pw);let ink=inkOf(small).data;for(let y=0;y<nh;y++)x.set(ink.subarray(y*nw,(y+1)*nw),y*pw);return{x,ph,pw,nh,nw,scale:s,origin:[x0,y0]}}export async function splitMaps(session,Tensor,ops,gray,bbox,lineH){let input=splitInput(ops,gray,bbox,lineH);if(!input)return null;const{x,ph,pw,nh,nw,scale,origin}=input;let res=await session.run({x:new Tensor("float32",x,[1,1,ph,pw])});let out=output(res,item(session.outputNames,0));let logits=floats(out);const[,,h2=0,w2=0]=out.dims;let vh=ceilDiv(nh,SPLIT_STRIDE);let vw=ceilDiv(nw,SPLIT_STRIDE);if(vh>h2||vw>w2)throw new RangeError(`tsr_split map ${h2}x${w2} is smaller than ${vh}x${vw}`);let prob=new Float32Array(3*vh*vw);for(let c=0;c<3;c++)for(let y=0;y<vh;y++)for(let xx=0;xx<vw;xx++){let v=item(logits,(c*h2+y)*w2+xx);prob[(c*vh+y)*vw+xx]=f(1/f(1+f(Math.exp(f(-v)))))}return{prob,h:vh,w:vw,scale:scale/SPLIT_STRIDE,origin}}function band(P,[h,w],[a,b],[lo,hi]){let k=8;let cs=new Float32Array(h*(w+1));for(let r=0;r<h;r++)for(let c=0;c<w;c++)cs[r*(w+1)+c+1]=item(cs,r*(w+1)+c)+item(P,r*w+c);let clip=(v,top)=>Math.min(Math.max(v,0),top);return Array.from(a,(a0,i)=>{let c0=clip(Math.floor(item(lo,i)),w);let c1=Math.max(clip(Math.ceil(item(hi,i)),w),Math.min(c0+1,w));let span=f(item(b,i)-a0);let best=-1/0;for(let j=0;j<k;j++){let r=Math.floor(f(a0+f(span*((j+0.5)/k))));let rr=clip(r,h-1);let v=f(item(cs,rr*(w+1)+c1)-item(cs,rr*(w+1)+c0))/Math.max(c1-c0,1);best=Math.max(best,r>=0&&r<h&&c1>c0?v:0)}return best})}export function splitFeatures(boxes,maps){let n=boxes.length/4;let out=new Float32Array(n*N_SPLIT);if(!maps||n===0)return out;const{prob,h:mh,w:mw,scale:s,origin}=maps;let plane=(c)=>prob.subarray(c*mh*mw,(c+1)*mh*mw);let pr=plane(0);let pc=plane(1);let ph=plane(2);let pcT=new Float32Array(mw*mh);for(let y=0;y<mh;y++)for(let x=0;x<mw;x++)pcT[x*mh+y]=item(pc,y*mw+x);let col=(j)=>Float32Array.from({length:n},(_,i)=>item(boxes,i*4+j));let scaled=(v,o)=>v.map((e)=>f(f(e-f(o))*f(s)));const[x0,x1]=[scaled(col(0),origin[0]),scaled(col(2),origin[0])];const[y0,y1]=[scaled(col(1),origin[1]),scaled(col(3),origin[1])];let h=y1.map((e,i)=>Math.max(f(e-item(y0,i)),1));let edge=(base,c)=>base.map((e,i)=>f(e+f(f(c)*item(h,i))));let rows=[mh,mw];let cols=[mw,mh];let put=(j,v)=>{for(const[i,e]of v.entries())out[i*N_SPLIT+j]=e};put(0,band(pr,rows,[edge(y1,-0.1),edge(y1,0.8)],[x0,x1]));put(1,band(pr,rows,[edge(y0,-0.8),edge(y0,0.1)],[x0,x1]));put(2,band(pcT,cols,[edge(x0,-2),edge(x0,0.1)],[y0,y1]));put(3,band(pcT,cols,[edge(x1,-0.1),edge(x1,2)],[y0,y1]));put(4,band(pr,rows,[edge(y0,0.3),edge(y1,-0.3)],[x0,x1]));put(5,band(pcT,cols,[edge(x0,0.2),edge(x1,-0.2)],[y0,y1]));put(6,band(ph,rows,[y0,y1],[x0,x1]));for(let i=0;i<n;i++)out[i*N_SPLIT+7]=1;return out}