tomaseo2022 commited on
Commit
d5215b8
ยท
1 Parent(s): 206ce69

Upload 2 files

Browse files
Files changed (2) hide show
  1. __init__.py +7 -0
  2. client.py +268 -0
__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Free Google Translate API for Python. Translates totally free of charge."""
2
+ __all__ = 'Translator',
3
+ __version__ = '3.0.0'
4
+
5
+
6
+ from googletrans.client import Translator
7
+ from googletrans.constants import LANGCODES, LANGUAGES # noqa
client.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ A Translation module.
4
+
5
+ You can translate text using this module.
6
+ """
7
+ import random
8
+ import typing
9
+
10
+ import httpcore
11
+ import httpx
12
+ from httpx import Timeout
13
+
14
+ from googletrans import urls, utils
15
+ from googletrans.gtoken import TokenAcquirer
16
+ from googletrans.constants import (
17
+ DEFAULT_USER_AGENT, LANGCODES, LANGUAGES, SPECIAL_CASES,
18
+ DEFAULT_RAISE_EXCEPTION, DUMMY_DATA
19
+ )
20
+ from googletrans.models import Translated, Detected
21
+
22
+ EXCLUDES = ('en', 'ca', 'fr')
23
+
24
+
25
+ class Translator:
26
+ """Google Translate ajax API implementation class
27
+
28
+ You have to create an instance of Translator to use this API
29
+
30
+ :param service_urls: google translate url list. URLs will be used randomly.
31
+ For example ``['translate.google.com', 'translate.google.co.kr']``
32
+ :type service_urls: a sequence of strings
33
+
34
+ :param user_agent: the User-Agent header to send when making requests.
35
+ :type user_agent: :class:`str`
36
+
37
+ :param proxies: proxies configuration.
38
+ Dictionary mapping protocol or protocol and host to the URL of the proxy
39
+ For example ``{'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}``
40
+ :type proxies: dictionary
41
+
42
+ :param timeout: Definition of timeout for httpx library.
43
+ Will be used for every request.
44
+ :type timeout: number or a double of numbers
45
+ ||||||| constructed merge base
46
+ :param proxies: proxies configuration.
47
+ Dictionary mapping protocol or protocol and host to the URL of the proxy
48
+ For example ``{'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}``
49
+ :param raise_exception: if `True` then raise exception if smth will go wrong
50
+ :type raise_exception: boolean
51
+ """
52
+
53
+ def __init__(self, service_urls=None, user_agent=DEFAULT_USER_AGENT,
54
+ raise_exception=DEFAULT_RAISE_EXCEPTION,
55
+ proxies: typing.Dict[str, httpcore.AsyncHTTPProxy] = None, timeout: Timeout = None):
56
+
57
+ self.client = httpx.Client()
58
+ if proxies is not None: # pragma: nocover
59
+ self.client.proxies = proxies
60
+
61
+ self.client.headers.update({
62
+ 'User-Agent': user_agent,
63
+ })
64
+
65
+ if timeout is not None:
66
+ self.client.timeout = timeout
67
+
68
+ self.service_urls = service_urls or ['translate.google.com']
69
+ self.token_acquirer = TokenAcquirer(client=self.client, host=self.service_urls[0])
70
+ self.raise_exception = raise_exception
71
+
72
+ def _pick_service_url(self):
73
+ if len(self.service_urls) == 1:
74
+ return self.service_urls[0]
75
+ return random.choice(self.service_urls)
76
+
77
+ def _translate(self, text, dest, src, override):
78
+ token = self.token_acquirer.do(text)
79
+ params = utils.build_params(query=text, src=src, dest=dest,
80
+ token=token, override=override)
81
+
82
+ url = urls.TRANSLATE.format(host=self._pick_service_url())
83
+ r = self.client.get(url, params=params)
84
+
85
+ if r.status_code == 200:
86
+ data = utils.format_json(r.text)
87
+ return data
88
+ else:
89
+ if self.raise_exception:
90
+ raise Exception('Unexpected status code "{}" from {}'.format(r.status_code, self.service_urls))
91
+ DUMMY_DATA[0][0][0] = text
92
+ return DUMMY_DATA
93
+
94
+ def _parse_extra_data(self, data):
95
+ response_parts_name_mapping = {
96
+ 0: 'translation',
97
+ 1: 'all-translations',
98
+ 2: 'original-language',
99
+ 5: 'possible-translations',
100
+ 6: 'confidence',
101
+ 7: 'possible-mistakes',
102
+ 8: 'language',
103
+ 11: 'synonyms',
104
+ 12: 'definitions',
105
+ 13: 'examples',
106
+ 14: 'see-also',
107
+ }
108
+
109
+ extra = {}
110
+
111
+ for index, category in response_parts_name_mapping.items():
112
+ extra[category] = data[index] if (index < len(data) and data[index]) else None
113
+
114
+ return extra
115
+
116
+ def translate(self, text, dest='en', src='auto', **kwargs):
117
+ """Translate text from source language to destination language
118
+
119
+ :param text: The source text(s) to be translated. Batch translation is supported via sequence input.
120
+ :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, generator)
121
+
122
+ :param dest: The language to translate the source text into.
123
+ The value should be one of the language codes listed in :const:`googletrans.LANGUAGES`
124
+ or one of the language names listed in :const:`googletrans.LANGCODES`.
125
+ :param dest: :class:`str`; :class:`unicode`
126
+
127
+ :param src: The language of the source text.
128
+ The value should be one of the language codes listed in :const:`googletrans.LANGUAGES`
129
+ or one of the language names listed in :const:`googletrans.LANGCODES`.
130
+ If a language is not specified,
131
+ the system will attempt to identify the source language automatically.
132
+ :param src: :class:`str`; :class:`unicode`
133
+
134
+ :rtype: Translated
135
+ :rtype: :class:`list` (when a list is passed)
136
+
137
+ Basic usage:
138
+ >>> from googletrans import Translator
139
+ >>> translator = Translator()
140
+ >>> translator.translate('์•ˆ๋…•ํ•˜์„ธ์š”.')
141
+ <Translated src=ko dest=en text=Good evening. pronunciation=Good evening.>
142
+ >>> translator.translate('์•ˆ๋…•ํ•˜์„ธ์š”.', dest='ja')
143
+ <Translated src=ko dest=ja text=ใ“ใ‚“ใซใกใฏใ€‚ pronunciation=Kon'nichiwa.>
144
+ >>> translator.translate('veritas lux mea', src='la')
145
+ <Translated src=la dest=en text=The truth is my light pronunciation=The truth is my light>
146
+
147
+ Advanced usage:
148
+ >>> translations = translator.translate(['The quick brown fox', 'jumps over', 'the lazy dog'], dest='ko')
149
+ >>> for translation in translations:
150
+ ... print(translation.origin, ' -> ', translation.text)
151
+ The quick brown fox -> ๋น ๋ฅธ ๊ฐˆ์ƒ‰ ์—ฌ์šฐ
152
+ jumps over -> ์ด์ƒ ์ ํ”„
153
+ the lazy dog -> ๊ฒŒ์œผ๋ฅธ ๊ฐœ
154
+ """
155
+ dest = dest.lower().split('_', 1)[0]
156
+ src = src.lower().split('_', 1)[0]
157
+
158
+ if src != 'auto' and src not in LANGUAGES:
159
+ if src in SPECIAL_CASES:
160
+ src = SPECIAL_CASES[src]
161
+ elif src in LANGCODES:
162
+ src = LANGCODES[src]
163
+ else:
164
+ raise ValueError('invalid source language')
165
+
166
+ if dest not in LANGUAGES:
167
+ if dest in SPECIAL_CASES:
168
+ dest = SPECIAL_CASES[dest]
169
+ elif dest in LANGCODES:
170
+ dest = LANGCODES[dest]
171
+ else:
172
+ raise ValueError('invalid destination language')
173
+
174
+ if isinstance(text, list):
175
+ result = []
176
+ for item in text:
177
+ translated = self.translate(item, dest=dest, src=src, **kwargs)
178
+ result.append(translated)
179
+ return result
180
+
181
+ origin = text
182
+ data = self._translate(text, dest, src, kwargs)
183
+
184
+ # this code will be updated when the format is changed.
185
+ translated = ''.join([d[0] if d[0] else '' for d in data[0]])
186
+
187
+ extra_data = self._parse_extra_data(data)
188
+
189
+ # actual source language that will be recognized by Google Translator when the
190
+ # src passed is equal to auto.
191
+ try:
192
+ src = data[2]
193
+ except Exception: # pragma: nocover
194
+ pass
195
+
196
+ pron = origin
197
+ try:
198
+ pron = data[0][1][-2]
199
+ except Exception: # pragma: nocover
200
+ pass
201
+
202
+ if pron is None:
203
+ try:
204
+ pron = data[0][1][2]
205
+ except: # pragma: nocover
206
+ pass
207
+
208
+ if dest in EXCLUDES and pron == origin:
209
+ pron = translated
210
+
211
+ # put final values into a new Translated object
212
+ result = Translated(src=src, dest=dest, origin=origin,
213
+ text=translated, pronunciation=pron, extra_data=extra_data)
214
+
215
+ return result
216
+
217
+ def detect(self, text, **kwargs):
218
+ """Detect language of the input text
219
+
220
+ :param text: The source text(s) whose language you want to identify.
221
+ Batch detection is supported via sequence input.
222
+ :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, generator)
223
+
224
+ :rtype: Detected
225
+ :rtype: :class:`list` (when a list is passed)
226
+
227
+ Basic usage:
228
+ >>> from googletrans import Translator
229
+ >>> translator = Translator()
230
+ >>> translator.detect('์ด ๋ฌธ์žฅ์€ ํ•œ๊ธ€๋กœ ์“ฐ์—ฌ์กŒ์Šต๋‹ˆ๋‹ค.')
231
+ <Detected lang=ko confidence=0.27041003>
232
+ >>> translator.detect('ใ“ใฎๆ–‡็ซ ใฏๆ—ฅๆœฌ่ชžใงๆ›ธใ‹ใ‚Œใพใ—ใŸใ€‚')
233
+ <Detected lang=ja confidence=0.64889508>
234
+ >>> translator.detect('This sentence is written in English.')
235
+ <Detected lang=en confidence=0.22348526>
236
+ >>> translator.detect('Tiu frazo estas skribita en Esperanto.')
237
+ <Detected lang=eo confidence=0.10538048>
238
+
239
+ Advanced usage:
240
+ >>> langs = translator.detect(['ํ•œ๊ตญ์–ด', 'ๆ—ฅๆœฌ่ชž', 'English', 'le franรงais'])
241
+ >>> for lang in langs:
242
+ ... print(lang.lang, lang.confidence)
243
+ ko 1
244
+ ja 0.92929292
245
+ en 0.96954316
246
+ fr 0.043500196
247
+ """
248
+ if isinstance(text, list):
249
+ result = []
250
+ for item in text:
251
+ lang = self.detect(item)
252
+ result.append(lang)
253
+ return result
254
+
255
+ data = self._translate(text, 'en', 'auto', kwargs)
256
+
257
+ # actual source language that will be recognized by Google Translator when the
258
+ # src passed is equal to auto.
259
+ src = ''
260
+ confidence = 0.0
261
+ try:
262
+ src = ''.join(data[8][0])
263
+ confidence = data[8][-2][0]
264
+ except Exception: # pragma: nocover
265
+ pass
266
+ result = Detected(lang=src, confidence=confidence)
267
+
268
+ return result