Skip to content

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

// text-translator — AI text translator: prompt building + reply cleanup.
//
// Language: C++ (C++17, standard library only)
// Source:   CosmoDev polyglot showcase port of the `text-translator` tool,
//           ported from src/lib/translate.ts (the canonical TypeScript
//           implementation).
// License:  display source — part of CosmoDev's polyglot tool pages.
//
// The portable surface is pure — language list, [system, user] message
// building, reply cleanup. std::regex runs the TS port's fence pattern
// verbatim and std::optional carries the "null when nothing survives"
// contract. std::string is byte-based, so truncation counts bytes where the
// TS slice counts UTF-16 units.
//
// Build: c++ -std=c++17 cpp.cpp && ./a.out

#include <optional>
#include <regex>
#include <string>
#include <vector>

namespace texttranslator {

/** One entry of the curated common-language list. */
struct Language {
    const char *id;
    const char *label;
};

/// Source-language sentinel: let the model detect the input language.
constexpr const char *kAutoSource = "auto";

/// Sentinel entry shown in the "from" select (inline: external linkage).
inline constexpr Language kAutoLanguage{kAutoSource, "Auto-detect"};

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

/// Input cap; longer text is cut and marked so the model knows it ends early.
constexpr int kMaxInputChars = 12000;

/// One message for the provider layer; role is "system" or "user".
struct ChatMessage {
    std::string role;
    std::string content;
};

/// Label for a known language id; unknown ids pass through (the TS `?? id`).
std::string languageLabel(const std::string &id)
{
    for (const Language &l : kLanguages) {
        if (id == l.id) return l.label;
    }
    return id;
}

/// Build the [system, user] chat messages for the provider layer. from is
/// kAutoSource or a kLanguages id; to is a kLanguages id.
std::vector<ChatMessage> buildPromptMessages(const std::string &text,
                                             const std::string &from,
                                             const std::string &to)
{
    const std::string fromPart = from == kAutoSource
        ? "Detect the source language yourself."
        : "The source language is " + languageLabel(from) + ".";
    const std::string body = text.size() > kMaxInputChars
        ? text.substr(0, kMaxInputChars) + "\n… (text truncated)"
        : text;
    const std::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 {{"system", system}, {"user", body}};
}

/// Clean the model's reply into displayable translation text. Strips every
/// /```[a-z]*\n?/ span (the fences models sometimes wrap translations in),
/// trims the six characters isspace() and JS \s share, and returns nullopt
/// when nothing survives — the TS port's null.
std::optional<std::string> parseTranslation(const std::string &text)
{
    static const std::regex kFence("```[a-z]*\n?");
    const std::string cleaned = std::regex_replace(text, kFence, "");
    static const char kWhitespace[] = " \t\n\v\f\r";
    const std::string::size_type b = cleaned.find_first_not_of(kWhitespace);
    if (b == std::string::npos) return std::nullopt;
    const std::string::size_type e = cleaned.find_last_not_of(kWhitespace);
    return cleaned.substr(b, e - b + 1);
}

}  // namespace texttranslator

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 →