Skip to content

AI Text Translator — Python source

Translate any text between 24 languages with an LLM — auto-detected or explicit source, straight from your browser with your own free Groq key.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""text-translator — AI text translator: prompt building + reply cleanup.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `text-translator` tool, ported from
src/lib/translate.ts (the canonical TypeScript implementation).

Why this file exists: the translator island is a thin shell over a shared LLM
provider, so the portable, testable surface is pure — the curated language
list, the [system, user] chat-message construction, and the reply cleanup
that strips stray markdown fences. Network I/O stays behind.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import re

#: Source-language sentinel: let the model detect the input language.
AUTO_SOURCE = "auto"

#: Sentinel entry shown in the "from" select.
AUTO_LANGUAGE = {"id": AUTO_SOURCE, "label": "Auto-detect"}

#: Curated common-language list — the single source of truth for both selects.
LANGUAGES = [
    {"id": "en", "label": "English"},
    {"id": "es", "label": "Spanish"},
    {"id": "fr", "label": "French"},
    {"id": "de", "label": "German"},
    {"id": "pt", "label": "Portuguese"},
    {"id": "it", "label": "Italian"},
    {"id": "nl", "label": "Dutch"},
    {"id": "sv", "label": "Swedish"},
    {"id": "pl", "label": "Polish"},
    {"id": "tr", "label": "Turkish"},
    {"id": "ru", "label": "Russian"},
    {"id": "uk", "label": "Ukrainian"},
    {"id": "ar", "label": "Arabic"},
    {"id": "fa", "label": "Persian"},
    {"id": "he", "label": "Hebrew"},
    {"id": "hi", "label": "Hindi"},
    {"id": "bn", "label": "Bengali"},
    {"id": "zh", "label": "Chinese"},
    {"id": "ja", "label": "Japanese"},
    {"id": "ko", "label": "Korean"},
    {"id": "vi", "label": "Vietnamese"},
    {"id": "th", "label": "Thai"},
    {"id": "id", "label": "Indonesian"},
    {"id": "sw", "label": "Swahili"},
]

MAX_INPUT_CHARS = 12000

_FENCE_RE = re.compile(r"```[a-z]*\n?")


def _language_label(lang_id: str) -> str:
    """Label for a known language id; unknown ids pass through unchanged."""
    for language in LANGUAGES:
        if language["id"] == lang_id:
            return language["label"]
    return lang_id


def build_prompt_messages(
    text: str, *, from_lang: str, to: str
) -> list[dict[str, str]]:
    """Build the [system, user] chat messages for the provider layer.

    ``from_lang`` uses AUTO_SOURCE (or a LANGUAGES id) — renamed from the TS
    port's ``from`` because that identifier is a Python keyword. Inputs longer
    than MAX_INPUT_CHARS are cut and marked so the model knows the text ends
    early; Python counts code points where the TS ``slice`` counts UTF-16
    code units.
    """
    if from_lang == AUTO_SOURCE:
        from_part = "Detect the source language yourself."
    else:
        from_part = f"The source language is {_language_label(from_lang)}."

    body = text
    if len(text) > MAX_INPUT_CHARS:
        body = f"{text[:MAX_INPUT_CHARS]}\n… (text truncated)"

    system = (
        "You are a faithful translator. "
        f"{from_part} "
        f"Translate the user's text into {_language_label(to)}. "
        "Output ONLY the translation — no preamble, no notes, no backticks, "
        "preserving paragraphs, formatting, and code blocks as-is."
    )
    return [
        {"role": "system", "content": system},
        {"role": "user", "content": body},
    ]


def parse_translation(text: str) -> str | None:
    """Clean the model's reply into displayable translation text.

    No strict format contract — any non-empty cleaned text is the
    translation; None only when nothing survives. Strips markdown code
    fences (``` plus an optional lowercase info-string and newline).
    """
    cleaned = _FENCE_RE.sub("", text).strip()
    return cleaned if cleaned else None

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →