Nidhal Baccouri commited on
Commit
e8eddb4
·
unverified ·
2 Parent(s): 8572051 c9e74de

Merge pull request #73 from nidhaloff/nothead31/issue66

Browse files
AUTHORS.rst CHANGED
@@ -12,3 +12,4 @@ Contributors
12
 
13
  @prataffel
14
  @senk8
 
 
12
 
13
  @prataffel
14
  @senk8
15
+ @nothead31
deep_translator/__init__.py CHANGED
@@ -13,18 +13,17 @@ from .microsoft import MicrosoftTranslator
13
  from .papago import PapagoTranslator
14
 
15
  # TODO: Discussion: These should be declared in setup.cfg, setting them here is redundant
16
- # __author__ = """Nidhal Baccouri"""
17
- # __email__ = '[email protected]'
18
- # __version__ = '1.4.4'
19
 
20
- # __all__ = [GoogleTranslator,
21
- # PonsTranslator,
22
- # LingueeTranslator,
23
- # MyMemoryTranslator,
24
- # YandexTranslator,
25
- # MicrosoftTranslator,
26
- # QCRI,
27
- # DeepL,
28
- # main,
29
- # single_detection,
30
- # batch_detection]
 
13
  from .papago import PapagoTranslator
14
 
15
  # TODO: Discussion: These should be declared in setup.cfg, setting them here is redundant
16
+ __author__ = """Nidhal Baccouri"""
17
+ __email__ = '[email protected]'
18
+ __version__ = '1.5.0'
19
 
20
+ __all__ = [GoogleTranslator,
21
+ PonsTranslator,
22
+ LingueeTranslator,
23
+ MyMemoryTranslator,
24
+ YandexTranslator,
25
+ MicrosoftTranslator,
26
+ QCRI,
27
+ DeepL,
28
+ single_detection,
29
+ batch_detection]
 
deep_translator/configs.py DELETED
@@ -1,11 +0,0 @@
1
- """
2
- configuration object that holds data about the language detection api
3
- """
4
-
5
- config = {
6
- "url": 'https://ws.detectlanguage.com/0.2/detect',
7
- "headers": {
8
- 'User-Agent': 'Detect Language API Python Client 1.4.0',
9
- 'Authorization': 'Bearer {}',
10
- }
11
- }
 
 
 
 
 
 
 
 
 
 
 
 
deep_translator/detection.py CHANGED
@@ -2,9 +2,10 @@
2
  language detection API
3
  """
4
  import requests
5
- from .configs import config # TODO: Discussion: Could this be moved here and remove configs.py entirely?
6
  from requests.exceptions import HTTPError
7
 
 
 
8
 
9
  def get_request_body(text, api_key, *args, **kwargs):
10
  """
 
2
  language detection API
3
  """
4
  import requests
 
5
  from requests.exceptions import HTTPError
6
 
7
+ # Module global config
8
+ config = {"url": 'https://ws.detectlanguage.com/0.2/detect',"headers": {'User-Agent': 'Detect Language API Python Client 1.4.0','Authorization': 'Bearer {}',}}
9
 
10
  def get_request_body(text, api_key, *args, **kwargs):
11
  """
deep_translator/{__main__.py → main.py} RENAMED
@@ -12,70 +12,31 @@ from .microsoft import MicrosoftTranslator
12
  from .papago import PapagoTranslator
13
 
14
  CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
 
 
 
15
 
16
- @click.command(name='Deep Translator', context_settings=CONTEXT_SETTINGS, no_args_is_help=True)
17
- @click.argument(
18
- 'translator',
19
- required=True,
20
- default='google',
21
- type=str)
22
- @click.option(
23
- "--source",
24
- "-src",
25
- required=True,
26
- type=str,
27
- help="source language to translate from")
28
- @click.option(
29
- "--target",
30
- "-tgt",
31
- required=True,
32
- type=str,
33
- help="target language to translate to")
34
- @click.option(
35
- "--text",
36
- "-txt",
37
- type=str,
38
- required = True,
39
- prompt="Enter the text you want to translate",
40
- help="text you want to translate")
41
- @click.option(
42
- "--api-key",
43
- type=str,
44
- help="required for DeepL, QCRI, Yandex, Microsoft and Papago translators")
45
- @click.option(
46
- "--languages",
47
- "-lang",
48
- is_flag=True,
49
- help="list all the languages available with the translator."
50
- " Run with deep_translator <translator service> -lang",)
51
- def main(translator, source, target, text, api_key, languages):
52
  """
53
  Use TRANSLATOR to translate source material into another language.
54
- Available translators include: Google, MyMemory, QCRI, Linguee, Pons, Yandex, Microsoft (Bing), and Papago.\n
55
  \f
56
- function responsible for parsing terminal arguments and provide them for
57
- further use in the translation process
 
58
  """
59
  api_key_required = ["deepl", "qcri", "yandex", "microsoft", "papago"]
60
  if translator in api_key_required and not api_key:
61
  click.echo(
62
- "This translator requires an api key provided through --api-key"
63
- )
64
- elif languages:
65
- print_supported_languages(translator, api_key)
66
  else:
67
- translate(translator, source, target, text, api_key)
68
 
69
- def translate(translator, source, target, text, api_key):
70
- """
71
- function used to provide translations from the parsed terminal arguments
72
- @param translator: translator name parsed from terminal arguments
73
- @param source: source language parsed from terminal arguments
74
- @param target: target language parsed from terminal arguments
75
- @param text: text that will be translated parsed from terminal arguments
76
- @param api_key: api key for translators that requires them
77
- @return: None
78
- """
79
  if translator == "google":
80
  translator = GoogleTranslator(source=source, target=target)
81
  elif translator == "mymemory":
@@ -92,66 +53,72 @@ def translate(translator, source, target, text, api_key):
92
  translator = YandexTranslator(
93
  source=source,
94
  target=target,
95
- api_key=api_key
96
- )
97
  elif translator == "microsoft":
98
  translator = MicrosoftTranslator(
99
  source=source,
100
  target=target,
101
- api_key=api_key
102
- )
103
  elif translator == "papago":
104
  translator = PapagoTranslator(
105
  source=source,
106
  target=target,
107
- api_key=api_key
108
- )
109
  else:
110
- click.echo(
111
- "The given translator is not supported."
112
- " Please use a translator supported by the deep_translator tool"
113
- )
114
- return
115
 
116
  res = translator.translate(text)
117
  click.echo(f" | Translation from {source} to {target} |")
118
  click.echo(f"Translated text: \n {res}")
 
119
 
120
- def print_supported_languages(requested_translator, api_key):
 
 
 
121
  """
122
- function used to print the languages supported by the translator service
123
- from the parsed terminal arguments
124
- @param args: parsed terminal arguments
125
  @return: None
126
  """
127
- translator = None
128
- if requested_translator == "google":
 
 
 
 
 
 
129
  translator = GoogleTranslator
130
- elif requested_translator == "mymemory":
131
  translator = MyMemoryTranslator
132
- elif requested_translator == "qcri":
133
  translator = QCRI(api_key=api_key)
134
- elif requested_translator == "linguee":
135
  translator = LingueeTranslator
136
- elif requested_translator == "pons":
137
  translator = PonsTranslator
138
- elif requested_translator == "yandex":
139
  translator = YandexTranslator(api_key=api_key)
140
- elif requested_translator == "microsoft":
141
  translator = MicrosoftTranslator(api_key=api_key)
142
- elif requested_translator == "papago":
143
  translator = PapagoTranslator(api_key=api_key)
144
  else:
145
- click.echo(
146
- "The given translator is not supported."
147
- " Please use a translator supported by the deep_translator tool"
148
- )
149
- return
150
 
151
  supported_languages = translator.get_supported_languages(as_dict=True)
152
- click.echo(f"Languages supported by '{requested_translator}' are :")
153
  for k, v in supported_languages.items():
154
  click.echo(f"|- {k}: {v}")
 
 
 
 
 
 
 
155
 
156
  if __name__ == "__main__":
157
- main()
 
12
  from .papago import PapagoTranslator
13
 
14
  CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
15
+ @click.group()
16
+ def cli():
17
+ pass
18
 
19
+ @cli.command(context_settings=CONTEXT_SETTINGS, no_args_is_help=True)
20
+ @click.argument('translator', required=True, default='google', type=str)
21
+ @click.option("--source", "-src", required=True, type=str, help="source language to translate from")
22
+ @click.option("--target", "-tgt", required=True, type=str, help="target language to translate to")
23
+ @click.option("--text", "-txt", type=str,required = True,prompt="Enter the text you want to translate",help="text you want to translate")
24
+ @click.option("--api-key",type=str,help="required for DeepL, QCRI, Yandex, Microsoft and Papago translators")
25
+ def translate(translator, source, target, text, api_key, languages):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  """
27
  Use TRANSLATOR to translate source material into another language.
 
28
  \f
29
+ Directory function to send arguments to the correct translator.
30
+ @param translator: translator name parsed from terminal arguments
31
+ @return: None
32
  """
33
  api_key_required = ["deepl", "qcri", "yandex", "microsoft", "papago"]
34
  if translator in api_key_required and not api_key:
35
  click.echo(
36
+ "This translator requires an api key provided through --api-key")
 
 
 
37
  else:
38
+ pass
39
 
 
 
 
 
 
 
 
 
 
 
40
  if translator == "google":
41
  translator = GoogleTranslator(source=source, target=target)
42
  elif translator == "mymemory":
 
53
  translator = YandexTranslator(
54
  source=source,
55
  target=target,
56
+ api_key=api_key)
 
57
  elif translator == "microsoft":
58
  translator = MicrosoftTranslator(
59
  source=source,
60
  target=target,
61
+ api_key=api_key)
 
62
  elif translator == "papago":
63
  translator = PapagoTranslator(
64
  source=source,
65
  target=target,
66
+ api_key=api_key)
 
67
  else:
68
+ raise AttributeError("The given translator is not supported.")
 
 
 
 
69
 
70
  res = translator.translate(text)
71
  click.echo(f" | Translation from {source} to {target} |")
72
  click.echo(f"Translated text: \n {res}")
73
+ return 0
74
 
75
+ @cli.command(context_settings=CONTEXT_SETTINGS, no_args_is_help=True)
76
+ @click.argument('translator')
77
+ @click.argument('api_key', required=False)
78
+ def languages(translator, api_key):
79
  """
80
+ Retrieve the list of available languages from the given translator.
81
+ @param translator: Translator given by the user.
82
+ @param api_key: Optional API key given by the user. Required for some translators.
83
  @return: None
84
  """
85
+ translator = translator.lower()
86
+ api_key_required = ["deepl", "qcri", "yandex", "microsoft", "papago"]
87
+ if translator in api_key_required and not api_key:
88
+ click.echo("This translator requires an api key provided through --api-key")
89
+ else:
90
+ pass
91
+
92
+ if translator == "google":
93
  translator = GoogleTranslator
94
+ elif translator == "mymemory":
95
  translator = MyMemoryTranslator
96
+ elif translator == "qcri":
97
  translator = QCRI(api_key=api_key)
98
+ elif translator == "linguee":
99
  translator = LingueeTranslator
100
+ elif translator == "pons":
101
  translator = PonsTranslator
102
+ elif translator == "yandex":
103
  translator = YandexTranslator(api_key=api_key)
104
+ elif translator == "microsoft":
105
  translator = MicrosoftTranslator(api_key=api_key)
106
+ elif translator == "papago":
107
  translator = PapagoTranslator(api_key=api_key)
108
  else:
109
+ raise AttributeError("The given translator is not supported.")
 
 
 
 
110
 
111
  supported_languages = translator.get_supported_languages(as_dict=True)
112
+ click.echo(f"Languages supported by '{translator}' are :")
113
  for k, v in supported_languages.items():
114
  click.echo(f"|- {k}: {v}")
115
+ return 0
116
+
117
+ @cli.command()
118
+ def list():
119
+ """Lists available translators."""
120
+ click.echo("Available translators include: Google, MyMemory, QCRI, Linguee, Pons, Yandex, Microsoft (Bing), and Papago.")
121
+ return 0
122
 
123
  if __name__ == "__main__":
124
+ cli()
deep_translator/tests/test_cli.py CHANGED
@@ -3,14 +3,20 @@
3
  """Tests for the CLI interface."""
4
 
5
  from click.testing import CliRunner
6
- from deep_translator import __main__
7
 
8
  def results_test():
9
  runner = CliRunner()
10
- result = runner.invoke(__main__.main, [ 'google', 'auto', 'en', '좋은'])
11
  assert result.exit_code == 0
12
  assert result == 'good'
13
 
14
- api_error = runner.invoke(__main__.main, ['microsoft','auto','en','Zwei minimale Dellchen auf der Rückseite.'])
15
  assert api_error.exit_code == 0
16
- assert api_error == "This translator requires an api key provided through --api-key"
 
 
 
 
 
 
 
3
  """Tests for the CLI interface."""
4
 
5
  from click.testing import CliRunner
6
+ from deep_translator import main
7
 
8
  def results_test():
9
  runner = CliRunner()
10
+ result = runner.invoke(main.translate, [ 'google', 'auto', 'en', '좋은'])
11
  assert result.exit_code == 0
12
  assert result == 'good'
13
 
14
+ api_error = runner.invoke(main.translate, ['microsoft','auto','en','Zwei minimale Dellchen auf der Rückseite.'])
15
  assert api_error.exit_code == 0
16
+ assert api_error == "This translator requires an api key provided through --api-key"
17
+
18
+ language_list_test = runner.invoke(main.languages, ['google'])
19
+ assert language_list_test.exit_code == 0
20
+
21
+ language_list_invalid_test = runner.invoke(main.languages, ['notValidTranslator'])
22
+ assert language_list_invalid_test.exception == AttributeError
deep_translator/utils.py DELETED
@@ -1,4 +0,0 @@
1
- """
2
- utilities
3
- """
4
- # TODO: Discussion: Whats the purpsoe of this module?
 
 
 
 
 
setup.cfg CHANGED
@@ -1,7 +1,7 @@
1
  #main config
2
  [metadata]
3
  name = Deep Translator
4
- version = 1.4.4
5
  url = https://github.com/nidhaloff/deep_translator
6
  author = Nidhal Baccouri
7
  author_email = [email protected]
@@ -36,8 +36,8 @@ keywords = deep_translator, deepL, DeepL, translator, translation, automation,
36
  detect language, free translation, unlimited translation, translate for free
37
 
38
  [build_sphinx]
39
- version = 1.4.4
40
- release = 1.4.4
41
 
42
  # TODO: These can be switched back on if the CI platform changes from Travis. Travis still requires setup.py to function properly.
43
  # [options]
@@ -72,6 +72,7 @@ release = 1.4.4
72
  # search = __version__ = '{current_version}'
73
  # replace = __version__ = '{new_version}'
74
 
 
75
  # TODO: These are all optional settings, turned on for now since they exist already.
76
  [bdist_wheel]
77
  universal = 1
@@ -84,4 +85,4 @@ exclude = docs
84
  test = pytest
85
 
86
  [tool:pytest]
87
- collect_ignore = [setup.py]
 
1
  #main config
2
  [metadata]
3
  name = Deep Translator
4
+ version = 1.5.0
5
  url = https://github.com/nidhaloff/deep_translator
6
  author = Nidhal Baccouri
7
  author_email = [email protected]
 
36
  detect language, free translation, unlimited translation, translate for free
37
 
38
  [build_sphinx]
39
+ version = 1.5.0
40
+ release = 1.5.0
41
 
42
  # TODO: These can be switched back on if the CI platform changes from Travis. Travis still requires setup.py to function properly.
43
  # [options]
 
72
  # search = __version__ = '{current_version}'
73
  # replace = __version__ = '{new_version}'
74
 
75
+
76
  # TODO: These are all optional settings, turned on for now since they exist already.
77
  [bdist_wheel]
78
  universal = 1
 
85
  test = pytest
86
 
87
  [tool:pytest]
88
+ collect_ignore = [setup.py]
setup.py CHANGED
@@ -11,7 +11,7 @@ setup(
11
  include_package_data=True,
12
  packages=find_packages(include=['deep_translator'],),
13
  entry_points={'console_scripts':[
14
- 'deep-translator=deep_translator.__main__:main',
15
- 'dt=deep_translator.__main__:main',
16
  ],},
17
  )
 
11
  include_package_data=True,
12
  packages=find_packages(include=['deep_translator'],),
13
  entry_points={'console_scripts':[
14
+ 'deep-translator=deep_translator.main:cli',
15
+ 'dt=deep_translator.main:cli',
16
  ],},
17
  )