Open History to see the last commit
1import { requireOptionalNativeModule } from "expo";
2
3import {
4 VoiceTranscriptionError,
5 throwIfVoiceTranscriptionAborted,
6 type VoiceTranscriber,
7} from "@t3tools/client-runtime/voice-input";
8
9type PreparedGoogleTranscription = { readonly locale: string; readonly mode: number };
10
11type GoogleTranscriptionModule = {
12 checkAvailability(): Promise<boolean>;
13 prepare(id: number): Promise<PreparedGoogleTranscription>;
14 transcribe(id: number, uri: string, locale: string, mode: number): Promise<string>;
15 cancel(id: number): Promise<void>;
16};
17
18const native = requireOptionalNativeModule<GoogleTranscriptionModule>("T3VoiceTranscription");
19
20const nativeErrorMessages: Readonly<Record<string, string>> = {
21 unavailable: "On-device voice transcription is not available for this device language.",
22 storage: "Not enough storage for on-device dictation. Free device storage and retry.",
23 quota: "On-device speech quota reached. Let the device rest or charge it, then retry.",
24 "no-speech": "No speech was detected. Speak again and retry dictation.",
25 busy: "On-device speech is busy. Wait for it to finish, then retry dictation.",
26 "needs-update": "Update Android and its on-device speech services, then retry dictation.",
27 "download-failed": "Speech model download failed. Check your network connection and retry.",
28 "audio-overflow":
29 "The speech engine could not process the complete recording. No text was added. Retry dictation.",
30 "incomplete-audio":
31 "Speech recognition could not process the complete recording. No text was added. Retry dictation.",
32};
33
34let nextOperationId = 0;
35
36export async function getLocalVoiceTranscriber(): Promise<VoiceTranscriber | null> {
37 if (!native || !(await native.checkAvailability())) return null;
38 const module = native;
39 return {
40 prepare: async ({ signal }) => {
41 const prepared = await runOperation(module, signal, "preparation-failed", (id) =>
42 module.prepare(id),
43 );
44 return {
45 locale: prepared.locale,
46 transcribe: (uri, { signal }) =>
47 runOperation(module, signal, "transcription-failed", (id) =>
48 module.transcribe(id, uri, prepared.locale, prepared.mode),
49 ),
50 };
51 },
52 };
53}
54
55async function runOperation<T>(
56 module: GoogleTranscriptionModule,
57 signal: AbortSignal,
58 fallbackCode: "preparation-failed" | "transcription-failed",
59 operation: (id: number) => Promise<T>,
60): Promise<T> {
61 throwIfVoiceTranscriptionAborted(signal);
62 const id = ++nextOperationId;
63 let cancellation: Promise<void> | undefined;
64 const abort = () => {
65 cancellation = module.cancel(id).catch(() => {});
66 };
67 signal.addEventListener("abort", abort, { once: true });
68 try {
69 const result = await operation(id);
70 throwIfVoiceTranscriptionAborted(signal);
71 return result;
72 } catch (error) {
73 throwIfVoiceTranscriptionAborted(signal);
74 const code =
75 typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
76 throw new VoiceTranscriptionError(
77 code === "unavailable" || code === "unsupported-locale" ? code : fallbackCode,
78 (typeof code === "string" ? nativeErrorMessages[code] : undefined) ??
79 (fallbackCode === "preparation-failed"
80 ? "Voice transcription could not prepare this language. Check Google speech services and try again."
81 : "Voice transcription failed."),
82 { cause: error },
83 );
84 } finally {
85 signal.removeEventListener("abort", abort);
86 await cancellation;
87 }
88}