From 78d0ff18796901bb1adea00e23e5352692955820 Mon Sep 17 00:00:00 2001 From: nidhal baccouri Date: Wed, 9 Mar 2022 15:01:59 +0100 Subject: [PATCH 1/5] added black for formatting --- Makefile | 2 +- deep_translator/__init__.py | 28 +-- deep_translator/__main__.py | 3 +- deep_translator/base.py | 37 ++-- deep_translator/cli.py | 86 +++++---- deep_translator/constants.py | 342 +++++++++++++++++----------------- deep_translator/deepl.py | 36 ++-- deep_translator/detection.py | 33 ++-- deep_translator/engines.py | 7 +- deep_translator/exceptions.py | 47 +++-- deep_translator/google.py | 48 +++-- deep_translator/libre.py | 34 ++-- deep_translator/linguee.py | 51 ++--- deep_translator/microsoft.py | 52 +++--- deep_translator/mymemory.py | 57 +++--- deep_translator/papago.py | 35 ++-- deep_translator/pons.py | 49 ++--- deep_translator/qcri.py | 23 ++- deep_translator/validate.py | 4 +- deep_translator/yandex.py | 51 ++--- poetry.lock | 152 ++++++++++++++- pyproject.toml | 1 + tests/test_cli.py | 8 +- tests/test_data.py | 4 +- tests/test_deepl.py | 24 +-- tests/test_google.py | 14 +- tests/test_libre.py | 12 +- tests/test_linguee.py | 6 +- tests/test_microsoft_trans.py | 29 ++- tests/test_mymemory.py | 8 +- tests/test_pons.py | 5 +- 31 files changed, 758 insertions(+), 530 deletions(-) diff --git a/Makefile b/Makefile index ff0bf8b..1d3d3ed 100644 --- a/Makefile +++ b/Makefile @@ -48,7 +48,7 @@ clean-test: ## remove test and coverage artifacts rm -fr .pytest_cache lint: ## check style with flake8 - flake8 deep_translator tests + poetry run black deep_translator tests test: ## run tests quickly with the default Python pytest diff --git a/deep_translator/__init__.py b/deep_translator/__init__.py index 539b1b1..e3133c0 100644 --- a/deep_translator/__init__.py +++ b/deep_translator/__init__.py @@ -1,20 +1,20 @@ """Top-level package for Deep Translator""" -from .google import GoogleTranslator -from .pons import PonsTranslator -from .linguee import LingueeTranslator -from .mymemory import MyMemoryTranslator -from .yandex import YandexTranslator -from .qcri import QcriTranslator -from .deepl import DeeplTranslator -from .detection import single_detection, batch_detection -from .microsoft import MicrosoftTranslator -from .papago import PapagoTranslator -from .libre import LibreTranslator +from deep_translator.google import GoogleTranslator +from deep_translator.pons import PonsTranslator +from deep_translator.linguee import LingueeTranslator +from deep_translator.mymemory import MyMemoryTranslator +from deep_translator.yandex import YandexTranslator +from deep_translator.qcri import QcriTranslator +from deep_translator.deepl import DeeplTranslator +from deep_translator.detection import single_detection, batch_detection +from deep_translator.microsoft import MicrosoftTranslator +from deep_translator.papago import PapagoTranslator +from deep_translator.libre import LibreTranslator __author__ = """Nidhal Baccouri""" -__email__ = 'nidhalbacc@gmail.com' -__version__ = '1.7.1' +__email__ = "nidhalbacc@gmail.com" +__version__ = "1.7.1" __all__ = [ "GoogleTranslator", @@ -28,5 +28,5 @@ "LibreTranslator", "PapagoTranslator", "single_detection", - "batch_detection" + "batch_detection", ] diff --git a/deep_translator/__main__.py b/deep_translator/__main__.py index d0af3a0..9a35ad5 100644 --- a/deep_translator/__main__.py +++ b/deep_translator/__main__.py @@ -1,5 +1,4 @@ - -from .cli import CLI +from deep_translator.cli import CLI def main(): diff --git a/deep_translator/base.py b/deep_translator/base.py index 0d07e28..82f529f 100644 --- a/deep_translator/base.py +++ b/deep_translator/base.py @@ -1,7 +1,7 @@ """base translator class""" -from .constants import GOOGLE_LANGUAGES_TO_CODES -from .exceptions import InvalidSourceOrTargetLanguage +from deep_translator.constants import GOOGLE_LANGUAGES_TO_CODES +from deep_translator.exceptions import InvalidSourceOrTargetLanguage from abc import ABC, abstractmethod @@ -9,15 +9,18 @@ class BaseTranslator(ABC): """ Abstract class that serve as a base translator for other different translators """ - def __init__(self, - base_url=None, - source="auto", - target="en", - payload_key=None, - element_tag=None, - element_query=None, - languages=None, - **url_params): + + def __init__( + self, + base_url=None, + source="auto", + target="en", + payload_key=None, + element_tag=None, + element_query=None, + languages=None, + **url_params + ): """ @param source: source language to translate from @param target: target language to translate to @@ -47,7 +50,7 @@ def _map_language_to_code(self, *languages): @return: mapped value of the language or raise an exception if the language is not supported """ for language in languages: - if language in self.languages.values() or language == 'auto': + if language in self.languages.values() or language == "auto": yield language elif language in self.languages.keys(): yield self.languages[language] @@ -69,7 +72,11 @@ def is_language_supported(self, language, **kwargs): @param language: a string for 1 language @return: bool or raise an Exception """ - if language == 'auto' or language in self.languages.keys() or language in self.languages.values(): + if ( + language == "auto" + or language in self.languages.keys() + or language in self.languages.values() + ): return True else: return False @@ -82,7 +89,7 @@ def translate(self, text, **kwargs): @param kwargs: additional arguments @return: str """ - return NotImplemented('You need to implement the translate method!') + return NotImplemented("You need to implement the translate method!") def _translate_file(self, path, **kwargs): """ @@ -93,7 +100,7 @@ def _translate_file(self, path, **kwargs): @return: str """ try: - with open(path, 'r', encoding='utf-8') as f: + with open(path, "r", encoding="utf-8") as f: text = f.read().strip() return self.translate(text) except Exception as e: diff --git a/deep_translator/cli.py b/deep_translator/cli.py index ae310c0..96be8cd 100644 --- a/deep_translator/cli.py +++ b/deep_translator/cli.py @@ -1,6 +1,6 @@ """Console script for deep_translator.""" import argparse -from .engines import __engines__ +from deep_translator.engines import __engines__ class CLI(object): @@ -12,9 +12,13 @@ def __init__(self, custom_args=None): self.args = self.parse_args() translator_class = self.translators_dict.get(self.args.translator, None) if not translator_class: - raise Exception(f"Translator {self.args.translator} is not supported." - f"Supported translators: {list(self.translators_dict.keys())}") - self.translator = translator_class(source=self.args.source, target=self.args.target) + raise Exception( + f"Translator {self.args.translator} is not supported." + f"Supported translators: {list(self.translators_dict.keys())}" + ) + self.translator = translator_class( + source=self.args.source, target=self.args.target + ) def translate(self): """ @@ -22,9 +26,9 @@ def translate(self): @return: None """ res = self.translator.translate(self.args.text) - print("Translation from {} to {}".format(self.args.source, self.args.target)) + print(f"Translation from {self.args.source} to {self.args.target}") print("-" * 50) - print("Translation result: {}".format(res)) + print(f"Translation result: {res}") def get_supported_languages(self): """ @@ -32,42 +36,54 @@ def get_supported_languages(self): @return: None """ - translator_supported_languages = self.translator.get_supported_languages(as_dict=True) - print(f'Languages supported by \'{self.args.translator}\' are :\n') + translator_supported_languages = self.translator.get_supported_languages( + as_dict=True + ) + print(f"Languages supported by '{self.args.translator}' are :\n") print(translator_supported_languages) def parse_args(self): """ function responsible for parsing terminal arguments and provide them for further use in the translation process """ - parser = argparse.ArgumentParser(add_help=True, - description="Official CLI for deep-translator", - usage="dt --help") + parser = argparse.ArgumentParser( + add_help=True, + description="Official CLI for deep-translator", + usage="dt --help", + ) - parser.add_argument('--translator', - '-trans', - default='google', - type=str, - help="name of the translator you want to use") - parser.add_argument('--source', - '-src', - default='auto', - type=str, - help="source language to translate from") - parser.add_argument('--target', - '-tg', - type=str, - help="target language to translate to") - parser.add_argument('--text', - '-txt', - type=str, - help="text you want to translate") - parser.add_argument('--languages', - '-lang', - action='store_true', - help="all the languages available with the translator" - "Run the command deep_translator -trans -lang") - parsed_args = parser.parse_args(self.custom_args) if self.custom_args else parser.parse_args() + parser.add_argument( + "--translator", + "-trans", + default="google", + type=str, + help="name of the translator you want to use", + ) + parser.add_argument( + "--source", + "-src", + default="auto", + type=str, + help="source language to translate from", + ) + parser.add_argument( + "--target", "-tg", type=str, help="target language to translate to" + ) + parser.add_argument( + "--text", "-txt", type=str, help="text you want to translate" + ) + parser.add_argument( + "--languages", + "-lang", + action="store_true", + help="all the languages available with the translator" + "Run the command deep_translator -trans -lang", + ) + parsed_args = ( + parser.parse_args(self.custom_args) + if self.custom_args + else parser.parse_args() + ) return parsed_args def run(self): diff --git a/deep_translator/constants.py b/deep_translator/constants.py index eeb18b4..b42f9a4 100644 --- a/deep_translator/constants.py +++ b/deep_translator/constants.py @@ -1,5 +1,3 @@ -import requests - BASE_URLS = { "GOOGLE_TRANSLATE": "https://translate.google.com/m", "PONS": "https://en.pons.com/translate/", @@ -17,150 +15,150 @@ } GOOGLE_CODES_TO_LANGUAGES = { - 'af': 'afrikaans', - 'sq': 'albanian', - 'am': 'amharic', - 'ar': 'arabic', - 'hy': 'armenian', - 'az': 'azerbaijani', - 'eu': 'basque', - 'be': 'belarusian', - 'bn': 'bengali', - 'bs': 'bosnian', - 'bg': 'bulgarian', - 'ca': 'catalan', - 'ceb': 'cebuano', - 'ny': 'chichewa', - 'zh-CN': 'chinese (simplified)', - 'zh-TW': 'chinese (traditional)', - 'co': 'corsican', - 'hr': 'croatian', - 'cs': 'czech', - 'da': 'danish', - 'nl': 'dutch', - 'en': 'english', - 'eo': 'esperanto', - 'et': 'estonian', - 'tl': 'filipino', - 'fi': 'finnish', - 'fr': 'french', - 'fy': 'frisian', - 'gl': 'galician', - 'ka': 'georgian', - 'de': 'german', - 'el': 'greek', - 'gu': 'gujarati', - 'ht': 'haitian creole', - 'ha': 'hausa', - 'haw': 'hawaiian', - 'iw': 'hebrew', - 'hi': 'hindi', - 'hmn': 'hmong', - 'hu': 'hungarian', - 'is': 'icelandic', - 'ig': 'igbo', - 'id': 'indonesian', - 'ga': 'irish', - 'it': 'italian', - 'ja': 'japanese', - 'jw': 'javanese', - 'kn': 'kannada', - 'kk': 'kazakh', - 'km': 'khmer', - 'rw': 'kinyarwanda', - 'ko': 'korean', - 'ku': 'kurdish', - 'ky': 'kyrgyz', - 'lo': 'lao', - 'la': 'latin', - 'lv': 'latvian', - 'lt': 'lithuanian', - 'lb': 'luxembourgish', - 'mk': 'macedonian', - 'mg': 'malagasy', - 'ms': 'malay', - 'ml': 'malayalam', - 'mt': 'maltese', - 'mi': 'maori', - 'mr': 'marathi', - 'mn': 'mongolian', - 'my': 'myanmar', - 'ne': 'nepali', - 'no': 'norwegian', - 'or': 'odia', - 'ps': 'pashto', - 'fa': 'persian', - 'pl': 'polish', - 'pt': 'portuguese', - 'pa': 'punjabi', - 'ro': 'romanian', - 'ru': 'russian', - 'sm': 'samoan', - 'gd': 'scots gaelic', - 'sr': 'serbian', - 'st': 'sesotho', - 'sn': 'shona', - 'sd': 'sindhi', - 'si': 'sinhala', - 'sk': 'slovak', - 'sl': 'slovenian', - 'so': 'somali', - 'es': 'spanish', - 'su': 'sundanese', - 'sw': 'swahili', - 'sv': 'swedish', - 'tg': 'tajik', - 'ta': 'tamil', - 'tt': 'tatar', - 'te': 'telugu', - 'th': 'thai', - 'tr': 'turkish', - 'tk': 'turkmen', - 'uk': 'ukrainian', - 'ur': 'urdu', - 'ug': 'uyghur', - 'uz': 'uzbek', - 'vi': 'vietnamese', - 'cy': 'welsh', - 'xh': 'xhosa', - 'yi': 'yiddish', - 'yo': 'yoruba', - 'zu': 'zulu', + "af": "afrikaans", + "sq": "albanian", + "am": "amharic", + "ar": "arabic", + "hy": "armenian", + "az": "azerbaijani", + "eu": "basque", + "be": "belarusian", + "bn": "bengali", + "bs": "bosnian", + "bg": "bulgarian", + "ca": "catalan", + "ceb": "cebuano", + "ny": "chichewa", + "zh-CN": "chinese (simplified)", + "zh-TW": "chinese (traditional)", + "co": "corsican", + "hr": "croatian", + "cs": "czech", + "da": "danish", + "nl": "dutch", + "en": "english", + "eo": "esperanto", + "et": "estonian", + "tl": "filipino", + "fi": "finnish", + "fr": "french", + "fy": "frisian", + "gl": "galician", + "ka": "georgian", + "de": "german", + "el": "greek", + "gu": "gujarati", + "ht": "haitian creole", + "ha": "hausa", + "haw": "hawaiian", + "iw": "hebrew", + "hi": "hindi", + "hmn": "hmong", + "hu": "hungarian", + "is": "icelandic", + "ig": "igbo", + "id": "indonesian", + "ga": "irish", + "it": "italian", + "ja": "japanese", + "jw": "javanese", + "kn": "kannada", + "kk": "kazakh", + "km": "khmer", + "rw": "kinyarwanda", + "ko": "korean", + "ku": "kurdish", + "ky": "kyrgyz", + "lo": "lao", + "la": "latin", + "lv": "latvian", + "lt": "lithuanian", + "lb": "luxembourgish", + "mk": "macedonian", + "mg": "malagasy", + "ms": "malay", + "ml": "malayalam", + "mt": "maltese", + "mi": "maori", + "mr": "marathi", + "mn": "mongolian", + "my": "myanmar", + "ne": "nepali", + "no": "norwegian", + "or": "odia", + "ps": "pashto", + "fa": "persian", + "pl": "polish", + "pt": "portuguese", + "pa": "punjabi", + "ro": "romanian", + "ru": "russian", + "sm": "samoan", + "gd": "scots gaelic", + "sr": "serbian", + "st": "sesotho", + "sn": "shona", + "sd": "sindhi", + "si": "sinhala", + "sk": "slovak", + "sl": "slovenian", + "so": "somali", + "es": "spanish", + "su": "sundanese", + "sw": "swahili", + "sv": "swedish", + "tg": "tajik", + "ta": "tamil", + "tt": "tatar", + "te": "telugu", + "th": "thai", + "tr": "turkish", + "tk": "turkmen", + "uk": "ukrainian", + "ur": "urdu", + "ug": "uyghur", + "uz": "uzbek", + "vi": "vietnamese", + "cy": "welsh", + "xh": "xhosa", + "yi": "yiddish", + "yo": "yoruba", + "zu": "zulu", } GOOGLE_LANGUAGES_TO_CODES = {v: k for k, v in GOOGLE_CODES_TO_LANGUAGES.items()} # This dictionary maps the primary name of language to its secondary names in list manner (if any) GOOGLE_LANGUAGES_SECONDARY_NAMES = { - 'myanmar': ['burmese'], - 'odia': ['oriya'], - 'kurdish': ['kurmanji'] + "myanmar": ["burmese"], + "odia": ["oriya"], + "kurdish": ["kurmanji"], } PONS_CODES_TO_LANGUAGES = { - 'ar': 'arabic', - 'bg': 'bulgarian', - 'zh-cn': 'chinese', - 'cs': 'czech', - 'da': 'danish', - 'nl': 'dutch', - 'en': 'english', - 'fr': 'french', - 'de': 'german', - 'el': 'greek', - 'hu': 'hungarian', - 'it': 'italian', - 'la': 'latin', - 'no': 'norwegian', - 'pl': 'polish', - 'pt': 'portuguese', - 'ru': 'russian', - 'sl': 'slovenian', - 'es': 'spanish', - 'sv': 'swedish', - 'tr': 'turkish', - 'elv': 'elvish' + "ar": "arabic", + "bg": "bulgarian", + "zh-cn": "chinese", + "cs": "czech", + "da": "danish", + "nl": "dutch", + "en": "english", + "fr": "french", + "de": "german", + "el": "greek", + "hu": "hungarian", + "it": "italian", + "la": "latin", + "no": "norwegian", + "pl": "polish", + "pt": "portuguese", + "ru": "russian", + "sl": "slovenian", + "es": "spanish", + "sv": "swedish", + "tr": "turkish", + "elv": "elvish", } PONS_LANGUAGES_TO_CODES = {v: k for k, v in PONS_CODES_TO_LANGUAGES.items()} @@ -192,7 +190,7 @@ "swedish": "sv", "latvian": "lv", "estonian": "et", - "japanese": "ja" + "japanese": "ja", } LINGUEE_CODE_TO_LANGUAGE = {v: k for k, v in LINGUEE_LANGUAGES_TO_CODES.items()} @@ -221,56 +219,48 @@ "slovak": "sk", "slovenian": "sl", "swedish": "sv", - "chinese": "zh" + "chinese": "zh", } DEEPL_CODE_TO_LANGUAGE = {v: k for k, v in DEEPL_LANGUAGE_TO_CODE.items()} PAPAGO_CODE_TO_LANGUAGE = { - 'ko': 'Korean', - 'en': 'English', - 'ja': 'Japanese', - 'zh-CN': 'Chinese', - 'zh-TW': 'Chinese traditional', - 'es': 'Spanish', - 'fr': 'French', - 'vi': 'Vietnamese', - 'th': 'Thai', - 'id': 'Indonesia' + "ko": "Korean", + "en": "English", + "ja": "Japanese", + "zh-CN": "Chinese", + "zh-TW": "Chinese traditional", + "es": "Spanish", + "fr": "French", + "vi": "Vietnamese", + "th": "Thai", + "id": "Indonesia", } PAPAGO_LANGUAGE_TO_CODE = {v: k for v, k in PAPAGO_CODE_TO_LANGUAGE.items()} -QCRI_CODE_TO_LANGUAGE = { - 'ar': 'Arabic', - 'en': 'English', - 'es': 'Spanish' -} +QCRI_CODE_TO_LANGUAGE = {"ar": "Arabic", "en": "English", "es": "Spanish"} -QCRI_LANGUAGE_TO_CODE = { - v: k for k, v in QCRI_CODE_TO_LANGUAGE.items() -} +QCRI_LANGUAGE_TO_CODE = {v: k for k, v in QCRI_CODE_TO_LANGUAGE.items()} LIBRE_CODES_TO_LANGUAGES = { - 'en': 'English', - 'ar': 'Arabic', - 'zh': 'Chinese', - 'fr': 'French', - 'de': 'German', - 'hi': 'Hindi', - 'id': 'Indonesian', - 'ga': 'Irish', - 'it': 'Italian', - 'ja': 'Japanese', - 'ko': 'Korean', - 'pl': 'Polish', - 'pt': 'Portuguese', - 'ru': 'Russian', - 'es': 'Spanish', - 'tr': 'Turkish', - 'vi': 'Vietnamese' + "en": "English", + "ar": "Arabic", + "zh": "Chinese", + "fr": "French", + "de": "German", + "hi": "Hindi", + "id": "Indonesian", + "ga": "Irish", + "it": "Italian", + "ja": "Japanese", + "ko": "Korean", + "pl": "Polish", + "pt": "Portuguese", + "ru": "Russian", + "es": "Spanish", + "tr": "Turkish", + "vi": "Vietnamese", } -LIBRE_LANGUAGES_TO_CODES = { - v: k for k, v in LIBRE_CODES_TO_LANGUAGES.items() -} +LIBRE_LANGUAGES_TO_CODES = {v: k for k, v in LIBRE_CODES_TO_LANGUAGES.items()} diff --git a/deep_translator/deepl.py b/deep_translator/deepl.py index ca0fb8b..01933c8 100644 --- a/deep_translator/deepl.py +++ b/deep_translator/deepl.py @@ -2,9 +2,11 @@ from deep_translator.validate import is_empty, validate_input from deep_translator.constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE -from deep_translator.exceptions import (ServerException, - TranslationNotFound, - AuthorizationException) +from deep_translator.exceptions import ( + ServerException, + TranslationNotFound, + AuthorizationException, +) from deep_translator.base import BaseTranslator @@ -13,7 +15,9 @@ class DeeplTranslator(BaseTranslator): class that wraps functions, which use the DeeplTranslator translator under the hood to translate word(s) """ - def __init__(self, api_key=None, source="de", target="en", use_free_api=True, **kwargs): + def __init__( + self, api_key=None, source="de", target="en", use_free_api=True, **kwargs + ): """ @param api_key: your DeeplTranslator api key. Get one here: https://www.deepl.com/docs-api/accessing-the-api/ @@ -22,17 +26,20 @@ def __init__(self, api_key=None, source="de", target="en", use_free_api=True, ** """ if not api_key: raise ServerException(401) - self.version = 'v2' + self.version = "v2" self.api_key = api_key - url = BASE_URLS.get( - "DEEPL_FREE").format(version=self.version) if use_free_api else BASE_URLS.get( - "DEEPL").format(version=self.version) + url = ( + BASE_URLS.get("DEEPL_FREE").format(version=self.version) + if use_free_api + else BASE_URLS.get("DEEPL").format(version=self.version) + ) super().__init__( base_url=url, source=source, target=target, languages=DEEPL_LANGUAGE_TO_CODE, - **kwargs) + **kwargs + ) def translate(self, text, **kwargs): """ @@ -44,17 +51,18 @@ def translate(self, text, **kwargs): return text # Create the request parameters. - translate_endpoint = 'translate' + translate_endpoint = "translate" params = { "auth_key": self.api_key, "source_lang": self._source, "target_lang": self._target, - "text": text + "text": text, } # Do the request and check the connection. try: response = requests.get( - self._base_url + translate_endpoint, params=params) + self._base_url + translate_endpoint, params=params + ) except ConnectionError: raise ServerException(503) # If the answer is not success, raise server exception. @@ -67,7 +75,7 @@ def translate(self, text, **kwargs): if not res: raise TranslationNotFound(text) # Process and return the response. - return res['translations'][0]['text'] + return res["translations"][0]["text"] def translate_file(self, path, **kwargs): return self._translate_file(path, **kwargs) @@ -80,7 +88,7 @@ def translate_batch(self, batch, **kwargs): return self._translate_batch(batch, **kwargs) -if __name__ == '__main__': +if __name__ == "__main__": d = DeeplTranslator(target="en", api_key="some-key") t = d.translate("Ich habe keine ahnung") print("text: ", t) diff --git a/deep_translator/detection.py b/deep_translator/detection.py index ce45433..3c7e395 100644 --- a/deep_translator/detection.py +++ b/deep_translator/detection.py @@ -5,7 +5,13 @@ from requests.exceptions import HTTPError # Module global config -config = {"url": 'https://ws.detectlanguage.com/0.2/detect',"headers": {'User-Agent': 'Detect Language API Python Client 1.4.0','Authorization': 'Bearer {}',}} +config = { + "url": "https://ws.detectlanguage.com/0.2/detect", + "headers": { + "User-Agent": "Detect Language API Python Client 1.4.0", + "Authorization": "Bearer {}", + }, +} def get_request_body(text, api_key, *args, **kwargs): @@ -19,20 +25,20 @@ def get_request_body(text, api_key, *args, **kwargs): """ if not api_key: - raise Exception("you need to get an API_KEY for this to work. " - "Get one for free here: https://detectlanguage.com/documentation") + raise Exception( + "you need to get an API_KEY for this to work. " + "Get one for free here: https://detectlanguage.com/documentation" + ) if not text: raise Exception("Please provide an input text") else: try: - headers = config['headers'] - headers['Authorization'] = headers['Authorization'].format(api_key) - response = requests.post(config['url'], - json={'q': text}, - headers=headers) + headers = config["headers"] + headers["Authorization"] = headers["Authorization"].format(api_key) + response = requests.post(config["url"], json={"q": text}, headers=headers) - body = response.json().get('data') + body = response.json().get("data") return body except HTTPError as e: @@ -51,11 +57,11 @@ def single_detection(text, api_key=None, detailed=False, *args, **kwargs): @param detailed: set to True if you want to get detailed information about the detection process """ body = get_request_body(text, api_key) - detections = body.get('detections') + detections = body.get("detections") if detailed: return detections[0] - lang = detections[0].get('language', None) + lang = detections[0].get("language", None) if lang: return lang @@ -69,10 +75,9 @@ def batch_detection(text_list, api_key, detailed=False, *args, **kwargs): @param detailed: set to True if you want to get detailed information about the detection process """ body = get_request_body(text_list, api_key) - detections = body.get('detections') + detections = body.get("detections") res = [obj[0] for obj in detections] if detailed: return res else: - return [obj['language'] for obj in res] - + return [obj["language"] for obj in res] diff --git a/deep_translator/engines.py b/deep_translator/engines.py index c87adaa..fe28b8b 100644 --- a/deep_translator/engines.py +++ b/deep_translator/engines.py @@ -1,7 +1,6 @@ - -from .base import BaseTranslator +from deep_translator.base import BaseTranslator __engines__ = { - translator.__name__.replace('Translator', '').lower(): - translator for translator in BaseTranslator.__subclasses__() + translator.__name__.replace("Translator", "").lower(): translator + for translator in BaseTranslator.__subclasses__() } diff --git a/deep_translator/exceptions.py b/deep_translator/exceptions.py index 7e4a3fe..418faaa 100644 --- a/deep_translator/exceptions.py +++ b/deep_translator/exceptions.py @@ -30,9 +30,11 @@ class NotValidPayload(BaseError): exception thrown if the user enters an invalid payload """ - def __init__(self, - val, - message='text must be a valid text with maximum 5000 character, otherwise it cannot be translated'): + def __init__( + self, + val, + message="text must be a valid text with maximum 5000 character, otherwise it cannot be translated", + ): super(NotValidPayload, self).__init__(val, message) @@ -41,9 +43,7 @@ class InvalidSourceOrTargetLanguage(BaseError): exception thrown if the user enters an invalid payload """ - def __init__(self, - val, - message="Invalid source or target language!"): + def __init__(self, val, message="Invalid source or target language!"): super(InvalidSourceOrTargetLanguage, self).__init__(val, message) @@ -52,9 +52,11 @@ class TranslationNotFound(BaseError): exception thrown if no translation was found for the text provided by the user """ - def __init__(self, - val, - message='No translation was found using the current translator. Try another translator?'): + def __init__( + self, + val, + message="No translation was found using the current translator. Try another translator?", + ): super(TranslationNotFound, self).__init__(val, message) @@ -63,9 +65,9 @@ class ElementNotFoundInGetRequest(BaseError): exception thrown if the html element was not found in the body parsed by beautifulsoup """ - def __init__(self, - val, - message='Required element was not found in the API response'): + def __init__( + self, val, message="Required element was not found in the API response" + ): super(ElementNotFoundInGetRequest, self).__init__(val, message) @@ -75,7 +77,9 @@ class NotValidLength(BaseError): """ def __init__(self, val, min_chars, max_chars): - message = "Text length need to be between {} and {} characters".format(min_chars, max_chars) + message = ( + f"Text length need to be between {min_chars} and {max_chars} characters" + ) super(NotValidLength, self).__init__(val, message) @@ -84,8 +88,11 @@ class RequestError(Exception): exception thrown if an error occurred during the request call, e.g a connection problem. """ - def __init__(self, message="Request exception can happen due to an api connection error. " - "Please check your connection and try again"): + def __init__( + self, + message="Request exception can happen due to an api connection error. " + "Please check your connection and try again", + ): self.message = message def __str__(self): @@ -99,7 +106,7 @@ class MicrosoftAPIerror(Exception): def __init__(self, api_message): self.api_message = str(api_message) - self.message="Microsoft API returned the following error" + self.message = "Microsoft API returned the following error" def __str__(self): return "{}: {}".format(self.message, self.api_message) @@ -110,7 +117,10 @@ class TooManyRequests(Exception): exception thrown if an error occurred during the request call, e.g a connection problem. """ - def __init__(self, message="Server Error: You made too many requests to the server. According to google, you are allowed to make 5 requests per second and up to 200k requests per day. You can wait and try again later or you can try the translate_batch function"): + def __init__( + self, + message="Server Error: You made too many requests to the server. According to google, you are allowed to make 5 requests per second and up to 200k requests per day. You can wait and try again later or you can try the translate_batch function", + ): self.message = message def __str__(self): @@ -121,6 +131,7 @@ class ServerException(Exception): """ Default YandexTranslate exception from the official website """ + errors = { 400: "ERR_BAD_REQUEST", 401: "ERR_KEY_INVALID", @@ -142,5 +153,5 @@ def __init__(self, status_code, *args): class AuthorizationException(Exception): def __init__(self, api_key, *args): - msg = 'Unauthorized access with the api key ' + api_key + msg = "Unauthorized access with the api key " + api_key super().__init__(msg, *args) diff --git a/deep_translator/google.py b/deep_translator/google.py index 39b46d9..65ce927 100644 --- a/deep_translator/google.py +++ b/deep_translator/google.py @@ -3,7 +3,11 @@ """ from deep_translator.constants import BASE_URLS -from deep_translator.exceptions import TooManyRequests, TranslationNotFound, RequestError +from deep_translator.exceptions import ( + TooManyRequests, + TranslationNotFound, + RequestError, +) from deep_translator.base import BaseTranslator from deep_translator.validate import validate_input, is_empty from bs4 import BeautifulSoup @@ -21,13 +25,15 @@ def __init__(self, source="auto", target="en", proxies=None, **kwargs): @param target: target language to translate to """ self.proxies = proxies - super().__init__(base_url=BASE_URLS.get("GOOGLE_TRANSLATE"), - source=source, - target=target, - element_tag='div', - element_query={"class": "t0"}, - payload_key='q', # key of text in the url - **kwargs) + super().__init__( + base_url=BASE_URLS.get("GOOGLE_TRANSLATE"), + source=source, + target=target, + element_tag="div", + element_query={"class": "t0"}, + payload_key="q", # key of text in the url + **kwargs + ) self._alt_element_query = {"class": "result-container"} @@ -41,22 +47,22 @@ def translate(self, text, **kwargs): text = text.strip() if self._same_source_target() or is_empty(text): return text - self._url_params['tl'] = self._target - self._url_params['sl'] = self._source + self._url_params["tl"] = self._target + self._url_params["sl"] = self._source if self.payload_key: self._url_params[self.payload_key] = text - response = requests.get(self._base_url, - params=self._url_params, - proxies=self.proxies) + response = requests.get( + self._base_url, params=self._url_params, proxies=self.proxies + ) if response.status_code == 429: raise TooManyRequests() if response.status_code != 200: raise RequestError() - soup = BeautifulSoup(response.text, 'html.parser') + soup = BeautifulSoup(response.text, "html.parser") element = soup.find(self._element_tag, self._element_query) @@ -65,9 +71,15 @@ def translate(self, text, **kwargs): if not element: raise TranslationNotFound(text) if element.get_text(strip=True) == text.strip(): - to_translate_alpha = ''.join(ch for ch in text.strip() if ch.isalnum()) - translated_alpha = ''.join(ch for ch in element.get_text(strip=True) if ch.isalnum()) - if to_translate_alpha and translated_alpha and to_translate_alpha == translated_alpha: + to_translate_alpha = "".join(ch for ch in text.strip() if ch.isalnum()) + translated_alpha = "".join( + ch for ch in element.get_text(strip=True) if ch.isalnum() + ) + if ( + to_translate_alpha + and translated_alpha + and to_translate_alpha == translated_alpha + ): self._url_params["tl"] = self._target if "hl" not in self._url_params: return text.strip() @@ -96,6 +108,6 @@ def translate_batch(self, batch=None, **kwargs): return self._translate_batch(batch, **kwargs) -if __name__ == '__main__': +if __name__ == "__main__": t = GoogleTranslator().translate("hallo welt") print("translation: ", t) diff --git a/deep_translator/libre.py b/deep_translator/libre.py index 4c7d055..8c5e581 100644 --- a/deep_translator/libre.py +++ b/deep_translator/libre.py @@ -4,12 +4,14 @@ import requests -from .validate import is_empty, validate_input -from .base import BaseTranslator -from .constants import BASE_URLS,LIBRE_LANGUAGES_TO_CODES -from .exceptions import (ServerException, - TranslationNotFound, - AuthorizationException) +from deep_translator.validate import is_empty, validate_input +from deep_translator.base import BaseTranslator +from deep_translator.constants import BASE_URLS, LIBRE_LANGUAGES_TO_CODES +from deep_translator.exceptions import ( + ServerException, + TranslationNotFound, + AuthorizationException, +) class LibreTranslator(BaseTranslator): @@ -27,10 +29,12 @@ def __init__(self, source="auto", target="en", api_key=None, **kwargs): if not api_key: raise ServerException(401) self.api_key = api_key - super().__init__(base_url=BASE_URLS.get("LIBRE"), - source=source, - target=target, - languages=LIBRE_LANGUAGES_TO_CODES) + super().__init__( + base_url=BASE_URLS.get("LIBRE"), + source=source, + target=target, + languages=LIBRE_LANGUAGES_TO_CODES, + ) def translate(self, text, **kwargs): """ @@ -42,19 +46,21 @@ def translate(self, text, **kwargs): if self._same_source_target() or is_empty(text): return text - translate_endpoint = 'translate' + translate_endpoint = "translate" params = { "q": text, "source": self._source, "target": self._target, - "format": 'text' + "format": "text", } # Add API Key if required if self.api_key: params["api_key"] = self.api_key # Do the request and check the connection. try: - response = requests.post(self._base_url + translate_endpoint, params=params) + response = requests.post( + self._base_url + translate_endpoint, params=params + ) except ConnectionError: raise ServerException(503) # If the answer is not success, raise server exception. @@ -68,7 +74,7 @@ def translate(self, text, **kwargs): if not res: raise TranslationNotFound(text) # Process and return the response. - return res['translatedText'] + return res["translatedText"] def translate_file(self, path, **kwargs): """ diff --git a/deep_translator/linguee.py b/deep_translator/linguee.py index 65c956b..596df61 100644 --- a/deep_translator/linguee.py +++ b/deep_translator/linguee.py @@ -1,15 +1,16 @@ """ linguee translator API """ -from .validate import validate_input, is_empty -from .constants import BASE_URLS, LINGUEE_LANGUAGES_TO_CODES -from .exceptions import ( - TranslationNotFound, - NotValidPayload, - ElementNotFoundInGetRequest, - RequestError, - TooManyRequests) -from .base import BaseTranslator +from deep_translator.validate import validate_input, is_empty +from deep_translator.constants import BASE_URLS, LINGUEE_LANGUAGES_TO_CODES +from deep_translator.exceptions import ( + TranslationNotFound, + NotValidPayload, + ElementNotFoundInGetRequest, + RequestError, + TooManyRequests, +) +from deep_translator.base import BaseTranslator from bs4 import BeautifulSoup import requests from requests.utils import requote_uri @@ -26,14 +27,15 @@ def __init__(self, source, target="en", proxies=None, **kwargs): @param target: target language to translate to """ self.proxies = proxies - super().__init__(base_url=BASE_URLS.get("LINGUEE"), - source=source, - target=target, - languages=LINGUEE_LANGUAGES_TO_CODES, - element_tag='a', - element_query={'class': 'dictLink featured'}, - payload_key=None, # key of text in the url - ) + super().__init__( + base_url=BASE_URLS.get("LINGUEE"), + source=source, + target=target, + languages=LINGUEE_LANGUAGES_TO_CODES, + element_tag="a", + element_query={"class": "dictLink featured"}, + payload_key=None, # key of text in the url + ) def translate(self, word, return_all=False, **kwargs): """ @@ -49,7 +51,9 @@ def translate(self, word, return_all=False, **kwargs): if validate_input(word, max_chars=50): # %s-%s/translation/%s.html - url = "{}{}-{}/translation/{}.html".format(self._base_url, self._source, self._target, word) + url = ( + f"{self._base_url}{self._source}-{self._target}/translation/{word}.html" + ) url = requote_uri(url) response = requests.get(url, proxies=self.proxies) @@ -58,7 +62,7 @@ def translate(self, word, return_all=False, **kwargs): if response.status_code != 200: raise RequestError() - soup = BeautifulSoup(response.text, 'html.parser') + soup = BeautifulSoup(response.text, "html.parser") elements = soup.find_all(self._element_tag, self._element_query) if not elements: raise ElementNotFoundInGetRequest(elements) @@ -66,10 +70,12 @@ def translate(self, word, return_all=False, **kwargs): filtered_elements = [] for el in elements: try: - pronoun = el.find('span', {'class': 'placeholder'}).get_text(strip=True) + pronoun = el.find("span", {"class": "placeholder"}).get_text( + strip=True + ) except AttributeError: - pronoun = '' - filtered_elements.append(el.get_text(strip=True).replace(pronoun, '')) + pronoun = "" + filtered_elements.append(el.get_text(strip=True).replace(pronoun, "")) if not filtered_elements: raise TranslationNotFound(word) @@ -90,4 +96,3 @@ def translate_words(self, words, **kwargs): for word in words: translated_words.append(self.translate(word=word, **kwargs)) return translated_words - diff --git a/deep_translator/microsoft.py b/deep_translator/microsoft.py index e2df049..95e6167 100644 --- a/deep_translator/microsoft.py +++ b/deep_translator/microsoft.py @@ -3,10 +3,10 @@ import requests import logging import sys -from .constants import BASE_URLS -from .exceptions import ServerException, MicrosoftAPIerror -from .base import BaseTranslator -from .validate import validate_input +from deep_translator.constants import BASE_URLS +from deep_translator.exceptions import ServerException, MicrosoftAPIerror +from deep_translator.base import BaseTranslator +from deep_translator.validate import validate_input class MicrosoftTranslator(BaseTranslator): @@ -14,7 +14,15 @@ class MicrosoftTranslator(BaseTranslator): the class that wraps functions, which use the Microsoft translator under the hood to translate word(s) """ - def __init__(self, api_key=None, region=None, source=None, target=None, proxies=None, **kwargs): + def __init__( + self, + api_key=None, + region=None, + source=None, + target=None, + proxies=None, + **kwargs, + ): """ @params api_key and target are the required params @param api_key: your Microsoft API key @@ -41,17 +49,16 @@ def __init__(self, api_key=None, region=None, source=None, target=None, proxies= source=source, target=target, languages=MICROSOFT_CODES_TO_LANGUAGES, - **kwargs + **kwargs, ) def _get_supported_languages(self): - microsoft_languages_api_url = \ - "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation" + microsoft_languages_api_url = "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation" microsoft_languages_response = requests.get(microsoft_languages_api_url) - translation_dict = microsoft_languages_response.json()['translation'] + translation_dict = microsoft_languages_response.json()["translation"] - return {translation_dict[k]['name'].lower(): k for k in translation_dict.keys()} + return {translation_dict[k]["name"].lower(): k for k in translation_dict.keys()} def translate(self, text, **kwargs): """ @@ -63,28 +70,31 @@ def translate(self, text, **kwargs): # I have not added multiple text processing here since it is covered by the translate_batch method if validate_input(text): - self._url_params['from'] = self._source - self._url_params['to'] = self._target + self._url_params["from"] = self._source + self._url_params["to"] = self._target - valid_microsoft_json = [{'text': text}] + valid_microsoft_json = [{"text": text}] try: - requested = requests.post(self._base_url, - params=self._url_params, - headers=self.headers, - json=valid_microsoft_json, - proxies=self.proxies) + requested = requests.post( + self._base_url, + params=self._url_params, + headers=self.headers, + json=valid_microsoft_json, + proxies=self.proxies, + ) except requests.exceptions.RequestException: exc_type, value, traceback = sys.exc_info() logging.warning(f"Returned error: {exc_type.__name__}") # Where Microsoft API responds with an api error, it returns a dict in response.json() if type(requested.json()) is dict: - error_message = requested.json()['error'] + error_message = requested.json()["error"] raise MicrosoftAPIerror(error_message) # Where it responds with a translation, its response.json() is a list e.g. [{'translations': [{'text': 'Hello world!', 'to': 'en'}]}] elif type(requested.json()) is list: - all_translations = [i['text'] - for i in requested.json()[0]['translations']] + all_translations = [ + i["text"] for i in requested.json()[0]["translations"] + ] return "\n".join(all_translations) def translate_file(self, path, **kwargs): diff --git a/deep_translator/mymemory.py b/deep_translator/mymemory.py index ea1262c..5275999 100644 --- a/deep_translator/mymemory.py +++ b/deep_translator/mymemory.py @@ -1,13 +1,14 @@ """ mymemory translator API """ -from .validate import is_empty, validate_input -from .constants import BASE_URLS -from .exceptions import ( - TranslationNotFound, - RequestError, - TooManyRequests) -from .base import BaseTranslator +from deep_translator.validate import is_empty, validate_input +from deep_translator.constants import BASE_URLS +from deep_translator.exceptions import ( + TranslationNotFound, + RequestError, + TooManyRequests, +) +from deep_translator.base import BaseTranslator import requests @@ -15,18 +16,20 @@ class MyMemoryTranslator(BaseTranslator): """ class that uses the mymemory translator to translate texts """ + def __init__(self, source="auto", target="en", proxies=None, **kwargs): """ @param source: source language to translate from @param target: target language to translate to """ self.proxies = proxies - self.email = kwargs.get('email', None) - super().__init__(base_url=BASE_URLS.get("MYMEMORY"), - source=source, - target=target, - payload_key='q', - ) + self.email = kwargs.get("email", None) + super().__init__( + base_url=BASE_URLS.get("MYMEMORY"), + source=source, + target=target, + payload_key="q", + ) def translate(self, text, return_all=False, **kwargs): """ @@ -41,15 +44,15 @@ def translate(self, text, return_all=False, **kwargs): if self._same_source_target() or is_empty(text): return text - self._url_params['langpair'] = '{}|{}'.format(self._source, self._target) + self._url_params["langpair"] = f"{self._source}|{self._target}" if self.payload_key: self._url_params[self.payload_key] = text if self.email: - self._url_params['de'] = self.email + self._url_params["de"] = self.email - response = requests.get(self._base_url, - params=self._url_params, - proxies=self.proxies) + response = requests.get( + self._base_url, params=self._url_params, proxies=self.proxies + ) if response.status_code == 429: raise TooManyRequests() @@ -60,24 +63,24 @@ def translate(self, text, return_all=False, **kwargs): if not data: TranslationNotFound(text) - translation = data.get('responseData').get('translatedText') + translation = data.get("responseData").get("translatedText") if translation: return translation elif not translation: - all_matches = data.get('matches') - matches = (match['translation'] for match in all_matches) + all_matches = data.get("matches") + matches = (match["translation"] for match in all_matches) next_match = next(matches) return next_match if not return_all else list(all_matches) def translate_file(self, path, **kwargs): """ - translate directly from file - @param path: path to the target file - @type path: str - @param kwargs: additional args - @return: str - """ + translate directly from file + @param path: path to the target file + @type path: str + @param kwargs: additional args + @return: str + """ return self._translate_file(path, **kwargs) def translate_batch(self, batch=None, **kwargs): diff --git a/deep_translator/papago.py b/deep_translator/papago.py index 2d22e36..70322b4 100644 --- a/deep_translator/papago.py +++ b/deep_translator/papago.py @@ -2,12 +2,12 @@ google translator API """ import json -from .constants import BASE_URLS, PAPAGO_LANGUAGE_TO_CODE -from .exceptions import TranslationNotFound -from .base import BaseTranslator +from deep_translator.constants import BASE_URLS, PAPAGO_LANGUAGE_TO_CODE +from deep_translator.exceptions import TranslationNotFound +from deep_translator.base import BaseTranslator import requests -from .validate import validate_input +from deep_translator.validate import validate_input class PapagoTranslator(BaseTranslator): @@ -15,14 +15,17 @@ class PapagoTranslator(BaseTranslator): class that wraps functions, which use google translate under the hood to translate text(s) """ - def __init__(self, client_id=None, secret_key=None, source="auto", target="en", **kwargs): + def __init__( + self, client_id=None, secret_key=None, source="auto", target="en", **kwargs + ): """ @param source: source language to translate from @param target: target language to translate to """ if not client_id or not secret_key: raise Exception( - "Please pass your client id and secret key! visit the papago website for more infos") + "Please pass your client id and secret key! visit the papago website for more infos" + ) self.client_id = client_id self.secret_key = secret_key @@ -31,7 +34,7 @@ def __init__(self, client_id=None, secret_key=None, source="auto", target="en", source=source, target=target, languages=PAPAGO_LANGUAGE_TO_CODE, - **kwargs + **kwargs, ) def translate(self, text, **kwargs): @@ -41,21 +44,17 @@ def translate(self, text, **kwargs): @return: str: translated text """ if validate_input(text): - payload = { - "source": self._source, - "target": self._target, - "text": text - } + payload = {"source": self._source, "target": self._target, "text": text} headers = { - 'X-Naver-Client-Id': self.client_id, - 'X-Naver-Client-Secret': self.secret_key, - 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' + "X-Naver-Client-Id": self.client_id, + "X-Naver-Client-Secret": self.secret_key, + "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", } - response = requests.post( - self._base_url, headers=headers, data=payload) + response = requests.post(self._base_url, headers=headers, data=payload) if response.status_code != 200: raise Exception( - f'Translation error! -> status code: {response.status_code}') + f"Translation error! -> status code: {response.status_code}" + ) res_body = json.loads(response.text) if "message" not in res_body: raise TranslationNotFound(text) diff --git a/deep_translator/pons.py b/deep_translator/pons.py index 5073d26..e517177 100644 --- a/deep_translator/pons.py +++ b/deep_translator/pons.py @@ -4,15 +4,16 @@ from bs4 import BeautifulSoup import requests -from .validate import validate_input, is_empty -from .constants import BASE_URLS, PONS_CODES_TO_LANGUAGES -from .exceptions import ( - TranslationNotFound, - NotValidPayload, - ElementNotFoundInGetRequest, - RequestError, - TooManyRequests) -from .base import BaseTranslator +from deep_translator.validate import validate_input, is_empty +from deep_translator.constants import BASE_URLS, PONS_CODES_TO_LANGUAGES +from deep_translator.exceptions import ( + TranslationNotFound, + NotValidPayload, + ElementNotFoundInGetRequest, + RequestError, + TooManyRequests, +) +from deep_translator.base import BaseTranslator from requests.utils import requote_uri @@ -27,15 +28,16 @@ def __init__(self, source, target="en", proxies=None, **kwargs): @param target: target language to translate to """ self.proxies = proxies - super().__init__(base_url=BASE_URLS.get("PONS"), - languages=PONS_CODES_TO_LANGUAGES, - source=source, - target=target, - payload_key=None, - element_tag='div', - element_query={"class": "target"}, - **kwargs - ) + super().__init__( + base_url=BASE_URLS.get("PONS"), + languages=PONS_CODES_TO_LANGUAGES, + source=source, + target=target, + payload_key=None, + element_tag="div", + element_query={"class": "target"}, + **kwargs, + ) def translate(self, word, return_all=False, **kwargs): """ @@ -49,7 +51,7 @@ def translate(self, word, return_all=False, **kwargs): if validate_input(word, max_chars=50): if self._same_source_target() or is_empty(word): return word - url = "{}{}-{}/{}".format(self._base_url, self._source, self._target, word) + url = f"{self._base_url}{self._source}-{self._target}/{word}" url = requote_uri(url) response = requests.get(url, proxies=self.proxies) @@ -59,7 +61,7 @@ def translate(self, word, return_all=False, **kwargs): if response.status_code != 200: raise RequestError() - soup = BeautifulSoup(response.text, 'html.parser') + soup = BeautifulSoup(response.text, "html.parser") elements = soup.findAll(self._element_tag, self._element_query) if not elements: @@ -67,9 +69,9 @@ def translate(self, word, return_all=False, **kwargs): filtered_elements = [] for el in elements: - temp = '' - for e in el.findAll('a'): - temp += e.get_text() + ' ' + temp = "" + for e in el.findAll("a"): + temp += e.get_text() + " " filtered_elements.append(temp) if not filtered_elements: @@ -96,4 +98,3 @@ def translate_words(self, words, **kwargs): for word in words: translated_words.append(self.translate(word=word, **kwargs)) return translated_words - diff --git a/deep_translator/qcri.py b/deep_translator/qcri.py index a0958fa..9b8a2bb 100644 --- a/deep_translator/qcri.py +++ b/deep_translator/qcri.py @@ -1,8 +1,7 @@ - import requests -from .constants import BASE_URLS, QCRI_LANGUAGE_TO_CODE -from .exceptions import (ServerException, TranslationNotFound) -from .base import BaseTranslator +from deep_translator.constants import BASE_URLS, QCRI_LANGUAGE_TO_CODE +from deep_translator.exceptions import ServerException, TranslationNotFound +from deep_translator.base import BaseTranslator class QcriTranslator(BaseTranslator): @@ -24,23 +23,23 @@ def __init__(self, api_key=None, source="en", target="en", **kwargs): "translate": "translate", } - self.params = { - "key": self.api_key - } + self.params = {"key": self.api_key} super().__init__( base_url=BASE_URLS.get("QcriTranslator"), source=source, target=target, languages=QCRI_LANGUAGE_TO_CODE, - **kwargs + **kwargs, ) def _get(self, endpoint, params=None, return_text=True): if not params: params = self.params try: - res = requests.get(self._base_url.format( - endpoint=self.api_endpoints[endpoint]), params=params) + res = requests.get( + self._base_url.format(endpoint=self.api_endpoints[endpoint]), + params=params, + ) return res.text if return_text else res except Exception as e: raise e @@ -60,9 +59,9 @@ def domains(self): def translate(self, text, **kwargs): params = { "key": self.api_key, - "langpair": "{}-{}".format(self._source, self._target), + "langpair": f"{self._source}-{self._target}", "domain": kwargs["domain"], - "text": text + "text": text, } try: response = self._get("translate", params=params, return_text=False) diff --git a/deep_translator/validate.py b/deep_translator/validate.py index 8480419..92f19a1 100644 --- a/deep_translator/validate.py +++ b/deep_translator/validate.py @@ -1,6 +1,4 @@ - -from .exceptions import NotValidPayload, NotValidLength -import string +from deep_translator.exceptions import NotValidPayload, NotValidLength def is_empty(text: str): diff --git a/deep_translator/yandex.py b/deep_translator/yandex.py index 2eac0f5..ef1c003 100644 --- a/deep_translator/yandex.py +++ b/deep_translator/yandex.py @@ -2,10 +2,15 @@ Yandex translator API """ import requests -from .constants import BASE_URLS -from .exceptions import (RequestError, ServerException, - TranslationNotFound, TooManyRequests) -from .base import BaseTranslator +from deep_translator.constants import BASE_URLS +from deep_translator.exceptions import ( + RequestError, + ServerException, + TranslationNotFound, + TooManyRequests, +) +from deep_translator.base import BaseTranslator +from deep_translator.validate import validate_input class YandexTranslator(BaseTranslator): @@ -27,10 +32,7 @@ def __init__(self, api_key=None, source="en", target="de", **kwargs): "translate": "translate", } super().__init__( - base_url=BASE_URLS.get("YANDEX"), - source=source, - target=target, - **kwargs + base_url=BASE_URLS.get("YANDEX"), source=source, target=target, **kwargs ) def _get_supported_languages(self): @@ -44,11 +46,9 @@ def languages(self): def dirs(self, proxies=None): try: - url = self._base_url.format( - version=self.api_version, endpoint="getLangs") + url = self._base_url.format(version=self.api_version, endpoint="getLangs") print("url: ", url) - response = requests.get( - url, params={"key": self.api_key}, proxies=proxies) + response = requests.get(url, params={"key": self.api_key}, proxies=proxies) except requests.exceptions.ConnectionError: raise ServerException(503) else: @@ -66,8 +66,7 @@ def detect(self, text, proxies=None): "key": self.api_key, } try: - url = self._base_url.format( - version=self.api_version, endpoint="detect") + url = self._base_url.format(version=self.api_version, endpoint="detect") response = requests.post(url, data=params, proxies=proxies) except RequestError: @@ -78,8 +77,8 @@ def detect(self, text, proxies=None): raise ServerException(response.status_code) else: response = response.json() - language = response['lang'] - status_code = response['code'] + language = response["lang"] + status_code = response["code"] if status_code != 200: raise RequestError() elif not language: @@ -91,28 +90,31 @@ def translate(self, text, proxies=None, **kwargs): params = { "text": text, "format": "plain", - "lang": self._target if self._source == "auto" else "{}-{}".format(self._source, self._target), - "key": self.api_key + "lang": self._target + if self._source == "auto" + else "{}-{}".format(self._source, self._target), + "key": self.api_key, } try: url = self._base_url.format( - version=self.api_version, endpoint="translate") + version=self.api_version, endpoint="translate" + ) response = requests.post(url, data=params, proxies=proxies) except ConnectionError: raise ServerException(503) else: response = response.json() - if response['code'] == 429: + if response["code"] == 429: raise TooManyRequests() - if response['code'] != 200: - raise ServerException(response['code']) + if response["code"] != 200: + raise ServerException(response["code"]) - if not response['text']: + if not response["text"]: raise TranslationNotFound() - return response['text'] + return response["text"] def translate_file(self, path, **kwargs): """ @@ -129,4 +131,3 @@ def translate_batch(self, batch, **kwargs): @return: list of translations """ return self._translate_batch(batch, **kwargs) - diff --git a/poetry.lock b/poetry.lock index ad6e477..c3da6de 100644 --- a/poetry.lock +++ b/poetry.lock @@ -54,6 +54,29 @@ soupsieve = ">1.2" html5lib = ["html5lib"] lxml = ["lxml"] +[[package]] +name = "black" +version = "22.1.0" +description = "The uncompromising code formatter." +category = "dev" +optional = false +python-versions = ">=3.6.2" + +[package.dependencies] +click = ">=8.0.0" +mypy-extensions = ">=0.4.3" +pathspec = ">=0.9.0" +platformdirs = ">=2" +tomli = ">=1.1.0" +typed-ast = {version = ">=1.4.2", markers = "python_version < \"3.8\" and implementation_name == \"cpython\""} +typing-extensions = {version = ">=3.10.0.0", markers = "python_version < \"3.10\""} + +[package.extras] +colorama = ["colorama (>=0.4.3)"] +d = ["aiohttp (>=3.7.4)"] +jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"] +uvloop = ["uvloop (>=0.15.2)"] + [[package]] name = "bleach" version = "4.1.0" @@ -97,6 +120,18 @@ python-versions = ">=3.5.0" [package.extras] unicode_backport = ["unicodedata2"] +[[package]] +name = "click" +version = "8.0.4" +description = "Composable command line interface toolkit" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +colorama = {version = "*", markers = "platform_system == \"Windows\""} +importlib-metadata = {version = "*", markers = "python_version < \"3.8\""} + [[package]] name = "colorama" version = "0.4.4" @@ -236,6 +271,14 @@ category = "dev" optional = false python-versions = ">=3.6" +[[package]] +name = "mypy-extensions" +version = "0.4.3" +description = "Experimental type system extensions for programs checked with the mypy typechecker." +category = "dev" +optional = false +python-versions = "*" + [[package]] name = "packaging" version = "21.3" @@ -247,6 +290,14 @@ python-versions = ">=3.6" [package.dependencies] pyparsing = ">=2.0.2,<3.0.5 || >3.0.5" +[[package]] +name = "pathspec" +version = "0.9.0" +description = "Utility library for gitignore style pattern matching of file paths." +category = "dev" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" + [[package]] name = "pkginfo" version = "1.8.2" @@ -258,6 +309,18 @@ python-versions = "*" [package.extras] testing = ["coverage", "nose"] +[[package]] +name = "platformdirs" +version = "2.5.1" +description = "A small Python module for determining appropriate platform-specific dirs, e.g. a \"user data dir\"." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["Sphinx (>=4)", "furo (>=2021.7.5b38)", "proselint (>=0.10.2)", "sphinx-autodoc-typehints (>=1.12)"] +test = ["appdirs (==1.4.4)", "pytest (>=6)", "pytest-cov (>=2.7)", "pytest-mock (>=3.6)"] + [[package]] name = "pluggy" version = "1.0.0" @@ -561,6 +624,14 @@ category = "dev" optional = false python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" +[[package]] +name = "tomli" +version = "2.0.1" +description = "A lil' TOML parser" +category = "dev" +optional = false +python-versions = ">=3.7" + [[package]] name = "tqdm" version = "4.62.3" @@ -597,6 +668,14 @@ rfc3986 = ">=1.4.0" tqdm = ">=4.14" urllib3 = ">=1.26.0" +[[package]] +name = "typed-ast" +version = "1.5.2" +description = "a fork of Python 2 and 3 ast modules with type comment support" +category = "dev" +optional = false +python-versions = ">=3.6" + [[package]] name = "typing-extensions" version = "4.0.1" @@ -641,7 +720,7 @@ testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest- [metadata] lock-version = "1.1" python-versions = "^3.7" -content-hash = "2877a59ad1ac817881dcea5583bd7f07310ab5da4301dda5dadbe598b9ec6511" +content-hash = "465ff9b79ec7a4f8f67638bed33190079fbe1dcca8261d36813c7787e30624f2" [metadata.files] alabaster = [ @@ -664,6 +743,31 @@ beautifulsoup4 = [ {file = "beautifulsoup4-4.10.0-py3-none-any.whl", hash = "sha256:9a315ce70049920ea4572a4055bc4bd700c940521d36fc858205ad4fcde149bf"}, {file = "beautifulsoup4-4.10.0.tar.gz", hash = "sha256:c23ad23c521d818955a4151a67d81580319d4bf548d3d49f4223ae041ff98891"}, ] +black = [ + {file = "black-22.1.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:1297c63b9e1b96a3d0da2d85d11cd9bf8664251fd69ddac068b98dc4f34f73b6"}, + {file = "black-22.1.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:2ff96450d3ad9ea499fc4c60e425a1439c2120cbbc1ab959ff20f7c76ec7e866"}, + {file = "black-22.1.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0e21e1f1efa65a50e3960edd068b6ae6d64ad6235bd8bfea116a03b21836af71"}, + {file = "black-22.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e2f69158a7d120fd641d1fa9a921d898e20d52e44a74a6fbbcc570a62a6bc8ab"}, + {file = "black-22.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:228b5ae2c8e3d6227e4bde5920d2fc66cc3400fde7bcc74f480cb07ef0b570d5"}, + {file = "black-22.1.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:b1a5ed73ab4c482208d20434f700d514f66ffe2840f63a6252ecc43a9bc77e8a"}, + {file = "black-22.1.0-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:35944b7100af4a985abfcaa860b06af15590deb1f392f06c8683b4381e8eeaf0"}, + {file = "black-22.1.0-cp36-cp36m-win_amd64.whl", hash = "sha256:7835fee5238fc0a0baf6c9268fb816b5f5cd9b8793423a75e8cd663c48d073ba"}, + {file = "black-22.1.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:dae63f2dbf82882fa3b2a3c49c32bffe144970a573cd68d247af6560fc493ae1"}, + {file = "black-22.1.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5fa1db02410b1924b6749c245ab38d30621564e658297484952f3d8a39fce7e8"}, + {file = "black-22.1.0-cp37-cp37m-win_amd64.whl", hash = "sha256:c8226f50b8c34a14608b848dc23a46e5d08397d009446353dad45e04af0c8e28"}, + {file = "black-22.1.0-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:2d6f331c02f0f40aa51a22e479c8209d37fcd520c77721c034517d44eecf5912"}, + {file = "black-22.1.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:742ce9af3086e5bd07e58c8feb09dbb2b047b7f566eb5f5bc63fd455814979f3"}, + {file = "black-22.1.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:fdb8754b453fb15fad3f72cd9cad3e16776f0964d67cf30ebcbf10327a3777a3"}, + {file = "black-22.1.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f5660feab44c2e3cb24b2419b998846cbb01c23c7fe645fee45087efa3da2d61"}, + {file = "black-22.1.0-cp38-cp38-win_amd64.whl", hash = "sha256:6f2f01381f91c1efb1451998bd65a129b3ed6f64f79663a55fe0e9b74a5f81fd"}, + {file = "black-22.1.0-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:efbadd9b52c060a8fc3b9658744091cb33c31f830b3f074422ed27bad2b18e8f"}, + {file = "black-22.1.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8871fcb4b447206904932b54b567923e5be802b9b19b744fdff092bd2f3118d0"}, + {file = "black-22.1.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:ccad888050f5393f0d6029deea2a33e5ae371fd182a697313bdbd835d3edaf9c"}, + {file = "black-22.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:07e5c049442d7ca1a2fc273c79d1aecbbf1bc858f62e8184abe1ad175c4f7cc2"}, + {file = "black-22.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:373922fc66676133ddc3e754e4509196a8c392fec3f5ca4486673e685a421321"}, + {file = "black-22.1.0-py3-none-any.whl", hash = "sha256:3524739d76b6b3ed1132422bf9d82123cd1705086723bc3e235ca39fd21c667d"}, + {file = "black-22.1.0.tar.gz", hash = "sha256:a7c0192d35635f6fc1174be575cb7915e92e5dd629ee79fdaf0dcfa41a80afb5"}, +] bleach = [ {file = "bleach-4.1.0-py2.py3-none-any.whl", hash = "sha256:4d2651ab93271d1129ac9cbc679f524565cc8a1b791909c4a51eac4446a15994"}, {file = "bleach-4.1.0.tar.gz", hash = "sha256:0900d8b37eba61a802ee40ac0061f8c2b5dee29c1927dd1d233e075ebf5a71da"}, @@ -728,6 +832,10 @@ charset-normalizer = [ {file = "charset-normalizer-2.0.11.tar.gz", hash = "sha256:98398a9d69ee80548c762ba991a4728bfc3836768ed226b3945908d1a688371c"}, {file = "charset_normalizer-2.0.11-py3-none-any.whl", hash = "sha256:2842d8f5e82a1f6aa437380934d5e1cd4fcf2003b06fed6940769c164a480a45"}, ] +click = [ + {file = "click-8.0.4-py3-none-any.whl", hash = "sha256:6a7a62563bbfabfda3a38f3023a1db4a35978c0abd76f6c9605ecd6554d6d9b1"}, + {file = "click-8.0.4.tar.gz", hash = "sha256:8458d7b1287c5fb128c90e23381cf99dcde74beaf6c7ff6384ce84d6fe090adb"}, +] colorama = [ {file = "colorama-0.4.4-py2.py3-none-any.whl", hash = "sha256:9f47eda37229f68eee03b24b9748937c7dc3868f906e8ba69fbcbdd3bc5dc3e2"}, {file = "colorama-0.4.4.tar.gz", hash = "sha256:5941b2b48a20143d2267e95b1c2a7603ce057ee39fd88e7329b0c292aa16869b"}, @@ -876,14 +984,26 @@ markupsafe = [ {file = "MarkupSafe-2.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:693ce3f9e70a6cf7d2fb9e6c9d8b204b6b39897a2c4a1aa65728d5ac97dcc1d8"}, {file = "MarkupSafe-2.0.1.tar.gz", hash = "sha256:594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a"}, ] +mypy-extensions = [ + {file = "mypy_extensions-0.4.3-py2.py3-none-any.whl", hash = "sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d"}, + {file = "mypy_extensions-0.4.3.tar.gz", hash = "sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8"}, +] packaging = [ {file = "packaging-21.3-py3-none-any.whl", hash = "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522"}, {file = "packaging-21.3.tar.gz", hash = "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"}, ] +pathspec = [ + {file = "pathspec-0.9.0-py2.py3-none-any.whl", hash = "sha256:7d15c4ddb0b5c802d161efc417ec1a2558ea2653c2e8ad9c19098201dc1c993a"}, + {file = "pathspec-0.9.0.tar.gz", hash = "sha256:e564499435a2673d586f6b2130bb5b95f04a3ba06f81b8f895b651a3c76aabb1"}, +] pkginfo = [ {file = "pkginfo-1.8.2-py2.py3-none-any.whl", hash = "sha256:c24c487c6a7f72c66e816ab1796b96ac6c3d14d49338293d2141664330b55ffc"}, {file = "pkginfo-1.8.2.tar.gz", hash = "sha256:542e0d0b6750e2e21c20179803e40ab50598d8066d51097a0e382cba9eb02bff"}, ] +platformdirs = [ + {file = "platformdirs-2.5.1-py3-none-any.whl", hash = "sha256:bcae7cab893c2d310a711b70b24efb93334febe65f8de776ee320b517471e227"}, + {file = "platformdirs-2.5.1.tar.gz", hash = "sha256:7535e70dfa32e84d4b34996ea99c5e432fa29a708d0f4e394bbcb2a8faa4f16d"}, +] pluggy = [ {file = "pluggy-1.0.0-py2.py3-none-any.whl", hash = "sha256:74134bbf457f031a36d68416e1509f34bd5ccc019f0bcc952c7b909d06b37bd3"}, {file = "pluggy-1.0.0.tar.gz", hash = "sha256:4224373bacce55f955a878bf9cfa763c1e360858e330072059e10bad68531159"}, @@ -984,6 +1104,10 @@ toml = [ {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, ] +tomli = [ + {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, + {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, +] tqdm = [ {file = "tqdm-4.62.3-py2.py3-none-any.whl", hash = "sha256:8dd278a422499cd6b727e6ae4061c40b48fce8b76d1ccbf5d34fca9b7f925b0c"}, {file = "tqdm-4.62.3.tar.gz", hash = "sha256:d359de7217506c9851b7869f3708d8ee53ed70a1b8edbba4dbcb47442592920d"}, @@ -992,6 +1116,32 @@ twine = [ {file = "twine-3.8.0-py3-none-any.whl", hash = "sha256:d0550fca9dc19f3d5e8eadfce0c227294df0a2a951251a4385797c8a6198b7c8"}, {file = "twine-3.8.0.tar.gz", hash = "sha256:8efa52658e0ae770686a13b675569328f1fba9837e5de1867bfe5f46a9aefe19"}, ] +typed-ast = [ + {file = "typed_ast-1.5.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:183b183b7771a508395d2cbffd6db67d6ad52958a5fdc99f450d954003900266"}, + {file = "typed_ast-1.5.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:676d051b1da67a852c0447621fdd11c4e104827417bf216092ec3e286f7da596"}, + {file = "typed_ast-1.5.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bc2542e83ac8399752bc16e0b35e038bdb659ba237f4222616b4e83fb9654985"}, + {file = "typed_ast-1.5.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:74cac86cc586db8dfda0ce65d8bcd2bf17b58668dfcc3652762f3ef0e6677e76"}, + {file = "typed_ast-1.5.2-cp310-cp310-win_amd64.whl", hash = "sha256:18fe320f354d6f9ad3147859b6e16649a0781425268c4dde596093177660e71a"}, + {file = "typed_ast-1.5.2-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:31d8c6b2df19a777bc8826770b872a45a1f30cfefcfd729491baa5237faae837"}, + {file = "typed_ast-1.5.2-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:963a0ccc9a4188524e6e6d39b12c9ca24cc2d45a71cfdd04a26d883c922b4b78"}, + {file = "typed_ast-1.5.2-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:0eb77764ea470f14fcbb89d51bc6bbf5e7623446ac4ed06cbd9ca9495b62e36e"}, + {file = "typed_ast-1.5.2-cp36-cp36m-win_amd64.whl", hash = "sha256:294a6903a4d087db805a7656989f613371915fc45c8cc0ddc5c5a0a8ad9bea4d"}, + {file = "typed_ast-1.5.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:26a432dc219c6b6f38be20a958cbe1abffcc5492821d7e27f08606ef99e0dffd"}, + {file = "typed_ast-1.5.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c7407cfcad702f0b6c0e0f3e7ab876cd1d2c13b14ce770e412c0c4b9728a0f88"}, + {file = "typed_ast-1.5.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f30ddd110634c2d7534b2d4e0e22967e88366b0d356b24de87419cc4410c41b7"}, + {file = "typed_ast-1.5.2-cp37-cp37m-win_amd64.whl", hash = "sha256:8c08d6625bb258179b6e512f55ad20f9dfef019bbfbe3095247401e053a3ea30"}, + {file = "typed_ast-1.5.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:90904d889ab8e81a956f2c0935a523cc4e077c7847a836abee832f868d5c26a4"}, + {file = "typed_ast-1.5.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:bbebc31bf11762b63bf61aaae232becb41c5bf6b3461b80a4df7e791fabb3aca"}, + {file = "typed_ast-1.5.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c29dd9a3a9d259c9fa19d19738d021632d673f6ed9b35a739f48e5f807f264fb"}, + {file = "typed_ast-1.5.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:58ae097a325e9bb7a684572d20eb3e1809802c5c9ec7108e85da1eb6c1a3331b"}, + {file = "typed_ast-1.5.2-cp38-cp38-win_amd64.whl", hash = "sha256:da0a98d458010bf4fe535f2d1e367a2e2060e105978873c04c04212fb20543f7"}, + {file = "typed_ast-1.5.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:33b4a19ddc9fc551ebabca9765d54d04600c4a50eda13893dadf67ed81d9a098"}, + {file = "typed_ast-1.5.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1098df9a0592dd4c8c0ccfc2e98931278a6c6c53cb3a3e2cf7e9ee3b06153344"}, + {file = "typed_ast-1.5.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:42c47c3b43fe3a39ddf8de1d40dbbfca60ac8530a36c9b198ea5b9efac75c09e"}, + {file = "typed_ast-1.5.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f290617f74a610849bd8f5514e34ae3d09eafd521dceaa6cf68b3f4414266d4e"}, + {file = "typed_ast-1.5.2-cp39-cp39-win_amd64.whl", hash = "sha256:df05aa5b241e2e8045f5f4367a9f6187b09c4cdf8578bb219861c4e27c443db5"}, + {file = "typed_ast-1.5.2.tar.gz", hash = "sha256:525a2d4088e70a9f75b08b3f87a51acc9cde640e19cc523c7e41aa355564ae27"}, +] typing-extensions = [ {file = "typing_extensions-4.0.1-py3-none-any.whl", hash = "sha256:7f001e5ac290a0c0401508864c7ec868be4e701886d5b573a9528ed3973d9d3b"}, {file = "typing_extensions-4.0.1.tar.gz", hash = "sha256:4ca091dea149f945ec56afb48dae714f21e8692ef22a395223bcd328961b6a0e"}, diff --git a/pyproject.toml b/pyproject.toml index a716b20..ad54707 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,6 +40,7 @@ twine = "^3.4.2" pytest = "^6.2.4" pytest-runner = "^5.3.1" toml = "^0.10.2" +black = "^22.1.0" [build-system] requires = ["poetry-core>=1.0.0"] diff --git a/tests/test_cli.py b/tests/test_cli.py index e8682b1..e632cb1 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -9,15 +9,13 @@ @pytest.fixture def mock_args(): - sys.argv[1:] = ['--source', 'en', '--target', 'de', '--text', 'hello'] + sys.argv[1:] = ["--source", "en", "--target", "de", "--text", "hello"] return CLI(sys.argv[1:]).parse_args() def test_source(mock_args): - assert mock_args.source == 'en' + assert mock_args.source == "en" def test_target(mock_args): - assert mock_args.target == 'de' - - + assert mock_args.target == "de" diff --git a/tests/test_data.py b/tests/test_data.py index 6b647ce..7c77e96 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -1,4 +1,4 @@ -test_text_standard = 'Hello world.' +test_text_standard = "Hello world." TRANSLATED_RESULTS = { "afrikaans": "Hello Wêreld.", @@ -108,5 +108,5 @@ "xhosa": "Molo Lizwe.", "yiddish": "העלא וועלט.", "yoruba": "Mo ki O Ile Aiye.", - "zulu": "Sawubona Mhlaba." + "zulu": "Sawubona Mhlaba.", } diff --git a/tests/test_deepl.py b/tests/test_deepl.py index 84c780f..9c9473c 100644 --- a/tests/test_deepl.py +++ b/tests/test_deepl.py @@ -4,26 +4,26 @@ from deep_translator.exceptions import AuthorizationException -@patch('deep_translator.deepl.requests') +@patch("deep_translator.deepl.requests") def test_simple_translation(mock_requests): - translator = DeeplTranslator(api_key='imagine-this-is-an-valid-api-key', source='en', target='es') + translator = DeeplTranslator( + api_key="imagine-this-is-an-valid-api-key", source="en", target="es" + ) # Set the request response mock. mock_response = Mock() mock_response.status_code = 200 - mock_response.json.return_value = { - "translations": [{ - "text": "hola" - }] - } + mock_response.json.return_value = {"translations": [{"text": "hola"}]} mock_requests.get.return_value = mock_response - translation = translator.translate('hello') - assert translation == 'hola' + translation = translator.translate("hello") + assert translation == "hola" -@patch('deep_translator.deepl.requests.get') +@patch("deep_translator.deepl.requests.get") def test_wrong_api_key(mock_requests): - translator = DeeplTranslator(api_key='this-is-a-wrong-api-key!', source="en", target="es") + translator = DeeplTranslator( + api_key="this-is-a-wrong-api-key!", source="en", target="es" + ) # Set the response status_code only. mock_requests.return_value = Mock(status_code=403) with pytest.raises(AuthorizationException): - translator.translate('Hello') + translator.translate("Hello") diff --git a/tests/test_google.py b/tests/test_google.py index a670b27..de60042 100644 --- a/tests/test_google.py +++ b/tests/test_google.py @@ -12,12 +12,12 @@ def google_translator(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ - return GoogleTranslator(target='en') + return GoogleTranslator(target="en") def test_content(google_translator): """Sample pytest test function with the pytest fixture as an argument.""" - assert google_translator.translate(text='좋은') == "good" + assert google_translator.translate(text="좋은") == "good" def test_abbreviations_and_languages_mapping(): @@ -47,9 +47,9 @@ def test_empty_text(google_translator): def test_payload(google_translator): with pytest.raises(exceptions.NotValidPayload): - google_translator.translate(text='1234') - google_translator.translate(text='{}') - google_translator.translate(text='%@') + google_translator.translate(text="1234") + google_translator.translate(text="{}") + google_translator.translate(text="%@") with pytest.raises(exceptions.NotValidPayload): google_translator.translate(text=123) @@ -61,8 +61,8 @@ def test_payload(google_translator): google_translator.translate(text=[]) with pytest.raises(exceptions.NotValidLength): - google_translator.translate("a"*5001) + google_translator.translate("a" * 5001) def test_one_character_words(): - assert GoogleTranslator(source='es', target='en').translate('o') == 'or' + assert GoogleTranslator(source="es", target="en").translate("o") == "or" diff --git a/tests/test_libre.py b/tests/test_libre.py index 36a4163..b078c1e 100644 --- a/tests/test_libre.py +++ b/tests/test_libre.py @@ -9,24 +9,24 @@ @pytest.fixture def libre(): - return LibreTranslator(source="en", target='fr', api_key='some_key') + return LibreTranslator(source="en", target="fr", api_key="some_key") def test_inputs(): with pytest.raises(exceptions.InvalidSourceOrTargetLanguage): - LibreTranslator(source="", target="", api_key='some_key') + LibreTranslator(source="", target="", api_key="some_key") with pytest.raises(exceptions.InvalidSourceOrTargetLanguage): - LibreTranslator(source="auto", target="", api_key='some_key') + LibreTranslator(source="auto", target="", api_key="some_key") with pytest.raises(exceptions.InvalidSourceOrTargetLanguage): - LibreTranslator(source="", target="en", api_key='some_key') + LibreTranslator(source="", target="en", api_key="some_key") def test_abbreviations_and_languages_mapping(): for abb, lang in LIBRE_CODES_TO_LANGUAGES.items(): - l1 = LibreTranslator(abb, api_key='some_key') - l2 = LibreTranslator(lang, api_key='some_key') + l1 = LibreTranslator(abb, api_key="some_key") + l2 = LibreTranslator(lang, api_key="some_key") assert l1._source == l2._source diff --git a/tests/test_linguee.py b/tests/test_linguee.py index f5e7892..7e80741 100644 --- a/tests/test_linguee.py +++ b/tests/test_linguee.py @@ -8,14 +8,14 @@ @pytest.fixture def linguee(): - return LingueeTranslator(source="english", target='german') + return LingueeTranslator(source="english", target="german") def test_content(linguee): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string - assert linguee.translate(word='good') is not None + assert linguee.translate(word="good") is not None def test_inputs(): @@ -46,4 +46,4 @@ def test_payload(linguee): linguee.translate([]) with pytest.raises(exceptions.NotValidLength): - linguee.translate("a"*51) + linguee.translate("a" * 51) diff --git a/tests/test_microsoft_trans.py b/tests/test_microsoft_trans.py index 83ae842..891acba 100644 --- a/tests/test_microsoft_trans.py +++ b/tests/test_microsoft_trans.py @@ -10,22 +10,31 @@ # mocked request.post -@patch.object(requests, 'post') +@patch.object(requests, "post") def test_microsoft_successful_post_mock(mock_request_post): - returned_json = [{'translations': [{'text': 'See you later!', 'to': 'en'}]}] + returned_json = [{"translations": [{"text": "See you later!", "to": "en"}]}] + def res(): r = requests.Response() + def json_func(): return returned_json + r.json = json_func return r + mock_request_post.return_value = res() - assert MicrosoftTranslator(api_key="an_api_key", source='de', target="en").translate("auf wiedersehen!") == "See you later!" + assert ( + MicrosoftTranslator(api_key="an_api_key", source="de", target="en").translate( + "auf wiedersehen!" + ) + == "See you later!" + ) def test_MicrosoftAPIerror(): with pytest.raises(exceptions.MicrosoftAPIerror): - MicrosoftTranslator(api_key="empty", source='de', target="en").translate("text") + MicrosoftTranslator(api_key="empty", source="de", target="en").translate("text") # the remaining tests are actual requests to Microsoft API and use an api key @@ -36,13 +45,17 @@ def test_MicrosoftAPIerror(): @pytest.mark.skipif(APIkey is None, reason="api_key is not provided") def test_microsoft_successful_post_onetarget(): - posted = MicrosoftTranslator(api_key=APIkey, target="en").translate("auf wiedersehen!") + posted = MicrosoftTranslator(api_key=APIkey, target="en").translate( + "auf wiedersehen!" + ) assert isinstance(posted, str) @pytest.mark.skipif(APIkey is None, reason="api_key is not provided") def test_microsoft_successful_post_twotargets(): - posted = MicrosoftTranslator(api_key=APIkey, target=["en", "ru"]).translate("auf wiedersehen!") + posted = MicrosoftTranslator(api_key=APIkey, target=["en", "ru"]).translate( + "auf wiedersehen!" + ) assert isinstance(posted, str) @@ -58,5 +71,5 @@ def test_incorrect_target_attributes(): def test_abbreviations(): m1 = MicrosoftTranslator(api_key=APIkey, source="en", target="fr") m2 = MicrosoftTranslator(api_key=APIkey, source="English", target="French") - assert ''.join(m1._source) == ''.join(m2._source) - assert ''.join(m1._target) == ''.join(m2._target) + assert "".join(m1._source) == "".join(m2._source) + assert "".join(m1._target) == "".join(m2._target) diff --git a/tests/test_mymemory.py b/tests/test_mymemory.py index 8c7c213..a0e21b1 100644 --- a/tests/test_mymemory.py +++ b/tests/test_mymemory.py @@ -8,14 +8,14 @@ @pytest.fixture def mymemory(): - return MyMemoryTranslator(source="en", target='fr') + return MyMemoryTranslator(source="en", target="fr") def test_content(mymemory): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string - assert mymemory.translate(text='good') is not None + assert mymemory.translate(text="good") is not None def test_inputs(): @@ -46,6 +46,4 @@ def test_payload(mymemory): mymemory.translate(text=[]) with pytest.raises(exceptions.NotValidLength): - mymemory.translate(text="a"*501) - - + mymemory.translate(text="a" * 501) diff --git a/tests/test_pons.py b/tests/test_pons.py index 74dd30f..79e661d 100644 --- a/tests/test_pons.py +++ b/tests/test_pons.py @@ -8,14 +8,14 @@ @pytest.fixture def pons(): - return PonsTranslator(source="english", target='french') + return PonsTranslator(source="english", target="french") def test_content(pons): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string - assert pons.translate(word='good') is not None + assert pons.translate(word="good") is not None def test_inputs(): @@ -46,4 +46,3 @@ def test_payload(pons): with pytest.raises(exceptions.NotValidLength): pons.translate("a" * 51) - From 76688c08d4b5df883bf846b9257d3c37c7a4752f Mon Sep 17 00:00:00 2001 From: nidhal baccouri Date: Wed, 9 Mar 2022 15:12:38 +0100 Subject: [PATCH 2/5] removed unused constants --- deep_translator/constants.py | 284 ++++++++++++++++------------------- 1 file changed, 131 insertions(+), 153 deletions(-) diff --git a/deep_translator/constants.py b/deep_translator/constants.py index b42f9a4..d17541a 100644 --- a/deep_translator/constants.py +++ b/deep_translator/constants.py @@ -14,128 +14,118 @@ "LIBRE_FREE": "https://libretranslate.de/", } -GOOGLE_CODES_TO_LANGUAGES = { - "af": "afrikaans", - "sq": "albanian", - "am": "amharic", - "ar": "arabic", - "hy": "armenian", - "az": "azerbaijani", - "eu": "basque", - "be": "belarusian", - "bn": "bengali", - "bs": "bosnian", - "bg": "bulgarian", - "ca": "catalan", - "ceb": "cebuano", - "ny": "chichewa", - "zh-CN": "chinese (simplified)", - "zh-TW": "chinese (traditional)", - "co": "corsican", - "hr": "croatian", - "cs": "czech", - "da": "danish", - "nl": "dutch", - "en": "english", - "eo": "esperanto", - "et": "estonian", - "tl": "filipino", - "fi": "finnish", - "fr": "french", - "fy": "frisian", - "gl": "galician", - "ka": "georgian", - "de": "german", - "el": "greek", - "gu": "gujarati", - "ht": "haitian creole", - "ha": "hausa", - "haw": "hawaiian", - "iw": "hebrew", - "hi": "hindi", - "hmn": "hmong", - "hu": "hungarian", - "is": "icelandic", - "ig": "igbo", - "id": "indonesian", - "ga": "irish", - "it": "italian", - "ja": "japanese", - "jw": "javanese", - "kn": "kannada", - "kk": "kazakh", - "km": "khmer", - "rw": "kinyarwanda", - "ko": "korean", - "ku": "kurdish", - "ky": "kyrgyz", - "lo": "lao", - "la": "latin", - "lv": "latvian", - "lt": "lithuanian", - "lb": "luxembourgish", - "mk": "macedonian", - "mg": "malagasy", - "ms": "malay", - "ml": "malayalam", - "mt": "maltese", - "mi": "maori", - "mr": "marathi", - "mn": "mongolian", - "my": "myanmar", - "ne": "nepali", - "no": "norwegian", - "or": "odia", - "ps": "pashto", - "fa": "persian", - "pl": "polish", - "pt": "portuguese", - "pa": "punjabi", - "ro": "romanian", - "ru": "russian", - "sm": "samoan", - "gd": "scots gaelic", - "sr": "serbian", - "st": "sesotho", - "sn": "shona", - "sd": "sindhi", - "si": "sinhala", - "sk": "slovak", - "sl": "slovenian", - "so": "somali", - "es": "spanish", - "su": "sundanese", - "sw": "swahili", - "sv": "swedish", - "tg": "tajik", - "ta": "tamil", - "tt": "tatar", - "te": "telugu", - "th": "thai", - "tr": "turkish", - "tk": "turkmen", - "uk": "ukrainian", - "ur": "urdu", - "ug": "uyghur", - "uz": "uzbek", - "vi": "vietnamese", - "cy": "welsh", - "xh": "xhosa", - "yi": "yiddish", - "yo": "yoruba", - "zu": "zulu", -} - -GOOGLE_LANGUAGES_TO_CODES = {v: k for k, v in GOOGLE_CODES_TO_LANGUAGES.items()} - -# This dictionary maps the primary name of language to its secondary names in list manner (if any) -GOOGLE_LANGUAGES_SECONDARY_NAMES = { - "myanmar": ["burmese"], - "odia": ["oriya"], - "kurdish": ["kurmanji"], +GOOGLE_LANGUAGES_TO_CODES = { + "afrikaans": "af", + "albanian": "sq", + "amharic": "am", + "arabic": "ar", + "armenian": "hy", + "azerbaijani": "az", + "basque": "eu", + "belarusian": "be", + "bengali": "bn", + "bosnian": "bs", + "bulgarian": "bg", + "catalan": "ca", + "cebuano": "ceb", + "chichewa": "ny", + "chinese (simplified)": "zh-CN", + "chinese (traditional)": "zh-TW", + "corsican": "co", + "croatian": "hr", + "czech": "cs", + "danish": "da", + "dutch": "nl", + "english": "en", + "esperanto": "eo", + "estonian": "et", + "filipino": "tl", + "finnish": "fi", + "french": "fr", + "frisian": "fy", + "galician": "gl", + "georgian": "ka", + "german": "de", + "greek": "el", + "gujarati": "gu", + "haitian creole": "ht", + "hausa": "ha", + "hawaiian": "haw", + "hebrew": "iw", + "hindi": "hi", + "hmong": "hmn", + "hungarian": "hu", + "icelandic": "is", + "igbo": "ig", + "indonesian": "id", + "irish": "ga", + "italian": "it", + "japanese": "ja", + "javanese": "jw", + "kannada": "kn", + "kazakh": "kk", + "khmer": "km", + "kinyarwanda": "rw", + "korean": "ko", + "kurdish": "ku", + "kyrgyz": "ky", + "lao": "lo", + "latin": "la", + "latvian": "lv", + "lithuanian": "lt", + "luxembourgish": "lb", + "macedonian": "mk", + "malagasy": "mg", + "malay": "ms", + "malayalam": "ml", + "maltese": "mt", + "maori": "mi", + "marathi": "mr", + "mongolian": "mn", + "myanmar": "my", + "nepali": "ne", + "norwegian": "no", + "odia": "or", + "pashto": "ps", + "persian": "fa", + "polish": "pl", + "portuguese": "pt", + "punjabi": "pa", + "romanian": "ro", + "russian": "ru", + "samoan": "sm", + "scots gaelic": "gd", + "serbian": "sr", + "sesotho": "st", + "shona": "sn", + "sindhi": "sd", + "sinhala": "si", + "slovak": "sk", + "slovenian": "sl", + "somali": "so", + "spanish": "es", + "sundanese": "su", + "swahili": "sw", + "swedish": "sv", + "tajik": "tg", + "tamil": "ta", + "tatar": "tt", + "telugu": "te", + "thai": "th", + "turkish": "tr", + "turkmen": "tk", + "ukrainian": "uk", + "urdu": "ur", + "uyghur": "ug", + "uzbek": "uz", + "vietnamese": "vi", + "welsh": "cy", + "xhosa": "xh", + "yiddish": "yi", + "yoruba": "yo", + "zulu": "zu", } - PONS_CODES_TO_LANGUAGES = { "ar": "arabic", "bg": "bulgarian", @@ -161,8 +151,6 @@ "elv": "elvish", } -PONS_LANGUAGES_TO_CODES = {v: k for k, v in PONS_CODES_TO_LANGUAGES.items()} - LINGUEE_LANGUAGES_TO_CODES = { "maltese": "mt", "english": "en", @@ -193,8 +181,6 @@ "japanese": "ja", } -LINGUEE_CODE_TO_LANGUAGE = {v: k for k, v in LINGUEE_LANGUAGES_TO_CODES.items()} - DEEPL_LANGUAGE_TO_CODE = { "bulgarian": "bg", "czech": "cs", @@ -222,9 +208,7 @@ "chinese": "zh", } -DEEPL_CODE_TO_LANGUAGE = {v: k for k, v in DEEPL_LANGUAGE_TO_CODE.items()} - -PAPAGO_CODE_TO_LANGUAGE = { +PAPAGO_LANGUAGE_TO_CODE = { "ko": "Korean", "en": "English", "ja": "Japanese", @@ -237,30 +221,24 @@ "id": "Indonesia", } -PAPAGO_LANGUAGE_TO_CODE = {v: k for v, k in PAPAGO_CODE_TO_LANGUAGE.items()} - -QCRI_CODE_TO_LANGUAGE = {"ar": "Arabic", "en": "English", "es": "Spanish"} - -QCRI_LANGUAGE_TO_CODE = {v: k for k, v in QCRI_CODE_TO_LANGUAGE.items()} - -LIBRE_CODES_TO_LANGUAGES = { - "en": "English", - "ar": "Arabic", - "zh": "Chinese", - "fr": "French", - "de": "German", - "hi": "Hindi", - "id": "Indonesian", - "ga": "Irish", - "it": "Italian", - "ja": "Japanese", - "ko": "Korean", - "pl": "Polish", - "pt": "Portuguese", - "ru": "Russian", - "es": "Spanish", - "tr": "Turkish", - "vi": "Vietnamese", +QCRI_LANGUAGE_TO_CODE = {"Arabic": "ar", "English": "en", "Spanish": "es"} + +LIBRE_LANGUAGES_TO_CODES = { + "English": "en", + "Arabic": "ar", + "Chinese": "zh", + "French": "fr", + "German": "de", + "Hindi": "hi", + "Indonesian": "id", + "Irish": "ga", + "Italian": "it", + "Japanese": "ja", + "Korean": "ko", + "Polish": "pl", + "Portuguese": "pt", + "Russian": "ru", + "Spanish": "es", + "Turkish": "tr", + "Vietnamese": "vi", } - -LIBRE_LANGUAGES_TO_CODES = {v: k for k, v in LIBRE_CODES_TO_LANGUAGES.items()} From 7ade3be71f77342d9fada1e91db751e24c465d80 Mon Sep 17 00:00:00 2001 From: nidhal baccouri Date: Wed, 9 Mar 2022 17:48:24 +0100 Subject: [PATCH 3/5] added typing --- deep_translator/base.py | 35 +++++++++++++++++++---------------- deep_translator/cli.py | 11 ++++++----- deep_translator/deepl.py | 15 ++++++++++----- deep_translator/detection.py | 12 +++++++++--- deep_translator/google.py | 15 +++++++++++---- deep_translator/libre.py | 16 +++++++++++----- deep_translator/linguee.py | 11 ++++++++--- deep_translator/microsoft.py | 17 +++++++++-------- deep_translator/mymemory.py | 17 +++++++++++++---- deep_translator/papago.py | 15 ++++++++++----- deep_translator/pons.py | 11 ++++++++--- deep_translator/qcri.py | 19 ++++++++++++++----- deep_translator/validate.py | 4 ++-- deep_translator/yandex.py | 19 +++++++++++++------ 14 files changed, 143 insertions(+), 74 deletions(-) diff --git a/deep_translator/base.py b/deep_translator/base.py index 82f529f..f11c499 100644 --- a/deep_translator/base.py +++ b/deep_translator/base.py @@ -3,6 +3,7 @@ from deep_translator.constants import GOOGLE_LANGUAGES_TO_CODES from deep_translator.exceptions import InvalidSourceOrTargetLanguage from abc import ABC, abstractmethod +from typing import Optional, List, Union class BaseTranslator(ABC): @@ -12,13 +13,13 @@ class BaseTranslator(ABC): def __init__( self, - base_url=None, - source="auto", - target="en", - payload_key=None, - element_tag=None, - element_query=None, - languages=None, + base_url: str, + languages: dict = GOOGLE_LANGUAGES_TO_CODES, + source: str = "auto", + target: str = "en", + payload_key: Optional[str] = None, + element_tag: Optional[str] = None, + element_query: Optional[dict] = None, **url_params ): """ @@ -26,8 +27,8 @@ def __init__( @param target: target language to translate to """ self._base_url = base_url - self.languages: dict = GOOGLE_LANGUAGES_TO_CODES if not languages else languages - self.supported_languages: list = list(self.languages.keys()) + self.languages = languages + self.supported_languages = list(self.languages.keys()) if not source: raise InvalidSourceOrTargetLanguage(source) if not target: @@ -55,18 +56,20 @@ def _map_language_to_code(self, *languages): elif language in self.languages.keys(): yield self.languages[language] - def _same_source_target(self): + def _same_source_target(self) -> bool: return self._source == self._target - def get_supported_languages(self, as_dict=False, **kwargs): + def get_supported_languages( + self, as_dict: bool = False, **kwargs + ) -> Union[list, dict]: """ - return the supported languages by the google translator + return the supported languages by the Google translator @param as_dict: if True, the languages will be returned as a dictionary mapping languages to their abbreviations @return: list or dict """ return self.supported_languages if not as_dict else self.languages - def is_language_supported(self, language, **kwargs): + def is_language_supported(self, language: str, **kwargs) -> bool: """ check if the language is supported by the translator @param language: a string for 1 language @@ -82,7 +85,7 @@ def is_language_supported(self, language, **kwargs): return False @abstractmethod - def translate(self, text, **kwargs): + def translate(self, text: str, **kwargs) -> str: """ translate a text using a translator under the hood and return the translated text @param text: text to translate @@ -91,7 +94,7 @@ def translate(self, text, **kwargs): """ return NotImplemented("You need to implement the translate method!") - def _translate_file(self, path, **kwargs): + def _translate_file(self, path: str, **kwargs) -> str: """ translate directly from file @param path: path to the target file @@ -106,7 +109,7 @@ def _translate_file(self, path, **kwargs): except Exception as e: raise e - def _translate_batch(self, batch=None, **kwargs): + def _translate_batch(self, batch: List[str], **kwargs) -> List[str]: """ translate a list of texts @param batch: list of texts you want to translate diff --git a/deep_translator/cli.py b/deep_translator/cli.py index 96be8cd..c7130cc 100644 --- a/deep_translator/cli.py +++ b/deep_translator/cli.py @@ -1,13 +1,14 @@ """Console script for deep_translator.""" import argparse from deep_translator.engines import __engines__ +from typing import Optional class CLI(object): translators_dict = __engines__ translator = None - def __init__(self, custom_args=None): + def __init__(self, custom_args: Optional[list] = None): self.custom_args = custom_args self.args = self.parse_args() translator_class = self.translators_dict.get(self.args.translator, None) @@ -20,7 +21,7 @@ def __init__(self, custom_args=None): source=self.args.source, target=self.args.target ) - def translate(self): + def translate(self) -> None: """ function used to provide translations from the parsed terminal arguments @return: None @@ -30,7 +31,7 @@ def translate(self): print("-" * 50) print(f"Translation result: {res}") - def get_supported_languages(self): + def get_supported_languages(self) -> None: """ function used to return the languages supported by the translator service from the parsed terminal arguments @return: None @@ -42,7 +43,7 @@ def get_supported_languages(self): print(f"Languages supported by '{self.args.translator}' are :\n") print(translator_supported_languages) - def parse_args(self): + def parse_args(self) -> argparse.Namespace: """ function responsible for parsing terminal arguments and provide them for further use in the translation process """ @@ -86,7 +87,7 @@ def parse_args(self): ) return parsed_args - def run(self): + def run(self) -> None: if self.args.languages: self.get_supported_languages() else: diff --git a/deep_translator/deepl.py b/deep_translator/deepl.py index 01933c8..d976ad0 100644 --- a/deep_translator/deepl.py +++ b/deep_translator/deepl.py @@ -1,5 +1,5 @@ import requests - +from typing import Optional, List from deep_translator.validate import is_empty, validate_input from deep_translator.constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE from deep_translator.exceptions import ( @@ -16,7 +16,12 @@ class that wraps functions, which use the DeeplTranslator translator under the h """ def __init__( - self, api_key=None, source="de", target="en", use_free_api=True, **kwargs + self, + api_key: Optional[str] = None, + source: str = "de", + target: str = "en", + use_free_api: bool = True, + **kwargs ): """ @param api_key: your DeeplTranslator api key. @@ -41,7 +46,7 @@ def __init__( **kwargs ) - def translate(self, text, **kwargs): + def translate(self, text: str, **kwargs) -> str: """ @param text: text to translate @return: translated text @@ -77,10 +82,10 @@ def translate(self, text, **kwargs): # Process and return the response. return res["translations"][0]["text"] - def translate_file(self, path, **kwargs): + def translate_file(self, path: str, **kwargs) -> str: return self._translate_file(path, **kwargs) - def translate_batch(self, batch, **kwargs): + def translate_batch(self, batch: List[str], **kwargs) -> List[str]: """ @param batch: list of texts to translate @return: list of translations diff --git a/deep_translator/detection.py b/deep_translator/detection.py index 3c7e395..438afed 100644 --- a/deep_translator/detection.py +++ b/deep_translator/detection.py @@ -3,6 +3,8 @@ """ import requests from requests.exceptions import HTTPError +from typing import Optional, List, Union + # Module global config config = { @@ -14,7 +16,7 @@ } -def get_request_body(text, api_key, *args, **kwargs): +def get_request_body(text: Union[str, List[str]], api_key: str, *args, **kwargs): """ send a request and return the response body parsed as dictionary @@ -46,7 +48,9 @@ def get_request_body(text, api_key, *args, **kwargs): raise e -def single_detection(text, api_key=None, detailed=False, *args, **kwargs): +def single_detection( + text: str, api_key: Optional[str] = None, detailed: bool = False, *args, **kwargs +): """ function responsible for detecting the language from a text @@ -66,7 +70,9 @@ def single_detection(text, api_key=None, detailed=False, *args, **kwargs): return lang -def batch_detection(text_list, api_key, detailed=False, *args, **kwargs): +def batch_detection( + text_list: List[str], api_key: str, detailed: bool = False, *args, **kwargs +): """ function responsible for detecting the language from a text diff --git a/deep_translator/google.py b/deep_translator/google.py index 65ce927..5e9bcf0 100644 --- a/deep_translator/google.py +++ b/deep_translator/google.py @@ -12,6 +12,7 @@ from deep_translator.validate import validate_input, is_empty from bs4 import BeautifulSoup import requests +from typing import Optional, List class GoogleTranslator(BaseTranslator): @@ -19,7 +20,13 @@ class GoogleTranslator(BaseTranslator): class that wraps functions, which use google translate under the hood to translate text(s) """ - def __init__(self, source="auto", target="en", proxies=None, **kwargs): + def __init__( + self, + source: str = "auto", + target: str = "en", + proxies: Optional[dict] = None, + **kwargs + ): """ @param source: source language to translate from @param target: target language to translate to @@ -37,7 +44,7 @@ def __init__(self, source="auto", target="en", proxies=None, **kwargs): self._alt_element_query = {"class": "result-container"} - def translate(self, text, **kwargs): + def translate(self, text: str, **kwargs) -> str: """ function that uses google translate to translate a text @param text: desired text to translate @@ -89,7 +96,7 @@ def translate(self, text, **kwargs): else: return element.get_text(strip=True) - def translate_file(self, path, **kwargs): + def translate_file(self, path: str, **kwargs) -> str: """ translate directly from file @param path: path to the target file @@ -99,7 +106,7 @@ def translate_file(self, path, **kwargs): """ return self._translate_file(path, **kwargs) - def translate_batch(self, batch=None, **kwargs): + def translate_batch(self, batch: List[str], **kwargs) -> List[str]: """ translate a list of texts @param batch: list of texts you want to translate diff --git a/deep_translator/libre.py b/deep_translator/libre.py index 8c5e581..4f9b548 100644 --- a/deep_translator/libre.py +++ b/deep_translator/libre.py @@ -3,7 +3,7 @@ """ import requests - +from typing import Optional, List from deep_translator.validate import is_empty, validate_input from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS, LIBRE_LANGUAGES_TO_CODES @@ -19,7 +19,13 @@ class LibreTranslator(BaseTranslator): class that wraps functions, which use libre translator under the hood to translate text(s) """ - def __init__(self, source="auto", target="en", api_key=None, **kwargs): + def __init__( + self, + api_key: Optional[str] = None, + source: str = "auto", + target: str = "en", + **kwargs + ): """ @param source: source language to translate from List of LibreTranslate nedpoints can be found at : https://github.com/LibreTranslate/LibreTranslate#mirrors @@ -36,7 +42,7 @@ def __init__(self, source="auto", target="en", api_key=None, **kwargs): languages=LIBRE_LANGUAGES_TO_CODES, ) - def translate(self, text, **kwargs): + def translate(self, text: str, **kwargs) -> str: """ function that uses microsoft translate to translate a text @param text: desired text to translate @@ -76,7 +82,7 @@ def translate(self, text, **kwargs): # Process and return the response. return res["translatedText"] - def translate_file(self, path, **kwargs): + def translate_file(self, path: str, **kwargs) -> str: """ translate directly from file @param path: path to the target file @@ -86,7 +92,7 @@ def translate_file(self, path, **kwargs): """ return self._translate_file(path, **kwargs) - def translate_batch(self, batch=None, **kwargs): + def translate_batch(self, batch: List[str], **kwargs) -> List[str]: """ translate a list of texts @param batch: list of texts you want to translate diff --git a/deep_translator/linguee.py b/deep_translator/linguee.py index 596df61..b566073 100644 --- a/deep_translator/linguee.py +++ b/deep_translator/linguee.py @@ -14,6 +14,7 @@ from bs4 import BeautifulSoup import requests from requests.utils import requote_uri +from typing import Optional, List, Union class LingueeTranslator(BaseTranslator): @@ -21,7 +22,9 @@ class LingueeTranslator(BaseTranslator): class that wraps functions, which use the linguee translator under the hood to translate word(s) """ - def __init__(self, source, target="en", proxies=None, **kwargs): + def __init__( + self, source: str, target: str = "en", proxies: Optional[dict] = None, **kwargs + ): """ @param source: source language to translate from @param target: target language to translate to @@ -37,7 +40,9 @@ def __init__(self, source, target="en", proxies=None, **kwargs): payload_key=None, # key of text in the url ) - def translate(self, word, return_all=False, **kwargs): + def translate( + self, word: str, return_all: bool = False, **kwargs + ) -> Union[str, List[str]]: """ function that uses linguee to translate a word @param word: word to translate @@ -82,7 +87,7 @@ def translate(self, word, return_all=False, **kwargs): return filtered_elements if return_all else filtered_elements[0] - def translate_words(self, words, **kwargs): + def translate_words(self, words: List[str], **kwargs) -> List[str]: """ translate a batch of words together by providing them in a list @param words: list of words you want to translate diff --git a/deep_translator/microsoft.py b/deep_translator/microsoft.py index 95e6167..bf87fc8 100644 --- a/deep_translator/microsoft.py +++ b/deep_translator/microsoft.py @@ -7,6 +7,7 @@ from deep_translator.exceptions import ServerException, MicrosoftAPIerror from deep_translator.base import BaseTranslator from deep_translator.validate import validate_input +from typing import Optional, List class MicrosoftTranslator(BaseTranslator): @@ -16,11 +17,11 @@ class MicrosoftTranslator(BaseTranslator): def __init__( self, - api_key=None, - region=None, - source=None, - target=None, - proxies=None, + api_key: Optional[str] = None, + region: Optional[str] = None, + source: str = "auto", + target: str = "en", + proxies: Optional[dict] = None, **kwargs, ): """ @@ -60,7 +61,7 @@ def _get_supported_languages(self): return {translation_dict[k]["name"].lower(): k for k in translation_dict.keys()} - def translate(self, text, **kwargs): + def translate(self, text: str, **kwargs) -> str: """ function that uses microsoft translate to translate a text @param text: desired text to translate @@ -97,7 +98,7 @@ def translate(self, text, **kwargs): ] return "\n".join(all_translations) - def translate_file(self, path, **kwargs): + def translate_file(self, path: str, **kwargs) -> str: """ translate from a file @param path: path to file @@ -105,7 +106,7 @@ def translate_file(self, path, **kwargs): """ return self._translate_file(path, **kwargs) - def translate_batch(self, batch, **kwargs): + def translate_batch(self, batch: List[str], **kwargs) -> List[str]: """ translate a batch of texts @param batch: list of texts to translate diff --git a/deep_translator/mymemory.py b/deep_translator/mymemory.py index 5275999..6839e18 100644 --- a/deep_translator/mymemory.py +++ b/deep_translator/mymemory.py @@ -10,6 +10,7 @@ ) from deep_translator.base import BaseTranslator import requests +from typing import Optional, List, Union class MyMemoryTranslator(BaseTranslator): @@ -17,7 +18,13 @@ class MyMemoryTranslator(BaseTranslator): class that uses the mymemory translator to translate texts """ - def __init__(self, source="auto", target="en", proxies=None, **kwargs): + def __init__( + self, + source: str = "auto", + target: str = "en", + proxies: Optional[dict] = None, + **kwargs, + ): """ @param source: source language to translate from @param target: target language to translate to @@ -31,7 +38,9 @@ def __init__(self, source="auto", target="en", proxies=None, **kwargs): payload_key="q", ) - def translate(self, text, return_all=False, **kwargs): + def translate( + self, text: str, return_all: bool = False, **kwargs + ) -> Union[str, List[str]]: """ function that uses the mymemory translator to translate a text @param text: desired text to translate @@ -73,7 +82,7 @@ def translate(self, text, return_all=False, **kwargs): next_match = next(matches) return next_match if not return_all else list(all_matches) - def translate_file(self, path, **kwargs): + def translate_file(self, path: str, **kwargs) -> str: """ translate directly from file @param path: path to the target file @@ -83,7 +92,7 @@ def translate_file(self, path, **kwargs): """ return self._translate_file(path, **kwargs) - def translate_batch(self, batch=None, **kwargs): + def translate_batch(self, batch: List[str], **kwargs) -> List[str]: """ translate a list of texts @param batch: list of texts you want to translate diff --git a/deep_translator/papago.py b/deep_translator/papago.py index 70322b4..b093ce8 100644 --- a/deep_translator/papago.py +++ b/deep_translator/papago.py @@ -6,7 +6,7 @@ from deep_translator.exceptions import TranslationNotFound from deep_translator.base import BaseTranslator import requests - +from typing import Optional, List from deep_translator.validate import validate_input @@ -16,7 +16,12 @@ class that wraps functions, which use google translate under the hood to transla """ def __init__( - self, client_id=None, secret_key=None, source="auto", target="en", **kwargs + self, + client_id: Optional[str] = None, + secret_key: Optional[str] = None, + source: str = "auto", + target: str = "en", + **kwargs, ): """ @param source: source language to translate from @@ -37,7 +42,7 @@ def __init__( **kwargs, ) - def translate(self, text, **kwargs): + def translate(self, text: str, **kwargs) -> str: """ function that uses google translate to translate a text @param text: desired text to translate @@ -66,7 +71,7 @@ def translate(self, text, **kwargs): translated_text = result.get("translatedText") return translated_text - def translate_file(self, path, **kwargs): + def translate_file(self, path: str, **kwargs) -> str: """ translate directly from file @param path: path to the target file @@ -76,7 +81,7 @@ def translate_file(self, path, **kwargs): """ return self._translate_file(path, **kwargs) - def translate_batch(self, batch=None, **kwargs): + def translate_batch(self, batch: List[str], **kwargs) -> List[str]: """ translate a list of texts @param batch: list of texts you want to translate diff --git a/deep_translator/pons.py b/deep_translator/pons.py index e517177..9b74a24 100644 --- a/deep_translator/pons.py +++ b/deep_translator/pons.py @@ -15,6 +15,7 @@ ) from deep_translator.base import BaseTranslator from requests.utils import requote_uri +from typing import Optional, Union, List class PonsTranslator(BaseTranslator): @@ -22,7 +23,9 @@ class PonsTranslator(BaseTranslator): class that uses PONS translator to translate words """ - def __init__(self, source, target="en", proxies=None, **kwargs): + def __init__( + self, source: str, target: str = "en", proxies: Optional[dict] = None, **kwargs + ): """ @param source: source language to translate from @param target: target language to translate to @@ -39,7 +42,9 @@ def __init__(self, source, target="en", proxies=None, **kwargs): **kwargs, ) - def translate(self, word, return_all=False, **kwargs): + def translate( + self, word: str, return_all: bool = False, **kwargs + ) -> Union[str, List[str]]: """ function that uses PONS to translate a word @param word: word to translate @@ -84,7 +89,7 @@ def translate(self, word, return_all=False, **kwargs): return word_list if return_all else word_list[0] - def translate_words(self, words, **kwargs): + def translate_words(self, words: List[str], **kwargs) -> List[str]: """ translate a batch of words together by providing them in a list @param words: list of words you want to translate diff --git a/deep_translator/qcri.py b/deep_translator/qcri.py index 9b8a2bb..d67ddc1 100644 --- a/deep_translator/qcri.py +++ b/deep_translator/qcri.py @@ -2,6 +2,7 @@ from deep_translator.constants import BASE_URLS, QCRI_LANGUAGE_TO_CODE from deep_translator.exceptions import ServerException, TranslationNotFound from deep_translator.base import BaseTranslator +from typing import Optional, List class QcriTranslator(BaseTranslator): @@ -9,7 +10,13 @@ class QcriTranslator(BaseTranslator): class that wraps functions, which use the QRCI translator under the hood to translate word(s) """ - def __init__(self, api_key=None, source="en", target="en", **kwargs): + def __init__( + self, + api_key: Optional[str] = None, + source: str = "en", + target: str = "en", + **kwargs, + ): """ @param api_key: your qrci api key. Get one for free here https://mt.qcri.org/api/v1/ref """ @@ -32,7 +39,9 @@ def __init__(self, api_key=None, source="en", target="en", **kwargs): **kwargs, ) - def _get(self, endpoint, params=None, return_text=True): + def _get( + self, endpoint: str, params: Optional[dict] = None, return_text: bool = True + ): if not params: params = self.params try: @@ -56,7 +65,7 @@ def get_domains(self): def domains(self): return self.get_domains() - def translate(self, text, **kwargs): + def translate(self, text: str, **kwargs) -> str: params = { "key": self.api_key, "langpair": f"{self._source}-{self._target}", @@ -78,10 +87,10 @@ def translate(self, text, **kwargs): raise TranslationNotFound(text) return translation - def translate_file(self, path, **kwargs): + def translate_file(self, path: str, **kwargs) -> str: return self._translate_file(path, **kwargs) - def translate_batch(self, batch, **kwargs): + def translate_batch(self, batch: List[str], **kwargs) -> List[str]: """ translate a batch of texts @domain: domain diff --git a/deep_translator/validate.py b/deep_translator/validate.py index 92f19a1..d203eb8 100644 --- a/deep_translator/validate.py +++ b/deep_translator/validate.py @@ -1,11 +1,11 @@ from deep_translator.exceptions import NotValidPayload, NotValidLength -def is_empty(text: str): +def is_empty(text: str) -> bool: return text == "" -def validate_input(text: str, min_chars: int = 0, max_chars: int = 5000): +def validate_input(text: str, min_chars: int = 0, max_chars: int = 5000) -> bool: """ validate the target text to translate @param min_chars: min characters diff --git a/deep_translator/yandex.py b/deep_translator/yandex.py index ef1c003..3c4bcc3 100644 --- a/deep_translator/yandex.py +++ b/deep_translator/yandex.py @@ -11,6 +11,7 @@ ) from deep_translator.base import BaseTranslator from deep_translator.validate import validate_input +from typing import Optional, List class YandexTranslator(BaseTranslator): @@ -18,7 +19,13 @@ class YandexTranslator(BaseTranslator): class that wraps functions, which use the yandex translator under the hood to translate word(s) """ - def __init__(self, api_key=None, source="en", target="de", **kwargs): + def __init__( + self, + api_key: Optional[str] = None, + source: str = "en", + target: str = "de", + **kwargs + ): """ @param api_key: your yandex api key """ @@ -43,7 +50,7 @@ def languages(self): return self.get_supported_languages() @property - def dirs(self, proxies=None): + def dirs(self, proxies: Optional[dict] = None): try: url = self._base_url.format(version=self.api_version, endpoint="getLangs") @@ -58,7 +65,7 @@ def dirs(self, proxies=None): raise ServerException(response.status_code) return data.get("dirs") - def detect(self, text, proxies=None): + def detect(self, text: str, proxies: Optional[dict] = None): response = None params = { "text": text, @@ -85,7 +92,7 @@ def detect(self, text, proxies=None): raise ServerException(501) return language - def translate(self, text, proxies=None, **kwargs): + def translate(self, text: str, proxies: Optional[dict] = None, **kwargs) -> str: if validate_input(text): params = { "text": text, @@ -116,7 +123,7 @@ def translate(self, text, proxies=None, **kwargs): return response["text"] - def translate_file(self, path, **kwargs): + def translate_file(self, path: str, **kwargs) -> str: """ translate from a file @param path: path to file @@ -124,7 +131,7 @@ def translate_file(self, path, **kwargs): """ return self._translate_file(path, **kwargs) - def translate_batch(self, batch, **kwargs): + def translate_batch(self, batch: List[str], **kwargs) -> List[str]: """ translate a batch of texts @param batch: list of texts to translate From 76aa3b2a8085fd4f77ac9cf1edee0b4e651cac3c Mon Sep 17 00:00:00 2001 From: nidhal baccouri Date: Wed, 9 Mar 2022 18:46:09 +0100 Subject: [PATCH 4/5] renamed input validation func --- deep_translator/deepl.py | 4 ++-- deep_translator/google.py | 8 ++++---- deep_translator/libre.py | 4 ++-- deep_translator/linguee.py | 4 ++-- deep_translator/microsoft.py | 4 ++-- deep_translator/mymemory.py | 4 ++-- deep_translator/papago.py | 4 ++-- deep_translator/pons.py | 4 ++-- deep_translator/validate.py | 2 +- deep_translator/yandex.py | 4 ++-- tests/test_deepl.py | 2 +- tests/test_google.py | 4 ++-- tests/test_libre.py | 8 ++++---- 13 files changed, 28 insertions(+), 28 deletions(-) diff --git a/deep_translator/deepl.py b/deep_translator/deepl.py index d976ad0..78040c6 100644 --- a/deep_translator/deepl.py +++ b/deep_translator/deepl.py @@ -1,6 +1,6 @@ import requests from typing import Optional, List -from deep_translator.validate import is_empty, validate_input +from deep_translator.validate import is_empty, is_input_valid from deep_translator.constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE from deep_translator.exceptions import ( ServerException, @@ -51,7 +51,7 @@ def translate(self, text: str, **kwargs) -> str: @param text: text to translate @return: translated text """ - if validate_input(text): + if is_input_valid(text): if self._same_source_target() or is_empty(text): return text diff --git a/deep_translator/google.py b/deep_translator/google.py index 5e9bcf0..78f8d0c 100644 --- a/deep_translator/google.py +++ b/deep_translator/google.py @@ -9,7 +9,7 @@ RequestError, ) from deep_translator.base import BaseTranslator -from deep_translator.validate import validate_input, is_empty +from deep_translator.validate import is_input_valid, is_empty from bs4 import BeautifulSoup import requests from typing import Optional, List @@ -17,7 +17,7 @@ class GoogleTranslator(BaseTranslator): """ - class that wraps functions, which use google translate under the hood to translate text(s) + class that wraps functions, which use Google Translate under the hood to translate text(s) """ def __init__( @@ -46,11 +46,11 @@ def __init__( def translate(self, text: str, **kwargs) -> str: """ - function that uses google translate to translate a text + function to translate a text @param text: desired text to translate @return: str: translated text """ - if validate_input(text): + if is_input_valid(text): text = text.strip() if self._same_source_target() or is_empty(text): return text diff --git a/deep_translator/libre.py b/deep_translator/libre.py index 4f9b548..03bdf80 100644 --- a/deep_translator/libre.py +++ b/deep_translator/libre.py @@ -4,7 +4,7 @@ import requests from typing import Optional, List -from deep_translator.validate import is_empty, validate_input +from deep_translator.validate import is_empty, is_input_valid from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS, LIBRE_LANGUAGES_TO_CODES from deep_translator.exceptions import ( @@ -48,7 +48,7 @@ def translate(self, text: str, **kwargs) -> str: @param text: desired text to translate @return: str: translated text """ - if validate_input(text): + if is_input_valid(text): if self._same_source_target() or is_empty(text): return text diff --git a/deep_translator/linguee.py b/deep_translator/linguee.py index b566073..9c02cda 100644 --- a/deep_translator/linguee.py +++ b/deep_translator/linguee.py @@ -1,7 +1,7 @@ """ linguee translator API """ -from deep_translator.validate import validate_input, is_empty +from deep_translator.validate import is_input_valid, is_empty from deep_translator.constants import BASE_URLS, LINGUEE_LANGUAGES_TO_CODES from deep_translator.exceptions import ( TranslationNotFound, @@ -54,7 +54,7 @@ def translate( if self._same_source_target() or is_empty(word): return word - if validate_input(word, max_chars=50): + if is_input_valid(word, max_chars=50): # %s-%s/translation/%s.html url = ( f"{self._base_url}{self._source}-{self._target}/translation/{word}.html" diff --git a/deep_translator/microsoft.py b/deep_translator/microsoft.py index bf87fc8..2f37908 100644 --- a/deep_translator/microsoft.py +++ b/deep_translator/microsoft.py @@ -6,7 +6,7 @@ from deep_translator.constants import BASE_URLS from deep_translator.exceptions import ServerException, MicrosoftAPIerror from deep_translator.base import BaseTranslator -from deep_translator.validate import validate_input +from deep_translator.validate import is_input_valid from typing import Optional, List @@ -70,7 +70,7 @@ def translate(self, text: str, **kwargs) -> str: # a body must be a list of dicts to process multiple texts; # I have not added multiple text processing here since it is covered by the translate_batch method - if validate_input(text): + if is_input_valid(text): self._url_params["from"] = self._source self._url_params["to"] = self._target diff --git a/deep_translator/mymemory.py b/deep_translator/mymemory.py index 6839e18..de5efa3 100644 --- a/deep_translator/mymemory.py +++ b/deep_translator/mymemory.py @@ -1,7 +1,7 @@ """ mymemory translator API """ -from deep_translator.validate import is_empty, validate_input +from deep_translator.validate import is_empty, is_input_valid from deep_translator.constants import BASE_URLS from deep_translator.exceptions import ( TranslationNotFound, @@ -48,7 +48,7 @@ def translate( @param return_all: set to True to return all synonym/similars of the translated text @return: str or list """ - if validate_input(text, max_chars=500): + if is_input_valid(text, max_chars=500): text = text.strip() if self._same_source_target() or is_empty(text): return text diff --git a/deep_translator/papago.py b/deep_translator/papago.py index b093ce8..0c5f323 100644 --- a/deep_translator/papago.py +++ b/deep_translator/papago.py @@ -7,7 +7,7 @@ from deep_translator.base import BaseTranslator import requests from typing import Optional, List -from deep_translator.validate import validate_input +from deep_translator.validate import is_input_valid class PapagoTranslator(BaseTranslator): @@ -48,7 +48,7 @@ def translate(self, text: str, **kwargs) -> str: @param text: desired text to translate @return: str: translated text """ - if validate_input(text): + if is_input_valid(text): payload = {"source": self._source, "target": self._target, "text": text} headers = { "X-Naver-Client-Id": self.client_id, diff --git a/deep_translator/pons.py b/deep_translator/pons.py index 9b74a24..c1c5161 100644 --- a/deep_translator/pons.py +++ b/deep_translator/pons.py @@ -4,7 +4,7 @@ from bs4 import BeautifulSoup import requests -from deep_translator.validate import validate_input, is_empty +from deep_translator.validate import is_input_valid, is_empty from deep_translator.constants import BASE_URLS, PONS_CODES_TO_LANGUAGES from deep_translator.exceptions import ( TranslationNotFound, @@ -53,7 +53,7 @@ def translate( @type return_all: bool @return: str: translated word """ - if validate_input(word, max_chars=50): + if is_input_valid(word, max_chars=50): if self._same_source_target() or is_empty(word): return word url = f"{self._base_url}{self._source}-{self._target}/{word}" diff --git a/deep_translator/validate.py b/deep_translator/validate.py index d203eb8..1512e19 100644 --- a/deep_translator/validate.py +++ b/deep_translator/validate.py @@ -5,7 +5,7 @@ def is_empty(text: str) -> bool: return text == "" -def validate_input(text: str, min_chars: int = 0, max_chars: int = 5000) -> bool: +def is_input_valid(text: str, min_chars: int = 0, max_chars: int = 5000) -> bool: """ validate the target text to translate @param min_chars: min characters diff --git a/deep_translator/yandex.py b/deep_translator/yandex.py index 3c4bcc3..2ed2c70 100644 --- a/deep_translator/yandex.py +++ b/deep_translator/yandex.py @@ -10,7 +10,7 @@ TooManyRequests, ) from deep_translator.base import BaseTranslator -from deep_translator.validate import validate_input +from deep_translator.validate import is_input_valid from typing import Optional, List @@ -93,7 +93,7 @@ def detect(self, text: str, proxies: Optional[dict] = None): return language def translate(self, text: str, proxies: Optional[dict] = None, **kwargs) -> str: - if validate_input(text): + if is_input_valid(text): params = { "text": text, "format": "plain", diff --git a/tests/test_deepl.py b/tests/test_deepl.py index 9c9473c..6c898a6 100644 --- a/tests/test_deepl.py +++ b/tests/test_deepl.py @@ -1,5 +1,5 @@ import pytest -from unittest.mock import Mock, PropertyMock, patch +from unittest.mock import Mock, patch from deep_translator.deepl import DeeplTranslator from deep_translator.exceptions import AuthorizationException diff --git a/tests/test_google.py b/tests/test_google.py index de60042..65b252c 100644 --- a/tests/test_google.py +++ b/tests/test_google.py @@ -4,7 +4,7 @@ import pytest from deep_translator import exceptions, GoogleTranslator -from deep_translator.constants import GOOGLE_CODES_TO_LANGUAGES +from deep_translator.constants import GOOGLE_LANGUAGES_TO_CODES @pytest.fixture @@ -21,7 +21,7 @@ def test_content(google_translator): def test_abbreviations_and_languages_mapping(): - for abb, lang in GOOGLE_CODES_TO_LANGUAGES.items(): + for abb, lang in GOOGLE_LANGUAGES_TO_CODES.items(): g1 = GoogleTranslator(abb) g2 = GoogleTranslator(lang) assert g1._source == g2._source diff --git a/tests/test_libre.py b/tests/test_libre.py index b078c1e..9166ea6 100644 --- a/tests/test_libre.py +++ b/tests/test_libre.py @@ -4,7 +4,7 @@ import pytest from deep_translator import exceptions, LibreTranslator -from deep_translator.constants import LIBRE_CODES_TO_LANGUAGES +from deep_translator.constants import LIBRE_LANGUAGES_TO_CODES @pytest.fixture @@ -24,9 +24,9 @@ def test_inputs(): def test_abbreviations_and_languages_mapping(): - for abb, lang in LIBRE_CODES_TO_LANGUAGES.items(): - l1 = LibreTranslator(abb, api_key="some_key") - l2 = LibreTranslator(lang, api_key="some_key") + for abb, lang in LIBRE_LANGUAGES_TO_CODES.items(): + l1 = LibreTranslator(source=abb, api_key="some_key") + l2 = LibreTranslator(source=lang, api_key="some_key") assert l1._source == l2._source From 7a05cd719d323de33c7209e89728b743b2470674 Mon Sep 17 00:00:00 2001 From: nidhal baccouri Date: Wed, 9 Mar 2022 18:52:05 +0100 Subject: [PATCH 5/5] sorted imports --- Makefile | 6 ++---- deep_translator/__init__.py | 14 +++++++------- deep_translator/base.py | 5 +++-- deep_translator/cli.py | 3 ++- deep_translator/deepl.py | 10 ++++++---- deep_translator/detection.py | 4 ++-- deep_translator/google.py | 14 ++++++++------ deep_translator/libre.py | 8 +++++--- deep_translator/linguee.py | 18 ++++++++++-------- deep_translator/microsoft.py | 10 ++++++---- deep_translator/mymemory.py | 12 +++++++----- deep_translator/papago.py | 8 +++++--- deep_translator/pons.py | 15 ++++++++------- deep_translator/qcri.py | 6 ++++-- deep_translator/validate.py | 2 +- deep_translator/yandex.py | 8 +++++--- docs/conf.py | 2 ++ examples/linguee.py | 1 - examples/mymemory.py | 1 - examples/pons.py | 1 - examples/trans.py | 3 +-- poetry.lock | 20 +++++++++++++++++++- pyproject.toml | 1 + tests/test_cli.py | 6 ++++-- tests/test_deepl.py | 4 +++- tests/test_google.py | 3 ++- tests/test_libre.py | 3 ++- tests/test_linguee.py | 3 ++- tests/test_microsoft_trans.py | 5 +++-- tests/test_mymemory.py | 3 ++- tests/test_pons.py | 3 ++- 31 files changed, 124 insertions(+), 78 deletions(-) diff --git a/Makefile b/Makefile index 1d3d3ed..c571045 100644 --- a/Makefile +++ b/Makefile @@ -47,15 +47,13 @@ clean-test: ## remove test and coverage artifacts rm -fr htmlcov/ rm -fr .pytest_cache -lint: ## check style with flake8 +format: ## format with black + poetry run isort . poetry run black deep_translator tests test: ## run tests quickly with the default Python pytest -test-all: ## run tests on every Python version with tox - tox - coverage: ## check code coverage quickly with the default Python coverage run --source deep_translator -m pytest coverage report -m diff --git a/deep_translator/__init__.py b/deep_translator/__init__.py index e3133c0..61cae66 100644 --- a/deep_translator/__init__.py +++ b/deep_translator/__init__.py @@ -1,16 +1,16 @@ """Top-level package for Deep Translator""" +from deep_translator.deepl import DeeplTranslator +from deep_translator.detection import batch_detection, single_detection from deep_translator.google import GoogleTranslator -from deep_translator.pons import PonsTranslator +from deep_translator.libre import LibreTranslator from deep_translator.linguee import LingueeTranslator -from deep_translator.mymemory import MyMemoryTranslator -from deep_translator.yandex import YandexTranslator -from deep_translator.qcri import QcriTranslator -from deep_translator.deepl import DeeplTranslator -from deep_translator.detection import single_detection, batch_detection from deep_translator.microsoft import MicrosoftTranslator +from deep_translator.mymemory import MyMemoryTranslator from deep_translator.papago import PapagoTranslator -from deep_translator.libre import LibreTranslator +from deep_translator.pons import PonsTranslator +from deep_translator.qcri import QcriTranslator +from deep_translator.yandex import YandexTranslator __author__ = """Nidhal Baccouri""" __email__ = "nidhalbacc@gmail.com" diff --git a/deep_translator/base.py b/deep_translator/base.py index f11c499..68b6869 100644 --- a/deep_translator/base.py +++ b/deep_translator/base.py @@ -1,9 +1,10 @@ """base translator class""" +from abc import ABC, abstractmethod +from typing import List, Optional, Union + from deep_translator.constants import GOOGLE_LANGUAGES_TO_CODES from deep_translator.exceptions import InvalidSourceOrTargetLanguage -from abc import ABC, abstractmethod -from typing import Optional, List, Union class BaseTranslator(ABC): diff --git a/deep_translator/cli.py b/deep_translator/cli.py index c7130cc..f3e0db9 100644 --- a/deep_translator/cli.py +++ b/deep_translator/cli.py @@ -1,8 +1,9 @@ """Console script for deep_translator.""" import argparse -from deep_translator.engines import __engines__ from typing import Optional +from deep_translator.engines import __engines__ + class CLI(object): translators_dict = __engines__ diff --git a/deep_translator/deepl.py b/deep_translator/deepl.py index 78040c6..0ab7d9c 100644 --- a/deep_translator/deepl.py +++ b/deep_translator/deepl.py @@ -1,13 +1,15 @@ +from typing import List, Optional + import requests -from typing import Optional, List -from deep_translator.validate import is_empty, is_input_valid + +from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE from deep_translator.exceptions import ( + AuthorizationException, ServerException, TranslationNotFound, - AuthorizationException, ) -from deep_translator.base import BaseTranslator +from deep_translator.validate import is_empty, is_input_valid class DeeplTranslator(BaseTranslator): diff --git a/deep_translator/detection.py b/deep_translator/detection.py index 438afed..4759d44 100644 --- a/deep_translator/detection.py +++ b/deep_translator/detection.py @@ -1,10 +1,10 @@ """ language detection API """ +from typing import List, Optional, Union + import requests from requests.exceptions import HTTPError -from typing import Optional, List, Union - # Module global config config = { diff --git a/deep_translator/google.py b/deep_translator/google.py index 78f8d0c..39b2cdb 100644 --- a/deep_translator/google.py +++ b/deep_translator/google.py @@ -2,17 +2,19 @@ google translator API """ +from typing import List, Optional + +import requests +from bs4 import BeautifulSoup + +from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS from deep_translator.exceptions import ( + RequestError, TooManyRequests, TranslationNotFound, - RequestError, ) -from deep_translator.base import BaseTranslator -from deep_translator.validate import is_input_valid, is_empty -from bs4 import BeautifulSoup -import requests -from typing import Optional, List +from deep_translator.validate import is_empty, is_input_valid class GoogleTranslator(BaseTranslator): diff --git a/deep_translator/libre.py b/deep_translator/libre.py index 03bdf80..2fc8df2 100644 --- a/deep_translator/libre.py +++ b/deep_translator/libre.py @@ -2,16 +2,18 @@ LibreTranslate API """ +from typing import List, Optional + import requests -from typing import Optional, List -from deep_translator.validate import is_empty, is_input_valid + from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS, LIBRE_LANGUAGES_TO_CODES from deep_translator.exceptions import ( + AuthorizationException, ServerException, TranslationNotFound, - AuthorizationException, ) +from deep_translator.validate import is_empty, is_input_valid class LibreTranslator(BaseTranslator): diff --git a/deep_translator/linguee.py b/deep_translator/linguee.py index 9c02cda..81a84b9 100644 --- a/deep_translator/linguee.py +++ b/deep_translator/linguee.py @@ -1,20 +1,22 @@ """ linguee translator API """ -from deep_translator.validate import is_input_valid, is_empty +from typing import List, Optional, Union + +import requests +from bs4 import BeautifulSoup +from requests.utils import requote_uri + +from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS, LINGUEE_LANGUAGES_TO_CODES from deep_translator.exceptions import ( - TranslationNotFound, - NotValidPayload, ElementNotFoundInGetRequest, + NotValidPayload, RequestError, TooManyRequests, + TranslationNotFound, ) -from deep_translator.base import BaseTranslator -from bs4 import BeautifulSoup -import requests -from requests.utils import requote_uri -from typing import Optional, List, Union +from deep_translator.validate import is_empty, is_input_valid class LingueeTranslator(BaseTranslator): diff --git a/deep_translator/microsoft.py b/deep_translator/microsoft.py index 2f37908..e6d6953 100644 --- a/deep_translator/microsoft.py +++ b/deep_translator/microsoft.py @@ -1,13 +1,15 @@ # -*- coding: utf-8 -*- -import requests import logging import sys -from deep_translator.constants import BASE_URLS -from deep_translator.exceptions import ServerException, MicrosoftAPIerror +from typing import List, Optional + +import requests + from deep_translator.base import BaseTranslator +from deep_translator.constants import BASE_URLS +from deep_translator.exceptions import MicrosoftAPIerror, ServerException from deep_translator.validate import is_input_valid -from typing import Optional, List class MicrosoftTranslator(BaseTranslator): diff --git a/deep_translator/mymemory.py b/deep_translator/mymemory.py index de5efa3..ba16b9b 100644 --- a/deep_translator/mymemory.py +++ b/deep_translator/mymemory.py @@ -1,16 +1,18 @@ """ mymemory translator API """ -from deep_translator.validate import is_empty, is_input_valid +from typing import List, Optional, Union + +import requests + +from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS from deep_translator.exceptions import ( - TranslationNotFound, RequestError, TooManyRequests, + TranslationNotFound, ) -from deep_translator.base import BaseTranslator -import requests -from typing import Optional, List, Union +from deep_translator.validate import is_empty, is_input_valid class MyMemoryTranslator(BaseTranslator): diff --git a/deep_translator/papago.py b/deep_translator/papago.py index 0c5f323..814a28e 100644 --- a/deep_translator/papago.py +++ b/deep_translator/papago.py @@ -2,11 +2,13 @@ google translator API """ import json +from typing import List, Optional + +import requests + +from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS, PAPAGO_LANGUAGE_TO_CODE from deep_translator.exceptions import TranslationNotFound -from deep_translator.base import BaseTranslator -import requests -from typing import Optional, List from deep_translator.validate import is_input_valid diff --git a/deep_translator/pons.py b/deep_translator/pons.py index c1c5161..c7b711a 100644 --- a/deep_translator/pons.py +++ b/deep_translator/pons.py @@ -1,21 +1,22 @@ """ pons translator API """ -from bs4 import BeautifulSoup +from typing import List, Optional, Union + import requests +from bs4 import BeautifulSoup +from requests.utils import requote_uri -from deep_translator.validate import is_input_valid, is_empty +from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS, PONS_CODES_TO_LANGUAGES from deep_translator.exceptions import ( - TranslationNotFound, - NotValidPayload, ElementNotFoundInGetRequest, + NotValidPayload, RequestError, TooManyRequests, + TranslationNotFound, ) -from deep_translator.base import BaseTranslator -from requests.utils import requote_uri -from typing import Optional, Union, List +from deep_translator.validate import is_empty, is_input_valid class PonsTranslator(BaseTranslator): diff --git a/deep_translator/qcri.py b/deep_translator/qcri.py index d67ddc1..1ac92d4 100644 --- a/deep_translator/qcri.py +++ b/deep_translator/qcri.py @@ -1,8 +1,10 @@ +from typing import List, Optional + import requests + +from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS, QCRI_LANGUAGE_TO_CODE from deep_translator.exceptions import ServerException, TranslationNotFound -from deep_translator.base import BaseTranslator -from typing import Optional, List class QcriTranslator(BaseTranslator): diff --git a/deep_translator/validate.py b/deep_translator/validate.py index 1512e19..f152076 100644 --- a/deep_translator/validate.py +++ b/deep_translator/validate.py @@ -1,4 +1,4 @@ -from deep_translator.exceptions import NotValidPayload, NotValidLength +from deep_translator.exceptions import NotValidLength, NotValidPayload def is_empty(text: str) -> bool: diff --git a/deep_translator/yandex.py b/deep_translator/yandex.py index 2ed2c70..016a246 100644 --- a/deep_translator/yandex.py +++ b/deep_translator/yandex.py @@ -1,17 +1,19 @@ """ Yandex translator API """ +from typing import List, Optional + import requests + +from deep_translator.base import BaseTranslator from deep_translator.constants import BASE_URLS from deep_translator.exceptions import ( RequestError, ServerException, - TranslationNotFound, TooManyRequests, + TranslationNotFound, ) -from deep_translator.base import BaseTranslator from deep_translator.validate import is_input_valid -from typing import Optional, List class YandexTranslator(BaseTranslator): diff --git a/docs/conf.py b/docs/conf.py index 88bcb16..b53a0ca 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -19,6 +19,7 @@ # import os import sys + sys.path.insert(0, os.path.abspath('..')) # import deep_translator @@ -58,6 +59,7 @@ # # The short X.Y version. import toml + with open("../pyproject.toml", "r") as f: tom = toml.load(f) version = tom['tool']['poetry']['version'] diff --git a/examples/linguee.py b/examples/linguee.py index f5d8a0f..65eb82d 100644 --- a/examples/linguee.py +++ b/examples/linguee.py @@ -1,7 +1,6 @@ from deep_translator import LingueeTranslator - res = LingueeTranslator(source='de', target='en').translate('laufen', return_all=False) print(res) diff --git a/examples/mymemory.py b/examples/mymemory.py index 52ee93e..0cd58a5 100644 --- a/examples/mymemory.py +++ b/examples/mymemory.py @@ -1,7 +1,6 @@ from deep_translator import MyMemoryTranslator - res = MyMemoryTranslator(source='ar', target='en').translate('آخُذ اَلْباص.') print(res) diff --git a/examples/pons.py b/examples/pons.py index 376beef..265cc56 100644 --- a/examples/pons.py +++ b/examples/pons.py @@ -1,7 +1,6 @@ from deep_translator import PonsTranslator - res = PonsTranslator(source='en', target='de').translate('good', return_all=False) print(res) diff --git a/examples/trans.py b/examples/trans.py index cc1209d..7efc25a 100644 --- a/examples/trans.py +++ b/examples/trans.py @@ -1,5 +1,4 @@ -from deep_translator import GoogleTranslator, PonsTranslator, LingueeTranslator - +from deep_translator import GoogleTranslator, LingueeTranslator, PonsTranslator # examples using google translate diff --git a/poetry.lock b/poetry.lock index c3da6de..efaa7c0 100644 --- a/poetry.lock +++ b/poetry.lock @@ -219,6 +219,20 @@ category = "dev" optional = false python-versions = "*" +[[package]] +name = "isort" +version = "5.10.1" +description = "A Python utility / library to sort Python imports." +category = "dev" +optional = false +python-versions = ">=3.6.1,<4.0" + +[package.extras] +pipfile_deprecated_finder = ["pipreqs", "requirementslib"] +requirements_deprecated_finder = ["pipreqs", "pip-api"] +colors = ["colorama (>=0.4.3,<0.5.0)"] +plugins = ["setuptools"] + [[package]] name = "jeepney" version = "0.7.1" @@ -720,7 +734,7 @@ testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest- [metadata] lock-version = "1.1" python-versions = "^3.7" -content-hash = "465ff9b79ec7a4f8f67638bed33190079fbe1dcca8261d36813c7787e30624f2" +content-hash = "999f9269962bc8ce6f5ad597f7aa7afc6d5a4382b8cadfd8ffe75cd8ed16a41e" [metadata.files] alabaster = [ @@ -936,6 +950,10 @@ iniconfig = [ {file = "iniconfig-1.1.1-py2.py3-none-any.whl", hash = "sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3"}, {file = "iniconfig-1.1.1.tar.gz", hash = "sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32"}, ] +isort = [ + {file = "isort-5.10.1-py3-none-any.whl", hash = "sha256:6f62d78e2f89b4500b080fe3a81690850cd254227f27f75c3a0c491a1f351ba7"}, + {file = "isort-5.10.1.tar.gz", hash = "sha256:e8443a5e7a020e9d7f97f1d7d9cd17c88bcb3bc7e218bf9cf5095fe550be2951"}, +] jeepney = [ {file = "jeepney-0.7.1-py3-none-any.whl", hash = "sha256:1b5a0ea5c0e7b166b2f5895b91a08c14de8915afda4407fb5022a195224958ac"}, {file = "jeepney-0.7.1.tar.gz", hash = "sha256:fa9e232dfa0c498bd0b8a3a73b8d8a31978304dcef0515adc859d4e096f96f4f"}, diff --git a/pyproject.toml b/pyproject.toml index ad54707..fc1d697 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,6 +41,7 @@ pytest = "^6.2.4" pytest-runner = "^5.3.1" toml = "^0.10.2" black = "^22.1.0" +isort = "^5.10.1" [build-system] requires = ["poetry-core>=1.0.0"] diff --git a/tests/test_cli.py b/tests/test_cli.py index e632cb1..5250f44 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2,10 +2,12 @@ """Tests for the CLI interface.""" -from deep_translator.cli import CLI -import pytest import sys +import pytest + +from deep_translator.cli import CLI + @pytest.fixture def mock_args(): diff --git a/tests/test_deepl.py b/tests/test_deepl.py index 6c898a6..e4d4426 100644 --- a/tests/test_deepl.py +++ b/tests/test_deepl.py @@ -1,5 +1,7 @@ -import pytest from unittest.mock import Mock, patch + +import pytest + from deep_translator.deepl import DeeplTranslator from deep_translator.exceptions import AuthorizationException diff --git a/tests/test_google.py b/tests/test_google.py index 65b252c..c142be8 100644 --- a/tests/test_google.py +++ b/tests/test_google.py @@ -3,7 +3,8 @@ """Tests for `deep_translator` package.""" import pytest -from deep_translator import exceptions, GoogleTranslator + +from deep_translator import GoogleTranslator, exceptions from deep_translator.constants import GOOGLE_LANGUAGES_TO_CODES diff --git a/tests/test_libre.py b/tests/test_libre.py index 9166ea6..ba24e36 100644 --- a/tests/test_libre.py +++ b/tests/test_libre.py @@ -3,7 +3,8 @@ """Tests for `deep_translator` package.""" import pytest -from deep_translator import exceptions, LibreTranslator + +from deep_translator import LibreTranslator, exceptions from deep_translator.constants import LIBRE_LANGUAGES_TO_CODES diff --git a/tests/test_linguee.py b/tests/test_linguee.py index 7e80741..ebb4b5f 100644 --- a/tests/test_linguee.py +++ b/tests/test_linguee.py @@ -3,7 +3,8 @@ """Tests for `deep_translator` package.""" import pytest -from deep_translator import exceptions, LingueeTranslator + +from deep_translator import LingueeTranslator, exceptions @pytest.fixture diff --git a/tests/test_microsoft_trans.py b/tests/test_microsoft_trans.py index 891acba..9bc0fc0 100644 --- a/tests/test_microsoft_trans.py +++ b/tests/test_microsoft_trans.py @@ -2,11 +2,12 @@ """Tests for `deep_translator` package.""" -import pytest from unittest.mock import patch + +import pytest import requests -from deep_translator import exceptions, MicrosoftTranslator +from deep_translator import MicrosoftTranslator, exceptions # mocked request.post diff --git a/tests/test_mymemory.py b/tests/test_mymemory.py index a0e21b1..b651e24 100644 --- a/tests/test_mymemory.py +++ b/tests/test_mymemory.py @@ -3,7 +3,8 @@ """Tests for `deep_translator` package.""" import pytest -from deep_translator import exceptions, MyMemoryTranslator + +from deep_translator import MyMemoryTranslator, exceptions @pytest.fixture diff --git a/tests/test_pons.py b/tests/test_pons.py index 79e661d..67e459c 100644 --- a/tests/test_pons.py +++ b/tests/test_pons.py @@ -3,7 +3,8 @@ """Tests for `deep_translator` package.""" import pytest -from deep_translator import exceptions, PonsTranslator + +from deep_translator import PonsTranslator, exceptions @pytest.fixture