Skip to content

Instantly share code, notes, and snippets.

@liron-navon
Last active January 19, 2022 23:15
Show Gist options
  • Select an option

  • Save liron-navon/eff96016a233f102fe43030c3a16f4a5 to your computer and use it in GitHub Desktop.

Select an option

Save liron-navon/eff96016a233f102fe43030c3a16f4a5 to your computer and use it in GitHub Desktop.
A simple script to do a quick translation using yandex and cors anywhere
// if you want a demo, just throw it in the console
// it won't work in github's console since they use {"connect-src": "self"} header, you can however do it in google.com
// or almost any other website
//
// yandex translation api is free for up to 1 million characters a day 🤩
// you can set up a free key here: https://tech.yandex.com/translate/
// or just use this, since it's from a fake account it might get blocked in the near future
const KEY = 'trnsl.1.1.20190308T095934Z.95ae5cf4e28588ea.9d108fb6e768af347464925e4e98b91edb0013f5';
const FROM = 'nl'; // default source language
const TO = 'en'; // default target language
const yandexTranslateOrigin = 'https://translate.yandex.net';
const baseAPI = `${yandexTranslateOrigin}/api/v1.5/tr.json`;
const translateAPI = `${baseAPI}/translate?key=${KEY}`;
// to prevent cors in the browser
const withCors = (url) => `https://cors-anywhere.herokuapp.com/${url}`;
// used to cache some of the text, making the translation faster and cheaper
const maxCacheSize = 10000;
const cache = new Map();
// translates a text from one language to another
async function translate(originalText, from = FROM, to = TO) {
if (typeof originalText !== 'string' || originalText === '') {
return ''; // no text to translate ¯\_(ツ)_/¯
}
const sourceText = originalText.trim();
// if you have long texts you should hash them here
const key = `${sourceText}${from}${to}`;
if (cache.has(key)) {
return cache.get(key); // already cached this text (ᵔᴥᵔ)
}
if (cache.size >= maxCacheSize) {
cache.clear(); // too much stuff in the cache (ಠ_ಠ)
}
// getting free translation from yandex (Яндекс ☭ 🇷🇺)
const url = `${translateAPI}&lang=${from}-${to}&text=${encodeURIComponent(sourceText)}`;
const response = await fetch(withCors(url), {
method: 'POST',
headers: {
Origin: yandexTranslateOrigin // used for cors-anywhere
}
});
const responseData = await response.json();
const text = responseData.text[0];
cache.set(key, text);
return text;
}
// ----- EXAMPLE ----- It's a warhammer referance...
// with a promise
translate('in de grimmige donkere toekomst is er alleen oorlog', 'nl', 'en')
.then((text) => console.log(text));
// with async await
const printTranslation = async (text) => {
const translation = await translate(text);
console.log(translation);
}
printTranslation('in de grimmige donkere toekomst is er alleen oorlog');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment