audit-e2w 0.0.0-stage → 1.11.7
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.
- package/LICENSE +21 -0
- package/README.md +152 -3
- package/cordis.patch.yml +3 -0
- package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
- package/dsh_plugins/audit-e2w/lib/index.js +122 -0
- package/dsh_plugins/audit-e2w/lib/skill.js +42 -0
- package/excel_word/README.md +388 -0
- package/excel_word/qoder_engine.py +437 -0
- package/excel_word/requirements.txt +4 -0
- package/excel_word/wesync/__init__.py +19 -0
- package/excel_word/wesync/__main__.py +6 -0
- package/excel_word/wesync/ai/__init__.py +52 -0
- package/excel_word/wesync/ai/actions.py +369 -0
- package/excel_word/wesync/ai/client.py +340 -0
- package/excel_word/wesync/ai/config.py +291 -0
- package/excel_word/wesync/ai/docs.py +177 -0
- package/excel_word/wesync/ai/prompts.py +288 -0
- package/excel_word/wesync/ai/tasks/__init__.py +26 -0
- package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
- package/excel_word/wesync/ai/tasks/combined.py +123 -0
- package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
- package/excel_word/wesync/ai/tasks/headings.py +119 -0
- package/excel_word/wesync/ai/tasks/help_task.py +69 -0
- package/excel_word/wesync/ai/tasks/roles.py +128 -0
- package/excel_word/wesync/align.py +155 -0
- package/excel_word/wesync/api.py +1292 -0
- package/excel_word/wesync/backup_history.py +100 -0
- package/excel_word/wesync/changelog.py +58 -0
- package/excel_word/wesync/cli.py +191 -0
- package/excel_word/wesync/commands/__init__.py +8 -0
- package/excel_word/wesync/commands/blank_cmd.py +279 -0
- package/excel_word/wesync/commands/bookmark_cmd.py +146 -0
- package/excel_word/wesync/commands/clear_cmd.py +50 -0
- package/excel_word/wesync/commands/export_cmd.py +270 -0
- package/excel_word/wesync/commands/incremental_cmd.py +157 -0
- package/excel_word/wesync/commands/marks_cmd.py +160 -0
- package/excel_word/wesync/commands/placeholders_cmd.py +92 -0
- package/excel_word/wesync/commands/writeback_cmd.py +469 -0
- package/excel_word/wesync/config.py +97 -0
- package/excel_word/wesync/console.py +85 -0
- package/excel_word/wesync/docx_blank.py +156 -0
- package/excel_word/wesync/docx_bookmarks.py +294 -0
- package/excel_word/wesync/docx_columns.py +257 -0
- package/excel_word/wesync/docx_edit.py +77 -0
- package/excel_word/wesync/docx_grid.py +212 -0
- package/excel_word/wesync/docx_marks.py +399 -0
- package/excel_word/wesync/docx_meta.py +157 -0
- package/excel_word/wesync/docx_newtable.py +220 -0
- package/excel_word/wesync/docx_placeholders.py +200 -0
- package/excel_word/wesync/docx_rows.py +67 -0
- package/excel_word/wesync/errors.py +5 -0
- package/excel_word/wesync/excel_blocks.py +502 -0
- package/excel_word/wesync/excel_export.py +143 -0
- package/excel_word/wesync/excel_marks.py +265 -0
- package/excel_word/wesync/excel_totals.py +53 -0
- package/excel_word/wesync/fsops.py +219 -0
- package/excel_word/wesync/gui/__init__.py +53 -0
- package/excel_word/wesync/gui/__main__.py +6 -0
- package/excel_word/wesync/gui/app.py +613 -0
- package/excel_word/wesync/gui/manual.py +70 -0
- package/excel_word/wesync/gui/pages/__init__.py +80 -0
- package/excel_word/wesync/gui/pages/_page.py +211 -0
- package/excel_word/wesync/gui/pages/ai_page.py +854 -0
- package/excel_word/wesync/gui/pages/batch_page.py +456 -0
- package/excel_word/wesync/gui/pages/blank_page.py +530 -0
- package/excel_word/wesync/gui/pages/bookmark_page.py +97 -0
- package/excel_word/wesync/gui/pages/export_page.py +141 -0
- package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
- package/excel_word/wesync/gui/pages/format_page.py +551 -0
- package/excel_word/wesync/gui/pages/help_page.py +158 -0
- package/excel_word/wesync/gui/pages/history_page.py +168 -0
- package/excel_word/wesync/gui/pages/marks_page.py +211 -0
- package/excel_word/wesync/gui/pages/settings_page.py +450 -0
- package/excel_word/wesync/gui/pages/writeback_page.py +473 -0
- package/excel_word/wesync/gui/resources.py +22 -0
- package/excel_word/wesync/gui/runner.py +90 -0
- package/excel_word/wesync/gui/store.py +50 -0
- package/excel_word/wesync/gui/theme.py +271 -0
- package/excel_word/wesync/gui/widgets/__init__.py +8 -0
- package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
- package/excel_word/wesync/gui/widgets/cards.py +139 -0
- package/excel_word/wesync/gui/widgets/chips.py +565 -0
- package/excel_word/wesync/gui/widgets/filebar.py +58 -0
- package/excel_word/wesync/gui/widgets/logpane.py +126 -0
- package/excel_word/wesync/gui/widgets/nav.py +294 -0
- package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
- package/excel_word/wesync/report_format.py +1585 -0
- package/excel_word/wesync/settings.py +35 -0
- package/excel_word/wesync/sort_rules.py +293 -0
- package/excel_word/wesync/valuefmt.py +485 -0
- package/package.json +53 -6
- package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
- package/qoder_plugins/audit-toolbox/README.md +159 -0
- package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
|
@@ -0,0 +1,1585 @@
|
|
|
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
|
+
# 目录条目结尾:制表符、引导点,或末尾页码 / 页码区间(如「1-3」「1–3」「11~12」)。
|
|
735
|
+
# 缺了页码区间这一支,目录里的「一、审计报告 1-3」会被当成正文候选送进模型。
|
|
736
|
+
_TOC_TAIL_RE = re.compile(r"(?:\.{2,}|…{2,}|\t)|\s\d+(?:\s*[-–—-~]\s*\d+)?\s*$")
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def _context_text(paragraph: Paragraph | None) -> str:
|
|
740
|
+
return re.sub(r"\s+", " ", paragraph.text).strip()[:100] if paragraph is not None else ""
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def _candidate_id(element_index: int, paragraph: Paragraph) -> str:
|
|
744
|
+
digest = hashlib.sha256(_normalized_text(paragraph).encode("utf-8")).hexdigest()[:10]
|
|
745
|
+
return f"b{element_index:04d}-{digest}"
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _candidate_record(element_index: int, paragraph: Paragraph, paragraphs: list[Paragraph], position: int) -> dict:
|
|
749
|
+
text = re.sub(r"\s+", " ", paragraph.text).strip()
|
|
750
|
+
fmt = _effective_paragraph_format(paragraph)
|
|
751
|
+
return {
|
|
752
|
+
"id": _candidate_id(element_index, paragraph),
|
|
753
|
+
"element_index": element_index,
|
|
754
|
+
"text": text,
|
|
755
|
+
"before": _context_text(paragraphs[position - 1] if position else None),
|
|
756
|
+
"after": _context_text(paragraphs[position + 1] if position + 1 < len(paragraphs) else None),
|
|
757
|
+
"style": paragraph.style.name if paragraph.style is not None else "",
|
|
758
|
+
"bold": fmt.bold,
|
|
759
|
+
"size": fmt.size,
|
|
760
|
+
"align": ALIGN_LABELS.get(fmt.align, fmt.align or "默认"),
|
|
761
|
+
"numbered": bool(_HEADING_NUMBER_RE.match(text)),
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def _format_candidate_package(doc, fingerprint: str) -> dict:
|
|
766
|
+
region = _notes_region(doc)
|
|
767
|
+
entries = list(_region_entries(doc, region))
|
|
768
|
+
paragraph_entries = [(index, item) for index, item in entries if isinstance(item, Paragraph) and item.text.strip()]
|
|
769
|
+
paragraphs = [item for _, item in paragraph_entries]
|
|
770
|
+
positions = {paragraph._p: index for index, paragraph in enumerate(paragraphs)}
|
|
771
|
+
classified, _ = _classify_paragraphs(doc, region=region)
|
|
772
|
+
roles = {paragraph._p: role for paragraph, role in classified}
|
|
773
|
+
toc_index = next((index for index, item in enumerate(paragraphs) if _normalized_text(item) == "目录"), None)
|
|
774
|
+
content_start = 0
|
|
775
|
+
if toc_index is not None:
|
|
776
|
+
content_start = toc_index + 1
|
|
777
|
+
while content_start < len(paragraphs):
|
|
778
|
+
text = re.sub(r"\s+", " ", paragraphs[content_start].text).strip()
|
|
779
|
+
style_name = paragraphs[content_start].style.name if paragraphs[content_start].style is not None else ""
|
|
780
|
+
if "toc" not in style_name.lower() and "目录" not in style_name and not _TOC_TAIL_RE.search(text):
|
|
781
|
+
break
|
|
782
|
+
content_start += 1
|
|
783
|
+
|
|
784
|
+
candidates = []
|
|
785
|
+
truncated = False
|
|
786
|
+
for element_index, paragraph in paragraph_entries:
|
|
787
|
+
index = positions[paragraph._p]
|
|
788
|
+
text = re.sub(r"\s+", " ", paragraph.text).strip()
|
|
789
|
+
level = _outline_level(paragraph)
|
|
790
|
+
if roles[paragraph._p] not in ("body", "toc_entry") or index < content_start or level is not None or not 2 <= len(text) <= 120:
|
|
791
|
+
continue
|
|
792
|
+
if DATE_RE.match(text) or re.search(r"[。;;!!??]$", text):
|
|
793
|
+
continue
|
|
794
|
+
# 带页码/页码区间的条目是目录行,不是标题:交给模型只会被误判,也浪费 token。
|
|
795
|
+
if _TOC_TAIL_RE.search(text):
|
|
796
|
+
continue
|
|
797
|
+
fmt = _effective_paragraph_format(paragraph)
|
|
798
|
+
visual = fmt.bold is True or fmt.align == "center" or (fmt.size is not None and fmt.size >= 14)
|
|
799
|
+
if not _HEADING_NUMBER_RE.match(text) and not (visual and len(text) <= 60):
|
|
800
|
+
continue
|
|
801
|
+
candidates.append(_candidate_record(element_index, paragraph, paragraphs, index))
|
|
802
|
+
if len(candidates) == 300:
|
|
803
|
+
truncated = True
|
|
804
|
+
break
|
|
805
|
+
|
|
806
|
+
heading_ids = {item["id"] for item in candidates}
|
|
807
|
+
role_candidates = []
|
|
808
|
+
previous: tuple[int, Paragraph] | None = None
|
|
809
|
+
for element_index, item in entries:
|
|
810
|
+
if isinstance(item, Paragraph):
|
|
811
|
+
if item.text.strip():
|
|
812
|
+
previous = (element_index, item)
|
|
813
|
+
continue
|
|
814
|
+
if previous is None:
|
|
815
|
+
continue
|
|
816
|
+
previous_index, paragraph = previous
|
|
817
|
+
if len(candidates) >= 300:
|
|
818
|
+
if roles[paragraph._p] == "body" and _outline_level(paragraph) is None and _candidate_id(previous_index, paragraph) not in heading_ids:
|
|
819
|
+
truncated = True
|
|
820
|
+
continue
|
|
821
|
+
if roles[paragraph._p] != "body" or _outline_level(paragraph) is not None or _candidate_id(previous_index, paragraph) in heading_ids:
|
|
822
|
+
continue
|
|
823
|
+
text = re.sub(r"\s+", " ", paragraph.text).strip()
|
|
824
|
+
if not 2 <= len(text) <= 120 or DATE_RE.match(text):
|
|
825
|
+
continue
|
|
826
|
+
record = _candidate_record(previous_index, paragraph, paragraphs, positions[paragraph._p])
|
|
827
|
+
record.update({
|
|
828
|
+
"kind": "table_role",
|
|
829
|
+
"current_role": "body",
|
|
830
|
+
"options": ["body", "table_title"],
|
|
831
|
+
"next_element": "表格(未读取单元格内容)",
|
|
832
|
+
})
|
|
833
|
+
role_candidates.append(record)
|
|
834
|
+
candidates.append(record)
|
|
835
|
+
|
|
836
|
+
children = list(doc.element.body.iterchildren())
|
|
837
|
+
boundary_indexes: list[int] = []
|
|
838
|
+
if region is not None:
|
|
839
|
+
boundary_indexes = list(range(max(0, region[0] - 3), min(len(children), region[0] + 5)))
|
|
840
|
+
else:
|
|
841
|
+
for index, child in enumerate(children):
|
|
842
|
+
if child.tag == qn("w:p") and "财务报表附注" in Paragraph(child, doc).text:
|
|
843
|
+
boundary_indexes.append(index)
|
|
844
|
+
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)
|
|
845
|
+
if previous_index is not None:
|
|
846
|
+
boundary_indexes.append(previous_index)
|
|
847
|
+
if len(boundary_indexes) >= 8:
|
|
848
|
+
break
|
|
849
|
+
all_paragraphs = [Paragraph(child, doc) for child in children if child.tag == qn("w:p") and Paragraph(child, doc).text.strip()]
|
|
850
|
+
all_positions = {paragraph._p: index for index, paragraph in enumerate(all_paragraphs)}
|
|
851
|
+
boundary_candidates = []
|
|
852
|
+
for element_index in dict.fromkeys(boundary_indexes):
|
|
853
|
+
child = children[element_index]
|
|
854
|
+
if child.tag != qn("w:p"):
|
|
855
|
+
continue
|
|
856
|
+
paragraph = Paragraph(child, doc)
|
|
857
|
+
if not paragraph.text.strip():
|
|
858
|
+
continue
|
|
859
|
+
record = _candidate_record(element_index, paragraph, all_paragraphs, all_positions[paragraph._p])
|
|
860
|
+
record.update({
|
|
861
|
+
"kind": "region_start",
|
|
862
|
+
"current_role": roles.get(paragraph._p, "区外"),
|
|
863
|
+
"current_boundary": region is not None and element_index == region[0],
|
|
864
|
+
})
|
|
865
|
+
boundary_candidates.append(record)
|
|
866
|
+
|
|
867
|
+
ids = ",".join(item["id"] for item in candidates + boundary_candidates)
|
|
868
|
+
batch_id = hashlib.sha256(f"{fingerprint}|{ids}".encode("ascii")).hexdigest()[:24]
|
|
869
|
+
return {
|
|
870
|
+
"batch_id": batch_id,
|
|
871
|
+
"candidates": [item for item in candidates if item.get("kind") != "table_role"],
|
|
872
|
+
"role_candidates": role_candidates,
|
|
873
|
+
"boundary_candidates": boundary_candidates,
|
|
874
|
+
"candidate_count": len(candidates),
|
|
875
|
+
"truncated": truncated,
|
|
876
|
+
"privacy": "仅含本地筛出的候选标题、表格前段落、附注边界及前后各最多100字;不含整篇报告或表格单元格。",
|
|
877
|
+
"apply_mode": "只应用用户确认的直接排版和附注起始边界,不写标题样式、不改大纲级别、不更新目录。",
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
def scan_heading_candidates(docx: str | Path) -> dict:
|
|
882
|
+
source = resolve_docx(str(docx))
|
|
883
|
+
fingerprint = hashlib.sha256(source.read_bytes()).hexdigest()
|
|
884
|
+
return _format_candidate_package(_open_document(source), fingerprint)
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
def _validated_format_overrides(
|
|
888
|
+
doc,
|
|
889
|
+
fingerprint: str,
|
|
890
|
+
heading_batch_id: str | None,
|
|
891
|
+
levels: dict | None,
|
|
892
|
+
role_batch_id: str | None,
|
|
893
|
+
role_overrides: dict | None,
|
|
894
|
+
region_start_id: str | None,
|
|
895
|
+
) -> tuple[tuple[int, int] | None, dict[int, str]]:
|
|
896
|
+
package = _format_candidate_package(doc, fingerprint)
|
|
897
|
+
region = _notes_region(doc)
|
|
898
|
+
batch_ids = [value for value in (heading_batch_id, role_batch_id) if value is not None]
|
|
899
|
+
if not batch_ids and levels is None and role_overrides is None and region_start_id is None:
|
|
900
|
+
return region, {}
|
|
901
|
+
if any(not isinstance(value, str) or not value for value in batch_ids) or len(set(batch_ids)) > 1:
|
|
902
|
+
raise SyncError("候选批次编号必须是非空文本,且标题与角色批次必须一致")
|
|
903
|
+
if any(value != package["batch_id"] for value in batch_ids):
|
|
904
|
+
raise SyncError("报告或候选标题已变化,请重新扫描;旧批次结果不能应用")
|
|
905
|
+
if region_start_id is not None and role_batch_id is None:
|
|
906
|
+
raise SyncError("应用附注边界必须同时提供角色批次编号")
|
|
907
|
+
if role_overrides is not None and role_batch_id is None:
|
|
908
|
+
raise SyncError("应用疑难角色必须同时提供角色批次编号")
|
|
909
|
+
if levels is not None and heading_batch_id is None:
|
|
910
|
+
raise SyncError("应用候选标题级别必须同时提供标题批次编号")
|
|
911
|
+
|
|
912
|
+
heading_items = {item["id"]: item for item in package["candidates"]}
|
|
913
|
+
role_items = {item["id"]: item for item in package["role_candidates"]}
|
|
914
|
+
boundary_items = {item["id"]: item for item in package["boundary_candidates"]}
|
|
915
|
+
overrides: dict[int, str] = {}
|
|
916
|
+
if levels is not None:
|
|
917
|
+
if not isinstance(levels, dict) or not levels or len(levels) > 300:
|
|
918
|
+
raise SyncError("候选标题级别必须是最多 300 项的非空映射")
|
|
919
|
+
for key, value in levels.items():
|
|
920
|
+
if key not in heading_items:
|
|
921
|
+
raise SyncError("候选标题编号不存在或不属于当前批次,已停止应用")
|
|
922
|
+
if type(value) is not int or not 1 <= value <= 4:
|
|
923
|
+
raise SyncError("候选标题级别必须是 1~4 的整数")
|
|
924
|
+
overrides[heading_items[key]["element_index"]] = f"heading_{value}"
|
|
925
|
+
if role_overrides is not None:
|
|
926
|
+
if not isinstance(role_overrides, dict) or not role_overrides or len(role_overrides) > 300:
|
|
927
|
+
raise SyncError("疑难角色必须是最多 300 项的非空映射")
|
|
928
|
+
for key, value in role_overrides.items():
|
|
929
|
+
if key not in role_items:
|
|
930
|
+
raise SyncError("疑难角色编号不存在或不属于当前批次,已停止应用")
|
|
931
|
+
if value not in role_items[key]["options"]:
|
|
932
|
+
raise SyncError("疑难角色只能选择候选提供的正文或表格标题")
|
|
933
|
+
element_index = role_items[key]["element_index"]
|
|
934
|
+
if element_index in overrides and overrides[element_index] != value:
|
|
935
|
+
raise SyncError("同一候选不能同时确认为不同角色")
|
|
936
|
+
overrides[element_index] = value
|
|
937
|
+
if region_start_id is not None:
|
|
938
|
+
if not isinstance(region_start_id, str) or region_start_id not in boundary_items:
|
|
939
|
+
raise SyncError("附注边界编号不存在或不属于当前批次,已停止应用")
|
|
940
|
+
region = (boundary_items[region_start_id]["element_index"], len(doc.element.body))
|
|
941
|
+
return region, overrides
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
def _mode(values, *, ignore_none: bool = False):
|
|
945
|
+
usable = [value for value in values if not ignore_none or value is not None]
|
|
946
|
+
if not usable:
|
|
947
|
+
return None
|
|
948
|
+
return Counter(usable).most_common(1)[0][0]
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
def _default_formats() -> dict[str, ParagraphFormat]:
|
|
952
|
+
body = ParagraphFormat("Times New Roman", "宋体", 10.5, None, "left", 20.0, "exact", 0.0, 0.0, 21.0, 0.0)
|
|
953
|
+
return {
|
|
954
|
+
"cover_title": ParagraphFormat("Times New Roman", "宋体", 26.0, True, "center", 47.0, "atLeast", 0.0, 0.0, 0.0, 0.0),
|
|
955
|
+
"cover_info": ParagraphFormat("Times New Roman", "宋体", 14.0, None, "center", 30.0, "atLeast", 0.0, 0.0, 0.0, 0.0),
|
|
956
|
+
"toc_title": ParagraphFormat("Times New Roman", "宋体", 18.0, True, "center", 24.0, "exact", 0.0, 0.0, 0.0, 0.0),
|
|
957
|
+
"toc_entry": ParagraphFormat("Times New Roman", "宋体", 12.0, False, "left", 40.0, "atLeast", 0.0, 0.0, 0.0, 26.25),
|
|
958
|
+
"heading_1": ParagraphFormat("Times New Roman", "宋体", 12.0, True, "left", 20.0, "exact", 12.0, 0.0, 24.1, 0.0),
|
|
959
|
+
"heading_2": ParagraphFormat("Times New Roman", "宋体", 10.5, True, "left", 20.0, "exact", 6.0, 0.0, 21.1, 0.0),
|
|
960
|
+
"heading_3": ParagraphFormat("Times New Roman", "宋体", 10.5, False, "left", 18.0, "exact", 6.0, 0.0, 21.1, 0.0),
|
|
961
|
+
"heading_4": ParagraphFormat("Times New Roman", "宋体", 10.5, False, "left", 18.0, "exact", 6.0, 0.0, 31.5, 0.0),
|
|
962
|
+
"statement": ParagraphFormat("Times New Roman", "宋体", 10.5, False, "left", 18.0, "exact", 6.0, 0.0, 31.5, 0.0),
|
|
963
|
+
"table_title": ParagraphFormat("Times New Roman", "宋体", 9.0, True, "center", 18.0, "exact", 6.0, 0.0, 0.0, 0.0),
|
|
964
|
+
"table_continuation": ParagraphFormat("Times New Roman", "宋体", 10.5, False, "right", 1.0, "auto", 0.0, 0.0, 0.0, 0.0),
|
|
965
|
+
"body": body,
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def _merge_format(default: ParagraphFormat, samples: list[ParagraphFormat]) -> ParagraphFormat:
|
|
970
|
+
if not samples:
|
|
971
|
+
return default
|
|
972
|
+
bold_values = [item.bold for item in samples]
|
|
973
|
+
bold = _mode(bold_values)
|
|
974
|
+
if bold is None and default.bold is not None:
|
|
975
|
+
bold = default.bold
|
|
976
|
+
return ParagraphFormat(
|
|
977
|
+
ascii_font=_mode([item.ascii_font for item in samples], ignore_none=True) or default.ascii_font,
|
|
978
|
+
east_asia_font=_mode([item.east_asia_font for item in samples], ignore_none=True) or default.east_asia_font,
|
|
979
|
+
size=_mode([item.size for item in samples], ignore_none=True) or default.size,
|
|
980
|
+
bold=bold,
|
|
981
|
+
align=_mode([item.align for item in samples], ignore_none=True) or default.align,
|
|
982
|
+
line_value=_mode([item.line_value for item in samples], ignore_none=True) or default.line_value,
|
|
983
|
+
line_rule=_mode([item.line_rule for item in samples if item.line_value is not None], ignore_none=True) or default.line_rule,
|
|
984
|
+
before=_mode([item.before for item in samples]) if any(item.before is not None for item in samples) else default.before,
|
|
985
|
+
after=_mode([item.after for item in samples]) if any(item.after is not None for item in samples) else default.after,
|
|
986
|
+
first_line=_mode([item.first_line for item in samples], ignore_none=True) or default.first_line,
|
|
987
|
+
left=_mode([item.left for item in samples], ignore_none=True) or default.left,
|
|
988
|
+
)
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def _table_run_formats(doc, tables: list[Table] | None = None) -> tuple[Counter, Counter]:
|
|
992
|
+
fonts = Counter()
|
|
993
|
+
sizes = Counter()
|
|
994
|
+
for table in doc.tables if tables is None else tables:
|
|
995
|
+
for row in table.rows:
|
|
996
|
+
for cell in row.cells:
|
|
997
|
+
for paragraph in cell.paragraphs:
|
|
998
|
+
run = next((item for item in paragraph.runs if item.text.strip()), None)
|
|
999
|
+
if run is None:
|
|
1000
|
+
continue
|
|
1001
|
+
fmt = _effective_paragraph_format(paragraph)
|
|
1002
|
+
if fmt.ascii_font:
|
|
1003
|
+
fonts[fmt.ascii_font] += len(run.text)
|
|
1004
|
+
if fmt.east_asia_font:
|
|
1005
|
+
fonts[fmt.east_asia_font] += len(run.text)
|
|
1006
|
+
if fmt.size is not None:
|
|
1007
|
+
sizes[fmt.size] += len(run.text)
|
|
1008
|
+
return fonts, sizes
|
|
1009
|
+
|
|
1010
|
+
|
|
1011
|
+
def _table_border_containers(table: Table) -> list:
|
|
1012
|
+
containers = [table._tbl.tblPr]
|
|
1013
|
+
style = table.style or table.part.styles.default(WD_STYLE_TYPE.TABLE)
|
|
1014
|
+
seen = set()
|
|
1015
|
+
while style is not None and style.style_id not in seen:
|
|
1016
|
+
seen.add(style.style_id)
|
|
1017
|
+
tbl_pr = style.element.find(qn("w:tblPr"))
|
|
1018
|
+
if tbl_pr is not None:
|
|
1019
|
+
containers.append(tbl_pr)
|
|
1020
|
+
style = style.base_style
|
|
1021
|
+
return containers
|
|
1022
|
+
|
|
1023
|
+
|
|
1024
|
+
def _read_border(element) -> BorderFormat | None:
|
|
1025
|
+
if element is None:
|
|
1026
|
+
return None
|
|
1027
|
+
val = element.get(qn("w:val")) or "single"
|
|
1028
|
+
if val not in BORDER_VALUES:
|
|
1029
|
+
return None
|
|
1030
|
+
size = _number(element, "sz", 8.0)
|
|
1031
|
+
if val in ("nil", "none"):
|
|
1032
|
+
size = 0.0
|
|
1033
|
+
elif size is None:
|
|
1034
|
+
size = 0.5
|
|
1035
|
+
color = element.get(qn("w:color"))
|
|
1036
|
+
if color is not None and color.lower() != "auto" and not re.fullmatch(r"[0-9a-fA-F]{6}", color):
|
|
1037
|
+
color = None
|
|
1038
|
+
return BorderFormat(val, size, color)
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
def _extract_table_borders(table: Table) -> dict[str, BorderFormat | None]:
|
|
1042
|
+
containers = _table_border_containers(table)
|
|
1043
|
+
result = {}
|
|
1044
|
+
for edge in BORDER_EDGES:
|
|
1045
|
+
result[edge] = None
|
|
1046
|
+
for container in containers:
|
|
1047
|
+
borders = container.find(qn("w:tblBorders"))
|
|
1048
|
+
border = borders.find(qn(f"w:{edge}")) if borders is not None else None
|
|
1049
|
+
value = _read_border(border)
|
|
1050
|
+
if value is not None:
|
|
1051
|
+
result[edge] = value
|
|
1052
|
+
break
|
|
1053
|
+
return result
|
|
1054
|
+
|
|
1055
|
+
|
|
1056
|
+
def _build_table_borders(doc, tables: list[Table] | None = None) -> dict[str, BorderFormat]:
|
|
1057
|
+
samples: dict[str, list[BorderFormat]] = {edge: [] for edge in BORDER_EDGES}
|
|
1058
|
+
for table in doc.tables if tables is None else tables:
|
|
1059
|
+
for edge, value in _extract_table_borders(table).items():
|
|
1060
|
+
if value is not None:
|
|
1061
|
+
samples[edge].append(value)
|
|
1062
|
+
return {edge: _mode(samples[edge]) or BorderFormat() for edge in BORDER_EDGES}
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
def build_profile(template: str | Path, source: str | Path | None = None) -> FormatProfile:
|
|
1066
|
+
path = resolve_docx(str(template))
|
|
1067
|
+
doc = _open_document(path)
|
|
1068
|
+
source_is_notes = source is not None and _notes_region(_open_document(resolve_docx(str(source)))) is not None
|
|
1069
|
+
region = _notes_region(doc)
|
|
1070
|
+
if source_is_notes and region is None:
|
|
1071
|
+
raise SyncError("样板报告中未找到可识别的财务报表附注区,已停止套用")
|
|
1072
|
+
classified, _ = _classify_paragraphs(doc, region=region if source_is_notes else None)
|
|
1073
|
+
grouped: dict[str, list[ParagraphFormat]] = defaultdict(list)
|
|
1074
|
+
for paragraph, role in classified:
|
|
1075
|
+
grouped[role].append(_effective_paragraph_format(paragraph))
|
|
1076
|
+
formats = _default_formats()
|
|
1077
|
+
for role, samples in grouped.items():
|
|
1078
|
+
formats[role] = _merge_format(formats.get(role, ParagraphFormat()), samples)
|
|
1079
|
+
tables = _region_tables(doc, region) if source_is_notes else None
|
|
1080
|
+
fonts, sizes = _table_run_formats(doc, tables)
|
|
1081
|
+
ascii_fonts = [name for name in fonts if name not in ("宋体", "SimSun", "微软雅黑")]
|
|
1082
|
+
return FormatProfile(
|
|
1083
|
+
paragraphs=formats,
|
|
1084
|
+
table_ascii_font=_mode(ascii_fonts) or "Times New Roman",
|
|
1085
|
+
table_east_asia_font=_mode([name for name in fonts if name in ("宋体", "SimSun")]) or "宋体",
|
|
1086
|
+
table_size=_mode([size for size in sizes if size <= 9.0]) or _mode(list(sizes)) or 9.0,
|
|
1087
|
+
table_borders=_build_table_borders(doc, tables),
|
|
1088
|
+
template=str(path),
|
|
1089
|
+
)
|
|
1090
|
+
|
|
1091
|
+
|
|
1092
|
+
def _suggested_output(source: Path) -> Path:
|
|
1093
|
+
candidate = source.with_name(f"{source.stem}_格式调整{source.suffix}")
|
|
1094
|
+
counter = 2
|
|
1095
|
+
while candidate.exists():
|
|
1096
|
+
candidate = source.with_name(f"{source.stem}_格式调整_{counter}{source.suffix}")
|
|
1097
|
+
counter += 1
|
|
1098
|
+
return candidate
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def _format_summary(fmt: ParagraphFormat) -> str:
|
|
1102
|
+
font = " / ".join(dict.fromkeys(item for item in (fmt.ascii_font, fmt.east_asia_font) if item))
|
|
1103
|
+
parts = [font or "继承字体"]
|
|
1104
|
+
if fmt.size is not None:
|
|
1105
|
+
parts.append(f"{fmt.size:g}磅")
|
|
1106
|
+
if fmt.bold is not None:
|
|
1107
|
+
parts.append("加粗" if fmt.bold else "不加粗")
|
|
1108
|
+
parts.append(ALIGN_LABELS.get(fmt.align, fmt.align or "默认对齐"))
|
|
1109
|
+
if fmt.line_value is not None:
|
|
1110
|
+
if fmt.line_rule == "auto":
|
|
1111
|
+
parts.append(f"{fmt.line_value:g}倍行距")
|
|
1112
|
+
else:
|
|
1113
|
+
rule = "固定行距" if fmt.line_rule == "exact" else "最小行距"
|
|
1114
|
+
parts.append(f"{rule}{fmt.line_value:g}磅")
|
|
1115
|
+
if fmt.first_line:
|
|
1116
|
+
parts.append(f"首行缩进{fmt.first_line:g}磅")
|
|
1117
|
+
if fmt.left:
|
|
1118
|
+
parts.append(f"左缩进{fmt.left:g}磅")
|
|
1119
|
+
return ";".join(parts)
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
def _table_border_summary(profile: FormatProfile) -> str:
|
|
1123
|
+
if profile.table_borders is None:
|
|
1124
|
+
return "旧方案未保存框线数据,保持原样"
|
|
1125
|
+
groups: dict[BorderFormat, list[str]] = defaultdict(list)
|
|
1126
|
+
for edge in BORDER_EDGES:
|
|
1127
|
+
groups[profile.table_borders[edge]].append(BORDER_EDGE_LABELS[edge])
|
|
1128
|
+
parts = []
|
|
1129
|
+
for fmt, labels in groups.items():
|
|
1130
|
+
if fmt.val in ("nil", "none"):
|
|
1131
|
+
parts.append(f"{'、'.join(labels)}无框线")
|
|
1132
|
+
else:
|
|
1133
|
+
value = f"{'、'.join(labels)}:{BORDER_STYLE_LABELS[fmt.val]} {fmt.size:g}磅"
|
|
1134
|
+
if fmt.color:
|
|
1135
|
+
value += f" #{fmt.color}"
|
|
1136
|
+
parts.append(value)
|
|
1137
|
+
return ";".join(parts)
|
|
1138
|
+
|
|
1139
|
+
|
|
1140
|
+
def _apply_table_borders(table: Table, profile: FormatProfile) -> bool:
|
|
1141
|
+
if profile.table_borders is None:
|
|
1142
|
+
return False
|
|
1143
|
+
tbl_pr = table._tbl.tblPr
|
|
1144
|
+
previous = tbl_pr.find(qn("w:tblBorders"))
|
|
1145
|
+
if previous is not None:
|
|
1146
|
+
tbl_pr.remove(previous)
|
|
1147
|
+
borders = OxmlElement("w:tblBorders")
|
|
1148
|
+
for edge in BORDER_EDGES:
|
|
1149
|
+
fmt = profile.table_borders[edge]
|
|
1150
|
+
element = OxmlElement(f"w:{edge}")
|
|
1151
|
+
element.set(qn("w:val"), fmt.val)
|
|
1152
|
+
element.set(qn("w:space"), "0")
|
|
1153
|
+
if fmt.val not in ("nil", "none"):
|
|
1154
|
+
if fmt.size > 0:
|
|
1155
|
+
element.set(qn("w:sz"), str(round(fmt.size * 8)))
|
|
1156
|
+
if fmt.color:
|
|
1157
|
+
element.set(qn("w:color"), fmt.color)
|
|
1158
|
+
borders.append(element)
|
|
1159
|
+
successors = {
|
|
1160
|
+
qn("w:shd"), qn("w:tblLayout"), qn("w:tblCellMar"), qn("w:tblLook"),
|
|
1161
|
+
qn("w:tblCaption"), qn("w:tblDescription"), qn("w:tblPrChange"),
|
|
1162
|
+
}
|
|
1163
|
+
for child in tbl_pr:
|
|
1164
|
+
if child.tag in successors:
|
|
1165
|
+
child.addprevious(borders)
|
|
1166
|
+
break
|
|
1167
|
+
else:
|
|
1168
|
+
tbl_pr.append(borders)
|
|
1169
|
+
for cell in table._tbl.xpath(".//w:tc"):
|
|
1170
|
+
tc_pr = cell.find(qn("w:tcPr"))
|
|
1171
|
+
cell_borders = tc_pr.find(qn("w:tcBorders")) if tc_pr is not None else None
|
|
1172
|
+
if cell_borders is not None:
|
|
1173
|
+
tc_pr.remove(cell_borders)
|
|
1174
|
+
return True
|
|
1175
|
+
|
|
1176
|
+
|
|
1177
|
+
def _table_row_roles(table: Table) -> list[str]:
|
|
1178
|
+
roles = []
|
|
1179
|
+
header_seen = False
|
|
1180
|
+
for row in table.rows:
|
|
1181
|
+
first_text = next((cell.text.strip() for cell in row.cells if cell.text.strip()), "")
|
|
1182
|
+
if first_text.startswith(("合计", "小计", "总计")):
|
|
1183
|
+
roles.append("table_total")
|
|
1184
|
+
elif not header_seen and any(cell.text.strip() for cell in row.cells):
|
|
1185
|
+
roles.append("table_header")
|
|
1186
|
+
header_seen = True
|
|
1187
|
+
else:
|
|
1188
|
+
roles.append("table_data")
|
|
1189
|
+
return roles
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
def _paragraph_runs(paragraph: Paragraph) -> list[Run]:
|
|
1193
|
+
return [Run(element, paragraph) for element in paragraph._p.xpath(".//w:r") if element.xpath(".//w:t")]
|
|
1194
|
+
|
|
1195
|
+
|
|
1196
|
+
def _set_run_font(run: Run, fmt: ParagraphFormat, *, size: float | None = None, bold: bool | None = None) -> None:
|
|
1197
|
+
if fmt.ascii_font:
|
|
1198
|
+
run.font.name = fmt.ascii_font
|
|
1199
|
+
rpr = run._r.get_or_add_rPr()
|
|
1200
|
+
rfonts = rpr.find(qn("w:rFonts"))
|
|
1201
|
+
if rfonts is None:
|
|
1202
|
+
rfonts = OxmlElement("w:rFonts")
|
|
1203
|
+
rpr.insert(0, rfonts)
|
|
1204
|
+
rfonts.set(qn("w:ascii"), fmt.ascii_font)
|
|
1205
|
+
rfonts.set(qn("w:hAnsi"), fmt.ascii_font)
|
|
1206
|
+
if fmt.east_asia_font:
|
|
1207
|
+
rfonts.set(qn("w:eastAsia"), fmt.east_asia_font)
|
|
1208
|
+
rfonts.set(qn("w:cs"), fmt.ascii_font)
|
|
1209
|
+
target_size = fmt.size if size is None else size
|
|
1210
|
+
if target_size is not None:
|
|
1211
|
+
run.font.size = Pt(target_size)
|
|
1212
|
+
target_bold = fmt.bold if bold is None else bold
|
|
1213
|
+
if target_bold is not None:
|
|
1214
|
+
run.font.bold = target_bold
|
|
1215
|
+
|
|
1216
|
+
|
|
1217
|
+
def _clean_paragraph_format(paragraph: Paragraph) -> None:
|
|
1218
|
+
ppr = paragraph._p.get_or_add_pPr()
|
|
1219
|
+
spacing = ppr.find(qn("w:spacing"))
|
|
1220
|
+
if spacing is not None:
|
|
1221
|
+
for name in ("before", "after", "line", "lineRule", "beforeLines", "afterLines", "beforeAutospacing", "afterAutospacing"):
|
|
1222
|
+
spacing.attrib.pop(qn(f"w:{name}"), None)
|
|
1223
|
+
if not spacing.attrib:
|
|
1224
|
+
ppr.remove(spacing)
|
|
1225
|
+
indent = ppr.find(qn("w:ind"))
|
|
1226
|
+
if indent is not None:
|
|
1227
|
+
for name in ("left", "leftChars", "firstLine", "firstLineChars", "hanging", "hangingChars"):
|
|
1228
|
+
indent.attrib.pop(qn(f"w:{name}"), None)
|
|
1229
|
+
if not indent.attrib:
|
|
1230
|
+
ppr.remove(indent)
|
|
1231
|
+
alignment = ppr.find(qn("w:jc"))
|
|
1232
|
+
if alignment is not None:
|
|
1233
|
+
ppr.remove(alignment)
|
|
1234
|
+
containers = [run._r.rPr for run in _paragraph_runs(paragraph)]
|
|
1235
|
+
mark_rpr = ppr.find(qn("w:rPr"))
|
|
1236
|
+
if mark_rpr is not None:
|
|
1237
|
+
containers.append(mark_rpr)
|
|
1238
|
+
for rpr in containers:
|
|
1239
|
+
if rpr is None:
|
|
1240
|
+
continue
|
|
1241
|
+
for name in ("rFonts", "sz", "szCs", "b", "bCs"):
|
|
1242
|
+
for element in rpr.findall(qn(f"w:{name}")):
|
|
1243
|
+
rpr.remove(element)
|
|
1244
|
+
if not len(rpr):
|
|
1245
|
+
rpr.getparent().remove(rpr)
|
|
1246
|
+
|
|
1247
|
+
|
|
1248
|
+
def _apply_paragraph_format(paragraph: Paragraph, fmt: ParagraphFormat) -> None:
|
|
1249
|
+
_clean_paragraph_format(paragraph)
|
|
1250
|
+
for run in _paragraph_runs(paragraph):
|
|
1251
|
+
_set_run_font(run, fmt)
|
|
1252
|
+
pf = paragraph.paragraph_format
|
|
1253
|
+
if fmt.align in ALIGN_VALUES:
|
|
1254
|
+
pf.alignment = ALIGN_VALUES[fmt.align]
|
|
1255
|
+
if fmt.line_value is not None:
|
|
1256
|
+
pf.line_spacing = fmt.line_value if fmt.line_rule == "auto" else Pt(fmt.line_value)
|
|
1257
|
+
if fmt.before is not None:
|
|
1258
|
+
pf.space_before = Pt(fmt.before)
|
|
1259
|
+
if fmt.after is not None:
|
|
1260
|
+
pf.space_after = Pt(fmt.after)
|
|
1261
|
+
if fmt.first_line is not None:
|
|
1262
|
+
pf.first_line_indent = Pt(fmt.first_line)
|
|
1263
|
+
if fmt.left is not None:
|
|
1264
|
+
pf.left_indent = Pt(fmt.left)
|
|
1265
|
+
|
|
1266
|
+
|
|
1267
|
+
def _looks_numeric(text: str) -> bool:
|
|
1268
|
+
value = text.strip().replace(",", "").replace(",", "")
|
|
1269
|
+
if value in ("", "-", "—", "–", "(", ")", "()"):
|
|
1270
|
+
return False
|
|
1271
|
+
return bool(re.fullmatch(r"[¥¥$]?-?\d[\d,]*(?:\.\d+)?%?\)?", value))
|
|
1272
|
+
|
|
1273
|
+
|
|
1274
|
+
def _apply_table_format(table: Table, profile: FormatProfile, scope: dict[str, bool]) -> tuple[int, Counter]:
|
|
1275
|
+
apply_text = scope["table_text"]
|
|
1276
|
+
apply_emphasis = scope["table_emphasis"]
|
|
1277
|
+
if not apply_text and not apply_emphasis:
|
|
1278
|
+
return 0, Counter()
|
|
1279
|
+
base = ParagraphFormat(profile.table_ascii_font, profile.table_east_asia_font, profile.table_size, None)
|
|
1280
|
+
formatted = 0
|
|
1281
|
+
roles = _table_row_roles(table)
|
|
1282
|
+
for row_index, row in enumerate(table.rows):
|
|
1283
|
+
role = roles[row_index]
|
|
1284
|
+
for cell in row.cells:
|
|
1285
|
+
for paragraph in cell.paragraphs:
|
|
1286
|
+
if not paragraph.text.strip():
|
|
1287
|
+
continue
|
|
1288
|
+
if apply_emphasis:
|
|
1289
|
+
align = "center" if role == "table_header" else ("right" if _looks_numeric(paragraph.text) else "left")
|
|
1290
|
+
paragraph.alignment = ALIGN_VALUES[align]
|
|
1291
|
+
for run in _paragraph_runs(paragraph):
|
|
1292
|
+
if not apply_text:
|
|
1293
|
+
if role in ("table_header", "table_total"):
|
|
1294
|
+
run.font.bold = True
|
|
1295
|
+
continue
|
|
1296
|
+
current_size = _effective_run_size(paragraph, run)
|
|
1297
|
+
size = min(current_size, profile.table_size) if current_size is not None else profile.table_size
|
|
1298
|
+
bold = True if apply_emphasis and role in ("table_header", "table_total") else None
|
|
1299
|
+
_set_run_font(run, base, size=size, bold=bold)
|
|
1300
|
+
formatted += 1
|
|
1301
|
+
return formatted, Counter(roles)
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
def _apply_profile(
|
|
1305
|
+
doc,
|
|
1306
|
+
profile: FormatProfile,
|
|
1307
|
+
scope: dict[str, bool],
|
|
1308
|
+
paragraph_overrides: dict[int, str] | None = None,
|
|
1309
|
+
region: tuple[int, int] | None = None,
|
|
1310
|
+
) -> dict[str, int]:
|
|
1311
|
+
counts: Counter[str] = Counter()
|
|
1312
|
+
selected_roles = _selected_paragraph_roles(scope)
|
|
1313
|
+
classified, meta = _classify_paragraphs(doc, paragraph_overrides, region=region)
|
|
1314
|
+
skipped_paragraphs = 0
|
|
1315
|
+
protected_paragraphs = 0
|
|
1316
|
+
for paragraph, role in classified:
|
|
1317
|
+
if (_outline_level(paragraph) or 0) > 4:
|
|
1318
|
+
protected_paragraphs += 1
|
|
1319
|
+
continue
|
|
1320
|
+
if role not in selected_roles:
|
|
1321
|
+
skipped_paragraphs += 1
|
|
1322
|
+
continue
|
|
1323
|
+
fmt = profile.paragraphs.get(role) or profile.paragraphs["body"]
|
|
1324
|
+
_apply_paragraph_format(paragraph, fmt)
|
|
1325
|
+
counts[role] += 1
|
|
1326
|
+
table_paragraphs = 0
|
|
1327
|
+
skipped_tables = 0
|
|
1328
|
+
table_enabled = scope["table_text"] or scope["table_emphasis"] or scope["table_borders"]
|
|
1329
|
+
for table in _region_tables(doc, region):
|
|
1330
|
+
if not table_enabled:
|
|
1331
|
+
skipped_tables += 1
|
|
1332
|
+
continue
|
|
1333
|
+
formatted, roles = _apply_table_format(table, profile, scope)
|
|
1334
|
+
table_paragraphs += formatted
|
|
1335
|
+
counts.update(roles)
|
|
1336
|
+
if scope["table_borders"] and _apply_table_borders(table, profile):
|
|
1337
|
+
counts["table_borders"] += 1
|
|
1338
|
+
counts["table_paragraphs"] = table_paragraphs
|
|
1339
|
+
counts["ambiguous"] = meta["ambiguous"]
|
|
1340
|
+
counts["empty"] = meta["empty"]
|
|
1341
|
+
counts["protected_paragraphs"] = protected_paragraphs
|
|
1342
|
+
counts["skipped_paragraphs"] = skipped_paragraphs
|
|
1343
|
+
counts["skipped_tables"] = skipped_tables
|
|
1344
|
+
return dict(counts)
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
def _document_snapshot(doc) -> dict:
|
|
1348
|
+
body = doc.element.body
|
|
1349
|
+
section_values = []
|
|
1350
|
+
for section in doc.sections:
|
|
1351
|
+
section_values.append((
|
|
1352
|
+
section.page_width, section.page_height, section.left_margin, section.right_margin,
|
|
1353
|
+
section.top_margin, section.bottom_margin, section.orientation,
|
|
1354
|
+
))
|
|
1355
|
+
merges = []
|
|
1356
|
+
for table in body.xpath(".//w:tbl"):
|
|
1357
|
+
for cell in table.xpath(".//w:tc"):
|
|
1358
|
+
tcpr = cell.find(qn("w:tcPr"))
|
|
1359
|
+
grid = tcpr.find(qn("w:gridSpan")) if tcpr is not None else None
|
|
1360
|
+
vertical = tcpr.find(qn("w:vMerge")) if tcpr is not None else None
|
|
1361
|
+
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))
|
|
1362
|
+
links = sorted(rel.target_ref for rel in doc.part.rels.values() if rel.is_external)
|
|
1363
|
+
return {
|
|
1364
|
+
"text": tuple(body.xpath(".//w:t/text()")),
|
|
1365
|
+
"bookmarks": tuple(body.xpath(".//w:bookmarkStart/@w:name")),
|
|
1366
|
+
"numbering": tuple(element.xml for element in body.xpath(".//w:numPr")),
|
|
1367
|
+
"outlines": tuple(element.xml for element in body.xpath(".//w:outlineLvl")),
|
|
1368
|
+
"fields": tuple(body.xpath(".//w:instrText/text()")) + tuple(body.xpath(".//w:fldSimple/@w:instr")),
|
|
1369
|
+
"tables": len(doc.tables),
|
|
1370
|
+
"table_shapes": tuple(
|
|
1371
|
+
(len(table.rows), tuple(len(row.cells) for row in table.rows), table._tbl.tblGrid.xml)
|
|
1372
|
+
for table in doc.tables
|
|
1373
|
+
),
|
|
1374
|
+
"merges": tuple(merges),
|
|
1375
|
+
"sections": tuple(section_values),
|
|
1376
|
+
"links": tuple(links),
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
|
|
1380
|
+
def _binary_parts(path: Path) -> dict[str, str]:
|
|
1381
|
+
prefixes = ("word/media/", "word/embeddings/", "word/fonts/")
|
|
1382
|
+
result = {}
|
|
1383
|
+
with zipfile.ZipFile(path) as archive:
|
|
1384
|
+
for name in archive.namelist():
|
|
1385
|
+
if name.startswith(prefixes) or name == "word/vbaProject.bin":
|
|
1386
|
+
result[name] = hashlib.sha256(archive.read(name)).hexdigest()
|
|
1387
|
+
return result
|
|
1388
|
+
|
|
1389
|
+
|
|
1390
|
+
def _validate_output(source: Path, output: Path, before: dict) -> None:
|
|
1391
|
+
check = _open_document(output)
|
|
1392
|
+
after = _document_snapshot(check)
|
|
1393
|
+
for key in before:
|
|
1394
|
+
if before[key] != after[key]:
|
|
1395
|
+
raise SyncError(f"格式副本校验失败:{key} 与原文不一致,已删除未通过的副本")
|
|
1396
|
+
if _binary_parts(source) != _binary_parts(output):
|
|
1397
|
+
raise SyncError("格式副本校验失败:图片、嵌入对象或 VBA 部分与原文不一致,已删除未通过的副本")
|
|
1398
|
+
|
|
1399
|
+
|
|
1400
|
+
def _format_source(source: Path, template: str | Path | None, profile_name: str | None) -> tuple[FormatProfile, str, bool]:
|
|
1401
|
+
if profile_name is not None:
|
|
1402
|
+
if template is not None:
|
|
1403
|
+
raise SyncError("样板报告与已存格式方案只能二选一")
|
|
1404
|
+
name = profile_name.strip()
|
|
1405
|
+
return load_format_profile(name), f"已存方案:{name}", False
|
|
1406
|
+
if template is None:
|
|
1407
|
+
return build_profile(source), str(source), True
|
|
1408
|
+
path = resolve_docx(str(template))
|
|
1409
|
+
return build_profile(path, source), str(path), False
|
|
1410
|
+
|
|
1411
|
+
|
|
1412
|
+
def _scan_opened_report(
|
|
1413
|
+
source: Path,
|
|
1414
|
+
template_label: str,
|
|
1415
|
+
profile: FormatProfile,
|
|
1416
|
+
target,
|
|
1417
|
+
self_sample: bool = False,
|
|
1418
|
+
scope: dict | None = None,
|
|
1419
|
+
paragraph_overrides: dict[int, str] | None = None,
|
|
1420
|
+
region: tuple[int, int] | None = None,
|
|
1421
|
+
) -> dict:
|
|
1422
|
+
scope = _validated_scope(scope)
|
|
1423
|
+
selected_roles = _selected_paragraph_roles(scope)
|
|
1424
|
+
classified, meta = _classify_paragraphs(target, paragraph_overrides, region=region)
|
|
1425
|
+
counts = Counter(role for _, role in classified)
|
|
1426
|
+
protected_roles = Counter(role for paragraph, role in classified if (_outline_level(paragraph) or 0) > 4)
|
|
1427
|
+
protected = sum(protected_roles.values())
|
|
1428
|
+
selected_paragraphs = sum(counts[role] - protected_roles[role] for role in selected_roles)
|
|
1429
|
+
roles = []
|
|
1430
|
+
for role in ROLE_LABELS:
|
|
1431
|
+
if role in ("table_header", "table_total", "table_data"):
|
|
1432
|
+
continue
|
|
1433
|
+
if counts[role]:
|
|
1434
|
+
roles.append({
|
|
1435
|
+
"role": role,
|
|
1436
|
+
"label": ROLE_LABELS[role],
|
|
1437
|
+
"paragraphs": counts[role],
|
|
1438
|
+
"selected_paragraphs": counts[role] - protected_roles[role] if role in selected_roles else 0,
|
|
1439
|
+
"selected": role in selected_roles and counts[role] > protected_roles[role],
|
|
1440
|
+
"format": _format_summary(profile.paragraphs[role]),
|
|
1441
|
+
})
|
|
1442
|
+
table_enabled = scope["table_text"] or scope["table_emphasis"] or scope["table_borders"]
|
|
1443
|
+
tables = _region_tables(target, region)
|
|
1444
|
+
table_rows = sum(len(table.rows) for table in tables) if table_enabled else 0
|
|
1445
|
+
warnings = []
|
|
1446
|
+
if meta["ambiguous"]:
|
|
1447
|
+
warnings.append(f"有 {meta['ambiguous']} 个大纲级别异常的段落保持原样,不会强行套用格式。")
|
|
1448
|
+
if source.suffix.lower() == ".docm":
|
|
1449
|
+
warnings.append("将校验 Word 宏(VBA)是否完整保留。")
|
|
1450
|
+
if self_sample:
|
|
1451
|
+
warnings.append("未指定样板,已按原文件自身格式提取。")
|
|
1452
|
+
return {
|
|
1453
|
+
"source": str(source),
|
|
1454
|
+
"template": template_label,
|
|
1455
|
+
"suggested_output": str(_suggested_output(source)),
|
|
1456
|
+
"scope": dict(scope),
|
|
1457
|
+
"totals": {
|
|
1458
|
+
"paragraphs": len(classified),
|
|
1459
|
+
"tables": len(tables) if table_enabled else 0,
|
|
1460
|
+
"table_rows": table_rows,
|
|
1461
|
+
"empty_paragraphs": meta["empty"],
|
|
1462
|
+
"ambiguous_paragraphs": meta["ambiguous"],
|
|
1463
|
+
"selected_paragraphs": selected_paragraphs,
|
|
1464
|
+
"protected_paragraphs": protected,
|
|
1465
|
+
"skipped_paragraphs": len(classified) - selected_paragraphs - protected,
|
|
1466
|
+
"skipped_tables": 0 if table_enabled else len(tables),
|
|
1467
|
+
},
|
|
1468
|
+
"roles": roles,
|
|
1469
|
+
"table_format": _format_summary(ParagraphFormat(profile.table_ascii_font, profile.table_east_asia_font, profile.table_size, None)),
|
|
1470
|
+
"table_border_format": _table_border_summary(profile),
|
|
1471
|
+
"small_table_policy": "不大于样板表格字号的字号保留;较大字号统一为样板字号。",
|
|
1472
|
+
"warnings": warnings,
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
|
|
1476
|
+
def scan_report_format(
|
|
1477
|
+
docx: str | Path,
|
|
1478
|
+
template: str | Path | None = None,
|
|
1479
|
+
*,
|
|
1480
|
+
profile_name: str | None = None,
|
|
1481
|
+
scope: dict | None = None,
|
|
1482
|
+
heading_batch_id: str | None = None,
|
|
1483
|
+
heading_levels: dict | None = None,
|
|
1484
|
+
role_batch_id: str | None = None,
|
|
1485
|
+
role_overrides: dict | None = None,
|
|
1486
|
+
region_start_id: str | None = None,
|
|
1487
|
+
) -> dict:
|
|
1488
|
+
scope = _validated_scope(scope)
|
|
1489
|
+
source = resolve_docx(str(docx))
|
|
1490
|
+
profile, template_label, self_sample = _format_source(source, template, profile_name)
|
|
1491
|
+
target = _open_document(source)
|
|
1492
|
+
fingerprint = hashlib.sha256(source.read_bytes()).hexdigest() if any(
|
|
1493
|
+
value is not None
|
|
1494
|
+
for value in (heading_batch_id, heading_levels, role_batch_id, role_overrides, region_start_id)
|
|
1495
|
+
) else ""
|
|
1496
|
+
region, paragraph_overrides = _validated_format_overrides(
|
|
1497
|
+
target, fingerprint, heading_batch_id, heading_levels,
|
|
1498
|
+
role_batch_id, role_overrides, region_start_id,
|
|
1499
|
+
)
|
|
1500
|
+
if any(role.startswith("heading_") for role in paragraph_overrides.values()) and not scope["headings"]:
|
|
1501
|
+
raise SyncError("应用候选标题级别时必须勾选“一至四级标题”")
|
|
1502
|
+
if any(role in ("table_title", "table_continuation") for role in paragraph_overrides.values()) and not scope["statement"]:
|
|
1503
|
+
raise SyncError("应用表格标题角色时必须勾选“报表名称、日期与表格标题”")
|
|
1504
|
+
return _scan_opened_report(
|
|
1505
|
+
source, template_label, profile, target, self_sample, scope,
|
|
1506
|
+
paragraph_overrides, region,
|
|
1507
|
+
)
|
|
1508
|
+
|
|
1509
|
+
|
|
1510
|
+
def run_report_format(
|
|
1511
|
+
docx: str | Path,
|
|
1512
|
+
template: str | Path | None = None,
|
|
1513
|
+
*,
|
|
1514
|
+
output: str | Path | None = None,
|
|
1515
|
+
dry_run: bool = False,
|
|
1516
|
+
profile_name: str | None = None,
|
|
1517
|
+
scope: dict | None = None,
|
|
1518
|
+
heading_batch_id: str | None = None,
|
|
1519
|
+
heading_levels: dict | None = None,
|
|
1520
|
+
role_batch_id: str | None = None,
|
|
1521
|
+
role_overrides: dict | None = None,
|
|
1522
|
+
region_start_id: str | None = None,
|
|
1523
|
+
) -> dict:
|
|
1524
|
+
scope = _validated_scope(scope)
|
|
1525
|
+
source = resolve_docx(str(docx))
|
|
1526
|
+
output_path = _suggested_output(source) if output is None else Path(output).expanduser().resolve()
|
|
1527
|
+
if output_path.suffix.lower() != source.suffix.lower():
|
|
1528
|
+
raise SyncError("格式副本必须与原报告使用同一种文件类型(.docx 或 .docm)")
|
|
1529
|
+
if output_path == source:
|
|
1530
|
+
raise SyncError("为保护原报告,格式调整只生成新副本;请选择其他输出路径")
|
|
1531
|
+
if not output_path.parent.is_dir():
|
|
1532
|
+
raise SyncError(f"输出目录不存在:{output_path.parent}")
|
|
1533
|
+
if output_path.exists():
|
|
1534
|
+
raise SyncError(f"输出文件已存在,未覆盖:{output_path}")
|
|
1535
|
+
profile, template_label, self_sample = _format_source(source, template, profile_name)
|
|
1536
|
+
target = _open_document(source)
|
|
1537
|
+
fingerprint = hashlib.sha256(source.read_bytes()).hexdigest() if any(
|
|
1538
|
+
value is not None
|
|
1539
|
+
for value in (heading_batch_id, heading_levels, role_batch_id, role_overrides, region_start_id)
|
|
1540
|
+
) else ""
|
|
1541
|
+
region, paragraph_overrides = _validated_format_overrides(
|
|
1542
|
+
target, fingerprint, heading_batch_id, heading_levels,
|
|
1543
|
+
role_batch_id, role_overrides, region_start_id,
|
|
1544
|
+
)
|
|
1545
|
+
if any(role.startswith("heading_") for role in paragraph_overrides.values()) and not scope["headings"]:
|
|
1546
|
+
raise SyncError("应用候选标题级别时必须勾选“一至四级标题”")
|
|
1547
|
+
if any(role in ("table_title", "table_continuation") for role in paragraph_overrides.values()) and not scope["statement"]:
|
|
1548
|
+
raise SyncError("应用表格标题角色时必须勾选“报表名称、日期与表格标题”")
|
|
1549
|
+
result = _scan_opened_report(
|
|
1550
|
+
source, template_label, profile, target, self_sample, scope,
|
|
1551
|
+
paragraph_overrides, region,
|
|
1552
|
+
)
|
|
1553
|
+
result["assigned_headings"] = sum(role.startswith("heading_") for role in paragraph_overrides.values())
|
|
1554
|
+
result["assigned_roles"] = sum(not role.startswith("heading_") for role in paragraph_overrides.values())
|
|
1555
|
+
result["region_start"] = region[0] if region is not None else None
|
|
1556
|
+
result["output"] = str(output_path)
|
|
1557
|
+
result["dry_run"] = bool(dry_run)
|
|
1558
|
+
result["visual_review"] = list(VISUAL_REVIEW)
|
|
1559
|
+
log(f"[格式] 格式来源:{template_label}")
|
|
1560
|
+
log(f"[格式] 待调整:{source.name}(处理 {result['totals']['selected_paragraphs']} 段、{result['totals']['tables']} 张表)")
|
|
1561
|
+
if dry_run:
|
|
1562
|
+
log(f"[格式] 预演完成,未写入文件;计划输出:{output_path.name}")
|
|
1563
|
+
return result
|
|
1564
|
+
|
|
1565
|
+
before = _document_snapshot(target)
|
|
1566
|
+
counts = _apply_profile(target, profile, scope, paragraph_overrides, region)
|
|
1567
|
+
fd, temp_name = tempfile.mkstemp(prefix=f".{output_path.stem}.", suffix=output_path.suffix, dir=output_path.parent)
|
|
1568
|
+
os.close(fd)
|
|
1569
|
+
staged = Path(temp_name)
|
|
1570
|
+
try:
|
|
1571
|
+
target.save(str(staged))
|
|
1572
|
+
if source.suffix.lower() == ".docm":
|
|
1573
|
+
_rewrite_main_type(staged, macro_enabled=True)
|
|
1574
|
+
_validate_output(source, staged, before)
|
|
1575
|
+
os.replace(staged, output_path)
|
|
1576
|
+
except Exception as exc:
|
|
1577
|
+
staged.unlink(missing_ok=True)
|
|
1578
|
+
if isinstance(exc, SyncError):
|
|
1579
|
+
raise
|
|
1580
|
+
raise SyncError(f"生成格式副本失败,原报告未改动:{exc}") from exc
|
|
1581
|
+
result["counts"] = counts
|
|
1582
|
+
result["applied"] = True
|
|
1583
|
+
log(f"[格式] 已生成:{output_path}")
|
|
1584
|
+
log("[格式] 已核验文字、书签、表格、分节、图片/嵌入对象和 VBA 与原文一致。")
|
|
1585
|
+
return result
|