Files
LLeMbas-Android/scripts/gen-strings.py
T
HomerandClaude Opus 5.5 fd1af60dbb
CI / check (push) Canceled after 0s
Android 1.0 for server 2.0: the file viewer, and older servers refused
The show card. A tool call may now carry `show` (event["show"], harness spec 3.0.0): a file's
name, path, kind, line and which copy -- node and version in the chat's tree, or the copy a linked
device sent (shown_id). The transcript draws it as a card with Open; the viewer is a full-screen,
read-only dialog that fetches the text and opens at the named line. Markdown goes through the same
Markwon setup as a reply (rule 4); code, text and Markdown over 200 000 characters are numbered
lines in a lazy list, the number column measured from the file's longest number. HTML is never
rendered: no WebView exists in the app, so it is shown as source, and "Open in the browser" opens
the web UI's viewer, which renders it in its sealed frame. Copy takes the whole file.

The text comes from GET /api/v2/chats/{chat}/show?node=&version= (or ?shown=), plain text, at most
1 MB. That route is the app's half of a contract the server does not have yet: /api/v2 neither
publishes `show` on a tool call nor serves the file to a token. Until it does, the card does not
appear, and a viewer that meets a missing route says so and offers the browser.

Older servers are refused: the discovery document's device-link protocol must be 3 (LLeMbas 2.0),
at sign-in and, for an instance signed in to before, when the chat list opens. The protocol and
not the version string, because the server's dev still says 1.7.x before its first beta.

Also: gen-strings.py takes a server ref like the other two generators, so the strings come from
the same commit as the contract and the tokens rather than from a shared working tree; the
Reports notification channel goes (2.0 has no reports) and is deleted on first start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 04:31:07 +00:00

117 lines
4.6 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 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 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 catalogue.get(english)
if text and text.count("%1$s") == english.count("%1$s"):
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()