Skip to content

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

// text-translator — AI text translator: prompt building + reply cleanup.
//
// Language: Java (17, standard library only; a non-public top-level class so
//           the file may be named java.java)
// Source:   CosmoDev polyglot showcase port of the `text-translator` tool,
//           ported from src/lib/translate.ts (the canonical implementation).
// License:  display source — part of CosmoDev's polyglot tool pages.
//
// Java strings are UTF-16, exactly like the TypeScript original, so length()
// and substring() reproduce the 12000-unit truncation verbatim, replaceAll
// runs the TS port's fence regex unchanged, and a null return carries the
// "nothing survives" outcome. Records keep the Language / ChatMessage shapes
// to one line each.

import java.util.List;

/**
 * Pure core of the AI text translator — the curated language list, the
 * [system, user] chat-message construction, and the reply cleanup. The
 * translator island is a thin shell over a shared LLM provider; network
 * I/O stays behind.
 */
final class TextTranslatorTool {

    /** One entry of the curated common-language list. */
    record Language(String id, String label) {}

    /** One message for the provider layer; role is "system" or "user". */
    record ChatMessage(String role, String content) {}

    /** Source-language sentinel: let the model detect the input language. */
    static final String AUTO_SOURCE = "auto";

    /** Sentinel entry shown in the "from" select. */
    static final Language AUTO_LANGUAGE = new Language(AUTO_SOURCE, "Auto-detect");

    /** Curated common-language list — the SSOT for both selects. */
    static final List<Language> LANGUAGES = List.of(
        new Language("en", "English"),    new Language("es", "Spanish"),
        new Language("fr", "French"),     new Language("de", "German"),
        new Language("pt", "Portuguese"), new Language("it", "Italian"),
        new Language("nl", "Dutch"),      new Language("sv", "Swedish"),
        new Language("pl", "Polish"),     new Language("tr", "Turkish"),
        new Language("ru", "Russian"),    new Language("uk", "Ukrainian"),
        new Language("ar", "Arabic"),     new Language("fa", "Persian"),
        new Language("he", "Hebrew"),     new Language("hi", "Hindi"),
        new Language("bn", "Bengali"),    new Language("zh", "Chinese"),
        new Language("ja", "Japanese"),   new Language("ko", "Korean"),
        new Language("vi", "Vietnamese"), new Language("th", "Thai"),
        new Language("id", "Indonesian"), new Language("sw", "Swahili"));

    /** Input cap; longer text is cut and marked so the model knows it ends early. */
    private static final int MAX_INPUT_CHARS = 12000;

    private TextTranslatorTool() {}

    /** Label for a known language id; unknown ids pass through (the TS `?? id`). */
    static String languageLabel(String id) {
        for (Language l : LANGUAGES) {
            if (l.id().equals(id)) return l.label();
        }
        return id;
    }

    /** Build the [system, user] chat messages for the provider layer. */
    static List<ChatMessage> buildPromptMessages(String text, String from, String to) {
        String fromPart = from.equals(AUTO_SOURCE)
                ? "Detect the source language yourself."
                : "The source language is " + languageLabel(from) + ".";
        String body = text.length() > MAX_INPUT_CHARS
                ? text.substring(0, MAX_INPUT_CHARS) + "\n… (text truncated)"
                : text;
        String system = "You are a faithful translator. " + fromPart
                + " Translate the user's text into " + languageLabel(to)
                + ". Output ONLY the translation — no preamble, no notes, no backticks, "
                + "preserving paragraphs, formatting, and code blocks as-is.";
        return List.of(new ChatMessage("system", system), new ChatMessage("user", body));
    }

    /**
     * Clean the model's reply into displayable translation text. Strips stray
     * markdown fences (``` plus an optional lowercase info-string and newline)
     * and trims; null only when nothing survives — the TS port's null.
     */
    static String parseTranslation(String text) {
        String cleaned = text.replaceAll("```[a-z]*\\n?", "").strip();
        return cleaned.isEmpty() ? null : cleaned;
    }
}

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 →