Coverage for rdgai/translations.py: 96.88%
32 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-24 23:53 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-24 23:53 +0000
1"""
2Contextual translations of the verse with each reading in place, for the annotator.
4They are written by Claude through MCP (``set_translations``) and stored in a sidecar YAML file next to the TEI file
5(by default ``<file>.translations.yaml``), never in the TEI. Each translation keeps the text of the reading it was
6made for, so a translation whose reading has since changed is not shown.
7"""
8import os
9import tempfile
10from pathlib import Path
12import yaml
13from pydantic import BaseModel, Field
16class ReadingTranslation(BaseModel):
17 reading: str = Field(description="The reading's text when it was translated.")
18 translation: str
21class UnitTranslations(BaseModel):
22 source: str = ""
23 when: str = ""
24 readings: dict[str, ReadingTranslation] = Field(default_factory=dict)
27class Translations(BaseModel):
28 units: dict[str, UnitTranslations] = Field(default_factory=dict)
31def default_translations_path(tei_path:Path|str) -> Path:
32 tei_path = Path(tei_path)
33 return tei_path.with_name(f"{tei_path.stem}.translations.yaml")
36def load_translations(path:Path|str) -> Translations:
37 path = Path(path)
38 if not path.exists():
39 return Translations()
40 data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
41 return Translations.model_validate(data)
44def save_translations(translations:Translations, path:Path|str):
45 """ Writes the file atomically (a temporary file renamed over it). """
46 path = Path(path)
47 fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
48 try:
49 with os.fdopen(fd, "w", encoding="utf-8") as f:
50 yaml.safe_dump(translations.model_dump(), f, sort_keys=False, allow_unicode=True, width=120)
51 os.replace(tmp, path)
52 finally:
53 if os.path.exists(tmp):
54 os.remove(tmp)