validate_cpld_teaching_html.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. #!/usr/bin/env python3
  2. """Validate generated CPLD teaching HTML reports."""
  3. from __future__ import annotations
  4. import argparse
  5. import html
  6. import json
  7. import re
  8. import sys
  9. from collections import Counter
  10. from dataclasses import dataclass
  11. from pathlib import Path
  12. from typing import Any
  13. ROOT = Path(__file__).resolve().parents[1]
  14. DEFAULT_CONTENT = ROOT / "workspace" / "teaching_content" / "chapters" / "cpld_teaching_content.json"
  15. OLD_TEMPLATE_PHRASES = [
  16. "建议读者先完成前序章节,再在本节动手",
  17. "打开 TD 工程对照 Top Module",
  18. "排障时保留 Waveform 截图、 Programmer 日志与 Git 版本号",
  19. "若出现 Timing 违例或 CDC 告警,不要强行下板",
  20. ]
  21. FORBIDDEN_BY_CHAPTER = {
  22. 4: ["PID 控制器", "三 DSP", "A0*e"],
  23. 5: ["UART 调试接口", "24 路 PID"],
  24. 6: ["PID24", "PWM", "ADC"],
  25. 11: ["EEPROM 写周期忙状态会直接导致 PID 饱和"],
  26. }
  27. REQUIRED_INTERACTIVE = {
  28. 4: ["id=\"i2cFrameBtn\""],
  29. 5: ["id=\"sclCalcBtn\""],
  30. 6: ["id=\"transactionStepper\""],
  31. 7: ["id=\"transactionStepper\""],
  32. 9: ["id=\"tool-pin\""],
  33. 11: ["id=\"pidScheduler\""],
  34. 13: ["id=\"debugTree\""],
  35. }
  36. RIGID_STRUCTURE_MARKERS = [
  37. 'class="causal-grid"',
  38. "前因 Why",
  39. "机制 How",
  40. "后果 So what",
  41. ]
  42. MECHANICAL_JOIN_MARKERS = [
  43. "。;",
  44. ";;",
  45. "。。这个问题链",
  46. ]
  47. @dataclass
  48. class Finding:
  49. level: str
  50. file: str
  51. message: str
  52. def load_content(path: Path) -> dict[str, Any]:
  53. return json.loads(path.read_text(encoding="utf-8-sig"))
  54. def strip_tags(html: str) -> str:
  55. html = re.sub(r"<script[\s\S]*?</script>", " ", html, flags=re.I)
  56. html = re.sub(r"<style[\s\S]*?</style>", " ", html, flags=re.I)
  57. html = re.sub(r"<[^>]+>", " ", html)
  58. return html_module_unescape(re.sub(r"\s+", " ", html))
  59. def html_module_unescape(text: str) -> str:
  60. return html.unescape(text)
  61. def han_count(text: str) -> int:
  62. return sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
  63. def section_blocks(html: str) -> list[str]:
  64. return re.findall(r'<section class="section depth-section"[\s\S]*?</section>', html, flags=re.I)
  65. def repeated_paragraphs(plain: str) -> list[str]:
  66. sentences = [s.strip() for s in re.split(r"[。!?!?]", plain) if len(s.strip()) >= 28]
  67. counts = Counter(sentences)
  68. return [sentence for sentence, count in counts.items() if count >= 4]
  69. def validate_file(path: Path, chapter: dict[str, Any], glossary: dict[str, Any]) -> list[Finding]:
  70. findings: list[Finding] = []
  71. html = path.read_text(encoding="utf-8")
  72. plain = strip_tags(html)
  73. name = path.name
  74. if han_count(plain) < 9000:
  75. findings.append(Finding("error", name, f"content depth too shallow: {han_count(plain)} Han chars"))
  76. sections = section_blocks(html)
  77. expected_sections = len(chapter["sections"])
  78. if len(sections) != expected_sections:
  79. findings.append(Finding("error", name, f"expected {expected_sections} depth sections, got {len(sections)}"))
  80. for index, block in enumerate(sections, start=1):
  81. block_plain = strip_tags(block)
  82. if han_count(block_plain) < 900:
  83. findings.append(Finding("error", name, f"section {index} is too shallow: {han_count(block_plain)} Han chars"))
  84. if 'class="explanation-flow"' not in block:
  85. findings.append(Finding("error", name, f"section {index} missing natural explanation flow"))
  86. if 'class="evidence-panel"' not in block:
  87. findings.append(Finding("error", name, f"section {index} missing evidence panel"))
  88. for required_text in ["工程讲解", "证据与操作", "验证", "Runbook"]:
  89. if required_text not in block_plain:
  90. findings.append(Finding("error", name, f"section {index} missing required text {required_text}"))
  91. for marker in RIGID_STRUCTURE_MARKERS:
  92. if marker in html:
  93. findings.append(Finding("error", name, f"rigid causal grid marker found: {marker}"))
  94. for marker in MECHANICAL_JOIN_MARKERS:
  95. if marker in html:
  96. findings.append(Finding("error", name, f"mechanical join marker found: {marker}"))
  97. for phrase in OLD_TEMPLATE_PHRASES:
  98. if phrase in plain:
  99. findings.append(Finding("error", name, f"forbidden template phrase found: {phrase}"))
  100. for sentence in repeated_paragraphs(plain):
  101. if any(phrase in sentence for phrase in OLD_TEMPLATE_PHRASES):
  102. findings.append(Finding("error", name, f"forbidden template repetition: {sentence[:80]}"))
  103. section_plain = " ".join(strip_tags(block) for block in sections)
  104. for phrase in FORBIDDEN_BY_CHAPTER.get(chapter["id"], []):
  105. if phrase in section_plain:
  106. findings.append(Finding("error", name, f"chapter-specific forbidden phrase found: {phrase}"))
  107. if html.count("<svg") < expected_sections:
  108. findings.append(Finding("error", name, f"expected at least {expected_sections} SVG diagrams"))
  109. if html.count('class="term"') < 40:
  110. findings.append(Finding("error", name, "expected at least 40 clickable terms"))
  111. if "CPLD 术语总表" not in html:
  112. findings.append(Finding("error", name, "missing glossary"))
  113. if "series-nav" not in html or "tocPanel" not in html or "progress" not in html:
  114. findings.append(Finding("error", name, "missing navigation/progress chrome"))
  115. if re.search(r"https?://|file://", html, flags=re.I):
  116. findings.append(Finding("error", name, "HTML should not depend on external URLs"))
  117. for needle in REQUIRED_INTERACTIVE.get(chapter["id"], []):
  118. if needle not in html:
  119. findings.append(Finding("error", name, f"missing interactive component marker {needle}"))
  120. for section in chapter["sections"]:
  121. for anchor in section["anchors"]:
  122. if str(anchor) not in html and str(anchor) not in plain:
  123. findings.append(Finding("error", name, f"missing anchor: {anchor}"))
  124. for term in chapter.get("terms", []):
  125. if term not in glossary:
  126. findings.append(Finding("error", name, f"term not defined in glossary: {term}"))
  127. elif f'data-term="{term}"' not in html:
  128. findings.append(Finding("error", name, f"term not clickable in HTML: {term}"))
  129. return findings
  130. def validate(directory: Path, content: Path) -> dict[str, Any]:
  131. data = load_content(content)
  132. chapters = data["chapters"]
  133. glossary = data["glossary"]
  134. all_findings: list[Finding] = []
  135. files = []
  136. for chapter in chapters:
  137. path = directory / chapter["file"]
  138. files.append(path)
  139. if not path.exists():
  140. all_findings.append(Finding("error", chapter["file"], "missing expected HTML file"))
  141. continue
  142. all_findings.extend(validate_file(path, chapter, glossary))
  143. extra = sorted(p.name for p in directory.glob("cpld_ch*_learning_report_v1.html") if p not in files)
  144. for name in extra:
  145. all_findings.append(Finding("warning", name, "extra CPLD teaching HTML file"))
  146. errors = [f for f in all_findings if f.level == "error"]
  147. warnings = [f for f in all_findings if f.level == "warning"]
  148. required_anchor_errors = [f for f in errors if f.message.startswith("missing anchor")]
  149. forbidden_template_errors = [f for f in errors if "forbidden template" in f.message]
  150. interactive_errors = [f for f in errors if "interactive component" in f.message]
  151. rigid_structure_errors = [f for f in errors if "rigid causal grid marker" in f.message]
  152. mechanical_join_errors = [f for f in errors if "mechanical join marker" in f.message]
  153. return {
  154. "summary": {
  155. "files": sum(1 for p in files if p.exists()),
  156. "expected_files": len(chapters),
  157. "errors": len(errors),
  158. "warnings": len(warnings),
  159. },
  160. "checks": {
  161. "required_anchors": {"passed": not required_anchor_errors, "errors": len(required_anchor_errors)},
  162. "forbidden_template": {"passed": not forbidden_template_errors, "errors": len(forbidden_template_errors)},
  163. "interactive_components": {"passed": not interactive_errors, "errors": len(interactive_errors)},
  164. "rigid_causal_grid": {"passed": not rigid_structure_errors, "errors": len(rigid_structure_errors)},
  165. "mechanical_join": {"passed": not mechanical_join_errors, "errors": len(mechanical_join_errors)},
  166. },
  167. "findings": [f.__dict__ for f in all_findings],
  168. }
  169. def main() -> int:
  170. parser = argparse.ArgumentParser(description=__doc__)
  171. parser.add_argument("--dir", type=Path, required=True)
  172. parser.add_argument("--content", type=Path, default=DEFAULT_CONTENT)
  173. parser.add_argument("--json", action="store_true")
  174. parser.add_argument("--receipt", type=Path)
  175. args = parser.parse_args()
  176. payload = validate(args.dir, args.content)
  177. text = json.dumps(payload, ensure_ascii=False, indent=2)
  178. if args.receipt:
  179. args.receipt.parent.mkdir(parents=True, exist_ok=True)
  180. args.receipt.write_text(text + "\n", encoding="utf-8")
  181. if args.json:
  182. print(text)
  183. else:
  184. for finding in payload["findings"]:
  185. print(f"{finding['level'].upper()} {finding['file']}: {finding['message']}")
  186. print(
  187. f"files={payload['summary']['files']} errors={payload['summary']['errors']} warnings={payload['summary']['warnings']}"
  188. )
  189. if payload["summary"]["errors"]:
  190. print("validation failed", file=sys.stderr)
  191. return 1
  192. return 0
  193. if __name__ == "__main__":
  194. raise SystemExit(main())