Skip to content

Commit 15ecbc0

Browse files
committed
fix: support async context, fix list ops, and fix pronunciation extraction
1 parent a0eb858 commit 15ecbc0

File tree

1 file changed

+39
-17
lines changed

1 file changed

+39
-17
lines changed

googletrans/client.py

+39-17
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
You can translate text using this module.
55
"""
66

7+
import asyncio
78
import random
89
import re
910
import typing
@@ -64,6 +65,7 @@ def __init__(
6465
proxies: typing.Optional[ProxiesTypes] = None,
6566
timeout: typing.Optional[Timeout] = None,
6667
http2: bool = True,
68+
list_operation_max_concurrency: int = 2,
6769
):
6870
self.client = httpx.AsyncClient(
6971
http2=http2,
@@ -86,7 +88,7 @@ def __init__(
8688
# default way of working: use the defined values from user app
8789
self.service_urls = service_urls
8890
self.client_type = "webapp"
89-
self.tok1en_acquirer = TokenAcquirer(
91+
self.token_acquirer = TokenAcquirer(
9092
client=self.client, host=self.service_urls[0]
9193
)
9294

@@ -99,12 +101,19 @@ def __init__(
99101
break
100102

101103
self.raise_exception = raise_exception
104+
self.list_operation_max_concurrency = list_operation_max_concurrency
102105

103106
def _pick_service_url(self) -> str:
104107
if len(self.service_urls) == 1:
105108
return self.service_urls[0]
106109
return random.choice(self.service_urls)
107110

111+
async def __aenter__(self):
112+
return self
113+
114+
async def __aexit__(self, exc_type, exc_val, exc_tb):
115+
await self.client.aclose()
116+
108117
async def _translate(
109118
self, text: str, dest: str, src: str, override: typing.Dict[str, typing.Any]
110119
) -> typing.Tuple[typing.List[typing.Any], Response]:
@@ -266,10 +275,17 @@ async def translate(
266275
raise ValueError("invalid destination language")
267276

268277
if isinstance(text, list):
269-
result = []
270-
for item in text:
271-
translated = await self.translate(item, dest=dest, src=src, **kwargs)
272-
result.append(translated)
278+
concurrency_limit = kwargs.pop(
279+
"list_operation_max_concurrency", self.list_operation_max_concurrency
280+
)
281+
semaphore = asyncio.Semaphore(concurrency_limit)
282+
283+
async def translate_with_semaphore(item):
284+
async with semaphore:
285+
return await self.translate(item, dest=dest, src=src, **kwargs)
286+
287+
tasks = [translate_with_semaphore(item) for item in text]
288+
result = await asyncio.gather(*tasks)
273289
return result
274290

275291
origin = text
@@ -289,17 +305,16 @@ async def translate(
289305

290306
pron = origin
291307
try:
292-
# Get pronunciation from [0][1][3] which contains romanized pronunciation
293-
if data[0][1] and len(data[0][1]) > 3:
294-
pron = data[0][1][3]
295-
# Fallback to previous methods if not found
296-
elif data[0][1] and len(data[0][1]) > 2:
297-
pron = data[0][1][2]
298-
elif data[0][1] and len(data[0][1]) >= 2:
299-
pron = data[0][1][-2]
308+
pron = data[0][1][-2]
300309
except Exception: # pragma: nocover
301310
pass
302311

312+
if pron is None:
313+
try:
314+
pron = data[0][1][2]
315+
except: # pragma: nocover # noqa: E722
316+
pass
317+
303318
if dest in EXCLUDES and pron == origin:
304319
pron = translated
305320

@@ -358,10 +373,17 @@ async def detect(
358373
fr 0.043500196
359374
"""
360375
if isinstance(text, list):
361-
result = []
362-
for item in text:
363-
lang = self.detect(item)
364-
result.append(lang)
376+
concurrency_limit = kwargs.pop(
377+
"list_operation_max_concurrency", self.list_operation_max_concurrency
378+
)
379+
semaphore = asyncio.Semaphore(concurrency_limit)
380+
381+
async def detect_with_semaphore(item):
382+
async with semaphore:
383+
return await self.detect(item, **kwargs)
384+
385+
tasks = [detect_with_semaphore(item) for item in text]
386+
result = await asyncio.gather(*tasks)
365387
return result
366388

367389
data, response = await self._translate(text, "en", "auto", kwargs)

0 commit comments

Comments
 (0)