Files
ai-agent/backend/core/i18n.py
gabrielvidalandClaude Opus 5.5 d0130df93c feat(i18n): per-user language on the server, French mail, errors, pushes and prompt
users.json gains lang (auto|en|fr) and the guest's last-seen browserLang;
/api/me returns it (the owner: en), PUT /api/me and the owner's user
update accept it, and the guest's page in Settings → Users gets a
Language row. core/i18n.tr() localizes for a French guest: the sign-in
and invitation mails, the app's own pushes and feeds, the errors a guest
can hit, the New-project form, and one line in the guest run's system
prompt so Claude answers in French (tu, ask-form --lang fr). What's new
entries are written in French from now on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 22:37:31 +01:00

108 lines
4.1 KiB
Python

"""
French for guests, on the backend's side: the text the app itself sends a
guest — the sign-in mail, its own pushes, the API errors a guest can hit, the
*New project* form. The frontend's half is ``frontend/src/i18n/``.
* ``tr(lang, "Hi {name},", name=…)`` — the English text **is the key**; the
French lives in :mod:`core.i18n_fr`. A missing entry (or ``lang`` "en", or
an unknown one) falls back to the English, placeholders filled either way.
``{var}`` placeholders only: a brace that isn't one (code in a string) stays.
* ``msg("…")`` — marks a string that reaches :func:`tr` through a variable
(a table of labels), so ``test_i18n.py`` still sees it.
* A user's language (``users.json`` → ``lang``): ``auto`` | ``en`` | ``fr``,
``auto`` being their browser's — the primary ``Accept-Language`` recorded
as ``browserLang`` when they sign in and on ``GET /api/me``.
:func:`effective_lang` resolves it. The owner is always English.
Text written *for Claude* (system prompts, app turns, notes appended to a
prompt) stays English; a French guest's run is told to answer in French
(``users/runs.py``). Style: tutoiement, plain and short, a no-break space
(U+00A0) before ``:`` ``;`` ``!`` ``?`` and inside « » — as the frontend.
"""
from __future__ import annotations
import re
from core.i18n_fr import FR
LANGS = ("en", "fr")
# What a user may pick (Settings → Display / the owner's page for them).
LANG_PREFS = ("auto", "en", "fr")
DEFAULT_LANG = "en"
_VAR_RE = re.compile(r"\{(\w+)\}")
_TABLES = {"fr": FR}
def msg(english: str) -> str:
"""A string translated later through a variable: ``tr(lang, LABELS[k])``."""
return english
def tr(lang: str | None, english: str, **vars) -> str:
"""``english`` in ``lang`` with its ``{var}`` placeholders filled."""
text = _TABLES.get(lang or "", {}).get(english, english)
if not vars:
return text
return _VAR_RE.sub(lambda m: str(vars[m.group(1)]) if m.group(1) in vars
else m.group(0), text)
def localized(build) -> dict:
"""``{lang: build(lang)}`` for every language but English — the
per-recipient variants a shared notice carries (``i18n`` on a push:
``{"fr": {"title", "message"}}``; the English is ``build("en")``)."""
return {lang: build(lang) for lang in LANGS if lang != DEFAULT_LANG}
def pick(variants: dict | None, lang: str | None) -> dict | None:
"""The variant of a notice for ``lang``, None ⇒ keep the English."""
if not variants or not lang or lang == DEFAULT_LANG:
return None
v = variants.get(lang)
return v if isinstance(v, dict) else None
def clean_pref(value) -> str:
"""A language preference as stored; ValueError for anything else."""
v = str(value or "").strip().lower()
if v not in LANG_PREFS:
raise ValueError(f"lang must be one of {', '.join(LANG_PREFS)}")
return v
def primary_lang(accept_language: str | None) -> str | None:
"""The browser's first-choice language from an ``Accept-Language`` header
— ``"fr"`` / ``"en"`` — or None when it is another one (or none)."""
best, best_q = None, -1.0
for part in (accept_language or "").split(","):
tag, _, params = part.strip().partition(";")
tag = tag.strip().lower()
if not tag or tag == "*":
continue
q = 1.0
for p in params.split(";"):
k, _, val = p.strip().partition("=")
if k.strip() == "q":
try:
q = float(val)
except ValueError:
q = 0.0
if q > best_q:
best, best_q = tag.split("-")[0], q
return best if best in LANGS else None
def effective_lang(user: dict | None, accept_language: str | None = None) -> str:
"""The language the app speaks to ``user``: their ``lang`` unless
``auto``; else the browser language last recorded for them
(``browserLang``); else this request's ``Accept-Language``; else English."""
u = user or {}
pref = u.get("lang")
if pref in LANGS:
return pref
if u.get("browserLang") in LANGS:
return u["browserLang"]
return primary_lang(accept_language) or DEFAULT_LANG