Skip to content

AI Text Translator — Rust 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 Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! text-translator — AI text translator: prompt building + reply cleanup.
//!
//! Language: Rust (std only — no external crates).
//! 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 — language list,
//! chat-message construction, and reply cleanup. Even the code-fence stripper
//! is hand-rolled: one 4-line scan beats pulling in the `regex` crate.
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// Source-language sentinel: let the model detect the input language.
pub const AUTO_SOURCE: &str = "auto";

/// One entry of the curated common-language list.
#[derive(Clone, Copy)]
pub struct Language {
    pub id: &'static str,
    pub label: &'static str,
}

/// Sentinel entry shown in the "from" select.
pub const AUTO_LANGUAGE: Language = Language { id: AUTO_SOURCE, label: "Auto-detect" };

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

const MAX_INPUT_CHARS: usize = 12000;

/// One chat message for the provider layer; `role` is `"system"` or `"user"`.
pub struct ChatMessage {
    pub role: &'static str,
    pub content: String,
}

/// Label for a known language id; unknown ids pass through unchanged.
fn language_label(id: &str) -> &str {
    LANGUAGES.iter().find(|l| l.id == id).map_or(id, |l| l.label)
}

/// Build the [system, user] chat messages for the provider layer.
///
/// `from` is [`AUTO_SOURCE`] or a [`LANGUAGES`] id; `to` is a [`LANGUAGES`]
/// id. Inputs longer than MAX_INPUT_CHARS chars are cut and marked so the
/// model knows the text ends early (Unicode scalar values; the TS original
/// slices by UTF-16 code units).
pub fn build_prompt_messages(text: &str, from: &str, to: &str) -> Vec<ChatMessage> {
    let from_part = if from == AUTO_SOURCE {
        "Detect the source language yourself.".to_string()
    } else {
        format!("The source language is {}.", language_label(from))
    };

    let body: String = if text.chars().count() > MAX_INPUT_CHARS {
        let head: String = text.chars().take(MAX_INPUT_CHARS).collect();
        format!("{head}\n… (text truncated)")
    } else {
        text.to_string()
    };

    let system = format!(
        "You are a faithful translator. {from_part} Translate the user's text into {}. \
         Output ONLY the translation — no preamble, no notes, no backticks, \
         preserving paragraphs, formatting, and code blocks as-is.",
        language_label(to),
    );

    vec![
        ChatMessage { role: "system", content: system },
        ChatMessage { role: "user", content: body },
    ]
}

/// 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.
pub fn parse_translation(text: &str) -> Option<String> {
    let cleaned = strip_fences(text).trim().to_string();
    if cleaned.is_empty() { None } else { Some(cleaned) }
}

/// std-only equivalent of the TS port's `text.replace(/```[a-z]*\n?/g, '')`:
/// drop every "```" plus an optional lowercase info-string and newline.
fn strip_fences(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut rest = input;
    while let Some(pos) = rest.find("```") {
        out.push_str(&rest[..pos]);
        rest = &rest[pos + 3..];
        let tag_end = rest.find(|c: char| !c.is_ascii_lowercase()).unwrap_or(rest.len());
        rest = &rest[tag_end..];
        if rest.starts_with('\n') {
            rest = &rest[1..];
        }
    }
    out.push_str(rest);
    out
}

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 →