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

SpeechService.ts

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