diff --git a/apps/board/strings/sitio.yaml b/apps/board/strings/sitio.yaml index 8b16a5b..6104502 100644 --- a/apps/board/strings/sitio.yaml +++ b/apps/board/strings/sitio.yaml @@ -140,3 +140,27 @@ site.askmasto: de: "Auf welchem Mastodon-Server hast du dein Konto? Zum Beispiel: mastodon.social" pt-br: "Em qual servidor do Mastodon está a sua conta? Por exemplo: mastodon.social" _note: "La pregunta antes de compartir en Mastodon." + +site.sections: + es: "Secciones" + de: "Bereiche" + pt-br: "Seções" + _note: "No se ve: nombra la barra de navegación para un lector de pantalla." + +site.language: + es: "Idioma" + de: "Sprache" + pt-br: "Idioma" + _note: "No se ve: nombra el selector de idioma." + +site.pages: + es: "Páginas del sitio" + de: "Seiten" + pt-br: "Páginas do site" + _note: "No se ve: nombra la lista de páginas del pie." + +site.social: + es: "Redes" + de: "Soziale Netzwerke" + pt-br: "Redes" + _note: "No se ve: nombra los iconos de redes del pie." diff --git a/apps/board/tests/test_strings.py b/apps/board/tests/test_strings.py index 038d597..5638ac1 100644 --- a/apps/board/tests/test_strings.py +++ b/apps/board/tests/test_strings.py @@ -82,6 +82,33 @@ def test_every_theme_call_site_passes_the_page_explicitly(): f"build inside a `with`: {offenders}") +def test_nothing_reads_the_site_name_around_the_override(): + """`site-name.html` and `site-tagline.html` exist so that Gestión → + Identidad can rename the site. Reading `.Site.Title` directly goes round + them. + + That had been true since Identidad shipped, and quietly: the human-facing + surfaces were converted and the machine-facing ones were not, so renaming + the site updated every og: tag and left the old name in every JSON-LD + `publisher`, `author` and `isPartOf`, in `llms.txt` and in the .ics product + id. The home page emitted two JSON-LD blocks that disagreed with each other. + """ + offenders = [] + for path in THEME.rglob("*"): + if not path.is_file() or path.suffix in (".css", ".js", ".toml"): + continue + # The two partials are the override; reading the config is their job. + if path.name in ("site-name.html", "site-tagline.html"): + continue + for line_no, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + code = line.split("*/")[-1] if "*/" in line else line + if re.search(r"\{\{[^}]*\bsite\.(Title|Params\.description)\b", code, re.I): + offenders.append(f"{path.relative_to(THEME)}:{line_no}") + assert not offenders, ( + "these read the site's name or tagline directly instead of through " + f"site-name.html / site-tagline.html, so Identidad cannot reach them: {offenders}") + + def test_the_theme_and_the_catalogue_agree_on_the_public_defaults(): """Two copies, deliberately — Hugo reads the repository and the members area reads its own image, and neither can read the other's file. The same trade @@ -335,3 +362,136 @@ def test_erasing_whoever_chose_the_words_leaves_them_standing(client, db, post, row = db.execute("SELECT strings_json, updated_by FROM strings").fetchone() assert json.loads(row["strings_json"]) == {"nav.inicio": {"es": "Escritorio"}} assert row["updated_by"] is None + + +# --- the pipeline filling a language somebody left empty ------------------- + +def _translate_module(): + """`scripts/translate.py` is a script, not a package — same loader + `test_content.py` uses.""" + import importlib.util + import sys + sys.path.insert(0, str(ROOT / "scripts")) + spec = importlib.util.spec_from_file_location( + "vl_translate_ui", ROOT / "scripts" / "translate.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class _Shouty: + """A provider that never loads a model. What matters here is which strings + were asked for and how often — the engine is tested in its own suite.""" + + def __init__(self): + self.asked = [] + + def translate(self, texts, src, tgt): + self.asked += [(text, src, tgt) for text in texts] + return [f"{text.upper()}-{tgt}" for text in texts] + + +@pytest.fixture +def pipeline(tmp_path, monkeypatch): + """translate.py pointed at a throwaway `data/` directory.""" + module = _translate_module() + monkeypatch.setattr(module, "UI_FILE", tmp_path / "ui.yaml") + monkeypatch.setattr(module, "UI_AUTO_FILE", tmp_path / "ui_auto.yaml") + return module + + +def test_a_language_left_empty_is_filled_from_the_spanish(pipeline): + pipeline.UI_FILE.write_text('home:\n es: "Escritorio"\n', encoding="utf-8") + provider = _Shouty() + + written = pipeline.translate_ui(lambda: provider) + + assert written == [pipeline.UI_AUTO_FILE] + out = pipeline.UI_AUTO_FILE.read_text(encoding="utf-8") + assert 'de: "ESCRITORIO-de"' in out + assert 'pt-br: "ESCRITORIO-pt-br"' in out + # The Spanish it came from, so a reword can invalidate it. + assert '_source: "Escritorio"' in out + # And Spanish is never translated into itself. + assert all(tgt != "es" for _, _, tgt in provider.asked) + + +def test_a_language_somebody_typed_is_left_alone(pipeline): + """The three boxes are the real path; this only fills what was skipped.""" + pipeline.UI_FILE.write_text( + 'home:\n es: "Escritorio"\n de: "Schreibtisch"\n', encoding="utf-8") + provider = _Shouty() + + pipeline.translate_ui(lambda: provider) + + out = pipeline.UI_AUTO_FILE.read_text(encoding="utf-8") + assert "Schreibtisch" not in out, "a hand-written language must not be regenerated" + assert [tgt for _, _, tgt in provider.asked] == ["pt-br"] + + +def test_nothing_is_translated_twice(pipeline): + """A push that changed no label must not re-run the engine — and must not + rewrite the file, or every build would commit a no-op.""" + pipeline.UI_FILE.write_text('home:\n es: "Escritorio"\n', encoding="utf-8") + pipeline.translate_ui(lambda: _Shouty()) + + second = _Shouty() + written = pipeline.translate_ui(lambda: second) + + assert second.asked == [] + assert written == [] + + +def test_rewording_the_spanish_redoes_the_translation(pipeline): + """What `_source` is for. Without it the German would describe a label + nobody uses any more, and nothing would ever say so.""" + pipeline.UI_FILE.write_text('home:\n es: "Escritorio"\n', encoding="utf-8") + pipeline.translate_ui(lambda: _Shouty()) + + pipeline.UI_FILE.write_text('home:\n es: "Novedades"\n', encoding="utf-8") + again = _Shouty() + pipeline.translate_ui(lambda: again) + + out = pipeline.UI_AUTO_FILE.read_text(encoding="utf-8") + assert 'de: "NOVEDADES-de"' in out and "ESCRITORIO" not in out + assert '_source: "Novedades"' in out + + +def test_the_model_is_not_loaded_when_there_is_nothing_to_fill(pipeline): + """Loading a 237MB model to decide there is no work is the difference + between a push that costs seconds and one that costs a minute, and most + pushes change no labels at all.""" + pipeline.UI_FILE.write_text( + 'home:\n es: "Escritorio"\n de: "Schreibtisch"\n pt-br: "Escrivaninha"\n', + encoding="utf-8") + + def refuse(): + raise AssertionError("the provider was built with nothing to translate") + + assert pipeline.translate_ui(refuse) == [] + + +def test_a_key_with_no_spanish_is_not_guessed_at(pipeline): + """Nothing authored means nothing to translate from — the theme's own + default stands in every language.""" + pipeline.UI_FILE.write_text('home:\n de: "Schreibtisch"\n', encoding="utf-8") + + def refuse(): + raise AssertionError("the provider was built with no source language") + + assert pipeline.translate_ui(refuse) == [] + + +def test_no_overrides_at_all_means_no_file(pipeline): + assert pipeline.translate_ui(lambda: _Shouty()) == [] + assert not pipeline.UI_AUTO_FILE.exists() + + +def test_a_quote_in_a_translation_cannot_break_the_file(pipeline): + pipeline.UI_FILE.write_text('home:\n es: "El \\"Escritorio\\""\n', encoding="utf-8") + + pipeline.translate_ui(lambda: _Shouty()) + + import yaml + loaded = yaml.safe_load(pipeline.UI_AUTO_FILE.read_text(encoding="utf-8")) + assert loaded["home"]["_source"] == 'El "Escritorio"' diff --git a/docs/server-setup.md b/docs/server-setup.md index 5690617..52e0505 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -1619,6 +1619,49 @@ The public menu keeps its entry in `config.yaml` — a data file cannot override carries `identifier: home`, and `header.html` looks its *label* up in the table. The entry and its weight stay in config; the word is editable. +**`$.` and never a bare `.`** at a `t.html` call site. Inside a `{{ with }}` the +dot is whatever that block holds — `.Params.author` is a string — and `.Site` on +a string fails the build rather than producing a wrong word. Two call sites +shipped that way and only broke on a post that happened to carry an `author`; a +guard now holds every call site to `$.`. + +#### A language left empty, filled by the pipeline + +`scripts/translate.py` gained a pass over `data/ui.yaml` — it walked `content/` +only before, so `data/` had never been touched by it. For every key with Spanish +set and a language left blank, it translates and writes **`data/ui_auto.yaml`**. + +**Two files, not one, and that is the design.** `ui.yaml` is regenerated +wholesale from the override store every time somebody presses *Guardar*, so +anything the pipeline wrote into it would be destroyed by the next save — and +the members area cannot write back into the repository's copy. Each file has one +writer that owns it outright, and the split names the provenance. + +Each entry records the Spanish it came **from**, as `_source`. Reword the +Spanish and the stored German stops matching and is translated again; leave it +alone and nothing is recomputed, so a build that changed no label commits +nothing and never loads the model. + +`t.html`'s order is therefore **override → automatic → shipped → Spanish**. The +automatic file only ever holds a key whose Spanish was overridden, so it beats +the shipped word without displacing one nobody touched: rename «Inicio» to +«Escritorio» and the shipped «Start» is no longer a translation of anything. + +Said once, plainly: a one-word label is the worst case for machine translation. +This fills a box somebody left empty; the screen has three boxes so it does not +have to be relied on. + +#### A bug this phase found rather than caused + +`site-name.html` and `site-tagline.html` have existed since §11.18b so that +Identidad can rename the site — and **eleven places read `.Site.Title` or +`.Site.Params.description` directly**, going round them. The human-facing +surfaces had been converted and the machine-facing ones had not, so renaming the +site updated every `og:` tag and left the old name in every JSON-LD `publisher`, +`author` and `isPartOf`, in `llms.txt` and in the `.ics` product id — the home +page emitted two JSON-LD blocks that openly disagreed. All eleven now read +through the partials, and a guard fails on a twelfth. + ### 11.20 The three admin tools **Estado del sistema** (superadministrator). The backups panel reads diff --git a/scripts/translate.py b/scripts/translate.py index fc7d0b4..11908e9 100644 --- a/scripts/translate.py +++ b/scripts/translate.py @@ -57,6 +57,17 @@ def build_provider(): REPO_ROOT = Path(__file__).resolve().parent.parent CONTENT_DIR = REPO_ROOT / "content" +# The site's own labels — menu entries, button words — written by Gestión → +# Textos, and the file this script fills the gaps in. Two files rather than one +# because each has a writer that owns it outright: `ui.yaml` is regenerated +# wholesale from the members area's override store on every save, so anything +# written into it here would be destroyed by the next person to press Guardar, +# and the members area cannot write back into the repository's copy. Keeping +# them apart also names the provenance, which matters for a machine +# translation of a one-word label. +UI_FILE = REPO_ROOT / "data" / "ui.yaml" +UI_AUTO_FILE = REPO_ROOT / "data" / "ui_auto.yaml" + # Frontmatter strings translated alongside the body. # `event_location` is deliberately absent: an address is how somebody finds the # place, and a translated street or venue name is worse than an untranslated one. @@ -282,6 +293,92 @@ def translate_file(source: Path, basename: str, src_lang: str, provider) -> list return written +def translate_ui(provider_factory) -> list[Path]: + """Fill the languages Gestión → Textos left empty. + + A label is prose with no markup, so `translate_text` handles it directly — + it already protects «Viena Latina» as a term, which is the one thing in a + menu that must survive. + + Each entry records the Spanish it was translated **from**. Reword the + Spanish and the stored German stops matching its source and is translated + again; leave it alone and nothing is recomputed. Without that the file would + drift into German that describes a label nobody uses any more, and nothing + would ever say so. + + Worth stating plainly, once: a one-word label is the worst case for machine + translation. This is a fallback for a box somebody left empty, not the + intended path — the screen has a box per language precisely so this does not + have to be relied on. + """ + if not UI_FILE.exists(): + return [] + overrides = yaml.safe_load(UI_FILE.read_text(encoding="utf-8")) or {} + previous = {} + if UI_AUTO_FILE.exists(): + previous = yaml.safe_load(UI_AUTO_FILE.read_text(encoding="utf-8")) or {} + + wanted = {} + for key, values in overrides.items(): + if not isinstance(values, dict): + continue + source = str(values.get("es", "")).strip() + if not source: + # Nothing authored in Spanish, so there is nothing to translate + # from. The theme's own default stands in every language. + continue + missing = [lang for lang in SITE_LANGS + if lang != "es" and not str(values.get(lang, "")).strip()] + if not missing: + continue + wanted[key] = (source, missing) + + if not wanted and previous == {}: + return [] + + # Only now, because loading a 237MB model to decide there is nothing to do + # is the difference between a push that costs seconds and one that costs a + # minute. Most pushes change no labels at all. + provider = None + filled = {} + for key, (source, missing) in sorted(wanted.items()): + before = previous.get(key) or {} + keep = str(before.get("_source", "")) == source + entry = {"_source": source} + for lang in missing: + if keep and str(before.get(lang, "")).strip(): + entry[lang] = before[lang] + continue + if provider is None: + print("Translating the site's own labels:") + provider = provider_factory() + entry[lang] = translate_text(source, "es", lang, provider) + print(f" {key} [{lang}]: {source!r} -> {entry[lang]!r}") + filled[key] = entry + + if filled == {k: v for k, v in previous.items()}: + return [] + + UI_AUTO_FILE.parent.mkdir(parents=True, exist_ok=True) + lines = ["# Traducciones automáticas de los textos de Gestión → Textos.", + "# Las escribe el pipeline; lo escrito a mano está en ui.yaml y manda.", + "# `_source` es el español del que salió cada una: si cambia, se rehace."] + for key in sorted(filled): + lines.append(f"{key}:") + for lang in SITE_LANGS: + if lang != "es" and filled[key].get(lang): + lines.append(f" {lang}: {_quote(filled[key][lang])}") + lines.append(f" _source: {_quote(filled[key]['_source'])}") + UI_AUTO_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8") + return [UI_AUTO_FILE] + + +def _quote(value: str) -> str: + """A double-quoted YAML scalar. Backslashes and quotes are the only two + characters that can end one, and both are escapable inside it.""" + return '"' + str(value).replace("\\", "\\\\").replace('"', '\\"') + '"' + + def commit_and_push(files: list[Path], summary: str) -> None: branch = os.environ.get("CI_COMMIT_BRANCH", "main") run("git", "config", "user.name", BOT_NAME) @@ -335,6 +432,12 @@ def main() -> None: removed.append(orphan) print(f" {orphan.relative_to(REPO_ROOT)}: source deleted — removed") + # The site's own labels, which live in `data/` and so are outside everything + # above — `changed_markdown` filters on the `content/` prefix, so a push + # that only touches a label reaches here with no sources at all, which is + # exactly the case this fills. + written.extend(translate_ui(build_provider)) + touched = written + removed if not touched: print("Nothing to commit.") diff --git a/themes/vienalatina/layouts/_default/single.ics b/themes/vienalatina/layouts/_default/single.ics index 60fa6da..3552e95 100644 --- a/themes/vienalatina/layouts/_default/single.ics +++ b/themes/vienalatina/layouts/_default/single.ics @@ -17,7 +17,7 @@ {{- $stamp := now.UTC.Format "20060102T150405Z" -}} BEGIN:VCALENDAR{{ printf "\r" }} VERSION:2.0{{ printf "\r" }} -PRODID:-//{{ .Site.Title }}//agenda//ES{{ printf "\r" }} +PRODID:-//{{ partial "site-name.html" . }}//agenda//ES{{ printf "\r" }} CALSCALE:GREGORIAN{{ printf "\r" }} METHOD:PUBLISH{{ printf "\r" }} BEGIN:VEVENT{{ printf "\r" }} diff --git a/themes/vienalatina/layouts/index.llms.txt b/themes/vienalatina/layouts/index.llms.txt index 5429f58..9dbb79b 100644 --- a/themes/vienalatina/layouts/index.llms.txt +++ b/themes/vienalatina/layouts/index.llms.txt @@ -1,6 +1,6 @@ -# {{ .Site.Title }} +# {{ partial "site-name.html" . }} -> {{ .Site.Params.description }} +> {{ partial "site-tagline.html" . }} Site home: {{ .Site.Home.Permalink }} diff --git a/themes/vienalatina/layouts/partials/breadcrumbs-schema.html b/themes/vienalatina/layouts/partials/breadcrumbs-schema.html index 1db445c..19efba4 100644 --- a/themes/vienalatina/layouts/partials/breadcrumbs-schema.html +++ b/themes/vienalatina/layouts/partials/breadcrumbs-schema.html @@ -9,7 +9,7 @@ A subpage says Inicio → its parent → itself, read from the same `parent` basename the menu is built from, so the trail and the menu cannot disagree. */}} -{{ $items := slice (dict "@type" "ListItem" "position" 1 "name" "Inicio" "item" .Site.Home.Permalink) }} +{{ $items := slice (dict "@type" "ListItem" "position" 1 "name" (partial "t.html" (dict "key" "home" "lang" $.Site.Language.Lang)) "item" .Site.Home.Permalink) }} {{ $position := 2 }} {{ if ne .Section "post" }} diff --git a/themes/vienalatina/layouts/partials/footer.html b/themes/vienalatina/layouts/partials/footer.html index 49dce01..4020fd5 100644 --- a/themes/vienalatina/layouts/partials/footer.html +++ b/themes/vienalatina/layouts/partials/footer.html @@ -2,7 +2,7 @@