diff --git "a/app.js" "b/app.js" --- "a/app.js" +++ "b/app.js" @@ -1,12 +1,12 @@ -import{InferenceSession as Je,Tensor as Qe,env as In}from"onnxruntime-web";function z(t){let n=Math.floor(t),e=t-n;if(e>0.5)return n+1;if(e<0.5)return n;return n%2===0?n:n+1}var G=(t,n,e)=>te?e:t,H=(t)=>{if(!t.length)return NaN;let n=[...t].sort((o,s)=>o-s),e=n.length>>1;return n.length%2?n[e]:(n[e-1]+n[e])/2};function Kt(t,n,e){let o=[];if(e==="area"&&n0)u.push([c,p])}o.push(u)}return o}let s=t/n;for(let a=0;at-1)u=t-1;o.push(l===u||i<=0?[[l,1]]:[[l,1-i],[u,i]])}return o}function X(t,n,e,o,s,a="linear"){if(o===n&&s===e)return t;let r=Kt(n,o,a),l=Kt(e,s,a),i=new Float64Array(o*e);for(let h=0;h{if(f)w=w<0?0:w>=s?s-1:w,M=M<0?0:M>=a?a-1:M;else if(w<0||w>=s||M<0||M>=a)return 0;return o[M*s+w]},x=new o.constructor(r*l),A=x instanceof Uint8Array;for(let w=0;w0){let A=p[--g],w=A/e|0,M=A-w*e;if(x.area++,Mx.x1)x.x1=M;let I=(w+0.5)*kt;if(x.sumTop+=I-l[A],x.sumBot+=I+i[A],x.sumSc+=h[A],M>0&&u[A-1]===0&&h[A-1]>o)u[A-1]=f,p[g++]=A-1;if(Mo)u[A+1]=f,p[g++]=A+1;if(w>0&&u[A-e]===0&&h[A-e]>o)u[A-e]=f,p[g++]=A-e;if(wo)u[A+e]=f,p[g++]=A+e}c.push(x)}let d=[];for(let m=1;m{let l=0,i=256;while(l>1;if(o[u]>r)i=u;else l=u+1}return l};return e.map((r)=>{let l=r*(n-1),i=Math.floor(l),u=l-i,h=a(i),c=a(Math.min(i+1,n-1)),p=c-h;return u>=0.5?c-p*(1-u):h+p*u})}function Tt(t,n){let{height:e,width:o}=t,s=n[0],a=n[1],r=n[2],l=n[3],i=Math.max(0,Math.trunc(a)),u=Math.min(e,Math.trunc(l)+1),h=Math.max(0,Math.trunc(s)),c=Math.min(o,Math.trunc(r)+1);if(u<=i||c<=h)return!1;let p=new Int32Array(256),d=0;for(let x=i;x2*(f-m)+8}function rt(t,n,e=jn,o=4096,s=1,a=null){let r=(s*(1+2*Dn)-1)/2;e=e*s;let[l,i,u,h]=n,c=Math.max(1,h-i),p=l-at*c,d=u+at*c,m=i-r*c,f=h+r*c,{height:g,width:x}=t,A=Math.floor(p),w=Math.floor(m),M=Math.ceil(d),I=Math.ceil(f),k=Math.max(1,M-A),_=Math.max(1,I-w);if(a===null)a=Tt(t,n);let E=new Uint8Array(_*k).fill(a?0:255),C=Math.max(0,A),L=Math.max(0,w),R=Math.min(x,M),y=Math.min(g,I);if(R>C&&y>L)for(let S=L;Se?"area":"linear"),j=new Float32Array(T.length);if(a)for(let S=0;Sa.w));e=Math.ceil(e/Et)*Et;let o=new Float32Array(t.length*n*e),s=new BigInt64Array(t.length);return t.forEach((a,r)=>{for(let l=0;li).sort((l,i)=>t[l]-t[i]),r=[];for(let l of a){let i=r[r.length-1];if(i&&i.length{let e=0,o=t.length/2;while(e>1;if(t[s*2+1]q(Fn,t.codePointAt(0))||q(Pn,t.codePointAt(0)),Zt=(t)=>q(Yt,t.codePointAt(0)),Jt=(t)=>q(Yt,t.codePointAt(0))||q(Un,t.codePointAt(0)),Qt=(t)=>q(Hn,t.codePointAt(0)),tn=(t)=>q(Gn,t.codePointAt(0)),Wn=new Int32Array([48,57,178,179,185,185,1632,1641,1776,1785,1984,1993,2406,2415,2534,2543,2662,2671,2790,2799,2918,2927,3046,3055,3174,3183,3302,3311,3430,3439,3558,3567,3664,3673,3792,3801,3872,3881,4160,4169,4240,4249,4969,4977,6112,6121,6160,6169,6470,6479,6608,6618,6784,6793,6800,6809,6992,7001,7088,7097,7232,7241,7248,7257,8304,8304,8308,8313,8320,8329,9312,9320,9332,9340,9352,9360,9450,9450,9461,9469,9471,9471,10102,10110,10112,10120,10122,10130,42528,42537,43216,43225,43264,43273,43472,43481,43504,43513,43600,43609,44016,44025,65296,65305,66720,66729,68160,68163,68912,68921,68928,68937,69216,69224,69714,69722,69734,69743,69872,69881,69942,69951,70096,70105,70384,70393,70736,70745,70864,70873,71248,71257,71360,71369,71376,71395,71472,71481,71904,71913,72016,72025,72688,72697,72784,72793,73040,73049,73120,73129,73552,73561,90416,90425,92768,92777,92864,92873,93008,93017,93552,93561,118000,118009,120782,120831,123200,123209,123632,123641,124144,124153,124401,124410,125264,125273,127232,127242,130032,130041]),Lt=(t)=>q(Wn,t.codePointAt(0));var nn=16,F=["Text","Section-Header","Page-Header","Page-Footer","List-Group","Table","Caption","Footnote","Table-Of-Contents","Form"],Ct=new Set(["Table","Form","Table-Of-Contents"].map((t)=>F.indexOf(t))),Vn=".!?:;。!?:;.",Kn=(t)=>!!t&&[...t].every(Lt),Xn=(t)=>t!==t.toLowerCase()&&t===t.toUpperCase(),qn=(t)=>{let n=0;for(let e of t)n+=Qt(e)?2:1;return n};function en(t,n,e,o){let s=t.length,a=new Float32Array(s*nn);if(!s)return a;let r=H(t.map((l)=>Math.max(l[3]-l[1],0.001)));for(let l=0;l3),a[m+13]=Number(f.endsWith("-")),a[m+14]=Number(Vn.includes(f[f.length-1])),a[m+15]=Number(Xn(f[0]))}return a}var dt=(t)=>t>=0?-Math.log1p(Math.exp(-t)):t-Math.log1p(Math.exp(t));function $t(t,n,e=4){if(n<=1)return Array.from({length:n},(a,r)=>r);let o=new Float64Array(n);for(let a=0;ar).sort((a,r)=>o[a]-o[r]);for(let a=0;af!==l),u=i.map((f)=>dt(t[f*n+l])),h=i.map((f)=>dt(t[l*n+f])),c=new Float64Array(n),p=0;for(let f=1;f=0;f--)c[f]+=p+=h[f];let d=0;for(let f=1;fc[d])d=f;let m=s.indexOf(l);if(c[d]>c[m]+0.000001)i.splice(d,0,l),s=i,r=!0}if(!r)break}return s}function et(t,n){if(!n)return[];let e=new Float64Array(n*n);for(let h=0;he[h*n+c])c=p;s[h]=c,a[h]=e[h*n+c]}let r=Array.from({length:n},(h,c)=>[c]),l=new Float64Array(e),i=new Float64Array(n).fill(1);for(let h=0;ha[c])c=f;let p=s[c];if(a[c]<=0)break;if(pd[m])m=f;s[c]=m,a[c]=d[m];for(let f=0;fe[f*n+g])g=x;s[f]=g,a[f]=e[f*n+g]}if(d[f]>a[f])s[f]=c,a[f]=d[f]}}let u=[];for(let h=0;hc-p));return u}function on(t){if(!t.length)return[];let n=H(t.map((e)=>e[3]-e[1]));return t.map((e,o)=>[z((e[1]+e[3])/2/Math.max(n*0.5,0.001)),e[0],o]).sort((e,o)=>e[0]-o[0]||e[1]-o[1]).map((e)=>e[2])}function gt(t){let n=(o,s)=>{let a=o.map((c)=>s?c[1]:c[0]),r=o.map((c)=>s?c[3]:c[2]),l=a.map((c,p)=>p).sort((c,p)=>a[c]-a[p]),i=r[l[0]],u=0,h=-1;for(let c=1;cu)u=p,h=c;i=Math.max(i,r[l[c]])}return[u,h,l]},e=(o)=>{if(o.length<=1)return[...o];let s=o.map((d)=>t[d]),[a,r,l]=n(s,1),[i,u,h]=n(s,0);if(r<0&&u<0)return on(s).map((d)=>o[d]);let[c,p]=a>=i?[r,l]:[u,h];return e(p.slice(0,c).map((d)=>o[d])).concat(e(p.slice(c).map((d)=>o[d])))};return e(t.map((o,s)=>s))}function sn(t,n=1){if(!t.length)return[];let e=H(t.map((a)=>a[3]-a[1])),o=(a,r)=>{let l=a.map((d)=>r?d[1]:d[0]),i=a.map((d)=>r?d[3]:d[2]),u=l.map((d,m)=>m).sort((d,m)=>l[d]-l[m]),h=i[u[0]],c=0,p=-1;for(let d=1;dc)c=m,p=d;h=Math.max(h,i[u[d]])}return[c,p,u]},s=(a)=>{let r=a.map((l)=>t[l]);if(a.length>1){let[l,i,u]=o(r,1),[h,c,p]=o(r,0),[d,m,f]=l>=h?[l,i,u]:[h,c,p];if(m>=0&&d>=n*e)return s(f.slice(0,m).map((g)=>a[g])).concat(s(f.slice(m).map((g)=>a[g])))}return[gt(r).map((l)=>a[l])]};return s(t.map((a,r)=>r))}function an(t,n,e,o){let s=e.length;if(s<=1)return Array.from({length:s},(u,h)=>h);let a=et(n,s),r=a.map((u)=>{let h=!1;if(o){let d=new Float64Array(F.length);for(let f of u)for(let g=0;gd[m])m=f;h=Ct.has(m)}let c=u.map((d)=>e[d]);return(h?on(c):gt(c)).map((d)=>u[d])}),l=a.length,i=new Float64Array(l*l);for(let u=0;ur[u])}async function Yn(t){let n=new DecompressionStream("deflate-raw"),e=new Blob([t]).stream().pipeThrough(n);return new Uint8Array(await new Response(e).arrayBuffer())}async function Zn(t){let n=new DataView(t.buffer,t.byteOffset,t.byteLength);if(n.getUint32(0,!0)!==67324752)throw Error("lm file is not an .npz (zip) archive");let e=-1;for(let r=t.length-22;r>=Math.max(0,t.length-22-65536);r--)if(n.getUint32(r,!0)===101010256){e=r;break}if(e<0)throw Error("lm file: no zip central directory");let o=n.getUint16(e+10,!0),s=n.getUint32(e+16,!0),a=new Map;for(let r=0;rparseInt(h,10)).filter((h)=>!Number.isNaN(h));o+=s;let i=l.reduce((h,c)=>h*c,1);if(r==="|u1")return{descr:r,shape:l,data:t.slice(o)};let u=t.slice(o);if(r==="Jn(n.get(c)).data,o=new W;if(o.order=Number(e("order")[0]),o.vocabSize=Number(e("vocab_size")[0]),o.bits=n.has("bits")?Number(e("bits")[0]):11,o.order*o.bits>61)throw Error(`order ${o.order} x ${o.bits} bits do not fit a key`);let s=(c)=>{let p=0;for(let x of c)p+=x.length;let d=new Float64Array(p),m=new Float64Array(p),f=new Float64Array(p),g=0;for(let x of c){for(let A=0;A>26n),m[g+A]=Number(x[A]&0x3ffffffn);g+=x.length}return{hi:d,lo:m}},a=(c)=>BigInt(c)<{let m=c.reduce((w,M)=>w+M.length,0),f=new Float64Array(m),g=new Float64Array(m),x=new Float64Array(m),A=0;for(let w=0;w>26n),g[A]=Number(_&0x3ffffffn),x[A]=p[w][k],A++}}return{hi:f,lo:g,vs:x}};return o.p=h(r,l,a),o.h=h(i,u,a),o.hb=u,o.ikcache=new Map,o}get maxLogp(){if(this._maxLogp===void 0){let t=-Math.log(this.vocabSize);for(let e=0;et)t=this.p.vs[e];let n=0;for(let e of this.hb){let o=-1/0;for(let s=0;so)o=e[s];if(o>0)n+=o}this._maxLogp=t+n}return this._maxLogp}static#t(t,n,e){let o=0,s=t.hi.length;while(o>1,r=t.hi[a];if(r>s,c=u&(a<BigInt(g)<>26n),w=Number(x&0x3ffffffn),M=W.#t(this.h,A,w);if(!W.#n(this.h,M,A,w))break;d=g}let m=0,f=null;for(let g=d;g>=0;g--){let x=h&(a<>26n),M=Number(A&0x3ffffffn),I=W.#t(this.p,w,M);if(W.#n(this.p,I,w,M)){f=m+this.p.vs[I];break}let k=x|p(g),_=W.#t(this.h,Number(k>>26n),Number(k&0x3ffffffn));m+=W.#n(this.h,_,Number(k>>26n),Number(k&0x3ffffffn))?this.h.vs[_]:0}if(f===null)f=m-r;if(n[i]=f,l.size<1e6)l.set(u,f)}return n}}var K=(t,n)=>{if(t===-1/0)return n;if(n===-1/0)return t;let e=t>n?t:n;return e+Math.log(Math.exp(t-e)+Math.exp(n-e))};function rn(t,n,e,o,s=0.5,a=1.5,r=8,l=0.999,i=0.001){let u=BigInt(o.bits),h=(1n<d){p=new Map([...p].map(([y,v])=>[y,[K(v[0],v[1])+M,-1/0,v[2],v[3],v[4]]]));continue}let I=new Map,k=(y,v,T,j,S,P)=>{let N=I.get(y);if(N===void 0)I.set(y,[v,T,j,S,P]);else I.set(y,[K(N[0],v),K(N[1],T),N[2],N[3],N[4]])},_=[];for(let y=0;y=m)_.push([v,T])}for(let[y,v]of p){let T=y.length?Number(y.slice(y.lastIndexOf(",")+1)):null;k(y,K(v[0],v[1])+M,-1/0,v[2],v[3],v[4]);for(let[j,S]of _)if(j===T)k(y,-1/0,v[1]+S,v[2],v[3],v[4])}let E=p.size>=r?Math.min(...[...I.values()].map((y)=>K(y[0],y[1])+y[2])):-1/0,C=a+s*o.maxLogp,L=[];for(let[y,v]of p){let T=K(v[0],v[1]),j=y.length?Number(y.slice(y.lastIndexOf(",")+1)):null;for(let[S,P]of _){let N=S===j?v[0]+P:T+P;if(N===-1/0)continue;let U=y?`${y},${S}`:`${S}`;if(I.has(U))k(U,-1/0,N,v[2],v[3],v[4]);else if(N+v[2]+C>=E-0.000000001)L.push([y,S,N,v[2],v[3],v[4]])}}let R=L.length?o.logpKeys(L.map((y)=>y[5]<{k(y?`${y},${v}`:`${v}`,-1/0,T,j+s*R[N]+a,[...S,w],(P<K(v[1][0],v[1][1])+v[1][2]-(K(y[1][0],y[1][1])+y[1][2])).slice(0,r))}let g=null,x=-1/0;for(let[w,M]of p){let I=K(M[0],M[1])+M[2];if(I>x)x=I,g=w}return[g?g.split(",").filter(Boolean).map(Number):[],g?p.get(g)[3]:[]]}var Qn=0.5,Bt=0.9,te=0.1,ne=1,ee=2,oe=4,se=["mathcls.onnx","math_enc.onnx","math_dec_init.onnx","math_dec_step.onnx"];function ae(t){let n=[],e=[],o=!1;for(let s of t)if(s==="$"){if(o)n.push("$"+e.join(" ")+"$"),e.length=0;o=!o}else if(o)e.push(s);else n.push(s);if(o&&e.length)n.push("$"+e.join(" ")+"$");return n.join("").split(/\s+/).filter(Boolean).join(" ")}var wt=(t,n)=>{if(!t.inputNames)return n;let e={};for(let o in n)if(t.inputNames.includes(o))e[o]=n[o];return e};class xt{constructor(t,n,e){this.Tensor=t,this.cls=n.cls,this.enc=n.enc,this.init=n.init,this.step=n.step;let o=e.config;this.height=o.height,this.maxTokens=o.max_tokens,this.layers=o.dec_layers,this.heads=o.dec_heads,this.headDim=o.channels/o.dec_heads,this.itos=["","","","",...e.tokens]}static async load(t){let n;try{n=await t.json("math_meta.json")}catch{return null}let e={};for(let l of se)e[l]=await t.session(l);let{"mathcls.onnx":o,"math_enc.onnx":s,"math_dec_init.onnx":a,"math_dec_step.onnx":r}=e;return new xt(t.Tensor,{cls:o,enc:s,init:a,step:r},n)}async flags(t,n=64){let e=Array(t.length).fill(!1);for(let o of nt(t.map((s)=>s.w),n)){let s=o.map((h)=>t[h]),{arr:a,w:r,widths:l}=tt(s),i=s[0].ink.length/s[0].w,{p:u}=await this.cls.run(wt(this.cls,{x:new this.Tensor("float32",a,[o.length,1,i,r]),widths:new this.Tensor("int64",l,[o.length])}));o.forEach((h,c)=>e[h]=u.data[c]>Qn)}return e}async read(t,n,e=64){let o=n.map((a)=>rt(t,a,this.height)),s=o.map(()=>({text:"",conf:0}));for(let a of nt(o.map((r)=>r.w),e,4,64,655360)){let r=a.map((k)=>o[k]),{arr:l,w:i,widths:u}=tt(r),h=a.length,c=this.Tensor,{memory:p,mask:d}=await this.enc.run(wt(this.enc,{x:new c("float32",l,[h,1,this.height,i]),widths:new c("int64",u,[h])})),{cross_k:m,cross_v:f}=await this.init.run(wt(this.init,{memory:p})),g={data:new Float32Array(0),dims:[this.layers,h,this.heads,0,this.headDim]},x={data:new Float32Array(0),dims:g.dims},A=new BigInt64Array(h).fill(BigInt(ne)),w=Array.from({length:h},()=>[]),M=Array.from({length:h},()=>[]),I=new Uint8Array(h);for(let k=0;kT)T=U,j=N}if(A[y]=BigInt(j),I[y])continue;let S=0;for(let N=0;N=8&&M[y].reduce((N,U)=>N+U,0)/M[y].length=oe)w[y].push(j)}if(I.every(Boolean))break}a.forEach((k,_)=>{s[k]={text:ae(w[_].map((E)=>this.itos[E])),conf:M[_].length?M[_].reduce((E,C)=>E+C,0)/M[_].length:0}})}return s}}var re=F.indexOf("Page-Header"),ie=F.indexOf("Page-Footer"),ce=F.indexOf("Section-Header"),le=F.indexOf("List-Group"),cn=F.indexOf("Table"),he=/^\$[^$]+\$$/,fe=/^\s*([•\-–▪◦*·→]|\(?\d{1,3}[.)]|\(?[a-zA-Z][.)])(\s|$)/,Mt=(t)=>z(t*10)/10,un=(t)=>t.replace(/&/g,"&").replace(//g,">"),ln=(t)=>{let n=t.codePointAt(0);return n>=12288&&n<=12543||n>=13312&&n<=40959||n>=63744&&n<=64255||n>=65280&&n<=65519||n>=131072&&n<=195103},ue=(t)=>String.fromCodePoint(t.codePointAt(0)),pe=(t)=>t.length>1&&t.charCodeAt(t.length-1)>=56320&&t.charCodeAt(t.length-1)<=57343?t.slice(-2):t.slice(-1),hn=(t)=>/\p{L}/u.test(t),me=(t)=>/\p{Ll}/u.test(t);function St(t){let n="";for(let e of t){if(e=e.trim(),!e)continue;let o=ue(e);if(n.length>1&&n.endsWith("-")&&hn(n[n.length-2])&&hn(o)&&me(o))n=n.slice(0,-1)+e;else if(n&&ln(pe(n))&&ln(o))n+=e;else n=n?n+" "+e:e}return n}function pn(t,n,e){let o=[];for(let s of t){let a=o[o.length-1];if(a&&n[a[a.length-1]*e+s]>0)a.push(s);else o.push([s])}return o}var de=(t)=>t.reduce((n,e)=>n+e,0)/t.length;function ge(t){let n=t.map((s)=>(s[1]+s[3])/2),e=H(t.map((s)=>s[3]-s[1])),o=[];for(let s of n.map((a,r)=>r).sort((a,r)=>n[a]-n[r])){let a=o[o.length-1];if(a&&Math.abs(n[s]-de(a.map((r)=>n[r])))<0.5*e)a.push(s);else o.push([s])}return o.map((s)=>s.slice().sort((a,r)=>t[a][0]-t[r][0]))}function we(t,n){if(t.length<3)return t;let e=H(n.map((l)=>l[3]-l[1])),o=t.slice(0,-1).map((l,i)=>{let u=t[i+1];return Math.min(...u.map((h)=>n[h][1]))-Math.max(...l.map((h)=>n[h][3]))}),s=H(o),a=[t[0].slice()],r=t[0];for(let l=0;l{let e=0,o=t.length;while(e>1;if(t[s]>n)o=s;else e=s+1}return e};function Nt(t,n){let e=ge(t),o=Math.max(...t.map((h)=>h[2]))-Math.min(...t.map((h)=>h[0]));if(e.length>2&&e[0].length===1&&Math.max(...e.map((h)=>h.length))>1&&t[e[0][0]][2]-t[e[0][0]][0]>0.6*o){let h=t.map((c,p)=>p).filter((c)=>c!==e[0][0]);return n[e[0][0]]+` +import{InferenceSession as Je,Tensor as Qe,env as In}from"onnxruntime-web";function z(t){let n=Math.floor(t),e=t-n;if(e>0.5)return n+1;if(e<0.5)return n;return n%2===0?n:n+1}var G=(t,n,e)=>te?e:t,H=(t)=>{if(!t.length)return NaN;let n=[...t].sort((o,s)=>o-s),e=n.length>>1;return n.length%2?n[e]:(n[e-1]+n[e])/2};function Kt(t,n,e){let o=[];if(e==="area"&&n0)u.push([i,p])}o.push(u)}return o}let s=t/n;for(let a=0;at-1)u=t-1;o.push(l===u||c<=0?[[l,1]]:[[l,1-c],[u,c]])}return o}function X(t,n,e,o,s,a="linear"){if(o===n&&s===e)return t;let r=Kt(n,o,a),l=Kt(e,s,a),c=new Float64Array(o*e);for(let h=0;h{if(f)w=w<0?0:w>=s?s-1:w,M=M<0?0:M>=a?a-1:M;else if(w<0||w>=s||M<0||M>=a)return 0;return o[M*s+w]},x=new o.constructor(r*l),A=x instanceof Uint8Array;for(let w=0;w0){let A=p[--g],w=A/e|0,M=A-w*e;if(x.area++,Mx.x1)x.x1=M;let I=(w+0.5)*_t;if(x.sumTop+=I-l[A],x.sumBot+=I+c[A],x.sumSc+=h[A],M>0&&u[A-1]===0&&h[A-1]>o)u[A-1]=f,p[g++]=A-1;if(Mo)u[A+1]=f,p[g++]=A+1;if(w>0&&u[A-e]===0&&h[A-e]>o)u[A-e]=f,p[g++]=A-e;if(wo)u[A+e]=f,p[g++]=A+e}i.push(x)}let d=[];for(let m=1;m{let l=0,c=256;while(l>1;if(o[u]>r)c=u;else l=u+1}return l};return e.map((r)=>{let l=r*(n-1),c=Math.floor(l),u=l-c,h=a(c),i=a(Math.min(c+1,n-1)),p=i-h;return u>=0.5?i-p*(1-u):h+p*u})}function Tt(t,n){let{height:e,width:o}=t,s=n[0],a=n[1],r=n[2],l=n[3],c=Math.max(0,Math.trunc(a)),u=Math.min(e,Math.trunc(l)+1),h=Math.max(0,Math.trunc(s)),i=Math.min(o,Math.trunc(r)+1);if(u<=c||i<=h)return!1;let p=new Int32Array(256),d=0;for(let x=c;x2*(f-m)+8}function rt(t,n,e=jn,o=4096,s=1,a=null){let r=(s*(1+2*Dn)-1)/2;e=e*s;let[l,c,u,h]=n,i=Math.max(1,h-c),p=l-at*i,d=u+at*i,m=c-r*i,f=h+r*i,{height:g,width:x}=t,A=Math.floor(p),w=Math.floor(m),M=Math.ceil(d),I=Math.ceil(f),_=Math.max(1,M-A),k=Math.max(1,I-w);if(a===null)a=Tt(t,n);let E=new Uint8Array(k*_).fill(a?0:255),S=Math.max(0,A),L=Math.max(0,w),R=Math.min(x,M),y=Math.min(g,I);if(R>S&&y>L)for(let B=L;Be?"area":"linear"),j=new Float32Array(T.length);if(a)for(let B=0;Ba.w));e=Math.ceil(e/Et)*Et;let o=new Float32Array(t.length*n*e),s=new BigInt64Array(t.length);return t.forEach((a,r)=>{for(let l=0;lc).sort((l,c)=>t[l]-t[c]),r=[];for(let l of a){let c=r[r.length-1];if(c&&c.length{let e=0,o=t.length/2;while(e>1;if(t[s*2+1]q(Fn,t.codePointAt(0))||q(Pn,t.codePointAt(0)),Zt=(t)=>q(Yt,t.codePointAt(0)),Jt=(t)=>q(Yt,t.codePointAt(0))||q(Un,t.codePointAt(0)),Qt=(t)=>q(Hn,t.codePointAt(0)),tn=(t)=>q(Gn,t.codePointAt(0)),Wn=new Int32Array([48,57,178,179,185,185,1632,1641,1776,1785,1984,1993,2406,2415,2534,2543,2662,2671,2790,2799,2918,2927,3046,3055,3174,3183,3302,3311,3430,3439,3558,3567,3664,3673,3792,3801,3872,3881,4160,4169,4240,4249,4969,4977,6112,6121,6160,6169,6470,6479,6608,6618,6784,6793,6800,6809,6992,7001,7088,7097,7232,7241,7248,7257,8304,8304,8308,8313,8320,8329,9312,9320,9332,9340,9352,9360,9450,9450,9461,9469,9471,9471,10102,10110,10112,10120,10122,10130,42528,42537,43216,43225,43264,43273,43472,43481,43504,43513,43600,43609,44016,44025,65296,65305,66720,66729,68160,68163,68912,68921,68928,68937,69216,69224,69714,69722,69734,69743,69872,69881,69942,69951,70096,70105,70384,70393,70736,70745,70864,70873,71248,71257,71360,71369,71376,71395,71472,71481,71904,71913,72016,72025,72688,72697,72784,72793,73040,73049,73120,73129,73552,73561,90416,90425,92768,92777,92864,92873,93008,93017,93552,93561,118000,118009,120782,120831,123200,123209,123632,123641,124144,124153,124401,124410,125264,125273,127232,127242,130032,130041]),Lt=(t)=>q(Wn,t.codePointAt(0));var nn=16,F=["Text","Section-Header","Page-Header","Page-Footer","List-Group","Table","Caption","Footnote","Table-Of-Contents","Form"],St=new Set(["Table","Form","Table-Of-Contents"].map((t)=>F.indexOf(t))),Vn=".!?:;。!?:;.",Kn=(t)=>!!t&&[...t].every(Lt),Xn=(t)=>t!==t.toLowerCase()&&t===t.toUpperCase(),qn=(t)=>{let n=0;for(let e of t)n+=Qt(e)?2:1;return n};function en(t,n,e,o){let s=t.length,a=new Float32Array(s*nn);if(!s)return a;let r=H(t.map((l)=>Math.max(l[3]-l[1],0.001)));for(let l=0;l3),a[m+13]=Number(f.endsWith("-")),a[m+14]=Number(Vn.includes(f[f.length-1])),a[m+15]=Number(Xn(f[0]))}return a}var dt=(t)=>t>=0?-Math.log1p(Math.exp(-t)):t-Math.log1p(Math.exp(t));function Ct(t,n,e=4){if(n<=1)return Array.from({length:n},(a,r)=>r);let o=new Float64Array(n);for(let a=0;ar).sort((a,r)=>o[a]-o[r]);for(let a=0;af!==l),u=c.map((f)=>dt(t[f*n+l])),h=c.map((f)=>dt(t[l*n+f])),i=new Float64Array(n),p=0;for(let f=1;f=0;f--)i[f]+=p+=h[f];let d=0;for(let f=1;fi[d])d=f;let m=s.indexOf(l);if(i[d]>i[m]+0.000001)c.splice(d,0,l),s=c,r=!0}if(!r)break}return s}function et(t,n){if(!n)return[];let e=new Float64Array(n*n);for(let h=0;he[h*n+i])i=p;s[h]=i,a[h]=e[h*n+i]}let r=Array.from({length:n},(h,i)=>[i]),l=new Float64Array(e),c=new Float64Array(n).fill(1);for(let h=0;ha[i])i=f;let p=s[i];if(a[i]<=0)break;if(pd[m])m=f;s[i]=m,a[i]=d[m];for(let f=0;fe[f*n+g])g=x;s[f]=g,a[f]=e[f*n+g]}if(d[f]>a[f])s[f]=i,a[f]=d[f]}}let u=[];for(let h=0;hi-p));return u}function on(t){if(!t.length)return[];let n=H(t.map((e)=>e[3]-e[1]));return t.map((e,o)=>[z((e[1]+e[3])/2/Math.max(n*0.5,0.001)),e[0],o]).sort((e,o)=>e[0]-o[0]||e[1]-o[1]).map((e)=>e[2])}function gt(t){let n=(o,s)=>{let a=o.map((i)=>s?i[1]:i[0]),r=o.map((i)=>s?i[3]:i[2]),l=a.map((i,p)=>p).sort((i,p)=>a[i]-a[p]),c=r[l[0]],u=0,h=-1;for(let i=1;iu)u=p,h=i;c=Math.max(c,r[l[i]])}return[u,h,l]},e=(o)=>{if(o.length<=1)return[...o];let s=o.map((d)=>t[d]),[a,r,l]=n(s,1),[c,u,h]=n(s,0);if(r<0&&u<0)return on(s).map((d)=>o[d]);let[i,p]=a>=c?[r,l]:[u,h];return e(p.slice(0,i).map((d)=>o[d])).concat(e(p.slice(i).map((d)=>o[d])))};return e(t.map((o,s)=>s))}function sn(t,n=1){if(!t.length)return[];let e=H(t.map((a)=>a[3]-a[1])),o=(a,r)=>{let l=a.map((d)=>r?d[1]:d[0]),c=a.map((d)=>r?d[3]:d[2]),u=l.map((d,m)=>m).sort((d,m)=>l[d]-l[m]),h=c[u[0]],i=0,p=-1;for(let d=1;di)i=m,p=d;h=Math.max(h,c[u[d]])}return[i,p,u]},s=(a)=>{let r=a.map((l)=>t[l]);if(a.length>1){let[l,c,u]=o(r,1),[h,i,p]=o(r,0),[d,m,f]=l>=h?[l,c,u]:[h,i,p];if(m>=0&&d>=n*e)return s(f.slice(0,m).map((g)=>a[g])).concat(s(f.slice(m).map((g)=>a[g])))}return[gt(r).map((l)=>a[l])]};return s(t.map((a,r)=>r))}function an(t,n,e,o){let s=e.length;if(s<=1)return Array.from({length:s},(u,h)=>h);let a=et(n,s),r=a.map((u)=>{let h=!1;if(o){let d=new Float64Array(F.length);for(let f of u)for(let g=0;gd[m])m=f;h=St.has(m)}let i=u.map((d)=>e[d]);return(h?on(i):gt(i)).map((d)=>u[d])}),l=a.length,c=new Float64Array(l*l);for(let u=0;ur[u])}async function Yn(t){let n=new DecompressionStream("deflate-raw"),e=new Blob([t]).stream().pipeThrough(n);return new Uint8Array(await new Response(e).arrayBuffer())}async function Zn(t){let n=new DataView(t.buffer,t.byteOffset,t.byteLength);if(n.getUint32(0,!0)!==67324752)throw Error("lm file is not an .npz (zip) archive");let e=-1;for(let r=t.length-22;r>=Math.max(0,t.length-22-65536);r--)if(n.getUint32(r,!0)===101010256){e=r;break}if(e<0)throw Error("lm file: no zip central directory");let o=n.getUint16(e+10,!0),s=n.getUint32(e+16,!0),a=new Map;for(let r=0;rparseInt(h,10)).filter((h)=>!Number.isNaN(h));o+=s;let c=l.reduce((h,i)=>h*i,1);if(r==="|u1")return{descr:r,shape:l,data:t.slice(o)};let u=t.slice(o);if(r==="Jn(n.get(i)).data,o=new W;if(o.order=Number(e("order")[0]),o.vocabSize=Number(e("vocab_size")[0]),o.bits=n.has("bits")?Number(e("bits")[0]):11,o.order*o.bits>61)throw Error(`order ${o.order} x ${o.bits} bits do not fit a key`);let s=(i)=>{let p=0;for(let x of i)p+=x.length;let d=new Float64Array(p),m=new Float64Array(p),f=new Float64Array(p),g=0;for(let x of i){for(let A=0;A>26n),m[g+A]=Number(x[A]&0x3ffffffn);g+=x.length}return{hi:d,lo:m}},a=(i)=>BigInt(i)<{let m=i.reduce((w,M)=>w+M.length,0),f=new Float64Array(m),g=new Float64Array(m),x=new Float64Array(m),A=0;for(let w=0;w>26n),g[A]=Number(k&0x3ffffffn),x[A]=p[w][_],A++}}return{hi:f,lo:g,vs:x}};return o.p=h(r,l,a),o.h=h(c,u,a),o.hb=u,o.ikcache=new Map,o}get maxLogp(){if(this._maxLogp===void 0){let t=-Math.log(this.vocabSize);for(let e=0;et)t=this.p.vs[e];let n=0;for(let e of this.hb){let o=-1/0;for(let s=0;so)o=e[s];if(o>0)n+=o}this._maxLogp=t+n}return this._maxLogp}static#t(t,n,e){let o=0,s=t.hi.length;while(o>1,r=t.hi[a];if(r>s,i=u&(a<BigInt(g)<>26n),w=Number(x&0x3ffffffn),M=W.#t(this.h,A,w);if(!W.#n(this.h,M,A,w))break;d=g}let m=0,f=null;for(let g=d;g>=0;g--){let x=h&(a<>26n),M=Number(A&0x3ffffffn),I=W.#t(this.p,w,M);if(W.#n(this.p,I,w,M)){f=m+this.p.vs[I];break}let _=x|p(g),k=W.#t(this.h,Number(_>>26n),Number(_&0x3ffffffn));m+=W.#n(this.h,k,Number(_>>26n),Number(_&0x3ffffffn))?this.h.vs[k]:0}if(f===null)f=m-r;if(n[c]=f,l.size<1e6)l.set(u,f)}return n}}var K=(t,n)=>{if(t===-1/0)return n;if(n===-1/0)return t;let e=t>n?t:n;return e+Math.log(Math.exp(t-e)+Math.exp(n-e))};function rn(t,n,e,o,s=0.5,a=1.5,r=8,l=0.999,c=0.001){let u=BigInt(o.bits),h=(1n<d){p=new Map([...p].map(([y,v])=>[y,[K(v[0],v[1])+M,-1/0,v[2],v[3],v[4]]]));continue}let I=new Map,_=(y,v,T,j,B,P)=>{let N=I.get(y);if(N===void 0)I.set(y,[v,T,j,B,P]);else I.set(y,[K(N[0],v),K(N[1],T),N[2],N[3],N[4]])},k=[];for(let y=0;y=m)k.push([v,T])}for(let[y,v]of p){let T=y.length?Number(y.slice(y.lastIndexOf(",")+1)):null;_(y,K(v[0],v[1])+M,-1/0,v[2],v[3],v[4]);for(let[j,B]of k)if(j===T)_(y,-1/0,v[1]+B,v[2],v[3],v[4])}let E=p.size>=r?Math.min(...[...I.values()].map((y)=>K(y[0],y[1])+y[2])):-1/0,S=a+s*o.maxLogp,L=[];for(let[y,v]of p){let T=K(v[0],v[1]),j=y.length?Number(y.slice(y.lastIndexOf(",")+1)):null;for(let[B,P]of k){let N=B===j?v[0]+P:T+P;if(N===-1/0)continue;let U=y?`${y},${B}`:`${B}`;if(I.has(U))_(U,-1/0,N,v[2],v[3],v[4]);else if(N+v[2]+S>=E-0.000000001)L.push([y,B,N,v[2],v[3],v[4]])}}let R=L.length?o.logpKeys(L.map((y)=>y[5]<{_(y?`${y},${v}`:`${v}`,-1/0,T,j+s*R[N]+a,[...B,w],(P<K(v[1][0],v[1][1])+v[1][2]-(K(y[1][0],y[1][1])+y[1][2])).slice(0,r))}let g=null,x=-1/0;for(let[w,M]of p){let I=K(M[0],M[1])+M[2];if(I>x)x=I,g=w}return[g?g.split(",").filter(Boolean).map(Number):[],g?p.get(g)[3]:[]]}var Qn=0.5,$t=0.9,te=0.1,ne=1,ee=2,oe=4,se=["mathcls.onnx","math_enc.onnx","math_dec_init.onnx","math_dec_step.onnx"];function ae(t){let n=[],e=[],o=!1;for(let s of t)if(s==="$"){if(o)n.push("$"+e.join(" ")+"$"),e.length=0;o=!o}else if(o)e.push(s);else n.push(s);if(o&&e.length)n.push("$"+e.join(" ")+"$");return n.join("").split(/\s+/).filter(Boolean).join(" ")}var wt=(t,n)=>{if(!t.inputNames)return n;let e={};for(let o in n)if(t.inputNames.includes(o))e[o]=n[o];return e};class xt{constructor(t,n,e){this.Tensor=t,this.cls=n.cls,this.enc=n.enc,this.init=n.init,this.step=n.step;let o=e.config;this.height=o.height,this.maxTokens=o.max_tokens,this.layers=o.dec_layers,this.heads=o.dec_heads,this.headDim=o.channels/o.dec_heads,this.itos=["","","","",...e.tokens]}static async load(t){let n;try{n=await t.json("math_meta.json")}catch{return null}let e={};for(let l of se)e[l]=await t.session(l);let{"mathcls.onnx":o,"math_enc.onnx":s,"math_dec_init.onnx":a,"math_dec_step.onnx":r}=e;return new xt(t.Tensor,{cls:o,enc:s,init:a,step:r},n)}async flags(t,n=64){let e=Array(t.length).fill(!1);for(let o of nt(t.map((s)=>s.w),n)){let s=o.map((h)=>t[h]),{arr:a,w:r,widths:l}=tt(s),c=s[0].ink.length/s[0].w,{p:u}=await this.cls.run(wt(this.cls,{x:new this.Tensor("float32",a,[o.length,1,c,r]),widths:new this.Tensor("int64",l,[o.length])}));o.forEach((h,i)=>e[h]=u.data[i]>Qn)}return e}async read(t,n,e=64){let o=n.map((a)=>rt(t,a,this.height)),s=o.map(()=>({text:"",conf:0}));for(let a of nt(o.map((r)=>r.w),e,4,64,655360)){let r=a.map((_)=>o[_]),{arr:l,w:c,widths:u}=tt(r),h=a.length,i=this.Tensor,{memory:p,mask:d}=await this.enc.run(wt(this.enc,{x:new i("float32",l,[h,1,this.height,c]),widths:new i("int64",u,[h])})),{cross_k:m,cross_v:f}=await this.init.run(wt(this.init,{memory:p})),g={data:new Float32Array(0),dims:[this.layers,h,this.heads,0,this.headDim]},x={data:new Float32Array(0),dims:g.dims},A=new BigInt64Array(h).fill(BigInt(ne)),w=Array.from({length:h},()=>[]),M=Array.from({length:h},()=>[]),I=new Uint8Array(h);for(let _=0;_T)T=U,j=N}if(A[y]=BigInt(j),I[y])continue;let B=0;for(let N=0;N=8&&M[y].reduce((N,U)=>N+U,0)/M[y].length<$t-te)I[y]=!0;else if(j>=oe)w[y].push(j)}if(I.every(Boolean))break}a.forEach((_,k)=>{s[_]={text:ae(w[k].map((E)=>this.itos[E])),conf:M[k].length?M[k].reduce((E,S)=>E+S,0)/M[k].length:0}})}return s}}var re=F.indexOf("Page-Header"),ie=F.indexOf("Page-Footer"),ce=F.indexOf("Section-Header"),le=F.indexOf("List-Group"),cn=F.indexOf("Table"),he=/^\$[^$]+\$$/,fe=/^\s*([•\-–▪◦*·→]|\(?\d{1,3}[.)]|\(?[a-zA-Z][.)])(\s|$)/,Mt=(t)=>z(t*10)/10,un=(t)=>t.replace(/&/g,"&").replace(//g,">"),ln=(t)=>{let n=t.codePointAt(0);return n>=12288&&n<=12543||n>=13312&&n<=40959||n>=63744&&n<=64255||n>=65280&&n<=65519||n>=131072&&n<=195103},ue=(t)=>String.fromCodePoint(t.codePointAt(0)),pe=(t)=>t.length>1&&t.charCodeAt(t.length-1)>=56320&&t.charCodeAt(t.length-1)<=57343?t.slice(-2):t.slice(-1),hn=(t)=>/\p{L}/u.test(t),me=(t)=>/\p{Ll}/u.test(t);function Bt(t){let n="";for(let e of t){if(e=e.trim(),!e)continue;let o=ue(e);if(n.length>1&&n.endsWith("-")&&hn(n[n.length-2])&&hn(o)&&me(o))n=n.slice(0,-1)+e;else if(n&&ln(pe(n))&&ln(o))n+=e;else n=n?n+" "+e:e}return n}function pn(t,n,e){let o=[];for(let s of t){let a=o[o.length-1];if(a&&n[a[a.length-1]*e+s]>0)a.push(s);else o.push([s])}return o}var de=(t)=>t.reduce((n,e)=>n+e,0)/t.length;function ge(t){let n=t.map((s)=>(s[1]+s[3])/2),e=H(t.map((s)=>s[3]-s[1])),o=[];for(let s of n.map((a,r)=>r).sort((a,r)=>n[a]-n[r])){let a=o[o.length-1];if(a&&Math.abs(n[s]-de(a.map((r)=>n[r])))<0.5*e)a.push(s);else o.push([s])}return o.map((s)=>s.slice().sort((a,r)=>t[a][0]-t[r][0]))}function we(t,n){if(t.length<3)return t;let e=H(n.map((l)=>l[3]-l[1])),o=t.slice(0,-1).map((l,c)=>{let u=t[c+1];return Math.min(...u.map((h)=>n[h][1]))-Math.max(...l.map((h)=>n[h][3]))}),s=H(o),a=[t[0].slice()],r=t[0];for(let l=0;l{let e=0,o=t.length;while(e>1;if(t[s]>n)o=s;else e=s+1}return e};function Nt(t,n){let e=ge(t),o=Math.max(...t.map((h)=>h[2]))-Math.min(...t.map((h)=>h[0]));if(e.length>2&&e[0].length===1&&Math.max(...e.map((h)=>h.length))>1&&t[e[0][0]][2]-t[e[0][0]][0]>0.6*o){let h=t.map((i,p)=>p).filter((i)=>i!==e[0][0]);return n[e[0][0]]+` -`+Nt(h.map((c)=>t[c]),h.map((c)=>n[c]))}let s=Math.max(...e.map((h)=>h.length)),a=e.filter((h)=>h.length===s),r=we(e,t),l=Array.from({length:s},(h,c)=>[H(a.map((p)=>t[p[c]][0])),H(a.map((p)=>t[p[c]][2]))]),i=[-1/0];for(let h=0;h"];for(let h=0;h1?"th":"td",p=new Map;for(let f of r[h].slice().sort((g,x)=>t[g][1]-t[x][1]||t[g][0]-t[x][0])){let[g,,x]=t[f],A=fn(i,g)-1,w=fn(i,x)-1,M=[];for(let _=Math.max(A,0);_<=Math.min(w,s-1);_++)if(Math.min(x,l[_][1])-Math.max(g,l[_][0])>0.5*(l[_][1]-l[_][0]))M.push(_);if(!M.length)M=[Math.min(Math.max(A,0),s-1)];let I=M[0],k=p.get(I);p.set(I,{n:k?Math.max(k.n,M.length):M.length,text:k?k.text+" "+n[f]:n[f]})}let d=[],m=0;while(m1?` colspan="${f.n}"`:""}>${un(f.text)}`),m+=f.n;else d.push(`<${c}>`),m+=1}u.push(""+d.join("")+"")}return u.push(""),u.join(` -`)}function xe(t,n,e){let o=et(n.subarray(2*e*e),e),s=0;for(let a of o){if(a.length<2)continue;let r=1/0;for(let l of a)for(let i of a)r=Math.min(r,Math.min(t[l][2],t[i][2])-Math.max(t[l][0],t[i][0]));if(r<0)s++}return s<=0.1*o.length}function Me(t,n){let e=Math.round(Math.sqrt(t.length/3)),o=n.length,s=new Float32Array(3*o*o);for(let a=0;a<3;a++)for(let r=0;r[Math.min(...w.map((M)=>t[M][0])),Math.min(...w.map((M)=>t[M][1])),Math.max(...w.map((M)=>t[M][2])),Math.max(...w.map((M)=>t[M][3]))]),r=s.map((w)=>w.slice().sort((M,I)=>t[M][1]-t[I][1]||t[M][0]-t[I][0]).map((M)=>n[M]).join(" ")),l=s.length,i=(w)=>{let M=new Float32Array(l*l);for(let I=0;IMath.min(...w.map((M)=>a[M][1])),h=(w)=>Math.min(...w.map((M)=>a[M][0])),c=et(i(0),l).sort((w,M)=>u(w)-u(M)),p=et(i(1),l).sort((w,M)=>h(w)-h(M)),d=new Map;c.forEach((w,M)=>w.forEach((I)=>d.set(I,M)));let m=new Map;p.forEach((w,M)=>w.forEach((I)=>m.set(I,M)));let f=p.map((w)=>H(w.map((M)=>(a[M][0]+a[M][2])/2))),g=H(t.map((w)=>w[3]-w[1])),x=new Map;for(let w=0;w"];for(let w=0;w1?"th":"td",I=[],k=0;while(k1?` colspan="${_.span}"`:""}>${un(_.text)}`),k+=_.span;else I.push(`<${M}>`),k+=1}A.push(""+I.join("")+"")}return A.push(""),A.join(` -`)}function mn(t,n,e){let o=t.length/e,s=0,a=-1/0;for(let r=0;ra)a=l,s=r}return s}function dn(t,n,e,o,s){let a=t.length;return pn(e,s,a).map((r)=>{let l=r.map((i)=>t[i]);return{label:F[mn(o,r,a)],bbox:[Mt(Math.min(...l.map((i)=>i[0]))),Mt(Math.min(...l.map((i)=>i[1]))),Mt(Math.max(...l.map((i)=>i[2]))),Mt(Math.max(...l.map((i)=>i[3])))],text:r.map((i)=>n[i]).join(` -`)}})}function gn(t,n,e,o,s,a={}){let{keepFurniture:r=!1,cells:l=null,tab:i=null,pictures:u=null}=a,h=t.length,c=[],p=[];for(let d of pn(e,s,h)){let m=c.length;if(Ae(c,d,t,n,o,r,l,i,h),c.length>m){let f=d.map((g)=>t[g]);p.push([Math.min(...f.map((g)=>g[0])),Math.min(...f.map((g)=>g[1])),Math.max(...f.map((g)=>g[2])),Math.max(...f.map((g)=>g[3]))])}}if(u&&u.length){let d=new Map;u.forEach(([f,g,x,A],w)=>{let M=(g+A)/2,I=p.findIndex(([_,E,C,L])=>(E+L)/2>M&&Math.min(x,C)>Math.max(f,_)),k=I===-1?c.length:I;if(!d.has(k))d.set(k,[]);d.get(k).push(`![](picture-${w})`)});let m=[];for(let f=0;f<=c.length;f++)if(m.push(...d.get(f)??[]),ft[i]),h.map((i)=>n[i]))}let s=Math.max(...e.map((h)=>h.length)),a=e.filter((h)=>h.length===s),r=we(e,t),l=Array.from({length:s},(h,i)=>[H(a.map((p)=>t[p[i]][0])),H(a.map((p)=>t[p[i]][2]))]),c=[-1/0];for(let h=0;h"];for(let h=0;h1?"th":"td",p=new Map;for(let f of r[h].slice().sort((g,x)=>t[g][1]-t[x][1]||t[g][0]-t[x][0])){let[g,,x]=t[f],A=fn(c,g)-1,w=fn(c,x)-1,M=[];for(let k=Math.max(A,0);k<=Math.min(w,s-1);k++)if(Math.min(x,l[k][1])-Math.max(g,l[k][0])>0.5*(l[k][1]-l[k][0]))M.push(k);if(!M.length)M=[Math.min(Math.max(A,0),s-1)];let I=M[0],_=p.get(I);p.set(I,{n:_?Math.max(_.n,M.length):M.length,text:_?_.text+" "+n[f]:n[f]})}let d=[],m=0;while(m1?` colspan="${f.n}"`:""}>${un(f.text)}`),m+=f.n;else d.push(`<${i}>`),m+=1}u.push(""+d.join("")+"")}return u.push(""),u.join(` +`)}function xe(t,n,e){let o=et(n.subarray(2*e*e),e),s=0;for(let a of o){if(a.length<2)continue;let r=1/0;for(let l of a)for(let c of a)r=Math.min(r,Math.min(t[l][2],t[c][2])-Math.max(t[l][0],t[c][0]));if(r<0)s++}return s<=0.1*o.length}function Me(t,n){let e=Math.round(Math.sqrt(t.length/3)),o=n.length,s=new Float32Array(3*o*o);for(let a=0;a<3;a++)for(let r=0;r[Math.min(...w.map((M)=>t[M][0])),Math.min(...w.map((M)=>t[M][1])),Math.max(...w.map((M)=>t[M][2])),Math.max(...w.map((M)=>t[M][3]))]),r=s.map((w)=>w.slice().sort((M,I)=>t[M][1]-t[I][1]||t[M][0]-t[I][0]).map((M)=>n[M]).join(" ")),l=s.length,c=(w)=>{let M=new Float32Array(l*l);for(let I=0;IMath.min(...w.map((M)=>a[M][1])),h=(w)=>Math.min(...w.map((M)=>a[M][0])),i=et(c(0),l).sort((w,M)=>u(w)-u(M)),p=et(c(1),l).sort((w,M)=>h(w)-h(M)),d=new Map;i.forEach((w,M)=>w.forEach((I)=>d.set(I,M)));let m=new Map;p.forEach((w,M)=>w.forEach((I)=>m.set(I,M)));let f=p.map((w)=>H(w.map((M)=>(a[M][0]+a[M][2])/2))),g=H(t.map((w)=>w[3]-w[1])),x=new Map;for(let w=0;w"];for(let w=0;w1?"th":"td",I=[],_=0;while(_1?` colspan="${k.span}"`:""}>${un(k.text)}`),_+=k.span;else I.push(`<${M}>`),_+=1}A.push(""+I.join("")+"")}return A.push(""),A.join(` +`)}function mn(t,n,e){let o=t.length/e,s=0,a=-1/0;for(let r=0;ra)a=l,s=r}return s}function dn(t,n,e,o,s){let a=t.length;return pn(e,s,a).map((r)=>{let l=r.map((c)=>t[c]);return{label:F[mn(o,r,a)],bbox:[Mt(Math.min(...l.map((c)=>c[0]))),Mt(Math.min(...l.map((c)=>c[1]))),Mt(Math.max(...l.map((c)=>c[2]))),Mt(Math.max(...l.map((c)=>c[3])))],text:r.map((c)=>n[c]).join(` +`)}})}function gn(t,n,e,o,s,a={}){let{keepFurniture:r=!1,cells:l=null,tab:c=null,pictures:u=null}=a,h=t.length,i=[],p=[];for(let d of pn(e,s,h)){let m=i.length;if(Ae(i,d,t,n,o,r,l,c,h),i.length>m){let f=d.map((g)=>t[g]);p.push([Math.min(...f.map((g)=>g[0])),Math.min(...f.map((g)=>g[1])),Math.max(...f.map((g)=>g[2])),Math.max(...f.map((g)=>g[3]))])}}if(u&&u.length){let d=new Map;u.forEach(([f,g,x,A],w)=>{let M=(g+A)/2,I=p.findIndex(([k,E,S,L])=>(E+L)/2>M&&Math.min(x,S)>Math.max(f,k)),_=I===-1?i.length:I;if(!d.has(_))d.set(_,[]);d.get(_).push(`![](picture-${w})`)});let m=[];for(let f=0;f<=i.length;f++)if(m.push(...d.get(f)??[]),fo[c]);if((u===re||u===ie)&&!a)return;if(h.every((c)=>he.test(c.trim()))){t.push(h.map((c)=>"$$"+c.trim().slice(1,-1)+"$$").join(` -`));return}if(u===ce)t.push("## "+St(h));else if(u===cn&&n.length>1&&l){let c=n.map((d)=>e[d]),p=Me(l,n);if(xe(c,p,n.length))t.push(ye(c,h,p,n.length));else{let d=[],m=[];for(let f of n)for(let[g,x]of r?.get(f)||[[e[f],o[f]]])d.push(g),m.push(x);t.push(Nt(d,m))}}else if(u===cn&&n.length>1){let c=[],p=[];for(let d of n)for(let[m,f]of r?.get(d)||[[e[d],o[d]]])c.push(m),p.push(f);t.push(Nt(c,p))}else if(u===le){let c=[];for(let p of h)if(!c.length||fe.test(p))c.push([p]);else c[c.length-1].push(p);t.push(c.map(St).join(` -`))}else t.push(St(h))}class ct{constructor(t){this.chars=t,this.index=new Map(t.map((n,e)=>[n,e+1])),this.hasCommands=t.some((n)=>n.length>1),this.jamo=this.index.has("ᄀ")}static fromMeta(t){if(typeof t==="string")t=JSON.parse(t);if(t.blank!==0)throw Error("only blank=0 vocabularies are supported");return new ct(t.chars)}decode(t){let n=[];for(let o of t)if(o>0&&o<=this.chars.length)n.push(this.chars[o-1]);if(this.jamo)return n.join("").normalize("NFC");if(!this.hasCommands)return n.join("");let e="";for(let o=0;o2&&s[0]==="\\"&&/^\p{L}+$/u.test(s.slice(1))&&/^\p{L}/u.test(a))e+=" "}return e}}var be=new Map([..."()[]{}<>«»‹›"].map((t,n)=>[t,")(][}{><»«›‹"[n]]));var Mn=(t)=>it(t),Rt=(t)=>{for(let n of t)if(it(n))return!0;return!1},ve=(t)=>{let n=0,e=0;for(let o of t)if(it(o))n++;else if(Zt(o))e++;return n>e};function Ie(t){let n=[];for(let e of t)if(n.length&&tn(e))n[n.length-1]+=e;else n.push(e);return n}var _e=(t)=>it(t)?"R":Jt(t)?"L":"N";function wn(t,n,e){let o=[],s=null,a=null;for(let r=0;r<=t.length;r++){let l=r{let n=String.fromCodePoint(t.codePointAt(0));return(be.get(n)??n)+t.slice(n.length)};function yn(t,n=null,e=!0){if(!Rt(t))return t;let o=Ie(t),s=o.map(_e);if(n===null?ve(t):n){let l=[],i=[...wn(s,"L",new Set(["R"])),[o.length,o.length]],u=0;for(let[h,c]of i){for(;uz(t*10)/10,He=(t)=>z(t*100)/100,Ge=(t)=>z(t*1e4)/1e4,We=new Set(".·…‥_-–—="),Ve=new Set("-–—"),Ke=new Set("•◦▪▫●○■□‣⁃∙*"),Xe=/^(?:\d{1,3}|[A-Za-z])[.)]$|^\((?:\d{1,3}|[A-Za-z]|[ivxlcIVXLC]{1,5})\)$/,qe=2.5;function Ye(t,n,e=!1,o=null){let s=n.map(()=>!0),a=t.map((i)=>i[3]-i[1]),r=t.map((i)=>i[2]-i[0]);for(let i=0;iWe.has(h))){let h=r[i]>=3*a[i],c=[...u].some((p)=>Ve.has(p));if(u.length>=3||h||!c)s[i]=!1}}for(let i=0;i0&&typeof p[0][0]==="string",m=d?" ":o;if(!e&&n[i].toks.length&&p.length&&m!==null){if(typeof n[i].toks[0][0]==="string"===d){let f=(t[i][2]+t[h][0])/2;n[h].toks=[...n[i].toks,[m,f,...n[i].toks[n[i].toks.length-1].slice(2)],...p]}}n[h]={text:`${u} ${n[h].text.trim()}`,conf:n[h].conf,toks:n[h].toks},t[h]=[Math.min(t[i][0],t[h][0]),Math.min(t[i][1],t[h][1]),Math.max(t[i][2],t[h][2]),Math.max(t[i][3],t[h][3])],s[i]=!1}let l=[];for(let i=0;it[i]),rec:l.map((i)=>n[i])}}class At{static async create(t,n={}){let e=new At;e.Tensor=t.Tensor,e.tableHeads=n.tableHeads??!1,e.furniture=n.furniture??!1;let o=await t.meta();if(e.vocab=ct.fromMeta(o.vocab),e.longSide=o.det_long_side,e.height=o.rec_height,e.window=o.rec_window??1,e.det=await t.session("det.onnx"),e.rec=await t.session(n.recInt8?"rec.int8.onnx":"rec.onnx"),e.#t=null,e.order=e.orient=null,n.order!==!1)try{e.order=await t.session("order.onnx")}catch{}if(n.orient!==!1)try{e.orient=await t.session("orient.onnx")}catch{}if(e.script=null,e.groups=new Map,e.scriptGroups=o.script_groups??ze,n.cjk!==!1){for(let s of Object.keys(o)){if(!s.startsWith("vocab_"))continue;let a=s.slice(6);try{let r=await t.session(`rec_${a}.onnx`);e.groups.set(a,{sess:r,vocab:ct.fromMeta(o[s])})}catch{}}if(e.groups.size)try{e.script=await t.session("script.onnx")}catch{e.script=null}}if(e.lms=new Map,n.lm!==!1){let s=o.lm_params??{},a=(l)=>!!l.outputNames&&["blank","topv","topi"].every((i)=>l.outputNames.includes(i)),r=async(l,i)=>{if(!a(i))return;try{let u=await W.load(await t.bytes(l==="base"?"lm.npz":`lm_${l}.npz`)),h=s[l]??{};e.lms.set(i,{lm:u,alpha:h.alpha??Re,beta:h.beta??Oe,gate:h.gate??Ne})}catch{}};await r("base",e.rec);for(let l of e.groups.keys()){let i=e.groups.get(l);if(i)await r(l,i.sess)}}if(e.math=null,n.math){if(t.json)e.math=await xt.load(t);if(!e.math)throw Error("math: true needs the math models (mathcls.onnx, math_enc.onnx, math_dec_init.onnx, math_dec_step.onnx, math_meta.json)")}return e.adaptive=n.adaptive??!0,e._pageRtl=!1,e}#t;async#n(t,n){let{x:e,ph:o,pw:s,scale:a}=Xt(t,n),{out:r}=await this.det.run({x:new this.Tensor("float32",e,[1,1,o,s])}),[,l,i,u]=r.dims;return this.#t=l>3?{logit:r.data.subarray(3*i*u,4*i*u),w:u,h:i,scale:a}:null,{boxes:qt(r.data,i,u),scale:a}}async detect(t){let{boxes:n,scale:e}=await this.#n(t,this.longSide);if(this.adaptive&&n.length>=8){let o=H(n.map((s)=>s[3]-s[1]));if(othis.longSide)({boxes:n,scale:e}=await this.#n(t,s))}}for(let o of n)o[0]=G(o[0]/e,0,t.width),o[2]=G(o[2]/e,0,t.width),o[1]=G(o[1]/e,0,t.height),o[3]=G(o[3]/e,0,t.height);return n}async detectAll(t){this.#t=null;let n=await this.detect(t),e=this.#t;if(!e)return[n,[]];return[n,Ze(e.logit,e.w,e.h,e.scale,t.width,t.height)]}async#f(t,n=64){let e=t.map(()=>"base"),o=t.map(()=>!0);for(let s of nt(t.map((a)=>a.w),n)){let{arr:a,w:r,widths:l}=tt(s.map((c)=>t[c])),{p:i}=await this.script.run({x:new this.Tensor("float32",a,[s.length,1,this.height,r]),widths:new this.Tensor("int64",l,[s.length])}),u=i.dims.length>1,h=u?i.dims[1]:1;s.forEach((c,p)=>{let d,m;if(!u){let f=i.data[p];d=f>0.5?"cjk":"base",m=Math.max(f,1-f)}else{let f=0;for(let g=1;gi.data[p*h+f])f=g;d=this.scriptGroups[f],m=i.data[p*h+f]}e[c]=this.groups.has(d)?d:"base",o[c]=m>Fe})}return{names:e,sure:o}}async recognize(t,n,e=64,o=!1){let s=this.window,a=s>1?n.map((c)=>Tt(t,c)):null,r=n.map((c,p)=>rt(t,c,this.height,4096,1,a?a[p]:null)),l=s>1?n.map((c,p)=>rt(t,c,this.height,4096,s,a?a[p]:null)):r,i=r.map(()=>({text:"",conf:0,toks:[]})),u;if(o&&this.groups.has("cjk")){let{sess:c,vocab:p}=this.groups.get("cjk");u=[[c,p,r.map((d,m)=>m),!0]]}else if(this.script&&r.length){let{names:c,sure:p}=await this.#f(r,e);u=[[this.rec,this.vocab,c.flatMap((d,m)=>d==="base"||!p[m]?[m]:[]),!1]].concat([...this.groups].map(([d,{sess:m,vocab:f}])=>[m,f,c.flatMap((g,x)=>g===d?[x]:[]),!0]))}else u=[[this.rec,this.vocab,r.map((c,p)=>p),!1]];let h=new Float64Array(r.length).fill(-1);for(let[c,p,d,m]of u){if(!d.length)continue;for(let f of nt(d.map((g)=>r[g].w),e)){let g=f.map((T)=>d[T]),x=l===r||c!==this.rec?r:l,{arr:A,w,widths:M}=tt(g.map((T)=>x[T])),I=this.lms.get(c),k=A.length/(f.length*w),_=await c.run({x:new this.Tensor("float32",A,[f.length,1,k,w]),widths:new this.Tensor("int64",M,[f.length])}),{ids:E,conf:C,lengths:L}=_,R=I&&_.blank&&_.topv&&_.topi,y=E.dims[1],v=w/Math.max(y,1);for(let T=0;TNumber(E.data[T*y+Q])),N=[];for(let D=0;DP[D]),Wt=N,J=N.length?N.reduce((D,Q)=>D+C.data[T*y+Q],0)/N.length:0;if(R&&J>=An&&JGt+(D+0.5)*v*Nn),Rn=m?ft.map((D,Q)=>[p.chars[D-1],Vt[Q]]):ft.map((D,Q)=>[D,Vt[Q]]);if(J<=h[j])continue;h[j]=J,i[j]=J>=An?{text:p.decode(ft),conf:J,toks:Rn}:{text:"",conf:J,toks:[]}}}}if(this.math&&r.length){let p=(await this.math.flags(r)).flatMap((d,m)=>d?[m]:[]);if(p.length){let d=await this.math.read(t,p.map((m)=>n[m]));p.forEach((m,f)=>{let{text:g,conf:x}=d[f];if(g.includes("$")&&x>=Bt){let A=(n[m][0]+n[m][2])/2;i[m]={text:g,conf:1,toks:[[g,A]]}}})}}return i}async readingOrder(t,n,e){if(t.length<2||!this.order)return{order:t.length?gt(t):[],layout:null};let o=en(t,e[0],e[1],n),s=t.length,a=await this.order.run({feats:new this.Tensor("float32",o,[1,s,16]),mask:new this.Tensor("bool",new Uint8Array(s).fill(1),[1,s])}),r=a.a.data,l=a.cls?a.cls.data:null;if(a.same)return{order:an(r,a.same.data,t,l),layout:{cls:l,same:a.same.data,tab:this.tableHeads&&a.tab?a.tab.data:null,classes:F}};return{order:$t(r,s),layout:null}}#e(t){return t===" "||t===this.vocab.index.get(" ")}#i(t){if(!t.length)return"";if(typeof t[0][0]==="string"){let n=t.map((e)=>e[0]).join("").split(/\s+/).filter(Boolean).join(" ");if(t[0].length===2){if(n=n.normalize("NFC"),Rt(n))n=yn(n,this._pageRtl||null)}return n}return this.vocab.decode(t.map((n)=>n[0]))}#u(t,n){let e=t.map((s)=>s[0]),o=t.map((s)=>s[2]);return t.map((s,a)=>{let r=Math.max(1,s[3]-s[1]),l=n[a].toks.filter((u)=>!this.#e(u[0])).map((u)=>u[1]),i=[];for(let u=1;u=Se)i.push((h+c)/2)}return i})}#o(t,n,e,o=[]){let s=Math.max(1,t[3]-t[1]),a=[[]],r=null,l=[...o].sort((u,h)=>u-h);for(let u of n){let h=u[1];if(!this.#e(u[0])){if(r!==null&&(h-r>e*s||l.some((p)=>r!this.#e(p[0])).map((p)=>p[1]);if(h&&c.length)i.push([[Math.max(t[0],Math.min(...c)-0.35*s),t[1],Math.min(t[2],Math.max(...c)+0.35*s),t[3]],h,u])}return i}async#p(t,n,e,o,s=!1,a=null){let r=Date.now(),l=0,i=0;for(let E of e)for(let C of E.text)if(/\p{L}/u.test(C)){if(i++,Mn(C))l++}this._pageRtl=l>i-l;let u=t[0],h=(E)=>this._pageRtl?[u-E[2],E[1],u-E[0],E[3]]:E,c=[],p=[],d=n.length?this.#u(n,e):[];n.forEach((E,C)=>{for(let[L,R,y]of this.#o(E,e[C].toks,$e,d[C]))c.push(L),p.push({text:R,conf:e[C].conf,toks:y})});let m=Ye(c,p,this._pageRtl,this.vocab.index.get(" ")??null),{boxes:f,rec:g}=m,x=g.map((E)=>E.text),{order:A,layout:w}=await this.readingOrder(f.map(h),x,t);if(s&&w){let E=sn(f);A=E.flat();let C=f.length,L=new Float32Array(C*C).fill(-1);for(let v of E)for(let T of v)for(let j of v)L[T*C+j]=1;let R=w.cls.length/C,y=w.cls.slice();for(let v of Ct)for(let T=0;T{let y=0;for(let v=1;vw.cls[R*F.length+y])y=v;return y===E});if(C.some(Boolean)){let L=[],R=[];if(f.forEach((y,v)=>{let T=C[v]?this.#o(y,g[v].toks,bn):[[y,g[v].text,g[v].toks]];for(let[j,S,P]of T)L.push(j),R.push({text:S,conf:g[v].conf,toks:P})}),L.length!==f.length)f=L,g=R,x=g.map((y)=>y.text),{order:A,layout:w}=await this.readingOrder(f.map(h),x,t)}}o.orderMs=Date.now()-r,o.totalMs=o.orientMs+o.detMs+o.recMs+o.orderMs;let M=s?"order=xycut":"order=model",I=A.map((E)=>({box:f[E].slice(0,4).map(V),text:g[E].text,conf:Ge(g[E].conf)})),k=null,_=[];if(w){_=dn(f.map(h),x,A,w.cls,w.same);for(let L of _)L.bbox=h(L.bbox).map(V);let E=new Map(f.map((L,R)=>[R,this.#o(L,g[R].toks,bn).map(([y,v])=>[h(y),v])])),C=a&&a.length;if(k=gn(f.map(h),x,A,w.cls,w.same,{keepFurniture:this.furniture,cells:E,tab:this.tableHeads?w.tab:null,pictures:C?a.map(h):null}),C)for(let L of a){let R=(L[1]+L[3])/2,y=_.findIndex((v)=>(v.bbox[1]+v.bbox[3])/2>R&&Math.min(L[2],v.bbox[2])>Math.max(L[0],v.bbox[0]));_.splice(y===-1?_.length:y,0,{label:"Picture",bbox:[V(L[0]),V(L[1]),V(L[2]),V(L[3])],text:""})}}else if(f.length<2)k=x.join(` -`);return{lines:I,md:k,blocks:_,note:M}}#c(t,n){let{width:e,height:o}=t,s=n/Math.max(o,e),a=Math.max(1,z(e*s)),r=Math.max(1,z(o*s)),l=X(t.data,e,o,a,r,"area"),i=new Uint8Array(a*r);for(let u=0;uvn+0.000001)break;a.push(x)}let r=a.map((g)=>this.#s(s,g)),l=-1,i=-1;for(let g=0;gr[l])i=l,l=g;else if(i<0||r[g]>r[i])i=g;let u=[0,a[i],a[l]],h=[],c=new Set;for(let g of u)for(let x=0;x<=8;x++){let A=g-2+x*0.5;if(!c.has(A))c.add(A),h.push(A)}let p=h[0],d=-1/0;for(let g of h){let x=this.#s(e,g);if(x>d)d=x,p=g}let m=[];for(let g=0;;g++){let x=p-0.5+g*0.1;if(x>p+0.5+0.000001)break;m.push(x)}let f=m[0];d=-1/0;for(let g of m){let x=this.#s(e,g);if(x>d)d=x,f=g}return f}#m(t,n=Ue){let e=n/Math.max(t.height,t.width);if(e>=1)return t;let o=Math.max(1,z(t.width*e)),s=Math.max(1,z(t.height*e));return{data:X(t.data,t.width,t.height,o,s,"area"),width:o,height:s}}#r(t,n){return _t(t,ut(t.width/2,t.height/2,n),"replicate")}#l(t,n,e,o){let s=ut(e/2,o/2,-n),a=[t[0],t[2],t[0],t[2]],r=[t[1],t[1],t[3],t[3]],l=a.map((u,h)=>s[0]*u+s[1]*r[h]+s[2]),i=r.map((u,h)=>s[3]*a[h]+s[4]*u+s[5]);return[V(G(Math.min(...l),0,e)),V(G(Math.min(...i),0,o)),V(G(Math.max(...l),0,e)),V(G(Math.max(...i),0,o))]}async upright(t,n=!0,e=null){let o=this.#a(t);if(e===null)e=n?await this.orientation(Math.abs(o)>=Ot?this.#r(t,o):t):0;return this.#h(t,e,o,null)}#h(t,n,e,o){let s=n===yt?1:-n;if(n===yt)t=pt(t,3);else if(n)t=pt(t,n);if(n===1||n===3||n===yt){let a=o?pt(o,s===1?3:-s):t;e=this.#a(a)}if(Math.abs(e)>=Ot)t=this.#r(t,e);else e=0;return{gray:t,turns:n,skew:e}}async orientation(t){if(!this.orient)return 0;let n=Le,{height:e,width:o}=t,s=n/Math.max(e,o),a=Math.max(1,z(e*s)),r=Math.max(1,z(o*s)),l=a===e&&r===o?t.data:X(t.data,o,e,r,a,"area"),i=new Float32Array(n*n);for(let c=0;cu.data[h])h=c;return u.data[h]>Ce?h:0}async run(t,n=!0){let e={},o=Date.now(),s=this.#m(t),a=this.#a(s),r=n?await this.orientation(Math.abs(a)>=Ot?this.#r(s,a):s):0,l=Date.now()-o,i=await this.#d(t,r,a,s);return i.timings.orientMs+=l,i}async#d(t,n,e,o){let s={},a=Date.now(),r=this.#h(t,n,e,o);t=r.gray,s.orientMs=Date.now()-a,a=Date.now();let[l,i]=await this.detectAll(t);s.detMs=Date.now()-a,a=Date.now();let u=r.turns===yt,h=await this.recognize(t,l,64,u);s.recMs=Date.now()-a;let c=await this.#p([t.width,t.height],l,h,s,u,u?null:i),p=u?0:90*r.turns,d=He(r.skew);if(r.skew){for(let m of c.lines)m.box=this.#l(m.box,r.skew,t.width,t.height);for(let m of c.blocks)m.bbox=this.#l(m.bbox,r.skew,t.width,t.height)}if(u){let m=t.height,f=(g)=>[m-g[3],g[0],m-g[1],g[2]];for(let g of c.lines)g.box=f(g.box);for(let g of c.blocks)g.bbox=f(g.bbox)}return{lines:c.lines,source:"ocr",rotation:p,skew:d,vertical:u,markdown:c.md,blocks:c.blocks,pictures:c.blocks.filter((m)=>m.label==="Picture").map((m)=>m.bbox),text:c.lines.map((m)=>m.text).join(` -`),note:c.note,timings:s}}}function Ze(t,n,e,o,s,a){let r=t.length,l=new Uint8Array(r);for(let m=0;m0?1:0;let i=new Int32Array(r),u=[],h=new Int32Array(r);for(let m=0;m0){let A=h[--g],w=A/n|0,M=A-w*n;if(Mx.x1)x.x1=M;if(wx.y1)x.y1=w;for(let I=-1;I<=1;I++){let k=w+I;if(k<0||k>=e)continue;for(let _=-1;_<=1;_++){let E=M+_;if(E<0||E>=n)continue;let C=k*n+E;if(l[C]&&!i[C])i[C]=f,h[g++]=C}}}u.push(x)}let c=2/o,p=Pe*a*s,d=[];for(let m of u){let f=[m.x0*c,m.y0*c,Math.min((m.x1+1)*c,s),Math.min((m.y1+1)*c,a)];if((f[2]-f[0])*(f[3]-f[1])>=p)d.push(f)}return d}var t1="v1.1.0";async function n1(t,n){let e=await fetch(t);if(!e.ok)throw Error(`${e.status} ${e.statusText} for ${t}`);if(!e.body||!n)return new Uint8Array(await e.arrayBuffer());let o=e.headers.has("content-length")?+e.headers.get("content-length"):null,s=e.body.getReader(),a=[],r=0;for(;;){let{done:u,value:h}=await s.read();if(u)break;a.push(h),r+=h.byteLength,n(r,o)}let l=new Uint8Array(r),i=0;for(let u of a)l.set(u,i),i+=u.byteLength;return l}async function e1(t,n,e){let o=await e(n),s=await Je.create(o,{executionProviders:["wasm"],graphOptimizationLevel:"all"});return{run:(a)=>s.run(a),inputNames:s.inputNames,outputNames:s.outputNames}}function o1(t){let n=/^([^/@:\s]+)\/([^/@:\s]+)(?:@(.+))?$/.exec(t);return n?`https://huggingface.co/${n[1]}/${n[2]}/resolve/${n[3]||t1}`:t}async function _n(t,n={}){let e=n.threads??4;if(t=o1(t),!/\/$/.test(t))t+="/";if(n.wasmPaths)In.wasm.wasmPaths=n.wasmPaths;In.wasm.numThreads=e;let o=typeof n.progress==="function"?n.progress:null,s=new Map,a=(d)=>{if(!s.has(d)){let m=n1(t+d,o?(f,g)=>o({file:d,loaded:f,total:g}):null).then((f)=>(o?.({file:d,loaded:f.byteLength,total:f.byteLength,done:!0}),f));s.set(d,m)}return s.get(d)},r=["meta.json","det.onnx",n.recInt8?"rec.int8.onnx":"rec.onnx"];if(n.order!==!1)r.push("order.onnx");if(n.orient!==!1)r.push("orient.onnx");if(n.math)r.push("mathcls.onnx","math_enc.onnx","math_dec_init.onnx","math_dec_step.onnx","math_meta.json");await Promise.allSettled(r.map(a));let l=async(d)=>JSON.parse(new TextDecoder().decode(await a(d))),i=null;try{i=await l("meta.json")}catch{}let u=(i?.script_groups??["base","cjk","rtl","other"]).filter((d)=>d!=="base"),h=[];if(n.cjk!==!1)h.push("script.onnx",...u.map((d)=>`rec_${d}.onnx`));if(n.lm!==!1){if(h.push("lm.npz"),n.cjk!==!1)h.push(...u.map((d)=>`lm_${d}.npz`))}await Promise.allSettled(h.map(a));let c={Tensor:Qe,meta:()=>l("meta.json"),json:l,bytes:async(d)=>new Uint8Array(await a(d)),session:(d)=>e1(t,d,a)},p=await At.create(c,n);return p.device="wasm",p}async function kn(t){let n=t instanceof Blob?t:await(await fetch(t)).blob(),e=await createImageBitmap(n),o=document.createElement("canvas");o.width=e.width,o.height=e.height;let s=o.getContext("2d",{willReadFrequently:!0});s.drawImage(e,0,0);let{data:a,width:r,height:l}=s.getImageData(0,0,e.width,e.height),i=new Uint8Array(r*l);for(let u=0,h=0;u>15;return e.close(),{data:i,width:r,height:l}}var O=(t)=>document.getElementById(t),b={run:O("run"),gear:O("gear"),panel:O("panel"),models:O("models"),cjk:O("cjk"),orient:O("orient"),pbar:O("pbar"),pfill:O("pbar").firstElementChild,viewport:O("viewport"),wrap:O("pageWrap"),cv:O("cv"),overlay:O("overlay"),empty:O("empty"),samples:O("samples"),pick:O("pick"),open:O("open"),file:O("file"),zin:O("zin"),zout:O("zout"),zfit:O("zfit"),zpct:O("zpct"),dims:O("dims"),tabs:[...document.querySelectorAll(".tab")],copy:O("copy"),lines:O("lines"),mdview:O("mdview"),ph:O("ph"),scroll:O("scroll"),status:O("status"),chips:O("chips")},B={gray:null,shown:null,page:null,view:"text",zoom:"fit",busy:!1},Z=(t,n=!1)=>{b.status.textContent=t,b.status.classList.toggle("err",n)},En=(t)=>`${(t/1048576).toFixed(1)} MB`,ot=null,lt=null,jt=new Map;function s1(t){jt.set(t.file,{loaded:t.loaded,total:t.total});let n=0,e=0,o=!0;for(let{loaded:s,total:a}of jt.values())if(n+=s,a==null)o=!1;else e+=a;b.pbar.hidden=!1,b.pbar.classList.toggle("indet",!o),b.pfill.style.transform=o?`scaleX(${e?n/e:0})`:"",Z(o?`downloading models ${En(n)} / ${En(e)} — ${t.file}`:`downloading models — ${t.file}`)}async function a1(){let t=b.models.value.trim()||"datalab-to/indra-ocr@v1.1.0",n={cjk:b.cjk.checked,orient:b.orient.checked},e=JSON.stringify([t,n.cjk,n.orient]);if(ot&<===e)return ot;ot=null,lt=e,jt.clear();try{return ot=await _n(t,{...n,progress:s1}),b.pbar.hidden=!0,ot}catch(o){throw lt=null,b.pbar.hidden=!0,o}}for(let t of[b.models,b.cjk,b.orient])t.addEventListener("change",()=>{if(lt!==null)Z("settings changed — models reload on the next run");lt=null});b.gear.addEventListener("click",()=>{b.panel.hidden=!b.panel.hidden,b.gear.setAttribute("aria-expanded",String(!b.panel.hidden))});document.addEventListener("pointerdown",(t)=>{if(!b.panel.hidden&&!t.target.closest(".settings"))b.panel.hidden=!0,b.gear.setAttribute("aria-expanded","false")});function ht(t,n){let e=document.createElement("canvas");e.width=t,e.height=n;let o=e.getContext("2d");return o.fillStyle="#fdfdfb",o.fillRect(0,0,t,n),o.fillStyle="#1a1a1e",o}var st=(t,n)=>`${n?"bold ":""}${t}px Georgia, "Times New Roman", serif`,bt=(t)=>`${t}px ui-monospace, Menlo, Consolas, monospace`;function Tn({flip:t=!1}={}){let o=ht(1080,560);if(o.font=st(38,!0),o.fillText("Notes from a Quiet Machine",64,104),o.font=st(25),["This page was recognized without leaving the browser:","line detection, recognition, reading order and orientation","all run locally on WebAssembly, via ONNX Runtime.","Your pixels stay put — only the model weights travel,","about 18 MB, once, and then the browser caches them.","Filed under on-device intelligence"].forEach((a,r)=>o.fillText(a,64,180+r*54)),!t)return o.canvas;let s=ht(1080,560);return s.translate(540,280),s.rotate(Math.PI),s.drawImage(o.canvas,-540,-280),s.canvas}function r1(){let e=ht(1080,620);e.font=st(36,!0),e.fillText("Reading Order, Demonstrated",64,96),e.font=st(23);let o=["Documents rarely read in one straight run:","columns, sidebars and tables all compete","for attention. Detection only sees lines,","so ordering is a problem of its own."],s=["1. find the lines","2. read every line, left to right","3. decide what belongs to what block","4. put the blocks back in order"];return o.forEach((a,r)=>e.fillText(a,64,180+r*56)),s.forEach((a,r)=>e.fillText(a,610,180+r*56)),e.canvas}function i1(){let e=ht(640,860);e.font=bt(30),e.textAlign="center",e.fillText("CORNER BOOKSTORE",320,96),e.font=bt(22),e.fillText("123 Inkwell Lane · tel 555-0110",320,136),e.textAlign="left";let o=(a,r,l)=>{e.fillText(a,56,l),e.textAlign="right",e.fillText(r,584,l),e.textAlign="left"},s=220;for(let[a,r]of[["Map of Invisible Cities","18.50"],["The Index Card","9.75"],["Brass Bookmark","4.00"],["Absolute Python 4e","52.00"]])o(a,r,s),s+=52;return e.fillText("—".repeat(24),56,s+14),o("SUBTOTAL","84.25",s+70),o("TAX 8%","6.74",s+122),e.font=bt(30),o("TOTAL","90.99",s+190),e.font=bt(20),o("2026-10-19 14:32","VISA ..0424",s+260),e.textAlign="center",e.fillText("thank you — come again",320,s+330),e.canvas}function c1(){let e=ht(1080,520);return e.font=st(40,!0),e.fillText("光学字符识别",64,100),e.font=st(26),["检测、识别与阅读顺序模型都运行在浏览器里。","图片不会离开这台设备,识别结果实时生成。","标点也要保留:,。、;!?——(2026)"].forEach((o,s)=>e.fillText(o,64,190+s*60)),e.canvas}var l1=[{label:"Article",draw:Tn},{label:"Two columns",draw:r1},{label:"Receipt",draw:i1},{label:"中文",draw:c1},{label:"Upside down",draw:()=>Tn({flip:!0})}];for(let t of l1){let n=t.draw(),e=document.createElement("button"),o=document.createElement("span");o.className="thumb",o.appendChild(n);let s=document.createElement("span");s.className="lbl",s.textContent=t.label,e.append(o,s),e.onclick=()=>{n.toBlob(async(a)=>{Z(`sample: ${t.label}…`),await It(a)},"image/png")},b.samples.appendChild(e)}function h1({data:t,width:n,height:e}){let o=new Uint8Array(n*e);for(let s=0;sFt((B.zoom==="fit"?Dt():B.zoom)*1.25);b.zout.onclick=()=>Ft(Math.min(5,Math.max(0.15,(B.zoom==="fit"?Dt():B.zoom)/1.25)));b.zfit.onclick=()=>Ft("fit");function Ft(t){B.zoom=t,zt()}new ResizeObserver(()=>{if(B.zoom==="fit"&&B.shown)zt()}).observe(b.viewport);async function It(t){let n=await kn(t);B.gray=n,B.page=null,B.zoom="fit",Ln(n),b.empty.hidden=!0,b.wrap.hidden=!1,b.pick.hidden=!1,b.run.disabled=!1,f1(),await Cn()}function f1(){b.lines.replaceChildren(),b.lines.hidden=!0,b.mdview.hidden=!0,b.ph.hidden=!1,b.chips.replaceChildren(),b.tabs.find((t)=>t.dataset.v==="md").disabled=!0,Pt("text")}function Pt(t){B.view=t;for(let n of b.tabs)n.classList.toggle("on",n.dataset.v===t);b.mdview.hidden=t!=="md",b.lines.hidden=t!=="text"||!B.page,b.ph.hidden=!(t==="text"&&!B.page)}for(let t of b.tabs)t.onclick=()=>!t.disabled&&Pt(t.dataset.v);b.copy.onclick=async()=>{let t=B.view==="md"?B.page?.markdown:B.page?.text;if(!t)return;try{await navigator.clipboard.writeText(t),Z(B.view==="md"?"markdown copied":"text copied")}catch{Z("clipboard blocked by the browser",!0)}};function vt(t,n){if(b.overlay.children[t]?.classList.toggle("hot",n),b.lines.children[t]?.classList.toggle("hot",n),n)b.lines.children[t]?.scrollIntoView({block:"nearest"})}function u1(){let t=B.page;b.overlay.replaceChildren(),b.lines.replaceChildren(),t.lines.forEach((e,o)=>{let[s,a,r,l]=e.box,i=document.createElement("div");i.className="box",i.style.cssText=`left:${s/B.shown.width*100}%;top:${a/B.shown.height*100}%;width:${(r-s)/B.shown.width*100}%;height:${(l-a)/B.shown.height*100}%`,i.onmouseenter=()=>vt(o,!0),i.onmouseleave=()=>vt(o,!1),b.overlay.appendChild(i);let u=document.createElement("div");u.className="row";let h=Math.round((e.conf??0)*100),c=document.createElement("span");c.className="idx",c.textContent=o+1;let p=document.createElement("span");p.className="txt",p.textContent=e.text;let d=document.createElement("span");d.className="conf",d.title=`confidence ${h}%`,d.appendChild(document.createElement("i")).style.width=`${h}%`;let m=document.createElement("span");m.className="pct",m.textContent=`${h}%`,u.append(c,p,d,m),u.onmouseenter=()=>vt(o,!0),u.onmouseleave=()=>vt(o,!1),b.lines.appendChild(u)}),b.ph.hidden=!0,b.lines.hidden=B.view!=="text";let n=b.tabs.find((e)=>e.dataset.v==="md");n.disabled=t.markdown==null,b.mdview.textContent=t.markdown??"",p1()}function Y(t,n=""){let e=document.createElement("span");e.className=`chip ${n}`.trim(),e.textContent=t,b.chips.appendChild(e)}function p1(){let{page:t}=B;if(b.chips.replaceChildren(),Y(`${t.lines.length} lines`,"good"),t.rotation)Y(`↻ ${t.rotation}°`,"good");if(t.skew)Y(`deskew ${t.skew}°`);let n=t.timings??{};if(n.orientMs!=null)Y(`orient ${n.orientMs}ms`);if(n.detMs!=null)Y(`det ${n.detMs}ms`);if(n.recMs!=null)Y(`rec ${n.recMs}ms`);if(n.orderMs!=null)Y(`order ${n.orderMs}ms`)}async function Cn(){if(!B.gray||B.busy)return;B.busy=!0,b.run.disabled=!0;let t=performance.now();try{await a1(),Z("running OCR…"),await new Promise((o)=>setTimeout(o,20));let n=await ot.run(B.gray);if(B.page=n,n.rotation)Ln(m1(B.gray,n.rotation/90));Pt(B.view),u1();let e=Math.round(performance.now()-t);Z("done — hover a line to locate it on the page"+(n.rotation?` (page was turned ${n.rotation}°)`:"")),Y(`${e} ms`)}catch(n){Z("failed: "+(n?.message??n),!0),console.error(n)}b.run.disabled=!1,B.busy=!1}function m1(t,n){for(;n>0;n--)t=h1(t);return t}b.run.onclick=()=>Cn();b.pick.onclick=()=>{b.empty.hidden=!b.empty.hidden};b.open.onclick=()=>b.file.click();b.file.onchange=()=>{if(b.file.files[0])It(b.file.files[0]);b.file.value=""};var Ut=0;window.addEventListener("dragenter",(t)=>{if(t.preventDefault(),++Ut===1)b.viewport.classList.add("drag")});window.addEventListener("dragleave",()=>{if(--Ut===0)b.viewport.classList.remove("drag")});window.addEventListener("dragover",(t)=>t.preventDefault());window.addEventListener("drop",(t)=>{t.preventDefault(),Ut=0,b.viewport.classList.remove("drag");let n=t.dataTransfer.files[0];if(n)It(n)});window.addEventListener("paste",(t)=>{let e=[...t.clipboardData?.items??[]].find((o)=>o.type.startsWith("image/"))?.getAsFile();if(e)It(e)}); +`)}function Ae(t,n,e,o,s,a,r,l,c){let u=mn(s,n,c),h=n.map((i)=>o[i]);if((u===re||u===ie)&&!a)return;if(h.every((i)=>he.test(i.trim()))){t.push(h.map((i)=>"$$"+i.trim().slice(1,-1)+"$$").join(` +`));return}if(u===ce)t.push("## "+Bt(h));else if(u===cn&&n.length>1&&l){let i=n.map((d)=>e[d]),p=Me(l,n);if(xe(i,p,n.length))t.push(ye(i,h,p,n.length));else{let d=[],m=[];for(let f of n)for(let[g,x]of r?.get(f)||[[e[f],o[f]]])d.push(g),m.push(x);t.push(Nt(d,m))}}else if(u===cn&&n.length>1){let i=[],p=[];for(let d of n)for(let[m,f]of r?.get(d)||[[e[d],o[d]]])i.push(m),p.push(f);t.push(Nt(i,p))}else if(u===le){let i=[];for(let p of h)if(!i.length||fe.test(p))i.push([p]);else i[i.length-1].push(p);t.push(i.map(Bt).join(` +`))}else t.push(Bt(h))}class ct{constructor(t){this.chars=t,this.index=new Map(t.map((n,e)=>[n,e+1])),this.hasCommands=t.some((n)=>n.length>1),this.jamo=this.index.has("ᄀ")}static fromMeta(t){if(typeof t==="string")t=JSON.parse(t);if(t.blank!==0)throw Error("only blank=0 vocabularies are supported");return new ct(t.chars)}decode(t){let n=[];for(let o of t)if(o>0&&o<=this.chars.length)n.push(this.chars[o-1]);if(this.jamo)return n.join("").normalize("NFC");if(!this.hasCommands)return n.join("");let e="";for(let o=0;o2&&s[0]==="\\"&&/^\p{L}+$/u.test(s.slice(1))&&/^\p{L}/u.test(a))e+=" "}return e}}var be=new Map([..."()[]{}<>«»‹›"].map((t,n)=>[t,")(][}{><»«›‹"[n]]));var Mn=(t)=>it(t),Rt=(t)=>{for(let n of t)if(it(n))return!0;return!1},ve=(t)=>{let n=0,e=0;for(let o of t)if(it(o))n++;else if(Zt(o))e++;return n>e};function Ie(t){let n=[];for(let e of t)if(n.length&&tn(e))n[n.length-1]+=e;else n.push(e);return n}var ke=(t)=>it(t)?"R":Jt(t)?"L":"N";function wn(t,n,e){let o=[],s=null,a=null;for(let r=0;r<=t.length;r++){let l=r{let n=String.fromCodePoint(t.codePointAt(0));return(be.get(n)??n)+t.slice(n.length)};function yn(t,n=null,e=!0){if(!Rt(t))return t;let o=Ie(t),s=o.map(ke);if(n===null?ve(t):n){let l=[],c=[...wn(s,"L",new Set(["R"])),[o.length,o.length]],u=0;for(let[h,i]of c){for(;uz(t*10)/10,He=(t)=>z(t*100)/100,Ge=(t)=>z(t*1e4)/1e4,We=new Set(".·…‥_-–—="),Ve=new Set("-–—"),Ke=new Set("•◦▪▫●○■□‣⁃∙*"),Xe=/^(?:\d{1,3}|[A-Za-z])[.)]$|^\((?:\d{1,3}|[A-Za-z]|[ivxlcIVXLC]{1,5})\)$/,qe=2.5;function Ye(t,n,e=!1,o=null){let s=n.map(()=>!0),a=t.map((c)=>c[3]-c[1]),r=t.map((c)=>c[2]-c[0]);for(let c=0;cWe.has(h))){let h=r[c]>=3*a[c],i=[...u].some((p)=>Ve.has(p));if(u.length>=3||h||!i)s[c]=!1}}for(let c=0;c0&&typeof p[0][0]==="string",m=d?" ":o;if(!e&&n[c].toks.length&&p.length&&m!==null){if(typeof n[c].toks[0][0]==="string"===d){let f=(t[c][2]+t[h][0])/2;n[h].toks=[...n[c].toks,[m,f,...n[c].toks[n[c].toks.length-1].slice(2)],...p]}}n[h]={text:`${u} ${n[h].text.trim()}`,conf:n[h].conf,toks:n[h].toks},t[h]=[Math.min(t[c][0],t[h][0]),Math.min(t[c][1],t[h][1]),Math.max(t[c][2],t[h][2]),Math.max(t[c][3],t[h][3])],s[c]=!1}let l=[];for(let c=0;ct[c]),rec:l.map((c)=>n[c])}}class At{static async create(t,n={}){let e=new At;e.Tensor=t.Tensor,e.tableHeads=n.tableHeads??!1,e.furniture=n.furniture??!1;let o=await t.meta();if(e.vocab=ct.fromMeta(o.vocab),e.longSide=o.det_long_side,e.height=o.rec_height,e.window=o.rec_window??1,e.det=await t.session("det.onnx"),e.rec=await t.session(n.recInt8?"rec.int8.onnx":"rec.onnx"),e.#t=null,e.order=e.orient=null,n.order!==!1)try{e.order=await t.session("order.onnx")}catch{}if(n.orient!==!1)try{e.orient=await t.session("orient.onnx")}catch{}if(e.script=null,e.groups=new Map,e.scriptGroups=o.script_groups??ze,n.cjk!==!1){for(let s of Object.keys(o)){if(!s.startsWith("vocab_"))continue;let a=s.slice(6);try{let r=await t.session(`rec_${a}.onnx`);e.groups.set(a,{sess:r,vocab:ct.fromMeta(o[s])})}catch{}}if(e.groups.size)try{e.script=await t.session("script.onnx")}catch{e.script=null}}if(e.lms=new Map,n.lm!==!1){let s=o.lm_params??{},a=(l)=>!!l.outputNames&&["blank","topv","topi"].every((c)=>l.outputNames.includes(c)),r=async(l,c)=>{if(!a(c))return;try{let u=await W.load(await t.bytes(l==="base"?"lm.npz":`lm_${l}.npz`)),h=s[l]??{};e.lms.set(c,{lm:u,alpha:h.alpha??Re,beta:h.beta??Oe,gate:h.gate??Ne})}catch{}};await r("base",e.rec);for(let l of e.groups.keys()){let c=e.groups.get(l);if(c)await r(l,c.sess)}}if(e.math=null,n.math){if(t.json)e.math=await xt.load(t);if(!e.math)throw Error("math: true needs the math models (mathcls.onnx, math_enc.onnx, math_dec_init.onnx, math_dec_step.onnx, math_meta.json)")}return e.adaptive=n.adaptive??!0,e._pageRtl=!1,e}#t;async#n(t,n){let{x:e,ph:o,pw:s,scale:a}=Xt(t,n),{out:r}=await this.det.run({x:new this.Tensor("float32",e,[1,1,o,s])}),[,l,c,u]=r.dims;return this.#t=l>3?{logit:r.data.subarray(3*c*u,4*c*u),w:u,h:c,scale:a}:null,{boxes:qt(r.data,c,u),scale:a}}async detect(t){let{boxes:n,scale:e}=await this.#n(t,this.longSide);if(this.adaptive&&n.length>=8){let o=H(n.map((s)=>s[3]-s[1]));if(o<_e){let s=Math.floor(Math.min(Te,this.longSide*Ee/Math.max(o,1)));if(s=Math.floor(s/32)*32,s>this.longSide)({boxes:n,scale:e}=await this.#n(t,s))}}for(let o of n)o[0]=G(o[0]/e,0,t.width),o[2]=G(o[2]/e,0,t.width),o[1]=G(o[1]/e,0,t.height),o[3]=G(o[3]/e,0,t.height);return n}async detectAll(t){this.#t=null;let n=await this.detect(t),e=this.#t;if(!e)return[n,[]];return[n,Ze(e.logit,e.w,e.h,e.scale,t.width,t.height)]}async#f(t,n=64){let e=t.map(()=>"base"),o=t.map(()=>!0);for(let s of nt(t.map((a)=>a.w),n)){let{arr:a,w:r,widths:l}=tt(s.map((i)=>t[i])),{p:c}=await this.script.run({x:new this.Tensor("float32",a,[s.length,1,this.height,r]),widths:new this.Tensor("int64",l,[s.length])}),u=c.dims.length>1,h=u?c.dims[1]:1;s.forEach((i,p)=>{let d,m;if(!u){let f=c.data[p];d=f>0.5?"cjk":"base",m=Math.max(f,1-f)}else{let f=0;for(let g=1;gc.data[p*h+f])f=g;d=this.scriptGroups[f],m=c.data[p*h+f]}e[i]=this.groups.has(d)?d:"base",o[i]=m>Fe})}return{names:e,sure:o}}async recognize(t,n,e=64,o=!1){let s=this.window,a=s>1?n.map((i)=>Tt(t,i)):null,r=n.map((i,p)=>rt(t,i,this.height,4096,1,a?a[p]:null)),l=s>1?n.map((i,p)=>rt(t,i,this.height,4096,s,a?a[p]:null)):r,c=r.map(()=>({text:"",conf:0,toks:[]})),u;if(o&&this.groups.has("cjk")){let{sess:i,vocab:p}=this.groups.get("cjk");u=[[i,p,r.map((d,m)=>m),!0]]}else if(this.script&&r.length){let{names:i,sure:p}=await this.#f(r,e);u=[[this.rec,this.vocab,i.flatMap((d,m)=>d==="base"||!p[m]?[m]:[]),!1]].concat([...this.groups].map(([d,{sess:m,vocab:f}])=>[m,f,i.flatMap((g,x)=>g===d?[x]:[]),!0]))}else u=[[this.rec,this.vocab,r.map((i,p)=>p),!1]];let h=new Float64Array(r.length).fill(-1);for(let[i,p,d,m]of u){if(!d.length)continue;for(let f of nt(d.map((g)=>r[g].w),e)){let g=f.map((T)=>d[T]),x=l===r||i!==this.rec?r:l,{arr:A,w,widths:M}=tt(g.map((T)=>x[T])),I=this.lms.get(i),_=A.length/(f.length*w),k=await i.run({x:new this.Tensor("float32",A,[f.length,1,_,w]),widths:new this.Tensor("int64",M,[f.length])}),{ids:E,conf:S,lengths:L}=k,R=I&&k.blank&&k.topv&&k.topi,y=E.dims[1],v=w/Math.max(y,1);for(let T=0;TNumber(E.data[T*y+Q])),N=[];for(let D=0;DP[D]),Wt=N,J=N.length?N.reduce((D,Q)=>D+S.data[T*y+Q],0)/N.length:0;if(R&&J>=An&&JGt+(D+0.5)*v*Nn),Rn=m?ft.map((D,Q)=>[p.chars[D-1],Vt[Q]]):ft.map((D,Q)=>[D,Vt[Q]]);if(J<=h[j])continue;h[j]=J,c[j]=J>=An?{text:p.decode(ft),conf:J,toks:Rn}:{text:"",conf:J,toks:[]}}}}if(this.math&&r.length){let p=(await this.math.flags(r)).flatMap((d,m)=>d?[m]:[]);if(p.length){let d=await this.math.read(t,p.map((m)=>n[m]));p.forEach((m,f)=>{let{text:g,conf:x}=d[f];if(g.includes("$")&&x>=$t){let A=(n[m][0]+n[m][2])/2;c[m]={text:g,conf:1,toks:[[g,A]]}}})}}return c}async readingOrder(t,n,e){if(t.length<2||!this.order)return{order:t.length?gt(t):[],layout:null};let o=en(t,e[0],e[1],n),s=t.length,a=await this.order.run({feats:new this.Tensor("float32",o,[1,s,16]),mask:new this.Tensor("bool",new Uint8Array(s).fill(1),[1,s])}),r=a.a.data,l=a.cls?a.cls.data:null;if(a.same)return{order:an(r,a.same.data,t,l),layout:{cls:l,same:a.same.data,tab:this.tableHeads&&a.tab?a.tab.data:null,classes:F}};return{order:Ct(r,s),layout:null}}#e(t){return t===" "||t===this.vocab.index.get(" ")}#i(t){if(!t.length)return"";if(typeof t[0][0]==="string"){let n=t.map((e)=>e[0]).join("").split(/\s+/).filter(Boolean).join(" ");if(t[0].length===2){if(n=n.normalize("NFC"),Rt(n))n=yn(n,this._pageRtl||null)}return n}return this.vocab.decode(t.map((n)=>n[0]))}#u(t,n){let e=t.map((s)=>s[0]),o=t.map((s)=>s[2]);return t.map((s,a)=>{let r=Math.max(1,s[3]-s[1]),l=n[a].toks.filter((u)=>!this.#e(u[0])).map((u)=>u[1]),c=[];for(let u=1;u=Be)c.push((h+i)/2)}return c})}#o(t,n,e,o=[]){let s=Math.max(1,t[3]-t[1]),a=[[]],r=null,l=[...o].sort((u,h)=>u-h);for(let u of n){let h=u[1];if(!this.#e(u[0])){if(r!==null&&(h-r>e*s||l.some((p)=>r!this.#e(p[0])).map((p)=>p[1]);if(h&&i.length)c.push([[Math.max(t[0],Math.min(...i)-0.35*s),t[1],Math.min(t[2],Math.max(...i)+0.35*s),t[3]],h,u])}return c}async#p(t,n,e,o,s=!1,a=null){let r=Date.now(),l=0,c=0;for(let E of e)for(let S of E.text)if(/\p{L}/u.test(S)){if(c++,Mn(S))l++}this._pageRtl=l>c-l;let u=t[0],h=(E)=>this._pageRtl?[u-E[2],E[1],u-E[0],E[3]]:E,i=[],p=[],d=n.length?this.#u(n,e):[];n.forEach((E,S)=>{for(let[L,R,y]of this.#o(E,e[S].toks,Ce,d[S]))i.push(L),p.push({text:R,conf:e[S].conf,toks:y})});let m=Ye(i,p,this._pageRtl,this.vocab.index.get(" ")??null),{boxes:f,rec:g}=m,x=g.map((E)=>E.text),{order:A,layout:w}=await this.readingOrder(f.map(h),x,t);if(s&&w){let E=sn(f);A=E.flat();let S=f.length,L=new Float32Array(S*S).fill(-1);for(let v of E)for(let T of v)for(let j of v)L[T*S+j]=1;let R=w.cls.length/S,y=w.cls.slice();for(let v of St)for(let T=0;T{let y=0;for(let v=1;vw.cls[R*F.length+y])y=v;return y===E});if(S.some(Boolean)){let L=[],R=[];if(f.forEach((y,v)=>{let T=S[v]?this.#o(y,g[v].toks,bn):[[y,g[v].text,g[v].toks]];for(let[j,B,P]of T)L.push(j),R.push({text:B,conf:g[v].conf,toks:P})}),L.length!==f.length)f=L,g=R,x=g.map((y)=>y.text),{order:A,layout:w}=await this.readingOrder(f.map(h),x,t)}}o.orderMs=Date.now()-r,o.totalMs=o.orientMs+o.detMs+o.recMs+o.orderMs;let M=s?"order=xycut":"order=model",I=A.map((E)=>({box:f[E].slice(0,4).map(V),text:g[E].text,conf:Ge(g[E].conf)})),_=null,k=[];if(w){k=dn(f.map(h),x,A,w.cls,w.same);for(let L of k)L.bbox=h(L.bbox).map(V);let E=new Map(f.map((L,R)=>[R,this.#o(L,g[R].toks,bn).map(([y,v])=>[h(y),v])])),S=a&&a.length;if(_=gn(f.map(h),x,A,w.cls,w.same,{keepFurniture:this.furniture,cells:E,tab:this.tableHeads?w.tab:null,pictures:S?a.map(h):null}),S)for(let L of a){let R=(L[1]+L[3])/2,y=k.findIndex((v)=>(v.bbox[1]+v.bbox[3])/2>R&&Math.min(L[2],v.bbox[2])>Math.max(L[0],v.bbox[0]));k.splice(y===-1?k.length:y,0,{label:"Picture",bbox:[V(L[0]),V(L[1]),V(L[2]),V(L[3])],text:""})}}else if(f.length<2)_=x.join(` +`);return{lines:I,md:_,blocks:k,note:M}}#c(t,n){let{width:e,height:o}=t,s=n/Math.max(o,e),a=Math.max(1,z(e*s)),r=Math.max(1,z(o*s)),l=X(t.data,e,o,a,r,"area"),c=new Uint8Array(a*r);for(let u=0;uvn+0.000001)break;a.push(x)}let r=a.map((g)=>this.#s(s,g)),l=-1,c=-1;for(let g=0;gr[l])c=l,l=g;else if(c<0||r[g]>r[c])c=g;let u=[0,a[c],a[l]],h=[],i=new Set;for(let g of u)for(let x=0;x<=8;x++){let A=g-2+x*0.5;if(!i.has(A))i.add(A),h.push(A)}let p=h[0],d=-1/0;for(let g of h){let x=this.#s(e,g);if(x>d)d=x,p=g}let m=[];for(let g=0;;g++){let x=p-0.5+g*0.1;if(x>p+0.5+0.000001)break;m.push(x)}let f=m[0];d=-1/0;for(let g of m){let x=this.#s(e,g);if(x>d)d=x,f=g}return f}#m(t,n=Ue){let e=n/Math.max(t.height,t.width);if(e>=1)return t;let o=Math.max(1,z(t.width*e)),s=Math.max(1,z(t.height*e));return{data:X(t.data,t.width,t.height,o,s,"area"),width:o,height:s}}#r(t,n){return kt(t,ut(t.width/2,t.height/2,n),"replicate")}#l(t,n,e,o){let s=ut(e/2,o/2,-n),a=[t[0],t[2],t[0],t[2]],r=[t[1],t[1],t[3],t[3]],l=a.map((u,h)=>s[0]*u+s[1]*r[h]+s[2]),c=r.map((u,h)=>s[3]*a[h]+s[4]*u+s[5]);return[V(G(Math.min(...l),0,e)),V(G(Math.min(...c),0,o)),V(G(Math.max(...l),0,e)),V(G(Math.max(...c),0,o))]}async upright(t,n=!0,e=null){let o=this.#a(t);if(e===null)e=n?await this.orientation(Math.abs(o)>=Ot?this.#r(t,o):t):0;return this.#h(t,e,o,null)}#h(t,n,e,o){let s=n===yt?1:-n;if(n===yt)t=pt(t,3);else if(n)t=pt(t,n);if(n===1||n===3||n===yt){let a=o?pt(o,s===1?3:-s):t;e=this.#a(a)}if(Math.abs(e)>=Ot)t=this.#r(t,e);else e=0;return{gray:t,turns:n,skew:e}}async orientation(t){if(!this.orient)return 0;let n=Le,{height:e,width:o}=t,s=n/Math.max(e,o),a=Math.max(1,z(e*s)),r=Math.max(1,z(o*s)),l=a===e&&r===o?t.data:X(t.data,o,e,r,a,"area"),c=new Float32Array(n*n);for(let i=0;iu.data[h])h=i;return u.data[h]>Se?h:0}async run(t,n=!0){let e={},o=Date.now(),s=this.#m(t),a=this.#a(s),r=n?await this.orientation(Math.abs(a)>=Ot?this.#r(s,a):s):0,l=Date.now()-o,c=await this.#d(t,r,a,s);return c.timings.orientMs+=l,c}async#d(t,n,e,o){let s={},a=Date.now(),r=this.#h(t,n,e,o);t=r.gray,s.orientMs=Date.now()-a,a=Date.now();let[l,c]=await this.detectAll(t);s.detMs=Date.now()-a,a=Date.now();let u=r.turns===yt,h=await this.recognize(t,l,64,u);s.recMs=Date.now()-a;let i=await this.#p([t.width,t.height],l,h,s,u,u?null:c),p=u?0:90*r.turns,d=He(r.skew);if(r.skew){for(let m of i.lines)m.box=this.#l(m.box,r.skew,t.width,t.height);for(let m of i.blocks)m.bbox=this.#l(m.bbox,r.skew,t.width,t.height)}if(u){let m=t.height,f=(g)=>[m-g[3],g[0],m-g[1],g[2]];for(let g of i.lines)g.box=f(g.box);for(let g of i.blocks)g.bbox=f(g.bbox)}return{lines:i.lines,source:"ocr",rotation:p,skew:d,vertical:u,markdown:i.md,blocks:i.blocks,pictures:i.blocks.filter((m)=>m.label==="Picture").map((m)=>m.bbox),text:i.lines.map((m)=>m.text).join(` +`),note:i.note,timings:s}}}function Ze(t,n,e,o,s,a){let r=t.length,l=new Uint8Array(r);for(let m=0;m0?1:0;let c=new Int32Array(r),u=[],h=new Int32Array(r);for(let m=0;m0){let A=h[--g],w=A/n|0,M=A-w*n;if(Mx.x1)x.x1=M;if(wx.y1)x.y1=w;for(let I=-1;I<=1;I++){let _=w+I;if(_<0||_>=e)continue;for(let k=-1;k<=1;k++){let E=M+k;if(E<0||E>=n)continue;let S=_*n+E;if(l[S]&&!c[S])c[S]=f,h[g++]=S}}}u.push(x)}let i=2/o,p=Pe*a*s,d=[];for(let m of u){let f=[m.x0*i,m.y0*i,Math.min((m.x1+1)*i,s),Math.min((m.y1+1)*i,a)];if((f[2]-f[0])*(f[3]-f[1])>=p)d.push(f)}return d}var t1="v1.1.0";async function n1(t,n){let e=await fetch(t);if(!e.ok)throw Error(`${e.status} ${e.statusText} for ${t}`);if(!e.body||!n)return new Uint8Array(await e.arrayBuffer());let o=e.headers.has("content-length")?+e.headers.get("content-length"):null,s=e.body.getReader(),a=[],r=0;for(;;){let{done:u,value:h}=await s.read();if(u)break;a.push(h),r+=h.byteLength,n(r,o)}let l=new Uint8Array(r),c=0;for(let u of a)l.set(u,c),c+=u.byteLength;return l}async function e1(t,n,e){let o=await e(n),s=await Je.create(o,{executionProviders:["wasm"],graphOptimizationLevel:"all"});return{run:(a)=>s.run(a),inputNames:s.inputNames,outputNames:s.outputNames}}function o1(t){let n=/^([^/@:\s]+)\/([^/@:\s]+)(?:@(.+))?$/.exec(t);return n?`https://huggingface.co/${n[1]}/${n[2]}/resolve/${n[3]||t1}`:t}async function kn(t,n={}){let e=n.threads??4;if(t=o1(t),!/\/$/.test(t))t+="/";if(n.wasmPaths)In.wasm.wasmPaths=n.wasmPaths;In.wasm.numThreads=e;let o=typeof n.progress==="function"?n.progress:null,s=new Map,a=(d)=>{if(!s.has(d)){let m=n1(t+d,o?(f,g)=>o({file:d,loaded:f,total:g}):null).then((f)=>(o?.({file:d,loaded:f.byteLength,total:f.byteLength,done:!0}),f));s.set(d,m)}return s.get(d)},r=["meta.json","det.onnx",n.recInt8?"rec.int8.onnx":"rec.onnx"];if(n.order!==!1)r.push("order.onnx");if(n.orient!==!1)r.push("orient.onnx");if(n.math)r.push("mathcls.onnx","math_enc.onnx","math_dec_init.onnx","math_dec_step.onnx","math_meta.json");await Promise.allSettled(r.map(a));let l=async(d)=>JSON.parse(new TextDecoder().decode(await a(d))),c=null;try{c=await l("meta.json")}catch{}let u=(c?.script_groups??["base","cjk","rtl","other"]).filter((d)=>d!=="base"),h=[];if(n.cjk!==!1)h.push("script.onnx",...u.map((d)=>`rec_${d}.onnx`));if(n.lm!==!1){if(h.push("lm.npz"),n.cjk!==!1)h.push(...u.map((d)=>`lm_${d}.npz`))}await Promise.allSettled(h.map(a));let i={Tensor:Qe,meta:()=>l("meta.json"),json:l,bytes:async(d)=>new Uint8Array(await a(d)),session:(d)=>e1(t,d,a)},p=await At.create(i,n);return p.device="wasm",p}async function _n(t,n={}){if(typeof t==="string"||t instanceof URL){let s=await fetch(t);if(!s.ok)throw Error(`${s.status} ${s.statusText} for ${t}`);t=await s.blob()}let e=!(typeof ImageBitmap<"u"&&t instanceof ImageBitmap),o=e?await createImageBitmap(t):t;try{let{width:s,height:a}=o,r=n.maxSide,l=r>0?Math.min(1,r/Math.max(s,a)):1,c=Math.max(1,Math.round(s*l)),u=Math.max(1,Math.round(a*l)),i=(typeof OffscreenCanvas<"u"?new OffscreenCanvas(c,u):Object.assign(document.createElement("canvas"),{width:c,height:u})).getContext("2d",{willReadFrequently:!0});i.fillStyle="#fff",i.fillRect(0,0,c,u),i.imageSmoothingEnabled=!0,i.imageSmoothingQuality="high",i.drawImage(o,0,0,c,u);let{data:p}=i.getImageData(0,0,c,u),d=new Uint8Array(c*u);for(let m=0,f=0;m>15;return{data:d,width:c,height:u}}finally{if(e)o.close()}}var O=(t)=>document.getElementById(t),b={run:O("run"),gear:O("gear"),panel:O("panel"),models:O("models"),cjk:O("cjk"),orient:O("orient"),pbar:O("pbar"),pfill:O("pbar").firstElementChild,viewport:O("viewport"),wrap:O("pageWrap"),cv:O("cv"),overlay:O("overlay"),empty:O("empty"),samples:O("samples"),pick:O("pick"),open:O("open"),file:O("file"),zin:O("zin"),zout:O("zout"),zfit:O("zfit"),zpct:O("zpct"),dims:O("dims"),tabs:[...document.querySelectorAll(".tab")],copy:O("copy"),lines:O("lines"),mdview:O("mdview"),ph:O("ph"),scroll:O("scroll"),status:O("status"),chips:O("chips")},C={gray:null,shown:null,page:null,view:"text",zoom:"fit",busy:!1},Z=(t,n=!1)=>{b.status.textContent=t,b.status.classList.toggle("err",n)},En=(t)=>`${(t/1048576).toFixed(1)} MB`,ot=null,lt=null,jt=new Map;function s1(t){jt.set(t.file,{loaded:t.loaded,total:t.total});let n=0,e=0,o=!0;for(let{loaded:s,total:a}of jt.values())if(n+=s,a==null)o=!1;else e+=a;b.pbar.hidden=!1,b.pbar.classList.toggle("indet",!o),b.pfill.style.transform=o?`scaleX(${e?n/e:0})`:"",Z(o?`downloading models ${En(n)} / ${En(e)} — ${t.file}`:`downloading models — ${t.file}`)}async function a1(){let t=b.models.value.trim()||"datalab-to/indra-ocr@v1.1.0",n={cjk:b.cjk.checked,orient:b.orient.checked},e=JSON.stringify([t,n.cjk,n.orient]);if(ot&<===e)return ot;ot=null,lt=e,jt.clear();try{return ot=await kn(t,{...n,progress:s1}),b.pbar.hidden=!0,ot}catch(o){throw lt=null,b.pbar.hidden=!0,o}}for(let t of[b.models,b.cjk,b.orient])t.addEventListener("change",()=>{if(lt!==null)Z("settings changed — models reload on the next run");lt=null});b.gear.addEventListener("click",()=>{b.panel.hidden=!b.panel.hidden,b.gear.setAttribute("aria-expanded",String(!b.panel.hidden))});document.addEventListener("pointerdown",(t)=>{if(!b.panel.hidden&&!t.target.closest(".settings"))b.panel.hidden=!0,b.gear.setAttribute("aria-expanded","false")});function ht(t,n){let e=document.createElement("canvas");e.width=t,e.height=n;let o=e.getContext("2d");return o.fillStyle="#fdfdfb",o.fillRect(0,0,t,n),o.fillStyle="#1a1a1e",o}var st=(t,n)=>`${n?"bold ":""}${t}px Georgia, "Times New Roman", serif`,bt=(t)=>`${t}px ui-monospace, Menlo, Consolas, monospace`;function Tn({flip:t=!1}={}){let o=ht(1080,560);if(o.font=st(38,!0),o.fillText("Notes from a Quiet Machine",64,104),o.font=st(25),["This page was recognized without leaving the browser:","line detection, recognition, reading order and orientation","all run locally on WebAssembly, via ONNX Runtime.","Your pixels stay put — only the model weights travel,","once, and then the browser caches them.","Filed under on-device intelligence"].forEach((a,r)=>o.fillText(a,64,180+r*54)),!t)return o.canvas;let s=ht(1080,560);return s.translate(540,280),s.rotate(Math.PI),s.drawImage(o.canvas,-540,-280),s.canvas}function r1(){let e=ht(1080,620);e.font=st(36,!0),e.fillText("Reading Order, Demonstrated",64,96),e.font=st(23);let o=["Documents rarely read in one straight run:","columns, sidebars and tables all compete","for attention. Detection only sees lines,","so ordering is a problem of its own."],s=["1. find the lines","2. read every line, left to right","3. decide what belongs to what block","4. put the blocks back in order"];return o.forEach((a,r)=>e.fillText(a,64,180+r*56)),s.forEach((a,r)=>e.fillText(a,610,180+r*56)),e.canvas}function i1(){let e=ht(640,860);e.font=bt(30),e.textAlign="center",e.fillText("CORNER BOOKSTORE",320,96),e.font=bt(22),e.fillText("123 Inkwell Lane · tel 555-0110",320,136),e.textAlign="left";let o=(a,r,l)=>{e.fillText(a,56,l),e.textAlign="right",e.fillText(r,584,l),e.textAlign="left"},s=220;for(let[a,r]of[["Map of Invisible Cities","18.50"],["The Index Card","9.75"],["Brass Bookmark","4.00"],["Absolute Python 4e","52.00"]])o(a,r,s),s+=52;return e.fillText("—".repeat(24),56,s+14),o("SUBTOTAL","84.25",s+70),o("TAX 8%","6.74",s+122),e.font=bt(30),o("TOTAL","90.99",s+190),e.font=bt(20),o("2026-10-19 14:32","VISA ..0424",s+260),e.textAlign="center",e.fillText("thank you — come again",320,s+330),e.canvas}function c1(){let e=ht(1080,520);return e.font=st(40,!0),e.fillText("光学字符识别",64,100),e.font=st(26),["检测、识别与阅读顺序模型都运行在浏览器里。","图片不会离开这台设备,识别结果实时生成。","标点也要保留:,。、;!��——(2026)"].forEach((o,s)=>e.fillText(o,64,190+s*60)),e.canvas}var l1=[{label:"Article",draw:Tn},{label:"Two columns",draw:r1},{label:"Receipt",draw:i1},{label:"中文",draw:c1},{label:"Upside down",draw:()=>Tn({flip:!0})}];for(let t of l1){let n=t.draw(),e=document.createElement("button"),o=document.createElement("span");o.className="thumb",o.appendChild(n);let s=document.createElement("span");s.className="lbl",s.textContent=t.label,e.append(o,s),e.onclick=()=>{n.toBlob(async(a)=>{Z(`sample: ${t.label}…`),await It(a)},"image/png")},b.samples.appendChild(e)}function h1({data:t,width:n,height:e}){let o=new Uint8Array(n*e);for(let s=0;sFt((C.zoom==="fit"?Dt():C.zoom)*1.25);b.zout.onclick=()=>Ft(Math.min(5,Math.max(0.15,(C.zoom==="fit"?Dt():C.zoom)/1.25)));b.zfit.onclick=()=>Ft("fit");function Ft(t){C.zoom=t,zt()}new ResizeObserver(()=>{if(C.zoom==="fit"&&C.shown)zt()}).observe(b.viewport);async function It(t){let n=await _n(t);C.gray=n,C.page=null,C.zoom="fit",Ln(n),b.empty.hidden=!0,b.wrap.hidden=!1,b.pick.hidden=!1,b.run.disabled=!1,f1(),await Sn()}function f1(){b.lines.replaceChildren(),b.lines.hidden=!0,b.mdview.hidden=!0,b.ph.hidden=!1,b.chips.replaceChildren(),b.tabs.find((t)=>t.dataset.v==="md").disabled=!0,Pt("text")}function Pt(t){C.view=t;for(let n of b.tabs)n.classList.toggle("on",n.dataset.v===t);b.mdview.hidden=t!=="md",b.lines.hidden=t!=="text"||!C.page,b.ph.hidden=!(t==="text"&&!C.page)}for(let t of b.tabs)t.onclick=()=>!t.disabled&&Pt(t.dataset.v);b.copy.onclick=async()=>{let t=C.view==="md"?C.page?.markdown:C.page?.text;if(!t)return;try{await navigator.clipboard.writeText(t),Z(C.view==="md"?"markdown copied":"text copied")}catch{Z("clipboard blocked by the browser",!0)}};function vt(t,n){if(b.overlay.children[t]?.classList.toggle("hot",n),b.lines.children[t]?.classList.toggle("hot",n),n)b.lines.children[t]?.scrollIntoView({block:"nearest"})}function u1(){let t=C.page;b.overlay.replaceChildren(),b.lines.replaceChildren(),t.lines.forEach((e,o)=>{let[s,a,r,l]=e.box,c=document.createElement("div");c.className="box",c.style.cssText=`left:${s/C.shown.width*100}%;top:${a/C.shown.height*100}%;width:${(r-s)/C.shown.width*100}%;height:${(l-a)/C.shown.height*100}%`,c.onmouseenter=()=>vt(o,!0),c.onmouseleave=()=>vt(o,!1),b.overlay.appendChild(c);let u=document.createElement("div");u.className="row";let h=Math.round((e.conf??0)*100),i=document.createElement("span");i.className="idx",i.textContent=o+1;let p=document.createElement("span");p.className="txt",p.textContent=e.text;let d=document.createElement("span");d.className="conf",d.title=`confidence ${h}%`,d.appendChild(document.createElement("i")).style.width=`${h}%`;let m=document.createElement("span");m.className="pct",m.textContent=`${h}%`,u.append(i,p,d,m),u.onmouseenter=()=>vt(o,!0),u.onmouseleave=()=>vt(o,!1),b.lines.appendChild(u)}),b.ph.hidden=!0,b.lines.hidden=C.view!=="text";let n=b.tabs.find((e)=>e.dataset.v==="md");n.disabled=t.markdown==null,b.mdview.textContent=t.markdown??"",p1()}function Y(t,n=""){let e=document.createElement("span");e.className=`chip ${n}`.trim(),e.textContent=t,b.chips.appendChild(e)}function p1(){let{page:t}=C;if(b.chips.replaceChildren(),Y(`${t.lines.length} lines`,"good"),t.rotation)Y(`↻ ${t.rotation}°`,"good");if(t.skew)Y(`deskew ${t.skew}°`);let n=t.timings??{};if(n.orientMs!=null)Y(`orient ${n.orientMs}ms`);if(n.detMs!=null)Y(`det ${n.detMs}ms`);if(n.recMs!=null)Y(`rec ${n.recMs}ms`);if(n.orderMs!=null)Y(`order ${n.orderMs}ms`)}async function Sn(){if(!C.gray||C.busy)return;C.busy=!0,b.run.disabled=!0;let t=performance.now();try{await a1(),Z("running OCR…"),await new Promise((o)=>setTimeout(o,20));let n=await ot.run(C.gray);if(C.page=n,n.rotation)Ln(m1(C.gray,n.rotation/90));Pt(C.view),u1();let e=Math.round(performance.now()-t);Z("done — hover a line to locate it on the page"+(n.rotation?` (page was turned ${n.rotation}°)`:"")),Y(`${e} ms`)}catch(n){Z("failed: "+(n?.message??n),!0),console.error(n)}b.run.disabled=!1,C.busy=!1}function m1(t,n){for(;n>0;n--)t=h1(t);return t}b.run.onclick=()=>Sn();b.pick.onclick=()=>{b.empty.hidden=!b.empty.hidden};b.open.onclick=()=>b.file.click();b.file.onchange=()=>{if(b.file.files[0])It(b.file.files[0]);b.file.value=""};var Ut=0;window.addEventListener("dragenter",(t)=>{if(t.preventDefault(),++Ut===1)b.viewport.classList.add("drag")});window.addEventListener("dragleave",()=>{if(--Ut===0)b.viewport.classList.remove("drag")});window.addEventListener("dragover",(t)=>t.preventDefault());window.addEventListener("drop",(t)=>{t.preventDefault(),Ut=0,b.viewport.classList.remove("drag");let n=t.dataTransfer.files[0];if(n)It(n)});window.addEventListener("paste",(t)=>{let e=[...t.clipboardData?.items??[]].find((o)=>o.type.startsWith("image/"))?.getAsFile();if(e)It(e)});