Skip to content

Backends API

django_traduire.backends.base.BaseBackend

Bases: ABC

Abstract base class for translation backends.

Subclasses must implement translate_batch.

Source code in src/django_traduire/backends/base.py
class BaseBackend(ABC):
    """Abstract base class for translation backends.

    Subclasses must implement ``translate_batch``.
    """

    @abstractmethod
    def translate_batch(self, texts, source, target):
        """Translate a list of texts from source to target language.

        Args:
            texts: List of strings to translate.
            source: Source language code (e.g. ``"fr"``).
            target: Target language code (e.g. ``"de"``).

        Returns:
            list[str]: Translated texts, same length as input.
        """

    def translate(self, text, source, target):
        """Translate a single string. Convenience wrapper around ``translate_batch``."""
        results = self.translate_batch([text], source=source, target=target)
        return results[0] if results else ""

translate_batch(texts, source, target) abstractmethod

Translate a list of texts from source to target language.

Parameters:

Name Type Description Default
texts

List of strings to translate.

required
source

Source language code (e.g. "fr").

required
target

Target language code (e.g. "de").

required

Returns:

Type Description

list[str]: Translated texts, same length as input.

Source code in src/django_traduire/backends/base.py
@abstractmethod
def translate_batch(self, texts, source, target):
    """Translate a list of texts from source to target language.

    Args:
        texts: List of strings to translate.
        source: Source language code (e.g. ``"fr"``).
        target: Target language code (e.g. ``"de"``).

    Returns:
        list[str]: Translated texts, same length as input.
    """

translate(text, source, target)

Translate a single string. Convenience wrapper around translate_batch.

Source code in src/django_traduire/backends/base.py
def translate(self, text, source, target):
    """Translate a single string. Convenience wrapper around ``translate_batch``."""
    results = self.translate_batch([text], source=source, target=target)
    return results[0] if results else ""

django_traduire.backends.deepl.DeepLBackend

Bases: BaseBackend

Translation backend using the DeepL API.

Parameters:

Name Type Description Default
auth_key

Your DeepL API authentication key.

required
**kwargs

Additional options passed to deepl.Translator.

{}
Source code in src/django_traduire/backends/deepl.py
class DeepLBackend(BaseBackend):
    """Translation backend using the DeepL API.

    Args:
        auth_key: Your DeepL API authentication key.
        **kwargs: Additional options passed to ``deepl.Translator``.
    """

    def __init__(self, auth_key, **kwargs):
        try:
            import deepl
        except ImportError:
            raise ImportError(
                "The deepl package is required for this backend. "
                "Install it with: pip install django-traduire[deepl]"
            )
        self.client = deepl.Translator(auth_key, **kwargs)

    def translate_batch(self, texts, source, target):
        src_lang = source.upper()
        tgt_lang = DEEPL_LANG_MAP.get(target, target.upper())
        results = self.client.translate_text(texts, source_lang=src_lang, target_lang=tgt_lang)
        return [r.text for r in results]

django_traduire.backends.google.GoogleBackend

Bases: BaseBackend

Translation backend using Google Cloud Translation API v3.

Parameters:

Name Type Description Default
project_id

Your Google Cloud project ID.

required
location

API location (default "global").

'global'
**kwargs

Additional options.

{}
Source code in src/django_traduire/backends/google.py
class GoogleBackend(BaseBackend):
    """Translation backend using Google Cloud Translation API v3.

    Args:
        project_id: Your Google Cloud project ID.
        location: API location (default ``"global"``).
        **kwargs: Additional options.
    """

    def __init__(self, project_id, location="global", **kwargs):
        try:
            from google.cloud import translate_v3 as translate
        except ImportError:
            raise ImportError(
                "The google-cloud-translate package is required for this backend. "
                "Install it with: pip install django-traduire[google]"
            )
        self.client = translate.TranslationServiceClient(**kwargs)
        self.parent = f"projects/{project_id}/locations/{location}"

    def translate_batch(self, texts, source, target):
        from google.cloud import translate_v3 as translate

        response = self.client.translate_text(
            request=translate.TranslateTextRequest(
                parent=self.parent,
                contents=texts,
                source_language_code=source,
                target_language_code=target,
                mime_type="text/plain",
            )
        )
        return [t.translated_text for t in response.translations]

django_traduire.backends.openai.OpenAIBackend

Bases: BaseBackend

Translation backend using the OpenAI API.

Works with any OpenAI-compatible API (OpenAI, Azure, local models).

Parameters:

Name Type Description Default
api_key

Your OpenAI API key.

None
model

Model to use (default "gpt-4o-mini").

'gpt-4o-mini'
**kwargs

Additional options passed to OpenAI().

{}
Source code in src/django_traduire/backends/openai.py
class OpenAIBackend(BaseBackend):
    """Translation backend using the OpenAI API.

    Works with any OpenAI-compatible API (OpenAI, Azure, local models).

    Args:
        api_key: Your OpenAI API key.
        model: Model to use (default ``"gpt-4o-mini"``).
        **kwargs: Additional options passed to ``OpenAI()``.
    """

    def __init__(self, api_key=None, model="gpt-4o-mini", **kwargs):
        try:
            import openai
        except ImportError:
            raise ImportError(
                "The openai package is required for this backend. "
                "Install it with: pip install django-traduire[openai]"
            )
        self.client = openai.OpenAI(api_key=api_key, **kwargs)
        self.model = model

    def translate_batch(self, texts, source, target):
        user_msg = (
            f"Translate the following texts from {source} to {target}.\n"
            f"Input: {json.dumps(texts, ensure_ascii=False)}\n"
            f"Return ONLY a JSON array of {len(texts)} translated strings."
        )
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": user_msg},
            ],
            temperature=0.1,
        )
        content = response.choices[0].message.content.strip()
        # Strip markdown code fences if present
        if content.startswith("```"):
            content = content.split("\n", 1)[1].rsplit("```", 1)[0].strip()
        return json.loads(content)