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