extract_docx_text.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. """Content-truth extractor for DOCX files.
  2. This script lifts ``READ_CONTENT`` from "concatenated paragraph text" to a real
  3. content-truth view. It walks ``word/document.xml`` (and the supporting parts:
  4. ``footnotes.xml``, ``endnotes.xml``, ``comments.xml``, ``header*.xml``,
  5. ``footer*.xml`` plus the document relationships) and emits the body content in
  6. reading order while keeping side channels addressable.
  7. Output formats
  8. ==============
  9. ``--format text`` (default, back-compatible with the previous behaviour but
  10. richer):
  11. * one paragraph per line, with hyperlink targets shown as ``text (→ url)``
  12. * footnote / endnote / comment markers shown inline as ``[fn:1]`` / ``[en:1]``
  13. / ``[cmt:0]``
  14. * tables rendered as ``cell | cell`` rows, one row per line
  15. * tracked changes resolved by ``--revisions`` (default ``accept``: insertions
  16. in, deletions out)
  17. * a trailing "FOOTNOTES", "ENDNOTES", "COMMENTS", "HEADERS", "FOOTERS" and
  18. "TEXT BOXES" section when those parts contain anything. These can be turned
  19. off individually with ``--no-*`` flags.
  20. ``--format json`` produces a structured document suitable for downstream
  21. consumers (RAG, audit, diff). Schema (top-level keys):
  22. * ``file`` — absolute path
  23. * ``options`` — the options actually applied
  24. * ``body`` — list of block dicts (``paragraph`` or ``table``) in reading order
  25. * ``footnotes`` / ``endnotes`` / ``comments`` — lists with id, author, text
  26. * ``hyperlinks`` — every external hyperlink reference with ``text`` + ``target``
  27. * ``textboxes`` — text inside ``w:txbxContent`` / drawing shapes
  28. * ``headers`` / ``footers`` — text per header/footer part with ``role`` (``default``/
  29. ``first``/``even``)
  30. * ``revisions`` — ``{policy, insertions, deletions, retainedInsertions,
  31. retainedDeletions}``
  32. * ``warnings`` — anything we deliberately did not silently drop
  33. ``--format markdown`` produces a lightweight, human-readable Markdown digest.
  34. The script is stdlib-only (zipfile + xml.etree) so it has no dependency on
  35. ``python-docx`` and never silently degrades when that package is missing.
  36. """
  37. from __future__ import annotations
  38. import argparse
  39. import json
  40. import sys
  41. import xml.etree.ElementTree as ET
  42. from dataclasses import dataclass, field
  43. from pathlib import Path
  44. from typing import Iterable, Optional
  45. from zipfile import ZipFile
  46. W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
  47. R_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
  48. PKG_REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
  49. V_NS = "urn:schemas-microsoft-com:vml"
  50. WPS_NS = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape"
  51. MC_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006"
  52. NS = {
  53. "w": W_NS,
  54. "r": R_NS,
  55. "v": V_NS,
  56. "wps": WPS_NS,
  57. "mc": MC_NS,
  58. "pkg": PKG_REL_NS,
  59. }
  60. W_TAGS = {
  61. "p": f"{{{W_NS}}}p",
  62. "tbl": f"{{{W_NS}}}tbl",
  63. "tr": f"{{{W_NS}}}tr",
  64. "tc": f"{{{W_NS}}}tc",
  65. "r": f"{{{W_NS}}}r",
  66. "t": f"{{{W_NS}}}t",
  67. "delText": f"{{{W_NS}}}delText",
  68. "tab": f"{{{W_NS}}}tab",
  69. "br": f"{{{W_NS}}}br",
  70. "ins": f"{{{W_NS}}}ins",
  71. "del": f"{{{W_NS}}}del",
  72. "hyperlink": f"{{{W_NS}}}hyperlink",
  73. "footnoteReference": f"{{{W_NS}}}footnoteReference",
  74. "endnoteReference": f"{{{W_NS}}}endnoteReference",
  75. "commentRangeStart": f"{{{W_NS}}}commentRangeStart",
  76. "commentRangeEnd": f"{{{W_NS}}}commentRangeEnd",
  77. "commentReference": f"{{{W_NS}}}commentReference",
  78. "fldSimple": f"{{{W_NS}}}fldSimple",
  79. "instrText": f"{{{W_NS}}}instrText",
  80. "txbxContent": f"{{{W_NS}}}txbxContent",
  81. "drawing": f"{{{W_NS}}}drawing",
  82. "pStyle": f"{{{W_NS}}}pStyle",
  83. "pPr": f"{{{W_NS}}}pPr",
  84. "rPr": f"{{{W_NS}}}rPr",
  85. "sectPr": f"{{{W_NS}}}sectPr",
  86. "type": f"{{{W_NS}}}type",
  87. "headerReference": f"{{{W_NS}}}headerReference",
  88. "footerReference": f"{{{W_NS}}}footerReference",
  89. }
  90. W_ATTR = {
  91. "val": f"{{{W_NS}}}val",
  92. "id": f"{{{W_NS}}}id",
  93. "author": f"{{{W_NS}}}author",
  94. "date": f"{{{W_NS}}}date",
  95. "type": f"{{{W_NS}}}type",
  96. "anchor": f"{{{W_NS}}}anchor",
  97. "tooltip": f"{{{W_NS}}}tooltip",
  98. "history": f"{{{W_NS}}}history",
  99. "fldCharType": f"{{{W_NS}}}fldCharType",
  100. }
  101. R_ATTR = {
  102. "id": f"{{{R_NS}}}id",
  103. }
  104. # ---------------------------------------------------------------------------
  105. # Options
  106. # ---------------------------------------------------------------------------
  107. @dataclass
  108. class Options:
  109. fmt: str = "text"
  110. revisions: str = "accept" # accept | reject | raw
  111. include_footnotes: bool = True
  112. include_endnotes: bool = True
  113. include_comments: bool = True
  114. include_hyperlinks: bool = True
  115. include_textboxes: bool = True
  116. include_headers: bool = False
  117. include_footers: bool = False
  118. inline_comment_marker: bool = True
  119. def to_dict(self) -> dict:
  120. return {
  121. "format": self.fmt,
  122. "revisions": self.revisions,
  123. "includeFootnotes": self.include_footnotes,
  124. "includeEndnotes": self.include_endnotes,
  125. "includeComments": self.include_comments,
  126. "includeHyperlinks": self.include_hyperlinks,
  127. "includeTextboxes": self.include_textboxes,
  128. "includeHeaders": self.include_headers,
  129. "includeFooters": self.include_footers,
  130. }
  131. # ---------------------------------------------------------------------------
  132. # Low-level helpers
  133. # ---------------------------------------------------------------------------
  134. def _read_xml(archive: ZipFile, name: str) -> Optional[ET.Element]:
  135. try:
  136. with archive.open(name) as handle:
  137. return ET.fromstring(handle.read())
  138. except KeyError:
  139. return None
  140. except ET.ParseError:
  141. return None
  142. def _wval(node: Optional[ET.Element], default: Optional[str] = None) -> Optional[str]:
  143. if node is None:
  144. return default
  145. return node.get(W_ATTR["val"]) or node.get("val") or default
  146. def _strip_alternate_content(root: ET.Element) -> None:
  147. """Resolve mc:AlternateContent so we walk the WML choice (preferred) and skip
  148. fallback duplicates. Without this, drawing text inside ``mc:Fallback`` gets
  149. counted twice. Loops until no AlternateContent remains (handles nesting)."""
  150. while True:
  151. parent_map = {child: parent for parent in root.iter() for child in parent}
  152. targets = [el for el in root.iter() if el.tag == f"{{{MC_NS}}}AlternateContent"]
  153. if not targets:
  154. return
  155. for ac in targets:
  156. parent = parent_map.get(ac)
  157. if parent is None:
  158. continue
  159. idx = list(parent).index(ac)
  160. choice = ac.find(f"{{{MC_NS}}}Choice")
  161. chosen = choice if choice is not None else ac.find(f"{{{MC_NS}}}Fallback")
  162. replacements = list(chosen) if chosen is not None else []
  163. parent.remove(ac)
  164. for offset, child in enumerate(replacements):
  165. parent.insert(idx + offset, child)
  166. def _load_relationships(archive: ZipFile, part_path: str) -> dict[str, dict]:
  167. """Return {rId: {"target": str, "type": str, "mode": str}} for a given part."""
  168. rel_path = _rel_path_for(part_path)
  169. root = _read_xml(archive, rel_path)
  170. if root is None:
  171. return {}
  172. rels: dict[str, dict] = {}
  173. for rel in root.findall(f"{{{PKG_REL_NS}}}Relationship"):
  174. rid = rel.get("Id")
  175. if not rid:
  176. continue
  177. rels[rid] = {
  178. "target": rel.get("Target") or "",
  179. "type": rel.get("Type") or "",
  180. "mode": rel.get("TargetMode") or "Internal",
  181. }
  182. return rels
  183. def _rel_path_for(part_path: str) -> str:
  184. parts = part_path.rsplit("/", 1)
  185. if len(parts) == 1:
  186. return f"_rels/{part_path}.rels"
  187. return f"{parts[0]}/_rels/{parts[1]}.rels"
  188. # ---------------------------------------------------------------------------
  189. # Run-level extraction (revisions, hyperlinks, footnotes, comments)
  190. # ---------------------------------------------------------------------------
  191. @dataclass
  192. class ParagraphRun:
  193. text: str
  194. revision: str = "none" # none | ins | del
  195. in_hyperlink: Optional[str] = None # hyperlink id key (for grouping)
  196. @dataclass
  197. class Hyperlink:
  198. text: str
  199. target: str
  200. anchor: Optional[str] = None
  201. tooltip: Optional[str] = None
  202. @dataclass
  203. class FieldEvent:
  204. kind: str # field-begin | field-instr | field-end
  205. text: str = ""
  206. @dataclass
  207. class ParagraphBlock:
  208. style: Optional[str]
  209. style_name: Optional[str]
  210. text: str
  211. runs: list[dict]
  212. hyperlinks: list[Hyperlink] = field(default_factory=list)
  213. footnote_refs: list[str] = field(default_factory=list)
  214. endnote_refs: list[str] = field(default_factory=list)
  215. comment_refs: list[str] = field(default_factory=list)
  216. fields: list[str] = field(default_factory=list)
  217. @dataclass
  218. class TableBlock:
  219. rows: list[list[ParagraphBlock]]
  220. @dataclass
  221. class ExtractionResult:
  222. body: list[object]
  223. footnotes: list[dict]
  224. endnotes: list[dict]
  225. comments: list[dict]
  226. hyperlinks: list[Hyperlink]
  227. textboxes: list[dict]
  228. headers: list[dict]
  229. footers: list[dict]
  230. revisions: dict
  231. warnings: list[str]
  232. style_names: dict[str, str]
  233. # ---------------------------------------------------------------------------
  234. # Paragraph walker
  235. # ---------------------------------------------------------------------------
  236. class ParagraphWalker:
  237. """Walk a ``w:p`` element and emit a structured ``ParagraphBlock``.
  238. The walker honours the requested revision policy and reports inline side
  239. channels (hyperlinks, footnote/endnote/comment references) via the
  240. paragraph's lists. Text from drawing shapes / text boxes is *not* inlined
  241. here — the caller harvests those globally so they are addressable on their
  242. own.
  243. """
  244. def __init__(self, options: Options, rels: dict[str, dict], style_names: dict[str, str]):
  245. self.options = options
  246. self.rels = rels
  247. self.style_names = style_names
  248. # ------------------------------------------------------------------ runs
  249. def _emit_text(self, runs: list[ParagraphRun], text: str, revision: str, link_key: Optional[str]) -> None:
  250. if text == "":
  251. return
  252. # merge with previous run when revision/link unchanged
  253. if runs and runs[-1].revision == revision and runs[-1].in_hyperlink == link_key:
  254. runs[-1].text += text
  255. return
  256. runs.append(ParagraphRun(text=text, revision=revision, in_hyperlink=link_key))
  257. def _walk_run(
  258. self,
  259. run: ET.Element,
  260. runs: list[ParagraphRun],
  261. revision: str,
  262. link_key: Optional[str],
  263. block: ParagraphBlock,
  264. ) -> None:
  265. for child in run:
  266. tag = child.tag
  267. if tag == W_TAGS["t"]:
  268. self._emit_text(runs, child.text or "", revision, link_key)
  269. elif tag == W_TAGS["delText"]:
  270. # only surface deletion text when caller asked for raw or reject
  271. if revision == "del" and self.options.revisions in {"raw", "reject"}:
  272. self._emit_text(runs, child.text or "", "del", link_key)
  273. elif tag == W_TAGS["tab"]:
  274. self._emit_text(runs, "\t", revision, link_key)
  275. elif tag == W_TAGS["br"]:
  276. self._emit_text(runs, "\n", revision, link_key)
  277. elif tag == W_TAGS["footnoteReference"]:
  278. fid = child.get(W_ATTR["id"])
  279. if fid:
  280. block.footnote_refs.append(fid)
  281. if self.options.include_footnotes:
  282. self._emit_text(runs, f"[fn:{fid}]", revision, link_key)
  283. elif tag == W_TAGS["endnoteReference"]:
  284. eid = child.get(W_ATTR["id"])
  285. if eid:
  286. block.endnote_refs.append(eid)
  287. if self.options.include_endnotes:
  288. self._emit_text(runs, f"[en:{eid}]", revision, link_key)
  289. elif tag == W_TAGS["commentReference"]:
  290. cid = child.get(W_ATTR["id"])
  291. if cid:
  292. block.comment_refs.append(cid)
  293. if self.options.include_comments and self.options.inline_comment_marker:
  294. self._emit_text(runs, f"[cmt:{cid}]", revision, link_key)
  295. elif tag == W_TAGS["instrText"]:
  296. instr = (child.text or "").strip()
  297. if instr:
  298. block.fields.append(instr)
  299. else:
  300. # ignore unknown run children silently — they cannot carry text
  301. pass
  302. # -------------------------------------------------------------- paragraph
  303. def _walk_paragraph_children(
  304. self,
  305. node: ET.Element,
  306. runs: list[ParagraphRun],
  307. revision: str,
  308. link_key: Optional[str],
  309. block: ParagraphBlock,
  310. ) -> None:
  311. for child in node:
  312. tag = child.tag
  313. if tag == W_TAGS["pPr"]:
  314. continue
  315. if tag == W_TAGS["r"]:
  316. self._walk_run(child, runs, revision, link_key, block)
  317. elif tag == W_TAGS["ins"]:
  318. if self.options.revisions == "reject":
  319. # discard inserted text in reject mode
  320. continue
  321. self._walk_paragraph_children(child, runs, "ins", link_key, block)
  322. elif tag == W_TAGS["del"]:
  323. if self.options.revisions == "accept":
  324. # accepted means deletions are gone
  325. continue
  326. self._walk_paragraph_children(child, runs, "del", link_key, block)
  327. elif tag == W_TAGS["hyperlink"]:
  328. rid = child.get(R_ATTR["id"])
  329. anchor = child.get(W_ATTR["anchor"])
  330. tooltip = child.get(W_ATTR["tooltip"])
  331. target: Optional[str] = None
  332. if rid and rid in self.rels:
  333. target = self.rels[rid].get("target")
  334. if anchor and not target:
  335. target = f"#{anchor}"
  336. key = f"{rid or ''}|{anchor or ''}"
  337. # collect text that lives inside this hyperlink
  338. inner_runs: list[ParagraphRun] = []
  339. self._walk_paragraph_children(child, inner_runs, revision, key, block)
  340. # merge into outer run list with hyperlink marker
  341. for run in inner_runs:
  342. self._emit_text(runs, run.text, run.revision, key)
  343. # record hyperlink entry once
  344. hl_text = "".join(r.text for r in inner_runs)
  345. if hl_text or target:
  346. block.hyperlinks.append(
  347. Hyperlink(text=hl_text, target=target or "", anchor=anchor, tooltip=tooltip)
  348. )
  349. elif tag == W_TAGS["fldSimple"]:
  350. instr = child.get(f"{{{W_NS}}}instr") or ""
  351. if instr.strip():
  352. block.fields.append(instr.strip())
  353. # field result lives as run children below
  354. self._walk_paragraph_children(child, runs, revision, link_key, block)
  355. elif tag == W_TAGS["drawing"]:
  356. # Drawing-shape text (text boxes) is harvested globally so it can
  357. # be addressed on its own. Skip the subtree here to avoid double
  358. # counting.
  359. continue
  360. elif tag == W_TAGS["txbxContent"]:
  361. continue
  362. else:
  363. # recurse so that <w:smartTag>, <w:bdo>, <w:dir>, etc. surface their text
  364. self._walk_paragraph_children(child, runs, revision, link_key, block)
  365. def walk(self, paragraph: ET.Element) -> ParagraphBlock:
  366. ppr = paragraph.find(W_TAGS["pPr"])
  367. style_id: Optional[str] = None
  368. if ppr is not None:
  369. pstyle = ppr.find(W_TAGS["pStyle"])
  370. style_id = _wval(pstyle)
  371. style_name = self.style_names.get(style_id or "")
  372. block = ParagraphBlock(style=style_id, style_name=style_name, text="", runs=[])
  373. runs: list[ParagraphRun] = []
  374. self._walk_paragraph_children(paragraph, runs, "none", None, block)
  375. block.runs = [
  376. {"text": r.text, "revision": r.revision, "hyperlinkKey": r.in_hyperlink}
  377. for r in runs
  378. if r.text
  379. ]
  380. block.text = "".join(r.text for r in runs)
  381. return block
  382. # ---------------------------------------------------------------------------
  383. # Side-channel parts: footnotes / endnotes / comments / headers / footers
  384. # ---------------------------------------------------------------------------
  385. def _collect_footnote_like(
  386. archive: ZipFile,
  387. part_name: str,
  388. container_local: str,
  389. options: Options,
  390. style_names: dict[str, str],
  391. ) -> list[dict]:
  392. root = _read_xml(archive, part_name)
  393. if root is None:
  394. return []
  395. _strip_alternate_content(root)
  396. rels = _load_relationships(archive, part_name)
  397. walker = ParagraphWalker(options, rels, style_names)
  398. out: list[dict] = []
  399. container_tag = f"{{{W_NS}}}{container_local}"
  400. for entry in root.findall(container_tag):
  401. fid = entry.get(W_ATTR["id"])
  402. ftype = entry.get(W_ATTR["type"]) # "separator" / "continuationSeparator" / "normal"
  403. if ftype in {"separator", "continuationSeparator"}:
  404. continue
  405. paragraphs = entry.findall(f".//{W_TAGS['p']}")
  406. text = "\n".join(walker.walk(p).text.strip() for p in paragraphs).strip()
  407. if not text:
  408. continue
  409. out.append({"id": fid, "type": ftype or "normal", "text": text})
  410. return out
  411. def _collect_comments(
  412. archive: ZipFile, options: Options, style_names: dict[str, str]
  413. ) -> list[dict]:
  414. root = _read_xml(archive, "word/comments.xml")
  415. if root is None:
  416. return []
  417. _strip_alternate_content(root)
  418. rels = _load_relationships(archive, "word/comments.xml")
  419. walker = ParagraphWalker(options, rels, style_names)
  420. out: list[dict] = []
  421. for entry in root.findall(f"{{{W_NS}}}comment"):
  422. cid = entry.get(W_ATTR["id"])
  423. author = entry.get(W_ATTR["author"])
  424. date = entry.get(W_ATTR["date"])
  425. paragraphs = entry.findall(f".//{W_TAGS['p']}")
  426. text = "\n".join(walker.walk(p).text.strip() for p in paragraphs).strip()
  427. out.append(
  428. {
  429. "id": cid,
  430. "author": author,
  431. "date": date,
  432. "text": text,
  433. }
  434. )
  435. return out
  436. def _collect_headers_or_footers(
  437. archive: ZipFile,
  438. document_rels: dict[str, dict],
  439. document_root: ET.Element,
  440. kind: str, # "header" or "footer"
  441. options: Options,
  442. style_names: dict[str, str],
  443. ) -> list[dict]:
  444. """Walk every header/footer part referenced by every section, preserving
  445. section index and reference type (default/first/even)."""
  446. ref_tag = W_TAGS["headerReference" if kind == "header" else "footerReference"]
  447. parts: list[dict] = []
  448. for sect_idx, sect in enumerate(document_root.findall(f".//{W_TAGS['sectPr']}")):
  449. for ref in sect.findall(ref_tag):
  450. rid = ref.get(R_ATTR["id"])
  451. ref_type = ref.get(W_ATTR["type"]) or "default"
  452. if not rid or rid not in document_rels:
  453. continue
  454. target = document_rels[rid]["target"]
  455. part_name = _resolve_target("word/document.xml", target)
  456. root = _read_xml(archive, part_name)
  457. if root is None:
  458. continue
  459. _strip_alternate_content(root)
  460. rels = _load_relationships(archive, part_name)
  461. walker = ParagraphWalker(options, rels, style_names)
  462. paragraphs = root.findall(f".//{W_TAGS['p']}")
  463. text = "\n".join(walker.walk(p).text.strip() for p in paragraphs).strip()
  464. parts.append(
  465. {
  466. "section": sect_idx,
  467. "kind": kind,
  468. "role": ref_type,
  469. "part": part_name,
  470. "text": text,
  471. }
  472. )
  473. return parts
  474. def _resolve_target(source_part: str, target: str) -> str:
  475. if target.startswith("/"):
  476. return target.lstrip("/")
  477. base = source_part.rsplit("/", 1)[0]
  478. pieces = []
  479. for piece in (base + "/" + target).split("/"):
  480. if piece in {"", "."}:
  481. continue
  482. if piece == "..":
  483. if pieces:
  484. pieces.pop()
  485. else:
  486. pieces.append(piece)
  487. return "/".join(pieces)
  488. # ---------------------------------------------------------------------------
  489. # Body walker
  490. # ---------------------------------------------------------------------------
  491. def _collect_textboxes(root: ET.Element, walker: ParagraphWalker, location: str) -> list[dict]:
  492. out: list[dict] = []
  493. for txbx in root.findall(f".//{W_TAGS['txbxContent']}"):
  494. paragraphs = txbx.findall(f".//{W_TAGS['p']}")
  495. text = "\n".join(walker.walk(p).text.strip() for p in paragraphs).strip()
  496. if text:
  497. out.append({"location": location, "text": text})
  498. return out
  499. def _walk_body(
  500. body: ET.Element, walker: ParagraphWalker
  501. ) -> tuple[list[object], int, int, int, int]:
  502. """Walk body in order. Returns (blocks, raw_ins_count, raw_del_count,
  503. retained_ins, retained_del)."""
  504. blocks: list[object] = []
  505. raw_ins = len(body.findall(f".//{W_TAGS['ins']}"))
  506. raw_del = len(body.findall(f".//{W_TAGS['del']}"))
  507. # we count "retained" by re-walking with a probe walker after the main walk
  508. # (cheap because each paragraph is small). Actual retention happens inline
  509. # inside walker.walk based on options.revisions.
  510. retained_ins = 0
  511. retained_del = 0
  512. def _on_paragraph(p: ET.Element) -> ParagraphBlock:
  513. nonlocal retained_ins, retained_del
  514. block = walker.walk(p)
  515. retained_ins += sum(1 for r in block.runs if r["revision"] == "ins")
  516. retained_del += sum(1 for r in block.runs if r["revision"] == "del")
  517. return block
  518. for child in body:
  519. if child.tag == W_TAGS["p"]:
  520. blocks.append({"kind": "paragraph", "block": _on_paragraph(child)})
  521. elif child.tag == W_TAGS["tbl"]:
  522. rows: list[list[ParagraphBlock]] = []
  523. for tr in child.findall(W_TAGS["tr"]):
  524. row: list[ParagraphBlock] = []
  525. for tc in tr.findall(W_TAGS["tc"]):
  526. cell_blocks: list[ParagraphBlock] = []
  527. for cp in tc.findall(W_TAGS["p"]):
  528. cell_blocks.append(_on_paragraph(cp))
  529. row.append(cell_blocks)
  530. rows.append(row)
  531. blocks.append({"kind": "table", "rows": rows})
  532. elif child.tag == W_TAGS["sectPr"]:
  533. continue
  534. else:
  535. # fall back: collect any paragraphs nested inside (e.g. SDT containers)
  536. for p in child.findall(f".//{W_TAGS['p']}"):
  537. blocks.append({"kind": "paragraph", "block": _on_paragraph(p)})
  538. return blocks, raw_ins, raw_del, retained_ins, retained_del
  539. def _load_style_names(archive: ZipFile) -> dict[str, str]:
  540. root = _read_xml(archive, "word/styles.xml")
  541. if root is None:
  542. return {}
  543. out: dict[str, str] = {}
  544. for style in root.findall(f"{{{W_NS}}}style"):
  545. sid = style.get(f"{{{W_NS}}}styleId") or style.get("styleId")
  546. if not sid:
  547. continue
  548. name_el = style.find(f"{{{W_NS}}}name")
  549. name = _wval(name_el)
  550. if name:
  551. out[sid] = name
  552. return out
  553. # ---------------------------------------------------------------------------
  554. # Top-level extraction
  555. # ---------------------------------------------------------------------------
  556. def extract(path: Path, options: Options) -> ExtractionResult:
  557. warnings: list[str] = []
  558. with ZipFile(path, "r") as archive:
  559. document_root = _read_xml(archive, "word/document.xml")
  560. if document_root is None:
  561. raise RuntimeError("Not a valid DOCX: word/document.xml missing")
  562. _strip_alternate_content(document_root)
  563. body = document_root.find(f"{{{W_NS}}}body")
  564. if body is None:
  565. raise RuntimeError("Document body missing")
  566. style_names = _load_style_names(archive)
  567. document_rels = _load_relationships(archive, "word/document.xml")
  568. walker = ParagraphWalker(options, document_rels, style_names)
  569. body_blocks, raw_ins, raw_del, ret_ins, ret_del = _walk_body(body, walker)
  570. # gather hyperlinks across body in walk order (for stable id-less listing)
  571. all_hyperlinks: list[Hyperlink] = []
  572. for entry in body_blocks:
  573. if entry["kind"] == "paragraph":
  574. all_hyperlinks.extend(entry["block"].hyperlinks)
  575. else:
  576. for row in entry["rows"]:
  577. for cell in row:
  578. for cp in cell:
  579. all_hyperlinks.extend(cp.hyperlinks)
  580. textboxes: list[dict] = []
  581. if options.include_textboxes:
  582. textboxes = _collect_textboxes(document_root, walker, "body")
  583. footnotes: list[dict] = []
  584. if options.include_footnotes:
  585. footnotes = _collect_footnote_like(
  586. archive, "word/footnotes.xml", "footnote", options, style_names
  587. )
  588. endnotes: list[dict] = []
  589. if options.include_endnotes:
  590. endnotes = _collect_footnote_like(
  591. archive, "word/endnotes.xml", "endnote", options, style_names
  592. )
  593. comments: list[dict] = []
  594. if options.include_comments:
  595. comments = _collect_comments(archive, options, style_names)
  596. headers: list[dict] = []
  597. if options.include_headers:
  598. headers = _collect_headers_or_footers(
  599. archive, document_rels, document_root, "header", options, style_names
  600. )
  601. footers: list[dict] = []
  602. if options.include_footers:
  603. footers = _collect_headers_or_footers(
  604. archive, document_rels, document_root, "footer", options, style_names
  605. )
  606. # warn loudly when we drop something the user might care about
  607. if options.revisions == "accept" and raw_del > 0:
  608. warnings.append(
  609. f"revisions policy 'accept' dropped {raw_del} <w:del> block(s); "
  610. "use --revisions raw to retain them"
  611. )
  612. if options.revisions == "reject" and raw_ins > 0:
  613. warnings.append(
  614. f"revisions policy 'reject' dropped {raw_ins} <w:ins> block(s); "
  615. "use --revisions raw to retain them"
  616. )
  617. if not options.include_footnotes and footnotes_referenced(body_blocks):
  618. warnings.append("footnote references in body were ignored (--no-footnotes)")
  619. if not options.include_endnotes and endnotes_referenced(body_blocks):
  620. warnings.append("endnote references in body were ignored (--no-endnotes)")
  621. if not options.include_comments and comments_referenced(body_blocks):
  622. warnings.append("comment references in body were ignored (--no-comments)")
  623. return ExtractionResult(
  624. body=body_blocks,
  625. footnotes=footnotes,
  626. endnotes=endnotes,
  627. comments=comments,
  628. hyperlinks=all_hyperlinks,
  629. textboxes=textboxes,
  630. headers=headers,
  631. footers=footers,
  632. revisions={
  633. "policy": options.revisions,
  634. "rawInsertions": raw_ins,
  635. "rawDeletions": raw_del,
  636. "retainedInsertions": ret_ins,
  637. "retainedDeletions": ret_del,
  638. },
  639. warnings=warnings,
  640. style_names=style_names,
  641. )
  642. def footnotes_referenced(blocks: Iterable[object]) -> bool:
  643. for entry in blocks:
  644. if entry["kind"] == "paragraph" and entry["block"].footnote_refs:
  645. return True
  646. if entry["kind"] == "table":
  647. for row in entry["rows"]:
  648. for cell in row:
  649. for cp in cell:
  650. if cp.footnote_refs:
  651. return True
  652. return False
  653. def endnotes_referenced(blocks: Iterable[object]) -> bool:
  654. for entry in blocks:
  655. if entry["kind"] == "paragraph" and entry["block"].endnote_refs:
  656. return True
  657. if entry["kind"] == "table":
  658. for row in entry["rows"]:
  659. for cell in row:
  660. for cp in cell:
  661. if cp.endnote_refs:
  662. return True
  663. return False
  664. def comments_referenced(blocks: Iterable[object]) -> bool:
  665. for entry in blocks:
  666. if entry["kind"] == "paragraph" and entry["block"].comment_refs:
  667. return True
  668. if entry["kind"] == "table":
  669. for row in entry["rows"]:
  670. for cell in row:
  671. for cp in cell:
  672. if cp.comment_refs:
  673. return True
  674. return False
  675. # ---------------------------------------------------------------------------
  676. # Renderers
  677. # ---------------------------------------------------------------------------
  678. def _paragraph_to_text(p: ParagraphBlock, options: Options) -> str:
  679. text = p.text
  680. if options.include_hyperlinks and p.hyperlinks:
  681. suffix_parts = []
  682. for hl in p.hyperlinks:
  683. target = hl.target or (f"#{hl.anchor}" if hl.anchor else "")
  684. if not target:
  685. continue
  686. label = hl.text or target
  687. # rewrite link inline — replace first occurrence of label with `label (→ target)`
  688. if label and label in text:
  689. text = text.replace(label, f"{label} (→ {target})", 1)
  690. else:
  691. suffix_parts.append(f"{label} (→ {target})")
  692. if suffix_parts:
  693. text = text + " " + " ".join(suffix_parts)
  694. return text.strip()
  695. def render_text(result: ExtractionResult, options: Options) -> str:
  696. out: list[str] = []
  697. for entry in result.body:
  698. if entry["kind"] == "paragraph":
  699. line = _paragraph_to_text(entry["block"], options)
  700. if line:
  701. out.append(line)
  702. else:
  703. for row in entry["rows"]:
  704. cells = []
  705. for cell in row:
  706. cell_text = " ".join(_paragraph_to_text(cp, options) for cp in cell).strip()
  707. cells.append(cell_text)
  708. if any(cells):
  709. out.append(" | ".join(cells))
  710. if options.include_footnotes and result.footnotes:
  711. out.append("")
  712. out.append("FOOTNOTES")
  713. for fn in result.footnotes:
  714. out.append(f" [fn:{fn['id']}] {fn['text']}")
  715. if options.include_endnotes and result.endnotes:
  716. out.append("")
  717. out.append("ENDNOTES")
  718. for en in result.endnotes:
  719. out.append(f" [en:{en['id']}] {en['text']}")
  720. if options.include_comments and result.comments:
  721. out.append("")
  722. out.append("COMMENTS")
  723. for cm in result.comments:
  724. who = cm.get("author") or "anon"
  725. when = cm.get("date") or "?"
  726. out.append(f" [cmt:{cm['id']}] ({who}, {when}) {cm['text']}")
  727. if options.include_headers and result.headers:
  728. out.append("")
  729. out.append("HEADERS")
  730. for hd in result.headers:
  731. if hd["text"]:
  732. out.append(f" section={hd['section']} role={hd['role']} :: {hd['text']}")
  733. if options.include_footers and result.footers:
  734. out.append("")
  735. out.append("FOOTERS")
  736. for ft in result.footers:
  737. if ft["text"]:
  738. out.append(f" section={ft['section']} role={ft['role']} :: {ft['text']}")
  739. if options.include_textboxes and result.textboxes:
  740. out.append("")
  741. out.append("TEXT BOXES")
  742. for tb in result.textboxes:
  743. out.append(f" ({tb['location']}) {tb['text']}")
  744. if result.warnings:
  745. out.append("")
  746. out.append("WARNINGS")
  747. for w in result.warnings:
  748. out.append(f" {w}")
  749. return "\n".join(line for line in out).strip() + ("\n" if out else "")
  750. def render_markdown(result: ExtractionResult, options: Options) -> str:
  751. out: list[str] = []
  752. for entry in result.body:
  753. if entry["kind"] == "paragraph":
  754. block = entry["block"]
  755. text = _paragraph_to_text(block, options)
  756. if not text:
  757. continue
  758. style = (block.style or "").lower()
  759. if "heading" in style or style in {"title", "subtitle"}:
  760. level = 1
  761. for ch in style[::-1]:
  762. if ch.isdigit():
  763. level = int(ch)
  764. break
  765. out.append(f"{'#' * max(1, min(level, 6))} {text}")
  766. else:
  767. out.append(text)
  768. out.append("")
  769. else:
  770. rows = entry["rows"]
  771. if not rows:
  772. continue
  773. md_rows = []
  774. for row in rows:
  775. md_rows.append(
  776. "| "
  777. + " | ".join(
  778. " ".join(_paragraph_to_text(cp, options) for cp in cell).replace("|", "\\|")
  779. for cell in row
  780. )
  781. + " |"
  782. )
  783. if md_rows:
  784. header_cells = len(rows[0])
  785. out.append(md_rows[0])
  786. out.append("|" + "|".join([" --- "] * header_cells) + "|")
  787. out.extend(md_rows[1:])
  788. out.append("")
  789. if options.include_footnotes and result.footnotes:
  790. out.append("## Footnotes")
  791. for fn in result.footnotes:
  792. out.append(f"- **fn:{fn['id']}** — {fn['text']}")
  793. out.append("")
  794. if options.include_endnotes and result.endnotes:
  795. out.append("## Endnotes")
  796. for en in result.endnotes:
  797. out.append(f"- **en:{en['id']}** — {en['text']}")
  798. out.append("")
  799. if options.include_comments and result.comments:
  800. out.append("## Comments")
  801. for cm in result.comments:
  802. out.append(
  803. f"- **cmt:{cm['id']}** ({cm.get('author') or 'anon'}, {cm.get('date') or '?'}): {cm['text']}"
  804. )
  805. out.append("")
  806. return "\n".join(out).strip() + "\n"
  807. def render_json(result: ExtractionResult, options: Options, path: Path) -> str:
  808. body_payload: list[dict] = []
  809. for entry in result.body:
  810. if entry["kind"] == "paragraph":
  811. block: ParagraphBlock = entry["block"]
  812. body_payload.append(
  813. {
  814. "kind": "paragraph",
  815. "style": block.style,
  816. "styleName": block.style_name,
  817. "text": block.text,
  818. "runs": block.runs,
  819. "hyperlinks": [hl.__dict__ for hl in block.hyperlinks],
  820. "footnoteRefs": block.footnote_refs,
  821. "endnoteRefs": block.endnote_refs,
  822. "commentRefs": block.comment_refs,
  823. "fields": block.fields,
  824. }
  825. )
  826. else:
  827. body_payload.append(
  828. {
  829. "kind": "table",
  830. "rows": [
  831. [
  832. [
  833. {
  834. "style": cp.style,
  835. "styleName": cp.style_name,
  836. "text": cp.text,
  837. "footnoteRefs": cp.footnote_refs,
  838. "endnoteRefs": cp.endnote_refs,
  839. "commentRefs": cp.comment_refs,
  840. "hyperlinks": [hl.__dict__ for hl in cp.hyperlinks],
  841. }
  842. for cp in cell
  843. ]
  844. for cell in row
  845. ]
  846. for row in entry["rows"]
  847. ],
  848. }
  849. )
  850. payload = {
  851. "file": str(path),
  852. "options": options.to_dict(),
  853. "body": body_payload,
  854. "footnotes": result.footnotes,
  855. "endnotes": result.endnotes,
  856. "comments": result.comments,
  857. "hyperlinks": [hl.__dict__ for hl in result.hyperlinks],
  858. "textboxes": result.textboxes,
  859. "headers": result.headers,
  860. "footers": result.footers,
  861. "revisions": result.revisions,
  862. "warnings": result.warnings,
  863. }
  864. return json.dumps(payload, ensure_ascii=False, indent=2)
  865. # ---------------------------------------------------------------------------
  866. # CLI
  867. # ---------------------------------------------------------------------------
  868. def _build_parser() -> argparse.ArgumentParser:
  869. parser = argparse.ArgumentParser(
  870. description="Extract content-truth view of a DOCX (text/json/markdown).",
  871. )
  872. parser.add_argument("input_path", help="Path to the .docx file")
  873. parser.add_argument(
  874. "--format",
  875. choices=["text", "json", "markdown"],
  876. default="text",
  877. help="Output format. Default: text (back-compat).",
  878. )
  879. parser.add_argument(
  880. "--revisions",
  881. choices=["accept", "reject", "raw"],
  882. default="accept",
  883. help=(
  884. "Track-changes read policy. accept: keep insertions, drop deletions. "
  885. "reject: drop insertions, keep deletions. raw: keep both."
  886. ),
  887. )
  888. parser.add_argument("--no-footnotes", action="store_true")
  889. parser.add_argument("--no-endnotes", action="store_true")
  890. parser.add_argument("--no-comments", action="store_true")
  891. parser.add_argument("--no-hyperlinks", action="store_true")
  892. parser.add_argument("--no-textboxes", action="store_true")
  893. parser.add_argument(
  894. "--include-headers",
  895. action="store_true",
  896. help="Include header text. Off by default to mirror reading-only intent.",
  897. )
  898. parser.add_argument(
  899. "--include-footers",
  900. action="store_true",
  901. help="Include footer text. Off by default to mirror reading-only intent.",
  902. )
  903. parser.add_argument(
  904. "--no-comment-markers",
  905. action="store_true",
  906. help="Drop inline [cmt:N] markers; comments still listed in the dedicated section.",
  907. )
  908. return parser
  909. def _options_from_args(args: argparse.Namespace) -> Options:
  910. return Options(
  911. fmt=args.format,
  912. revisions=args.revisions,
  913. include_footnotes=not args.no_footnotes,
  914. include_endnotes=not args.no_endnotes,
  915. include_comments=not args.no_comments,
  916. include_hyperlinks=not args.no_hyperlinks,
  917. include_textboxes=not args.no_textboxes,
  918. include_headers=args.include_headers,
  919. include_footers=args.include_footers,
  920. inline_comment_marker=not args.no_comment_markers,
  921. )
  922. def main(argv: Optional[list[str]] = None) -> int:
  923. parser = _build_parser()
  924. args = parser.parse_args(argv)
  925. input_path = Path(args.input_path).expanduser().resolve()
  926. if not input_path.exists():
  927. raise RuntimeError(f"Input file does not exist: {input_path}")
  928. if input_path.suffix.lower() != ".docx":
  929. raise RuntimeError("extract_docx_text.py currently supports .docx only")
  930. options = _options_from_args(args)
  931. result = extract(input_path, options)
  932. if options.fmt == "json":
  933. sys.stdout.write(render_json(result, options, input_path))
  934. sys.stdout.write("\n")
  935. elif options.fmt == "markdown":
  936. sys.stdout.write(render_markdown(result, options))
  937. else:
  938. sys.stdout.write(render_text(result, options))
  939. return 0
  940. if __name__ == "__main__":
  941. try:
  942. raise SystemExit(main())
  943. except Exception as exc: # pragma: no cover - CLI error path
  944. print(f"extract_docx_text.py failed: {exc}", file=sys.stderr)
  945. raise SystemExit(1)