alkove 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/alkove-engine.wasm +0 -0
- package/dist/alkove-worker.js +1 -1
- package/dist/api-4YJABVLZ.js +1 -0
- package/dist/api.d.ts +18 -5
- package/dist/assets-27T24F6J.js +2 -0
- package/dist/chunk-2PTYZFLZ.js +1 -0
- package/dist/chunk-C5QG5BVR.js +1 -0
- package/dist/chunk-N4S2422Z.js +1 -0
- package/dist/cli.js +5 -3
- package/dist/copy-models.d.ts +7 -0
- package/dist/core/chain.d.ts +1 -0
- package/dist/core/engine.d.ts +19 -7
- package/dist/core/lex.d.ts +1 -1
- package/dist/core/native.d.ts +22 -5
- package/dist/core/spot/spot.d.ts +40 -0
- package/dist/engine/alk.d.ts +13 -4
- package/dist/errors.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/manifest.d.ts +4 -2
- package/dist/models.generated.d.ts +155 -1
- package/dist/node-3YHT2KZ5.js +1 -0
- package/dist/process.d.ts +24 -1
- package/dist/react.js +1 -1
- package/dist/realtime/worker.d.ts +2 -0
- package/dist/recipes/input.d.ts +14 -1
- package/dist/runtime/calls.d.ts +1 -0
- package/dist/runtime/node.d.ts +1 -0
- package/package.json +1 -1
- package/dist/api-5Z64WCXH.js +0 -1
- package/dist/assets-5RV3UURM.js +0 -2
- package/dist/chunk-BWNLE4ZO.js +0 -1
- package/dist/chunk-LB4OLDBE.js +0 -1
- package/dist/chunk-SSJ7CLCP.js +0 -1
- package/dist/node-KQMEHMZQ.js +0 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { InterruptOptions, TurnOptions } from '../core/cue';
|
|
2
2
|
import type { ChainOptions } from '../core/chain';
|
|
3
3
|
import { type Context, type WordJSON } from '../core/spot/spot';
|
|
4
|
+
import { type Lang } from '../manifest';
|
|
4
5
|
import type { OutputOptions } from './packer';
|
|
5
6
|
export type { OutputOptions };
|
|
6
7
|
export interface RealtimeOptions {
|
|
@@ -28,4 +29,5 @@ export interface RealtimeOptions {
|
|
|
28
29
|
};
|
|
29
30
|
turn?: boolean | Partial<TurnOptions>;
|
|
30
31
|
interrupt?: boolean | Partial<InterruptOptions>;
|
|
32
|
+
langs?: Lang[];
|
|
31
33
|
}
|
package/dist/recipes/input.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { TurnOptions } from '../core/cue';
|
|
2
2
|
import type { Take } from '../core/spot/spot';
|
|
3
|
-
import { type Context, type WakeEvent, type Word, type WordJSON } from '../core/spot/spot';
|
|
3
|
+
import { type CommandEvent, type CommandsJSON, type Context, type LanguageEvent, type WakeEvent, type Word, type WordJSON } from '../core/spot/spot';
|
|
4
4
|
import type { Warning } from '../core/lex';
|
|
5
5
|
import { Voiceprint } from '../core/timbre';
|
|
6
6
|
import { type Diag } from '../errors';
|
|
@@ -70,6 +70,8 @@ export interface InputEvents {
|
|
|
70
70
|
};
|
|
71
71
|
trackchange: MediaStreamTrack;
|
|
72
72
|
wake: WakeEvent;
|
|
73
|
+
command: CommandEvent;
|
|
74
|
+
language: LanguageEvent;
|
|
73
75
|
heard: {
|
|
74
76
|
speech: number;
|
|
75
77
|
scores: {
|
|
@@ -105,8 +107,10 @@ export interface FocusOptions extends CommonOptions {
|
|
|
105
107
|
voiceprint?: VoiceprintInput;
|
|
106
108
|
farEnd?: MediaStreamTrack | AudioNode;
|
|
107
109
|
near?: boolean;
|
|
110
|
+
lowPower?: boolean;
|
|
108
111
|
trace?: boolean;
|
|
109
112
|
keepRecent?: number;
|
|
113
|
+
langs?: readonly Lang[];
|
|
110
114
|
}
|
|
111
115
|
export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
112
116
|
protected opts: FocusOptions;
|
|
@@ -141,6 +145,7 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
|
141
145
|
words: WordJSON[];
|
|
142
146
|
context: Context;
|
|
143
147
|
} | null;
|
|
148
|
+
protected spotCommands: CommandsJSON[] | null;
|
|
144
149
|
private running;
|
|
145
150
|
private markRunning;
|
|
146
151
|
private ran;
|
|
@@ -167,6 +172,10 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
|
167
172
|
now(): number;
|
|
168
173
|
protected abstract realtimeOptions(): RealtimeOptions;
|
|
169
174
|
protected abstract models(): ('focus' | 'cue' | 'spot')[];
|
|
175
|
+
protected spotLangs(): Lang[];
|
|
176
|
+
private spotting;
|
|
177
|
+
private spotFiles;
|
|
178
|
+
private realtimeModels;
|
|
170
179
|
protected get delay16(): number;
|
|
171
180
|
protected open(): Promise<void>;
|
|
172
181
|
private opening;
|
|
@@ -235,6 +244,7 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
|
235
244
|
lang?: Lang | Lang[];
|
|
236
245
|
}): Enrollment;
|
|
237
246
|
setWords(words: WordJSON[], context: Context): void;
|
|
247
|
+
setCommands(commands: readonly CommandsJSON[] | null): void;
|
|
238
248
|
dispose(): void;
|
|
239
249
|
}
|
|
240
250
|
export interface CallOptions extends FocusOptions {
|
|
@@ -298,6 +308,7 @@ export declare function createAgentInput(opts?: AgentOptions): Promise<AgentInpu
|
|
|
298
308
|
export interface WakeOptions extends CommonOptions {
|
|
299
309
|
words: readonly (Word | WordJSON | string)[];
|
|
300
310
|
context?: Context;
|
|
311
|
+
langs?: readonly Lang[];
|
|
301
312
|
voiceprint?: VoiceprintInput;
|
|
302
313
|
trace?: boolean;
|
|
303
314
|
}
|
|
@@ -308,6 +319,7 @@ declare class WakeListener extends AlkoveInput {
|
|
|
308
319
|
constructor(opts: WakeOptions & FocusOptions);
|
|
309
320
|
protected resolveVoice(): Promise<void>;
|
|
310
321
|
protected models(): ('focus' | 'cue' | 'spot')[];
|
|
322
|
+
protected spotLangs(): Lang[];
|
|
311
323
|
protected connectOutput(): void;
|
|
312
324
|
protected wantsBackground(): boolean;
|
|
313
325
|
protected reference(): Voiceprint | null;
|
|
@@ -323,6 +335,7 @@ declare class EnrollInput extends AlkoveInput {
|
|
|
323
335
|
protected models(): ('focus' | 'cue' | 'spot')[];
|
|
324
336
|
protected connectOutput(): void;
|
|
325
337
|
protected realtimeOptions(): RealtimeOptions;
|
|
338
|
+
protected spotLangs(): Lang[];
|
|
326
339
|
start(): Promise<this>;
|
|
327
340
|
}
|
|
328
341
|
export declare function createEnrollInput(opts: CommonOptions, word: WordJSON): Promise<EnrollInput>;
|
package/dist/runtime/calls.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ export declare function makeCalls(engine: () => Engine): {
|
|
|
26
26
|
lang?: Lang | Lang[];
|
|
27
27
|
chain?: string;
|
|
28
28
|
}) => Value;
|
|
29
|
+
compileCommands: (spec: unknown, langs: Lang[]) => Value[];
|
|
29
30
|
process: (pcm: Float32Array, opts: Omit<ProcessOptions, "onProgress" | "signal">, onProgress?: ProcessOptions["onProgress"]) => {
|
|
30
31
|
audio: Float32Array<ArrayBufferLike>;
|
|
31
32
|
raw: Float32Array<ArrayBufferLike>;
|
package/dist/runtime/node.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ export declare class NodeBackend {
|
|
|
26
26
|
lang?: import("..").Lang | import("..").Lang[];
|
|
27
27
|
chain?: string;
|
|
28
28
|
}) => import("../core/native").Value;
|
|
29
|
+
compileCommands: (spec: unknown, langs: import("..").Lang[]) => import("../core/native").Value[];
|
|
29
30
|
process: (pcm: Float32Array, opts: Omit<import("..").ProcessOptions, "onProgress" | "signal">, onProgress?: import("..").ProcessOptions["onProgress"]) => {
|
|
30
31
|
audio: Float32Array<ArrayBufferLike>;
|
|
31
32
|
raw: Float32Array<ArrayBufferLike>;
|
package/package.json
CHANGED
package/dist/api-5Z64WCXH.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-LB4OLDBE.js";import"./chunk-BWNLE4ZO.js";import"./chunk-SSJ7CLCP.js";export{a as Alkove,c as Lex,f as Spot,b as Timbre,g as VoiceprintLearner,e as compileWord,d as embedAs};
|
package/dist/assets-5RV3UURM.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var e='var b=(n,e)=>()=>(n&&(e=n(n=0)),e);var se,oe=b(()=>{"use strict";se={focus:{name:"alkove-focus-1",file:"alkove-focus-1.alk",bytes:2320032,sha256:"25028c1f9faf765ccab4076716b5e8a8e756cd7662babd2bc078951982df5ce4",revision:"69075e56ca39f9bc09bcf41c3f79288a2d753989"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1",file:"alkove-timbre-1.alk",bytes:970064,sha256:"fc94dfff533f1a4fb2abea172c1f5ff7a92cc00c6331275ea1a26e38f877b0e8",revision:"cb87ad720218e582f114d89b5a6936b9fd3f811a"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}}});var _,ae,le,V,A,O=b(()=>{"use strict";oe();_=16e3,ae=se,le={chunk:256,print:192,lag:256},V=n=>`${ae[n].name}@${ae[n].sha256.slice(0,12)}`,A={model:V("timbre"),window:24e3,min:1400,max:32e3,dim:192}});var T,ue=b(()=>{"use strict";T=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,t){let r=0;for(;r<e.length;){let i=Math.min(this.size-this.fill,e.length-r);this.buf.set(e.subarray(r,r+i),this.fill),this.fill+=i,r+=i,this.fill===this.size&&(this.fill=0,t(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}}});var C,K=b(()=>{"use strict";C={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6}});var w,ze,ce,L,pe=b(()=>{"use strict";O();ue();K();w=le.chunk,ze=["silence","forced","wake"],ce=n=>new Uint8Array(n.buffer,n.byteOffset,n.byteLength),L=class{constructor(e,t,r,i={}){this.alk=e;let o={gate:!1,normalize:!0,strength:1,sleep:!0,...i},s={...C,...i.speech},a=(h,m)=>e.x.alk_chain(t.ptr,r.ptr,+o.gate,+o.normalize,+o.sleep,o.strength,s.confidence,s.exitConfidence,s.startSecs,s.stopSecs,h,m),u=i.print?Float32Array.from(i.print):null;this.ptr=u?e.with(ce(u),h=>a(h,u.length)):a(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new T(w);mix=new Float32Array(w);focusOut=new Float32Array(w);onFocus=null;onCue=null;get speaking(){return this.alk.x.alk_chain_get(this.ptr,0)===1}get sleeping(){return this.alk.x.alk_chain_get(this.ptr,1)===1}get time(){return this.alk.x.alk_chain_get(this.ptr,2)}get gainDb(){return this.alk.x.alk_chain_get(this.ptr,3)}release(){this.ptr&&this.alk.x.alk_chain_free(this.ptr),this.ptr=0}setPrint(e){let t=this.alk.x;if(!e)t.alk_chain_print(this.ptr,0,0);else{let r=Float32Array.from(e);this.alk.with(ce(r),i=>t.alk_chain_print(this.ptr,i,r.length))<0&&this.alk.fail("print")}}setStrength(e){this.alk.x.alk_chain_strength(this.ptr,e)}setEnabled(e){this.alk.x.alk_chain_enabled(this.ptr,+e)}step(e,t){if(this.hops.pending||e.length!==w)throw new RangeError("step() takes whole hops only");return this.hop(e,t)}push(e,t){let r=new Float32Array(Math.floor((this.hops.pending+e.length)/w)*w),i=0;return this.hops.push(e,o=>{r.set(this.hop(o,t),i),i+=w}),r}hop(e,t){let{alk:r,ptr:i}=this,o=r.x;new Float32Array(r.heap,o.alk_chain_hop(i),w).set(e);let s=o.alk_chain_step(i);this.mix.set(new Float32Array(r.heap,s,w));let a=new Float64Array(r.heap,o.alk_chain_events(i),4*o.alk_chain_event_count(i)).slice();for(let u=0;u<a.length;u+=4){let[h,m,l]=[a[u+1],a[u+2],a[u+3]];switch(a[u]){case 0:t({type:"speechstart",start:h});break;case 1:t({type:"speechend",start:h,end:m});break;case 2:t({type:"idle",asleep:h===1,at:m});break;case 3:t({type:"diag",code:"focus.print",level:"info",data:{print:h===1,after:m,why:ze[l]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(r.heap,o.alk_chain_focus(i),w)),this.onFocus(this.focusOut,h));break;case 6:this.onCue?.(h,m)}}return this.mix}}});var S,X=b(()=>{"use strict";S=class extends Error{constructor(t,r,i){super(r);this.code=t;this.cause=i}name="AlkoveError"}});function He(n){let e=[],t=[],r=0,i=()=>{e.length&&(t.push(Uint8Array.from(e)),r+=e.length,e.length=0)},o=l=>{i(),t.push(l),r+=l.length},s=l=>e.push(l&255,l>>>8&255,l>>>16&255,l>>>24),a=l=>{let p=De.encode(l);s(p.length),o(p)},u=l=>{if(l==null)e.push(0);else if(typeof l=="boolean")e.push(l?2:1);else if(typeof l=="number")e.push(3),o(new Uint8Array(Float64Array.of(l).buffer));else if(typeof l=="string")e.push(4),a(l);else if(l instanceof Uint8Array)e.push(7),s(l.length),o(l.slice());else if(l instanceof Float32Array)e.push(8),s(l.length),o(new Uint8Array(l.slice().buffer));else if(Array.isArray(l)||ArrayBuffer.isView(l)){let p=Array.from(l);e.push(5),s(p.length);for(let f of p)u(f)}else{let p=Object.entries(l).filter(([,f])=>f!==void 0);e.push(6),s(p.length);for(let[f,G]of p)a(f),u(G)}};u(n),i();let h=new Uint8Array(r),m=0;for(let l of t)h.set(l,m),m+=l.length;return h}function $e(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0,r=()=>(t+=4,e.getUint32(t-4,!0)),i=()=>{let s=r();return t+=s,Je.decode(n.subarray(t-s,t))},o=()=>{switch(n[t++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return t+=8,e.getFloat64(t-8,!0);case 4:return i();case 5:return Array.from({length:r()},o);case 6:return Object.fromEntries(Array.from({length:r()},()=>[i(),o()]));case 7:{let s=r();return t+=s,n.slice(t-s,t)}case 8:{let s=r();return t+=4*s,new Float32Array(n.slice(t-4*s,t).buffer)}default:throw new Error("bad value from the core")}};return o()}function g(n,e){let t=He(e),r=n.x.alk_value_in(t.length);new Uint8Array(n.heap,r,t.length).set(t)}function d(n,e){let t=$e(new Uint8Array(n.heap,n.x.alk_value_out(),n.x.alk_value_len()).slice());if(e>=0)return t;let r=t;throw r.kind==="TypeError"?new TypeError(r.message):r.kind==="RangeError"?new RangeError(r.message):r.kind==="AlkoveError"?new S(r.code,r.message):new Error(r.message)}function he(n,e,t,r,i){return g(n,{text:t,lang:r,chain:i}),d(n,n.x.alk_compile(e?.handle??0))}function me(n,e){return g(n,e),d(n,n.x.alk_voiceprint())}var De,Je,c,y,U,I,W,z,D,J,H,$,de=b(()=>{"use strict";X();De=new TextEncoder,Je=new TextDecoder;c=n=>{if(!n)throw new Error("used after release");return n},y=(n,e,t)=>n.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=>t(r,e.length)),U=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_lex(t.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,t){return g(this.alk,{texts:e,lang:t}),d(this.alk,this.alk.x.alk_lex_phonemize(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};I=class{constructor(e,t,r){this.alk=e;g(e,r),this.ptr=e.x.alk_processor(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0,t.timbre?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:t}=this.alk,r=d(this.alk,e),i=new Float32Array(this.alk.heap,t.alk_processor_audio(c(this.ptr)),t.alk_processor_audio_len(c(this.ptr))).slice(),{start:o,...s}=r;return{start:o,audio:i,...s}}push(e){return this.part(y(this.alk,e,(t,r)=>this.alk.x.alk_processor_push(c(this.ptr),t,r)))}end(){return this.part(this.alk.x.alk_processor_end(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},W=class{constructor(e,t,r,i){this.alk=e;g(e,{words:r,context:i}),this.ptr=e.x.alk_listener(t.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,t){g(this.alk,{words:e,context:t}),d(this.alk,this.alk.x.alk_listener_words(c(this.ptr)))}push(e){return d(this.alk,y(this.alk,e,(t,r)=>this.alk.x.alk_listener_push(c(this.ptr),t,r)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},z=class{constructor(e,t,r,i,o){this.alk=e;g(e,{word:r,takes:i,chain:o}),this.ptr=e.x.alk_enroller(t.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return d(this.alk,y(this.alk,e,(t,r)=>this.alk.x.alk_enroller_push(c(this.ptr),t,r)))}result(){return d(this.alk,this.alk.x.alk_enroller_result(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},D=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_timbre(t.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return d(this.alk,y(this.alk,e,(t,r)=>this.alk.x.alk_timbre_windows(c(this.ptr),t,r)))}embed(e,t){return g(this.alk,{source:t}),d(this.alk,y(this.alk,e,(r,i)=>this.alk.x.alk_timbre_embed(c(this.ptr),r,i)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};J=class{constructor(e,t,r){this.alk=e;g(e,{source:t,start:r}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,t){return d(this.alk,y(this.alk,t,(r,i)=>this.alk.x.alk_learner_learn(c(this.ptr),e.handle,r,i)))}offer(e,t){return d(this.alk,y(this.alk,t,(r,i)=>this.alk.x.alk_learner_offer(c(this.ptr),e.handle,r,i)))}progress(){return d(this.alk,this.state()).progress}ready(){return d(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(c(this.ptr))}voiceprint(e=!1){return d(this.alk,this.alk.x.alk_learner_voiceprint(c(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(c(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},H=class{constructor(e,t,r){this.alk=e;g(e,r),this.ptr=e.x.alk_pipeline(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,t){let{alk:r}=this,i=c(this.ptr);new Float32Array(r.heap,r.x.alk_pipeline_hop(i),256).set(e);let o=r.x.alk_pipeline_step(i,t);return this.out.set(new Float32Array(r.heap,o,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(c(this.ptr),e.ptr)}timbre(e){this.alk.x.alk_pipeline_timbre(c(this.ptr),e.ptr)<0&&this.alk.fail("pipeline.timbre")}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(c(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(c(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(c(this.ptr))?d(this.alk,this.alk.x.alk_pipeline_outs(c(this.ptr))):[]}verified(e,t,r){this.alk.x.alk_pipeline_verified(c(this.ptr),e,+t,r)}set(e){g(this.alk,e),d(this.alk,this.alk.x.alk_pipeline_set(c(this.ptr)))}record(e){d(this.alk,this.alk.x.alk_pipeline_record(c(this.ptr),e))}recent(){return d(this.alk,this.alk.x.alk_pipeline_recent(c(this.ptr)))}stats(){return d(this.alk,this.alk.x.alk_pipeline_stats(c(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(c(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(c(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(c(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(c(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(c(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},$=class{constructor(e,t){this.alk=e;g(e,{reference:t}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return g(this.alk,{start:e}),d(this.alk,this.alk.x.alk_coach_learner(c(this.ptr)))}forget(){this.alk.x.alk_coach_forget(c(this.ptr))}window(e,t,r,i){return d(this.alk,y(this.alk,t,(o,s)=>this.alk.x.alk_coach_window(c(this.ptr),e.handle,o,s,r,i)))}verify(e,t){return d(this.alk,y(this.alk,t,(r,i)=>this.alk.x.alk_coach_verify(c(this.ptr),e.handle,r,i)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}}});var j,fe=b(()=>{"use strict";pe();de();j=class{constructor(e,t){this.alk=e;this.bytes=t}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let t=this.models.get(e);return t||this.models.set(e,t=this.alk.model(this.bytes(e))),t}stream(e){return this.model(e).session()}chain(e){return new L(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let t=!!e.focus,r={focus:t?this.model("focus"):void 0,cue:t||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0,timbre:t?this.model("timbre"):void 0};return new I(this.alk,r,e)}listener(e,t){return new W(this.alk,this.model("spot"),e,t)}enroller(e,t,r){return new z(this.alk,this.model("spot"),e,t,r)}lex(){return this.lexer??=new U(this.alk,this.model("lex"))}timbre(){return this.voices??=new D(this.alk,this.model("timbre"))}learner(e,t){return new J(this.alk,e,t)}pipeline(e){let t=!!e.chain,r=!!e.words?.length||!!e.enroll,i=new H(this.alk,{focus:t?this.model("focus"):void 0,cue:t?this.model("cue"):void 0,spot:r?this.model("spot"):void 0},e);return t&&i.timbre(this.model("timbre")),i}coach(e){return new $(this.alk,e)}voiceprint(e){return me(this.alk,e)}compile(e,t,r){return he(this.alk,/^\\s*\\/.+\\/\\s*$/.test(e)?null:this.lex(),e,t,r)}net(e,t){let r=`${e} ${t??""}`,i=this.calls.get(r);i||this.calls.set(r,i=this.model(e).session(t));let o=i;return{run:(s,a)=>o.call(s,a),reset:()=>o.reset()}}release(){this.lexer?.release(),this.voices?.release(),this.lexer=null,this.voices=null;for(let e of this.calls.values())e.release();for(let e of this.models.values())e.release();this.calls.clear(),this.models.clear()}}});function Ge(n){let e=ge.get(n);if(!e){let t=Object.entries({...je,...Qe[n]??{}}).map(([r,i])=>[r.normalize("NFD"),i.normalize("NFD")]);ge.set(n,e=new Map(t))}return e}function ke(n){let e=[];for(let t of n.normalize("NFD")){if(/\\p{M}/u.test(t)){t==="\\u0303"&&e.length&&(e[e.length-1]+=t);continue}e.push(t)}return e}function ye(n,e=""){let t=Ge(e),r=[];for(let i of ke(n.replace(/\\([^)]*\\)/g," ").replace(/\u200D/g,"").replace(/\\s+/g," ")))if(!Be.has(i))for(let o of ke(t.get(i)??i)){o=t.get(o)??o;let s=Y.get(o);if(!s)return null;r[r.length-1]!==s&&r.push(s)}return r}var we,Y,St,je,Qe,Be,qe,be,ge,ve=b(()=>{"use strict";we=["i","y","\\u0268","u","e","\\xF8","\\u0259","o","\\u025B","\\u0153","\\u0254","a","\\u0251","\\xE6","\\u028C","\\u026A","\\u028A","\\u0250","\\u025C","\\u025B\\u0303","\\u0251\\u0303","\\u0254\\u0303","\\u0250\\u0303","\\u1EBD","\\u0129","\\xF5","\\u0169","j","w","\\u0265","p","b","t","d","k","\\u0261","f","v","s","z","\\u0283","\\u0292","m","n","\\u0272","\\u014B","l","\\u028E","\\u0281","\\u027E","r","\\u0279","x","\\u03B8","\\xF0","\\u03B2","\\u0263","h"].map(n=>n.normalize("NFD")),Y=new Map(we.map((n,e)=>[n,e+1])),St=Y.get("\\u0259"),je={"\\u1D7B":"\\u026A",\\u025A:"\\u0259\\u0279",\\u025D:"\\u025C\\u0279",\\u029D:"j",\\u025F:"\\u0261",c:"k",\\u026B:"l",\\u026C:"l",\\u03C7:"x",\\u0266:"h",\\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"},Qe={fr:{\\u0251:"a",\\u00E3:"\\u0251\\u0303",\\u00F5:"\\u0254\\u0303",\\u1EBD:"\\u025B\\u0303",\\u0129:"\\u025B\\u0303",\\u0169:"\\u0254\\u0303",\\u0250\\u0303:"\\u0251\\u0303",\\u0250:"a",\\u00E6:"a",\\u028C:"\\u0153",\\u025C:"\\u0153",\\u026A:"i",\\u028A:"u",\\u0279:"\\u0281",r:"\\u0281",\\u027E:"\\u0281",x:"\\u0281",\\u03B8:"s",\\u00F0:"z",h:"",\\u03B2:"b",\\u0263:"\\u0261",\\u028E:"lj",\\u0268:"i"},es:{\\u026A:"i",\\u028A:"u",\\u025B:"e",\\u0254:"o",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0259:"e",\\u0250:"a",\\u0279:"\\u027E"},it:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0250:"a",\\u0279:"r",x:"k",\\u03B8:"t",h:""},pt:{\\u026A:"i",\\u028A:"u",\\u028A\\u0303:"\\u0169",y:"j",\\u00E3:"\\u0250\\u0303",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0279:"\\u027E"},ca:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"\\u0259",\\u0279:"\\u027E",\\u0250:"\\u0259"},ro:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"\\u0259",\\u0279:"r",\\u027E:"r"},en:{\\u0250:"\\u0259",r:"\\u0279",x:"k",\\u025B\\u0303:"\\u0251\\u0303"}},Be=new Set("\\u02C8\\u02CC\\u02D0\\u02D1\\u203F-.|\\u02B2\\u02B0\\u02B7\' "),qe=[["e","\\u025B"],["o","\\u0254"],["\\xF8","\\u0153","\\u0259"],["i","j"],["u","w"],["y","\\u0265"],["\\u027E","r"]],be=we.map((n,e)=>[e+1]);for(let n of qe){let e=n.map(t=>Y.get(t.normalize("NFD")));for(let t of e)for(let r of e)be[t-1].includes(r)||be[t-1].push(r)}ge=new Map});var Q,N,Z=b(()=>{"use strict";X();O();ve();Q=class n{constructor(e,t,r,i,o,s,a=[]){this.text=e;this.lang=t;this.phonemes=r;this.thresholds=i;this.calibrated=o;this.chain=s;this.warnings=a}warnings;toJSON(){return{alkove:"word",spot:V("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:e,lang:t,p:r})=>({ipa:e,lang:t,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="word")throw new TypeError("not an Alkove word");if(t.spot!==V("spot"))return null;let r=t.phonemes.map(i=>({...i,ids:ye(i.ipa,i.lang)??[]})).filter(i=>i.ids.length);return new n(t.text,t.lang,r,t.thresholds,t.calibrated,t.chain)}},N=n=>{if(n instanceof Q)return n;let e=Q.fromJSON(n);if(!e)throw new S("word.outdated",`Compiled for another Spot: compile "${typeof n=="string"?JSON.parse(n).text:n.text}" again.`);return e}});var M,B,ee,te,_e=b(()=>{"use strict";M=class extends Error{},B=class n{constructor(e){this.x=e}static async create(e){let t=await WebAssembly.instantiate(e,{});return new n(t.exports)}get heap(){return this.x.memory.buffer}with(e,t){let r=this.x.alk_alloc(e.length);new Uint8Array(this.heap,r,e.length).set(e);try{return t(r,e.length)}finally{this.x.alk_free(r,e.length)}}fail(e){let r=this.x.alk_alloc(512);try{let i=this.x.alk_error(r,512);throw new M(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,r,i))}`)}finally{this.x.alk_free(r,512)}}model(e){return new ee(this,e)}},ee=class{constructor(e,t){this.alk=e;let r=e.x;this.ptr=e.with(t,(s,a)=>r.alk_model(s,a)),this.ptr||e.fail("model");let i=r.alk_alloc(256),o=s=>new TextDecoder().decode(new Uint8Array(e.heap,i,s));try{this.plans=Array.from({length:r.alk_plans(this.ptr)},(s,a)=>{let u=m=>Array.from({length:r.alk_io_count(this.ptr,a,m)},(l,p)=>{let f=o(r.alk_io_name(this.ptr,a,m,p,i,256)),G=r.alk_io_shape(this.ptr,a,m,p,i,64),ie=Array.from(new Uint32Array(e.heap,i,G));return{name:f,dims:ie,size:ie.reduce((Ie,We)=>Ie*We,1)}}),h=u(0);return{index:a,name:o(r.alk_plan_name(this.ptr,a,i,256)),inputs:h,outputs:u(1),variable:h[r.alk_variable(this.ptr,a)]?.name??null}})}finally{r.alk_free(i,256)}}ptr;plans;session(e){let t=e===void 0?this.plans[0]:this.plans.find(r=>r.name===e);if(!t)throw new M(`no plan named ${e}`);return new te(this,t)}release(){this.alk.x.alk_model_free(this.ptr)}},te=class{constructor(e,t){this.model=e;this.plan=t;let{alk:r}=e,i=r.x;this.ptr=i.alk_session(e.ptr,t.index),this.ptr||r.fail("session");let o=new TextEncoder;for(let[s,a]of[[t.inputs,i.alk_input],[t.outputs,i.alk_output]])for(let u of s)this.at.set(u.name,{...u,p:r.with(o.encode(u.name),(h,m)=>a(this.ptr,h,m))})}ptr;at=new Map;io(e){let t=this.at.get(e);if(!t)throw new M(`no tensor named ${e}`);return t}f32(e){let t=this.io(e);return new Float32Array(this.model.alk.heap,t.p,t.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,t=this.plan.outputs.map(r=>r.name)){let{alk:r}=this.model,{variable:i}=this.plan;for(let s of this.plan.inputs){let a=e[s.name];if(!a)throw new M(`missing input ${s.name}`);if(s.name===i)r.x.alk_set_len(this.ptr,a.data.length)!==0&&r.fail(s.name);else if(a.data.length!==s.size)throw new M(`${s.name}: ${a.data.length} values for ${s.size}`);this.f32(s.name).set(a.data)}this.run();let o={};for(let s of t)o[s]={data:this.f32(s).slice(),dims:[...this.io(s).dims]};return o}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}}});function Xe(n){let e=new Uint8Array(n.length*2*(A.dim+4)),t=new DataView(e.buffer),r=0;for(let o of n)for(let s of[o.embedding,o.id]){let a=1e-9;for(let u of s)a=Math.max(a,Math.abs(u));t.setFloat32(r,a/127,!0),r+=4;for(let u of s)t.setInt8(r++,Math.round(u/a*127))}let i="";for(let o of e)i+=String.fromCharCode(o);return btoa(i)}function Ye(n){let e=atob(n),t=Uint8Array.from(e,s=>s.charCodeAt(0)),r=new DataView(t.buffer),i=[],o=0;for(;o+2*(A.dim+4)<=t.length;){let s=[];for(let a=0;a<2;a++){let u=r.getFloat32(o,!0);o+=4;let h=new Float32Array(A.dim);for(let m=0;m<h.length;m++)h[m]=r.getInt8(o++)*u;s.push(h)}i.push({embedding:s[0],id:s[1],seconds:A.window/_})}return i}var Ke,P,xe=b(()=>{"use strict";O();Ke=(n,e)=>{let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t},P=class n{constructor(e,t="focus",r=A.model,i=[]){this.centers=e;this.source=t;this.model=r;this.windows=i;if(!e.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(e){return this.closest(e).score}closest(e){let t=e instanceof n?e.centers:[e],r={score:-1,mine:0,theirs:0};for(let i of this.centers)for(let o of t){let s=Ke(i.id,o.id);s>r.score&&(r={score:s,mine:i.seconds,theirs:o.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let e=t=>Array.from(t,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(t=>({embedding:e(t.embedding),id:e(t.id),seconds:+t.seconds.toFixed(1)})),...this.windows.length?{windows:Xe(this.windows)}:{}}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(t.model!==A.model)return null;let r=t.centers.map(i=>({embedding:Float32Array.from(i.embedding),id:Float32Array.from(i.id),seconds:i.seconds}));return new n(r,t.source,t.model,t.windows?Ye(t.windows):[])}static merge(e){return new n(e.flatMap(t=>t.centers),e.every(t=>t.source==="raw")?"raw":"focus")}}});function Ae(n,e){let t=n[0]?.length??0,r=n.length,i=t*r*2,o=new Uint8Array(44+i),s=new DataView(o.buffer),a=(h,m)=>[...m].forEach((l,p)=>s.setUint8(h+p,l.charCodeAt(0)));a(0,"RIFF"),s.setUint32(4,36+i,!0),a(8,"WAVE"),a(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,r,!0),s.setUint32(24,e,!0),s.setUint32(28,e*r*2,!0),s.setUint16(32,r*2,!0),s.setUint16(34,16,!0),a(36,"data"),s.setUint32(40,i,!0);let u=44;for(let h=0;h<t;h++)for(let m=0;m<r;m++){let l=Math.max(-1,Math.min(1,n[m][h]));s.setInt16(u,l<0?l*32768:l*32767,!0),u+=2}return o}var Me=b(()=>{"use strict"});function Ze(n,e=_){let t=n.focus!==void 0&&n.focus!==!1,r=typeof n.focus=="object"?n.focus:{},i=et(r.voiceprint)?.embedding,o=n.spot?.words.map(N)??[];return{focus:t?{print:i?Array.from(i):null,strength:r.strength??1,...r.sample?{sample:Array.from(r.sample)}:{}}:null,cue:n.cue===void 0||n.cue===null?null:n.cue!==!1,speech:{...C,...typeof n.cue=="object"?n.cue:{}},normalize:n.normalize??!1,trace:!!n.trace,rate:e,spot:o.length?{words:o.map(s=>s.toJSON()),context:n.spot?.context??"anywhere"}:null}}function et(n){return!n||n instanceof Float32Array?null:n instanceof P?n:P.fromJSON(n)}function Fe(n,e,t={}){let{onProgress:r,signal:i,...o}=t,s=new R(n,o),a=[];try{for(let p=0;p<e.length;p+=re)i?.throwIfAborted(),a.push(s.push(e.subarray(p,Math.min(e.length,p+re)))),r?.({done:Math.min(e.length,p+re),total:e.length});a.push(s.end())}finally{s.release()}let u=new Float32Array(e.length),h=0;for(let p of a)u.set(p.audio.subarray(0,u.length-h),h),h+=p.audio.length;let m=e,l=a.reduce((p,f)=>({speech:[...p.speech,...f.speech],wakes:[...p.wakes,...f.wakes],diag:[...p.diag,...f.diag],trace:f.trace||p.trace?{focus:[...p.trace?.focus??[],...f.trace?.focus??[]],cue:[...p.trace?.cue??[],...f.trace?.cue??[]],spot:[...p.trace?.spot??[],...f.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:o.focus?u:e,raw:m,...l,toWav(p="audio"){return Ae(p==="both"?[m,this.audio]:[p==="raw"?m:this.audio],_)}}}var R,re,Oe=b(()=>{"use strict";K();Z();xe();Me();O();R=class{constructor(e,t={}){this.opts=t;this.core=e.processor(Ze(t))}core;closed=!1;push(e){if(this.closed)throw new Error("push after end");return this.core.push(e)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},re=16e3});function Se(n){let e=new Map,t=new Map,r=(i,o,s)=>{let a=i.get(o);if(!a)throw new Error(`${s} ${o} is closed, or its worker was started again`);return a};return{embed:(i,o)=>n().timbre().embed(i,o??"raw"),learnerOpen:(i,o)=>{let s=n().learner("raw",o);return e.set(i,s),{progress:s.progress(),ready:s.ready(),voiceprint:s.voiceprint(!0)}},learnerOffer:(i,o)=>{let s=r(e,i,"learner");return{...s.offer(n().timbre(),o),voiceprint:s.voiceprint(!0)}},learnerForget:i=>(e.get(i)?.forget(),null),learnerClose:i=>(e.get(i)?.release(),e.delete(i),null),phonemize:(i,o)=>n().lex().phonemize(i,o),compile:(i,o)=>n().compile(i,o.lang===void 0?[]:[o.lang].flat(),o.chain).word,process:(i,o,s)=>{let a=Fe(n(),i,{...o,onProgress:s});return{audio:a.audio,raw:a.raw,speech:a.speech,wakes:a.wakes,diag:a.diag,trace:a.trace}},streamOpen:(i,o)=>(t.set(i,new R(n(),o)),null),streamPush:(i,o)=>r(t,i,"stream").push(o),streamEnd:i=>{let o=r(t,i,"stream");return t.delete(i),o.end()}}}var Ee=b(()=>{"use strict";Oe()});fe();Z();_e();O();Ee();var E=256,Qt=E+2,Ne=-1;var Ve=new Map,x=null,k=(n,e=[])=>self.postMessage(n,e);async function tt(n){x=new j(await B.create(n),e=>{let t=Ve.get(e);if(!t)throw new Error(`model ${e} not sent`);return t})}var rt=100,nt=125,v=new Map;function Te(n,e){let t=n.shift;typeof e.start=="number"&&(e.start+=t),typeof e.end=="number"&&(e.end+=t),typeof e.at=="number"&&(e.at+=t);let r=e.data;e.type==="diag"&&r&&(typeof r.start=="number"&&(r.start+=t),typeof r.end=="number"&&(r.end+=t)),n.events.push(e)}var Ce=n=>n.map(e=>N(e).toJSON()),Le=n=>n?{word:N(n.word).toJSON(),takes:n.takes}:null;function it(n,e,t,r){let i=e.pipeline!=="wake"&&e.pipeline!=="enroll",o=x.pipeline({chain:i?e.chain??{}:null,verify:!!(e.verify&&t),onlyMyVoice:!!(e.onlyMyVoice&&t&&i),learn:!!(e.learn&&t),keepRecent:e.keepRecent??0,trace:!!e.trace,stats:!!e.stats,output:e.output??null,words:Ce(e.words??[]),context:e.context??"anywhere",wake:!!e.wake&&i,enroll:Le(e.enroll),turn:e.turn??!1,interrupt:e.interrupt??!1}),s={id:n,port:null,closed:!1,timer:setInterval(()=>lt(s),rt),opts:e,p:o,events:[],shift:0,timing:{n:0,sum:0,max:0,slow:0},bg:null,out:r,recordId:null};return t&&Ue(s,t),v.set(n,s),s}function Ue(n,e){n.bg=e,e.onmessage=t=>{n.closed||(t.data.type==="print"?n.p.set({print:t.data.embedding}):t.data.type==="verified"&&(n.opts.verify||n.opts.onlyMyVoice)&&(n.p.verified(t.data.key,t.data.same,t.data.score),q(n)))}}function Pe(n,e,t){n.out?n.out.postMessage(e,t):k({...e,kind:e.type,type:"pcm",input:n.id},t)}function q(n){for(let e of n.p.outs())switch(e[0]){case"event":Te(n,e[1]);break;case"window":n.bg?.postMessage({type:"window",pcm:e[1],farQuietMs:e[2],t:e[3]},[e[1].buffer]);break;case"verify":n.bg?.postMessage({type:"verify",key:e[1],pcm:e[2]},[e[2].buffer]);break;case"audio":Pe(n,{type:"audio",pcm:e[1].buffer},[e[1].buffer]);break;case"utterance":Pe(n,{type:"utterance",pcm:e[1].buffer,start:e[2]+n.shift,end:e[3]+n.shift,...e[4]&&{level:e[4]}},[e[1].buffer]);break;case"record":k({type:"reply",id:n.recordId,result:e[1]},[e[1].buffer]),n.recordId=null}}function st(n,e){let t=!x.has("spot")&&n.port;t&&n.port.postMessage({pause:!0});try{return e()}finally{t&&n.port.postMessage({pause:!1})}}function ot(n,e,t){let r=new Float32Array(e),i=r.subarray(0,E);if(r[E+1]===Ne){n.p.raw(i),q(n),t.postMessage(e,[e]);return}let o=performance.now(),s=n.p.step(i,r[E]),a=performance.now()-o;r.set(s),t.postMessage(e,[e]),q(n),at(n,a)}function at(n,e){let t=n.timing;if(t.n++,t.sum+=e,t.max=Math.max(t.max,e),e>E/_*1e3&&t.slow++,t.n<nt)return;let r=n.p.chained;Te(n,{type:"diag",code:"timing",level:t.slow>t.n/10?"warn":"info",data:{meanMs:+(t.sum/t.n).toFixed(2),maxMs:+t.max.toFixed(1),slow:t.slow,asleep:r&&n.p.sleeping,gainDb:r?+n.p.gainDb.toFixed(1):0}}),n.timing={n:0,sum:0,max:0,slow:0}}function lt(n){n.events.length&&(k({type:"events",input:n.id,list:n.events}),n.events=[])}var Re=Se(()=>x),F=new Map,ut=(n,e)=>k({type:"event",input:n,event:e});function ct(n,e,t,r){let i=F.get(n);if(!i)return;let o=performance.now(),s=i.coach.window(x.timbre(),e,t,r),a=Math.round(performance.now()-o);for(let u of s)u[0]==="print"?i.port.postMessage({type:"print",embedding:u[1]}):(u[1].type==="diag"&&(u[1].data.ms=a),ut(n,u[1]))}function pt({id:n,method:e,args:t,progress:r}){switch(e){case"process":return Re.process(t[0],t[1],r?i=>k({type:"progress",id:n,p:i}):void 0);case"embed":case"learnerOpen":case"learnerOffer":case"learnerForget":case"learnerClose":case"phonemize":case"compile":case"streamOpen":case"streamPush":case"streamEnd":return Re[e](...t);case"learner":{let i=F.get(t[0]);if(!i)throw new Error("no learning port for this input");return{progress:i.coach.learner(t[1]??null)}}case"forget":return F.get(t[0])?.coach.forget(),null;case"record":{let i=v.get(t[0]);if(!i)throw new Error("no input");i.p.record(t[1]),i.recordId=n;return}case"recent":return v.get(t[0])?.p.recent()??null;case"stats":return v.get(t[0])?.p.stats()??null;default:throw new Error(`unknown method ${e}`)}}function ne(n){let e=v.get(n);e&&(e.closed=!0,e.port?.close(),e.bg?.close(),clearInterval(e.timer),e.p.release(),v.delete(n)),F.get(n)?.port.close(),F.get(n)?.coach.release(),F.delete(n)}self.onmessage=async n=>{let e=n.data;try{switch(e.type){case"boot":await tt(e.module),k({type:"booted"});break;case"models":for(let[t,r]of Object.entries(e.models))Ve.set(t,new Uint8Array(r));k({type:"reply",id:e.id,result:!0});break;case"realtime":ne(e.input),it(e.input,e.opts,e.bg??null,e.out??null),k({type:"reply",id:e.id,result:!0});break;case"learn":{let t=v.get(e.input);if(!t)break;e.bg&&(t.bg?.close(),Ue(t,e.bg)),t.bg&&t.p.set({learn:!0});break}case"worklet":{let t=v.get(e.input),r=e.port;if(!t)break;t.port=r,r.onmessage=i=>{t.closed||(i.data instanceof ArrayBuffer?ot(t,i.data,r):typeof i.data?.clock=="number"&&(t.shift=i.data.clock/_-t.p.time))};break}case"rt-port":{ne(e.input);let t={coach:x.coach(e.ref??null),port:e.port};F.set(e.input,t),t.port.onmessage=r=>{r.data.type==="window"?ct(e.input,r.data.pcm,r.data.farQuietMs,r.data.t):r.data.type==="verify"&&t.port.postMessage({type:"verified",key:r.data.key,...t.coach.verify(x.timbre(),r.data.pcm)})};break}case"set":{let t=v.get(e.input);if(!t)break;let r={};"strength"in e&&(r.strength=e.strength),"enabled"in e&&(r.enabled=e.enabled),"print"in e&&(r.print=e.print),"words"in e&&Object.assign(r,{words:Ce(e.words),context:e.context??"anywhere"}),"enroll"in e&&(r.enroll=Le(e.enroll)),"listen"in e&&(r.listen=e.listen),"hold"in e&&(r.hold=e.hold),"words"in e||"enroll"in e&&e.enroll?st(t,()=>{t.p.spot(x.model("spot")),t.p.set(r)}):t.p.set(r),q(t);break}case"dispose":ne(e.input);break;case"call":{let t=pt(e);t!==void 0&&k({type:"reply",id:e.id,result:t});break}}}catch(t){let r=String(t?.message??t);e.id!==void 0?k({type:"reply",id:e.id,error:{message:r,code:t?.code}}):k({type:"events",input:e.input,list:[{type:"diag",code:"worker.error",level:"warn",data:{message:r,on:e.type}}]})}};\n',t=`var R=.6931471803691238,q=19082149292705877e-26,N=1.4426950408889634;var F=new DataView(new ArrayBuffer(8));function P(r){return F.setUint32(0,r+1023<<20),F.setUint32(4,0),F.getFloat64(0)}function _(r){if(r!==r)return r;if(r>709.782712893384)return 1/0;if(r<-745.1332191019411)return 0;let t=Math.round(r*N),e=r-t*R,s=t*q,i=e-s,n=i*i,o=i-n*(.16666666666666602+n*(-.0027777777777015593+n*(6613756321437934e-20+n*(-16533902205465252e-22+n*41381367970572385e-24)))),a=1-(s-i*o/(2-o)-e),h=t>>1;return a*P(h)*P(t-h)}var T=1.5707963267341256,W=6077100506506192e-26,H=.6366197723675814;function y(r){let t=r*r;return r+r*t*(-.16666666666666632+t*(.00833333333332249+t*(-.0001984126982985795+t*(27557313707070068e-22+t*(-25050760253406863e-24+t*158969099521155e-24)))))}function b(r){let t=r*r,e=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),s=.5*t,i=1-s;return i+(1-i-s+t*e)}function k(r){let t=Math.round(r*H);return[t&3,r-t*T-t*W]}function x(r){let[t,e]=k(r);return t===0?y(e):t===1?b(e):t===2?-y(e):-b(e)}function I(r){let[t,e]=k(r);return t===0?b(e):t===1?-y(e):t===2?-b(e):y(e)}var l=24,M=128,m=class r{constructor(t,e,s=!1){this.inRate=t;this.outRate=e;if(this.identity=t===e,s&&(this.t=l),this.identity)return;this.ratio=t/e;let i=this.half,n=.9/Math.max(1,this.ratio),o=new Float32Array((M+1)*l);for(let a=0;a<=M;a++){let h=a/M,u=0;for(let p=0;p<l;p++){let v=p-(i-1)-h,f=n*v,L=f===0?1:x(Math.PI*f)/(Math.PI*f),O=.42+.5*I(Math.PI*v/i)+.08*I(2*Math.PI*v/i);o[a*l+p]=L*O,u+=o[a*l+p]}for(let p=0;p<l;p++)o[a*l+p]/=u}this.table=o}static HALF=l/2;identity;ratio=1;half=l/2;table=new Float32Array(0);work=new Float32Array(0);histLen=l;t=l/2;push(t,e){if(this.identity){for(let h=0;h<t.length;h++)e(t[h]);return}if(this.work.length<l+8+t.length){let h=new Float32Array(l+8+t.length);h.set(this.work.subarray(0,this.histLen)),this.work=h}let s=this.work;s.set(t,this.histLen);let i=this.histLen+t.length,n=i-1-this.half,o=this.t;for(;o<=n;){let h=Math.floor(o),u=Math.round((o-h)*M)*l,p=h-(this.half-1),v=0;for(let f=0;f<l;f++)v+=s[p+f]*this.table[u+f];e(v),o+=this.ratio}let a=Math.floor(o)-(this.half-1);s.copyWithin(0,a,i),this.histLen=i-a,this.t=o-a}static all(t,e,s){if(e===s)return t;let i=new r(e,s,!0),n=Math.round(t.length*s/e),o=new Float32Array(n),a=0,h=u=>{a<n&&(o[a++]=u)};return i.push(t,h),i.push(new Float32Array(Math.ceil(l*i.ratio)+16),h),o}};var c=256,A=c+2,D=-1,d=16e3,z=2,Q=250,U=1e4,V=400,E=1e4,B=16e4,C=6e4,K=.005,Y=10,G=.003,w=class{buf;start=0;size=0;lost=0;constructor(t){this.buf=new Float32Array(t)}push(t){this.size===this.buf.length&&(this.lost+=this.size,this.start=this.size=0),this.buf[(this.start+this.size)%this.buf.length]=t,this.size++}pull(t,e){for(let s=0;s<e;s++)t[s]=this.buf[(this.start+s)%this.buf.length];this.skip(e)}skip(t){this.start=(this.start+t)%this.buf.length,this.size-=t}peak(t){let e=0;for(let s=0;s<t;s++)e=Math.max(e,Math.abs(this.buf[(this.start+s)%this.buf.length]));return e}},g=class{constructor(t,e,s,i,n=!1){this.rate=t;this.delay16=e;this.now=s;this.emit=i;n&&(this.tap={down:new m(t,d),in16:new w(4096),hop:new Float32Array(A)}),this.fade=1-_(-1/(Y/1e3*t)),this.floor=Math.round(c*(t/d)),this.raw=new Float32Array(Math.max(1,this.latency))}mode="raw";send=null;down;up;in16=new w(4096);out;hop=new Float32Array(A);epoch=0;raw;rawPos=0;mix=0;fade;debt=0;floor;starvedAt=0;windowStart=0;windowStarved=0;sent=0;received=0;inFlight=0;retryMs=E;retryAt=0;activatedAt=0;stopped=!1;quanta=0;stats={min:1/0,max:0,dropped:0};mins=[];windowMin=1/0;farActive=0;farQuietMs=1/0;frames=0;silence=new Float32Array(0);tap=null;onActivate=null;get latency(){let t=this.rate===d?0:m.HALF+m.HALF*(this.rate/d);return Math.round((z*c+this.delay16)*(this.rate/d)+t)}get latencyMs(){return(this.latency+this.debt)/this.rate*1e3}connect(t){this.send=t,this.activate()}pause(t){t?this.mode==="active"&&(this.mode="raw"):this.mode==="raw"&&!this.stopped&&!this.retryAt&&this.send&&this.activate()}stop(){this.stopped=!0,this.mode="raw",this.retryAt=0}activate(){this.down=new m(this.rate,d),this.up=new m(d,this.rate),this.in16=new w(4096),this.out=new w(Math.ceil(this.rate*2));let t=Math.round(z*c*(this.rate/d));for(let e=0;e<t;e++)this.out.push(0);this.epoch++,this.inFlight=0,this.debt=0,this.starvedAt=0,this.windowStart=this.now(),this.windowStarved=0,this.activatedAt=this.now(),this.stopped=!1,this.mode="active",this.onActivate?.(Math.round(this.frames*d/this.rate))}receive(t){this.received++,!(t[c+1]!==this.epoch||this.mode!=="active")&&(this.inFlight>0&&this.inFlight--,this.up.push(t.subarray(0,c),e=>this.out.push(e)))}fail(){this.now()-this.activatedAt>C&&(this.retryMs=E),this.mode="raw",this.retryAt=this.now()+this.retryMs,this.retryMs=Math.min(2*this.retryMs,B),this.emit({type:"overload",queueMs:Math.round(this.out.size/this.rate*1e3),sent:this.sent,received:this.received})}process(t,e,s){let i=s.length;this.frames+=i,this.listenFar(e,i),(!t||!t.length)&&(t=this.silence.length===i?this.silence:this.silence=new Float32Array(i));let n=this.raw,o=n.length;if(this.mode==="raw"&&this.retryAt&&this.now()>=this.retryAt&&this.send&&(this.retryAt=0,this.activate(),this.emit({type:"retry"})),this.mode==="active"){for(this.down.push(t,a=>this.in16.push(a));this.in16.size>=c;)this.in16.pull(this.hop,c),this.hop[c]=this.farQuietMs,this.hop[c+1]=this.epoch,this.send(this.hop),this.inFlight++,this.sent++;this.drain(s)}else this.tap&&this.tapRaw(t);for(let a=0;a<i;a++){let h=t[a]??0,u=n[this.rawPos];n[this.rawPos]=h,this.rawPos=(this.rawPos+1)%o,this.mix+=((this.mode==="active"?1:0)-this.mix)*this.fade,s[a]=this.mode==="active"||this.mix>1e-4?this.mix*(this.mode==="active"?s[a]:0)+(1-this.mix)*u:u}this.mode==="active"&&this.track()}tapRaw(t){let e=this.tap;for(e.down.push(t,s=>e.in16.push(s));e.in16.size>=c;)e.in16.pull(e.hop,c),this.send&&!this.stopped?(e.hop[c]=this.farQuietMs,e.hop[c+1]=D,this.send(e.hop)):this.emit({type:"raw",pcm:e.hop.slice(0,c)})}drain(t){let e=t.length,s=this.out;if(s.lost&&(this.debt=Math.max(0,this.debt-s.lost),s.lost=0),s.size>=e){this.debt>=e&&s.size>=2*e&&this.lowWater()-e>=this.floor&&s.peak(e)<K&&(s.skip(e),this.debt-=e,this.stats.dropped+=e),s.pull(t,e),this.starvedAt&&(this.windowStarved+=this.now()-this.starvedAt,this.starvedAt=0);return}if(t.fill(0),!this.sent)return;this.debt+=e;let i=this.now();this.starvedAt||(this.starvedAt=i),i-this.windowStart>U&&(this.windowStart=i,this.windowStarved=0),(i-this.starvedAt>=Q||this.windowStarved+(i-this.starvedAt)>=V)&&this.fail()}lowWater(){return Math.min(this.windowMin,...this.mins)}track(){let t=this.out.size;this.windowMin=Math.min(this.windowMin,t),this.stats.min=Math.min(this.stats.min,t),this.stats.max=Math.max(this.stats.max,t);let e=Math.round(this.rate/128);if(++this.quanta%e===0&&(this.mins.push(this.windowMin),this.mins.length>2&&this.mins.shift(),this.windowMin=1/0),this.quanta%(2*e)===0){let s=i=>Math.round(i/this.rate*1e3);this.emit({type:"timing",queueMs:[s(this.stats.min),s(this.stats.max)],debtMs:s(this.debt),droppedMs:s(this.stats.dropped),latencyMs:Math.round(this.latencyMs)}),this.stats={min:1/0,max:0,dropped:0}}}listenFar(t,e){let s=e/this.rate*1e3,i=this.farActive>0;if(t&&t.length){let n=0;for(let o=0;o<t.length;o++)n+=t[o]*t[o];i||=Math.sqrt(n/t.length)>G}this.farQuietMs=i?0:this.farQuietMs+s}setFarActive(t){this.farActive=t?1:0,t&&(this.farQuietMs=0)}};var S=class extends AudioWorkletProcessor{core;worker=null;pool=[];dead=!1;constructor(t){super(),this.core=new g(sampleRate,t.processorOptions.delay16,()=>Date.now(),e=>this.port.postMessage(e),!!t.processorOptions.tapRaw),this.port.postMessage({type:"latency",ms:this.core.latencyMs}),this.port.onmessage=e=>{let s=e.data;s.type==="connect"?(this.worker=s.port,this.worker.onmessage=i=>{if(!(i.data instanceof ArrayBuffer))return this.core.pause(!!i.data?.pause);let n=i.data;this.core.receive(new Float32Array(n)),this.pool.push(n)},this.core.onActivate=i=>this.worker.postMessage({clock:i}),this.core.connect(i=>{let n=this.pool.pop()??new ArrayBuffer(A*4);new Float32Array(n).set(i),this.worker.postMessage(n,[n])}),this.port.postMessage({type:"latency",ms:this.core.latencyMs})):s.type==="stop"?this.core.stop():s.type==="far"?this.core.setFarActive(!!s.on):s.type==="dispose"&&(this.dead=!0)}}process(t,e){if(this.dead)return!1;let s=e[0]?.[0];if(!s)return!0;this.core.process(t[0]?.[0]??null,t[1]?.[0]??null,s);for(let i=1;i<(e[0]?.length??0);i++)e[0][i].set(s);return!0}};registerProcessor("alkove",S);
|
|
2
|
-
`;export{e as WORKER,t as WORKLET};
|
package/dist/chunk-BWNLE4ZO.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{B as m,C as x,a as N,b as M,d as C,i as p,j as q,k as y,l as $,m as I,n as z,q as S,r as Y,s as X,t as T,u as L,w as Z,x as Q}from"./chunk-SSJ7CLCP.js";var g=class{handlers=new Map;on(s,t){let e=this.handlers.get(s);return e||this.handlers.set(s,e=new Set),e.add(t),()=>void e.delete(t)}emit(s,t){for(let e of this.handlers.get(s)??[])try{e(t)}catch(r){queueMicrotask(()=>{throw r})}}listens(s){return!!this.handlers.get(s)?.size}clear(){this.handlers.clear()}};var A=class extends g{done;target=null;cancelled=!1;abort=null;constructor(s){super(),this.done=this.run(s),this.done.catch(()=>{})}async run(s){let t=await s.compile();for(let i of t.warnings)this.emit("warning",i);if(this.cancelled)throw new DOMException("cancelled","AbortError");let e=this.target=await s.open(t.toJSON()),r=[e.on("take",i=>this.emit("take",i))];try{let i=await new Promise((c,l)=>{r.push(e.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 o=i.audio&&i.audio.length>=4e3?await s.embed(i.audio,e.source):null,a=y(i.word);return{word:new q(a.text,a.lang,a.phonemes,a.thresholds,a.calibrated,a.chain,[...t.warnings,...i.warnings??[]]),voiceprint:o}}finally{for(let i of r)i();e.stop()}}cancel(){this.cancelled=!0,this.abort?.(),this.target?.stop()}};var u=24,O=128,E=class n{constructor(s,t,e=!1){this.inRate=s;this.outRate=t;if(this.identity=s===t,e&&(this.t=u),this.identity)return;this.ratio=s/t;let r=this.half,i=.9/Math.max(1,this.ratio),o=new Float32Array((O+1)*u);for(let a=0;a<=O;a++){let d=a/O,c=0;for(let l=0;l<u;l++){let f=l-(r-1)-d,h=i*f,w=h===0?1:$(Math.PI*h)/(Math.PI*h),st=.42+.5*I(Math.PI*f/r)+.08*I(2*Math.PI*f/r);o[a*u+l]=w*st,c+=o[a*u+l]}for(let l=0;l<u;l++)o[a*u+l]/=c}this.table=o}static HALF=u/2;identity;ratio=1;half=u/2;table=new Float32Array(0);work=new Float32Array(0);histLen=u;t=u/2;push(s,t){if(this.identity){for(let d=0;d<s.length;d++)t(s[d]);return}if(this.work.length<u+8+s.length){let d=new Float32Array(u+8+s.length);d.set(this.work.subarray(0,this.histLen)),this.work=d}let e=this.work;e.set(s,this.histLen);let r=this.histLen+s.length,i=r-1-this.half,o=this.t;for(;o<=i;){let d=Math.floor(o),c=Math.round((o-d)*O)*u,l=d-(this.half-1),f=0;for(let h=0;h<u;h++)f+=e[l+h]*this.table[c+h];t(f),o+=this.ratio}let a=Math.floor(o)-(this.half-1);e.copyWithin(0,a,r),this.histLen=r-a,this.t=o-a}static all(s,t,e){if(t===e)return s;let r=new n(t,e,!0),i=Math.round(s.length*e/t),o=new Float32Array(i),a=0,d=c=>{a<i&&(o[a++]=c)};return r.push(s,d),r.push(new Float32Array(Math.ceil(u*r.ratio)+16),d),o}};var V=class{constructor(s){this.worker=s;s.onmessage=t=>{let e=t.data;if(e?.type==="reply"){let r=this.replies.get(e.id);this.replies.delete(e.id),e.error?r?.reject(Object.assign(new Error(e.error.message),{code:e.error.code})):r?.resolve(e.result)}else if(e?.type==="progress")this.replies.get(e.id)?.progress?.(e.p);else for(let r of this.listeners)r(e)},s.onerror=t=>{for(let e of this.replies.values())e.reject(new p("engine.failed",t.message||"worker failed"));this.replies.clear();for(let e of this.listeners)e({type:"crash",message:t.message})}}next=1;replies=new Map;listeners=new Set;listen(s){return this.listeners.add(s),()=>void this.listeners.delete(s)}get busy(){return this.replies.size>0}request(s,t=[],e){let r=this.next++;return new Promise((i,o)=>{this.replies.set(r,{resolve:i,reject:o,progress:e}),this.worker.postMessage({...s,id:r,progress:!!e},t)})}call(s,t,e=[],r){return this.request({type:"call",method:s,args:t},e,r)}post(s,t=[]){this.worker.postMessage(s,t)}},it=null,ot=()=>it??=import("./assets-5RV3UURM.js");async function _(n){let s=S().assetBaseUrl;if(s)return L(s,`alkove-${n}.js`);let t=await ot();return URL.createObjectURL(new Blob([n==="worker"?t.WORKER:t.WORKLET],{type:"text/javascript"}))}var tt=null;function nt(n){return tt??=(async()=>{let s=S().models?.engine,t=S().assetBaseUrl,e=s??(t?L(t,N.file):new URL("./alkove-engine.wasm",import.meta.url).href),r=await Z(N,n,e);return WebAssembly.compile(r)})().catch(s=>{throw tt=null,s})}var v=class n{static current=null;sent={realtime:new Set,background:new Set};links={};holds=0;static get(){return Y(),n.current??=new n}link(s){return this.links[s]??=(async()=>{let[t,e]=await Promise.all([nt(),_("worker")]),r=new V(new Worker(e,{type:"module",name:`alkove-${s}`})),i=this.links[s];return r.listen(o=>o.type==="crash"&&this.links[s]===i&&this.drop(s,r)),await new Promise((o,a)=>{let d=r.listen(c=>{c.type==="booted"?(d(),o()):c.type==="crash"&&a(new p("engine.failed",c.message))});r.post({type:"boot",module:t})}),r})().catch(t=>{throw delete this.links[s],t})}drop(s,t){delete this.links[s],this.sent[s].clear(),t.worker.terminate()}hold(){this.holds++;let s=!0;return()=>{s&&this.holds--,s=!1}}async idle(){for(let s of["realtime","background"]){let t=this.links[s],e=t&&await t.catch(()=>null);e&&this.links[s]===t&&(s==="realtime"||!e.busy&&!this.holds)&&this.drop(s,e)}}async models(s,t,e){let r=await this.link(s),i=t.filter(c=>!this.sent[s].has(c));if(!i.length)return r;let o=new Map,a=await Promise.all(i.map(c=>Q(c,l=>{o.set(c,l);let f=0,h=0;for(let w of o.values())f+=w.loaded,h+=w.total;e?.({loaded:f,total:h})}))),d=Object.fromEntries(i.map((c,l)=>[c,a[l].slice().buffer]));await r.request({type:"models",models:d},Object.values(d));for(let c of i)this.sent[s].add(c);return r}static report=T};var at=5e3,dt=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 P(){let n=globalThis,s=!1;try{s=typeof WebAssembly<"u"&&WebAssembly.validate(dt)}catch{}return{worklet:typeof n.AudioWorkletNode=="function",simd:s,secure:n.isSecureContext!==!1}}async function Pt(){try{let n=await navigator.permissions.query({name:"microphone"});return n.state==="granted"||n.state==="denied"?n.state:"prompt"}catch{return"prompt"}}var F={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,voiceIsolation:!1,channelCount:1};async function b(n,s,t=!1){if(!P().secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!navigator.mediaDevices?.getUserMedia)throw new p("browser.unsupported","No getUserMedia in this browser.");let e=setTimeout(()=>T({code:"mic.waiting",level:"info",message:"The permission prompt has had no answer for 5 s."}),at);try{let r=t?{noiseSuppression:!0,autoGainControl:!0}:{},i=navigator.mediaDevices.getUserMedia({audio:{...F,...r,...n?{deviceId:{exact:n}}:{}}});return await(s?Promise.race([i,new Promise((a,d)=>{s.aborted&&d(s.reason),s.addEventListener("abort",()=>{i.then(c=>c.getTracks().forEach(l=>l.stop()),()=>{}),d(s.reason)})})]):i)}catch(r){if(s?.aborted)throw s.reason;let i=r?.name;throw i==="NotAllowedError"||i==="SecurityError"?new p("mic.denied","Microphone permission denied.",r):i==="NotFoundError"||i==="OverconstrainedError"?new p("mic.not-found","No microphone.",r):i==="NotReadableError"||i==="AbortError"?new p("mic.busy","The microphone is used by another app.",r):r}finally{clearTimeout(e)}}function et(n){let s=n.getSettings();return["noiseSuppression","autoGainControl","voiceIsolation"].filter(t=>s[t]===!0)}var W=class{constructor(s,t){this.opts=s;this.send=t;this.resampler=new E(M,s.rate),this.buf=new Float32Array(Math.round(s.rate*s.chunkMs/1e3))}resampler;buf;fill=0;push(s){this.resampler.push(s,t=>{this.buf[this.fill++]=t,this.fill===this.buf.length&&(this.send(ct(this.buf,this.opts.format)),this.fill=0)})}};function ct(n,s){if(s==="f32")return n.slice().buffer;let t=new Int16Array(n.length);for(let e=0;e<n.length;e++){let r=Math.max(-1,Math.min(1,n[e]));t[e]=r<0?r*32768:r*32767}return t.buffer}var R=5e3,B=6e4,lt=1500,pt=30,ht=.002,ut=2e3,mt=0,D=new WeakMap,J=new Set,rt=0,ft="This print comes from another Timbre: ignored, learn it again.",k=class extends g{constructor(t){super();this.opts=t;this.running=new Promise(e=>this.markRunning=e)}id=++mt;ctx;ownCtx=!1;stream;ownStream=!1;source;node;dest=null;farSource=null;rt=null;bg=null;offs=[];_mode={mode:"raw",reason:"loading"};_status="starting";_latency=0;_voiceprint=null;sample=null;retryMs=R;retryTimer;started=0;counted=!1;enabled=!0;printed=!1;learning=!1;farCalled=!1;sender=null;stalled=!1;spotWords=null;running;markRunning;ran=!1;notReady=null;waiting=[];warned=new Set;browserWant=!1;browserHas=!1;browserBusy=Promise.resolve();browserTimer;listening=!0;holding=!1;get disposed(){return this._status==="disposed"}get mode(){return this._mode.mode}get status(){return this._status}get latency(){return this._latency}get voiceprint(){return this._voiceprint}get ready(){return this.ran?Promise.resolve():this.notReady?Promise.reject(this.notReady):new Promise((t,e)=>this.waiting.push([t,e]))}settle(t,e=!1){if(this.ran)return;this.ran=!t,e&&(this.notReady=t);let r=this.waiting;this.waiting=[];for(let[i,o]of r)t?o(t):i()}get track(){return this.currentTrack()}currentTrack(){return this.stalled?this.stream.getAudioTracks()[0]??null:this.dest?.stream.getAudioTracks()[0]??null}now(){return this.ctx?this.ctx.currentTime-this.started:0}get delay16(){return 0}async open(){rt++,this.counted=!0;try{await this.opening()}catch(t){throw this.dispose(),t}}async opening(){this.offs.push(X(i=>this.diag(i))),this.opts.voiceprint&&!(this.opts.voiceprint instanceof Float32Array)&&!m(this.opts.voiceprint)&&this.diag({code:"voiceprint.reset",level:"warn",message:ft});let t=P();if(!t.secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!t.worklet)throw new p("browser.unsupported","No AudioWorklet in this browser (Safari 14.1 or later).");let e=this.opts;e.stream||e.track?this.stream=e.stream??new MediaStream([e.track]):(this.stream=await b(e.deviceId,e.signal),this.ownStream=!0);let r=this.stream.getAudioTracks()[0];if(!r)throw new p("mic.not-found","The stream has no audio track.");if(!this.ownStream){let i=et(r);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 J)i.stream.getAudioTracks()[0]?.getSettings().deviceId===r.getSettings().deviceId&&i!==this&&this.diag({code:"mic.twice",level:"warn",message:"Two inputs on the same microphone run everything twice: use call.spot() for words on a call input."});e.audioContext?this.ctx=e.audioContext:(this.ctx=new AudioContext,this.ownCtx=!0),await this.build(),J.add(this),this.watchContext(),this.watchTrack(r),this.ownStream&&!e.deviceId&&this.followDefault(),this.startModels(),this.flushHeld()}async build(){let t=this.ctx,e=D.get(t);e||(e=_("worklet").then(i=>t.audioWorklet.addModule(i)),e.catch(()=>D.delete(t)),D.set(t,e)),await e,this.node=new AudioWorkletNode(t,"alkove",{numberOfInputs:2,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{delay16:this.delay16,tapRaw:this.kind==="agent"}}),this.node.port.onmessage=i=>this.onWorklet(i.data),this.source=t.createMediaStreamSource(this.stream),this.source.connect(this.node,0,0);let r=this.opts.farEnd;r&&(this.farSource=r instanceof MediaStreamTrack?t.createMediaStreamSource(new MediaStream([r])):r,this.farSource.connect(this.node,0,1)),this.connectOutput(),this.started=t.currentTime,await this.resume()}connectOutput(){this.dest=this.ctx.createMediaStreamDestination(),this.node.connect(this.dest)}onWorklet(t){t.type==="overload"?(this.diag({code:"overload",level:"warn",message:"The device is too slow for the models: raw microphone for a while.",queueMs:t.queueMs,sent:t.sent,received:t.received}),this.setMode("raw","overload")):t.type==="retry"?this.setMode(this.activeMode()):t.type==="latency"?this._latency=Math.round(t.ms):t.type==="raw"?this.rawAudio(t.pcm):t.type==="timing"&&(this._latency=t.latencyMs,this.diag({code:"queue",level:"info",...t}))}rawAudio(t){}activeMode(){return this.enabled?this.kind==="wake"?this.reference()?"spot+print":"spot":this.printed?"focus+print":"focus":"raw"}held=[];emit(t,e){this.held?this.held.push([t,e]):this.deliver(t,e)}flushHeld(){setTimeout(()=>{let t=this.held??[];this.held=null;for(let[e,r]of t)this.deliver(e,r)},0)}deliver(t,e){if(super.emit(t,e),t!=="diag")return;let r=e;r.level!=="warn"||this.listens("diag")||this.warned.has(r.code)||(this.warned.add(r.code),console.warn(`alkove: ${r.message??r.code}`,r))}setMode(t,e){this._mode.mode===t&&this._mode.reason===e||(this._mode=e?{mode:t,reason:e}:{mode:t},this.emit("mode",this._mode),this.followRaw())}followRaw(){if(clearTimeout(this.browserTimer),!this.ownStream||this.disposed)return;this._mode.mode==="raw"&&this._mode.reason!=="off"?this.browserWant||(this.browserTimer=setTimeout(()=>this.wantBrowser(!0),ut)):this.wantBrowser(!1)}wantBrowser(t){this.browserWant=t,this.browserBusy=this.browserBusy.then(()=>this.browser())}async browser(){let t=this.browserWant,e=this.stream.getAudioTracks()[0];if(this.disposed||!this.ownStream||t===this.browserHas||!e)return;try{await e.applyConstraints({...F,noiseSuppression:t,autoGainControl:t})}catch{}let r=e.getSettings().noiseSuppression;if(typeof r=="boolean"&&r!==t){if(this.disposed||!this.ownStream)return;let o=e.getSettings().deviceId??this.opts.deviceId;e.stop();try{let a=await b(o,void 0,t);if(this.disposed||!this.ownStream){for(let d of a.getTracks())d.stop();return}await this.setStream(a,!0)}catch{this.onTrackEnded();return}}this.browserHas=t;let i=this.stream.getAudioTracks()[0]?.getSettings().noiseSuppression;this.diag({code:"mic.browser",level:"info",noiseSuppression:t,autoGainControl:t,applied:typeof i=="boolean"?i:null})}setStatus(t){this._status!==t&&(this._status=t,this.emit("status",t))}diag(t){this.emit("diag",t)}async startModels(){if(!this.disposed){if(!P().simd){this.diag({code:"engine.unsupported",level:"warn",message:"No WebAssembly SIMD: raw microphone for this session."}),this.setMode("raw","unsupported"),this.settle(new p("browser.unsupported","No WebAssembly SIMD: the models cannot run in this browser."),!0);return}this.setMode("raw","loading"),this.followRaw();try{await this.resolveVoice(),this.learning=this.learns();let t=v.get(),e=await t.models("realtime",[...this.models(),...this.models().includes("focus")?["timbre"]:[],...this.spotWords?.words.length?["spot"]:[]]),r;if(this.wantsBackground()){let d=await t.models("background",["timbre"]);r=this.toBackground(d,this.reference()),this.learning&&await d.call("learner",[this.id,m(this.opts.voiceprint)?.toJSON()??null])}if(this.disposed)return;this.rt=e,this.offs.push(e.listen(d=>this.onRealtime(d)));let i=this.appPort(),o=[...r?[r]:[],...i?[i]:[]];i&&(this.portGiven=!0),await e.request({type:"realtime",input:this.id,opts:this.realtimeOptions(),bg:r,out:i},o),(!this.listening||this.holding)&&e.post({type:"set",input:this.id,...!this.listening&&{listen:!1},...this.holding&&{hold:!0}}),this.spotWords?.words.length&&(await t.models("realtime",["spot"]),e.post({type:"set",input:this.id,...this.spotWords})),this.markRunning(),this.settle(null);let a=new MessageChannel;e.post({type:"worklet",input:this.id,port:a.port2},[a.port2]),this.node.port.postMessage({type:"connect",port:a.port1},[a.port1]),this.printed=!!m(this.opts.voiceprint),this.retryMs=R,this.setMode(this.activeMode(),this.enabled?void 0:"off"),!this.learning&&this.learns()&&this.startLearning()}catch(t){if(this.disposed)return;this.diag({code:"models.failed",level:"warn",message:`Models not loaded, raw microphone; retry in ${this.retryMs/1e3} s.`,error:String(t?.message??t)}),this.setMode("raw","failed"),this.settle(t instanceof p?t:new p("engine.failed",`Models not loaded: ${String(t?.message??t)}`,t)),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,B)}}}portGiven=!1;appPort(){return this.portGiven?void 0:this.opts.output?.port}wantsBackground(){return this.learning}learns(){return this.kind==="call"||this.kind==="agent"&&(!!this.opts.farEnd||this.farCalled)}toBackground(t,e){let r=new MessageChannel;return t.post({type:"rt-port",input:this.id,port:r.port2,ref:e?.toJSON()??null},[r.port2]),this.bg!==t&&this.offs.push(t.listen(i=>i.input===this.id&&i.type==="event"&&this.onEvent(i.event))),this.bg=t,r.port1}async startLearning(){let t=this.rt;if(!(this.learning||!t||this.disposed)){this.learning=!0;try{let e=this.bg?void 0:this.toBackground(await v.get().models("background",["timbre"]),null);if(this.disposed||this.rt!==t)return;t.post({type:"learn",input:this.id,...e&&{bg:e}},e?[e]:[]),await this.bg.call("learner",[this.id,m(this.opts.voiceprint)?.toJSON()??null])}catch(e){this.disposed||this.diag({code:"models.failed",level:"warn",message:"Timbre not loaded: the print does not learn.",error:String(e?.message??e)})}}}reference(){return null}onRealtime(t){if(t.input===this.id)if(t.type==="events"){let e=[];for(let r of t.list)r.type==="trace"?e.push(r):this.onEvent(r);e.length&&this.emit("trace",e)}else t.type==="pcm"?t.kind==="audio"?this.emit("audio",t.pcm):this.emit("utterance",{pcm:t.pcm,start:t.start,end:t.end,...t.level&&{level:t.level}}):t.type==="crash"&&(this.node.port.postMessage({type:"stop"}),this.rt=null,this.diag({code:"engine.crash",level:"warn",message:`The engine stopped: raw microphone; retry in ${this.retryMs/1e3} s.`,error:t.message}),this.setMode("raw","failed"),clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,B))}onEvent(t){switch(t.type){case"speechstart":this.emit("speechstart",{start:t.start});break;case"speechcancel":this.emit("speechcancel",{start:t.start});break;case"speechend":this.emit("speechend",{start:t.start,end:t.end,..."voiceDb"in t&&{level:{voiceDb:t.voiceDb,noiseDb:t.noiseDb,refDb:t.refDb}}});break;case"turn":this.emit("turn",{pause:t.pause,probability:t.probability,hesitation:t.hesitation,at:t.at});break;case"turnend":this.emit("turnend",{start:t.start,end:t.end,probability:t.probability,hesitation:t.hesitation,at:t.at});break;case"interruptstart":this.emit("interruptstart",{start:t.start});break;case"interrupt":this.emit("interrupt",{start:t.start,at:t.at});break;case"interruptcancel":this.emit("interruptcancel",{start:t.start,end:t.end});break;case"wake":this.emit("wake",t);break;case"take":{let{type:e,...r}=t;this.emit("take",r);break}case"enrolled":{let{type:e,...r}=t;this.emit("enrolled",r);break}case"heard":this.emit("heard",{speech:t.speech,scores:t.scores});break;case"learn":this.emit("learn",{progress:t.progress});break;case"voiceprint":{let e=z.fromJSON(t.json);e&&(this._voiceprint=e,this.emit("voiceprint",e));break}case"idle":this.diag({code:"idle",level:"info",asleep:t.asleep,at:t.at});break;case"diag":t.code==="focus.print"&&(this.printed=!!t.data?.print,this._mode.mode!=="raw"&&this.setMode(this.activeMode())),this.diag({code:t.code,level:t.level,...t.data});break}}async setEnabled(t){return this.enabled=t,this.rt?.post({type:"set",input:this.id,enabled:t}),t?this.rt&&this._mode.reason==="off"&&this.setMode(this.activeMode()):this.setMode("raw","off"),t&&!!this.rt}listen(t){this.listening=t,this.rt?.post({type:"set",input:this.id,listen:t})}hold(){this.holding=!0,this.rt?.post({type:"set",input:this.id,hold:!0})}release(){this.holding=!1,this.rt?.post({type:"set",input:this.id,hold:!1})}setVoiceprint(t){if(t instanceof Float32Array){x(t).then(e=>this.applyPrint(e.print??null,e.sample),e=>this.diag({code:"voiceprint.reset",level:"warn",message:`A recording as the voiceprint: ${e.message}`}));return}this.applyPrint(t)}async resolveVoice(){if(!(this.opts.voiceprint instanceof Float32Array))return;let t=await x(this.opts.voiceprint);this.opts.voiceprint=t.print??null,this.sample=t.sample??null}applyPrint(t,e){let r=m(t);t&&!r&&this.diag({code:"voiceprint.reset",level:"warn",message:"This print comes from another Timbre: ignored, learn it again."}),this.opts.voiceprint=r,this.sample=e??null,this.rt?.post({type:"set",input:this.id,print:r?.embedding??null,...e&&{sample:e}}),this.learning&&this.bg?.call("learner",[this.id,r?.toJSON()??null])}forgetVoiceprint(){this._voiceprint=null,this.rt?.post({type:"set",input:this.id,print:null}),this.bg?.call("forget",[this.id])}farEndActive(t){this.node?.port.postMessage({type:"far",on:t}),!this.farCalled&&(this.farCalled=!0,this.learns()&&this.startLearning())}async stats(){return this.rt?this.rt.call("stats",[this.id]):null}async record(t){if(!this.rt)throw new p("engine.failed","The models are not running yet.");let e=await this.rt.call("record",[this.id,t]);return new Blob([e],{type:"audio/wav"})}async recent(){let t=this.rt?await this.rt.call("recent",[this.id]):null;return t?new Blob([t],{type:"audio/wav"}):null}async resume(){try{await Promise.race([this.ctx.resume(),new Promise(t=>setTimeout(t,300))])}catch{}this.setStatus(this.ctx.state==="running"?"running":this.ctx.state==="interrupted"?"interrupted":"blocked")}watchContext(){let t=this.ctx,e=()=>{if(this.disposed)return;let d=t.state;d==="running"?this.setStatus("running"):d==="interrupted"?this.setStatus("interrupted"):d==="suspended"&&t.resume().then(()=>this.setStatus(t.state==="running"?"running":"blocked"),()=>this.setStatus("blocked"))};t.addEventListener("statechange",e),this.offs.push(()=>t.removeEventListener("statechange",e));let r=t.currentTime,i=performance.now(),o=0,a=setInterval(()=>{let d=performance.now(),c=(t.currentTime-r)*1e3,l=d-i;r=t.currentTime,i=d,o=t.state!=="running"||c<.9*l?o||d:0;let h=!!o&&d-o>=lt;if(h!==this.stalled){this.stalled=h,this.diag({code:h?"audio.stalled":"audio.resumed",level:h?"warn":"info"});let w=this.currentTrack();w&&(this.sender?this.sender.replaceTrack(w):this.emit("trackchange",w))}},500);this.offs.push(()=>clearInterval(a))}bind(t){this.sender=t;let e=this.track;e&&t.track!==e&&t.replaceTrack(e)}watchTrack(t){let e=()=>void this.onTrackEnded(),r=()=>this.emit("mic",{state:"muted"}),i=()=>this.emit("mic",{state:"unmuted"});t.addEventListener("ended",e),t.addEventListener("mute",r),t.addEventListener("unmute",i),this.offs.push(()=>{t.removeEventListener("ended",e),t.removeEventListener("mute",r),t.removeEventListener("unmute",i)})}reopenMs=R;async onTrackEnded(){if(!this.disposed&&(this.emit("mic",{state:"lost"}),!!this.ownStream))try{let t=this.browserWant;await this.setStream(await b(this.opts.deviceId,void 0,t),!0),this.browserHas=t,this.reopenMs=R,this.emit("mic",{state:"reopened"})}catch(t){if(t.code==="mic.denied"){this.emit("mic",{state:"denied"});return}setTimeout(()=>void this.onTrackEnded(),this.reopenMs),this.reopenMs=Math.min(2*this.reopenMs,B)}}async setStream(t,e=!1){if(this.ownStream)for(let i of this.stream.getTracks())i!==t.getAudioTracks()[0]&&i.stop();this.source.disconnect(),this.stream=t,this.ownStream=e,this.source=this.ctx.createMediaStreamSource(t),this.source.connect(this.node,0,0);let r=t.getAudioTracks()[0];r&&this.watchTrack(r)}async setDevice(t){this.opts.deviceId=t;let e=this.browserWant;await this.setStream(await b(t,void 0,e),!0),this.browserHas=e}followDefault(){let t=navigator.mediaDevices;if(!t?.addEventListener)return;let e=this.stream.getAudioTracks()[0]?.getSettings().groupId,r=async()=>{if(this.opts.deviceId||this.disposed)return;let o=(await t.enumerateDevices().catch(()=>[])).find(a=>a.kind==="audioinput"&&a.deviceId==="default");if(o&&o.groupId&&o.groupId!==e){e=o.groupId;let a=this.browserWant;await this.setStream(await b(void 0,void 0,a),!0).then(()=>void(this.browserHas=a)).catch(()=>{}),this.emit("mic",{state:"reopened"})}};t.addEventListener("devicechange",r),this.offs.push(()=>t.removeEventListener("devicechange",r))}async restart({track:t,audioContext:e}={}){let r=this.currentTrack();if(e&&e!==this.ctx){if(this.teardownGraph(),this.ownCtx&&this.ctx.close().catch(()=>{}),this.ctx=e,this.ownCtx=!1,t){if(this.ownStream)for(let o of this.stream.getTracks())o.stop();this.stream=new MediaStream([t]),this.ownStream=!1}await this.build(),this.watchContext(),this.rt?.post({type:"dispose",input:this.id}),this.rt=null,this.startModels()}else t&&await this.setStream(new MediaStream([t]));let i=this.currentTrack();i&&i!==r&&this.emit("trackchange",i)}teardownGraph(){this.node?.port.postMessage({type:"dispose"});for(let t of[this.source,this.node,this.dest,this.farSource])t?.disconnect()}spot(t,e={}){if(this.kind==="wake")throw new TypeError("spot() reads Focus: use the wake listener itself");return new K(this,t.map(r=>y(r).toJSON()),e.context??"anywhere")}enrollWord(t,e={}){return new A({compile:async()=>(await import("./api-5Z64WCXH.js")).compileWord(t,e.lang,"focus"),open:async r=>{await this.running;let i=await v.get().models("realtime",["spot"]);return i.post({type:"set",input:this.id,enroll:{word:r}}),{on:this.on.bind(this),stop:()=>i.post({type:"set",input:this.id,enroll:null}),source:"focus"}},embed:async(r,i)=>(await import("./api-5Z64WCXH.js")).embedAs(r,i)})}setWords(t,e){this.spotWords={words:t,context:e},this.rt&&v.get().models("realtime",["spot"]).then(r=>r.post({type:"set",input:this.id,words:t,context:e}))}dispose(){if(!this.disposed){clearTimeout(this.retryTimer),clearTimeout(this.browserTimer),this.setStatus("disposed"),this.settle(new p("engine.failed","The input was disposed before its models ran."),!0),this.counted&&--rt===0&&v.get().idle();for(let t of this.offs)t();if(this.offs=[],this.rt?.post({type:"dispose",input:this.id}),this.bg?.post({type:"dispose",input:this.id}),this.teardownGraph(),this.ownStream)for(let t of this.stream.getTracks())t.stop();this.ownCtx&&this.ctx.close().catch(()=>{}),J.delete(this),this.clear()}}},H=class extends k{constructor(t){super(t);this.opts=t}kind="call";get track(){return super.track}get delay16(){return C.lag+.1*M}models(){return["focus","cue"]}chainOptions(){let t=m(this.opts.voiceprint);return{gate:!0,normalize:!0,strength:this.opts.strength??1,print:t?.embedding??null,sample:this.sample,levels:!0,near:!!this.opts.near}}wantsBackground(){return this.learning||!!this.opts.onlyMyVoice}reference(){return this.opts.onlyMyVoice&&!this.learning?m(this.opts.voiceprint):null}realtimeOptions(){return{pipeline:"call",chain:this.chainOptions(),learn:this.learning,onlyMyVoice:!!this.opts.onlyMyVoice,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:!0}}setStrength(t){this.rt?.post({type:"set",input:this.id,strength:t}),this.opts.strength=t}async start(){return await this.open(),this.keepAlive(),this}keepAlive(){if(typeof document>"u")return;let t=this.ctx.createOscillator();t.frequency.value=pt;let e=this.ctx.createGain(),r=()=>void(e.gain.value=document.hidden?ht:0);r(),t.connect(e).connect(this.ctx.destination),t.start(),document.addEventListener("visibilitychange",r),this.offs.push(()=>{document.removeEventListener("visibilitychange",r),t.stop()})}},K=class extends g{constructor(t,e,r){super();this.input=t;t.setWords(e,r),this.off=t.on("wake",i=>this.emit("wake",i))}off;dispose(){this.off(),this.input.setWords([],"anywhere"),this.clear()}};function Ut(n={}){return new H(n).start()}var G=class extends k{constructor(t){super(t);this.opts=t}kind="agent";packer=null;rawAudio(t){this.packer??=new W(this.output(),e=>{let r=this.appPort();r?r.postMessage({type:"audio",pcm:e},[e]):this.opts.output?.port||this.emit("audio",e)}),this.packer.push(t)}output(){let t=this.opts.output??{};return{format:t.format??"f32",rate:t.rate??M,chunkMs:Math.max(16,Math.round((t.chunkMs??32)/16)*16)}}get delay16(){return C.lag}models(){return["focus","cue"]}withTrack=!1;get track(){return this.withTrack||(this.withTrack=!0,this.node&&!this.disposed&&super.connectOutput()),super.track}connectOutput(){this.withTrack&&super.connectOutput();let t=this.ctx.createGain();t.gain.value=0,this.node.connect(t).connect(this.ctx.destination)}wantsBackground(){return this.learning||!!this.opts.onlyMyVoice}reference(){return this.opts.onlyMyVoice&&!this.learning?m(this.opts.voiceprint):null}realtimeOptions(){let t=m(this.opts.voiceprint);return{pipeline:"agent",onlyMyVoice:!!this.opts.onlyMyVoice,chain:{gate:!1,normalize:!0,strength:1,print:t?.embedding??null,sample:this.sample,levels:!0,near:!!this.opts.near},learn:this.learning,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:!0,output:{...this.output(),audio:!0,utterance:!0},turn:{...this.opts.turn},interrupt:!0,wake:!!this.opts.wake}}async start(){let t=this.opts.wake;if(t){if(!Array.isArray(t.words))throw new TypeError("createAgentInput: wake takes { words, lang, context }");let{Spot:e}=await import("./api-5Z64WCXH.js"),r=o=>typeof o=="string"&&!o.trimStart().startsWith("{");if(t.words.some(r)&&!t.lang)throw new TypeError("createAgentInput: wake.lang is needed for a typed word");let i=await Promise.all(t.words.map(async o=>(r(o)?await e.compile(o,{lang:t.lang}):y(o)).toJSON()));if(!i.length)throw new TypeError("createAgentInput: wake.words is empty");this.spotWords={words:i,context:t.context??"pause"}}return await this.open(),this}};function jt(n={}){return new G(n).start()}var U=class extends k{constructor(t){super(t);this.opts=t;if(this.words=t.words.map(e=>y(e).toJSON()),!this.words.length)throw new TypeError("createWakeListener: no word");for(let e of this.words)e.chain==="focus"&&this.diag({code:"word.chain",level:"warn",message:`"${e.text}" was enrolled behind Focus: its thresholds are off on the raw microphone.`})}kind="wake";words;async resolveVoice(){this.opts.voiceprint instanceof Float32Array&&(this.opts.voiceprint=(await x(this.opts.voiceprint)).print??null)}models(){return["spot"]}connectOutput(){let t=this.ctx.createGain();t.gain.value=0,this.node.connect(t).connect(this.ctx.destination)}wantsBackground(){return!!this.reference()}reference(){return m(this.opts.voiceprint)}realtimeOptions(){return{pipeline:"wake",words:this.words,context:this.opts.context??"pause",trace:this.opts.trace,verify:!!this.reference()}}async start(){return await this.open(),this}};function qt(n){return new U(n).start()}var j=class extends k{constructor(t,e){super(t);this.opts=t;this.word=e}kind="wake";models(){return["spot"]}connectOutput(){let t=this.ctx.createGain();t.gain.value=0,this.node.connect(t).connect(this.ctx.destination)}realtimeOptions(){return{pipeline:"enroll",enroll:{word:this.word}}}async start(){return await this.open(),this}};function $t(n,s){return new j(n,s).start()}export{A as a,E as b,v as c,P as d,Pt as e,Ut as f,jt as g,qt as h,$t as i};
|
package/dist/chunk-LB4OLDBE.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as R,b as p,c as O,d as I,e as T,i as M}from"./chunk-BWNLE4ZO.js";import{A as E,D as A,a as k,b as d,c as S,e as F,f as N,g as x,h,i as b,k as P,n as y,o as v,p as B,s as L,v as V,z as W}from"./chunk-SSJ7CLCP.js";var c=class{static langs=F.langs;static inventory=N.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 H=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",G=0,Q=null;async function m(e,r){if(H()){let n=await(Q??=import("./node-KQMEHMZQ.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=O.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","timbre"];return r.voiceprint&&!t.includes("timbre")&&t.push("timbre"),r.typedWords&&t.push("lex"),t}async function Y(e){if("pcm"in e&&"rate"in e)return p.all(e.pcm,e.rate,d);if(typeof AudioBuffer<"u"&&e instanceof AudioBuffer)return p.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}=E(r);return p.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 p.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 ve={configure:B,stream:Z,supported:I,micPermission:T,onDiag:L,async preload(e,r={}){let t=U(e,r);if(H()){await m(t);return}let n=O.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=[k,...U(e,r).map(n=>S[n])];return(await Promise.all(t.map(V))).every(Boolean)},async process(e,r={}){r=await A(r);let t=await Y(e);r.signal?.throwIfAborted();let o=await(await m(_(r))).call("process",[t,X(r)],[],r.onProgress);return{...o,toWav(a="audio"){return W(a==="both"?[o.raw,o.audio]:[a==="raw"?o.raw:o.audio],d)}}}};function _(e){let r=[];return e.focus?r.push("focus","cue","timbre"):e.cue&&r.push("cue"),e.spot?.words.length&&r.push("spot"),r}function X(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*Z(e,r={}){r=await A(r);let t=await m(_(r)),n=++G,o=t.hold();await t.call("streamOpen",[n,X(r)]).catch(u=>{throw o(),u});let a=r.rate??d,s=new p(a,d,!0),l=0,i=0,f=Symbol.asyncIterator in e?e:ee(e);try{for await(let g of f){r.signal?.throwIfAborted();let w=[];l+=g.length,s.push(g,K=>w.push(K)),i+=w.length,w.length&&(yield await t.call("streamPush",[n,Float32Array.from(w)]))}let u=[],C=Math.round(l*d/a)-i;C>0&&s.push(new Float32Array(p.HALF*2+8),g=>u.length<C&&u.push(g)),u.length&&(yield await t.call("streamPush",[n,Float32Array.from(u)]))}finally{try{yield await t.call("streamEnd",[n])}finally{o()}}}async function*ee(e){let r=e.getReader();try{for(;;){let{done:t,value:n}=await r.read();if(t)return;yield n}}finally{r.releaseLock()}}var z=class e{constructor(r){this.b=r}static async create(){return new e(await m(["timbre"]))}async embed(r){return q(r,"raw",this.b)}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)}},J=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 m(["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]}};async function q(e,r,t){return y.fromJSON(await(t??await m(["timbre"])).call("embed",[e,r]))}async function re(e,r,t){for(let a of[r??[]].flat())if(!c.langs.includes(a))throw new b("lang.unsupported",`No ${a}: ${c.langs.join(", ")} only.`);let n=/^\s*\/.+\/\s*$/.test(e),o=await m(n?[]:["lex"]);return P(await o.call("compile",[e,{lang:r,chain:t}]))}var te={compile(e,r={}){return re(e,r.lang)},enroll(e,r={}){return new R({compile:()=>te.compile(e,r),open:async t=>{let n=await M(r,t);return{on:n.on.bind(n),stop:()=>n.dispose(),source:"raw"}},embed:(t,n)=>q(t,n)})}},$=e=>e?new y(e.centers,e.source,e.model,e.windows):null,ne=e=>({alkove:"voiceprint",model:e.model,source:e.source,centers:e.centers,windows:e.windows}),oe=typeof FinalizationRegistry>"u"?null:new FinalizationRegistry(e=>e()),D=class e{constructor(r,t,n,o){this.b=r;this.id=t;this.state={progress:n.progress,ready:n.ready,voiceprint:$(n.voiceprint)},oe?.register(this,()=>void r.call("learnerClose",[t]).catch(()=>{}).finally(o))}state;static async create(r={}){let t=await m(["timbre"]),n=++G,o=t.hold();try{let a=await t.call("learnerOpen",[n,r.voiceprint?ne(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:$(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{ve as a,z as b,J as c,q as d,re as e,te as f,D as g};
|
package/dist/chunk-SSJ7CLCP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var ae={name:"alkove-engine",file:"alkove-engine.wasm",bytes:635017,sha256:"03f52bfcfa1bc0b0491a4eb982e08a765e69e3e4ab3801f66349c9b0048d624a"};var L="alkove-ai",z={focus:{name:"alkove-focus-1",file:"alkove-focus-1.alk",bytes:2320032,sha256:"25028c1f9faf765ccab4076716b5e8a8e756cd7662babd2bc078951982df5ce4",revision:"69075e56ca39f9bc09bcf41c3f79288a2d753989"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1",file:"alkove-timbre-1.alk",bytes:970064,sha256:"fc94dfff533f1a4fb2abea172c1f5ff7a92cc00c6331275ea1a26e38f877b0e8",revision:"cb87ad720218e582f114d89b5a6936b9fd3f811a"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var A=16e3,x=z,Ie={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:1400,max:32e3,dim:192},Ve={langs:["fr","en","es","pt","it","ca","ro"],beams:3,bos:59,eos:60,vocab:61,word:33,steps:39};var h=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 I=new Map(H.map((e,t)=>[e,t+1])),Je=I.get("\u0259"),ie={"\u1D7B":"\u026A",\u025A:"\u0259\u0279",\u025D:"\u025C\u0279",\u029D:"j",\u025F:"\u0261",c:"k",\u026B:"l",\u026C:"l",\u03C7:"x",\u0266:"h",\u028B:"v",\u0271:"m",\u027B:"\u0279",\u0280:"\u0281",g:"\u0261",\u0258:"\u0259",\u0275:"\xF8",\u028F:"y",\u026F:"u",\u0264:"o",q:"k",\u0255:"\u0283",\u0291:"\u0292",\u00E7:"\u0283",\u0294:"",\u0252:"\u0254",\u0153\u0303:"\u025B\u0303",\u0278:"f",\u0299:"b"},ce={fr:{\u0251:"a",\u00E3:"\u0251\u0303",\u00F5:"\u0254\u0303",\u1EBD:"\u025B\u0303",\u0129:"\u025B\u0303",\u0169:"\u0254\u0303",\u0250\u0303:"\u0251\u0303",\u0250:"a",\u00E6:"a",\u028C:"\u0153",\u025C:"\u0153",\u026A:"i",\u028A:"u",\u0279:"\u0281",r:"\u0281",\u027E:"\u0281",x:"\u0281",\u03B8:"s",\u00F0:"z",h:"",\u03B2:"b",\u0263:"\u0261",\u028E:"lj",\u0268:"i"},es:{\u026A:"i",\u028A:"u",\u025B:"e",\u0254:"o",\u0251:"a",\u00E6:"a",\u028C:"a",\u0259:"e",\u0250:"a",\u0279:"\u027E"},it:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"a",\u0250:"a",\u0279:"r",x:"k",\u03B8:"t",h:""},pt:{\u026A:"i",\u028A:"u",\u028A\u0303:"\u0169",y:"j",\u00E3:"\u0250\u0303",\u0251:"a",\u00E6:"a",\u028C:"a",\u0279:"\u027E"},ca:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"\u027E",\u0250:"\u0259"},ro:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"r",\u027E:"r"},en:{\u0250:"\u0259",r:"\u0279",x:"k",\u025B\u0303:"\u0251\u0303"}},ue=new Set("\u02C8\u02CC\u02D0\u02D1\u203F-.|\u02B2\u02B0\u02B7' "),le=[["e","\u025B"],["o","\u0254"],["\xF8","\u0153","\u0259"],["i","j"],["u","w"],["y","\u0265"],["\u027E","r"]],B=H.map((e,t)=>[t+1]);for(let e of le){let t=e.map(r=>I.get(r.normalize("NFD")));for(let r of t)for(let n of t)B[r-1].includes(n)||B[r-1].push(n)}var $=new Map;function fe(e){let t=$.get(e);if(!t){let r=Object.entries({...ie,...ce[e]??{}}).map(([n,o])=>[n.normalize("NFD"),o.normalize("NFD")]);$.set(e,t=new Map(r))}return t}function j(e){let t=[];for(let r of e.normalize("NFD")){if(/\p{M}/u.test(r)){r==="\u0303"&&t.length&&(t[t.length-1]+=r);continue}t.push(r)}return t}function _(e,t=""){let r=fe(t),n=[];for(let o of j(e.replace(/\([^)]*\)/g," ").replace(//g,"").replace(/\s+/g," ")))if(!ue.has(o))for(let a of j(r.get(o)??o)){a=r.get(a)??a;let s=I.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 h("word.outdated",`Compiled for another Spot: compile "${typeof e=="string"?JSON.parse(e).text:e.text}" again.`);return t};var de=.6931471803691238,pe=19082149292705877e-26;var F=new DataView(new ArrayBuffer(8));function V(e){if(e!==e||e<0)return NaN;if(e===0)return-1/0;if(e===1/0)return e;let t=0;e<22250738585072014e-324&&(e*=0x40000000000000,t=-54),F.setFloat64(0,e);let r=F.getUint32(0);t+=(r>>>20)-1023;let n=r&1048575,o=n+614244&1048576;t+=o>>>20,n|=o^1072693248,F.setUint32(0,n);let a=F.getFloat64(0)-1,s=a/(2+a),i=s*s,u=i*i,f=u*(.3999999999940942+u*(.22222198432149784+u*.15313837699209373)),l=i*(.6666666666666735+u*(.2857142874366239+u*(.1818357216161805+u*.14798198605116586))),d=.5*a*a;return t*de-(d-(s*(d+l+f)+t*pe)-a)}var me=1.5707963267341256,he=6077100506506192e-26,ge=.6366197723675814;function P(e){let t=e*e;return e+e*t*(-.16666666666666632+t*(.00833333333332249+t*(-.0001984126982985795+t*(27557313707070068e-22+t*(-25050760253406863e-24+t*158969099521155e-24)))))}function N(e){let t=e*e,r=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),n=.5*t,o=1-n;return o+(1-o-n+t*r)}function G(e){let t=Math.round(e*ge);return[t&3,e-t*me-t*he]}function _e(e){let[t,r]=G(e);return t===0?P(r):t===1?N(r):t===2?-P(r):-N(r)}function qe(e){let[t,r]=G(e);return t===0?N(r):t===1?-P(r):t===2?-N(r):P(r)}var be=(e,t)=>{let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r},S=class e{constructor(t,r="focus",n=y.model,o=[]){this.centers=t;this.source=r;this.model=n;this.windows=o;if(!t.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(t){return this.closest(t).score}closest(t){let r=t instanceof e?t.centers:[t],n={score:-1,mine:0,theirs:0};for(let o of this.centers)for(let a of r){let s=be(o.id,a.id);s>n.score&&(n={score:s,mine:o.seconds,theirs:a.seconds})}return n}toArray(){return this.centers[0].id.slice()}toJSON(){let t=r=>Array.from(r,n=>+n.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(r=>({embedding:t(r.embedding),id:t(r.id),seconds:+r.seconds.toFixed(1)})),...this.windows.length?{windows:we(this.windows)}:{}}}static fromJSON(t){let r=typeof t=="string"?JSON.parse(t):t;if(r.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(r.model!==y.model)return null;let n=r.centers.map(o=>({embedding:Float32Array.from(o.embedding),id:Float32Array.from(o.id),seconds:o.seconds}));return new e(n,r.source,r.model,r.windows?ye(r.windows):[])}static merge(t){return new e(t.flatMap(r=>r.centers),t.every(r=>r.source==="raw")?"raw":"focus")}};function we(e){let t=new Uint8Array(e.length*2*(y.dim+4)),r=new DataView(t.buffer),n=0;for(let a of e)for(let s of[a.embedding,a.id]){let i=1e-9;for(let u of s)i=Math.max(i,Math.abs(u));r.setFloat32(n,i/127,!0),n+=4;for(let u of s)r.setInt8(n++,Math.round(u/i*127))}let o="";for(let a of t)o+=String.fromCharCode(a);return btoa(o)}function ye(e){let t=atob(e),r=Uint8Array.from(t,s=>s.charCodeAt(0)),n=new DataView(r.buffer),o=[],a=0;for(;a+2*(y.dim+4)<=r.length;){let s=[];for(let i=0;i<2;i++){let u=n.getFloat32(a,!0);a+=4;let f=new Float32Array(y.dim);for(let l=0;l<f.length;l++)f[l]=n.getInt8(a++)*u;s.push(f)}o.push({embedding:s[0],id:s[1],seconds:y.window/A})}return o}function ve(e,t,r){let n=(c,p)=>{let v=Math.min(Math.max(p,c[0]),c[c.length-1]),m=Math.max(1,c.findIndex(b=>b>=v));return[m-1,m,V(v/c[m-1])/V(c[m]/c[m-1])]},[o,a,s]=n(W.print,r),[i,u,f]=n(W.heard,t),l=W[e],d=c=>l[c][i]+(l[c][u]-l[c][i])*f;return d(o)+(d(a)-d(o))*s}var W={print:[1.5,3,6,12,24],heard:[.6,.9,1.5,3],lenient:[[.0375,.0725,.0925,.1125],[.0775,.1675,.195,.2275],[.1125,.2375,.2925,.33],[.155,.27,.335,.3725],[.1775,.295,.365,.4075]],balanced:[[.26,.3,.3325,.3575],[.2975,.345,.3825,.41],[.325,.38,.4225,.4525],[.3475,.405,.4425,.475],[.3575,.42,.465,.495]],strict:[[.405,.4325,.455,.4725],[.425,.455,.4775,.5],[.44,.4725,.4975,.52],[.4475,.48,.51,.5325],[.4525,.4875,.515,.5375]]},K=class e{static verify(t,r,{level:n="balanced"}={}){let{score:o,mine:a,theirs:s}=t.closest(r);return{same:o>=ve(n,s,a),score:o}}static identify(t,r,n={}){let o=null;for(let[a,s]of Object.entries(r)){let{same:i,score:u}=e.verify(s,t,n);i&&(!o||u>o.score)&&(o={who:a,score:u})}return o}};var Z="alkove",E="https://cache.alkove.invalid/",xe=30,g={},ee=!1,C=new Set;function et(e){ee&&te({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),g={...g,...e}}var tt=()=>g,rt=()=>void(ee=!0);function nt(e){return C.add(e),()=>void C.delete(e)}var X=new Set;function te(e){for(let t of C)t(e);C.size||e.level!=="warn"||X.has(e.code)||(X.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function re(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}var Ae=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",ne=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function Se(e,t){let r=globalThis.location?.href;return new URL(t,new URL(String(e).replace(/\/?$/,"/"),r)).href}function Y(e){if(g.modelBaseUrl)return Se(g.modelBaseUrl,e.file);if(!e.revision)throw new h("models.fetch",`${e.name}: not on Hugging Face in this version, set modelBaseUrl`);return te({code:"models.default-host",level:"warn",message:`${e.name} comes from Hugging Face: each user sends it their IP. Self-host the models in production (modelBaseUrl).`}),`https://huggingface.co/${L}/${e.name}/resolve/${e.revision}/${e.file}`}async function ke(e,t,r=0){let n;try{n=await fetch(e)}catch(l){throw new h("models.fetch",`fetch failed: ${e}`,l)}if(!n.ok||!n.body)throw new h("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:l,value:d}=await a.read();if(l)break;s.push(d),i+=d.length,t?.({loaded:i,total:Math.max(o,i)})}let u=new Uint8Array(i),f=0;for(let l of s)u.set(l,f),f+=l.length;return u}async function k(e,t){let r=await re(t);if(r!==e.sha256)throw new h("models.hash",`${e.name}: sha256 ${r}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return t}async function R(e,t,r){return t instanceof ArrayBuffer?k(e,new Uint8Array(t)):t instanceof Uint8Array?k(e,t):k(e,await ke(String(t),r,e.bytes))}async function Ue(e,t){if(!ne())return t();let r;try{r=await caches.open(Z)}catch{return t()}let n=E+e.sha256,o=await r.match(n).catch(()=>{});if(o){let s=new Uint8Array(await o.arrayBuffer());if(await re(s)===e.sha256)return Q(r,e.sha256),s;await r.delete(n).catch(()=>{})}let a=await t();return await r.put(n,new Response(a,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),Q(r,e.sha256),a}async function Q(e,t){try{let r=E+"used.json",n=await(await e.match(r))?.json().catch(()=>null)??{},o=Date.now();n[t]=o;for(let[a,s]of Object.entries(n))o-s>xe*864e5&&(await e.delete(E+a),delete n[a]);await e.put(r,new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}}))}catch{}}async function ot(e){if(g.models?.[T(e)]instanceof ArrayBuffer||g.models?.[T(e)]instanceof Uint8Array)return!0;if(!ne())return!1;try{return!!await(await caches.open(Z)).match(E+e.sha256)}catch{return!1}}var T=e=>Object.entries(x).find(([,t])=>t===e)?.[0]??"engine";async function Oe(e,t,r){let n=g.models?.[T(e)]??r;if(n instanceof ArrayBuffer||n instanceof Uint8Array)return R(e,n);if(Ae()){if(n&&String(n).startsWith("file:")){let{readFile:a}=await import("node:fs/promises");return k(e,new Uint8Array(await a(new URL(String(n)))))}let o=Fe(g.modelBaseUrl);if(o){let{readFile:a}=await import("node:fs/promises"),{join:s}=await import("node:path");return k(e,new Uint8Array(await a(s(await o,e.file))))}return R(e,n??Y(e),t)}return Ue(e,()=>R(e,n??Y(e),t))}function Fe(e){if(!e)return null;let t=String(e);return t.startsWith("file:")?import("node:url").then(r=>r.fileURLToPath(t)):/^[a-z][a-z0-9+.-]+:/i.test(t)?null:Promise.resolve(t)}function st(e,t){return Oe(x[e],t)}function oe(e,t){let r=e[0]?.length??0,n=e.length,o=r*n*2,a=new Uint8Array(44+o),s=new DataView(a.buffer),i=(f,l)=>[...l].forEach((d,c)=>s.setUint8(f+c,d.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 f=0;f<r;f++)for(let l=0;l<n;l++){let d=Math.max(-1,Math.min(1,e[l][f]));s.setInt16(u,d<0?d*32768:d*32767,!0),u+=2}return a}function it(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:f,rate:l,bits:d}=o,c=d/8,p=Math.floor(Math.min(s,e.length-i)/(c*f)),v=new Float32Array(p);for(let m=0;m<p;m++){let b=0;for(let M=0;M<f;M++){let w=i+(m*f+M)*c;if(u===3)b+=d===64?t.getFloat64(w,!0):t.getFloat32(w,!0);else if(d===8)b+=(t.getUint8(w)-128)/128;else if(d===16)b+=t.getInt16(w,!0)/32768;else if(d===24)b+=(t.getUint8(w)|t.getUint8(w+1)<<8|t.getInt8(w+2)<<16)/8388608;else if(d===32)b+=t.getInt32(w,!0)/2147483648;else throw new TypeError(`audio.format: ${d}-bit WAV`)}v[m]=b/f}return{pcm:v,rate:l}}n=i+s+(s&1)}throw new TypeError("audio.format: WAV without data")}var se={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6};function Pe(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,...n.sample?{sample:Array.from(n.sample)}:{}}:null,cue:e.cue===void 0||e.cue===null?null:e.cue!==!1,speech:{...se,...typeof e.cue=="object"?e.cue:{}},normalize:e.normalize??!1,trace:!!e.trace,rate:t,spot:a.length?{words:a.map(s=>s.toJSON()),context:e.spot?.context??"anywhere"}:null}}function Ne(e){return!e||e instanceof Float32Array?null:e instanceof S?e:S.fromJSON(e)}async function Ee(e){if(!(e instanceof Float32Array))return{print:e};let{Timbre:t}=await import("./api-5Z64WCXH.js");return{print:await(await t.create()).embed(e),sample:e}}async function ht(e){let t=e.focus;if(typeof t!="object"||!(t.voiceprint instanceof Float32Array))return e;let r=await Ee(t.voiceprint);return{...e,focus:{...t,voiceprint:r.print,sample:t.sample??r.sample}}}var J=class{constructor(t,r={}){this.opts=r;this.core=t.processor(Pe(r))}core;closed=!1;push(t){if(this.closed)throw new Error("push after end");return this.core.push(t)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},D=16e3;function gt(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+=D)o?.throwIfAborted(),i.push(s.push(t.subarray(c,Math.min(t.length,c+D)))),n?.({done:Math.min(t.length,c+D),total:t.length});i.push(s.end())}finally{s.release()}let u=new Float32Array(t.length),f=0;for(let c of i)u.set(c.audio.subarray(0,u.length-f),f),f+=c.audio.length;let l=t,d=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:l,...d,toWav(c="audio"){return oe(c==="both"?[l,this.audio]:[c==="raw"?l:this.audio],A)}}}export{ae as a,A as b,x as c,Ie as d,Ve as e,H as f,B as g,_ as h,h as i,O as j,q as k,_e as l,qe as m,S as n,K as o,et as p,tt as q,rt as r,nt as s,te as t,Se as u,ot as v,Oe as w,st as x,se as y,oe as z,it as A,Ne as B,Ee as C,ht as D,J as E,gt as F};
|
package/dist/node-KQMEHMZQ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{E as W,F as H,a as S,d as R,i as z,w as $,x as D,y as I}from"./chunk-SSJ7CLCP.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,K=["silence","forced","wake"],j=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(j(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(j(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:K[u]}});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 B(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,r.timbre?.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 J(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)}timbre(e){this.alk.x.alk_pipeline_timbre(o(this.ptr),e.ptr)<0&&this.alk.fail("pipeline.timbre")}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,timbre:r?this.model("timbre"):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,n=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);return r&&n.timbre(this.model("timbre")),n}coach(e){return new E(this.alk,e)}voiceprint(e){return J(this.alk,e)}compile(e,r,t){return B(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((Y,q)=>Y*q,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 Q(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 G=class{engine=null;boot=null;bytes=new Map;calls=Q(()=>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{G as NodeBackend};
|