Auto Translate

BaseTranslate

class headless_cms.auto_translate.base_translate.BaseTranslate(instance: LocalizedModel)

Bases: object

Base class for translating localized fields in Django models.

This class provides the framework for translating localized fields in Django models, specifically for use with translation buttons in the Django admin interface.

can_batch_translate

Indicates whether the class supports batch translation.

Type:

bool

Parameters:

instance (LocalizedModel) – The Django model instance to be translated.

batch_translate(batches: dict[str, dict]) dict[str, dict]

Batch translate multiple fields to a single language.

This method should be overridden in subclasses to provide the actual batch translation logic.

Parameters:

batches (dict[str, dict]) – A dictionary where keys are language codes and values are dictionaries mapping field names to text to be translated.

Returns:

A dictionary where keys are language codes and values are

dictionaries mapping field names to translated text.

Return type:

dict[str, dict]

can_batch_translate = False
process(force=False)

Process the translation for the database object instance.

This method translates all localized fields of the instance.

Parameters:

force (bool) – Whether to force retranslation for all localized fields (even if the fields are already translated).

translate(language: str, text: str)

Translate text to a single language.

This method should be overridden in subclasses to provide the actual translation logic.

Parameters:
  • language (str) – The target language code.

  • text (str) – The text to be translated.

Returns:

The translated text.

Return type:

str

OpenAITranslate

class headless_cms.auto_translate.openai_translate.OpenAITranslate(instance: LocalizedModel)

Bases: BaseTranslate

Translation class using OpenAI’s chat model.

This class extends the BaseTranslate class to provide translation functionality using OpenAI’s chat model. It supports both single and batch translations.

batch_translate(batches: dict[str, dict])

Batch translate multiple fields to multiple languages using OpenAI’s chat model.

Parameters:

batches (dict[str, dict]) – A dictionary where keys are language codes and values are dictionaries mapping field names to text to be translated.

Returns:

A dictionary where keys are language codes and values are

dictionaries mapping field names to translated text.

Return type:

dict[str, dict]

can_batch_translate = True
chat_gpt_translate(prompt)
translate(language, text)

Translate text to a single language using OpenAI’s chat model.

Parameters:
  • language (str) – The target language code.

  • text (str) – The text to be translated.

Returns:

The translated text.

Return type:

str