verify_anchor_atomicity.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import argparse
  2. import json
  3. import re
  4. import sys
  5. import xml.etree.ElementTree as ET
  6. from pathlib import Path
  7. from zipfile import ZipFile
  8. NS = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
  9. ANCHOR_RE = re.compile(r"@@[A-Z]+:[A-Za-z0-9_-]+@@")
  10. def qn(name: str) -> str:
  11. return f"{{{NS['w']}}}{name}"
  12. def load_document_xml(path: Path) -> ET.Element:
  13. with ZipFile(path, "r") as archive:
  14. with archive.open("word/document.xml") as handle:
  15. return ET.fromstring(handle.read())
  16. def paragraph_text_nodes(paragraph: ET.Element):
  17. return paragraph.findall(".//w:t", NS)
  18. def paragraph_location(index: int) -> str:
  19. return f"/word/document.xml#p[{index}]"
  20. def analyze(path: Path) -> dict:
  21. root = load_document_xml(path)
  22. paragraphs = root.findall(".//w:body//w:p", NS)
  23. results = []
  24. for idx, paragraph in enumerate(paragraphs, start=1):
  25. text_nodes = paragraph_text_nodes(paragraph)
  26. full_text = "".join(node.text or "" for node in text_nodes)
  27. anchors = ANCHOR_RE.findall(full_text)
  28. if not anchors:
  29. continue
  30. for anchor in anchors:
  31. matching_nodes = []
  32. for node in text_nodes:
  33. node_text = node.text or ""
  34. if anchor in node_text:
  35. matching_nodes.append(node)
  36. status = "ok" if len(matching_nodes) == 1 else "cross_run"
  37. results.append(
  38. {
  39. "anchor": anchor,
  40. "status": status,
  41. "location": paragraph_location(idx),
  42. "textNodeHits": len(matching_nodes),
  43. }
  44. )
  45. return {
  46. "file": str(path),
  47. "ok": all(item["status"] == "ok" for item in results),
  48. "anchors": results,
  49. }
  50. def main() -> int:
  51. parser = argparse.ArgumentParser(description="Verify that DOCX anchors are atomic within single w:t nodes.")
  52. parser.add_argument("input_path", help="Path to the .docx file")
  53. args = parser.parse_args()
  54. input_path = Path(args.input_path).expanduser().resolve()
  55. if not input_path.exists():
  56. raise RuntimeError(f"Input file does not exist: {input_path}")
  57. if input_path.suffix.lower() != ".docx":
  58. raise RuntimeError("verify_anchor_atomicity.py currently supports .docx only")
  59. result = analyze(input_path)
  60. print(json.dumps(result, ensure_ascii=False, indent=2))
  61. return 0
  62. if __name__ == "__main__":
  63. try:
  64. raise SystemExit(main())
  65. except Exception as exc: # pragma: no cover
  66. print(f"verify_anchor_atomicity.py failed: {exc}", file=sys.stderr)
  67. raise SystemExit(1)