From fb0cc81d1db0d88c90bb112a0caec66095fcc0f0 Mon Sep 17 00:00:00 2001 From: André Oliveira <37463445+SpecialAro@users.noreply.github.com> Date: Wed, 17 Aug 2022 22:54:41 +0100 Subject: 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). --- src/helpers/translation-helpers.ts | 47 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/helpers/translation-helpers.ts (limited to 'src/helpers') 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 @@ +import fetch from 'node-fetch'; +import translateGoogle from 'translate-google'; +import { LIVE_API_FERDIUM_LIBRETRANSLATE } from '../config'; + +export async function translateTo( + text: string, + translateToLanguage: string, + translatorEngine: string, +): Promise<{ text: string; error: boolean }> { + const errorText = + // TODO: Need to support i18n + 'FERDIUM ERROR: An error occured. Please select less text to translate or try again later.'; + + if (translatorEngine === 'Google') { + try { + const res = await translateGoogle(text, { + to: translateToLanguage, + }); + + return { text: res, error: false }; + } catch { + return { text: errorText, error: true }; + } + } else if (translatorEngine === 'LibreTranslate') { + try { + const res = await fetch(LIVE_API_FERDIUM_LIBRETRANSLATE, { + method: 'POST', + body: JSON.stringify({ + q: text, + source: 'auto', + target: translateToLanguage, + }), + headers: { + 'Content-Type': 'application/json', + }, + }); + + const response = await res.json(); + + return { text: response.translatedText, error: false }; + } catch { + return { text: errorText, error: true }; + } + } + + return { text: errorText, error: true }; +} -- cgit v1.2.3-54-g00ecf