toc_validate.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  1. #!/usr/bin/env python3
  2. """
  3. toc_validate.py - Table of Contents Validation for DOCX and PDF files.
  4. Checks DOCX and PDF files for TOC quality issues including missing TOC fields,
  5. empty placeholders, heading style mismatches, page break issues, and more.
  6. Also validates TOC consistency across DOCX→PDF conversions.
  7. Usage:
  8. "$(command -v zcode-python || command -v python3)" toc_validate.py check-docx output.docx
  9. "$(command -v zcode-python || command -v python3)" toc_validate.py check-pdf output.pdf
  10. "$(command -v zcode-python || command -v python3)" toc_validate.py check-conversion input.docx output.pdf
  11. Output:
  12. JSON to stdout with structure:
  13. {
  14. "pass": true/false,
  15. "source": "filename",
  16. "check_type": "docx-toc"|"pdf-toc"|"conversion-toc",
  17. "errors": [...],
  18. "warnings": [...],
  19. "info": [...]
  20. }
  21. Exit codes:
  22. 0 = pass (no errors)
  23. 1 = fail (errors found)
  24. 2 = script error (bad args, file not found, etc.)
  25. Dependencies:
  26. - Standard library (zipfile, xml.etree.ElementTree, etc.)
  27. - pdfplumber (for PDF checks)
  28. - pikepdf (optional, for link annotation checks)
  29. """
  30. import json
  31. import os
  32. import re
  33. import sys
  34. import tempfile
  35. import xml.etree.ElementTree as ET
  36. import zipfile
  37. from typing import Any
  38. # ---------------------------------------------------------------------------
  39. # XML namespace constants
  40. # ---------------------------------------------------------------------------
  41. NS = {
  42. 'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
  43. 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
  44. }
  45. # Standard heading style names (case-insensitive comparison)
  46. STANDARD_HEADING_STYLES = {
  47. 'heading1', 'heading2', 'heading3', 'heading4',
  48. 'heading 1', 'heading 2', 'heading 3', 'heading 4',
  49. # Some localized variants
  50. '1', '2', '3', '4',
  51. }
  52. # TOC keywords to search for in PDF text
  53. TOC_KEYWORDS = ['目录', '目 录', '目 录', 'table of contents', 'contents']
  54. # Hint phrases that should not leak into final PDF
  55. HINT_PHRASES = [
  56. '提示:本目录通过域代码生成',
  57. '右键更新域',
  58. 'Update Field',
  59. 'right-click',
  60. 'Tip: This table of contents',
  61. ]
  62. # Hint text indicators for DOCX styling check
  63. HINT_INDICATORS = ['提示', 'Tip:', 'Update Field', '更新域']
  64. # Gray color values (hex, case-insensitive)
  65. GRAY_COLORS = {'808080', '999999', 'a0a0a0', 'a5a5a5', 'b0b0b0', 'c0c0c0',
  66. '888888', '777777', '666666', 'aaaaaa', 'bbbbbb', 'cccccc',
  67. '909090', '959595', '9a9a9a', 'a8a8a8', 'b8b8b8'}
  68. # ---------------------------------------------------------------------------
  69. # Result helpers
  70. # ---------------------------------------------------------------------------
  71. def make_item(code: str, message: str, severity: str) -> dict[str, str]:
  72. """Create a single result item."""
  73. return {"code": code, "message": message, "severity": severity}
  74. def make_result(source: str, check_type: str, errors: list, warnings: list,
  75. info: list) -> dict[str, Any]:
  76. """Build the final result dict."""
  77. return {
  78. "pass": len(errors) == 0,
  79. "source": source,
  80. "check_type": check_type,
  81. "errors": errors,
  82. "warnings": warnings,
  83. "info": info,
  84. }
  85. # ---------------------------------------------------------------------------
  86. # DOCX XML parsing helpers
  87. # ---------------------------------------------------------------------------
  88. def parse_docx_xml(docx_path: str) -> ET.Element | None:
  89. """Extract and parse document.xml from a .docx file.
  90. Returns the root Element or None if extraction fails.
  91. """
  92. try:
  93. with zipfile.ZipFile(docx_path, 'r') as z, z.open('word/document.xml') as f:
  94. return ET.parse(f).getroot()
  95. except (zipfile.BadZipFile, KeyError, ET.ParseError):
  96. return None
  97. def get_all_paragraphs(root: ET.Element) -> list[ET.Element]:
  98. """Return all w:p elements in document order."""
  99. return root.findall('.//' + _w('p'))
  100. def _w(tag: str) -> str:
  101. """Shorthand for word namespace tag."""
  102. return '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' + tag
  103. def get_paragraph_text(para: ET.Element) -> str:
  104. """Extract concatenated text from all w:t elements in a paragraph."""
  105. texts = []
  106. for t in para.findall('.//' + _w('t')):
  107. if t.text:
  108. texts.append(t.text)
  109. return ''.join(texts)
  110. def get_paragraph_style(para: ET.Element) -> str | None:
  111. """Get the pStyle val from a paragraph, or None."""
  112. pPr = para.find(_w('pPr'))
  113. if pPr is None:
  114. return None
  115. pStyle = pPr.find(_w('pStyle'))
  116. if pStyle is None:
  117. return None
  118. return pStyle.get(_w('val'))
  119. def is_heading_style(style_val: str | None) -> bool:
  120. """Check if a style value is a standard heading style."""
  121. if style_val is None:
  122. return False
  123. lower = style_val.lower().strip()
  124. # Check direct matches
  125. if lower in STANDARD_HEADING_STYLES:
  126. return True
  127. # Check "Heading" prefix pattern (e.g. "Heading1", "Heading 2")
  128. if lower.startswith('heading'):
  129. return True
  130. # Numeric style IDs sometimes used for headings
  131. if lower in ('1', '2', '3', '4'):
  132. return True
  133. return False
  134. def is_any_heading_style(style_val: str | None) -> bool:
  135. """Check if a style looks like any heading (standard or custom with 'heading')."""
  136. if style_val is None:
  137. return False
  138. lower = style_val.lower().strip()
  139. return lower.startswith('heading') or lower in ('1', '2', '3', '4')
  140. def is_standard_heading_style(style_val: str | None) -> bool:
  141. """Check if a style is specifically a standard Heading1-4."""
  142. if style_val is None:
  143. return False
  144. lower = style_val.lower().strip()
  145. return lower in {'heading1', 'heading2', 'heading3', 'heading4',
  146. 'heading 1', 'heading 2', 'heading 3', 'heading 4'}
  147. def paragraph_is_bold_large(para: ET.Element) -> bool:
  148. """Check if a paragraph has bold text and large font (≥28 half-points / 14pt).
  149. Checks both paragraph-level and run-level properties.
  150. """
  151. is_bold = False
  152. is_large = False
  153. # Check paragraph-level properties
  154. pPr = para.find(_w('pPr'))
  155. if pPr is not None:
  156. rPr = pPr.find(_w('rPr'))
  157. if rPr is not None:
  158. b = rPr.find(_w('b'))
  159. if b is not None:
  160. b_val = b.get(_w('val'))
  161. if b_val is None or b_val.lower() not in ('false', '0', 'off'):
  162. is_bold = True
  163. sz = rPr.find(_w('sz'))
  164. if sz is not None:
  165. try:
  166. size = int(sz.get(_w('val'), '0'))
  167. if size >= 28:
  168. is_large = True
  169. except (ValueError, TypeError):
  170. pass
  171. # Check run-level properties
  172. for run in para.findall(_w('r')):
  173. rPr = run.find(_w('rPr'))
  174. if rPr is None:
  175. continue
  176. b = rPr.find(_w('b'))
  177. if b is not None:
  178. b_val = b.get(_w('val'))
  179. if b_val is None or b_val.lower() not in ('false', '0', 'off'):
  180. is_bold = True
  181. sz = rPr.find(_w('sz'))
  182. if sz is not None:
  183. try:
  184. size = int(sz.get(_w('val'), '0'))
  185. if size >= 28:
  186. is_large = True
  187. except (ValueError, TypeError):
  188. pass
  189. return is_bold and is_large
  190. def docx_has_toc_field(root: ET.Element) -> bool:
  191. """Check if the document has a TOC field code.
  192. Looks for:
  193. - <w:fldSimple> with w:instr containing "TOC"
  194. - <w:instrText> containing "TOC"
  195. """
  196. # Check fldSimple
  197. for fld in root.findall('.//' + _w('fldSimple')):
  198. instr = fld.get(_w('instr'), '')
  199. if 'TOC' in instr.upper():
  200. return True
  201. # Check instrText
  202. for instr in root.findall('.//' + _w('instrText')):
  203. if instr.text and 'TOC' in instr.text.upper():
  204. return True
  205. return False
  206. def find_toc_field_boundaries(root: ET.Element) -> tuple[ET.Element | None, ET.Element | None, ET.Element | None]:
  207. """Find the TOC field begin/separate/end fldChar elements.
  208. Returns (begin_elem, separate_elem, end_elem) — any may be None.
  209. We search for the TOC instrText and then find the corresponding
  210. fldChar markers.
  211. """
  212. body = root.find(_w('body'))
  213. if body is None:
  214. return None, None, None
  215. all_paragraphs = list(body) # Direct children of body
  216. # Flatten all runs across all paragraphs to find field structure
  217. # We need to track field nesting to find the right begin/separate/end
  218. in_toc_field = False
  219. toc_begin_para_idx = None
  220. toc_separate_para_idx = None
  221. toc_end_para_idx = None
  222. field_depth = 0
  223. for para_idx, elem in enumerate(all_paragraphs):
  224. if elem.tag != _w('p'):
  225. continue
  226. for run in elem.findall(_w('r')):
  227. # Check for instrText with TOC
  228. instr = run.find(_w('instrText'))
  229. if instr is not None and instr.text and 'TOC' in instr.text.upper():
  230. in_toc_field = True
  231. fldChar = run.find(_w('fldChar'))
  232. if fldChar is not None:
  233. fld_type = fldChar.get(_w('fldCharType'), '')
  234. if fld_type == 'begin':
  235. field_depth += 1
  236. if not in_toc_field and toc_begin_para_idx is None:
  237. # Mark tentatively; will confirm when we see instrText
  238. pass
  239. if in_toc_field and toc_begin_para_idx is None:
  240. toc_begin_para_idx = para_idx
  241. elif fld_type == 'separate':
  242. if in_toc_field and toc_separate_para_idx is None:
  243. toc_separate_para_idx = para_idx
  244. elif fld_type == 'end':
  245. if in_toc_field and field_depth <= 1:
  246. toc_end_para_idx = para_idx
  247. in_toc_field = False
  248. field_depth = max(0, field_depth - 1)
  249. return toc_begin_para_idx, toc_separate_para_idx, toc_end_para_idx
  250. def find_toc_field_boundaries_v2(root: ET.Element) -> dict[str, Any]:
  251. """Enhanced TOC boundary finder that works with nested fields.
  252. Returns dict with:
  253. 'has_toc': bool
  254. 'begin_para_idx': int or None
  255. 'separate_para_idx': int or None
  256. 'end_para_idx': int or None
  257. 'toc_entry_texts': list of str (text between separate and end)
  258. """
  259. body = root.find(_w('body'))
  260. if body is None:
  261. return {'has_toc': False, 'begin_para_idx': None,
  262. 'separate_para_idx': None, 'end_para_idx': None,
  263. 'toc_entry_texts': []}
  264. paragraphs = [e for e in body if e.tag == _w('p')]
  265. # Phase 1: Find the TOC instrText and its surrounding begin marker
  266. toc_begin_idx = None
  267. toc_separate_idx = None
  268. toc_end_idx = None
  269. # Track all fldChar positions
  270. events = [] # (para_idx, event_type, element)
  271. for pi, para in enumerate(paragraphs):
  272. for run in para.findall('.//' + _w('r')):
  273. fldChar = run.find(_w('fldChar'))
  274. if fldChar is not None:
  275. events.append((pi, fldChar.get(_w('fldCharType'), ''), run))
  276. instr = run.find(_w('instrText'))
  277. if instr is not None and instr.text and 'TOC' in instr.text.upper():
  278. events.append((pi, 'toc_instr', run))
  279. # Find TOC field boundaries using field nesting
  280. depth = 0
  281. found_toc = False
  282. toc_depth = None
  283. begin_stack = [] # Stack of (para_idx, depth)
  284. for pi, evt, run in events:
  285. if evt == 'begin':
  286. depth += 1
  287. begin_stack.append((pi, depth))
  288. elif evt == 'toc_instr':
  289. if not found_toc and begin_stack:
  290. found_toc = True
  291. toc_begin_idx = begin_stack[-1][0]
  292. toc_depth = begin_stack[-1][1]
  293. elif evt == 'separate':
  294. if found_toc and toc_separate_idx is None and depth == toc_depth:
  295. toc_separate_idx = pi
  296. elif evt == 'end':
  297. if found_toc and toc_end_idx is None and depth == toc_depth:
  298. toc_end_idx = pi
  299. depth = max(0, depth - 1)
  300. if begin_stack:
  301. begin_stack.pop()
  302. # Phase 2: Extract TOC entry texts between separate and end
  303. toc_entry_texts = []
  304. if toc_separate_idx is not None and toc_end_idx is not None:
  305. for pi in range(toc_separate_idx, toc_end_idx + 1):
  306. if pi < len(paragraphs):
  307. text = get_paragraph_text(paragraphs[pi]).strip()
  308. if text:
  309. toc_entry_texts.append(text)
  310. return {
  311. 'has_toc': found_toc,
  312. 'begin_para_idx': toc_begin_idx,
  313. 'separate_para_idx': toc_separate_idx,
  314. 'end_para_idx': toc_end_idx,
  315. 'toc_entry_texts': toc_entry_texts,
  316. }
  317. def check_toc_has_content(root: ET.Element, separate_para_idx: int | None,
  318. end_para_idx: int | None) -> bool:
  319. """Check if there are w:t elements between the separate and end markers.
  320. Looks at all paragraphs between the separate and end field char markers.
  321. """
  322. if separate_para_idx is None or end_para_idx is None:
  323. return False
  324. body = root.find(_w('body'))
  325. if body is None:
  326. return False
  327. paragraphs = [e for e in body if e.tag == _w('p')]
  328. for pi in range(separate_para_idx, min(end_para_idx + 1, len(paragraphs))):
  329. para = paragraphs[pi]
  330. for t in para.findall('.//' + _w('t')):
  331. if t.text and t.text.strip():
  332. return True
  333. return False
  334. def fuzzy_match(text_a: str, text_b: str) -> bool:
  335. """Check if two strings match fuzzily.
  336. Match if one contains the other, or they share >60% of characters.
  337. """
  338. a = text_a.strip().lower()
  339. b = text_b.strip().lower()
  340. if not a or not b:
  341. return False
  342. # One contains the other
  343. if a in b or b in a:
  344. return True
  345. # Character overlap >60%
  346. set_a = set(a)
  347. set_b = set(b)
  348. if not set_a or not set_b:
  349. return False
  350. intersection = set_a & set_b
  351. union = set_a | set_b
  352. similarity = len(intersection) / len(union)
  353. return similarity > 0.6
  354. def _detect_language(texts: list) -> str:
  355. """Detect the primary language of a list of text strings.
  356. Returns 'zh' if more than half contain Chinese characters, else 'en'.
  357. """
  358. if not texts:
  359. return 'en'
  360. total = len(texts)
  361. chinese_count = sum(1 for t in texts if re.search(r'[\u4e00-\u9fff]', t))
  362. return 'zh' if chinese_count > total / 2 else 'en'
  363. def _get_heading_level(style_val: str | None) -> int:
  364. """Extract heading level (1-9) from a style value. Returns 0 if not a heading."""
  365. if style_val is None:
  366. return 0
  367. lower = style_val.lower().strip()
  368. # "heading1", "heading 1", "heading2", etc.
  369. m = re.match(r'heading\s*(\d+)', lower)
  370. if m:
  371. return int(m.group(1))
  372. # Numeric style IDs
  373. if lower in ('1', '2', '3', '4', '5', '6', '7', '8', '9'):
  374. return int(lower)
  375. return 0
  376. def check_run_hint_style(run: ET.Element) -> tuple[bool, bool]:
  377. """Check if a run has gray color and small font size.
  378. Returns (has_gray_color, has_small_font).
  379. """
  380. has_gray = False
  381. has_small = False
  382. rPr = run.find(_w('rPr'))
  383. if rPr is None:
  384. return False, False
  385. color = rPr.find(_w('color'))
  386. if color is not None:
  387. val = color.get(_w('val'), '').lower()
  388. if val in GRAY_COLORS:
  389. has_gray = True
  390. # Also check if it's any gray-ish color (same R, G, B values or close)
  391. if len(val) == 6:
  392. try:
  393. r = int(val[0:2], 16)
  394. g = int(val[2:4], 16)
  395. b = int(val[4:6], 16)
  396. # Gray if R, G, B are all close to each other and in mid-range
  397. if (abs(r - g) < 30 and abs(g - b) < 30 and abs(r - b) < 30
  398. and 80 <= r <= 210):
  399. has_gray = True
  400. except ValueError:
  401. pass
  402. sz = rPr.find(_w('sz'))
  403. if sz is not None:
  404. try:
  405. size = int(sz.get(_w('val'), '0'))
  406. if size <= 18: # 18 half-points = 9pt
  407. has_small = True
  408. except (ValueError, TypeError):
  409. pass
  410. return has_gray, has_small
  411. # ---------------------------------------------------------------------------
  412. # check-docx implementation
  413. # ---------------------------------------------------------------------------
  414. def check_docx(docx_path: str) -> dict[str, Any]:
  415. """Run all DOCX TOC validation checks.
  416. Returns the result dict.
  417. """
  418. errors: list[dict] = []
  419. warnings: list[dict] = []
  420. info: list[dict] = []
  421. source = os.path.basename(docx_path)
  422. # Parse document.xml
  423. root = parse_docx_xml(docx_path)
  424. if root is None:
  425. return make_result(source, "docx-toc",
  426. [make_item("PARSE_ERROR",
  427. "Failed to parse DOCX file. File may be corrupted.",
  428. "error")],
  429. [], [])
  430. body = root.find(_w('body'))
  431. if body is None:
  432. return make_result(source, "docx-toc", [], [],
  433. [make_item("EMPTY_BODY",
  434. "Document body is empty.",
  435. "info")])
  436. paragraphs = [e for e in body if e.tag == _w('p')]
  437. # Detect TOC field boundaries
  438. toc_info = find_toc_field_boundaries_v2(root)
  439. has_toc = toc_info['has_toc']
  440. toc_begin_idx = toc_info['begin_para_idx']
  441. toc_separate_idx = toc_info['separate_para_idx']
  442. toc_end_idx = toc_info['end_para_idx']
  443. toc_entry_texts = toc_info['toc_entry_texts']
  444. # Also check for fldSimple-based TOC
  445. if not has_toc:
  446. for fld in root.findall('.//' + _w('fldSimple')):
  447. instr = fld.get(_w('instr'), '')
  448. if 'TOC' in instr.upper():
  449. has_toc = True
  450. break
  451. # Also check for SDT-wrapped TOC (e.g. generated by fix-docx)
  452. if not has_toc:
  453. if docx_has_toc_field(root):
  454. has_toc = True
  455. # Count headings (all paragraphs with heading styles)
  456. all_heading_paras = []
  457. for pi, para in enumerate(paragraphs):
  458. style = get_paragraph_style(para)
  459. if is_any_heading_style(style):
  460. all_heading_paras.append((pi, para, style))
  461. # Content headings: headings AFTER the TOC end (or all if no TOC)
  462. content_heading_paras = []
  463. if toc_end_idx is not None:
  464. for pi, para, style in all_heading_paras:
  465. if pi > toc_end_idx:
  466. content_heading_paras.append((pi, para, style))
  467. else:
  468. content_heading_paras = list(all_heading_paras)
  469. # ---- CHECK 1: TOC_FIELD_MISSING ----
  470. heading_count = len(all_heading_paras)
  471. if heading_count >= 3 and not has_toc:
  472. warnings.append(make_item(
  473. "TOC_FIELD_MISSING",
  474. f"Document has {heading_count} headings but no Table of Contents.",
  475. "warning"
  476. ))
  477. # ---- CHECK 2: TOC_PLACEHOLDER_EMPTY ----
  478. if has_toc and toc_separate_idx is not None and toc_end_idx is not None:
  479. has_content = check_toc_has_content(root, toc_separate_idx, toc_end_idx)
  480. if not has_content:
  481. errors.append(make_item(
  482. "TOC_PLACEHOLDER_EMPTY",
  483. "TOC field exists but has no placeholder entries. Run add_toc_placeholders.py.",
  484. "error"
  485. ))
  486. # ---- CHECK 3: TOC_HEADING_STYLE ----
  487. # Scan ALL paragraphs after TOC (not just those in content_heading_paras)
  488. # to catch bold+large paragraphs with non-heading styles that TOC won't see.
  489. if has_toc:
  490. start_idx = (toc_end_idx + 1) if toc_end_idx is not None else 0
  491. for pi in range(start_idx, len(paragraphs)):
  492. para = paragraphs[pi]
  493. style = get_paragraph_style(para)
  494. if paragraph_is_bold_large(para) and not is_standard_heading_style(style):
  495. text = get_paragraph_text(para).strip()
  496. if text:
  497. truncated = text[:50] + ('...' if len(text) > 50 else '')
  498. style_name = style if style else '(none)'
  499. errors.append(make_item(
  500. "TOC_HEADING_STYLE",
  501. f"Paragraph '{truncated}' uses custom style '{style_name}' "
  502. f"instead of HeadingLevel. TOC will not pick it up.",
  503. "error"
  504. ))
  505. # ---- CHECK 4: TOC_ENTRY_MISMATCH ----
  506. if toc_entry_texts and content_heading_paras:
  507. heading_texts = [get_paragraph_text(para).strip()
  508. for _, para, _ in content_heading_paras
  509. if get_paragraph_text(para).strip()]
  510. if heading_texts:
  511. unmatched = 0
  512. for ht in heading_texts:
  513. matched = any(fuzzy_match(ht, et) for et in toc_entry_texts)
  514. if not matched:
  515. unmatched += 1
  516. match_ratio = (len(heading_texts) - unmatched) / len(heading_texts)
  517. if match_ratio < 0.5:
  518. errors.append(make_item(
  519. "TOC_ENTRY_MISMATCH",
  520. f"TOC placeholder entries don't match actual headings. "
  521. f"{unmatched} of {len(heading_texts)} headings not found in TOC.",
  522. "error"
  523. ))
  524. # ---- CHECK 5: TOC_NO_PAGEBREAK ----
  525. if toc_end_idx is not None:
  526. found_pagebreak = False
  527. # Check up to 2 paragraphs after TOC end
  528. check_end = min(toc_end_idx + 3, len(paragraphs))
  529. for pi in range(toc_end_idx, check_end):
  530. para = paragraphs[pi]
  531. # Check for <w:br w:type="page"/>
  532. for br in para.findall('.//' + _w('br')):
  533. if br.get(_w('type')) == 'page':
  534. found_pagebreak = True
  535. break
  536. # Check for <w:lastRenderedPageBreak/>
  537. if para.findall('.//' + _w('lastRenderedPageBreak')):
  538. found_pagebreak = True
  539. if found_pagebreak:
  540. break
  541. if not found_pagebreak:
  542. warnings.append(make_item(
  543. "TOC_NO_PAGEBREAK",
  544. "No page break found after TOC. Content may run into the table of contents.",
  545. "warning"
  546. ))
  547. # ---- CHECK 6: TOC_HINT_STYLE ----
  548. for para in paragraphs:
  549. text = get_paragraph_text(para).strip()
  550. has_hint = any(indicator in text for indicator in HINT_INDICATORS)
  551. if has_hint:
  552. # Check if runs containing hint text are properly styled
  553. properly_styled = True
  554. for run in para.findall(_w('r')):
  555. run_text = ''
  556. for t in run.findall(_w('t')):
  557. if t.text:
  558. run_text += t.text
  559. if any(ind in run_text for ind in HINT_INDICATORS):
  560. has_gray, has_small = check_run_hint_style(run)
  561. if not (has_gray and has_small):
  562. properly_styled = False
  563. break
  564. if not properly_styled:
  565. warnings.append(make_item(
  566. "TOC_HINT_STYLE",
  567. "TOC hint text found but not styled as gray/small. "
  568. "It may look like regular content.",
  569. "warning"
  570. ))
  571. break # Only report once
  572. return make_result(source, "docx-toc", errors, warnings, info)
  573. # ---------------------------------------------------------------------------
  574. # check-pdf implementation
  575. # ---------------------------------------------------------------------------
  576. def check_pdf(pdf_path: str) -> dict[str, Any]:
  577. """Run all PDF TOC validation checks.
  578. Returns the result dict.
  579. """
  580. errors: list[dict] = []
  581. warnings: list[dict] = []
  582. info: list[dict] = []
  583. source = os.path.basename(pdf_path)
  584. try:
  585. import pdfplumber
  586. except ImportError:
  587. return make_result(source, "pdf-toc",
  588. [make_item("DEPENDENCY_MISSING",
  589. "pdfplumber is not installed. Run: \"$(command -v zcode-python || command -v python3)\" -m pip install pdfplumber",
  590. "error")],
  591. [], [])
  592. try:
  593. pdf = pdfplumber.open(pdf_path)
  594. except Exception as e:
  595. return make_result(source, "pdf-toc",
  596. [make_item("PARSE_ERROR",
  597. f"Failed to open PDF: {str(e)[:100]}",
  598. "error")],
  599. [], [])
  600. total_pages = len(pdf.pages)
  601. if total_pages == 0:
  602. pdf.close()
  603. return make_result(source, "pdf-toc", [], [],
  604. [make_item("EMPTY_PDF", "PDF has no pages.", "info")])
  605. # Extract text from first 5 pages (or all if <5)
  606. check_pages = min(5, total_pages)
  607. page_texts = {}
  608. for i in range(check_pages):
  609. try:
  610. text = pdf.pages[i].extract_text() or ''
  611. except Exception:
  612. text = ''
  613. page_texts[i] = text
  614. # ---- CHECK 1: TOC_NOT_FOUND ----
  615. toc_pages = []
  616. for page_idx, text in page_texts.items():
  617. text_lower = text.lower()
  618. for kw in TOC_KEYWORDS:
  619. if kw.lower() in text_lower:
  620. toc_pages.append(page_idx)
  621. break
  622. if not toc_pages and total_pages > 5:
  623. warnings.append(make_item(
  624. "TOC_NOT_FOUND",
  625. f"No TOC detected in first 5 pages of a {total_pages}-page document.",
  626. "warning"
  627. ))
  628. # ---- CHECK 1b: TOC_ON_FIRST_PAGE ----
  629. # If TOC appears on page 1, it likely means either:
  630. # (a) there is no cover page before the TOC, or
  631. # (b) the TOC and body content are not separated by a page break
  632. if toc_pages and 0 in toc_pages and total_pages > 1:
  633. errors.append(make_item(
  634. "TOC_ON_FIRST_PAGE",
  635. "TOC detected on page 1. A cover page should precede the TOC "
  636. "(expected structure: Cover → TOC → Content). "
  637. "Either the cover page is missing or the TOC was not separated by a page break.",
  638. "error"
  639. ))
  640. # ---- CHECK 2 & 3 & 4: TOC entry analysis ----
  641. # Regex to find lines where the last token is a number (page reference)
  642. entry_pattern = re.compile(r'^(.+?)\s+(\d{1,4})\s*$')
  643. toc_entries = [] # List of (title_text, page_number)
  644. if toc_pages:
  645. for page_idx in toc_pages:
  646. text = page_texts.get(page_idx, '')
  647. for line in text.split('\n'):
  648. line = line.strip()
  649. if not line:
  650. continue
  651. m = entry_pattern.match(line)
  652. if m:
  653. title = m.group(1).strip()
  654. page_num = int(m.group(2))
  655. if 1 <= page_num <= 9999 and title:
  656. toc_entries.append((title, page_num))
  657. if toc_pages:
  658. # CHECK 2: TOC_NO_ENTRIES
  659. if len(toc_entries) < 2:
  660. errors.append(make_item(
  661. "TOC_NO_ENTRIES",
  662. "TOC page found but contains fewer than 2 entries.",
  663. "error"
  664. ))
  665. if toc_entries:
  666. # CHECK 3: TOC_PAGES_INVALID
  667. invalid_entries = []
  668. for title, page_num in toc_entries:
  669. if page_num < 1 or page_num > total_pages:
  670. invalid_entries.append((title, page_num))
  671. for title, page_num in invalid_entries:
  672. truncated = title[:50] + ('...' if len(title) > 50 else '')
  673. errors.append(make_item(
  674. "TOC_PAGES_INVALID",
  675. f"TOC entry '{truncated}' references page {page_num} "
  676. f"but document only has {total_pages} pages.",
  677. "error"
  678. ))
  679. # CHECK 4: TOC_ALL_SAME_PAGE
  680. if len(toc_entries) >= 2:
  681. page_nums = set(pn for _, pn in toc_entries)
  682. if len(page_nums) == 1:
  683. same_page = page_nums.pop()
  684. errors.append(make_item(
  685. "TOC_ALL_SAME_PAGE",
  686. f"All TOC entries point to page {same_page}. "
  687. f"This likely means placeholder page numbers were not updated.",
  688. "error"
  689. ))
  690. # ---- CHECK 5: TOC_LINKS_MISSING ----
  691. if toc_entries and toc_pages:
  692. has_links = False
  693. for page_idx in toc_pages:
  694. try:
  695. page = pdf.pages[page_idx]
  696. # Try annots (annotations)
  697. annots = page.annots
  698. if annots:
  699. has_links = True
  700. break
  701. # Try hyperlinks
  702. hyperlinks = page.hyperlinks
  703. if hyperlinks:
  704. has_links = True
  705. break
  706. except (AttributeError, Exception):
  707. pass
  708. if not has_links:
  709. # Also try pikepdf for more thorough annotation check
  710. try:
  711. import pikepdf
  712. pike_pdf = pikepdf.open(pdf_path)
  713. for page_idx in toc_pages:
  714. if page_idx < len(pike_pdf.pages):
  715. pike_page = pike_pdf.pages[page_idx]
  716. if '/Annots' in pike_page:
  717. annots = pike_page['/Annots']
  718. if len(annots) > 0:
  719. has_links = True
  720. break
  721. pike_pdf.close()
  722. except (ImportError, Exception):
  723. pass
  724. if not has_links:
  725. warnings.append(make_item(
  726. "TOC_LINKS_MISSING",
  727. "TOC entries found but no clickable links detected.",
  728. "warning"
  729. ))
  730. pdf.close()
  731. return make_result(source, "pdf-toc", errors, warnings, info)
  732. # ---------------------------------------------------------------------------
  733. # check-conversion implementation
  734. # ---------------------------------------------------------------------------
  735. def check_conversion(docx_path: str, pdf_path: str) -> dict[str, Any]:
  736. """Run DOCX→PDF conversion TOC consistency checks.
  737. Returns the result dict.
  738. """
  739. errors: list[dict] = []
  740. warnings: list[dict] = []
  741. info: list[dict] = []
  742. source = f"{os.path.basename(docx_path)} → {os.path.basename(pdf_path)}"
  743. # Parse DOCX
  744. docx_root = parse_docx_xml(docx_path)
  745. if docx_root is None:
  746. return make_result(source, "conversion-toc",
  747. [make_item("PARSE_ERROR",
  748. "Failed to parse source DOCX file.",
  749. "error")],
  750. [], [])
  751. # Check DOCX has TOC
  752. docx_has_toc = docx_has_toc_field(docx_root)
  753. # Parse PDF
  754. try:
  755. import pdfplumber
  756. except ImportError:
  757. return make_result(source, "conversion-toc",
  758. [make_item("DEPENDENCY_MISSING",
  759. "pdfplumber is not installed.",
  760. "error")],
  761. [], [])
  762. try:
  763. pdf = pdfplumber.open(pdf_path)
  764. except Exception as e:
  765. return make_result(source, "conversion-toc",
  766. [make_item("PARSE_ERROR",
  767. f"Failed to open PDF: {str(e)[:100]}",
  768. "error")],
  769. [], [])
  770. total_pages = len(pdf.pages)
  771. # Extract all PDF text
  772. all_pdf_text = ''
  773. page_texts = {}
  774. for i in range(total_pages):
  775. try:
  776. text = pdf.pages[i].extract_text() or ''
  777. except Exception:
  778. text = ''
  779. page_texts[i] = text
  780. all_pdf_text += text + '\n'
  781. # Find TOC pages in PDF
  782. toc_pages = []
  783. check_pages = min(5, total_pages)
  784. for i in range(check_pages):
  785. text_lower = page_texts.get(i, '').lower()
  786. for kw in TOC_KEYWORDS:
  787. if kw.lower() in text_lower:
  788. toc_pages.append(i)
  789. break
  790. pdf_has_toc = len(toc_pages) > 0
  791. # ---- CHECK 1: CONV_TOC_LOST ----
  792. if docx_has_toc and not pdf_has_toc and total_pages > 5:
  793. errors.append(make_item(
  794. "CONV_TOC_LOST",
  795. "Source DOCX has TOC but converted PDF does not. "
  796. "TOC was lost during conversion.",
  797. "error"
  798. ))
  799. # ---- CHECK 2: CONV_HINT_LEAKED ----
  800. all_text_lower = all_pdf_text.lower()
  801. for phrase in HINT_PHRASES:
  802. if phrase.lower() in all_text_lower:
  803. # Find the actual matched text (up to 60 chars)
  804. idx = all_text_lower.index(phrase.lower())
  805. matched = all_pdf_text[idx:idx + len(phrase)]
  806. truncated = matched[:60] + ('...' if len(matched) > 60 else '')
  807. errors.append(make_item(
  808. "CONV_HINT_LEAKED",
  809. f"TOC hint text leaked into PDF: '{truncated}'. "
  810. f"Clean hints before conversion.",
  811. "error"
  812. ))
  813. break # Report only the first match
  814. # ---- CHECK 3: CONV_HEADING_DRIFT ----
  815. # Count DOCX headings
  816. body = docx_root.find(_w('body'))
  817. docx_heading_count = 0
  818. if body is not None:
  819. for para in body:
  820. if para.tag != _w('p'):
  821. continue
  822. style = get_paragraph_style(para)
  823. if is_any_heading_style(style):
  824. docx_heading_count += 1
  825. # Count PDF TOC entries
  826. entry_pattern = re.compile(r'^(.+?)\s+(\d{1,4})\s*$')
  827. pdf_toc_entry_count = 0
  828. if toc_pages:
  829. for page_idx in toc_pages:
  830. text = page_texts.get(page_idx, '')
  831. for line in text.split('\n'):
  832. line = line.strip()
  833. if not line:
  834. continue
  835. m = entry_pattern.match(line)
  836. if m:
  837. page_num = int(m.group(2))
  838. if 1 <= page_num <= 9999:
  839. pdf_toc_entry_count += 1
  840. if docx_heading_count > 0 and pdf_toc_entry_count > 0:
  841. drift = abs(docx_heading_count - pdf_toc_entry_count)
  842. drift_pct = (drift / docx_heading_count) * 100
  843. if drift_pct > 30:
  844. warnings.append(make_item(
  845. "CONV_HEADING_DRIFT",
  846. f"DOCX has {docx_heading_count} headings but PDF TOC has "
  847. f"{pdf_toc_entry_count} entries ({drift_pct:.0f}% drift).",
  848. "warning"
  849. ))
  850. pdf.close()
  851. return make_result(source, "conversion-toc", errors, warnings, info)
  852. # ---------------------------------------------------------------------------
  853. # fix-docx implementation
  854. # ---------------------------------------------------------------------------
  855. def _find_toc_sdt_indices(body_elem) -> list[int]:
  856. """Find indices of SDT elements in body that contain TOC.
  857. Returns list of indices into body's direct children.
  858. """
  859. indices = []
  860. for idx, child in enumerate(body_elem):
  861. if child.tag == '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}sdt':
  862. # Check if this SDT contains TOC-related content
  863. for instr in child.findall('.//' + _w('instrText')):
  864. if instr.text and 'TOC' in instr.text.upper():
  865. indices.append(idx)
  866. break
  867. else:
  868. # Also check alias/tag
  869. sdtPr = child.find('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}sdtPr')
  870. if sdtPr is not None:
  871. alias = sdtPr.find('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}alias')
  872. if alias is not None and alias.get(_w('val'), '').upper() in ('TOC', '目录'):
  873. indices.append(idx)
  874. continue
  875. docPartObj = sdtPr.find('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}docPartObj')
  876. if docPartObj is not None:
  877. docPartGallery = docPartObj.find('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}docPartGallery')
  878. if docPartGallery is not None and 'toc' in docPartGallery.get(_w('val'), '').lower():
  879. indices.append(idx)
  880. return indices
  881. def _find_toc_field_para_range(body_elem) -> tuple[int | None, int | None]:
  882. """Find the range of paragraph indices that make up a TOC field code block.
  883. Returns (start_idx, end_idx) inclusive, or (None, None) if not found.
  884. These are indices into body's direct children.
  885. """
  886. children = list(body_elem)
  887. in_toc = False
  888. toc_depth = None
  889. depth = 0
  890. start_idx = None
  891. end_idx = None
  892. for ci, child in enumerate(children):
  893. if child.tag != _w('p'):
  894. continue
  895. for run in child.findall('.//' + _w('r')):
  896. instr = run.find(_w('instrText'))
  897. if instr is not None and instr.text and 'TOC' in instr.text.upper():
  898. in_toc = True
  899. fldChar = run.find(_w('fldChar'))
  900. if fldChar is not None:
  901. fld_type = fldChar.get(_w('fldCharType'), '')
  902. if fld_type == 'begin':
  903. depth += 1
  904. if in_toc and start_idx is None:
  905. # The begin was before instrText; look back
  906. start_idx = ci
  907. toc_depth = depth
  908. elif not in_toc and start_idx is None:
  909. # tentative; may become TOC if instrText follows
  910. pass
  911. elif fld_type == 'end':
  912. if in_toc and depth == toc_depth:
  913. end_idx = ci
  914. in_toc = False
  915. depth = max(0, depth - 1)
  916. # If we found instrText but start_idx wasn't set (begin was in the same para before instrText)
  917. # Re-scan more carefully
  918. if in_toc and start_idx is None:
  919. # Fall back to find_toc_field_boundaries_v2 style
  920. pass
  921. return start_idx, end_idx
  922. def fix_docx(docx_path: str, output_path: str | None = None) -> dict[str, Any]:
  923. """Detect TOC issues in a DOCX and fix them, outputting a new DOCX file.
  924. Returns the result dict.
  925. """
  926. from docx import Document as DocxDocument
  927. from docx.oxml import OxmlElement
  928. from docx.oxml.ns import qn
  929. errors: list[dict] = []
  930. warnings: list[dict] = []
  931. info_list: list[dict] = []
  932. source = os.path.basename(docx_path)
  933. if output_path is None:
  934. base, ext = os.path.splitext(docx_path)
  935. output_path = base + '_fixed' + ext
  936. # Parse using low-level XML for analysis
  937. root = parse_docx_xml(docx_path)
  938. if root is None:
  939. return {
  940. "pass": False, "source": source, "check_type": "fix-docx",
  941. "action": "failed", "reason": "Failed to parse DOCX file",
  942. "heading_count": 0, "toc_entries_before": 0, "toc_entries_after": 0,
  943. "output": output_path,
  944. "errors": [make_item("PARSE_ERROR", "Failed to parse DOCX", "error")],
  945. "warnings": [], "info": []
  946. }
  947. body = root.find(_w('body'))
  948. if body is None:
  949. return {
  950. "pass": False, "source": source, "check_type": "fix-docx",
  951. "action": "failed", "reason": "Document body is empty",
  952. "heading_count": 0, "toc_entries_before": 0, "toc_entries_after": 0,
  953. "output": output_path,
  954. "errors": [make_item("EMPTY_BODY", "Document body is empty", "error")],
  955. "warnings": [], "info": []
  956. }
  957. paragraphs = [e for e in body if e.tag == _w('p')]
  958. # Extract headings
  959. headings = [] # list of (para_index_in_body, text, level)
  960. body_children = list(body)
  961. para_to_body_idx = {} # map paragraph element to body child index
  962. pi = 0
  963. caption_filter = re.compile(r'^[表图]\s*\d')
  964. for ci, child in enumerate(body_children):
  965. if child.tag == _w('p'):
  966. para_to_body_idx[id(child)] = ci
  967. style = get_paragraph_style(child)
  968. if is_any_heading_style(style):
  969. text = get_paragraph_text(child).strip()
  970. level = _get_heading_level(style)
  971. if text and level > 0:
  972. # Skip table/figure captions styled as headings
  973. if caption_filter.match(text):
  974. continue
  975. headings.append((ci, text, level))
  976. pi += 1
  977. heading_count = len(headings)
  978. heading_texts = [h[1] for h in headings]
  979. # Get TOC info
  980. toc_info = find_toc_field_boundaries_v2(root)
  981. has_toc = toc_info['has_toc']
  982. toc_entry_texts = toc_info['toc_entry_texts']
  983. toc_entries_before = len(toc_entry_texts)
  984. # Also check for SDT-based TOC
  985. sdt_indices = _find_toc_sdt_indices(body)
  986. has_sdt_toc = len(sdt_indices) > 0
  987. has_any_toc = has_toc or has_sdt_toc
  988. # If SDT TOC, extract text from it for analysis
  989. if has_sdt_toc and not toc_entry_texts:
  990. for si in sdt_indices:
  991. sdt_elem = body_children[si]
  992. for t in sdt_elem.findall('.//' + _w('t')):
  993. if t.text and t.text.strip():
  994. toc_entry_texts.append(t.text.strip())
  995. toc_entries_before = len(toc_entry_texts)
  996. # ---- Decision logic ----
  997. # Case 1: No TOC exists
  998. if not has_any_toc:
  999. if heading_count < 3:
  1000. return {
  1001. "pass": True, "source": source, "check_type": "fix-docx",
  1002. "action": "no_toc_needed",
  1003. "reason": f"Document has only {heading_count} headings, no TOC needed",
  1004. "heading_count": heading_count,
  1005. "toc_entries_before": 0, "toc_entries_after": 0,
  1006. "output": output_path,
  1007. "errors": [], "warnings": [],
  1008. "info": [f"Document has {heading_count} headings (< 3), no TOC needed"]
  1009. }
  1010. else:
  1011. # Need to generate TOC
  1012. info_list.append(f"No TOC found, generating new TOC with {heading_count} entries")
  1013. need_fix = True
  1014. fix_reason = "no_toc"
  1015. toc_insert_body_idx = None # Will determine below
  1016. else:
  1017. # Case 2 & 3: TOC exists, check if it's stale/placeholder
  1018. need_fix = False
  1019. fix_reason = ""
  1020. # Check for empty TOC
  1021. non_empty_entries = [t for t in toc_entry_texts if t.strip()]
  1022. if not non_empty_entries:
  1023. need_fix = True
  1024. fix_reason = "empty_toc"
  1025. info_list.append("TOC exists but has no text content (uninitialized)")
  1026. else:
  1027. # Language mismatch check
  1028. heading_lang = _detect_language(heading_texts)
  1029. toc_lang = _detect_language(non_empty_entries)
  1030. if heading_lang != toc_lang and heading_count >= 3:
  1031. need_fix = True
  1032. fix_reason = "language_mismatch"
  1033. info_list.append(
  1034. f"Deleted stale TOC with {toc_entries_before} "
  1035. f"{'English' if toc_lang == 'en' else 'Chinese'} placeholder entries"
  1036. )
  1037. # Count mismatch check (>50% difference)
  1038. if not need_fix and heading_count > 0:
  1039. diff = abs(heading_count - toc_entries_before)
  1040. if diff / heading_count > 0.5:
  1041. need_fix = True
  1042. fix_reason = "count_mismatch"
  1043. info_list.append(
  1044. f"TOC has {toc_entries_before} entries but document has "
  1045. f"{heading_count} headings (>{50}% drift)"
  1046. )
  1047. if not need_fix:
  1048. # TOC looks OK
  1049. return {
  1050. "pass": True, "source": source, "check_type": "fix-docx",
  1051. "action": "skipped",
  1052. "reason": "TOC appears to be up-to-date",
  1053. "heading_count": heading_count,
  1054. "toc_entries_before": toc_entries_before,
  1055. "toc_entries_after": toc_entries_before,
  1056. "output": output_path,
  1057. "errors": [], "warnings": [],
  1058. "info": ["TOC entries and headings are consistent, no fix needed"]
  1059. }
  1060. # ---- Perform the fix using python-docx ----
  1061. try:
  1062. doc = DocxDocument(docx_path)
  1063. except Exception as e:
  1064. return {
  1065. "pass": False, "source": source, "check_type": "fix-docx",
  1066. "action": "failed", "reason": f"Failed to open DOCX with python-docx: {str(e)[:200]}",
  1067. "heading_count": heading_count,
  1068. "toc_entries_before": toc_entries_before, "toc_entries_after": 0,
  1069. "output": output_path,
  1070. "errors": [make_item("OPEN_ERROR", f"Failed to open: {str(e)[:200]}", "error")],
  1071. "warnings": [], "info": []
  1072. }
  1073. doc_body = doc.element.body
  1074. doc_children = list(doc_body)
  1075. # Determine language for TOC title
  1076. content_lang = _detect_language(heading_texts)
  1077. toc_title = "目 录" if content_lang == 'zh' else "Table of Contents"
  1078. # Re-extract headings from the python-docx document for consistency
  1079. doc_headings = [] # (element_index, text, level)
  1080. # Pattern to filter out table/figure captions styled as headings
  1081. caption_re = re.compile(r'^[表图]\s*\d')
  1082. for ci, child in enumerate(doc_children):
  1083. if child.tag == qn('w:p'):
  1084. pPr = child.find(qn('w:pPr'))
  1085. if pPr is not None:
  1086. pStyle = pPr.find(qn('w:pStyle'))
  1087. if pStyle is not None:
  1088. style_val = pStyle.get(qn('w:val'))
  1089. if is_any_heading_style(style_val):
  1090. text_parts = []
  1091. for t in child.findall('.//' + qn('w:t')):
  1092. if t.text:
  1093. text_parts.append(t.text)
  1094. text = ''.join(text_parts).strip()
  1095. level = _get_heading_level(style_val)
  1096. if text and level > 0:
  1097. # Skip table/figure captions (e.g. "表 1:xxx", "图 2:xxx")
  1098. if caption_re.match(text):
  1099. continue
  1100. doc_headings.append((ci, text, level))
  1101. if not doc_headings:
  1102. return {
  1103. "pass": True, "source": source, "check_type": "fix-docx",
  1104. "action": "no_toc_needed",
  1105. "reason": "No headings found in document after re-parse",
  1106. "heading_count": 0,
  1107. "toc_entries_before": toc_entries_before, "toc_entries_after": 0,
  1108. "output": output_path,
  1109. "errors": [], "warnings": [],
  1110. "info": ["No headings found, skipping TOC generation"]
  1111. }
  1112. # Step 1: Remove existing TOC (SDT or field code range)
  1113. insert_before_idx = None
  1114. # Remove SDT-based TOC
  1115. sdt_removed = False
  1116. for child in list(doc_body):
  1117. if child.tag == qn('w:sdt'):
  1118. is_toc_sdt = False
  1119. for instr in child.findall('.//' + qn('w:instrText')):
  1120. if instr.text and 'TOC' in instr.text.upper():
  1121. is_toc_sdt = True
  1122. break
  1123. if not is_toc_sdt:
  1124. sdtPr = child.find(qn('w:sdtPr'))
  1125. if sdtPr is not None:
  1126. alias = sdtPr.find(qn('w:alias'))
  1127. if alias is not None and alias.get(qn('w:val'), '').upper() in ('TOC', '目录'):
  1128. is_toc_sdt = True
  1129. docPartObj = sdtPr.find(qn('w:docPartObj'))
  1130. if docPartObj is not None:
  1131. dpg = docPartObj.find(qn('w:docPartGallery'))
  1132. if dpg is not None and 'toc' in dpg.get(qn('w:val'), '').lower():
  1133. is_toc_sdt = True
  1134. if is_toc_sdt:
  1135. # Record position
  1136. insert_before_idx = list(doc_body).index(child)
  1137. doc_body.remove(child)
  1138. sdt_removed = True
  1139. # Remove field code TOC (non-SDT)
  1140. if not sdt_removed and has_toc:
  1141. # Find and remove paragraphs that are part of the TOC field
  1142. doc_children_fresh = list(doc_body)
  1143. # Use similar logic to find_toc_field_boundaries_v2 but on python-docx elements
  1144. in_toc = False
  1145. toc_depth = None
  1146. depth = 0
  1147. toc_paras_to_remove = []
  1148. field_begin_idx = None
  1149. for ci, child in enumerate(doc_children_fresh):
  1150. if child.tag != qn('w:p'):
  1151. continue
  1152. for run in child.findall('.//' + qn('w:r')):
  1153. instr = run.find(qn('w:instrText'))
  1154. if instr is not None and instr.text and 'TOC' in instr.text.upper():
  1155. in_toc = True
  1156. fldChar = run.find(qn('w:fldChar'))
  1157. if fldChar is not None:
  1158. fld_type = fldChar.get(qn('w:fldCharType'), '')
  1159. if fld_type == 'begin':
  1160. depth += 1
  1161. if in_toc and field_begin_idx is None:
  1162. field_begin_idx = ci
  1163. toc_depth = depth
  1164. elif fld_type == 'end':
  1165. if in_toc and depth == toc_depth:
  1166. # Mark all paragraphs from begin to end for removal
  1167. if field_begin_idx is not None:
  1168. for ri in range(field_begin_idx, ci + 1):
  1169. toc_paras_to_remove.append(doc_children_fresh[ri])
  1170. in_toc = False
  1171. depth = max(0, depth - 1)
  1172. if toc_paras_to_remove:
  1173. insert_before_idx = list(doc_body).index(toc_paras_to_remove[0])
  1174. for p in toc_paras_to_remove:
  1175. try:
  1176. doc_body.remove(p)
  1177. except ValueError:
  1178. pass
  1179. # Step 2: Determine insertion point
  1180. if insert_before_idx is None:
  1181. # No existing TOC was removed — find the right place to insert
  1182. doc_children_now = list(doc_body)
  1183. first_heading_idx = None
  1184. for ci, child in enumerate(doc_children_now):
  1185. if child.tag == qn('w:p'):
  1186. pPr = child.find(qn('w:pPr'))
  1187. if pPr is not None:
  1188. pStyle = pPr.find(qn('w:pStyle'))
  1189. if pStyle is not None:
  1190. sv = pStyle.get(qn('w:val'))
  1191. if is_any_heading_style(sv):
  1192. first_heading_idx = ci
  1193. break
  1194. if first_heading_idx is not None:
  1195. insert_before_idx = first_heading_idx
  1196. else:
  1197. insert_before_idx = 0
  1198. # Step 3: Build TOC paragraphs as OxmlElements and insert them
  1199. def _make_toc_paragraph(text: str, level: int, lang: str, page_num: str = '1', bookmark_name: str = '') -> Any:
  1200. """Create a TOC entry paragraph with HYPERLINK + PAGEREF for clickable links and auto page numbers."""
  1201. p = OxmlElement('w:p')
  1202. pPr = OxmlElement('w:pPr')
  1203. # TOC style
  1204. toc_style = OxmlElement('w:pStyle')
  1205. toc_style.set(qn('w:val'), f'TOC{level}' if level <= 3 else 'TOC3')
  1206. pPr.append(toc_style)
  1207. # Indentation based on level
  1208. if level >= 2:
  1209. ind = OxmlElement('w:ind')
  1210. indent_twips = (level - 1) * 420
  1211. ind.set(qn('w:left'), str(indent_twips))
  1212. pPr.append(ind)
  1213. # Right-aligned tab stop with dot leader at 9026 twips (~15.9cm)
  1214. tabs = OxmlElement('w:tabs')
  1215. tab = OxmlElement('w:tab')
  1216. tab.set(qn('w:val'), 'right')
  1217. tab.set(qn('w:leader'), 'dot')
  1218. tab.set(qn('w:pos'), '9026')
  1219. tabs.append(tab)
  1220. pPr.append(tabs)
  1221. # Line spacing
  1222. spacing = OxmlElement('w:spacing')
  1223. spacing.set(qn('w:before'), '120')
  1224. spacing.set(qn('w:after'), '60')
  1225. pPr.append(spacing)
  1226. p.append(pPr)
  1227. if bookmark_name:
  1228. # Wrap everything in a hyperlink element pointing to the bookmark
  1229. hyperlink = OxmlElement('w:hyperlink')
  1230. hyperlink.set(qn('w:anchor'), bookmark_name)
  1231. hyperlink.set(qn('w:history'), '1')
  1232. # --- Run 1: heading text ---
  1233. r = OxmlElement('w:r')
  1234. rPr_r = OxmlElement('w:rPr')
  1235. # Style as hyperlink (blue, underline optional)
  1236. rStyle = OxmlElement('w:rStyle')
  1237. rStyle.set(qn('w:val'), 'Hyperlink')
  1238. rPr_r.append(rStyle)
  1239. sz2 = OxmlElement('w:sz')
  1240. szCs2 = OxmlElement('w:szCs')
  1241. if level == 1:
  1242. sz2.set(qn('w:val'), '28')
  1243. szCs2.set(qn('w:val'), '28')
  1244. b2 = OxmlElement('w:b')
  1245. rPr_r.append(b2)
  1246. elif level == 2:
  1247. sz2.set(qn('w:val'), '24')
  1248. szCs2.set(qn('w:val'), '24')
  1249. else:
  1250. sz2.set(qn('w:val'), '22')
  1251. szCs2.set(qn('w:val'), '22')
  1252. rPr_r.append(sz2)
  1253. rPr_r.append(szCs2)
  1254. r.append(rPr_r)
  1255. t = OxmlElement('w:t')
  1256. t.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve')
  1257. t.text = text
  1258. r.append(t)
  1259. hyperlink.append(r)
  1260. # --- Run 2: tab ---
  1261. r_tab = OxmlElement('w:r')
  1262. tab_elem = OxmlElement('w:tab')
  1263. r_tab.append(tab_elem)
  1264. hyperlink.append(r_tab)
  1265. # --- Run 3: PAGEREF field code for auto page number ---
  1266. # fldChar begin
  1267. r_begin = OxmlElement('w:r')
  1268. fldChar_begin = OxmlElement('w:fldChar')
  1269. fldChar_begin.set(qn('w:fldCharType'), 'begin')
  1270. r_begin.append(fldChar_begin)
  1271. hyperlink.append(r_begin)
  1272. # instrText: PAGEREF bookmark_name \h
  1273. r_instr = OxmlElement('w:r')
  1274. instrText = OxmlElement('w:instrText')
  1275. instrText.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve')
  1276. instrText.text = f' PAGEREF {bookmark_name} \\h '
  1277. r_instr.append(instrText)
  1278. hyperlink.append(r_instr)
  1279. # fldChar separate
  1280. r_sep = OxmlElement('w:r')
  1281. fldChar_sep = OxmlElement('w:fldChar')
  1282. fldChar_sep.set(qn('w:fldCharType'), 'separate')
  1283. r_sep.append(fldChar_sep)
  1284. hyperlink.append(r_sep)
  1285. # Page number placeholder text
  1286. r_page = OxmlElement('w:r')
  1287. rPr_page = OxmlElement('w:rPr')
  1288. noProof = OxmlElement('w:noProof')
  1289. rPr_page.append(noProof)
  1290. r_page.append(rPr_page)
  1291. t_page = OxmlElement('w:t')
  1292. t_page.text = str(page_num)
  1293. r_page.append(t_page)
  1294. hyperlink.append(r_page)
  1295. # fldChar end
  1296. r_end = OxmlElement('w:r')
  1297. fldChar_end = OxmlElement('w:fldChar')
  1298. fldChar_end.set(qn('w:fldCharType'), 'end')
  1299. r_end.append(fldChar_end)
  1300. hyperlink.append(r_end)
  1301. p.append(hyperlink)
  1302. else:
  1303. # Fallback: plain text without hyperlink (same as before)
  1304. r = OxmlElement('w:r')
  1305. rPr_r = OxmlElement('w:rPr')
  1306. sz2 = OxmlElement('w:sz')
  1307. szCs2 = OxmlElement('w:szCs')
  1308. if level == 1:
  1309. sz2.set(qn('w:val'), '28')
  1310. szCs2.set(qn('w:val'), '28')
  1311. b2 = OxmlElement('w:b')
  1312. rPr_r.append(b2)
  1313. elif level == 2:
  1314. sz2.set(qn('w:val'), '24')
  1315. szCs2.set(qn('w:val'), '24')
  1316. else:
  1317. sz2.set(qn('w:val'), '22')
  1318. szCs2.set(qn('w:val'), '22')
  1319. rPr_r.append(sz2)
  1320. rPr_r.append(szCs2)
  1321. r.append(rPr_r)
  1322. t = OxmlElement('w:t')
  1323. t.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve')
  1324. t.text = text
  1325. r.append(t)
  1326. p.append(r)
  1327. r_tab = OxmlElement('w:r')
  1328. tab_elem = OxmlElement('w:tab')
  1329. r_tab.append(tab_elem)
  1330. p.append(r_tab)
  1331. r_page = OxmlElement('w:r')
  1332. t_page = OxmlElement('w:t')
  1333. t_page.text = str(page_num)
  1334. r_page.append(t_page)
  1335. p.append(r_page)
  1336. return p
  1337. def _make_toc_title(title_text: str) -> Any:
  1338. """Create the TOC title paragraph (centered, 18pt, bold)."""
  1339. p = OxmlElement('w:p')
  1340. pPr = OxmlElement('w:pPr')
  1341. # Center alignment
  1342. jc = OxmlElement('w:jc')
  1343. jc.set(qn('w:val'), 'center')
  1344. pPr.append(jc)
  1345. # Spacing
  1346. spacing = OxmlElement('w:spacing')
  1347. spacing.set(qn('w:after'), '200')
  1348. spacing.set(qn('w:line'), '360')
  1349. spacing.set(qn('w:lineRule'), 'auto')
  1350. pPr.append(spacing)
  1351. # Run properties
  1352. rPr_p = OxmlElement('w:rPr')
  1353. b = OxmlElement('w:b')
  1354. rPr_p.append(b)
  1355. sz = OxmlElement('w:sz')
  1356. sz.set(qn('w:val'), '36') # 18pt = 36 half-points
  1357. rPr_p.append(sz)
  1358. szCs = OxmlElement('w:szCs')
  1359. szCs.set(qn('w:val'), '36')
  1360. rPr_p.append(szCs)
  1361. pPr.append(rPr_p)
  1362. p.append(pPr)
  1363. # Run with text
  1364. r = OxmlElement('w:r')
  1365. rPr_r = OxmlElement('w:rPr')
  1366. b2 = OxmlElement('w:b')
  1367. rPr_r.append(b2)
  1368. sz2 = OxmlElement('w:sz')
  1369. sz2.set(qn('w:val'), '36')
  1370. rPr_r.append(sz2)
  1371. szCs2 = OxmlElement('w:szCs')
  1372. szCs2.set(qn('w:val'), '36')
  1373. rPr_r.append(szCs2)
  1374. r.append(rPr_r)
  1375. t = OxmlElement('w:t')
  1376. t.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve')
  1377. t.text = title_text
  1378. r.append(t)
  1379. p.append(r)
  1380. return p
  1381. def _make_page_break() -> Any:
  1382. """Create a paragraph with a page break."""
  1383. p = OxmlElement('w:p')
  1384. r = OxmlElement('w:r')
  1385. br = OxmlElement('w:br')
  1386. br.set(qn('w:type'), 'page')
  1387. r.append(br)
  1388. p.append(r)
  1389. return p
  1390. # Build the TOC as an SDT (Structured Document Tag) wrapping a TOC field
  1391. # This ensures check-docx recognizes it and fix-docx can detect/replace it
  1392. def _build_toc_sdt(title_text: str, heading_entries: list, lang: str) -> Any:
  1393. """Build a complete SDT element containing a TOC field with entries."""
  1394. sdt = OxmlElement('w:sdt')
  1395. # SDT properties
  1396. sdtPr = OxmlElement('w:sdtPr')
  1397. alias = OxmlElement('w:alias')
  1398. alias.set(qn('w:val'), 'TOC')
  1399. sdtPr.append(alias)
  1400. # docPartObj with TOC gallery
  1401. docPartObj = OxmlElement('w:docPartObj')
  1402. docPartGallery = OxmlElement('w:docPartGallery')
  1403. docPartGallery.set(qn('w:val'), 'Table of Contents')
  1404. docPartObj.append(docPartGallery)
  1405. docPartUnique = OxmlElement('w:docPartUnique')
  1406. docPartObj.append(docPartUnique)
  1407. sdtPr.append(docPartObj)
  1408. sdt.append(sdtPr)
  1409. # SDT content
  1410. sdtContent = OxmlElement('w:sdtContent')
  1411. # Title paragraph
  1412. sdtContent.append(_make_toc_title(title_text))
  1413. # Field begin paragraph
  1414. p_begin = OxmlElement('w:p')
  1415. r_begin = OxmlElement('w:r')
  1416. fldChar_begin = OxmlElement('w:fldChar')
  1417. fldChar_begin.set(qn('w:fldCharType'), 'begin')
  1418. r_begin.append(fldChar_begin)
  1419. p_begin.append(r_begin)
  1420. r_instr = OxmlElement('w:r')
  1421. instrText = OxmlElement('w:instrText')
  1422. instrText.set('{http://www.w3.org/XML/1998/namespace}space', 'preserve')
  1423. instrText.text = ' TOC \\o "1-3" \\h \\z \\u '
  1424. r_instr.append(instrText)
  1425. p_begin.append(r_instr)
  1426. r_sep = OxmlElement('w:r')
  1427. fldChar_sep = OxmlElement('w:fldChar')
  1428. fldChar_sep.set(qn('w:fldCharType'), 'separate')
  1429. r_sep.append(fldChar_sep)
  1430. p_begin.append(r_sep)
  1431. sdtContent.append(p_begin)
  1432. # TOC entry paragraphs — estimate page numbers based on heading position
  1433. toc_entries = [(i, h_text, h_level) for i, (_, h_text, h_level) in enumerate(heading_entries) if h_level <= 3]
  1434. total_headings = len(toc_entries)
  1435. # TOC itself takes ~2 pages; cover takes ~1 page
  1436. toc_offset = 3 # cover + TOC pages
  1437. # Count body children in the original document to estimate total pages
  1438. # Rough heuristic: ~40 paragraphs per page for typical documents
  1439. doc_body_count = len(list(doc_body))
  1440. estimated_total_pages = max(toc_offset + 1, doc_body_count // 40 + toc_offset)
  1441. # Map each heading to its position ratio in the document
  1442. # Also generate bookmark names for HYPERLINK + PAGEREF
  1443. bookmark_names = []
  1444. for seq, (idx, h_text, h_level) in enumerate(toc_entries):
  1445. # Generate a unique bookmark name for each heading
  1446. bm_name = f'_Toc{100000 + seq}'
  1447. bookmark_names.append(bm_name)
  1448. # Use the heading's body child index to estimate position
  1449. h_body_idx = heading_entries[idx][0] if idx < len(heading_entries) else 0
  1450. if doc_body_count > 0:
  1451. position_ratio = h_body_idx / doc_body_count
  1452. est_page = toc_offset + max(0, int(position_ratio * (estimated_total_pages - toc_offset)))
  1453. else:
  1454. est_page = toc_offset + seq
  1455. est_page = max(toc_offset, est_page) # never less than toc_offset
  1456. sdtContent.append(_make_toc_paragraph(h_text, h_level, lang, str(est_page), bm_name))
  1457. # Field end paragraph
  1458. p_end = OxmlElement('w:p')
  1459. r_end = OxmlElement('w:r')
  1460. fldChar_end = OxmlElement('w:fldChar')
  1461. fldChar_end.set(qn('w:fldCharType'), 'end')
  1462. r_end.append(fldChar_end)
  1463. p_end.append(r_end)
  1464. sdtContent.append(p_end)
  1465. sdt.append(sdtContent)
  1466. # Build bookmark mapping: list of (heading_body_index, bookmark_name)
  1467. bm_mapping = []
  1468. for seq, (idx, h_text, h_level) in enumerate(toc_entries):
  1469. h_body_idx = heading_entries[idx][0] if idx < len(heading_entries) else 0
  1470. bm_mapping.append((h_body_idx, bookmark_names[seq]))
  1471. return sdt, bm_mapping
  1472. # Build TOC SDT and page break
  1473. toc_sdt, bookmark_mapping = _build_toc_sdt(toc_title, doc_headings, content_lang)
  1474. page_break = _make_page_break()
  1475. # Insert TOC elements at the determined position
  1476. ref_children = list(doc_body)
  1477. # Clamp insert_before_idx
  1478. if insert_before_idx >= len(ref_children):
  1479. doc_body.append(toc_sdt)
  1480. doc_body.append(page_break)
  1481. else:
  1482. ref_element = ref_children[insert_before_idx]
  1483. ref_element.addprevious(toc_sdt)
  1484. ref_element.addprevious(page_break)
  1485. # Add bookmarks to heading paragraphs so PAGEREF and HYPERLINK can resolve
  1486. body_children = list(doc_body)
  1487. bm_id_start = 10 # bookmark IDs must be unique integers in the document
  1488. for body_idx, bm_name in bookmark_mapping:
  1489. if body_idx < len(body_children):
  1490. heading_para = body_children[body_idx]
  1491. # Insert bookmarkStart before first run, bookmarkEnd after last run
  1492. bm_start = OxmlElement('w:bookmarkStart')
  1493. bm_start.set(qn('w:id'), str(bm_id_start))
  1494. bm_start.set(qn('w:name'), bm_name)
  1495. bm_end = OxmlElement('w:bookmarkEnd')
  1496. bm_end.set(qn('w:id'), str(bm_id_start))
  1497. # Insert at beginning and end of the paragraph
  1498. heading_para.insert(0, bm_start)
  1499. heading_para.append(bm_end)
  1500. bm_id_start += 1
  1501. # Save
  1502. try:
  1503. doc.save(output_path)
  1504. except Exception as e:
  1505. return {
  1506. "pass": False, "source": source, "check_type": "fix-docx",
  1507. "action": "failed", "reason": f"Failed to save: {str(e)[:200]}",
  1508. "heading_count": heading_count,
  1509. "toc_entries_before": toc_entries_before, "toc_entries_after": 0,
  1510. "output": output_path,
  1511. "errors": [make_item("SAVE_ERROR", f"Failed to save: {str(e)[:200]}", "error")],
  1512. "warnings": [], "info": []
  1513. }
  1514. toc_entries_after = sum(1 for _, _, l in doc_headings if l <= 3)
  1515. info_list.append(f"Generated new TOC with {toc_entries_after} entries")
  1516. return {
  1517. "pass": True, "source": source, "check_type": "fix-docx",
  1518. "action": "fixed",
  1519. "reason": fix_reason,
  1520. "heading_count": heading_count,
  1521. "toc_entries_before": toc_entries_before,
  1522. "toc_entries_after": toc_entries_after,
  1523. "output": output_path,
  1524. "errors": [], "warnings": [],
  1525. "info": info_list
  1526. }
  1527. # ---------------------------------------------------------------------------
  1528. # CLI entry point
  1529. # ---------------------------------------------------------------------------
  1530. def fix_docx_accurate_pages(fixed_docx_path: str, pass1_pdf_path: str, output_path: str | None = None) -> dict[str, Any]:
  1531. """Update TOC page numbers in a fix-docx output using actual page positions from a PDF.
  1532. Two-pass approach:
  1533. Pass 1: Convert the DOCX (without TOC fix or with estimated pages) to PDF
  1534. Pass 2: Read actual heading positions from PDF, update PAGEREF placeholder text
  1535. Args:
  1536. fixed_docx_path: Path to the DOCX after fix-docx (has PAGEREF fields with estimated pages)
  1537. pass1_pdf_path: Path to a PDF converted from the ORIGINAL docx (without TOC)
  1538. output_path: Where to save the updated DOCX (defaults to overwrite fixed_docx_path)
  1539. """
  1540. import zipfile as zf_mod
  1541. try:
  1542. import pdfplumber
  1543. except ImportError:
  1544. return {"pass": False, "error": "pdfplumber not installed — cannot extract page positions"}
  1545. try:
  1546. from docx import Document
  1547. from docx.oxml.ns import qn as docx_qn
  1548. except ImportError:
  1549. return {"pass": False, "error": "python-docx not installed"}
  1550. try:
  1551. from lxml import etree
  1552. except ImportError:
  1553. return {"pass": False, "error": "lxml not installed"}
  1554. if output_path is None:
  1555. output_path = fixed_docx_path
  1556. source = os.path.basename(fixed_docx_path)
  1557. # --- Step 1: Extract headings from the fixed DOCX ---
  1558. doc = Document(fixed_docx_path)
  1559. headings = []
  1560. caption_pattern = re.compile(r'^[表图]\s*\d')
  1561. for p in doc.paragraphs:
  1562. style_name = p.style.name if p.style else ''
  1563. if style_name.startswith('Heading'):
  1564. m = re.match(r'Heading\s*(\d+)', style_name)
  1565. if m:
  1566. text = p.text.strip()
  1567. if text and not caption_pattern.match(text):
  1568. headings.append({'text': text, 'level': int(m.group(1))})
  1569. if not headings:
  1570. return {"pass": True, "source": source, "info": "No headings found, nothing to update"}
  1571. # --- Step 2: Find actual page positions in pass1 PDF ---
  1572. pdf = pdfplumber.open(pass1_pdf_path)
  1573. total_pdf_pages = len(pdf.pages)
  1574. page_texts = []
  1575. for i in range(total_pdf_pages):
  1576. page_texts.append(pdf.pages[i].extract_text() or '')
  1577. heading_pages_pass1: dict[str, int] = {}
  1578. for h in headings:
  1579. for page_num, pt in enumerate(page_texts):
  1580. if h['text'] in pt:
  1581. heading_pages_pass1[h['text']] = page_num + 1 # 1-indexed
  1582. break
  1583. pdf.close()
  1584. # --- Step 3: Calculate offset ---
  1585. # Instead of estimating TOC page count, calculate actual offset by comparing
  1586. # where the first heading appears in pass1 vs where it should appear after TOC insertion.
  1587. # The offset = (number of pages TOC adds) which depends on entry count and formatting.
  1588. toc_entry_count = sum(1 for h in headings if h['level'] <= 3)
  1589. # Better estimate: ~15 entries per page for CJK text with leader dots
  1590. toc_pages = max(1, (toc_entry_count + 14) // 15)
  1591. # Additional offset for the page break after TOC
  1592. # Check if the original DOCX already had a TOC (pass1 already includes TOC space)
  1593. # by looking at whether the first heading is on page 1-2 (no TOC) or later (has TOC)
  1594. first_heading_page = min(heading_pages_pass1.values()) if heading_pages_pass1 else 1
  1595. if first_heading_page <= 2:
  1596. # Pass1 has no significant TOC content, so we need full offset
  1597. offset = toc_pages + 1 # +1 for page break after TOC
  1598. else:
  1599. # Pass1 already has some TOC pages, smaller offset needed
  1600. offset = max(0, toc_pages - (first_heading_page - 2))
  1601. heading_page_map: dict[str, int] = {}
  1602. for h_text, orig_page in heading_pages_pass1.items():
  1603. heading_page_map[h_text] = orig_page + offset
  1604. # --- Step 4: Update PAGEREF placeholder text in the DOCX XML ---
  1605. with zf_mod.ZipFile(fixed_docx_path, 'r') as zf:
  1606. doc_xml = zf.read('word/document.xml')
  1607. root = etree.fromstring(doc_xml)
  1608. nsmap = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
  1609. w_ns = nsmap['w']
  1610. all_runs = root.findall(f'.//{{{w_ns}}}r')
  1611. updates = 0
  1612. i = 0
  1613. while i < len(all_runs):
  1614. r = all_runs[i]
  1615. fld = r.find(f'{{{w_ns}}}fldChar')
  1616. if fld is not None and fld.get(f'{{{w_ns}}}fldCharType') == 'begin':
  1617. if i + 1 < len(all_runs):
  1618. instr_r = all_runs[i + 1]
  1619. instr_t = instr_r.find(f'{{{w_ns}}}instrText')
  1620. if instr_t is not None and instr_t.text and 'PAGEREF' in instr_t.text:
  1621. # Find the hyperlink parent to get heading text
  1622. hyperlink = r.getparent()
  1623. if hyperlink is not None:
  1624. text_runs = hyperlink.findall(f'.//{{{w_ns}}}t')
  1625. # Find the 'separate' then the page number text
  1626. for j in range(i + 2, min(i + 5, len(all_runs))):
  1627. sep_fld = all_runs[j].find(f'{{{w_ns}}}fldChar')
  1628. if sep_fld is not None and sep_fld.get(f'{{{w_ns}}}fldCharType') == 'separate':
  1629. if j + 1 < len(all_runs):
  1630. page_t = all_runs[j + 1].find(f'{{{w_ns}}}t')
  1631. if page_t is not None:
  1632. # Get heading text from the hyperlink
  1633. heading_text = ''
  1634. for tr in text_runs:
  1635. if tr.text and tr != page_t:
  1636. heading_text += tr.text
  1637. heading_text = heading_text.strip()
  1638. correct_page = heading_page_map.get(heading_text)
  1639. if correct_page:
  1640. page_t.text = str(correct_page)
  1641. updates += 1
  1642. break
  1643. i += 1
  1644. # --- Step 5: Save updated DOCX ---
  1645. with tempfile.TemporaryDirectory() as tmpdir:
  1646. with zf_mod.ZipFile(fixed_docx_path, 'r') as zf:
  1647. zf.extractall(tmpdir)
  1648. doc_xml_path = os.path.join(tmpdir, 'word', 'document.xml')
  1649. with open(doc_xml_path, 'wb') as f:
  1650. f.write(etree.tostring(root, xml_declaration=True, encoding='UTF-8', standalone=True))
  1651. with zf_mod.ZipFile(output_path, 'w', zf_mod.ZIP_DEFLATED) as zf:
  1652. for dirpath, dirnames, filenames in os.walk(tmpdir):
  1653. for fn in filenames:
  1654. full_path = os.path.join(dirpath, fn)
  1655. arcname = os.path.relpath(full_path, tmpdir)
  1656. zf.write(full_path, arcname)
  1657. return {
  1658. "pass": True,
  1659. "source": source,
  1660. "check_type": "fix-pages",
  1661. "pages_updated": updates,
  1662. "total_headings": len(headings),
  1663. "toc_pages_estimated": toc_pages,
  1664. "offset_applied": offset,
  1665. "output": output_path,
  1666. }
  1667. def print_usage():
  1668. """Print usage information to stderr."""
  1669. print("Usage:", file=sys.stderr)
  1670. print(" toc_validate.py check-docx <file.docx>", file=sys.stderr)
  1671. print(" toc_validate.py check-pdf <file.pdf>", file=sys.stderr)
  1672. print(" toc_validate.py check-conversion <input.docx> <output.pdf>",
  1673. file=sys.stderr)
  1674. print(" toc_validate.py fix-docx <input.docx> [-o output.docx]",
  1675. file=sys.stderr)
  1676. print(" toc_validate.py fix-pages <fixed.docx> <pass1.pdf> [-o output.docx]",
  1677. file=sys.stderr)
  1678. print("", file=sys.stderr)
  1679. print("fix-pages: 2-pass page number correction. Requires a PDF converted", file=sys.stderr)
  1680. print(" from the ORIGINAL docx (without TOC) as reference.", file=sys.stderr)
  1681. def main():
  1682. """CLI entry point."""
  1683. if len(sys.argv) < 2:
  1684. print_usage()
  1685. sys.exit(2)
  1686. command = sys.argv[1].lower()
  1687. try:
  1688. if command == 'check-docx':
  1689. if len(sys.argv) < 3:
  1690. print("Error: Missing DOCX file path.", file=sys.stderr)
  1691. print_usage()
  1692. sys.exit(2)
  1693. docx_path = sys.argv[2]
  1694. if not os.path.isfile(docx_path):
  1695. print(f"Error: File not found: {docx_path}", file=sys.stderr)
  1696. sys.exit(2)
  1697. result = check_docx(docx_path)
  1698. elif command == 'check-pdf':
  1699. if len(sys.argv) < 3:
  1700. print("Error: Missing PDF file path.", file=sys.stderr)
  1701. print_usage()
  1702. sys.exit(2)
  1703. pdf_path = sys.argv[2]
  1704. if not os.path.isfile(pdf_path):
  1705. print(f"Error: File not found: {pdf_path}", file=sys.stderr)
  1706. sys.exit(2)
  1707. result = check_pdf(pdf_path)
  1708. elif command == 'check-conversion':
  1709. if len(sys.argv) < 4:
  1710. print("Error: Missing file paths. Need both DOCX and PDF.",
  1711. file=sys.stderr)
  1712. print_usage()
  1713. sys.exit(2)
  1714. docx_path = sys.argv[2]
  1715. pdf_path = sys.argv[3]
  1716. if not os.path.isfile(docx_path):
  1717. print(f"Error: File not found: {docx_path}", file=sys.stderr)
  1718. sys.exit(2)
  1719. if not os.path.isfile(pdf_path):
  1720. print(f"Error: File not found: {pdf_path}", file=sys.stderr)
  1721. sys.exit(2)
  1722. result = check_conversion(docx_path, pdf_path)
  1723. elif command == 'fix-docx':
  1724. if len(sys.argv) < 3:
  1725. print("Error: Missing DOCX file path.", file=sys.stderr)
  1726. print_usage()
  1727. sys.exit(2)
  1728. docx_path = sys.argv[2]
  1729. if not os.path.isfile(docx_path):
  1730. print(f"Error: File not found: {docx_path}", file=sys.stderr)
  1731. sys.exit(2)
  1732. # Parse optional -o flag
  1733. output_path = None
  1734. if '-o' in sys.argv:
  1735. o_idx = sys.argv.index('-o')
  1736. if o_idx + 1 < len(sys.argv):
  1737. output_path = sys.argv[o_idx + 1]
  1738. else:
  1739. print("Error: -o flag requires an output path.",
  1740. file=sys.stderr)
  1741. sys.exit(2)
  1742. result = fix_docx(docx_path, output_path)
  1743. elif command == 'fix-pages':
  1744. if len(sys.argv) < 4:
  1745. print("Error: Need both fixed DOCX and pass1 PDF paths.", file=sys.stderr)
  1746. print_usage()
  1747. sys.exit(2)
  1748. fixed_docx = sys.argv[2]
  1749. pass1_pdf = sys.argv[3]
  1750. if not os.path.isfile(fixed_docx):
  1751. print(f"Error: File not found: {fixed_docx}", file=sys.stderr)
  1752. sys.exit(2)
  1753. if not os.path.isfile(pass1_pdf):
  1754. print(f"Error: File not found: {pass1_pdf}", file=sys.stderr)
  1755. sys.exit(2)
  1756. output_path = None
  1757. if '-o' in sys.argv:
  1758. o_idx = sys.argv.index('-o')
  1759. if o_idx + 1 < len(sys.argv):
  1760. output_path = sys.argv[o_idx + 1]
  1761. result = fix_docx_accurate_pages(fixed_docx, pass1_pdf, output_path)
  1762. else:
  1763. print(f"Error: Unknown command '{command}'", file=sys.stderr)
  1764. print_usage()
  1765. sys.exit(2)
  1766. # Output JSON to stdout
  1767. print(json.dumps(result, ensure_ascii=False, indent=2))
  1768. # Exit code: 0=pass, 1=fail
  1769. sys.exit(0 if result['pass'] else 1)
  1770. except Exception as e:
  1771. # Unexpected error — output JSON error and exit 2
  1772. error_result = {
  1773. "pass": False,
  1774. "source": sys.argv[2] if len(sys.argv) > 2 else "unknown",
  1775. "check_type": command.replace('check-', '') + '-toc'
  1776. if command.startswith('check-') else 'unknown',
  1777. "errors": [make_item("SCRIPT_ERROR",
  1778. f"Unexpected error: {str(e)[:200]}",
  1779. "error")],
  1780. "warnings": [],
  1781. "info": [],
  1782. }
  1783. print(json.dumps(error_result, ensure_ascii=False, indent=2))
  1784. sys.exit(2)
  1785. if __name__ == '__main__':
  1786. main()