millirec 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +229 -19
  3. package/dist/char-cnn/core.d.ts +18 -5
  4. package/dist/char-cnn/core.js +152 -25
  5. package/dist/char-cnn/index.d.ts +3 -2
  6. package/dist/char-cnn/index.js +152 -25
  7. package/dist/char-cnn/millirec-char-cnn-core.min.js +1 -1
  8. package/dist/char-cnn/millirec-char-cnn.min.js +1 -1
  9. package/dist/char-cnn/options/accurate.js +4 -4
  10. package/dist/char-cnn/options/accurate.json +4 -4
  11. package/dist/char-cnn/options/digits/digits-base.head.bin +0 -0
  12. package/dist/char-cnn/options/digits/digits-base.q4.bin +0 -0
  13. package/dist/char-cnn/options/digits/digits-tiny.bin +0 -0
  14. package/dist/char-cnn/options/digits/digits-tiny.head.bin +0 -0
  15. package/dist/char-cnn/options/digits.js +17 -0
  16. package/dist/char-cnn/options/digits.json +15 -0
  17. package/dist/char-cnn/options/fast/tiny.bin +0 -0
  18. package/dist/char-cnn/options/fast/tiny.head.bin +0 -0
  19. package/dist/char-cnn/options/fast.js +4 -4
  20. package/dist/char-cnn/options/fast.json +4 -4
  21. package/dist/char-cnn/options/lowercase/lowercase-base.head.bin +0 -0
  22. package/dist/char-cnn/options/lowercase/lowercase-base.q4.bin +0 -0
  23. package/dist/char-cnn/options/lowercase/lowercase-tiny.bin +0 -0
  24. package/dist/char-cnn/options/lowercase/lowercase-tiny.head.bin +0 -0
  25. package/dist/char-cnn/options/lowercase.js +17 -0
  26. package/dist/char-cnn/options/lowercase.json +15 -0
  27. package/dist/char-cnn/options/small/tiny.bin +0 -0
  28. package/dist/char-cnn/options/small/tiny.head.bin +0 -0
  29. package/dist/char-cnn/options/small.js +2 -2
  30. package/dist/char-cnn/options/small.json +2 -2
  31. package/dist/char-lite/index.d.ts +26 -4
  32. package/dist/char-lite/index.js +113 -11
  33. package/dist/char-lite/millirec-char-lite.min.js +1 -1
  34. package/dist/char-lite/millirec.wasm +0 -0
  35. package/dist/char-lite/sets.json +25 -29
  36. package/dist/overlap/index.d.ts +139 -0
  37. package/dist/overlap/millirec.wasm +0 -0
  38. package/package.json +45 -3
  39. /package/dist/char-cnn/{base.head.bin → options/accurate/base.head.bin} +0 -0
  40. /package/dist/char-cnn/{base.q4.bin → options/accurate/base.q4.bin} +0 -0
  41. /package/dist/char-cnn/{tiny.bin → options/accurate/tiny.bin} +0 -0
  42. /package/dist/char-cnn/{tiny.head.bin → options/accurate/tiny.head.bin} +0 -0
  43. /package/dist/char-cnn/{base-p25.bin → options/fast/base-p25.bin} +0 -0
  44. /package/dist/char-cnn/{base-p25.head.bin → options/fast/base-p25.head.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 lt(n,t,{margin:e,mag:o,bias:r}){return n<1e-9?.99:1/(1+Math.exp(-(e*Math.log(Math.max(t,1e-9)/n)-o*Math.log(n)-r)))}function z(n,t,e,o=1e3){let r=[];for(let p=0;p<3;p++)r.push(t[n[2*p]]);let i=ct[e];if(i){let p=[n[1],n[3],n[5]],c=p.map((f,m)=>{let x=1/0;for(let u=0;u<3;u++)u!==m&&(x=Math.min(x,p[u]));return lt(f,x,i)});return{chars:r,probs:c}}let s=Math.max(n[1],o/1e3),l=Math.exp(-1*o/s);for(let p=0;p<3;p++)l+=Math.exp(-1*n[2*p+1]/s);let a=[];for(let p=0;p<3;p++)a.push(Math.exp(-1*n[2*p+1]/s)/l);return{chars:r,probs:a}}function X(n){let t=[],e=0,o=0;for(let r=0;r<n.x.length;r++)e+=n.x[r],o+=n.y[r],t.push({x:e,y:o});return t}function tt(n){let t=[],e=[],o=[0,0];for(let r=0;r<n.length;r++){let i=Math.round(n[r].x),s=Math.round(n[r].y);t.push(r===0?i:i-o[0]),e.push(r===0?s:s-o[1]),o=[i,s]}return{x:t,y:e}}function Y(n){let t=n.length,e=[0,0],o=[0,0],r=[];for(let c=0;c<t;c++){let f=n[c];e[0]+=f.x,e[1]+=f.y;let m={x:f.x,y:f.y,a:1.570795};c>0&&f.x!==o[0]&&(m.a=Math.atan2(f.y-o[1],f.x-o[0])),m.s=Math.sin(m.a),m.c=Math.cos(m.a),c===1&&(r[0].s=m.s,r[0].c=m.c),o=[f.x,f.y],r.push(m)}e[0]/=t,e[1]/=t;let i=[0,0],s=[0,0],l=[0,0],a=[0,0];for(let c of r)c.x<e[0]?(l[0]+=c.x-e[0],l[1]++):(a[0]+=c.x-e[0],a[1]++),c.y<e[1]?(i[0]+=c.y-e[1],i[1]++):(s[0]+=c.y-e[1],s[1]++),c.x-=e[0],c.y-=e[1];i[1]>0&&(i[0]/=i[1]),s[1]>0&&(s[0]/=s[1]),l[1]>0&&(l[0]/=l[1]),a[1]>0&&(a[0]/=a[1]);let p=s[0]-i[0]<a[0]-l[0]?100/(a[0]-l[0]):i[0]<s[0]?100/(s[0]-i[0]):1;return{points:r,scale:p}}function N(n,t=50){let e=[],o=0;for(let s of n)for(let l=1;l<s.length;l++){let a=s[l].x-s[l-1].x,p=s[l].y-s[l-1].y,c=Math.sqrt(a*a+p*p);e.push({ax:s[l-1].x,ay:s[l-1].y,bx:s[l].x,by:s[l].y,cumStart:o,cumEnd:o+c}),o+=c}if(!o||!e.length)return null;let r=[],i=0;for(let s=0;s<t;s++){let l=s*o/(t-1);for(;i<e.length-1&&e[i].cumEnd<l;)i++;let a=e[i],p=a.cumEnd-a.cumStart,c=p?Math.min(1,Math.max(0,(l-a.cumStart)/p)):0;r.push({x:a.ax+(a.bx-a.ax)*c,y:a.ay+(a.by-a.ay)*c})}return r}function V(n){return tt(n)}var ft=n=>Array.isArray(n),ht=n=>ft(n)?n.every(t=>typeof t?.x=="number"&&typeof t?.y=="number"):Array.isArray(n?.x)&&Array.isArray(n?.y)&&n.x.length===n.y.length;function ut(n){return!!n&&typeof n=="object"&&!n.version&&!n.classes&&Object.values(n).every(Array.isArray)}function pt(n,{mode:t="both"}={}){let e={};for(let[o,r]of Object.entries(n))e[o]={samples:r,geometry:null};return{version:2,mode:t,pointsPerShape:50,classes:e,ext:{}}}function yt(n){let t=[];if(!n||typeof n!="object")return["not an object"];if((typeof n.version!="number"||n.version<2)&&t.push("bad version"),!n.classes||typeof n.classes!="object"||!Object.keys(n.classes).length)return t.push("no classes"),t;for(let[e,o]of Object.entries(n.classes)){if(!Array.isArray(o?.samples)||!o.samples.length){t.push(`class ${e}: no samples`);continue}o.samples.forEach((i,s)=>{ht(i)||t.push(`class ${e} sample ${s}: bad shape`)});let r=o.geometry;r!=null&&typeof r!="object"&&t.push(`class ${e}: bad geometry`)}return n.wordList!=null&&!Array.isArray(n.wordList)&&t.push("bad wordList"),n.params!=null&&typeof n.params!="object"&&t.push("bad params"),t}function W(n){let t=ut(n)?pt(n):n,e=yt(t);if(e.length)throw new Error("invalid training data: "+e.join("; "));return t.mode||(t.mode="both"),t.pointsPerShape||(t.pointsPerShape=50),t.ext||(t.ext={}),t}function et(n){let t={};for(let[e,o]of Object.entries(n.classes))t[e]=o.samples;return t}var st={turns:5,retrace:.5,winding:3.5,cover:.6,minLength:40,minSpan:12,deadband:.22},C=2;function nt(n){return{x0:n.x0-C,y0:n.y0-C,x1:n.x1+C,y1:n.y1+C,w:n.w+2*C,h:n.h+2*C}}function rt(n){let t=1/0,e=1/0,o=-1/0,r=-1/0;for(let i of n){let s=i.x!==void 0?i.x:i[0],l=i.y!==void 0?i.y:i[1];s<t&&(t=s),s>o&&(o=s),l<e&&(e=l),l>r&&(r=l)}return{x0:t,y0:e,x1:o,y1:r,w:o-t,h:r-e}}function ot(n,t){let e=1/0,o=-1/0;for(let a of n)a<e&&(e=a),a>o&&(o=a);let r=(o-e)*t;if(!(r>0))return 0;let i=0,s=n[0],l=0;for(let a of n)i>0?a>s?s=a:a<s-r&&(l++,i=-1,s=a):i<0?a<s?s=a:a>s+r&&(l++,i=1,s=a):a>s+r?(i=1,s=a):a<s-r&&(i=-1,s=a);return l}function mt(n){let t=0,e=0;for(let m of n)t+=m.x,e+=m.y;t/=n.length,e/=n.length;let o=0,r=0,i=0;for(let m of n){let x=m.x-t,u=m.y-e;o+=x*x,r+=x*u,i+=u*u}let s=o+i,l=o*i-r*r,a=s/2+Math.sqrt(Math.max(0,s*s/4-l)),p=r,c=a-o;Math.hypot(p,c)<1e-9&&(p=1,c=0);let f=Math.hypot(p,c);return{ux:p/f,uy:c/f}}var xt=.09,dt=4;function gt(n,t){let e=Math.max(2,t*xt),o=e/2,r=[n[0]],i=0;for(let c=1;c<n.length;c++){let f=n[c].x-n[c-1].x,m=n[c].y-n[c-1].y,x=Math.hypot(f,m);if(!(x>0))continue;let u=(o-i)/x;for(;u<=1;)r.push({x:n[c-1].x+f*u,y:n[c-1].y+m*u}),u+=o/x;i=(i+x)%o}if(r.length<8)return 0;let s=Math.round(dt*e/o),l=c=>`${Math.floor(c.x/e)},${Math.floor(c.y/e)}`,a=new Map;r.forEach((c,f)=>{let m=l(c);a.has(m)||a.set(m,[]),a.get(m).push(f)});let p=0;for(let c=0;c<r.length;c++){let f=r[c],m=Math.floor(f.x/e),x=Math.floor(f.y/e),u=!1;for(let w=-1;w<=1&&!u;w++)for(let y=-1;y<=1&&!u;y++)for(let d of a.get(`${m+w},${x+y}`)||[])if(!(Math.abs(c-d)<=s)&&Math.hypot(r[d].x-f.x,r[d].y-f.y)<=e){u=!0;break}u&&p++}return p/r.length}function Mt(n,t=[],e={}){let o={...st,...e},r=[];for(let y of n){let d={x:y.x!==void 0?y.x:y[0],y:y.y!==void 0?y.y:y[1]},E=r[r.length-1];(!E||Math.hypot(d.x-E.x,d.y-E.y)>.75)&&r.push(d)}if(r.length<4)return{turns:0,cross:0,retrace:0,winding:0,cover:0,length:0,span:0};let i=0;for(let y=1;y<r.length;y++)i+=Math.hypot(r[y].x-r[y-1].x,r[y].y-r[y-1].y);let s=rt(r),l=Math.hypot(s.w,s.h),{ux:a,uy:p}=mt(r),c=r.map(y=>y.x*a+y.y*p),f=r.map(y=>-y.x*p+y.y*a),m=ot(c,o.deadband),x=ot(f,o.deadband),u=0,w=[];for(let y of t)for(let d of y)w.push(d);if(w.length){let y=nt(rt(w)),d=nt(s),E=Math.max(0,Math.min(y.x1,d.x1)-Math.max(y.x0,d.x0)),v=Math.max(0,Math.min(y.y1,d.y1)-Math.max(y.y0,d.y0));u=E/Math.min(y.w,d.w)*(v/Math.min(y.h,d.h))}return{turns:m,cross:x,retrace:gt(r,l),winding:l>0?i/l:0,cover:u,length:i,span:l}}function it(n,t=[],e={}){let o={...st,...e};if(!t||!t.length)return!1;let r=Mt(n,t,o);return r.length>=o.minLength&&r.span>=o.minSpan&&r.turns>=o.turns&&r.retrace>=o.retrace&&r.winding>=o.winding&&r.cover>=o.cover}var wt=12,T=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function $({width:n=160,height:t=90,ink:e="#111827",onStrokeEnd:o,colorOf:r=null,idleOverwrite:i=0,scribbleClear:s=!1,scribble:l=null,onClear:a=null,staleAlpha:p=.3,onStale:c=null}){let f=document.createElement("canvas"),m=typeof devicePixelRatio<"u"&&devicePixelRatio||1;f.width=n*m,f.height=t*m,f.style.width=n+"px",f.style.height=t+"px",f.style.touchAction="none";let x=f.getContext("2d");x.scale(m,m);let u=[],w=[],y=null,d=!1,E=1,v=0,A=0,L=!1,P=null,k=!1;function K(h,g){if(!(h.length<2)){x.strokeStyle=g||e,x.beginPath(),x.moveTo(h[0].x,h[0].y);for(let M=1;M<h.length;M++)x.lineTo(h[M].x,h[M].y);x.stroke()}}function I(){x.clearRect(0,0,n,t),x.lineWidth=2.5,x.lineCap="round",x.lineJoin="round",x.globalAlpha=L?p:1;for(let h of u)K(h,r&&r(h));x.globalAlpha=1,K(w,null)}function R(h){L!==h&&(L=h,I(),c&&c(h))}function O(){clearTimeout(A),A=0;let h=(Number(i)||0)*1e3;if(!h||!u.length){R(!1);return}let g=h-(T()-v);if(g<=0){R(!0);return}R(!1),A=setTimeout(()=>R(!0),g)}function J(h){u.length&&(P=u,u=[],clearTimeout(A),A=0,R(!1),I(),a&&a(h))}function Q(h,g){let M=u.filter(S=>!S.some(b=>Math.hypot(b.x-h,b.y-g)<=wt));return M.length===u.length?!1:(u=M,I(),!0)}let _=null,D=h=>{let g=_||(_=f.getBoundingClientRect()),M=n/(f.clientWidth||n),S=t/(f.clientHeight||t);return{x:(h.clientX-g.left-f.clientLeft)*M,y:(h.clientY-g.top-f.clientTop)*S,p:h.pressure||.5}},G=!1,U=null,F=h=>h.preventDefault();f.addEventListener("touchstart",F,{passive:!1}),f.addEventListener("touchmove",F,{passive:!1}),f.addEventListener("contextmenu",F),f.style.userSelect=f.style.webkitUserSelect="none",f.style.webkitTouchCallout="none",f.addEventListener("pointerdown",h=>{if(h.button>0)return;if(y!==null&&y!==h.pointerId){if(U==="pen"&&h.pointerType!=="pen")return;q({pointerId:y})}h.preventDefault(),y=h.pointerId,U=h.pointerType,_=f.getBoundingClientRect();try{f.setPointerCapture(h.pointerId)}catch{}let g=D(h);if(d){G=Q(g.x,g.y);return}L&&u.length&&(J("idle"),k=!0),w=[g],I()},{passive:!1}),f.addEventListener("pointermove",h=>{if(y!==h.pointerId)return;h.preventDefault();let g=h.getCoalescedEvents?h.getCoalescedEvents():null,M=g&&g.length?g:[h];if(d){for(let S of M){let b=D(S);Q(b.x,b.y)&&(G=!0)}return}for(let S of M)w.push(D(S));I()},{passive:!1});let q=(h,g=!1)=>{if(y===h.pointerId){try{f.releasePointerCapture(h.pointerId)}catch{}if(y=null,U=null,_=null,d){G&&(v=T(),O(),o&&o(u)),G=!1;return}if(w.length>0){let M=w;if(M.length===1){if(g){w=[],I(),k&&(k=!1,o&&o(u));return}let b=M[0];M=[{x:b.x-1,y:b.y,p:b.p},{x:b.x+1,y:b.y,p:b.p}]}let S=u.length?u:k?P:null;if(s&&S&&S.length&&it(M,S,l||{})){w=[],v=T(),k=!1,u.length?J("scribble"):(I(),a&&a("scribble")),o&&o(u);return}M.id=E++,u=[...u,M],w=[],k=!1,v=T(),O(),o&&o(u)}I()}};return f.addEventListener("pointerup",h=>q(h)),f.addEventListener("pointercancel",h=>q(h,!0)),{el:f,getStrokes:()=>u,setInk(h){e=h,I()},setErasing(h){d=!!h,f.style.cursor=d?"cell":"crosshair"},isErasing:()=>d,repaint:I,isStale:()=>L,undoClear(){return!P||!P.length?!1:(u=u.length?[...P,...u]:P,P=null,v=T(),O(),I(),o&&o(u),!0)},configure(h={}){"idleOverwrite"in h&&(i=Number(h.idleOverwrite)||0),"scribbleClear"in h&&(s=!!h.scribbleClear),"scribble"in h&&(l=h.scribble),"staleAlpha"in h&&(p=Number(h.staleAlpha)),O()},clear(){u=[],w=[],y=null,U=null,_=null,clearTimeout(A),A=0,R(!1),k=!1,I(),o&&o(u)}}}function at(n){let t=n?String(n):"";return t?(t.endsWith("/")||(t+="/"),typeof location<"u"?new URL(t,location.href).href:t):typeof location<"u"?new URL("./",location.href).href:""}function It(){let n=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return n?n.slice(0,n.lastIndexOf("/")+1):""}var bt=It(),H=class{constructor({assetBase:t,workerName:e,training:o,params:r}){t=at(t);let i=W(o);this.trainPaths=et(i),this.charList=Object.keys(this.trainPaths),this.samplesPerChar=Math.max(1,...this.charList.map(l=>this.trainPaths[l].length)),this.pointsPerShape=i.pointsPerShape||50,this.params=r||i.params||null,this.plugins=[],this.cache=new Map,this.inFlight=new Map,this.allWaiters=new Map,this.reqCounter=0;let s=`self.__MILLIREC_ASSET_BASE=${JSON.stringify(t)};importScripts(${JSON.stringify(t+e)});`;this.bootUrl=URL.createObjectURL(new Blob([s],{type:"text/javascript"})),this.worker=new Worker(this.bootUrl),this.readyPromise=new Promise((l,a)=>{this.readyResolve=l,this.readyReject=a}),this.worker.onmessage=l=>this.onMessage(l),this.worker.onerror=l=>this.readyReject(new Error("millirec worker error: "+(l.message||"script failed to load")))}onMessage(t){let e=t.data;if(this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null),e.type==="getCharList")this.params&&this.worker.postMessage({type:"setParams",params:this.params}),this.worker.postMessage({type:"charList",charList:this.charList,pointsPerShape:this.pointsPerShape,samplesPerChar:this.samplesPerChar});else if(e.type==="prepAll")this.charList.forEach((o,r)=>{this.trainPaths[o].forEach((i,s)=>{let{points:l,scale:a}=Y(X(i));this.worker.postMessage({type:"addPoints",points:l,m:r*this.samplesPerChar+s,scale:a})})}),this.readyResolve();else if(e.type==="addResult"&&e.result){this.cache.set(e.path,e.result);let o=this.inFlight.get(e.path)||[];this.inFlight.delete(e.path);for(let r of o)r(this.applyPlugins(e.result,e.path))}else if(e.type==="allResult"){let o=this.allWaiters.get(e.path)||[];this.allWaiters.delete(e.path);for(let r of o)r(e.costs)}else e.type==="bootError"&&this.readyReject(new Error("millirec worker boot failed: "+e.message))}applyPlugins(t,e){let o=z(t,this.charList,"stroke",1e3);for(let r of this.plugins)r.rerank&&(o=r.rerank(o,{raw:t,path:e,charList:this.charList,mode:"stroke",recognizer:this})||o);return o}uploadTest(t){let e=Array.isArray(t[0])?t:[t],o=N(e,this.pointsPerShape);if(!o)return!1;let{points:r,scale:i}=Y(o);return this.worker.postMessage({type:"addPoints",points:r,m:-1,scale:i}),!0}keyFor(t){let e=Array.isArray(t[0])?t.flat():t,o=5381;for(let r of e)o=(o*33^(r.x*7919+r.y|0))>>>0;return"strokes:"+e.length+":"+o.toString(36)}async recognize(t){if(!t||!t.length)return null;await this.readyPromise;let e=this.keyFor(t);return this.cache.has(e)?this.applyPlugins(this.cache.get(e),e):this.uploadTest(t)?new Promise(o=>{let r,i=s=>{clearTimeout(r),o(s)};this.inFlight.has(e)?this.inFlight.get(e).push(i):(this.inFlight.set(e,[i]),this.worker.postMessage({type:"compare",path:e,elementID:"req"+ ++this.reqCounter})),r=setTimeout(()=>i(null),4e3)}):null}async rawScores(t){if(await this.readyPromise,!this.uploadTest(t))return null;let e="all:"+ ++this.reqCounter,o=await new Promise(r=>{let i,s=l=>{clearTimeout(i),r(l)};this.allWaiters.set(e,[s]),this.worker.postMessage({type:"compareAll",path:e,counts:this.charList.map(l=>this.trainPaths[l].length)}),i=setTimeout(()=>s(null),8e3)});return o?{classes:this.charList,costs:o}:null}destroy(){this.worker.terminate(),this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null)}},St=n=>n?n.chars.map((t,e)=>({char:t,prob:n.probs[e]})):null,Z=class{static strokesToSample(t,e=50){let o=N(Array.isArray(t[0])?t:[t],e);return o?V(o):null}static withSamples(t,e,{replace:o=!1}={}){let r=W({...t}),i=r.pointsPerShape,s=a=>{let p=Array.isArray(a)?Array.isArray(a[0])?a:[a]:[X(a)],c=N(p,i);return c?V(c):null},l={...r.classes};for(let[a,p]of Object.entries(e||{})){let c=(p||[]).map(s).filter(Boolean);if(!c.length)continue;let f=l[a]?.samples||[];l[a]={...l[a]||{},samples:o?c:f.concat(c)}}return{...r,classes:l}}static createDrawCanvas(t){return $(t)}static async create(t={}){let e=typeof window<"u"?window:globalThis,o={...e.MILLIREC_CONFIG||{},...t},r=t.training||e.MILLIREC_TRAINING;if(!r)throw new Error("MillirecCharLite: no training data (training.js missing?)");let i=new this(o,r);return await i.ready,i}constructor(t,e){this.config=t,this.stroke=new H({assetBase:t.assetBase||bt,workerName:t.workerStroke||"worker-stroke.js",training:e,params:t.params?.stroke||t.params||null}),this.charList=this.stroke.charList,this.ready=this.stroke.readyPromise}use(t){return this.stroke.plugins.push(t),this}async recognize(t){return St(await this.stroke.recognize(t))}rawScores(t){return this.stroke.rawScores(t)}attach(t,{width:e=240,height:o=240,ink:r="#1e293b",idleOverwrite:i=2,scribbleClear:s=!0,scribble:l=null,staleAlpha:a,onStale:p}={}){let c=$({width:e,height:o,ink:r,idleOverwrite:i,scribbleClear:s,scribble:l,onStale:p,...a===void 0?{}:{staleAlpha:a},onClear:f=>t.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:f,undo:()=>c.undoClear()}})),onStrokeEnd:async f=>{if(!f.length){t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let m=await this.recognize(f);t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:m,strokes:f}}))}});return t.appendChild(c.el),{clear:c.clear,undoClear:c.undoClear,isStale:c.isStale,configure:c.configure,setInk:c.setInk,repaint:c.repaint,getStrokes:c.getStrokes,canvas:c.el}}destroy(){this.stroke.destroy()}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharLite=Z,window.MillirecChar||(window.MillirecChar=Z));})();
1
+ "use strict";(()=>{var ct={image:{margin:.6884,mag:.6846,bias:-1.0768},imageGeom:{margin:.6925,mag:1.0731,bias:-2.4927}};function ht(r,t,{margin:e,mag:s,bias:n}){return r<1e-9?.99:1/(1+Math.exp(-(e*Math.log(Math.max(t,1e-9)/r)-s*Math.log(r)-n)))}function tt(r,t,e,s=1e3){let n=[];for(let u=0;u<3;u++)n.push(t[r[2*u]]);let a=ct[e];if(a){let u=[r[1],r[3],r[5]],l=u.map((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
  }
@@ -0,0 +1,139 @@
1
+ // The overlap widget is a script-tag build (dist/overlap/millirec-overlap.min.js) that sets
2
+ // window.MillirecOverlap. These declarations type that global:
3
+ //
4
+ // import type {} from 'millirec/overlap' // or: /// <reference types="millirec/overlap" />
5
+ // const w = await MillirecOverlap.create('#box', { set: 'capitals', words: ['HELLO'] })
6
+ //
7
+ // Source: library/src/overlap.js (the full option list is in OverlapWidget's constructor comment).
8
+
9
+ export type OverlapSet = 'capitals' | 'lowercase' | 'digits' | 'punctuation' | 'all'
10
+ export type OverlapEvent = 'ready' | 'stroke' | 'change' | 'word' | 'select' | 'error'
11
+ export interface OverlapPoint { x: number; y: number }
12
+
13
+ export interface OverlapCandidate { word: string; score: number; complete: boolean; inList: boolean }
14
+ export interface OverlapWord {
15
+ word: string
16
+ letters: Array<{ ch: string; strokes: OverlapPoint[][] }>
17
+ inList: boolean
18
+ selected: boolean
19
+ alternatives: Array<{ word: string; score: number; inList: boolean }>
20
+ }
21
+
22
+ export interface OverlapOptions {
23
+ /** Which characters the box reads (default 'capitals'). */
24
+ set?: OverlapSet
25
+ /** An explicit alphabet ('ABC…' or 'capitals,digits'); loads the superset and uses these. */
26
+ alphabet?: string
27
+ /** The word list: an array, or a whitespace/comma-separated string. */
28
+ words?: string[] | string
29
+ /** A list hosted on a millirec server (needs apiBase). */
30
+ list?: string
31
+ /** URL of a text/JSON file of words. */
32
+ wordsSrc?: string
33
+ /** Receives the text (an input/textarea's value, else textContent). */
34
+ target?: string | HTMLElement
35
+ /** 'live' (default) includes the word being written. */
36
+ targetMode?: 'live' | 'words'
37
+ /** The box, in CSS px (default 240). */
38
+ size?: number
39
+ layout?: 'column' | 'row'
40
+ /** Candidate words shown (default 6). */
41
+ chips?: number
42
+ /** Previous words' handwriting kept beside the current one (default 1). */
43
+ history?: number
44
+ /** Seconds of pen-up after which the word finishes itself (0 = never, the default). */
45
+ idleFinish?: number
46
+ theme?: 'auto' | 'light' | 'dark'
47
+ /** Any of 'text,handwriting,words,buttons'. */
48
+ hide?: string
49
+ placeholder?: string
50
+ /** Recognizer knobs (commitMargin, lmW, …). */
51
+ engine?: Record<string, number>
52
+ /** Where millirec.wasm, training.<set>.json and words.json are. Default: beside the script.
53
+ * A code-loading option: never fill it from user input. */
54
+ assetBase?: string
55
+ /** The millirec server, for `list`. */
56
+ apiBase?: string
57
+ onReady?: (detail: OverlapDetail) => void
58
+ onStroke?: (detail: OverlapDetail) => void
59
+ onChange?: (detail: OverlapDetail) => void
60
+ onWord?: (detail: OverlapDetail & OverlapWord & { canvas: HTMLCanvasElement }) => void
61
+ onSelect?: (detail: OverlapDetail) => void
62
+ onError?: (detail: OverlapDetail & { error: Error }) => void
63
+ }
64
+
65
+ /** An event's detail. 'stroke'/'change'/'word' carry the text fields; 'word' adds the finished word. */
66
+ export interface OverlapDetail {
67
+ widget: OverlapWidget
68
+ text?: string
69
+ live?: string
70
+ current?: string
71
+ committed?: string
72
+ pending?: string
73
+ candidates?: OverlapCandidate[]
74
+ strokes?: number
75
+ erased?: number
76
+ canvas?: HTMLCanvasElement | null
77
+ [key: string]: unknown
78
+ }
79
+
80
+ export interface OverlapWidget {
81
+ readonly el: HTMLElement
82
+ readonly ready: Promise<void>
83
+ /** Subscribe; returns the unsubscribe function. DOM events 'millirec-overlap:<event>' bubble from the host too. */
84
+ on(event: OverlapEvent, fn: (detail: OverlapDetail) => void): () => boolean
85
+ /** The finished words, joined by spaces. */
86
+ getText(): string
87
+ /** The finished words plus the word being written. */
88
+ getLiveText(): string
89
+ getWords(): OverlapWord[]
90
+ getCandidates(): OverlapCandidate[]
91
+ getWordList(): string[]
92
+ getHandwriting(opts?: { scope?: 'word' | 'all'; index?: number; capHeight?: number }): HTMLCanvasElement | null
93
+ /** Replace the word list; returns the usable words (0 = free mode). */
94
+ setWords(words: string[] | string): number
95
+ /** Load a list hosted on the millirec server by id. */
96
+ loadList(id: string): Promise<number>
97
+ getLexiconSize(): number
98
+ /** Switch the character set or an explicit alphabet; resolves with the alphabet when ready. */
99
+ setAlphabet(spec: OverlapSet | string): Promise<string | undefined>
100
+ /** Finish the word being written (best reading), or force it to `word`. */
101
+ finishWord(word?: string | null): void
102
+ /** Accept a candidate; `finish: false` adopts it as a prefix and keeps writing. */
103
+ selectWord(word: string, opts?: { finish?: boolean }): void
104
+ undo(): void
105
+ /** Drop the current word's ink; finished words stay. */
106
+ clearWord(): void
107
+ /** Forget everything, finished words included. */
108
+ clear(): void
109
+ setOptions(engineOpts: Record<string, number>): void
110
+ destroy(): void
111
+ }
112
+
113
+ export interface MillirecOverlapApi {
114
+ readonly version: string
115
+ create(host: string | HTMLElement, opts?: OverlapOptions): Promise<OverlapWidget>
116
+ /** Mount a widget on every [data-millirec-overlap] element not yet mounted (done once on load). */
117
+ scan(root?: ParentNode): OverlapWidget[]
118
+ Widget: new (host: string | HTMLElement, opts?: OverlapOptions) => OverlapWidget
119
+ /** Prewarm the matcher and templates for a set (optional; create() does it on demand). */
120
+ preload(set?: OverlapSet | string, assetBase?: string): Promise<unknown>
121
+ splitWords(s: string): string[]
122
+ wordStrip(groups: unknown[], capHeight?: number, colors?: Record<string, string>): HTMLCanvasElement
123
+ sentenceStrip(wordsGroups: unknown[][], capHeight?: number, colors?: Record<string, string>): HTMLCanvasElement
124
+ SET_NAMES: readonly string[]
125
+ [key: string]: unknown
126
+ }
127
+
128
+ declare global {
129
+ interface Window { MillirecOverlap: MillirecOverlapApi }
130
+ var MillirecOverlap: MillirecOverlapApi
131
+ interface HTMLElementEventMap {
132
+ 'millirec-overlap:ready': CustomEvent<OverlapDetail>
133
+ 'millirec-overlap:stroke': CustomEvent<OverlapDetail>
134
+ 'millirec-overlap:change': CustomEvent<OverlapDetail>
135
+ 'millirec-overlap:word': CustomEvent<OverlapDetail & OverlapWord & { canvas: HTMLCanvasElement }>
136
+ 'millirec-overlap:select': CustomEvent<OverlapDetail & { word: string; finish: boolean }>
137
+ 'millirec-overlap:error': CustomEvent<OverlapDetail & { error: Error }>
138
+ }
139
+ }
Binary file
package/package.json CHANGED
@@ -1,13 +1,40 @@
1
1
  {
2
2
  "name": "millirec",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Small, fast handwriting recognition in the browser: drawn characters, digits and symbols, trainable on your own strokes.",
5
5
  "license": "MIT",
6
6
  "author": "Robert Wilcox",
7
7
  "homepage": "https://millirec.com",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/triplelog/millirec.git"
11
+ },
12
+ "bugs": "https://millirec.com/help.html",
8
13
  "type": "module",
9
14
  "main": "./dist/char-lite/index.js",
10
15
  "types": "./dist/char-lite/index.d.ts",
16
+ "typesVersions": {
17
+ "*": {
18
+ "char-lite": [
19
+ "dist/char-lite/index.d.ts"
20
+ ],
21
+ "char-cnn": [
22
+ "dist/char-cnn/index.d.ts"
23
+ ],
24
+ "char-cnn/core": [
25
+ "dist/char-cnn/core.d.ts"
26
+ ],
27
+ "overlap": [
28
+ "dist/overlap/index.d.ts"
29
+ ],
30
+ "char-lite/sets/*": [
31
+ "dist/char-lite/sets/*"
32
+ ],
33
+ "char-cnn/options/*": [
34
+ "dist/char-cnn/options/*"
35
+ ]
36
+ }
37
+ },
11
38
  "keywords": [
12
39
  "handwriting",
13
40
  "recognition",
@@ -16,7 +43,11 @@
16
43
  "pen",
17
44
  "drawing",
18
45
  "wasm",
19
- "character-recognition"
46
+ "character-recognition",
47
+ "handwriting-recognition",
48
+ "browser",
49
+ "webassembly",
50
+ "digit-recognition"
20
51
  ],
21
52
  "exports": {
22
53
  ".": {
@@ -37,6 +68,9 @@
37
68
  },
38
69
  "./char-lite/sets/*.json": "./dist/char-lite/sets/*.json",
39
70
  "./char-cnn/options/*.json": "./dist/char-cnn/options/*.json",
71
+ "./overlap": {
72
+ "types": "./dist/overlap/index.d.ts"
73
+ },
40
74
  "./overlap/*": "./dist/overlap/*",
41
75
  "./dist/*": "./dist/*",
42
76
  "./package.json": "./package.json"
@@ -44,12 +78,20 @@
44
78
  "files": [
45
79
  "dist",
46
80
  "README.md",
81
+ "CHANGELOG.md",
47
82
  "LICENSE"
48
83
  ],
49
- "sideEffects": false,
84
+ "sideEffects": [
85
+ "./dist/**/*.min.js",
86
+ "./dist/char-lite/sets/*.js",
87
+ "./dist/char-cnn/options/*.js"
88
+ ],
50
89
  "scripts": {
51
90
  "build": "node build.mjs",
52
91
  "test": "node build.mjs && node test/verify.mjs",
53
92
  "prepack": "node build.mjs"
93
+ },
94
+ "engines": {
95
+ "node": ">=18"
54
96
  }
55
97
  }