#!/usr/bin/env python3 """ hyperstitionstud_io.publishing.pdf_compiler Unified Dark-Mode ReportLab Markdown-to-PDF Compiler (`hs-pdf-build`) with: - Group 3 `haiperdohp-jemaytreeah ร— hyperstitionstud.io` 45-Deg Chamfered Basalt Frame & 24pt Signal Pip, - Deterministic LaTeX/Math (`T_math`), Missing-Glyph (`T_char`), and Table/Break (`T_elem`) Sanitization, - 100% Embedded DejaVu / DejaVuMono TrueType `charToGlyph` Verification (Zero `/Helvetica` or `.notdef` Tofu Boxes), - Atomic Temp-File Replacement & pypdf Verification. """ from __future__ import annotations import argparse import html import json import os import re import unicodedata from pathlib import Path from typing import Any # Deterministic T_char replacements for glyphs absent from DejaVuSans.ttf / DejaVuSansMono.ttf CHAR_REPLACEMENTS: dict[str, str] = { "โ“˜": "[i]", "โญ": ">>|", "โฎ": "|<<", "\ufe0f": "", "\ufe0e": "", "๐Ÿ“„": "[PDF]", "๐Ÿ“–": "[DOC]", "๐Ÿ“œ": "[DOS]", "๐Ÿ”Š": "[AUD]", "๐Ÿ•ธ": "[KG]", "โšก": "[*]", "โ˜…": "*", "๐”ผ": "E", "โ„": "R", "โ„™": "P", "โ„ค": "Z", "โ„•": "N", } # Deterministic T_math LaTeX macro -> DejaVu-verified Unicode replacements LATEX_MACRO_PATTERNS: list[tuple[str, str]] = [ (r"\\mathbb\{E\}", "E"), (r"\\mathbb\{R\}", "R"), (r"\\mathbb\{P\}", "P"), (r"\\mathbb\{Z\}", "Z"), (r"\\mathbb\{N\}", "N"), (r"\\text\{([^}]*)\}", r"\1"), (r"\\mathrm\{([^}]*)\}", r"\1"), (r"\\textbf\{([^}]*)\}", r"**\1**"), (r"\\textit\{([^}]*)\}", r"*\1*"), (r"\\bar\{\\sigma\}", "ฯƒฬ„"), (r"\\bar\{([^}]*)\}", r"\1ฬ„"), (r"\\hat\{([^}]*)\}", r"\1ฬ‚"), (r"\\Delta", "ฮ”"), (r"\\delta", "ฮด"), (r"\\rho", "ฯ"), (r"\\tau", "ฯ„"), (r"\\sigma", "ฯƒ"), (r"\\mu", "ฮผ"), (r"\\alpha", "ฮฑ"), (r"\\beta", "ฮฒ"), (r"\\gamma", "ฮณ"), (r"\\lambda", "ฮป"), (r"\\pi", "ฯ€"), (r"\\sum", "โˆ‘"), (r"\\prod", "โˆ"), (r"\\in\b", "โˆˆ"), (r"\\notin\b", "โˆ‰"), (r"\\subset\b", "โŠ‚"), (r"\\cup\b", "โˆช"), (r"\\cap\b", "โˆฉ"), (r"\\le(?:q)?\b", "โ‰ค"), (r"\\ge(?:q)?\b", "โ‰ฅ"), (r"\\ne(?:q)?\b", "โ‰ "), (r"\\approx\b", "โ‰ˆ"), (r"\\equiv\b", "โ‰ก"), (r"\\pm\b", "ยฑ"), (r"\\times\b", "ร—"), (r"\\cdot\b", "ยท"), (r"\\rightarrow\b|\\to\b", "โ†’"), (r"\\leftarrow\b", "โ†"), (r"\\leftrightarrow\b", "โ†”"), (r"\\dots\b|\\ldots\b", "..."), (r"\\\{", "{"), (r"\\\}", "}"), (r"\\\|", "|"), ] def _filter_to_cmap(text: str, cmap: dict[int, Any] | None) -> str: """Guarantee that every emitted character exists in the embedded TrueType font's `charToGlyph` table.""" for src, dst in CHAR_REPLACEMENTS.items(): if src in text: text = text.replace(src, dst) if not cmap: return text out: list[str] = [] for ch in text: cp = ord(ch) if cp < 128 or cp in cmap or ch in ("\n", "\r", "\t", "\x00"): out.append(ch) else: decomp = unicodedata.normalize("NFKD", ch).encode("ascii", "ignore").decode("ascii") out.append(decomp if decomp else "?") return "".join(out) def _transpile_latex_segment(seg: str) -> str: s = seg for pat, repl in LATEX_MACRO_PATTERNS: s = re.sub(pat, repl, s) # Remove any remaining unknown \macro backslashes while keeping the word s = re.sub(r"\\([A-Za-z]+)", r"\1", s) return s def _split_markdown_table_row(line: str) -> list[str]: """ Split a Markdown table row `| a | b | c |` ONLY on unescaped `|` characters that are outside backtick `` `...` `` spans, inline `$...$` math spans, and HTML entities (`|`). """ inner = line.strip() if inner.startswith("|"): inner = inner[1:] if inner.endswith("|") and not inner.endswith(r"\|"): inner = inner[:-1] cells: list[str] = [] buf: list[str] = [] in_ticks = False in_math = False i = 0 n = len(inner) while i < n: ch = inner[i] if ch == "`": in_ticks = not in_ticks buf.append(ch) i += 1 elif ch == "$" and not in_ticks and (i == 0 or inner[i - 1] != "\\"): in_math = not in_math buf.append(ch) i += 1 elif ch == "\\" and i + 1 < n and inner[i + 1] == "|": buf.append("|") i += 2 elif ch == "|" and not in_ticks and not in_math: cells.append("".join(buf).strip()) buf = [] i += 1 else: buf.append(ch) i += 1 cells.append("".join(buf).strip()) return cells def _format_inline( text: str, sans_cmap: dict[int, Any] | None = None, mono_cmap: dict[int, Any] | None = None, ) -> str: # 1. Decode HTML pipe entity and preserve
/
as a sentinel before html.escape() s = text.replace("|", "|").replace(r"\|", "|").replace(r"\$", "$") s = re.sub(r"", "\x00BR\x00", s, flags=re.IGNORECASE) # 2. Extract inline `code` spans first so math/markdown regexes do not touch code code_spans: list[str] = [] def _save_code(m: re.Match[str]) -> str: idx = len(code_spans) raw_code = _filter_to_cmap(m.group(1), mono_cmap) escaped_code = html.escape(raw_code, quote=False) code_spans.append(f'{escaped_code}') return f"\x00CODE{idx}\x00" s = re.sub(r"`([^`]+)`", _save_code, s) # 3. Extract Markdown links [label](url) link_spans: list[str] = [] def _save_link(m: re.Match[str]) -> str: idx = len(link_spans) lbl = _filter_to_cmap(m.group(1), sans_cmap) link_spans.append(f'{html.escape(lbl, quote=False)}') return f"\x00LINK{idx}\x00" s = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", _save_link, s) # 4. Transpile inline math $...$ (distinguishing real math from currency like $150.49 ... $212.06) def _replace_math_span(m: re.Match[str]) -> str: inner = m.group(1) # If it starts with a digit and has comma/space/period typical of two currency figures on one line, skip if re.match(r"^\d[\d,.]*[BTMK]?\b.*\s+.*^\d", inner): return m.group(0) return _transpile_latex_segment(inner) s = re.sub(r"\$([^$\n]+)\$", lambda m: _transpile_latex_segment(m.group(1)) if not re.match(r"^\d[\d,.]*\s*[BTMK]?\s+and\s+", m.group(1)) else m.group(0), s) # Also transpile any bare LaTeX macros outside $...$ s = _transpile_latex_segment(s) # 5. Extract _{sub} and ^{sup} before html.escape() sub_spans: list[str] = [] def _save_sub(m: re.Match[str]) -> str: idx = len(sub_spans) val = html.escape(_filter_to_cmap(m.group(1), sans_cmap), quote=False) sub_spans.append(f'{val}') return f"\x00SUB{idx}\x00" sup_spans: list[str] = [] def _save_sup(m: re.Match[str]) -> str: idx = len(sup_spans) val = html.escape(_filter_to_cmap(m.group(1), sans_cmap), quote=False) sup_spans.append(f'{val}') return f"\x00SUP{idx}\x00" s = re.sub(r"_\{([^}]+)\}", _save_sub, s) s = re.sub(r"_([A-Za-z0-9])\b", _save_sub, s) s = re.sub(r"\^\{([^}]+)\}", _save_sup, s) # 6. Filter remaining text against DejaVuSans cmap and escape HTML entities s = _filter_to_cmap(s, sans_cmap) s = html.escape(s, quote=False) # 7. Apply bold (**...**) in warm Amber-Gold (#fbbf24) and italic (*...*) in Silver-Slate (#cbd5e1) s = re.sub(r"\*\*([^*]+)\*\*", r'\1', s) s = re.sub(r"\*([^*]+)\*", r'\1', s) # 8. Restore sentinels s = s.replace("\x00BR\x00", "
") for idx, val in enumerate(sub_spans): s = s.replace(f"\x00SUB{idx}\x00", val) for idx, val in enumerate(sup_spans): s = s.replace(f"\x00SUP{idx}\x00", val) for idx, val in enumerate(link_spans): s = s.replace(f"\x00LINK{idx}\x00", val) for idx, val in enumerate(code_spans): s = s.replace(f"\x00CODE{idx}\x00", val) return s def _wrap_code_line(line: str, max_chars: int = 94) -> list[str]: if len(line) <= max_chars: return [line] out: list[str] = [] rem = line while len(rem) > max_chars: out.append(rem[:max_chars]) rem = " " + rem[max_chars:] if rem: out.append(rem) return out def compile_markdown_to_pdf( md_path: str | Path, pdf_path: str | Path, title: str | None = None, ) -> dict[str, Any]: try: from pypdf import PdfReader from reportlab.lib import colors except ImportError: import subprocess import sys subprocess.run( [sys.executable, "-m", "pip", "install", "--break-system-packages", "--root-user-action=ignore", "-q", "reportlab", "pypdf"], check=True, ) from pypdf import PdfReader from reportlab.lib import colors from reportlab.lib.pagesizes import letter from reportlab.lib.styles import ParagraphStyle from reportlab.lib.units import inch from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.platypus import ( HRFlowable, KeepTogether, Paragraph, Preformatted, SimpleDocTemplate, Spacer, Table, TableStyle, ) from hyperstitionstud_io.publishing.fonts import resolve_font_path md_p = Path(md_path).resolve() pdf_p = Path(pdf_path).resolve() pdf_p.parent.mkdir(parents=True, exist_ok=True) tmp_p = pdf_p.with_suffix(f".tmp.{os.getpid()}.pdf") f_reg = resolve_font_path("DejaVuSans.ttf") f_bold = resolve_font_path("DejaVuSans-Bold.ttf") f_ob = resolve_font_path("DejaVuSans-Oblique.ttf", fallback_filename="DejaVuSans.ttf") f_bob = resolve_font_path("DejaVuSans-BoldOblique.ttf", fallback_filename="DejaVuSans-Bold.ttf") f_mreg = resolve_font_path("DejaVuSansMono.ttf") f_mbold = resolve_font_path("DejaVuSansMono-Bold.ttf") sans_cmap: dict[int, Any] | None = None mono_cmap: dict[int, Any] | None = None if f_reg and f_bold and f_mreg and f_mbold: from reportlab import rl_config tt_sans = TTFont("DejaVu", str(f_reg)) tt_bold = TTFont("DejaVu-Bold", str(f_bold)) tt_ob = TTFont("DejaVu-Oblique", str(f_ob or f_reg)) tt_bob = TTFont("DejaVu-BoldOblique", str(f_bob or f_bold)) tt_mono = TTFont("DejaVuMono", str(f_mreg)) tt_mbold = TTFont("DejaVuMono-Bold", str(f_mbold)) sans_cmap = tt_sans.face.charToGlyph mono_cmap = tt_mono.face.charToGlyph pdfmetrics.registerFont(tt_sans) pdfmetrics.registerFont(tt_bold) pdfmetrics.registerFont(tt_ob) pdfmetrics.registerFont(tt_bob) pdfmetrics.registerFont(tt_mono) pdfmetrics.registerFont(tt_mbold) rl_config.defaultGraphicsFontName = "DejaVu" rl_config.canvas_basefontname = "DejaVu" pdfmetrics.registerFontFamily( "DejaVu", normal="DejaVu", bold="DejaVu-Bold", italic="DejaVu-Oblique", boldItalic="DejaVu-BoldOblique", ) pdfmetrics.registerFontFamily( "DejaVuMono", normal="DejaVuMono", bold="DejaVuMono-Bold", italic="DejaVuMono", boldItalic="DejaVuMono-Bold", ) # Group 3 Dark-Mode Palette Tokens (#020617 Void, #070d1b Well, #0c1324/#111a2e Zebra, #26344d Border) c_void = colors.HexColor("#020617") c_well = colors.HexColor("#070d1b") c_odd = colors.HexColor("#0c1324") c_even = colors.HexColor("#111a2e") c_bezel = colors.HexColor("#182338") c_border = colors.HexColor("#26344d") c_txt_pri = colors.HexColor("#e2e8f0") c_txt_sec = colors.HexColor("#94a3b8") c_gold = colors.HexColor("#f59e0b") c_cyan = colors.HexColor("#38bdf8") c_emerald = colors.HexColor("#10b981") # Standalone ParagraphStyles (zero inheritance from unembedded Helvetica defaults) st_h1 = ParagraphStyle( "HS_H1", fontName="DejaVu-Bold", fontSize=14.0, leading=18.0, textColor=c_gold, backColor=c_odd, borderColor=c_border, borderWidth=0.6, borderPadding=6, spaceBefore=4, spaceAfter=8, ) st_h2 = ParagraphStyle( "HS_H2", fontName="DejaVu-Bold", fontSize=11.2, leading=14.5, textColor=c_cyan, backColor=c_odd, borderColor=c_border, borderWidth=0.5, borderPadding=4, spaceBefore=9, spaceAfter=5, ) st_h3 = ParagraphStyle( "HS_H3", fontName="DejaVu-Bold", fontSize=9.8, leading=13.0, textColor=c_emerald, spaceBefore=6, spaceAfter=3, ) st_body = ParagraphStyle( "HS_Body", fontName="DejaVu", fontSize=8.8, leading=12.6, textColor=c_txt_pri, spaceAfter=4, ) st_bullet = ParagraphStyle( "HS_Bullet", parent=st_body, leftIndent=13, firstLineIndent=-8, spaceAfter=3, ) st_code = ParagraphStyle( "HS_Code", fontName="DejaVuMono", fontSize=6.8, leading=9.2, textColor=c_txt_pri, backColor=c_well, borderColor=c_border, borderWidth=0.6, borderPadding=5, leftIndent=6, rightIndent=6, spaceBefore=4, spaceAfter=6, ) st_th = ParagraphStyle( "HS_TH", fontName="DejaVu-Bold", fontSize=7.6, leading=10.0, textColor=c_gold, ) st_td = ParagraphStyle( "HS_TD", fontName="DejaVu", fontSize=7.6, leading=10.0, textColor=c_txt_pri, ) raw_lines = md_p.read_text(encoding="utf-8").splitlines() story: list[Any] = [] doc_title_clean = _filter_to_cmap(title or md_p.stem, sans_cmap) if title: story.append(Paragraph(_format_inline(title, sans_cmap, mono_cmap), st_h1)) story.append(HRFlowable(width="100%", thickness=1.0, color=c_gold, spaceAfter=6)) in_code = False code_buf: list[str] = [] table_buf: list[list[str]] = [] def _flush_table() -> None: nonlocal table_buf if not table_buf: return rows_clean = [r for r in table_buf if not all(set(c.strip()) <= {"-", ":"} for c in r)] table_buf = [] if not rows_clean: return ncols = max(len(r) for r in rows_clean) avail_w = 7.1 * inch # Proportional column widths bounded between 0.65" and 3.4" so narrow columns never explode height col_weights: list[float] = [] for c_i in range(ncols): max_len = max((len(r[c_i]) if c_i < len(r) else 4) for r in rows_clean) col_weights.append(max(10.0, min(65.0, float(max_len) ** 0.65))) total_w = sum(col_weights) or 1.0 col_w = [(w / total_w) * avail_w for w in col_weights] data_cells = [] for r_idx, r in enumerate(rows_clean): padded = (r + [""] * ncols)[:ncols] st = st_th if r_idx == 0 else st_td data_cells.append([Paragraph(_format_inline(c.strip(), sans_cmap, mono_cmap), st) for c in padded]) tbl = Table(data_cells, colWidths=col_w, repeatRows=1, splitByRow=1) tbl.setStyle( TableStyle( [ ("FONTNAME", (0, 0), (-1, 0), "DejaVu-Bold"), ("FONTNAME", (0, 1), (-1, -1), "DejaVu"), ("BACKGROUND", (0, 0), (-1, 0), c_well), ("LINEBELOW", (0, 0), (-1, 0), 1.0, c_gold), ("ROWBACKGROUNDS", (0, 1), (-1, -1), [c_odd, c_even]), ("GRID", (0, 0), (-1, -1), 0.5, c_border), ("VALIGN", (0, 0), (-1, -1), "TOP"), ("TOPPADDING", (0, 0), (-1, -1), 3.5), ("BOTTOMPADDING", (0, 0), (-1, -1), 3.5), ("LEFTPADDING", (0, 0), (-1, -1), 4.5), ("RIGHTPADDING", (0, 0), (-1, -1), 4.5), ] ) ) story.append(tbl) story.append(Spacer(1, 6)) for ln in raw_lines: if ln.strip().startswith("```"): _flush_table() if in_code: wrapped_code: list[str] = [] for cln in code_buf: clean_cln = _filter_to_cmap(cln, mono_cmap) wrapped_code.extend(_wrap_code_line(clean_cln, max_chars=94)) story.append(Preformatted("\n".join(wrapped_code), st_code)) code_buf = [] in_code = False else: in_code = True continue if in_code: code_buf.append(ln) continue if ln.strip().startswith("|") and ln.strip().endswith("|"): cells = _split_markdown_table_row(ln) table_buf.append(cells) continue else: _flush_table() stripped = ln.strip() if not stripped: story.append(Spacer(1, 3.5)) elif stripped == "---": story.append(HRFlowable(width="100%", thickness=0.6, color=c_border, spaceBefore=4, spaceAfter=4)) elif stripped.startswith("# "): if not title: story.append(Paragraph(_format_inline(stripped[2:].strip(), sans_cmap, mono_cmap), st_h1)) elif stripped.startswith("## "): story.append(KeepTogether([Paragraph(_format_inline(stripped[3:].strip(), sans_cmap, mono_cmap), st_h2)])) elif stripped.startswith("### "): story.append(KeepTogether([Paragraph(_format_inline(stripped[4:].strip(), sans_cmap, mono_cmap), st_h3)])) elif stripped.startswith("#### "): story.append(KeepTogether([Paragraph(_format_inline(stripped[5:].strip(), sans_cmap, mono_cmap), st_h3)])) elif stripped.startswith(("- ", "* ")): story.append(Paragraph("โ€ข " + _format_inline(stripped[2:].strip(), sans_cmap, mono_cmap), st_bullet)) elif re.match(r"^\d+\.\s+", stripped): story.append(Paragraph(_format_inline(stripped, sans_cmap, mono_cmap), st_bullet)) else: story.append(Paragraph(_format_inline(stripped, sans_cmap, mono_cmap), st_body)) _flush_table() if code_buf: wrapped_code = [] for cln in code_buf: clean_cln = _filter_to_cmap(cln, mono_cmap) wrapped_code.extend(_wrap_code_line(clean_cln, max_chars=94)) story.append(Preformatted("\n".join(wrapped_code), st_code)) def _draw_dark_mode_page_frame(canvas: Any, doc_obj: Any) -> None: canvas.saveState() page_w, page_h = letter # 1. Full-bleed Abyssal Obsidian background (#020617) canvas.setFillColor(c_void) canvas.rect(0, 0, page_w, page_h, stroke=0, fill=1) # 2. Group 3 10pt/4pt 45-Deg Chamfered Outer Basalt Frame (margin 0.36") m = 0.36 * inch x0, y0, x1, y1 = m, m, page_w - m, page_h - m ct, cb = 10.0, 4.0 p = canvas.beginPath() p.moveTo(x0 + ct, y1) p.lineTo(x1 - ct, y1) p.lineTo(x1, y1 - ct) p.lineTo(x1, y0 + cb) p.lineTo(x1 - cb, y0) p.lineTo(x0 + cb, y0) p.lineTo(x0, y0 + cb) p.lineTo(x0, y1 - ct) p.close() canvas.setStrokeColor(c_border) canvas.setLineWidth(0.8) canvas.drawPath(p, stroke=1, fill=0) # 3. Group 3 Matte Basalt Top Structural Rail (#182338) + 28pt Left-Shoulder Signal Pip (#f59e0b) canvas.setFillColor(c_bezel) canvas.rect(x0 + ct, y1 - 3.0, (x1 - x0) - 2 * ct, 2.5, stroke=0, fill=1) canvas.setFillColor(c_gold) canvas.rect(x0 + ct + 4.0, y1 - 3.0, 28.0, 2.5, stroke=0, fill=1) # 4. Running Header & Footer in Embedded DejaVuMono (Zero Helvetica!) canvas.setFont("DejaVuMono-Bold", 6.8) canvas.setFillColor(c_txt_sec) canvas.drawString(x0 + 14, y1 - 13, "HYPERSTITION STUDIO // STEALTH BASALT CODEX") canvas.setFont("DejaVuMono", 6.8) canvas.setFillColor(c_cyan) canvas.drawRightString(x1 - 14, y1 - 13, md_p.name[:58]) canvas.setStrokeColor(c_border) canvas.setLineWidth(0.5) canvas.line(x0 + 6, y1 - 17, x1 - 6, y1 - 17) # Footer canvas.line(x0 + 6, y0 + 16, x1 - 6, y0 + 16) canvas.setFont("DejaVuMono", 6.5) canvas.setFillColor(c_txt_sec) canvas.drawString(x0 + 14, y0 + 6, f"urn:io:hyperstitionstud:pdf:{md_p.stem[:42]} โ€ข Zero Synthetic Data") canvas.setFont("DejaVuMono-Bold", 6.8) canvas.setFillColor(c_gold) canvas.drawRightString(x1 - 14, y0 + 6, f"PAGE {doc_obj.page}") canvas.restoreState() doc = SimpleDocTemplate( str(tmp_p), pagesize=letter, leftMargin=0.68 * inch, rightMargin=0.68 * inch, topMargin=0.66 * inch, bottomMargin=0.64 * inch, title=doc_title_clean, ) doc.build(story, onFirstPage=_draw_dark_mode_page_frame, onLaterPages=_draw_dark_mode_page_frame) os.replace(tmp_p, pdf_p) reader = PdfReader(str(pdf_p)) extracted_chars = sum(len(page.extract_text() or "") for page in reader.pages) return { "md_path": str(md_p), "pdf_path": str(pdf_p), "page_count": len(reader.pages), "extracted_chars": extracted_chars, "dark_mode_style": "group_3_stealth_basalt", } def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="hs-pdf-build", description="Compile Markdown to verified Dark-Mode ReportLab PDF.") ap.add_argument("--md", required=True) ap.add_argument("--pdf", required=True) ap.add_argument("--title", default=None) args = ap.parse_args(argv) res = compile_markdown_to_pdf(args.md, args.pdf, title=args.title) print(json.dumps(res, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())