-
Notifications
You must be signed in to change notification settings - Fork 1
/
LibreTranslator.js
65 lines (59 loc) · 1.68 KB
/
LibreTranslator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Homepage: https://github.com/LibreTranslate/LibreTranslate
* Demo: https://libretranslate.com/
* API docs: https://libretranslate.com/docs/
*/
class LibreTranslator {
// URL of your instance of LibreTranslate
// for local instance use URL "http://localhost/translate"
apiPath = 'https://translate.terraprint.co/translate';
// Insert API key if you have
apiKey = '';
translate = (text, from, to) => {
return fetch(this.apiPath, {
credentials: 'omit',
headers: {
'User-Agent':
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:99.0) Gecko/20100101 Firefox/99.0',
Accept: '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'Content-Type': 'application/json',
},
method: 'POST',
mode: 'cors',
body: JSON.stringify({
q: text,
source: from,
target: to,
format: 'text',
api_key: this.apiKey,
}),
})
.then((r) => r.json())
.then(({ translatedText }) => translatedText);
};
translateBatch = (texts, from, to) =>
Promise.all(texts.map((text) => this.translate(text, from, to)));
getLengthLimit = () => 4000;
getRequestsTimeout = () => 300;
checkLimitExceeding = (text) => {
const textLength = !Array.isArray(text)
? text.length
: text.reduce((len, text) => len + text.length, 0);
return textLength - this.getLengthLimit();
};
static isSupportedAutoFrom = () => true;
// prettier-ignore
static getSupportedLanguages = () => [
"en", "ar", "az", "zh", "cs",
"nl", "eo", "fi", "fr", "de",
"el", "hi", "hu", "id", "ga",
"it", "ja", "ko", "fa", "pl",
"pt", "ru", "sk", "es", "sv",
"tr", "uk", "vi"
];
}
LibreTranslator;