4
4
You can translate text using this module.
5
5
"""
6
6
7
+ import asyncio
7
8
import random
8
9
import re
9
10
import typing
@@ -64,6 +65,7 @@ def __init__(
64
65
proxies : typing .Optional [ProxiesTypes ] = None ,
65
66
timeout : typing .Optional [Timeout ] = None ,
66
67
http2 : bool = True ,
68
+ list_operation_max_concurrency : int = 2 ,
67
69
):
68
70
self .client = httpx .AsyncClient (
69
71
http2 = http2 ,
@@ -86,7 +88,7 @@ def __init__(
86
88
# default way of working: use the defined values from user app
87
89
self .service_urls = service_urls
88
90
self .client_type = "webapp"
89
- self .tok1en_acquirer = TokenAcquirer (
91
+ self .token_acquirer = TokenAcquirer (
90
92
client = self .client , host = self .service_urls [0 ]
91
93
)
92
94
@@ -99,12 +101,19 @@ def __init__(
99
101
break
100
102
101
103
self .raise_exception = raise_exception
104
+ self .list_operation_max_concurrency = list_operation_max_concurrency
102
105
103
106
def _pick_service_url (self ) -> str :
104
107
if len (self .service_urls ) == 1 :
105
108
return self .service_urls [0 ]
106
109
return random .choice (self .service_urls )
107
110
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
+
108
117
async def _translate (
109
118
self , text : str , dest : str , src : str , override : typing .Dict [str , typing .Any ]
110
119
) -> typing .Tuple [typing .List [typing .Any ], Response ]:
@@ -266,10 +275,17 @@ async def translate(
266
275
raise ValueError ("invalid destination language" )
267
276
268
277
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 )
273
289
return result
274
290
275
291
origin = text
@@ -289,17 +305,16 @@ async def translate(
289
305
290
306
pron = origin
291
307
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 ]
300
309
except Exception : # pragma: nocover
301
310
pass
302
311
312
+ if pron is None :
313
+ try :
314
+ pron = data [0 ][1 ][2 ]
315
+ except : # pragma: nocover # noqa: E722
316
+ pass
317
+
303
318
if dest in EXCLUDES and pron == origin :
304
319
pron = translated
305
320
@@ -358,10 +373,17 @@ async def detect(
358
373
fr 0.043500196
359
374
"""
360
375
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 )
365
387
return result
366
388
367
389
data , response = await self ._translate (text , "en" , "auto" , kwargs )
0 commit comments