Merge pull request #48 from RubenEu/topic-deepl
Browse files- deep_translator/constants.py +29 -0
- deep_translator/deepl.py +34 -22
- deep_translator/exceptions.py +6 -0
- deep_translator/tests/test_deepl.py +29 -0
deep_translator/constants.py
CHANGED
@@ -191,3 +191,32 @@ microsoft_languages_response = requests.get(microsoft_languages_api_url)
|
|
191 |
translation_dict = microsoft_languages_response.json()['translation']
|
192 |
|
193 |
MICROSOFT_CODES_TO_LANGUAGES = {translation_dict[k]['name'].lower(): k for k in translation_dict.keys()}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
191 |
translation_dict = microsoft_languages_response.json()['translation']
|
192 |
|
193 |
MICROSOFT_CODES_TO_LANGUAGES = {translation_dict[k]['name'].lower(): k for k in translation_dict.keys()}
|
194 |
+
|
195 |
+
DEEPL_LANGUAGE_TO_CODE = {
|
196 |
+
"bulgarian": "bg",
|
197 |
+
"czech": "cs",
|
198 |
+
"danish": "da",
|
199 |
+
"german": "de",
|
200 |
+
"greek": "el",
|
201 |
+
"english": "en",
|
202 |
+
"spanish": "es",
|
203 |
+
"estonian": "et",
|
204 |
+
"finnish": "fi",
|
205 |
+
"french": "fr",
|
206 |
+
"hungarian": "hu",
|
207 |
+
"italian": "it",
|
208 |
+
"japanese": "ja",
|
209 |
+
"lithuanian": "lt",
|
210 |
+
"latvian": "lv",
|
211 |
+
"dutch": "nl",
|
212 |
+
"polish": "pl",
|
213 |
+
"portuguese": "pt",
|
214 |
+
"romanian": "ro",
|
215 |
+
"russian": "ru",
|
216 |
+
"slovak": "sk",
|
217 |
+
"slovenian": "sl",
|
218 |
+
"swedish": "sv",
|
219 |
+
"chinese": "zh"
|
220 |
+
}
|
221 |
+
|
222 |
+
DEEPL_CODE_TO_LANGUAGE = {v: k for k, v in DEEPL_LANGUAGE_TO_CODE.items()}
|
deep_translator/deepl.py
CHANGED
@@ -1,21 +1,22 @@
|
|
1 |
-
|
2 |
import requests
|
3 |
-
from
|
4 |
-
from deep_translator.
|
5 |
-
|
6 |
-
|
|
|
7 |
|
8 |
|
9 |
class DeepL(object):
|
10 |
"""
|
11 |
class that wraps functions, which use the DeepL translator under the hood to translate word(s)
|
12 |
"""
|
|
|
13 |
|
14 |
def __init__(self, api_key=None):
|
15 |
"""
|
16 |
-
@param api_key: your DeepL api key.
|
|
|
17 |
"""
|
18 |
-
|
19 |
if not api_key:
|
20 |
raise ServerException(401)
|
21 |
self.version = 'v2'
|
@@ -23,25 +24,30 @@ class DeepL(object):
|
|
23 |
self.__base_url = BASE_URLS.get("DEEPL").format(version=self.version)
|
24 |
|
25 |
def translate(self, source, target, text):
|
|
|
|
|
26 |
params = {
|
27 |
"auth_key": self.api_key,
|
28 |
-
"target_lang": target,
|
29 |
-
"source_lang": source,
|
30 |
"text": text
|
31 |
}
|
|
|
32 |
try:
|
33 |
-
response = requests.get(self.__base_url, params=params)
|
34 |
except ConnectionError:
|
35 |
raise ServerException(503)
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
|
|
|
|
45 |
|
46 |
def translate_batch(self, source, target, batch):
|
47 |
"""
|
@@ -53,7 +59,13 @@ class DeepL(object):
|
|
53 |
"""
|
54 |
return [self.translate(source, target, text) for text in batch]
|
55 |
|
|
|
|
|
|
|
56 |
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
1 |
import requests
|
2 |
+
from deep_translator.constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE
|
3 |
+
from deep_translator.exceptions import (ServerException,
|
4 |
+
TranslationNotFound,
|
5 |
+
LanguageNotSupportedException,
|
6 |
+
AuthorizationException)
|
7 |
|
8 |
|
9 |
class DeepL(object):
|
10 |
"""
|
11 |
class that wraps functions, which use the DeepL translator under the hood to translate word(s)
|
12 |
"""
|
13 |
+
_languages = DEEPL_LANGUAGE_TO_CODE
|
14 |
|
15 |
def __init__(self, api_key=None):
|
16 |
"""
|
17 |
+
@param api_key: your DeepL api key.
|
18 |
+
Get one here: https://www.deepl.com/docs-api/accessing-the-api/
|
19 |
"""
|
|
|
20 |
if not api_key:
|
21 |
raise ServerException(401)
|
22 |
self.version = 'v2'
|
|
|
24 |
self.__base_url = BASE_URLS.get("DEEPL").format(version=self.version)
|
25 |
|
26 |
def translate(self, source, target, text):
|
27 |
+
# Create the request parameters.
|
28 |
+
translate_endpoint = 'translate'
|
29 |
params = {
|
30 |
"auth_key": self.api_key,
|
31 |
+
"target_lang": self._map_language_to_code(target),
|
32 |
+
"source_lang": self._map_language_to_code(source),
|
33 |
"text": text
|
34 |
}
|
35 |
+
# Do the request and check the connection.
|
36 |
try:
|
37 |
+
response = requests.get(self.__base_url + translate_endpoint, params=params)
|
38 |
except ConnectionError:
|
39 |
raise ServerException(503)
|
40 |
+
# If the answer is not success, raise server exception.
|
41 |
+
if response.status_code == 403:
|
42 |
+
raise AuthorizationException(self.api_key)
|
43 |
+
elif response.status_code != 200:
|
44 |
+
raise ServerException(response.status_code)
|
45 |
+
# Get the response and check is not empty.
|
46 |
+
res = response.json()
|
47 |
+
if not res:
|
48 |
+
raise TranslationNotFound(text)
|
49 |
+
# Process and return the response.
|
50 |
+
return res['translations'][0]['text']
|
51 |
|
52 |
def translate_batch(self, source, target, batch):
|
53 |
"""
|
|
|
59 |
"""
|
60 |
return [self.translate(source, target, text) for text in batch]
|
61 |
|
62 |
+
def _is_language_supported(self, lang):
|
63 |
+
# The language is supported when is in the dicionary.
|
64 |
+
return lang == 'auto' or lang in self._languages.keys() or lang in self._languages.values()
|
65 |
|
66 |
+
def _map_language_to_code(self, lang):
|
67 |
+
if lang in self._languages.keys():
|
68 |
+
return self._languages[lang]
|
69 |
+
elif lang in self._languages.values():
|
70 |
+
return lang
|
71 |
+
raise LanguageNotSupportedException(lang)
|
deep_translator/exceptions.py
CHANGED
@@ -136,3 +136,9 @@ class ServerException(Exception):
|
|
136 |
def __init__(self, status_code, *args):
|
137 |
message = self.errors.get(status_code, "API server error")
|
138 |
super(ServerException, self).__init__(message, *args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
def __init__(self, status_code, *args):
|
137 |
message = self.errors.get(status_code, "API server error")
|
138 |
super(ServerException, self).__init__(message, *args)
|
139 |
+
|
140 |
+
|
141 |
+
class AuthorizationException(Exception):
|
142 |
+
def __init__(self, api_key, *args):
|
143 |
+
msg = 'Unauthorized access with the api key ' + api_key
|
144 |
+
super().__init__(msg, *args)
|
deep_translator/tests/test_deepl.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
from unittest.mock import Mock, PropertyMock, patch
|
3 |
+
from deep_translator.deepl import DeepL
|
4 |
+
from deep_translator.exceptions import AuthorizationException
|
5 |
+
|
6 |
+
|
7 |
+
@patch('deep_translator.deepl.requests')
|
8 |
+
def test_simple_translation(mock_requests):
|
9 |
+
translator = DeepL(api_key='imagine-this-is-an-valid-api-key')
|
10 |
+
# Set the request response mock.
|
11 |
+
mock_response = Mock()
|
12 |
+
mock_response.status_code = 200
|
13 |
+
mock_response.json.return_value = {
|
14 |
+
"translations": [{
|
15 |
+
"text": "hola"
|
16 |
+
}]
|
17 |
+
}
|
18 |
+
mock_requests.get.return_value = mock_response
|
19 |
+
translation = translator.translate('en', 'es', 'hello')
|
20 |
+
assert translation == 'hola'
|
21 |
+
|
22 |
+
|
23 |
+
@patch('deep_translator.deepl.requests.get')
|
24 |
+
def test_wrong_api_key(mock_requests):
|
25 |
+
translator = DeepL(api_key='this-is-a-wrong-api-key!')
|
26 |
+
# Set the response status_code only.
|
27 |
+
mock_requests.return_value = Mock(status_code=403)
|
28 |
+
with pytest.raises(AuthorizationException):
|
29 |
+
translator.translate('en', 'es', 'Hello')
|