diff options
author | André Oliveira <37463445+SpecialAro@users.noreply.github.com> | 2022-08-17 22:54:41 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-08-17 22:54:41 +0100 |
commit | fb0cc81d1db0d88c90bb112a0caec66095fcc0f0 (patch) | |
tree | aaa5d0f92f55ccf3984af2cbf2ebbcb1da5fd7c6 /src/helpers | |
parent | 6.0.1-nightly.16 [skip ci] (diff) | |
download | ferdium-app-fb0cc81d1db0d88c90bb112a0caec66095fcc0f0.tar.gz ferdium-app-fb0cc81d1db0d88c90bb112a0caec66095fcc0f0.tar.zst ferdium-app-fb0cc81d1db0d88c90bb112a0caec66095fcc0f0.zip |
Feature: Add Ferdium Translator (#548)
Add feature to translate text natively using https://github.com/shikar/NODE_GOOGLE_TRANSLATE package and a LibreTranslate self-hosted option (already running on our server on https://translator.ferdium.org).
Diffstat (limited to 'src/helpers')
-rw-r--r-- | src/helpers/translation-helpers.ts | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/src/helpers/translation-helpers.ts b/src/helpers/translation-helpers.ts new file mode 100644 index 000000000..215b2a49c --- /dev/null +++ b/src/helpers/translation-helpers.ts | |||
@@ -0,0 +1,47 @@ | |||
1 | import fetch from 'node-fetch'; | ||
2 | import translateGoogle from 'translate-google'; | ||
3 | import { LIVE_API_FERDIUM_LIBRETRANSLATE } from '../config'; | ||
4 | |||
5 | export async function translateTo( | ||
6 | text: string, | ||
7 | translateToLanguage: string, | ||
8 | translatorEngine: string, | ||
9 | ): Promise<{ text: string; error: boolean }> { | ||
10 | const errorText = | ||
11 | // TODO: Need to support i18n | ||
12 | 'FERDIUM ERROR: An error occured. Please select less text to translate or try again later.'; | ||
13 | |||
14 | if (translatorEngine === 'Google') { | ||
15 | try { | ||
16 | const res = await translateGoogle(text, { | ||
17 | to: translateToLanguage, | ||
18 | }); | ||
19 | |||
20 | return { text: res, error: false }; | ||
21 | } catch { | ||
22 | return { text: errorText, error: true }; | ||
23 | } | ||
24 | } else if (translatorEngine === 'LibreTranslate') { | ||
25 | try { | ||
26 | const res = await fetch(LIVE_API_FERDIUM_LIBRETRANSLATE, { | ||
27 | method: 'POST', | ||
28 | body: JSON.stringify({ | ||
29 | q: text, | ||
30 | source: 'auto', | ||
31 | target: translateToLanguage, | ||
32 | }), | ||
33 | headers: { | ||
34 | 'Content-Type': 'application/json', | ||
35 | }, | ||
36 | }); | ||
37 | |||
38 | const response = await res.json(); | ||
39 | |||
40 | return { text: response.translatedText, error: false }; | ||
41 | } catch { | ||
42 | return { text: errorText, error: true }; | ||
43 | } | ||
44 | } | ||
45 | |||
46 | return { text: errorText, error: true }; | ||
47 | } | ||