Remove legacy report Python scripts and update documentation

This commit is contained in:
gitea committed 2026-10-12 15:12:25 +08:00
1 parent 736728496f
commit 90c366ebb2
3 files changed
-605

No files matched your search

-1
View File
@@ -8,7 +8,6 @@
| `assets/` | 报告配图(图 1 数据图、图 2/3 占位图),相对引用,渲染时随 md 一起解析 |
| `examples/` | 填充真实数据的成品示例(结构参考 + 测试夹具) |
| `report.css` | HTML、长图和 A4 PDF 共用的版式,随 CLI 内嵌 |
| `validate.py` / `render.py` | 历史独立工具,保留作迁移对照;CLI 已使用 `src/domains/seal/reports/` 下的 TypeScript 校验和渲染模块,不再内嵌或调用这两个脚本 |
模板纪律见模板仓库 README:不引入 frontmatter/占位符标记(结构即契约)、正文不含 HTML 注释、表格只换数据行。
-352
View File
@@ -1,352 +0,0 @@
#!/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)
-252
View File
@@ -1,252 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""AI 审核报告结构校验器。
文档是纯 Markdown(无 frontmatter、无模板标记),校验器只看文档本身:
- 结构:标题层级、章节编号、表格列数、代码围栏、必填报告信息、图片可解析
- 纯净:不得出现任何模板机制痕迹(slot/@table/{{}}/render:stop/frontmatter)
- 数值:总览表求和与占比、小节标题张数、§6 明细与正文、公式算术——全部从正文推导
用法:
python3 tools/validate.py # 校验根目录全部 .md(README 除外)
python3 tools/validate.py 某文件.md
"""
from __future__ import annotations
import re
import sys
import argparse
import json
from pathlib import Path
from urllib.parse import unquote
SECTION_NUMBERS = ["1", "2", "3", "4", "5", "6", "7"]
REQUIRED_INFO_ROWS = {"报告编号", "客户名称", "统计期间", "报告状态", "生成日期"}
FORBIDDEN_MARKS = [
(r"<!--slot:", "slot 标记"),
(r"<!--/slot", "slot 闭合"),
(r"<!--@", "@table/@block 区域标记"),
(r"<!-- render:stop", "render:stop 标记"),
(r"\{\{", "{{槽位}}"),
]
class Report:
def __init__(self, path: Path):
self.path = path
self.issues: list[tuple[str, str, str]] = []
self.n_tables = 0
self.n_figs = 0
def err(self, code: str, msg: str) -> None:
self.issues.append(("ERROR", code, msg))
def warn(self, code: str, msg: str) -> None:
self.issues.append(("WARN", code, msg))
def ok(self) -> bool:
return not any(lv == "ERROR" for lv, _, _ in self.issues)
def cells(line: str) -> list[str]:
"""按未转义的 | 拆单元格;\\| 视为字面竖线。"""
s = line.strip()
if s.startswith("|"):
s = s[1:]
if s.endswith("|") and not s.endswith("\\|"):
s = s[:-1]
return [p.replace("\\|", "|").strip() for p in re.split(r"(?<!\\)\|", s)]
def is_sep(line: str) -> bool:
return line.strip() != "" and "-" in line and set(line.strip()) <= set("|-: ")
def iter_tables(lines: list[str]):
i = 0
while i < len(lines):
if lines[i].startswith("|") and i + 1 < len(lines) and is_sep(lines[i + 1]):
header = cells(lines[i])
body, j = [], i + 2
while j < len(lines) and lines[j].startswith("|"):
body.append((j + 1, cells(lines[j])))
j += 1
yield i + 1, header, body
i = j
else:
i += 1
def table_by_header(lines: list[str], keyword: str) -> dict | None:
"""按表头关键词找表,返回 {rows, start, end}(行号 1-based,含表头与分隔行)。"""
for lineno, header, rows in iter_tables(lines):
if keyword in "".join(header).replace(" ", ""):
end = rows[-1][0] if rows else lineno + 1
return {"rows": [r for _, r in rows], "start": lineno, "end": end}
return None
def pct(x: str) -> float | None:
m = re.search(r"(\d+(?:\.\d+)?)\s*%", x)
return float(m.group(1)) if m else None
def count(x: str) -> float | None:
m = re.search(r"(\d+(?:\.\d+)?)", x)
return float(m.group(1)) if m else None
def check(path: Path) -> Report:
r = Report(path)
text = path.read_text(encoding="utf-8")
lines = text.split("\n")
# 1. 纯净性:单层纯 Markdown
if text.startswith("---\n"):
r.err("FM001", "文件以 YAML frontmatter 开头;元数据请放正文「报告信息」表")
for pat, name in FORBIDDEN_MARKS:
if re.search(pat, text):
r.err("MK001", f"出现模板机制痕迹({name}),模板应是纯 Markdown 文档")
# 2. 代码围栏
fences = [i for i, ln in enumerate(lines, 1) if ln.startswith("```")]
if len(fences) % 2:
r.err("MD001", f"代码围栏为奇数({len(fences)}),存在未闭合代码块")
# 3. 表格列数与表头
for lineno, header, rows in iter_tables(lines):
r.n_tables += 1
n = len(header)
for rl, row in rows:
if len(row) != n:
r.err("TB001", f"第 {rl} 行表格列数 {len(row)} ≠ 表头 {n} 列")
if any("**" in c for c in header):
r.err("TB002", f"第 {lineno} 行表头含加粗标记 **")
# 4. 标题层级与章节编号
prev, seen = 0, []
for ln in lines:
m = re.match(r"^(#{1,6})\s+(.*)$", ln)
if not m:
continue
lvl = len(m.group(1))
if prev and lvl > prev + 1:
r.err("HD001", f"标题层级跳级({prev} → {lvl}):{m.group(2)[:40]}")
prev = lvl
m2 = re.match(r"^(\d+)\.", m.group(2))
if lvl == 2 and m2:
seen.append(m2.group(1))
if seen and seen != SECTION_NUMBERS:
r.err("HD002", f"## 章节编号应为 {SECTION_NUMBERS},实际 {seen}")
# 5. 报告信息表
info = table_by_header(lines, "报告信息")
if not info:
r.err("INFO001", "缺少「报告信息」表")
else:
keys = {row[0] for row in info["rows"] if row}
missing = REQUIRED_INFO_ROWS - keys
if missing:
r.err("INFO001", f"报告信息表缺少:{', '.join(sorted(missing))}")
empty = [row[0] for row in info["rows"] if row and len(row) > 1 and not row[1].strip()]
if empty:
r.err("INFO002", f"报告信息表以下项为空:{', '.join(empty)}")
# 6. 图片可解析:http(s) 或存在的本地文件
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
src = m.group(1).strip()
r.n_figs += 1
if src.startswith(("http://", "https://")):
continue
if src.startswith("data:"):
continue
if not (path.parent / unquote(src)).exists():
r.err("IMG001", f"图片不存在:{src}")
# 7. 数值自洽(全部从正文推导)
for tag, kw in (("NM001", "失准类型"), ("NM002", "风险类型")):
tb = table_by_header(lines, kw)
if not tb:
continue
rows = tb["rows"]
tops = [(c[0], count(c[3])) for c in rows if len(c) > 3 and c[0].startswith("TOP")]
totals = [count(c[3]) for c in rows if len(c) > 3 and c[0] in ("合计", "总计", "—")]
if tops and totals and all(c is not None for _, c in tops):
if sum(c for _, c in tops) != totals[0]:
r.err(tag, f"{kw}各维度之和 {sum(c for _, c in tops)} ≠ 合计 {totals[0]}")
base = totals[0] if totals else None
for c in rows:
if len(c) < 4:
continue
share, cnt = pct(c[2]), count(c[3])
if share and cnt and base and c[0].startswith("TOP") and abs(cnt / base * 100 - share) > 0.15:
r.err("NM003", f"{kw}「{c[1]}」占比 {share}% ≠ {cnt:.0f}/{base:.0f} = {cnt / base * 100:.1f}%")
# 小节标题里的张数与总览表一致
for no, cnt in tops:
sec = "2" if kw == "失准类型" else "3"
m = re.search(r"###\s*%s\.\d+\s*%s[^(]*((\d+)\s*张" % (sec, re.escape(no)), text)
if m and cnt is not None and int(m.group(1)) != cnt:
r.err(tag, f"{no} 小节标题写 {m.group(1)} 张,总览表写 {cnt:.0f} 张")
# NM004:§6 明细表的结论分类计数 = 正文数字
pr = table_by_header(lines, "原因分类")
if pr:
d4 = sum(1 for c in pr["rows"] if len(c) > 4 and "依规正确" in c[4])
miss = sum(1 for c in pr["rows"] if len(c) > 4 and "失准" in c[4])
m = re.search(r"((\d+)\s*/\s*(\d+)\s*笔)", text)
m2 = re.search(r"仅有\s*\*{0,2}(\d+)\s*笔", text)
if m and int(m.group(1)) != d4:
r.err("NM004", f"正文称依规正确 {m.group(1)} 笔,明细表实际 {d4} 行")
if m and int(m.group(2)) != len(pr["rows"]):
r.err("NM004", f"正文称合计 {m.group(2)} 笔,明细表实际 {len(pr['rows'])} 行")
if m2 and int(m2.group(1)) != miss:
r.err("NM004", f"正文称 AI 失准 {m2.group(1)} 笔,明细表实际 {miss} 行")
# NM005:公式算术自洽,且代入值能在正文别处找到
formula_lines = [l for l in lines if l.strip().startswith("$$")]
outside = "\n".join(l for l in lines if not l.strip().startswith("$$"))
for ln in formula_lines:
for frac in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", ln):
a, b, p = int(frac.group(1)), int(frac.group(2)), float(frac.group(3))
if b and abs(a / b * 100 - p) > 0.05:
r.err("NM005", f"公式 {a}/{b} = {p}% 算术不成立(实为 {a / b * 100:.2f}%)")
for tok in re.findall(r"\d+(?:\.\d+)?", ln):
if tok not in outside:
r.err("NM005", f"公式中的数值 {tok} 在正文别处找不到,可能与数据脱节")
return r
def default_paths() -> list[Path]:
"""默认校验根目录全部 .md(README.md 除外)。"""
return sorted(p for p in Path(".").glob("*.md") if p.name != "README.md")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("paths", nargs="*")
ap.add_argument("--json", action="store_true", help="输出机器可读的校验结果")
a = ap.parse_args()
paths = [Path(p) for p in a.paths] or default_paths()
failed = False
results = []
for p in paths:
rep = check(p)
if a.json:
results.append({
"file": str(p.resolve()), "valid": rep.ok(),
"tables": rep.n_tables, "figures": rep.n_figs,
"issues": [{"level": lv, "code": code, "message": msg} for lv, code, msg in rep.issues],
})
else:
print(f"[{'PASS' if rep.ok() else 'FAIL'}] {p} (表格 {rep.n_tables} 个, 图片 {rep.n_figs} 张)")
for lv, code, msg in rep.issues:
print(f" {lv} {code}: {msg}")
failed |= not rep.ok()
if a.json:
print(json.dumps(results, ensure_ascii=False))
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())