ppu-indra-ocr 0.2.0 → 0.2.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/README.md CHANGED
@@ -401,7 +401,7 @@ const pages = isPdf(bytes)
401
401
  | `maxPages` | all | Read at most this many pages |
402
402
  | `password` | - | Password of an encrypted PDF |
403
403
 
404
- The text layer is checked first: invisible text (an OCR layer), broken font maps, right-to-left letters stored in visual order, and runs with no ink under them send the page to OCR. A table set sideways, a page turned by its `/Rotate`, and vertical writing are read upright from the text layer; sideways labels inside a page become their own lines. A page that fails comes back with `source: "error"` and the reason in `note`; a file that cannot be opened throws. pdfium runs as WebAssembly (`@embedpdf/pdfium`); a browser fetches its wasm from jsDelivr unless you pass `pdfium: await loadPdfium(wasmBytesOrUrl)`. `isPdf(bytes)` is exported from every entry to route files without loading pdfium. On Node and Bun, set `PPU_INDRA_OCR_PDFIUM_WASM` to a local `pdfium.wasm` path to load it from there instead of `node_modules`.
404
+ The text layer is checked first: invisible text (an OCR layer), broken font maps, right-to-left letters stored in visual order, and runs with no ink under them send the page to OCR. So does a legacy-font layer (Kruti Dev or DevLys for Hindi, Bijoy for Bangla) that stores Latin codes while the page shows another script: the script model checks up to six of its lines against their images (upstream measures about 5 ms a page). A table set sideways, a page turned by its `/Rotate`, and vertical writing are read upright from the text layer; sideways labels inside a page become their own lines. A page that fails comes back with `source: "error"` and the reason in `note`; a file that cannot be opened throws. pdfium runs as WebAssembly (`@embedpdf/pdfium`); a browser fetches its wasm from jsDelivr unless you pass `pdfium: await loadPdfium(wasmBytesOrUrl)`. `isPdf(bytes)` is exported from every entry to route files without loading pdfium. On Node and Bun, set `PPU_INDRA_OCR_PDFIUM_WASM` to a local `pdfium.wasm` path to load it from there instead of `node_modules`.
405
405
 
406
406
  ## Math
407
407
 
@@ -597,7 +597,7 @@ new IndraOcrService({ session: { executionProviders: ["nnapi"] } });
597
597
 
598
598
  ### Model Presets
599
599
 
600
- A preset is one pinned revision of [datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr) and the files it holds. Both run on the same pipeline, ported from `indra-ocr` 1.1.1.
600
+ A preset is one pinned revision of [datalab-to/indra-ocr](https://huggingface.co/datalab-to/indra-ocr) and the files it holds. Both run on the same pipeline, ported from `indra-ocr` 1.1.2.
601
601
 
602
602
  | Preset | Hugging Face tag | Base download | What it reads |
603
603
  | :--------------- | :--------------- | :------------ | :------------------------------------------------------------------------------------------------------------ |
@@ -818,7 +818,7 @@ Both read the characters equally well. Indra keeps the spaces between words (tok
818
818
 
819
819
  ## How the Port Is Checked
820
820
 
821
- `scripts/golden/` renders test pages and records every stage of the Python reference (`indra-ocr` 1.1.1) on them, once on each preset's models: orientation, skew, detection, recognition, script routing, language-model beam search, reading order, the text layer and the final page. The pages cover every script group, a light-on-dark title, a right-to-left page, a vertical page, a page tilted 30 degrees, and PDFs with a sideways table, a `/Rotate` page and Hebrew and vertical text layers. The tests compare this package with those goldens. On the opencv engine the line text, blocks and markdown match exactly, and the line boxes agree to an IoU of 0.98 or better (0.9 on deskewed pages, where the reference's cv2 warps through a platform-specific code path). The canvas-native engine stays within a token-F1 of 0.98.
821
+ `scripts/golden/` renders test pages and records every stage of the Python reference (`indra-ocr` 1.1.2) on them, once on each preset's models: orientation, skew, detection, recognition, script routing, language-model beam search, reading order, the text layer and the final page. The pages cover every script group, a light-on-dark title, a right-to-left page, a vertical page, a page tilted 30 degrees, and PDFs with a sideways table, a `/Rotate` page, Hebrew and vertical text layers, and a Hindi page whose text layer stores Latin codes. The tests compare this package with those goldens. On the opencv engine the line text, blocks and markdown match exactly, and the line boxes agree to an IoU of 0.98 or better (0.9 on deskewed pages, where the reference's cv2 warps through a platform-specific code path). The canvas-native engine stays within a token-F1 of 0.98.
822
822
 
823
823
  ## Ecosystem
824
824
 
@@ -17,11 +17,6 @@ export type AssignedRuns = {
17
17
  toks: Tok[][];
18
18
  lost: number;
19
19
  };
20
- /**
21
- * Whether the recognizers know at least READABLE_MIN of the letters in these
22
- * runs. A recognizer that reads Hangul as jamo knows a syllable by its jamo.
23
- */
24
- export declare function readable(pipeline: IndraPipeline, runs: readonly TextLine[]): boolean;
25
20
  /** Unicode bidi base direction: most strong characters are right-to-left. */
26
21
  export declare function rightToLeft(tokens: readonly Tok[]): boolean;
27
22
  /**
package/indra/document.js CHANGED
@@ -1 +1 @@
1
- import{decodeToks}from"./lines.js";import{MATH_MIN_CONF}from"./math.js";import{cropLine}from"./rec-preproc.js";import{BROKEN_FONT_MAP,uprightTextLayer}from"./textlayer.js";import{isStrongL}from"./unicode.js";import{isRtl}from"./rtl.js";import{rot90}from"./upright.js";import{isPySpace,item}from"./util.js";let CHECK_DPI=72;let MAX_PAGE_PIXELS=1e8;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 vocabs=pipeline.vocabs.map((v)=>v.index);let known=letters.filter((c)=>vocabs.some((v)=>v.has(c)||[...c.normalize("NFD")].every((j)=>v.has(j)))).length;return known>=READABLE_MIN*letters.length}export function rightToLeft(tokens){let rtl=0;let ltr=0;for(const[c]of tokens){if(typeof c!=="string"||[...c].length!==1)continue;if(isRtl(c))rtl++;else if(isStrongL(c))ltr++}return rtl>ltr}function covered(box,boxes,frac=0.5){let f=Math.fround;let area=Math.max(f(f(box[2]-box[0])*f(box[3]-box[1])),0.000001);return boxes.some((b)=>{let ix=Math.max(f(Math.min(box[2],b[2])-Math.max(box[0],b[0])),0);let iy=Math.max(f(Math.min(box[3],b[3])-Math.max(box[1],b[1])),0);return f(f(ix*iy)/area)>frac})}export function assignRuns(runs,boxes,k){if(!boxes.length){return{toks:[],lost:runs.reduce((n,r)=>n+r.chars.filter(([c])=>!isPySpace(c)).length,0)}}let f=Math.fround;let area=boxes.map(([x0,y0,x1,y1])=>f(f(x1-x0)*f(y1-y0)));let parts=boxes.map(()=>new Map);let lost=0;for(let run of runs){let idx=run.seq;let j;for(const[c,b]of run.chars){if(!isPySpace(c)){let cx=(b[0]+b[2])/2*k;let cy=(b[1]+b[3])/2*k;let fx=f(cx);let fy=f(cy);let best;for(const[i,[x0,y0,x1,y1]]of boxes.entries()){if(x0<=fx&&fx<=x1&&y0<=fy&&fy<=y1&&(best===undefined||item(area,i)<item(area,best))){best=i}}j=best;if(j===undefined){lost++;continue}let line=item(parts,j);line.set(idx,[...line.get(idx)??[],[c,cx,idx]])}else if(j!==undefined){let part=item(parts,j).get(idx)??[];part.push([c,part.at(-1)?.[1]??0,idx])}}}let toks=parts.map((line)=>{let all=[...line.values()].flat();let rtl=rightToLeft(all);let key=(toksOf)=>rtl?-Math.max(...toksOf.map((t)=>t[1])):Math.min(...toksOf.map((t)=>t[1]));let order=[...line.keys()].toSorted((a,b)=>key(line.get(a)??[])-key(line.get(b)??[]));let tk=[];for(let idx of order){let last=tk.at(-1);if(last)tk.push([" ",last[1],idx]);tk.push(...line.get(idx)??[])}return tk});return{toks,lost}}function pageScale(page,dpi){const[w,h]=page.size();return Math.min(dpi/72,Math.sqrt(MAX_PAGE_PIXELS/Math.max(w*h,1)))}function timed(t,key,run){let t0=performance.now();let out=run();t[key]=performance.now()-t0;return out}export async function pdfPage(pipeline,page,options={}){const{mode="auto",dpi=200,imageOcr=true}=options;let t={};let note="mode=ocr";let turn=true;if(mode!=="ocr"){let s=CHECK_DPI/72;const{tl,done}=timed(t,"text_ms",()=>uprightTextLayer(page,page.render(s),s,mode));if(done)return textPage(pipeline,page,tl,t,dpi,imageOcr);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,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,imageOcr){let k=pageScale(page,dpi);let turn=tl.stats.turn??0;let frame=tl.stats.frame??turn;let vertical=Boolean(tl.stats.vertical);let rendered=timed(t,"render_ms",()=>page.render(k));let gray=frame?rot90(rendered,frame):rendered;let t0=performance.now();let boxes=(await pipeline.detect(gray)).map(([x0,y0,x1,y1])=>[x0,y0,x1,y1]);t["det_ms"]=performance.now()-t0;const{toks,lost}=assignRuns(tl.lines,boxes,k);let rec=toks.map((tk)=>{let text=tk.length?decodeToks(pipeline.vocab,tk):"";return text?{text,conf:1,toks:tk}:undefined});let empty=rec.flatMap((r,i)=>r?[]:[i]);let source="text";let side=tl.rotated.filter((r)=>r.text.trim());let f=Math.fround;let sideBoxes=side.map((r)=>[f(r.bbox[0]*k),f(r.bbox[1]*k),f(r.bbox[2]*k),f(r.bbox[3]*k)]);if(side.length&&empty.length){empty=empty.filter((i)=>!covered(item(boxes,i),sideBoxes))}if(empty.length&&imageOcr&&readable(pipeline,tl.lines)){t0=performance.now();let read=await pipeline.recognize(gray,empty.map((i)=>item(boxes,i)),64,vertical);for(const[n,i]of empty.entries()){let r=item(read,n);if(r.text.trim()){rec[i]=r;source="hybrid"}}t["rec_ms"]=performance.now()-t0}if(pipeline.mathReader){t0=performance.now();await readMath(pipeline,gray,boxes,rec);t["math_ms"]=performance.now()-t0}let keep=rec.flatMap((r,i)=>r?[i]:[]);let keptBoxes=keep.map((i)=>item(boxes,i));let keptRec=keep.map((i)=>item(rec,i)??{text:"",conf:0,toks:[]});for(const[n,r]of side.entries()){let b=item(sideBoxes,n);keptBoxes.push(b);let cx=f(b[0]+b[2])/2;keptRec.push({text:r.text,conf:1,toks:[...r.text].map((c)=>[c,cx,r.seq])})}let out=await pipeline.assemble(gray.width,gray.height,keptBoxes,keptRec,t,vertical);out.source=source;out.rotation=90*turn;if(vertical){let w=gray.height;let back=([x0,y0,x1,y1])=>[w-y1,x0,w-y0,x1];out.lines=out.lines.map((ln)=>({...ln,box:back(ln.box)}));out.blocks=out.blocks.map((b)=>({...b,bbox:back(b.bbox)}));out.vertical=true}if(lost)out.note+=`; ${lost} chars outside detected lines`;return out}async function readMath(pipeline,gray,boxes,rec){let math=pipeline.mathReader;if(!math)return;let idx=rec.flatMap((r,i)=>{let first=r?.toks[0];return first&&typeof first[0]==="string"&&first.length>2?[i]:[]});if(!idx.length)return;let crops=idx.map((i)=>cropLine(gray,item(boxes,i),pipeline.height,pipeline.imageOps));let flagged=(await math.flags(crops)).flatMap((fl,n)=>fl?[item(idx,n)]:[]);if(!flagged.length)return;let readings=await math.read(gray,flagged.map((i)=>item(boxes,i)));for(const[n,i]of flagged.entries()){const{text,conf}=item(readings,n);let r=rec[i];if(!r||!text.includes("$")||conf<MATH_MIN_CONF)continue;let first=Math.min(...r.toks.flatMap((tk)=>tk[2]===undefined?[]:[tk[2]]));const[x0,,x1]=item(boxes,i);rec[i]={text,conf:1,toks:[[text,Math.fround(x0+x1)/2,first]]}}}export function isPdf(bytes){let view=bytes instanceof Uint8Array?bytes.subarray(0,1024):new Uint8Array(bytes,0,Math.min(1024,bytes.byteLength));for(let i=0;i+5<=view.length;i++){if(view[i]===37&&view[i+1]===80&&view[i+2]===68&&view[i+3]===70&&view[i+4]===45){return true}}return false}
1
+ import{decodeToks}from"./lines.js";import{MATH_MIN_CONF}from"./math.js";import{cropLine}from"./rec-preproc.js";import{BROKEN_FONT_MAP,uprightTextLayer}from"./textlayer.js";import{NOT_THE_PAGE,layerMatches,readable}from"./layer-check.js";import{isStrongL}from"./unicode.js";import{isRtl}from"./rtl.js";import{rot90}from"./upright.js";import{isPySpace,item}from"./util.js";let CHECK_DPI=72;let MAX_PAGE_PIXELS=1e8;export function rightToLeft(tokens){let rtl=0;let ltr=0;for(const[c]of tokens){if(typeof c!=="string"||[...c].length!==1)continue;if(isRtl(c))rtl++;else if(isStrongL(c))ltr++}return rtl>ltr}function covered(box,boxes,frac=0.5){let f=Math.fround;let area=Math.max(f(f(box[2]-box[0])*f(box[3]-box[1])),0.000001);return boxes.some((b)=>{let ix=Math.max(f(Math.min(box[2],b[2])-Math.max(box[0],b[0])),0);let iy=Math.max(f(Math.min(box[3],b[3])-Math.max(box[1],b[1])),0);return f(f(ix*iy)/area)>frac})}export function assignRuns(runs,boxes,k){if(!boxes.length){return{toks:[],lost:runs.reduce((n,r)=>n+r.chars.filter(([c])=>!isPySpace(c)).length,0)}}let f=Math.fround;let area=boxes.map(([x0,y0,x1,y1])=>f(f(x1-x0)*f(y1-y0)));let parts=boxes.map(()=>new Map);let lost=0;for(let run of runs){let idx=run.seq;let j;for(const[c,b]of run.chars){if(!isPySpace(c)){let cx=(b[0]+b[2])/2*k;let cy=(b[1]+b[3])/2*k;let fx=f(cx);let fy=f(cy);let best;for(const[i,[x0,y0,x1,y1]]of boxes.entries()){if(x0<=fx&&fx<=x1&&y0<=fy&&fy<=y1&&(best===undefined||item(area,i)<item(area,best))){best=i}}j=best;if(j===undefined){lost++;continue}let line=item(parts,j);line.set(idx,[...line.get(idx)??[],[c,cx,idx]])}else if(j!==undefined){let part=item(parts,j).get(idx)??[];part.push([c,part.at(-1)?.[1]??0,idx])}}}let toks=parts.map((line)=>{let all=[...line.values()].flat();let rtl=rightToLeft(all);let key=(toksOf)=>rtl?-Math.max(...toksOf.map((t)=>t[1])):Math.min(...toksOf.map((t)=>t[1]));let order=[...line.keys()].toSorted((a,b)=>key(line.get(a)??[])-key(line.get(b)??[]));let tk=[];for(let idx of order){let last=tk.at(-1);if(last)tk.push([" ",last[1],idx]);tk.push(...line.get(idx)??[])}return tk});return{toks,lost}}function pageScale(page,dpi){const[w,h]=page.size();return Math.min(dpi/72,Math.sqrt(MAX_PAGE_PIXELS/Math.max(w*h,1)))}function timed(t,key,run){let t0=performance.now();let out=run();t[key]=performance.now()-t0;return out}export async function pdfPage(pipeline,page,options={}){const{mode="auto",dpi=200,imageOcr=true}=options;let t={};let note="mode=ocr";let turn=true;if(mode!=="ocr"){let s=CHECK_DPI/72;let t0=performance.now();let read=await uprightTextLayer(page,page.render(s),s,mode,async(up)=>{t["text_ms"]=performance.now()-t0;return textPage(pipeline,page,up,t,dpi,imageOcr,mode==="auto")});if(read.page)return read.page;const{tl}=read;t["text_ms"]=performance.now()-t0;let unreadable=tl.reason!==BROKEN_FONT_MAP&&!readable(pipeline,tl.lines);note=tl.reason;if(tl.lines.length&&(tl.trusted||mode==="text"||unreadable)){let check=mode==="auto"&&tl.trusted&&!unreadable;let out=await textPage(pipeline,page,tl,t,dpi,imageOcr,check);if(out)return out;note=NOT_THE_PAGE}turn=!(tl.reason===BROKEN_FONT_MAP&&tl.stats.rotated<0.5*tl.stats.chars)}let gray=timed(t,"render_ms",()=>page.render(pageScale(page,dpi)));let out=await pipeline.page(gray,turn);out.timings={...t,...out.timings};out.timings["total_ms"]=Object.entries(out.timings).reduce((n,[k,v])=>k==="total_ms"?n:n+v,0);out.note=`${note}; ${out.note}`;return out}async function textPage(pipeline,page,tl,t,dpi,imageOcr,check=false){let k=pageScale(page,dpi);let turn=tl.stats.turn??0;let frame=tl.stats.frame??turn;let vertical=Boolean(tl.stats.vertical);let rendered=timed(t,"render_ms",()=>page.render(k));let gray=frame?rot90(rendered,frame):rendered;let t0=performance.now();let boxes=(await pipeline.detect(gray)).map(([x0,y0,x1,y1])=>[x0,y0,x1,y1]);t["det_ms"]=performance.now()-t0;const{toks,lost}=assignRuns(tl.lines,boxes,k);let rec=toks.map((tk)=>{let text=tk.length?decodeToks(pipeline.vocab,tk):"";return text?{text,conf:1,toks:tk}:undefined});if(check&&!await layerMatches(pipeline,gray,boxes,rec,t))return;let empty=rec.flatMap((r,i)=>r?[]:[i]);let source="text";let side=tl.rotated.filter((r)=>r.text.trim());let f=Math.fround;let sideBoxes=side.map((r)=>[f(r.bbox[0]*k),f(r.bbox[1]*k),f(r.bbox[2]*k),f(r.bbox[3]*k)]);if(side.length&&empty.length){empty=empty.filter((i)=>!covered(item(boxes,i),sideBoxes))}if(empty.length&&imageOcr&&readable(pipeline,tl.lines)){t0=performance.now();let read=await pipeline.recognize(gray,empty.map((i)=>item(boxes,i)),64,vertical);for(const[n,i]of empty.entries()){let r=item(read,n);if(r.text.trim()){rec[i]=r;source="hybrid"}}t["rec_ms"]=performance.now()-t0}if(pipeline.mathReader){t0=performance.now();await readMath(pipeline,gray,boxes,rec);t["math_ms"]=performance.now()-t0}let keep=rec.flatMap((r,i)=>r?[i]:[]);let keptBoxes=keep.map((i)=>item(boxes,i));let keptRec=keep.map((i)=>item(rec,i)??{text:"",conf:0,toks:[]});for(const[n,r]of side.entries()){let b=item(sideBoxes,n);keptBoxes.push(b);let cx=f(b[0]+b[2])/2;keptRec.push({text:r.text,conf:1,toks:[...r.text].map((c)=>[c,cx,r.seq])})}let out=await pipeline.assemble(gray.width,gray.height,keptBoxes,keptRec,t,vertical);out.source=source;out.rotation=90*turn;if(vertical){let w=gray.height;let back=([x0,y0,x1,y1])=>[w-y1,x0,w-y0,x1];out.lines=out.lines.map((ln)=>({...ln,box:back(ln.box)}));out.blocks=out.blocks.map((b)=>({...b,bbox:back(b.bbox)}));out.vertical=true}if(lost)out.note+=`; ${lost} chars outside detected lines`;return out}async function readMath(pipeline,gray,boxes,rec){let math=pipeline.mathReader;if(!math)return;let idx=rec.flatMap((r,i)=>{let first=r?.toks[0];return first&&typeof first[0]==="string"&&first.length>2?[i]:[]});if(!idx.length)return;let crops=idx.map((i)=>cropLine(gray,item(boxes,i),pipeline.height,pipeline.imageOps));let flagged=(await math.flags(crops)).flatMap((fl,n)=>fl?[item(idx,n)]:[]);if(!flagged.length)return;let readings=await math.read(gray,flagged.map((i)=>item(boxes,i)));for(const[n,i]of flagged.entries()){const{text,conf}=item(readings,n);let r=rec[i];if(!r||!text.includes("$")||conf<MATH_MIN_CONF)continue;let first=Math.min(...r.toks.flatMap((tk)=>tk[2]===undefined?[]:[tk[2]]));const[x0,,x1]=item(boxes,i);rec[i]={text,conf:1,toks:[[text,Math.fround(x0+x1)/2,first]]}}}export function isPdf(bytes){let view=bytes instanceof Uint8Array?bytes.subarray(0,1024):new Uint8Array(bytes,0,Math.min(1024,bytes.byteLength));for(let i=0;i+5<=view.length;i++){if(view[i]===37&&view[i+1]===80&&view[i+2]===68&&view[i+3]===70&&view[i+4]===45){return true}}return false}
@@ -0,0 +1,26 @@
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 { TextLine } from "./textlayer.js";
5
+ import type { RecLine } from "./types.js";
6
+ /** Page.note when the script check sends a page to OCR. */
7
+ export declare const NOT_THE_PAGE = "text layer does not match the page";
8
+ /** Share of the letters in `text` that are basic Latin (a-z, A-Z). */
9
+ export declare function latinShare(text: string): number;
10
+ /**
11
+ * Whether a text layer matches its page: at least AGREE_SHARE of the checked
12
+ * lines agree. A legacy font (Kruti Dev and DevLys for Hindi, Bijoy for
13
+ * Bangla) stores Latin codes for another script, so almost every line disagrees.
14
+ */
15
+ export declare function layerAgrees(agree: readonly boolean[]): boolean;
16
+ /**
17
+ * Whether the recognizers know at least READABLE_MIN of the letters in these
18
+ * runs. A recognizer that reads Hangul as jamo knows a syllable by its jamo.
19
+ */
20
+ export declare function readable(pipeline: IndraPipeline, runs: readonly TextLine[]): boolean;
21
+ /**
22
+ * A line agrees unless its layer text is Latin while the script classifier
23
+ * is sure its image is another script. Up to AGREE_LINES lines with four
24
+ * letters or more are checked, spread over the page.
25
+ */
26
+ export declare function layerMatches(pipeline: IndraPipeline, gray: Gray, boxes: readonly Box[], rec: readonly (RecLine | undefined)[], t: Record<string, number>): Promise<boolean>;
@@ -0,0 +1 @@
1
+ import{item}from"./util.js";let LETTER=/^\p{L}$/u;let READABLE_MIN=0.9;let AGREE_LINES=6;let AGREE_SHARE=0.25;let LATIN_CODES=0.9;export let NOT_THE_PAGE="text layer does not match the page";export function latinShare(text){let letters=[...text].filter((c)=>LETTER.test(c));return letters.filter((c)=>c.charCodeAt(0)<128).length/Math.max(letters.length,1)}export function layerAgrees(agree){return!agree.length||agree.filter(Boolean).length>=AGREE_SHARE*agree.length}export function readable(pipeline,runs){let letters=runs.flatMap((r)=>[...r.text].filter((c)=>LETTER.test(c)));if(!letters.length)return true;let vocabs=pipeline.vocabs.map((v)=>v.index);let known=letters.filter((c)=>vocabs.some((v)=>v.has(c)||[...c.normalize("NFD")].every((j)=>v.has(j)))).length;return known>=READABLE_MIN*letters.length}export async function layerMatches(pipeline,gray,boxes,rec,t){let full=rec.flatMap((r,i)=>r&&[...r.text].filter((c)=>LETTER.test(c)).length>=4?[i]:[]);let step=Math.max(1,Math.floor(full.length/AGREE_LINES));let pick=full.filter((_,n)=>n%step===0).slice(0,AGREE_LINES);if(!pick.length)return true;let t0=performance.now();const{names,sure}=await pipeline.boxGroups(gray,pick.map((i)=>item(boxes,i)));let agree=pick.map((i,n)=>!(latinShare(item(rec,i)?.text??"")>=LATIN_CODES&&names[n]!=="base"&&sure[n]));t["check_ms"]=performance.now()-t0;return layerAgrees(agree)}
@@ -2,6 +2,7 @@ import type { DetBox } from "./det-post.js";
2
2
  import type { Gray, ImageOps } from "./image.js";
3
3
  import type { MathReader } from "./math.js";
4
4
  import type { Box } from "./rec-preproc.js";
5
+ import type { LineGroups } from "./recognize.js";
5
6
  import type { DetectPass, IndraMeta, IndraSessions, Orientation, Page, PipelineOptions, ReadingOrder, RecLine, Straightened, TensorCtor } from "./types.js";
6
7
  import type { Vocab } from "./vocab.js";
7
8
  /**
@@ -56,6 +57,8 @@ export declare class IndraPipeline {
56
57
  * back empty.
57
58
  */
58
59
  recognize(gray: Gray, boxes: readonly Box[], batch?: number, vertical?: boolean): Promise<RecLine[]>;
60
+ /** The script group of each line box (script.onnx), and whether the classifier is sure. */
61
+ boxGroups(gray: Gray, boxes: readonly Box[]): Promise<LineGroups>;
59
62
  /**
60
63
  * OCR of one page image: measure the tilt and the turn on a preview (unless
61
64
  * `turn` is false), turn upright and deskew, detect, recognize, order and
package/indra/pipeline.js CHANGED
@@ -1 +1 @@
1
- export class IndraPipeline{Tensor;sessions;ops;vocab;longSide;height;furniture;adaptive;math;recognizers;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.recognizers=new Recognizers(Tensor,sessions,meta,ops,options.lm??true,this.math);this.vocab=this.recognizers.vocab;this.longSide=meta.det_long_side;this.height=meta.rec_height}get vocabs(){return this.recognizers.vocabs}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,skew=estimateSkew(gray,this.ops),small){let cw=turns===VERTICAL?3:turns;let image=cw?rot90(gray,cw):gray;let a=skew;if(turns===1||turns===3||turns===VERTICAL){a=estimateSkew(small?rot90(small,cw):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,vertical=false){return this.recognizers.read(gray,boxes,batch,vertical)}async page(gray,turn=true){let t0=performance.now();let small=preview(gray,this.ops);let a=estimateSkew(small,this.ops);const{turns}=turn?await this.orient(Math.abs(a)>=DESKEW_MIN?rotatePage(small,a,this.ops):small):{turns:0};let orientMs=performance.now()-t0;let t={};t0=performance.now();const{image,skew}=this.straighten(gray,turns,a,small);t["orient_ms"]=performance.now()-t0;t0=performance.now();let boxes=(await this.detect(image)).map(toBox);t["det_ms"]=performance.now()-t0;t0=performance.now();let vertical=turns===VERTICAL;let rec=await this.recognize(image,boxes,64,vertical);t["rec_ms"]=performance.now()-t0;let page=await this.assemble(image.width,image.height,boxes,rec,t,vertical);page.timings["orient_ms"]=(page.timings["orient_ms"]??0)+orientMs;page.rotation=vertical?0:90*turns;page.skew=roundTo(skew,2);page.vertical=vertical;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)}))}if(vertical){let w=image.height;let back=([x0,y0,x1,y1])=>[w-y1,x0,w-y0,x1];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={},vertical=false){let t0=performance.now();let pageRtl=pageIsRtl(rec);let parts=splitParts(this.vocab,boxes,rec,pageRtl);let ro=await this.readingOrder(parts.map((p)=>pageRtl?mirrorBox(p.box,width):p.box),parts.map((p)=>p.text),width,height);if(vertical){ro=verticalOrder(parts.map((p)=>p.box),ro)}t["order_ms"]=performance.now()-t0;return buildPage(this.vocab,parts,ro,vertical?"order=xycut":"order=model",this.furniture,t,pageRtl,width)}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{buildPage,mirrorBox,pageIsRtl,splitParts,verticalOrder}from"./assemble.js";import{decode,pageToInput}from"./det-post.js";import{N_FEATS,decodeBlocksOrder,decodeOrder,lineFeatures,medianF32,orderXYCut}from"./order-post.js";import{Recognizers}from"./recognizers.js";import{DESKEW_MIN,ORIENT_MIN,ORIENT_SIDE,VERTICAL,estimateSkew,orientInput,preview,rot90,rotatePage,roundTo,unrotateBox}from"./upright.js";import{floats,output}from"./util.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]]}
1
+ export class IndraPipeline{Tensor;sessions;ops;vocab;longSide;height;furniture;adaptive;math;recognizers;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.recognizers=new Recognizers(Tensor,sessions,meta,ops,options.lm??true,this.math);this.vocab=this.recognizers.vocab;this.longSide=meta.det_long_side;this.height=meta.rec_height}get vocabs(){return this.recognizers.vocabs}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,skew=estimateSkew(gray,this.ops),small){let cw=turns===VERTICAL?3:turns;let image=cw?rot90(gray,cw):gray;let a=skew;if(turns===1||turns===3||turns===VERTICAL){a=estimateSkew(small?rot90(small,cw):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,vertical=false){return this.recognizers.read(gray,boxes,batch,vertical)}async boxGroups(gray,boxes){return this.recognizers.boxGroups(gray,boxes)}async page(gray,turn=true){let t0=performance.now();let small=preview(gray,this.ops);let a=estimateSkew(small,this.ops);const{turns}=turn?await this.orient(Math.abs(a)>=DESKEW_MIN?rotatePage(small,a,this.ops):small):{turns:0};let orientMs=performance.now()-t0;let t={};t0=performance.now();const{image,skew}=this.straighten(gray,turns,a,small);t["orient_ms"]=performance.now()-t0;t0=performance.now();let boxes=(await this.detect(image)).map(toBox);t["det_ms"]=performance.now()-t0;t0=performance.now();let vertical=turns===VERTICAL;let rec=await this.recognize(image,boxes,64,vertical);t["rec_ms"]=performance.now()-t0;let page=await this.assemble(image.width,image.height,boxes,rec,t,vertical);page.timings["orient_ms"]=(page.timings["orient_ms"]??0)+orientMs;page.rotation=vertical?0:90*turns;page.skew=roundTo(skew,2);page.vertical=vertical;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)}))}if(vertical){let w=image.height;let back=([x0,y0,x1,y1])=>[w-y1,x0,w-y0,x1];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={},vertical=false){let t0=performance.now();let pageRtl=pageIsRtl(rec);let parts=splitParts(this.vocab,boxes,rec,pageRtl);let ro=await this.readingOrder(parts.map((p)=>pageRtl?mirrorBox(p.box,width):p.box),parts.map((p)=>p.text),width,height);if(vertical){ro=verticalOrder(parts.map((p)=>p.box),ro)}t["order_ms"]=performance.now()-t0;return buildPage(this.vocab,parts,ro,vertical?"order=xycut":"order=model",this.furniture,t,pageRtl,width)}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{buildPage,mirrorBox,pageIsRtl,splitParts,verticalOrder}from"./assemble.js";import{decode,pageToInput}from"./det-post.js";import{N_FEATS,decodeBlocksOrder,decodeOrder,lineFeatures,medianF32,orderXYCut}from"./order-post.js";import{Recognizers}from"./recognizers.js";import{DESKEW_MIN,ORIENT_MIN,ORIENT_SIDE,VERTICAL,estimateSkew,orientInput,preview,rot90,rotatePage,roundTo,unrotateBox}from"./upright.js";import{floats,output}from"./util.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]]}
@@ -1,6 +1,7 @@
1
1
  import type { Gray, ImageOps } from "./image.js";
2
2
  import type { MathReader } from "./math.js";
3
3
  import type { Box } from "./rec-preproc.js";
4
+ import type { LineGroups } from "./recognize.js";
4
5
  import type { IndraMeta, IndraSessions, RecLine, TensorCtor } from "./types.js";
5
6
  import { Vocab } from "./vocab.js";
6
7
  /**
@@ -37,6 +38,12 @@ export declare class Recognizers {
37
38
  * columns, characters on their side: all go to the CJK recognizer.
38
39
  */
39
40
  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>;
40
47
  /**
41
48
  * Text, confidence and character positions per line; a line read twice
42
49
  * 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 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;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,4 +1,5 @@
1
1
  import type { Gray } from "./image.js";
2
+ import type { Page } from "./types.js";
2
3
  import type { Box } from "./rec-preproc.js";
3
4
  export { badCharCount, codePoint, collapseSpaces, extractRuns, pageTurn, verticalLayout, visualRtlFrac, } from "./text-runs.js";
4
5
  /** TextLayer.reason when the layer's character codes are not text. */
@@ -84,16 +85,18 @@ export type TextLayer = {
84
85
  * pixels per point, turned like the runs (`frame` quarter turns clockwise).
85
86
  */
86
87
  export declare function readTextLayer(page: PdfPageSource, gray: Gray, scale: number, turn?: number, frame?: number): TextLayer;
87
- /** A page's text layer read upright, and whether it is final (read without the page's /Rotate). */
88
+ /** A page's text layer read upright, or the page already read from it. */
88
89
  export type UprightLayer = {
89
90
  tl: TextLayer;
90
- done: boolean;
91
+ page?: Page;
91
92
  };
92
93
  /**
93
94
  * The text layer of a page, read upright (`check` is a render at `scale`
94
95
  * pixels per point): a table set sideways is read in the page turned
95
- * upright, and so is a page whose /Rotate alone turns its text (a trusted
96
- * layer then is final, read without the /Rotate). Vertical writing is read in
97
- * the page turned a quarter turn counter-clockwise.
96
+ * upright, and so is a page whose /Rotate alone turns its text. A trusted
97
+ * layer read without the /Rotate goes to `readUpright` while the page is
98
+ * still turned back; when that returns no page, the turned layer is read
99
+ * instead. Vertical writing is read in the page turned a quarter turn
100
+ * counter-clockwise.
98
101
  */
99
- export declare function uprightTextLayer(page: PdfPageSource, check: Gray, scale: number, mode: string): UprightLayer;
102
+ export declare function uprightTextLayer(page: PdfPageSource, check: Gray, scale: number, mode: string, readUpright: (tl: TextLayer) => Promise<Page | undefined>): Promise<UprightLayer>;
@@ -1 +1 @@
1
- import{extractRuns,pageTurn,verticalLayout,visualRtlFrac}from"./text-runs.js";import{roundTo,rot90}from"./upright.js";export{badCharCount,codePoint,collapseSpaces,extractRuns,pageTurn,verticalLayout,visualRtlFrac}from"./text-runs.js";let MAX_INVISIBLE_FRAC=0.05;let MAX_BAD_CHAR_FRAC=0.005;let MAX_NO_INK_LINE_FRAC=0.03;let MAX_VISUAL_RTL_FRAC=0.25;let MIN_RTL_PAIRS=20;let DARK=160;let TEXT_RENDER_INVISIBLE=3;export let BROKEN_FONT_MAP="broken font map";export let VISUAL_RTL="right-to-left text in visual order";function invisibleTextFrac(page){let modes=page.textRenderModes();return modes.length?modes.filter((m)=>m===TEXT_RENDER_INVISIBLE).length/modes.length:0}function noInkFrac(gray,runs,scale){let empty=0;for(const{bbox:[x0,y0,x1,y1]}of runs){let r0=Math.max(0,Math.trunc(y0*scale));let r1=Math.min(gray.height,Math.trunc(y1*scale)+1);let c0=Math.max(0,Math.trunc(x0*scale));let c1=Math.min(gray.width,Math.trunc(x1*scale)+1);let ink=false;for(let y=r0;y<r1&&!ink;y++){for(let x=c0;x<c1;x++){if((gray.data[y*gray.width+x]??255)<DARK){ink=true;break}}}if(!ink)empty++}return empty/Math.max(runs.length,1)}let pct=(x)=>`${roundTo(x*100,0)}%`;export function readTextLayer(page,gray,scale,turn=0,frame=turn){const[w,h]=page.size();let size=frame%2?[h,w]:[w,h];let inv=invisibleTextFrac(page);let fail=(lines,reason,stats,rotated=[])=>({lines,size,trusted:false,reason,stats,rotated});if(inv>MAX_INVISIBLE_FRAC){return fail([],`invisible text ${pct(inv)} (OCR layer)`,{chars:0,rotated:0,bad:0,quarters:[0,0,0,0]})}const{runs:all,stats}=extractRuns(page,turn,frame);stats.turn=turn;stats.frame=frame;let rotated=all.filter((r)=>r.quarter);let runs=all.filter((r)=>!r.quarter);if(!runs.length)return fail([],"no text layer",stats,rotated);if(stats.bad>MAX_BAD_CHAR_FRAC*Math.max(stats.chars,1)){return fail(runs,BROKEN_FONT_MAP,stats,rotated)}const{pairs,share}=frame===turn?visualRtlFrac(runs):{pairs:0,share:0};if(pairs>=MIN_RTL_PAIRS&&share>MAX_VISUAL_RTL_FRAC){stats.visual_rtl=roundTo(share,3);return fail(runs,VISUAL_RTL,stats,rotated)}let empty=noInkFrac(gray,runs,scale);stats.no_ink=roundTo(empty,4);if(empty>MAX_NO_INK_LINE_FRAC){return fail(runs,`${pct(empty)} of text runs have no ink`,stats,rotated)}return{lines:runs,size,trusted:true,reason:"",stats,rotated}}export function uprightTextLayer(page,check,scale,mode){let tl=readTextLayer(page,check,scale);let k=pageTurn(tl.stats);let rot=page.rotation();if(k&&(rot+90*k)%360===0){page.setRotation(0);tl=readTextLayer(page,page.render(scale),scale);if(tl.lines.length&&(tl.trusted||mode==="text")){tl.stats.turn=k;return{tl,done:true}}page.setRotation(rot);tl=readTextLayer(page,rot90(check,k),scale,k)}else if(k){tl=readTextLayer(page,rot90(check,k),scale,k)}else if(verticalLayout(tl.stats)){tl=readTextLayer(page,rot90(check,3),scale,0,3);tl.stats.vertical=true}return{tl,done:false}}
1
+ import{extractRuns,pageTurn,verticalLayout,visualRtlFrac}from"./text-runs.js";import{roundTo,rot90}from"./upright.js";export{badCharCount,codePoint,collapseSpaces,extractRuns,pageTurn,verticalLayout,visualRtlFrac}from"./text-runs.js";let MAX_INVISIBLE_FRAC=0.05;let MAX_BAD_CHAR_FRAC=0.005;let MAX_NO_INK_LINE_FRAC=0.03;let MAX_VISUAL_RTL_FRAC=0.25;let MIN_RTL_PAIRS=20;let DARK=160;let TEXT_RENDER_INVISIBLE=3;export let BROKEN_FONT_MAP="broken font map";export let VISUAL_RTL="right-to-left text in visual order";function invisibleTextFrac(page){let modes=page.textRenderModes();return modes.length?modes.filter((m)=>m===TEXT_RENDER_INVISIBLE).length/modes.length:0}function noInkFrac(gray,runs,scale){let empty=0;for(const{bbox:[x0,y0,x1,y1]}of runs){let r0=Math.max(0,Math.trunc(y0*scale));let r1=Math.min(gray.height,Math.trunc(y1*scale)+1);let c0=Math.max(0,Math.trunc(x0*scale));let c1=Math.min(gray.width,Math.trunc(x1*scale)+1);let ink=false;for(let y=r0;y<r1&&!ink;y++){for(let x=c0;x<c1;x++){if((gray.data[y*gray.width+x]??255)<DARK){ink=true;break}}}if(!ink)empty++}return empty/Math.max(runs.length,1)}let pct=(x)=>`${roundTo(x*100,0)}%`;export function readTextLayer(page,gray,scale,turn=0,frame=turn){const[w,h]=page.size();let size=frame%2?[h,w]:[w,h];let inv=invisibleTextFrac(page);let fail=(lines,reason,stats,rotated=[])=>({lines,size,trusted:false,reason,stats,rotated});if(inv>MAX_INVISIBLE_FRAC){return fail([],`invisible text ${pct(inv)} (OCR layer)`,{chars:0,rotated:0,bad:0,quarters:[0,0,0,0]})}const{runs:all,stats}=extractRuns(page,turn,frame);stats.turn=turn;stats.frame=frame;let rotated=all.filter((r)=>r.quarter);let runs=all.filter((r)=>!r.quarter);if(!runs.length)return fail([],"no text layer",stats,rotated);if(stats.bad>MAX_BAD_CHAR_FRAC*Math.max(stats.chars,1)){return fail(runs,BROKEN_FONT_MAP,stats,rotated)}const{pairs,share}=frame===turn?visualRtlFrac(runs):{pairs:0,share:0};if(pairs>=MIN_RTL_PAIRS&&share>MAX_VISUAL_RTL_FRAC){stats.visual_rtl=roundTo(share,3);return fail(runs,VISUAL_RTL,stats,rotated)}let empty=noInkFrac(gray,runs,scale);stats.no_ink=roundTo(empty,4);if(empty>MAX_NO_INK_LINE_FRAC){return fail(runs,`${pct(empty)} of text runs have no ink`,stats,rotated)}return{lines:runs,size,trusted:true,reason:"",stats,rotated}}export async function uprightTextLayer(page,check,scale,mode,readUpright){let tl=readTextLayer(page,check,scale);let k=pageTurn(tl.stats);let rot=page.rotation();if(k&&(rot+90*k)%360===0){page.setRotation(0);tl=readTextLayer(page,page.render(scale),scale);if(tl.lines.length&&(tl.trusted||mode==="text")){tl.stats.turn=k;let out=await readUpright(tl);if(out)return{tl,page:out}}page.setRotation(rot);tl=readTextLayer(page,rot90(check,k),scale,k)}else if(k){tl=readTextLayer(page,rot90(check,k),scale,k)}else if(verticalLayout(tl.stats)){tl=readTextLayer(page,rot90(check,3),scale,0,3);tl.stats.vertical=true}return{tl}}
@@ -9,6 +9,12 @@ export declare const ORIENT_MIN = 0.95;
9
9
  /** orient.onnx class (5-class models): the page is set in vertical columns. */
10
10
  export declare const VERTICAL = 4;
11
11
  export declare const DESKEW_MIN = 0.3;
12
+ /**
13
+ * Degrees below which warpZero returns its input bytes on both backends, so
14
+ * the skew search skips the warp. The 0.5 and 0.1 degree passes score 0 or a
15
+ * float error away from it (np.arange gives -1.1e-16 for 0).
16
+ */
17
+ export declare const IDENTITY_TURN = 1e-9;
12
18
  /** The skew search and orient.onnx read this shrunk copy of the page, not the full scan. */
13
19
  export declare const PREVIEW_SIDE = 1600;
14
20
  /** The orient.onnx input: [side, side] ink map, long side scaled to `side`, padded with 0. */
package/indra/upright.js CHANGED
@@ -1 +1 @@
1
- import{pyRound}from"./det-post.js";import{inkOf,rotationMatrix}from"./image.js";export let ORIENT_SIDE=768;export let ORIENT_MIN=0.95;export let VERTICAL=4;let DESKEW_MAX=45;export let DESKEW_MIN=0.3;let SKEW_SIDE=800;export let PREVIEW_SIDE=1600;function thumbnail(gray,side,ops){let s=side/Math.max(gray.height,gray.width);let w=Math.max(1,pyRound(gray.width*s));let h=Math.max(1,pyRound(gray.height*s));return ops.resize(gray,w,h,"area")}export function orientInput(gray,ops,side=ORIENT_SIDE){let small=inkOf(thumbnail(gray,side,ops));let out=new Float32Array(side*side);for(let y=0;y<small.height;y++){out.set(small.data.subarray(y*small.width,(y+1)*small.width),y*side)}return out}export function preview(gray,ops,side=PREVIEW_SIDE){return side/Math.max(gray.height,gray.width)>=1?gray:thumbnail(gray,side,ops)}function inkThumb(gray,side,ops){let small=thumbnail(gray,side,ops);let data=new Uint8Array(small.data.length);for(let i=0;i<data.length;i++)data[i]=255-(small.data[i]??0);return{data,width:small.width,height:small.height}}function rowSharpness(ink,a,ops){const{width:w,height:h}=ink;let r=ops.warpZero(ink,rotationMatrix(w/2,h/2,a),w,h);let total=0;let prev=0;for(let y=0;y<h;y++){let row=0;for(let x=0;x<w;x++)row+=r.data[y*w+x]??0;if(y)total+=(row-prev)*(row-prev);prev=row}return total}export function estimateSkew(gray,ops,side=SKEW_SIDE){let fine=inkThumb(gray,side,ops);let sum=0;for(let v of fine.data)sum+=v;if(sum/fine.data.length<0.003*255)return 0;let coarse=inkThumb(gray,Math.floor(side/2),ops);let grid=arange(-DESKEW_MAX,DESKEW_MAX+0.000001,2);let scores=grid.map((a)=>rowSharpness(coarse,a,ops));let top=grid.map((_,i)=>i).toSorted((i,j)=>(scores[i]??0)-(scores[j]??0)).slice(-2);let starts=[0,...top.map((i)=>grid[i]??0)];let near=starts.flatMap((a0)=>arange(a0-2,a0+2+0.000001,0.5));let seen=new Map;for(let a of near)if(!seen.has(a))seen.set(a,rowSharpness(fine,a,ops));let a1=argmax(near,(a)=>seen.get(a)??-1/0);return argmax(arange(a1-0.5,a1+0.5+0.000001,0.1),(a)=>rowSharpness(fine,a,ops))}function arange(start,stop,step){let n=Math.ceil((stop-start)/step);let delta=start+step-start;return Array.from({length:Math.max(0,n)},(_,i)=>start+i*delta)}function argmax(values,key){let best=values[0]??0;let bestKey=-1/0;for(let v of values){let k=key(v);if(k>bestKey){best=v;bestKey=k}}return best}export function rotatePage(gray,degrees,ops){let m=rotationMatrix(gray.width/2,gray.height/2,degrees);return ops.warpReplicate(gray,m,gray.width,gray.height)}export function rot90(gray,k){let out=gray;for(let t=0;t<(k%4+4)%4;t++){const{width:w,height:h,data}=out;let next=new Uint8Array(w*h);for(let y=0;y<w;y++){for(let x=0;x<h;x++)next[y*h+x]=data[(h-1-x)*w+y]??0}out={data:next,width:h,height:w}}return out}export function unrotateBox(box,degrees,width,height){const[a,b,c,d,e,g]=rotationMatrix(width/2,height/2,-degrees);const[x0,y0,x1,y1]=box;let xs=[x0,x1,x0,x1];let ys=[y0,y0,y1,y1];let mx=xs.map((x,i)=>a*x+b*(ys[i]??0)+c);let my=xs.map((x,i)=>d*x+e*(ys[i]??0)+g);let clip=(v,hi)=>roundTo(Math.min(Math.max(v,0),hi),1);return[clip(Math.min(...mx),width),clip(Math.min(...my),height),clip(Math.max(...mx),width),clip(Math.max(...my),height)]}export function roundTo(x,digits){let p=10**digits;let t=x*p;if(Math.abs(t-Math.trunc(t))===0.5)return pyRound(t)/p;return Number(x.toFixed(digits))}
1
+ import{pyRound}from"./det-post.js";import{inkOf,rotationMatrix}from"./image.js";export let ORIENT_SIDE=768;export let ORIENT_MIN=0.95;export let VERTICAL=4;let DESKEW_MAX=45;export let DESKEW_MIN=0.3;let SKEW_SIDE=800;export let IDENTITY_TURN=0.000000001;export let PREVIEW_SIDE=1600;function thumbnail(gray,side,ops){let s=side/Math.max(gray.height,gray.width);let w=Math.max(1,pyRound(gray.width*s));let h=Math.max(1,pyRound(gray.height*s));return ops.resize(gray,w,h,"area")}export function orientInput(gray,ops,side=ORIENT_SIDE){let small=inkOf(thumbnail(gray,side,ops));let out=new Float32Array(side*side);for(let y=0;y<small.height;y++){out.set(small.data.subarray(y*small.width,(y+1)*small.width),y*side)}return out}export function preview(gray,ops,side=PREVIEW_SIDE){return side/Math.max(gray.height,gray.width)>=1?gray:thumbnail(gray,side,ops)}function inkThumb(gray,side,ops){let small=thumbnail(gray,side,ops);let data=new Uint8Array(small.data.length);for(let i=0;i<data.length;i++)data[i]=255-(small.data[i]??0);return{data,width:small.width,height:small.height}}function rowSharpness(ink,a,ops){const{width:w,height:h}=ink;let r=Math.abs(a)<IDENTITY_TURN?ink:ops.warpZero(ink,rotationMatrix(w/2,h/2,a),w,h);let total=0;let prev=0;for(let y=0;y<h;y++){let row=0;for(let x=0;x<w;x++)row+=r.data[y*w+x]??0;if(y)total+=(row-prev)*(row-prev);prev=row}return total}export function estimateSkew(gray,ops,side=SKEW_SIDE){let fine=inkThumb(gray,side,ops);let sum=0;for(let v of fine.data)sum+=v;if(sum/fine.data.length<0.003*255)return 0;let coarse=inkThumb(gray,Math.floor(side/2),ops);let grid=arange(-DESKEW_MAX,DESKEW_MAX+0.000001,2);let scores=grid.map((a)=>rowSharpness(coarse,a,ops));let top=grid.map((_,i)=>i).toSorted((i,j)=>(scores[i]??0)-(scores[j]??0)).slice(-2);let starts=[0,...top.map((i)=>grid[i]??0)];let near=starts.flatMap((a0)=>arange(a0-2,a0+2+0.000001,0.5));let seen=new Map;for(let a of near)if(!seen.has(a))seen.set(a,rowSharpness(fine,a,ops));let a1=argmax(near,(a)=>seen.get(a)??-1/0);return argmax(arange(a1-0.5,a1+0.5+0.000001,0.1),(a)=>rowSharpness(fine,a,ops))}function arange(start,stop,step){let n=Math.ceil((stop-start)/step);let delta=start+step-start;return Array.from({length:Math.max(0,n)},(_,i)=>start+i*delta)}function argmax(values,key){let best=values[0]??0;let bestKey=-1/0;for(let v of values){let k=key(v);if(k>bestKey){best=v;bestKey=k}}return best}export function rotatePage(gray,degrees,ops){let m=rotationMatrix(gray.width/2,gray.height/2,degrees);return ops.warpReplicate(gray,m,gray.width,gray.height)}export function rot90(gray,k){let out=gray;for(let t=0;t<(k%4+4)%4;t++){const{width:w,height:h,data}=out;let next=new Uint8Array(w*h);for(let y=0;y<w;y++){for(let x=0;x<h;x++)next[y*h+x]=data[(h-1-x)*w+y]??0}out={data:next,width:h,height:w}}return out}export function unrotateBox(box,degrees,width,height){const[a,b,c,d,e,g]=rotationMatrix(width/2,height/2,-degrees);const[x0,y0,x1,y1]=box;let xs=[x0,x1,x0,x1];let ys=[y0,y0,y1,y1];let mx=xs.map((x,i)=>a*x+b*(ys[i]??0)+c);let my=xs.map((x,i)=>d*x+e*(ys[i]??0)+g);let clip=(v,hi)=>roundTo(Math.min(Math.max(v,0),hi),1);return[clip(Math.min(...mx),width),clip(Math.min(...my),height),clip(Math.max(...mx),width),clip(Math.max(...my),height)]}export function roundTo(x,digits){let p=10**digits;let t=x*p;if(Math.abs(t-Math.trunc(t))===0.5)return pyRound(t)/p;return Number(x.toFixed(digits))}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ppu-indra-ocr",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "TypeScript SDK for Datalab's Indra OCR models: page orientation, line detection, recognition (Latin, Cyrillic, Greek, Devanagari, Bengali, Chinese), reading order, layout blocks, markdown, optional math, and PDF text layers. Runs on Node.js, Bun, Deno, browsers, web workers and React Native via ONNX Runtime.",
5
5
  "keywords": [
6
6
  "accurate-ocr",
@@ -79,7 +79,7 @@
79
79
  },
80
80
  "homepage": "https://github.com/PT-Perkasa-Pilar-Utama/ppu-indra-ocr#readme",
81
81
  "dependencies": {
82
- "ppu-ocv": "^4.0.0"
82
+ "ppu-ocv": "^4.0.1"
83
83
  },
84
84
  "peerDependencies": {
85
85
  "@embedpdf/pdfium": "^2.15.1",