@adea-ai/voice 0.2.0 → 0.4.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 +86 -1
- package/dist/cli/helpers-cli.js +17 -2
- package/dist/contract/contract.d.ts +21 -2
- package/dist/contract/index.d.ts +1 -0
- package/dist/contract/index.js +12 -2
- package/dist/contract/session.d.ts +13 -0
- package/dist/contract/turns.d.ts +91 -0
- package/dist/contract/wire.d.ts +92 -1
- package/dist/desktop/conversation.d.ts +86 -0
- package/dist/desktop/desktop-voice.d.ts +61 -1
- package/dist/desktop/helper-lock.d.ts +45 -7
- package/dist/desktop/helper-process.d.ts +4 -0
- package/dist/desktop/index.d.ts +2 -0
- package/dist/desktop/index.js +427 -15
- package/dist/desktop/macho-digest.d.ts +9 -0
- package/dist/{index-rehs788p.js → index-7n7epq1a.js} +7 -2
- package/dist/{index-s270cw30.js → index-a7d617zr.js} +1 -1
- package/dist/{index-9kerqn9r.js → index-ght8wwpd.js} +9 -3
- package/dist/{index-acm1yvvv.js → index-m4g2tpeq.js} +258 -26
- package/dist/index.js +13 -3
- package/dist/settings/index.js +1 -1
- package/dist/web/index.d.ts +1 -0
- package/dist/web/index.js +459 -49
- package/dist/web/stt/speech-recognition.d.ts +128 -7
- package/dist/web/tts/locale-match.d.ts +40 -0
- package/dist/web/tts/system-voices.d.ts +44 -4
- package/dist/web/turns.d.ts +15 -25
- package/package.json +1 -1
- package/src/cli/helpers-cli.ts +18 -2
- package/src/contract/contract.ts +32 -4
- package/src/contract/index.ts +1 -0
- package/src/contract/session.ts +14 -2
- package/src/contract/turns.ts +48 -0
- package/src/contract/wire.ts +123 -2
- package/src/desktop/conversation.ts +347 -0
- package/src/desktop/desktop-voice.ts +197 -1
- package/src/desktop/helper-lock.ts +195 -20
- package/src/desktop/helper-process.ts +17 -10
- package/src/desktop/index.ts +2 -0
- package/src/desktop/macho-digest.ts +135 -0
- package/src/web/index.ts +1 -0
- package/src/web/stt/speech-recognition.ts +454 -24
- package/src/web/tts/locale-match.ts +131 -0
- package/src/web/tts/system-voices.ts +144 -35
- package/src/web/turns.ts +22 -11
|
@@ -68,7 +68,10 @@ export interface SpeechRecognitionLike {
|
|
|
68
68
|
onresult: ((event: SpeechRecognitionEventLike) => void) | null;
|
|
69
69
|
onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;
|
|
70
70
|
onend: (() => void) | null;
|
|
71
|
-
|
|
71
|
+
/** The browser heard speech begin. Not every engine fires it; the first words stand in. */
|
|
72
|
+
onspeechstart?: (() => void) | null;
|
|
73
|
+
/** Chrome 137+ accepts an audio track to recognise from (a chosen microphone). */
|
|
74
|
+
start(audioTrack?: MediaStreamTrackLike): void;
|
|
72
75
|
stop(): void;
|
|
73
76
|
abort(): void;
|
|
74
77
|
}
|
|
@@ -82,6 +85,45 @@ export interface SpeechRecognitionConstructor {
|
|
|
82
85
|
install?(options: { langs: string[] }): Promise<boolean>;
|
|
83
86
|
}
|
|
84
87
|
|
|
88
|
+
/** The subset of `PermissionStatus` the microphone pre-check uses. */
|
|
89
|
+
export interface PermissionStatusLike {
|
|
90
|
+
readonly state: "granted" | "denied" | "prompt" | (string & {});
|
|
91
|
+
onchange?: (() => void) | null;
|
|
92
|
+
addEventListener?(type: "change", listener: () => void): void;
|
|
93
|
+
removeEventListener?(type: "change", listener: () => void): void;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The subset of `MediaStreamTrack` a chosen microphone needs. */
|
|
97
|
+
export interface MediaStreamTrackLike {
|
|
98
|
+
readonly kind?: string;
|
|
99
|
+
readonly readyState?: string;
|
|
100
|
+
stop(): void;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface MediaStreamLike {
|
|
104
|
+
getAudioTracks(): MediaStreamTrackLike[];
|
|
105
|
+
getTracks?(): MediaStreamTrackLike[];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The parts of `navigator` dictation reads: permissions, connectivity and microphones. */
|
|
109
|
+
export interface RecognitionNavigatorLike {
|
|
110
|
+
readonly onLine?: boolean;
|
|
111
|
+
readonly permissions?: { query(descriptor: { name: string }): Promise<PermissionStatusLike> };
|
|
112
|
+
readonly mediaDevices?: {
|
|
113
|
+
getUserMedia(constraints: { audio: boolean | { deviceId: { exact: string } } }): Promise<MediaStreamLike>;
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** `window`/`document` as event targets (`offline`, `pagehide`, `visibilitychange`). */
|
|
118
|
+
export interface EventTargetLike {
|
|
119
|
+
addEventListener(type: string, listener: () => void): void;
|
|
120
|
+
removeEventListener(type: string, listener: () => void): void;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface RecognitionDocumentLike extends EventTargetLike {
|
|
124
|
+
readonly visibilityState?: string;
|
|
125
|
+
}
|
|
126
|
+
|
|
85
127
|
export interface SpeechRecognitionEnvironment {
|
|
86
128
|
/** The constructor, or undefined where the browser has no Web Speech API. */
|
|
87
129
|
readonly SpeechRecognition?: SpeechRecognitionConstructor;
|
|
@@ -89,6 +131,67 @@ export interface SpeechRecognitionEnvironment {
|
|
|
89
131
|
readonly webkitSpeechRecognition?: SpeechRecognitionConstructor;
|
|
90
132
|
readonly now?: () => number;
|
|
91
133
|
readonly sleep?: (milliseconds: number) => Promise<void>;
|
|
134
|
+
/** Permissions, `onLine` and `mediaDevices`. Default: the global `navigator`. */
|
|
135
|
+
readonly navigator?: RecognitionNavigatorLike;
|
|
136
|
+
/** For `visibilitychange`. Default: the global `document`. */
|
|
137
|
+
readonly document?: RecognitionDocumentLike;
|
|
138
|
+
/** `window`'s listeners, for `offline` and `pagehide`. Default: the global ones. */
|
|
139
|
+
readonly addEventListener?: (type: string, listener: () => void) => void;
|
|
140
|
+
readonly removeEventListener?: (type: string, listener: () => void) => void;
|
|
141
|
+
/**
|
|
142
|
+
* Whether `start(audioTrack)` is honoured. Browsers that predate it ignore the argument and record
|
|
143
|
+
* the default microphone, so a chosen device would be silently dropped. Default: detected as
|
|
144
|
+
* Chrome's on-device recognizer (`processLocally` on the instance), which shipped after it.
|
|
145
|
+
*/
|
|
146
|
+
readonly recognitionAcceptsAudioTrack?: boolean;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Progress of a browser model install. The browser reports states, not bytes. */
|
|
150
|
+
export interface ModelInstallProgress {
|
|
151
|
+
readonly locale: string;
|
|
152
|
+
readonly phase: "started" | "downloading" | "installed" | "failed" | "cancelled";
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface InstallModelOptions {
|
|
156
|
+
/** The person agreed to the download (for example `allowsModelDownload(settings)`). */
|
|
157
|
+
readonly allowDownload: boolean;
|
|
158
|
+
/** Called on each phase change; `downloading` is observed by polling the browser's state. */
|
|
159
|
+
readonly onProgress?: (progress: ModelInstallProgress) => void;
|
|
160
|
+
/**
|
|
161
|
+
* Stops waiting and rejects with `cancelled`. The browser has no cancel for its own download, so
|
|
162
|
+
* it may finish in the background; the SDK only stops reporting and never claims it installed.
|
|
163
|
+
*/
|
|
164
|
+
readonly signal?: AbortSignal;
|
|
165
|
+
/** How often `downloading` is polled. Default 500 ms. */
|
|
166
|
+
readonly pollIntervalMs?: number;
|
|
167
|
+
/** A settings object; `privacy.offlineOnly` refuses the download whatever `allowDownload` says. */
|
|
168
|
+
readonly settings?: { readonly privacy: { readonly offlineOnly: boolean } };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** What dictation does when the page is hidden (`visibilitychange` to hidden, or `pagehide`). */
|
|
172
|
+
export type HiddenPagePolicy = "finalize" | "cancel" | "ignore";
|
|
173
|
+
|
|
174
|
+
/** Browser-specific session options on top of the shared contract. All optional. */
|
|
175
|
+
export interface WebTranscriptionSessionOptions extends TranscriptionSessionOptions {
|
|
176
|
+
/**
|
|
177
|
+
* A chosen microphone: a `deviceId` the SDK opens (and always stops on every terminal path), or a
|
|
178
|
+
* `track` the host owns (stopped at the end only with `stopOnEnd: true`). Needs a browser that
|
|
179
|
+
* honours `start(audioTrack)`, otherwise the session is refused instead of using another mic.
|
|
180
|
+
*/
|
|
181
|
+
readonly microphone?: { readonly deviceId: string } | { readonly track: MediaStreamTrackLike; readonly stopOnEnd?: boolean };
|
|
182
|
+
/**
|
|
183
|
+
* What to do when the browser ends recognition on its own before `end()` (Chrome on Android
|
|
184
|
+
* ignores `continuous` and stops after one utterance): `finalize` (default) reports the words so
|
|
185
|
+
* far as a clean `final`; `restart` starts the recognizer again inside the same session, so the
|
|
186
|
+
* person can keep talking until endpointing, the hard cap or `end()` finishes it.
|
|
187
|
+
*/
|
|
188
|
+
readonly onEarlyEnd?: "finalize" | "restart";
|
|
189
|
+
/** At most this many restarts per session with `onEarlyEnd: "restart"`. Default 50. */
|
|
190
|
+
readonly maxRestarts?: number;
|
|
191
|
+
/** Default `finalize`: a hidden page ends the session with one terminal event. */
|
|
192
|
+
readonly whenHidden?: HiddenPagePolicy;
|
|
193
|
+
/** A settings object; `privacy.offlineOnly` refuses the service recognizer outright. */
|
|
194
|
+
readonly settings?: { readonly privacy: { readonly offlineOnly: boolean } };
|
|
92
195
|
}
|
|
93
196
|
|
|
94
197
|
/** The recognizer constructor this browser exposes, unprefixed first. */
|
|
@@ -101,6 +204,7 @@ export function recognitionConstructor(
|
|
|
101
204
|
export {
|
|
102
205
|
DEFAULT_ENDPOINTING,
|
|
103
206
|
type EndpointingOptions,
|
|
207
|
+
type RecognitionExecution,
|
|
104
208
|
type PartialTranscript,
|
|
105
209
|
type SessionEvent,
|
|
106
210
|
type TranscriptionProvider,
|
|
@@ -110,6 +214,7 @@ export {
|
|
|
110
214
|
import {
|
|
111
215
|
DEFAULT_ENDPOINTING,
|
|
112
216
|
type EndpointingOptions,
|
|
217
|
+
type RecognitionExecution,
|
|
113
218
|
type PartialTranscript,
|
|
114
219
|
type SessionEvent,
|
|
115
220
|
type TranscriptionProvider,
|
|
@@ -205,20 +310,78 @@ export class BrowserRecognitionProvider implements TranscriptionProvider {
|
|
|
205
310
|
/**
|
|
206
311
|
* Installs the on-device model where the browser exposes an install path (#37 consent step).
|
|
207
312
|
* 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.
|
|
313
|
+
* agreed to it (for example `settings.models.allowDownload`), otherwise this refuses. Resolves
|
|
314
|
+
* with the browser's boolean; `onProgress` and `signal` are optional.
|
|
209
315
|
*/
|
|
210
|
-
async installModel(locale: string, options:
|
|
316
|
+
async installModel(locale: string, options: InstallModelOptions): Promise<boolean> {
|
|
211
317
|
if (options?.allowDownload !== true) {
|
|
212
318
|
throw new VoiceError("denied", "installing a recognition model needs the person's explicit download consent");
|
|
213
319
|
}
|
|
214
|
-
|
|
215
|
-
|
|
320
|
+
if (options.settings?.privacy.offlineOnly === true) {
|
|
321
|
+
throw new VoiceError("denied", "offline-only mode forbids downloading a recognition model");
|
|
322
|
+
}
|
|
323
|
+
const constructor = recognitionConstructor(this.environment);
|
|
324
|
+
const install = constructor?.install;
|
|
325
|
+
if (constructor === undefined || install === undefined) {
|
|
216
326
|
throw new VoiceError("assets_missing", "this browser has no on-device recognition install path");
|
|
217
327
|
}
|
|
218
|
-
|
|
328
|
+
const signal = options.signal;
|
|
329
|
+
if (signal?.aborted) throw new VoiceError("cancelled", "the model install was cancelled before it started");
|
|
330
|
+
const report = (phase: ModelInstallProgress["phase"]) => {
|
|
331
|
+
try {
|
|
332
|
+
options.onProgress?.({ locale, phase });
|
|
333
|
+
} catch {
|
|
334
|
+
// a broken progress listener must not fail the install
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
report("started");
|
|
338
|
+
|
|
339
|
+
let settled = false;
|
|
340
|
+
let onAbort: (() => void) | undefined;
|
|
341
|
+
const aborted = new Promise<never>((_, reject) => {
|
|
342
|
+
onAbort = () => reject(new VoiceError("cancelled", "the model install was cancelled; the browser may finish it in the background"));
|
|
343
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
344
|
+
});
|
|
345
|
+
void this.pollInstall(constructor, locale, options.pollIntervalMs ?? 500, () => settled, () => report("downloading"));
|
|
346
|
+
try {
|
|
347
|
+
const installed = await Promise.race([Promise.resolve(install.call(constructor, { langs: [locale] })), aborted]);
|
|
348
|
+
report(installed ? "installed" : "failed");
|
|
349
|
+
return installed;
|
|
350
|
+
} catch (error) {
|
|
351
|
+
const wrapped = VoiceError.wrapping(error);
|
|
352
|
+
report(wrapped.code === "cancelled" ? "cancelled" : "failed");
|
|
353
|
+
throw error instanceof VoiceError ? error : wrapped;
|
|
354
|
+
} finally {
|
|
355
|
+
settled = true;
|
|
356
|
+
if (onAbort) signal?.removeEventListener("abort", onAbort);
|
|
357
|
+
}
|
|
219
358
|
}
|
|
220
359
|
|
|
221
|
-
|
|
360
|
+
/** Reports `downloading` once the browser says so; the browser exposes no byte counts. */
|
|
361
|
+
private async pollInstall(
|
|
362
|
+
constructor: SpeechRecognitionConstructor,
|
|
363
|
+
locale: string,
|
|
364
|
+
intervalMs: number,
|
|
365
|
+
done: () => boolean,
|
|
366
|
+
downloading: () => void,
|
|
367
|
+
): Promise<void> {
|
|
368
|
+
if (constructor.available === undefined) return;
|
|
369
|
+
const sleep = this.environment.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
|
370
|
+
while (!done()) {
|
|
371
|
+
const state = await probeOnDevice(constructor, locale);
|
|
372
|
+
if (done()) return;
|
|
373
|
+
if (state === "downloading") {
|
|
374
|
+
downloading();
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
await sleep(intervalMs);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
async createSession(options: WebTranscriptionSessionOptions): Promise<TranscriptionSession> {
|
|
382
|
+
if (this.mode === "service" && options.settings?.privacy.offlineOnly === true) {
|
|
383
|
+
throw new VoiceError("denied", "offline-only mode forbids the browser's network recognition service");
|
|
384
|
+
}
|
|
222
385
|
const availability = await this.availability(options.locale);
|
|
223
386
|
if (!isAvailable(availability)) {
|
|
224
387
|
const reason = availability.unavailable;
|
|
@@ -230,6 +393,14 @@ export class BrowserRecognitionProvider implements TranscriptionProvider {
|
|
|
230
393
|
"browser service recognition sends audio to the browser vendor; it needs explicit consent",
|
|
231
394
|
);
|
|
232
395
|
}
|
|
396
|
+
const navigator = this.navigator;
|
|
397
|
+
if (this.mode === "service" && navigator?.onLine === false) {
|
|
398
|
+
throw new VoiceError("unavailable", "the device is offline, so the browser's recognition service cannot be reached");
|
|
399
|
+
}
|
|
400
|
+
const permission = await queryMicrophone(navigator);
|
|
401
|
+
if (permission?.state === "denied") {
|
|
402
|
+
throw new VoiceError("denied", "microphone permission is denied for this site");
|
|
403
|
+
}
|
|
233
404
|
const constructor = recognitionConstructor(this.environment);
|
|
234
405
|
if (constructor === undefined) throw new VoiceError("unavailable");
|
|
235
406
|
const recognition = new constructor();
|
|
@@ -237,13 +408,116 @@ export class BrowserRecognitionProvider implements TranscriptionProvider {
|
|
|
237
408
|
recognition.continuous = true;
|
|
238
409
|
recognition.interimResults = true;
|
|
239
410
|
recognition.maxAlternatives = 1;
|
|
240
|
-
if (this.mode === "local")
|
|
411
|
+
if (this.mode === "local") {
|
|
412
|
+
recognition.processLocally = true;
|
|
413
|
+
// The runtime half of the offline proof: a recognizer that drops the flag would fall back
|
|
414
|
+
// to the service, so the session is refused rather than labelled local.
|
|
415
|
+
if (recognition.processLocally !== true) {
|
|
416
|
+
throw new VoiceError("unavailable", "this browser did not accept on-device recognition, so offline dictation cannot be proven");
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
const audio = await this.openMicrophone(options, recognition);
|
|
241
420
|
return new WebRecognitionSession(recognition, this.mode === "local" ? "onDevice" : "network", {
|
|
242
421
|
endpointing: options.endpointing ?? DEFAULT_ENDPOINTING,
|
|
243
422
|
now: this.environment.now ?? (() => performance.now()),
|
|
244
423
|
sleep: this.environment.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
|
|
424
|
+
audio,
|
|
425
|
+
permission,
|
|
426
|
+
onSpeechStart: options.onSpeechStart,
|
|
427
|
+
onEarlyEnd: options.onEarlyEnd ?? "finalize",
|
|
428
|
+
maxRestarts: options.maxRestarts ?? 50,
|
|
429
|
+
whenHidden: options.whenHidden ?? "finalize",
|
|
430
|
+
document: this.environment.document,
|
|
431
|
+
window: this.window,
|
|
245
432
|
});
|
|
246
433
|
}
|
|
434
|
+
|
|
435
|
+
private get navigator(): RecognitionNavigatorLike | undefined {
|
|
436
|
+
return this.environment.navigator;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
private get window(): EventTargetLike | undefined {
|
|
440
|
+
const add = this.environment.addEventListener;
|
|
441
|
+
const remove = this.environment.removeEventListener;
|
|
442
|
+
if (add && remove) {
|
|
443
|
+
const target = this.environment;
|
|
444
|
+
return { addEventListener: (type, listener) => add.call(target, type, listener), removeEventListener: (type, listener) => remove.call(target, type, listener) };
|
|
445
|
+
}
|
|
446
|
+
return undefined;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** Opens (or adopts) the chosen microphone. Nothing is opened when no device was chosen. */
|
|
450
|
+
private async openMicrophone(
|
|
451
|
+
options: WebTranscriptionSessionOptions,
|
|
452
|
+
recognition: SpeechRecognitionLike,
|
|
453
|
+
): Promise<SessionAudio | undefined> {
|
|
454
|
+
const microphone = options.microphone;
|
|
455
|
+
if (microphone === undefined) return undefined;
|
|
456
|
+
const accepts = this.environment.recognitionAcceptsAudioTrack ?? "processLocally" in recognition;
|
|
457
|
+
if (!accepts) {
|
|
458
|
+
throw new VoiceError("unavailable", "this browser cannot recognise from a chosen microphone, only the default one");
|
|
459
|
+
}
|
|
460
|
+
if ("track" in microphone) {
|
|
461
|
+
return { track: microphone.track, owned: [], stopTrack: microphone.stopOnEnd === true };
|
|
462
|
+
}
|
|
463
|
+
const getUserMedia = this.navigator?.mediaDevices?.getUserMedia;
|
|
464
|
+
if (getUserMedia === undefined) {
|
|
465
|
+
throw new VoiceError("unavailable", "this browser cannot open a chosen microphone");
|
|
466
|
+
}
|
|
467
|
+
let stream: MediaStreamLike;
|
|
468
|
+
try {
|
|
469
|
+
stream = await getUserMedia.call(this.navigator!.mediaDevices, { audio: { deviceId: { exact: microphone.deviceId } } });
|
|
470
|
+
} catch (error) {
|
|
471
|
+
throw mapMediaError(error);
|
|
472
|
+
}
|
|
473
|
+
const tracks = stream.getTracks?.() ?? stream.getAudioTracks();
|
|
474
|
+
const track = stream.getAudioTracks()[0];
|
|
475
|
+
if (track === undefined) {
|
|
476
|
+
for (const owned of tracks) owned.stop();
|
|
477
|
+
throw new VoiceError("unavailable", "the chosen microphone produced no audio track");
|
|
478
|
+
}
|
|
479
|
+
return { track, owned: tracks, stopTrack: true };
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** The audio a session records from, and what it must stop at the end. */
|
|
484
|
+
interface SessionAudio {
|
|
485
|
+
readonly track: MediaStreamTrackLike;
|
|
486
|
+
/** Tracks the SDK opened; always stopped on every terminal path. */
|
|
487
|
+
readonly owned: readonly MediaStreamTrackLike[];
|
|
488
|
+
/** Whether `track` itself is stopped at the end. */
|
|
489
|
+
readonly stopTrack: boolean;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* `navigator.permissions.query({ name: "microphone" })` where it exists. Firefox before 131 and
|
|
494
|
+
* some WebViews throw for the name; that is "unknown", never "denied".
|
|
495
|
+
*/
|
|
496
|
+
async function queryMicrophone(navigator: RecognitionNavigatorLike | undefined): Promise<PermissionStatusLike | undefined> {
|
|
497
|
+
const permissions = navigator?.permissions;
|
|
498
|
+
if (permissions === undefined || typeof permissions.query !== "function") return undefined;
|
|
499
|
+
try {
|
|
500
|
+
return await permissions.query({ name: "microphone" });
|
|
501
|
+
} catch {
|
|
502
|
+
return undefined;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function mapMediaError(error: unknown): VoiceError {
|
|
507
|
+
const name = (error as { name?: string } | undefined)?.name;
|
|
508
|
+
switch (name) {
|
|
509
|
+
case "NotAllowedError":
|
|
510
|
+
case "SecurityError":
|
|
511
|
+
return new VoiceError("denied", "microphone permission was denied");
|
|
512
|
+
case "NotFoundError":
|
|
513
|
+
case "OverconstrainedError":
|
|
514
|
+
return new VoiceError("unavailable", "the chosen microphone is not available");
|
|
515
|
+
case "NotReadableError":
|
|
516
|
+
case "AbortError":
|
|
517
|
+
return new VoiceError("busy", "the chosen microphone is in use or could not be opened");
|
|
518
|
+
default:
|
|
519
|
+
return VoiceError.wrapping(error);
|
|
520
|
+
}
|
|
247
521
|
}
|
|
248
522
|
|
|
249
523
|
async function probeOnDevice(constructor: SpeechRecognitionConstructor, locale: string): Promise<RecognitionModelState> {
|
|
@@ -276,6 +550,22 @@ function codeFor(reason: VoiceUnavailabilityReason): VoiceErrorCode {
|
|
|
276
550
|
|
|
277
551
|
type Terminal = "final" | "failed" | "cancelled";
|
|
278
552
|
|
|
553
|
+
const MAX_IDLE_RESTARTS = 3;
|
|
554
|
+
|
|
555
|
+
interface SessionConfig {
|
|
556
|
+
readonly endpointing: EndpointingOptions;
|
|
557
|
+
readonly now: () => number;
|
|
558
|
+
readonly sleep: (milliseconds: number) => Promise<void>;
|
|
559
|
+
readonly audio: SessionAudio | undefined;
|
|
560
|
+
readonly permission: PermissionStatusLike | undefined;
|
|
561
|
+
readonly onSpeechStart: (() => void) | undefined;
|
|
562
|
+
readonly onEarlyEnd: "finalize" | "restart";
|
|
563
|
+
readonly maxRestarts: number;
|
|
564
|
+
readonly whenHidden: HiddenPagePolicy;
|
|
565
|
+
readonly document: RecognitionDocumentLike | undefined;
|
|
566
|
+
readonly window: EventTargetLike | undefined;
|
|
567
|
+
}
|
|
568
|
+
|
|
279
569
|
class WebRecognitionSession implements TranscriptionSession {
|
|
280
570
|
readonly execution: "onDevice" | "network";
|
|
281
571
|
private readonly recognition: SpeechRecognitionLike;
|
|
@@ -304,16 +594,22 @@ class WebRecognitionSession implements TranscriptionSession {
|
|
|
304
594
|
private stopRequested = false;
|
|
305
595
|
private endPromise: Promise<void> | undefined;
|
|
306
596
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
597
|
+
private readonly config: SessionConfig;
|
|
598
|
+
/** Listeners to remove on the terminal event (permission, offline, page lifecycle). */
|
|
599
|
+
private readonly cleanups: Array<() => void> = [];
|
|
600
|
+
/** Whether this recognizer run reported speech start (reset on restart). */
|
|
601
|
+
private speechSignalled = false;
|
|
602
|
+
private restarts = 0;
|
|
603
|
+
/** Restarts in a row that produced no result: a recognizer that ends at once is not restarted forever. */
|
|
604
|
+
private idleRestarts = 0;
|
|
605
|
+
|
|
606
|
+
constructor(recognition: SpeechRecognitionLike, execution: "onDevice" | "network", config: SessionConfig) {
|
|
312
607
|
this.recognition = recognition;
|
|
313
608
|
this.execution = execution;
|
|
314
|
-
this.
|
|
315
|
-
this.
|
|
316
|
-
this.
|
|
609
|
+
this.config = config;
|
|
610
|
+
this.endpointing = config.endpointing;
|
|
611
|
+
this.now = config.now;
|
|
612
|
+
this.sleep = config.sleep;
|
|
317
613
|
|
|
318
614
|
recognition.onstart = () => {
|
|
319
615
|
this.started = true;
|
|
@@ -322,6 +618,77 @@ class WebRecognitionSession implements TranscriptionSession {
|
|
|
322
618
|
recognition.onresult = (event) => this.onResult(event);
|
|
323
619
|
recognition.onerror = (event) => this.onError(event);
|
|
324
620
|
recognition.onend = () => this.onEnd();
|
|
621
|
+
recognition.onspeechstart = () => this.signalSpeech();
|
|
622
|
+
this.watchEnvironment();
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** Permission revocation, connectivity (service mode) and page lifecycle each end the session once. */
|
|
626
|
+
private watchEnvironment(): void {
|
|
627
|
+
const permission = this.config.permission;
|
|
628
|
+
if (permission !== undefined) {
|
|
629
|
+
const onChange = () => {
|
|
630
|
+
if (permission.state === "denied") this.fail(new VoiceError("denied", "microphone permission was revoked"));
|
|
631
|
+
};
|
|
632
|
+
if (permission.addEventListener && permission.removeEventListener) {
|
|
633
|
+
permission.addEventListener("change", onChange);
|
|
634
|
+
this.cleanups.push(() => permission.removeEventListener!("change", onChange));
|
|
635
|
+
} else if ("onchange" in permission) {
|
|
636
|
+
const previous = permission.onchange ?? null;
|
|
637
|
+
permission.onchange = () => {
|
|
638
|
+
previous?.();
|
|
639
|
+
onChange();
|
|
640
|
+
};
|
|
641
|
+
this.cleanups.push(() => {
|
|
642
|
+
permission.onchange = previous;
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
const window = this.config.window;
|
|
647
|
+
if (window !== undefined) {
|
|
648
|
+
if (this.execution === "network") {
|
|
649
|
+
const onOffline = () =>
|
|
650
|
+
this.fail(new VoiceError("unavailable", "the device went offline, so the browser's recognition service was lost"));
|
|
651
|
+
window.addEventListener("offline", onOffline);
|
|
652
|
+
this.cleanups.push(() => window.removeEventListener("offline", onOffline));
|
|
653
|
+
}
|
|
654
|
+
if (this.config.whenHidden !== "ignore") {
|
|
655
|
+
const onPageHide = () => this.pageHidden();
|
|
656
|
+
window.addEventListener("pagehide", onPageHide);
|
|
657
|
+
this.cleanups.push(() => window.removeEventListener("pagehide", onPageHide));
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const document = this.config.document;
|
|
661
|
+
if (document !== undefined && this.config.whenHidden !== "ignore") {
|
|
662
|
+
const onVisibility = () => {
|
|
663
|
+
if (document.visibilityState === "hidden") this.pageHidden();
|
|
664
|
+
};
|
|
665
|
+
document.addEventListener("visibilitychange", onVisibility);
|
|
666
|
+
this.cleanups.push(() => document.removeEventListener("visibilitychange", onVisibility));
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** The page went away: one terminal event, by policy, and the microphone closes. */
|
|
671
|
+
private pageHidden(): void {
|
|
672
|
+
if (this.terminal) return;
|
|
673
|
+
this.started = true; // never start later
|
|
674
|
+
if (this.config.whenHidden === "cancel") this.emitTerminal({ type: "cancelled" });
|
|
675
|
+
else this.finishWithCollected();
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
private signalSpeech(): void {
|
|
679
|
+
if (this.terminal || this.speechSignalled) return;
|
|
680
|
+
this.speechSignalled = true;
|
|
681
|
+
try {
|
|
682
|
+
this.config.onSpeechStart?.();
|
|
683
|
+
} catch {
|
|
684
|
+
// a host callback must not break the recognizer's event handling
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
private startRecognizer(): void {
|
|
689
|
+
const track = this.config.audio?.track;
|
|
690
|
+
if (track !== undefined) this.recognition.start(track);
|
|
691
|
+
else this.recognition.start();
|
|
325
692
|
}
|
|
326
693
|
|
|
327
694
|
events(): AsyncIterable<SessionEvent> {
|
|
@@ -336,7 +703,7 @@ class WebRecognitionSession implements TranscriptionSession {
|
|
|
336
703
|
// to fail with `no_speech` by itself, and the hard cap has to hold when nothing arrives.
|
|
337
704
|
this.startWatching();
|
|
338
705
|
try {
|
|
339
|
-
this.
|
|
706
|
+
this.startRecognizer();
|
|
340
707
|
} catch (error) {
|
|
341
708
|
this.fail(VoiceError.wrapping(error));
|
|
342
709
|
}
|
|
@@ -395,6 +762,7 @@ class WebRecognitionSession implements TranscriptionSession {
|
|
|
395
762
|
|
|
396
763
|
private onResult(event: SpeechRecognitionEventLike): void {
|
|
397
764
|
if (this.terminal) return;
|
|
765
|
+
this.idleRestarts = 0;
|
|
398
766
|
let changed = false;
|
|
399
767
|
// Results before `resultIndex` are settled. From it on, finals are appended once and every
|
|
400
768
|
// non-final result is part of the current hypothesis, so the volatile text is all of them.
|
|
@@ -422,6 +790,7 @@ class WebRecognitionSession implements TranscriptionSession {
|
|
|
422
790
|
}
|
|
423
791
|
}
|
|
424
792
|
const volatileText = volatile.reduce(joinText, "");
|
|
793
|
+
if (this.words) this.signalSpeech(); // engines without `speechstart` (Safari) still barge in
|
|
425
794
|
if (volatileText !== this.volatileText) changed = true;
|
|
426
795
|
this.volatileText = volatileText;
|
|
427
796
|
if (changed) {
|
|
@@ -439,6 +808,15 @@ class WebRecognitionSession implements TranscriptionSession {
|
|
|
439
808
|
private onError(event: SpeechRecognitionErrorEventLike): void {
|
|
440
809
|
if (this.terminal) return;
|
|
441
810
|
const error = mapRecognitionError(event);
|
|
811
|
+
if (error.code === "no_speech") {
|
|
812
|
+
// The browser's own silence timeout. Words already heard are a final, not a failure; with
|
|
813
|
+
// restarts on, a silent run just restarts and the session's own no-speech deadline decides.
|
|
814
|
+
if (this.words) {
|
|
815
|
+
this.finishWithCollected();
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
if (this.config.onEarlyEnd === "restart" && !this.stopRequested) return;
|
|
819
|
+
}
|
|
442
820
|
if (error.code === "cancelled") {
|
|
443
821
|
this.emitTerminal({ type: "cancelled" });
|
|
444
822
|
return;
|
|
@@ -448,20 +826,50 @@ class WebRecognitionSession implements TranscriptionSession {
|
|
|
448
826
|
|
|
449
827
|
private onEnd(): void {
|
|
450
828
|
if (this.terminal) return;
|
|
829
|
+
if (!this.stopRequested && this.config.onEarlyEnd === "restart" && this.restart()) return;
|
|
451
830
|
this.finishWithCollected(true);
|
|
452
831
|
}
|
|
453
832
|
|
|
833
|
+
/**
|
|
834
|
+
* The browser ended recognition on its own (Chrome on Android after one utterance). Keep the
|
|
835
|
+
* session: what it heard becomes settled text and the recognizer starts again.
|
|
836
|
+
*/
|
|
837
|
+
private restart(): boolean {
|
|
838
|
+
if (this.restarts >= this.config.maxRestarts || this.idleRestarts >= MAX_IDLE_RESTARTS) return false;
|
|
839
|
+
if (this.volatileText.length > 0) {
|
|
840
|
+
// The ended run's hypothesis will never be finalized by the browser now.
|
|
841
|
+
this.finalizedText = joinText(this.finalizedText, this.volatileText);
|
|
842
|
+
this.volatileText = "";
|
|
843
|
+
}
|
|
844
|
+
this.restarts += 1;
|
|
845
|
+
this.idleRestarts += 1;
|
|
846
|
+
this.speechSignalled = false;
|
|
847
|
+
try {
|
|
848
|
+
this.startRecognizer();
|
|
849
|
+
return true;
|
|
850
|
+
} catch {
|
|
851
|
+
return false;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
|
|
454
855
|
/**
|
|
455
856
|
* The one rule for "the session is over, report what it heard": words make a `final`, no words
|
|
456
857
|
* is `no_speech` — whether the end came from the browser, `end()`, or the finalization deadline.
|
|
457
858
|
*/
|
|
458
859
|
private finishWithCollected(fromEnd = false): void {
|
|
459
860
|
this.emitTerminal(
|
|
460
|
-
this.words
|
|
861
|
+
this.words
|
|
862
|
+
? { type: "final", text: this.text, execution: this.recognitionExecution }
|
|
863
|
+
: { type: "failed", error: new VoiceError("no_speech"), execution: this.recognitionExecution },
|
|
461
864
|
fromEnd,
|
|
462
865
|
);
|
|
463
866
|
}
|
|
464
867
|
|
|
868
|
+
/** `local` only while the on-device flag still holds; anything else is reported as the service. */
|
|
869
|
+
private get recognitionExecution(): RecognitionExecution {
|
|
870
|
+
return this.execution === "onDevice" && this.recognition.processLocally === true ? "local" : "service";
|
|
871
|
+
}
|
|
872
|
+
|
|
465
873
|
/** Endpointing: silence after words, a silent session, and the hard cap. */
|
|
466
874
|
private startWatching(): void {
|
|
467
875
|
void this.watch();
|
|
@@ -499,7 +907,7 @@ class WebRecognitionSession implements TranscriptionSession {
|
|
|
499
907
|
}
|
|
500
908
|
|
|
501
909
|
private fail(error: VoiceError): void {
|
|
502
|
-
this.emitTerminal({ type: "failed", error });
|
|
910
|
+
this.emitTerminal({ type: "failed", error, execution: this.recognitionExecution });
|
|
503
911
|
}
|
|
504
912
|
|
|
505
913
|
/**
|
|
@@ -523,11 +931,33 @@ class WebRecognitionSession implements TranscriptionSession {
|
|
|
523
931
|
recognition.onresult = null;
|
|
524
932
|
recognition.onerror = null;
|
|
525
933
|
recognition.onend = null;
|
|
526
|
-
if (
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
934
|
+
if ("onspeechstart" in recognition) recognition.onspeechstart = null;
|
|
935
|
+
for (const cleanup of this.cleanups.splice(0)) {
|
|
936
|
+
try {
|
|
937
|
+
cleanup();
|
|
938
|
+
} catch {
|
|
939
|
+
// removing a listener never fails the session
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
if (!fromEnd) {
|
|
943
|
+
try {
|
|
944
|
+
recognition.abort();
|
|
945
|
+
} catch {
|
|
946
|
+
// aborting an already-ended or failed recognizer is not itself a failure
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
// Every terminal path closes the microphone the SDK opened.
|
|
950
|
+
const audio = this.config.audio;
|
|
951
|
+
if (audio !== undefined) {
|
|
952
|
+
const tracks = new Set(audio.owned);
|
|
953
|
+
if (audio.stopTrack) tracks.add(audio.track);
|
|
954
|
+
for (const track of tracks) {
|
|
955
|
+
try {
|
|
956
|
+
track.stop();
|
|
957
|
+
} catch {
|
|
958
|
+
// an already-stopped track is fine
|
|
959
|
+
}
|
|
960
|
+
}
|
|
531
961
|
}
|
|
532
962
|
}
|
|
533
963
|
|