Source code for reli.localization

"""Robot messages in the user's language.

The first time a message is needed in a language, its *template* is translated by the language
model, checked, and cached (optionally on disk). Later uses only fill in, so status updates cost no
extra model call or latency.
"""

from __future__ import annotations

import json
import logging
import threading
from pathlib import Path
from typing import Any

from .llm import ChatMessage, LLMProvider
from .prompts import Prompts, placeholders, render

log = logging.getLogger(__name__)


def _is_english(language: str) -> bool:
    return language.lower().split("-")[0] in ("en", "eng", "english", "")


[docs] class Localizer: def __init__( self, provider: LLMProvider | None, prompts: Prompts, cache_file: Path | None = None ): self.provider = provider self.prompts = prompts self.cache_file = cache_file self._lock = threading.Lock() self._cache: dict[str, dict[str, str]] = {} if cache_file and cache_file.exists(): try: self._cache = json.loads(cache_file.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): log.warning("Ignoring unreadable translation cache %s", cache_file)
[docs] def message(self, key: str, language: str, **values: Any) -> str: """Render catalogue message ``key`` in ``language``.""" template = self.prompts.messages[key] return render(self.template(template, language), **values)
def template(self, template: str, language: str) -> str: if _is_english(language) or self.provider is None: return template lang = language.strip() with self._lock: cached = self._cache.get(lang, {}).get(template) if cached is not None: return cached translated = self._translate(template, lang) if translated is None: return template # not cached: a later call may succeed with self._lock: self._cache.setdefault(lang, {})[template] = translated self._save() return translated def _translate(self, template: str, language: str) -> str | None: prompt = render(self.prompts["translate_template"], language=language, template=template) try: out = ( self.provider.complete( "You are a professional translator for a robot's user interface.", [ChatMessage("user", prompt)], ) .strip() .strip('"') ) except Exception: # degrade to English rather than fail the action log.exception("Template translation to %s failed; using English.", language) return None if not out or placeholders(out) != placeholders(template): log.warning( "Translation to %s changed the placeholders; using English. Got: %r", language, out ) return None return out def _save(self) -> None: if not self.cache_file: return try: self.cache_file.parent.mkdir(parents=True, exist_ok=True) tmp = self.cache_file.with_suffix(".tmp") tmp.write_text(json.dumps(self._cache, ensure_ascii=False, indent=1), encoding="utf-8") tmp.replace(self.cache_file) except OSError: log.warning("Could not write translation cache %s", self.cache_file)