docx_read.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #!/usr/bin/env python3
  2. # MIT License. Part of the Hermes docx skill.
  3. """Read a .docx: text, structure outline, styles, images, revision detection.
  4. Usage:
  5. docx_read.py file.docx --text # full text incl. tables + headers/footers
  6. docx_read.py file.docx --structure # JSON outline (headings, tables, counts)
  7. docx_read.py file.docx --styles # JSON list of styles actually used
  8. docx_read.py file.docx --images DIR # extract embedded images into DIR
  9. docx_read.py file.docx --revisions # JSON: tracked changes / comments present?
  10. Text output is JSON: {"body": [...], "tables": [[...rows]], "headers": [...],
  11. "footers": [...]}. Body text is the accepted/as-is text (python-docx ignores
  12. deleted-in-revision text and shows inserted text).
  13. """
  14. from __future__ import annotations
  15. import argparse
  16. import json
  17. import os
  18. import sys
  19. import zipfile
  20. from docx import Document
  21. def cell_text(cell) -> str:
  22. """Flatten a cell's paragraphs and nested tables in document order."""
  23. parts = []
  24. for block in cell.iter_inner_content():
  25. if hasattr(block, "rows"):
  26. for row in table_to_rows(block):
  27. parts.extend(text for text in row if text)
  28. elif block.text:
  29. parts.append(block.text)
  30. return "\n".join(parts)
  31. def table_to_rows(table) -> list:
  32. return [[cell_text(cell) for cell in row.cells] for row in table.rows]
  33. def append_part_text(target: list[str], part, seen: set[int]) -> None:
  34. """Append one header/footer variant without duplicating linked parts."""
  35. marker = id(part._element)
  36. if marker in seen:
  37. return
  38. seen.add(marker)
  39. target.extend(p.text for p in part.paragraphs)
  40. for table in part.tables:
  41. target.append(json.dumps(table_to_rows(table), ensure_ascii=False))
  42. def extract_text(doc) -> dict:
  43. out = {"body": [p.text for p in doc.paragraphs],
  44. "tables": [table_to_rows(t) for t in doc.tables],
  45. "headers": [], "footers": []}
  46. seen_headers: set[int] = set()
  47. seen_footers: set[int] = set()
  48. for section in doc.sections:
  49. for part in (section.header, section.first_page_header,
  50. section.even_page_header):
  51. append_part_text(out["headers"], part, seen_headers)
  52. for part in (section.footer, section.first_page_footer,
  53. section.even_page_footer):
  54. append_part_text(out["footers"], part, seen_footers)
  55. return out
  56. def extract_structure(doc) -> dict:
  57. outline = []
  58. for i, para in enumerate(doc.paragraphs):
  59. style = para.style.name if para.style else ""
  60. if style.startswith("Heading"):
  61. try:
  62. level = int(style.split()[-1])
  63. except ValueError:
  64. level = 1
  65. outline.append({"index": i, "level": level, "text": para.text})
  66. return {
  67. "outline": outline,
  68. "paragraph_count": len(doc.paragraphs),
  69. "table_count": len(doc.tables),
  70. "tables": [{"rows": len(t.rows), "cols": len(t.columns)}
  71. for t in doc.tables],
  72. "section_count": len(doc.sections),
  73. }
  74. def styles_used(doc) -> list:
  75. used = set()
  76. for para in doc.paragraphs:
  77. if para.style:
  78. used.add(para.style.name)
  79. for run in para.runs:
  80. if run.style:
  81. used.add(run.style.name)
  82. for table in doc.tables:
  83. if table.style:
  84. used.add(table.style.name)
  85. for row in table.rows:
  86. for cell in row.cells:
  87. for para in cell.paragraphs:
  88. if para.style:
  89. used.add(para.style.name)
  90. return sorted(used)
  91. def extract_images(path: str, outdir: str) -> list:
  92. os.makedirs(outdir, exist_ok=True)
  93. written = []
  94. with zipfile.ZipFile(path) as zf:
  95. for name in zf.namelist():
  96. if name.startswith("word/media/"):
  97. target = os.path.join(outdir, os.path.basename(name))
  98. with open(target, "wb") as f:
  99. f.write(zf.read(name))
  100. written.append(target)
  101. return written
  102. def detect_revisions(path: str) -> dict:
  103. """Detect tracked changes and comments by scanning the raw XML parts."""
  104. markers = {"insertions": b"<w:ins ", "deletions": b"<w:del ",
  105. "format_changes": b"<w:rPrChange"}
  106. result = {k: False for k in markers}
  107. result["comments"] = False
  108. with zipfile.ZipFile(path) as zf:
  109. names = zf.namelist()
  110. result["comments"] = any(n.startswith("word/comments") for n in names)
  111. for name in names:
  112. if name.startswith("word/") and name.endswith(".xml"):
  113. data = zf.read(name)
  114. for key, marker in markers.items():
  115. if marker in data:
  116. result[key] = True
  117. result["has_tracked_changes"] = any(
  118. result[k] for k in ("insertions", "deletions", "format_changes"))
  119. return result
  120. def main() -> int:
  121. ap = argparse.ArgumentParser(description="Read/inspect a .docx file.")
  122. ap.add_argument("path", help=".docx file to read")
  123. g = ap.add_mutually_exclusive_group(required=True)
  124. g.add_argument("--text", action="store_true", help="extract all text as JSON")
  125. g.add_argument("--structure", action="store_true", help="outline JSON")
  126. g.add_argument("--styles", action="store_true", help="styles used, JSON")
  127. g.add_argument("--images", metavar="DIR", help="extract images to DIR")
  128. g.add_argument("--revisions", action="store_true",
  129. help="detect tracked changes / comments")
  130. args = ap.parse_args()
  131. if args.images:
  132. print(json.dumps({"images": extract_images(args.path, args.images)},
  133. ensure_ascii=False))
  134. return 0
  135. if args.revisions:
  136. print(json.dumps(detect_revisions(args.path), ensure_ascii=False))
  137. return 0
  138. doc = Document(args.path)
  139. if args.text:
  140. out = extract_text(doc)
  141. elif args.structure:
  142. out = extract_structure(doc)
  143. else:
  144. out = {"styles": styles_used(doc)}
  145. print(json.dumps(out, ensure_ascii=False, indent=2))
  146. return 0
  147. if __name__ == "__main__":
  148. sys.exit(main())