Skip to content

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

// text-translator — AI text translator: prompt building + reply cleanup.
//
// Language: Kotlin (1.9, JVM, standard library only)
// 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.
//
// Kotlin strings are UTF-16, exactly like the TypeScript original, so length
// and take reproduce the 12000-unit truncation verbatim, Regex runs the TS
// port's fence pattern unchanged, and a nullable String? carries the TS null.

/** One entry of the curated common-language list. */
data class Language(val id: String, val label: String)

/** One message for the provider layer; role is "system" or "user". */
data class ChatMessage(val role: String, val content: String)

/** Source-language sentinel: let the model detect the input language. */
const val AUTO_SOURCE = "auto"

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

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

/** Input cap; longer text is cut and marked so the model knows it ends early. */
const val MAX_INPUT_CHARS = 12000

/** Label for a known language id; unknown ids pass through (the TS `?: id`). */
fun languageLabel(id: String): String =
    LANGUAGES.firstOrNull { it.id == id }?.label ?: id

/** Build the [system, user] chat messages for the provider layer. */
fun buildPromptMessages(text: String, from: String, to: String): List<ChatMessage> {
    val fromPart =
        if (from == AUTO_SOURCE) "Detect the source language yourself."
        else "The source language is ${languageLabel(from)}."
    val body =
        if (text.length > MAX_INPUT_CHARS) "${text.take(MAX_INPUT_CHARS)}\n… (text truncated)"
        else text
    val 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 listOf(ChatMessage("system", system), 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.
 */
fun parseTranslation(text: String): String? =
    text.replace(Regex("```[a-z]*\n?"), "").trim().ifEmpty { null }

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 →