Files
LLeMbas-Android/scripts/gen-strings.py
T
HomerandClaude Opus 5.5 4f09bc41bb
CI / check (push) Canceled after 0s
LLeMbas for Android 0.1.0 (alpha, unreleased): the first commit
A native client for a LLeMbas instance on the server's /api/v2, and the
phone's digital assistant.

- Sign in by device code; the token sealed in the Android Keystore; several
  instances.
- Chats and agent chats: the list, a chat with its reply streaming as JSON
  server-sent events (reconnecting, whole blocks), thinking, tool calls,
  steered messages, the plan, jobs, stop, edit, regenerate, continue, the
  model, effort and Plan mode, attachments and dictation.
- Cards in a sheet, answered as the page's form says it; first answer wins.
- Notifications through UnifiedPush, no Google services; an approval can be
  answered from its notification.
- The digital assistant: a VoiceInteractionService with its session (a sheet
  over the current app, "Include screen" off by default), a recognition
  service through the instance's speech-to-text, the lock-screen path that
  asks to unlock before sending, a Quick Settings tile and an Ask shortcut.
- Share to LLeMbas; Moria and Shire from the server's tokens; nine
  languages; a self-updater in the `full` flavour, none in `fdroid`.

Generated and pinned from the server, each checked in CI: the theme
(tokens.lock.json), the contract (contract/lock.json, server 2124ba9), the
strings and the icons. Built and tested only on GitHub Actions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:44:30 +00:00

92 lines
3.3 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 at ../LLeMbas, or LEMBAS_SERVER)
scripts/gen-strings.py --check fail if a key the code uses has no English, or the other way round
"""
from __future__ import annotations
import importlib.util
import json
import os
import re
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) -> dict[str, str]:
path = SERVER / "src/lembas/web/i18n" / f"{code}.py"
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
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)
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}")
if __name__ == "__main__":
main()