validate_cpld_teaching_html.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. GENERIC_NARRATION_MARKERS = [
  48. "本节的交付标准是读者能把",
  49. "常见误判要单独拎出来",
  50. "复盘本章时建议按下面的问题链自问",
  51. "本章的最小复述标准是",
  52. ]
  53. @dataclass
  54. class Finding:
  55. level: str
  56. file: str
  57. message: str
  58. def load_content(path: Path) -> dict[str, Any]:
  59. return json.loads(path.read_text(encoding="utf-8-sig"))
  60. def strip_tags(html: str) -> str:
  61. html = re.sub(r"<script[\s\S]*?</script>", " ", html, flags=re.I)
  62. html = re.sub(r"<style[\s\S]*?</style>", " ", html, flags=re.I)
  63. html = re.sub(r"<[^>]+>", " ", html)
  64. return html_module_unescape(re.sub(r"\s+", " ", html))
  65. def html_module_unescape(text: str) -> str:
  66. return html.unescape(text)
  67. def han_count(text: str) -> int:
  68. return sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
  69. def section_blocks(html: str) -> list[str]:
  70. return re.findall(r'<section class="section depth-section"[\s\S]*?</section>', html, flags=re.I)
  71. def repeated_paragraphs(plain: str) -> list[str]:
  72. sentences = [s.strip() for s in re.split(r"[。!?!?]", plain) if len(s.strip()) >= 28]
  73. counts = Counter(sentences)
  74. return [sentence for sentence, count in counts.items() if count >= 4]
  75. def validate_file(path: Path, chapter: dict[str, Any], glossary: dict[str, Any]) -> list[Finding]:
  76. findings: list[Finding] = []
  77. html = path.read_text(encoding="utf-8")
  78. plain = strip_tags(html)
  79. name = path.name
  80. if han_count(plain) < 9000:
  81. findings.append(Finding("error", name, f"content depth too shallow: {han_count(plain)} Han chars"))
  82. sections = section_blocks(html)
  83. expected_sections = len(chapter["sections"])
  84. if len(sections) != expected_sections:
  85. findings.append(Finding("error", name, f"expected {expected_sections} depth sections, got {len(sections)}"))
  86. for index, block in enumerate(sections, start=1):
  87. block_plain = strip_tags(block)
  88. if han_count(block_plain) < 900:
  89. findings.append(Finding("error", name, f"section {index} is too shallow: {han_count(block_plain)} Han chars"))
  90. if 'class="explanation-flow"' not in block:
  91. findings.append(Finding("error", name, f"section {index} missing natural explanation flow"))
  92. if 'class="evidence-panel"' not in block:
  93. findings.append(Finding("error", name, f"section {index} missing evidence panel"))
  94. if 'class="section-thread"' not in block:
  95. findings.append(Finding("error", name, f"section {index} missing progressive section thread"))
  96. for required_text in ["工程讲解", "证据与操作", "验证", "Runbook"]:
  97. if required_text not in block_plain:
  98. findings.append(Finding("error", name, f"section {index} missing required text {required_text}"))
  99. if "learning-ladder" not in html or "从浅到深的学习阶梯" not in plain:
  100. findings.append(Finding("error", name, "missing progressive learning ladder"))
  101. if "knowledge-system" not in html or "本章知识系统" not in plain:
  102. findings.append(Finding("error", name, "missing chapter knowledge system"))
  103. for marker in RIGID_STRUCTURE_MARKERS:
  104. if marker in html:
  105. findings.append(Finding("error", name, f"rigid causal grid marker found: {marker}"))
  106. for marker in MECHANICAL_JOIN_MARKERS:
  107. if marker in html:
  108. findings.append(Finding("error", name, f"mechanical join marker found: {marker}"))
  109. for marker in GENERIC_NARRATION_MARKERS:
  110. if marker in plain:
  111. findings.append(Finding("error", name, f"generic narration marker found: {marker}"))
  112. for phrase in OLD_TEMPLATE_PHRASES:
  113. if phrase in plain:
  114. findings.append(Finding("error", name, f"forbidden template phrase found: {phrase}"))
  115. for sentence in repeated_paragraphs(plain):
  116. if any(phrase in sentence for phrase in OLD_TEMPLATE_PHRASES):
  117. findings.append(Finding("error", name, f"forbidden template repetition: {sentence[:80]}"))
  118. section_plain = " ".join(strip_tags(block) for block in sections)
  119. for phrase in FORBIDDEN_BY_CHAPTER.get(chapter["id"], []):
  120. if phrase in section_plain:
  121. findings.append(Finding("error", name, f"chapter-specific forbidden phrase found: {phrase}"))
  122. if html.count("<svg") < expected_sections:
  123. findings.append(Finding("error", name, f"expected at least {expected_sections} SVG diagrams"))
  124. if html.count('class="term"') < 40:
  125. findings.append(Finding("error", name, "expected at least 40 clickable terms"))
  126. if "CPLD 术语总表" not in html:
  127. findings.append(Finding("error", name, "missing glossary"))
  128. if "series-nav" not in html or "tocPanel" not in html or "progress" not in html:
  129. findings.append(Finding("error", name, "missing navigation/progress chrome"))
  130. if re.search(r"https?://|file://", html, flags=re.I):
  131. findings.append(Finding("error", name, "HTML should not depend on external URLs"))
  132. for needle in REQUIRED_INTERACTIVE.get(chapter["id"], []):
  133. if needle not in html:
  134. findings.append(Finding("error", name, f"missing interactive component marker {needle}"))
  135. for section in chapter["sections"]:
  136. for anchor in section["anchors"]:
  137. if str(anchor) not in html and str(anchor) not in plain:
  138. findings.append(Finding("error", name, f"missing anchor: {anchor}"))
  139. for term in chapter.get("terms", []):
  140. if term not in glossary:
  141. findings.append(Finding("error", name, f"term not defined in glossary: {term}"))
  142. elif f'data-term="{term}"' not in html:
  143. findings.append(Finding("error", name, f"term not clickable in HTML: {term}"))
  144. return findings
  145. def validate(directory: Path, content: Path) -> dict[str, Any]:
  146. data = load_content(content)
  147. chapters = data["chapters"]
  148. glossary = data["glossary"]
  149. all_findings: list[Finding] = []
  150. files = []
  151. for chapter in chapters:
  152. path = directory / chapter["file"]
  153. files.append(path)
  154. if not path.exists():
  155. all_findings.append(Finding("error", chapter["file"], "missing expected HTML file"))
  156. continue
  157. all_findings.extend(validate_file(path, chapter, glossary))
  158. extra = sorted(p.name for p in directory.glob("cpld_ch*_learning_report_v1.html") if p not in files)
  159. for name in extra:
  160. all_findings.append(Finding("warning", name, "extra CPLD teaching HTML file"))
  161. errors = [f for f in all_findings if f.level == "error"]
  162. warnings = [f for f in all_findings if f.level == "warning"]
  163. required_anchor_errors = [f for f in errors if f.message.startswith("missing anchor")]
  164. forbidden_template_errors = [f for f in errors if "forbidden template" in f.message]
  165. interactive_errors = [f for f in errors if "interactive component" in f.message]
  166. rigid_structure_errors = [f for f in errors if "rigid causal grid marker" in f.message]
  167. mechanical_join_errors = [f for f in errors if "mechanical join marker" in f.message]
  168. learning_progression_errors = [f for f in errors if "progressive" in f.message or "learning ladder" in f.message]
  169. knowledge_system_errors = [f for f in errors if "knowledge system" in f.message]
  170. return {
  171. "summary": {
  172. "files": sum(1 for p in files if p.exists()),
  173. "expected_files": len(chapters),
  174. "errors": len(errors),
  175. "warnings": len(warnings),
  176. },
  177. "checks": {
  178. "required_anchors": {"passed": not required_anchor_errors, "errors": len(required_anchor_errors)},
  179. "forbidden_template": {"passed": not forbidden_template_errors, "errors": len(forbidden_template_errors)},
  180. "interactive_components": {"passed": not interactive_errors, "errors": len(interactive_errors)},
  181. "rigid_causal_grid": {"passed": not rigid_structure_errors, "errors": len(rigid_structure_errors)},
  182. "mechanical_join": {"passed": not mechanical_join_errors, "errors": len(mechanical_join_errors)},
  183. "learning_progression": {"passed": not learning_progression_errors, "errors": len(learning_progression_errors)},
  184. "knowledge_system": {"passed": not knowledge_system_errors, "errors": len(knowledge_system_errors)},
  185. },
  186. "findings": [f.__dict__ for f in all_findings],
  187. }
  188. def main() -> int:
  189. parser = argparse.ArgumentParser(description=__doc__)
  190. parser.add_argument("--dir", type=Path, required=True)
  191. parser.add_argument("--content", type=Path, default=DEFAULT_CONTENT)
  192. parser.add_argument("--json", action="store_true")
  193. parser.add_argument("--receipt", type=Path)
  194. args = parser.parse_args()
  195. payload = validate(args.dir, args.content)
  196. text = json.dumps(payload, ensure_ascii=False, indent=2)
  197. if args.receipt:
  198. args.receipt.parent.mkdir(parents=True, exist_ok=True)
  199. args.receipt.write_text(text + "\n", encoding="utf-8")
  200. if args.json:
  201. print(text)
  202. else:
  203. for finding in payload["findings"]:
  204. print(f"{finding['level'].upper()} {finding['file']}: {finding['message']}")
  205. print(
  206. f"files={payload['summary']['files']} errors={payload['summary']['errors']} warnings={payload['summary']['warnings']}"
  207. )
  208. if payload["summary"]["errors"]:
  209. print("validation failed", file=sys.stderr)
  210. return 1
  211. return 0
  212. if __name__ == "__main__":
  213. raise SystemExit(main())