AI Text Translator — Zig 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 Zig implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! text-translator — AI text translator: prompt building + reply cleanup.
//!
//! Language: Zig (0.13, 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, reply cleanup. Slices are bytes, so truncation counts bytes
//! where the TS slice counts UTF-16 units; the fence stripper hand-rolls the
//! /```[a-z]*\n?/ scan (std.regex does not exist), and an optional return
//! carries the TS null.
//!
//! Test: zig test zig.zig
const std = @import("std");
/// Source-language sentinel: let the model detect the input language.
pub const AUTO_SOURCE = "auto";
/// One entry of the curated common-language list.
pub const Language = struct { id: []const u8, label: []const u8 };
/// Sentinel entry shown in the "from" select.
pub const auto_language = Language{ .id = AUTO_SOURCE, .label = "Auto-detect" };
/// Curated common-language list — the SSOT for both selects.
pub const languages = [_]Language{
.{ .id = "en", .label = "English" }, .{ .id = "es", .label = "Spanish" },
.{ .id = "fr", .label = "French" }, .{ .id = "de", .label = "German" },
.{ .id = "pt", .label = "Portuguese" }, .{ .id = "it", .label = "Italian" },
.{ .id = "nl", .label = "Dutch" }, .{ .id = "sv", .label = "Swedish" },
.{ .id = "pl", .label = "Polish" }, .{ .id = "tr", .label = "Turkish" },
.{ .id = "ru", .label = "Russian" }, .{ .id = "uk", .label = "Ukrainian" },
.{ .id = "ar", .label = "Arabic" }, .{ .id = "fa", .label = "Persian" },
.{ .id = "he", .label = "Hebrew" }, .{ .id = "hi", .label = "Hindi" },
.{ .id = "bn", .label = "Bengali" }, .{ .id = "zh", .label = "Chinese" },
.{ .id = "ja", .label = "Japanese" }, .{ .id = "ko", .label = "Korean" },
.{ .id = "vi", .label = "Vietnamese" }, .{ .id = "th", .label = "Thai" },
.{ .id = "id", .label = "Indonesian" }, .{ .id = "sw", .label = "Swahili" },
};
/// Input cap; longer text is cut and marked so the model knows it ends early.
const max_input_chars = 12000;
/// One message for the provider layer; role is "system" or "user".
pub const ChatMessage = struct { role: []const u8, content: []const u8 };
/// Label for a known language id; unknown ids pass through (the TS `?? id`).
fn languageLabel(id: []const u8) []const u8 {
for (languages) |l| {
if (std.mem.eql(u8, l.id, id)) return l.label;
}
return id;
}
pub const BuildError = error{OutOfMemory};
/// Build the [system, user] chat messages for the provider layer. from is
/// AUTO_SOURCE or a languages id; to is a languages id. The caller owns and
/// frees the returned slice and both content slices.
pub fn buildPromptMessages(
allocator: std.mem.Allocator,
text: []const u8,
from: []const u8,
to: []const u8,
) BuildError![]ChatMessage {
const from_part = if (std.mem.eql(u8, from, AUTO_SOURCE))
try allocator.dupe(u8, "Detect the source language yourself.")
else
try std.fmt.allocPrint(allocator, "The source language is {s}.", .{languageLabel(from)});
// Slices are bytes; the TS port's slice counts UTF-16 code units.
const body = if (text.len > max_input_chars)
try std.fmt.allocPrint(allocator, "{s}\n… (text truncated)", .{text[0..max_input_chars]})
else
try allocator.dupe(u8, text);
const system = try std.fmt.allocPrint(
allocator,
"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, languageLabel(to) },
);
const messages = try allocator.alloc(ChatMessage, 2);
messages[0] = .{ .role = "system", .content = system };
messages[1] = .{ .role = "user", .content = body };
allocator.free(from_part);
return messages;
}
/// 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 JS \s recognizes, and returns null when nothing
/// survives — the TS port's null. The caller owns the returned slice.
pub fn parseTranslation(allocator: std.mem.Allocator, text: []const u8) BuildError!?[]u8 {
const stripped = try allocator.alloc(u8, text.len);
defer allocator.free(stripped);
var o: usize = 0;
var i: usize = 0;
while (i < text.len) {
if (std.mem.startsWith(u8, text[i..], "```")) {
i += 3;
while (i < text.len and text[i] >= 'a' and text[i] <= 'z') i += 1;
if (i < text.len and text[i] == '\n') i += 1; // the regex's \n?
continue;
}
stripped[o] = text[i];
o += 1;
i += 1;
}
// The exact six characters JavaScript's \s (and C isspace) recognize.
const cleaned = std.mem.trim(u8, stripped[0..o], " \t\n\x0b\x0c\r");
if (cleaned.len == 0) return null;
return try allocator.dupe(u8, 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 →