millirec 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +286 -51
  3. package/dist/char-cnn/cnn-web.wasm +0 -0
  4. package/dist/char-cnn/core.d.ts +15 -1
  5. package/dist/char-cnn/core.js +214 -100
  6. package/dist/char-cnn/index.d.ts +1 -1
  7. package/dist/char-cnn/index.js +267 -137
  8. package/dist/char-cnn/millirec-char-cnn-core.min.js +1 -1
  9. package/dist/char-cnn/millirec-char-cnn.min.js +1 -1
  10. package/dist/char-cnn/options/accurate/tiny.head.bin +0 -0
  11. package/dist/char-cnn/options/accurate.js +6 -6
  12. package/dist/char-cnn/options/accurate.json +5 -5
  13. package/dist/char-cnn/options/all/all-base.head.bin +0 -0
  14. package/dist/char-cnn/options/all/all-base.q4.bin +0 -0
  15. package/dist/char-cnn/options/all/all-tiny.bin +0 -0
  16. package/dist/char-cnn/options/all/all-tiny.head.bin +0 -0
  17. package/dist/char-cnn/options/all-fast/all-base-p25.bin +0 -0
  18. package/dist/char-cnn/options/all-fast/all-base-p25.head.bin +0 -0
  19. package/dist/char-cnn/options/all-fast/all-tiny.bin +0 -0
  20. package/dist/char-cnn/options/all-fast/all-tiny.head.bin +0 -0
  21. package/dist/char-cnn/options/all-fast.js +17 -0
  22. package/dist/char-cnn/options/all-fast.json +15 -0
  23. package/dist/char-cnn/options/all-small/all-tiny-qat4.head.bin +0 -0
  24. package/dist/char-cnn/options/all-small/all-tiny-qat4.q4.bin +0 -0
  25. package/dist/char-cnn/options/all-small.js +11 -0
  26. package/dist/char-cnn/options/all-small.json +9 -0
  27. package/dist/char-cnn/options/all.js +17 -0
  28. package/dist/char-cnn/options/all.json +15 -0
  29. package/dist/char-cnn/options/digits/digits-base.head.bin +0 -0
  30. package/dist/char-cnn/options/digits/digits-base.q4.bin +0 -0
  31. package/dist/char-cnn/options/digits/digits-tiny.bin +0 -0
  32. package/dist/char-cnn/options/digits/digits-tiny.head.bin +0 -0
  33. package/dist/char-cnn/options/digits-fast/digits-base-p25.bin +0 -0
  34. package/dist/char-cnn/options/digits-fast/digits-base-p25.head.bin +0 -0
  35. package/dist/char-cnn/options/digits-fast/digits-tiny.bin +0 -0
  36. package/dist/char-cnn/options/digits-fast/digits-tiny.head.bin +0 -0
  37. package/dist/char-cnn/options/digits-fast.js +17 -0
  38. package/dist/char-cnn/options/digits-fast.json +15 -0
  39. package/dist/char-cnn/options/digits-small/digits-tiny-qat4.head.bin +0 -0
  40. package/dist/char-cnn/options/digits-small/digits-tiny-qat4.q4.bin +0 -0
  41. package/dist/char-cnn/options/digits-small.js +11 -0
  42. package/dist/char-cnn/options/digits-small.json +9 -0
  43. package/dist/char-cnn/options/digits.js +17 -0
  44. package/dist/char-cnn/options/digits.json +15 -0
  45. package/dist/char-cnn/options/fast/base-p25.head.bin +0 -0
  46. package/dist/char-cnn/options/fast/tiny.bin +0 -0
  47. package/dist/char-cnn/options/fast/tiny.head.bin +0 -0
  48. package/dist/char-cnn/options/fast.js +6 -6
  49. package/dist/char-cnn/options/fast.json +5 -5
  50. package/dist/char-cnn/options/lowercase/lowercase-base.head.bin +0 -0
  51. package/dist/char-cnn/options/lowercase/lowercase-base.q4.bin +0 -0
  52. package/dist/char-cnn/options/lowercase/lowercase-tiny.bin +0 -0
  53. package/dist/char-cnn/options/lowercase/lowercase-tiny.head.bin +0 -0
  54. package/dist/char-cnn/options/lowercase-fast/lowercase-base-p25.bin +0 -0
  55. package/dist/char-cnn/options/lowercase-fast/lowercase-base-p25.head.bin +0 -0
  56. package/dist/char-cnn/options/lowercase-fast/lowercase-tiny.bin +0 -0
  57. package/dist/char-cnn/options/lowercase-fast/lowercase-tiny.head.bin +0 -0
  58. package/dist/char-cnn/options/lowercase-fast.js +17 -0
  59. package/dist/char-cnn/options/lowercase-fast.json +15 -0
  60. package/dist/char-cnn/options/lowercase-small/lowercase-tiny-qat4.head.bin +0 -0
  61. package/dist/char-cnn/options/lowercase-small/lowercase-tiny-qat4.q4.bin +0 -0
  62. package/dist/char-cnn/options/lowercase-small.js +11 -0
  63. package/dist/char-cnn/options/lowercase-small.json +9 -0
  64. package/dist/char-cnn/options/lowercase.js +17 -0
  65. package/dist/char-cnn/options/lowercase.json +15 -0
  66. package/dist/char-cnn/options/small/tiny.head.bin +0 -0
  67. package/dist/char-cnn/options/small/tiny.q4.bin +0 -0
  68. package/dist/char-cnn/options/small.js +3 -3
  69. package/dist/char-cnn/options/small.json +2 -2
  70. package/dist/char-lite/core.d.ts +1 -0
  71. package/dist/char-lite/core.js +628 -0
  72. package/dist/char-lite/index.d.ts +28 -8
  73. package/dist/char-lite/index.js +459 -297
  74. package/dist/char-lite/millirec-char-lite.min.js +1 -1
  75. package/dist/char-lite/millirec.wasm +0 -0
  76. package/dist/char-lite/sets.json +25 -29
  77. package/dist/index.d.ts +35 -0
  78. package/dist/index.js +88 -0
  79. package/dist/overlap/millirec-overlap.min.js +7 -7
  80. package/dist/overlap/millirec.wasm +0 -0
  81. package/dist/pad/index.d.ts +8 -0
  82. package/dist/pad/index.js +482 -0
  83. package/package.json +30 -8
  84. package/dist/char-cnn/base-p25.head.bin +0 -0
  85. package/dist/char-cnn/tiny.head.bin +0 -0
  86. /package/dist/char-cnn/{base.head.bin → options/accurate/base.head.bin} +0 -0
  87. /package/dist/char-cnn/{base.q4.bin → options/accurate/base.q4.bin} +0 -0
  88. /package/dist/char-cnn/{tiny.bin → options/accurate/tiny.bin} +0 -0
  89. /package/dist/char-cnn/{base-p25.bin → options/fast/base-p25.bin} +0 -0
@@ -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 yt={image:{margin:.6884,mag:.6846,bias:-1.0768},imageGeom:{margin:.6925,mag:1.0731,bias:-2.4927}};function mt(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 V(r,t,e,s=1e3){let n=[];for(let u=0;u<3;u++)n.push(t[r[2*u]]);let a=yt[e];if(a){let u=[r[1],r[3],r[5]],f=u.map((h,m)=>{let y=1/0;for(let p=0;p<3;p++)p!==m&&(y=Math.min(y,u[p]));return mt(h,y,a)});return{chars:n,probs:f}}let i=Math.max(r[1],s/1e3),l=Math.exp(-1*s/i);for(let u=0;u<3;u++)l+=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)/l);return{chars:n,probs:o}}function J(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 rt(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 X(r){let t=r.length,e=[0,0],s=[0,0],n=[];for(let f=0;f<t;f++){let h=r[f];e[0]+=h.x,e[1]+=h.y;let m={x:h.x,y:h.y,a:1.570795};f>0&&h.x!==s[0]&&(m.a=Math.atan2(h.y-s[1],h.x-s[0])),m.s=Math.sin(m.a),m.c=Math.cos(m.a),f===1&&(n[0].s=m.s,n[0].c=m.c),s=[h.x,h.y],n.push(m)}e[0]/=t,e[1]/=t;let a=[0,0],i=[0,0],l=[0,0],o=[0,0];for(let f of n)f.x<e[0]?(l[0]+=f.x-e[0],l[1]++):(o[0]+=f.x-e[0],o[1]++),f.y<e[1]?(a[0]+=f.y-e[1],a[1]++):(i[0]+=f.y-e[1],i[1]++),f.x-=e[0],f.y-=e[1];a[1]>0&&(a[0]/=a[1]),i[1]>0&&(i[0]/=i[1]),l[1]>0&&(l[0]/=l[1]),o[1]>0&&(o[0]/=o[1]);let u=i[0]-a[0]<o[0]-l[0]?100/(o[0]-l[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){let l=i.length===1?[{x:i[0].x-.5,y:i[0].y},{x:i[0].x+.5,y:i[0].y}]:i;for(let o=1;o<l.length;o++){let u=l[o].x-l[o-1].x,f=l[o].y-l[o-1].y,h=Math.sqrt(u*u+f*f);e.push({ax:l[o-1].x,ay:l[o-1].y,bx:l[o].x,by:l[o].y,cumStart:s,cumEnd:s+h}),s+=h}}if(!s||!e.length)return null;let n=[],a=0;for(let i=0;i<t;i++){let l=i*s/(t-1);for(;a<e.length-1&&e[a].cumEnd<l;)a++;let o=e[a],u=o.cumEnd-o.cumStart,f=u?Math.min(1,Math.max(0,(l-o.cumStart)/u)):0;n.push({x:o.ax+(o.bx-o.ax)*f,y:o.ay+(o.by-o.ay)*f})}return n}function z(r){return rt(r)}var gt=r=>Array.isArray(r),xt=r=>gt(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 wt(r){return!!r&&typeof r=="object"&&!r.version&&!r.classes&&Object.values(r).every(Array.isArray)}function bt(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 Mt(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)=>{xt(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 K(r){let t=wt(r)?bt(r):r,e=Mt(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 nt(r){let t={};for(let[e,s]of Object.entries(r.classes))t[e]=s.samples;return t}function it(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 Y=(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 vt(){let r=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return r?r.slice(0,r.lastIndexOf("/")+1):""}var St=vt(),Pt=256,Q=class{constructor({assetBase:t,workerName:e,training:s,params:n}){t=it(t);let a=K(s);this.trainPaths=nt(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 l=t+e;this.worker.onerror=o=>{if(this.booted){this.flush();return}let u=Y(l,"the char-lite worker",t,"char-lite");u.message+=` (${o.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,i)=>{let{points:l,scale:o}=X(J(a));this.worker.postMessage({type:"addPoints",points:l,m:n*this.samplesPerChar+i,scale:o})})}),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>Pt&&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=Y(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=V(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}=X(s);return this.worker.postMessage({type:"addPoints",points:n,m:-1,scale:a}),!0}keyFor(t){let e=Array.isArray(t[0])?t:[t],s=2166136261,n=16777619,a=0,i=l=>{s=Math.imul(s^l,16777619),n=Math.imul(n^l,2246822519)};for(let l of e){i(2147483647^l.length);for(let o of l)i(Math.round(o.x*1e3)|0),i(Math.round(o.y*1e3)|0),a++}return"strokes:"+e.length+":"+a+":"+(s>>>0).toString(36)+(n>>>0).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(()=>{let i=this.inFlight.get(e);if(i){let l=i.indexOf(a);l>=0&&i.splice(l,1),i.length||this.inFlight.delete(e)}a(null)},4e3)}):null}async rawScores(t){if(this.destroyed||!t||!t.length||(await this.readyPromise,this.destroyed)||!this.uploadTest(t))return null;let e="all:"+ ++this.reqCounter,s=await new Promise(n=>{let a,i=l=>{clearTimeout(a),n(l)};this.allWaiters.set(e,[i]),this.worker.postMessage({type:"compareAll",path:e,counts:this.charList.map(l=>this.trainPaths[l].length)}),a=setTimeout(()=>{this.allWaiters.delete(e),i(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())}},ot=r=>{if(!r)return null;let t=new Set,e=[];return r.chars.forEach((s,n)=>{s!==void 0&&!t.has(s)&&(t.add(s),e.push({char:s,prob:r.probs[n]}))}),e},kt=r=>{let t=1/0,e=1/0;for(let s of r||[])s<t?(e=t,t=s):s<e&&(e=s);return t===1/0?1/0:e===1/0?.9*t*t*t:t*t*e};function at(r,t,{replace:e=!1}={}){let n=r&&r.classes&&!Object.keys(r.classes).length?{version:2,mode:"stroke",ext:{},...r,pointsPerShape:r.pointsPerShape||50,classes:{}}:K({...r}),a=n.pointsPerShape,i=o=>{let u=Array.isArray(o)?Array.isArray(o[0])?o:[o]:[J(o)],f=$(u,a);return f?z(f):null},l={...n.classes};for(let[o,u]of Object.entries(t||{})){let f=(u||[]).map(i).filter(Boolean);if(!f.length)continue;let h=l[o]?.samples||[];l[o]={...l[o]||{},samples:e?f:h.concat(f)}}return{...n,classes:l}}var B=class{static strokesToSample(t,e=50){let s=$(Array.isArray(t[0])?t:[t],e);return s?z(s):null}static withSamples(t,e,s){return at(t,e,s)}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.plugins=[],this.shipped=this.stroke=this.newWorker(e),this.ready=this.stroke.readyPromise}newWorker(t){let e=new Q({assetBase:this.config.assetBase||St,workerName:this.config.workerStroke||"worker-stroke.js",training:t,params:this.config.params?.stroke||this.config.params||null});return e.plugins=this.plugins,e}get engine(){return"char-lite"}get classes(){return this.shipped.charList}get charList(){return this.shipped.charList}use(t){return this.plugins.push(t),this}async recognize(t,{only:e=null}={}){if(!e)return ot(await this.stroke.recognize(t));let s=new Set(typeof e=="string"?[...e]:e),n=await this.stroke.rawScores(t);if(!n)return null;let a=n.classes.map((i,l)=>({i:l,c:i,v:kt(n.costs[l])})).filter(i=>s.has(i.c)&&i.v<1/0).sort((i,l)=>i.v-l.v).slice(0,3);if(!a.length)return[];for(;a.length<3;)a.push({...a[0],v:1e30});return ot(V(a.flatMap(i=>[i.i,i.v]),n.classes,"stroke",1e3))}async teach(t,{add:e=!1}={}){if(await this.ready,this.destroyed)return null;let s=e&&this.taught?this.taught:{version:2,mode:"stroke",pointsPerShape:this.shipped.pointsPerShape,classes:{}},n=at(s,t),a=Object.values(n.classes).reduce((l,o)=>l+o.samples.length,0);if(!a)return null;let i=this.newWorker(n);return await i.readyPromise,this.destroyed?(i.destroy(),null):(this.stroke!==this.shipped&&this.stroke.destroy(),this.stroke=i,this.taught=n,{classes:i.charList,n:a})}forget(){this.stroke!==this.shipped&&this.stroke.destroy(),this.stroke=this.shipped,this.taught=null}rawScores(t){return this.stroke.rawScores(t)}destroy(){this.destroyed=!0,this.stroke!==this.shipped&&this.stroke.destroy(),this.shipped.destroy()}};var ft={turns:5,retrace:.5,winding:3.5,cover:.6,minLength:40,minSpan:12,deadband:.22},I=2;function lt(r){return{x0:r.x0-I,y0:r.y0-I,x1:r.x1+I,y1:r.y1+I,w:r.w+2*I,h:r.h+2*I}}function ct(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],l=a.y!==void 0?a.y:a[1];i<t&&(t=i),i>s&&(s=i),l<e&&(e=l),l>n&&(n=l)}return{x0:t,y0:e,x1:s,y1:n,w:s-t,h:n-e}}function ht(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],l=0;for(let o of r)a>0?o>i?i=o:o<i-n&&(l++,a=-1,i=o):a<0?o<i?i=o:o>i+n&&(l++,a=1,i=o):o>i+n?(a=1,i=o):o<i-n&&(a=-1,i=o);return l}function At(r){let t=0,e=0;for(let m of r)t+=m.x,e+=m.y;t/=r.length,e/=r.length;let s=0,n=0,a=0;for(let m of r){let y=m.x-t,p=m.y-e;s+=y*y,n+=y*p,a+=p*p}let i=s+a,l=s*a-n*n,o=i/2+Math.sqrt(Math.max(0,i*i/4-l)),u=n,f=o-s;Math.hypot(u,f)<1e-9&&(u=1,f=0);let h=Math.hypot(u,f);return{ux:u/h,uy:f/h}}var Et=.09,Ct=4;function Lt(r,t){let e=Math.max(2,t*Et),s=e/2,n=[r[0]],a=0;for(let f=1;f<r.length;f++){let h=r[f].x-r[f-1].x,m=r[f].y-r[f-1].y,y=Math.hypot(h,m);if(!(y>0))continue;let p=(s-a)/y;for(;p<=1;)n.push({x:r[f-1].x+h*p,y:r[f-1].y+m*p}),p+=s/y;a=(a+y)%s}if(n.length<8)return 0;let i=Math.round(Ct*e/s),l=f=>`${Math.floor(f.x/e)},${Math.floor(f.y/e)}`,o=new Map;n.forEach((f,h)=>{let m=l(f);o.has(m)||o.set(m,[]),o.get(m).push(h)});let u=0;for(let f=0;f<n.length;f++){let h=n[f],m=Math.floor(h.x/e),y=Math.floor(h.y/e),p=!1;for(let b=-1;b<=1&&!p;b++)for(let d=-1;d<=1&&!p;d++)for(let w of o.get(`${m+b},${y+d}`)||[])if(!(Math.abs(f-w)<=i)&&Math.hypot(n[w].x-h.x,n[w].y-h.y)<=e){p=!0;break}p&&u++}return u/n.length}function It(r,t=[],e={}){let s={...ft,...e},n=[];for(let d of r){let w={x:d.x!==void 0?d.x:d[0],y:d.y!==void 0?d.y:d[1]},P=n[n.length-1];(!P||Math.hypot(w.x-P.x,w.y-P.y)>.75)&&n.push(w)}if(n.length<4)return{turns:0,cross:0,retrace:0,winding:0,cover:0,length:0,span:0};let a=0;for(let d=1;d<n.length;d++)a+=Math.hypot(n[d].x-n[d-1].x,n[d].y-n[d-1].y);let i=ct(n),l=Math.hypot(i.w,i.h),{ux:o,uy:u}=At(n),f=n.map(d=>d.x*o+d.y*u),h=n.map(d=>-d.x*u+d.y*o),m=ht(f,s.deadband),y=ht(h,s.deadband),p=0,b=[];for(let d of t)for(let w of d)b.push(w);if(b.length){let d=lt(ct(b)),w=lt(i),P=Math.max(0,Math.min(d.x1,w.x1)-Math.max(d.x0,w.x0)),k=Math.max(0,Math.min(d.y1,w.y1)-Math.max(d.y0,w.y0));p=P/Math.min(d.w,w.w)*(k/Math.min(d.h,w.h))}return{turns:m,cross:y,retrace:Lt(n,l),winding:l>0?a/l:0,cover:p,length:a,span:l}}function ut(r,t=[],e={}){let s={...ft,...e};if(!t||!t.length)return!1;let n=It(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 Rt=12,_=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function D({width:r=160,height:t=90,ink:e="#111827",onStrokeEnd:s,colorOf:n=null,idleOverwrite:a=0,scribbleClear:i=!1,scribble:l=null,onClear:o=null,staleAlpha:u=.3,onStale:f=null}){let h=document.createElement("canvas"),m=typeof devicePixelRatio<"u"&&devicePixelRatio||1;h.width=r*m,h.height=t*m,h.style.width=r+"px",h.style.height=t+"px",h.style.touchAction="none";let y=h.getContext("2d");y.scale(m,m);let p=[],b=[],d=null,w=!1,P=1,k=0,A=0,R=!1,E=null,C=!1;function Z(c,g){if(!(c.length<2)){y.strokeStyle=g||e,y.beginPath(),y.moveTo(c[0].x,c[0].y);for(let x=1;x<c.length;x++)y.lineTo(c[x].x,c[x].y);y.stroke()}}function dt(c,g){if(!(c.length<2||g>=c.length-1)){y.lineWidth=2.5,y.lineCap="round",y.lineJoin="round",y.globalAlpha=1,y.strokeStyle=e,y.beginPath(),y.moveTo(c[Math.max(0,g)].x,c[Math.max(0,g)].y);for(let x=Math.max(1,g+1);x<c.length;x++)y.lineTo(c[x].x,c[x].y);y.stroke()}}function v(){y.clearRect(0,0,r,t),y.lineWidth=2.5,y.lineCap="round",y.lineJoin="round",y.globalAlpha=R?u:1;for(let c of p)Z(c,n&&n(c));y.globalAlpha=1,Z(b,null)}function L(c){R!==c&&(R=c,v(),f&&f(c))}function U(){clearTimeout(A),A=0;let c=(Number(a)||0)*1e3;if(!c||!p.length){L(!1);return}let g=c-(_()-k);if(g<=0){L(!0);return}L(!1),A=setTimeout(()=>L(!0),g)}function tt(c){p.length&&(E=p,p=[],clearTimeout(A),A=0,L(!1),v(),o&&o(c))}function et(c,g){let x=p.filter(S=>!S.some(M=>Math.hypot(M.x-c,M.y-g)<=Rt));return x.length===p.length?!1:(p=x,v(),!0)}let T=null,q=c=>{let g=T||(T=h.getBoundingClientRect()),x=r/(h.clientWidth||r),S=t/(h.clientHeight||t);return{x:(c.clientX-g.left-h.clientLeft)*x,y:(c.clientY-g.top-h.clientTop)*S,p:c.pressure||.5}},j=!1,F=null,G=c=>c.preventDefault();h.addEventListener("touchstart",G,{passive:!1}),h.addEventListener("touchmove",G,{passive:!1}),h.addEventListener("contextmenu",G),h.style.userSelect=h.style.webkitUserSelect="none",h.style.webkitTouchCallout="none",h.addEventListener("pointerdown",c=>{if(c.button>0)return;if(d!==null){if(F==="pen"&&c.pointerType!=="pen"&&c.pointerId!==d)return;N({pointerId:d})}c.preventDefault(),d=c.pointerId,F=c.pointerType,T=h.getBoundingClientRect();try{h.setPointerCapture(c.pointerId)}catch{}let g=q(c);if(w){j=et(g.x,g.y);return}R&&p.length&&(tt("idle"),C=!0),b=[g],v()},{passive:!1}),h.addEventListener("pointermove",c=>{if(d!==c.pointerId)return;c.preventDefault();let g=c.getCoalescedEvents?c.getCoalescedEvents():null,x=g&&g.length?g:[c];if(w){for(let M of x){let st=q(M);et(st.x,st.y)&&(j=!0)}return}let S=b.length-1;for(let M of x)b.push(q(M));dt(b,S)},{passive:!1});let N=(c,g=!1)=>{if(d===c.pointerId){try{h.releasePointerCapture(c.pointerId)}catch{}if(d=null,F=null,T=null,w){j&&(k=_(),U(),s&&s(p)),j=!1;return}if(b.length>0){let x=b;if(x.length===1){if(g){b=[],v(),C&&(C=!1,s&&s(p));return}let M=x[0];x=[{x:M.x-1,y:M.y,p:M.p},{x:M.x+1,y:M.y,p:M.p}]}let S=p.length?p:C?E:null;if(i&&S&&S.length&&ut(x,S,l||{})){b=[],k=_(),C=!1,p.length?tt("scribble"):(v(),o&&o("scribble")),s&&s(p);return}x.id=P++,p=[...p,x],b=[],C=!1,k=_(),U(),s&&s(p)}v()}};return h.addEventListener("pointerup",c=>{c.pointerId===d&&c.preventDefault(),N(c)},{passive:!1}),h.addEventListener("pointercancel",c=>N(c,!0),{passive:!1}),h.addEventListener("lostpointercapture",c=>{(!h.hasPointerCapture||!h.hasPointerCapture(c.pointerId))&&N(c,!0)}),{el:h,getStrokes:()=>p,setInk(c){e=c,v()},setErasing(c){w=!!c,h.style.cursor=w?"cell":"crosshair"},isErasing:()=>w,repaint:v,isStale:()=>R,undoClear(){return!E||!E.length?!1:(p=p.length?[...E,...p]:E,E=null,k=_(),U(),v(),s&&s(p),!0)},configure(c={}){"idleOverwrite"in c&&(a=Number(c.idleOverwrite)||0),"scribbleClear"in c&&(i=!!c.scribbleClear),"scribble"in c&&(l=c.scribble),"staleAlpha"in c&&(u=Number(c.staleAlpha)),U()},clear(){p=[],b=[],d=null,F=null,T=null,clearTimeout(A),A=0,L(!1),C=!1,v(),s&&s(p)}}}function pt(r,t,{width:e=240,height:s=240,ink:n="#1e293b",idleOverwrite:a=2,scribbleClear:i=!0,scribble:l=null,staleAlpha:o,onStale:u,recognizeOptions:f}={}){if(!t||typeof t.recognize!="function")throw new TypeError("millirec: attachPad(el, recognizer) needs a recognizer with recognize(strokes)");let h=D({width:e,height:s,ink:n,idleOverwrite:a,scribbleClear:i,scribble:l,onStale:u,...o===void 0?{}:{staleAlpha:o},onClear:m=>r.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:m,undo:()=>h.undoClear()}})),onStrokeEnd:async m=>{if(!m.length){r.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let y=await(f?t.recognize(m,f):t.recognize(m));r.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:y,strokes:m}}))}});return r.appendChild(h.el),{clear:h.clear,undoClear:h.undoClear,isStale:h.isStale,configure:h.configure,setInk:h.setInk,repaint:h.repaint,getStrokes:h.getStrokes,canvas:h.el}}var H=class extends B{static createDrawCanvas(t){return D(t)}attach(t,e){return pt(t,this,e)}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharLite=H,window.MillirecChar||(window.MillirecChar=H));})();
Binary file
@@ -1,8 +1,8 @@
1
1
  {
2
- "generated": "2026-09-10T13:47:38.537Z",
2
+ "generated": "2026-11-21T20:48:03.820Z",
3
3
  "pps": 25,
4
4
  "folds": 3,
5
- "fixedKB": 54.2,
5
+ "fixedKB": 60.7,
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.47,
18
18
  "folds": 3,
19
19
  "trainingKB": 44.2,
20
20
  "trainingGz": 10.9,
21
- "bundleKB": 98.4,
22
- "zipKB": 37.1,
21
+ "bundleKB": 104.9,
22
+ "zipKB": 39.3,
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.5,
39
39
  "folds": 3,
40
40
  "trainingKB": 49.9,
41
41
  "trainingGz": 11.4,
42
- "bundleKB": 104.1,
43
- "zipKB": 37.6,
42
+ "bundleKB": 110.6,
43
+ "zipKB": 39.7,
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.21,
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": 77.8,
68
+ "zipKB": 32.6,
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.14,
87
83
  "folds": 3,
88
84
  "trainingKB": 9.4,
89
85
  "trainingGz": 1.7,
90
- "bundleKB": 63.6,
91
- "zipKB": 27.7,
86
+ "bundleKB": 70.1,
87
+ "zipKB": 29.8,
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.11,
113
109
  "folds": 3,
114
110
  "trainingKB": 120.2,
115
111
  "trainingGz": 27,
116
- "bundleKB": 174.4,
117
- "zipKB": 53.9,
112
+ "bundleKB": 180.9,
113
+ "zipKB": 56,
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
  }
@@ -0,0 +1,35 @@
1
+ import type { MillirecCharLite, Strokes, Stroke } from './char-lite/index.js'
2
+ import type { MillirecCharCnn } from './char-cnn/index.js'
3
+ import type { OptionName } from './char-cnn/core.js'
4
+
5
+ export { MillirecCharLite, SETS, loadSet, type SetName, type Training, type Sample, type Reading, type Point, type Stroke, type Strokes, type Only, type AttachOptions, type Pad, type ResultDetail, type ClearDetail } from './char-lite/index.js'
6
+ export { attachPad, type Recognizer } from './pad/index.js'
7
+
8
+ export declare const ALPHABETS: readonly ['digits', 'capitals', 'lowercase', 'all', 'punctuation']
9
+ export type Alphabet = (typeof ALPHABETS)[number]
10
+ export declare const PRIORITIES: readonly ['accurate', 'fast', 'small']
11
+ export type Priority = (typeof PRIORITIES)[number]
12
+
13
+ export interface RecognizerOptions {
14
+ /** What to read. Required unless `examples` are given. */
15
+ alphabet?: Alphabet
16
+ /** Among the CNN options: the most accurate (default), the fastest, or the smallest download. char-lite has one build. */
17
+ priority?: Priority
18
+ /** Your own symbols, a few drawings each: added to `alphabet`, or read alone without one. */
19
+ examples?: Record<string, Array<Strokes | Stroke>>
20
+ /** 'auto' (default): the CNN for digits, capitals, lowercase and all; char-lite for punctuation and whenever
21
+ * `examples` are given. */
22
+ engine?: 'auto' | 'cnn' | 'lite'
23
+ /** Where you serve the package's dist/ folder (it holds char-cnn/ and char-lite/). Default: beside this module.
24
+ * It decides what code is loaded: never fill it from a URL parameter or user input. */
25
+ assetBase?: string
26
+ /** char-lite matcher overrides. */
27
+ params?: Record<string, number>
28
+ }
29
+
30
+ export type Choice = { engine: 'char-cnn'; option: OptionName; teach: boolean } | { engine: 'char-lite'; set: Alphabet | null; examples: boolean }
31
+
32
+ /** What createRecognizer() would load, without loading it. */
33
+ export declare function chooseEngine(opts: RecognizerOptions | Alphabet): Choice
34
+ /** Load the recognizer for an alphabet (a string is the alphabet) or for your own examples. */
35
+ export declare function createRecognizer(opts: RecognizerOptions | Alphabet): Promise<MillirecCharCnn | MillirecCharLite>
package/dist/index.js ADDED
@@ -0,0 +1,88 @@
1
+ // millirec — the package's front door: say what you want to read and how you
2
+ // want it traded off, and createRecognizer() picks the engine and loads it.
3
+ //
4
+ // import { createRecognizer } from 'millirec'
5
+ // const rec = await createRecognizer('digits') // the CNN, option 'digits'
6
+ // const rec = await createRecognizer({ alphabet: 'lowercase', priority: 'small' })
7
+ // const rec = await createRecognizer({ examples: { star: [d1, d2, d3], heart: [...] } }) // your own symbols
8
+ // rec.attach(document.querySelector('#pad'))
9
+ //
10
+ // COPIED, NOT BUNDLED, to dist/index.js (build.mjs): its imports name the
11
+ // engine entries beside it in dist/, and each engine is imported only when it
12
+ // is the one picked, so a char-lite page never downloads the CNN runtime.
13
+ //
14
+ // The engines stay importable on their own (millirec/char-cnn, millirec/char-lite,
15
+ // their /core builds without the pad, millirec/pad); 0.1's
16
+ // `import { MillirecCharLite, loadSet } from 'millirec'` still works.
17
+ // 0.1 imported char-lite from 'millirec': kept. Without a bundler this re-export makes the browser fetch char-lite's
18
+ // module (8 KB gzipped) even when the CNN is picked; a bundler drops it when nothing uses it, and splits both engines
19
+ // out of createRecognizer(), which imports each lazily.
20
+ export { MillirecCharLite, loadSet, SETS } from './char-lite/index.js'
21
+ export { attachPad } from './pad/index.js'
22
+
23
+ /** What createRecognizer() can read without examples. */
24
+ export const ALPHABETS = ['digits', 'capitals', 'lowercase', 'all', 'punctuation']
25
+ /** How a CNN option is traded off: the most accurate, the fastest, or the smallest download. */
26
+ export const PRIORITIES = ['accurate', 'fast', 'small']
27
+ const ENGINES = ['auto', 'cnn', 'lite']
28
+ // the CNN option family per alphabet: capitals are the unprefixed 'accurate' / 'fast' / 'small'
29
+ const CNN_FAMILY = { capitals: '', digits: 'digits', lowercase: 'lowercase', all: 'all' }
30
+
31
+ const oneOf = (what, v, list) => { if (!list.includes(v)) throw new Error(`millirec: ${what} "${v}" is not one of ${list.join(', ')}`) }
32
+ const hasAny = (examples) => !!examples && typeof examples === 'object' && Object.keys(examples).length > 0
33
+
34
+ /**
35
+ * The engine and shipped asset createRecognizer() would load, without loading anything:
36
+ * { engine: 'char-cnn', option, teach } or { engine: 'char-lite', set, examples }.
37
+ *
38
+ * engine 'auto' (default): the CNN for digits, capitals, lowercase and all — trained on hundreds of
39
+ * writers, it reads strangers' handwriting; the point-cloud matcher (char-lite) for punctuation and
40
+ * whenever `examples` are given, since it can add any symbol to a set or read symbols alone.
41
+ */
42
+ export function chooseEngine(opts) {
43
+ if (typeof opts === 'string') opts = { alphabet: opts }
44
+ const { alphabet = null, priority = 'accurate', engine = 'auto', examples = null } = opts || {}
45
+ if (alphabet != null) oneOf('alphabet', alphabet, ALPHABETS)
46
+ oneOf('priority', priority, PRIORITIES)
47
+ oneOf('engine', engine, ENGINES)
48
+ const own = hasAny(examples)
49
+ if (alphabet == null && !own) throw new Error(`millirec: createRecognizer needs an alphabet (${ALPHABETS.join(', ')}) or examples of your own symbols`)
50
+ const pick = engine !== 'auto' ? engine : own || !(alphabet in CNN_FAMILY) ? 'lite' : 'cnn'
51
+ if (pick === 'cnn') {
52
+ if (alphabet != null && !(alphabet in CNN_FAMILY)) throw new Error(`millirec: there is no CNN for "${alphabet}" — use engine 'lite' (or 'auto')`)
53
+ if (alphabet != null && own) throw new Error("millirec: char-cnn cannot add symbols to a shipped alphabet (its teach() reads the taught symbols alone) — use engine 'lite', or leave out the alphabet")
54
+ const family = CNN_FAMILY[alphabet ?? 'capitals']
55
+ const option = family ? (priority === 'accurate' ? family : `${family}-${priority}`) : priority
56
+ return { engine: 'char-cnn', option, teach: own }
57
+ }
58
+ return { engine: 'char-lite', set: alphabet, examples: own }
59
+ }
60
+
61
+ /**
62
+ * Load a recognizer for `alphabet` (or for your `examples`), traded off by `priority`. A string is the alphabet:
63
+ * createRecognizer('digits'). Resolves to the engine's recognizer — MillirecCharCnn or MillirecCharLite — which
64
+ * both have recognize(strokes, { only }), attach(el), teach(examples), forget(), classes, engine and destroy().
65
+ *
66
+ * alphabet 'digits' | 'capitals' | 'lowercase' | 'all' | 'punctuation'
67
+ * priority 'accurate' (default) | 'fast' | 'small' — picks among the CNN options; char-lite has one build
68
+ * examples { name: [drawing, …] } — your own symbols: added to `alphabet`, or read alone without one
69
+ * engine 'auto' (default) | 'cnn' | 'lite' — see chooseEngine()
70
+ * assetBase where you serve the package's dist/ folder (it holds char-cnn/ and char-lite/); default: beside this module
71
+ * anything else goes to the engine's create() (params for char-lite, ...)
72
+ */
73
+ export async function createRecognizer(opts) {
74
+ if (typeof opts === 'string') opts = { alphabet: opts }
75
+ const { alphabet, priority, engine, examples, assetBase, ...rest } = opts || {}
76
+ const choice = chooseEngine({ alphabet, priority, engine, examples })
77
+ const under = (dir) => (assetBase ? { assetBase: String(assetBase).replace(/\/?$/, '/') + dir + '/' } : {})
78
+ if (choice.engine === 'char-cnn') {
79
+ const { MillirecCharCnn } = await import('./char-cnn/index.js')
80
+ return MillirecCharCnn.create({ ...rest, ...under('char-cnn'), option: choice.option, ...(choice.teach ? { examples } : {}) })
81
+ }
82
+ const { MillirecCharLite, loadSet } = await import('./char-lite/index.js')
83
+ const base = under('char-lite')
84
+ let training = choice.set ? await loadSet(choice.set, base) : { version: 2, mode: 'stroke', pointsPerShape: 25, classes: {} }
85
+ if (choice.examples) training = MillirecCharLite.withSamples(training, examples)
86
+ if (!Object.keys(training.classes).length) throw new Error('millirec: none of the examples held a usable drawing')
87
+ return MillirecCharLite.create({ ...rest, ...base, training })
88
+ }