zcode-app-cli 3.3.5-1

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