168 lines
6.9 KiB
Python
Executable File
168 lines
6.9 KiB
Python
Executable File
#!/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("Δ", '<font name="Symbol">D</font>')
|
||
text = text.replace("δ", '<font name="Symbol">d</font>')
|
||
text = text.replace("μ", '<font name="Symbol">m</font>')
|
||
text = text.replace("σ", '<font name="Symbol">s</font>')
|
||
text = text.replace("π", '<font name="Symbol">p</font>')
|
||
text = (
|
||
text.replace("⁰", "<super>0</super>")
|
||
.replace("¹", "<super>1</super>")
|
||
.replace("²", "<super>2</super>")
|
||
.replace("³", "<super>3</super>")
|
||
.replace("⁴", "<super>4</super>")
|
||
.replace("⁵", "<super>5</super>")
|
||
.replace("⁶", "<super>6</super>")
|
||
.replace("⁷", "<super>7</super>")
|
||
.replace("⁸", "<super>8</super>")
|
||
.replace("⁹", "<super>9</super>")
|
||
.replace("√", "sqrt")
|
||
.replace("≈", "~")
|
||
)
|
||
code_spans: list[str] = []
|
||
|
||
def save_code(m: re.Match) -> str:
|
||
idx = len(code_spans)
|
||
code_spans.append(f'<font name="Courier">{m.group(1)}</font>')
|
||
return f"\x00CODE{idx}\x00"
|
||
|
||
text = re.sub(r"`([^`]+)`", save_code, text)
|
||
text = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", text)
|
||
text = re.sub(r"\*([^*]+)\*", r"<i>\1</i>", 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'(?<!\\)\|(?=(?:[^`]*`[^`]*`)*[^`]*$)', s)[1:-1]]
|
||
if all(re.fullmatch(r":?-+:?", c) for c in cols):
|
||
in_table = True
|
||
continue
|
||
if not in_table and not headers:
|
||
headers = cols
|
||
continue
|
||
parts = [f"**{re.sub(r'\\*\\*([^*]+)\\*\\*', r'\\1', h)}:** {v}" for h, v in zip(headers, cols)]
|
||
story.append(Paragraph("• " + fmt_inline_safe(" | ".join(parts)), bullet))
|
||
continue
|
||
in_table, headers = False, []
|
||
if s.startswith("# "):
|
||
story.append(Paragraph(fmt_inline_safe(s[2:]), h1))
|
||
elif s.startswith("## "):
|
||
story.append(Paragraph(fmt_inline_safe(s[3:]), h2))
|
||
elif s.startswith("### "):
|
||
story.append(Paragraph(fmt_inline_safe(s[4:]), h3))
|
||
elif line.startswith(" - ") or line.startswith(" - ") or line.startswith(" - "):
|
||
story.append(Paragraph("◦ " + fmt_inline_safe(s[2:]), subbullet))
|
||
elif re.match(r"^\s+\d+\.\s+", line):
|
||
story.append(Paragraph(fmt_inline_safe(s), subbullet))
|
||
elif s.startswith("- "):
|
||
story.append(Paragraph("• " + fmt_inline_safe(s[2:]), bullet))
|
||
elif re.match(r"^\d+\.\s+", s):
|
||
story.append(Paragraph(fmt_inline_safe(s), bullet))
|
||
else:
|
||
story.append(Paragraph(fmt_inline_safe(s), body))
|
||
|
||
doc.build(story, onFirstPage=add_page_number, onLaterPages=add_page_number)
|
||
|
||
reader = PdfReader(pdf_path)
|
||
with pdfplumber.open(pdf_path) as pdf:
|
||
chars = sum(len(p.extract_text() or "") for p in pdf.pages)
|
||
return {
|
||
"md_path": md_path,
|
||
"pdf_path": pdf_path,
|
||
"page_count": len(reader.pages),
|
||
"extracted_chars": chars,
|
||
}
|
||
|
||
|
||
def main() -> 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())
|