39 lines
1.1 KiB
Python
39 lines
1.1 KiB
Python
|
|
import httpx
|
||
|
|
|
||
|
|
DEEPL_API_URL = "https://api-free.deepl.com/v2/translate"
|
||
|
|
|
||
|
|
DEEPL_LANGUAGE_CODES = {
|
||
|
|
"en": "EN-GB",
|
||
|
|
"fr": "FR",
|
||
|
|
"es": "ES",
|
||
|
|
"it": "IT",
|
||
|
|
"de": "DE",
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
class DeepLClient():
|
||
|
|
def __init__(self, api_key: str):
|
||
|
|
self._api_key = api_key
|
||
|
|
|
||
|
|
def can_translate_to(self, the_language: str) -> bool:
|
||
|
|
return the_language in DEEPL_LANGUAGE_CODES
|
||
|
|
|
||
|
|
async def translate(self, text: str, to_language: str, context: str | None = None) -> str:
|
||
|
|
target_lang_code = DEEPL_LANGUAGE_CODES[to_language]
|
||
|
|
async with httpx.AsyncClient() as client:
|
||
|
|
response = await client.post(
|
||
|
|
DEEPL_API_URL,
|
||
|
|
headers={
|
||
|
|
"Authorization": f"DeepL-Auth-Key {self._api_key}",
|
||
|
|
"Content-Type": "application/json",
|
||
|
|
},
|
||
|
|
json={
|
||
|
|
"text": [text],
|
||
|
|
"target_lang": target_lang_code,
|
||
|
|
"context": context or None,
|
||
|
|
},
|
||
|
|
)
|
||
|
|
response.raise_for_status()
|
||
|
|
data = response.json()
|
||
|
|
return data["translations"][0]["text"]
|