Files
Hermes Agent 44c48bb12a chore(repo): finalize 3-repo separation, sync 8 AQ skills/scripts, and add Eval 47
- Remove legacy tracked hyperdope-ci-build/* files (moved to sibling repo /workspace/hyperdope-ci-build).
- Remove duplicate root news dossiers (25, 46) and duplicate archive PDF compendium per Archive File Hygiene Rule.
- Add evaluate_aq.mjs, generate_aq_tier_list.py, build_wire_report_pdf.py, pdf_create.py, and pdf_read.py to ingglish-aq-archive/scripts/.
- Synchronize all 8 scripts and 8 creative Ingglish AQ skills into packaging/bundle/ and rebuild .tar.gz / .tar.xz bundles.
- Update reconstruct_option4_curve.py and option-4-curve-migration-manifest.json paths to /workspace/ingglish-hyperdope-gematria/.
- Add 47-eval-news-2026-11-02-bidirectional (.md + .pdf) and update master 17-dossier tier list (.md, .pdf, .png).
- Track Series I-V repeat lecture transcripts, genealogy compendium, repdigit compendium, and wire report artifacts.
2026-11-03 07:24:55 +00:00

160 lines
6.6 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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>4</super>")
.replace("⁵", "<super>5</super>")
.replace("⁶", "<super>6</super>")
.replace("⁷", "<super>7</super>")
)
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())