Skillfarm / skills · skillfarm.ai / converted / docx / scripts / comment.py
| 1 | """Add comments to a DOCX document. |
| 2 | |
| 3 | Accepts either an unpacked directory OR a .docx/.dotx file directly. |
| 4 | |
| 5 | Usage: |
| 6 | # Against an unpacked directory (writes satellite files in place) |
| 7 | python comment.py unpacked/ "Comment text" |
| 8 | python comment.py unpacked/ "Reply text" --parent 0 |
| 9 | |
| 10 | # Against a .docx directly (extracts, writes satellite files, rezips) |
| 11 | python comment.py contract.docx "This cap is too low" -o annotated.docx |
| 12 | python comment.py contract.docx "Comment" --id 5 # explicit ID |
| 13 | |
| 14 | The comment ID is auto-assigned (max existing + 1) unless --id is given. |
| 15 | Plain text is XML-escaped automatically; if you pass already-escaped text |
| 16 | (e.g. &, ’) use --raw to skip escaping. |
| 17 | |
| 18 | After running, add markers to word/document.xml so the comment is visible: |
| 19 | <w:commentRangeStart w:id="N"/> |
| 20 | ... commented content ... |
| 21 | <w:commentRangeEnd w:id="N"/> |
| 22 | <w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:commentReference w:id="N"/></w:r> |
| 23 | """ |
| 24 | |
| 25 | import argparse |
| 26 | import random |
| 27 | import shutil |
| 28 | import sys |
| 29 | import tempfile |
| 30 | import zipfile |
| 31 | from datetime import datetime, timezone |
| 32 | from pathlib import Path |
| 33 | |
| 34 | import defusedxml.minidom |
| 35 | from xml.parsers.expat import ExpatError |
| 36 | from xml.sax.saxutils import escape as xml_escape |
| 37 | |
| 38 | from office.helpers import opc_target, rezip as _rezip, safe_extract as _safe_extract |
| 39 | |
| 40 | TEMPLATE_DIR = Path(__file__).parent / "templates" |
| 41 | NS = { |
| 42 | "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main", |
| 43 | "w14": "http://schemas.microsoft.com/office/word/2010/wordml", |
| 44 | "w15": "http://schemas.microsoft.com/office/word/2012/wordml", |
| 45 | "w16cid": "http://schemas.microsoft.com/office/word/2016/wordml/cid", |
| 46 | "w16cex": "http://schemas.microsoft.com/office/word/2018/wordml/cex", |
| 47 | } |
| 48 | |
| 49 | COMMENT_XML = """\ |
| 50 | <w:comment w:id="{id}" w:author="{author}" w:date="{date}" w:initials="{initials}"> |
| 51 | <w:p w14:paraId="{para_id}" w14:textId="77777777"> |
| 52 | <w:r> |
| 53 | <w:rPr><w:rStyle w:val="CommentReference"/></w:rPr> |
| 54 | <w:annotationRef/> |
| 55 | </w:r> |
| 56 | <w:r> |
| 57 | <w:rPr> |
| 58 | <w:color w:val="000000"/> |
| 59 | <w:sz w:val="20"/> |
| 60 | <w:szCs w:val="20"/> |
| 61 | </w:rPr> |
| 62 | <w:t xml:space="preserve">{text}</w:t> |
| 63 | </w:r> |
| 64 | </w:p> |
| 65 | </w:comment>""" |
| 66 | |
| 67 | COMMENT_MARKER_TEMPLATE = """ |
| 68 | Add to word/document.xml (markers must be direct children of w:p, never inside w:r): |
| 69 | <w:commentRangeStart w:id="{cid}"/> |
| 70 | <w:r>...</w:r> |
| 71 | <w:commentRangeEnd w:id="{cid}"/> |
| 72 | <w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:commentReference w:id="{cid}"/></w:r>""" |
| 73 | |
| 74 | REPLY_MARKER_TEMPLATE = """ |
| 75 | Nest markers inside parent {pid}'s markers (direct children of w:p, never inside w:r): |
| 76 | <w:commentRangeStart w:id="{pid}"/><w:commentRangeStart w:id="{cid}"/> |
| 77 | <w:r>...</w:r> |
| 78 | <w:commentRangeEnd w:id="{cid}"/><w:commentRangeEnd w:id="{pid}"/> |
| 79 | <w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:commentReference w:id="{pid}"/></w:r> |
| 80 | <w:r><w:rPr><w:rStyle w:val="CommentReference"/></w:rPr><w:commentReference w:id="{cid}"/></w:r>""" |
| 81 | |
| 82 | SMART_QUOTE_ENTITIES = { |
| 83 | "“": "“", |
| 84 | "”": "”", |
| 85 | "‘": "‘", |
| 86 | "’": "’", |
| 87 | } |
| 88 | |
| 89 | |
| 90 | def _generate_hex_id() -> str: |
| 91 | return f"{random.randint(0, 0x7FFFFFFE):08X}" |
| 92 | |
| 93 | |
| 94 | def _encode_smart_quotes(text: str) -> str: |
| 95 | for char, entity in SMART_QUOTE_ENTITIES.items(): |
| 96 | text = text.replace(char, entity) |
| 97 | return text |
| 98 | |
| 99 | |
| 100 | def _append_xml(xml_path: Path, root_tag: str, content: str) -> None: |
| 101 | dom = defusedxml.minidom.parseString(xml_path.read_text(encoding="utf-8")) |
| 102 | root = dom.getElementsByTagName(root_tag)[0] |
| 103 | ns_attrs = " ".join(f'xmlns:{k}="{v}"' for k, v in NS.items()) |
| 104 | wrapper_dom = defusedxml.minidom.parseString(f"<root {ns_attrs}>{content}</root>") |
| 105 | for child in wrapper_dom.documentElement.childNodes: |
| 106 | if child.nodeType == child.ELEMENT_NODE: |
| 107 | root.appendChild(dom.importNode(child, True)) |
| 108 | output = _encode_smart_quotes(dom.toxml(encoding="UTF-8").decode("utf-8")) |
| 109 | xml_path.write_text(output, encoding="utf-8") |
| 110 | |
| 111 | |
| 112 | def _find_para_id(comments_path: Path, comment_id: int) -> str | None: |
| 113 | dom = defusedxml.minidom.parseString(comments_path.read_text(encoding="utf-8")) |
| 114 | for c in dom.getElementsByTagName("w:comment"): |
| 115 | if c.getAttribute("w:id") == str(comment_id): |
| 116 | for p in c.getElementsByTagName("w:p"): |
| 117 | if pid := p.getAttribute("w14:paraId"): |
| 118 | return pid |
| 119 | return None |
| 120 | |
| 121 | |
| 122 | def _next_comment_id(comments_path: Path) -> int: |
| 123 | if not comments_path.exists(): |
| 124 | return 0 |
| 125 | dom = defusedxml.minidom.parseString(comments_path.read_text(encoding="utf-8")) |
| 126 | ids = [] |
| 127 | for c in dom.getElementsByTagName("w:comment"): |
| 128 | try: |
| 129 | ids.append(int(c.getAttribute("w:id"))) |
| 130 | except ValueError: |
| 131 | pass |
| 132 | return (max(ids) + 1) if ids else 0 |
| 133 | |
| 134 | |
| 135 | def _get_next_rid(rels_path: Path) -> int: |
| 136 | dom = defusedxml.minidom.parseString(rels_path.read_text(encoding="utf-8")) |
| 137 | max_rid = 0 |
| 138 | for rel in dom.getElementsByTagName("Relationship"): |
| 139 | rid = rel.getAttribute("Id") |
| 140 | if rid and rid.startswith("rId"): |
| 141 | try: |
| 142 | max_rid = max(max_rid, int(rid[3:])) |
| 143 | except ValueError: |
| 144 | pass |
| 145 | return max_rid + 1 |
| 146 | |
| 147 | |
| 148 | def _has_relationship(rels_path: Path, target: str) -> bool: |
| 149 | dom = defusedxml.minidom.parseString(rels_path.read_text(encoding="utf-8")) |
| 150 | return any( |
| 151 | rel.getAttribute("Target") == target |
| 152 | for rel in dom.getElementsByTagName("Relationship") |
| 153 | ) |
| 154 | |
| 155 | |
| 156 | def _has_content_type(ct_path: Path, part_name: str) -> bool: |
| 157 | dom = defusedxml.minidom.parseString(ct_path.read_text(encoding="utf-8")) |
| 158 | return any( |
| 159 | o.getAttribute("PartName") == part_name |
| 160 | for o in dom.getElementsByTagName("Override") |
| 161 | ) |
| 162 | |
| 163 | |
| 164 | _COMMENT_RELS = [ |
| 165 | ("http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments", "comments.xml"), |
| 166 | ("http://schemas.microsoft.com/office/2011/relationships/commentsExtended", "commentsExtended.xml"), |
| 167 | ("http://schemas.microsoft.com/office/2016/09/relationships/commentsIds", "commentsIds.xml"), |
| 168 | ("http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible", "commentsExtensible.xml"), |
| 169 | ] |
| 170 | _COMMENT_OVERRIDES = [ |
| 171 | ("/word/comments.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"), |
| 172 | ("/word/commentsExtended.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml"), |
| 173 | ("/word/commentsIds.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsIds+xml"), |
| 174 | ("/word/commentsExtensible.xml", "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtensible+xml"), |
| 175 | ] |
| 176 | |
| 177 | |
| 178 | def _ensure_comment_relationships(unpacked_dir: Path) -> None: |
| 179 | rels_path = unpacked_dir / "word" / "_rels" / "document.xml.rels" |
| 180 | if not rels_path.exists(): |
| 181 | return |
| 182 | dom = defusedxml.minidom.parseString(rels_path.read_text(encoding="utf-8")) |
| 183 | root = dom.documentElement |
| 184 | comment_types = {rel_type for rel_type, _ in _COMMENT_RELS} |
| 185 | existing = set() |
| 186 | for rel in dom.getElementsByTagName("Relationship"): |
| 187 | if rel.getAttribute("Type") not in comment_types: |
| 188 | continue |
| 189 | part = opc_target( |
| 190 | rel.getAttribute("Target"), |
| 191 | "word/document.xml", |
| 192 | rel.getAttribute("TargetMode"), |
| 193 | ) |
| 194 | if part is not None: |
| 195 | existing.add(part) |
| 196 | next_rid = _get_next_rid(rels_path) |
| 197 | changed = False |
| 198 | for rel_type, target in _COMMENT_RELS: |
| 199 | if opc_target(target, "word/document.xml") in existing: |
| 200 | continue |
| 201 | rel = dom.createElement("Relationship") |
| 202 | rel.setAttribute("Id", f"rId{next_rid}") |
| 203 | rel.setAttribute("Type", rel_type) |
| 204 | rel.setAttribute("Target", target) |
| 205 | root.appendChild(rel) |
| 206 | next_rid += 1 |
| 207 | changed = True |
| 208 | if changed: |
| 209 | rels_path.write_bytes(dom.toxml(encoding="UTF-8")) |
| 210 | |
| 211 | |
| 212 | def _ensure_comment_content_types(unpacked_dir: Path) -> None: |
| 213 | ct_path = unpacked_dir / "[Content_Types].xml" |
| 214 | if not ct_path.exists(): |
| 215 | return |
| 216 | dom = defusedxml.minidom.parseString(ct_path.read_text(encoding="utf-8")) |
| 217 | root = dom.documentElement |
| 218 | existing = { |
| 219 | o.getAttribute("PartName") |
| 220 | for o in dom.getElementsByTagName("Override") |
| 221 | } |
| 222 | changed = False |
| 223 | for part_name, content_type in _COMMENT_OVERRIDES: |
| 224 | if part_name in existing: |
| 225 | continue |
| 226 | override = dom.createElement("Override") |
| 227 | override.setAttribute("PartName", part_name) |
| 228 | override.setAttribute("ContentType", content_type) |
| 229 | root.appendChild(override) |
| 230 | changed = True |
| 231 | if changed: |
| 232 | ct_path.write_bytes(dom.toxml(encoding="UTF-8")) |
| 233 | |
| 234 | |
| 235 | def add_comment( |
| 236 | unpacked_dir: Path | str, |
| 237 | text: str, |
| 238 | comment_id: int | None = None, |
| 239 | author: str = "Claude", |
| 240 | initials: str = "C", |
| 241 | parent_id: int | None = None, |
| 242 | raw: bool = False, |
| 243 | ) -> tuple[int, str, str]: |
| 244 | unpacked_dir = Path(unpacked_dir) |
| 245 | if not raw: |
| 246 | text = xml_escape(text) |
| 247 | author = xml_escape(author, {'"': """}) |
| 248 | initials = xml_escape(initials, {'"': """}) |
| 249 | word = unpacked_dir / "word" |
| 250 | if not word.exists(): |
| 251 | raise FileNotFoundError(f"{word} not found (not an unpacked .docx?)") |
| 252 | |
| 253 | comments = word / "comments.xml" |
| 254 | if comment_id is None: |
| 255 | comment_id = _next_comment_id(comments) |
| 256 | |
| 257 | parent_para = None |
| 258 | if parent_id is not None: |
| 259 | parent_para = _find_para_id(comments, parent_id) if comments.exists() else None |
| 260 | if not parent_para: |
| 261 | raise ValueError(f"parent comment {parent_id} not found") |
| 262 | |
| 263 | para_id, durable_id = _generate_hex_id(), _generate_hex_id() |
| 264 | ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 265 | |
| 266 | if not comments.exists(): |
| 267 | shutil.copy(TEMPLATE_DIR / "comments.xml", comments) |
| 268 | _ensure_comment_relationships(unpacked_dir) |
| 269 | _ensure_comment_content_types(unpacked_dir) |
| 270 | _append_xml( |
| 271 | comments, |
| 272 | "w:comments", |
| 273 | COMMENT_XML.format( |
| 274 | id=comment_id, author=author, date=ts, initials=initials, |
| 275 | para_id=para_id, text=text, |
| 276 | ), |
| 277 | ) |
| 278 | |
| 279 | ext = word / "commentsExtended.xml" |
| 280 | if not ext.exists(): |
| 281 | shutil.copy(TEMPLATE_DIR / "commentsExtended.xml", ext) |
| 282 | if parent_para is not None: |
| 283 | _append_xml( |
| 284 | ext, "w15:commentsEx", |
| 285 | f'<w15:commentEx w15:paraId="{para_id}" w15:paraIdParent="{parent_para}" w15:done="0"/>', |
| 286 | ) |
| 287 | else: |
| 288 | _append_xml( |
| 289 | ext, "w15:commentsEx", |
| 290 | f'<w15:commentEx w15:paraId="{para_id}" w15:done="0"/>', |
| 291 | ) |
| 292 | |
| 293 | ids = word / "commentsIds.xml" |
| 294 | if not ids.exists(): |
| 295 | shutil.copy(TEMPLATE_DIR / "commentsIds.xml", ids) |
| 296 | _append_xml( |
| 297 | ids, "w16cid:commentsIds", |
| 298 | f'<w16cid:commentId w16cid:paraId="{para_id}" w16cid:durableId="{durable_id}"/>', |
| 299 | ) |
| 300 | |
| 301 | extensible = word / "commentsExtensible.xml" |
| 302 | if not extensible.exists(): |
| 303 | shutil.copy(TEMPLATE_DIR / "commentsExtensible.xml", extensible) |
| 304 | _append_xml( |
| 305 | extensible, "w16cex:commentsExtensible", |
| 306 | f'<w16cex:commentExtensible w16cex:durableId="{durable_id}" w16cex:dateUtc="{ts}"/>', |
| 307 | ) |
| 308 | |
| 309 | action = "reply" if parent_id is not None else "comment" |
| 310 | return comment_id, para_id, f"Added {action} id={comment_id} (paraId={para_id})" |
| 311 | |
| 312 | |
| 313 | def main() -> None: |
| 314 | p = argparse.ArgumentParser(description="Add a comment to a DOCX (directory or .docx file).") |
| 315 | p.add_argument("input", help="Unpacked DOCX directory OR a .docx/.dotx file") |
| 316 | p.add_argument("text", help="Comment text (plain text; XML-escaped automatically)") |
| 317 | p.add_argument("--raw", action="store_true", |
| 318 | help="Treat text as pre-escaped XML (skip automatic escaping)") |
| 319 | p.add_argument("--id", type=int, dest="comment_id", |
| 320 | help="Comment ID (default: auto-assign as max existing + 1)") |
| 321 | p.add_argument("--author", default="Claude", help="Author name") |
| 322 | p.add_argument("--initials", default="C", help="Author initials") |
| 323 | p.add_argument("--parent", type=int, help="Parent comment ID (makes this a reply)") |
| 324 | p.add_argument("-o", "--output", |
| 325 | help="Output .docx path (only used when input is a .docx; default: overwrite input)") |
| 326 | args = p.parse_args() |
| 327 | |
| 328 | src = Path(args.input) |
| 329 | |
| 330 | try: |
| 331 | if src.is_dir(): |
| 332 | if args.output: |
| 333 | print("Warning: --output ignored for directory input", file=sys.stderr) |
| 334 | cid, _, msg = add_comment( |
| 335 | src, args.text, comment_id=args.comment_id, |
| 336 | author=args.author, initials=args.initials, |
| 337 | parent_id=args.parent, raw=args.raw, |
| 338 | ) |
| 339 | print(msg) |
| 340 | elif src.is_file() and src.suffix.lower() in (".docx", ".dotx"): |
| 341 | out = Path(args.output) if args.output else src |
| 342 | with tempfile.TemporaryDirectory() as tmp: |
| 343 | tmp_path = Path(tmp) |
| 344 | with zipfile.ZipFile(src) as zf: |
| 345 | _safe_extract(zf, tmp_path) |
| 346 | cid, _, msg = add_comment( |
| 347 | tmp_path, args.text, comment_id=args.comment_id, |
| 348 | author=args.author, initials=args.initials, |
| 349 | parent_id=args.parent, raw=args.raw, |
| 350 | ) |
| 351 | _rezip(tmp_path, out) |
| 352 | print(msg) |
| 353 | print(f"Wrote {out} (comment defined; add markers to word/document.xml to make it visible)") |
| 354 | else: |
| 355 | print(f"Error: {src} is neither a directory nor a .docx/.dotx file", file=sys.stderr) |
| 356 | sys.exit(1) |
| 357 | except (FileNotFoundError, ValueError, zipfile.BadZipFile, ExpatError) as e: |
| 358 | print(f"Error: {e}", file=sys.stderr) |
| 359 | sys.exit(1) |
| 360 | |
| 361 | if args.parent is not None: |
| 362 | print(REPLY_MARKER_TEMPLATE.format(pid=args.parent, cid=cid)) |
| 363 | else: |
| 364 | print(COMMENT_MARKER_TEMPLATE.format(cid=cid)) |
| 365 | |
| 366 | |
| 367 | if __name__ == "__main__": |
| 368 | main() |