Compare commits

...

1 Commits

Author SHA1 Message Date
wukko 6b1abb9947 devutils/i18n: map sentence case strings to Title Case strings (WIP)
macOS' Title Case styling isn't applicable in languages other than en-US
2026-06-14 22:18:30 +06:00
5 changed files with 135 additions and 39 deletions
+1
View File
@@ -13,6 +13,7 @@ from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO_ROOT))
sys.path.insert(1, str(REPO_ROOT / 'utils'))
PLATFORMS_DIR = Path(__file__).resolve().parent / "i18n-data"
OUT_PATH = REPO_ROOT / 'i18n' / 'source.gen.json'
+37 -13
View File
@@ -6,29 +6,54 @@
import json
from pathlib import Path
I18N_DIR = Path(__file__).resolve().parent.parent / 'i18n'
from i18n_titlecase import (
build_title_case_aliases,
source_key,
translation_key,
)
REPO_ROOT = Path(__file__).resolve().parent.parent
I18N_DIR = REPO_ROOT / 'i18n'
SOURCE_PATH = I18N_DIR / 'source.gen.json'
TRANSLATIONS_DIR = I18N_DIR / 'translations'
def clean_translation_file(lang, source_keys):
def clean_translation_file(lang, source_keys, translation_aliases):
"""Clean up outdated and duplicated translations in a language file."""
path = TRANSLATIONS_DIR / f'{lang}.json'
with open(path, encoding='utf-8') as file:
entries = json.load(file)
translation_keys = set()
result_indices = {}
result_has_alias = {}
result = []
n_filtered = 0
changed = False
for entry in entries:
key = (entry['name'], entry['source'])
if key in source_keys and key not in translation_keys:
result.append(entry)
translation_keys.add(key)
else:
key = translation_key(entry, translation_aliases)
if key not in source_keys:
n_filtered += 1
changed = True
continue
if n_filtered > 0:
entry = dict(entry)
is_alias = entry['source'] != key[1]
if is_alias:
entry['source'] = key[1]
changed = True
if key not in result_indices:
result_indices[key] = len(result)
result_has_alias[key] = is_alias
result.append(entry)
else:
if result_has_alias[key] and not is_alias:
result[result_indices[key]] = entry
result_has_alias[key] = False
n_filtered += 1
changed = True
if changed:
with open(path, 'w', encoding='utf-8') as file:
json.dump(result, file, indent=2, ensure_ascii=False)
file.write('\n')
@@ -43,11 +68,10 @@ def run():
with open(I18N_DIR / 'languages.json', encoding='utf-8') as file:
languages = json.load(file)
existing_keys = set()
for entry in source:
existing_keys.add((entry['name'], entry['message']))
source_aliases, translation_aliases = build_title_case_aliases(source)
existing_keys = {source_key(entry, source_aliases) for entry in source}
for lang in languages:
n_filtered = clean_translation_file(lang, existing_keys)
n_filtered = clean_translation_file(lang, existing_keys, translation_aliases)
if n_filtered:
print(f'{lang}: filtered {n_filtered} string(s)')
+36 -19
View File
@@ -16,6 +16,13 @@ from pathlib import Path
from urllib.request import Request, urlopen
REPO_ROOT = Path(__file__).resolve().parent.parent
from i18n_titlecase import (
build_title_case_aliases,
source_key,
translation_key,
)
I18N_DIR = REPO_ROOT / 'i18n'
SOURCE_PATH = I18N_DIR / 'source.gen.json'
TRANSLATIONS_DIR = I18N_DIR / 'translations'
@@ -104,7 +111,7 @@ def translate_with_backend(prompt, data, command=None):
return llm_chat(prompt, data)
def load_existing(lang_code):
def load_existing(lang_code, translation_aliases):
"""Load existing translations as a dict keyed by (name, source)."""
path = TRANSLATIONS_DIR / f'{lang_code}.json'
if not path.exists():
@@ -114,11 +121,16 @@ def load_existing(lang_code):
result = {}
for entry in entries:
if entry:
result[(entry['name'], entry['source'])] = entry
key = translation_key(entry, translation_aliases)
entry = dict(entry)
is_alias = entry['source'] != key[1]
entry['source'] = key[1]
if key not in result or not is_alias:
result[key] = entry
return result
def find_untranslated(source, existing):
def find_untranslated(source, existing, source_aliases):
"""
Return indices into source for strings that need (re)translation.
A string needs translation if:
@@ -127,13 +139,13 @@ def find_untranslated(source, existing):
"""
indices = []
for i, entry in enumerate(source):
key = (entry['name'], entry['message'])
key = source_key(entry, source_aliases)
if key not in existing:
indices.append(i)
return indices
def build_payload(source, untranslated, existing, context_window=2):
def build_payload(source, untranslated, existing, source_aliases, context_window=2):
"""
Build the JSON array to send to the model.
Includes untranslated strings plus nearby neighbors as context.
@@ -151,10 +163,10 @@ def build_payload(source, untranslated, existing, context_window=2):
if 0 <= idx < len(source):
all_indices.add(idx)
# group untranslated indices by (name, message) for dedup
# group untranslated indices by canonical (name, message) for dedup
seen = {}
for i in untranslated:
key = (source[i]['name'], source[i]['message'])
key = source_key(source[i], source_aliases)
seen.setdefault(key, []).append(i)
payload = []
@@ -162,7 +174,7 @@ def build_payload(source, untranslated, existing, context_window=2):
added_keys = set()
for i in sorted(all_indices):
if i not in needed:
key = (source[i]['name'], source[i]['message'])
key = source_key(source[i], source_aliases)
entry = {
'name': source[i]['name'],
'context': source[i]['context'],
@@ -173,15 +185,19 @@ def build_payload(source, untranslated, existing, context_window=2):
payload.append(entry)
continue
key = (source[i]['name'], source[i]['message'])
key = source_key(source[i], source_aliases)
if key in added_keys:
continue
added_keys.add(key)
rep_idx = next(
(idx for idx in seen[key] if source[idx]['message'] == key[1]),
seen[key][0],
)
entry = {
'name': source[i]['name'],
'context': source[i]['context'],
'message': source[i]['message'],
'name': source[rep_idx]['name'],
'context': source[rep_idx]['context'],
'message': source[rep_idx]['message'],
}
payload.append(entry)
dedup_map.append(seen[key])
@@ -268,7 +284,7 @@ def parse_response(raw, expected_names):
return results
def save_translations(lang_code, source, existing, response, dedup_map):
def save_translations(lang_code, source, existing, response, dedup_map, source_aliases):
"""Merge model response into existing translations and save."""
for entry, indices in zip(response, dedup_map):
expected_name = source[indices[0]]['name']
@@ -276,10 +292,10 @@ def save_translations(lang_code, source, existing, response, dedup_map):
raise ValueError(f'response order mismatch at index {indices[0]}: '
f'expected {expected_name}, got {entry["name"]}')
for src_idx in indices:
key = (source[src_idx]['name'], source[src_idx]['message'])
key = source_key(source[src_idx], source_aliases)
result = {
'name': source[src_idx]['name'],
'source': source[src_idx]['message'],
'source': key[1],
'message': entry['message'],
}
if 'feminine' in entry:
@@ -298,8 +314,9 @@ def save_translations(lang_code, source, existing, response, dedup_map):
def translate_language(language, source, prompt_template, from_file=None, command=None):
"""Run translation for a single language."""
lang_code, lang_name = language
existing = load_existing(lang_code)
untranslated = find_untranslated(source, existing)
source_aliases, translation_aliases = build_title_case_aliases(source)
existing = load_existing(lang_code, translation_aliases)
untranslated = find_untranslated(source, existing, source_aliases)
if not untranslated:
print(f'{lang_code}: already up to date')
@@ -307,7 +324,7 @@ def translate_language(language, source, prompt_template, from_file=None, comman
print(f'{lang_code}: {len(untranslated)} strings to translate')
payload, dedup_map = build_payload(source, untranslated, existing)
payload, dedup_map = build_payload(source, untranslated, existing, source_aliases)
expected_names = {source[i]['name'] for i in untranslated}
if from_file:
@@ -322,7 +339,7 @@ def translate_language(language, source, prompt_template, from_file=None, comman
response = parse_response(raw, expected_names)
save_translations(lang_code, source, existing, response, dedup_map)
save_translations(lang_code, source, existing, response, dedup_map, source_aliases)
print(f'{lang_code}: done')
+15 -7
View File
@@ -18,6 +18,7 @@ from multiprocessing import Pool
from pathlib import Path
import name_substitution_utils as namesub
from i18n_titlecase import build_title_case_aliases, source_key, translation_key
REPO_ROOT = Path(__file__).resolve().parent.parent
I18N_DIR = REPO_ROOT / 'i18n'
@@ -136,13 +137,13 @@ def resolve_xtb(src, lang_code, xtb_index):
return xtb_map.get(xtb_lang)
def merge_into_xtb(xtb_path, source_entries, trans_by_key):
def merge_into_xtb(xtb_path, source_entries, trans_by_key, source_aliases):
"""Merge translations for matching source entries into a single XTB file."""
# TODO: handle feminine/masculine variants via <branch> elements
seen_ids = set()
entries = []
for src in source_entries:
key = (src['name'], src['message'])
key = source_key(src, source_aliases)
trans = trans_by_key.get(key)
if not trans:
continue
@@ -159,7 +160,7 @@ def merge_into_xtb(xtb_path, source_entries, trans_by_key):
def apply_language(task):
"""Apply translations for a single language into XTB files."""
lang_code, source, xtb_index = task
lang_code, source, xtb_index, source_aliases, translation_aliases = task
trans_path = TRANSLATIONS_DIR / f'{lang_code}.json'
if not trans_path.exists():
print(f'{lang_code}: no translations found, skipping', file=sys.stderr)
@@ -170,8 +171,11 @@ def apply_language(task):
trans_by_key = {}
for trans in translations:
if trans:
trans_by_key[(trans['name'], trans['source'])] = trans
if not trans:
continue
key = translation_key(trans, translation_aliases)
if key not in trans_by_key or trans['source'] == key[1]:
trans_by_key[key] = trans
# group source entries by target XTB file
by_xtb = defaultdict(list)
@@ -184,7 +188,7 @@ def apply_language(task):
total = 0
for xtb_path, source_entries in by_xtb.items():
total += merge_into_xtb(xtb_path, source_entries, trans_by_key)
total += merge_into_xtb(xtb_path, source_entries, trans_by_key, source_aliases)
print(f'{lang_code}: applied {total} translations to {len(by_xtb)} XTB files')
@@ -198,8 +202,12 @@ def apply_translations(tree):
namesub.add_grit_to_path(tree)
xtb_index = build_xtb_index(source, tree)
source_aliases, translation_aliases = build_title_case_aliases(source)
tasks = [(code, source, xtb_index) for code in languages]
tasks = [
(code, source, xtb_index, source_aliases, translation_aliases)
for code in languages
]
with Pool(min(32, os.cpu_count() or 1)) as pool:
pool.map(apply_language, tasks)
+46
View File
@@ -0,0 +1,46 @@
# Copyright 2026 The Helium Authors
# You can use, redistribute, and/or modify this source code under
# the terms of the GPL-3.0 license that can be found in the LICENSE file.
"""Helpers for sharing translations between title-case source variants."""
def build_title_case_aliases(source):
"""Map same-scope title-case variants to the regular-case source."""
groups = {}
for entry in source:
key = (entry['source'], entry['name'], entry['message'].casefold())
groups.setdefault(key, []).append(entry)
source_aliases = {}
translation_aliases = {}
for (scope, name, _), entries in groups.items():
regular = next(
(entry for entry in entries
if not entry['context'].startswith('In Title Case:')),
None,
)
if not regular:
continue
for entry in entries:
if entry is regular or entry['message'] == regular['message']:
continue
source_aliases[(scope, name, entry['message'])] = regular['message']
translation_aliases[(name, entry['message'])] = regular['message']
return source_aliases, translation_aliases
def source_key(entry, aliases):
"""Return the canonical translation key for a source entry."""
message = aliases.get(
(entry['source'], entry['name'], entry['message']),
entry['message'],
)
return entry['name'], message
def translation_key(entry, aliases):
"""Return the canonical translation key for a translation entry."""
source = aliases.get((entry['name'], entry['source']), entry['source'])
return entry['name'], source