Open History to see the last commit
1import * as Schema from "effect/Schema";
2import AppleTranscription from "@react-native-ai/apple/src/NativeAppleTranscription";
3import { File } from "expo-file-system";
4import { msg } from "gt-react-native";
5import { Settings } from "react-native";
6import { m } from "../i18n/messages";
7
8import {
9 VoiceTranscriptionError,
10 throwIfVoiceTranscriptionAborted,
11 type PreparedVoiceTranscription,
12 type VoiceTranscriber,
13 type VoiceTranscriptionOptions,
14} from "@t3tools/client-runtime/voice-input";
15
16const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError);
17
18/** The user's ordered Language & Region list, then the app locale; the app ships in English only. */
19function getPreferredLocales(): string[] {
20 const languages: unknown = Settings.get("AppleLanguages");
21 const preferred = Array.isArray(languages)
22 ? languages.filter(
23 (language): language is string => typeof language === "string" && language.length > 0,
24 )
25 : [];
26 return [...new Set([...preferred, Intl.DateTimeFormat().resolvedOptions().locale])];
27}
28
29function wrapError(
30 code: "preparation-failed" | "transcription-failed",
31 message: string,
32 cause: unknown,
33): VoiceTranscriptionError {
34 if (isVoiceTranscriptionError(cause)) {
35 return cause;
36 }
37
38 return new VoiceTranscriptionError({ code, message, cause });
39}
40
41function getNativeErrorCode(error: unknown): string | undefined {
42 if (typeof error !== "object" || error === null || !("code" in error)) {
43 return undefined;
44 }
45
46 return typeof error.code === "string" ? error.code : undefined;
47}
48
49export async function getLocalVoiceTranscriber(): Promise<VoiceTranscriber | null> {
50 const locales = getPreferredLocales();
51 // Availability is a device and OS check; which languages have a model only `prepare` knows.
52 if (!AppleTranscription.isAvailable(locales[0]!)) return null;
53 return { prepare: (options) => prepareVoiceTranscription(locales, options) };
54}
55
56async function prepareVoiceTranscription(
57 locales: readonly string[],
58 { signal }: VoiceTranscriptionOptions,
59): Promise<PreparedVoiceTranscription> {
60 throwIfVoiceTranscriptionAborted(signal);
61 if (!AppleTranscription.isAvailable(locales[0]!)) {
62 throw new VoiceTranscriptionError({
63 code: "unavailable",
64 message: m(
65 msg("Voice transcription requires a supported device with {platform} or later.", {
66 platform: "iOS 26",
67 }),
68 ),
69 });
70 }
71
72 let locale = locales[0]!;
73 const model = prepareLocales(locales, signal).then((supported) => {
74 locale = supported;
75 });
76 // Recorder setup can fail before either consumer observes the model.
77 void model.catch(() => {});
78
79 async function ready(signal: AbortSignal) {
80 throwIfVoiceTranscriptionAborted(signal);
81 const cancelled = Promise.withResolvers<void>();
82 const cancel = () => cancelled.resolve();
83 signal.addEventListener("abort", cancel, { once: true });
84 try {
85 await Promise.race([model, cancelled.promise]);
86 throwIfVoiceTranscriptionAborted(signal);
87 return locale;
88 } finally {
89 signal.removeEventListener("abort", cancel);
90 }
91 }
92 return {
93 get locale() {
94 return locale;
95 },
96 start: async (_uri, { signal }) => {
97 await ready(signal);
98 return null;
99 },
100 transcribe: async (uri, options) =>
101 transcribeVoiceRecording(uri, await ready(options.signal), options),
102 };
103}
104
105async function prepareLocales(locales: readonly string[], signal: AbortSignal): Promise<string> {
106 throwIfVoiceTranscriptionAborted(signal);
107 let unsupported: VoiceTranscriptionError | undefined;
108 for (const locale of locales) {
109 try {
110 return await prepareLocale(locale, signal);
111 } catch (error) {
112 if (!isVoiceTranscriptionError(error) || error.code !== "unsupported-locale") throw error;
113 unsupported = error;
114 }
115 }
116 throw unsupported!;
117}
118
119async function prepareLocale(locale: string, signal: AbortSignal): Promise<string> {
120 try {
121 const supportedLocale = await AppleTranscription.prepare(locale);
122 throwIfVoiceTranscriptionAborted(signal);
123 return supportedLocale;
124 } catch (error) {
125 throwIfVoiceTranscriptionAborted(signal);
126 if (getNativeErrorCode(error) === "AppleTranscriptionUnsupportedLocale") {
127 throw new VoiceTranscriptionError({
128 code: "unsupported-locale",
129 message: m(msg("Voice transcription does not support any of your languages.")),
130 cause: error,
131 });
132 }
133
134 throw wrapError(
135 "preparation-failed",
136 m(msg("Voice transcription could not prepare this language.")),
137 error,
138 );
139 }
140}
141
142async function transcribeVoiceRecording(
143 uri: string,
144 locale: string,
145 { signal }: VoiceTranscriptionOptions,
146): Promise<string> {
147 try {
148 throwIfVoiceTranscriptionAborted(signal);
149 const audio = await new File(uri).arrayBuffer();
150 throwIfVoiceTranscriptionAborted(signal);
151 const result = await AppleTranscription.transcribe(audio, locale);
152 throwIfVoiceTranscriptionAborted(signal);
153 return result.segments
154 .map((segment) => segment.text)
155 .join(" ")
156 .trim();
157 } catch (error) {
158 throwIfVoiceTranscriptionAborted(signal);
159 throw wrapError("transcription-failed", m(msg("Voice transcription failed.")), error);
160 }
161}