Translating an app’s string files is a different job from translating prose. Each value is short, often has no context, and carries syntax the model must not touch: placeholders, HTML tags and plural rules. Arabic makes the last one hard. English files hold two plural forms; Arabic needs six. This post builds a small pipeline on an OpenAI-compatible LLM: freeze placeholders, ask for six plain plural strings, assemble the ICU syntax in code, then validate everything in CI.
For translating documents, tickets and contracts, see Arabic–English translation with LLMs, which covers tone, glossaries and evaluation for prose.
Why do Arabic plurals break machine-translated string files?
Unicode CLDR, which Intl.PluralRules, ICU and i18next all follow, gives Arabic six cardinal categories:
| Category | CLDR rule | Example numbers | Example: “file” |
|---|---|---|---|
| zero | n = 0 | 0 | لا توجد ملفات |
| one | n = 1 | 1 | ملف واحد |
| two | n = 2 | 2 | ملفان (dual) |
| few | n % 100 = 3..10 | 3–10, 103–110 | 5 ملفات (plural) |
| many | n % 100 = 11..99 | 11–99, 111 | 11 ملفًا (singular, accusative) |
| other | everything else | 100–102, 1000, 0.5 | 100 ملف (singular) |
Two details catch people out. First, the categories are not the numbers: 103 is few and 111 is many. Second, an English source gives the model only one and other, so it has to invent four forms from grammar alone. Most failures come from the model copying the English pair.
The failure is silent. We rendered an Arabic message that had only one and other with intl-messageformat 12.1.5: 0, 2 and 11 files all came out as “N ملف”. i18next 27.1.2 behaved the same way when the _many key was missing: 11 files showed the _other text. No error, no warning, just wrong Arabic.
How should you send strings to the model?
Batch them. One request per string wastes tokens on the system prompt and loses context between related strings. Send 50 to 200 keys at a time as a JSON object, grouped by screen or feature so “Save” next to “Cancel” reads as a button.
Three rules make the reply checkable:
- Freeze placeholders. Replace
{name}, double-brace i18next placeholders,%s,%1$sand tags such as<b>with markers like ⟦0⟧. The model sees “Welcome back, ⟦0⟧!” and cannot translatenameinto اسم. - Ask for plural forms as plain strings. Send the English
oneandothertexts and ask for six Arabic strings. Code builds the ICU syntax. The model never writes a brace. - Give a glossary and a do-not-translate list. Product names, plan names and terms your support team uses. The glossary section of the translation post explains why this matters more than model choice.
The translation script
The source file uses ICU MessageFormat, the syntax FormatJS documents. The same freezing works for i18next’s own JSON format, whose plural keys end _zero, _one, _two, _few, _many and _other.
{
"save": "Save",
"welcome": "Welcome back, {name}!",
"invite": "<b>{inviter}</b> invited you to the {workspace} workspace",
"billing": "Pay with AcmePay",
"files": "{count, plural, one {# file} other {# files}}"
}
import json, os, re
from openai import OpenAI
client = OpenAI(base_url="https://inference.broadnet.ai/v1", api_key=os.environ["BROADNET_API_KEY"])
FORMS = ["zero", "one", "two", "few", "many", "other"]
# ICU arguments, double-brace and printf placeholders, HTML-style tags
PH = re.compile(r"\{\{\s*\w+\s*\}\}|\{\w+\}|%(?:\d+\$)?[sdif@]|</?\w+[^>]*>")
PLURAL = re.compile(r"^\{(\w+), plural,(.*)\}$", re.S)
def freeze(text):
"""Replace each placeholder with ⟦n⟧ so the model cannot translate or break it."""
found = PH.findall(text)
for i, p in enumerate(found):
text = text.replace(p, f"⟦{i}⟧", 1)
return text, found
def thaw(text, found):
for i, p in enumerate(found):
text = text.replace(f"⟦{i}⟧", p)
return text
def branches(body):
"""'one {# file} other {# files}' -> {'one': '# file', 'other': '# files'}."""
out, i = {}, 0
while i < len(body):
m = re.compile(r"\s*([=\w]+)\s*\{").match(body, i)
if not m:
break
depth, j = 1, m.end()
while depth:
depth += {"{": 1, "}": -1}.get(body[j], 0)
j += 1
out[m.group(1)] = body[m.end():j - 1]
i = j
return out
SYSTEM = """You translate app interface strings from English to Modern Standard Arabic.
Reply with one JSON object only: {"STRINGS": {key: Arabic}, "PLURALS": {key: {six forms}}}.
Rules:
- ⟦0⟧, ⟦1⟧ ... are placeholders. Keep every one exactly once and unchanged; move it if Arabic word order needs it.
- # stands for the number. Keep it where the number should appear.
- Interface style: short, no full stops on buttons or labels.
- Never translate terms in DO_NOT_TRANSLATE. Use GLOSSARY translations exactly.
- For each PLURALS key, return all six Arabic forms: zero, one, two, few, many, other.
zero = none; one = singular without a number; two = dual without a number;
few = 3-10: # + plural noun; many = 11-99: # + singular noun in the accusative;
other = 100, 1000 and also 0.5 and 1.5: # + singular noun."""
def translate(src, glossary=None, dnt=(), model="broadnet/qwen3.8-27b"):
strings, plurals, frozen = {}, {}, {}
for key, text in src.items():
m = PLURAL.match(text)
if m:
b = branches(m.group(2))
fone, ph = freeze(b.get("one", b["other"]))
fother, _ = freeze(b["other"])
plurals[key] = {"one": fone, "other": fother}
frozen[key] = (m.group(1), ph)
elif "{" in PH.sub("", text):
raise ValueError(f"{key}: nested ICU, send to a human")
else:
strings[key], ph = freeze(text)
frozen[key] = (None, ph)
payload = {"STRINGS": strings, "PLURALS": plurals,
"GLOSSARY": glossary or {}, "DO_NOT_TRANSLATE": list(dnt)}
r = client.chat.completions.create(
model=model, max_tokens=4000, temperature=0.2,
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": json.dumps(payload, ensure_ascii=False)}])
out = json.loads(r.choices[0].message.content)
ar = {k: thaw(v, frozen[k][1]) for k, v in out.get("STRINGS", {}).items() if k in frozen}
for k, forms in out.get("PLURALS", {}).items():
if k not in frozen:
continue
arg, ph = frozen[k]
ar[k] = "{%s, plural, %s}" % (arg, " ".join(
f + " {" + thaw(forms[f], ph) + "}" for f in FORMS if f in forms))
return ar
en = json.load(open("en.json"))
ar = translate(en, glossary={"workspace": "مساحة العمل"}, dnt=["AcmePay"])
json.dump(ar, open("ar.json", "w"), ensure_ascii=False, indent=2)
We ran it with the OpenAI Python SDK against a local mock server, not the live API, with a canned Arabic reply. The request the model would see held “Welcome back, ⟦0⟧!” and “⟦0⟧⟦1⟧⟦2⟧ invited you to the ⟦3⟧ workspace”, and the script wrote this ar.json:
{
"save": "حفظ",
"welcome": "مرحبًا بعودتك يا {name}!",
"invite": "دعاك <b>{inviter}</b> إلى مساحة العمل {workspace}",
"billing": "ادفع عبر AcmePay",
"files": "{count, plural, zero {لا توجد ملفات} one {ملف واحد} two {ملفان} few {# ملفات} many {# ملفًا} other {# ملف}}"
}
Notes on the code:
- Markers move, they don’t vanish. Arabic often puts the verb first, so ⟦0⟧ can move. The check below counts markers; it does not care where they sit.
- Nested ICU goes to a person. A
selectinside apluralis rare and easy to break. The script refuses it rather than guessing. max_tokens=4000leaves room for reasoning. BroadNet’s docs say DeepSeek V4.1 Flash, GLM 5.3 and Qwen3.8 27B reason before answering, and the reasoning counts toward max_tokens. See empty responses from reasoning models.json.loadscan fail. Wrap it and resend once with the error; fixing invalid JSON from an LLM has a tested repair function. On GLM 5.3 and Qwen3.8 27B, the two BroadNet models documented with structured output, add aresponse_formatschema too. The check below stays either way.
How do you validate the Arabic file in CI?
Parse every message with the same parser your app uses at runtime, and compare it with the source. This Node script uses @formatjs/icu-messageformat-parser (version 3.5.23 in our test):
// node check-ar.mjs en.json ar.json -> exits 1 on any problem
import { readFileSync } from "node:fs";
import { parse, TYPE } from "@formatjs/icu-messageformat-parser";
const AR_FORMS = ["zero", "one", "two", "few", "many", "other"];
const [en, ar] = process.argv.slice(2).map((p) => JSON.parse(readFileSync(p, "utf8")));
const errors = [];
// Collect argument and tag names; return the plural elements too.
function walk(nodes, names = [], plurals = []) {
for (const n of nodes) {
if (n.type === TYPE.literal || n.type === TYPE.pound) continue;
names.push(n.type === TYPE.tag ? `<${n.value}>` : `{${n.value}}`);
if (n.type === TYPE.tag) walk(n.children, names, plurals);
if (n.type === TYPE.plural) plurals.push(n);
if (n.options) for (const o of Object.values(n.options)) walk(o.value, [], plurals);
}
return { names: names.sort().join(" "), plurals };
}
for (const key of Object.keys(en)) {
if (!(key in ar)) { errors.push(`${key}: missing`); continue; }
let src, dst;
try { src = walk(parse(en[key])); dst = walk(parse(ar[key], { requiresOtherClause: true })); }
catch (e) { errors.push(`${key}: ICU syntax error ${e.message}`); continue; }
if (src.names !== dst.names) errors.push(`${key}: arguments differ: [${src.names}] vs [${dst.names}]`);
for (const p of dst.plurals) {
const missing = AR_FORMS.filter((f) => !(f in p.options));
if (missing.length) errors.push(`${key}: plural {${p.value}} lacks ${missing.join(", ")}`);
}
if (!/[-ۿ]/.test(ar[key])) errors.push(`${key}: no Arabic letters`);
if (/⟦\d+⟧/.test(ar[key])) errors.push(`${key}: placeholder marker left in text`);
}
for (const key of Object.keys(ar)) if (!(key in en)) errors.push(`${key}: not in source`);
console.log(errors.join("\n") || "ok");
process.exit(errors.length ? 1 : 0);
On the file above it printed ok. We then made the mock reply drop the many form and the {workspace} marker. The script exited with code 1 and printed:
invite: arguments differ: [<b> {inviter} {workspace}] vs [<b> {inviter}]
files: plural {count} lacks many
The “no Arabic letters” rule flags strings the model left in English. It also flags values that are only a product name or a number, so keep an allow-list for those. For i18next’s own format, apply the same checks per key: every _one/_other pair in English needs all six suffixed keys in Arabic, and each needs the same placeholders, except that _zero, _one and _two may drop the count.
Finally, render a few numbers through your real formatter. With intl-messageformat 12.1.5, the files message above gave 0 → لا توجد ملفات, 2 → ملفان, 5 → 5 ملفات, 11 → 11 ملفًا, 102 → 102 ملف and 111 → 111 ملفًا. That spot check catches a form that parses but uses the wrong noun.
What about right-to-left display?
Translation gets the words right; the browser still has to order them. When a Latin name or a number is inserted into an Arabic sentence, the Unicode bidirectional algorithm can move punctuation or swap neighbouring runs. The W3C’s advice is to isolate inserted text: wrap it in <bdi> or an element with dir="auto" in HTML, or surround it with U+2068 FIRST STRONG ISOLATE and U+2069 POP DIRECTIONAL ISOLATE in plain text, such as push notifications.
Do this where you interpolate, not in the translation. In our test, formatting the welcome message with the name wrapped in U+2068 and U+2069 kept both characters in the output and left the Arabic untouched. Set dir="rtl" and lang="ar" on the page or container too. Arabic prompt engineering has a short checklist for RTL display bugs.
Digits are a formatter choice, not a translation choice. Keep # or the argument in the string. In Node 24 (ICU 78.3), Intl.NumberFormat wrote 1234 as 1,234 for ar and as ١٬٢٣٤ for ar-EG and ar-SA. Pick the locale tag that matches your market. For the wider product questions (interface locale versus model language, chat bubbles with mixed directions, language detection and per-language cost), see designing an AI experience for multiple languages.
Who should review the output?
An LLM pipeline with these checks guarantees the file is well-formed. It does not guarantee the Arabic is right. Have an Arabic speaker review:
- New and changed strings only. Diff
en.jsonagainst the last release and translate only what changed. Reviews stay small, and approved strings never move. - Plural forms, word by word. Agreement with numbers is where the model most often slips, especially the accusative after 11 to 99.
- Gender. “You” and verbs change with the reader’s gender in Arabic. If your UI addresses users directly, decide on a convention, such as a fixed form or a neutral rephrasing, and put it in the system prompt.
- Length. Arabic strings can run longer or shorter than English. Check buttons and tabs in the real layout at mobile width.
Keep a reviewed glossary file in the repo and send it with every request, so approved terms stay fixed.
What does it cost?
String files are small. Output is about as long as the input, and Arabic usually needs more tokens per word than English; tokens per word in Arabic and English has measured ratios. Paste a batch into the Arabic token counter, multiply by the number of batches, and add the system prompt to each one. Reasoning models also spend tokens thinking; BroadNet reports them in usage as completion_tokens_details.reasoning_tokens, so read usage from a real request before you extrapolate.
| Model | Notes for this job | Input / output per 1M tokens |
|---|---|---|
| Qwen3.8 27B | Structured output documented | $0.175 / $2.17 |
| GLM 5.3 | Structured output documented; 1,048,576-token context | $0.78 / $3.46 |
| Gemma 4 VL 26B | Runs on the $5 starting credit; prompt-only JSON, so the validator matters more | $0.10 / $0.22 |
| DeepSeek V4.1 Flash | Also on flat plans, such as $15 a week per session, one request at a time per session | $0.175 / $0.52 |
Prices are from BroadNet’s pricing feed, updated 2026-11-14. Translate the same 100 strings with two models and have your reviewer compare them before you pick one; price per token matters less than the number of fixes. For thousands of keys across many languages, batch processing without a Batch API covers concurrency and retries.
Where BroadNet Inference fits
BroadRouter is BroadNet’s own site. BroadNet Inference gives OpenAI-compatible access to the models above, so the script runs with the OpenAI Python SDK after changing the base URL and model ID; check the API reference for parameters each model supports. It has no translation endpoint and publishes no localisation benchmark, so the validator and a human reviewer remain your quality gate. Dedicated localisation platforms add translation memory, reviewer workflows and in-context screenshots; if you need those, use one and keep the CI check above as a second line.
