docx_validate.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. #!/usr/bin/env python3
  2. # MIT License. Part of the Hermes docx skill.
  3. """Health-check a .docx package and report issues as JSON.
  4. Usage: docx_validate.py file.docx
  5. Checks (health-check tier, NOT full XSD schema validation):
  6. - the file is a readable zip and python-docx can open it
  7. - required package parts exist ([Content_Types].xml, document.xml)
  8. - every relationship in every .rels file resolves to a part in the
  9. package (dangling image/hyperlink/etc. rels are reported; external
  10. targets such as hyperlinks are skipped)
  11. - r:embed / r:id references in document.xml resolve to relationships
  12. - embedded images are non-empty and start with known magic bytes
  13. (PNG/JPEG/GIF/BMP/TIFF/EMF/WMF/SVG); no PIL required
  14. - paragraph and run style ids referenced by the document exist in
  15. styles.xml
  16. Output: {"ok": bool, "issues": [{"severity": "error"|"warning", ...}]}
  17. Exit code 1 when any error-severity issue is found (warnings exit 0).
  18. """
  19. from __future__ import annotations
  20. import argparse
  21. import json
  22. import posixpath
  23. import sys
  24. import zipfile
  25. from lxml import etree
  26. W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
  27. R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
  28. PR = "http://schemas.openxmlformats.org/package/2006/relationships"
  29. IMAGE_MAGIC = (
  30. b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a",
  31. b"BM", b"II*\x00", b"MM\x00*",
  32. b"\x01\x00\x00\x00", # EMF
  33. b"\xd7\xcd\xc6\x9a", b"\x01\x00\x09\x00", # WMF variants
  34. b"<?xml", b"<svg",
  35. )
  36. def _issue(issues, severity, code, detail):
  37. issues.append({"severity": severity, "code": code, "detail": detail})
  38. def _rel_target(base_part: str, target: str) -> str:
  39. base_dir = posixpath.dirname(base_part)
  40. return posixpath.normpath(posixpath.join(base_dir, target)).lstrip("/")
  41. def validate(path: str) -> dict:
  42. issues: list[dict] = []
  43. try:
  44. zf = zipfile.ZipFile(path)
  45. except (OSError, zipfile.BadZipFile) as exc:
  46. _issue(issues, "error", "not-a-zip", str(exc))
  47. return {"ok": False, "issues": issues}
  48. names = set(zf.namelist())
  49. bad = zf.testzip()
  50. if bad is not None:
  51. _issue(issues, "error", "corrupt-member", f"CRC check failed: {bad}")
  52. for required in ("[Content_Types].xml", "word/document.xml"):
  53. if required not in names:
  54. _issue(issues, "error", "missing-part",
  55. f"required part absent: {required}")
  56. if issues and any(i["severity"] == "error" for i in issues):
  57. return {"ok": False, "issues": issues}
  58. # --- relationships resolve ------------------------------------------
  59. rel_ids_by_source: dict[str, dict] = {}
  60. for rels_name in [n for n in names if n.endswith(".rels")]:
  61. try:
  62. root = etree.fromstring(zf.read(rels_name))
  63. except etree.XMLSyntaxError as exc:
  64. _issue(issues, "error", "bad-rels-xml", f"{rels_name}: {exc}")
  65. continue
  66. source_part = posixpath.normpath(
  67. posixpath.join(posixpath.dirname(rels_name), ".."))
  68. source_part = "" if source_part == "." else source_part
  69. ids = {}
  70. for rel in root.iter(f"{{{PR}}}Relationship"):
  71. rid, target = rel.get("Id"), rel.get("Target", "")
  72. mode = rel.get("TargetMode", "Internal")
  73. ids[rid] = target
  74. if mode == "External":
  75. continue
  76. resolved = _rel_target(source_part + "/x" if source_part
  77. else "x", target)
  78. if resolved not in names:
  79. _issue(issues, "error", "dangling-rel",
  80. f"{rels_name}: {rid} -> {target} (missing part)")
  81. rel_ids_by_source[source_part or "_package"] = ids
  82. # --- r:id / r:embed references in document.xml -----------------------
  83. doc_root = etree.fromstring(zf.read("word/document.xml"))
  84. doc_rels = rel_ids_by_source.get("word", {})
  85. for el in doc_root.iter():
  86. for attr in (f"{{{R}}}id", f"{{{R}}}embed", f"{{{R}}}link"):
  87. rid = el.get(attr)
  88. if rid and rid not in doc_rels:
  89. _issue(issues, "error", "unresolved-reference",
  90. f"document.xml references {rid} with no relationship")
  91. # --- embedded images decode ------------------------------------------
  92. for name in [n for n in names if n.startswith("word/media/")]:
  93. data = zf.read(name)
  94. if not data:
  95. _issue(issues, "error", "empty-image", name)
  96. elif not any(data.startswith(m) for m in IMAGE_MAGIC):
  97. _issue(issues, "warning", "unknown-image-format",
  98. f"{name}: unrecognized magic bytes")
  99. # --- styles referenced exist ------------------------------------------
  100. defined = set()
  101. if "word/styles.xml" in names:
  102. styles_root = etree.fromstring(zf.read("word/styles.xml"))
  103. defined = {s.get(f"{{{W}}}styleId")
  104. for s in styles_root.iter(f"{{{W}}}style")}
  105. for tag, attr in ((f"{{{W}}}pStyle", f"{{{W}}}val"),
  106. (f"{{{W}}}rStyle", f"{{{W}}}val"),
  107. (f"{{{W}}}tblStyle", f"{{{W}}}val")):
  108. for el in doc_root.iter(tag):
  109. sid = el.get(attr)
  110. if sid and sid not in defined:
  111. _issue(issues, "error", "missing-style",
  112. f"style id referenced but not defined: {sid}")
  113. # --- python-docx can open it ------------------------------------------
  114. try:
  115. from docx import Document
  116. Document(path)
  117. except Exception as exc:
  118. _issue(issues, "error", "python-docx-open-failed", str(exc))
  119. ok = not any(i["severity"] == "error" for i in issues)
  120. return {"ok": ok, "issues": issues}
  121. def main() -> int:
  122. ap = argparse.ArgumentParser(
  123. description="Health-check a .docx (not XSD schema validation).")
  124. ap.add_argument("path", help="the .docx file to check")
  125. args = ap.parse_args()
  126. report = validate(args.path)
  127. print(json.dumps(report, ensure_ascii=False))
  128. return 0 if report["ok"] else 1
  129. if __name__ == "__main__":
  130. sys.exit(main())