| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242 |
- #!/usr/bin/env python3
- """Validate generated CPLD teaching HTML reports."""
- from __future__ import annotations
- import argparse
- import html
- import json
- import re
- import sys
- from collections import Counter
- from dataclasses import dataclass
- from pathlib import Path
- from typing import Any
- ROOT = Path(__file__).resolve().parents[1]
- DEFAULT_CONTENT = ROOT / "workspace" / "teaching_content" / "chapters" / "cpld_teaching_content.json"
- OLD_TEMPLATE_PHRASES = [
- "建议读者先完成前序章节,再在本节动手",
- "打开 TD 工程对照 Top Module",
- "排障时保留 Waveform 截图、 Programmer 日志与 Git 版本号",
- "若出现 Timing 违例或 CDC 告警,不要强行下板",
- ]
- FORBIDDEN_BY_CHAPTER = {
- 4: ["PID 控制器", "三 DSP", "A0*e"],
- 5: ["UART 调试接口", "24 路 PID"],
- 6: ["PID24", "PWM", "ADC"],
- 11: ["EEPROM 写周期忙状态会直接导致 PID 饱和"],
- }
- REQUIRED_INTERACTIVE = {
- 4: ["id=\"i2cFrameBtn\""],
- 5: ["id=\"sclCalcBtn\""],
- 6: ["id=\"transactionStepper\""],
- 7: ["id=\"transactionStepper\""],
- 9: ["id=\"tool-pin\""],
- 11: ["id=\"pidScheduler\""],
- 13: ["id=\"debugTree\""],
- }
- RIGID_STRUCTURE_MARKERS = [
- 'class="causal-grid"',
- "前因 Why",
- "机制 How",
- "后果 So what",
- ]
- MECHANICAL_JOIN_MARKERS = [
- "。;",
- ";;",
- "。。这个问题链",
- ]
- @dataclass
- class Finding:
- level: str
- file: str
- message: str
- def load_content(path: Path) -> dict[str, Any]:
- return json.loads(path.read_text(encoding="utf-8-sig"))
- def strip_tags(html: str) -> str:
- html = re.sub(r"<script[\s\S]*?</script>", " ", html, flags=re.I)
- html = re.sub(r"<style[\s\S]*?</style>", " ", html, flags=re.I)
- html = re.sub(r"<[^>]+>", " ", html)
- return html_module_unescape(re.sub(r"\s+", " ", html))
- def html_module_unescape(text: str) -> str:
- return html.unescape(text)
- def han_count(text: str) -> int:
- return sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
- def section_blocks(html: str) -> list[str]:
- return re.findall(r'<section class="section depth-section"[\s\S]*?</section>', html, flags=re.I)
- def repeated_paragraphs(plain: str) -> list[str]:
- sentences = [s.strip() for s in re.split(r"[。!?!?]", plain) if len(s.strip()) >= 28]
- counts = Counter(sentences)
- return [sentence for sentence, count in counts.items() if count >= 4]
- def validate_file(path: Path, chapter: dict[str, Any], glossary: dict[str, Any]) -> list[Finding]:
- findings: list[Finding] = []
- html = path.read_text(encoding="utf-8")
- plain = strip_tags(html)
- name = path.name
- if han_count(plain) < 9000:
- findings.append(Finding("error", name, f"content depth too shallow: {han_count(plain)} Han chars"))
- sections = section_blocks(html)
- expected_sections = len(chapter["sections"])
- if len(sections) != expected_sections:
- findings.append(Finding("error", name, f"expected {expected_sections} depth sections, got {len(sections)}"))
- for index, block in enumerate(sections, start=1):
- block_plain = strip_tags(block)
- if han_count(block_plain) < 900:
- findings.append(Finding("error", name, f"section {index} is too shallow: {han_count(block_plain)} Han chars"))
- if 'class="explanation-flow"' not in block:
- findings.append(Finding("error", name, f"section {index} missing natural explanation flow"))
- if 'class="evidence-panel"' not in block:
- findings.append(Finding("error", name, f"section {index} missing evidence panel"))
- for required_text in ["工程讲解", "证据与操作", "验证", "Runbook"]:
- if required_text not in block_plain:
- findings.append(Finding("error", name, f"section {index} missing required text {required_text}"))
- for marker in RIGID_STRUCTURE_MARKERS:
- if marker in html:
- findings.append(Finding("error", name, f"rigid causal grid marker found: {marker}"))
- for marker in MECHANICAL_JOIN_MARKERS:
- if marker in html:
- findings.append(Finding("error", name, f"mechanical join marker found: {marker}"))
- for phrase in OLD_TEMPLATE_PHRASES:
- if phrase in plain:
- findings.append(Finding("error", name, f"forbidden template phrase found: {phrase}"))
- for sentence in repeated_paragraphs(plain):
- if any(phrase in sentence for phrase in OLD_TEMPLATE_PHRASES):
- findings.append(Finding("error", name, f"forbidden template repetition: {sentence[:80]}"))
- section_plain = " ".join(strip_tags(block) for block in sections)
- for phrase in FORBIDDEN_BY_CHAPTER.get(chapter["id"], []):
- if phrase in section_plain:
- findings.append(Finding("error", name, f"chapter-specific forbidden phrase found: {phrase}"))
- if html.count("<svg") < expected_sections:
- findings.append(Finding("error", name, f"expected at least {expected_sections} SVG diagrams"))
- if html.count('class="term"') < 40:
- findings.append(Finding("error", name, "expected at least 40 clickable terms"))
- if "CPLD 术语总表" not in html:
- findings.append(Finding("error", name, "missing glossary"))
- if "series-nav" not in html or "tocPanel" not in html or "progress" not in html:
- findings.append(Finding("error", name, "missing navigation/progress chrome"))
- if re.search(r"https?://|file://", html, flags=re.I):
- findings.append(Finding("error", name, "HTML should not depend on external URLs"))
- for needle in REQUIRED_INTERACTIVE.get(chapter["id"], []):
- if needle not in html:
- findings.append(Finding("error", name, f"missing interactive component marker {needle}"))
- for section in chapter["sections"]:
- for anchor in section["anchors"]:
- if str(anchor) not in html and str(anchor) not in plain:
- findings.append(Finding("error", name, f"missing anchor: {anchor}"))
- for term in chapter.get("terms", []):
- if term not in glossary:
- findings.append(Finding("error", name, f"term not defined in glossary: {term}"))
- elif f'data-term="{term}"' not in html:
- findings.append(Finding("error", name, f"term not clickable in HTML: {term}"))
- return findings
- def validate(directory: Path, content: Path) -> dict[str, Any]:
- data = load_content(content)
- chapters = data["chapters"]
- glossary = data["glossary"]
- all_findings: list[Finding] = []
- files = []
- for chapter in chapters:
- path = directory / chapter["file"]
- files.append(path)
- if not path.exists():
- all_findings.append(Finding("error", chapter["file"], "missing expected HTML file"))
- continue
- all_findings.extend(validate_file(path, chapter, glossary))
- extra = sorted(p.name for p in directory.glob("cpld_ch*_learning_report_v1.html") if p not in files)
- for name in extra:
- all_findings.append(Finding("warning", name, "extra CPLD teaching HTML file"))
- errors = [f for f in all_findings if f.level == "error"]
- warnings = [f for f in all_findings if f.level == "warning"]
- required_anchor_errors = [f for f in errors if f.message.startswith("missing anchor")]
- forbidden_template_errors = [f for f in errors if "forbidden template" in f.message]
- interactive_errors = [f for f in errors if "interactive component" in f.message]
- rigid_structure_errors = [f for f in errors if "rigid causal grid marker" in f.message]
- mechanical_join_errors = [f for f in errors if "mechanical join marker" in f.message]
- return {
- "summary": {
- "files": sum(1 for p in files if p.exists()),
- "expected_files": len(chapters),
- "errors": len(errors),
- "warnings": len(warnings),
- },
- "checks": {
- "required_anchors": {"passed": not required_anchor_errors, "errors": len(required_anchor_errors)},
- "forbidden_template": {"passed": not forbidden_template_errors, "errors": len(forbidden_template_errors)},
- "interactive_components": {"passed": not interactive_errors, "errors": len(interactive_errors)},
- "rigid_causal_grid": {"passed": not rigid_structure_errors, "errors": len(rigid_structure_errors)},
- "mechanical_join": {"passed": not mechanical_join_errors, "errors": len(mechanical_join_errors)},
- },
- "findings": [f.__dict__ for f in all_findings],
- }
- def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--dir", type=Path, required=True)
- parser.add_argument("--content", type=Path, default=DEFAULT_CONTENT)
- parser.add_argument("--json", action="store_true")
- parser.add_argument("--receipt", type=Path)
- args = parser.parse_args()
- payload = validate(args.dir, args.content)
- text = json.dumps(payload, ensure_ascii=False, indent=2)
- if args.receipt:
- args.receipt.parent.mkdir(parents=True, exist_ok=True)
- args.receipt.write_text(text + "\n", encoding="utf-8")
- if args.json:
- print(text)
- else:
- for finding in payload["findings"]:
- print(f"{finding['level'].upper()} {finding['file']}: {finding['message']}")
- print(
- f"files={payload['summary']['files']} errors={payload['summary']['errors']} warnings={payload['summary']['warnings']}"
- )
- if payload["summary"]["errors"]:
- print("validation failed", file=sys.stderr)
- return 1
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|