A Pen by Raymond Camden on CodePen.
Created
March 24, 2025 18:16
-
-
Save cfjedimaster/f0e40a0e25035bb0282d1bc84366f91f to your computer and use it in GitHub Desktop.
Translator March 2025
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p> | |
<textarea id="input"></textarea> | |
<button disabled id="translateBtn">Translate</button> | |
</p> | |
<div id="result"></div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener('DOMContentLoaded', init, false); | |
let $input, $translateBtn, $result; | |
let translator; | |
async function init() { | |
$result = document.querySelector('#result'); | |
$translateBtn = document.querySelector('#translateBtn'); | |
$input = document.querySelector('#input'); | |
if('ai' in window && 'translator' in window.ai) { | |
// You can haz translation | |
console.log('yeah buddy'); | |
let translatorCapabilities = await window.ai.translator.capabilities(); | |
let en_to_zh = translatorCapabilities.languagePairAvailable('en', 'zh'); | |
console.log('English to Mandarin? ', en_to_zh); | |
translator = await self.ai.translator.create({ | |
sourceLanguage: 'en', | |
targetLanguage: 'zh', | |
monitor(m) { | |
m.addEventListener('downloadprogress', (e) => { | |
console.log(`Downloaded ${e.loaded} of ${e.total} bytes.`); | |
// in theory, flip the button disabled and add event listener | |
}); | |
}, | |
}); | |
if(en_to_zh === 'readily') { | |
$translateBtn.disabled=false; | |
$translateBtn.addEventListener('click', translate, false); | |
} | |
} else { | |
console.log('nope'); | |
$result.innerHTML = '<p>Sorry, you can\'t use this API.'; | |
} | |
} | |
async function translate() { | |
let input = $input.value.trim(); | |
if(input === '') return; | |
console.log('Translating', input); | |
let result = await translator.translate(input); | |
console.log(result); | |
$result.innerHTML = result; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
textarea { | |
width: 500px; | |
height: 200px; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment