RubénEu commited on
Commit
41a7e8f
·
1 Parent(s): da70592

Improved the DeepL implementation

Browse files
deep_translator/deepl.py CHANGED
@@ -1,21 +1,22 @@
1
-
2
  import requests
3
- from requests.utils import requote_uri
4
- from deep_translator.constants import BASE_URLS
5
- from deep_translator.exceptions import (RequestError,
6
- ServerException, TranslationNotFound, TooManyRequests)
 
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. Get one here: https://www.deepl.com/docs-api/accessing-the-api/
 
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
- else:
38
- if response.status_code != 200:
39
- ServerException(response.status_code)
40
- else:
41
- res = response.json()
42
- if not res:
43
- raise TranslationNotFound(text)
44
- return res
 
 
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
- if __name__ == '__main__':
58
- d = DeepL(api_key="key")
59
- print(d)
 
 
 
 
 
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)