feat(core): initialize hyperstitionstudio-core (hyperstitionstud_io.* / urn:io:hyperstitionstud:*) shared library, 4897-entry offline CMUdict fallback, local-config citation resolver, CLI entrypoints, and test suite (v1.2.0)
This commit is contained in:
commit
f8235a2037
32 files changed
+6646
No files matched your search
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
hyperstitionstud_io.publishing.pdf_compiler
|
||||
Unified ReportLab Markdown-to-PDF Compiler with Atomic Temp-File Replacement & pypdf Verification.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _format_inline(text: str) -> str:
|
||||
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>')
|
||||
return f"\x00CODE{idx}\x00"
|
||||
|
||||
s = re.sub(r"`([^`]+)`", _save_code, text)
|
||||
s = html.escape(s, quote=False)
|
||||
s = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", s)
|
||||
s = re.sub(r"\*([^*]+)\*", r"<i>\1</i>", s)
|
||||
for idx, val in enumerate(code_spans):
|
||||
s = s.replace(f"\x00CODE{idx}\x00", val)
|
||||
return s
|
||||
|
||||
|
||||
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
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
|
||||
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,
|
||||
)
|
||||
|
||||
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")
|
||||
|
||||
oblique_ttf = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Oblique.ttf"
|
||||
bold_oblique_ttf = "/usr/share/fonts/truetype/dejavu/DejaVuSans-BoldOblique.ttf"
|
||||
pdfmetrics.registerFont(TTFont("DejaVu", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-Bold", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-Oblique", oblique_ttf if Path(oblique_ttf).is_file() else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-BoldOblique", bold_oblique_ttf if Path(bold_oblique_ttf).is_file() else "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVuMono", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVuMono-Bold", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"))
|
||||
pdfmetrics.registerFontFamily(
|
||||
"DejaVu",
|
||||
normal="DejaVu",
|
||||
bold="DejaVu-Bold",
|
||||
italic="DejaVu-Oblique",
|
||||
boldItalic="DejaVu-BoldOblique",
|
||||
)
|
||||
|
||||
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"))
|
||||
|
||||
raw_lines = md_p.read_text(encoding="utf-8").splitlines()
|
||||
story: list[Any] = []
|
||||
if title:
|
||||
story.append(Paragraph(_format_inline(title), st_h1))
|
||||
story.append(HRFlowable(width="100%", thickness=1.2, color=colors.HexColor("#8B1A1A"), spaceAfter=8))
|
||||
|
||||
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.0 * inch
|
||||
col_w = [avail_w / ncols] * ncols
|
||||
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)
|
||||
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")),
|
||||
("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),
|
||||
]
|
||||
)
|
||||
)
|
||||
story.append(tbl)
|
||||
story.append(Spacer(1, 6))
|
||||
|
||||
for ln in raw_lines:
|
||||
if ln.strip().startswith("```"):
|
||||
_flush_table()
|
||||
if in_code:
|
||||
story.append(Preformatted("\n".join(code_buf), 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 = [c.strip() for c in ln.strip()[1:-1].split("|")]
|
||||
table_buf.append(cells)
|
||||
continue
|
||||
else:
|
||||
_flush_table()
|
||||
|
||||
stripped = ln.strip()
|
||||
if not stripped:
|
||||
story.append(Spacer(1, 4))
|
||||
elif stripped == "---":
|
||||
story.append(HRFlowable(width="100%", thickness=0.6, color=colors.HexColor("#D1D5DB"), spaceBefore=4, spaceAfter=4))
|
||||
elif stripped.startswith("# "):
|
||||
if not title:
|
||||
story.append(Paragraph(_format_inline(stripped[2:].strip()), st_h1))
|
||||
elif stripped.startswith("## "):
|
||||
story.append(KeepTogether([Paragraph(_format_inline(stripped[3:].strip()), st_h2)]))
|
||||
elif stripped.startswith("### "):
|
||||
story.append(KeepTogether([Paragraph(_format_inline(stripped[4:].strip()), st_h3)]))
|
||||
elif stripped.startswith(("- ", "* ")):
|
||||
story.append(Paragraph("• " + _format_inline(stripped[2:].strip()), st_bullet))
|
||||
elif re.match(r"^\d+\.\s+", stripped):
|
||||
story.append(Paragraph(_format_inline(stripped), st_bullet))
|
||||
else:
|
||||
story.append(Paragraph(_format_inline(stripped), st_body))
|
||||
|
||||
_flush_table()
|
||||
if code_buf:
|
||||
story.append(Preformatted("\n".join(code_buf), st_code))
|
||||
|
||||
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,
|
||||
)
|
||||
doc.build(story)
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(prog="hs-pdf-build", description="Compile Markdown to verified 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())
|
||||
Reference in new issue
Block a user