Skip to content

Commit

Permalink
Refactor Google Translate & DeepL Translate & Improved CLI mode & New
Browse files Browse the repository at this point in the history
tests
  • Loading branch information
ZhymabekRoman committed May 27, 2021
1 parent a87bd79 commit faf4b27
Show file tree
Hide file tree
Showing 17 changed files with 598 additions and 858 deletions.
5 changes: 5 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@
long_description_content_type = "text/markdown",
include_package_data=True,
python_requires='>=3.2, <4',
entry_points={
'console_scripts': [
'translatepy-cli = translatepy.__main__:main'
]
},
package_data={
'translatepy': ['LICENSE'],
},
Expand Down
67 changes: 0 additions & 67 deletions tests/test_translator.py

This file was deleted.

48 changes: 48 additions & 0 deletions tests/test_translators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from translatepy.translators.google import GoogleTranslateV1, GoogleTranslateV2
from translatepy.translators.bing import BingTranslate
from translatepy.translators.yandex import YandexTranslate
from translatepy.translators.reverso import ReversoTranslate
from translatepy.translators.deepl import DeeplTranslate
from translatepy import Translator


class TestAllTranslators:
def setup(self):
self.services_list = [
Translator(),
GoogleTranslateV1(),
GoogleTranslateV2(),
BingTranslate(),
ReversoTranslate(),
YandexTranslate(),
DeeplTranslate(),
]

def test_service_translate(self):
translation_args_list = [["What cool weather today!", "fr"],
["Hello", "Japanese", "en"],
["Hello, how are you?", "ja"]]

for service in self.services_list:
for args in translation_args_list:
result = service.translate(*args)
assert result

def test_service_transliterate(self):
transliteration_args_list = [["What cool weather today!", "ar"],
["Hello", "Japanese", "en"],
["Hello, how are you?", "ja"]]

for service in self.services_list:
for args in transliteration_args_list:
result = service.transliterate(*args)
assert result

def test_service_spellcheck(self):
spellcheck_args_list = [["What cool weater todai!"], ["Helo"],
["Helo, how are tou?"]]

for service in self.services_list:
for args in spellcheck_args_list:
result = service.spellcheck(*args)
assert result
16 changes: 0 additions & 16 deletions tests/translators/test_reverso.py

This file was deleted.

24 changes: 0 additions & 24 deletions tests/translators/test_yandex.py

This file was deleted.

39 changes: 27 additions & 12 deletions translatepy/__main__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,34 @@
import argparse
from translatepy import Translator

dl = Translator()

# Create the parser
my_parser = argparse.ArgumentParser(prog='translatepy-cli', description='Translate, transliterate, get the language of texts in no time with the help of multiple APIs!')
def main():
dl = Translator()

subparser = my_parser.add_subparsers(help='Actions', dest="action", required=True)
parser_translate = subparser.add_parser('translate', help='Translates the given text to the given language')
parser_translate.add_argument('--text', '-t', action='store', type=str, required=True, help='text to translate')
parser_translate.add_argument('--dest-lang', '-d', action='store', type=str, required=True, help='destination language')
parser_translate.add_argument('--source-lang', '-s', action='store', default='auto', type=str, help='source language')
# Create the parser
my_parser = argparse.ArgumentParser(prog='translatepy-cli', description='Translate, transliterate, get the language of texts in no time with the help of multiple APIs!')

args = my_parser.parse_args()
subparser = my_parser.add_subparsers(help='Actions', dest="action", required=True)
parser_translate = subparser.add_parser('translate', help='Translates the given text to the given language')
parser_translate.add_argument('--text', '-t', action='store', type=str, required=True, help='text to translate')
parser_translate.add_argument('--dest-lang', '-d', action='store', type=str, required=True, help='destination language')
parser_translate.add_argument('--source-lang', '-s', action='store', default='auto', type=str, help='source language')

if args.action == 'translate':
result = dl.translate(args.text, args.dest_lang, args.source_lang)
print(result)
parser_translate = subparser.add_parser('shell', help='Translates the given text in interactive shell mode')

args = my_parser.parse_args()

if args.action == 'translate':
result = dl.translate(args.text, args.dest_lang, args.source_lang)
print(result)

if args.action == 'shell':
while True:
input_text = input(">>> ")

result = dl.translate(input_text, "en")
print(result)


if __name__ == "__main__":
main()
1 change: 0 additions & 1 deletion translatepy/_google_translate_domains.json

This file was deleted.

56 changes: 30 additions & 26 deletions translatepy/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
© Anime no Sekai — 2021
"""

import inspect
# import inspect

# from translatepy.translators import GoogleTranslate
from translatepy.translators.google import GoogleTranslateV1, GoogleTranslateV2
from translatepy.translators.bing import BingTranslate
from translatepy.translators.yandex import YandexTranslate
from translatepy.translators.reverso import ReversoTranslate
# from translatepy.translators import DeepL
from translatepy.translators.deepl import DeeplTranslate
from translatepy.translators.base import BaseTranslator

from translatepy.models import TranslationResult, TransliterationResult, SpellcheckResult, LanguageResult
from translatepy.utils.annotations import List


Expand All @@ -22,12 +22,12 @@ class Translator():
"""

def __init__(self, services_list: List[BaseTranslator] = [
# GoogleTranslator,
# GoogleV2Translator,
BingTranslate,
# DeepLTranslator,
ReversoTranslate,
YandexTranslate,
YandexTranslate(),
GoogleTranslateV1(),
GoogleTranslateV2(),
BingTranslate(),
ReversoTranslate(),
DeeplTranslate(),
]) -> None:

if not isinstance(services_list, List):
Expand All @@ -36,15 +36,19 @@ def __init__(self, services_list: List[BaseTranslator] = [
if not services_list:
raise ValueError("Parameter 'services_list' must not be empty")

for service in services_list:
if not inspect.isclass(service):
raise ValueError("Type of the parameter 'services_list' must be a class")
if not issubclass(service, BaseTranslator):
raise TypeError("Type of the parameter 'services_list' must be a child class of BaseTranslator class")
# TODO: validation is broken
# for service in services_list:
# if not inspect.isclass(service):
# ...
# Or:
# if not isinstance(service, type):
# raise ValueError("Type of the parameter 'services_list' must be a class")
# if not issubclass(service, BaseTranslator):
# raise TypeError("Type of the parameter 'services_list' must be a child class of BaseTranslator class")

self.services = services_list

def translate(self, text, destination_language, source_language="auto"):
def translate(self, text: str, destination_language: str, source_language: str = "auto") -> TranslationResult:
"""
Translates the given text to the given language
Expand All @@ -53,32 +57,32 @@ def translate(self, text, destination_language, source_language="auto"):

for service in self.services:
try:
result = service().translate(
result = service.translate(
text, destination_language, source_language)
except ImportError: # Exception:
except Exception:
continue
else:
return result
else:
print("ERROR!")

def transliterate(self, text, source_language="auto") -> str:
def transliterate(self, text: str, destination_language: str = "en", source_language: str = "auto") -> TransliterationResult:
"""
Transliterates the given text
i.e おはよう --> Ohayou
"""
for service in self.services:
try:
result = service().transliterate(text, source_language)
result = service.transliterate(text, destination_language, source_language)
except Exception:
continue
else:
return result
else:
print("NOOOOOOOOOOOO!")

def spellcheck(self, text, source_language="auto") -> str:
def spellcheck(self, text: str, source_language: str = "auto") -> SpellcheckResult:
"""
Checks the spelling of a given text
Expand All @@ -87,15 +91,15 @@ def spellcheck(self, text, source_language="auto") -> str:

for service in self.services:
try:
result = service().spellcheck(text, source_language)
result = service.spellcheck(text, source_language)
except Exception:
continue
else:
return result
else:
print("NOOOOOO!")

def language(self, text: str) -> str:
def language(self, text: str) -> LanguageResult:
"""
Returns the language of the given text
Expand All @@ -104,15 +108,15 @@ def language(self, text: str) -> str:

for service in self.services:
try:
response = service().language(text)
response = service.language(text)
except Exception:
continue
else:
return response
else:
print("NOOOOOOOOOOOOO!")

def example(self, text, destination_language=None, source_language="auto") -> str:
def example(self, text: str, destination_language: str, source_language: str = "auto") -> str:
"""
Returns a set of examples / use cases for the given word
Expand All @@ -121,7 +125,7 @@ def example(self, text, destination_language=None, source_language="auto") -> st

result = self.bing_translate.example(text, destination_language, source_language)

def dictionary(self, text, destination_language, source_language="auto") -> str:
def dictionary(self, text: str, destination_language: str, source_language="auto") -> str:
"""
Returns a list of translations that are classified between two categories: featured and less common
Expand Down
15 changes: 5 additions & 10 deletions translatepy/translators/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
# TODO

"""
from .bing import BingTranslator
from .deepl import DeepLTranslator
from .google import GoogleTranslator, GoogleV2Translator
from .reverso import ReversoTranslator
from .translator import Translator
from .yandex import YandexTranslator
"""
from translatepy.translators.google import GoogleTranslateV1, GoogleTranslateV2
from translatepy.translators.bing import BingTranslate
from translatepy.translators.yandex import YandexTranslate
from translatepy.translators.reverso import ReversoTranslate
from translatepy.translators.deepl import DeeplTranslate
Loading

0 comments on commit faf4b27

Please sign in to comment.