376 lines
17 KiB
Python
Executable File
376 lines
17 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""
|
||
AI 审核报告(Markdown)独立校验器
|
||
Independent Markdown Validator for AI Audit Reports
|
||
|
||
特点:
|
||
- 零外部依赖:纯 Python 标准库(Python 3.8+),跨平台(macOS / Linux / Windows)
|
||
- 专为外部协同与客户交付设计:不依赖 seal-use、不强求本地 Excel 伴生台账
|
||
- 核心章节硬匹配大标题名称:中间任意插入的自定义章节完全自由放行
|
||
- 严格守护格式合规与数学总账守恒
|
||
|
||
用法:
|
||
python3 validate.py <report.md>
|
||
python3 validate.py <report.md> --json
|
||
"""
|
||
|
||
import os
|
||
import sys
|
||
import re
|
||
import json
|
||
from pathlib import Path
|
||
from typing import List, Dict, Any, Optional, Tuple
|
||
|
||
REQUIRED_INFO_ROWS = ["报告编号", "客户名称", "统计期间", "报告状态", "生成日期"]
|
||
FORBIDDEN_MARKS = [
|
||
(re.compile(r"<!--slot:"), "slot 标记"),
|
||
(re.compile(r"<!--/slot"), "slot 闭合"),
|
||
(re.compile(r"<!--@"), "@table/@block 区域标记"),
|
||
(re.compile(r"<!-- render:stop"), "render:stop 标记"),
|
||
(re.compile(r"\{\{"), "{{槽位}}"),
|
||
]
|
||
|
||
class ReportIssue:
|
||
def __init__(self, level: str, code: str, message: str, line: Optional[int] = None):
|
||
self.level = level # "ERROR" | "WARN"
|
||
self.code = code
|
||
self.message = message
|
||
self.line = line
|
||
|
||
def to_dict(self) -> Dict[str, Any]:
|
||
d: Dict[str, Any] = {"level": self.level, "code": self.code, "message": self.message}
|
||
if self.line is not None:
|
||
d["line"] = self.line
|
||
return d
|
||
|
||
|
||
class TableRow:
|
||
def __init__(self, line_num: int, cells: List[str]):
|
||
self.line_num = line_num
|
||
self.cells = cells
|
||
|
||
|
||
class ParsedTable:
|
||
def __init__(self, line_num: int, header: List[str], rows: List[TableRow]):
|
||
self.line_num = line_num
|
||
self.header = header
|
||
self.rows = rows
|
||
|
||
|
||
def split_cells(line: str) -> List[str]:
|
||
text = line.strip()
|
||
if text.startswith("|"):
|
||
text = text[1:]
|
||
if text.endswith("|") and not text.endswith(r"\|"):
|
||
text = text[:-1]
|
||
# Split on unescaped pipe
|
||
raw_cells = re.split(r"(?<!\\)\|", text)
|
||
return [c.replace(r"\|", "|").strip() for c in raw_cells]
|
||
|
||
|
||
def parse_tables(lines: List[str]) -> List[ParsedTable]:
|
||
result: List[ParsedTable] = []
|
||
i = 0
|
||
while i < len(lines):
|
||
line = lines[i].strip()
|
||
if i + 1 < len(lines):
|
||
separator = lines[i + 1].strip()
|
||
if line.startswith("|") and "-" in separator and re.match(r"^[|\-: ]+$", separator):
|
||
header = split_cells(line)
|
||
table = ParsedTable(line_num=i + 1, header=header, rows=[])
|
||
i += 2
|
||
while i < len(lines) and lines[i].strip().startswith("|"):
|
||
table.rows.append(TableRow(line_num=i + 1, cells=split_cells(lines[i])))
|
||
i += 1
|
||
result.append(table)
|
||
continue
|
||
i += 1
|
||
return result
|
||
|
||
|
||
def extract_numeric(text: str, is_percent: bool = False) -> Optional[float]:
|
||
pattern = r"(\d+(?:\.\d+)?)\s*%" if is_percent else r"(\d+(?:\.\d+)?)"
|
||
m = re.search(pattern, text)
|
||
if m:
|
||
try:
|
||
return float(m.group(1))
|
||
except ValueError:
|
||
return None
|
||
return None
|
||
|
||
|
||
def validate_report(filepath: str) -> Dict[str, Any]:
|
||
path = Path(filepath).resolve()
|
||
if not path.is_file():
|
||
return {
|
||
"file": str(path),
|
||
"valid": False,
|
||
"tables": 0,
|
||
"figures": 0,
|
||
"issues": [{"level": "ERROR", "code": "FS001", "message": f"文件不存在: {filepath}"}],
|
||
}
|
||
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
text = f.read().replace("\r\n", "\n").replace("\r", "\n")
|
||
|
||
lines = text.split("\n")
|
||
issues: List[ReportIssue] = []
|
||
|
||
def add_error(code: str, message: str, line: Optional[int] = None):
|
||
issues.append(ReportIssue(level="ERROR", code=code, message=message, line=line))
|
||
|
||
# 1. 纯净性:严禁 Frontmatter 和 模板草稿占位标记
|
||
if text.startswith("---\n"):
|
||
add_error("FM001", "文件以 YAML frontmatter 开头;元数据请放正文开头的「报告信息」表格中", line=1)
|
||
for pattern, name in FORBIDDEN_MARKS:
|
||
for idx, l in enumerate(lines, start=1):
|
||
if pattern.search(l):
|
||
add_error("MK001", f"出现模板未渲染痕迹({name}),交付文件应为纯 Markdown 文档", line=idx)
|
||
|
||
# 2. 代码围栏成对闭合
|
||
fences = [idx for idx, l in enumerate(lines, start=1) if l.strip().startswith("```")]
|
||
if len(fences) % 2 != 0:
|
||
add_error("MD001", f"代码围栏为奇数(共 {len(fences)} 个),存在未闭合代码块", line=fences[-1] if fences else None)
|
||
|
||
# 3. 表格结构规范(列对齐、表头无加粗)
|
||
parsed_tables = parse_tables(lines)
|
||
for table in parsed_tables:
|
||
header_len = len(table.header)
|
||
for row in table.rows:
|
||
if len(row.cells) != header_len:
|
||
add_error("TB001", f"第 {row.line_num} 行表格列数 {len(row.cells)} ≠ 表头 {header_len} 列", line=row.line_num)
|
||
for cell in table.header:
|
||
if "**" in cell:
|
||
add_error("TB002", f"第 {table.line_num} 行表头含有加粗标记 **(表头应保持纯文本)", line=table.line_num)
|
||
|
||
# 4. 标题层级与章节序号连续性
|
||
previous_level = 0
|
||
numbered_h2s: List[Tuple[int, str, int]] = [] # (chapter_num, full_heading, line_num)
|
||
chapters: List[Dict[str, Any]] = []
|
||
|
||
for idx, l in enumerate(lines, start=1):
|
||
m = re.match(r"^(#{1,6})\s+(.*)$", l)
|
||
if not m:
|
||
continue
|
||
level = len(m.group(1))
|
||
heading_text = m.group(2).strip()
|
||
if previous_level > 0 and level > previous_level + 1:
|
||
add_error("HD001", f"标题层级跳级(从 H{previous_level} 直接跳到 H{level}):{heading_text[:40]}", line=idx)
|
||
previous_level = level
|
||
|
||
if level == 2:
|
||
num_match = re.match(r"^(\d+)\.", heading_text)
|
||
if num_match:
|
||
numbered_h2s.append((int(num_match.group(1)), heading_text, idx))
|
||
chapters.append({"heading": heading_text, "start_line": idx, "line_num": idx})
|
||
|
||
# 检查大标题数字是否严格连续递增:1, 2, 3...
|
||
if numbered_h2s:
|
||
seen_nums = [item[0] for item in numbered_h2s]
|
||
expected_nums = list(range(1, len(seen_nums) + 1))
|
||
if seen_nums != expected_nums:
|
||
add_error("HD002", f"## 大章节编号应自 1 开始连续递增,期望 {expected_nums},实际 {seen_nums}", line=numbered_h2s[0][2])
|
||
|
||
# 为每个大章节划分文本切片(从当前 ## 到下一个 ##)
|
||
for i, chap in enumerate(chapters):
|
||
start_idx = chap["start_line"] - 1
|
||
end_idx = chapters[i + 1]["start_line"] - 1 if i + 1 < len(chapters) else len(lines)
|
||
chap["text"] = "\n".join(lines[start_idx:end_idx])
|
||
|
||
def find_chapter_by_keyword(kw: str) -> Optional[Dict[str, Any]]:
|
||
for c in chapters:
|
||
if kw in c["heading"]:
|
||
return c
|
||
return None
|
||
|
||
def by_header_in_scope(keyword: str, scope_lines: Optional[List[str]] = None) -> Optional[ParsedTable]:
|
||
target_tables = parse_tables(scope_lines) if scope_lines is not None else parsed_tables
|
||
for t in target_tables:
|
||
header_str = "".join(t.header).replace(" ", "")
|
||
if keyword in header_str:
|
||
return t
|
||
return None
|
||
|
||
# 5. 开篇「报告信息」表完备性
|
||
info_table = by_header_in_scope("报告信息")
|
||
if not info_table:
|
||
add_error("INFO001", "缺少开篇「报告信息」表(必须包含客户名称、期间、报告编号等元数据)")
|
||
else:
|
||
existing_keys = {r.cells[0] for r in info_table.rows if r.cells}
|
||
missing_keys = [k for k in REQUIRED_INFO_ROWS if k not in existing_keys]
|
||
if missing_keys:
|
||
add_error("INFO001", f"「报告信息」表缺少必要字段:{', '.join(missing_keys)}", line=info_table.line_num)
|
||
empty_keys = [r.cells[0] for r in info_table.rows if len(r.cells) > 1 and not r.cells[1].strip()]
|
||
if empty_keys:
|
||
add_error("INFO002", f"「报告信息」表以下字段值为空:{', '.join(empty_keys)}", line=info_table.line_num)
|
||
|
||
# 6. 本地图片资产存活性
|
||
figure_count = 0
|
||
for idx, l in enumerate(lines, start=1):
|
||
for img_match in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", l):
|
||
figure_count += 1
|
||
src = img_match.group(1).strip()
|
||
if src.startswith("http://") or src.startswith("https://") or src.startswith("data:"):
|
||
continue
|
||
# 解码 URL 编码的中文路径
|
||
try:
|
||
import urllib.parse
|
||
decoded_src = urllib.parse.unquote(src)
|
||
except Exception:
|
||
decoded_src = src
|
||
target_path = (path.parent / decoded_src).resolve()
|
||
if not target_path.exists():
|
||
add_error("IMG001", f"本地引用的图片文件不存在:{src}", line=idx)
|
||
|
||
# 7. 核心业务章节硬匹配校验与数学总账守恒
|
||
|
||
# 7.1 【AI 失准分析】核心章节
|
||
mismatch_chapter = find_chapter_by_keyword("失准")
|
||
if mismatch_chapter:
|
||
c_lines = mismatch_chapter["text"].split("\n")
|
||
table = by_header_in_scope("失准类型", c_lines)
|
||
if table:
|
||
tops = []
|
||
totals = []
|
||
for r in table.rows:
|
||
if len(r.cells) > 3:
|
||
if r.cells[0].startswith("TOP"):
|
||
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
|
||
elif r.cells[0] in ["合计", "总计", "—"]:
|
||
totals.append(extract_numeric(r.cells[3]))
|
||
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
|
||
s = sum(t["count"] for t in tops if t["count"] is not None)
|
||
if s != totals[0]:
|
||
add_error("NM001", f"失准类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
|
||
base = totals[0]
|
||
for r in table.rows:
|
||
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
|
||
share = extract_numeric(r.cells[2], is_percent=True)
|
||
count = extract_numeric(r.cells[3])
|
||
if share is not None and count is not None and base > 0:
|
||
calc_share = (count / base) * 100
|
||
if abs(calc_share - share) > 0.15:
|
||
add_error("NM003", f"失准类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
|
||
# 校验小节标题张数与总览表严格一致
|
||
for top in tops:
|
||
esc = re.escape(top["name"])
|
||
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", mismatch_chapter["text"])
|
||
if m and top["count"] is not None:
|
||
c_in_h = int(m.group(1))
|
||
if c_in_h != int(top["count"]):
|
||
add_error("NM001", f"失准分析 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
|
||
|
||
# 7.2 【AI 发现的潜在风险】核心章节
|
||
risk_chapter = find_chapter_by_keyword("风险")
|
||
if risk_chapter:
|
||
c_lines = risk_chapter["text"].split("\n")
|
||
table = by_header_in_scope("风险类型", c_lines)
|
||
if table:
|
||
tops = []
|
||
totals = []
|
||
for r in table.rows:
|
||
if len(r.cells) > 3:
|
||
if r.cells[0].startswith("TOP"):
|
||
tops.append({"name": r.cells[0], "count": extract_numeric(r.cells[3])})
|
||
elif r.cells[0] in ["合计", "总计", "—"]:
|
||
totals.append(extract_numeric(r.cells[3]))
|
||
if tops and totals and totals[0] is not None and all(t["count"] is not None for t in tops):
|
||
s = sum(t["count"] for t in tops if t["count"] is not None)
|
||
if s != totals[0]:
|
||
add_error("NM002", f"风险类型各维度单数之和 {s} ≠ 合计 {totals[0]}", line=table.line_num)
|
||
base = totals[0]
|
||
for r in table.rows:
|
||
if len(r.cells) >= 4 and r.cells[0].startswith("TOP"):
|
||
share = extract_numeric(r.cells[2], is_percent=True)
|
||
count = extract_numeric(r.cells[3])
|
||
if share is not None and count is not None and base > 0:
|
||
calc_share = (count / base) * 100
|
||
if abs(calc_share - share) > 0.15:
|
||
add_error("NM003", f"风险类型「{r.cells[1]}」占比 {share}% ≠ {int(count)}/{int(base)} = {calc_share:.1f}%", line=r.line_num)
|
||
for top in tops:
|
||
esc = re.escape(top["name"])
|
||
m = re.search(rf"###\s*\S*\s*{esc}[^(\n]*((\d+)\s*张", risk_chapter["text"])
|
||
if m and top["count"] is not None:
|
||
c_in_h = int(m.group(1))
|
||
if c_in_h != int(top["count"]):
|
||
add_error("NM002", f"潜在风险 {top['name']} 小节标题写 {c_in_h} 张,总览表写 {int(top['count'])} 张")
|
||
|
||
# 7.3 【审核分歧与复核归因】核心章节
|
||
diverged_chapter = find_chapter_by_keyword("分歧") or find_chapter_by_keyword("复核归因")
|
||
if diverged_chapter:
|
||
c_lines = diverged_chapter["text"].split("\n")
|
||
table = by_header_in_scope("原因分类", c_lines)
|
||
if table:
|
||
count_idx = -1
|
||
for ci, col in enumerate(table.header):
|
||
if "单数" in col:
|
||
count_idx = ci
|
||
break
|
||
if count_idx >= 0:
|
||
rows = [r.cells for r in table.rows]
|
||
non_totals = [r for r in rows if r and r[0] not in ["合计", "总计", "—"]]
|
||
total_row = next((r for r in rows if r and r[0] in ["合计", "总计", "—"]), None)
|
||
s = sum(extract_numeric(r[count_idx]) or 0 for r in non_totals if len(r) > count_idx)
|
||
if total_row and len(total_row) > count_idx:
|
||
tv = extract_numeric(total_row[count_idx])
|
||
if tv is not None and s != tv:
|
||
add_error("NM004", f"原因分类各维度单数之和 {s} ≠ 合计 {tv}", line=table.line_num)
|
||
|
||
# 7.4 LaTeX 公式算术自洽
|
||
formula_lines = [l for l in lines if l.strip().startswith("$$")]
|
||
outside_text = "\n".join([l for l in lines if not l.strip().startswith("$$")])
|
||
for fl in formula_lines:
|
||
for frac_match in re.finditer(r"\\frac\{(\d+)\}\{(\d+)\}\s*=\s*([\d.]+)\\%", fl):
|
||
a = int(frac_match.group(1))
|
||
b = int(frac_match.group(2))
|
||
pct_val = float(frac_match.group(3))
|
||
if b > 0:
|
||
real_pct = (a / b) * 100
|
||
if abs(real_pct - pct_val) > 0.05:
|
||
add_error("NM005", f"公式 \\frac{{{a}}}{{{b}}} = {pct_val}% 算术不成立(实为 {real_pct:.2f}%)")
|
||
for num_token in re.findall(r"\d+(?:\.\d+)?", fl):
|
||
if num_token not in outside_text:
|
||
add_error("NM005", f"公式中的数值 {num_token} 在正文别处找不到,可能与实际数据脱节")
|
||
|
||
return {
|
||
"file": str(path),
|
||
"valid": len(issues) == 0,
|
||
"tables": len(parsed_tables),
|
||
"figures": figure_count,
|
||
"issues": [i.to_dict() for i in issues],
|
||
}
|
||
|
||
|
||
def main():
|
||
if len(sys.argv) < 2 or sys.argv[1] in ["-h", "--help"]:
|
||
print("用法: python3 validate.py <report.md> [--json]")
|
||
print("说明: 离线静态校验 AI 审核报告 Markdown 文档的结构纯净度与数学总账守恒。")
|
||
sys.exit(0)
|
||
|
||
target_file = sys.argv[1]
|
||
is_json = "--json" in sys.argv
|
||
|
||
result = validate_report(target_file)
|
||
|
||
if is_json:
|
||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||
else:
|
||
status_symbol = "✅" if result["valid"] else "❌"
|
||
print(f"\n{status_symbol} 报告文件: {result['file']}")
|
||
print(f"📊 识别表格: {result['tables']} 个 | 配图资产: {result['figures']} 个")
|
||
|
||
if result["valid"]:
|
||
print("🎉 恭喜!报告结构完全合规,所有分类总览表、小节张数与数学公式严密闭环,无任何格式缺陷。\n")
|
||
sys.exit(0)
|
||
else:
|
||
print(f"⚠️ 发现 {len(result['issues'])} 项格式或勾稽问题,必须修正后方可交付:\n")
|
||
for i, issue in enumerate(result["issues"], 1):
|
||
loc = f" [第 {issue['line']} 行]" if "line" in issue else ""
|
||
print(f" {i}. [{issue['code']}]{loc} {issue['message']}")
|
||
print("\n💡 提示:请根据上述提示调整对应行的数字或表格结构,直至校验通过。\n")
|
||
sys.exit(1)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|