PEP-99: localizeText picks the variant with the least Russian left untranslated, not the least Cyrillic — Kazakh is Cyrillic too
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
fcdbb26f47
commit
2526b6b59a
@ -21,3 +21,8 @@ PEP-98; свой механизм здесь не делаем. Эта стор
|
||||
русскому значению ключа, остаток переведён вручную.
|
||||
- **Полнота** — тест: у `kk` есть все ключи базового словаря и те же плейсхолдеры.
|
||||
Отсутствующий ключ во время работы откатывается на базовый язык (поведение PEP-98).
|
||||
- **Выбор варианта в `localizeText`** — из вариантов перевода готового текста PEP-98
|
||||
выбирала вариант с наименьшим числом кириллических букв. Казахский тоже кириллица, поэтому
|
||||
побеждал непереведённый русский («2 ч назад» вместо «2 сағ бұрын»). Теперь каждый вариант
|
||||
несёт счётчик `left` — сколько русских букв осталось непереведёнными (точное совпадение — 0,
|
||||
шаблон — сумма по непереведённым подстановкам); для английского результат прежний.
|
||||
|
||||
@ -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<string, string> = {};
|
||||
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;
|
||||
|
||||
@ -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");
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user