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

VoiceModelSection.tsx

322 lines10.7 KB

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