Updated deep-translator module and made some fix to support translation to Chinese. There's still a bug in this module that prevent it but one it's fixed, it should be fine.
parent
6a88596aab
commit
f0828959f3
@ -1,52 +0,0 @@
|
||||
"""Console script for deep_translator."""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from .google_trans import GoogleTranslator
|
||||
from .mymemory import MyMemoryTranslator
|
||||
from .pons import PonsTranslator
|
||||
from .linguee import LingueeTranslator
|
||||
|
||||
|
||||
def translate(args):
|
||||
"""
|
||||
function used to provide translations from the parsed terminal arguments
|
||||
@param args: parsed terminal arguments
|
||||
@return: None
|
||||
"""
|
||||
translator = None
|
||||
if args.translator == 'google':
|
||||
translator = GoogleTranslator(source=args.source, target=args.target)
|
||||
elif args.translator == 'pons':
|
||||
translator = PonsTranslator(source=args.source, target=args.target)
|
||||
elif args.translator == 'linguee':
|
||||
translator = LingueeTranslator(source=args.source, target=args.target)
|
||||
elif args.translator == 'mymemory':
|
||||
translator = MyMemoryTranslator(source=args.source, target=args.target)
|
||||
else:
|
||||
print("given translator is not supported. Please use a supported translator from the deep_translator tool")
|
||||
|
||||
res = translator.translate(args.text)
|
||||
print(" | Translation from {} to {} |".format(args.source, args.target))
|
||||
print("Translated text: \n {}".format(res))
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
function responsible for parsing terminal arguments and provide them for further use in the translation process
|
||||
|
||||
"""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--translator', '-trans',
|
||||
default='google', type=str, help="name of the translator you want to use")
|
||||
parser.add_argument('--source', '-src', type=str, help="source language to translate from", required=True)
|
||||
parser.add_argument('--target', '-tg', type=str, help="target language to translate to", required=True)
|
||||
parser.add_argument('--text', '-txt', type=str, help="text you want to translate", required=True)
|
||||
|
||||
args = parser.parse_args()
|
||||
translate(args)
|
||||
# sys.exit()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -1,11 +0,0 @@
|
||||
"""
|
||||
configuration object that holds data about the language detection api
|
||||
"""
|
||||
|
||||
config = {
|
||||
"url": 'https://ws.detectlanguage.com/0.2/detect',
|
||||
"headers": {
|
||||
'User-Agent': 'Detect Language API Python Client 1.4.0',
|
||||
'Authorization': 'Bearer {}',
|
||||
}
|
||||
}
|
@ -1,59 +1,89 @@
|
||||
|
||||
import requests
|
||||
from requests.utils import requote_uri
|
||||
from deep_translator.constants import BASE_URLS
|
||||
from deep_translator.exceptions import (RequestError,
|
||||
ServerException, TranslationNotFound, TooManyRequests)
|
||||
from .constants import BASE_URLS, DEEPL_LANGUAGE_TO_CODE
|
||||
from .exceptions import (ServerException,
|
||||
TranslationNotFound,
|
||||
LanguageNotSupportedException,
|
||||
AuthorizationException)
|
||||
|
||||
|
||||
class DeepL(object):
|
||||
"""
|
||||
class that wraps functions, which use the DeepL translator under the hood to translate word(s)
|
||||
"""
|
||||
_languages = DEEPL_LANGUAGE_TO_CODE
|
||||
|
||||
def __init__(self, api_key=None):
|
||||
def __init__(self, api_key=None, source="en", target="en", use_free_api=True, **kwargs):
|
||||
"""
|
||||
@param api_key: your DeepL api key. Get one here: https://www.deepl.com/docs-api/accessing-the-api/
|
||||
@param api_key: your DeepL api key.
|
||||
Get one here: https://www.deepl.com/docs-api/accessing-the-api/
|
||||
@param source: source language
|
||||
@param target: target language
|
||||
"""
|
||||
|
||||
if not api_key:
|
||||
raise ServerException(401)
|
||||
self.version = 'v2'
|
||||
self.api_key = api_key
|
||||
self.__base_url = BASE_URLS.get("DEEPL").format(version=self.version)
|
||||
self.source = self._map_language_to_code(source)
|
||||
self.target = self._map_language_to_code(target)
|
||||
if use_free_api:
|
||||
self.__base_url = BASE_URLS.get("DEEPL_FREE").format(version=self.version)
|
||||
else:
|
||||
self.__base_url = BASE_URLS.get("DEEPL").format(version=self.version)
|
||||
|
||||
def translate(self, source, target, text):
|
||||
def translate(self, text, **kwargs):
|
||||
"""
|
||||
@param text: text to translate
|
||||
@return: translated text
|
||||
"""
|
||||
# Create the request parameters.
|
||||
translate_endpoint = 'translate'
|
||||
params = {
|
||||
"auth_key": self.api_key,
|
||||
"target_lang": target,
|
||||
"source_lang": source,
|
||||
"source_lang": self.source,
|
||||
"target_lang": self.target,
|
||||
"text": text
|
||||
}
|
||||
# Do the request and check the connection.
|
||||
try:
|
||||
response = requests.get(self.__base_url, params=params)
|
||||
response = requests.get(self.__base_url + translate_endpoint, params=params)
|
||||
except ConnectionError:
|
||||
raise ServerException(503)
|
||||
# If the answer is not success, raise server exception.
|
||||
if response.status_code == 403:
|
||||
raise AuthorizationException(self.api_key)
|
||||
elif response.status_code != 200:
|
||||
raise ServerException(response.status_code)
|
||||
# Get the response and check is not empty.
|
||||
res = response.json()
|
||||
if not res:
|
||||
raise TranslationNotFound(text)
|
||||
# Process and return the response.
|
||||
return res['translations'][0]['text']
|
||||
|
||||
else:
|
||||
if response.status_code != 200:
|
||||
ServerException(response.status_code)
|
||||
else:
|
||||
res = response.json()
|
||||
if not res:
|
||||
raise TranslationNotFound(text)
|
||||
return res
|
||||
|
||||
def translate_batch(self, source, target, batch):
|
||||
def translate_batch(self, batch, **kwargs):
|
||||
"""
|
||||
translate a batch of texts
|
||||
@param source: source language
|
||||
@param target: target language
|
||||
@param batch: list of texts to translate
|
||||
@return: list of translations
|
||||
"""
|
||||
return [self.translate(source, target, text) for text in batch]
|
||||
return [self.translate(text, **kwargs) for text in batch]
|
||||
|
||||
@staticmethod
|
||||
def get_supported_languages(as_dict=False, **kwargs):
|
||||
return [*DeepL._languages.keys()] if not as_dict else DeepL._languages
|
||||
|
||||
def _is_language_supported(self, lang, **kwargs):
|
||||
# The language is supported when is in the dicionary.
|
||||
return lang == 'auto' or lang in self._languages.keys() or lang in self._languages.values()
|
||||
|
||||
def _map_language_to_code(self, lang, **kwargs):
|
||||
if lang in self._languages.keys():
|
||||
return self._languages[lang]
|
||||
elif lang in self._languages.values():
|
||||
return lang
|
||||
raise LanguageNotSupportedException(lang)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
d = DeepL(api_key="key")
|
||||
print(d)
|
||||
d = DeepL(target="de")
|
||||
t = d.translate("I have no idea")
|
||||
print("text: ", t)
|
||||
|
@ -0,0 +1,124 @@
|
||||
"""Console script for deep_translator."""
|
||||
|
||||
import click
|
||||
from .google_trans import GoogleTranslator
|
||||
from .mymemory import MyMemoryTranslator
|
||||
from .deepl import DeepL
|
||||
from .qcri import QCRI
|
||||
from .linguee import LingueeTranslator
|
||||
from .pons import PonsTranslator
|
||||
from .yandex import YandexTranslator
|
||||
from .microsoft import MicrosoftTranslator
|
||||
from .papago import PapagoTranslator
|
||||
|
||||
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
|
||||
@click.group()
|
||||
def cli():
|
||||
pass
|
||||
|
||||
@cli.command(context_settings=CONTEXT_SETTINGS, no_args_is_help=True)
|
||||
@click.argument('translator', required=True, default='google', type=str)
|
||||
@click.option("--source", "-src", required=True, type=str, help="source language to translate from")
|
||||
@click.option("--target", "-tgt", required=True, type=str, help="target language to translate to")
|
||||
@click.option("--text", "-txt", type=str,required = True,prompt="Enter the text you want to translate",help="text you want to translate")
|
||||
@click.option("--api-key",type=str,help="required for DeepL, QCRI, Yandex, Microsoft and Papago translators")
|
||||
def translate(translator, source, target, text, api_key):
|
||||
"""
|
||||
Use TRANSLATOR to translate source material into another language.
|
||||
\f
|
||||
Directory function to send arguments to the correct translator.
|
||||
@param translator: translator name parsed from terminal arguments
|
||||
@return: None
|
||||
"""
|
||||
api_key_required = ["deepl", "qcri", "yandex", "microsoft", "papago"]
|
||||
if translator in api_key_required and not api_key:
|
||||
click.echo(
|
||||
"This translator requires an api key provided through --api-key")
|
||||
else:
|
||||
pass
|
||||
|
||||
if translator == "google":
|
||||
translator = GoogleTranslator(source=source, target=target)
|
||||
elif translator == "mymemory":
|
||||
translator = MyMemoryTranslator(source=source, target=target)
|
||||
elif translator == "deepl":
|
||||
translator = DeepL(source=source, target=target, api_key=api_key)
|
||||
elif translator == "qcri":
|
||||
translator = QCRI(source=source, target=target, api_key=api_key)
|
||||
elif translator == "linguee":
|
||||
translator = LingueeTranslator(source=source, target=target)
|
||||
elif translator == "pons":
|
||||
translator = PonsTranslator(source=source, target=target)
|
||||
elif translator == "yandex":
|
||||
translator = YandexTranslator(
|
||||
source=source,
|
||||
target=target,
|
||||
api_key=api_key)
|
||||
elif translator == "microsoft":
|
||||
translator = MicrosoftTranslator(
|
||||
source=source,
|
||||
target=target,
|
||||
api_key=api_key)
|
||||
elif translator == "papago":
|
||||
translator = PapagoTranslator(
|
||||
source=source,
|
||||
target=target,
|
||||
api_key=api_key)
|
||||
else:
|
||||
raise AttributeError("The given translator is not supported.")
|
||||
|
||||
res = translator.translate(text)
|
||||
click.echo(f" | Translation from {source} to {target} |")
|
||||
click.echo(f"Translated text: \n {res}")
|
||||
return 0
|
||||
|
||||
@cli.command(context_settings=CONTEXT_SETTINGS, no_args_is_help=True)
|
||||
@click.argument('translator')
|
||||
@click.argument('api_key', required=False)
|
||||
def languages(translator, api_key):
|
||||
"""
|
||||
Retrieve the list of available languages from the given translator.
|
||||
@param translator: Translator given by the user.
|
||||
@param api_key: Optional API key given by the user. Required for some translators.
|
||||
@return: None
|
||||
"""
|
||||
translator = translator.lower()
|
||||
api_key_required = ["deepl", "qcri", "yandex", "microsoft", "papago"]
|
||||
if translator in api_key_required and not api_key:
|
||||
click.echo("This translator requires an api key provided through --api-key")
|
||||
else:
|
||||
pass
|
||||
|
||||
if translator == "google":
|
||||
translator = GoogleTranslator
|
||||
elif translator == "mymemory":
|
||||
translator = MyMemoryTranslator
|
||||
elif translator == "qcri":
|
||||
translator = QCRI(api_key=api_key)
|
||||
elif translator == "linguee":
|
||||
translator = LingueeTranslator
|
||||
elif translator == "pons":
|
||||
translator = PonsTranslator
|
||||
elif translator == "yandex":
|
||||
translator = YandexTranslator(api_key=api_key)
|
||||
elif translator == "microsoft":
|
||||
translator = MicrosoftTranslator(api_key=api_key)
|
||||
elif translator == "papago":
|
||||
translator = PapagoTranslator(api_key=api_key)
|
||||
else:
|
||||
raise AttributeError("The given translator is not supported.")
|
||||
|
||||
supported_languages = translator.get_supported_languages(as_dict=True)
|
||||
click.echo(f"Languages supported by '{translator}' are :")
|
||||
for k, v in supported_languages.items():
|
||||
click.echo(f"|- {k}: {v}")
|
||||
return 0
|
||||
|
||||
@cli.command()
|
||||
def list():
|
||||
"""Lists available translators."""
|
||||
click.echo("Available translators include: Google, MyMemory, QCRI, Linguee, Pons, Yandex, Microsoft (Bing), and Papago.")
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli()
|
@ -0,0 +1,146 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import requests
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from .constants import BASE_URLS, MICROSOFT_CODES_TO_LANGUAGES
|
||||
from .exceptions import LanguageNotSupportedException, ServerException, MicrosoftAPIerror
|
||||
|
||||
|
||||
class MicrosoftTranslator:
|
||||
"""
|
||||
the class that wraps functions, which use the Microsoft translator under the hood to translate word(s)
|
||||
"""
|
||||
|
||||
_languages = MICROSOFT_CODES_TO_LANGUAGES
|
||||
supported_languages = list(_languages.values())
|
||||
|
||||
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
|
||||
@param region: your Microsoft Location
|
||||
"""
|
||||
if not api_key:
|
||||
raise ServerException(401)
|
||||
else:
|
||||
self.api_key = api_key
|
||||
|
||||
self.proxies = proxies
|
||||
self.headers = {
|
||||
"Ocp-Apim-Subscription-Key": self.api_key,
|
||||
"Content-type": "application/json",
|
||||
}
|
||||
# region is not required but very common and goes to headers if passed
|
||||
if region:
|
||||
self.region = region
|
||||
self.headers["Ocp-Apim-Subscription-Region"] = self.region
|
||||
|
||||
if not target:
|
||||
raise ServerException(401)
|
||||
else:
|
||||
if type(target) is str:
|
||||
self.target = target.lower()
|
||||
else:
|
||||
self.target = [i.lower() for i in target]
|
||||
if self.is_language_supported(self.target):
|
||||
self.target = self._map_language_to_code(self.target)
|
||||
|
||||
self.url_params = {'to': self.target, **kwargs}
|
||||
|
||||
if source:
|
||||
self.source = source.lower()
|
||||
if self.is_language_supported(self.source):
|
||||
self.source = self._map_language_to_code(self.source)
|
||||
self.url_params['from'] = self.source
|
||||
|
||||
self.__base_url = BASE_URLS.get("MICROSOFT_TRANSLATE")
|
||||
|
||||
@staticmethod
|
||||
def get_supported_languages(as_dict=False, **kwargs):
|
||||
"""
|
||||
return the languages supported by the microsoft translator
|
||||
@param as_dict: if True, the languages will be returned as a dictionary mapping languages to their abbreviations
|
||||
@return: list or dict
|
||||
"""
|
||||
return MicrosoftTranslator.supported_languages if not as_dict else MicrosoftTranslator._languages
|
||||
|
||||
def _map_language_to_code(self, language, **kwargs):
|
||||
"""
|
||||
map the language to its corresponding code (abbreviation) if the language was passed by its full name by the user
|
||||
@param language: a string (if 1 lang) or a list (if multiple langs)
|
||||
@return: mapped value of the language or raise an exception if the language is not supported
|
||||
"""
|
||||
if type(language) is str:
|
||||
language = [language]
|
||||
for lang in language:
|
||||
if lang in self._languages.values():
|
||||
yield lang
|
||||
elif lang in self._languages.keys():
|
||||
yield self._languages[lang]
|
||||
else:
|
||||
raise LanguageNotSupportedException(lang)
|
||||
|
||||
def is_language_supported(self, language, **kwargs):
|
||||
"""
|
||||
check if the language is supported by the translator
|
||||
@param language: a string (if 1 lang) or a list (if multiple langs)
|
||||
@return: bool or raise an Exception
|
||||
"""
|
||||
if type(language) is str:
|
||||
language = [language]
|
||||
for lang in language:
|
||||
if lang not in self._languages.keys():
|
||||
if lang not in self._languages.values():
|
||||
raise LanguageNotSupportedException(lang)
|
||||
return True
|
||||
|
||||
def translate(self, text, **kwargs):
|
||||
"""
|
||||
function that uses microsoft translate to translate a text
|
||||
@param text: desired text to translate
|
||||
@return: str: translated text
|
||||
"""
|
||||
# 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
|
||||
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)
|
||||
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']
|
||||
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']]
|
||||
return "\n".join(all_translations)
|
||||
|
||||
def translate_file(self, path, **kwargs):
|
||||
"""
|
||||
translate from a file
|
||||
@param path: path to file
|
||||
@return: translated text
|
||||
"""
|
||||
try:
|
||||
with open(path) as f:
|
||||
text = f.read().strip()
|
||||
return self.translate(text)
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
def translate_batch(self, batch, **kwargs):
|
||||
"""
|
||||
translate a batch of texts
|
||||
@param batch: list of texts to translate
|
||||
@return: list of translations
|
||||
"""
|
||||
return [self.translate(text, **kwargs) for text in batch]
|
@ -0,0 +1,154 @@
|
||||
"""
|
||||
google translator API
|
||||
"""
|
||||
import json
|
||||
from .constants import BASE_URLS, PAPAGO_LANGUAGE_TO_CODE
|
||||
from .exceptions import LanguageNotSupportedException, TranslationNotFound, NotValidPayload
|
||||
import requests
|
||||
import warnings
|
||||
import logging
|
||||
|
||||
|
||||
class PapagoTranslator(object):
|
||||
"""
|
||||
class that wraps functions, which use google translate under the hood to translate text(s)
|
||||
"""
|
||||
_languages = PAPAGO_LANGUAGE_TO_CODE
|
||||
supported_languages = list(_languages.keys())
|
||||
|
||||
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")
|
||||
|
||||
self.__base_url = BASE_URLS.get("PAPAGO_API")
|
||||
self.client_id = client_id
|
||||
self.secret_key = secret_key
|
||||
if self.is_language_supported(source, target):
|
||||
self._source, self._target = self._map_language_to_code(source.lower(), target.lower())
|
||||
|
||||
@staticmethod
|
||||
def get_supported_languages(as_dict=False, **kwargs):
|
||||
"""
|
||||
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 PapagoTranslator.supported_languages if not as_dict else PapagoTranslator._languages
|
||||
|
||||
def _map_language_to_code(self, *languages):
|
||||
"""
|
||||
map language to its corresponding code (abbreviation) if the language was passed by its full name by the user
|
||||
@param languages: list of 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':
|
||||
yield language
|
||||
elif language in self._languages.keys():
|
||||
yield self._languages[language]
|
||||
else:
|
||||
raise LanguageNotSupportedException(language)
|
||||
|
||||
def is_language_supported(self, *languages):
|
||||
"""
|
||||
check if the language is supported by the translator
|
||||
@param languages: list of languages
|
||||
@return: bool or raise an Exception
|
||||
"""
|
||||
for lang in languages:
|
||||
if lang != 'auto' and lang not in self._languages.keys():
|
||||
if lang != 'auto' and lang not in self._languages.values():
|
||||
raise LanguageNotSupportedException(lang)
|
||||
return True
|
||||
|
||||
def translate(self, text, **kwargs):
|
||||
"""
|
||||
function that uses google translate to translate a text
|
||||
@param text: desired text to translate
|
||||
@return: str: translated 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'
|
||||
}
|
||||
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}')
|
||||
res_body = json.loads(response.text)
|
||||
if "message" not in res_body:
|
||||
raise TranslationNotFound(text)
|
||||
|
||||
msg = res_body.get("message")
|
||||
result = msg.get("result", None)
|
||||
if not result:
|
||||
raise TranslationNotFound(text)
|
||||
translated_text = result.get("translatedText")
|
||||
return translated_text
|
||||
|
||||
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
|
||||
"""
|
||||
try:
|
||||
with open(path) as f:
|
||||
text = f.read().strip()
|
||||
return self.translate(text)
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
def translate_sentences(self, sentences=None, **kwargs):
|
||||
"""
|
||||
translate many sentences together. This makes sense if you have sentences with different languages
|
||||
and you want to translate all to unified language. This is handy because it detects
|
||||
automatically the language of each sentence and then translate it.
|
||||
|
||||
@param sentences: list of sentences to translate
|
||||
@return: list of all translated sentences
|
||||
"""
|
||||
warnings.warn("deprecated. Use the translate_batch function instead", DeprecationWarning, stacklevel=2)
|
||||
logging.warning("deprecated. Use the translate_batch function instead")
|
||||
if not sentences:
|
||||
raise NotValidPayload(sentences)
|
||||
|
||||
translated_sentences = []
|
||||
try:
|
||||
for sentence in sentences:
|
||||
translated = self.translate(text=sentence)
|
||||
translated_sentences.append(translated)
|
||||
|
||||
return translated_sentences
|
||||
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
def translate_batch(self, batch=None, **kwargs):
|
||||
"""
|
||||
translate a list of texts
|
||||
@param batch: list of texts you want to translate
|
||||
@return: list of translations
|
||||
"""
|
||||
if not batch:
|
||||
raise Exception("Enter your text list that you want to translate")
|
||||
arr = []
|
||||
for i, text in enumerate(batch):
|
||||
|
||||
translated = self.translate(text, **kwargs)
|
||||
arr.append(translated)
|
||||
return arr
|
||||
|
||||
|
@ -1 +0,0 @@
|
||||
"""Unit test package for deep_translator."""
|
@ -1,57 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""Tests for `deep_translator` package."""
|
||||
|
||||
import pytest
|
||||
from deep_translator import exceptions, GoogleTranslator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def google_translator():
|
||||
"""Sample pytest fixture.
|
||||
|
||||
See more at: http://doc.pytest.org/en/latest/fixture.html
|
||||
"""
|
||||
return GoogleTranslator(target='en')
|
||||
|
||||
|
||||
def test_content(google_translator):
|
||||
"""Sample pytest test function with the pytest fixture as an argument."""
|
||||
# from bs4 import BeautifulSoup
|
||||
# assert 'GitHub' in BeautifulSoup(response.content).title.string
|
||||
assert google_translator.translate(text='좋은') == "good"
|
||||
|
||||
|
||||
def test_inputs():
|
||||
with pytest.raises(exceptions.LanguageNotSupportedException):
|
||||
GoogleTranslator(source="", target="")
|
||||
|
||||
with pytest.raises(exceptions.LanguageNotSupportedException):
|
||||
GoogleTranslator(source="auto", target="nothing")
|
||||
|
||||
# test abbreviations and languages
|
||||
g1 = GoogleTranslator("en", "fr")
|
||||
g2 = GoogleTranslator("english", "french")
|
||||
assert g1._source == g2._source
|
||||
assert g1._target == g2._target
|
||||
|
||||
|
||||
def test_payload(google_translator):
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
google_translator.translate(text="")
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
google_translator.translate(text=123)
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
google_translator.translate(text={})
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
google_translator.translate(text=[])
|
||||
|
||||
with pytest.raises(exceptions.NotValidLength):
|
||||
google_translator.translate("a"*5001)
|
||||
|
||||
#for _ in range(1):
|
||||
#assert google_translator.translate(text='좋은') == "good"
|
@ -1,49 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""Tests for `deep_translator` package."""
|
||||
|
||||
import pytest
|
||||
from deep_translator import exceptions, LingueeTranslator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def linguee():
|
||||
return LingueeTranslator(source="english", target='french')
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_inputs():
|
||||
with pytest.raises(exceptions.LanguageNotSupportedException):
|
||||
LingueeTranslator(source="", target="")
|
||||
|
||||
with pytest.raises(exceptions.LanguageNotSupportedException):
|
||||
LingueeTranslator(source="auto", target="nothing")
|
||||
|
||||
l1 = LingueeTranslator("en", "fr")
|
||||
l2 = LingueeTranslator("english", "french")
|
||||
assert l1._source == l2._source
|
||||
assert l1._target == l2._target
|
||||
|
||||
|
||||
def test_payload(linguee):
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
linguee.translate("")
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
linguee.translate(123)
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
linguee.translate({})
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
linguee.translate([])
|
||||
|
||||
with pytest.raises(exceptions.NotValidLength):
|
||||
linguee.translate("a"*51)
|
@ -1,48 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""Tests for `deep_translator` package."""
|
||||
|
||||
import pytest
|
||||
from deep_translator import exceptions, MyMemoryTranslator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mymemory():
|
||||
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
|
||||
|
||||
|
||||
def test_inputs():
|
||||
with pytest.raises(exceptions.LanguageNotSupportedException):
|
||||
MyMemoryTranslator(source="", target="")
|
||||
|
||||
with pytest.raises(exceptions.LanguageNotSupportedException):
|
||||
MyMemoryTranslator(source="auto", target="nothing")
|
||||
m1 = MyMemoryTranslator("en", "fr")
|
||||
m2 = MyMemoryTranslator("english", "french")
|
||||
assert m1._source == m2._source
|
||||
assert m1._target == m2._target
|
||||
|
||||
|
||||
def test_payload(mymemory):
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
mymemory.translate(text="")
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
mymemory.translate(text=123)
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
mymemory.translate(text={})
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
mymemory.translate(text=[])
|
||||
|
||||
with pytest.raises(exceptions.NotValidLength):
|
||||
mymemory.translate(text="a"*501)
|
@ -1,48 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""Tests for `deep_translator` package."""
|
||||
|
||||
import pytest
|
||||
from deep_translator import exceptions, PonsTranslator
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pons():
|
||||
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
|
||||
|
||||
|
||||
def test_inputs():
|
||||
with pytest.raises(exceptions.LanguageNotSupportedException):
|
||||
PonsTranslator(source="", target="")
|
||||
|
||||
with pytest.raises(exceptions.LanguageNotSupportedException):
|
||||
PonsTranslator(source="auto", target="nothing")
|
||||
l1 = PonsTranslator("en", "fr")
|
||||
l2 = PonsTranslator("english", "french")
|
||||
assert l1._source == l2._source
|
||||
assert l1._target == l2._target
|
||||
|
||||
|
||||
def test_payload(pons):
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
pons.translate("")
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
pons.translate(123)
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
pons.translate({})
|
||||
|
||||
with pytest.raises(exceptions.NotValidPayload):
|
||||
pons.translate([])
|
||||
|
||||
with pytest.raises(exceptions.NotValidLength):
|
||||
pons.translate("a" * 51)
|
@ -1,3 +0,0 @@
|
||||
"""
|
||||
utilities
|
||||
"""
|
Loading…
Reference in new issue