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

VoiceModelSection.tsx

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