Skip to content

Commit 1ddcb10

Browse files
committed
refactor
1 parent 685fcaa commit 1ddcb10

3 files changed

Lines changed: 154 additions & 163 deletions

File tree

deepl/deepl.py

Lines changed: 13 additions & 157 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,16 @@
44
import contextlib
55
import os
66
from collections.abc import Coroutine
7-
from functools import partial
8-
from typing import Any, ClassVar
7+
from typing import Any
98
from urllib.parse import quote
109

1110
from install_playwright import install
1211
from playwright._impl._errors import Error as PlaywrightError
1312
from playwright.async_api import async_playwright
1413
from playwright.async_api._generated import Browser, Playwright
1514

15+
from deepl.languages import FR_LANGS, TO_LANGS
16+
1617

1718
class DeepLCLIError(Exception):
1819
"""Generic error for DeepLCLI."""
@@ -41,129 +42,6 @@ class DeepLCLI:
4142
```
4243
"""
4344

44-
fr_langs: ClassVar[set[str]] = {
45-
# "auto",
46-
"ace",
47-
"af",
48-
"an",
49-
"ar",
50-
"as",
51-
"ay",
52-
"az",
53-
"ba",
54-
"be",
55-
"bg",
56-
"bho",
57-
"bn",
58-
"br",
59-
"bs",
60-
"ca",
61-
"ceb",
62-
"ckb",
63-
"cs",
64-
"cy",
65-
"da",
66-
"de",
67-
"el",
68-
"en",
69-
"eo",
70-
"es",
71-
"et",
72-
"eu",
73-
"fa",
74-
"fi",
75-
"fr",
76-
"ga",
77-
"gl",
78-
"gn",
79-
"gom",
80-
"gu",
81-
"ha",
82-
"he",
83-
"hi",
84-
"hr",
85-
"ht",
86-
"hu",
87-
"hy",
88-
"id",
89-
"ig",
90-
"is",
91-
"it",
92-
"ja",
93-
"jv",
94-
"ka",
95-
"kk",
96-
"kmr",
97-
"ko",
98-
"ky",
99-
"la",
100-
"lb",
101-
"lmo",
102-
"ln",
103-
"lt",
104-
"lv",
105-
"mai",
106-
"mg",
107-
"mi",
108-
"mk",
109-
"ml",
110-
"mn",
111-
"mr",
112-
"ms",
113-
"mt",
114-
"my",
115-
"nb",
116-
"ne",
117-
"nl",
118-
"oc",
119-
"om",
120-
"pa",
121-
"pag",
122-
"pam",
123-
"pl",
124-
"prs",
125-
"ps",
126-
"pt",
127-
"qu",
128-
"ro",
129-
"ru",
130-
"sa",
131-
"scn",
132-
"sk",
133-
"sl",
134-
"sq",
135-
"sr",
136-
"st",
137-
"su",
138-
"sv",
139-
"sw",
140-
"ta",
141-
"te",
142-
"tg",
143-
"tk",
144-
"tl",
145-
"tn",
146-
"tr",
147-
"ts",
148-
"tt",
149-
"uk",
150-
"ur",
151-
"uz",
152-
"vi",
153-
"wo",
154-
"xh",
155-
"yi",
156-
"yue",
157-
"zh",
158-
"zu",
159-
}
160-
to_langs = fr_langs | {"zh-hans", "zh-hant", "en-us", "en-gb", "pt-pt", "pt-br", "es-419"} - {
161-
"auto",
162-
"zh",
163-
"en",
164-
"pt",
165-
}
166-
16745
def __init__(
16846
self,
16947
fr_lang: str,
@@ -183,13 +61,13 @@ def __init__(
18361
Raises:
18462
DeepLCLIError: If the language is not valid.
18563
"""
186-
if fr_lang not in self.fr_langs:
64+
if fr_lang not in FR_LANGS:
18765
raise DeepLCLIError(
188-
f"{fr_lang!r} is not valid language. Valid language:\n" + repr(self.fr_langs),
66+
f"{fr_lang!r} is not valid language. Valid language:\n" + repr(FR_LANGS),
18967
)
190-
if to_lang not in self.to_langs:
68+
if to_lang not in TO_LANGS:
19169
raise DeepLCLIError(
192-
f"{to_lang!r} is not valid language. Valid language:\n" + repr(self.to_langs),
70+
f"{to_lang!r} is not valid language. Valid language:\n" + repr(TO_LANGS),
19371
)
19472

19573
self.fr_lang = fr_lang
@@ -215,7 +93,6 @@ def translate(self, script: str) -> str:
21593
"""
21694
script = self.__sanitize_script(script)
21795

218-
# run in the current thread
21996
return asyncio.run(self.__translate(script))
22097

22198
def translate_async(self, script: str) -> Coroutine[Any, Any, str]:
@@ -235,26 +112,10 @@ def translate_async(self, script: str) -> Coroutine[Any, Any, str]:
235112

236113
return self.__translate(script)
237114

238-
async def __translate(self, script: str) -> str: # noqa: C901, PLR0915
115+
async def __translate(self, script: str) -> str: # noqa: PLR0915
239116
"""Throw a request."""
240117
async with async_playwright() as p:
241-
# Dry run
242-
try:
243-
browser = await self.__get_browser(p)
244-
except PlaywrightError as e:
245-
if "playwright install" in e.message:
246-
await asyncio.get_event_loop().run_in_executor(
247-
None,
248-
partial(install, p.chromium, with_deps=True),
249-
)
250-
await asyncio.get_event_loop().run_in_executor(
251-
None,
252-
install,
253-
p.chromium,
254-
)
255-
browser = await self.__get_browser(p)
256-
else:
257-
raise
118+
browser = await self.__get_browser(p)
258119

259120
page = await browser.new_page()
260121
page.set_default_timeout(self.timeout)
@@ -293,7 +154,7 @@ async def __translate(self, script: str) -> str: # noqa: C901, PLR0915
293154
""",
294155
)
295156

296-
# try to close the extension banner
157+
# close the extension banner
297158
with contextlib.suppress(PlaywrightError):
298159
await page.evaluate(
299160
"""
@@ -303,7 +164,6 @@ async def __translate(self, script: str) -> str: # noqa: C901, PLR0915
303164
""",
304165
)
305166

306-
# select input / output language
307167
await page.locator(
308168
"button[data-testid=translator-source-lang-btn]",
309169
).dispatch_event("click")
@@ -324,13 +184,11 @@ async def __translate(self, script: str) -> str: # noqa: C901, PLR0915
324184
)
325185
.first.dispatch_event("click")
326186
)
327-
# fill in the form of translating script
328187
await page.fill(
329188
"div[aria-labelledby=translation-source-heading]",
330189
script,
331190
)
332191

333-
# Wait for translation to complete (perhaps partially)
334192
try:
335193
await page.wait_for_function(
336194
"""
@@ -343,7 +201,6 @@ async def __translate(self, script: str) -> str: # noqa: C901, PLR0915
343201
msg = f"Time limit exceeded. ({self.timeout} ms)"
344202
raise DeepLCLIPageLoadError(msg) from e
345203

346-
# Get the number of lines in the translated text field
347204
try:
348205
line_count = await page.evaluate(
349206
"""
@@ -356,8 +213,6 @@ async def __translate(self, script: str) -> str: # noqa: C901, PLR0915
356213
msg = "Unable to evaluate line count of the translation"
357214
raise DeepLCLIPageLoadError(msg) from e
358215

359-
# Since the site may not output all lines at once, we wait until each line is finished
360-
# and then add it to the list of translated lines
361216
translated_lines = []
362217
for line_index in range(line_count):
363218
try:
@@ -388,7 +243,6 @@ async def __translate(self, script: str) -> str: # noqa: C901, PLR0915
388243
msg = f"Unable get translated text for line {line_index}"
389244
raise DeepLCLIPageLoadError(msg) from e
390245

391-
# Get information
392246
input_textbox = page.get_by_role("region", name="Source text").locator(
393247
"d-textarea",
394248
)
@@ -426,8 +280,10 @@ def __sanitize_script(self, script: str) -> str:
426280

427281
async def __get_browser(self, p: Playwright) -> Browser:
428282
"""Launch browser executable and get playwright browser object."""
283+
install(p.chromium, with_deps=True)
284+
429285
return await p.chromium.launch(
430-
headless=False,
286+
headless=True,
431287
args=[
432288
"--no-sandbox",
433289
"--single-process" if os.name != "nt" else "",

0 commit comments

Comments
 (0)