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