millirec 0.1.0 → 0.1.1
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/CHANGELOG.md +35 -0
- package/README.md +100 -12
- package/dist/char-cnn/core.d.ts +5 -4
- package/dist/char-cnn/core.js +82 -23
- package/dist/char-cnn/index.d.ts +3 -2
- package/dist/char-cnn/index.js +82 -23
- package/dist/char-cnn/millirec-char-cnn-core.min.js +1 -1
- package/dist/char-cnn/millirec-char-cnn.min.js +1 -1
- package/dist/char-lite/index.d.ts +26 -4
- package/dist/char-lite/index.js +77 -9
- package/dist/char-lite/millirec-char-lite.min.js +1 -1
- package/dist/overlap/index.d.ts +139 -0
- package/package.json +36 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var H={MRCNN1:8,MRCNN3:3,MRCNN4:4,MRCNN5:5,MRCNN6:6};function O(s){let n=new DataView(s.buffer?s.buffer:s,s.byteOffset||0,s.byteLength),l=new Uint8Array(n.buffer,n.byteOffset,n.byteLength),o=0;return{u32:()=>{let t=n.getUint32(o,!0);return o+=4,t},f32s:t=>{let r=new Float32Array(t);for(let f=0;f<t;f++)r[f]=n.getFloat32(o,!0),o+=4;return r},i8s:t=>{let r=new Int8Array(t);for(let f=0;f<t;f++)r[f]=l[o+f]<<24>>24;return o+=t,r},ibits:(t,r)=>{if(r===8){let i=new Int8Array(t);for(let e=0;e<t;e++)i[e]=l[o+e]<<24>>24;return o+=t,i}let f=new Int8Array(t),d=(1<<r)-1,u=1<<r-1;for(let i=0;i<t;i++){let e=i*r,c=o+(e>>3),a=e&7,w=(l[c]|l[c+1]<<8)>>a&d;f[i]=w&u?w-(1<<r):w}return o+=t*r+7>>3,f},str:t=>{let r=String.fromCharCode(...l.subarray(o,o+t));return o+=t,r},done:()=>o>=n.byteLength}}function T(s,n=8){let l=s.u32(),o=s.u32(),t=s.f32s(l),r=s.f32s(l),f=s.ibits(l*o,n),d=new Float32Array(l*o);for(let u=0;u<l;u++)for(let i=0;i<o;i++)d[u*o+i]=f[u*o+i]*t[u];return{out:l,in:o,w:d,bias:r}}function X(s){let n=O(s),l=n.str(6),o=H[l];if(!o)throw new Error("not an MRCNN1/3/4/5/6 model");let t=n.u32();if(t!==1)throw new Error("unknown model version "+t);let r=n.u32(),f=n.u32(),d=n.u32(),u=[];for(let e=0;e<d;e++){let c=n.u32(),a=n.u32(),w=n.u32(),x=n.u32(),y=n.f32s(c),m=n.f32s(c),A=n.ibits(c*a*w*w,o),I=new Float32Array(A.length),M=a*w*w;for(let p=0;p<c;p++)for(let b=0;b<M;b++)I[p*M+b]=A[p*M+b]*y[p];u.push({cout:c,cin:a,k:w,pool:x,w:I,bias:m})}let i=T(n,o);return{size:r,dim:f,convs:u,lin:i,bits:o}}function Y(s){let n=new Uint8Array(s.buffer?s.buffer:s,s.byteOffset||0,s.byteLength),l=String.fromCharCode(...n.subarray(0,6)),o=H[l];if(!o)throw new Error("not an MRCNN model");if(o===8)return n;let t=O(s);t.str(6);let r=t.u32(),f=t.u32(),d=t.u32(),u=t.u32(),i=[],e=p=>{let b=new Uint8Array(4);return new DataView(b.buffer).setUint32(0,p,!0),b},c=p=>new Uint8Array(p.buffer,p.byteOffset,p.byteLength);i.push(new TextEncoder().encode("MRCNN1"),e(r),e(f),e(d),e(u));for(let p=0;p<u;p++){let b=t.u32(),h=t.u32(),g=t.u32(),_=t.u32(),k=t.f32s(b),N=t.f32s(b),F=t.ibits(b*h*g*g,o);i.push(e(b),e(h),e(g),e(_),c(k),c(N),new Uint8Array(F.buffer,F.byteOffset,F.length))}let a=t.u32(),w=t.u32(),x=t.f32s(a),y=t.f32s(a),m=t.ibits(a*w,o);i.push(e(a),e(w),c(x),c(y),new Uint8Array(m.buffer,m.byteOffset,m.length));let A=i.reduce((p,b)=>p+b.length,0),I=new Uint8Array(A),M=0;for(let p of i)I.set(p,M),M+=p.length;return I}function q(s){return T(O(s))}function nt(s,n,l,o){let{cout:t,cin:r,k:f,w:d,bias:u}=s,i=l*l,e=f-1>>1,c=r*f*f;for(let a=0;a<t;a++){let w=a*i,x=u[a],y=a*c;for(let m=0;m<l;m++)for(let A=0;A<l;A++){let I=x;for(let M=0;M<r;M++){let p=M*i,b=y+M*f*f;for(let h=0;h<f;h++){let g=m+h-e;if(g<0||g>=l)continue;let _=p+g*l,k=b+h*f;for(let N=0;N<f;N++){let F=A+N-e;F<0||F>=l||(I+=d[k+N]*n[_+F])}}}o[w+m*l+A]=I>0?I:0}}}function et(s,n,l,o){let t=n>>1;for(let r=0;r<l;r++){let f=r*n*n,d=r*t*t;for(let u=0;u<t;u++)for(let i=0;i<t;i++){let e=f+2*u*n+2*i,c=s[e],a=s[e+1],w=s[e+n],x=s[e+n+1];o[d+u*t+i]=Math.max(c,a,w,x)}}}function W(s,n){let l=s.size,o=Float32Array.from(n),t=l,r=1;for(let e of s.convs){let c=new Float32Array(e.cout*t*t);if(nt(e,o,t,c),o=c,r=e.cout,e.pool){let a=new Float32Array(r*(t>>1)*(t>>1));et(o,t,r,a),o=a,t>>=1}}let f=t*t,d=new Float32Array(r);for(let e=0;e<r;e++){let c=0;for(let a=0;a<f;a++)c+=o[e*f+a];d[e]=c/f}let{lin:u}=s,i=new Float32Array(u.out);for(let e=0;e<u.out;e++){let c=u.bias[e];for(let a=0;a<u.in;a++)c+=u.w[e*u.in+a]*d[a];i[e]=c}return i}function K(s){let n=0;for(let o=0;o<s.length;o++)n+=s[o]*s[o];n=1/(Math.sqrt(n)+1e-9);let l=new Float32Array(s.length);for(let o=0;o<s.length;o++)l[o]=s[o]*n;return l}function C(s,n){let l=new Float32Array(s.out);for(let o=0;o<s.out;o++){let t=s.bias[o];for(let r=0;r<s.in;r++){let f=n[r];f>0&&(t+=s.w[o*s.in+r]*f)}l[o]=t}return l}function B(s){let n=-1/0;for(let t of s)t>n&&(n=t);let l=new Float32Array(s.length),o=0;for(let t=0;t<s.length;t++)l[t]=Math.exp(s[t]-n),o+=l[t];for(let t=0;t<s.length;t++)l[t]/=o;return l}function Z(s,n,l=120,o=7,t=10){let r=1/0,f=1/0,d=-1/0,u=-1/0;for(let c of n)for(let a of c)a.x<r&&(r=a.x),a.x>d&&(d=a.x),a.y<f&&(f=a.y),a.y>u&&(u=a.y);let i=l/Math.max(d-r,u-f,1),e=l+2*t;s.fillStyle="#fff",s.fillRect(0,0,e,e),s.strokeStyle="#000",s.lineWidth=o,s.lineCap="round",s.lineJoin="round";for(let c of n)if(!(c.length<2)){s.beginPath(),s.moveTo((c[0].x-r)*i+t,(c[0].y-f)*i+t);for(let a=1;a<c.length;a++)s.lineTo((c[a].x-r)*i+t,(c[a].y-f)*i+t);s.stroke()}return e}function $(s,n,l){let o=new Float32Array(n*l);for(let t=0,r=0;t<o.length;t++,r+=4)o[t]=1-(s[r]*.299+s[r+1]*.587+s[r+2]*.114)/255;return o}function V(s,n,l,o=32,t=24){let r=1/0,f=-1,d=1/0,u=-1;for(let h=0;h<l;h++)for(let g=0;g<n;g++)s[h*n+g]>.15&&(g<r&&(r=g),g>f&&(f=g),h<d&&(d=h),h>u&&(u=h));let i=new Float32Array(o*o);if(f<0)return i;let e=f-r+1,c=u-d+1,a=new Float32Array(e*c);for(let h=0;h<c;h++)for(let g=0;g<e;g++)a[h*e+g]=s[(h+d)*n+(g+r)];let w=0;for(let h=0;h<a.length;h++)a[h]>w&&(w=a[h]);if(w>.05&&w<.999)for(let h=0;h<a.length;h++)a[h]=Math.min(1,a[h]/w);let x=t/Math.max(c,e),y=Math.max(1,Math.round(c*x)),m=Math.max(1,Math.round(e*x)),A=new Float32Array(m*y),I=e/m,M=c/y;for(let h=0;h<y;h++){let g=h*M,_=(h+1)*M,k=Math.floor(g),N=Math.min(c,Math.ceil(_));for(let F=0;F<m;F++){let z=F*I,j=(F+1)*I,Q=Math.floor(z),tt=Math.min(e,Math.ceil(j)),D=0,L=0;for(let S=k;S<N;S++){let R=Math.min(_,S+1)-Math.max(g,S);if(!(R<=0))for(let E=Q;E<tt;E++){let U=Math.min(j,E+1)-Math.max(z,E);U<=0||(D+=a[S*e+E]*U*R,L+=U*R)}}A[h*m+F]=L>0?D/L:0}}let p=o-y>>1,b=o-m>>1;for(let h=0;h<y;h++)for(let g=0;g<m;g++)i[(h+p)*o+g+b]=A[h*m+g];return i}function J(s){let n=s?String(s):"";return n?(n.endsWith("/")||(n+="/"),typeof location<"u"?new URL(n,location.href).href:n):typeof location<"u"?new URL("./",location.href).href:""}var v=s=>Array.isArray(s)&&s.length&&!Array.isArray(s[0])?[s]:s;function ot(){let s=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return s?s.slice(0,s.lastIndexOf("/")+1):""}var st=ot(),G=s=>fetch(s).then(n=>{if(!n.ok)throw new Error(`${s}: ${n.status}`);return n.arrayBuffer()}),P=class{static async create(n={}){let o={...(typeof window<"u"?window:globalThis).MILLIREC_CNN||{},...n};if(!o.stages||!o.stages.length)throw new Error("MillirecCharCnn: no stages configured");let t=new this(o);return await t.ready,t}constructor(n){this.config=n,this.base=J(n.assetBase||st),this.classes=typeof n.classes=="string"?n.classes.split(""):n.classes,this.stages=[],this.off=typeof document<"u"?document.createElement("canvas"):null,this.off&&(this.off.width=this.off.height=140,this.octx=this.off.getContext("2d",{willReadFrequently:!0})),this.ready=this.load()}async load(){let{base:n,config:l}=this,o=null;l.kernel&&(o=(await import(n+l.kernel)).default);for(let t of l.stages){let[r,f]=await Promise.all([G(n+t.model),G(n+t.head)]),d=q(f),u={theta:t.theta==null?null:t.theta,head:d,headNorm:t.headNorm!==!1,size:0};if(o){let i=await o(),e=Y(new Uint8Array(r)),c=i._malloc(e.byteLength);i.HEAPU8.set(e,c);let a=i._cnnLoad(c,e.byteLength);if(i._free(c),!a)throw new Error(`kernel rejected ${t.model} (channel widths must be multiples of four)`);let w=i._cnnSize(),x=i._cnnDim();u.size=w,u.embed=y=>{let m=i._cnnInputPtr(1)>>2;i.HEAPF32.set(y,m),i._cnnRun(1);let A=i._cnnEmbedPtr(1)>>2;return i.HEAPF32.slice(A,A+x)},u.logits=y=>C(u.head,u.embed(y))}else{let i=X(r);u.size=i.size,u.embed=e=>{let c=W(i,e);return u.headNorm?K(c):c},u.logits=e=>C(u.head,u.embed(e))}this.stages.push(u)}}raster(n,l){if(this._planeFor!==n){let r=Z(this.octx,n);this._plane={ink:$(this.octx.getImageData(0,0,r,r).data,r,r),W:r},this._planeFor=n}let{ink:o,W:t}=this._plane;return V(o,t,t,l,Math.round(l*.75))}async recognize(n,{only:l=null}={}){if(n=v(n),!n||!n.length||(await this.ready,!this.stages.length))return null;this._planeFor=null;let o=l?new Set(l):null,t=null,r=0;for(let e=0;e<this.stages.length;e++){let c=this.stages[e];if((this.personal||o)&&e<this.stages.length-1)continue;if(t=c.logits(this.raster(n,c.size)),r=e,c.theta==null||e===this.stages.length-1)break;let a=-1/0,w=-1/0;for(let x of t)x>a?(w=a,a=x):x>w&&(w=x);if(a-w>=c.theta)break}let f=[...t.keys()];if(o&&(f=f.filter(e=>o.has(this.classes[e])),!f.length)){let e=[];return e.stage=r,e}let d=B(f.map(e=>t[e])),i=[...d.keys()].sort((e,c)=>d[c]-d[e]).slice(0,3).map(e=>({char:this.classes[f[e]],prob:d[e]}));return i.stage=r,i}async embedding(n){n=v(n),await this.ready,this._planeFor=null;let l=this.stages[this.stages.length-1];return l.embed(this.raster(n,l.size))}async personalize(n,{steps:l=250,lr:o=.5,prior:t=1}={}){await this.ready;let r=this.stages[this.stages.length-1],f=r.head0||(r.head0=r.head),d=[],u=[];for(let[w,x]of Object.entries(n||{})){let y=this.classes.indexOf(w);if(!(y<0))for(let m of x||[]){let A=v(m);!A||!A.length||(d.push(await this.embedding(A)),u.push(y))}}if(!d.length)return r.head=f,this.personal=null,null;let i={in:f.in,out:f.out,w:Float32Array.from(f.w),bias:Float32Array.from(f.bias)},e=d.length,c=new Float32Array(i.w.length),a=new Float32Array(i.out);for(let w=0;w<l;w++){c.fill(0),a.fill(0);for(let y=0;y<e;y++){let m=B(C(i,d[y])),A=d[y];for(let I=0;I<i.out;I++){let M=(m[I]-(I===u[y]?1:0))/e;if(!M)continue;a[I]+=M;let p=I*i.in;for(let b=0;b<i.in;b++){let h=A[b];h>0&&(c[p+b]+=M*h)}}}let x=t/e;for(let y=0;y<i.w.length;y++)i.w[y]-=o*(c[y]+x*(i.w[y]-f.w[y]));for(let y=0;y<i.out;y++)i.bias[y]-=o*(a[y]+x*(i.bias[y]-f.bias[y]))}return r.head=i,this.personal={n:e,classes:[...new Set(u)].map(w=>this.classes[w]).sort()},this.personal}destroy(){this.stages=[],this.personal=null,this._plane=null,this._planeFor=null}depersonalize(){let n=this.stages[this.stages.length-1];n.head0&&(n.head=n.head0),this.personal=null}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharCnn=P);})();
|
|
1
|
+
"use strict";(()=>{var H={MRCNN1:8,MRCNN3:3,MRCNN4:4,MRCNN5:5,MRCNN6:6};function U(o){let e=new DataView(o.buffer?o.buffer:o,o.byteOffset||0,o.byteLength),c=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=0;return{u32:()=>{let t=e.getUint32(r,!0);return r+=4,t},f32s:t=>{let s=new Float32Array(t);for(let a=0;a<t;a++)s[a]=e.getFloat32(r,!0),r+=4;return s},i8s:t=>{let s=new Int8Array(t);for(let a=0;a<t;a++)s[a]=c[r+a]<<24>>24;return r+=t,s},ibits:(t,s)=>{if(s===8){let i=new Int8Array(t);for(let n=0;n<t;n++)i[n]=c[r+n]<<24>>24;return r+=t,i}let a=new Int8Array(t),y=(1<<s)-1,h=1<<s-1;for(let i=0;i<t;i++){let n=i*s,f=r+(n>>3),l=n&7,w=(c[f]|c[f+1]<<8)>>l&y;a[i]=w&h?w-(1<<s):w}return r+=t*s+7>>3,a},str:t=>{let s=String.fromCharCode(...c.subarray(r,r+t));return r+=t,s},done:()=>r>=e.byteLength}}function W(o,e=8){let c=o.u32(),r=o.u32(),t=o.f32s(c),s=o.f32s(c),a=o.ibits(c*r,e),y=new Float32Array(c*r);for(let h=0;h<c;h++)for(let i=0;i<r;i++)y[h*r+i]=a[h*r+i]*t[h];return{out:c,in:r,w:y,bias:s}}function Y(o){let e=U(o),c=e.str(6),r=H[c];if(!r)throw new Error("not an MRCNN1/3/4/5/6 model");let t=e.u32();if(t!==1)throw new Error("unknown model version "+t);let s=e.u32(),a=e.u32(),y=e.u32(),h=[];for(let n=0;n<y;n++){let f=e.u32(),l=e.u32(),w=e.u32(),x=e.u32(),d=e.f32s(f),p=e.f32s(f),A=e.ibits(f*l*w*w,r),I=new Float32Array(A.length),M=l*w*w;for(let m=0;m<f;m++)for(let b=0;b<M;b++)I[m*M+b]=A[m*M+b]*d[m];h.push({cout:f,cin:l,k:w,pool:x,w:I,bias:p})}let i=W(e,r);return{size:s,dim:a,convs:h,lin:i,bits:r}}function $(o){let e=new Uint8Array(o.buffer?o.buffer:o,o.byteOffset||0,o.byteLength),c=String.fromCharCode(...e.subarray(0,6)),r=H[c];if(!r)throw new Error("not an MRCNN model");if(r===8)return e;let t=U(o);t.str(6);let s=t.u32(),a=t.u32(),y=t.u32(),h=t.u32(),i=[],n=m=>{let b=new Uint8Array(4);return new DataView(b.buffer).setUint32(0,m,!0),b},f=m=>new Uint8Array(m.buffer,m.byteOffset,m.byteLength);i.push(new TextEncoder().encode("MRCNN1"),n(s),n(a),n(y),n(h));for(let m=0;m<h;m++){let b=t.u32(),u=t.u32(),g=t.u32(),k=t.u32(),N=t.f32s(b),S=t.f32s(b),F=t.ibits(b*u*g*g,r);i.push(n(b),n(u),n(g),n(k),f(N),f(S),new Uint8Array(F.buffer,F.byteOffset,F.length))}let l=t.u32(),w=t.u32(),x=t.f32s(l),d=t.f32s(l),p=t.ibits(l*w,r);i.push(n(l),n(w),f(x),f(d),new Uint8Array(p.buffer,p.byteOffset,p.length));let A=i.reduce((m,b)=>m+b.length,0),I=new Uint8Array(A),M=0;for(let m of i)I.set(m,M),M+=m.length;return I}function X(o){return W(U(o))}function ot(o,e,c,r){let{cout:t,cin:s,k:a,w:y,bias:h}=o,i=c*c,n=a-1>>1,f=s*a*a;for(let l=0;l<t;l++){let w=l*i,x=h[l],d=l*f;for(let p=0;p<c;p++)for(let A=0;A<c;A++){let I=x;for(let M=0;M<s;M++){let m=M*i,b=d+M*a*a;for(let u=0;u<a;u++){let g=p+u-n;if(g<0||g>=c)continue;let k=m+g*c,N=b+u*a;for(let S=0;S<a;S++){let F=A+S-n;F<0||F>=c||(I+=y[N+S]*e[k+F])}}}r[w+p*c+A]=I>0?I:0}}}function rt(o,e,c,r){let t=e>>1;for(let s=0;s<c;s++){let a=s*e*e,y=s*t*t;for(let h=0;h<t;h++)for(let i=0;i<t;i++){let n=a+2*h*e+2*i,f=o[n],l=o[n+1],w=o[n+e],x=o[n+e+1];r[y+h*t+i]=Math.max(f,l,w,x)}}}function q(o,e){let c=o.size,r=Float32Array.from(e),t=c,s=1;for(let n of o.convs){let f=new Float32Array(n.cout*t*t);if(ot(n,r,t,f),r=f,s=n.cout,n.pool){let l=new Float32Array(s*(t>>1)*(t>>1));rt(r,t,s,l),r=l,t>>=1}}let a=t*t,y=new Float32Array(s);for(let n=0;n<s;n++){let f=0;for(let l=0;l<a;l++)f+=r[n*a+l];y[n]=f/a}let{lin:h}=o,i=new Float32Array(h.out);for(let n=0;n<h.out;n++){let f=h.bias[n];for(let l=0;l<h.in;l++)f+=h.w[n*h.in+l]*y[l];i[n]=f}return i}function K(o){let e=0;for(let r=0;r<o.length;r++)e+=o[r]*o[r];e=1/(Math.sqrt(e)+1e-9);let c=new Float32Array(o.length);for(let r=0;r<o.length;r++)c[r]=o[r]*e;return c}function E(o,e){let c=new Float32Array(o.out);for(let r=0;r<o.out;r++){let t=o.bias[r];for(let s=0;s<o.in;s++){let a=e[s];a>0&&(t+=o.w[r*o.in+s]*a)}c[r]=t}return c}function B(o){let e=-1/0;for(let t of o)t>e&&(e=t);let c=new Float32Array(o.length),r=0;for(let t=0;t<o.length;t++)c[t]=Math.exp(o[t]-e),r+=c[t];for(let t=0;t<o.length;t++)c[t]/=r;return c}function Z(o,e,c=120,r=7,t=10){let s=1/0,a=1/0,y=-1/0,h=-1/0;for(let f of e)for(let l of f)l.x<s&&(s=l.x),l.x>y&&(y=l.x),l.y<a&&(a=l.y),l.y>h&&(h=l.y);let i=c/Math.max(y-s,h-a,1),n=c+2*t;o.fillStyle="#fff",o.fillRect(0,0,n,n),o.strokeStyle="#000",o.lineWidth=r,o.lineCap="round",o.lineJoin="round";for(let f of e)if(!(f.length<2)){o.beginPath(),o.moveTo((f[0].x-s)*i+t,(f[0].y-a)*i+t);for(let l=1;l<f.length;l++)o.lineTo((f[l].x-s)*i+t,(f[l].y-a)*i+t);o.stroke()}return n}function V(o,e,c){let r=new Float32Array(e*c);for(let t=0,s=0;t<r.length;t++,s+=4)r[t]=1-(o[s]*.299+o[s+1]*.587+o[s+2]*.114)/255;return r}function J(o,e,c,r=32,t=24){let s=1/0,a=-1,y=1/0,h=-1;for(let u=0;u<c;u++)for(let g=0;g<e;g++)o[u*e+g]>.15&&(g<s&&(s=g),g>a&&(a=g),u<y&&(y=u),u>h&&(h=u));let i=new Float32Array(r*r);if(a<0)return i;let n=a-s+1,f=h-y+1,l=new Float32Array(n*f);for(let u=0;u<f;u++)for(let g=0;g<n;g++)l[u*n+g]=o[(u+y)*e+(g+s)];let w=0;for(let u=0;u<l.length;u++)l[u]>w&&(w=l[u]);if(w>.05&&w<.999)for(let u=0;u<l.length;u++)l[u]=Math.min(1,l[u]/w);let x=t/Math.max(f,n),d=Math.max(1,Math.round(f*x)),p=Math.max(1,Math.round(n*x)),A=new Float32Array(p*d),I=n/p,M=f/d;for(let u=0;u<d;u++){let g=u*M,k=(u+1)*M,N=Math.floor(g),S=Math.min(f,Math.ceil(k));for(let F=0;F<p;F++){let z=F*I,P=(F+1)*I,et=Math.floor(z),nt=Math.min(n,Math.ceil(P)),D=0,L=0;for(let v=N;v<S;v++){let O=Math.min(k,v+1)-Math.max(g,v);if(!(O<=0))for(let C=et;C<nt;C++){let R=Math.min(P,C+1)-Math.max(z,C);R<=0||(D+=l[v*n+C]*R*O,L+=R*O)}}A[u*p+F]=L>0?D/L:0}}let m=r-d>>1,b=r-p>>1;for(let u=0;u<d;u++)for(let g=0;g<p;g++)i[(u+m)*r+g+b]=A[u*p+g];return i}function G(o){let e=o?String(o):"";return e?(e.endsWith("/")||(e+="/"),typeof location<"u"?new URL(e,location.href).href:e):typeof location<"u"?new URL("./",location.href).href:""}var _=o=>Array.isArray(o)&&o.length&&!Array.isArray(o[0])?[o]:o,T=(o,e,c,r)=>new Error(`millirec: ${o} is not ${e} \u2014 the package files are not served at ${c}; copy node_modules/millirec/dist/${r}/ and pass assetBase (see README "Serving the files")`);async function Q(o,{as:e="json",what:c,base:r,recognizer:t}){let s=n=>{let f=T(o,c,r,t);return n&&(f.message+=` (${n})`),f},a;try{a=await fetch(o)}catch(n){throw s(n&&n.message)}let y=a.headers&&a.headers.get("content-type")||"";if(!a.ok)throw s(`HTTP ${a.status}`);if(e==="json")try{return await a.json()}catch(n){throw s(/html/i.test(y)?"an HTML page":n&&n.message)}let h=await a.arrayBuffer(),i=String.fromCharCode(...new Uint8Array(h,0,Math.min(h.byteLength,16))).trimStart().toLowerCase();if(i.startsWith("<!doctype")||i.startsWith("<html"))throw s("an HTML page");return h}function st(){let o=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return o?o.slice(0,o.lastIndexOf("/")+1):""}var it=st(),tt=(o,e)=>Q(o,{as:"buf",what:"a char-cnn model file",base:e,recognizer:"char-cnn"}),at="millirec: recognizer destroyed",ct=o=>typeof document<"u"&&document.createElement?Object.assign(document.createElement("canvas"),{width:o,height:o}):typeof OffscreenCanvas<"u"?new OffscreenCanvas(o,o):null,j=class{static async create(e={}){let r={...(typeof window<"u"?window:globalThis).MILLIREC_CNN||{},...e};if(!r.stages||!r.stages.length)throw new Error("MillirecCharCnn: no stages configured");if(typeof fetch>"u"||typeof document>"u"&&typeof OffscreenCanvas>"u")throw new Error("millirec: char-cnn needs a browser (fetch, and a canvas or OffscreenCanvas); importing is SSR-safe but call create() on the client");let t=new this(r);return await t.ready,t}constructor(e){this.config=e,this.base=G(e.assetBase||it),this.classes=typeof e.classes=="string"?e.classes.split(""):e.classes,this.stages=[],this.off=ct(140),this.octx=this.off?this.off.getContext("2d",{willReadFrequently:!0}):null,this.ready=this.load()}async load(){let{base:e,config:c}=this,r=null;if(c.kernel){let t=e+c.kernel;try{r=(await import(t)).default}catch(s){let a=T(t,"the char-cnn kernel",e,"char-cnn");throw a.message+=` (${s&&s.message})`,a}}for(let t of c.stages){let[s,a]=await Promise.all([tt(e+t.model,e),tt(e+t.head,e)]);if(this.destroyed)return;let y=X(a),h={theta:t.theta==null?null:t.theta,head:y,headNorm:t.headNorm!==!1,size:0};if(r){let i=await r();if(this.destroyed)return;let n=$(new Uint8Array(s)),f=i._malloc(n.byteLength);i.HEAPU8.set(n,f);let l=i._cnnLoad(f,n.byteLength);if(i._free(f),!l)throw new Error(`kernel rejected ${t.model} (channel widths must be multiples of four)`);let w=i._cnnSize(),x=i._cnnDim();h.size=w,h.embed=d=>{let p=i._cnnInputPtr(1)>>2;i.HEAPF32.set(d,p),i._cnnRun(1);let A=i._cnnEmbedPtr(1)>>2;return i.HEAPF32.slice(A,A+x)},h.logits=d=>E(h.head,h.embed(d))}else{let i=Y(s);h.size=i.size,h.embed=n=>{let f=q(i,n);return h.headNorm?K(f):f},h.logits=n=>E(h.head,h.embed(n))}this.stages.push(h)}}raster(e,c){if(!this.octx)throw new Error("millirec: char-cnn needs a canvas to draw strokes on (a document, or OffscreenCanvas in a worker)");if(this._planeFor!==e){let s=Z(this.octx,e);this._plane={ink:V(this.octx.getImageData(0,0,s,s).data,s,s),W:s},this._planeFor=e}let{ink:r,W:t}=this._plane;return J(r,t,t,c,Math.round(c*.75))}async recognize(e,{only:c=null}={}){if(e=_(e),!e||!e.length||(await this.ready,this.destroyed||!this.stages.length))return null;this._planeFor=null;let r=c?new Set(c):null,t=null,s=0;for(let n=0;n<this.stages.length;n++){let f=this.stages[n];if((this.personal||r)&&n<this.stages.length-1)continue;if(t=f.logits(this.raster(e,f.size)),s=n,f.theta==null||n===this.stages.length-1)break;let l=-1/0,w=-1/0;for(let x of t)x>l?(w=l,l=x):x>w&&(w=x);if(l-w>=f.theta)break}let a=[...t.keys()];if(r&&(a=a.filter(n=>r.has(this.classes[n])),!a.length)){let n=[];return n.stage=s,n}let y=B(a.map(n=>t[n])),i=[...y.keys()].sort((n,f)=>y[f]-y[n]).slice(0,3).map(n=>({char:this.classes[a[n]],prob:y[n]}));return i.stage=s,i}async embedding(e){if(e=_(e),await this.ready,this.destroyed||!this.stages.length)throw new Error(at);this._planeFor=null;let c=this.stages[this.stages.length-1];return c.embed(this.raster(e,c.size))}async personalize(e,{steps:c=250,lr:r=.5,prior:t=1}={}){if(await this.ready,this.destroyed||!this.stages.length)return null;let s=this.stages[this.stages.length-1],a=s.head0||(s.head0=s.head),y=[],h=[];for(let[w,x]of Object.entries(e||{})){let d=this.classes.indexOf(w);if(!(d<0))for(let p of x||[]){let A=_(p);!A||!A.length||(y.push(await this.embedding(A)),h.push(d))}}if(this.destroyed)return null;if(!y.length)return s.head=a,this.personal=null,null;let i={in:a.in,out:a.out,w:Float32Array.from(a.w),bias:Float32Array.from(a.bias)},n=y.length,f=new Float32Array(i.w.length),l=new Float32Array(i.out);for(let w=0;w<c;w++){f.fill(0),l.fill(0);for(let d=0;d<n;d++){let p=B(E(i,y[d])),A=y[d];for(let I=0;I<i.out;I++){let M=(p[I]-(I===h[d]?1:0))/n;if(!M)continue;l[I]+=M;let m=I*i.in;for(let b=0;b<i.in;b++){let u=A[b];u>0&&(f[m+b]+=M*u)}}}let x=t/n;for(let d=0;d<i.w.length;d++)i.w[d]-=r*(f[d]+x*(i.w[d]-a.w[d]));for(let d=0;d<i.out;d++)i.bias[d]-=r*(l[d]+x*(i.bias[d]-a.bias[d]))}return s.head=i,this.personal={n,classes:[...new Set(h)].map(w=>this.classes[w]).sort()},this.personal}destroy(){this.destroyed=!0,this.stages=[],this.personal=null,this._plane=null,this._planeFor=null}depersonalize(){let e=this.stages[this.stages.length-1];e&&e.head0&&(e.head=e.head0),this.personal=null}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharCnn=j);})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var $={MRCNN1:8,MRCNN3:3,MRCNN4:4,MRCNN5:5,MRCNN6:6};function W(r){let o=new DataView(r.buffer?r.buffer:r,r.byteOffset||0,r.byteLength),l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),n=0;return{u32:()=>{let t=o.getUint32(n,!0);return n+=4,t},f32s:t=>{let i=new Float32Array(t);for(let a=0;a<t;a++)i[a]=o.getFloat32(n,!0),n+=4;return i},i8s:t=>{let i=new Int8Array(t);for(let a=0;a<t;a++)i[a]=l[n+a]<<24>>24;return n+=t,i},ibits:(t,i)=>{if(i===8){let f=new Int8Array(t);for(let e=0;e<t;e++)f[e]=l[n+e]<<24>>24;return n+=t,f}let a=new Int8Array(t),m=(1<<i)-1,c=1<<i-1;for(let f=0;f<t;f++){let e=f*i,s=n+(e>>3),u=e&7,x=(l[s]|l[s+1]<<8)>>u&m;a[f]=x&c?x-(1<<i):x}return n+=t*i+7>>3,a},str:t=>{let i=String.fromCharCode(...l.subarray(n,n+t));return n+=t,i},done:()=>n>=o.byteLength}}function J(r,o=8){let l=r.u32(),n=r.u32(),t=r.f32s(l),i=r.f32s(l),a=r.ibits(l*n,o),m=new Float32Array(l*n);for(let c=0;c<l;c++)for(let f=0;f<n;f++)m[c*n+f]=a[c*n+f]*t[c];return{out:l,in:n,w:m,bias:i}}function V(r){let o=W(r),l=o.str(6),n=$[l];if(!n)throw new Error("not an MRCNN1/3/4/5/6 model");let t=o.u32();if(t!==1)throw new Error("unknown model version "+t);let i=o.u32(),a=o.u32(),m=o.u32(),c=[];for(let e=0;e<m;e++){let s=o.u32(),u=o.u32(),x=o.u32(),d=o.u32(),g=o.f32s(s),y=o.f32s(s),w=o.ibits(s*u*x*x,n),v=new Float32Array(w.length),A=u*x*x;for(let I=0;I<s;I++)for(let b=0;b<A;b++)v[I*A+b]=w[I*A+b]*g[I];c.push({cout:s,cin:u,k:x,pool:d,w:v,bias:y})}let f=J(o,n);return{size:i,dim:a,convs:c,lin:f,bits:n}}function Q(r){let o=new Uint8Array(r.buffer?r.buffer:r,r.byteOffset||0,r.byteLength),l=String.fromCharCode(...o.subarray(0,6)),n=$[l];if(!n)throw new Error("not an MRCNN model");if(n===8)return o;let t=W(r);t.str(6);let i=t.u32(),a=t.u32(),m=t.u32(),c=t.u32(),f=[],e=I=>{let b=new Uint8Array(4);return new DataView(b.buffer).setUint32(0,I,!0),b},s=I=>new Uint8Array(I.buffer,I.byteOffset,I.byteLength);f.push(new TextEncoder().encode("MRCNN1"),e(i),e(a),e(m),e(c));for(let I=0;I<c;I++){let b=t.u32(),p=t.u32(),M=t.u32(),L=t.u32(),_=t.f32s(b),C=t.f32s(b),k=t.ibits(b*p*M*M,n);f.push(e(b),e(p),e(M),e(L),s(_),s(C),new Uint8Array(k.buffer,k.byteOffset,k.length))}let u=t.u32(),x=t.u32(),d=t.f32s(u),g=t.f32s(u),y=t.ibits(u*x,n);f.push(e(u),e(x),s(d),s(g),new Uint8Array(y.buffer,y.byteOffset,y.length));let w=f.reduce((I,b)=>I+b.length,0),v=new Uint8Array(w),A=0;for(let I of f)v.set(I,A),A+=I.length;return v}function z(r){return J(W(r))}function yt(r,o,l,n){let{cout:t,cin:i,k:a,w:m,bias:c}=r,f=l*l,e=a-1>>1,s=i*a*a;for(let u=0;u<t;u++){let x=u*f,d=c[u],g=u*s;for(let y=0;y<l;y++)for(let w=0;w<l;w++){let v=d;for(let A=0;A<i;A++){let I=A*f,b=g+A*a*a;for(let p=0;p<a;p++){let M=y+p-e;if(M<0||M>=l)continue;let L=I+M*l,_=b+p*a;for(let C=0;C<a;C++){let k=w+C-e;k<0||k>=l||(v+=m[_+C]*o[L+k])}}}n[x+y*l+w]=v>0?v:0}}}function dt(r,o,l,n){let t=o>>1;for(let i=0;i<l;i++){let a=i*o*o,m=i*t*t;for(let c=0;c<t;c++)for(let f=0;f<t;f++){let e=a+2*c*o+2*f,s=r[e],u=r[e+1],x=r[e+o],d=r[e+o+1];n[m+c*t+f]=Math.max(s,u,x,d)}}}function tt(r,o){let l=r.size,n=Float32Array.from(o),t=l,i=1;for(let e of r.convs){let s=new Float32Array(e.cout*t*t);if(yt(e,n,t,s),n=s,i=e.cout,e.pool){let u=new Float32Array(i*(t>>1)*(t>>1));dt(n,t,i,u),n=u,t>>=1}}let a=t*t,m=new Float32Array(i);for(let e=0;e<i;e++){let s=0;for(let u=0;u<a;u++)s+=n[e*a+u];m[e]=s/a}let{lin:c}=r,f=new Float32Array(c.out);for(let e=0;e<c.out;e++){let s=c.bias[e];for(let u=0;u<c.in;u++)s+=c.w[e*c.in+u]*m[u];f[e]=s}return f}function nt(r){let o=0;for(let n=0;n<r.length;n++)o+=r[n]*r[n];o=1/(Math.sqrt(o)+1e-9);let l=new Float32Array(r.length);for(let n=0;n<r.length;n++)l[n]=r[n]*o;return l}function O(r,o){let l=new Float32Array(r.out);for(let n=0;n<r.out;n++){let t=r.bias[n];for(let i=0;i<r.in;i++){let a=o[i];a>0&&(t+=r.w[n*r.in+i]*a)}l[n]=t}return l}function H(r){let o=-1/0;for(let t of r)t>o&&(o=t);let l=new Float32Array(r.length),n=0;for(let t=0;t<r.length;t++)l[t]=Math.exp(r[t]-o),n+=l[t];for(let t=0;t<r.length;t++)l[t]/=n;return l}function et(r,o,l=120,n=7,t=10){let i=1/0,a=1/0,m=-1/0,c=-1/0;for(let s of o)for(let u of s)u.x<i&&(i=u.x),u.x>m&&(m=u.x),u.y<a&&(a=u.y),u.y>c&&(c=u.y);let f=l/Math.max(m-i,c-a,1),e=l+2*t;r.fillStyle="#fff",r.fillRect(0,0,e,e),r.strokeStyle="#000",r.lineWidth=n,r.lineCap="round",r.lineJoin="round";for(let s of o)if(!(s.length<2)){r.beginPath(),r.moveTo((s[0].x-i)*f+t,(s[0].y-a)*f+t);for(let u=1;u<s.length;u++)r.lineTo((s[u].x-i)*f+t,(s[u].y-a)*f+t);r.stroke()}return e}function ot(r,o,l){let n=new Float32Array(o*l);for(let t=0,i=0;t<n.length;t++,i+=4)n[t]=1-(r[i]*.299+r[i+1]*.587+r[i+2]*.114)/255;return n}function rt(r,o,l,n=32,t=24){let i=1/0,a=-1,m=1/0,c=-1;for(let p=0;p<l;p++)for(let M=0;M<o;M++)r[p*o+M]>.15&&(M<i&&(i=M),M>a&&(a=M),p<m&&(m=p),p>c&&(c=p));let f=new Float32Array(n*n);if(a<0)return f;let e=a-i+1,s=c-m+1,u=new Float32Array(e*s);for(let p=0;p<s;p++)for(let M=0;M<e;M++)u[p*e+M]=r[(p+m)*o+(M+i)];let x=0;for(let p=0;p<u.length;p++)u[p]>x&&(x=u[p]);if(x>.05&&x<.999)for(let p=0;p<u.length;p++)u[p]=Math.min(1,u[p]/x);let d=t/Math.max(s,e),g=Math.max(1,Math.round(s*d)),y=Math.max(1,Math.round(e*d)),w=new Float32Array(y*g),v=e/y,A=s/g;for(let p=0;p<g;p++){let M=p*A,L=(p+1)*A,_=Math.floor(M),C=Math.min(s,Math.ceil(L));for(let k=0;k<y;k++){let X=k*v,D=(k+1)*v,P=Math.floor(X),Y=Math.min(e,Math.ceil(D)),U=0,T=0;for(let N=_;N<C;N++){let Z=Math.min(L,N+1)-Math.max(M,N);if(!(Z<=0))for(let h=P;h<Y;h++){let E=Math.min(D,h+1)-Math.max(X,h);E<=0||(U+=u[N*e+h]*E*Z,T+=E*Z)}}w[p*y+k]=T>0?U/T:0}}let I=n-g>>1,b=n-y>>1;for(let p=0;p<g;p++)for(let M=0;M<y;M++)f[(p+I)*n+M+b]=w[p*y+M];return f}function st(r){let o=r?String(r):"";return o?(o.endsWith("/")||(o+="/"),typeof location<"u"?new URL(o,location.href).href:o):typeof location<"u"?new URL("./",location.href).href:""}var j=r=>Array.isArray(r)&&r.length&&!Array.isArray(r[0])?[r]:r;function xt(){let r=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return r?r.slice(0,r.lastIndexOf("/")+1):""}var mt=xt(),it=r=>fetch(r).then(o=>{if(!o.ok)throw new Error(`${r}: ${o.status}`);return o.arrayBuffer()}),B=class{static async create(o={}){let n={...(typeof window<"u"?window:globalThis).MILLIREC_CNN||{},...o};if(!n.stages||!n.stages.length)throw new Error("MillirecCharCnn: no stages configured");let t=new this(n);return await t.ready,t}constructor(o){this.config=o,this.base=st(o.assetBase||mt),this.classes=typeof o.classes=="string"?o.classes.split(""):o.classes,this.stages=[],this.off=typeof document<"u"?document.createElement("canvas"):null,this.off&&(this.off.width=this.off.height=140,this.octx=this.off.getContext("2d",{willReadFrequently:!0})),this.ready=this.load()}async load(){let{base:o,config:l}=this,n=null;l.kernel&&(n=(await import(o+l.kernel)).default);for(let t of l.stages){let[i,a]=await Promise.all([it(o+t.model),it(o+t.head)]),m=z(a),c={theta:t.theta==null?null:t.theta,head:m,headNorm:t.headNorm!==!1,size:0};if(n){let f=await n(),e=Q(new Uint8Array(i)),s=f._malloc(e.byteLength);f.HEAPU8.set(e,s);let u=f._cnnLoad(s,e.byteLength);if(f._free(s),!u)throw new Error(`kernel rejected ${t.model} (channel widths must be multiples of four)`);let x=f._cnnSize(),d=f._cnnDim();c.size=x,c.embed=g=>{let y=f._cnnInputPtr(1)>>2;f.HEAPF32.set(g,y),f._cnnRun(1);let w=f._cnnEmbedPtr(1)>>2;return f.HEAPF32.slice(w,w+d)},c.logits=g=>O(c.head,c.embed(g))}else{let f=V(i);c.size=f.size,c.embed=e=>{let s=tt(f,e);return c.headNorm?nt(s):s},c.logits=e=>O(c.head,c.embed(e))}this.stages.push(c)}}raster(o,l){if(this._planeFor!==o){let i=et(this.octx,o);this._plane={ink:ot(this.octx.getImageData(0,0,i,i).data,i,i),W:i},this._planeFor=o}let{ink:n,W:t}=this._plane;return rt(n,t,t,l,Math.round(l*.75))}async recognize(o,{only:l=null}={}){if(o=j(o),!o||!o.length||(await this.ready,!this.stages.length))return null;this._planeFor=null;let n=l?new Set(l):null,t=null,i=0;for(let e=0;e<this.stages.length;e++){let s=this.stages[e];if((this.personal||n)&&e<this.stages.length-1)continue;if(t=s.logits(this.raster(o,s.size)),i=e,s.theta==null||e===this.stages.length-1)break;let u=-1/0,x=-1/0;for(let d of t)d>u?(x=u,u=d):d>x&&(x=d);if(u-x>=s.theta)break}let a=[...t.keys()];if(n&&(a=a.filter(e=>n.has(this.classes[e])),!a.length)){let e=[];return e.stage=i,e}let m=H(a.map(e=>t[e])),f=[...m.keys()].sort((e,s)=>m[s]-m[e]).slice(0,3).map(e=>({char:this.classes[a[e]],prob:m[e]}));return f.stage=i,f}async embedding(o){o=j(o),await this.ready,this._planeFor=null;let l=this.stages[this.stages.length-1];return l.embed(this.raster(o,l.size))}async personalize(o,{steps:l=250,lr:n=.5,prior:t=1}={}){await this.ready;let i=this.stages[this.stages.length-1],a=i.head0||(i.head0=i.head),m=[],c=[];for(let[x,d]of Object.entries(o||{})){let g=this.classes.indexOf(x);if(!(g<0))for(let y of d||[]){let w=j(y);!w||!w.length||(m.push(await this.embedding(w)),c.push(g))}}if(!m.length)return i.head=a,this.personal=null,null;let f={in:a.in,out:a.out,w:Float32Array.from(a.w),bias:Float32Array.from(a.bias)},e=m.length,s=new Float32Array(f.w.length),u=new Float32Array(f.out);for(let x=0;x<l;x++){s.fill(0),u.fill(0);for(let g=0;g<e;g++){let y=H(O(f,m[g])),w=m[g];for(let v=0;v<f.out;v++){let A=(y[v]-(v===c[g]?1:0))/e;if(!A)continue;u[v]+=A;let I=v*f.in;for(let b=0;b<f.in;b++){let p=w[b];p>0&&(s[I+b]+=A*p)}}}let d=t/e;for(let g=0;g<f.w.length;g++)f.w[g]-=n*(s[g]+d*(f.w[g]-a.w[g]));for(let g=0;g<f.out;g++)f.bias[g]-=n*(u[g]+d*(f.bias[g]-a.bias[g]))}return i.head=f,this.personal={n:e,classes:[...new Set(c)].map(x=>this.classes[x]).sort()},this.personal}destroy(){this.stages=[],this.personal=null,this._plane=null,this._planeFor=null}depersonalize(){let o=this.stages[this.stages.length-1];o.head0&&(o.head=o.head0),this.personal=null}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharCnn=B);var ft={turns:5,retrace:.5,winding:3.5,cover:.6,minLength:40,minSpan:12,deadband:.22},G=2;function at(r){return{x0:r.x0-G,y0:r.y0-G,x1:r.x1+G,y1:r.y1+G,w:r.w+2*G,h:r.h+2*G}}function lt(r){let o=1/0,l=1/0,n=-1/0,t=-1/0;for(let i of r){let a=i.x!==void 0?i.x:i[0],m=i.y!==void 0?i.y:i[1];a<o&&(o=a),a>n&&(n=a),m<l&&(l=m),m>t&&(t=m)}return{x0:o,y0:l,x1:n,y1:t,w:n-o,h:t-l}}function ct(r,o){let l=1/0,n=-1/0;for(let c of r)c<l&&(l=c),c>n&&(n=c);let t=(n-l)*o;if(!(t>0))return 0;let i=0,a=r[0],m=0;for(let c of r)i>0?c>a?a=c:c<a-t&&(m++,i=-1,a=c):i<0?c<a?a=c:c>a+t&&(m++,i=1,a=c):c>a+t?(i=1,a=c):c<a-t&&(i=-1,a=c);return m}function gt(r){let o=0,l=0;for(let u of r)o+=u.x,l+=u.y;o/=r.length,l/=r.length;let n=0,t=0,i=0;for(let u of r){let x=u.x-o,d=u.y-l;n+=x*x,t+=x*d,i+=d*d}let a=n+i,m=n*i-t*t,c=a/2+Math.sqrt(Math.max(0,a*a/4-m)),f=t,e=c-n;Math.hypot(f,e)<1e-9&&(f=1,e=0);let s=Math.hypot(f,e);return{ux:f/s,uy:e/s}}var pt=.09,wt=4;function Mt(r,o){let l=Math.max(2,o*pt),n=l/2,t=[r[0]],i=0;for(let e=1;e<r.length;e++){let s=r[e].x-r[e-1].x,u=r[e].y-r[e-1].y,x=Math.hypot(s,u);if(!(x>0))continue;let d=(n-i)/x;for(;d<=1;)t.push({x:r[e-1].x+s*d,y:r[e-1].y+u*d}),d+=n/x;i=(i+x)%n}if(t.length<8)return 0;let a=Math.round(wt*l/n),m=e=>`${Math.floor(e.x/l)},${Math.floor(e.y/l)}`,c=new Map;t.forEach((e,s)=>{let u=m(e);c.has(u)||c.set(u,[]),c.get(u).push(s)});let f=0;for(let e=0;e<t.length;e++){let s=t[e],u=Math.floor(s.x/l),x=Math.floor(s.y/l),d=!1;for(let g=-1;g<=1&&!d;g++)for(let y=-1;y<=1&&!d;y++)for(let w of c.get(`${u+g},${x+y}`)||[])if(!(Math.abs(e-w)<=a)&&Math.hypot(t[w].x-s.x,t[w].y-s.y)<=l){d=!0;break}d&&f++}return f/t.length}function It(r,o=[],l={}){let n={...ft,...l},t=[];for(let y of r){let w={x:y.x!==void 0?y.x:y[0],y:y.y!==void 0?y.y:y[1]},v=t[t.length-1];(!v||Math.hypot(w.x-v.x,w.y-v.y)>.75)&&t.push(w)}if(t.length<4)return{turns:0,cross:0,retrace:0,winding:0,cover:0,length:0,span:0};let i=0;for(let y=1;y<t.length;y++)i+=Math.hypot(t[y].x-t[y-1].x,t[y].y-t[y-1].y);let a=lt(t),m=Math.hypot(a.w,a.h),{ux:c,uy:f}=gt(t),e=t.map(y=>y.x*c+y.y*f),s=t.map(y=>-y.x*f+y.y*c),u=ct(e,n.deadband),x=ct(s,n.deadband),d=0,g=[];for(let y of o)for(let w of y)g.push(w);if(g.length){let y=at(lt(g)),w=at(a),v=Math.max(0,Math.min(y.x1,w.x1)-Math.max(y.x0,w.x0)),A=Math.max(0,Math.min(y.y1,w.y1)-Math.max(y.y0,w.y0));d=v/Math.min(y.w,w.w)*(A/Math.min(y.h,w.h))}return{turns:u,cross:x,retrace:Mt(t,m),winding:m>0?i/m:0,cover:d,length:i,span:m}}function ut(r,o=[],l={}){let n={...ft,...l};if(!o||!o.length)return!1;let t=It(r,o,n);return t.length>=n.minLength&&t.span>=n.minSpan&&t.turns>=n.turns&&t.retrace>=n.retrace&&t.winding>=n.winding&&t.cover>=n.cover}var bt=12,q=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function ht({width:r=160,height:o=90,ink:l="#111827",onStrokeEnd:n,colorOf:t=null,idleOverwrite:i=0,scribbleClear:a=!1,scribble:m=null,onClear:c=null,staleAlpha:f=.3,onStale:e=null}){let s=document.createElement("canvas"),u=typeof devicePixelRatio<"u"&&devicePixelRatio||1;s.width=r*u,s.height=o*u,s.style.width=r+"px",s.style.height=o+"px",s.style.touchAction="none";let x=s.getContext("2d");x.scale(u,u);let d=[],g=[],y=null,w=!1,v=1,A=0,I=0,b=!1,p=null,M=!1;function L(h,E){if(!(h.length<2)){x.strokeStyle=E||l,x.beginPath(),x.moveTo(h[0].x,h[0].y);for(let S=1;S<h.length;S++)x.lineTo(h[S].x,h[S].y);x.stroke()}}function _(){x.clearRect(0,0,r,o),x.lineWidth=2.5,x.lineCap="round",x.lineJoin="round",x.globalAlpha=b?f:1;for(let h of d)L(h,t&&t(h));x.globalAlpha=1,L(g,null)}function C(h){b!==h&&(b=h,_(),e&&e(h))}function k(){clearTimeout(I),I=0;let h=(Number(i)||0)*1e3;if(!h||!d.length){C(!1);return}let E=h-(q()-A);if(E<=0){C(!0);return}C(!1),I=setTimeout(()=>C(!0),E)}function X(h){d.length&&(p=d,d=[],clearTimeout(I),I=0,C(!1),_(),c&&c(h))}function D(h,E){let S=d.filter(F=>!F.some(R=>Math.hypot(R.x-h,R.y-E)<=bt));return S.length===d.length?!1:(d=S,_(),!0)}let P=null,Y=h=>{let E=P||(P=s.getBoundingClientRect()),S=r/(s.clientWidth||r),F=o/(s.clientHeight||o);return{x:(h.clientX-E.left-s.clientLeft)*S,y:(h.clientY-E.top-s.clientTop)*F,p:h.pressure||.5}},U=!1,T=null,N=h=>h.preventDefault();s.addEventListener("touchstart",N,{passive:!1}),s.addEventListener("touchmove",N,{passive:!1}),s.addEventListener("contextmenu",N),s.style.userSelect=s.style.webkitUserSelect="none",s.style.webkitTouchCallout="none",s.addEventListener("pointerdown",h=>{if(h.button>0)return;if(y!==null&&y!==h.pointerId){if(T==="pen"&&h.pointerType!=="pen")return;Z({pointerId:y})}h.preventDefault(),y=h.pointerId,T=h.pointerType,P=s.getBoundingClientRect();try{s.setPointerCapture(h.pointerId)}catch{}let E=Y(h);if(w){U=D(E.x,E.y);return}b&&d.length&&(X("idle"),M=!0),g=[E],_()},{passive:!1}),s.addEventListener("pointermove",h=>{if(y!==h.pointerId)return;h.preventDefault();let E=h.getCoalescedEvents?h.getCoalescedEvents():null,S=E&&E.length?E:[h];if(w){for(let F of S){let R=Y(F);D(R.x,R.y)&&(U=!0)}return}for(let F of S)g.push(Y(F));_()},{passive:!1});let Z=(h,E=!1)=>{if(y===h.pointerId){try{s.releasePointerCapture(h.pointerId)}catch{}if(y=null,T=null,P=null,w){U&&(A=q(),k(),n&&n(d)),U=!1;return}if(g.length>0){let S=g;if(S.length===1){if(E){g=[],_(),M&&(M=!1,n&&n(d));return}let R=S[0];S=[{x:R.x-1,y:R.y,p:R.p},{x:R.x+1,y:R.y,p:R.p}]}let F=d.length?d:M?p:null;if(a&&F&&F.length&&ut(S,F,m||{})){g=[],A=q(),M=!1,d.length?X("scribble"):(_(),c&&c("scribble")),n&&n(d);return}S.id=v++,d=[...d,S],g=[],M=!1,A=q(),k(),n&&n(d)}_()}};return s.addEventListener("pointerup",h=>Z(h)),s.addEventListener("pointercancel",h=>Z(h,!0)),{el:s,getStrokes:()=>d,setInk(h){l=h,_()},setErasing(h){w=!!h,s.style.cursor=w?"cell":"crosshair"},isErasing:()=>w,repaint:_,isStale:()=>b,undoClear(){return!p||!p.length?!1:(d=d.length?[...p,...d]:p,p=null,A=q(),k(),_(),n&&n(d),!0)},configure(h={}){"idleOverwrite"in h&&(i=Number(h.idleOverwrite)||0),"scribbleClear"in h&&(a=!!h.scribbleClear),"scribble"in h&&(m=h.scribble),"staleAlpha"in h&&(f=Number(h.staleAlpha)),k()},clear(){d=[],g=[],y=null,T=null,P=null,clearTimeout(I),I=0,C(!1),M=!1,_(),n&&n(d)}}}var K=class extends B{attach(o,{width:l=240,height:n=240,ink:t="#1e293b",idleOverwrite:i=2,scribbleClear:a=!0,scribble:m=null,staleAlpha:c,onStale:f}={}){let e=ht({width:l,height:n,ink:t,idleOverwrite:i,scribbleClear:a,scribble:m,onStale:f,...c===void 0?{}:{staleAlpha:c},onClear:s=>o.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:s,undo:()=>e.undoClear()}})),onStrokeEnd:async s=>{if(!s.length){o.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let u=await this.recognize(s);o.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:u,strokes:s}}))}});return o.appendChild(e.el),{clear:e.clear,undoClear:e.undoClear,isStale:e.isStale,configure:e.configure,setInk:e.setInk,repaint:e.repaint,getStrokes:e.getStrokes,canvas:e.el}}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharCnn=K);})();
|
|
1
|
+
"use strict";(()=>{var J={MRCNN1:8,MRCNN3:3,MRCNN4:4,MRCNN5:5,MRCNN6:6};function q(o){let r=new DataView(o.buffer?o.buffer:o,o.byteOffset||0,o.byteLength),l=new Uint8Array(r.buffer,r.byteOffset,r.byteLength),n=0;return{u32:()=>{let t=r.getUint32(n,!0);return n+=4,t},f32s:t=>{let s=new Float32Array(t);for(let a=0;a<t;a++)s[a]=r.getFloat32(n,!0),n+=4;return s},i8s:t=>{let s=new Int8Array(t);for(let a=0;a<t;a++)s[a]=l[n+a]<<24>>24;return n+=t,s},ibits:(t,s)=>{if(s===8){let f=new Int8Array(t);for(let e=0;e<t;e++)f[e]=l[n+e]<<24>>24;return n+=t,f}let a=new Int8Array(t),p=(1<<s)-1,c=1<<s-1;for(let f=0;f<t;f++){let e=f*s,i=n+(e>>3),u=e&7,g=(l[i]|l[i+1]<<8)>>u&p;a[f]=g&c?g-(1<<s):g}return n+=t*s+7>>3,a},str:t=>{let s=String.fromCharCode(...l.subarray(n,n+t));return n+=t,s},done:()=>n>=r.byteLength}}function V(o,r=8){let l=o.u32(),n=o.u32(),t=o.f32s(l),s=o.f32s(l),a=o.ibits(l*n,r),p=new Float32Array(l*n);for(let c=0;c<l;c++)for(let f=0;f<n;f++)p[c*n+f]=a[c*n+f]*t[c];return{out:l,in:n,w:p,bias:s}}function G(o){let r=q(o),l=r.str(6),n=J[l];if(!n)throw new Error("not an MRCNN1/3/4/5/6 model");let t=r.u32();if(t!==1)throw new Error("unknown model version "+t);let s=r.u32(),a=r.u32(),p=r.u32(),c=[];for(let e=0;e<p;e++){let i=r.u32(),u=r.u32(),g=r.u32(),y=r.u32(),m=r.f32s(i),d=r.f32s(i),w=r.ibits(i*u*g*g,n),I=new Float32Array(w.length),A=u*g*g;for(let M=0;M<i;M++)for(let v=0;v<A;v++)I[M*A+v]=w[M*A+v]*m[M];c.push({cout:i,cin:u,k:g,pool:y,w:I,bias:d})}let f=V(r,n);return{size:s,dim:a,convs:c,lin:f,bits:n}}function Q(o){let r=new Uint8Array(o.buffer?o.buffer:o,o.byteOffset||0,o.byteLength),l=String.fromCharCode(...r.subarray(0,6)),n=J[l];if(!n)throw new Error("not an MRCNN model");if(n===8)return r;let t=q(o);t.str(6);let s=t.u32(),a=t.u32(),p=t.u32(),c=t.u32(),f=[],e=M=>{let v=new Uint8Array(4);return new DataView(v.buffer).setUint32(0,M,!0),v},i=M=>new Uint8Array(M.buffer,M.byteOffset,M.byteLength);f.push(new TextEncoder().encode("MRCNN1"),e(s),e(a),e(p),e(c));for(let M=0;M<c;M++){let v=t.u32(),x=t.u32(),b=t.u32(),N=t.u32(),S=t.f32s(v),k=t.f32s(v),F=t.ibits(v*x*b*b,n);f.push(e(v),e(x),e(b),e(N),i(S),i(k),new Uint8Array(F.buffer,F.byteOffset,F.length))}let u=t.u32(),g=t.u32(),y=t.f32s(u),m=t.f32s(u),d=t.ibits(u*g,n);f.push(e(u),e(g),i(y),i(m),new Uint8Array(d.buffer,d.byteOffset,d.length));let w=f.reduce((M,v)=>M+v.length,0),I=new Uint8Array(w),A=0;for(let M of f)I.set(M,A),A+=M.length;return I}function tt(o){return V(q(o))}function pt(o,r,l,n){let{cout:t,cin:s,k:a,w:p,bias:c}=o,f=l*l,e=a-1>>1,i=s*a*a;for(let u=0;u<t;u++){let g=u*f,y=c[u],m=u*i;for(let d=0;d<l;d++)for(let w=0;w<l;w++){let I=y;for(let A=0;A<s;A++){let M=A*f,v=m+A*a*a;for(let x=0;x<a;x++){let b=d+x-e;if(b<0||b>=l)continue;let N=M+b*l,S=v+x*a;for(let k=0;k<a;k++){let F=w+k-e;F<0||F>=l||(I+=p[S+k]*r[N+F])}}}n[g+d*l+w]=I>0?I:0}}}function gt(o,r,l,n){let t=r>>1;for(let s=0;s<l;s++){let a=s*r*r,p=s*t*t;for(let c=0;c<t;c++)for(let f=0;f<t;f++){let e=a+2*c*r+2*f,i=o[e],u=o[e+1],g=o[e+r],y=o[e+r+1];n[p+c*t+f]=Math.max(i,u,g,y)}}}function et(o,r){let l=o.size,n=Float32Array.from(r),t=l,s=1;for(let e of o.convs){let i=new Float32Array(e.cout*t*t);if(pt(e,n,t,i),n=i,s=e.cout,e.pool){let u=new Float32Array(s*(t>>1)*(t>>1));gt(n,t,s,u),n=u,t>>=1}}let a=t*t,p=new Float32Array(s);for(let e=0;e<s;e++){let i=0;for(let u=0;u<a;u++)i+=n[e*a+u];p[e]=i/a}let{lin:c}=o,f=new Float32Array(c.out);for(let e=0;e<c.out;e++){let i=c.bias[e];for(let u=0;u<c.in;u++)i+=c.w[e*c.in+u]*p[u];f[e]=i}return f}function nt(o){let r=0;for(let n=0;n<o.length;n++)r+=o[n]*o[n];r=1/(Math.sqrt(r)+1e-9);let l=new Float32Array(o.length);for(let n=0;n<o.length;n++)l[n]=o[n]*r;return l}function Y(o,r){let l=new Float32Array(o.out);for(let n=0;n<o.out;n++){let t=o.bias[n];for(let s=0;s<o.in;s++){let a=r[s];a>0&&(t+=o.w[n*o.in+s]*a)}l[n]=t}return l}function z(o){let r=-1/0;for(let t of o)t>r&&(r=t);let l=new Float32Array(o.length),n=0;for(let t=0;t<o.length;t++)l[t]=Math.exp(o[t]-r),n+=l[t];for(let t=0;t<o.length;t++)l[t]/=n;return l}function ot(o,r,l=120,n=7,t=10){let s=1/0,a=1/0,p=-1/0,c=-1/0;for(let i of r)for(let u of i)u.x<s&&(s=u.x),u.x>p&&(p=u.x),u.y<a&&(a=u.y),u.y>c&&(c=u.y);let f=l/Math.max(p-s,c-a,1),e=l+2*t;o.fillStyle="#fff",o.fillRect(0,0,e,e),o.strokeStyle="#000",o.lineWidth=n,o.lineCap="round",o.lineJoin="round";for(let i of r)if(!(i.length<2)){o.beginPath(),o.moveTo((i[0].x-s)*f+t,(i[0].y-a)*f+t);for(let u=1;u<i.length;u++)o.lineTo((i[u].x-s)*f+t,(i[u].y-a)*f+t);o.stroke()}return e}function rt(o,r,l){let n=new Float32Array(r*l);for(let t=0,s=0;t<n.length;t++,s+=4)n[t]=1-(o[s]*.299+o[s+1]*.587+o[s+2]*.114)/255;return n}function st(o,r,l,n=32,t=24){let s=1/0,a=-1,p=1/0,c=-1;for(let x=0;x<l;x++)for(let b=0;b<r;b++)o[x*r+b]>.15&&(b<s&&(s=b),b>a&&(a=b),x<p&&(p=x),x>c&&(c=x));let f=new Float32Array(n*n);if(a<0)return f;let e=a-s+1,i=c-p+1,u=new Float32Array(e*i);for(let x=0;x<i;x++)for(let b=0;b<e;b++)u[x*e+b]=o[(x+p)*r+(b+s)];let g=0;for(let x=0;x<u.length;x++)u[x]>g&&(g=u[x]);if(g>.05&&g<.999)for(let x=0;x<u.length;x++)u[x]=Math.min(1,u[x]/g);let y=t/Math.max(i,e),m=Math.max(1,Math.round(i*y)),d=Math.max(1,Math.round(e*y)),w=new Float32Array(d*m),I=e/d,A=i/m;for(let x=0;x<m;x++){let b=x*A,N=(x+1)*A,S=Math.floor(b),k=Math.min(i,Math.ceil(N));for(let F=0;F<d;F++){let B=F*I,j=(F+1)*I,P=Math.floor(B),H=Math.min(e,Math.ceil(j)),O=0,T=0;for(let R=S;R<k;R++){let D=Math.min(N,R+1)-Math.max(b,R);if(!(D<=0))for(let h=P;h<H;h++){let C=Math.min(j,h+1)-Math.max(B,h);C<=0||(O+=u[R*e+h]*C*D,T+=C*D)}}w[x*d+F]=T>0?O/T:0}}let M=n-m>>1,v=n-d>>1;for(let x=0;x<m;x++)for(let b=0;b<d;b++)f[(x+M)*n+b+v]=w[x*d+b];return f}function it(o){let r=o?String(o):"";return r?(r.endsWith("/")||(r+="/"),typeof location<"u"?new URL(r,location.href).href:r):typeof location<"u"?new URL("./",location.href).href:""}var X=o=>Array.isArray(o)&&o.length&&!Array.isArray(o[0])?[o]:o,K=(o,r,l,n)=>new Error(`millirec: ${o} is not ${r} \u2014 the package files are not served at ${l}; copy node_modules/millirec/dist/${n}/ and pass assetBase (see README "Serving the files")`);async function at(o,{as:r="json",what:l,base:n,recognizer:t}){let s=e=>{let i=K(o,l,n,t);return e&&(i.message+=` (${e})`),i},a;try{a=await fetch(o)}catch(e){throw s(e&&e.message)}let p=a.headers&&a.headers.get("content-type")||"";if(!a.ok)throw s(`HTTP ${a.status}`);if(r==="json")try{return await a.json()}catch(e){throw s(/html/i.test(p)?"an HTML page":e&&e.message)}let c=await a.arrayBuffer(),f=String.fromCharCode(...new Uint8Array(c,0,Math.min(c.byteLength,16))).trimStart().toLowerCase();if(f.startsWith("<!doctype")||f.startsWith("<html"))throw s("an HTML page");return c}function mt(){let o=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return o?o.slice(0,o.lastIndexOf("/")+1):""}var xt=mt(),lt=(o,r)=>at(o,{as:"buf",what:"a char-cnn model file",base:r,recognizer:"char-cnn"}),wt="millirec: recognizer destroyed",bt=o=>typeof document<"u"&&document.createElement?Object.assign(document.createElement("canvas"),{width:o,height:o}):typeof OffscreenCanvas<"u"?new OffscreenCanvas(o,o):null,$=class{static async create(r={}){let n={...(typeof window<"u"?window:globalThis).MILLIREC_CNN||{},...r};if(!n.stages||!n.stages.length)throw new Error("MillirecCharCnn: no stages configured");if(typeof fetch>"u"||typeof document>"u"&&typeof OffscreenCanvas>"u")throw new Error("millirec: char-cnn needs a browser (fetch, and a canvas or OffscreenCanvas); importing is SSR-safe but call create() on the client");let t=new this(n);return await t.ready,t}constructor(r){this.config=r,this.base=it(r.assetBase||xt),this.classes=typeof r.classes=="string"?r.classes.split(""):r.classes,this.stages=[],this.off=bt(140),this.octx=this.off?this.off.getContext("2d",{willReadFrequently:!0}):null,this.ready=this.load()}async load(){let{base:r,config:l}=this,n=null;if(l.kernel){let t=r+l.kernel;try{n=(await import(t)).default}catch(s){let a=K(t,"the char-cnn kernel",r,"char-cnn");throw a.message+=` (${s&&s.message})`,a}}for(let t of l.stages){let[s,a]=await Promise.all([lt(r+t.model,r),lt(r+t.head,r)]);if(this.destroyed)return;let p=tt(a),c={theta:t.theta==null?null:t.theta,head:p,headNorm:t.headNorm!==!1,size:0};if(n){let f=await n();if(this.destroyed)return;let e=Q(new Uint8Array(s)),i=f._malloc(e.byteLength);f.HEAPU8.set(e,i);let u=f._cnnLoad(i,e.byteLength);if(f._free(i),!u)throw new Error(`kernel rejected ${t.model} (channel widths must be multiples of four)`);let g=f._cnnSize(),y=f._cnnDim();c.size=g,c.embed=m=>{let d=f._cnnInputPtr(1)>>2;f.HEAPF32.set(m,d),f._cnnRun(1);let w=f._cnnEmbedPtr(1)>>2;return f.HEAPF32.slice(w,w+y)},c.logits=m=>Y(c.head,c.embed(m))}else{let f=G(s);c.size=f.size,c.embed=e=>{let i=et(f,e);return c.headNorm?nt(i):i},c.logits=e=>Y(c.head,c.embed(e))}this.stages.push(c)}}raster(r,l){if(!this.octx)throw new Error("millirec: char-cnn needs a canvas to draw strokes on (a document, or OffscreenCanvas in a worker)");if(this._planeFor!==r){let s=ot(this.octx,r);this._plane={ink:rt(this.octx.getImageData(0,0,s,s).data,s,s),W:s},this._planeFor=r}let{ink:n,W:t}=this._plane;return st(n,t,t,l,Math.round(l*.75))}async recognize(r,{only:l=null}={}){if(r=X(r),!r||!r.length||(await this.ready,this.destroyed||!this.stages.length))return null;this._planeFor=null;let n=l?new Set(l):null,t=null,s=0;for(let e=0;e<this.stages.length;e++){let i=this.stages[e];if((this.personal||n)&&e<this.stages.length-1)continue;if(t=i.logits(this.raster(r,i.size)),s=e,i.theta==null||e===this.stages.length-1)break;let u=-1/0,g=-1/0;for(let y of t)y>u?(g=u,u=y):y>g&&(g=y);if(u-g>=i.theta)break}let a=[...t.keys()];if(n&&(a=a.filter(e=>n.has(this.classes[e])),!a.length)){let e=[];return e.stage=s,e}let p=z(a.map(e=>t[e])),f=[...p.keys()].sort((e,i)=>p[i]-p[e]).slice(0,3).map(e=>({char:this.classes[a[e]],prob:p[e]}));return f.stage=s,f}async embedding(r){if(r=X(r),await this.ready,this.destroyed||!this.stages.length)throw new Error(wt);this._planeFor=null;let l=this.stages[this.stages.length-1];return l.embed(this.raster(r,l.size))}async personalize(r,{steps:l=250,lr:n=.5,prior:t=1}={}){if(await this.ready,this.destroyed||!this.stages.length)return null;let s=this.stages[this.stages.length-1],a=s.head0||(s.head0=s.head),p=[],c=[];for(let[g,y]of Object.entries(r||{})){let m=this.classes.indexOf(g);if(!(m<0))for(let d of y||[]){let w=X(d);!w||!w.length||(p.push(await this.embedding(w)),c.push(m))}}if(this.destroyed)return null;if(!p.length)return s.head=a,this.personal=null,null;let f={in:a.in,out:a.out,w:Float32Array.from(a.w),bias:Float32Array.from(a.bias)},e=p.length,i=new Float32Array(f.w.length),u=new Float32Array(f.out);for(let g=0;g<l;g++){i.fill(0),u.fill(0);for(let m=0;m<e;m++){let d=z(Y(f,p[m])),w=p[m];for(let I=0;I<f.out;I++){let A=(d[I]-(I===c[m]?1:0))/e;if(!A)continue;u[I]+=A;let M=I*f.in;for(let v=0;v<f.in;v++){let x=w[v];x>0&&(i[M+v]+=A*x)}}}let y=t/e;for(let m=0;m<f.w.length;m++)f.w[m]-=n*(i[m]+y*(f.w[m]-a.w[m]));for(let m=0;m<f.out;m++)f.bias[m]-=n*(u[m]+y*(f.bias[m]-a.bias[m]))}return s.head=f,this.personal={n:e,classes:[...new Set(c)].map(g=>this.classes[g]).sort()},this.personal}destroy(){this.destroyed=!0,this.stages=[],this.personal=null,this._plane=null,this._planeFor=null}depersonalize(){let r=this.stages[this.stages.length-1];r&&r.head0&&(r.head=r.head0),this.personal=null}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharCnn=$);var ht={turns:5,retrace:.5,winding:3.5,cover:.6,minLength:40,minSpan:12,deadband:.22},U=2;function ct(o){return{x0:o.x0-U,y0:o.y0-U,x1:o.x1+U,y1:o.y1+U,w:o.w+2*U,h:o.h+2*U}}function ft(o){let r=1/0,l=1/0,n=-1/0,t=-1/0;for(let s of o){let a=s.x!==void 0?s.x:s[0],p=s.y!==void 0?s.y:s[1];a<r&&(r=a),a>n&&(n=a),p<l&&(l=p),p>t&&(t=p)}return{x0:r,y0:l,x1:n,y1:t,w:n-r,h:t-l}}function ut(o,r){let l=1/0,n=-1/0;for(let c of o)c<l&&(l=c),c>n&&(n=c);let t=(n-l)*r;if(!(t>0))return 0;let s=0,a=o[0],p=0;for(let c of o)s>0?c>a?a=c:c<a-t&&(p++,s=-1,a=c):s<0?c<a?a=c:c>a+t&&(p++,s=1,a=c):c>a+t?(s=1,a=c):c<a-t&&(s=-1,a=c);return p}function Mt(o){let r=0,l=0;for(let u of o)r+=u.x,l+=u.y;r/=o.length,l/=o.length;let n=0,t=0,s=0;for(let u of o){let g=u.x-r,y=u.y-l;n+=g*g,t+=g*y,s+=y*y}let a=n+s,p=n*s-t*t,c=a/2+Math.sqrt(Math.max(0,a*a/4-p)),f=t,e=c-n;Math.hypot(f,e)<1e-9&&(f=1,e=0);let i=Math.hypot(f,e);return{ux:f/i,uy:e/i}}var vt=.09,It=4;function At(o,r){let l=Math.max(2,r*vt),n=l/2,t=[o[0]],s=0;for(let e=1;e<o.length;e++){let i=o[e].x-o[e-1].x,u=o[e].y-o[e-1].y,g=Math.hypot(i,u);if(!(g>0))continue;let y=(n-s)/g;for(;y<=1;)t.push({x:o[e-1].x+i*y,y:o[e-1].y+u*y}),y+=n/g;s=(s+g)%n}if(t.length<8)return 0;let a=Math.round(It*l/n),p=e=>`${Math.floor(e.x/l)},${Math.floor(e.y/l)}`,c=new Map;t.forEach((e,i)=>{let u=p(e);c.has(u)||c.set(u,[]),c.get(u).push(i)});let f=0;for(let e=0;e<t.length;e++){let i=t[e],u=Math.floor(i.x/l),g=Math.floor(i.y/l),y=!1;for(let m=-1;m<=1&&!y;m++)for(let d=-1;d<=1&&!y;d++)for(let w of c.get(`${u+m},${g+d}`)||[])if(!(Math.abs(e-w)<=a)&&Math.hypot(t[w].x-i.x,t[w].y-i.y)<=l){y=!0;break}y&&f++}return f/t.length}function Ct(o,r=[],l={}){let n={...ht,...l},t=[];for(let d of o){let w={x:d.x!==void 0?d.x:d[0],y:d.y!==void 0?d.y:d[1]},I=t[t.length-1];(!I||Math.hypot(w.x-I.x,w.y-I.y)>.75)&&t.push(w)}if(t.length<4)return{turns:0,cross:0,retrace:0,winding:0,cover:0,length:0,span:0};let s=0;for(let d=1;d<t.length;d++)s+=Math.hypot(t[d].x-t[d-1].x,t[d].y-t[d-1].y);let a=ft(t),p=Math.hypot(a.w,a.h),{ux:c,uy:f}=Mt(t),e=t.map(d=>d.x*c+d.y*f),i=t.map(d=>-d.x*f+d.y*c),u=ut(e,n.deadband),g=ut(i,n.deadband),y=0,m=[];for(let d of r)for(let w of d)m.push(w);if(m.length){let d=ct(ft(m)),w=ct(a),I=Math.max(0,Math.min(d.x1,w.x1)-Math.max(d.x0,w.x0)),A=Math.max(0,Math.min(d.y1,w.y1)-Math.max(d.y0,w.y0));y=I/Math.min(d.w,w.w)*(A/Math.min(d.h,w.h))}return{turns:u,cross:g,retrace:At(t,p),winding:p>0?s/p:0,cover:y,length:s,span:p}}function dt(o,r=[],l={}){let n={...ht,...l};if(!r||!r.length)return!1;let t=Ct(o,r,n);return t.length>=n.minLength&&t.span>=n.minSpan&&t.turns>=n.turns&&t.retrace>=n.retrace&&t.winding>=n.winding&&t.cover>=n.cover}var Et=12,W=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function yt({width:o=160,height:r=90,ink:l="#111827",onStrokeEnd:n,colorOf:t=null,idleOverwrite:s=0,scribbleClear:a=!1,scribble:p=null,onClear:c=null,staleAlpha:f=.3,onStale:e=null}){let i=document.createElement("canvas"),u=typeof devicePixelRatio<"u"&&devicePixelRatio||1;i.width=o*u,i.height=r*u,i.style.width=o+"px",i.style.height=r+"px",i.style.touchAction="none";let g=i.getContext("2d");g.scale(u,u);let y=[],m=[],d=null,w=!1,I=1,A=0,M=0,v=!1,x=null,b=!1;function N(h,C){if(!(h.length<2)){g.strokeStyle=C||l,g.beginPath(),g.moveTo(h[0].x,h[0].y);for(let E=1;E<h.length;E++)g.lineTo(h[E].x,h[E].y);g.stroke()}}function S(){g.clearRect(0,0,o,r),g.lineWidth=2.5,g.lineCap="round",g.lineJoin="round",g.globalAlpha=v?f:1;for(let h of y)N(h,t&&t(h));g.globalAlpha=1,N(m,null)}function k(h){v!==h&&(v=h,S(),e&&e(h))}function F(){clearTimeout(M),M=0;let h=(Number(s)||0)*1e3;if(!h||!y.length){k(!1);return}let C=h-(W()-A);if(C<=0){k(!0);return}k(!1),M=setTimeout(()=>k(!0),C)}function B(h){y.length&&(x=y,y=[],clearTimeout(M),M=0,k(!1),S(),c&&c(h))}function j(h,C){let E=y.filter(L=>!L.some(_=>Math.hypot(_.x-h,_.y-C)<=Et));return E.length===y.length?!1:(y=E,S(),!0)}let P=null,H=h=>{let C=P||(P=i.getBoundingClientRect()),E=o/(i.clientWidth||o),L=r/(i.clientHeight||r);return{x:(h.clientX-C.left-i.clientLeft)*E,y:(h.clientY-C.top-i.clientTop)*L,p:h.pressure||.5}},O=!1,T=null,R=h=>h.preventDefault();i.addEventListener("touchstart",R,{passive:!1}),i.addEventListener("touchmove",R,{passive:!1}),i.addEventListener("contextmenu",R),i.style.userSelect=i.style.webkitUserSelect="none",i.style.webkitTouchCallout="none",i.addEventListener("pointerdown",h=>{if(h.button>0)return;if(d!==null&&d!==h.pointerId){if(T==="pen"&&h.pointerType!=="pen")return;D({pointerId:d})}h.preventDefault(),d=h.pointerId,T=h.pointerType,P=i.getBoundingClientRect();try{i.setPointerCapture(h.pointerId)}catch{}let C=H(h);if(w){O=j(C.x,C.y);return}v&&y.length&&(B("idle"),b=!0),m=[C],S()},{passive:!1}),i.addEventListener("pointermove",h=>{if(d!==h.pointerId)return;h.preventDefault();let C=h.getCoalescedEvents?h.getCoalescedEvents():null,E=C&&C.length?C:[h];if(w){for(let L of E){let _=H(L);j(_.x,_.y)&&(O=!0)}return}for(let L of E)m.push(H(L));S()},{passive:!1});let D=(h,C=!1)=>{if(d===h.pointerId){try{i.releasePointerCapture(h.pointerId)}catch{}if(d=null,T=null,P=null,w){O&&(A=W(),F(),n&&n(y)),O=!1;return}if(m.length>0){let E=m;if(E.length===1){if(C){m=[],S(),b&&(b=!1,n&&n(y));return}let _=E[0];E=[{x:_.x-1,y:_.y,p:_.p},{x:_.x+1,y:_.y,p:_.p}]}let L=y.length?y:b?x:null;if(a&&L&&L.length&&dt(E,L,p||{})){m=[],A=W(),b=!1,y.length?B("scribble"):(S(),c&&c("scribble")),n&&n(y);return}E.id=I++,y=[...y,E],m=[],b=!1,A=W(),F(),n&&n(y)}S()}};return i.addEventListener("pointerup",h=>D(h)),i.addEventListener("pointercancel",h=>D(h,!0)),{el:i,getStrokes:()=>y,setInk(h){l=h,S()},setErasing(h){w=!!h,i.style.cursor=w?"cell":"crosshair"},isErasing:()=>w,repaint:S,isStale:()=>v,undoClear(){return!x||!x.length?!1:(y=y.length?[...x,...y]:x,x=null,A=W(),F(),S(),n&&n(y),!0)},configure(h={}){"idleOverwrite"in h&&(s=Number(h.idleOverwrite)||0),"scribbleClear"in h&&(a=!!h.scribbleClear),"scribble"in h&&(p=h.scribble),"staleAlpha"in h&&(f=Number(h.staleAlpha)),F()},clear(){y=[],m=[],d=null,T=null,P=null,clearTimeout(M),M=0,k(!1),b=!1,S(),n&&n(y)}}}var Z=class extends ${attach(r,{width:l=240,height:n=240,ink:t="#1e293b",idleOverwrite:s=2,scribbleClear:a=!0,scribble:p=null,staleAlpha:c,onStale:f}={}){let e=yt({width:l,height:n,ink:t,idleOverwrite:s,scribbleClear:a,scribble:p,onStale:f,...c===void 0?{}:{staleAlpha:c},onClear:i=>r.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:i,undo:()=>e.undoClear()}})),onStrokeEnd:async i=>{if(!i.length){r.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let u=await this.recognize(i);r.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:u,strokes:i}}))}});return r.appendChild(e.el),{clear:e.clear,undoClear:e.undoClear,isStale:e.isStale,configure:e.configure,setInk:e.setInk,repaint:e.repaint,getStrokes:e.getStrokes,canvas:e.el}}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharCnn=Z);})();
|
|
@@ -6,10 +6,13 @@ export type Strokes = Stroke[]
|
|
|
6
6
|
export interface Sample { x: number[]; y: number[] }
|
|
7
7
|
export interface Reading { char: string; prob: number }
|
|
8
8
|
|
|
9
|
-
/** v2 training data (core/format/schema.js). v1 `{ class: Sample[] }` is also accepted.
|
|
9
|
+
/** v2 training data (core/format/schema.js). v1 `{ class: Sample[] }` is also accepted.
|
|
10
|
+
* `version` and `mode` are wide (number, string) so a set imported as JSON type-checks. */
|
|
10
11
|
export interface Training {
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
/** 2 */
|
|
13
|
+
version: number
|
|
14
|
+
/** 'stroke' | 'image' | 'both' */
|
|
15
|
+
mode?: 'stroke' | 'image' | 'both' | (string & {})
|
|
13
16
|
pointsPerShape?: number
|
|
14
17
|
classes: Record<string, { samples: Sample[]; geometry?: unknown }>
|
|
15
18
|
params?: Record<string, number>
|
|
@@ -27,11 +30,14 @@ export interface CreateOptions {
|
|
|
27
30
|
}
|
|
28
31
|
|
|
29
32
|
export interface AttachOptions {
|
|
33
|
+
/** Pad size in CSS px (default 240 x 240). */
|
|
30
34
|
width?: number
|
|
31
35
|
height?: number
|
|
36
|
+
/** Ink colour (default '#1e293b'). */
|
|
32
37
|
ink?: string
|
|
33
|
-
/** Seconds of pen-up after which the next stroke starts a new character (0 = off). */
|
|
38
|
+
/** Seconds of pen-up after which the next stroke starts a new character (default 2; 0 = off). */
|
|
34
39
|
idleOverwrite?: number
|
|
40
|
+
/** Scribbling over the character throws it away (default true). */
|
|
35
41
|
scribbleClear?: boolean
|
|
36
42
|
/** Overrides for the scribble-out detector's bars (turns, retrace, winding, cover). */
|
|
37
43
|
scribble?: Record<string, number> | null
|
|
@@ -53,6 +59,18 @@ export interface Pad {
|
|
|
53
59
|
canvas: HTMLCanvasElement
|
|
54
60
|
}
|
|
55
61
|
|
|
62
|
+
/** `millirec:result` — after every stroke (and with empty results when the pad empties). */
|
|
63
|
+
export interface ResultDetail { results: Reading[] | null; strokes: Strokes }
|
|
64
|
+
/** `millirec:clear` — the pad dropped its own ink: 'idle' (idleOverwrite) or 'scribble'. `undo()` puts it back. */
|
|
65
|
+
export interface ClearDetail { reason: 'idle' | 'scribble'; undo: () => boolean }
|
|
66
|
+
|
|
67
|
+
declare global {
|
|
68
|
+
interface HTMLElementEventMap {
|
|
69
|
+
'millirec:result': CustomEvent<ResultDetail>
|
|
70
|
+
'millirec:clear': CustomEvent<ClearDetail>
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
56
74
|
export declare const SETS: readonly ['all', 'capitals', 'digits', 'lowercase', 'punctuation']
|
|
57
75
|
export type SetName = (typeof SETS)[number]
|
|
58
76
|
|
|
@@ -68,10 +86,14 @@ export declare class MillirecCharLite {
|
|
|
68
86
|
static createDrawCanvas(opts?: object): unknown
|
|
69
87
|
readonly charList: string[]
|
|
70
88
|
readonly ready: Promise<void>
|
|
89
|
+
/** null for an empty drawing, and after destroy(). */
|
|
71
90
|
recognize(strokes: Strokes | Stroke): Promise<Reading[] | null>
|
|
72
91
|
/** Raw per-template costs: costs[i] holds one cost per training sample of classes[i] (lower is closer). */
|
|
73
92
|
rawScores(strokes: Strokes | Stroke): Promise<{ classes: string[]; costs: number[][] } | null>
|
|
74
93
|
use(plugin: { rerank?: (out: unknown, ctx: unknown) => unknown }): this
|
|
94
|
+
/** Mount a drawing pad in `el`; `el` then fires 'millirec:result' and 'millirec:clear'. */
|
|
75
95
|
attach(el: HTMLElement, opts?: AttachOptions): Pad
|
|
96
|
+
/** Stop the instance's Worker (each instance holds one, plus a wasm matcher). Pending and later
|
|
97
|
+
* recognize()/rawScores() calls resolve null. */
|
|
76
98
|
destroy(): void
|
|
77
99
|
}
|
package/dist/char-lite/index.js
CHANGED
|
@@ -632,6 +632,33 @@ function assetBaseOf(base) {
|
|
|
632
632
|
if (!s.endsWith("/")) s += "/";
|
|
633
633
|
return typeof location !== "undefined" ? new URL(s, location.href).href : s;
|
|
634
634
|
}
|
|
635
|
+
var notServed = (url2, what, base, recognizer) => new Error(`millirec: ${url2} is not ${what} \u2014 the package files are not served at ${base}; copy node_modules/millirec/dist/${recognizer}/ and pass assetBase (see README "Serving the files")`);
|
|
636
|
+
async function fetchAsset(url2, { as = "json", what, base, recognizer }) {
|
|
637
|
+
const fail = (detail) => {
|
|
638
|
+
const e = notServed(url2, what, base, recognizer);
|
|
639
|
+
if (detail) e.message += ` (${detail})`;
|
|
640
|
+
return e;
|
|
641
|
+
};
|
|
642
|
+
let r;
|
|
643
|
+
try {
|
|
644
|
+
r = await fetch(url2);
|
|
645
|
+
} catch (e) {
|
|
646
|
+
throw fail(e && e.message);
|
|
647
|
+
}
|
|
648
|
+
const type = r.headers && r.headers.get("content-type") || "";
|
|
649
|
+
if (!r.ok) throw fail(`HTTP ${r.status}`);
|
|
650
|
+
if (as === "json") {
|
|
651
|
+
try {
|
|
652
|
+
return await r.json();
|
|
653
|
+
} catch (e) {
|
|
654
|
+
throw fail(/html/i.test(type) ? "an HTML page" : e && e.message);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
const buf = await r.arrayBuffer();
|
|
658
|
+
const head = String.fromCharCode(...new Uint8Array(buf, 0, Math.min(buf.byteLength, 16))).trimStart().toLowerCase();
|
|
659
|
+
if (head.startsWith("<!doctype") || head.startsWith("<html")) throw fail("an HTML page");
|
|
660
|
+
return buf;
|
|
661
|
+
}
|
|
635
662
|
|
|
636
663
|
// ../../library/src/char-lite.js
|
|
637
664
|
function scriptBase() {
|
|
@@ -639,6 +666,7 @@ function scriptBase() {
|
|
|
639
666
|
return src ? src.slice(0, src.lastIndexOf("/") + 1) : "";
|
|
640
667
|
}
|
|
641
668
|
var ASSET_BASE = scriptBase();
|
|
669
|
+
var CACHE_MAX = 256;
|
|
642
670
|
var StrokeWorker = class {
|
|
643
671
|
constructor({ assetBase, workerName, training, params }) {
|
|
644
672
|
assetBase = assetBaseOf(assetBase);
|
|
@@ -661,7 +689,13 @@ var StrokeWorker = class {
|
|
|
661
689
|
this.readyReject = reject;
|
|
662
690
|
});
|
|
663
691
|
this.worker.onmessage = (evt) => this.onMessage(evt);
|
|
664
|
-
|
|
692
|
+
const workerUrl = assetBase + workerName;
|
|
693
|
+
this.worker.onerror = (evt) => {
|
|
694
|
+
const e = notServed(workerUrl, "the char-lite worker", assetBase, "char-lite");
|
|
695
|
+
e.message += ` (${evt.message || "script failed to load"})`;
|
|
696
|
+
this.readyReject(e);
|
|
697
|
+
};
|
|
698
|
+
this.assetBase = assetBase;
|
|
665
699
|
}
|
|
666
700
|
onMessage(evt) {
|
|
667
701
|
const d = evt.data;
|
|
@@ -681,7 +715,9 @@ var StrokeWorker = class {
|
|
|
681
715
|
});
|
|
682
716
|
this.readyResolve();
|
|
683
717
|
} else if (d.type === "addResult" && d.result) {
|
|
718
|
+
this.cache.delete(d.path);
|
|
684
719
|
this.cache.set(d.path, d.result);
|
|
720
|
+
if (this.cache.size > CACHE_MAX) this.cache.delete(this.cache.keys().next().value);
|
|
685
721
|
const waiters = this.inFlight.get(d.path) || [];
|
|
686
722
|
this.inFlight.delete(d.path);
|
|
687
723
|
for (const resolve of waiters) resolve(this.applyPlugins(d.result, d.path));
|
|
@@ -690,7 +726,9 @@ var StrokeWorker = class {
|
|
|
690
726
|
this.allWaiters.delete(d.path);
|
|
691
727
|
for (const resolve of waiters) resolve(d.costs);
|
|
692
728
|
} else if (d.type === "bootError") {
|
|
693
|
-
this.
|
|
729
|
+
const e = notServed(this.assetBase + "millirec.wasm", "the char-lite matcher", this.assetBase, "char-lite");
|
|
730
|
+
e.message += ` (worker boot failed: ${d.message})`;
|
|
731
|
+
this.readyReject(e);
|
|
694
732
|
}
|
|
695
733
|
}
|
|
696
734
|
applyPlugins(raw, path) {
|
|
@@ -713,10 +751,16 @@ var StrokeWorker = class {
|
|
|
713
751
|
return "strokes:" + flat.length + ":" + hash.toString(36);
|
|
714
752
|
}
|
|
715
753
|
async recognize(strokes) {
|
|
716
|
-
if (!strokes || !strokes.length) return null;
|
|
754
|
+
if (this.destroyed || !strokes || !strokes.length) return null;
|
|
717
755
|
await this.readyPromise;
|
|
756
|
+
if (this.destroyed) return null;
|
|
718
757
|
const key = this.keyFor(strokes);
|
|
719
|
-
if (this.cache.has(key))
|
|
758
|
+
if (this.cache.has(key)) {
|
|
759
|
+
const hit = this.cache.get(key);
|
|
760
|
+
this.cache.delete(key);
|
|
761
|
+
this.cache.set(key, hit);
|
|
762
|
+
return this.applyPlugins(hit, key);
|
|
763
|
+
}
|
|
720
764
|
if (!this.uploadTest(strokes)) return null;
|
|
721
765
|
return new Promise((resolve) => {
|
|
722
766
|
let timer;
|
|
@@ -733,7 +777,9 @@ var StrokeWorker = class {
|
|
|
733
777
|
});
|
|
734
778
|
}
|
|
735
779
|
async rawScores(strokes) {
|
|
780
|
+
if (this.destroyed) return null;
|
|
736
781
|
await this.readyPromise;
|
|
782
|
+
if (this.destroyed) return null;
|
|
737
783
|
if (!this.uploadTest(strokes)) return null;
|
|
738
784
|
const key = "all:" + ++this.reqCounter;
|
|
739
785
|
const costs = await new Promise((resolve) => {
|
|
@@ -748,12 +794,21 @@ var StrokeWorker = class {
|
|
|
748
794
|
});
|
|
749
795
|
return costs ? { classes: this.charList, costs } : null;
|
|
750
796
|
}
|
|
797
|
+
/** Stop the worker; anything still waiting gets null, and so does every later call. */
|
|
751
798
|
destroy() {
|
|
799
|
+
if (this.destroyed) return;
|
|
800
|
+
this.destroyed = true;
|
|
752
801
|
this.worker.terminate();
|
|
753
802
|
if (this.bootUrl) {
|
|
754
803
|
URL.revokeObjectURL(this.bootUrl);
|
|
755
804
|
this.bootUrl = null;
|
|
756
805
|
}
|
|
806
|
+
for (const map of [this.inFlight, this.allWaiters]) {
|
|
807
|
+
for (const list of map.values()) for (const done of list) done(null);
|
|
808
|
+
map.clear();
|
|
809
|
+
}
|
|
810
|
+
this.cache.clear();
|
|
811
|
+
this.readyResolve();
|
|
757
812
|
}
|
|
758
813
|
};
|
|
759
814
|
var toPairs = (parsed) => parsed ? parsed.chars.map((c, i) => ({ char: c, prob: parsed.probs[i] })) : null;
|
|
@@ -800,6 +855,9 @@ var MillirecCharLite = class {
|
|
|
800
855
|
const config = { ...g.MILLIREC_CONFIG || {}, ...opts };
|
|
801
856
|
const training = opts.training || g.MILLIREC_TRAINING;
|
|
802
857
|
if (!training) throw new Error("MillirecCharLite: no training data (training.js missing?)");
|
|
858
|
+
if (typeof Worker === "undefined" || typeof Blob === "undefined") {
|
|
859
|
+
throw new Error("millirec: char-lite needs a browser (Worker, fetch, canvas); importing is SSR-safe but call create() on the client");
|
|
860
|
+
}
|
|
803
861
|
const inst = new this(config, training);
|
|
804
862
|
await inst.ready;
|
|
805
863
|
return inst;
|
|
@@ -869,15 +927,25 @@ if (typeof window !== "undefined" && false) {
|
|
|
869
927
|
if (!window.MillirecChar) window.MillirecChar = MillirecCharLite;
|
|
870
928
|
}
|
|
871
929
|
|
|
930
|
+
// src/here.js
|
|
931
|
+
var url = (import.meta.url || "").replace(/[?#].*$/, "");
|
|
932
|
+
var HERE = url.slice(0, url.lastIndexOf("/") + 1);
|
|
933
|
+
function nodeFileUrl(url2, spec) {
|
|
934
|
+
const g = globalThis;
|
|
935
|
+
const node = typeof g.process !== "undefined" && g.process.versions && g.process.versions.node && typeof g.Deno === "undefined" && typeof g.Bun === "undefined";
|
|
936
|
+
if (url2.startsWith("file:") && node && typeof document === "undefined" && typeof WorkerGlobalScope === "undefined") {
|
|
937
|
+
throw new Error(`millirec: cannot fetch ${url2} outside a browser \u2014 in Node, import the JSON instead: import x from '${spec}' with { type: 'json' }`);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
|
|
872
941
|
// src/char-lite.js
|
|
873
|
-
var HERE = new URL("./", import.meta.url).href;
|
|
874
942
|
var SETS = ["all", "capitals", "digits", "lowercase", "punctuation"];
|
|
875
943
|
async function loadSet(name, { assetBase = HERE } = {}) {
|
|
876
944
|
if (!SETS.includes(name)) throw new Error(`millirec: no training set "${name}" (one of ${SETS.join(", ")})`);
|
|
877
|
-
const
|
|
878
|
-
const
|
|
879
|
-
|
|
880
|
-
return
|
|
945
|
+
const base = assetBaseOf(assetBase);
|
|
946
|
+
const url2 = new URL(`sets/${name}.json`, base).href;
|
|
947
|
+
nodeFileUrl(url2, `millirec/char-lite/sets/${name}.json`);
|
|
948
|
+
return fetchAsset(url2, { what: `the ${name} training set`, base, recognizer: "char-lite" });
|
|
881
949
|
}
|
|
882
950
|
var MillirecCharLite2 = class extends MillirecCharLite {
|
|
883
951
|
/** As the script-tag create(), but `training` is required (no window.MILLIREC_TRAINING)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(()=>{var ct={image:{margin:.6884,mag:.6846,bias:-1.0768},imageGeom:{margin:.6925,mag:1.0731,bias:-2.4927}};function lt(n,t,{margin:e,mag:o,bias:r}){return n<1e-9?.99:1/(1+Math.exp(-(e*Math.log(Math.max(t,1e-9)/n)-o*Math.log(n)-r)))}function z(n,t,e,o=1e3){let r=[];for(let p=0;p<3;p++)r.push(t[n[2*p]]);let i=ct[e];if(i){let p=[n[1],n[3],n[5]],c=p.map((f,m)=>{let x=1/0;for(let u=0;u<3;u++)u!==m&&(x=Math.min(x,p[u]));return lt(f,x,i)});return{chars:r,probs:c}}let s=Math.max(n[1],o/1e3),l=Math.exp(-1*o/s);for(let p=0;p<3;p++)l+=Math.exp(-1*n[2*p+1]/s);let a=[];for(let p=0;p<3;p++)a.push(Math.exp(-1*n[2*p+1]/s)/l);return{chars:r,probs:a}}function X(n){let t=[],e=0,o=0;for(let r=0;r<n.x.length;r++)e+=n.x[r],o+=n.y[r],t.push({x:e,y:o});return t}function tt(n){let t=[],e=[],o=[0,0];for(let r=0;r<n.length;r++){let i=Math.round(n[r].x),s=Math.round(n[r].y);t.push(r===0?i:i-o[0]),e.push(r===0?s:s-o[1]),o=[i,s]}return{x:t,y:e}}function Y(n){let t=n.length,e=[0,0],o=[0,0],r=[];for(let c=0;c<t;c++){let f=n[c];e[0]+=f.x,e[1]+=f.y;let m={x:f.x,y:f.y,a:1.570795};c>0&&f.x!==o[0]&&(m.a=Math.atan2(f.y-o[1],f.x-o[0])),m.s=Math.sin(m.a),m.c=Math.cos(m.a),c===1&&(r[0].s=m.s,r[0].c=m.c),o=[f.x,f.y],r.push(m)}e[0]/=t,e[1]/=t;let i=[0,0],s=[0,0],l=[0,0],a=[0,0];for(let c of r)c.x<e[0]?(l[0]+=c.x-e[0],l[1]++):(a[0]+=c.x-e[0],a[1]++),c.y<e[1]?(i[0]+=c.y-e[1],i[1]++):(s[0]+=c.y-e[1],s[1]++),c.x-=e[0],c.y-=e[1];i[1]>0&&(i[0]/=i[1]),s[1]>0&&(s[0]/=s[1]),l[1]>0&&(l[0]/=l[1]),a[1]>0&&(a[0]/=a[1]);let p=s[0]-i[0]<a[0]-l[0]?100/(a[0]-l[0]):i[0]<s[0]?100/(s[0]-i[0]):1;return{points:r,scale:p}}function N(n,t=50){let e=[],o=0;for(let s of n)for(let l=1;l<s.length;l++){let a=s[l].x-s[l-1].x,p=s[l].y-s[l-1].y,c=Math.sqrt(a*a+p*p);e.push({ax:s[l-1].x,ay:s[l-1].y,bx:s[l].x,by:s[l].y,cumStart:o,cumEnd:o+c}),o+=c}if(!o||!e.length)return null;let r=[],i=0;for(let s=0;s<t;s++){let l=s*o/(t-1);for(;i<e.length-1&&e[i].cumEnd<l;)i++;let a=e[i],p=a.cumEnd-a.cumStart,c=p?Math.min(1,Math.max(0,(l-a.cumStart)/p)):0;r.push({x:a.ax+(a.bx-a.ax)*c,y:a.ay+(a.by-a.ay)*c})}return r}function V(n){return tt(n)}var ft=n=>Array.isArray(n),ht=n=>ft(n)?n.every(t=>typeof t?.x=="number"&&typeof t?.y=="number"):Array.isArray(n?.x)&&Array.isArray(n?.y)&&n.x.length===n.y.length;function ut(n){return!!n&&typeof n=="object"&&!n.version&&!n.classes&&Object.values(n).every(Array.isArray)}function pt(n,{mode:t="both"}={}){let e={};for(let[o,r]of Object.entries(n))e[o]={samples:r,geometry:null};return{version:2,mode:t,pointsPerShape:50,classes:e,ext:{}}}function yt(n){let t=[];if(!n||typeof n!="object")return["not an object"];if((typeof n.version!="number"||n.version<2)&&t.push("bad version"),!n.classes||typeof n.classes!="object"||!Object.keys(n.classes).length)return t.push("no classes"),t;for(let[e,o]of Object.entries(n.classes)){if(!Array.isArray(o?.samples)||!o.samples.length){t.push(`class ${e}: no samples`);continue}o.samples.forEach((i,s)=>{ht(i)||t.push(`class ${e} sample ${s}: bad shape`)});let r=o.geometry;r!=null&&typeof r!="object"&&t.push(`class ${e}: bad geometry`)}return n.wordList!=null&&!Array.isArray(n.wordList)&&t.push("bad wordList"),n.params!=null&&typeof n.params!="object"&&t.push("bad params"),t}function W(n){let t=ut(n)?pt(n):n,e=yt(t);if(e.length)throw new Error("invalid training data: "+e.join("; "));return t.mode||(t.mode="both"),t.pointsPerShape||(t.pointsPerShape=50),t.ext||(t.ext={}),t}function et(n){let t={};for(let[e,o]of Object.entries(n.classes))t[e]=o.samples;return t}var st={turns:5,retrace:.5,winding:3.5,cover:.6,minLength:40,minSpan:12,deadband:.22},C=2;function nt(n){return{x0:n.x0-C,y0:n.y0-C,x1:n.x1+C,y1:n.y1+C,w:n.w+2*C,h:n.h+2*C}}function rt(n){let t=1/0,e=1/0,o=-1/0,r=-1/0;for(let i of n){let s=i.x!==void 0?i.x:i[0],l=i.y!==void 0?i.y:i[1];s<t&&(t=s),s>o&&(o=s),l<e&&(e=l),l>r&&(r=l)}return{x0:t,y0:e,x1:o,y1:r,w:o-t,h:r-e}}function ot(n,t){let e=1/0,o=-1/0;for(let a of n)a<e&&(e=a),a>o&&(o=a);let r=(o-e)*t;if(!(r>0))return 0;let i=0,s=n[0],l=0;for(let a of n)i>0?a>s?s=a:a<s-r&&(l++,i=-1,s=a):i<0?a<s?s=a:a>s+r&&(l++,i=1,s=a):a>s+r?(i=1,s=a):a<s-r&&(i=-1,s=a);return l}function mt(n){let t=0,e=0;for(let m of n)t+=m.x,e+=m.y;t/=n.length,e/=n.length;let o=0,r=0,i=0;for(let m of n){let x=m.x-t,u=m.y-e;o+=x*x,r+=x*u,i+=u*u}let s=o+i,l=o*i-r*r,a=s/2+Math.sqrt(Math.max(0,s*s/4-l)),p=r,c=a-o;Math.hypot(p,c)<1e-9&&(p=1,c=0);let f=Math.hypot(p,c);return{ux:p/f,uy:c/f}}var xt=.09,dt=4;function gt(n,t){let e=Math.max(2,t*xt),o=e/2,r=[n[0]],i=0;for(let c=1;c<n.length;c++){let f=n[c].x-n[c-1].x,m=n[c].y-n[c-1].y,x=Math.hypot(f,m);if(!(x>0))continue;let u=(o-i)/x;for(;u<=1;)r.push({x:n[c-1].x+f*u,y:n[c-1].y+m*u}),u+=o/x;i=(i+x)%o}if(r.length<8)return 0;let s=Math.round(dt*e/o),l=c=>`${Math.floor(c.x/e)},${Math.floor(c.y/e)}`,a=new Map;r.forEach((c,f)=>{let m=l(c);a.has(m)||a.set(m,[]),a.get(m).push(f)});let p=0;for(let c=0;c<r.length;c++){let f=r[c],m=Math.floor(f.x/e),x=Math.floor(f.y/e),u=!1;for(let w=-1;w<=1&&!u;w++)for(let y=-1;y<=1&&!u;y++)for(let d of a.get(`${m+w},${x+y}`)||[])if(!(Math.abs(c-d)<=s)&&Math.hypot(r[d].x-f.x,r[d].y-f.y)<=e){u=!0;break}u&&p++}return p/r.length}function Mt(n,t=[],e={}){let o={...st,...e},r=[];for(let y of n){let d={x:y.x!==void 0?y.x:y[0],y:y.y!==void 0?y.y:y[1]},E=r[r.length-1];(!E||Math.hypot(d.x-E.x,d.y-E.y)>.75)&&r.push(d)}if(r.length<4)return{turns:0,cross:0,retrace:0,winding:0,cover:0,length:0,span:0};let i=0;for(let y=1;y<r.length;y++)i+=Math.hypot(r[y].x-r[y-1].x,r[y].y-r[y-1].y);let s=rt(r),l=Math.hypot(s.w,s.h),{ux:a,uy:p}=mt(r),c=r.map(y=>y.x*a+y.y*p),f=r.map(y=>-y.x*p+y.y*a),m=ot(c,o.deadband),x=ot(f,o.deadband),u=0,w=[];for(let y of t)for(let d of y)w.push(d);if(w.length){let y=nt(rt(w)),d=nt(s),E=Math.max(0,Math.min(y.x1,d.x1)-Math.max(y.x0,d.x0)),v=Math.max(0,Math.min(y.y1,d.y1)-Math.max(y.y0,d.y0));u=E/Math.min(y.w,d.w)*(v/Math.min(y.h,d.h))}return{turns:m,cross:x,retrace:gt(r,l),winding:l>0?i/l:0,cover:u,length:i,span:l}}function it(n,t=[],e={}){let o={...st,...e};if(!t||!t.length)return!1;let r=Mt(n,t,o);return r.length>=o.minLength&&r.span>=o.minSpan&&r.turns>=o.turns&&r.retrace>=o.retrace&&r.winding>=o.winding&&r.cover>=o.cover}var wt=12,T=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function $({width:n=160,height:t=90,ink:e="#111827",onStrokeEnd:o,colorOf:r=null,idleOverwrite:i=0,scribbleClear:s=!1,scribble:l=null,onClear:a=null,staleAlpha:p=.3,onStale:c=null}){let f=document.createElement("canvas"),m=typeof devicePixelRatio<"u"&&devicePixelRatio||1;f.width=n*m,f.height=t*m,f.style.width=n+"px",f.style.height=t+"px",f.style.touchAction="none";let x=f.getContext("2d");x.scale(m,m);let u=[],w=[],y=null,d=!1,E=1,v=0,A=0,L=!1,P=null,k=!1;function K(h,g){if(!(h.length<2)){x.strokeStyle=g||e,x.beginPath(),x.moveTo(h[0].x,h[0].y);for(let M=1;M<h.length;M++)x.lineTo(h[M].x,h[M].y);x.stroke()}}function I(){x.clearRect(0,0,n,t),x.lineWidth=2.5,x.lineCap="round",x.lineJoin="round",x.globalAlpha=L?p:1;for(let h of u)K(h,r&&r(h));x.globalAlpha=1,K(w,null)}function R(h){L!==h&&(L=h,I(),c&&c(h))}function O(){clearTimeout(A),A=0;let h=(Number(i)||0)*1e3;if(!h||!u.length){R(!1);return}let g=h-(T()-v);if(g<=0){R(!0);return}R(!1),A=setTimeout(()=>R(!0),g)}function J(h){u.length&&(P=u,u=[],clearTimeout(A),A=0,R(!1),I(),a&&a(h))}function Q(h,g){let M=u.filter(S=>!S.some(b=>Math.hypot(b.x-h,b.y-g)<=wt));return M.length===u.length?!1:(u=M,I(),!0)}let _=null,D=h=>{let g=_||(_=f.getBoundingClientRect()),M=n/(f.clientWidth||n),S=t/(f.clientHeight||t);return{x:(h.clientX-g.left-f.clientLeft)*M,y:(h.clientY-g.top-f.clientTop)*S,p:h.pressure||.5}},G=!1,U=null,F=h=>h.preventDefault();f.addEventListener("touchstart",F,{passive:!1}),f.addEventListener("touchmove",F,{passive:!1}),f.addEventListener("contextmenu",F),f.style.userSelect=f.style.webkitUserSelect="none",f.style.webkitTouchCallout="none",f.addEventListener("pointerdown",h=>{if(h.button>0)return;if(y!==null&&y!==h.pointerId){if(U==="pen"&&h.pointerType!=="pen")return;q({pointerId:y})}h.preventDefault(),y=h.pointerId,U=h.pointerType,_=f.getBoundingClientRect();try{f.setPointerCapture(h.pointerId)}catch{}let g=D(h);if(d){G=Q(g.x,g.y);return}L&&u.length&&(J("idle"),k=!0),w=[g],I()},{passive:!1}),f.addEventListener("pointermove",h=>{if(y!==h.pointerId)return;h.preventDefault();let g=h.getCoalescedEvents?h.getCoalescedEvents():null,M=g&&g.length?g:[h];if(d){for(let S of M){let b=D(S);Q(b.x,b.y)&&(G=!0)}return}for(let S of M)w.push(D(S));I()},{passive:!1});let q=(h,g=!1)=>{if(y===h.pointerId){try{f.releasePointerCapture(h.pointerId)}catch{}if(y=null,U=null,_=null,d){G&&(v=T(),O(),o&&o(u)),G=!1;return}if(w.length>0){let M=w;if(M.length===1){if(g){w=[],I(),k&&(k=!1,o&&o(u));return}let b=M[0];M=[{x:b.x-1,y:b.y,p:b.p},{x:b.x+1,y:b.y,p:b.p}]}let S=u.length?u:k?P:null;if(s&&S&&S.length&&it(M,S,l||{})){w=[],v=T(),k=!1,u.length?J("scribble"):(I(),a&&a("scribble")),o&&o(u);return}M.id=E++,u=[...u,M],w=[],k=!1,v=T(),O(),o&&o(u)}I()}};return f.addEventListener("pointerup",h=>q(h)),f.addEventListener("pointercancel",h=>q(h,!0)),{el:f,getStrokes:()=>u,setInk(h){e=h,I()},setErasing(h){d=!!h,f.style.cursor=d?"cell":"crosshair"},isErasing:()=>d,repaint:I,isStale:()=>L,undoClear(){return!P||!P.length?!1:(u=u.length?[...P,...u]:P,P=null,v=T(),O(),I(),o&&o(u),!0)},configure(h={}){"idleOverwrite"in h&&(i=Number(h.idleOverwrite)||0),"scribbleClear"in h&&(s=!!h.scribbleClear),"scribble"in h&&(l=h.scribble),"staleAlpha"in h&&(p=Number(h.staleAlpha)),O()},clear(){u=[],w=[],y=null,U=null,_=null,clearTimeout(A),A=0,R(!1),k=!1,I(),o&&o(u)}}}function at(n){let t=n?String(n):"";return t?(t.endsWith("/")||(t+="/"),typeof location<"u"?new URL(t,location.href).href:t):typeof location<"u"?new URL("./",location.href).href:""}function It(){let n=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return n?n.slice(0,n.lastIndexOf("/")+1):""}var bt=It(),H=class{constructor({assetBase:t,workerName:e,training:o,params:r}){t=at(t);let i=W(o);this.trainPaths=et(i),this.charList=Object.keys(this.trainPaths),this.samplesPerChar=Math.max(1,...this.charList.map(l=>this.trainPaths[l].length)),this.pointsPerShape=i.pointsPerShape||50,this.params=r||i.params||null,this.plugins=[],this.cache=new Map,this.inFlight=new Map,this.allWaiters=new Map,this.reqCounter=0;let s=`self.__MILLIREC_ASSET_BASE=${JSON.stringify(t)};importScripts(${JSON.stringify(t+e)});`;this.bootUrl=URL.createObjectURL(new Blob([s],{type:"text/javascript"})),this.worker=new Worker(this.bootUrl),this.readyPromise=new Promise((l,a)=>{this.readyResolve=l,this.readyReject=a}),this.worker.onmessage=l=>this.onMessage(l),this.worker.onerror=l=>this.readyReject(new Error("millirec worker error: "+(l.message||"script failed to load")))}onMessage(t){let e=t.data;if(this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null),e.type==="getCharList")this.params&&this.worker.postMessage({type:"setParams",params:this.params}),this.worker.postMessage({type:"charList",charList:this.charList,pointsPerShape:this.pointsPerShape,samplesPerChar:this.samplesPerChar});else if(e.type==="prepAll")this.charList.forEach((o,r)=>{this.trainPaths[o].forEach((i,s)=>{let{points:l,scale:a}=Y(X(i));this.worker.postMessage({type:"addPoints",points:l,m:r*this.samplesPerChar+s,scale:a})})}),this.readyResolve();else if(e.type==="addResult"&&e.result){this.cache.set(e.path,e.result);let o=this.inFlight.get(e.path)||[];this.inFlight.delete(e.path);for(let r of o)r(this.applyPlugins(e.result,e.path))}else if(e.type==="allResult"){let o=this.allWaiters.get(e.path)||[];this.allWaiters.delete(e.path);for(let r of o)r(e.costs)}else e.type==="bootError"&&this.readyReject(new Error("millirec worker boot failed: "+e.message))}applyPlugins(t,e){let o=z(t,this.charList,"stroke",1e3);for(let r of this.plugins)r.rerank&&(o=r.rerank(o,{raw:t,path:e,charList:this.charList,mode:"stroke",recognizer:this})||o);return o}uploadTest(t){let e=Array.isArray(t[0])?t:[t],o=N(e,this.pointsPerShape);if(!o)return!1;let{points:r,scale:i}=Y(o);return this.worker.postMessage({type:"addPoints",points:r,m:-1,scale:i}),!0}keyFor(t){let e=Array.isArray(t[0])?t.flat():t,o=5381;for(let r of e)o=(o*33^(r.x*7919+r.y|0))>>>0;return"strokes:"+e.length+":"+o.toString(36)}async recognize(t){if(!t||!t.length)return null;await this.readyPromise;let e=this.keyFor(t);return this.cache.has(e)?this.applyPlugins(this.cache.get(e),e):this.uploadTest(t)?new Promise(o=>{let r,i=s=>{clearTimeout(r),o(s)};this.inFlight.has(e)?this.inFlight.get(e).push(i):(this.inFlight.set(e,[i]),this.worker.postMessage({type:"compare",path:e,elementID:"req"+ ++this.reqCounter})),r=setTimeout(()=>i(null),4e3)}):null}async rawScores(t){if(await this.readyPromise,!this.uploadTest(t))return null;let e="all:"+ ++this.reqCounter,o=await new Promise(r=>{let i,s=l=>{clearTimeout(i),r(l)};this.allWaiters.set(e,[s]),this.worker.postMessage({type:"compareAll",path:e,counts:this.charList.map(l=>this.trainPaths[l].length)}),i=setTimeout(()=>s(null),8e3)});return o?{classes:this.charList,costs:o}:null}destroy(){this.worker.terminate(),this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null)}},St=n=>n?n.chars.map((t,e)=>({char:t,prob:n.probs[e]})):null,Z=class{static strokesToSample(t,e=50){let o=N(Array.isArray(t[0])?t:[t],e);return o?V(o):null}static withSamples(t,e,{replace:o=!1}={}){let r=W({...t}),i=r.pointsPerShape,s=a=>{let p=Array.isArray(a)?Array.isArray(a[0])?a:[a]:[X(a)],c=N(p,i);return c?V(c):null},l={...r.classes};for(let[a,p]of Object.entries(e||{})){let c=(p||[]).map(s).filter(Boolean);if(!c.length)continue;let f=l[a]?.samples||[];l[a]={...l[a]||{},samples:o?c:f.concat(c)}}return{...r,classes:l}}static createDrawCanvas(t){return $(t)}static async create(t={}){let e=typeof window<"u"?window:globalThis,o={...e.MILLIREC_CONFIG||{},...t},r=t.training||e.MILLIREC_TRAINING;if(!r)throw new Error("MillirecCharLite: no training data (training.js missing?)");let i=new this(o,r);return await i.ready,i}constructor(t,e){this.config=t,this.stroke=new H({assetBase:t.assetBase||bt,workerName:t.workerStroke||"worker-stroke.js",training:e,params:t.params?.stroke||t.params||null}),this.charList=this.stroke.charList,this.ready=this.stroke.readyPromise}use(t){return this.stroke.plugins.push(t),this}async recognize(t){return St(await this.stroke.recognize(t))}rawScores(t){return this.stroke.rawScores(t)}attach(t,{width:e=240,height:o=240,ink:r="#1e293b",idleOverwrite:i=2,scribbleClear:s=!0,scribble:l=null,staleAlpha:a,onStale:p}={}){let c=$({width:e,height:o,ink:r,idleOverwrite:i,scribbleClear:s,scribble:l,onStale:p,...a===void 0?{}:{staleAlpha:a},onClear:f=>t.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:f,undo:()=>c.undoClear()}})),onStrokeEnd:async f=>{if(!f.length){t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let m=await this.recognize(f);t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:m,strokes:f}}))}});return t.appendChild(c.el),{clear:c.clear,undoClear:c.undoClear,isStale:c.isStale,configure:c.configure,setInk:c.setInk,repaint:c.repaint,getStrokes:c.getStrokes,canvas:c.el}}destroy(){this.stroke.destroy()}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharLite=Z,window.MillirecChar||(window.MillirecChar=Z));})();
|
|
1
|
+
"use strict";(()=>{var ct={image:{margin:.6884,mag:.6846,bias:-1.0768},imageGeom:{margin:.6925,mag:1.0731,bias:-2.4927}};function ht(r,t,{margin:e,mag:s,bias:n}){return r<1e-9?.99:1/(1+Math.exp(-(e*Math.log(Math.max(t,1e-9)/r)-s*Math.log(r)-n)))}function tt(r,t,e,s=1e3){let n=[];for(let u=0;u<3;u++)n.push(t[r[2*u]]);let a=ct[e];if(a){let u=[r[1],r[3],r[5]],l=u.map((c,d)=>{let m=1/0;for(let p=0;p<3;p++)p!==d&&(m=Math.min(m,u[p]));return ht(c,m,a)});return{chars:n,probs:l}}let i=Math.max(r[1],s/1e3),f=Math.exp(-1*s/i);for(let u=0;u<3;u++)f+=Math.exp(-1*r[2*u+1]/i);let o=[];for(let u=0;u<3;u++)o.push(Math.exp(-1*r[2*u+1]/i)/f);return{chars:n,probs:o}}function q(r){let t=[],e=0,s=0;for(let n=0;n<r.x.length;n++)e+=r.x[n],s+=r.y[n],t.push({x:e,y:s});return t}function et(r){let t=[],e=[],s=[0,0];for(let n=0;n<r.length;n++){let a=Math.round(r[n].x),i=Math.round(r[n].y);t.push(n===0?a:a-s[0]),e.push(n===0?i:i-s[1]),s=[a,i]}return{x:t,y:e}}function G(r){let t=r.length,e=[0,0],s=[0,0],n=[];for(let l=0;l<t;l++){let c=r[l];e[0]+=c.x,e[1]+=c.y;let d={x:c.x,y:c.y,a:1.570795};l>0&&c.x!==s[0]&&(d.a=Math.atan2(c.y-s[1],c.x-s[0])),d.s=Math.sin(d.a),d.c=Math.cos(d.a),l===1&&(n[0].s=d.s,n[0].c=d.c),s=[c.x,c.y],n.push(d)}e[0]/=t,e[1]/=t;let a=[0,0],i=[0,0],f=[0,0],o=[0,0];for(let l of n)l.x<e[0]?(f[0]+=l.x-e[0],f[1]++):(o[0]+=l.x-e[0],o[1]++),l.y<e[1]?(a[0]+=l.y-e[1],a[1]++):(i[0]+=l.y-e[1],i[1]++),l.x-=e[0],l.y-=e[1];a[1]>0&&(a[0]/=a[1]),i[1]>0&&(i[0]/=i[1]),f[1]>0&&(f[0]/=f[1]),o[1]>0&&(o[0]/=o[1]);let u=i[0]-a[0]<o[0]-f[0]?100/(o[0]-f[0]):a[0]<i[0]?100/(i[0]-a[0]):1;return{points:n,scale:u}}function $(r,t=50){let e=[],s=0;for(let i of r)for(let f=1;f<i.length;f++){let o=i[f].x-i[f-1].x,u=i[f].y-i[f-1].y,l=Math.sqrt(o*o+u*u);e.push({ax:i[f-1].x,ay:i[f-1].y,bx:i[f].x,by:i[f].y,cumStart:s,cumEnd:s+l}),s+=l}if(!s||!e.length)return null;let n=[],a=0;for(let i=0;i<t;i++){let f=i*s/(t-1);for(;a<e.length-1&&e[a].cumEnd<f;)a++;let o=e[a],u=o.cumEnd-o.cumStart,l=u?Math.min(1,Math.max(0,(f-o.cumStart)/u)):0;n.push({x:o.ax+(o.bx-o.ax)*l,y:o.ay+(o.by-o.ay)*l})}return n}function V(r){return et(r)}var ft=r=>Array.isArray(r),ut=r=>ft(r)?r.every(t=>typeof t?.x=="number"&&typeof t?.y=="number"):Array.isArray(r?.x)&&Array.isArray(r?.y)&&r.x.length===r.y.length;function pt(r){return!!r&&typeof r=="object"&&!r.version&&!r.classes&&Object.values(r).every(Array.isArray)}function yt(r,{mode:t="both"}={}){let e={};for(let[s,n]of Object.entries(r))e[s]={samples:n,geometry:null};return{version:2,mode:t,pointsPerShape:50,classes:e,ext:{}}}function dt(r){let t=[];if(!r||typeof r!="object")return["not an object"];if((typeof r.version!="number"||r.version<2)&&t.push("bad version"),!r.classes||typeof r.classes!="object"||!Object.keys(r.classes).length)return t.push("no classes"),t;for(let[e,s]of Object.entries(r.classes)){if(!Array.isArray(s?.samples)||!s.samples.length){t.push(`class ${e}: no samples`);continue}s.samples.forEach((a,i)=>{ut(a)||t.push(`class ${e} sample ${i}: bad shape`)});let n=s.geometry;n!=null&&typeof n!="object"&&t.push(`class ${e}: bad geometry`)}return r.wordList!=null&&!Array.isArray(r.wordList)&&t.push("bad wordList"),r.params!=null&&typeof r.params!="object"&&t.push("bad params"),t}function J(r){let t=pt(r)?yt(r):r,e=dt(t);if(e.length)throw new Error("invalid training data: "+e.join("; "));return t.mode||(t.mode="both"),t.pointsPerShape||(t.pointsPerShape=50),t.ext||(t.ext={}),t}function st(r){let t={};for(let[e,s]of Object.entries(r.classes))t[e]=s.samples;return t}var it={turns:5,retrace:.5,winding:3.5,cover:.6,minLength:40,minSpan:12,deadband:.22},L=2;function rt(r){return{x0:r.x0-L,y0:r.y0-L,x1:r.x1+L,y1:r.y1+L,w:r.w+2*L,h:r.h+2*L}}function nt(r){let t=1/0,e=1/0,s=-1/0,n=-1/0;for(let a of r){let i=a.x!==void 0?a.x:a[0],f=a.y!==void 0?a.y:a[1];i<t&&(t=i),i>s&&(s=i),f<e&&(e=f),f>n&&(n=f)}return{x0:t,y0:e,x1:s,y1:n,w:s-t,h:n-e}}function ot(r,t){let e=1/0,s=-1/0;for(let o of r)o<e&&(e=o),o>s&&(s=o);let n=(s-e)*t;if(!(n>0))return 0;let a=0,i=r[0],f=0;for(let o of r)a>0?o>i?i=o:o<i-n&&(f++,a=-1,i=o):a<0?o<i?i=o:o>i+n&&(f++,a=1,i=o):o>i+n?(a=1,i=o):o<i-n&&(a=-1,i=o);return f}function mt(r){let t=0,e=0;for(let d of r)t+=d.x,e+=d.y;t/=r.length,e/=r.length;let s=0,n=0,a=0;for(let d of r){let m=d.x-t,p=d.y-e;s+=m*m,n+=m*p,a+=p*p}let i=s+a,f=s*a-n*n,o=i/2+Math.sqrt(Math.max(0,i*i/4-f)),u=n,l=o-s;Math.hypot(u,l)<1e-9&&(u=1,l=0);let c=Math.hypot(u,l);return{ux:u/c,uy:l/c}}var xt=.09,gt=4;function wt(r,t){let e=Math.max(2,t*xt),s=e/2,n=[r[0]],a=0;for(let l=1;l<r.length;l++){let c=r[l].x-r[l-1].x,d=r[l].y-r[l-1].y,m=Math.hypot(c,d);if(!(m>0))continue;let p=(s-a)/m;for(;p<=1;)n.push({x:r[l-1].x+c*p,y:r[l-1].y+d*p}),p+=s/m;a=(a+m)%s}if(n.length<8)return 0;let i=Math.round(gt*e/s),f=l=>`${Math.floor(l.x/e)},${Math.floor(l.y/e)}`,o=new Map;n.forEach((l,c)=>{let d=f(l);o.has(d)||o.set(d,[]),o.get(d).push(c)});let u=0;for(let l=0;l<n.length;l++){let c=n[l],d=Math.floor(c.x/e),m=Math.floor(c.y/e),p=!1;for(let b=-1;b<=1&&!p;b++)for(let y=-1;y<=1&&!p;y++)for(let x of o.get(`${d+b},${m+y}`)||[])if(!(Math.abs(l-x)<=i)&&Math.hypot(n[x].x-c.x,n[x].y-c.y)<=e){p=!0;break}p&&u++}return u/n.length}function bt(r,t=[],e={}){let s={...it,...e},n=[];for(let y of r){let x={x:y.x!==void 0?y.x:y[0],y:y.y!==void 0?y.y:y[1]},A=n[n.length-1];(!A||Math.hypot(x.x-A.x,x.y-A.y)>.75)&&n.push(x)}if(n.length<4)return{turns:0,cross:0,retrace:0,winding:0,cover:0,length:0,span:0};let a=0;for(let y=1;y<n.length;y++)a+=Math.hypot(n[y].x-n[y-1].x,n[y].y-n[y-1].y);let i=nt(n),f=Math.hypot(i.w,i.h),{ux:o,uy:u}=mt(n),l=n.map(y=>y.x*o+y.y*u),c=n.map(y=>-y.x*u+y.y*o),d=ot(l,s.deadband),m=ot(c,s.deadband),p=0,b=[];for(let y of t)for(let x of y)b.push(x);if(b.length){let y=rt(nt(b)),x=rt(i),A=Math.max(0,Math.min(y.x1,x.x1)-Math.max(y.x0,x.x0)),P=Math.max(0,Math.min(y.y1,x.y1)-Math.max(y.y0,x.y0));p=A/Math.min(y.w,x.w)*(P/Math.min(y.h,x.h))}return{turns:d,cross:m,retrace:wt(n,f),winding:f>0?a/f:0,cover:p,length:a,span:f}}function at(r,t=[],e={}){let s={...it,...e};if(!t||!t.length)return!1;let n=bt(r,t,s);return n.length>=s.minLength&&n.span>=s.minSpan&&n.turns>=s.turns&&n.retrace>=s.retrace&&n.winding>=s.winding&&n.cover>=s.cover}var Mt=12,O=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function X({width:r=160,height:t=90,ink:e="#111827",onStrokeEnd:s,colorOf:n=null,idleOverwrite:a=0,scribbleClear:i=!1,scribble:f=null,onClear:o=null,staleAlpha:u=.3,onStale:l=null}){let c=document.createElement("canvas"),d=typeof devicePixelRatio<"u"&&devicePixelRatio||1;c.width=r*d,c.height=t*d,c.style.width=r+"px",c.style.height=t+"px",c.style.touchAction="none";let m=c.getContext("2d");m.scale(d,d);let p=[],b=[],y=null,x=!1,A=1,P=0,E=0,I=!1,k=null,C=!1;function z(h,g){if(!(h.length<2)){m.strokeStyle=g||e,m.beginPath(),m.moveTo(h[0].x,h[0].y);for(let w=1;w<h.length;w++)m.lineTo(h[w].x,h[w].y);m.stroke()}}function M(){m.clearRect(0,0,r,t),m.lineWidth=2.5,m.lineCap="round",m.lineJoin="round",m.globalAlpha=I?u:1;for(let h of p)z(h,n&&n(h));m.globalAlpha=1,z(b,null)}function R(h){I!==h&&(I=h,M(),l&&l(h))}function _(){clearTimeout(E),E=0;let h=(Number(a)||0)*1e3;if(!h||!p.length){R(!1);return}let g=h-(O()-P);if(g<=0){R(!0);return}R(!1),E=setTimeout(()=>R(!0),g)}function Q(h){p.length&&(k=p,p=[],clearTimeout(E),E=0,R(!1),M(),o&&o(h))}function Z(h,g){let w=p.filter(v=>!v.some(S=>Math.hypot(S.x-h,S.y-g)<=Mt));return w.length===p.length?!1:(p=w,M(),!0)}let T=null,D=h=>{let g=T||(T=c.getBoundingClientRect()),w=r/(c.clientWidth||r),v=t/(c.clientHeight||t);return{x:(h.clientX-g.left-c.clientLeft)*w,y:(h.clientY-g.top-c.clientTop)*v,p:h.pressure||.5}},j=!1,U=null,B=h=>h.preventDefault();c.addEventListener("touchstart",B,{passive:!1}),c.addEventListener("touchmove",B,{passive:!1}),c.addEventListener("contextmenu",B),c.style.userSelect=c.style.webkitUserSelect="none",c.style.webkitTouchCallout="none",c.addEventListener("pointerdown",h=>{if(h.button>0)return;if(y!==null&&y!==h.pointerId){if(U==="pen"&&h.pointerType!=="pen")return;W({pointerId:y})}h.preventDefault(),y=h.pointerId,U=h.pointerType,T=c.getBoundingClientRect();try{c.setPointerCapture(h.pointerId)}catch{}let g=D(h);if(x){j=Z(g.x,g.y);return}I&&p.length&&(Q("idle"),C=!0),b=[g],M()},{passive:!1}),c.addEventListener("pointermove",h=>{if(y!==h.pointerId)return;h.preventDefault();let g=h.getCoalescedEvents?h.getCoalescedEvents():null,w=g&&g.length?g:[h];if(x){for(let v of w){let S=D(v);Z(S.x,S.y)&&(j=!0)}return}for(let v of w)b.push(D(v));M()},{passive:!1});let W=(h,g=!1)=>{if(y===h.pointerId){try{c.releasePointerCapture(h.pointerId)}catch{}if(y=null,U=null,T=null,x){j&&(P=O(),_(),s&&s(p)),j=!1;return}if(b.length>0){let w=b;if(w.length===1){if(g){b=[],M(),C&&(C=!1,s&&s(p));return}let S=w[0];w=[{x:S.x-1,y:S.y,p:S.p},{x:S.x+1,y:S.y,p:S.p}]}let v=p.length?p:C?k:null;if(i&&v&&v.length&&at(w,v,f||{})){b=[],P=O(),C=!1,p.length?Q("scribble"):(M(),o&&o("scribble")),s&&s(p);return}w.id=A++,p=[...p,w],b=[],C=!1,P=O(),_(),s&&s(p)}M()}};return c.addEventListener("pointerup",h=>W(h)),c.addEventListener("pointercancel",h=>W(h,!0)),{el:c,getStrokes:()=>p,setInk(h){e=h,M()},setErasing(h){x=!!h,c.style.cursor=x?"cell":"crosshair"},isErasing:()=>x,repaint:M,isStale:()=>I,undoClear(){return!k||!k.length?!1:(p=p.length?[...k,...p]:k,k=null,P=O(),_(),M(),s&&s(p),!0)},configure(h={}){"idleOverwrite"in h&&(a=Number(h.idleOverwrite)||0),"scribbleClear"in h&&(i=!!h.scribbleClear),"scribble"in h&&(f=h.scribble),"staleAlpha"in h&&(u=Number(h.staleAlpha)),_()},clear(){p=[],b=[],y=null,U=null,T=null,clearTimeout(E),E=0,R(!1),C=!1,M(),s&&s(p)}}}function lt(r){let t=r?String(r):"";return t?(t.endsWith("/")||(t+="/"),typeof location<"u"?new URL(t,location.href).href:t):typeof location<"u"?new URL("./",location.href).href:""}var K=(r,t,e,s)=>new Error(`millirec: ${r} is not ${t} \u2014 the package files are not served at ${e}; copy node_modules/millirec/dist/${s}/ and pass assetBase (see README "Serving the files")`);function St(){let r=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return r?r.slice(0,r.lastIndexOf("/")+1):""}var vt=St(),At=256,Y=class{constructor({assetBase:t,workerName:e,training:s,params:n}){t=lt(t);let a=J(s);this.trainPaths=st(a),this.charList=Object.keys(this.trainPaths),this.samplesPerChar=Math.max(1,...this.charList.map(o=>this.trainPaths[o].length)),this.pointsPerShape=a.pointsPerShape||50,this.params=n||a.params||null,this.plugins=[],this.cache=new Map,this.inFlight=new Map,this.allWaiters=new Map,this.reqCounter=0;let i=`self.__MILLIREC_ASSET_BASE=${JSON.stringify(t)};importScripts(${JSON.stringify(t+e)});`;this.bootUrl=URL.createObjectURL(new Blob([i],{type:"text/javascript"})),this.worker=new Worker(this.bootUrl),this.readyPromise=new Promise((o,u)=>{this.readyResolve=o,this.readyReject=u}),this.worker.onmessage=o=>this.onMessage(o);let f=t+e;this.worker.onerror=o=>{let u=K(f,"the char-lite worker",t,"char-lite");u.message+=` (${o.message||"script failed to load"})`,this.readyReject(u)},this.assetBase=t}onMessage(t){let e=t.data;if(this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null),e.type==="getCharList")this.params&&this.worker.postMessage({type:"setParams",params:this.params}),this.worker.postMessage({type:"charList",charList:this.charList,pointsPerShape:this.pointsPerShape,samplesPerChar:this.samplesPerChar});else if(e.type==="prepAll")this.charList.forEach((s,n)=>{this.trainPaths[s].forEach((a,i)=>{let{points:f,scale:o}=G(q(a));this.worker.postMessage({type:"addPoints",points:f,m:n*this.samplesPerChar+i,scale:o})})}),this.readyResolve();else if(e.type==="addResult"&&e.result){this.cache.delete(e.path),this.cache.set(e.path,e.result),this.cache.size>At&&this.cache.delete(this.cache.keys().next().value);let s=this.inFlight.get(e.path)||[];this.inFlight.delete(e.path);for(let n of s)n(this.applyPlugins(e.result,e.path))}else if(e.type==="allResult"){let s=this.allWaiters.get(e.path)||[];this.allWaiters.delete(e.path);for(let n of s)n(e.costs)}else if(e.type==="bootError"){let s=K(this.assetBase+"millirec.wasm","the char-lite matcher",this.assetBase,"char-lite");s.message+=` (worker boot failed: ${e.message})`,this.readyReject(s)}}applyPlugins(t,e){let s=tt(t,this.charList,"stroke",1e3);for(let n of this.plugins)n.rerank&&(s=n.rerank(s,{raw:t,path:e,charList:this.charList,mode:"stroke",recognizer:this})||s);return s}uploadTest(t){let e=Array.isArray(t[0])?t:[t],s=$(e,this.pointsPerShape);if(!s)return!1;let{points:n,scale:a}=G(s);return this.worker.postMessage({type:"addPoints",points:n,m:-1,scale:a}),!0}keyFor(t){let e=Array.isArray(t[0])?t.flat():t,s=5381;for(let n of e)s=(s*33^(n.x*7919+n.y|0))>>>0;return"strokes:"+e.length+":"+s.toString(36)}async recognize(t){if(this.destroyed||!t||!t.length||(await this.readyPromise,this.destroyed))return null;let e=this.keyFor(t);if(this.cache.has(e)){let s=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,s),this.applyPlugins(s,e)}return this.uploadTest(t)?new Promise(s=>{let n,a=i=>{clearTimeout(n),s(i)};this.inFlight.has(e)?this.inFlight.get(e).push(a):(this.inFlight.set(e,[a]),this.worker.postMessage({type:"compare",path:e,elementID:"req"+ ++this.reqCounter})),n=setTimeout(()=>a(null),4e3)}):null}async rawScores(t){if(this.destroyed||(await this.readyPromise,this.destroyed)||!this.uploadTest(t))return null;let e="all:"+ ++this.reqCounter,s=await new Promise(n=>{let a,i=f=>{clearTimeout(a),n(f)};this.allWaiters.set(e,[i]),this.worker.postMessage({type:"compareAll",path:e,counts:this.charList.map(f=>this.trainPaths[f].length)}),a=setTimeout(()=>i(null),8e3)});return s?{classes:this.charList,costs:s}:null}destroy(){if(!this.destroyed){this.destroyed=!0,this.worker.terminate(),this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null);for(let t of[this.inFlight,this.allWaiters]){for(let e of t.values())for(let s of e)s(null);t.clear()}this.cache.clear(),this.readyResolve()}}},Pt=r=>r?r.chars.map((t,e)=>({char:t,prob:r.probs[e]})):null,F=class{static strokesToSample(t,e=50){let s=$(Array.isArray(t[0])?t:[t],e);return s?V(s):null}static withSamples(t,e,{replace:s=!1}={}){let n=J({...t}),a=n.pointsPerShape,i=o=>{let u=Array.isArray(o)?Array.isArray(o[0])?o:[o]:[q(o)],l=$(u,a);return l?V(l):null},f={...n.classes};for(let[o,u]of Object.entries(e||{})){let l=(u||[]).map(i).filter(Boolean);if(!l.length)continue;let c=f[o]?.samples||[];f[o]={...f[o]||{},samples:s?l:c.concat(l)}}return{...n,classes:f}}static createDrawCanvas(t){return X(t)}static async create(t={}){let e=typeof window<"u"?window:globalThis,s={...e.MILLIREC_CONFIG||{},...t},n=t.training||e.MILLIREC_TRAINING;if(!n)throw new Error("MillirecCharLite: no training data (training.js missing?)");if(typeof Worker>"u"||typeof Blob>"u")throw new Error("millirec: char-lite needs a browser (Worker, fetch, canvas); importing is SSR-safe but call create() on the client");let a=new this(s,n);return await a.ready,a}constructor(t,e){this.config=t,this.stroke=new Y({assetBase:t.assetBase||vt,workerName:t.workerStroke||"worker-stroke.js",training:e,params:t.params?.stroke||t.params||null}),this.charList=this.stroke.charList,this.ready=this.stroke.readyPromise}use(t){return this.stroke.plugins.push(t),this}async recognize(t){return Pt(await this.stroke.recognize(t))}rawScores(t){return this.stroke.rawScores(t)}attach(t,{width:e=240,height:s=240,ink:n="#1e293b",idleOverwrite:a=2,scribbleClear:i=!0,scribble:f=null,staleAlpha:o,onStale:u}={}){let l=X({width:e,height:s,ink:n,idleOverwrite:a,scribbleClear:i,scribble:f,onStale:u,...o===void 0?{}:{staleAlpha:o},onClear:c=>t.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:c,undo:()=>l.undoClear()}})),onStrokeEnd:async c=>{if(!c.length){t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let d=await this.recognize(c);t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:d,strokes:c}}))}});return t.appendChild(l.el),{clear:l.clear,undoClear:l.undoClear,isStale:l.isStale,configure:l.configure,setInk:l.setInk,repaint:l.repaint,getStrokes:l.getStrokes,canvas:l.el}}destroy(){this.stroke.destroy()}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharLite=F,window.MillirecChar||(window.MillirecChar=F));})();
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// The overlap widget is a script-tag build (dist/overlap/millirec-overlap.min.js) that sets
|
|
2
|
+
// window.MillirecOverlap. These declarations type that global:
|
|
3
|
+
//
|
|
4
|
+
// import type {} from 'millirec/overlap' // or: /// <reference types="millirec/overlap" />
|
|
5
|
+
// const w = await MillirecOverlap.create('#box', { set: 'capitals', words: ['HELLO'] })
|
|
6
|
+
//
|
|
7
|
+
// Source: library/src/overlap.js (the full option list is in OverlapWidget's constructor comment).
|
|
8
|
+
|
|
9
|
+
export type OverlapSet = 'capitals' | 'lowercase' | 'digits' | 'punctuation' | 'all'
|
|
10
|
+
export type OverlapEvent = 'ready' | 'stroke' | 'change' | 'word' | 'select' | 'error'
|
|
11
|
+
export interface OverlapPoint { x: number; y: number }
|
|
12
|
+
|
|
13
|
+
export interface OverlapCandidate { word: string; score: number; complete: boolean; inList: boolean }
|
|
14
|
+
export interface OverlapWord {
|
|
15
|
+
word: string
|
|
16
|
+
letters: Array<{ ch: string; strokes: OverlapPoint[][] }>
|
|
17
|
+
inList: boolean
|
|
18
|
+
selected: boolean
|
|
19
|
+
alternatives: Array<{ word: string; score: number; inList: boolean }>
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface OverlapOptions {
|
|
23
|
+
/** Which characters the box reads (default 'capitals'). */
|
|
24
|
+
set?: OverlapSet
|
|
25
|
+
/** An explicit alphabet ('ABC…' or 'capitals,digits'); loads the superset and uses these. */
|
|
26
|
+
alphabet?: string
|
|
27
|
+
/** The word list: an array, or a whitespace/comma-separated string. */
|
|
28
|
+
words?: string[] | string
|
|
29
|
+
/** A list hosted on a millirec server (needs apiBase). */
|
|
30
|
+
list?: string
|
|
31
|
+
/** URL of a text/JSON file of words. */
|
|
32
|
+
wordsSrc?: string
|
|
33
|
+
/** Receives the text (an input/textarea's value, else textContent). */
|
|
34
|
+
target?: string | HTMLElement
|
|
35
|
+
/** 'live' (default) includes the word being written. */
|
|
36
|
+
targetMode?: 'live' | 'words'
|
|
37
|
+
/** The box, in CSS px (default 240). */
|
|
38
|
+
size?: number
|
|
39
|
+
layout?: 'column' | 'row'
|
|
40
|
+
/** Candidate words shown (default 6). */
|
|
41
|
+
chips?: number
|
|
42
|
+
/** Previous words' handwriting kept beside the current one (default 1). */
|
|
43
|
+
history?: number
|
|
44
|
+
/** Seconds of pen-up after which the word finishes itself (0 = never, the default). */
|
|
45
|
+
idleFinish?: number
|
|
46
|
+
theme?: 'auto' | 'light' | 'dark'
|
|
47
|
+
/** Any of 'text,handwriting,words,buttons'. */
|
|
48
|
+
hide?: string
|
|
49
|
+
placeholder?: string
|
|
50
|
+
/** Recognizer knobs (commitMargin, lmW, …). */
|
|
51
|
+
engine?: Record<string, number>
|
|
52
|
+
/** Where millirec.wasm, training.<set>.json and words.json are. Default: beside the script.
|
|
53
|
+
* A code-loading option: never fill it from user input. */
|
|
54
|
+
assetBase?: string
|
|
55
|
+
/** The millirec server, for `list`. */
|
|
56
|
+
apiBase?: string
|
|
57
|
+
onReady?: (detail: OverlapDetail) => void
|
|
58
|
+
onStroke?: (detail: OverlapDetail) => void
|
|
59
|
+
onChange?: (detail: OverlapDetail) => void
|
|
60
|
+
onWord?: (detail: OverlapDetail & OverlapWord & { canvas: HTMLCanvasElement }) => void
|
|
61
|
+
onSelect?: (detail: OverlapDetail) => void
|
|
62
|
+
onError?: (detail: OverlapDetail & { error: Error }) => void
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** An event's detail. 'stroke'/'change'/'word' carry the text fields; 'word' adds the finished word. */
|
|
66
|
+
export interface OverlapDetail {
|
|
67
|
+
widget: OverlapWidget
|
|
68
|
+
text?: string
|
|
69
|
+
live?: string
|
|
70
|
+
current?: string
|
|
71
|
+
committed?: string
|
|
72
|
+
pending?: string
|
|
73
|
+
candidates?: OverlapCandidate[]
|
|
74
|
+
strokes?: number
|
|
75
|
+
erased?: number
|
|
76
|
+
canvas?: HTMLCanvasElement | null
|
|
77
|
+
[key: string]: unknown
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface OverlapWidget {
|
|
81
|
+
readonly el: HTMLElement
|
|
82
|
+
readonly ready: Promise<void>
|
|
83
|
+
/** Subscribe; returns the unsubscribe function. DOM events 'millirec-overlap:<event>' bubble from the host too. */
|
|
84
|
+
on(event: OverlapEvent, fn: (detail: OverlapDetail) => void): () => boolean
|
|
85
|
+
/** The finished words, joined by spaces. */
|
|
86
|
+
getText(): string
|
|
87
|
+
/** The finished words plus the word being written. */
|
|
88
|
+
getLiveText(): string
|
|
89
|
+
getWords(): OverlapWord[]
|
|
90
|
+
getCandidates(): OverlapCandidate[]
|
|
91
|
+
getWordList(): string[]
|
|
92
|
+
getHandwriting(opts?: { scope?: 'word' | 'all'; index?: number; capHeight?: number }): HTMLCanvasElement | null
|
|
93
|
+
/** Replace the word list; returns the usable words (0 = free mode). */
|
|
94
|
+
setWords(words: string[] | string): number
|
|
95
|
+
/** Load a list hosted on the millirec server by id. */
|
|
96
|
+
loadList(id: string): Promise<number>
|
|
97
|
+
getLexiconSize(): number
|
|
98
|
+
/** Switch the character set or an explicit alphabet; resolves with the alphabet when ready. */
|
|
99
|
+
setAlphabet(spec: OverlapSet | string): Promise<string | undefined>
|
|
100
|
+
/** Finish the word being written (best reading), or force it to `word`. */
|
|
101
|
+
finishWord(word?: string | null): void
|
|
102
|
+
/** Accept a candidate; `finish: false` adopts it as a prefix and keeps writing. */
|
|
103
|
+
selectWord(word: string, opts?: { finish?: boolean }): void
|
|
104
|
+
undo(): void
|
|
105
|
+
/** Drop the current word's ink; finished words stay. */
|
|
106
|
+
clearWord(): void
|
|
107
|
+
/** Forget everything, finished words included. */
|
|
108
|
+
clear(): void
|
|
109
|
+
setOptions(engineOpts: Record<string, number>): void
|
|
110
|
+
destroy(): void
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface MillirecOverlapApi {
|
|
114
|
+
readonly version: string
|
|
115
|
+
create(host: string | HTMLElement, opts?: OverlapOptions): Promise<OverlapWidget>
|
|
116
|
+
/** Mount a widget on every [data-millirec-overlap] element not yet mounted (done once on load). */
|
|
117
|
+
scan(root?: ParentNode): OverlapWidget[]
|
|
118
|
+
Widget: new (host: string | HTMLElement, opts?: OverlapOptions) => OverlapWidget
|
|
119
|
+
/** Prewarm the matcher and templates for a set (optional; create() does it on demand). */
|
|
120
|
+
preload(set?: OverlapSet | string, assetBase?: string): Promise<unknown>
|
|
121
|
+
splitWords(s: string): string[]
|
|
122
|
+
wordStrip(groups: unknown[], capHeight?: number, colors?: Record<string, string>): HTMLCanvasElement
|
|
123
|
+
sentenceStrip(wordsGroups: unknown[][], capHeight?: number, colors?: Record<string, string>): HTMLCanvasElement
|
|
124
|
+
SET_NAMES: readonly string[]
|
|
125
|
+
[key: string]: unknown
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
declare global {
|
|
129
|
+
interface Window { MillirecOverlap: MillirecOverlapApi }
|
|
130
|
+
var MillirecOverlap: MillirecOverlapApi
|
|
131
|
+
interface HTMLElementEventMap {
|
|
132
|
+
'millirec-overlap:ready': CustomEvent<OverlapDetail>
|
|
133
|
+
'millirec-overlap:stroke': CustomEvent<OverlapDetail>
|
|
134
|
+
'millirec-overlap:change': CustomEvent<OverlapDetail>
|
|
135
|
+
'millirec-overlap:word': CustomEvent<OverlapDetail & OverlapWord & { canvas: HTMLCanvasElement }>
|
|
136
|
+
'millirec-overlap:select': CustomEvent<OverlapDetail & { word: string; finish: boolean }>
|
|
137
|
+
'millirec-overlap:error': CustomEvent<OverlapDetail & { error: Error }>
|
|
138
|
+
}
|
|
139
|
+
}
|