nidhal baccouri
commited on
Commit
·
d03a2fc
1
Parent(s):
2bbc526
simplified code and enhanced consistency
Browse files- deep_translator/base.py +8 -4
- deep_translator/cli.py +4 -4
- deep_translator/deepl.py +4 -4
- deep_translator/detection.py +1 -0
- deep_translator/google_trans.py +13 -9
- deep_translator/libre.py +3 -3
- deep_translator/linguee.py +4 -4
- deep_translator/microsoft.py +2 -2
- deep_translator/mymemory.py +4 -4
- deep_translator/papago.py +3 -5
- deep_translator/pons.py +12 -13
- deep_translator/qcri.py +2 -2
- deep_translator/yandex.py +4 -4
- examples/trans.py +10 -5
deep_translator/base.py
CHANGED
|
@@ -15,22 +15,26 @@ class BaseTranslator(ABC):
|
|
| 15 |
payload_key=None,
|
| 16 |
element_tag=None,
|
| 17 |
element_query=None,
|
| 18 |
-
languages=
|
| 19 |
**url_params):
|
| 20 |
"""
|
| 21 |
@param source: source language to translate from
|
| 22 |
@param target: target language to translate to
|
| 23 |
"""
|
| 24 |
-
self.
|
|
|
|
|
|
|
|
|
|
| 25 |
self._source, self._target = self._map_language_to_code(source, target)
|
| 26 |
self._url_params = url_params
|
| 27 |
self._element_tag = element_tag
|
| 28 |
self._element_query = element_query
|
| 29 |
self.payload_key = payload_key
|
| 30 |
-
self.languages: dict = languages
|
| 31 |
-
self.supported_languages: list = list(self.languages.keys())
|
| 32 |
super().__init__()
|
| 33 |
|
|
|
|
|
|
|
|
|
|
| 34 |
def _map_language_to_code(self, *languages):
|
| 35 |
"""
|
| 36 |
map language to its corresponding code (abbreviation) if the language was passed by its full name by the user
|
|
|
|
| 15 |
payload_key=None,
|
| 16 |
element_tag=None,
|
| 17 |
element_query=None,
|
| 18 |
+
languages=None,
|
| 19 |
**url_params):
|
| 20 |
"""
|
| 21 |
@param source: source language to translate from
|
| 22 |
@param target: target language to translate to
|
| 23 |
"""
|
| 24 |
+
self._base_url = base_url
|
| 25 |
+
self.languages: dict = GOOGLE_LANGUAGES_TO_CODES if not languages else languages
|
| 26 |
+
self.supported_languages: list = list(self.languages.keys())
|
| 27 |
+
|
| 28 |
self._source, self._target = self._map_language_to_code(source, target)
|
| 29 |
self._url_params = url_params
|
| 30 |
self._element_tag = element_tag
|
| 31 |
self._element_query = element_query
|
| 32 |
self.payload_key = payload_key
|
|
|
|
|
|
|
| 33 |
super().__init__()
|
| 34 |
|
| 35 |
+
def _type(self):
|
| 36 |
+
return self.__class__.__name__
|
| 37 |
+
|
| 38 |
def _map_language_to_code(self, *languages):
|
| 39 |
"""
|
| 40 |
map language to its corresponding code (abbreviation) if the language was passed by its full name by the user
|
deep_translator/cli.py
CHANGED
|
@@ -4,14 +4,14 @@ from .base import BaseTranslator
|
|
| 4 |
|
| 5 |
|
| 6 |
class CLI(object):
|
| 7 |
-
translators_dict =
|
|
|
|
|
|
|
| 8 |
translator = None
|
| 9 |
|
| 10 |
def __init__(self, custom_args=None):
|
| 11 |
self.custom_args = custom_args
|
| 12 |
self.args = self.parse_args()
|
| 13 |
-
print(f'translators_dict: {self.translators_dict}')
|
| 14 |
-
exit()
|
| 15 |
translator_class = self.translators_dict.get(self.args.translator, None)
|
| 16 |
if not translator_class:
|
| 17 |
raise Exception(f"Translator {self.args.translator} is not supported."
|
|
@@ -25,7 +25,7 @@ class CLI(object):
|
|
| 25 |
"""
|
| 26 |
res = self.translator.translate(self.args.text)
|
| 27 |
print("Translation from {} to {}".format(self.args.source, self.args.target))
|
| 28 |
-
print("-"*50)
|
| 29 |
print("Translation result: {}".format(res))
|
| 30 |
|
| 31 |
def get_supported_languages(self):
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
class CLI(object):
|
| 7 |
+
translators_dict = {
|
| 8 |
+
translator.__name__.replace('Translator', '').lower():
|
| 9 |
+
translator for translator in BaseTranslator.__subclasses__()}
|
| 10 |
translator = None
|
| 11 |
|
| 12 |
def __init__(self, custom_args=None):
|
| 13 |
self.custom_args = custom_args
|
| 14 |
self.args = self.parse_args()
|
|
|
|
|
|
|
| 15 |
translator_class = self.translators_dict.get(self.args.translator, None)
|
| 16 |
if not translator_class:
|
| 17 |
raise Exception(f"Translator {self.args.translator} is not supported."
|
|
|
|
| 25 |
"""
|
| 26 |
res = self.translator.translate(self.args.text)
|
| 27 |
print("Translation from {} to {}".format(self.args.source, self.args.target))
|
| 28 |
+
print("-" * 50)
|
| 29 |
print("Translation result: {}".format(res))
|
| 30 |
|
| 31 |
def get_supported_languages(self):
|
deep_translator/deepl.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
import requests
|
| 2 |
|
| 3 |
-
from validate import is_empty
|
| 4 |
from .constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE
|
| 5 |
from .exceptions import (ServerException,
|
| 6 |
TranslationNotFound,
|
|
@@ -25,10 +25,10 @@ class DeepL(BaseTranslator):
|
|
| 25 |
self.version = 'v2'
|
| 26 |
self.api_key = api_key
|
| 27 |
if use_free_api:
|
| 28 |
-
self.
|
| 29 |
"DEEPL_FREE").format(version=self.version)
|
| 30 |
else:
|
| 31 |
-
self.
|
| 32 |
"DEEPL").format(version=self.version)
|
| 33 |
super().__init__(source=source,
|
| 34 |
target=target,
|
|
@@ -53,7 +53,7 @@ class DeepL(BaseTranslator):
|
|
| 53 |
# Do the request and check the connection.
|
| 54 |
try:
|
| 55 |
response = requests.get(
|
| 56 |
-
self.
|
| 57 |
except ConnectionError:
|
| 58 |
raise ServerException(503)
|
| 59 |
# If the answer is not success, raise server exception.
|
|
|
|
| 1 |
import requests
|
| 2 |
|
| 3 |
+
from .validate import is_empty
|
| 4 |
from .constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE
|
| 5 |
from .exceptions import (ServerException,
|
| 6 |
TranslationNotFound,
|
|
|
|
| 25 |
self.version = 'v2'
|
| 26 |
self.api_key = api_key
|
| 27 |
if use_free_api:
|
| 28 |
+
self._base_url = BASE_URLS.get(
|
| 29 |
"DEEPL_FREE").format(version=self.version)
|
| 30 |
else:
|
| 31 |
+
self._base_url = BASE_URLS.get(
|
| 32 |
"DEEPL").format(version=self.version)
|
| 33 |
super().__init__(source=source,
|
| 34 |
target=target,
|
|
|
|
| 53 |
# Do the request and check the connection.
|
| 54 |
try:
|
| 55 |
response = requests.get(
|
| 56 |
+
self._base_url + translate_endpoint, params=params)
|
| 57 |
except ConnectionError:
|
| 58 |
raise ServerException(503)
|
| 59 |
# If the answer is not success, raise server exception.
|
deep_translator/detection.py
CHANGED
|
@@ -7,6 +7,7 @@ from requests.exceptions import HTTPError
|
|
| 7 |
# Module global config
|
| 8 |
config = {"url": 'https://ws.detectlanguage.com/0.2/detect',"headers": {'User-Agent': 'Detect Language API Python Client 1.4.0','Authorization': 'Bearer {}',}}
|
| 9 |
|
|
|
|
| 10 |
def get_request_body(text, api_key, *args, **kwargs):
|
| 11 |
"""
|
| 12 |
send a request and return the response body parsed as dictionary
|
|
|
|
| 7 |
# Module global config
|
| 8 |
config = {"url": 'https://ws.detectlanguage.com/0.2/detect',"headers": {'User-Agent': 'Detect Language API Python Client 1.4.0','Authorization': 'Bearer {}',}}
|
| 9 |
|
| 10 |
+
|
| 11 |
def get_request_body(text, api_key, *args, **kwargs):
|
| 12 |
"""
|
| 13 |
send a request and return the response body parsed as dictionary
|
deep_translator/google_trans.py
CHANGED
|
@@ -2,10 +2,10 @@
|
|
| 2 |
google translator API
|
| 3 |
"""
|
| 4 |
|
| 5 |
-
from .constants import BASE_URLS
|
| 6 |
-
from .exceptions import TooManyRequests, TranslationNotFound, RequestError
|
| 7 |
-
from .base import BaseTranslator
|
| 8 |
-
from .validate import validate_input, is_empty
|
| 9 |
from bs4 import BeautifulSoup
|
| 10 |
import requests
|
| 11 |
|
|
@@ -20,16 +20,13 @@ class GoogleTranslator(BaseTranslator):
|
|
| 20 |
@param source: source language to translate from
|
| 21 |
@param target: target language to translate to
|
| 22 |
"""
|
| 23 |
-
self.__base_url = BASE_URLS.get("GOOGLE_TRANSLATE")
|
| 24 |
self.proxies = proxies
|
| 25 |
-
super().__init__(base_url=
|
| 26 |
source=source,
|
| 27 |
target=target,
|
| 28 |
element_tag='div',
|
| 29 |
element_query={"class": "t0"},
|
| 30 |
payload_key='q', # key of text in the url
|
| 31 |
-
tl=self._target,
|
| 32 |
-
sl=self._source,
|
| 33 |
**kwargs)
|
| 34 |
|
| 35 |
self._alt_element_query = {"class": "result-container"}
|
|
@@ -45,11 +42,13 @@ class GoogleTranslator(BaseTranslator):
|
|
| 45 |
|
| 46 |
if validate_input(text):
|
| 47 |
text = text.strip()
|
|
|
|
|
|
|
| 48 |
|
| 49 |
if self.payload_key:
|
| 50 |
self._url_params[self.payload_key] = text
|
| 51 |
|
| 52 |
-
response = requests.get(self.
|
| 53 |
params=self._url_params,
|
| 54 |
proxies=self.proxies)
|
| 55 |
if response.status_code == 429:
|
|
@@ -96,3 +95,8 @@ class GoogleTranslator(BaseTranslator):
|
|
| 96 |
@return: list of translations
|
| 97 |
"""
|
| 98 |
return self._translate_batch(batch, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
google translator API
|
| 3 |
"""
|
| 4 |
|
| 5 |
+
from deep_translator.constants import BASE_URLS
|
| 6 |
+
from deep_translator.exceptions import TooManyRequests, TranslationNotFound, RequestError
|
| 7 |
+
from deep_translator.base import BaseTranslator
|
| 8 |
+
from deep_translator.validate import validate_input, is_empty
|
| 9 |
from bs4 import BeautifulSoup
|
| 10 |
import requests
|
| 11 |
|
|
|
|
| 20 |
@param source: source language to translate from
|
| 21 |
@param target: target language to translate to
|
| 22 |
"""
|
|
|
|
| 23 |
self.proxies = proxies
|
| 24 |
+
super().__init__(base_url=BASE_URLS.get("GOOGLE_TRANSLATE"),
|
| 25 |
source=source,
|
| 26 |
target=target,
|
| 27 |
element_tag='div',
|
| 28 |
element_query={"class": "t0"},
|
| 29 |
payload_key='q', # key of text in the url
|
|
|
|
|
|
|
| 30 |
**kwargs)
|
| 31 |
|
| 32 |
self._alt_element_query = {"class": "result-container"}
|
|
|
|
| 42 |
|
| 43 |
if validate_input(text):
|
| 44 |
text = text.strip()
|
| 45 |
+
self._url_params['tl'] = self._target
|
| 46 |
+
self._url_params['sl'] = self._source
|
| 47 |
|
| 48 |
if self.payload_key:
|
| 49 |
self._url_params[self.payload_key] = text
|
| 50 |
|
| 51 |
+
response = requests.get(self._base_url,
|
| 52 |
params=self._url_params,
|
| 53 |
proxies=self.proxies)
|
| 54 |
if response.status_code == 429:
|
|
|
|
| 95 |
@return: list of translations
|
| 96 |
"""
|
| 97 |
return self._translate_batch(batch, **kwargs)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == '__main__':
|
| 101 |
+
t = GoogleTranslator().translate("hallo welt")
|
| 102 |
+
print("translation: ", t)
|
deep_translator/libre.py
CHANGED
|
@@ -4,7 +4,7 @@ LibreTranslate API
|
|
| 4 |
|
| 5 |
import requests
|
| 6 |
|
| 7 |
-
from validate import is_empty
|
| 8 |
from .base import BaseTranslator
|
| 9 |
from .constants import BASE_URLS,LIBRE_LANGUAGES_TO_CODES
|
| 10 |
from .exceptions import (ServerException,
|
|
@@ -26,7 +26,7 @@ class LibreTranslator(BaseTranslator):
|
|
| 26 |
"""
|
| 27 |
if not api_key:
|
| 28 |
raise ServerException(401)
|
| 29 |
-
self.
|
| 30 |
self.api_key = api_key
|
| 31 |
super().__init__(source=source,
|
| 32 |
target=target,
|
|
@@ -53,7 +53,7 @@ class LibreTranslator(BaseTranslator):
|
|
| 53 |
params["api_key"] = self.api_key
|
| 54 |
# Do the request and check the connection.
|
| 55 |
try:
|
| 56 |
-
response = requests.post(self.
|
| 57 |
except ConnectionError:
|
| 58 |
raise ServerException(503)
|
| 59 |
# If the answer is not success, raise server exception.
|
|
|
|
| 4 |
|
| 5 |
import requests
|
| 6 |
|
| 7 |
+
from .validate import is_empty
|
| 8 |
from .base import BaseTranslator
|
| 9 |
from .constants import BASE_URLS,LIBRE_LANGUAGES_TO_CODES
|
| 10 |
from .exceptions import (ServerException,
|
|
|
|
| 26 |
"""
|
| 27 |
if not api_key:
|
| 28 |
raise ServerException(401)
|
| 29 |
+
self._base_url = BASE_URLS.get("LIBRE")
|
| 30 |
self.api_key = api_key
|
| 31 |
super().__init__(source=source,
|
| 32 |
target=target,
|
|
|
|
| 53 |
params["api_key"] = self.api_key
|
| 54 |
# Do the request and check the connection.
|
| 55 |
try:
|
| 56 |
+
response = requests.post(self._base_url + translate_endpoint, params=params)
|
| 57 |
except ConnectionError:
|
| 58 |
raise ServerException(503)
|
| 59 |
# If the answer is not success, raise server exception.
|
deep_translator/linguee.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
linguee translator API
|
| 3 |
"""
|
| 4 |
-
from validate import validate_input, is_empty
|
| 5 |
from .constants import BASE_URLS, LINGUEE_LANGUAGES_TO_CODES
|
| 6 |
from .exceptions import (
|
| 7 |
TranslationNotFound,
|
|
@@ -25,9 +25,9 @@ class LingueeTranslator(BaseTranslator):
|
|
| 25 |
@param source: source language to translate from
|
| 26 |
@param target: target language to translate to
|
| 27 |
"""
|
| 28 |
-
self.
|
| 29 |
self.proxies = proxies
|
| 30 |
-
super().__init__(base_url=self.
|
| 31 |
source=source,
|
| 32 |
target=target,
|
| 33 |
languages=LINGUEE_LANGUAGES_TO_CODES,
|
|
@@ -50,7 +50,7 @@ class LingueeTranslator(BaseTranslator):
|
|
| 50 |
|
| 51 |
if validate_input(word, max_chars=50):
|
| 52 |
# %s-%s/translation/%s.html
|
| 53 |
-
url = "{}{}-{}/translation/{}.html".format(self.
|
| 54 |
url = requote_uri(url)
|
| 55 |
response = requests.get(url, proxies=self.proxies)
|
| 56 |
|
|
|
|
| 1 |
"""
|
| 2 |
linguee translator API
|
| 3 |
"""
|
| 4 |
+
from .validate import validate_input, is_empty
|
| 5 |
from .constants import BASE_URLS, LINGUEE_LANGUAGES_TO_CODES
|
| 6 |
from .exceptions import (
|
| 7 |
TranslationNotFound,
|
|
|
|
| 25 |
@param source: source language to translate from
|
| 26 |
@param target: target language to translate to
|
| 27 |
"""
|
| 28 |
+
self._base_url = BASE_URLS.get("LINGUEE")
|
| 29 |
self.proxies = proxies
|
| 30 |
+
super().__init__(base_url=self._base_url,
|
| 31 |
source=source,
|
| 32 |
target=target,
|
| 33 |
languages=LINGUEE_LANGUAGES_TO_CODES,
|
|
|
|
| 50 |
|
| 51 |
if validate_input(word, max_chars=50):
|
| 52 |
# %s-%s/translation/%s.html
|
| 53 |
+
url = "{}{}-{}/translation/{}.html".format(self._base_url, self._source, self._target, word)
|
| 54 |
url = requote_uri(url)
|
| 55 |
response = requests.get(url, proxies=self.proxies)
|
| 56 |
|
deep_translator/microsoft.py
CHANGED
|
@@ -35,7 +35,7 @@ class MicrosoftTranslator(BaseTranslator):
|
|
| 35 |
if region:
|
| 36 |
self.region = region
|
| 37 |
self.headers["Ocp-Apim-Subscription-Region"] = self.region
|
| 38 |
-
self.
|
| 39 |
super().__init__(
|
| 40 |
source=source,
|
| 41 |
target=target,
|
|
@@ -66,7 +66,7 @@ class MicrosoftTranslator(BaseTranslator):
|
|
| 66 |
|
| 67 |
valid_microsoft_json = [{'text': text}]
|
| 68 |
try:
|
| 69 |
-
requested = requests.post(self.
|
| 70 |
params=self._url_params,
|
| 71 |
headers=self.headers,
|
| 72 |
json=valid_microsoft_json,
|
|
|
|
| 35 |
if region:
|
| 36 |
self.region = region
|
| 37 |
self.headers["Ocp-Apim-Subscription-Region"] = self.region
|
| 38 |
+
self._base_url = BASE_URLS.get("MICROSOFT_TRANSLATE")
|
| 39 |
super().__init__(
|
| 40 |
source=source,
|
| 41 |
target=target,
|
|
|
|
| 66 |
|
| 67 |
valid_microsoft_json = [{'text': text}]
|
| 68 |
try:
|
| 69 |
+
requested = requests.post(self._base_url,
|
| 70 |
params=self._url_params,
|
| 71 |
headers=self.headers,
|
| 72 |
json=valid_microsoft_json,
|
deep_translator/mymemory.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
mymemory translator API
|
| 3 |
"""
|
| 4 |
-
from validate import is_empty, validate_input
|
| 5 |
from .constants import BASE_URLS
|
| 6 |
from .exceptions import (
|
| 7 |
TranslationNotFound,
|
|
@@ -20,10 +20,10 @@ class MyMemoryTranslator(BaseTranslator):
|
|
| 20 |
@param source: source language to translate from
|
| 21 |
@param target: target language to translate to
|
| 22 |
"""
|
| 23 |
-
self.
|
| 24 |
self.proxies = proxies
|
| 25 |
self.email = kwargs.get('email', None)
|
| 26 |
-
super(MyMemoryTranslator, self).__init__(base_url=self.
|
| 27 |
source=self._source,
|
| 28 |
target=self._target,
|
| 29 |
payload_key='q',
|
|
@@ -49,7 +49,7 @@ class MyMemoryTranslator(BaseTranslator):
|
|
| 49 |
if self.email:
|
| 50 |
self._url_params['de'] = self.email
|
| 51 |
|
| 52 |
-
response = requests.get(self.
|
| 53 |
params=self._url_params,
|
| 54 |
proxies=self.proxies)
|
| 55 |
|
|
|
|
| 1 |
"""
|
| 2 |
mymemory translator API
|
| 3 |
"""
|
| 4 |
+
from .validate import is_empty, validate_input
|
| 5 |
from .constants import BASE_URLS
|
| 6 |
from .exceptions import (
|
| 7 |
TranslationNotFound,
|
|
|
|
| 20 |
@param source: source language to translate from
|
| 21 |
@param target: target language to translate to
|
| 22 |
"""
|
| 23 |
+
self._base_url = BASE_URLS.get("MYMEMORY")
|
| 24 |
self.proxies = proxies
|
| 25 |
self.email = kwargs.get('email', None)
|
| 26 |
+
super(MyMemoryTranslator, self).__init__(base_url=self._base_url,
|
| 27 |
source=self._source,
|
| 28 |
target=self._target,
|
| 29 |
payload_key='q',
|
|
|
|
| 49 |
if self.email:
|
| 50 |
self._url_params['de'] = self.email
|
| 51 |
|
| 52 |
+
response = requests.get(self._base_url,
|
| 53 |
params=self._url_params,
|
| 54 |
proxies=self.proxies)
|
| 55 |
|
deep_translator/papago.py
CHANGED
|
@@ -3,11 +3,9 @@ google translator API
|
|
| 3 |
"""
|
| 4 |
import json
|
| 5 |
from .constants import BASE_URLS, PAPAGO_LANGUAGE_TO_CODE
|
| 6 |
-
from .exceptions import
|
| 7 |
from .base import BaseTranslator
|
| 8 |
import requests
|
| 9 |
-
import warnings
|
| 10 |
-
import logging
|
| 11 |
|
| 12 |
|
| 13 |
class PapagoTranslator(BaseTranslator):
|
|
@@ -24,7 +22,7 @@ class PapagoTranslator(BaseTranslator):
|
|
| 24 |
raise Exception(
|
| 25 |
"Please pass your client id and secret key! visit the papago website for more infos")
|
| 26 |
|
| 27 |
-
self.
|
| 28 |
self.client_id = client_id
|
| 29 |
self.secret_key = secret_key
|
| 30 |
super().__init__(
|
|
@@ -52,7 +50,7 @@ class PapagoTranslator(BaseTranslator):
|
|
| 52 |
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
|
| 53 |
}
|
| 54 |
response = requests.post(
|
| 55 |
-
self.
|
| 56 |
if response.status_code != 200:
|
| 57 |
raise Exception(
|
| 58 |
f'Translation error! -> status code: {response.status_code}')
|
|
|
|
| 3 |
"""
|
| 4 |
import json
|
| 5 |
from .constants import BASE_URLS, PAPAGO_LANGUAGE_TO_CODE
|
| 6 |
+
from .exceptions import TranslationNotFound
|
| 7 |
from .base import BaseTranslator
|
| 8 |
import requests
|
|
|
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
class PapagoTranslator(BaseTranslator):
|
|
|
|
| 22 |
raise Exception(
|
| 23 |
"Please pass your client id and secret key! visit the papago website for more infos")
|
| 24 |
|
| 25 |
+
self._base_url = BASE_URLS.get("PAPAGO_API")
|
| 26 |
self.client_id = client_id
|
| 27 |
self.secret_key = secret_key
|
| 28 |
super().__init__(
|
|
|
|
| 50 |
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
|
| 51 |
}
|
| 52 |
response = requests.post(
|
| 53 |
+
self._base_url, headers=headers, data=payload)
|
| 54 |
if response.status_code != 200:
|
| 55 |
raise Exception(
|
| 56 |
f'Translation error! -> status code: {response.status_code}')
|
deep_translator/pons.py
CHANGED
|
@@ -4,9 +4,9 @@ pons translator API
|
|
| 4 |
from bs4 import BeautifulSoup
|
| 5 |
import requests
|
| 6 |
|
| 7 |
-
from validate import validate_input, is_empty
|
| 8 |
-
from .constants import BASE_URLS,
|
| 9 |
-
from .exceptions import (
|
| 10 |
TranslationNotFound,
|
| 11 |
NotValidPayload,
|
| 12 |
ElementNotFoundInGetRequest,
|
|
@@ -26,15 +26,16 @@ class PonsTranslator(BaseTranslator):
|
|
| 26 |
@param source: source language to translate from
|
| 27 |
@param target: target language to translate to
|
| 28 |
"""
|
| 29 |
-
self.
|
| 30 |
self.proxies = proxies
|
| 31 |
-
super().__init__(base_url=self.
|
| 32 |
-
languages=
|
| 33 |
-
source=
|
| 34 |
-
target=
|
| 35 |
payload_key=None,
|
| 36 |
element_tag='div',
|
| 37 |
-
element_query={"class": "target"}
|
|
|
|
| 38 |
)
|
| 39 |
|
| 40 |
def translate(self, word, return_all=False, **kwargs):
|
|
@@ -50,7 +51,7 @@ class PonsTranslator(BaseTranslator):
|
|
| 50 |
return word
|
| 51 |
|
| 52 |
if validate_input(word, max_chars=50):
|
| 53 |
-
url = "{}{}-{}/{}".format(self.
|
| 54 |
url = requote_uri(url)
|
| 55 |
response = requests.get(url, proxies=self.proxies)
|
| 56 |
|
|
@@ -70,9 +71,7 @@ class PonsTranslator(BaseTranslator):
|
|
| 70 |
for el in elements:
|
| 71 |
temp = ''
|
| 72 |
for e in el.findAll('a'):
|
| 73 |
-
|
| 74 |
-
if e and "/translate/{}-{}/".format(self._target, self._source) in e.get('href'):
|
| 75 |
-
temp += e.get_text() + ' '
|
| 76 |
filtered_elements.append(temp)
|
| 77 |
|
| 78 |
if not filtered_elements:
|
|
|
|
| 4 |
from bs4 import BeautifulSoup
|
| 5 |
import requests
|
| 6 |
|
| 7 |
+
from .validate import validate_input, is_empty
|
| 8 |
+
from .constants import BASE_URLS, PONS_CODES_TO_LANGUAGES
|
| 9 |
+
from .exceptions import (
|
| 10 |
TranslationNotFound,
|
| 11 |
NotValidPayload,
|
| 12 |
ElementNotFoundInGetRequest,
|
|
|
|
| 26 |
@param source: source language to translate from
|
| 27 |
@param target: target language to translate to
|
| 28 |
"""
|
| 29 |
+
self._base_url = BASE_URLS.get("PONS")
|
| 30 |
self.proxies = proxies
|
| 31 |
+
super().__init__(base_url=self._base_url,
|
| 32 |
+
languages=PONS_CODES_TO_LANGUAGES,
|
| 33 |
+
source=source,
|
| 34 |
+
target=target,
|
| 35 |
payload_key=None,
|
| 36 |
element_tag='div',
|
| 37 |
+
element_query={"class": "target"},
|
| 38 |
+
**kwargs
|
| 39 |
)
|
| 40 |
|
| 41 |
def translate(self, word, return_all=False, **kwargs):
|
|
|
|
| 51 |
return word
|
| 52 |
|
| 53 |
if validate_input(word, max_chars=50):
|
| 54 |
+
url = "{}{}-{}/{}".format(self._base_url, self._source, self._target, word)
|
| 55 |
url = requote_uri(url)
|
| 56 |
response = requests.get(url, proxies=self.proxies)
|
| 57 |
|
|
|
|
| 71 |
for el in elements:
|
| 72 |
temp = ''
|
| 73 |
for e in el.findAll('a'):
|
| 74 |
+
temp += e.get_text() + ' '
|
|
|
|
|
|
|
| 75 |
filtered_elements.append(temp)
|
| 76 |
|
| 77 |
if not filtered_elements:
|
deep_translator/qcri.py
CHANGED
|
@@ -17,7 +17,7 @@ class QCRI(BaseTranslator):
|
|
| 17 |
|
| 18 |
if not api_key:
|
| 19 |
raise ServerException(401)
|
| 20 |
-
self.
|
| 21 |
self.api_key = api_key
|
| 22 |
self.api_endpoints = {
|
| 23 |
"get_languages": "getLanguagePairs",
|
|
@@ -39,7 +39,7 @@ class QCRI(BaseTranslator):
|
|
| 39 |
if not params:
|
| 40 |
params = self.params
|
| 41 |
try:
|
| 42 |
-
res = requests.get(self.
|
| 43 |
endpoint=self.api_endpoints[endpoint]), params=params)
|
| 44 |
return res.text if return_text else res
|
| 45 |
except Exception as e:
|
|
|
|
| 17 |
|
| 18 |
if not api_key:
|
| 19 |
raise ServerException(401)
|
| 20 |
+
self._base_url = BASE_URLS.get("QCRI")
|
| 21 |
self.api_key = api_key
|
| 22 |
self.api_endpoints = {
|
| 23 |
"get_languages": "getLanguagePairs",
|
|
|
|
| 39 |
if not params:
|
| 40 |
params = self.params
|
| 41 |
try:
|
| 42 |
+
res = requests.get(self._base_url.format(
|
| 43 |
endpoint=self.api_endpoints[endpoint]), params=params)
|
| 44 |
return res.text if return_text else res
|
| 45 |
except Exception as e:
|
deep_translator/yandex.py
CHANGED
|
@@ -19,7 +19,7 @@ class YandexTranslator(BaseTranslator):
|
|
| 19 |
"""
|
| 20 |
if not api_key:
|
| 21 |
raise ServerException(401)
|
| 22 |
-
self.
|
| 23 |
self.api_key = api_key
|
| 24 |
self.api_version = "v1.5"
|
| 25 |
self.api_endpoints = {
|
|
@@ -44,7 +44,7 @@ class YandexTranslator(BaseTranslator):
|
|
| 44 |
def dirs(self, proxies=None):
|
| 45 |
|
| 46 |
try:
|
| 47 |
-
url = self.
|
| 48 |
version=self.api_version, endpoint="getLangs")
|
| 49 |
print("url: ", url)
|
| 50 |
response = requests.get(
|
|
@@ -66,7 +66,7 @@ class YandexTranslator(BaseTranslator):
|
|
| 66 |
"key": self.api_key,
|
| 67 |
}
|
| 68 |
try:
|
| 69 |
-
url = self.
|
| 70 |
version=self.api_version, endpoint="detect")
|
| 71 |
response = requests.post(url, data=params, proxies=proxies)
|
| 72 |
|
|
@@ -94,7 +94,7 @@ class YandexTranslator(BaseTranslator):
|
|
| 94 |
"key": self.api_key
|
| 95 |
}
|
| 96 |
try:
|
| 97 |
-
url = self.
|
| 98 |
version=self.api_version, endpoint="translate")
|
| 99 |
response = requests.post(url, data=params, proxies=proxies)
|
| 100 |
except ConnectionError:
|
|
|
|
| 19 |
"""
|
| 20 |
if not api_key:
|
| 21 |
raise ServerException(401)
|
| 22 |
+
self._base_url = BASE_URLS.get("YANDEX")
|
| 23 |
self.api_key = api_key
|
| 24 |
self.api_version = "v1.5"
|
| 25 |
self.api_endpoints = {
|
|
|
|
| 44 |
def dirs(self, proxies=None):
|
| 45 |
|
| 46 |
try:
|
| 47 |
+
url = self._base_url.format(
|
| 48 |
version=self.api_version, endpoint="getLangs")
|
| 49 |
print("url: ", url)
|
| 50 |
response = requests.get(
|
|
|
|
| 66 |
"key": self.api_key,
|
| 67 |
}
|
| 68 |
try:
|
| 69 |
+
url = self._base_url.format(
|
| 70 |
version=self.api_version, endpoint="detect")
|
| 71 |
response = requests.post(url, data=params, proxies=proxies)
|
| 72 |
|
|
|
|
| 94 |
"key": self.api_key
|
| 95 |
}
|
| 96 |
try:
|
| 97 |
+
url = self._base_url.format(
|
| 98 |
version=self.api_version, endpoint="translate")
|
| 99 |
response = requests.post(url, data=params, proxies=proxies)
|
| 100 |
except ConnectionError:
|
examples/trans.py
CHANGED
|
@@ -5,12 +5,16 @@ from deep_translator import GoogleTranslator, PonsTranslator, LingueeTranslator
|
|
| 5 |
|
| 6 |
english_text = 'happy coding'
|
| 7 |
chinese_text = '這很好'
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
|
|
|
| 14 |
|
| 15 |
# examples using linguee:
|
| 16 |
text = 'cute'
|
|
@@ -19,5 +23,6 @@ print("Using Linguee ==> the translated text: ", translated)
|
|
| 19 |
|
| 20 |
# examples using pons:
|
| 21 |
text = 'good'
|
| 22 |
-
translated = PonsTranslator(source='
|
| 23 |
print("using Pons ==> the translated text: ", translated)
|
|
|
|
|
|
| 5 |
|
| 6 |
english_text = 'happy coding'
|
| 7 |
chinese_text = '這很好'
|
| 8 |
+
translator = GoogleTranslator(source='english', target='german')
|
| 9 |
+
result1 = translator.translate(text=english_text)
|
| 10 |
+
result2 = translator.translate(text=chinese_text)
|
| 11 |
|
| 12 |
+
print(f"original english text: {english_text} | translated text: {result1}")
|
| 13 |
+
print(f"original chinese text: {chinese_text} | translated text: {result2}")
|
| 14 |
|
| 15 |
+
# file translation
|
| 16 |
+
result_file = translator.translate_file('./test.txt')
|
| 17 |
+
print("file translation: ", result_file)
|
| 18 |
|
| 19 |
# examples using linguee:
|
| 20 |
text = 'cute'
|
|
|
|
| 23 |
|
| 24 |
# examples using pons:
|
| 25 |
text = 'good'
|
| 26 |
+
translated = PonsTranslator(source='en', target='ar').translate(word=text)
|
| 27 |
print("using Pons ==> the translated text: ", translated)
|
| 28 |
+
|