audit-e2w 0.0.0-stage → 1.11.2

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 (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +147 -2
  3. package/cordis.patch.yml +3 -0
  4. package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
  5. package/dsh_plugins/audit-e2w/lib/index.js +114 -0
  6. package/dsh_plugins/audit-e2w/lib/skill.js +41 -0
  7. package/excel_word/README.md +380 -0
  8. package/excel_word/qoder_engine.py +438 -0
  9. package/excel_word/requirements.txt +4 -0
  10. package/excel_word/wesync/__init__.py +19 -0
  11. package/excel_word/wesync/__main__.py +6 -0
  12. package/excel_word/wesync/align.py +154 -0
  13. package/excel_word/wesync/api.py +840 -0
  14. package/excel_word/wesync/backup_history.py +65 -0
  15. package/excel_word/wesync/changelog.py +58 -0
  16. package/excel_word/wesync/cli.py +173 -0
  17. package/excel_word/wesync/commands/__init__.py +8 -0
  18. package/excel_word/wesync/commands/blank_cmd.py +250 -0
  19. package/excel_word/wesync/commands/bookmark_cmd.py +115 -0
  20. package/excel_word/wesync/commands/clear_cmd.py +48 -0
  21. package/excel_word/wesync/commands/export_cmd.py +220 -0
  22. package/excel_word/wesync/commands/marks_cmd.py +152 -0
  23. package/excel_word/wesync/commands/placeholders_cmd.py +87 -0
  24. package/excel_word/wesync/commands/writeback_cmd.py +513 -0
  25. package/excel_word/wesync/config.py +96 -0
  26. package/excel_word/wesync/console.py +78 -0
  27. package/excel_word/wesync/docx_blank.py +156 -0
  28. package/excel_word/wesync/docx_bookmarks.py +287 -0
  29. package/excel_word/wesync/docx_columns.py +257 -0
  30. package/excel_word/wesync/docx_edit.py +77 -0
  31. package/excel_word/wesync/docx_grid.py +212 -0
  32. package/excel_word/wesync/docx_marks.py +291 -0
  33. package/excel_word/wesync/docx_meta.py +157 -0
  34. package/excel_word/wesync/docx_newtable.py +220 -0
  35. package/excel_word/wesync/docx_placeholders.py +161 -0
  36. package/excel_word/wesync/docx_rows.py +67 -0
  37. package/excel_word/wesync/errors.py +5 -0
  38. package/excel_word/wesync/excel_blocks.py +543 -0
  39. package/excel_word/wesync/excel_export.py +136 -0
  40. package/excel_word/wesync/excel_marks.py +193 -0
  41. package/excel_word/wesync/excel_totals.py +53 -0
  42. package/excel_word/wesync/fsops.py +214 -0
  43. package/excel_word/wesync/gui/__init__.py +34 -0
  44. package/excel_word/wesync/gui/__main__.py +6 -0
  45. package/excel_word/wesync/gui/app.py +399 -0
  46. package/excel_word/wesync/gui/manual.py +68 -0
  47. package/excel_word/wesync/gui/pages/__init__.py +31 -0
  48. package/excel_word/wesync/gui/pages/_page.py +89 -0
  49. package/excel_word/wesync/gui/pages/batch_page.py +423 -0
  50. package/excel_word/wesync/gui/pages/blank_page.py +465 -0
  51. package/excel_word/wesync/gui/pages/bookmark_page.py +37 -0
  52. package/excel_word/wesync/gui/pages/export_page.py +88 -0
  53. package/excel_word/wesync/gui/pages/format_page.py +429 -0
  54. package/excel_word/wesync/gui/pages/help_page.py +92 -0
  55. package/excel_word/wesync/gui/pages/history_page.py +145 -0
  56. package/excel_word/wesync/gui/pages/marks_page.py +178 -0
  57. package/excel_word/wesync/gui/pages/writeback_page.py +452 -0
  58. package/excel_word/wesync/gui/resources.py +22 -0
  59. package/excel_word/wesync/gui/runner.py +74 -0
  60. package/excel_word/wesync/gui/store.py +34 -0
  61. package/excel_word/wesync/gui/theme.py +100 -0
  62. package/excel_word/wesync/gui/widgets/__init__.py +8 -0
  63. package/excel_word/wesync/gui/widgets/cards.py +20 -0
  64. package/excel_word/wesync/gui/widgets/filebar.py +58 -0
  65. package/excel_word/wesync/gui/widgets/logpane.py +110 -0
  66. package/excel_word/wesync/gui/widgets/nav.py +39 -0
  67. package/excel_word/wesync/report_format.py +1577 -0
  68. package/excel_word/wesync/sort_rules.py +244 -0
  69. package/excel_word/wesync/valuefmt.py +462 -0
  70. package/package.json +49 -4
  71. package/qoder_plugins/audit-toolbox/README.md +156 -0
  72. package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
@@ -0,0 +1,1577 @@
1
+ """审计报告格式方案:从样板提取角色格式,预演或生成格式调整副本。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import os
9
+ import re
10
+ import tempfile
11
+ import zipfile
12
+ from collections import Counter, defaultdict
13
+ from dataclasses import asdict, dataclass, field
14
+ from pathlib import Path
15
+ from weakref import WeakKeyDictionary
16
+
17
+ from docx import Document
18
+ from docx.enum.style import WD_STYLE_TYPE
19
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
20
+ from docx.oxml import OxmlElement
21
+ from docx.oxml.ns import qn
22
+ from docx.shared import Pt
23
+ from docx.styles import BabelFish
24
+ from docx.table import Table
25
+ from docx.text.paragraph import Paragraph
26
+ from docx.text.run import Run
27
+
28
+ from .config import DATE_RE
29
+ from .console import log
30
+ from .errors import SyncError
31
+ from .fsops import project_root, resolve_docx, tmp_root
32
+
33
+
34
+ DOCX_MAIN_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
35
+ DOCM_MAIN_TYPE = "application/vnd.ms-word.document.macroEnabled.main+xml"
36
+
37
+
38
+ def _rewrite_main_type(path: Path, macro_enabled: bool) -> None:
39
+ with zipfile.ZipFile(path) as archive:
40
+ files = {name: archive.read(name) for name in archive.namelist()}
41
+ content = files["[Content_Types].xml"].decode("utf-8")
42
+ if macro_enabled:
43
+ content = content.replace(DOCX_MAIN_TYPE, DOCM_MAIN_TYPE)
44
+ else:
45
+ content = content.replace(DOCM_MAIN_TYPE, DOCX_MAIN_TYPE)
46
+ files["[Content_Types].xml"] = content.encode("utf-8")
47
+ with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as archive:
48
+ for name, data in files.items():
49
+ archive.writestr(name, data)
50
+
51
+
52
+ def _open_document(path: Path):
53
+ if path.suffix.lower() != ".docm":
54
+ return Document(str(path))
55
+ fd, temp_name = tempfile.mkstemp(prefix="wesync_docm_", suffix=".docx", dir=tmp_root())
56
+ os.close(fd)
57
+ temp_path = Path(temp_name)
58
+ try:
59
+ with zipfile.ZipFile(path) as source, zipfile.ZipFile(temp_path, "w", zipfile.ZIP_DEFLATED) as target:
60
+ for name in source.namelist():
61
+ data = source.read(name)
62
+ if name == "[Content_Types].xml":
63
+ data = data.replace(DOCM_MAIN_TYPE.encode(), DOCX_MAIN_TYPE.encode())
64
+ target.writestr(name, data)
65
+ return Document(str(temp_path))
66
+ finally:
67
+ temp_path.unlink(missing_ok=True)
68
+
69
+
70
+ ROLE_LABELS = {
71
+ "cover_title": "封面标题",
72
+ "cover_info": "封面信息",
73
+ "toc_title": "目录标题",
74
+ "toc_entry": "目录条目",
75
+ "heading_1": "一级标题",
76
+ "heading_2": "二级标题",
77
+ "heading_3": "三级标题",
78
+ "heading_4": "四级标题",
79
+ "statement": "报表名称/日期",
80
+ "table_title": "表格标题",
81
+ "table_continuation": "续表标题",
82
+ "body": "正文",
83
+ "table_header": "表头",
84
+ "table_total": "合计行",
85
+ "table_data": "表格数据",
86
+ }
87
+
88
+ SCOPE_LABELS = {
89
+ "cover": "封面与目录",
90
+ "headings": "一至四级标题",
91
+ "statement": "报表名称、日期与表格标题",
92
+ "body": "正文段落",
93
+ "table_text": "表格字体与字号",
94
+ "table_emphasis": "表格对齐、表头与合计行加粗",
95
+ "table_borders": "表格框线",
96
+ }
97
+ DEFAULT_SCOPE = {key: True for key in SCOPE_LABELS}
98
+ VISUAL_REVIEW = [
99
+ "封面:公司名、报告名、期间和单位说明的层次是否与样板一致。",
100
+ "标题:首个一级标题及后续各级标题的字体、缩进和编号是否正常。",
101
+ "正文:普通段落字号、行距和两端对齐是否正常,有无异常缩小。",
102
+ "表题:金额单位、表名与引导正文是否分清,续表标签位置是否正确。",
103
+ "宽表格:列宽、换行、合计行和框线是否完整,有无超出页面。",
104
+ "分页:封面、目录、正文和表格附近有无空白页、孤行或错位。",
105
+ ]
106
+ PARAGRAPH_SCOPE_ROLES = {
107
+ "cover": ("cover_title", "cover_info", "toc_title", "toc_entry"),
108
+ "headings": ("heading_1", "heading_2", "heading_3", "heading_4"),
109
+ "statement": ("statement", "table_title", "table_continuation"),
110
+ "body": ("body",),
111
+ }
112
+
113
+ ALIGN_VALUES = {
114
+ "left": WD_ALIGN_PARAGRAPH.LEFT,
115
+ "center": WD_ALIGN_PARAGRAPH.CENTER,
116
+ "right": WD_ALIGN_PARAGRAPH.RIGHT,
117
+ "both": WD_ALIGN_PARAGRAPH.JUSTIFY,
118
+ "distribute": WD_ALIGN_PARAGRAPH.JUSTIFY,
119
+ }
120
+
121
+ ALIGN_LABELS = {
122
+ None: "默认",
123
+ "left": "左对齐",
124
+ "center": "居中",
125
+ "right": "右对齐",
126
+ "both": "两端对齐",
127
+ "distribute": "分散对齐",
128
+ }
129
+
130
+ BORDER_EDGES = ("top", "left", "bottom", "right", "insideH", "insideV")
131
+ BORDER_EDGE_LABELS = {
132
+ "top": "上外框",
133
+ "left": "左外框",
134
+ "bottom": "下外框",
135
+ "right": "右外框",
136
+ "insideH": "内部横线",
137
+ "insideV": "内部竖线",
138
+ }
139
+ BORDER_VALUES = {
140
+ "nil", "none", "single", "dashSmallGap", "dotted", "dotDash", "dotDotDash",
141
+ "double", "wave", "dashLargeGap", "dashDotGap", "thinThick",
142
+ "mediumDashSmallGap", "mediumDotDash", "mediumDashDotGap", "mediumThickSmallGap",
143
+ "slantDashDot",
144
+ }
145
+ BORDER_STYLE_LABELS = {
146
+ "nil": "无框线",
147
+ "none": "无框线",
148
+ "single": "实线",
149
+ "dashSmallGap": "短虚线",
150
+ "dotted": "点线",
151
+ "dotDash": "点划线",
152
+ "dotDotDash": "双点划线",
153
+ "double": "双线",
154
+ "wave": "波浪线",
155
+ "dashLargeGap": "长虚线",
156
+ "dashDotGap": "划线点线",
157
+ "thinThick": "一细一粗",
158
+ "mediumDashSmallGap": "中短虚线",
159
+ "mediumDotDash": "中点划线",
160
+ "mediumDashDotGap": "中划线点线",
161
+ "mediumThickSmallGap": "中一细一粗",
162
+ "slantDashDot": "斜点划线",
163
+ }
164
+
165
+
166
+ @dataclass
167
+ class ParagraphFormat:
168
+ ascii_font: str | None = None
169
+ east_asia_font: str | None = None
170
+ size: float | None = None
171
+ bold: bool | None = None
172
+ align: str | None = None
173
+ line_value: float | None = None
174
+ line_rule: str | None = None
175
+ before: float | None = None
176
+ after: float | None = None
177
+ first_line: float | None = None
178
+ left: float | None = None
179
+
180
+
181
+ @dataclass(frozen=True)
182
+ class BorderFormat:
183
+ val: str = "nil"
184
+ size: float = 0.0
185
+ color: str | None = None
186
+
187
+
188
+ @dataclass
189
+ class FormatProfile:
190
+ paragraphs: dict[str, ParagraphFormat] = field(default_factory=dict)
191
+ table_ascii_font: str = "Times New Roman"
192
+ table_east_asia_font: str = "宋体"
193
+ table_size: float = 9.0
194
+ table_borders: dict[str, BorderFormat] | None = None
195
+ template: str = ""
196
+
197
+
198
+ def _profiles_dir() -> Path:
199
+ path = project_root() / "format_profiles"
200
+ path.mkdir(parents=True, exist_ok=True)
201
+ return path
202
+
203
+
204
+ def _validated_scope(scope: dict | None) -> dict[str, bool]:
205
+ if scope is None:
206
+ return dict(DEFAULT_SCOPE)
207
+ if not isinstance(scope, dict) or set(scope) != set(DEFAULT_SCOPE):
208
+ raise SyncError("调整项目必须完整包含七项,且不能包含未知项目")
209
+ if any(type(scope[key]) is not bool for key in DEFAULT_SCOPE):
210
+ raise SyncError("调整项目的选择必须为“是”或“否”")
211
+ if not any(scope.values()):
212
+ raise SyncError("请至少选择一项需要调整的项目")
213
+ return {key: scope[key] for key in DEFAULT_SCOPE}
214
+
215
+
216
+ def _selected_paragraph_roles(scope: dict[str, bool]) -> set[str]:
217
+ return {
218
+ role
219
+ for key, enabled in scope.items()
220
+ if enabled and key in PARAGRAPH_SCOPE_ROLES
221
+ for role in PARAGRAPH_SCOPE_ROLES[key]
222
+ }
223
+
224
+
225
+ def _profile_path(name: str) -> Path:
226
+ name = name.strip()
227
+ if (
228
+ not name
229
+ or len(name) > 80
230
+ or name.endswith((".", " "))
231
+ or re.search(r'[<>:"/\\|?*\x00-\x1f]', name)
232
+ or re.match(r"^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)", name, re.IGNORECASE)
233
+ ):
234
+ raise SyncError("方案名称不能为空,且不能超过 80 个字符或包含文件名禁用字符")
235
+ return _profiles_dir() / f"{name}.json"
236
+
237
+
238
+ def _profile_data(profile: FormatProfile, name: str) -> dict:
239
+ data = {
240
+ "version": 1,
241
+ "name": name,
242
+ "paragraphs": {role: asdict(fmt) for role, fmt in profile.paragraphs.items()},
243
+ "table_ascii_font": profile.table_ascii_font,
244
+ "table_east_asia_font": profile.table_east_asia_font,
245
+ "table_size": profile.table_size,
246
+ }
247
+ if profile.table_borders is not None:
248
+ data["table_borders"] = {edge: asdict(fmt) for edge, fmt in profile.table_borders.items()}
249
+ return data
250
+
251
+
252
+ def _validated_borders(data) -> dict[str, BorderFormat] | None:
253
+ if data is None:
254
+ return None
255
+ if not isinstance(data, dict) or set(data) != set(BORDER_EDGES):
256
+ raise SyncError("格式方案表格框线数据不完整")
257
+ result = {}
258
+ for edge in BORDER_EDGES:
259
+ values = data[edge]
260
+ if not isinstance(values, dict) or set(values) != {"val", "size", "color"}:
261
+ raise SyncError("格式方案表格框线字段不正确")
262
+ val = values["val"]
263
+ size = values["size"]
264
+ color = values["color"]
265
+ if not isinstance(val, str) or val not in BORDER_VALUES:
266
+ raise SyncError("格式方案表格框线类型不正确")
267
+ if isinstance(size, bool) or not isinstance(size, (int, float)) or not math.isfinite(size) or not 0 <= size <= 96:
268
+ raise SyncError("格式方案表格框线粗细不正确")
269
+ if color is not None and (not isinstance(color, str) or (color.lower() != "auto" and not re.fullmatch(r"[0-9a-fA-F]{6}", color))):
270
+ raise SyncError("格式方案表格框线颜色不正确")
271
+ result[edge] = BorderFormat(val, float(size), color)
272
+ return result
273
+
274
+
275
+ def _validated_profile(data: dict) -> FormatProfile:
276
+ if not isinstance(data, dict) or data.get("version") != 1:
277
+ raise SyncError("格式方案文件版本不受支持")
278
+ paragraphs = data.get("paragraphs")
279
+ if not isinstance(paragraphs, dict):
280
+ raise SyncError("格式方案缺少段落格式数据")
281
+ fields = set(ParagraphFormat.__dataclass_fields__)
282
+ parsed = {}
283
+ for role, values in paragraphs.items():
284
+ if role not in ROLE_LABELS or role in ("table_header", "table_total", "table_data") or not isinstance(values, dict):
285
+ raise SyncError("格式方案包含不支持的段落角色")
286
+ if set(values) - fields:
287
+ raise SyncError("格式方案包含不支持的格式字段")
288
+ try:
289
+ fmt = ParagraphFormat(**values)
290
+ except TypeError as exc:
291
+ raise SyncError("格式方案字段类型不正确") from exc
292
+ for key in ("ascii_font", "east_asia_font", "align", "line_rule"):
293
+ value = getattr(fmt, key)
294
+ if value is not None and not isinstance(value, str):
295
+ raise SyncError("格式方案字体或段落属性类型不正确")
296
+ if fmt.align is not None and fmt.align not in ALIGN_LABELS:
297
+ raise SyncError("格式方案段落对齐属性不正确")
298
+ if fmt.line_rule is not None and fmt.line_rule not in ("auto", "exact", "atLeast"):
299
+ raise SyncError("格式方案行距属性不正确")
300
+ for key in ("size", "line_value", "before", "after", "first_line", "left"):
301
+ value = getattr(fmt, key)
302
+ if value is not None and (isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0):
303
+ raise SyncError("格式方案数值属性不正确")
304
+ if fmt.bold is not None and not isinstance(fmt.bold, bool):
305
+ raise SyncError("格式方案加粗属性类型不正确")
306
+ parsed[role] = fmt
307
+ required_roles = set(ROLE_LABELS) - {"table_header", "table_total", "table_data", "table_continuation"}
308
+ if not required_roles <= set(parsed) or set(parsed) - (required_roles | {"table_continuation"}):
309
+ raise SyncError("格式方案段落角色不完整")
310
+ if "table_continuation" not in parsed:
311
+ parsed["table_continuation"] = _default_formats()["table_continuation"]
312
+ fonts = (data.get("table_ascii_font"), data.get("table_east_asia_font"))
313
+ size = data.get("table_size")
314
+ if any(not isinstance(font, str) or not font for font in fonts):
315
+ raise SyncError("格式方案缺少表格字体")
316
+ if isinstance(size, bool) or not isinstance(size, (int, float)) or not math.isfinite(size) or size <= 0:
317
+ raise SyncError("格式方案表格字号不正确")
318
+ return FormatProfile(parsed, fonts[0], fonts[1], float(size), _validated_borders(data.get("table_borders")))
319
+
320
+
321
+ def list_format_profiles() -> list[dict]:
322
+ result = []
323
+ for path in sorted(_profiles_dir().glob("*.json")):
324
+ try:
325
+ data = json.loads(path.read_text(encoding="utf-8"))
326
+ name = data.get("name")
327
+ if not isinstance(name, str) or not name:
328
+ raise ValueError("缺少方案名称")
329
+ result.append({"name": name, "path": str(path), "size": path.stat().st_size})
330
+ except (OSError, ValueError, AttributeError) as exc:
331
+ raise SyncError(f"格式方案文件无法读取,已停止加载:{path.name}:{exc}") from exc
332
+ return result
333
+
334
+
335
+ def save_format_profile(template: str | Path, name: str, source: str | Path | None = None) -> dict:
336
+ path = _profile_path(name)
337
+ if path.exists():
338
+ raise SyncError(f"格式方案已存在,未覆盖:{name}")
339
+ profile = build_profile(template, source)
340
+ data = _profile_data(profile, name.strip())
341
+ fd, temp_name = tempfile.mkstemp(prefix=f".{path.stem}.", suffix=".json", dir=path.parent)
342
+ try:
343
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
344
+ json.dump(data, handle, ensure_ascii=False, indent=2)
345
+ os.replace(temp_name, path)
346
+ except Exception:
347
+ Path(temp_name).unlink(missing_ok=True)
348
+ raise
349
+ log(f"[格式] 已保存纯格式方案:{path}(不含报告文字、表格内容或样板路径)")
350
+ return {"name": name.strip(), "path": str(path)}
351
+
352
+
353
+ def load_format_profile(name: str) -> FormatProfile:
354
+ path = _profile_path(name)
355
+ try:
356
+ data = json.loads(path.read_text(encoding="utf-8"))
357
+ except FileNotFoundError as exc:
358
+ raise SyncError(f"找不到格式方案:{name}") from exc
359
+ except (OSError, ValueError) as exc:
360
+ raise SyncError(f"格式方案无法读取:{name}:{exc}") from exc
361
+ if not isinstance(data, dict) or data.get("name") != name.strip():
362
+ raise SyncError("格式方案文件名称不一致")
363
+ return _validated_profile(data)
364
+
365
+
366
+ def delete_format_profile(name: str) -> dict:
367
+ path = _profile_path(name)
368
+ try:
369
+ path.unlink()
370
+ except FileNotFoundError as exc:
371
+ raise SyncError(f"找不到格式方案:{name}") from exc
372
+ log(f"[格式] 已删除格式方案:{name}")
373
+ return {"name": name.strip(), "deleted": True}
374
+
375
+
376
+ def _number(element, name: str, scale: float = 1.0) -> float | None:
377
+ if element is None:
378
+ return None
379
+ value = element.get(qn(f"w:{name}"))
380
+ if value is None or not value.lstrip("-").isdigit():
381
+ return None
382
+ return int(value) / scale
383
+
384
+
385
+ def _on_off(element) -> bool | None:
386
+ if element is None:
387
+ return None
388
+ return element.get(qn("w:val")) not in ("0", "false", "off")
389
+
390
+
391
+ _STYLE_CACHE: WeakKeyDictionary = WeakKeyDictionary()
392
+ _DEFAULTS_CACHE: WeakKeyDictionary = WeakKeyDictionary()
393
+
394
+
395
+ def _style_data(paragraph: Paragraph):
396
+ part = paragraph.part
397
+ cached = _STYLE_CACHE.get(part)
398
+ if cached is not None:
399
+ return cached
400
+ styles = part.styles
401
+ by_id = {style.style_id: style for style in styles}
402
+ defaults = {
403
+ WD_STYLE_TYPE.PARAGRAPH: styles.default(WD_STYLE_TYPE.PARAGRAPH),
404
+ WD_STYLE_TYPE.CHARACTER: styles.default(WD_STYLE_TYPE.CHARACTER),
405
+ }
406
+ cached = (by_id, defaults, {})
407
+ _STYLE_CACHE[part] = cached
408
+ return cached
409
+
410
+
411
+ def _paragraph_style(paragraph: Paragraph):
412
+ by_id, defaults, _ = _style_data(paragraph)
413
+ style_id = paragraph._p.style
414
+ style = by_id.get(style_id)
415
+ if style is None or style.type != WD_STYLE_TYPE.PARAGRAPH:
416
+ style = defaults[WD_STYLE_TYPE.PARAGRAPH]
417
+ return style
418
+
419
+
420
+ def _run_style(paragraph: Paragraph, run: Run):
421
+ by_id, defaults, _ = _style_data(paragraph)
422
+ style_id = run._r.rPr.rStyle.val if run._r.rPr is not None and run._r.rPr.rStyle is not None else None
423
+ style = by_id.get(style_id)
424
+ if style is None or style.type != WD_STYLE_TYPE.CHARACTER:
425
+ style = defaults[WD_STYLE_TYPE.CHARACTER]
426
+ return style
427
+
428
+
429
+ def _style_chain(paragraph: Paragraph, style) -> list:
430
+ _, _, chains = _style_data(paragraph)
431
+ key = style.style_id if style is not None else None
432
+ if key not in chains:
433
+ result = []
434
+ seen = set()
435
+ while style is not None and style.style_id not in seen:
436
+ seen.add(style.style_id)
437
+ result.append(style.element)
438
+ style = style.base_style
439
+ chains[key] = result
440
+ return chains[key]
441
+
442
+
443
+ def _doc_defaults(paragraph: Paragraph) -> tuple:
444
+ part = paragraph.part
445
+ cached = _DEFAULTS_CACHE.get(part)
446
+ if cached is not None:
447
+ return cached
448
+ defaults = part.styles.element.find(qn("w:docDefaults"))
449
+ run_defaults = defaults.find(qn("w:rPrDefault")) if defaults is not None else None
450
+ paragraph_defaults = defaults.find(qn("w:pPrDefault")) if defaults is not None else None
451
+ cached = (
452
+ run_defaults.find(qn("w:rPr")) if run_defaults is not None else None,
453
+ paragraph_defaults.find(qn("w:pPr")) if paragraph_defaults is not None else None,
454
+ )
455
+ _DEFAULTS_CACHE[part] = cached
456
+ return cached
457
+
458
+
459
+ def _property_containers(paragraph: Paragraph, name: str, run: Run | None) -> list:
460
+ paragraph_property = name in ("spacing", "ind", "jc", "outlineLvl")
461
+ if paragraph_property:
462
+ containers = [paragraph._p.pPr]
463
+ containers.extend(
464
+ style.find(qn("w:pPr"))
465
+ for style in _style_chain(paragraph, _paragraph_style(paragraph))
466
+ )
467
+ default = _doc_defaults(paragraph)[1]
468
+ else:
469
+ containers = []
470
+ if run is not None:
471
+ containers.append(run._r.rPr)
472
+ containers.extend(_style_chain(paragraph, _run_style(paragraph, run)))
473
+ containers.extend(
474
+ style.find(qn("w:rPr"))
475
+ for style in _style_chain(paragraph, _paragraph_style(paragraph))
476
+ )
477
+ default = _doc_defaults(paragraph)[0]
478
+ containers.append(default)
479
+ return [container for container in containers if container is not None]
480
+
481
+
482
+ def _find_property(paragraph: Paragraph, name: str, run: Run | None = None):
483
+ for container in _property_containers(paragraph, name, run):
484
+ found = container.find(qn(f"w:{name}"))
485
+ if found is not None:
486
+ return found
487
+ return None
488
+
489
+
490
+ def _font_attribute(paragraph: Paragraph, names: tuple[str, ...], run: Run | None) -> str | None:
491
+ for container in _property_containers(paragraph, "rFonts", run):
492
+ fonts = container.find(qn("w:rFonts"))
493
+ if fonts is not None:
494
+ for name in names:
495
+ value = fonts.get(qn(f"w:{name}"))
496
+ if value:
497
+ return value
498
+ return None
499
+
500
+
501
+ def _effective_paragraph_format(paragraph: Paragraph) -> ParagraphFormat:
502
+ run = next((item for item in paragraph.runs if item.text.strip()), None)
503
+ ascii_font = _font_attribute(paragraph, ("ascii", "hAnsi"), run)
504
+ east_asia_font = _font_attribute(paragraph, ("eastAsia",), run)
505
+ spacing = _find_property(paragraph, "spacing")
506
+ line_rule = spacing.get(qn("w:lineRule")) if spacing is not None else None
507
+ line_value = _number(spacing, "line")
508
+ if line_rule == "auto" and line_value is not None:
509
+ line_value /= 240.0
510
+ else:
511
+ line_value = _number(spacing, "line", 20.0)
512
+ indent = _find_property(paragraph, "ind")
513
+ alignment = _find_property(paragraph, "jc")
514
+ return ParagraphFormat(
515
+ ascii_font=ascii_font,
516
+ east_asia_font=east_asia_font,
517
+ size=_number(_find_property(paragraph, "sz", run), "val", 2.0),
518
+ bold=_on_off(_find_property(paragraph, "b", run)),
519
+ align=alignment.get(qn("w:val")) if alignment is not None else None,
520
+ line_value=line_value,
521
+ line_rule=line_rule,
522
+ before=_number(spacing, "before", 20.0),
523
+ after=_number(spacing, "after", 20.0),
524
+ first_line=_number(indent, "firstLine", 20.0),
525
+ left=_number(indent, "left", 20.0),
526
+ )
527
+
528
+
529
+ def _effective_run_size(paragraph: Paragraph, run: Run) -> float | None:
530
+ return _number(_find_property(paragraph, "sz", run), "val", 2.0)
531
+
532
+
533
+ def _outline_level(paragraph: Paragraph) -> int | None:
534
+ element = _find_property(paragraph, "outlineLvl")
535
+ value = element.get(qn("w:val")) if element is not None else None
536
+ if value is None or not value.lstrip("-").isdigit():
537
+ return None
538
+ return int(value)
539
+
540
+
541
+ def _style_heading_level(paragraph: Paragraph) -> int | None:
542
+ style = _paragraph_style(paragraph)
543
+ internal_name = style.element.name_val if style is not None else None
544
+ name = BabelFish.internal2ui(internal_name) if internal_name else ""
545
+ match = re.search(r"(?:标题|heading)\s*\[?\s*([1-5])", name, re.IGNORECASE)
546
+ if match:
547
+ return int(match.group(1))
548
+ match = re.search(r"([一二三四五])级标题", name)
549
+ if match:
550
+ return "一二三四五".index(match.group(1)) + 1
551
+ return None
552
+
553
+
554
+ def _heading_role(paragraph: Paragraph) -> str | None:
555
+ level = _outline_level(paragraph)
556
+ if level is not None and 0 <= level <= 4:
557
+ return "statement" if level == 4 else f"heading_{level + 1}"
558
+ if level is not None and level > 4:
559
+ return None
560
+ level = _style_heading_level(paragraph)
561
+ if level is None:
562
+ return None
563
+ return "statement" if level == 5 else f"heading_{level}"
564
+
565
+
566
+ def _body_items(doc):
567
+ for child in doc.element.body.iterchildren():
568
+ if child.tag == qn("w:p"):
569
+ yield Paragraph(child, doc)
570
+ elif child.tag == qn("w:tbl"):
571
+ yield Table(child, doc)
572
+
573
+
574
+ def _normalized_text(paragraph: Paragraph) -> str:
575
+ return re.sub(r"\s+", "", paragraph.text)
576
+
577
+
578
+ def _region_entries(doc, region: tuple[int, int] | None):
579
+ children = list(doc.element.body.iterchildren())
580
+ indexes = range(len(children)) if region is None else range(*region)
581
+ for index in indexes:
582
+ child = children[index]
583
+ if child.tag == qn("w:p"):
584
+ yield index, Paragraph(child, doc)
585
+ elif child.tag == qn("w:tbl"):
586
+ yield index, Table(child, doc)
587
+
588
+
589
+ def _region_items(doc, region: tuple[int, int] | None):
590
+ for _, item in _region_entries(doc, region):
591
+ yield item
592
+
593
+
594
+ def _notes_region(doc) -> tuple[int, int] | None:
595
+ children = list(doc.element.body.iterchildren())
596
+ for index, child in enumerate(children):
597
+ if child.tag != qn("w:p"):
598
+ continue
599
+ title = _normalized_text(Paragraph(child, doc))
600
+ combined_title = bool(re.match(r"^\d{4}\s*年.*财务报表附注$", title))
601
+ if title != "财务报表附注" and not combined_title:
602
+ continue
603
+ following = next(
604
+ (
605
+ Paragraph(item, doc)
606
+ for item in children[index + 1:]
607
+ if item.tag == qn("w:p") and Paragraph(item, doc).text.strip()
608
+ ),
609
+ None,
610
+ )
611
+ if following is None:
612
+ continue
613
+ following_text = following.text.strip()
614
+ if not combined_title and not re.match(r"^\d{4}\s*年.*(?:年度|年)$", following_text):
615
+ continue
616
+ if combined_title and not ("金额单位" in following_text or ("本附注" in following_text and "单位" in following_text)):
617
+ continue
618
+ start = index
619
+ for previous in range(index - 1, max(-1, index - 4), -1):
620
+ if children[previous].tag == qn("w:p") and Paragraph(children[previous], doc).text.strip():
621
+ start = previous
622
+ break
623
+ return start, len(children)
624
+ return None
625
+
626
+
627
+ def _region_tables(doc, region: tuple[int, int] | None) -> list[Table]:
628
+ return [item for item in _region_items(doc, region) if isinstance(item, Table)]
629
+
630
+
631
+ def _is_table_continuation(text: str) -> bool:
632
+ return bool(re.fullmatch(r"[((]?(?:续上表|续下表|续表)[))]?", re.sub(r"\s+", "", text)))
633
+
634
+
635
+ def _is_table_caption(text: str) -> bool:
636
+ value = re.sub(r"\s+", "", text)
637
+ if _is_table_continuation(value):
638
+ return True
639
+ if re.match(r"^(?:金额)?单位[::]", value):
640
+ return True
641
+ return bool(re.match(r"^(?:表|图表)\d+(?:[..、]|\s|[^\d])", value) and len(value) <= 80)
642
+
643
+
644
+ def _classify_paragraphs(
645
+ doc,
646
+ paragraph_overrides: dict[int, str] | None = None,
647
+ region: tuple[int, int] | None = None,
648
+ ) -> tuple[list[tuple[Paragraph, str]], dict[str, int]]:
649
+ entries = list(_region_entries(doc, region))
650
+ items = [item for _, item in entries]
651
+ paragraphs = [item for item in items if isinstance(item, Paragraph)]
652
+ paragraph_indexes = [index for index, item in entries if isinstance(item, Paragraph)]
653
+ nonempty = [item for item in paragraphs if item.text.strip()]
654
+ positions = {paragraph._p: index for index, paragraph in enumerate(nonempty)}
655
+ heading_roles = [_heading_role(item) for item in nonempty]
656
+ for element_index, role in (paragraph_overrides or {}).items():
657
+ position = positions.get(doc.element.body[element_index])
658
+ if position is not None and role.startswith("heading_"):
659
+ heading_roles[position] = role
660
+ heading_indexes = [index for index, role in enumerate(heading_roles) if role]
661
+ toc_index = next((index for index, item in enumerate(nonempty) if _normalized_text(item) == "目录"), None)
662
+ first_heading = heading_indexes[0] if heading_indexes else len(nonempty)
663
+ if region is not None:
664
+ cover_end = min(first_heading, 4)
665
+ elif toc_index is not None:
666
+ cover_end = toc_index
667
+ else:
668
+ cover_end = min(first_heading, 3)
669
+ if first_heading == len(nonempty):
670
+ numbered = next((index for index, item in enumerate(nonempty) if index and _HEADING_NUMBER_RE.match(item.text.strip())), None)
671
+ if numbered is not None:
672
+ cover_end = min(cover_end, numbered)
673
+ toc_end = len(nonempty)
674
+ if toc_index is not None:
675
+ later = [index for index in heading_indexes if index > toc_index]
676
+ toc_end = later[0] if later else len(nonempty)
677
+
678
+ table_titles: set[int] = set()
679
+ table_continuations: set[int] = set()
680
+ previous: Paragraph | None = None
681
+ previous_index = -1
682
+ position = -1
683
+ for item in items:
684
+ if isinstance(item, Paragraph):
685
+ if item.text.strip():
686
+ position += 1
687
+ previous = item
688
+ previous_index = position
689
+ continue
690
+ if previous is None or not previous.text.strip() or heading_roles[previous_index]:
691
+ continue
692
+ if DATE_RE.match(previous.text.strip()) or not _is_table_caption(previous.text):
693
+ continue
694
+ index = previous_index
695
+ if index < cover_end:
696
+ continue
697
+ if toc_index is not None and toc_index <= index < toc_end:
698
+ continue
699
+ table_titles.add(index)
700
+ if _is_table_continuation(previous.text):
701
+ table_continuations.add(index)
702
+
703
+ notes_title_count = 2
704
+ if region is not None and len(nonempty) > 2 and re.match(r"^\d{4}\s*年.*(?:年度|年)$", nonempty[2].text.strip()):
705
+ notes_title_count = 3
706
+
707
+ result: list[tuple[Paragraph, str]] = []
708
+ ambiguous = 0
709
+ for index, paragraph in enumerate(nonempty):
710
+ role = heading_roles[index]
711
+ role = (paragraph_overrides or {}).get(paragraph_indexes[index]) or role
712
+ if role is None and (_outline_level(paragraph) or 0) > 4:
713
+ ambiguous += 1
714
+ if role is None and index in table_titles:
715
+ role = "table_continuation" if index in table_continuations else "table_title"
716
+ if role is None and toc_index is not None:
717
+ if index == toc_index:
718
+ role = "toc_title"
719
+ elif toc_index < index < toc_end:
720
+ role = "toc_entry"
721
+ if role is None and index < cover_end:
722
+ title = region is not None and index < notes_title_count
723
+ role = "cover_title" if title or (region is None and index < min(3, cover_end)) else "cover_info"
724
+ result.append((paragraph, role or "body"))
725
+ return result, {"ambiguous": ambiguous, "empty": len(paragraphs) - len(nonempty)}
726
+
727
+
728
+ _HEADING_NUMBER_RE = re.compile(
729
+ r"^(?:第[一二三四五六七八九十百\d]+[章节部分篇]|[一二三四五六七八九十百]+[、..]|"
730
+ r"[((]?[一二三四五六七八九十百]+[))]?|[((]\d+[))]|\d+(?:\.\d+)*[、..))]?)\s*\S"
731
+ )
732
+
733
+
734
+ def _context_text(paragraph: Paragraph | None) -> str:
735
+ return re.sub(r"\s+", " ", paragraph.text).strip()[:100] if paragraph is not None else ""
736
+
737
+
738
+ def _candidate_id(element_index: int, paragraph: Paragraph) -> str:
739
+ digest = hashlib.sha256(_normalized_text(paragraph).encode("utf-8")).hexdigest()[:10]
740
+ return f"b{element_index:04d}-{digest}"
741
+
742
+
743
+ def _candidate_record(element_index: int, paragraph: Paragraph, paragraphs: list[Paragraph], position: int) -> dict:
744
+ text = re.sub(r"\s+", " ", paragraph.text).strip()
745
+ fmt = _effective_paragraph_format(paragraph)
746
+ return {
747
+ "id": _candidate_id(element_index, paragraph),
748
+ "element_index": element_index,
749
+ "text": text,
750
+ "before": _context_text(paragraphs[position - 1] if position else None),
751
+ "after": _context_text(paragraphs[position + 1] if position + 1 < len(paragraphs) else None),
752
+ "style": paragraph.style.name if paragraph.style is not None else "",
753
+ "bold": fmt.bold,
754
+ "size": fmt.size,
755
+ "align": ALIGN_LABELS.get(fmt.align, fmt.align or "默认"),
756
+ "numbered": bool(_HEADING_NUMBER_RE.match(text)),
757
+ }
758
+
759
+
760
+ def _format_candidate_package(doc, fingerprint: str) -> dict:
761
+ region = _notes_region(doc)
762
+ entries = list(_region_entries(doc, region))
763
+ paragraph_entries = [(index, item) for index, item in entries if isinstance(item, Paragraph) and item.text.strip()]
764
+ paragraphs = [item for _, item in paragraph_entries]
765
+ positions = {paragraph._p: index for index, paragraph in enumerate(paragraphs)}
766
+ classified, _ = _classify_paragraphs(doc, region=region)
767
+ roles = {paragraph._p: role for paragraph, role in classified}
768
+ toc_index = next((index for index, item in enumerate(paragraphs) if _normalized_text(item) == "目录"), None)
769
+ content_start = 0
770
+ if toc_index is not None:
771
+ content_start = toc_index + 1
772
+ while content_start < len(paragraphs):
773
+ text = re.sub(r"\s+", " ", paragraphs[content_start].text).strip()
774
+ style_name = paragraphs[content_start].style.name if paragraphs[content_start].style is not None else ""
775
+ if "toc" not in style_name.lower() and "目录" not in style_name and not re.search(r"(?:\.{2,}|…{2,}|\t)|\s\d+$", text):
776
+ break
777
+ content_start += 1
778
+
779
+ candidates = []
780
+ truncated = False
781
+ for element_index, paragraph in paragraph_entries:
782
+ index = positions[paragraph._p]
783
+ text = re.sub(r"\s+", " ", paragraph.text).strip()
784
+ level = _outline_level(paragraph)
785
+ if roles[paragraph._p] not in ("body", "toc_entry") or index < content_start or level is not None or not 2 <= len(text) <= 120:
786
+ continue
787
+ if DATE_RE.match(text) or re.search(r"[。;;!!??]$", text):
788
+ continue
789
+ fmt = _effective_paragraph_format(paragraph)
790
+ visual = fmt.bold is True or fmt.align == "center" or (fmt.size is not None and fmt.size >= 14)
791
+ if not _HEADING_NUMBER_RE.match(text) and not (visual and len(text) <= 60):
792
+ continue
793
+ candidates.append(_candidate_record(element_index, paragraph, paragraphs, index))
794
+ if len(candidates) == 300:
795
+ truncated = True
796
+ break
797
+
798
+ heading_ids = {item["id"] for item in candidates}
799
+ role_candidates = []
800
+ previous: tuple[int, Paragraph] | None = None
801
+ for element_index, item in entries:
802
+ if isinstance(item, Paragraph):
803
+ if item.text.strip():
804
+ previous = (element_index, item)
805
+ continue
806
+ if previous is None:
807
+ continue
808
+ previous_index, paragraph = previous
809
+ if len(candidates) >= 300:
810
+ if roles[paragraph._p] == "body" and _outline_level(paragraph) is None and _candidate_id(previous_index, paragraph) not in heading_ids:
811
+ truncated = True
812
+ continue
813
+ if roles[paragraph._p] != "body" or _outline_level(paragraph) is not None or _candidate_id(previous_index, paragraph) in heading_ids:
814
+ continue
815
+ text = re.sub(r"\s+", " ", paragraph.text).strip()
816
+ if not 2 <= len(text) <= 120 or DATE_RE.match(text):
817
+ continue
818
+ record = _candidate_record(previous_index, paragraph, paragraphs, positions[paragraph._p])
819
+ record.update({
820
+ "kind": "table_role",
821
+ "current_role": "body",
822
+ "options": ["body", "table_title"],
823
+ "next_element": "表格(未读取单元格内容)",
824
+ })
825
+ role_candidates.append(record)
826
+ candidates.append(record)
827
+
828
+ children = list(doc.element.body.iterchildren())
829
+ boundary_indexes: list[int] = []
830
+ if region is not None:
831
+ boundary_indexes = list(range(max(0, region[0] - 3), min(len(children), region[0] + 5)))
832
+ else:
833
+ for index, child in enumerate(children):
834
+ if child.tag == qn("w:p") and "财务报表附注" in Paragraph(child, doc).text:
835
+ boundary_indexes.append(index)
836
+ previous_index = next((i for i in range(index - 1, max(-1, index - 4), -1) if children[i].tag == qn("w:p") and Paragraph(children[i], doc).text.strip()), None)
837
+ if previous_index is not None:
838
+ boundary_indexes.append(previous_index)
839
+ if len(boundary_indexes) >= 8:
840
+ break
841
+ all_paragraphs = [Paragraph(child, doc) for child in children if child.tag == qn("w:p") and Paragraph(child, doc).text.strip()]
842
+ all_positions = {paragraph._p: index for index, paragraph in enumerate(all_paragraphs)}
843
+ boundary_candidates = []
844
+ for element_index in dict.fromkeys(boundary_indexes):
845
+ child = children[element_index]
846
+ if child.tag != qn("w:p"):
847
+ continue
848
+ paragraph = Paragraph(child, doc)
849
+ if not paragraph.text.strip():
850
+ continue
851
+ record = _candidate_record(element_index, paragraph, all_paragraphs, all_positions[paragraph._p])
852
+ record.update({
853
+ "kind": "region_start",
854
+ "current_role": roles.get(paragraph._p, "区外"),
855
+ "current_boundary": region is not None and element_index == region[0],
856
+ })
857
+ boundary_candidates.append(record)
858
+
859
+ ids = ",".join(item["id"] for item in candidates + boundary_candidates)
860
+ batch_id = hashlib.sha256(f"{fingerprint}|{ids}".encode("ascii")).hexdigest()[:24]
861
+ return {
862
+ "batch_id": batch_id,
863
+ "candidates": [item for item in candidates if item.get("kind") != "table_role"],
864
+ "role_candidates": role_candidates,
865
+ "boundary_candidates": boundary_candidates,
866
+ "candidate_count": len(candidates),
867
+ "truncated": truncated,
868
+ "privacy": "仅含本地筛出的候选标题、表格前段落、附注边界及前后各最多100字;不含整篇报告或表格单元格。",
869
+ "apply_mode": "只应用用户确认的直接排版和附注起始边界,不写标题样式、不改大纲级别、不更新目录。",
870
+ }
871
+
872
+
873
+ def scan_heading_candidates(docx: str | Path) -> dict:
874
+ source = resolve_docx(str(docx))
875
+ fingerprint = hashlib.sha256(source.read_bytes()).hexdigest()
876
+ return _format_candidate_package(_open_document(source), fingerprint)
877
+
878
+
879
+ def _validated_format_overrides(
880
+ doc,
881
+ fingerprint: str,
882
+ heading_batch_id: str | None,
883
+ levels: dict | None,
884
+ role_batch_id: str | None,
885
+ role_overrides: dict | None,
886
+ region_start_id: str | None,
887
+ ) -> tuple[tuple[int, int] | None, dict[int, str]]:
888
+ package = _format_candidate_package(doc, fingerprint)
889
+ region = _notes_region(doc)
890
+ batch_ids = [value for value in (heading_batch_id, role_batch_id) if value is not None]
891
+ if not batch_ids and levels is None and role_overrides is None and region_start_id is None:
892
+ return region, {}
893
+ if any(not isinstance(value, str) or not value for value in batch_ids) or len(set(batch_ids)) > 1:
894
+ raise SyncError("候选批次编号必须是非空文本,且标题与角色批次必须一致")
895
+ if any(value != package["batch_id"] for value in batch_ids):
896
+ raise SyncError("报告或候选标题已变化,请重新扫描;旧批次结果不能应用")
897
+ if region_start_id is not None and role_batch_id is None:
898
+ raise SyncError("应用附注边界必须同时提供角色批次编号")
899
+ if role_overrides is not None and role_batch_id is None:
900
+ raise SyncError("应用疑难角色必须同时提供角色批次编号")
901
+ if levels is not None and heading_batch_id is None:
902
+ raise SyncError("应用候选标题级别必须同时提供标题批次编号")
903
+
904
+ heading_items = {item["id"]: item for item in package["candidates"]}
905
+ role_items = {item["id"]: item for item in package["role_candidates"]}
906
+ boundary_items = {item["id"]: item for item in package["boundary_candidates"]}
907
+ overrides: dict[int, str] = {}
908
+ if levels is not None:
909
+ if not isinstance(levels, dict) or not levels or len(levels) > 300:
910
+ raise SyncError("候选标题级别必须是最多 300 项的非空映射")
911
+ for key, value in levels.items():
912
+ if key not in heading_items:
913
+ raise SyncError("候选标题编号不存在或不属于当前批次,已停止应用")
914
+ if type(value) is not int or not 1 <= value <= 4:
915
+ raise SyncError("候选标题级别必须是 1~4 的整数")
916
+ overrides[heading_items[key]["element_index"]] = f"heading_{value}"
917
+ if role_overrides is not None:
918
+ if not isinstance(role_overrides, dict) or not role_overrides or len(role_overrides) > 300:
919
+ raise SyncError("疑难角色必须是最多 300 项的非空映射")
920
+ for key, value in role_overrides.items():
921
+ if key not in role_items:
922
+ raise SyncError("疑难角色编号不存在或不属于当前批次,已停止应用")
923
+ if value not in role_items[key]["options"]:
924
+ raise SyncError("疑难角色只能选择候选提供的正文或表格标题")
925
+ element_index = role_items[key]["element_index"]
926
+ if element_index in overrides and overrides[element_index] != value:
927
+ raise SyncError("同一候选不能同时确认为不同角色")
928
+ overrides[element_index] = value
929
+ if region_start_id is not None:
930
+ if not isinstance(region_start_id, str) or region_start_id not in boundary_items:
931
+ raise SyncError("附注边界编号不存在或不属于当前批次,已停止应用")
932
+ region = (boundary_items[region_start_id]["element_index"], len(doc.element.body))
933
+ return region, overrides
934
+
935
+
936
+ def _mode(values, *, ignore_none: bool = False):
937
+ usable = [value for value in values if not ignore_none or value is not None]
938
+ if not usable:
939
+ return None
940
+ return Counter(usable).most_common(1)[0][0]
941
+
942
+
943
+ def _default_formats() -> dict[str, ParagraphFormat]:
944
+ body = ParagraphFormat("Times New Roman", "宋体", 10.5, None, "left", 20.0, "exact", 0.0, 0.0, 21.0, 0.0)
945
+ return {
946
+ "cover_title": ParagraphFormat("Times New Roman", "宋体", 26.0, True, "center", 47.0, "atLeast", 0.0, 0.0, 0.0, 0.0),
947
+ "cover_info": ParagraphFormat("Times New Roman", "宋体", 14.0, None, "center", 30.0, "atLeast", 0.0, 0.0, 0.0, 0.0),
948
+ "toc_title": ParagraphFormat("Times New Roman", "宋体", 18.0, True, "center", 24.0, "exact", 0.0, 0.0, 0.0, 0.0),
949
+ "toc_entry": ParagraphFormat("Times New Roman", "宋体", 12.0, False, "left", 40.0, "atLeast", 0.0, 0.0, 0.0, 26.25),
950
+ "heading_1": ParagraphFormat("Times New Roman", "宋体", 12.0, True, "left", 20.0, "exact", 12.0, 0.0, 24.1, 0.0),
951
+ "heading_2": ParagraphFormat("Times New Roman", "宋体", 10.5, True, "left", 20.0, "exact", 6.0, 0.0, 21.1, 0.0),
952
+ "heading_3": ParagraphFormat("Times New Roman", "宋体", 10.5, False, "left", 18.0, "exact", 6.0, 0.0, 21.1, 0.0),
953
+ "heading_4": ParagraphFormat("Times New Roman", "宋体", 10.5, False, "left", 18.0, "exact", 6.0, 0.0, 31.5, 0.0),
954
+ "statement": ParagraphFormat("Times New Roman", "宋体", 10.5, False, "left", 18.0, "exact", 6.0, 0.0, 31.5, 0.0),
955
+ "table_title": ParagraphFormat("Times New Roman", "宋体", 9.0, True, "center", 18.0, "exact", 6.0, 0.0, 0.0, 0.0),
956
+ "table_continuation": ParagraphFormat("Times New Roman", "宋体", 10.5, False, "right", 1.0, "auto", 0.0, 0.0, 0.0, 0.0),
957
+ "body": body,
958
+ }
959
+
960
+
961
+ def _merge_format(default: ParagraphFormat, samples: list[ParagraphFormat]) -> ParagraphFormat:
962
+ if not samples:
963
+ return default
964
+ bold_values = [item.bold for item in samples]
965
+ bold = _mode(bold_values)
966
+ if bold is None and default.bold is not None:
967
+ bold = default.bold
968
+ return ParagraphFormat(
969
+ ascii_font=_mode([item.ascii_font for item in samples], ignore_none=True) or default.ascii_font,
970
+ east_asia_font=_mode([item.east_asia_font for item in samples], ignore_none=True) or default.east_asia_font,
971
+ size=_mode([item.size for item in samples], ignore_none=True) or default.size,
972
+ bold=bold,
973
+ align=_mode([item.align for item in samples], ignore_none=True) or default.align,
974
+ line_value=_mode([item.line_value for item in samples], ignore_none=True) or default.line_value,
975
+ line_rule=_mode([item.line_rule for item in samples if item.line_value is not None], ignore_none=True) or default.line_rule,
976
+ before=_mode([item.before for item in samples]) if any(item.before is not None for item in samples) else default.before,
977
+ after=_mode([item.after for item in samples]) if any(item.after is not None for item in samples) else default.after,
978
+ first_line=_mode([item.first_line for item in samples], ignore_none=True) or default.first_line,
979
+ left=_mode([item.left for item in samples], ignore_none=True) or default.left,
980
+ )
981
+
982
+
983
+ def _table_run_formats(doc, tables: list[Table] | None = None) -> tuple[Counter, Counter]:
984
+ fonts = Counter()
985
+ sizes = Counter()
986
+ for table in doc.tables if tables is None else tables:
987
+ for row in table.rows:
988
+ for cell in row.cells:
989
+ for paragraph in cell.paragraphs:
990
+ run = next((item for item in paragraph.runs if item.text.strip()), None)
991
+ if run is None:
992
+ continue
993
+ fmt = _effective_paragraph_format(paragraph)
994
+ if fmt.ascii_font:
995
+ fonts[fmt.ascii_font] += len(run.text)
996
+ if fmt.east_asia_font:
997
+ fonts[fmt.east_asia_font] += len(run.text)
998
+ if fmt.size is not None:
999
+ sizes[fmt.size] += len(run.text)
1000
+ return fonts, sizes
1001
+
1002
+
1003
+ def _table_border_containers(table: Table) -> list:
1004
+ containers = [table._tbl.tblPr]
1005
+ style = table.style or table.part.styles.default(WD_STYLE_TYPE.TABLE)
1006
+ seen = set()
1007
+ while style is not None and style.style_id not in seen:
1008
+ seen.add(style.style_id)
1009
+ tbl_pr = style.element.find(qn("w:tblPr"))
1010
+ if tbl_pr is not None:
1011
+ containers.append(tbl_pr)
1012
+ style = style.base_style
1013
+ return containers
1014
+
1015
+
1016
+ def _read_border(element) -> BorderFormat | None:
1017
+ if element is None:
1018
+ return None
1019
+ val = element.get(qn("w:val")) or "single"
1020
+ if val not in BORDER_VALUES:
1021
+ return None
1022
+ size = _number(element, "sz", 8.0)
1023
+ if val in ("nil", "none"):
1024
+ size = 0.0
1025
+ elif size is None:
1026
+ size = 0.5
1027
+ color = element.get(qn("w:color"))
1028
+ if color is not None and color.lower() != "auto" and not re.fullmatch(r"[0-9a-fA-F]{6}", color):
1029
+ color = None
1030
+ return BorderFormat(val, size, color)
1031
+
1032
+
1033
+ def _extract_table_borders(table: Table) -> dict[str, BorderFormat | None]:
1034
+ containers = _table_border_containers(table)
1035
+ result = {}
1036
+ for edge in BORDER_EDGES:
1037
+ result[edge] = None
1038
+ for container in containers:
1039
+ borders = container.find(qn("w:tblBorders"))
1040
+ border = borders.find(qn(f"w:{edge}")) if borders is not None else None
1041
+ value = _read_border(border)
1042
+ if value is not None:
1043
+ result[edge] = value
1044
+ break
1045
+ return result
1046
+
1047
+
1048
+ def _build_table_borders(doc, tables: list[Table] | None = None) -> dict[str, BorderFormat]:
1049
+ samples: dict[str, list[BorderFormat]] = {edge: [] for edge in BORDER_EDGES}
1050
+ for table in doc.tables if tables is None else tables:
1051
+ for edge, value in _extract_table_borders(table).items():
1052
+ if value is not None:
1053
+ samples[edge].append(value)
1054
+ return {edge: _mode(samples[edge]) or BorderFormat() for edge in BORDER_EDGES}
1055
+
1056
+
1057
+ def build_profile(template: str | Path, source: str | Path | None = None) -> FormatProfile:
1058
+ path = resolve_docx(str(template))
1059
+ doc = _open_document(path)
1060
+ source_is_notes = source is not None and _notes_region(_open_document(resolve_docx(str(source)))) is not None
1061
+ region = _notes_region(doc)
1062
+ if source_is_notes and region is None:
1063
+ raise SyncError("样板报告中未找到可识别的财务报表附注区,已停止套用")
1064
+ classified, _ = _classify_paragraphs(doc, region=region if source_is_notes else None)
1065
+ grouped: dict[str, list[ParagraphFormat]] = defaultdict(list)
1066
+ for paragraph, role in classified:
1067
+ grouped[role].append(_effective_paragraph_format(paragraph))
1068
+ formats = _default_formats()
1069
+ for role, samples in grouped.items():
1070
+ formats[role] = _merge_format(formats.get(role, ParagraphFormat()), samples)
1071
+ tables = _region_tables(doc, region) if source_is_notes else None
1072
+ fonts, sizes = _table_run_formats(doc, tables)
1073
+ ascii_fonts = [name for name in fonts if name not in ("宋体", "SimSun", "微软雅黑")]
1074
+ return FormatProfile(
1075
+ paragraphs=formats,
1076
+ table_ascii_font=_mode(ascii_fonts) or "Times New Roman",
1077
+ table_east_asia_font=_mode([name for name in fonts if name in ("宋体", "SimSun")]) or "宋体",
1078
+ table_size=_mode([size for size in sizes if size <= 9.0]) or _mode(list(sizes)) or 9.0,
1079
+ table_borders=_build_table_borders(doc, tables),
1080
+ template=str(path),
1081
+ )
1082
+
1083
+
1084
+ def _suggested_output(source: Path) -> Path:
1085
+ candidate = source.with_name(f"{source.stem}_格式调整{source.suffix}")
1086
+ counter = 2
1087
+ while candidate.exists():
1088
+ candidate = source.with_name(f"{source.stem}_格式调整_{counter}{source.suffix}")
1089
+ counter += 1
1090
+ return candidate
1091
+
1092
+
1093
+ def _format_summary(fmt: ParagraphFormat) -> str:
1094
+ font = " / ".join(dict.fromkeys(item for item in (fmt.ascii_font, fmt.east_asia_font) if item))
1095
+ parts = [font or "继承字体"]
1096
+ if fmt.size is not None:
1097
+ parts.append(f"{fmt.size:g}磅")
1098
+ if fmt.bold is not None:
1099
+ parts.append("加粗" if fmt.bold else "不加粗")
1100
+ parts.append(ALIGN_LABELS.get(fmt.align, fmt.align or "默认对齐"))
1101
+ if fmt.line_value is not None:
1102
+ if fmt.line_rule == "auto":
1103
+ parts.append(f"{fmt.line_value:g}倍行距")
1104
+ else:
1105
+ rule = "固定行距" if fmt.line_rule == "exact" else "最小行距"
1106
+ parts.append(f"{rule}{fmt.line_value:g}磅")
1107
+ if fmt.first_line:
1108
+ parts.append(f"首行缩进{fmt.first_line:g}磅")
1109
+ if fmt.left:
1110
+ parts.append(f"左缩进{fmt.left:g}磅")
1111
+ return ";".join(parts)
1112
+
1113
+
1114
+ def _table_border_summary(profile: FormatProfile) -> str:
1115
+ if profile.table_borders is None:
1116
+ return "旧方案未保存框线数据,保持原样"
1117
+ groups: dict[BorderFormat, list[str]] = defaultdict(list)
1118
+ for edge in BORDER_EDGES:
1119
+ groups[profile.table_borders[edge]].append(BORDER_EDGE_LABELS[edge])
1120
+ parts = []
1121
+ for fmt, labels in groups.items():
1122
+ if fmt.val in ("nil", "none"):
1123
+ parts.append(f"{'、'.join(labels)}无框线")
1124
+ else:
1125
+ value = f"{'、'.join(labels)}:{BORDER_STYLE_LABELS[fmt.val]} {fmt.size:g}磅"
1126
+ if fmt.color:
1127
+ value += f" #{fmt.color}"
1128
+ parts.append(value)
1129
+ return ";".join(parts)
1130
+
1131
+
1132
+ def _apply_table_borders(table: Table, profile: FormatProfile) -> bool:
1133
+ if profile.table_borders is None:
1134
+ return False
1135
+ tbl_pr = table._tbl.tblPr
1136
+ previous = tbl_pr.find(qn("w:tblBorders"))
1137
+ if previous is not None:
1138
+ tbl_pr.remove(previous)
1139
+ borders = OxmlElement("w:tblBorders")
1140
+ for edge in BORDER_EDGES:
1141
+ fmt = profile.table_borders[edge]
1142
+ element = OxmlElement(f"w:{edge}")
1143
+ element.set(qn("w:val"), fmt.val)
1144
+ element.set(qn("w:space"), "0")
1145
+ if fmt.val not in ("nil", "none"):
1146
+ if fmt.size > 0:
1147
+ element.set(qn("w:sz"), str(round(fmt.size * 8)))
1148
+ if fmt.color:
1149
+ element.set(qn("w:color"), fmt.color)
1150
+ borders.append(element)
1151
+ successors = {
1152
+ qn("w:shd"), qn("w:tblLayout"), qn("w:tblCellMar"), qn("w:tblLook"),
1153
+ qn("w:tblCaption"), qn("w:tblDescription"), qn("w:tblPrChange"),
1154
+ }
1155
+ for child in tbl_pr:
1156
+ if child.tag in successors:
1157
+ child.addprevious(borders)
1158
+ break
1159
+ else:
1160
+ tbl_pr.append(borders)
1161
+ for cell in table._tbl.xpath(".//w:tc"):
1162
+ tc_pr = cell.find(qn("w:tcPr"))
1163
+ cell_borders = tc_pr.find(qn("w:tcBorders")) if tc_pr is not None else None
1164
+ if cell_borders is not None:
1165
+ tc_pr.remove(cell_borders)
1166
+ return True
1167
+
1168
+
1169
+ def _table_row_roles(table: Table) -> list[str]:
1170
+ roles = []
1171
+ header_seen = False
1172
+ for row in table.rows:
1173
+ first_text = next((cell.text.strip() for cell in row.cells if cell.text.strip()), "")
1174
+ if first_text.startswith(("合计", "小计", "总计")):
1175
+ roles.append("table_total")
1176
+ elif not header_seen and any(cell.text.strip() for cell in row.cells):
1177
+ roles.append("table_header")
1178
+ header_seen = True
1179
+ else:
1180
+ roles.append("table_data")
1181
+ return roles
1182
+
1183
+
1184
+ def _paragraph_runs(paragraph: Paragraph) -> list[Run]:
1185
+ return [Run(element, paragraph) for element in paragraph._p.xpath(".//w:r") if element.xpath(".//w:t")]
1186
+
1187
+
1188
+ def _set_run_font(run: Run, fmt: ParagraphFormat, *, size: float | None = None, bold: bool | None = None) -> None:
1189
+ if fmt.ascii_font:
1190
+ run.font.name = fmt.ascii_font
1191
+ rpr = run._r.get_or_add_rPr()
1192
+ rfonts = rpr.find(qn("w:rFonts"))
1193
+ if rfonts is None:
1194
+ rfonts = OxmlElement("w:rFonts")
1195
+ rpr.insert(0, rfonts)
1196
+ rfonts.set(qn("w:ascii"), fmt.ascii_font)
1197
+ rfonts.set(qn("w:hAnsi"), fmt.ascii_font)
1198
+ if fmt.east_asia_font:
1199
+ rfonts.set(qn("w:eastAsia"), fmt.east_asia_font)
1200
+ rfonts.set(qn("w:cs"), fmt.ascii_font)
1201
+ target_size = fmt.size if size is None else size
1202
+ if target_size is not None:
1203
+ run.font.size = Pt(target_size)
1204
+ target_bold = fmt.bold if bold is None else bold
1205
+ if target_bold is not None:
1206
+ run.font.bold = target_bold
1207
+
1208
+
1209
+ def _clean_paragraph_format(paragraph: Paragraph) -> None:
1210
+ ppr = paragraph._p.get_or_add_pPr()
1211
+ spacing = ppr.find(qn("w:spacing"))
1212
+ if spacing is not None:
1213
+ for name in ("before", "after", "line", "lineRule", "beforeLines", "afterLines", "beforeAutospacing", "afterAutospacing"):
1214
+ spacing.attrib.pop(qn(f"w:{name}"), None)
1215
+ if not spacing.attrib:
1216
+ ppr.remove(spacing)
1217
+ indent = ppr.find(qn("w:ind"))
1218
+ if indent is not None:
1219
+ for name in ("left", "leftChars", "firstLine", "firstLineChars", "hanging", "hangingChars"):
1220
+ indent.attrib.pop(qn(f"w:{name}"), None)
1221
+ if not indent.attrib:
1222
+ ppr.remove(indent)
1223
+ alignment = ppr.find(qn("w:jc"))
1224
+ if alignment is not None:
1225
+ ppr.remove(alignment)
1226
+ containers = [run._r.rPr for run in _paragraph_runs(paragraph)]
1227
+ mark_rpr = ppr.find(qn("w:rPr"))
1228
+ if mark_rpr is not None:
1229
+ containers.append(mark_rpr)
1230
+ for rpr in containers:
1231
+ if rpr is None:
1232
+ continue
1233
+ for name in ("rFonts", "sz", "szCs", "b", "bCs"):
1234
+ for element in rpr.findall(qn(f"w:{name}")):
1235
+ rpr.remove(element)
1236
+ if not len(rpr):
1237
+ rpr.getparent().remove(rpr)
1238
+
1239
+
1240
+ def _apply_paragraph_format(paragraph: Paragraph, fmt: ParagraphFormat) -> None:
1241
+ _clean_paragraph_format(paragraph)
1242
+ for run in _paragraph_runs(paragraph):
1243
+ _set_run_font(run, fmt)
1244
+ pf = paragraph.paragraph_format
1245
+ if fmt.align in ALIGN_VALUES:
1246
+ pf.alignment = ALIGN_VALUES[fmt.align]
1247
+ if fmt.line_value is not None:
1248
+ pf.line_spacing = fmt.line_value if fmt.line_rule == "auto" else Pt(fmt.line_value)
1249
+ if fmt.before is not None:
1250
+ pf.space_before = Pt(fmt.before)
1251
+ if fmt.after is not None:
1252
+ pf.space_after = Pt(fmt.after)
1253
+ if fmt.first_line is not None:
1254
+ pf.first_line_indent = Pt(fmt.first_line)
1255
+ if fmt.left is not None:
1256
+ pf.left_indent = Pt(fmt.left)
1257
+
1258
+
1259
+ def _looks_numeric(text: str) -> bool:
1260
+ value = text.strip().replace(",", "").replace(",", "")
1261
+ if value in ("", "-", "—", "–", "(", ")", "()"):
1262
+ return False
1263
+ return bool(re.fullmatch(r"[¥¥$]?-?\d[\d,]*(?:\.\d+)?%?\)?", value))
1264
+
1265
+
1266
+ def _apply_table_format(table: Table, profile: FormatProfile, scope: dict[str, bool]) -> tuple[int, Counter]:
1267
+ apply_text = scope["table_text"]
1268
+ apply_emphasis = scope["table_emphasis"]
1269
+ if not apply_text and not apply_emphasis:
1270
+ return 0, Counter()
1271
+ base = ParagraphFormat(profile.table_ascii_font, profile.table_east_asia_font, profile.table_size, None)
1272
+ formatted = 0
1273
+ roles = _table_row_roles(table)
1274
+ for row_index, row in enumerate(table.rows):
1275
+ role = roles[row_index]
1276
+ for cell in row.cells:
1277
+ for paragraph in cell.paragraphs:
1278
+ if not paragraph.text.strip():
1279
+ continue
1280
+ if apply_emphasis:
1281
+ align = "center" if role == "table_header" else ("right" if _looks_numeric(paragraph.text) else "left")
1282
+ paragraph.alignment = ALIGN_VALUES[align]
1283
+ for run in _paragraph_runs(paragraph):
1284
+ if not apply_text:
1285
+ if role in ("table_header", "table_total"):
1286
+ run.font.bold = True
1287
+ continue
1288
+ current_size = _effective_run_size(paragraph, run)
1289
+ size = min(current_size, profile.table_size) if current_size is not None else profile.table_size
1290
+ bold = True if apply_emphasis and role in ("table_header", "table_total") else None
1291
+ _set_run_font(run, base, size=size, bold=bold)
1292
+ formatted += 1
1293
+ return formatted, Counter(roles)
1294
+
1295
+
1296
+ def _apply_profile(
1297
+ doc,
1298
+ profile: FormatProfile,
1299
+ scope: dict[str, bool],
1300
+ paragraph_overrides: dict[int, str] | None = None,
1301
+ region: tuple[int, int] | None = None,
1302
+ ) -> dict[str, int]:
1303
+ counts: Counter[str] = Counter()
1304
+ selected_roles = _selected_paragraph_roles(scope)
1305
+ classified, meta = _classify_paragraphs(doc, paragraph_overrides, region=region)
1306
+ skipped_paragraphs = 0
1307
+ protected_paragraphs = 0
1308
+ for paragraph, role in classified:
1309
+ if (_outline_level(paragraph) or 0) > 4:
1310
+ protected_paragraphs += 1
1311
+ continue
1312
+ if role not in selected_roles:
1313
+ skipped_paragraphs += 1
1314
+ continue
1315
+ fmt = profile.paragraphs.get(role) or profile.paragraphs["body"]
1316
+ _apply_paragraph_format(paragraph, fmt)
1317
+ counts[role] += 1
1318
+ table_paragraphs = 0
1319
+ skipped_tables = 0
1320
+ table_enabled = scope["table_text"] or scope["table_emphasis"] or scope["table_borders"]
1321
+ for table in _region_tables(doc, region):
1322
+ if not table_enabled:
1323
+ skipped_tables += 1
1324
+ continue
1325
+ formatted, roles = _apply_table_format(table, profile, scope)
1326
+ table_paragraphs += formatted
1327
+ counts.update(roles)
1328
+ if scope["table_borders"] and _apply_table_borders(table, profile):
1329
+ counts["table_borders"] += 1
1330
+ counts["table_paragraphs"] = table_paragraphs
1331
+ counts["ambiguous"] = meta["ambiguous"]
1332
+ counts["empty"] = meta["empty"]
1333
+ counts["protected_paragraphs"] = protected_paragraphs
1334
+ counts["skipped_paragraphs"] = skipped_paragraphs
1335
+ counts["skipped_tables"] = skipped_tables
1336
+ return dict(counts)
1337
+
1338
+
1339
+ def _document_snapshot(doc) -> dict:
1340
+ body = doc.element.body
1341
+ section_values = []
1342
+ for section in doc.sections:
1343
+ section_values.append((
1344
+ section.page_width, section.page_height, section.left_margin, section.right_margin,
1345
+ section.top_margin, section.bottom_margin, section.orientation,
1346
+ ))
1347
+ merges = []
1348
+ for table in body.xpath(".//w:tbl"):
1349
+ for cell in table.xpath(".//w:tc"):
1350
+ tcpr = cell.find(qn("w:tcPr"))
1351
+ grid = tcpr.find(qn("w:gridSpan")) if tcpr is not None else None
1352
+ vertical = tcpr.find(qn("w:vMerge")) if tcpr is not None else None
1353
+ merges.append((grid.get(qn("w:val")) if grid is not None else None, vertical.get(qn("w:val")) if vertical is not None else None))
1354
+ links = sorted(rel.target_ref for rel in doc.part.rels.values() if rel.is_external)
1355
+ return {
1356
+ "text": tuple(body.xpath(".//w:t/text()")),
1357
+ "bookmarks": tuple(body.xpath(".//w:bookmarkStart/@w:name")),
1358
+ "numbering": tuple(element.xml for element in body.xpath(".//w:numPr")),
1359
+ "outlines": tuple(element.xml for element in body.xpath(".//w:outlineLvl")),
1360
+ "fields": tuple(body.xpath(".//w:instrText/text()")) + tuple(body.xpath(".//w:fldSimple/@w:instr")),
1361
+ "tables": len(doc.tables),
1362
+ "table_shapes": tuple(
1363
+ (len(table.rows), tuple(len(row.cells) for row in table.rows), table._tbl.tblGrid.xml)
1364
+ for table in doc.tables
1365
+ ),
1366
+ "merges": tuple(merges),
1367
+ "sections": tuple(section_values),
1368
+ "links": tuple(links),
1369
+ }
1370
+
1371
+
1372
+ def _binary_parts(path: Path) -> dict[str, str]:
1373
+ prefixes = ("word/media/", "word/embeddings/", "word/fonts/")
1374
+ result = {}
1375
+ with zipfile.ZipFile(path) as archive:
1376
+ for name in archive.namelist():
1377
+ if name.startswith(prefixes) or name == "word/vbaProject.bin":
1378
+ result[name] = hashlib.sha256(archive.read(name)).hexdigest()
1379
+ return result
1380
+
1381
+
1382
+ def _validate_output(source: Path, output: Path, before: dict) -> None:
1383
+ check = _open_document(output)
1384
+ after = _document_snapshot(check)
1385
+ for key in before:
1386
+ if before[key] != after[key]:
1387
+ raise SyncError(f"格式副本校验失败:{key} 与原文不一致,已删除未通过的副本")
1388
+ if _binary_parts(source) != _binary_parts(output):
1389
+ raise SyncError("格式副本校验失败:图片、嵌入对象或 VBA 部分与原文不一致,已删除未通过的副本")
1390
+
1391
+
1392
+ def _format_source(source: Path, template: str | Path | None, profile_name: str | None) -> tuple[FormatProfile, str, bool]:
1393
+ if profile_name is not None:
1394
+ if template is not None:
1395
+ raise SyncError("样板报告与已存格式方案只能二选一")
1396
+ name = profile_name.strip()
1397
+ return load_format_profile(name), f"已存方案:{name}", False
1398
+ if template is None:
1399
+ return build_profile(source), str(source), True
1400
+ path = resolve_docx(str(template))
1401
+ return build_profile(path, source), str(path), False
1402
+
1403
+
1404
+ def _scan_opened_report(
1405
+ source: Path,
1406
+ template_label: str,
1407
+ profile: FormatProfile,
1408
+ target,
1409
+ self_sample: bool = False,
1410
+ scope: dict | None = None,
1411
+ paragraph_overrides: dict[int, str] | None = None,
1412
+ region: tuple[int, int] | None = None,
1413
+ ) -> dict:
1414
+ scope = _validated_scope(scope)
1415
+ selected_roles = _selected_paragraph_roles(scope)
1416
+ classified, meta = _classify_paragraphs(target, paragraph_overrides, region=region)
1417
+ counts = Counter(role for _, role in classified)
1418
+ protected_roles = Counter(role for paragraph, role in classified if (_outline_level(paragraph) or 0) > 4)
1419
+ protected = sum(protected_roles.values())
1420
+ selected_paragraphs = sum(counts[role] - protected_roles[role] for role in selected_roles)
1421
+ roles = []
1422
+ for role in ROLE_LABELS:
1423
+ if role in ("table_header", "table_total", "table_data"):
1424
+ continue
1425
+ if counts[role]:
1426
+ roles.append({
1427
+ "role": role,
1428
+ "label": ROLE_LABELS[role],
1429
+ "paragraphs": counts[role],
1430
+ "selected_paragraphs": counts[role] - protected_roles[role] if role in selected_roles else 0,
1431
+ "selected": role in selected_roles and counts[role] > protected_roles[role],
1432
+ "format": _format_summary(profile.paragraphs[role]),
1433
+ })
1434
+ table_enabled = scope["table_text"] or scope["table_emphasis"] or scope["table_borders"]
1435
+ tables = _region_tables(target, region)
1436
+ table_rows = sum(len(table.rows) for table in tables) if table_enabled else 0
1437
+ warnings = []
1438
+ if meta["ambiguous"]:
1439
+ warnings.append(f"有 {meta['ambiguous']} 个大纲级别异常的段落保持原样,不会强行套用格式。")
1440
+ if source.suffix.lower() == ".docm":
1441
+ warnings.append("将校验 Word 宏(VBA)是否完整保留。")
1442
+ if self_sample:
1443
+ warnings.append("未指定样板,已按原文件自身格式提取。")
1444
+ return {
1445
+ "source": str(source),
1446
+ "template": template_label,
1447
+ "suggested_output": str(_suggested_output(source)),
1448
+ "scope": dict(scope),
1449
+ "totals": {
1450
+ "paragraphs": len(classified),
1451
+ "tables": len(tables) if table_enabled else 0,
1452
+ "table_rows": table_rows,
1453
+ "empty_paragraphs": meta["empty"],
1454
+ "ambiguous_paragraphs": meta["ambiguous"],
1455
+ "selected_paragraphs": selected_paragraphs,
1456
+ "protected_paragraphs": protected,
1457
+ "skipped_paragraphs": len(classified) - selected_paragraphs - protected,
1458
+ "skipped_tables": 0 if table_enabled else len(tables),
1459
+ },
1460
+ "roles": roles,
1461
+ "table_format": _format_summary(ParagraphFormat(profile.table_ascii_font, profile.table_east_asia_font, profile.table_size, None)),
1462
+ "table_border_format": _table_border_summary(profile),
1463
+ "small_table_policy": "不大于样板表格字号的字号保留;较大字号统一为样板字号。",
1464
+ "warnings": warnings,
1465
+ }
1466
+
1467
+
1468
+ def scan_report_format(
1469
+ docx: str | Path,
1470
+ template: str | Path | None = None,
1471
+ *,
1472
+ profile_name: str | None = None,
1473
+ scope: dict | None = None,
1474
+ heading_batch_id: str | None = None,
1475
+ heading_levels: dict | None = None,
1476
+ role_batch_id: str | None = None,
1477
+ role_overrides: dict | None = None,
1478
+ region_start_id: str | None = None,
1479
+ ) -> dict:
1480
+ scope = _validated_scope(scope)
1481
+ source = resolve_docx(str(docx))
1482
+ profile, template_label, self_sample = _format_source(source, template, profile_name)
1483
+ target = _open_document(source)
1484
+ fingerprint = hashlib.sha256(source.read_bytes()).hexdigest() if any(
1485
+ value is not None
1486
+ for value in (heading_batch_id, heading_levels, role_batch_id, role_overrides, region_start_id)
1487
+ ) else ""
1488
+ region, paragraph_overrides = _validated_format_overrides(
1489
+ target, fingerprint, heading_batch_id, heading_levels,
1490
+ role_batch_id, role_overrides, region_start_id,
1491
+ )
1492
+ if any(role.startswith("heading_") for role in paragraph_overrides.values()) and not scope["headings"]:
1493
+ raise SyncError("应用候选标题级别时必须勾选“一至四级标题”")
1494
+ if any(role in ("table_title", "table_continuation") for role in paragraph_overrides.values()) and not scope["statement"]:
1495
+ raise SyncError("应用表格标题角色时必须勾选“报表名称、日期与表格标题”")
1496
+ return _scan_opened_report(
1497
+ source, template_label, profile, target, self_sample, scope,
1498
+ paragraph_overrides, region,
1499
+ )
1500
+
1501
+
1502
+ def run_report_format(
1503
+ docx: str | Path,
1504
+ template: str | Path | None = None,
1505
+ *,
1506
+ output: str | Path | None = None,
1507
+ dry_run: bool = False,
1508
+ profile_name: str | None = None,
1509
+ scope: dict | None = None,
1510
+ heading_batch_id: str | None = None,
1511
+ heading_levels: dict | None = None,
1512
+ role_batch_id: str | None = None,
1513
+ role_overrides: dict | None = None,
1514
+ region_start_id: str | None = None,
1515
+ ) -> dict:
1516
+ scope = _validated_scope(scope)
1517
+ source = resolve_docx(str(docx))
1518
+ output_path = _suggested_output(source) if output is None else Path(output).expanduser().resolve()
1519
+ if output_path.suffix.lower() != source.suffix.lower():
1520
+ raise SyncError("格式副本必须与原报告使用同一种文件类型(.docx 或 .docm)")
1521
+ if output_path == source:
1522
+ raise SyncError("为保护原报告,格式调整只生成新副本;请选择其他输出路径")
1523
+ if not output_path.parent.is_dir():
1524
+ raise SyncError(f"输出目录不存在:{output_path.parent}")
1525
+ if output_path.exists():
1526
+ raise SyncError(f"输出文件已存在,未覆盖:{output_path}")
1527
+ profile, template_label, self_sample = _format_source(source, template, profile_name)
1528
+ target = _open_document(source)
1529
+ fingerprint = hashlib.sha256(source.read_bytes()).hexdigest() if any(
1530
+ value is not None
1531
+ for value in (heading_batch_id, heading_levels, role_batch_id, role_overrides, region_start_id)
1532
+ ) else ""
1533
+ region, paragraph_overrides = _validated_format_overrides(
1534
+ target, fingerprint, heading_batch_id, heading_levels,
1535
+ role_batch_id, role_overrides, region_start_id,
1536
+ )
1537
+ if any(role.startswith("heading_") for role in paragraph_overrides.values()) and not scope["headings"]:
1538
+ raise SyncError("应用候选标题级别时必须勾选“一至四级标题”")
1539
+ if any(role in ("table_title", "table_continuation") for role in paragraph_overrides.values()) and not scope["statement"]:
1540
+ raise SyncError("应用表格标题角色时必须勾选“报表名称、日期与表格标题”")
1541
+ result = _scan_opened_report(
1542
+ source, template_label, profile, target, self_sample, scope,
1543
+ paragraph_overrides, region,
1544
+ )
1545
+ result["assigned_headings"] = sum(role.startswith("heading_") for role in paragraph_overrides.values())
1546
+ result["assigned_roles"] = sum(not role.startswith("heading_") for role in paragraph_overrides.values())
1547
+ result["region_start"] = region[0] if region is not None else None
1548
+ result["output"] = str(output_path)
1549
+ result["dry_run"] = bool(dry_run)
1550
+ result["visual_review"] = list(VISUAL_REVIEW)
1551
+ log(f"[格式] 格式来源:{template_label}")
1552
+ log(f"[格式] 待调整:{source.name}(处理 {result['totals']['selected_paragraphs']} 段、{result['totals']['tables']} 张表)")
1553
+ if dry_run:
1554
+ log(f"[格式] 预演完成,未写入文件;计划输出:{output_path.name}")
1555
+ return result
1556
+
1557
+ before = _document_snapshot(target)
1558
+ counts = _apply_profile(target, profile, scope, paragraph_overrides, region)
1559
+ fd, temp_name = tempfile.mkstemp(prefix=f".{output_path.stem}.", suffix=output_path.suffix, dir=output_path.parent)
1560
+ os.close(fd)
1561
+ staged = Path(temp_name)
1562
+ try:
1563
+ target.save(str(staged))
1564
+ if source.suffix.lower() == ".docm":
1565
+ _rewrite_main_type(staged, macro_enabled=True)
1566
+ _validate_output(source, staged, before)
1567
+ os.replace(staged, output_path)
1568
+ except Exception as exc:
1569
+ staged.unlink(missing_ok=True)
1570
+ if isinstance(exc, SyncError):
1571
+ raise
1572
+ raise SyncError(f"生成格式副本失败,原报告未改动:{exc}") from exc
1573
+ result["counts"] = counts
1574
+ result["applied"] = True
1575
+ log(f"[格式] 已生成:{output_path}")
1576
+ log("[格式] 已核验文字、书签、表格、分节、图片/嵌入对象和 VBA 与原文一致。")
1577
+ return result