docx_comments.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #!/usr/bin/env python3
  2. # MIT License. Part of the Hermes docx skill.
  3. """List, add, and delete comments in a .docx.
  4. Subcommands:
  5. list JSON per comment: id, author, initials, date, text, anchored_text
  6. add add a comment anchored to the first occurrence of --target
  7. delete remove a comment (and its range markers) by --id
  8. Examples:
  9. docx_comments.py list report.docx
  10. docx_comments.py add report.docx --target "Q3 revenue" \
  11. --text "Needs a source" --author "Reviewer" -o out.docx
  12. docx_comments.py delete report.docx --id 0 -o out.docx
  13. Uses the native python-docx comments API (>= 1.2) when available; falls
  14. back to building word/comments.xml and the range markers directly for
  15. older versions (or when --xml is passed). Listing and deletion always
  16. work at the XML level so they handle documents from any producer.
  17. """
  18. from __future__ import annotations
  19. import argparse
  20. import datetime as _dt
  21. import json
  22. import sys
  23. from copy import deepcopy
  24. from docx import Document
  25. from docx.opc.constants import RELATIONSHIP_TYPE as RT
  26. from lxml import etree
  27. from docx_common import iter_part_roots
  28. W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
  29. COMMENTS_CT = ("application/vnd.openxmlformats-officedocument"
  30. ".wordprocessingml.comments+xml")
  31. def q(tag: str) -> str:
  32. return f"{{{W}}}{tag}"
  33. # ---------------------------------------------------------------- reading
  34. def _comments_root(doc):
  35. """Return the XML root of the comments part, or None."""
  36. for rel in doc.part.rels.values():
  37. if rel.reltype == RT.COMMENTS:
  38. part = rel.target_part
  39. el = getattr(part, "_element", None)
  40. if el is not None:
  41. return el
  42. return etree.fromstring(part.blob)
  43. return None
  44. def _anchored_texts(doc) -> dict:
  45. """Map comment id -> document text between its range markers."""
  46. anchored: dict[str, list[str]] = {}
  47. for root in iter_part_roots(doc):
  48. active: set[str] = set()
  49. for el in root.iter():
  50. if el.tag == q("commentRangeStart"):
  51. cid = el.get(q("id"))
  52. active.add(cid)
  53. anchored.setdefault(cid, [])
  54. elif el.tag == q("commentRangeEnd"):
  55. active.discard(el.get(q("id")))
  56. elif el.tag == q("t") and active:
  57. for cid in active:
  58. anchored[cid].append(el.text or "")
  59. return {cid: "".join(parts) for cid, parts in anchored.items()}
  60. def list_comments(doc) -> list:
  61. root = _comments_root(doc)
  62. if root is None:
  63. return []
  64. anchored = _anchored_texts(doc)
  65. out = []
  66. for c in root.iter(q("comment")):
  67. cid = c.get(q("id"))
  68. text = "\n".join(
  69. "".join(t.text or "" for t in p.iter(q("t")))
  70. for p in c.iter(q("p")))
  71. out.append({"id": cid, "author": c.get(q("author")),
  72. "initials": c.get(q("initials")),
  73. "date": c.get(q("date")), "text": text,
  74. "anchored_text": anchored.get(cid, "")})
  75. return out
  76. # ---------------------------------------------------------------- anchoring
  77. def _split_run(para, run_el, offset: int):
  78. """Split a run element at text offset; return the new right-hand run."""
  79. text = "".join(t.text or "" for t in run_el.iter(q("t")))
  80. right = deepcopy(run_el)
  81. run_el.addnext(right)
  82. for el, s in ((run_el, text[:offset]), (right, text[offset:])):
  83. for t in list(el.iter(q("t"))):
  84. el.remove(t)
  85. t = etree.SubElement(el, q("t"))
  86. t.text = s
  87. t.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
  88. return right
  89. def find_anchor_runs(doc, target: str):
  90. """Isolate `target`'s first occurrence into whole runs; return them."""
  91. from docx_common import iter_all_paragraphs
  92. for para in iter_all_paragraphs(doc):
  93. full = para.text
  94. start = full.find(target)
  95. if start < 0:
  96. continue
  97. end = start + len(target)
  98. pos = 0
  99. covered = []
  100. for run_el in para._p.iter(q("r")):
  101. rtext = "".join(t.text or "" for t in run_el.iter(q("t")))
  102. r_start, r_end = pos, pos + len(rtext)
  103. pos = r_end
  104. if r_end <= start or r_start >= end:
  105. continue
  106. if r_start < start: # split off the left part
  107. run_el = _split_run(para, run_el, start - r_start)
  108. r_start = start
  109. if r_end > end: # split off the right part
  110. _split_run(para, run_el, end - r_start)
  111. covered.append(run_el)
  112. return para, covered
  113. return None, []
  114. # ---------------------------------------------------------------- adding
  115. def _next_id(doc) -> int:
  116. root = _comments_root(doc)
  117. if root is None:
  118. return 0
  119. ids = [int(c.get(q("id"), "0")) for c in root.iter(q("comment"))
  120. if c.get(q("id"), "").isdigit()]
  121. return max(ids) + 1 if ids else 0
  122. def add_comment_native(doc, runs, text, author, initials):
  123. from docx.text.run import Run
  124. run_objs = [Run(r, None) for r in runs]
  125. comment = doc.add_comment(run_objs, text=text, author=author,
  126. initials=initials or "")
  127. return str(comment.comment_id)
  128. def add_comment_xml(doc, runs, text, author, initials) -> str:
  129. cid = str(_next_id(doc))
  130. root = _comments_root(doc)
  131. if root is None:
  132. root = etree.fromstring(
  133. f'<w:comments xmlns:w="{W}"/>'.encode())
  134. from docx.opc.packuri import PackURI
  135. from docx.opc.part import Part
  136. blob = etree.tostring(root, xml_declaration=True,
  137. encoding="UTF-8", standalone=True)
  138. part = Part(PackURI("/word/comments.xml"), COMMENTS_CT, blob,
  139. doc.part.package)
  140. doc.part.relate_to(part, RT.COMMENTS)
  141. # keep a live element on the part so edits reach save()
  142. part._element = root
  143. part.blob_ = None
  144. def _blob(self=part):
  145. return etree.tostring(self._element, xml_declaration=True,
  146. encoding="UTF-8", standalone=True)
  147. part.__class__ = type("CommentsXmlPart", (Part,),
  148. {"blob": property(lambda self: _blob(self))})
  149. now = _dt.datetime.now(_dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
  150. comment = etree.SubElement(root, q("comment"))
  151. comment.set(q("id"), cid)
  152. comment.set(q("author"), author)
  153. if initials:
  154. comment.set(q("initials"), initials)
  155. comment.set(q("date"), now)
  156. p = etree.SubElement(comment, q("p"))
  157. r = etree.SubElement(p, q("r"))
  158. t = etree.SubElement(r, q("t"))
  159. t.text = text
  160. # range markers around the anchor runs + reference run after them
  161. first, last = runs[0], runs[-1]
  162. start = first.makeelement(q("commentRangeStart"), {q("id"): cid})
  163. first.addprevious(start)
  164. end = last.makeelement(q("commentRangeEnd"), {q("id"): cid})
  165. last.addnext(end)
  166. ref_run = last.makeelement(q("r"), {})
  167. ref = etree.SubElement(ref_run, q("commentReference"))
  168. ref.set(q("id"), cid)
  169. end.addnext(ref_run)
  170. return cid
  171. # ---------------------------------------------------------------- deleting
  172. def delete_comment(doc, cid: str) -> bool:
  173. root = _comments_root(doc)
  174. found = False
  175. if root is not None:
  176. for c in list(root.iter(q("comment"))):
  177. if c.get(q("id")) == cid:
  178. c.getparent().remove(c)
  179. found = True
  180. for part_root in iter_part_roots(doc):
  181. for tag in ("commentRangeStart", "commentRangeEnd",
  182. "commentReference"):
  183. for el in list(part_root.iter(q(tag))):
  184. if el.get(q("id")) == cid:
  185. parent = el.getparent()
  186. # remove the wrapping run for reference marks
  187. if tag == "commentReference" and parent.tag == q("r"):
  188. parent.getparent().remove(parent)
  189. else:
  190. parent.remove(el)
  191. found = True
  192. return found
  193. def main() -> int:
  194. ap = argparse.ArgumentParser(
  195. description="List, add, or delete comments in a .docx.")
  196. sub = ap.add_subparsers(dest="cmd", required=True)
  197. p = sub.add_parser("list", help="list comments as JSON")
  198. p.add_argument("path", help="input .docx")
  199. p = sub.add_parser("add", help="add a comment anchored to text")
  200. p.add_argument("path", help="input .docx")
  201. p.add_argument("-o", "--output", help="output path (default: in place)")
  202. p.add_argument("--target", required=True,
  203. help="anchor: first occurrence of this text")
  204. p.add_argument("--text", required=True, help="comment body")
  205. p.add_argument("--author", default="Hermes")
  206. p.add_argument("--initials", default="")
  207. p.add_argument("--xml", action="store_true",
  208. help="force the XML fallback (skip native API)")
  209. p = sub.add_parser("delete", help="delete a comment by id")
  210. p.add_argument("path", help="input .docx")
  211. p.add_argument("-o", "--output", help="output path (default: in place)")
  212. p.add_argument("--id", required=True, help="comment id")
  213. args = ap.parse_args()
  214. doc = Document(args.path)
  215. if args.cmd == "list":
  216. print(json.dumps({"ok": True, "comments": list_comments(doc)},
  217. ensure_ascii=False))
  218. return 0
  219. if args.cmd == "add":
  220. _para, runs = find_anchor_runs(doc, args.target)
  221. if not runs:
  222. print(json.dumps({"ok": False,
  223. "error": f"target not found: {args.target}"}))
  224. return 1
  225. native = hasattr(doc, "add_comment") and not args.xml
  226. if native:
  227. cid = add_comment_native(doc, runs, args.text, args.author,
  228. args.initials)
  229. else:
  230. cid = add_comment_xml(doc, runs, args.text, args.author,
  231. args.initials)
  232. result = {"ok": True, "comment_id": cid,
  233. "native_api": native, "anchored_to": args.target}
  234. else: # delete
  235. if not delete_comment(doc, args.id):
  236. print(json.dumps({"ok": False,
  237. "error": f"no comment with id {args.id}"}))
  238. return 1
  239. result = {"ok": True, "deleted_id": args.id}
  240. out = args.output or args.path
  241. doc.save(out)
  242. result["output"] = out
  243. print(json.dumps(result, ensure_ascii=False))
  244. return 0
  245. if __name__ == "__main__":
  246. sys.exit(main())