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

SpeechService.ts

967 lines36.0 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 const gpuDevices = yield* discoverGpuDevices.pipe(Effect.orElseSucceed(() => []));
456 const autoUsesCpu =
457 gpuDevices.length === 0 ||
458 autoCpuModel === definition.id ||
459 (loadedModelId === definition.id &&
460 loadedAcceleration === "auto" &&
461 model?.backend.toLowerCase() === "cpu");
462 return {
463 supported: true,
464 state: activeTranscriptions > 0 ? "transcribing" : ready ? "ready" : "missing-model",
465 modelId: definition.id,
466 model: definition.name,
467 size: definition.size,
468 supportsStreaming: definition.supportsStreaming,
469 supportsBufferedStreaming: true,
470 supportsTranslation: definition.supportsTranslation,
471 languages: definition.languages,
472 supportsLanguageDetection: definition.supportsLanguageDetection,
473 acceleration: settings.speechAcceleration,
474 benchmarkTier:
475 settings.speechAcceleration === "cpu" ||
476 (settings.speechAcceleration === "auto" && autoUsesCpu)
477 ? "cpu"
478 : "accelerated",
479 modelUnloadTimeout: settings.speechModelUnloadTimeout,
480 gpuDevices,
481 };
482 });
483​
484 const listModels = Effect.fn("SpeechService.listModels")(function* (
485 settings: SettingsSnapshot,
486 includeBenchmarks: boolean,
487 ): Effect.fn.Return<SpeechModels> {
488 const selected = selectedModel(settings);
489 const models = yield* Effect.forEach(
490 SPEECH_MODELS,
491 (definition) =>
492 store.isReady(definition).pipe(
493 Effect.map((ready): EnvironmentSpeechModel => {
494 const operation = downloading?.modelId === definition.id ? downloading : undefined;
495 return {
496 id: definition.id,
497 name: definition.name,
498 description: definition.description,
499 size: definition.size,
500 languages: definition.languages,
501 accuracy: definition.accuracy,
502 speed: definition.speed,
503 ...(includeBenchmarks ? { benchmark: definition.benchmark } : {}),
504 recommended: definition.recommended,
505 supportsStreaming: definition.supportsStreaming,
506 supportsLanguageDetection: definition.supportsLanguageDetection,
507 supportsTranslation: definition.supportsTranslation,
508 active: ready && selected.id === definition.id,
509 state: operation
510 ? operation.verifying
511 ? "verifying"
512 : "downloading"
513 : ready
514 ? "installed"
515 : "downloadable",
516 ...(operation ? { downloaded: operation.downloaded } : {}),
517 };
518 }),
519 ),
520 { concurrency: "unbounded" },
521 );
522 return { models };
523 });
524​
525 const freshStatus = (operation: string) =>
526 readSettings(operation).pipe(Effect.flatMap(currentStatus));
527 const readModels = (includeBenchmarks: boolean) =>
528 readSettings("model listing").pipe(
529 Effect.flatMap((settings) => listModels(settings, includeBenchmarks)),
530 );
531 const modelsEffect = readModels(false);
532​
533 const requireSupported = Effect.suspend(() =>
534 unsupportedReason
535 ? Effect.fail(new SpeechUnsupportedPlatformError({ platform, architecture }))
536 : Effect.void,
537 );
538​
539 const finalizeTranscript = (
540 text: string,
541 options: SpeechTranscriptionOptions,
542 language: string | undefined,
543 ) => {
544 return (
545 options.speechRemoveFillerWords
546 ? removeSpeechFillerWords(text, language, options.speechCorrectionWord)
547 : text
548 ).trim();
549 };
550​
551 const prepareModel = readSettings("model preparation").pipe(
552 Effect.flatMap((settings) =>
553 exclusive(
554 "model preparation",
555 requireSupported.pipe(
556 Effect.andThen(installedModelPath(selectedModel(settings))),
557 Effect.flatMap((modelPath) =>
558 attempt("model preparation", (signal) =>
559 loadModel(
560 modelPath,
561 selectedModel(settings),
562 AbortSignal.any([signal, lifetime.signal]),
563 settings.speechAcceleration,
564 ),
565 ).pipe(
566 Effect.timeout("2 minutes"),
567 Effect.catchTags({
568 TimeoutError: (cause) =>
569 Effect.fail(new SpeechOperationError({ operation: "model preparation", cause })),
570 }),
571 ),
572 ),
573 ),
574 ),
575 ),
576 );
577​
578 const silenceModelPath = Effect.fn("SpeechService.silenceModelPath")(function* (
579 loaded: LoadedModel,
580 options: SpeechTranscriptionOptions,
581 ) {
582 if (!options.speechSilenceFiltering && (loaded.supportsStreaming || loaded.supportsLongForm))
583 return undefined;
584 return yield* acquireSilenceModel("recording");
585 });
586​
587 const transcribe: SpeechService["Service"]["transcribe"] = Effect.fn("SpeechService.transcribe")(
588 function* (pcmBytes, options) {
589 const settings = yield* readSettings("transcription");
590 return yield* exclusive(
591 "transcription",
592 Effect.gen(function* () {
593 yield* requireSupported;
594 const pcm = yield* Effect.try({
595 try: () => decodeSpeechPcm(pcmBytes),
596 catch: (cause) => speechError("transcription", cause),
597 });
598 if (pcm.length === 0) return "";
599 activeTranscriptions += 1;
600 return yield* Effect.gen(function* () {
601 const definition = selectedModel(settings);
602 const language = effectiveSpeechLanguage(definition, options.speechLanguage);
603 const translateToEnglish =
604 options.speechTranslateToEnglish &&
605 definition.supportsTranslation &&
606 language !== "en";
607 const modelPath = yield* installedModelPath(definition);
608 const loaded = yield* Effect.tryPromise({
609 try: (signal) =>
610 loadModel(
611 modelPath,
612 definition,
613 AbortSignal.any([signal, lifetime.signal]),
614 settings.speechAcceleration,
615 ),
616 catch: (cause) => speechError("model preparation", cause),
617 });
618 const vadPath = yield* silenceModelPath(loaded, options);
619 const dictionary = normalizeSpeechCustomWords(options.speechCustomWords);
620 const customWords = dictionary.map(({ term }) => term);
621 // The vocabulary capability guarantees plain transcription, not translation.
622 const vocabularyFor = (inference: LoadedModel) =>
623 inference.supportsVocabulary && !translateToEnglish ? customWords : [];
624 const transcribeWith = (inference: LoadedModel) =>
625 Effect.tryPromise({
626 try: (signal) => {
627 // Interruption kills the isolated process; the next request reloads the model.
628 signal.addEventListener("abort", () => dropModel(inference), { once: true });
629 const hint = nativeSpeechLanguage(inference.languages, language);
630 return inference.transcribe(
631 pcm,
632 {
633 timestamps: "none",
634 ...(hint ? { language: hint } : {}),
635 ...(translateToEnglish
636 ? { task: "translate" as const, targetLanguage: "en" as const }
637 : {}),
638 ...(vocabularyFor(inference).length > 0 ? { vocabulary: customWords } : {}),
639 },
640 options.speechSilenceFiltering,
641 vadPath,
642 );
643 },
644 catch: (cause) => {
645 dropModel(inference);
646 return speechError("inference", cause);
647 },
648 });
649 let inference = loaded;
650 const result = yield* transcribeWith(loaded).pipe(
651 Effect.catch((error) => {
652 if (!canRetryOnCpu(settings.speechAcceleration, loaded)) return Effect.fail(error);
653 return Effect.tryPromise({
654 try: (signal) =>
655 loadModel(
656 modelPath,
657 definition,
658 AbortSignal.any([signal, lifetime.signal]),
659 "cpu",
660 ),
661 catch: (cause) => speechError("model preparation", cause),
662 }).pipe(
663 Effect.flatMap((cpu) => {
664 autoCpuModel = definition.id;
665 inference = cpu;
666 return transcribeWith(cpu);
667 }),
668 );
669 }),
670 );
671 const correct = makeSpeechTextCorrector(
672 vocabularyFor(inference).length > 0 ? [] : customWords,
673 dictionary,
674 );
675 return finalizeTranscript(
676 correct(result.text),
677 options,
678 translateToEnglish ? "en" : language === "auto" ? undefined : language,
679 );
680 }).pipe(
681 Effect.ensuring(
682 Effect.sync(() => {
683 activeTranscriptions -= 1;
684 }),
685 ),
686 );
687 }),
688 );
689 },
690 );
691​
692 // Stream setup shares the public startStream span.
693 const openStream = Effect.fnUntraced(function* (options: SpeechTranscriptionOptions) {
694 const operation = "streaming transcription";
695 yield* requireSupported;
696 const released = Promise.withResolvers<void>();
697 // @effect-diagnostics-next-line abortControllerInEffect:off - Stream cancellation must abort native work independently of the caller fiber.
698 const controller = new AbortController();
699 const signal = AbortSignal.any([controller.signal, lifetime.signal]);
700 let finished = false;
701 let closed = false;
702 let started = false;
703 let loaded: LoadedModel | undefined;
704 yield* Effect.acquireRelease(
705 Effect.suspend(() => {
706 if (closing || operationBusy()) return Effect.fail(new SpeechBusyError({ operation }));
707 activeOperation = released.promise;
708 activeTranscriptions += 1;
709 return Effect.void;
710 }),
711 () =>
712 Effect.sync(() => {
713 activeTranscriptions -= 1;
714 if (activeOperation === released.promise) activeOperation = undefined;
715 scheduleUnload();
716 released.resolve();
717 }),
718 );
719 yield* Effect.addFinalizer(() =>
720 Effect.gen(function* () {
721 closed = true;
722 if (!finished) {
723 const dispose = Effect.promise(async () => {
724 const pending = loading;
725 controller.abort();
726 await pending?.catch(() => undefined);
727 if (loaded) {
728 forgetModel(loaded);
729 await loaded.dispose();
730 }
731 });
732 if (loaded && started) {
733 yield* attempt("reset stream", () => loaded!.reset()).pipe(
734 Effect.timeout("2500 millis"),
735 Effect.catch(() => dispose),
736 );
737 } else {
738 yield* dispose;
739 }
740 }
741 }),
742 );
743 const settings = yield* readSettings(operation);
744 const definition = selectedModel(settings);
745 const language = effectiveSpeechLanguage(definition, options.speechLanguage);
746 const dictionary = normalizeSpeechCustomWords(options.speechCustomWords);
747 const customWords = dictionary.map(({ term }) => term);
748 let correct = makeSpeechTextCorrector(customWords, dictionary);
749 const modelPath = yield* installedModelPath(definition);
750 let streamModel = yield* attempt(operation, () =>
751 loadModel(modelPath, definition, signal, settings.speechAcceleration),
752 );
753 loaded = streamModel;
754 const vadPath = yield* silenceModelPath(streamModel, options);
755 let translateToEnglish = false;
756 const beginStream = async () => {
757 translateToEnglish =
758 options.speechTranslateToEnglish &&
759 !streamModel.supportsStreaming &&
760 streamModel.supportsTranslation &&
761 language !== "en";
762 const vocabulary =
763 streamModel.supportsVocabulary && !translateToEnglish && customWords.length
764 ? customWords
765 : undefined;
766 const hint = nativeSpeechLanguage(streamModel.languages, language);
767 await streamModel.begin(
768 {
769 timestamps: "none",
770 ...(hint ? { language: hint } : {}),
771 ...(translateToEnglish ? { task: "translate", targetLanguage: "en" } : {}),
772 ...(vocabulary ? { vocabulary } : {}),
773 },
774 options.speechSilenceFiltering,
775 vadPath,
776 );
777 correct = makeSpeechTextCorrector(vocabulary ? [] : customWords, dictionary);
778 started = true;
779 };
780 // Audio already fed is kept so a CPU restart can replay it; the limit caps it at one recording.
781 const received: Float32Array[] = [];
782 let retriedOnCpu = false;
783 const recoverOnCpu = async (cause: unknown) => {
784 started = false;
785 if (closed || signal.aborted || retriedOnCpu) throw cause;
786 if (!canRetryOnCpu(settings.speechAcceleration, streamModel)) throw cause;
787 retriedOnCpu = true;
788 forgetModel(streamModel);
789 await streamModel.dispose();
790 if (closed || signal.aborted) throw cause;
791 streamModel = await loadModel(modelPath, definition, signal, "cpu");
792 autoCpuModel = definition.id;
793 loaded = streamModel;
794 await beginStream();
795 let update: Awaited<ReturnType<LoadedModel["feed"]>> | undefined;
796 for (const chunk of received) {
797 if (closed || signal.aborted) throw new Error("Speech stream is closed.");
798 update = await streamModel.feed(chunk);
799 }
800 return update;
801 };
802 yield* attempt(operation, async () => {
803 try {
804 await beginStream();
805 } catch (cause) {
806 await recoverOnCpu(cause);
807 }
808 });
809 let byteLength = 0;
810 let busy = false;
811 // Client revisions stay monotonic across a native restart, whose own counter resets.
812 let revisionBase = 0;
813 let lastNativeRevision = 0;
814 const run = <A>(work: () => Promise<A>) =>
815 attempt(operation, async () => {
816 if (busy || finished || closed || !started || signal.aborted)
817 throw new Error("Speech stream is not ready.");
818 busy = true;
819 try {
820 return await work();
821 } finally {
822 busy = false;
823 }
824 });
825 return {
826 feed: (bytes: Uint8Array) =>
827 run(async () => {
828 if (
829 bytes.byteLength > SPEECH_STREAM_MAX_CHUNK_BYTES ||
830 byteLength + bytes.byteLength > MAX_SPEECH_BYTES
831 )
832 throw new SpeechInvalidAudioError({
833 byteLength: bytes.byteLength,
834 message: "Speech stream audio limit exceeded.",
835 });
836 const pcm = decodeSpeechPcm(bytes);
837 byteLength += bytes.byteLength;
838 received.push(pcm);
839 let update: Awaited<ReturnType<LoadedModel["feed"]>> | undefined;
840 try {
841 update = await streamModel.feed(pcm);
842 } catch (cause) {
843 update = await recoverOnCpu(cause);
844 revisionBase += lastNativeRevision;
845 lastNativeRevision = 0;
846 }
847 if (update) lastNativeRevision = update.revision;
848 return {
849 revision: revisionBase + (update?.revision ?? lastNativeRevision),
850 text: update?.text
851 ? {
852 committed: correct(update.text.committed),
853 tentative: correct(update.text.tentative),
854 }
855 : null,
856 };
857 }),
858 finish: run(async () => {
859 let text: string;
860 try {
861 text = await streamModel.finish().catch(async (cause: unknown) => {
862 await recoverOnCpu(cause);
863 if (closed || signal.aborted) throw cause;
864 return streamModel.finish();
865 });
866 } catch (cause) {
867 started = false;
868 throw cause;
869 }
870 finished = true;
871 return finalizeTranscript(
872 correct(text),
873 options,
874 translateToEnglish ? "en" : language === "auto" ? undefined : language,
875 );
876 }),
877 };
878 });
879​
880 return SpeechService.of({
881 status: freshStatus("status"),
882 models: readModels,
883 prepareModel,
884 transcribe,
885 startStream: Effect.fn("SpeechService.startStream")(function* (options) {
886 const session = yield* Scope.fork(yield* Effect.scope);
887 return yield* openStream(options).pipe(
888 Scope.provide(session),
889 Effect.onError((cause) => Scope.close(session, Exit.failCause(cause))),
890 );
891 }),
892 downloadModel: Effect.fn("SpeechService.downloadModel")((modelId) =>
893 requireSupported.pipe(
894 Effect.andThen(download(modelId)),
895 Effect.catchTags({ SpeechDownloadCancelledError: () => Effect.void }),
896 Effect.andThen(modelsEffect),
897 ),
898 ),
899 selectModel: Effect.fn("SpeechService.selectModel")((modelId) =>
900 exclusive(
901 "model selection",
902 attempt("model selection", async () => {
903 if (!getSpeechModel(modelId)) throw new SpeechModelNotFoundError({ modelId });
904 await disposeModel();
905 }),
906 ).pipe(
907 Effect.andThen(writeSettings("model selection", { speechModelId: modelId })),
908 Effect.andThen(modelsEffect),
909 ),
910 ),
911 cancelDownload: Effect.fn("SpeechService.cancelDownload")((modelId) =>
912 Effect.suspend(() =>
913 downloading?.modelId === modelId
914 ? Deferred.await(downloading.fiber).pipe(Effect.flatMap(Fiber.interrupt))
915 : Effect.void,
916 ).pipe(Effect.andThen(modelsEffect)),
917 ),
918 removeModel: Effect.fn("SpeechService.removeModel")((modelId) =>
919 readSettings("model removal").pipe(
920 Effect.flatMap((settings) =>
921 exclusive(
922 "model removal",
923 Effect.gen(function* () {
924 const definition = getSpeechModel(modelId);
925 if (!definition) return yield* new SpeechModelNotFoundError({ modelId });
926 yield* attempt("model removal", async () => {
927 await loading?.catch(() => undefined);
928 if (loadedModelId === modelId) await disposeModel();
929 });
930 yield* store
931 .remove(definition)
932 .pipe(Effect.mapError((cause) => speechError("model removal", cause)));
933 if (selectedModel(settings).id !== modelId) return undefined;
934 const candidates = yield* Effect.forEach(
935 SPEECH_MODELS.filter((candidate) => candidate.id !== modelId),
936 (candidate) =>
937 store.isReady(candidate).pipe(Effect.map((ready) => ({ candidate, ready }))),
938 { concurrency: "unbounded" },
939 );
940 return candidates.find(({ ready }) => ready)?.candidate.id;
941 }),
942 ).pipe(
943 Effect.flatMap((replacementId) =>
944 replacementId
945 ? writeSettings("model removal", { speechModelId: replacementId }).pipe(
946 Effect.andThen(modelsEffect),
947 )
948 : modelsEffect,
949 ),
950 ),
951 ),
952 ),
953 ),
954 updateAcceleration: Effect.fn("SpeechService.updateAcceleration")((acceleration) =>
955 writeSettings("acceleration update", { speechAcceleration: acceleration }).pipe(
956 Effect.andThen(freshStatus("acceleration update")),
957 ),
958 ),
959 updateModelUnloadTimeout: Effect.fn("SpeechService.updateModelUnloadTimeout")((timeout) =>
960 writeSettings("model unload timeout update", { speechModelUnloadTimeout: timeout }).pipe(
961 Effect.andThen(freshStatus("model unload timeout update")),
962 ),
963 ),
964 });
965});
966​
967export const layer = Layer.effect(SpeechService, make);