Skip to content

Commit

Permalink
feat: libretranslate support (#607)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <[email protected]>
  • Loading branch information
farfromrefug and antfu authored Jul 13, 2021
1 parent 0c963d7 commit ab3451d
Show file tree
Hide file tree
Showing 18 changed files with 77 additions and 1 deletion.
1 change: 1 addition & 0 deletions locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "Schlüssel, die als verwendet markiert werden sollen, obwohl sie nicht im Code vorkommen",
"config.keystyle": "Stil der Lokalisierungsschlüssel",
"config.language_tag_system": "Sprachen tag system",
"config.libretranslate_api_root": "",
"config.locale_country_map": "Ein Objekt zur Zuordnung von zwei Buchstaben des Lokalisierungscodes zum Ländercode",
"config.locales_paths": "Pfad des Lokalisierungsordners (relative zum Hauptverzeichnes). Glob pattern akzeptiert.",
"config.namespace": "Namespace aktivieren. Dokumentation für weitere Details prüfen.",
Expand Down
1 change: 1 addition & 0 deletions locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "Keys to mark as in use despite not appearing in the code",
"config.keystyle": "Locale key style",
"config.language_tag_system": "Language tag system use are using.",
"config.libretranslate_api_root": "LibreTranslate API root URL",
"config.locale_country_map": "An object to map two letters locale code to country code",
"config.locales_paths": "Path to locales directory (relative to project root). Glob pattern is also acceptable.",
"config.namespace": "Enable namespaces. Check out the docs for more details.",
Expand Down
1 change: 1 addition & 0 deletions locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "Claves a marcar para rellenar incluso sin aparecer en el código",
"config.keystyle": "Estilo de la clave de configuración regional",
"config.language_tag_system": "Sistema de etiquetado de lenguaje se está usando",
"config.libretranslate_api_root": "",
"config.locale_country_map": "Un objeto para relacionar dos letras de código regional a código de país",
"config.locales_paths": "Ruta de acceso al directorio de configuración regional (relativa a la raíz del proyecto). Acepta patrón Glob.",
"config.namespace": "Habilitar espacios de nombres. Comprueba la documentación para más detalles.",
Expand Down
1 change: 1 addition & 0 deletions locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "Clés à marquer comme étant utilisées bien qu'elles n'apparaissent pas dans le code",
"config.keystyle": "Style de clé locale.",
"config.language_tag_system": "Utilisation du système de balise pour la langue utilisée.",
"config.libretranslate_api_root": "Point d'entree pour l'API LibreTranslate",
"config.locale_country_map": "Objet pour mapper le code local de deux lettres au code du pays",
"config.locales_paths": "Chemin du répertoire de la locale (par rapport à la racine). Les schémas globaux sont acceptés.",
"config.namespace": "Activer les namespaces. Vérifiez la documentation pour plus de détails.",
Expand Down
1 change: 1 addition & 0 deletions locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "",
"config.keystyle": "ロケールキースタイル",
"config.language_tag_system": "",
"config.libretranslate_api_root": "",
"config.locale_country_map": "",
"config.locales_paths": "ロケールディレクトリのパス (プロジェクトルートの相対パス), glob pattern が有効です。",
"config.namespace": "",
Expand Down
1 change: 1 addition & 0 deletions locales/nb-NO.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "",
"config.keystyle": "Oversettelseskodestil",
"config.language_tag_system": "",
"config.libretranslate_api_root": "",
"config.locale_country_map": "",
"config.locales_paths": "Bane til oversettelsesmappe (relativt til prosjektets rotmappe). Glob-mønster er også akseptabelt.",
"config.namespace": "",
Expand Down
1 change: 1 addition & 0 deletions locales/nl-NL.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "",
"config.keystyle": "Locale sleutel stijl",
"config.language_tag_system": "",
"config.libretranslate_api_root": "",
"config.locale_country_map": "",
"config.locales_paths": "Pad naar locale folder (relatief aan project root), glob patroon is acceptabel.",
"config.namespace": "Schakel in om sleutels te onderscheiden op basis van bestandsnaam. Zie documentatie voor meer uitleg.",
Expand Down
1 change: 1 addition & 0 deletions locales/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "",
"config.keystyle": "Estilo de chave de tradução",
"config.language_tag_system": "",
"config.libretranslate_api_root": "",
"config.locale_country_map": "",
"config.locales_paths": "Caminho para os arquivos de tradução (relativo à raiz do projeto). O padrão glob também é aceito.",
"config.namespace": "",
Expand Down
1 change: 1 addition & 0 deletions locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "Ключи, которые нужно отметить как используемые, несмотря на то, что они не отображаются в коде",
"config.keystyle": "Стиль ключа перевода",
"config.language_tag_system": "Использование языковой системы тегов.",
"config.libretranslate_api_root": "",
"config.locale_country_map": "Объект для сопоставления двухбуквенного кода перевода с кодом страны",
"config.locales_paths": "Путь к каталогу переводов (относительно корня проекта). Допускается шаблон соответствия Glob",
"config.namespace": "Включить пространства имен. Подробности смотрите в документации.",
Expand Down
1 change: 1 addition & 0 deletions locales/sv-SE.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "Nycklar att markera som i användning, även fast de inte dyker upp i koden",
"config.keystyle": "locale-fils nyckelstilmall",
"config.language_tag_system": "Språkmärkningssystem som används.",
"config.libretranslate_api_root": "",
"config.locale_country_map": "Ett objekt för att mappa två-bokstäverskod till landskod",
"config.locales_paths": "Sökväg till locale-filer (relativt projektets rot). `glob` mönster är också accepterat.",
"config.namespace": "Aktivera \"namespaces\". Se dokumentation för mer detaljer.",
Expand Down
1 change: 1 addition & 0 deletions locales/tr.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "Kod içerisinde belirtilmeyen ama kullanımda olarak işaretlenecek çeviriler",
"config.keystyle": "Çeviri anahtarı görünümü",
"config.language_tag_system": "Kullandığınız dil eki sistemi",
"config.libretranslate_api_root": "",
"config.locale_country_map": "İki harfli yerel kodunu ülke koduyla eşleştirmek için bir 'object'",
"config.locales_paths": "Çeviri dosyalarının bulunduğu alan (projenin olduğu yere göre). Global patternler de kabul edilmektedir.",
"config.namespace": "Namespace'lerini etkinleştirin. Daha fazla ayrıntı için dokümantasyona göz atın.",
Expand Down
1 change: 1 addition & 0 deletions locales/uk-UA.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "Ключі, які потрібно відзначити як використовувані, незважаючи на те, що вони не відображаються в коді",
"config.keystyle": "Стиль ключа перекладу",
"config.language_tag_system": "Використання мовної системи тегів.",
"config.libretranslate_api_root": "",
"config.locale_country_map": "Об'єкт для зіставлення двобуквеного коду мовного стандарту з кодом країни",
"config.locales_paths": "Шлях до каталогу перекладів (щодо кореня проекту). Допускається шаблон відповідності Glob",
"config.namespace": "Включити `namespace`. Подробиці дивіться в документації.",
Expand Down
1 change: 1 addition & 0 deletions locales/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "尽管代码中没有出现,但仍标记为正在使用的键",
"config.keystyle": "翻译路径格式",
"config.language_tag_system": "语言标签系统",
"config.libretranslate_api_root": "",
"config.locale_country_map": "将两个字母的区域设置代码映射到国家/地区代码的对象",
"config.locales_paths": "翻译文件夹路径 (相对于项目根目录),你也可以使用Glob匹配模式。",
"config.namespace": "启用命名空间。查看文档了解更多详细信息。",
Expand Down
1 change: 1 addition & 0 deletions locales/zh-TW.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"config.keys_in_use": "儘管程式碼中沒有出現,但仍標記為正在使用的鍵",
"config.keystyle": "翻譯路徑格式",
"config.language_tag_system": "語言標籤系統",
"config.libretranslate_api_root": "",
"config.locale_country_map": "將兩個字母的區域設置代碼映射到國家/地區代碼的對象",
"config.locales_paths": "翻譯資料夾路徑 (相對於專案根目錄),你也可以使用Glob匹配模式。",
"config.namespace": "啟用命名空間。\n查看文件了解更多詳細信息。",
Expand Down
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1002,7 +1002,8 @@
"enum": [
"google",
"google-cn",
"deepl"
"deepl",
"libretranslate"
]
},
"default": [
Expand Down Expand Up @@ -1045,6 +1046,11 @@
"default": false,
"description": "%config.deepl_use_free_api_entry%"
},
"i18n-ally.translate.libre.apiRoot": {
"type": "string",
"default": "http://localhost:5000",
"description": "%config.libretranslate_api_root%"
},
"i18n-ally.usage.scanningIgnore": {
"type": "array",
"items": {
Expand Down
4 changes: 4 additions & 0 deletions src/core/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,10 @@ export class Config {
return !!this.getConfig('translate.deepl.enableLog')
}

static get libreTranslateApiRoot() {
return this.getConfig<string | null | undefined>('translate.libre.apiRoot')
}

static get telemetry(): boolean {
return workspace.getConfiguration().get('telemetry.enableTelemetry') as boolean
}
Expand Down
49 changes: 49 additions & 0 deletions src/translators/engines/libretranslate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import axios from 'axios'
import TranslateEngine, { TranslateOptions, TranslateResult } from './base'
import { Config } from '~/core'

export default class LibreTranslate extends TranslateEngine {
apiRoot = 'http://localhost:5000'

async translate(options: TranslateOptions) {
const {
from = 'auto',
to = 'auto',
} = options

let apiRoot = this.apiRoot
if (Config.libreTranslateApiRoot)
apiRoot = Config.libreTranslateApiRoot

const response = await axios.post(`${apiRoot}/translate`, {
q: options.text,
source: from,
target: to,
}, {
headers: {
'Content-Type': 'application/json',
},
},
)

return this.transform(response, options)
}

transform(response: any, options: TranslateOptions): TranslateResult {
const {
text,
to = 'auto',
} = options

const r: TranslateResult = {
text,
to,
from: response.src,
response,
result: [response.data.translatedText],
linkToResult: '',
}

return r
}
}
3 changes: 3 additions & 0 deletions src/translators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import TranslateEngine, { TranslateOptions } from './engines/base'
import GoogleTranslateEngine from './engines/google'
import GoogleTranslateCnEngine from './engines/google-cn'
import DeepLTranslateEngine from './engines/deepl'
import LibreTranslateEngine from './engines/libretranslate'

export class Translator {
engines: Record<string, TranslateEngine> ={
'google': new GoogleTranslateEngine(),
'google-cn': new GoogleTranslateCnEngine(),
'deepl': new DeepLTranslateEngine(),
'libretranslate': new LibreTranslateEngine(),
}

async translate(options: TranslateOptions & { engine: string }) {
Expand All @@ -21,6 +23,7 @@ export {
GoogleTranslateEngine,
GoogleTranslateCnEngine,
DeepLTranslateEngine,
LibreTranslateEngine,
}

export * from './engines/base'

0 comments on commit ab3451d

Please sign in to comment.