read_docx_structure.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. #!/usr/bin/env python3
  2. """Deep DOCX structure analyzer.
  3. This script is the **primary** structure-truth implementation for the docx
  4. skill. It is intentionally not "a summarizer that needs dotnet to corroborate" —
  5. it parses the OOXML parts directly (stdlib only) and produces an independent,
  6. self-contained structure report covering:
  7. * parts inventory + Content-Types vs rels cross-check
  8. * relationship graph (document, headers, footers)
  9. * section graph with page geometry, header/footer references and titlePg
  10. * numbering chain (numId -> abstractNumId -> level definitions) plus usage
  11. * field topology (simple + complex fields, instruction text, dirty/locked)
  12. * bookmark topology (start/end pairing, orphan detection, reserved names)
  13. * hyperlink topology (internal anchors + external URLs resolved via rels)
  14. * comments topology (definitions, in-document ranges, parent links, orphans)
  15. * revisions topology (kinds, actors, date range)
  16. * styles inventory + cross-reference audit (defined/used/missing/contaminated)
  17. * direct-formatting contamination heatmap
  18. * a `diagnostics` array of categorized findings (template diagnosis aid)
  19. The dotnet `analyze` command remains useful as an **independent confirmation**
  20. shot (different parser, different runtime), but it is not the structure-truth
  21. oracle. This script is.
  22. Run:
  23. python3 read_docx_structure.py path/to/file.docx --json
  24. python3 read_docx_structure.py path/to/file.docx --section sections,numbering
  25. """
  26. from __future__ import annotations
  27. import argparse
  28. import json
  29. import re
  30. import sys
  31. import xml.etree.ElementTree as ET
  32. from collections import Counter, defaultdict
  33. from datetime import datetime
  34. from pathlib import Path
  35. from typing import Any, Dict, Iterable, List, Optional, Tuple
  36. from zipfile import ZipFile
  37. # -- namespaces ----------------------------------------------------------------
  38. NS = {
  39. "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
  40. "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
  41. "rel": "http://schemas.openxmlformats.org/package/2006/relationships",
  42. "ct": "http://schemas.openxmlformats.org/package/2006/content-types",
  43. "w14": "http://schemas.microsoft.com/office/word/2010/wordml",
  44. "w15": "http://schemas.microsoft.com/office/word/2012/wordml",
  45. }
  46. W = NS["w"]
  47. R = NS["r"]
  48. REL = NS["rel"]
  49. CT = NS["ct"]
  50. def qn(prefix: str, name: str) -> str:
  51. return f"{{{NS[prefix]}}}{name}"
  52. WVAL = qn("w", "val")
  53. WTYPE = qn("w", "type")
  54. WSTYLEID = qn("w", "styleId")
  55. WCUSTOM = qn("w", "customStyle")
  56. WDEFAULT = qn("w", "default")
  57. RID = qn("r", "id")
  58. WAUTHOR = qn("w", "author")
  59. WDATE = qn("w", "date")
  60. # -- XML helpers ---------------------------------------------------------------
  61. def load_xml(archive: ZipFile, entry_name: str) -> Optional[ET.Element]:
  62. try:
  63. with archive.open(entry_name) as handle:
  64. return ET.fromstring(handle.read())
  65. except KeyError:
  66. return None
  67. except ET.ParseError as exc:
  68. # Surface as diagnostic but do not crash the whole analysis.
  69. return ET.fromstring(f"<broken xmlns='urn:broken'>{exc}</broken>")
  70. def text_of(node: ET.Element) -> str:
  71. return "".join(part.text or "" for part in node.findall(".//w:t", NS)).strip()
  72. def attr(elem: ET.Element, name: str) -> Optional[str]:
  73. """Return attribute by prefixed-or-bare name."""
  74. return elem.get(name) or elem.get(name.split("}", 1)[-1] if "}" in name else name)
  75. def w_attr(elem: ET.Element, local: str) -> Optional[str]:
  76. return elem.get(qn("w", local)) or elem.get(local)
  77. # -- conversion helpers --------------------------------------------------------
  78. def twips_to_mm(value: Optional[str]) -> Optional[float]:
  79. if value is None:
  80. return None
  81. try:
  82. return round(int(value) / 1440.0 * 25.4, 2)
  83. except (TypeError, ValueError):
  84. return None
  85. # -- packaging layer -----------------------------------------------------------
  86. def parse_content_types(archive: ZipFile) -> Dict[str, Any]:
  87. elem = load_xml(archive, "[Content_Types].xml")
  88. if elem is None:
  89. return {"defaults": {}, "overrides": {}, "missing": True}
  90. defaults: Dict[str, str] = {}
  91. overrides: Dict[str, str] = {}
  92. for child in elem.findall(qn("ct", "Default")):
  93. defaults[child.get("Extension", "")] = child.get("ContentType", "")
  94. for child in elem.findall(qn("ct", "Override")):
  95. overrides[child.get("PartName", "")] = child.get("ContentType", "")
  96. return {"defaults": defaults, "overrides": overrides, "missing": False}
  97. def parse_rels(archive: ZipFile, rels_path: str) -> List[Dict[str, str]]:
  98. elem = load_xml(archive, rels_path)
  99. if elem is None:
  100. return []
  101. rels: List[Dict[str, str]] = []
  102. for child in elem.findall(qn("rel", "Relationship")):
  103. rels.append({
  104. "id": child.get("Id", ""),
  105. "type": child.get("Type", ""),
  106. "target": child.get("Target", ""),
  107. "targetMode": child.get("TargetMode", "Internal"),
  108. })
  109. return rels
  110. def collect_parts_inventory(archive: ZipFile) -> Dict[str, Any]:
  111. parts = []
  112. for info in archive.infolist():
  113. parts.append({
  114. "name": info.filename,
  115. "size": info.file_size,
  116. "compressed": info.compress_size,
  117. })
  118. return {
  119. "count": len(parts),
  120. "totalUncompressed": sum(p["size"] for p in parts),
  121. "items": parts,
  122. }
  123. # -- styles --------------------------------------------------------------------
  124. def parse_styles(styles_doc: Optional[ET.Element]) -> Dict[str, Any]:
  125. if styles_doc is None:
  126. return {"missing": True, "byId": {}, "defaults": {}}
  127. by_id: Dict[str, Dict[str, Any]] = {}
  128. defaults: Dict[str, str] = {}
  129. for style in styles_doc.findall(qn("w", "style")):
  130. style_id = w_attr(style, "styleId")
  131. if not style_id:
  132. continue
  133. name_node = style.find(qn("w", "name"))
  134. based_on = style.find(qn("w", "basedOn"))
  135. link = style.find(qn("w", "link"))
  136. next_style = style.find(qn("w", "next"))
  137. ppr = style.find(qn("w", "pPr"))
  138. outline_lvl = ppr.find(qn("w", "outlineLvl")) if ppr is not None else None
  139. num_pr = ppr.find(qn("w", "numPr")) if ppr is not None else None
  140. num_id = None
  141. if num_pr is not None:
  142. num_id_node = num_pr.find(qn("w", "numId"))
  143. if num_id_node is not None:
  144. num_id = w_attr(num_id_node, "val")
  145. info = {
  146. "styleId": style_id,
  147. "type": w_attr(style, "type"),
  148. "name": w_attr(name_node, "val") if name_node is not None else None,
  149. "basedOn": w_attr(based_on, "val") if based_on is not None else None,
  150. "linked": w_attr(link, "val") if link is not None else None,
  151. "next": w_attr(next_style, "val") if next_style is not None else None,
  152. "isDefault": w_attr(style, "default") == "1",
  153. "isCustom": w_attr(style, "customStyle") == "1",
  154. "outlineLvl": w_attr(outline_lvl, "val") if outline_lvl is not None else None,
  155. "numId": num_id,
  156. }
  157. if info["isDefault"] and info["type"]:
  158. defaults[info["type"]] = style_id
  159. by_id[style_id] = info
  160. return {"missing": False, "byId": by_id, "defaults": defaults}
  161. def style_inheritance_chain(styles: Dict[str, Any], style_id: str) -> List[str]:
  162. chain: List[str] = []
  163. seen = set()
  164. cursor = style_id
  165. while cursor and cursor not in seen:
  166. seen.add(cursor)
  167. chain.append(cursor)
  168. info = styles["byId"].get(cursor)
  169. if not info:
  170. break
  171. cursor = info.get("basedOn")
  172. return chain
  173. # -- numbering -----------------------------------------------------------------
  174. def parse_numbering(numbering_doc: Optional[ET.Element]) -> Dict[str, Any]:
  175. if numbering_doc is None:
  176. return {"missing": True, "abstractNums": {}, "nums": {}}
  177. abstract: Dict[str, Dict[str, Any]] = {}
  178. for an in numbering_doc.findall(qn("w", "abstractNum")):
  179. an_id = w_attr(an, "abstractNumId")
  180. multi = an.find(qn("w", "multiLevelType"))
  181. levels: List[Dict[str, Any]] = []
  182. for lvl in an.findall(qn("w", "lvl")):
  183. num_fmt = lvl.find(qn("w", "numFmt"))
  184. lvl_text = lvl.find(qn("w", "lvlText"))
  185. start = lvl.find(qn("w", "start"))
  186. p_style = lvl.find(qn("w", "pStyle"))
  187. levels.append({
  188. "ilvl": w_attr(lvl, "ilvl"),
  189. "numFmt": w_attr(num_fmt, "val") if num_fmt is not None else None,
  190. "lvlText": w_attr(lvl_text, "val") if lvl_text is not None else None,
  191. "start": w_attr(start, "val") if start is not None else None,
  192. "pStyle": w_attr(p_style, "val") if p_style is not None else None,
  193. })
  194. abstract[an_id or ""] = {
  195. "abstractNumId": an_id,
  196. "multiLevelType": w_attr(multi, "val") if multi is not None else None,
  197. "levels": levels,
  198. }
  199. nums: Dict[str, Dict[str, Any]] = {}
  200. for num in numbering_doc.findall(qn("w", "num")):
  201. num_id = w_attr(num, "numId")
  202. an_ref = num.find(qn("w", "abstractNumId"))
  203. overrides = []
  204. for ov in num.findall(qn("w", "lvlOverride")):
  205. overrides.append({"ilvl": w_attr(ov, "ilvl")})
  206. nums[num_id or ""] = {
  207. "numId": num_id,
  208. "abstractNumId": w_attr(an_ref, "val") if an_ref is not None else None,
  209. "lvlOverrides": overrides,
  210. }
  211. return {"missing": False, "abstractNums": abstract, "nums": nums}
  212. # -- comments ------------------------------------------------------------------
  213. def parse_comments(comments_doc: Optional[ET.Element]) -> List[Dict[str, Any]]:
  214. if comments_doc is None:
  215. return []
  216. items: List[Dict[str, Any]] = []
  217. for comment in comments_doc.findall(qn("w", "comment")):
  218. items.append({
  219. "id": w_attr(comment, "id"),
  220. "author": w_attr(comment, "author"),
  221. "initials": w_attr(comment, "initials"),
  222. "date": w_attr(comment, "date"),
  223. "text": text_of(comment),
  224. })
  225. return items
  226. def parse_comments_extended(doc: Optional[ET.Element]) -> List[Dict[str, Any]]:
  227. if doc is None:
  228. return []
  229. items: List[Dict[str, Any]] = []
  230. for entry in doc.findall(qn("w15", "commentEx")):
  231. items.append({
  232. "paraId": entry.get(qn("w15", "paraId")) or entry.get("paraId"),
  233. "paraIdParent": entry.get(qn("w15", "paraIdParent")) or entry.get("paraIdParent"),
  234. "done": (entry.get(qn("w15", "done")) or entry.get("done")) == "1",
  235. })
  236. return items
  237. # -- field state machine -------------------------------------------------------
  238. FIELD_KIND = re.compile(r"^\s*([A-Z]+)")
  239. def classify_field(instr: str) -> str:
  240. match = FIELD_KIND.match(instr.strip())
  241. return match.group(1) if match else "UNKNOWN"
  242. def collect_complex_fields(body: ET.Element) -> List[Dict[str, Any]]:
  243. """Walk body in document order pairing fldChar begin/separate/end."""
  244. out: List[Dict[str, Any]] = []
  245. stack: List[Dict[str, Any]] = []
  246. for run in body.iter(qn("w", "r")):
  247. fld_char = run.find(qn("w", "fldChar"))
  248. instr = run.find(qn("w", "instrText"))
  249. text = run.find(qn("w", "t"))
  250. if fld_char is not None:
  251. kind = w_attr(fld_char, "fldCharType")
  252. if kind == "begin":
  253. stack.append({
  254. "instr": "",
  255. "result": "",
  256. "dirty": w_attr(fld_char, "dirty") == "1",
  257. "locked": w_attr(fld_char, "fldLock") == "1",
  258. "phase": "instr",
  259. })
  260. elif kind == "separate" and stack:
  261. stack[-1]["phase"] = "result"
  262. elif kind == "end" and stack:
  263. completed = stack.pop()
  264. completed["kind"] = classify_field(completed["instr"])
  265. completed.pop("phase", None)
  266. if stack:
  267. # Field-in-field (rare); treat outer result as still being captured.
  268. stack[-1]["result"] += completed.get("result", "")
  269. out.append(completed)
  270. elif instr is not None and stack and stack[-1].get("phase") == "instr":
  271. stack[-1]["instr"] += instr.text or ""
  272. elif text is not None and stack and stack[-1].get("phase") == "result":
  273. stack[-1]["result"] += text.text or ""
  274. return out
  275. def collect_simple_fields(body: ET.Element) -> List[Dict[str, Any]]:
  276. out: List[Dict[str, Any]] = []
  277. for fld in body.iter(qn("w", "fldSimple")):
  278. instr = w_attr(fld, "instr") or ""
  279. out.append({
  280. "instr": instr.strip(),
  281. "kind": classify_field(instr),
  282. "dirty": w_attr(fld, "dirty") == "1",
  283. "result": text_of(fld),
  284. })
  285. return out
  286. # -- bookmarks -----------------------------------------------------------------
  287. def collect_bookmarks(body: ET.Element) -> Dict[str, Any]:
  288. starts: Dict[str, Dict[str, Any]] = {}
  289. ends_seen: List[str] = []
  290. paragraph_seq: List[ET.Element] = list(body.iter(qn("w", "p")))
  291. para_index_by_id = {id(p): idx for idx, p in enumerate(paragraph_seq)}
  292. def parent_paragraph_index(elem: ET.Element) -> Optional[int]:
  293. # Walk through the tree to find the enclosing <w:p>; ET has no parent
  294. # pointer, so we precomputed paragraph identity below.
  295. return None
  296. # Instead of walking ancestors we walk paragraphs and record bookmark anchors
  297. # encountered inside each paragraph. This still provides a correct paragraph-
  298. # span for any bookmark whose start/end are inside the body's paragraph tree.
  299. para_index: Dict[str, Dict[str, int]] = {}
  300. for idx, paragraph in enumerate(paragraph_seq):
  301. for bm in paragraph.iter(qn("w", "bookmarkStart")):
  302. bm_id = w_attr(bm, "id")
  303. if bm_id is not None:
  304. para_index.setdefault(bm_id, {})["startPara"] = idx
  305. for bm in paragraph.iter(qn("w", "bookmarkEnd")):
  306. bm_id = w_attr(bm, "id")
  307. if bm_id is not None:
  308. para_index.setdefault(bm_id, {})["endPara"] = idx
  309. for bm in body.iter(qn("w", "bookmarkStart")):
  310. bm_id = w_attr(bm, "id")
  311. name = w_attr(bm, "name") or ""
  312. starts[bm_id or ""] = {
  313. "id": bm_id,
  314. "name": name,
  315. "reserved": name.startswith("_"),
  316. "startPara": para_index.get(bm_id or "", {}).get("startPara"),
  317. }
  318. for bm in body.iter(qn("w", "bookmarkEnd")):
  319. bm_id = w_attr(bm, "id")
  320. ends_seen.append(bm_id or "")
  321. if bm_id and bm_id in starts:
  322. starts[bm_id]["endPara"] = para_index.get(bm_id, {}).get("endPara")
  323. end_counter = Counter(ends_seen)
  324. pairs: List[Dict[str, Any]] = []
  325. orphan_starts: List[Dict[str, Any]] = []
  326. for bm_id, info in starts.items():
  327. if end_counter.get(bm_id, 0) >= 1:
  328. pairs.append(info)
  329. else:
  330. orphan_starts.append(info)
  331. orphan_ends = [bm_id for bm_id in end_counter if bm_id not in starts]
  332. return {
  333. "pairs": pairs,
  334. "orphanStarts": orphan_starts,
  335. "orphanEnds": orphan_ends,
  336. }
  337. # -- hyperlinks ----------------------------------------------------------------
  338. def collect_hyperlinks(body: ET.Element, rels_by_id: Dict[str, Dict[str, str]]) -> List[Dict[str, Any]]:
  339. items: List[Dict[str, Any]] = []
  340. for hl in body.iter(qn("w", "hyperlink")):
  341. anchor = w_attr(hl, "anchor")
  342. rid = hl.get(RID)
  343. target_url = None
  344. target_mode = None
  345. if rid and rid in rels_by_id:
  346. target_url = rels_by_id[rid].get("target")
  347. target_mode = rels_by_id[rid].get("targetMode")
  348. items.append({
  349. "anchor": anchor,
  350. "rId": rid,
  351. "url": target_url,
  352. "external": target_mode == "External",
  353. "text": text_of(hl)[:200] or None,
  354. })
  355. return items
  356. # -- sections / page setup -----------------------------------------------------
  357. def parse_section(sect_pr: ET.Element) -> Dict[str, Any]:
  358. pg_sz = sect_pr.find(qn("w", "pgSz"))
  359. pg_mar = sect_pr.find(qn("w", "pgMar"))
  360. type_node = sect_pr.find(qn("w", "type"))
  361. cols = sect_pr.find(qn("w", "cols"))
  362. title_pg = sect_pr.find(qn("w", "titlePg"))
  363. line_num = sect_pr.find(qn("w", "lnNumType"))
  364. pg_borders = sect_pr.find(qn("w", "pgBorders"))
  365. headers = []
  366. footers = []
  367. for ref in sect_pr.findall(qn("w", "headerReference")):
  368. headers.append({"type": w_attr(ref, "type"), "rId": ref.get(RID)})
  369. for ref in sect_pr.findall(qn("w", "footerReference")):
  370. footers.append({"type": w_attr(ref, "type"), "rId": ref.get(RID)})
  371. page_size = None
  372. if pg_sz is not None:
  373. page_size = {
  374. "widthMm": twips_to_mm(w_attr(pg_sz, "w")),
  375. "heightMm": twips_to_mm(w_attr(pg_sz, "h")),
  376. "orient": w_attr(pg_sz, "orient") or "portrait",
  377. }
  378. margins = None
  379. if pg_mar is not None:
  380. margins = {
  381. side: twips_to_mm(w_attr(pg_mar, side))
  382. for side in ("top", "right", "bottom", "left", "header", "footer", "gutter")
  383. }
  384. return {
  385. "type": (w_attr(type_node, "val") if type_node is not None else None) or "nextPage",
  386. "pageSize": page_size,
  387. "margins": margins,
  388. "columns": (int(w_attr(cols, "num")) if cols is not None and (w_attr(cols, "num") or "").isdigit() else 1),
  389. "titlePg": title_pg is not None,
  390. "lineNumbering": line_num is not None,
  391. "pageBorders": pg_borders is not None,
  392. "headerReferences": headers,
  393. "footerReferences": footers,
  394. }
  395. # -- direct-formatting contamination ------------------------------------------
  396. NON_REF_PPR_CHILDREN = {
  397. qn("w", "rPr"), qn("w", "sectPr"),
  398. }
  399. ALLOWED_PPR_REF_CHILDREN = {qn("w", "pStyle"), qn("w", "numPr")}
  400. def paragraph_contamination(paragraph: ET.Element) -> Dict[str, int]:
  401. info = {"pPrDirect": 0, "rPrDirectRuns": 0, "totalRuns": 0}
  402. ppr = paragraph.find(qn("w", "pPr"))
  403. if ppr is not None:
  404. for child in list(ppr):
  405. if child.tag not in ALLOWED_PPR_REF_CHILDREN and child.tag not in NON_REF_PPR_CHILDREN:
  406. info["pPrDirect"] += 1
  407. # rPr inside pPr (paragraph-mark formatting) also counts as direct
  408. run_ppr = ppr.find(qn("w", "rPr"))
  409. if run_ppr is not None and len(list(run_ppr)) > 0:
  410. info["pPrDirect"] += 1
  411. for run in paragraph.findall(qn("w", "r")):
  412. info["totalRuns"] += 1
  413. rpr = run.find(qn("w", "rPr"))
  414. if rpr is not None:
  415. non_style = [c for c in list(rpr) if c.tag != qn("w", "rStyle")]
  416. if non_style:
  417. info["rPrDirectRuns"] += 1
  418. return info
  419. # -- main analyze --------------------------------------------------------------
  420. def analyze(path: Path) -> Dict[str, Any]:
  421. diagnostics: List[Dict[str, str]] = []
  422. def diag(severity: str, code: str, message: str, **extra: Any) -> None:
  423. item = {"severity": severity, "code": code, "message": message}
  424. item.update(extra)
  425. diagnostics.append(item)
  426. with ZipFile(path, "r") as archive:
  427. document = load_xml(archive, "word/document.xml")
  428. if document is None:
  429. raise RuntimeError("Not a valid DOCX: word/document.xml missing")
  430. body = document.find(qn("w", "body"))
  431. if body is None:
  432. raise RuntimeError("Document body missing")
  433. styles_doc = load_xml(archive, "word/styles.xml")
  434. numbering_doc = load_xml(archive, "word/numbering.xml")
  435. comments_doc = load_xml(archive, "word/comments.xml")
  436. comments_ext_doc = load_xml(archive, "word/commentsExtended.xml")
  437. footnotes_doc = load_xml(archive, "word/footnotes.xml")
  438. endnotes_doc = load_xml(archive, "word/endnotes.xml")
  439. settings_doc = load_xml(archive, "word/settings.xml")
  440. content_types = parse_content_types(archive)
  441. rels_doc = parse_rels(archive, "word/_rels/document.xml.rels")
  442. package_rels = parse_rels(archive, "_rels/.rels")
  443. rels_by_id = {r["id"]: r for r in rels_doc}
  444. styles = parse_styles(styles_doc)
  445. numbering = parse_numbering(numbering_doc)
  446. comments = parse_comments(comments_doc)
  447. comments_ext = parse_comments_extended(comments_ext_doc)
  448. # --- traverse body --------------------------------------------------
  449. paragraphs = list(body.iter(qn("w", "p")))
  450. tables = list(body.iter(qn("w", "tbl")))
  451. sect_prs = list(body.iter(qn("w", "sectPr")))
  452. drawings = list(body.iter(qn("w", "drawing")))
  453. used_para_styles: Counter = Counter()
  454. used_run_styles: Counter = Counter()
  455. numbered_paragraphs: List[Dict[str, Any]] = []
  456. contamination_total = {"pPrDirect": 0, "rPrDirectRuns": 0, "paragraphsDirty": 0, "totalRuns": 0}
  457. heading_paragraphs: List[Dict[str, Any]] = []
  458. para_ids: List[str] = []
  459. for index, paragraph in enumerate(paragraphs):
  460. ppr = paragraph.find(qn("w", "pPr"))
  461. style_node = ppr.find(qn("w", "pStyle")) if ppr is not None else None
  462. style_id = w_attr(style_node, "val") if style_node is not None else None
  463. if style_id:
  464. used_para_styles[style_id] += 1
  465. for run in paragraph.findall(qn("w", "r")):
  466. rpr = run.find(qn("w", "rPr"))
  467. if rpr is not None:
  468. rstyle = rpr.find(qn("w", "rStyle"))
  469. if rstyle is not None:
  470. rs_val = w_attr(rstyle, "val")
  471. if rs_val:
  472. used_run_styles[rs_val] += 1
  473. num_pr = ppr.find(qn("w", "numPr")) if ppr is not None else None
  474. if num_pr is not None:
  475. num_id_node = num_pr.find(qn("w", "numId"))
  476. ilvl_node = num_pr.find(qn("w", "ilvl"))
  477. numbered_paragraphs.append({
  478. "index": index,
  479. "numId": w_attr(num_id_node, "val") if num_id_node is not None else None,
  480. "ilvl": w_attr(ilvl_node, "val") if ilvl_node is not None else None,
  481. "styleId": style_id,
  482. })
  483. para_id = paragraph.get(qn("w14", "paraId"))
  484. if para_id:
  485. para_ids.append(para_id)
  486. cont = paragraph_contamination(paragraph)
  487. contamination_total["pPrDirect"] += cont["pPrDirect"]
  488. contamination_total["rPrDirectRuns"] += cont["rPrDirectRuns"]
  489. contamination_total["totalRuns"] += cont["totalRuns"]
  490. if cont["pPrDirect"] or cont["rPrDirectRuns"]:
  491. contamination_total["paragraphsDirty"] += 1
  492. text = text_of(paragraph)
  493. outline_lvl = None
  494. if style_id and style_id in styles["byId"]:
  495. outline_lvl = styles["byId"][style_id].get("outlineLvl")
  496. if outline_lvl is None and ppr is not None:
  497. outline_node = ppr.find(qn("w", "outlineLvl"))
  498. if outline_node is not None:
  499. outline_lvl = w_attr(outline_node, "val")
  500. heading_like = bool(style_id and (
  501. "heading" in style_id.lower() or style_id.lower() in {"title", "subtitle"}
  502. ))
  503. if text and (outline_lvl is not None or heading_like):
  504. heading_paragraphs.append({
  505. "paraIndex": index,
  506. "styleId": style_id,
  507. "outlineLvl": int(outline_lvl) if outline_lvl and str(outline_lvl).isdigit() else None,
  508. "text": text[:240],
  509. })
  510. # --- sections -------------------------------------------------------
  511. sections: List[Dict[str, Any]] = []
  512. for sect_index, sect_pr in enumerate(sect_prs, start=1):
  513. entry = parse_section(sect_pr)
  514. entry["index"] = sect_index
  515. sections.append(entry)
  516. # --- header/footer parts via rels ----------------------------------
  517. header_footer_parts = []
  518. for rel in rels_doc:
  519. if rel["type"].endswith("/header") or rel["type"].endswith("/footer"):
  520. target = rel["target"]
  521. if not target.startswith("/"):
  522. full = f"word/{target.lstrip('./')}"
  523. else:
  524. full = target.lstrip("/")
  525. part_xml = load_xml(archive, full)
  526. if part_xml is None:
  527. diag("error", "missing-header-footer-part",
  528. f"rel {rel['id']} -> {target} but part not found", target=target)
  529. continue
  530. paragraphs_in_part = list(part_xml.iter(qn("w", "p")))
  531. simple_in_part = collect_simple_fields(part_xml)
  532. complex_in_part = collect_complex_fields(part_xml)
  533. part_fields = simple_in_part + complex_in_part
  534. images_in_part = sum(1 for _ in part_xml.iter(qn("w", "drawing")))
  535. hyperlinks_in_part = sum(1 for _ in part_xml.iter(qn("w", "hyperlink")))
  536. header_footer_parts.append({
  537. "kind": "header" if rel["type"].endswith("/header") else "footer",
  538. "rId": rel["id"],
  539. "target": target,
  540. "paragraphs": len(paragraphs_in_part),
  541. "fields": len(part_fields),
  542. "fieldKinds": dict(Counter(f["kind"] for f in part_fields)),
  543. "drawings": images_in_part,
  544. "hyperlinks": hyperlinks_in_part,
  545. })
  546. # Cross-check: every header/footerReference in any section MUST resolve.
  547. ref_rids = set()
  548. for sect in sections:
  549. for ref in sect["headerReferences"] + sect["footerReferences"]:
  550. rid = ref.get("rId")
  551. if rid:
  552. ref_rids.add(rid)
  553. if rid not in rels_by_id:
  554. diag("error", "section-ref-broken",
  555. f"section {sect['index']} references rId {rid} but rels has no such id",
  556. sectionIndex=sect["index"], rId=rid)
  557. # --- numbering analysis --------------------------------------------
  558. num_usage: Counter = Counter()
  559. num_per_level: Dict[Tuple[str, str], int] = defaultdict(int)
  560. for entry in numbered_paragraphs:
  561. nid = entry.get("numId") or ""
  562. num_usage[nid] += 1
  563. ilvl = entry.get("ilvl") or "0"
  564. num_per_level[(nid, ilvl)] += 1
  565. numbering_usage = {
  566. "perNumId": dict(num_usage),
  567. "perNumIdLevel": [
  568. {"numId": k[0], "ilvl": k[1], "paragraphs": v}
  569. for k, v in sorted(num_per_level.items())
  570. ],
  571. }
  572. for nid in num_usage:
  573. if nid not in numbering["nums"]:
  574. diag("error", "numbering-numid-missing",
  575. f"numId {nid} used in body but not defined in numbering.xml",
  576. numId=nid)
  577. else:
  578. an_id = numbering["nums"][nid].get("abstractNumId")
  579. if an_id and an_id not in numbering["abstractNums"]:
  580. diag("error", "numbering-abstractnum-missing",
  581. f"numId {nid} -> abstractNumId {an_id} (definition missing)",
  582. numId=nid, abstractNumId=an_id)
  583. for nid, info in numbering["nums"].items():
  584. if nid not in num_usage:
  585. diag("info", "numbering-numid-unused",
  586. f"numId {nid} defined in numbering.xml but not referenced in document body",
  587. numId=nid)
  588. # --- styles audit ---------------------------------------------------
  589. defined_ids = set(styles["byId"].keys())
  590. referenced_para_styles = set(used_para_styles)
  591. referenced_run_styles = set(used_run_styles)
  592. # styles linked from numbering pStyle pull
  593. for an in numbering["abstractNums"].values():
  594. for lvl in an["levels"]:
  595. if lvl.get("pStyle"):
  596. referenced_para_styles.add(lvl["pStyle"])
  597. all_referenced = referenced_para_styles | referenced_run_styles
  598. missing_styles = sorted(s for s in all_referenced if s not in defined_ids)
  599. for s in missing_styles:
  600. diag("error", "style-missing",
  601. f"style '{s}' is referenced but not defined in styles.xml",
  602. styleId=s)
  603. unused_defined = sorted(s for s in defined_ids if s not in all_referenced)
  604. heading_outline_audit = []
  605. for sid, info in styles["byId"].items():
  606. name = (info.get("name") or "").lower()
  607. if "heading" in (sid.lower() + name) and info.get("outlineLvl") is None:
  608. heading_outline_audit.append(sid)
  609. diag("warn", "heading-style-without-outline",
  610. f"heading-like style '{sid}' has no <w:outlineLvl/>; TOC and nav pane will misbehave",
  611. styleId=sid)
  612. # --- references -----------------------------------------------------
  613. complex_fields = collect_complex_fields(body)
  614. simple_fields = collect_simple_fields(body)
  615. all_fields = simple_fields + complex_fields
  616. field_kinds = Counter(f["kind"] for f in all_fields)
  617. dirty_fields = sum(1 for f in all_fields if f.get("dirty"))
  618. bookmarks = collect_bookmarks(body)
  619. if bookmarks["orphanStarts"]:
  620. diag("warn", "bookmark-orphan-start",
  621. f"{len(bookmarks['orphanStarts'])} bookmarkStart without matching bookmarkEnd",
  622. ids=[b.get("id") for b in bookmarks["orphanStarts"]])
  623. if bookmarks["orphanEnds"]:
  624. diag("warn", "bookmark-orphan-end",
  625. f"{len(bookmarks['orphanEnds'])} bookmarkEnd without matching bookmarkStart",
  626. ids=bookmarks["orphanEnds"])
  627. hyperlinks = collect_hyperlinks(body, rels_by_id)
  628. for hl in hyperlinks:
  629. if hl["rId"] and hl["url"] is None:
  630. diag("error", "hyperlink-rel-broken",
  631. f"hyperlink references rId {hl['rId']} but rel target missing",
  632. rId=hl["rId"])
  633. # --- comments topology ---------------------------------------------
  634. comment_starts = list(body.iter(qn("w", "commentRangeStart")))
  635. comment_ends = list(body.iter(qn("w", "commentRangeEnd")))
  636. comment_refs = list(body.iter(qn("w", "commentReference")))
  637. comment_ids_in_body = {w_attr(c, "id") for c in comment_starts}
  638. comment_ids_defined = {c["id"] for c in comments}
  639. comment_orphan_in_body = sorted(comment_ids_in_body - comment_ids_defined)
  640. comment_orphan_in_defs = sorted(comment_ids_defined - comment_ids_in_body)
  641. for cid in comment_orphan_in_body:
  642. diag("error", "comment-id-undefined",
  643. f"commentRangeStart id={cid} not defined in comments.xml",
  644. commentId=cid)
  645. for cid in comment_orphan_in_defs:
  646. diag("info", "comment-defined-not-anchored",
  647. f"comment {cid} defined but no commentRangeStart in document body",
  648. commentId=cid)
  649. # --- revisions ------------------------------------------------------
  650. revision_kinds = [
  651. "ins", "del", "moveFrom", "moveTo",
  652. "cellIns", "cellDel", "cellMerge",
  653. "rPrChange", "pPrChange", "tblPrChange",
  654. "trPrChange", "tcPrChange", "sectPrChange", "numberingChange",
  655. ]
  656. revision_counts: Dict[str, int] = {}
  657. revision_actors: Counter = Counter()
  658. revision_dates: List[str] = []
  659. for kind in revision_kinds:
  660. elems = list(body.iter(qn("w", kind)))
  661. revision_counts[kind] = len(elems)
  662. for el in elems:
  663. author = el.get(WAUTHOR)
  664. if author:
  665. revision_actors[author] += 1
  666. date = el.get(WDATE)
  667. if date:
  668. revision_dates.append(date)
  669. date_min = min(revision_dates) if revision_dates else None
  670. date_max = max(revision_dates) if revision_dates else None
  671. # --- footnotes / endnotes ------------------------------------------
  672. def count_notes(doc: Optional[ET.Element], tag: str) -> int:
  673. if doc is None:
  674. return 0
  675. return sum(1 for n in doc.findall(qn("w", tag))
  676. if w_attr(n, "type") not in {"separator", "continuationSeparator"})
  677. footnotes_count = count_notes(footnotes_doc, "footnote")
  678. endnotes_count = count_notes(endnotes_doc, "endnote")
  679. # --- settings flags relevant to structure --------------------------
  680. settings_flags: Dict[str, Any] = {}
  681. if settings_doc is not None:
  682. for flag in ("trackChanges", "evenAndOddHeaders", "mirrorMargins",
  683. "updateFields", "compatSetting", "footnotePr", "endnotePr"):
  684. node = settings_doc.find(qn("w", flag))
  685. settings_flags[flag] = node is not None
  686. # --- packaging audit ------------------------------------------------
  687. overrides = content_types["overrides"]
  688. rel_targets = set()
  689. for rel in rels_doc:
  690. if rel["targetMode"] == "Internal":
  691. target = rel["target"]
  692. full = "word/" + target.lstrip("./") if not target.startswith("/") else target.lstrip("/")
  693. rel_targets.add(full)
  694. overrides_paths = {p.lstrip("/") for p in overrides.keys()}
  695. for tgt in rel_targets:
  696. if tgt not in overrides_paths and tgt + "" not in overrides_paths:
  697. # allow non-override parts (e.g. images, fonts handled by Default content type)
  698. pass
  699. # ------------------------------------------------------------------
  700. return {
  701. "file": str(path),
  702. "summary": {
  703. "paragraphs": len(paragraphs),
  704. "tables": len(tables),
  705. "drawings": len(drawings),
  706. "sections": len(sections),
  707. "definedStyles": len(styles["byId"]),
  708. "fields": len(all_fields),
  709. "bookmarks": len(bookmarks["pairs"]) + len(bookmarks["orphanStarts"]),
  710. "hyperlinks": len(hyperlinks),
  711. "comments": len(comments),
  712. "footnotes": footnotes_count,
  713. "endnotes": endnotes_count,
  714. "diagnostics": len(diagnostics),
  715. },
  716. "packaging": {
  717. "contentTypes": content_types,
  718. "packageRels": package_rels,
  719. "documentRels": rels_doc,
  720. "parts": collect_parts_inventory(archive),
  721. },
  722. "sections": sections,
  723. "headerFooterParts": header_footer_parts,
  724. "styles": {
  725. "byId": styles["byId"],
  726. "defaults": styles["defaults"],
  727. "usedParagraphStyles": used_para_styles.most_common(),
  728. "usedRunStyles": used_run_styles.most_common(),
  729. "missingReferenced": missing_styles,
  730. "definedButUnused": unused_defined,
  731. "headingsWithoutOutlineLvl": heading_outline_audit,
  732. "missing": styles["missing"],
  733. },
  734. "numbering": {
  735. "abstractNums": numbering["abstractNums"],
  736. "nums": numbering["nums"],
  737. "usage": numbering_usage,
  738. "missing": numbering["missing"],
  739. },
  740. "headings": heading_paragraphs,
  741. "fields": {
  742. "simple": simple_fields,
  743. "complex": complex_fields,
  744. "kindCounts": dict(field_kinds),
  745. "kindCountsAllParts": dict(
  746. field_kinds + sum(
  747. (Counter(p.get("fieldKinds", {})) for p in header_footer_parts),
  748. Counter(),
  749. )
  750. ),
  751. "dirty": dirty_fields,
  752. },
  753. "bookmarks": bookmarks,
  754. "hyperlinks": hyperlinks,
  755. "comments": {
  756. "definitions": comments,
  757. "extended": comments_ext,
  758. "rangeStartsInBody": len(comment_starts),
  759. "rangeEndsInBody": len(comment_ends),
  760. "referencesInBody": len(comment_refs),
  761. "orphansInBody": comment_orphan_in_body,
  762. "definedNotAnchored": comment_orphan_in_defs,
  763. },
  764. "revisions": {
  765. "counts": revision_counts,
  766. "actors": dict(revision_actors),
  767. "dateRange": {"min": date_min, "max": date_max},
  768. },
  769. "contamination": {
  770. **contamination_total,
  771. "paragraphTotal": len(paragraphs),
  772. "dirtyRatio": round(
  773. contamination_total["paragraphsDirty"] / len(paragraphs), 4
  774. ) if paragraphs else 0.0,
  775. },
  776. "settingsFlags": settings_flags,
  777. "diagnostics": diagnostics,
  778. }
  779. # -- text rendering ------------------------------------------------------------
  780. def render_text(report: Dict[str, Any]) -> str:
  781. out: List[str] = []
  782. s = report["summary"]
  783. out.append(f"File: {report['file']}")
  784. out.append(f"Paragraphs: {s['paragraphs']} Tables: {s['tables']} Drawings: {s['drawings']}")
  785. out.append(f"Sections: {s['sections']} Defined styles: {s['definedStyles']}")
  786. out.append(
  787. f"Fields: {s['fields']} Bookmarks: {s['bookmarks']} Hyperlinks: {s['hyperlinks']}"
  788. )
  789. out.append(
  790. f"Comments: {s['comments']} Footnotes: {s['footnotes']} Endnotes: {s['endnotes']}"
  791. )
  792. out.append(f"Diagnostics: {s['diagnostics']}")
  793. out.append("")
  794. out.append("Sections:")
  795. for sect in report["sections"]:
  796. margins = sect.get("margins") or {}
  797. page = sect.get("pageSize") or {}
  798. out.append(
  799. f" #{sect['index']} type={sect['type']} "
  800. f"page={page.get('widthMm')}x{page.get('heightMm')}mm "
  801. f"margins(top/right/bottom/left)={margins.get('top')}/{margins.get('right')}/{margins.get('bottom')}/{margins.get('left')} "
  802. f"titlePg={sect['titlePg']} cols={sect['columns']}"
  803. )
  804. for ref in sect["headerReferences"]:
  805. out.append(f" header[{ref['type']}] -> {ref['rId']}")
  806. for ref in sect["footerReferences"]:
  807. out.append(f" footer[{ref['type']}] -> {ref['rId']}")
  808. if report["headerFooterParts"]:
  809. out.append("Header/footer parts:")
  810. for p in report["headerFooterParts"]:
  811. out.append(
  812. f" {p['kind']:<6} rId={p['rId']:<6} target={p['target']} "
  813. f"paragraphs={p['paragraphs']} fields={p['fields']} drawings={p['drawings']}"
  814. )
  815. out.append("")
  816. out.append("Styles audit:")
  817. out.append(f" used paragraph styles: {len(report['styles']['usedParagraphStyles'])}")
  818. out.append(f" used run styles: {len(report['styles']['usedRunStyles'])}")
  819. out.append(f" missing referenced: {report['styles']['missingReferenced']}")
  820. out.append(f" defined-but-unused: {len(report['styles']['definedButUnused'])}")
  821. out.append(f" headings missing outlineLvl: {report['styles']['headingsWithoutOutlineLvl']}")
  822. out.append("")
  823. out.append("Numbering:")
  824. out.append(f" abstractNums: {len(report['numbering']['abstractNums'])}")
  825. out.append(f" nums: {len(report['numbering']['nums'])}")
  826. out.append(f" numbered paragraphs by numId: {report['numbering']['usage']['perNumId']}")
  827. out.append("")
  828. out.append("Field kinds: " + ", ".join(f"{k}={v}" for k, v in report["fields"]["kindCounts"].items()))
  829. out.append(f"Dirty fields: {report['fields']['dirty']}")
  830. out.append("")
  831. out.append("Comments:")
  832. out.append(
  833. f" definitions={len(report['comments']['definitions'])} "
  834. f"rangeStartsInBody={report['comments']['rangeStartsInBody']} "
  835. f"orphansInBody={report['comments']['orphansInBody']}"
  836. )
  837. out.append("")
  838. out.append("Contamination:")
  839. c = report["contamination"]
  840. out.append(
  841. f" paragraphsDirty={c['paragraphsDirty']}/{c['paragraphTotal']} "
  842. f"({c['dirtyRatio']*100:.1f}%) pPrDirect={c['pPrDirect']} rPrDirectRuns={c['rPrDirectRuns']}"
  843. )
  844. out.append("")
  845. out.append("Diagnostics:")
  846. if not report["diagnostics"]:
  847. out.append(" (none)")
  848. for d in report["diagnostics"]:
  849. out.append(f" [{d['severity']}] {d['code']}: {d['message']}")
  850. return "\n".join(out)
  851. # -- CLI -----------------------------------------------------------------------
  852. SECTION_KEYS = {
  853. "summary", "packaging", "sections", "headerFooterParts", "styles",
  854. "numbering", "headings", "fields", "bookmarks", "hyperlinks",
  855. "comments", "revisions", "contamination", "settingsFlags", "diagnostics",
  856. }
  857. def main(argv: Optional[List[str]] = None) -> int:
  858. parser = argparse.ArgumentParser(
  859. description=(
  860. "Deep DOCX structure analyzer. Primary structure-truth implementation; "
  861. "no dotnet required."
  862. )
  863. )
  864. parser.add_argument("input_path", help="Path to the .docx file")
  865. parser.add_argument("--json", action="store_true", help="Emit JSON instead of text")
  866. parser.add_argument(
  867. "--section", default="",
  868. help=(
  869. "Comma-separated subset of top-level keys to include. "
  870. "Allowed: " + ",".join(sorted(SECTION_KEYS))
  871. ),
  872. )
  873. args = parser.parse_args(argv)
  874. input_path = Path(args.input_path).expanduser().resolve()
  875. if not input_path.exists():
  876. raise RuntimeError(f"Input file does not exist: {input_path}")
  877. if input_path.suffix.lower() != ".docx":
  878. raise RuntimeError("read_docx_structure.py currently supports .docx only")
  879. report = analyze(input_path)
  880. if args.section:
  881. wanted = {s.strip() for s in args.section.split(",") if s.strip()}
  882. unknown = wanted - SECTION_KEYS
  883. if unknown:
  884. raise RuntimeError(f"Unknown --section keys: {sorted(unknown)}")
  885. report = {k: v for k, v in report.items() if k in wanted or k == "file"}
  886. if args.json:
  887. print(json.dumps(report, ensure_ascii=False, indent=2))
  888. else:
  889. print(render_text(report))
  890. return 0
  891. if __name__ == "__main__":
  892. try:
  893. raise SystemExit(main())
  894. except Exception as exc: # pragma: no cover - CLI error path
  895. print(f"read_docx_structure.py failed: {exc}", file=sys.stderr)
  896. raise SystemExit(1)