Skip to content

Instantly share code, notes, and snippets.

@adalinesimonian
Created January 7, 2024 06:07
Show Gist options
  • Save adalinesimonian/ac453d88ff524e571a6d24b9e1a16001 to your computer and use it in GitHub Desktop.
Save adalinesimonian/ac453d88ff524e571a6d24b9e1a16001 to your computer and use it in GitHub Desktop.
Linguist custom translator for DeepL with Nynorsk support
const deepLApiKey = '' // REQUIRED, Specify your DeepL API key here
const apiSubdomain = deepLApiKey.endsWith(':fx') ? 'api-free' : 'api'
class DeepLTranslator {
async translate(text, from, to) {
const deeplFrom = from === 'nn' ? 'nb' : from
let deeplText = text
// If from language is Nynorsk, convert to Bokmål using Apertium
if (from === 'nn') {
deeplText = await this.translateWithApertium(text, 'nno', 'nob')
}
const deeplTo = to === 'nn' ? 'nb' : to
let translatedText =
from === to ||
(from === 'nb' && to === 'nn') ||
(from === 'nn' && to === 'nb')
? deeplText
: await this.translateWithDeepL(deeplText, deeplFrom, deeplTo)
// If target language is Nynorsk, convert from Bokmål using Apertium
if (to === 'nn') {
translatedText = await this.translateWithApertium(
translatedText,
'nob',
'nno'
)
}
return translatedText
}
async translateBatch(texts, from, to) {
return Promise.all(texts.map(text => this.translate(text, from, to)))
}
async translateWithDeepL(text, from, to) {
const deepLData = JSON.stringify({
text: [text],
...(from !== 'auto' && { source_lang: from }),
target_lang: to
})
const deepLRes = await fetch(
`https://${apiSubdomain}.deepl.com/v2/translate`,
{
method: 'POST',
headers: {
Authorization: `DeepL-Auth-Key ${deepLApiKey}`,
'Content-Type': 'application/json'
},
body: deepLData
}
)
const deepLJson = await deepLRes.json()
return deepLJson.translations[0].text
}
async translateWithApertium(text, from, to) {
const apertiumData = new URLSearchParams({
langpair: `${from}|${to}`,
markUnknown: 'no',
prefs: '',
q: text
})
const apertiumRes = await fetch('https://apertium.org/apy/translate', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: apertiumData
})
const apertiumJson = await apertiumRes.json()
return apertiumJson.responseData.translatedText
}
getLengthLimit() {
return 10000
}
getRequestsTimeout() {
return 300
}
checkLimitExceeding(text) {
return text.length - this.getLengthLimit()
}
static isSupportedAutoFrom() {
return true
}
// Returns ISO 639-1 codes of supported languages
static getSupportedLanguages() {
// prettier-ignore
return [
'bg', 'cs', 'da', 'de', 'el', 'en', 'es', 'et', 'fi',
'fr', 'hu', 'id', 'it', 'ja', 'ko', 'lt', 'lv', 'nb',
'nn', 'nl', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sv',
'tr', 'uk', 'zh'
]
}
}
DeepLTranslator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment