Download frontends/react/src/useTranslation.ts from elvis-hf/attention: direct link, hf CLI and curl.
- Browser
- Download file 1.37 kB
-
https://huggingface.co/spaces/elvis-hf/attention/resolve/main/frontends/react/src/useTranslation.ts
- Command line
-
hf download hf://spaces/elvis-hf/attention/frontends/react/src/useTranslation.ts
-
curl -L -o useTranslation.ts https://huggingface.co/spaces/elvis-hf/attention/resolve/main/frontends/react/src/useTranslation.ts
1.37 kB
| import { useEffect, useState } from "react"; | |
| import { usePythonStatus } from "@elvis/pyodide"; | |
| import { python } from "./python"; | |
| import type { Language, Translation } from "./types"; | |
| const DEFAULT_SENTENCE = "I will go to school tomorrow."; | |
| // After typing stops, wait this long before translating | |
| const TYPING_DELAY_MS = 500; | |
| export default function useTranslation() { | |
| const status = usePythonStatus(python); | |
| const [sentence, setSentence] = useState(DEFAULT_SENTENCE); | |
| const [language, setLanguage] = useState<Language>("zh"); | |
| const [error, setError] = useState<string | null>(null); | |
| // The last sentence that translated, kept while the box holds one that doesn't | |
| const [translation, setTranslation] = useState<Translation | null>(null); | |
| useEffect(() => { | |
| let current = true; | |
| const timer = setTimeout(async () => { | |
| const result = await python.call("handle_translate", { | |
| sentence, | |
| language, | |
| }); | |
| if (!current) { | |
| return; | |
| } | |
| setError(result.ok ? null : result.error.message); | |
| if (result.ok) { | |
| setTranslation(result.data); | |
| } | |
| }, TYPING_DELAY_MS); | |
| return () => { | |
| current = false; | |
| clearTimeout(timer); | |
| }; | |
| }, [sentence, language]); | |
| return { | |
| status, | |
| sentence, | |
| setSentence, | |
| language, | |
| setLanguage, | |
| error, | |
| translation, | |
| }; | |
| } | |