alkove 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/dist/api-63K47HT3.js +1 -0
- package/dist/chunk-IMUNEOSF.js +1 -0
- package/dist/chunk-MZOMHWYI.js +1 -0
- package/dist/index.js +1 -1
- package/dist/react.d.ts +19 -0
- package/dist/react.js +2 -0
- package/dist/same.d.ts +1 -0
- package/package.json +20 -1
- package/dist/api-5UTMEGDH.js +0 -1
- package/dist/chunk-CWKQLHLV.js +0 -1
package/README.md
CHANGED
|
@@ -56,6 +56,16 @@ wake.on('wake', ({ word, start, audio }) => …)
|
|
|
56
56
|
|
|
57
57
|
Any word, typed in one of 7 languages (fr, en, es, it, pt, ca, ro). By default it counts only after a pause (far fewer false alarms; "Bon, Camille, on y va ?" does not wake it, use `context: 'both'` for that). Enrolling the word (the user says it 3 times) sets its thresholds on their voice. `onlyMyVoice: print` ignores other voices.
|
|
58
58
|
|
|
59
|
+
## React
|
|
60
|
+
|
|
61
|
+
```tsx
|
|
62
|
+
import { useAgentInput } from 'alkove/react'
|
|
63
|
+
|
|
64
|
+
const { status, error } = useAgentInput({ enabled: on, on: { utterance: ({ pcm }) => transcribe(pcm) } })
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`useAgentInput`, `useCallInput` and `useWakeListener` take the options of their function, plus `enabled` and `on`. The input opens with the component and closes with it, strict mode and Next.js included. [The React guide](https://alkove.ai/docs/guides/react/); two apps in [`examples`](https://github.com/alkove-ai/alkove/tree/main/examples) (Next.js, Vite).
|
|
68
|
+
|
|
59
69
|
## Files, offline
|
|
60
70
|
|
|
61
71
|
```ts
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-MZOMHWYI.js";import"./chunk-IMUNEOSF.js";import"./chunk-FC4ZSMUX.js";export{a as Alkove,c as Lex,d as Spot,b as Timbre,e as VoiceprintLearner};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{B as f,a as R,b as k,d as N,i as p,j,k as M,l as q,m as I,n as $,q as S,r as z,s as Y,t as T,u as C,w as X,x as Z}from"./chunk-FC4ZSMUX.js";var v=class{handlers=new Map;on(r,e){let t=this.handlers.get(r);return t||this.handlers.set(r,t=new Set),t.add(e),()=>void t.delete(e)}emit(r,e){for(let t of this.handlers.get(r)??[])try{t(e)}catch(s){queueMicrotask(()=>{throw s})}}listens(r){return!!this.handlers.get(r)?.size}clear(){this.handlers.clear()}};var x=class extends v{done;target=null;cancelled=!1;abort=null;constructor(r){super(),this.done=this.run(r),this.done.catch(()=>{})}async run(r){let e=await r.compile();for(let i of e.warnings)this.emit("warning",i);if(this.cancelled)throw new DOMException("cancelled","AbortError");let t=this.target=await r.open(e.toJSON()),s=[t.on("take",i=>this.emit("take",i))];try{let i=await new Promise((c,l)=>{s.push(t.on("enrolled",c)),this.abort=()=>l(new DOMException("cancelled","AbortError"))});if(i.error||!i.word)throw new p("engine.failed",i.error??"enrollment failed");for(let c of i.warnings??[])this.emit("warning",c);let n=i.audio&&i.audio.length>=4e3?await r.embed(i.audio,t.source):null,a=M(i.word);return{word:new j(a.text,a.lang,a.phonemes,a.thresholds,a.calibrated,a.chain,[...e.warnings,...i.warnings??[]]),voiceprint:n}}finally{for(let i of s)i();t.stop()}}cancel(){this.cancelled=!0,this.abort?.(),this.target?.stop()}};var u=24,A=128,O=class o{constructor(r,e,t=!1){this.inRate=r;this.outRate=e;if(this.identity=r===e,t&&(this.t=u),this.identity)return;this.ratio=r/e;let s=this.half,i=.9/Math.max(1,this.ratio),n=new Float32Array((A+1)*u);for(let a=0;a<=A;a++){let d=a/A,c=0;for(let l=0;l<u;l++){let m=l-(s-1)-d,h=i*m,w=h===0?1:q(Math.PI*h)/(Math.PI*h),re=.42+.5*I(Math.PI*m/s)+.08*I(2*Math.PI*m/s);n[a*u+l]=w*re,c+=n[a*u+l]}for(let l=0;l<u;l++)n[a*u+l]/=c}this.table=n}static HALF=u/2;identity;ratio=1;half=u/2;table=new Float32Array(0);work=new Float32Array(0);histLen=u;t=u/2;push(r,e){if(this.identity){for(let d=0;d<r.length;d++)e(r[d]);return}if(this.work.length<u+8+r.length){let d=new Float32Array(u+8+r.length);d.set(this.work.subarray(0,this.histLen)),this.work=d}let t=this.work;t.set(r,this.histLen);let s=this.histLen+r.length,i=s-1-this.half,n=this.t;for(;n<=i;){let d=Math.floor(n),c=Math.round((n-d)*A)*u,l=d-(this.half-1),m=0;for(let h=0;h<u;h++)m+=t[l+h]*this.table[c+h];e(m),n+=this.ratio}let a=Math.floor(n)-(this.half-1);t.copyWithin(0,a,s),this.histLen=s-a,this.t=n-a}static all(r,e,t){if(e===t)return r;let s=new o(e,t,!0),i=Math.round(r.length*t/e),n=new Float32Array(i),a=0,d=c=>{a<i&&(n[a++]=c)};return s.push(r,d),s.push(new Float32Array(Math.ceil(u*s.ratio)+16),d),n}};var L=class{constructor(r){this.worker=r;r.onmessage=e=>{let t=e.data;if(t?.type==="reply"){let s=this.replies.get(t.id);this.replies.delete(t.id),t.error?s?.reject(Object.assign(new Error(t.error.message),{code:t.error.code})):s?.resolve(t.result)}else if(t?.type==="progress")this.replies.get(t.id)?.progress?.(t.p);else for(let s of this.listeners)s(t)},r.onerror=e=>{for(let t of this.replies.values())t.reject(new p("engine.failed",e.message||"worker failed"));this.replies.clear();for(let t of this.listeners)t({type:"crash",message:e.message})}}next=1;replies=new Map;listeners=new Set;listen(r){return this.listeners.add(r),()=>void this.listeners.delete(r)}get busy(){return this.replies.size>0}request(r,e=[],t){let s=this.next++;return new Promise((i,n)=>{this.replies.set(s,{resolve:i,reject:n,progress:t}),this.worker.postMessage({...r,id:s,progress:!!t},e)})}call(r,e,t=[],s){return this.request({type:"call",method:r,args:e},t,s)}post(r,e=[]){this.worker.postMessage(r,e)}},ie=null,oe=()=>ie??=import("./assets-CPGXIA43.js");async function _(o){let r=S().assetBaseUrl;if(r)return C(r,`alkove-${o}.js`);let e=await oe();return URL.createObjectURL(new Blob([o==="worker"?e.WORKER:e.WORKLET],{type:"text/javascript"}))}var Q=null;function ne(o){return Q??=(async()=>{let r=S().models?.engine,e=S().assetBaseUrl,t=r??(e?C(e,R.file):new URL("./alkove-engine.wasm",import.meta.url).href),s=await X(R,o,t);return WebAssembly.compile(s)})().catch(r=>{throw Q=null,r})}var g=class o{static current=null;sent={realtime:new Set,background:new Set};links={};holds=0;static get(){return z(),o.current??=new o}link(r){return this.links[r]??=(async()=>{let[e,t]=await Promise.all([ne(),_("worker")]),s=new L(new Worker(t,{type:"module",name:`alkove-${r}`})),i=this.links[r];return s.listen(n=>n.type==="crash"&&this.links[r]===i&&this.drop(r,s)),await new Promise((n,a)=>{let d=s.listen(c=>{c.type==="booted"?(d(),n()):c.type==="crash"&&a(new p("engine.failed",c.message))});s.post({type:"boot",module:e})}),s})().catch(e=>{throw delete this.links[r],e})}drop(r,e){delete this.links[r],this.sent[r].clear(),e.worker.terminate()}hold(){this.holds++;let r=!0;return()=>{r&&this.holds--,r=!1}}async idle(){for(let r of["realtime","background"]){let e=this.links[r],t=e&&await e.catch(()=>null);t&&this.links[r]===e&&(r==="realtime"||!t.busy&&!this.holds)&&this.drop(r,t)}}async models(r,e,t){let s=await this.link(r),i=e.filter(c=>!this.sent[r].has(c));if(!i.length)return s;let n=new Map,a=await Promise.all(i.map(c=>Z(c,l=>{n.set(c,l);let m=0,h=0;for(let w of n.values())m+=w.loaded,h+=w.total;t?.({loaded:m,total:h})}))),d=Object.fromEntries(i.map((c,l)=>[c,a[l].slice().buffer]));await s.request({type:"models",models:d},Object.values(d));for(let c of i)this.sent[r].add(c);return s}static report=T};var ae=5e3,de=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 E(){let o=globalThis,r=!1;try{r=typeof WebAssembly<"u"&&WebAssembly.validate(de)}catch{}return{worklet:typeof o.AudioWorkletNode=="function",simd:r,secure:o.isSecureContext!==!1}}async function Ee(){try{let o=await navigator.permissions.query({name:"microphone"});return o.state==="granted"||o.state==="denied"?o.state:"prompt"}catch{return"prompt"}}var D={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,voiceIsolation:!1,channelCount:1};async function y(o,r,e=!1){if(!E().secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!navigator.mediaDevices?.getUserMedia)throw new p("browser.unsupported","No getUserMedia in this browser.");let t=setTimeout(()=>T({code:"mic.waiting",level:"info",message:"The permission prompt has had no answer for 5 s."}),ae);try{let s=e?{noiseSuppression:!0,autoGainControl:!0}:{},i=navigator.mediaDevices.getUserMedia({audio:{...D,...s,...o?{deviceId:{exact:o}}:{}}});return await(r?Promise.race([i,new Promise((a,d)=>{r.aborted&&d(r.reason),r.addEventListener("abort",()=>{i.then(c=>c.getTracks().forEach(l=>l.stop()),()=>{}),d(r.reason)})})]):i)}catch(s){if(r?.aborted)throw r.reason;let i=s?.name;throw i==="NotAllowedError"||i==="SecurityError"?new p("mic.denied","Microphone permission denied.",s):i==="NotFoundError"||i==="OverconstrainedError"?new p("mic.not-found","No microphone.",s):i==="NotReadableError"||i==="AbortError"?new p("mic.busy","The microphone is used by another app.",s):s}finally{clearTimeout(t)}}function ee(o){let r=o.getSettings();return["noiseSuppression","autoGainControl","voiceIsolation"].filter(e=>r[e]===!0)}var P=class{constructor(r,e){this.opts=r;this.send=e;this.resampler=new O(k,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(ce(this.buf,this.opts.format)),this.fill=0)})}};function ce(o,r){if(r==="f32")return o.slice().buffer;let e=new Int16Array(o.length);for(let t=0;t<o.length;t++){let s=Math.max(-1,Math.min(1,o[t]));e[t]=s<0?s*32768:s*32767}return e.buffer}var W=5e3,F=6e4,le=1500,pe=30,he=.002,ue=2e3,me=0,V=new WeakMap,B=new Set,te=0,se="This print comes from another Timbre: ignored, learn it again.",b=class extends v{constructor(e){super();this.opts=e;this.running=new Promise(t=>this.markRunning=t)}id=++me;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=W;retryTimer;started=0;counted=!1;enabled=!0;printed=!1;sender=null;stalled=!1;spotWords=null;running;markRunning;ran=!1;notReady=null;waiting=[];warned=new Set;browserWant=!1;browserHas=!1;browserBusy=Promise.resolve();browserTimer;listening=!0;holding=!1;get disposed(){return this._status==="disposed"}get mode(){return this._mode.mode}get status(){return this._status}get latency(){return this._latency}get voiceprint(){return this._voiceprint}get ready(){return this.ran?Promise.resolve():this.notReady?Promise.reject(this.notReady):new Promise((e,t)=>this.waiting.push([e,t]))}settle(e,t=!1){if(this.ran)return;this.ran=!e,t&&(this.notReady=e);let s=this.waiting;this.waiting=[];for(let[i,n]of s)e?n(e):i()}get track(){return this.stalled?this.stream.getAudioTracks()[0]??null:this.dest?.stream.getAudioTracks()[0]??null}now(){return this.ctx?this.ctx.currentTime-this.started:0}get delay16(){return 0}async open(){te++,this.counted=!0;try{await this.opening()}catch(e){throw this.dispose(),e}}async opening(){this.offs.push(Y(i=>this.diag(i))),this.opts.voiceprint&&!f(this.opts.voiceprint)&&this.diag({code:"voiceprint.reset",level:"warn",message:se});let e=E();if(!e.secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!e.worklet)throw new p("browser.unsupported","No AudioWorklet in this browser (Safari 14.1 or later).");let t=this.opts;t.stream||t.track?this.stream=t.stream??new MediaStream([t.track]):(this.stream=await y(t.deviceId,t.signal),this.ownStream=!0);let s=this.stream.getAudioTracks()[0];if(!s)throw new p("mic.not-found","The stream has no audio track.");if(!this.ownStream){let i=ee(s);i.length&&this.diag({code:"mic.processed",level:"warn",message:`The browser processes the stream before the models (${i.join(", ")}): open it with these off.`,settings:i})}for(let i of B)i.stream.getAudioTracks()[0]?.getSettings().deviceId===s.getSettings().deviceId&&i!==this&&this.diag({code:"mic.twice",level:"warn",message:"Two inputs on the same microphone run everything twice: use call.spot() for words on a call input."});t.audioContext?this.ctx=t.audioContext:(this.ctx=new AudioContext,this.ownCtx=!0),await this.build(),B.add(this),this.watchContext(),this.watchTrack(s),this.ownStream&&t.followDefault!==!1&&!t.deviceId&&this.followDefault(),this.startModels(),this.flushHeld()}async build(){let e=this.ctx,t=V.get(e);t||(t=_("worklet").then(i=>e.audioWorklet.addModule(i)),t.catch(()=>V.delete(e)),V.set(e,t)),await t,this.node=new AudioWorkletNode(e,"alkove",{numberOfInputs:2,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{delay16:this.delay16,tapRaw:this.kind==="agent"}}),this.node.port.onmessage=i=>this.onWorklet(i.data),this.source=e.createMediaStreamSource(this.stream),this.source.connect(this.node,0,0);let s=this.opts.farEnd;s&&s!=="manual"&&(this.farSource=s instanceof MediaStreamTrack?e.createMediaStreamSource(new MediaStream([s])):s,this.farSource.connect(this.node,0,1)),this.connectOutput(),this.started=e.currentTime,await this.resume()}connectOutput(){this.dest=this.ctx.createMediaStreamDestination(),this.node.connect(this.dest)}onWorklet(e){e.type==="overload"?(this.diag({code:"overload",level:"warn",message:"The device is too slow for the models: raw microphone for a while.",queueMs:e.queueMs,sent:e.sent,received:e.received}),this.setMode("raw","overload")):e.type==="retry"?this.setMode(this.activeMode()):e.type==="latency"?this._latency=Math.round(e.ms):e.type==="raw"?this.rawAudio(e.pcm):e.type==="timing"&&(this._latency=e.latencyMs,this.diag({code:"queue",level:"info",...e}))}rawAudio(e){}activeMode(){return this.enabled?this.kind==="wake"?this.reference()?"spot+print":"spot":this.printed?"focus+print":"focus":"raw"}held=[];emit(e,t){this.held?this.held.push([e,t]):this.deliver(e,t)}flushHeld(){setTimeout(()=>{let e=this.held??[];this.held=null;for(let[t,s]of e)this.deliver(t,s)},0)}deliver(e,t){if(super.emit(e,t),e!=="diag")return;let s=t;s.level!=="warn"||this.listens("diag")||this.warned.has(s.code)||(this.warned.add(s.code),console.warn(`alkove: ${s.message??s.code}`,s))}setMode(e,t){this._mode.mode===e&&this._mode.reason===t||(this._mode=t?{mode:e,reason:t}:{mode:e},this.emit("mode",this._mode),this.followRaw())}followRaw(){if(clearTimeout(this.browserTimer),!this.ownStream||this.disposed)return;this._mode.mode==="raw"&&this._mode.reason!=="off"?this.browserWant||(this.browserTimer=setTimeout(()=>this.wantBrowser(!0),ue)):this.wantBrowser(!1)}wantBrowser(e){this.browserWant=e,this.browserBusy=this.browserBusy.then(()=>this.browser())}async browser(){let e=this.browserWant,t=this.stream.getAudioTracks()[0];if(this.disposed||!this.ownStream||e===this.browserHas||!t)return;try{await t.applyConstraints({...D,noiseSuppression:e,autoGainControl:e})}catch{}let s=t.getSettings().noiseSuppression;if(typeof s=="boolean"&&s!==e){if(this.disposed||!this.ownStream)return;let n=t.getSettings().deviceId??this.opts.deviceId;t.stop();try{let a=await y(n,void 0,e);if(this.disposed||!this.ownStream){for(let d of a.getTracks())d.stop();return}await this.setStream(a,!0)}catch{this.onTrackEnded();return}}this.browserHas=e;let i=this.stream.getAudioTracks()[0]?.getSettings().noiseSuppression;this.diag({code:"mic.browser",level:"info",noiseSuppression:e,autoGainControl:e,applied:typeof i=="boolean"?i:null})}setStatus(e){this._status!==e&&(this._status=e,this.emit("status",e))}diag(e){this.emit("diag",e)}async startModels(){if(!this.disposed){if(!E().simd){this.diag({code:"engine.unsupported",level:"warn",message:"No WebAssembly SIMD: raw microphone for this session."}),this.setMode("raw","unsupported"),this.settle(new p("browser.unsupported","No WebAssembly SIMD: the models cannot run in this browser."),!0);return}this.setMode("raw","loading"),this.followRaw();try{let e=g.get(),t=await e.models("realtime",[...this.models(),...this.spotWords?.words.length?["spot"]:[]]),s;if(this.wantsBackground()){let d=await e.models("background",["timbre"]),c=new MessageChannel;d.post({type:"rt-port",input:this.id,port:c.port2,ref:this.reference()?.toJSON()??null},[c.port2]),s=c.port1,this.bg=d,this.offs.push(d.listen(m=>m.input===this.id&&m.type==="event"&&this.onEvent(m.event)));let l=f(this.opts.voiceprint);this.opts.learn&&await d.call("learner",[this.id,l?.toJSON()??null])}if(this.disposed)return;this.rt=t,this.offs.push(t.listen(d=>this.onRealtime(d)));let i=this.appPort(),n=[...s?[s]:[],...i?[i]:[]];i&&(this.portGiven=!0),await t.request({type:"realtime",input:this.id,opts:this.realtimeOptions(),bg:s,out:i},n),(!this.listening||this.holding)&&t.post({type:"set",input:this.id,...!this.listening&&{listen:!1},...this.holding&&{hold:!0}}),this.spotWords?.words.length&&(await e.models("realtime",["spot"]),t.post({type:"set",input:this.id,...this.spotWords})),this.markRunning(),this.settle(null);let a=new MessageChannel;t.post({type:"worklet",input:this.id,port:a.port2},[a.port2]),this.node.port.postMessage({type:"connect",port:a.port1},[a.port1]),this.printed=!!f(this.opts.voiceprint),this.retryMs=W,this.setMode(this.activeMode(),this.enabled?void 0:"off")}catch(e){if(this.disposed)return;this.diag({code:"models.failed",level:"warn",message:`Models not loaded, raw microphone; retry in ${this.retryMs/1e3} s.`,error:String(e?.message??e)}),this.setMode("raw","failed"),this.settle(e instanceof p?e:new p("engine.failed",`Models not loaded: ${String(e?.message??e)}`,e)),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,F)}}}portGiven=!1;appPort(){return this.portGiven?void 0:this.opts.output?.port}wantsBackground(){return!!this.opts.learn}reference(){return null}onRealtime(e){if(e.input===this.id)if(e.type==="events"){let t=[];for(let s of e.list)s.type==="trace"?t.push(s):this.onEvent(s);t.length&&this.emit("trace",t)}else e.type==="pcm"?e.kind==="audio"?this.emit("audio",e.pcm):this.emit("utterance",{pcm:e.pcm,start:e.start,end:e.end,...e.level&&{level:e.level}}):e.type==="crash"&&(this.node.port.postMessage({type:"stop"}),this.rt=null,this.diag({code:"engine.crash",level:"warn",message:`The engine stopped: raw microphone; retry in ${this.retryMs/1e3} s.`,error:e.message}),this.setMode("raw","failed"),clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,F))}onEvent(e){switch(e.type){case"speechstart":this.emit("speechstart",{start:e.start});break;case"speechcancel":this.emit("speechcancel",{start:e.start});break;case"speechend":this.emit("speechend",{start:e.start,end:e.end,..."voiceDb"in e&&{level:{voiceDb:e.voiceDb,noiseDb:e.noiseDb,refDb:e.refDb}}});break;case"turn":this.emit("turn",{pause:e.pause,probability:e.probability,hesitation:e.hesitation,at:e.at});break;case"turnend":this.emit("turnend",{start:e.start,end:e.end,probability:e.probability,hesitation:e.hesitation,at:e.at});break;case"interruptstart":this.emit("interruptstart",{start:e.start});break;case"interrupt":this.emit("interrupt",{start:e.start,at:e.at});break;case"interruptcancel":this.emit("interruptcancel",{start:e.start,end:e.end});break;case"wake":this.emit("wake",e);break;case"take":{let{type:t,...s}=e;this.emit("take",s);break}case"enrolled":{let{type:t,...s}=e;this.emit("enrolled",s);break}case"heard":this.emit("heard",{speech:e.speech,scores:e.scores});break;case"learn":this.emit("learn",{progress:e.progress});break;case"voiceprint":{let t=$.fromJSON(e.json);t&&(this._voiceprint=t,this.emit("voiceprint",t));break}case"idle":this.diag({code:"idle",level:"info",asleep:e.asleep,at:e.at});break;case"diag":e.code==="focus.print"&&(this.printed=!!e.data?.print,this._mode.mode!=="raw"&&this.setMode(this.activeMode())),this.diag({code:e.code,level:e.level,...e.data});break}}async setEnabled(e){return this.enabled=e,this.rt?.post({type:"set",input:this.id,enabled:e}),e?this.rt&&this._mode.reason==="off"&&this.setMode(this.activeMode()):this.setMode("raw","off"),e&&!!this.rt}listen(e){this.listening=e,this.rt?.post({type:"set",input:this.id,listen:e})}hold(){this.holding=!0,this.rt?.post({type:"set",input:this.id,hold:!0})}release(){this.holding=!1,this.rt?.post({type:"set",input:this.id,hold:!1})}setStrength(e){this.rt?.post({type:"set",input:this.id,strength:e}),this.opts.strength=e}setVoiceprint(e){let t=f(e);e&&!t&&this.diag({code:"voiceprint.reset",level:"warn",message:"This print comes from another Timbre: ignored, learn it again."}),this.opts.voiceprint=t,this.rt?.post({type:"set",input:this.id,print:t?.embedding??null}),this.opts.learn&&this.bg?.call("learner",[this.id,t?.toJSON()??null])}forgetVoiceprint(){this._voiceprint=null,this.rt?.post({type:"set",input:this.id,print:null}),this.bg?.call("forget",[this.id])}farEndActive(e){this.node?.port.postMessage({type:"far",on:e})}async stats(){return this.rt?this.rt.call("stats",[this.id]):null}async record(e){if(!this.rt)throw new p("engine.failed","The models are not running yet.");let t=await this.rt.call("record",[this.id,e]);return new Blob([t],{type:"audio/wav"})}async recent(){let e=this.rt?await this.rt.call("recent",[this.id]):null;return e?new Blob([e],{type:"audio/wav"}):null}async resume(){try{await Promise.race([this.ctx.resume(),new Promise(e=>setTimeout(e,300))])}catch{}this.setStatus(this.ctx.state==="running"?"running":this.ctx.state==="interrupted"?"interrupted":"blocked")}watchContext(){let e=this.ctx,t=()=>{if(this.disposed)return;let d=e.state;d==="running"?this.setStatus("running"):d==="interrupted"?this.setStatus("interrupted"):d==="suspended"&&e.resume().then(()=>this.setStatus(e.state==="running"?"running":"blocked"),()=>this.setStatus("blocked"))};e.addEventListener("statechange",t),this.offs.push(()=>e.removeEventListener("statechange",t));let s=e.currentTime,i=performance.now(),n=0,a=setInterval(()=>{let d=performance.now(),c=(e.currentTime-s)*1e3,l=d-i;s=e.currentTime,i=d,n=e.state!=="running"||c<.9*l?n||d:0;let h=!!n&&d-n>=le;if(h!==this.stalled){this.stalled=h,this.diag({code:h?"audio.stalled":"audio.resumed",level:h?"warn":"info"});let w=this.track;w&&(this.sender?this.sender.replaceTrack(w):this.emit("trackchange",w))}},500);this.offs.push(()=>clearInterval(a))}bind(e){this.sender=e;let t=this.track;t&&e.track!==t&&e.replaceTrack(t)}watchTrack(e){let t=()=>void this.onTrackEnded(),s=()=>this.emit("mic",{state:"muted"}),i=()=>this.emit("mic",{state:"unmuted"});e.addEventListener("ended",t),e.addEventListener("mute",s),e.addEventListener("unmute",i),this.offs.push(()=>{e.removeEventListener("ended",t),e.removeEventListener("mute",s),e.removeEventListener("unmute",i)})}reopenMs=W;async onTrackEnded(){if(!this.disposed&&(this.emit("mic",{state:"lost"}),!!this.ownStream))try{let e=this.browserWant;await this.setStream(await y(this.opts.deviceId,void 0,e),!0),this.browserHas=e,this.reopenMs=W,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,F)}}async setStream(e,t=!1){if(this.ownStream)for(let i of this.stream.getTracks())i!==e.getAudioTracks()[0]&&i.stop();this.source.disconnect(),this.stream=e,this.ownStream=t,this.source=this.ctx.createMediaStreamSource(e),this.source.connect(this.node,0,0);let s=e.getAudioTracks()[0];s&&this.watchTrack(s)}async setDevice(e){this.opts.deviceId=e,this.opts.followDefault=!1;let t=this.browserWant;await this.setStream(await y(e,void 0,t),!0),this.browserHas=t}followDefault(){let e=navigator.mediaDevices;if(!e?.addEventListener)return;let t=this.stream.getAudioTracks()[0]?.getSettings().groupId,s=async()=>{if(this.opts.followDefault===!1||this.disposed)return;let n=(await e.enumerateDevices().catch(()=>[])).find(a=>a.kind==="audioinput"&&a.deviceId==="default");if(n&&n.groupId&&n.groupId!==t){t=n.groupId;let a=this.browserWant;await this.setStream(await y(void 0,void 0,a),!0).then(()=>void(this.browserHas=a)).catch(()=>{}),this.emit("mic",{state:"reopened"})}};e.addEventListener("devicechange",s),this.offs.push(()=>e.removeEventListener("devicechange",s))}async restart({track:e,audioContext:t}={}){let s=this.track;if(t&&t!==this.ctx){if(this.teardownGraph(),this.ownCtx&&this.ctx.close().catch(()=>{}),this.ctx=t,this.ownCtx=!1,e){if(this.ownStream)for(let n of this.stream.getTracks())n.stop();this.stream=new MediaStream([e]),this.ownStream=!1}await this.build(),this.watchContext(),this.rt?.post({type:"dispose",input:this.id}),this.rt=null,this.startModels()}else e&&await this.setStream(new MediaStream([e]));let i=this.track;i&&i!==s&&this.emit("trackchange",i)}teardownGraph(){this.node?.port.postMessage({type:"dispose"});for(let e of[this.source,this.node,this.dest,this.farSource])e?.disconnect()}spot(e,t={}){if(this.kind==="wake")throw new TypeError("spot() reads Focus: use the wake listener itself");return t.onlyMyVoice&&!f(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 H(this,e.map(s=>M(s).toJSON()),t.context??"anywhere")}enrollWord(e,t={}){return new x({compile:async()=>(await import("./api-63K47HT3.js")).Spot.compile(e,{lang:t.lang,chain:"focus"}),open:async s=>{await this.running;let i=await g.get().models("realtime",["spot"]);return i.post({type:"set",input:this.id,enroll:{word:s,takes:t.takes??3}}),{on:this.on.bind(this),stop:()=>i.post({type:"set",input:this.id,enroll:null}),source:"focus"}},embed:async(s,i)=>(await(await import("./api-63K47HT3.js")).Timbre.create()).embed(s,{source:i})})}setWords(e,t){this.spotWords={words:e,context:t},this.rt&&g.get().models("realtime",["spot"]).then(s=>s.post({type:"set",input:this.id,words:e,context:t}))}dispose(){if(!this.disposed){clearTimeout(this.retryTimer),clearTimeout(this.browserTimer),this.setStatus("disposed"),this.settle(new p("engine.failed","The input was disposed before its models ran."),!0),this.counted&&--te===0&&g.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(()=>{}),B.delete(this),this.clear()}}},J=class extends b{constructor(e){super(e);this.opts=e}kind="call";osc=null;get track(){return super.track}get delay16(){return N.lag+.1*k}models(){return["focus","cue"]}chainOptions(){let e=f(this.opts.voiceprint);return{gate:!0,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near}}realtimeOptions(){return{pipeline:"call",chain:this.chainOptions(),learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats}}async start(){if(this.opts.learn&&!this.opts.farEnd&&this.diag({code:"learn.no-far-end",level:"warn",message:"learn without farEnd: the other voice may get into the print."}),await this.open(),this.opts.keepAliveWhenHidden!==!1){this.osc=this.ctx.createOscillator(),this.osc.frequency.value=pe;let e=this.ctx.createGain();e.gain.value=he,this.osc.connect(e).connect(this.ctx.destination),this.osc.start(),this.offs.push(()=>this.osc?.stop())}return this}},H=class extends v{constructor(e,t,s){super();this.input=e;e.setWords(t,s),this.off=e.on("wake",i=>this.emit("wake",i))}off;dispose(){this.off(),this.input.setWords([],"anywhere"),this.clear()}};function Ge(o={}){return new J(o).start()}var K=class extends b{constructor(e){super(e);this.opts=e}kind="agent";packer=null;rawAudio(e){this.packer??=new P(this.output(),t=>{let s=this.appPort();s?s.postMessage({type:"audio",pcm:t},[t]):this.opts.output?.port||this.emit("audio",t)}),this.packer.push(e)}output(){let e=this.opts.output??{};return{format:e.format??"f32",rate:e.rate??k,chunkMs:Math.max(16,Math.round((e.chunkMs??32)/16)*16)}}get delay16(){return N.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=f(this.opts.voiceprint);return{pipeline:"agent",chain:{gate:!1,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near},learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats,output:{...this.output(),audio:!0,utterance:!0},turn:this.opts.turn??!0,interrupt:this.opts.interrupt??!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 Ue(o={}){return new K(o).start()}var G=class extends b{constructor(e){super(e);this.opts=e;if(this.words=e.words.map(t=>M(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: ${se}`})}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 f(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 je(o){return new G(o).start()}var U=class extends b{constructor(e,t,s){super(e);this.opts=e;this.word=t;this.takes=s}kind="wake";models(){return["spot"]}connectOutput(){let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}realtimeOptions(){return{pipeline:"enroll",enroll:{word:this.word,takes:this.takes}}}async start(){return await this.open(),this}};function qe(o,r,e){return new U(o,r,e).start()}export{x as a,O as b,g as c,E as d,Ee as e,Ge as f,Ue as g,je as h,qe as i};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as R,b as m,c as A,d as V,e as W,i as M}from"./chunk-IMUNEOSF.js";import{A as T,a as C,b as d,c as N,e as F,f as S,g as x,h,i as b,k as P,n as y,o as v,p as B,s as L,v as E,z as I}from"./chunk-FC4ZSMUX.js";var c=class{static langs=F.langs;static inventory=S.map(r=>r.normalize("NFC"));static distance(r,t){let n=typeof r=="string"?h(r.replace(/^\/|\/$/g,""))??[]:r,o=typeof t=="string"?h(t.replace(/^\/|\/$/g,""))??[]:t;if(!n.length||!o.length)return n.length===o.length?0:1;let a=Array.from({length:o.length+1},(s,l)=>l);for(let s=1;s<=n.length;s++){let l=[s];for(let i=1;i<=o.length;i++){let f=n[s-1]===o[i-1]?0:x[n[s-1]-1].includes(o[i-1])?.5:1;l.push(Math.min(a[i]+1,l[i-1]+1,a[i-1]+f))}a=l}return a[o.length]/Math.max(n.length,o.length)}};var D=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",H=0,q=null;async function u(e,r){if(D()){let n=await(q??=import("./node-VEIFZSW6.js").then(o=>new o.NodeBackend));return await n.ready(e),{call:async(o,a,s,l)=>n.calls[o](...a,l),hold:()=>()=>{}}}let t=A.get();return await t.models("background",e,r),{call:async(n,o,a=[],s)=>(await t.models("background",e)).call(n,o,a,s),hold:()=>t.hold()}}function U(e,r={}){let t=e==="wake"?["spot"]:["focus","cue"];return r.voiceprint&&t.push("timbre"),r.typedWords&&t.push("lex"),t}async function K(e){if("pcm"in e&&"rate"in e)return m.all(e.pcm,e.rate,d);if(typeof AudioBuffer<"u"&&e instanceof AudioBuffer)return m.all(j(e),e.sampleRate,d);let r=typeof Blob<"u"&&e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e);if(String.fromCharCode(...r.subarray(0,4))==="RIFF"){let{pcm:o,rate:a}=T(r);return m.all(o,a,d)}if(typeof OfflineAudioContext>"u")throw new b("browser.unsupported","Outside a browser only WAV is decoded: decode the file and pass { pcm, rate }.");let n=await new OfflineAudioContext(1,1,44100).decodeAudioData(r.slice().buffer);return m.all(j(n),n.sampleRate,d)}function j(e){if(e.numberOfChannels===1)return e.getChannelData(0).slice();let r=new Float32Array(e.length);for(let t=0;t<e.numberOfChannels;t++){let n=e.getChannelData(t);for(let o=0;o<r.length;o++)r[o]+=n[o]/e.numberOfChannels}return r}var we={configure:B,stream:Q,supported:V,micPermission:W,onDiag:L,async preload(e,r={}){let t=U(e,r);if(D()){await u(t);return}let n=A.get(),o=t.filter(i=>i!=="timbre"&&i!=="lex"),a=t.filter(i=>i==="timbre"||i==="lex"),s=[{loaded:0,total:0},{loaded:0,total:0}],l=i=>f=>{s[i]=f,r.onProgress?.({loaded:s[0].loaded+s[1].loaded,total:s[0].total+s[1].total})};await Promise.all([n.models("realtime",o,l(0)),a.length?n.models("background",a,l(1)):null])},async cached(e,r={}){let t=[C,...U(e,r).map(n=>N[n])];return(await Promise.all(t.map(E))).every(Boolean)},async process(e,r={}){let t=await K(e);r.signal?.throwIfAborted();let o=await(await u(G(r))).call("process",[t,_(r)],[],r.onProgress);return{...o,toWav(a="audio"){return I(a==="both"?[o.raw,o.audio]:[a==="raw"?o.raw:o.audio],d)}}}};function G(e){let r=[];return e.focus?r.push("focus","cue"):e.cue&&r.push("cue"),e.spot?.words.length&&r.push("spot"),r}function _(e){let{onProgress:r,signal:t,...n}=e;return{...n,focus:typeof e.focus=="object"?{...e.focus,voiceprint:e.focus.voiceprint instanceof y?e.focus.voiceprint.toJSON():e.focus.voiceprint}:e.focus,spot:e.spot?{...e.spot,words:e.spot.words.map(o=>P(o).toJSON())}:void 0}}async function*Q(e,r={}){let t=await u(G(r)),n=++H,o=t.hold();await t.call("streamOpen",[n,_(r)]).catch(p=>{throw o(),p});let a=r.rate??d,s=new m(a,d,!0),l=0,i=0,f=Symbol.asyncIterator in e?e:Y(e);try{for await(let g of f){r.signal?.throwIfAborted();let w=[];l+=g.length,s.push(g,X=>w.push(X)),i+=w.length,w.length&&(yield await t.call("streamPush",[n,Float32Array.from(w)]))}let p=[],k=Math.round(l*d/a)-i;k>0&&s.push(new Float32Array(m.HALF*2+8),g=>p.length<k&&p.push(g)),p.length&&(yield await t.call("streamPush",[n,Float32Array.from(p)]))}finally{try{yield await t.call("streamEnd",[n])}finally{o()}}}async function*Y(e){let r=e.getReader();try{for(;;){let{done:t,value:n}=await r.read();if(t)return;yield n}}finally{r.releaseLock()}}var O=class e{constructor(r){this.b=r}static async create(){return new e(await u(["timbre"]))}async embed(r,t={}){return y.fromJSON(await this.b.call("embed",[r,t.source??"raw"]))}verify(r,t,n={}){return v.verify(r,t,n)}async identify(r,t,n={}){let o=r instanceof y?r:await this.embed(r);return v.identify(o,t,n)}},z=class e{constructor(r){this.b=r}static inventory=c.inventory;static langs=c.langs;static distance=c.distance;static async create(){return new e(await u(["lex"]))}async phonemize(r,t){if(!c.langs.includes(t))throw new b("lang.unsupported",`No ${t}: ${c.langs.join(", ")} only.`);let o=(await this.b.call("phonemize",[Array.isArray(r)?r:[r],t])).map(a=>a.map(({ipa:s,p:l})=>({ipa:s,p:l})));return Array.isArray(r)?o:o[0]}},Z={async compile(e,r={}){for(let o of[r.lang??[]].flat())if(!c.langs.includes(o))throw new b("lang.unsupported",`No ${o}: ${c.langs.join(", ")} only.`);let t=/^\s*\/.+\/\s*$/.test(e),n=await u(t?[]:["lex"]);return P(await n.call("compile",[e,{lang:r.lang,chain:r.chain}]))},enroll(e,r={}){return new R({compile:()=>Z.compile(e,r),open:async t=>{let n=await M(r,t,r.takes??3);return{on:n.on.bind(n),stop:()=>n.dispose(),source:"raw"}},embed:async(t,n)=>(await O.create()).embed(t,{source:n})})}},J=e=>e?new y(e.centers,e.source,e.model,e.windows):null,ee=e=>({alkove:"voiceprint",model:e.model,source:e.source,centers:e.centers,windows:e.windows}),re=typeof FinalizationRegistry>"u"?null:new FinalizationRegistry(e=>e()),$=class e{constructor(r,t,n,o){this.b=r;this.id=t;this.state={progress:n.progress,ready:n.ready,voiceprint:J(n.voiceprint)},re?.register(this,()=>void r.call("learnerClose",[t]).catch(()=>{}).finally(o))}state;static async create(r={}){let t=await u(["timbre"]),n=++H,o=t.hold();try{let a=await t.call("learnerOpen",[n,r.voiceprint?ee(r.voiceprint):null]);return new e(t,n,a,o)}catch(a){throw o(),a}}get progress(){return this.state.progress}get ready(){return this.state.ready}get voiceprint(){return this.state.voiceprint}async offer(r){let t=await this.b.call("learnerOffer",[this.id,r]);return this.state={progress:t.progress,ready:t.ready,voiceprint:J(t.voiceprint)},{accepted:t.accepted,rejected:t.rejected,progress:t.progress,ready:t.ready}}forget(){this.state={progress:0,ready:!1,voiceprint:null},this.b.call("learnerForget",[this.id])}};export{we as a,O as b,z as c,Z as d,$ as e};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as n,b as s,c as a,d as i,e as c}from"./chunk-MZOMHWYI.js";import{f as o,g as t,h as p}from"./chunk-IMUNEOSF.js";import{i as e,n as r}from"./chunk-FC4ZSMUX.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};
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AgentInput, AgentOptions, CallInput, CallOptions, InputEvents, Mode, Status, WakeListener, WakeOptions } from './recipes/input';
|
|
2
|
+
export type Handlers = {
|
|
3
|
+
[K in keyof InputEvents]?: (value: InputEvents[K]) => void;
|
|
4
|
+
};
|
|
5
|
+
export interface HookOptions {
|
|
6
|
+
enabled?: boolean;
|
|
7
|
+
on?: Handlers;
|
|
8
|
+
}
|
|
9
|
+
export interface InputState<I> {
|
|
10
|
+
input: I | null;
|
|
11
|
+
status: Status | 'off';
|
|
12
|
+
mode: Mode | null;
|
|
13
|
+
error: Error | null;
|
|
14
|
+
track: MediaStreamTrack | null;
|
|
15
|
+
resume: () => Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export declare function useAgentInput(options?: Omit<AgentOptions, 'signal'> & HookOptions): InputState<AgentInput>;
|
|
18
|
+
export declare function useCallInput(options?: Omit<CallOptions, 'signal'> & HookOptions): InputState<CallInput>;
|
|
19
|
+
export declare function useWakeListener(options: Omit<WakeOptions, 'signal'> & HookOptions): InputState<WakeListener>;
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import{f as W,g as T,h as J}from"./chunk-IMUNEOSF.js";import"./chunk-FC4ZSMUX.js";import{useCallback as D,useEffect as I,useLayoutEffect as Q,useRef as p,useState as v}from"react";var M=t=>Array.isArray(t)||Object.getPrototypeOf(t)===Object.prototype;function k(t,r){if(Object.is(t,r))return!0;if(typeof t!="object"||typeof r!="object"||!t||!r)return!1;let u=t.toJSON,a=r.toJSON;if(typeof u=="function"||typeof a=="function")return k(typeof u=="function"?u.call(t):t,typeof a=="function"?a.call(r):r);if(!M(t)||!M(r)||Array.isArray(t)!==Array.isArray(r))return!1;let l=Object.keys(t).filter(o=>t[o]!==void 0),h=Object.keys(r).filter(o=>r[o]!==void 0);return l.length===h.length&&l.every(o=>k(t[o],r[o]))}var X={speechstart:!0,speechend:!0,speechcancel:!0,turn:!0,turnend:!0,interruptstart:!0,interrupt:!0,interruptcancel:!0,mode:!0,status:!0,voiceprint:!0,learn:!0,mic:!0,trackchange:!0,wake:!0,heard:!0,trace:!0,audio:!0,utterance:!0,take:!0,enrolled:!0},Y=Object.keys(X),C=1,F=Promise.resolve(),Z=typeof window>"u"?I:Q;function N(t,r,u){let{enabled:a=!0,on:l,...h}=r,o=h,m=p(l),R=p(o),S=Object.fromEntries(Object.entries(o).filter(([n])=>!u.includes(n))),f=p({value:S,version:0}),w=k(f.current.value,S)?f.current.version:f.current.version+1;Z(()=>{m.current=l,R.current=o,w!==f.current.version&&(f.current={value:S,version:w})});let[b,H]=v(null),[K,d]=v("off"),[q,E]=v(null),[G,A]=v(null),[U,j]=v(null),s=p(null),c=p({}),i=p(null),O=D(()=>{let n=!!s.current&&!!m.current?.diag;n&&!i.current?i.current=s.current.on("diag",g=>m.current?.diag?.(g)):!n&&i.current&&(i.current(),i.current=null)},[]);I(()=>{if(!a)return;let n=new AbortController,g=[];d("starting"),A(null);let V=F.then(()=>{if(n.signal.aborted)return;let e={...R.current,signal:n.signal};return c.current={strength:e.strength??C,voiceprint:e.voiceprint??null},t(e)});return F=V.catch(()=>{}),V.then(e=>{if(e){if(n.signal.aborted)return e.dispose();s.current=e,O();for(let y of Y)g.push(e.on(y,(B=>m.current?.[y]?.(B))));g.push(e.on("status",d),e.on("mode",y=>E(y.mode)),e.on("trackchange",j)),H(e),d(e.status),E(e.mode),j(e.track)}},e=>{n.signal.aborted||(A(e instanceof Error?e:new Error(String(e))),d("off"))}),()=>{n.abort();for(let e of g)e();i.current?.(),i.current=null,s.current?.dispose(),s.current=null,H(null),d("off"),E(null),j(null),A(null)}},[a,w,t,O]);let _=!!l?.diag;I(O,[b,_,O]);let L=u.includes("strength")?o.strength:void 0,x=u.includes("voiceprint")?o.voiceprint:void 0;I(()=>{let n=s.current;n&&(u.includes("strength")&&(L??C)!==c.current.strength&&(c.current.strength=L??C,n.setStrength(c.current.strength)),u.includes("voiceprint")&&!k(x??null,c.current.voiceprint??null)&&(c.current.voiceprint=x??null,n.setVoiceprint(c.current.voiceprint)))},[b,L,x,u]);let z=D(async()=>{await s.current?.resume()},[]);return{input:b,status:K,mode:q,error:G,track:U,resume:z}}var P=["strength","voiceprint"],$=[];function ot(t={}){return N(T,t,P)}function ut(t={}){return N(W,t,P)}function st(t){return N(J,t,$)}export{ot as useAgentInput,ut as useCallInput,st as useWakeListener};
|
package/dist/same.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function same(a: unknown, b: unknown): boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "alkove",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
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",
|
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
"webrtc",
|
|
23
23
|
"voice-agent",
|
|
24
24
|
"on-device",
|
|
25
|
+
"react",
|
|
25
26
|
"browser",
|
|
26
27
|
"webassembly",
|
|
27
28
|
"wasm"
|
|
@@ -41,6 +42,10 @@
|
|
|
41
42
|
".": {
|
|
42
43
|
"types": "./dist/index.d.ts",
|
|
43
44
|
"default": "./dist/index.js"
|
|
45
|
+
},
|
|
46
|
+
"./react": {
|
|
47
|
+
"types": "./dist/react.d.ts",
|
|
48
|
+
"default": "./dist/react.js"
|
|
44
49
|
}
|
|
45
50
|
},
|
|
46
51
|
"files": [
|
|
@@ -48,6 +53,14 @@
|
|
|
48
53
|
"LICENSE",
|
|
49
54
|
"NOTICE"
|
|
50
55
|
],
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"react": ">=18"
|
|
58
|
+
},
|
|
59
|
+
"peerDependenciesMeta": {
|
|
60
|
+
"react": {
|
|
61
|
+
"optional": true
|
|
62
|
+
}
|
|
63
|
+
},
|
|
51
64
|
"scripts": {
|
|
52
65
|
"build": "node scripts/build.mjs",
|
|
53
66
|
"check": "tsc --noEmit",
|
|
@@ -56,8 +69,14 @@
|
|
|
56
69
|
},
|
|
57
70
|
"devDependencies": {
|
|
58
71
|
"@playwright/test": "1.60.0",
|
|
72
|
+
"@testing-library/react": "16.3.3",
|
|
59
73
|
"@types/node": "^22.10.0",
|
|
74
|
+
"@types/react": "19.3.0",
|
|
75
|
+
"@types/react-dom": "19.3.0",
|
|
60
76
|
"esbuild": "^0.25.0",
|
|
77
|
+
"jsdom": "30.1.3",
|
|
78
|
+
"react": "19.3.1",
|
|
79
|
+
"react-dom": "19.3.1",
|
|
61
80
|
"tsx": "^4.23.15",
|
|
62
81
|
"typescript": "^5.7.0",
|
|
63
82
|
"vitest": "^3.0.0"
|
package/dist/api-5UTMEGDH.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as a,e as b,f as c,g as d,h as e}from"./chunk-CWKQLHLV.js";import"./chunk-FC4ZSMUX.js";export{a as Alkove,c as Lex,d as Spot,b as Timbre,e as VoiceprintLearner};
|
package/dist/chunk-CWKQLHLV.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{A as ue,B as b,a as E,b as f,c as ee,d as B,e as te,f as re,g as se,h as V,i as p,j as oe,k,l as ie,m as _,n as S,o as D,p as ne,q as W,r as ae,s as R,t as N,u as J,v as le,w as ce,x as de,z as pe}from"./chunk-FC4ZSMUX.js";var v=class{static langs=te.langs;static inventory=re.map(r=>r.normalize("NFC"));static distance(r,e){let t=typeof r=="string"?V(r.replace(/^\/|\/$/g,""))??[]:r,s=typeof e=="string"?V(e.replace(/^\/|\/$/g,""))??[]:e;if(!t.length||!s.length)return t.length===s.length?0:1;let i=Array.from({length:s.length+1},(n,l)=>l);for(let n=1;n<=t.length;n++){let l=[n];for(let a=1;a<=s.length;a++){let c=t[n-1]===s[a-1]?0:se[t[n-1]-1].includes(s[a-1])?.5:1;l.push(Math.min(i[a]+1,l[a-1]+1,i[a-1]+c))}i=l}return i[s.length]/Math.max(t.length,s.length)}};var M=class{handlers=new Map;on(r,e){let t=this.handlers.get(r);return t||this.handlers.set(r,t=new Set),t.add(e),()=>void t.delete(e)}emit(r,e){for(let t of this.handlers.get(r)??[])try{t(e)}catch(s){queueMicrotask(()=>{throw s})}}listens(r){return!!this.handlers.get(r)?.size}clear(){this.handlers.clear()}};var P=class extends M{done;target=null;cancelled=!1;abort=null;constructor(r){super(),this.done=this.run(r),this.done.catch(()=>{})}async run(r){let e=await r.compile();for(let i of e.warnings)this.emit("warning",i);if(this.cancelled)throw new DOMException("cancelled","AbortError");let t=this.target=await r.open(e.toJSON()),s=[t.on("take",i=>this.emit("take",i))];try{let i=await new Promise((c,d)=>{s.push(t.on("enrolled",c)),this.abort=()=>d(new DOMException("cancelled","AbortError"))});if(i.error||!i.word)throw new p("engine.failed",i.error??"enrollment failed");for(let c of i.warnings??[])this.emit("warning",c);let n=i.audio&&i.audio.length>=4e3?await r.embed(i.audio,t.source):null,l=k(i.word);return{word:new oe(l.text,l.lang,l.phonemes,l.thresholds,l.calibrated,l.chain,[...e.warnings,...i.warnings??[]]),voiceprint:n}}finally{for(let i of s)i();t.stop()}}cancel(){this.cancelled=!0,this.abort?.(),this.target?.stop()}};var m=24,C=128,g=class o{constructor(r,e,t=!1){this.inRate=r;this.outRate=e;if(this.identity=r===e,t&&(this.t=m),this.identity)return;this.ratio=r/e;let s=this.half,i=.9/Math.max(1,this.ratio),n=new Float32Array((C+1)*m);for(let l=0;l<=C;l++){let a=l/C,c=0;for(let d=0;d<m;d++){let h=d-(s-1)-a,u=i*h,w=u===0?1:ie(Math.PI*u)/(Math.PI*u),F=.42+.5*_(Math.PI*h/s)+.08*_(2*Math.PI*h/s);n[l*m+d]=w*F,c+=n[l*m+d]}for(let d=0;d<m;d++)n[l*m+d]/=c}this.table=n}static HALF=m/2;identity;ratio=1;half=m/2;table=new Float32Array(0);work=new Float32Array(0);histLen=m;t=m/2;push(r,e){if(this.identity){for(let a=0;a<r.length;a++)e(r[a]);return}if(this.work.length<m+8+r.length){let a=new Float32Array(m+8+r.length);a.set(this.work.subarray(0,this.histLen)),this.work=a}let t=this.work;t.set(r,this.histLen);let s=this.histLen+r.length,i=s-1-this.half,n=this.t;for(;n<=i;){let a=Math.floor(n),c=Math.round((n-a)*C)*m,d=a-(this.half-1),h=0;for(let u=0;u<m;u++)h+=t[d+u]*this.table[c+u];e(h),n+=this.ratio}let l=Math.floor(n)-(this.half-1);t.copyWithin(0,l,s),this.histLen=s-l,this.t=n-l}static all(r,e,t){if(e===t)return r;let s=new o(e,t,!0),i=Math.round(r.length*t/e),n=new Float32Array(i),l=0,a=c=>{l<i&&(n[l++]=c)};return s.push(r,a),s.push(new Float32Array(Math.ceil(m*s.ratio)+16),a),n}};var I=class{constructor(r,e){this.opts=r;this.send=e;this.resampler=new g(f,r.rate),this.buf=new Float32Array(Math.round(r.rate*r.chunkMs/1e3))}resampler;buf;fill=0;push(r){this.resampler.push(r,e=>{this.buf[this.fill++]=e,this.fill===this.buf.length&&(this.send(Oe(this.buf,this.opts.format)),this.fill=0)})}};function Oe(o,r){if(r==="f32")return o.slice().buffer;let e=new Int16Array(o.length);for(let t=0;t<o.length;t++){let s=Math.max(-1,Math.min(1,o[t]));e[t]=s<0?s*32768:s*32767}return e.buffer}var U=class{constructor(r){this.worker=r;r.onmessage=e=>{let t=e.data;if(t?.type==="reply"){let s=this.replies.get(t.id);this.replies.delete(t.id),t.error?s?.reject(Object.assign(new Error(t.error.message),{code:t.error.code})):s?.resolve(t.result)}else if(t?.type==="progress")this.replies.get(t.id)?.progress?.(t.p);else for(let s of this.listeners)s(t)},r.onerror=e=>{for(let t of this.replies.values())t.reject(new p("engine.failed",e.message||"worker failed"));this.replies.clear();for(let t of this.listeners)t({type:"crash",message:e.message})}}next=1;replies=new Map;listeners=new Set;listen(r){return this.listeners.add(r),()=>void this.listeners.delete(r)}get busy(){return this.replies.size>0}request(r,e=[],t){let s=this.next++;return new Promise((i,n)=>{this.replies.set(s,{resolve:i,reject:n,progress:t}),this.worker.postMessage({...r,id:s,progress:!!t},e)})}call(r,e,t=[],s){return this.request({type:"call",method:r,args:e},t,s)}post(r,e=[]){this.worker.postMessage(r,e)}},Ee=null,We=()=>Ee??=import("./assets-CPGXIA43.js");async function H(o){let r=W().assetBaseUrl;if(r)return J(r,`alkove-${o}.js`);let e=await We();return URL.createObjectURL(new Blob([o==="worker"?e.WORKER:e.WORKLET],{type:"text/javascript"}))}var he=null;function Re(o){return he??=(async()=>{let r=W().models?.engine,e=W().assetBaseUrl,t=r??(e?J(e,E.file):new URL("./alkove-engine.wasm",import.meta.url).href),s=await ce(E,o,t);return WebAssembly.compile(s)})().catch(r=>{throw he=null,r})}var y=class o{static current=null;sent={realtime:new Set,background:new Set};links={};holds=0;static get(){return ae(),o.current??=new o}link(r){return this.links[r]??=(async()=>{let[e,t]=await Promise.all([Re(),H("worker")]),s=new U(new Worker(t,{type:"module",name:`alkove-${r}`})),i=this.links[r];return s.listen(n=>n.type==="crash"&&this.links[r]===i&&this.drop(r,s)),await new Promise((n,l)=>{let a=s.listen(c=>{c.type==="booted"?(a(),n()):c.type==="crash"&&l(new p("engine.failed",c.message))});s.post({type:"boot",module:e})}),s})().catch(e=>{throw delete this.links[r],e})}drop(r,e){delete this.links[r],this.sent[r].clear(),e.worker.terminate()}hold(){this.holds++;let r=!0;return()=>{r&&this.holds--,r=!1}}async idle(){for(let r of["realtime","background"]){let e=this.links[r],t=e&&await e.catch(()=>null);t&&this.links[r]===e&&(r==="realtime"||!t.busy&&!this.holds)&&this.drop(r,t)}}async models(r,e,t){let s=await this.link(r),i=e.filter(c=>!this.sent[r].has(c));if(!i.length)return s;let n=new Map,l=await Promise.all(i.map(c=>de(c,d=>{n.set(c,d);let h=0,u=0;for(let w of n.values())h+=w.loaded,u+=w.total;t?.({loaded:h,total:u})}))),a=Object.fromEntries(i.map((c,d)=>[c,l[d].slice().buffer]));await s.request({type:"models",models:a},Object.values(a));for(let c of i)this.sent[r].add(c);return s}static report=N};var Ne=5e3,Ce=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function T(){let o=globalThis,r=!1;try{r=typeof WebAssembly<"u"&&WebAssembly.validate(Ce)}catch{}return{worklet:typeof o.AudioWorkletNode=="function",simd:r,secure:o.isSecureContext!==!1}}async function me(){try{let o=await navigator.permissions.query({name:"microphone"});return o.state==="granted"||o.state==="denied"?o.state:"prompt"}catch{return"prompt"}}var j={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,voiceIsolation:!1,channelCount:1};async function x(o,r,e=!1){if(!T().secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!navigator.mediaDevices?.getUserMedia)throw new p("browser.unsupported","No getUserMedia in this browser.");let t=setTimeout(()=>N({code:"mic.waiting",level:"info",message:"The permission prompt has had no answer for 5 s."}),Ne);try{let s=e?{noiseSuppression:!0,autoGainControl:!0}:{},i=navigator.mediaDevices.getUserMedia({audio:{...j,...s,...o?{deviceId:{exact:o}}:{}}});return await(r?Promise.race([i,new Promise((l,a)=>{r.aborted&&a(r.reason),r.addEventListener("abort",()=>{i.then(c=>c.getTracks().forEach(d=>d.stop()),()=>{}),a(r.reason)})})]):i)}catch(s){if(r?.aborted)throw r.reason;let i=s?.name;throw i==="NotAllowedError"||i==="SecurityError"?new p("mic.denied","Microphone permission denied.",s):i==="NotFoundError"||i==="OverconstrainedError"?new p("mic.not-found","No microphone.",s):i==="NotReadableError"||i==="AbortError"?new p("mic.busy","The microphone is used by another app.",s):s}finally{clearTimeout(t)}}function fe(o){let r=o.getSettings();return["noiseSuppression","autoGainControl","voiceIsolation"].filter(e=>r[e]===!0)}var L=5e3,G=6e4,Ie=1500,Le=30,Fe=.002,Be=2e3,Ve=0,K=new WeakMap,$=new Set,we=0,ge="This print comes from another Timbre: ignored, learn it again.",O=class extends M{constructor(e){super();this.opts=e;this.running=new Promise(t=>this.markRunning=t)}id=++Ve;ctx;ownCtx=!1;stream;ownStream=!1;source;node;dest=null;farSource=null;rt=null;bg=null;offs=[];_mode={mode:"raw",reason:"loading"};_status="starting";_latency=0;_voiceprint=null;retryMs=L;retryTimer;started=0;counted=!1;enabled=!0;printed=!1;sender=null;stalled=!1;spotWords=null;running;markRunning;ran=!1;notReady=null;waiting=[];warned=new Set;browserWant=!1;browserHas=!1;browserBusy=Promise.resolve();browserTimer;listening=!0;holding=!1;get disposed(){return this._status==="disposed"}get mode(){return this._mode.mode}get status(){return this._status}get latency(){return this._latency}get voiceprint(){return this._voiceprint}get ready(){return this.ran?Promise.resolve():this.notReady?Promise.reject(this.notReady):new Promise((e,t)=>this.waiting.push([e,t]))}settle(e,t=!1){if(this.ran)return;this.ran=!e,t&&(this.notReady=e);let s=this.waiting;this.waiting=[];for(let[i,n]of s)e?n(e):i()}get track(){return this.stalled?this.stream.getAudioTracks()[0]??null:this.dest?.stream.getAudioTracks()[0]??null}now(){return this.ctx?this.ctx.currentTime-this.started:0}get delay16(){return 0}async open(){we++,this.counted=!0;try{await this.opening()}catch(e){throw this.dispose(),e}}async opening(){this.offs.push(R(i=>this.diag(i))),this.opts.voiceprint&&!b(this.opts.voiceprint)&&this.diag({code:"voiceprint.reset",level:"warn",message:ge});let e=T();if(!e.secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!e.worklet)throw new p("browser.unsupported","No AudioWorklet in this browser (Safari 14.1 or later).");let t=this.opts;t.stream||t.track?this.stream=t.stream??new MediaStream([t.track]):(this.stream=await x(t.deviceId,t.signal),this.ownStream=!0);let s=this.stream.getAudioTracks()[0];if(!s)throw new p("mic.not-found","The stream has no audio track.");if(!this.ownStream){let i=fe(s);i.length&&this.diag({code:"mic.processed",level:"warn",message:`The browser processes the stream before the models (${i.join(", ")}): open it with these off.`,settings:i})}for(let i of $)i.stream.getAudioTracks()[0]?.getSettings().deviceId===s.getSettings().deviceId&&i!==this&&this.diag({code:"mic.twice",level:"warn",message:"Two inputs on the same microphone run everything twice: use call.spot() for words on a call input."});t.audioContext?this.ctx=t.audioContext:(this.ctx=new AudioContext,this.ownCtx=!0),await this.build(),$.add(this),this.watchContext(),this.watchTrack(s),this.ownStream&&t.followDefault!==!1&&!t.deviceId&&this.followDefault(),this.startModels(),this.flushHeld()}async build(){let e=this.ctx,t=K.get(e);t||(t=H("worklet").then(i=>e.audioWorklet.addModule(i)),t.catch(()=>K.delete(e)),K.set(e,t)),await t,this.node=new AudioWorkletNode(e,"alkove",{numberOfInputs:2,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{delay16:this.delay16,tapRaw:this.kind==="agent"}}),this.node.port.onmessage=i=>this.onWorklet(i.data),this.source=e.createMediaStreamSource(this.stream),this.source.connect(this.node,0,0);let s=this.opts.farEnd;s&&s!=="manual"&&(this.farSource=s instanceof MediaStreamTrack?e.createMediaStreamSource(new MediaStream([s])):s,this.farSource.connect(this.node,0,1)),this.connectOutput(),this.started=e.currentTime,await this.resume()}connectOutput(){this.dest=this.ctx.createMediaStreamDestination(),this.node.connect(this.dest)}onWorklet(e){e.type==="overload"?(this.diag({code:"overload",level:"warn",message:"The device is too slow for the models: raw microphone for a while.",queueMs:e.queueMs,sent:e.sent,received:e.received}),this.setMode("raw","overload")):e.type==="retry"?this.setMode(this.activeMode()):e.type==="latency"?this._latency=Math.round(e.ms):e.type==="raw"?this.rawAudio(e.pcm):e.type==="timing"&&(this._latency=e.latencyMs,this.diag({code:"queue",level:"info",...e}))}rawAudio(e){}activeMode(){return this.enabled?this.kind==="wake"?this.reference()?"spot+print":"spot":this.printed?"focus+print":"focus":"raw"}held=[];emit(e,t){this.held?this.held.push([e,t]):this.deliver(e,t)}flushHeld(){setTimeout(()=>{let e=this.held??[];this.held=null;for(let[t,s]of e)this.deliver(t,s)},0)}deliver(e,t){if(super.emit(e,t),e!=="diag")return;let s=t;s.level!=="warn"||this.listens("diag")||this.warned.has(s.code)||(this.warned.add(s.code),console.warn(`alkove: ${s.message??s.code}`,s))}setMode(e,t){this._mode.mode===e&&this._mode.reason===t||(this._mode=t?{mode:e,reason:t}:{mode:e},this.emit("mode",this._mode),this.followRaw())}followRaw(){if(clearTimeout(this.browserTimer),!this.ownStream||this.disposed)return;this._mode.mode==="raw"&&this._mode.reason!=="off"?this.browserWant||(this.browserTimer=setTimeout(()=>this.wantBrowser(!0),Be)):this.wantBrowser(!1)}wantBrowser(e){this.browserWant=e,this.browserBusy=this.browserBusy.then(()=>this.browser())}async browser(){let e=this.browserWant,t=this.stream.getAudioTracks()[0];if(this.disposed||!this.ownStream||e===this.browserHas||!t)return;try{await t.applyConstraints({...j,noiseSuppression:e,autoGainControl:e})}catch{}let s=t.getSettings().noiseSuppression;if(typeof s=="boolean"&&s!==e){if(this.disposed||!this.ownStream)return;let n=t.getSettings().deviceId??this.opts.deviceId;t.stop();try{let l=await x(n,void 0,e);if(this.disposed||!this.ownStream){for(let a of l.getTracks())a.stop();return}await this.setStream(l,!0)}catch{this.onTrackEnded();return}}this.browserHas=e;let i=this.stream.getAudioTracks()[0]?.getSettings().noiseSuppression;this.diag({code:"mic.browser",level:"info",noiseSuppression:e,autoGainControl:e,applied:typeof i=="boolean"?i:null})}setStatus(e){this._status!==e&&(this._status=e,this.emit("status",e))}diag(e){this.emit("diag",e)}async startModels(){if(!this.disposed){if(!T().simd){this.diag({code:"engine.unsupported",level:"warn",message:"No WebAssembly SIMD: raw microphone for this session."}),this.setMode("raw","unsupported"),this.settle(new p("browser.unsupported","No WebAssembly SIMD: the models cannot run in this browser."),!0);return}this.setMode("raw","loading"),this.followRaw();try{let e=y.get(),t=await e.models("realtime",[...this.models(),...this.spotWords?.words.length?["spot"]:[]]),s;if(this.wantsBackground()){let a=await e.models("background",["timbre"]),c=new MessageChannel;a.post({type:"rt-port",input:this.id,port:c.port2,ref:this.reference()?.toJSON()??null},[c.port2]),s=c.port1,this.bg=a,this.offs.push(a.listen(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=[...s?[s]:[],...i?[i]:[]];i&&(this.portGiven=!0),await t.request({type:"realtime",input:this.id,opts:this.realtimeOptions(),bg:s,out:i},n),(!this.listening||this.holding)&&t.post({type:"set",input:this.id,...!this.listening&&{listen:!1},...this.holding&&{hold:!0}}),this.spotWords?.words.length&&(await e.models("realtime",["spot"]),t.post({type:"set",input:this.id,...this.spotWords})),this.markRunning(),this.settle(null);let l=new MessageChannel;t.post({type:"worklet",input:this.id,port:l.port2},[l.port2]),this.node.port.postMessage({type:"connect",port:l.port1},[l.port1]),this.printed=!!b(this.opts.voiceprint),this.retryMs=L,this.setMode(this.activeMode(),this.enabled?void 0:"off")}catch(e){if(this.disposed)return;this.diag({code:"models.failed",level:"warn",message:`Models not loaded, raw microphone; retry in ${this.retryMs/1e3} s.`,error:String(e?.message??e)}),this.setMode("raw","failed"),this.settle(e instanceof p?e:new p("engine.failed",`Models not loaded: ${String(e?.message??e)}`,e)),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,G)}}}portGiven=!1;appPort(){return this.portGiven?void 0:this.opts.output?.port}wantsBackground(){return!!this.opts.learn}reference(){return null}onRealtime(e){if(e.input===this.id)if(e.type==="events"){let t=[];for(let s of e.list)s.type==="trace"?t.push(s):this.onEvent(s);t.length&&this.emit("trace",t)}else e.type==="pcm"?e.kind==="audio"?this.emit("audio",e.pcm):this.emit("utterance",{pcm:e.pcm,start:e.start,end:e.end,...e.level&&{level:e.level}}):e.type==="crash"&&(this.node.port.postMessage({type:"stop"}),this.rt=null,this.diag({code:"engine.crash",level:"warn",message:`The engine stopped: raw microphone; retry in ${this.retryMs/1e3} s.`,error:e.message}),this.setMode("raw","failed"),clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,G))}onEvent(e){switch(e.type){case"speechstart":this.emit("speechstart",{start:e.start});break;case"speechcancel":this.emit("speechcancel",{start:e.start});break;case"speechend":this.emit("speechend",{start:e.start,end:e.end,..."voiceDb"in e&&{level:{voiceDb:e.voiceDb,noiseDb:e.noiseDb,refDb:e.refDb}}});break;case"turn":this.emit("turn",{pause:e.pause,probability:e.probability,hesitation:e.hesitation,at:e.at});break;case"turnend":this.emit("turnend",{start:e.start,end:e.end,probability:e.probability,hesitation:e.hesitation,at:e.at});break;case"interruptstart":this.emit("interruptstart",{start:e.start});break;case"interrupt":this.emit("interrupt",{start:e.start,at:e.at});break;case"interruptcancel":this.emit("interruptcancel",{start:e.start,end:e.end});break;case"wake":this.emit("wake",e);break;case"take":{let{type:t,...s}=e;this.emit("take",s);break}case"enrolled":{let{type:t,...s}=e;this.emit("enrolled",s);break}case"heard":this.emit("heard",{speech:e.speech,scores:e.scores});break;case"learn":this.emit("learn",{progress:e.progress});break;case"voiceprint":{let t=S.fromJSON(e.json);t&&(this._voiceprint=t,this.emit("voiceprint",t));break}case"idle":this.diag({code:"idle",level:"info",asleep:e.asleep,at:e.at});break;case"diag":e.code==="focus.print"&&(this.printed=!!e.data?.print,this._mode.mode!=="raw"&&this.setMode(this.activeMode())),this.diag({code:e.code,level:e.level,...e.data});break}}async setEnabled(e){return this.enabled=e,this.rt?.post({type:"set",input:this.id,enabled:e}),e?this.rt&&this._mode.reason==="off"&&this.setMode(this.activeMode()):this.setMode("raw","off"),e&&!!this.rt}listen(e){this.listening=e,this.rt?.post({type:"set",input:this.id,listen:e})}hold(){this.holding=!0,this.rt?.post({type:"set",input:this.id,hold:!0})}release(){this.holding=!1,this.rt?.post({type:"set",input:this.id,hold:!1})}setStrength(e){this.rt?.post({type:"set",input:this.id,strength:e}),this.opts.strength=e}setVoiceprint(e){let t=b(e);e&&!t&&this.diag({code:"voiceprint.reset",level:"warn",message:"This print comes from another Timbre: ignored, learn it again."}),this.opts.voiceprint=t,this.rt?.post({type:"set",input:this.id,print:t?.embedding??null}),this.opts.learn&&this.bg?.call("learner",[this.id,t?.toJSON()??null])}forgetVoiceprint(){this._voiceprint=null,this.rt?.post({type:"set",input:this.id,print:null}),this.bg?.call("forget",[this.id])}farEndActive(e){this.node?.port.postMessage({type:"far",on:e})}async stats(){return this.rt?this.rt.call("stats",[this.id]):null}async record(e){if(!this.rt)throw new p("engine.failed","The models are not running yet.");let t=await this.rt.call("record",[this.id,e]);return new Blob([t],{type:"audio/wav"})}async recent(){let e=this.rt?await this.rt.call("recent",[this.id]):null;return e?new Blob([e],{type:"audio/wav"}):null}async resume(){try{await Promise.race([this.ctx.resume(),new Promise(e=>setTimeout(e,300))])}catch{}this.setStatus(this.ctx.state==="running"?"running":this.ctx.state==="interrupted"?"interrupted":"blocked")}watchContext(){let e=this.ctx,t=()=>{if(this.disposed)return;let a=e.state;a==="running"?this.setStatus("running"):a==="interrupted"?this.setStatus("interrupted"):a==="suspended"&&e.resume().then(()=>this.setStatus(e.state==="running"?"running":"blocked"),()=>this.setStatus("blocked"))};e.addEventListener("statechange",t),this.offs.push(()=>e.removeEventListener("statechange",t));let s=e.currentTime,i=performance.now(),n=0,l=setInterval(()=>{let a=performance.now(),c=(e.currentTime-s)*1e3,d=a-i;s=e.currentTime,i=a,n=e.state!=="running"||c<.9*d?n||a:0;let u=!!n&&a-n>=Ie;if(u!==this.stalled){this.stalled=u,this.diag({code:u?"audio.stalled":"audio.resumed",level:u?"warn":"info"});let w=this.track;w&&(this.sender?this.sender.replaceTrack(w):this.emit("trackchange",w))}},500);this.offs.push(()=>clearInterval(l))}bind(e){this.sender=e;let t=this.track;t&&e.track!==t&&e.replaceTrack(t)}watchTrack(e){let t=()=>void this.onTrackEnded(),s=()=>this.emit("mic",{state:"muted"}),i=()=>this.emit("mic",{state:"unmuted"});e.addEventListener("ended",t),e.addEventListener("mute",s),e.addEventListener("unmute",i),this.offs.push(()=>{e.removeEventListener("ended",t),e.removeEventListener("mute",s),e.removeEventListener("unmute",i)})}reopenMs=L;async onTrackEnded(){if(!this.disposed&&(this.emit("mic",{state:"lost"}),!!this.ownStream))try{let e=this.browserWant;await this.setStream(await x(this.opts.deviceId,void 0,e),!0),this.browserHas=e,this.reopenMs=L,this.emit("mic",{state:"reopened"})}catch(e){if(e.code==="mic.denied"){this.emit("mic",{state:"denied"});return}setTimeout(()=>void this.onTrackEnded(),this.reopenMs),this.reopenMs=Math.min(2*this.reopenMs,G)}}async setStream(e,t=!1){if(this.ownStream)for(let i of this.stream.getTracks())i!==e.getAudioTracks()[0]&&i.stop();this.source.disconnect(),this.stream=e,this.ownStream=t,this.source=this.ctx.createMediaStreamSource(e),this.source.connect(this.node,0,0);let s=e.getAudioTracks()[0];s&&this.watchTrack(s)}async setDevice(e){this.opts.deviceId=e,this.opts.followDefault=!1;let t=this.browserWant;await this.setStream(await x(e,void 0,t),!0),this.browserHas=t}followDefault(){let e=navigator.mediaDevices;if(!e?.addEventListener)return;let t=this.stream.getAudioTracks()[0]?.getSettings().groupId,s=async()=>{if(this.opts.followDefault===!1||this.disposed)return;let n=(await e.enumerateDevices().catch(()=>[])).find(l=>l.kind==="audioinput"&&l.deviceId==="default");if(n&&n.groupId&&n.groupId!==t){t=n.groupId;let l=this.browserWant;await this.setStream(await x(void 0,void 0,l),!0).then(()=>void(this.browserHas=l)).catch(()=>{}),this.emit("mic",{state:"reopened"})}};e.addEventListener("devicechange",s),this.offs.push(()=>e.removeEventListener("devicechange",s))}async restart({track:e,audioContext:t}={}){let s=this.track;if(t&&t!==this.ctx){if(this.teardownGraph(),this.ownCtx&&this.ctx.close().catch(()=>{}),this.ctx=t,this.ownCtx=!1,e){if(this.ownStream)for(let n of this.stream.getTracks())n.stop();this.stream=new MediaStream([e]),this.ownStream=!1}await this.build(),this.watchContext(),this.rt?.post({type:"dispose",input:this.id}),this.rt=null,this.startModels()}else e&&await this.setStream(new MediaStream([e]));let i=this.track;i&&i!==s&&this.emit("trackchange",i)}teardownGraph(){this.node?.port.postMessage({type:"dispose"});for(let e of[this.source,this.node,this.dest,this.farSource])e?.disconnect()}spot(e,t={}){if(this.kind==="wake")throw new TypeError("spot() reads Focus: use the wake listener itself");return t.onlyMyVoice&&!b(this.opts.voiceprint)&&!this.opts.learn&&this.diag({code:"spot.no-print",level:"warn",message:"onlyMyVoice relies on this input's print: give it a voiceprint (or learn: true), else the closest voice wakes it."}),new q(this,e.map(s=>k(s).toJSON()),t.context??"anywhere")}enrollWord(e,t={}){return new P({compile:async()=>(await import("./api-5UTMEGDH.js")).Spot.compile(e,{lang:t.lang,chain:"focus"}),open:async s=>{await this.running;let i=await y.get().models("realtime",["spot"]);return i.post({type:"set",input:this.id,enroll:{word:s,takes:t.takes??3}}),{on:this.on.bind(this),stop:()=>i.post({type:"set",input:this.id,enroll:null}),source:"focus"}},embed:async(s,i)=>(await(await import("./api-5UTMEGDH.js")).Timbre.create()).embed(s,{source:i})})}setWords(e,t){this.spotWords={words:e,context:t},this.rt&&y.get().models("realtime",["spot"]).then(s=>s.post({type:"set",input:this.id,words:e,context:t}))}dispose(){if(!this.disposed){clearTimeout(this.retryTimer),clearTimeout(this.browserTimer),this.setStatus("disposed"),this.settle(new p("engine.failed","The input was disposed before its models ran."),!0),this.counted&&--we===0&&y.get().idle();for(let e of this.offs)e();if(this.offs=[],this.rt?.post({type:"dispose",input:this.id}),this.bg?.post({type:"dispose",input:this.id}),this.teardownGraph(),this.ownStream)for(let e of this.stream.getTracks())e.stop();this.ownCtx&&this.ctx.close().catch(()=>{}),$.delete(this),this.clear()}}},z=class extends O{constructor(e){super(e);this.opts=e}kind="call";osc=null;get track(){return super.track}get delay16(){return B.lag+.1*f}models(){return["focus","cue"]}chainOptions(){let e=b(this.opts.voiceprint);return{gate:!0,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near}}realtimeOptions(){return{pipeline:"call",chain:this.chainOptions(),learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats}}async start(){if(this.opts.learn&&!this.opts.farEnd&&this.diag({code:"learn.no-far-end",level:"warn",message:"learn without farEnd: the other voice may get into the print."}),await this.open(),this.opts.keepAliveWhenHidden!==!1){this.osc=this.ctx.createOscillator(),this.osc.frequency.value=Le;let e=this.ctx.createGain();e.gain.value=Fe,this.osc.connect(e).connect(this.ctx.destination),this.osc.start(),this.offs.push(()=>this.osc?.stop())}return this}},q=class extends M{constructor(e,t,s){super();this.input=e;e.setWords(t,s),this.off=e.on("wake",i=>this.emit("wake",i))}off;dispose(){this.off(),this.input.setWords([],"anywhere"),this.clear()}};function Mt(o={}){return new z(o).start()}var X=class extends O{constructor(e){super(e);this.opts=e}kind="agent";packer=null;rawAudio(e){this.packer??=new I(this.output(),t=>{let s=this.appPort();s?s.postMessage({type:"audio",pcm:t},[t]):this.opts.output?.port||this.emit("audio",t)}),this.packer.push(e)}output(){let e=this.opts.output??{};return{format:e.format??"f32",rate:e.rate??f,chunkMs:Math.max(16,Math.round((e.chunkMs??32)/16)*16)}}get delay16(){return B.lag}models(){return["focus","cue"]}connectOutput(){if(this.opts.withTrack)return super.connectOutput();let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}realtimeOptions(){let e=b(this.opts.voiceprint);return{pipeline:"agent",chain:{gate:!1,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near},learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats,output:{...this.output(),audio:!0,utterance:!0},turn:this.opts.turn??!0,interrupt:this.opts.interrupt??!0}}async start(){if(this.opts.learn&&!this.opts.farEnd)throw new TypeError("createAgentInput: learn needs farEnd (the agent's voice would teach the print)");if(this.opts.wake)throw new TypeError("createAgentInput: wake is reserved, not in this preview (use createWakeListener)");return await this.open(),this}};function At(o={}){return new X(o).start()}var Y=class extends O{constructor(e){super(e);this.opts=e;if(this.words=e.words.map(t=>k(t).toJSON()),!this.words.length)throw new TypeError("createWakeListener: no word");for(let t of this.words)t.chain==="focus"&&this.diag({code:"word.chain",level:"warn",message:`"${t.text}" was enrolled behind Focus: its thresholds are off on the raw microphone.`});e.onlyMyVoice&&!this.reference()&&this.diag({code:"voiceprint.reset",level:"warn",message:`onlyMyVoice: ${ge}`})}kind="wake";words;models(){return["spot"]}connectOutput(){let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}wantsBackground(){return!!this.reference()}reference(){return b(this.opts.onlyMyVoice)}realtimeOptions(){return{pipeline:"wake",words:this.words,context:this.opts.context??"pause",trace:this.opts.trace,verify:!!this.reference()}}async start(){return await this.open(),this}};function Pt(o){return new Y(o).start()}var Z=class extends O{constructor(e,t,s){super(e);this.opts=e;this.word=t;this.takes=s}kind="wake";models(){return["spot"]}connectOutput(){let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}realtimeOptions(){return{pipeline:"enroll",enroll:{word:this.word,takes:this.takes}}}async start(){return await this.open(),this}};function ve(o,r,e){return new Z(o,r,e).start()}var Ae=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",Pe=0,_e=null;async function A(o,r){if(Ae()){let t=await(_e??=import("./node-VEIFZSW6.js").then(s=>new s.NodeBackend));return await t.ready(o),{call:async(s,i,n,l)=>t.calls[s](...i,l),hold:()=>()=>{}}}let e=y.get();return await e.models("background",o,r),{call:async(t,s,i=[],n)=>(await e.models("background",o)).call(t,s,i,n),hold:()=>e.hold()}}function ye(o,r={}){let e=o==="wake"?["spot"]:["focus","cue"];return r.voiceprint&&e.push("timbre"),r.typedWords&&e.push("lex"),e}async function De(o){if("pcm"in o&&"rate"in o)return g.all(o.pcm,o.rate,f);if(typeof AudioBuffer<"u"&&o instanceof AudioBuffer)return g.all(be(o),o.sampleRate,f);let r=typeof Blob<"u"&&o instanceof Blob?new Uint8Array(await o.arrayBuffer()):o instanceof Uint8Array?o:new Uint8Array(o);if(String.fromCharCode(...r.subarray(0,4))==="RIFF"){let{pcm:s,rate:i}=ue(r);return g.all(s,i,f)}if(typeof OfflineAudioContext>"u")throw new p("browser.unsupported","Outside a browser only WAV is decoded: decode the file and pass { pcm, rate }.");let t=await new OfflineAudioContext(1,1,44100).decodeAudioData(r.slice().buffer);return g.all(be(t),t.sampleRate,f)}function be(o){if(o.numberOfChannels===1)return o.getChannelData(0).slice();let r=new Float32Array(o.length);for(let e=0;e<o.numberOfChannels;e++){let t=o.getChannelData(e);for(let s=0;s<r.length;s++)r[s]+=t[s]/o.numberOfChannels}return r}var _t={configure:ne,stream:Je,supported:T,micPermission:me,onDiag:R,async preload(o,r={}){let e=ye(o,r);if(Ae()){await A(e);return}let t=y.get(),s=e.filter(a=>a!=="timbre"&&a!=="lex"),i=e.filter(a=>a==="timbre"||a==="lex"),n=[{loaded:0,total:0},{loaded:0,total:0}],l=a=>c=>{n[a]=c,r.onProgress?.({loaded:n[0].loaded+n[1].loaded,total:n[0].total+n[1].total})};await Promise.all([t.models("realtime",s,l(0)),i.length?t.models("background",i,l(1)):null])},async cached(o,r={}){let e=[E,...ye(o,r).map(t=>ee[t])];return(await Promise.all(e.map(le))).every(Boolean)},async process(o,r={}){let e=await De(o);r.signal?.throwIfAborted();let s=await(await A(Te(r))).call("process",[e,xe(r)],[],r.onProgress);return{...s,toWav(i="audio"){return pe(i==="both"?[s.raw,s.audio]:[i==="raw"?s.raw:s.audio],f)}}}};function Te(o){let r=[];return o.focus?r.push("focus","cue"):o.cue&&r.push("cue"),o.spot?.words.length&&r.push("spot"),r}function xe(o){let{onProgress:r,signal:e,...t}=o;return{...t,focus:typeof o.focus=="object"?{...o.focus,voiceprint:o.focus.voiceprint instanceof S?o.focus.voiceprint.toJSON():o.focus.voiceprint}:o.focus,spot:o.spot?{...o.spot,words:o.spot.words.map(s=>k(s).toJSON())}:void 0}}async function*Je(o,r={}){let e=await A(Te(r)),t=++Pe,s=e.hold();await e.call("streamOpen",[t,xe(r)]).catch(d=>{throw s(),d});let i=r.rate??f,n=new g(i,f,!0),l=0,a=0,c=Symbol.asyncIterator in o?o:Ue(o);try{for await(let u of c){r.signal?.throwIfAborted();let w=[];l+=u.length,n.push(u,F=>w.push(F)),a+=w.length,w.length&&(yield await e.call("streamPush",[t,Float32Array.from(w)]))}let d=[],h=Math.round(l*f/i)-a;h>0&&n.push(new Float32Array(g.HALF*2+8),u=>d.length<h&&d.push(u)),d.length&&(yield await e.call("streamPush",[t,Float32Array.from(d)]))}finally{try{yield await e.call("streamEnd",[t])}finally{s()}}}async function*Ue(o){let r=o.getReader();try{for(;;){let{done:e,value:t}=await r.read();if(e)return;yield t}}finally{r.releaseLock()}}var Q=class o{constructor(r){this.b=r}static async create(){return new o(await A(["timbre"]))}async embed(r,e={}){return S.fromJSON(await this.b.call("embed",[r,e.source??"raw"]))}verify(r,e,t={}){return D.verify(r,e,t)}async identify(r,e,t={}){let s=r instanceof S?r:await this.embed(r);return D.identify(s,e,t)}},ke=class o{constructor(r){this.b=r}static inventory=v.inventory;static langs=v.langs;static distance=v.distance;static async create(){return new o(await A(["lex"]))}async phonemize(r,e){if(!v.langs.includes(e))throw new p("lang.unsupported",`No ${e}: ${v.langs.join(", ")} only.`);let s=(await this.b.call("phonemize",[Array.isArray(r)?r:[r],e])).map(i=>i.map(({ipa:n,p:l})=>({ipa:n,p:l})));return Array.isArray(r)?s:s[0]}},He={async compile(o,r={}){for(let s of[r.lang??[]].flat())if(!v.langs.includes(s))throw new p("lang.unsupported",`No ${s}: ${v.langs.join(", ")} only.`);let e=/^\s*\/.+\/\s*$/.test(o),t=await A(e?[]:["lex"]);return k(await t.call("compile",[o,{lang:r.lang,chain:r.chain}]))},enroll(o,r={}){return new P({compile:()=>He.compile(o,r),open:async e=>{let t=await ve(r,e,r.takes??3);return{on:t.on.bind(t),stop:()=>t.dispose(),source:"raw"}},embed:async(e,t)=>(await Q.create()).embed(e,{source:t})})}},Se=o=>o?new S(o.centers,o.source,o.model,o.windows):null,je=o=>({alkove:"voiceprint",model:o.model,source:o.source,centers:o.centers,windows:o.windows}),Ge=typeof FinalizationRegistry>"u"?null:new FinalizationRegistry(o=>o()),Me=class o{constructor(r,e,t,s){this.b=r;this.id=e;this.state={progress:t.progress,ready:t.ready,voiceprint:Se(t.voiceprint)},Ge?.register(this,()=>void r.call("learnerClose",[e]).catch(()=>{}).finally(s))}state;static async create(r={}){let e=await A(["timbre"]),t=++Pe,s=e.hold();try{let i=await e.call("learnerOpen",[t,r.voiceprint?je(r.voiceprint):null]);return new o(e,t,i,s)}catch(i){throw s(),i}}get progress(){return this.state.progress}get ready(){return this.state.ready}get voiceprint(){return this.state.voiceprint}async offer(r){let e=await this.b.call("learnerOffer",[this.id,r]);return this.state={progress:e.progress,ready:e.ready,voiceprint:Se(e.voiceprint)},{accepted:e.accepted,rejected:e.rejected,progress:e.progress,ready:e.ready}}forget(){this.state={progress:0,ready:!1,voiceprint:null},this.b.call("learnerForget",[this.id])}};export{Mt as a,At as b,Pt as c,_t as d,Q as e,ke as f,He as g,Me as h};
|