deep-translator-v2 1.11.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ """Top-level package for Deep Translator"""
2
+
3
+ __copyright__ = "Copyright (C) 2020 Nidhal Baccouri"
4
+
5
+ from deep_translator.baidu import BaiduTranslator
6
+ from deep_translator.chatgpt import ChatGptTranslator
7
+ from deep_translator.deepl import DeeplTranslator
8
+ from deep_translator.detection import batch_detection, single_detection
9
+ from deep_translator.google import GoogleTranslator
10
+ from deep_translator.libre import LibreTranslator
11
+ from deep_translator.linguee import LingueeTranslator
12
+ from deep_translator.microsoft import MicrosoftTranslator
13
+ from deep_translator.mymemory import MyMemoryTranslator
14
+ from deep_translator.papago import PapagoTranslator
15
+ from deep_translator.pons import PonsTranslator
16
+ from deep_translator.qcri import QcriTranslator
17
+ from deep_translator.tencent import TencentTranslator
18
+ from deep_translator.yandex import YandexTranslator
19
+
20
+ __author__ = """Nidhal Baccouri"""
21
+ __email__ = "nidhalbacc@gmail.com"
22
+ __version__ = "1.9.1"
23
+
24
+ __all__ = [
25
+ "GoogleTranslator",
26
+ "PonsTranslator",
27
+ "LingueeTranslator",
28
+ "MyMemoryTranslator",
29
+ "YandexTranslator",
30
+ "MicrosoftTranslator",
31
+ "QcriTranslator",
32
+ "DeeplTranslator",
33
+ "LibreTranslator",
34
+ "PapagoTranslator",
35
+ "ChatGptTranslator",
36
+ "TencentTranslator",
37
+ "BaiduTranslator",
38
+ "single_detection",
39
+ "batch_detection",
40
+ ]
@@ -0,0 +1,12 @@
1
+ __copyright__ = "Copyright (C) 2020 Nidhal Baccouri"
2
+
3
+
4
+ from deep_translator.cli import CLI
5
+
6
+
7
+ def main():
8
+ CLI().run()
9
+
10
+
11
+ if __name__ == "__main__":
12
+ main()
@@ -0,0 +1,120 @@
1
+ """
2
+ baidu translator API
3
+ """
4
+
5
+ __copyright__ = "Copyright (C) 2020 Nidhal Baccouri"
6
+
7
+ import hashlib
8
+ import os
9
+ import random
10
+ from typing import List, Optional
11
+
12
+ import requests
13
+
14
+ from deep_translator.base import BaseTranslator
15
+ from deep_translator.constants import (
16
+ BAIDU_APPID_ENV_VAR,
17
+ BAIDU_APPKEY_ENV_VAR,
18
+ BAIDU_LANGUAGE_TO_CODE,
19
+ BASE_URLS,
20
+ )
21
+ from deep_translator.exceptions import (
22
+ ApiKeyException,
23
+ BaiduAPIerror,
24
+ ServerException,
25
+ TranslationNotFound,
26
+ )
27
+ from deep_translator.validate import is_empty, is_input_valid
28
+
29
+
30
+ class BaiduTranslator(BaseTranslator):
31
+ """
32
+ class that wraps functions, which use the BaiduTranslator translator
33
+ under the hood to translate word(s)
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ source: str = "en",
39
+ target: str = "zh",
40
+ appid: Optional[str] = os.getenv(BAIDU_APPID_ENV_VAR, None),
41
+ appkey: Optional[str] = os.getenv(BAIDU_APPKEY_ENV_VAR, None),
42
+ **kwargs
43
+ ):
44
+ """
45
+ @param appid: your baidu cloud api appid.
46
+ Get one here: https://fanyi-api.baidu.com/choose
47
+ @param appkey: your baidu cloud api appkey.
48
+ @param source: source language
49
+ @param target: target language
50
+ """
51
+ if not appid:
52
+ raise ApiKeyException(env_var=BAIDU_APPID_ENV_VAR)
53
+
54
+ if not appkey:
55
+ raise ApiKeyException(env_var=BAIDU_APPKEY_ENV_VAR)
56
+
57
+ self.appid = appid
58
+ self.appkey = appkey
59
+ super().__init__(
60
+ base_url=BASE_URLS.get("BAIDU"),
61
+ source=source,
62
+ target=target,
63
+ languages=BAIDU_LANGUAGE_TO_CODE,
64
+ **kwargs
65
+ )
66
+
67
+ def translate(self, text: str, **kwargs) -> str:
68
+ """
69
+ @param text: text to translate
70
+ @return: translated text
71
+ """
72
+ if is_input_valid(text):
73
+ if self._same_source_target() or is_empty(text):
74
+ return text
75
+
76
+ # Create the request parameters.
77
+ salt = random.randint(32768, 65536)
78
+ sign = hashlib.md5(
79
+ (self.appid + text + str(salt) + self.appkey).encode("utf-8")
80
+ ).hexdigest()
81
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
82
+ payload = {
83
+ "appid": self.appid,
84
+ "q": text,
85
+ "from": self.source,
86
+ "to": self.target,
87
+ "salt": salt,
88
+ "sign": sign,
89
+ }
90
+
91
+ # Do the request and check the connection.
92
+ try:
93
+ response = requests.post(
94
+ self._base_url, params=payload, headers=headers
95
+ )
96
+ except ConnectionError:
97
+ raise ServerException(503)
98
+ if response.status_code != 200:
99
+ raise ServerException(response.status_code)
100
+ # Get the response and check is not empty.
101
+ res = response.json()
102
+ if not res:
103
+ raise TranslationNotFound(text)
104
+ # Process and return the response.
105
+ if "error_code" in res:
106
+ raise BaiduAPIerror(res["error_msg"])
107
+ if "trans_result" in res:
108
+ return "\n".join([s["dst"] for s in res["trans_result"]])
109
+ else:
110
+ raise TranslationNotFound(text)
111
+
112
+ def translate_file(self, path: str, **kwargs) -> str:
113
+ return self._translate_file(path, **kwargs)
114
+
115
+ def translate_batch(self, batch: List[str], **kwargs) -> List[str]:
116
+ """
117
+ @param batch: list of texts to translate
118
+ @return: list of translations
119
+ """
120
+ return self._translate_batch(batch, **kwargs)
@@ -0,0 +1,183 @@
1
+ """base translator class"""
2
+
3
+ __copyright__ = "Copyright (C) 2020 Nidhal Baccouri"
4
+
5
+ from abc import ABC, abstractmethod
6
+ from pathlib import Path
7
+ from typing import List, Optional, Union
8
+
9
+ from deep_translator.constants import GOOGLE_LANGUAGES_TO_CODES
10
+ from deep_translator.exceptions import (
11
+ InvalidSourceOrTargetLanguage,
12
+ LanguageNotSupportedException,
13
+ )
14
+
15
+
16
+ class BaseTranslator(ABC):
17
+ """
18
+ Abstract class that serve as a base translator for other different translators
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ base_url: str = None,
24
+ languages: dict = GOOGLE_LANGUAGES_TO_CODES,
25
+ source: str = "auto",
26
+ target: str = "en",
27
+ payload_key: Optional[str] = None,
28
+ element_tag: Optional[str] = None,
29
+ element_query: Optional[dict] = None,
30
+ **url_params,
31
+ ):
32
+ """
33
+ @param source: source language to translate from
34
+ @param target: target language to translate to
35
+ """
36
+ self._base_url = base_url
37
+ self._languages = languages
38
+ self._supported_languages = list(self._languages.keys())
39
+ if not source:
40
+ raise InvalidSourceOrTargetLanguage(source)
41
+ if not target:
42
+ raise InvalidSourceOrTargetLanguage(target)
43
+
44
+ self._source, self._target = self._map_language_to_code(source, target)
45
+ self._url_params = url_params
46
+ self._element_tag = element_tag
47
+ self._element_query = element_query
48
+ self.payload_key = payload_key
49
+ super().__init__()
50
+
51
+ @property
52
+ def source(self):
53
+ return self._source
54
+
55
+ @source.setter
56
+ def source(self, lang):
57
+ self._source = lang
58
+
59
+ @property
60
+ def target(self):
61
+ return self._target
62
+
63
+ @target.setter
64
+ def target(self, lang):
65
+ self._target = lang
66
+
67
+ def _type(self):
68
+ return self.__class__.__name__
69
+
70
+ def _map_language_to_code(self, *languages):
71
+ """
72
+ map language to its corresponding code (abbreviation) if the language was passed
73
+ by its full name by the user
74
+ @param languages: list of languages
75
+ @return: mapped value of the language or raise an exception if the language is
76
+ not supported
77
+ """
78
+ for language in languages:
79
+ if language in self._languages.values() or language == "auto":
80
+ yield language
81
+ elif language in self._languages.keys():
82
+ yield self._languages[language]
83
+ else:
84
+ raise LanguageNotSupportedException(
85
+ language,
86
+ message=f"No support for the provided language.\n"
87
+ f"Please select on of the supported languages:\n"
88
+ f"{self._languages}",
89
+ )
90
+
91
+ def _same_source_target(self) -> bool:
92
+ return self._source == self._target
93
+
94
+ def get_supported_languages(
95
+ self, as_dict: bool = False, **kwargs
96
+ ) -> Union[list, dict]:
97
+ """
98
+ return the supported languages by the Google translator
99
+ @param as_dict: if True, the languages will be returned as a dictionary
100
+ mapping languages to their abbreviations
101
+ @return: list or dict
102
+ """
103
+ return self._supported_languages if not as_dict else self._languages
104
+
105
+ def is_language_supported(self, language: str, **kwargs) -> bool:
106
+ """
107
+ check if the language is supported by the translator
108
+ @param language: a string for 1 language
109
+ @return: bool or raise an Exception
110
+ """
111
+ if (
112
+ language == "auto"
113
+ or language in self._languages.keys()
114
+ or language in self._languages.values()
115
+ ):
116
+ return True
117
+ else:
118
+ return False
119
+
120
+ @abstractmethod
121
+ def translate(self, text: str, **kwargs) -> str:
122
+ """
123
+ translate a text using a translator under the hood and return
124
+ the translated text
125
+ @param text: text to translate
126
+ @param kwargs: additional arguments
127
+ @return: str
128
+ """
129
+ return NotImplemented("You need to implement the translate method!")
130
+
131
+ def _read_docx(self, f: str):
132
+ import docx2txt
133
+
134
+ return docx2txt.process(f)
135
+
136
+ def _read_pdf(self, f: str):
137
+ import pypdf
138
+
139
+ reader = pypdf.PdfReader(f)
140
+ page = reader.pages[0]
141
+ return page.extract_text()
142
+
143
+ def _translate_file(self, path: str, **kwargs) -> str:
144
+ """
145
+ translate directly from file
146
+ @param path: path to the target file
147
+ @type path: str
148
+ @param kwargs: additional args
149
+ @return: str
150
+ """
151
+ if not isinstance(path, Path):
152
+ path = Path(path)
153
+
154
+ if not path.exists():
155
+ print("Path to the file is wrong!")
156
+ exit(1)
157
+
158
+ ext = path.suffix
159
+
160
+ if ext == ".docx":
161
+ text = self._read_docx(f=str(path))
162
+
163
+ elif ext == ".pdf":
164
+ text = self._read_pdf(f=str(path))
165
+ else:
166
+ with open(path, "r", encoding="utf-8") as f:
167
+ text = f.read().strip()
168
+
169
+ return self.translate(text)
170
+
171
+ def _translate_batch(self, batch: List[str], **kwargs) -> List[str]:
172
+ """
173
+ translate a list of texts
174
+ @param batch: list of texts you want to translate
175
+ @return: list of translations
176
+ """
177
+ if not batch:
178
+ raise Exception("Enter your text list that you want to translate")
179
+ arr = []
180
+ for i, text in enumerate(batch):
181
+ translated = self.translate(text, **kwargs)
182
+ arr.append(translated)
183
+ return arr
@@ -0,0 +1,71 @@
1
+ __copyright__ = "Copyright (C) 2020 Nidhal Baccouri"
2
+
3
+ import os
4
+ from typing import List, Optional
5
+
6
+ import requests
7
+
8
+ from deep_translator.base import BaseTranslator
9
+ from deep_translator.constants import OPEN_AI_ENV_VAR
10
+ from deep_translator.exceptions import ApiKeyException
11
+
12
+
13
+ class ChatGptTranslator(BaseTranslator):
14
+ """
15
+ class that wraps functions, which use the ChatGPT
16
+ under the hood to translate word(s)
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ source: str = "auto",
22
+ target: str = "english",
23
+ api_key: Optional[str] = None,
24
+ model: str = "gpt-6-luna",
25
+ **kwargs,
26
+ ):
27
+ """
28
+ @param api_key: your openai api key.
29
+ @param source: source language
30
+ @param target: target language
31
+ @param model: OpenAI model that supports Chat Completions
32
+ """
33
+ if api_key is None:
34
+ api_key = os.getenv("OPENAI_API_KEY") or os.getenv(OPEN_AI_ENV_VAR)
35
+ if not api_key:
36
+ raise ApiKeyException(env_var="OPENAI_API_KEY")
37
+
38
+ self.api_key = api_key
39
+ self.model = model
40
+
41
+ super().__init__(source=source, target=target, **kwargs)
42
+
43
+ def translate(self, text: str, **kwargs) -> str:
44
+ """
45
+ @param text: text to translate
46
+ @return: translated text
47
+ """
48
+ prompt = f"Translate the text below into {self.target}.\n"
49
+ prompt += f'Text: "{text}"'
50
+
51
+ response = requests.post(
52
+ "https://api.openai.com/v1/chat/completions",
53
+ headers={"Authorization": f"Bearer {self.api_key}"},
54
+ json={
55
+ "model": self.model,
56
+ "messages": [{"role": "user", "content": prompt}],
57
+ },
58
+ timeout=60,
59
+ )
60
+ response.raise_for_status()
61
+ return response.json()["choices"][0]["message"]["content"]
62
+
63
+ def translate_file(self, path: str, **kwargs) -> str:
64
+ return self._translate_file(path, **kwargs)
65
+
66
+ def translate_batch(self, batch: List[str], **kwargs) -> List[str]:
67
+ """
68
+ @param batch: list of texts to translate
69
+ @return: list of translations
70
+ """
71
+ return self._translate_batch(batch, **kwargs)
deep_translator/cli.py ADDED
@@ -0,0 +1,102 @@
1
+ """Console script for deep_translator."""
2
+
3
+ __copyright__ = "Copyright (C) 2020 Nidhal Baccouri"
4
+
5
+ import argparse
6
+ from typing import Optional
7
+
8
+ from deep_translator.engines import __engines__
9
+
10
+
11
+ class CLI(object):
12
+ translators_dict = __engines__
13
+ translator = None
14
+
15
+ def __init__(self, custom_args: Optional[list] = None):
16
+ self.custom_args = custom_args
17
+ self.args = self.parse_args()
18
+ translator_class = self.translators_dict.get(
19
+ self.args.translator, None
20
+ )
21
+ if not translator_class:
22
+ raise Exception(
23
+ f"Translator {self.args.translator} is not supported."
24
+ f"Supported translators: {list(self.translators_dict.keys())}"
25
+ )
26
+ self.translator = translator_class(
27
+ source=self.args.source, target=self.args.target
28
+ )
29
+
30
+ def translate(self) -> None:
31
+ """
32
+ function used to provide translations from the parsed terminal arguments
33
+ @return: None
34
+ """
35
+ res = self.translator.translate(self.args.text)
36
+ print(f"Translation from {self.args.source} to {self.args.target}")
37
+ print("-" * 50)
38
+ print(f"Translation result: {res}")
39
+
40
+ def get_supported_languages(self) -> None:
41
+ """
42
+ function used to return the languages supported by the translator service
43
+ from the parsed terminal arguments
44
+ @return: None
45
+ """
46
+
47
+ translator_supported_languages = (
48
+ self.translator.get_supported_languages(as_dict=True)
49
+ )
50
+ print(f"Languages supported by '{self.args.translator}' are :\n")
51
+ print(translator_supported_languages)
52
+
53
+ def parse_args(self) -> argparse.Namespace:
54
+ """
55
+ function responsible for parsing terminal arguments and provide
56
+ them for further use in the translation process
57
+ """
58
+ parser = argparse.ArgumentParser(
59
+ add_help=True,
60
+ description="Official CLI for deep-translator",
61
+ usage="dt --help",
62
+ )
63
+
64
+ parser.add_argument(
65
+ "--translator",
66
+ "-trans",
67
+ default="google",
68
+ type=str,
69
+ help="name of the translator you want to use",
70
+ )
71
+ parser.add_argument(
72
+ "--source",
73
+ "-src",
74
+ default="auto",
75
+ type=str,
76
+ help="source language to translate from",
77
+ )
78
+ parser.add_argument(
79
+ "--target", "-tg", type=str, help="target language to translate to"
80
+ )
81
+ parser.add_argument(
82
+ "--text", "-txt", type=str, help="text you want to translate"
83
+ )
84
+ parser.add_argument(
85
+ "--languages",
86
+ "-lang",
87
+ action="store_true",
88
+ help="all the languages available with the translator"
89
+ "Run the command deep_translator -trans <translator service> -lang",
90
+ )
91
+ parsed_args = (
92
+ parser.parse_args(self.custom_args)
93
+ if self.custom_args
94
+ else parser.parse_args()
95
+ )
96
+ return parsed_args
97
+
98
+ def run(self) -> None:
99
+ if self.args.languages:
100
+ self.get_supported_languages()
101
+ else:
102
+ self.translate()