dsh-docx-format 0.0.0-stage → 1.0.0

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/lib/docxfmt.py ADDED
@@ -0,0 +1,1731 @@
1
+ # -*- coding: utf-8 -*-
2
+ """docxfmt.py — 通用公文格式规范化引擎 (dsh-docx-format)
3
+
4
+ 用法:
5
+ python docxfmt.py <file.docx|dir> [--mode apply|check] [--recursive] [--json] [--print] [--config '<json>']
6
+ 模式:
7
+ apply 规范化并写回(原子替换)
8
+ check 只检查不修改,输出违规项
9
+ 退出码: 0 成功;1 参数/运行错误;2 check 模式下存在违规。
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import base64
15
+ import copy
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import time
24
+ from collections import Counter
25
+
26
+ try:
27
+ from docx import Document
28
+ from docx.enum.table import WD_TABLE_ALIGNMENT
29
+ from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
30
+ from docx.oxml import OxmlElement
31
+ from docx.oxml.ns import qn
32
+ from docx.shared import Cm, Pt
33
+ from docx.table import Table
34
+ from docx.text.paragraph import Paragraph
35
+ except Exception as exc: # pragma: no cover
36
+ print(json.dumps({"ok": False, "error": "python-docx 不可用: %s" % exc}, ensure_ascii=False))
37
+ sys.exit(1)
38
+
39
+ CENTER = WD_ALIGN_PARAGRAPH.CENTER
40
+ RIGHT = WD_ALIGN_PARAGRAPH.RIGHT
41
+ JUSTIFY = WD_ALIGN_PARAGRAPH.JUSTIFY
42
+
43
+ DEFAULTS = {
44
+ "fonts": {
45
+ "title": "方正小标宋简体",
46
+ "body": "仿宋",
47
+ "h1": "黑体",
48
+ "h2": "楷体",
49
+ "h3": "仿宋",
50
+ "latin": "Times New Roman",
51
+ "footer": "宋体",
52
+ "tableHead": "黑体",
53
+ "tableBody": "仿宋",
54
+ "tableCaption": "方正小标宋简体",
55
+ },
56
+ "sizes": {"title": 22, "body": 16, "table": 12, "footer": 14, "spacer": 10.5},
57
+ "linePt": 29,
58
+ # 首行缩进以“字符”为单位(w:firstLineChars),不用磅值
59
+ "indentChars": 2,
60
+ # 附件:左/右/悬挂缩进一律 0,只用“首行缩进”这一种特殊缩进。
61
+ # attach_line 「附件:1.……」 首行 2 字符
62
+ # attach_cont 「2.……」 首行 5 字符(= 3 字“附件:”+ 2 字“1.”)
63
+ # attach_wrap 手工换行出来的续行 首行 6 字符
64
+ "attachLineIndentChars": 2,
65
+ "attachContIndentChars": 5,
66
+ "attachWrapIndentChars": 6,
67
+ # 附件条目超出一行时,用 Word/WPS 实测折行点,把视觉行拆成真实段落(续行 6 字符)。
68
+ # 拿不到排版引擎就只设首行缩进,不拆段(由用户手工换行)。
69
+ "attachSplit": {"enabled": True, "mode": "word", "maxRounds": 12,
70
+ "minCharsToMeasure": 20},
71
+ # 所有段落段前/段后一律 0 磅;空行用独立空段落(整行)表达
72
+ "spaceBeforePt": 0,
73
+ "spaceAfterPt": 0,
74
+ "marginsCm": {"top": 3.6, "bottom": 3.0, "left": 2.7, "right": 2.7},
75
+ "titleBlankBeforeLines": 2,
76
+ "titleBlankAfterLines": 1,
77
+ "attachBlankBeforeLines": 1,
78
+ "attachBlankAfterLines": 2,
79
+ # 文件中的“附件1”标记:下与附件标题空出一行(参考要求未规定其上要空行)
80
+ "attachTagBlankAfterLines": 1,
81
+ "tableBordersPt": {"outer": 1.5, "inner": 0.5},
82
+ "rowHeightCm": 0.7,
83
+ "pageNumber": True,
84
+ # enabled=False:完全不处理落款(不右对齐、不加空行、不补空格)。
85
+ # 默认 True 只格式化文档里【已有】的落款,绝不新增;“默认不写落款”由提示词层
86
+ # 控制(未明确要求署名/日期时不生成落款文字)。
87
+ "signature": {"enabled": True, "seal": False, "datePadSpaces": 2,
88
+ "blankLinesBefore": 2},
89
+ # 正文命中这些关键词时整篇跳过(白名单),如“实验报告”
90
+ "skipContentKeywords": ["实验报告"],
91
+ "normalize": {
92
+ "stripLeadingSpace": True,
93
+ "fullwidthNumberDot": True,
94
+ "twoCharCellSpace": True,
95
+ "dashFont": True,
96
+ "boldOff": True,
97
+ },
98
+ }
99
+
100
+ RE_H1 = re.compile(r"^[ \u3000]*[一二三四五六七八九十百]{1,4}、")
101
+ RE_H2 = re.compile(r"^[ \u3000]*[((][一二三四五六七八九十百]{1,4}[))]")
102
+ RE_H3 = re.compile(r"^[ \u3000]*\d{1,2}\s*[..、](?!\d)")
103
+ RE_ATTACH_TAG = re.compile(r"^[ \u3000]*附件\s*\d{0,2}\s*$")
104
+ RE_ATTACH_LINE = re.compile(r"^[ \u3000]*附件\s*[::]")
105
+ RE_ATTACH_ITEM = re.compile(r"^[((]?\d{1,2}\s*[..、))]")
106
+ RE_DATE = re.compile(r"\d{4}\s*年\s*\d{1,2}\s*月\s*\d{1,2}\s*日")
107
+ RE_LEAD_SPACE = re.compile(r"^[\u3000 ]+")
108
+ RE_FULLWIDTH_SPACE = "\u3000"
109
+
110
+
111
+ # ---------------------------------------------------------------- 工具函数
112
+ def ename(value):
113
+ if value is None:
114
+ return None
115
+ return getattr(value, "name", None) or str(value)
116
+
117
+
118
+ def pt_of(length):
119
+ if length is None:
120
+ return None
121
+ try:
122
+ return round(length.pt, 2)
123
+ except Exception:
124
+ return None
125
+
126
+
127
+ def text_width(s):
128
+ """按全角字符数估算显示宽度(半角记 0.5)。"""
129
+ w = 0.0
130
+ for ch in s:
131
+ w += 0.5 if ord(ch) < 0x2000 else 1.0
132
+ return w
133
+
134
+
135
+ def is_cjk(ch):
136
+ return "\u4e00" <= ch <= "\u9fff"
137
+
138
+
139
+ def merge_config(user):
140
+ cfg = copy.deepcopy(DEFAULTS)
141
+ if not user:
142
+ return cfg
143
+ for k, v in user.items():
144
+ if isinstance(v, dict) and isinstance(cfg.get(k), dict):
145
+ cfg[k].update(v)
146
+ else:
147
+ cfg[k] = v
148
+ return cfg
149
+
150
+
151
+ # ---------------------------------------------------------------- 报告收集
152
+ class Report:
153
+ def __init__(self, path, mode, fix):
154
+ self.path = path
155
+ self.mode = mode
156
+ self.fix = fix
157
+ self.rules = {} # rule -> {"count":int,"samples":[...]}
158
+ self.warnings = []
159
+ self.stats = Counter()
160
+ self.total = 0
161
+
162
+ def want(self, rule, where, current, expected, apply_fn=None):
163
+ """记录一处偏差;fix 模式下调用 apply_fn。返回是否命中偏差。"""
164
+ if current == expected:
165
+ return False
166
+ self.total += 1
167
+ entry = self.rules.setdefault(rule, {"count": 0, "samples": []})
168
+ entry["count"] += 1
169
+ if len(entry["samples"]) < 3:
170
+ entry["samples"].append(
171
+ {"where": where, "current": _s(current), "expected": _s(expected)}
172
+ )
173
+ if self.fix and apply_fn is not None:
174
+ apply_fn()
175
+ return True
176
+
177
+ def warn(self, msg):
178
+ if msg not in self.warnings:
179
+ self.warnings.append(msg)
180
+
181
+ def as_dict(self, changed):
182
+ return {
183
+ "ok": True,
184
+ "file": self.path,
185
+ "mode": self.mode,
186
+ "changed": bool(changed),
187
+ "violations": self.total,
188
+ "rules": self.rules,
189
+ "stats": dict(self.stats),
190
+ "warnings": self.warnings,
191
+ }
192
+
193
+
194
+ def _s(v):
195
+ if v is None:
196
+ return "无"
197
+ if isinstance(v, bool):
198
+ return "是" if v else "否"
199
+ return str(v)
200
+
201
+
202
+ # ---------------------------------------------------------------- 字体/段落
203
+ def set_run(run, font, size, latin, report, where, cfg):
204
+ if run.text is None or run.text == "":
205
+ if run._element.findall(".//" + qn("w:drawing")):
206
+ pass
207
+ f = run.font
208
+ rPr = run._element.get_or_add_rPr()
209
+
210
+ if cfg["normalize"]["boldOff"]:
211
+ if f.bold:
212
+ report.want("run.bold", where, "加粗", "常规",
213
+ lambda: setattr(f, "bold", None))
214
+ cur_ascii = f.name
215
+ if cur_ascii != latin:
216
+ report.want("run.font.latin", where, cur_ascii, latin,
217
+ lambda: setattr(f, "name", latin))
218
+ if rPr.find(qn("w:rFonts")) is None:
219
+ f.name = latin
220
+ rFonts = rPr.find(qn("w:rFonts"))
221
+ cur_ea = rFonts.get(qn("w:eastAsia"))
222
+ if cur_ea != font:
223
+ report.want("run.font.eastAsia", where, cur_ea, font,
224
+ lambda: rFonts.set(qn("w:eastAsia"), font))
225
+ cur_sz = pt_of(f.size)
226
+ if cur_sz != size:
227
+ report.want("run.font.size", where, cur_sz, size,
228
+ lambda: setattr(f, "size", Pt(size)))
229
+ if f.highlight_color is not None:
230
+ report.want("run.highlight", where, ename(f.highlight_color), "无",
231
+ lambda: setattr(f, "highlight_color", None))
232
+
233
+
234
+ def style_runs(par, font, size, latin, report, label, cfg):
235
+ for idx, run in enumerate(par.runs):
236
+ where = "%s#r%d" % (label, idx)
237
+ if (cfg["normalize"]["dashFont"] and run.text
238
+ and set(run.text) <= {"—", "-"} and run.text.strip()):
239
+ # 破折号用 Times New Roman
240
+ set_run(run, latin, size, latin, report, where, cfg)
241
+ else:
242
+ set_run(run, font, size, latin, report, where, cfg)
243
+
244
+
245
+ # ---------------------------------------------------------------- 缩进(字符单位)
246
+ # python-docx 没有 firstLineChars / leftChars 的 API,直接写 OOXML 属性。
247
+ # Word 优先使用 *Chars 属性(1/100 字符),*FirstLine/*Left 仅作兼容回退值。
248
+ IND_SUCCESSORS = ("w:contextualSpacing", "w:mirrorIndents", "w:suppressOverlap", "w:jc",
249
+ "w:textDirection", "w:textAlignment", "w:textboxTightWrap", "w:outlineLvl",
250
+ "w:divId", "w:cnfStyle", "w:rPr", "w:sectPr", "w:pPrChange")
251
+
252
+ IND_CHAR_ATTRS = ("w:firstLineChars", "w:leftChars", "w:rightChars",
253
+ "w:hangingChars", "w:hanging")
254
+
255
+ # 空段落有两种:正文侧(沿用仿宋三号正文格式)与标题侧(沿用方正小标宋二号居中)
256
+ BLANK_KINDS = ("blank", "blank_title")
257
+
258
+
259
+ def _mark_rpr(par, make=False):
260
+ """段落标记的 w:pPr/w:rPr(空段落的“字体”就存在这里)。"""
261
+ pPr = par._p.pPr
262
+ if pPr is None:
263
+ if not make:
264
+ return None
265
+ pPr = par._p.get_or_add_pPr()
266
+ rPr = pPr.find(qn("w:rPr"))
267
+ if rPr is None and make:
268
+ rPr = OxmlElement("w:rPr")
269
+ pPr.append(rPr) # w:rPr 是 pPr 的最后一个子元素
270
+ return rPr
271
+
272
+
273
+ def _mark_font(par):
274
+ """读段落标记的 (东亚字体, 字号磅);未显式设置则为 None(继承样式)。"""
275
+ rPr = _mark_rpr(par)
276
+ if rPr is None:
277
+ return None, None
278
+ font = None
279
+ rf = rPr.find(qn("w:rFonts"))
280
+ if rf is not None:
281
+ font = rf.get(qn("w:eastAsia")) or rf.get(qn("w:ascii"))
282
+ size = None
283
+ sz = rPr.find(qn("w:sz"))
284
+ if sz is not None:
285
+ try:
286
+ size = int(sz.get(qn("w:val"))) / 2.0
287
+ except (TypeError, ValueError):
288
+ size = None
289
+ return font, size
290
+
291
+
292
+ def _write_mark_font(par, font, size_pt, latin):
293
+ """写段落标记的字体字号:手工回车时 Word 也是把字体记在段落标记上。"""
294
+ rPr = _mark_rpr(par, make=True)
295
+ rf = rPr.find(qn("w:rFonts"))
296
+ if rf is None:
297
+ rf = OxmlElement("w:rFonts")
298
+ rPr.insert(0, rf)
299
+ rf.set(qn("w:ascii"), latin)
300
+ rf.set(qn("w:hAnsi"), latin)
301
+ rf.set(qn("w:eastAsia"), font)
302
+ rf.set(qn("w:cs"), latin)
303
+ val = str(int(round(float(size_pt) * 2)))
304
+ for tag in ("w:sz", "w:szCs"):
305
+ el = rPr.find(qn(tag))
306
+ if el is None:
307
+ el = OxmlElement(tag)
308
+ rPr.append(el)
309
+ el.set(qn("w:val"), val)
310
+
311
+
312
+ def _get_ind(par, make=False):
313
+ pPr = par._p.pPr
314
+ if pPr is None:
315
+ if not make:
316
+ return None
317
+ pPr = par._p.get_or_add_pPr()
318
+ ind = pPr.find(qn("w:ind"))
319
+ if ind is None and make:
320
+ ind = OxmlElement("w:ind")
321
+ try:
322
+ pPr.insert_element_before(ind, *IND_SUCCESSORS)
323
+ except Exception:
324
+ pPr.append(ind)
325
+ return ind
326
+
327
+
328
+ def _get_chars(par, attr):
329
+ ind = _get_ind(par)
330
+ if ind is None:
331
+ return None
332
+ raw = ind.get(qn(attr))
333
+ if raw is None or raw == "":
334
+ return None
335
+ try:
336
+ return int(round(int(raw))) / 100.0
337
+ except ValueError:
338
+ return None
339
+
340
+
341
+ def set_chars_indent(par, attr, chars, fallback_pt):
342
+ """把 *Chars 缩进写入 w:ind(chars 为 None 时清除该属性)。"""
343
+ ind = _get_ind(par, make=True)
344
+ char_attr = qn("w:" + attr + "Chars")
345
+ pt_attr = qn("w:" + attr)
346
+ other = {
347
+ "firstLine": "hanging",
348
+ "left": "leftChars",
349
+ "right": "rightChars",
350
+ }.get(attr)
351
+ if chars is None or chars == 0:
352
+ for key in (char_attr, pt_attr):
353
+ if ind.get(key) is not None:
354
+ del ind.attrib[key]
355
+ else:
356
+ ind.set(char_attr, str(int(round(chars * 100))))
357
+ ind.set(pt_attr, str(int(round(fallback_pt.twips))))
358
+ if attr == "firstLine":
359
+ # 首行缩进与悬挂互斥:写首行就清悬挂
360
+ for key in (qn("w:hangingChars"), qn("w:hanging")):
361
+ if ind.get(key) is not None:
362
+ del ind.attrib[key]
363
+ elif attr == "hanging" and chars:
364
+ for key in (qn("w:firstLineChars"), qn("w:firstLine")):
365
+ if ind.get(key) is not None:
366
+ del ind.attrib[key]
367
+
368
+
369
+ def clear_side_indent(par):
370
+ """清掉左/右/悬挂缩进(字符与磅两套属性),保留首行缩进。
371
+
372
+ 公文里唯一允许的缩进是“首行缩进”,左右缩进与悬挂缩进一律 0。
373
+ """
374
+ ind = _get_ind(par)
375
+ if ind is None:
376
+ return
377
+ for key in ("w:leftChars", "w:left", "w:rightChars", "w:right",
378
+ "w:hangingChars", "w:hanging"):
379
+ if ind.get(qn(key)) is not None:
380
+ del ind.attrib[qn(key)]
381
+
382
+
383
+ def _has_side(chars, pt):
384
+ """侧边缩进是否非 0(字符或磅任一表达)。"""
385
+ if chars:
386
+ return abs(chars) > 0.01
387
+ return pt is not None and abs(pt) > 0.5
388
+
389
+
390
+ def _side_desc(chars, pt):
391
+ """侧边缩进的当前值描述;0 与“无”统一写成 0,避免误判偏差。"""
392
+ if chars:
393
+ return "%.2f 字符" % chars
394
+ if pt is not None and abs(pt) > 0.5:
395
+ return "%.1f 磅" % pt
396
+ return "0"
397
+
398
+
399
+ def _get_pt(ind, attr):
400
+ """读 w:left / w:hanging 的磅值(twips / 20)。"""
401
+ if ind is None:
402
+ return None
403
+ raw = ind.get(qn(attr))
404
+ if raw in (None, ""):
405
+ return None
406
+ try:
407
+ return int(raw) / 20.0
408
+ except ValueError:
409
+ return None
410
+
411
+
412
+ def _style_blank(par, cfg, kind="blank"):
413
+ """空行 = 独立空段落,但格式要与“手工回车”的结果一致:
414
+
415
+ - 标题上/下那几行沿用标题格式:方正小标宋简体二号、居中、无首行缩进;
416
+ - 其余空行沿用正文格式:仿宋三号、两端对齐、首行缩进 2 字符。
417
+
418
+ 段落标记(w:pPr/w:rPr)就是 Word 存“空段落字体”的地方,所以字体字号写在那里。
419
+ """
420
+ title_side = kind == "blank_title"
421
+ pf = par.paragraph_format
422
+ pf.line_spacing_rule = WD_LINE_SPACING.EXACTLY
423
+ pf.line_spacing = Pt(cfg["linePt"])
424
+ _write_zero_spacing(par)
425
+ pf.alignment = CENTER if title_side else JUSTIFY
426
+ font = cfg["fonts"]["title"] if title_side else cfg["fonts"]["body"]
427
+ size = cfg["sizes"]["title"] if title_side else cfg["sizes"]["body"]
428
+ _write_mark_font(par, font, size, cfg["fonts"]["latin"])
429
+ chars = 0.0 if title_side else float(cfg["indentChars"])
430
+ set_chars_indent(par, "firstLine", chars, Pt(chars * float(cfg["sizes"]["body"])))
431
+ set_chars_indent(par, "left", None, Pt(0))
432
+ set_chars_indent(par, "right", None, Pt(0))
433
+
434
+
435
+ def style_par(par, kind, report, label, cfg):
436
+ pf = par.paragraph_format
437
+ fonts = cfg["fonts"]
438
+ sizes = cfg["sizes"]
439
+ line = Pt(cfg["linePt"])
440
+ body_pt = Pt(sizes["body"])
441
+ indent_chars = float(cfg["indentChars"]) # 首行缩进 2 字符
442
+
443
+ if kind in BLANK_KINDS:
444
+ report.stats["para.blank"] += 1
445
+ title_side = kind == "blank_title"
446
+ b_font = fonts["title"] if title_side else fonts["body"]
447
+ b_size = float(sizes["title"] if title_side else sizes["body"])
448
+ b_align = CENTER if title_side else JUSTIFY
449
+ b_chars = 0.0 if title_side else indent_chars
450
+ if pf.line_spacing_rule != WD_LINE_SPACING.EXACTLY or pt_of(pf.line_spacing) != float(cfg["linePt"]):
451
+ report.want("blank.lineSpacing", label, pt_of(pf.line_spacing), float(cfg["linePt"]),
452
+ (lambda: (setattr(pf, "line_spacing_rule", WD_LINE_SPACING.EXACTLY),
453
+ setattr(pf, "line_spacing", line))))
454
+ _zero_spacing(par, pf, report, label, cfg)
455
+ # 空段落也要像手工回车那样带着前后文的字体、字号、对齐与首行缩进
456
+ cur_font, cur_size = _mark_font(par)
457
+ cur_chars = _get_chars(par, "w:firstLineChars")
458
+ drift = []
459
+ if cur_font != b_font:
460
+ drift.append("字体 %s" % (cur_font or "继承样式"))
461
+ if cur_size is None or abs(cur_size - b_size) > 0.01:
462
+ drift.append("字号 %s" % ("继承样式" if cur_size is None else "%g 磅" % cur_size))
463
+ if pf.alignment != b_align:
464
+ drift.append("对齐 %s" % ("居中" if pf.alignment == CENTER
465
+ else "两端对齐" if pf.alignment == JUSTIFY
466
+ else ("左对齐" if pf.alignment is None
467
+ else str(pf.alignment))))
468
+ if abs((cur_chars or 0.0) - b_chars) > 0.01:
469
+ drift.append("首行缩进 %.2f 字符" % (cur_chars or 0.0))
470
+ if drift:
471
+ report.want("blank.mark", label, "、".join(drift),
472
+ "%s %g 磅、%s、首行缩进 %g 字符"
473
+ % (b_font, b_size,
474
+ "居中" if title_side else "两端对齐", b_chars),
475
+ (lambda p=par, k=kind: _style_blank(p, cfg, k)))
476
+ _clear_indent_chars(par, report, label, kind, b_chars)
477
+ return
478
+
479
+ if kind == "caption_spacer":
480
+ report.stats["para.blank"] += 1
481
+ if not _spacer_props_ok(par._p, cfg):
482
+ report.want("table.captionSpacer", label, "空行行高/字号不符",
483
+ "行高最小值 0 磅、5 号字",
484
+ lambda: _write_spacer_props(par._p, cfg))
485
+ return
486
+
487
+ want_align = None
488
+ want_font = fonts["body"]
489
+ want_size = sizes["body"]
490
+ want_first_chars = indent_chars
491
+ want_left_chars = 0.0
492
+ want_hang_chars = 0.0
493
+ want_line_single = False # 图片行用单倍行距,不套 29 磅固定值
494
+
495
+ if kind in ("title", "title_first", "title_mid", "title_last", "title_only"):
496
+ want_align, want_font, want_size = CENTER, fonts["title"], sizes["title"]
497
+ want_first_chars = None
498
+ elif kind == "table_caption":
499
+ want_align, want_font, want_size = CENTER, fonts["tableCaption"], sizes["title"]
500
+ want_first_chars = None
501
+ elif kind == "h1":
502
+ want_font = fonts["h1"]
503
+ elif kind == "h2":
504
+ want_font = fonts["h2"]
505
+ elif kind == "h3":
506
+ want_font = fonts["h3"]
507
+ elif kind == "attach_tag":
508
+ want_align, want_font, want_first_chars = JUSTIFY, fonts["h1"], None
509
+ elif kind == "attach_line":
510
+ # 「附件:1.……」:左/右/悬挂全 0,只有首行缩进 2 字符
511
+ want_align = JUSTIFY
512
+ want_first_chars = float(cfg["attachLineIndentChars"])
513
+ elif kind == "attach_cont":
514
+ # 多附件的“2.……”:首行缩进 5 字符,与冒号后序号同一竖线
515
+ want_align = JUSTIFY
516
+ want_first_chars = float(cfg["attachContIndentChars"])
517
+ elif kind == "attach_wrap":
518
+ # 手工换行出来的续行:首行缩进 6 字符
519
+ want_align = JUSTIFY
520
+ want_first_chars = float(cfg["attachWrapIndentChars"])
521
+ elif kind == "sign_org":
522
+ if cfg["signature"]["enabled"]:
523
+ want_align, want_first_chars = RIGHT, None
524
+ else:
525
+ want_align, want_first_chars = None, None # 不写落款:不改造版式
526
+ elif kind == "sign_date":
527
+ if cfg["signature"]["enabled"]:
528
+ want_align, want_first_chars = RIGHT, None
529
+ else:
530
+ want_align, want_first_chars = None, None
531
+ elif kind == "image":
532
+ # 图片所在行:居中、无缩进(首行/左右/悬挂全 0)、单倍行距
533
+ want_align, want_first_chars = CENTER, None
534
+ want_line_single = True
535
+ else:
536
+ want_align = JUSTIFY
537
+
538
+ report.stats["para." + kind] += 1
539
+
540
+ def do_align():
541
+ pf.alignment = want_align
542
+
543
+ if want_align is None:
544
+ if pf.alignment is not None:
545
+ report.want("par.alignment", label, ename(pf.alignment), "无",
546
+ lambda: setattr(pf, "alignment", None))
547
+ else:
548
+ report.want("par.alignment", label, ename(pf.alignment), ename(want_align), do_align)
549
+
550
+ if want_line_single:
551
+ _check_single_line(par, pf, report, label)
552
+ else:
553
+ cur_rule = ename(pf.line_spacing_rule)
554
+ if pf.line_spacing_rule != WD_LINE_SPACING.EXACTLY:
555
+ report.want("par.lineRule", label, cur_rule, "EXACTLY",
556
+ lambda: setattr(pf, "line_spacing_rule", WD_LINE_SPACING.EXACTLY))
557
+ if pt_of(pf.line_spacing) != float(cfg["linePt"]):
558
+ report.want("par.lineSpacing", label, pt_of(pf.line_spacing), float(cfg["linePt"]),
559
+ lambda: setattr(pf, "line_spacing", line))
560
+
561
+ # 首行缩进:以字符为单位(w:firstLineChars=200 → 2 字符)
562
+ cur_chars = _get_chars(par, "w:firstLineChars")
563
+ if want_first_chars is None:
564
+ if cur_chars is not None:
565
+ report.want("par.firstLineChars", label, "%.2f 字符" % cur_chars, "无",
566
+ (lambda p=par: set_chars_indent(p, "firstLine", None, body_pt)))
567
+ if not want_hang_chars and pf.first_line_indent is not None \
568
+ and abs(pt_of(pf.first_line_indent) or 0) > 1:
569
+ # 悬挂缩进时 python-docx 会把 w:hanging 读成负的 first_line_indent,
570
+ # 那种情况由下面的 hanging 分支管,这里不能判它违规。
571
+ report.want("par.firstLineIndent", label, pt_of(pf.first_line_indent), "无",
572
+ (lambda p=par: set_chars_indent(p, "firstLine", None, body_pt)))
573
+ else:
574
+ if cur_chars is None or abs(cur_chars - want_first_chars) > 0.01:
575
+ report.want("par.firstLineChars", label,
576
+ "无(%.1f 磅)" % (pt_of(pf.first_line_indent) or 0) if cur_chars is None
577
+ else "%.2f 字符" % cur_chars,
578
+ "%.2f 字符" % want_first_chars,
579
+ (lambda p=par, c=want_first_chars, b=body_pt:
580
+ set_chars_indent(p, "firstLine", c, Pt(c * b.pt))))
581
+
582
+ # 侧边缩进(左 / 右 / 悬挂)一律 0:可用的“特殊缩进”只有首行缩进
583
+ ind = _get_ind(par)
584
+ cur_left_chars = _get_chars(par, "w:leftChars")
585
+ cur_left_pt = _get_pt(ind, "w:left")
586
+ cur_hang_chars = _get_chars(par, "w:hangingChars")
587
+ cur_hang_pt = _get_pt(ind, "w:hanging")
588
+
589
+ if want_left_chars:
590
+ if (cur_left_chars is None or abs(cur_left_chars - want_left_chars) > 0.01
591
+ or _has_side(None, cur_left_pt)):
592
+ report.want("par.leftChars", label, _side_desc(cur_left_chars, cur_left_pt),
593
+ "%.2f 字符" % want_left_chars,
594
+ (lambda p=par, c=want_left_chars, b=body_pt:
595
+ set_chars_indent(p, "left", c, Pt(c * b.pt))))
596
+ elif _has_side(cur_left_chars, cur_left_pt):
597
+ report.want("par.leftIndent", label, _side_desc(cur_left_chars, cur_left_pt), "0",
598
+ (lambda p=par: clear_side_indent(p)))
599
+
600
+ if want_hang_chars:
601
+ if (cur_hang_chars is None or abs(cur_hang_chars - want_hang_chars) > 0.01
602
+ or _has_side(None, cur_hang_pt)):
603
+ report.want("par.hangingChars", label, _side_desc(cur_hang_chars, cur_hang_pt),
604
+ "%.2f 字符" % want_hang_chars,
605
+ (lambda p=par, c=want_hang_chars, b=body_pt:
606
+ set_chars_indent(p, "hanging", c, Pt(c * b.pt))))
607
+ elif _has_side(cur_hang_chars, cur_hang_pt):
608
+ report.want("par.hangingIndent", label, _side_desc(cur_hang_chars, cur_hang_pt), "0",
609
+ (lambda p=par: clear_side_indent(p)))
610
+
611
+ _zero_spacing(par, pf, report, label, cfg)
612
+
613
+ cur_right = pt_of(pf.right_indent) or 0
614
+ if abs(cur_right) > 1:
615
+ report.want("par.rightIndent", label, cur_right, 0,
616
+ (lambda: setattr(pf, "right_indent", None)))
617
+
618
+ if par.runs:
619
+ style_runs(par, want_font, want_size, fonts["latin"], report, label, cfg)
620
+
621
+
622
+ def _spacing_elm(par):
623
+ pPr = par._p.find(qn("w:pPr"))
624
+ return None if pPr is None else pPr.find(qn("w:spacing"))
625
+
626
+
627
+ def _is_single_line(par):
628
+ """w:line="240" + w:lineRule="auto"(或缺省 lineRule)即标准单倍行距。"""
629
+ sp = _spacing_elm(par)
630
+ if sp is None or sp.get(qn("w:line")) != "240":
631
+ return False
632
+ return (sp.get(qn("w:lineRule")) or "auto") == "auto"
633
+
634
+
635
+ def _write_single_line(par):
636
+ pPr = par._p.get_or_add_pPr()
637
+ sp = pPr.get_or_add_spacing()
638
+ sp.set(qn("w:line"), "240")
639
+ sp.set(qn("w:lineRule"), "auto")
640
+
641
+
642
+ def _check_single_line(par, pf, report, label):
643
+ """图片行:要求单倍行距(w:line=240 lineRule=auto),不套 29 磅固定值。"""
644
+ if _is_single_line(par):
645
+ return
646
+ sp = _spacing_elm(par)
647
+ raw = None if sp is None else sp.get(qn("w:line"))
648
+ if raw is None:
649
+ cur = "继承样式"
650
+ else:
651
+ try:
652
+ val = float(raw)
653
+ except (TypeError, ValueError):
654
+ val = 0.0
655
+ rule = sp.get(qn("w:lineRule")) or "auto"
656
+ if rule == "exact":
657
+ cur = "%g 磅(固定)" % round(val / 20.0, 1)
658
+ elif rule == "atLeast":
659
+ cur = "%g 磅(最小值)" % round(val / 20.0, 1)
660
+ else:
661
+ cur = "%g 倍" % round(val / 240.0, 2)
662
+ report.want("par.lineSingle", label, cur, "单倍行距",
663
+ lambda: _write_single_line(par))
664
+
665
+
666
+ def _write_zero_spacing(par):
667
+ """把段前/段后显式写成 0 磅,并清掉“行”单位与自动间距。
668
+
669
+ 只把 w:before / w:after 删掉是不行的:Word 会继续继承 docDefaults 或
670
+ Normal 样式里的段后间距(常见 w:after="200" = 10 磅),用户看到的就是
671
+ “段前段后不是 0 磅”。
672
+ """
673
+ pPr = par._p.get_or_add_pPr()
674
+ sp = pPr.get_or_add_spacing()
675
+ for key in ("w:beforeLines", "w:afterLines",
676
+ "w:beforeAutospacing", "w:afterAutospacing"):
677
+ sp.attrib.pop(qn(key), None)
678
+ sp.set(qn("w:before"), "0")
679
+ sp.set(qn("w:after"), "0")
680
+
681
+
682
+ def _zero_spacing(par, pf, report, label, cfg):
683
+ """段前/段后一律 0 磅:间距由独立空段落表达,不用段前段后。"""
684
+ pPr = par._p.get_or_add_pPr()
685
+ sp = pPr.find(qn("w:spacing"))
686
+ need = sp is None
687
+ if sp is not None:
688
+ for key in ("w:before", "w:after"):
689
+ if (sp.get(qn(key)) or "") != "0":
690
+ need = True
691
+ for key in ("w:beforeLines", "w:afterLines",
692
+ "w:beforeAutospacing", "w:afterAutospacing"):
693
+ if sp.get(qn(key)) is not None:
694
+ need = True
695
+ if need:
696
+ report.want("par.spaceZero", label, "非 0 磅或继承样式", "0 磅",
697
+ lambda: _write_zero_spacing(par))
698
+
699
+
700
+ def _clear_indent_chars(par, report, label, kind, first_chars=0.0):
701
+ """清掉不该有的字符缩进;*first_chars* 是本 kind 期望的首行缩进(默认 0)。"""
702
+ for attr, name in (("firstLine", "firstLineChars"), ("left", "leftChars"),
703
+ ("right", "rightChars")):
704
+ cur = _get_chars(par, "w:" + name)
705
+ if cur is None:
706
+ continue
707
+ if attr == "firstLine" and abs(cur - float(first_chars)) <= 0.01:
708
+ continue
709
+ report.want("par." + name, label, "%.2f 字符" % cur, "无",
710
+ (lambda p=par, a=attr: set_chars_indent(p, a, None, Pt(0))))
711
+ cur_hang = _get_chars(par, "w:hangingChars")
712
+ if cur_hang is not None:
713
+ report.want("par.hangingChars", label, "%.2f 字符" % cur_hang, "无",
714
+ (lambda p=par: set_hanging_chars(p, None, Pt(0))))
715
+
716
+
717
+ # ---------------------------------------------------------------- 文本规范化
718
+ def normalize_text(par, report, label, cfg):
719
+ p = par
720
+ text = p.text
721
+ if not text:
722
+ return
723
+ n = cfg["normalize"]
724
+ if n["stripLeadingSpace"] and RE_LEAD_SPACE.match(text):
725
+ stripped = text.lstrip("\u3000 ")
726
+ if stripped and p.runs:
727
+ first = p.runs[0]
728
+ report.want("text.leadingSpace", label, "存在行首空格", "无",
729
+ lambda: setattr(first, "text", first.text.lstrip("\u3000 ")))
730
+ if n["fullwidthNumberDot"]:
731
+ m = re.match(r"^(\s*)(\d{1,2})\.(?!\d)", p.text)
732
+ if m and p.runs:
733
+ runs = p.runs
734
+ for run in runs:
735
+ if "." in run.text and re.match(r"^\s*\d{1,2}\.\D*", run.text):
736
+ new = re.sub(r"^(\s*\d{1,2})\.(?!\d)\s*", "\\1.", run.text)
737
+ if new != run.text:
738
+ report.want("text.numberDot", label, "半角序号点", "全角.",
739
+ (lambda r=run, v=new: setattr(r, "text", v)))
740
+ break
741
+ # 「附件:1. xxx」里的序号点也要全角,且不留空格
742
+ for run in p.runs:
743
+ if "附件" not in run.text:
744
+ continue
745
+ new = re.sub(r"(附件:\s*)(\d{1,2})\s*\.(?!\d)\s*", "\\1\\2.", run.text)
746
+ new = re.sub(r"(附件:\s*)(\d{1,2})\s*.\s+", "\\1\\2.", new)
747
+ if new != run.text:
748
+ report.want("text.attachNumberDot", label, "附件序号半角点/空格", "全角.",
749
+ (lambda r=run, v=new: setattr(r, "text", v)))
750
+ break
751
+
752
+
753
+ # ---------------------------------------------------------------- 表格
754
+ BORDER_ORDER = ["top", "left", "bottom", "right", "insideH", "insideV"]
755
+
756
+
757
+ def set_borders(tbl, report, label, cfg):
758
+ """外边框 1.5 磅、内边框 0.5 磅(sz 单位为 1/8 磅)。"""
759
+ tblPr = tbl._element.tblPr
760
+ want_sz = {}
761
+ for edge in BORDER_ORDER:
762
+ kind = "outer" if edge in ("top", "left", "bottom", "right") else "inner"
763
+ want_sz[edge] = str(int(round(cfg["tableBordersPt"][kind] * 8)))
764
+
765
+ cur_el = tblPr.find(qn("w:tblBorders"))
766
+ diffs = []
767
+ for edge in BORDER_ORDER:
768
+ cur = None if cur_el is None else cur_el.find(qn("w:" + edge))
769
+ val = None if cur is None else cur.get(qn("w:val"))
770
+ sz = None if cur is None else cur.get(qn("w:sz"))
771
+ if val in (None, "nil", "none") or sz != want_sz[edge]:
772
+ diffs.append((edge, "%s/%s" % (val, sz), "single/%s" % want_sz[edge]))
773
+ if not diffs:
774
+ return
775
+ def rebuild():
776
+ old = tblPr.find(qn("w:tblBorders"))
777
+ if old is not None:
778
+ tblPr.remove(old)
779
+ el = OxmlElement("w:tblBorders")
780
+ for edge in BORDER_ORDER:
781
+ b = OxmlElement("w:" + edge)
782
+ b.set(qn("w:val"), "single")
783
+ b.set(qn("w:sz"), want_sz[edge])
784
+ b.set(qn("w:space"), "0")
785
+ b.set(qn("w:color"), "auto")
786
+ el.append(b)
787
+ tblPr.insert_element_before(el, "w:shd", "w:tblLayout", "w:tblCellMar",
788
+ "w:tblLook", "w:tblCaption", "w:tblDescription")
789
+ for edge, cur_s, want_s in diffs:
790
+ report.want("table.border." + edge, label, cur_s, want_s, rebuild)
791
+
792
+
793
+ def style_table(tbl, report, label, cfg):
794
+ report.stats["tables"] += 1
795
+ tblPr = tbl._element.tblPr
796
+ jc = tblPr.find(qn("w:jc"))
797
+ if jc is None or jc.get(qn("w:val")) != "center":
798
+ report.want("table.alignment", label, None if jc is None else jc.get(qn("w:val")), "center",
799
+ lambda: (_set_or_make(tblPr, "w:jc", {"w:val": "center"})))
800
+ set_borders(tbl, report, label, cfg)
801
+
802
+ # 表格本体缩进清零,避免 tblInd 把整表推偏导致“看起来没居中”
803
+ tblInd = tblPr.find(qn("w:tblInd"))
804
+ if tblInd is not None and (tblInd.get(qn("w:w")) or "0") != "0":
805
+ report.want("table.indent", label, tblInd.get(qn("w:w")), 0,
806
+ lambda: tblPr.remove(tblInd))
807
+
808
+ fonts, sizes = cfg["fonts"], cfg["sizes"]
809
+ for r_i, row in enumerate(tbl.rows):
810
+ trPr = row._tr.get_or_add_trPr()
811
+ h = trPr.find(qn("w:trHeight"))
812
+ want_twips = str(int(round(Cm(cfg["rowHeightCm"]).twips)))
813
+ if h is None:
814
+ report.want("table.rowHeight", "%s.r%d" % (label, r_i), "无", cfg["rowHeightCm"],
815
+ lambda r=trPr, t=want_twips: _set_or_make(r, "w:trHeight",
816
+ {"w:val": t, "w:hRule": "atLeast"}))
817
+ else:
818
+ if h.get(qn("w:hRule")) != "atLeast":
819
+ report.want("table.rowHeight.rule", "%s.r%d" % (label, r_i),
820
+ h.get(qn("w:hRule")), "atLeast",
821
+ lambda e=h: e.set(qn("w:hRule"), "atLeast"))
822
+ if (h.get(qn("w:val")) or "0") != want_twips:
823
+ report.want("table.rowHeight.value", "%s.r%d" % (label, r_i),
824
+ h.get(qn("w:val")), cfg["rowHeightCm"],
825
+ lambda e=h, t=want_twips: e.set(qn("w:val"), t))
826
+ if r_i == 0:
827
+ if trPr.find(qn("w:tblHeader")) is None:
828
+ report.want("table.headerRepeat", "%s.r0" % label, "未重复标题行", "重复",
829
+ lambda r=trPr: _set_or_make(r, "w:tblHeader", {}))
830
+ head = r_i == 0
831
+ for c_i, cell in enumerate(row.cells):
832
+ tcPr = cell._tc.get_or_add_tcPr()
833
+ va = tcPr.find(qn("w:vAlign"))
834
+ if va is None or va.get(qn("w:val")) != "center":
835
+ report.want("table.vAlign", "%s.r%d.c%d" % (label, r_i, c_i), None, "center",
836
+ lambda p=tcPr: _set_or_make(p, "w:vAlign", {"w:val": "center"}))
837
+ font = fonts["tableHead"] if head else fonts["tableBody"]
838
+ for p_i, par in enumerate(cell.paragraphs):
839
+ where = "%s.r%d.c%d.p%d" % (label, r_i, c_i, p_i)
840
+ pf = par.paragraph_format
841
+ if pf.line_spacing_rule != WD_LINE_SPACING.SINGLE:
842
+ report.want("table.lineRule", where, ename(pf.line_spacing_rule), "SINGLE",
843
+ lambda x=pf: setattr(x, "line_spacing_rule", WD_LINE_SPACING.SINGLE))
844
+ if pt_of(pf.line_spacing) not in (None, 1.0):
845
+ report.want("table.lineSpacing", where, pt_of(pf.line_spacing), "单倍",
846
+ lambda x=pf: setattr(x, "line_spacing", 1.0))
847
+ if pf.first_line_indent not in (None, 0):
848
+ report.want("table.firstLineIndent", where, pt_of(pf.first_line_indent), "无",
849
+ lambda x=pf: setattr(x, "first_line_indent", None))
850
+ for attr in ("firstLine", "left", "right"):
851
+ cur_chars = _get_chars(par, "w:" + attr + "Chars")
852
+ if cur_chars is not None:
853
+ report.want("table.%sChars" % attr, where, "%.2f 字符" % cur_chars, "无",
854
+ (lambda p=par, a=attr: set_chars_indent(p, a, None, Pt(0))))
855
+ _zero_spacing(par, pf, report, where, cfg)
856
+ # 单元格内容(含表头与正文)一律水平居中,并清掉左右缩进
857
+ if pf.alignment != CENTER:
858
+ report.want("table.cellAlign", where, ename(pf.alignment), "CENTER",
859
+ lambda x=pf: setattr(x, "alignment", CENTER))
860
+ if (pt_of(pf.left_indent) or 0) != 0:
861
+ report.want("table.cellLeftIndent", where, pt_of(pf.left_indent), 0,
862
+ lambda x=pf: setattr(x, "left_indent", None))
863
+ if (pt_of(pf.right_indent) or 0) != 0:
864
+ report.want("table.cellRightIndent", where, pt_of(pf.right_indent), 0,
865
+ lambda x=pf: setattr(x, "right_indent", None))
866
+ if cfg["normalize"]["twoCharCellSpace"] and par.text and re.fullmatch(r"[\u4e00-\u9fff]{2}", par.text):
867
+ _spread_two_chars(par, report, where, font, sizes["table"], cfg)
868
+ if par.runs:
869
+ style_runs(par, font, sizes["table"], fonts["latin"], report, where, cfg)
870
+
871
+
872
+ def _spread_two_chars(par, report, where, font, size, cfg):
873
+ """表格内两个字的词语中间加两个半格空格。"""
874
+ target = par.text[0] + " " + par.text[1]
875
+ nonempty = [r for r in par.runs if r.text]
876
+ keep_el = nonempty[0]._element if nonempty else None
877
+
878
+ def apply():
879
+ if keep_el is None:
880
+ run = par.add_run()
881
+ set_run(run, font, size, cfg["fonts"]["latin"], _NullReport(), where, cfg)
882
+ run.text = target
883
+ return
884
+ for r in par.runs:
885
+ r.text = target if r._element is keep_el else ""
886
+
887
+ report.want("text.twoCharCell", where, par.text, target, apply)
888
+
889
+
890
+ class _NullReport:
891
+ def want(self, *a, **k):
892
+ return False
893
+
894
+
895
+ def _set_or_make(parent, tag, attrs):
896
+ el = parent.find(qn(tag))
897
+ if el is None:
898
+ el = OxmlElement(tag)
899
+ parent.append(el)
900
+ for k, v in attrs.items():
901
+ el.set(qn(k), v)
902
+ return el
903
+
904
+
905
+ # ---------------------------------------------------------------- 页脚页码
906
+ def set_footer(section, report, cfg, fix=True):
907
+ footer = section.footer
908
+ if not fix:
909
+ has_field = "PAGE" in footer._element.xml
910
+ par0 = footer.paragraphs[0] if footer.paragraphs else None
911
+ align_ok = par0 is not None and par0.paragraph_format.alignment == CENTER
912
+ if not (has_field and align_ok):
913
+ report.want("footer.pageNumber", "footer",
914
+ "有" if has_field else "无页码域", "底端居中 — 1 —")
915
+ return
916
+ if footer.is_linked_to_previous:
917
+ footer.is_linked_to_previous = False
918
+ par = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
919
+ has_field = "PAGE" in par._element.xml or True
920
+ for child in list(par._p):
921
+ if child.tag != qn("w:pPr"):
922
+ par._p.remove(child)
923
+ pf = par.paragraph_format
924
+ pf.alignment = CENTER
925
+ if pf.first_line_indent not in (None, 0):
926
+ report.want("footer.firstLineIndent", "footer", pt_of(pf.first_line_indent), "无",
927
+ lambda: setattr(pf, "first_line_indent", None))
928
+
929
+ def mk_run(text=None):
930
+ r = par.add_run()
931
+ rPr = r._element.get_or_add_rPr()
932
+ rFonts = OxmlElement("w:rFonts")
933
+ rFonts.set(qn("w:ascii"), cfg["fonts"]["latin"])
934
+ rFonts.set(qn("w:hAnsi"), cfg["fonts"]["latin"])
935
+ rFonts.set(qn("w:eastAsia"), cfg["fonts"]["footer"])
936
+ rPr.append(rFonts)
937
+ r.font.size = Pt(cfg["sizes"]["footer"])
938
+ if text is not None:
939
+ r.text = text
940
+ return r
941
+
942
+ def add_field_run(fld_type=None, instr=None):
943
+ r = mk_run()
944
+ if instr is not None:
945
+ el = OxmlElement("w:instrText")
946
+ el.set(qn("xml:space"), "preserve")
947
+ el.text = instr
948
+ else:
949
+ el = OxmlElement("w:fldChar")
950
+ el.set(qn("w:fldCharType"), fld_type)
951
+ r._element.append(el)
952
+ return r
953
+
954
+ mk_run("— ")
955
+ add_field_run("begin")
956
+ add_field_run(instr=" PAGE ")
957
+ add_field_run("separate")
958
+ mk_run("1")
959
+ add_field_run("end")
960
+ mk_run(" —")
961
+ report.stats["footer"] = report.stats.get("footer", 0) + 1
962
+
963
+
964
+ # ---------------------------------------------------------------- 主流程
965
+ def _looks_like_attach_wrap(par, cfg):
966
+ """判断是否是附件条目被拆出来的续行:首行缩进正好等于 attachWrapIndentChars。"""
967
+ want = float(cfg["attachWrapIndentChars"])
968
+ cur = _get_chars(par, "w:firstLineChars")
969
+ return cur is not None and abs(cur - want) < 0.05
970
+
971
+
972
+ def classify(items, cfg):
973
+ """返回 [(kind, obj, text)],kinds: title/table_caption/h1/h2/h3/attach_tag/attach_line/
974
+ sign_org/sign_date/image/body/blank/tbl"""
975
+ out = []
976
+ paras = [(i, obj) for i, (t, obj) in enumerate(items) if t == "p"]
977
+ nonempty = [(i, p) for i, p in paras if p.text.strip()]
978
+ title_idx = set()
979
+ if nonempty:
980
+ i0 = nonempty[0][0]
981
+ title_idx.add(i0)
982
+ # 标题续行:紧跟其后、短、非标题模式、非编号
983
+ prev_len = len(nonempty[0][1].text.strip())
984
+ for i, p in nonempty[1:3]:
985
+ txt = p.text.strip()
986
+ if (i == i0 + 1 and prev_len <= 18 and len(txt) <= 40
987
+ and not txt.endswith(("。", ":", ",", ";", "!", "?", "、", ":"))
988
+ and not RE_H1.match(txt) and not RE_H2.match(txt)
989
+ and not RE_ATTACH_LINE.match(txt) and not RE_ATTACH_TAG.match(txt)):
990
+ title_idx.add(i)
991
+ else:
992
+ break
993
+
994
+ # 落款:末尾日期行
995
+ sign = {}
996
+ tail = [(i, p) for i, p in paras if p.text.strip()][-6:]
997
+ for pos, (i, p) in enumerate(tail):
998
+ if RE_DATE.search(p.text) and text_width(p.text.strip()) <= 26:
999
+ sign[i] = "sign_date"
1000
+ if pos > 0:
1001
+ prev_i, prev_p = tail[pos - 1]
1002
+ if (text_width(prev_p.text.strip()) <= 24 and not RE_DATE.search(prev_p.text)
1003
+ and not prev_p.text.strip().endswith(("。", ".", ",", ";"))):
1004
+ sign[prev_i] = "sign_org"
1005
+ break
1006
+
1007
+ for i, (t, obj) in enumerate(items):
1008
+ if t == "tbl":
1009
+ out.append(("tbl", obj, ""))
1010
+ continue
1011
+ p = obj
1012
+ txt = p.text.strip()
1013
+ if i in title_idx:
1014
+ out.append(("title", p, txt))
1015
+ elif i in sign:
1016
+ out.append((sign[i], p, txt))
1017
+ elif not txt:
1018
+ has_img = bool(p._element.findall(".//" + qn("w:drawing")))
1019
+ out.append(("image" if has_img else "blank", p, ""))
1020
+ elif RE_ATTACH_TAG.match(p.text or txt):
1021
+ out.append(("attach_tag", p, txt))
1022
+ elif RE_ATTACH_LINE.match(p.text or txt):
1023
+ out.append(("attach_line", p, txt))
1024
+ elif RE_H1.match(p.text):
1025
+ out.append(("h1", p, txt))
1026
+ elif RE_H2.match(p.text):
1027
+ out.append(("h2", p, txt))
1028
+ elif RE_H3.match(p.text):
1029
+ out.append(("h3", p, txt))
1030
+ elif p._element.findall(".//" + qn("w:drawing")):
1031
+ out.append(("image", p, txt))
1032
+ else:
1033
+ out.append(("body", p, txt))
1034
+ # 附件续行:紧接“附件:XXX”之后的附件条目,需与冒号后首字对齐
1035
+ in_attach = False
1036
+ for idx, (t, obj, txt) in enumerate(out):
1037
+ if t == "tbl":
1038
+ in_attach = False
1039
+ continue
1040
+ kind = t
1041
+ if kind == "attach_line":
1042
+ in_attach = True
1043
+ continue
1044
+ if not in_attach:
1045
+ continue
1046
+ if kind in BLANK_KINDS:
1047
+ continue # 空行不打断附件条目序列
1048
+ if kind in ("sign_org", "sign_date", "attach_tag", "title"):
1049
+ in_attach = False
1050
+ elif RE_ATTACH_ITEM.match(txt):
1051
+ out[idx] = ("attach_cont", obj, txt)
1052
+ elif _looks_like_attach_wrap(obj, cfg):
1053
+ # 我们自己拆出来的续行(首行缩进 6 字符)→ 保持附件归属
1054
+ out[idx] = ("attach_wrap", obj, txt)
1055
+ else:
1056
+ in_attach = False
1057
+ # 表标题:紧邻表格之前的段落
1058
+ for idx, (t, obj, txt) in enumerate(out):
1059
+ if t != "tbl":
1060
+ continue
1061
+ j = idx - 1
1062
+ while j >= 0 and out[j][0] in BLANK_KINDS:
1063
+ j -= 1
1064
+ if j >= 0:
1065
+ kind, prev, ptxt = out[j]
1066
+ if kind == "body" and ptxt and text_width(ptxt) <= 40 and not ptxt.endswith("。"):
1067
+ out[j] = ("table_caption", prev, ptxt)
1068
+ # 表标题与表格之间那一段:专用“0 行高、5 号字”空段,不能按普通空行排 29 磅
1069
+ for idx, (t, obj, txt) in enumerate(out):
1070
+ if t != "tbl":
1071
+ continue
1072
+ j = idx - 1
1073
+ while j >= 0 and out[j][0] in BLANK_KINDS + ("caption_spacer",):
1074
+ j -= 1
1075
+ if j >= 0 and out[j][0] == "table_caption":
1076
+ for k in range(j + 1, idx):
1077
+ out[k] = ("caption_spacer", out[k][1], "")
1078
+ # 空行也带格式:标题上空、多行标题之间、标题下固定那 1 行 → 沿用标题格式;
1079
+ # 其余空行沿用正文格式——和“手工回车”继承出来的结果一致。
1080
+ title_positions = [i for i, (t, _o, _x) in enumerate(out) if t == "title"]
1081
+ if title_positions:
1082
+ first_t, last_t = title_positions[0], title_positions[-1]
1083
+ title_side = set(range(0, first_t)) | set(range(first_t + 1, last_t))
1084
+ j = last_t + 1
1085
+ room = int(cfg["titleBlankAfterLines"])
1086
+ while j < len(out) and out[j][0] == "blank" and room > 0:
1087
+ title_side.add(j)
1088
+ room -= 1
1089
+ j += 1
1090
+ for idx in title_side:
1091
+ if out[idx][0] == "blank":
1092
+ out[idx] = ("blank_title", out[idx][1], "")
1093
+ return out
1094
+
1095
+
1096
+ def _spacer_size_val(cfg):
1097
+ return str(int(round(cfg["sizes"]["spacer"] * 2)))
1098
+
1099
+
1100
+ def _spacer_props_ok(p_el, cfg):
1101
+ pPr = p_el.find(qn("w:pPr"))
1102
+ if pPr is None:
1103
+ return False
1104
+ sp = pPr.find(qn("w:spacing"))
1105
+ if sp is None:
1106
+ return False
1107
+ if sp.get(qn("w:line")) != "0" or sp.get(qn("w:lineRule")) != "atLeast":
1108
+ return False
1109
+ if (sp.get(qn("w:before")) or "") != "0" or (sp.get(qn("w:after")) or "") != "0":
1110
+ return False
1111
+ rPr = pPr.find(qn("w:rPr"))
1112
+ sz = None if rPr is None else rPr.find(qn("w:sz"))
1113
+ return sz is not None and sz.get(qn("w:val")) == _spacer_size_val(cfg)
1114
+
1115
+
1116
+ def _write_spacer_props(p_el, cfg):
1117
+ """行高最小值 0 磅、字号 5 号、段前段后 0 —— 表标题与表格之间那一行。"""
1118
+ pPr = p_el.get_or_add_pPr()
1119
+ sp = pPr.get_or_add_spacing()
1120
+ for key in ("w:beforeLines", "w:afterLines",
1121
+ "w:beforeAutospacing", "w:afterAutospacing"):
1122
+ sp.attrib.pop(qn(key), None)
1123
+ sp.set(qn("w:line"), "0")
1124
+ sp.set(qn("w:lineRule"), "atLeast")
1125
+ sp.set(qn("w:before"), "0")
1126
+ sp.set(qn("w:after"), "0")
1127
+ rPr = pPr.find(qn("w:rPr"))
1128
+ if rPr is None:
1129
+ rPr = OxmlElement("w:rPr")
1130
+ pPr.append(rPr)
1131
+ val = _spacer_size_val(cfg)
1132
+ for tag in ("w:sz", "w:szCs"):
1133
+ el = rPr.find(qn(tag))
1134
+ if el is None:
1135
+ el = OxmlElement(tag)
1136
+ rPr.append(el)
1137
+ el.set(qn("w:val"), val)
1138
+
1139
+
1140
+ def format_table_caption_spacer(items, kinds, report, cfg):
1141
+ """表标题与表格之间插入一行(行高最小值 0,字号 5 号);已有则只校正属性。"""
1142
+ n = 0
1143
+ for idx, (t, obj) in enumerate(items):
1144
+ if t != "tbl":
1145
+ continue
1146
+ j = idx - 1
1147
+ while j >= 0 and kinds[j] in BLANK_KINDS + ("caption_spacer",):
1148
+ j -= 1
1149
+ if j < 0 or kinds[j] != "table_caption":
1150
+ continue
1151
+ n += 1
1152
+ prev_p = items[j][1]
1153
+ nxt = prev_p._p.getnext()
1154
+ if nxt is not None and nxt.tag == qn("w:p") and _is_blank_el(nxt):
1155
+ if not _spacer_props_ok(nxt, cfg):
1156
+ report.want("table.captionSpacer", "table%d" % n,
1157
+ "空行行高/字号不符", "行高最小值 0 磅、5 号字",
1158
+ lambda e=nxt: _write_spacer_props(e, cfg))
1159
+ continue
1160
+ spacer = OxmlElement("w:p")
1161
+ _write_spacer_props(spacer, cfg)
1162
+ prev_p._p.addnext(spacer)
1163
+ report.want("table.captionSpacer", "table%d" % n,
1164
+ "表标题与表格间无空行", "插入空行",
1165
+ lambda: None)
1166
+ report.stats["table.spacer"] += 1
1167
+
1168
+
1169
+ def _is_blank_el(el):
1170
+ if el.tag != qn("w:p"):
1171
+ return False
1172
+ if el.findall(".//" + qn("w:drawing")):
1173
+ return False
1174
+ return not "".join(el.itertext()).strip()
1175
+
1176
+
1177
+ def _count_blanks_before(par):
1178
+ n = 0
1179
+ prev = par._p.getprevious()
1180
+ while prev is not None and _is_blank_el(prev):
1181
+ n += 1
1182
+ prev = prev.getprevious()
1183
+ return n
1184
+
1185
+
1186
+ def _next_anchor_par(par):
1187
+ """其后第一个非空段落(跳过空段落;表格不作为锚点)。"""
1188
+ cur = par._p.getnext()
1189
+ while cur is not None:
1190
+ if cur.tag == qn("w:p") and not _is_blank_el(cur):
1191
+ return Paragraph(cur, par._parent)
1192
+ cur = cur.getnext()
1193
+ return None
1194
+
1195
+
1196
+ def _anchor_after_attach(seq, idx):
1197
+ """「附件:…」之后第一个非附件条目、非空行的段落。
1198
+
1199
+ 附件条目(attach_cont)属于同一段附件说明,不能把它们和“附件:”拆开插空行。
1200
+ """
1201
+ for j in range(idx + 1, len(seq)):
1202
+ kind, obj, _txt = seq[j]
1203
+ if kind in BLANK_KINDS + ("attach_cont", "attach_wrap"):
1204
+ continue
1205
+ if kind == "tbl":
1206
+ return None
1207
+ return obj
1208
+ return None
1209
+
1210
+
1211
+ def ensure_blank_lines(kinds, report, cfg):
1212
+ """段前段后一律 0 磅,空行改用独立空段落(整行)表达。
1213
+
1214
+ 按参考要求保证:标题上空 2 行、下空 1 行;附件说明前空 1 行、后空 2 行;
1215
+ 文末「附件1」标记前空 1 行;落款前空 2 行(仅 signature.enabled 时)。
1216
+ """
1217
+ plan = {}
1218
+
1219
+ def bump(par, want, label, blank_kind="blank"):
1220
+ if par is None or not want:
1221
+ return
1222
+ key = id(par._p)
1223
+ old = plan.get(key)
1224
+ if old is None or old[1] < want:
1225
+ plan[key] = (par, want, label, blank_kind)
1226
+
1227
+ titles = [obj for k, obj, _t in kinds if k == "title"]
1228
+ if titles:
1229
+ bump(titles[0], cfg["titleBlankBeforeLines"], "标题前", "blank_title")
1230
+ bump(_next_anchor_par(titles[-1]), cfg["titleBlankAfterLines"], "标题后", "blank_title")
1231
+ for idx, (k, obj, _t) in enumerate(kinds):
1232
+ if k == "attach_line":
1233
+ bump(obj, cfg["attachBlankBeforeLines"], "附件说明前")
1234
+ bump(_anchor_after_attach(kinds, idx), cfg["attachBlankAfterLines"], "附件说明后")
1235
+ elif k == "attach_tag":
1236
+ bump(_next_anchor_par(obj), cfg["attachTagBlankAfterLines"], "附件标记与附件标题之间")
1237
+ elif k == "sign_org" and cfg["signature"]["enabled"]:
1238
+ bump(obj, cfg["signature"]["blankLinesBefore"], "落款前")
1239
+
1240
+ touched = 0
1241
+ for par, want, label, blank_kind in plan.values():
1242
+ cur = _count_blanks_before(par)
1243
+ if cur == want:
1244
+ continue
1245
+ if cur < want:
1246
+ for _ in range(want - cur):
1247
+ _style_blank(par.insert_paragraph_before(), cfg, blank_kind)
1248
+ else:
1249
+ for _ in range(cur - want):
1250
+ prev = par._p.getprevious()
1251
+ if prev is None or not _is_blank_el(prev):
1252
+ break
1253
+ prev.getparent().remove(prev)
1254
+ report.want("doc.blankLines", "doc." + label,
1255
+ "%d 个空行" % cur, "%d 个空行" % want)
1256
+ touched += 1
1257
+ return touched
1258
+
1259
+
1260
+ def _collect_body(doc):
1261
+ body = doc.element.body
1262
+ items = []
1263
+ for child in list(body.iterchildren()):
1264
+ if child.tag == qn("w:p"):
1265
+ items.append(("p", Paragraph(child, doc)))
1266
+ elif child.tag == qn("w:tbl"):
1267
+ items.append(("tbl", Table(child, doc)))
1268
+ return items
1269
+
1270
+
1271
+ # --------------------------------------------------------------- 附件自动分段
1272
+ # “附件:1.……”这类条目往往长到要折行。公文做法是把它拆成真正的多个段落:
1273
+ # 第 1 段(“附件:1.……首行”)首行缩进 2 字符;
1274
+ # 每个折行出来的续行段落首行缩进 6 字符(“附件:”3 字 + “1.”2 字 + 半字),
1275
+ # 后续条目“2.……”首行缩进 5 字符。左/右/悬挂缩进一律 0,段前段后 0。
1276
+ #
1277
+ # 折行位置不靠字宽估算:把待测段落单独存成临时文档交给 Word/WPS 排版,用
1278
+ # Range.Information(wdFirstCharacterLineNumber) 读回每个字符落在第几行,
1279
+ # 按实测行边界拆段,因此和最终打印效果完全一致。
1280
+
1281
+ _WORD_MEASURE_PS = r"""
1282
+ $ErrorActionPreference = 'Stop'
1283
+ $src = '@SRC@'
1284
+ $out = '@OUT@'
1285
+ $app = $null
1286
+ $doc = $null
1287
+ try {
1288
+ $app = New-Object -ComObject Word.Application
1289
+ $app.Visible = $false
1290
+ $app.DisplayAlerts = 0
1291
+ $doc = $app.Documents.Open($src, $false, $true)
1292
+ $parts = New-Object System.Collections.Generic.List[string]
1293
+ $count = $doc.Paragraphs.Count
1294
+ for ($p = 1; $p -le $count; $p++) {
1295
+ $r = $doc.Paragraphs($p).Range
1296
+ $t = $r.Text -replace "`r", "" -replace "`a", ""
1297
+ $len = $t.Length
1298
+ if ($len -eq 0) { $parts.Add('[]'); continue }
1299
+ if ([int]$r.ComputeStatistics(1) -le 1) { $parts.Add('[[' + 0 + ',' + ($len - 1) + ']]'); continue }
1300
+ $segs = New-Object System.Collections.Generic.List[string]
1301
+ $prev = -1
1302
+ $start = 0
1303
+ for ($i = 0; $i -lt $len; $i++) {
1304
+ $ln = [int]$doc.Range($r.Start + $i, $r.Start + $i + 1).Information(10)
1305
+ if ($ln -ne $prev) {
1306
+ if ($prev -ne -1) { $segs.Add('[' + $start + ',' + ($i - 1) + ']') }
1307
+ $start = $i
1308
+ $prev = $ln
1309
+ }
1310
+ }
1311
+ $segs.Add('[' + $start + ',' + ($len - 1) + ']')
1312
+ $parts.Add('[' + ($segs -join ',') + ']')
1313
+ }
1314
+ [System.IO.File]::WriteAllText($out, '[' + ($parts -join ',') + ']', [System.Text.UTF8Encoding]::new($false))
1315
+ 'OK'
1316
+ } catch {
1317
+ 'ERR ' + $_.Exception.Message
1318
+ } finally {
1319
+ if ($doc) { try { $doc.Close($false) } catch {} }
1320
+ if ($app) { try { $app.Quit() } catch {} }
1321
+ }
1322
+ """
1323
+
1324
+
1325
+ def _powershell():
1326
+ for name in ("powershell.exe", "powershell", "pwsh"):
1327
+ found = shutil.which(name)
1328
+ if found:
1329
+ return found
1330
+ return None
1331
+
1332
+
1333
+ def _word_measure(path):
1334
+ """调用 Word/WPS 读回每段的行区间;不可用时返回 None。"""
1335
+ shell = _powershell()
1336
+ if not shell:
1337
+ return None
1338
+ fd, out_json = tempfile.mkstemp(suffix=".json")
1339
+ os.close(fd)
1340
+ script = _WORD_MEASURE_PS.replace("@SRC@", path).replace("@OUT@", out_json)
1341
+ enc = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
1342
+ try:
1343
+ proc = subprocess.run([shell, "-NoProfile", "-NonInteractive",
1344
+ "-EncodedCommand", enc],
1345
+ capture_output=True, timeout=180)
1346
+ head = (proc.stdout or b"").decode("utf-8", "replace").strip()
1347
+ if not head.startswith("OK"):
1348
+ return None
1349
+ return json.loads(open(out_json, encoding="utf-8").read())
1350
+ except Exception:
1351
+ return None
1352
+ finally:
1353
+ try:
1354
+ os.unlink(out_json)
1355
+ except OSError:
1356
+ pass
1357
+
1358
+
1359
+ def _sibling_pos(el):
1360
+ """元素在 body 里的位置(前面有几个元素兄弟)。lxml 代理对象不保证同一性,用 XPath 数最稳。"""
1361
+ return int(el.xpath("count(preceding-sibling::*)"))
1362
+
1363
+
1364
+ def _measure_attach_lines(doc, entries, wrap_chars, body_pt=16.0):
1365
+ """entries: [(body 位置, Paragraph, label, is_wrap)](已按位置升序);返回等长行区间列表。
1366
+
1367
+ 两种测量几何:
1368
+ * 起始段(`附件:1.` / `2.`):保持它自己的 firstLineChars,量出“首行写到哪换行”;
1369
+ * 续行段(已经拆出来的 wrap 段):把缩进临时设成 `leftChars = 6 字符`、firstLine 清零,
1370
+ 量成“整段 6 字符缩进”的均匀版式——拆出来的每一段都从 6 字符开始,只有这样量才准。
1371
+ """
1372
+ if not entries:
1373
+ return []
1374
+ tmpdir = tempfile.mkdtemp(prefix="docxfmt-measure-")
1375
+ src = os.path.join(tmpdir, "measure.docx")
1376
+ try:
1377
+ doc.save(src)
1378
+ probe = Document(src)
1379
+ keep = dict((pos, is_wrap) for pos, _p, _l, is_wrap in entries)
1380
+ body = probe.element.body
1381
+ cursor = 0
1382
+ for child in list(body.iterchildren()):
1383
+ if child.tag == qn("w:sectPr"):
1384
+ continue
1385
+ pos = cursor
1386
+ cursor += 1
1387
+ if pos not in keep:
1388
+ body.remove(child)
1389
+ continue
1390
+ if not keep[pos]:
1391
+ continue
1392
+ par = Paragraph(child, probe)
1393
+ ind = _get_ind(par, make=True)
1394
+ # 探测段落只用磅值左缩进:实测 `w:leftChars` 与 `w:left` 并存时 Word 会按
1395
+ # 别的方式解释(6 字符被当成 30 磅,折行点偏后 2 个字),只写磅值才准。
1396
+ ind.set(qn("w:left"), str(int(round(float(wrap_chars) * float(body_pt) * 20))))
1397
+ for name in ("w:leftChars", "w:firstLineChars", "w:firstLine",
1398
+ "w:hangingChars", "w:hanging"):
1399
+ if ind.get(qn(name)) is not None:
1400
+ del ind.attrib[qn(name)]
1401
+ probe.save(src)
1402
+ res = _word_measure(src)
1403
+ if res is None or len(res) != len(entries):
1404
+ return None
1405
+ return res
1406
+ finally:
1407
+ shutil.rmtree(tmpdir, ignore_errors=True)
1408
+
1409
+
1410
+ def _do_split_par(par, segs, cfg):
1411
+ """按给定文本切片把一个段落拆成多个段落,续行首行缩进 attachWrapIndentChars。"""
1412
+ p_el = par._p
1413
+ parent = p_el.getparent()
1414
+ runs = list(par.runs)
1415
+ spans = []
1416
+ pos = 0
1417
+ for seg in segs:
1418
+ spans.append((pos, pos + len(seg)))
1419
+ pos += len(seg)
1420
+ els = []
1421
+ for a, b in spans:
1422
+ el = copy.deepcopy(p_el)
1423
+ for child in list(el):
1424
+ if child.tag != qn("w:pPr"):
1425
+ el.remove(child)
1426
+ cursor = 0
1427
+ for r in runs:
1428
+ rtxt = r.text
1429
+ rs = cursor
1430
+ cursor += len(rtxt)
1431
+ lo, hi = max(rs, a), min(cursor, b)
1432
+ if hi <= lo:
1433
+ continue
1434
+ new_r = copy.deepcopy(r._r)
1435
+ for t in new_r.findall(qn("w:t")):
1436
+ new_r.remove(t)
1437
+ t = OxmlElement("w:t")
1438
+ t.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
1439
+ t.text = rtxt[lo - rs:hi - rs]
1440
+ new_r.append(t)
1441
+ el.append(new_r)
1442
+ els.append(el)
1443
+ anchor = p_el
1444
+ for el in els:
1445
+ anchor.addnext(el)
1446
+ anchor = el
1447
+ parent.remove(p_el)
1448
+ wrap_chars = float(cfg["attachWrapIndentChars"])
1449
+ body_pt = float(cfg["sizes"]["body"])
1450
+ for el in els[1:]:
1451
+ sub = Paragraph(el, par._parent)
1452
+ set_chars_indent(sub, "firstLine", wrap_chars, Pt(wrap_chars * body_pt))
1453
+
1454
+
1455
+ def split_attach_paragraphs(doc, report, cfg):
1456
+ """把超过一行的附件条目按 Word 实测折行点拆段;返回是否有改动。"""
1457
+ if not cfg["attachSplit"]["enabled"]:
1458
+ return False
1459
+ if cfg["attachSplit"]["mode"] != "word":
1460
+ return False # indent-only:只排 2/5 字符缩进,折行交给使用者手工处理
1461
+ kinds = classify(_collect_body(doc), cfg)
1462
+ targets = []
1463
+ for i, (kind, obj, _txt) in enumerate(kinds):
1464
+ if kind not in ("attach_line", "attach_cont", "attach_wrap"):
1465
+ continue
1466
+ style_par(obj, kind, report, "p%d" % i, cfg) # 先落缩进,测量才准
1467
+ # 版心宽 15.6cm ≈ 27.6 个三号汉字,按 6 字符缩进算也还有 21 字;
1468
+ # 短于此的条目不可能折行,不必启动 Word(省 3~6 秒)
1469
+ if len(obj.text) < int(cfg["attachSplit"]["minCharsToMeasure"]):
1470
+ continue
1471
+ targets.append((_sibling_pos(obj._p), obj, "p%d" % i, kind == "attach_wrap"))
1472
+ targets.sort(key=lambda t: t[0])
1473
+ if not targets:
1474
+ return False
1475
+ ranges = _measure_attach_lines(doc, targets, cfg["attachWrapIndentChars"],
1476
+ cfg["sizes"]["body"])
1477
+ if ranges is None:
1478
+ report.warn("附件自动分段不可用:本机没有能调用的 Word/WPS 排版引擎,"
1479
+ "已按“附件条目首行缩进 2/5 字符、左右悬挂 0”排版,折行请手工换行。")
1480
+ return False
1481
+ changed = False
1482
+ for (_pidx, par, label, is_wrap), rng in zip(targets, ranges):
1483
+ if not rng or len(rng) < 2:
1484
+ continue
1485
+ text = par.text
1486
+ if not text:
1487
+ continue
1488
+ if is_wrap:
1489
+ segs = [text[s:e + 1] for s, e in rng if 0 <= s <= e < len(text)]
1490
+ else:
1491
+ # 起始段只切第一处折行;剩下的尾巴留给下一轮按 6 字符缩进量
1492
+ cut = rng[0][1] + 1
1493
+ segs = [text[:cut], text[cut:]]
1494
+ if len(segs) < 2 or "".join(segs) != text or not all(segs):
1495
+ continue
1496
+ report.want("attach.split", label, "1 段 %d 字(自动折行)" % len(text),
1497
+ "%d 段(续行首行缩进 %g 字符)"
1498
+ % (len(segs), cfg["attachWrapIndentChars"]),
1499
+ (lambda p=par, s=segs: _do_split_par(p, s, cfg)))
1500
+ changed = True
1501
+ return changed
1502
+
1503
+
1504
+ def process(path, mode, cfg):
1505
+ t0 = time.time()
1506
+ fix = mode == "apply"
1507
+ doc = Document(path)
1508
+ report = Report(os.path.abspath(path), mode, fix)
1509
+
1510
+ for section in doc.sections:
1511
+ m = cfg["marginsCm"]
1512
+ for attr, key in (("top_margin", "top"), ("bottom_margin", "bottom"),
1513
+ ("left_margin", "left"), ("right_margin", "right")):
1514
+ cur = getattr(section, attr)
1515
+ want = Cm(m[key])
1516
+ if cur is None or abs(cur.cm - m[key]) > 0.02:
1517
+ report.want("page.margin." + key, "section", None if cur is None else round(cur.cm, 2), m[key],
1518
+ (lambda s=section, a=attr, w=want: setattr(s, a, w)))
1519
+ if cfg["pageNumber"]:
1520
+ set_footer(section, report, cfg, fix)
1521
+
1522
+ body = doc.element.body
1523
+ items = _collect_body(doc)
1524
+
1525
+ kinds = classify(items, cfg)
1526
+ if fix:
1527
+ if cfg["attachSplit"]["enabled"]:
1528
+ for _round in range(max(1, int(cfg["attachSplit"]["maxRounds"]))):
1529
+ if not split_attach_paragraphs(doc, report, cfg):
1530
+ break
1531
+ items = _collect_body(doc)
1532
+ kinds = classify(items, cfg)
1533
+ ensure_blank_lines(kinds, report, cfg)
1534
+ format_table_caption_spacer(items, [k for k, _o, _t in kinds], report, cfg)
1535
+ items = _collect_body(doc)
1536
+ kinds = classify(items, cfg)
1537
+
1538
+ if not fix and cfg["attachSplit"]["enabled"]:
1539
+ split_attach_paragraphs(doc, report, cfg)
1540
+
1541
+ title_positions = [i for i, (k, _o, _t) in enumerate(kinds) if k == "title"]
1542
+ if title_positions:
1543
+ if len(title_positions) == 1:
1544
+ kinds[title_positions[0]] = ("title_only",) + tuple(kinds[title_positions[0]][1:])
1545
+ else:
1546
+ for pos, idx in enumerate(title_positions):
1547
+ name = "title_first" if pos == 0 else ("title_last" if pos == len(title_positions) - 1 else "title_mid")
1548
+ kinds[idx] = (name,) + tuple(kinds[idx][1:])
1549
+ table_idx = 0
1550
+ for i, (kind, obj, txt) in enumerate(kinds):
1551
+ label = "p%d" % i
1552
+ if kind == "tbl":
1553
+ style_table(obj, report, "t%d" % table_idx, cfg)
1554
+ table_idx += 1
1555
+ continue
1556
+ if kind in BLANK_KINDS:
1557
+ style_par(obj, kind, report, label, cfg)
1558
+ continue
1559
+ if kind in ("body", "h1", "h2", "h3", "attach_line", "attach_cont",
1560
+ "attach_wrap"):
1561
+ normalize_text(obj, report, label, cfg)
1562
+ style_par(obj, kind, report, label, cfg)
1563
+ if kind == "sign_org" and cfg["signature"]["enabled"]:
1564
+ _pad_signature(obj, report, label, cfg, kinds, i)
1565
+ if kind == "sign_date" and cfg["signature"]["enabled"]:
1566
+ _pad_date(obj, report, label, cfg)
1567
+
1568
+ if not fix:
1569
+ # check 模式:只统计表标题与表格之间是否缺空行,内存里插入不写回
1570
+ format_table_caption_spacer(items, [k for k, _o, _t in kinds], report, cfg)
1571
+
1572
+ changed = report.total > 0
1573
+ if fix and changed:
1574
+ tmp = path + ".tmp.docx"
1575
+ doc.save(tmp)
1576
+ os.replace(tmp, path)
1577
+ out = report.as_dict(changed)
1578
+ out["writeBack"] = bool(fix and changed)
1579
+ out["elapsedMs"] = int((time.time() - t0) * 1000)
1580
+ return out
1581
+
1582
+
1583
+ def _pad_date(par, report, label, cfg):
1584
+ txt = par.text
1585
+ pad = cfg["signature"]["datePadSpaces"]
1586
+ want = txt.rstrip("\u3000 ") + "\u3000" * pad
1587
+ if par.runs and not txt.endswith("\u3000" * pad):
1588
+ last = par.runs[-1]
1589
+ report.want("signature.datePad", label, txt, want,
1590
+ (lambda r=last, w=want, cur=txt: setattr(r, "text", r.text + "\u3000" * pad)))
1591
+
1592
+
1593
+ def _pad_signature(par, report, label, cfg, kinds, i):
1594
+ """按参考样例给署名补尾部全角空格:无需盖章→与日期左边缘对齐;需盖章→居中对齐。"""
1595
+ date_txt = None
1596
+ for j in range(i + 1, len(kinds)):
1597
+ if kinds[j][0] == "sign_date":
1598
+ date_txt = kinds[j][2]
1599
+ break
1600
+ if not date_txt:
1601
+ return
1602
+ need = text_width(date_txt.rstrip("\u3000 ")) + cfg["signature"]["datePadSpaces"]
1603
+ mine = text_width(par.text.rstrip("\u3000 "))
1604
+ if cfg["signature"]["seal"]:
1605
+ pad = int(round((need - mine) / 2))
1606
+ else:
1607
+ pad = int(round(need - mine))
1608
+ pad = max(cfg["signature"]["datePadSpaces"], pad)
1609
+ want = par.text.rstrip("\u3000 ") + "\u3000" * pad
1610
+ if par.runs and par.text != want:
1611
+ last = par.runs[-1]
1612
+ cur = par.text
1613
+ report.want("signature.orgPad", label, cur.strip("\u3000"), want.strip("\u3000"),
1614
+ (lambda r=last, d=pad, c=cur: setattr(r, "text", c.rstrip("\u3000 ") + "\u3000" * d)))
1615
+
1616
+
1617
+ def doc_text(path):
1618
+ doc = Document(path)
1619
+ parts = [p.text for p in doc.paragraphs]
1620
+ for tbl in doc.tables:
1621
+ for row in tbl.rows:
1622
+ for cell in row.cells:
1623
+ parts.append(cell.text)
1624
+ return "\n".join(parts)
1625
+
1626
+
1627
+ def skip_reason(path, cfg):
1628
+ """白名单:正文命中 skipContentKeywords(默认「实验报告」)时整篇跳过。"""
1629
+ kws = cfg.get("skipContentKeywords") or []
1630
+ if not kws:
1631
+ return None
1632
+ try:
1633
+ text = doc_text(path)
1634
+ except Exception:
1635
+ return None
1636
+ for kw in kws:
1637
+ if kw and kw in text:
1638
+ return kw
1639
+ return None
1640
+
1641
+
1642
+ def _collect(paths, recursive):
1643
+ out = []
1644
+ for p in paths:
1645
+ if os.path.isdir(p):
1646
+ if recursive:
1647
+ for root, _dirs, files in os.walk(p):
1648
+ for f in sorted(files):
1649
+ if f.lower().endswith(".docx") and not f.startswith("~$"):
1650
+ out.append(os.path.join(root, f))
1651
+ else:
1652
+ for f in sorted(os.listdir(p)):
1653
+ fp = os.path.join(p, f)
1654
+ if os.path.isfile(fp) and f.lower().endswith(".docx") and not f.startswith("~$"):
1655
+ out.append(fp)
1656
+ else:
1657
+ out.append(p)
1658
+ return out
1659
+
1660
+
1661
+ def main(argv=None):
1662
+ ap = argparse.ArgumentParser(description="docx 公文格式规范化")
1663
+ ap.add_argument("path", nargs="+")
1664
+ ap.add_argument("--mode", choices=["apply", "check"], default="apply")
1665
+ ap.add_argument("--recursive", action="store_true")
1666
+ ap.add_argument("--json", action="store_true")
1667
+ ap.add_argument("--config", default=None, help="JSON 配置字符串或 .json 文件路径")
1668
+ args = ap.parse_args(argv)
1669
+
1670
+ cfg = DEFAULTS
1671
+ if args.config:
1672
+ raw = args.config
1673
+ if os.path.isfile(raw):
1674
+ with open(raw, "r", encoding="utf-8") as fh:
1675
+ raw = fh.read()
1676
+ cfg = merge_config(json.loads(raw))
1677
+
1678
+ results = []
1679
+ failed = False
1680
+ violations = 0
1681
+ for path in _collect(args.path, args.recursive):
1682
+ if not path.lower().endswith(".docx"):
1683
+ continue
1684
+ reason = skip_reason(path, cfg)
1685
+ if reason:
1686
+ results.append({
1687
+ "ok": True, "file": os.path.abspath(path), "mode": args.mode,
1688
+ "skipped": True, "skipReason": "正文含白名单关键词「%s」" % reason,
1689
+ "changed": False, "violations": 0, "rules": {}, "stats": {}, "warnings": [],
1690
+ })
1691
+ continue
1692
+ try:
1693
+ res = process(path, args.mode, cfg)
1694
+ except Exception as exc:
1695
+ import traceback
1696
+ res = {"ok": False, "file": os.path.abspath(path), "mode": args.mode,
1697
+ "error": "%s: %s" % (type(exc).__name__, exc),
1698
+ "trace": traceback.format_exc()[-1200:]}
1699
+ failed = True
1700
+ violations += res.get("violations", 0) or 0
1701
+ results.append(res)
1702
+
1703
+ payload = results[0] if len(results) == 1 else {"ok": not failed, "files": results,
1704
+ "count": len(results), "violations": violations}
1705
+ if args.json:
1706
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
1707
+ else:
1708
+ for res in (results if len(results) > 1 else [results[0]]):
1709
+ if not res.get("ok"):
1710
+ print("[失败] %s\n %s" % (res.get("file"), res.get("error")))
1711
+ continue
1712
+ if res.get("skipped"):
1713
+ print("[已跳过] %s (%s)" % (res.get("file"), res.get("skipReason")))
1714
+ continue
1715
+ tag = "已规范化" if res.get("writeBack") else ("无需修改" if not res["changed"] else "存在偏差")
1716
+ print("[%s] %s (偏差 %d 处, %d ms)" % (tag, res["file"], res["violations"], res.get("elapsedMs", 0)))
1717
+ for rule, info in res["rules"].items():
1718
+ smp = info["samples"][0]
1719
+ print(" - %s ×%d 例: %s: %s → %s" % (rule, info["count"], smp["where"],
1720
+ smp["current"], smp["expected"]))
1721
+ for w in res["warnings"]:
1722
+ print(" ! " + w)
1723
+ if failed:
1724
+ return 1
1725
+ if args.mode == "check" and violations:
1726
+ return 2
1727
+ return 0
1728
+
1729
+
1730
+ if __name__ == "__main__":
1731
+ sys.exit(main())