Jobo16/ielts-buddy / skills/ielts-writing-review
ielts-writing-review
Verified批改雅思 Task 1 或 Task 2 作文,进行写前规划、原文证据批注和二改对照;需要可下载 Word 时生成并验证文档。用户提供作文即可使用,网站连接可选。
scripts/ielts-task1-review/validate_task1_review_docx.py
View on GitHub#!/usr/bin/env python3
"""Validate an IELTS Task 1 reviewed DOCX generated by this skill."""
from __future__ import annotations
import argparse
import re
from pathlib import Path
from xml.etree import ElementTree as ET
from zipfile import ZipFile
from extract_task1_input import extract_docx as extract_task1_docx
W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
W = f"{{{W_NS}}}"
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 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 paragraph_has_comment_id(paragraph: ET.Element, comment_ids: set[str]) -> bool:
for ref in paragraph.iter(qn("commentReference")):
if ref.get(qn("id")) in comment_ids:
return True
return False
def original_paragraph_positions(input_doc: ET.Element, output_doc: ET.Element) -> set[int]:
input_texts = [normalize_spaces(text_of(p)) for p in direct_paragraphs(input_doc)]
input_texts = [text for text in input_texts if text]
output_paragraphs = direct_paragraphs(output_doc)
output_texts = [normalize_spaces(text_of(p)) for p in output_paragraphs]
positions: set[int] = set()
start = 0
for input_text in input_texts:
for idx in range(start, len(output_texts)):
if output_texts[idx] == input_text:
positions.add(idx)
start = idx + 1
break
return positions
def original_paragraph_position_map(input_doc: ET.Element, output_doc: ET.Element) -> dict[int, int]:
input_texts = [normalize_spaces(text_of(p)) for p in direct_paragraphs(input_doc)]
output_paragraphs = direct_paragraphs(output_doc)
output_texts = [normalize_spaces(text_of(p)) for p in output_paragraphs]
positions: dict[int, int] = {}
start = 0
for input_number, input_text in enumerate(input_texts, start=1):
if not input_text:
continue
for idx in range(start, len(output_texts)):
if output_texts[idx] == input_text:
positions[input_number] = idx
start = idx + 1
break
return positions
def paragraph_texts_by_page(doc: ET.Element) -> list[list[str]]:
paragraphs = direct_paragraphs(doc)
if not paragraphs:
return [[text_of(doc)]]
pages: list[list[str]] = [[]]
for child in paragraphs:
text = text_of(child).strip()
breaks = sum(1 for br in child.iter(qn("br")) if br.get(qn("type")) == "page")
if text:
pages[-1].append(text)
for _ in range(breaks):
pages.append([])
return pages
def pages_of(doc: ET.Element) -> list[str]:
return [" ".join(page).strip() for page in paragraph_texts_by_page(doc)]
def word_count(text: str) -> int:
return len(re.findall(r"[A-Za-z]+(?:[-'][A-Za-z]+)?|\d+", text))
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("docx", type=Path)
parser.add_argument("--input-docx", type=Path, default=None, help="Original DOCX used to verify comment anchoring.")
args = parser.parse_args()
with ZipFile(args.docx) as zf:
names = set(zf.namelist())
required = {"word/document.xml", "word/comments.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")
comments_xml = zf.read("word/comments.xml").decode("utf-8")
validate_mc_ignorable_namespaces(doc_xml)
doc = ET.fromstring(doc_xml)
comments = ET.fromstring(comments_xml)
input_doc = None
if args.input_docx:
with ZipFile(args.input_docx) as zf:
input_doc = ET.fromstring(zf.read("word/document.xml"))
comment_count = len(comments.findall(qn("comment")))
comment_refs = len(list(doc.iter(qn("commentReference"))))
italic_runs = 0
for run in doc.iter(qn("r")):
rpr = run.find(qn("rPr"))
if rpr is not None and rpr.find(qn("i")) is not None:
italic_runs += 1
all_text = text_of(doc)
for marker in ["冲刺 Band 7.5 / 8.0", "Task Achievement", "Coherence & Cohesion", "Lexical Resource", "Grammatical Range & Accuracy", "Overall"]:
if marker not in all_text:
raise SystemExit(f"Missing required review text: {marker}")
for removed_heading in ["IELTS Writing Task 1 Review", "Reviewed Answer", "Model Answer"]:
if removed_heading in all_text:
raise SystemExit(f"Old heading should not be present: {removed_heading}")
authors = {c.get(qn("author")) for c in comments.findall(qn("comment"))}
if "Cyber Esme" not in authors:
raise SystemExit(f"Cyber Esme comment author not found; authors={authors}")
cyber_ids = comment_ids_by_author(comments, "Cyber Esme")
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 input_doc is not None:
original_positions = original_paragraph_positions(input_doc, doc)
position_map = original_paragraph_position_map(input_doc, doc)
extraction = extract_task1_docx(args.input_docx)
answer_positions = {
position_map[int(index)]
for index in extraction.get("student_answer_paragraph_indices", [])
if int(index) in position_map
}
output_paragraphs = direct_paragraphs(doc)
cyber_comment_positions = [
idx for idx, paragraph in enumerate(output_paragraphs)
if paragraph_has_comment_id(paragraph, cyber_ids)
]
if not cyber_comment_positions:
raise SystemExit("No Cyber Esme comments found in document paragraphs")
misplaced = [idx for idx in cyber_comment_positions if idx not in original_positions]
if misplaced:
raise SystemExit(f"Cyber Esme comments are not anchored to original input paragraphs: {misplaced[:10]}")
if not answer_positions:
raise SystemExit("Could not determine student answer paragraph positions from input DOCX")
misplaced_answer = [idx for idx in cyber_comment_positions if idx not in answer_positions]
if misplaced_answer:
raise SystemExit(f"Cyber Esme comments are not anchored to student answer paragraphs: {misplaced_answer[:10]}")
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}")
if "Times New Roman" not in doc_xml or "Times New Roman" not in comments_xml:
raise SystemExit("Times New Roman not found in document or comments")
model_page = paragraph_texts_by_page(doc)[-1]
model_paragraphs = [
normalize_spaces(text)
for text in model_page
if not re.fullmatch(r"\(\d+\s*words\)", normalize_spaces(text), flags=re.I)
]
if len(model_paragraphs) != 4:
raise SystemExit(f"Model answer must contain exactly 4 paragraphs before the word-count line: {len(model_paragraphs)}")
if not re.match(r"^overall\b", model_paragraphs[1], flags=re.I):
raise SystemExit("Task 1 model answer paragraph 2 must begin with 'Overall'")
model = " ".join(model_paragraphs)
words = word_count(model)
if not 150 <= words <= 200:
raise SystemExit(f"Model answer word count must be 150-200: {words}")
if italic_runs == 0:
raise SystemExit("No italic rewrite runs found")
print(f"OK: comments={comment_count}, italic_runs={italic_runs}, page_breaks={page_breaks}, model_words={words}")
if __name__ == "__main__":
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| 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 implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| 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 fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| 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 always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |