Skip to content

Jobo16/ielts-buddy / skills/ielts-reading-review

ielts-reading-review

Verified

根据阅读题目、用户答案和原文证据解释错因、同义替换与干扰项,开展精读或整理阅读词块;也可读取已提交 IELTS Buddy 练习或模考科目。

scripts/reading-lexicon/validate_reading_lexicon_docx.py

View on GitHub
#!/usr/bin/env python3
"""Validate an IELTS Reading lexicon DOCX generated by this workflow."""

from __future__ import annotations

import argparse
import json
import re
from pathlib import Path
from xml.etree import ElementTree as ET
from zipfile import ZipFile


W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
W = f"{{{W_NS}}}"
FONT = "Times New Roman"


def qn(tag: str) -> str:
    return f"{W}{tag}"


def text_of(el: ET.Element) -> str:
    return "".join(t.text or "" for t in el.iter(qn("t")))


def normalize_spaces(text: str) -> str:
    return " ".join(text.split())


def contains_phrase(text: str, phrase: str) -> bool:
    return normalize_spaces(phrase).lower() in normalize_spaces(text).lower()


def validate_mc_ignorable_namespaces(doc_xml: str) -> None:
    match = re.search(r"<w:document\b([^>]*)>", doc_xml)
    if not match:
        return
    attrs = match.group(1)
    if re.search(r"\bns\d+:Ignorable=", attrs):
        raise SystemExit("Markup Compatibility Ignorable attribute was serialized with an unstable ns* prefix")
    declared = set(re.findall(r'xmlns:([^=\s]+)="[^"]+"', attrs))
    ignorable = re.search(r'\bmc:Ignorable="([^"]*)"', attrs)
    if not ignorable:
        return
    if "mc" not in declared:
        raise SystemExit("mc:Ignorable is present but xmlns:mc is missing")
    missing = [prefix for prefix in ignorable.group(1).split() if prefix not in declared]
    if missing:
        raise SystemExit(f"mc:Ignorable references undeclared namespace prefix(es): {missing}")


def direct_paragraphs(doc: ET.Element) -> list[ET.Element]:
    body = doc.find(qn("body"))
    if body is None:
        return []
    return [child for child in list(body) if child.tag == qn("p")]


def comment_ids_by_author(comments: ET.Element, author: str) -> set[str]:
    ids: set[str] = set()
    for comment in comments.findall(qn("comment")):
        if comment.get(qn("author")) == author:
            cid = comment.get(qn("id"))
            if cid is not None:
                ids.add(cid)
    return ids


def terms_from_plan(plan_path: Path | None) -> list[dict[str, object]]:
    if plan_path is None:
        return []
    plan = json.loads(plan_path.read_text(encoding="utf-8"))
    raw_terms = plan.get("terms") or plan.get("items") or plan.get("lexicon") or []
    if not isinstance(raw_terms, list):
        raise SystemExit("Plan terms must be an array")
    terms = [term for term in raw_terms if isinstance(term, dict) and str(term.get("phrase") or term.get("term") or "").strip()]
    if not terms:
        raise SystemExit("Plan does not contain any phrase terms")
    return terms


def phrase_of(term: dict[str, object]) -> str:
    return str(term.get("phrase") or term.get("term") or "").strip()


def read_doc_text(path: Path) -> str:
    with ZipFile(path) as zf:
        doc = ET.fromstring(zf.read("word/document.xml"))
    return text_of(doc)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("docx", type=Path)
    parser.add_argument("--input-docx", type=Path, default=None)
    parser.add_argument("--plan-json", type=Path, default=None)
    args = parser.parse_args()

    with ZipFile(args.docx) as zf:
        names = set(zf.namelist())
        required = {"word/document.xml", "[Content_Types].xml"}
        missing = sorted(required - names)
        if missing:
            raise SystemExit(f"Missing required DOCX parts: {missing}")
        doc_xml = zf.read("word/document.xml").decode("utf-8")
        validate_mc_ignorable_namespaces(doc_xml)
        doc = ET.fromstring(doc_xml)
        comments_xml = zf.read("word/comments.xml").decode("utf-8") if "word/comments.xml" in names else ""
        comments = ET.fromstring(comments_xml) if comments_xml else None

    output_text = text_of(doc)
    for marker in ["雅思阅读词汇手册", "核心词汇", "用法说明", "复习提示"]:
        if marker not in output_text:
            raise SystemExit(f"Missing required lexicon section: {marker}")

    terms = terms_from_plan(args.plan_json)
    for term in terms:
        phrase = phrase_of(term)
        if not contains_phrase(output_text, phrase):
            raise SystemExit(f"Phrase from plan is missing in output DOCX: {phrase}")
        for key in ("meaning", "usage", "example"):
            value = str(term.get(key) or "").strip()
            if value and not contains_phrase(output_text, value[:80]):
                raise SystemExit(f"{key} for '{phrase}' is missing in output DOCX")

    has_comment_entries = comments is not None and bool(comments.findall(qn("comment")))

    if args.input_docx:
        input_text = read_doc_text(args.input_docx)
        for term in terms:
            phrase = phrase_of(term)
            if not contains_phrase(input_text, phrase):
                raise SystemExit(f"Phrase does not appear in source DOCX: {phrase}")
        if comments is None:
            raise SystemExit("Expected word/comments.xml for annotated DOCX")
        cyber_ids = comment_ids_by_author(comments, "Cyber Esme")
        if not cyber_ids:
            raise SystemExit("Cyber Esme comment author not found")
        cyber_refs = [
            ref for ref in doc.iter(qn("commentReference"))
            if ref.get(qn("id")) in cyber_ids
        ]
        if len(cyber_refs) != len(cyber_ids):
            raise SystemExit(f"Cyber Esme comment mismatch: comments={len(cyber_ids)}, references={len(cyber_refs)}")
        if terms and len(cyber_ids) < len(terms):
            raise SystemExit(f"Expected at least one anchored comment per term: comments={len(cyber_ids)}, terms={len(terms)}")
        page_breaks = sum(1 for br in doc.iter(qn("br")) if br.get(qn("type")) == "page")
        if page_breaks < 2:
            raise SystemExit(f"Expected at least 2 page breaks, found {page_breaks}")
    elif has_comment_entries and "Cyber Esme" not in comments_xml:
        raise SystemExit("Unexpected comments part without Cyber Esme author")

    if FONT not in doc_xml:
        raise SystemExit(f"{FONT} not found in generated document XML")
    if has_comment_entries and FONT not in comments_xml:
        raise SystemExit(f"{FONT} not found in comments XML")

    paragraph_count = len([p for p in direct_paragraphs(doc) if normalize_spaces(text_of(p))])
    table_count = len(list(doc.iter(qn("tbl"))))
    print(f"OK: terms={len(terms) or 'unchecked'}, paragraphs={paragraph_count}, tables={table_count}")


if __name__ == "__main__":
    main()
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall