@adea-ai/voice 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -2
- package/dist/cli/helpers-cli.d.ts +2 -0
- package/dist/cli/helpers-cli.js +102 -0
- package/dist/contract/contract.d.ts +138 -0
- package/dist/contract/errors.d.ts +26 -0
- package/dist/contract/index.d.ts +9 -0
- package/dist/contract/index.js +54 -0
- package/dist/contract/session.d.ts +58 -0
- package/dist/contract/wire.d.ts +188 -0
- package/dist/desktop/desktop-voice.d.ts +152 -0
- package/dist/desktop/helper-lock.d.ts +83 -0
- package/dist/desktop/helper-process.d.ts +92 -0
- package/dist/desktop/index.d.ts +7 -0
- package/dist/desktop/index.js +1042 -0
- package/dist/index-9kerqn9r.js +150 -0
- package/dist/index-acm1yvvv.js +290 -0
- package/dist/index-r4hz8gk0.js +10 -0
- package/dist/index-rehs788p.js +42 -0
- package/dist/index-s270cw30.js +295 -0
- package/dist/index-tvz9s9nz.js +77 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +86 -0
- package/dist/settings/index.d.ts +5 -0
- package/dist/settings/index.js +34 -0
- package/dist/settings/settings.d.ts +163 -0
- package/dist/web/index.d.ts +15 -0
- package/dist/web/index.js +1287 -0
- package/dist/web/stt/speech-recognition.d.ts +105 -0
- package/dist/web/tts/phonon.d.ts +139 -0
- package/dist/web/tts/player.d.ts +115 -0
- package/dist/web/tts/system-voices.d.ts +122 -0
- package/dist/web/turns.d.ts +101 -0
- package/package.json +68 -4
- package/src/cli/helpers-cli.ts +119 -0
- package/src/contract/contract.ts +365 -0
- package/src/contract/errors.ts +98 -0
- package/src/contract/index.ts +9 -0
- package/src/contract/session.ts +65 -0
- package/src/contract/wire.ts +263 -0
- package/src/desktop/desktop-voice.ts +933 -0
- package/src/desktop/helper-lock.ts +375 -0
- package/src/desktop/helper-process.ts +401 -0
- package/src/desktop/index.ts +16 -0
- package/src/index.ts +7 -0
- package/src/settings/index.ts +5 -0
- package/src/settings/settings.ts +478 -0
- package/src/web/index.ts +15 -0
- package/src/web/stt/speech-recognition.ts +583 -0
- package/src/web/tts/phonon.ts +386 -0
- package/src/web/tts/player.ts +271 -0
- package/src/web/tts/system-voices.ts +401 -0
- package/src/web/turns.ts +224 -0
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser dictation over the Web Speech API, with an explicit local/network policy (issues #21
|
|
3
|
+
* and #37).
|
|
4
|
+
*
|
|
5
|
+
* The browser's recognizer is not automatically offline: Chrome's service-based recognition sends
|
|
6
|
+
* audio to Google, and Safari/Chrome differ per OS version. This module therefore exposes **two
|
|
7
|
+
* providers over one implementation**:
|
|
8
|
+
*
|
|
9
|
+
* - `web.speech-recognition-local` (`execution: "onDevice"`): only available when the browser can
|
|
10
|
+
* run recognition on-device *and* confirms a model for the locale. It is the only entry in the
|
|
11
|
+
* routing chain, so routing never silently reaches the network.
|
|
12
|
+
* - `web.speech-recognition-service` (`execution: "network"`): the host must select it explicitly,
|
|
13
|
+
* with a privacy notice and `allowNetwork: true`. Routing refuses it (`networkRequired`).
|
|
14
|
+
*
|
|
15
|
+
* The session keeps the platform-neutral event contract from #19: `partial` snapshots with
|
|
16
|
+
* `finalizedText`/`volatileText`/`sequence`, exactly one terminal `final`/`failed`/`cancelled`, and
|
|
17
|
+
* deadlines that end a stuck session instead of hanging it.
|
|
18
|
+
*/
|
|
19
|
+
import {
|
|
20
|
+
AVAILABLE,
|
|
21
|
+
VOICE_CONTRACT,
|
|
22
|
+
isAvailable,
|
|
23
|
+
type VoiceProvider,
|
|
24
|
+
type VoiceProviderAvailability,
|
|
25
|
+
type VoiceProviderDescriptor,
|
|
26
|
+
type VoiceUnavailabilityReason,
|
|
27
|
+
unavailable,
|
|
28
|
+
} from "../../contract/contract";
|
|
29
|
+
import { VoiceError, type VoiceErrorCode } from "../../contract/errors";
|
|
30
|
+
|
|
31
|
+
// MARK: - The browser surface we depend on
|
|
32
|
+
|
|
33
|
+
export interface RecognitionAlternative {
|
|
34
|
+
readonly transcript: string;
|
|
35
|
+
readonly confidence?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface RecognitionResult {
|
|
39
|
+
readonly isFinal: boolean;
|
|
40
|
+
readonly length: number;
|
|
41
|
+
readonly [index: number]: RecognitionAlternative;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface RecognitionResultList {
|
|
45
|
+
readonly length: number;
|
|
46
|
+
readonly [index: number]: RecognitionResult;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface SpeechRecognitionEventLike {
|
|
50
|
+
readonly resultIndex: number;
|
|
51
|
+
readonly results: RecognitionResultList;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface SpeechRecognitionErrorEventLike {
|
|
55
|
+
readonly error: string;
|
|
56
|
+
readonly message?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The subset of `SpeechRecognition` this adapter uses. */
|
|
60
|
+
export interface SpeechRecognitionLike {
|
|
61
|
+
lang: string;
|
|
62
|
+
continuous: boolean;
|
|
63
|
+
interimResults: boolean;
|
|
64
|
+
maxAlternatives: number;
|
|
65
|
+
/** Chrome's on-device flag; ignored by browsers that do not implement it. */
|
|
66
|
+
processLocally?: boolean;
|
|
67
|
+
onstart: (() => void) | null;
|
|
68
|
+
onresult: ((event: SpeechRecognitionEventLike) => void) | null;
|
|
69
|
+
onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;
|
|
70
|
+
onend: (() => void) | null;
|
|
71
|
+
start(): void;
|
|
72
|
+
stop(): void;
|
|
73
|
+
abort(): void;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type RecognitionModelState = "available" | "downloadable" | "downloading" | "unavailable";
|
|
77
|
+
|
|
78
|
+
/** Chrome's on-device lifecycle methods, which live on the constructor, not the instance. */
|
|
79
|
+
export interface SpeechRecognitionConstructor {
|
|
80
|
+
new (): SpeechRecognitionLike;
|
|
81
|
+
available?(options: { langs: string[]; processLocally?: boolean }): Promise<RecognitionModelState>;
|
|
82
|
+
install?(options: { langs: string[] }): Promise<boolean>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface SpeechRecognitionEnvironment {
|
|
86
|
+
/** The constructor, or undefined where the browser has no Web Speech API. */
|
|
87
|
+
readonly SpeechRecognition?: SpeechRecognitionConstructor;
|
|
88
|
+
/** Safari's prefixed constructor. Present without the unprefixed name on Safari and older WebKit. */
|
|
89
|
+
readonly webkitSpeechRecognition?: SpeechRecognitionConstructor;
|
|
90
|
+
readonly now?: () => number;
|
|
91
|
+
readonly sleep?: (milliseconds: number) => Promise<void>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The recognizer constructor this browser exposes, unprefixed first. */
|
|
95
|
+
export function recognitionConstructor(
|
|
96
|
+
environment: SpeechRecognitionEnvironment,
|
|
97
|
+
): SpeechRecognitionConstructor | undefined {
|
|
98
|
+
return environment.SpeechRecognition ?? environment.webkitSpeechRecognition;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export {
|
|
102
|
+
DEFAULT_ENDPOINTING,
|
|
103
|
+
type EndpointingOptions,
|
|
104
|
+
type PartialTranscript,
|
|
105
|
+
type SessionEvent,
|
|
106
|
+
type TranscriptionProvider,
|
|
107
|
+
type TranscriptionSession,
|
|
108
|
+
type TranscriptionSessionOptions,
|
|
109
|
+
} from "../../contract/session";
|
|
110
|
+
import {
|
|
111
|
+
DEFAULT_ENDPOINTING,
|
|
112
|
+
type EndpointingOptions,
|
|
113
|
+
type PartialTranscript,
|
|
114
|
+
type SessionEvent,
|
|
115
|
+
type TranscriptionProvider,
|
|
116
|
+
type TranscriptionSession,
|
|
117
|
+
type TranscriptionSessionOptions,
|
|
118
|
+
} from "../../contract/session";
|
|
119
|
+
|
|
120
|
+
// MARK: - Providers
|
|
121
|
+
|
|
122
|
+
const WEB = ["web"] as const;
|
|
123
|
+
|
|
124
|
+
export const LOCAL_RECOGNITION_ID = "web.speech-recognition-local";
|
|
125
|
+
export const SERVICE_RECOGNITION_ID = "web.speech-recognition-service";
|
|
126
|
+
|
|
127
|
+
export function browserRecognitionLocal(environment: SpeechRecognitionEnvironment = globalThis as never): BrowserRecognitionProvider {
|
|
128
|
+
return new BrowserRecognitionProvider("local", environment);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function browserRecognitionService(environment: SpeechRecognitionEnvironment = globalThis as never): BrowserRecognitionProvider {
|
|
132
|
+
return new BrowserRecognitionProvider("service", environment);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The recognizer as a provider. `mode` decides which of the two descriptors it carries; the
|
|
137
|
+
* implementation is the same and the policy difference is the point.
|
|
138
|
+
*/
|
|
139
|
+
export class BrowserRecognitionProvider implements TranscriptionProvider {
|
|
140
|
+
readonly descriptor: VoiceProviderDescriptor;
|
|
141
|
+
private readonly environment: SpeechRecognitionEnvironment;
|
|
142
|
+
private readonly mode: "local" | "service";
|
|
143
|
+
|
|
144
|
+
constructor(mode: "local" | "service", environment: SpeechRecognitionEnvironment) {
|
|
145
|
+
this.mode = mode;
|
|
146
|
+
this.environment = environment;
|
|
147
|
+
this.descriptor = {
|
|
148
|
+
id: mode === "local" ? LOCAL_RECOGNITION_ID : SERVICE_RECOGNITION_ID,
|
|
149
|
+
displayName: mode === "local" ? "Browser dictation (on-device)" : "Browser dictation (browser service)",
|
|
150
|
+
kind: "speechToText",
|
|
151
|
+
platforms: WEB,
|
|
152
|
+
execution: mode === "local" ? "onDevice" : "network",
|
|
153
|
+
contract: VOICE_CONTRACT,
|
|
154
|
+
requiresModelDownload: mode === "local",
|
|
155
|
+
modelFamilies: mode === "local" ? ["browser.on-device-recognition"] : [],
|
|
156
|
+
licenses: [
|
|
157
|
+
{ spdxIdentifier: mode === "local" ? "Browser-On-Device-Recognition" : "Browser-Speech-Service", commercialUse: true },
|
|
158
|
+
],
|
|
159
|
+
capabilities: {
|
|
160
|
+
streamingPartials: true,
|
|
161
|
+
trueCancellation: true,
|
|
162
|
+
modelInstallation: mode === "local",
|
|
163
|
+
localeSelection: true,
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Probes the browser. Prompts for nothing, sends nothing. */
|
|
169
|
+
async availability(locale: string): Promise<VoiceProviderAvailability> {
|
|
170
|
+
const constructor = recognitionConstructor(this.environment);
|
|
171
|
+
if (constructor === undefined) {
|
|
172
|
+
return unavailable("unsupportedPlatform", "this browser has no Web Speech API", {
|
|
173
|
+
kind: "chooseAnotherProvider",
|
|
174
|
+
detail: "use a browser with speech recognition, or the native app",
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
if (this.mode === "service") {
|
|
178
|
+
return AVAILABLE;
|
|
179
|
+
}
|
|
180
|
+
if (constructor.available === undefined) {
|
|
181
|
+
return unavailable(
|
|
182
|
+
"unsupportedDevice",
|
|
183
|
+
"this browser cannot run recognition on-device, so offline dictation is not offered here",
|
|
184
|
+
{ kind: "chooseAnotherProvider", detail: "use a browser with on-device recognition, or dictation with network consent" },
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
const state = await probeOnDevice(constructor, locale);
|
|
188
|
+
switch (state) {
|
|
189
|
+
case "available":
|
|
190
|
+
return AVAILABLE;
|
|
191
|
+
case "downloadable":
|
|
192
|
+
case "downloading":
|
|
193
|
+
return unavailable("modelNotInstalled", `the ${locale} recognition model is not installed on this device`, {
|
|
194
|
+
kind: "installModel",
|
|
195
|
+
detail: `install the ${locale} browser recognition model`,
|
|
196
|
+
});
|
|
197
|
+
case "unavailable":
|
|
198
|
+
return unavailable("unsupportedLocale", `${locale} has no on-device recognition model in this browser`, {
|
|
199
|
+
kind: "switchLocale",
|
|
200
|
+
detail: "choose a language this browser supports on-device",
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Installs the on-device model where the browser exposes an install path (#37 consent step).
|
|
207
|
+
* Downloading is never implied: the host passes `allowDownload: true` only after the person
|
|
208
|
+
* agreed to it (for example `settings.models.allowDownload`), otherwise this refuses.
|
|
209
|
+
*/
|
|
210
|
+
async installModel(locale: string, options: { readonly allowDownload: boolean }): Promise<boolean> {
|
|
211
|
+
if (options?.allowDownload !== true) {
|
|
212
|
+
throw new VoiceError("denied", "installing a recognition model needs the person's explicit download consent");
|
|
213
|
+
}
|
|
214
|
+
const install = recognitionConstructor(this.environment)?.install;
|
|
215
|
+
if (install === undefined) {
|
|
216
|
+
throw new VoiceError("assets_missing", "this browser has no on-device recognition install path");
|
|
217
|
+
}
|
|
218
|
+
return install({ langs: [locale] });
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async createSession(options: TranscriptionSessionOptions): Promise<TranscriptionSession> {
|
|
222
|
+
const availability = await this.availability(options.locale);
|
|
223
|
+
if (!isAvailable(availability)) {
|
|
224
|
+
const reason = availability.unavailable;
|
|
225
|
+
throw new VoiceError(codeFor(reason.reason), reason.message);
|
|
226
|
+
}
|
|
227
|
+
if (this.mode === "service" && !options.allowNetwork) {
|
|
228
|
+
throw new VoiceError(
|
|
229
|
+
"denied",
|
|
230
|
+
"browser service recognition sends audio to the browser vendor; it needs explicit consent",
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
const constructor = recognitionConstructor(this.environment);
|
|
234
|
+
if (constructor === undefined) throw new VoiceError("unavailable");
|
|
235
|
+
const recognition = new constructor();
|
|
236
|
+
recognition.lang = options.locale;
|
|
237
|
+
recognition.continuous = true;
|
|
238
|
+
recognition.interimResults = true;
|
|
239
|
+
recognition.maxAlternatives = 1;
|
|
240
|
+
if (this.mode === "local") recognition.processLocally = true;
|
|
241
|
+
return new WebRecognitionSession(recognition, this.mode === "local" ? "onDevice" : "network", {
|
|
242
|
+
endpointing: options.endpointing ?? DEFAULT_ENDPOINTING,
|
|
243
|
+
now: this.environment.now ?? (() => performance.now()),
|
|
244
|
+
sleep: this.environment.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function probeOnDevice(constructor: SpeechRecognitionConstructor, locale: string): Promise<RecognitionModelState> {
|
|
250
|
+
try {
|
|
251
|
+
return (await constructor.available!({ langs: [locale], processLocally: true })) ?? "unavailable";
|
|
252
|
+
} catch {
|
|
253
|
+
return "unavailable";
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function codeFor(reason: VoiceUnavailabilityReason): VoiceErrorCode {
|
|
258
|
+
switch (reason) {
|
|
259
|
+
case "unsupportedLocale":
|
|
260
|
+
return "language_unsupported";
|
|
261
|
+
case "modelNotInstalled":
|
|
262
|
+
case "modelDownloadDisabled":
|
|
263
|
+
return "assets_missing";
|
|
264
|
+
case "permissionDenied":
|
|
265
|
+
return "denied";
|
|
266
|
+
case "unsupportedDevice":
|
|
267
|
+
case "unsupportedOperatingSystem":
|
|
268
|
+
case "unsupportedPlatform":
|
|
269
|
+
return "unavailable";
|
|
270
|
+
default:
|
|
271
|
+
return "unavailable";
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// MARK: - Session
|
|
276
|
+
|
|
277
|
+
type Terminal = "final" | "failed" | "cancelled";
|
|
278
|
+
|
|
279
|
+
class WebRecognitionSession implements TranscriptionSession {
|
|
280
|
+
readonly execution: "onDevice" | "network";
|
|
281
|
+
private readonly recognition: SpeechRecognitionLike;
|
|
282
|
+
private readonly endpointing: EndpointingOptions;
|
|
283
|
+
private readonly now: () => number;
|
|
284
|
+
private readonly sleep: (milliseconds: number) => Promise<void>;
|
|
285
|
+
|
|
286
|
+
private readonly queue: SessionEvent[] = [];
|
|
287
|
+
private resolved: (() => void) | undefined;
|
|
288
|
+
private finished = false;
|
|
289
|
+
private terminal: Terminal | undefined;
|
|
290
|
+
/** Whether the recognizer was started, or must never be (cancelled/ended before `events()`). */
|
|
291
|
+
private started = false;
|
|
292
|
+
/** `events()` hands out one stream: a second consumer would steal the first one's wake-ups. */
|
|
293
|
+
private iterated = false;
|
|
294
|
+
private resolveTerminal: (() => void) | undefined = undefined;
|
|
295
|
+
private readonly terminalSignal: Promise<void> = new Promise<void>((resolve) => {
|
|
296
|
+
this.resolveTerminal = resolve;
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
private finalizedText = "";
|
|
300
|
+
private volatileText = "";
|
|
301
|
+
private sequence = 0;
|
|
302
|
+
private lastWordAt = 0;
|
|
303
|
+
private words = false;
|
|
304
|
+
private stopRequested = false;
|
|
305
|
+
private endPromise: Promise<void> | undefined;
|
|
306
|
+
|
|
307
|
+
constructor(
|
|
308
|
+
recognition: SpeechRecognitionLike,
|
|
309
|
+
execution: "onDevice" | "network",
|
|
310
|
+
timing: { endpointing: EndpointingOptions; now: () => number; sleep: (ms: number) => Promise<void> },
|
|
311
|
+
) {
|
|
312
|
+
this.recognition = recognition;
|
|
313
|
+
this.execution = execution;
|
|
314
|
+
this.endpointing = timing.endpointing;
|
|
315
|
+
this.now = timing.now;
|
|
316
|
+
this.sleep = timing.sleep;
|
|
317
|
+
|
|
318
|
+
recognition.onstart = () => {
|
|
319
|
+
this.started = true;
|
|
320
|
+
this.lastWordAt = this.now();
|
|
321
|
+
};
|
|
322
|
+
recognition.onresult = (event) => this.onResult(event);
|
|
323
|
+
recognition.onerror = (event) => this.onError(event);
|
|
324
|
+
recognition.onend = () => this.onEnd();
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
events(): AsyncIterable<SessionEvent> {
|
|
328
|
+
if (this.iterated) {
|
|
329
|
+
throw new VoiceError("bad_request", "a transcription session's events() can be consumed only once");
|
|
330
|
+
}
|
|
331
|
+
this.iterated = true;
|
|
332
|
+
if (!this.started && !this.terminal) {
|
|
333
|
+
this.started = true;
|
|
334
|
+
this.lastWordAt = this.now();
|
|
335
|
+
// Endpointing starts with the recognizer, not with the first result: a silent session has
|
|
336
|
+
// to fail with `no_speech` by itself, and the hard cap has to hold when nothing arrives.
|
|
337
|
+
this.startWatching();
|
|
338
|
+
try {
|
|
339
|
+
this.recognition.start();
|
|
340
|
+
} catch (error) {
|
|
341
|
+
this.fail(VoiceError.wrapping(error));
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
let handedOut = false;
|
|
345
|
+
return {
|
|
346
|
+
[Symbol.asyncIterator]: () => {
|
|
347
|
+
if (handedOut) throw new VoiceError("bad_request", "a transcription session's events can be iterated only once");
|
|
348
|
+
handedOut = true;
|
|
349
|
+
return { next: () => this.next() };
|
|
350
|
+
},
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async end(): Promise<void> {
|
|
355
|
+
if (this.endPromise) return this.endPromise;
|
|
356
|
+
this.stopRequested = true;
|
|
357
|
+
if (!this.started) {
|
|
358
|
+
// Ended before `events()` started anything: nothing was heard, and nothing may start later.
|
|
359
|
+
this.started = true;
|
|
360
|
+
this.fail(new VoiceError("no_speech"));
|
|
361
|
+
this.endPromise = Promise.resolve();
|
|
362
|
+
return this.endPromise;
|
|
363
|
+
}
|
|
364
|
+
this.endPromise = this.finishByRequest();
|
|
365
|
+
return this.endPromise;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async cancel(): Promise<void> {
|
|
369
|
+
// A cancelled session never starts the recognizer, even if `events()` is called afterwards.
|
|
370
|
+
this.started = true;
|
|
371
|
+
if (this.terminal) return;
|
|
372
|
+
// `emitTerminal` aborts the recognizer: the microphone (and, in service mode, the upload) stops.
|
|
373
|
+
this.emitTerminal({ type: "cancelled" });
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// MARK: internals
|
|
377
|
+
|
|
378
|
+
private async finishByRequest(): Promise<void> {
|
|
379
|
+
try {
|
|
380
|
+
this.recognition.stop();
|
|
381
|
+
} catch (error) {
|
|
382
|
+
this.fail(VoiceError.wrapping(error));
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
// Wait for the browser's final (it fires `end` after `stop`), but never longer than the
|
|
386
|
+
// finalization deadline: an engine that ignores `stop` still yields the words it collected.
|
|
387
|
+
await Promise.race([
|
|
388
|
+
this.terminalSignal,
|
|
389
|
+
(async () => {
|
|
390
|
+
await this.sleep(this.endpointing.finalizationDeadlineSeconds * 1000);
|
|
391
|
+
if (!this.terminal) this.finishWithCollected();
|
|
392
|
+
})(),
|
|
393
|
+
]);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private onResult(event: SpeechRecognitionEventLike): void {
|
|
397
|
+
if (this.terminal) return;
|
|
398
|
+
let changed = false;
|
|
399
|
+
// Results before `resultIndex` are settled. From it on, finals are appended once and every
|
|
400
|
+
// non-final result is part of the current hypothesis, so the volatile text is all of them.
|
|
401
|
+
const volatile: string[] = [];
|
|
402
|
+
for (let index = event.resultIndex; index < event.results.length; index += 1) {
|
|
403
|
+
const result = event.results[index];
|
|
404
|
+
if (!result) continue;
|
|
405
|
+
const alternative = result[0];
|
|
406
|
+
const transcript = alternative?.transcript ?? "";
|
|
407
|
+
if (result.isFinal) {
|
|
408
|
+
const trimmed = transcript.trim();
|
|
409
|
+
if (trimmed.length > 0) {
|
|
410
|
+
this.finalizedText = joinText(this.finalizedText, trimmed);
|
|
411
|
+
changed = true;
|
|
412
|
+
this.words = true;
|
|
413
|
+
this.lastWordAt = this.now();
|
|
414
|
+
}
|
|
415
|
+
} else {
|
|
416
|
+
volatile.push(transcript);
|
|
417
|
+
if (transcript.trim().length > 0) {
|
|
418
|
+
this.words = true;
|
|
419
|
+
this.lastWordAt = this.now();
|
|
420
|
+
}
|
|
421
|
+
changed = true;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
const volatileText = volatile.reduce(joinText, "");
|
|
425
|
+
if (volatileText !== this.volatileText) changed = true;
|
|
426
|
+
this.volatileText = volatileText;
|
|
427
|
+
if (changed) {
|
|
428
|
+
this.queue.push({
|
|
429
|
+
type: "partial",
|
|
430
|
+
partial: { finalizedText: this.finalizedText, volatileText: this.volatileText, sequence: this.sequence++ },
|
|
431
|
+
});
|
|
432
|
+
this.drain();
|
|
433
|
+
}
|
|
434
|
+
if (this.stopRequested && this.volatileText.length === 0) {
|
|
435
|
+
this.finishWithCollected();
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
private onError(event: SpeechRecognitionErrorEventLike): void {
|
|
440
|
+
if (this.terminal) return;
|
|
441
|
+
const error = mapRecognitionError(event);
|
|
442
|
+
if (error.code === "cancelled") {
|
|
443
|
+
this.emitTerminal({ type: "cancelled" });
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
this.fail(error);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
private onEnd(): void {
|
|
450
|
+
if (this.terminal) return;
|
|
451
|
+
this.finishWithCollected(true);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* The one rule for "the session is over, report what it heard": words make a `final`, no words
|
|
456
|
+
* is `no_speech` — whether the end came from the browser, `end()`, or the finalization deadline.
|
|
457
|
+
*/
|
|
458
|
+
private finishWithCollected(fromEnd = false): void {
|
|
459
|
+
this.emitTerminal(
|
|
460
|
+
this.words ? { type: "final", text: this.text } : { type: "failed", error: new VoiceError("no_speech") },
|
|
461
|
+
fromEnd,
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** Endpointing: silence after words, a silent session, and the hard cap. */
|
|
466
|
+
private startWatching(): void {
|
|
467
|
+
void this.watch();
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
private async watch(): Promise<void> {
|
|
471
|
+
if (this.watchTask) return;
|
|
472
|
+
this.watchTask = (async () => {
|
|
473
|
+
const startedAt = this.now();
|
|
474
|
+
for (;;) {
|
|
475
|
+
if (this.terminal) return;
|
|
476
|
+
await this.sleep(this.endpointing.tickIntervalSeconds * 1000);
|
|
477
|
+
if (this.terminal) return;
|
|
478
|
+
const now = this.now();
|
|
479
|
+
if (this.endpointing.maxDurationSeconds !== null && now - startedAt >= this.endpointing.maxDurationSeconds * 1000) {
|
|
480
|
+
await this.end();
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
if (!this.words && now - startedAt >= this.endpointing.noSpeechTimeoutSeconds * 1000) {
|
|
484
|
+
this.fail(new VoiceError("no_speech"));
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (this.words && now - this.lastWordAt >= this.endpointing.silenceLimitSeconds * 1000) {
|
|
488
|
+
await this.end();
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
})();
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
private watchTask: Promise<void> | undefined;
|
|
496
|
+
|
|
497
|
+
private get text(): string {
|
|
498
|
+
return joinText(this.finalizedText, this.volatileText);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
private fail(error: VoiceError): void {
|
|
502
|
+
this.emitTerminal({ type: "failed", error });
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Records the one terminal event. Unless the browser already ended the session (`onend`), the
|
|
507
|
+
* recognizer is aborted and detached here: a watchdog or deadline that ends the session must
|
|
508
|
+
* also close the microphone, and in service mode stop audio going to the network.
|
|
509
|
+
*/
|
|
510
|
+
private emitTerminal(event: SessionEvent, fromEnd = false): void {
|
|
511
|
+
if (this.terminal) return;
|
|
512
|
+
this.terminal = event.type === "final" ? "final" : event.type === "failed" ? "failed" : "cancelled";
|
|
513
|
+
this.release(fromEnd);
|
|
514
|
+
this.queue.push(event);
|
|
515
|
+
this.finished = true;
|
|
516
|
+
this.drain();
|
|
517
|
+
this.resolveTerminal?.();
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private release(fromEnd: boolean): void {
|
|
521
|
+
const recognition = this.recognition;
|
|
522
|
+
recognition.onstart = null;
|
|
523
|
+
recognition.onresult = null;
|
|
524
|
+
recognition.onerror = null;
|
|
525
|
+
recognition.onend = null;
|
|
526
|
+
if (fromEnd) return;
|
|
527
|
+
try {
|
|
528
|
+
recognition.abort();
|
|
529
|
+
} catch {
|
|
530
|
+
// aborting an already-ended or failed recognizer is not itself a failure
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
private drain(): void {
|
|
535
|
+
const resolve = this.resolved;
|
|
536
|
+
this.resolved = undefined;
|
|
537
|
+
resolve?.();
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
private async next(): Promise<IteratorResult<SessionEvent>> {
|
|
541
|
+
// Single consumer (enforced in `events()`), so one resolver slot is enough.
|
|
542
|
+
for (;;) {
|
|
543
|
+
const event = this.queue.shift();
|
|
544
|
+
if (event) {
|
|
545
|
+
if (this.finished && this.queue.length === 0) this.resolved = undefined;
|
|
546
|
+
return { value: event, done: false };
|
|
547
|
+
}
|
|
548
|
+
if (this.finished) return { value: undefined, done: true };
|
|
549
|
+
await new Promise<void>((resolve) => {
|
|
550
|
+
this.resolved = resolve;
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
function mapRecognitionError(event: SpeechRecognitionErrorEventLike): VoiceError {
|
|
557
|
+
switch (event.error) {
|
|
558
|
+
case "not-allowed":
|
|
559
|
+
case "service-not-allowed":
|
|
560
|
+
return new VoiceError("denied", event.message ?? "microphone or recognition permission was denied");
|
|
561
|
+
case "no-speech":
|
|
562
|
+
return new VoiceError("no_speech");
|
|
563
|
+
case "language-not-supported":
|
|
564
|
+
return new VoiceError("language_unsupported");
|
|
565
|
+
case "audio-capture":
|
|
566
|
+
return new VoiceError("unavailable", "no microphone is available");
|
|
567
|
+
case "network":
|
|
568
|
+
return new VoiceError("failed", "the browser's recognition service could not be reached");
|
|
569
|
+
case "aborted":
|
|
570
|
+
return new VoiceError("cancelled");
|
|
571
|
+
default:
|
|
572
|
+
return new VoiceError("failed", event.message ?? `recognition error: ${event.error}`);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** Joins two transcript pieces with exactly one space between non-empty, trimmed parts. */
|
|
577
|
+
function joinText(left: string, right: string): string {
|
|
578
|
+
const a = left.trim();
|
|
579
|
+
const b = right.trim();
|
|
580
|
+
if (a.length === 0) return b;
|
|
581
|
+
if (b.length === 0) return a;
|
|
582
|
+
return `${a} ${b}`;
|
|
583
|
+
}
|