#!/usr/bin/env python3 """ build_wire_report_pdf.py Deterministic ReportLab PDF compiler & ASCII/mechanism verifier for `isopsephic-wire-report-synthesis`. Safely masks inline backtick code spans before applying bold/italic tags and verifies the resulting PDF via pypdf and pdfplumber. """ from __future__ import annotations import argparse import json import re import sys from pathlib import Path from xml.sax.saxutils import escape def fmt_inline_safe(text: str) -> str: text = escape(text) text = text.replace("Δ", 'D') text = text.replace("δ", 'd') text = text.replace("μ", 'm') text = text.replace("σ", 's') text = text.replace("π", 'p') text = ( text.replace("⁰", "0") .replace("¹", "1") .replace("²", "2") .replace("³", "3") .replace("⁴", "4") .replace("⁵", "5") .replace("⁶", "6") .replace("⁷", "7") .replace("⁸", "8") .replace("⁹", "9") .replace("√", "sqrt") .replace("≈", "~") ) code_spans: list[str] = [] def save_code(m: re.Match) -> str: idx = len(code_spans) code_spans.append(f'{m.group(1)}') return f"\x00CODE{idx}\x00" text = re.sub(r"`([^`]+)`", save_code, text) text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) text = re.sub(r"\*([^*]+)\*", r"\1", text) for idx, span in enumerate(code_spans): text = text.replace(f"\x00CODE{idx}\x00", span) return text def build_pdf(md_path: str, pdf_path: str, title: str) -> dict: try: from reportlab.lib import colors from reportlab.lib.pagesizes import letter from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet from reportlab.platypus import HRFlowable, Paragraph, SimpleDocTemplate, Spacer from pypdf import PdfReader import pdfplumber except ImportError: import subprocess subprocess.run( [sys.executable, "-m", "pip", "install", "--root-user-action=ignore", "--cache-dir", "/tmp/.pip", "reportlab", "pypdf", "pdfplumber"], check=True, stdout=subprocess.DEVNULL, ) from reportlab.lib import colors from reportlab.lib.pagesizes import letter from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet from reportlab.platypus import HRFlowable, Paragraph, SimpleDocTemplate, Spacer from pypdf import PdfReader import pdfplumber def add_page_number(canvas, doc): canvas.saveState() canvas.setFont("Helvetica", 9) canvas.setFillColor(colors.HexColor("#555555")) canvas.drawRightString(letter[0] - 54, 36, f"Page {doc.page}") canvas.restoreState() lines = Path(md_path).read_text(encoding="utf-8").splitlines() doc = SimpleDocTemplate( pdf_path, pagesize=letter, leftMargin=54, rightMargin=54, topMargin=54, bottomMargin=54, title=title, author="Hermes Agent", ) styles = getSampleStyleSheet() h1 = ParagraphStyle("H1", parent=styles["Heading1"], fontName="Helvetica-Bold", fontSize=15, leading=19, spaceAfter=8, textColor=colors.HexColor("#111111")) h2 = ParagraphStyle("H2", parent=styles["Heading2"], fontName="Helvetica-Bold", fontSize=12.5, leading=16, spaceBefore=10, spaceAfter=6, textColor=colors.HexColor("#1a1a1a")) h3 = ParagraphStyle("H3", parent=styles["Heading3"], fontName="Helvetica-Bold", fontSize=10.5, leading=14, spaceBefore=8, spaceAfter=4, textColor=colors.HexColor("#222222")) body = ParagraphStyle("Body", parent=styles["Normal"], fontName="Helvetica", fontSize=9.5, leading=13.5, spaceAfter=5) bullet = ParagraphStyle("Bullet", parent=body, leftIndent=14, firstLineIndent=-8, spaceAfter=4) subbullet = ParagraphStyle("SubBullet", parent=body, leftIndent=28, firstLineIndent=-8, spaceAfter=3) story, headers, in_table = [], [], False for line in lines: s = line.strip() if not s: in_table, headers = False, [] continue if s == "---": story.extend([Spacer(1, 4), HRFlowable(width="100%", thickness=0.6, color=colors.HexColor("#cccccc")), Spacer(1, 4)]) continue if s.startswith("|") and s.endswith("|"): cols = [c.strip() for c in re.split(r'(? int: ap = argparse.ArgumentParser(description="Compile wire report Markdown to verified PDF.") ap.add_argument("--md", required=True, help="Input Markdown file path") ap.add_argument("--pdf", required=True, help="Output PDF file path") ap.add_argument("--title", default="Isopsephic Wire Report", help="PDF document title") args = ap.parse_args() res = build_pdf(args.md, args.pdf, args.title) print(json.dumps(res, indent=2)) return 0 if res["page_count"] >= 1 and res["extracted_chars"] > 0 else 1 if __name__ == "__main__": raise SystemExit(main())