reformat_parse.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. #!/usr/bin/env python3
  2. """
  3. reformat_parse.py — Parse a markdown / text / PDF / HTML source into a
  4. self-contained .html file ready for `render_html.cjs`.
  5. Input formats (auto-detected by extension):
  6. .md / .markdown — Markdown (markdown-it-py with GFM table + strikethrough)
  7. .txt — Plain text (treated as a sequence of paragraphs)
  8. .pdf — pdftotext -layout (requires poppler) → markdown-ish
  9. .html / .htm — Pass-through body extraction (<body>…</body>)
  10. Output: a single HTML file (templates/<template>/skeleton.html with
  11. placeholders filled). Hand it to `node scripts/render_html.cjs`.
  12. Usage:
  13. python3 reformat_parse.py --input doc.md --out page.html
  14. python3 reformat_parse.py --input doc.md --out page.html \
  15. --title "Q3 Review" --subtitle "FY26" --author "Jane" --date 2026-04-22 \
  16. --accent "#0066cc" --template default
  17. Exit codes: 0 success, 1 bad args, 2 dep missing, 3 parse error
  18. """
  19. import argparse
  20. import importlib
  21. import importlib.util
  22. import re
  23. import shutil
  24. import subprocess
  25. import sys
  26. from datetime import date as _date
  27. from pathlib import Path
  28. SCRIPTS_DIR = Path(__file__).resolve().parent
  29. SKILL_ROOT = SCRIPTS_DIR.parent
  30. TEMPLATES_DIR = SKILL_ROOT / "templates"
  31. # ── Dependency bootstrap ──────────────────────────────────────────────────────
  32. def ensure_deps() -> None:
  33. missing = []
  34. if importlib.util.find_spec("markdown_it") is None:
  35. missing.append("markdown-it-py")
  36. if not missing:
  37. return
  38. print(f" Installing missing Python packages: {missing}", file=sys.stderr)
  39. subprocess.check_call(
  40. [sys.executable, "-m", "pip", "install", "--break-system-packages", "-q", *missing]
  41. )
  42. ensure_deps()
  43. from markdown_it import MarkdownIt # noqa: E402
  44. # ── Source readers ────────────────────────────────────────────────────────────
  45. def read_source(path: Path) -> str:
  46. """Return markdown-ish text content for any supported input format."""
  47. suffix = path.suffix.lower()
  48. if suffix in (".md", ".markdown", ".txt"):
  49. return path.read_text(encoding="utf-8")
  50. if suffix == ".pdf":
  51. if shutil.which("pdftotext") is None:
  52. sys.exit(
  53. "error: pdftotext not found — install poppler "
  54. "(brew install poppler / apt install poppler-utils) "
  55. "or convert the PDF to .md upstream."
  56. )
  57. out = subprocess.run(
  58. ["pdftotext", "-layout", str(path), "-"],
  59. check=True,
  60. capture_output=True,
  61. text=True,
  62. )
  63. return out.stdout
  64. if suffix in (".html", ".htm"):
  65. # Pass-through: extract <body> if present, otherwise use the whole file.
  66. text = path.read_text(encoding="utf-8")
  67. m = re.search(r"<body[^>]*>(.*?)</body>", text, flags=re.S | re.I)
  68. return m.group(1) if m else text
  69. sys.exit(f"error: unsupported input format: {suffix}")
  70. def is_html_source(path: Path) -> bool:
  71. return path.suffix.lower() in (".html", ".htm")
  72. # ── Markdown → HTML ───────────────────────────────────────────────────────────
  73. def md_to_html(text: str) -> str:
  74. md = (
  75. MarkdownIt("commonmark", {"breaks": False, "html": False, "linkify": True})
  76. .enable("table")
  77. .enable("strikethrough")
  78. )
  79. return md.render(text)
  80. def infer_title_and_body(html: str, fallback_title: str) -> tuple[str, str]:
  81. """If the first element is <h1>, lift it as the document title."""
  82. m = re.match(r"\s*<h1[^>]*>(.*?)</h1>\s*", html, flags=re.S | re.I)
  83. if m:
  84. title = re.sub(r"<[^>]+>", "", m.group(1)).strip()
  85. body = html[m.end():]
  86. return title, body
  87. return fallback_title, html
  88. # ── Template loading + placeholder fill ───────────────────────────────────────
  89. def load_template(template_name: str) -> str:
  90. path = TEMPLATES_DIR / f"reformat-{template_name}" / "skeleton.html"
  91. if not path.exists():
  92. # Allow bare directory name as well.
  93. path = TEMPLATES_DIR / template_name / "skeleton.html"
  94. if not path.exists():
  95. sys.exit(
  96. f"error: reformat template not found: {template_name} "
  97. f"(tried {TEMPLATES_DIR}/reformat-{template_name}/skeleton.html)"
  98. )
  99. return path.read_text(encoding="utf-8")
  100. def fill(template: str, **values: str) -> str:
  101. out = template
  102. for key, val in values.items():
  103. token = f"<!-- {key.upper()} -->"
  104. out = out.replace(token, val if val is not None else "")
  105. return out
  106. # ── Main ──────────────────────────────────────────────────────────────────────
  107. def main() -> int:
  108. ap = argparse.ArgumentParser(description="Parse markdown/text/pdf → HTML")
  109. ap.add_argument("--input", required=True, help="Source file (.md / .txt / .pdf / .html)")
  110. ap.add_argument("--out", required=True, help="Output HTML path")
  111. ap.add_argument("--title", default="", help="Document title (default: first H1 or filename)")
  112. ap.add_argument("--subtitle", default="", help="Subtitle (cover line 2)")
  113. ap.add_argument("--author", default="", help="Author")
  114. ap.add_argument("--date", default="", help="Date (default: today)")
  115. ap.add_argument("--accent", default="#1d4ed8", help="Accent color (CSS hex)")
  116. ap.add_argument("--template", default="default", help="reformat-* template slug")
  117. args = ap.parse_args()
  118. src = Path(args.input)
  119. if not src.exists():
  120. sys.exit(f"error: input not found: {src}")
  121. raw = read_source(src)
  122. # If source is HTML, treat it as already-rendered body; otherwise render
  123. # markdown.
  124. body_html = raw if is_html_source(src) else md_to_html(raw)
  125. fallback_title = src.stem.replace("_", " ").replace("-", " ").strip().title()
  126. title, body_html = infer_title_and_body(body_html, args.title or fallback_title)
  127. template = load_template(args.template)
  128. page = fill(
  129. template,
  130. title=title,
  131. subtitle=args.subtitle,
  132. author=args.author,
  133. date=args.date or _date.today().isoformat(),
  134. accent=args.accent,
  135. body_html=body_html,
  136. )
  137. out = Path(args.out)
  138. out.parent.mkdir(parents=True, exist_ok=True)
  139. out.write_text(page, encoding="utf-8")
  140. print(f" OK Parsed → {out} (title: {title!r}, {len(body_html):,} chars body)")
  141. return 0
  142. if __name__ == "__main__":
  143. try:
  144. sys.exit(main())
  145. except SystemExit:
  146. raise
  147. except Exception as exc: # noqa: BLE001
  148. print(f"error: {exc}", file=sys.stderr)
  149. sys.exit(3)