Skip to content

Commit

Permalink
Improved LibreTranslate support
Browse files Browse the repository at this point in the history
  • Loading branch information
PJ-Finlay committed Jun 16, 2021
1 parent 39f517d commit 2f81965
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 27 deletions.
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
click
lxml
requests
libretranslatepy==2.1.1
42 changes: 15 additions & 27 deletions translate/providers/libre.py
Original file line number Diff line number Diff line change
@@ -1,47 +1,35 @@
#!/usr/bin/env python
# encoding: utf-8
import requests
from libretranslatepy import LibreTranslateAPI
import json

from .base import BaseProvider
from ..exceptions import TranslationError


class LibreProvider(BaseProvider):
"""
@LibreProvider: This is a integration with LibreTranslate Translator API.
@LibreProvider: This is a integration with LibreTranslate translation API.
Website: https://libretranslate.com/
Documentation: https://libretranslate.com/docs/
Github: https://github.com/uav4geo/LibreTranslate
Github: https://github.com/LibreTranslate/LibreTranslate
"""

name = "Libre"

def _make_request(self, text):
params = {
"api_key": self.secret_access_key,
"target": self.to_lang,
"q": text,
"source": self.from_lang,
}

response = requests.post(
self.base_url, params=params, headers=self.headers, json=[{}]
)
return response.json()
def __init__(self, to_lang, from_lang='en', secret_access_key=None, region=None, base_url=None, **kwargs):
super().__init__(to_lang)
self.base_url = base_url
self.api = LibreTranslateAPI(base_url, secret_access_key)

def get_translation(self, text):
if self.base_url == "":
raise TranslationError(
"""
Please provide a base_url in constructor
for example,
translator = Translator(to_lang = "en" , base_url = "http://localhost:5000/")
"""
)
data = self._make_request(text)
if self.from_lang == 'autodetect':
from_lang = self.api.detect(text)[0]['language']
else:
from_lang = self.from_lang

if "error" in data:
raise TranslationError(data["error"])
try:
return self.api.translate(text, from_lang, self.to_lang)
except Exception as e:
raise TranslationError(e)

return data["translatedText"]

0 comments on commit 2f81965

Please sign in to comment.