import httpx from ..config import settings DEEPL_API_URL = "https://api-free.deepl.com/v2/translate" DEEPL_LANGUAGE_CODES = { "en": "EN-GB", "fr": "FR", "es": "ES", "it": "IT", "de": "DE", } async def translate(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 {settings.deepl_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"]