Files
LLeMbas-Android/scripts/gen-strings.py
T
HomerandClaude Opus 5.5 37cf778c44
CI / check (push) Canceled after 0s
Language: the account's by default, Settings › Language, per-app locale
The app followed the phone's locale, so a Slovak phone showed Slovak while the
instance and the account were English. Now the default is the account's
language from /api/v2/me (read once per instance in use, kept in Prefs), and
Settings › Language offers Same as my account / Phone language / each language
the app has, named in itself.

Android 13+: LocaleManager.setApplicationLocales, and android:localeConfig
(res/xml/locales_config.xml, written by gen-strings.py from LANGS) so the
system's per-app language lists the same set; a choice made there is adopted
as the person's. Older phones: the chosen tag in a small synchronous file,
applied in attachBaseContext of every activity and to the assistant's window.
No AppCompat: the framework API covers it.

LanguageTest holds the offered list, the values-* folders and the locale
config equal. Screenshot 17-language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:06:47 +00:00

155 lines
6.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""Write the app's string resources: English from `strings.py`, the eight translations from
the server's catalogues and `strings_own.json`. See `strings.py` for the rule.
scripts/gen-strings.py <server-ref> the catalogues at that ref of the server's git checkout
(../LLeMbas, or LEMBAS_SERVER) -- the same ref the
contract and the tokens are pinned to
scripts/gen-strings.py the server's working tree as it is
scripts/gen-strings.py --check fail if a key the code uses has no English, or the other
way round
A ref, not the working tree, is the way to regenerate: the server's checkout is shared, and
whatever is uncommitted in it is not what a released server says.
"""
from __future__ import annotations
import importlib.util
import json
import os
import re
import subprocess
import sys
from pathlib import Path
from xml.sax.saxutils import escape
ROOT = Path(__file__).resolve().parent.parent
SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas"))
RES = ROOT / "app/src/main/res"
LANGS = ("cs", "de", "es", "fr", "hu", "it", "pl", "sk")
HEADER = "<!-- Generated by scripts/gen-strings.py. Edit scripts/strings.py or strings_own.json. -->"
sys.path.insert(0, str(Path(__file__).parent))
from strings import SERVER_ENGLISH, STRINGS # noqa: E402
def android(text: str) -> str:
"""Escaped for a <string>: XML, then Android's own apostrophe and quote rules."""
return escape(text).replace("'", "\\'").replace('"', '\\"')
def server_catalogue(code: str, ref: str | None = None) -> dict[str, str]:
path = SERVER / "src/lembas/web/i18n" / f"{code}.py"
if ref:
shown = subprocess.run(
["git", "-C", str(SERVER), "show", f"{ref}:src/lembas/web/i18n/{code}.py"],
capture_output=True, text=True,
)
if shown.returncode != 0:
return {}
scope: dict = {"__name__": f"catalogue_{code}"}
exec(compile(shown.stdout, f"{ref}:{code}.py", "exec"), scope) # the server's own file
return dict(scope.get("MESSAGES", {}))
if not path.exists():
return {}
spec = importlib.util.spec_from_file_location(f"catalogue_{code}", path)
module = importlib.util.module_from_spec(spec)
sys.dont_write_bytecode = True
spec.loader.exec_module(module)
return dict(getattr(module, "MESSAGES", {}))
def numbered(server_english: str, translation: str) -> str:
"""A server translation with its named placeholders (`%(n)s`) numbered as Android's
(`%1$s`), in the order the server's English names them. `%%` stays as it is: both write a
percent sign that way."""
names: list[str] = []
for name in re.findall(r"%\((\w+)\)s", server_english):
if name not in names:
names.append(name)
for i, name in enumerate(names, start=1):
translation = translation.replace(f"%({name})s", f"%{i}$s")
return translation
def server_text(catalogue: dict[str, str], key: str, english: str) -> str | None:
"""The server's translation of a sentence: by the app's English, or by the server's own
English for it (`SERVER_ENGLISH`), placeholders numbered."""
if english in catalogue:
return catalogue[english]
source = SERVER_ENGLISH.get(key)
if source and source in catalogue:
text = numbered(source, catalogue[source])
return None if "%(" in text else text
return None
def used_keys() -> set[str]:
keys: set[str] = set()
for path in (ROOT / "app/src").rglob("*"):
if path.suffix in (".kt", ".xml") and "/res/values" not in str(path):
keys |= set(re.findall(r"(?:R\.string\.|@string/)([a-z_]+)", path.read_text(errors="ignore")))
return keys
def write(folder: Path, entries: dict[str, str]) -> None:
folder.mkdir(parents=True, exist_ok=True)
lines = ['<?xml version="1.0" encoding="utf-8"?>', HEADER, "<resources>"]
for key, text in entries.items():
extra = ' translatable="false"' if key == "app_name" else ""
lines.append(f' <string name="{key}"{extra}>{android(text)}</string>')
lines.append("</resources>")
(folder / "strings.xml").write_text("\n".join(lines) + "\n", encoding="utf-8")
def write_locale_config() -> None:
"""`res/xml/locales_config.xml`: the languages the app has, for Android 13+'s per-app language
(the manifest's `android:localeConfig`). Written from LANGS, so it cannot list a language
the app has no strings for, or miss one it has."""
lines = ['<?xml version="1.0" encoding="utf-8"?>', HEADER.replace("Edit scripts/strings.py or strings_own.json", "Edit LANGS there"),
'<locale-config xmlns:android="http://schemas.android.com/apk/res/android">',
' <locale android:name="en" />']
lines += [f' <locale android:name="{code}" />' for code in LANGS]
lines.append("</locale-config>")
(RES / "xml/locales_config.xml").write_text("\n".join(lines) + "\n", encoding="utf-8")
def main() -> None:
used = used_keys()
missing = sorted(used - set(STRINGS))
unused = sorted(set(STRINGS) - used)
if missing or unused:
print(f"gen-strings: used but not in strings.py: {missing}; in strings.py but unused: {unused}")
if "--check" in sys.argv or missing:
sys.exit(1)
if "--check" in sys.argv:
print(f"gen-strings: {len(STRINGS)} strings, all used")
return
args = [a for a in sys.argv[1:] if not a.startswith("--")]
ref = None
if args:
ref = subprocess.run(
["git", "-C", str(SERVER), "rev-parse", "--verify", f"{args[0]}^{{commit}}"],
capture_output=True, text=True, check=True,
).stdout.strip()
own = json.loads((Path(__file__).parent / "strings_own.json").read_text(encoding="utf-8"))
write(RES / "values", STRINGS)
write_locale_config()
for code in LANGS:
catalogue = server_catalogue(code, ref)
mine = own.get(code, {})
out = {}
for key, english in STRINGS.items():
if key == "app_name":
continue
text = mine.get(key) or server_text(catalogue, key, english)
if text and all(text.count(f"%{i}$s") == english.count(f"%{i}$s") for i in (1, 2, 3)):
out[key] = text
write(RES / f"values-{code}", out)
print(f"gen-strings: {code}: {len(out)}/{len(STRINGS) - 1}" + (f" (server {ref[:12]})" if ref else ""))
if __name__ == "__main__":
main()