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.

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

  1. Detect. If LanguageDetector.availability() is available, call detect() 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.
  2. Compare. Same language as the recipient: send as is.
  3. 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