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 (C11, 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.
*
* The portable surface is pure — language list, [system, user] message
* building, fence-stripping reply cleanup. C strings are bytes, so truncation
* counts bytes where the TS slice counts UTF-16 units; C has no regex, so the
* fence scan is hand-rolled.
*
* Build: cc -std=c11 c.c && ./a.out
*/
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/** Input cap; longer text is cut and marked so the model knows it ends early. */
#define MAX_INPUT_CHARS 12000
/** Source-language sentinel: let the model detect the input language. */
static const char AUTO_SOURCE[] = "auto";
/** One entry of the curated common-language list. */
typedef struct { const char *id; const char *label; } Language;
/* Sentinel entry shown in the "from" select (non-static: no unused warning). */
const Language AUTO_LANGUAGE = { AUTO_SOURCE, "Auto-detect" };
/** Curated common-language list — the SSOT for both selects. */
static const Language LANGUAGES[] = {
{"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"},
};
/** One chat message; role is "system"/"user", content is malloc'd (caller frees). */
typedef struct { const char *role; char *content; } ChatMessage;
/** Format into a malloc'd string (vsnprintf twice: measure, then fill). */
static char *xasprintf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
int n = vsnprintf(NULL, 0, fmt, args);
va_end(args);
if (n < 0) return NULL;
char *out = malloc((size_t)n + 1);
if (out == NULL) return NULL;
va_start(args, fmt);
vsnprintf(out, (size_t)n + 1, fmt, args);
va_end(args);
return out;
}
/** Label for a known language id; unknown ids pass through (the TS `?? id`). */
static const char *language_label(const char *id)
{
for (size_t i = 0; i < sizeof LANGUAGES / sizeof LANGUAGES[0]; i++)
if (strcmp(LANGUAGES[i].id, id) == 0) return LANGUAGES[i].label;
return id;
}
/**
* 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 are cut and marked; free() both contents when done.
*/
void build_prompt_messages(const char *text, const char *from, const char *to,
ChatMessage out[2])
{
char *from_part = strcmp(from, AUTO_SOURCE) == 0
? xasprintf("Detect the source language yourself.")
: xasprintf("The source language is %s.", language_label(from));
size_t text_len = strlen(text);
size_t body_len = text_len > MAX_INPUT_CHARS ? MAX_INPUT_CHARS : text_len;
char *body = malloc(body_len + sizeof "\n… (text truncated)");
if (body != NULL) {
memcpy(body, text, body_len);
strcpy(body + body_len,
text_len > MAX_INPUT_CHARS ? "\n… (text truncated)" : "");
}
out[0].role = "system";
out[0].content = xasprintf(
"You are a faithful translator. %s Translate the user's text into %s. "
"Output ONLY the translation — no preamble, no notes, no backticks, "
"preserving paragraphs, formatting, and code blocks as-is.",
from_part, language_label(to));
out[1].role = "user";
out[1].content = body;
free(from_part);
}
/**
* Clean the model's reply into displayable translation text. Strips every
* /```[a-z]*\n?/ span (stray markdown fences), trims the six characters
* C isspace() and JS \s share; NULL when nothing survives (the TS null).
*/
char *parse_translation(const char *text)
{
size_t len = strlen(text);
char *out = malloc(len + 1);
if (out == NULL) return NULL;
size_t o = 0, i = 0;
while (i < len) {
if (strncmp(text + i, "```", 3) == 0) {
i += 3;
while (i < len && text[i] >= 'a' && text[i] <= 'z') i++;
if (i < len && text[i] == '\n') i++; /* the regex's \n? */
continue;
}
out[o++] = text[i++];
}
size_t start = 0, end = o;
while (start < end && isspace((unsigned char)out[start])) start++;
while (end > start && isspace((unsigned char)out[end - 1])) end--;
if (start == end) { free(out); return NULL; }
memmove(out, out + start, end - start);
out[end - start] = '\0';
return 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 →