#!/usr/bin/env python3 """ figures/build-figures.py -- one drawing, three languages. Each diagram is written once, as an SVG in figures/src/ whose labels are {{key}} placeholders. figures/labels.yml gives every key its en/fr/de string. For each language this writes figures/-.svg for the html book figures/-.pdf for the pdf book (via rsvg-convert) and a chapter refers to the pair without an extension, so each format picks the file it can use: ![caption](figures/-@tr{langcode}){#fig-...} The svg keeps the labels as real nodes rather than outlines, which is the whole reason for not going through TikZ: the text stays selectable and searchable, the reader's find-in-page reaches it, and figures/diagram.css -- injected into every built svg -- can restyle it, including a dark theme that follows the page. rsvg-convert applies the same stylesheet when it makes the pdf, minus the dark-mode block, so print gets the light theme. German labels run long. A key may therefore carry a per-language font size, which overrides the class default for that one label: key: {en: "Primary key", de: {text: "Primärschlüssel", size: 10}} python3 figures/build-figures.py build what changed python3 figures/build-figures.py --force rebuild everything python3 figures/build-figures.py --check report only, build nothing """ from __future__ import annotations import re import subprocess import sys from pathlib import Path import yaml LANGS = ("en", "fr", "de") HERE = Path(__file__).resolve().parent SRC = HERE / "src" LABELS = HERE / "labels.yml" CSS = HERE / "diagram.css" PLACEHOLDER = re.compile(r"\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}") STYLE_SLOT = "" # --------------------------------------------------------------- label table def load_labels() -> dict: if not LABELS.exists(): return {} return yaml.safe_load(LABELS.read_text(encoding="utf-8")) or {} def resolve(entry, lang: str, key: str, name: str): """One label -> (text, font-size or None). Falls back to en, then the key.""" if entry is None: return None, None if isinstance(entry, str): return entry, None if not isinstance(entry, dict): return str(entry), None value = entry.get(lang) if value is None: value = entry.get("en") if value is None: return None, None print(f"figures: {name}: no '{lang}' label for '{key}' -- using English", file=sys.stderr) if isinstance(value, dict): return str(value.get("text", "")), value.get("size") return str(value), None XML_ESCAPE = {"&": "&", "<": "<", ">": ">"} def escape(text: str) -> str: out = [] for ch in text: out.append(XML_ESCAPE.get(ch, ch)) return "".join(out) def substitute(svg: str, table: dict, lang: str, name: str) -> tuple[str, int]: """Replace every {{key}}. Returns the svg and the number of keys missed.""" missed = 0 sizes: dict[str, float] = {} def one(match: re.Match) -> str: nonlocal missed key = match.group(1) text, size = resolve(table.get(key), lang, key, name) if text is None: missed += 1 print(f"figures: {name}: no label for '{key}' -- add it to labels.yml", file=sys.stderr) return escape("{{" + key + "}}") if size is not None: sizes[key] = size return escape(text) svg = PLACEHOLDER.sub(one, svg) # a per-language size rides along as a style on the element carrying the # label, matched by its data-label attribute if sizes: rules = "\n".join( f' [data-label="{k}"] {{ font-size: {v}px; }}' for k, v in sizes.items() ) svg = svg.replace(STYLE_SLOT, STYLE_SLOT + "\n" + rules, 1) return svg, missed # ------------------------------------------------------------------- building def newer(target: Path, *sources: Path) -> bool: """True when target is missing or older than any source.""" if not target.exists(): return True stamp = target.stat().st_mtime return any(s.exists() and s.stat().st_mtime > stamp for s in sources) def build(force: bool = False, check: bool = False) -> int: if not SRC.is_dir(): print(f"figures: no {SRC.relative_to(HERE.parent)}/ -- nothing to build") return 0 table_all = load_labels() css = CSS.read_text(encoding="utf-8") if CSS.exists() else "" sources = sorted(SRC.glob("*.svg")) if not sources: print("figures: figures/src/ holds no .svg -- nothing to build") return 0 problems = 0 built = 0 for src in sources: name = src.stem table = table_all.get(name, {}) if not isinstance(table, dict): print(f"figures: labels.yml: '{name}' is not a mapping", file=sys.stderr) problems += 1 continue raw = src.read_text(encoding="utf-8") for lang in LANGS: svg_out = HERE / f"{name}-{lang}.svg" pdf_out = HERE / f"{name}-{lang}.pdf" if not force and not newer(svg_out, src, LABELS, CSS) \ and not newer(pdf_out, src, LABELS, CSS): continue if check: print(f"figures: {name}-{lang} would be rebuilt") built += 1 continue svg, missed = substitute(raw, table, lang, name) problems += missed # CDATA, so a "<" or "&" written in the stylesheet (in a comment, # say) cannot turn into markup and break the parse svg = svg.replace(STYLE_SLOT, f"", 1) svg_out.write_text(svg, encoding="utf-8") try: subprocess.run( ["rsvg-convert", "-f", "pdf", "-o", str(pdf_out), str(svg_out)], check=True, capture_output=True, ) except FileNotFoundError: print("figures: rsvg-convert not found -- the pdf book will be " "missing its figures (sudo pacman -S librsvg)", file=sys.stderr) return 1 except subprocess.CalledProcessError as exc: print(f"figures: {name}-{lang}: pdf failed -- " f"{exc.stderr.decode(errors='replace').strip()}", file=sys.stderr) problems += 1 continue built += 1 print(f"figures: built {name}-{lang}") if not built: print("figures: up to date") elif not check: print(f"figures: {built} file(s) built") return 1 if problems else 0 if __name__ == "__main__": args = set(sys.argv[1:]) unknown = args - {"--force", "--check"} if unknown: print(f"figures: unknown option {' '.join(sorted(unknown))}", file=sys.stderr) sys.exit(2) sys.exit(build(force="--force" in args, check="--check" in args))