alkove 0.3.2 → 0.3.3

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.
Binary file
@@ -0,0 +1 @@
1
+ import{d as a,e as b,f as c,g as d,h as e}from"./chunk-DI5ZLGIU.js";import"./chunk-CMAGZACJ.js";export{a as Alkove,c as Lex,d as Spot,b as Timbre,e as VoiceprintLearner};
@@ -1 +1 @@
1
- var ae={name:"alkove-engine",file:"alkove-engine.wasm",bytes:484109,sha256:"c22e900af5f401b29689b3b882f7245feefe4dea617ffdb3046a1d4f5771e543"};var L="alkove-ai",z={focus:{name:"alkove-focus-1-preview",file:"alkove-focus-1-preview.alk",bytes:1111696,sha256:"a63cda32e023b8d76089f4c3df0cc2c69ba36017b8f6cdea1da1094ef8022b6a",revision:"8e91ef608366cf503fbd8aaa44bc2000dce899ed"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1066516,sha256:"977cd614996498f468536effbc2fb05138331751ca21572cf07b24184b4e7911",revision:"49e90fcff90dc6e6c47fa6e990e810bd628af4b3"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1-preview",file:"alkove-timbre-1-preview.alk",bytes:739632,sha256:"d498a7dd8b20528d783052b1e1d49e54ab7ee4e47aa12712d04f3d43edc68bd8",revision:"013f7c621e8687e992508b5fb01607eb17143550"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var A=16e3,x=z,Me={chunk:256,print:192,lag:256};var U=e=>`${x[e].name}@${x[e].sha256.slice(0,12)}`,y={model:U("timbre"),window:24e3,min:280,dim:192},Le={langs:["fr","en","es","pt","it","ca","ro"],beams:3,bos:59,eos:60,vocab:61,word:33,steps:39};var g=class extends Error{constructor(r,n,o){super(n);this.code=r;this.cause=o}name="AlkoveError"};var H=["i","y","\u0268","u","e","\xF8","\u0259","o","\u025B","\u0153","\u0254","a","\u0251","\xE6","\u028C","\u026A","\u028A","\u0250","\u025C","\u025B\u0303","\u0251\u0303","\u0254\u0303","\u0250\u0303","\u1EBD","\u0129","\xF5","\u0169","j","w","\u0265","p","b","t","d","k","\u0261","f","v","s","z","\u0283","\u0292","m","n","\u0272","\u014B","l","\u028E","\u0281","\u027E","r","\u0279","x","\u03B8","\xF0","\u03B2","\u0263","h"].map(e=>e.normalize("NFD"));var R=new Map(H.map((e,t)=>[e,t+1])),De=R.get("\u0259"),ie={"\u1D7B":"\u026A",\u025A:"\u0259\u0279",\u025D:"\u025C\u0279",\u029D:"j",\u025F:"\u0261",c:"k",\u026B:"l",\u026C:"l",\u03C7:"x",\u0266:"h",\u028B:"v",\u0271:"m",\u027B:"\u0279",\u0280:"\u0281",g:"\u0261",\u0258:"\u0259",\u0275:"\xF8",\u028F:"y",\u026F:"u",\u0264:"o",q:"k",\u0255:"\u0283",\u0291:"\u0292",\u00E7:"\u0283",\u0294:"",\u0252:"\u0254",\u0153\u0303:"\u025B\u0303",\u0278:"f",\u0299:"b"},ce={fr:{\u0251:"a",\u00E3:"\u0251\u0303",\u00F5:"\u0254\u0303",\u1EBD:"\u025B\u0303",\u0129:"\u025B\u0303",\u0169:"\u0254\u0303",\u0250\u0303:"\u0251\u0303",\u0250:"a",\u00E6:"a",\u028C:"\u0153",\u025C:"\u0153",\u026A:"i",\u028A:"u",\u0279:"\u0281",r:"\u0281",\u027E:"\u0281",x:"\u0281",\u03B8:"s",\u00F0:"z",h:"",\u03B2:"b",\u0263:"\u0261",\u028E:"lj",\u0268:"i"},es:{\u026A:"i",\u028A:"u",\u025B:"e",\u0254:"o",\u0251:"a",\u00E6:"a",\u028C:"a",\u0259:"e",\u0250:"a",\u0279:"\u027E"},it:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"a",\u0250:"a",\u0279:"r",x:"k",\u03B8:"t",h:""},pt:{\u026A:"i",\u028A:"u",\u028A\u0303:"\u0169",y:"j",\u00E3:"\u0250\u0303",\u0251:"a",\u00E6:"a",\u028C:"a",\u0279:"\u027E"},ca:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"\u027E",\u0250:"\u0259"},ro:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"r",\u027E:"r"},en:{\u0250:"\u0259",r:"\u0279",x:"k",\u025B\u0303:"\u0251\u0303"}},ue=new Set("\u02C8\u02CC\u02D0\u02D1\u203F-.|\u02B2\u02B0\u02B7' "),de=[["e","\u025B"],["o","\u0254"],["\xF8","\u0153","\u0259"],["i","j"],["u","w"],["y","\u0265"],["\u027E","r"]],B=H.map((e,t)=>[t+1]);for(let e of de){let t=e.map(r=>R.get(r.normalize("NFD")));for(let r of t)for(let n of t)B[r-1].includes(n)||B[r-1].push(n)}var $=new Map;function le(e){let t=$.get(e);if(!t){let r=Object.entries({...ie,...ce[e]??{}}).map(([n,o])=>[n.normalize("NFD"),o.normalize("NFD")]);$.set(e,t=new Map(r))}return t}function j(e){let t=[];for(let r of e.normalize("NFD")){if(/\p{M}/u.test(r)){r==="\u0303"&&t.length&&(t[t.length-1]+=r);continue}t.push(r)}return t}function _(e,t=""){let r=le(t),n=[];for(let o of j(e.replace(/\([^)]*\)/g," ").replace(/‍/g,"").replace(/\s+/g," ")))if(!ue.has(o))for(let a of j(r.get(o)??o)){a=r.get(a)??a;let s=R.get(a);if(!s)return null;n[n.length-1]!==s&&n.push(s)}return n}var O=class e{constructor(t,r,n,o,a,s,i=[]){this.text=t;this.lang=r;this.phonemes=n;this.thresholds=o;this.calibrated=a;this.chain=s;this.warnings=i}warnings;toJSON(){return{alkove:"word",spot:U("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:t,lang:r,p:n})=>({ipa:t,lang:r,p:+n.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(t){let r=typeof t=="string"?JSON.parse(t):t;if(r.alkove!=="word")throw new TypeError("not an Alkove word");if(r.spot!==U("spot"))return null;let n=r.phonemes.map(o=>({...o,ids:_(o.ipa,o.lang)??[]})).filter(o=>o.ids.length);return new e(r.text,r.lang,n,r.thresholds,r.calibrated,r.chain)}},q=e=>{if(e instanceof O)return e;let t=O.fromJSON(e);if(!t)throw new g("word.outdated",`Compiled for another Spot: compile "${typeof e=="string"?JSON.parse(e).text:e.text}" again.`);return t};var fe=.6931471803691238,pe=19082149292705877e-26;var N=new DataView(new ArrayBuffer(8));function W(e){if(e!==e||e<0)return NaN;if(e===0)return-1/0;if(e===1/0)return e;let t=0;e<22250738585072014e-324&&(e*=0x40000000000000,t=-54),N.setFloat64(0,e);let r=N.getUint32(0);t+=(r>>>20)-1023;let n=r&1048575,o=n+614244&1048576;t+=o>>>20,n|=o^1072693248,N.setUint32(0,n);let a=N.getFloat64(0)-1,s=a/(2+a),i=s*s,u=i*i,l=u*(.3999999999940942+u*(.22222198432149784+u*.15313837699209373)),d=i*(.6666666666666735+u*(.2857142874366239+u*(.1818357216161805+u*.14798198605116586))),f=.5*a*a;return t*fe-(f-(s*(f+d+l)+t*pe)-a)}var me=1.5707963267341256,he=6077100506506192e-26,ge=.6366197723675814;function F(e){let t=e*e;return e+e*t*(-.16666666666666632+t*(.00833333333332249+t*(-.0001984126982985795+t*(27557313707070068e-22+t*(-25050760253406863e-24+t*158969099521155e-24)))))}function E(e){let t=e*e,r=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),n=.5*t,o=1-n;return o+(1-o-n+t*r)}function G(e){let t=Math.round(e*ge);return[t&3,e-t*me-t*he]}function je(e){let[t,r]=G(e);return t===0?F(r):t===1?E(r):t===2?-F(r):-E(r)}function He(e){let[t,r]=G(e);return t===0?E(r):t===1?-F(r):t===2?-E(r):F(r)}var be=(e,t)=>{let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r},S=class e{constructor(t,r="focus",n=y.model,o=[]){this.centers=t;this.source=r;this.model=n;this.windows=o;if(!t.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(t){return this.closest(t).score}closest(t){let r=t instanceof e?t.centers:[t],n={score:-1,mine:0,theirs:0};for(let o of this.centers)for(let a of r){let s=be(o.id,a.id);s>n.score&&(n={score:s,mine:o.seconds,theirs:a.seconds})}return n}toArray(){return this.centers[0].id.slice()}toJSON(){let t=r=>Array.from(r,n=>+n.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(r=>({embedding:t(r.embedding),id:t(r.id),seconds:+r.seconds.toFixed(1)})),...this.windows.length?{windows:we(this.windows)}:{}}}static fromJSON(t){let r=typeof t=="string"?JSON.parse(t):t;if(r.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(r.model!==y.model)return null;let n=r.centers.map(o=>({embedding:Float32Array.from(o.embedding),id:Float32Array.from(o.id),seconds:o.seconds}));return new e(n,r.source,r.model,r.windows?ye(r.windows):[])}static merge(t){return new e(t.flatMap(r=>r.centers),t.every(r=>r.source==="raw")?"raw":"focus")}};function we(e){let t=new Uint8Array(e.length*2*(y.dim+4)),r=new DataView(t.buffer),n=0;for(let a of e)for(let s of[a.embedding,a.id]){let i=1e-9;for(let u of s)i=Math.max(i,Math.abs(u));r.setFloat32(n,i/127,!0),n+=4;for(let u of s)r.setInt8(n++,Math.round(u/i*127))}let o="";for(let a of t)o+=String.fromCharCode(a);return btoa(o)}function ye(e){let t=atob(e),r=Uint8Array.from(t,s=>s.charCodeAt(0)),n=new DataView(r.buffer),o=[],a=0;for(;a+2*(y.dim+4)<=r.length;){let s=[];for(let i=0;i<2;i++){let u=n.getFloat32(a,!0);a+=4;let l=new Float32Array(y.dim);for(let d=0;d<l.length;d++)l[d]=n.getInt8(a++)*u;s.push(l)}o.push({embedding:s[0],id:s[1],seconds:y.window/A})}return o}function ve(e,t,r){let n=(c,p)=>{let v=Math.min(Math.max(p,c[0]),c[c.length-1]),m=Math.max(1,c.findIndex(b=>b>=v));return[m-1,m,W(v/c[m-1])/W(c[m]/c[m-1])]},[o,a,s]=n(I.print,r),[i,u,l]=n(I.heard,t),d=I[e],f=c=>d[c][i]+(d[c][u]-d[c][i])*l;return f(o)+(f(a)-f(o))*s}var I={print:[1.5,3,6,12,24],heard:[.6,.9,1.5,3],lenient:[[-.07,-.065,-.05,-.0325],[.0025,.0275,.0825,.1075],[.045,.105,.135,.17],[.07,.1125,.2025,.255],[.0875,.15,.23,.2825]],balanced:[[.1675,.195,.2225,.245],[.2,.2325,.2675,.2925],[.23,.27,.3125,.335],[.2475,.295,.34,.37],[.26,.3125,.36,.3925]],strict:[[.335,.35,.365,.38],[.3475,.365,.385,.405],[.3625,.3825,.4075,.4275],[.3725,.395,.4225,.445],[.38,.405,.4325,.455]]},K=class e{static verify(t,r,{level:n="balanced"}={}){let{score:o,mine:a,theirs:s}=t.closest(r);return{same:o>=ve(n,s,a),score:o}}static identify(t,r,n={}){let o=null;for(let[a,s]of Object.entries(r)){let{same:i,score:u}=e.verify(s,t,n);i&&(!o||u>o.score)&&(o={who:a,score:u})}return o}};var Z="alkove",P="https://cache.alkove.invalid/",xe=30,h={},ee=!1,C=new Set;function Qe(e){ee&&te({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),h={...h,...e}}var Ze=()=>h,et=()=>void(ee=!0);function tt(e){return C.add(e),()=>void C.delete(e)}var X=new Set;function te(e){for(let t of C)t(e);C.size||e.level!=="warn"||X.has(e.code)||(X.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function re(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}var Ae=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",ne=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function Se(e,t){let r=globalThis.location?.href;return new URL(t,new URL(String(e).replace(/\/?$/,"/"),r)).href}function Y(e){if(h.modelBaseUrl)return Se(h.modelBaseUrl,e.file);if(!e.revision)throw new g("models.fetch",`${e.name}: not on Hugging Face in this version, set modelBaseUrl`);return te({code:"models.default-host",level:"warn",message:`${e.name} comes from Hugging Face: each user sends it their IP. Self-host the models in production (modelBaseUrl).`}),`https://huggingface.co/${L}/${e.name}/resolve/${e.revision}/${e.file}`}async function ke(e,t,r=0){let n;try{n=await fetch(e)}catch(d){throw new g("models.fetch",`fetch failed: ${e}`,d)}if(!n.ok||!n.body)throw new g("models.fetch",`HTTP ${n.status}: ${e}`);let o=Number(n.headers.get("content-length"))||r,a=n.body.getReader(),s=[],i=0;for(;;){let{done:d,value:f}=await a.read();if(d)break;s.push(f),i+=f.length,t?.({loaded:i,total:Math.max(o,i)})}let u=new Uint8Array(i),l=0;for(let d of s)u.set(d,l),l+=d.length;return u}async function k(e,t){let r=await re(t);if(r!==e.sha256)throw new g("models.hash",`${e.name}: sha256 ${r}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return t}async function V(e,t,r){return t instanceof ArrayBuffer?k(e,new Uint8Array(t)):t instanceof Uint8Array?k(e,t):k(e,await ke(String(t),r,e.bytes))}async function Ue(e,t){if(!ne())return t();let r;try{r=await caches.open(Z)}catch{return t()}let n=P+e.sha256,o=await r.match(n).catch(()=>{});if(o){let s=new Uint8Array(await o.arrayBuffer());if(await re(s)===e.sha256)return Q(r,e.sha256),s;await r.delete(n).catch(()=>{})}let a=await t();return await r.put(n,new Response(a,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),Q(r,e.sha256),a}async function Q(e,t){try{let r=P+"used.json",n=await(await e.match(r))?.json().catch(()=>null)??{},o=Date.now();n[t]=o;for(let[a,s]of Object.entries(n))o-s>xe*864e5&&(await e.delete(P+a),delete n[a]);await e.put(r,new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}}))}catch{}}async function rt(e){if(h.models?.[D(e)]instanceof ArrayBuffer||h.models?.[D(e)]instanceof Uint8Array)return!0;if(!ne())return!1;try{return!!await(await caches.open(Z)).match(P+e.sha256)}catch{return!1}}var D=e=>Object.entries(x).find(([,t])=>t===e)?.[0]??"engine";async function Oe(e,t,r){let n=h.models?.[D(e)]??r;if(n instanceof ArrayBuffer||n instanceof Uint8Array)return V(e,n);if(Ae()){if(n&&String(n).startsWith("file:")){let{readFile:o}=await import("node:fs/promises");return k(e,new Uint8Array(await o(new URL(String(n)))))}if(h.modelDir){let{readFile:o}=await import("node:fs/promises"),{join:a}=await import("node:path");return k(e,new Uint8Array(await o(a(h.modelDir,e.file))))}return V(e,n??Y(e),t)}return Ue(e,()=>V(e,n??Y(e),t))}function nt(e,t){return Oe(x[e],t)}function oe(e,t){let r=e[0]?.length??0,n=e.length,o=r*n*2,a=new Uint8Array(44+o),s=new DataView(a.buffer),i=(l,d)=>[...d].forEach((f,c)=>s.setUint8(l+c,f.charCodeAt(0)));i(0,"RIFF"),s.setUint32(4,36+o,!0),i(8,"WAVE"),i(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,t,!0),s.setUint32(28,t*n*2,!0),s.setUint16(32,n*2,!0),s.setUint16(34,16,!0),i(36,"data"),s.setUint32(40,o,!0);let u=44;for(let l=0;l<r;l++)for(let d=0;d<n;d++){let f=Math.max(-1,Math.min(1,e[d][l]));s.setInt16(u,f<0?f*32768:f*32767,!0),u+=2}return a}function st(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=a=>String.fromCharCode(...e.subarray(a,a+4));if(r(0)!=="RIFF"||r(8)!=="WAVE")throw new TypeError("audio.format: not a WAV file");let n=12,o=null;for(;n+8<=e.length;){let a=r(n),s=t.getUint32(n+4,!0),i=n+8;if(a==="fmt "){let u=t.getUint16(i,!0);u===65534&&(u=t.getUint16(i+24,!0)),o={format:u,ch:t.getUint16(i+2,!0),rate:t.getUint32(i+4,!0),bits:t.getUint16(i+14,!0)}}else if(a==="data"&&o){let{format:u,ch:l,rate:d,bits:f}=o,c=f/8,p=Math.floor(Math.min(s,e.length-i)/(c*l)),v=new Float32Array(p);for(let m=0;m<p;m++){let b=0;for(let M=0;M<l;M++){let w=i+(m*l+M)*c;if(u===3)b+=f===64?t.getFloat64(w,!0):t.getFloat32(w,!0);else if(f===8)b+=(t.getUint8(w)-128)/128;else if(f===16)b+=t.getInt16(w,!0)/32768;else if(f===24)b+=(t.getUint8(w)|t.getUint8(w+1)<<8|t.getInt8(w+2)<<16)/8388608;else if(f===32)b+=t.getInt32(w,!0)/2147483648;else throw new TypeError(`audio.format: ${f}-bit WAV`)}v[m]=b/l}return{pcm:v,rate:d}}n=i+s+(s&1)}throw new TypeError("audio.format: WAV without data")}var se={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6};function Ne(e,t=A){let r=e.focus!==void 0&&e.focus!==!1,n=typeof e.focus=="object"?e.focus:{},o=Fe(n.voiceprint)?.embedding,a=e.spot?.words.map(q)??[];return{focus:r?{print:o?Array.from(o):null,strength:n.strength??1}:null,cue:e.cue===void 0||e.cue===null?null:e.cue!==!1,speech:{...se,...typeof e.cue=="object"?e.cue:{}},normalize:e.normalize??!1,trace:!!e.trace,rate:t,spot:a.length?{words:a.map(s=>s.toJSON()),context:e.spot?.context??"anywhere"}:null}}function Fe(e){return e?e instanceof S?e:S.fromJSON(e):null}var J=class{constructor(t,r={}){this.opts=r;this.core=t.processor(Ne(r))}core;closed=!1;push(t){if(this.closed)throw new Error("push after end");return this.core.push(t)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},T=16e3;function pt(e,t,r={}){let{onProgress:n,signal:o,...a}=r,s=new J(e,a),i=[];try{for(let c=0;c<t.length;c+=T)o?.throwIfAborted(),i.push(s.push(t.subarray(c,Math.min(t.length,c+T)))),n?.({done:Math.min(t.length,c+T),total:t.length});i.push(s.end())}finally{s.release()}let u=new Float32Array(t.length),l=0;for(let c of i)u.set(c.audio.subarray(0,u.length-l),l),l+=c.audio.length;let d=t,f=i.reduce((c,p)=>({speech:[...c.speech,...p.speech],wakes:[...c.wakes,...p.wakes],diag:[...c.diag,...p.diag],trace:p.trace||c.trace?{focus:[...c.trace?.focus??[],...p.trace?.focus??[]],cue:[...c.trace?.cue??[],...p.trace?.cue??[]],spot:[...c.trace?.spot??[],...p.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:a.focus?u:t,raw:d,...f,toWav(c="audio"){return oe(c==="both"?[d,this.audio]:[c==="raw"?d:this.audio],A)}}}export{ae as a,A as b,x as c,Me as d,Le as e,H as f,B as g,_ as h,g as i,O as j,q as k,je as l,He as m,S as n,K as o,Qe as p,Ze as q,et as r,tt as s,te as t,Se as u,rt as v,Oe as w,nt as x,se as y,oe as z,st as A,Fe as B,J as C,pt as D};
1
+ var ae={name:"alkove-engine",file:"alkove-engine.wasm",bytes:488297,sha256:"239e24fe8293b36f6059b569d59d3ee7c2b2bfee562bd37fa33e71686ea33a1f"};var L="alkove-ai",z={focus:{name:"alkove-focus-1-preview",file:"alkove-focus-1-preview.alk",bytes:1111696,sha256:"a63cda32e023b8d76089f4c3df0cc2c69ba36017b8f6cdea1da1094ef8022b6a",revision:"8e91ef608366cf503fbd8aaa44bc2000dce899ed"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1066516,sha256:"977cd614996498f468536effbc2fb05138331751ca21572cf07b24184b4e7911",revision:"49e90fcff90dc6e6c47fa6e990e810bd628af4b3"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1-preview",file:"alkove-timbre-1-preview.alk",bytes:739632,sha256:"d498a7dd8b20528d783052b1e1d49e54ab7ee4e47aa12712d04f3d43edc68bd8",revision:"013f7c621e8687e992508b5fb01607eb17143550"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var A=16e3,x=z,Me={chunk:256,print:192,lag:256};var U=e=>`${x[e].name}@${x[e].sha256.slice(0,12)}`,y={model:U("timbre"),window:24e3,min:280,dim:192},Le={langs:["fr","en","es","pt","it","ca","ro"],beams:3,bos:59,eos:60,vocab:61,word:33,steps:39};var g=class extends Error{constructor(r,n,o){super(n);this.code=r;this.cause=o}name="AlkoveError"};var H=["i","y","\u0268","u","e","\xF8","\u0259","o","\u025B","\u0153","\u0254","a","\u0251","\xE6","\u028C","\u026A","\u028A","\u0250","\u025C","\u025B\u0303","\u0251\u0303","\u0254\u0303","\u0250\u0303","\u1EBD","\u0129","\xF5","\u0169","j","w","\u0265","p","b","t","d","k","\u0261","f","v","s","z","\u0283","\u0292","m","n","\u0272","\u014B","l","\u028E","\u0281","\u027E","r","\u0279","x","\u03B8","\xF0","\u03B2","\u0263","h"].map(e=>e.normalize("NFD"));var R=new Map(H.map((e,t)=>[e,t+1])),De=R.get("\u0259"),ie={"\u1D7B":"\u026A",\u025A:"\u0259\u0279",\u025D:"\u025C\u0279",\u029D:"j",\u025F:"\u0261",c:"k",\u026B:"l",\u026C:"l",\u03C7:"x",\u0266:"h",\u028B:"v",\u0271:"m",\u027B:"\u0279",\u0280:"\u0281",g:"\u0261",\u0258:"\u0259",\u0275:"\xF8",\u028F:"y",\u026F:"u",\u0264:"o",q:"k",\u0255:"\u0283",\u0291:"\u0292",\u00E7:"\u0283",\u0294:"",\u0252:"\u0254",\u0153\u0303:"\u025B\u0303",\u0278:"f",\u0299:"b"},ce={fr:{\u0251:"a",\u00E3:"\u0251\u0303",\u00F5:"\u0254\u0303",\u1EBD:"\u025B\u0303",\u0129:"\u025B\u0303",\u0169:"\u0254\u0303",\u0250\u0303:"\u0251\u0303",\u0250:"a",\u00E6:"a",\u028C:"\u0153",\u025C:"\u0153",\u026A:"i",\u028A:"u",\u0279:"\u0281",r:"\u0281",\u027E:"\u0281",x:"\u0281",\u03B8:"s",\u00F0:"z",h:"",\u03B2:"b",\u0263:"\u0261",\u028E:"lj",\u0268:"i"},es:{\u026A:"i",\u028A:"u",\u025B:"e",\u0254:"o",\u0251:"a",\u00E6:"a",\u028C:"a",\u0259:"e",\u0250:"a",\u0279:"\u027E"},it:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"a",\u0250:"a",\u0279:"r",x:"k",\u03B8:"t",h:""},pt:{\u026A:"i",\u028A:"u",\u028A\u0303:"\u0169",y:"j",\u00E3:"\u0250\u0303",\u0251:"a",\u00E6:"a",\u028C:"a",\u0279:"\u027E"},ca:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"\u027E",\u0250:"\u0259"},ro:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"r",\u027E:"r"},en:{\u0250:"\u0259",r:"\u0279",x:"k",\u025B\u0303:"\u0251\u0303"}},ue=new Set("\u02C8\u02CC\u02D0\u02D1\u203F-.|\u02B2\u02B0\u02B7' "),de=[["e","\u025B"],["o","\u0254"],["\xF8","\u0153","\u0259"],["i","j"],["u","w"],["y","\u0265"],["\u027E","r"]],B=H.map((e,t)=>[t+1]);for(let e of de){let t=e.map(r=>R.get(r.normalize("NFD")));for(let r of t)for(let n of t)B[r-1].includes(n)||B[r-1].push(n)}var $=new Map;function le(e){let t=$.get(e);if(!t){let r=Object.entries({...ie,...ce[e]??{}}).map(([n,o])=>[n.normalize("NFD"),o.normalize("NFD")]);$.set(e,t=new Map(r))}return t}function j(e){let t=[];for(let r of e.normalize("NFD")){if(/\p{M}/u.test(r)){r==="\u0303"&&t.length&&(t[t.length-1]+=r);continue}t.push(r)}return t}function _(e,t=""){let r=le(t),n=[];for(let o of j(e.replace(/\([^)]*\)/g," ").replace(/‍/g,"").replace(/\s+/g," ")))if(!ue.has(o))for(let a of j(r.get(o)??o)){a=r.get(a)??a;let s=R.get(a);if(!s)return null;n[n.length-1]!==s&&n.push(s)}return n}var O=class e{constructor(t,r,n,o,a,s,i=[]){this.text=t;this.lang=r;this.phonemes=n;this.thresholds=o;this.calibrated=a;this.chain=s;this.warnings=i}warnings;toJSON(){return{alkove:"word",spot:U("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:t,lang:r,p:n})=>({ipa:t,lang:r,p:+n.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(t){let r=typeof t=="string"?JSON.parse(t):t;if(r.alkove!=="word")throw new TypeError("not an Alkove word");if(r.spot!==U("spot"))return null;let n=r.phonemes.map(o=>({...o,ids:_(o.ipa,o.lang)??[]})).filter(o=>o.ids.length);return new e(r.text,r.lang,n,r.thresholds,r.calibrated,r.chain)}},q=e=>{if(e instanceof O)return e;let t=O.fromJSON(e);if(!t)throw new g("word.outdated",`Compiled for another Spot: compile "${typeof e=="string"?JSON.parse(e).text:e.text}" again.`);return t};var fe=.6931471803691238,pe=19082149292705877e-26;var N=new DataView(new ArrayBuffer(8));function W(e){if(e!==e||e<0)return NaN;if(e===0)return-1/0;if(e===1/0)return e;let t=0;e<22250738585072014e-324&&(e*=0x40000000000000,t=-54),N.setFloat64(0,e);let r=N.getUint32(0);t+=(r>>>20)-1023;let n=r&1048575,o=n+614244&1048576;t+=o>>>20,n|=o^1072693248,N.setUint32(0,n);let a=N.getFloat64(0)-1,s=a/(2+a),i=s*s,u=i*i,l=u*(.3999999999940942+u*(.22222198432149784+u*.15313837699209373)),d=i*(.6666666666666735+u*(.2857142874366239+u*(.1818357216161805+u*.14798198605116586))),f=.5*a*a;return t*fe-(f-(s*(f+d+l)+t*pe)-a)}var me=1.5707963267341256,he=6077100506506192e-26,ge=.6366197723675814;function F(e){let t=e*e;return e+e*t*(-.16666666666666632+t*(.00833333333332249+t*(-.0001984126982985795+t*(27557313707070068e-22+t*(-25050760253406863e-24+t*158969099521155e-24)))))}function E(e){let t=e*e,r=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),n=.5*t,o=1-n;return o+(1-o-n+t*r)}function G(e){let t=Math.round(e*ge);return[t&3,e-t*me-t*he]}function je(e){let[t,r]=G(e);return t===0?F(r):t===1?E(r):t===2?-F(r):-E(r)}function He(e){let[t,r]=G(e);return t===0?E(r):t===1?-F(r):t===2?-E(r):F(r)}var be=(e,t)=>{let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r},S=class e{constructor(t,r="focus",n=y.model,o=[]){this.centers=t;this.source=r;this.model=n;this.windows=o;if(!t.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(t){return this.closest(t).score}closest(t){let r=t instanceof e?t.centers:[t],n={score:-1,mine:0,theirs:0};for(let o of this.centers)for(let a of r){let s=be(o.id,a.id);s>n.score&&(n={score:s,mine:o.seconds,theirs:a.seconds})}return n}toArray(){return this.centers[0].id.slice()}toJSON(){let t=r=>Array.from(r,n=>+n.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(r=>({embedding:t(r.embedding),id:t(r.id),seconds:+r.seconds.toFixed(1)})),...this.windows.length?{windows:we(this.windows)}:{}}}static fromJSON(t){let r=typeof t=="string"?JSON.parse(t):t;if(r.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(r.model!==y.model)return null;let n=r.centers.map(o=>({embedding:Float32Array.from(o.embedding),id:Float32Array.from(o.id),seconds:o.seconds}));return new e(n,r.source,r.model,r.windows?ye(r.windows):[])}static merge(t){return new e(t.flatMap(r=>r.centers),t.every(r=>r.source==="raw")?"raw":"focus")}};function we(e){let t=new Uint8Array(e.length*2*(y.dim+4)),r=new DataView(t.buffer),n=0;for(let a of e)for(let s of[a.embedding,a.id]){let i=1e-9;for(let u of s)i=Math.max(i,Math.abs(u));r.setFloat32(n,i/127,!0),n+=4;for(let u of s)r.setInt8(n++,Math.round(u/i*127))}let o="";for(let a of t)o+=String.fromCharCode(a);return btoa(o)}function ye(e){let t=atob(e),r=Uint8Array.from(t,s=>s.charCodeAt(0)),n=new DataView(r.buffer),o=[],a=0;for(;a+2*(y.dim+4)<=r.length;){let s=[];for(let i=0;i<2;i++){let u=n.getFloat32(a,!0);a+=4;let l=new Float32Array(y.dim);for(let d=0;d<l.length;d++)l[d]=n.getInt8(a++)*u;s.push(l)}o.push({embedding:s[0],id:s[1],seconds:y.window/A})}return o}function ve(e,t,r){let n=(c,p)=>{let v=Math.min(Math.max(p,c[0]),c[c.length-1]),m=Math.max(1,c.findIndex(b=>b>=v));return[m-1,m,W(v/c[m-1])/W(c[m]/c[m-1])]},[o,a,s]=n(I.print,r),[i,u,l]=n(I.heard,t),d=I[e],f=c=>d[c][i]+(d[c][u]-d[c][i])*l;return f(o)+(f(a)-f(o))*s}var I={print:[1.5,3,6,12,24],heard:[.6,.9,1.5,3],lenient:[[-.07,-.065,-.05,-.0325],[.0025,.0275,.0825,.1075],[.045,.105,.135,.17],[.07,.1125,.2025,.255],[.0875,.15,.23,.2825]],balanced:[[.1675,.195,.2225,.245],[.2,.2325,.2675,.2925],[.23,.27,.3125,.335],[.2475,.295,.34,.37],[.26,.3125,.36,.3925]],strict:[[.335,.35,.365,.38],[.3475,.365,.385,.405],[.3625,.3825,.4075,.4275],[.3725,.395,.4225,.445],[.38,.405,.4325,.455]]},K=class e{static verify(t,r,{level:n="balanced"}={}){let{score:o,mine:a,theirs:s}=t.closest(r);return{same:o>=ve(n,s,a),score:o}}static identify(t,r,n={}){let o=null;for(let[a,s]of Object.entries(r)){let{same:i,score:u}=e.verify(s,t,n);i&&(!o||u>o.score)&&(o={who:a,score:u})}return o}};var Z="alkove",P="https://cache.alkove.invalid/",xe=30,h={},ee=!1,C=new Set;function Qe(e){ee&&te({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),h={...h,...e}}var Ze=()=>h,et=()=>void(ee=!0);function tt(e){return C.add(e),()=>void C.delete(e)}var X=new Set;function te(e){for(let t of C)t(e);C.size||e.level!=="warn"||X.has(e.code)||(X.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function re(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}var Ae=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",ne=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function Se(e,t){let r=globalThis.location?.href;return new URL(t,new URL(String(e).replace(/\/?$/,"/"),r)).href}function Y(e){if(h.modelBaseUrl)return Se(h.modelBaseUrl,e.file);if(!e.revision)throw new g("models.fetch",`${e.name}: not on Hugging Face in this version, set modelBaseUrl`);return te({code:"models.default-host",level:"warn",message:`${e.name} comes from Hugging Face: each user sends it their IP. Self-host the models in production (modelBaseUrl).`}),`https://huggingface.co/${L}/${e.name}/resolve/${e.revision}/${e.file}`}async function ke(e,t,r=0){let n;try{n=await fetch(e)}catch(d){throw new g("models.fetch",`fetch failed: ${e}`,d)}if(!n.ok||!n.body)throw new g("models.fetch",`HTTP ${n.status}: ${e}`);let o=Number(n.headers.get("content-length"))||r,a=n.body.getReader(),s=[],i=0;for(;;){let{done:d,value:f}=await a.read();if(d)break;s.push(f),i+=f.length,t?.({loaded:i,total:Math.max(o,i)})}let u=new Uint8Array(i),l=0;for(let d of s)u.set(d,l),l+=d.length;return u}async function k(e,t){let r=await re(t);if(r!==e.sha256)throw new g("models.hash",`${e.name}: sha256 ${r}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return t}async function V(e,t,r){return t instanceof ArrayBuffer?k(e,new Uint8Array(t)):t instanceof Uint8Array?k(e,t):k(e,await ke(String(t),r,e.bytes))}async function Ue(e,t){if(!ne())return t();let r;try{r=await caches.open(Z)}catch{return t()}let n=P+e.sha256,o=await r.match(n).catch(()=>{});if(o){let s=new Uint8Array(await o.arrayBuffer());if(await re(s)===e.sha256)return Q(r,e.sha256),s;await r.delete(n).catch(()=>{})}let a=await t();return await r.put(n,new Response(a,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),Q(r,e.sha256),a}async function Q(e,t){try{let r=P+"used.json",n=await(await e.match(r))?.json().catch(()=>null)??{},o=Date.now();n[t]=o;for(let[a,s]of Object.entries(n))o-s>xe*864e5&&(await e.delete(P+a),delete n[a]);await e.put(r,new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}}))}catch{}}async function rt(e){if(h.models?.[D(e)]instanceof ArrayBuffer||h.models?.[D(e)]instanceof Uint8Array)return!0;if(!ne())return!1;try{return!!await(await caches.open(Z)).match(P+e.sha256)}catch{return!1}}var D=e=>Object.entries(x).find(([,t])=>t===e)?.[0]??"engine";async function Oe(e,t,r){let n=h.models?.[D(e)]??r;if(n instanceof ArrayBuffer||n instanceof Uint8Array)return V(e,n);if(Ae()){if(n&&String(n).startsWith("file:")){let{readFile:o}=await import("node:fs/promises");return k(e,new Uint8Array(await o(new URL(String(n)))))}if(h.modelDir){let{readFile:o}=await import("node:fs/promises"),{join:a}=await import("node:path");return k(e,new Uint8Array(await o(a(h.modelDir,e.file))))}return V(e,n??Y(e),t)}return Ue(e,()=>V(e,n??Y(e),t))}function nt(e,t){return Oe(x[e],t)}function oe(e,t){let r=e[0]?.length??0,n=e.length,o=r*n*2,a=new Uint8Array(44+o),s=new DataView(a.buffer),i=(l,d)=>[...d].forEach((f,c)=>s.setUint8(l+c,f.charCodeAt(0)));i(0,"RIFF"),s.setUint32(4,36+o,!0),i(8,"WAVE"),i(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,t,!0),s.setUint32(28,t*n*2,!0),s.setUint16(32,n*2,!0),s.setUint16(34,16,!0),i(36,"data"),s.setUint32(40,o,!0);let u=44;for(let l=0;l<r;l++)for(let d=0;d<n;d++){let f=Math.max(-1,Math.min(1,e[d][l]));s.setInt16(u,f<0?f*32768:f*32767,!0),u+=2}return a}function st(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=a=>String.fromCharCode(...e.subarray(a,a+4));if(r(0)!=="RIFF"||r(8)!=="WAVE")throw new TypeError("audio.format: not a WAV file");let n=12,o=null;for(;n+8<=e.length;){let a=r(n),s=t.getUint32(n+4,!0),i=n+8;if(a==="fmt "){let u=t.getUint16(i,!0);u===65534&&(u=t.getUint16(i+24,!0)),o={format:u,ch:t.getUint16(i+2,!0),rate:t.getUint32(i+4,!0),bits:t.getUint16(i+14,!0)}}else if(a==="data"&&o){let{format:u,ch:l,rate:d,bits:f}=o,c=f/8,p=Math.floor(Math.min(s,e.length-i)/(c*l)),v=new Float32Array(p);for(let m=0;m<p;m++){let b=0;for(let M=0;M<l;M++){let w=i+(m*l+M)*c;if(u===3)b+=f===64?t.getFloat64(w,!0):t.getFloat32(w,!0);else if(f===8)b+=(t.getUint8(w)-128)/128;else if(f===16)b+=t.getInt16(w,!0)/32768;else if(f===24)b+=(t.getUint8(w)|t.getUint8(w+1)<<8|t.getInt8(w+2)<<16)/8388608;else if(f===32)b+=t.getInt32(w,!0)/2147483648;else throw new TypeError(`audio.format: ${f}-bit WAV`)}v[m]=b/l}return{pcm:v,rate:d}}n=i+s+(s&1)}throw new TypeError("audio.format: WAV without data")}var se={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6};function Ne(e,t=A){let r=e.focus!==void 0&&e.focus!==!1,n=typeof e.focus=="object"?e.focus:{},o=Fe(n.voiceprint)?.embedding,a=e.spot?.words.map(q)??[];return{focus:r?{print:o?Array.from(o):null,strength:n.strength??1}:null,cue:e.cue===void 0||e.cue===null?null:e.cue!==!1,speech:{...se,...typeof e.cue=="object"?e.cue:{}},normalize:e.normalize??!1,trace:!!e.trace,rate:t,spot:a.length?{words:a.map(s=>s.toJSON()),context:e.spot?.context??"anywhere"}:null}}function Fe(e){return e?e instanceof S?e:S.fromJSON(e):null}var J=class{constructor(t,r={}){this.opts=r;this.core=t.processor(Ne(r))}core;closed=!1;push(t){if(this.closed)throw new Error("push after end");return this.core.push(t)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},T=16e3;function pt(e,t,r={}){let{onProgress:n,signal:o,...a}=r,s=new J(e,a),i=[];try{for(let c=0;c<t.length;c+=T)o?.throwIfAborted(),i.push(s.push(t.subarray(c,Math.min(t.length,c+T)))),n?.({done:Math.min(t.length,c+T),total:t.length});i.push(s.end())}finally{s.release()}let u=new Float32Array(t.length),l=0;for(let c of i)u.set(c.audio.subarray(0,u.length-l),l),l+=c.audio.length;let d=t,f=i.reduce((c,p)=>({speech:[...c.speech,...p.speech],wakes:[...c.wakes,...p.wakes],diag:[...c.diag,...p.diag],trace:p.trace||c.trace?{focus:[...c.trace?.focus??[],...p.trace?.focus??[]],cue:[...c.trace?.cue??[],...p.trace?.cue??[]],spot:[...c.trace?.spot??[],...p.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:a.focus?u:t,raw:d,...f,toWav(c="audio"){return oe(c==="both"?[d,this.audio]:[c==="raw"?d:this.audio],A)}}}export{ae as a,A as b,x as c,Me as d,Le as e,H as f,B as g,_ as h,g as i,O as j,q as k,je as l,He as m,S as n,K as o,Qe as p,Ze as q,et as r,tt as s,te as t,Se as u,rt as v,Oe as w,nt as x,se as y,oe as z,st as A,Fe as B,J as C,pt as D};
@@ -1 +1 @@
1
- import{A as he,B as b,a as E,b as f,c as ee,d as B,e as te,f as re,g as se,h as V,i as p,j as oe,k,l as ie,m as _,n as S,o as D,p as ne,q as W,r as ae,s as R,t as N,u as J,v as le,w as ce,x as de,z as pe}from"./chunk-23LYNLTX.js";var v=class{static langs=te.langs;static inventory=re.map(r=>r.normalize("NFC"));static distance(r,e){let t=typeof r=="string"?V(r.replace(/^\/|\/$/g,""))??[]:r,s=typeof e=="string"?V(e.replace(/^\/|\/$/g,""))??[]:e;if(!t.length||!s.length)return t.length===s.length?0:1;let i=Array.from({length:s.length+1},(n,l)=>l);for(let n=1;n<=t.length;n++){let l=[n];for(let a=1;a<=s.length;a++){let c=t[n-1]===s[a-1]?0:se[t[n-1]-1].includes(s[a-1])?.5:1;l.push(Math.min(i[a]+1,l[a-1]+1,i[a-1]+c))}i=l}return i[s.length]/Math.max(t.length,s.length)}};var M=class{handlers=new Map;on(r,e){let t=this.handlers.get(r);return t||this.handlers.set(r,t=new Set),t.add(e),()=>void t.delete(e)}emit(r,e){for(let t of this.handlers.get(r)??[])try{t(e)}catch(s){queueMicrotask(()=>{throw s})}}listens(r){return!!this.handlers.get(r)?.size}clear(){this.handlers.clear()}};var P=class extends M{done;target=null;cancelled=!1;abort=null;constructor(r){super(),this.done=this.run(r),this.done.catch(()=>{})}async run(r){let e=await r.compile();for(let i of e.warnings)this.emit("warning",i);if(this.cancelled)throw new DOMException("cancelled","AbortError");let t=this.target=await r.open(e.toJSON()),s=[t.on("take",i=>this.emit("take",i))];try{let i=await new Promise((c,d)=>{s.push(t.on("enrolled",c)),this.abort=()=>d(new DOMException("cancelled","AbortError"))});if(i.error||!i.word)throw new p("engine.failed",i.error??"enrollment failed");for(let c of i.warnings??[])this.emit("warning",c);let n=i.audio&&i.audio.length>=4e3?await r.embed(i.audio,t.source):null,l=k(i.word);return{word:new oe(l.text,l.lang,l.phonemes,l.thresholds,l.calibrated,l.chain,[...e.warnings,...i.warnings??[]]),voiceprint:n}}finally{for(let i of s)i();t.stop()}}cancel(){this.cancelled=!0,this.abort?.(),this.target?.stop()}};var m=24,C=128,g=class o{constructor(r,e,t=!1){this.inRate=r;this.outRate=e;if(this.identity=r===e,t&&(this.t=m),this.identity)return;this.ratio=r/e;let s=this.half,i=.9/Math.max(1,this.ratio),n=new Float32Array((C+1)*m);for(let l=0;l<=C;l++){let a=l/C,c=0;for(let d=0;d<m;d++){let u=d-(s-1)-a,h=i*u,w=h===0?1:ie(Math.PI*h)/(Math.PI*h),F=.42+.5*_(Math.PI*u/s)+.08*_(2*Math.PI*u/s);n[l*m+d]=w*F,c+=n[l*m+d]}for(let d=0;d<m;d++)n[l*m+d]/=c}this.table=n}static HALF=m/2;identity;ratio=1;half=m/2;table=new Float32Array(0);work=new Float32Array(0);histLen=m;t=m/2;push(r,e){if(this.identity){for(let a=0;a<r.length;a++)e(r[a]);return}if(this.work.length<m+8+r.length){let a=new Float32Array(m+8+r.length);a.set(this.work.subarray(0,this.histLen)),this.work=a}let t=this.work;t.set(r,this.histLen);let s=this.histLen+r.length,i=s-1-this.half,n=this.t;for(;n<=i;){let a=Math.floor(n),c=Math.round((n-a)*C)*m,d=a-(this.half-1),u=0;for(let h=0;h<m;h++)u+=t[d+h]*this.table[c+h];e(u),n+=this.ratio}let l=Math.floor(n)-(this.half-1);t.copyWithin(0,l,s),this.histLen=s-l,this.t=n-l}static all(r,e,t){if(e===t)return r;let s=new o(e,t,!0),i=Math.round(r.length*t/e),n=new Float32Array(i),l=0,a=c=>{l<i&&(n[l++]=c)};return s.push(r,a),s.push(new Float32Array(Math.ceil(m*s.ratio)+16),a),n}};var I=class{constructor(r,e){this.opts=r;this.send=e;this.resampler=new g(f,r.rate),this.buf=new Float32Array(Math.round(r.rate*r.chunkMs/1e3))}resampler;buf;fill=0;push(r){this.resampler.push(r,e=>{this.buf[this.fill++]=e,this.fill===this.buf.length&&(this.send(Oe(this.buf,this.opts.format)),this.fill=0)})}};function Oe(o,r){if(r==="f32")return o.slice().buffer;let e=new Int16Array(o.length);for(let t=0;t<o.length;t++){let s=Math.max(-1,Math.min(1,o[t]));e[t]=s<0?s*32768:s*32767}return e.buffer}var U=class{constructor(r){this.worker=r;r.onmessage=e=>{let t=e.data;if(t?.type==="reply"){let s=this.replies.get(t.id);this.replies.delete(t.id),t.error?s?.reject(Object.assign(new Error(t.error.message),{code:t.error.code})):s?.resolve(t.result)}else if(t?.type==="progress")this.replies.get(t.id)?.progress?.(t.p);else for(let s of this.listeners)s(t)},r.onerror=e=>{for(let t of this.replies.values())t.reject(new p("engine.failed",e.message||"worker failed"));this.replies.clear();for(let t of this.listeners)t({type:"crash",message:e.message})}}next=1;replies=new Map;listeners=new Set;listen(r){return this.listeners.add(r),()=>void this.listeners.delete(r)}get busy(){return this.replies.size>0}request(r,e=[],t){let s=this.next++;return new Promise((i,n)=>{this.replies.set(s,{resolve:i,reject:n,progress:t}),this.worker.postMessage({...r,id:s,progress:!!t},e)})}call(r,e,t=[],s){return this.request({type:"call",method:r,args:e},t,s)}post(r,e=[]){this.worker.postMessage(r,e)}},Ee=null,We=()=>Ee??=import("./assets-VHBYP6JE.js");async function H(o){let r=W().assetBaseUrl;if(r)return J(r,`alkove-${o}.js`);let e=await We();return URL.createObjectURL(new Blob([o==="worker"?e.WORKER:e.WORKLET],{type:"text/javascript"}))}var ue=null;function Re(o){return ue??=(async()=>{let r=W().models?.engine,e=W().assetBaseUrl,t=r??(e?J(e,E.file):new URL("./alkove-engine.wasm",import.meta.url).href),s=await ce(E,o,t);return WebAssembly.compile(s)})().catch(r=>{throw ue=null,r})}var y=class o{static current=null;sent={realtime:new Set,background:new Set};links={};holds=0;static get(){return ae(),o.current??=new o}link(r){return this.links[r]??=(async()=>{let[e,t]=await Promise.all([Re(),H("worker")]),s=new U(new Worker(t,{type:"module",name:`alkove-${r}`})),i=this.links[r];return s.listen(n=>n.type==="crash"&&this.links[r]===i&&this.drop(r,s)),await new Promise((n,l)=>{let a=s.listen(c=>{c.type==="booted"?(a(),n()):c.type==="crash"&&l(new p("engine.failed",c.message))});s.post({type:"boot",module:e})}),s})().catch(e=>{throw delete this.links[r],e})}drop(r,e){delete this.links[r],this.sent[r].clear(),e.worker.terminate()}hold(){this.holds++;let r=!0;return()=>{r&&this.holds--,r=!1}}async idle(){for(let r of["realtime","background"]){let e=this.links[r],t=e&&await e.catch(()=>null);t&&this.links[r]===e&&(r==="realtime"||!t.busy&&!this.holds)&&this.drop(r,t)}}async models(r,e,t){let s=await this.link(r),i=e.filter(c=>!this.sent[r].has(c));if(!i.length)return s;let n=new Map,l=await Promise.all(i.map(c=>de(c,d=>{n.set(c,d);let u=0,h=0;for(let w of n.values())u+=w.loaded,h+=w.total;t?.({loaded:u,total:h})}))),a=Object.fromEntries(i.map((c,d)=>[c,l[d].slice().buffer]));await s.request({type:"models",models:a},Object.values(a));for(let c of i)this.sent[r].add(c);return s}static report=N};var Ne=5e3,Ce=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function T(){let o=globalThis,r=!1;try{r=typeof WebAssembly<"u"&&WebAssembly.validate(Ce)}catch{}return{worklet:typeof o.AudioWorkletNode=="function",simd:r,secure:o.isSecureContext!==!1}}async function me(){try{let o=await navigator.permissions.query({name:"microphone"});return o.state==="granted"||o.state==="denied"?o.state:"prompt"}catch{return"prompt"}}var j={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,voiceIsolation:!1,channelCount:1};async function x(o,r,e=!1){if(!T().secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!navigator.mediaDevices?.getUserMedia)throw new p("browser.unsupported","No getUserMedia in this browser.");let t=setTimeout(()=>N({code:"mic.waiting",level:"info",message:"The permission prompt has had no answer for 5 s."}),Ne);try{let s=e?{noiseSuppression:!0,autoGainControl:!0}:{},i=navigator.mediaDevices.getUserMedia({audio:{...j,...s,...o?{deviceId:{exact:o}}:{}}});return await(r?Promise.race([i,new Promise((l,a)=>{r.aborted&&a(r.reason),r.addEventListener("abort",()=>{i.then(c=>c.getTracks().forEach(d=>d.stop()),()=>{}),a(r.reason)})})]):i)}catch(s){if(r?.aborted)throw r.reason;let i=s?.name;throw i==="NotAllowedError"||i==="SecurityError"?new p("mic.denied","Microphone permission denied.",s):i==="NotFoundError"||i==="OverconstrainedError"?new p("mic.not-found","No microphone.",s):i==="NotReadableError"||i==="AbortError"?new p("mic.busy","The microphone is used by another app.",s):s}finally{clearTimeout(t)}}function fe(o){let r=o.getSettings();return["noiseSuppression","autoGainControl","voiceIsolation"].filter(e=>r[e]===!0)}var L=5e3,G=6e4,Ie=1500,Le=30,Fe=.002,Be=2e3,Ve=0,K=new WeakMap,$=new Set,we=0,ge="This print comes from another Timbre: ignored, learn it again.",O=class extends M{constructor(e){super();this.opts=e;this.running=new Promise(t=>this.markRunning=t)}id=++Ve;ctx;ownCtx=!1;stream;ownStream=!1;source;node;dest=null;farSource=null;rt=null;bg=null;offs=[];_mode={mode:"raw",reason:"loading"};_status="starting";_latency=0;_voiceprint=null;retryMs=L;retryTimer;started=0;counted=!1;enabled=!0;printed=!1;sender=null;stalled=!1;spotWords=null;running;markRunning;ran=!1;notReady=null;waiting=[];warned=new Set;browserWant=!1;browserHas=!1;browserBusy=Promise.resolve();browserTimer;listening=!0;holding=!1;get disposed(){return this._status==="disposed"}get mode(){return this._mode.mode}get status(){return this._status}get latency(){return this._latency}get voiceprint(){return this._voiceprint}get ready(){return this.ran?Promise.resolve():this.notReady?Promise.reject(this.notReady):new Promise((e,t)=>this.waiting.push([e,t]))}settle(e,t=!1){if(this.ran)return;this.ran=!e,t&&(this.notReady=e);let s=this.waiting;this.waiting=[];for(let[i,n]of s)e?n(e):i()}get track(){return this.stalled?this.stream.getAudioTracks()[0]??null:this.dest?.stream.getAudioTracks()[0]??null}now(){return this.ctx?this.ctx.currentTime-this.started:0}get delay16(){return 0}async open(){we++,this.counted=!0;try{await this.opening()}catch(e){throw this.dispose(),e}}async opening(){this.offs.push(R(i=>this.diag(i))),this.opts.voiceprint&&!b(this.opts.voiceprint)&&this.diag({code:"voiceprint.reset",level:"warn",message:ge});let e=T();if(!e.secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!e.worklet)throw new p("browser.unsupported","No AudioWorklet in this browser (Safari 14.1 or later).");let t=this.opts;t.stream||t.track?this.stream=t.stream??new MediaStream([t.track]):(this.stream=await x(t.deviceId,t.signal),this.ownStream=!0);let s=this.stream.getAudioTracks()[0];if(!s)throw new p("mic.not-found","The stream has no audio track.");if(!this.ownStream){let i=fe(s);i.length&&this.diag({code:"mic.processed",level:"warn",message:`The browser processes the stream before the models (${i.join(", ")}): open it with these off.`,settings:i})}for(let i of $)i.stream.getAudioTracks()[0]?.getSettings().deviceId===s.getSettings().deviceId&&i!==this&&this.diag({code:"mic.twice",level:"warn",message:"Two inputs on the same microphone run everything twice: use call.spot() for words on a call input."});t.audioContext?this.ctx=t.audioContext:(this.ctx=new AudioContext,this.ownCtx=!0),await this.build(),$.add(this),this.watchContext(),this.watchTrack(s),this.ownStream&&t.followDefault!==!1&&!t.deviceId&&this.followDefault(),this.startModels(),this.flushHeld()}async build(){let e=this.ctx,t=K.get(e);t||(t=H("worklet").then(i=>e.audioWorklet.addModule(i)),t.catch(()=>K.delete(e)),K.set(e,t)),await t,this.node=new AudioWorkletNode(e,"alkove",{numberOfInputs:2,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{delay16:this.delay16,tapRaw:this.kind==="agent"}}),this.node.port.onmessage=i=>this.onWorklet(i.data),this.source=e.createMediaStreamSource(this.stream),this.source.connect(this.node,0,0);let s=this.opts.farEnd;s&&s!=="manual"&&(this.farSource=s instanceof MediaStreamTrack?e.createMediaStreamSource(new MediaStream([s])):s,this.farSource.connect(this.node,0,1)),this.connectOutput(),this.started=e.currentTime,await this.resume()}connectOutput(){this.dest=this.ctx.createMediaStreamDestination(),this.node.connect(this.dest)}onWorklet(e){e.type==="overload"?(this.diag({code:"overload",level:"warn",message:"The device is too slow for the models: raw microphone for a while.",queueMs:e.queueMs,sent:e.sent,received:e.received}),this.setMode("raw","overload")):e.type==="retry"?this.setMode(this.activeMode()):e.type==="latency"?this._latency=Math.round(e.ms):e.type==="raw"?this.rawAudio(e.pcm):e.type==="timing"&&(this._latency=e.latencyMs,this.diag({code:"queue",level:"info",...e}))}rawAudio(e){}activeMode(){return this.enabled?this.kind==="wake"?this.reference()?"spot+print":"spot":this.printed?"focus+print":"focus":"raw"}held=[];emit(e,t){this.held?this.held.push([e,t]):this.deliver(e,t)}flushHeld(){setTimeout(()=>{let e=this.held??[];this.held=null;for(let[t,s]of e)this.deliver(t,s)},0)}deliver(e,t){if(super.emit(e,t),e!=="diag")return;let s=t;s.level!=="warn"||this.listens("diag")||this.warned.has(s.code)||(this.warned.add(s.code),console.warn(`alkove: ${s.message??s.code}`,s))}setMode(e,t){this._mode.mode===e&&this._mode.reason===t||(this._mode=t?{mode:e,reason:t}:{mode:e},this.emit("mode",this._mode),this.followRaw())}followRaw(){if(clearTimeout(this.browserTimer),!this.ownStream||this.disposed)return;this._mode.mode==="raw"&&this._mode.reason!=="off"?this.browserWant||(this.browserTimer=setTimeout(()=>this.wantBrowser(!0),Be)):this.wantBrowser(!1)}wantBrowser(e){this.browserWant=e,this.browserBusy=this.browserBusy.then(()=>this.browser())}async browser(){let e=this.browserWant,t=this.stream.getAudioTracks()[0];if(this.disposed||!this.ownStream||e===this.browserHas||!t)return;try{await t.applyConstraints({...j,noiseSuppression:e,autoGainControl:e})}catch{}let s=t.getSettings().noiseSuppression;if(typeof s=="boolean"&&s!==e){if(this.disposed||!this.ownStream)return;let n=t.getSettings().deviceId??this.opts.deviceId;t.stop();try{let l=await x(n,void 0,e);if(this.disposed||!this.ownStream){for(let a of l.getTracks())a.stop();return}await this.setStream(l,!0)}catch{this.onTrackEnded();return}}this.browserHas=e;let i=this.stream.getAudioTracks()[0]?.getSettings().noiseSuppression;this.diag({code:"mic.browser",level:"info",noiseSuppression:e,autoGainControl:e,applied:typeof i=="boolean"?i:null})}setStatus(e){this._status!==e&&(this._status=e,this.emit("status",e))}diag(e){this.emit("diag",e)}async startModels(){if(!this.disposed){if(!T().simd){this.diag({code:"engine.unsupported",level:"warn",message:"No WebAssembly SIMD: raw microphone for this session."}),this.setMode("raw","unsupported"),this.settle(new p("browser.unsupported","No WebAssembly SIMD: the models cannot run in this browser."),!0);return}this.setMode("raw","loading"),this.followRaw();try{let e=y.get(),t=await e.models("realtime",[...this.models(),...this.spotWords?.words.length?["spot"]:[]]),s;if(this.wantsBackground()){let a=await e.models("background",["timbre"]),c=new MessageChannel;a.post({type:"rt-port",input:this.id,port:c.port2,ref:this.reference()?.toJSON()??null},[c.port2]),s=c.port1,this.bg=a,this.offs.push(a.listen(u=>u.input===this.id&&u.type==="event"&&this.onEvent(u.event)));let d=b(this.opts.voiceprint);this.opts.learn&&await a.call("learner",[this.id,d?.toJSON()??null])}if(this.disposed)return;this.rt=t,this.offs.push(t.listen(a=>this.onRealtime(a)));let i=this.appPort(),n=[...s?[s]:[],...i?[i]:[]];i&&(this.portGiven=!0),await t.request({type:"realtime",input:this.id,opts:this.realtimeOptions(),bg:s,out:i},n),(!this.listening||this.holding)&&t.post({type:"set",input:this.id,...!this.listening&&{listen:!1},...this.holding&&{hold:!0}}),this.spotWords?.words.length&&(await e.models("realtime",["spot"]),t.post({type:"set",input:this.id,...this.spotWords})),this.markRunning(),this.settle(null);let l=new MessageChannel;t.post({type:"worklet",input:this.id,port:l.port2},[l.port2]),this.node.port.postMessage({type:"connect",port:l.port1},[l.port1]),this.printed=!!b(this.opts.voiceprint),this.retryMs=L,this.setMode(this.activeMode(),this.enabled?void 0:"off")}catch(e){if(this.disposed)return;this.diag({code:"models.failed",level:"warn",message:`Models not loaded, raw microphone; retry in ${this.retryMs/1e3} s.`,error:String(e?.message??e)}),this.setMode("raw","failed"),this.settle(e instanceof p?e:new p("engine.failed",`Models not loaded: ${String(e?.message??e)}`,e)),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,G)}}}portGiven=!1;appPort(){return this.portGiven?void 0:this.opts.output?.port}wantsBackground(){return!!this.opts.learn}reference(){return null}onRealtime(e){if(e.input===this.id)if(e.type==="events"){let t=[];for(let s of e.list)s.type==="trace"?t.push(s):this.onEvent(s);t.length&&this.emit("trace",t)}else e.type==="pcm"?e.kind==="audio"?this.emit("audio",e.pcm):this.emit("utterance",{pcm:e.pcm,start:e.start,end:e.end,...e.level&&{level:e.level}}):e.type==="crash"&&(this.node.port.postMessage({type:"stop"}),this.rt=null,this.diag({code:"engine.crash",level:"warn",message:`The engine stopped: raw microphone; retry in ${this.retryMs/1e3} s.`,error:e.message}),this.setMode("raw","failed"),clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,G))}onEvent(e){switch(e.type){case"speechstart":this.emit("speechstart",{start:e.start});break;case"speechcancel":this.emit("speechcancel",{start:e.start});break;case"speechend":this.emit("speechend",{start:e.start,end:e.end,..."voiceDb"in e&&{level:{voiceDb:e.voiceDb,noiseDb:e.noiseDb,refDb:e.refDb}}});break;case"wake":this.emit("wake",e);break;case"take":{let{type:t,...s}=e;this.emit("take",s);break}case"enrolled":{let{type:t,...s}=e;this.emit("enrolled",s);break}case"heard":this.emit("heard",{speech:e.speech,scores:e.scores});break;case"learn":this.emit("learn",{progress:e.progress});break;case"voiceprint":{let t=S.fromJSON(e.json);t&&(this._voiceprint=t,this.emit("voiceprint",t));break}case"idle":this.diag({code:"idle",level:"info",asleep:e.asleep,at:e.at});break;case"diag":e.code==="focus.print"&&(this.printed=!!e.data?.print,this._mode.mode!=="raw"&&this.setMode(this.activeMode())),this.diag({code:e.code,level:e.level,...e.data});break}}async setEnabled(e){return this.enabled=e,this.rt?.post({type:"set",input:this.id,enabled:e}),e?this.rt&&this._mode.reason==="off"&&this.setMode(this.activeMode()):this.setMode("raw","off"),e&&!!this.rt}listen(e){this.listening=e,this.rt?.post({type:"set",input:this.id,listen:e})}hold(){this.holding=!0,this.rt?.post({type:"set",input:this.id,hold:!0})}release(){this.holding=!1,this.rt?.post({type:"set",input:this.id,hold:!1})}setStrength(e){this.rt?.post({type:"set",input:this.id,strength:e}),this.opts.strength=e}setVoiceprint(e){let t=b(e);e&&!t&&this.diag({code:"voiceprint.reset",level:"warn",message:"This print comes from another Timbre: ignored, learn it again."}),this.opts.voiceprint=t,this.rt?.post({type:"set",input:this.id,print:t?.embedding??null}),this.opts.learn&&this.bg?.call("learner",[this.id,t?.toJSON()??null])}forgetVoiceprint(){this._voiceprint=null,this.rt?.post({type:"set",input:this.id,print:null}),this.bg?.call("forget",[this.id])}farEndActive(e){this.node?.port.postMessage({type:"far",on:e})}async stats(){return this.rt?this.rt.call("stats",[this.id]):null}async record(e){if(!this.rt)throw new p("engine.failed","The models are not running yet.");let t=await this.rt.call("record",[this.id,e]);return new Blob([t],{type:"audio/wav"})}async recent(){let e=this.rt?await this.rt.call("recent",[this.id]):null;return e?new Blob([e],{type:"audio/wav"}):null}async resume(){try{await Promise.race([this.ctx.resume(),new Promise(e=>setTimeout(e,300))])}catch{}this.setStatus(this.ctx.state==="running"?"running":this.ctx.state==="interrupted"?"interrupted":"blocked")}watchContext(){let e=this.ctx,t=()=>{if(this.disposed)return;let a=e.state;a==="running"?this.setStatus("running"):a==="interrupted"?this.setStatus("interrupted"):a==="suspended"&&e.resume().then(()=>this.setStatus(e.state==="running"?"running":"blocked"),()=>this.setStatus("blocked"))};e.addEventListener("statechange",t),this.offs.push(()=>e.removeEventListener("statechange",t));let s=e.currentTime,i=performance.now(),n=0,l=setInterval(()=>{let a=performance.now(),c=(e.currentTime-s)*1e3,d=a-i;s=e.currentTime,i=a,n=e.state!=="running"||c<.9*d?n||a:0;let h=!!n&&a-n>=Ie;if(h!==this.stalled){this.stalled=h,this.diag({code:h?"audio.stalled":"audio.resumed",level:h?"warn":"info"});let w=this.track;w&&(this.sender?this.sender.replaceTrack(w):this.emit("trackchange",w))}},500);this.offs.push(()=>clearInterval(l))}bind(e){this.sender=e;let t=this.track;t&&e.track!==t&&e.replaceTrack(t)}watchTrack(e){let t=()=>void this.onTrackEnded(),s=()=>this.emit("mic",{state:"muted"}),i=()=>this.emit("mic",{state:"unmuted"});e.addEventListener("ended",t),e.addEventListener("mute",s),e.addEventListener("unmute",i),this.offs.push(()=>{e.removeEventListener("ended",t),e.removeEventListener("mute",s),e.removeEventListener("unmute",i)})}reopenMs=L;async onTrackEnded(){if(!this.disposed&&(this.emit("mic",{state:"lost"}),!!this.ownStream))try{let e=this.browserWant;await this.setStream(await x(this.opts.deviceId,void 0,e),!0),this.browserHas=e,this.reopenMs=L,this.emit("mic",{state:"reopened"})}catch(e){if(e.code==="mic.denied"){this.emit("mic",{state:"denied"});return}setTimeout(()=>void this.onTrackEnded(),this.reopenMs),this.reopenMs=Math.min(2*this.reopenMs,G)}}async setStream(e,t=!1){if(this.ownStream)for(let i of this.stream.getTracks())i!==e.getAudioTracks()[0]&&i.stop();this.source.disconnect(),this.stream=e,this.ownStream=t,this.source=this.ctx.createMediaStreamSource(e),this.source.connect(this.node,0,0);let s=e.getAudioTracks()[0];s&&this.watchTrack(s)}async setDevice(e){this.opts.deviceId=e,this.opts.followDefault=!1;let t=this.browserWant;await this.setStream(await x(e,void 0,t),!0),this.browserHas=t}followDefault(){let e=navigator.mediaDevices;if(!e?.addEventListener)return;let t=this.stream.getAudioTracks()[0]?.getSettings().groupId,s=async()=>{if(this.opts.followDefault===!1||this.disposed)return;let n=(await e.enumerateDevices().catch(()=>[])).find(l=>l.kind==="audioinput"&&l.deviceId==="default");if(n&&n.groupId&&n.groupId!==t){t=n.groupId;let l=this.browserWant;await this.setStream(await x(void 0,void 0,l),!0).then(()=>void(this.browserHas=l)).catch(()=>{}),this.emit("mic",{state:"reopened"})}};e.addEventListener("devicechange",s),this.offs.push(()=>e.removeEventListener("devicechange",s))}async restart({track:e,audioContext:t}={}){let s=this.track;if(t&&t!==this.ctx){if(this.teardownGraph(),this.ownCtx&&this.ctx.close().catch(()=>{}),this.ctx=t,this.ownCtx=!1,e){if(this.ownStream)for(let n of this.stream.getTracks())n.stop();this.stream=new MediaStream([e]),this.ownStream=!1}await this.build(),this.watchContext(),this.rt?.post({type:"dispose",input:this.id}),this.rt=null,this.startModels()}else e&&await this.setStream(new MediaStream([e]));let i=this.track;i&&i!==s&&this.emit("trackchange",i)}teardownGraph(){this.node?.port.postMessage({type:"dispose"});for(let e of[this.source,this.node,this.dest,this.farSource])e?.disconnect()}spot(e,t={}){if(this.kind==="wake")throw new TypeError("spot() reads Focus: use the wake listener itself");return t.onlyMyVoice&&!b(this.opts.voiceprint)&&!this.opts.learn&&this.diag({code:"spot.no-print",level:"warn",message:"onlyMyVoice relies on this input's print: give it a voiceprint (or learn: true), else the closest voice wakes it."}),new q(this,e.map(s=>k(s).toJSON()),t.context??"anywhere")}enrollWord(e,t={}){return new P({compile:async()=>(await import("./api-OCT4ZIYY.js")).Spot.compile(e,{lang:t.lang,chain:"focus"}),open:async s=>{await this.running;let i=await y.get().models("realtime",["spot"]);return i.post({type:"set",input:this.id,enroll:{word:s,takes:t.takes??3}}),{on:this.on.bind(this),stop:()=>i.post({type:"set",input:this.id,enroll:null}),source:"focus"}},embed:async(s,i)=>(await(await import("./api-OCT4ZIYY.js")).Timbre.create()).embed(s,{source:i})})}setWords(e,t){this.spotWords={words:e,context:t},this.rt&&y.get().models("realtime",["spot"]).then(s=>s.post({type:"set",input:this.id,words:e,context:t}))}dispose(){if(!this.disposed){clearTimeout(this.retryTimer),clearTimeout(this.browserTimer),this.setStatus("disposed"),this.settle(new p("engine.failed","The input was disposed before its models ran."),!0),this.counted&&--we===0&&y.get().idle();for(let e of this.offs)e();if(this.offs=[],this.rt?.post({type:"dispose",input:this.id}),this.bg?.post({type:"dispose",input:this.id}),this.teardownGraph(),this.ownStream)for(let e of this.stream.getTracks())e.stop();this.ownCtx&&this.ctx.close().catch(()=>{}),$.delete(this),this.clear()}}},z=class extends O{constructor(e){super(e);this.opts=e}kind="call";osc=null;get track(){return super.track}get delay16(){return B.lag+.1*f}models(){return["focus","cue"]}chainOptions(){let e=b(this.opts.voiceprint);return{gate:!0,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near}}realtimeOptions(){return{pipeline:"call",chain:this.chainOptions(),learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats}}async start(){if(this.opts.learn&&!this.opts.farEnd&&this.diag({code:"learn.no-far-end",level:"warn",message:"learn without farEnd: the other voice may get into the print."}),await this.open(),this.opts.keepAliveWhenHidden!==!1){this.osc=this.ctx.createOscillator(),this.osc.frequency.value=Le;let e=this.ctx.createGain();e.gain.value=Fe,this.osc.connect(e).connect(this.ctx.destination),this.osc.start(),this.offs.push(()=>this.osc?.stop())}return this}},q=class extends M{constructor(e,t,s){super();this.input=e;e.setWords(t,s),this.off=e.on("wake",i=>this.emit("wake",i))}off;dispose(){this.off(),this.input.setWords([],"anywhere"),this.clear()}};function Mt(o={}){return new z(o).start()}var X=class extends O{constructor(e){super(e);this.opts=e}kind="agent";packer=null;rawAudio(e){this.packer??=new I(this.output(),t=>{let s=this.appPort();s?s.postMessage({type:"audio",pcm:t},[t]):this.opts.output?.port||this.emit("audio",t)}),this.packer.push(e)}output(){let e=this.opts.output??{};return{format:e.format??"f32",rate:e.rate??f,chunkMs:Math.max(16,Math.round((e.chunkMs??32)/16)*16)}}get delay16(){return B.lag}models(){return["focus","cue"]}connectOutput(){if(this.opts.withTrack)return super.connectOutput();let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}realtimeOptions(){let e=b(this.opts.voiceprint);return{pipeline:"agent",chain:{gate:!1,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near},learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats,output:{...this.output(),audio:!0,utterance:!0}}}async start(){if(this.opts.learn&&!this.opts.farEnd)throw new TypeError("createAgentInput: learn needs farEnd (the agent's voice would teach the print)");if(this.opts.wake)throw new TypeError("createAgentInput: wake is reserved, not in this preview (use createWakeListener)");return await this.open(),this}};function At(o={}){return new X(o).start()}var Y=class extends O{constructor(e){super(e);this.opts=e;if(this.words=e.words.map(t=>k(t).toJSON()),!this.words.length)throw new TypeError("createWakeListener: no word");for(let t of this.words)t.chain==="focus"&&this.diag({code:"word.chain",level:"warn",message:`"${t.text}" was enrolled behind Focus: its thresholds are off on the raw microphone.`});e.onlyMyVoice&&!this.reference()&&this.diag({code:"voiceprint.reset",level:"warn",message:`onlyMyVoice: ${ge}`})}kind="wake";words;models(){return["spot"]}connectOutput(){let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}wantsBackground(){return!!this.reference()}reference(){return b(this.opts.onlyMyVoice)}realtimeOptions(){return{pipeline:"wake",words:this.words,context:this.opts.context??"pause",trace:this.opts.trace,verify:!!this.reference()}}async start(){return await this.open(),this}};function Pt(o){return new Y(o).start()}var Z=class extends O{constructor(e,t,s){super(e);this.opts=e;this.word=t;this.takes=s}kind="wake";models(){return["spot"]}connectOutput(){let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}realtimeOptions(){return{pipeline:"enroll",enroll:{word:this.word,takes:this.takes}}}async start(){return await this.open(),this}};function ve(o,r,e){return new Z(o,r,e).start()}var Ae=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",Pe=0,_e=null;async function A(o,r){if(Ae()){let t=await(_e??=import("./node-2NC6GL6J.js").then(s=>new s.NodeBackend));return await t.ready(o),{call:async(s,i,n,l)=>t.calls[s](...i,l),hold:()=>()=>{}}}let e=y.get();return await e.models("background",o,r),{call:async(t,s,i=[],n)=>(await e.models("background",o)).call(t,s,i,n),hold:()=>e.hold()}}function ye(o,r={}){let e=o==="wake"?["spot"]:["focus","cue"];return r.voiceprint&&e.push("timbre"),r.typedWords&&e.push("lex"),e}async function De(o){if("pcm"in o&&"rate"in o)return g.all(o.pcm,o.rate,f);if(typeof AudioBuffer<"u"&&o instanceof AudioBuffer)return g.all(be(o),o.sampleRate,f);let r=typeof Blob<"u"&&o instanceof Blob?new Uint8Array(await o.arrayBuffer()):o instanceof Uint8Array?o:new Uint8Array(o);if(String.fromCharCode(...r.subarray(0,4))==="RIFF"){let{pcm:s,rate:i}=he(r);return g.all(s,i,f)}if(typeof OfflineAudioContext>"u")throw new p("browser.unsupported","Outside a browser only WAV is decoded: decode the file and pass { pcm, rate }.");let t=await new OfflineAudioContext(1,1,44100).decodeAudioData(r.slice().buffer);return g.all(be(t),t.sampleRate,f)}function be(o){if(o.numberOfChannels===1)return o.getChannelData(0).slice();let r=new Float32Array(o.length);for(let e=0;e<o.numberOfChannels;e++){let t=o.getChannelData(e);for(let s=0;s<r.length;s++)r[s]+=t[s]/o.numberOfChannels}return r}var _t={configure:ne,stream:Je,supported:T,micPermission:me,onDiag:R,async preload(o,r={}){let e=ye(o,r);if(Ae()){await A(e);return}let t=y.get(),s=e.filter(a=>a!=="timbre"&&a!=="lex"),i=e.filter(a=>a==="timbre"||a==="lex"),n=[{loaded:0,total:0},{loaded:0,total:0}],l=a=>c=>{n[a]=c,r.onProgress?.({loaded:n[0].loaded+n[1].loaded,total:n[0].total+n[1].total})};await Promise.all([t.models("realtime",s,l(0)),i.length?t.models("background",i,l(1)):null])},async cached(o,r={}){let e=[E,...ye(o,r).map(t=>ee[t])];return(await Promise.all(e.map(le))).every(Boolean)},async process(o,r={}){let e=await De(o);r.signal?.throwIfAborted();let s=await(await A(Te(r))).call("process",[e,xe(r)],[],r.onProgress);return{...s,toWav(i="audio"){return pe(i==="both"?[s.raw,s.audio]:[i==="raw"?s.raw:s.audio],f)}}}};function Te(o){let r=[];return o.focus?r.push("focus","cue"):o.cue&&r.push("cue"),o.spot?.words.length&&r.push("spot"),r}function xe(o){let{onProgress:r,signal:e,...t}=o;return{...t,focus:typeof o.focus=="object"?{...o.focus,voiceprint:o.focus.voiceprint instanceof S?o.focus.voiceprint.toJSON():o.focus.voiceprint}:o.focus,spot:o.spot?{...o.spot,words:o.spot.words.map(s=>k(s).toJSON())}:void 0}}async function*Je(o,r={}){let e=await A(Te(r)),t=++Pe,s=e.hold();await e.call("streamOpen",[t,xe(r)]).catch(d=>{throw s(),d});let i=r.rate??f,n=new g(i,f,!0),l=0,a=0,c=Symbol.asyncIterator in o?o:Ue(o);try{for await(let h of c){r.signal?.throwIfAborted();let w=[];l+=h.length,n.push(h,F=>w.push(F)),a+=w.length,w.length&&(yield await e.call("streamPush",[t,Float32Array.from(w)]))}let d=[],u=Math.round(l*f/i)-a;u>0&&n.push(new Float32Array(g.HALF*2+8),h=>d.length<u&&d.push(h)),d.length&&(yield await e.call("streamPush",[t,Float32Array.from(d)]))}finally{try{yield await e.call("streamEnd",[t])}finally{s()}}}async function*Ue(o){let r=o.getReader();try{for(;;){let{done:e,value:t}=await r.read();if(e)return;yield t}}finally{r.releaseLock()}}var Q=class o{constructor(r){this.b=r}static async create(){return new o(await A(["timbre"]))}async embed(r,e={}){return S.fromJSON(await this.b.call("embed",[r,e.source??"raw"]))}verify(r,e,t={}){return D.verify(r,e,t)}async identify(r,e,t={}){let s=r instanceof S?r:await this.embed(r);return D.identify(s,e,t)}},ke=class o{constructor(r){this.b=r}static inventory=v.inventory;static langs=v.langs;static distance=v.distance;static async create(){return new o(await A(["lex"]))}async phonemize(r,e){if(!v.langs.includes(e))throw new p("lang.unsupported",`No ${e}: ${v.langs.join(", ")} only.`);let s=(await this.b.call("phonemize",[Array.isArray(r)?r:[r],e])).map(i=>i.map(({ipa:n,p:l})=>({ipa:n,p:l})));return Array.isArray(r)?s:s[0]}},He={async compile(o,r={}){for(let s of[r.lang??[]].flat())if(!v.langs.includes(s))throw new p("lang.unsupported",`No ${s}: ${v.langs.join(", ")} only.`);let e=/^\s*\/.+\/\s*$/.test(o),t=await A(e?[]:["lex"]);return k(await t.call("compile",[o,{lang:r.lang,chain:r.chain}]))},enroll(o,r={}){return new P({compile:()=>He.compile(o,r),open:async e=>{let t=await ve(r,e,r.takes??3);return{on:t.on.bind(t),stop:()=>t.dispose(),source:"raw"}},embed:async(e,t)=>(await Q.create()).embed(e,{source:t})})}},Se=o=>o?new S(o.centers,o.source,o.model,o.windows):null,je=o=>({alkove:"voiceprint",model:o.model,source:o.source,centers:o.centers,windows:o.windows}),Ge=typeof FinalizationRegistry>"u"?null:new FinalizationRegistry(o=>o()),Me=class o{constructor(r,e,t,s){this.b=r;this.id=e;this.state={progress:t.progress,ready:t.ready,voiceprint:Se(t.voiceprint)},Ge?.register(this,()=>void r.call("learnerClose",[e]).catch(()=>{}).finally(s))}state;static async create(r={}){let e=await A(["timbre"]),t=++Pe,s=e.hold();try{let i=await e.call("learnerOpen",[t,r.voiceprint?je(r.voiceprint):null]);return new o(e,t,i,s)}catch(i){throw s(),i}}get progress(){return this.state.progress}get ready(){return this.state.ready}get voiceprint(){return this.state.voiceprint}async offer(r){let e=await this.b.call("learnerOffer",[this.id,r]);return this.state={progress:e.progress,ready:e.ready,voiceprint:Se(e.voiceprint)},{accepted:e.accepted,rejected:e.rejected,progress:e.progress,ready:e.ready}}forget(){this.state={progress:0,ready:!1,voiceprint:null},this.b.call("learnerForget",[this.id])}};export{Mt as a,At as b,Pt as c,_t as d,Q as e,ke as f,He as g,Me as h};
1
+ import{A as he,B as b,a as E,b as f,c as ee,d as B,e as te,f as re,g as se,h as V,i as p,j as oe,k,l as ie,m as _,n as S,o as D,p as ne,q as W,r as ae,s as R,t as N,u as J,v as le,w as ce,x as de,z as pe}from"./chunk-CMAGZACJ.js";var v=class{static langs=te.langs;static inventory=re.map(r=>r.normalize("NFC"));static distance(r,e){let t=typeof r=="string"?V(r.replace(/^\/|\/$/g,""))??[]:r,s=typeof e=="string"?V(e.replace(/^\/|\/$/g,""))??[]:e;if(!t.length||!s.length)return t.length===s.length?0:1;let i=Array.from({length:s.length+1},(n,l)=>l);for(let n=1;n<=t.length;n++){let l=[n];for(let a=1;a<=s.length;a++){let c=t[n-1]===s[a-1]?0:se[t[n-1]-1].includes(s[a-1])?.5:1;l.push(Math.min(i[a]+1,l[a-1]+1,i[a-1]+c))}i=l}return i[s.length]/Math.max(t.length,s.length)}};var M=class{handlers=new Map;on(r,e){let t=this.handlers.get(r);return t||this.handlers.set(r,t=new Set),t.add(e),()=>void t.delete(e)}emit(r,e){for(let t of this.handlers.get(r)??[])try{t(e)}catch(s){queueMicrotask(()=>{throw s})}}listens(r){return!!this.handlers.get(r)?.size}clear(){this.handlers.clear()}};var P=class extends M{done;target=null;cancelled=!1;abort=null;constructor(r){super(),this.done=this.run(r),this.done.catch(()=>{})}async run(r){let e=await r.compile();for(let i of e.warnings)this.emit("warning",i);if(this.cancelled)throw new DOMException("cancelled","AbortError");let t=this.target=await r.open(e.toJSON()),s=[t.on("take",i=>this.emit("take",i))];try{let i=await new Promise((c,d)=>{s.push(t.on("enrolled",c)),this.abort=()=>d(new DOMException("cancelled","AbortError"))});if(i.error||!i.word)throw new p("engine.failed",i.error??"enrollment failed");for(let c of i.warnings??[])this.emit("warning",c);let n=i.audio&&i.audio.length>=4e3?await r.embed(i.audio,t.source):null,l=k(i.word);return{word:new oe(l.text,l.lang,l.phonemes,l.thresholds,l.calibrated,l.chain,[...e.warnings,...i.warnings??[]]),voiceprint:n}}finally{for(let i of s)i();t.stop()}}cancel(){this.cancelled=!0,this.abort?.(),this.target?.stop()}};var m=24,C=128,g=class o{constructor(r,e,t=!1){this.inRate=r;this.outRate=e;if(this.identity=r===e,t&&(this.t=m),this.identity)return;this.ratio=r/e;let s=this.half,i=.9/Math.max(1,this.ratio),n=new Float32Array((C+1)*m);for(let l=0;l<=C;l++){let a=l/C,c=0;for(let d=0;d<m;d++){let u=d-(s-1)-a,h=i*u,w=h===0?1:ie(Math.PI*h)/(Math.PI*h),F=.42+.5*_(Math.PI*u/s)+.08*_(2*Math.PI*u/s);n[l*m+d]=w*F,c+=n[l*m+d]}for(let d=0;d<m;d++)n[l*m+d]/=c}this.table=n}static HALF=m/2;identity;ratio=1;half=m/2;table=new Float32Array(0);work=new Float32Array(0);histLen=m;t=m/2;push(r,e){if(this.identity){for(let a=0;a<r.length;a++)e(r[a]);return}if(this.work.length<m+8+r.length){let a=new Float32Array(m+8+r.length);a.set(this.work.subarray(0,this.histLen)),this.work=a}let t=this.work;t.set(r,this.histLen);let s=this.histLen+r.length,i=s-1-this.half,n=this.t;for(;n<=i;){let a=Math.floor(n),c=Math.round((n-a)*C)*m,d=a-(this.half-1),u=0;for(let h=0;h<m;h++)u+=t[d+h]*this.table[c+h];e(u),n+=this.ratio}let l=Math.floor(n)-(this.half-1);t.copyWithin(0,l,s),this.histLen=s-l,this.t=n-l}static all(r,e,t){if(e===t)return r;let s=new o(e,t,!0),i=Math.round(r.length*t/e),n=new Float32Array(i),l=0,a=c=>{l<i&&(n[l++]=c)};return s.push(r,a),s.push(new Float32Array(Math.ceil(m*s.ratio)+16),a),n}};var I=class{constructor(r,e){this.opts=r;this.send=e;this.resampler=new g(f,r.rate),this.buf=new Float32Array(Math.round(r.rate*r.chunkMs/1e3))}resampler;buf;fill=0;push(r){this.resampler.push(r,e=>{this.buf[this.fill++]=e,this.fill===this.buf.length&&(this.send(Oe(this.buf,this.opts.format)),this.fill=0)})}};function Oe(o,r){if(r==="f32")return o.slice().buffer;let e=new Int16Array(o.length);for(let t=0;t<o.length;t++){let s=Math.max(-1,Math.min(1,o[t]));e[t]=s<0?s*32768:s*32767}return e.buffer}var U=class{constructor(r){this.worker=r;r.onmessage=e=>{let t=e.data;if(t?.type==="reply"){let s=this.replies.get(t.id);this.replies.delete(t.id),t.error?s?.reject(Object.assign(new Error(t.error.message),{code:t.error.code})):s?.resolve(t.result)}else if(t?.type==="progress")this.replies.get(t.id)?.progress?.(t.p);else for(let s of this.listeners)s(t)},r.onerror=e=>{for(let t of this.replies.values())t.reject(new p("engine.failed",e.message||"worker failed"));this.replies.clear();for(let t of this.listeners)t({type:"crash",message:e.message})}}next=1;replies=new Map;listeners=new Set;listen(r){return this.listeners.add(r),()=>void this.listeners.delete(r)}get busy(){return this.replies.size>0}request(r,e=[],t){let s=this.next++;return new Promise((i,n)=>{this.replies.set(s,{resolve:i,reject:n,progress:t}),this.worker.postMessage({...r,id:s,progress:!!t},e)})}call(r,e,t=[],s){return this.request({type:"call",method:r,args:e},t,s)}post(r,e=[]){this.worker.postMessage(r,e)}},Ee=null,We=()=>Ee??=import("./assets-VHBYP6JE.js");async function H(o){let r=W().assetBaseUrl;if(r)return J(r,`alkove-${o}.js`);let e=await We();return URL.createObjectURL(new Blob([o==="worker"?e.WORKER:e.WORKLET],{type:"text/javascript"}))}var ue=null;function Re(o){return ue??=(async()=>{let r=W().models?.engine,e=W().assetBaseUrl,t=r??(e?J(e,E.file):new URL("./alkove-engine.wasm",import.meta.url).href),s=await ce(E,o,t);return WebAssembly.compile(s)})().catch(r=>{throw ue=null,r})}var y=class o{static current=null;sent={realtime:new Set,background:new Set};links={};holds=0;static get(){return ae(),o.current??=new o}link(r){return this.links[r]??=(async()=>{let[e,t]=await Promise.all([Re(),H("worker")]),s=new U(new Worker(t,{type:"module",name:`alkove-${r}`})),i=this.links[r];return s.listen(n=>n.type==="crash"&&this.links[r]===i&&this.drop(r,s)),await new Promise((n,l)=>{let a=s.listen(c=>{c.type==="booted"?(a(),n()):c.type==="crash"&&l(new p("engine.failed",c.message))});s.post({type:"boot",module:e})}),s})().catch(e=>{throw delete this.links[r],e})}drop(r,e){delete this.links[r],this.sent[r].clear(),e.worker.terminate()}hold(){this.holds++;let r=!0;return()=>{r&&this.holds--,r=!1}}async idle(){for(let r of["realtime","background"]){let e=this.links[r],t=e&&await e.catch(()=>null);t&&this.links[r]===e&&(r==="realtime"||!t.busy&&!this.holds)&&this.drop(r,t)}}async models(r,e,t){let s=await this.link(r),i=e.filter(c=>!this.sent[r].has(c));if(!i.length)return s;let n=new Map,l=await Promise.all(i.map(c=>de(c,d=>{n.set(c,d);let u=0,h=0;for(let w of n.values())u+=w.loaded,h+=w.total;t?.({loaded:u,total:h})}))),a=Object.fromEntries(i.map((c,d)=>[c,l[d].slice().buffer]));await s.request({type:"models",models:a},Object.values(a));for(let c of i)this.sent[r].add(c);return s}static report=N};var Ne=5e3,Ce=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function T(){let o=globalThis,r=!1;try{r=typeof WebAssembly<"u"&&WebAssembly.validate(Ce)}catch{}return{worklet:typeof o.AudioWorkletNode=="function",simd:r,secure:o.isSecureContext!==!1}}async function me(){try{let o=await navigator.permissions.query({name:"microphone"});return o.state==="granted"||o.state==="denied"?o.state:"prompt"}catch{return"prompt"}}var j={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,voiceIsolation:!1,channelCount:1};async function x(o,r,e=!1){if(!T().secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!navigator.mediaDevices?.getUserMedia)throw new p("browser.unsupported","No getUserMedia in this browser.");let t=setTimeout(()=>N({code:"mic.waiting",level:"info",message:"The permission prompt has had no answer for 5 s."}),Ne);try{let s=e?{noiseSuppression:!0,autoGainControl:!0}:{},i=navigator.mediaDevices.getUserMedia({audio:{...j,...s,...o?{deviceId:{exact:o}}:{}}});return await(r?Promise.race([i,new Promise((l,a)=>{r.aborted&&a(r.reason),r.addEventListener("abort",()=>{i.then(c=>c.getTracks().forEach(d=>d.stop()),()=>{}),a(r.reason)})})]):i)}catch(s){if(r?.aborted)throw r.reason;let i=s?.name;throw i==="NotAllowedError"||i==="SecurityError"?new p("mic.denied","Microphone permission denied.",s):i==="NotFoundError"||i==="OverconstrainedError"?new p("mic.not-found","No microphone.",s):i==="NotReadableError"||i==="AbortError"?new p("mic.busy","The microphone is used by another app.",s):s}finally{clearTimeout(t)}}function fe(o){let r=o.getSettings();return["noiseSuppression","autoGainControl","voiceIsolation"].filter(e=>r[e]===!0)}var L=5e3,G=6e4,Ie=1500,Le=30,Fe=.002,Be=2e3,Ve=0,K=new WeakMap,$=new Set,we=0,ge="This print comes from another Timbre: ignored, learn it again.",O=class extends M{constructor(e){super();this.opts=e;this.running=new Promise(t=>this.markRunning=t)}id=++Ve;ctx;ownCtx=!1;stream;ownStream=!1;source;node;dest=null;farSource=null;rt=null;bg=null;offs=[];_mode={mode:"raw",reason:"loading"};_status="starting";_latency=0;_voiceprint=null;retryMs=L;retryTimer;started=0;counted=!1;enabled=!0;printed=!1;sender=null;stalled=!1;spotWords=null;running;markRunning;ran=!1;notReady=null;waiting=[];warned=new Set;browserWant=!1;browserHas=!1;browserBusy=Promise.resolve();browserTimer;listening=!0;holding=!1;get disposed(){return this._status==="disposed"}get mode(){return this._mode.mode}get status(){return this._status}get latency(){return this._latency}get voiceprint(){return this._voiceprint}get ready(){return this.ran?Promise.resolve():this.notReady?Promise.reject(this.notReady):new Promise((e,t)=>this.waiting.push([e,t]))}settle(e,t=!1){if(this.ran)return;this.ran=!e,t&&(this.notReady=e);let s=this.waiting;this.waiting=[];for(let[i,n]of s)e?n(e):i()}get track(){return this.stalled?this.stream.getAudioTracks()[0]??null:this.dest?.stream.getAudioTracks()[0]??null}now(){return this.ctx?this.ctx.currentTime-this.started:0}get delay16(){return 0}async open(){we++,this.counted=!0;try{await this.opening()}catch(e){throw this.dispose(),e}}async opening(){this.offs.push(R(i=>this.diag(i))),this.opts.voiceprint&&!b(this.opts.voiceprint)&&this.diag({code:"voiceprint.reset",level:"warn",message:ge});let e=T();if(!e.secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!e.worklet)throw new p("browser.unsupported","No AudioWorklet in this browser (Safari 14.1 or later).");let t=this.opts;t.stream||t.track?this.stream=t.stream??new MediaStream([t.track]):(this.stream=await x(t.deviceId,t.signal),this.ownStream=!0);let s=this.stream.getAudioTracks()[0];if(!s)throw new p("mic.not-found","The stream has no audio track.");if(!this.ownStream){let i=fe(s);i.length&&this.diag({code:"mic.processed",level:"warn",message:`The browser processes the stream before the models (${i.join(", ")}): open it with these off.`,settings:i})}for(let i of $)i.stream.getAudioTracks()[0]?.getSettings().deviceId===s.getSettings().deviceId&&i!==this&&this.diag({code:"mic.twice",level:"warn",message:"Two inputs on the same microphone run everything twice: use call.spot() for words on a call input."});t.audioContext?this.ctx=t.audioContext:(this.ctx=new AudioContext,this.ownCtx=!0),await this.build(),$.add(this),this.watchContext(),this.watchTrack(s),this.ownStream&&t.followDefault!==!1&&!t.deviceId&&this.followDefault(),this.startModels(),this.flushHeld()}async build(){let e=this.ctx,t=K.get(e);t||(t=H("worklet").then(i=>e.audioWorklet.addModule(i)),t.catch(()=>K.delete(e)),K.set(e,t)),await t,this.node=new AudioWorkletNode(e,"alkove",{numberOfInputs:2,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{delay16:this.delay16,tapRaw:this.kind==="agent"}}),this.node.port.onmessage=i=>this.onWorklet(i.data),this.source=e.createMediaStreamSource(this.stream),this.source.connect(this.node,0,0);let s=this.opts.farEnd;s&&s!=="manual"&&(this.farSource=s instanceof MediaStreamTrack?e.createMediaStreamSource(new MediaStream([s])):s,this.farSource.connect(this.node,0,1)),this.connectOutput(),this.started=e.currentTime,await this.resume()}connectOutput(){this.dest=this.ctx.createMediaStreamDestination(),this.node.connect(this.dest)}onWorklet(e){e.type==="overload"?(this.diag({code:"overload",level:"warn",message:"The device is too slow for the models: raw microphone for a while.",queueMs:e.queueMs,sent:e.sent,received:e.received}),this.setMode("raw","overload")):e.type==="retry"?this.setMode(this.activeMode()):e.type==="latency"?this._latency=Math.round(e.ms):e.type==="raw"?this.rawAudio(e.pcm):e.type==="timing"&&(this._latency=e.latencyMs,this.diag({code:"queue",level:"info",...e}))}rawAudio(e){}activeMode(){return this.enabled?this.kind==="wake"?this.reference()?"spot+print":"spot":this.printed?"focus+print":"focus":"raw"}held=[];emit(e,t){this.held?this.held.push([e,t]):this.deliver(e,t)}flushHeld(){setTimeout(()=>{let e=this.held??[];this.held=null;for(let[t,s]of e)this.deliver(t,s)},0)}deliver(e,t){if(super.emit(e,t),e!=="diag")return;let s=t;s.level!=="warn"||this.listens("diag")||this.warned.has(s.code)||(this.warned.add(s.code),console.warn(`alkove: ${s.message??s.code}`,s))}setMode(e,t){this._mode.mode===e&&this._mode.reason===t||(this._mode=t?{mode:e,reason:t}:{mode:e},this.emit("mode",this._mode),this.followRaw())}followRaw(){if(clearTimeout(this.browserTimer),!this.ownStream||this.disposed)return;this._mode.mode==="raw"&&this._mode.reason!=="off"?this.browserWant||(this.browserTimer=setTimeout(()=>this.wantBrowser(!0),Be)):this.wantBrowser(!1)}wantBrowser(e){this.browserWant=e,this.browserBusy=this.browserBusy.then(()=>this.browser())}async browser(){let e=this.browserWant,t=this.stream.getAudioTracks()[0];if(this.disposed||!this.ownStream||e===this.browserHas||!t)return;try{await t.applyConstraints({...j,noiseSuppression:e,autoGainControl:e})}catch{}let s=t.getSettings().noiseSuppression;if(typeof s=="boolean"&&s!==e){if(this.disposed||!this.ownStream)return;let n=t.getSettings().deviceId??this.opts.deviceId;t.stop();try{let l=await x(n,void 0,e);if(this.disposed||!this.ownStream){for(let a of l.getTracks())a.stop();return}await this.setStream(l,!0)}catch{this.onTrackEnded();return}}this.browserHas=e;let i=this.stream.getAudioTracks()[0]?.getSettings().noiseSuppression;this.diag({code:"mic.browser",level:"info",noiseSuppression:e,autoGainControl:e,applied:typeof i=="boolean"?i:null})}setStatus(e){this._status!==e&&(this._status=e,this.emit("status",e))}diag(e){this.emit("diag",e)}async startModels(){if(!this.disposed){if(!T().simd){this.diag({code:"engine.unsupported",level:"warn",message:"No WebAssembly SIMD: raw microphone for this session."}),this.setMode("raw","unsupported"),this.settle(new p("browser.unsupported","No WebAssembly SIMD: the models cannot run in this browser."),!0);return}this.setMode("raw","loading"),this.followRaw();try{let e=y.get(),t=await e.models("realtime",[...this.models(),...this.spotWords?.words.length?["spot"]:[]]),s;if(this.wantsBackground()){let a=await e.models("background",["timbre"]),c=new MessageChannel;a.post({type:"rt-port",input:this.id,port:c.port2,ref:this.reference()?.toJSON()??null},[c.port2]),s=c.port1,this.bg=a,this.offs.push(a.listen(u=>u.input===this.id&&u.type==="event"&&this.onEvent(u.event)));let d=b(this.opts.voiceprint);this.opts.learn&&await a.call("learner",[this.id,d?.toJSON()??null])}if(this.disposed)return;this.rt=t,this.offs.push(t.listen(a=>this.onRealtime(a)));let i=this.appPort(),n=[...s?[s]:[],...i?[i]:[]];i&&(this.portGiven=!0),await t.request({type:"realtime",input:this.id,opts:this.realtimeOptions(),bg:s,out:i},n),(!this.listening||this.holding)&&t.post({type:"set",input:this.id,...!this.listening&&{listen:!1},...this.holding&&{hold:!0}}),this.spotWords?.words.length&&(await e.models("realtime",["spot"]),t.post({type:"set",input:this.id,...this.spotWords})),this.markRunning(),this.settle(null);let l=new MessageChannel;t.post({type:"worklet",input:this.id,port:l.port2},[l.port2]),this.node.port.postMessage({type:"connect",port:l.port1},[l.port1]),this.printed=!!b(this.opts.voiceprint),this.retryMs=L,this.setMode(this.activeMode(),this.enabled?void 0:"off")}catch(e){if(this.disposed)return;this.diag({code:"models.failed",level:"warn",message:`Models not loaded, raw microphone; retry in ${this.retryMs/1e3} s.`,error:String(e?.message??e)}),this.setMode("raw","failed"),this.settle(e instanceof p?e:new p("engine.failed",`Models not loaded: ${String(e?.message??e)}`,e)),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,G)}}}portGiven=!1;appPort(){return this.portGiven?void 0:this.opts.output?.port}wantsBackground(){return!!this.opts.learn}reference(){return null}onRealtime(e){if(e.input===this.id)if(e.type==="events"){let t=[];for(let s of e.list)s.type==="trace"?t.push(s):this.onEvent(s);t.length&&this.emit("trace",t)}else e.type==="pcm"?e.kind==="audio"?this.emit("audio",e.pcm):this.emit("utterance",{pcm:e.pcm,start:e.start,end:e.end,...e.level&&{level:e.level}}):e.type==="crash"&&(this.node.port.postMessage({type:"stop"}),this.rt=null,this.diag({code:"engine.crash",level:"warn",message:`The engine stopped: raw microphone; retry in ${this.retryMs/1e3} s.`,error:e.message}),this.setMode("raw","failed"),clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,G))}onEvent(e){switch(e.type){case"speechstart":this.emit("speechstart",{start:e.start});break;case"speechcancel":this.emit("speechcancel",{start:e.start});break;case"speechend":this.emit("speechend",{start:e.start,end:e.end,..."voiceDb"in e&&{level:{voiceDb:e.voiceDb,noiseDb:e.noiseDb,refDb:e.refDb}}});break;case"wake":this.emit("wake",e);break;case"take":{let{type:t,...s}=e;this.emit("take",s);break}case"enrolled":{let{type:t,...s}=e;this.emit("enrolled",s);break}case"heard":this.emit("heard",{speech:e.speech,scores:e.scores});break;case"learn":this.emit("learn",{progress:e.progress});break;case"voiceprint":{let t=S.fromJSON(e.json);t&&(this._voiceprint=t,this.emit("voiceprint",t));break}case"idle":this.diag({code:"idle",level:"info",asleep:e.asleep,at:e.at});break;case"diag":e.code==="focus.print"&&(this.printed=!!e.data?.print,this._mode.mode!=="raw"&&this.setMode(this.activeMode())),this.diag({code:e.code,level:e.level,...e.data});break}}async setEnabled(e){return this.enabled=e,this.rt?.post({type:"set",input:this.id,enabled:e}),e?this.rt&&this._mode.reason==="off"&&this.setMode(this.activeMode()):this.setMode("raw","off"),e&&!!this.rt}listen(e){this.listening=e,this.rt?.post({type:"set",input:this.id,listen:e})}hold(){this.holding=!0,this.rt?.post({type:"set",input:this.id,hold:!0})}release(){this.holding=!1,this.rt?.post({type:"set",input:this.id,hold:!1})}setStrength(e){this.rt?.post({type:"set",input:this.id,strength:e}),this.opts.strength=e}setVoiceprint(e){let t=b(e);e&&!t&&this.diag({code:"voiceprint.reset",level:"warn",message:"This print comes from another Timbre: ignored, learn it again."}),this.opts.voiceprint=t,this.rt?.post({type:"set",input:this.id,print:t?.embedding??null}),this.opts.learn&&this.bg?.call("learner",[this.id,t?.toJSON()??null])}forgetVoiceprint(){this._voiceprint=null,this.rt?.post({type:"set",input:this.id,print:null}),this.bg?.call("forget",[this.id])}farEndActive(e){this.node?.port.postMessage({type:"far",on:e})}async stats(){return this.rt?this.rt.call("stats",[this.id]):null}async record(e){if(!this.rt)throw new p("engine.failed","The models are not running yet.");let t=await this.rt.call("record",[this.id,e]);return new Blob([t],{type:"audio/wav"})}async recent(){let e=this.rt?await this.rt.call("recent",[this.id]):null;return e?new Blob([e],{type:"audio/wav"}):null}async resume(){try{await Promise.race([this.ctx.resume(),new Promise(e=>setTimeout(e,300))])}catch{}this.setStatus(this.ctx.state==="running"?"running":this.ctx.state==="interrupted"?"interrupted":"blocked")}watchContext(){let e=this.ctx,t=()=>{if(this.disposed)return;let a=e.state;a==="running"?this.setStatus("running"):a==="interrupted"?this.setStatus("interrupted"):a==="suspended"&&e.resume().then(()=>this.setStatus(e.state==="running"?"running":"blocked"),()=>this.setStatus("blocked"))};e.addEventListener("statechange",t),this.offs.push(()=>e.removeEventListener("statechange",t));let s=e.currentTime,i=performance.now(),n=0,l=setInterval(()=>{let a=performance.now(),c=(e.currentTime-s)*1e3,d=a-i;s=e.currentTime,i=a,n=e.state!=="running"||c<.9*d?n||a:0;let h=!!n&&a-n>=Ie;if(h!==this.stalled){this.stalled=h,this.diag({code:h?"audio.stalled":"audio.resumed",level:h?"warn":"info"});let w=this.track;w&&(this.sender?this.sender.replaceTrack(w):this.emit("trackchange",w))}},500);this.offs.push(()=>clearInterval(l))}bind(e){this.sender=e;let t=this.track;t&&e.track!==t&&e.replaceTrack(t)}watchTrack(e){let t=()=>void this.onTrackEnded(),s=()=>this.emit("mic",{state:"muted"}),i=()=>this.emit("mic",{state:"unmuted"});e.addEventListener("ended",t),e.addEventListener("mute",s),e.addEventListener("unmute",i),this.offs.push(()=>{e.removeEventListener("ended",t),e.removeEventListener("mute",s),e.removeEventListener("unmute",i)})}reopenMs=L;async onTrackEnded(){if(!this.disposed&&(this.emit("mic",{state:"lost"}),!!this.ownStream))try{let e=this.browserWant;await this.setStream(await x(this.opts.deviceId,void 0,e),!0),this.browserHas=e,this.reopenMs=L,this.emit("mic",{state:"reopened"})}catch(e){if(e.code==="mic.denied"){this.emit("mic",{state:"denied"});return}setTimeout(()=>void this.onTrackEnded(),this.reopenMs),this.reopenMs=Math.min(2*this.reopenMs,G)}}async setStream(e,t=!1){if(this.ownStream)for(let i of this.stream.getTracks())i!==e.getAudioTracks()[0]&&i.stop();this.source.disconnect(),this.stream=e,this.ownStream=t,this.source=this.ctx.createMediaStreamSource(e),this.source.connect(this.node,0,0);let s=e.getAudioTracks()[0];s&&this.watchTrack(s)}async setDevice(e){this.opts.deviceId=e,this.opts.followDefault=!1;let t=this.browserWant;await this.setStream(await x(e,void 0,t),!0),this.browserHas=t}followDefault(){let e=navigator.mediaDevices;if(!e?.addEventListener)return;let t=this.stream.getAudioTracks()[0]?.getSettings().groupId,s=async()=>{if(this.opts.followDefault===!1||this.disposed)return;let n=(await e.enumerateDevices().catch(()=>[])).find(l=>l.kind==="audioinput"&&l.deviceId==="default");if(n&&n.groupId&&n.groupId!==t){t=n.groupId;let l=this.browserWant;await this.setStream(await x(void 0,void 0,l),!0).then(()=>void(this.browserHas=l)).catch(()=>{}),this.emit("mic",{state:"reopened"})}};e.addEventListener("devicechange",s),this.offs.push(()=>e.removeEventListener("devicechange",s))}async restart({track:e,audioContext:t}={}){let s=this.track;if(t&&t!==this.ctx){if(this.teardownGraph(),this.ownCtx&&this.ctx.close().catch(()=>{}),this.ctx=t,this.ownCtx=!1,e){if(this.ownStream)for(let n of this.stream.getTracks())n.stop();this.stream=new MediaStream([e]),this.ownStream=!1}await this.build(),this.watchContext(),this.rt?.post({type:"dispose",input:this.id}),this.rt=null,this.startModels()}else e&&await this.setStream(new MediaStream([e]));let i=this.track;i&&i!==s&&this.emit("trackchange",i)}teardownGraph(){this.node?.port.postMessage({type:"dispose"});for(let e of[this.source,this.node,this.dest,this.farSource])e?.disconnect()}spot(e,t={}){if(this.kind==="wake")throw new TypeError("spot() reads Focus: use the wake listener itself");return t.onlyMyVoice&&!b(this.opts.voiceprint)&&!this.opts.learn&&this.diag({code:"spot.no-print",level:"warn",message:"onlyMyVoice relies on this input's print: give it a voiceprint (or learn: true), else the closest voice wakes it."}),new q(this,e.map(s=>k(s).toJSON()),t.context??"anywhere")}enrollWord(e,t={}){return new P({compile:async()=>(await import("./api-BG2ZH7Z5.js")).Spot.compile(e,{lang:t.lang,chain:"focus"}),open:async s=>{await this.running;let i=await y.get().models("realtime",["spot"]);return i.post({type:"set",input:this.id,enroll:{word:s,takes:t.takes??3}}),{on:this.on.bind(this),stop:()=>i.post({type:"set",input:this.id,enroll:null}),source:"focus"}},embed:async(s,i)=>(await(await import("./api-BG2ZH7Z5.js")).Timbre.create()).embed(s,{source:i})})}setWords(e,t){this.spotWords={words:e,context:t},this.rt&&y.get().models("realtime",["spot"]).then(s=>s.post({type:"set",input:this.id,words:e,context:t}))}dispose(){if(!this.disposed){clearTimeout(this.retryTimer),clearTimeout(this.browserTimer),this.setStatus("disposed"),this.settle(new p("engine.failed","The input was disposed before its models ran."),!0),this.counted&&--we===0&&y.get().idle();for(let e of this.offs)e();if(this.offs=[],this.rt?.post({type:"dispose",input:this.id}),this.bg?.post({type:"dispose",input:this.id}),this.teardownGraph(),this.ownStream)for(let e of this.stream.getTracks())e.stop();this.ownCtx&&this.ctx.close().catch(()=>{}),$.delete(this),this.clear()}}},z=class extends O{constructor(e){super(e);this.opts=e}kind="call";osc=null;get track(){return super.track}get delay16(){return B.lag+.1*f}models(){return["focus","cue"]}chainOptions(){let e=b(this.opts.voiceprint);return{gate:!0,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near}}realtimeOptions(){return{pipeline:"call",chain:this.chainOptions(),learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats}}async start(){if(this.opts.learn&&!this.opts.farEnd&&this.diag({code:"learn.no-far-end",level:"warn",message:"learn without farEnd: the other voice may get into the print."}),await this.open(),this.opts.keepAliveWhenHidden!==!1){this.osc=this.ctx.createOscillator(),this.osc.frequency.value=Le;let e=this.ctx.createGain();e.gain.value=Fe,this.osc.connect(e).connect(this.ctx.destination),this.osc.start(),this.offs.push(()=>this.osc?.stop())}return this}},q=class extends M{constructor(e,t,s){super();this.input=e;e.setWords(t,s),this.off=e.on("wake",i=>this.emit("wake",i))}off;dispose(){this.off(),this.input.setWords([],"anywhere"),this.clear()}};function Mt(o={}){return new z(o).start()}var X=class extends O{constructor(e){super(e);this.opts=e}kind="agent";packer=null;rawAudio(e){this.packer??=new I(this.output(),t=>{let s=this.appPort();s?s.postMessage({type:"audio",pcm:t},[t]):this.opts.output?.port||this.emit("audio",t)}),this.packer.push(e)}output(){let e=this.opts.output??{};return{format:e.format??"f32",rate:e.rate??f,chunkMs:Math.max(16,Math.round((e.chunkMs??32)/16)*16)}}get delay16(){return B.lag}models(){return["focus","cue"]}connectOutput(){if(this.opts.withTrack)return super.connectOutput();let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}realtimeOptions(){let e=b(this.opts.voiceprint);return{pipeline:"agent",chain:{gate:!1,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near},learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats,output:{...this.output(),audio:!0,utterance:!0}}}async start(){if(this.opts.learn&&!this.opts.farEnd)throw new TypeError("createAgentInput: learn needs farEnd (the agent's voice would teach the print)");if(this.opts.wake)throw new TypeError("createAgentInput: wake is reserved, not in this preview (use createWakeListener)");return await this.open(),this}};function At(o={}){return new X(o).start()}var Y=class extends O{constructor(e){super(e);this.opts=e;if(this.words=e.words.map(t=>k(t).toJSON()),!this.words.length)throw new TypeError("createWakeListener: no word");for(let t of this.words)t.chain==="focus"&&this.diag({code:"word.chain",level:"warn",message:`"${t.text}" was enrolled behind Focus: its thresholds are off on the raw microphone.`});e.onlyMyVoice&&!this.reference()&&this.diag({code:"voiceprint.reset",level:"warn",message:`onlyMyVoice: ${ge}`})}kind="wake";words;models(){return["spot"]}connectOutput(){let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}wantsBackground(){return!!this.reference()}reference(){return b(this.opts.onlyMyVoice)}realtimeOptions(){return{pipeline:"wake",words:this.words,context:this.opts.context??"pause",trace:this.opts.trace,verify:!!this.reference()}}async start(){return await this.open(),this}};function Pt(o){return new Y(o).start()}var Z=class extends O{constructor(e,t,s){super(e);this.opts=e;this.word=t;this.takes=s}kind="wake";models(){return["spot"]}connectOutput(){let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}realtimeOptions(){return{pipeline:"enroll",enroll:{word:this.word,takes:this.takes}}}async start(){return await this.open(),this}};function ve(o,r,e){return new Z(o,r,e).start()}var Ae=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",Pe=0,_e=null;async function A(o,r){if(Ae()){let t=await(_e??=import("./node-RMGH6RRH.js").then(s=>new s.NodeBackend));return await t.ready(o),{call:async(s,i,n,l)=>t.calls[s](...i,l),hold:()=>()=>{}}}let e=y.get();return await e.models("background",o,r),{call:async(t,s,i=[],n)=>(await e.models("background",o)).call(t,s,i,n),hold:()=>e.hold()}}function ye(o,r={}){let e=o==="wake"?["spot"]:["focus","cue"];return r.voiceprint&&e.push("timbre"),r.typedWords&&e.push("lex"),e}async function De(o){if("pcm"in o&&"rate"in o)return g.all(o.pcm,o.rate,f);if(typeof AudioBuffer<"u"&&o instanceof AudioBuffer)return g.all(be(o),o.sampleRate,f);let r=typeof Blob<"u"&&o instanceof Blob?new Uint8Array(await o.arrayBuffer()):o instanceof Uint8Array?o:new Uint8Array(o);if(String.fromCharCode(...r.subarray(0,4))==="RIFF"){let{pcm:s,rate:i}=he(r);return g.all(s,i,f)}if(typeof OfflineAudioContext>"u")throw new p("browser.unsupported","Outside a browser only WAV is decoded: decode the file and pass { pcm, rate }.");let t=await new OfflineAudioContext(1,1,44100).decodeAudioData(r.slice().buffer);return g.all(be(t),t.sampleRate,f)}function be(o){if(o.numberOfChannels===1)return o.getChannelData(0).slice();let r=new Float32Array(o.length);for(let e=0;e<o.numberOfChannels;e++){let t=o.getChannelData(e);for(let s=0;s<r.length;s++)r[s]+=t[s]/o.numberOfChannels}return r}var _t={configure:ne,stream:Je,supported:T,micPermission:me,onDiag:R,async preload(o,r={}){let e=ye(o,r);if(Ae()){await A(e);return}let t=y.get(),s=e.filter(a=>a!=="timbre"&&a!=="lex"),i=e.filter(a=>a==="timbre"||a==="lex"),n=[{loaded:0,total:0},{loaded:0,total:0}],l=a=>c=>{n[a]=c,r.onProgress?.({loaded:n[0].loaded+n[1].loaded,total:n[0].total+n[1].total})};await Promise.all([t.models("realtime",s,l(0)),i.length?t.models("background",i,l(1)):null])},async cached(o,r={}){let e=[E,...ye(o,r).map(t=>ee[t])];return(await Promise.all(e.map(le))).every(Boolean)},async process(o,r={}){let e=await De(o);r.signal?.throwIfAborted();let s=await(await A(Te(r))).call("process",[e,xe(r)],[],r.onProgress);return{...s,toWav(i="audio"){return pe(i==="both"?[s.raw,s.audio]:[i==="raw"?s.raw:s.audio],f)}}}};function Te(o){let r=[];return o.focus?r.push("focus","cue"):o.cue&&r.push("cue"),o.spot?.words.length&&r.push("spot"),r}function xe(o){let{onProgress:r,signal:e,...t}=o;return{...t,focus:typeof o.focus=="object"?{...o.focus,voiceprint:o.focus.voiceprint instanceof S?o.focus.voiceprint.toJSON():o.focus.voiceprint}:o.focus,spot:o.spot?{...o.spot,words:o.spot.words.map(s=>k(s).toJSON())}:void 0}}async function*Je(o,r={}){let e=await A(Te(r)),t=++Pe,s=e.hold();await e.call("streamOpen",[t,xe(r)]).catch(d=>{throw s(),d});let i=r.rate??f,n=new g(i,f,!0),l=0,a=0,c=Symbol.asyncIterator in o?o:Ue(o);try{for await(let h of c){r.signal?.throwIfAborted();let w=[];l+=h.length,n.push(h,F=>w.push(F)),a+=w.length,w.length&&(yield await e.call("streamPush",[t,Float32Array.from(w)]))}let d=[],u=Math.round(l*f/i)-a;u>0&&n.push(new Float32Array(g.HALF*2+8),h=>d.length<u&&d.push(h)),d.length&&(yield await e.call("streamPush",[t,Float32Array.from(d)]))}finally{try{yield await e.call("streamEnd",[t])}finally{s()}}}async function*Ue(o){let r=o.getReader();try{for(;;){let{done:e,value:t}=await r.read();if(e)return;yield t}}finally{r.releaseLock()}}var Q=class o{constructor(r){this.b=r}static async create(){return new o(await A(["timbre"]))}async embed(r,e={}){return S.fromJSON(await this.b.call("embed",[r,e.source??"raw"]))}verify(r,e,t={}){return D.verify(r,e,t)}async identify(r,e,t={}){let s=r instanceof S?r:await this.embed(r);return D.identify(s,e,t)}},ke=class o{constructor(r){this.b=r}static inventory=v.inventory;static langs=v.langs;static distance=v.distance;static async create(){return new o(await A(["lex"]))}async phonemize(r,e){if(!v.langs.includes(e))throw new p("lang.unsupported",`No ${e}: ${v.langs.join(", ")} only.`);let s=(await this.b.call("phonemize",[Array.isArray(r)?r:[r],e])).map(i=>i.map(({ipa:n,p:l})=>({ipa:n,p:l})));return Array.isArray(r)?s:s[0]}},He={async compile(o,r={}){for(let s of[r.lang??[]].flat())if(!v.langs.includes(s))throw new p("lang.unsupported",`No ${s}: ${v.langs.join(", ")} only.`);let e=/^\s*\/.+\/\s*$/.test(o),t=await A(e?[]:["lex"]);return k(await t.call("compile",[o,{lang:r.lang,chain:r.chain}]))},enroll(o,r={}){return new P({compile:()=>He.compile(o,r),open:async e=>{let t=await ve(r,e,r.takes??3);return{on:t.on.bind(t),stop:()=>t.dispose(),source:"raw"}},embed:async(e,t)=>(await Q.create()).embed(e,{source:t})})}},Se=o=>o?new S(o.centers,o.source,o.model,o.windows):null,je=o=>({alkove:"voiceprint",model:o.model,source:o.source,centers:o.centers,windows:o.windows}),Ge=typeof FinalizationRegistry>"u"?null:new FinalizationRegistry(o=>o()),Me=class o{constructor(r,e,t,s){this.b=r;this.id=e;this.state={progress:t.progress,ready:t.ready,voiceprint:Se(t.voiceprint)},Ge?.register(this,()=>void r.call("learnerClose",[e]).catch(()=>{}).finally(s))}state;static async create(r={}){let e=await A(["timbre"]),t=++Pe,s=e.hold();try{let i=await e.call("learnerOpen",[t,r.voiceprint?je(r.voiceprint):null]);return new o(e,t,i,s)}catch(i){throw s(),i}}get progress(){return this.state.progress}get ready(){return this.state.ready}get voiceprint(){return this.state.voiceprint}async offer(r){let e=await this.b.call("learnerOffer",[this.id,r]);return this.state={progress:e.progress,ready:e.ready,voiceprint:Se(e.voiceprint)},{accepted:e.accepted,rejected:e.rejected,progress:e.progress,ready:e.ready}}forget(){this.state={progress:0,ready:!1,voiceprint:null},this.b.call("learnerForget",[this.id])}};export{Mt as a,At as b,Pt as c,_t as d,Q as e,ke as f,He as g,Me as h};
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{copyFile as T,mkdir as G,writeFile as I}from"node:fs/promises";import{dirname as W,join as w}from"node:path";import{fileURLToPath as J}from"node:url";var d=class extends Error{constructor(r,t,a){super(t);this.code=r;this.cause=a}name="AlkoveError"};var p="alkove-ai",k={focus:{name:"alkove-focus-1-preview",file:"alkove-focus-1-preview.alk",bytes:1111696,sha256:"a63cda32e023b8d76089f4c3df0cc2c69ba36017b8f6cdea1da1094ef8022b6a",revision:"8e91ef608366cf503fbd8aaa44bc2000dce899ed"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1066516,sha256:"977cd614996498f468536effbc2fb05138331751ca21572cf07b24184b4e7911",revision:"49e90fcff90dc6e6c47fa6e990e810bd628af4b3"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1-preview",file:"alkove-timbre-1-preview.alk",bytes:739632,sha256:"d498a7dd8b20528d783052b1e1d49e54ab7ee4e47aa12712d04f3d43edc68bd8",revision:"013f7c621e8687e992508b5fb01607eb17143550"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var u={name:"alkove-engine",file:"alkove-engine.wasm",bytes:484109,sha256:"c22e900af5f401b29689b3b882f7245feefe4dea617ffdb3046a1d4f5771e543"};var i=k;var N=e=>`${i[e].name}@${i[e].sha256.slice(0,12)}`,V={model:N("timbre"),window:24e3,min:280,dim:192};var P="alkove",g="https://cache.alkove.invalid/",R=30,f={},O=!1,x=new Set;function M(e){O&&E({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),f={...f,...e}}var U=new Set;function E(e){for(let o of x)o(e);x.size||e.level!=="warn"||U.has(e.code)||(U.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function C(e){let o=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(o),r=>r.toString(16).padStart(2,"0")).join("")}var $=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",B=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function D(e,o){let r=globalThis.location?.href;return new URL(o,new URL(String(e).replace(/\/?$/,"/"),r)).href}function A(e){if(f.modelBaseUrl)return D(f.modelBaseUrl,e.file);if(!e.revision)throw new d("models.fetch",`${e.name}: not on Hugging Face in this version, set modelBaseUrl`);return E({code:"models.default-host",level:"warn",message:`${e.name} comes from Hugging Face: each user sends it their IP. Self-host the models in production (modelBaseUrl).`}),`https://huggingface.co/${p}/${e.name}/resolve/${e.revision}/${e.file}`}async function L(e,o,r=0){let t;try{t=await fetch(e)}catch(l){throw new d("models.fetch",`fetch failed: ${e}`,l)}if(!t.ok||!t.body)throw new d("models.fetch",`HTTP ${t.status}: ${e}`);let a=Number(t.headers.get("content-length"))||r,s=t.body.getReader(),n=[],c=0;for(;;){let{done:l,value:b}=await s.read();if(l)break;n.push(b),c+=b.length,o?.({loaded:c,total:Math.max(a,c)})}let y=new Uint8Array(c),v=0;for(let l of n)y.set(l,v),v+=l.length;return y}async function m(e,o){let r=await C(o);if(r!==e.sha256)throw new d("models.hash",`${e.name}: sha256 ${r}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return o}async function h(e,o,r){return o instanceof ArrayBuffer?m(e,new Uint8Array(o)):o instanceof Uint8Array?m(e,o):m(e,await L(String(o),r,e.bytes))}async function j(e,o){if(!B())return o();let r;try{r=await caches.open(P)}catch{return o()}let t=g+e.sha256,a=await r.match(t).catch(()=>{});if(a){let n=new Uint8Array(await a.arrayBuffer());if(await C(n)===e.sha256)return S(r,e.sha256),n;await r.delete(t).catch(()=>{})}let s=await o();return await r.put(t,new Response(s,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),S(r,e.sha256),s}async function S(e,o){try{let r=g+"used.json",t=await(await e.match(r))?.json().catch(()=>null)??{},a=Date.now();t[o]=a;for(let[s,n]of Object.entries(t))a-n>R*864e5&&(await e.delete(g+s),delete t[s]);await e.put(r,new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}}))}catch{}}var H=e=>Object.entries(i).find(([,o])=>o===e)?.[0]??"engine";async function _(e,o,r){let t=f.models?.[H(e)]??r;if(t instanceof ArrayBuffer||t instanceof Uint8Array)return h(e,t);if($()){if(t&&String(t).startsWith("file:")){let{readFile:a}=await import("node:fs/promises");return m(e,new Uint8Array(await a(new URL(String(t)))))}if(f.modelDir){let{readFile:a}=await import("node:fs/promises"),{join:s}=await import("node:path");return m(e,new Uint8Array(await a(s(f.modelDir,e.file))))}return h(e,t??A(e),o)}return j(e,()=>h(e,t??A(e),o))}function F(e,o){return _(i[e],o)}var z=`alkove models <dir> [focus cue spot timbre lex]
2
+ import{copyFile as T,mkdir as G,writeFile as I}from"node:fs/promises";import{dirname as W,join as w}from"node:path";import{fileURLToPath as J}from"node:url";var d=class extends Error{constructor(r,t,a){super(t);this.code=r;this.cause=a}name="AlkoveError"};var p="alkove-ai",k={focus:{name:"alkove-focus-1-preview",file:"alkove-focus-1-preview.alk",bytes:1111696,sha256:"a63cda32e023b8d76089f4c3df0cc2c69ba36017b8f6cdea1da1094ef8022b6a",revision:"8e91ef608366cf503fbd8aaa44bc2000dce899ed"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1066516,sha256:"977cd614996498f468536effbc2fb05138331751ca21572cf07b24184b4e7911",revision:"49e90fcff90dc6e6c47fa6e990e810bd628af4b3"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1-preview",file:"alkove-timbre-1-preview.alk",bytes:739632,sha256:"d498a7dd8b20528d783052b1e1d49e54ab7ee4e47aa12712d04f3d43edc68bd8",revision:"013f7c621e8687e992508b5fb01607eb17143550"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var u={name:"alkove-engine",file:"alkove-engine.wasm",bytes:488297,sha256:"239e24fe8293b36f6059b569d59d3ee7c2b2bfee562bd37fa33e71686ea33a1f"};var i=k;var N=e=>`${i[e].name}@${i[e].sha256.slice(0,12)}`,V={model:N("timbre"),window:24e3,min:280,dim:192};var P="alkove",g="https://cache.alkove.invalid/",R=30,l={},O=!1,x=new Set;function M(e){O&&E({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),l={...l,...e}}var U=new Set;function E(e){for(let o of x)o(e);x.size||e.level!=="warn"||U.has(e.code)||(U.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function C(e){let o=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(o),r=>r.toString(16).padStart(2,"0")).join("")}var $=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",B=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function D(e,o){let r=globalThis.location?.href;return new URL(o,new URL(String(e).replace(/\/?$/,"/"),r)).href}function A(e){if(l.modelBaseUrl)return D(l.modelBaseUrl,e.file);if(!e.revision)throw new d("models.fetch",`${e.name}: not on Hugging Face in this version, set modelBaseUrl`);return E({code:"models.default-host",level:"warn",message:`${e.name} comes from Hugging Face: each user sends it their IP. Self-host the models in production (modelBaseUrl).`}),`https://huggingface.co/${p}/${e.name}/resolve/${e.revision}/${e.file}`}async function L(e,o,r=0){let t;try{t=await fetch(e)}catch(f){throw new d("models.fetch",`fetch failed: ${e}`,f)}if(!t.ok||!t.body)throw new d("models.fetch",`HTTP ${t.status}: ${e}`);let a=Number(t.headers.get("content-length"))||r,s=t.body.getReader(),n=[],c=0;for(;;){let{done:f,value:b}=await s.read();if(f)break;n.push(b),c+=b.length,o?.({loaded:c,total:Math.max(a,c)})}let y=new Uint8Array(c),v=0;for(let f of n)y.set(f,v),v+=f.length;return y}async function m(e,o){let r=await C(o);if(r!==e.sha256)throw new d("models.hash",`${e.name}: sha256 ${r}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return o}async function h(e,o,r){return o instanceof ArrayBuffer?m(e,new Uint8Array(o)):o instanceof Uint8Array?m(e,o):m(e,await L(String(o),r,e.bytes))}async function j(e,o){if(!B())return o();let r;try{r=await caches.open(P)}catch{return o()}let t=g+e.sha256,a=await r.match(t).catch(()=>{});if(a){let n=new Uint8Array(await a.arrayBuffer());if(await C(n)===e.sha256)return S(r,e.sha256),n;await r.delete(t).catch(()=>{})}let s=await o();return await r.put(t,new Response(s,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),S(r,e.sha256),s}async function S(e,o){try{let r=g+"used.json",t=await(await e.match(r))?.json().catch(()=>null)??{},a=Date.now();t[o]=a;for(let[s,n]of Object.entries(t))a-n>R*864e5&&(await e.delete(g+s),delete t[s]);await e.put(r,new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}}))}catch{}}var H=e=>Object.entries(i).find(([,o])=>o===e)?.[0]??"engine";async function _(e,o,r){let t=l.models?.[H(e)]??r;if(t instanceof ArrayBuffer||t instanceof Uint8Array)return h(e,t);if($()){if(t&&String(t).startsWith("file:")){let{readFile:a}=await import("node:fs/promises");return m(e,new Uint8Array(await a(new URL(String(t)))))}if(l.modelDir){let{readFile:a}=await import("node:fs/promises"),{join:s}=await import("node:path");return m(e,new Uint8Array(await a(s(l.modelDir,e.file))))}return h(e,t??A(e),o)}return j(e,()=>h(e,t??A(e),o))}function F(e,o){return _(i[e],o)}var z=`alkove models <dir> [focus cue spot timbre lex]
3
3
 
4
4
  Copies what the installed version of alkove loads into <dir>, for self-hosting:
5
5
  the models (downloaded from Hugging Face at the pinned revision, sha256 checked),
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as t,c as p,d as n,e as s,f as a,g as i,h as c}from"./chunk-BAKUJKPE.js";import{i as e,n as r}from"./chunk-23LYNLTX.js";export{n as Alkove,e as AlkoveError,a as Lex,i as Spot,s as Timbre,r as Voiceprint,c as VoiceprintLearner,t as createAgentInput,o as createCallInput,p as createWakeListener};
1
+ import{a as o,b as t,c as p,d as n,e as s,f as a,g as i,h as c}from"./chunk-DI5ZLGIU.js";import{i as e,n as r}from"./chunk-CMAGZACJ.js";export{n as Alkove,e as AlkoveError,a as Lex,i as Spot,s as Timbre,r as Voiceprint,c as VoiceprintLearner,t as createAgentInput,o as createCallInput,p as createWakeListener};
@@ -1 +1 @@
1
- import{C as W,D as H,a as S,d as R,i as z,w as $,x as D,y as I}from"./chunk-23LYNLTX.js";var y=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,r){let t=0;for(;t<e.length;){let n=Math.min(this.size-this.fill,e.length-t);this.buf.set(e.subarray(t,t+n),this.fill),this.fill+=n,t+=n,this.fill===this.size&&(this.fill=0,r(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}};var d=R.chunk,j=["silence","forced","wake"],B=s=>new Uint8Array(s.buffer,s.byteOffset,s.byteLength),v=class{constructor(e,r,t,n={}){this.alk=e;let a={gate:!1,normalize:!0,strength:1,sleep:!0,...n},i={...I,...n.speech},l=(h,c)=>e.x.alk_chain(r.ptr,t.ptr,+a.gate,+a.normalize,+a.sleep,a.strength,i.confidence,i.exitConfidence,i.startSecs,i.stopSecs,h,c),m=n.print?Float32Array.from(n.print):null;this.ptr=m?e.with(B(m),h=>l(h,m.length)):l(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new y(d);mix=new Float32Array(d);focusOut=new Float32Array(d);onFocus=null;onCue=null;get speaking(){return this.alk.x.alk_chain_get(this.ptr,0)===1}get sleeping(){return this.alk.x.alk_chain_get(this.ptr,1)===1}get time(){return this.alk.x.alk_chain_get(this.ptr,2)}get gainDb(){return this.alk.x.alk_chain_get(this.ptr,3)}release(){this.ptr&&this.alk.x.alk_chain_free(this.ptr),this.ptr=0}setPrint(e){let r=this.alk.x;if(!e)r.alk_chain_print(this.ptr,0,0);else{let t=Float32Array.from(e);this.alk.with(B(t),n=>r.alk_chain_print(this.ptr,n,t.length))<0&&this.alk.fail("print")}}setStrength(e){this.alk.x.alk_chain_strength(this.ptr,e)}setEnabled(e){this.alk.x.alk_chain_enabled(this.ptr,+e)}step(e,r){if(this.hops.pending||e.length!==d)throw new RangeError("step() takes whole hops only");return this.hop(e,r)}push(e,r){let t=new Float32Array(Math.floor((this.hops.pending+e.length)/d)*d),n=0;return this.hops.push(e,a=>{t.set(this.hop(a,r),n),n+=d}),t}hop(e,r){let{alk:t,ptr:n}=this,a=t.x;new Float32Array(t.heap,a.alk_chain_hop(n),d).set(e);let i=a.alk_chain_step(n);this.mix.set(new Float32Array(t.heap,i,d));let l=new Float64Array(t.heap,a.alk_chain_events(n),4*a.alk_chain_event_count(n)).slice();for(let m=0;m<l.length;m+=4){let[h,c,u]=[l[m+1],l[m+2],l[m+3]];switch(l[m]){case 0:r({type:"speechstart",start:h});break;case 1:r({type:"speechend",start:h,end:c});break;case 2:r({type:"idle",asleep:h===1,at:c});break;case 3:r({type:"diag",code:"focus.print",level:"info",data:{print:h===1,after:c,why:j[u]}});break;case 4:r({type:"diag",code:"focus.reset",level:"info",data:{after:h,why:j[c]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(t.heap,a.alk_chain_focus(n),d)),this.onFocus(this.focusOut,h));break;case 6:this.onCue?.(h,c)}}return this.mix}};var X=new TextEncoder,Z=new TextDecoder;function ee(s){let e=[],r=[],t=0,n=()=>{e.length&&(r.push(Uint8Array.from(e)),t+=e.length,e.length=0)},a=u=>{n(),r.push(u),t+=u.length},i=u=>e.push(u&255,u>>>8&255,u>>>16&255,u>>>24),l=u=>{let k=X.encode(u);i(k.length),a(k)},m=u=>{if(u==null)e.push(0);else if(typeof u=="boolean")e.push(u?2:1);else if(typeof u=="number")e.push(3),a(new Uint8Array(Float64Array.of(u).buffer));else if(typeof u=="string")e.push(4),l(u);else if(u instanceof Uint8Array)e.push(7),i(u.length),a(u.slice());else if(u instanceof Float32Array)e.push(8),i(u.length),a(new Uint8Array(u.slice().buffer));else if(Array.isArray(u)||ArrayBuffer.isView(u)){let k=Array.from(u);e.push(5),i(k.length);for(let f of k)m(f)}else{let k=Object.entries(u).filter(([,f])=>f!==void 0);e.push(6),i(k.length);for(let[f,O]of k)l(f),m(O)}};m(s),n();let h=new Uint8Array(t),c=0;for(let u of r)h.set(u,c),c+=u.length;return h}function re(s){let e=new DataView(s.buffer,s.byteOffset,s.byteLength),r=0,t=()=>(r+=4,e.getUint32(r-4,!0)),n=()=>{let i=t();return r+=i,Z.decode(s.subarray(r-i,r))},a=()=>{switch(s[r++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return r+=8,e.getFloat64(r-8,!0);case 4:return n();case 5:return Array.from({length:t()},a);case 6:return Object.fromEntries(Array.from({length:t()},()=>[n(),a()]));case 7:{let i=t();return r+=i,s.slice(r-i,r)}case 8:{let i=t();return r+=4*i,new Float32Array(s.slice(r-4*i,r).buffer)}default:throw new Error("bad value from the core")}};return a()}function b(s,e){let r=ee(e),t=s.x.alk_value_in(r.length);new Uint8Array(s.heap,t,r.length).set(r)}function p(s,e){let r=re(new Uint8Array(s.heap,s.x.alk_value_out(),s.x.alk_value_len()).slice());if(e>=0)return r;let t=r;throw t.kind==="TypeError"?new TypeError(t.message):t.kind==="RangeError"?new RangeError(t.message):t.kind==="AlkoveError"?new z(t.code,t.message):new Error(t.message)}var o=s=>{if(!s)throw new Error("used after release");return s},_=(s,e,r)=>s.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),t=>r(t,e.length)),w=class{constructor(e,r){this.alk=e;this.ptr=e.x.alk_lex(r.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,r){return b(this.alk,{texts:e,lang:r}),p(this.alk,this.alk.x.alk_lex_phonemize(o(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};function J(s,e,r,t,n){return b(s,{text:r,lang:t,chain:n}),p(s,s.x.alk_compile(e?.handle??0))}var x=class{constructor(e,r,t){this.alk=e;b(e,t),this.ptr=e.x.alk_processor(r.focus?.ptr??0,r.cue?.ptr??0,r.spot?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:r}=this.alk,t=p(this.alk,e),n=new Float32Array(this.alk.heap,r.alk_processor_audio(o(this.ptr)),r.alk_processor_audio_len(o(this.ptr))).slice(),{start:a,...i}=t;return{start:a,audio:n,...i}}push(e){return this.part(_(this.alk,e,(r,t)=>this.alk.x.alk_processor_push(o(this.ptr),r,t)))}end(){return this.part(this.alk.x.alk_processor_end(o(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},A=class{constructor(e,r,t,n){this.alk=e;b(e,{words:t,context:n}),this.ptr=e.x.alk_listener(r.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,r){b(this.alk,{words:e,context:r}),p(this.alk,this.alk.x.alk_listener_words(o(this.ptr)))}push(e){return p(this.alk,_(this.alk,e,(r,t)=>this.alk.x.alk_listener_push(o(this.ptr),r,t)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},F=class{constructor(e,r,t,n,a){this.alk=e;b(e,{word:t,takes:n,chain:a}),this.ptr=e.x.alk_enroller(r.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return p(this.alk,_(this.alk,e,(r,t)=>this.alk.x.alk_enroller_push(o(this.ptr),r,t)))}result(){return p(this.alk,this.alk.x.alk_enroller_result(o(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},N=class{constructor(e,r){this.alk=e;this.ptr=e.x.alk_timbre(r.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return p(this.alk,_(this.alk,e,(r,t)=>this.alk.x.alk_timbre_windows(o(this.ptr),r,t)))}embed(e,r){return b(this.alk,{source:r}),p(this.alk,_(this.alk,e,(t,n)=>this.alk.x.alk_timbre_embed(o(this.ptr),t,n)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};function Q(s,e){return b(s,e),p(s,s.x.alk_voiceprint())}var M=class{constructor(e,r,t){this.alk=e;b(e,{source:r,start:t}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,r){return p(this.alk,_(this.alk,r,(t,n)=>this.alk.x.alk_learner_learn(o(this.ptr),e.handle,t,n)))}offer(e,r){return p(this.alk,_(this.alk,r,(t,n)=>this.alk.x.alk_learner_offer(o(this.ptr),e.handle,t,n)))}progress(){return p(this.alk,this.state()).progress}ready(){return p(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(o(this.ptr))}voiceprint(e=!1){return p(this.alk,this.alk.x.alk_learner_voiceprint(o(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(o(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},V=class{constructor(e,r,t){this.alk=e;b(e,t),this.ptr=e.x.alk_pipeline(r.focus?.ptr??0,r.cue?.ptr??0,r.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,r){let{alk:t}=this,n=o(this.ptr);new Float32Array(t.heap,t.x.alk_pipeline_hop(n),256).set(e);let a=t.x.alk_pipeline_step(n,r);return this.out.set(new Float32Array(t.heap,a,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(o(this.ptr),e.ptr)}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(o(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(o(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(o(this.ptr))?p(this.alk,this.alk.x.alk_pipeline_outs(o(this.ptr))):[]}verified(e,r,t){this.alk.x.alk_pipeline_verified(o(this.ptr),e,+r,t)}set(e){b(this.alk,e),p(this.alk,this.alk.x.alk_pipeline_set(o(this.ptr)))}record(e){p(this.alk,this.alk.x.alk_pipeline_record(o(this.ptr),e))}recent(){return p(this.alk,this.alk.x.alk_pipeline_recent(o(this.ptr)))}stats(){return p(this.alk,this.alk.x.alk_pipeline_stats(o(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(o(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(o(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(o(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(o(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(o(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},E=class{constructor(e,r){this.alk=e;b(e,{reference:r}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return b(this.alk,{start:e}),p(this.alk,this.alk.x.alk_coach_learner(o(this.ptr)))}forget(){this.alk.x.alk_coach_forget(o(this.ptr))}window(e,r,t,n){return p(this.alk,_(this.alk,r,(a,i)=>this.alk.x.alk_coach_window(o(this.ptr),e.handle,a,i,t,n)))}verify(e,r){return p(this.alk,_(this.alk,r,(t,n)=>this.alk.x.alk_coach_verify(o(this.ptr),e.handle,t,n)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}};var T=class{constructor(e,r){this.alk=e;this.bytes=r}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let r=this.models.get(e);return r||this.models.set(e,r=this.alk.model(this.bytes(e))),r}stream(e){return this.model(e).session()}chain(e){return new v(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let r=!!e.focus,t={focus:r?this.model("focus"):void 0,cue:r||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0};return new x(this.alk,t,e)}listener(e,r){return new A(this.alk,this.model("spot"),e,r)}enroller(e,r,t){return new F(this.alk,this.model("spot"),e,r,t)}lex(){return this.lexer??=new w(this.alk,this.model("lex"))}timbre(){return this.voices??=new N(this.alk,this.model("timbre"))}learner(e,r){return new M(this.alk,e,r)}pipeline(e){let r=!!e.chain,t=!!e.words?.length||!!e.enroll;return new V(this.alk,{focus:r?this.model("focus"):void 0,cue:r?this.model("cue"):void 0,spot:t?this.model("spot"):void 0},e)}coach(e){return new E(this.alk,e)}voiceprint(e){return Q(this.alk,e)}compile(e,r,t){return J(this.alk,/^\s*\/.+\/\s*$/.test(e)?null:this.lex(),e,r,t)}net(e,r){let t=`${e} ${r??""}`,n=this.calls.get(t);n||this.calls.set(t,n=this.model(e).session(r));let a=n;return{run:(i,l)=>a.call(i,l),reset:()=>a.reset()}}release(){this.lexer?.release(),this.voices?.release(),this.lexer=null,this.voices=null;for(let e of this.calls.values())e.release();for(let e of this.models.values())e.release();this.calls.clear(),this.models.clear()}};var g=class extends Error{},C=class s{constructor(e){this.x=e}static async create(e){let r=await WebAssembly.instantiate(e,{});return new s(r.exports)}get heap(){return this.x.memory.buffer}with(e,r){let t=this.x.alk_alloc(e.length);new Uint8Array(this.heap,t,e.length).set(e);try{return r(t,e.length)}finally{this.x.alk_free(t,e.length)}}fail(e){let t=this.x.alk_alloc(512);try{let n=this.x.alk_error(t,512);throw new g(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,t,n))}`)}finally{this.x.alk_free(t,512)}}model(e){return new U(this,e)}},U=class{constructor(e,r){this.alk=e;let t=e.x;this.ptr=e.with(r,(i,l)=>t.alk_model(i,l)),this.ptr||e.fail("model");let n=t.alk_alloc(256),a=i=>new TextDecoder().decode(new Uint8Array(e.heap,n,i));try{this.plans=Array.from({length:t.alk_plans(this.ptr)},(i,l)=>{let m=c=>Array.from({length:t.alk_io_count(this.ptr,l,c)},(u,k)=>{let f=a(t.alk_io_name(this.ptr,l,c,k,n,256)),O=t.alk_io_shape(this.ptr,l,c,k,n,64),L=Array.from(new Uint32Array(e.heap,n,O));return{name:f,dims:L,size:L.reduce((q,K)=>q*K,1)}}),h=m(0);return{index:l,name:a(t.alk_plan_name(this.ptr,l,n,256)),inputs:h,outputs:m(1),variable:h[t.alk_variable(this.ptr,l)]?.name??null}})}finally{t.alk_free(n,256)}}ptr;plans;session(e){let r=e===void 0?this.plans[0]:this.plans.find(t=>t.name===e);if(!r)throw new g(`no plan named ${e}`);return new P(this,r)}release(){this.alk.x.alk_model_free(this.ptr)}},P=class{constructor(e,r){this.model=e;this.plan=r;let{alk:t}=e,n=t.x;this.ptr=n.alk_session(e.ptr,r.index),this.ptr||t.fail("session");let a=new TextEncoder;for(let[i,l]of[[r.inputs,n.alk_input],[r.outputs,n.alk_output]])for(let m of i)this.at.set(m.name,{...m,p:t.with(a.encode(m.name),(h,c)=>l(this.ptr,h,c))})}ptr;at=new Map;io(e){let r=this.at.get(e);if(!r)throw new g(`no tensor named ${e}`);return r}f32(e){let r=this.io(e);return new Float32Array(this.model.alk.heap,r.p,r.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,r=this.plan.outputs.map(t=>t.name)){let{alk:t}=this.model,{variable:n}=this.plan;for(let i of this.plan.inputs){let l=e[i.name];if(!l)throw new g(`missing input ${i.name}`);if(i.name===n)t.x.alk_set_len(this.ptr,l.data.length)!==0&&t.fail(i.name);else if(l.data.length!==i.size)throw new g(`${i.name}: ${l.data.length} values for ${i.size}`);this.f32(i.name).set(l.data)}this.run();let a={};for(let i of r)a[i]={data:this.f32(i).slice(),dims:[...this.io(i).dims]};return a}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}};function G(s){let e=new Map,r=new Map,t=(n,a,i)=>{let l=n.get(a);if(!l)throw new Error(`${i} ${a} is closed, or its worker was started again`);return l};return{embed:(n,a)=>s().timbre().embed(n,a??"raw"),learnerOpen:(n,a)=>{let i=s().learner("raw",a);return e.set(n,i),{progress:i.progress(),ready:i.ready(),voiceprint:i.voiceprint(!0)}},learnerOffer:(n,a)=>{let i=t(e,n,"learner");return{...i.offer(s().timbre(),a),voiceprint:i.voiceprint(!0)}},learnerForget:n=>(e.get(n)?.forget(),null),learnerClose:n=>(e.get(n)?.release(),e.delete(n),null),phonemize:(n,a)=>s().lex().phonemize(n,a),compile:(n,a)=>s().compile(n,a.lang===void 0?[]:[a.lang].flat(),a.chain).word,process:(n,a,i)=>{let l=H(s(),n,{...a,onProgress:i});return{audio:l.audio,raw:l.raw,speech:l.speech,wakes:l.wakes,diag:l.diag,trace:l.trace}},streamOpen:(n,a)=>(r.set(n,new W(s(),a)),null),streamPush:(n,a)=>t(r,n,"stream").push(a),streamEnd:n=>{let a=t(r,n,"stream");return r.delete(n),a.end()}}}var Y=class{engine=null;boot=null;bytes=new Map;calls=G(()=>this.engine);async ready(e){await(this.boot??=(async()=>{let r=await $(S,void 0,new URL("./alkove-engine.wasm",import.meta.url).href),t=await C.create(await WebAssembly.compile(r));this.engine=new T(t,n=>this.bytes.get(n))})().catch(r=>{throw this.boot=null,r}));for(let r of e)this.bytes.has(r)||this.bytes.set(r,await D(r));return this}};export{Y as NodeBackend};
1
+ import{C as W,D as H,a as S,d as R,i as z,w as $,x as D,y as I}from"./chunk-CMAGZACJ.js";var y=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,r){let t=0;for(;t<e.length;){let n=Math.min(this.size-this.fill,e.length-t);this.buf.set(e.subarray(t,t+n),this.fill),this.fill+=n,t+=n,this.fill===this.size&&(this.fill=0,r(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}};var d=R.chunk,j=["silence","forced","wake"],B=s=>new Uint8Array(s.buffer,s.byteOffset,s.byteLength),v=class{constructor(e,r,t,n={}){this.alk=e;let a={gate:!1,normalize:!0,strength:1,sleep:!0,...n},i={...I,...n.speech},l=(h,c)=>e.x.alk_chain(r.ptr,t.ptr,+a.gate,+a.normalize,+a.sleep,a.strength,i.confidence,i.exitConfidence,i.startSecs,i.stopSecs,h,c),m=n.print?Float32Array.from(n.print):null;this.ptr=m?e.with(B(m),h=>l(h,m.length)):l(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new y(d);mix=new Float32Array(d);focusOut=new Float32Array(d);onFocus=null;onCue=null;get speaking(){return this.alk.x.alk_chain_get(this.ptr,0)===1}get sleeping(){return this.alk.x.alk_chain_get(this.ptr,1)===1}get time(){return this.alk.x.alk_chain_get(this.ptr,2)}get gainDb(){return this.alk.x.alk_chain_get(this.ptr,3)}release(){this.ptr&&this.alk.x.alk_chain_free(this.ptr),this.ptr=0}setPrint(e){let r=this.alk.x;if(!e)r.alk_chain_print(this.ptr,0,0);else{let t=Float32Array.from(e);this.alk.with(B(t),n=>r.alk_chain_print(this.ptr,n,t.length))<0&&this.alk.fail("print")}}setStrength(e){this.alk.x.alk_chain_strength(this.ptr,e)}setEnabled(e){this.alk.x.alk_chain_enabled(this.ptr,+e)}step(e,r){if(this.hops.pending||e.length!==d)throw new RangeError("step() takes whole hops only");return this.hop(e,r)}push(e,r){let t=new Float32Array(Math.floor((this.hops.pending+e.length)/d)*d),n=0;return this.hops.push(e,a=>{t.set(this.hop(a,r),n),n+=d}),t}hop(e,r){let{alk:t,ptr:n}=this,a=t.x;new Float32Array(t.heap,a.alk_chain_hop(n),d).set(e);let i=a.alk_chain_step(n);this.mix.set(new Float32Array(t.heap,i,d));let l=new Float64Array(t.heap,a.alk_chain_events(n),4*a.alk_chain_event_count(n)).slice();for(let m=0;m<l.length;m+=4){let[h,c,u]=[l[m+1],l[m+2],l[m+3]];switch(l[m]){case 0:r({type:"speechstart",start:h});break;case 1:r({type:"speechend",start:h,end:c});break;case 2:r({type:"idle",asleep:h===1,at:c});break;case 3:r({type:"diag",code:"focus.print",level:"info",data:{print:h===1,after:c,why:j[u]}});break;case 4:r({type:"diag",code:"focus.reset",level:"info",data:{after:h,why:j[c]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(t.heap,a.alk_chain_focus(n),d)),this.onFocus(this.focusOut,h));break;case 6:this.onCue?.(h,c)}}return this.mix}};var X=new TextEncoder,Z=new TextDecoder;function ee(s){let e=[],r=[],t=0,n=()=>{e.length&&(r.push(Uint8Array.from(e)),t+=e.length,e.length=0)},a=u=>{n(),r.push(u),t+=u.length},i=u=>e.push(u&255,u>>>8&255,u>>>16&255,u>>>24),l=u=>{let k=X.encode(u);i(k.length),a(k)},m=u=>{if(u==null)e.push(0);else if(typeof u=="boolean")e.push(u?2:1);else if(typeof u=="number")e.push(3),a(new Uint8Array(Float64Array.of(u).buffer));else if(typeof u=="string")e.push(4),l(u);else if(u instanceof Uint8Array)e.push(7),i(u.length),a(u.slice());else if(u instanceof Float32Array)e.push(8),i(u.length),a(new Uint8Array(u.slice().buffer));else if(Array.isArray(u)||ArrayBuffer.isView(u)){let k=Array.from(u);e.push(5),i(k.length);for(let f of k)m(f)}else{let k=Object.entries(u).filter(([,f])=>f!==void 0);e.push(6),i(k.length);for(let[f,O]of k)l(f),m(O)}};m(s),n();let h=new Uint8Array(t),c=0;for(let u of r)h.set(u,c),c+=u.length;return h}function re(s){let e=new DataView(s.buffer,s.byteOffset,s.byteLength),r=0,t=()=>(r+=4,e.getUint32(r-4,!0)),n=()=>{let i=t();return r+=i,Z.decode(s.subarray(r-i,r))},a=()=>{switch(s[r++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return r+=8,e.getFloat64(r-8,!0);case 4:return n();case 5:return Array.from({length:t()},a);case 6:return Object.fromEntries(Array.from({length:t()},()=>[n(),a()]));case 7:{let i=t();return r+=i,s.slice(r-i,r)}case 8:{let i=t();return r+=4*i,new Float32Array(s.slice(r-4*i,r).buffer)}default:throw new Error("bad value from the core")}};return a()}function b(s,e){let r=ee(e),t=s.x.alk_value_in(r.length);new Uint8Array(s.heap,t,r.length).set(r)}function p(s,e){let r=re(new Uint8Array(s.heap,s.x.alk_value_out(),s.x.alk_value_len()).slice());if(e>=0)return r;let t=r;throw t.kind==="TypeError"?new TypeError(t.message):t.kind==="RangeError"?new RangeError(t.message):t.kind==="AlkoveError"?new z(t.code,t.message):new Error(t.message)}var o=s=>{if(!s)throw new Error("used after release");return s},_=(s,e,r)=>s.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),t=>r(t,e.length)),w=class{constructor(e,r){this.alk=e;this.ptr=e.x.alk_lex(r.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,r){return b(this.alk,{texts:e,lang:r}),p(this.alk,this.alk.x.alk_lex_phonemize(o(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};function J(s,e,r,t,n){return b(s,{text:r,lang:t,chain:n}),p(s,s.x.alk_compile(e?.handle??0))}var x=class{constructor(e,r,t){this.alk=e;b(e,t),this.ptr=e.x.alk_processor(r.focus?.ptr??0,r.cue?.ptr??0,r.spot?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:r}=this.alk,t=p(this.alk,e),n=new Float32Array(this.alk.heap,r.alk_processor_audio(o(this.ptr)),r.alk_processor_audio_len(o(this.ptr))).slice(),{start:a,...i}=t;return{start:a,audio:n,...i}}push(e){return this.part(_(this.alk,e,(r,t)=>this.alk.x.alk_processor_push(o(this.ptr),r,t)))}end(){return this.part(this.alk.x.alk_processor_end(o(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},A=class{constructor(e,r,t,n){this.alk=e;b(e,{words:t,context:n}),this.ptr=e.x.alk_listener(r.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,r){b(this.alk,{words:e,context:r}),p(this.alk,this.alk.x.alk_listener_words(o(this.ptr)))}push(e){return p(this.alk,_(this.alk,e,(r,t)=>this.alk.x.alk_listener_push(o(this.ptr),r,t)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},F=class{constructor(e,r,t,n,a){this.alk=e;b(e,{word:t,takes:n,chain:a}),this.ptr=e.x.alk_enroller(r.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return p(this.alk,_(this.alk,e,(r,t)=>this.alk.x.alk_enroller_push(o(this.ptr),r,t)))}result(){return p(this.alk,this.alk.x.alk_enroller_result(o(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},N=class{constructor(e,r){this.alk=e;this.ptr=e.x.alk_timbre(r.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return p(this.alk,_(this.alk,e,(r,t)=>this.alk.x.alk_timbre_windows(o(this.ptr),r,t)))}embed(e,r){return b(this.alk,{source:r}),p(this.alk,_(this.alk,e,(t,n)=>this.alk.x.alk_timbre_embed(o(this.ptr),t,n)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};function Q(s,e){return b(s,e),p(s,s.x.alk_voiceprint())}var M=class{constructor(e,r,t){this.alk=e;b(e,{source:r,start:t}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,r){return p(this.alk,_(this.alk,r,(t,n)=>this.alk.x.alk_learner_learn(o(this.ptr),e.handle,t,n)))}offer(e,r){return p(this.alk,_(this.alk,r,(t,n)=>this.alk.x.alk_learner_offer(o(this.ptr),e.handle,t,n)))}progress(){return p(this.alk,this.state()).progress}ready(){return p(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(o(this.ptr))}voiceprint(e=!1){return p(this.alk,this.alk.x.alk_learner_voiceprint(o(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(o(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},V=class{constructor(e,r,t){this.alk=e;b(e,t),this.ptr=e.x.alk_pipeline(r.focus?.ptr??0,r.cue?.ptr??0,r.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,r){let{alk:t}=this,n=o(this.ptr);new Float32Array(t.heap,t.x.alk_pipeline_hop(n),256).set(e);let a=t.x.alk_pipeline_step(n,r);return this.out.set(new Float32Array(t.heap,a,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(o(this.ptr),e.ptr)}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(o(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(o(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(o(this.ptr))?p(this.alk,this.alk.x.alk_pipeline_outs(o(this.ptr))):[]}verified(e,r,t){this.alk.x.alk_pipeline_verified(o(this.ptr),e,+r,t)}set(e){b(this.alk,e),p(this.alk,this.alk.x.alk_pipeline_set(o(this.ptr)))}record(e){p(this.alk,this.alk.x.alk_pipeline_record(o(this.ptr),e))}recent(){return p(this.alk,this.alk.x.alk_pipeline_recent(o(this.ptr)))}stats(){return p(this.alk,this.alk.x.alk_pipeline_stats(o(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(o(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(o(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(o(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(o(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(o(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},E=class{constructor(e,r){this.alk=e;b(e,{reference:r}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return b(this.alk,{start:e}),p(this.alk,this.alk.x.alk_coach_learner(o(this.ptr)))}forget(){this.alk.x.alk_coach_forget(o(this.ptr))}window(e,r,t,n){return p(this.alk,_(this.alk,r,(a,i)=>this.alk.x.alk_coach_window(o(this.ptr),e.handle,a,i,t,n)))}verify(e,r){return p(this.alk,_(this.alk,r,(t,n)=>this.alk.x.alk_coach_verify(o(this.ptr),e.handle,t,n)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}};var T=class{constructor(e,r){this.alk=e;this.bytes=r}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let r=this.models.get(e);return r||this.models.set(e,r=this.alk.model(this.bytes(e))),r}stream(e){return this.model(e).session()}chain(e){return new v(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let r=!!e.focus,t={focus:r?this.model("focus"):void 0,cue:r||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0};return new x(this.alk,t,e)}listener(e,r){return new A(this.alk,this.model("spot"),e,r)}enroller(e,r,t){return new F(this.alk,this.model("spot"),e,r,t)}lex(){return this.lexer??=new w(this.alk,this.model("lex"))}timbre(){return this.voices??=new N(this.alk,this.model("timbre"))}learner(e,r){return new M(this.alk,e,r)}pipeline(e){let r=!!e.chain,t=!!e.words?.length||!!e.enroll;return new V(this.alk,{focus:r?this.model("focus"):void 0,cue:r?this.model("cue"):void 0,spot:t?this.model("spot"):void 0},e)}coach(e){return new E(this.alk,e)}voiceprint(e){return Q(this.alk,e)}compile(e,r,t){return J(this.alk,/^\s*\/.+\/\s*$/.test(e)?null:this.lex(),e,r,t)}net(e,r){let t=`${e} ${r??""}`,n=this.calls.get(t);n||this.calls.set(t,n=this.model(e).session(r));let a=n;return{run:(i,l)=>a.call(i,l),reset:()=>a.reset()}}release(){this.lexer?.release(),this.voices?.release(),this.lexer=null,this.voices=null;for(let e of this.calls.values())e.release();for(let e of this.models.values())e.release();this.calls.clear(),this.models.clear()}};var g=class extends Error{},C=class s{constructor(e){this.x=e}static async create(e){let r=await WebAssembly.instantiate(e,{});return new s(r.exports)}get heap(){return this.x.memory.buffer}with(e,r){let t=this.x.alk_alloc(e.length);new Uint8Array(this.heap,t,e.length).set(e);try{return r(t,e.length)}finally{this.x.alk_free(t,e.length)}}fail(e){let t=this.x.alk_alloc(512);try{let n=this.x.alk_error(t,512);throw new g(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,t,n))}`)}finally{this.x.alk_free(t,512)}}model(e){return new U(this,e)}},U=class{constructor(e,r){this.alk=e;let t=e.x;this.ptr=e.with(r,(i,l)=>t.alk_model(i,l)),this.ptr||e.fail("model");let n=t.alk_alloc(256),a=i=>new TextDecoder().decode(new Uint8Array(e.heap,n,i));try{this.plans=Array.from({length:t.alk_plans(this.ptr)},(i,l)=>{let m=c=>Array.from({length:t.alk_io_count(this.ptr,l,c)},(u,k)=>{let f=a(t.alk_io_name(this.ptr,l,c,k,n,256)),O=t.alk_io_shape(this.ptr,l,c,k,n,64),L=Array.from(new Uint32Array(e.heap,n,O));return{name:f,dims:L,size:L.reduce((q,K)=>q*K,1)}}),h=m(0);return{index:l,name:a(t.alk_plan_name(this.ptr,l,n,256)),inputs:h,outputs:m(1),variable:h[t.alk_variable(this.ptr,l)]?.name??null}})}finally{t.alk_free(n,256)}}ptr;plans;session(e){let r=e===void 0?this.plans[0]:this.plans.find(t=>t.name===e);if(!r)throw new g(`no plan named ${e}`);return new P(this,r)}release(){this.alk.x.alk_model_free(this.ptr)}},P=class{constructor(e,r){this.model=e;this.plan=r;let{alk:t}=e,n=t.x;this.ptr=n.alk_session(e.ptr,r.index),this.ptr||t.fail("session");let a=new TextEncoder;for(let[i,l]of[[r.inputs,n.alk_input],[r.outputs,n.alk_output]])for(let m of i)this.at.set(m.name,{...m,p:t.with(a.encode(m.name),(h,c)=>l(this.ptr,h,c))})}ptr;at=new Map;io(e){let r=this.at.get(e);if(!r)throw new g(`no tensor named ${e}`);return r}f32(e){let r=this.io(e);return new Float32Array(this.model.alk.heap,r.p,r.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,r=this.plan.outputs.map(t=>t.name)){let{alk:t}=this.model,{variable:n}=this.plan;for(let i of this.plan.inputs){let l=e[i.name];if(!l)throw new g(`missing input ${i.name}`);if(i.name===n)t.x.alk_set_len(this.ptr,l.data.length)!==0&&t.fail(i.name);else if(l.data.length!==i.size)throw new g(`${i.name}: ${l.data.length} values for ${i.size}`);this.f32(i.name).set(l.data)}this.run();let a={};for(let i of r)a[i]={data:this.f32(i).slice(),dims:[...this.io(i).dims]};return a}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}};function G(s){let e=new Map,r=new Map,t=(n,a,i)=>{let l=n.get(a);if(!l)throw new Error(`${i} ${a} is closed, or its worker was started again`);return l};return{embed:(n,a)=>s().timbre().embed(n,a??"raw"),learnerOpen:(n,a)=>{let i=s().learner("raw",a);return e.set(n,i),{progress:i.progress(),ready:i.ready(),voiceprint:i.voiceprint(!0)}},learnerOffer:(n,a)=>{let i=t(e,n,"learner");return{...i.offer(s().timbre(),a),voiceprint:i.voiceprint(!0)}},learnerForget:n=>(e.get(n)?.forget(),null),learnerClose:n=>(e.get(n)?.release(),e.delete(n),null),phonemize:(n,a)=>s().lex().phonemize(n,a),compile:(n,a)=>s().compile(n,a.lang===void 0?[]:[a.lang].flat(),a.chain).word,process:(n,a,i)=>{let l=H(s(),n,{...a,onProgress:i});return{audio:l.audio,raw:l.raw,speech:l.speech,wakes:l.wakes,diag:l.diag,trace:l.trace}},streamOpen:(n,a)=>(r.set(n,new W(s(),a)),null),streamPush:(n,a)=>t(r,n,"stream").push(a),streamEnd:n=>{let a=t(r,n,"stream");return r.delete(n),a.end()}}}var Y=class{engine=null;boot=null;bytes=new Map;calls=G(()=>this.engine);async ready(e){await(this.boot??=(async()=>{let r=await $(S,void 0,new URL("./alkove-engine.wasm",import.meta.url).href),t=await C.create(await WebAssembly.compile(r));this.engine=new T(t,n=>this.bytes.get(n))})().catch(r=>{throw this.boot=null,r}));for(let r of e)this.bytes.has(r)||this.bytes.set(r,await D(r));return this}};export{Y as NodeBackend};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alkove",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "On-device voice input for the web: keep the user's voice, detect speech and wake words. No server, no key.",
5
5
  "keywords": [
6
6
  "voice",
@@ -1 +0,0 @@
1
- import{d as a,e as b,f as c,g as d,h as e}from"./chunk-BAKUJKPE.js";import"./chunk-23LYNLTX.js";export{a as Alkove,c as Lex,d as Spot,b as Timbre,e as VoiceprintLearner};