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

VoiceModelSection.tsx

355 lines12.0 KB

1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { T, useGT, useLocale, Var } from "gt-react-native";
3import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
4import { useNavigation } from "@react-navigation/native";
5import {
6 cancelEnvironmentSpeechModelDownload,
7 downloadEnvironmentSpeechModel,
8 selectEnvironmentSpeechModel,
9} from "@t3tools/client-runtime/voice-input";
10import {
11 AuthSettingsWriteScope,
12 type EnvironmentId,
13 type EnvironmentSpeechModel,
14} from "@t3tools/contracts";
15import { AsyncResult } from "effect/reactivity";
16import { type ReactNode, useEffect, useState } from "react";
17import { Platform, Text as NativeText, View } from "react-native";
18import { m } from "../../i18n/messages";
19​
20import { SymbolView } from "../../components/ui/AppSymbol";
21import { AppText as Text } from "../../components/ui/AppText";
22import * as Dialog from "../../components/ui/Dialog";
23import { ListActionRow } from "../../components/ui/ListActionRow";
24import { ListChoiceRow } from "../../components/ui/ListChoiceRow";
25import { ListRow } from "../../components/ui/ListRow";
26import { Progress } from "../../components/ui/Progress";
27import { formatBytes } from "../../lib/formatBytes";
28import { useEnvironmentScope } from "../../state/session";
29import {
30 runSpeech,
31 voiceConnectionAtom,
32 voiceSpeechModelsAtom,
33 voiceSpeechStatusAtom,
34} from "../voice-input/voiceDestination";
35​
36const isDownloading = (model: EnvironmentSpeechModel) =>
37 model.state === "downloading" || model.state === "verifying";
38​
39export function useVoiceModels(environmentId: EnvironmentId, label: string) {
40 const gt = useGT();
41 const connection = useAtomValue(voiceConnectionAtom(environmentId));
42 const statusAtom = voiceSpeechStatusAtom(environmentId);
43 const modelsAtom = voiceSpeechModelsAtom(environmentId);
44 const status = AsyncResult.getOrElse(useAtomValue(statusAtom), () => null);
45 const modelsResult = useAtomValue(modelsAtom);
46 const refreshStatus = useAtomRefresh(statusAtom);
47 const refreshModels = useAtomRefresh(modelsAtom);
48 const canManage = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
49 const [requested, setRequested] = useState<string | null>(null);
50 const [busy, setBusy] = useState(false);
51​
52 const models = AsyncResult.getOrElse(modelsResult, () => null)?.models ?? [];
53 const downloading = requested !== null || models.some(isDownloading);
54​
55 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- polls the environment's download progress while one runs
56 useEffect(() => {
57 if (!downloading) return;
58 const timer = setInterval(refreshModels, 1_000);
59 return () => clearInterval(timer);
60 }, [downloading, refreshModels]);
61​
62 const run = async (title: string, work: () => Promise<unknown>, downloadId?: string) => {
63 if (downloadId) setRequested(downloadId);
64 else setBusy(true);
65 try {
66 await work();
67 } catch (error) {
68 Dialog.alert(
69 title,
70 error instanceof Error ? (errorDisplayMessage(error, m) ?? error.message) : String(error),
71 );
72 }
73 if (downloadId) setRequested(null);
74 else setBusy(false);
75 refreshModels();
76 refreshStatus();
77 };
78 const ready = connection !== null && status?.supported === true;
79 return {
80 connection,
81 status,
82 models,
83 loading: modelsResult._tag === "Initial",
84 canManage,
85 requested,
86 busy,
87 downloading,
88 label,
89 download: (model: EnvironmentSpeechModel) => {
90 if (!ready) return;
91 Dialog.confirm({
92 title: gt("Download {model}?", { model: model.name }),
93 message: gt("{environment} will download {size} and use it as its transcription model.", {
94 environment: label,
95 size: formatBytes(model.size),
96 }),
97 confirmText: gt("Download", { $context: "verb" }),
98 onConfirm: () =>
99 void run(
100 gt("Could not download the model"),
101 async () => {
102 await runSpeech(downloadEnvironmentSpeechModel(connection, model.id));
103 if (model.id !== status.modelId)
104 await runSpeech(selectEnvironmentSpeechModel(connection, model.id));
105 },
106 model.id,
107 ),
108 });
109 },
110 select: (model: EnvironmentSpeechModel) => {
111 if (!ready || model.active) return;
112 void run(gt("Could not select the model"), () =>
113 runSpeech(selectEnvironmentSpeechModel(connection, model.id)),
114 );
115 },
116 cancel: (model: EnvironmentSpeechModel) => {
117 if (!ready) return;
118 void run(gt("Could not cancel the download"), () =>
119 runSpeech(cancelEnvironmentSpeechModelDownload(connection, model.id)),
120 );
121 },
122 };
124​
125export type VoiceModels = ReturnType<typeof useVoiceModels>;
126​
127const languageNames = new Map<string, Intl.DisplayNames>();
128function languageLabel(code: string, locale: string) {
129 if (typeof Intl.DisplayNames !== "function") return code.toUpperCase();
130 let names = languageNames.get(locale);
131 if (!names)
132 languageNames.set(locale, (names = new Intl.DisplayNames([locale], { type: "language" })));
133 return names.of(code) ?? code.toUpperCase();
135​
136function ModelStats(props: { readonly model: EnvironmentSpeechModel; readonly language: string }) {
137 const { model, language } = props;
138 const locale = useLocale();
139 const data = model.benchmark;
140 const code = !data
141 ? undefined
142 : data.accuracy[language]
143 ? language
144 : (model.languages.find((candidate) => data.accuracy[candidate]) ?? model.languages[0]);
145 const score = code ? data?.accuracy[code] : undefined;
146 const parts: ReadonlyArray<readonly [string, ReactNode]> = [
147 ...(code && score
148 ? ([
149 [
150 "score",
151 <T key="score">
152 <Var>{languageLabel(code, locale)}</Var>{" "}
153 <Text className="font-t3-medium text-foreground">
154 <Var>{score.grade}</Var>
155 </Text>{" "}
156 (<Var>{score.errorPercent}</Var>% error)
157 </T>,
158 ],
159 ] as const)
160 : []),
161 ...(data && data.secondsPer30s.accelerated !== null
162 ? ([
163 [
164 "speed",
165 <>
166 <Text className="font-t3-medium text-foreground">
167 {Number(data.secondsPer30s.accelerated.toFixed(2))} s
168 </Text>{" "}
169 / 30 s
170 </>,
171 ],
172 ] as const)
173 : []),
174 // A single-language model's score already names its language.
175 ...(model.languages.length > 1
176 ? ([
177 [
178 "languages",
179 <>
180 <SymbolView
181 name="globe"
182 size={13}
183 tintColorClassName="accent-icon-muted"
184 type="monochrome"
185 weight="regular"
186 />{" "}
187 {model.languages.length}
188 </>,
189 ],
190 ] as const)
191 : score
192 ? []
193 : ([["languages", languageLabel(model.languages[0] ?? "", locale)]] as const)),
194 ["size", formatBytes(model.size)],
195 ];
196 return (
197 <Text textRole="footnote" className="text-foreground-muted tabular-nums">
198 {parts.map(([key, part], index) => (
199 // Plain Text inherits the muted footnote style; AppText would reset it.
200 <NativeText key={key}>
201 {index > 0 ? " · " : null}
202 {part}
203 </NativeText>
204 ))}
205 </Text>
206 );
208​
209function DownloadedGlyph() {
210 return (
211 <View className="size-6">
212 <SymbolView
213 name="tray.and.arrow.down"
214 size={Platform.OS === "android" ? 24 : 22}
215 tintColorClassName="accent-icon"
216 type="monochrome"
217 weight="regular"
218 />
219 <View className="absolute -right-1.5 -bottom-1 size-3.5 items-center justify-center rounded-full bg-primary ring-2 ring-grouped-card">
220 <SymbolView
221 name="checkmark"
222 size={9}
223 tintColorClassName="accent-primary-foreground"
224 type="monochrome"
225 weight="bold"
226 />
227 </View>
228 </View>
229 );
231​
232export function VoiceModelRow(props: {
233 readonly model: EnvironmentSpeechModel;
234 readonly voice: VoiceModels;
235 readonly separated: boolean;
236 /** The language whose benchmark score to show, when the model has one. */
237 readonly language: string;
238}) {
239 const gt = useGT();
240 const { model, voice, separated } = props;
241 const meta = <ModelStats model={model} language={props.language} />;
242 if (model.state === "installed")
243 return (
244 <ListChoiceRow
245 leading={<DownloadedGlyph />}
246 label={model.name}
247 description={model.description}
248 meta={meta}
249 selected={model.active}
250 separated={separated}
251 disabled={!voice.canManage || voice.busy || voice.downloading}
252 onPress={() => voice.select(model)}
253 />
254 );
255 const progress = model.downloaded === undefined ? undefined : model.downloaded / model.size;
256 if (isDownloading(model) || voice.requested === model.id)
257 return (
258 <View className={separated ? "border-t border-border-subtle" : ""}>
259 <ListActionRow
260 icon="xmark"
261 label={model.name}
262 description={
263 model.state === "verifying"
264 ? gt("Verifying download…")
265 : gt("{percent}% downloaded · Tap to cancel", {
266 percent: Math.round((progress ?? 0) * 100),
267 })
268 }
269 disabled={!voice.canManage || voice.busy}
270 onPress={() => voice.cancel(model)}
271 />
272 <Progress
273 className="bg-grouped-card px-4 pb-3"
274 value={model.state === "verifying" ? undefined : progress}
275 label={gt("{model} download progress", { model: model.name })}
276 />
277 </View>
278 );
279 return (
280 <View className={separated ? "border-t border-border-subtle" : ""}>
281 <ListActionRow
282 icon="tray.and.arrow.down"
283 label={model.name}
284 description={model.description}
285 meta={meta}
286 disabled={!voice.canManage || voice.busy || voice.downloading}
287 onPress={() => voice.download(model)}
288 />
289 </View>
290 );
292​
293/** The environment's local-model method: chosen by its mark, opens the model list. */
294export function LocalModelChoice(props: {
295 readonly environmentId: EnvironmentId;
296 readonly label: string;
297 readonly selected: boolean;
298 readonly onSelect: () => void;
299}) {
300 const gt = useGT();
301 const navigation = useNavigation();
302 const voice = useVoiceModels(props.environmentId, props.label);
303 const { status } = voice;
304 const open = () =>
305 navigation.navigate("SettingsVoiceModels", { environmentId: props.environmentId });
306 if (!voice.connection || !status || !status.supported)
307 return (
308 <ListChoiceRow
309 label={gt("Local model")}
310 description={
311 !voice.connection
312 ? gt("Not available on this environment")
313 : status?.supported === false
314 ? status.reason
315 : gt("Checking…")
316 }
317 selected={props.selected}
318 disabled
319 onPress={() => {}}
320 />
321 );
322​
323 const active = status.state === "missing-model" ? null : status;
324 const pending = voice.models.find(isDownloading);
325 const progress =
326 pending?.downloaded === undefined ? undefined : pending.downloaded / pending.size;
327 return (
328 <ListRow
329 label={active?.model ?? gt("Local model")}
330 description={
331 pending
332 ? pending.state === "verifying"
333 ? gt("Verifying {model}…", { model: pending.name })
334 : gt("Downloading {model} · {percent}%", {
335 model: pending.name,
336 percent: Math.round((progress ?? 0) * 100),
337 })
338 : active
339 ? gt("Local model · {size}", { size: formatBytes(active.size) })
340 : voice.canManage
341 ? gt("No model installed · Choose one to download")
342 : gt("No model installed · Add one using {product} on {environment}", {
343 product: "T3 Code",
344 environment: props.label,
345 })
346 }
347 selected={props.selected}
348 onPress={() => {
349 if (!props.selected) props.onSelect();
350 // Switching to an installed model needs no further step.
351 if (props.selected || !active) open();
352 }}
353 />
354 );