Release v2.0.25: Dark-mode hs-pdf-build, bidirectional 14-point census & Dose 0..3+, FRED macro indicators, 5-agenda Bayesian daily brief, one-shot .png+.json chatbot stats cards, Group 3 unified style, and minimal /donate/ reduction
This commit is contained in:
1 parent
74ef8b60a6
commit
d91d36ca5e
35 files changed
+14332
-2898
No files matched your search
@@ -1,7 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
hyperstitionstud_io.publishing.pdf_compiler
|
||||
Unified ReportLab Markdown-to-PDF Compiler with Atomic Temp-File Replacement & pypdf Verification.
|
||||
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
|
||||
@@ -11,36 +15,262 @@ 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",
|
||||
}
|
||||
|
||||
def _format_inline(text: str) -> str:
|
||||
# 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 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
|
||||
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 i + 1 < n and inner[i + 1] == "|":
|
||||
buf.append("|")
|
||||
i += 2
|
||||
elif ch == "|" and not in_ticks:
|
||||
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 <br/> / <br> as a sentinel before html.escape()
|
||||
s = text.replace("|", "|").replace(r"\|", "|").replace(r"\$", "$")
|
||||
s = re.sub(r"<br\s*/?>", "\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)
|
||||
code_spans.append(f'<font name="DejaVuMono" size="8.5" color="#8B1A1A">{html.escape(m.group(1), quote=False)}</font>')
|
||||
raw_code = _filter_to_cmap(m.group(1), mono_cmap)
|
||||
escaped_code = html.escape(raw_code, quote=False)
|
||||
code_spans.append(f'<font name="DejaVuMono" size="8.2" color="#38bdf8">{escaped_code}</font>')
|
||||
return f"\x00CODE{idx}\x00"
|
||||
|
||||
s = re.sub(r"`([^`]+)`", _save_code, text)
|
||||
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'<font color="#38bdf8"><u>{html.escape(lbl, quote=False)}</u></font>')
|
||||
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'<sub rise="-2" size="6.5">{val}</sub>')
|
||||
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'<super rise="3" size="6.5">{val}</super>')
|
||||
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)
|
||||
s = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", s)
|
||||
s = re.sub(r"\*([^*]+)\*", r"<i>\1</i>", s)
|
||||
|
||||
# 7. Apply bold (**...**) in warm Amber-Gold (#fbbf24) and italic (*...*) in Silver-Slate (#cbd5e1)
|
||||
s = re.sub(r"\*\*([^*]+)\*\*", r'<font name="DejaVu-Bold" color="#fbbf24">\1</font>', s)
|
||||
s = re.sub(r"\*([^*]+)\*", r'<font name="DejaVu-Oblique" color="#cbd5e1">\1</font>', s)
|
||||
|
||||
# 8. Restore sentinels
|
||||
s = s.replace("\x00BR\x00", "<br/>")
|
||||
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]:
|
||||
from pypdf import PdfReader
|
||||
from reportlab.lib import colors
|
||||
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, getSampleStyleSheet
|
||||
from reportlab.lib.styles import ParagraphStyle
|
||||
from reportlab.lib.units import inch
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
@@ -68,13 +298,30 @@ def compile_markdown_to_pdf(
|
||||
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:
|
||||
pdfmetrics.registerFont(TTFont("DejaVu", str(f_reg)))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-Bold", str(f_bold)))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-Oblique", str(f_ob or f_reg)))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-BoldOblique", str(f_bob or f_bold)))
|
||||
pdfmetrics.registerFont(TTFont("DejaVuMono", str(f_mreg)))
|
||||
pdfmetrics.registerFont(TTFont("DejaVuMono-Bold", str(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",
|
||||
@@ -82,25 +329,114 @@ def compile_markdown_to_pdf(
|
||||
italic="DejaVu-Oblique",
|
||||
boldItalic="DejaVu-BoldOblique",
|
||||
)
|
||||
base_font, bold_font, mono_font = "DejaVu", "DejaVu-Bold", "DejaVuMono"
|
||||
else:
|
||||
base_font, bold_font, mono_font = "Helvetica", "Helvetica-Bold", "Courier"
|
||||
pdfmetrics.registerFontFamily(
|
||||
"DejaVuMono",
|
||||
normal="DejaVuMono",
|
||||
bold="DejaVuMono-Bold",
|
||||
italic="DejaVuMono",
|
||||
boldItalic="DejaVuMono-Bold",
|
||||
)
|
||||
|
||||
styles = getSampleStyleSheet()
|
||||
st_h1 = ParagraphStyle("HS_H1", parent=styles["Heading1"], fontName="DejaVu-Bold", fontSize=15, leading=19, textColor=colors.HexColor("#111827"), spaceAfter=8)
|
||||
st_h2 = ParagraphStyle("HS_H2", parent=styles["Heading2"], fontName="DejaVu-Bold", fontSize=12, leading=15, textColor=colors.HexColor("#8B1A1A"), spaceBefore=10, spaceAfter=5)
|
||||
st_h3 = ParagraphStyle("HS_H3", parent=styles["Heading3"], fontName="DejaVu-Bold", fontSize=10.5, leading=13.5, textColor=colors.HexColor("#1F2937"), spaceBefore=7, spaceAfter=4)
|
||||
st_body = ParagraphStyle("HS_Body", parent=styles["BodyText"], fontName="DejaVu", fontSize=9.2, leading=13, textColor=colors.HexColor("#1F2937"), spaceAfter=5)
|
||||
st_bullet = ParagraphStyle("HS_Bullet", parent=st_body, leftIndent=14, firstLineIndent=-8, spaceAfter=3)
|
||||
st_code = ParagraphStyle("HS_Code", fontName="DejaVuMono", fontSize=7.5, leading=10, textColor=colors.HexColor("#111827"), backColor=colors.HexColor("#F3F4F6"), leftIndent=6, rightIndent=6, spaceBefore=4, spaceAfter=6)
|
||||
st_th = ParagraphStyle("HS_TH", fontName="DejaVu-Bold", fontSize=8.0, leading=10.5, textColor=colors.white)
|
||||
st_td = ParagraphStyle("HS_TD", fontName="DejaVu", fontSize=8.0, leading=10.5, textColor=colors.HexColor("#111827"))
|
||||
# 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), st_h1))
|
||||
story.append(HRFlowable(width="100%", thickness=1.2, color=colors.HexColor("#8B1A1A"), spaceAfter=8))
|
||||
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] = []
|
||||
@@ -115,25 +451,35 @@ def compile_markdown_to_pdf(
|
||||
if not rows_clean:
|
||||
return
|
||||
ncols = max(len(r) for r in rows_clean)
|
||||
avail_w = 7.0 * inch
|
||||
col_w = [avail_w / ncols] * ncols
|
||||
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()), st) for c in padded])
|
||||
tbl = Table(data_cells, colWidths=col_w, repeatRows=1)
|
||||
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(
|
||||
[
|
||||
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1F2937")),
|
||||
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#F9FAFB")]),
|
||||
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#D1D5DB")),
|
||||
("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), 4),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
|
||||
("LEFTPADDING", (0, 0), (-1, -1), 5),
|
||||
("RIGHTPADDING", (0, 0), (-1, -1), 5),
|
||||
("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),
|
||||
]
|
||||
)
|
||||
)
|
||||
@@ -144,7 +490,11 @@ def compile_markdown_to_pdf(
|
||||
if ln.strip().startswith("```"):
|
||||
_flush_table()
|
||||
if in_code:
|
||||
story.append(Preformatted("\n".join(code_buf), st_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:
|
||||
@@ -154,7 +504,7 @@ def compile_markdown_to_pdf(
|
||||
code_buf.append(ln)
|
||||
continue
|
||||
if ln.strip().startswith("|") and ln.strip().endswith("|"):
|
||||
cells = [c.strip() for c in ln.strip()[1:-1].split("|")]
|
||||
cells = _split_markdown_table_row(ln)
|
||||
table_buf.append(cells)
|
||||
continue
|
||||
else:
|
||||
@@ -162,37 +512,95 @@ def compile_markdown_to_pdf(
|
||||
|
||||
stripped = ln.strip()
|
||||
if not stripped:
|
||||
story.append(Spacer(1, 4))
|
||||
story.append(Spacer(1, 3.5))
|
||||
elif stripped == "---":
|
||||
story.append(HRFlowable(width="100%", thickness=0.6, color=colors.HexColor("#D1D5DB"), spaceBefore=4, spaceAfter=4))
|
||||
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()), st_h1))
|
||||
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()), st_h2)]))
|
||||
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()), st_h3)]))
|
||||
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()), st_bullet))
|
||||
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), st_bullet))
|
||||
story.append(Paragraph(_format_inline(stripped, sans_cmap, mono_cmap), st_bullet))
|
||||
else:
|
||||
story.append(Paragraph(_format_inline(stripped), st_body))
|
||||
story.append(Paragraph(_format_inline(stripped, sans_cmap, mono_cmap), st_body))
|
||||
|
||||
_flush_table()
|
||||
if code_buf:
|
||||
story.append(Preformatted("\n".join(code_buf), st_code))
|
||||
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.65 * inch,
|
||||
rightMargin=0.65 * inch,
|
||||
topMargin=0.60 * inch,
|
||||
bottomMargin=0.60 * inch,
|
||||
title=title or md_p.stem,
|
||||
leftMargin=0.68 * inch,
|
||||
rightMargin=0.68 * inch,
|
||||
topMargin=0.66 * inch,
|
||||
bottomMargin=0.64 * inch,
|
||||
title=doc_title_clean,
|
||||
)
|
||||
doc.build(story)
|
||||
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))
|
||||
@@ -202,11 +610,12 @@ def compile_markdown_to_pdf(
|
||||
"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 ReportLab PDF.")
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user