millirec 0.1.1 → 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.
Files changed (41) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +133 -11
  3. package/dist/char-cnn/core.d.ts +13 -1
  4. package/dist/char-cnn/core.js +70 -2
  5. package/dist/char-cnn/index.js +70 -2
  6. package/dist/char-cnn/millirec-char-cnn-core.min.js +1 -1
  7. package/dist/char-cnn/millirec-char-cnn.min.js +1 -1
  8. package/dist/char-cnn/options/accurate.js +4 -4
  9. package/dist/char-cnn/options/accurate.json +4 -4
  10. package/dist/char-cnn/options/digits/digits-base.head.bin +0 -0
  11. package/dist/char-cnn/options/digits/digits-base.q4.bin +0 -0
  12. package/dist/char-cnn/options/digits/digits-tiny.bin +0 -0
  13. package/dist/char-cnn/options/digits/digits-tiny.head.bin +0 -0
  14. package/dist/char-cnn/options/digits.js +17 -0
  15. package/dist/char-cnn/options/digits.json +15 -0
  16. package/dist/char-cnn/options/fast/tiny.bin +0 -0
  17. package/dist/char-cnn/options/fast/tiny.head.bin +0 -0
  18. package/dist/char-cnn/options/fast.js +4 -4
  19. package/dist/char-cnn/options/fast.json +4 -4
  20. package/dist/char-cnn/options/lowercase/lowercase-base.head.bin +0 -0
  21. package/dist/char-cnn/options/lowercase/lowercase-base.q4.bin +0 -0
  22. package/dist/char-cnn/options/lowercase/lowercase-tiny.bin +0 -0
  23. package/dist/char-cnn/options/lowercase/lowercase-tiny.head.bin +0 -0
  24. package/dist/char-cnn/options/lowercase.js +17 -0
  25. package/dist/char-cnn/options/lowercase.json +15 -0
  26. package/dist/char-cnn/options/small/tiny.bin +0 -0
  27. package/dist/char-cnn/options/small/tiny.head.bin +0 -0
  28. package/dist/char-cnn/options/small.js +2 -2
  29. package/dist/char-cnn/options/small.json +2 -2
  30. package/dist/char-lite/index.js +42 -8
  31. package/dist/char-lite/millirec-char-lite.min.js +1 -1
  32. package/dist/char-lite/millirec.wasm +0 -0
  33. package/dist/char-lite/sets.json +25 -29
  34. package/dist/overlap/millirec.wasm +0 -0
  35. package/package.json +10 -2
  36. /package/dist/char-cnn/{base.head.bin → options/accurate/base.head.bin} +0 -0
  37. /package/dist/char-cnn/{base.q4.bin → options/accurate/base.q4.bin} +0 -0
  38. /package/dist/char-cnn/{tiny.bin → options/accurate/tiny.bin} +0 -0
  39. /package/dist/char-cnn/{tiny.head.bin → options/accurate/tiny.head.bin} +0 -0
  40. /package/dist/char-cnn/{base-p25.bin → options/fast/base-p25.bin} +0 -0
  41. /package/dist/char-cnn/{base-p25.head.bin → options/fast/base-p25.head.bin} +0 -0
@@ -1 +1 @@
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);})();
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"
@@ -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
+ }
@@ -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"
@@ -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
+ }
@@ -4,8 +4,8 @@ window.MILLIREC_CNN = {
4
4
  "classes": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
5
5
  "stages": [
6
6
  {
7
- "model": "tiny.bin",
8
- "head": "tiny.head.bin"
7
+ "model": "options/small/tiny.bin",
8
+ "head": "options/small/tiny.head.bin"
9
9
  }
10
10
  ]
11
11
  }
@@ -2,8 +2,8 @@
2
2
  "classes": "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
3
3
  "stages": [
4
4
  {
5
- "model": "tiny.bin",
6
- "head": "tiny.head.bin"
5
+ "model": "options/small/tiny.bin",
6
+ "head": "options/small/tiny.head.bin"
7
7
  }
8
8
  ]
9
9
  }
@@ -691,9 +691,13 @@ var StrokeWorker = class {
691
691
  this.worker.onmessage = (evt) => this.onMessage(evt);
692
692
  const workerUrl = assetBase + workerName;
693
693
  this.worker.onerror = (evt) => {
694
+ if (this.booted) {
695
+ this.flush();
696
+ return;
697
+ }
694
698
  const e = notServed(workerUrl, "the char-lite worker", assetBase, "char-lite");
695
699
  e.message += ` (${evt.message || "script failed to load"})`;
696
- this.readyReject(e);
700
+ this.failBoot(e);
697
701
  };
698
702
  this.assetBase = assetBase;
699
703
  }
@@ -713,6 +717,7 @@ var StrokeWorker = class {
713
717
  this.worker.postMessage({ type: "addPoints", points, m: idx * this.samplesPerChar + i, scale });
714
718
  });
715
719
  });
720
+ this.booted = true;
716
721
  this.readyResolve();
717
722
  } else if (d.type === "addResult" && d.result) {
718
723
  this.cache.delete(d.path);
@@ -728,7 +733,28 @@ var StrokeWorker = class {
728
733
  } else if (d.type === "bootError") {
729
734
  const e = notServed(this.assetBase + "millirec.wasm", "the char-lite matcher", this.assetBase, "char-lite");
730
735
  e.message += ` (worker boot failed: ${d.message})`;
731
- this.readyReject(e);
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;
732
758
  }
733
759
  }
734
760
  applyPlugins(raw, path) {
@@ -773,7 +799,15 @@ var StrokeWorker = class {
773
799
  this.inFlight.set(key, [done]);
774
800
  this.worker.postMessage({ type: "compare", path: key, elementID: "req" + ++this.reqCounter });
775
801
  }
776
- timer = setTimeout(() => done(null), 4e3);
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);
777
811
  });
778
812
  }
779
813
  async rawScores(strokes) {
@@ -790,7 +824,10 @@ var StrokeWorker = class {
790
824
  };
791
825
  this.allWaiters.set(key, [done]);
792
826
  this.worker.postMessage({ type: "compareAll", path: key, counts: this.charList.map((c) => this.trainPaths[c].length) });
793
- timer = setTimeout(() => done(null), 8e3);
827
+ timer = setTimeout(() => {
828
+ this.allWaiters.delete(key);
829
+ done(null);
830
+ }, 8e3);
794
831
  });
795
832
  return costs ? { classes: this.charList, costs } : null;
796
833
  }
@@ -803,10 +840,7 @@ var StrokeWorker = class {
803
840
  URL.revokeObjectURL(this.bootUrl);
804
841
  this.bootUrl = null;
805
842
  }
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
- }
843
+ this.flush();
810
844
  this.cache.clear();
811
845
  this.readyResolve();
812
846
  }
@@ -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 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));})();
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((h,d)=>{let m=1/0;for(let p=0;p<3;p++)p!==d&&(m=Math.min(m,u[p]));return ht(h,m,a)});return{chars:n,probs:l}}let o=Math.max(r[1],s/1e3),c=Math.exp(-1*s/o);for(let u=0;u<3;u++)c+=Math.exp(-1*r[2*u+1]/o);let i=[];for(let u=0;u<3;u++)i.push(Math.exp(-1*r[2*u+1]/o)/c);return{chars:n,probs:i}}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),o=Math.round(r[n].y);t.push(n===0?a:a-s[0]),e.push(n===0?o:o-s[1]),s=[a,o]}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 h=r[l];e[0]+=h.x,e[1]+=h.y;let d={x:h.x,y:h.y,a:1.570795};l>0&&h.x!==s[0]&&(d.a=Math.atan2(h.y-s[1],h.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=[h.x,h.y],n.push(d)}e[0]/=t,e[1]/=t;let a=[0,0],o=[0,0],c=[0,0],i=[0,0];for(let l of n)l.x<e[0]?(c[0]+=l.x-e[0],c[1]++):(i[0]+=l.x-e[0],i[1]++),l.y<e[1]?(a[0]+=l.y-e[1],a[1]++):(o[0]+=l.y-e[1],o[1]++),l.x-=e[0],l.y-=e[1];a[1]>0&&(a[0]/=a[1]),o[1]>0&&(o[0]/=o[1]),c[1]>0&&(c[0]/=c[1]),i[1]>0&&(i[0]/=i[1]);let u=o[0]-a[0]<i[0]-c[0]?100/(i[0]-c[0]):a[0]<o[0]?100/(o[0]-a[0]):1;return{points:n,scale:u}}function N(r,t=50){let e=[],s=0;for(let o of r)for(let c=1;c<o.length;c++){let i=o[c].x-o[c-1].x,u=o[c].y-o[c-1].y,l=Math.sqrt(i*i+u*u);e.push({ax:o[c-1].x,ay:o[c-1].y,bx:o[c].x,by:o[c].y,cumStart:s,cumEnd:s+l}),s+=l}if(!s||!e.length)return null;let n=[],a=0;for(let o=0;o<t;o++){let c=o*s/(t-1);for(;a<e.length-1&&e[a].cumEnd<c;)a++;let i=e[a],u=i.cumEnd-i.cumStart,l=u?Math.min(1,Math.max(0,(c-i.cumStart)/u)):0;n.push({x:i.ax+(i.bx-i.ax)*l,y:i.ay+(i.by-i.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,o)=>{ut(a)||t.push(`class ${e} sample ${o}: 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},R=2;function rt(r){return{x0:r.x0-R,y0:r.y0-R,x1:r.x1+R,y1:r.y1+R,w:r.w+2*R,h:r.h+2*R}}function nt(r){let t=1/0,e=1/0,s=-1/0,n=-1/0;for(let a of r){let o=a.x!==void 0?a.x:a[0],c=a.y!==void 0?a.y:a[1];o<t&&(t=o),o>s&&(s=o),c<e&&(e=c),c>n&&(n=c)}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 i of r)i<e&&(e=i),i>s&&(s=i);let n=(s-e)*t;if(!(n>0))return 0;let a=0,o=r[0],c=0;for(let i of r)a>0?i>o?o=i:i<o-n&&(c++,a=-1,o=i):a<0?i<o?o=i:i>o+n&&(c++,a=1,o=i):i>o+n?(a=1,o=i):i<o-n&&(a=-1,o=i);return c}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 o=s+a,c=s*a-n*n,i=o/2+Math.sqrt(Math.max(0,o*o/4-c)),u=n,l=i-s;Math.hypot(u,l)<1e-9&&(u=1,l=0);let h=Math.hypot(u,l);return{ux:u/h,uy:l/h}}var gt=.09,xt=4;function wt(r,t){let e=Math.max(2,t*gt),s=e/2,n=[r[0]],a=0;for(let l=1;l<r.length;l++){let h=r[l].x-r[l-1].x,d=r[l].y-r[l-1].y,m=Math.hypot(h,d);if(!(m>0))continue;let p=(s-a)/m;for(;p<=1;)n.push({x:r[l-1].x+h*p,y:r[l-1].y+d*p}),p+=s/m;a=(a+m)%s}if(n.length<8)return 0;let o=Math.round(xt*e/s),c=l=>`${Math.floor(l.x/e)},${Math.floor(l.y/e)}`,i=new Map;n.forEach((l,h)=>{let d=c(l);i.has(d)||i.set(d,[]),i.get(d).push(h)});let u=0;for(let l=0;l<n.length;l++){let h=n[l],d=Math.floor(h.x/e),m=Math.floor(h.y/e),p=!1;for(let b=-1;b<=1&&!p;b++)for(let y=-1;y<=1&&!p;y++)for(let g of i.get(`${d+b},${m+y}`)||[])if(!(Math.abs(l-g)<=o)&&Math.hypot(n[g].x-h.x,n[g].y-h.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 g={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(g.x-A.x,g.y-A.y)>.75)&&n.push(g)}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 o=nt(n),c=Math.hypot(o.w,o.h),{ux:i,uy:u}=mt(n),l=n.map(y=>y.x*i+y.y*u),h=n.map(y=>-y.x*u+y.y*i),d=ot(l,s.deadband),m=ot(h,s.deadband),p=0,b=[];for(let y of t)for(let g of y)b.push(g);if(b.length){let y=rt(nt(b)),g=rt(o),A=Math.max(0,Math.min(y.x1,g.x1)-Math.max(y.x0,g.x0)),P=Math.max(0,Math.min(y.y1,g.y1)-Math.max(y.y0,g.y0));p=A/Math.min(y.w,g.w)*(P/Math.min(y.h,g.h))}return{turns:d,cross:m,retrace:wt(n,c),winding:c>0?a/c:0,cover:p,length:a,span:c}}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:o=!1,scribble:c=null,onClear:i=null,staleAlpha:u=.3,onStale:l=null}){let h=document.createElement("canvas"),d=typeof devicePixelRatio<"u"&&devicePixelRatio||1;h.width=r*d,h.height=t*d,h.style.width=r+"px",h.style.height=t+"px",h.style.touchAction="none";let m=h.getContext("2d");m.scale(d,d);let p=[],b=[],y=null,g=!1,A=1,P=0,E=0,I=!1,k=null,C=!1;function z(f,x){if(!(f.length<2)){m.strokeStyle=x||e,m.beginPath(),m.moveTo(f[0].x,f[0].y);for(let w=1;w<f.length;w++)m.lineTo(f[w].x,f[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 f of p)z(f,n&&n(f));m.globalAlpha=1,z(b,null)}function L(f){I!==f&&(I=f,M(),l&&l(f))}function _(){clearTimeout(E),E=0;let f=(Number(a)||0)*1e3;if(!f||!p.length){L(!1);return}let x=f-(O()-P);if(x<=0){L(!0);return}L(!1),E=setTimeout(()=>L(!0),x)}function Q(f){p.length&&(k=p,p=[],clearTimeout(E),E=0,L(!1),M(),i&&i(f))}function Z(f,x){let w=p.filter(v=>!v.some(S=>Math.hypot(S.x-f,S.y-x)<=Mt));return w.length===p.length?!1:(p=w,M(),!0)}let T=null,B=f=>{let x=T||(T=h.getBoundingClientRect()),w=r/(h.clientWidth||r),v=t/(h.clientHeight||t);return{x:(f.clientX-x.left-h.clientLeft)*w,y:(f.clientY-x.top-h.clientTop)*v,p:f.pressure||.5}},U=!1,j=null,D=f=>f.preventDefault();h.addEventListener("touchstart",D,{passive:!1}),h.addEventListener("touchmove",D,{passive:!1}),h.addEventListener("contextmenu",D),h.style.userSelect=h.style.webkitUserSelect="none",h.style.webkitTouchCallout="none",h.addEventListener("pointerdown",f=>{if(f.button>0)return;if(y!==null&&y!==f.pointerId){if(j==="pen"&&f.pointerType!=="pen")return;W({pointerId:y})}f.preventDefault(),y=f.pointerId,j=f.pointerType,T=h.getBoundingClientRect();try{h.setPointerCapture(f.pointerId)}catch{}let x=B(f);if(g){U=Z(x.x,x.y);return}I&&p.length&&(Q("idle"),C=!0),b=[x],M()},{passive:!1}),h.addEventListener("pointermove",f=>{if(y!==f.pointerId)return;f.preventDefault();let x=f.getCoalescedEvents?f.getCoalescedEvents():null,w=x&&x.length?x:[f];if(g){for(let v of w){let S=B(v);Z(S.x,S.y)&&(U=!0)}return}for(let v of w)b.push(B(v));M()},{passive:!1});let W=(f,x=!1)=>{if(y===f.pointerId){try{h.releasePointerCapture(f.pointerId)}catch{}if(y=null,j=null,T=null,g){U&&(P=O(),_(),s&&s(p)),U=!1;return}if(b.length>0){let w=b;if(w.length===1){if(x){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(o&&v&&v.length&&at(w,v,c||{})){b=[],P=O(),C=!1,p.length?Q("scribble"):(M(),i&&i("scribble")),s&&s(p);return}w.id=A++,p=[...p,w],b=[],C=!1,P=O(),_(),s&&s(p)}M()}};return h.addEventListener("pointerup",f=>W(f)),h.addEventListener("pointercancel",f=>W(f,!0)),{el:h,getStrokes:()=>p,setInk(f){e=f,M()},setErasing(f){g=!!f,h.style.cursor=g?"cell":"crosshair"},isErasing:()=>g,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(f={}){"idleOverwrite"in f&&(a=Number(f.idleOverwrite)||0),"scribbleClear"in f&&(o=!!f.scribbleClear),"scribble"in f&&(c=f.scribble),"staleAlpha"in f&&(u=Number(f.staleAlpha)),_()},clear(){p=[],b=[],y=null,j=null,T=null,clearTimeout(E),E=0,L(!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(i=>this.trainPaths[i].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 o=`self.__MILLIREC_ASSET_BASE=${JSON.stringify(t)};importScripts(${JSON.stringify(t+e)});`;this.bootUrl=URL.createObjectURL(new Blob([o],{type:"text/javascript"})),this.worker=new Worker(this.bootUrl),this.readyPromise=new Promise((i,u)=>{this.readyResolve=i,this.readyReject=u}),this.worker.onmessage=i=>this.onMessage(i);let c=t+e;this.worker.onerror=i=>{if(this.booted){this.flush();return}let u=K(c,"the char-lite worker",t,"char-lite");u.message+=` (${i.message||"script failed to load"})`,this.failBoot(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,o)=>{let{points:c,scale:i}=G(q(a));this.worker.postMessage({type:"addPoints",points:c,m:n*this.samplesPerChar+o,scale:i})})}),this.booted=!0,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.failBoot(s)}}flush(){for(let t of[this.inFlight,this.allWaiters]){let e=[...t.values()];t.clear();for(let s of e)for(let n of s)n(null)}}failBoot(t){this.readyReject(t),this.destroyed=!0;try{this.worker.terminate()}catch{}this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null)}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=N(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=o=>{clearTimeout(n),s(o)};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(()=>{let o=this.inFlight.get(e);if(o){let c=o.indexOf(a);c>=0&&o.splice(c,1),o.length||this.inFlight.delete(e)}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,o=c=>{clearTimeout(a),n(c)};this.allWaiters.set(e,[o]),this.worker.postMessage({type:"compareAll",path:e,counts:this.charList.map(c=>this.trainPaths[c].length)}),a=setTimeout(()=>{this.allWaiters.delete(e),o(null)},8e3)});return s?{classes:this.charList,costs:s}:null}destroy(){this.destroyed||(this.destroyed=!0,this.worker.terminate(),this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null),this.flush(),this.cache.clear(),this.readyResolve())}},Pt=r=>r?r.chars.map((t,e)=>({char:t,prob:r.probs[e]})):null,$=class{static strokesToSample(t,e=50){let s=N(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,o=i=>{let u=Array.isArray(i)?Array.isArray(i[0])?i:[i]:[q(i)],l=N(u,a);return l?V(l):null},c={...n.classes};for(let[i,u]of Object.entries(e||{})){let l=(u||[]).map(o).filter(Boolean);if(!l.length)continue;let h=c[i]?.samples||[];c[i]={...c[i]||{},samples:s?l:h.concat(l)}}return{...n,classes:c}}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:o=!0,scribble:c=null,staleAlpha:i,onStale:u}={}){let l=X({width:e,height:s,ink:n,idleOverwrite:a,scribbleClear:o,scribble:c,onStale:u,...i===void 0?{}:{staleAlpha:i},onClear:h=>t.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:h,undo:()=>l.undoClear()}})),onStrokeEnd:async h=>{if(!h.length){t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let d=await this.recognize(h);t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:d,strokes:h}}))}});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=$,window.MillirecChar||(window.MillirecChar=$));})();
Binary file
@@ -1,8 +1,8 @@
1
1
  {
2
- "generated": "2026-09-10T13:47:38.537Z",
2
+ "generated": "2026-11-16T20:48:50.138Z",
3
3
  "pps": 25,
4
4
  "folds": 3,
5
- "fixedKB": 54.2,
5
+ "fixedKB": 58.2,
6
6
  "sets": {
7
7
  "capitals": {
8
8
  "title": "Capital letters A–Z",
@@ -14,12 +14,12 @@
14
14
  "pps": 25,
15
15
  "top1": 99.69,
16
16
  "top3": 99.69,
17
- "msPerChar": 0.63,
17
+ "msPerChar": 0.49,
18
18
  "folds": 3,
19
19
  "trainingKB": 44.2,
20
20
  "trainingGz": 10.9,
21
- "bundleKB": 98.4,
22
- "zipKB": 37.1,
21
+ "bundleKB": 102.4,
22
+ "zipKB": 38.5,
23
23
  "errors": [
24
24
  "A→R"
25
25
  ],
@@ -33,22 +33,20 @@
33
33
  "cells": 381,
34
34
  "templates": 381,
35
35
  "pps": 25,
36
- "top1": 98.16,
36
+ "top1": 98.69,
37
37
  "top3": 100,
38
- "msPerChar": 0.68,
38
+ "msPerChar": 0.52,
39
39
  "folds": 3,
40
40
  "trainingKB": 49.9,
41
41
  "trainingGz": 11.4,
42
- "bundleKB": 104.1,
43
- "zipKB": 37.6,
42
+ "bundleKB": 108.1,
43
+ "zipKB": 38.9,
44
44
  "errors": [
45
45
  "a→u",
46
46
  "i→j",
47
- "t→e",
48
47
  "u→a",
49
48
  "u→a",
50
- "q→g",
51
- "s→y"
49
+ "q→g"
52
50
  ],
53
51
  "missing": ""
54
52
  },
@@ -60,17 +58,15 @@
60
58
  "cells": 126,
61
59
  "templates": 126,
62
60
  "pps": 25,
63
- "top1": 99.21,
61
+ "top1": 100,
64
62
  "top3": 100,
65
- "msPerChar": 0.32,
63
+ "msPerChar": 0.23,
66
64
  "folds": 3,
67
65
  "trainingKB": 17.1,
68
66
  "trainingGz": 4.4,
69
- "bundleKB": 71.3,
70
- "zipKB": 30.4,
71
- "errors": [
72
- "4→9"
73
- ],
67
+ "bundleKB": 75.3,
68
+ "zipKB": 31.8,
69
+ "errors": [],
74
70
  "missing": ""
75
71
  },
76
72
  "punctuation": {
@@ -83,12 +79,12 @@
83
79
  "pps": 25,
84
80
  "top1": 91.78,
85
81
  "top3": 98.63,
86
- "msPerChar": 0.2,
82
+ "msPerChar": 0.15,
87
83
  "folds": 3,
88
84
  "trainingKB": 9.4,
89
85
  "trainingGz": 1.7,
90
- "bundleKB": 63.6,
91
- "zipKB": 27.7,
86
+ "bundleKB": 67.6,
87
+ "zipKB": 29,
92
88
  "errors": [
93
89
  ".→,",
94
90
  ".→-",
@@ -108,13 +104,13 @@
108
104
  "templates": 903,
109
105
  "pps": 25,
110
106
  "top1": 92.03,
111
- "top3": 97.79,
112
- "msPerChar": 1.4,
107
+ "top3": 97.9,
108
+ "msPerChar": 1.13,
113
109
  "folds": 3,
114
110
  "trainingKB": 120.2,
115
111
  "trainingGz": 27,
116
- "bundleKB": 174.4,
117
- "zipKB": 53.9,
112
+ "bundleKB": 178.4,
113
+ "zipKB": 55.2,
118
114
  "errors": [
119
115
  "0→O",
120
116
  "1→I",
@@ -129,14 +125,14 @@
129
125
  "I→1",
130
126
  "i→j",
131
127
  "l→I",
128
+ "l→I",
132
129
  "M→m",
133
130
  "n→D",
134
131
  "o→O",
132
+ "s→S",
135
133
  "S→s",
136
- "t→e",
137
134
  "u→a",
138
135
  "U→u",
139
- "y→Y",
140
136
  "0→O",
141
137
  "1→I",
142
138
  "1→I",
@@ -155,7 +151,7 @@
155
151
  "s→S",
156
152
  "s→S",
157
153
  "u→U",
158
- "v→V"
154
+ "u→U"
159
155
  ],
160
156
  "missing": "%$"
161
157
  }
Binary file