docx_revisions.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #!/usr/bin/env python3
  2. # MIT License. Part of the Hermes docx skill.
  3. """Inspect and resolve tracked changes (w:ins / w:del) in a .docx.
  4. Subcommands:
  5. list JSON list of revisions: id, author, date, type, text
  6. accept-all accept every insertion and deletion
  7. reject-all reject every insertion and deletion
  8. accept accept one revision by --id
  9. reject reject one revision by --id
  10. Examples:
  11. docx_revisions.py list report.docx
  12. docx_revisions.py accept-all report.docx -o accepted.docx
  13. docx_revisions.py reject report.docx --id 3 -o out.docx
  14. Semantics (direct XML manipulation, python-docx oxml layer):
  15. accept w:ins -> unwrap (keep inserted runs) reject w:ins -> remove
  16. accept w:del -> remove reject w:del -> restore
  17. (restore = w:delText tags renamed to w:t, wrapper unwrapped)
  18. Covers run-level insertions/deletions anywhere in body, tables (nested
  19. included), headers and footers. Row/paragraph-mark revisions and format
  20. changes (w:rPrChange etc.) are reported by docx_read.py --revisions but
  21. not resolved here.
  22. """
  23. from __future__ import annotations
  24. import argparse
  25. import json
  26. import sys
  27. from docx import Document
  28. from docx_common import iter_part_roots
  29. W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
  30. def q(tag: str) -> str:
  31. return f"{{{W}}}{tag}"
  32. INS, DEL = q("ins"), q("del")
  33. def _iter_revision_elements(doc):
  34. """Yield every w:ins / w:del element across body, headers, footers."""
  35. for root in iter_part_roots(doc):
  36. yield from root.iter(INS, DEL)
  37. def _rev_text(el) -> str:
  38. tag = q("delText") if el.tag == DEL else q("t")
  39. return "".join(t.text or "" for t in el.iter(tag))
  40. def _rev_record(el) -> dict:
  41. return {
  42. "id": el.get(q("id")),
  43. "author": el.get(q("author")),
  44. "date": el.get(q("date")),
  45. "type": "insertion" if el.tag == INS else "deletion",
  46. "text": _rev_text(el),
  47. }
  48. def _unwrap(el) -> None:
  49. """Replace `el` with its children, keeping document order."""
  50. parent = el.getparent()
  51. idx = list(parent).index(el)
  52. for child in list(el):
  53. parent.insert(idx, child)
  54. idx += 1
  55. parent.remove(el)
  56. def _apply(el, accept: bool) -> None:
  57. if el.getparent() is None: # already detached via an outer wrapper
  58. return
  59. if el.tag == INS:
  60. if accept:
  61. _unwrap(el)
  62. else:
  63. el.getparent().remove(el)
  64. else: # w:del
  65. if accept:
  66. el.getparent().remove(el)
  67. else:
  68. for dt in list(el.iter(q("delText"))):
  69. dt.tag = q("t")
  70. _unwrap(el)
  71. def resolve(doc, accept: bool, rev_id: str | None = None) -> int:
  72. targets = [el for el in _iter_revision_elements(doc)
  73. if rev_id is None or el.get(q("id")) == rev_id]
  74. for el in targets:
  75. _apply(el, accept)
  76. return len(targets)
  77. def main() -> int:
  78. ap = argparse.ArgumentParser(
  79. description="List, accept, or reject tracked changes in a .docx.")
  80. sub = ap.add_subparsers(dest="cmd", required=True)
  81. def common(p, out=True):
  82. p.add_argument("path", help="input .docx")
  83. if out:
  84. p.add_argument("-o", "--output",
  85. help="output path (default: overwrite input)")
  86. common(sub.add_parser("list", help="list revisions as JSON"), out=False)
  87. common(sub.add_parser("accept-all", help="accept every revision"))
  88. common(sub.add_parser("reject-all", help="reject every revision"))
  89. for name in ("accept", "reject"):
  90. p = sub.add_parser(name, help=f"{name} one revision by id")
  91. common(p)
  92. p.add_argument("--id", required=True, help="revision id (w:id)")
  93. args = ap.parse_args()
  94. doc = Document(args.path)
  95. if args.cmd == "list":
  96. revs = [_rev_record(el) for el in _iter_revision_elements(doc)]
  97. print(json.dumps({"ok": True, "revisions": revs}, ensure_ascii=False))
  98. return 0
  99. accept = args.cmd in ("accept-all", "accept")
  100. rev_id = getattr(args, "id", None)
  101. n = resolve(doc, accept, rev_id)
  102. if rev_id is not None and n == 0:
  103. print(json.dumps({"ok": False,
  104. "error": f"no revision with id {rev_id}"}))
  105. return 1
  106. out = args.output or args.path
  107. doc.save(out)
  108. print(json.dumps({"ok": True, "output": out, "resolved": n,
  109. "action": "accept" if accept else "reject"},
  110. ensure_ascii=False))
  111. return 0
  112. if __name__ == "__main__":
  113. sys.exit(main())