Kirill commited on
Commit
8d368b7
·
1 Parent(s): 7980585

added microsoft.py for microsoft translator and updated constants.py and exceptions.py for microsoft translator

Browse files
deep_translator/constants.py CHANGED
@@ -1,4 +1,4 @@
1
-
2
 
3
  BASE_URLS = {
4
  "GOOGLE_TRANSLATE": "https://translate.google.com/m",
@@ -8,6 +8,7 @@ BASE_URLS = {
8
  "MYMEMORY": "http://api.mymemory.translated.net/get",
9
  "QCRI": "https://mt.qcri.org/api/v1/{endpoint}?",
10
  "DEEPL": "https://api.deepl.com/{version}/"
 
11
  }
12
 
13
  GOOGLE_CODES_TO_LANGUAGES = {
@@ -182,3 +183,11 @@ LINGUEE_LANGUAGES_TO_CODES = {
182
  LINGUEE_CODE_TO_LANGUAGE = {v: k for k, v in LINGUEE_LANGUAGES_TO_CODES.items()}
183
 
184
  # "72e9e2cc7c992db4dcbdd6fb9f91a0d1"
 
 
 
 
 
 
 
 
 
1
+ import requests
2
 
3
  BASE_URLS = {
4
  "GOOGLE_TRANSLATE": "https://translate.google.com/m",
 
8
  "MYMEMORY": "http://api.mymemory.translated.net/get",
9
  "QCRI": "https://mt.qcri.org/api/v1/{endpoint}?",
10
  "DEEPL": "https://api.deepl.com/{version}/"
11
+ "MICROSOFT_TRANSLATE": "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0"
12
  }
13
 
14
  GOOGLE_CODES_TO_LANGUAGES = {
 
183
  LINGUEE_CODE_TO_LANGUAGE = {v: k for k, v in LINGUEE_LANGUAGES_TO_CODES.items()}
184
 
185
  # "72e9e2cc7c992db4dcbdd6fb9f91a0d1"
186
+
187
+ # obtaining the current list of supported Microsoft languages for translation
188
+
189
+ microsoft_languages_api_url = "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation"
190
+ 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()}
deep_translator/exceptions.py CHANGED
@@ -81,6 +81,19 @@ class RequestError(Exception):
81
  return self.message
82
 
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  class TooManyRequests(Exception):
85
  """
86
  exception thrown if an error occured during the request call, e.g a connection problem.
 
81
  return self.message
82
 
83
 
84
+ class MicrosoftAPIerror(Exception):
85
+ """
86
+ exception thrown if Microsoft API returns one of its errors
87
+ """
88
+
89
+ def __init__(self, api_message):
90
+ self.api_message = str(api_message)
91
+ self.message="Microsoft API returned the following error"
92
+
93
+ def __str__(self):
94
+ return "{}: {}".format(self.message, self.api_message)
95
+
96
+
97
  class TooManyRequests(Exception):
98
  """
99
  exception thrown if an error occured during the request call, e.g a connection problem.
deep_translator/microsoft.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import requests
4
+ # import uuid
5
+ import logging
6
+ import sys
7
+
8
+ from deep_translator.constants import BASE_URLS, MICROSOFT_CODES_TO_LANGUAGES
9
+ from deep_translator.exceptions import LanguageNotSupportedException, ServerException, MicrosoftAPIerror
10
+
11
+
12
+ class MicrosoftTranslator:
13
+ """
14
+ the class that wraps functions, which use the Microsoft translator under the hood to translate word(s)
15
+ """
16
+
17
+ _languages = MICROSOFT_CODES_TO_LANGUAGES
18
+ supported_languages = list(_languages.values())
19
+
20
+ def __init__(self, api_key=None, region=None, source=None, target=None, **kwargs):
21
+ """
22
+ @params api_key and target are the required params
23
+ @param api_key: your Microsoft API key
24
+ @param region: your Microsoft Location
25
+ """
26
+ if not api_key:
27
+ raise ServerException(401)
28
+ else:
29
+ self.api_key = api_key
30
+ self.headers = {
31
+ "Ocp-Apim-Subscription-Key": self.api_key,
32
+ "Content-type": "application/json",
33
+ }
34
+ # region is not required but very common and goes to headers if passed
35
+ if region:
36
+ self.region = region
37
+ self.headers["Ocp-Apim-Subscription-Region"] = self.region
38
+
39
+ if not target:
40
+ raise ServerException(401)
41
+ else:
42
+ if type(target) is str:
43
+ self.target = target.lower()
44
+ else:
45
+ self.target = [i.lower() for i in target]
46
+ if self.is_language_supported(self.target):
47
+ self.target = self._map_language_to_code(self.target)
48
+
49
+ self.url_params = {'to': self.target, **kwargs}
50
+
51
+ if source:
52
+ self.source = source.lower()
53
+ if self.is_language_supported(self.source):
54
+ self.source = self._map_language_to_code(self.source)
55
+ self.url_params['from'] = self.source
56
+
57
+ self.__base_url = BASE_URLS.get("MICROSOFT_TRANSLATE")
58
+
59
+ @staticmethod
60
+ def get_supported_languages(as_dict=False):
61
+ """
62
+ return the languages supported by the microsoft translator
63
+ @param as_dict: if True, the languages will be returned as a dictionary mapping languages to their abbreviations
64
+ @return: list or dict
65
+ """
66
+ return MicrosoftTranslator.supported_languages if not as_dict else MicrosoftTranslator._languages
67
+
68
+ def _map_language_to_code(self, language):
69
+ """
70
+ map the language to its corresponding code (abbreviation) if the language was passed by its full name by the user
71
+ @param languages: a string (if 1 lang) or a list (if multiple langs)
72
+ @return: mapped value of the language or raise an exception if the language is not supported
73
+ """
74
+ if type(language) is str:
75
+ language = [language]
76
+ for lang in language:
77
+ if lang in self._languages.values():
78
+ yield lang
79
+ elif lang in self._languages.keys():
80
+ yield self._languages[lang]
81
+ else:
82
+ raise LanguageNotSupportedException(lang)
83
+
84
+ def is_language_supported(self, language):
85
+ """
86
+ check if the language is supported by the translator
87
+ @param languages: a string (if 1 lang) or a list (if multiple langs)
88
+ @return: bool or raise an Exception
89
+ """
90
+ if type(language) is str:
91
+ language = [language]
92
+ for lang in language:
93
+ if lang not in self._languages.keys():
94
+ if lang not in self._languages.values():
95
+ raise LanguageNotSupportedException(lang)
96
+ return True
97
+
98
+ def translate(self, text):
99
+ """
100
+ function that uses microsoft translate to translate a text
101
+ @param text: desired text to translate
102
+ @return: str: translated text
103
+ """
104
+ # a body must be a list of dicts to process multiple texts;
105
+ # I have not added multiple text processing here since it is covered by the translate_batch method
106
+ valid_microsoft_json = [{'text': text}]
107
+ try:
108
+ requested = requests.post(self.__base_url, params=self.url_params, headers=self.headers, json=valid_microsoft_json)
109
+ except requests.exceptions.RequestException:
110
+ exc_type, value, traceback = sys.exc_info()
111
+ logging.warning(f"Returned error: {exc_type.__name__}")
112
+
113
+ # Where Microsoft API responds with an api error, it returns a dict in response.json()
114
+ if type(requested.json()) is dict:
115
+ error_message = requested.json()['error']
116
+ raise MicrosoftAPIerror(error_message)
117
+ # Where it responds with a translation, its response.json() is a list e.g. [{'translations': [{'text': 'Hello world!', 'to': 'en'}]}]
118
+ elif type(requested.json()) is list:
119
+ all_translations = [i['text'] for i in requested.json()[0]['translations']]
120
+ return "\n".join(all_translations)
121
+
122
+ def translate_file(self, path):
123
+ """
124
+ translate from a file
125
+ @param path: path to file
126
+ @return: translated text
127
+ """
128
+ try:
129
+ with open(path) as f:
130
+ text = f.read()
131
+ return self.translate(text)
132
+ except Exception as e:
133
+ raise e
134
+
135
+ def translate_batch(self, batch):
136
+ """
137
+ translate a batch of texts
138
+ @param batch: list of texts to translate
139
+ @return: list of translations
140
+ """
141
+ return [self.translate(text) for text in batch]