alkove 0.4.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NOTICE CHANGED
@@ -3,7 +3,7 @@ Copyright 2026 Eddy Bordi
3
3
 
4
4
  This product includes software developed by third parties:
5
5
 
6
- - alkove-focus-1-preview is derived from GTCRN
6
+ - alkove-focus-1 is derived from GTCRN
7
7
  (https://github.com/Xiaobin-Rong/gtcrn), under the MIT License:
8
8
 
9
9
  Copyright (c) 2024 Rong Xiaobin
package/README.md CHANGED
@@ -19,23 +19,23 @@ ESM only, no runtime dependency (the engine, Alkove's own, is bundled). Works wi
19
19
  ```ts
20
20
  import { createCallInput } from 'alkove'
21
21
 
22
- const input = await createCallInput({ learn: true, farEnd: remoteTrack })
22
+ const input = await createCallInput({ farEnd: remoteTrack })
23
23
  pc.addTrack(input.track)
24
24
  input.bind(pc.getSenders()[0]) // the SDK swaps in the raw mic if the audio clock stalls
25
25
  input.on('voiceprint', (p) => localStorage.setItem('print', JSON.stringify(p.toJSON())))
26
26
  ```
27
27
 
28
- Out goes the user's voice only, gated between sentences, at a steady level. With `learn: true`, the user's print is learned while they talk (about 6 s of their voice), then only their voice goes out.
28
+ Out goes the user's voice only, gated between sentences, at a steady level. The user's print is learned while they talk (about 6 s of their voice), never while the far end does, then only their voice goes out.
29
29
 
30
30
  ## A voice agent (speech to text, LLM)
31
31
 
32
32
  ```ts
33
33
  import { createAgentInput } from 'alkove'
34
34
 
35
- const input = await createAgentInput({ farEnd: 'manual', output: { format: 's16', rate: 24000 } })
35
+ const input = await createAgentInput({ output: { format: 's16', rate: 24000 } })
36
36
  input.on('audio', (pcm) => ws.send(pcm)) // continuous, 32 ms packets
37
37
  input.on('utterance', ({ pcm }) => transcribe(pcm)) // one segment per sentence, 300 ms of pre-roll included
38
- input.farEndActive(true) // the agent starts speaking; false when it stops
38
+ input.farEndActive(true) // the agent starts speaking; false when it stops. From the first call, the user's print learns
39
39
  ```
40
40
 
41
41
  Nothing is cut: `audio` is continuous, `speechstart` / `speechend` tell where the user speaks.
@@ -54,7 +54,7 @@ const wake = await createWakeListener({ words: [word] })
54
54
  wake.on('wake', ({ word, start, audio }) => …)
55
55
  ```
56
56
 
57
- Any word, typed in one of 7 languages (fr, en, es, it, pt, ca, ro). By default it counts only after a pause (far fewer false alarms; "Bon, Camille, on y va ?" does not wake it, use `context: 'both'` for that). Enrolling the word (the user says it 3 times) sets its thresholds on their voice. `onlyMyVoice: print` ignores other voices.
57
+ Any word, typed in one of 11 languages (fr, en, es, it, pt, ca, ro, de, nl, pl, sv). By default it counts only after a pause (far fewer false alarms; "Bon, Camille, on y va ?" does not wake it, use `context: 'both'` for that). Enrolling the word (the user says it 3 times) sets its thresholds on their voice. `voiceprint: print` ignores other voices.
58
58
 
59
59
  ## React
60
60
 
@@ -105,7 +105,7 @@ Alkove.configure({ modelBaseUrl: '/alkove/', assetBaseUrl: '/alkove/' })
105
105
  |---|---|
106
106
  | call / agent | Focus 0.9 MB + Cue 0.9 MB, + Timbre 0.7 MB with a print |
107
107
  | wake word | Spot 2.5 MB, + Lex 1.5 MB for a typed word |
108
- | engine | Alkove's own, 141 KB |
108
+ | engine | Alkove's own, 223 KB |
109
109
 
110
110
  ## Content Security Policy
111
111
 
Binary file
@@ -1 +1 @@
1
- var ee={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:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},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 y=16e3,te=ee,re={chunk:256,print:192,lag:256};var P=n=>`${te[n].name}@${te[n].sha256.slice(0,12)}`,x={model:P("timbre"),window:24e3,min:280,dim:192};var R=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,t){let r=0;for(;r<e.length;){let s=Math.min(this.size-this.fill,e.length-r);this.buf.set(e.subarray(r,r+s),this.fill),this.fill+=s,r+=s,this.fill===this.size&&(this.fill=0,t(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}};var T={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6};var k=re.chunk,ne=["silence","forced","wake"],se=n=>new Uint8Array(n.buffer,n.byteOffset,n.byteLength),C=class{constructor(e,t,r,s={}){this.alk=e;let o={gate:!1,normalize:!0,strength:1,sleep:!0,...s},i={...T,...s.speech},a=(p,m)=>e.x.alk_chain(t.ptr,r.ptr,+o.gate,+o.normalize,+o.sleep,o.strength,i.confidence,i.exitConfidence,i.startSecs,i.stopSecs,p,m),u=s.print?Float32Array.from(s.print):null;this.ptr=u?e.with(se(u),p=>a(p,u.length)):a(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new R(k);mix=new Float32Array(k);focusOut=new Float32Array(k);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 t=this.alk.x;if(!e)t.alk_chain_print(this.ptr,0,0);else{let r=Float32Array.from(e);this.alk.with(se(r),s=>t.alk_chain_print(this.ptr,s,r.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,t){if(this.hops.pending||e.length!==k)throw new RangeError("step() takes whole hops only");return this.hop(e,t)}push(e,t){let r=new Float32Array(Math.floor((this.hops.pending+e.length)/k)*k),s=0;return this.hops.push(e,o=>{r.set(this.hop(o,t),s),s+=k}),r}hop(e,t){let{alk:r,ptr:s}=this,o=r.x;new Float32Array(r.heap,o.alk_chain_hop(s),k).set(e);let i=o.alk_chain_step(s);this.mix.set(new Float32Array(r.heap,i,k));let a=new Float64Array(r.heap,o.alk_chain_events(s),4*o.alk_chain_event_count(s)).slice();for(let u=0;u<a.length;u+=4){let[p,m,l]=[a[u+1],a[u+2],a[u+3]];switch(a[u]){case 0:t({type:"speechstart",start:p});break;case 1:t({type:"speechend",start:p,end:m});break;case 2:t({type:"idle",asleep:p===1,at:m});break;case 3:t({type:"diag",code:"focus.print",level:"info",data:{print:p===1,after:m,why:ne[l]}});break;case 4:t({type:"diag",code:"focus.reset",level:"info",data:{after:p,why:ne[m]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(r.heap,o.alk_chain_focus(s),k)),this.onFocus(this.focusOut,p));break;case 6:this.onCue?.(p,m)}}return this.mix}};var F=class extends Error{constructor(t,r,s){super(r);this.code=t;this.cause=s}name="AlkoveError"};var Ae=new TextEncoder,Me=new TextDecoder;function Fe(n){let e=[],t=[],r=0,s=()=>{e.length&&(t.push(Uint8Array.from(e)),r+=e.length,e.length=0)},o=l=>{s(),t.push(l),r+=l.length},i=l=>e.push(l&255,l>>>8&255,l>>>16&255,l>>>24),a=l=>{let h=Ae.encode(l);i(h.length),o(h)},u=l=>{if(l==null)e.push(0);else if(typeof l=="boolean")e.push(l?2:1);else if(typeof l=="number")e.push(3),o(new Uint8Array(Float64Array.of(l).buffer));else if(typeof l=="string")e.push(4),a(l);else if(l instanceof Uint8Array)e.push(7),i(l.length),o(l.slice());else if(l instanceof Float32Array)e.push(8),i(l.length),o(new Uint8Array(l.slice().buffer));else if(Array.isArray(l)||ArrayBuffer.isView(l)){let h=Array.from(l);e.push(5),i(h.length);for(let f of h)u(f)}else{let h=Object.entries(l).filter(([,f])=>f!==void 0);e.push(6),i(h.length);for(let[f,B]of h)a(f),u(B)}};u(n),s();let p=new Uint8Array(r),m=0;for(let l of t)p.set(l,m),m+=l.length;return p}function Se(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0,r=()=>(t+=4,e.getUint32(t-4,!0)),s=()=>{let i=r();return t+=i,Me.decode(n.subarray(t-i,t))},o=()=>{switch(n[t++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return t+=8,e.getFloat64(t-8,!0);case 4:return s();case 5:return Array.from({length:r()},o);case 6:return Object.fromEntries(Array.from({length:r()},()=>[s(),o()]));case 7:{let i=r();return t+=i,n.slice(t-i,t)}case 8:{let i=r();return t+=4*i,new Float32Array(n.slice(t-4*i,t).buffer)}default:throw new Error("bad value from the core")}};return o()}function b(n,e){let t=Fe(e),r=n.x.alk_value_in(t.length);new Uint8Array(n.heap,r,t.length).set(t)}function d(n,e){let t=Se(new Uint8Array(n.heap,n.x.alk_value_out(),n.x.alk_value_len()).slice());if(e>=0)return t;let r=t;throw r.kind==="TypeError"?new TypeError(r.message):r.kind==="RangeError"?new RangeError(r.message):r.kind==="AlkoveError"?new F(r.code,r.message):new Error(r.message)}var c=n=>{if(!n)throw new Error("used after release");return n},w=(n,e,t)=>n.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=>t(r,e.length)),V=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_lex(t.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,t){return b(this.alk,{texts:e,lang:t}),d(this.alk,this.alk.x.alk_lex_phonemize(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};function ie(n,e,t,r,s){return b(n,{text:t,lang:r,chain:s}),d(n,n.x.alk_compile(e?.handle??0))}var L=class{constructor(e,t,r){this.alk=e;b(e,r),this.ptr=e.x.alk_processor(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:t}=this.alk,r=d(this.alk,e),s=new Float32Array(this.alk.heap,t.alk_processor_audio(c(this.ptr)),t.alk_processor_audio_len(c(this.ptr))).slice(),{start:o,...i}=r;return{start:o,audio:s,...i}}push(e){return this.part(w(this.alk,e,(t,r)=>this.alk.x.alk_processor_push(c(this.ptr),t,r)))}end(){return this.part(this.alk.x.alk_processor_end(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},U=class{constructor(e,t,r,s){this.alk=e;b(e,{words:r,context:s}),this.ptr=e.x.alk_listener(t.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,t){b(this.alk,{words:e,context:t}),d(this.alk,this.alk.x.alk_listener_words(c(this.ptr)))}push(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_listener_push(c(this.ptr),t,r)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},W=class{constructor(e,t,r,s,o){this.alk=e;b(e,{word:r,takes:s,chain:o}),this.ptr=e.x.alk_enroller(t.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_enroller_push(c(this.ptr),t,r)))}result(){return d(this.alk,this.alk.x.alk_enroller_result(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},I=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_timbre(t.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_timbre_windows(c(this.ptr),t,r)))}embed(e,t){return b(this.alk,{source:t}),d(this.alk,w(this.alk,e,(r,s)=>this.alk.x.alk_timbre_embed(c(this.ptr),r,s)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};function oe(n,e){return b(n,e),d(n,n.x.alk_voiceprint())}var z=class{constructor(e,t,r){this.alk=e;b(e,{source:t,start:r}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_learner_learn(c(this.ptr),e.handle,r,s)))}offer(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_learner_offer(c(this.ptr),e.handle,r,s)))}progress(){return d(this.alk,this.state()).progress}ready(){return d(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(c(this.ptr))}voiceprint(e=!1){return d(this.alk,this.alk.x.alk_learner_voiceprint(c(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(c(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},D=class{constructor(e,t,r){this.alk=e;b(e,r),this.ptr=e.x.alk_pipeline(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,t){let{alk:r}=this,s=c(this.ptr);new Float32Array(r.heap,r.x.alk_pipeline_hop(s),256).set(e);let o=r.x.alk_pipeline_step(s,t);return this.out.set(new Float32Array(r.heap,o,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(c(this.ptr),e.ptr)}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(c(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(c(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(c(this.ptr))?d(this.alk,this.alk.x.alk_pipeline_outs(c(this.ptr))):[]}verified(e,t,r){this.alk.x.alk_pipeline_verified(c(this.ptr),e,+t,r)}set(e){b(this.alk,e),d(this.alk,this.alk.x.alk_pipeline_set(c(this.ptr)))}record(e){d(this.alk,this.alk.x.alk_pipeline_record(c(this.ptr),e))}recent(){return d(this.alk,this.alk.x.alk_pipeline_recent(c(this.ptr)))}stats(){return d(this.alk,this.alk.x.alk_pipeline_stats(c(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(c(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(c(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(c(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(c(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(c(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},J=class{constructor(e,t){this.alk=e;b(e,{reference:t}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return b(this.alk,{start:e}),d(this.alk,this.alk.x.alk_coach_learner(c(this.ptr)))}forget(){this.alk.x.alk_coach_forget(c(this.ptr))}window(e,t,r,s){return d(this.alk,w(this.alk,t,(o,i)=>this.alk.x.alk_coach_window(c(this.ptr),e.handle,o,i,r,s)))}verify(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_coach_verify(c(this.ptr),e.handle,r,s)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}};var H=class{constructor(e,t){this.alk=e;this.bytes=t}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let t=this.models.get(e);return t||this.models.set(e,t=this.alk.model(this.bytes(e))),t}stream(e){return this.model(e).session()}chain(e){return new C(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let t=!!e.focus,r={focus:t?this.model("focus"):void 0,cue:t||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0};return new L(this.alk,r,e)}listener(e,t){return new U(this.alk,this.model("spot"),e,t)}enroller(e,t,r){return new W(this.alk,this.model("spot"),e,t,r)}lex(){return this.lexer??=new V(this.alk,this.model("lex"))}timbre(){return this.voices??=new I(this.alk,this.model("timbre"))}learner(e,t){return new z(this.alk,e,t)}pipeline(e){let t=!!e.chain,r=!!e.words?.length||!!e.enroll;return new D(this.alk,{focus:t?this.model("focus"):void 0,cue:t?this.model("cue"):void 0,spot:r?this.model("spot"):void 0},e)}coach(e){return new J(this.alk,e)}voiceprint(e){return oe(this.alk,e)}compile(e,t,r){return ie(this.alk,/^\s*\/.+\/\s*$/.test(e)?null:this.lex(),e,t,r)}net(e,t){let r=`${e} ${t??""}`,s=this.calls.get(r);s||this.calls.set(r,s=this.model(e).session(t));let o=s;return{run:(i,a)=>o.call(i,a),reset:()=>o.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 ce=["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(n=>n.normalize("NFD"));var q=new Map(ce.map((n,e)=>[n,e+1])),ct=q.get("\u0259"),Oe={"\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"},Ee={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"}},Ne=new Set("\u02C8\u02CC\u02D0\u02D1\u203F-.|\u02B2\u02B0\u02B7' "),Pe=[["e","\u025B"],["o","\u0254"],["\xF8","\u0153","\u0259"],["i","j"],["u","w"],["y","\u0265"],["\u027E","r"]],ae=ce.map((n,e)=>[e+1]);for(let n of Pe){let e=n.map(t=>q.get(t.normalize("NFD")));for(let t of e)for(let r of e)ae[t-1].includes(r)||ae[t-1].push(r)}var le=new Map;function Re(n){let e=le.get(n);if(!e){let t=Object.entries({...Oe,...Ee[n]??{}}).map(([r,s])=>[r.normalize("NFD"),s.normalize("NFD")]);le.set(n,e=new Map(t))}return e}function ue(n){let e=[];for(let t of n.normalize("NFD")){if(/\p{M}/u.test(t)){t==="\u0303"&&e.length&&(e[e.length-1]+=t);continue}e.push(t)}return e}function pe(n,e=""){let t=Re(e),r=[];for(let s of ue(n.replace(/\([^)]*\)/g," ").replace(/‍/g,"").replace(/\s+/g," ")))if(!Ne.has(s))for(let o of ue(t.get(s)??s)){o=t.get(o)??o;let i=q.get(o);if(!i)return null;r[r.length-1]!==i&&r.push(i)}return r}var $=class n{constructor(e,t,r,s,o,i,a=[]){this.text=e;this.lang=t;this.phonemes=r;this.thresholds=s;this.calibrated=o;this.chain=i;this.warnings=a}warnings;toJSON(){return{alkove:"word",spot:P("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:e,lang:t,p:r})=>({ipa:e,lang:t,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="word")throw new TypeError("not an Alkove word");if(t.spot!==P("spot"))return null;let r=t.phonemes.map(s=>({...s,ids:pe(s.ipa,s.lang)??[]})).filter(s=>s.ids.length);return new n(t.text,t.lang,r,t.thresholds,t.calibrated,t.chain)}},O=n=>{if(n instanceof $)return n;let e=$.fromJSON(n);if(!e)throw new F("word.outdated",`Compiled for another Spot: compile "${typeof n=="string"?JSON.parse(n).text:n.text}" again.`);return e};var A=class extends Error{},j=class n{constructor(e){this.x=e}static async create(e){let t=await WebAssembly.instantiate(e,{});return new n(t.exports)}get heap(){return this.x.memory.buffer}with(e,t){let r=this.x.alk_alloc(e.length);new Uint8Array(this.heap,r,e.length).set(e);try{return t(r,e.length)}finally{this.x.alk_free(r,e.length)}}fail(e){let r=this.x.alk_alloc(512);try{let s=this.x.alk_error(r,512);throw new A(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,r,s))}`)}finally{this.x.alk_free(r,512)}}model(e){return new G(this,e)}},G=class{constructor(e,t){this.alk=e;let r=e.x;this.ptr=e.with(t,(i,a)=>r.alk_model(i,a)),this.ptr||e.fail("model");let s=r.alk_alloc(256),o=i=>new TextDecoder().decode(new Uint8Array(e.heap,s,i));try{this.plans=Array.from({length:r.alk_plans(this.ptr)},(i,a)=>{let u=m=>Array.from({length:r.alk_io_count(this.ptr,a,m)},(l,h)=>{let f=o(r.alk_io_name(this.ptr,a,m,h,s,256)),B=r.alk_io_shape(this.ptr,a,m,h,s,64),Z=Array.from(new Uint32Array(e.heap,s,B));return{name:f,dims:Z,size:Z.reduce((_e,xe)=>_e*xe,1)}}),p=u(0);return{index:a,name:o(r.alk_plan_name(this.ptr,a,s,256)),inputs:p,outputs:u(1),variable:p[r.alk_variable(this.ptr,a)]?.name??null}})}finally{r.alk_free(s,256)}}ptr;plans;session(e){let t=e===void 0?this.plans[0]:this.plans.find(r=>r.name===e);if(!t)throw new A(`no plan named ${e}`);return new K(this,t)}release(){this.alk.x.alk_model_free(this.ptr)}},K=class{constructor(e,t){this.model=e;this.plan=t;let{alk:r}=e,s=r.x;this.ptr=s.alk_session(e.ptr,t.index),this.ptr||r.fail("session");let o=new TextEncoder;for(let[i,a]of[[t.inputs,s.alk_input],[t.outputs,s.alk_output]])for(let u of i)this.at.set(u.name,{...u,p:r.with(o.encode(u.name),(p,m)=>a(this.ptr,p,m))})}ptr;at=new Map;io(e){let t=this.at.get(e);if(!t)throw new A(`no tensor named ${e}`);return t}f32(e){let t=this.io(e);return new Float32Array(this.model.alk.heap,t.p,t.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,t=this.plan.outputs.map(r=>r.name)){let{alk:r}=this.model,{variable:s}=this.plan;for(let i of this.plan.inputs){let a=e[i.name];if(!a)throw new A(`missing input ${i.name}`);if(i.name===s)r.x.alk_set_len(this.ptr,a.data.length)!==0&&r.fail(i.name);else if(a.data.length!==i.size)throw new A(`${i.name}: ${a.data.length} values for ${i.size}`);this.f32(i.name).set(a.data)}this.run();let o={};for(let i of t)o[i]={data:this.f32(i).slice(),dims:[...this.io(i).dims]};return o}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}};var Te=(n,e)=>{let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t},E=class n{constructor(e,t="focus",r=x.model,s=[]){this.centers=e;this.source=t;this.model=r;this.windows=s;if(!e.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(e){return this.closest(e).score}closest(e){let t=e instanceof n?e.centers:[e],r={score:-1,mine:0,theirs:0};for(let s of this.centers)for(let o of t){let i=Te(s.id,o.id);i>r.score&&(r={score:i,mine:s.seconds,theirs:o.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let e=t=>Array.from(t,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(t=>({embedding:e(t.embedding),id:e(t.id),seconds:+t.seconds.toFixed(1)})),...this.windows.length?{windows:Ce(this.windows)}:{}}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(t.model!==x.model)return null;let r=t.centers.map(s=>({embedding:Float32Array.from(s.embedding),id:Float32Array.from(s.id),seconds:s.seconds}));return new n(r,t.source,t.model,t.windows?Ve(t.windows):[])}static merge(e){return new n(e.flatMap(t=>t.centers),e.every(t=>t.source==="raw")?"raw":"focus")}};function Ce(n){let e=new Uint8Array(n.length*2*(x.dim+4)),t=new DataView(e.buffer),r=0;for(let o of n)for(let i of[o.embedding,o.id]){let a=1e-9;for(let u of i)a=Math.max(a,Math.abs(u));t.setFloat32(r,a/127,!0),r+=4;for(let u of i)t.setInt8(r++,Math.round(u/a*127))}let s="";for(let o of e)s+=String.fromCharCode(o);return btoa(s)}function Ve(n){let e=atob(n),t=Uint8Array.from(e,i=>i.charCodeAt(0)),r=new DataView(t.buffer),s=[],o=0;for(;o+2*(x.dim+4)<=t.length;){let i=[];for(let a=0;a<2;a++){let u=r.getFloat32(o,!0);o+=4;let p=new Float32Array(x.dim);for(let m=0;m<p.length;m++)p[m]=r.getInt8(o++)*u;i.push(p)}s.push({embedding:i[0],id:i[1],seconds:x.window/y})}return s}function he(n,e){let t=n[0]?.length??0,r=n.length,s=t*r*2,o=new Uint8Array(44+s),i=new DataView(o.buffer),a=(p,m)=>[...m].forEach((l,h)=>i.setUint8(p+h,l.charCodeAt(0)));a(0,"RIFF"),i.setUint32(4,36+s,!0),a(8,"WAVE"),a(12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,r,!0),i.setUint32(24,e,!0),i.setUint32(28,e*r*2,!0),i.setUint16(32,r*2,!0),i.setUint16(34,16,!0),a(36,"data"),i.setUint32(40,s,!0);let u=44;for(let p=0;p<t;p++)for(let m=0;m<r;m++){let l=Math.max(-1,Math.min(1,n[m][p]));i.setInt16(u,l<0?l*32768:l*32767,!0),u+=2}return o}function Le(n,e=y){let t=n.focus!==void 0&&n.focus!==!1,r=typeof n.focus=="object"?n.focus:{},s=Ue(r.voiceprint)?.embedding,o=n.spot?.words.map(O)??[];return{focus:t?{print:s?Array.from(s):null,strength:r.strength??1}:null,cue:n.cue===void 0||n.cue===null?null:n.cue!==!1,speech:{...T,...typeof n.cue=="object"?n.cue:{}},normalize:n.normalize??!1,trace:!!n.trace,rate:e,spot:o.length?{words:o.map(i=>i.toJSON()),context:n.spot?.context??"anywhere"}:null}}function Ue(n){return n?n instanceof E?n:E.fromJSON(n):null}var N=class{constructor(e,t={}){this.opts=t;this.core=e.processor(Le(t))}core;closed=!1;push(e){if(this.closed)throw new Error("push after end");return this.core.push(e)}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()}},X=16e3;function me(n,e,t={}){let{onProgress:r,signal:s,...o}=t,i=new N(n,o),a=[];try{for(let h=0;h<e.length;h+=X)s?.throwIfAborted(),a.push(i.push(e.subarray(h,Math.min(e.length,h+X)))),r?.({done:Math.min(e.length,h+X),total:e.length});a.push(i.end())}finally{i.release()}let u=new Float32Array(e.length),p=0;for(let h of a)u.set(h.audio.subarray(0,u.length-p),p),p+=h.audio.length;let m=e,l=a.reduce((h,f)=>({speech:[...h.speech,...f.speech],wakes:[...h.wakes,...f.wakes],diag:[...h.diag,...f.diag],trace:f.trace||h.trace?{focus:[...h.trace?.focus??[],...f.trace?.focus??[]],cue:[...h.trace?.cue??[],...f.trace?.cue??[]],spot:[...h.trace?.spot??[],...f.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:o.focus?u:e,raw:m,...l,toWav(h="audio"){return he(h==="both"?[m,this.audio]:[h==="raw"?m:this.audio],y)}}}function de(n){let e=new Map,t=new Map,r=(s,o,i)=>{let a=s.get(o);if(!a)throw new Error(`${i} ${o} is closed, or its worker was started again`);return a};return{embed:(s,o)=>n().timbre().embed(s,o??"raw"),learnerOpen:(s,o)=>{let i=n().learner("raw",o);return e.set(s,i),{progress:i.progress(),ready:i.ready(),voiceprint:i.voiceprint(!0)}},learnerOffer:(s,o)=>{let i=r(e,s,"learner");return{...i.offer(n().timbre(),o),voiceprint:i.voiceprint(!0)}},learnerForget:s=>(e.get(s)?.forget(),null),learnerClose:s=>(e.get(s)?.release(),e.delete(s),null),phonemize:(s,o)=>n().lex().phonemize(s,o),compile:(s,o)=>n().compile(s,o.lang===void 0?[]:[o.lang].flat(),o.chain).word,process:(s,o,i)=>{let a=me(n(),s,{...o,onProgress:i});return{audio:a.audio,raw:a.raw,speech:a.speech,wakes:a.wakes,diag:a.diag,trace:a.trace}},streamOpen:(s,o)=>(t.set(s,new N(n(),o)),null),streamPush:(s,o)=>r(t,s,"stream").push(o),streamEnd:s=>{let o=r(t,s,"stream");return t.delete(s),o.end()}}}var S=256,Ot=S+2,fe=-1;var ke=new Map,v=null,g=(n,e=[])=>self.postMessage(n,e);async function We(n){v=new H(await j.create(n),e=>{let t=ke.get(e);if(!t)throw new Error(`model ${e} not sent`);return t})}var Ie=100,ze=125,_=new Map;function we(n,e){let t=n.shift;typeof e.start=="number"&&(e.start+=t),typeof e.end=="number"&&(e.end+=t),typeof e.at=="number"&&(e.at+=t);let r=e.data;e.type==="diag"&&typeof r?.start=="number"&&typeof r.end=="number"&&(r.start+=t,r.end+=t),n.events.push(e)}var ye=n=>n.map(e=>O(e).toJSON()),ve=n=>n?{word:O(n.word).toJSON(),takes:n.takes}:null;function De(n,e,t,r){let s=e.pipeline!=="wake"&&e.pipeline!=="enroll",o=v.pipeline({chain:s?e.chain??{}:null,verify:!!(e.verify&&t),learn:!!(e.learn&&t),keepRecent:e.keepRecent??0,trace:!!e.trace,stats:!!e.stats,output:e.output??null,words:ye(e.words??[]),context:e.context??"anywhere",enroll:ve(e.enroll),turn:e.turn??!1,interrupt:e.interrupt??!1}),i={id:n,port:null,closed:!1,timer:setInterval(()=>je(i),Ie),opts:e,p:o,events:[],shift:0,timing:{n:0,sum:0,max:0,slow:0},bg:t,out:r,recordId:null};return t&&e.verify&&t.addEventListener("message",a=>{a.data.type!=="verified"||i.closed||(i.p.verified(a.data.key,a.data.same,a.data.score),Q(i))}),_.set(n,i),i}function be(n,e,t){n.out?n.out.postMessage(e,t):g({...e,kind:e.type,type:"pcm",input:n.id},t)}function Q(n){for(let e of n.p.outs())switch(e[0]){case"event":we(n,e[1]);break;case"window":n.bg?.postMessage({type:"window",pcm:e[1],farQuietMs:e[2],t:e[3]},[e[1].buffer]);break;case"verify":n.bg?.postMessage({type:"verify",key:e[1],pcm:e[2]},[e[2].buffer]);break;case"audio":be(n,{type:"audio",pcm:e[1].buffer},[e[1].buffer]);break;case"utterance":be(n,{type:"utterance",pcm:e[1].buffer,start:e[2]+n.shift,end:e[3]+n.shift,...e[4]&&{level:e[4]}},[e[1].buffer]);break;case"record":g({type:"reply",id:n.recordId,result:e[1]},[e[1].buffer]),n.recordId=null}}function Je(n,e){let t=!v.has("spot")&&n.port;t&&n.port.postMessage({pause:!0});try{return e()}finally{t&&n.port.postMessage({pause:!1})}}function He(n,e,t){let r=new Float32Array(e),s=r.subarray(0,S);if(r[S+1]===fe){n.p.raw(s),Q(n),t.postMessage(e,[e]);return}let o=performance.now(),i=n.p.step(s,r[S]),a=performance.now()-o;r.set(i),t.postMessage(e,[e]),Q(n),$e(n,a)}function $e(n,e){let t=n.timing;if(t.n++,t.sum+=e,t.max=Math.max(t.max,e),e>S/y*1e3&&t.slow++,t.n<ze)return;let r=n.p.chained;we(n,{type:"diag",code:"timing",level:t.slow>t.n/10?"warn":"info",data:{meanMs:+(t.sum/t.n).toFixed(2),maxMs:+t.max.toFixed(1),slow:t.slow,asleep:r&&n.p.sleeping,gainDb:r?+n.p.gainDb.toFixed(1):0}}),n.timing={n:0,sum:0,max:0,slow:0}}function je(n){n.events.length&&(g({type:"events",input:n.id,list:n.events}),n.events=[])}var ge=de(()=>v),M=new Map,Qe=(n,e)=>g({type:"event",input:n,event:e});function Be(n,e,t,r){let s=M.get(n);if(!s)return;let o=performance.now(),i=s.coach.window(v.timbre(),e,t,r),a=Math.round(performance.now()-o);for(let u of i)u[0]==="print"?s.port.postMessage({type:"print",embedding:u[1]}):(u[1].type==="diag"&&(u[1].data.ms=a),Qe(n,u[1]))}function qe({id:n,method:e,args:t,progress:r}){switch(e){case"process":return ge.process(t[0],t[1],r?s=>g({type:"progress",id:n,p:s}):void 0);case"embed":case"learnerOpen":case"learnerOffer":case"learnerForget":case"learnerClose":case"phonemize":case"compile":case"streamOpen":case"streamPush":case"streamEnd":return ge[e](...t);case"learner":{let s=M.get(t[0]);if(!s)throw new Error("no learning port for this input");return{progress:s.coach.learner(t[1]??null)}}case"forget":return M.get(t[0])?.coach.forget(),null;case"record":{let s=_.get(t[0]);if(!s)throw new Error("no input");s.p.record(t[1]),s.recordId=n;return}case"recent":return _.get(t[0])?.p.recent()??null;case"stats":return _.get(t[0])?.p.stats()??null;default:throw new Error(`unknown method ${e}`)}}function Y(n){let e=_.get(n);e&&(e.closed=!0,e.port?.close(),e.bg?.close(),clearInterval(e.timer),e.p.release(),_.delete(n)),M.get(n)?.port.close(),M.get(n)?.coach.release(),M.delete(n)}self.onmessage=async n=>{let e=n.data;try{switch(e.type){case"boot":await We(e.module),g({type:"booted"});break;case"models":for(let[t,r]of Object.entries(e.models))ke.set(t,new Uint8Array(r));g({type:"reply",id:e.id,result:!0});break;case"realtime":{Y(e.input);let t=De(e.input,e.opts,e.bg??null,e.out??null);e.bg&&(e.bg.onmessage=r=>{r.data.type==="print"&&!t.closed&&t.p.set({print:r.data.embedding})}),g({type:"reply",id:e.id,result:!0});break}case"worklet":{let t=_.get(e.input),r=e.port;if(!t)break;t.port=r,r.onmessage=s=>{t.closed||(s.data instanceof ArrayBuffer?He(t,s.data,r):typeof s.data?.clock=="number"&&(t.shift=s.data.clock/y-t.p.time))};break}case"rt-port":{Y(e.input);let t={coach:v.coach(e.ref??null),port:e.port};M.set(e.input,t),t.port.onmessage=r=>{r.data.type==="window"?Be(e.input,r.data.pcm,r.data.farQuietMs,r.data.t):r.data.type==="verify"&&t.port.postMessage({type:"verified",key:r.data.key,...t.coach.verify(v.timbre(),r.data.pcm)})};break}case"set":{let t=_.get(e.input);if(!t)break;let r={};"strength"in e&&(r.strength=e.strength),"enabled"in e&&(r.enabled=e.enabled),"print"in e&&(r.print=e.print),"words"in e&&Object.assign(r,{words:ye(e.words),context:e.context??"anywhere"}),"enroll"in e&&(r.enroll=ve(e.enroll)),"listen"in e&&(r.listen=e.listen),"hold"in e&&(r.hold=e.hold),"words"in e||"enroll"in e&&e.enroll?Je(t,()=>{t.p.spot(v.model("spot")),t.p.set(r)}):t.p.set(r),Q(t);break}case"dispose":Y(e.input);break;case"call":{let t=qe(e);t!==void 0&&g({type:"reply",id:e.id,result:t});break}}}catch(t){let r=String(t?.message??t);e.id!==void 0?g({type:"reply",id:e.id,error:{message:r,code:t?.code}}):g({type:"events",input:e.input,list:[{type:"diag",code:"worker.error",level:"warn",data:{message:r,on:e.type}}]})}};
1
+ var g=(n,e)=>()=>(n&&(e=n(n=0)),e);var _,T=g(()=>{"use strict";_=class extends Error{constructor(t,r,a){super(r);this.code=t;this.cause=a}name="AlkoveError"}});var ie,le=g(()=>{"use strict";ie={focus:{name:"alkove-focus-1",file:"alkove-focus-1.alk",bytes:2320032,sha256:"25028c1f9faf765ccab4076716b5e8a8e756cd7662babd2bc078951982df5ce4",revision:"bb6db3ecd63f322565c1b625635c762b1a5797cd"},cue:{name:"alkove-cue-1",file:"alkove-cue-1.alk",bytes:1334468,sha256:"b5b7b3e239203eac95bb4510ae7a9c057e79959926dfb64665f46eccc1e4d3de",revision:"0b404bbf29f3480ad7539de8bcbf36ea4b89a5b5"},spot:{name:"alkove-spot-1",file:"alkove-spot-1.alk",bytes:553664,sha256:"946110dd1bd3ff9092d551c1f8d828dbe3e1f0cc9c1e00f63cfe7400ef6e66cd",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-fr":{name:"alkove-spot-1",file:"alkove-spot-1-fr.alk",bytes:339107,sha256:"4a203e4cc5499ff0f1dfa8741058a6313067faa919ea61b9455ee7b2d8be91b4",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-en":{name:"alkove-spot-1",file:"alkove-spot-1-en.alk",bytes:339107,sha256:"52bf84fbed6728cb2a604ad04fa00bc901c720774e6a9c7278bcf48e7e3225c7",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-es":{name:"alkove-spot-1",file:"alkove-spot-1-es.alk",bytes:339107,sha256:"2098eb29c1ada3f2da6254ce083133a3e1e2893fec663479cad0b7ab6081d168",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-pt":{name:"alkove-spot-1",file:"alkove-spot-1-pt.alk",bytes:339107,sha256:"84803c861590c8698214edf4a55a47f58a1c7a518eebf6b4a75511d600866ce9",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-it":{name:"alkove-spot-1",file:"alkove-spot-1-it.alk",bytes:339107,sha256:"573a65d7f96c4bf4a78192530f68cb8776d434e6699e7c3d97e6edf60278803d",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-ca":{name:"alkove-spot-1",file:"alkove-spot-1-ca.alk",bytes:339107,sha256:"1d2adb0ec5855f627cdab8e974cbb67088a1a46189572acdee3d39f0953df1ba",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-ro":{name:"alkove-spot-1",file:"alkove-spot-1-ro.alk",bytes:339107,sha256:"73991a8e2c9e32c9438e64d7715b35af08cee033ae434ed9fe4d6e6b518581e3",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-de":{name:"alkove-spot-1",file:"alkove-spot-1-de.alk",bytes:339107,sha256:"4a3bba1d1a5da91998510c5dd7fdf7800390825f24ea33edadd433ede81722bf",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-nl":{name:"alkove-spot-1",file:"alkove-spot-1-nl.alk",bytes:339107,sha256:"717ecc565d224254ce43a6fddfc259c7b3099011f10ef20af29c4b925cf67285",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-pl":{name:"alkove-spot-1",file:"alkove-spot-1-pl.alk",bytes:339107,sha256:"891cb9c5596876975c2ea7b7023ac94c4c4972b6441cca902925eb31dcf6038a",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-sv":{name:"alkove-spot-1",file:"alkove-spot-1-sv.alk",bytes:339107,sha256:"fdbe462b8fca971c90f727c3494286ad849a914d9271903be818a35040b72f5e",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-lang":{name:"alkove-spot-1",file:"alkove-spot-1-lang.alk",bytes:264161,sha256:"69b8bbb2d788c54056eefbf534d8fc2dab1e1215684a1a8dc3a5fdbaae6f147b",revision:"18c30629f26ffcfba5987663c144471b23a08945"},timbre:{name:"alkove-timbre-1",file:"alkove-timbre-1.alk",bytes:970064,sha256:"fc94dfff533f1a4fb2abea172c1f5ff7a92cc00c6331275ea1a26e38f877b0e8",revision:"c4770d4575c7e37306708351b18b39fb211b2c14"},"lex-fr":{name:"alkove-lex-1",file:"alkove-lex-1-fr.alk",bytes:1252088,sha256:"280f64fa48509f44893ec13a7000ebf321c54fd4d732f0bffd173777bc8847b5",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-en":{name:"alkove-lex-1",file:"alkove-lex-1-en.alk",bytes:1465760,sha256:"37029e330b7afc3984784a39e4577f6a0e0cb33037adb8070cbd283d06cbabe0",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-es":{name:"alkove-lex-1",file:"alkove-lex-1-es.alk",bytes:386680,sha256:"01ba0aeb04b7d4cfe216e620d65f009849ef4ab841f8ce98b9a20e35df07dcf1",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-pt":{name:"alkove-lex-1",file:"alkove-lex-1-pt.alk",bytes:1470971,sha256:"1af83d0d607c16972e05c990ea7c803ce614a6df4ea93a001cbc55748c4a4c85",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-it":{name:"alkove-lex-1",file:"alkove-lex-1-it.alk",bytes:1190010,sha256:"0a88b0616927675f588ae7a81a3b25813a642d10534ff5dc475d796c57e7387b",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-ca":{name:"alkove-lex-1",file:"alkove-lex-1-ca.alk",bytes:1157080,sha256:"4b6f0bb9dcbadfd0efaf4065acde4b974b59e5502f1ecd8818332d0189253b8a",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-ro":{name:"alkove-lex-1",file:"alkove-lex-1-ro.alk",bytes:369425,sha256:"6c49c0bfb3b9ac55f6483b0ec0e05cd62ba975a32923dff794a4a76a0dfa7d45",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-de":{name:"alkove-lex-1",file:"alkove-lex-1-de.alk",bytes:1356248,sha256:"64ed6add4fb369f1b1a9a43c1028d570d1ae740e37a2163417bbe6d9fa997d88",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-nl":{name:"alkove-lex-1",file:"alkove-lex-1-nl.alk",bytes:1147472,sha256:"5e05ffd8ac66047cd1049dc1aa98c1b9ef086eb94fc575eb8440a5beef1db683",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-pl":{name:"alkove-lex-1",file:"alkove-lex-1-pl.alk",bytes:395038,sha256:"f4250c033c1555d8076bd7b15884741accde3f88a751ae44f08972de88e89de4",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-sv":{name:"alkove-lex-1",file:"alkove-lex-1-sv.alk",bytes:1171030,sha256:"58fd5c019711e2604f204618d79bd0c744bb31acda6af45cd758699a7b945f56",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"}}});var A,ce,ue,U,F,E=g(()=>{"use strict";le();A=16e3,ce=ie,ue={chunk:256,print:192,lag:256},U=n=>`${ce[n].name}@${ce[n].sha256.slice(0,12)}`,F={model:U("timbre"),window:24e3,min:1400,max:32e3,dim:192}});function Ge(n){let e=de.get(n);if(!e){let t=Object.entries({...je,...Qe[n]??{}}).map(([r,a])=>[r.normalize("NFD"),a.normalize("NFD")]);de.set(n,e=new Map(t))}return e}function he(n){let e=[];for(let t of n.normalize("NFD")){if(/\p{M}/u.test(t)){t==="\u0303"&&e.length&&(e[e.length-1]+=t);continue}e.push(t)}return e}function fe(n,e=""){let t=Ge(e),r=[];for(let a of he(n.replace(/\([^)]*\)/g," ").replace(/‍/g,"").replace(/\s+/g," ")))if(!Be.has(a))for(let o of he(t.get(a)??a)){o=t.get(o)??o;let s=ee.get(o);if(!s)return null;r[r.length-1]!==s&&r.push(s)}return r}var me,ee,wt,je,Qe,Be,qe,pe,de,be=g(()=>{"use strict";me=["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","\xE7","\u028F","\u028B","\u0255","\u0291","\u0267","\u0289"].map(n=>n.normalize("NFD")),ee=new Map(me.map((n,e)=>[n,e+1])),wt=ee.get("\u0259"),je={"\u1D7B":"\u026A",\u025A:"\u0259\u0279",\u025D:"\u025C\u0279",\u029D:"j",\u025F:"\u0261",c:"k",\u026B:"l",\u026C:"l",\u03C7:"x",\u0266:"h",\u0271:"m",\u027B:"\u0279",\u0280:"\u0281",g:"\u0261",\u0258:"\u0259",\u0275:"\xF8",\u026F:"u",\u0264:"o",q:"k",\u0294:"",\u0252:"\u0254",\u0153\u0303:"\u025B\u0303",\u0278:"f",\u0299:"b"},Qe={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"}},Be=new Set("\u02C8\u02CC\u02D0\u02D1\u203F-.|\u02B2\u02B0\u02B7' "),qe=[["e","\u025B"],["o","\u0254"],["\xF8","\u0153","\u0259"],["i","j"],["u","w"],["y","\u0265"],["\u027E","r"]],pe=me.map((n,e)=>[e+1]);for(let n of qe){let e=n.map(t=>ee.get(t.normalize("NFD")));for(let t of e)for(let r of e)pe[t-1].includes(r)||pe[t-1].push(r)}de=new Map});function S(n){let e=[];for(let t of n)for(let r of t?.phonemes??[]){let a=r.lang||t.lang?.[0];a&&!e.includes(a)&&e.push(a)}return e}var I,L,W=g(()=>{"use strict";T();E();be();I=class n{constructor(e,t,r,a,o,s,i=[]){this.text=e;this.lang=t;this.phonemes=r;this.thresholds=a;this.calibrated=o;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:e,lang:t,p:r})=>({ipa:e,lang:t,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="word")throw new TypeError("not an Alkove word");if(t.spot!==U("spot"))return null;let r=t.phonemes.map(a=>({...a,ids:fe(a.ipa,a.lang)??[]})).filter(a=>a.ids.length);return new n(t.text,t.lang,r,t.thresholds,t.calibrated,t.chain)}},L=n=>{if(n instanceof I)return n;let e=I.fromJSON(n);if(!e)throw new _("word.outdated",`Compiled for another Spot: compile "${typeof n=="string"?JSON.parse(n).text:n.text}" again.`);return e}});var z,ge=g(()=>{"use strict";z=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,t){let r=0;for(;r<e.length;){let a=Math.min(this.size-this.fill,e.length-r);this.buf.set(e.subarray(r,r+a),this.fill),this.fill+=a,r+=a,this.fill===this.size&&(this.fill=0,t(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}}});var D,te=g(()=>{"use strict";D={confidence:.7,exitConfidence:.4,startSecs:.2,stopSecs:.6}});var y,Ke,ke,J,ve=g(()=>{"use strict";E();ge();te();y=ue.chunk,Ke=["silence","forced","wake"],ke=n=>new Uint8Array(n.buffer,n.byteOffset,n.byteLength),J=class{constructor(e,t,r,a={}){this.alk=e;let o={gate:!1,normalize:!0,strength:1,sleep:!0,...a},s={...D,...a.speech},i=a.lowPower===void 0?-1:+a.lowPower,u=(d,l)=>e.x.alk_chain(t.ptr,r.ptr,+o.gate,+o.normalize,+o.sleep,o.strength,s.confidence,s.exitConfidence,s.startSecs,s.stopSecs,d,l,i),p=a.print?Float32Array.from(a.print):null;this.ptr=p?e.with(ke(p),d=>u(d,p.length)):u(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new z(y);mix=new Float32Array(y);focusOut=new Float32Array(y);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 t=this.alk.x;if(!e)t.alk_chain_print(this.ptr,0,0);else{let r=Float32Array.from(e);this.alk.with(ke(r),a=>t.alk_chain_print(this.ptr,a,r.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,t){if(this.hops.pending||e.length!==y)throw new RangeError("step() takes whole hops only");return this.hop(e,t)}push(e,t){let r=new Float32Array(Math.floor((this.hops.pending+e.length)/y)*y),a=0;return this.hops.push(e,o=>{r.set(this.hop(o,t),a),a+=y}),r}hop(e,t){let{alk:r,ptr:a}=this,o=r.x;new Float32Array(r.heap,o.alk_chain_hop(a),y).set(e);let s=o.alk_chain_step(a);this.mix.set(new Float32Array(r.heap,s,y));let i=new Float64Array(r.heap,o.alk_chain_events(a),4*o.alk_chain_event_count(a)).slice();for(let u=0;u<i.length;u+=4){let[p,d,l]=[i[u+1],i[u+2],i[u+3]];switch(i[u]){case 0:t({type:"speechstart",start:p});break;case 1:t({type:"speechend",start:p,end:d});break;case 2:t({type:"idle",asleep:p===1,at:d});break;case 3:t({type:"diag",code:"focus.print",level:"info",data:{print:p===1,after:d,why:Ke[l]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(r.heap,o.alk_chain_focus(a),y)),this.onFocus(this.focusOut,p));break;case 6:this.onCue?.(p,d);break;case 10:t({type:"diag",code:"focus.mode",level:p===1&&d===1?"info":"warn",data:{focus:p===1,separator:d===1,threads:l}})}}return this.mix}}});function Ze(n){let e=[],t=[],r=0,a=()=>{e.length&&(t.push(Uint8Array.from(e)),r+=e.length,e.length=0)},o=l=>{a(),t.push(l),r+=l.length},s=l=>e.push(l&255,l>>>8&255,l>>>16&255,l>>>24),i=l=>{let b=Xe.encode(l);s(b.length),o(b)},u=l=>{if(l==null)e.push(0);else if(typeof l=="boolean")e.push(l?2:1);else if(typeof l=="number")e.push(3),o(new Uint8Array(Float64Array.of(l).buffer));else if(typeof l=="string")e.push(4),i(l);else if(l instanceof Uint8Array)e.push(7),s(l.length),o(l.slice());else if(l instanceof Float32Array)e.push(8),s(l.length),o(new Uint8Array(l.slice().buffer));else if(Array.isArray(l)||ArrayBuffer.isView(l)){let b=Array.from(l);e.push(5),s(b.length);for(let m of b)u(m)}else{let b=Object.entries(l).filter(([,m])=>m!==void 0);e.push(6),s(b.length);for(let[m,k]of b)i(m),u(k)}};u(n),a();let p=new Uint8Array(r),d=0;for(let l of t)p.set(l,d),d+=l.length;return p}function et(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0,r=()=>(t+=4,e.getUint32(t-4,!0)),a=()=>{let s=r();return t+=s,Ye.decode(n.subarray(t-s,t))},o=()=>{switch(n[t++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return t+=8,e.getFloat64(t-8,!0);case 4:return a();case 5:return Array.from({length:r()},o);case 6:return Object.fromEntries(Array.from({length:r()},()=>[a(),o()]));case 7:{let s=r();return t+=s,n.slice(t-s,t)}case 8:{let s=r();return t+=4*s,new Float32Array(n.slice(t-4*s,t).buffer)}default:throw new Error("bad value from the core")}};return o()}function f(n,e){let t=Ze(e),r=n.x.alk_value_in(t.length);new Uint8Array(n.heap,r,t.length).set(t)}function h(n,e){let t=et(new Uint8Array(n.heap,n.x.alk_value_out(),n.x.alk_value_len()).slice());if(e>=0)return t;let r=t;throw r.kind==="TypeError"?new TypeError(r.message):r.kind==="RangeError"?new RangeError(r.message):r.kind==="AlkoveError"?new _(r.code,r.message):new Error(r.message)}function ye(n,e,t,r,a){return f(n,{text:t,lang:r,chain:a}),h(n,n.x.alk_compile(e?.handle??0))}function we(n,e,t,r){return f(n,{spec:t,langs:r}),h(n,n.x.alk_commands(e.handle))}function _e(n,e,t,r,a,o){f(n,o);let s=h(n,w(n,a,(i,u)=>n.x.alk_recording_print(e.ptr,t.ptr,r.ptr,i,u)));return s?Array.from(s):null}function xe(n,e){return f(n,e),h(n,n.x.alk_voiceprint())}var Xe,Ye,c,w,$,R,H,j,Q,B,q,G,K,Ae=g(()=>{"use strict";T();Xe=new TextEncoder,Ye=new TextDecoder;c=n=>{if(!n)throw new Error("used after release");return n},w=(n,e,t)=>n.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=>t(r,e.length)),$=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_lex(t.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,t){return f(this.alk,{texts:e,lang:t}),h(this.alk,this.alk.x.alk_lex_phonemize(c(this.ptr)))}add(e){h(this.alk,this.alk.x.alk_lex_add(c(this.ptr),e.ptr))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}},R=class{constructor(e,t,r){this.alk=e;this.ptr=e.x.alk_spot(t.ptr,r.ptr),this.ptr||e.fail("spot")}ptr;langs=[];all=[];head=!1;get handle(){return c(this.ptr)}add(e){let t=h(this.alk,this.alk.x.alk_spot_add(c(this.ptr),e.ptr));return this.langs.includes(t)||this.langs.push(t),this.all.includes(t)||this.all.push(t),t}addLangs(e){let t=e.filter(r=>!this.all.includes(r));t.length&&(f(this.alk,t),h(this.alk,this.alk.x.alk_spot_langs(c(this.ptr))),this.all.push(...t))}setLang(e){h(this.alk,this.alk.x.alk_spot_lang(c(this.ptr),e.ptr)),this.head=!0}release(){this.ptr&&this.alk.x.alk_spot_free(this.ptr),this.ptr=0}};H=class{constructor(e,t,r){this.alk=e;f(e,r),this.ptr=e.x.alk_processor(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.handle??0,t.timbre?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:t}=this.alk,r=h(this.alk,e),a=new Float32Array(this.alk.heap,t.alk_processor_audio(c(this.ptr)),t.alk_processor_audio_len(c(this.ptr))).slice(),{start:o,...s}=r;return{start:o,audio:a,...s}}push(e){return this.part(w(this.alk,e,(t,r)=>this.alk.x.alk_processor_push(c(this.ptr),t,r)))}end(){return this.part(this.alk.x.alk_processor_end(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},j=class{constructor(e,t,r,a){this.alk=e;f(e,{words:r,context:a}),this.ptr=e.x.alk_listener(t.handle),this.ptr||e.fail("listener")}ptr;setWords(e,t){f(this.alk,{words:e,context:t}),h(this.alk,this.alk.x.alk_listener_words(c(this.ptr)))}push(e){return h(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_listener_push(c(this.ptr),t,r)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},Q=class{constructor(e,t,r,a,o){this.alk=e;f(e,{word:r,takes:a,chain:o}),this.ptr=e.x.alk_enroller(t.handle),this.ptr||e.fail("enroller")}ptr;push(e){return h(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_enroller_push(c(this.ptr),t,r)))}result(){return h(this.alk,this.alk.x.alk_enroller_result(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},B=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_timbre(t.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return h(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_timbre_windows(c(this.ptr),t,r)))}embed(e,t){return f(this.alk,{source:t}),h(this.alk,w(this.alk,e,(r,a)=>this.alk.x.alk_timbre_embed(c(this.ptr),r,a)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};q=class{constructor(e,t,r){this.alk=e;f(e,{source:t,start:r}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,t){return h(this.alk,w(this.alk,t,(r,a)=>this.alk.x.alk_learner_learn(c(this.ptr),e.handle,r,a)))}offer(e,t){return h(this.alk,w(this.alk,t,(r,a)=>this.alk.x.alk_learner_offer(c(this.ptr),e.handle,r,a)))}progress(){return h(this.alk,this.state()).progress}ready(){return h(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(c(this.ptr))}voiceprint(e=!1){return h(this.alk,this.alk.x.alk_learner_voiceprint(c(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(c(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},G=class{constructor(e,t,r){this.alk=e;f(e,r),this.ptr=e.x.alk_pipeline(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.handle??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,t){let{alk:r}=this,a=c(this.ptr);new Float32Array(r.heap,r.x.alk_pipeline_hop(a),256).set(e);let o=r.x.alk_pipeline_step(a,t);return this.out.set(new Float32Array(r.heap,o,256)),this.out}spent(e){this.alk.x.alk_pipeline_spent(c(this.ptr),e)}spot(e){h(this.alk,this.alk.x.alk_pipeline_spot(c(this.ptr),e.handle))}timbre(e){this.alk.x.alk_pipeline_timbre(c(this.ptr),e.ptr)<0&&this.alk.fail("pipeline.timbre")}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(c(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(c(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(c(this.ptr))?h(this.alk,this.alk.x.alk_pipeline_outs(c(this.ptr))):[]}verified(e,t,r){this.alk.x.alk_pipeline_verified(c(this.ptr),e,+t,r)}set(e){f(this.alk,e),h(this.alk,this.alk.x.alk_pipeline_set(c(this.ptr)))}record(e){h(this.alk,this.alk.x.alk_pipeline_record(c(this.ptr),e))}recent(){return h(this.alk,this.alk.x.alk_pipeline_recent(c(this.ptr)))}stats(){return h(this.alk,this.alk.x.alk_pipeline_stats(c(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(c(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(c(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(c(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(c(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(c(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},K=class{constructor(e,t){this.alk=e;f(e,{reference:t}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return f(this.alk,{start:e}),h(this.alk,this.alk.x.alk_coach_learner(c(this.ptr)))}forget(){this.alk.x.alk_coach_forget(c(this.ptr))}window(e,t,r,a){return h(this.alk,w(this.alk,t,(o,s)=>this.alk.x.alk_coach_window(c(this.ptr),e.handle,o,s,r,a)))}verify(e,t){return h(this.alk,w(this.alk,t,(r,a)=>this.alk.x.alk_coach_verify(c(this.ptr),e.handle,r,a)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}}});var X,Me=g(()=>{"use strict";T();W();ve();Ae();X=class{constructor(e,t){this.alk=e;this.bytes=t}models=new Map;calls=new Map;lexer=null;spotter=null;bare=null;voices=null;has(e){return this.models.has(e)}model(e){let t=this.models.get(e);return t||this.models.set(e,t=this.alk.model(this.bytes(e))),t}langModel(e){try{return this.model(e)}catch(t){throw new _("models.missing",`${e} was not loaded: load the languages the words use.`,t)}}stream(e){return this.model(e).session()}chain(e){return new J(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let t=!!e.focus,r=e.spot?this.bareSpot(S(e.spot.words??[])):void 0,a={focus:t?this.model("focus"):void 0,cue:t||e.cue?this.model("cue"):void 0,spot:r,timbre:t?this.model("timbre"):void 0};return new H(this.alk,a,e)}recordingPrint(e,t){return _e(this.alk,this.model("focus"),this.model("cue"),this.model("timbre"),e,t)}listener(e,t){return new j(this.alk,this.bareSpot(S(e)),e,t)}enroller(e,t,r){return new Q(this.alk,this.bareSpot(S([e])),e,t,r)}lex(e){for(let t of e)this.lexer?this.lexer.add(this.langModel(`lex-${t}`)):this.lexer=new $(this.alk,this.langModel(`lex-${t}`));if(!this.lexer)throw new _("models.missing","Lex needs a language.");return this.lexer}spot(e,t=[]){let r=this.tops(this.spotter??=new R(this.alk,this.model("cue"),this.model("spot")),e);if(r.addLangs(t),!r.head&&r.all.length>1){let a=this.sent("spot-lang");a&&r.setLang(a)}return r}bareSpot(e){return this.tops(this.bare??=new R(this.alk,this.model("cue"),this.model("spot")),e)}tops(e,t){for(let r of t)e.langs.includes(r)||e.add(this.langModel(`spot-${r}`));return e}sent(e){try{return this.model(e)}catch{return null}}timbre(){return this.voices??=new B(this.alk,this.model("timbre"))}learner(e,t){return new q(this.alk,e,t)}pipeline(e){let t=!!e.chain,r=[...e.words??[],...e.enroll?[e.enroll.word]:[]],a=e.langs??[],o=r.length||a.length?this.spot(S(r),a):void 0,s=new G(this.alk,{focus:t?this.model("focus"):void 0,cue:t?this.model("cue"):void 0,spot:o},e);return t&&s.timbre(this.model("timbre")),s}coach(e){return new K(this.alk,e)}voiceprint(e){return xe(this.alk,e)}compile(e,t,r){return ye(this.alk,/^\s*\/.+\/\s*$/.test(e)?null:this.lex(t),e,t,r)}commands(e,t){return we(this.alk,this.lex(t),e,[...t])}net(e,t){let r=`${e} ${t??""}`,a=this.calls.get(r);a||this.calls.set(r,a=this.model(e).session(t));let o=a;return{run:(s,i)=>o.call(s,i),reset:()=>o.reset()}}release(){this.lexer?.release(),this.spotter?.release(),this.bare?.release(),this.voices?.release(),this.lexer=null,this.spotter=null,this.bare=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 N,Y,re,ne,Fe=g(()=>{"use strict";N=class extends Error{},Y=class n{constructor(e){this.x=e}static async create(e){let t=await WebAssembly.instantiate(e,{});return new n(t.exports)}get heap(){return this.x.memory.buffer}with(e,t){let r=this.x.alk_alloc(e.length);new Uint8Array(this.heap,r,e.length).set(e);try{return t(r,e.length)}finally{this.x.alk_free(r,e.length)}}fail(e){let r=this.x.alk_alloc(512);try{let a=this.x.alk_error(r,512);throw new N(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,r,a))}`)}finally{this.x.alk_free(r,512)}}model(e){return new re(this,e)}},re=class{constructor(e,t){this.alk=e;let r=e.x;this.ptr=e.with(t,(s,i)=>r.alk_model(s,i)),this.ptr||e.fail("model");let a=r.alk_alloc(256),o=s=>new TextDecoder().decode(new Uint8Array(e.heap,a,s));try{this.plans=Array.from({length:r.alk_plans(this.ptr)},(s,i)=>{let u=d=>Array.from({length:r.alk_io_count(this.ptr,i,d)},(l,b)=>{let m=o(r.alk_io_name(this.ptr,i,d,b,a,256)),k=r.alk_io_shape(this.ptr,i,d,b,a,64),oe=Array.from(new Uint32Array(e.heap,a,k));return{name:m,dims:oe,size:oe.reduce(($e,He)=>$e*He,1)}}),p=u(0);return{index:i,name:o(r.alk_plan_name(this.ptr,i,a,256)),inputs:p,outputs:u(1),variable:p[r.alk_variable(this.ptr,i)]?.name??null}})}finally{r.alk_free(a,256)}}ptr;plans;session(e){let t=e===void 0?this.plans[0]:this.plans.find(r=>r.name===e);if(!t)throw new N(`no plan named ${e}`);return new ne(this,t)}release(){this.alk.x.alk_model_free(this.ptr)}},ne=class{constructor(e,t){this.model=e;this.plan=t;let{alk:r}=e,a=r.x;this.ptr=a.alk_session(e.ptr,t.index),this.ptr||r.fail("session");let o=new TextEncoder;for(let[s,i]of[[t.inputs,a.alk_input],[t.outputs,a.alk_output]])for(let u of s)this.at.set(u.name,{...u,p:r.with(o.encode(u.name),(p,d)=>i(this.ptr,p,d))})}ptr;at=new Map;io(e){let t=this.at.get(e);if(!t)throw new N(`no tensor named ${e}`);return t}f32(e){let t=this.io(e);return new Float32Array(this.model.alk.heap,t.p,t.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,t=this.plan.outputs.map(r=>r.name)){let{alk:r}=this.model,{variable:a}=this.plan;for(let s of this.plan.inputs){let i=e[s.name];if(!i)throw new N(`missing input ${s.name}`);if(s.name===a)r.x.alk_set_len(this.ptr,i.data.length)!==0&&r.fail(s.name);else if(i.data.length!==s.size)throw new N(`${s.name}: ${i.data.length} values for ${s.size}`);this.f32(s.name).set(i.data)}this.run();let o={};for(let s of t)o[s]={data:this.f32(s).slice(),dims:[...this.io(s).dims]};return o}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}}});function rt(n){let e=new Uint8Array(n.length*2*(F.dim+4)),t=new DataView(e.buffer),r=0;for(let o of n)for(let s of[o.embedding,o.id]){let i=1e-9;for(let u of s)i=Math.max(i,Math.abs(u));t.setFloat32(r,i/127,!0),r+=4;for(let u of s)t.setInt8(r++,Math.round(u/i*127))}let a="";for(let o of e)a+=String.fromCharCode(o);return btoa(a)}function nt(n){let e=atob(n),t=Uint8Array.from(e,s=>s.charCodeAt(0)),r=new DataView(t.buffer),a=[],o=0;for(;o+2*(F.dim+4)<=t.length;){let s=[];for(let i=0;i<2;i++){let u=r.getFloat32(o,!0);o+=4;let p=new Float32Array(F.dim);for(let d=0;d<p.length;d++)p[d]=r.getInt8(o++)*u;s.push(p)}a.push({embedding:s[0],id:s[1],seconds:F.window/A})}return a}var tt,V,Se=g(()=>{"use strict";E();tt=(n,e)=>{let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t},V=class n{constructor(e,t="focus",r=F.model,a=[]){this.centers=e;this.source=t;this.model=r;this.windows=a;if(!e.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(e){return this.closest(e).score}closest(e){let t=e instanceof n?e.centers:[e],r={score:-1,mine:0,theirs:0};for(let a of this.centers)for(let o of t){let s=tt(a.id,o.id);s>r.score&&(r={score:s,mine:a.seconds,theirs:o.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let e=t=>Array.from(t,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(t=>({embedding:e(t.embedding),id:e(t.id),seconds:+t.seconds.toFixed(1)})),...this.windows.length?{windows:rt(this.windows)}:{}}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(t.model!==F.model)return null;let r=t.centers.map(a=>({embedding:Float32Array.from(a.embedding),id:Float32Array.from(a.id),seconds:a.seconds}));return new n(r,t.source,t.model,t.windows?nt(t.windows):[])}static merge(e){return new n(e.flatMap(t=>t.centers),e.every(t=>t.source==="raw")?"raw":"focus")}}});function Ne(n,e){let t=n[0]?.length??0,r=n.length,a=t*r*2,o=new Uint8Array(44+a),s=new DataView(o.buffer),i=(p,d)=>[...d].forEach((l,b)=>s.setUint8(p+b,l.charCodeAt(0)));i(0,"RIFF"),s.setUint32(4,36+a,!0),i(8,"WAVE"),i(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,r,!0),s.setUint32(24,e,!0),s.setUint32(28,e*r*2,!0),s.setUint16(32,r*2,!0),s.setUint16(34,16,!0),i(36,"data"),s.setUint32(40,a,!0);let u=44;for(let p=0;p<t;p++)for(let d=0;d<r;d++){let l=Math.max(-1,Math.min(1,n[d][p]));s.setInt16(u,l<0?l*32768:l*32767,!0),u+=2}return o}var Oe=g(()=>{"use strict"});function Ee(n,e=A){let t=n.focus!==void 0&&n.focus!==!1,r=typeof n.focus=="object"?n.focus:{},a=at(r.voiceprint)?.embedding,o=n.spot?.words.map(L)??[];return{focus:t?{print:a?Array.from(a):null,strength:r.strength??1,lowPower:!!r.lowPower,...r.sample?{sample:Array.from(r.sample)}:{}}:null,cue:n.cue===void 0||n.cue===null?null:n.cue!==!1,speech:{...D,...typeof n.cue=="object"?n.cue:{}},normalize:n.normalize??!1,trace:!!n.trace,rate:e,spot:o.length?{words:o.map(s=>s.toJSON()),context:n.spot?.context??"anywhere"}:null}}function at(n){return!n||n instanceof Float32Array?null:n instanceof V?n:V.fromJSON(n)}function Pe(n,e,t={}){let{onProgress:r,signal:a,...o}=t,s=Ee(o);s.focus&&!s.focus.print&&!s.focus.sample&&(s.focus.print=n.recordingPrint(e,s));let i=new C(n,o,s),u=[];try{for(let m=0;m<e.length;m+=ae)a?.throwIfAborted(),u.push(i.push(e.subarray(m,Math.min(e.length,m+ae)))),r?.({done:Math.min(e.length,m+ae),total:e.length});u.push(i.end())}finally{i.release()}let p=new Float32Array(e.length),d=0;for(let m of u)p.set(m.audio.subarray(0,p.length-d),d),d+=m.audio.length;let l=e,b=u.reduce((m,k)=>({speech:[...m.speech,...k.speech],wakes:[...m.wakes,...k.wakes],diag:[...m.diag,...k.diag],trace:k.trace||m.trace?{focus:[...m.trace?.focus??[],...k.trace?.focus??[]],cue:[...m.trace?.cue??[],...k.trace?.cue??[]],spot:[...m.trace?.spot??[],...k.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:o.focus?p:e,raw:l,...b,toWav(m="audio"){return Ne(m==="both"?[l,this.audio]:[m==="raw"?l:this.audio],A)}}}var C,ae,Le=g(()=>{"use strict";te();W();Se();Oe();E();C=class{constructor(e,t={},r=Ee(t)){this.opts=t;this.core=e.processor(r)}core;closed=!1;push(e){if(this.closed)throw new Error("push after end");return this.core.push(e)}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()}},ae=16e3});function Re(n){let e=new Map,t=new Map,r=(a,o,s)=>{let i=a.get(o);if(!i)throw new Error(`${s} ${o} is closed, or its worker was started again`);return i};return{embed:(a,o)=>n().timbre().embed(a,o??"raw"),learnerOpen:(a,o)=>{let s=n().learner("raw",o);return e.set(a,s),{progress:s.progress(),ready:s.ready(),voiceprint:s.voiceprint(!0)}},learnerOffer:(a,o)=>{let s=r(e,a,"learner");return{...s.offer(n().timbre(),o),voiceprint:s.voiceprint(!0)}},learnerForget:a=>(e.get(a)?.forget(),null),learnerClose:a=>(e.get(a)?.release(),e.delete(a),null),phonemize:(a,o)=>n().lex([o]).phonemize(a,o),compile:(a,o)=>n().compile(a,o.lang===void 0?[]:[o.lang].flat(),o.chain).word,compileCommands:(a,o)=>n().commands(a,o),process:(a,o,s)=>{let i=Pe(n(),a,{...o,onProgress:s});return{audio:i.audio,raw:i.raw,speech:i.speech,wakes:i.wakes,diag:i.diag,trace:i.trace}},streamOpen:(a,o)=>(t.set(a,new C(n(),o)),null),streamPush:(a,o)=>r(t,a,"stream").push(o),streamEnd:a=>{let o=r(t,a,"stream");return t.delete(a),o.end()}}}var Ve=g(()=>{"use strict";Le()});Me();W();Fe();E();Ve();var P=256,Yt=P+2,Ce=-1;var Ie=new Map,M=null,v=(n,e=[])=>self.postMessage(n,e);async function st(n){M=new X(await Y.create(n),e=>{let t=Ie.get(e);if(!t)throw new Error(`model ${e} not sent`);return t})}var ot=100,it=125,x=new Map;function We(n,e){let t=n.shift;typeof e.start=="number"&&(e.start+=t),typeof e.end=="number"&&(e.end+=t),typeof e.at=="number"&&(e.at+=t);let r=e.data;e.type==="diag"&&r&&(typeof r.start=="number"&&(r.start+=t),typeof r.end=="number"&&(r.end+=t)),n.events.push(e)}var ze=n=>n.map(e=>L(e).toJSON()),De=n=>n?{word:L(n.word).toJSON(),takes:n.takes}:null;function lt(n,e,t,r){let a=e.pipeline!=="wake"&&e.pipeline!=="enroll",o=M.pipeline({chain:a?e.chain??{}:null,verify:!!(e.verify&&t),onlyMyVoice:!!(e.onlyMyVoice&&t&&a),learn:!!(e.learn&&t),keepRecent:e.keepRecent??0,trace:!!e.trace,stats:!!e.stats,output:e.output??null,words:ze(e.words??[]),context:e.context??"anywhere",wake:!!e.wake&&a,enroll:De(e.enroll),turn:e.turn??!1,interrupt:e.interrupt??!1,langs:e.langs??[]}),s={id:n,port:null,closed:!1,timer:setInterval(()=>dt(s),ot),opts:e,p:o,events:[],shift:0,timing:{n:0,sum:0,max:0,slow:0},bg:null,out:r,recordId:null};return t&&Je(s,t),x.set(n,s),s}function Je(n,e){n.bg=e,e.onmessage=t=>{n.closed||(t.data.type==="print"?n.p.set({print:t.data.embedding}):t.data.type==="verified"&&(n.opts.verify||n.opts.onlyMyVoice)&&(n.p.verified(t.data.key,t.data.same,t.data.score),Z(n)))}}function Te(n,e,t){n.out?n.out.postMessage(e,t):v({...e,kind:e.type,type:"pcm",input:n.id},t)}function Z(n){for(let e of n.p.outs())switch(e[0]){case"event":We(n,e[1]);break;case"window":n.bg?.postMessage({type:"window",pcm:e[1],farQuietMs:e[2],t:e[3]},[e[1].buffer]);break;case"verify":n.bg?.postMessage({type:"verify",key:e[1],pcm:e[2]},[e[2].buffer]);break;case"audio":Te(n,{type:"audio",pcm:e[1].buffer},[e[1].buffer]);break;case"utterance":Te(n,{type:"utterance",pcm:e[1].buffer,start:e[2]+n.shift,end:e[3]+n.shift,...e[4]&&{level:e[4]}},[e[1].buffer]);break;case"record":v({type:"reply",id:n.recordId,result:e[1]},[e[1].buffer]),n.recordId=null}}function ct(n,e){let t=!M.has("spot")&&n.port;t&&n.port.postMessage({pause:!0});try{return e()}finally{t&&n.port.postMessage({pause:!1})}}function ut(n,e,t){let r=new Float32Array(e),a=r.subarray(0,P);if(r[P+1]===Ce){n.p.raw(a),Z(n),t.postMessage(e,[e]);return}let o=performance.now(),s=n.p.step(a,r[P]),i=performance.now()-o;n.p.spent(i),r.set(s),t.postMessage(e,[e]),Z(n),pt(n,i)}function pt(n,e){let t=n.timing;if(t.n++,t.sum+=e,t.max=Math.max(t.max,e),e>P/A*1e3&&t.slow++,t.n<it)return;let r=n.p.chained;We(n,{type:"diag",code:"timing",level:t.slow>t.n/10?"warn":"info",data:{meanMs:+(t.sum/t.n).toFixed(2),maxMs:+t.max.toFixed(1),slow:t.slow,asleep:r&&n.p.sleeping,gainDb:r?+n.p.gainDb.toFixed(1):0}}),n.timing={n:0,sum:0,max:0,slow:0}}function dt(n){n.events.length&&(v({type:"events",input:n.id,list:n.events}),n.events=[])}var Ue=Re(()=>M),O=new Map,ht=(n,e)=>v({type:"event",input:n,event:e});function mt(n,e,t,r){let a=O.get(n);if(!a)return;let o=performance.now(),s=a.coach.window(M.timbre(),e,t,r),i=Math.round(performance.now()-o);for(let u of s)u[0]==="print"?a.port.postMessage({type:"print",embedding:u[1]}):(u[1].type==="diag"&&(u[1].data.ms=i),ht(n,u[1]))}function ft({id:n,method:e,args:t,progress:r}){switch(e){case"process":return Ue.process(t[0],t[1],r?a=>v({type:"progress",id:n,p:a}):void 0);case"embed":case"learnerOpen":case"learnerOffer":case"learnerForget":case"learnerClose":case"phonemize":case"compile":case"compileCommands":case"streamOpen":case"streamPush":case"streamEnd":return Ue[e](...t);case"learner":{let a=O.get(t[0]);if(!a)throw new Error("no learning port for this input");return{progress:a.coach.learner(t[1]??null)}}case"forget":return O.get(t[0])?.coach.forget(),null;case"record":{let a=x.get(t[0]);if(!a)throw new Error("no input");a.p.record(t[1]),a.recordId=n;return}case"recent":return x.get(t[0])?.p.recent()??null;case"stats":return x.get(t[0])?.p.stats()??null;default:throw new Error(`unknown method ${e}`)}}function se(n){let e=x.get(n);e&&(e.closed=!0,e.port?.close(),e.bg?.close(),clearInterval(e.timer),e.p.release(),x.delete(n)),O.get(n)?.port.close(),O.get(n)?.coach.release(),O.delete(n)}self.onmessage=async n=>{let e=n.data;try{switch(e.type){case"boot":await st(e.module),v({type:"booted"});break;case"models":for(let[t,r]of Object.entries(e.models))Ie.set(t,new Uint8Array(r));v({type:"reply",id:e.id,result:!0});break;case"realtime":se(e.input),lt(e.input,e.opts,e.bg??null,e.out??null),v({type:"reply",id:e.id,result:!0});break;case"learn":{let t=x.get(e.input);if(!t)break;e.bg&&(t.bg?.close(),Je(t,e.bg)),t.bg&&t.p.set({learn:!0});break}case"worklet":{let t=x.get(e.input),r=e.port;if(!t)break;t.port=r,r.onmessage=a=>{t.closed||(a.data instanceof ArrayBuffer?ut(t,a.data,r):typeof a.data?.clock=="number"&&(t.shift=a.data.clock/A-t.p.time))};break}case"rt-port":{se(e.input);let t={coach:M.coach(e.ref??null),port:e.port};O.set(e.input,t),t.port.onmessage=r=>{r.data.type==="window"?mt(e.input,r.data.pcm,r.data.farQuietMs,r.data.t):r.data.type==="verify"&&t.port.postMessage({type:"verified",key:r.data.key,...t.coach.verify(M.timbre(),r.data.pcm)})};break}case"set":{let t=x.get(e.input);if(!t)break;let r={};"strength"in e&&(r.strength=e.strength),"enabled"in e&&(r.enabled=e.enabled),"print"in e&&(r.print=e.print),"words"in e&&Object.assign(r,{words:ze(e.words),context:e.context??"anywhere"}),"enroll"in e&&(r.enroll=De(e.enroll)),"listen"in e&&(r.listen=e.listen),"hold"in e&&(r.hold=e.hold),"commands"in e&&(r.commands=e.commands??[]);let a=(r.commands??[]).map(o=>o.lang);"words"in e||"enroll"in e&&e.enroll||a.length?ct(t,()=>{t.p.spot(M.spot([...S([...r.words??[],...e.enroll?.word?[e.enroll.word]:[]]),...a])),t.p.set(r)}):t.p.set(r),Z(t);break}case"dispose":se(e.input);break;case"call":{let t=ft(e);t!==void 0&&v({type:"reply",id:e.id,result:t});break}}}catch(t){let r=String(t?.message??t);e.id!==void 0?v({type:"reply",id:e.id,error:{message:r,code:t?.code}}):v({type:"events",input:e.input,list:[{type:"diag",code:"worker.error",level:"warn",data:{message:r,on:e.type}}]})}};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h,i}from"./chunk-N4S2422Z.js";import"./chunk-C5QG5BVR.js";import"./chunk-2PTYZFLZ.js";export{b as Alkove,d as Lex,h as Spot,c as Timbre,i as VoiceprintLearner,g as compileCommands,f as compileWord,e as embedAs,a as modelsFor};
package/dist/api.d.ts CHANGED
@@ -1,17 +1,31 @@
1
1
  import { Lex as LexCore, type Pronunciation } from './core/lex';
2
- import { type CompileOptions, type Word } from './core/spot/spot';
2
+ import { type Chain, type CommandSpec, type CommandsJSON, type CompileOptions, type Word, type WordJSON } from './core/spot/spot';
3
3
  import { Enrollment } from './recipes/enroll';
4
4
  import { type CommonOptions } from './recipes/input';
5
- import { type Level, Voiceprint } from './core/timbre';
5
+ import { type Level, type Source, Voiceprint } from './core/timbre';
6
6
  import { configure, onDiag, type Progress } from './loader';
7
- import { type Lang } from './manifest';
8
- import type { ProcessOptions, ProcessPart, ProcessResult } from './process';
7
+ import { type Lang, type ModelName } from './manifest';
8
+ import { type ProcessOptions, type ProcessPart, type ProcessResult } from './process';
9
9
  import { micPermission, supported } from './recipes/mic';
10
+ import type { CallName } from './runtime/calls';
11
+ interface Backend {
12
+ call<T>(name: CallName, args: unknown[], transfer?: Transferable[], onProgress?: (p: {
13
+ done: number;
14
+ total: number;
15
+ }) => void): Promise<T>;
16
+ hold(): () => void;
17
+ }
10
18
  export type Usage = 'call' | 'agent' | 'wake';
11
19
  export interface UsageOptions {
12
20
  voiceprint?: boolean;
13
21
  typedWords?: boolean;
22
+ langs?: Lang[];
23
+ wake?: {
24
+ words: readonly (Word | WordJSON | string)[];
25
+ lang?: Lang | Lang[];
26
+ };
14
27
  }
28
+ export declare function modelsFor(usage: Usage, o?: UsageOptions): ModelName[];
15
29
  export type ProcessInput = Blob | ArrayBuffer | Uint8Array | AudioBuffer | {
16
30
  pcm: Float32Array;
17
31
  rate: number;
@@ -36,9 +50,7 @@ export declare class Timbre {
36
50
  private b;
37
51
  private constructor();
38
52
  static create(): Promise<Timbre>;
39
- embed(pcm: Float32Array, opts?: {
40
- source?: 'raw' | 'focus';
41
- }): Promise<Voiceprint>;
53
+ embed(pcm: Float32Array): Promise<Voiceprint>;
42
54
  verify(a: Voiceprint, b: Voiceprint, opts?: {
43
55
  level?: Level;
44
56
  }): {
@@ -53,20 +65,27 @@ export declare class Timbre {
53
65
  } | null>;
54
66
  }
55
67
  export declare class Lex {
56
- private b;
57
68
  static readonly inventory: string[];
58
- static readonly langs: readonly ["fr", "en", "es", "pt", "it", "ca", "ro"];
69
+ static readonly langs: readonly ["fr", "en", "es", "pt", "it", "ca", "ro", "de", "nl", "pl", "sv"];
59
70
  static readonly distance: typeof LexCore.distance;
60
71
  private constructor();
61
- static create(): Promise<Lex>;
72
+ static create(opts?: {
73
+ langs?: Lang[];
74
+ }): Promise<Lex>;
62
75
  phonemize(text: string, lang: Lang): Promise<Omit<Pronunciation, 'ids'>[]>;
63
76
  phonemize(texts: string[], lang: Lang): Promise<Omit<Pronunciation, 'ids'>[][]>;
64
77
  }
78
+ export declare function embedAs(pcm: Float32Array, source: Source, b?: Backend): Promise<Voiceprint>;
79
+ export declare function compileWord(text: string, lang: CompileOptions['lang'], chain?: Chain): Promise<Word>;
80
+ export declare function compileCommands(spec: CommandSpec, opts: {
81
+ langs: readonly Lang[];
82
+ }): Promise<CommandsJSON[]>;
65
83
  export declare const Spot: {
66
84
  compile(text: string, opts?: CompileOptions): Promise<Word>;
67
- enroll(text: string, opts?: CompileOptions & CommonOptions & {
68
- takes?: number;
69
- }): Enrollment;
85
+ commands(spec: CommandSpec, opts: {
86
+ langs: readonly Lang[];
87
+ }): Promise<CommandsJSON[]>;
88
+ enroll(text: string, opts?: CompileOptions & CommonOptions): Enrollment;
70
89
  };
71
90
  export declare class VoiceprintLearner {
72
91
  private b;
@@ -0,0 +1,2 @@
1
+ var e='var g=(n,e)=>()=>(n&&(e=n(n=0)),e);var _,T=g(()=>{"use strict";_=class extends Error{constructor(t,r,a){super(r);this.code=t;this.cause=a}name="AlkoveError"}});var ie,le=g(()=>{"use strict";ie={focus:{name:"alkove-focus-1",file:"alkove-focus-1.alk",bytes:2320032,sha256:"25028c1f9faf765ccab4076716b5e8a8e756cd7662babd2bc078951982df5ce4",revision:"bb6db3ecd63f322565c1b625635c762b1a5797cd"},cue:{name:"alkove-cue-1",file:"alkove-cue-1.alk",bytes:1334468,sha256:"b5b7b3e239203eac95bb4510ae7a9c057e79959926dfb64665f46eccc1e4d3de",revision:"0b404bbf29f3480ad7539de8bcbf36ea4b89a5b5"},spot:{name:"alkove-spot-1",file:"alkove-spot-1.alk",bytes:553664,sha256:"946110dd1bd3ff9092d551c1f8d828dbe3e1f0cc9c1e00f63cfe7400ef6e66cd",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-fr":{name:"alkove-spot-1",file:"alkove-spot-1-fr.alk",bytes:339107,sha256:"4a203e4cc5499ff0f1dfa8741058a6313067faa919ea61b9455ee7b2d8be91b4",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-en":{name:"alkove-spot-1",file:"alkove-spot-1-en.alk",bytes:339107,sha256:"52bf84fbed6728cb2a604ad04fa00bc901c720774e6a9c7278bcf48e7e3225c7",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-es":{name:"alkove-spot-1",file:"alkove-spot-1-es.alk",bytes:339107,sha256:"2098eb29c1ada3f2da6254ce083133a3e1e2893fec663479cad0b7ab6081d168",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-pt":{name:"alkove-spot-1",file:"alkove-spot-1-pt.alk",bytes:339107,sha256:"84803c861590c8698214edf4a55a47f58a1c7a518eebf6b4a75511d600866ce9",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-it":{name:"alkove-spot-1",file:"alkove-spot-1-it.alk",bytes:339107,sha256:"573a65d7f96c4bf4a78192530f68cb8776d434e6699e7c3d97e6edf60278803d",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-ca":{name:"alkove-spot-1",file:"alkove-spot-1-ca.alk",bytes:339107,sha256:"1d2adb0ec5855f627cdab8e974cbb67088a1a46189572acdee3d39f0953df1ba",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-ro":{name:"alkove-spot-1",file:"alkove-spot-1-ro.alk",bytes:339107,sha256:"73991a8e2c9e32c9438e64d7715b35af08cee033ae434ed9fe4d6e6b518581e3",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-de":{name:"alkove-spot-1",file:"alkove-spot-1-de.alk",bytes:339107,sha256:"4a3bba1d1a5da91998510c5dd7fdf7800390825f24ea33edadd433ede81722bf",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-nl":{name:"alkove-spot-1",file:"alkove-spot-1-nl.alk",bytes:339107,sha256:"717ecc565d224254ce43a6fddfc259c7b3099011f10ef20af29c4b925cf67285",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-pl":{name:"alkove-spot-1",file:"alkove-spot-1-pl.alk",bytes:339107,sha256:"891cb9c5596876975c2ea7b7023ac94c4c4972b6441cca902925eb31dcf6038a",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-sv":{name:"alkove-spot-1",file:"alkove-spot-1-sv.alk",bytes:339107,sha256:"fdbe462b8fca971c90f727c3494286ad849a914d9271903be818a35040b72f5e",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-lang":{name:"alkove-spot-1",file:"alkove-spot-1-lang.alk",bytes:264161,sha256:"69b8bbb2d788c54056eefbf534d8fc2dab1e1215684a1a8dc3a5fdbaae6f147b",revision:"18c30629f26ffcfba5987663c144471b23a08945"},timbre:{name:"alkove-timbre-1",file:"alkove-timbre-1.alk",bytes:970064,sha256:"fc94dfff533f1a4fb2abea172c1f5ff7a92cc00c6331275ea1a26e38f877b0e8",revision:"c4770d4575c7e37306708351b18b39fb211b2c14"},"lex-fr":{name:"alkove-lex-1",file:"alkove-lex-1-fr.alk",bytes:1252088,sha256:"280f64fa48509f44893ec13a7000ebf321c54fd4d732f0bffd173777bc8847b5",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-en":{name:"alkove-lex-1",file:"alkove-lex-1-en.alk",bytes:1465760,sha256:"37029e330b7afc3984784a39e4577f6a0e0cb33037adb8070cbd283d06cbabe0",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-es":{name:"alkove-lex-1",file:"alkove-lex-1-es.alk",bytes:386680,sha256:"01ba0aeb04b7d4cfe216e620d65f009849ef4ab841f8ce98b9a20e35df07dcf1",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-pt":{name:"alkove-lex-1",file:"alkove-lex-1-pt.alk",bytes:1470971,sha256:"1af83d0d607c16972e05c990ea7c803ce614a6df4ea93a001cbc55748c4a4c85",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-it":{name:"alkove-lex-1",file:"alkove-lex-1-it.alk",bytes:1190010,sha256:"0a88b0616927675f588ae7a81a3b25813a642d10534ff5dc475d796c57e7387b",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-ca":{name:"alkove-lex-1",file:"alkove-lex-1-ca.alk",bytes:1157080,sha256:"4b6f0bb9dcbadfd0efaf4065acde4b974b59e5502f1ecd8818332d0189253b8a",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-ro":{name:"alkove-lex-1",file:"alkove-lex-1-ro.alk",bytes:369425,sha256:"6c49c0bfb3b9ac55f6483b0ec0e05cd62ba975a32923dff794a4a76a0dfa7d45",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-de":{name:"alkove-lex-1",file:"alkove-lex-1-de.alk",bytes:1356248,sha256:"64ed6add4fb369f1b1a9a43c1028d570d1ae740e37a2163417bbe6d9fa997d88",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-nl":{name:"alkove-lex-1",file:"alkove-lex-1-nl.alk",bytes:1147472,sha256:"5e05ffd8ac66047cd1049dc1aa98c1b9ef086eb94fc575eb8440a5beef1db683",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-pl":{name:"alkove-lex-1",file:"alkove-lex-1-pl.alk",bytes:395038,sha256:"f4250c033c1555d8076bd7b15884741accde3f88a751ae44f08972de88e89de4",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-sv":{name:"alkove-lex-1",file:"alkove-lex-1-sv.alk",bytes:1171030,sha256:"58fd5c019711e2604f204618d79bd0c744bb31acda6af45cd758699a7b945f56",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"}}});var A,ce,ue,U,F,E=g(()=>{"use strict";le();A=16e3,ce=ie,ue={chunk:256,print:192,lag:256},U=n=>`${ce[n].name}@${ce[n].sha256.slice(0,12)}`,F={model:U("timbre"),window:24e3,min:1400,max:32e3,dim:192}});function Ge(n){let e=de.get(n);if(!e){let t=Object.entries({...je,...Qe[n]??{}}).map(([r,a])=>[r.normalize("NFD"),a.normalize("NFD")]);de.set(n,e=new Map(t))}return e}function he(n){let e=[];for(let t of n.normalize("NFD")){if(/\\p{M}/u.test(t)){t==="\\u0303"&&e.length&&(e[e.length-1]+=t);continue}e.push(t)}return e}function fe(n,e=""){let t=Ge(e),r=[];for(let a of he(n.replace(/\\([^)]*\\)/g," ").replace(/\u200D/g,"").replace(/\\s+/g," ")))if(!Be.has(a))for(let o of he(t.get(a)??a)){o=t.get(o)??o;let s=ee.get(o);if(!s)return null;r[r.length-1]!==s&&r.push(s)}return r}var me,ee,wt,je,Qe,Be,qe,pe,de,be=g(()=>{"use strict";me=["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","\\xE7","\\u028F","\\u028B","\\u0255","\\u0291","\\u0267","\\u0289"].map(n=>n.normalize("NFD")),ee=new Map(me.map((n,e)=>[n,e+1])),wt=ee.get("\\u0259"),je={"\\u1D7B":"\\u026A",\\u025A:"\\u0259\\u0279",\\u025D:"\\u025C\\u0279",\\u029D:"j",\\u025F:"\\u0261",c:"k",\\u026B:"l",\\u026C:"l",\\u03C7:"x",\\u0266:"h",\\u0271:"m",\\u027B:"\\u0279",\\u0280:"\\u0281",g:"\\u0261",\\u0258:"\\u0259",\\u0275:"\\xF8",\\u026F:"u",\\u0264:"o",q:"k",\\u0294:"",\\u0252:"\\u0254",\\u0153\\u0303:"\\u025B\\u0303",\\u0278:"f",\\u0299:"b"},Qe={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"}},Be=new Set("\\u02C8\\u02CC\\u02D0\\u02D1\\u203F-.|\\u02B2\\u02B0\\u02B7\' "),qe=[["e","\\u025B"],["o","\\u0254"],["\\xF8","\\u0153","\\u0259"],["i","j"],["u","w"],["y","\\u0265"],["\\u027E","r"]],pe=me.map((n,e)=>[e+1]);for(let n of qe){let e=n.map(t=>ee.get(t.normalize("NFD")));for(let t of e)for(let r of e)pe[t-1].includes(r)||pe[t-1].push(r)}de=new Map});function S(n){let e=[];for(let t of n)for(let r of t?.phonemes??[]){let a=r.lang||t.lang?.[0];a&&!e.includes(a)&&e.push(a)}return e}var I,L,W=g(()=>{"use strict";T();E();be();I=class n{constructor(e,t,r,a,o,s,i=[]){this.text=e;this.lang=t;this.phonemes=r;this.thresholds=a;this.calibrated=o;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:e,lang:t,p:r})=>({ipa:e,lang:t,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="word")throw new TypeError("not an Alkove word");if(t.spot!==U("spot"))return null;let r=t.phonemes.map(a=>({...a,ids:fe(a.ipa,a.lang)??[]})).filter(a=>a.ids.length);return new n(t.text,t.lang,r,t.thresholds,t.calibrated,t.chain)}},L=n=>{if(n instanceof I)return n;let e=I.fromJSON(n);if(!e)throw new _("word.outdated",`Compiled for another Spot: compile "${typeof n=="string"?JSON.parse(n).text:n.text}" again.`);return e}});var z,ge=g(()=>{"use strict";z=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,t){let r=0;for(;r<e.length;){let a=Math.min(this.size-this.fill,e.length-r);this.buf.set(e.subarray(r,r+a),this.fill),this.fill+=a,r+=a,this.fill===this.size&&(this.fill=0,t(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}}});var D,te=g(()=>{"use strict";D={confidence:.7,exitConfidence:.4,startSecs:.2,stopSecs:.6}});var y,Ke,ke,J,ve=g(()=>{"use strict";E();ge();te();y=ue.chunk,Ke=["silence","forced","wake"],ke=n=>new Uint8Array(n.buffer,n.byteOffset,n.byteLength),J=class{constructor(e,t,r,a={}){this.alk=e;let o={gate:!1,normalize:!0,strength:1,sleep:!0,...a},s={...D,...a.speech},i=a.lowPower===void 0?-1:+a.lowPower,u=(d,l)=>e.x.alk_chain(t.ptr,r.ptr,+o.gate,+o.normalize,+o.sleep,o.strength,s.confidence,s.exitConfidence,s.startSecs,s.stopSecs,d,l,i),p=a.print?Float32Array.from(a.print):null;this.ptr=p?e.with(ke(p),d=>u(d,p.length)):u(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new z(y);mix=new Float32Array(y);focusOut=new Float32Array(y);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 t=this.alk.x;if(!e)t.alk_chain_print(this.ptr,0,0);else{let r=Float32Array.from(e);this.alk.with(ke(r),a=>t.alk_chain_print(this.ptr,a,r.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,t){if(this.hops.pending||e.length!==y)throw new RangeError("step() takes whole hops only");return this.hop(e,t)}push(e,t){let r=new Float32Array(Math.floor((this.hops.pending+e.length)/y)*y),a=0;return this.hops.push(e,o=>{r.set(this.hop(o,t),a),a+=y}),r}hop(e,t){let{alk:r,ptr:a}=this,o=r.x;new Float32Array(r.heap,o.alk_chain_hop(a),y).set(e);let s=o.alk_chain_step(a);this.mix.set(new Float32Array(r.heap,s,y));let i=new Float64Array(r.heap,o.alk_chain_events(a),4*o.alk_chain_event_count(a)).slice();for(let u=0;u<i.length;u+=4){let[p,d,l]=[i[u+1],i[u+2],i[u+3]];switch(i[u]){case 0:t({type:"speechstart",start:p});break;case 1:t({type:"speechend",start:p,end:d});break;case 2:t({type:"idle",asleep:p===1,at:d});break;case 3:t({type:"diag",code:"focus.print",level:"info",data:{print:p===1,after:d,why:Ke[l]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(r.heap,o.alk_chain_focus(a),y)),this.onFocus(this.focusOut,p));break;case 6:this.onCue?.(p,d);break;case 10:t({type:"diag",code:"focus.mode",level:p===1&&d===1?"info":"warn",data:{focus:p===1,separator:d===1,threads:l}})}}return this.mix}}});function Ze(n){let e=[],t=[],r=0,a=()=>{e.length&&(t.push(Uint8Array.from(e)),r+=e.length,e.length=0)},o=l=>{a(),t.push(l),r+=l.length},s=l=>e.push(l&255,l>>>8&255,l>>>16&255,l>>>24),i=l=>{let b=Xe.encode(l);s(b.length),o(b)},u=l=>{if(l==null)e.push(0);else if(typeof l=="boolean")e.push(l?2:1);else if(typeof l=="number")e.push(3),o(new Uint8Array(Float64Array.of(l).buffer));else if(typeof l=="string")e.push(4),i(l);else if(l instanceof Uint8Array)e.push(7),s(l.length),o(l.slice());else if(l instanceof Float32Array)e.push(8),s(l.length),o(new Uint8Array(l.slice().buffer));else if(Array.isArray(l)||ArrayBuffer.isView(l)){let b=Array.from(l);e.push(5),s(b.length);for(let m of b)u(m)}else{let b=Object.entries(l).filter(([,m])=>m!==void 0);e.push(6),s(b.length);for(let[m,k]of b)i(m),u(k)}};u(n),a();let p=new Uint8Array(r),d=0;for(let l of t)p.set(l,d),d+=l.length;return p}function et(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0,r=()=>(t+=4,e.getUint32(t-4,!0)),a=()=>{let s=r();return t+=s,Ye.decode(n.subarray(t-s,t))},o=()=>{switch(n[t++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return t+=8,e.getFloat64(t-8,!0);case 4:return a();case 5:return Array.from({length:r()},o);case 6:return Object.fromEntries(Array.from({length:r()},()=>[a(),o()]));case 7:{let s=r();return t+=s,n.slice(t-s,t)}case 8:{let s=r();return t+=4*s,new Float32Array(n.slice(t-4*s,t).buffer)}default:throw new Error("bad value from the core")}};return o()}function f(n,e){let t=Ze(e),r=n.x.alk_value_in(t.length);new Uint8Array(n.heap,r,t.length).set(t)}function h(n,e){let t=et(new Uint8Array(n.heap,n.x.alk_value_out(),n.x.alk_value_len()).slice());if(e>=0)return t;let r=t;throw r.kind==="TypeError"?new TypeError(r.message):r.kind==="RangeError"?new RangeError(r.message):r.kind==="AlkoveError"?new _(r.code,r.message):new Error(r.message)}function ye(n,e,t,r,a){return f(n,{text:t,lang:r,chain:a}),h(n,n.x.alk_compile(e?.handle??0))}function we(n,e,t,r){return f(n,{spec:t,langs:r}),h(n,n.x.alk_commands(e.handle))}function _e(n,e,t,r,a,o){f(n,o);let s=h(n,w(n,a,(i,u)=>n.x.alk_recording_print(e.ptr,t.ptr,r.ptr,i,u)));return s?Array.from(s):null}function xe(n,e){return f(n,e),h(n,n.x.alk_voiceprint())}var Xe,Ye,c,w,$,R,H,j,Q,B,q,G,K,Ae=g(()=>{"use strict";T();Xe=new TextEncoder,Ye=new TextDecoder;c=n=>{if(!n)throw new Error("used after release");return n},w=(n,e,t)=>n.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=>t(r,e.length)),$=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_lex(t.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,t){return f(this.alk,{texts:e,lang:t}),h(this.alk,this.alk.x.alk_lex_phonemize(c(this.ptr)))}add(e){h(this.alk,this.alk.x.alk_lex_add(c(this.ptr),e.ptr))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}},R=class{constructor(e,t,r){this.alk=e;this.ptr=e.x.alk_spot(t.ptr,r.ptr),this.ptr||e.fail("spot")}ptr;langs=[];all=[];head=!1;get handle(){return c(this.ptr)}add(e){let t=h(this.alk,this.alk.x.alk_spot_add(c(this.ptr),e.ptr));return this.langs.includes(t)||this.langs.push(t),this.all.includes(t)||this.all.push(t),t}addLangs(e){let t=e.filter(r=>!this.all.includes(r));t.length&&(f(this.alk,t),h(this.alk,this.alk.x.alk_spot_langs(c(this.ptr))),this.all.push(...t))}setLang(e){h(this.alk,this.alk.x.alk_spot_lang(c(this.ptr),e.ptr)),this.head=!0}release(){this.ptr&&this.alk.x.alk_spot_free(this.ptr),this.ptr=0}};H=class{constructor(e,t,r){this.alk=e;f(e,r),this.ptr=e.x.alk_processor(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.handle??0,t.timbre?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:t}=this.alk,r=h(this.alk,e),a=new Float32Array(this.alk.heap,t.alk_processor_audio(c(this.ptr)),t.alk_processor_audio_len(c(this.ptr))).slice(),{start:o,...s}=r;return{start:o,audio:a,...s}}push(e){return this.part(w(this.alk,e,(t,r)=>this.alk.x.alk_processor_push(c(this.ptr),t,r)))}end(){return this.part(this.alk.x.alk_processor_end(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},j=class{constructor(e,t,r,a){this.alk=e;f(e,{words:r,context:a}),this.ptr=e.x.alk_listener(t.handle),this.ptr||e.fail("listener")}ptr;setWords(e,t){f(this.alk,{words:e,context:t}),h(this.alk,this.alk.x.alk_listener_words(c(this.ptr)))}push(e){return h(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_listener_push(c(this.ptr),t,r)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},Q=class{constructor(e,t,r,a,o){this.alk=e;f(e,{word:r,takes:a,chain:o}),this.ptr=e.x.alk_enroller(t.handle),this.ptr||e.fail("enroller")}ptr;push(e){return h(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_enroller_push(c(this.ptr),t,r)))}result(){return h(this.alk,this.alk.x.alk_enroller_result(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},B=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_timbre(t.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return h(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_timbre_windows(c(this.ptr),t,r)))}embed(e,t){return f(this.alk,{source:t}),h(this.alk,w(this.alk,e,(r,a)=>this.alk.x.alk_timbre_embed(c(this.ptr),r,a)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};q=class{constructor(e,t,r){this.alk=e;f(e,{source:t,start:r}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,t){return h(this.alk,w(this.alk,t,(r,a)=>this.alk.x.alk_learner_learn(c(this.ptr),e.handle,r,a)))}offer(e,t){return h(this.alk,w(this.alk,t,(r,a)=>this.alk.x.alk_learner_offer(c(this.ptr),e.handle,r,a)))}progress(){return h(this.alk,this.state()).progress}ready(){return h(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(c(this.ptr))}voiceprint(e=!1){return h(this.alk,this.alk.x.alk_learner_voiceprint(c(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(c(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},G=class{constructor(e,t,r){this.alk=e;f(e,r),this.ptr=e.x.alk_pipeline(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.handle??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,t){let{alk:r}=this,a=c(this.ptr);new Float32Array(r.heap,r.x.alk_pipeline_hop(a),256).set(e);let o=r.x.alk_pipeline_step(a,t);return this.out.set(new Float32Array(r.heap,o,256)),this.out}spent(e){this.alk.x.alk_pipeline_spent(c(this.ptr),e)}spot(e){h(this.alk,this.alk.x.alk_pipeline_spot(c(this.ptr),e.handle))}timbre(e){this.alk.x.alk_pipeline_timbre(c(this.ptr),e.ptr)<0&&this.alk.fail("pipeline.timbre")}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(c(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(c(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(c(this.ptr))?h(this.alk,this.alk.x.alk_pipeline_outs(c(this.ptr))):[]}verified(e,t,r){this.alk.x.alk_pipeline_verified(c(this.ptr),e,+t,r)}set(e){f(this.alk,e),h(this.alk,this.alk.x.alk_pipeline_set(c(this.ptr)))}record(e){h(this.alk,this.alk.x.alk_pipeline_record(c(this.ptr),e))}recent(){return h(this.alk,this.alk.x.alk_pipeline_recent(c(this.ptr)))}stats(){return h(this.alk,this.alk.x.alk_pipeline_stats(c(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(c(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(c(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(c(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(c(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(c(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},K=class{constructor(e,t){this.alk=e;f(e,{reference:t}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return f(this.alk,{start:e}),h(this.alk,this.alk.x.alk_coach_learner(c(this.ptr)))}forget(){this.alk.x.alk_coach_forget(c(this.ptr))}window(e,t,r,a){return h(this.alk,w(this.alk,t,(o,s)=>this.alk.x.alk_coach_window(c(this.ptr),e.handle,o,s,r,a)))}verify(e,t){return h(this.alk,w(this.alk,t,(r,a)=>this.alk.x.alk_coach_verify(c(this.ptr),e.handle,r,a)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}}});var X,Me=g(()=>{"use strict";T();W();ve();Ae();X=class{constructor(e,t){this.alk=e;this.bytes=t}models=new Map;calls=new Map;lexer=null;spotter=null;bare=null;voices=null;has(e){return this.models.has(e)}model(e){let t=this.models.get(e);return t||this.models.set(e,t=this.alk.model(this.bytes(e))),t}langModel(e){try{return this.model(e)}catch(t){throw new _("models.missing",`${e} was not loaded: load the languages the words use.`,t)}}stream(e){return this.model(e).session()}chain(e){return new J(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let t=!!e.focus,r=e.spot?this.bareSpot(S(e.spot.words??[])):void 0,a={focus:t?this.model("focus"):void 0,cue:t||e.cue?this.model("cue"):void 0,spot:r,timbre:t?this.model("timbre"):void 0};return new H(this.alk,a,e)}recordingPrint(e,t){return _e(this.alk,this.model("focus"),this.model("cue"),this.model("timbre"),e,t)}listener(e,t){return new j(this.alk,this.bareSpot(S(e)),e,t)}enroller(e,t,r){return new Q(this.alk,this.bareSpot(S([e])),e,t,r)}lex(e){for(let t of e)this.lexer?this.lexer.add(this.langModel(`lex-${t}`)):this.lexer=new $(this.alk,this.langModel(`lex-${t}`));if(!this.lexer)throw new _("models.missing","Lex needs a language.");return this.lexer}spot(e,t=[]){let r=this.tops(this.spotter??=new R(this.alk,this.model("cue"),this.model("spot")),e);if(r.addLangs(t),!r.head&&r.all.length>1){let a=this.sent("spot-lang");a&&r.setLang(a)}return r}bareSpot(e){return this.tops(this.bare??=new R(this.alk,this.model("cue"),this.model("spot")),e)}tops(e,t){for(let r of t)e.langs.includes(r)||e.add(this.langModel(`spot-${r}`));return e}sent(e){try{return this.model(e)}catch{return null}}timbre(){return this.voices??=new B(this.alk,this.model("timbre"))}learner(e,t){return new q(this.alk,e,t)}pipeline(e){let t=!!e.chain,r=[...e.words??[],...e.enroll?[e.enroll.word]:[]],a=e.langs??[],o=r.length||a.length?this.spot(S(r),a):void 0,s=new G(this.alk,{focus:t?this.model("focus"):void 0,cue:t?this.model("cue"):void 0,spot:o},e);return t&&s.timbre(this.model("timbre")),s}coach(e){return new K(this.alk,e)}voiceprint(e){return xe(this.alk,e)}compile(e,t,r){return ye(this.alk,/^\\s*\\/.+\\/\\s*$/.test(e)?null:this.lex(t),e,t,r)}commands(e,t){return we(this.alk,this.lex(t),e,[...t])}net(e,t){let r=`${e} ${t??""}`,a=this.calls.get(r);a||this.calls.set(r,a=this.model(e).session(t));let o=a;return{run:(s,i)=>o.call(s,i),reset:()=>o.reset()}}release(){this.lexer?.release(),this.spotter?.release(),this.bare?.release(),this.voices?.release(),this.lexer=null,this.spotter=null,this.bare=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 N,Y,re,ne,Fe=g(()=>{"use strict";N=class extends Error{},Y=class n{constructor(e){this.x=e}static async create(e){let t=await WebAssembly.instantiate(e,{});return new n(t.exports)}get heap(){return this.x.memory.buffer}with(e,t){let r=this.x.alk_alloc(e.length);new Uint8Array(this.heap,r,e.length).set(e);try{return t(r,e.length)}finally{this.x.alk_free(r,e.length)}}fail(e){let r=this.x.alk_alloc(512);try{let a=this.x.alk_error(r,512);throw new N(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,r,a))}`)}finally{this.x.alk_free(r,512)}}model(e){return new re(this,e)}},re=class{constructor(e,t){this.alk=e;let r=e.x;this.ptr=e.with(t,(s,i)=>r.alk_model(s,i)),this.ptr||e.fail("model");let a=r.alk_alloc(256),o=s=>new TextDecoder().decode(new Uint8Array(e.heap,a,s));try{this.plans=Array.from({length:r.alk_plans(this.ptr)},(s,i)=>{let u=d=>Array.from({length:r.alk_io_count(this.ptr,i,d)},(l,b)=>{let m=o(r.alk_io_name(this.ptr,i,d,b,a,256)),k=r.alk_io_shape(this.ptr,i,d,b,a,64),oe=Array.from(new Uint32Array(e.heap,a,k));return{name:m,dims:oe,size:oe.reduce(($e,He)=>$e*He,1)}}),p=u(0);return{index:i,name:o(r.alk_plan_name(this.ptr,i,a,256)),inputs:p,outputs:u(1),variable:p[r.alk_variable(this.ptr,i)]?.name??null}})}finally{r.alk_free(a,256)}}ptr;plans;session(e){let t=e===void 0?this.plans[0]:this.plans.find(r=>r.name===e);if(!t)throw new N(`no plan named ${e}`);return new ne(this,t)}release(){this.alk.x.alk_model_free(this.ptr)}},ne=class{constructor(e,t){this.model=e;this.plan=t;let{alk:r}=e,a=r.x;this.ptr=a.alk_session(e.ptr,t.index),this.ptr||r.fail("session");let o=new TextEncoder;for(let[s,i]of[[t.inputs,a.alk_input],[t.outputs,a.alk_output]])for(let u of s)this.at.set(u.name,{...u,p:r.with(o.encode(u.name),(p,d)=>i(this.ptr,p,d))})}ptr;at=new Map;io(e){let t=this.at.get(e);if(!t)throw new N(`no tensor named ${e}`);return t}f32(e){let t=this.io(e);return new Float32Array(this.model.alk.heap,t.p,t.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,t=this.plan.outputs.map(r=>r.name)){let{alk:r}=this.model,{variable:a}=this.plan;for(let s of this.plan.inputs){let i=e[s.name];if(!i)throw new N(`missing input ${s.name}`);if(s.name===a)r.x.alk_set_len(this.ptr,i.data.length)!==0&&r.fail(s.name);else if(i.data.length!==s.size)throw new N(`${s.name}: ${i.data.length} values for ${s.size}`);this.f32(s.name).set(i.data)}this.run();let o={};for(let s of t)o[s]={data:this.f32(s).slice(),dims:[...this.io(s).dims]};return o}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}}});function rt(n){let e=new Uint8Array(n.length*2*(F.dim+4)),t=new DataView(e.buffer),r=0;for(let o of n)for(let s of[o.embedding,o.id]){let i=1e-9;for(let u of s)i=Math.max(i,Math.abs(u));t.setFloat32(r,i/127,!0),r+=4;for(let u of s)t.setInt8(r++,Math.round(u/i*127))}let a="";for(let o of e)a+=String.fromCharCode(o);return btoa(a)}function nt(n){let e=atob(n),t=Uint8Array.from(e,s=>s.charCodeAt(0)),r=new DataView(t.buffer),a=[],o=0;for(;o+2*(F.dim+4)<=t.length;){let s=[];for(let i=0;i<2;i++){let u=r.getFloat32(o,!0);o+=4;let p=new Float32Array(F.dim);for(let d=0;d<p.length;d++)p[d]=r.getInt8(o++)*u;s.push(p)}a.push({embedding:s[0],id:s[1],seconds:F.window/A})}return a}var tt,V,Se=g(()=>{"use strict";E();tt=(n,e)=>{let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t},V=class n{constructor(e,t="focus",r=F.model,a=[]){this.centers=e;this.source=t;this.model=r;this.windows=a;if(!e.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(e){return this.closest(e).score}closest(e){let t=e instanceof n?e.centers:[e],r={score:-1,mine:0,theirs:0};for(let a of this.centers)for(let o of t){let s=tt(a.id,o.id);s>r.score&&(r={score:s,mine:a.seconds,theirs:o.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let e=t=>Array.from(t,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(t=>({embedding:e(t.embedding),id:e(t.id),seconds:+t.seconds.toFixed(1)})),...this.windows.length?{windows:rt(this.windows)}:{}}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(t.model!==F.model)return null;let r=t.centers.map(a=>({embedding:Float32Array.from(a.embedding),id:Float32Array.from(a.id),seconds:a.seconds}));return new n(r,t.source,t.model,t.windows?nt(t.windows):[])}static merge(e){return new n(e.flatMap(t=>t.centers),e.every(t=>t.source==="raw")?"raw":"focus")}}});function Ne(n,e){let t=n[0]?.length??0,r=n.length,a=t*r*2,o=new Uint8Array(44+a),s=new DataView(o.buffer),i=(p,d)=>[...d].forEach((l,b)=>s.setUint8(p+b,l.charCodeAt(0)));i(0,"RIFF"),s.setUint32(4,36+a,!0),i(8,"WAVE"),i(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,r,!0),s.setUint32(24,e,!0),s.setUint32(28,e*r*2,!0),s.setUint16(32,r*2,!0),s.setUint16(34,16,!0),i(36,"data"),s.setUint32(40,a,!0);let u=44;for(let p=0;p<t;p++)for(let d=0;d<r;d++){let l=Math.max(-1,Math.min(1,n[d][p]));s.setInt16(u,l<0?l*32768:l*32767,!0),u+=2}return o}var Oe=g(()=>{"use strict"});function Ee(n,e=A){let t=n.focus!==void 0&&n.focus!==!1,r=typeof n.focus=="object"?n.focus:{},a=at(r.voiceprint)?.embedding,o=n.spot?.words.map(L)??[];return{focus:t?{print:a?Array.from(a):null,strength:r.strength??1,lowPower:!!r.lowPower,...r.sample?{sample:Array.from(r.sample)}:{}}:null,cue:n.cue===void 0||n.cue===null?null:n.cue!==!1,speech:{...D,...typeof n.cue=="object"?n.cue:{}},normalize:n.normalize??!1,trace:!!n.trace,rate:e,spot:o.length?{words:o.map(s=>s.toJSON()),context:n.spot?.context??"anywhere"}:null}}function at(n){return!n||n instanceof Float32Array?null:n instanceof V?n:V.fromJSON(n)}function Pe(n,e,t={}){let{onProgress:r,signal:a,...o}=t,s=Ee(o);s.focus&&!s.focus.print&&!s.focus.sample&&(s.focus.print=n.recordingPrint(e,s));let i=new C(n,o,s),u=[];try{for(let m=0;m<e.length;m+=ae)a?.throwIfAborted(),u.push(i.push(e.subarray(m,Math.min(e.length,m+ae)))),r?.({done:Math.min(e.length,m+ae),total:e.length});u.push(i.end())}finally{i.release()}let p=new Float32Array(e.length),d=0;for(let m of u)p.set(m.audio.subarray(0,p.length-d),d),d+=m.audio.length;let l=e,b=u.reduce((m,k)=>({speech:[...m.speech,...k.speech],wakes:[...m.wakes,...k.wakes],diag:[...m.diag,...k.diag],trace:k.trace||m.trace?{focus:[...m.trace?.focus??[],...k.trace?.focus??[]],cue:[...m.trace?.cue??[],...k.trace?.cue??[]],spot:[...m.trace?.spot??[],...k.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:o.focus?p:e,raw:l,...b,toWav(m="audio"){return Ne(m==="both"?[l,this.audio]:[m==="raw"?l:this.audio],A)}}}var C,ae,Le=g(()=>{"use strict";te();W();Se();Oe();E();C=class{constructor(e,t={},r=Ee(t)){this.opts=t;this.core=e.processor(r)}core;closed=!1;push(e){if(this.closed)throw new Error("push after end");return this.core.push(e)}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()}},ae=16e3});function Re(n){let e=new Map,t=new Map,r=(a,o,s)=>{let i=a.get(o);if(!i)throw new Error(`${s} ${o} is closed, or its worker was started again`);return i};return{embed:(a,o)=>n().timbre().embed(a,o??"raw"),learnerOpen:(a,o)=>{let s=n().learner("raw",o);return e.set(a,s),{progress:s.progress(),ready:s.ready(),voiceprint:s.voiceprint(!0)}},learnerOffer:(a,o)=>{let s=r(e,a,"learner");return{...s.offer(n().timbre(),o),voiceprint:s.voiceprint(!0)}},learnerForget:a=>(e.get(a)?.forget(),null),learnerClose:a=>(e.get(a)?.release(),e.delete(a),null),phonemize:(a,o)=>n().lex([o]).phonemize(a,o),compile:(a,o)=>n().compile(a,o.lang===void 0?[]:[o.lang].flat(),o.chain).word,compileCommands:(a,o)=>n().commands(a,o),process:(a,o,s)=>{let i=Pe(n(),a,{...o,onProgress:s});return{audio:i.audio,raw:i.raw,speech:i.speech,wakes:i.wakes,diag:i.diag,trace:i.trace}},streamOpen:(a,o)=>(t.set(a,new C(n(),o)),null),streamPush:(a,o)=>r(t,a,"stream").push(o),streamEnd:a=>{let o=r(t,a,"stream");return t.delete(a),o.end()}}}var Ve=g(()=>{"use strict";Le()});Me();W();Fe();E();Ve();var P=256,Yt=P+2,Ce=-1;var Ie=new Map,M=null,v=(n,e=[])=>self.postMessage(n,e);async function st(n){M=new X(await Y.create(n),e=>{let t=Ie.get(e);if(!t)throw new Error(`model ${e} not sent`);return t})}var ot=100,it=125,x=new Map;function We(n,e){let t=n.shift;typeof e.start=="number"&&(e.start+=t),typeof e.end=="number"&&(e.end+=t),typeof e.at=="number"&&(e.at+=t);let r=e.data;e.type==="diag"&&r&&(typeof r.start=="number"&&(r.start+=t),typeof r.end=="number"&&(r.end+=t)),n.events.push(e)}var ze=n=>n.map(e=>L(e).toJSON()),De=n=>n?{word:L(n.word).toJSON(),takes:n.takes}:null;function lt(n,e,t,r){let a=e.pipeline!=="wake"&&e.pipeline!=="enroll",o=M.pipeline({chain:a?e.chain??{}:null,verify:!!(e.verify&&t),onlyMyVoice:!!(e.onlyMyVoice&&t&&a),learn:!!(e.learn&&t),keepRecent:e.keepRecent??0,trace:!!e.trace,stats:!!e.stats,output:e.output??null,words:ze(e.words??[]),context:e.context??"anywhere",wake:!!e.wake&&a,enroll:De(e.enroll),turn:e.turn??!1,interrupt:e.interrupt??!1,langs:e.langs??[]}),s={id:n,port:null,closed:!1,timer:setInterval(()=>dt(s),ot),opts:e,p:o,events:[],shift:0,timing:{n:0,sum:0,max:0,slow:0},bg:null,out:r,recordId:null};return t&&Je(s,t),x.set(n,s),s}function Je(n,e){n.bg=e,e.onmessage=t=>{n.closed||(t.data.type==="print"?n.p.set({print:t.data.embedding}):t.data.type==="verified"&&(n.opts.verify||n.opts.onlyMyVoice)&&(n.p.verified(t.data.key,t.data.same,t.data.score),Z(n)))}}function Te(n,e,t){n.out?n.out.postMessage(e,t):v({...e,kind:e.type,type:"pcm",input:n.id},t)}function Z(n){for(let e of n.p.outs())switch(e[0]){case"event":We(n,e[1]);break;case"window":n.bg?.postMessage({type:"window",pcm:e[1],farQuietMs:e[2],t:e[3]},[e[1].buffer]);break;case"verify":n.bg?.postMessage({type:"verify",key:e[1],pcm:e[2]},[e[2].buffer]);break;case"audio":Te(n,{type:"audio",pcm:e[1].buffer},[e[1].buffer]);break;case"utterance":Te(n,{type:"utterance",pcm:e[1].buffer,start:e[2]+n.shift,end:e[3]+n.shift,...e[4]&&{level:e[4]}},[e[1].buffer]);break;case"record":v({type:"reply",id:n.recordId,result:e[1]},[e[1].buffer]),n.recordId=null}}function ct(n,e){let t=!M.has("spot")&&n.port;t&&n.port.postMessage({pause:!0});try{return e()}finally{t&&n.port.postMessage({pause:!1})}}function ut(n,e,t){let r=new Float32Array(e),a=r.subarray(0,P);if(r[P+1]===Ce){n.p.raw(a),Z(n),t.postMessage(e,[e]);return}let o=performance.now(),s=n.p.step(a,r[P]),i=performance.now()-o;n.p.spent(i),r.set(s),t.postMessage(e,[e]),Z(n),pt(n,i)}function pt(n,e){let t=n.timing;if(t.n++,t.sum+=e,t.max=Math.max(t.max,e),e>P/A*1e3&&t.slow++,t.n<it)return;let r=n.p.chained;We(n,{type:"diag",code:"timing",level:t.slow>t.n/10?"warn":"info",data:{meanMs:+(t.sum/t.n).toFixed(2),maxMs:+t.max.toFixed(1),slow:t.slow,asleep:r&&n.p.sleeping,gainDb:r?+n.p.gainDb.toFixed(1):0}}),n.timing={n:0,sum:0,max:0,slow:0}}function dt(n){n.events.length&&(v({type:"events",input:n.id,list:n.events}),n.events=[])}var Ue=Re(()=>M),O=new Map,ht=(n,e)=>v({type:"event",input:n,event:e});function mt(n,e,t,r){let a=O.get(n);if(!a)return;let o=performance.now(),s=a.coach.window(M.timbre(),e,t,r),i=Math.round(performance.now()-o);for(let u of s)u[0]==="print"?a.port.postMessage({type:"print",embedding:u[1]}):(u[1].type==="diag"&&(u[1].data.ms=i),ht(n,u[1]))}function ft({id:n,method:e,args:t,progress:r}){switch(e){case"process":return Ue.process(t[0],t[1],r?a=>v({type:"progress",id:n,p:a}):void 0);case"embed":case"learnerOpen":case"learnerOffer":case"learnerForget":case"learnerClose":case"phonemize":case"compile":case"compileCommands":case"streamOpen":case"streamPush":case"streamEnd":return Ue[e](...t);case"learner":{let a=O.get(t[0]);if(!a)throw new Error("no learning port for this input");return{progress:a.coach.learner(t[1]??null)}}case"forget":return O.get(t[0])?.coach.forget(),null;case"record":{let a=x.get(t[0]);if(!a)throw new Error("no input");a.p.record(t[1]),a.recordId=n;return}case"recent":return x.get(t[0])?.p.recent()??null;case"stats":return x.get(t[0])?.p.stats()??null;default:throw new Error(`unknown method ${e}`)}}function se(n){let e=x.get(n);e&&(e.closed=!0,e.port?.close(),e.bg?.close(),clearInterval(e.timer),e.p.release(),x.delete(n)),O.get(n)?.port.close(),O.get(n)?.coach.release(),O.delete(n)}self.onmessage=async n=>{let e=n.data;try{switch(e.type){case"boot":await st(e.module),v({type:"booted"});break;case"models":for(let[t,r]of Object.entries(e.models))Ie.set(t,new Uint8Array(r));v({type:"reply",id:e.id,result:!0});break;case"realtime":se(e.input),lt(e.input,e.opts,e.bg??null,e.out??null),v({type:"reply",id:e.id,result:!0});break;case"learn":{let t=x.get(e.input);if(!t)break;e.bg&&(t.bg?.close(),Je(t,e.bg)),t.bg&&t.p.set({learn:!0});break}case"worklet":{let t=x.get(e.input),r=e.port;if(!t)break;t.port=r,r.onmessage=a=>{t.closed||(a.data instanceof ArrayBuffer?ut(t,a.data,r):typeof a.data?.clock=="number"&&(t.shift=a.data.clock/A-t.p.time))};break}case"rt-port":{se(e.input);let t={coach:M.coach(e.ref??null),port:e.port};O.set(e.input,t),t.port.onmessage=r=>{r.data.type==="window"?mt(e.input,r.data.pcm,r.data.farQuietMs,r.data.t):r.data.type==="verify"&&t.port.postMessage({type:"verified",key:r.data.key,...t.coach.verify(M.timbre(),r.data.pcm)})};break}case"set":{let t=x.get(e.input);if(!t)break;let r={};"strength"in e&&(r.strength=e.strength),"enabled"in e&&(r.enabled=e.enabled),"print"in e&&(r.print=e.print),"words"in e&&Object.assign(r,{words:ze(e.words),context:e.context??"anywhere"}),"enroll"in e&&(r.enroll=De(e.enroll)),"listen"in e&&(r.listen=e.listen),"hold"in e&&(r.hold=e.hold),"commands"in e&&(r.commands=e.commands??[]);let a=(r.commands??[]).map(o=>o.lang);"words"in e||"enroll"in e&&e.enroll||a.length?ct(t,()=>{t.p.spot(M.spot([...S([...r.words??[],...e.enroll?.word?[e.enroll.word]:[]]),...a])),t.p.set(r)}):t.p.set(r),Z(t);break}case"dispose":se(e.input);break;case"call":{let t=ft(e);t!==void 0&&v({type:"reply",id:e.id,result:t});break}}}catch(t){let r=String(t?.message??t);e.id!==void 0?v({type:"reply",id:e.id,error:{message:r,code:t?.code}}):v({type:"events",input:e.input,list:[{type:"diag",code:"worker.error",level:"warn",data:{message:r,on:e.type}}]})}};\n',t=`var R=.6931471803691238,q=19082149292705877e-26,N=1.4426950408889634;var F=new DataView(new ArrayBuffer(8));function P(r){return F.setUint32(0,r+1023<<20),F.setUint32(4,0),F.getFloat64(0)}function _(r){if(r!==r)return r;if(r>709.782712893384)return 1/0;if(r<-745.1332191019411)return 0;let t=Math.round(r*N),e=r-t*R,s=t*q,i=e-s,n=i*i,o=i-n*(.16666666666666602+n*(-.0027777777777015593+n*(6613756321437934e-20+n*(-16533902205465252e-22+n*41381367970572385e-24)))),a=1-(s-i*o/(2-o)-e),h=t>>1;return a*P(h)*P(t-h)}var T=1.5707963267341256,W=6077100506506192e-26,H=.6366197723675814;function y(r){let t=r*r;return r+r*t*(-.16666666666666632+t*(.00833333333332249+t*(-.0001984126982985795+t*(27557313707070068e-22+t*(-25050760253406863e-24+t*158969099521155e-24)))))}function b(r){let t=r*r,e=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),s=.5*t,i=1-s;return i+(1-i-s+t*e)}function k(r){let t=Math.round(r*H);return[t&3,r-t*T-t*W]}function x(r){let[t,e]=k(r);return t===0?y(e):t===1?b(e):t===2?-y(e):-b(e)}function I(r){let[t,e]=k(r);return t===0?b(e):t===1?-y(e):t===2?-b(e):y(e)}var l=24,M=128,m=class r{constructor(t,e,s=!1){this.inRate=t;this.outRate=e;if(this.identity=t===e,s&&(this.t=l),this.identity)return;this.ratio=t/e;let i=this.half,n=.9/Math.max(1,this.ratio),o=new Float32Array((M+1)*l);for(let a=0;a<=M;a++){let h=a/M,u=0;for(let p=0;p<l;p++){let v=p-(i-1)-h,f=n*v,L=f===0?1:x(Math.PI*f)/(Math.PI*f),O=.42+.5*I(Math.PI*v/i)+.08*I(2*Math.PI*v/i);o[a*l+p]=L*O,u+=o[a*l+p]}for(let p=0;p<l;p++)o[a*l+p]/=u}this.table=o}static HALF=l/2;identity;ratio=1;half=l/2;table=new Float32Array(0);work=new Float32Array(0);histLen=l;t=l/2;push(t,e){if(this.identity){for(let h=0;h<t.length;h++)e(t[h]);return}if(this.work.length<l+8+t.length){let h=new Float32Array(l+8+t.length);h.set(this.work.subarray(0,this.histLen)),this.work=h}let s=this.work;s.set(t,this.histLen);let i=this.histLen+t.length,n=i-1-this.half,o=this.t;for(;o<=n;){let h=Math.floor(o),u=Math.round((o-h)*M)*l,p=h-(this.half-1),v=0;for(let f=0;f<l;f++)v+=s[p+f]*this.table[u+f];e(v),o+=this.ratio}let a=Math.floor(o)-(this.half-1);s.copyWithin(0,a,i),this.histLen=i-a,this.t=o-a}static all(t,e,s){if(e===s)return t;let i=new r(e,s,!0),n=Math.round(t.length*s/e),o=new Float32Array(n),a=0,h=u=>{a<n&&(o[a++]=u)};return i.push(t,h),i.push(new Float32Array(Math.ceil(l*i.ratio)+16),h),o}};var c=256,A=c+2,D=-1,d=16e3,z=2,Q=250,U=1e4,V=400,E=1e4,B=16e4,C=6e4,K=.005,Y=10,G=.003,w=class{buf;start=0;size=0;lost=0;constructor(t){this.buf=new Float32Array(t)}push(t){this.size===this.buf.length&&(this.lost+=this.size,this.start=this.size=0),this.buf[(this.start+this.size)%this.buf.length]=t,this.size++}pull(t,e){for(let s=0;s<e;s++)t[s]=this.buf[(this.start+s)%this.buf.length];this.skip(e)}skip(t){this.start=(this.start+t)%this.buf.length,this.size-=t}peak(t){let e=0;for(let s=0;s<t;s++)e=Math.max(e,Math.abs(this.buf[(this.start+s)%this.buf.length]));return e}},g=class{constructor(t,e,s,i,n=!1){this.rate=t;this.delay16=e;this.now=s;this.emit=i;n&&(this.tap={down:new m(t,d),in16:new w(4096),hop:new Float32Array(A)}),this.fade=1-_(-1/(Y/1e3*t)),this.floor=Math.round(c*(t/d)),this.raw=new Float32Array(Math.max(1,this.latency))}mode="raw";send=null;down;up;in16=new w(4096);out;hop=new Float32Array(A);epoch=0;raw;rawPos=0;mix=0;fade;debt=0;floor;starvedAt=0;windowStart=0;windowStarved=0;sent=0;received=0;inFlight=0;retryMs=E;retryAt=0;activatedAt=0;stopped=!1;quanta=0;stats={min:1/0,max:0,dropped:0};mins=[];windowMin=1/0;farActive=0;farQuietMs=1/0;frames=0;silence=new Float32Array(0);tap=null;onActivate=null;get latency(){let t=this.rate===d?0:m.HALF+m.HALF*(this.rate/d);return Math.round((z*c+this.delay16)*(this.rate/d)+t)}get latencyMs(){return(this.latency+this.debt)/this.rate*1e3}connect(t){this.send=t,this.activate()}pause(t){t?this.mode==="active"&&(this.mode="raw"):this.mode==="raw"&&!this.stopped&&!this.retryAt&&this.send&&this.activate()}stop(){this.stopped=!0,this.mode="raw",this.retryAt=0}activate(){this.down=new m(this.rate,d),this.up=new m(d,this.rate),this.in16=new w(4096),this.out=new w(Math.ceil(this.rate*2));let t=Math.round(z*c*(this.rate/d));for(let e=0;e<t;e++)this.out.push(0);this.epoch++,this.inFlight=0,this.debt=0,this.starvedAt=0,this.windowStart=this.now(),this.windowStarved=0,this.activatedAt=this.now(),this.stopped=!1,this.mode="active",this.onActivate?.(Math.round(this.frames*d/this.rate))}receive(t){this.received++,!(t[c+1]!==this.epoch||this.mode!=="active")&&(this.inFlight>0&&this.inFlight--,this.up.push(t.subarray(0,c),e=>this.out.push(e)))}fail(){this.now()-this.activatedAt>C&&(this.retryMs=E),this.mode="raw",this.retryAt=this.now()+this.retryMs,this.retryMs=Math.min(2*this.retryMs,B),this.emit({type:"overload",queueMs:Math.round(this.out.size/this.rate*1e3),sent:this.sent,received:this.received})}process(t,e,s){let i=s.length;this.frames+=i,this.listenFar(e,i),(!t||!t.length)&&(t=this.silence.length===i?this.silence:this.silence=new Float32Array(i));let n=this.raw,o=n.length;if(this.mode==="raw"&&this.retryAt&&this.now()>=this.retryAt&&this.send&&(this.retryAt=0,this.activate(),this.emit({type:"retry"})),this.mode==="active"){for(this.down.push(t,a=>this.in16.push(a));this.in16.size>=c;)this.in16.pull(this.hop,c),this.hop[c]=this.farQuietMs,this.hop[c+1]=this.epoch,this.send(this.hop),this.inFlight++,this.sent++;this.drain(s)}else this.tap&&this.tapRaw(t);for(let a=0;a<i;a++){let h=t[a]??0,u=n[this.rawPos];n[this.rawPos]=h,this.rawPos=(this.rawPos+1)%o,this.mix+=((this.mode==="active"?1:0)-this.mix)*this.fade,s[a]=this.mode==="active"||this.mix>1e-4?this.mix*(this.mode==="active"?s[a]:0)+(1-this.mix)*u:u}this.mode==="active"&&this.track()}tapRaw(t){let e=this.tap;for(e.down.push(t,s=>e.in16.push(s));e.in16.size>=c;)e.in16.pull(e.hop,c),this.send&&!this.stopped?(e.hop[c]=this.farQuietMs,e.hop[c+1]=D,this.send(e.hop)):this.emit({type:"raw",pcm:e.hop.slice(0,c)})}drain(t){let e=t.length,s=this.out;if(s.lost&&(this.debt=Math.max(0,this.debt-s.lost),s.lost=0),s.size>=e){this.debt>=e&&s.size>=2*e&&this.lowWater()-e>=this.floor&&s.peak(e)<K&&(s.skip(e),this.debt-=e,this.stats.dropped+=e),s.pull(t,e),this.starvedAt&&(this.windowStarved+=this.now()-this.starvedAt,this.starvedAt=0);return}if(t.fill(0),!this.sent)return;this.debt+=e;let i=this.now();this.starvedAt||(this.starvedAt=i),i-this.windowStart>U&&(this.windowStart=i,this.windowStarved=0),(i-this.starvedAt>=Q||this.windowStarved+(i-this.starvedAt)>=V)&&this.fail()}lowWater(){return Math.min(this.windowMin,...this.mins)}track(){let t=this.out.size;this.windowMin=Math.min(this.windowMin,t),this.stats.min=Math.min(this.stats.min,t),this.stats.max=Math.max(this.stats.max,t);let e=Math.round(this.rate/128);if(++this.quanta%e===0&&(this.mins.push(this.windowMin),this.mins.length>2&&this.mins.shift(),this.windowMin=1/0),this.quanta%(2*e)===0){let s=i=>Math.round(i/this.rate*1e3);this.emit({type:"timing",queueMs:[s(this.stats.min),s(this.stats.max)],debtMs:s(this.debt),droppedMs:s(this.stats.dropped),latencyMs:Math.round(this.latencyMs)}),this.stats={min:1/0,max:0,dropped:0}}}listenFar(t,e){let s=e/this.rate*1e3,i=this.farActive>0;if(t&&t.length){let n=0;for(let o=0;o<t.length;o++)n+=t[o]*t[o];i||=Math.sqrt(n/t.length)>G}this.farQuietMs=i?0:this.farQuietMs+s}setFarActive(t){this.farActive=t?1:0,t&&(this.farQuietMs=0)}};var S=class extends AudioWorkletProcessor{core;worker=null;pool=[];dead=!1;constructor(t){super(),this.core=new g(sampleRate,t.processorOptions.delay16,()=>Date.now(),e=>this.port.postMessage(e),!!t.processorOptions.tapRaw),this.port.postMessage({type:"latency",ms:this.core.latencyMs}),this.port.onmessage=e=>{let s=e.data;s.type==="connect"?(this.worker=s.port,this.worker.onmessage=i=>{if(!(i.data instanceof ArrayBuffer))return this.core.pause(!!i.data?.pause);let n=i.data;this.core.receive(new Float32Array(n)),this.pool.push(n)},this.core.onActivate=i=>this.worker.postMessage({clock:i}),this.core.connect(i=>{let n=this.pool.pop()??new ArrayBuffer(A*4);new Float32Array(n).set(i),this.worker.postMessage(n,[n])}),this.port.postMessage({type:"latency",ms:this.core.latencyMs})):s.type==="stop"?this.core.stop():s.type==="far"?this.core.setFarActive(!!s.on):s.type==="dispose"&&(this.dead=!0)}}process(t,e){if(this.dead)return!1;let s=e[0]?.[0];if(!s)return!0;this.core.process(t[0]?.[0]??null,t[1]?.[0]??null,s);for(let i=1;i<(e[0]?.length??0);i++)e[0][i].set(s);return!0}};registerProcessor("alkove",S);
2
+ `;export{e as WORKER,t as WORKLET};
@@ -0,0 +1 @@
1
+ var ie={name:"alkove-engine",file:"alkove-engine.wasm",bytes:799946,sha256:"a570ec034cdb4f0cccb7e7a0ca9d0f47e3094adee056b73cee02b1d71d341ed9"};var M="alkove-ai",z={focus:{name:"alkove-focus-1",file:"alkove-focus-1.alk",bytes:2320032,sha256:"25028c1f9faf765ccab4076716b5e8a8e756cd7662babd2bc078951982df5ce4",revision:"bb6db3ecd63f322565c1b625635c762b1a5797cd"},cue:{name:"alkove-cue-1",file:"alkove-cue-1.alk",bytes:1334468,sha256:"b5b7b3e239203eac95bb4510ae7a9c057e79959926dfb64665f46eccc1e4d3de",revision:"0b404bbf29f3480ad7539de8bcbf36ea4b89a5b5"},spot:{name:"alkove-spot-1",file:"alkove-spot-1.alk",bytes:553664,sha256:"946110dd1bd3ff9092d551c1f8d828dbe3e1f0cc9c1e00f63cfe7400ef6e66cd",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-fr":{name:"alkove-spot-1",file:"alkove-spot-1-fr.alk",bytes:339107,sha256:"4a203e4cc5499ff0f1dfa8741058a6313067faa919ea61b9455ee7b2d8be91b4",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-en":{name:"alkove-spot-1",file:"alkove-spot-1-en.alk",bytes:339107,sha256:"52bf84fbed6728cb2a604ad04fa00bc901c720774e6a9c7278bcf48e7e3225c7",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-es":{name:"alkove-spot-1",file:"alkove-spot-1-es.alk",bytes:339107,sha256:"2098eb29c1ada3f2da6254ce083133a3e1e2893fec663479cad0b7ab6081d168",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-pt":{name:"alkove-spot-1",file:"alkove-spot-1-pt.alk",bytes:339107,sha256:"84803c861590c8698214edf4a55a47f58a1c7a518eebf6b4a75511d600866ce9",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-it":{name:"alkove-spot-1",file:"alkove-spot-1-it.alk",bytes:339107,sha256:"573a65d7f96c4bf4a78192530f68cb8776d434e6699e7c3d97e6edf60278803d",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-ca":{name:"alkove-spot-1",file:"alkove-spot-1-ca.alk",bytes:339107,sha256:"1d2adb0ec5855f627cdab8e974cbb67088a1a46189572acdee3d39f0953df1ba",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-ro":{name:"alkove-spot-1",file:"alkove-spot-1-ro.alk",bytes:339107,sha256:"73991a8e2c9e32c9438e64d7715b35af08cee033ae434ed9fe4d6e6b518581e3",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-de":{name:"alkove-spot-1",file:"alkove-spot-1-de.alk",bytes:339107,sha256:"4a3bba1d1a5da91998510c5dd7fdf7800390825f24ea33edadd433ede81722bf",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-nl":{name:"alkove-spot-1",file:"alkove-spot-1-nl.alk",bytes:339107,sha256:"717ecc565d224254ce43a6fddfc259c7b3099011f10ef20af29c4b925cf67285",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-pl":{name:"alkove-spot-1",file:"alkove-spot-1-pl.alk",bytes:339107,sha256:"891cb9c5596876975c2ea7b7023ac94c4c4972b6441cca902925eb31dcf6038a",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-sv":{name:"alkove-spot-1",file:"alkove-spot-1-sv.alk",bytes:339107,sha256:"fdbe462b8fca971c90f727c3494286ad849a914d9271903be818a35040b72f5e",revision:"18c30629f26ffcfba5987663c144471b23a08945"},"spot-lang":{name:"alkove-spot-1",file:"alkove-spot-1-lang.alk",bytes:264161,sha256:"69b8bbb2d788c54056eefbf534d8fc2dab1e1215684a1a8dc3a5fdbaae6f147b",revision:"18c30629f26ffcfba5987663c144471b23a08945"},timbre:{name:"alkove-timbre-1",file:"alkove-timbre-1.alk",bytes:970064,sha256:"fc94dfff533f1a4fb2abea172c1f5ff7a92cc00c6331275ea1a26e38f877b0e8",revision:"c4770d4575c7e37306708351b18b39fb211b2c14"},"lex-fr":{name:"alkove-lex-1",file:"alkove-lex-1-fr.alk",bytes:1252088,sha256:"280f64fa48509f44893ec13a7000ebf321c54fd4d732f0bffd173777bc8847b5",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-en":{name:"alkove-lex-1",file:"alkove-lex-1-en.alk",bytes:1465760,sha256:"37029e330b7afc3984784a39e4577f6a0e0cb33037adb8070cbd283d06cbabe0",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-es":{name:"alkove-lex-1",file:"alkove-lex-1-es.alk",bytes:386680,sha256:"01ba0aeb04b7d4cfe216e620d65f009849ef4ab841f8ce98b9a20e35df07dcf1",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-pt":{name:"alkove-lex-1",file:"alkove-lex-1-pt.alk",bytes:1470971,sha256:"1af83d0d607c16972e05c990ea7c803ce614a6df4ea93a001cbc55748c4a4c85",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-it":{name:"alkove-lex-1",file:"alkove-lex-1-it.alk",bytes:1190010,sha256:"0a88b0616927675f588ae7a81a3b25813a642d10534ff5dc475d796c57e7387b",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-ca":{name:"alkove-lex-1",file:"alkove-lex-1-ca.alk",bytes:1157080,sha256:"4b6f0bb9dcbadfd0efaf4065acde4b974b59e5502f1ecd8818332d0189253b8a",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-ro":{name:"alkove-lex-1",file:"alkove-lex-1-ro.alk",bytes:369425,sha256:"6c49c0bfb3b9ac55f6483b0ec0e05cd62ba975a32923dff794a4a76a0dfa7d45",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-de":{name:"alkove-lex-1",file:"alkove-lex-1-de.alk",bytes:1356248,sha256:"64ed6add4fb369f1b1a9a43c1028d570d1ae740e37a2163417bbe6d9fa997d88",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-nl":{name:"alkove-lex-1",file:"alkove-lex-1-nl.alk",bytes:1147472,sha256:"5e05ffd8ac66047cd1049dc1aa98c1b9ef086eb94fc575eb8440a5beef1db683",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-pl":{name:"alkove-lex-1",file:"alkove-lex-1-pl.alk",bytes:395038,sha256:"f4250c033c1555d8076bd7b15884741accde3f88a751ae44f08972de88e89de4",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"},"lex-sv":{name:"alkove-lex-1",file:"alkove-lex-1-sv.alk",bytes:1171030,sha256:"58fd5c019711e2604f204618d79bd0c744bb31acda6af45cd758699a7b945f56",revision:"df4cac7735c505b5506e245a97d50cf204af1eb1"}};var x=16e3,k=z,Re={chunk:256,print:192,lag:256};var U=e=>`${k[e].name}@${k[e].sha256.slice(0,12)}`,v={model:U("timbre"),window:24e3,min:1400,max:32e3,dim:192},Ve={langs:["fr","en","es","pt","it","ca","ro","de","nl","pl","sv"],beams:3,bos:66,eos:67,vocab:68,word:33,steps:39},Ie=e=>["cue","spot",...e.map(t=>`spot-${t}`),...new Set(e).size>1?["spot-lang"]:[]],We=e=>e.map(t=>`lex-${t}`);var h=class extends Error{constructor(n,r,o){super(r);this.code=n;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","\xE7","\u028F","\u028B","\u0255","\u0291","\u0267","\u0289"].map(e=>e.normalize("NFD"));var R=new Map(H.map((e,t)=>[e,t+1])),$e=R.get("\u0259"),ce={"\u1D7B":"\u026A",\u025A:"\u0259\u0279",\u025D:"\u025C\u0279",\u029D:"j",\u025F:"\u0261",c:"k",\u026B:"l",\u026C:"l",\u03C7:"x",\u0266:"h",\u0271:"m",\u027B:"\u0279",\u0280:"\u0281",g:"\u0261",\u0258:"\u0259",\u0275:"\xF8",\u026F:"u",\u0264:"o",q:"k",\u0294:"",\u0252:"\u0254",\u0153\u0303:"\u025B\u0303",\u0278:"f",\u0299:"b"},fe={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"}},le=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"]],$=H.map((e,t)=>[t+1]);for(let e of de){let t=e.map(n=>R.get(n.normalize("NFD")));for(let n of t)for(let r of t)$[n-1].includes(r)||$[n-1].push(r)}var B=new Map;function ue(e){let t=B.get(e);if(!t){let n=Object.entries({...ce,...fe[e]??{}}).map(([r,o])=>[r.normalize("NFD"),o.normalize("NFD")]);B.set(e,t=new Map(n))}return t}function j(e){let t=[];for(let n of e.normalize("NFD")){if(/\p{M}/u.test(n)){n==="\u0303"&&t.length&&(t[t.length-1]+=n);continue}t.push(n)}return t}function _(e,t=""){let n=ue(t),r=[];for(let o of j(e.replace(/\([^)]*\)/g," ").replace(/‍/g,"").replace(/\s+/g," ")))if(!le.has(o))for(let s of j(n.get(o)??o)){s=n.get(s)??s;let a=R.get(s);if(!a)return null;r[r.length-1]!==a&&r.push(a)}return r}var O=class e{constructor(t,n,r,o,s,a,i=[]){this.text=t;this.lang=n;this.phonemes=r;this.thresholds=o;this.calibrated=s;this.chain=a;this.warnings=i}warnings;toJSON(){return{alkove:"word",spot:U("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:t,lang:n,p:r})=>({ipa:t,lang:n,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(t){let n=typeof t=="string"?JSON.parse(t):t;if(n.alkove!=="word")throw new TypeError("not an Alkove word");if(n.spot!==U("spot"))return null;let r=n.phonemes.map(o=>({...o,ids:_(o.ipa,o.lang)??[]})).filter(o=>o.ids.length);return new e(n.text,n.lang,r,n.thresholds,n.calibrated,n.chain)}},q=e=>{if(e instanceof O)return e;let t=O.fromJSON(e);if(!t)throw new h("word.outdated",`Compiled for another Spot: compile "${typeof e=="string"?JSON.parse(e).text:e.text}" again.`);return t};function qe(e){let t=[];for(let n of e)for(let r of n?.phonemes??[]){let o=r.lang||n.lang?.[0];o&&!t.includes(o)&&t.push(o)}return t}var pe=.6931471803691238,be=19082149292705877e-26;var P=new DataView(new ArrayBuffer(8));function V(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),P.setFloat64(0,e);let n=P.getUint32(0);t+=(n>>>20)-1023;let r=n&1048575,o=r+614244&1048576;t+=o>>>20,r|=o^1072693248,P.setUint32(0,r);let s=P.getFloat64(0)-1,a=s/(2+s),i=a*a,c=i*i,d=c*(.3999999999940942+c*(.22222198432149784+c*.15313837699209373)),f=i*(.6666666666666735+c*(.2857142874366239+c*(.1818357216161805+c*.14798198605116586))),l=.5*s*s;return t*pe-(l-(a*(l+f+d)+t*be)-s)}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 N(e){let t=e*e,n=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),r=.5*t,o=1-r;return o+(1-o-r+t*n)}function G(e){let t=Math.round(e*ge);return[t&3,e-t*me-t*he]}function Ke(e){let[t,n]=G(e);return t===0?F(n):t===1?N(n):t===2?-F(n):-N(n)}function Xe(e){let[t,n]=G(e);return t===0?N(n):t===1?-F(n):t===2?-N(n):F(n)}var ye=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n},A=class e{constructor(t,n="focus",r=v.model,o=[]){this.centers=t;this.source=n;this.model=r;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 n=t instanceof e?t.centers:[t],r={score:-1,mine:0,theirs:0};for(let o of this.centers)for(let s of n){let a=ye(o.id,s.id);a>r.score&&(r={score:a,mine:o.seconds,theirs:s.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let t=n=>Array.from(n,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(n=>({embedding:t(n.embedding),id:t(n.id),seconds:+n.seconds.toFixed(1)})),...this.windows.length?{windows:we(this.windows)}:{}}}static fromJSON(t){let n=typeof t=="string"?JSON.parse(t):t;if(n.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(n.model!==v.model)return null;let r=n.centers.map(o=>({embedding:Float32Array.from(o.embedding),id:Float32Array.from(o.id),seconds:o.seconds}));return new e(r,n.source,n.model,n.windows?ve(n.windows):[])}static merge(t){return new e(t.flatMap(n=>n.centers),t.every(n=>n.source==="raw")?"raw":"focus")}};function we(e){let t=new Uint8Array(e.length*2*(v.dim+4)),n=new DataView(t.buffer),r=0;for(let s of e)for(let a of[s.embedding,s.id]){let i=1e-9;for(let c of a)i=Math.max(i,Math.abs(c));n.setFloat32(r,i/127,!0),r+=4;for(let c of a)n.setInt8(r++,Math.round(c/i*127))}let o="";for(let s of t)o+=String.fromCharCode(s);return btoa(o)}function ve(e){let t=atob(e),n=Uint8Array.from(t,a=>a.charCodeAt(0)),r=new DataView(n.buffer),o=[],s=0;for(;s+2*(v.dim+4)<=n.length;){let a=[];for(let i=0;i<2;i++){let c=r.getFloat32(s,!0);s+=4;let d=new Float32Array(v.dim);for(let f=0;f<d.length;f++)d[f]=r.getInt8(s++)*c;a.push(d)}o.push({embedding:a[0],id:a[1],seconds:v.window/x})}return o}function ke(e,t,n){let r=(p,u)=>{let b=Math.min(Math.max(u,p[0]),p[p.length-1]),m=Math.max(1,p.findIndex(y=>y>=b));return[m-1,m,V(b/p[m-1])/V(p[m]/p[m-1])]},[o,s,a]=r(I.print,n),[i,c,d]=r(I.heard,t),f=I[e],l=p=>f[p][i]+(f[p][c]-f[p][i])*d;return l(o)+(l(s)-l(o))*a}var I={print:[1.5,3,6,12,24],heard:[.6,.9,1.5,3],lenient:[[.0375,.0725,.0925,.1125],[.0775,.1675,.195,.2275],[.1125,.2375,.2925,.33],[.155,.27,.335,.3725],[.1775,.295,.365,.4075]],balanced:[[.26,.3,.3325,.3575],[.2975,.345,.3825,.41],[.325,.38,.4225,.4525],[.3475,.405,.4425,.475],[.3575,.42,.465,.495]],strict:[[.405,.4325,.455,.4725],[.425,.455,.4775,.5],[.44,.4725,.4975,.52],[.4475,.48,.51,.5325],[.4525,.4875,.515,.5375]]},K=class e{static verify(t,n,{level:r="balanced"}={}){let{score:o,mine:s,theirs:a}=t.closest(n);return{same:o>=ke(r,a,s),score:o}}static identify(t,n,r={}){let o=null;for(let[s,a]of Object.entries(n)){let{same:i,score:c}=e.verify(a,t,r);i&&(!o||c>o.score)&&(o={who:s,score:c})}return o}};var Z="alkove",E="https://cache.alkove.invalid/",xe=30,g={},ee=!1,L=new Set;function rt(e){ee&&te({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),g={...g,...e}}var ot=()=>g,at=()=>void(ee=!0);function st(e){return L.add(e),()=>void L.delete(e)}var X=new Set;function te(e){for(let t of L)t(e);L.size||e.level!=="warn"||X.has(e.code)||(X.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function ne(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}var Ae=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",re=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function Se(e,t){let n=globalThis.location?.href;return new URL(t,new URL(String(e).replace(/\/?$/,"/"),n)).href}function Y(e){if(g.modelBaseUrl)return Se(g.modelBaseUrl,e.file);if(!e.revision)throw new h("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/${M}/${e.name}/resolve/${e.revision}/${e.file}`}async function Ue(e,t,n=0){let r;try{r=await fetch(e)}catch(f){throw new h("models.fetch",`fetch failed: ${e}`,f)}if(!r.ok||!r.body)throw new h("models.fetch",`HTTP ${r.status}: ${e}`);let o=Number(r.headers.get("content-length"))||n,s=r.body.getReader(),a=[],i=0;for(;;){let{done:f,value:l}=await s.read();if(f)break;a.push(l),i+=l.length,t?.({loaded:i,total:Math.max(o,i)})}let c=new Uint8Array(i),d=0;for(let f of a)c.set(f,d),d+=f.length;return c}async function S(e,t){let n=await ne(t);if(n!==e.sha256)throw new h("models.hash",`${e.name}: sha256 ${n}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return t}async function W(e,t,n){return t instanceof ArrayBuffer?S(e,new Uint8Array(t)):t instanceof Uint8Array?S(e,t):S(e,await Ue(String(t),n,e.bytes))}async function Oe(e,t){if(!re())return t();let n;try{n=await caches.open(Z)}catch{return t()}let r=E+e.sha256,o=await n.match(r).catch(()=>{});if(o){let a=new Uint8Array(await o.arrayBuffer());if(await ne(a)===e.sha256)return Q(n,e.sha256),a;await n.delete(r).catch(()=>{})}let s=await t();return await n.put(r,new Response(s,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),Q(n,e.sha256),s}async function Q(e,t){try{let n=E+"used.json",r=await(await e.match(n))?.json().catch(()=>null)??{},o=Date.now();r[t]=o;for(let[s,a]of Object.entries(r))o-a>xe*864e5&&(await e.delete(E+s),delete r[s]);await e.put(n,new Response(JSON.stringify(r),{headers:{"content-type":"application/json"}}))}catch{}}async function it(e){if(g.models?.[T(e)]instanceof ArrayBuffer||g.models?.[T(e)]instanceof Uint8Array)return!0;if(!re())return!1;try{return!!await(await caches.open(Z)).match(E+e.sha256)}catch{return!1}}var T=e=>Object.entries(k).find(([,t])=>t===e)?.[0]??"engine";async function Pe(e,t,n){let r=g.models?.[T(e)]??n;if(r instanceof ArrayBuffer||r instanceof Uint8Array)return W(e,r);if(Ae()){if(r&&String(r).startsWith("file:")){let{readFile:s}=await import("node:fs/promises");return S(e,new Uint8Array(await s(new URL(String(r)))))}let o=Fe(g.modelBaseUrl);if(o){let{readFile:s}=await import("node:fs/promises"),{join:a}=await import("node:path");return S(e,new Uint8Array(await s(a(await o,e.file))))}return W(e,r??Y(e),t)}return Oe(e,()=>W(e,r??Y(e),t))}function Fe(e){if(!e)return null;let t=String(e);return t.startsWith("file:")?import("node:url").then(n=>n.fileURLToPath(t)):/^[a-z][a-z0-9+.-]+:/i.test(t)?null:Promise.resolve(t)}function ct(e,t){return Pe(k[e],t)}function oe(e,t){let n=e[0]?.length??0,r=e.length,o=n*r*2,s=new Uint8Array(44+o),a=new DataView(s.buffer),i=(d,f)=>[...f].forEach((l,p)=>a.setUint8(d+p,l.charCodeAt(0)));i(0,"RIFF"),a.setUint32(4,36+o,!0),i(8,"WAVE"),i(12,"fmt "),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,r,!0),a.setUint32(24,t,!0),a.setUint32(28,t*r*2,!0),a.setUint16(32,r*2,!0),a.setUint16(34,16,!0),i(36,"data"),a.setUint32(40,o,!0);let c=44;for(let d=0;d<n;d++)for(let f=0;f<r;f++){let l=Math.max(-1,Math.min(1,e[f][d]));a.setInt16(c,l<0?l*32768:l*32767,!0),c+=2}return s}function lt(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=s=>String.fromCharCode(...e.subarray(s,s+4));if(n(0)!=="RIFF"||n(8)!=="WAVE")throw new TypeError("audio.format: not a WAV file");let r=12,o=null;for(;r+8<=e.length;){let s=n(r),a=t.getUint32(r+4,!0),i=r+8;if(s==="fmt "){let c=t.getUint16(i,!0);c===65534&&(c=t.getUint16(i+24,!0)),o={format:c,ch:t.getUint16(i+2,!0),rate:t.getUint32(i+4,!0),bits:t.getUint16(i+14,!0)}}else if(s==="data"&&o){let{format:c,ch:d,rate:f,bits:l}=o,p=l/8,u=Math.floor(Math.min(a,e.length-i)/(p*d)),b=new Float32Array(u);for(let m=0;m<u;m++){let y=0;for(let C=0;C<d;C++){let w=i+(m*d+C)*p;if(c===3)y+=l===64?t.getFloat64(w,!0):t.getFloat32(w,!0);else if(l===8)y+=(t.getUint8(w)-128)/128;else if(l===16)y+=t.getInt16(w,!0)/32768;else if(l===24)y+=(t.getUint8(w)|t.getUint8(w+1)<<8|t.getInt8(w+2)<<16)/8388608;else if(l===32)y+=t.getInt32(w,!0)/2147483648;else throw new TypeError(`audio.format: ${l}-bit WAV`)}b[m]=y/d}return{pcm:b,rate:f}}r=i+a+(a&1)}throw new TypeError("audio.format: WAV without data")}var ae={confidence:.7,exitConfidence:.4,startSecs:.2,stopSecs:.6};function se(e,t=x){let n=e.focus!==void 0&&e.focus!==!1,r=typeof e.focus=="object"?e.focus:{},o=Ne(r.voiceprint)?.embedding,s=e.spot?.words.map(q)??[];return{focus:n?{print:o?Array.from(o):null,strength:r.strength??1,lowPower:!!r.lowPower,...r.sample?{sample:Array.from(r.sample)}:{}}:null,cue:e.cue===void 0||e.cue===null?null:e.cue!==!1,speech:{...ae,...typeof e.cue=="object"?e.cue:{}},normalize:e.normalize??!1,trace:!!e.trace,rate:t,spot:s.length?{words:s.map(a=>a.toJSON()),context:e.spot?.context??"anywhere"}:null}}function Ne(e){return!e||e instanceof Float32Array?null:e instanceof A?e:A.fromJSON(e)}async function Ee(e){if(!(e instanceof Float32Array))return{print:e};let{Timbre:t}=await import("./api-4YJABVLZ.js");return{print:await(await t.create()).embed(e),sample:e}}async function yt(e){let t=e.focus;if(typeof t!="object"||!(t.voiceprint instanceof Float32Array))return e;let n=await Ee(t.voiceprint);return{...e,focus:{...t,voiceprint:n.print,sample:t.sample??n.sample}}}var J=class{constructor(t,n={},r=se(n)){this.opts=n;this.core=t.processor(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()}},D=16e3;function wt(e,t,n={}){let{onProgress:r,signal:o,...s}=n,a=se(s);a.focus&&!a.focus.print&&!a.focus.sample&&(a.focus.print=e.recordingPrint(t,a));let i=new J(e,s,a),c=[];try{for(let u=0;u<t.length;u+=D)o?.throwIfAborted(),c.push(i.push(t.subarray(u,Math.min(t.length,u+D)))),r?.({done:Math.min(t.length,u+D),total:t.length});c.push(i.end())}finally{i.release()}let d=new Float32Array(t.length),f=0;for(let u of c)d.set(u.audio.subarray(0,d.length-f),f),f+=u.audio.length;let l=t,p=c.reduce((u,b)=>({speech:[...u.speech,...b.speech],wakes:[...u.wakes,...b.wakes],diag:[...u.diag,...b.diag],trace:b.trace||u.trace?{focus:[...u.trace?.focus??[],...b.trace?.focus??[]],cue:[...u.trace?.cue??[],...b.trace?.cue??[]],spot:[...u.trace?.spot??[],...b.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:s.focus?d:t,raw:l,...p,toWav(u="audio"){return oe(u==="both"?[l,this.audio]:[u==="raw"?l:this.audio],x)}}}export{ie as a,x as b,k as c,Re as d,Ve as e,Ie as f,We as g,H as h,$ as i,_ as j,h as k,O as l,q as m,qe as n,Ke as o,Xe as p,A as q,K as r,rt as s,ot as t,at as u,st as v,te as w,Se as x,it as y,Pe as z,ct as A,ae as B,oe as C,lt as D,Ne as E,Ee as F,yt as G,J as H,wt as I};
@@ -0,0 +1 @@
1
+ import{A as st,E as m,F as E,a as N,b as S,d as I,e as T,f as F,k as p,l as X,m as y,n as b,o as Y,p as _,q as Z,t as x,u as Q,v as tt,w as A,x as V,z as et}from"./chunk-2PTYZFLZ.js";var v=class{handlers=new Map;on(r,t){let e=this.handlers.get(r);return e||this.handlers.set(r,e=new Set),e.add(t),()=>void e.delete(t)}emit(r,t){for(let e of this.handlers.get(r)??[])try{e(t)}catch(s){queueMicrotask(()=>{throw s})}}listens(r){return!!this.handlers.get(r)?.size}clear(){this.handlers.clear()}};var O=class extends v{done;target=null;cancelled=!1;abort=null;constructor(r){super(),this.done=this.run(r),this.done.catch(()=>{})}async run(r){let t=await r.compile();for(let i of t.warnings)this.emit("warning",i);if(this.cancelled)throw new DOMException("cancelled","AbortError");let e=this.target=await r.open(t.toJSON()),s=[e.on("take",i=>this.emit("take",i))];try{let i=await new Promise((l,c)=>{s.push(e.on("enrolled",l)),this.abort=()=>c(new DOMException("cancelled","AbortError"))});if(i.error||!i.word)throw new p("engine.failed",i.error??"enrollment failed");for(let l of i.warnings??[])this.emit("warning",l);let o=i.audio&&i.audio.length>=4e3?await r.embed(i.audio,e.source):null,a=y(i.word);return{word:new X(a.text,a.lang,a.phonemes,a.thresholds,a.calibrated,a.chain,[...t.warnings,...i.warnings??[]]),voiceprint:o}}finally{for(let i of s)i();e.stop()}}cancel(){this.cancelled=!0,this.abort?.(),this.target?.stop()}};var u=24,P=128,W=class n{constructor(r,t,e=!1){this.inRate=r;this.outRate=t;if(this.identity=r===t,e&&(this.t=u),this.identity)return;this.ratio=r/t;let s=this.half,i=.9/Math.max(1,this.ratio),o=new Float32Array((P+1)*u);for(let a=0;a<=P;a++){let d=a/P,l=0;for(let c=0;c<u;c++){let f=c-(s-1)-d,h=i*f,w=h===0?1:Y(Math.PI*h)/(Math.PI*h),nt=.42+.5*_(Math.PI*f/s)+.08*_(2*Math.PI*f/s);o[a*u+c]=w*nt,l+=o[a*u+c]}for(let c=0;c<u;c++)o[a*u+c]/=l}this.table=o}static HALF=u/2;identity;ratio=1;half=u/2;table=new Float32Array(0);work=new Float32Array(0);histLen=u;t=u/2;push(r,t){if(this.identity){for(let d=0;d<r.length;d++)t(r[d]);return}if(this.work.length<u+8+r.length){let d=new Float32Array(u+8+r.length);d.set(this.work.subarray(0,this.histLen)),this.work=d}let e=this.work;e.set(r,this.histLen);let s=this.histLen+r.length,i=s-1-this.half,o=this.t;for(;o<=i;){let d=Math.floor(o),l=Math.round((o-d)*P)*u,c=d-(this.half-1),f=0;for(let h=0;h<u;h++)f+=e[c+h]*this.table[l+h];t(f),o+=this.ratio}let a=Math.floor(o)-(this.half-1);e.copyWithin(0,a,s),this.histLen=s-a,this.t=o-a}static all(r,t,e){if(t===e)return r;let s=new n(t,e,!0),i=Math.round(r.length*e/t),o=new Float32Array(i),a=0,d=l=>{a<i&&(o[a++]=l)};return s.push(r,d),s.push(new Float32Array(Math.ceil(u*s.ratio)+16),d),o}};var B=class{constructor(r){this.worker=r;r.onmessage=t=>{let e=t.data;if(e?.type==="reply"){let s=this.replies.get(e.id);this.replies.delete(e.id),e.error?s?.reject(Object.assign(new Error(e.error.message),{code:e.error.code})):s?.resolve(e.result)}else if(e?.type==="progress")this.replies.get(e.id)?.progress?.(e.p);else for(let s of this.listeners)s(e)},r.onerror=t=>{for(let e of this.replies.values())e.reject(new p("engine.failed",t.message||"worker failed"));this.replies.clear();for(let e of this.listeners)e({type:"crash",message:t.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,t=[],e){let s=this.next++;return new Promise((i,o)=>{this.replies.set(s,{resolve:i,reject:o,progress:e}),this.worker.postMessage({...r,id:s,progress:!!e},t)})}call(r,t,e=[],s){return this.request({type:"call",method:r,args:t},e,s)}post(r,t=[]){this.worker.postMessage(r,t)}},at=null,dt=()=>at??=import("./assets-27T24F6J.js");async function D(n){let r=x().assetBaseUrl;if(r)return V(r,`alkove-${n}.js`);let t=await dt();return URL.createObjectURL(new Blob([n==="worker"?t.WORKER:t.WORKLET],{type:"text/javascript"}))}var rt=null;function lt(n){return rt??=(async()=>{let r=x().models?.engine,t=x().assetBaseUrl,e=r??(t?V(t,N.file):new URL("./alkove-engine.wasm",import.meta.url).href),s=await et(N,n,e);return WebAssembly.compile(s)})().catch(r=>{throw rt=null,r})}var g=class n{static current=null;sent={realtime:new Set,background:new Set};links={};holds=0;static get(){return Q(),n.current??=new n}link(r){return this.links[r]??=(async()=>{let[t,e]=await Promise.all([lt(),D("worker")]),s=new B(new Worker(e,{type:"module",name:`alkove-${r}`})),i=this.links[r];return s.listen(o=>o.type==="crash"&&this.links[r]===i&&this.drop(r,s)),await new Promise((o,a)=>{let d=s.listen(l=>{l.type==="booted"?(d(),o()):l.type==="crash"&&a(new p("engine.failed",l.message))});s.post({type:"boot",module:t})}),s})().catch(t=>{throw delete this.links[r],t})}drop(r,t){delete this.links[r],this.sent[r].clear(),t.worker.terminate()}hold(){this.holds++;let r=!0;return()=>{r&&this.holds--,r=!1}}async idle(){for(let r of["realtime","background"]){let t=this.links[r],e=t&&await t.catch(()=>null);e&&this.links[r]===t&&(r==="realtime"||!e.busy&&!this.holds)&&this.drop(r,e)}}async models(r,t,e){let s=await this.link(r),i=[...new Set(t)].filter(l=>!this.sent[r].has(l));if(!i.length)return s;let o=new Map,a=await Promise.all(i.map(l=>st(l,c=>{o.set(l,c);let f=0,h=0;for(let w of o.values())f+=w.loaded,h+=w.total;e?.({loaded:f,total:h})}))),d=Object.fromEntries(i.map((l,c)=>[l,a[c].slice().buffer]));await s.request({type:"models",models:d},Object.values(d));for(let l of i)this.sent[r].add(l);return s}static report=A};var ct=5e3,pt=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 C(){let n=globalThis,r=!1;try{r=typeof WebAssembly<"u"&&WebAssembly.validate(pt)}catch{}return{worklet:typeof n.AudioWorkletNode=="function",simd:r,secure:n.isSecureContext!==!1}}async function Lt(){try{let n=await navigator.permissions.query({name:"microphone"});return n.state==="granted"||n.state==="denied"?n.state:"prompt"}catch{return"prompt"}}var J={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,voiceIsolation:!1,channelCount:1};async function k(n,r,t=!1){if(!C().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 e=setTimeout(()=>A({code:"mic.waiting",level:"info",message:"The permission prompt has had no answer for 5 s."}),ct);try{let s=t?{noiseSuppression:!0,autoGainControl:!0}:{},i=navigator.mediaDevices.getUserMedia({audio:{...J,...s,...n?{deviceId:{exact:n}}:{}}});return await(r?Promise.race([i,new Promise((a,d)=>{r.aborted&&d(r.reason),r.addEventListener("abort",()=>{i.then(l=>l.getTracks().forEach(c=>c.stop()),()=>{}),d(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(e)}}function it(n){let r=n.getSettings();return["noiseSuppression","autoGainControl","voiceIsolation"].filter(t=>r[t]===!0)}var L=class{constructor(r,t){this.opts=r;this.send=t;this.resampler=new W(S,r.rate),this.buf=new Float32Array(Math.round(r.rate*r.chunkMs/1e3))}resampler;buf;fill=0;push(r){this.resampler.push(r,t=>{this.buf[this.fill++]=t,this.fill===this.buf.length&&(this.send(ht(this.buf,this.opts.format)),this.fill=0)})}};function ht(n,r){if(r==="f32")return n.slice().buffer;let t=new Int16Array(n.length);for(let e=0;e<n.length;e++){let s=Math.max(-1,Math.min(1,n[e]));t[e]=s<0?s*32768:s*32767}return t.buffer}var R=5e3,H=6e4,ut=1500,mt=30,ft=.002,gt=2e3,wt=0,K=new WeakMap,G=new Set,ot=0,vt="This print comes from another Timbre: ignored, learn it again.",M=class extends v{constructor(t){super();this.opts=t;for(let e of t.langs??[])if(!T.langs.includes(e))throw new TypeError(`langs: no ${e}, one of ${T.langs.join(", ")}`);this.running=new Promise(e=>this.markRunning=e)}id=++wt;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;sample=null;retryMs=R;retryTimer;started=0;counted=!1;enabled=!0;printed=!1;learning=!1;farCalled=!1;sender=null;stalled=!1;spotWords=null;spotCommands=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((t,e)=>this.waiting.push([t,e]))}settle(t,e=!1){if(this.ran)return;this.ran=!t,e&&(this.notReady=t);let s=this.waiting;this.waiting=[];for(let[i,o]of s)t?o(t):i()}get track(){return this.currentTrack()}currentTrack(){return this.stalled?this.stream.getAudioTracks()[0]??null:this.dest?.stream.getAudioTracks()[0]??null}now(){return this.ctx?this.ctx.currentTime-this.started:0}spotLangs(){return[...new Set([...b(this.spotWords?.words??[]),...(this.spotCommands??[]).map(t=>t.lang)])]}spotting(){return!!(this.spotWords?.words.length||this.spotCommands?.length)}spotFiles(t){let e=F(t);return new Set([...t,...this.opts.langs??[]]).size>1&&!e.includes("spot-lang")?[...e,"spot-lang"]:e}realtimeModels(){let t=this.models().flatMap(i=>i==="spot"?this.spotFiles(this.spotLangs()):[i]),e=new Set([...this.opts.langs??[],...this.spotLangs()]).size>1,s=[...this.spotting()||this.opts.langs?.length&&e?this.spotFiles(this.spotLangs()):[],...this.models().includes("focus")?["timbre"]:[]];return[...new Set([...t,...s])]}get delay16(){return 0}async open(){ot++,this.counted=!0;try{await this.opening()}catch(t){throw this.dispose(),t}}async opening(){this.offs.push(tt(i=>this.diag(i))),this.opts.voiceprint&&!(this.opts.voiceprint instanceof Float32Array)&&!m(this.opts.voiceprint)&&this.diag({code:"voiceprint.reset",level:"warn",message:vt});let t=C();if(!t.secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!t.worklet)throw new p("browser.unsupported","No AudioWorklet in this browser (Safari 14.1 or later).");let e=this.opts;e.stream||e.track?this.stream=e.stream??new MediaStream([e.track]):(this.stream=await k(e.deviceId,e.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=it(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 G)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."});e.audioContext?this.ctx=e.audioContext:(this.ctx=new AudioContext,this.ownCtx=!0),await this.build(),G.add(this),this.watchContext(),this.watchTrack(s),this.ownStream&&!e.deviceId&&this.followDefault(),this.startModels(),this.flushHeld()}async build(){let t=this.ctx,e=K.get(t);e||(e=D("worklet").then(i=>t.audioWorklet.addModule(i)),e.catch(()=>K.delete(t)),K.set(t,e)),await e,this.node=new AudioWorkletNode(t,"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=t.createMediaStreamSource(this.stream),this.source.connect(this.node,0,0);let s=this.opts.farEnd;s&&(this.farSource=s instanceof MediaStreamTrack?t.createMediaStreamSource(new MediaStream([s])):s,this.farSource.connect(this.node,0,1)),this.connectOutput(),this.started=t.currentTime,await this.resume()}connectOutput(){this.dest=this.ctx.createMediaStreamDestination(),this.node.connect(this.dest)}onWorklet(t){t.type==="overload"?(this.diag({code:"overload",level:"warn",message:"The device is too slow for the models: raw microphone for a while.",queueMs:t.queueMs,sent:t.sent,received:t.received}),this.setMode("raw","overload")):t.type==="retry"?this.setMode(this.activeMode()):t.type==="latency"?this._latency=Math.round(t.ms):t.type==="raw"?this.rawAudio(t.pcm):t.type==="timing"&&(this._latency=t.latencyMs,this.diag({code:"queue",level:"info",...t}))}rawAudio(t){}activeMode(){return this.enabled?this.kind==="wake"?this.reference()?"spot+print":"spot":this.printed?"focus+print":"focus":"raw"}held=[];emit(t,e){this.held?this.held.push([t,e]):this.deliver(t,e)}flushHeld(){setTimeout(()=>{let t=this.held??[];this.held=null;for(let[e,s]of t)this.deliver(e,s)},0)}deliver(t,e){if(super.emit(t,e),t!=="diag")return;let s=e;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(t,e){this._mode.mode===t&&this._mode.reason===e||(this._mode=e?{mode:t,reason:e}:{mode:t},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),gt)):this.wantBrowser(!1)}wantBrowser(t){this.browserWant=t,this.browserBusy=this.browserBusy.then(()=>this.browser())}async browser(){let t=this.browserWant,e=this.stream.getAudioTracks()[0];if(this.disposed||!this.ownStream||t===this.browserHas||!e)return;try{await e.applyConstraints({...J,noiseSuppression:t,autoGainControl:t})}catch{}let s=e.getSettings().noiseSuppression;if(typeof s=="boolean"&&s!==t){if(this.disposed||!this.ownStream)return;let o=e.getSettings().deviceId??this.opts.deviceId;e.stop();try{let a=await k(o,void 0,t);if(this.disposed||!this.ownStream){for(let d of a.getTracks())d.stop();return}await this.setStream(a,!0)}catch{this.onTrackEnded();return}}this.browserHas=t;let i=this.stream.getAudioTracks()[0]?.getSettings().noiseSuppression;this.diag({code:"mic.browser",level:"info",noiseSuppression:t,autoGainControl:t,applied:typeof i=="boolean"?i:null})}setStatus(t){this._status!==t&&(this._status=t,this.emit("status",t))}diag(t){this.emit("diag",t)}async startModels(){if(!this.disposed){if(!C().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{await this.resolveVoice(),this.learning=this.learns();let t=g.get(),e=await t.models("realtime",this.realtimeModels()),s;if(this.wantsBackground()){let d=await t.models("background",["timbre"]);s=this.toBackground(d,this.reference()),this.learning&&await d.call("learner",[this.id,m(this.opts.voiceprint)?.toJSON()??null])}if(this.disposed)return;this.rt=e,this.offs.push(e.listen(d=>this.onRealtime(d)));let i=this.appPort(),o=[...s?[s]:[],...i?[i]:[]];i&&(this.portGiven=!0),await e.request({type:"realtime",input:this.id,opts:{...this.realtimeOptions(),...this.opts.langs?.length&&{langs:[...this.opts.langs]}},bg:s,out:i},o),(!this.listening||this.holding)&&e.post({type:"set",input:this.id,...!this.listening&&{listen:!1},...this.holding&&{hold:!0}}),this.spotting()&&(await t.models("realtime",this.spotFiles(this.spotLangs())),e.post({type:"set",input:this.id,...this.spotWords?.words.length?this.spotWords:{},...this.spotCommands?.length?{commands:this.spotCommands}:{}})),this.markRunning(),this.settle(null);let a=new MessageChannel;e.post({type:"worklet",input:this.id,port:a.port2},[a.port2]),this.node.port.postMessage({type:"connect",port:a.port1},[a.port1]),this.printed=!!m(this.opts.voiceprint),this.retryMs=R,this.setMode(this.activeMode(),this.enabled?void 0:"off"),!this.learning&&this.learns()&&this.startLearning()}catch(t){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(t?.message??t)}),this.setMode("raw","failed"),this.settle(t instanceof p?t:new p("engine.failed",`Models not loaded: ${String(t?.message??t)}`,t)),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,H)}}}portGiven=!1;appPort(){return this.portGiven?void 0:this.opts.output?.port}wantsBackground(){return this.learning}learns(){return this.kind==="call"||this.kind==="agent"&&(!!this.opts.farEnd||this.farCalled)}toBackground(t,e){let s=new MessageChannel;return t.post({type:"rt-port",input:this.id,port:s.port2,ref:e?.toJSON()??null},[s.port2]),this.bg!==t&&this.offs.push(t.listen(i=>i.input===this.id&&i.type==="event"&&this.onEvent(i.event))),this.bg=t,s.port1}async startLearning(){let t=this.rt;if(!(this.learning||!t||this.disposed)){this.learning=!0;try{let e=this.bg?void 0:this.toBackground(await g.get().models("background",["timbre"]),null);if(this.disposed||this.rt!==t)return;t.post({type:"learn",input:this.id,...e&&{bg:e}},e?[e]:[]),await this.bg.call("learner",[this.id,m(this.opts.voiceprint)?.toJSON()??null])}catch(e){this.disposed||this.diag({code:"models.failed",level:"warn",message:"Timbre not loaded: the print does not learn.",error:String(e?.message??e)})}}}reference(){return null}onRealtime(t){if(t.input===this.id)if(t.type==="events"){let e=[];for(let s of t.list)s.type==="trace"?e.push(s):this.onEvent(s);e.length&&this.emit("trace",e)}else t.type==="pcm"?t.kind==="audio"?this.emit("audio",t.pcm):this.emit("utterance",{pcm:t.pcm,start:t.start,end:t.end,...t.level&&{level:t.level}}):t.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:t.message}),this.setMode("raw","failed"),clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,H))}onEvent(t){switch(t.type){case"speechstart":this.emit("speechstart",{start:t.start});break;case"speechcancel":this.emit("speechcancel",{start:t.start});break;case"speechend":this.emit("speechend",{start:t.start,end:t.end,..."voiceDb"in t&&{level:{voiceDb:t.voiceDb,noiseDb:t.noiseDb,refDb:t.refDb}}});break;case"turn":this.emit("turn",{pause:t.pause,probability:t.probability,hesitation:t.hesitation,at:t.at});break;case"turnend":this.emit("turnend",{start:t.start,end:t.end,probability:t.probability,hesitation:t.hesitation,at:t.at});break;case"interruptstart":this.emit("interruptstart",{start:t.start});break;case"interrupt":this.emit("interrupt",{start:t.start,at:t.at});break;case"interruptcancel":this.emit("interruptcancel",{start:t.start,end:t.end});break;case"wake":this.emit("wake",t);break;case"command":{let{type:e,...s}=t;this.emit("command",s);break}case"language":this.emit("language",{lang:t.lang,p:t.p,start:t.start,end:t.end});break;case"take":{let{type:e,...s}=t;this.emit("take",s);break}case"enrolled":{let{type:e,...s}=t;this.emit("enrolled",s);break}case"heard":this.emit("heard",{speech:t.speech,scores:t.scores});break;case"learn":this.emit("learn",{progress:t.progress});break;case"voiceprint":{let e=Z.fromJSON(t.json);e&&(this._voiceprint=e,this.emit("voiceprint",e));break}case"idle":this.diag({code:"idle",level:"info",asleep:t.asleep,at:t.at});break;case"diag":t.code==="focus.print"&&(this.printed=!!t.data?.print,this._mode.mode!=="raw"&&this.setMode(this.activeMode())),this.diag({code:t.code,level:t.level,...t.data});break}}async setEnabled(t){return this.enabled=t,this.rt?.post({type:"set",input:this.id,enabled:t}),t?this.rt&&this._mode.reason==="off"&&this.setMode(this.activeMode()):this.setMode("raw","off"),t&&!!this.rt}listen(t){this.listening=t,this.rt?.post({type:"set",input:this.id,listen:t})}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})}setVoiceprint(t){if(t instanceof Float32Array){E(t).then(e=>this.applyPrint(e.print??null,e.sample),e=>this.diag({code:"voiceprint.reset",level:"warn",message:`A recording as the voiceprint: ${e.message}`}));return}this.applyPrint(t)}async resolveVoice(){if(!(this.opts.voiceprint instanceof Float32Array))return;let t=await E(this.opts.voiceprint);this.opts.voiceprint=t.print??null,this.sample=t.sample??null}applyPrint(t,e){let s=m(t);t&&!s&&this.diag({code:"voiceprint.reset",level:"warn",message:"This print comes from another Timbre: ignored, learn it again."}),this.opts.voiceprint=s,this.sample=e??null,this.rt?.post({type:"set",input:this.id,print:s?.embedding??null,...e&&{sample:e}}),this.learning&&this.bg?.call("learner",[this.id,s?.toJSON()??null])}forgetVoiceprint(){this._voiceprint=null,this.rt?.post({type:"set",input:this.id,print:null}),this.bg?.call("forget",[this.id])}farEndActive(t){this.node?.port.postMessage({type:"far",on:t}),!this.farCalled&&(this.farCalled=!0,this.learns()&&this.startLearning())}async stats(){return this.rt?this.rt.call("stats",[this.id]):null}async record(t){if(!this.rt)throw new p("engine.failed","The models are not running yet.");let e=await this.rt.call("record",[this.id,t]);return new Blob([e],{type:"audio/wav"})}async recent(){let t=this.rt?await this.rt.call("recent",[this.id]):null;return t?new Blob([t],{type:"audio/wav"}):null}async resume(){try{await Promise.race([this.ctx.resume(),new Promise(t=>setTimeout(t,300))])}catch{}this.setStatus(this.ctx.state==="running"?"running":this.ctx.state==="interrupted"?"interrupted":"blocked")}watchContext(){let t=this.ctx,e=()=>{if(this.disposed)return;let d=t.state;d==="running"?this.setStatus("running"):d==="interrupted"?this.setStatus("interrupted"):d==="suspended"&&t.resume().then(()=>this.setStatus(t.state==="running"?"running":"blocked"),()=>this.setStatus("blocked"))};t.addEventListener("statechange",e),this.offs.push(()=>t.removeEventListener("statechange",e));let s=t.currentTime,i=performance.now(),o=0,a=setInterval(()=>{let d=performance.now(),l=(t.currentTime-s)*1e3,c=d-i;s=t.currentTime,i=d,o=t.state!=="running"||l<.9*c?o||d:0;let h=!!o&&d-o>=ut;if(h!==this.stalled){this.stalled=h,this.diag({code:h?"audio.stalled":"audio.resumed",level:h?"warn":"info"});let w=this.currentTrack();w&&(this.sender?this.sender.replaceTrack(w):this.emit("trackchange",w))}},500);this.offs.push(()=>clearInterval(a))}bind(t){this.sender=t;let e=this.track;e&&t.track!==e&&t.replaceTrack(e)}watchTrack(t){let e=()=>void this.onTrackEnded(),s=()=>this.emit("mic",{state:"muted"}),i=()=>this.emit("mic",{state:"unmuted"});t.addEventListener("ended",e),t.addEventListener("mute",s),t.addEventListener("unmute",i),this.offs.push(()=>{t.removeEventListener("ended",e),t.removeEventListener("mute",s),t.removeEventListener("unmute",i)})}reopenMs=R;async onTrackEnded(){if(!this.disposed&&(this.emit("mic",{state:"lost"}),!!this.ownStream))try{let t=this.browserWant;await this.setStream(await k(this.opts.deviceId,void 0,t),!0),this.browserHas=t,this.reopenMs=R,this.emit("mic",{state:"reopened"})}catch(t){if(t.code==="mic.denied"){this.emit("mic",{state:"denied"});return}setTimeout(()=>void this.onTrackEnded(),this.reopenMs),this.reopenMs=Math.min(2*this.reopenMs,H)}}async setStream(t,e=!1){if(this.ownStream)for(let i of this.stream.getTracks())i!==t.getAudioTracks()[0]&&i.stop();this.source.disconnect(),this.stream=t,this.ownStream=e,this.source=this.ctx.createMediaStreamSource(t),this.source.connect(this.node,0,0);let s=t.getAudioTracks()[0];s&&this.watchTrack(s)}async setDevice(t){this.opts.deviceId=t;let e=this.browserWant;await this.setStream(await k(t,void 0,e),!0),this.browserHas=e}followDefault(){let t=navigator.mediaDevices;if(!t?.addEventListener)return;let e=this.stream.getAudioTracks()[0]?.getSettings().groupId,s=async()=>{if(this.opts.deviceId||this.disposed)return;let o=(await t.enumerateDevices().catch(()=>[])).find(a=>a.kind==="audioinput"&&a.deviceId==="default");if(o&&o.groupId&&o.groupId!==e){e=o.groupId;let a=this.browserWant;await this.setStream(await k(void 0,void 0,a),!0).then(()=>void(this.browserHas=a)).catch(()=>{}),this.emit("mic",{state:"reopened"})}};t.addEventListener("devicechange",s),this.offs.push(()=>t.removeEventListener("devicechange",s))}async restart({track:t,audioContext:e}={}){let s=this.currentTrack();if(e&&e!==this.ctx){if(this.teardownGraph(),this.ownCtx&&this.ctx.close().catch(()=>{}),this.ctx=e,this.ownCtx=!1,t){if(this.ownStream)for(let o of this.stream.getTracks())o.stop();this.stream=new MediaStream([t]),this.ownStream=!1}await this.build(),this.watchContext(),this.rt?.post({type:"dispose",input:this.id}),this.rt=null,this.startModels()}else t&&await this.setStream(new MediaStream([t]));let i=this.currentTrack();i&&i!==s&&this.emit("trackchange",i)}teardownGraph(){this.node?.port.postMessage({type:"dispose"});for(let t of[this.source,this.node,this.dest,this.farSource])t?.disconnect()}spot(t,e={}){if(this.kind==="wake")throw new TypeError("spot() reads Focus: use the wake listener itself");return new j(this,t.map(s=>y(s).toJSON()),e.context??"anywhere")}enrollWord(t,e={}){return new O({compile:async()=>(await import("./api-4YJABVLZ.js")).compileWord(t,e.lang,"focus"),open:async s=>{await this.running;let i=await g.get().models("realtime",F(b([s])));return i.post({type:"set",input:this.id,enroll:{word:s}}),{on:this.on.bind(this),stop:()=>i.post({type:"set",input:this.id,enroll:null}),source:"focus"}},embed:async(s,i)=>(await import("./api-4YJABVLZ.js")).embedAs(s,i)})}setWords(t,e){this.spotWords={words:t,context:e},this.rt&&g.get().models("realtime",this.spotFiles(b(t))).then(s=>s.post({type:"set",input:this.id,words:t,context:e}))}setCommands(t){for(let s of t??[])if(s?.alkove!=="commands"||!T.langs.includes(s.lang))throw new TypeError("setCommands takes what Spot.commands() gives");if(this.spotCommands=t?.length?[...t]:null,!this.rt)return;let e=this.spotCommands??[];g.get().models("realtime",this.spotFiles(this.spotLangs())).then(s=>s.post({type:"set",input:this.id,commands:e}))}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&&--ot===0&&g.get().idle();for(let t of this.offs)t();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 t of this.stream.getTracks())t.stop();this.ownCtx&&this.ctx.close().catch(()=>{}),G.delete(this),this.clear()}}},U=class extends M{constructor(t){super(t);this.opts=t}kind="call";get track(){return super.track}get delay16(){return I.lag+.1*S}models(){return["focus","cue"]}chainOptions(){let t=m(this.opts.voiceprint);return{gate:!0,normalize:!0,strength:this.opts.strength??1,print:t?.embedding??null,sample:this.sample,levels:!0,near:!!this.opts.near,...this.opts.lowPower!==void 0?{lowPower:this.opts.lowPower}:{}}}wantsBackground(){return this.learning||!!this.opts.onlyMyVoice}reference(){return this.opts.onlyMyVoice&&!this.learning?m(this.opts.voiceprint):null}realtimeOptions(){return{pipeline:"call",chain:this.chainOptions(),learn:this.learning,onlyMyVoice:!!this.opts.onlyMyVoice,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:!0}}setStrength(t){this.rt?.post({type:"set",input:this.id,strength:t}),this.opts.strength=t}async start(){return await this.open(),this.keepAlive(),this}keepAlive(){if(typeof document>"u")return;let t=this.ctx.createOscillator();t.frequency.value=mt;let e=this.ctx.createGain(),s=()=>void(e.gain.value=document.hidden?ft:0);s(),t.connect(e).connect(this.ctx.destination),t.start(),document.addEventListener("visibilitychange",s),this.offs.push(()=>{document.removeEventListener("visibilitychange",s),t.stop()})}},j=class extends v{constructor(t,e,s){super();this.input=t;t.setWords(e,s),this.off=t.on("wake",i=>this.emit("wake",i))}off;dispose(){this.off(),this.input.setWords([],"anywhere"),this.clear()}};function $t(n={}){return new U(n).start()}var q=class extends M{constructor(t){super(t);this.opts=t}kind="agent";packer=null;rawAudio(t){this.packer??=new L(this.output(),e=>{let s=this.appPort();s?s.postMessage({type:"audio",pcm:e},[e]):this.opts.output?.port||this.emit("audio",e)}),this.packer.push(t)}output(){let t=this.opts.output??{};return{format:t.format??"f32",rate:t.rate??S,chunkMs:Math.max(16,Math.round((t.chunkMs??32)/16)*16)}}get delay16(){return I.lag}models(){return["focus","cue"]}withTrack=!1;get track(){return this.withTrack||(this.withTrack=!0,this.node&&!this.disposed&&super.connectOutput()),super.track}connectOutput(){this.withTrack&&super.connectOutput();let t=this.ctx.createGain();t.gain.value=0,this.node.connect(t).connect(this.ctx.destination)}wantsBackground(){return this.learning||!!this.opts.onlyMyVoice}reference(){return this.opts.onlyMyVoice&&!this.learning?m(this.opts.voiceprint):null}realtimeOptions(){let t=m(this.opts.voiceprint);return{pipeline:"agent",onlyMyVoice:!!this.opts.onlyMyVoice,chain:{gate:!1,normalize:!0,strength:1,print:t?.embedding??null,sample:this.sample,levels:!0,near:!!this.opts.near,...this.opts.lowPower!==void 0?{lowPower:this.opts.lowPower}:{}},learn:this.learning,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:!0,output:{...this.output(),audio:!0,utterance:!0},turn:{...this.opts.turn},interrupt:!0,wake:!!this.opts.wake}}async start(){let t=this.opts.wake;if(t){if(!Array.isArray(t.words))throw new TypeError("createAgentInput: wake takes { words, lang, context }");let{Spot:e}=await import("./api-4YJABVLZ.js"),s=o=>typeof o=="string"&&!o.trimStart().startsWith("{");if(t.words.some(s)&&!t.lang)throw new TypeError("createAgentInput: wake.lang is needed for a typed word");let i=await Promise.all(t.words.map(async o=>(s(o)?await e.compile(o,{lang:t.lang}):y(o)).toJSON()));if(!i.length)throw new TypeError("createAgentInput: wake.words is empty");this.spotWords={words:i,context:t.context??"pause"}}return await this.open(),this}};function zt(n={}){return new q(n).start()}var $=class extends M{constructor(t){super(t);this.opts=t;if(this.words=t.words.map(e=>y(e).toJSON()),!this.words.length)throw new TypeError("createWakeListener: no word");for(let e of this.words)e.chain==="focus"&&this.diag({code:"word.chain",level:"warn",message:`"${e.text}" was enrolled behind Focus: its thresholds are off on the raw microphone.`})}kind="wake";words;async resolveVoice(){this.opts.voiceprint instanceof Float32Array&&(this.opts.voiceprint=(await E(this.opts.voiceprint)).print??null)}models(){return["spot"]}spotLangs(){return[...new Set([...b(this.words),...super.spotLangs()])]}connectOutput(){let t=this.ctx.createGain();t.gain.value=0,this.node.connect(t).connect(this.ctx.destination)}wantsBackground(){return!!this.reference()}reference(){return m(this.opts.voiceprint)}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 Xt(n){return new $(n).start()}var z=class extends M{constructor(t,e){super(t);this.opts=t;this.word=e}kind="wake";models(){return["spot"]}connectOutput(){let t=this.ctx.createGain();t.gain.value=0,this.node.connect(t).connect(this.ctx.destination)}realtimeOptions(){return{pipeline:"enroll",enroll:{word:this.word}}}spotLangs(){return b([this.word])}async start(){return await this.open(),this}};function Yt(n,r){return new z(n,r).start()}export{O as a,W as b,g as c,C as d,Lt as e,$t as f,zt as g,Xt as h,Yt as i};