Skip to content

translation

English translation with source-language and engine metadata.

TranslationResult dataclass

TranslationResult(original_text: str, text: str, source_language: str, engine: str | None, language_detection: LanguageDetection | None = None)

Prepared English text and its translation provenance.

Attributes:

Name Type Description
original_text str

Original input body.

text str

English body for downstream analysis.

source_language str

Normalized source-language code.

engine str | None

Translation engine citation, or None for English input.

language_detection LanguageDetection | None

Detection or verification evidence, when collected.

translated property

translated: bool

Whether the source language required translation into English.

Translator

Bases: Protocol

English translation backend exposing engine and translate(text, source_language).

TranslationUnavailableError

Bases: RuntimeError

Optional dependencies or local model resources are unavailable.

M2M100Translator

M2M100Translator(tokenizer, model, *, engine, chunk_tokens=384, batch_size=4, num_beams=4, max_new_tokens=768, min_new_tokens=1, cache_identity=None, translation_profile=None)

Local M2M100 translation with sentence chunking and batched inference.

Load with from_model and reuse one instance for sequential translation calls.

Attributes:

Name Type Description
engine

Public model citation used in translation metadata.

cache_identity

Full inference configuration, or the supplied engine for direct construction without an explicit cache identity.

translation_profile

JSON-serializable load-time provenance from the factory, or an optional caller-supplied profile for direct construction.

Source code in src/gdelt_regkg/fields/translation.py
def __init__(
    self,
    tokenizer,
    model,
    *,
    engine,
    chunk_tokens=384,
    batch_size=4,
    num_beams=4,
    max_new_tokens=768,
    min_new_tokens=1,
    cache_identity=None,
    translation_profile=None,
):
    _validate_translation_options(
        chunk_tokens, batch_size, num_beams, max_new_tokens, min_new_tokens
    )
    self.tokenizer, self.model, self.engine = tokenizer, model, engine
    if cache_identity is not None and (
        not isinstance(cache_identity, str) or not cache_identity.strip()
    ):
        raise ValueError("cache_identity must be a nonempty string")
    self.cache_identity = engine if cache_identity is None else cache_identity
    self.translation_profile = translation_profile
    self.chunk_tokens = chunk_tokens
    self.batch_size, self.num_beams = batch_size, num_beams
    self.max_new_tokens, self.min_new_tokens = max_new_tokens, min_new_tokens

from_model classmethod

from_model(model='facebook/m2m100_418M', *, device='cpu', allow_download=False, revision=None, batch_size=4, num_beams=4, chunk_tokens=384, max_new_tokens=768, min_new_tokens=1, cache_dir=None, token=None) -> M2M100Translator

Load a reusable M2M100 model and tokenizer.

Parameters:

Name Type Description Default
model str

Model identifier or local model directory.

'facebook/m2m100_418M'
device str

PyTorch device, such as cpu or cuda:0.

'cpu'
allow_download bool

Allow model downloads when local files are missing.

False
revision str | None

Optional model revision.

None
batch_size int

Positive number of text chunks per inference batch.

4
num_beams int

Positive beam count for generation.

4
chunk_tokens int

Source tokens per chunk, between 1 and 512.

384
max_new_tokens int

Positive output-token limit per chunk.

768
min_new_tokens int

Minimum output tokens per chunk, between zero and max_new_tokens.

1
cache_dir str | None

Optional Hub cache shared by resolution and loading.

None
token str | bool | None

Hub authentication, shared by resolution and loading.

None

Returns:

Type Description
M2M100Translator

A translator with a short model citation and full configuration provenance.

Raises:

Type Description
OptionalDependencyError

If a required backend dependency is unavailable.

TranslationUnavailableError

If model resources cannot be loaded.

ValueError

If chunk, batch, beam, or output-length settings are invalid.

Source code in src/gdelt_regkg/fields/translation.py
@classmethod
# Keep generation and Hub context explicit and keyword-only.
# pylint: disable-next=too-many-arguments
def from_model(
    cls,
    model="facebook/m2m100_418M",
    *,
    device="cpu",
    allow_download=False,
    revision=None,
    batch_size=4,
    num_beams=4,
    chunk_tokens=384,
    max_new_tokens=768,
    min_new_tokens=1,
    cache_dir=None,
    token=None,
) -> M2M100Translator:
    """Load a reusable M2M100 model and tokenizer.

    Args:
        model (str): Model identifier or local model directory.
        device (str): PyTorch device, such as `cpu` or `cuda:0`.
        allow_download (bool): Allow model downloads when local files are missing.
        revision (str | None): Optional model revision.
        batch_size (int): Positive number of text chunks per inference batch.
        num_beams (int): Positive beam count for generation.
        chunk_tokens (int): Source tokens per chunk, between 1 and 512.
        max_new_tokens (int): Positive output-token limit per chunk.
        min_new_tokens (int): Minimum output tokens per chunk, between zero
            and `max_new_tokens`.
        cache_dir (str | None): Optional Hub cache shared by resolution and loading.
        token (str | bool | None): Hub authentication, shared by resolution and loading.

    Returns:
        A translator with a short model citation and full configuration provenance.

    Raises:
        OptionalDependencyError: If a required backend dependency is unavailable.
        TranslationUnavailableError: If model resources cannot be loaded.
        ValueError: If chunk, batch, beam, or output-length settings are invalid.
    """
    _validate_translation_options(
        chunk_tokens, batch_size, num_beams, max_new_tokens, min_new_tokens
    )
    torch = require_dependency("torch", "translate")
    transformers = require_dependency("transformers", "translate")
    sentencepiece = require_dependency("sentencepiece", "translate")
    hub = require_dependency("huggingface_hub", "translate")
    try:
        reference = _resolve_model_reference(
            model,
            revision=revision,
            allow_download=allow_download,
            cache_dir=cache_dir,
            token=token,
        )
        options: dict[str, Any] = {"local_files_only": not allow_download}
        if reference.identity_kind == "hub_commit":
            options["revision"] = reference.resolved_revision
        if cache_dir is not None:
            options["cache_dir"] = cache_dir
        if token is not None:
            options["token"] = token
        tokenizer = transformers.M2M100Tokenizer.from_pretrained(
            reference.load_reference, **options
        )
        network = (
            transformers.M2M100ForConditionalGeneration.from_pretrained(
                reference.load_reference, **options
            )
            .to(device)
            .eval()
        )
        if str(device).startswith("cuda"):
            network = network.half()
    except OSError as error:
        raise TranslationUnavailableError(
            "M2M100 resources unavailable; download explicitly with allow_download=True or supply a local model directory"
        ) from error
    precision = "fp16" if str(device).startswith("cuda") else "fp32"
    generation = {
        "chunk_tokens": chunk_tokens,
        "num_beams": num_beams,
        "max_new_tokens": max_new_tokens,
        "min_new_tokens": min_new_tokens,
    }
    cache_identity = _translation_identity(
        reference,
        transformers_version=transformers.__version__,
        precision=precision,
        generation=generation,
    )
    model_identity = {
        "identifier": reference.model_identifier,
        "identity_kind": reference.identity_kind,
        "resolved_revision": reference.resolved_revision,
    }
    profile = {
        "schema_version": 1,
        "model": model_identity,
        "tokenizer": dict(model_identity),
        "requested_revision": reference.requested_revision,
        "revision_resolution": reference.resolution_method,
        "generation": generation,
        "precision": precision,
        "packing": "packed-v2",
        "dependencies": {
            "transformers": transformers.__version__,
            "torch": torch.__version__,
            "sentencepiece": sentencepiece.__version__,
            "huggingface_hub": hub.__version__,
        },
        "runtime": {"device": str(device), "batch_size": batch_size},
    }
    suffix = "sha256:" if reference.identity_kind == "local_sha256" else ""
    engine = f"{reference.model_identifier}@{suffix}{reference.resolved_revision[:12]}"
    return cls(
        tokenizer,
        network,
        engine=engine,
        chunk_tokens=chunk_tokens,
        batch_size=batch_size,
        num_beams=num_beams,
        max_new_tokens=max_new_tokens,
        min_new_tokens=min_new_tokens,
        cache_identity=cache_identity,
        translation_profile=profile,
    )

translate

translate(text: str, source_language: str) -> str

Translate one body into English using the batch translation path.

Parameters:

Name Type Description Default
text str

Source body.

required
source_language str

Supported language code, name, or regional tag.

required

Returns:

Type Description
str

The English translation.

Raises:

Type Description
ValueError

If the language, input, or generated output is unsupported.

Source code in src/gdelt_regkg/fields/translation.py
def translate(self, text: str, source_language: str) -> str:
    """Translate one body into English using the batch translation path.

    Args:
        text: Source body.
        source_language: Supported language code, name, or regional tag.

    Returns:
        The English translation.

    Raises:
        ValueError: If the language, input, or generated output is unsupported.
    """
    return self.translate_many([text], source_language)[0]

translate_many

translate_many(texts: Iterable[str], source_language: str) -> list[str]

Translate same-language bodies in bounded batches of text chunks.

Parameters:

Name Type Description Default
texts Iterable[str]

Source bodies sharing one language.

required
source_language str

Supported language code, name, or regional tag.

required

Returns:

Type Description
list[str]

English translations in input order, with translated chunks joined

list[str]

by newlines.

Raises:

Type Description
ValueError

If the language is unsupported or a body produces invalid or empty output.

OptionalDependencyError

If PyTorch is unavailable.

Source code in src/gdelt_regkg/fields/translation.py
def translate_many(self, texts: Iterable[str], source_language: str) -> list[str]:
    """Translate same-language bodies in bounded batches of text chunks.

    Args:
        texts: Source bodies sharing one language.
        source_language: Supported language code, name, or regional tag.

    Returns:
        English translations in input order, with translated chunks joined
        by newlines.

    Raises:
        ValueError: If the language is unsupported or a body produces invalid
            or empty output.
        OptionalDependencyError: If PyTorch is unavailable.
    """
    torch = require_dependency("torch", "translate")

    source = normalize_language(source_language)
    if _MODEL_CODES[source] not in self.tokenizer.lang_code_to_id:
        raise ValueError(f"Model does not support language {source}")
    self.tokenizer.src_lang = _MODEL_CODES[source]
    texts = list(texts)
    chunks = [
        (index, chunk) for index, text in enumerate(texts) for chunk in self._chunks(text)
    ]
    outputs: list[list[str]] = [[] for _ in texts]
    with torch.inference_mode():
        for start in range(0, len(chunks), self.batch_size):
            batch = chunks[start : start + self.batch_size]
            translated = self._generate([chunk for _, chunk in batch])
            for (index, chunk), output in zip(batch, translated):
                outputs[index].append(output or self._retry_empty(chunk))
    result = ["\n".join(parts) for parts in outputs]
    if any(not text.strip() for text in result):
        raise ValueError("Cannot translate an empty body")
    return result

normalize_language

normalize_language(value: str) -> str

Return ISO 639-2/T for supported codes/names and regional/script tags.

Examples: UR, Urdu, ur_PK, ur-PK, urPK, and urd_Arab all become urd. Unknown or missing labels fail explicitly; no domain-based guessing runs.

Source code in src/gdelt_regkg/fields/translation.py
def normalize_language(value: str) -> str:
    """Return ISO 639-2/T for supported codes/names and regional/script tags.

    Examples: UR, Urdu, ur_PK, ur-PK, urPK, and urd_Arab all become urd.
    Unknown or missing labels fail explicitly; no domain-based guessing runs.
    """
    if not isinstance(value, str) or not value.strip():
        raise ValueError("A source language is required for translation")
    label = re.sub(r"[\s_]+", "-", value.strip().casefold())
    if label in _CODES:
        return _CODES[label]
    base = label.split("-", 1)[0]
    if base in _CODES:
        return _CODES[base]
    # Compact language+region or language+script forms, e.g. urpk, zhHant.
    for width in (3, 2):
        suffix = label[width:]
        if label[:width] in _CODES and (
            re.fullmatch(r"[a-z]{2}", suffix)
            or suffix
            in {
                "latn",
                "arab",
                "hans",
                "hant",
                "cyrl",
                "deva",
                "jpan",
                "kore",
                "hebr",
                "thai",
            }
        ):
            return _CODES[label[:width]]
    raise ValueError(f"Unsupported source language {value!r}")

translate_text

translate_text(text: str, *, language: str | None = None, translator: Translator, detect_missing_language: bool = True, language_detector: LanguageDetector | None = None, language_check: LanguageCheck = 'script') -> TranslationResult

Prepare English text and record its source language and translation engine.

English input passes through unchanged.

Parameters:

Name Type Description Default
text str

Prepared article body.

required
language str | None

Supported language code, name, or regional tag.

None
translator Translator

Backend used for non-English input.

required
detect_missing_language bool

Detect the language when its label is missing.

True
language_detector LanguageDetector | None

Custom detection backend. Defaults to local Lingua.

None
language_check LanguageCheck

none, script for alphabet conflicts, or all to check every supplied label.

'script'

Returns:

Type Description
TranslationResult

English text with original text, language, engine, and detection evidence.

Raises:

Type Description
TypeError

If text is not a string or detection output is invalid.

ValueError

If language settings, the engine, or translated text are invalid.

LanguageDetectionError

If detection fails or a script conflict is unresolved.

OptionalDependencyError

If a required detection dependency is unavailable.

Source code in src/gdelt_regkg/fields/translation.py
def translate_text(
    text: str,
    *,
    language: str | None = None,
    translator: Translator,
    detect_missing_language: bool = True,
    language_detector: LanguageDetector | None = None,
    language_check: LanguageCheck = "script",
) -> TranslationResult:
    """Prepare English text and record its source language and translation engine.

    English input passes through unchanged.

    Args:
        text: Prepared article body.
        language: Supported language code, name, or regional tag.
        translator: Backend used for non-English input.
        detect_missing_language: Detect the language when its label is missing.
        language_detector: Custom detection backend. Defaults to local Lingua.
        language_check: `none`, `script` for alphabet conflicts, or `all` to check
            every supplied label.

    Returns:
        English text with original text, language, engine, and detection evidence.

    Raises:
        TypeError: If `text` is not a string or detection output is invalid.
        ValueError: If language settings, the engine, or translated text are invalid.
        LanguageDetectionError: If detection fails or a script conflict is unresolved.
        OptionalDependencyError: If a required detection dependency is unavailable.
    """
    if not isinstance(text, str):
        raise TypeError("text must be str")
    detection = None
    if detect_missing_language and (
        language is None or (isinstance(language, str) and not language.strip())
    ):
        detection = detect_language(text, detector=language_detector)
        language = detection.language
    source = normalize_language(language or "")
    if detection is None:
        detection = verify_language(text, source, check=language_check, detector=language_detector)
        if detection is not None:
            source = normalize_language(detection.language)
    if source == "eng":
        return TranslationResult(text, text, source, None, detection)
    if not text.strip():
        raise ValueError("Cannot translate a blank body")
    engine = translator.engine
    if not isinstance(engine, str):
        raise ValueError("Translator must identify its engine")
    engine = text_component(engine, separators=";")
    if not engine:
        raise ValueError("Translator must identify its engine")
    translated = translator.translate(text, source)
    if not isinstance(translated, str) or not translated.strip():
        raise ValueError("Translator returned an empty or invalid English body")
    return TranslationResult(text, translated, source, engine, detection)