Files
seal-use/report-templates/render.py
T

353 lines
16 KiB
Python
Raw 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
# -*- coding: utf-8 -*-
"""md → 渲染产物三件套:HTML + 全长度 PNG + A4 PDF。
用法:
python3 tools/render.py 模板.md -o build/模板
# 产出 build/模板.html、build/模板.png(完整长图,非第一页)、build/模板.pdf(A4 分页)
PNG 先量出文档真实高度再整页截取;超过单次截取上限时自动分带截取并用 Pillow 拼接。
PDF 走 Chrome 打印管线,A4 分页,表头跨页重复、行不跨页截断。
"""
from __future__ import annotations
import argparse
import base64
import html as html_module
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import unquote
CHROME = ""
BROWSER_PROFILE = ""
PNG_WIDTH = 1200 # PNG 视口宽度(CSS 像素)
PNG_BAND = 14000 # 单次截取的最大高度,超出则分带拼接
# KaTeX 公式渲染(CDN 引入一次并缓存到本地,此后渲染不依赖网络)
KATEX_CSS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css"
KATEX_JS = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"
KATEX_AUTO = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
CSS = """
:root { --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --bg:#fff; --head:#f6f8fa; }
* { box-sizing: border-box; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
body { margin:0 auto; max-width:900px; padding:48px 56px; background:var(--bg); color:var(--fg);
font:16px/1.75 -apple-system,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;
-webkit-font-smoothing:antialiased; }
h1 { font-size:28px; line-height:1.35; margin:0 0 20px; padding-bottom:14px; border-bottom:2px solid var(--line); }
h2 { font-size:22px; margin:40px 0 14px; padding-bottom:8px; border-bottom:1px solid var(--line); }
h3 { font-size:18px; margin:28px 0 12px; }
h4 { font-size:16px; margin:22px 0 10px; color:var(--muted); }
p, li { margin:10px 0; }
blockquote { margin:16px 0; padding:10px 18px; border-left:4px solid #4c8bf5; background:var(--head);
color:#33404d; border-radius:0 6px 6px 0; }
blockquote p { margin:6px 0; }
code { background:rgba(129,139,152,.14); padding:.15em .4em; border-radius:4px;
font:.9em ui-monospace,SFMono-Regular,Menlo,monospace; }
pre { background:#0d1117; color:#e6edf3; padding:16px 18px; border-radius:8px; overflow:auto; }
pre code { background:none; padding:0; color:inherit; font-size:13px; line-height:1.6; }
table { border-collapse:collapse; width:100%; margin:16px 0; font-size:14px; }
th, td { border:1px solid var(--line); padding:8px 10px; text-align:left; vertical-align:top; }
th { background:var(--head); font-weight:600; }
tr:nth-child(even) td { background:#fbfcfd; }
img { max-width:100%; border:1px solid var(--line); border-radius:6px; display:block; margin:14px 0; }
em { color:var(--muted); font-size:14px; }
hr { border:0; border-top:1px solid var(--line); margin:32px 0; }
a { color:#0969da; }
.katex-display { margin:18px 0; }
@page { size: A4; margin: 14mm 12mm; }
@media print {
body { max-width:none; padding:0; font-size:12pt; }
h2, h3 { page-break-after:avoid; break-after:avoid; }
tr, img, blockquote { page-break-inside:avoid; break-inside:avoid; }
thead { display:table-header-group; }
}
"""
def chrome(args: list[str], timeout: int = 60) -> subprocess.CompletedProcess:
return subprocess.run(
[CHROME, "--headless", "--disable-gpu", "--hide-scrollbars",
f"--user-data-dir={BROWSER_PROFILE}", "--no-first-run", "--no-default-browser-check",
"--run-all-compositor-stages-before-draw", *args],
capture_output=True, text=True, timeout=timeout, check=True,
)
def find_chrome(explicit: str | None) -> str:
# A dedicated headless shell avoids desktop Chrome startup/shutdown problems on headless hosts.
cached_shells = []
if not explicit:
for root in (Path.home() / "Library/Caches/ms-playwright", Path.home() / ".cache/ms-playwright",
Path(os.environ.get("LOCALAPPDATA", "")) / "ms-playwright"):
cached_shells.extend(root.glob("chromium_headless_shell-*/chrome-headless-shell-*/chrome-headless-shell*"))
cached_shells = sorted((p for p in cached_shells if p.is_file()), key=lambda p: p.stat().st_mtime, reverse=True)
candidates = [shutil.which(explicit) or explicit] if explicit else [
shutil.which("chrome-headless-shell"), *map(str, cached_shells),
*[shutil.which(name) for name in ("google-chrome", "chromium", "chromium-browser", "chrome", "msedge")],
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
str(Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "Google/Chrome/Application/chrome.exe"),
str(Path(os.environ.get("PROGRAMFILES(X86)", "C:/Program Files (x86)")) / "Microsoft/Edge/Application/msedge.exe"),
]
for candidate in candidates:
if candidate and Path(candidate).is_file() and os.access(candidate, os.X_OK):
return candidate
raise RuntimeError("未找到 Chrome/Chromium:请安装浏览器,或通过 --chrome <可执行文件> 指定")
def doc_title(md: str, fallback: str) -> str:
"""标题取自正文 H1;顺带剥掉可能夹在里面的 HTML 注释。"""
m = re.search(r"(?m)^#\s+(.+?)\s*$", md)
if not m:
return fallback
return re.sub(r"<!--.*?-->", "", m.group(1), flags=re.S).strip() or fallback
def md_to_html(md: str) -> str:
with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as f:
f.write(md)
tmp = f.name
try:
res = subprocess.run(["npx", "--yes", "marked@15", "-i", tmp],
capture_output=True, text=True, check=True)
finally:
Path(tmp).unlink(missing_ok=True)
return res.stdout
def build_html(src: Path, body_file: str | None = None) -> tuple[str, str]:
"""渲染出完整 HTML 文本,返回 (html, 标题)。"""
text = src.read_text(encoding="utf-8")
body = Path(body_file).read_text(encoding="utf-8") if body_file else md_to_html(text)
base = src.resolve().parent
# 本地图片内嵌进 HTML;marked 输出已做一次百分号编码,先 unquote 再转。
# 产物移动到其他目录或发送给别人后,仍能显示配图。
def absolutize(m: re.Match) -> str:
s = m.group(1)
if s.startswith(("http://", "https://", "file://", "data:")):
return m.group(0)
path = base / html_module.unescape(unquote(s))
mime = {".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}.get(path.suffix.lower(), "application/octet-stream")
data = base64.b64encode(path.read_bytes()).decode("ascii")
return m.group(0).replace(s, f"data:{mime};base64,{data}", 1)
body = re.sub(r'<img src="([^"]+)"', absolutize, body)
title = doc_title(text, src.stem)
# $…$ / $$…$$ → KaTeX 显示式;原文中的反斜杠需先转义回渲染器写法
has_math = False
if "$$" in text or re.search(r"(?<!\\)\$(?!\$)[^$]+?\$(?!\$)", text):
has_math = True
body = body.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&")
def _display(m: re.Match) -> str:
# KaTeX 把裸 % 当注释符,须转义
return "\\(\\displaystyle " + m.group(1).replace("%", "\\%") + " \\)"
def _inline(m: re.Match) -> str:
return "\\(" + m.group(1).replace("%", "\\%") + " \\)"
body = re.sub(r"\$\$(.+?)\$\$", _display, body, flags=re.S)
body = re.sub(r"(?<!\\)\$(?!\$)([^$]+?)\$(?!\$)", _inline, body)
math_head, scripts = "", ""
if has_math:
css_path, _ = local_assets("katex.min.css", KATEX_CSS)
math_css = Path(css_path).read_text(encoding="utf-8")
font_names = sorted(set(re.findall(r"url\((fonts/[^)]+)\)", math_css)))
with ThreadPoolExecutor(max_workers=8) as pool:
list(pool.map(lambda name: local_assets(name, KATEX_CSS.rsplit("/", 1)[0] + "/" + name), font_names))
# 字体也内嵌,避免 HTML 引用临时脚本目录或缺少 KaTeX 字体。
def embed_font(m: re.Match) -> str:
name = m.group(1)
font_path, _ = local_assets(name, KATEX_CSS.rsplit("/", 1)[0] + "/" + name)
mime = "font/woff2" if name.endswith("woff2") else "font/woff" if name.endswith("woff") else "font/ttf"
data = base64.b64encode(Path(font_path).read_bytes()).decode("ascii")
return f"url(data:{mime};base64,{data})"
math_css = re.sub(r"url\((fonts/[^)]+)\)", embed_font, math_css)
math_head = f"<style>{math_css}</style>\n"
scripts = "\n".join("<script>" + Path(local_assets(n, u)[0]).read_text(encoding="utf-8") + "</script>" for n, u in (
("katex.min.js", KATEX_JS), ("auto-render.min.js", KATEX_AUTO)))
head = (
'<!doctype html>\n<html lang="zh-CN">\n<head>\n<meta charset="utf-8">\n'
f"<title>{html_module.escape(title)}</title>\n" +
math_head +
f"<style>{CSS}</style>\n</head>\n"
)
if has_math:
init = (
"<script>document.addEventListener('DOMContentLoaded',function(){"
"renderMathInElement(document.body,{"
"delimiters:[{left:'\\\\(',right:'\\\\)',display:false}],"
"throwOnError:false});});</script>"
)
body += "\n" + init
body = scripts + "\n" + body
html = head + f"<body>\n{body}\n</body>\n</html>\n"
return html, title
def local_assets(name: str, url: str) -> tuple[str, str]:
"""CDN 资源下载到 .cache/assets 后用本地路径,渲染离线可用;缓存命中不联网。"""
d = Path(os.environ.get("SEAL_REPORT_CACHE_DIR") or Path.home() / ".cache" / "seal-use" / "report-render" / "katex-0.16.11")
f = d / name
f.parent.mkdir(parents=True, exist_ok=True)
if not f.exists() or f.stat().st_size == 0:
with urllib.request.urlopen(url, timeout=30) as response:
content = response.read()
if not content:
raise RuntimeError(f"公式资源下载为空:{name}")
# 原子写入:并发导出或中途失败不留下半个缓存文件。
with tempfile.NamedTemporaryFile(dir=f.parent, delete=False) as temp:
temp.write(content)
Path(temp.name).replace(f)
return str(f), f.as_uri()
def measure_height(html_path: Path, width: int = PNG_WIDTH) -> int:
"""注入测量脚本,用 dump-dom 取文档真实高度(等待全部图片加载完)。"""
probe = html_path.with_name("_measure.html")
script = ("<script>window.addEventListener('load',function(){"
"document.title='PAGEH:'+Math.ceil(document.documentElement.scrollHeight)});"
"setTimeout(function(){document.title='PAGEH:'+Math.ceil("
"document.documentElement.scrollHeight)},3000)</script>")
probe.write_text(html_path.read_text(encoding="utf-8").replace("</body>", script + "</body>"),
encoding="utf-8")
try:
res = chrome([f"--window-size={width},1000", "--virtual-time-budget=30000", "--dump-dom", probe.as_uri()])
finally:
probe.unlink(missing_ok=True)
hits = re.findall(r"PAGEH:(\d+)", res.stdout)
if not hits:
raise RuntimeError("量取页面高度失败:" + res.stderr[-300:])
return int(hits[-1])
def render_png(html_path: Path, png_path: Path, width: int = PNG_WIDTH) -> None:
h = measure_height(html_path, width)
uri = html_path.as_uri()
if h <= PNG_BAND:
chrome([f"--screenshot={png_path}", f"--window-size={width},{h}",
"--virtual-time-budget=30000", uri])
else:
bands: list[Path] = []
offset, i = 0, 0
while offset < h:
bh = min(PNG_BAND, h - offset)
band_html = html_path.with_name(f"_band{i}.html")
band_html.write_text(
html_path.read_text(encoding="utf-8").replace(
"</head>", f"<style>body{{margin-top:-{offset}px}}</style></head>", 1),
encoding="utf-8")
out = html_path.parent / f"_band{i}.png"
chrome([f"--screenshot={out}", f"--window-size={width},{bh}",
"--virtual-time-budget=30000", band_html.as_uri()])
bands.append(out)
band_html.unlink(missing_ok=True)
offset += bh
i += 1
from PIL import Image
imgs = [Image.open(b) for b in bands]
total = sum(im.height for im in imgs)
canvas = Image.new("RGB", (imgs[0].width, total), "white")
y = 0
for im in imgs:
canvas.paste(im, (0, y))
y += im.height
canvas.save(png_path)
for b, im in zip(bands, imgs):
b.unlink(missing_ok=True)
im.close()
def render_pdf(html_path: Path, pdf_path: Path) -> None:
chrome([f"--print-to-pdf={pdf_path}", "--no-pdf-header-footer",
"--virtual-time-budget=30000", html_path.as_uri()])
def main() -> int:
global CHROME, BROWSER_PROFILE
ap = argparse.ArgumentParser()
ap.add_argument("src")
ap.add_argument("-o", "--out", required=True, help="产物路径词干,如 build/模板")
ap.add_argument("--width", type=int, default=PNG_WIDTH, help="PNG 视口宽度")
ap.add_argument("--format", choices=("all", "html", "png", "pdf"), default="all")
ap.add_argument("--body-file", help="CLI 已解析的 HTML 正文;无需 npx")
ap.add_argument("--chrome", help="Chrome/Chromium 可执行文件")
ap.add_argument("--json", action="store_true")
a = ap.parse_args()
src = Path(a.src)
stem = Path(a.out).resolve()
stem.parent.mkdir(parents=True, exist_ok=True)
html_path = stem.with_suffix(".html")
if a.format != "html":
CHROME = find_chrome(a.chrome)
if a.format in ("all", "png"):
try:
import PIL
except ImportError as e:
raise RuntimeError("PNG 导出需要 Pillow:请在当前 Python 环境安装 Pillow") from e
html, _ = build_html(src, a.body_file)
html_path.write_text(html, encoding="utf-8")
png_path = stem.with_suffix(".png")
pdf_path = stem.with_suffix(".pdf")
paths = [html_path]
with tempfile.TemporaryDirectory(prefix="seal-report-chrome-") as profile:
BROWSER_PROFILE = profile
if a.format in ("all", "png"):
render_png(html_path, png_path, a.width)
paths.append(png_path)
if a.format in ("all", "pdf"):
render_pdf(html_path, pdf_path)
paths.append(pdf_path)
if a.json:
print(json.dumps({"artifacts": [{"path": str(p), "format": p.suffix[1:], "bytes": p.stat().st_size} for p in paths]}, ensure_ascii=False))
return 0
for p in paths:
size = p.stat().st_size
extra = ""
if p.suffix == ".png":
try:
from PIL import Image
with Image.open(p) as im:
extra = f",{im.width}×{im.height}px"
except ImportError:
pass
if p.suffix == ".pdf":
try:
import subprocess as sp
r = sp.run(["mdls", "-name", "kMDItemNumberOfPages", "-raw", str(p)],
capture_output=True, text=True)
if r.stdout.strip().isdigit():
extra = f",{r.stdout.strip()} 页"
except Exception:
pass
print(f" {p} ({size / 1024:.0f} KB{extra})")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except subprocess.TimeoutExpired:
print("浏览器渲染超时。可通过 --chrome 指定可用的 Chrome/Chromium 或 chrome-headless-shell。", file=sys.stderr)
raise SystemExit(1)
except Exception as e:
print(str(e), file=sys.stderr)
raise SystemExit(1)