1import requests 2from .constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE 3from .exceptions import (ServerException, 4 TranslationNotFound, 5 LanguageNotSupportedException, 6 AuthorizationException) 7 8 9class 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, source="en", target="en", use_free_api=True, **kwargs): 16 """ 17 @param api_key: your DeepL api key. 18 Get one here: https://www.deepl.com/docs-api/accessing-the-api/ 19 @param source: source language 20 @param target: target language 21 """ 22 if not api_key: 23 raise ServerException(401) 24 self.version = 'v2' 25 self.api_key = api_key 26 self.source = self._map_language_to_code(source) 27 self.target = self._map_language_to_code(target) 28 if use_free_api: 29 self.__base_url = BASE_URLS.get("DEEPL_FREE").format(version=self.version) 30 else: 31 self.__base_url = BASE_URLS.get("DEEPL").format(version=self.version) 32 33 def translate(self, text, **kwargs): 34 """ 35 @param text: text to translate 36 @return: translated text 37 """ 38 # Create the request parameters. 39 translate_endpoint = 'translate' 40 params = { 41 "auth_key": self.api_key, 42 "source_lang": self.source, 43 "target_lang": self.target, 44 "text": text 45 } 46 # Do the request and check the connection. 47 try: 48 response = requests.get(self.__base_url + translate_endpoint, params=params) 49 except ConnectionError: 50 raise ServerException(503) 51 # If the answer is not success, raise server exception. 52 if response.status_code == 403: 53 raise AuthorizationException(self.api_key) 54 elif response.status_code != 200: 55 raise ServerException(response.status_code) 56 # Get the response and check is not empty. 57 res = response.json() 58 if not res: 59 raise TranslationNotFound(text) 60 # Process and return the response. 61 return res['translations'][0]['text'] 62 63 def translate_batch(self, batch, **kwargs): 64 """ 65 @param batch: list of texts to translate 66 @return: list of translations 67 """ 68 return [self.translate(text, **kwargs) for text in batch] 69 70 @staticmethod 71 def get_supported_languages(as_dict=False, **kwargs): 72 return [*DeepL._languages.keys()] if not as_dict else DeepL._languages 73 74 def _is_language_supported(self, lang, **kwargs): 75 # The language is supported when is in the dicionary. 76 return lang == 'auto' or lang in self._languages.keys() or lang in self._languages.values() 77 78 def _map_language_to_code(self, lang, **kwargs): 79 if lang in self._languages.keys(): 80 return self._languages[lang] 81 elif lang in self._languages.values(): 82 return lang 83 raise LanguageNotSupportedException(lang) 84 85 86if __name__ == '__main__': 87 d = DeepL(target="de") 88 t = d.translate("I have no idea") 89 print("text: ", t) 90