From 2526b6b59a535057a2749c15cd7e1bc7c067153c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 15:25:30 +0500 Subject: [PATCH] =?UTF-8?q?PEP-99:=20localizeText=20picks=20the=20variant?= =?UTF-8?q?=20with=20the=20least=20Russian=20left=20untranslated,=20not=20?= =?UTF-8?q?the=20least=20Cyrillic=20=E2=80=94=20Kazakh=20is=20Cyrillic=20t?= =?UTF-8?q?oo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- openspec/changes/pep-99-kazakh-ui/design.md | 5 ++ packages/shared/src/i18n/index.ts | 59 ++++++++++++++------- packages/testkit/test/i18n-kk.test.ts | 3 ++ 3 files changed, 47 insertions(+), 20 deletions(-) diff --git a/openspec/changes/pep-99-kazakh-ui/design.md b/openspec/changes/pep-99-kazakh-ui/design.md index 314627c9..7504f414 100644 --- a/openspec/changes/pep-99-kazakh-ui/design.md +++ b/openspec/changes/pep-99-kazakh-ui/design.md @@ -21,3 +21,8 @@ PEP-98; свой механизм здесь не делаем. Эта стор русскому значению ключа, остаток переведён вручную. - **Полнота** — тест: у `kk` есть все ключи базового словаря и те же плейсхолдеры. Отсутствующий ключ во время работы откатывается на базовый язык (поведение PEP-98). +- **Выбор варианта в `localizeText`** — из вариантов перевода готового текста PEP-98 + выбирала вариант с наименьшим числом кириллических букв. Казахский тоже кириллица, поэтому + побеждал непереведённый русский («2 ч назад» вместо «2 сағ бұрын»). Теперь каждый вариант + несёт счётчик `left` — сколько русских букв осталось непереведёнными (точное совпадение — 0, + шаблон — сумма по непереведённым подстановкам); для английского результат прежний. diff --git a/packages/shared/src/i18n/index.ts b/packages/shared/src/i18n/index.ts index 961d6a81..e69c0d8e 100644 --- a/packages/shared/src/i18n/index.ts +++ b/packages/shared/src/i18n/index.ts @@ -158,7 +158,13 @@ function compile(locale: Locale) { return c; } -function matchTemplate(locale: Locale, s: string, depth: number): string | undefined { +/** A translation and how many Russian letters it left untranslated (Kazakh is Cyrillic too). */ +interface Rendered { + text: string; + left: number; +} + +function matchTemplate(locale: Locale, s: string, depth: number): Rendered | undefined { const c = compile(locale); const lists = [c.byHead.get(s.slice(0, 2)) ?? [], c.loose]; for (const list of lists) { @@ -166,26 +172,31 @@ function matchTemplate(locale: Locale, s: string, depth: number): string | undef const mt = tpl.re.exec(s); if (!mt) continue; const vars: Record = {}; + let left = 0; let ok = true; tpl.names.forEach((name, i) => { const v = mt[i + 1]!; - vars[name] = depth < 2 ? (piece(locale, v, depth + 1) ?? v) : v; + const sub = depth < 2 ? piece(locale, v, depth + 1) : undefined; + vars[name] = sub?.text ?? v; + const rest = sub ? sub.left : cyrillic(v); + left += rest; // A template anchored only in the middle must not cut free Russian text (a person's or an - // agent's sentence "Какой формат из двух?" is not "{done} из {total}"). - if (tpl.loose && CYR.test(vars[name]!)) ok = false; + // agent's sentence "Какой формат из двух?" is not "{done} из {total}"). Russian left + // untranslated counts, not Cyrillic: Kazakh is Cyrillic too. + if (tpl.loose && rest) ok = false; }); if (!ok) continue; - return fill(tpl.out, vars); + return { text: fill(tpl.out, vars), left }; } } return undefined; } /** Exact entry or a template match; undefined when nothing fits. */ -function piece(locale: Locale, s: string, depth = 0): string | undefined { +function piece(locale: Locale, s: string, depth = 0): Rendered | undefined { if (!CYR.test(s)) return undefined; const exact = entry(locale, s); - if (exact !== undefined) return exact; + if (exact !== undefined) return { text: exact, left: 0 }; return matchTemplate(locale, s, depth); } @@ -193,14 +204,15 @@ function piece(locale: Locale, s: string, depth = 0): string | undefined { const EDGE = /^([^А-Яа-яЁёA-Za-z0-9«"(<{]*)([\s\S]*?)([\s.:;,!?…)»"]*)$/u; const cyrillic = (s: string) => (s.match(/[А-Яа-яЁё]/g) ?? []).length; -/** The variant with the least Russian left; the first one wins a tie. */ -const fewest = (list: string[]) => list.reduce((best, x) => (cyrillic(x) < cyrillic(best) ? x : best)); +/** The variant with the least Russian left untranslated; the first one wins a tie. */ +const fewest = (list: Rendered[]) => list.reduce((best, x) => (x.left < best.left ? x : best)); +const untouched = (s: string): Rendered => ({ text: s, left: cyrillic(s) }); -function phrase(locale: Locale, s: string): string { - const out = [s]; +function phrase(locale: Locale, s: string): Rendered { + const out = [untouched(s)]; const direct = piece(locale, s); if (direct !== undefined) { - if (!cyrillic(direct)) return direct; + if (!direct.left) return direct; out.push(direct); } // Decorations stripped: "🧪 Проверки: 4 из 4" must not be eaten by a key starting with a placeholder. @@ -208,29 +220,34 @@ function phrase(locale: Locale, s: string): string { if (mt && (mt[1] || mt[3])) { const core = mt[2]!; const inner = piece(locale, core); - if (inner !== undefined) out.push(mt[1] + inner + mt[3]); + if (inner !== undefined) out.push({ text: mt[1] + inner.text + mt[3], left: inner.left + cyrillic(mt[1]! + mt[3]) }); if (mt[3]) { const kept = mt[3].trimEnd(); const withTail = piece(locale, core + kept); - if (withTail !== undefined) out.push(mt[1] + withTail + mt[3].slice(kept.length)); + if (withTail !== undefined) out.push({ text: mt[1] + withTail.text + mt[3].slice(kept.length), left: withTail.left + cyrillic(mt[1]!) }); } } return fewest(out); } -function line(locale: Locale, s: string): string { - if (!CYR.test(s)) return s; +const joined = (parts: Rendered[], sep: string): Rendered => ({ + text: parts.map((p) => p.text).join(sep), + left: parts.reduce((n, p) => n + p.left, 0), +}); + +function line(locale: Locale, s: string): Rendered { + if (!CYR.test(s)) return untouched(s); const whole = phrase(locale, s); - if (!cyrillic(whole)) return whole; + if (!whole.left) return whole; const out = [whole]; // Telegram HTML: the text between tags one by one. if (s.includes("<")) { const segs = s.split(/(<[^>]+>)/); - if (segs.length > 1) out.push(segs.map((seg) => (seg.startsWith("<") ? seg : seg && line(locale, seg))).join("")); + if (segs.length > 1) out.push(joined(segs.map((seg) => (seg.startsWith("<") || !seg ? untouched(seg) : line(locale, seg))), "")); } // "a · b", "a — b" and "Label: value" pieces. for (const sep of [" · ", " — ", ": "]) { - if (s.includes(sep)) out.push(s.split(sep).map((p) => line(locale, p)).join(sep)); + if (s.includes(sep)) out.push(joined(s.split(sep).map((p) => line(locale, p)), sep)); } return fewest(out); } @@ -248,7 +265,9 @@ export function localizeText(locale: Locale, text: string): string { const hit = cache.get(text); if (hit !== undefined) return hit; const whole = phrase(locale, text); - const out = !cyrillic(whole) ? whole : text.includes("\n") ? fewest([whole, text.split("\n").map((l) => line(locale, l)).join("\n")]) : fewest([whole, line(locale, text)]); + const out = ( + !whole.left ? whole : text.includes("\n") ? fewest([whole, joined(text.split("\n").map((l) => line(locale, l)), "\n")]) : fewest([whole, line(locale, text)]) + ).text; if (cache.size >= CACHE_MAX) cache.clear(); cache.set(text, out); return out; diff --git a/packages/testkit/test/i18n-kk.test.ts b/packages/testkit/test/i18n-kk.test.ts index 3a968f96..c20f5a61 100644 --- a/packages/testkit/test/i18n-kk.test.ts +++ b/packages/testkit/test/i18n-kk.test.ts @@ -34,6 +34,9 @@ test("Казахский интерфейс: перевод, название, test("Готовый русский текст переводится на казахский, неизвестный остаётся как есть", () => { assert.equal(localizeText("kk", "Ошибка: нет связи"), "Қате: нет связи"); + // Kazakh is Cyrillic too: the translated variant must win over the untouched Russian one. + assert.equal(localizeText("kk", "2 ч назад"), "2 сағ бұрын"); + assert.equal(localizeText("kk", "✅ Стори PEP-4 готова к ревью · PR: http://x"), "✅ Стори PEP-4 ревьюге дайын · PR: http://x"); assert.equal(localizeText("kk", "Совсем неизвестная фраза"), "Совсем неизвестная фраза"); assert.equal(localizeText("ru", "Ошибка: x"), "Ошибка: x"); });