postcheck.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. #!/usr/bin/env python3
  2. """
  3. postcheck.py — Document business rule self-check script
  4. Unlike traditional OpenXML Schema validation, this script does not check XML legality.
  5. Instead, it checks document "visual quality" and "typesetting correctness" — issues visible to the human eye.
  6. Usage:
  7. "$(command -v zcode-python || command -v python3)" postcheck.py output.docx [--fix] [--json]
  8. Checks:
  9. 1. Blank page detection — trailing/middle excess blank pages, double page breaks, consecutive empty paragraphs
  10. 2. Line spacing consistency — whether body paragraph line spacing is uniform
  11. 3. Table margins — whether cells have padding set
  12. 4. Table pagination control — whether header rows have tblHeader set, data rows have cantSplit
  13. 5. Image overflow — whether image width exceeds page usable area
  14. 6. Font fallback — whether fonts are used that may be missing on target systems
  15. 7. CJK indentation — whether Chinese body text has first-line indent (excluding table cells, lists, centered paragraphs)
  16. 8. Heading level continuity — whether headings skip levels (H1→H3 skipping H2)
  17. 9. Numbering continuity — whether numbered lists have gaps
  18. 10. Cover separation — whether cover and body are in different sections
  19. 11. ShadingType — whether SOLID is misused causing black cells
  20. 12. TOC quality — whether TOC field exists, whether headings use standard Heading styles
  21. 13. Image aspect ratio — whether images are stretched/distorted
  22. 14. Document cleanliness — whether placeholder text, Markdown syntax, or draft expressions remain
  23. 15. Report content quality — whether summary exists, whether titles are specific, whether vague conclusions are used
  24. """
  25. import json
  26. import re
  27. import sys
  28. import zipfile
  29. from pathlib import Path
  30. from xml.etree import ElementTree as ET
  31. NS = {
  32. "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
  33. "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
  34. "wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
  35. "a": "http://schemas.openxmlformats.org/drawingml/2006/main",
  36. "pic": "http://schemas.openxmlformats.org/drawingml/2006/picture",
  37. }
  38. class CheckResult:
  39. def __init__(self, name: str, passed: bool, message: str, severity: str = "warning"):
  40. self.name = name
  41. self.passed = passed
  42. self.message = message
  43. self.severity = severity # "error" | "warning" | "info"
  44. def to_dict(self):
  45. return {
  46. "name": self.name,
  47. "passed": self.passed,
  48. "message": self.message,
  49. "severity": self.severity,
  50. }
  51. def __str__(self):
  52. icon = "✅" if self.passed else ("❌" if self.severity == "error" else "⚠️")
  53. return f"{icon} [{self.name}] {self.message}"
  54. def read_document_xml(docx_path: str) -> ET.Element:
  55. """Read document.xml and return the root element"""
  56. with zipfile.ZipFile(docx_path, "r") as z:
  57. return ET.fromstring(z.read("word/document.xml"))
  58. def get_sections(root: ET.Element) -> list:
  59. """Extract all sections (located via sectPr)"""
  60. body = root.find(".//w:body", NS)
  61. if body is None:
  62. return []
  63. sections = []
  64. current_children = []
  65. for child in body:
  66. tag = child.tag.split("}")[-1] if "}" in child.tag else child.tag
  67. if tag == "sectPr":
  68. sections.append({"children": current_children, "sectPr": child})
  69. current_children = []
  70. else:
  71. # Check whether paragraph contains sectPr (section break inside paragraph pPr)
  72. ppr_sect = child.find(".//w:pPr/w:sectPr", NS)
  73. if ppr_sect is not None:
  74. current_children.append(child)
  75. sections.append({"children": current_children, "sectPr": ppr_sect})
  76. current_children = []
  77. else:
  78. current_children.append(child)
  79. # Last section (body-level sectPr)
  80. body_sect = body.find("w:sectPr", NS)
  81. if body_sect is not None and current_children:
  82. sections.append({"children": current_children, "sectPr": body_sect})
  83. return sections
  84. def check_blank_pages(root: ET.Element) -> CheckResult:
  85. """Detect excess blank pages — multi-pattern detection"""
  86. body = root.find(".//w:body", NS)
  87. paragraphs = body.findall("w:p", NS)
  88. issues = []
  89. if not paragraphs:
  90. return CheckResult("blank-pages", True, "No paragraph content")
  91. # Check 1: Whether the last paragraph only has a page break
  92. last_p = paragraphs[-1]
  93. runs = last_p.findall(".//w:r", NS)
  94. has_page_break = False
  95. has_text = False
  96. for run in runs:
  97. br = run.find("w:br", NS)
  98. if br is not None and br.get(f"{{{NS['w']}}}type") == "page":
  99. has_page_break = True
  100. t = run.find("w:t", NS)
  101. if t is not None and t.text and t.text.strip():
  102. has_text = True
  103. if has_page_break and not has_text:
  104. issues.append("Trailing page break at document end may cause blank page")
  105. # Check 2: Consecutive empty paragraphs (≥5 consecutive may form visual blank page)
  106. consecutive_empty = 0
  107. max_empty = 0
  108. max_empty_pos = 0
  109. for idx, p in enumerate(paragraphs):
  110. texts = p.findall(".//w:t", NS)
  111. has_any_text = any(t.text and t.text.strip() for t in texts)
  112. has_br = any(
  113. br.get(f"{{{NS['w']}}}type") == "page"
  114. for br in p.findall(".//w:br", NS)
  115. )
  116. has_drawing = p.find(".//{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}inline", None) is not None
  117. if not has_any_text and not has_br and not has_drawing:
  118. consecutive_empty += 1
  119. if consecutive_empty > max_empty:
  120. max_empty = consecutive_empty
  121. max_empty_pos = idx
  122. else:
  123. consecutive_empty = 0
  124. if max_empty >= 5:
  125. issues.append(f"Found {max_empty} consecutive empty paragraphs (starting around paragraph {max_empty_pos - max_empty + 2}), may form visual blank page")
  126. # Check 3: Double page break at section boundary (PageBreak at section end + NEXT_PAGE in next section)
  127. sections = get_sections(root)
  128. for i in range(len(sections) - 1):
  129. sec_children = sections[i]["children"]
  130. if not sec_children:
  131. continue
  132. # Check whether the last paragraph of the section contains PageBreak
  133. last_child = sec_children[-1]
  134. if last_child.tag == f"{{{NS['w']}}}p":
  135. for br in last_child.findall(".//w:br", NS):
  136. if br.get(f"{{{NS['w']}}}type") == "page":
  137. # Check whether the next section is NEXT_PAGE
  138. next_sect_pr = sections[i + 1]["sectPr"]
  139. sect_type = next_sect_pr.find("w:type", NS)
  140. if sect_type is not None and sect_type.get(f"{{{NS['w']}}}val") == "nextPage":
  141. issues.append(f"Section {i+1} ends with PageBreak and Section {i+2} is type nextPage, double page break causes blank page")
  142. # Check 4: Empty paragraph + PageBreak (paragraph has only PageBreak, no text)
  143. # Exclude section-ending PageBreaks — they are normal section separators
  144. # (e.g., cover page ending with an empty para + PageBreak before a new section)
  145. section_last_paras = set()
  146. for sec in sections:
  147. children = sec["children"]
  148. if children:
  149. last_child = children[-1]
  150. section_last_paras.add(id(last_child))
  151. empty_pb_count = 0
  152. for p in paragraphs[:-1]: # Last paragraph already handled in Check 1
  153. if id(p) in section_last_paras:
  154. continue # Skip section-ending paragraphs (normal section breaks)
  155. runs = p.findall(".//w:r", NS)
  156. p_has_break = False
  157. p_has_text = False
  158. for run in runs:
  159. br = run.find("w:br", NS)
  160. if br is not None and br.get(f"{{{NS['w']}}}type") == "page":
  161. p_has_break = True
  162. t = run.find("w:t", NS)
  163. if t is not None and t.text and t.text.strip():
  164. p_has_text = True
  165. if p_has_break and not p_has_text:
  166. empty_pb_count += 1
  167. if empty_pb_count > 0:
  168. issues.append(f"Found {empty_pb_count} empty paragraphs with PageBreak (suggest attaching PageBreak to content paragraphs)")
  169. # Separate hard errors from soft warnings
  170. hard_issues = [i for i in issues if "double page break" in i.lower() or "trailing page break" in i.lower() or "consecutive" in i.lower()]
  171. soft_issues = [i for i in issues if i not in hard_issues]
  172. if hard_issues:
  173. return CheckResult(
  174. "blank-pages", False,
  175. "; ".join(hard_issues[:3]),
  176. "error"
  177. )
  178. if soft_issues:
  179. return CheckResult(
  180. "blank-pages", False,
  181. "; ".join(soft_issues[:3]),
  182. "warning"
  183. )
  184. return CheckResult("blank-pages", True, "No blank page issues detected")
  185. def check_line_spacing(root: ET.Element) -> CheckResult:
  186. """Check body paragraph line spacing consistency"""
  187. body = root.find(".//w:body", NS)
  188. paragraphs = body.findall(".//w:p", NS)
  189. spacing_values = {}
  190. body_para_count = 0
  191. for p in paragraphs:
  192. ppr = p.find("w:pPr", NS)
  193. # Skip heading paragraphs
  194. if ppr is not None:
  195. style = ppr.find("w:pStyle", NS)
  196. if style is not None:
  197. val = style.get(f"{{{NS['w']}}}val", "")
  198. if val.startswith("Heading") or val == "Title":
  199. continue
  200. spacing = ppr.find("w:spacing", NS) if ppr is not None else None
  201. line_val = spacing.get(f"{{{NS['w']}}}line") if spacing is not None else None
  202. # Only count paragraphs with text content
  203. texts = p.findall(".//w:t", NS)
  204. if not any(t.text and t.text.strip() for t in texts):
  205. continue
  206. body_para_count += 1
  207. key = line_val or "default"
  208. spacing_values[key] = spacing_values.get(key, 0) + 1
  209. if body_para_count == 0:
  210. return CheckResult("line-spacing", True, "No body paragraphs")
  211. if len(spacing_values) <= 1:
  212. dominant = list(spacing_values.keys())[0] if spacing_values else "default"
  213. return CheckResult("line-spacing", True, f"Line spacing uniform (line={dominant})")
  214. # Find the most common line spacing
  215. dominant = max(spacing_values, key=spacing_values.get)
  216. inconsistent = sum(v for k, v in spacing_values.items() if k != dominant)
  217. total = sum(spacing_values.values())
  218. if inconsistent / total > 0.2:
  219. return CheckResult(
  220. "line-spacing", False,
  221. f"Line spacing inconsistent: {dict(spacing_values)}, {inconsistent}/{total} paragraphs differ from dominant spacing {dominant}",
  222. "warning"
  223. )
  224. return CheckResult("line-spacing", True, f"Line spacing mostly uniform (line={dominant}, {inconsistent} exceptions)")
  225. def check_image_overflow(root: ET.Element) -> CheckResult:
  226. """Check whether image width may exceed page bounds"""
  227. # Get page width
  228. sect_pr = root.find(".//w:body/w:sectPr", NS)
  229. page_width = 11906 # A4 default
  230. margin_left = 1701
  231. margin_right = 1417
  232. if sect_pr is not None:
  233. pg_sz = sect_pr.find("w:pgSz", NS)
  234. pg_mar = sect_pr.find("w:pgMar", NS)
  235. if pg_sz is not None:
  236. page_width = int(pg_sz.get(f"{{{NS['w']}}}w", "11906"))
  237. if pg_mar is not None:
  238. margin_left = int(pg_mar.get(f"{{{NS['w']}}}left", "1701"))
  239. margin_right = int(pg_mar.get(f"{{{NS['w']}}}right", "1417"))
  240. usable_width_emu = (page_width - margin_left - margin_right) * 635 # twips → EMU
  241. drawings = root.findall(".//wp:inline", NS) + root.findall(".//wp:anchor", NS)
  242. oversized = 0
  243. for dwg in drawings:
  244. extent = dwg.find("wp:extent", NS)
  245. if extent is not None:
  246. cx = int(extent.get("cx", "0"))
  247. if cx > usable_width_emu * 1.05: # 5% tolerance
  248. oversized += 1
  249. if oversized > 0:
  250. return CheckResult(
  251. "image-overflow", False,
  252. f"{oversized} images exceed page usable area",
  253. "error"
  254. )
  255. return CheckResult(
  256. "image-overflow", True,
  257. f"All images within page width ({len(drawings)} images)"
  258. )
  259. def check_image_aspect_ratio(docx_path: str, root: ET.Element) -> CheckResult:
  260. """Check whether images are stretched/distorted (aspect ratio drift).
  261. Compares the original aspect ratio of embedded images with the display aspect ratio set in wp:extent.
  262. Drift >10% is considered distortion (pie charts becoming elliptical, radar charts becoming diamond-shaped, etc).
  263. """
  264. import zipfile as _zf
  265. # Build a mapping: rId → image file path inside the zip
  266. # We need to parse word/_rels/document.xml.rels
  267. rid_to_path = {}
  268. try:
  269. with _zf.ZipFile(docx_path, 'r') as z:
  270. rels_path = 'word/_rels/document.xml.rels'
  271. if rels_path in z.namelist():
  272. rels_xml = z.read(rels_path)
  273. rels_root = ET.fromstring(rels_xml)
  274. rels_ns = 'http://schemas.openxmlformats.org/package/2006/relationships'
  275. for rel in rels_root.findall(f'{{{rels_ns}}}Relationship'):
  276. rid = rel.get('Id', '')
  277. target = rel.get('Target', '')
  278. rel_type = rel.get('Type', '')
  279. if 'image' in rel_type:
  280. # Target is relative to word/ directory
  281. if not target.startswith('/'):
  282. img_path = 'word/' + target
  283. else:
  284. img_path = target.lstrip('/')
  285. rid_to_path[rid] = img_path
  286. # Now check each drawing
  287. drawings = root.findall(".//wp:inline", NS) + root.findall(".//wp:anchor", NS)
  288. distorted = []
  289. for dwg in drawings:
  290. extent = dwg.find("wp:extent", NS)
  291. if extent is None:
  292. continue
  293. display_cx = int(extent.get("cx", "0"))
  294. display_cy = int(extent.get("cy", "0"))
  295. if display_cx == 0 or display_cy == 0:
  296. continue
  297. # Find the blip rId
  298. blip = dwg.find(".//a:blip", NS)
  299. if blip is None:
  300. continue
  301. r_embed = blip.get(f"{{{NS['r']}}}embed", "")
  302. if not r_embed or r_embed not in rid_to_path:
  303. continue
  304. img_zip_path = rid_to_path[r_embed]
  305. if img_zip_path not in z.namelist():
  306. continue
  307. # Read actual image dimensions
  308. try:
  309. img_data = z.read(img_zip_path)
  310. import io as _io
  311. from PIL import Image as _PILImage
  312. pil_img = _PILImage.open(_io.BytesIO(img_data))
  313. orig_w, orig_h = pil_img.size
  314. if orig_w == 0 or orig_h == 0:
  315. continue
  316. except Exception:
  317. continue
  318. # Compare aspect ratios
  319. orig_ratio = orig_w / orig_h
  320. display_ratio = display_cx / display_cy
  321. drift = abs(orig_ratio - display_ratio) / orig_ratio
  322. if drift > 0.10: # >10% distortion
  323. pct = drift * 100
  324. distorted.append(
  325. f"{img_zip_path.split('/')[-1]}: "
  326. f"original {orig_w}×{orig_h} (ratio={orig_ratio:.2f}), "
  327. f"display ratio={display_ratio:.2f}, distortion {pct:.0f}%"
  328. )
  329. except Exception:
  330. return CheckResult(
  331. "image-aspect-ratio", True,
  332. "Cannot check image aspect ratio (zip read error)",
  333. "info"
  334. )
  335. if distorted:
  336. detail = "; ".join(distorted[:3])
  337. if len(distorted) > 3:
  338. detail += f" ...and {len(distorted)} more"
  339. return CheckResult(
  340. "image-aspect-ratio", False,
  341. f"{len(distorted)} images have aspect ratio distortion: {detail}",
  342. "warning"
  343. )
  344. img_count = len(drawings)
  345. return CheckResult(
  346. "image-aspect-ratio", True,
  347. f"All images have correct aspect ratio ({img_count} images)"
  348. )
  349. def check_font_fallback(root: ET.Element) -> CheckResult:
  350. """Check whether potentially missing fonts are used"""
  351. SAFE_FONTS = {
  352. # Chinese
  353. "宋体", "SimSun", "黑体", "SimHei", "微软雅黑", "Microsoft YaHei",
  354. "仿宋", "FangSong", "FangSong_GB2312", "楷体", "KaiTi",
  355. # English
  356. "Times New Roman", "Arial", "Calibri", "Helvetica",
  357. "Courier New", "Georgia", "Verdana", "Tahoma",
  358. # Universal
  359. "Symbol", "Wingdings",
  360. }
  361. fonts_used = set()
  362. for rpr in root.findall(".//w:rPr", NS):
  363. for font_tag in ["w:rFonts"]:
  364. rf = rpr.find(font_tag, NS)
  365. if rf is not None:
  366. for attr in ["ascii", "eastAsia", "hAnsi", "cs"]:
  367. f = rf.get(f"{{{NS['w']}}}{attr}")
  368. if f:
  369. fonts_used.add(f)
  370. risky = fonts_used - SAFE_FONTS
  371. if risky:
  372. return CheckResult(
  373. "font-fallback", False,
  374. f"Following fonts may be missing on target system: {', '.join(sorted(risky))}",
  375. "info"
  376. )
  377. return CheckResult("font-fallback", True, f"All fonts are common system fonts ({len(fonts_used)} types)")
  378. def check_heading_levels(root: ET.Element) -> CheckResult:
  379. """Check whether headings skip levels"""
  380. body = root.find(".//w:body", NS)
  381. heading_levels = []
  382. for p in body.findall(".//w:p", NS):
  383. ppr = p.find("w:pPr", NS)
  384. if ppr is None:
  385. continue
  386. style = ppr.find("w:pStyle", NS)
  387. if style is None:
  388. continue
  389. val = style.get(f"{{{NS['w']}}}val", "")
  390. m = re.match(r"Heading(\d+)", val)
  391. if m:
  392. heading_levels.append(int(m.group(1)))
  393. if len(heading_levels) < 2:
  394. return CheckResult("heading-levels", True, "Too few headings, skipping check")
  395. skips = []
  396. for i in range(1, len(heading_levels)):
  397. diff = heading_levels[i] - heading_levels[i - 1]
  398. if diff > 1:
  399. skips.append(f"H{heading_levels[i-1]}→H{heading_levels[i]}")
  400. if skips:
  401. return CheckResult(
  402. "heading-levels", False,
  403. f"Heading level skip: {', '.join(skips[:5])}",
  404. "warning"
  405. )
  406. return CheckResult("heading-levels", True, f"Heading levels continuous ({len(heading_levels)} headings)")
  407. # check_cover_separation removed — false positives on complex covers (>15 elements is normal)
  408. def check_shading_type(root: ET.Element) -> CheckResult:
  409. """Check whether ShadingType.SOLID is misused"""
  410. shadings = root.findall(".//w:shd", NS)
  411. solid_count = 0
  412. for shd in shadings:
  413. val = shd.get(f"{{{NS['w']}}}val", "")
  414. if val == "solid":
  415. solid_count += 1
  416. if solid_count > 0:
  417. return CheckResult(
  418. "shading-type", False,
  419. f"Found {solid_count} instances of ShadingType.SOLID (should be CLEAR), may cause black cells",
  420. "error"
  421. )
  422. return CheckResult("shading-type", True, "No ShadingType.SOLID misuse found")
  423. def check_toc(root: ET.Element, docx_path: str = "") -> CheckResult:
  424. """Check TOC quality: field existence, headings presence, outlineLvl, updateFields."""
  425. body = root.find(".//w:body", NS)
  426. if body is None:
  427. return CheckResult("toc", True, "Document body is empty, skipping TOC check", "info")
  428. paragraphs = list(body)
  429. w_ns = NS["w"]
  430. # --- Detect headings and their levels ---
  431. heading_count = 0
  432. heading_levels_used = set() # e.g. {1, 2, 3}
  433. for p in paragraphs:
  434. if p.tag != f"{{{w_ns}}}p":
  435. continue
  436. ppr = p.find(f"{{{w_ns}}}pPr")
  437. if ppr is None:
  438. continue
  439. ps = ppr.find(f"{{{w_ns}}}pStyle")
  440. if ps is None:
  441. continue
  442. val = ps.get(f"{{{w_ns}}}val", "")
  443. m = re.match(r"(?i)heading\s*(\d)", val)
  444. if m:
  445. heading_count += 1
  446. heading_levels_used.add(int(m.group(1)))
  447. # --- Detect TOC field ---
  448. has_toc = False
  449. for instr in root.findall(f".//{{{w_ns}}}instrText"):
  450. if instr.text and "TOC" in instr.text.upper():
  451. has_toc = True
  452. break
  453. if not has_toc:
  454. for fld in root.findall(f".//{{{w_ns}}}fldSimple"):
  455. if "TOC" in fld.get(f"{{{w_ns}}}instr", "").upper():
  456. has_toc = True
  457. break
  458. # Also check SDT-wrapped TOC
  459. if not has_toc:
  460. for sdt in root.findall(f".//{{{w_ns}}}sdt"):
  461. for instr in sdt.findall(f".//{{{w_ns}}}instrText"):
  462. if instr.text and "TOC" in instr.text.upper():
  463. has_toc = True
  464. break
  465. if has_toc:
  466. break
  467. issues = []
  468. # Check 1: Document has a "目录" / "目 录" / "Table of Contents" title but no TOC field
  469. has_toc_title = False
  470. toc_title_pattern = re.compile(r'^(?:目\s*录|table\s+of\s+contents|contents)$', re.IGNORECASE)
  471. for p in paragraphs:
  472. if p.tag != f"{{{w_ns}}}p":
  473. continue
  474. texts = p.findall(f".//{{{w_ns}}}t")
  475. p_text = "".join(t.text or "" for t in texts).strip()
  476. if toc_title_pattern.match(p_text):
  477. has_toc_title = True
  478. break
  479. if has_toc_title and not has_toc:
  480. issues.append("TOC_FIELD_MISSING: document has a TOC title but no TOC field element — add TableOfContents in code")
  481. # Check 2: TOC field exists but no headings in document → TOC will be empty after update
  482. if has_toc and heading_count == 0:
  483. issues.append("TOC_NO_HEADINGS: TOC field exists but document has 0 Heading-styled paragraphs — TOC will be empty after update")
  484. # Check 3 & 4: Read styles.xml and settings.xml from DOCX (only when TOC exists)
  485. if has_toc and docx_path:
  486. try:
  487. import zipfile
  488. with zipfile.ZipFile(docx_path, 'r') as zf:
  489. # Check 3: outlineLvl missing in Heading styles
  490. if 'word/styles.xml' in zf.namelist():
  491. styles_content = zf.read('word/styles.xml').decode('utf-8')
  492. styles_root = ET.fromstring(styles_content)
  493. missing_outline = []
  494. for level in sorted(heading_levels_used):
  495. style_id = f"Heading{level}"
  496. # Find <w:style w:styleId="HeadingN">
  497. for style_elem in styles_root.findall(f".//{{{w_ns}}}style"):
  498. sid = style_elem.get(f"{{{w_ns}}}styleId", "")
  499. if sid == style_id:
  500. # Check if pPr has outlineLvl
  501. ppr = style_elem.find(f"{{{w_ns}}}pPr")
  502. has_outline = False
  503. if ppr is not None:
  504. ol = ppr.find(f"{{{w_ns}}}outlineLvl")
  505. if ol is not None:
  506. has_outline = True
  507. if not has_outline:
  508. missing_outline.append(style_id)
  509. break
  510. if missing_outline:
  511. issues.append(
  512. "TOC_OUTLINE_MISSING: %s style(s) missing outlineLvl — "
  513. "Word TOC update won't find these headings. "
  514. "Run add_toc_placeholders.py to fix" % ", ".join(missing_outline)
  515. )
  516. # Check 4: updateFields not set to true
  517. if 'word/settings.xml' in zf.namelist():
  518. settings_content = zf.read('word/settings.xml').decode('utf-8')
  519. # Check for <w:updateFields w:val="true"/>
  520. update_ok = bool(re.search(
  521. r'<w:updateFields\s+[^>]*w:val\s*=\s*"true"',
  522. settings_content
  523. ))
  524. if not update_ok:
  525. issues.append(
  526. "TOC_UPDATE_DISABLED: settings.xml missing updateFields=true — "
  527. "Word won't prompt to update TOC on open. "
  528. "Run add_toc_placeholders.py to fix"
  529. )
  530. except Exception as e:
  531. issues.append(f"TOC_CHECK_ERROR: failed to read styles/settings from DOCX: {e}")
  532. if not issues:
  533. if has_toc:
  534. return CheckResult("toc", True, "TOC field present and update-ready")
  535. else:
  536. return CheckResult("toc", True, "No TOC needed")
  537. severity = "error" if any(k in i for i in issues for k in ("FIELD_MISSING", "NO_HEADINGS", "OUTLINE_MISSING")) else "warning"
  538. return CheckResult("toc", False, "; ".join(issues[:5]), severity)
  539. def check_cover_overflow(root: ET.Element) -> CheckResult:
  540. """Detect cover section issues: oversized fonts, excessive spacing, trailing empty content."""
  541. sections = get_sections(root)
  542. if not sections:
  543. return CheckResult("cover-overflow", True, "No sections found")
  544. sec0 = sections[0]
  545. sect_pr = sec0["sectPr"]
  546. # Get page dimensions and margins for accurate available height calculation
  547. pg_sz = sect_pr.find("w:pgSz", NS)
  548. pg_mar = sect_pr.find("w:pgMar", NS)
  549. page_height = int(pg_sz.get(f"{{{NS['w']}}}h", "16838")) if pg_sz is not None else 16838
  550. margin_top = int(pg_mar.get(f"{{{NS['w']}}}top", "0")) if pg_mar is not None else 0
  551. margin_bottom = int(pg_mar.get(f"{{{NS['w']}}}bottom", "0")) if pg_mar is not None else 0
  552. issues = []
  553. children = sec0["children"]
  554. # Check 1: Oversized font in cover section (> 44pt = 88 half-points = 889000 EMU)
  555. max_font_size = 0
  556. for child in children:
  557. for sz in child.findall(".//" + f"{{{NS['w']}}}sz"):
  558. val = sz.get(f"{{{NS['w']}}}val")
  559. if val and val.isdigit():
  560. size_hp = int(val)
  561. if size_hp > max_font_size:
  562. max_font_size = size_hp
  563. if max_font_size > 88: # 88 half-points = 44pt
  564. issues.append(
  565. f"Cover has font size {max_font_size // 2}pt (>{44}pt max). "
  566. f"Use calcTitleLayout() for dynamic sizing"
  567. )
  568. # Check 2: Excessive spacing.before in cover section (> 5000 twips)
  569. max_spacing = 0
  570. for child in children:
  571. for sp in child.findall(".//" + f"{{{NS['w']}}}spacing"):
  572. before = sp.get(f"{{{NS['w']}}}before")
  573. if before and before.isdigit():
  574. val = int(before)
  575. if val > max_spacing:
  576. max_spacing = val
  577. if max_spacing > 5000:
  578. issues.append(
  579. f"Cover has spacing.before={max_spacing} twips (>5000 max). "
  580. f"Use calcCoverSpacing() for dynamic spacing"
  581. )
  582. # Check 3: Trailing empty paragraphs in cover section
  583. trailing_empty = 0
  584. for child in reversed(children):
  585. tag = child.tag.split("}")[-1] if "}" in child.tag else child.tag
  586. if tag != "p":
  587. break
  588. texts = child.findall(".//" + f"{{{NS['w']}}}t")
  589. has_text = any(t.text and t.text.strip() for t in texts)
  590. if not has_text:
  591. trailing_empty += 1
  592. else:
  593. break
  594. if trailing_empty > 2:
  595. issues.append(
  596. f"Cover section ends with {trailing_empty} empty paragraphs (max 2 allowed) — "
  597. f"excessive empty paragraphs may cause blank page after cover"
  598. )
  599. if issues:
  600. return CheckResult(
  601. "cover-overflow", False,
  602. "; ".join(issues),
  603. "error"
  604. )
  605. return CheckResult("cover-overflow", True, "Cover section layout looks OK")
  606. def run_all_checks(docx_path: str) -> list[CheckResult]:
  607. """Run all checks"""
  608. root = read_document_xml(docx_path)
  609. checks = [
  610. check_blank_pages,
  611. check_cover_overflow,
  612. check_line_spacing,
  613. check_image_overflow,
  614. check_font_fallback,
  615. check_heading_levels,
  616. check_shading_type,
  617. ]
  618. results = []
  619. for check_fn in checks:
  620. try:
  621. results.append(check_fn(root))
  622. except Exception as e:
  623. results.append(CheckResult(
  624. check_fn.__name__.replace("check_", ""),
  625. False,
  626. f"Check error: {e}",
  627. "error"
  628. ))
  629. # TOC check needs both root and docx_path
  630. try:
  631. results.append(check_toc(root, docx_path))
  632. except Exception as e:
  633. results.append(CheckResult("toc", False, f"Check error: {e}", "error"))
  634. # Image aspect ratio check needs both root and docx_path
  635. try:
  636. results.append(check_image_aspect_ratio(docx_path, root))
  637. except Exception as e:
  638. results.append(CheckResult("image-aspect-ratio", False, f"Check error: {e}", "error"))
  639. return results
  640. def main():
  641. import argparse
  642. parser = argparse.ArgumentParser(description="docx business rule self-check")
  643. parser.add_argument("docx_path", help="Path to the .docx file to check")
  644. parser.add_argument("--json", action="store_true", help="Output in JSON format")
  645. parser.add_argument("--strict", action="store_true", help="Treat warnings as failures")
  646. args = parser.parse_args()
  647. if not Path(args.docx_path).exists():
  648. print(f"❌ File not found: {args.docx_path}")
  649. sys.exit(1)
  650. results = run_all_checks(args.docx_path)
  651. if args.json:
  652. print(json.dumps([r.to_dict() for r in results], ensure_ascii=False, indent=2))
  653. else:
  654. print(f"\n📋 Document self-check report: {args.docx_path}\n")
  655. for r in results:
  656. print(f" {r}")
  657. passed = sum(1 for r in results if r.passed)
  658. total = len(results)
  659. errors = sum(1 for r in results if not r.passed and r.severity == "error")
  660. warnings = sum(1 for r in results if not r.passed and r.severity == "warning")
  661. print(f"\n {'─' * 50}")
  662. print(f" Passed {passed}/{total} | ❌ {errors} errors | ⚠️ {warnings} warnings\n")
  663. # Exit code
  664. has_errors = any(not r.passed and r.severity == "error" for r in results)
  665. has_warnings = any(not r.passed and r.severity == "warning" for r in results)
  666. if has_errors:
  667. sys.exit(2)
  668. elif args.strict and has_warnings:
  669. sys.exit(1)
  670. else:
  671. sys.exit(0)
  672. if __name__ == "__main__":
  673. main()