#!/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 = [ "。;", ";;", "。。这个问题链", ] GENERIC_NARRATION_MARKERS = [ "本节的交付标准是读者能把", "常见误判要单独拎出来", "复盘本章时建议按下面的问题链自问", "本章的最小复述标准是", "讨论「", "读者真正会遇到的不是抽象名词", "这个现象要落到证据上看", "顺着这个点往下学", "放进系统里看", "扩展学习时不要把", "讲解时可以采用一个很小的实验", "不要从术语背诵开始", "自然串讲:从现象走到验证", "工程化深挖", "问题链自问", "最小复述标准", ] VISIBLE_HTML_FRAGMENT_PATTERNS = [ re.compile(r'\b[a-z][a-z0-9_-]{1,40}">[A-Za-z0-9\u4e00-\u9fff]', re.I), re.compile(r'\b(?:button|article|section|header|aside|div|span|a)\s+class="[^"]+"', re.I), re.compile(r'\bdata-term="[^"]+"', re.I), ] RAW_HTML_CORRUPTION_PATTERNS = [ re.compile(r']*>(?:(?!).)*<(?:a|button)\b', re.I | re.S), ] BALANCED_TAGS = ["button"] @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"", " ", html, flags=re.I) html = re.sub(r"", " ", 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'
', 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 clipped(text: str, start: int, size: int = 80) -> str: return text[max(0, start - 24) : start + size].replace("\n", " ") def tag_counts(markup: str, tag: str) -> tuple[int, int]: opens = len(re.findall(fr"<{tag}\b", markup, flags=re.I)) closes = len(re.findall(fr"", markup, flags=re.I)) return opens, closes def validate_integrated_section(block: str, block_plain: str, index: int, name: str) -> list[Finding]: findings: list[Finding] = [] if han_count(block_plain) < 800: findings.append(Finding("error", name, f"section {index} is too shallow: {han_count(block_plain)} Han chars")) for marker in [ 'class="integrated-section"', 'class="scene-lead"', 'class="visual-explain-grid"', 'class="integrated-mechanism"', 'class="visual-figure-block"', 'class="integrated-proof-table"', 'class="verify-table"', ]: if marker not in block: findings.append(Finding("error", name, f"section {index} missing integrated marker {marker}")) for forbidden in ['class="term-strip"', 'class="section-story"', 'class="evidence-panel"', 'class="explanation-flow"']: if forbidden in block: findings.append(Finding("error", name, f"section {index} still uses legacy marker {forbidden}")) for forbidden_text in ["工程讲解", "证据与操作", "完整讲解"]: if forbidden_text in block_plain: findings.append(Finding("error", name, f"section {index} still exposes legacy heading {forbidden_text}")) for required_text in ["先看现场", "结构图", "工程锚点表", "机制拆解", "验证与排障"]: if required_text not in block_plain: findings.append(Finding("error", name, f"section {index} missing integrated text {required_text}")) if " list[Finding]: findings: list[Finding] = [] 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")) if 'class="section-story"' not in block: findings.append(Finding("error", name, f"section {index} missing section-specific story")) if 'class="progressive-note"' not in block: findings.append(Finding("error", name, f"section {index} missing progressive note")) if 'class="section-thread"' in block: findings.append(Finding("error", name, f"section {index} still uses generic section thread")) 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}")) return findings 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 '' not in html: findings.append(Finding("error", name, "html fragment leak: missing exact utf-8 meta tag")) if '' not in html: findings.append(Finding("error", name, "html fragment leak: missing exact viewport meta tag")) for pattern in RAW_HTML_CORRUPTION_PATTERNS: match = pattern.search(html) if match: findings.append(Finding("error", name, f"html fragment leak in markup: {clipped(html, match.start())}")) for tag in BALANCED_TAGS: opens, closes = tag_counts(html, tag) if opens != closes: findings.append(Finding("error", name, f"html fragment leak: unbalanced <{tag}> tags ({opens} open, {closes} close)")) for pattern in VISIBLE_HTML_FRAGMENT_PATTERNS: match = pattern.search(plain) if match: findings.append(Finding("error", name, f"html fragment leak in visible text: {clipped(plain, match.start())}")) min_han = 8200 if chapter["id"] in {1, 2} else 9000 if han_count(plain) < min_han: 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 chapter["id"] in {1, 2}: findings.extend(validate_integrated_section(block, block_plain, index, name)) else: findings.extend(validate_legacy_section(block, block_plain, index, name)) if "learning-ladder" not in html or "从浅到深的学习阶梯" not in plain: findings.append(Finding("error", name, "missing progressive learning ladder")) if "knowledge-system" not in html or "本章知识系统" not in plain: findings.append(Finding("error", name, "missing chapter knowledge system")) 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 marker in GENERIC_NARRATION_MARKERS: if marker in plain: findings.append(Finding("error", name, f"generic narration 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(" 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] learning_progression_errors = [f for f in errors if "progressive" in f.message or "learning ladder" in f.message] knowledge_system_errors = [f for f in errors if "knowledge system" in f.message] natural_section_story_errors = [ f for f in errors if "section-specific story" in f.message or "generic section thread" in f.message or "generic narration marker" in f.message ] integrated_section_errors = [ f for f in errors if "integrated" in f.message or "legacy marker" in f.message or "legacy heading" in f.message ] html_integrity_errors = [f for f in errors if "html fragment leak" 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)}, "learning_progression": {"passed": not learning_progression_errors, "errors": len(learning_progression_errors)}, "knowledge_system": {"passed": not knowledge_system_errors, "errors": len(knowledge_system_errors)}, "natural_section_story": {"passed": not natural_section_story_errors, "errors": len(natural_section_story_errors)}, "integrated_sections": {"passed": not integrated_section_errors, "errors": len(integrated_section_errors)}, "html_integrity": {"passed": not html_integrity_errors, "errors": len(html_integrity_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())