validate_cpld_teaching_html.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. @dataclass
  37. class Finding:
  38. level: str
  39. file: str
  40. message: str
  41. def load_content(path: Path) -> dict[str, Any]:
  42. return json.loads(path.read_text(encoding="utf-8-sig"))
  43. def strip_tags(html: str) -> str:
  44. html = re.sub(r"<script[\s\S]*?</script>", " ", html, flags=re.I)
  45. html = re.sub(r"<style[\s\S]*?</style>", " ", html, flags=re.I)
  46. html = re.sub(r"<[^>]+>", " ", html)
  47. return html_module_unescape(re.sub(r"\s+", " ", html))
  48. def html_module_unescape(text: str) -> str:
  49. return html.unescape(text)
  50. def han_count(text: str) -> int:
  51. return sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
  52. def section_blocks(html: str) -> list[str]:
  53. return re.findall(r'<section class="section depth-section"[\s\S]*?</section>', html, flags=re.I)
  54. def repeated_paragraphs(plain: str) -> list[str]:
  55. sentences = [s.strip() for s in re.split(r"[。!?!?]", plain) if len(s.strip()) >= 28]
  56. counts = Counter(sentences)
  57. return [sentence for sentence, count in counts.items() if count >= 4]
  58. def validate_file(path: Path, chapter: dict[str, Any], glossary: dict[str, Any]) -> list[Finding]:
  59. findings: list[Finding] = []
  60. html = path.read_text(encoding="utf-8")
  61. plain = strip_tags(html)
  62. name = path.name
  63. if han_count(plain) < 9000:
  64. findings.append(Finding("error", name, f"content depth too shallow: {han_count(plain)} Han chars"))
  65. sections = section_blocks(html)
  66. expected_sections = len(chapter["sections"])
  67. if len(sections) != expected_sections:
  68. findings.append(Finding("error", name, f"expected {expected_sections} depth sections, got {len(sections)}"))
  69. for index, block in enumerate(sections, start=1):
  70. block_plain = strip_tags(block)
  71. if han_count(block_plain) < 900:
  72. findings.append(Finding("error", name, f"section {index} is too shallow: {han_count(block_plain)} Han chars"))
  73. for heading in ["现象", "前因", "机制", "后果", "验证", "Runbook"]:
  74. if heading not in block_plain:
  75. findings.append(Finding("error", name, f"section {index} missing segment {heading}"))
  76. for phrase in OLD_TEMPLATE_PHRASES:
  77. if phrase in plain:
  78. findings.append(Finding("error", name, f"forbidden template phrase found: {phrase}"))
  79. for sentence in repeated_paragraphs(plain):
  80. if any(phrase in sentence for phrase in OLD_TEMPLATE_PHRASES):
  81. findings.append(Finding("error", name, f"forbidden template repetition: {sentence[:80]}"))
  82. section_plain = " ".join(strip_tags(block) for block in sections)
  83. for phrase in FORBIDDEN_BY_CHAPTER.get(chapter["id"], []):
  84. if phrase in section_plain:
  85. findings.append(Finding("error", name, f"chapter-specific forbidden phrase found: {phrase}"))
  86. if html.count("<svg") < expected_sections:
  87. findings.append(Finding("error", name, f"expected at least {expected_sections} SVG diagrams"))
  88. if html.count('class="term"') < 40:
  89. findings.append(Finding("error", name, "expected at least 40 clickable terms"))
  90. if "CPLD 术语总表" not in html:
  91. findings.append(Finding("error", name, "missing glossary"))
  92. if "series-nav" not in html or "tocPanel" not in html or "progress" not in html:
  93. findings.append(Finding("error", name, "missing navigation/progress chrome"))
  94. if re.search(r"https?://|file://", html, flags=re.I):
  95. findings.append(Finding("error", name, "HTML should not depend on external URLs"))
  96. for needle in REQUIRED_INTERACTIVE.get(chapter["id"], []):
  97. if needle not in html:
  98. findings.append(Finding("error", name, f"missing interactive component marker {needle}"))
  99. for section in chapter["sections"]:
  100. for anchor in section["anchors"]:
  101. if str(anchor) not in html and str(anchor) not in plain:
  102. findings.append(Finding("error", name, f"missing anchor: {anchor}"))
  103. for term in chapter.get("terms", []):
  104. if term not in glossary:
  105. findings.append(Finding("error", name, f"term not defined in glossary: {term}"))
  106. elif f'data-term="{term}"' not in html:
  107. findings.append(Finding("error", name, f"term not clickable in HTML: {term}"))
  108. return findings
  109. def validate(directory: Path, content: Path) -> dict[str, Any]:
  110. data = load_content(content)
  111. chapters = data["chapters"]
  112. glossary = data["glossary"]
  113. all_findings: list[Finding] = []
  114. files = []
  115. for chapter in chapters:
  116. path = directory / chapter["file"]
  117. files.append(path)
  118. if not path.exists():
  119. all_findings.append(Finding("error", chapter["file"], "missing expected HTML file"))
  120. continue
  121. all_findings.extend(validate_file(path, chapter, glossary))
  122. extra = sorted(p.name for p in directory.glob("cpld_ch*_learning_report_v1.html") if p not in files)
  123. for name in extra:
  124. all_findings.append(Finding("warning", name, "extra CPLD teaching HTML file"))
  125. errors = [f for f in all_findings if f.level == "error"]
  126. warnings = [f for f in all_findings if f.level == "warning"]
  127. required_anchor_errors = [f for f in errors if f.message.startswith("missing anchor")]
  128. forbidden_template_errors = [f for f in errors if "forbidden template" in f.message]
  129. interactive_errors = [f for f in errors if "interactive component" in f.message]
  130. return {
  131. "summary": {
  132. "files": sum(1 for p in files if p.exists()),
  133. "expected_files": len(chapters),
  134. "errors": len(errors),
  135. "warnings": len(warnings),
  136. },
  137. "checks": {
  138. "required_anchors": {"passed": not required_anchor_errors, "errors": len(required_anchor_errors)},
  139. "forbidden_template": {"passed": not forbidden_template_errors, "errors": len(forbidden_template_errors)},
  140. "interactive_components": {"passed": not interactive_errors, "errors": len(interactive_errors)},
  141. },
  142. "findings": [f.__dict__ for f in all_findings],
  143. }
  144. def main() -> int:
  145. parser = argparse.ArgumentParser(description=__doc__)
  146. parser.add_argument("--dir", type=Path, required=True)
  147. parser.add_argument("--content", type=Path, default=DEFAULT_CONTENT)
  148. parser.add_argument("--json", action="store_true")
  149. parser.add_argument("--receipt", type=Path)
  150. args = parser.parse_args()
  151. payload = validate(args.dir, args.content)
  152. text = json.dumps(payload, ensure_ascii=False, indent=2)
  153. if args.receipt:
  154. args.receipt.parent.mkdir(parents=True, exist_ok=True)
  155. args.receipt.write_text(text + "\n", encoding="utf-8")
  156. if args.json:
  157. print(text)
  158. else:
  159. for finding in payload["findings"]:
  160. print(f"{finding['level'].upper()} {finding['file']}: {finding['message']}")
  161. print(
  162. f"files={payload['summary']['files']} errors={payload['summary']['errors']} warnings={payload['summary']['warnings']}"
  163. )
  164. if payload["summary"]["errors"]:
  165. print("validation failed", file=sys.stderr)
  166. return 1
  167. return 0
  168. if __name__ == "__main__":
  169. raise SystemExit(main())