Files
LLeMbas-Android/scripts/gen-strings.py
T
HomerandClaude Opus 5.5 665ac44e5c
CI / check (push) Canceled after 0s
Chats: the activity panel, the model's level control, team size, model pictures
The activity panel full screen (Context, Outputs, Background tasks with the
team's room, Plan), kept current from the events route, with a summary line
above the composer that opens it; an agent's conversation read-only and a
stop with confirmation. The effort control follows the model (none, a
Thinking switch, the picker); Agents fewest/most where a team is offered;
model pictures in the picker and the chat's title. gen-strings takes the
server's translation of a sentence with named placeholders (SERVER_ENGLISH);
all eight languages complete.

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

142 lines
5.7 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 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)
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()