From 42edeef51ef8c155a904ad3b43bdb28fc76ca925 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 25 Sep 2026 11:38:47 +0200 Subject: [PATCH] Add configurable localisation for authored reports --- docs/report-contract.md | 44 +++++++++++++++ examples/example-report.yaml | 2 + plugins/report/locales.json | 76 +++++++++++++++++++++++++ plugins/report/model.typ | 106 ++++++++++++++++++----------------- plugins/report/render.typ | 18 ++++++ render.sh | 1 + tests/test_plugin.py | 82 +++++++++++++++++++++++++++ 7 files changed, 277 insertions(+), 52 deletions(-) create mode 100644 plugins/report/locales.json diff --git a/docs/report-contract.md b/docs/report-contract.md index 35e51ff..3a9d925 100644 --- a/docs/report-contract.md +++ b/docs/report-contract.md @@ -9,3 +9,47 @@ a custom theme dictionary can also be provided. The renderer is `plugins/report/ The diagnostic plugin has a separate raw WinDiagnostics input and its own Typst document model. Both plugins import `reporter/visual/elements.typ` for graphical primitives. + +## Localisation + +Set the top-level `language` field to select the language of built-in report +headings and labels. English (`en`) is the default; French (`fr`) is included. +The field works in both YAML and JSON: + +```yaml +language: fr +metadata: + Author: "Marie Dupont" + Date: "2026-09-25" +title: "Rapport d’intervention" +summary: "Le service est de nouveau disponible." +``` + +This translates section headings, timeline column headings, diagnostic labels, +report-type labels, default titles, footer labels, and known metadata labels. +It also sets Typst's text language. Keep metadata keys such as `Author` and +`Date` unchanged. Authored text, explicit titles (including `actions_title`), +custom metadata labels, and status/severity values remain as supplied. + +Add any number of languages to +[`plugins/report/locales.json`](../plugins/report/locales.json), without changing +renderer code. Each top-level language code maps English labels to their +translations. For example, add this entry alongside `en` and `fr`: + +```json +"es": { + "Executive summary": "Resumen ejecutivo", + "Findings": "Hallazgos", + "Current state": "Estado actual" +} +``` + +Use a Typst-compatible language code and set `language: es` in the report. +Copy the complete `en` entry to translate every label, or start with a partial +entry: missing translations fall back to English. Values must be strings. +Unknown language codes fail validation with the available languages listed. +Language codes in reports are case-insensitive; catalog codes use lowercase. + +Localisation applies to the authored report plugin, including its diagnostic +hypotheses section. The separate raw diagnostic and consumables plugins have +their own document models. diff --git a/examples/example-report.yaml b/examples/example-report.yaml index c93e881..86b2e1f 100644 --- a/examples/example-report.yaml +++ b/examples/example-report.yaml @@ -1,3 +1,5 @@ +# Set language: fr for French headings (English by default). +# Add languages in plugins/report/locales.json. id: INC-2026-001 title: Service Interruption Investigation subtitle: Incident analysis and shift handoff diff --git a/plugins/report/locales.json b/plugins/report/locales.json new file mode 100644 index 0000000..3b58f7e --- /dev/null +++ b/plugins/report/locales.json @@ -0,0 +1,76 @@ +{ + "en": { + "Report": "Report", + "Technical report": "Technical report", + "Stakeholder briefing": "Stakeholder briefing", + "Executive summary": "Executive summary", + "Timeline": "Timeline", + "Time": "Time", + "Event": "Event", + "Notes": "Notes", + "Findings": "Findings", + "Finding": "Finding", + "EVIDENCE": "EVIDENCE", + "ASSESSMENT": "ASSESSMENT", + "Diagnostic hypotheses": "Diagnostic hypotheses", + "Diagnostic hypothesis": "Diagnostic hypothesis", + "How to read confidence": "How to read confidence", + "SCOPE": "SCOPE", + "EVIDENCE FOR": "EVIDENCE FOR", + "EVIDENCE AGAINST / LIMITATIONS": "EVIDENCE AGAINST / LIMITATIONS", + "INTERPRETATION": "INTERPRETATION", + "TESTS TO CONFIRM / REFUTE": "TESTS TO CONFIRM / REFUTE", + "Current leading assessment": "Current leading assessment", + "NOT YET SUPPORTED": "NOT YET SUPPORTED", + "Action plan": "Action plan", + "Action": "Action", + "Section": "Section", + "Current state": "Current state", + "Stopping point": "Stopping point", + "Page": "Page", + "Renderer warning": "Renderer warning", + "Unknown report block type:": "Unknown report block type:", + "Author": "Author", + "Date": "Date", + "Service": "Service", + "Environment": "Environment", + "Owner": "Owner" + }, + "fr": { + "Report": "Rapport", + "Technical report": "Rapport technique", + "Stakeholder briefing": "Note de synthèse", + "Executive summary": "Synthèse", + "Timeline": "Chronologie", + "Time": "Heure", + "Event": "Événement", + "Notes": "Notes", + "Findings": "Constats", + "Finding": "Constat", + "EVIDENCE": "ÉLÉMENTS DE PREUVE", + "ASSESSMENT": "ÉVALUATION", + "Diagnostic hypotheses": "Hypothèses diagnostiques", + "Diagnostic hypothesis": "Hypothèse diagnostique", + "How to read confidence": "Comment interpréter le niveau de confiance", + "SCOPE": "PÉRIMÈTRE", + "EVIDENCE FOR": "ÉLÉMENTS EN FAVEUR", + "EVIDENCE AGAINST / LIMITATIONS": "ÉLÉMENTS DÉFAVORABLES / LIMITES", + "INTERPRETATION": "INTERPRÉTATION", + "TESTS TO CONFIRM / REFUTE": "TESTS POUR CONFIRMER / INFIRMER", + "Current leading assessment": "Évaluation principale actuelle", + "NOT YET SUPPORTED": "PAS ENCORE ÉTAYÉ", + "Action plan": "Plan d’action", + "Action": "Action", + "Section": "Section", + "Current state": "État actuel", + "Stopping point": "Point d’arrêt", + "Page": "Page", + "Renderer warning": "Avertissement du moteur de rendu", + "Unknown report block type:": "Type de bloc de rapport inconnu :", + "Author": "Auteur", + "Date": "Date", + "Service": "Service", + "Environment": "Environnement", + "Owner": "Responsable" + } +} diff --git a/plugins/report/model.typ b/plugins/report/model.typ index 12aea4a..4bf6553 100644 --- a/plugins/report/model.typ +++ b/plugins/report/model.typ @@ -19,13 +19,13 @@ #import "/visual/elements.typ": dict-get, as-content, theme-color, severity-color, badge, metadata-line, section-title, subsection-title, callout, code-block -#let report-type-label(value) = { +#let report-type-label(value, t) = { let value = lower(str(value)) if value == "technical" { - "Technical report" + t("Technical report") } else if value == "briefing" { - "Stakeholder briefing" + t("Stakeholder briefing") } else { str(value) } @@ -35,7 +35,7 @@ // ----- Generic content renderer // ----------------------------------------------------------------------------- -#let render-block(theme, block-data) = { +#let render-block(theme, block-data, t) = { let kind = dict-get(block-data, "type", "text") if kind == "text" { @@ -75,17 +75,17 @@ ) for child in dict-get(block-data, "content", ()) { - render-block(theme, child) + render-block(theme, child, t) v(0.4em) } } else { callout( theme, [ - Unknown report block type: + #t("Unknown report block type:") #raw(str(kind)) ], - title: "Renderer warning", + title: t("Renderer warning"), kind: "warning", ) } @@ -96,9 +96,9 @@ // ----- Findings // ----------------------------------------------------------------------------- -#let render-findings(theme, findings) = { +#let render-findings(theme, findings, t) = { for finding in findings { - let title = dict-get(finding, "title", "Finding") + let title = dict-get(finding, "title", t("Finding")) let severity = dict-get(finding, "severity", "info") let status = dict-get(finding, "status", none) let evidence = dict-get(finding, "evidence", none) @@ -144,7 +144,7 @@ size: 8pt, weight: "bold", fill: theme-color(theme, "muted"), - )[EVIDENCE] + )[#t("EVIDENCE")] v(2pt) @@ -161,7 +161,7 @@ size: 8pt, weight: "bold", fill: theme-color(theme, "muted"), - )[ASSESSMENT] + )[#t("ASSESSMENT")] v(2pt) @@ -181,13 +181,13 @@ // ----- Timeline // ----------------------------------------------------------------------------- -#let render-timeline(theme, entries) = { +#let render-timeline(theme, entries, t) = { let rows = ( ( table.header( - [Time], - [Event], - [Notes], + [#t("Time")], + [#t("Event")], + [#t("Notes")], ), ) ) @@ -270,7 +270,7 @@ } } -#let render-diagnostics(theme, diagnostics) = { +#let render-diagnostics(theme, diagnostics, t) = { let scale = dict-get(diagnostics, "confidence_scale", (:)) let interpretation = dict-get(scale, "interpretation", none) let hypotheses = dict-get(diagnostics, "hypotheses", ()) @@ -281,7 +281,7 @@ callout( theme, [#as-content(interpretation)], - title: "How to read confidence", + title: t("How to read confidence"), kind: "info", ) v(7pt) @@ -289,7 +289,7 @@ for hypothesis in hypotheses { let id = dict-get(hypothesis, "id", "Dx") - let diagnosis = dict-get(hypothesis, "diagnosis", "Diagnostic hypothesis") + let diagnosis = dict-get(hypothesis, "diagnosis", t("Diagnostic hypothesis")) let confidence = dict-get(hypothesis, "confidence_percent", 0) let status = dict-get(hypothesis, "status", none) let scope = dict-get(hypothesis, "scope", none) @@ -322,26 +322,26 @@ #if scope != none { v(3pt) text(size: 7.5pt, fill: theme-color(theme, "muted"))[ - SCOPE: #upper(str(scope)) + #t("SCOPE"): #upper(str(scope)) ] } #if evidence-for.len() > 0 { v(6pt) - diagnostic-list(theme, "EVIDENCE FOR", evidence-for) + diagnostic-list(theme, t("EVIDENCE FOR"), evidence-for) } #if evidence-against.len() > 0 { v(5pt) - diagnostic-list(theme, "EVIDENCE AGAINST / LIMITATIONS", evidence-against) + diagnostic-list(theme, t("EVIDENCE AGAINST / LIMITATIONS"), evidence-against) } #if hypothesis-interpretation != none { v(5pt) - text(size: 7.5pt, weight: "bold", fill: theme-color(theme, "muted"))[INTERPRETATION] + text(size: 7.5pt, weight: "bold", fill: theme-color(theme, "muted"))[#t("INTERPRETATION")] v(2pt) text(size: 8.5pt)[#as-content(hypothesis-interpretation)] } #if tests.len() > 0 { v(5pt) - diagnostic-list(theme, "TESTS TO CONFIRM / REFUTE", tests) + diagnostic-list(theme, t("TESTS TO CONFIRM / REFUTE"), tests) } ] v(6pt) @@ -359,14 +359,14 @@ } #as-content(statement) ], - title: "Current leading assessment", + title: t("Current leading assessment"), kind: "warning", ) } if unsupported.len() > 0 { v(7pt) - diagnostic-list(theme, "NOT YET SUPPORTED", unsupported) + diagnostic-list(theme, t("NOT YET SUPPORTED"), unsupported) } } @@ -375,9 +375,9 @@ // ----- Action plan // ----------------------------------------------------------------------------- -#let render-actions(theme, actions) = { +#let render-actions(theme, actions, t) = { for (index, action) in actions.enumerate() { - let title = dict-get(action, "title", "Action") + let title = dict-get(action, "title", t("Action")) let status = dict-get(action, "status", "pending") let body = dict-get(action, "text", none) let commands = dict-get(action, "commands", ()) @@ -448,13 +448,13 @@ // ----- Header / Footer // ----------------------------------------------------------------------------- -#let report-header(theme, report, logo) = { +#let report-header(theme, report, logo, t) = { let organization = dict-get(report, "organization", "Beffroi") let report-type = dict-get(report, "report_type", none) let descriptor = if report-type == none { - "Report" + t("Report") } else { - report-type-label(report-type) + report-type-label(report-type, t) } grid( @@ -484,7 +484,7 @@ ) } -#let report-footer(theme, report) = { +#let report-footer(theme, report, t) = { let id = dict-get(report, "id", none) grid( @@ -495,14 +495,14 @@ fill: theme-color(theme, "muted"), )[ #if id != none { - [Report #id] + [#t("Report") #id] } ], text( size: 7pt, fill: theme-color(theme, "muted"), )[ - Page #context counter(page).display() + #t("Page") #context counter(page).display() ], ) } @@ -516,6 +516,8 @@ report: (:), theme: (:), logo: "/assets/beffroi.png", + language: "en", + t: value => value, body, ) = { set page( @@ -526,15 +528,15 @@ left: 20mm, right: 20mm, ), - header: context report-header(theme, report, logo), - footer: context report-footer(theme, report), + header: context report-header(theme, report, logo, t), + footer: context report-footer(theme, report, t), ) set text( font: dict-get(theme, "font", "DejaVu Sans"), size: 9.5pt, fill: theme-color(theme, "ink"), - lang: "en", + lang: language, ) set par( @@ -547,7 +549,7 @@ // Title block // --------------------------------------------------------------------------- - let title = dict-get(report, "title", "Report") + let title = dict-get(report, "title", t("Report")) let subtitle = dict-get(report, "subtitle", none) let report-type = dict-get(report, "report_type", none) let status = dict-get(report, "status", none) @@ -581,7 +583,7 @@ if report-type != none { badge( - report-type-label(report-type), + report-type-label(report-type, t), color: theme-color(theme, "accent"), ) @@ -632,7 +634,7 @@ .pairs() .map(pair => metadata-line( theme, - pair.at(0), + t(pair.at(0)), pair.at(1), )) ) @@ -646,7 +648,7 @@ let summary = dict-get(report, "summary", none) if summary != none { - section-title(theme, "Executive summary") + section-title(theme, t("Executive summary")) callout( theme, @@ -662,8 +664,8 @@ let timeline = dict-get(report, "timeline", ()) if timeline.len() > 0 { - section-title(theme, "Timeline") - render-timeline(theme, timeline) + section-title(theme, t("Timeline")) + render-timeline(theme, timeline, t) } // --------------------------------------------------------------------------- @@ -673,8 +675,8 @@ let findings = dict-get(report, "findings", ()) if findings.len() > 0 { - section-title(theme, "Findings") - render-findings(theme, findings) + section-title(theme, t("Findings")) + render-findings(theme, findings, t) } // --------------------------------------------------------------------------- @@ -685,8 +687,8 @@ let hypotheses = dict-get(diagnostics, "hypotheses", ()) if hypotheses.len() > 0 { - section-title(theme, "Diagnostic hypotheses") - render-diagnostics(theme, diagnostics) + section-title(theme, t("Diagnostic hypotheses")) + render-diagnostics(theme, diagnostics, t) } // --------------------------------------------------------------------------- @@ -699,12 +701,12 @@ section-title( theme, as-content( - dict-get(section, "title", "Section"), + dict-get(section, "title", t("Section")), ), ) for block-data in dict-get(section, "content", ()) { - render-block(theme, block-data) + render-block(theme, block-data, t) v(0.45em) } } @@ -718,10 +720,10 @@ if actions.len() > 0 { section-title( theme, - dict-get(report, "actions_title", "Action plan"), + dict-get(report, "actions_title", t("Action plan")), ) - render-actions(theme, actions) + render-actions(theme, actions, t) } // --------------------------------------------------------------------------- @@ -731,12 +733,12 @@ let closing = dict-get(report, "closing", none) if closing != none { - section-title(theme, "Current state") + section-title(theme, t("Current state")) callout( theme, [#as-content(closing)], - title: "Stopping point", + title: t("Stopping point"), kind: dict-get(report, "severity", "info"), breakable: false, ) diff --git a/plugins/report/render.typ b/plugins/report/render.typ index b9e6c5c..716224e 100644 --- a/plugins/report/render.typ +++ b/plugins/report/render.typ @@ -28,6 +28,22 @@ ) } +// Catalog entries use English labels as keys; partial locales fall back to English. +#let locales = json("config/locales.json") +#let language = report.at("language", default: "en") +#if type(language) != str { + panic("Report language must be a string, for example language: fr") +} +#let language = lower(language) +#if language not in locales { + panic("Unknown report language: " + language + ". Available languages: " + locales.keys().join(", ")) +} +#let messages = locales.at(language) +#if type(messages) != dictionary or messages.values().any(value => type(value) != str) { + panic("Report language catalog must map labels to strings: " + language) +} +#let translate(value) = messages.at(value, default: locales.en.at(value, default: value)) + #let themes = yaml("config/themes.yaml") #let theme-choice = report.at("theme", default: report.at("branding", default: (:)).at("theme", default: "default")) #let theme-name = if type(theme-choice) == str { lower(theme-choice) } else { "custom" } @@ -44,6 +60,8 @@ #show: report-model.with( report: report, + language: language, + t: translate, theme: theme, logo: "/assets/beffroi.png", ) diff --git a/render.sh b/render.sh index a813470..6531381 100755 --- a/render.sh +++ b/render.sh @@ -26,6 +26,7 @@ stage=$RENDER_STAGE mkdir -p "$stage/modules" "$stage/config" "$stage/assets" "$stage/reports" "$stage/visual" cp -- "$root/plugins/report/render.typ" "$stage/report.typ" cp -- "$root/plugins/report/model.typ" "$stage/modules/model.typ" +cp -- "$root/plugins/report/locales.json" "$stage/config/locales.json" cp -- "$root/visual/themes.yaml" "$stage/config/themes.yaml" cp -- "$root/visual/beffroi.png" "$stage/assets/beffroi.png" cp -- "$root/visual/elements.typ" "$stage/visual/elements.typ" diff --git a/tests/test_plugin.py b/tests/test_plugin.py index 4202e14..f0909db 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -1,4 +1,6 @@ from pathlib import Path +import json +import shutil import subprocess import tempfile import unittest @@ -7,6 +9,86 @@ ROOT = Path(__file__).resolve().parents[1] class ReportPluginTests(unittest.TestCase): + def render_text(self, source, work, root=ROOT): + output = work / 'report.pdf' + result = subprocess.run([str(root / 'build.sh'), 'render', 'report', str(source), + '--output', str(output), '--force'], text=True, capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + return subprocess.check_output(['pdftotext', '-layout', str(output), '-'], text=True) + + def test_localised_report_headings_and_authored_content(self): + report = json.loads((ROOT / 'examples/example-report.json').read_text()) + report.pop('actions_title') + report['diagnostics'] = { + 'confidence_scale': {'interpretation': 'Authored confidence explanation'}, + 'hypotheses': [{'scope': 'system', 'evidence_for': ['For'], + 'evidence_against': ['Against'], 'interpretation': 'Authored interpretation', + 'tests_to_confirm': ['Test']}], + 'current_leading_assessment': {'statement': 'Authored assessment'}, + 'not_yet_supported': ['Unsupported'], + } + report['sections'].append({'content': [{'type': 'subsection', 'content': [{'type': 'unknown'}]}]}) + report['findings'].append({'evidence': 'Authored evidence'}) + report['actions'].append({'text': 'Authored action'}) + catalog = json.loads((ROOT / 'plugins/report/locales.json').read_text()) + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + source = work / 'input.json' + source.write_text(json.dumps(report)) + default = self.render_text(source, work) + report['language'] = 'en' + source.write_text(json.dumps(report)) + self.assertEqual(default, self.render_text(source, work)) + report['language'] = 'fr' + source.write_text(json.dumps(report)) + french = self.render_text(source, work) + for label, translation in catalog['fr'].items(): + if label == 'Stakeholder briefing': + continue + with self.subTest(label=label): + self.assertIn(translation, french) + self.assertIn(report['title'], french) + self.assertIn('Authored confidence explanation', french) + self.assertIn('Operational precautions', french) + self.assertNotIn('Executive summary', french) + report['actions_title'] = 'Authored action heading' + source.write_text(json.dumps(report)) + self.assertIn('Authored action heading', self.render_text(source, work)) + + def test_yaml_language_and_invalid_language(self): + source_text = (ROOT / 'examples/example-report.yaml').read_text() + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + source = work / 'input.yaml' + source.write_text('language: fr\n' + source_text) + self.assertIn('Synthèse', self.render_text(source, work)) + for value, message in [('unknown', 'Unknown report language'), ('[fr]', 'must be a string')]: + source.write_text(f'language: {value}\n' + source_text) + result = subprocess.run([str(ROOT / 'build.sh'), 'validate', 'report', str(source)], + text=True, capture_output=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn(message, result.stderr) + + def test_additional_catalog_language_and_english_fallback(self): + with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + root = work / 'reportist' + root.mkdir() + for name in ('build.sh', 'render.sh'): + shutil.copy2(ROOT / name, root / name) + for name in ('tools', 'visual', 'plugins/report'): + shutil.copytree(ROOT / name, root / name) + catalog_path = root / 'plugins/report/locales.json' + catalog = json.loads(catalog_path.read_text()) + catalog['es'] = {'Executive summary': 'Resumen ejecutivo'} + catalog_path.write_text(json.dumps(catalog)) + source = work / 'input.yaml' + source.write_text('language: es\n' + (ROOT / 'examples/example-report.yaml').read_text()) + rendered = self.render_text(source, work, root) + self.assertIn('Resumen ejecutivo', rendered) + self.assertIn('Findings', rendered) + self.assertNotIn('Executive summary', rendered) + def test_new_palettes_render_in_both_plugins(self): palettes = ("warm", "steel", "bw", "high-contrast", "yon-sen", "steingrund", "draan") capture = ROOT / "plugins/diagnostics/tests/fixtures/legacy/windiagnostics-v1.json"