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

SpeechService.ts

1,011 lines38.2 KB

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