v157 · concept 5 · practical use + composition with Translator
Detect-then-translate composer
A phone-first reply box for a marketplace chat. When you send, LanguageDetector works out what language you wrote in, on the device. If that isn't the recipient's language and the Translator pack for the pair is already installed, the message is translated before it's sent. If either model is missing, the message goes out untranslated and is labelled that way. A pack is only downloaded when you tap the button that says so.
Checking which on-device models this browser has…
the chat
Messages you send appear here, each labelled with how its language was found and whether it was translated.
Pipeline trace: nothing sent yet.
how the pipeline decides
- Detect. If
LanguageDetector.availability()isavailable, calldetect()and take the top result. If its confidence is below 0.6 (common for short messages), the page doesn't trust it and sends untranslated. If the detector isn't on the device, the page doesn't download it from a Send tap; it sends untranslated. - Compare. Same language as the recipient: send as is.
- Translate. Check
Translator.availability({ sourceLanguage, targetLanguage }).available: translate on the device, no tap needed.downloadable: stop and ask, with a button whose label says it downloads.unavailable: send untranslated.
Enter sends, Shift+Enter adds a line, and Enter while an IME is composing (Japanese, Chinese, Korean input) is ignored, so a half-converted message is never sent.
the code
const [top] = await detector.detect(text);
if (top.confidence >= 0.6 && top.detectedLanguage !== target) {
const a = await Translator.availability({ sourceLanguage: top.detectedLanguage, targetLanguage: target });
if (a === "available") text = await (await Translator.create({ sourceLanguage: top.detectedLanguage, targetLanguage: target })).translate(text);
}
see also
- Translator API on Android (v161), the sibling feature this page composes with
- Offline chat composer (v161), the same pattern seen from the Translator side
- Download on a constrained device
- ChromeStatus entry (5087964794322944)
- Spec: Translator and Language Detector APIs