ppu-indra-ocr 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-STATUS.md +25 -9
- package/README.md +76 -65
- package/cli/commands.js +2 -2
- package/cli/help.d.ts +1 -1
- package/cli/help.js +3 -3
- package/cli/options.d.ts +2 -0
- package/cli/options.js +1 -1
- package/core/indra-ocr.service.d.ts +2 -0
- package/core/indra-ocr.service.js +1 -1
- package/core/load-math.d.ts +11 -0
- package/core/load-math.js +1 -0
- package/core/opencv-image-ops.js +1 -1
- package/core/platform.d.ts +2 -0
- package/indra/agree.d.ts +70 -0
- package/indra/agree.js +1 -0
- package/indra/assemble.d.ts +14 -3
- package/indra/assemble.js +1 -1
- package/indra/ctc.d.ts +28 -0
- package/indra/ctc.js +1 -0
- package/indra/document.js +1 -1
- package/indra/image.d.ts +2 -0
- package/indra/layer-check.d.ts +29 -15
- package/indra/layer-check.js +1 -1
- package/indra/layer-gaps.d.ts +23 -0
- package/indra/layer-gaps.js +1 -0
- package/indra/layer-math.d.ts +13 -0
- package/indra/layer-math.js +1 -0
- package/indra/layout-post.d.ts +17 -2
- package/indra/layout-post.js +5 -5
- package/indra/line-thumbs.d.ts +34 -0
- package/indra/line-thumbs.js +1 -0
- package/indra/lines.d.ts +1 -1
- package/indra/lines.js +1 -1
- package/indra/math-decoder.d.ts +16 -0
- package/indra/math-decoder.js +1 -0
- package/indra/math-span-img.d.ts +61 -0
- package/indra/math-span-img.js +1 -0
- package/indra/math-splice.d.ts +46 -0
- package/indra/math-splice.js +1 -0
- package/indra/math-text.d.ts +98 -0
- package/indra/math-text.js +1 -0
- package/indra/math.d.ts +48 -9
- package/indra/math.js +1 -1
- package/indra/numeric.d.ts +8 -0
- package/indra/numeric.js +1 -1
- package/indra/order-post.js +1 -1
- package/indra/page-layout.d.ts +22 -0
- package/indra/page-layout.js +1 -0
- package/indra/page-tables.d.ts +32 -0
- package/indra/page-tables.js +1 -0
- package/indra/pipeline.d.ts +24 -10
- package/indra/pipeline.js +1 -1
- package/indra/py-text.d.ts +14 -0
- package/indra/py-text.js +1 -0
- package/indra/py-unicode.d.ts +28 -0
- package/indra/py-unicode.js +1 -0
- package/indra/rec-preproc.d.ts +8 -1
- package/indra/rec-preproc.js +1 -1
- package/indra/recognize.d.ts +19 -8
- package/indra/recognize.js +1 -1
- package/indra/recognizers.d.ts +40 -13
- package/indra/recognizers.js +1 -1
- package/indra/sequence-matcher.d.ts +34 -0
- package/indra/sequence-matcher.js +1 -0
- package/indra/symbol-digits.d.ts +29 -0
- package/indra/symbol-digits.js +1 -0
- package/indra/table-block-features.d.ts +38 -0
- package/indra/table-block-features.js +1 -0
- package/indra/table-decode.d.ts +50 -0
- package/indra/table-decode.js +4 -0
- package/indra/table-features.d.ts +34 -0
- package/indra/table-features.js +1 -0
- package/indra/table-heads.d.ts +15 -0
- package/indra/table-heads.js +2 -0
- package/indra/table-rel.d.ts +42 -0
- package/indra/table-rel.js +1 -0
- package/indra/table-split.d.ts +44 -0
- package/indra/table-split.js +1 -0
- package/indra/table-text.d.ts +15 -0
- package/indra/table-text.js +1 -0
- package/indra/table-verify.d.ts +80 -0
- package/indra/table-verify.js +1 -0
- package/indra/text-runs.d.ts +4 -0
- package/indra/text-runs.js +1 -1
- package/indra/textlayer.d.ts +18 -0
- package/indra/textlayer.js +1 -1
- package/indra/tiles.d.ts +20 -0
- package/indra/tiles.js +1 -0
- package/indra/ts-image-ops.js +1 -1
- package/indra/turn-check.d.ts +30 -0
- package/indra/turn-check.js +1 -0
- package/indra/types.d.ts +69 -5
- package/indra/upright.d.ts +1 -1
- package/indra/upright.js +1 -1
- package/indra/util.d.ts +8 -0
- package/indra/util.js +1 -1
- package/indra/vocab.d.ts +11 -0
- package/indra/vocab.js +1 -1
- package/interface.d.ts +9 -4
- package/mobile/platform.mobile.d.ts +1 -0
- package/mobile/platform.mobile.js +1 -1
- package/model-catalogue.d.ts +23 -7
- package/model-catalogue.js +1 -1
- package/package.json +2 -2
- package/pdf/pdfium.d.ts +2 -0
- package/pdf/pdfium.js +1 -1
- package/processor/indra-ocr.service.d.ts +4 -3
- package/processor/indra-ocr.service.js +1 -1
- package/processor/platform.node.d.ts +1 -0
- package/processor/platform.node.js +1 -1
- package/web/platform.web.d.ts +1 -0
- package/web/platform.web.js +1 -1
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** A prose segment is spliced only when this share of its characters align with the plain reading. */
|
|
2
|
+
export declare const SPLICE_MIN_SEG = 0.5;
|
|
3
|
+
/** ... and only when the line's prose as a whole reaches this share: else the line keeps today's reading. */
|
|
4
|
+
export declare const SPLICE_MIN_LINE = 0.6;
|
|
5
|
+
export declare const SP = "\\t-\\r\\u001c-\\u0020\\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
|
|
6
|
+
export declare const TEXT_STYLE = "mathrm|mathbf|mathit|mathsf|mathtt|mathcal|mathbb|boldsymbol|textbf|textit|textrm|text|operatorname";
|
|
7
|
+
export declare const STYLE_SOURCE: string;
|
|
8
|
+
export declare const ACCENT: RegExp;
|
|
9
|
+
/** A character without its accents, lower case (one character out): `_fold`. */
|
|
10
|
+
export declare function fold(c: string): string;
|
|
11
|
+
/** `_fold(c) != c.lower()`: the character has an accent. */
|
|
12
|
+
export declare const accentedLetter: (c: string) => boolean;
|
|
13
|
+
export declare const hasAccents: (draft: string) => boolean;
|
|
14
|
+
/**
|
|
15
|
+
* MathRec's reading with the accents of the plain reading put back in its prose:
|
|
16
|
+
* MathRec writes Latin letters without accents ("duvodu" for "d u-with-hacek vodu").
|
|
17
|
+
* Only prose letters that match a letter of the plain reading change; the $...$ spans
|
|
18
|
+
* stay as MathRec wrote them.
|
|
19
|
+
*/
|
|
20
|
+
export declare function restoreAccents(reading: string, draft: string): string;
|
|
21
|
+
/** One character for the alignment: no accents, lower case, look-alike letters as one Latin letter. */
|
|
22
|
+
export declare const look: (c: string) => string;
|
|
23
|
+
/** An alignment unit: (folded unit, start, end) in code points of the text. */
|
|
24
|
+
export type Unit = readonly [unit: string, start: number, end: number];
|
|
25
|
+
/**
|
|
26
|
+
* Alignment units of a text, spaces left out. A LaTeX command is one unit (a Greek
|
|
27
|
+
* letter as its look-alike), and the structure of a $...$ span (braces, ^, _, styling
|
|
28
|
+
* commands) writes none, so a span compares with the plain characters it stands for.
|
|
29
|
+
* A plain reading may hold commands as well ("Burada \sigma ana").
|
|
30
|
+
*/
|
|
31
|
+
export declare function units(text: string): Unit[];
|
|
32
|
+
/**
|
|
33
|
+
* MathRec's reading with its prose (the text outside $...$) taken from the plain
|
|
34
|
+
* reading: MathRec writes LaTeX and Latin letters, so prose around a formula loses
|
|
35
|
+
* accents and letters of other scripts. The reading's prose characters and its spans'
|
|
36
|
+
* plain characters are aligned with the plain reading on a folded form (look). Each
|
|
37
|
+
* prose segment maps to the plain characters between its first and last aligned
|
|
38
|
+
* position, and that substring replaces the segment when it holds non-ASCII letters
|
|
39
|
+
* that the segment lacks. A span that only writes an accent over one letter counts as
|
|
40
|
+
* prose when the plain reading has accents.
|
|
41
|
+
*
|
|
42
|
+
* today: the text without the splice (default: restoreAccents). It comes back
|
|
43
|
+
* unchanged when nothing is lost, when the line is all math, or when the alignment is
|
|
44
|
+
* not sure (SPLICE_MIN_SEG, SPLICE_MIN_LINE).
|
|
45
|
+
*/
|
|
46
|
+
export declare function spliceProse(reading: string, draft: string, today?: string): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{greekSmallLetter,isAlpha,isCombining,pyLstrip,pyRstrip,pyStrip}from"./py-unicode.js";import{SequenceMatcher}from"./sequence-matcher.js";import{isPySpace,item}from"./util.js";export let SPLICE_MIN_SEG=0.5;export let SPLICE_MIN_LINE=0.6;export let SP="\\t-\\r\\u001c-\\u0020\\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";let WORD_END="(?![\\p{L}\\p{N}_])";export let TEXT_STYLE="mathrm|mathbf|mathit|mathsf|mathtt|mathcal|mathbb|boldsymbol|textbf|textit|textrm|text|operatorname";export let STYLE_SOURCE=`\\\\(?:${TEXT_STYLE})${WORD_END}|\\\\[,;:! %#&$]|\\\\q?quad${WORD_END}|[{}~${SP}]`;let STYLE_FULL=new RegExp(`^(?:${STYLE_SOURCE})$`,"u");export let ACCENT=new RegExp(`^[${SP}]*\\\\(?:hat|bar|dot|ddot|tilde|acute|grave|breve|check)[${SP}]*\\{[${SP}]*\\\\?[A-Za-z]{1,8}[${SP}]*\\}[${SP}]*$`,"u");let ASCII_LETTER=/^[A-Za-z]$/;let ACCENT_SPAN=/(\$[^$]*\$)/;let GREEK=/^\\(?:var)?([a-z]+)$/;let LOOK_FROM="430 432 441 435 4bb 456 458 43a 43c 43d 43e 440 455 442 443 445 44c 501 51b 51d 433 454 3b1 3b2 3b5 3b7 3b9 3ba 3bd 3bf 3c1 3c4 3c5 3c7 3c9 3f2 3f3 131 237 142 111 f0 127 167 f8 153 e6 df fe 1bf 259 25b 254";let LOOK_TO="abcehijkmhopstyxbdqwreabenikvoptuxwcjijlddhtooabppeeo";let LOOK=new Map(LOOK_FROM.split(" ").map((h,i)=>[Number.parseInt(h,16),LOOK_TO.charAt(i)]));export function fold(c){let base=Array.from(c.normalize("NFKD")).filter((x)=>!isCombining(x));return(base[0]??c).toLowerCase()}export let accentedLetter=(c)=>isAlpha(c)&&fold(c)!==c.toLowerCase();export let hasAccents=(draft)=>Array.from(draft).some(accentedLetter);export function restoreAccents(reading,draft){if(!pyStrip(draft))return reading;let chars=reading.split("$").map((p)=>Array.from(p));let pos=[];for(let k=0;k<chars.length;k+=2){item(chars,k).forEach((c,i)=>{if(isAlpha(c))pos.push([k,i])})}let b=Array.from(draft).filter(isAlpha);if(!pos.length||!b.length)return reading;let sm=new SequenceMatcher(pos.map(([k,i])=>fold(item(item(chars,k),i))),b.map(fold));for(const[op,a0,a1,b0,b1]of sm.getOpcodes()){if(op!=="equal"&&!(op==="replace"&&a1-a0===b1-b0&&b1-b0<=2))continue;for(let t=0;t<a1-a0;t++){const[k,i]=item(pos,a0+t);let c=item(b,b0+t);if(accentedLetter(c))item(chars,k)[i]=c}}return chars.map((p)=>p.join("")).join("$")}export let look=(c)=>Array.from(fold(c),(x)=>LOOK.get(x.codePointAt(0)??0)??x).join("");let isAsciiLetter=(c)=>c!==undefined&&ASCII_LETTER.test(c);export function units(text){let cps=Array.from(text);let out=[];for(let i=0;i<cps.length;){let c=item(cps,i);let end=i+1;if(c==="\\")while(isAsciiLetter(cps[end]))end++;let tok=cps.slice(i,end).join("");let start=i;i=end;if(isPySpace(c))continue;if(tok.startsWith("\\")){if(STYLE_FULL.test(tok))continue;let g=GREEK.exec(tok);let letter=g?.[1]===undefined?undefined:greekSmallLetter(g[1]);out.push([letter===undefined?tok:look(letter),start,end])}else if(!"{}^_~".includes(tok)){out.push([look(tok),start,end])}}return out}function letters(s){let n=new Map;for(let c of s){if(isAlpha(c)&&(c.codePointAt(0)??0)>127)n.set(c,(n.get(c)??0)+1)}return n}function hasMoreLetters(sub,t){let have=letters(t);for(const[c,count]of letters(sub))if(count>(have.get(c)??0))return true;return false}function segments(parts,tparts,accented){let segs=[];parts.forEach((part,k)=>{let p=part;let t=item(tparts,k);if(k%2===1&&!(accented&&ACCENT.test(p))){segs.push({prose:false,reading:p,today:t});return}if(k%2===1){p=`$${p}$`;t=`$${t}$`}let last=segs.at(-1);if(last?.prose){last.reading+=p;last.today+=t}else{segs.push({prose:true,reading:p,today:t})}});return segs}function readingUnits(segs){let out=[];segs.forEach((seg,n)=>{if(!seg.prose){for(const[u]of units(seg.reading))out.push([u,n]);return}for(let piece of seg.reading.split(ACCENT_SPAN)){if(piece.length>1&&piece.startsWith("$")&&piece.endsWith("$")){out.push(["\x00",n])}else{for(let c of piece)if(!isPySpace(c))out.push([look(c),n])}}});return out}function align(kindOf,u,d){let start=Array.from({length:u.length},()=>0);let end=Array.from({length:u.length},()=>0);let hit=Array.from({length:u.length},()=>false);for(const[op,a0,a1,b0,b1]of new SequenceMatcher(u,d).getOpcodes()){if(op==="equal"){for(let i=a0;i<a1;i++){start[i]=b0+i-a0;end[i]=b0+i-a0+1;hit[i]=true}continue}let kinds=kindOf.slice(a0,a1);let first=kinds[0]===true;let cut=-1;for(let i=1;i<kinds.length&&cut<0;i++)if(kinds[i]!==kinds[0])cut=i;let mid=null;if(cut>=0&&kinds.slice(cut).every((k)=>k===kinds[cut])){let take=Math.min(first?cut:kinds.length-cut,b1-b0);mid=first?b0+take:b1-take}for(let i=a0;i<a1;i++){let r=i-a0;if(mid===null){start[i]=b0+Math.floor(r*(b1-b0)/(a1-a0));end[i]=b0+Math.floor((r+1)*(b1-b0)/(a1-a0))}else if(first){[start[i],end[i]]=r<cut?[Math.min(b0+r,mid),Math.min(b0+r+1,mid)]:[mid,b1]}else{let q=r-cut;[start[i],end[i]]=r<cut?[b0,mid]:[Math.min(mid+q,b1),Math.min(mid+q+1,b1)]}}}return{start,end,hit}}let count=(flags,ids)=>ids.reduce((n,i)=>n+(flags[i]?1:0),0);export function spliceProse(reading,draft,today=restoreAccents(reading,draft)){if(!pyStrip(draft)||letters(draft).size===0||!reading.includes("$"))return today;let parts=reading.split("$");let tparts=today.split("$");if(parts.length!==tparts.length||parts.length%2===0)return today;let segs=segments(parts,tparts,hasAccents(draft));if(!segs.some((s)=>s.prose&&Array.from(s.reading).some(isAlpha)))return today;let ru=readingUnits(segs);let du=units(draft);const{start,end,hit}=align(ru.map(([,n])=>item(segs,n).prose),ru.map(([u])=>u),du.map(([u])=>u));let proseIds=ru.flatMap(([,n],i)=>item(segs,n).prose?[i]:[]);if(!proseIds.length||count(hit,proseIds)<SPLICE_MIN_LINE*proseIds.length)return today;let draftCps=Array.from(draft);let out=[];for(const[n,seg]of segs.entries()){if(!seg.prose){out.push(`$${seg.today}$`);continue}let ids=proseIds.filter((i)=>item(ru,i)[1]===n);let first=ids[0];let last=ids.at(-1);let lo=first===undefined?0:item(start,first);let hi=last===undefined?0:item(end,last);let sub=hi>lo?draftCps.slice(item(du,lo)[1],item(du,hi-1)[2]).join(""):"";if(!hasMoreLetters(sub,seg.today)){out.push(seg.today);continue}let span=(hi-lo)/ids.length;if(count(hit,ids)<SPLICE_MIN_SEG*ids.length||!(span>=0.5&&span<=2))return today;let lead=seg.reading.slice(0,seg.reading.length-pyLstrip(seg.reading).length);let trail=seg.reading.slice(pyRstrip(seg.reading).length);out.push(lead+sub+trail)}return out.join("")}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { SPLICE_MIN_LINE, SPLICE_MIN_SEG, fold, look, restoreAccents, spliceProse, units } from "./math-splice.js";
|
|
2
|
+
import type { Unit } from "./math-splice.js";
|
|
3
|
+
export { SPLICE_MIN_LINE, SPLICE_MIN_SEG, fold, look, restoreAccents, spliceProse, units };
|
|
4
|
+
export type { Unit };
|
|
5
|
+
/** A math reading replaces a line only at this mean token probability or more (no learned head). */
|
|
6
|
+
export declare const MATH_MIN_CONF = 0.9;
|
|
7
|
+
/** `math_accept.json`: a logistic head on the features of a reading. */
|
|
8
|
+
export type MathAcceptHead = {
|
|
9
|
+
w: readonly number[];
|
|
10
|
+
mu: readonly number[];
|
|
11
|
+
sd: readonly number[];
|
|
12
|
+
tau: number;
|
|
13
|
+
features?: readonly string[];
|
|
14
|
+
};
|
|
15
|
+
/** `math_gate.json`: a logistic gate on `gateFeatures`. */
|
|
16
|
+
export type MathGateHead = {
|
|
17
|
+
w: readonly number[];
|
|
18
|
+
b: number;
|
|
19
|
+
z_min: number;
|
|
20
|
+
keep?: number;
|
|
21
|
+
features?: string;
|
|
22
|
+
train_reads?: number;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* A MathRec reading holds math: a $...$ span with a command (\frac, \alpha, \leq),
|
|
26
|
+
* a superscript or a subscript once styling and spacing are gone. A span of plain
|
|
27
|
+
* characters (a number, a word, "x = 2") writes the same as plain text, and the line
|
|
28
|
+
* keeps the recognizer's reading.
|
|
29
|
+
*/
|
|
30
|
+
export declare function hasMath(text: string): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* A reading's $...$ spans hold structure a text layer cannot write: a superscript, a
|
|
33
|
+
* subscript, or a command with an argument (\frac{, \sqrt{, \hat{). A text layer has
|
|
34
|
+
* every symbol (alpha, triangle, the element sign) as a character, so a span of
|
|
35
|
+
* symbols and plain characters adds nothing to it.
|
|
36
|
+
*/
|
|
37
|
+
export declare function hasStructure(text: string): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* The line's text when MathRec's reading replaces the plain reading (the recognizer's
|
|
40
|
+
* or the text layer's), else null: the reading must hold math (hasMath) once accents
|
|
41
|
+
* written as math are left out (when the plain reading has accented letters), and it
|
|
42
|
+
* must not write LaTeX outside its $...$ spans (a malformed reading). The plain
|
|
43
|
+
* reading's accents go back into the prose (restoreAccents).
|
|
44
|
+
*/
|
|
45
|
+
export declare function acceptMath(reading: string, draft: string): string | null;
|
|
46
|
+
/**
|
|
47
|
+
* Whether MathRec may read a line with this text (the recognizer's or the text layer's
|
|
48
|
+
* reading). MathRec writes Latin letters only: a line whose letters are mostly of
|
|
49
|
+
* another script (Greek or Cyrillic prose, any other script) stays with its own
|
|
50
|
+
* reading. A letter of another script on its own (a Greek variable) is a math symbol,
|
|
51
|
+
* not text: only runs of 2 or more such letters count. A line without such text
|
|
52
|
+
* (numbers, symbols) may go.
|
|
53
|
+
*/
|
|
54
|
+
export declare function latinLine(text: string): boolean;
|
|
55
|
+
/** Letters, digits and a few operators of a LaTeX reading (commands dropped). */
|
|
56
|
+
export declare const sigReading: (text: string) => string;
|
|
57
|
+
/** The same for a plain reading, after NFKC. */
|
|
58
|
+
export declare const sigDraft: (text: string) => string;
|
|
59
|
+
/**
|
|
60
|
+
* Features of a flagged line for the read gate (mathGate): its math-classifier
|
|
61
|
+
* probability, what its draft is made of, and page counts. 16 numbers.
|
|
62
|
+
*/
|
|
63
|
+
export declare function gateFeatures(prob: number, draft: string, nFlagged: number, pmax: number, nCand: number, source: string): number[];
|
|
64
|
+
/** The single-character tokens of `math_meta.json`: the letters MathRec can write. */
|
|
65
|
+
export declare const mathChars: (tokens: readonly string[]) => ReadonlySet<string>;
|
|
66
|
+
/**
|
|
67
|
+
* Whether MathRec's vocabulary writes this line's letters (the recognizer's or the
|
|
68
|
+
* text layer's reading): at least `share` of them are its tokens. A MathRec whose
|
|
69
|
+
* vocabulary holds another script's letters may then read lines of that script; one
|
|
70
|
+
* with Latin letters only writes no such line, and latinLine alone decides.
|
|
71
|
+
*/
|
|
72
|
+
export declare function mathWrites(chars: ReadonlySet<string>, text: string, share?: number): boolean;
|
|
73
|
+
/**
|
|
74
|
+
* The line's text when MathRec's reading replaces the plain reading, else null. With
|
|
75
|
+
* `math_accept.json` (`head`), a learned logistic head decides (features of the
|
|
76
|
+
* reading, its confidence, the recognizer's confidence and the agreement with the
|
|
77
|
+
* draft); else the reading needs conf >= MATH_MIN_CONF and acceptMath. A malformed
|
|
78
|
+
* reading (LaTeX outside its $...$ spans) never replaces the line. With proseSplice,
|
|
79
|
+
* the accepted text keeps the plain reading's prose (spliceProse).
|
|
80
|
+
*/
|
|
81
|
+
export declare function mathAccept(head: MathAcceptHead | null, text: string, conf: number, draft: string, rconf?: number, inTable?: number, proseSplice?: boolean): string | null;
|
|
82
|
+
/**
|
|
83
|
+
* Which flagged lines MathRec reads. With `math_gate.json` (`head`), a learned logistic
|
|
84
|
+
* gate skips lines whose reading would not be used (features: gateFeatures); without
|
|
85
|
+
* it every flagged line is read.
|
|
86
|
+
*/
|
|
87
|
+
export declare function mathGate(head: MathGateHead | null, probs: readonly number[], drafts: readonly string[], nCand: number, source: string): boolean[];
|
|
88
|
+
/** The decoder's state after a token, and whether the reading can no longer pass acceptMath. */
|
|
89
|
+
export type TextLikeStep = {
|
|
90
|
+
inMath: boolean;
|
|
91
|
+
textLike: boolean;
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Tracks one emitted token: true when the reading can no longer pass acceptMath (a
|
|
95
|
+
* LaTeX command outside the $...$ spans). `inMath` is whether the decoder is inside a
|
|
96
|
+
* $...$ span before the token; the result has it after the token.
|
|
97
|
+
*/
|
|
98
|
+
export declare function textLike(token: string, inMath: boolean): TextLikeStep;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ACCENT,SP,SPLICE_MIN_LINE,SPLICE_MIN_SEG,STYLE_SOURCE,TEXT_STYLE,fold,hasAccents,look,restoreAccents,spliceProse,units}from"./math-splice.js";import{hasLatinName,isAlpha,isCategoryM,isDigit,isUpper,pyLen,pySplit}from"./py-unicode.js";import{SequenceMatcher}from"./sequence-matcher.js";import{item}from"./util.js";export{SPLICE_MIN_LINE,SPLICE_MIN_SEG,fold,look,restoreAccents,spliceProse,units};export let MATH_MIN_CONF=0.9;let STYLE=new RegExp(STYLE_SOURCE,"gu");let SYMBOL=/\\(?:pm|mp|times|cdot|div|leq|geq|le|ge|neq|ne|approx|sim|simeq|equiv|rightarrow|leftarrow|to|uparrow|downarrow|longrightarrow|circ|degree|ldots|cdots|dots|prime|bullet|star|ast|mid|vert|Rightarrow|Leftarrow|Leftrightarrow|leftrightarrow)(?![A-Za-z])/g;let TEXT_STYLE_ARG=new RegExp(`\\\\(?:${TEXT_STYLE})[${SP}]*\\{([^{}]*)\\}`,"gu");let COMMAND_ARG=new RegExp(`\\\\[A-Za-z]+[${SP}]*\\{`,"u");let LATEX_COMMAND=/\\[A-Za-z]/;let OUTSIDE_MARKUP=/\\[A-Za-z]|[\^_{}]/;let COMMAND_OR_CHAR=/\\[A-Za-z]+/g;let SIG_KEEP=new Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-=<>()/");let GATE_OPS=new Set("=+-*/<>^_|".split("").concat([8721,8747,8730,8804,8805,177,215,247,8706,8734,8776,8800,8712,8704,8707,8594,8592].map((cp)=>String.fromCodePoint(cp))));let CURRENCY=new Set("$%".split("").concat([8364,163,165].map((cp)=>String.fromCodePoint(cp))));let spans=(parts)=>parts.filter((_,k)=>k%2===1);let proseParts=(parts)=>parts.filter((_,k)=>k%2===0);export function hasMath(text){return spans(text.split("$")).some((span)=>{let s=span.replace(SYMBOL,"").replace(STYLE,"");return s.includes("\\")||s.includes("^")||s.includes("_")})}export function hasStructure(text){return spans(text.split("$")).some((span)=>{let s=span.replace(TEXT_STYLE_ARG,"$1");return s.includes("^")||s.includes("_")||COMMAND_ARG.test(s)})}export function acceptMath(reading,draft){let parts=reading.split("$");if(proseParts(parts).some((p)=>LATEX_COMMAND.test(p)))return null;let accented=hasAccents(draft);let kept=spans(parts).filter((sp)=>!(accented&&ACCENT.test(sp)));if(!hasMath(kept.map((sp)=>`$${sp}$`).join("")))return null;return restoreAccents(reading,draft)}export function latinLine(text){let latin=0;let other=0;let run=0;for(let c of`${text} `){if(isCategoryM(c)){if(run>0)run++;continue}if(isAlpha(c)&&!hasLatinName(c)){run++;continue}if(run>=2)other+=run;run=0;if(isAlpha(c))latin++}return latin>other||other===0}export let sigReading=(text)=>Array.from(text.replace(COMMAND_OR_CHAR," ")).filter((c)=>SIG_KEEP.has(c)).join("");export let sigDraft=(text)=>Array.from(text.normalize("NFKC")).filter((c)=>SIG_KEEP.has(c)).join("");export function gateFeatures(prob,draft,nFlagged,pmax,nCand,source){let cps=Array.from(draft);let n=Math.max(1,cps.length);let share=(f)=>cps.filter(f).length/n;return[prob,Math.log1p(cps.length),share(isDigit),share(isAlpha),share((c)=>GATE_OPS.has(c)),share((c)=>CURRENCY.has(c)),share((c)=>c===" "),pySplit(draft).length,share((c)=>879<(c.codePointAt(0)??0)&&(c.codePointAt(0)??0)<1024),draft.includes("=")?1:0,share(isUpper),Math.log1p(nFlagged),pmax,Math.log1p(nCand),source==="ocr"?1:0,source==="text"?1:0]}export let mathChars=(tokens)=>new Set(tokens.filter((t)=>pyLen(t)===1));export function mathWrites(chars,text,share=0.9){let letterList=Array.from(text).filter(isAlpha);return letterList.length>0&&letterList.filter((c)=>chars.has(c)).length>=share*letterList.length}function spliced(text,draft,out,proseSplice){return out===null||!proseSplice?out:spliceProse(text,draft,out)}export function mathAccept(head,text,conf,draft,rconf=1,inTable=0,proseSplice=true){if(head===null){let out=conf>=MATH_MIN_CONF?acceptMath(text,draft):null;return spliced(text,draft,out,proseSplice)}let parts=text.split("$");if(!text||proseParts(parts).some((p)=>OUTSIDE_MARKUP.test(p)))return null;let kept=acceptMath(text,draft);let inside=spans(parts).reduce((n,p)=>n+pyLen(p),0)/Math.max(1,pyLen(text.replaceAll("$","")));let agree=new SequenceMatcher(sigDraft(draft),sigReading(text)).ratio();let ok=kept===null?0:1;let x=[conf,rconf,ok,inside,agree,Math.log1p(pySplit(text).length),ok*conf];if(head.mu.length>x.length)x.push(inTable);let n=Math.min(head.w.length-1,x.length,head.mu.length,head.sd.length);let sum=0;for(let i=0;i<n;i++){sum+=item(head.w,i+1)*(item(x,i)-item(head.mu,i))/item(head.sd,i)}let z=item(head.w,0)+sum;if(1/(1+Math.exp(-z))<head.tau)return null;return spliced(text,draft,kept??(text.includes("$")?text:null),proseSplice)}export function mathGate(head,probs,drafts,nCand,source){if(head===null||probs.length===0)return probs.map(()=>true);let pmax=Math.max(...probs);return probs.slice(0,drafts.length).map((p,i)=>{let x=gateFeatures(p,item(drafts,i),probs.length,pmax,nCand,source);let n=Math.min(head.w.length,x.length);let z=0;for(let k=0;k<n;k++)z+=item(head.w,k)*item(x,k);return head.b+z>=head.z_min})}export function textLike(token,inMath){if(token==="$")return{inMath:!inMath,textLike:false};let cps=Array.from(token);return{inMath,textLike:!inMath&&cps.length>1&&cps[0]==="\\"&&isAlpha(item(cps,1))}}
|
package/indra/math.d.ts
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
import type { InferenceSession } from "onnxruntime-common";
|
|
2
2
|
import type { FloatImage, Gray, ImageOps } from "./image.js";
|
|
3
3
|
import type { Box } from "./rec-preproc.js";
|
|
4
|
+
import type { MathAcceptHead, MathGateHead } from "./math-text.js";
|
|
5
|
+
import { MATH_MIN_CONF } from "./math-text.js";
|
|
6
|
+
import type { SpanImgTagger } from "./math-span-img.js";
|
|
4
7
|
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;
|
|
8
|
+
export { MATH_MIN_CONF };
|
|
11
9
|
/** The math models: line classifier, encoder, and the decoder's init and step graphs. */
|
|
12
10
|
export type MathSessions = {
|
|
13
11
|
cls: InferenceSession;
|
|
@@ -26,6 +24,17 @@ export type MathMeta = {
|
|
|
26
24
|
};
|
|
27
25
|
tokens: string[];
|
|
28
26
|
};
|
|
27
|
+
/** The optional parts of math: the learned accept head and read gate, and the inline formula tagger. */
|
|
28
|
+
export type MathHeads = {
|
|
29
|
+
accept?: MathAcceptHead;
|
|
30
|
+
gate?: MathGateHead;
|
|
31
|
+
spanImg?: SpanImgTagger;
|
|
32
|
+
};
|
|
33
|
+
/** The classifier's verdict per line crop: holds math, and its probability (for the read gate). */
|
|
34
|
+
export type MathFlags = {
|
|
35
|
+
flags: boolean[];
|
|
36
|
+
probs: number[];
|
|
37
|
+
};
|
|
29
38
|
/** A math reading: text with inline LaTeX, and the mean token probability. */
|
|
30
39
|
export type MathReading = {
|
|
31
40
|
text: string;
|
|
@@ -43,12 +52,42 @@ export declare class MathReader {
|
|
|
43
52
|
private readonly sessions;
|
|
44
53
|
private readonly meta;
|
|
45
54
|
private readonly ops;
|
|
55
|
+
/** The tagger of inline formulas in lines MathRec does not read whole (math_span_img.onnx). */
|
|
56
|
+
readonly spanImg: SpanImgTagger | undefined;
|
|
46
57
|
private readonly itos;
|
|
47
58
|
private readonly headDim;
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
59
|
+
/** The step graph takes one cache per layer (math_dec_step_kv.onnx). */
|
|
60
|
+
private readonly splitKv;
|
|
61
|
+
/** Single-character tokens: the letters MathRec can write. */
|
|
62
|
+
private readonly chars;
|
|
63
|
+
private readonly acceptHead;
|
|
64
|
+
private readonly gateHead;
|
|
65
|
+
constructor(Tensor: TensorCtor, sessions: MathSessions, meta: MathMeta, ops: ImageOps, heads?: MathHeads);
|
|
66
|
+
/** The math crops' line height (MathRec reads a taller crop than the recognizers). */
|
|
67
|
+
get height(): number;
|
|
68
|
+
/** Whether a learned read gate decides which flagged lines MathRec reads. */
|
|
69
|
+
get hasGate(): boolean;
|
|
70
|
+
/** Whether a learned accept head decides which readings replace a line (and knows table lines). */
|
|
71
|
+
get hasAcceptHead(): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* The line's text when MathRec's reading replaces the plain reading (the
|
|
74
|
+
* recognizer's or the text layer's, `draft`, read with confidence `rconf`),
|
|
75
|
+
* else null; `inTable`: the layout puts the line in a table.
|
|
76
|
+
*/
|
|
77
|
+
accept(text: string, conf: number, draft: string, rconf?: number, inTable?: number): string | null;
|
|
78
|
+
/** Which flagged lines (classifier probabilities, drafts) MathRec reads; `nCand`: lines the classifier saw. */
|
|
79
|
+
gate(probs: readonly number[], drafts: readonly string[], nCand: number, source: "ocr" | "text" | "hybrid"): boolean[];
|
|
80
|
+
/** Whether MathRec's vocabulary writes this line's letters (a MathRec with another script's letters may read it). */
|
|
81
|
+
writes(text: string): boolean;
|
|
82
|
+
/** Per line crop (the recognizer's crop): does it hold math, and the classifier's probability. */
|
|
83
|
+
flags(crops: readonly FloatImage[], batch?: number): Promise<MathFlags>;
|
|
51
84
|
/** Text with inline LaTeX and the mean token probability, for each box. */
|
|
52
85
|
read(gray: Gray, boxes: readonly Box[], batch?: number): Promise<MathReading[]>;
|
|
86
|
+
/** The caches at the first step, from the init graph's cross keys and values ([layers, B, heads, T, d]). */
|
|
87
|
+
private caches;
|
|
88
|
+
/** The caches of the decoder rows `rows` only. */
|
|
89
|
+
private take;
|
|
90
|
+
/** One decoder step: logits [B, V] and the caches with this token's keys and values appended. */
|
|
91
|
+
private step;
|
|
53
92
|
private decodeBatch;
|
|
54
93
|
}
|
package/indra/math.js
CHANGED
|
@@ -1 +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
|
|
1
|
+
export class MathReader{Tensor;sessions;meta;ops;spanImg;itos;headDim;splitKv;chars;acceptHead;gateHead;constructor(Tensor,sessions,meta,ops,heads={}){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;this.splitKv=sessions.step.inputNames.includes("self_k0");this.chars=mathChars(meta.tokens);this.acceptHead=heads.accept??null;this.gateHead=heads.gate??null;this.spanImg=heads.spanImg}get height(){return this.meta.config.height}get hasGate(){return this.gateHead!==null}get hasAcceptHead(){return this.acceptHead!==null}accept(text,conf,draft,rconf=1,inTable=0){return mathAccept(this.acceptHead,text,conf,draft,rconf,inTable)}gate(probs,drafts,nCand,source){return mathGate(this.gateHead,probs,drafts,nCand,source)}writes(text){return mathWrites(this.chars,text)}async flags(crops,batch=64){let flags=crops.map(()=>false);let probs=crops.map(()=>0);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()){probs[j]=p[k]??0;flags[j]=(p[k]??0)>MATH_MIN}}return{flags,probs}}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}caches(ck,cv,B){const{dec_layers:layers,dec_heads:heads}=this.meta.config;if(!this.splitKv){let empty=new this.Tensor("float32",new Float32Array(0),[layers,B,heads,0,this.headDim]);return{selfK:[empty],selfV:[empty],crossK:[ck],crossV:[cv]}}let empty=new this.Tensor("float32",new Float32Array(0),[B,heads,0,this.headDim]);let all=Array.from({length:layers},(_,i)=>i);let layer=(t,i)=>{const[,b=0,h=0,n=0,d=0]=t.dims;let size=b*h*n*d;return new this.Tensor("float32",floats(t).subarray(i*size,(i+1)*size),[b,h,n,d])};return{selfK:all.map(()=>empty),selfV:all.map(()=>empty),crossK:all.map((i)=>layer(ck,i)),crossV:all.map((i)=>layer(cv,i))}}take(c,rows){let axis=this.splitKv?0:1;let t=(xs)=>xs.map((x)=>takeRows(this.Tensor,x,rows,axis));return{selfK:t(c.selfK),selfV:t(c.selfV),crossK:t(c.crossK),crossV:t(c.crossV)}}async step(tok,t,c,mask){const{step}=this.sessions;let base={token:new this.Tensor("int64",tok,[tok.length]),pos:new this.Tensor("int64",BigInt64Array.of(BigInt(t)),[]),mask};if(!this.splitKv){let res=await step.run(declared(step,{...base,self_k:item(c.selfK,0),self_v:item(c.selfV,0),cross_k:item(c.crossK,0),cross_v:item(c.crossV,0)}));let next={...c,selfK:[output(res,"new_k")],selfV:[output(res,"new_v")]};return{logits:output(res,"logits"),c:next}}let caches=Object.fromEntries(c.selfK.flatMap((_,i)=>[[`self_k${i}`,item(c.selfK,i)],[`self_v${i}`,item(c.selfV,i)],[`cross_k${i}`,item(c.crossK,i)],[`cross_v${i}`,item(c.crossV,i)]]));let res=await step.run(declared(step,{...base,...caches}));let next={...c,selfK:c.selfK.map((_,i)=>output(res,`new_k${i}`)),selfV:c.selfV.map((_,i)=>output(res,`new_v${i}`))};return{logits:output(res,"logits"),c:next}}async decodeBatch(crops){const{enc,init}=this.sessions;const{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 mask=output(encoded,"mask");let cross=await init.run(declared(init,{memory:output(encoded,"memory"),mask}));let c=this.caches(output(cross,"cross_k"),output(cross,"cross_v"),B);let tok=new BigInt64Array(B).fill(BigInt(BOS));let seqs=Array.from({length:B},()=>[]);let probs=Array.from({length:B},()=>[]);let rows=Array.from({length:B},(_,i)=>i);let inMath=Array.from({length:B},()=>false);let textLike=Array.from({length:B},()=>false);for(let t=0;t<maxTokens-1;t++){let step=await this.step(tok,t,c,mask);c=step.c;let logits=step.logits;let ids=topTokens(floats(logits),rows.length,logits.dims[1]??0);tok=BigInt64Array.from(ids.map((p)=>BigInt(p.id)));let live=rows.map(()=>true);for(const[r,b]of rows.entries()){const{id,top}=item(ids,r);let pb=item(probs,b);pb.push(top);if(id===EOS){live[r]=false}else if(pb.length>=8&&meanF64(pb)<MATH_MIN_CONF-EARLY_STOP_MARGIN){live[r]=false}else if(id>=N_SPECIAL){item(seqs,b).push(id);let tk=item(this.itos,id);if(tk==="$"){inMath[b]=!inMath[b]}else if(!inMath[b]&&isCommand(tk)){textLike[b]=true;live[r]=false}}}if(!live.some(Boolean))break;if(!live.every(Boolean)){let keep=live.flatMap((l,r)=>l?[r]:[]);rows=keep.map((r)=>item(rows,r));tok=BigInt64Array.from(keep.map((r)=>tok[r]??0n));mask=takeRows(this.Tensor,mask,keep,0);c=this.take(c,keep)}}return seqs.map((seq,b)=>{if(item(textLike,b))return{text:"",conf:0};let pb=item(probs,b);return{text:detokenize(seq.map((i)=>item(this.itos,i))),conf:pb.length?meanF64(pb):0}})}}import{declared,isCommand,takeRows,topTokens}from"./math-decoder.js";import{meanF64}from"./numeric.js";import{cropLine,padBatch,widthBatches}from"./rec-preproc.js";import{MATH_MIN_CONF,mathAccept,mathChars,mathGate,mathWrites}from"./math-text.js";import{floats,item,output}from"./util.js";let MATH_MIN=0.5;export{MATH_MIN_CONF};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(" ")}
|
package/indra/numeric.d.ts
CHANGED
|
@@ -7,3 +7,11 @@
|
|
|
7
7
|
export declare function sumF32(a: ArrayLike<number>, start?: number, end?: number): number;
|
|
8
8
|
/** numpy's float32 mean: the pairwise sum divided in float32. */
|
|
9
9
|
export declare function meanF32(a: ArrayLike<number>): number;
|
|
10
|
+
/**
|
|
11
|
+
* Sum of float64 values the way numpy sums a contiguous float64 array
|
|
12
|
+
* (pairwise, blocks of up to 128 with 8 lanes): `np.mean` of a list of Python
|
|
13
|
+
* floats rounds the same way only with this order.
|
|
14
|
+
*/
|
|
15
|
+
export declare function sumF64(a: ArrayLike<number>, start?: number, end?: number): number;
|
|
16
|
+
/** `np.mean` of float64 values. */
|
|
17
|
+
export declare function meanF64(a: ArrayLike<number>): number;
|
package/indra/numeric.js
CHANGED
|
@@ -1 +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)}
|
|
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)}export function sumF64(a,start=0,end=a.length){let n=end-start;if(n<8){let r=0;for(let i=start;i<end;i++)r+=a[i]??0;return r}if(n<=128){let r=[0,1,2,3,4,5,6,7].map((k)=>a[start+k]??0);let stop=start+n-n%8;let i=start+8;for(;i<stop;i+=8)for(let k=0;k<8;k++)r[k]=(r[k]??0)+(a[i+k]??0);const[r0=0,r1=0,r2=0,r3=0,r4=0,r5=0,r6=0,r7=0]=r;let res=r0+r1+(r2+r3)+(r4+r5+(r6+r7));for(;i<end;i++)res+=a[i]??0;return res}let n2=Math.floor(n/2);n2-=n2%8;return sumF64(a,start,start+n2)+sumF64(a,start+n2,end)}export function meanF64(a){return sumF64(a)/a.length}
|
package/indra/order-post.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{pyRound}from"./det-post.js";import{sumF32}from"./numeric.js";import{displayLen}from"./unicode.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"];export let GRID_CLASSES=new Set([5,8,9]);let BULLETS=String.fromCharCode(8226,45,8211,9642,9702,42,183,8594);let
|
|
1
|
+
import{pyRound}from"./det-post.js";import{sumF32}from"./numeric.js";import{isDigit}from"./py-unicode.js";import{displayLen}from"./unicode.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"];export let GRID_CLASSES=new Set([5,8,9]);let BULLETS=String.fromCharCode(8226,45,8211,9642,9702,42,183,8594);let UPPER=/^\p{Uppercase}$/u;let SENTENCE_END=`.!?:;${String.fromCharCode(12290,65281,65311,65306,65307,65294)}`;let isDigits=(s)=>s.length>0&&[...s].every(isDigit);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(displayLen(t))/5;row[11]=cps.filter(isDigit).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]=SENTENCE_END.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))}export function xycutBlocks(boxes,minGap=1){if(!boxes.length)return[];let h=medianF32(boxes.map(([,y0,,y1])=>f(y1-y0)));let rec=(ids)=>{let b=ids.map((i)=>item(boxes,i));if(ids.length>1){let y=bestCut(b,1);let x=bestCut(b,0);const{gap,k,order}=y.gap>=x.gap?y:x;if(k>=0&&gap>=minGap*h){return[...rec(order.slice(0,k).map((i)=>item(ids,i))),...rec(order.slice(k).map((i)=>item(ids,i)))]}}return[orderXYCut(b).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_CLASSES.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,22 @@
|
|
|
1
|
+
import type { Gray } from "./image.js";
|
|
2
|
+
import type { MathReader } from "./math.js";
|
|
3
|
+
import type { TableModels } from "./page-tables.js";
|
|
4
|
+
import type { Box } from "./rec-preproc.js";
|
|
5
|
+
import type { Page, ReadingOrder, RecLine } from "./types.js";
|
|
6
|
+
import type { Vocab } from "./vocab.js";
|
|
7
|
+
/** What laying out a page needs from the pipeline. */
|
|
8
|
+
export type LayoutDeps = {
|
|
9
|
+
vocab: Vocab;
|
|
10
|
+
furniture: boolean;
|
|
11
|
+
math: MathReader | undefined;
|
|
12
|
+
tables: TableModels;
|
|
13
|
+
readingOrder(boxes: readonly Box[], texts: readonly string[], width: number, height: number, gray?: Gray, imgBoxes?: readonly Box[]): Promise<ReadingOrder>;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Lines -> split at wide gaps -> tidy -> reading order -> blocks and
|
|
17
|
+
* markdown. `rec` holds the text, confidence and tokens of each box on `gray`.
|
|
18
|
+
* A right-to-left page orders and lays out its lines mirrored, so the right
|
|
19
|
+
* column comes first. `vertical`: a vertical page read turned, ordered by
|
|
20
|
+
* XY-cut.
|
|
21
|
+
*/
|
|
22
|
+
export declare function layoutPage(deps: LayoutDeps, gray: Gray, boxes: readonly Box[], rec: readonly RecLine[], t: Record<string, number>, vertical: boolean, fromLayer: boolean): Promise<Page>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{buildPage,mirrorBox,pageIsRtl,splitParts,verticalOrder}from"./assemble.js";import{decodeToks}from"./lines.js";import{isFormula,unspliced}from"./math-span-img.js";import{pageTables}from"./page-tables.js";import{BLOCK_CLASSES}from"./order-post.js";let TABLE=BLOCK_CLASSES.indexOf("Table");function orderTexts(vocab,parts,pageRtl){return parts.map((p)=>p.toks.some(isFormula)?decodeToks(vocab,unspliced(p.toks),pageRtl):p.text)}function inTable(cls,i){let c=BLOCK_CLASSES.length;let best=0;for(let k=1;k<c;k++)if((cls[i*c+k]??0)>(cls[i*c+best]??0))best=k;return best===TABLE}export async function layoutPage(deps,gray,boxes,rec,t,vertical,fromLayer){let t0=performance.now();const{width,height}=gray;let pageRtl=pageIsRtl(rec);let parts=splitParts(deps.vocab,boxes,rec,pageRtl);let order=async(ps)=>deps.readingOrder(ps.map((p)=>pageRtl?mirrorBox(p.box,width):p.box),orderTexts(deps.vocab,ps,pageRtl),width,height,gray,ps.map((p)=>p.box));let ro=await order(parts);let math=deps.math;const{cls}=ro;if(math?.hasAcceptHead&&cls&&parts.some((p)=>p.math)){let back=false;parts=parts.map((p,i)=>{let q=p.math;if(!q||!inTable(cls,i))return p;if(math.accept(q.reading,q.conf,q.draft,q.rconf,1)!==null)return p;back=true;return{box:p.box,text:q.plain.text,toks:q.plain.toks,conf:q.plain.conf}});if(back)ro=await order(parts)}if(vertical){ro=verticalOrder(parts.map((p)=>p.box),ro)}t["order_ms"]=performance.now()-t0;let tab=vertical?{ro,ms:0}:await pageTables(deps.tables,deps.vocab,gray,parts,ro,pageRtl,fromLayer);let page=buildPage(deps.vocab,parts,tab.ro,vertical?"order=xycut":"order=model",deps.furniture,t,pageRtl,width,tab.tables);if(tab.tables)page.timings["table_ms"]=tab.ms;return page}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Part } from "./assemble.js";
|
|
2
|
+
import type { Gray } from "./image.js";
|
|
3
|
+
import type { TableMap } from "./layout-post.js";
|
|
4
|
+
import type { TableReader } from "./table-rel.js";
|
|
5
|
+
import type { VerifierSet } from "./table-verify.js";
|
|
6
|
+
import type { Lazy, ReadingOrder } from "./types.js";
|
|
7
|
+
import type { Vocab } from "./vocab.js";
|
|
8
|
+
/**
|
|
9
|
+
* The table models of a model set: tsr_rel.onnx (with tsr_split and
|
|
10
|
+
* tsr_refine) reads the cells of each Table block, and table_verify.json
|
|
11
|
+
* relabels Table blocks it calls false tables (charts, prose). `layerTables`
|
|
12
|
+
* false leaves PDF text-layer tables to the geometric assembly
|
|
13
|
+
* (meta.json "tsr_rel_layer").
|
|
14
|
+
*/
|
|
15
|
+
export type TableModels = {
|
|
16
|
+
reader?: Lazy<TableReader>;
|
|
17
|
+
verifiers?: VerifierSet;
|
|
18
|
+
layerTables: boolean;
|
|
19
|
+
};
|
|
20
|
+
/** The reading order with the verifier's classes, and the HTML read per table block. */
|
|
21
|
+
export type PageTables = {
|
|
22
|
+
ro: ReadingOrder;
|
|
23
|
+
tables?: TableMap;
|
|
24
|
+
ms: number;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Tables of a laid-out page. Lines with a spliced formula are read as the
|
|
28
|
+
* recognizer read them: the formula is not a table feature. Text-layer pages
|
|
29
|
+
* (`fromLayer`) get the verifier's own weight set, and no check when the
|
|
30
|
+
* file has none (the OCR set rejected real tables there).
|
|
31
|
+
*/
|
|
32
|
+
export declare function pageTables(models: TableModels, vocab: Vocab, gray: Gray, parts: readonly Part[], ro: ReadingOrder, pageRtl: boolean, fromLayer: boolean): Promise<PageTables>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{mirrorBox,partCells}from"./assemble.js";import{TABLE,blockKey,splitBlocks}from"./layout-post.js";import{decodeToks,isSpace}from"./lines.js";import{isFormula,unspliced}from"./math-span-img.js";import{blockClass}from"./order-post.js";export async function pageTables(models,vocab,gray,parts,ro,pageRtl,fromLayer){const{cls,same,order}=ro;if(!cls||!same)return{ro,ms:0};let t0=performance.now();let n=parts.length;let tables;if(models.reader&&!(fromLayer&&!models.layerTables)){let reader=await models.reader();let text={isSpace:(id)=>isSpace(vocab,id),decode:(toks)=>decodeToks(vocab,toks,pageRtl)};let read=new Map;for(let blk of splitBlocks(order,same,n)){if(blk.length<2||blockClass(cls,blk)!==TABLE)continue;let lines=blk.map((i)=>{let p=parts[i];if(!p)throw new Error(`no line ${i}`);return{box:p.box,toks:unspliced(p.toks)}});let html=await reader.read(gray,lines,text,pageRtl);if(html)read.set(blockKey(blk),html)}tables=read}let ms=performance.now()-t0;let verifier=fromLayer?models.verifiers?.layer:models.verifiers?.ocr;if(!verifier)return{ro,tables,ms};let spliced=parts.map((p)=>p.toks.some(isFormula));let res=verifier.apply({boxes:parts.map((p)=>pageRtl?mirrorBox(p.box,gray.width):p.box),texts:parts.map((p,i)=>spliced[i]?decodeToks(vocab,unspliced(p.toks),pageRtl):p.text),order,cls,same,cells:partCells(vocab,parts,pageRtl,gray.width,(p)=>unspliced(p.toks)),tables,gray});return res.relabelled?{ro:{...ro,cls:res.cls},tables:res.tables,ms}:{ro,tables,ms}}
|
package/indra/pipeline.d.ts
CHANGED
|
@@ -2,9 +2,10 @@ 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 {
|
|
6
|
-
import type { DetectPass, IndraMeta, IndraSessions, Orientation, Page, PipelineOptions, ReadingOrder, RecLine, Straightened, TensorCtor } from "./types.js";
|
|
5
|
+
import type { LayerRead } from "./layer-gaps.js";
|
|
6
|
+
import type { DetectPass, IndraMeta, IndraSessions, Orientation, Page, PipelineOptions, ReadingOrder, RecLine, Straightened, TensorCtor, Tok } from "./types.js";
|
|
7
7
|
import type { Vocab } from "./vocab.js";
|
|
8
|
+
export declare const ADAPTIVE_MIN_H = 9;
|
|
8
9
|
/**
|
|
9
10
|
* The OCR pipeline on one grayscale page. Each stage is its own method, so
|
|
10
11
|
* callers can run the whole page or chain stages themselves.
|
|
@@ -20,6 +21,8 @@ export declare class IndraPipeline {
|
|
|
20
21
|
private readonly adaptive;
|
|
21
22
|
private readonly math;
|
|
22
23
|
private readonly recognizers;
|
|
24
|
+
private readonly thumbs;
|
|
25
|
+
private readonly tables;
|
|
23
26
|
constructor(Tensor: TensorCtor, sessions: IndraSessions, meta: IndraMeta, ops: ImageOps, options?: PipelineOptions);
|
|
24
27
|
/** Every recognizer's vocabulary: the main one first, then each script group's. */
|
|
25
28
|
get vocabs(): Vocab[];
|
|
@@ -33,6 +36,14 @@ export declare class IndraPipeline {
|
|
|
33
36
|
* when no class is more likely than ORIENT_MIN.
|
|
34
37
|
*/
|
|
35
38
|
orient(gray: Gray): Promise<Orientation>;
|
|
39
|
+
/**
|
|
40
|
+
* The quarter turns that bring a page upright. orient.onnx reads the page
|
|
41
|
+
* straightened by its row angle (a tilted page could read as turned). Below
|
|
42
|
+
* ORIENT_MIN, a page it sees as likely sideways is settled by reading lines
|
|
43
|
+
* each way (readTurn); a half turn is checked the same way before it is
|
|
44
|
+
* made, since orient.onnx can turn an upright book scan half round.
|
|
45
|
+
*/
|
|
46
|
+
pageTurns(gray: Gray, skew: number, small: Gray): Promise<number>;
|
|
36
47
|
/**
|
|
37
48
|
* The page turned upright by `turns` quarter turns (VERTICAL: a quarter
|
|
38
49
|
* turn counter-clockwise, columns become lines), then straightened when its
|
|
@@ -57,8 +68,11 @@ export declare class IndraPipeline {
|
|
|
57
68
|
* back empty.
|
|
58
69
|
*/
|
|
59
70
|
recognize(gray: Gray, boxes: readonly Box[], batch?: number, vertical?: boolean): Promise<RecLine[]>;
|
|
60
|
-
/**
|
|
61
|
-
|
|
71
|
+
/**
|
|
72
|
+
* Per line box and its text-layer tokens: how much less likely the line's
|
|
73
|
+
* recognizer finds the layer's text than its own reading (layer-gaps.ts).
|
|
74
|
+
*/
|
|
75
|
+
layerGaps(gray: Gray, boxes: readonly Box[], tokens: readonly (readonly Tok[])[]): Promise<LayerRead[]>;
|
|
62
76
|
/**
|
|
63
77
|
* OCR of one page image: measure the tilt and the turn on a preview (unless
|
|
64
78
|
* `turn` is false), turn upright and deskew, detect, recognize, order and
|
|
@@ -67,15 +81,15 @@ export declare class IndraPipeline {
|
|
|
67
81
|
page(gray: Gray, turn?: boolean): Promise<Page>;
|
|
68
82
|
/**
|
|
69
83
|
* Lines -> split at wide gaps -> tidy -> reading order -> blocks and
|
|
70
|
-
* markdown. `rec` holds the text, confidence and tokens of
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
84
|
+
* markdown (page-layout.ts). `rec` holds the text, confidence and tokens of
|
|
85
|
+
* each box on `gray`. `vertical`: a vertical page read turned, ordered by
|
|
86
|
+
* XY-cut. `fromLayer`: the lines come from a PDF text layer (tables and the
|
|
87
|
+
* false-table check treat those apart).
|
|
74
88
|
*/
|
|
75
|
-
assemble(
|
|
89
|
+
assemble(gray: Gray, boxes: readonly Box[], rec: readonly RecLine[], t?: Record<string, number>, vertical?: boolean, fromLayer?: boolean): Promise<Page>;
|
|
76
90
|
/**
|
|
77
91
|
* Reading order of the lines. With order.onnx's layout heads: blocks first,
|
|
78
92
|
* then lines inside blocks, plus the class and same-block logits.
|
|
79
93
|
*/
|
|
80
|
-
readingOrder(boxes: readonly Box[], texts: readonly string[], width: number, height: number): Promise<ReadingOrder>;
|
|
94
|
+
readingOrder(boxes: readonly Box[], texts: readonly string[], width: number, height: number, gray?: Gray, imgBoxes?: readonly Box[]): Promise<ReadingOrder>;
|
|
81
95
|
}
|
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(
|
|
1
|
+
export class IndraPipeline{Tensor;sessions;ops;vocab;longSide;height;furniture;adaptive;math;recognizers;thumbs;tables;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;this.thumbs=sessions.order&&thumbSpec(sessions.order,meta.order_thumbs_interp);let tsr=sessions.tables;this.tables={...tsr?{reader:once(async()=>new TableReader(Tensor,await tsr(),ops,colSpans(meta.tsr_rel_span)))}:{},...sessions.tableVerify?{verifiers:TableVerifier.load(sessions.tableVerify)}:{},layerTables:meta.tsr_rel_layer??true}}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}}async pageTurns(gray,skew,small){const{probs}=await this.orient(Math.abs(skew)>=DESKEW_MIN?rotatePage(small,skew,this.ops):small);if(!probs.length)return 0;let k=0;for(const[i,p]of probs.entries())if(p>(probs[k]??0))k=i;if((probs[k]??0)<=ORIENT_MIN){let sideways=(probs[1]??0)+(probs[3]??0)+(probs[VERTICAL]??0);return sideways>=SIDEWAYS_MASS?readTurn(this,gray,skew,small,probs):0}return k===2?readHalfTurn(this,gray,skew,small):k}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;let data=floats(out);return{boxes:decode(data,h,w),scale,logit:{data:data.subarray(0,h*w),width:w,height:h}}}async detect(gray){let pass=await this.detectAt(gray,this.longSide);if(this.adaptive&&pass.boxes.length>=8){let medH=medianF32(pass.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)pass=await this.detectAt(gray,ls)}}const{boxes,scale}=pass;if(Math.max(gray.width,gray.height)>TILE_MIN_SIDE&&boxes.length>=8&&medianF32(boxes.map((b)=>Math.fround(b[3]-b[1])))<ADAPTIVE_MIN_H){return detectTiled(gray,pass,(crop,ls)=>this.detectAt(crop,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 layerGaps(gray,boxes,tokens){return layerGaps(this.Tensor,this.recognizers,this.ops,gray,boxes,tokens)}async page(gray,turn=true){let t0=performance.now();let small=preview(gray,this.ops);let a=estimateSkew(small,this.ops);let turns=turn?await this.pageTurns(gray,a,small):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,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(gray,boxes,rec,t={},vertical=false,fromLayer=false){return layoutPage({vocab:this.vocab,furniture:this.furniture,math:this.math,tables:this.tables,readingOrder:(b,x,w,h,g,ib)=>this.readingOrder(b,x,w,h,g,ib)},gray,boxes,rec,t,vertical,fromLayer)}async readingOrder(boxes,texts,width,height,gray,imgBoxes){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 base={feats:new this.Tensor("float32",feats,[1,n,N_FEATS]),mask:new this.Tensor("bool",new Uint8Array(n).fill(1),[1,n])};let spec=this.thumbs;let res=await order.run(spec?{...base,...thumbFeed(this.Tensor,this.ops,spec,n,gray,imgBoxes??boxes)}:base);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{thumbFeed,thumbSpec}from"./line-thumbs.js";import{N_FEATS,decodeBlocksOrder,decodeOrder,lineFeatures,medianF32,orderXYCut}from"./order-post.js";import{layerGaps}from"./layer-gaps.js";import{Recognizers,once}from"./recognizers.js";import{layoutPage}from"./page-layout.js";import{colSpans}from"./table-decode.js";import{TableReader}from"./table-rel.js";import{TableVerifier}from"./table-verify.js";import{TILE_MIN_SIDE,detectTiled}from"./tiles.js";import{SIDEWAYS_MASS,readHalfTurn,readTurn}from"./turn-check.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";export 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,14 @@
|
|
|
1
|
+
/** One letter: str.isalpha for one character. */
|
|
2
|
+
export declare const LETTER: RegExp;
|
|
3
|
+
/** One uppercase character: str.isupper for one character. */
|
|
4
|
+
export declare const UPPER: RegExp;
|
|
5
|
+
/** One lowercase character: str.islower for one character. */
|
|
6
|
+
export declare const LOWER: RegExp;
|
|
7
|
+
/** Python's \s in a str pattern (the str.isspace characters), as the inside of a character class. */
|
|
8
|
+
export declare const PY_SPACE: string;
|
|
9
|
+
/** The character with these code points (source files stay ASCII). */
|
|
10
|
+
export declare const chars: (...cps: number[]) => string;
|
|
11
|
+
/** Python's html.escape(s, quote=False). */
|
|
12
|
+
export declare function pyHtmlEscape(s: string): string;
|
|
13
|
+
/** Python's html.unescape for text made by `pyHtmlEscape`; see the ceiling in the file header. */
|
|
14
|
+
export declare function pyHtmlUnescape(s: string): string;
|
package/indra/py-text.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{item}from"./util.js";export let LETTER=/^\p{L}$/u;export let UPPER=/^\p{Uppercase}$/u;export let LOWER=/^\p{Lowercase}$/u;export let PY_SPACE="\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";export let chars=(...cps)=>String.fromCodePoint(...cps);export function pyHtmlEscape(s){return s.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}let C1=[8364,129,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,141,381,143,144,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,157,382,376];let NAMED=new Map([["amp","&"],["amp;","&"],["lt","<"],["lt;","<"],["gt",">"],["gt;",">"],["quot",'"'],["quot;",'"'],["apos;","'"],["nbsp",chars(160)],["nbsp;",chars(160)]]);let CHARREF=/&(#[0-9]+;?|#[xX][0-9a-fA-F]+;?|[^\t\n\f <&#;]{1,32};?)/g;function numericRef(num){if(num===0)return chars(65533);if(num===13)return"\r";if(num>=128&&num<=159)return chars(item(C1,num-128));if(num>=55296&&num<=57343||num>1114111)return chars(65533);let dropped=num>=1&&num<=8||num===11||num>=14&&num<=31||num===127||num>=64976&&num<=65007||num>=65534&&(num&65534)===65534;return dropped?"":chars(num)}export function pyHtmlUnescape(s){if(!s.includes("&"))return s;return s.replace(CHARREF,(_,body)=>{if(body.startsWith("#")){let hex=body[1]==="x"||body[1]==="X";return numericRef(Number.parseInt(body.slice(hex?2:1).replace(/;$/,""),hex?16:10))}let exact=NAMED.get(body);if(exact!==undefined)return exact;for(let x=body.length-1;x>1;x--){let prefix=NAMED.get(body.slice(0,x));if(prefix!==undefined)return prefix+body.slice(x)}return`&${body}`})}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** str.isalpha for one code point: categories Lm, Lt, Lu, Ll, Lo. */
|
|
2
|
+
export declare const isAlpha: (c: string) => boolean;
|
|
3
|
+
/** str.isupper for one code point. */
|
|
4
|
+
export declare const isUpper: (c: string) => boolean;
|
|
5
|
+
/** str.isdigit for one code point. */
|
|
6
|
+
export declare const isDigit: (c: string) => boolean;
|
|
7
|
+
/** unicodedata.category(c).startswith("M"): a combining mark of any kind. */
|
|
8
|
+
export declare const isCategoryM: (c: string) => boolean;
|
|
9
|
+
/** unicodedata.combining(c) != 0: a nonzero canonical combining class. */
|
|
10
|
+
export declare const isCombining: (c: string) => boolean;
|
|
11
|
+
/** unicodedata.name(c, "").startswith("LATIN"). */
|
|
12
|
+
export declare const hasLatinName: (c: string) => boolean;
|
|
13
|
+
/**
|
|
14
|
+
* unicodedata.lookup("GREEK SMALL LETTER " + name.upper()), or undefined where
|
|
15
|
+
* Python raises KeyError. Only the one-word names resolve ("lambda" does not:
|
|
16
|
+
* the Unicode name is LAMDA).
|
|
17
|
+
*/
|
|
18
|
+
export declare function greekSmallLetter(name: string): string | undefined;
|
|
19
|
+
/** Python's len(s): code points, not UTF-16 units. */
|
|
20
|
+
export declare const pyLen: (s: string) => number;
|
|
21
|
+
/** str.split() with no argument: runs of Python whitespace separate the words. */
|
|
22
|
+
export declare function pySplit(s: string): string[];
|
|
23
|
+
/** str.lstrip() with no argument. */
|
|
24
|
+
export declare function pyLstrip(s: string): string;
|
|
25
|
+
/** str.rstrip() with no argument. */
|
|
26
|
+
export declare function pyRstrip(s: string): string;
|
|
27
|
+
/** str.strip() with no argument. */
|
|
28
|
+
export declare const pyStrip: (s: string) => string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isPySpace}from"./util.js";let ALPHA=/^\p{L}$/u;let UPPER=/^\p{Uppercase}$/u;let CATEGORY_M=/^\p{M}$/u;let COMBINING=1;let LATIN_NAME=2;let DIGIT=4;let FLAG_TABLE="1c 9 4 7 p 2 6 p 2 1j 1 4 5 0 4 6 m 2 1 u 2 1 c7 2 28 26 1 1 v 1 7n 4 1 7d 18 1 1 0 1 1 "+"1 1 1 1 1 1 0 1 20 a 1 1c k 1 0 9 4 6 0 1 2t 6 1 2 5 1 2 1 1 1 3 1 2 9 4 n 0 1 u q 1 39 "+"9 4 x 8 1 9 0 1 o 3 1 1 8 1 1 2 1 1 4 1 17 2 1 1o 7 1 16 n 1 1 s 1 1o 0 1 g 0 1 3 3 1 h "+"9 4 24 0 1 g 0 1 o 9 4 e 0 1 1p 0 1 g 0 1 o 9 4 24 0 1 g 0 1 o 9 4 24 0 1 g 0 1 o 9 4 2l"+" 0 1 o 9 4 24 0 1 g 0 1 7 1 1 f 9 4 24 0 1 g 0 1 o 9 4 23 1 1 g 0 1 o 9 4 2i 0 1 r 9 4 2"+"0 2 1 d 3 1 4 9 4 2m 2 1 d 3 1 4 9 4 1q 1 1 6 9 4 b 0 1 1 0 1 1 0 1 1j 1 1 1 0 1 5 3 1 2"+" 0 1 1 2 1 1 1 1 1q 0 1 34 0 1 1 1 1 5 9 4 1v 0 1 2 9 4 jn 2 1 9 8 4 pu 1 1 u 0 1 4d 0 1"+" a 0 1 2 9 4 12 9 4 3z 0 1 3z 2 1 a 9 4 3k a 4 1o 1 1 1z 0 1 k 7 1 2 0 1 0 9 4 6 9 4 m d"+" 1 1 f 1 2t 0 1 f 0 1 b 9 4 h 8 1 1i 1 1 4 9 4 18 0 1 b 1 1 1v 0 1 8 9 4 6 9 4 3a 2 1 1 "+"c 1 1 6 1 4 0 1 6 0 1 3 1 1 6 11 2 1o 3 2 5 c 2 1 x 2 11 1r 1 0 73 2 a8 0 4 3 5 4 6 9 4 "+"6 c 2 1f c 1 4 0 1 3 b 1 43 0 2 kb 8 4 b 8 4 b 8 4 2h 0 4 a 8 4 1 0 4 f1 0 2 2g 8 4 1 8 "+"4 1 8 4 y5 s 2 1 1 2 33 2 1 3x 0 1 2o v 1 fe 5 1 2x 1 1 n7p 9 4 1x 0 1 4 9 1 w 1 1 28 1 "+"1 1c 25 2 1 m 2 3 1r 2 5 1 2 1 0 2 1 4 2 r 2 2 2 5 2 6 0 1 11 0 1 47 0 1 b 9 4 6 h 1 e 9"+" 4 x 2 1 11 0 1 2n 0 1 c 0 1 f 9 4 m 9 4 2e 9 4 2e 0 1 1 2 1 2 1 1 5 1 1 1 0 1 1g 0 1 1l"+" 16 2 5 4 2 1 2 2 3o 0 1 2 9 4 fly 6 2 n 0 1 ld f 1 68 9 4 kj 0 1 6a 0 1 45 4 1 85 9 4 1"+"2b 0 1 1 0 1 14 2 1 4 0 1 0 3 4 4h 1 1 fx 3 1 8 9 4 86 8 4 1u 1 1 28 2 1 1y a 1 1d 3 1 5"+"c 0 1 b 8 4 b 9 4 0 0 1 e 0 1 1l 1 1 1h 9 4 6 2 1 1c 1 1 1 9 4 1f 0 1 24 0 1 9 0 1 5 9 4"+" 2j 1 1 4y 1 1 5 9 4 1t 1 1 g 0 1 o 6 1 3 4 1 5p 0 1 3 0 1 9 9 4 4 0 1 2r 1 1 c 9 4 6d 1"+" 1 3i 0 1 g 9 4 2k 1 1 8 9 4 2p 0 1 4 9 4 73 1 1 4l 9 4 2b 1 1 4 0 1 c 9 4 3q 0 1 2b 0 1"+" i 0 1 29 0 1 bp 0 1 g 9 4 6g 0 1 1 1 1 a 9 4 1p 0 1 8 9 4 bb 1 1 d 9 4 eti 9 4 2e 9 4 1"+"2 4 1 1n 6 1 p 9 4 wm 1 1 f58 0 1 43q 4 1 3 5 1 8 7 1 2 6 1 u 3 1 44 2 1 13d 1d 4 1ds u "+"2 6 5 2 5x 6 1 1 g 1 2 6 1 1 1 1 1 4 1 2s 0 1 4g 6 1 9 9 4 9w 0 1 1p 3 1 0 9 4 du 3 1 0 "+"9 4 ra 6 1 31 6 1 5 9 4 1ie a 4 25h 9 4";let GREEK_TABLE="heta:371 alpha:3b1 beta:3b2 gamma:3b3 delta:3b4 epsilon:3b5 zeta:3b6 eta:3b7 theta:3b8 iota:3b9 kappa:3ba lamda:3bb mu:3bc nu:3bd xi:3be omicron:3bf pi:3c0 rho:3c1 sigma:3c3 tau:3c4 upsilon:3c5 phi:3c6 chi:3c7 psi:3c8 omega:3c9 stigma:3db digamma:3dd koppa:3df sampi:3e1 sho:3f8 san:3fb";function decodeFlags(table){let t=table.split(" ").map((s)=>Number.parseInt(s,36));let n=t.length/3;let starts=new Uint32Array(n);let ends=new Uint32Array(n);let flags=new Uint8Array(n);let end=-1;for(let i=0;i<n;i++){let start=end+1+(t[3*i]??0);end=start+(t[3*i+1]??0);starts[i]=start;ends[i]=end;flags[i]=t[3*i+2]??0}return{starts,ends,flags}}let ranges;function flagsOf(c){ranges??=decodeFlags(FLAG_TABLE);let cp=c.codePointAt(0)??0;let lo=0;let hi=ranges.starts.length-1;while(lo<=hi){let mid=lo+hi>>1;if(cp<(ranges.starts[mid]??0))hi=mid-1;else if(cp>(ranges.ends[mid]??0))lo=mid+1;else return ranges.flags[mid]??0}return 0}let greek;export let isAlpha=(c)=>ALPHA.test(c);export let isUpper=(c)=>UPPER.test(c);export let isDigit=(c)=>(flagsOf(c)&DIGIT)!==0;export let isCategoryM=(c)=>CATEGORY_M.test(c);export let isCombining=(c)=>(flagsOf(c)&COMBINING)!==0;export let hasLatinName=(c)=>(flagsOf(c)&LATIN_NAME)!==0;export function greekSmallLetter(name){greek??=new Map(GREEK_TABLE.split(" ").map((p)=>{const[word="",hex="0"]=p.split(":");return[word,String.fromCodePoint(Number.parseInt(hex,16))]}));return greek.get(name)}export let pyLen=(s)=>Array.from(s).length;export function pySplit(s){let words=[];let word="";for(let c of s){if(isPySpace(c)){if(word)words.push(word);word=""}else{word+=c}}if(word)words.push(word);return words}export function pyLstrip(s){let i=0;while(i<s.length&&isPySpace(s.charAt(i)))i++;return s.slice(i)}export function pyRstrip(s){let n=s.length;while(n>0&&isPySpace(s.charAt(n-1)))n--;return s.slice(0,n)}export let pyStrip=(s)=>pyLstrip(pyRstrip(s));
|
package/indra/rec-preproc.d.ts
CHANGED
|
@@ -28,8 +28,15 @@ export type PaddedBatch = {
|
|
|
28
28
|
dims: [number, number, number, number];
|
|
29
29
|
widths: BigInt64Array;
|
|
30
30
|
};
|
|
31
|
-
/** Right-pad ink maps to one width (a multiple of 8). */
|
|
31
|
+
/** Right-pad ink maps to one width (a multiple of 8, at least MIN_BATCH_WIDTH). */
|
|
32
32
|
export declare function padBatch(lines: readonly FloatImage[]): PaddedBatch;
|
|
33
|
+
/**
|
|
34
|
+
* Line ink maps resized to `xscale` times their width (same height), for a
|
|
35
|
+
* recognizer that reads widened lines (meta.json `rec_xscale_<group>`):
|
|
36
|
+
* Nastaliq stacks several letters in the width of one, and widened lines give
|
|
37
|
+
* the recognizer a timestep for each.
|
|
38
|
+
*/
|
|
39
|
+
export declare function widen(lines: readonly FloatImage[], xscale: number, ops: ImageOps): FloatImage[];
|
|
33
40
|
/**
|
|
34
41
|
* Group line indices into batches of similar width, narrowest first. A batch
|
|
35
42
|
* closes at `maxBatch` lines, when the next line is wider than `maxRatio`
|