SPB Git

Repository Public

make_diagrams.py 23.3 KB 561 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Sheet10# File             : docs/assets/diagrams/make_diagrams.py11# Description      : SVG fallbacks for the Mermaid diagrams of the ORIX Sheet12#                    documentation.13# Module           : docs14# Repository       : https://git.spboucher.ai/orix-sheet15# Created          : 2026-11-2116# Last Modified    : 2026-11-2117#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author           : Simon-Pierre Boucher23# Position         : Professor of Finance24# Institution      : Université du Québec en Outaouais (UQO)25# Department       : Département des sciences administratives26# Organization     : SP Boucher27#28# Website          : https://spboucher.ai29# Git              : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General          : info@spboucher.ai36# Professional     : contact@spboucher.ai37# Direct           : simon@spboucher.ai38# Research         : research@spboucher.ai39# Development      : dev@spboucher.ai40# Support          : support@spboucher.ai41# Security/Admin   : admin@spboucher.ai42# Notifications    : notifications@spboucher.ai43#44# Preferred Contact: support@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification   : Public69# Distribution     : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License          : None specified (no license file in this repository)83# Maintainer       : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""SVG fallbacks for the Mermaid diagrams of the ORIX Sheet documentation.9192The Mermaid CLI is not available offline on the build machine, so this script93renders every diagram itself. The Mermaid source in the Markdown files stays94the single source of truth: the script scans ``docs/**/*.md`` for blocks of95the form9697    <!-- diagram: some-name -->98    ```mermaid99    flowchart TD100        A["Label"] --> B["Other label"]101    ```102103and writes ``docs/assets/diagrams/some-name.svg``.104105Only the subset of Mermaid used by the documentation is understood:106107* ``flowchart TD|TB|LR`` / ``graph TD|LR`` with one edge or node per line:108  ``A["text"]``, ``A[text]``, ``A("text")``, ``A{"text"}``, ``A --> B``,109  ``A -->|label| B``, ``A -.-> B``, ``A -.->|label| B``, ``A --- B``.110  Node declarations may be inline in an edge. ``<br/>`` breaks a line.111  ``subgraph`` / ``end`` / ``classDef`` / ``class`` / ``style`` lines are ignored112  (nodes of a subgraph are laid out like any other node).113* ``sequenceDiagram`` with ``participant X as Label``, ``A->>B: text``,114  ``A-->>B: text``, ``A->>A: text`` and ``Note over A,B: text``.115116Layout: longest-path layering, barycentre ordering inside each layer, straight117connectors; an edge that spans several layers is routed through one waypoint per118layer so that it passes between the boxes. No external dependency (Python 3 standard library).119120Usage:  python3 docs/assets/diagrams/make_diagrams.py [--check]121        --check  exits 1 if an SVG is missing or out of date, writes nothing.122"""123from __future__ import annotations124125import html126import re127import sys128from pathlib import Path129130HERE = Path(__file__).resolve().parent131DOCS = HERE.parent.parent132133# Neutral documentation colours. These are NOT the ORIX design tokens (docs/design/design-system.md).134INK = "#1A1D21"135MUTED = "#5A626C"136LINE = "#8A939E"137FILL = "#F4F6F8"138STROKE = "#2F6F6A"139NOTE_FILL = "#FFF6DA"140FONT = "-apple-system, 'SF Pro Text', 'Helvetica Neue', Helvetica, Arial, sans-serif"141FONT_SIZE = 12142CHAR_W = 6.5          # average glyph advance at 12 px (estimate; boxes get padding)143LINE_H = 15144PAD_X = 12145PAD_Y = 8146147BLOCK_RE = re.compile(r"<!--\s*diagram:\s*([a-z0-9][a-z0-9-]*)\s*-->\s*\n```mermaid\n(.*?)\n```", re.S)148149150def esc(text: str) -> str:151    return html.escape(text, quote=True)152153154def text_lines(label: str) -> list[str]:155    label = re.sub(r"<br\s*/?>", "\n", label)156    return [part.strip() for part in label.split("\n")]157158159def box_size(label: str) -> tuple[float, float]:160    lines = text_lines(label)161    width = max(len(line) for line in lines) * CHAR_W + 2 * PAD_X162    height = len(lines) * LINE_H + 2 * PAD_Y163    return max(width, 60.0), height164165166def svg_text(x: float, y: float, label: str, *, size: int = FONT_SIZE, fill: str = INK, anchor: str = "middle") -> str:167    lines = text_lines(label)168    start = y - (len(lines) - 1) * LINE_H / 2 + size * 0.35169    out = []170    for index, line in enumerate(lines):171        out.append(172            f'<text x="{x:.1f}" y="{start + index * LINE_H:.1f}" font-size="{size}" fill="{fill}" '173            f'text-anchor="{anchor}">{esc(line)}</text>'174        )175    return "".join(out)176177178def svg_wrap(width: float, height: float, body: str, title: str) -> str:179    return (180        f'<svg xmlns="http://www.w3.org/2000/svg" width="{width:.0f}" height="{height:.0f}" '181        f'viewBox="0 0 {width:.0f} {height:.0f}" font-family="{FONT}" role="img" aria-label="{esc(title)}">\n'182        f"<title>{esc(title)}</title>\n"183        '<defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" '184        f'orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="{LINE}"/></marker></defs>\n'185        f'<rect width="100%" height="100%" fill="#FFFFFF"/>\n{body}\n</svg>\n'186    )187188189# --------------------------------------------------------------------------- flowchart190191NODE_RE = re.compile(r"""^([A-Za-z_][\w]*)\s*(?:(\[\(|\[\[|\[|\(\(|\(|\{)\s*(.*?)\s*(\)\]|\]\]|\]|\)\)|\)|\})\s*)?$""")192EDGE_SPLIT_RE = re.compile(r"\s*(-\.->|-->|---|==>)\s*(?:\|([^|]*)\|)?\s*")193194195def parse_node(token: str, nodes: dict[str, str], shapes: dict[str, str]) -> str:196    token = token.strip().rstrip(";")197    match = NODE_RE.match(token)198    if not match:199        raise ValueError(f"cannot parse node: {token!r}")200    ident, opener, label, _ = match.groups()201    if label is not None:202        label = label.strip()203        if len(label) >= 2 and label[0] == '"' and label[-1] == '"':204            label = label[1:-1]205        nodes[ident] = label206        shapes[ident] = {"(": "round", "((": "round", "{": "diamond", "[(": "round"}.get(opener, "rect")207    else:208        nodes.setdefault(ident, ident)209        shapes.setdefault(ident, "rect")210    return ident211212213def parse_flowchart(lines: list[str]):214    header = lines[0].split()215    direction = header[1] if len(header) > 1 else "TD"216    nodes: dict[str, str] = {}217    shapes: dict[str, str] = {}218    edges: list[tuple[str, str, str, bool]] = []219    for raw in lines[1:]:220        line = raw.strip()221        if not line or line.startswith("%%"):222            continue223        if line.split()[0] in {"subgraph", "end", "classDef", "class", "style", "linkStyle", "direction"}:224            continue225        parts = EDGE_SPLIT_RE.split(line)226        # parts = [node, arrow, label, node, arrow, label, node ...]227        previous = parse_node(parts[0], nodes, shapes)228        index = 1229        while index + 2 < len(parts) + 0 and index + 2 <= len(parts) - 1 + 0:230            arrow, label, target = parts[index], parts[index + 1], parts[index + 2]231            current = parse_node(target, nodes, shapes)232            edges.append((previous, current, (label or "").strip().strip('"'), arrow == "-.->"))233            previous = current234            index += 3235    return direction, nodes, shapes, edges236237238def layer_nodes(nodes: dict[str, str], edges) -> dict[str, int]:239    order = list(nodes)240    successors: dict[str, list[str]] = {n: [] for n in order}241    for source, target, _, _ in edges:242        if source != target:243            successors[source].append(target)244    # Remove back edges found by a depth-first walk in declaration order.245    state: dict[str, int] = {}246    forward: list[tuple[str, str]] = []247248    def visit(node: str) -> None:249        state[node] = 1250        for nxt in successors[node]:251            if state.get(nxt) == 1:252                continue  # back edge: ignored for layering253            forward.append((node, nxt))254            if nxt not in state:255                visit(nxt)256        state[node] = 2257258    for node in order:259        if node not in state:260            visit(node)261    layer = {n: 0 for n in order}262    changed = True263    guard = 0264    while changed and guard < len(order) + 2:265        changed = False266        guard += 1267        for source, target in forward:268            if layer[target] < layer[source] + 1:269                layer[target] = layer[source] + 1270                changed = True271    return layer272273274def render_flowchart(lines: list[str], title: str) -> str:275    direction, nodes, shapes, edges = parse_flowchart(lines)276    horizontal = direction in {"LR", "RL"}277    layer = layer_nodes(nodes, edges)278    count = max(layer.values()) + 1 if layer else 1279    layers: list[list[str]] = [[] for _ in range(count)]280    for node in nodes:281        layers[layer[node]].append(node)282283    # Edges that span several layers get an invisible waypoint in every layer they cross, so that284    # they are routed between the boxes instead of behind them.285    sizes = {node: box_size(label) for node, label in nodes.items()}286    waypoints: dict[int, list[str]] = {}287    links: list[tuple[str, str]] = []288    for index, (source, target, _, _) in enumerate(edges):289        chain = [source]290        if layer[target] - layer[source] > 1:291            for level in range(layer[source] + 1, layer[target]):292                dummy = f"\u0000{index}:{level}"293                layer[dummy] = level294                layers[level].append(dummy)295                sizes[dummy] = (14.0, 1.0)296                chain.append(dummy)297            waypoints[index] = chain[1:]298        chain.append(target)299        links.extend(zip(chain, chain[1:]))300301    neighbours: dict[str, list[str]] = {n: [] for n in layer}302    for a, b in links:303        neighbours[a].append(b)304        neighbours[b].append(a)305    position: dict[str, float] = {}306    for row in layers:307        for index, node in enumerate(row):308            position[node] = index309    for sweep in range(8):  # barycentre sweeps, alternately looking up and down310        rows = layers if sweep % 2 == 0 else layers[::-1]311        for row in rows:312            def key(node: str) -> float:313                wanted = layer[node] - 1 if sweep % 2 == 0 else layer[node] + 1314                linked = [position[m] for m in neighbours[node] if layer[m] == wanted]315                if not linked:316                    linked = [position[m] for m in neighbours[node] if layer[m] != layer[node]]317                return sum(linked) / len(linked) if linked else position[node]318            keyed = sorted(((key(node), position[node], node) for node in row))319            row[:] = [node for _, _, node in keyed]320            for index, node in enumerate(row):321                position[node] = index322323    gap_main, gap_cross, margin = 56.0, 26.0, 24.0324    centre: dict[str, tuple[float, float]] = {}325    if horizontal:326        heights = [sum(sizes[n][1] for n in row) + gap_cross * (len(row) - 1) for row in layers]327        total_h = max(heights)328        x = margin329        for row, used in zip(layers, heights):330            width = max(sizes[n][0] for n in row)331            y = margin + (total_h - used) / 2332            for node in row:333                centre[node] = (x + width / 2, y + sizes[node][1] / 2)334                y += sizes[node][1] + gap_cross335            x += width + gap_main + 20336        canvas_w, canvas_h = x - gap_main - 20 + margin, total_h + 2 * margin337    else:338        widths = [sum(sizes[n][0] for n in row) + gap_cross * (len(row) - 1) for row in layers]339        total_w = max(widths)340        y = margin341        for row, used in zip(layers, widths):342            height = max(sizes[n][1] for n in row)343            x = margin + (total_w - used) / 2344            for node in row:345                centre[node] = (x + sizes[node][0] / 2, y + height / 2)346                x += sizes[node][0] + gap_cross347            y += height + gap_main348        canvas_w, canvas_h = total_w + 2 * margin, y - gap_main + margin349350    def anchor(node: str, toward: tuple[float, float]) -> tuple[float, float]:351        cx, cy = centre[node]352        w, h = sizes[node]353        dx, dy = toward[0] - cx, toward[1] - cy354        if dx == 0 and dy == 0:355            return cx, cy356        scale_x = (w / 2) / abs(dx) if dx else float("inf")357        scale_y = (h / 2) / abs(dy) if dy else float("inf")358        scale = min(scale_x, scale_y)359        return cx + dx * scale, cy + dy * scale360361    body: list[str] = []362    labels: list[str] = []363    for index, (source, target, label, dotted) in enumerate(edges):364        dash = ' stroke-dasharray="5 4"' if dotted else ""365        if source == target:366            cx, cy = centre[source]367            w, h = sizes[source]368            body.append(369                f'<path d="M{cx + w / 2:.1f},{cy - 6:.1f} c26,-16 26,28 0,12" fill="none" stroke="{LINE}" '370                f'stroke-width="1.3"{dash} marker-end="url(#arrow)"/>'371            )372            if label:373                labels.append(svg_text(cx + w / 2 + 30, cy, label, size=10, fill=MUTED, anchor="start"))374                canvas_w = max(canvas_w, cx + w / 2 + 40 + len(label) * 5.6)375            continue376        via = [centre[d] for d in waypoints.get(index, [])]377        start = anchor(source, via[0] if via else centre[target])378        end = anchor(target, via[-1] if via else centre[source])379        points = [start] + via + [end]380        path = " ".join(f"{x:.1f},{y:.1f}" for x, y in points)381        body.append(382            f'<polyline points="{path}" fill="none" stroke="{LINE}" stroke-width="1.3" stroke-linejoin="round"{dash} '383            'marker-end="url(#arrow)"/>'384        )385        if label:386            (x1, y1), (x2, y2) = points[0], points[1]387            mx, my = (x1 + x2) / 2, (y1 + y2) / 2388            lw = max(len(part) for part in text_lines(label)) * 5.6 + 8389            lh = len(text_lines(label)) * LINE_H390            labels.append(391                f'<rect x="{mx - lw / 2:.1f}" y="{my - lh / 2:.1f}" width="{lw:.1f}" height="{lh:.1f}" fill="#FFFFFF" opacity="0.9"/>'392                + svg_text(mx, my, label, size=10, fill=MUTED)393            )394    for node, label in nodes.items():395        cx, cy = centre[node]396        w, h = sizes[node]397        radius = 14 if shapes[node] == "round" else 5398        dash = ' stroke-dasharray="4 3"' if shapes[node] == "diamond" else ""399        body.append(400            f'<rect x="{cx - w / 2:.1f}" y="{cy - h / 2:.1f}" width="{w:.1f}" height="{h:.1f}" rx="{radius}" '401            f'fill="{FILL}" stroke="{STROKE}" stroke-width="1.2"{dash}/>' + svg_text(cx, cy, label)402        )403    return svg_wrap(canvas_w, canvas_h, "\n".join(body + labels), title)404405406# --------------------------------------------------------------------------- sequence407408MESSAGE_RE = re.compile(r"^(\w+)\s*(-->>|->>|-->|->|--\)|-\))\s*(\w+)\s*:\s*(.*)$")409NOTE_RE = re.compile(r"^Note\s+(over|right of|left of)\s+([\w, ]+?)\s*:\s*(.*)$", re.I)410411412def render_sequence(lines: list[str], title: str) -> str:413    participants: dict[str, str] = {}414    events: list[tuple] = []415    for raw in lines[1:]:416        line = raw.strip()417        if not line or line.startswith("%%"):418            continue419        if line.startswith(("participant ", "actor ")):420            rest = line.split(None, 1)[1]421            if " as " in rest:422                ident, label = rest.split(" as ", 1)423            else:424                ident, label = rest, rest425            participants[ident.strip()] = label.strip()426            continue427        note = NOTE_RE.match(line)428        if note:429            names = [name.strip() for name in note.group(2).split(",")]430            for name in names:431                participants.setdefault(name, name)432            events.append(("note", names, note.group(3)))433            continue434        message = MESSAGE_RE.match(line)435        if message:436            source, arrow, target, text = message.groups()437            participants.setdefault(source, source)438            participants.setdefault(target, target)439            events.append(("msg", source, target, text, arrow.startswith("--")))440            continue441        if line.split()[0] in {"autonumber", "activate", "deactivate", "loop", "end", "alt", "else", "opt", "par", "and", "rect"}:442            continue443        raise ValueError(f"cannot parse sequence line: {line!r}")444445    idents = list(participants)446    col_w = max(150.0, max(box_size(label)[0] for label in participants.values()) + 24)447    for event in events:  # widen columns for long messages between neighbours448        if event[0] == "msg":449            span = abs(idents.index(event[1]) - idents.index(event[2])) or 1450            need = (max(len(part) for part in text_lines(event[3])) * 5.9 + 30) / span451            col_w = max(col_w, min(need, 330.0))452    margin, head_h = 20.0, 0.0453    sizes = {ident: box_size(label) for ident, label in participants.items()}454    head_h = max(size[1] for size in sizes.values())455    xs = {ident: margin + col_w / 2 + index * col_w for index, ident in enumerate(idents)}456    y = margin + head_h + 26457    body: list[str] = []458    for event in events:459        if event[0] == "msg":460            _, source, target, text, dotted = event461            rows = len(text_lines(text))462            y += (rows - 1) * LINE_H463            dash = ' stroke-dasharray="5 4"' if dotted else ""464            if source == target:465                x = xs[source]466                body.append(467                    f'<path d="M{x:.1f},{y:.1f} h34 v16 h-32" fill="none" stroke="{LINE}" stroke-width="1.3"{dash} '468                    'marker-end="url(#arrow)"/>'469                )470                body.append(svg_text(x + 42, y + 8, text, size=11, anchor="start"))471                y += 38472            else:473                x1, x2 = xs[source], xs[target]474                body.append(475                    f'<line x1="{x1:.1f}" y1="{y:.1f}" x2="{x2 - (3 if x2 > x1 else -3):.1f}" y2="{y:.1f}" stroke="{LINE}" '476                    f'stroke-width="1.3"{dash} marker-end="url(#arrow)"/>'477                )478                body.append(svg_text((x1 + x2) / 2, y - 6 - (rows - 1) * LINE_H / 2, text, size=11))479                y += 34480        else:481            _, names, text = event482            left = min(xs[name] for name in names) - 50483            right = max(xs[name] for name in names) + 50484            rows = text_lines(text)485            width = max(right - left, max(len(row) for row in rows) * 5.9 + 20)486            centre_x = (left + right) / 2487            height = len(rows) * LINE_H + 10488            body.append(489                f'<rect x="{centre_x - width / 2:.1f}" y="{y - 12:.1f}" width="{width:.1f}" height="{height:.1f}" rx="3" '490                f'fill="{NOTE_FILL}" stroke="#C9B46A" stroke-width="1"/>'491            )492            body.append(svg_text(centre_x, y - 12 + height / 2, text, size=11))493            y += height + 18494    bottom = y495    heads: list[str] = []496    for ident in idents:497        x = xs[ident]498        w, h = sizes[ident]499        heads.append(500            f'<line x1="{x:.1f}" y1="{margin + head_h:.1f}" x2="{x:.1f}" y2="{bottom:.1f}" stroke="{LINE}" '501            'stroke-width="1" stroke-dasharray="3 4"/>'502        )503        heads.append(504            f'<rect x="{x - w / 2:.1f}" y="{margin + (head_h - h) / 2:.1f}" width="{w:.1f}" height="{h:.1f}" rx="5" '505            f'fill="{FILL}" stroke="{STROKE}" stroke-width="1.2"/>' + svg_text(x, margin + head_h / 2, participants[ident])506        )507    width = margin * 2 + col_w * len(idents) + 120508    return svg_wrap(width, bottom + margin, "\n".join(heads + body), title)509510511# --------------------------------------------------------------------------- driver512513def render(source: str, name: str) -> str:514    lines = [line for line in source.splitlines() if line.strip()]515    kind = lines[0].split()[0]516    if kind in {"flowchart", "graph"}:517        return render_flowchart(lines, name)518    if kind == "sequenceDiagram":519        return render_sequence(lines, name)520    raise ValueError(f"{name}: unsupported diagram type {kind!r}")521522523def main() -> int:524    check = "--check" in sys.argv[1:]525    seen: dict[str, Path] = {}526    stale = 0527    for path in sorted(DOCS.rglob("*.md")) + [p for p in [DOCS.parent / "README.md"] if p.exists()]:528        text = path.read_text(encoding="utf-8")529        for name, source in BLOCK_RE.findall(text):530            if name in seen:531                print(f"error: diagram name {name!r} used in {seen[name]} and {path}")532                return 1533            seen[name] = path534            try:535                svg = render(source, name)536            except Exception as error:  # report the file, keep going537                print(f"error: {path.relative_to(DOCS.parent)} [{name}]: {error}")538                stale += 1539                continue540            target = HERE / f"{name}.svg"541            if check:542                if not target.exists() or target.read_text(encoding="utf-8") != svg:543                    print(f"stale: {target.relative_to(DOCS.parent)}")544                    stale += 1545            else:546                target.write_text(svg, encoding="utf-8")547                print(f"wrote {target.relative_to(DOCS.parent)}  ({len(svg)} bytes)  <- {path.relative_to(DOCS.parent)}")548    unnamed = 0549    for path in sorted(DOCS.rglob("*.md")) + [p for p in [DOCS.parent / "README.md"] if p.exists()]:550        text = path.read_text(encoding="utf-8")551        unnamed_here = text.count("```mermaid") - len(BLOCK_RE.findall(text))552        if unnamed_here:553            print(f"error: {path.relative_to(DOCS.parent)} has {unnamed_here} Mermaid block(s) without a '<!-- diagram: name -->' line")554            unnamed += unnamed_here555    print(f"{len(seen)} diagram(s)")556    return 1 if (stale or unnamed) else 0557558559if __name__ == "__main__":560    sys.exit(main())561
Files main
Menu

Theme