#!/usr/bin/env python3 """Build the Ravenous Roll20 sheet from the Ravenous Typst source data.""" from __future__ import annotations import argparse import csv import hashlib import html import json import re from pathlib import Path import yaml ROOT = Path(__file__).resolve().parents[1] DATA = ROOT / "ravenous_typst" / "data" / "src" TEMPLATES = ROOT / "src" BUILD = ROOT / "build" BUILD_CONFIG = ROOT / "ravenous_typst" / "data" / "config" / "build.yaml" THEMES_SOURCE = ROOT / "ravenous_typst" / "setup" / "theme" / "themes.typ" THEME_COLORS = { "ink": "ink", "muted": "muted-ink", "gold": "gold", "dark-gold": "dark-gold", "paper": "parchment", "light": "parchment-light", "accent": "parchment-accent", "border": "border", "blood": "blood", } def slug(value: str) -> str: import unicodedata plain = unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode() return re.sub(r"[^a-z0-9]+", "_", plain.lower()).strip("_") def read_character_data() -> dict: path = DATA / "character_sheet.yaml" if not path.exists(): raise SystemExit("Missing Ravenous source data. Initialize ravenous_typst submodule first.") with path.open(encoding="utf-8") as stream: return yaml.safe_load(stream) def read_glossary_labels() -> dict[str, str]: labels: dict[str, str] = { "cl_sgA": "Sang immaculé", "cl_sgM": "Sang bestial", "cl_sgS": "Sang honni", "cl_no_cost": "Aethéré", "jauge": "Jauge", "sangressence": "Sangressence", } for path in sorted((DATA / "glossaries").glob("*.yaml")): with path.open(encoding="utf-8") as stream: entries = yaml.safe_load(stream) or [] for entry in entries: if not isinstance(entry, dict) or "key" not in entry: continue label = entry.get("short") if not isinstance(label, str): label = entry.get("long") if isinstance(label, str): labels.setdefault(entry["key"], label) return labels def _replace_balanced_calls(text: str, macro: str, renderer) -> str: marker = f"#{macro}(" while marker in text: start = text.find(marker) depth = 1 quote = None index = start + len(marker) while index < len(text) and depth: char = text[index] if quote: if char == quote and text[index - 1] != "\\": quote = None elif char in "\"'": quote = char elif char == "(": depth += 1 elif char == ")": depth -= 1 index += 1 if depth: break arguments = text[start + len(marker):index - 1] text = text[:start] + renderer(arguments) + text[index:] return text def translate_typst(text: str, glossary: dict[str, str]) -> str: """Turn the subset of Typst markup used by school TSVs into chat-safe text.""" characteristics = {"force": "Force", "agi": "Agilité", "per": "Perception", "int": "Intelligence", "vol": "Volonté", "psy": "Psy", "chance": "Chance", "cha": "Charisme"} text = re.sub(r"#inline_help\[([^]]*)]", r"Note : \1", text) text = re.sub(r"#footnote\[([^]]*)]", r"(Note : \1)", text) text = _replace_balanced_calls(text, "ddlvl", lambda args: "DD " + args.split(",", 1)[0].strip()) text = _replace_balanced_calls(text, "resist", lambda args: "Résistance " + args.split(",", 1)[0].strip()) text = _replace_balanced_calls(text, "marques", lambda args: "Marque " + args.replace("[", "").replace("]", "")) text = _replace_balanced_calls(text, "gls", lambda args: (re.search(r'display\s*:\s*"([^"]+)"', args) or re.search(r'"([^"]+)"', args)).group(1)) def weapon(args: str) -> str: fields = dict((key, value.strip().strip("[]\"")) for key, value in re.findall(r'(name|damage|rmax|range|aspect|arbreak|armor_pierce|am|precision|protection|integrity|actions)\s*:\s*(\[[^]]*]|"[^\"]*"|[^,]+)', args)) labels = {"damage":"dégâts","rmax":"RMax","range":"portée","aspect":"zone","arbreak":"brise-armure","armor_pierce":"perce-armure","am":"anti-matériel","precision":"précision","protection":"protection","integrity":"intégrité","actions":"actions"} name = fields.pop("name", "Attaque") values = [f"{labels.get(key, key)} {value}" for key, value in fields.items() if value] return f"{name} ({' · '.join(values)})" if values else name text = _replace_balanced_calls(text, "weapon-pill", weapon) def aoe(args: str) -> str: values = [f"{key.replace('repositionning', 'repositionnement').replace('parry', 'parade').replace('dodge', 'esquive')} {value}" for key, value in re.findall(r'(\w+)\s*:\s*"([^\"]*)"', args)] return "Défense de zone" + (" (" + " · ".join(values) + ")" if values else "") text = _replace_balanced_calls(text, "aoe_thresholds", aoe) text = re.sub(r"#cr\.([A-Za-z_]+)", lambda match: characteristics.get(match.group(1), match.group(1).replace("_", " ").title()), text) text = re.sub(r"@([A-Za-z_][A-Za-z0-9_]*)(?::(?:short|long|pl))?", lambda match: glossary.get(match.group(1), match.group(1).replace("_", " ")), text) text = re.sub(r"#([A-Za-z_][A-Za-z0-9_-]*)", lambda match: match.group(1).replace("_", " ").replace("-", " "), text) text = text.replace("[", "").replace("]", "").replace("_", "") return re.sub(r"\s+", " ", text).strip() def effect_reminder_metadata(text: str) -> dict[str, str | int]: """Infer conservative turn reminders from translated French rules text.""" lowered = text.casefold().replace("’", "'") sentences = re.split(r"(?<=[.!?])\s+", text) start = [sentence for sentence in sentences if re.search(r"\bau début (?:du|de|d')", sentence.casefold())] end = [sentence for sentence in sentences if re.search(r"\b(?:à|a) la fin (?:du|de|d')", sentence.casefold()) and "jusqu'à la fin" not in sentence.casefold().replace("’", "'")] metadata: dict[str, str | int] = {} if start: metadata["start_reminder"] = " ".join(start) if end: metadata["end_reminder"] = " ".join(end) if "jusqu'à la fin du combat" in lowered: metadata.update(duration_type="combat", countdown_phase="end") elif re.search(r"jusqu'au début (?:du|de|d')", lowered): metadata.update(duration_type="until_start", countdown_phase="start") elif re.search(r"jusqu'à la fin (?:du|de|d')", lowered): metadata.update(duration_type="until_end", countdown_phase="end") else: count = re.search(r"(?:pendant|dure(?:nt)?)\s+(\d+|un|une|deux|trois|quatre|cinq|six)\s+tours?", lowered) if count: words = {"un": 1, "une": 1, "deux": 2, "trois": 3, "quatre": 4, "cinq": 5, "six": 6} value = int(count.group(1)) if count.group(1).isdigit() else words[count.group(1)] metadata.update(duration_type="turns", remaining=value, countdown_phase="start" if start and not end else "end") return metadata def read_schools(max_tier_exclusive: int, glossary: dict[str, str]) -> dict[str, list[dict[str, str]]]: schools: dict[str, list[dict[str, str]]] = {} for path in sorted((DATA / "schools").glob("*.tsv")): techniques: list[dict[str, str]] = [] tier = "" headers: list[str] | None = None with path.open(encoding="utf-8-sig", newline="") as stream: for row in csv.reader(stream, delimiter="\t"): row += [""] * (16 - len(row)) first = row[0].strip() if first.startswith("Tier "): tier = first.removeprefix("Tier ").strip() headers = None elif first == "Technique": headers = row elif headers and first and tier.isdigit() and int(tier) < max_tier_exclusive: item = dict(zip(headers, row)) effect = translate_typst(item.get("Effet", "").strip(), glossary) techniques.append({ "name": first, "level": item.get("Niv", "").strip(), "tier": tier, "type": item.get("Type", "").strip(), "blood": item.get("Sang", "").strip(), "gauge": item.get("Jauge", "").strip(), "other": translate_typst(item.get("Autre", "").strip(), glossary), "effect": effect, **effect_reminder_metadata(effect), }) schools[path.stem] = techniques return schools def read_origins(glossary: dict[str, str]) -> dict[str, dict]: descriptions = {} for path in sorted((DATA / "glossaries").glob("*.yaml")): for entry in yaml.safe_load(path.read_text(encoding="utf-8")) or []: if isinstance(entry, dict) and isinstance(entry.get("description"), str): descriptions[entry["key"]] = entry["description"] def power_text(value: str) -> str: value = re.sub(r'#reference\(<[^>]+>,\s*fallback:\s*\[([^]]+)\]\)', lambda match: f"voir {match.group(1)}", value) value = re.sub(r'#gls-definition\("([^"]+)"\)', lambda match: descriptions.get(match.group(1), glossary.get(match.group(1), match.group(1))), value) value = re.sub(r"#spend\[([^]]*)]", r"Dépensez \1 —", value) value = re.sub(r"#mecaniquejeu\[([^]]*)]", r"\1", value) value = value.replace("#death-without-penalty", "Cette mort ne vous inflige aucun malus de mort.") return translate_typst(value, glossary) origins = {} for path in sorted((DATA / "origines").glob("*.yaml")): data = yaml.safe_load(path.read_text(encoding="utf-8")) powers = [] for stage in data.get("stades", []): for index, ability in enumerate(stage.get("abilities", [])): description = power_text(ability["description"]) powers.append({ "key": f"{path.stem}:{stage['number']}:{index}", "stage": str(stage["number"]), "type": ability["type"], "name": power_text(ability.get("name", "Passif")), "description": description, **effect_reminder_metadata(description), }) origins[path.stem] = {"name": data["name"], "powers": powers} return origins def origin_options(origins: dict[str, dict]) -> str: return "".join(f'' for key, origin in origins.items()) def power_stage_options(origins: dict[str, dict]) -> str: stages = sorted({power["stage"] for origin in origins.values() for power in origin["powers"]}, key=int) return "".join(f'' for stage in stages) def read_build_config() -> dict: with BUILD_CONFIG.open(encoding="utf-8") as stream: return yaml.safe_load(stream) def read_theme_palettes() -> dict[str, dict[str, str]]: source = THEMES_SOURCE.read_text(encoding="utf-8") starts = list(re.finditer(r"^ ([a-z][a-z-]+): \($", source, re.MULTILINE)) palettes = {} for index, match in enumerate(starts): body = source[match.end():starts[index + 1].start() if index + 1 < len(starts) else len(source)] colors = dict(re.findall(r'^ ([a-z-]+): rgb\("(#[0-9A-Fa-f]{6})"\),', body, re.MULTILINE)) missing = set(THEME_COLORS.values()) - colors.keys() if missing: raise ValueError(f"Theme {match.group(1)} is missing colors: {sorted(missing)}") palettes[match.group(1)] = colors return palettes def theme_variables(palette: dict[str, str]) -> str: values = [f"--{css_key}:{palette[book_key].lower()};" for css_key, book_key in THEME_COLORS.items()] for name in ("gold", "blood", "light", "accent"): color = palette[THEME_COLORS[name]].lstrip("#") values.append(f"--{name}-rgb:{','.join(str(int(color[i:i + 2], 16)) for i in (0, 2, 4))};") return " ".join(values) def skills_from_data(data: dict) -> list[dict]: skills: list[dict] = [] defaults = { "Parade": "force", "Esquive": "agilite", "Encaissement": "force", "Initiative": "perception", "Sens commun": "charisme", "Négociation": "charisme", "Traque": "perception", "Survie": "perception", "Dépeçage": "intelligence", "Médecine": "intelligence", } for category in data["competences"]: if not category.get("sheet", {}).get("visible", True): continue def add_entry(entry: dict, parent_id: str = "", parent_name: str = "", inherited: str = "", depth: int = 0) -> None: name = entry["name"] key = f"{parent_id}_{slug(name)}" if parent_id else slug(name) label = f"{parent_name} — {name}" if parent_name else name characteristic = inherited or defaults.get(name, "agilite" if category["name"] == "Athlétisme" else "intelligence") skills.append({"id": key, "name": label, "display_name": name, "depth": depth, "category": category["name"], "characteristic": characteristic, "description": entry.get("description", "")}) for child in entry.get("subskills", []): add_entry(child, key, label, characteristic, depth + 1) for entry in category.get("entries", []): add_entry(entry) return skills def skill_rows(skills: list[dict]) -> str: categories = list(dict.fromkeys(skill["category"] for skill in skills)) tabs = ['