alkove 0.4.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +1 -1
- package/README.md +6 -6
- 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 +32 -13
- 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 +2 -0
- package/dist/core/engine.d.ts +19 -7
- package/dist/core/lex.d.ts +1 -1
- package/dist/core/native.d.ts +24 -5
- package/dist/core/spot/spot.d.ts +40 -1
- package/dist/engine/alk.d.ts +15 -5
- package/dist/errors.d.ts +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/loader.d.ts +0 -1
- package/dist/manifest.d.ts +5 -2
- package/dist/models.generated.d.ts +155 -1
- package/dist/node-3YHT2KZ5.js +1 -0
- package/dist/process.d.ts +33 -3
- package/dist/react.js +1 -1
- package/dist/realtime/worker.d.ts +6 -4
- package/dist/recipes/input.d.ts +55 -32
- package/dist/runtime/calls.d.ts +1 -0
- package/dist/runtime/node.d.ts +1 -0
- package/package.json +2 -2
- package/dist/api-63K47HT3.js +0 -1
- package/dist/assets-CPGXIA43.js +0 -2
- package/dist/chunk-FC4ZSMUX.js +0 -1
- package/dist/chunk-IMUNEOSF.js +0 -1
- package/dist/chunk-MZOMHWYI.js +0 -1
- package/dist/node-VEIFZSW6.js +0 -1
package/dist/process.d.ts
CHANGED
|
@@ -5,8 +5,9 @@ import { type Context, type WakeEvent, type Word, type WordJSON } from './core/s
|
|
|
5
5
|
import { Voiceprint, type VoiceprintJSON } from './core/timbre';
|
|
6
6
|
export interface ProcessOptions {
|
|
7
7
|
focus?: boolean | {
|
|
8
|
-
voiceprint?:
|
|
8
|
+
voiceprint?: VoiceprintInput;
|
|
9
9
|
strength?: number;
|
|
10
|
+
lowPower?: boolean;
|
|
10
11
|
};
|
|
11
12
|
cue?: boolean | Partial<SpeechParams>;
|
|
12
13
|
spot?: {
|
|
@@ -55,8 +56,10 @@ export interface ProcessPart {
|
|
|
55
56
|
}
|
|
56
57
|
export declare function coreOptions(opts: Omit<ProcessOptions, 'onProgress' | 'signal'>, rate?: number): {
|
|
57
58
|
focus: {
|
|
59
|
+
sample?: number[] | undefined;
|
|
58
60
|
print: number[] | null;
|
|
59
61
|
strength: number;
|
|
62
|
+
lowPower: boolean;
|
|
60
63
|
} | null;
|
|
61
64
|
cue: boolean | null;
|
|
62
65
|
speech: {
|
|
@@ -73,12 +76,39 @@ export declare function coreOptions(opts: Omit<ProcessOptions, 'onProgress' | 's
|
|
|
73
76
|
context: Context;
|
|
74
77
|
} | null;
|
|
75
78
|
};
|
|
76
|
-
export
|
|
79
|
+
export type VoiceprintInput = Voiceprint | VoiceprintJSON | string | Float32Array | null;
|
|
80
|
+
export declare function printOf(p: VoiceprintInput | undefined): Voiceprint | null;
|
|
81
|
+
export declare function voiceOf(p: VoiceprintInput | undefined): Promise<{
|
|
82
|
+
print: Voiceprint | VoiceprintJSON | string | null | undefined;
|
|
83
|
+
sample?: Float32Array;
|
|
84
|
+
}>;
|
|
85
|
+
export declare function withVoice<T extends ProcessOptions>(opts: T): Promise<T>;
|
|
77
86
|
export declare class Processor {
|
|
78
87
|
readonly opts: Omit<ProcessOptions, 'onProgress' | 'signal'>;
|
|
79
88
|
private core;
|
|
80
89
|
private closed;
|
|
81
|
-
constructor(engine: Engine, opts?: Omit<ProcessOptions, 'onProgress' | 'signal'
|
|
90
|
+
constructor(engine: Engine, opts?: Omit<ProcessOptions, 'onProgress' | 'signal'>, wire?: {
|
|
91
|
+
focus: {
|
|
92
|
+
sample?: number[] | undefined;
|
|
93
|
+
print: number[] | null;
|
|
94
|
+
strength: number;
|
|
95
|
+
lowPower: boolean;
|
|
96
|
+
} | null;
|
|
97
|
+
cue: boolean | null;
|
|
98
|
+
speech: {
|
|
99
|
+
confidence: number;
|
|
100
|
+
exitConfidence: number;
|
|
101
|
+
startSecs: number;
|
|
102
|
+
stopSecs: number;
|
|
103
|
+
};
|
|
104
|
+
normalize: boolean;
|
|
105
|
+
trace: boolean;
|
|
106
|
+
rate: number;
|
|
107
|
+
spot: {
|
|
108
|
+
words: WordJSON[];
|
|
109
|
+
context: Context;
|
|
110
|
+
} | null;
|
|
111
|
+
});
|
|
82
112
|
push(pcm: Float32Array): ProcessPart;
|
|
83
113
|
end(): ProcessPart;
|
|
84
114
|
release(): void;
|
package/dist/react.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
import{f as W,g as
|
|
2
|
+
import{f as W,g as V,h as F}from"./chunk-C5QG5BVR.js";import"./chunk-2PTYZFLZ.js";import{useCallback as M,useEffect as h,useLayoutEffect as B,useRef as p,useState as v}from"react";var J=t=>Array.isArray(t)||Object.getPrototypeOf(t)===Object.prototype;function k(t,r){if(Object.is(t,r))return!0;if(typeof t!="object"||typeof r!="object"||!t||!r)return!1;let u=t.toJSON,a=r.toJSON;if(typeof u=="function"||typeof a=="function")return k(typeof u=="function"?u.call(t):t,typeof a=="function"?a.call(r):r);if(!J(t)||!J(r)||Array.isArray(t)!==Array.isArray(r))return!1;let l=Object.keys(t).filter(o=>t[o]!==void 0),S=Object.keys(r).filter(o=>r[o]!==void 0);return l.length===S.length&&l.every(o=>k(t[o],r[o]))}var Q={speechstart:!0,speechend:!0,speechcancel:!0,turn:!0,turnend:!0,interruptstart:!0,interrupt:!0,interruptcancel:!0,mode:!0,status:!0,voiceprint:!0,learn:!0,mic:!0,trackchange:!0,wake:!0,command:!0,language:!0,heard:!0,trace:!0,audio:!0,utterance:!0,take:!0,enrolled:!0},X=Object.keys(Q),C=1,D=Promise.resolve(),Y=typeof window>"u"?h:B;function N(t,r,u){let{enabled:a=!0,on:l,...S}=r,o=S,m=p(l),x=p(o),w=Object.fromEntries(Object.entries(o).filter(([n])=>!u.includes(n))),f=p({value:w,version:0}),b=k(f.current.value,w)?f.current.version:f.current.version+1;Y(()=>{m.current=l,x.current=o,b!==f.current.version&&(f.current={value:w,version:b})});let[O,R]=v(null),[P,d]=v("off"),[G,E]=v(null),[K,A]=v(null),[q,H]=v(null),s=p(null),c=p({}),i=p(null),y=M(()=>{let n=!!s.current&&!!m.current?.diag;n&&!i.current?i.current=s.current.on("diag",g=>m.current?.diag?.(g)):!n&&i.current&&(i.current(),i.current=null)},[]);h(()=>{if(!a)return;let n=new AbortController,g=[];d("starting"),A(null);let T=D.then(()=>{if(n.signal.aborted)return;let e={...x.current,signal:n.signal};return c.current={strength:e.strength??C,voiceprint:e.voiceprint??null},t(e)});return D=T.catch(()=>{}),T.then(e=>{if(e){if(n.signal.aborted)return e.dispose();s.current=e,y();for(let I of X)g.push(e.on(I,(z=>m.current?.[I]?.(z))));g.push(e.on("status",d),e.on("mode",I=>E(I.mode)),e.on("trackchange",H)),R(e),d(e.status),E(e.mode)}},e=>{n.signal.aborted||(A(e instanceof Error?e:new Error(String(e))),d("off"))}),()=>{n.abort();for(let e of g)e();i.current?.(),i.current=null,s.current?.dispose(),s.current=null,R(null),d("off"),E(null),H(null),A(null)}},[a,b,t,y]);let U=!!l?.diag;h(y,[O,U,y]);let j=u.includes("strength")?o.strength:void 0,L=u.includes("voiceprint")?o.voiceprint:void 0;h(()=>{let n=s.current;n&&(u.includes("strength")&&(j??C)!==c.current.strength&&(c.current.strength=j??C,n.setStrength(c.current.strength)),u.includes("voiceprint")&&!k(L??null,c.current.voiceprint??null)&&(c.current.voiceprint=L??null,n.setVoiceprint(c.current.voiceprint)))},[O,j,L,u]);let _=M(async()=>{await s.current?.resume()},[]);return{input:O,status:P,mode:G,error:K,get track(){return q??O?.track??null},resume:_}}var Z=["strength","voiceprint"],$=["voiceprint"],tt=[];function ut(t={}){return N(V,t,$)}function st(t={}){return N(W,t,Z)}function ct(t){return N(F,t,tt)}export{ut as useAgentInput,st as useCallInput,ct as useWakeListener};
|
|
@@ -1,23 +1,24 @@
|
|
|
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 {
|
|
7
8
|
pipeline: 'call' | 'agent' | 'wake' | 'enroll';
|
|
8
9
|
enroll?: {
|
|
9
10
|
word: WordJSON;
|
|
10
|
-
takes
|
|
11
|
+
takes?: number;
|
|
11
12
|
};
|
|
12
13
|
verify?: boolean;
|
|
14
|
+
onlyMyVoice?: boolean;
|
|
13
15
|
chain?: ChainOptions & {
|
|
14
16
|
levels?: boolean;
|
|
15
|
-
near?: boolean
|
|
16
|
-
gapDb?: number;
|
|
17
|
-
};
|
|
17
|
+
near?: boolean;
|
|
18
18
|
};
|
|
19
19
|
words?: WordJSON[];
|
|
20
20
|
context?: Context;
|
|
21
|
+
wake?: boolean;
|
|
21
22
|
learn?: boolean;
|
|
22
23
|
keepRecent?: number;
|
|
23
24
|
trace?: boolean;
|
|
@@ -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,11 +1,12 @@
|
|
|
1
|
-
import type {
|
|
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
|
-
import { Voiceprint
|
|
5
|
+
import { Voiceprint } from '../core/timbre';
|
|
6
6
|
import { type Diag } from '../errors';
|
|
7
7
|
import { Emitter } from '../events';
|
|
8
8
|
import { type Lang } from '../manifest';
|
|
9
|
+
import { type VoiceprintInput } from '../process';
|
|
9
10
|
import { type OutputOptions } from '../realtime/packer';
|
|
10
11
|
import type { RealtimeOptions } from '../realtime/worker';
|
|
11
12
|
import { type WorkerLink } from '../runtime/host';
|
|
@@ -69,6 +70,8 @@ export interface InputEvents {
|
|
|
69
70
|
};
|
|
70
71
|
trackchange: MediaStreamTrack;
|
|
71
72
|
wake: WakeEvent;
|
|
73
|
+
command: CommandEvent;
|
|
74
|
+
language: LanguageEvent;
|
|
72
75
|
heard: {
|
|
73
76
|
speech: number;
|
|
74
77
|
scores: {
|
|
@@ -98,23 +101,16 @@ export interface CommonOptions {
|
|
|
98
101
|
track?: MediaStreamTrack;
|
|
99
102
|
audioContext?: AudioContext;
|
|
100
103
|
deviceId?: string;
|
|
101
|
-
followDefault?: boolean;
|
|
102
104
|
signal?: AbortSignal;
|
|
103
|
-
trace?: boolean;
|
|
104
|
-
keepRecent?: number;
|
|
105
105
|
}
|
|
106
106
|
export interface FocusOptions extends CommonOptions {
|
|
107
|
-
voiceprint?:
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
levels?: boolean;
|
|
115
|
-
near?: boolean | {
|
|
116
|
-
gapDb?: number;
|
|
117
|
-
};
|
|
107
|
+
voiceprint?: VoiceprintInput;
|
|
108
|
+
farEnd?: MediaStreamTrack | AudioNode;
|
|
109
|
+
near?: boolean;
|
|
110
|
+
lowPower?: boolean;
|
|
111
|
+
trace?: boolean;
|
|
112
|
+
keepRecent?: number;
|
|
113
|
+
langs?: readonly Lang[];
|
|
118
114
|
}
|
|
119
115
|
export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
120
116
|
protected opts: FocusOptions;
|
|
@@ -134,18 +130,22 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
|
134
130
|
private _status;
|
|
135
131
|
private _latency;
|
|
136
132
|
private _voiceprint;
|
|
133
|
+
protected sample: Float32Array | null;
|
|
137
134
|
private retryMs;
|
|
138
135
|
private retryTimer;
|
|
139
136
|
private started;
|
|
140
137
|
private counted;
|
|
141
138
|
private enabled;
|
|
142
139
|
private printed;
|
|
140
|
+
protected learning: boolean;
|
|
141
|
+
private farCalled;
|
|
143
142
|
private sender;
|
|
144
143
|
private stalled;
|
|
145
144
|
protected spotWords: {
|
|
146
145
|
words: WordJSON[];
|
|
147
146
|
context: Context;
|
|
148
147
|
} | null;
|
|
148
|
+
protected spotCommands: CommandsJSON[] | null;
|
|
149
149
|
private running;
|
|
150
150
|
private markRunning;
|
|
151
151
|
private ran;
|
|
@@ -168,9 +168,14 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
|
168
168
|
get ready(): Promise<void>;
|
|
169
169
|
private settle;
|
|
170
170
|
get track(): MediaStreamTrack | null;
|
|
171
|
+
protected currentTrack(): MediaStreamTrack | null;
|
|
171
172
|
now(): number;
|
|
172
173
|
protected abstract realtimeOptions(): RealtimeOptions;
|
|
173
174
|
protected abstract models(): ('focus' | 'cue' | 'spot')[];
|
|
175
|
+
protected spotLangs(): Lang[];
|
|
176
|
+
private spotting;
|
|
177
|
+
private spotFiles;
|
|
178
|
+
private realtimeModels;
|
|
174
179
|
protected get delay16(): number;
|
|
175
180
|
protected open(): Promise<void>;
|
|
176
181
|
private opening;
|
|
@@ -193,6 +198,9 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
|
193
198
|
protected portGiven: boolean;
|
|
194
199
|
protected appPort(): MessagePort | undefined;
|
|
195
200
|
protected wantsBackground(): boolean;
|
|
201
|
+
protected learns(): boolean;
|
|
202
|
+
private toBackground;
|
|
203
|
+
private startLearning;
|
|
196
204
|
protected reference(): Voiceprint | null;
|
|
197
205
|
private onRealtime;
|
|
198
206
|
protected onEvent(e: {
|
|
@@ -203,8 +211,9 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
|
203
211
|
listen(on: boolean): void;
|
|
204
212
|
hold(): void;
|
|
205
213
|
release(): void;
|
|
206
|
-
|
|
207
|
-
|
|
214
|
+
setVoiceprint(p: VoiceprintInput): void;
|
|
215
|
+
protected resolveVoice(): Promise<void>;
|
|
216
|
+
private applyPrint;
|
|
208
217
|
forgetVoiceprint(): void;
|
|
209
218
|
farEndActive(on: boolean): void;
|
|
210
219
|
stats(): Promise<{
|
|
@@ -230,29 +239,32 @@ export declare abstract class AlkoveInput extends Emitter<InputEvents> {
|
|
|
230
239
|
private teardownGraph;
|
|
231
240
|
spot(words: readonly (Word | WordJSON | string)[], opts?: {
|
|
232
241
|
context?: Context;
|
|
233
|
-
onlyMyVoice?: boolean;
|
|
234
242
|
}): SpotHandle;
|
|
235
243
|
enrollWord(text: string, opts?: {
|
|
236
244
|
lang?: Lang | Lang[];
|
|
237
|
-
takes?: number;
|
|
238
245
|
}): Enrollment;
|
|
239
246
|
setWords(words: WordJSON[], context: Context): void;
|
|
247
|
+
setCommands(commands: readonly CommandsJSON[] | null): void;
|
|
240
248
|
dispose(): void;
|
|
241
249
|
}
|
|
242
250
|
export interface CallOptions extends FocusOptions {
|
|
243
|
-
|
|
251
|
+
onlyMyVoice?: boolean;
|
|
252
|
+
strength?: number;
|
|
244
253
|
}
|
|
245
254
|
declare class CallInput extends AlkoveInput {
|
|
246
255
|
protected opts: CallOptions;
|
|
247
256
|
protected readonly kind: "call";
|
|
248
|
-
private osc;
|
|
249
257
|
constructor(opts: CallOptions);
|
|
250
258
|
get track(): MediaStreamTrack;
|
|
251
259
|
protected get delay16(): number;
|
|
252
260
|
protected models(): ('focus' | 'cue' | 'spot')[];
|
|
253
261
|
protected chainOptions(): NonNullable<RealtimeOptions['chain']>;
|
|
262
|
+
protected wantsBackground(): boolean;
|
|
263
|
+
protected reference(): Voiceprint | null;
|
|
254
264
|
protected realtimeOptions(): RealtimeOptions;
|
|
265
|
+
setStrength(s: number): void;
|
|
255
266
|
start(): Promise<this>;
|
|
267
|
+
private keepAlive;
|
|
256
268
|
}
|
|
257
269
|
export declare class SpotHandle extends Emitter<{
|
|
258
270
|
wake: WakeEvent;
|
|
@@ -264,13 +276,16 @@ export declare class SpotHandle extends Emitter<{
|
|
|
264
276
|
}
|
|
265
277
|
export declare function createCallInput(opts?: CallOptions): Promise<CallInput>;
|
|
266
278
|
export interface AgentOptions extends FocusOptions {
|
|
279
|
+
onlyMyVoice?: boolean;
|
|
267
280
|
output?: Partial<OutputOptions> & {
|
|
268
281
|
port?: MessagePort;
|
|
269
282
|
};
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
283
|
+
turn?: Partial<TurnOptions>;
|
|
284
|
+
wake?: {
|
|
285
|
+
words: readonly (Word | WordJSON | string)[];
|
|
286
|
+
lang?: Lang | Lang[];
|
|
287
|
+
context?: Context;
|
|
288
|
+
};
|
|
274
289
|
}
|
|
275
290
|
declare class AgentInput extends AlkoveInput {
|
|
276
291
|
protected opts: AgentOptions;
|
|
@@ -281,7 +296,11 @@ declare class AgentInput extends AlkoveInput {
|
|
|
281
296
|
private output;
|
|
282
297
|
protected get delay16(): number;
|
|
283
298
|
protected models(): ('focus' | 'cue' | 'spot')[];
|
|
299
|
+
private withTrack;
|
|
300
|
+
get track(): MediaStreamTrack | null;
|
|
284
301
|
protected connectOutput(): void;
|
|
302
|
+
protected wantsBackground(): boolean;
|
|
303
|
+
protected reference(): Voiceprint | null;
|
|
285
304
|
protected realtimeOptions(): RealtimeOptions;
|
|
286
305
|
start(): Promise<this>;
|
|
287
306
|
}
|
|
@@ -289,14 +308,18 @@ export declare function createAgentInput(opts?: AgentOptions): Promise<AgentInpu
|
|
|
289
308
|
export interface WakeOptions extends CommonOptions {
|
|
290
309
|
words: readonly (Word | WordJSON | string)[];
|
|
291
310
|
context?: Context;
|
|
292
|
-
|
|
311
|
+
langs?: readonly Lang[];
|
|
312
|
+
voiceprint?: VoiceprintInput;
|
|
313
|
+
trace?: boolean;
|
|
293
314
|
}
|
|
294
315
|
declare class WakeListener extends AlkoveInput {
|
|
295
316
|
protected opts: WakeOptions & FocusOptions;
|
|
296
317
|
protected readonly kind: "wake";
|
|
297
318
|
private words;
|
|
298
319
|
constructor(opts: WakeOptions & FocusOptions);
|
|
320
|
+
protected resolveVoice(): Promise<void>;
|
|
299
321
|
protected models(): ('focus' | 'cue' | 'spot')[];
|
|
322
|
+
protected spotLangs(): Lang[];
|
|
300
323
|
protected connectOutput(): void;
|
|
301
324
|
protected wantsBackground(): boolean;
|
|
302
325
|
protected reference(): Voiceprint | null;
|
|
@@ -305,15 +328,15 @@ declare class WakeListener extends AlkoveInput {
|
|
|
305
328
|
}
|
|
306
329
|
export declare function createWakeListener(opts: WakeOptions): Promise<WakeListener>;
|
|
307
330
|
declare class EnrollInput extends AlkoveInput {
|
|
308
|
-
protected opts: CommonOptions
|
|
331
|
+
protected opts: CommonOptions;
|
|
309
332
|
private word;
|
|
310
|
-
private takes;
|
|
311
333
|
protected readonly kind: "wake";
|
|
312
|
-
constructor(opts: CommonOptions
|
|
334
|
+
constructor(opts: CommonOptions, word: WordJSON);
|
|
313
335
|
protected models(): ('focus' | 'cue' | 'spot')[];
|
|
314
336
|
protected connectOutput(): void;
|
|
315
337
|
protected realtimeOptions(): RealtimeOptions;
|
|
338
|
+
protected spotLangs(): Lang[];
|
|
316
339
|
start(): Promise<this>;
|
|
317
340
|
}
|
|
318
|
-
export declare function createEnrollInput(opts: CommonOptions, word: WordJSON
|
|
341
|
+
export declare function createEnrollInput(opts: CommonOptions, word: WordJSON): Promise<EnrollInput>;
|
|
319
342
|
export type { AgentInput, CallInput, EnrollInput, WakeListener };
|
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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "alkove",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "On-device voice
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "On-device voice models and SDK for the web: keep the user's voice, detect speech and wake words. No server, no key.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"voice",
|
|
7
7
|
"speech",
|
package/dist/api-63K47HT3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"./chunk-MZOMHWYI.js";import"./chunk-IMUNEOSF.js";import"./chunk-FC4ZSMUX.js";export{a as Alkove,c as Lex,d as Spot,b as Timbre,e as VoiceprintLearner};
|
package/dist/assets-CPGXIA43.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var e='var ee={focus:{name:"alkove-focus-1-preview",file:"alkove-focus-1-preview.alk",bytes:1111696,sha256:"a63cda32e023b8d76089f4c3df0cc2c69ba36017b8f6cdea1da1094ef8022b6a",revision:"8e91ef608366cf503fbd8aaa44bc2000dce899ed"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1-preview",file:"alkove-timbre-1-preview.alk",bytes:739632,sha256:"d498a7dd8b20528d783052b1e1d49e54ab7ee4e47aa12712d04f3d43edc68bd8",revision:"013f7c621e8687e992508b5fb01607eb17143550"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var y=16e3,te=ee,re={chunk:256,print:192,lag:256};var P=n=>`${te[n].name}@${te[n].sha256.slice(0,12)}`,x={model:P("timbre"),window:24e3,min:280,dim:192};var R=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,t){let r=0;for(;r<e.length;){let s=Math.min(this.size-this.fill,e.length-r);this.buf.set(e.subarray(r,r+s),this.fill),this.fill+=s,r+=s,this.fill===this.size&&(this.fill=0,t(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}};var T={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6};var k=re.chunk,ne=["silence","forced","wake"],se=n=>new Uint8Array(n.buffer,n.byteOffset,n.byteLength),C=class{constructor(e,t,r,s={}){this.alk=e;let o={gate:!1,normalize:!0,strength:1,sleep:!0,...s},i={...T,...s.speech},a=(p,m)=>e.x.alk_chain(t.ptr,r.ptr,+o.gate,+o.normalize,+o.sleep,o.strength,i.confidence,i.exitConfidence,i.startSecs,i.stopSecs,p,m),u=s.print?Float32Array.from(s.print):null;this.ptr=u?e.with(se(u),p=>a(p,u.length)):a(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new R(k);mix=new Float32Array(k);focusOut=new Float32Array(k);onFocus=null;onCue=null;get speaking(){return this.alk.x.alk_chain_get(this.ptr,0)===1}get sleeping(){return this.alk.x.alk_chain_get(this.ptr,1)===1}get time(){return this.alk.x.alk_chain_get(this.ptr,2)}get gainDb(){return this.alk.x.alk_chain_get(this.ptr,3)}release(){this.ptr&&this.alk.x.alk_chain_free(this.ptr),this.ptr=0}setPrint(e){let t=this.alk.x;if(!e)t.alk_chain_print(this.ptr,0,0);else{let r=Float32Array.from(e);this.alk.with(se(r),s=>t.alk_chain_print(this.ptr,s,r.length))<0&&this.alk.fail("print")}}setStrength(e){this.alk.x.alk_chain_strength(this.ptr,e)}setEnabled(e){this.alk.x.alk_chain_enabled(this.ptr,+e)}step(e,t){if(this.hops.pending||e.length!==k)throw new RangeError("step() takes whole hops only");return this.hop(e,t)}push(e,t){let r=new Float32Array(Math.floor((this.hops.pending+e.length)/k)*k),s=0;return this.hops.push(e,o=>{r.set(this.hop(o,t),s),s+=k}),r}hop(e,t){let{alk:r,ptr:s}=this,o=r.x;new Float32Array(r.heap,o.alk_chain_hop(s),k).set(e);let i=o.alk_chain_step(s);this.mix.set(new Float32Array(r.heap,i,k));let a=new Float64Array(r.heap,o.alk_chain_events(s),4*o.alk_chain_event_count(s)).slice();for(let u=0;u<a.length;u+=4){let[p,m,l]=[a[u+1],a[u+2],a[u+3]];switch(a[u]){case 0:t({type:"speechstart",start:p});break;case 1:t({type:"speechend",start:p,end:m});break;case 2:t({type:"idle",asleep:p===1,at:m});break;case 3:t({type:"diag",code:"focus.print",level:"info",data:{print:p===1,after:m,why:ne[l]}});break;case 4:t({type:"diag",code:"focus.reset",level:"info",data:{after:p,why:ne[m]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(r.heap,o.alk_chain_focus(s),k)),this.onFocus(this.focusOut,p));break;case 6:this.onCue?.(p,m)}}return this.mix}};var F=class extends Error{constructor(t,r,s){super(r);this.code=t;this.cause=s}name="AlkoveError"};var Ae=new TextEncoder,Me=new TextDecoder;function Fe(n){let e=[],t=[],r=0,s=()=>{e.length&&(t.push(Uint8Array.from(e)),r+=e.length,e.length=0)},o=l=>{s(),t.push(l),r+=l.length},i=l=>e.push(l&255,l>>>8&255,l>>>16&255,l>>>24),a=l=>{let h=Ae.encode(l);i(h.length),o(h)},u=l=>{if(l==null)e.push(0);else if(typeof l=="boolean")e.push(l?2:1);else if(typeof l=="number")e.push(3),o(new Uint8Array(Float64Array.of(l).buffer));else if(typeof l=="string")e.push(4),a(l);else if(l instanceof Uint8Array)e.push(7),i(l.length),o(l.slice());else if(l instanceof Float32Array)e.push(8),i(l.length),o(new Uint8Array(l.slice().buffer));else if(Array.isArray(l)||ArrayBuffer.isView(l)){let h=Array.from(l);e.push(5),i(h.length);for(let f of h)u(f)}else{let h=Object.entries(l).filter(([,f])=>f!==void 0);e.push(6),i(h.length);for(let[f,B]of h)a(f),u(B)}};u(n),s();let p=new Uint8Array(r),m=0;for(let l of t)p.set(l,m),m+=l.length;return p}function Se(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0,r=()=>(t+=4,e.getUint32(t-4,!0)),s=()=>{let i=r();return t+=i,Me.decode(n.subarray(t-i,t))},o=()=>{switch(n[t++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return t+=8,e.getFloat64(t-8,!0);case 4:return s();case 5:return Array.from({length:r()},o);case 6:return Object.fromEntries(Array.from({length:r()},()=>[s(),o()]));case 7:{let i=r();return t+=i,n.slice(t-i,t)}case 8:{let i=r();return t+=4*i,new Float32Array(n.slice(t-4*i,t).buffer)}default:throw new Error("bad value from the core")}};return o()}function b(n,e){let t=Fe(e),r=n.x.alk_value_in(t.length);new Uint8Array(n.heap,r,t.length).set(t)}function d(n,e){let t=Se(new Uint8Array(n.heap,n.x.alk_value_out(),n.x.alk_value_len()).slice());if(e>=0)return t;let r=t;throw r.kind==="TypeError"?new TypeError(r.message):r.kind==="RangeError"?new RangeError(r.message):r.kind==="AlkoveError"?new F(r.code,r.message):new Error(r.message)}var c=n=>{if(!n)throw new Error("used after release");return n},w=(n,e,t)=>n.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=>t(r,e.length)),V=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_lex(t.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,t){return b(this.alk,{texts:e,lang:t}),d(this.alk,this.alk.x.alk_lex_phonemize(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};function ie(n,e,t,r,s){return b(n,{text:t,lang:r,chain:s}),d(n,n.x.alk_compile(e?.handle??0))}var L=class{constructor(e,t,r){this.alk=e;b(e,r),this.ptr=e.x.alk_processor(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:t}=this.alk,r=d(this.alk,e),s=new Float32Array(this.alk.heap,t.alk_processor_audio(c(this.ptr)),t.alk_processor_audio_len(c(this.ptr))).slice(),{start:o,...i}=r;return{start:o,audio:s,...i}}push(e){return this.part(w(this.alk,e,(t,r)=>this.alk.x.alk_processor_push(c(this.ptr),t,r)))}end(){return this.part(this.alk.x.alk_processor_end(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},U=class{constructor(e,t,r,s){this.alk=e;b(e,{words:r,context:s}),this.ptr=e.x.alk_listener(t.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,t){b(this.alk,{words:e,context:t}),d(this.alk,this.alk.x.alk_listener_words(c(this.ptr)))}push(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_listener_push(c(this.ptr),t,r)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},W=class{constructor(e,t,r,s,o){this.alk=e;b(e,{word:r,takes:s,chain:o}),this.ptr=e.x.alk_enroller(t.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_enroller_push(c(this.ptr),t,r)))}result(){return d(this.alk,this.alk.x.alk_enroller_result(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},I=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_timbre(t.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_timbre_windows(c(this.ptr),t,r)))}embed(e,t){return b(this.alk,{source:t}),d(this.alk,w(this.alk,e,(r,s)=>this.alk.x.alk_timbre_embed(c(this.ptr),r,s)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};function oe(n,e){return b(n,e),d(n,n.x.alk_voiceprint())}var z=class{constructor(e,t,r){this.alk=e;b(e,{source:t,start:r}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_learner_learn(c(this.ptr),e.handle,r,s)))}offer(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_learner_offer(c(this.ptr),e.handle,r,s)))}progress(){return d(this.alk,this.state()).progress}ready(){return d(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(c(this.ptr))}voiceprint(e=!1){return d(this.alk,this.alk.x.alk_learner_voiceprint(c(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(c(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},D=class{constructor(e,t,r){this.alk=e;b(e,r),this.ptr=e.x.alk_pipeline(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,t){let{alk:r}=this,s=c(this.ptr);new Float32Array(r.heap,r.x.alk_pipeline_hop(s),256).set(e);let o=r.x.alk_pipeline_step(s,t);return this.out.set(new Float32Array(r.heap,o,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(c(this.ptr),e.ptr)}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(c(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(c(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(c(this.ptr))?d(this.alk,this.alk.x.alk_pipeline_outs(c(this.ptr))):[]}verified(e,t,r){this.alk.x.alk_pipeline_verified(c(this.ptr),e,+t,r)}set(e){b(this.alk,e),d(this.alk,this.alk.x.alk_pipeline_set(c(this.ptr)))}record(e){d(this.alk,this.alk.x.alk_pipeline_record(c(this.ptr),e))}recent(){return d(this.alk,this.alk.x.alk_pipeline_recent(c(this.ptr)))}stats(){return d(this.alk,this.alk.x.alk_pipeline_stats(c(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(c(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(c(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(c(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(c(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(c(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},J=class{constructor(e,t){this.alk=e;b(e,{reference:t}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return b(this.alk,{start:e}),d(this.alk,this.alk.x.alk_coach_learner(c(this.ptr)))}forget(){this.alk.x.alk_coach_forget(c(this.ptr))}window(e,t,r,s){return d(this.alk,w(this.alk,t,(o,i)=>this.alk.x.alk_coach_window(c(this.ptr),e.handle,o,i,r,s)))}verify(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_coach_verify(c(this.ptr),e.handle,r,s)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}};var H=class{constructor(e,t){this.alk=e;this.bytes=t}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let t=this.models.get(e);return t||this.models.set(e,t=this.alk.model(this.bytes(e))),t}stream(e){return this.model(e).session()}chain(e){return new C(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let t=!!e.focus,r={focus:t?this.model("focus"):void 0,cue:t||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0};return new L(this.alk,r,e)}listener(e,t){return new U(this.alk,this.model("spot"),e,t)}enroller(e,t,r){return new W(this.alk,this.model("spot"),e,t,r)}lex(){return this.lexer??=new V(this.alk,this.model("lex"))}timbre(){return this.voices??=new I(this.alk,this.model("timbre"))}learner(e,t){return new z(this.alk,e,t)}pipeline(e){let t=!!e.chain,r=!!e.words?.length||!!e.enroll;return new D(this.alk,{focus:t?this.model("focus"):void 0,cue:t?this.model("cue"):void 0,spot:r?this.model("spot"):void 0},e)}coach(e){return new J(this.alk,e)}voiceprint(e){return oe(this.alk,e)}compile(e,t,r){return ie(this.alk,/^\\s*\\/.+\\/\\s*$/.test(e)?null:this.lex(),e,t,r)}net(e,t){let r=`${e} ${t??""}`,s=this.calls.get(r);s||this.calls.set(r,s=this.model(e).session(t));let o=s;return{run:(i,a)=>o.call(i,a),reset:()=>o.reset()}}release(){this.lexer?.release(),this.voices?.release(),this.lexer=null,this.voices=null;for(let e of this.calls.values())e.release();for(let e of this.models.values())e.release();this.calls.clear(),this.models.clear()}};var ce=["i","y","\\u0268","u","e","\\xF8","\\u0259","o","\\u025B","\\u0153","\\u0254","a","\\u0251","\\xE6","\\u028C","\\u026A","\\u028A","\\u0250","\\u025C","\\u025B\\u0303","\\u0251\\u0303","\\u0254\\u0303","\\u0250\\u0303","\\u1EBD","\\u0129","\\xF5","\\u0169","j","w","\\u0265","p","b","t","d","k","\\u0261","f","v","s","z","\\u0283","\\u0292","m","n","\\u0272","\\u014B","l","\\u028E","\\u0281","\\u027E","r","\\u0279","x","\\u03B8","\\xF0","\\u03B2","\\u0263","h"].map(n=>n.normalize("NFD"));var q=new Map(ce.map((n,e)=>[n,e+1])),ct=q.get("\\u0259"),Oe={"\\u1D7B":"\\u026A",\\u025A:"\\u0259\\u0279",\\u025D:"\\u025C\\u0279",\\u029D:"j",\\u025F:"\\u0261",c:"k",\\u026B:"l",\\u026C:"l",\\u03C7:"x",\\u0266:"h",\\u028B:"v",\\u0271:"m",\\u027B:"\\u0279",\\u0280:"\\u0281",g:"\\u0261",\\u0258:"\\u0259",\\u0275:"\\xF8",\\u028F:"y",\\u026F:"u",\\u0264:"o",q:"k",\\u0255:"\\u0283",\\u0291:"\\u0292",\\u00E7:"\\u0283",\\u0294:"",\\u0252:"\\u0254",\\u0153\\u0303:"\\u025B\\u0303",\\u0278:"f",\\u0299:"b"},Ee={fr:{\\u0251:"a",\\u00E3:"\\u0251\\u0303",\\u00F5:"\\u0254\\u0303",\\u1EBD:"\\u025B\\u0303",\\u0129:"\\u025B\\u0303",\\u0169:"\\u0254\\u0303",\\u0250\\u0303:"\\u0251\\u0303",\\u0250:"a",\\u00E6:"a",\\u028C:"\\u0153",\\u025C:"\\u0153",\\u026A:"i",\\u028A:"u",\\u0279:"\\u0281",r:"\\u0281",\\u027E:"\\u0281",x:"\\u0281",\\u03B8:"s",\\u00F0:"z",h:"",\\u03B2:"b",\\u0263:"\\u0261",\\u028E:"lj",\\u0268:"i"},es:{\\u026A:"i",\\u028A:"u",\\u025B:"e",\\u0254:"o",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0259:"e",\\u0250:"a",\\u0279:"\\u027E"},it:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0250:"a",\\u0279:"r",x:"k",\\u03B8:"t",h:""},pt:{\\u026A:"i",\\u028A:"u",\\u028A\\u0303:"\\u0169",y:"j",\\u00E3:"\\u0250\\u0303",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0279:"\\u027E"},ca:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"\\u0259",\\u0279:"\\u027E",\\u0250:"\\u0259"},ro:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"\\u0259",\\u0279:"r",\\u027E:"r"},en:{\\u0250:"\\u0259",r:"\\u0279",x:"k",\\u025B\\u0303:"\\u0251\\u0303"}},Ne=new Set("\\u02C8\\u02CC\\u02D0\\u02D1\\u203F-.|\\u02B2\\u02B0\\u02B7\' "),Pe=[["e","\\u025B"],["o","\\u0254"],["\\xF8","\\u0153","\\u0259"],["i","j"],["u","w"],["y","\\u0265"],["\\u027E","r"]],ae=ce.map((n,e)=>[e+1]);for(let n of Pe){let e=n.map(t=>q.get(t.normalize("NFD")));for(let t of e)for(let r of e)ae[t-1].includes(r)||ae[t-1].push(r)}var le=new Map;function Re(n){let e=le.get(n);if(!e){let t=Object.entries({...Oe,...Ee[n]??{}}).map(([r,s])=>[r.normalize("NFD"),s.normalize("NFD")]);le.set(n,e=new Map(t))}return e}function ue(n){let e=[];for(let t of n.normalize("NFD")){if(/\\p{M}/u.test(t)){t==="\\u0303"&&e.length&&(e[e.length-1]+=t);continue}e.push(t)}return e}function pe(n,e=""){let t=Re(e),r=[];for(let s of ue(n.replace(/\\([^)]*\\)/g," ").replace(/\u200D/g,"").replace(/\\s+/g," ")))if(!Ne.has(s))for(let o of ue(t.get(s)??s)){o=t.get(o)??o;let i=q.get(o);if(!i)return null;r[r.length-1]!==i&&r.push(i)}return r}var $=class n{constructor(e,t,r,s,o,i,a=[]){this.text=e;this.lang=t;this.phonemes=r;this.thresholds=s;this.calibrated=o;this.chain=i;this.warnings=a}warnings;toJSON(){return{alkove:"word",spot:P("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:e,lang:t,p:r})=>({ipa:e,lang:t,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="word")throw new TypeError("not an Alkove word");if(t.spot!==P("spot"))return null;let r=t.phonemes.map(s=>({...s,ids:pe(s.ipa,s.lang)??[]})).filter(s=>s.ids.length);return new n(t.text,t.lang,r,t.thresholds,t.calibrated,t.chain)}},O=n=>{if(n instanceof $)return n;let e=$.fromJSON(n);if(!e)throw new F("word.outdated",`Compiled for another Spot: compile "${typeof n=="string"?JSON.parse(n).text:n.text}" again.`);return e};var A=class extends Error{},j=class n{constructor(e){this.x=e}static async create(e){let t=await WebAssembly.instantiate(e,{});return new n(t.exports)}get heap(){return this.x.memory.buffer}with(e,t){let r=this.x.alk_alloc(e.length);new Uint8Array(this.heap,r,e.length).set(e);try{return t(r,e.length)}finally{this.x.alk_free(r,e.length)}}fail(e){let r=this.x.alk_alloc(512);try{let s=this.x.alk_error(r,512);throw new A(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,r,s))}`)}finally{this.x.alk_free(r,512)}}model(e){return new G(this,e)}},G=class{constructor(e,t){this.alk=e;let r=e.x;this.ptr=e.with(t,(i,a)=>r.alk_model(i,a)),this.ptr||e.fail("model");let s=r.alk_alloc(256),o=i=>new TextDecoder().decode(new Uint8Array(e.heap,s,i));try{this.plans=Array.from({length:r.alk_plans(this.ptr)},(i,a)=>{let u=m=>Array.from({length:r.alk_io_count(this.ptr,a,m)},(l,h)=>{let f=o(r.alk_io_name(this.ptr,a,m,h,s,256)),B=r.alk_io_shape(this.ptr,a,m,h,s,64),Z=Array.from(new Uint32Array(e.heap,s,B));return{name:f,dims:Z,size:Z.reduce((_e,xe)=>_e*xe,1)}}),p=u(0);return{index:a,name:o(r.alk_plan_name(this.ptr,a,s,256)),inputs:p,outputs:u(1),variable:p[r.alk_variable(this.ptr,a)]?.name??null}})}finally{r.alk_free(s,256)}}ptr;plans;session(e){let t=e===void 0?this.plans[0]:this.plans.find(r=>r.name===e);if(!t)throw new A(`no plan named ${e}`);return new K(this,t)}release(){this.alk.x.alk_model_free(this.ptr)}},K=class{constructor(e,t){this.model=e;this.plan=t;let{alk:r}=e,s=r.x;this.ptr=s.alk_session(e.ptr,t.index),this.ptr||r.fail("session");let o=new TextEncoder;for(let[i,a]of[[t.inputs,s.alk_input],[t.outputs,s.alk_output]])for(let u of i)this.at.set(u.name,{...u,p:r.with(o.encode(u.name),(p,m)=>a(this.ptr,p,m))})}ptr;at=new Map;io(e){let t=this.at.get(e);if(!t)throw new A(`no tensor named ${e}`);return t}f32(e){let t=this.io(e);return new Float32Array(this.model.alk.heap,t.p,t.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,t=this.plan.outputs.map(r=>r.name)){let{alk:r}=this.model,{variable:s}=this.plan;for(let i of this.plan.inputs){let a=e[i.name];if(!a)throw new A(`missing input ${i.name}`);if(i.name===s)r.x.alk_set_len(this.ptr,a.data.length)!==0&&r.fail(i.name);else if(a.data.length!==i.size)throw new A(`${i.name}: ${a.data.length} values for ${i.size}`);this.f32(i.name).set(a.data)}this.run();let o={};for(let i of t)o[i]={data:this.f32(i).slice(),dims:[...this.io(i).dims]};return o}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}};var Te=(n,e)=>{let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t},E=class n{constructor(e,t="focus",r=x.model,s=[]){this.centers=e;this.source=t;this.model=r;this.windows=s;if(!e.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(e){return this.closest(e).score}closest(e){let t=e instanceof n?e.centers:[e],r={score:-1,mine:0,theirs:0};for(let s of this.centers)for(let o of t){let i=Te(s.id,o.id);i>r.score&&(r={score:i,mine:s.seconds,theirs:o.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let e=t=>Array.from(t,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(t=>({embedding:e(t.embedding),id:e(t.id),seconds:+t.seconds.toFixed(1)})),...this.windows.length?{windows:Ce(this.windows)}:{}}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(t.model!==x.model)return null;let r=t.centers.map(s=>({embedding:Float32Array.from(s.embedding),id:Float32Array.from(s.id),seconds:s.seconds}));return new n(r,t.source,t.model,t.windows?Ve(t.windows):[])}static merge(e){return new n(e.flatMap(t=>t.centers),e.every(t=>t.source==="raw")?"raw":"focus")}};function Ce(n){let e=new Uint8Array(n.length*2*(x.dim+4)),t=new DataView(e.buffer),r=0;for(let o of n)for(let i of[o.embedding,o.id]){let a=1e-9;for(let u of i)a=Math.max(a,Math.abs(u));t.setFloat32(r,a/127,!0),r+=4;for(let u of i)t.setInt8(r++,Math.round(u/a*127))}let s="";for(let o of e)s+=String.fromCharCode(o);return btoa(s)}function Ve(n){let e=atob(n),t=Uint8Array.from(e,i=>i.charCodeAt(0)),r=new DataView(t.buffer),s=[],o=0;for(;o+2*(x.dim+4)<=t.length;){let i=[];for(let a=0;a<2;a++){let u=r.getFloat32(o,!0);o+=4;let p=new Float32Array(x.dim);for(let m=0;m<p.length;m++)p[m]=r.getInt8(o++)*u;i.push(p)}s.push({embedding:i[0],id:i[1],seconds:x.window/y})}return s}function he(n,e){let t=n[0]?.length??0,r=n.length,s=t*r*2,o=new Uint8Array(44+s),i=new DataView(o.buffer),a=(p,m)=>[...m].forEach((l,h)=>i.setUint8(p+h,l.charCodeAt(0)));a(0,"RIFF"),i.setUint32(4,36+s,!0),a(8,"WAVE"),a(12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,r,!0),i.setUint32(24,e,!0),i.setUint32(28,e*r*2,!0),i.setUint16(32,r*2,!0),i.setUint16(34,16,!0),a(36,"data"),i.setUint32(40,s,!0);let u=44;for(let p=0;p<t;p++)for(let m=0;m<r;m++){let l=Math.max(-1,Math.min(1,n[m][p]));i.setInt16(u,l<0?l*32768:l*32767,!0),u+=2}return o}function Le(n,e=y){let t=n.focus!==void 0&&n.focus!==!1,r=typeof n.focus=="object"?n.focus:{},s=Ue(r.voiceprint)?.embedding,o=n.spot?.words.map(O)??[];return{focus:t?{print:s?Array.from(s):null,strength:r.strength??1}:null,cue:n.cue===void 0||n.cue===null?null:n.cue!==!1,speech:{...T,...typeof n.cue=="object"?n.cue:{}},normalize:n.normalize??!1,trace:!!n.trace,rate:e,spot:o.length?{words:o.map(i=>i.toJSON()),context:n.spot?.context??"anywhere"}:null}}function Ue(n){return n?n instanceof E?n:E.fromJSON(n):null}var N=class{constructor(e,t={}){this.opts=t;this.core=e.processor(Le(t))}core;closed=!1;push(e){if(this.closed)throw new Error("push after end");return this.core.push(e)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},X=16e3;function me(n,e,t={}){let{onProgress:r,signal:s,...o}=t,i=new N(n,o),a=[];try{for(let h=0;h<e.length;h+=X)s?.throwIfAborted(),a.push(i.push(e.subarray(h,Math.min(e.length,h+X)))),r?.({done:Math.min(e.length,h+X),total:e.length});a.push(i.end())}finally{i.release()}let u=new Float32Array(e.length),p=0;for(let h of a)u.set(h.audio.subarray(0,u.length-p),p),p+=h.audio.length;let m=e,l=a.reduce((h,f)=>({speech:[...h.speech,...f.speech],wakes:[...h.wakes,...f.wakes],diag:[...h.diag,...f.diag],trace:f.trace||h.trace?{focus:[...h.trace?.focus??[],...f.trace?.focus??[]],cue:[...h.trace?.cue??[],...f.trace?.cue??[]],spot:[...h.trace?.spot??[],...f.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:o.focus?u:e,raw:m,...l,toWav(h="audio"){return he(h==="both"?[m,this.audio]:[h==="raw"?m:this.audio],y)}}}function de(n){let e=new Map,t=new Map,r=(s,o,i)=>{let a=s.get(o);if(!a)throw new Error(`${i} ${o} is closed, or its worker was started again`);return a};return{embed:(s,o)=>n().timbre().embed(s,o??"raw"),learnerOpen:(s,o)=>{let i=n().learner("raw",o);return e.set(s,i),{progress:i.progress(),ready:i.ready(),voiceprint:i.voiceprint(!0)}},learnerOffer:(s,o)=>{let i=r(e,s,"learner");return{...i.offer(n().timbre(),o),voiceprint:i.voiceprint(!0)}},learnerForget:s=>(e.get(s)?.forget(),null),learnerClose:s=>(e.get(s)?.release(),e.delete(s),null),phonemize:(s,o)=>n().lex().phonemize(s,o),compile:(s,o)=>n().compile(s,o.lang===void 0?[]:[o.lang].flat(),o.chain).word,process:(s,o,i)=>{let a=me(n(),s,{...o,onProgress:i});return{audio:a.audio,raw:a.raw,speech:a.speech,wakes:a.wakes,diag:a.diag,trace:a.trace}},streamOpen:(s,o)=>(t.set(s,new N(n(),o)),null),streamPush:(s,o)=>r(t,s,"stream").push(o),streamEnd:s=>{let o=r(t,s,"stream");return t.delete(s),o.end()}}}var S=256,Ot=S+2,fe=-1;var ke=new Map,v=null,g=(n,e=[])=>self.postMessage(n,e);async function We(n){v=new H(await j.create(n),e=>{let t=ke.get(e);if(!t)throw new Error(`model ${e} not sent`);return t})}var Ie=100,ze=125,_=new Map;function we(n,e){let t=n.shift;typeof e.start=="number"&&(e.start+=t),typeof e.end=="number"&&(e.end+=t),typeof e.at=="number"&&(e.at+=t);let r=e.data;e.type==="diag"&&typeof r?.start=="number"&&typeof r.end=="number"&&(r.start+=t,r.end+=t),n.events.push(e)}var ye=n=>n.map(e=>O(e).toJSON()),ve=n=>n?{word:O(n.word).toJSON(),takes:n.takes}:null;function De(n,e,t,r){let s=e.pipeline!=="wake"&&e.pipeline!=="enroll",o=v.pipeline({chain:s?e.chain??{}:null,verify:!!(e.verify&&t),learn:!!(e.learn&&t),keepRecent:e.keepRecent??0,trace:!!e.trace,stats:!!e.stats,output:e.output??null,words:ye(e.words??[]),context:e.context??"anywhere",enroll:ve(e.enroll),turn:e.turn??!1,interrupt:e.interrupt??!1}),i={id:n,port:null,closed:!1,timer:setInterval(()=>je(i),Ie),opts:e,p:o,events:[],shift:0,timing:{n:0,sum:0,max:0,slow:0},bg:t,out:r,recordId:null};return t&&e.verify&&t.addEventListener("message",a=>{a.data.type!=="verified"||i.closed||(i.p.verified(a.data.key,a.data.same,a.data.score),Q(i))}),_.set(n,i),i}function be(n,e,t){n.out?n.out.postMessage(e,t):g({...e,kind:e.type,type:"pcm",input:n.id},t)}function Q(n){for(let e of n.p.outs())switch(e[0]){case"event":we(n,e[1]);break;case"window":n.bg?.postMessage({type:"window",pcm:e[1],farQuietMs:e[2],t:e[3]},[e[1].buffer]);break;case"verify":n.bg?.postMessage({type:"verify",key:e[1],pcm:e[2]},[e[2].buffer]);break;case"audio":be(n,{type:"audio",pcm:e[1].buffer},[e[1].buffer]);break;case"utterance":be(n,{type:"utterance",pcm:e[1].buffer,start:e[2]+n.shift,end:e[3]+n.shift,...e[4]&&{level:e[4]}},[e[1].buffer]);break;case"record":g({type:"reply",id:n.recordId,result:e[1]},[e[1].buffer]),n.recordId=null}}function Je(n,e){let t=!v.has("spot")&&n.port;t&&n.port.postMessage({pause:!0});try{return e()}finally{t&&n.port.postMessage({pause:!1})}}function He(n,e,t){let r=new Float32Array(e),s=r.subarray(0,S);if(r[S+1]===fe){n.p.raw(s),Q(n),t.postMessage(e,[e]);return}let o=performance.now(),i=n.p.step(s,r[S]),a=performance.now()-o;r.set(i),t.postMessage(e,[e]),Q(n),$e(n,a)}function $e(n,e){let t=n.timing;if(t.n++,t.sum+=e,t.max=Math.max(t.max,e),e>S/y*1e3&&t.slow++,t.n<ze)return;let r=n.p.chained;we(n,{type:"diag",code:"timing",level:t.slow>t.n/10?"warn":"info",data:{meanMs:+(t.sum/t.n).toFixed(2),maxMs:+t.max.toFixed(1),slow:t.slow,asleep:r&&n.p.sleeping,gainDb:r?+n.p.gainDb.toFixed(1):0}}),n.timing={n:0,sum:0,max:0,slow:0}}function je(n){n.events.length&&(g({type:"events",input:n.id,list:n.events}),n.events=[])}var ge=de(()=>v),M=new Map,Qe=(n,e)=>g({type:"event",input:n,event:e});function Be(n,e,t,r){let s=M.get(n);if(!s)return;let o=performance.now(),i=s.coach.window(v.timbre(),e,t,r),a=Math.round(performance.now()-o);for(let u of i)u[0]==="print"?s.port.postMessage({type:"print",embedding:u[1]}):(u[1].type==="diag"&&(u[1].data.ms=a),Qe(n,u[1]))}function qe({id:n,method:e,args:t,progress:r}){switch(e){case"process":return ge.process(t[0],t[1],r?s=>g({type:"progress",id:n,p:s}):void 0);case"embed":case"learnerOpen":case"learnerOffer":case"learnerForget":case"learnerClose":case"phonemize":case"compile":case"streamOpen":case"streamPush":case"streamEnd":return ge[e](...t);case"learner":{let s=M.get(t[0]);if(!s)throw new Error("no learning port for this input");return{progress:s.coach.learner(t[1]??null)}}case"forget":return M.get(t[0])?.coach.forget(),null;case"record":{let s=_.get(t[0]);if(!s)throw new Error("no input");s.p.record(t[1]),s.recordId=n;return}case"recent":return _.get(t[0])?.p.recent()??null;case"stats":return _.get(t[0])?.p.stats()??null;default:throw new Error(`unknown method ${e}`)}}function Y(n){let e=_.get(n);e&&(e.closed=!0,e.port?.close(),e.bg?.close(),clearInterval(e.timer),e.p.release(),_.delete(n)),M.get(n)?.port.close(),M.get(n)?.coach.release(),M.delete(n)}self.onmessage=async n=>{let e=n.data;try{switch(e.type){case"boot":await We(e.module),g({type:"booted"});break;case"models":for(let[t,r]of Object.entries(e.models))ke.set(t,new Uint8Array(r));g({type:"reply",id:e.id,result:!0});break;case"realtime":{Y(e.input);let t=De(e.input,e.opts,e.bg??null,e.out??null);e.bg&&(e.bg.onmessage=r=>{r.data.type==="print"&&!t.closed&&t.p.set({print:r.data.embedding})}),g({type:"reply",id:e.id,result:!0});break}case"worklet":{let t=_.get(e.input),r=e.port;if(!t)break;t.port=r,r.onmessage=s=>{t.closed||(s.data instanceof ArrayBuffer?He(t,s.data,r):typeof s.data?.clock=="number"&&(t.shift=s.data.clock/y-t.p.time))};break}case"rt-port":{Y(e.input);let t={coach:v.coach(e.ref??null),port:e.port};M.set(e.input,t),t.port.onmessage=r=>{r.data.type==="window"?Be(e.input,r.data.pcm,r.data.farQuietMs,r.data.t):r.data.type==="verify"&&t.port.postMessage({type:"verified",key:r.data.key,...t.coach.verify(v.timbre(),r.data.pcm)})};break}case"set":{let t=_.get(e.input);if(!t)break;let r={};"strength"in e&&(r.strength=e.strength),"enabled"in e&&(r.enabled=e.enabled),"print"in e&&(r.print=e.print),"words"in e&&Object.assign(r,{words:ye(e.words),context:e.context??"anywhere"}),"enroll"in e&&(r.enroll=ve(e.enroll)),"listen"in e&&(r.listen=e.listen),"hold"in e&&(r.hold=e.hold),"words"in e||"enroll"in e&&e.enroll?Je(t,()=>{t.p.spot(v.model("spot")),t.p.set(r)}):t.p.set(r),Q(t);break}case"dispose":Y(e.input);break;case"call":{let t=qe(e);t!==void 0&&g({type:"reply",id:e.id,result:t});break}}}catch(t){let r=String(t?.message??t);e.id!==void 0?g({type:"reply",id:e.id,error:{message:r,code:t?.code}}):g({type:"events",input:e.input,list:[{type:"diag",code:"worker.error",level:"warn",data:{message:r,on:e.type}}]})}};\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-FC4ZSMUX.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var ae={name:"alkove-engine",file:"alkove-engine.wasm",bytes:495093,sha256:"8c8966c15deffd6aa86b34f4f3c614271b90f0de0893facaaa082e695c3ffdf9"};var L="alkove-ai",z={focus:{name:"alkove-focus-1-preview",file:"alkove-focus-1-preview.alk",bytes:1111696,sha256:"a63cda32e023b8d76089f4c3df0cc2c69ba36017b8f6cdea1da1094ef8022b6a",revision:"8e91ef608366cf503fbd8aaa44bc2000dce899ed"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1-preview",file:"alkove-timbre-1-preview.alk",bytes:739632,sha256:"d498a7dd8b20528d783052b1e1d49e54ab7ee4e47aa12712d04f3d43edc68bd8",revision:"013f7c621e8687e992508b5fb01607eb17143550"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var A=16e3,x=z,Me={chunk:256,print:192,lag:256};var U=e=>`${x[e].name}@${x[e].sha256.slice(0,12)}`,y={model:U("timbre"),window:24e3,min:280,dim:192},Le={langs:["fr","en","es","pt","it","ca","ro"],beams:3,bos:59,eos:60,vocab:61,word:33,steps:39};var g=class extends Error{constructor(r,n,o){super(n);this.code=r;this.cause=o}name="AlkoveError"};var H=["i","y","\u0268","u","e","\xF8","\u0259","o","\u025B","\u0153","\u0254","a","\u0251","\xE6","\u028C","\u026A","\u028A","\u0250","\u025C","\u025B\u0303","\u0251\u0303","\u0254\u0303","\u0250\u0303","\u1EBD","\u0129","\xF5","\u0169","j","w","\u0265","p","b","t","d","k","\u0261","f","v","s","z","\u0283","\u0292","m","n","\u0272","\u014B","l","\u028E","\u0281","\u027E","r","\u0279","x","\u03B8","\xF0","\u03B2","\u0263","h"].map(e=>e.normalize("NFD"));var R=new Map(H.map((e,t)=>[e,t+1])),De=R.get("\u0259"),ie={"\u1D7B":"\u026A",\u025A:"\u0259\u0279",\u025D:"\u025C\u0279",\u029D:"j",\u025F:"\u0261",c:"k",\u026B:"l",\u026C:"l",\u03C7:"x",\u0266:"h",\u028B:"v",\u0271:"m",\u027B:"\u0279",\u0280:"\u0281",g:"\u0261",\u0258:"\u0259",\u0275:"\xF8",\u028F:"y",\u026F:"u",\u0264:"o",q:"k",\u0255:"\u0283",\u0291:"\u0292",\u00E7:"\u0283",\u0294:"",\u0252:"\u0254",\u0153\u0303:"\u025B\u0303",\u0278:"f",\u0299:"b"},ce={fr:{\u0251:"a",\u00E3:"\u0251\u0303",\u00F5:"\u0254\u0303",\u1EBD:"\u025B\u0303",\u0129:"\u025B\u0303",\u0169:"\u0254\u0303",\u0250\u0303:"\u0251\u0303",\u0250:"a",\u00E6:"a",\u028C:"\u0153",\u025C:"\u0153",\u026A:"i",\u028A:"u",\u0279:"\u0281",r:"\u0281",\u027E:"\u0281",x:"\u0281",\u03B8:"s",\u00F0:"z",h:"",\u03B2:"b",\u0263:"\u0261",\u028E:"lj",\u0268:"i"},es:{\u026A:"i",\u028A:"u",\u025B:"e",\u0254:"o",\u0251:"a",\u00E6:"a",\u028C:"a",\u0259:"e",\u0250:"a",\u0279:"\u027E"},it:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"a",\u0250:"a",\u0279:"r",x:"k",\u03B8:"t",h:""},pt:{\u026A:"i",\u028A:"u",\u028A\u0303:"\u0169",y:"j",\u00E3:"\u0250\u0303",\u0251:"a",\u00E6:"a",\u028C:"a",\u0279:"\u027E"},ca:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"\u027E",\u0250:"\u0259"},ro:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"r",\u027E:"r"},en:{\u0250:"\u0259",r:"\u0279",x:"k",\u025B\u0303:"\u0251\u0303"}},ue=new Set("\u02C8\u02CC\u02D0\u02D1\u203F-.|\u02B2\u02B0\u02B7' "),de=[["e","\u025B"],["o","\u0254"],["\xF8","\u0153","\u0259"],["i","j"],["u","w"],["y","\u0265"],["\u027E","r"]],B=H.map((e,t)=>[t+1]);for(let e of de){let t=e.map(r=>R.get(r.normalize("NFD")));for(let r of t)for(let n of t)B[r-1].includes(n)||B[r-1].push(n)}var $=new Map;function le(e){let t=$.get(e);if(!t){let r=Object.entries({...ie,...ce[e]??{}}).map(([n,o])=>[n.normalize("NFD"),o.normalize("NFD")]);$.set(e,t=new Map(r))}return t}function j(e){let t=[];for(let r of e.normalize("NFD")){if(/\p{M}/u.test(r)){r==="\u0303"&&t.length&&(t[t.length-1]+=r);continue}t.push(r)}return t}function _(e,t=""){let r=le(t),n=[];for(let o of j(e.replace(/\([^)]*\)/g," ").replace(//g,"").replace(/\s+/g," ")))if(!ue.has(o))for(let a of j(r.get(o)??o)){a=r.get(a)??a;let s=R.get(a);if(!s)return null;n[n.length-1]!==s&&n.push(s)}return n}var O=class e{constructor(t,r,n,o,a,s,i=[]){this.text=t;this.lang=r;this.phonemes=n;this.thresholds=o;this.calibrated=a;this.chain=s;this.warnings=i}warnings;toJSON(){return{alkove:"word",spot:U("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:t,lang:r,p:n})=>({ipa:t,lang:r,p:+n.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(t){let r=typeof t=="string"?JSON.parse(t):t;if(r.alkove!=="word")throw new TypeError("not an Alkove word");if(r.spot!==U("spot"))return null;let n=r.phonemes.map(o=>({...o,ids:_(o.ipa,o.lang)??[]})).filter(o=>o.ids.length);return new e(r.text,r.lang,n,r.thresholds,r.calibrated,r.chain)}},q=e=>{if(e instanceof O)return e;let t=O.fromJSON(e);if(!t)throw new g("word.outdated",`Compiled for another Spot: compile "${typeof e=="string"?JSON.parse(e).text:e.text}" again.`);return t};var fe=.6931471803691238,pe=19082149292705877e-26;var N=new DataView(new ArrayBuffer(8));function I(e){if(e!==e||e<0)return NaN;if(e===0)return-1/0;if(e===1/0)return e;let t=0;e<22250738585072014e-324&&(e*=0x40000000000000,t=-54),N.setFloat64(0,e);let r=N.getUint32(0);t+=(r>>>20)-1023;let n=r&1048575,o=n+614244&1048576;t+=o>>>20,n|=o^1072693248,N.setUint32(0,n);let a=N.getFloat64(0)-1,s=a/(2+a),i=s*s,u=i*i,l=u*(.3999999999940942+u*(.22222198432149784+u*.15313837699209373)),d=i*(.6666666666666735+u*(.2857142874366239+u*(.1818357216161805+u*.14798198605116586))),f=.5*a*a;return t*fe-(f-(s*(f+d+l)+t*pe)-a)}var me=1.5707963267341256,he=6077100506506192e-26,ge=.6366197723675814;function F(e){let t=e*e;return e+e*t*(-.16666666666666632+t*(.00833333333332249+t*(-.0001984126982985795+t*(27557313707070068e-22+t*(-25050760253406863e-24+t*158969099521155e-24)))))}function E(e){let t=e*e,r=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),n=.5*t,o=1-n;return o+(1-o-n+t*r)}function G(e){let t=Math.round(e*ge);return[t&3,e-t*me-t*he]}function je(e){let[t,r]=G(e);return t===0?F(r):t===1?E(r):t===2?-F(r):-E(r)}function He(e){let[t,r]=G(e);return t===0?E(r):t===1?-F(r):t===2?-E(r):F(r)}var be=(e,t)=>{let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r},S=class e{constructor(t,r="focus",n=y.model,o=[]){this.centers=t;this.source=r;this.model=n;this.windows=o;if(!t.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(t){return this.closest(t).score}closest(t){let r=t instanceof e?t.centers:[t],n={score:-1,mine:0,theirs:0};for(let o of this.centers)for(let a of r){let s=be(o.id,a.id);s>n.score&&(n={score:s,mine:o.seconds,theirs:a.seconds})}return n}toArray(){return this.centers[0].id.slice()}toJSON(){let t=r=>Array.from(r,n=>+n.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(r=>({embedding:t(r.embedding),id:t(r.id),seconds:+r.seconds.toFixed(1)})),...this.windows.length?{windows:we(this.windows)}:{}}}static fromJSON(t){let r=typeof t=="string"?JSON.parse(t):t;if(r.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(r.model!==y.model)return null;let n=r.centers.map(o=>({embedding:Float32Array.from(o.embedding),id:Float32Array.from(o.id),seconds:o.seconds}));return new e(n,r.source,r.model,r.windows?ye(r.windows):[])}static merge(t){return new e(t.flatMap(r=>r.centers),t.every(r=>r.source==="raw")?"raw":"focus")}};function we(e){let t=new Uint8Array(e.length*2*(y.dim+4)),r=new DataView(t.buffer),n=0;for(let a of e)for(let s of[a.embedding,a.id]){let i=1e-9;for(let u of s)i=Math.max(i,Math.abs(u));r.setFloat32(n,i/127,!0),n+=4;for(let u of s)r.setInt8(n++,Math.round(u/i*127))}let o="";for(let a of t)o+=String.fromCharCode(a);return btoa(o)}function ye(e){let t=atob(e),r=Uint8Array.from(t,s=>s.charCodeAt(0)),n=new DataView(r.buffer),o=[],a=0;for(;a+2*(y.dim+4)<=r.length;){let s=[];for(let i=0;i<2;i++){let u=n.getFloat32(a,!0);a+=4;let l=new Float32Array(y.dim);for(let d=0;d<l.length;d++)l[d]=n.getInt8(a++)*u;s.push(l)}o.push({embedding:s[0],id:s[1],seconds:y.window/A})}return o}function ve(e,t,r){let n=(c,p)=>{let v=Math.min(Math.max(p,c[0]),c[c.length-1]),m=Math.max(1,c.findIndex(b=>b>=v));return[m-1,m,I(v/c[m-1])/I(c[m]/c[m-1])]},[o,a,s]=n(W.print,r),[i,u,l]=n(W.heard,t),d=W[e],f=c=>d[c][i]+(d[c][u]-d[c][i])*l;return f(o)+(f(a)-f(o))*s}var W={print:[1.5,3,6,12,24],heard:[.6,.9,1.5,3],lenient:[[-.07,-.065,-.05,-.0325],[.0025,.0275,.0825,.1075],[.045,.105,.135,.17],[.07,.1125,.2025,.255],[.0875,.15,.23,.2825]],balanced:[[.1675,.195,.2225,.245],[.2,.2325,.2675,.2925],[.23,.27,.3125,.335],[.2475,.295,.34,.37],[.26,.3125,.36,.3925]],strict:[[.335,.35,.365,.38],[.3475,.365,.385,.405],[.3625,.3825,.4075,.4275],[.3725,.395,.4225,.445],[.38,.405,.4325,.455]]},K=class e{static verify(t,r,{level:n="balanced"}={}){let{score:o,mine:a,theirs:s}=t.closest(r);return{same:o>=ve(n,s,a),score:o}}static identify(t,r,n={}){let o=null;for(let[a,s]of Object.entries(r)){let{same:i,score:u}=e.verify(s,t,n);i&&(!o||u>o.score)&&(o={who:a,score:u})}return o}};var Z="alkove",P="https://cache.alkove.invalid/",xe=30,h={},ee=!1,C=new Set;function Qe(e){ee&&te({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),h={...h,...e}}var Ze=()=>h,et=()=>void(ee=!0);function tt(e){return C.add(e),()=>void C.delete(e)}var X=new Set;function te(e){for(let t of C)t(e);C.size||e.level!=="warn"||X.has(e.code)||(X.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function re(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}var Ae=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",ne=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function Se(e,t){let r=globalThis.location?.href;return new URL(t,new URL(String(e).replace(/\/?$/,"/"),r)).href}function Y(e){if(h.modelBaseUrl)return Se(h.modelBaseUrl,e.file);if(!e.revision)throw new g("models.fetch",`${e.name}: not on Hugging Face in this version, set modelBaseUrl`);return te({code:"models.default-host",level:"warn",message:`${e.name} comes from Hugging Face: each user sends it their IP. Self-host the models in production (modelBaseUrl).`}),`https://huggingface.co/${L}/${e.name}/resolve/${e.revision}/${e.file}`}async function ke(e,t,r=0){let n;try{n=await fetch(e)}catch(d){throw new g("models.fetch",`fetch failed: ${e}`,d)}if(!n.ok||!n.body)throw new g("models.fetch",`HTTP ${n.status}: ${e}`);let o=Number(n.headers.get("content-length"))||r,a=n.body.getReader(),s=[],i=0;for(;;){let{done:d,value:f}=await a.read();if(d)break;s.push(f),i+=f.length,t?.({loaded:i,total:Math.max(o,i)})}let u=new Uint8Array(i),l=0;for(let d of s)u.set(d,l),l+=d.length;return u}async function k(e,t){let r=await re(t);if(r!==e.sha256)throw new g("models.hash",`${e.name}: sha256 ${r}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return t}async function V(e,t,r){return t instanceof ArrayBuffer?k(e,new Uint8Array(t)):t instanceof Uint8Array?k(e,t):k(e,await ke(String(t),r,e.bytes))}async function Ue(e,t){if(!ne())return t();let r;try{r=await caches.open(Z)}catch{return t()}let n=P+e.sha256,o=await r.match(n).catch(()=>{});if(o){let s=new Uint8Array(await o.arrayBuffer());if(await re(s)===e.sha256)return Q(r,e.sha256),s;await r.delete(n).catch(()=>{})}let a=await t();return await r.put(n,new Response(a,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),Q(r,e.sha256),a}async function Q(e,t){try{let r=P+"used.json",n=await(await e.match(r))?.json().catch(()=>null)??{},o=Date.now();n[t]=o;for(let[a,s]of Object.entries(n))o-s>xe*864e5&&(await e.delete(P+a),delete n[a]);await e.put(r,new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}}))}catch{}}async function rt(e){if(h.models?.[D(e)]instanceof ArrayBuffer||h.models?.[D(e)]instanceof Uint8Array)return!0;if(!ne())return!1;try{return!!await(await caches.open(Z)).match(P+e.sha256)}catch{return!1}}var D=e=>Object.entries(x).find(([,t])=>t===e)?.[0]??"engine";async function Oe(e,t,r){let n=h.models?.[D(e)]??r;if(n instanceof ArrayBuffer||n instanceof Uint8Array)return V(e,n);if(Ae()){if(n&&String(n).startsWith("file:")){let{readFile:o}=await import("node:fs/promises");return k(e,new Uint8Array(await o(new URL(String(n)))))}if(h.modelDir){let{readFile:o}=await import("node:fs/promises"),{join:a}=await import("node:path");return k(e,new Uint8Array(await o(a(h.modelDir,e.file))))}return V(e,n??Y(e),t)}return Ue(e,()=>V(e,n??Y(e),t))}function nt(e,t){return Oe(x[e],t)}function oe(e,t){let r=e[0]?.length??0,n=e.length,o=r*n*2,a=new Uint8Array(44+o),s=new DataView(a.buffer),i=(l,d)=>[...d].forEach((f,c)=>s.setUint8(l+c,f.charCodeAt(0)));i(0,"RIFF"),s.setUint32(4,36+o,!0),i(8,"WAVE"),i(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,t,!0),s.setUint32(28,t*n*2,!0),s.setUint16(32,n*2,!0),s.setUint16(34,16,!0),i(36,"data"),s.setUint32(40,o,!0);let u=44;for(let l=0;l<r;l++)for(let d=0;d<n;d++){let f=Math.max(-1,Math.min(1,e[d][l]));s.setInt16(u,f<0?f*32768:f*32767,!0),u+=2}return a}function st(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=a=>String.fromCharCode(...e.subarray(a,a+4));if(r(0)!=="RIFF"||r(8)!=="WAVE")throw new TypeError("audio.format: not a WAV file");let n=12,o=null;for(;n+8<=e.length;){let a=r(n),s=t.getUint32(n+4,!0),i=n+8;if(a==="fmt "){let u=t.getUint16(i,!0);u===65534&&(u=t.getUint16(i+24,!0)),o={format:u,ch:t.getUint16(i+2,!0),rate:t.getUint32(i+4,!0),bits:t.getUint16(i+14,!0)}}else if(a==="data"&&o){let{format:u,ch:l,rate:d,bits:f}=o,c=f/8,p=Math.floor(Math.min(s,e.length-i)/(c*l)),v=new Float32Array(p);for(let m=0;m<p;m++){let b=0;for(let M=0;M<l;M++){let w=i+(m*l+M)*c;if(u===3)b+=f===64?t.getFloat64(w,!0):t.getFloat32(w,!0);else if(f===8)b+=(t.getUint8(w)-128)/128;else if(f===16)b+=t.getInt16(w,!0)/32768;else if(f===24)b+=(t.getUint8(w)|t.getUint8(w+1)<<8|t.getInt8(w+2)<<16)/8388608;else if(f===32)b+=t.getInt32(w,!0)/2147483648;else throw new TypeError(`audio.format: ${f}-bit WAV`)}v[m]=b/l}return{pcm:v,rate:d}}n=i+s+(s&1)}throw new TypeError("audio.format: WAV without data")}var se={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6};function Ne(e,t=A){let r=e.focus!==void 0&&e.focus!==!1,n=typeof e.focus=="object"?e.focus:{},o=Fe(n.voiceprint)?.embedding,a=e.spot?.words.map(q)??[];return{focus:r?{print:o?Array.from(o):null,strength:n.strength??1}:null,cue:e.cue===void 0||e.cue===null?null:e.cue!==!1,speech:{...se,...typeof e.cue=="object"?e.cue:{}},normalize:e.normalize??!1,trace:!!e.trace,rate:t,spot:a.length?{words:a.map(s=>s.toJSON()),context:e.spot?.context??"anywhere"}:null}}function Fe(e){return e?e instanceof S?e:S.fromJSON(e):null}var J=class{constructor(t,r={}){this.opts=r;this.core=t.processor(Ne(r))}core;closed=!1;push(t){if(this.closed)throw new Error("push after end");return this.core.push(t)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},T=16e3;function pt(e,t,r={}){let{onProgress:n,signal:o,...a}=r,s=new J(e,a),i=[];try{for(let c=0;c<t.length;c+=T)o?.throwIfAborted(),i.push(s.push(t.subarray(c,Math.min(t.length,c+T)))),n?.({done:Math.min(t.length,c+T),total:t.length});i.push(s.end())}finally{s.release()}let u=new Float32Array(t.length),l=0;for(let c of i)u.set(c.audio.subarray(0,u.length-l),l),l+=c.audio.length;let d=t,f=i.reduce((c,p)=>({speech:[...c.speech,...p.speech],wakes:[...c.wakes,...p.wakes],diag:[...c.diag,...p.diag],trace:p.trace||c.trace?{focus:[...c.trace?.focus??[],...p.trace?.focus??[]],cue:[...c.trace?.cue??[],...p.trace?.cue??[]],spot:[...c.trace?.spot??[],...p.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:a.focus?u:t,raw:d,...f,toWav(c="audio"){return oe(c==="both"?[d,this.audio]:[c==="raw"?d:this.audio],A)}}}export{ae as a,A as b,x as c,Me as d,Le as e,H as f,B as g,_ as h,g as i,O as j,q as k,je as l,He as m,S as n,K as o,Qe as p,Ze as q,et as r,tt as s,te as t,Se as u,rt as v,Oe as w,nt as x,se as y,oe as z,st as A,Fe as B,J as C,pt as D};
|
package/dist/chunk-IMUNEOSF.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{B as f,a as R,b as k,d as N,i as p,j,k as M,l as q,m as I,n as $,q as S,r as z,s as Y,t as T,u as C,w as X,x as Z}from"./chunk-FC4ZSMUX.js";var v=class{handlers=new Map;on(r,e){let t=this.handlers.get(r);return t||this.handlers.set(r,t=new Set),t.add(e),()=>void t.delete(e)}emit(r,e){for(let t of this.handlers.get(r)??[])try{t(e)}catch(s){queueMicrotask(()=>{throw s})}}listens(r){return!!this.handlers.get(r)?.size}clear(){this.handlers.clear()}};var x=class extends v{done;target=null;cancelled=!1;abort=null;constructor(r){super(),this.done=this.run(r),this.done.catch(()=>{})}async run(r){let e=await r.compile();for(let i of e.warnings)this.emit("warning",i);if(this.cancelled)throw new DOMException("cancelled","AbortError");let t=this.target=await r.open(e.toJSON()),s=[t.on("take",i=>this.emit("take",i))];try{let i=await new Promise((c,l)=>{s.push(t.on("enrolled",c)),this.abort=()=>l(new DOMException("cancelled","AbortError"))});if(i.error||!i.word)throw new p("engine.failed",i.error??"enrollment failed");for(let c of i.warnings??[])this.emit("warning",c);let n=i.audio&&i.audio.length>=4e3?await r.embed(i.audio,t.source):null,a=M(i.word);return{word:new j(a.text,a.lang,a.phonemes,a.thresholds,a.calibrated,a.chain,[...e.warnings,...i.warnings??[]]),voiceprint:n}}finally{for(let i of s)i();t.stop()}}cancel(){this.cancelled=!0,this.abort?.(),this.target?.stop()}};var u=24,A=128,O=class o{constructor(r,e,t=!1){this.inRate=r;this.outRate=e;if(this.identity=r===e,t&&(this.t=u),this.identity)return;this.ratio=r/e;let s=this.half,i=.9/Math.max(1,this.ratio),n=new Float32Array((A+1)*u);for(let a=0;a<=A;a++){let d=a/A,c=0;for(let l=0;l<u;l++){let m=l-(s-1)-d,h=i*m,w=h===0?1:q(Math.PI*h)/(Math.PI*h),re=.42+.5*I(Math.PI*m/s)+.08*I(2*Math.PI*m/s);n[a*u+l]=w*re,c+=n[a*u+l]}for(let l=0;l<u;l++)n[a*u+l]/=c}this.table=n}static HALF=u/2;identity;ratio=1;half=u/2;table=new Float32Array(0);work=new Float32Array(0);histLen=u;t=u/2;push(r,e){if(this.identity){for(let d=0;d<r.length;d++)e(r[d]);return}if(this.work.length<u+8+r.length){let d=new Float32Array(u+8+r.length);d.set(this.work.subarray(0,this.histLen)),this.work=d}let t=this.work;t.set(r,this.histLen);let s=this.histLen+r.length,i=s-1-this.half,n=this.t;for(;n<=i;){let d=Math.floor(n),c=Math.round((n-d)*A)*u,l=d-(this.half-1),m=0;for(let h=0;h<u;h++)m+=t[l+h]*this.table[c+h];e(m),n+=this.ratio}let a=Math.floor(n)-(this.half-1);t.copyWithin(0,a,s),this.histLen=s-a,this.t=n-a}static all(r,e,t){if(e===t)return r;let s=new o(e,t,!0),i=Math.round(r.length*t/e),n=new Float32Array(i),a=0,d=c=>{a<i&&(n[a++]=c)};return s.push(r,d),s.push(new Float32Array(Math.ceil(u*s.ratio)+16),d),n}};var L=class{constructor(r){this.worker=r;r.onmessage=e=>{let t=e.data;if(t?.type==="reply"){let s=this.replies.get(t.id);this.replies.delete(t.id),t.error?s?.reject(Object.assign(new Error(t.error.message),{code:t.error.code})):s?.resolve(t.result)}else if(t?.type==="progress")this.replies.get(t.id)?.progress?.(t.p);else for(let s of this.listeners)s(t)},r.onerror=e=>{for(let t of this.replies.values())t.reject(new p("engine.failed",e.message||"worker failed"));this.replies.clear();for(let t of this.listeners)t({type:"crash",message:e.message})}}next=1;replies=new Map;listeners=new Set;listen(r){return this.listeners.add(r),()=>void this.listeners.delete(r)}get busy(){return this.replies.size>0}request(r,e=[],t){let s=this.next++;return new Promise((i,n)=>{this.replies.set(s,{resolve:i,reject:n,progress:t}),this.worker.postMessage({...r,id:s,progress:!!t},e)})}call(r,e,t=[],s){return this.request({type:"call",method:r,args:e},t,s)}post(r,e=[]){this.worker.postMessage(r,e)}},ie=null,oe=()=>ie??=import("./assets-CPGXIA43.js");async function _(o){let r=S().assetBaseUrl;if(r)return C(r,`alkove-${o}.js`);let e=await oe();return URL.createObjectURL(new Blob([o==="worker"?e.WORKER:e.WORKLET],{type:"text/javascript"}))}var Q=null;function ne(o){return Q??=(async()=>{let r=S().models?.engine,e=S().assetBaseUrl,t=r??(e?C(e,R.file):new URL("./alkove-engine.wasm",import.meta.url).href),s=await X(R,o,t);return WebAssembly.compile(s)})().catch(r=>{throw Q=null,r})}var g=class o{static current=null;sent={realtime:new Set,background:new Set};links={};holds=0;static get(){return z(),o.current??=new o}link(r){return this.links[r]??=(async()=>{let[e,t]=await Promise.all([ne(),_("worker")]),s=new L(new Worker(t,{type:"module",name:`alkove-${r}`})),i=this.links[r];return s.listen(n=>n.type==="crash"&&this.links[r]===i&&this.drop(r,s)),await new Promise((n,a)=>{let d=s.listen(c=>{c.type==="booted"?(d(),n()):c.type==="crash"&&a(new p("engine.failed",c.message))});s.post({type:"boot",module:e})}),s})().catch(e=>{throw delete this.links[r],e})}drop(r,e){delete this.links[r],this.sent[r].clear(),e.worker.terminate()}hold(){this.holds++;let r=!0;return()=>{r&&this.holds--,r=!1}}async idle(){for(let r of["realtime","background"]){let e=this.links[r],t=e&&await e.catch(()=>null);t&&this.links[r]===e&&(r==="realtime"||!t.busy&&!this.holds)&&this.drop(r,t)}}async models(r,e,t){let s=await this.link(r),i=e.filter(c=>!this.sent[r].has(c));if(!i.length)return s;let n=new Map,a=await Promise.all(i.map(c=>Z(c,l=>{n.set(c,l);let m=0,h=0;for(let w of n.values())m+=w.loaded,h+=w.total;t?.({loaded:m,total:h})}))),d=Object.fromEntries(i.map((c,l)=>[c,a[l].slice().buffer]));await s.request({type:"models",models:d},Object.values(d));for(let c of i)this.sent[r].add(c);return s}static report=T};var ae=5e3,de=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function E(){let o=globalThis,r=!1;try{r=typeof WebAssembly<"u"&&WebAssembly.validate(de)}catch{}return{worklet:typeof o.AudioWorkletNode=="function",simd:r,secure:o.isSecureContext!==!1}}async function Ee(){try{let o=await navigator.permissions.query({name:"microphone"});return o.state==="granted"||o.state==="denied"?o.state:"prompt"}catch{return"prompt"}}var D={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,voiceIsolation:!1,channelCount:1};async function y(o,r,e=!1){if(!E().secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!navigator.mediaDevices?.getUserMedia)throw new p("browser.unsupported","No getUserMedia in this browser.");let t=setTimeout(()=>T({code:"mic.waiting",level:"info",message:"The permission prompt has had no answer for 5 s."}),ae);try{let s=e?{noiseSuppression:!0,autoGainControl:!0}:{},i=navigator.mediaDevices.getUserMedia({audio:{...D,...s,...o?{deviceId:{exact:o}}:{}}});return await(r?Promise.race([i,new Promise((a,d)=>{r.aborted&&d(r.reason),r.addEventListener("abort",()=>{i.then(c=>c.getTracks().forEach(l=>l.stop()),()=>{}),d(r.reason)})})]):i)}catch(s){if(r?.aborted)throw r.reason;let i=s?.name;throw i==="NotAllowedError"||i==="SecurityError"?new p("mic.denied","Microphone permission denied.",s):i==="NotFoundError"||i==="OverconstrainedError"?new p("mic.not-found","No microphone.",s):i==="NotReadableError"||i==="AbortError"?new p("mic.busy","The microphone is used by another app.",s):s}finally{clearTimeout(t)}}function ee(o){let r=o.getSettings();return["noiseSuppression","autoGainControl","voiceIsolation"].filter(e=>r[e]===!0)}var P=class{constructor(r,e){this.opts=r;this.send=e;this.resampler=new O(k,r.rate),this.buf=new Float32Array(Math.round(r.rate*r.chunkMs/1e3))}resampler;buf;fill=0;push(r){this.resampler.push(r,e=>{this.buf[this.fill++]=e,this.fill===this.buf.length&&(this.send(ce(this.buf,this.opts.format)),this.fill=0)})}};function ce(o,r){if(r==="f32")return o.slice().buffer;let e=new Int16Array(o.length);for(let t=0;t<o.length;t++){let s=Math.max(-1,Math.min(1,o[t]));e[t]=s<0?s*32768:s*32767}return e.buffer}var W=5e3,F=6e4,le=1500,pe=30,he=.002,ue=2e3,me=0,V=new WeakMap,B=new Set,te=0,se="This print comes from another Timbre: ignored, learn it again.",b=class extends v{constructor(e){super();this.opts=e;this.running=new Promise(t=>this.markRunning=t)}id=++me;ctx;ownCtx=!1;stream;ownStream=!1;source;node;dest=null;farSource=null;rt=null;bg=null;offs=[];_mode={mode:"raw",reason:"loading"};_status="starting";_latency=0;_voiceprint=null;retryMs=W;retryTimer;started=0;counted=!1;enabled=!0;printed=!1;sender=null;stalled=!1;spotWords=null;running;markRunning;ran=!1;notReady=null;waiting=[];warned=new Set;browserWant=!1;browserHas=!1;browserBusy=Promise.resolve();browserTimer;listening=!0;holding=!1;get disposed(){return this._status==="disposed"}get mode(){return this._mode.mode}get status(){return this._status}get latency(){return this._latency}get voiceprint(){return this._voiceprint}get ready(){return this.ran?Promise.resolve():this.notReady?Promise.reject(this.notReady):new Promise((e,t)=>this.waiting.push([e,t]))}settle(e,t=!1){if(this.ran)return;this.ran=!e,t&&(this.notReady=e);let s=this.waiting;this.waiting=[];for(let[i,n]of s)e?n(e):i()}get track(){return this.stalled?this.stream.getAudioTracks()[0]??null:this.dest?.stream.getAudioTracks()[0]??null}now(){return this.ctx?this.ctx.currentTime-this.started:0}get delay16(){return 0}async open(){te++,this.counted=!0;try{await this.opening()}catch(e){throw this.dispose(),e}}async opening(){this.offs.push(Y(i=>this.diag(i))),this.opts.voiceprint&&!f(this.opts.voiceprint)&&this.diag({code:"voiceprint.reset",level:"warn",message:se});let e=E();if(!e.secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!e.worklet)throw new p("browser.unsupported","No AudioWorklet in this browser (Safari 14.1 or later).");let t=this.opts;t.stream||t.track?this.stream=t.stream??new MediaStream([t.track]):(this.stream=await y(t.deviceId,t.signal),this.ownStream=!0);let s=this.stream.getAudioTracks()[0];if(!s)throw new p("mic.not-found","The stream has no audio track.");if(!this.ownStream){let i=ee(s);i.length&&this.diag({code:"mic.processed",level:"warn",message:`The browser processes the stream before the models (${i.join(", ")}): open it with these off.`,settings:i})}for(let i of B)i.stream.getAudioTracks()[0]?.getSettings().deviceId===s.getSettings().deviceId&&i!==this&&this.diag({code:"mic.twice",level:"warn",message:"Two inputs on the same microphone run everything twice: use call.spot() for words on a call input."});t.audioContext?this.ctx=t.audioContext:(this.ctx=new AudioContext,this.ownCtx=!0),await this.build(),B.add(this),this.watchContext(),this.watchTrack(s),this.ownStream&&t.followDefault!==!1&&!t.deviceId&&this.followDefault(),this.startModels(),this.flushHeld()}async build(){let e=this.ctx,t=V.get(e);t||(t=_("worklet").then(i=>e.audioWorklet.addModule(i)),t.catch(()=>V.delete(e)),V.set(e,t)),await t,this.node=new AudioWorkletNode(e,"alkove",{numberOfInputs:2,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{delay16:this.delay16,tapRaw:this.kind==="agent"}}),this.node.port.onmessage=i=>this.onWorklet(i.data),this.source=e.createMediaStreamSource(this.stream),this.source.connect(this.node,0,0);let s=this.opts.farEnd;s&&s!=="manual"&&(this.farSource=s instanceof MediaStreamTrack?e.createMediaStreamSource(new MediaStream([s])):s,this.farSource.connect(this.node,0,1)),this.connectOutput(),this.started=e.currentTime,await this.resume()}connectOutput(){this.dest=this.ctx.createMediaStreamDestination(),this.node.connect(this.dest)}onWorklet(e){e.type==="overload"?(this.diag({code:"overload",level:"warn",message:"The device is too slow for the models: raw microphone for a while.",queueMs:e.queueMs,sent:e.sent,received:e.received}),this.setMode("raw","overload")):e.type==="retry"?this.setMode(this.activeMode()):e.type==="latency"?this._latency=Math.round(e.ms):e.type==="raw"?this.rawAudio(e.pcm):e.type==="timing"&&(this._latency=e.latencyMs,this.diag({code:"queue",level:"info",...e}))}rawAudio(e){}activeMode(){return this.enabled?this.kind==="wake"?this.reference()?"spot+print":"spot":this.printed?"focus+print":"focus":"raw"}held=[];emit(e,t){this.held?this.held.push([e,t]):this.deliver(e,t)}flushHeld(){setTimeout(()=>{let e=this.held??[];this.held=null;for(let[t,s]of e)this.deliver(t,s)},0)}deliver(e,t){if(super.emit(e,t),e!=="diag")return;let s=t;s.level!=="warn"||this.listens("diag")||this.warned.has(s.code)||(this.warned.add(s.code),console.warn(`alkove: ${s.message??s.code}`,s))}setMode(e,t){this._mode.mode===e&&this._mode.reason===t||(this._mode=t?{mode:e,reason:t}:{mode:e},this.emit("mode",this._mode),this.followRaw())}followRaw(){if(clearTimeout(this.browserTimer),!this.ownStream||this.disposed)return;this._mode.mode==="raw"&&this._mode.reason!=="off"?this.browserWant||(this.browserTimer=setTimeout(()=>this.wantBrowser(!0),ue)):this.wantBrowser(!1)}wantBrowser(e){this.browserWant=e,this.browserBusy=this.browserBusy.then(()=>this.browser())}async browser(){let e=this.browserWant,t=this.stream.getAudioTracks()[0];if(this.disposed||!this.ownStream||e===this.browserHas||!t)return;try{await t.applyConstraints({...D,noiseSuppression:e,autoGainControl:e})}catch{}let s=t.getSettings().noiseSuppression;if(typeof s=="boolean"&&s!==e){if(this.disposed||!this.ownStream)return;let n=t.getSettings().deviceId??this.opts.deviceId;t.stop();try{let a=await y(n,void 0,e);if(this.disposed||!this.ownStream){for(let d of a.getTracks())d.stop();return}await this.setStream(a,!0)}catch{this.onTrackEnded();return}}this.browserHas=e;let i=this.stream.getAudioTracks()[0]?.getSettings().noiseSuppression;this.diag({code:"mic.browser",level:"info",noiseSuppression:e,autoGainControl:e,applied:typeof i=="boolean"?i:null})}setStatus(e){this._status!==e&&(this._status=e,this.emit("status",e))}diag(e){this.emit("diag",e)}async startModels(){if(!this.disposed){if(!E().simd){this.diag({code:"engine.unsupported",level:"warn",message:"No WebAssembly SIMD: raw microphone for this session."}),this.setMode("raw","unsupported"),this.settle(new p("browser.unsupported","No WebAssembly SIMD: the models cannot run in this browser."),!0);return}this.setMode("raw","loading"),this.followRaw();try{let e=g.get(),t=await e.models("realtime",[...this.models(),...this.spotWords?.words.length?["spot"]:[]]),s;if(this.wantsBackground()){let d=await e.models("background",["timbre"]),c=new MessageChannel;d.post({type:"rt-port",input:this.id,port:c.port2,ref:this.reference()?.toJSON()??null},[c.port2]),s=c.port1,this.bg=d,this.offs.push(d.listen(m=>m.input===this.id&&m.type==="event"&&this.onEvent(m.event)));let l=f(this.opts.voiceprint);this.opts.learn&&await d.call("learner",[this.id,l?.toJSON()??null])}if(this.disposed)return;this.rt=t,this.offs.push(t.listen(d=>this.onRealtime(d)));let i=this.appPort(),n=[...s?[s]:[],...i?[i]:[]];i&&(this.portGiven=!0),await t.request({type:"realtime",input:this.id,opts:this.realtimeOptions(),bg:s,out:i},n),(!this.listening||this.holding)&&t.post({type:"set",input:this.id,...!this.listening&&{listen:!1},...this.holding&&{hold:!0}}),this.spotWords?.words.length&&(await e.models("realtime",["spot"]),t.post({type:"set",input:this.id,...this.spotWords})),this.markRunning(),this.settle(null);let a=new MessageChannel;t.post({type:"worklet",input:this.id,port:a.port2},[a.port2]),this.node.port.postMessage({type:"connect",port:a.port1},[a.port1]),this.printed=!!f(this.opts.voiceprint),this.retryMs=W,this.setMode(this.activeMode(),this.enabled?void 0:"off")}catch(e){if(this.disposed)return;this.diag({code:"models.failed",level:"warn",message:`Models not loaded, raw microphone; retry in ${this.retryMs/1e3} s.`,error:String(e?.message??e)}),this.setMode("raw","failed"),this.settle(e instanceof p?e:new p("engine.failed",`Models not loaded: ${String(e?.message??e)}`,e)),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,F)}}}portGiven=!1;appPort(){return this.portGiven?void 0:this.opts.output?.port}wantsBackground(){return!!this.opts.learn}reference(){return null}onRealtime(e){if(e.input===this.id)if(e.type==="events"){let t=[];for(let s of e.list)s.type==="trace"?t.push(s):this.onEvent(s);t.length&&this.emit("trace",t)}else e.type==="pcm"?e.kind==="audio"?this.emit("audio",e.pcm):this.emit("utterance",{pcm:e.pcm,start:e.start,end:e.end,...e.level&&{level:e.level}}):e.type==="crash"&&(this.node.port.postMessage({type:"stop"}),this.rt=null,this.diag({code:"engine.crash",level:"warn",message:`The engine stopped: raw microphone; retry in ${this.retryMs/1e3} s.`,error:e.message}),this.setMode("raw","failed"),clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,F))}onEvent(e){switch(e.type){case"speechstart":this.emit("speechstart",{start:e.start});break;case"speechcancel":this.emit("speechcancel",{start:e.start});break;case"speechend":this.emit("speechend",{start:e.start,end:e.end,..."voiceDb"in e&&{level:{voiceDb:e.voiceDb,noiseDb:e.noiseDb,refDb:e.refDb}}});break;case"turn":this.emit("turn",{pause:e.pause,probability:e.probability,hesitation:e.hesitation,at:e.at});break;case"turnend":this.emit("turnend",{start:e.start,end:e.end,probability:e.probability,hesitation:e.hesitation,at:e.at});break;case"interruptstart":this.emit("interruptstart",{start:e.start});break;case"interrupt":this.emit("interrupt",{start:e.start,at:e.at});break;case"interruptcancel":this.emit("interruptcancel",{start:e.start,end:e.end});break;case"wake":this.emit("wake",e);break;case"take":{let{type:t,...s}=e;this.emit("take",s);break}case"enrolled":{let{type:t,...s}=e;this.emit("enrolled",s);break}case"heard":this.emit("heard",{speech:e.speech,scores:e.scores});break;case"learn":this.emit("learn",{progress:e.progress});break;case"voiceprint":{let t=$.fromJSON(e.json);t&&(this._voiceprint=t,this.emit("voiceprint",t));break}case"idle":this.diag({code:"idle",level:"info",asleep:e.asleep,at:e.at});break;case"diag":e.code==="focus.print"&&(this.printed=!!e.data?.print,this._mode.mode!=="raw"&&this.setMode(this.activeMode())),this.diag({code:e.code,level:e.level,...e.data});break}}async setEnabled(e){return this.enabled=e,this.rt?.post({type:"set",input:this.id,enabled:e}),e?this.rt&&this._mode.reason==="off"&&this.setMode(this.activeMode()):this.setMode("raw","off"),e&&!!this.rt}listen(e){this.listening=e,this.rt?.post({type:"set",input:this.id,listen:e})}hold(){this.holding=!0,this.rt?.post({type:"set",input:this.id,hold:!0})}release(){this.holding=!1,this.rt?.post({type:"set",input:this.id,hold:!1})}setStrength(e){this.rt?.post({type:"set",input:this.id,strength:e}),this.opts.strength=e}setVoiceprint(e){let t=f(e);e&&!t&&this.diag({code:"voiceprint.reset",level:"warn",message:"This print comes from another Timbre: ignored, learn it again."}),this.opts.voiceprint=t,this.rt?.post({type:"set",input:this.id,print:t?.embedding??null}),this.opts.learn&&this.bg?.call("learner",[this.id,t?.toJSON()??null])}forgetVoiceprint(){this._voiceprint=null,this.rt?.post({type:"set",input:this.id,print:null}),this.bg?.call("forget",[this.id])}farEndActive(e){this.node?.port.postMessage({type:"far",on:e})}async stats(){return this.rt?this.rt.call("stats",[this.id]):null}async record(e){if(!this.rt)throw new p("engine.failed","The models are not running yet.");let t=await this.rt.call("record",[this.id,e]);return new Blob([t],{type:"audio/wav"})}async recent(){let e=this.rt?await this.rt.call("recent",[this.id]):null;return e?new Blob([e],{type:"audio/wav"}):null}async resume(){try{await Promise.race([this.ctx.resume(),new Promise(e=>setTimeout(e,300))])}catch{}this.setStatus(this.ctx.state==="running"?"running":this.ctx.state==="interrupted"?"interrupted":"blocked")}watchContext(){let e=this.ctx,t=()=>{if(this.disposed)return;let d=e.state;d==="running"?this.setStatus("running"):d==="interrupted"?this.setStatus("interrupted"):d==="suspended"&&e.resume().then(()=>this.setStatus(e.state==="running"?"running":"blocked"),()=>this.setStatus("blocked"))};e.addEventListener("statechange",t),this.offs.push(()=>e.removeEventListener("statechange",t));let s=e.currentTime,i=performance.now(),n=0,a=setInterval(()=>{let d=performance.now(),c=(e.currentTime-s)*1e3,l=d-i;s=e.currentTime,i=d,n=e.state!=="running"||c<.9*l?n||d:0;let h=!!n&&d-n>=le;if(h!==this.stalled){this.stalled=h,this.diag({code:h?"audio.stalled":"audio.resumed",level:h?"warn":"info"});let w=this.track;w&&(this.sender?this.sender.replaceTrack(w):this.emit("trackchange",w))}},500);this.offs.push(()=>clearInterval(a))}bind(e){this.sender=e;let t=this.track;t&&e.track!==t&&e.replaceTrack(t)}watchTrack(e){let t=()=>void this.onTrackEnded(),s=()=>this.emit("mic",{state:"muted"}),i=()=>this.emit("mic",{state:"unmuted"});e.addEventListener("ended",t),e.addEventListener("mute",s),e.addEventListener("unmute",i),this.offs.push(()=>{e.removeEventListener("ended",t),e.removeEventListener("mute",s),e.removeEventListener("unmute",i)})}reopenMs=W;async onTrackEnded(){if(!this.disposed&&(this.emit("mic",{state:"lost"}),!!this.ownStream))try{let e=this.browserWant;await this.setStream(await y(this.opts.deviceId,void 0,e),!0),this.browserHas=e,this.reopenMs=W,this.emit("mic",{state:"reopened"})}catch(e){if(e.code==="mic.denied"){this.emit("mic",{state:"denied"});return}setTimeout(()=>void this.onTrackEnded(),this.reopenMs),this.reopenMs=Math.min(2*this.reopenMs,F)}}async setStream(e,t=!1){if(this.ownStream)for(let i of this.stream.getTracks())i!==e.getAudioTracks()[0]&&i.stop();this.source.disconnect(),this.stream=e,this.ownStream=t,this.source=this.ctx.createMediaStreamSource(e),this.source.connect(this.node,0,0);let s=e.getAudioTracks()[0];s&&this.watchTrack(s)}async setDevice(e){this.opts.deviceId=e,this.opts.followDefault=!1;let t=this.browserWant;await this.setStream(await y(e,void 0,t),!0),this.browserHas=t}followDefault(){let e=navigator.mediaDevices;if(!e?.addEventListener)return;let t=this.stream.getAudioTracks()[0]?.getSettings().groupId,s=async()=>{if(this.opts.followDefault===!1||this.disposed)return;let n=(await e.enumerateDevices().catch(()=>[])).find(a=>a.kind==="audioinput"&&a.deviceId==="default");if(n&&n.groupId&&n.groupId!==t){t=n.groupId;let a=this.browserWant;await this.setStream(await y(void 0,void 0,a),!0).then(()=>void(this.browserHas=a)).catch(()=>{}),this.emit("mic",{state:"reopened"})}};e.addEventListener("devicechange",s),this.offs.push(()=>e.removeEventListener("devicechange",s))}async restart({track:e,audioContext:t}={}){let s=this.track;if(t&&t!==this.ctx){if(this.teardownGraph(),this.ownCtx&&this.ctx.close().catch(()=>{}),this.ctx=t,this.ownCtx=!1,e){if(this.ownStream)for(let n of this.stream.getTracks())n.stop();this.stream=new MediaStream([e]),this.ownStream=!1}await this.build(),this.watchContext(),this.rt?.post({type:"dispose",input:this.id}),this.rt=null,this.startModels()}else e&&await this.setStream(new MediaStream([e]));let i=this.track;i&&i!==s&&this.emit("trackchange",i)}teardownGraph(){this.node?.port.postMessage({type:"dispose"});for(let e of[this.source,this.node,this.dest,this.farSource])e?.disconnect()}spot(e,t={}){if(this.kind==="wake")throw new TypeError("spot() reads Focus: use the wake listener itself");return t.onlyMyVoice&&!f(this.opts.voiceprint)&&!this.opts.learn&&this.diag({code:"spot.no-print",level:"warn",message:"onlyMyVoice relies on this input's print: give it a voiceprint (or learn: true), else the closest voice wakes it."}),new H(this,e.map(s=>M(s).toJSON()),t.context??"anywhere")}enrollWord(e,t={}){return new x({compile:async()=>(await import("./api-63K47HT3.js")).Spot.compile(e,{lang:t.lang,chain:"focus"}),open:async s=>{await this.running;let i=await g.get().models("realtime",["spot"]);return i.post({type:"set",input:this.id,enroll:{word:s,takes:t.takes??3}}),{on:this.on.bind(this),stop:()=>i.post({type:"set",input:this.id,enroll:null}),source:"focus"}},embed:async(s,i)=>(await(await import("./api-63K47HT3.js")).Timbre.create()).embed(s,{source:i})})}setWords(e,t){this.spotWords={words:e,context:t},this.rt&&g.get().models("realtime",["spot"]).then(s=>s.post({type:"set",input:this.id,words:e,context:t}))}dispose(){if(!this.disposed){clearTimeout(this.retryTimer),clearTimeout(this.browserTimer),this.setStatus("disposed"),this.settle(new p("engine.failed","The input was disposed before its models ran."),!0),this.counted&&--te===0&&g.get().idle();for(let e of this.offs)e();if(this.offs=[],this.rt?.post({type:"dispose",input:this.id}),this.bg?.post({type:"dispose",input:this.id}),this.teardownGraph(),this.ownStream)for(let e of this.stream.getTracks())e.stop();this.ownCtx&&this.ctx.close().catch(()=>{}),B.delete(this),this.clear()}}},J=class extends b{constructor(e){super(e);this.opts=e}kind="call";osc=null;get track(){return super.track}get delay16(){return N.lag+.1*k}models(){return["focus","cue"]}chainOptions(){let e=f(this.opts.voiceprint);return{gate:!0,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near}}realtimeOptions(){return{pipeline:"call",chain:this.chainOptions(),learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats}}async start(){if(this.opts.learn&&!this.opts.farEnd&&this.diag({code:"learn.no-far-end",level:"warn",message:"learn without farEnd: the other voice may get into the print."}),await this.open(),this.opts.keepAliveWhenHidden!==!1){this.osc=this.ctx.createOscillator(),this.osc.frequency.value=pe;let e=this.ctx.createGain();e.gain.value=he,this.osc.connect(e).connect(this.ctx.destination),this.osc.start(),this.offs.push(()=>this.osc?.stop())}return this}},H=class extends v{constructor(e,t,s){super();this.input=e;e.setWords(t,s),this.off=e.on("wake",i=>this.emit("wake",i))}off;dispose(){this.off(),this.input.setWords([],"anywhere"),this.clear()}};function Ge(o={}){return new J(o).start()}var K=class extends b{constructor(e){super(e);this.opts=e}kind="agent";packer=null;rawAudio(e){this.packer??=new P(this.output(),t=>{let s=this.appPort();s?s.postMessage({type:"audio",pcm:t},[t]):this.opts.output?.port||this.emit("audio",t)}),this.packer.push(e)}output(){let e=this.opts.output??{};return{format:e.format??"f32",rate:e.rate??k,chunkMs:Math.max(16,Math.round((e.chunkMs??32)/16)*16)}}get delay16(){return N.lag}models(){return["focus","cue"]}connectOutput(){if(this.opts.withTrack)return super.connectOutput();let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}realtimeOptions(){let e=f(this.opts.voiceprint);return{pipeline:"agent",chain:{gate:!1,normalize:this.opts.normalize??!0,strength:this.opts.strength??1,print:e?.embedding??null,speech:this.opts.speech,levels:this.opts.levels,near:this.opts.near},learn:!!this.opts.learn,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:this.opts.stats,output:{...this.output(),audio:!0,utterance:!0},turn:this.opts.turn??!0,interrupt:this.opts.interrupt??!0}}async start(){if(this.opts.learn&&!this.opts.farEnd)throw new TypeError("createAgentInput: learn needs farEnd (the agent's voice would teach the print)");if(this.opts.wake)throw new TypeError("createAgentInput: wake is reserved, not in this preview (use createWakeListener)");return await this.open(),this}};function Ue(o={}){return new K(o).start()}var G=class extends b{constructor(e){super(e);this.opts=e;if(this.words=e.words.map(t=>M(t).toJSON()),!this.words.length)throw new TypeError("createWakeListener: no word");for(let t of this.words)t.chain==="focus"&&this.diag({code:"word.chain",level:"warn",message:`"${t.text}" was enrolled behind Focus: its thresholds are off on the raw microphone.`});e.onlyMyVoice&&!this.reference()&&this.diag({code:"voiceprint.reset",level:"warn",message:`onlyMyVoice: ${se}`})}kind="wake";words;models(){return["spot"]}connectOutput(){let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}wantsBackground(){return!!this.reference()}reference(){return f(this.opts.onlyMyVoice)}realtimeOptions(){return{pipeline:"wake",words:this.words,context:this.opts.context??"pause",trace:this.opts.trace,verify:!!this.reference()}}async start(){return await this.open(),this}};function je(o){return new G(o).start()}var U=class extends b{constructor(e,t,s){super(e);this.opts=e;this.word=t;this.takes=s}kind="wake";models(){return["spot"]}connectOutput(){let e=this.ctx.createGain();e.gain.value=0,this.node.connect(e).connect(this.ctx.destination)}realtimeOptions(){return{pipeline:"enroll",enroll:{word:this.word,takes:this.takes}}}async start(){return await this.open(),this}};function qe(o,r,e){return new U(o,r,e).start()}export{x as a,O as b,g as c,E as d,Ee as e,Ge as f,Ue as g,je as h,qe as i};
|
package/dist/chunk-MZOMHWYI.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as R,b as m,c as A,d as V,e as W,i as M}from"./chunk-IMUNEOSF.js";import{A as T,a as C,b as d,c as N,e as F,f as S,g as x,h,i as b,k as P,n as y,o as v,p as B,s as L,v as E,z as I}from"./chunk-FC4ZSMUX.js";var c=class{static langs=F.langs;static inventory=S.map(r=>r.normalize("NFC"));static distance(r,t){let n=typeof r=="string"?h(r.replace(/^\/|\/$/g,""))??[]:r,o=typeof t=="string"?h(t.replace(/^\/|\/$/g,""))??[]:t;if(!n.length||!o.length)return n.length===o.length?0:1;let a=Array.from({length:o.length+1},(s,l)=>l);for(let s=1;s<=n.length;s++){let l=[s];for(let i=1;i<=o.length;i++){let f=n[s-1]===o[i-1]?0:x[n[s-1]-1].includes(o[i-1])?.5:1;l.push(Math.min(a[i]+1,l[i-1]+1,a[i-1]+f))}a=l}return a[o.length]/Math.max(n.length,o.length)}};var D=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",H=0,q=null;async function u(e,r){if(D()){let n=await(q??=import("./node-VEIFZSW6.js").then(o=>new o.NodeBackend));return await n.ready(e),{call:async(o,a,s,l)=>n.calls[o](...a,l),hold:()=>()=>{}}}let t=A.get();return await t.models("background",e,r),{call:async(n,o,a=[],s)=>(await t.models("background",e)).call(n,o,a,s),hold:()=>t.hold()}}function U(e,r={}){let t=e==="wake"?["spot"]:["focus","cue"];return r.voiceprint&&t.push("timbre"),r.typedWords&&t.push("lex"),t}async function K(e){if("pcm"in e&&"rate"in e)return m.all(e.pcm,e.rate,d);if(typeof AudioBuffer<"u"&&e instanceof AudioBuffer)return m.all(j(e),e.sampleRate,d);let r=typeof Blob<"u"&&e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e);if(String.fromCharCode(...r.subarray(0,4))==="RIFF"){let{pcm:o,rate:a}=T(r);return m.all(o,a,d)}if(typeof OfflineAudioContext>"u")throw new b("browser.unsupported","Outside a browser only WAV is decoded: decode the file and pass { pcm, rate }.");let n=await new OfflineAudioContext(1,1,44100).decodeAudioData(r.slice().buffer);return m.all(j(n),n.sampleRate,d)}function j(e){if(e.numberOfChannels===1)return e.getChannelData(0).slice();let r=new Float32Array(e.length);for(let t=0;t<e.numberOfChannels;t++){let n=e.getChannelData(t);for(let o=0;o<r.length;o++)r[o]+=n[o]/e.numberOfChannels}return r}var we={configure:B,stream:Q,supported:V,micPermission:W,onDiag:L,async preload(e,r={}){let t=U(e,r);if(D()){await u(t);return}let n=A.get(),o=t.filter(i=>i!=="timbre"&&i!=="lex"),a=t.filter(i=>i==="timbre"||i==="lex"),s=[{loaded:0,total:0},{loaded:0,total:0}],l=i=>f=>{s[i]=f,r.onProgress?.({loaded:s[0].loaded+s[1].loaded,total:s[0].total+s[1].total})};await Promise.all([n.models("realtime",o,l(0)),a.length?n.models("background",a,l(1)):null])},async cached(e,r={}){let t=[C,...U(e,r).map(n=>N[n])];return(await Promise.all(t.map(E))).every(Boolean)},async process(e,r={}){let t=await K(e);r.signal?.throwIfAborted();let o=await(await u(G(r))).call("process",[t,_(r)],[],r.onProgress);return{...o,toWav(a="audio"){return I(a==="both"?[o.raw,o.audio]:[a==="raw"?o.raw:o.audio],d)}}}};function G(e){let r=[];return e.focus?r.push("focus","cue"):e.cue&&r.push("cue"),e.spot?.words.length&&r.push("spot"),r}function _(e){let{onProgress:r,signal:t,...n}=e;return{...n,focus:typeof e.focus=="object"?{...e.focus,voiceprint:e.focus.voiceprint instanceof y?e.focus.voiceprint.toJSON():e.focus.voiceprint}:e.focus,spot:e.spot?{...e.spot,words:e.spot.words.map(o=>P(o).toJSON())}:void 0}}async function*Q(e,r={}){let t=await u(G(r)),n=++H,o=t.hold();await t.call("streamOpen",[n,_(r)]).catch(p=>{throw o(),p});let a=r.rate??d,s=new m(a,d,!0),l=0,i=0,f=Symbol.asyncIterator in e?e:Y(e);try{for await(let g of f){r.signal?.throwIfAborted();let w=[];l+=g.length,s.push(g,X=>w.push(X)),i+=w.length,w.length&&(yield await t.call("streamPush",[n,Float32Array.from(w)]))}let p=[],k=Math.round(l*d/a)-i;k>0&&s.push(new Float32Array(m.HALF*2+8),g=>p.length<k&&p.push(g)),p.length&&(yield await t.call("streamPush",[n,Float32Array.from(p)]))}finally{try{yield await t.call("streamEnd",[n])}finally{o()}}}async function*Y(e){let r=e.getReader();try{for(;;){let{done:t,value:n}=await r.read();if(t)return;yield n}}finally{r.releaseLock()}}var O=class e{constructor(r){this.b=r}static async create(){return new e(await u(["timbre"]))}async embed(r,t={}){return y.fromJSON(await this.b.call("embed",[r,t.source??"raw"]))}verify(r,t,n={}){return v.verify(r,t,n)}async identify(r,t,n={}){let o=r instanceof y?r:await this.embed(r);return v.identify(o,t,n)}},z=class e{constructor(r){this.b=r}static inventory=c.inventory;static langs=c.langs;static distance=c.distance;static async create(){return new e(await u(["lex"]))}async phonemize(r,t){if(!c.langs.includes(t))throw new b("lang.unsupported",`No ${t}: ${c.langs.join(", ")} only.`);let o=(await this.b.call("phonemize",[Array.isArray(r)?r:[r],t])).map(a=>a.map(({ipa:s,p:l})=>({ipa:s,p:l})));return Array.isArray(r)?o:o[0]}},Z={async compile(e,r={}){for(let o of[r.lang??[]].flat())if(!c.langs.includes(o))throw new b("lang.unsupported",`No ${o}: ${c.langs.join(", ")} only.`);let t=/^\s*\/.+\/\s*$/.test(e),n=await u(t?[]:["lex"]);return P(await n.call("compile",[e,{lang:r.lang,chain:r.chain}]))},enroll(e,r={}){return new R({compile:()=>Z.compile(e,r),open:async t=>{let n=await M(r,t,r.takes??3);return{on:n.on.bind(n),stop:()=>n.dispose(),source:"raw"}},embed:async(t,n)=>(await O.create()).embed(t,{source:n})})}},J=e=>e?new y(e.centers,e.source,e.model,e.windows):null,ee=e=>({alkove:"voiceprint",model:e.model,source:e.source,centers:e.centers,windows:e.windows}),re=typeof FinalizationRegistry>"u"?null:new FinalizationRegistry(e=>e()),$=class e{constructor(r,t,n,o){this.b=r;this.id=t;this.state={progress:n.progress,ready:n.ready,voiceprint:J(n.voiceprint)},re?.register(this,()=>void r.call("learnerClose",[t]).catch(()=>{}).finally(o))}state;static async create(r={}){let t=await u(["timbre"]),n=++H,o=t.hold();try{let a=await t.call("learnerOpen",[n,r.voiceprint?ee(r.voiceprint):null]);return new e(t,n,a,o)}catch(a){throw o(),a}}get progress(){return this.state.progress}get ready(){return this.state.ready}get voiceprint(){return this.state.voiceprint}async offer(r){let t=await this.b.call("learnerOffer",[this.id,r]);return this.state={progress:t.progress,ready:t.ready,voiceprint:J(t.voiceprint)},{accepted:t.accepted,rejected:t.rejected,progress:t.progress,ready:t.ready}}forget(){this.state={progress:0,ready:!1,voiceprint:null},this.b.call("learnerForget",[this.id])}};export{we as a,O as b,z as c,Z as d,$ as e};
|