Skip to content

Latest commit

 

History

History
110 lines (73 loc) · 12.3 KB

localization.md

File metadata and controls

110 lines (73 loc) · 12.3 KB

WriterAgent localization (i18n)

This document describes how translated UI strings are produced, loaded at runtime, and maintained. It replaces the older split between a “plan” and a short overview.

What ships today

  • GNU gettext (.pot template, per-locale writeragent.po, compiled writeragent.mo under locales/<lang>/LC_MESSAGES/).
  • Runtime loading in plugin/framework/i18n.py: init_i18n() installs a gettext.translation for domain writeragent; user code wraps strings with _().
  • Locale source: LibreOffice’s UI locale from configuration path /org.openoffice.Setup/L10N → property ooLocale (see get_lo_locale()). Values like en-US are normalized to gettext-style en_US. If lookup fails, the code falls back to en_US so behavior stays predictable in tests or early init.
  • Missing strings: fallback=True on the translation object means untranslated or absent catalogs show the English msgid.

There is no separate “UI language” override in writeragent.json today: displayed language follows LibreOffice’s UI locale plus whichever .mo files are packaged for that locale.

How strings get into the template

String extraction and catalog updates are driven by scripts/extract_strings.py.

  1. Python: User-visible literals should use _('...') (or the same pattern with format strings). After init_i18n(), _() delegates to gettext.

  2. XDL dialogs: English strings in .xdl files are not read by xgettext directly. scripts/extract_xdl_strings.py generates a temporary plugin/xdl_strings.py containing _() calls so those strings are picked up; that stub is removed after extraction.

  3. Input list & xgettext: Python files are collected depth-first and written to a temporary list file passed to xgettext via -f. --keyword=N_ is passed on both extract-strings and refresh-pot paths (extracts _ and N_). Slash-command English ids are registered with N_("help"), …; translators map those msgids to a localized alias in each locale's catalog. At runtime _() resolves the display name and typed-alias matching for the active catalog only; a missing or identity translation keeps the English id.

  4. Module metadata: scripts/merge_module_yaml_into_pot.py merges translatable entries from plugin/**/module.yaml (titles, labels, helpers, button_text, options) into the same POT, deduplicated by msgid. button_text is the button caption (dlg:value → Label); translate_dialog already calls _() on it, so a missing catalog entry stays English. Requires polib and PyYAML.

  5. Dialogs at runtime: translate_dialog in plugin/chatbot/dialogs.py walks controls and applies translated text. Do not pass raw saved config values through _(): empty strings can pick up gettext header garbage. Config validation strips bogus gettext headers; see tests/framework/test_i18n.py.

    Combos rebuilt in Python after translate_dialog (sidebar image aspect) must pass display strings through _("Square")-style literals. Stored image_default_aspect stays the English label; canonical_aspect_label maps the visible text back before the image-tool enum. The chat role prefix is _("Assistant:") in append_rich_text_with_span, not a bare literal.

  6. Monaco editor (pywebview): User-visible strings live in Python only — plugin/scripting/editor_ui_strings.py. launch_monaco_editor() enriches every IPC load message with a pre-translated ui dict; editor.js applies it in applyLoadMessage(). Add new shell strings in Python _(), run make extract-strings, then read the key from load.ui in JS. See scripting/monaco-editor-dev-plan.md § Localization.

Build and maintenance commands

Target Role
make extract-strings Full pipeline via scripts/extract_strings.py: XDL stub → xgettext (-f, --keyword=N_) → YAML merge → delete stub → merge-translations on every writeragent.po. Use when sources change and you want POT and all POs updated.
make refresh-pot scripts/extract_strings.py --pot-only: regenerates writeragent.pot only (with --keyword=N_) without merging into .po files.
make preview-translations refresh-pot then scripts/translate_missing.py --preview (status table of completion vs POT). Used by normal make build.
make merge-translations scripts/extract_strings.py --merge-only: for each writeragent.po, msgmerge --update from writeragent.pot, then msgattrib --no-obsolete so removed strings do not linger as obsolete entries.
make compile-translations Compile every .po to .mo via scripts/compile_translations.py (polib.save_as_mofile; no GNU msgfmt / find). Required for LibreOffice and for unit tests that load catalogs.
make compile-translations-core LibrePy only: build build/generated/librepy.pot from bundled sources (_() and N_() via ast, no GNU xgettext), filter each writeragent.po to those msgids, compile slim .mo with polib (no msgfmt) under build/generated/locales/ (part of make build-core). Windows CI does not have gettext on PATH (GHA 33780509372).
make add-language LANG=xx Creates locales/xx/LC_MESSAGES/writeragent.po from the POT and compiles an initial .mo.

Note: make build runs preview-translations (refresh POT + preview), not necessarily the full extract-strings + merge. Run make extract-strings when you add or change marked strings and need all locale files updated from the new template.

Release / AI assist: make release-build uses auto-translate (scripts/extract_strings.py --auto-translate), which regenerates strings with extract-strings, previews, then (if OPENROUTER_API_KEY is set) runs translate_missing.py --execute to fill gaps. Manual runs: make translate-missing or python scripts/translate_missing.py --execute.

AI-assisted gap filling (scripts/translate_missing.py)

Optional automation for translators:

  • Compares each locale’s writeragent.po to writeragent.pot and finds missing, empty, or fuzzy entries.
  • --preview prints the completion table (POT totals, pending, done, percentage) and exits; used by make preview-translations / make build.
  • With --execute, prints that same table at start unless --skip-initial-status, then fills gaps via the API.
  • Sends strings to an OpenAI-compatible chat API (default model google/gemini-3.1-flash-lite-preview, default endpoint OpenRouter) in batches; uses OPENROUTER_API_KEY when available.
  • Preserves leading/trailing whitespace on strings by peeling it before the API call and re-applying it to results.
  • Parses model JSON with safe_json_loads (strict=False and repair fallbacks) so multiline UI strings (e.g. Calc Python editor errors with embedded newlines) do not fail batch fill with “invalid control character” from strict json.loads.

AI-assisted translation review (--review)

Same script as gap fill; does not modify any .po or .mo file.

  • --review: sends every non-empty translation (including fuzzy) to the model for critique. You must pass --model <name> (no default on this path—use a different model than gap-fill if you want independent suggestions).
  • --execute still defaults to google/gemini-3.1-flash-lite-preview when --model is omitted.
  • --output PATH: optional; default file name is translation_review_<locale>.json or translation_review_<l1>_<l2>_….json with sorted locale directory names when multiple locales are reviewed.
  • While running, each finished batch prints one line per string to stdout (dense: batch size in = lines out). Acceptable rows show the fixed phrase No Errors; only suggest rows include current text, suggestion, and English reasoning.
  • The model returns a JSON array of exactly that many objects (action: ok or suggest). For ok, reasoning_en must be exactly No Errors (the script also normalizes verbose “keep” replies to that literal).
  • Report JSON includes generated_at, model, endpoint, locales, reviewed_string_count (how many strings were reviewed), and suggestions: only rows with action suggest or error (no ok / No Errors rows in the file).

This is a productivity aid, not a substitute for human review of tone and terminology.

Extension menus and registry (.xcu)

LibreOffice supports localized properties with <value xml:lang="...">. The project’s .xcu files use this shape but mostly only define en-US / en today.

WriterAgent menubar titles are not left to that en-US string. get_menu_text returns a _("…") literal and addStatusListener pushes it with FeatureStateEvent.State. A command missing from that map (or returned as a raw English literal) keeps the Addons.xcu English title even when the .po has a msgstr. Hamburger items call _() at popup build time and do not use this map.

LLM prompts vs UI language

A practical policy (from earlier design notes, still relevant):

  • Keep system/tool instructions in English when that improves model comprehension (especially for smaller or local models).
  • Add or keep a clear instruction that conversational replies to the user should match the user’s language when that differs from the prompt language.
  • Users can still override behavior with additional instructions in Settings.

This is separate from gettext: gettext handles fixed UI strings; the model handles free-form chat language.

Future considerations (not implemented as a tracked roadmap)

These are useful directions, not commitments:

  • Pluralization: Expose ngettext (and possibly npgettext) from i18n.py anywhere English uses “one vs many” or per-locale plural rules.
  • Message context: Use pgettext / msgctxt where the same English word must translate differently (e.g. “Table” in Writer vs Calc).
  • RTL locales: Arabic, Hebrew, etc. may need layout or UNO adjustments beyond string translation; test dialogs and sidebar with RTL UI.
  • Automated checks: Optional tests or lint rules that flag unwrapped user strings in high-traffic UI modules; CI jobs that run extract-strings and fail on accidental POT drift if desired.
  • Translation platform: Weblate, Crowdin, or Transifex if community scale grows; export writeragent.pot as the handoff artifact.
  • String freeze: Before a release aimed at translators, freeze msgid churn to reduce merge noise.
  • Coverage reporting: Extend or reuse the logic in translate_missing.py’s status output to publish a simple per-language table in docs or CI logs.

For day-to-day contributor steps (extract, merge, Poedit, compile), see locales/README.md.

Open

  • [feature M many] Expose ngettext and npgettext from i18n.py so one-versus-many strings follow per-locale plural rules. (§ Future considerations)
  • [fidelity S many] Use pgettext message contexts where the same English word must translate differently, such as "Table" in Writer versus Calc. (§ Future considerations)
  • [fidelity M few] Test and adjust dialogs and the sidebar for right-to-left locales such as Arabic and Hebrew. (§ Future considerations)
  • [eng S few] Add a test or lint rule that flags unwrapped user-facing strings in high-traffic UI modules, and a CI check for accidental POT drift. (§ Future considerations)
  • [eng S few] Publish a per-language translation coverage table in docs or CI logs by reusing the status logic in translate_missing.py. (§ Future considerations)
  • [idea M few] Move translation to a hosted platform such as Weblate, Crowdin or Transifex, with writeragent.pot as the handoff, if the community grows. (§ Future considerations)
  • [idea S few] Freeze msgid churn before a translator-facing release to reduce merge noise. (§ Future considerations)