millirec 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +71 -0
- package/README.md +229 -19
- package/dist/char-cnn/core.d.ts +18 -5
- package/dist/char-cnn/core.js +152 -25
- package/dist/char-cnn/index.d.ts +3 -2
- package/dist/char-cnn/index.js +152 -25
- 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-cnn/options/accurate.js +4 -4
- package/dist/char-cnn/options/accurate.json +4 -4
- package/dist/char-cnn/options/digits/digits-base.head.bin +0 -0
- package/dist/char-cnn/options/digits/digits-base.q4.bin +0 -0
- package/dist/char-cnn/options/digits/digits-tiny.bin +0 -0
- package/dist/char-cnn/options/digits/digits-tiny.head.bin +0 -0
- package/dist/char-cnn/options/digits.js +17 -0
- package/dist/char-cnn/options/digits.json +15 -0
- package/dist/char-cnn/options/fast/tiny.bin +0 -0
- package/dist/char-cnn/options/fast/tiny.head.bin +0 -0
- package/dist/char-cnn/options/fast.js +4 -4
- package/dist/char-cnn/options/fast.json +4 -4
- package/dist/char-cnn/options/lowercase/lowercase-base.head.bin +0 -0
- package/dist/char-cnn/options/lowercase/lowercase-base.q4.bin +0 -0
- package/dist/char-cnn/options/lowercase/lowercase-tiny.bin +0 -0
- package/dist/char-cnn/options/lowercase/lowercase-tiny.head.bin +0 -0
- package/dist/char-cnn/options/lowercase.js +17 -0
- package/dist/char-cnn/options/lowercase.json +15 -0
- package/dist/char-cnn/options/small/tiny.bin +0 -0
- package/dist/char-cnn/options/small/tiny.head.bin +0 -0
- package/dist/char-cnn/options/small.js +2 -2
- package/dist/char-cnn/options/small.json +2 -2
- package/dist/char-lite/index.d.ts +26 -4
- package/dist/char-lite/index.js +113 -11
- package/dist/char-lite/millirec-char-lite.min.js +1 -1
- package/dist/char-lite/millirec.wasm +0 -0
- package/dist/char-lite/sets.json +25 -29
- package/dist/overlap/index.d.ts +139 -0
- package/dist/overlap/millirec.wasm +0 -0
- package/package.json +45 -3
- /package/dist/char-cnn/{base.head.bin → options/accurate/base.head.bin} +0 -0
- /package/dist/char-cnn/{base.q4.bin → options/accurate/base.q4.bin} +0 -0
- /package/dist/char-cnn/{tiny.bin → options/accurate/tiny.bin} +0 -0
- /package/dist/char-cnn/{tiny.head.bin → options/accurate/tiny.head.bin} +0 -0
- /package/dist/char-cnn/{base-p25.bin → options/fast/base-p25.bin} +0 -0
- /package/dist/char-cnn/{base-p25.head.bin → options/fast/base-p25.head.bin} +0 -0
|
@@ -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 X(r){let o=new DataView(r.buffer?r.buffer:r,r.byteOffset||0,r.byteLength),l=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),e=0;return{u32:()=>{let t=o.getUint32(e,!0);return e+=4,t},f32s:t=>{let s=new Float32Array(t);for(let a=0;a<t;a++)s[a]=o.getFloat32(e,!0),e+=4;return s},i8s:t=>{let s=new Int8Array(t);for(let a=0;a<t;a++)s[a]=l[e+a]<<24>>24;return e+=t,s},ibits:(t,s)=>{if(s===8){let f=new Int8Array(t);for(let n=0;n<t;n++)f[n]=l[e+n]<<24>>24;return e+=t,f}let a=new Int8Array(t),h=(1<<s)-1,c=1<<s-1;for(let f=0;f<t;f++){let n=f*s,i=e+(n>>3),u=n&7,g=(l[i]|l[i+1]<<8)>>u&h;a[f]=g&c?g-(1<<s):g}return e+=t*s+7>>3,a},str:t=>{let s=String.fromCharCode(...l.subarray(e,e+t));return e+=t,s},done:()=>e>=o.byteLength}}function V(r,o=8){let l=r.u32(),e=r.u32(),t=r.f32s(l),s=r.f32s(l),a=r.ibits(l*e,o),h=new Float32Array(l*e);for(let c=0;c<l;c++)for(let f=0;f<e;f++)h[c*e+f]=a[c*e+f]*t[c];return{out:l,in:e,w:h,bias:s}}function G(r){let o=X(r),l=o.str(6),e=J[l];if(!e)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 s=o.u32(),a=o.u32(),h=o.u32(),c=[];for(let n=0;n<h;n++){let i=o.u32(),u=o.u32(),g=o.u32(),d=o.u32(),m=o.f32s(i),p=o.f32s(i),x=o.ibits(i*u*g*g,e),I=new Float32Array(x.length),A=u*g*g;for(let M=0;M<i;M++)for(let v=0;v<A;v++)I[M*A+v]=x[M*A+v]*m[M];c.push({cout:i,cin:u,k:g,pool:d,w:I,bias:p})}let f=V(o,e);return{size:s,dim:a,convs:c,lin:f,bits:e}}function Q(r){let o=new Uint8Array(r.buffer?r.buffer:r,r.byteOffset||0,r.byteLength),l=String.fromCharCode(...o.subarray(0,6)),e=J[l];if(!e)throw new Error("not an MRCNN model");if(e===8)return o;let t=X(r);t.str(6);let s=t.u32(),a=t.u32(),h=t.u32(),c=t.u32(),f=[],n=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"),n(s),n(a),n(h),n(c));for(let M=0;M<c;M++){let v=t.u32(),w=t.u32(),b=t.u32(),N=t.u32(),S=t.f32s(v),F=t.f32s(v),k=t.ibits(v*w*b*b,e);f.push(n(v),n(w),n(b),n(N),i(S),i(F),new Uint8Array(k.buffer,k.byteOffset,k.length))}let u=t.u32(),g=t.u32(),d=t.f32s(u),m=t.f32s(u),p=t.ibits(u*g,e);f.push(n(u),n(g),i(d),i(m),new Uint8Array(p.buffer,p.byteOffset,p.length));let x=f.reduce((M,v)=>M+v.length,0),I=new Uint8Array(x),A=0;for(let M of f)I.set(M,A),A+=M.length;return I}function tt(r){return V(X(r))}function pt(r,o,l,e){let{cout:t,cin:s,k:a,w:h,bias:c}=r,f=l*l,n=a-1>>1,i=s*a*a;for(let u=0;u<t;u++){let g=u*f,d=c[u],m=u*i;for(let p=0;p<l;p++)for(let x=0;x<l;x++){let I=d;for(let A=0;A<s;A++){let M=A*f,v=m+A*a*a;for(let w=0;w<a;w++){let b=p+w-n;if(b<0||b>=l)continue;let N=M+b*l,S=v+w*a;for(let F=0;F<a;F++){let k=x+F-n;k<0||k>=l||(I+=h[S+F]*o[N+k])}}}e[g+p*l+x]=I>0?I:0}}}function mt(r,o,l,e){let t=o>>1;for(let s=0;s<l;s++){let a=s*o*o,h=s*t*t;for(let c=0;c<t;c++)for(let f=0;f<t;f++){let n=a+2*c*o+2*f,i=r[n],u=r[n+1],g=r[n+o],d=r[n+o+1];e[h+c*t+f]=Math.max(i,u,g,d)}}}function et(r,o){let l=r.size,e=Float32Array.from(o),t=l,s=1;for(let n of r.convs){let i=new Float32Array(n.cout*t*t);if(pt(n,e,t,i),e=i,s=n.cout,n.pool){let u=new Float32Array(s*(t>>1)*(t>>1));mt(e,t,s,u),e=u,t>>=1}}let a=t*t,h=new Float32Array(s);for(let n=0;n<s;n++){let i=0;for(let u=0;u<a;u++)i+=e[n*a+u];h[n]=i/a}let{lin:c}=r,f=new Float32Array(c.out);for(let n=0;n<c.out;n++){let i=c.bias[n];for(let u=0;u<c.in;u++)i+=c.w[n*c.in+u]*h[u];f[n]=i}return f}function nt(r){let o=0;for(let e=0;e<r.length;e++)o+=r[e]*r[e];o=1/(Math.sqrt(o)+1e-9);let l=new Float32Array(r.length);for(let e=0;e<r.length;e++)l[e]=r[e]*o;return l}function q(r,o){let l=new Float32Array(r.out);for(let e=0;e<r.out;e++){let t=r.bias[e];for(let s=0;s<r.in;s++){let a=o[s];a>0&&(t+=r.w[e*r.in+s]*a)}l[e]=t}return l}function z(r){let o=-1/0;for(let t of r)t>o&&(o=t);let l=new Float32Array(r.length),e=0;for(let t=0;t<r.length;t++)l[t]=Math.exp(r[t]-o),e+=l[t];for(let t=0;t<r.length;t++)l[t]/=e;return l}function ot(r,o,l=120,e=7,t=10){let s=1/0,a=1/0,h=-1/0,c=-1/0;for(let i of o)for(let u of i)u.x<s&&(s=u.x),u.x>h&&(h=u.x),u.y<a&&(a=u.y),u.y>c&&(c=u.y);let f=l/Math.max(h-s,c-a,1),n=l+2*t;r.fillStyle="#fff",r.fillRect(0,0,n,n),r.strokeStyle="#000",r.lineWidth=e,r.lineCap="round",r.lineJoin="round";for(let i of o)if(!(i.length<2)){r.beginPath(),r.moveTo((i[0].x-s)*f+t,(i[0].y-a)*f+t);for(let u=1;u<i.length;u++)r.lineTo((i[u].x-s)*f+t,(i[u].y-a)*f+t);r.stroke()}return n}function rt(r,o,l){let e=new Float32Array(o*l);for(let t=0,s=0;t<e.length;t++,s+=4)e[t]=1-(r[s]*.299+r[s+1]*.587+r[s+2]*.114)/255;return e}function st(r,o,l,e=32,t=24){let s=1/0,a=-1,h=1/0,c=-1;for(let w=0;w<l;w++)for(let b=0;b<o;b++)r[w*o+b]>.15&&(b<s&&(s=b),b>a&&(a=b),w<h&&(h=w),w>c&&(c=w));let f=new Float32Array(e*e);if(a<0)return f;let n=a-s+1,i=c-h+1,u=new Float32Array(n*i);for(let w=0;w<i;w++)for(let b=0;b<n;b++)u[w*n+b]=r[(w+h)*o+(b+s)];let g=0;for(let w=0;w<u.length;w++)u[w]>g&&(g=u[w]);if(g>.05&&g<.999)for(let w=0;w<u.length;w++)u[w]=Math.min(1,u[w]/g);let d=t/Math.max(i,n),m=Math.max(1,Math.round(i*d)),p=Math.max(1,Math.round(n*d)),x=new Float32Array(p*m),I=n/p,A=i/m;for(let w=0;w<m;w++){let b=w*A,N=(w+1)*A,S=Math.floor(b),F=Math.min(i,Math.ceil(N));for(let k=0;k<p;k++){let B=k*I,j=(k+1)*I,O=Math.floor(B),H=Math.min(n,Math.ceil(j)),P=0,T=0;for(let R=S;R<F;R++){let D=Math.min(N,R+1)-Math.max(b,R);if(!(D<=0))for(let y=O;y<H;y++){let C=Math.min(j,y+1)-Math.max(B,y);C<=0||(P+=u[R*n+y]*C*D,T+=C*D)}}x[w*p+k]=T>0?P/T:0}}let M=e-m>>1,v=e-p>>1;for(let w=0;w<m;w++)for(let b=0;b<p;b++)f[(w+M)*e+b+v]=x[w*p+b];return f}function it(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 $=r=>Array.isArray(r)&&r.length&&!Array.isArray(r[0])?[r]:r,K=(r,o,l,e)=>new Error(`millirec: ${r} is not ${o} \u2014 the package files are not served at ${l}; copy node_modules/millirec/dist/${e}/ and pass assetBase (see README "Serving the files")`);async function at(r,{as:o="json",what:l,base:e,recognizer:t}){let s=n=>{let i=K(r,l,e,t);return n&&(i.message+=` (${n})`),i},a;try{a=await fetch(r)}catch(n){throw s(n&&n.message)}let h=a.headers&&a.headers.get("content-type")||"";if(!a.ok)throw s(`HTTP ${a.status}`);if(o==="json")try{return await a.json()}catch(n){throw s(/html/i.test(h)?"an HTML page":n&&n.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 wt(){let r=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return r?r.slice(0,r.lastIndexOf("/")+1):""}var xt=wt(),lt=(r,o)=>at(r,{as:"buf",what:"a char-cnn model file",base:o,recognizer:"char-cnn"}),bt="millirec: recognizer destroyed",Mt=r=>typeof document<"u"&&document.createElement?Object.assign(document.createElement("canvas"),{width:r,height:r}):typeof OffscreenCanvas<"u"?new OffscreenCanvas(r,r):null,vt=18,ct=r=>{let o=0;for(let e=0;e<r.length;e++)o+=r[e]*r[e];o=Math.sqrt(o)||1;let l=new Float32Array(r.length);for(let e=0;e<r.length;e++)l[e]=r[e]/o;return l},W=class{static async create(o={}){let e={...(typeof window<"u"?window:globalThis).MILLIREC_CNN||{},...o};if(!e.stages||!e.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(e);return await t.ready,e.examples&&await t.teach(e.examples),t}constructor(o){this.config=o,this.base=it(o.assetBase||xt),this.classes=typeof o.classes=="string"?o.classes.split(""):o.classes,this.stages=[],this.off=Mt(140),this.octx=this.off?this.off.getContext("2d",{willReadFrequently:!0}):null,this.ready=this.load()}async load(){let{base:o,config:l}=this,e=null;if(l.kernel){let t=o+l.kernel;try{e=(await import(t)).default}catch(s){let a=K(t,"the char-cnn kernel",o,"char-cnn");throw a.message+=` (${s&&s.message})`,a}}for(let t of l.stages){let[s,a]=await Promise.all([lt(o+t.model,o),lt(o+t.head,o)]);if(this.destroyed)return;let h=tt(a),c={theta:t.theta==null?null:t.theta,head:h,headNorm:t.headNorm!==!1,size:0};if(e){let f=await e();if(this.destroyed)return;let n=Q(new Uint8Array(s)),i=f._malloc(n.byteLength);f.HEAPU8.set(n,i);let u=f._cnnLoad(i,n.byteLength);if(f._free(i),!u)throw new Error(`kernel rejected ${t.model} (channel widths must be multiples of four)`);let g=f._cnnSize(),d=f._cnnDim();c.size=g,c.embed=m=>{let p=f._cnnInputPtr(1)>>2;f.HEAPF32.set(m,p),f._cnnRun(1);let x=f._cnnEmbedPtr(1)>>2;return f.HEAPF32.slice(x,x+d)},c.logits=m=>q(c.head,c.embed(m))}else{let f=G(s);c.size=f.size,c.embed=n=>{let i=et(f,n);return c.headNorm?nt(i):i},c.logits=n=>q(c.head,c.embed(n))}this.stages.push(c)}}raster(o,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!==o){let s=ot(this.octx,o);this._plane={ink:rt(this.octx.getImageData(0,0,s,s).data,s,s),W:s},this._planeFor=o}let{ink:e,W:t}=this._plane;return st(e,t,t,l,Math.round(l*.75))}async recognize(o,{only:l=null}={}){if(o=$(o),!o||!o.length||(await this.ready,this.destroyed||!this.stages.length))return null;this._planeFor=null;let e=l?new Set(l):null;if(this.taught)return this.nearest(o,e);let t=null,s=0;for(let n=0;n<this.stages.length;n++){let i=this.stages[n];if((this.personal||e)&&n<this.stages.length-1)continue;if(t=i.logits(this.raster(o,i.size)),s=n,i.theta==null||n===this.stages.length-1)break;let u=-1/0,g=-1/0;for(let d of t)d>u?(g=u,u=d):d>g&&(g=d);if(u-g>=i.theta)break}let a=[...t.keys()];if(e&&(a=a.filter(n=>e.has(this.classes[n])),!a.length)){let n=[];return n.stage=s,n}let h=z(a.map(n=>t[n])),f=[...h.keys()].sort((n,i)=>h[i]-h[n]).slice(0,3).map(n=>({char:this.classes[a[n]],prob:h[n]}));return f.stage=s,f}nearest(o,l){let e=this.stages.length-1,t=this.stages[e],s=ct(t.embed(this.raster(o,t.size))),a=[...this.taught.keys()].filter(c=>!l||l.has(c)),h=[];if(a.length){let c=a.map(n=>{let i=-2;for(let u of this.taught.get(n)){let g=0;for(let d=0;d<s.length;d++)g+=s[d]*u[d];g>i&&(i=g)}return i}),f=z(c.map(n=>n*vt));for(let n of[...f.keys()].sort((i,u)=>f[u]-f[i]).slice(0,3))h.push({char:a[n],prob:f[n]})}return h.stage=e,h}async teach(o,{add:l=!1}={}){if(await this.ready,this.destroyed||!this.stages.length)return null;let e=l&&this.taught?new Map([...this.taught].map(([t,s])=>[t,s.slice()])):new Map;for(let[t,s]of Object.entries(o||{}))for(let a of s||[]){let h=$(a);if(!h||!h.length)continue;let c=ct(await this.embedding(h));if(this.destroyed)return null;e.has(t)||e.set(t,[]),e.get(t).push(c)}return e.size?(this.taught=e,{classes:[...e.keys()],n:[...e.values()].reduce((t,s)=>t+s.length,0)}):(l||(this.taught=null),null)}forget(){this.taught=null}async embedding(o){if(o=$(o),await this.ready,this.destroyed||!this.stages.length)throw new Error(bt);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:e=.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),h=[],c=[];for(let[g,d]of Object.entries(o||{})){let m=this.classes.indexOf(g);if(!(m<0))for(let p of d||[]){let x=$(p);!x||!x.length||(h.push(await this.embedding(x)),c.push(m))}}if(this.destroyed)return null;if(!h.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)},n=h.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<n;m++){let p=z(q(f,h[m])),x=h[m];for(let I=0;I<f.out;I++){let A=(p[I]-(I===c[m]?1:0))/n;if(!A)continue;u[I]+=A;let M=I*f.in;for(let v=0;v<f.in;v++){let w=x[v];w>0&&(i[M+v]+=A*w)}}}let d=t/n;for(let m=0;m<f.w.length;m++)f.w[m]-=e*(i[m]+d*(f.w[m]-a.w[m]));for(let m=0;m<f.out;m++)f.bias[m]-=e*(u[m]+d*(f.bias[m]-a.bias[m]))}return s.head=f,this.personal={n,classes:[...new Set(c)].map(g=>this.classes[g]).sort()},this.personal}destroy(){this.destroyed=!0,this.stages=[],this.personal=null,this.taught=null,this._plane=null,this._planeFor=null}depersonalize(){let o=this.stages[this.stages.length-1];o&&o.head0&&(o.head=o.head0),this.personal=null}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharCnn=W);var dt={turns:5,retrace:.5,winding:3.5,cover:.6,minLength:40,minSpan:12,deadband:.22},U=2;function ft(r){return{x0:r.x0-U,y0:r.y0-U,x1:r.x1+U,y1:r.y1+U,w:r.w+2*U,h:r.h+2*U}}function ut(r){let o=1/0,l=1/0,e=-1/0,t=-1/0;for(let s of r){let a=s.x!==void 0?s.x:s[0],h=s.y!==void 0?s.y:s[1];a<o&&(o=a),a>e&&(e=a),h<l&&(l=h),h>t&&(t=h)}return{x0:o,y0:l,x1:e,y1:t,w:e-o,h:t-l}}function ht(r,o){let l=1/0,e=-1/0;for(let c of r)c<l&&(l=c),c>e&&(e=c);let t=(e-l)*o;if(!(t>0))return 0;let s=0,a=r[0],h=0;for(let c of r)s>0?c>a?a=c:c<a-t&&(h++,s=-1,a=c):s<0?c<a?a=c:c>a+t&&(h++,s=1,a=c):c>a+t?(s=1,a=c):c<a-t&&(s=-1,a=c);return h}function It(r){let o=0,l=0;for(let u of r)o+=u.x,l+=u.y;o/=r.length,l/=r.length;let e=0,t=0,s=0;for(let u of r){let g=u.x-o,d=u.y-l;e+=g*g,t+=g*d,s+=d*d}let a=e+s,h=e*s-t*t,c=a/2+Math.sqrt(Math.max(0,a*a/4-h)),f=t,n=c-e;Math.hypot(f,n)<1e-9&&(f=1,n=0);let i=Math.hypot(f,n);return{ux:f/i,uy:n/i}}var At=.09,Ct=4;function Et(r,o){let l=Math.max(2,o*At),e=l/2,t=[r[0]],s=0;for(let n=1;n<r.length;n++){let i=r[n].x-r[n-1].x,u=r[n].y-r[n-1].y,g=Math.hypot(i,u);if(!(g>0))continue;let d=(e-s)/g;for(;d<=1;)t.push({x:r[n-1].x+i*d,y:r[n-1].y+u*d}),d+=e/g;s=(s+g)%e}if(t.length<8)return 0;let a=Math.round(Ct*l/e),h=n=>`${Math.floor(n.x/l)},${Math.floor(n.y/l)}`,c=new Map;t.forEach((n,i)=>{let u=h(n);c.has(u)||c.set(u,[]),c.get(u).push(i)});let f=0;for(let n=0;n<t.length;n++){let i=t[n],u=Math.floor(i.x/l),g=Math.floor(i.y/l),d=!1;for(let m=-1;m<=1&&!d;m++)for(let p=-1;p<=1&&!d;p++)for(let x of c.get(`${u+m},${g+p}`)||[])if(!(Math.abs(n-x)<=a)&&Math.hypot(t[x].x-i.x,t[x].y-i.y)<=l){d=!0;break}d&&f++}return f/t.length}function St(r,o=[],l={}){let e={...dt,...l},t=[];for(let p of r){let x={x:p.x!==void 0?p.x:p[0],y:p.y!==void 0?p.y:p[1]},I=t[t.length-1];(!I||Math.hypot(x.x-I.x,x.y-I.y)>.75)&&t.push(x)}if(t.length<4)return{turns:0,cross:0,retrace:0,winding:0,cover:0,length:0,span:0};let s=0;for(let p=1;p<t.length;p++)s+=Math.hypot(t[p].x-t[p-1].x,t[p].y-t[p-1].y);let a=ut(t),h=Math.hypot(a.w,a.h),{ux:c,uy:f}=It(t),n=t.map(p=>p.x*c+p.y*f),i=t.map(p=>-p.x*f+p.y*c),u=ht(n,e.deadband),g=ht(i,e.deadband),d=0,m=[];for(let p of o)for(let x of p)m.push(x);if(m.length){let p=ft(ut(m)),x=ft(a),I=Math.max(0,Math.min(p.x1,x.x1)-Math.max(p.x0,x.x0)),A=Math.max(0,Math.min(p.y1,x.y1)-Math.max(p.y0,x.y0));d=I/Math.min(p.w,x.w)*(A/Math.min(p.h,x.h))}return{turns:u,cross:g,retrace:Et(t,h),winding:h>0?s/h:0,cover:d,length:s,span:h}}function yt(r,o=[],l={}){let e={...dt,...l};if(!o||!o.length)return!1;let t=St(r,o,e);return t.length>=e.minLength&&t.span>=e.minSpan&&t.turns>=e.turns&&t.retrace>=e.retrace&&t.winding>=e.winding&&t.cover>=e.cover}var kt=12,Y=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function gt({width:r=160,height:o=90,ink:l="#111827",onStrokeEnd:e,colorOf:t=null,idleOverwrite:s=0,scribbleClear:a=!1,scribble:h=null,onClear:c=null,staleAlpha:f=.3,onStale:n=null}){let i=document.createElement("canvas"),u=typeof devicePixelRatio<"u"&&devicePixelRatio||1;i.width=r*u,i.height=o*u,i.style.width=r+"px",i.style.height=o+"px",i.style.touchAction="none";let g=i.getContext("2d");g.scale(u,u);let d=[],m=[],p=null,x=!1,I=1,A=0,M=0,v=!1,w=null,b=!1;function N(y,C){if(!(y.length<2)){g.strokeStyle=C||l,g.beginPath(),g.moveTo(y[0].x,y[0].y);for(let E=1;E<y.length;E++)g.lineTo(y[E].x,y[E].y);g.stroke()}}function S(){g.clearRect(0,0,r,o),g.lineWidth=2.5,g.lineCap="round",g.lineJoin="round",g.globalAlpha=v?f:1;for(let y of d)N(y,t&&t(y));g.globalAlpha=1,N(m,null)}function F(y){v!==y&&(v=y,S(),n&&n(y))}function k(){clearTimeout(M),M=0;let y=(Number(s)||0)*1e3;if(!y||!d.length){F(!1);return}let C=y-(Y()-A);if(C<=0){F(!0);return}F(!1),M=setTimeout(()=>F(!0),C)}function B(y){d.length&&(w=d,d=[],clearTimeout(M),M=0,F(!1),S(),c&&c(y))}function j(y,C){let E=d.filter(L=>!L.some(_=>Math.hypot(_.x-y,_.y-C)<=kt));return E.length===d.length?!1:(d=E,S(),!0)}let O=null,H=y=>{let C=O||(O=i.getBoundingClientRect()),E=r/(i.clientWidth||r),L=o/(i.clientHeight||o);return{x:(y.clientX-C.left-i.clientLeft)*E,y:(y.clientY-C.top-i.clientTop)*L,p:y.pressure||.5}},P=!1,T=null,R=y=>y.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",y=>{if(y.button>0)return;if(p!==null&&p!==y.pointerId){if(T==="pen"&&y.pointerType!=="pen")return;D({pointerId:p})}y.preventDefault(),p=y.pointerId,T=y.pointerType,O=i.getBoundingClientRect();try{i.setPointerCapture(y.pointerId)}catch{}let C=H(y);if(x){P=j(C.x,C.y);return}v&&d.length&&(B("idle"),b=!0),m=[C],S()},{passive:!1}),i.addEventListener("pointermove",y=>{if(p!==y.pointerId)return;y.preventDefault();let C=y.getCoalescedEvents?y.getCoalescedEvents():null,E=C&&C.length?C:[y];if(x){for(let L of E){let _=H(L);j(_.x,_.y)&&(P=!0)}return}for(let L of E)m.push(H(L));S()},{passive:!1});let D=(y,C=!1)=>{if(p===y.pointerId){try{i.releasePointerCapture(y.pointerId)}catch{}if(p=null,T=null,O=null,x){P&&(A=Y(),k(),e&&e(d)),P=!1;return}if(m.length>0){let E=m;if(E.length===1){if(C){m=[],S(),b&&(b=!1,e&&e(d));return}let _=E[0];E=[{x:_.x-1,y:_.y,p:_.p},{x:_.x+1,y:_.y,p:_.p}]}let L=d.length?d:b?w:null;if(a&&L&&L.length&&yt(E,L,h||{})){m=[],A=Y(),b=!1,d.length?B("scribble"):(S(),c&&c("scribble")),e&&e(d);return}E.id=I++,d=[...d,E],m=[],b=!1,A=Y(),k(),e&&e(d)}S()}};return i.addEventListener("pointerup",y=>D(y)),i.addEventListener("pointercancel",y=>D(y,!0)),{el:i,getStrokes:()=>d,setInk(y){l=y,S()},setErasing(y){x=!!y,i.style.cursor=x?"cell":"crosshair"},isErasing:()=>x,repaint:S,isStale:()=>v,undoClear(){return!w||!w.length?!1:(d=d.length?[...w,...d]:w,w=null,A=Y(),k(),S(),e&&e(d),!0)},configure(y={}){"idleOverwrite"in y&&(s=Number(y.idleOverwrite)||0),"scribbleClear"in y&&(a=!!y.scribbleClear),"scribble"in y&&(h=y.scribble),"staleAlpha"in y&&(f=Number(y.staleAlpha)),k()},clear(){d=[],m=[],p=null,T=null,O=null,clearTimeout(M),M=0,F(!1),b=!1,S(),e&&e(d)}}}var Z=class extends W{attach(o,{width:l=240,height:e=240,ink:t="#1e293b",idleOverwrite:s=2,scribbleClear:a=!0,scribble:h=null,staleAlpha:c,onStale:f}={}){let n=gt({width:l,height:e,ink:t,idleOverwrite:s,scribbleClear:a,scribble:h,onStale:f,...c===void 0?{}:{staleAlpha:c},onClear:i=>o.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:i,undo:()=>n.undoClear()}})),onStrokeEnd:async i=>{if(!i.length){o.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let u=await this.recognize(i);o.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:u,strokes:i}}))}});return o.appendChild(n.el),{clear:n.clear,undoClear:n.undoClear,isStale:n.isStale,configure:n.configure,setInk:n.setInk,repaint:n.repaint,getStrokes:n.getStrokes,canvas:n.el}}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharCnn=Z);})();
|
|
@@ -4,13 +4,13 @@ window.MILLIREC_CNN = {
|
|
|
4
4
|
"classes": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
|
5
5
|
"stages": [
|
|
6
6
|
{
|
|
7
|
-
"model": "tiny.bin",
|
|
8
|
-
"head": "tiny.head.bin",
|
|
7
|
+
"model": "options/accurate/tiny.bin",
|
|
8
|
+
"head": "options/accurate/tiny.head.bin",
|
|
9
9
|
"theta": 2.032
|
|
10
10
|
},
|
|
11
11
|
{
|
|
12
|
-
"model": "base.q4.bin",
|
|
13
|
-
"head": "base.head.bin"
|
|
12
|
+
"model": "options/accurate/base.q4.bin",
|
|
13
|
+
"head": "options/accurate/base.head.bin"
|
|
14
14
|
}
|
|
15
15
|
],
|
|
16
16
|
"kernel": "cnn-web.js"
|
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
"classes": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
|
3
3
|
"stages": [
|
|
4
4
|
{
|
|
5
|
-
"model": "tiny.bin",
|
|
6
|
-
"head": "tiny.head.bin",
|
|
5
|
+
"model": "options/accurate/tiny.bin",
|
|
6
|
+
"head": "options/accurate/tiny.head.bin",
|
|
7
7
|
"theta": 2.032
|
|
8
8
|
},
|
|
9
9
|
{
|
|
10
|
-
"model": "base.q4.bin",
|
|
11
|
-
"head": "base.head.bin"
|
|
10
|
+
"model": "options/accurate/base.q4.bin",
|
|
11
|
+
"head": "options/accurate/base.head.bin"
|
|
12
12
|
}
|
|
13
13
|
],
|
|
14
14
|
"kernel": "cnn-web.js"
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// digits: digits 0–9, the accurate pair of networks
|
|
2
|
+
// 99.6% top-1 on strangers' digits (EMNIST, 3,000 test images), 20% escalated; 100% of the project's own writer's held-out drawings
|
|
3
|
+
window.MILLIREC_CNN = {
|
|
4
|
+
"classes": "0123456789",
|
|
5
|
+
"stages": [
|
|
6
|
+
{
|
|
7
|
+
"model": "options/digits/digits-tiny.bin",
|
|
8
|
+
"head": "options/digits/digits-tiny.head.bin",
|
|
9
|
+
"theta": 3.257
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"model": "options/digits/digits-base.q4.bin",
|
|
13
|
+
"head": "options/digits/digits-base.head.bin"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"kernel": "cnn-web.js"
|
|
17
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"classes": "0123456789",
|
|
3
|
+
"stages": [
|
|
4
|
+
{
|
|
5
|
+
"model": "options/digits/digits-tiny.bin",
|
|
6
|
+
"head": "options/digits/digits-tiny.head.bin",
|
|
7
|
+
"theta": 3.257
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"model": "options/digits/digits-base.q4.bin",
|
|
11
|
+
"head": "options/digits/digits-base.head.bin"
|
|
12
|
+
}
|
|
13
|
+
],
|
|
14
|
+
"kernel": "cnn-web.js"
|
|
15
|
+
}
|
|
Binary file
|
|
Binary file
|
|
@@ -4,13 +4,13 @@ window.MILLIREC_CNN = {
|
|
|
4
4
|
"classes": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
|
5
5
|
"stages": [
|
|
6
6
|
{
|
|
7
|
-
"model": "tiny.bin",
|
|
8
|
-
"head": "tiny.head.bin",
|
|
7
|
+
"model": "options/fast/tiny.bin",
|
|
8
|
+
"head": "options/fast/tiny.head.bin",
|
|
9
9
|
"theta": 0.89
|
|
10
10
|
},
|
|
11
11
|
{
|
|
12
|
-
"model": "base-p25.bin",
|
|
13
|
-
"head": "base-p25.head.bin"
|
|
12
|
+
"model": "options/fast/base-p25.bin",
|
|
13
|
+
"head": "options/fast/base-p25.head.bin"
|
|
14
14
|
}
|
|
15
15
|
],
|
|
16
16
|
"kernel": "cnn-web.js"
|
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
"classes": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
|
3
3
|
"stages": [
|
|
4
4
|
{
|
|
5
|
-
"model": "tiny.bin",
|
|
6
|
-
"head": "tiny.head.bin",
|
|
5
|
+
"model": "options/fast/tiny.bin",
|
|
6
|
+
"head": "options/fast/tiny.head.bin",
|
|
7
7
|
"theta": 0.89
|
|
8
8
|
},
|
|
9
9
|
{
|
|
10
|
-
"model": "base-p25.bin",
|
|
11
|
-
"head": "base-p25.head.bin"
|
|
10
|
+
"model": "options/fast/base-p25.bin",
|
|
11
|
+
"head": "options/fast/base-p25.head.bin"
|
|
12
12
|
}
|
|
13
13
|
],
|
|
14
14
|
"kernel": "cnn-web.js"
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// lowercase: lowercase letters a–z, the accurate pair of networks
|
|
2
|
+
// 93.73% top-1 on strangers' lowercase (EMNIST, 7,800 test images), 20% escalated; 98.96% of the project's own writer's held-out drawings
|
|
3
|
+
window.MILLIREC_CNN = {
|
|
4
|
+
"classes": "abcdefghijklmnopqrstuvwxyz",
|
|
5
|
+
"stages": [
|
|
6
|
+
{
|
|
7
|
+
"model": "options/lowercase/lowercase-tiny.bin",
|
|
8
|
+
"head": "options/lowercase/lowercase-tiny.head.bin",
|
|
9
|
+
"theta": 1.177
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"model": "options/lowercase/lowercase-base.q4.bin",
|
|
13
|
+
"head": "options/lowercase/lowercase-base.head.bin"
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"kernel": "cnn-web.js"
|
|
17
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"classes": "abcdefghijklmnopqrstuvwxyz",
|
|
3
|
+
"stages": [
|
|
4
|
+
{
|
|
5
|
+
"model": "options/lowercase/lowercase-tiny.bin",
|
|
6
|
+
"head": "options/lowercase/lowercase-tiny.head.bin",
|
|
7
|
+
"theta": 1.177
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"model": "options/lowercase/lowercase-base.q4.bin",
|
|
11
|
+
"head": "options/lowercase/lowercase-base.head.bin"
|
|
12
|
+
}
|
|
13
|
+
],
|
|
14
|
+
"kernel": "cnn-web.js"
|
|
15
|
+
}
|
|
Binary file
|
|
Binary file
|
|
@@ -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,17 @@ 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
|
+
if (this.booted) {
|
|
695
|
+
this.flush();
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
const e = notServed(workerUrl, "the char-lite worker", assetBase, "char-lite");
|
|
699
|
+
e.message += ` (${evt.message || "script failed to load"})`;
|
|
700
|
+
this.failBoot(e);
|
|
701
|
+
};
|
|
702
|
+
this.assetBase = assetBase;
|
|
665
703
|
}
|
|
666
704
|
onMessage(evt) {
|
|
667
705
|
const d = evt.data;
|
|
@@ -679,9 +717,12 @@ var StrokeWorker = class {
|
|
|
679
717
|
this.worker.postMessage({ type: "addPoints", points, m: idx * this.samplesPerChar + i, scale });
|
|
680
718
|
});
|
|
681
719
|
});
|
|
720
|
+
this.booted = true;
|
|
682
721
|
this.readyResolve();
|
|
683
722
|
} else if (d.type === "addResult" && d.result) {
|
|
723
|
+
this.cache.delete(d.path);
|
|
684
724
|
this.cache.set(d.path, d.result);
|
|
725
|
+
if (this.cache.size > CACHE_MAX) this.cache.delete(this.cache.keys().next().value);
|
|
685
726
|
const waiters = this.inFlight.get(d.path) || [];
|
|
686
727
|
this.inFlight.delete(d.path);
|
|
687
728
|
for (const resolve of waiters) resolve(this.applyPlugins(d.result, d.path));
|
|
@@ -690,7 +731,30 @@ var StrokeWorker = class {
|
|
|
690
731
|
this.allWaiters.delete(d.path);
|
|
691
732
|
for (const resolve of waiters) resolve(d.costs);
|
|
692
733
|
} else if (d.type === "bootError") {
|
|
693
|
-
this.
|
|
734
|
+
const e = notServed(this.assetBase + "millirec.wasm", "the char-lite matcher", this.assetBase, "char-lite");
|
|
735
|
+
e.message += ` (worker boot failed: ${d.message})`;
|
|
736
|
+
this.failBoot(e);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
/** Everyone waiting on the worker gets null, and nothing is left "in flight". */
|
|
740
|
+
flush() {
|
|
741
|
+
for (const map of [this.inFlight, this.allWaiters]) {
|
|
742
|
+
const lists = [...map.values()];
|
|
743
|
+
map.clear();
|
|
744
|
+
for (const list of lists) for (const done of list) done(null);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/** The worker never came up: create() rejects with `e`, and the worker and its boot URL are released. */
|
|
748
|
+
failBoot(e) {
|
|
749
|
+
this.readyReject(e);
|
|
750
|
+
this.destroyed = true;
|
|
751
|
+
try {
|
|
752
|
+
this.worker.terminate();
|
|
753
|
+
} catch {
|
|
754
|
+
}
|
|
755
|
+
if (this.bootUrl) {
|
|
756
|
+
URL.revokeObjectURL(this.bootUrl);
|
|
757
|
+
this.bootUrl = null;
|
|
694
758
|
}
|
|
695
759
|
}
|
|
696
760
|
applyPlugins(raw, path) {
|
|
@@ -713,10 +777,16 @@ var StrokeWorker = class {
|
|
|
713
777
|
return "strokes:" + flat.length + ":" + hash.toString(36);
|
|
714
778
|
}
|
|
715
779
|
async recognize(strokes) {
|
|
716
|
-
if (!strokes || !strokes.length) return null;
|
|
780
|
+
if (this.destroyed || !strokes || !strokes.length) return null;
|
|
717
781
|
await this.readyPromise;
|
|
782
|
+
if (this.destroyed) return null;
|
|
718
783
|
const key = this.keyFor(strokes);
|
|
719
|
-
if (this.cache.has(key))
|
|
784
|
+
if (this.cache.has(key)) {
|
|
785
|
+
const hit = this.cache.get(key);
|
|
786
|
+
this.cache.delete(key);
|
|
787
|
+
this.cache.set(key, hit);
|
|
788
|
+
return this.applyPlugins(hit, key);
|
|
789
|
+
}
|
|
720
790
|
if (!this.uploadTest(strokes)) return null;
|
|
721
791
|
return new Promise((resolve) => {
|
|
722
792
|
let timer;
|
|
@@ -729,11 +799,21 @@ var StrokeWorker = class {
|
|
|
729
799
|
this.inFlight.set(key, [done]);
|
|
730
800
|
this.worker.postMessage({ type: "compare", path: key, elementID: "req" + ++this.reqCounter });
|
|
731
801
|
}
|
|
732
|
-
timer = setTimeout(() =>
|
|
802
|
+
timer = setTimeout(() => {
|
|
803
|
+
const waiting = this.inFlight.get(key);
|
|
804
|
+
if (waiting) {
|
|
805
|
+
const i = waiting.indexOf(done);
|
|
806
|
+
if (i >= 0) waiting.splice(i, 1);
|
|
807
|
+
if (!waiting.length) this.inFlight.delete(key);
|
|
808
|
+
}
|
|
809
|
+
done(null);
|
|
810
|
+
}, 4e3);
|
|
733
811
|
});
|
|
734
812
|
}
|
|
735
813
|
async rawScores(strokes) {
|
|
814
|
+
if (this.destroyed) return null;
|
|
736
815
|
await this.readyPromise;
|
|
816
|
+
if (this.destroyed) return null;
|
|
737
817
|
if (!this.uploadTest(strokes)) return null;
|
|
738
818
|
const key = "all:" + ++this.reqCounter;
|
|
739
819
|
const costs = await new Promise((resolve) => {
|
|
@@ -744,16 +824,25 @@ var StrokeWorker = class {
|
|
|
744
824
|
};
|
|
745
825
|
this.allWaiters.set(key, [done]);
|
|
746
826
|
this.worker.postMessage({ type: "compareAll", path: key, counts: this.charList.map((c) => this.trainPaths[c].length) });
|
|
747
|
-
timer = setTimeout(() =>
|
|
827
|
+
timer = setTimeout(() => {
|
|
828
|
+
this.allWaiters.delete(key);
|
|
829
|
+
done(null);
|
|
830
|
+
}, 8e3);
|
|
748
831
|
});
|
|
749
832
|
return costs ? { classes: this.charList, costs } : null;
|
|
750
833
|
}
|
|
834
|
+
/** Stop the worker; anything still waiting gets null, and so does every later call. */
|
|
751
835
|
destroy() {
|
|
836
|
+
if (this.destroyed) return;
|
|
837
|
+
this.destroyed = true;
|
|
752
838
|
this.worker.terminate();
|
|
753
839
|
if (this.bootUrl) {
|
|
754
840
|
URL.revokeObjectURL(this.bootUrl);
|
|
755
841
|
this.bootUrl = null;
|
|
756
842
|
}
|
|
843
|
+
this.flush();
|
|
844
|
+
this.cache.clear();
|
|
845
|
+
this.readyResolve();
|
|
757
846
|
}
|
|
758
847
|
};
|
|
759
848
|
var toPairs = (parsed) => parsed ? parsed.chars.map((c, i) => ({ char: c, prob: parsed.probs[i] })) : null;
|
|
@@ -800,6 +889,9 @@ var MillirecCharLite = class {
|
|
|
800
889
|
const config = { ...g.MILLIREC_CONFIG || {}, ...opts };
|
|
801
890
|
const training = opts.training || g.MILLIREC_TRAINING;
|
|
802
891
|
if (!training) throw new Error("MillirecCharLite: no training data (training.js missing?)");
|
|
892
|
+
if (typeof Worker === "undefined" || typeof Blob === "undefined") {
|
|
893
|
+
throw new Error("millirec: char-lite needs a browser (Worker, fetch, canvas); importing is SSR-safe but call create() on the client");
|
|
894
|
+
}
|
|
803
895
|
const inst = new this(config, training);
|
|
804
896
|
await inst.ready;
|
|
805
897
|
return inst;
|
|
@@ -869,15 +961,25 @@ if (typeof window !== "undefined" && false) {
|
|
|
869
961
|
if (!window.MillirecChar) window.MillirecChar = MillirecCharLite;
|
|
870
962
|
}
|
|
871
963
|
|
|
964
|
+
// src/here.js
|
|
965
|
+
var url = (import.meta.url || "").replace(/[?#].*$/, "");
|
|
966
|
+
var HERE = url.slice(0, url.lastIndexOf("/") + 1);
|
|
967
|
+
function nodeFileUrl(url2, spec) {
|
|
968
|
+
const g = globalThis;
|
|
969
|
+
const node = typeof g.process !== "undefined" && g.process.versions && g.process.versions.node && typeof g.Deno === "undefined" && typeof g.Bun === "undefined";
|
|
970
|
+
if (url2.startsWith("file:") && node && typeof document === "undefined" && typeof WorkerGlobalScope === "undefined") {
|
|
971
|
+
throw new Error(`millirec: cannot fetch ${url2} outside a browser \u2014 in Node, import the JSON instead: import x from '${spec}' with { type: 'json' }`);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
872
975
|
// src/char-lite.js
|
|
873
|
-
var HERE = new URL("./", import.meta.url).href;
|
|
874
976
|
var SETS = ["all", "capitals", "digits", "lowercase", "punctuation"];
|
|
875
977
|
async function loadSet(name, { assetBase = HERE } = {}) {
|
|
876
978
|
if (!SETS.includes(name)) throw new Error(`millirec: no training set "${name}" (one of ${SETS.join(", ")})`);
|
|
877
|
-
const
|
|
878
|
-
const
|
|
879
|
-
|
|
880
|
-
return
|
|
979
|
+
const base = assetBaseOf(assetBase);
|
|
980
|
+
const url2 = new URL(`sets/${name}.json`, base).href;
|
|
981
|
+
nodeFileUrl(url2, `millirec/char-lite/sets/${name}.json`);
|
|
982
|
+
return fetchAsset(url2, { what: `the ${name} training set`, base, recognizer: "char-lite" });
|
|
881
983
|
}
|
|
882
984
|
var MillirecCharLite2 = class extends MillirecCharLite {
|
|
883
985
|
/** As the script-tag create(), but `training` is required (no window.MILLIREC_TRAINING)
|