dsh-docx-format 1.1.1 → 1.2.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/README.md +132 -10
- package/cordis.patch.yml +18 -7
- package/index.js +222 -52
- package/lib/docxfmt.py +460 -35
- package/locale/en.json +5 -4
- package/locale/zh.json +5 -4
- package/package.json +52 -52
package/lib/docxfmt.py
CHANGED
|
@@ -73,7 +73,11 @@ DEFAULTS = {
|
|
|
73
73
|
"spaceAfterPt": 0,
|
|
74
74
|
"marginsCm": {"top": 3.6, "bottom": 3.0, "left": 2.7, "right": 2.7},
|
|
75
75
|
"titleBlankBeforeLines": 2,
|
|
76
|
+
# 标题后的空行从“副标题”算起:主标题与副标题之间不留空行
|
|
76
77
|
"titleBlankAfterLines": 1,
|
|
78
|
+
# 副标题:紧跟主标题(中间最多隔一个空段)的另一段短文本,仿宋三号居中
|
|
79
|
+
"subtitle": {"enabled": True, "mainMaxChars": 18, "maxChars": 40,
|
|
80
|
+
"gapTolerance": 1},
|
|
77
81
|
"attachBlankBeforeLines": 1,
|
|
78
82
|
"attachBlankAfterLines": 2,
|
|
79
83
|
# 文件中的“附件1”标记:下与附件标题空出一行(参考要求未规定其上要空行)
|
|
@@ -86,8 +90,39 @@ DEFAULTS = {
|
|
|
86
90
|
# 控制(未明确要求署名/日期时不生成落款文字)。
|
|
87
91
|
"signature": {"enabled": True, "seal": False, "datePadSpaces": 2,
|
|
88
92
|
"blankLinesBefore": 2},
|
|
89
|
-
#
|
|
90
|
-
|
|
93
|
+
# 字体档:standard 用常见简体字体,strict 用 GBK/GB2312 全字库(更接近
|
|
94
|
+
# GB/T 9704-2012 的“标准字体”,缺字更少)。
|
|
95
|
+
# strictFonts=true → 一律 strict
|
|
96
|
+
# 本条请求含 strictKeywords → strict
|
|
97
|
+
# 都不满足 → standard
|
|
98
|
+
"fontProfile": "standard",
|
|
99
|
+
"strictFonts": False,
|
|
100
|
+
"strictKeywords": ["严格公文格式", "严格公文"],
|
|
101
|
+
# strict 档在 standard 之上覆盖这些位置
|
|
102
|
+
"fontsStrict": {
|
|
103
|
+
"title": "方正小标宋_GBK",
|
|
104
|
+
"tableCaption": "方正小标宋_GBK",
|
|
105
|
+
"body": "仿宋_GB2312",
|
|
106
|
+
"h3": "仿宋_GB2312",
|
|
107
|
+
"tableBody": "仿宋_GB2312",
|
|
108
|
+
"h1": "方正黑体_GBK",
|
|
109
|
+
"tableHead": "方正黑体_GBK",
|
|
110
|
+
"h2": "楷体_GB2312",
|
|
111
|
+
"footer": "宋体",
|
|
112
|
+
},
|
|
113
|
+
# 字体检测与安装。检测只读注册表/字体目录,**从不联网**;
|
|
114
|
+
# 下载必须拿到 consent token(或 CLI --yes)。
|
|
115
|
+
# autoInstall: ask 缺字体时返回 consentRequired,由对话里问用户
|
|
116
|
+
# off 只报告,从不下载
|
|
117
|
+
"fontCheck": {
|
|
118
|
+
"enabled": True,
|
|
119
|
+
"onRun": True,
|
|
120
|
+
"aliases": {},
|
|
121
|
+
"presets": {},
|
|
122
|
+
"sources": [],
|
|
123
|
+
"autoInstall": "ask",
|
|
124
|
+
"installDir": "",
|
|
125
|
+
},
|
|
91
126
|
"normalize": {
|
|
92
127
|
"stripLeadingSpace": True,
|
|
93
128
|
"fullwidthNumberDot": True,
|
|
@@ -96,6 +131,11 @@ DEFAULTS = {
|
|
|
96
131
|
"boldOff": True,
|
|
97
132
|
# 中文内容里英文前后不留空格(「使用AI工具」);纯英文语句的空格保持原样
|
|
98
133
|
"cjkLatinSpace": True,
|
|
134
|
+
# 中文里的引号用“”‘’,不用「」『』
|
|
135
|
+
"quotePair": True,
|
|
136
|
+
# 「换行和分页」里的 6 个开关(孤行控制/与下段同页/段中不分页/段前分页/
|
|
137
|
+
# 取消行号/取消断字)一律不启用
|
|
138
|
+
"paginationOff": True,
|
|
99
139
|
},
|
|
100
140
|
}
|
|
101
141
|
|
|
@@ -106,6 +146,8 @@ RE_ATTACH_TAG = re.compile(r"^[ \u3000]*附件\s*\d{0,2}\s*$")
|
|
|
106
146
|
RE_ATTACH_LINE = re.compile(r"^[ \u3000]*附件\s*[::]")
|
|
107
147
|
RE_ATTACH_ITEM = re.compile(r"^[((]?\d{1,2}\s*[..、))]")
|
|
108
148
|
RE_DATE = re.compile(r"\d{4}\s*年\s*\d{1,2}\s*月\s*\d{1,2}\s*日")
|
|
149
|
+
# 副标题常以破折号开头:「——在XX会议上的讲话」
|
|
150
|
+
RE_DASH_LEAD = re.compile(r"^[—–]{1,2}|^-{1,2}\s")
|
|
109
151
|
RE_LEAD_SPACE = re.compile(r"^[\u3000 ]+")
|
|
110
152
|
RE_FULLWIDTH_SPACE = "\u3000"
|
|
111
153
|
|
|
@@ -504,6 +546,10 @@ def style_par(par, kind, report, label, cfg):
|
|
|
504
546
|
if kind in ("title", "title_first", "title_mid", "title_last", "title_only"):
|
|
505
547
|
want_align, want_font, want_size = CENTER, fonts["title"], sizes["title"]
|
|
506
548
|
want_first_chars = None
|
|
549
|
+
elif kind == "subtitle":
|
|
550
|
+
# 副标题:仿宋三号、居中、无首行缩进,行距仍固定 29 磅
|
|
551
|
+
want_align, want_font, want_size = CENTER, fonts["body"], sizes["body"]
|
|
552
|
+
want_first_chars = None
|
|
507
553
|
elif kind == "table_caption":
|
|
508
554
|
want_align, want_font, want_size = CENTER, fonts["tableCaption"], sizes["title"]
|
|
509
555
|
want_first_chars = None
|
|
@@ -807,6 +853,80 @@ def drop_char_ranges(runs, gaps):
|
|
|
807
853
|
run.text = kept
|
|
808
854
|
|
|
809
855
|
|
|
856
|
+
# 「换行和分页」里那 6 个开关对应的 OOXML 属性,顺序即 pPr 的 schema 顺序
|
|
857
|
+
PAGINATION_ORDER = ("w:keepNext", "w:keepLines", "w:pageBreakBefore", "w:framePr",
|
|
858
|
+
"w:widowControl", "w:numPr", "w:suppressLineNumbers", "w:pBdr",
|
|
859
|
+
"w:shd", "w:tabs", "w:suppressAutoHyphens", "w:kinsoku",
|
|
860
|
+
"w:wordWrap", "w:overflowPunct", "w:topLinePunct",
|
|
861
|
+
"w:autoSpaceDE", "w:autoSpaceDN", "w:bidi", "w:adjustRightInd",
|
|
862
|
+
"w:snapToGrid", "w:spacing", "w:ind", "w:contextualSpacing",
|
|
863
|
+
"w:mirrorIndents", "w:suppressOverlap", "w:jc",
|
|
864
|
+
"w:textDirection", "w:textAlignment", "w:textboxTightWrap",
|
|
865
|
+
"w:outlineLvl", "w:divId", "w:cnfStyle", "w:rPr", "w:sectPr",
|
|
866
|
+
"w:pPrChange")
|
|
867
|
+
PAGINATION_TAGS = ("w:widowControl", "w:keepNext", "w:keepLines",
|
|
868
|
+
"w:pageBreakBefore", "w:suppressLineNumbers",
|
|
869
|
+
"w:suppressAutoHyphens")
|
|
870
|
+
PAGINATION_LABELS = {"w:widowControl": "孤行控制", "w:keepNext": "与下段同页",
|
|
871
|
+
"w:keepLines": "段中不分页", "w:pageBreakBefore": "段前分页",
|
|
872
|
+
"w:suppressLineNumbers": "取消行号",
|
|
873
|
+
"w:suppressAutoHyphens": "取消断字"}
|
|
874
|
+
|
|
875
|
+
# 中文引号:不用「」『』,用“”‘’
|
|
876
|
+
QUOTE_MAP = {"「": "“", "」": "”", "『": "‘", "』": "’"}
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
def _pagination_successors(tag):
|
|
880
|
+
return PAGINATION_ORDER[PAGINATION_ORDER.index(tag) + 1:]
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def clear_pagination(par, report, label):
|
|
884
|
+
"""段落「换行和分页」里的 6 个开关一律不启用(对话框里复选框全部留空)。
|
|
885
|
+
|
|
886
|
+
这 6 项都不在 python-docx 的 API 里,直接写 pPr:
|
|
887
|
+
孤行控制 / 与下段同页 / 段中不分页 / 段前分页 / 取消行号 / 取消断字。
|
|
888
|
+
widowControl 的 Word 默认值是“开”,所以必须显式写 0,不能靠删除元素。
|
|
889
|
+
"""
|
|
890
|
+
pPr = par._p.get_or_add_pPr()
|
|
891
|
+
for tag in PAGINATION_TAGS:
|
|
892
|
+
el = pPr.find(qn(tag))
|
|
893
|
+
val = None if el is None else (el.get(qn("w:val")) or "1")
|
|
894
|
+
if el is not None and str(val).lower() in ("0", "false", "off"):
|
|
895
|
+
continue
|
|
896
|
+
|
|
897
|
+
def apply(t=tag, e=el, p=pPr):
|
|
898
|
+
node = e
|
|
899
|
+
if node is None:
|
|
900
|
+
node = OxmlElement(t)
|
|
901
|
+
try:
|
|
902
|
+
p.insert_element_before(node, *_pagination_successors(t))
|
|
903
|
+
except Exception:
|
|
904
|
+
p.append(node)
|
|
905
|
+
node.set(qn("w:val"), "0")
|
|
906
|
+
|
|
907
|
+
report.want("par.pagination." + tag.split(":")[1], label,
|
|
908
|
+
"%s:启用" % PAGINATION_LABELS[tag],
|
|
909
|
+
"%s:不启用" % PAGINATION_LABELS[tag], apply)
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
def quote_normalize(par, report, label):
|
|
913
|
+
"""中文里的引号写成“”‘’,不写「」『』。"""
|
|
914
|
+
for idx, run in enumerate(par.runs):
|
|
915
|
+
t = run.text or ""
|
|
916
|
+
if not any(ch in QUOTE_MAP for ch in t):
|
|
917
|
+
continue
|
|
918
|
+
new = "".join(QUOTE_MAP.get(ch, ch) for ch in t)
|
|
919
|
+
report.want("text.quote", "%s#r%d" % (label, idx),
|
|
920
|
+
"使用「」『』", "使用“”‘’",
|
|
921
|
+
(lambda r=run, v=new: setattr(r, "text", v)))
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def _iter_all_paragraphs(doc):
|
|
925
|
+
"""文档里所有段落(正文 + 表格单元格 + 文本框),每个 XML 节点只回一次。"""
|
|
926
|
+
for node in doc.element.body.iter(qn("w:p")):
|
|
927
|
+
yield Paragraph(node, doc)
|
|
928
|
+
|
|
929
|
+
|
|
810
930
|
def auto_space_off(par, report, label):
|
|
811
931
|
"""关闭 Word 的“自动调整中西文间距”(w:autoSpaceDE / w:autoSpaceDN)。
|
|
812
932
|
|
|
@@ -831,12 +951,32 @@ def auto_space_off(par, report, label):
|
|
|
831
951
|
"开启(Word 自动在中英文之间加间距)", "关闭(autoSpaceDE/DN=0)", apply)
|
|
832
952
|
|
|
833
953
|
|
|
834
|
-
def
|
|
954
|
+
def _normalize_cjk_latin(par, report, label, cfg):
|
|
955
|
+
"""中文文段里英文词前后不留空格(「使用AI工具」);纯英文语句不动。"""
|
|
956
|
+
if not cfg["normalize"].get("cjkLatinSpace", True):
|
|
957
|
+
return
|
|
958
|
+
runs = par.runs
|
|
959
|
+
if not runs:
|
|
960
|
+
return
|
|
961
|
+
joined = "".join(r.text for r in runs)
|
|
962
|
+
gaps = cjk_latin_gaps(joined)
|
|
963
|
+
if gaps:
|
|
964
|
+
report.want("text.cjkLatinSpace", label,
|
|
965
|
+
"中文与英文之间夹着空白(共 %d 处)" % len(gaps),
|
|
966
|
+
"中文内英文前后不加空格(如「使用AI工具」)",
|
|
967
|
+
(lambda rs=runs, gs=gaps: drop_char_ranges(rs, gs)))
|
|
968
|
+
|
|
969
|
+
|
|
970
|
+
def normalize_text(par, report, label, cfg, light=False):
|
|
835
971
|
p = par
|
|
836
972
|
text = p.text
|
|
837
973
|
if not text:
|
|
838
974
|
return
|
|
839
975
|
n = cfg["normalize"]
|
|
976
|
+
if light:
|
|
977
|
+
# 轻量模式:只做与版式无关的两件事(中英之间不留空格、引号用“”)
|
|
978
|
+
_normalize_cjk_latin(p, report, label, cfg)
|
|
979
|
+
return
|
|
840
980
|
if n["stripLeadingSpace"] and RE_LEAD_SPACE.match(text):
|
|
841
981
|
stripped = text.lstrip("\u3000 ")
|
|
842
982
|
if stripped and p.runs:
|
|
@@ -865,14 +1005,7 @@ def normalize_text(par, report, label, cfg):
|
|
|
865
1005
|
(lambda r=run, v=new: setattr(r, "text", v)))
|
|
866
1006
|
break
|
|
867
1007
|
if n.get("cjkLatinSpace", True):
|
|
868
|
-
|
|
869
|
-
joined = "".join(r.text for r in runs)
|
|
870
|
-
gaps = cjk_latin_gaps(joined)
|
|
871
|
-
if gaps:
|
|
872
|
-
report.want("text.cjkLatinSpace", label,
|
|
873
|
-
"中文与英文之间夹着空白(共 %d 处)" % len(gaps),
|
|
874
|
-
"中文内英文前后不加空格(如「使用AI工具」)",
|
|
875
|
-
(lambda rs=runs, gs=gaps: drop_char_ranges(rs, gs)))
|
|
1008
|
+
_normalize_cjk_latin(p, report, label, cfg)
|
|
876
1009
|
|
|
877
1010
|
|
|
878
1011
|
# ---------------------------------------------------------------- 表格
|
|
@@ -1097,27 +1230,47 @@ def _looks_like_attach_wrap(par, cfg):
|
|
|
1097
1230
|
return cur is not None and abs(cur - want) < 0.05
|
|
1098
1231
|
|
|
1099
1232
|
|
|
1233
|
+
def _gap_all_blank(items, a, b):
|
|
1234
|
+
"""items[a] 与 items[b] 之间(不含两端)是否全是空段落。"""
|
|
1235
|
+
for k in range(a + 1, b):
|
|
1236
|
+
t, obj = items[k]
|
|
1237
|
+
if t != "p" or (obj.text or "").strip():
|
|
1238
|
+
return False
|
|
1239
|
+
return True
|
|
1240
|
+
|
|
1241
|
+
|
|
1100
1242
|
def classify(items, cfg):
|
|
1101
1243
|
"""返回 [(kind, obj, text)],kinds: title/table_caption/h1/h2/h3/attach_tag/attach_line/
|
|
1102
1244
|
sign_org/sign_date/image/body/blank/tbl"""
|
|
1103
1245
|
out = []
|
|
1104
1246
|
paras = [(i, obj) for i, (t, obj) in enumerate(items) if t == "p"]
|
|
1105
1247
|
nonempty = [(i, p) for i, p in paras if p.text.strip()]
|
|
1106
|
-
|
|
1248
|
+
title_map = {}
|
|
1107
1249
|
if nonempty:
|
|
1108
1250
|
i0 = nonempty[0][0]
|
|
1109
|
-
|
|
1110
|
-
#
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1251
|
+
title_map[i0] = "title"
|
|
1252
|
+
# 副标题:紧跟主标题(中间最多隔 gapTolerance 个空段)的另一段短文本
|
|
1253
|
+
sub = cfg.get("subtitle") or {}
|
|
1254
|
+
if sub.get("enabled", True):
|
|
1255
|
+
tol = max(0, int(sub.get("gapTolerance", 1)))
|
|
1256
|
+
main_max = int(sub.get("mainMaxChars", 18))
|
|
1257
|
+
sub_max = int(sub.get("maxChars", 40))
|
|
1258
|
+
prev_len = len(nonempty[0][1].text.strip())
|
|
1259
|
+
for i, p in nonempty[1:3]:
|
|
1260
|
+
txt = p.text.strip()
|
|
1261
|
+
gap_ok = (i - i0 - 1) <= tol and _gap_all_blank(items, i0, i)
|
|
1262
|
+
# 破折号开头基本就是副标题;否则要求主标题够短,避免把正文首段吃进来
|
|
1263
|
+
dash_lead = bool(RE_DASH_LEAD.match(txt))
|
|
1264
|
+
if (gap_ok and len(txt) <= sub_max
|
|
1265
|
+
and (dash_lead or prev_len <= main_max)
|
|
1266
|
+
and not txt.endswith(("。", ":", ",", ";", "!", "?", "、", ":"))
|
|
1267
|
+
and not RE_H1.match(txt) and not RE_H2.match(txt)
|
|
1268
|
+
and not RE_ATTACH_LINE.match(txt) and not RE_ATTACH_TAG.match(txt)
|
|
1269
|
+
and not RE_DATE.search(txt)):
|
|
1270
|
+
title_map[i] = "subtitle"
|
|
1271
|
+
prev_len = len(txt)
|
|
1272
|
+
else:
|
|
1273
|
+
break
|
|
1121
1274
|
|
|
1122
1275
|
# 落款:末尾日期行
|
|
1123
1276
|
sign = {}
|
|
@@ -1138,8 +1291,8 @@ def classify(items, cfg):
|
|
|
1138
1291
|
continue
|
|
1139
1292
|
p = obj
|
|
1140
1293
|
txt = p.text.strip()
|
|
1141
|
-
if i in
|
|
1142
|
-
out.append((
|
|
1294
|
+
if i in title_map:
|
|
1295
|
+
out.append((title_map[i], p, txt))
|
|
1143
1296
|
elif i in sign:
|
|
1144
1297
|
out.append((sign[i], p, txt))
|
|
1145
1298
|
elif not txt:
|
|
@@ -1205,7 +1358,7 @@ def classify(items, cfg):
|
|
|
1205
1358
|
out[k] = ("caption_spacer", out[k][1], "")
|
|
1206
1359
|
# 空行也带格式:标题上空、多行标题之间、标题下固定那 1 行 → 沿用标题格式;
|
|
1207
1360
|
# 其余空行沿用正文格式——和“手工回车”继承出来的结果一致。
|
|
1208
|
-
title_positions = [i for i, (t, _o, _x) in enumerate(out) if t
|
|
1361
|
+
title_positions = [i for i, (t, _o, _x) in enumerate(out) if t in ("title", "subtitle")]
|
|
1209
1362
|
if title_positions:
|
|
1210
1363
|
first_t, last_t = title_positions[0], title_positions[-1]
|
|
1211
1364
|
title_side = set(range(0, first_t)) | set(range(first_t + 1, last_t))
|
|
@@ -1352,7 +1505,7 @@ def ensure_blank_lines(kinds, report, cfg):
|
|
|
1352
1505
|
if old is None or old[1] < want:
|
|
1353
1506
|
plan[key] = (par, want, label, blank_kind)
|
|
1354
1507
|
|
|
1355
|
-
titles = [obj for k, obj, _t in kinds if k
|
|
1508
|
+
titles = [obj for k, obj, _t in kinds if k in ("title", "subtitle")]
|
|
1356
1509
|
if titles:
|
|
1357
1510
|
bump(titles[0], cfg["titleBlankBeforeLines"], "标题前", "blank_title")
|
|
1358
1511
|
bump(_next_anchor_par(titles[-1]), cfg["titleBlankAfterLines"], "标题后", "blank_title")
|
|
@@ -1629,12 +1782,127 @@ def split_attach_paragraphs(doc, report, cfg):
|
|
|
1629
1782
|
return changed
|
|
1630
1783
|
|
|
1631
1784
|
|
|
1632
|
-
def
|
|
1785
|
+
def _save(doc, path):
|
|
1786
|
+
tmp = path + ".tmp.docx"
|
|
1787
|
+
doc.save(tmp)
|
|
1788
|
+
os.replace(tmp, path)
|
|
1789
|
+
|
|
1790
|
+
|
|
1791
|
+
def light_pass(doc, report, cfg):
|
|
1792
|
+
"""与版式无关的全局规范化:不论是否套用公文版式都执行。
|
|
1793
|
+
|
|
1794
|
+
- 「换行和分页」里 6 个开关一律不启用
|
|
1795
|
+
- 中文里不写「」『』,改“”‘’
|
|
1796
|
+
- 中文文段里的英文前后不留空格(并关闭 Word 自动中西文间距)
|
|
1797
|
+
"""
|
|
1798
|
+
n = cfg["normalize"]
|
|
1799
|
+
pagination = n.get("paginationOff", True)
|
|
1800
|
+
quote = n.get("quotePair", True)
|
|
1801
|
+
for i, par in enumerate(_iter_all_paragraphs(doc)):
|
|
1802
|
+
label = "l%d" % i
|
|
1803
|
+
if pagination:
|
|
1804
|
+
clear_pagination(par, report, label)
|
|
1805
|
+
if quote:
|
|
1806
|
+
quote_normalize(par, report, label)
|
|
1807
|
+
_normalize_cjk_latin(par, report, label, cfg)
|
|
1808
|
+
auto_space_off(par, report, label)
|
|
1809
|
+
return report
|
|
1810
|
+
|
|
1811
|
+
|
|
1812
|
+
def drop_blanks_between_titles(items, kinds):
|
|
1813
|
+
"""主标题与副标题之间不留空行(空行从副标题之后开始算)。"""
|
|
1814
|
+
idxs = [i for i, (k, _o, _t) in enumerate(kinds) if k in ("title", "subtitle")]
|
|
1815
|
+
if len(idxs) < 2:
|
|
1816
|
+
return 0
|
|
1817
|
+
removed = 0
|
|
1818
|
+
for a, b in zip(idxs, idxs[1:]):
|
|
1819
|
+
for k in range(b - 1, a, -1):
|
|
1820
|
+
if kinds[k][0] in BLANK_KINDS:
|
|
1821
|
+
el = kinds[k][1]._p
|
|
1822
|
+
if el.getparent() is not None:
|
|
1823
|
+
el.getparent().remove(el)
|
|
1824
|
+
removed += 1
|
|
1825
|
+
return removed
|
|
1826
|
+
|
|
1827
|
+
|
|
1828
|
+
# ---------------------------------------------------------------- 字体档
|
|
1829
|
+
def apply_font_profile(cfg, profile=None):
|
|
1830
|
+
"""按档位覆盖 cfg["fonts"],返回实际生效的档位名。
|
|
1831
|
+
|
|
1832
|
+
standard 用常见简体字体;strict 用 GBK/GB2312 全字库。
|
|
1833
|
+
"""
|
|
1834
|
+
p = str(profile or cfg.get("fontProfile") or "standard").strip().lower()
|
|
1835
|
+
if p not in ("standard", "strict"):
|
|
1836
|
+
p = "standard"
|
|
1837
|
+
if p == "strict":
|
|
1838
|
+
fonts = cfg.setdefault("fonts", {})
|
|
1839
|
+
for k, v in (cfg.get("fontsStrict") or {}).items():
|
|
1840
|
+
if v:
|
|
1841
|
+
fonts[k] = v
|
|
1842
|
+
return p
|
|
1843
|
+
|
|
1844
|
+
|
|
1845
|
+
def check_fonts(report, cfg):
|
|
1846
|
+
"""检测缺哪些字体。
|
|
1847
|
+
|
|
1848
|
+
**不联网**:只读注册表与字体目录。check 模式把缺失记成偏差;
|
|
1849
|
+
apply 模式只写 warnings(不影响排版,也不阻断写回)。
|
|
1850
|
+
"""
|
|
1851
|
+
fc = cfg.get("fontCheck") or {}
|
|
1852
|
+
if not fc.get("enabled", True):
|
|
1853
|
+
return None
|
|
1854
|
+
try:
|
|
1855
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
1856
|
+
if here not in sys.path:
|
|
1857
|
+
sys.path.insert(0, here)
|
|
1858
|
+
import fontcheck
|
|
1859
|
+
except Exception: # noqa: BLE001
|
|
1860
|
+
return None
|
|
1861
|
+
try:
|
|
1862
|
+
info = fontcheck.check(cfg)
|
|
1863
|
+
except Exception: # noqa: BLE001
|
|
1864
|
+
return None
|
|
1865
|
+
if not info.get("missing"):
|
|
1866
|
+
return info
|
|
1867
|
+
cr = info.get("consentRequired") or {}
|
|
1868
|
+
ask = cr.get("ask") or ("缺少字体:%s" % "、".join(info["missing"]))
|
|
1869
|
+
if report.mode == "check":
|
|
1870
|
+
for name in info["missing"]:
|
|
1871
|
+
report.want("font.missing:" + name, "字体", "未安装", "已安装")
|
|
1872
|
+
else:
|
|
1873
|
+
report.warnings.append(ask)
|
|
1874
|
+
if cr.get("command"):
|
|
1875
|
+
report.warnings.append("修复:" + cr["command"])
|
|
1876
|
+
report.stats["missingFonts"] = len(info["missing"])
|
|
1877
|
+
return info
|
|
1878
|
+
|
|
1879
|
+
|
|
1880
|
+
def process(path, mode, cfg, full=True, profile=None):
|
|
1633
1881
|
t0 = time.time()
|
|
1634
1882
|
fix = mode == "apply"
|
|
1635
1883
|
doc = Document(path)
|
|
1636
1884
|
report = Report(os.path.abspath(path), mode, fix)
|
|
1637
1885
|
|
|
1886
|
+
profile = apply_font_profile(cfg, profile)
|
|
1887
|
+
fontinfo = None
|
|
1888
|
+
if (cfg.get("fontCheck") or {}).get("onRun", True):
|
|
1889
|
+
fontinfo = check_fonts(report, cfg)
|
|
1890
|
+
|
|
1891
|
+
light_pass(doc, report, cfg)
|
|
1892
|
+
|
|
1893
|
+
if not full:
|
|
1894
|
+
changed = report.total > 0
|
|
1895
|
+
if fix and changed:
|
|
1896
|
+
_save(doc, path)
|
|
1897
|
+
out = report.as_dict(changed)
|
|
1898
|
+
out["light"] = True
|
|
1899
|
+
out["writeBack"] = bool(fix and changed)
|
|
1900
|
+
out["elapsedMs"] = int((time.time() - t0) * 1000)
|
|
1901
|
+
out["fontProfile"] = profile
|
|
1902
|
+
if fontinfo:
|
|
1903
|
+
out["fonts"] = fontinfo
|
|
1904
|
+
return out
|
|
1905
|
+
|
|
1638
1906
|
for section in doc.sections:
|
|
1639
1907
|
m = cfg["marginsCm"]
|
|
1640
1908
|
for attr, key in (("top_margin", "top"), ("bottom_margin", "bottom"),
|
|
@@ -1658,6 +1926,12 @@ def process(path, mode, cfg):
|
|
|
1658
1926
|
break
|
|
1659
1927
|
items = _collect_body(doc)
|
|
1660
1928
|
kinds = classify(items, cfg)
|
|
1929
|
+
removed = drop_blanks_between_titles(items, kinds)
|
|
1930
|
+
if removed:
|
|
1931
|
+
report.want("title.subtitleGap", "doc.标题",
|
|
1932
|
+
"%d 个空行" % removed, "0 个空行(主标题与副标题紧邻)")
|
|
1933
|
+
items = _collect_body(doc)
|
|
1934
|
+
kinds = classify(items, cfg)
|
|
1661
1935
|
ensure_blank_lines(kinds, report, cfg)
|
|
1662
1936
|
format_table_caption_spacer(items, [k for k, _o, _t in kinds], report, cfg)
|
|
1663
1937
|
items = _collect_body(doc)
|
|
@@ -1697,14 +1971,18 @@ def process(path, mode, cfg):
|
|
|
1697
1971
|
# check 模式:只统计表标题与表格之间是否缺空行,内存里插入不写回
|
|
1698
1972
|
format_table_caption_spacer(items, [k for k, _o, _t in kinds], report, cfg)
|
|
1699
1973
|
|
|
1974
|
+
# 前面插过空段、拆过附件段,新段落还没被全局规范化覆盖:收尾再扫一遍
|
|
1975
|
+
light_pass(doc, report, cfg)
|
|
1976
|
+
|
|
1700
1977
|
changed = report.total > 0
|
|
1701
1978
|
if fix and changed:
|
|
1702
|
-
|
|
1703
|
-
doc.save(tmp)
|
|
1704
|
-
os.replace(tmp, path)
|
|
1979
|
+
_save(doc, path)
|
|
1705
1980
|
out = report.as_dict(changed)
|
|
1706
1981
|
out["writeBack"] = bool(fix and changed)
|
|
1707
1982
|
out["elapsedMs"] = int((time.time() - t0) * 1000)
|
|
1983
|
+
out["fontProfile"] = profile
|
|
1984
|
+
if fontinfo:
|
|
1985
|
+
out["fonts"] = fontinfo
|
|
1708
1986
|
return out
|
|
1709
1987
|
|
|
1710
1988
|
|
|
@@ -1753,7 +2031,7 @@ def doc_text(path):
|
|
|
1753
2031
|
|
|
1754
2032
|
|
|
1755
2033
|
def skip_reason(path, cfg):
|
|
1756
|
-
"""
|
|
2034
|
+
"""保留的扩展点:默认不按正文内容跳过任何文档。"""
|
|
1757
2035
|
kws = cfg.get("skipContentKeywords") or []
|
|
1758
2036
|
if not kws:
|
|
1759
2037
|
return None
|
|
@@ -1786,13 +2064,145 @@ def _collect(paths, recursive):
|
|
|
1786
2064
|
return out
|
|
1787
2065
|
|
|
1788
2066
|
|
|
2067
|
+
def _fonts_cli(args, cfg):
|
|
2068
|
+
"""--fonts / --install-fonts 的处理入口。"""
|
|
2069
|
+
import tempfile
|
|
2070
|
+
import shutil
|
|
2071
|
+
|
|
2072
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
2073
|
+
if here not in sys.path:
|
|
2074
|
+
sys.path.insert(0, here)
|
|
2075
|
+
import fontcheck
|
|
2076
|
+
|
|
2077
|
+
want_install = (args.install_fonts is not None or args.preset
|
|
2078
|
+
or args.from_zip)
|
|
2079
|
+
|
|
2080
|
+
if args.confirm:
|
|
2081
|
+
# 用户授权令牌:满足它等同于 --yes,且令牌只能用一次
|
|
2082
|
+
rec = fontcheck.consume_consent(args.confirm)
|
|
2083
|
+
if not rec:
|
|
2084
|
+
msg = "授权令牌无效或已过期(请重新运行 --fonts 取新的 token)"
|
|
2085
|
+
if args.json:
|
|
2086
|
+
print(json.dumps({"ok": False, "error": msg,
|
|
2087
|
+
"reason": "bad-consent"}, ensure_ascii=False))
|
|
2088
|
+
else:
|
|
2089
|
+
print(msg)
|
|
2090
|
+
return 3
|
|
2091
|
+
args.yes = True
|
|
2092
|
+
if not want_install:
|
|
2093
|
+
# 用户只回传了 token:按当初登记的来源装
|
|
2094
|
+
src = str(rec.get("source") or "")
|
|
2095
|
+
if src.lower().endswith(".zip") or src.startswith(("http://", "https://")):
|
|
2096
|
+
args.from_zip = src
|
|
2097
|
+
elif src in fontcheck.PRESETS:
|
|
2098
|
+
args.preset = src
|
|
2099
|
+
|
|
2100
|
+
if not want_install and not args.yes:
|
|
2101
|
+
info = fontcheck.check(cfg)
|
|
2102
|
+
if args.json:
|
|
2103
|
+
print(json.dumps(info, ensure_ascii=False, indent=2))
|
|
2104
|
+
else:
|
|
2105
|
+
print("平台:%s 安装目录:%s"
|
|
2106
|
+
% (info["platform"], info["installDir"]))
|
|
2107
|
+
for name in info["required"]:
|
|
2108
|
+
hit = info["found"].get(name)
|
|
2109
|
+
print(" %-4s %s" % ("OK" if hit else "缺失", name))
|
|
2110
|
+
if info["missing"]:
|
|
2111
|
+
cr = info.get("consentRequired") or {}
|
|
2112
|
+
print("")
|
|
2113
|
+
print(info["hint"])
|
|
2114
|
+
if cr:
|
|
2115
|
+
print(cr["ask"])
|
|
2116
|
+
print("命令:%s" % cr["command"])
|
|
2117
|
+
return 0 if info["ok"] else 2
|
|
2118
|
+
|
|
2119
|
+
if not args.yes:
|
|
2120
|
+
args.dry_run = True
|
|
2121
|
+
print("需要授权:加 --yes 才会下载安装(当前只做 dry-run)")
|
|
2122
|
+
|
|
2123
|
+
tmpdir = tempfile.mkdtemp(prefix="docxfmt-fonts-")
|
|
2124
|
+
results = []
|
|
2125
|
+
try:
|
|
2126
|
+
if args.from_zip:
|
|
2127
|
+
results += fontcheck.extract_zip(args.from_zip, tmpdir)
|
|
2128
|
+
if args.preset:
|
|
2129
|
+
results += fontcheck.download_preset(args.preset, tmpdir)
|
|
2130
|
+
for src in (args.install_fonts or []):
|
|
2131
|
+
if os.path.isdir(src):
|
|
2132
|
+
for fn in sorted(os.listdir(src)):
|
|
2133
|
+
if fn.lower().endswith(fontcheck.FONT_EXTS):
|
|
2134
|
+
results.append({"file": os.path.join(src, fn),
|
|
2135
|
+
"ok": True})
|
|
2136
|
+
elif os.path.isfile(src):
|
|
2137
|
+
results.append({"file": src, "ok": True})
|
|
2138
|
+
else:
|
|
2139
|
+
results.append({"file": src, "ok": False,
|
|
2140
|
+
"reason": "路径不存在"})
|
|
2141
|
+
good = [r["file"] for r in results if r.get("ok")]
|
|
2142
|
+
if not good:
|
|
2143
|
+
print("没有可安装的字体文件")
|
|
2144
|
+
if args.json:
|
|
2145
|
+
print(json.dumps({"results": results}, ensure_ascii=False,
|
|
2146
|
+
indent=2))
|
|
2147
|
+
return 1
|
|
2148
|
+
inst = fontcheck.install(good, dry_run=args.dry_run)
|
|
2149
|
+
if args.json:
|
|
2150
|
+
print(json.dumps({"downloaded": results, "installed": inst,
|
|
2151
|
+
"dryRun": args.dry_run},
|
|
2152
|
+
ensure_ascii=False, indent=2))
|
|
2153
|
+
else:
|
|
2154
|
+
for it in results:
|
|
2155
|
+
if not it.get("ok"):
|
|
2156
|
+
print(" [跳过] %s %s" % (it.get("file"), it.get("reason")))
|
|
2157
|
+
for it in inst:
|
|
2158
|
+
if not it.get("ok"):
|
|
2159
|
+
print(" [失败] %s %s" % (it.get("file"), it.get("reason")))
|
|
2160
|
+
continue
|
|
2161
|
+
verb = {"installed": "已安装", "exists": "已存在",
|
|
2162
|
+
"copy": "将安装"}.get(it["action"], it["action"])
|
|
2163
|
+
print(" [%s] %s → %s" % (verb, it.get("family"),
|
|
2164
|
+
it.get("dest")))
|
|
2165
|
+
if not args.dry_run:
|
|
2166
|
+
fams = [i["family"] for i in inst if i.get("ok")]
|
|
2167
|
+
if fams:
|
|
2168
|
+
fontcheck.save_consent(
|
|
2169
|
+
fams,
|
|
2170
|
+
args.from_zip or args.preset or "local",
|
|
2171
|
+
[i["dest"] for i in inst if i.get("ok")])
|
|
2172
|
+
print("\n重启 Word 后生效;以管理员身份运行的 Word "
|
|
2173
|
+
"看不到用户级字体。")
|
|
2174
|
+
return 0 if all(i.get("ok") for i in inst) else 1
|
|
2175
|
+
finally:
|
|
2176
|
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
2177
|
+
|
|
2178
|
+
|
|
1789
2179
|
def main(argv=None):
|
|
1790
2180
|
ap = argparse.ArgumentParser(description="docx 公文格式规范化")
|
|
1791
|
-
ap.add_argument("path", nargs="
|
|
2181
|
+
ap.add_argument("path", nargs="*")
|
|
1792
2182
|
ap.add_argument("--mode", choices=["apply", "check"], default="apply")
|
|
2183
|
+
ap.add_argument("--light", action="store_true",
|
|
2184
|
+
help="只做全局规范化(分页开关/中文引号/中英之间不留空格),不套公文版式")
|
|
1793
2185
|
ap.add_argument("--recursive", action="store_true")
|
|
1794
2186
|
ap.add_argument("--json", action="store_true")
|
|
1795
2187
|
ap.add_argument("--config", default=None, help="JSON 配置字符串或 .json 文件路径")
|
|
2188
|
+
ap.add_argument("--fonts", action="store_true",
|
|
2189
|
+
help="只报告字体安装情况(不处理文档)")
|
|
2190
|
+
ap.add_argument("--install-fonts", nargs="*", default=None,
|
|
2191
|
+
help="安装字体:本地文件/目录(可留空配合 --preset)")
|
|
2192
|
+
ap.add_argument("--preset", default=None,
|
|
2193
|
+
help="预置清单:gongwen(普通档)/ gongwen-strict(严格档)")
|
|
2194
|
+
ap.add_argument("--from-zip", default=None,
|
|
2195
|
+
help="从 zip(URL 或本地路径)提取字体后安装")
|
|
2196
|
+
ap.add_argument("--yes", action="store_true",
|
|
2197
|
+
help="确认下载安装;缺省时只做 dry-run")
|
|
2198
|
+
ap.add_argument("--confirm", default=None,
|
|
2199
|
+
help="授权令牌(由 --fonts --json 的 consentRequired.token 给出,"
|
|
2200
|
+
"用户同意后回传;一次性、10 分钟内有效)")
|
|
2201
|
+
ap.add_argument("--dry-run", action="store_true", help="只报告不落盘")
|
|
2202
|
+
ap.add_argument("--font-profile", choices=["standard", "strict"], default=None,
|
|
2203
|
+
help="字体档:standard(默认)/ strict(GBK/GB2312)")
|
|
2204
|
+
ap.add_argument("--no-font-check", action="store_true",
|
|
2205
|
+
help="跳过字体检测")
|
|
1796
2206
|
args = ap.parse_args(argv)
|
|
1797
2207
|
|
|
1798
2208
|
cfg = DEFAULTS
|
|
@@ -1803,6 +2213,21 @@ def main(argv=None):
|
|
|
1803
2213
|
raw = fh.read()
|
|
1804
2214
|
cfg = merge_config(json.loads(raw))
|
|
1805
2215
|
|
|
2216
|
+
if args.font_profile:
|
|
2217
|
+
cfg["fontProfile"] = args.font_profile
|
|
2218
|
+
if args.no_font_check:
|
|
2219
|
+
cfg.setdefault("fontCheck", {})["enabled"] = False
|
|
2220
|
+
if args.config and args.font_profile == "strict":
|
|
2221
|
+
cfg.setdefault("fontCheck", {})
|
|
2222
|
+
apply_font_profile(cfg, cfg.get("fontProfile"))
|
|
2223
|
+
|
|
2224
|
+
if args.fonts or args.install_fonts is not None or args.preset \
|
|
2225
|
+
or args.from_zip:
|
|
2226
|
+
return _fonts_cli(args, cfg)
|
|
2227
|
+
|
|
2228
|
+
if not args.path:
|
|
2229
|
+
ap.error("缺少要处理的 docx 路径(或用 --fonts 查看字体)")
|
|
2230
|
+
|
|
1806
2231
|
results = []
|
|
1807
2232
|
failed = False
|
|
1808
2233
|
violations = 0
|
|
@@ -1818,7 +2243,7 @@ def main(argv=None):
|
|
|
1818
2243
|
})
|
|
1819
2244
|
continue
|
|
1820
2245
|
try:
|
|
1821
|
-
res = process(path, args.mode, cfg)
|
|
2246
|
+
res = process(path, args.mode, cfg, full=not args.light)
|
|
1822
2247
|
except Exception as exc:
|
|
1823
2248
|
import traceback
|
|
1824
2249
|
res = {"ok": False, "file": os.path.abspath(path), "mode": args.mode,
|
package/locale/en.json
CHANGED
|
@@ -8,11 +8,12 @@
|
|
|
8
8
|
"applied": "normalized",
|
|
9
9
|
"clean": "already compliant",
|
|
10
10
|
"violations": "deviations",
|
|
11
|
-
"skipped": "skipped (no trigger keyword
|
|
12
|
-
"skipReason": "official-document formatting not applied (no trigger keyword
|
|
11
|
+
"skipped": "skipped (no trigger keyword, global normalization off)",
|
|
12
|
+
"skipReason": "official-document formatting not applied (no trigger keyword)",
|
|
13
|
+
"lightApplied": "global normalization only (no 公文 in the request: pagination switches, Chinese quotes, no space around Latin words)",
|
|
13
14
|
"config": {
|
|
14
|
-
"triggerKeywords": "trigger words; the request text must contain one of them, default ['公文']",
|
|
15
|
-
"
|
|
15
|
+
"triggerKeywords": "trigger words; the request text must contain one of them for the full layout, default ['公文']",
|
|
16
|
+
"globalNormalize": "still apply global normalization when no trigger word matched (pagination off, Chinese quotes, no CJK-Latin spacing)",
|
|
16
17
|
"autoFormat": "queue any .docx path seen in tool results",
|
|
17
18
|
"formatExisting": "also normalize files created before the plugin loaded"
|
|
18
19
|
}
|