Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SpeechService.ts

955 lines35.6 KB

1import {
2 SPEECH_STREAM_MAX_CHUNK_BYTES,
3 type EnvironmentSpeechModel,
4 type EnvironmentSpeechStatus,
5 type SpeechAcceleration,
6 type SpeechModelUnloadTimeout,
7 type SpeechTranscriptionOptions,
8} from "@t3tools/contracts";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import * as Cause from "effect/Cause";
11import * as Clock from "effect/Clock";
12import * as Context from "effect/Context";
13import * as Deferred from "effect/Deferred";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as Queue from "effect/Queue";
20import * as Schema from "effect/Schema";
21import * as Scope from "effect/Scope";
22import * as Stream from "effect/Stream";
23​
24import * as ServerSettings from "../serverSettings.ts";
25import { makeSpeechTextCorrector, normalizeSpeechCustomWords } from "./customWords.ts";
26import { removeSpeechFillerWords } from "./fillerWords.ts";
27import {
28 DEFAULT_SPEECH_MODEL_ID,
29 effectiveSpeechLanguage,
30 getSpeechModel,
31 SPEECH_MODELS,
32 type SpeechModel,
33} from "./model.ts";
34import { listNativeSpeechGpuDevices, loadNativeSpeechModel } from "./native.ts";
35import { nativeSpeechLanguage } from "./nativeLanguage.ts";
36import { SILERO_VAD } from "./silero.ts";
37import { isSpeechPlatformSupported } from "./platform.ts";
38import * as SpeechModelStore from "./SpeechModelStore.ts";
39​
40const SAMPLE_RATE = 16_000;
41const MAX_SPEECH_DURATION_SECONDS = 5 * 60;
42export const MAX_SPEECH_BYTES =
43 SAMPLE_RATE * Float32Array.BYTES_PER_ELEMENT * MAX_SPEECH_DURATION_SECONDS;
44​
45export class SpeechInvalidAudioError extends Schema.TaggedError<SpeechInvalidAudioError>()(
46 "SpeechInvalidAudioError",
47 { byteLength: Schema.Number, message: Schema.String },
48) {}
49​
50export function decodeSpeechPcm(pcmBytes: Uint8Array): Float32Array {
51 if (
52 pcmBytes.byteLength === 0 ||
53 pcmBytes.byteLength > MAX_SPEECH_BYTES ||
54 pcmBytes.byteLength % Float32Array.BYTES_PER_ELEMENT !== 0
55 ) {
56 throw new SpeechInvalidAudioError({
57 byteLength: pcmBytes.byteLength,
58 message: "audio must contain at most five minutes of 16 kHz mono Float32 PCM",
59 });
60 }
61 // WebSocket frames can be pooled Node Buffers whose backing storage is larger
62 // than the frame. Copy the view so only the received bytes are decoded.
63 const pcm = new Float32Array(Uint8Array.from(pcmBytes).buffer);
64 for (const sample of pcm) {
65 if (!Number.isFinite(sample) || sample < -1 || sample > 1) {
66 throw new SpeechInvalidAudioError({
67 byteLength: pcmBytes.byteLength,
68 message: "audio contains an invalid PCM sample",
69 });
70 }
71 }
72 return pcm;
74​
75export class SpeechOperationError extends Schema.TaggedError<SpeechOperationError>()(
76 "SpeechOperationError",
77 { operation: Schema.String, cause: Schema.Defect() },
78) {
79 override get message(): string {
80 return `Environment speech ${this.operation} failed.`;
81 }
83​
84export class SpeechUnsupportedPlatformError extends Schema.TaggedError<SpeechUnsupportedPlatformError>()(
85 "SpeechUnsupportedPlatformError",
86 { platform: Schema.String, architecture: Schema.String },
87) {}
88​
89export class SpeechBusyError extends Schema.TaggedError<SpeechBusyError>()("SpeechBusyError", {
90 operation: Schema.String,
91}) {}
92​
93export class SpeechModelNotFoundError extends Schema.TaggedError<SpeechModelNotFoundError>()(
94 "SpeechModelNotFoundError",
95 { modelId: Schema.String },
96) {}
97​
98export class SpeechDownloadCancelledError extends Schema.TaggedError<SpeechDownloadCancelledError>()(
99 "SpeechDownloadCancelledError",
100 { modelId: Schema.String },
101) {}
102​
103export type SpeechError =
104 | SpeechOperationError
105 | SpeechInvalidAudioError
106 | SpeechUnsupportedPlatformError
107 | SpeechModelNotFoundError
108 | SpeechDownloadCancelledError
109 | SpeechBusyError;
110​
111const isSpeechError = Schema.is(
112 Schema.Union([
113 SpeechInvalidAudioError,
114 SpeechUnsupportedPlatformError,
115 SpeechBusyError,
116 SpeechModelNotFoundError,
117 SpeechDownloadCancelledError,
118 SpeechOperationError,
119 ]),
120);
121​
122type LoadedModel = Awaited<ReturnType<typeof loadNativeSpeechModel>>;
123type SpeechModels = { readonly models: ReadonlyArray<EnvironmentSpeechModel> };
124​
125export type SpeechStream = {
126 readonly feed: (
127 pcm: Uint8Array,
128 ) => Effect.Effect<Awaited<ReturnType<LoadedModel["feed"]>>, SpeechError>;
129 readonly finish: Effect.Effect<string, SpeechError>;
130};
131​
132export class SpeechService extends Context.Service<
133 SpeechService,
134 {
135 readonly status: Effect.Effect<EnvironmentSpeechStatus, SpeechError>;
136 readonly models: (includeBenchmarks: boolean) => Effect.Effect<SpeechModels, SpeechError>;
137 readonly downloadModel: (modelId: string) => Effect.Effect<SpeechModels, SpeechError>;
138 readonly selectModel: (modelId: string) => Effect.Effect<SpeechModels, SpeechError>;
139 readonly cancelDownload: (modelId: string) => Effect.Effect<SpeechModels, SpeechError>;
140 readonly removeModel: (modelId: string) => Effect.Effect<SpeechModels, SpeechError>;
141 readonly prepareModel: Effect.Effect<void, SpeechError>;
142 readonly transcribe: (
143 pcmBytes: Uint8Array,
144 options: SpeechTranscriptionOptions,
145 ) => Effect.Effect<string, SpeechError>;
146 readonly startStream: (
147 options: SpeechTranscriptionOptions,
148 ) => Effect.Effect<SpeechStream, SpeechError, Scope.Scope>;
149 readonly updateAcceleration: (
150 acceleration: SpeechAcceleration,
151 ) => Effect.Effect<EnvironmentSpeechStatus, SpeechError>;
152 readonly updateModelUnloadTimeout: (
153 timeout: SpeechModelUnloadTimeout,
154 ) => Effect.Effect<EnvironmentSpeechStatus, SpeechError>;
155 }
156>()("t3/speech/SpeechService") {}
157​
158const UNLOAD_MILLISECONDS: Record<Exclude<SpeechModelUnloadTimeout, "never">, number> = {
159 immediately: 0,
160 min_2: 2 * 60_000,
161 min_5: 5 * 60_000,
162 min_10: 10 * 60_000,
163 min_15: 15 * 60_000,
164 hour_1: 60 * 60_000,
165};
166​
167const make = Effect.gen(function* () {
168 const platform = yield* HostProcess.Platform;
169 const architecture = yield* HostProcess.Architecture;
170 const serverSettings = yield* ServerSettings.ServerSettingsService;
171 const store = yield* SpeechModelStore.SpeechModelStore;
172 const scope = yield* Effect.scope;
173 const clock = yield* Clock.Clock;
174 const now = () => clock.currentTimeMillisUnsafe();
175 const libc = platform === "linux" ? yield* HostProcess.LinuxLibc : undefined;
176 const unsupportedReason = isSpeechPlatformSupported(platform, architecture, libc)
177 ? null
178 : `voice transcription is not available on ${platform}-${architecture}`;
179​
180 let model: LoadedModel | undefined;
181 let loadedModelId: string | undefined;
182 let loadedAcceleration: string | undefined;
183 let autoCpuModel: string | undefined;
184 let loading: Promise<LoadedModel> | undefined;
185 const discoverGpuDevices = yield* Effect.tryPromise({
186 try: () => listNativeSpeechGpuDevices(),
187 catch: (cause) => new SpeechOperationError({ operation: "discover GPU devices", cause }),
188 }).pipe(Effect.cachedWithTTL((exit) => (Exit.isSuccess(exit) ? Duration.infinity : "1 minute")));
189 let downloading:
190 | {
191 modelId: string;
192 downloaded: number;
193 verifying: boolean;
194 fiber: Deferred.Deferred<Fiber.Fiber<string, SpeechError>>;
195 }
196 | undefined;
197 let activeTranscriptions = 0;
198 // One native request at a time; the slot is a promise so unload waits for it.
199 let activeOperation: Promise<unknown> | undefined;
200 const operationBusy = () => Boolean(activeOperation || downloading);
201 let closing = false;
202 // @effect-diagnostics-next-line abortControllerInEffect:off - Cached native workers must also stop on service shutdown.
203 const lifetime = new AbortController();
204 let unloadTimeout: SpeechModelUnloadTimeout = "min_15";
205​
206 // Deadlines are absolute: the consumer fiber registers its sleep a few scheduler
207 // hops after the request, so a relative delay would drift.
208 const unloadRequests = yield* Queue.sliding<{ deadline: number } | null>(1);
209 const clearUnloadTimer = () => Queue.offerUnsafe(unloadRequests, null);
210 const scheduleUnload = (minimumDelayMs = 0) => {
211 clearUnloadTimer();
212 if (!model || closing || unloadTimeout === "never") return;
213 Queue.offerUnsafe(unloadRequests, {
214 deadline: now() + Math.max(minimumDelayMs, UNLOAD_MILLISECONDS[unloadTimeout]),
215 });
216 };
217​
218 const forgetModel = (target: LoadedModel) => {
219 if (model !== target) return;
220 model = undefined;
221 loadedModelId = undefined;
222 loadedAcceleration = undefined;
223 };
224 const disposeModel = async () => {
225 const target = model;
226 if (!target) return;
227 forgetModel(target);
228 await target.dispose();
229 };
230 // Stops the isolated process without waiting for native work to settle.
231 const dropModel = (target: LoadedModel) => {
232 forgetModel(target);
233 void Promise.resolve()
234 .then(() => target.dispose())
235 .catch(() => undefined);
236 };
237​
238 // Auto placement may land on a GPU the native engine cannot actually run; one retry on
239 // this host's CPU recovers it. A GPU the person chose, and CPU itself, report the error.
240 const canRetryOnCpu = (acceleration: SpeechAcceleration, loaded: LoadedModel) =>
241 acceleration === "auto" && loaded.backend.toLowerCase() !== "cpu";
242​
243 yield* Effect.addFinalizer(() =>
244 Effect.promise(async () => {
245 closing = true;
246 clearUnloadTimer();
247 lifetime.abort();
248 await disposeModel();
249 }),
250 );
251​
252 yield* Stream.fromQueue(unloadRequests).pipe(
253 Stream.switchMap((request) =>
254 request === null
255 ? Stream.empty
256 : Stream.fromEffect(
257 Effect.gen(function* () {
258 yield* Effect.sleep(Math.max(0, request.deadline - now()));
259 if (closing) return;
260 if (operationBusy() || activeTranscriptions || loading) {
261 scheduleUnload(1000);
262 return;
263 }
264 yield* Effect.promise(() => disposeModel().catch(() => undefined)).pipe(
265 Effect.uninterruptible,
266 );
267 }),
268 ),
269 ),
270 Stream.runDrain,
271 Effect.forkScoped,
272 );
273​
274 type SettingsSnapshot = Effect.Success<
275 ServerSettings.ServerSettingsService["Service"]["getSettings"]
276 >;
277​
278 const selectedModel = (settings: SettingsSnapshot): SpeechModel =>
279 getSpeechModel(settings.speechModelId) ?? getSpeechModel(DEFAULT_SPEECH_MODEL_ID)!;
280​
281 let silenceRetryAt = 0;
282 const acquireSilenceModel = Effect.fn("SpeechService.acquireSilenceModel")(function* (
283 purpose: "installation" | "recording",
284 ) {
285 if (purpose === "recording" && now() < silenceRetryAt) return undefined;
286 const path = yield* store.download(SILERO_VAD).pipe(
287 Effect.timeout(purpose === "recording" ? "15 seconds" : "2 minutes"),
288 Effect.orElseSucceed(() => undefined),
289 );
290 if (path !== undefined) {
291 silenceRetryAt = 0;
292 return path;
293 }
294 silenceRetryAt = now() + 10 * 60_000;
295 yield* Effect.logWarning("Silero unavailable; using raw audio with bounded ASR processing.");
296 });
297​
298 // Publish the reservation before forking: a cached transfer can finish before forkIn returns.
299 const downloadFiber = Effect.fn("SpeechService.downloadFiber")(function* (modelId: string) {
300 const definition = getSpeechModel(modelId);
301 if (!definition) return yield* new SpeechModelNotFoundError({ modelId });
302 if (closing || activeOperation || (downloading && downloading.modelId !== modelId))
303 return yield* new SpeechBusyError({ operation: "model download" });
304 if (downloading) return yield* Deferred.await(downloading.fiber);
305 const transfer = {
306 modelId,
307 downloaded: 0,
308 verifying: false,
309 fiber: Deferred.makeUnsafe<Fiber.Fiber<string, SpeechError>>(),
310 };
311 downloading = transfer;
312 const fiber = yield* store
313 .download(definition, {
314 onProgress: (downloaded) => {
315 transfer.downloaded = downloaded;
316 transfer.verifying = false;
317 },
318 onVerificationStart: () => {
319 transfer.verifying = true;
320 },
321 })
322 .pipe(
323 (modelDownload) =>
324 Effect.all([modelDownload, acquireSilenceModel("installation")], { concurrency: 2 }),
325 Effect.map(([modelPath]) => modelPath),
326 Effect.mapError((cause) => speechError("model download", cause)),
327 Effect.forkIn(scope),
328 );
329 fiber.addObserver(() => {
330 if (downloading !== transfer) return;
331 downloading = undefined;
332 scheduleUnload();
333 });
334 yield* Deferred.succeed(transfer.fiber, fiber);
335 return fiber;
336 }, Effect.uninterruptible);
337​
338 const download = Effect.fn("SpeechService.download")(function* (modelId: string) {
339 const exit = yield* Fiber.await(yield* downloadFiber(modelId));
340 if (Exit.isSuccess(exit)) return exit.value;
341 return yield* Cause.hasInterruptsOnly(exit.cause)
342 ? new SpeechDownloadCancelledError({ modelId })
343 : Effect.failCause(exit.cause);
344 });
345​
346 const installedModelPath = (definition: SpeechModel) =>
347 store.installedPath(definition).pipe(
348 Effect.filterOrFail(
349 (modelPath) => modelPath !== undefined,
350 () => new SpeechModelNotFoundError({ modelId: definition.id }),
351 ),
352 );
353​
354 const loadModel = async (
355 modelPath: string,
356 definition: SpeechModel,
357 signal = lifetime.signal,
358 requestedAcceleration = "auto",
359 ) => {
360 const acceleration =
361 requestedAcceleration === "auto" && autoCpuModel === definition.id
362 ? "cpu"
363 : requestedAcceleration;
364 if (model && loadedModelId === definition.id && loadedAcceleration === acceleration) {
365 scheduleUnload();
366 return model;
367 }
368 if (loading) return loading;
369 await disposeModel();
370 signal.throwIfAborted();
371 const pending = loadNativeSpeechModel(modelPath, signal, undefined, acceleration).then(
372 async (loaded) => {
373 if (closing || signal.aborted) {
374 await loaded.dispose();
375 signal.throwIfAborted();
376 throw new SpeechBusyError({ operation: "model preparation" });
377 }
378 model = loaded;
379 loadedModelId = definition.id;
380 loadedAcceleration = acceleration;
381 scheduleUnload();
382 return loaded;
383 },
384 );
385 const release = () => {
386 if (loading === pending) loading = undefined;
387 };
388 loading = pending;
389 signal.addEventListener("abort", release, { once: true });
390 try {
391 return await pending;
392 } finally {
393 signal.removeEventListener("abort", release);
394 release();
395 }
396 };
397​
398 const speechError = (operation: string, cause: unknown): SpeechError =>
399 isSpeechError(cause) ? cause : new SpeechOperationError({ operation, cause });
400​
401 const attempt = <A>(operation: string, run: (signal: AbortSignal) => Promise<A>) =>
402 Effect.tryPromise({ try: run, catch: (cause) => speechError(operation, cause) });
403​
404 // The busy slot is released by a finalizer, so interrupting the fiber frees it at
405 // once instead of waiting for native work that may never settle.
406 const exclusive = <A, E, R>(operation: string, effect: Effect.Effect<A, E, R>) =>
407 Effect.uninterruptibleMask((restore) =>
408 Effect.suspend<A, E | SpeechBusyError, R>(() => {
409 if (closing || operationBusy()) return Effect.fail(new SpeechBusyError({ operation }));
410 const gate = Promise.withResolvers<void>();
411 activeOperation = gate.promise;
412 return restore(effect).pipe(
413 Effect.ensuring(
414 Effect.sync(() => {
415 if (activeOperation === gate.promise) activeOperation = undefined;
416 scheduleUnload(
417 operation === "model preparation" ? MAX_SPEECH_DURATION_SECONDS * 1000 : 0,
418 );
419 gate.resolve();
420 }),
421 ),
422 );
423 }),
424 );
425​
426 const readSettings = (operation: string) =>
427 serverSettings.getSettings.pipe(
428 Effect.tap((settings) =>
429 Effect.sync(() => {
430 if (settings.speechModelId !== autoCpuModel || settings.speechAcceleration !== "auto")
431 autoCpuModel = undefined;
432 if (unloadTimeout !== settings.speechModelUnloadTimeout) {
433 unloadTimeout = settings.speechModelUnloadTimeout;
434 scheduleUnload();
435 }
436 }),
437 ),
438 Effect.mapError((cause) => new SpeechOperationError({ operation, cause })),
439 );
440​
441 const writeSettings = (
442 operation: string,
443 patch: Parameters<ServerSettings.ServerSettingsService["Service"]["updateSettings"]>[0],
444 ) =>
445 serverSettings
446 .updateSettings(patch)
447 .pipe(Effect.mapError((cause) => new SpeechOperationError({ operation, cause })));
448​
449 const currentStatus = Effect.fn("SpeechService.currentStatus")(function* (
450 settings: SettingsSnapshot,
451 ): Effect.fn.Return<EnvironmentSpeechStatus> {
452 if (unsupportedReason) return { supported: false, reason: unsupportedReason };
453 const definition = selectedModel(settings);
454 const ready = yield* store.isReady(definition);
455 return {
456 supported: true,
457 state: activeTranscriptions > 0 ? "transcribing" : ready ? "ready" : "missing-model",
458 modelId: definition.id,
459 model: definition.name,
460 size: definition.size,
461 supportsStreaming: definition.supportsStreaming,
462 supportsBufferedStreaming: true,
463 supportsTranslation: definition.supportsTranslation,
464 languages: definition.languages,
465 supportsLanguageDetection: definition.supportsLanguageDetection,
466 acceleration: settings.speechAcceleration,
467 modelUnloadTimeout: settings.speechModelUnloadTimeout,
468 gpuDevices: yield* discoverGpuDevices.pipe(Effect.orElseSucceed(() => [])),
469 };
470 });
471​
472 const listModels = Effect.fn("SpeechService.listModels")(function* (
473 settings: SettingsSnapshot,
474 includeBenchmarks: boolean,
475 ): Effect.fn.Return<SpeechModels> {
476 const selected = selectedModel(settings);
477 const models = yield* Effect.forEach(
478 SPEECH_MODELS,
479 (definition) =>
480 store.isReady(definition).pipe(
481 Effect.map((ready): EnvironmentSpeechModel => {
482 const operation = downloading?.modelId === definition.id ? downloading : undefined;
483 return {
484 id: definition.id,
485 name: definition.name,
486 description: definition.description,
487 size: definition.size,
488 languages: definition.languages,
489 accuracy: definition.accuracy,
490 speed: definition.speed,
491 ...(includeBenchmarks ? { benchmark: definition.benchmark } : {}),
492 recommended: definition.recommended,
493 supportsStreaming: definition.supportsStreaming,
494 supportsLanguageDetection: definition.supportsLanguageDetection,
495 supportsTranslation: definition.supportsTranslation,
496 active: ready && selected.id === definition.id,
497 state: operation
498 ? operation.verifying
499 ? "verifying"
500 : "downloading"
501 : ready
502 ? "installed"
503 : "downloadable",
504 ...(operation ? { downloaded: operation.downloaded } : {}),
505 };
506 }),
507 ),
508 { concurrency: "unbounded" },
509 );
510 return { models };
511 });
512​
513 const freshStatus = (operation: string) =>
514 readSettings(operation).pipe(Effect.flatMap(currentStatus));
515 const readModels = (includeBenchmarks: boolean) =>
516 readSettings("model listing").pipe(
517 Effect.flatMap((settings) => listModels(settings, includeBenchmarks)),
518 );
519 const modelsEffect = readModels(false);
520​
521 const requireSupported = Effect.suspend(() =>
522 unsupportedReason
523 ? Effect.fail(new SpeechUnsupportedPlatformError({ platform, architecture }))
524 : Effect.void,
525 );
526​
527 const finalizeTranscript = (
528 text: string,
529 options: SpeechTranscriptionOptions,
530 language: string | undefined,
531 ) => {
532 return (
533 options.speechRemoveFillerWords
534 ? removeSpeechFillerWords(text, language, options.speechCorrectionWord)
535 : text
536 ).trim();
537 };
538​
539 const prepareModel = readSettings("model preparation").pipe(
540 Effect.flatMap((settings) =>
541 exclusive(
542 "model preparation",
543 requireSupported.pipe(
544 Effect.andThen(installedModelPath(selectedModel(settings))),
545 Effect.flatMap((modelPath) =>
546 attempt("model preparation", (signal) =>
547 loadModel(
548 modelPath,
549 selectedModel(settings),
550 AbortSignal.any([signal, lifetime.signal]),
551 settings.speechAcceleration,
552 ),
553 ).pipe(
554 Effect.timeout("2 minutes"),
555 Effect.catchTags({
556 TimeoutError: (cause) =>
557 Effect.fail(new SpeechOperationError({ operation: "model preparation", cause })),
558 }),
559 ),
560 ),
561 ),
562 ),
563 ),
564 );
565​
566 const silenceModelPath = Effect.fn("SpeechService.silenceModelPath")(function* (
567 loaded: LoadedModel,
568 options: SpeechTranscriptionOptions,
569 ) {
570 if (!options.speechSilenceFiltering && (loaded.supportsStreaming || loaded.supportsLongForm))
571 return undefined;
572 return yield* acquireSilenceModel("recording");
573 });
574​
575 const transcribe: SpeechService["Service"]["transcribe"] = Effect.fn("SpeechService.transcribe")(
576 function* (pcmBytes, options) {
577 const settings = yield* readSettings("transcription");
578 return yield* exclusive(
579 "transcription",
580 Effect.gen(function* () {
581 yield* requireSupported;
582 const pcm = yield* Effect.try({
583 try: () => decodeSpeechPcm(pcmBytes),
584 catch: (cause) => speechError("transcription", cause),
585 });
586 if (pcm.length === 0) return "";
587 activeTranscriptions += 1;
588 return yield* Effect.gen(function* () {
589 const definition = selectedModel(settings);
590 const language = effectiveSpeechLanguage(definition, options.speechLanguage);
591 const translateToEnglish =
592 options.speechTranslateToEnglish &&
593 definition.supportsTranslation &&
594 language !== "en";
595 const modelPath = yield* installedModelPath(definition);
596 const loaded = yield* Effect.tryPromise({
597 try: (signal) =>
598 loadModel(
599 modelPath,
600 definition,
601 AbortSignal.any([signal, lifetime.signal]),
602 settings.speechAcceleration,
603 ),
604 catch: (cause) => speechError("model preparation", cause),
605 });
606 const vadPath = yield* silenceModelPath(loaded, options);
607 const dictionary = normalizeSpeechCustomWords(options.speechCustomWords);
608 const customWords = dictionary.map(({ term }) => term);
609 // The vocabulary capability guarantees plain transcription, not translation.
610 const vocabularyFor = (inference: LoadedModel) =>
611 inference.supportsVocabulary && !translateToEnglish ? customWords : [];
612 const transcribeWith = (inference: LoadedModel) =>
613 Effect.tryPromise({
614 try: (signal) => {
615 // Interruption kills the isolated process; the next request reloads the model.
616 signal.addEventListener("abort", () => dropModel(inference), { once: true });
617 const hint = nativeSpeechLanguage(inference.languages, language);
618 return inference.transcribe(
619 pcm,
620 {
621 timestamps: "none",
622 ...(hint ? { language: hint } : {}),
623 ...(translateToEnglish
624 ? { task: "translate" as const, targetLanguage: "en" as const }
625 : {}),
626 ...(vocabularyFor(inference).length > 0 ? { vocabulary: customWords } : {}),
627 },
628 options.speechSilenceFiltering,
629 vadPath,
630 );
631 },
632 catch: (cause) => {
633 dropModel(inference);
634 return speechError("inference", cause);
635 },
636 });
637 let inference = loaded;
638 const result = yield* transcribeWith(loaded).pipe(
639 Effect.catch((error) => {
640 if (!canRetryOnCpu(settings.speechAcceleration, loaded)) return Effect.fail(error);
641 return Effect.tryPromise({
642 try: (signal) =>
643 loadModel(
644 modelPath,
645 definition,
646 AbortSignal.any([signal, lifetime.signal]),
647 "cpu",
648 ),
649 catch: (cause) => speechError("model preparation", cause),
650 }).pipe(
651 Effect.flatMap((cpu) => {
652 autoCpuModel = definition.id;
653 inference = cpu;
654 return transcribeWith(cpu);
655 }),
656 );
657 }),
658 );
659 const correct = makeSpeechTextCorrector(
660 vocabularyFor(inference).length > 0 ? [] : customWords,
661 dictionary,
662 );
663 return finalizeTranscript(
664 correct(result.text),
665 options,
666 translateToEnglish ? "en" : language === "auto" ? undefined : language,
667 );
668 }).pipe(
669 Effect.ensuring(
670 Effect.sync(() => {
671 activeTranscriptions -= 1;
672 }),
673 ),
674 );
675 }),
676 );
677 },
678 );
679​
680 // Stream setup shares the public startStream span.
681 const openStream = Effect.fnUntraced(function* (options: SpeechTranscriptionOptions) {
682 const operation = "streaming transcription";
683 yield* requireSupported;
684 const released = Promise.withResolvers<void>();
685 // @effect-diagnostics-next-line abortControllerInEffect:off - Stream cancellation must abort native work independently of the caller fiber.
686 const controller = new AbortController();
687 const signal = AbortSignal.any([controller.signal, lifetime.signal]);
688 let finished = false;
689 let closed = false;
690 let started = false;
691 let loaded: LoadedModel | undefined;
692 yield* Effect.acquireRelease(
693 Effect.suspend(() => {
694 if (closing || operationBusy()) return Effect.fail(new SpeechBusyError({ operation }));
695 activeOperation = released.promise;
696 activeTranscriptions += 1;
697 return Effect.void;
698 }),
699 () =>
700 Effect.sync(() => {
701 activeTranscriptions -= 1;
702 if (activeOperation === released.promise) activeOperation = undefined;
703 scheduleUnload();
704 released.resolve();
705 }),
706 );
707 yield* Effect.addFinalizer(() =>
708 Effect.gen(function* () {
709 closed = true;
710 if (!finished) {
711 const dispose = Effect.promise(async () => {
712 const pending = loading;
713 controller.abort();
714 await pending?.catch(() => undefined);
715 if (loaded) {
716 forgetModel(loaded);
717 await loaded.dispose();
718 }
719 });
720 if (loaded && started) {
721 yield* attempt("reset stream", () => loaded!.reset()).pipe(
722 Effect.timeout("2500 millis"),
723 Effect.catch(() => dispose),
724 );
725 } else {
726 yield* dispose;
727 }
728 }
729 }),
730 );
731 const settings = yield* readSettings(operation);
732 const definition = selectedModel(settings);
733 const language = effectiveSpeechLanguage(definition, options.speechLanguage);
734 const dictionary = normalizeSpeechCustomWords(options.speechCustomWords);
735 const customWords = dictionary.map(({ term }) => term);
736 let correct = makeSpeechTextCorrector(customWords, dictionary);
737 const modelPath = yield* installedModelPath(definition);
738 let streamModel = yield* attempt(operation, () =>
739 loadModel(modelPath, definition, signal, settings.speechAcceleration),
740 );
741 loaded = streamModel;
742 const vadPath = yield* silenceModelPath(streamModel, options);
743 let translateToEnglish = false;
744 const beginStream = async () => {
745 translateToEnglish =
746 options.speechTranslateToEnglish &&
747 !streamModel.supportsStreaming &&
748 streamModel.supportsTranslation &&
749 language !== "en";
750 const vocabulary =
751 streamModel.supportsVocabulary && !translateToEnglish && customWords.length
752 ? customWords
753 : undefined;
754 const hint = nativeSpeechLanguage(streamModel.languages, language);
755 await streamModel.begin(
756 {
757 timestamps: "none",
758 ...(hint ? { language: hint } : {}),
759 ...(translateToEnglish ? { task: "translate", targetLanguage: "en" } : {}),
760 ...(vocabulary ? { vocabulary } : {}),
761 },
762 options.speechSilenceFiltering,
763 vadPath,
764 );
765 correct = makeSpeechTextCorrector(vocabulary ? [] : customWords, dictionary);
766 started = true;
767 };
768 // Audio already fed is kept so a CPU restart can replay it; the limit caps it at one recording.
769 const received: Float32Array[] = [];
770 let retriedOnCpu = false;
771 const recoverOnCpu = async (cause: unknown) => {
772 started = false;
773 if (closed || signal.aborted || retriedOnCpu) throw cause;
774 if (!canRetryOnCpu(settings.speechAcceleration, streamModel)) throw cause;
775 retriedOnCpu = true;
776 forgetModel(streamModel);
777 await streamModel.dispose();
778 if (closed || signal.aborted) throw cause;
779 streamModel = await loadModel(modelPath, definition, signal, "cpu");
780 autoCpuModel = definition.id;
781 loaded = streamModel;
782 await beginStream();
783 let update: Awaited<ReturnType<LoadedModel["feed"]>> | undefined;
784 for (const chunk of received) {
785 if (closed || signal.aborted) throw new Error("Speech stream is closed.");
786 update = await streamModel.feed(chunk);
787 }
788 return update;
789 };
790 yield* attempt(operation, async () => {
791 try {
792 await beginStream();
793 } catch (cause) {
794 await recoverOnCpu(cause);
795 }
796 });
797 let byteLength = 0;
798 let busy = false;
799 // Client revisions stay monotonic across a native restart, whose own counter resets.
800 let revisionBase = 0;
801 let lastNativeRevision = 0;
802 const run = <A>(work: () => Promise<A>) =>
803 attempt(operation, async () => {
804 if (busy || finished || closed || !started || signal.aborted)
805 throw new Error("Speech stream is not ready.");
806 busy = true;
807 try {
808 return await work();
809 } finally {
810 busy = false;
811 }
812 });
813 return {
814 feed: (bytes: Uint8Array) =>
815 run(async () => {
816 if (
817 bytes.byteLength > SPEECH_STREAM_MAX_CHUNK_BYTES ||
818 byteLength + bytes.byteLength > MAX_SPEECH_BYTES
819 )
820 throw new SpeechInvalidAudioError({
821 byteLength: bytes.byteLength,
822 message: "Speech stream audio limit exceeded.",
823 });
824 const pcm = decodeSpeechPcm(bytes);
825 byteLength += bytes.byteLength;
826 received.push(pcm);
827 let update: Awaited<ReturnType<LoadedModel["feed"]>> | undefined;
828 try {
829 update = await streamModel.feed(pcm);
830 } catch (cause) {
831 update = await recoverOnCpu(cause);
832 revisionBase += lastNativeRevision;
833 lastNativeRevision = 0;
834 }
835 if (update) lastNativeRevision = update.revision;
836 return {
837 revision: revisionBase + (update?.revision ?? lastNativeRevision),
838 text: update?.text
839 ? {
840 committed: correct(update.text.committed),
841 tentative: correct(update.text.tentative),
842 }
843 : null,
844 };
845 }),
846 finish: run(async () => {
847 let text: string;
848 try {
849 text = await streamModel.finish().catch(async (cause: unknown) => {
850 await recoverOnCpu(cause);
851 if (closed || signal.aborted) throw cause;
852 return streamModel.finish();
853 });
854 } catch (cause) {
855 started = false;
856 throw cause;
857 }
858 finished = true;
859 return finalizeTranscript(
860 correct(text),
861 options,
862 translateToEnglish ? "en" : language === "auto" ? undefined : language,
863 );
864 }),
865 };
866 });
867​
868 return SpeechService.of({
869 status: freshStatus("status"),
870 models: readModels,
871 prepareModel,
872 transcribe,
873 startStream: Effect.fn("SpeechService.startStream")(function* (options) {
874 const session = yield* Scope.fork(yield* Effect.scope);
875 return yield* openStream(options).pipe(
876 Scope.provide(session),
877 Effect.onError((cause) => Scope.close(session, Exit.failCause(cause))),
878 );
879 }),
880 downloadModel: Effect.fn("SpeechService.downloadModel")((modelId) =>
881 requireSupported.pipe(
882 Effect.andThen(download(modelId)),
883 Effect.catchTags({ SpeechDownloadCancelledError: () => Effect.void }),
884 Effect.andThen(modelsEffect),
885 ),
886 ),
887 selectModel: Effect.fn("SpeechService.selectModel")((modelId) =>
888 exclusive(
889 "model selection",
890 attempt("model selection", async () => {
891 if (!getSpeechModel(modelId)) throw new SpeechModelNotFoundError({ modelId });
892 await disposeModel();
893 }),
894 ).pipe(
895 Effect.andThen(writeSettings("model selection", { speechModelId: modelId })),
896 Effect.andThen(modelsEffect),
897 ),
898 ),
899 cancelDownload: Effect.fn("SpeechService.cancelDownload")((modelId) =>
900 Effect.suspend(() =>
901 downloading?.modelId === modelId
902 ? Deferred.await(downloading.fiber).pipe(Effect.flatMap(Fiber.interrupt))
903 : Effect.void,
904 ).pipe(Effect.andThen(modelsEffect)),
905 ),
906 removeModel: Effect.fn("SpeechService.removeModel")((modelId) =>
907 readSettings("model removal").pipe(
908 Effect.flatMap((settings) =>
909 exclusive(
910 "model removal",
911 Effect.gen(function* () {
912 const definition = getSpeechModel(modelId);
913 if (!definition) return yield* new SpeechModelNotFoundError({ modelId });
914 yield* attempt("model removal", async () => {
915 await loading?.catch(() => undefined);
916 if (loadedModelId === modelId) await disposeModel();
917 });
918 yield* store
919 .remove(definition)
920 .pipe(Effect.mapError((cause) => speechError("model removal", cause)));
921 if (selectedModel(settings).id !== modelId) return undefined;
922 const candidates = yield* Effect.forEach(
923 SPEECH_MODELS.filter((candidate) => candidate.id !== modelId),
924 (candidate) =>
925 store.isReady(candidate).pipe(Effect.map((ready) => ({ candidate, ready }))),
926 { concurrency: "unbounded" },
927 );
928 return candidates.find(({ ready }) => ready)?.candidate.id;
929 }),
930 ).pipe(
931 Effect.flatMap((replacementId) =>
932 replacementId
933 ? writeSettings("model removal", { speechModelId: replacementId }).pipe(
934 Effect.andThen(modelsEffect),
935 )
936 : modelsEffect,
937 ),
938 ),
939 ),
940 ),
941 ),
942 updateAcceleration: Effect.fn("SpeechService.updateAcceleration")((acceleration) =>
943 writeSettings("acceleration update", { speechAcceleration: acceleration }).pipe(
944 Effect.andThen(freshStatus("acceleration update")),
945 ),
946 ),
947 updateModelUnloadTimeout: Effect.fn("SpeechService.updateModelUnloadTimeout")((timeout) =>
948 writeSettings("model unload timeout update", { speechModelUnloadTimeout: timeout }).pipe(
949 Effect.andThen(freshStatus("model unload timeout update")),
950 ),
951 ),
952 });
953});
954​
955export const layer = Layer.effect(SpeechService, make);