ppu-indra-ocr 0.1.2 → 0.2.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 +15 -7
- package/README.md +105 -68
- package/cli/commands.js +2 -2
- package/cli/help.d.ts +1 -1
- package/cli/help.js +3 -2
- package/cli/options.d.ts +3 -0
- package/cli/options.js +1 -1
- package/core/indra-ocr.service.d.ts +19 -7
- package/core/indra-ocr.service.js +1 -1
- package/core/opencv-image-ops.js +1 -1
- package/core/platform.d.ts +2 -0
- package/exports.d.ts +2 -2
- package/exports.js +1 -1
- package/indra/assemble.d.ts +38 -13
- package/indra/assemble.js +2 -2
- package/indra/document.d.ts +4 -3
- package/indra/document.js +1 -1
- package/indra/image.d.ts +2 -2
- package/indra/lines.d.ts +8 -3
- package/indra/lines.js +1 -1
- package/indra/lm.d.ts +51 -0
- package/indra/lm.js +1 -0
- package/indra/npz.d.ts +14 -0
- package/indra/npz.js +1 -0
- package/indra/order-post.d.ts +9 -0
- package/indra/order-post.js +1 -1
- package/indra/pipeline.d.ts +30 -17
- package/indra/pipeline.js +1 -1
- package/indra/rec-preproc.d.ts +14 -2
- package/indra/rec-preproc.js +1 -1
- package/indra/recognize.d.ts +44 -6
- package/indra/recognize.js +1 -1
- package/indra/recognizers.d.ts +45 -0
- package/indra/recognizers.js +1 -0
- package/indra/rtl.d.ts +34 -0
- package/indra/rtl.js +1 -0
- package/indra/text-runs.d.ts +35 -0
- package/indra/text-runs.js +2 -0
- package/indra/textlayer.d.ts +43 -16
- package/indra/textlayer.js +1 -2
- package/indra/ts-image-ops.js +1 -1
- package/indra/types.d.ts +39 -7
- package/indra/unicode-data.d.ts +4 -0
- package/indra/unicode-data.js +1 -0
- package/indra/unicode.d.ts +24 -0
- package/indra/unicode.js +1 -0
- package/indra/upright.d.ts +13 -2
- package/indra/upright.js +1 -1
- package/indra/vocab.d.ts +3 -1
- package/indra/vocab.js +1 -1
- package/interface.d.ts +13 -2
- package/mobile/platform.mobile.d.ts +1 -0
- package/mobile/platform.mobile.js +1 -1
- package/model-catalogue.d.ts +76 -20
- package/model-catalogue.js +1 -1
- package/package.json +1 -1
- package/pdf/index.js +1 -1
- package/pdf/pdfium.d.ts +2 -0
- package/pdf/pdfium.js +1 -1
- package/processor/indra-ocr.service.d.ts +7 -2
- 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
package/indra/recognize.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { InferenceSession } from "onnxruntime-common";
|
|
2
2
|
import type { FloatImage, Gray } from "./image.js";
|
|
3
|
+
import type { NgramLM } from "./lm.js";
|
|
3
4
|
import type { MathReader } from "./math.js";
|
|
4
5
|
import type { Box } from "./rec-preproc.js";
|
|
5
|
-
import type { RecLine, TensorCtor } from "./types.js";
|
|
6
|
+
import type { Lazy, RecLine, TensorCtor } from "./types.js";
|
|
6
7
|
import type { Vocab } from "./vocab.js";
|
|
7
8
|
/**
|
|
8
9
|
* A recognized line under this confidence (mean CTC peak probability) gets no
|
|
@@ -10,17 +11,54 @@ import type { Vocab } from "./vocab.js";
|
|
|
10
11
|
* "I" or "1" at low confidence. The line's box stays.
|
|
11
12
|
*/
|
|
12
13
|
export declare const MIN_CONF = 0.5;
|
|
13
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* Language model re-reading: lines a recognizer reads with confidence in
|
|
16
|
+
* [MIN_CONF, gate) are read again by a CTC beam search that scores readings
|
|
17
|
+
* with the n-gram model (alpha weighs it, beta rewards each token).
|
|
18
|
+
*/
|
|
19
|
+
export type LmUse = {
|
|
20
|
+
lm: Lazy<NgramLM>;
|
|
21
|
+
alpha: number;
|
|
22
|
+
beta: number;
|
|
23
|
+
gate: number;
|
|
24
|
+
};
|
|
25
|
+
/** Lines that go to one recognizer, and whether its tokens are characters (group) or ids (main). */
|
|
14
26
|
export type RecGroup = {
|
|
15
27
|
sess: InferenceSession;
|
|
16
28
|
vocab: Vocab;
|
|
17
29
|
sel: number[];
|
|
18
30
|
asChars: boolean;
|
|
31
|
+
lm?: LmUse;
|
|
32
|
+
};
|
|
33
|
+
export declare const LM_BEAM = 8;
|
|
34
|
+
/** A class under this probability at a step is not tried by the beam search. */
|
|
35
|
+
export declare const LM_CAND_FLOOR = 0.003;
|
|
36
|
+
/**
|
|
37
|
+
* One recognizer batch: text, confidence and character positions per crop.
|
|
38
|
+
* `crops` are the recognizer inputs (a tall window for rec.onnx when its
|
|
39
|
+
* meta says so); `bands` are the line-band crops that map CTC steps back to
|
|
40
|
+
* page x, as the reference does for both.
|
|
41
|
+
*/
|
|
42
|
+
export declare function recognizeBatch(Tensor: TensorCtor, { sess, vocab, asChars, lm }: RecGroup, crops: readonly FloatImage[], bands: readonly FloatImage[], boxes: readonly Box[]): Promise<RecLine[]>;
|
|
43
|
+
/** Recognizer groups in script.onnx's class order, unless meta.json names them. */
|
|
44
|
+
export declare const GROUPS: readonly ["base", "cjk", "rtl", "other"];
|
|
45
|
+
/**
|
|
46
|
+
* A line goes to one recognizer when the classifier is surer than this;
|
|
47
|
+
* otherwise base reads it as well and the more confident reading wins.
|
|
48
|
+
*/
|
|
49
|
+
export declare const ROUTE_SURE = 0.95;
|
|
50
|
+
/** Per line crop: the script group whose recognizer reads it, and whether the classifier is sure. */
|
|
51
|
+
export type LineGroups = {
|
|
52
|
+
names: string[];
|
|
53
|
+
sure: boolean[];
|
|
19
54
|
};
|
|
20
|
-
/**
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
55
|
+
/**
|
|
56
|
+
* The group of each line crop (script.onnx), and whether the classifier is
|
|
57
|
+
* sure of it (probability over ROUTE_SURE). An older script.onnx has one
|
|
58
|
+
* output, the chance that the line holds Chinese characters. A group without
|
|
59
|
+
* its recognizer (`known`) goes to base.
|
|
60
|
+
*/
|
|
61
|
+
export declare function lineGroups(Tensor: TensorCtor, script: InferenceSession, crops: readonly FloatImage[], order: readonly string[], known: ReadonlySet<string>, batch?: number): Promise<LineGroups>;
|
|
24
62
|
/**
|
|
25
63
|
* Lines the math classifier flags are read by the math reader. A reading
|
|
26
64
|
* replaces the line only when it holds math and is confident; one token
|
package/indra/recognize.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MATH_MIN_CONF}from"./math.js";import{meanF32}from"./numeric.js";import{PAD_X,padBatch,widthBatches}from"./rec-preproc.js";import{floats,ints,item,output}from"./util.js";export let MIN_CONF=0.5;export async function recognizeBatch(Tensor,{sess,vocab,asChars},crops,boxes){const{data,dims,widths}=padBatch(crops);let res=await sess.run({x:new Tensor("float32",data,dims),widths:new Tensor("int64",widths,[crops.length])});let ids=output(res,"ids");let best=ints(ids);let pmax=floats(output(res,"conf"));let lengths=ints(output(res,"lengths"));let steps=ids.dims[1]??0;let stride=dims[3]/Math.max(steps,1);
|
|
1
|
+
import{beamSearch}from"./lm.js";import{MATH_MIN_CONF}from"./math.js";import{meanF32}from"./numeric.js";import{PAD_X,padBatch,widthBatches}from"./rec-preproc.js";import{floats,ints,item,output}from"./util.js";export let MIN_CONF=0.5;export let LM_BEAM=8;export let LM_CAND_FLOOR=0.003;let OUT_GREEDY=["ids","conf","lengths"];let OUT_LM=["blank","topv","topi"];export async function recognizeBatch(Tensor,{sess,vocab,asChars,lm},crops,bands,boxes){const{data,dims,widths}=padBatch(crops);let res=await sess.run({x:new Tensor("float32",data,dims),widths:new Tensor("int64",widths,[crops.length])},lm?[...OUT_GREEDY,...OUT_LM]:OUT_GREEDY);let ids=output(res,"ids");let best=ints(ids);let pmax=floats(output(res,"conf"));let lengths=ints(output(res,"lengths"));let steps=ids.dims[1]??0;let stride=dims[3]/Math.max(steps,1);let out=[];for(const[k,band]of bands.entries()){let n=item(lengths,k);let seq=best.slice(k*steps,k*steps+n);let kept=[];for(let t=0;t<n;t++){if(seq[t]!==0&&(t===0||seq[t]!==seq[t-1]))kept.push(t)}let keptIds=kept.map((t)=>item(seq,t));let conf=kept.length?meanF32(kept.map((t)=>pmax[k*steps+t]??0)):0;if(lm&&MIN_CONF<=conf&&conf<lm.gate){let topv=output(res,"topv");let K=topv.dims[2]??0;let read=beamSearch(floats(output(res,"blank")).subarray(k*steps,k*steps+n),floats(topv).subarray(k*steps*K,(k*steps+n)*K),topIds(output(res,"topi")).subarray(k*steps*K,(k*steps+n)*K),n,K,await lm.lm(),lm.alpha,lm.beta,LM_BEAM,0.999,LM_CAND_FLOOR);keptIds=read.ids;kept=read.steps}const[x0,y0,x1,y1]=item(boxes,k);let h=Math.max(1,y1-y0);let ix0=Math.floor(x0-PAD_X*h);let f=(Math.ceil(x1+PAD_X*h)-ix0)/band.width;let toks=kept.map((t,i)=>{let x=ix0+(t+0.5)*stride*f;let id=item(keptIds,i);return asChars?[item(vocab.chars,id-1),x]:[id,x]});out.push(conf>=MIN_CONF?{text:vocab.decode(keptIds),conf,toks}:{text:"",conf,toks:[]})}return out}function topIds(t){if(t.type!=="int64")throw new Error(`expected an int64 tensor, got ${t.type}`);return t.data}export let GROUPS=["base","cjk","rtl","other"];export let ROUTE_SURE=0.95;export async function lineGroups(Tensor,script,crops,order,known,batch=64){let names=crops.map(()=>"base");let sure=crops.map(()=>true);for(let idx of widthBatches(crops.map((c)=>c.width),batch)){const{data,dims,widths}=padBatch(idx.map((j)=>item(crops,j)));let res=await script.run({x:new Tensor("float32",data,dims),widths:new Tensor("int64",widths,[idx.length])});let out=output(res,"p");let p=floats(out);let c=out.dims.length===1?1:out.dims[1]??1;for(const[k,j]of idx.entries()){let g;let pk;if(out.dims.length===1){let v=p[k]??0;g=v>0.5?"cjk":"base";pk=Math.max(v,1-v)}else{let a=0;for(let i=1;i<c;i++)if((p[k*c+i]??0)>(p[k*c+a]??0))a=i;g=order[a]??"base";pk=p[k*c+a]??0}names[j]=known.has(g)?g:"base";sure[j]=pk>ROUTE_SURE}}return{names,sure}}export async function readMath(math,gray,boxes,crops,out){let idx=(await math.flags(crops)).flatMap((flag,j)=>flag?[j]:[]);if(!idx.length)return;let readings=await math.read(gray,idx.map((j)=>item(boxes,j)));for(const[k,j]of idx.entries()){const{text,conf}=item(readings,k);if(!text.includes("$")||conf<MATH_MIN_CONF)continue;const[x0,,x1]=item(boxes,j);out[j]={text,conf:1,toks:[[text,Math.fround(x0+x1)/2]]}}}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Gray, ImageOps } from "./image.js";
|
|
2
|
+
import type { MathReader } from "./math.js";
|
|
3
|
+
import type { Box } from "./rec-preproc.js";
|
|
4
|
+
import type { IndraMeta, IndraSessions, RecLine, TensorCtor } from "./types.js";
|
|
5
|
+
import { Vocab } from "./vocab.js";
|
|
6
|
+
/**
|
|
7
|
+
* The line recognizers of a model set: rec.onnx, and with script.onnx one
|
|
8
|
+
* recognizer per script group (rec_<group>.onnx with meta["vocab_<group>"]),
|
|
9
|
+
* each with its language model when there is one.
|
|
10
|
+
*/
|
|
11
|
+
export declare class Recognizers {
|
|
12
|
+
private readonly Tensor;
|
|
13
|
+
private readonly sessions;
|
|
14
|
+
private readonly ops;
|
|
15
|
+
private readonly useLm;
|
|
16
|
+
private readonly math;
|
|
17
|
+
readonly vocab: Vocab;
|
|
18
|
+
readonly height: number;
|
|
19
|
+
/** rec.onnx reads a window this many line heights tall. */
|
|
20
|
+
readonly window: number;
|
|
21
|
+
private readonly groups;
|
|
22
|
+
private readonly lms;
|
|
23
|
+
private readonly lmParams;
|
|
24
|
+
private readonly scriptGroups;
|
|
25
|
+
private readonly script;
|
|
26
|
+
constructor(Tensor: TensorCtor, sessions: IndraSessions, meta: IndraMeta, ops: ImageOps, useLm: boolean, math: MathReader | undefined);
|
|
27
|
+
/** Every recognizer's vocabulary: the main one first, then each group's. */
|
|
28
|
+
get vocabs(): Vocab[];
|
|
29
|
+
/** The language model use of one recognizer, when its file is there and the model emits top-k outputs. */
|
|
30
|
+
private lmUse;
|
|
31
|
+
private base;
|
|
32
|
+
private group;
|
|
33
|
+
/**
|
|
34
|
+
* Which recognizer reads which lines. With script.onnx, each line goes to
|
|
35
|
+
* the recognizer of its script group, and a line the classifier is unsure
|
|
36
|
+
* of goes to the main recognizer too. A vertical page's lines are CJK
|
|
37
|
+
* columns, characters on their side: all go to the CJK recognizer.
|
|
38
|
+
*/
|
|
39
|
+
private plan;
|
|
40
|
+
/**
|
|
41
|
+
* Text, confidence and character positions per line; a line read twice
|
|
42
|
+
* keeps the more confident reading. A line under MIN_CONF comes back empty.
|
|
43
|
+
*/
|
|
44
|
+
read(gray: Gray, boxes: readonly Box[], batch: number, vertical: boolean): Promise<RecLine[]>;
|
|
45
|
+
}
|
|
@@ -0,0 +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}}}
|
package/indra/rtl.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { isRtl } from "./unicode.js";
|
|
2
|
+
export { isRtl };
|
|
3
|
+
/** Whether any character is strong right to left. */
|
|
4
|
+
export declare function hasRtl(text: string): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Whether the line reads right to left: more RTL letters than LTR letters. The
|
|
7
|
+
* counts do not depend on the order, so logical and visual text agree.
|
|
8
|
+
*/
|
|
9
|
+
export declare function rtlBase(text: string): boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Presentation forms to base letters (NFKC on those blocks only), no tatweel,
|
|
12
|
+
* no combining mark without a base character.
|
|
13
|
+
*/
|
|
14
|
+
export declare function normalize(text: string): string;
|
|
15
|
+
/** Base characters with their combining marks (harakat, niqqud). */
|
|
16
|
+
export declare function clusters(text: string): string[];
|
|
17
|
+
/**
|
|
18
|
+
* Logical order to visual order, and visual order back to logical order.
|
|
19
|
+
* `baseRtl` is the paragraph direction when known; null or undefined decides by `rtlBase`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function flip(text: string, mirror?: boolean, baseRtl?: boolean | null): string;
|
|
22
|
+
/** The recognizer's label for a line stored in logical order. */
|
|
23
|
+
export declare function visualLabel(logical: string, baseRtl?: boolean | null): string;
|
|
24
|
+
/**
|
|
25
|
+
* The label for characters already in visual order, as stored (a PDF text layer
|
|
26
|
+
* read by glyph position). `shapes`: the layer stores each bracket as the shape
|
|
27
|
+
* drawn (see `bracketsAsShapes`), so it is already mirrored.
|
|
28
|
+
*/
|
|
29
|
+
export declare function labelFromVisual(rawVisual: string, shapes?: boolean): string;
|
|
30
|
+
/**
|
|
31
|
+
* Whether a page's text layer stores RTL brackets as drawn shapes. A page uses
|
|
32
|
+
* one convention, so its RTL lines without Latin letters vote by their first bracket.
|
|
33
|
+
*/
|
|
34
|
+
export declare function bracketsAsShapes(rawVisualLines: string[]): boolean;
|
package/indra/rtl.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isLtr,isMark,isRtl,isStrongL}from"./unicode.js";import{item}from"./util.js";export{isRtl};let MIRROR=new Map;{let from=String.fromCharCode(40,41,91,93,123,125,60,62);let to=String.fromCharCode(41,40,93,91,125,123,62,60);for(let i=0;i<from.length;i++)MIRROR.set(from.charAt(i),to.charAt(i));MIRROR.set(String.fromCharCode(171),String.fromCharCode(187));MIRROR.set(String.fromCharCode(187),String.fromCharCode(171));MIRROR.set(String.fromCharCode(8249),String.fromCharCode(8250));MIRROR.set(String.fromCharCode(8250),String.fromCharCode(8249))}let TATWEEL=1600;let isPresentation=(o)=>o>=64285&&o<=65023||o>=65136&&o<=65279;export function hasRtl(text){for(let c of text)if(isRtl(c))return true;return false}export function rtlBase(text){let r=0;let l=0;for(let c of text){if(isRtl(c))r++;else if(isStrongL(c))l++}return r>l}export function normalize(text){let out=[];for(let c of text){let o=c.codePointAt(0)??0;if(isPresentation(o))out.push(c.normalize("NFKC"));else if(o!==TATWEEL&&(out.length>0||!isMark(c)))out.push(c)}return out.join("")}export function clusters(text){let out=[];for(let c of text){if(out.length>0&&isMark(c))out[out.length-1]+=c;else out.push(c)}return out}function kindOf(cl){if(isRtl(cl))return"R";return isLtr(cl)?"L":"N"}function runs(kinds,strong,stop){let spans=[];let start=-1;let last=-1;for(let i=0;i<=kinds.length;i++){let k=kinds[i];if(k===strong){if(start<0)start=i;last=i}else if(k===stop||k===undefined){if(start>=0)spans.push([start,last+1]);start=last=-1}}return spans}function mirrored(cl){let first=String.fromCodePoint(cl.codePointAt(0)??0);return(MIRROR.get(first)??first)+cl.slice(first.length)}export function flip(text,mirror=true,baseRtl){if(!hasRtl(text))return text;let cls=clusters(text);let kinds=cls.map(kindOf);if(baseRtl??rtlBase(text)){let units=[];let i=0;let spans=runs(kinds,"L","R");spans.push([cls.length,cls.length]);for(const[a,b]of spans){for(let j=i;j<a;j++)units.push(mirror?mirrored(item(cls,j)):item(cls,j));if(a<b)units.push(cls.slice(a,b).join(""));i=b}return units.reverse().join("")}let out=[...cls];for(const[a,b]of runs(kinds,"R","L")){let seg=cls.slice(a,b).reverse();out.splice(a,b-a,...mirror?seg.map(mirrored):seg)}return out.join("")}export function visualLabel(logical,baseRtl){return flip(normalize(logical),true,baseRtl)}export function labelFromVisual(rawVisual,shapes=false){return visualLabel(flip(rawVisual,shapes))}export function bracketsAsShapes(rawVisualLines){let shapes=0;let logical=0;for(let t of rawVisualLines){if(!rtlBase(t)||[...t].some(isStrongL))continue;for(let c of t){if("([{".includes(c)){shapes++;break}if(")]}".includes(c)){logical++;break}}}return shapes>logical}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ExtractedRuns, PdfPageSource, TextLayerStats, TextLine } from "./textlayer.js";
|
|
2
|
+
/** Neighbouring right-to-left letters inside runs, and the share that step left to right. */
|
|
3
|
+
export type RtlPairs = {
|
|
4
|
+
pairs: number;
|
|
5
|
+
share: number;
|
|
6
|
+
};
|
|
7
|
+
/** Replacement, private-use, surrogate, unassigned and control characters (tab excepted). */
|
|
8
|
+
export declare function badCharCount(text: string): number;
|
|
9
|
+
/**
|
|
10
|
+
* Whether a page's upright characters run top to bottom (vertical writing):
|
|
11
|
+
* most steps between neighbouring characters go down, not right.
|
|
12
|
+
*/
|
|
13
|
+
export declare function verticalLayout(stats: TextLayerStats): boolean;
|
|
14
|
+
/** The quarter turn that holds most of the page's characters (a table set sideways), or 0. */
|
|
15
|
+
export declare function pageTurn(stats: TextLayerStats): number;
|
|
16
|
+
/**
|
|
17
|
+
* The character of a UTF-16 unit `u` (`u2`: the next unit), and whether it
|
|
18
|
+
* used `u2`. A character above U+FFFF comes as two surrogates; a lone
|
|
19
|
+
* surrogate becomes U+FFFD.
|
|
20
|
+
*/
|
|
21
|
+
export declare function codePoint(u: number, u2?: number): [string, boolean];
|
|
22
|
+
/**
|
|
23
|
+
* Text runs of a page that read left to right once the page is turned upright
|
|
24
|
+
* by `turn` quarter turns (see pageTurn), in content order, and character
|
|
25
|
+
* counts. Boxes are in the frame turned by `frame` (default `turn`): a
|
|
26
|
+
* vertical page has upright characters (turn 0) read in a turned frame (3).
|
|
27
|
+
*/
|
|
28
|
+
export declare function extractRuns(page: PdfPageSource, turn?: number, frame?: number): ExtractedRuns;
|
|
29
|
+
/**
|
|
30
|
+
* Neighbouring right-to-left letters inside a run, and the share of them that
|
|
31
|
+
* step left to right on the page.
|
|
32
|
+
*/
|
|
33
|
+
export declare function visualRtlFrac(runs: readonly TextLine[]): RtlPairs;
|
|
34
|
+
/** Python's " ".join(s.split()). */
|
|
35
|
+
export declare function collapseSpaces(s: string): string;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{pyRound}from"./det-post.js";import{isRtl}from"./rtl.js";import{isPySpace,item}from"./util.js";let BAD=/^[\p{Co}\p{Cs}\p{Cn}]$/u;let CONTROL=/^\p{Cc}$/u;export function badCharCount(text){let n=0;for(let c of text){if(c.codePointAt(0)===65533||BAD.test(c)||CONTROL.test(c)&&c!=="\t")n++}return n}function deviceAffine(page){const[w,h]=page.size();let S=1000;let dw=pyRound(w*S);let dh=pyRound(h*S);let dev=(x,y)=>{const[dx,dy]=page.pageToDevice(dw,dh,x,y);return[dx/S,dy/S]};const[o0,o1]=dev(0,0);const[ex0,ex1]=dev(1,0);const[ey0,ey1]=dev(0,1);return[ex0-o0,ey0-o0,o0,ex1-o1,ey1-o1,o1]}function quarter(dx,dy){let q=Math.atan2(dy,dx)/(Math.PI/2);let k=pyRound(q);return Math.abs(q-k)<0.01?(k%4+4)%4:undefined}function turnFrame(x,y,w,h,turn){if(turn===1)return[h-y,x];if(turn===2)return[w-x,h-y];if(turn===3)return[y,w-x];return[x,y]}export function verticalLayout(stats){const[down,right]=stats.steps??[0,0];return down>=30&&down>2*right}export function pageTurn(stats){let q=stats.quarters;let k=1;for(let i of[2,3])if(q[i]>q[k])k=i;return q[k]>0.5*Math.max(stats.chars,1)?k:0}export function codePoint(u,u2=0){if(u>=55296&&u<=56319&&u2>=56320&&u2<=57343){return[String.fromCodePoint(65536+(u-55296<<10)+(u2-56320)),true]}if(u>=55296&&u<=57343)return[String.fromCharCode(65533),false];return[String.fromCharCode(u),false]}export function extractRuns(page,turn=0,frame=turn){const[a00=0,a01=0,a02=0,a10=0,a11=0,a12=0]=deviceAffine(page);let l00=a00;let l01=-a01;let l10=-a10;let l11=a11;let quarters=new Map;let chars=[];let raw=[];let breaks=[];let qs=[];let curQ=0;let stats={chars:0,rotated:0,bad:0,quarters:[0,0,0,0]};let all=page.chars();let low=false;for(const[i,ch]of all.entries()){if(low){low=false;continue}let u2=ch.unit>=55296&&ch.unit<=56319?all[i+1]?.unit??0:0;let c;[c,low]=codePoint(ch.unit,u2);if(c==="\r"||c===`
|
|
2
|
+
`){breaks.push(chars.length);continue}if(c==="\x02")c="-";if(!isPySpace(c)){stats.chars++;stats.bad+=badCharCount(c);let q=quarters.get(ch.angle);if(!quarters.has(ch.angle)){let cos=Math.cos(ch.angle);let sin=Math.sin(ch.angle);q=quarter(l00*cos+l01*sin,l10*cos+l11*sin);quarters.set(ch.angle,q)}if(q!==undefined){stats.quarters[q]++}if(q!==turn)stats.rotated++;if(q===undefined){breaks.push(chars.length);continue}curQ=((q-turn)%4+4)%4}if(!ch.box)throw new Error("Failed to get charbox.");chars.push(c);qs.push(curQ);raw.push(ch.box)}if(!chars.length)return{runs:[],stats};const[w,h]=page.size();let corners=raw.map(([l,b,r,t])=>{let xs=[l,r,l,r];let ys=[b,b,t,t];return{px:xs.map((x,k)=>a00*x+a01*item(ys,k)+a02),py:xs.map((x,k)=>a10*x+a11*item(ys,k)+a12)}});let boxes=corners.map(({px,py})=>[Math.min(...px),Math.min(...py),Math.max(...px),Math.max(...py)]);let cx=boxes.map(([x0,,x1])=>(x0+x1)/2);let cy=boxes.map(([,y0,,y1])=>(y0+y1)/2);let visible=boxes.map((_,i)=>{let x=item(cx,i);let y=item(cy,i);return x>=0&&x<=w&&y>=0&&y<=h});stats.off_page=visible.filter((v)=>!v).length;let cut=new Set(breaks.filter((b)=>b>0&&b<chars.length).map((b)=>b-1));let down=0;let right=0;for(let i=0;i+1<chars.length;i++){if(cut.has(i)||item(qs,i)||item(qs,i+1))continue;if(isPySpace(item(chars,i))||isPySpace(item(chars,i+1)))continue;let b=item(boxes,i);let ch=Math.max(b[3]-b[1],0.001);let dx=Math.abs(item(cx,i+1)-item(cx,i));let dyRaw=item(cy,i+1)-item(cy,i);let dy=Math.abs(dyRaw);if(dx>3*ch||dy>3*ch)continue;if(dyRaw>0.3*ch&&dx<0.3*ch)down++;if(dx>0.3*ch&&dy<0.3*ch)right++}stats.steps=[down,right];if(frame){boxes=corners.map(({px,py})=>{let pts=px.map((x,k)=>turnFrame(x,item(py,k),w,h,frame));let tx=pts.map((p)=>p[0]);let ty=pts.map((p)=>p[1]);return[Math.min(...tx),Math.min(...ty),Math.max(...tx),Math.max(...ty)]})}let turns=qs.flatMap((q,i)=>i>0&&q!==qs[i-1]?[i]:[]);let runs=[];let start=0;for(let end of[...new Set([...breaks,...turns,chars.length])].toSorted((p,q)=>p-q)){let seg=[];for(let i=start;i<end;i++)if(visible[i])seg.push([item(chars,i),item(boxes,i)]);let q=start<qs.length?item(qs,start):0;start=end;let ink=seg.filter(([c])=>!isPySpace(c)).map(([,b])=>b);if(!ink.length)continue;if(frame!==turn&&!q&&ink.length>1){let first=item(ink,0);let last=item(ink,ink.length-1);let dx=Math.abs((last[0]+last[2])/2-(first[0]+first[2])/2);let dy=Math.abs((last[1]+last[3])/2-(first[1]+first[3])/2);if(dy>2*dx)q=1}runs.push({bbox:[Math.min(...ink.map((b)=>b[0])),Math.min(...ink.map((b)=>b[1])),Math.max(...ink.map((b)=>b[2])),Math.max(...ink.map((b)=>b[3]))],text:collapseSpaces(seg.map(([c])=>c).join("")),chars:seg,quarter:q,seq:runs.length})}return{runs,stats}}export function visualRtlFrac(runs){let pairs=0;let right=0;for(let r of runs){for(let i=1;i<r.chars.length;i++){const[a,ba]=item(r.chars,i-1);const[b,bb]=item(r.chars,i);if(isRtl(a)&&isRtl(b)){pairs++;if(bb[0]+bb[2]>ba[0]+ba[2])right++}}}return{pairs,share:right/Math.max(pairs,1)}}export function collapseSpaces(s){return[...s].reduce((words,c)=>{if(isPySpace(c))words.push("");else words[words.length-1]+=c;return words},[""]).filter(Boolean).join(" ")}
|
package/indra/textlayer.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import type { Gray } from "./image.js";
|
|
2
2
|
import type { Box } from "./rec-preproc.js";
|
|
3
|
+
export { badCharCount, codePoint, collapseSpaces, extractRuns, pageTurn, verticalLayout, visualRtlFrac, } from "./text-runs.js";
|
|
3
4
|
/** TextLayer.reason when the layer's character codes are not text. */
|
|
4
5
|
export declare const BROKEN_FONT_MAP = "broken font map";
|
|
6
|
+
/** TextLayer.reason when right-to-left letters are stored in visual order. */
|
|
7
|
+
export declare const VISUAL_RTL = "right-to-left text in visual order";
|
|
5
8
|
/**
|
|
6
9
|
* One character of a PDF text page: its UTF-16 unit, baseline angle, and box
|
|
7
10
|
* in page space (l, b, r, t), or undefined when pdfium has no box for it.
|
|
@@ -23,19 +26,39 @@ export type PdfPageSource = {
|
|
|
23
26
|
pageToDevice(width: number, height: number, x: number, y: number): readonly [number, number];
|
|
24
27
|
/** Render mode of every text object, nested form objects included. */
|
|
25
28
|
textRenderModes(): number[];
|
|
29
|
+
/** The page's /Rotate in degrees clockwise (0, 90, 180, 270). */
|
|
30
|
+
rotation(): number;
|
|
31
|
+
/** Set the page's /Rotate (degrees clockwise) for the reads that follow. */
|
|
32
|
+
setRotation(degrees: number): void;
|
|
26
33
|
};
|
|
27
|
-
/**
|
|
34
|
+
/**
|
|
35
|
+
* One text-layer run: its box, its text, and its characters with boxes
|
|
36
|
+
* (rendered frame, points), its quarter turns from upright, and its position
|
|
37
|
+
* among all of the page's runs in content order.
|
|
38
|
+
*/
|
|
28
39
|
export type TextLine = {
|
|
29
40
|
bbox: Box;
|
|
30
41
|
text: string;
|
|
31
42
|
chars: [string, Box][];
|
|
43
|
+
quarter: number;
|
|
44
|
+
seq: number;
|
|
32
45
|
};
|
|
33
46
|
export type TextLayerStats = {
|
|
34
47
|
chars: number;
|
|
35
48
|
rotated: number;
|
|
36
49
|
bad: number;
|
|
50
|
+
/** Characters at each quarter turn on the rendered page. */
|
|
51
|
+
quarters: [number, number, number, number];
|
|
37
52
|
off_page?: number;
|
|
53
|
+
/** Steps between neighbouring upright characters: down, right. */
|
|
54
|
+
steps?: [number, number];
|
|
38
55
|
no_ink?: number;
|
|
56
|
+
visual_rtl?: number;
|
|
57
|
+
/** The quarter turns the runs were read upright at, and the frame of their boxes. */
|
|
58
|
+
turn?: number;
|
|
59
|
+
frame?: number;
|
|
60
|
+
/** Read as vertical writing: upright characters in a turned frame. */
|
|
61
|
+
vertical?: boolean;
|
|
39
62
|
};
|
|
40
63
|
/** Upright runs of a page and its character counts. */
|
|
41
64
|
export type ExtractedRuns = {
|
|
@@ -44,29 +67,33 @@ export type ExtractedRuns = {
|
|
|
44
67
|
};
|
|
45
68
|
/** The runs of a page and whether to trust them. */
|
|
46
69
|
export type TextLayer = {
|
|
70
|
+
/** Upright runs in content order. */
|
|
47
71
|
lines: TextLine[];
|
|
48
72
|
size: readonly [number, number];
|
|
49
73
|
trusted: boolean;
|
|
50
74
|
reason: string;
|
|
51
75
|
stats: TextLayerStats;
|
|
76
|
+
/** Runs at other quarter turns (a sideways table head, a chart axis label). */
|
|
77
|
+
rotated: TextLine[];
|
|
52
78
|
};
|
|
53
|
-
/** Replacement, private-use, surrogate, unassigned and control characters (tab excepted). */
|
|
54
|
-
export declare function badCharCount(text: string): number;
|
|
55
|
-
/** Upright text runs of a page, in content order, and character counts. */
|
|
56
|
-
export declare function extractRuns(page: PdfPageSource): ExtractedRuns;
|
|
57
|
-
/** Python's " ".join(s.split()). */
|
|
58
|
-
export declare function collapseSpaces(s: string): string;
|
|
59
79
|
/**
|
|
60
80
|
* Text-layer runs of a page and the verdict on them: invisible text marks an
|
|
61
|
-
* OCR layer, bad characters a broken font map,
|
|
62
|
-
*
|
|
81
|
+
* OCR layer, bad characters a broken font map, right-to-left letters in
|
|
82
|
+
* visual order a layer that cannot be put back in reading order, runs with no
|
|
83
|
+
* ink under them hidden or misplaced text. `gray` is a render at `scale`
|
|
84
|
+
* pixels per point, turned like the runs (`frame` quarter turns clockwise).
|
|
63
85
|
*/
|
|
64
|
-
export declare function readTextLayer(page: PdfPageSource, gray: Gray, scale: number): TextLayer;
|
|
65
|
-
/**
|
|
66
|
-
export
|
|
86
|
+
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
|
+
export type UprightLayer = {
|
|
89
|
+
tl: TextLayer;
|
|
90
|
+
done: boolean;
|
|
91
|
+
};
|
|
67
92
|
/**
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
93
|
+
* The text layer of a page, read upright (`check` is a render at `scale`
|
|
94
|
+
* 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.
|
|
71
98
|
*/
|
|
72
|
-
export declare function
|
|
99
|
+
export declare function uprightTextLayer(page: PdfPageSource, check: Gray, scale: number, mode: string): UprightLayer;
|
package/indra/textlayer.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`){breaks.push(chars.length);continue}if(c==="\x02")c="-";if(!isPySpace(c)){stats.chars++;stats.bad+=badCharCount(c);let up=upright.get(ch.angle);if(up===undefined){let d0=a00*Math.cos(ch.angle)+a01*Math.sin(ch.angle);let d1=a10*Math.cos(ch.angle)+a11*Math.sin(ch.angle);up=!(d0<=0||Math.abs(d1)>0.001*Math.max(Math.abs(d0),0.000000001));upright.set(ch.angle,up)}if(!up){stats.rotated++;breaks.push(chars.length);continue}}if(!ch.box)throw new Error("Failed to get charbox.");chars.push(c);raw.push(ch.box)}if(!chars.length)return{runs:[],stats};const[w,h]=page.size();let boxes=raw.map(([l,b,r,t])=>{let px=[l,r,l,r].map((x,i)=>a00*x+a01*item([b,b,t,t],i)+a02);let py=[l,r,l,r].map((x,i)=>a10*x+a11*item([b,b,t,t],i)+a12);return[Math.min(...px),Math.min(...py),Math.max(...px),Math.max(...py)]});let visible=boxes.map(([x0,y0,x1,y1])=>{let cx=(x0+x1)/2;let cy=(y0+y1)/2;return cx>=0&&cx<=w&&cy>=0&&cy<=h});stats.off_page=visible.filter((v)=>!v).length;let runs=[];let start=0;for(let end of[...new Set([...breaks,chars.length])].toSorted((p,q)=>p-q)){let seg=[];for(let i=start;i<end;i++)if(visible[i])seg.push([item(chars,i),item(boxes,i)]);start=end;let ink=seg.filter(([c])=>!isPySpace(c)).map(([,b])=>b);if(!ink.length)continue;runs.push({bbox:[Math.min(...ink.map((b)=>b[0])),Math.min(...ink.map((b)=>b[1])),Math.max(...ink.map((b)=>b[2])),Math.max(...ink.map((b)=>b[3]))],text:collapseSpaces(seg.map(([c])=>c).join("")),chars:seg})}return{runs,stats}}export function collapseSpaces(s){return[...s].reduce((words,c)=>{if(isPySpace(c))words.push("");else words[words.length-1]+=c;return words},[""]).filter(Boolean).join(" ")}function invisibleTextFrac(page){let modes=page.textRenderModes();return modes.length?modes.filter((m)=>m===TEXT_RENDER_INVISIBLE).length/modes.length:0}function noInkFrac(gray,runs,scale){let empty=0;for(const{bbox:[x0,y0,x1,y1]}of runs){let r0=Math.max(0,Math.trunc(y0*scale));let r1=Math.min(gray.height,Math.trunc(y1*scale)+1);let c0=Math.max(0,Math.trunc(x0*scale));let c1=Math.min(gray.width,Math.trunc(x1*scale)+1);let ink=false;for(let y=r0;y<r1&&!ink;y++){for(let x=c0;x<c1;x++){if((gray.data[y*gray.width+x]??255)<DARK){ink=true;break}}}if(!ink)empty++}return empty/Math.max(runs.length,1)}let pct=(x)=>`${roundTo(x*100,0)}%`;export function readTextLayer(page,gray,scale){let size=page.size();let inv=invisibleTextFrac(page);let fail=(lines,reason,stats)=>({lines,size,trusted:false,reason,stats});if(inv>MAX_INVISIBLE_FRAC){return fail([],`invisible text ${pct(inv)} (OCR layer)`,{chars:0,rotated:0,bad:0})}const{runs,stats}=extractRuns(page);if(!runs.length)return fail([],"no text layer",stats);if(stats.bad>MAX_BAD_CHAR_FRAC*Math.max(stats.chars,1))return fail(runs,BROKEN_FONT_MAP,stats);let empty=noInkFrac(gray,runs,scale);stats.no_ink=roundTo(empty,4);if(empty>MAX_NO_INK_LINE_FRAC)return fail(runs,`${pct(empty)} of text runs have no ink`,stats);return{lines:runs,size,trusted:true,reason:"",stats}}export function orderBacktracks(boxes){if(boxes.length<3)return 0;let f=Math.fround;let h=medianF32(boxes.map(([,y0,,y1])=>f(y1-y0)));let bt=0;for(let i=1;i<boxes.length;i++){let a=item(boxes,i-1);let b=item(boxes,i);if(b[1]<f(a[1]-f(0.5*h))&&b[0]<f(a[2]-f(h)))bt++}return bt}export function pdfOrderCoherent(boxes,pairLogits){let n=boxes.length;if(orderBacktracks(boxes)>Math.max(1,Math.trunc(0.02*n)))return false;if(!pairLogits||n<3)return true;let agree=0;for(let i=0;i<n-1;i++)if((pairLogits[i*n+i+1]??0)>0)agree++;return agree/(n-1)>=MIN_MODEL_AGREEMENT}
|
|
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}}
|
package/indra/ts-image-ops.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
let clampByte=(v)=>Math.min(255,Math.max(0,Math.round(v)));function linearTaps(out,size){let scale=size/out;let i0=new Int32Array(out);let i1=new Int32Array(out);let w=new Float64Array(out);for(let d=0;d<out;d++){let s=Math.min(Math.max((d+0.5)*scale-0.5,0),size-1);let f=Math.floor(s);i0[d]=f;i1[d]=Math.min(f+1,size-1);w[d]=s-f}return{i0,i1,w}}function resizeLinear(src,width,height){let xs=linearTaps(width,src.width);let ys=linearTaps(height,src.height);let out=new Uint8Array(width*height);let s=src.data;for(let y=0;y<height;y++){let r0=(ys.i0[y]??0)*src.width;let r1=(ys.i1[y]??0)*src.width;let wy=ys.w[y]??0;for(let x=0;x<width;x++){let a=xs.i0[x]??0;let b=xs.i1[x]??0;let wx=xs.w[x]??0;let top=(s[r0+a]??0)*(1-wx)+(s[r0+b]??0)*wx;let bot=(s[r1+a]??0)*(1-wx)+(s[r1+b]??0)*wx;out[y*width+x]=clampByte(top*(1-wy)+bot*wy)}}return{data:out,width,height}}function areaSpans(out,size){let scale=size/out;return Array.from({length:out},(_,d)=>{let lo=d*scale;let hi=Math.min((d+1)*scale,size);let start=Math.floor(lo);let weights=[];for(let i=start;i<hi;i++)weights.push((Math.min(i+1,hi)-Math.max(i,lo))/(hi-lo));return{start,weights}})}function resizeArea(src,width,height){if(width>src.width||height>src.height)return resizeLinear(src,width,height);let xs=areaSpans(width,src.width);let ys=areaSpans(height,src.height);let out=new Uint8Array(width*height);let row=new Float64Array(width);for(const[y,sy]of ys.entries()){row.fill(0);for(const[k,wy]of sy.weights.entries()){let base=(sy.start+k)*src.width;for(const[x,sx]of xs.entries()){let acc=0;for(const[j,wx]of sx.weights.entries())acc+=(src.data[base+sx.start+j]??0)*wx;row[x]=(row[x]??0)+acc*wy}}for(let x=0;x<width;x++)out[y*width+x]=clampByte(row[x]??0)}return{data:out,width,height}}function invert([a,b,c,d,e,f]){let det=a*e-b*d;let ia=e/det;let ib=-b/det;let id=-d/det;let ie=a/det;return[ia,ib,-(ia*c+ib*f),id,ie,-(id*c+ie*f)]}function warp(src,m,width,height,edge){const[a,b,c,d,e,f]=invert(m);let out=new
|
|
1
|
+
let clampByte=(v)=>Math.min(255,Math.max(0,Math.round(v)));function linearTaps(out,size){let scale=size/out;let i0=new Int32Array(out);let i1=new Int32Array(out);let w=new Float64Array(out);for(let d=0;d<out;d++){let s=Math.min(Math.max((d+0.5)*scale-0.5,0),size-1);let f=Math.floor(s);i0[d]=f;i1[d]=Math.min(f+1,size-1);w[d]=s-f}return{i0,i1,w}}function resizeLinear(src,width,height){let xs=linearTaps(width,src.width);let ys=linearTaps(height,src.height);let out=new Uint8Array(width*height);let s=src.data;for(let y=0;y<height;y++){let r0=(ys.i0[y]??0)*src.width;let r1=(ys.i1[y]??0)*src.width;let wy=ys.w[y]??0;for(let x=0;x<width;x++){let a=xs.i0[x]??0;let b=xs.i1[x]??0;let wx=xs.w[x]??0;let top=(s[r0+a]??0)*(1-wx)+(s[r0+b]??0)*wx;let bot=(s[r1+a]??0)*(1-wx)+(s[r1+b]??0)*wx;out[y*width+x]=clampByte(top*(1-wy)+bot*wy)}}return{data:out,width,height}}function areaSpans(out,size){let scale=size/out;return Array.from({length:out},(_,d)=>{let lo=d*scale;let hi=Math.min((d+1)*scale,size);let start=Math.floor(lo);let weights=[];for(let i=start;i<hi;i++)weights.push((Math.min(i+1,hi)-Math.max(i,lo))/(hi-lo));return{start,weights}})}function resizeArea(src,width,height){if(width>src.width||height>src.height)return resizeLinear(src,width,height);let xs=areaSpans(width,src.width);let ys=areaSpans(height,src.height);let out=new Uint8Array(width*height);let row=new Float64Array(width);for(const[y,sy]of ys.entries()){row.fill(0);for(const[k,wy]of sy.weights.entries()){let base=(sy.start+k)*src.width;for(const[x,sx]of xs.entries()){let acc=0;for(const[j,wx]of sx.weights.entries())acc+=(src.data[base+sx.start+j]??0)*wx;row[x]=(row[x]??0)+acc*wy}}for(let x=0;x<width;x++)out[y*width+x]=clampByte(row[x]??0)}return{data:out,width,height}}function invert([a,b,c,d,e,f]){let det=a*e-b*d;let ia=e/det;let ib=-b/det;let id=-d/det;let ie=a/det;return[ia,ib,-(ia*c+ib*f),id,ie,-(id*c+ie*f)]}function warp(src,m,width,height,edge){const[a,b,c,d,e,f]=invert(m);let out=new Uint8Array(width*height);const{width:sw,height:sh,data}=src;let read=(x,y)=>{if(x>=0&&x<sw&&y>=0&&y<sh)return data[y*sw+x]??0;if(edge==="zero")return 0;return data[Math.min(Math.max(y,0),sh-1)*sw+Math.min(Math.max(x,0),sw-1)]??0};for(let y=0;y<height;y++){let rowX=b*y+c;let rowY=e*y+f;let row=y*width;for(let x=0;x<width;x++){let sx=a*x+rowX;let sy=d*x+rowY;let x0=Math.floor(sx);let y0=Math.floor(sy);let wx=sx-x0;let wy=sy-y0;let v;if(x0>=0&&y0>=0&&x0+1<sw&&y0+1<sh){let i=y0*sw+x0;let top=(data[i]??0)*(1-wx)+(data[i+1]??0)*wx;let bot=(data[i+sw]??0)*(1-wx)+(data[i+sw+1]??0)*wx;v=top*(1-wy)+bot*wy}else if(edge==="zero"&&(x0+1<0||y0+1<0||x0>=sw||y0>=sh)){continue}else{v=(read(x0,y0)*(1-wx)+read(x0+1,y0)*wx)*(1-wy)+(read(x0,y0+1)*(1-wx)+read(x0+1,y0+1)*wx)*wy}out[row+x]=Math.round(v)}}return{data:out,width,height}}export let tsImageOps={resize(src,width,height,interpolation){if(width===src.width&&height===src.height)return{...src,data:src.data.slice()};return interpolation==="area"?resizeArea(src,width,height):resizeLinear(src,width,height)},warpReplicate(src,m,width,height){return warp(src,m,width,height,"replicate")},warpZero(src,m,width,height){return warp(src,m,width,height,"zero")}};
|
package/indra/types.d.ts
CHANGED
|
@@ -2,12 +2,13 @@ import type { InferenceSession, Tensor } from "onnxruntime-common";
|
|
|
2
2
|
import type { DetBox } from "./det-post.js";
|
|
3
3
|
import type { Gray } from "./image.js";
|
|
4
4
|
import type { LayoutBlock } from "./layout-post.js";
|
|
5
|
+
import type { NgramLM } from "./lm.js";
|
|
5
6
|
import type { MathReader } from "./math.js";
|
|
6
7
|
import type { Box } from "./rec-preproc.js";
|
|
7
8
|
/**
|
|
8
|
-
* One recognized character position: a class id (
|
|
9
|
-
* character (
|
|
10
|
-
* layer characters their index in the PDF content stream.
|
|
9
|
+
* One recognized character position: a class id (main recognizer) or a
|
|
10
|
+
* character (group recognizer, PDF text layer, math), its page x, and for
|
|
11
|
+
* text-layer characters their index in the PDF content stream.
|
|
11
12
|
*/
|
|
12
13
|
export type Tok = readonly [id: number | string, x: number, contentIndex?: number];
|
|
13
14
|
/** Text, confidence and character positions of one detected line. */
|
|
@@ -41,6 +42,11 @@ export type Page = {
|
|
|
41
42
|
rotation: number;
|
|
42
43
|
/** Degrees of small tilt undone; boxes are mapped back to the turned page. */
|
|
43
44
|
skew: number;
|
|
45
|
+
/**
|
|
46
|
+
* Set in vertical columns (Chinese, Japanese): read turned a quarter turn,
|
|
47
|
+
* columns as lines. Boxes are on the page as it is (rotation stays 0).
|
|
48
|
+
*/
|
|
49
|
+
vertical: boolean;
|
|
44
50
|
/** Milliseconds per stage, with total_ms. */
|
|
45
51
|
timings: Record<string, number>;
|
|
46
52
|
};
|
|
@@ -62,7 +68,11 @@ export type DetectPass = {
|
|
|
62
68
|
boxes: DetBox[];
|
|
63
69
|
scale: number;
|
|
64
70
|
};
|
|
65
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* orient.onnx's verdict: quarter turns (counter-clockwise) the content is
|
|
73
|
+
* turned by, or VERTICAL (4) for a page set in vertical columns, and the
|
|
74
|
+
* class probabilities.
|
|
75
|
+
*/
|
|
66
76
|
export type Orientation = {
|
|
67
77
|
turns: number;
|
|
68
78
|
probs: number[];
|
|
@@ -73,21 +83,41 @@ export type Straightened = {
|
|
|
73
83
|
turns: number;
|
|
74
84
|
skew: number;
|
|
75
85
|
};
|
|
86
|
+
/** Per-group language model settings in meta.json (`lm_params`). */
|
|
87
|
+
export type LmParams = {
|
|
88
|
+
alpha?: number;
|
|
89
|
+
beta?: number;
|
|
90
|
+
gate?: number;
|
|
91
|
+
};
|
|
76
92
|
/** The `meta.json` that ships with the models. */
|
|
77
93
|
export type IndraMeta = {
|
|
78
94
|
vocab: string;
|
|
79
|
-
vocab_cjk?: string;
|
|
80
95
|
rec_height: number;
|
|
81
96
|
det_long_side: number;
|
|
97
|
+
/** rec.onnx reads a window this many line heights tall (the line and the page around it). */
|
|
98
|
+
rec_window?: number;
|
|
99
|
+
/** script.onnx's class order (default base, cjk, rtl, other). */
|
|
100
|
+
script_groups?: string[];
|
|
101
|
+
lm_params?: Record<string, LmParams>;
|
|
102
|
+
} & {
|
|
103
|
+
[group: `vocab_${string}`]: string | undefined;
|
|
82
104
|
};
|
|
83
|
-
/**
|
|
105
|
+
/** A model that loads on its first use. */
|
|
106
|
+
export type Lazy<T> = () => Promise<T>;
|
|
107
|
+
/**
|
|
108
|
+
* ONNX Runtime sessions of the Indra models. Optional ones switch a stage
|
|
109
|
+
* off. `groups` holds the recognizer of each script group (cjk, rtl, world),
|
|
110
|
+
* `lms` the language model of a recognizer ("base" is rec.onnx); both load on
|
|
111
|
+
* the first line that needs them.
|
|
112
|
+
*/
|
|
84
113
|
export type IndraSessions = {
|
|
85
114
|
det: InferenceSession;
|
|
86
115
|
rec: InferenceSession;
|
|
87
116
|
order?: InferenceSession;
|
|
88
117
|
orient?: InferenceSession;
|
|
89
118
|
script?: InferenceSession;
|
|
90
|
-
|
|
119
|
+
groups?: Record<string, Lazy<InferenceSession>>;
|
|
120
|
+
lms?: Record<string, Lazy<NgramLM>>;
|
|
91
121
|
};
|
|
92
122
|
export type TensorCtor = typeof Tensor;
|
|
93
123
|
/** Pipeline settings beyond the models. */
|
|
@@ -98,4 +128,6 @@ export type PipelineOptions = {
|
|
|
98
128
|
adaptive?: boolean;
|
|
99
129
|
/** Read lines with math as LaTeX. Off unless given. */
|
|
100
130
|
math?: MathReader;
|
|
131
|
+
/** Re-read unsure lines with the language models (when given). Default true. */
|
|
132
|
+
lm?: boolean;
|
|
101
133
|
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export let BIDI_TABLE="1c 9 3 7 p 2 6 p 2 1b 0 2 7 1 3 1 0 2 3 0 3 0 0 2 5 m 2 1 u 2 1 cg 2 2 6 2 e 1 2 e 4 2 9"+" 0 2 h 33 4 0 3 2 2 1 2 2 3 2 1 0 2 6 0 2 1 2 2 1 0 2 1 j 2 1 2a 2 1 3v 2 0 6 4 0 4l 2 1"+" 11 2 2 1c 2 7 18 4 0 0 1 0 0 4 0 0 1 0 1 4 0 0 1 0 1 4 0 0 1 0 0 4 8 q 1 4 5 1 b 5 3 2 "+"0 1 2 0 1 1 0 1 2 a 4 0 1b 1 0 k 4 0 9 3 1 1 3 0 2 1 0 0 4 0 2s 1 0 6 4 0 0 3 1 5 4 0 1 "+"1 0 1 4 1 3 4 0 1 1 0 9 3 0 j 1 1 1 1 0 0 4 0 t 1 0 q 4 2 2g 1 0 a 4 0 0 1 e 16 1 0 8 4 "+"0 1 1 4 0 1 2 0 4 0 n 1 0 3 4 0 0 1 0 8 4 0 0 1 0 2 4 0 0 1 0 4 4 2 e 1 1 o 1 0 2 4 2 0 "+"1 1 a 1 5 u 1 1 1 3 6 7 4 0 15 1 0 n 4 0 0 3 0 v 4 0 1i 2 0 0 4 0 0 2 0 0 4 0 3 2 0 7 4 "+"0 3 2 0 0 4 0 2 2 0 6 4 0 9 2 0 1 4 0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E_TABLE="3cw 2n 1 3i2 1 1 d 1 1 5a 3 1 3 0 1 2 0 1 eh 1 1 l 1 1 1e b 1 17 0 1 j 0 1 d 0 1 8 1 1 h"+" 1 1 5 1 1 8 0 1 5 0 1 l 0 1 7 1 1 1 0 1 4 0 1 2 0 1 7 0 1 4 1 1 s 0 1 z 0 1 1 0 1 4 2 1"+" 1 0 1 1p 2 1 o 0 1 e 0 1 nv 1 1 1f 0 1 4 0 1 mi p 1 1 2g 1 c 5x 1 q b 1 4 1q 1 2 2d 1 2"+" 2u 1 5 16 1 1 2l 1 1 2b 1 c 1a 1 1 13 1 8 5f3 1 1s h3g 1 3 1i 1 wp s 1 hv 8mb 1 6l8 e7 "+"1 ls 9 1 m y 1 1 i 1 1 3 1 45 2n 1 3j 6 1 m49 4 1 b 1 1 e 4qf 1 8 yd 1 16 8 1 6w7 3 1 1 "+"6 1 1 1 1 1 82 1 f 0 1 t 2 1 2 0 1 e 3 1 8 az 1 c20 0 1 5m 0 1 5a 0 1 2 9 1 2t 2 1 d 17 "+"1 4 8 1 7 1 1 e 5 1 4a w 1 c 8 1 1 1x 1 1 l 1 c 16 1 4 4 1 c g 1 3 0 1 3 1y 1 1 0 1 1 56"+" 1 2 1q 1 d 3 1 1 n 1 i 0 1 q 1 1 d 0 1 2e 2c 1 1c 1x 1 6 0 1 3 2 1 2 2 1 4 3 1 b 1 1 7 "+"8 1 6b b 1 4 0 1 7v 1a 1 1 9 1 1 54 1 34 c 1 3 8 1 7 19 1 1 6 1 8 d 1 4 8 1 7 8 1 zr 1ek"+"d 1 2 1ekd 1";
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Bidi classes the port tells apart; everything else is `OTHER`. */
|
|
2
|
+
export declare const OTHER = 0;
|
|
3
|
+
/** R or AL. */
|
|
4
|
+
export declare const RTL = 1;
|
|
5
|
+
/** L. */
|
|
6
|
+
export declare const LTR = 2;
|
|
7
|
+
/** EN or AN. */
|
|
8
|
+
export declare const DIGIT = 3;
|
|
9
|
+
/** General category Mn or Me. */
|
|
10
|
+
export declare const MARK = 4;
|
|
11
|
+
/** `RTL`, `LTR`, `DIGIT`, `MARK` or `OTHER` for a code point. */
|
|
12
|
+
export declare function bidiClass(cp: number): number;
|
|
13
|
+
/** Whether East Asian width is W or F. */
|
|
14
|
+
export declare function eastAsianWide(cp: number): boolean;
|
|
15
|
+
/** Strong right-to-left (bidi R or AL) for the first code point of `c`. */
|
|
16
|
+
export declare function isRtl(c: string): boolean;
|
|
17
|
+
/** Reads left to right inside RTL text: bidi L, EN or AN. */
|
|
18
|
+
export declare function isLtr(c: string): boolean;
|
|
19
|
+
/** Bidi class L only (letters, not digits). */
|
|
20
|
+
export declare function isStrongL(c: string): boolean;
|
|
21
|
+
/** Combining mark (Mn or Me). */
|
|
22
|
+
export declare function isMark(c: string): boolean;
|
|
23
|
+
/** Length in code points with East Asian wide characters counted twice. */
|
|
24
|
+
export declare function displayLen(text: string): number;
|
package/indra/unicode.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BIDI_TABLE,WIDE_TABLE}from"./unicode-data.js";import{item}from"./util.js";export let OTHER=0;export let RTL=1;export let LTR=2;export let DIGIT=3;export let MARK=4;function decode(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 classes=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;classes[i]=t[3*i+2]??0}return{starts,ends,classes}}let bidi;let wide;function lookup(r,cp){let lo=0;let hi=r.starts.length-1;while(lo<=hi){let mid=lo+hi>>1;if(cp<item(r.starts,mid))hi=mid-1;else if(cp>item(r.ends,mid))lo=mid+1;else return item(r.classes,mid)}return 0}export function bidiClass(cp){bidi??=decode(BIDI_TABLE);return lookup(bidi,cp)}export function eastAsianWide(cp){wide??=decode(WIDE_TABLE);return lookup(wide,cp)===1}let cpOf=(c)=>c.codePointAt(0)??0;export function isRtl(c){return bidiClass(cpOf(c))===RTL}export function isLtr(c){let k=bidiClass(cpOf(c));return k===LTR||k===DIGIT}export function isStrongL(c){return bidiClass(cpOf(c))===LTR}export function isMark(c){return bidiClass(cpOf(c))===MARK}export function displayLen(text){let n=0;for(let c of text)n+=eastAsianWide(cpOf(c))?2:1;return n}
|
package/indra/upright.d.ts
CHANGED
|
@@ -6,13 +6,24 @@ export declare const ORIENT_SIDE = 768;
|
|
|
6
6
|
* upright, and a wrong turn loses the page.
|
|
7
7
|
*/
|
|
8
8
|
export declare const ORIENT_MIN = 0.95;
|
|
9
|
+
/** orient.onnx class (5-class models): the page is set in vertical columns. */
|
|
10
|
+
export declare const VERTICAL = 4;
|
|
9
11
|
export declare const DESKEW_MIN = 0.3;
|
|
12
|
+
/** The skew search and orient.onnx read this shrunk copy of the page, not the full scan. */
|
|
13
|
+
export declare const PREVIEW_SIDE = 1600;
|
|
10
14
|
/** The orient.onnx input: [side, side] ink map, long side scaled to `side`, padded with 0. */
|
|
11
15
|
export declare function orientInput(gray: Gray, ops: ImageOps, side?: number): Float32Array;
|
|
16
|
+
/**
|
|
17
|
+
* The page shrunk once to at most `side` pixels a side (area averaging); a
|
|
18
|
+
* smaller page is returned as is.
|
|
19
|
+
*/
|
|
20
|
+
export declare function preview(gray: Gray, ops: ImageOps, side?: number): Gray;
|
|
12
21
|
/**
|
|
13
22
|
* Degrees (counter-clockwise) that straighten the text rows of a page: the
|
|
14
|
-
* angle whose horizontal ink profile changes most sharply row to row
|
|
15
|
-
*
|
|
23
|
+
* angle whose horizontal ink profile changes most sharply row to row. Searched
|
|
24
|
+
* over +-DESKEW_MAX in 2 degree steps on a half-size thumbnail; the two best
|
|
25
|
+
* angles and 0 are then refined in 0.5 and 0.1 degree steps on the full
|
|
26
|
+
* thumbnail (`side` pixels), where small text rows are still resolved.
|
|
16
27
|
*/
|
|
17
28
|
export declare function estimateSkew(gray: Gray, ops: ImageOps, side?: number): number;
|
|
18
29
|
/** The page rotated by `degrees` counter-clockwise about its center (same size, edges replicated). */
|
package/indra/upright.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{pyRound}from"./det-post.js";import{inkOf,rotationMatrix}from"./image.js";
|
|
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))}
|
package/indra/vocab.d.ts
CHANGED
|
@@ -6,8 +6,10 @@ export declare class Vocab {
|
|
|
6
6
|
readonly chars: readonly string[];
|
|
7
7
|
readonly index: ReadonlyMap<string, number>;
|
|
8
8
|
readonly hasCommands: boolean;
|
|
9
|
+
/** Hangul syllables are read as jamo and composed back (NFC) on decode. */
|
|
10
|
+
readonly jamo: boolean;
|
|
9
11
|
constructor(chars: readonly string[]);
|
|
10
|
-
/** A vocabulary from
|
|
12
|
+
/** A vocabulary from a `vocab` / `vocab_<group>` JSON string in meta.json. */
|
|
11
13
|
static fromJson(json: string): Vocab;
|
|
12
14
|
/** Text of class ids. A space goes back between a command and a following letter. */
|
|
13
15
|
decode(ids: readonly number[]): string;
|
package/indra/vocab.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class Vocab{chars;index;hasCommands;constructor(chars){this.chars=chars;this.index=new Map(chars.map((c,i)=>[c,i+1]));this.hasCommands=chars.some((c)=>[...c].length>1)}static fromJson(json){let data=JSON.parse(json);if((data.blank??0)!==0)throw new Error("only blank=0 vocabularies are supported");if(!Array.isArray(data.chars)||!data.chars.every((c)=>typeof c==="string")){throw new Error("vocab JSON has no chars array")}return new Vocab(data.chars)}decode(ids){let toks=[];for(let id of ids){let tok=this.chars[id-1];if(id>0&&tok!==undefined)toks.push(tok)}if(!this.hasCommands)return toks.join("");let out="";for(const[k,t]of toks.entries()){out+=t;let next=toks[k+1]??"";if(t.length>2&&t[0]==="\\"&&LETTERS.test(t.slice(1))&&LETTERS.test([...next][0]??"")){out+=" "}}return out}}let LETTERS=/^\p{L}+$/u;
|
|
1
|
+
export class Vocab{chars;index;hasCommands;jamo;constructor(chars){this.chars=chars;this.index=new Map(chars.map((c,i)=>[c,i+1]));this.hasCommands=chars.some((c)=>[...c].length>1);this.jamo=this.index.has(String.fromCharCode(4352))}static fromJson(json){let data=JSON.parse(json);if((data.blank??0)!==0)throw new Error("only blank=0 vocabularies are supported");if(!Array.isArray(data.chars)||!data.chars.every((c)=>typeof c==="string")){throw new Error("vocab JSON has no chars array")}return new Vocab(data.chars)}decode(ids){let toks=[];for(let id of ids){let tok=this.chars[id-1];if(id>0&&tok!==undefined)toks.push(tok)}if(this.jamo)return toks.join("").normalize("NFC");if(!this.hasCommands)return toks.join("");let out="";for(const[k,t]of toks.entries()){out+=t;let next=toks[k+1]??"";if(t.length>2&&t[0]==="\\"&&LETTERS.test(t.slice(1))&&LETTERS.test([...next][0]??"")){out+=" "}}return out}}let LETTERS=/^\p{L}+$/u;
|