ravenous_roll20/tools/build.py

408 lines
21 KiB
Python

#!/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 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))
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": translate_typst(item.get("Effet", "").strip(), glossary),
})
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", [])):
powers.append({
"key": f"{path.stem}:{stage['number']}:{index}",
"stage": str(stage["number"]),
"type": ability["type"],
"name": power_text(ability.get("name", "Passif")),
"description": power_text(ability["description"]),
})
origins[path.stem] = {"name": data["name"], "powers": powers}
return origins
def origin_options(origins: dict[str, dict]) -> str:
return "".join(f'<option value="{key}">{html.escape(origin["name"])}</option>'
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'<option value="{stage}">Stade {stage}</option>' 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 = ['<div class="skill-subtabs">']
labels = ['<div class="skill-subtab-bar" role="tablist" aria-label="Catégories de compétences">']
panels = ['<div class="skill-category-panels">']
for index, category in enumerate(categories):
key = slug(category)
checked = " checked" if index == 0 else ""
tabs.append(f'<input class="skill-subtab-state" type="radio" id="skill-tab-{key}" name="attr_skill_tab" value="{key}"{checked}>')
labels.append(f'<label class="skill-subtab" for="skill-tab-{key}" role="tab">{html.escape(category)}</label>')
panels.append(f'<div class="skill-category-panel skill-category-panel-{key}" role="tabpanel">')
for skill in (item for item in skills if item["category"] == category):
panels.append(f'''<div class="skill-row skill-depth-{min(skill['depth'], 3)}" title="{html.escape(skill['description'])}">
<button class="skill-roll" type="action" name="act_skill_{skill['id']}" title="Tester {html.escape(skill['name'])}" aria-label="Tester {html.escape(skill['name'])}"></button>
<span class="skill-name">{html.escape(skill['display_name'])}</span>
<select name="attr_{skill['id']}_characteristic">{characteristic_options(skill['characteristic'])}</select>
<input type="number" name="attr_{skill['id']}" value="0" min="0">
<input type="number" name="attr_{skill['id']}_temp" value="0">
<input type="hidden" name="attr_{skill['id']}_effect" value="0"><output name="attr_{skill['id']}_total">0</output>
</div>''')
panels.append('</div>')
labels.append('</div>')
labels.append('<div class="skill-head"><span></span><span>Compétence</span><span>Caractéristique</span><span>Base</span><span>Temp.</span><span>Total</span></div>')
panels.append('</div>')
return "\n".join(tabs + labels + panels + ['</div>'])
def skill_category_css(skills: list[dict]) -> str:
categories = dict.fromkeys(skill["category"] for skill in skills)
return "\n".join(
f'.skill-subtab-state[value="{slug(category)}"]:checked~.skill-subtab-bar label[for="skill-tab-{slug(category)}"]'
f'{{ color:var(--light); background:var(--blood); }}\n'
f'.skill-subtab-state[value="{slug(category)}"]:checked~.skill-category-panels '
f'.skill-category-panel-{slug(category)}{{ display:block; }}'
for category in categories
)
def technique_options(schools: dict[str, list[dict[str, str]]], trigrams: dict[str, str]) -> tuple[str, dict[str, dict[str, str]]]:
options = []
indexed: dict[str, dict[str, str]] = {}
for school, techniques in schools.items():
trigram = trigrams[school.replace("_", "-")]
school_label = school.replace("_", " ").title()
children = []
for index, technique in enumerate(techniques):
key = f"{school}:{index}"
indexed[key] = {**technique, "school": school, "school_label": school_label}
label = f"{trigram} · T{technique['tier']} · {technique['name']} {technique['level']}"
children.append(f'<option value="{key}">{html.escape(label.strip())}</option>')
group_label = f"{trigram} · {school_label}"
options.append(f'<optgroup label="{html.escape(group_label)}">{"".join(children)}</optgroup>')
return "".join(options), indexed
def javascript_data(value: dict | list) -> str:
"""Put generated entries on separate lines for the Roll20 sheet editor."""
if isinstance(value, dict):
entries = (f"{json.dumps(key, ensure_ascii=False)}:{json.dumps(item, ensure_ascii=False, separators=(',', ':'))}"
for key, item in value.items())
return "{\n" + ",\n".join(entries).replace("</", "<\\/") + "\n}"
entries = (json.dumps(item, ensure_ascii=False, separators=(',', ':')) for item in value)
return "[\n" + ",\n".join(entries).replace("</", "<\\/") + "\n]"
CHARACTERISTICS = ["force", "agilite", "perception", "intelligence", "volonte", "psy", "chance", "charisme"]
def characteristic_options(selected: str) -> str:
labels = dict(zip(CHARACTERISTICS, ["Force", "Agilité", "Perception", "Intelligence", "Volonté", "Psy", "Chance", "Charisme"]))
return "".join(f'<option value="{key}"{" selected" if key == selected else ""}>{label}</option>' for key, label in labels.items())
def render(template: str, replacements: dict[str, str]) -> str:
for key, value in replacements.items():
template = template.replace("{{" + key + "}}", value)
missing = re.findall(r"\{\{[A-Z][A-Z0-9_]+\}\}", template)
if missing:
raise RuntimeError(f"Unresolved template markers: {missing}")
return template
def target_options(skills: list[dict[str, str]], include_empty: bool = False) -> str:
empty = '<option value="">— aucune —</option>' if include_empty else ""
characteristics = "".join(
f'<option value="{key}">{label}</option>'
for key, label in zip(CHARACTERISTICS, ["Force", "Agilité", "Perception", "Intelligence", "Volonté", "Psy", "Chance", "Charisme"])
)
skill_options = "".join(f'<option value="{item["id"]}">{html.escape(item["name"])}</option>' for item in skills)
return empty + f'<optgroup label="Caractéristiques">{characteristics}</optgroup><optgroup label="Compétences">{skill_options}</optgroup>'
def skill_target_options(skills: list[dict[str, str]]) -> str:
return '<option value="">— aucune —</option>' + "".join(
f'<option value="{item["id"]}">{html.escape(item["name"])}</option>' for item in skills
)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--check", action="store_true", help="fail when build/ differs from generated output")
parser.add_argument("--theme", help="book color theme (defaults to document.color_scheme)")
parser.add_argument("--list-themes", action="store_true", help="list color themes from the book and exit")
parser.add_argument("--output-dir", type=Path, default=BUILD, help="directory for generated files (default: build/)")
args = parser.parse_args()
palettes = read_theme_palettes()
if args.list_themes:
print("\n".join(palettes))
return
data = read_character_data()
config = read_build_config()
theme = args.theme or config["document"]["color_scheme"]
if theme not in palettes:
parser.error(f"unknown theme {theme!r}; choose from: {', '.join(palettes)}")
output_dir = args.output_dir
max_tier_exclusive = int(config["build"]["max_tier_exclusive"])
schools = read_schools(max_tier_exclusive, read_glossary_labels())
origins = read_origins(read_glossary_labels())
skills = skills_from_data(data)
technique_select, techniques = technique_options(schools, config["schools"]["trigrams"])
generated = {
"ravenous.html": render((TEMPLATES / "ravenous.html").read_text(encoding="utf-8"), {
"SKILL_ROWS": skill_rows(skills),
"TECHNIQUE_OPTIONS": technique_select,
"ORIGIN_OPTIONS": origin_options(origins),
"POWER_STAGE_OPTIONS": power_stage_options(origins),
"CHARACTERISTIC_OPTIONS": characteristic_options("agilite"),
"TARGET_OPTIONS": target_options(skills),
"TARGET_OPTIONS_EMPTY": target_options(skills, include_empty=True),
"SKILL_TARGET_OPTIONS_EMPTY": skill_target_options(skills),
"TECHNIQUES_JSON": javascript_data(techniques),
"ORIGINS_JSON": javascript_data(origins),
"SKILLS_JSON": javascript_data(skills),
}),
"ravenous.css": render((TEMPLATES / "ravenous.css").read_text(encoding="utf-8"),
{"THEME_VARS": theme_variables(palettes[theme]),
"SKILL_CATEGORY_CSS": skill_category_css(skills)}),
"translation.json": (TEMPLATES / "translation.json").read_text(encoding="utf-8"),
"sheet.json": (TEMPLATES / "sheet.json").read_text(encoding="utf-8"),
}
digest = hashlib.sha256("".join(generated.values()).encode()).hexdigest()[:12]
generated["build-info.json"] = json.dumps({
"source": "ravenous_typst/data/src", "schools": len(schools), "max_tier_exclusive": max_tier_exclusive,
"techniques": sum(map(len, schools.values())), "skills": len(skills),
"origins": len(origins), "powers": sum(len(origin["powers"]) for origin in origins.values()),
"theme": theme,
"content_hash": digest,
}, ensure_ascii=False, indent=2) + "\n"
if args.check:
stale = [name for name, content in generated.items() if not (output_dir / name).exists() or (output_dir / name).read_text(encoding="utf-8") != content]
if stale:
raise SystemExit("Generated files are stale: " + ", ".join(stale))
return
output_dir.mkdir(parents=True, exist_ok=True)
for name, content in generated.items():
(output_dir / name).write_text(content, encoding="utf-8")
print(f"Built {len(generated)} files ({len(skills)} skills, {sum(map(len, schools.values()))} techniques).")
if __name__ == "__main__":
main()