CI / check (push) Canceled after 0s
The `status` frame carries `progress` {phase, since, ...} beside its
text from spec 3.4.0 (progress.md). The app draws it as
`{{text}} · {{elapsed}}` -- the shared texts as string resources, the
elapsed time ticking each second, `retrying`'s `in` counted down, the
text alone for stopped and failed -- under the reply and in the
assistant's sheet, and falls back to the free `status` text for a server
that does not send it, a phase it does not know, or a required field
missing. Under inspection the clock stands still (65 s), so screenshots
are stable and nothing animates forever.
Coded to the spec while the server's frame is being added. ProgressTest
runs the spec's own conformance cases (conformance/progress.json, copied
from LLeMbas CLI 3.4.0 until the server vendors it) against the English
in res/values; fetch-contract.py pins the server's copy as
contract/harness_progress.json once it is there. gen-strings.py takes
the server's translations of the `{{field}}` texts (its catalogues key
them by the spec's English), numbering the fields and doubling a lone %.
Screenshots: 04-writing with a rate, 04-waiting-for-model at 360 dp and
1.5x type.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
161 lines
6.9 KiB
Python
Executable File
161 lines
6.9 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 numbered as Android's (`%1$s`), in the
|
|
order the server's English names them. Two kinds: `%(n)s`, where `%%` stays as it is (both
|
|
write a percent sign that way); and the harness's shared texts' `{{n}}` (the progress
|
|
keys, `loop.json` `progress.texts`), which are not %-formatted on the server, so a lone `%`
|
|
there becomes Android's `%%`."""
|
|
names: list[str] = []
|
|
braces = "{{" in server_english
|
|
pattern = r"\{\{(\w+)\}\}" if braces else r"%\((\w+)\)s"
|
|
for name in re.findall(pattern, server_english):
|
|
if name not in names:
|
|
names.append(name)
|
|
if braces:
|
|
translation = translation.replace("%", "%%")
|
|
for i, name in enumerate(names, start=1):
|
|
translation = translation.replace("{{" + name + "}}" if braces else 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 or "{{" 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()
|