Translator API example
Translator API example. On-device language translation in the browser with Translator.create(). The model stays on the machine.
The problem
A page that translates usually sends the string somewhere else. You pay for an API. The text leaves the machine. The model is not yours.
The method
LanguageDetector names the language. Translator turns the string into another. Both
run on a model the browser already has, or will download. availability() is available,
downloadable, downloading, or unavailable. create() needs a user gesture.
What to do
- Run
availability(), thencreate(), thendetect()on the sample. - Pick a
targetLanguage. Create aTranslator. Runtranslate().
LanguageDetector.availability()
Whether this browser can detect. downloadable means create() will fetch a model. Does
not create the detector.
await LanguageDetector.availability()
LanguageDetector.create()
Needs a user gesture. A monitor fires downloadprogress while the pack arrives.
destroy() releases it.
const detector = await LanguageDetector.create({
monitor(monitor) {
monitor.addEventListener("downloadprogress", (event) => {
event.loaded
})
},
})
detect()
Returns language tags with a confidence. The last row is often und (undetermined). Short strings
are a poor fit. This lab takes the top hit that is not und.
const results = await detector.detect(text)
results[0].detectedLanguage
results[0].confidence
Translator.availability()
Pair-specific. Source is the last detected language, or es if you have not detected yet. Target is
the select.
await Translator.availability({
sourceLanguage: "es",
targetLanguage: "en",
})
Translator.create()
Same gesture rule. Changing targetLanguage means you create again. The old instance is destroyed.
const translator = await Translator.create({
sourceLanguage: "es",
targetLanguage: "en",
})
translate()
A string in, a string out. translateStreaming() is a ReadableStream of chunks. Same
pair. Same model.
await translator.translate(text)
const stream = translator.translateStreaming(text)
destroy()
Drops the detector and the translator. The model can stay on disk. The instances do not.
detector.destroy()
translator.destroy()