ppu-indra-ocr 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/LICENSE-STATUS.md +112 -0
- package/NOTICE +20 -0
- package/README.md +830 -2
- package/cli/commands.d.ts +9 -0
- package/cli/commands.js +11 -0
- package/cli/help.d.ts +5 -0
- package/cli/help.js +50 -0
- package/cli/index.d.ts +2 -0
- package/cli/index.js +6 -0
- package/cli/io.d.ts +27 -0
- package/cli/io.js +6 -0
- package/cli/options.d.ts +19 -0
- package/cli/options.js +1 -0
- package/cli/run.d.ts +1 -0
- package/cli/run.js +9 -0
- package/coi-serviceworker.js +130 -0
- package/core/batch.d.ts +53 -0
- package/core/batch.js +1 -0
- package/core/indra-ocr.service.d.ts +65 -0
- package/core/indra-ocr.service.js +1 -0
- package/core/one-shot.d.ts +5 -0
- package/core/one-shot.js +1 -0
- package/core/opencv-image-ops.d.ts +10 -0
- package/core/opencv-image-ops.js +1 -0
- package/core/platform.d.ts +40 -0
- package/core/session-factory.d.ts +23 -0
- package/core/session-factory.js +1 -0
- package/exports.d.ts +15 -0
- package/exports.js +1 -0
- package/index.d.ts +11 -0
- package/index.js +1 -0
- package/indra/assemble.d.ts +22 -0
- package/indra/assemble.js +3 -0
- package/indra/det-post.d.ts +34 -0
- package/indra/det-post.js +1 -0
- package/indra/document.d.ts +36 -0
- package/indra/document.js +1 -0
- package/indra/image.d.ts +43 -0
- package/indra/image.js +1 -0
- package/indra/layout-post.d.ts +35 -0
- package/indra/layout-post.js +9 -0
- package/indra/lines.d.ts +19 -0
- package/indra/lines.js +1 -0
- package/indra/math.d.ts +54 -0
- package/indra/math.js +1 -0
- package/indra/numeric.d.ts +9 -0
- package/indra/numeric.js +1 -0
- package/indra/order-post.d.ts +37 -0
- package/indra/order-post.js +1 -0
- package/indra/pipeline.d.ts +65 -0
- package/indra/pipeline.js +1 -0
- package/indra/rec-preproc.d.ts +28 -0
- package/indra/rec-preproc.js +1 -0
- package/indra/recognize.d.ts +29 -0
- package/indra/recognize.js +1 -0
- package/indra/textlayer.d.ts +72 -0
- package/indra/textlayer.js +2 -0
- package/indra/ts-image-ops.d.ts +3 -0
- package/indra/ts-image-ops.js +1 -0
- package/indra/types.d.ts +101 -0
- package/indra/upright.d.ts +28 -0
- package/indra/upright.js +1 -0
- package/indra/util.d.ts +14 -0
- package/indra/util.js +1 -0
- package/indra/vocab.d.ts +14 -0
- package/indra/vocab.js +1 -0
- package/interface.d.ts +61 -0
- package/mobile/index.d.ts +26 -0
- package/mobile/index.js +1 -0
- package/mobile/indra-ocr.service.mobile.d.ts +11 -0
- package/mobile/indra-ocr.service.mobile.js +1 -0
- package/mobile/platform.mobile.d.ts +16 -0
- package/mobile/platform.mobile.js +1 -0
- package/model-catalogue.d.ts +38 -0
- package/model-catalogue.js +1 -0
- package/package.json +109 -4
- package/pdf/index.d.ts +31 -0
- package/pdf/index.js +1 -0
- package/pdf/pdfium.d.ts +27 -0
- package/pdf/pdfium.js +1 -0
- package/processor/indra-ocr.service.d.ts +28 -0
- package/processor/indra-ocr.service.js +1 -0
- package/processor/model-cache.d.ts +17 -0
- package/processor/model-cache.js +2 -0
- package/processor/platform.node.d.ts +13 -0
- package/processor/platform.node.js +1 -0
- package/utils.d.ts +36 -0
- package/utils.js +2 -0
- package/web/index.d.ts +26 -0
- package/web/index.js +1 -0
- package/web/indra-ocr.service.web.d.ts +15 -0
- package/web/indra-ocr.service.web.js +1 -0
- package/web/platform.web.d.ts +32 -0
- package/web/platform.web.js +1 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { FloatImage, Gray, ImageOps } from "./image.js";
|
|
2
|
+
export declare const OUT_STRIDE = 2;
|
|
3
|
+
/** The detector input (float32 ink map) and the scale from page to input pixels. */
|
|
4
|
+
export type DetInput = {
|
|
5
|
+
input: FloatImage;
|
|
6
|
+
scale: number;
|
|
7
|
+
};
|
|
8
|
+
/** Component labels (0 = background) and left, width, area per label. */
|
|
9
|
+
export type Components = {
|
|
10
|
+
labels: Int32Array;
|
|
11
|
+
count: number;
|
|
12
|
+
stats: Int32Array;
|
|
13
|
+
};
|
|
14
|
+
/** A detected line: x0, y0, x1, y1 in pixels, and the mean core probability. */
|
|
15
|
+
export type DetBox = [number, number, number, number, number];
|
|
16
|
+
/**
|
|
17
|
+
* Resize a page so its long side is `longSide` and pad it with white to a
|
|
18
|
+
* multiple of 32. Returns the float32 ink map the detector reads, and the scale.
|
|
19
|
+
*/
|
|
20
|
+
export declare function pageToInput(gray: Gray, longSide: number, ops: ImageOps): DetInput;
|
|
21
|
+
/**
|
|
22
|
+
* Decode the detector output for one page. `out` is [3, h, w]: core logit,
|
|
23
|
+
* distance to the line top, distance to the line bottom. Returns boxes in
|
|
24
|
+
* detector-input pixels, in the order OpenCV labels their components.
|
|
25
|
+
*/
|
|
26
|
+
export declare function decode(out: Float32Array, h: number, w: number, thresh?: number, minArea?: number): DetBox[];
|
|
27
|
+
/**
|
|
28
|
+
* 4-connected component labels, numbered like OpenCV: in raster order of each
|
|
29
|
+
* component's first pixel. Label 0 is the background. `stats` holds left,
|
|
30
|
+
* width and area for each label.
|
|
31
|
+
*/
|
|
32
|
+
export declare function connectedComponents4(mask: Uint8Array, h: number, w: number): Components;
|
|
33
|
+
/** Python's round(): half to even. */
|
|
34
|
+
export declare function pyRound(x: number): number;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{inkOf}from"./image.js";let CORE_X_SHRINK=0.15;export let OUT_STRIDE=2;let INPUT_MULTIPLE=32;export function pageToInput(gray,longSide,ops){const{width:w,height:h}=gray;let scale=longSide/Math.max(h,w);let nh=Math.max(1,pyRound(h*scale));let nw=Math.max(1,pyRound(w*scale));let page=gray;if(nh!==h||nw!==w)page=ops.resize(gray,nw,nh,scale<1?"area":"linear");let ph=Math.ceil(nh/INPUT_MULTIPLE)*INPUT_MULTIPLE;let pw=Math.ceil(nw/INPUT_MULTIPLE)*INPUT_MULTIPLE;let ink=inkOf(page);let data=new Float32Array(ph*pw);for(let y=0;y<nh;y++)data.set(ink.data.subarray(y*nw,(y+1)*nw),y*pw);return{input:{data,width:pw,height:ph},scale}}export function decode(out,h,w,thresh=0.5,minArea=2){let n=h*w;let prob=new Float32Array(n);let mask=new Uint8Array(n);for(let i=0;i<n;i++){prob[i]=Math.fround(1/Math.fround(1+Math.fround(Math.exp(-(out[i]??0)))));mask[i]=(prob[i]??0)>thresh?1:0}const{labels,count,stats}=connectedComponents4(mask,h,w);if(count<=1)return[];let s=OUT_STRIDE;let cnt=new Float64Array(count);let sumTop=new Float64Array(count);let sumBot=new Float64Array(count);let sumScore=new Float64Array(count);for(let y=0;y<h;y++){let ys=Math.fround((y+0.5)*s);for(let x=0;x<w;x++){let i=y*w+x;let k=labels[i]??0;if(k===0)continue;cnt[k]=(cnt[k]??0)+1;sumTop[k]=(sumTop[k]??0)+Math.fround(ys-(out[n+i]??0));sumBot[k]=(sumBot[k]??0)+Math.fround(ys+(out[2*n+i]??0));sumScore[k]=(sumScore[k]??0)+(prob[i]??0)}}let boxes=[];for(let k=1;k<count;k++){let area=stats[k*3+2]??0;if(area<minArea)continue;let c=Math.max(Math.fround(cnt[k]??0),1);let y0=(sumTop[k]??0)/c;let y1=(sumBot[k]??0)/c;let lh=Math.max(1,y1-y0);let ex=Math.min(CORE_X_SHRINK*lh,0.5*lh);let left=stats[k*3]??0;let width=stats[k*3+1]??0;boxes.push([Math.fround(left*s-ex),Math.fround(y0),Math.fround((left+width)*s+ex),Math.fround(y1),Math.fround((sumScore[k]??0)/c)])}return boxes}export function connectedComponents4(mask,h,w){let prov=new Int32Array(h*w);let parent=[0];let find=(a)=>{let r=a;while(parent[r]!==r)r=parent[r]??r;while(parent[a]!==r){let next=parent[a]??r;parent[a]=r;a=next}return r};for(let y=0;y<h;y++){for(let x=0;x<w;x++){let i=y*w+x;if(!mask[i])continue;let up=y>0?prov[i-w]??0:0;let left=x>0?prov[i-1]??0:0;if(!up&&!left){parent.push(parent.length);prov[i]=parent.length-1}else if(up&&left){let a=find(up);let b=find(left);if(a!==b)parent[Math.max(a,b)]=Math.min(a,b);prov[i]=Math.min(a,b)}else{prov[i]=up||left}}}let final=new Int32Array(parent.length);let count=1;let labels=new Int32Array(h*w);let lefts=[0];let rights=[0];let areas=[0];for(let y=0;y<h;y++){for(let x=0;x<w;x++){let i=y*w+x;if(!prov[i])continue;let root=find(prov[i]??0);if(!final[root]){final[root]=count++;lefts.push(x);rights.push(x);areas.push(0)}let k=final[root]??0;labels[i]=k;if(x<(lefts[k]??x))lefts[k]=x;if(x>(rights[k]??x))rights[k]=x;areas[k]=(areas[k]??0)+1}}let stats=new Int32Array(count*3);for(let k=1;k<count;k++){let left=lefts[k]??0;stats[k*3]=left;stats[k*3+1]=(rights[k]??left)-left+1;stats[k*3+2]=areas[k]??0}return{labels,count,stats}}export function pyRound(x){let r=Math.round(x);return Math.abs(x%1)===0.5&&r%2!==0?r-1:r}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { IndraPipeline } from "./pipeline.js";
|
|
2
|
+
import type { Box } from "./rec-preproc.js";
|
|
3
|
+
import type { PdfPageSource, TextLine } from "./textlayer.js";
|
|
4
|
+
import type { Page, Tok } from "./types.js";
|
|
5
|
+
/** auto: text layer where sound, OCR elsewhere. ocr: always OCR. text: the text layer even when the checks fail. */
|
|
6
|
+
export type PdfMode = "auto" | "ocr" | "text";
|
|
7
|
+
export type PdfPageOptions = {
|
|
8
|
+
/** Default "auto". */
|
|
9
|
+
mode?: PdfMode;
|
|
10
|
+
/** Render resolution for OCR. Default 200. */
|
|
11
|
+
dpi?: number;
|
|
12
|
+
/** Keep the PDF content order when it is coherent. Default true. */
|
|
13
|
+
pdfOrder?: boolean;
|
|
14
|
+
/** OCR detected lines that hold no text-layer characters (text inside images). Default true. */
|
|
15
|
+
imageOcr?: boolean;
|
|
16
|
+
};
|
|
17
|
+
/** Tokens per detected line, and the characters outside every line. */
|
|
18
|
+
export type AssignedRuns = {
|
|
19
|
+
toks: Tok[][];
|
|
20
|
+
lost: number;
|
|
21
|
+
};
|
|
22
|
+
/** Whether the recognizers know at least READABLE_MIN of the letters in these runs. */
|
|
23
|
+
export declare function readable(pipeline: IndraPipeline, runs: readonly TextLine[]): boolean;
|
|
24
|
+
/** Unicode bidi base direction: most strong characters are right-to-left. */
|
|
25
|
+
export declare function rightToLeft(tokens: readonly Tok[]): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Text-layer characters per detected line (`boxes` in pixels, `k` pixels per
|
|
28
|
+
* point). Each character goes to the smallest box that contains its center; a
|
|
29
|
+
* space follows the character before it. Inside a line, each run's part keeps
|
|
30
|
+
* the PDF order, and the parts are ordered by x (right to left in an RTL line).
|
|
31
|
+
*/
|
|
32
|
+
export declare function assignRuns(runs: readonly TextLine[], boxes: readonly Box[], k: number): AssignedRuns;
|
|
33
|
+
/** One PDF page: the text layer when it can be trusted, OCR otherwise. */
|
|
34
|
+
export declare function pdfPage(pipeline: IndraPipeline, page: PdfPageSource, options?: PdfPageOptions): Promise<Page>;
|
|
35
|
+
/** The bytes say PDF: "%PDF-" in the first 1024 bytes (the header may follow a little junk). */
|
|
36
|
+
export declare function isPdf(bytes: ArrayBuffer | Uint8Array): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{decodeToks}from"./lines.js";import{MATH_MIN_CONF}from"./math.js";import{cropLine}from"./rec-preproc.js";import{BROKEN_FONT_MAP,readTextLayer}from"./textlayer.js";import{isPySpace,item}from"./util.js";let CHECK_DPI=72;let MAX_PAGE_PIXELS=1e8;let READABLE_MIN=0.9;let LETTER=/^\p{L}$/u;export function readable(pipeline,runs){let letters=runs.flatMap((r)=>[...r.text].filter((c)=>LETTER.test(c)));if(!letters.length)return true;let cjk=pipeline.vocabCjk?.index;let known=letters.filter((c)=>pipeline.vocab.index.has(c)||cjk?.has(c)).length;return known>=READABLE_MIN*letters.length}let RTL=new RegExp("^[\\u0590-\\u08ff\\ufb1d-\\ufdff\\ufe70-\\ufefe]$","u");export function rightToLeft(tokens){let rtl=0;let ltr=0;for(const[c]of tokens){if(typeof c!=="string"||c.length!==1)continue;if(RTL.test(c))rtl++;else if(LETTER.test(c))ltr++}return rtl>ltr}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(const[idx,run]of runs.entries()){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,pdfOrder=true,imageOcr=true}=options;let t={};let note="mode=ocr";let turn=true;if(mode!=="ocr"){let s=CHECK_DPI/72;let tl=timed(t,"text_ms",()=>readTextLayer(page,page.render(s),s));let unreadable=tl.reason!==BROKEN_FONT_MAP&&!readable(pipeline,tl.lines);if(tl.lines.length&&(tl.trusted||mode==="text"||unreadable)){return textPage(pipeline,page,tl,t,dpi,pdfOrder,imageOcr)}note=tl.reason;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,pdfOrder,imageOcr){let k=pageScale(page,dpi);let gray=timed(t,"render_ms",()=>page.render(k));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});let empty=rec.flatMap((r,i)=>r?[]:[i]);let source="text";if(empty.length&&imageOcr&&readable(pipeline,tl.lines)){t0=performance.now();let read=await pipeline.recognize(gray,empty.map((i)=>item(boxes,i)));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 out=await pipeline.assemble(gray.width,gray.height,keep.map((i)=>item(boxes,i)),keep.map((i)=>item(rec,i)??{text:"",conf:0,toks:[]}),t,pdfOrder);out.source=source;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}
|
package/indra/image.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** An 8-bit grayscale image, row-major, one byte per pixel (0 = black). */
|
|
2
|
+
export type Gray = {
|
|
3
|
+
data: Uint8Array;
|
|
4
|
+
width: number;
|
|
5
|
+
height: number;
|
|
6
|
+
};
|
|
7
|
+
/** A single-channel float32 image, row-major. */
|
|
8
|
+
export type FloatImage = {
|
|
9
|
+
data: Float32Array;
|
|
10
|
+
width: number;
|
|
11
|
+
height: number;
|
|
12
|
+
};
|
|
13
|
+
/** A 2x3 affine matrix, row-major: [a, b, c, d, e, f] maps (x, y) to (ax+by+c, dx+ey+f). */
|
|
14
|
+
export type Affine = [number, number, number, number, number, number];
|
|
15
|
+
export type Interpolation = "area" | "linear";
|
|
16
|
+
/**
|
|
17
|
+
* The image operations the Indra pipeline needs, with OpenCV semantics
|
|
18
|
+
* (`cv2.resize`, `cv2.warpAffine`). The opencv engine implements them with
|
|
19
|
+
* OpenCV.js and matches the Python reference byte for byte; the canvas-native
|
|
20
|
+
* engine implements them in plain TypeScript.
|
|
21
|
+
*/
|
|
22
|
+
export type ImageOps = {
|
|
23
|
+
/** `cv2.resize(src, (width, height), interpolation)` on uint8. */
|
|
24
|
+
resize(src: Gray, width: number, height: number, interpolation: Interpolation): Gray;
|
|
25
|
+
/** `cv2.warpAffine(src, m, (width, height), INTER_LINEAR, BORDER_REPLICATE)` on uint8. */
|
|
26
|
+
warpReplicate(src: Gray, m: Affine, width: number, height: number): Gray;
|
|
27
|
+
/** `cv2.warpAffine(src, m, (width, height))` on float32: linear, zero border. */
|
|
28
|
+
warpFloat(src: FloatImage, m: Affine, width: number, height: number): FloatImage;
|
|
29
|
+
};
|
|
30
|
+
/** `cv2.getRotationMatrix2D(center, degrees, 1.0)`: counter-clockwise about the center. */
|
|
31
|
+
export declare function rotationMatrix(cx: number, cy: number, degrees: number): Affine;
|
|
32
|
+
/** `1 - gray / 255` as float32: the ink map the models read (1 = ink). */
|
|
33
|
+
export declare function inkOf(gray: Gray): FloatImage;
|
|
34
|
+
/**
|
|
35
|
+
* 8-bit gray from RGBA pixels, with OpenCV's fixed-point BT.601 weights
|
|
36
|
+
* (cv.cvtColor RGBA2GRAY): Y = (4899 R + 9617 G + 1868 B + 8192) >> 14.
|
|
37
|
+
* Alpha is ignored, as cv2.imread ignores it.
|
|
38
|
+
*/
|
|
39
|
+
export declare function grayFromRgba(rgba: {
|
|
40
|
+
data: ArrayLike<number>;
|
|
41
|
+
width: number;
|
|
42
|
+
height: number;
|
|
43
|
+
}): Gray;
|
package/indra/image.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function rotationMatrix(cx,cy,degrees){let rad=degrees*Math.PI/180;let a=Math.cos(rad);let b=Math.sin(rad);return[a,b,(1-a)*cx-b*cy,-b,a,b*cx+(1-a)*cy]}export function inkOf(gray){let data=new Float32Array(gray.data.length);for(let i=0;i<data.length;i++){data[i]=Math.fround(1-Math.fround((gray.data[i]??0)/255))}return{data,width:gray.width,height:gray.height}}export function grayFromRgba(rgba){let n=rgba.width*rgba.height;let data=new Uint8Array(n);let d=rgba.data;for(let i=0;i<n;i++){let p=i*4;data[i]=(d[p]??0)*4899+(d[p+1]??0)*9617+(d[p+2]??0)*1868+8192>>14}return{data,width:rgba.width,height:rgba.height}}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { BlockLabel } from "./order-post.js";
|
|
2
|
+
import type { Box } from "./rec-preproc.js";
|
|
3
|
+
/** A layout block: its label, the union of its line boxes, and its lines' text. */
|
|
4
|
+
export type LayoutBlock = {
|
|
5
|
+
label: BlockLabel;
|
|
6
|
+
bbox: Box;
|
|
7
|
+
text: string;
|
|
8
|
+
};
|
|
9
|
+
/** One line split into table cells: each cell's box and text. */
|
|
10
|
+
export type Cell = {
|
|
11
|
+
box: Box;
|
|
12
|
+
text: string;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Join the lines of one paragraph. "tumori-" + "genesis" -> "tumorigenesis";
|
|
16
|
+
* a line break between two CJK characters takes no space.
|
|
17
|
+
*/
|
|
18
|
+
export declare function joinLines(texts: readonly string[]): string;
|
|
19
|
+
/** Runs of the reading order with a positive same-block logit between neighbours. */
|
|
20
|
+
export declare function splitBlocks(order: readonly number[], same: Float32Array, n: number): number[][];
|
|
21
|
+
/**
|
|
22
|
+
* An HTML table from cell lines (one text line per cell). A first row that is
|
|
23
|
+
* one line across most of the table is a title and goes before the table. The
|
|
24
|
+
* first remaining row is the header (<th>).
|
|
25
|
+
*/
|
|
26
|
+
export declare function tableHtml(boxes: readonly Box[], texts: readonly string[]): string;
|
|
27
|
+
/** The layout blocks behind pageMarkdown, in reading order. */
|
|
28
|
+
export declare function pageBlocks(boxes: readonly Box[], texts: readonly string[], order: readonly number[], cls: Float32Array, same: Float32Array): LayoutBlock[];
|
|
29
|
+
/**
|
|
30
|
+
* Markdown for one page: section headers as "## ", paragraphs joined, lists one
|
|
31
|
+
* item per line, tables as HTML from their cell lines, display math as $$...$$.
|
|
32
|
+
* Page headers and footers are left out unless `keepFurniture`. `cells` maps a
|
|
33
|
+
* line to its table cells when the line holds several.
|
|
34
|
+
*/
|
|
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;
|
|
@@ -0,0 +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("&","&").replaceAll("<","<").replaceAll(">",">");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
|
+
|
|
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(`
|
|
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(`
|
|
8
|
+
|
|
9
|
+
`)}
|
package/indra/lines.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Box } from "./rec-preproc.js";
|
|
2
|
+
import type { LinePart, RecLine, Tok } from "./types.js";
|
|
3
|
+
import type { Vocab } from "./vocab.js";
|
|
4
|
+
export declare const SPLIT_GAP = 3;
|
|
5
|
+
export declare const CELL_GAP = 1.8;
|
|
6
|
+
/**
|
|
7
|
+
* Per line, the x positions of gaps that sit on a column gutter: a gap over
|
|
8
|
+
* GUTTER_GAP line heights where at least GUTTER_EDGES other lines end at its
|
|
9
|
+
* left side or start at its right side.
|
|
10
|
+
*/
|
|
11
|
+
export declare function gutterCuts(vocab: Vocab, boxes: readonly Box[], rec: readonly RecLine[]): number[][];
|
|
12
|
+
export declare function isSpace(vocab: Vocab, tok: number | string): boolean;
|
|
13
|
+
/** Text of tokens: class ids from the recognizer, or characters (CJK, text layer, math). */
|
|
14
|
+
export declare function decodeToks(vocab: Vocab, toks: readonly Tok[]): string;
|
|
15
|
+
/**
|
|
16
|
+
* Cut a line where two neighbouring characters are more than `gap` line
|
|
17
|
+
* heights apart, or at the given x positions. One part when nothing is cut.
|
|
18
|
+
*/
|
|
19
|
+
export declare function splitLine(vocab: Vocab, box: Box, toks: readonly Tok[], gap: number, at?: readonly number[]): LinePart[];
|
package/indra/lines.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{item}from"./util.js";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){if(!toks.length)return vocab.decode([]);if(typeof item(toks,0)[0]==="string"){return toks.map((tk)=>String(tk[0])).join("").split(/\s+/u).filter(Boolean).join(" ")}return vocab.decode(toks.map((tk)=>Number(tk[0])))}export function splitLine(vocab,box,toks,gap,at=[]){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),toks}];let out=[];for(let sg of segs){let text=decodeToks(vocab,sg).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}
|
package/indra/math.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { InferenceSession } from "onnxruntime-common";
|
|
2
|
+
import type { FloatImage, Gray, ImageOps } from "./image.js";
|
|
3
|
+
import type { Box } from "./rec-preproc.js";
|
|
4
|
+
import type { TensorCtor } from "./types.js";
|
|
5
|
+
/**
|
|
6
|
+
* A math reading replaces a line only at this mean token probability or more:
|
|
7
|
+
* on print the model has not seen it writes confident-looking LaTeX that is
|
|
8
|
+
* wrong, at low probability.
|
|
9
|
+
*/
|
|
10
|
+
export declare const MATH_MIN_CONF = 0.9;
|
|
11
|
+
/** The math models: line classifier, encoder, and the decoder's init and step graphs. */
|
|
12
|
+
export type MathSessions = {
|
|
13
|
+
cls: InferenceSession;
|
|
14
|
+
enc: InferenceSession;
|
|
15
|
+
init: InferenceSession;
|
|
16
|
+
step: InferenceSession;
|
|
17
|
+
};
|
|
18
|
+
/** `math_meta.json`. */
|
|
19
|
+
export type MathMeta = {
|
|
20
|
+
config: {
|
|
21
|
+
height: number;
|
|
22
|
+
max_tokens: number;
|
|
23
|
+
dec_layers: number;
|
|
24
|
+
dec_heads: number;
|
|
25
|
+
channels: number;
|
|
26
|
+
};
|
|
27
|
+
tokens: string[];
|
|
28
|
+
};
|
|
29
|
+
/** A math reading: text with inline LaTeX, and the mean token probability. */
|
|
30
|
+
export type MathReading = {
|
|
31
|
+
text: string;
|
|
32
|
+
conf: number;
|
|
33
|
+
};
|
|
34
|
+
/** Tokens to text; inside math (between "$" tokens) they are joined by spaces. */
|
|
35
|
+
export declare function detokenize(tokens: readonly string[]): string;
|
|
36
|
+
/**
|
|
37
|
+
* Math lines: the classifier finds lines that hold math, and an attention
|
|
38
|
+
* decoder reads a taller crop of each one token per step, with its keys and
|
|
39
|
+
* values cached.
|
|
40
|
+
*/
|
|
41
|
+
export declare class MathReader {
|
|
42
|
+
private readonly Tensor;
|
|
43
|
+
private readonly sessions;
|
|
44
|
+
private readonly meta;
|
|
45
|
+
private readonly ops;
|
|
46
|
+
private readonly itos;
|
|
47
|
+
private readonly headDim;
|
|
48
|
+
constructor(Tensor: TensorCtor, sessions: MathSessions, meta: MathMeta, ops: ImageOps);
|
|
49
|
+
/** Per line crop (the recognizer's crop): does it hold math? */
|
|
50
|
+
flags(crops: readonly FloatImage[], batch?: number): Promise<boolean[]>;
|
|
51
|
+
/** Text with inline LaTeX and the mean token probability, for each box. */
|
|
52
|
+
read(gray: Gray, boxes: readonly Box[], batch?: number): Promise<MathReading[]>;
|
|
53
|
+
private decodeBatch;
|
|
54
|
+
}
|
package/indra/math.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export class MathReader{Tensor;sessions;meta;ops;itos;headDim;constructor(Tensor,sessions,meta,ops){this.Tensor=Tensor;this.sessions=sessions;this.meta=meta;this.ops=ops;this.itos=["","","","",...meta.tokens];this.headDim=meta.config.channels/meta.config.dec_heads}async flags(crops,batch=64){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 this.sessions.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)>MATH_MIN}return out}async read(gray,boxes,batch=64){const{height}=this.meta.config;let crops=boxes.map((b)=>cropLine(gray,b,height,this.ops));let out=crops.map(()=>({text:"",conf:0}));let widths=crops.map((c)=>c.width);for(let idx of widthBatches(widths,batch,4,64,16*64*640)){let readings=await this.decodeBatch(idx.map((j)=>item(crops,j)));for(const[k,j]of idx.entries())out[j]=item(readings,k)}return out}async decodeBatch(crops){const{enc,init,step}=this.sessions;const{dec_layers:layers,dec_heads:heads,max_tokens:maxTokens}=this.meta.config;let B=crops.length;const{data,dims,widths}=padBatch(crops);let encoded=await enc.run({x:new this.Tensor("float32",data,dims),widths:new this.Tensor("int64",widths,[B])});let memory=output(encoded,"memory");let mask=output(encoded,"mask");let cross=await init.run(declared(init,{memory,mask}));let empty=new this.Tensor("float32",new Float32Array(0),[layers,B,heads,0,this.headDim]);let selfK=empty;let selfV=empty;let tok=new BigInt64Array(B).fill(BigInt(BOS));let seqs=Array.from({length:B},()=>[]);let probs=Array.from({length:B},()=>[]);let done=Array.from({length:B},()=>false);for(let t=0;t<maxTokens-1;t++){let res=await step.run(declared(step,{token:new this.Tensor("int64",tok,[B]),pos:new this.Tensor("int64",BigInt64Array.of(BigInt(t)),[]),self_k:selfK,self_v:selfV,cross_k:output(cross,"cross_k"),cross_v:output(cross,"cross_v"),mask}));selfK=output(res,"new_k");selfV=output(res,"new_v");let logits=output(res,"logits");let n=logits.dims[1]??0;let ids=topTokens(floats(logits),B,n);tok=BigInt64Array.from(ids.map((p)=>BigInt(p.id)));for(const[b,{id,top}]of ids.entries()){if(done[b])continue;let pb=item(probs,b);pb.push(top);if(id===EOS){done[b]=true}else if(pb.length>=8&&meanOf(pb)<MATH_MIN_CONF-EARLY_STOP_MARGIN){done[b]=true}else if(id>=N_SPECIAL){item(seqs,b).push(id)}}if(done.every(Boolean))break}return seqs.map((seq,b)=>{let pb=item(probs,b);return{text:detokenize(seq.map((i)=>item(this.itos,i))),conf:pb.length?meanOf(pb):0}})}}import{sumF32}from"./numeric.js";import{cropLine,padBatch,widthBatches}from"./rec-preproc.js";import{floats,item,output}from"./util.js";let MATH_MIN=0.5;export let MATH_MIN_CONF=0.9;let EARLY_STOP_MARGIN=0.1;let BOS=1;let EOS=2;let N_SPECIAL=4;export function detokenize(tokens){let out=[];let math=[];let inMath=false;for(let t of tokens){if(t==="$"){if(inMath){out.push(`$${math.join(" ")}$`);math=[]}inMath=!inMath}else if(inMath){math.push(t)}else{out.push(t)}}if(inMath&&math.length)out.push(`$${math.join(" ")}$`);return out.join("").split(/\s+/u).filter(Boolean).join(" ")}function declared(sess,feeds){return Object.fromEntries(Object.entries(feeds).filter(([k])=>sess.inputNames.includes(k)))}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))}})}function meanOf(values){return values.reduce((a,b)=>a+b,0)/values.length}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sum of float32 values the way numpy sums a contiguous float32 array:
|
|
3
|
+
* pairwise, in blocks of up to 128 with 8 lanes, rounding to float32 at every
|
|
4
|
+
* step. The reference compares sums (skew search) and thresholds means
|
|
5
|
+
* (confidence), so a plain double sum would flip some of its decisions.
|
|
6
|
+
*/
|
|
7
|
+
export declare function sumF32(a: ArrayLike<number>, start?: number, end?: number): number;
|
|
8
|
+
/** numpy's float32 mean: the pairwise sum divided in float32. */
|
|
9
|
+
export declare function meanF32(a: ArrayLike<number>): number;
|
package/indra/numeric.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let f=Math.fround;export function sumF32(a,start=0,end=a.length){let n=end-start;if(n<8){let r=0;for(let i=start;i<end;i++)r=f(r+(a[i]??0));return r}if(n<=128){let r0=f(a[start]??0);let r1=f(a[start+1]??0);let r2=f(a[start+2]??0);let r3=f(a[start+3]??0);let r4=f(a[start+4]??0);let r5=f(a[start+5]??0);let r6=f(a[start+6]??0);let r7=f(a[start+7]??0);let stop=start+n-n%8;let i=start+8;for(;i<stop;i+=8){r0=f(r0+(a[i]??0));r1=f(r1+(a[i+1]??0));r2=f(r2+(a[i+2]??0));r3=f(r3+(a[i+3]??0));r4=f(r4+(a[i+4]??0));r5=f(r5+(a[i+5]??0));r6=f(r6+(a[i+6]??0));r7=f(r7+(a[i+7]??0))}let res=f(f(f(r0+r1)+f(r2+r3))+f(f(r4+r5)+f(r6+r7)));for(;i<end;i++)res=f(res+(a[i]??0));return res}let n2=Math.floor(n/2);n2-=n2%8;return f(sumF32(a,start,start+n2)+sumF32(a,start+n2,end))}export function meanF32(a){return f(sumF32(a)/a.length)}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Box } from "./rec-preproc.js";
|
|
2
|
+
export declare const N_FEATS = 16;
|
|
3
|
+
/** Block classes the layout heads predict for each line. */
|
|
4
|
+
export declare const BLOCK_CLASSES: readonly ["Text", "Section-Header", "Page-Header", "Page-Footer", "List-Group", "Table", "Caption", "Footnote", "Table-Of-Contents", "Form"];
|
|
5
|
+
export type BlockLabel = (typeof BLOCK_CLASSES)[number];
|
|
6
|
+
/** numpy's float32 median. */
|
|
7
|
+
export declare function medianF32(values: readonly number[]): number;
|
|
8
|
+
/** [N, 16] float32 features of the lines for order.onnx: 10 geometric, 6 from the text. */
|
|
9
|
+
export declare function lineFeatures(boxes: readonly Box[], width: number, height: number, texts?: readonly string[]): Float32Array;
|
|
10
|
+
/**
|
|
11
|
+
* Order from a pairwise logit matrix [n, n] (a[i, j] > 0: i before j). Start
|
|
12
|
+
* from the row-sum ranking, then insertion moves: take each item out and put
|
|
13
|
+
* it back where it most raises the summed log-probability of the pairs.
|
|
14
|
+
*/
|
|
15
|
+
export declare function decodeOrder(a: Float32Array, n: number, sweeps?: number): number[];
|
|
16
|
+
/** Rows top to bottom (centers within half a line height share a row), left to right. */
|
|
17
|
+
export declare function orderTopDown(boxes: readonly Box[]): number[];
|
|
18
|
+
/**
|
|
19
|
+
* Recursive XY-cut: split at the widest whitespace gap on either axis. The
|
|
20
|
+
* upper part goes first after a row cut, the left part after a column cut.
|
|
21
|
+
* Without a gap, top-down order.
|
|
22
|
+
*/
|
|
23
|
+
export declare function orderXYCut(boxes: readonly Box[]): number[];
|
|
24
|
+
/**
|
|
25
|
+
* Average-linkage clustering of pairwise "same group" logits [n, n]: merge the
|
|
26
|
+
* two groups with the highest mean logit between them while that mean is
|
|
27
|
+
* positive. One wrong pair cannot join two groups the other pairs keep apart.
|
|
28
|
+
*/
|
|
29
|
+
export declare function cluster(logits: ArrayLike<number>, n: number): number[][];
|
|
30
|
+
/** Index of the largest per-class sum of the lines' class logits [n, C]. */
|
|
31
|
+
export declare function blockClass(cls: Float32Array, lines: readonly number[]): number;
|
|
32
|
+
/**
|
|
33
|
+
* Reading order with the layout heads: blocks from clustering the same-block
|
|
34
|
+
* logits, lines inside a block by XY-cut (row by row in grid blocks), blocks
|
|
35
|
+
* by the mean pairwise order logit between them.
|
|
36
|
+
*/
|
|
37
|
+
export declare function decodeBlocksOrder(a: Float32Array, same: Float32Array, boxes: readonly Box[], cls: Float32Array): number[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{pyRound}from"./det-post.js";import{sumF32}from"./numeric.js";import{item}from"./util.js";let f=Math.fround;export let N_FEATS=16;export let BLOCK_CLASSES=["Text","Section-Header","Page-Header","Page-Footer","List-Group","Table","Caption","Footnote","Table-Of-Contents","Form"];let GRID=new Set([5,8,9]);let BULLETS=String.fromCharCode(8226,45,8211,9642,9702,42,183,8594);let DIGIT=new RegExp("^[\\p{Nd}\\u00b2\\u00b3\\u00b9\\u2070\\u2074-\\u2079\\u2080-\\u2089\\u2460-\\u2468\\u2474-\\u247c"+"\\u2488-\\u2490\\u24ea\\u24f5-\\u24fd\\u24ff\\u2776-\\u277e\\u2780-\\u2788\\u278a-\\u2792]$","u");let UPPER=/^\p{Uppercase}$/u;let isDigits=(s)=>s.length>0&&[...s].every((c)=>DIGIT.test(c));export function medianF32(values){let v=values.toSorted((a,b)=>a-b);let m=Math.floor(v.length/2);return v.length%2?item(v,m):f(f(item(v,m-1)+item(v,m))/2)}export function lineFeatures(boxes,width,height,texts){let n=boxes.length;let out=new Float32Array(n*N_FEATS);if(n===0)return out;let minSide=f(0.001);let ws=boxes.map(([x0,,x1])=>Math.max(f(x1-x0),minSide));let hs=boxes.map(([,y0,,y1])=>Math.max(f(y1-y0),minSide));let medH=medianF32(hs);let scaleCol=f(medH/height*20);for(const[i,[x0,y0,x1,y1]]of boxes.entries()){let w=item(ws,i);let h=item(hs,i);let row=out.subarray(i*N_FEATS,(i+1)*N_FEATS);row[0]=f(x0/width);row[1]=f(y0/height);row[2]=f(x1/width);row[3]=f(y1/height);row[4]=f(f(x0+x1)/(2*width));row[5]=f(f(y0+y1)/(2*height));row[6]=f(w/width);row[7]=f(Math.log(f(h/medH)));row[8]=f(f(Math.log(f(w/h)))/4);row[9]=scaleCol;let t=(texts?.[i]??"").trim();if(!t)continue;let cps=[...t];let first=item(cps,0);let last=item(cps,cps.length-1);row[10]=Math.log1p(cps.length)/5;row[11]=cps.filter((c)=>DIGIT.test(c)).length/cps.length;let numbered=isDigits(cps.slice(0,3).join("").replace(/[.)]+$/,""))&&cps.length>3;row[12]=BULLETS.includes(first)||numbered?1:0;row[13]=t.endsWith("-")?1:0;row[14]=".!?:;".includes(last)?1:0;row[15]=UPPER.test(first)?1:0}return out}function logAddExp0(x){if(x===0)return f(Math.LN2);let big=Math.max(0,x);return f(big+f(Math.log1p(f(Math.exp(-Math.abs(x))))))}export function decodeOrder(a,n,sweeps=4){if(n<=1)return Array.from({length:n},(_,i)=>i);let lp=new Float32Array(n*n);for(let i=0;i<n*n;i++)lp[i]=f(-logAddExp0(f(-(a[i]??0))));let at=(i,j)=>lp[i*n+j]??0;let col=new Float32Array(n);for(let i=0;i<n;i++)for(let j=0;j<n;j++)col[j]=f((col[j]??0)+at(i,j));let score=Array.from({length:n},(_,i)=>f(-sumF32(lp,i*n,(i+1)*n)+(col[i]??0)));let order=score.map((_,i)=>i).toSorted((p,q)=>item(score,p)-item(score,q));for(let s=0;s<sweeps;s++){let improved=false;for(let x of order){let rest=order.filter((v)=>v!==x);let m=rest.length;let gains=new Float64Array(m+1);let acc=0;for(let k=0;k<m;k++){acc=f(acc+at(item(rest,k),x));gains[k+1]=acc}acc=0;for(let k=m-1;k>=0;k--){acc=f(acc+at(x,item(rest,k)));gains[k]=(gains[k]??0)+acc}let k=0;for(let j=1;j<=m;j++)if((gains[j]??0)>(gains[k]??0))k=j;let cur=order.indexOf(x);if((gains[k]??0)>(gains[cur]??0)+0.000001){order=[...rest.slice(0,k),x,...rest.slice(k)];improved=true}}if(!improved)break}return order}export function orderTopDown(boxes){if(!boxes.length)return[];let cy=boxes.map(([,y0,,y1])=>f(f(y0+y1)/2));let h=medianF32(boxes.map(([,y0,,y1])=>f(y1-y0)));let half=f(h*0.5);let unit=half>0.001?half:0.001;let key=cy.map((c)=>pyRound(f(c/unit)));return boxes.map((_,i)=>i).toSorted((p,q)=>item(key,p)-item(key,q)||item(boxes,p)[0]-item(boxes,q)[0])}function bestCut(boxes,axis){let lo=boxes.map((b)=>axis===1?b[1]:b[0]);let hi=boxes.map((b)=>axis===1?b[3]:b[2]);let order=lo.map((_,i)=>i).toSorted((p,q)=>item(lo,p)-item(lo,q));let end=item(hi,item(order,0));let gap=0;let k=-1;for(let j=1;j<order.length;j++){let o=item(order,j);let g=f(item(lo,o)-end);if(g>gap){gap=g;k=j}end=Math.max(end,item(hi,o))}return{gap,k,order}}export function orderXYCut(boxes){let rec=(ids)=>{if(ids.length<=1)return ids;let b=ids.map((i)=>item(boxes,i));let y=bestCut(b,1);let x=bestCut(b,0);if(y.k<0&&x.k<0)return orderTopDown(b).map((i)=>item(ids,i));const{k,order}=y.gap>=x.gap?y:x;return[...rec(order.slice(0,k).map((i)=>item(ids,i))),...rec(order.slice(k).map((i)=>item(ids,i)))]};return rec(boxes.map((_,i)=>i))}function argmaxRow(m,row,n){let best=0;for(let j=1;j<n;j++)if((m[row*n+j]??0)>(m[row*n+best]??0))best=j;return best}export function cluster(logits,n){if(n===0)return[];let S=Float64Array.from({length:n*n},(_,i)=>i%(n+1)===0?0:logits[i]??0);let size=new Float64Array(n).fill(1);let alive=Array.from({length:n},()=>true);let members=Array.from({length:n},(_,i)=>[i]);let M=Float64Array.from(S,(v,i)=>i%(n+1)===0?-1/0:v);let best=Array.from({length:n},(_,i)=>argmaxRow(M,i,n));let bestV=Float64Array.from(best,(b,i)=>M[i*n+b]??-1/0);for(let step=0;step<n-1;step++){let a=0;for(let i=1;i<n;i++)if((bestV[i]??0)>(bestV[a]??0))a=i;let b=item(best,a);if((bestV[a]??0)<=0)break;[a,b]=[Math.min(a,b),Math.max(a,b)];for(let j=0;j<n;j++)S[a*n+j]=(S[a*n+j]??0)+(S[b*n+j]??0);for(let i=0;i<n;i++)S[i*n+a]=(S[i*n+a]??0)+(S[i*n+b]??0);S[a*n+a]=0;size[a]=(size[a]??0)+(size[b]??0);alive[b]=false;members[a]=[...item(members,a),...item(members,b)];let row=new Float64Array(n);for(let j=0;j<n;j++){row[j]=alive[j]&&j!==a?(S[a*n+j]??0)/((size[a]??1)*(size[j]??1)):-1/0}for(let j=0;j<n;j++){M[a*n+j]=row[j]??-1/0;M[j*n+a]=row[j]??-1/0}for(let j=0;j<n;j++){M[b*n+j]=-1/0;M[j*n+b]=-1/0}bestV[b]=-1/0;best[a]=argmaxRow(row,0,n);bestV[a]=row[item(best,a)]??-1/0;for(let j=0;j<n;j++){if(j===a||!alive[j]||best[j]!==a&&best[j]!==b)continue;best[j]=argmaxRow(M,j,n);bestV[j]=M[j*n+item(best,j)]??-1/0}for(let j=0;j<n;j++){if(j!==a&&alive[j]&&(row[j]??-1/0)>(bestV[j]??0)){best[j]=a;bestV[j]=row[j]??-1/0}}}return members.filter((_,i)=>alive[i]).map((m)=>m.toSorted((p,q)=>p-q))}export function blockClass(cls,lines){let c=BLOCK_CLASSES.length;let sums=new Float32Array(c);for(let i of lines)for(let k=0;k<c;k++)sums[k]=f((sums[k]??0)+(cls[i*c+k]??0));let best=0;for(let k=1;k<c;k++)if((sums[k]??0)>(sums[best]??0))best=k;return best}export function decodeBlocksOrder(a,same,boxes,cls){let n=boxes.length;if(n<=1)return boxes.map((_,i)=>i);let blocks=cluster(same,n);let inner=blocks.map((b)=>{let bx=b.map((i)=>item(boxes,i));let local=GRID.has(blockClass(cls,b))?orderTopDown(bx):orderXYCut(bx);return local.map((k)=>item(b,k))});let m=blocks.length;let ab=new Float32Array(m*m);for(let p=0;p<m;p++){for(let q=p+1;q<m;q++){let bp=item(blocks,p);let bq=item(blocks,q);let sum=0;for(let i of bp)for(let j of bq)sum+=a[i*n+j]??0;let mean=sum/(bp.length*bq.length);ab[p*m+q]=f(mean);ab[q*m+p]=f(-mean)}}return decodeOrder(ab,m).flatMap((k)=>item(inner,k))}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { DetBox } from "./det-post.js";
|
|
2
|
+
import type { Gray, ImageOps } from "./image.js";
|
|
3
|
+
import type { MathReader } from "./math.js";
|
|
4
|
+
import type { Box } from "./rec-preproc.js";
|
|
5
|
+
import type { DetectPass, IndraMeta, IndraSessions, PipelineOptions, Orientation, Page, ReadingOrder, RecLine, Straightened, TensorCtor } from "./types.js";
|
|
6
|
+
import { Vocab } from "./vocab.js";
|
|
7
|
+
/**
|
|
8
|
+
* The OCR pipeline on one grayscale page. Each stage is its own method, so
|
|
9
|
+
* callers can run the whole page or chain stages themselves.
|
|
10
|
+
*/
|
|
11
|
+
export declare class IndraPipeline {
|
|
12
|
+
private readonly Tensor;
|
|
13
|
+
private readonly sessions;
|
|
14
|
+
private readonly ops;
|
|
15
|
+
readonly vocab: Vocab;
|
|
16
|
+
readonly vocabCjk: Vocab | undefined;
|
|
17
|
+
readonly longSide: number;
|
|
18
|
+
readonly height: number;
|
|
19
|
+
private readonly furniture;
|
|
20
|
+
private readonly adaptive;
|
|
21
|
+
private readonly math;
|
|
22
|
+
constructor(Tensor: TensorCtor, sessions: IndraSessions, meta: IndraMeta, ops: ImageOps, options?: PipelineOptions);
|
|
23
|
+
/** The math reader, when math is on. */
|
|
24
|
+
get mathReader(): MathReader | undefined;
|
|
25
|
+
/** The image operations of this pipeline's engine. */
|
|
26
|
+
get imageOps(): ImageOps;
|
|
27
|
+
/**
|
|
28
|
+
* Quarter turns (counter-clockwise) the page content is turned by. 0 without
|
|
29
|
+
* orient.onnx, or when no turn is more likely than ORIENT_MIN.
|
|
30
|
+
*/
|
|
31
|
+
orient(gray: Gray): Promise<Orientation>;
|
|
32
|
+
/**
|
|
33
|
+
* The page turned upright by `turns` quarter turns, then straightened when
|
|
34
|
+
* its rows tilt by DESKEW_MIN degrees or more.
|
|
35
|
+
*/
|
|
36
|
+
straighten(gray: Gray, turns: number): Straightened;
|
|
37
|
+
/** One detector pass with the long side at `longSide`. */
|
|
38
|
+
detectAt(gray: Gray, longSide: number): Promise<DetectPass>;
|
|
39
|
+
/**
|
|
40
|
+
* Line boxes (x0, y0, x1, y1, score) in page pixels. Pages with small text
|
|
41
|
+
* get a second pass at a larger size.
|
|
42
|
+
*/
|
|
43
|
+
detect(gray: Gray): Promise<DetBox[]>;
|
|
44
|
+
/**
|
|
45
|
+
* Text, confidence and character positions per line. Lines with Chinese
|
|
46
|
+
* characters go to the CJK recognizer when the script model is loaded. A
|
|
47
|
+
* line under MIN_CONF comes back empty.
|
|
48
|
+
*/
|
|
49
|
+
recognize(gray: Gray, boxes: readonly Box[], batch?: number): Promise<RecLine[]>;
|
|
50
|
+
/**
|
|
51
|
+
* OCR of one page image: turn upright (unless `turn` is false), deskew,
|
|
52
|
+
* detect, recognize, order and lay out.
|
|
53
|
+
*/
|
|
54
|
+
page(gray: Gray, turn?: boolean): Promise<Page>;
|
|
55
|
+
/**
|
|
56
|
+
* Lines -> split at wide gaps -> reading order -> blocks and markdown. `rec`
|
|
57
|
+
* holds the text, confidence and tokens of each box.
|
|
58
|
+
*/
|
|
59
|
+
assemble(width: number, height: number, boxes: readonly Box[], rec: readonly RecLine[], t?: Record<string, number>, contentOrder?: boolean): Promise<Page>;
|
|
60
|
+
/**
|
|
61
|
+
* Reading order of the lines. With order.onnx's layout heads: blocks first,
|
|
62
|
+
* then lines inside blocks, plus the class and same-block logits.
|
|
63
|
+
*/
|
|
64
|
+
readingOrder(boxes: readonly Box[], texts: readonly string[], width: number, height: number): Promise<ReadingOrder>;
|
|
65
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export class IndraPipeline{Tensor;sessions;ops;vocab;vocabCjk;longSide;height;furniture;adaptive;math;constructor(Tensor,sessions,meta,ops,options={}){this.Tensor=Tensor;this.sessions=sessions;this.ops=ops;this.furniture=options.furniture??false;this.adaptive=options.adaptive??true;this.math=options.math;this.vocab=Vocab.fromJson(meta.vocab);this.vocabCjk=sessions.script&&sessions.recCjk&&meta.vocab_cjk?Vocab.fromJson(meta.vocab_cjk):undefined;this.longSide=meta.det_long_side;this.height=meta.rec_height}get mathReader(){return this.math}get imageOps(){return this.ops}async orient(gray){let orient=this.sessions.orient;if(!orient)return{turns:0,probs:[]};let x=new this.Tensor("float32",orientInput(gray,this.ops),[1,1,ORIENT_SIDE,ORIENT_SIDE]);let probs=Array.from(floats(output(await orient.run({x}),"p")));let k=0;for(const[i,p]of probs.entries())if(p>(probs[k]??0))k=i;return{turns:(probs[k]??0)>ORIENT_MIN?k:0,probs}}straighten(gray,turns){let image=turns?rot90(gray,turns):gray;let a=estimateSkew(image,this.ops);return Math.abs(a)>=DESKEW_MIN?{image:rotatePage(image,a,this.ops),turns,skew:a}:{image,turns,skew:0}}async detectAt(gray,longSide){const{input,scale}=pageToInput(gray,longSide,this.ops);let x=new this.Tensor("float32",input.data,[1,1,input.height,input.width]);let out=output(await this.sessions.det.run({x}),"out");const[,,h=0,w=0]=out.dims;return{boxes:decode(floats(out),h,w),scale}}async detect(gray){let{boxes,scale}=await this.detectAt(gray,this.longSide);if(this.adaptive&&boxes.length>=8){let medH=medianF32(boxes.map((b)=>Math.fround(b[3]-b[1])));if(medH<ADAPTIVE_MIN_H){let target=this.longSide*ADAPTIVE_TARGET_H/Math.max(medH,1);let ls=Math.floor(Math.trunc(Math.min(ADAPTIVE_MAX_SIDE,target))/32)*32;if(ls>this.longSide)({boxes,scale}=await this.detectAt(gray,ls))}}let s=Math.fround(scale);let clip=(v,hi)=>Math.min(Math.max(Math.fround(v/s),0),hi);return boxes.map(([x0,y0,x1,y1,score])=>[clip(x0,gray.width),clip(y0,gray.height),clip(x1,gray.width),clip(y1,gray.height),score])}async recognize(gray,boxes,batch=64){let crops=boxes.map((b)=>cropLine(gray,b,this.height,this.ops));let out=crops.map(()=>({text:"",conf:0,toks:[]}));let all=crops.map((_,i)=>i);let groups=[{sess:this.sessions.rec,vocab:this.vocab,sel:all,asChars:false}];const{recCjk}=this.sessions;if(recCjk&&this.vocabCjk&&crops.length){let hanzi=await hanziLines(this.Tensor,this.sessions.script,crops,batch);groups=[{sess:this.sessions.rec,vocab:this.vocab,sel:all.filter((j)=>!hanzi[j]),asChars:false},{sess:recCjk,vocab:this.vocabCjk,sel:all.filter((j)=>hanzi[j]),asChars:true}]}for(let group of groups){let widths=group.sel.map((j)=>item(crops,j).width);for(let part of widthBatches(widths,batch)){let idx=part.map((i)=>item(group.sel,i));let lines=await recognizeBatch(this.Tensor,group,idx.map((j)=>item(crops,j)),idx.map((j)=>item(boxes,j)));for(const[k,j]of idx.entries())out[j]=item(lines,k)}}if(this.math&&crops.length)await readMath(this.math,gray,boxes,crops,out);return out}async page(gray,turn=true){let t={};let t0=performance.now();const{turns}=turn?await this.orient(gray):{turns:0};const{image,skew}=this.straighten(gray,turns);t["orient_ms"]=performance.now()-t0;t0=performance.now();let boxes=await this.detect(image);t["det_ms"]=performance.now()-t0;t0=performance.now();let rec=await this.recognize(image,boxes.map(toBox));t["rec_ms"]=performance.now()-t0;let page=await this.assemble(image.width,image.height,boxes.map(toBox),rec,t);page.rotation=90*turns;page.skew=roundTo(skew,2);if(skew){let back=(b)=>unrotateBox(b,skew,image.width,image.height);page.lines=page.lines.map((ln)=>({...ln,box:back(ln.box)}));page.blocks=page.blocks.map((b)=>({...b,bbox:back(b.bbox)}))}return page}async assemble(width,height,boxes,rec,t={},contentOrder=false){let t0=performance.now();let parts=splitParts(this.vocab,boxes,rec);let ro=await this.readingOrder(parts.map((p)=>p.box),parts.map((p)=>p.text),width,height);let chosen=chooseOrder(parts,ro,contentOrder);t["order_ms"]=performance.now()-t0;return buildPage(this.vocab,parts,ro,chosen,this.furniture,t)}async readingOrder(boxes,texts,width,height){let order=this.sessions.order;let n=boxes.length;if(n<2||!order)return{order:n?orderXYCut(boxes):[]};let feats=lineFeatures(boxes,width,height,texts);let res=await order.run({feats:new this.Tensor("float32",feats,[1,n,N_FEATS]),mask:new this.Tensor("bool",new Uint8Array(n).fill(1),[1,n])});let logits=floats(output(res,"a"));if(!res["cls"]||!res["same"])return{order:decodeOrder(logits,n),logits};let cls=floats(output(res,"cls"));let same=floats(output(res,"same"));return{order:decodeBlocksOrder(logits,same,boxes,cls),cls,same,logits}}}import{decode,pageToInput}from"./det-post.js";import{buildPage,chooseOrder,splitParts}from"./assemble.js";import{N_FEATS,decodeBlocksOrder,decodeOrder,lineFeatures,medianF32,orderXYCut}from"./order-post.js";import{cropLine,widthBatches}from"./rec-preproc.js";import{hanziLines,readMath,recognizeBatch}from"./recognize.js";import{floats,item,output}from"./util.js";import{DESKEW_MIN,ORIENT_MIN,ORIENT_SIDE,estimateSkew,orientInput,rot90,rotatePage,roundTo,unrotateBox}from"./upright.js";import{Vocab}from"./vocab.js";let ADAPTIVE_MIN_H=9;let ADAPTIVE_TARGET_H=12;let ADAPTIVE_MAX_SIDE=2048;function toBox(b){return[b[0],b[1],b[2],b[3]]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { FloatImage, Gray, ImageOps } from "./image.js";
|
|
2
|
+
export declare const LINE_HEIGHT = 32;
|
|
3
|
+
export declare const PAD_Y = 0.2;
|
|
4
|
+
export declare const PAD_X = 0.3;
|
|
5
|
+
/** An axis-aligned box: x0, y0, x1, y1 in page pixels. */
|
|
6
|
+
export type Box = readonly [number, number, number, number];
|
|
7
|
+
/**
|
|
8
|
+
* Crop one line for the recognizer: grow the box by PAD_Y x its height above
|
|
9
|
+
* and below and PAD_X x its height left and right (white outside the page),
|
|
10
|
+
* then scale it to `height` pixels high. Returns the float32 ink map.
|
|
11
|
+
*/
|
|
12
|
+
export declare function cropLine(gray: Gray, box: Box, height: number, ops: ImageOps, maxWidth?: number): FloatImage;
|
|
13
|
+
/** A recognizer batch: [B, 1, H, W] ink maps and each line's real width. */
|
|
14
|
+
export type PaddedBatch = {
|
|
15
|
+
data: Float32Array;
|
|
16
|
+
dims: [number, number, number, number];
|
|
17
|
+
widths: BigInt64Array;
|
|
18
|
+
};
|
|
19
|
+
/** Right-pad ink maps to one width (a multiple of 8). */
|
|
20
|
+
export declare function padBatch(lines: readonly FloatImage[]): PaddedBatch;
|
|
21
|
+
/**
|
|
22
|
+
* Group line indices into batches of similar width, narrowest first. A batch
|
|
23
|
+
* closes at `maxBatch` lines, when the next line is wider than `maxRatio`
|
|
24
|
+
* times the batch's first (widths below `minWidth` count as `minWidth`), or
|
|
25
|
+
* when lines x width would pass `maxArea`: ONNX Runtime keeps its largest
|
|
26
|
+
* allocation, so one wide batch holds memory for the whole run.
|
|
27
|
+
*/
|
|
28
|
+
export declare function widthBatches(widths: readonly number[], maxBatch?: number, maxRatio?: number, minWidth?: number, maxArea?: number): number[][];
|
|
@@ -0,0 +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;export function cropLine(gray,box,height,ops,maxWidth=4096){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-PAD_Y*h);let ix1=Math.ceil(x1+PAD_X*h);let iy1=Math.ceil(y1+PAD_Y*h);let cw=Math.max(1,ix1-ix0);let ch=Math.max(1,iy1-iy0);let crop=new Uint8Array(cw*ch).fill(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*height/ch)));let resized=ops.resize({data:crop,width:cw,height:ch},outW,height,ch>height?"area":"linear");return inkOf(resized)}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}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { InferenceSession } from "onnxruntime-common";
|
|
2
|
+
import type { FloatImage, Gray } from "./image.js";
|
|
3
|
+
import type { MathReader } from "./math.js";
|
|
4
|
+
import type { Box } from "./rec-preproc.js";
|
|
5
|
+
import type { RecLine, TensorCtor } from "./types.js";
|
|
6
|
+
import type { Vocab } from "./vocab.js";
|
|
7
|
+
/**
|
|
8
|
+
* A recognized line under this confidence (mean CTC peak probability) gets no
|
|
9
|
+
* text: on empty form fields, checkboxes and rules the recognizer reads "-",
|
|
10
|
+
* "I" or "1" at low confidence. The line's box stays.
|
|
11
|
+
*/
|
|
12
|
+
export declare const MIN_CONF = 0.5;
|
|
13
|
+
/** Lines that go to one recognizer, and whether its tokens are characters (CJK) or Latin ids. */
|
|
14
|
+
export type RecGroup = {
|
|
15
|
+
sess: InferenceSession;
|
|
16
|
+
vocab: Vocab;
|
|
17
|
+
sel: number[];
|
|
18
|
+
asChars: boolean;
|
|
19
|
+
};
|
|
20
|
+
/** One recognizer batch: text, confidence and character positions per crop. */
|
|
21
|
+
export declare function recognizeBatch(Tensor: TensorCtor, { sess, vocab, asChars }: RecGroup, crops: readonly FloatImage[], boxes: readonly Box[]): Promise<RecLine[]>;
|
|
22
|
+
/** Per line crop: does it hold Chinese characters (script.onnx)? All false without the model. */
|
|
23
|
+
export declare function hanziLines(Tensor: TensorCtor, script: InferenceSession | undefined, crops: readonly FloatImage[], batch?: number): Promise<boolean[]>;
|
|
24
|
+
/**
|
|
25
|
+
* Lines the math classifier flags are read by the math reader. A reading
|
|
26
|
+
* replaces the line only when it holds math and is confident; one token
|
|
27
|
+
* holds the whole line, so it is never split.
|
|
28
|
+
*/
|
|
29
|
+
export declare function readMath(math: MathReader, gray: Gray, boxes: readonly Box[], crops: readonly FloatImage[], out: RecLine[]): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
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 async function recognizeBatch(Tensor,{sess,vocab,asChars},crops,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])});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);return crops.map((crop,k)=>{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)}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)/crop.width;let keptIds=kept.map((t)=>item(seq,t));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]});let conf=kept.length?meanF32(kept.map((t)=>pmax[k*steps+t]??0)):0;return conf>=MIN_CONF?{text:vocab.decode(keptIds),conf,toks}:{text:"",conf,toks:[]}})}export async function hanziLines(Tensor,script,crops,batch=64){let out=crops.map(()=>false);if(!script)return out;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 p=floats(output(res,"p"));for(const[k,j]of idx.entries())out[j]=(p[k]??0)>0.5}return out}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]]}}}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Gray } from "./image.js";
|
|
2
|
+
import type { Box } from "./rec-preproc.js";
|
|
3
|
+
/** TextLayer.reason when the layer's character codes are not text. */
|
|
4
|
+
export declare const BROKEN_FONT_MAP = "broken font map";
|
|
5
|
+
/**
|
|
6
|
+
* One character of a PDF text page: its UTF-16 unit, baseline angle, and box
|
|
7
|
+
* in page space (l, b, r, t), or undefined when pdfium has no box for it.
|
|
8
|
+
*/
|
|
9
|
+
export type PdfChar = {
|
|
10
|
+
unit: number;
|
|
11
|
+
angle: number;
|
|
12
|
+
box: readonly [number, number, number, number] | undefined;
|
|
13
|
+
};
|
|
14
|
+
/** What the text-layer code needs from one PDF page. Coordinates are PDF points. */
|
|
15
|
+
export type PdfPageSource = {
|
|
16
|
+
/** Page width and height as rendered (crop box and rotation applied). */
|
|
17
|
+
size(): readonly [number, number];
|
|
18
|
+
/** The page rendered in grayscale at `scale` pixels per point. */
|
|
19
|
+
render(scale: number): Gray;
|
|
20
|
+
/** The text page's characters in content order. */
|
|
21
|
+
chars(): PdfChar[];
|
|
22
|
+
/** pdfium's FPDF_PageToDevice on a (width x height) device: integer device x, y. */
|
|
23
|
+
pageToDevice(width: number, height: number, x: number, y: number): readonly [number, number];
|
|
24
|
+
/** Render mode of every text object, nested form objects included. */
|
|
25
|
+
textRenderModes(): number[];
|
|
26
|
+
};
|
|
27
|
+
/** One text-layer run: its box, its text, and its characters with boxes (rendered frame, points). */
|
|
28
|
+
export type TextLine = {
|
|
29
|
+
bbox: Box;
|
|
30
|
+
text: string;
|
|
31
|
+
chars: [string, Box][];
|
|
32
|
+
};
|
|
33
|
+
export type TextLayerStats = {
|
|
34
|
+
chars: number;
|
|
35
|
+
rotated: number;
|
|
36
|
+
bad: number;
|
|
37
|
+
off_page?: number;
|
|
38
|
+
no_ink?: number;
|
|
39
|
+
};
|
|
40
|
+
/** Upright runs of a page and its character counts. */
|
|
41
|
+
export type ExtractedRuns = {
|
|
42
|
+
runs: TextLine[];
|
|
43
|
+
stats: TextLayerStats;
|
|
44
|
+
};
|
|
45
|
+
/** The runs of a page and whether to trust them. */
|
|
46
|
+
export type TextLayer = {
|
|
47
|
+
lines: TextLine[];
|
|
48
|
+
size: readonly [number, number];
|
|
49
|
+
trusted: boolean;
|
|
50
|
+
reason: string;
|
|
51
|
+
stats: TextLayerStats;
|
|
52
|
+
};
|
|
53
|
+
/** Replacement, private-use, surrogate, unassigned and control characters (tab excepted). */
|
|
54
|
+
export declare function badCharCount(text: string): number;
|
|
55
|
+
/** Upright text runs of a page, in content order, and character counts. */
|
|
56
|
+
export declare function extractRuns(page: PdfPageSource): ExtractedRuns;
|
|
57
|
+
/** Python's " ".join(s.split()). */
|
|
58
|
+
export declare function collapseSpaces(s: string): string;
|
|
59
|
+
/**
|
|
60
|
+
* Text-layer runs of a page and the verdict on them: invisible text marks an
|
|
61
|
+
* OCR layer, bad characters a broken font map, runs with no ink under them
|
|
62
|
+
* hidden or misplaced text. `gray` is a render at `scale` pixels per point.
|
|
63
|
+
*/
|
|
64
|
+
export declare function readTextLayer(page: PdfPageSource, gray: Gray, scale: number): TextLayer;
|
|
65
|
+
/** Upward moves in content order that do not go to a column on the right. */
|
|
66
|
+
export declare function orderBacktracks(boxes: readonly Box[]): number;
|
|
67
|
+
/**
|
|
68
|
+
* Is the content order a reading order? Few upward moves that are not column
|
|
69
|
+
* changes, and the order model (pairwise logits [n, n], a[i, j] > 0: i
|
|
70
|
+
* before j) agrees with most consecutive pairs.
|
|
71
|
+
*/
|
|
72
|
+
export declare function pdfOrderCoherent(boxes: readonly Box[], pairLogits?: Float32Array): boolean;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{pyRound}from"./det-post.js";import{medianF32}from"./order-post.js";import{roundTo}from"./upright.js";import{isPySpace,item}from"./util.js";let MAX_INVISIBLE_FRAC=0.05;let MAX_BAD_CHAR_FRAC=0.005;let MAX_NO_INK_LINE_FRAC=0.03;let DARK=160;let MIN_MODEL_AGREEMENT=0.85;let TEXT_RENDER_INVISIBLE=3;export let BROKEN_FONT_MAP="broken font map";let BAD=/^[\p{Co}\p{Cs}\p{Cn}]$/u;let CONTROL=/^\p{Cc}$/u;export function badCharCount(text){let n=0;for(let i=0;i<text.length;i++){let c=text.charAt(i);if(c.charCodeAt(0)===65533||BAD.test(c)||CONTROL.test(c)&&c!=="\t")n++}return n}function deviceAffine(page){const[w,h]=page.size();let S=1000;let dw=pyRound(w*S);let dh=pyRound(h*S);let dev=(x,y)=>{const[dx,dy]=page.pageToDevice(dw,dh,x,y);return[dx/S,dy/S]};const[o0,o1]=dev(0,0);const[ex0,ex1]=dev(1,0);const[ey0,ey1]=dev(0,1);return[ex0-o0,ey0-o0,o0,ex1-o1,ey1-o1,o1]}export function extractRuns(page){const[a00=0,a01=0,a02=0,a10=0,a11=0,a12=0]=deviceAffine(page);let upright=new Map;let chars=[];let raw=[];let breaks=[];let stats={chars:0,rotated:0,bad:0};for(let ch of page.chars()){let c=String.fromCharCode(ch.unit);if(c==="\r"||c===`
|
|
2
|
+
`){breaks.push(chars.length);continue}if(c==="\x02")c="-";if(!isPySpace(c)){stats.chars++;stats.bad+=badCharCount(c);let up=upright.get(ch.angle);if(up===undefined){let d0=a00*Math.cos(ch.angle)+a01*Math.sin(ch.angle);let d1=a10*Math.cos(ch.angle)+a11*Math.sin(ch.angle);up=!(d0<=0||Math.abs(d1)>0.001*Math.max(Math.abs(d0),0.000000001));upright.set(ch.angle,up)}if(!up){stats.rotated++;breaks.push(chars.length);continue}}if(!ch.box)throw new Error("Failed to get charbox.");chars.push(c);raw.push(ch.box)}if(!chars.length)return{runs:[],stats};const[w,h]=page.size();let boxes=raw.map(([l,b,r,t])=>{let px=[l,r,l,r].map((x,i)=>a00*x+a01*item([b,b,t,t],i)+a02);let py=[l,r,l,r].map((x,i)=>a10*x+a11*item([b,b,t,t],i)+a12);return[Math.min(...px),Math.min(...py),Math.max(...px),Math.max(...py)]});let visible=boxes.map(([x0,y0,x1,y1])=>{let cx=(x0+x1)/2;let cy=(y0+y1)/2;return cx>=0&&cx<=w&&cy>=0&&cy<=h});stats.off_page=visible.filter((v)=>!v).length;let runs=[];let start=0;for(let end of[...new Set([...breaks,chars.length])].toSorted((p,q)=>p-q)){let seg=[];for(let i=start;i<end;i++)if(visible[i])seg.push([item(chars,i),item(boxes,i)]);start=end;let ink=seg.filter(([c])=>!isPySpace(c)).map(([,b])=>b);if(!ink.length)continue;runs.push({bbox:[Math.min(...ink.map((b)=>b[0])),Math.min(...ink.map((b)=>b[1])),Math.max(...ink.map((b)=>b[2])),Math.max(...ink.map((b)=>b[3]))],text:collapseSpaces(seg.map(([c])=>c).join("")),chars:seg})}return{runs,stats}}export function collapseSpaces(s){return[...s].reduce((words,c)=>{if(isPySpace(c))words.push("");else words[words.length-1]+=c;return words},[""]).filter(Boolean).join(" ")}function invisibleTextFrac(page){let modes=page.textRenderModes();return modes.length?modes.filter((m)=>m===TEXT_RENDER_INVISIBLE).length/modes.length:0}function noInkFrac(gray,runs,scale){let empty=0;for(const{bbox:[x0,y0,x1,y1]}of runs){let r0=Math.max(0,Math.trunc(y0*scale));let r1=Math.min(gray.height,Math.trunc(y1*scale)+1);let c0=Math.max(0,Math.trunc(x0*scale));let c1=Math.min(gray.width,Math.trunc(x1*scale)+1);let ink=false;for(let y=r0;y<r1&&!ink;y++){for(let x=c0;x<c1;x++){if((gray.data[y*gray.width+x]??255)<DARK){ink=true;break}}}if(!ink)empty++}return empty/Math.max(runs.length,1)}let pct=(x)=>`${roundTo(x*100,0)}%`;export function readTextLayer(page,gray,scale){let size=page.size();let inv=invisibleTextFrac(page);let fail=(lines,reason,stats)=>({lines,size,trusted:false,reason,stats});if(inv>MAX_INVISIBLE_FRAC){return fail([],`invisible text ${pct(inv)} (OCR layer)`,{chars:0,rotated:0,bad:0})}const{runs,stats}=extractRuns(page);if(!runs.length)return fail([],"no text layer",stats);if(stats.bad>MAX_BAD_CHAR_FRAC*Math.max(stats.chars,1))return fail(runs,BROKEN_FONT_MAP,stats);let empty=noInkFrac(gray,runs,scale);stats.no_ink=roundTo(empty,4);if(empty>MAX_NO_INK_LINE_FRAC)return fail(runs,`${pct(empty)} of text runs have no ink`,stats);return{lines:runs,size,trusted:true,reason:"",stats}}export function orderBacktracks(boxes){if(boxes.length<3)return 0;let f=Math.fround;let h=medianF32(boxes.map(([,y0,,y1])=>f(y1-y0)));let bt=0;for(let i=1;i<boxes.length;i++){let a=item(boxes,i-1);let b=item(boxes,i);if(b[1]<f(a[1]-f(0.5*h))&&b[0]<f(a[2]-f(h)))bt++}return bt}export function pdfOrderCoherent(boxes,pairLogits){let n=boxes.length;if(orderBacktracks(boxes)>Math.max(1,Math.trunc(0.02*n)))return false;if(!pairLogits||n<3)return true;let agree=0;for(let i=0;i<n-1;i++)if((pairLogits[i*n+i+1]??0)>0)agree++;return agree/(n-1)>=MIN_MODEL_AGREEMENT}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let clampByte=(v)=>Math.min(255,Math.max(0,Math.round(v)));function linearTaps(out,size){let scale=size/out;let i0=new Int32Array(out);let i1=new Int32Array(out);let w=new Float64Array(out);for(let d=0;d<out;d++){let s=Math.min(Math.max((d+0.5)*scale-0.5,0),size-1);let f=Math.floor(s);i0[d]=f;i1[d]=Math.min(f+1,size-1);w[d]=s-f}return{i0,i1,w}}function resizeLinear(src,width,height){let xs=linearTaps(width,src.width);let ys=linearTaps(height,src.height);let out=new Uint8Array(width*height);let s=src.data;for(let y=0;y<height;y++){let r0=(ys.i0[y]??0)*src.width;let r1=(ys.i1[y]??0)*src.width;let wy=ys.w[y]??0;for(let x=0;x<width;x++){let a=xs.i0[x]??0;let b=xs.i1[x]??0;let wx=xs.w[x]??0;let top=(s[r0+a]??0)*(1-wx)+(s[r0+b]??0)*wx;let bot=(s[r1+a]??0)*(1-wx)+(s[r1+b]??0)*wx;out[y*width+x]=clampByte(top*(1-wy)+bot*wy)}}return{data:out,width,height}}function areaSpans(out,size){let scale=size/out;return Array.from({length:out},(_,d)=>{let lo=d*scale;let hi=Math.min((d+1)*scale,size);let start=Math.floor(lo);let weights=[];for(let i=start;i<hi;i++)weights.push((Math.min(i+1,hi)-Math.max(i,lo))/(hi-lo));return{start,weights}})}function resizeArea(src,width,height){if(width>src.width||height>src.height)return resizeLinear(src,width,height);let xs=areaSpans(width,src.width);let ys=areaSpans(height,src.height);let out=new Uint8Array(width*height);let row=new Float64Array(width);for(const[y,sy]of ys.entries()){row.fill(0);for(const[k,wy]of sy.weights.entries()){let base=(sy.start+k)*src.width;for(const[x,sx]of xs.entries()){let acc=0;for(const[j,wx]of sx.weights.entries())acc+=(src.data[base+sx.start+j]??0)*wx;row[x]=(row[x]??0)+acc*wy}}for(let x=0;x<width;x++)out[y*width+x]=clampByte(row[x]??0)}return{data:out,width,height}}function invert([a,b,c,d,e,f]){let det=a*e-b*d;let ia=e/det;let ib=-b/det;let id=-d/det;let ie=a/det;return[ia,ib,-(ia*c+ib*f),id,ie,-(id*c+ie*f)]}function warp(src,m,width,height,edge){const[a,b,c,d,e,f]=invert(m);let out=new Float64Array(width*height);const{width:sw,height:sh,data}=src;let read=(x,y)=>{if(x>=0&&x<sw&&y>=0&&y<sh)return data[y*sw+x]??0;if(edge==="zero")return 0;return data[Math.min(Math.max(y,0),sh-1)*sw+Math.min(Math.max(x,0),sw-1)]??0};for(let y=0;y<height;y++){let rowX=b*y+c;let rowY=e*y+f;for(let x=0;x<width;x++){let sx=a*x+rowX;let sy=d*x+rowY;let x0=Math.floor(sx);let y0=Math.floor(sy);let wx=sx-x0;let wy=sy-y0;if(x0>=0&&y0>=0&&x0+1<sw&&y0+1<sh){let i=y0*sw+x0;let top=(data[i]??0)*(1-wx)+(data[i+1]??0)*wx;let bot=(data[i+sw]??0)*(1-wx)+(data[i+sw+1]??0)*wx;out[y*width+x]=top*(1-wy)+bot*wy}else{out[y*width+x]=(read(x0,y0)*(1-wx)+read(x0+1,y0)*wx)*(1-wy)+(read(x0,y0+1)*(1-wx)+read(x0+1,y0+1)*wx)*wy}}}return out}export let tsImageOps={resize(src,width,height,interpolation){if(width===src.width&&height===src.height)return{...src,data:src.data.slice()};return interpolation==="area"?resizeArea(src,width,height):resizeLinear(src,width,height)},warpReplicate(src,m,width,height){return{data:Uint8Array.from(warp(src,m,width,height,"replicate"),clampByte),width,height}},warpFloat(src,m,width,height){return{data:Float32Array.from(warp(src,m,width,height,"zero")),width,height}}};
|