dknowc-dsh 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.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -0
  3. package/cordis.patch.yml +17 -0
  4. package/package.json +33 -0
  5. package/skills/dknowc-official-doc-writer/README.md +156 -0
  6. package/skills/dknowc-official-doc-writer/SKILL.md +462 -0
  7. package/skills/dknowc-official-doc-writer/config/format.json +101 -0
  8. package/skills/dknowc-official-doc-writer/config/user_profile.json.example +6 -0
  9. package/skills/dknowc-official-doc-writer/official-docs/input/mcp_intro_content.md +61 -0
  10. package/skills/dknowc-official-doc-writer/reference/anti_ai_patterns.md +113 -0
  11. package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +62 -0
  12. package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +138 -0
  13. package/skills/dknowc-official-doc-writer/reference/output_guide.md +288 -0
  14. package/skills/dknowc-official-doc-writer/reference/review_checklist.md +156 -0
  15. package/skills/dknowc-official-doc-writer/reference/search_guide.md +317 -0
  16. package/skills/dknowc-official-doc-writer/reference/search_intro.md +15 -0
  17. package/skills/dknowc-official-doc-writer/reference/search_policy.md +284 -0
  18. package/skills/dknowc-official-doc-writer/reference/standards/00_index.md +151 -0
  19. package/skills/dknowc-official-doc-writer/reference/standards/01_report.md +51 -0
  20. package/skills/dknowc-official-doc-writer/reference/standards/02_qingshi.md +53 -0
  21. package/skills/dknowc-official-doc-writer/reference/standards/03_pifu.md +48 -0
  22. package/skills/dknowc-official-doc-writer/reference/standards/04_tongzhi.md +51 -0
  23. package/skills/dknowc-official-doc-writer/reference/standards/05_yijian.md +55 -0
  24. package/skills/dknowc-official-doc-writer/reference/standards/06_han.md +81 -0
  25. package/skills/dknowc-official-doc-writer/reference/standards/07_minutes.md +46 -0
  26. package/skills/dknowc-official-doc-writer/reference/standards/08_tongbao.md +53 -0
  27. package/skills/dknowc-official-doc-writer/reference/standards/09_tonggao.md +45 -0
  28. package/skills/dknowc-official-doc-writer/reference/standards/10_gonggao.md +44 -0
  29. package/skills/dknowc-official-doc-writer/reference/standards/11_fuhan_approve.md +46 -0
  30. package/skills/dknowc-official-doc-writer/reference/standards/12_fuhan_objection.md +46 -0
  31. package/skills/dknowc-official-doc-writer/reference/standards/13_reminder.md +46 -0
  32. package/skills/dknowc-official-doc-writer/reference/standards/14_generic.md +41 -0
  33. package/skills/dknowc-official-doc-writer/reference/standards/15_business_docs.md +47 -0
  34. package/skills/dknowc-official-doc-writer/reference/standards/16_decision.md +47 -0
  35. package/skills/dknowc-official-doc-writer/reference/standards/17_resolution.md +45 -0
  36. package/skills/dknowc-official-doc-writer/reference/standards/18_order.md +44 -0
  37. package/skills/dknowc-official-doc-writer/reference/standards/19_gazette.md +45 -0
  38. package/skills/dknowc-official-doc-writer/reference/standards/20_motion.md +45 -0
  39. package/skills/dknowc-official-doc-writer/reference/standards/21_explanation.md +40 -0
  40. package/skills/dknowc-official-doc-writer/reference/standards/22_application.md +47 -0
  41. package/skills/dknowc-official-doc-writer/reference/standards/23_publicity.md +46 -0
  42. package/skills/dknowc-official-doc-writer/reference/standards/24_procurement.md +40 -0
  43. package/skills/dknowc-official-doc-writer/reference/standards/25_plan.md +42 -0
  44. package/skills/dknowc-official-doc-writer/reference/standards/26_summary.md +42 -0
  45. package/skills/dknowc-official-doc-writer/reference/standards/27_speech.md +43 -0
  46. package/skills/dknowc-official-doc-writer/reference/standards/28_rules.md +40 -0
  47. package/skills/dknowc-official-doc-writer/reference/standards/29_research.md +42 -0
  48. package/skills/dknowc-official-doc-writer/reference/standards/30_feasibility.md +42 -0
  49. package/skills/dknowc-official-doc-writer/reference/standards/31_review_material.md +40 -0
  50. package/skills/dknowc-official-doc-writer/reference/standards/32_ai_compute.md +41 -0
  51. package/skills/dknowc-official-doc-writer/reference/standards/99_expressions.md +569 -0
  52. package/skills/dknowc-official-doc-writer/reference/task_router.md +119 -0
  53. package/skills/dknowc-official-doc-writer/scripts/adapt_mcp_result.py +241 -0
  54. package/skills/dknowc-official-doc-writer/scripts/check_release.py +78 -0
  55. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +575 -0
  56. package/skills/dknowc-official-doc-writer/scripts/format_document.py +1756 -0
  57. package/skills/dknowc-official-doc-writer/scripts/initialize.py +178 -0
  58. package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +158 -0
  59. package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +223 -0
  60. package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +202 -0
  61. package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +242 -0
  62. package/skills/dknowc-official-doc-writer/scripts/register.mjs +218 -0
  63. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +966 -0
  64. package/skills/dknowc-official-doc-writer/scripts/review_document.py +127 -0
  65. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +180 -0
  66. package/skills/dknowc-official-doc-writer/scripts/template_generator.py +975 -0
  67. package/skills/dknowc-trusted-consulting/README.md +63 -0
  68. package/skills/dknowc-trusted-consulting/SKILL.md +172 -0
  69. package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +241 -0
  70. package/skills/dknowc-trusted-consulting/scripts/check_release.py +66 -0
  71. package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +475 -0
  72. package/skills/dknowc-trusted-consulting/scripts/initialize.py +89 -0
  73. package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +158 -0
  74. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +181 -0
  75. package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +990 -0
  76. package/skills/dknowc-trusted-search/README.md +63 -0
  77. package/skills/dknowc-trusted-search/SKILL.md +232 -0
  78. package/skills/dknowc-trusted-search/official-docs/output/.gitkeep +0 -0
  79. package/skills/dknowc-trusted-search/official-docs/search-results/.gitkeep +0 -0
  80. package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +241 -0
  81. package/skills/dknowc-trusted-search/scripts/check_release.py +79 -0
  82. package/skills/dknowc-trusted-search/scripts/deep_query.py +266 -0
  83. package/skills/dknowc-trusted-search/scripts/initialize.py +89 -0
  84. package/skills/dknowc-trusted-search/scripts/mcp_direct.py +158 -0
  85. package/skills/dknowc-trusted-search/scripts/register_key.mjs +181 -0
  86. package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +889 -0
  87. package/skills/dknowc-trusted-search/scripts/render_trace_html.py +1011 -0
  88. package/skills/dknowc-trusted-search/scripts/trusted_search.py +325 -0
  89. package/src/index.js +103 -0
@@ -0,0 +1,1756 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ 公文排版脚本 v2.0.0
4
+ 严格按照《XX单位公文格式样本(试行)》进行自动排版
5
+
6
+ 【v2.0.0 更新说明】
7
+ - 删除所有红头文件相关代码(红头+尾表由 template_generator.py 处理)
8
+ - 只保留普通格式排版核心逻辑
9
+ - 架构:template_generator.py 调用本文件的函数进行正文排版
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import re
16
+ import sys
17
+ from datetime import datetime
18
+ from pathlib import Path
19
+
20
+ import docx
21
+ import docx.opc.constants
22
+ from docx.enum.section import WD_ORIENT, WD_SECTION
23
+ from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_TABLE_ALIGNMENT
24
+ from docx.enum.text import WD_BREAK
25
+ from docx.shared import Pt, Cm, Mm, RGBColor
26
+ from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
27
+ from docx.oxml.ns import qn
28
+ from docx.oxml import OxmlElement
29
+
30
+
31
+ def add_hyperlink(paragraph, url, text, font_name=None, font_size=None):
32
+ """在段落中添加可点击的超链接"""
33
+ part = paragraph.part
34
+ r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
35
+
36
+ hyperlink = OxmlElement('w:hyperlink')
37
+ hyperlink.set(qn('r:id'), r_id)
38
+
39
+ new_run = OxmlElement('w:r')
40
+ rPr = OxmlElement('w:rPr')
41
+
42
+ if font_name or font_size:
43
+ rFonts = OxmlElement('w:rFonts')
44
+ if font_name:
45
+ rFonts.set(qn('w:eastAsia'), font_name)
46
+ rFonts.set(qn('w:ascii'), font_name)
47
+ rFonts.set(qn('w:hAnsi'), font_name)
48
+ rPr.append(rFonts)
49
+ if font_size:
50
+ sz = OxmlElement('w:sz')
51
+ sz.set(qn('w:val'), str(int(font_size * 2)))
52
+ rPr.append(sz)
53
+ szCs = OxmlElement('w:szCs')
54
+ szCs.set(qn('w:val'), str(int(font_size * 2)))
55
+ rPr.append(szCs)
56
+
57
+ # 超链接颜色(蓝色)
58
+ color = OxmlElement('w:color')
59
+ color.set(qn('w:val'), '0563C1')
60
+ rPr.append(color)
61
+
62
+ # 下划线
63
+ u = OxmlElement('w:u')
64
+ u.set(qn('w:val'), 'single')
65
+ rPr.append(u)
66
+
67
+ new_run.append(rPr)
68
+ text_elem = OxmlElement('w:t')
69
+ text_elem.text = text
70
+ new_run.append(text_elem)
71
+
72
+ hyperlink.append(new_run)
73
+ paragraph._p.append(hyperlink)
74
+
75
+ return hyperlink
76
+
77
+
78
+ def sanitize_url(raw_url):
79
+ """清理 URL 后缀说明,避免把括号内说明写进超链接。"""
80
+ url = raw_url.strip().rstrip(',。、;;,.')
81
+ url = re.split(r'[((]', url, maxsplit=1)[0]
82
+ return url.strip().rstrip(',。、;;,.')
83
+
84
+
85
+ def hyperlink_display_text(label=None, fallback_index=None):
86
+ """生成知识专库链接的可见文本。"""
87
+ clean_label = normalize_kb_label(label)
88
+ if not clean_label:
89
+ clean_label = f"知识专库链接{fallback_index}" if fallback_index else "知识专库链接"
90
+ return f"{clean_label}(点击打开)"
91
+
92
+
93
+ def normalize_kb_label(label):
94
+ """清洗知识专库链接标签,去掉编号、Markdown 强调和已写入的点击提示。"""
95
+ clean_label = (label or "").strip()
96
+ clean_label = re.sub(r'^\s*\d+[\.、]\s*', '', clean_label)
97
+ clean_label = re.sub(r'^\s*[-*]\s*', '', clean_label)
98
+ clean_label = re.sub(r'[*_`]+', '', clean_label)
99
+ clean_label = re.sub(r'[((]\s*点击打开\s*[))]', '', clean_label)
100
+ clean_label = clean_label.replace('点击打开', '')
101
+ clean_label = re.sub(r'\s+', ' ', clean_label)
102
+ return clean_label.strip().rstrip('::')
103
+
104
+
105
+ def is_internal_search_endpoint(url):
106
+ """识别深知搜索接口地址,避免误当成知识专库链接输出。"""
107
+ return "open.dknowc.cn/dependable/search" in url
108
+
109
+
110
+ def is_generic_kb_label(text):
111
+ """识别不能作为知识专库链接显示名的泛化说明。"""
112
+ clean_text = (text or "").strip().rstrip('::')
113
+ if not clean_text:
114
+ return True
115
+ generic_patterns = (
116
+ r'^以下.*知识专库链接.*',
117
+ r'^本次.*知识专库.*',
118
+ r'^知识专库链接$',
119
+ r'^链接$',
120
+ r'^来源链接$',
121
+ r'^可点击链接$',
122
+ )
123
+ return any(re.match(pattern, clean_text) for pattern in generic_patterns)
124
+
125
+
126
+ def is_useless_kb_label_line(text):
127
+ """识别知识专库链接区中可直接丢弃的无意义标签行。"""
128
+ clean_text = (text or "").strip().rstrip('::')
129
+ return clean_text in {"知识专库链接", "链接", "来源链接", "可点击链接"}
130
+
131
+ DEFAULT_OUTPUT_DIR = "official-docs/output"
132
+ CONFIG_PATH = os.path.join(os.path.dirname(__file__), '..', 'config', 'format.json')
133
+ SKILL_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
134
+ # 工作区根:dsh 场景通过环境变量 DKNWOC_WS_ROOT 指向会话工作区,未设置时回退到 skill 目录
135
+ WS_ROOT = os.path.abspath(os.environ.get("DKNWOC_WS_ROOT") or os.getcwd())
136
+
137
+ OFFICIAL_DOCS_DIR = os.path.join(WS_ROOT, "official-docs")
138
+ INPUT_DIR = os.path.join(OFFICIAL_DOCS_DIR, "input")
139
+ SEARCH_RESULTS_DIR = os.path.join(OFFICIAL_DOCS_DIR, "search-results")
140
+ AI_DISCLAIMER_TEXT = "【AI生成提示】内容由AI生成,内容仅供参考。"
141
+
142
+
143
+ def load_format_config():
144
+ """加载格式配置文件"""
145
+ try:
146
+ with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
147
+ return json.load(f)
148
+ except FileNotFoundError:
149
+ print(f"警告: 配置文件不存在 {CONFIG_PATH},使用默认值")
150
+ return None
151
+ except json.JSONDecodeError as e:
152
+ print(f"警告: 配置文件格式错误 {CONFIG_PATH}: {e},使用默认值")
153
+ return None
154
+
155
+
156
+ # 加载配置(全局变量)
157
+ FORMAT_CONFIG = load_format_config()
158
+
159
+
160
+ def get_skill_root():
161
+ """Skill 安装根目录(含 scripts/、config/ 等),与调用时的 cwd 无关。"""
162
+ return SKILL_ROOT
163
+
164
+
165
+ def get_configured_output_dir():
166
+ """获取 Word 输出目录:相对路径基于 Skill 安装目录解析,不依赖 cwd。"""
167
+ configured_dir = None
168
+ if FORMAT_CONFIG:
169
+ output_config = FORMAT_CONFIG.get('output', {})
170
+ if isinstance(output_config, dict):
171
+ configured_dir = output_config.get('dir') or output_config.get('output_dir')
172
+
173
+ output_dir = os.path.expanduser(configured_dir or DEFAULT_OUTPUT_DIR)
174
+ if not os.path.isabs(output_dir):
175
+ output_dir = os.path.join(get_skill_root(), output_dir)
176
+ output_dir = os.path.abspath(output_dir)
177
+ if not is_path_within(output_dir, os.path.abspath(os.path.join(get_skill_root(), DEFAULT_OUTPUT_DIR))):
178
+ raise ValueError(f"输出目录必须位于 {os.path.join(get_skill_root(), DEFAULT_OUTPUT_DIR)} 内")
179
+ return output_dir
180
+
181
+
182
+ def is_path_within(path, parent):
183
+ """判断 path 是否位于 parent 目录内。"""
184
+ try:
185
+ return os.path.commonpath([os.path.abspath(path), os.path.abspath(parent)]) == os.path.abspath(parent)
186
+ except ValueError:
187
+ return False
188
+
189
+
190
+ def resolve_input_text_path(input_path):
191
+ """只允许读取 skill 工作目录内的正文文本文件。"""
192
+ raw_path = os.path.expanduser(str(input_path).strip())
193
+ if os.path.isabs(raw_path):
194
+ resolved = os.path.abspath(raw_path)
195
+ elif raw_path == os.path.basename(raw_path):
196
+ resolved = os.path.abspath(os.path.join(INPUT_DIR, raw_path))
197
+ else:
198
+ resolved = os.path.abspath(os.path.join(get_skill_root(), raw_path))
199
+
200
+ allowed_dirs = [
201
+ os.path.abspath(INPUT_DIR),
202
+ os.path.abspath(get_configured_output_dir()),
203
+ os.path.abspath(SEARCH_RESULTS_DIR),
204
+ ]
205
+ if not any(is_path_within(resolved, allowed_dir) for allowed_dir in allowed_dirs):
206
+ raise ValueError(f"输入文件必须位于 skill 工作目录内: {input_path}")
207
+ if os.path.splitext(resolved)[1].lower() not in {".txt", ".md"}:
208
+ raise ValueError(f"只允许读取 .txt 或 .md 正文文件: {input_path}")
209
+ return resolved
210
+
211
+
212
+ def resolve_output_path(output_path):
213
+ """解析输出路径:只允许写入固定 Word 输出目录。"""
214
+ if not output_path:
215
+ return None
216
+ output_path = os.path.expanduser(output_path.strip())
217
+ output_dir = get_configured_output_dir()
218
+ if os.path.isabs(output_path):
219
+ resolved = os.path.abspath(output_path)
220
+ elif output_path == os.path.basename(output_path):
221
+ resolved = os.path.abspath(os.path.join(output_dir, output_path))
222
+ else:
223
+ resolved = os.path.abspath(os.path.join(get_skill_root(), output_path))
224
+ if not is_path_within(resolved, output_dir):
225
+ raise ValueError(f"输出文件必须位于 Word 输出目录内: {output_dir}")
226
+ return resolved
227
+
228
+
229
+ def display_path(path):
230
+ """将 Skill 内文件路径转换为面向用户的相对路径。"""
231
+ resolved = os.path.abspath(os.path.expanduser(str(path)))
232
+ try:
233
+ return os.path.relpath(resolved, get_skill_root())
234
+ except ValueError:
235
+ return resolved
236
+
237
+
238
+ def get_font_config(element_name):
239
+ """从配置获取字体设置,返回 (font_name, font_size, bold)"""
240
+ if not FORMAT_CONFIG or element_name not in FORMAT_CONFIG:
241
+ # 默认值
242
+ defaults = {
243
+ 'title': ('方正小标宋简体', 22, False),
244
+ 'body': ('仿宋_GB2312', 16, False),
245
+ 'heading1': ('黑体', 16, False),
246
+ 'heading2': ('楷体_GB2312', 16, False),
247
+ 'heading3': ('仿宋_GB2312', 16, False),
248
+ }
249
+ return defaults.get(element_name, ('仿宋_GB2312', 16, False))
250
+
251
+ config = FORMAT_CONFIG[element_name]
252
+ return (
253
+ config.get('font', '仿宋_GB2312'),
254
+ config.get('size_pt', 16),
255
+ config.get('bold', False)
256
+ )
257
+
258
+
259
+ def get_page_margin():
260
+ """从配置获取页边距,返回 (top_mm, bottom_mm, left_mm, right_mm)"""
261
+ if FORMAT_CONFIG and 'page' in FORMAT_CONFIG:
262
+ page = FORMAT_CONFIG['page']
263
+ # 支持四边分别设置(国标 GB/T 9704)
264
+ if 'margin_top_mm' in page:
265
+ return (
266
+ page.get('margin_top_mm', 37),
267
+ page.get('margin_bottom_mm', 35),
268
+ page.get('margin_left_mm', 28),
269
+ page.get('margin_right_mm', 26),
270
+ )
271
+ # 兼容旧配置:统一边距
272
+ unified = page.get('margin_mm', 25)
273
+ return (unified, unified, unified, unified)
274
+ return (37, 35, 28, 26)
275
+
276
+
277
+ def get_page_size():
278
+ """从配置获取纸张尺寸,默认 A4。"""
279
+ if FORMAT_CONFIG and 'page' in FORMAT_CONFIG:
280
+ page = FORMAT_CONFIG['page']
281
+ return (
282
+ page.get('width_mm', 210),
283
+ page.get('height_mm', 297),
284
+ )
285
+ return (210, 297)
286
+
287
+
288
+ def get_latin_font_config():
289
+ """获取全文数字和字母字体。"""
290
+ if FORMAT_CONFIG:
291
+ body = FORMAT_CONFIG.get('body', {})
292
+ if body.get('latin_font'):
293
+ return body['latin_font']
294
+ return 'Times New Roman'
295
+
296
+ MAX_INPUT_LENGTH = 50000
297
+ MAX_INPUT_LINES = 2000
298
+ MAX_OUTPUT_LINES = 3000
299
+
300
+
301
+ def get_next_version(output_path: str) -> str:
302
+ """
303
+ 获取下一个版本号的输出路径
304
+
305
+ Args:
306
+ output_path: 原始输出路径
307
+
308
+ Returns:
309
+ 带版本号的输出路径(如果文件已存在)
310
+ """
311
+ output_path = os.path.expanduser(output_path)
312
+ output_dir = Path(output_path).parent
313
+ filename = Path(output_path).stem # 文件名(无扩展名)
314
+ ext = Path(output_path).suffix # 扩展名
315
+
316
+ # 如果文件不存在,直接返回原路径
317
+ if not Path(output_path).exists():
318
+ return output_path
319
+
320
+ # 文件已存在,需要添加版本号
321
+ # 查找所有同名文件(包含版本号)
322
+ pattern = f"{filename}_v*.docx"
323
+ existing_files = list(output_dir.glob(pattern))
324
+
325
+ # 如果没有版本号文件,从v1开始
326
+ if not existing_files:
327
+ return str(output_dir / f"{filename}_v1{ext}")
328
+
329
+ # 提取所有版本号
330
+ versions = []
331
+ for file in existing_files:
332
+ # 提取版本号(如"关于XXX的通知_v1.docx" -> 1)
333
+ try:
334
+ version_str = file.stem.split('_v')[-1]
335
+ version_num = int(version_str)
336
+ versions.append(version_num)
337
+ except:
338
+ continue
339
+
340
+ # 计算下一个版本号
341
+ next_version = max(versions) + 1 if versions else 1
342
+
343
+ return str(output_dir / f"{filename}_v{next_version}{ext}")
344
+
345
+
346
+ def sanitize_filename_component(text: str, max_length: int = 80) -> str:
347
+ """将公文标题转换为可用文件名。"""
348
+ value = re.sub(r'\s+', '', text.strip())
349
+ value = re.sub(r'[\\/:*?"<>|]', '', value)
350
+ value = value.strip('. ')
351
+ if not value:
352
+ return ""
353
+ return value[:max_length]
354
+
355
+
356
+ try:
357
+ from docx import Document
358
+ from docx.shared import Pt, Cm, Mm, RGBColor
359
+ from docx.enum.section import WD_ORIENT, WD_SECTION
360
+ from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT, WD_TABLE_ALIGNMENT
361
+ from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
362
+ from docx.oxml.ns import qn
363
+ from docx.oxml import OxmlElement
364
+ except ImportError:
365
+ print("错误: 缺少 python-docx 库,请安装: pip install python-docx")
366
+ sys.exit(1)
367
+
368
+
369
+ def set_run_font(run, font_name, font_size, bold=False, color=None, latin_font=None, latin=False):
370
+ """设置字体"""
371
+ latin_font = latin_font or get_latin_font_config()
372
+ display_font = latin_font if latin else font_name
373
+ run.font.name = display_font
374
+ run.font.size = Pt(font_size)
375
+ run.font.bold = bold
376
+ if color:
377
+ run.font.color.rgb = color
378
+ rPr = run._element.get_or_add_rPr()
379
+ rFonts = rPr.rFonts
380
+ if rFonts is None:
381
+ rFonts = OxmlElement('w:rFonts')
382
+ rPr.append(rFonts)
383
+ rFonts.set(qn('w:eastAsia'), font_name)
384
+ rFonts.set(qn('w:ascii'), display_font)
385
+ rFonts.set(qn('w:hAnsi'), display_font)
386
+ rFonts.set(qn('w:cs'), display_font)
387
+
388
+
389
+ def add_formatted_text(paragraph, text, font_name, font_size, bold=False, color=None):
390
+ """添加文本并确保数字、字母使用 Times New Roman。"""
391
+ latin_font = get_latin_font_config()
392
+ for segment in re.findall(r'[A-Za-z0-9]+|[^A-Za-z0-9]+', text):
393
+ run = paragraph.add_run(segment)
394
+ set_run_font(
395
+ run,
396
+ font_name,
397
+ font_size,
398
+ bold=bold,
399
+ color=color,
400
+ latin_font=latin_font,
401
+ latin=bool(re.fullmatch(r'[A-Za-z0-9]+', segment)),
402
+ )
403
+ return paragraph
404
+
405
+
406
+ def set_paragraph_format(para, first_line_indent=False, indent_chars=None, alignment=None, line_spacing=None):
407
+ """设置段落格式
408
+
409
+ Args:
410
+ para: 段落对象
411
+ first_line_indent: 是否首行缩进(已废弃,请使用indent_chars)
412
+ indent_chars: 缩进字符数(如2表示2字符)
413
+ alignment: 对齐方式
414
+ line_spacing: 行距(磅)
415
+ """
416
+ if indent_chars:
417
+ # 同时写入常规缩进,兼容只读取 first_line_indent 的校验器。
418
+ para.paragraph_format.first_line_indent = Cm(0.37 * indent_chars)
419
+ # 使用Word的字符单位缩进(更准确)
420
+ # 通过底层XML设置 w:firstLineChars 属性
421
+ # 值的单位是1/100字符,所以2字符 = 200
422
+ pPr = para._p.get_or_add_pPr()
423
+ ind = pPr.ind
424
+ if ind is None:
425
+ ind = OxmlElement('w:ind')
426
+ pPr.append(ind)
427
+ ind.set(qn('w:firstLineChars'), str(int(indent_chars * 100)))
428
+ elif first_line_indent:
429
+ # 兼容旧配置
430
+ indent_cm = FORMAT_CONFIG['body']['first_line_indent_cm'] if FORMAT_CONFIG else 0.74
431
+ para.paragraph_format.first_line_indent = Cm(indent_cm)
432
+ if alignment is not None:
433
+ para.alignment = alignment
434
+ para.paragraph_format.space_before = Pt(0)
435
+ para.paragraph_format.space_after = Pt(0)
436
+ if line_spacing:
437
+ para.paragraph_format.line_spacing = Pt(line_spacing)
438
+ para.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY
439
+
440
+
441
+ def set_outline_level(para, level):
442
+ """设置段落的大纲级别
443
+
444
+ Args:
445
+ para: 段落对象
446
+ level: 大纲级别(0-9,0为最高级)
447
+ 0 = 1级(对应 # 标题)
448
+ 1 = 2级(对应 ## 一、XXX)
449
+ 2 = 3级(对应 ### (一)XXX)
450
+ 3 = 4级(对应 #### 1.XXX)
451
+ 9 = 正文文本(默认)
452
+ """
453
+ pPr = para._p.get_or_add_pPr()
454
+ outlineLvl = OxmlElement('w:outlineLvl')
455
+ outlineLvl.set(qn('w:val'), str(level))
456
+ pPr.append(outlineLvl)
457
+
458
+
459
+ def add_page_field(run):
460
+ """添加 Word 页码域。"""
461
+ fld_begin = OxmlElement('w:fldChar')
462
+ fld_begin.set(qn('w:fldCharType'), 'begin')
463
+ instr_text = OxmlElement('w:instrText')
464
+ instr_text.set(qn('xml:space'), 'preserve')
465
+ instr_text.text = 'PAGE'
466
+ fld_separate = OxmlElement('w:fldChar')
467
+ fld_separate.set(qn('w:fldCharType'), 'separate')
468
+ text = OxmlElement('w:t')
469
+ text.text = '1'
470
+ fld_end = OxmlElement('w:fldChar')
471
+ fld_end.set(qn('w:fldCharType'), 'end')
472
+
473
+ run._r.append(fld_begin)
474
+ run._r.append(instr_text)
475
+ run._r.append(fld_separate)
476
+ run._r.append(text)
477
+ run._r.append(fld_end)
478
+
479
+
480
+ def add_standard_page_number(footer, alignment):
481
+ """按 GB/T 9704 页码样式添加页脚:数字左右各一字线。"""
482
+ para = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
483
+ para.clear()
484
+ para.alignment = alignment
485
+ left_dash = para.add_run("— ")
486
+ set_run_font(left_dash, '宋体', 14)
487
+ run = para.add_run()
488
+ set_run_font(run, '宋体', 14)
489
+ add_page_field(run)
490
+ right_dash = para.add_run(" —")
491
+ set_run_font(right_dash, '宋体', 14)
492
+
493
+
494
+ def add_gbt_page_numbers(doc, section):
495
+ """设置奇数页右侧、偶数页左侧页码。"""
496
+ doc.settings.odd_and_even_pages_header_footer = True
497
+ add_standard_page_number(section.footer, WD_ALIGN_PARAGRAPH.RIGHT)
498
+ add_standard_page_number(section.even_page_footer, WD_ALIGN_PARAGRAPH.LEFT)
499
+
500
+
501
+ def add_ai_disclaimer(doc):
502
+ """在文档最末尾添加 AI 生成提示。"""
503
+ if doc.paragraphs and doc.paragraphs[-1].text.strip() == AI_DISCLAIMER_TEXT:
504
+ return
505
+
506
+ para = doc.add_paragraph()
507
+ para.alignment = WD_ALIGN_PARAGRAPH.LEFT
508
+ para.paragraph_format.space_before = Pt(0)
509
+ para.paragraph_format.space_after = Pt(0)
510
+ para.paragraph_format.line_spacing = Pt(18)
511
+ para.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY
512
+
513
+ add_formatted_text(para, AI_DISCLAIMER_TEXT, '仿宋_GB2312', 10.5, color=RGBColor(0x80, 0x80, 0x80))
514
+
515
+
516
+ def set_document_core_properties(doc, title=None):
517
+ """清理并写入基础 DOCX 元数据。"""
518
+ props = doc.core_properties
519
+ now = datetime.now()
520
+ props.title = title or ""
521
+ props.subject = ""
522
+ props.author = ""
523
+ props.keywords = ""
524
+ props.comments = ""
525
+ props.last_modified_by = ""
526
+ props.created = now
527
+ props.modified = now
528
+
529
+
530
+ def get_line_type(line):
531
+ """
532
+ 根据Markdown结构判断行类型
533
+
534
+ 返回值:
535
+ - 'title': # 标题(公文标题)
536
+ - 'heading1': ## 一级标题
537
+ - 'heading2': ### 二级标题
538
+ - 'heading3': #### 三级标题
539
+ - 'empty': 空行
540
+ - 'text': 普通文本
541
+ """
542
+ stripped = line.strip()
543
+
544
+ # 空行
545
+ if not stripped:
546
+ return 'empty'
547
+
548
+ if stripped.startswith('#### '):
549
+ return 'heading3'
550
+ if stripped.startswith('### '):
551
+ return 'heading2'
552
+ if stripped.startswith('## '):
553
+ return 'heading1'
554
+ if stripped.startswith('# ') and not stripped.startswith('## '):
555
+ return 'title'
556
+
557
+ # 兼容模型未加 Markdown 标记但使用公文常见标题格式的情况。
558
+ if re.match(r'^[一二三四五六七八九十]+、[^。;;]{1,40}$', stripped):
559
+ return 'heading1'
560
+ if re.match(r'^([一二三四五六七八九十]+)[^。;;]{1,40}$', stripped):
561
+ return 'heading2'
562
+ if re.match(r'^\d+[\..、][^。;;]{1,40}$', stripped):
563
+ return 'heading3'
564
+
565
+ return 'text'
566
+
567
+
568
+ def strip_markdown_heading(line):
569
+ """去掉Markdown标题标记"""
570
+ stripped = line.strip()
571
+ if stripped.startswith('#### '):
572
+ return stripped[5:]
573
+ if stripped.startswith('### '):
574
+ return stripped[4:]
575
+ if stripped.startswith('## '):
576
+ return stripped[3:]
577
+ if stripped.startswith('# ') and not stripped.startswith('## '):
578
+ return stripped[2:]
579
+ return stripped
580
+
581
+
582
+ def has_markdown_title(lines):
583
+ """判断正文是否已经包含 Markdown 公文标题。"""
584
+ return any(get_line_type(line.strip()) == 'title' for line in lines)
585
+
586
+
587
+ def infer_title_from_output_path(output_path):
588
+ """当正文遗漏 # 标题时,从输出文件名推断公文标题。"""
589
+ if not output_path:
590
+ return None
591
+ stem = Path(os.path.expanduser(output_path)).stem.strip()
592
+ if not stem:
593
+ return None
594
+ stem = re.sub(r'_v\d+$', '', stem)
595
+ stem = re.sub(r'_红头$', '', stem)
596
+ if re.match(r'^公文_\d{8}_\d{6}$', stem):
597
+ return None
598
+ if len(stem) < 4 or len(stem) > 80:
599
+ return None
600
+ return stem
601
+
602
+
603
+ def is_standalone_source_note(output_path):
604
+ """判断当前输出是否为独立的素材来源说明文档。"""
605
+ if not output_path:
606
+ return False
607
+ stem = Path(os.path.expanduser(output_path)).stem.strip()
608
+ return bool(re.search(r'_素材来源说明(?:_v\d+)?$', stem, re.IGNORECASE))
609
+
610
+
611
+ def extract_document_title(lines):
612
+ """从正文行中提取公文标题,用于默认输出文件名。"""
613
+ for line in lines:
614
+ stripped = line.strip()
615
+ if not stripped:
616
+ continue
617
+ if get_line_type(stripped) == 'title':
618
+ title = strip_markdown_heading(stripped)
619
+ elif is_plain_document_title(stripped):
620
+ title = stripped
621
+ else:
622
+ continue
623
+ title = sanitize_filename_component(title)
624
+ if title:
625
+ return title
626
+ return None
627
+
628
+
629
+ def strip_markdown_bold(text):
630
+ """去掉Markdown加粗标记 **text** 或 __text__"""
631
+ text = re.sub(r'\*\*([^*]+)\*\*', r'\1', text)
632
+ text = re.sub(r'__([^_]+)__', r'\1', text)
633
+ return text
634
+
635
+
636
+ def normalize_appendix_text(text):
637
+ """清理素材附录中的内部写作痕迹。"""
638
+ text = strip_markdown_bold(text.strip())
639
+ text = re.sub(r'^[→➜]\s*用于[::]\s*', '用途:', text)
640
+ text = re.sub(r'^[→➜]\s*参考[::]\s*', '参考:', text)
641
+ text = re.sub(r'^[→➜]\s*用途[::]\s*', '用途:', text)
642
+ while '来源:来源:' in text:
643
+ text = text.replace('来源:来源:', '来源:')
644
+ while '数据源:数据源:' in text:
645
+ text = text.replace('数据源:数据源:', '数据源:')
646
+ return text
647
+
648
+
649
+ def is_attachment_line(line):
650
+ """判断是否为附件行"""
651
+ return bool(re.match(r'^附件[::]', line.strip()))
652
+
653
+
654
+ def is_attachment_continuation(line):
655
+ """判断是否为附件清单续行,如 2.×××。"""
656
+ return bool(re.match(r'^\d+[\..、]', line.strip()))
657
+
658
+
659
+ def set_attachment_list_format(para, continuation=False, line_spacing=None):
660
+ """设置正文末尾附件说明格式。"""
661
+ pPr = para._p.get_or_add_pPr()
662
+ ind = pPr.ind
663
+ if ind is None:
664
+ ind = OxmlElement('w:ind')
665
+ pPr.append(ind)
666
+ ind.set(qn('w:start'), "0")
667
+ ind.set(qn('w:startChars'), "0")
668
+ ind.set(qn('w:end'), "0")
669
+ ind.set(qn('w:endChars'), "0")
670
+ if continuation:
671
+ para.paragraph_format.left_indent = Cm(0)
672
+ para.paragraph_format.first_line_indent = None
673
+ ind.set(qn('w:firstLineChars'), "112")
674
+ else:
675
+ para.paragraph_format.first_line_indent = Cm(0.74)
676
+ ind.set(qn('w:firstLineChars'), "200")
677
+ para.alignment = WD_ALIGN_PARAGRAPH.LEFT
678
+ para.paragraph_format.space_before = Pt(0)
679
+ para.paragraph_format.space_after = Pt(0)
680
+ if line_spacing:
681
+ para.paragraph_format.line_spacing = Pt(line_spacing)
682
+ para.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY
683
+
684
+
685
+ def is_attachment_section_title(line):
686
+ """判断附件正文首页标题。"""
687
+ return line.strip() == "附件"
688
+
689
+
690
+ def document_has_visible_content(doc):
691
+ """判断文档中是否已经有正文内容,用于附件页前分页。"""
692
+ return any(paragraph.text.strip() for paragraph in doc.paragraphs)
693
+
694
+
695
+ def paragraph_has_page_break(paragraph):
696
+ """判断段落中是否包含分页符。"""
697
+ return bool(paragraph._p.xpath('.//w:br[@w:type="page"]'))
698
+
699
+
700
+ def document_ends_with_page_break(doc):
701
+ """判断当前文档末尾是否已经是分页符,避免重复插入空白页。"""
702
+ for paragraph in reversed(doc.paragraphs):
703
+ if paragraph_has_page_break(paragraph):
704
+ return True
705
+ if paragraph.text.strip():
706
+ return False
707
+ return False
708
+
709
+
710
+ def add_page_break_if_needed(doc, line_spacing=None):
711
+ """在已有正文后插入分页符;若末尾已有分页符则不重复插入。"""
712
+ if not document_has_visible_content(doc) or document_ends_with_page_break(doc):
713
+ return
714
+ para = doc.add_paragraph()
715
+ run = para.add_run()
716
+ run.add_break(WD_BREAK.PAGE)
717
+ if line_spacing:
718
+ set_paragraph_format(para, first_line_indent=False, line_spacing=line_spacing)
719
+
720
+
721
+ def is_signing_entity(line):
722
+ """判断是否为落款单位
723
+
724
+ 落款单位特征:
725
+ - 长度小于30
726
+ - 以机构名结尾(局、厅、委、办、中心等)
727
+ - 不包含具体场所(会议室、办公室等)
728
+ - 不以句号结尾
729
+ """
730
+ stripped = line.strip()
731
+
732
+ if len(stripped) >= 30:
733
+ return False
734
+
735
+ # 排除以句号结尾的(不是落款单位)
736
+ if stripped.endswith('。'):
737
+ return False
738
+
739
+ # 排除包含具体场所的(会议室、服务中心等)
740
+ exclude_keywords = ['会议室', '服务中心', '办事大厅', '窗口']
741
+ if any(kw in stripped for kw in exclude_keywords):
742
+ return False
743
+
744
+ # 必须以机构名结尾
745
+ agency_suffixes = ['局', '厅', '委', '办', '办公室', '中心', '院', '会', '组委会', '协会', '站', '所', '部', '处', '司', '署', '公司', '集团', '单位']
746
+ if not any(stripped.endswith(suffix) for suffix in agency_suffixes):
747
+ return False
748
+
749
+ return True
750
+
751
+
752
+ def is_date_line(line):
753
+ """判断是否为公文落款日期。"""
754
+ stripped = re.sub(r'\s+', '', line.strip())
755
+ patterns = [
756
+ r'^\d{4}年(?:\d{1,2}|【[^】]+】)月(?:\d{1,2}|【[^】]+】)日$',
757
+ r'^【[^】]+】年【[^】]+】月【[^】]+】日$',
758
+ r'^(?:\d{4}|×{4}|XXXX)年(?:\d{1,2}|×{1,2}|XX)月(?:\d{1,2}|×{1,2}|XX)日$',
759
+ ]
760
+ return any(re.match(pattern, stripped) for pattern in patterns)
761
+
762
+
763
+ def should_right_align_date(lines, idx):
764
+ """仅将正文落款附近的日期右对齐,避免正文日期误判。"""
765
+ if not is_date_line(lines[idx].strip()):
766
+ return False
767
+
768
+ prev_non_empty = ""
769
+ for prev_idx in range(idx - 1, -1, -1):
770
+ candidate = lines[prev_idx].strip()
771
+ if candidate:
772
+ prev_non_empty = candidate
773
+ break
774
+
775
+ if prev_non_empty and is_signing_entity(prev_non_empty):
776
+ return True
777
+
778
+ next_non_empty = ""
779
+ for next_idx in range(idx + 1, min(len(lines), idx + 4)):
780
+ candidate = lines[next_idx].strip()
781
+ if candidate:
782
+ next_non_empty = candidate
783
+ break
784
+
785
+ return next_non_empty in ("[分页符]", "【素材使用情况】", "【知识专库链接】")
786
+
787
+
788
+ def is_contact_info(line):
789
+ """判断是否为联系人信息"""
790
+ return bool(re.match(r'^(?:(?联系人|联系电话|联系人电话|联系方式)[::]', line.strip()))
791
+
792
+
793
+ def normalize_content_text(content_text):
794
+ """规范输入换行,降低命令行传参导致整篇文本变成一段的风险。"""
795
+ content_text = content_text.replace('\ufeff', '')
796
+ content_text = content_text.replace('\r\n', '\n').replace('\r', '\n')
797
+ content_text = content_text.replace('\u2028', '\n').replace('\u2029', '\n')
798
+
799
+ # 如果整段文本被转义成了字面量 \n,恢复为真实换行。
800
+ if '\n' not in content_text and '\\n' in content_text:
801
+ content_text = content_text.replace('\\n', '\n')
802
+
803
+ # 将模型生成的英文半角引号规范化为中文全角引号。
804
+ # 模型在中文正文中常直接输出 ASCII 直引号,Word 交付应统一为全角标点。
805
+ content_text = normalize_chinese_quotes(content_text)
806
+
807
+ return content_text
808
+
809
+
810
+ def normalize_chinese_quotes(text):
811
+ """把英文直引号按上下文智能配对转换为中文全角引号。
812
+
813
+ 规则:
814
+ - 英文双引号 " 转换为中文双引号 "…"。
815
+ - 英文单引号 ' 转换为中文单引号 '…'。
816
+ - 引号按出现顺序交替配对:首个为开引号,第二个为闭引号,以此类推。
817
+ 该启发式覆盖常见公文正文;已正确的全角引号不受影响。
818
+ """
819
+ if not text:
820
+ return text
821
+ out = []
822
+ double_open = True # 下一个双引号期待为开引号
823
+ single_open = True # 下一个单引号期待为开引号
824
+ for ch in text:
825
+ if ch == '"':
826
+ if double_open:
827
+ out.append('“') # "
828
+ else:
829
+ out.append('”') # "
830
+ double_open = not double_open
831
+ elif ch == "'":
832
+ if single_open:
833
+ out.append('‘') # '
834
+ else:
835
+ out.append('’') # '
836
+ single_open = not single_open
837
+ else:
838
+ out.append(ch)
839
+ return ''.join(out)
840
+
841
+
842
+ def is_plain_document_title(line):
843
+ """判断无 Markdown 标记时首个非空行是否像公文标题。"""
844
+ stripped = line.strip()
845
+ if not stripped or len(stripped) > 80:
846
+ return False
847
+ if stripped.endswith(('。', ';', ';', ':', ':')):
848
+ return False
849
+ title_suffixes = ('通知', '报告', '请示', '批复', '函', '意见', '方案', '总结', '纪要', '倡议书')
850
+ return stripped.endswith(title_suffixes)
851
+
852
+
853
+ def promote_plain_title(lines):
854
+ """没有 # 标题时,将首个疑似公文标题的非空行提升为标题。"""
855
+ for idx, line in enumerate(lines):
856
+ if not line.strip():
857
+ continue
858
+ if is_plain_document_title(line):
859
+ lines[idx] = f"# {line.strip()}"
860
+ return lines
861
+ return lines
862
+
863
+
864
+ def is_legacy_ai_disclaimer(line):
865
+ """过滤模型自行追加的旧版 AI 提示,统一由脚本在末尾生成规范提示。"""
866
+ stripped = line.strip()
867
+ return stripped in {
868
+ "---",
869
+ "内容由AI生成,仅供参考",
870
+ "内容由 AI 生成,仅供参考",
871
+ AI_DISCLAIMER_TEXT,
872
+ }
873
+
874
+
875
+ def is_recipient(line):
876
+ """判断是否为主送机关
877
+
878
+ 主送机关特征:
879
+ - 包含:政府、厅、局、委、办公室、机构等
880
+ - 以逗号、顿号分隔多个单位
881
+ - 以冒号结尾
882
+ """
883
+ stripped = line.strip()
884
+
885
+ # 必须以冒号结尾
886
+ if not stripped.endswith(':') and not stripped.endswith(':'):
887
+ return False
888
+
889
+ # 排除明显不是主送机关的句子
890
+ # 如:"现就...通知如下:"、"特此通知:"等
891
+ exclude_patterns = [
892
+ r'通知如下:?$',
893
+ r'决定如下:?$',
894
+ r'批复如下:?$',
895
+ r'意见如下:?$',
896
+ r'复函如下:?$',
897
+ r'函复如下:?$',
898
+ r'报告如下:?$',
899
+ r'请示如下:?$',
900
+ ]
901
+ if any(re.search(p, stripped) for p in exclude_patterns):
902
+ return False
903
+
904
+ # 占位示例或短主送机关也应识别,如“×××:”
905
+ if len(stripped) <= 30:
906
+ return True
907
+
908
+ # 包含主送机关关键词
909
+ keywords = ['政府', '厅', '局', '委', '办公室', '机构', '中心', '公司', '集团']
910
+ has_keyword = any(kw in stripped for kw in keywords)
911
+
912
+ if not has_keyword:
913
+ return False
914
+
915
+ # 排除过长的句子(主送机关通常不超过50字)
916
+ if len(stripped) > 50:
917
+ return False
918
+
919
+ return True
920
+
921
+
922
+ def validate_input(content_text: str) -> bool:
923
+ """验证输入内容"""
924
+ if len(content_text) > MAX_INPUT_LENGTH:
925
+ raise ValueError(f"输入内容过长({len(content_text):,} 字符)")
926
+ lines = content_text.split('\n')
927
+ if len(lines) > MAX_INPUT_LINES:
928
+ raise ValueError(f"输入行数过多({len(lines):,} 行)")
929
+ return True
930
+
931
+
932
+ def fix_reference_format(content_text: str) -> str:
933
+ """修复引用格式"""
934
+ def replace_ref(match):
935
+ ref_num = match.group(1)
936
+ return f'[^{ref_num}^]'
937
+ content_text = re.sub(r'\[\^(\d+)\](?!\^)', replace_ref, content_text)
938
+ content_text = re.sub(r'\[\^(\d+)\](?=\[\^\d+\])', replace_ref, content_text)
939
+ return content_text
940
+
941
+
942
+ LANDSCAPE_TABLE_MARKER = "<!-- landscape-table -->"
943
+ WIDE_TABLE_COLUMN_THRESHOLD = 6
944
+
945
+
946
+ def parse_markdown_table(lines, start_idx):
947
+ """
948
+ 从指定行开始解析Markdown表格,返回 (table_rows, alignments, next_idx)。
949
+
950
+ 支持格式:
951
+ | 列1 | 列2 | 列3 |
952
+ |-----|-----|-----|
953
+ | 数据 | 数据 | 数据 |
954
+
955
+ Returns:
956
+ list[list[str]]: 解析后的单元格内容(不含分隔行)
957
+ list[str|None]: Markdown 分隔行中提取的列对齐方式
958
+ int: 表格结束后的下一行索引;若start_idx不是表格行则返回 ([], start_idx)
959
+ """
960
+ if start_idx >= len(lines):
961
+ return [], [], start_idx
962
+
963
+ stripped = lines[start_idx].strip()
964
+ # 表格行必须以 | 开头(可选前导空格)
965
+ if not stripped.startswith('|'):
966
+ return [], [], start_idx
967
+
968
+ def split_table_row(line):
969
+ """拆分表格行,去掉首尾 | 并分割"""
970
+ s = line.strip()
971
+ if s.startswith('|'):
972
+ s = s[1:]
973
+ if s.endswith('|'):
974
+ s = s[:-1]
975
+ return [cell.strip() for cell in s.split('|')]
976
+
977
+ def is_separator(line):
978
+ """判断是否为分隔行(如 |---|---|---|)"""
979
+ s = line.strip()
980
+ if not s.startswith('|'):
981
+ return False
982
+ cells = split_table_row(s)
983
+ return all(re.match(r'^[-:]+$', c) for c in cells)
984
+
985
+ def parse_alignments(separator_line):
986
+ alignments = []
987
+ for cell in split_table_row(separator_line):
988
+ left = cell.startswith(':')
989
+ right = cell.endswith(':')
990
+ if left and right:
991
+ alignments.append('center')
992
+ elif right:
993
+ alignments.append('right')
994
+ elif left:
995
+ alignments.append('left')
996
+ else:
997
+ alignments.append(None)
998
+ return alignments
999
+
1000
+ rows = []
1001
+ alignments = []
1002
+ i = start_idx
1003
+ while i < len(lines):
1004
+ stripped = lines[i].strip()
1005
+ if not stripped.startswith('|'):
1006
+ break
1007
+ if is_separator(stripped):
1008
+ if not alignments:
1009
+ alignments = parse_alignments(stripped)
1010
+ i += 1
1011
+ continue
1012
+ rows.append(split_table_row(stripped))
1013
+ i += 1
1014
+
1015
+ # 至少要有2行(标题行 + 数据行)才算有效表格
1016
+ if len(rows) < 2:
1017
+ return [], [], start_idx
1018
+
1019
+ return rows, alignments, i
1020
+
1021
+
1022
+ def section_usable_width_dxa(section):
1023
+ """获取当前 section 可用正文宽度,单位 DXA/twips。"""
1024
+ return int(section.page_width.twips - section.left_margin.twips - section.right_margin.twips)
1025
+
1026
+
1027
+ def configure_section(section, landscape=False):
1028
+ """按公文版心配置 section,支持横向 A4 宽表页。"""
1029
+ page_width_mm, page_height_mm = get_page_size()
1030
+ margin_top, margin_bottom, margin_left, margin_right = get_page_margin()
1031
+ if landscape:
1032
+ section.orientation = WD_ORIENT.LANDSCAPE
1033
+ section.page_width = Mm(page_height_mm)
1034
+ section.page_height = Mm(page_width_mm)
1035
+ else:
1036
+ section.orientation = WD_ORIENT.PORTRAIT
1037
+ section.page_width = Mm(page_width_mm)
1038
+ section.page_height = Mm(page_height_mm)
1039
+ section.top_margin = Cm(margin_top / 10)
1040
+ section.bottom_margin = Cm(margin_bottom / 10)
1041
+ section.left_margin = Cm(margin_left / 10)
1042
+ section.right_margin = Cm(margin_right / 10)
1043
+
1044
+
1045
+ def add_landscape_section(doc):
1046
+ """新增横向 A4 section,并设置国标页码。"""
1047
+ section = doc.add_section(WD_SECTION.NEW_PAGE)
1048
+ configure_section(section, landscape=True)
1049
+ add_gbt_page_numbers(doc, section)
1050
+ return section
1051
+
1052
+
1053
+ def add_portrait_section(doc):
1054
+ """宽表结束后恢复竖向 A4 section。"""
1055
+ section = doc.add_section(WD_SECTION.NEW_PAGE)
1056
+ configure_section(section, landscape=False)
1057
+ add_gbt_page_numbers(doc, section)
1058
+ return section
1059
+
1060
+
1061
+ def set_table_width(table, width_dxa):
1062
+ tbl_pr = table._tbl.tblPr
1063
+ tbl_w = tbl_pr.find(qn('w:tblW'))
1064
+ if tbl_w is None:
1065
+ tbl_w = OxmlElement('w:tblW')
1066
+ tbl_pr.append(tbl_w)
1067
+ tbl_w.set(qn('w:type'), 'dxa')
1068
+ tbl_w.set(qn('w:w'), str(width_dxa))
1069
+
1070
+
1071
+ def set_table_cell_margins(table, top=80, start=120, bottom=80, end=120):
1072
+ tbl_pr = table._tbl.tblPr
1073
+ tbl_cell_mar = tbl_pr.find(qn('w:tblCellMar'))
1074
+ if tbl_cell_mar is None:
1075
+ tbl_cell_mar = OxmlElement('w:tblCellMar')
1076
+ tbl_pr.append(tbl_cell_mar)
1077
+ for margin_name, value in {
1078
+ 'top': top,
1079
+ 'start': start,
1080
+ 'bottom': bottom,
1081
+ 'end': end,
1082
+ }.items():
1083
+ node = tbl_cell_mar.find(qn(f'w:{margin_name}'))
1084
+ if node is None:
1085
+ node = OxmlElement(f'w:{margin_name}')
1086
+ tbl_cell_mar.append(node)
1087
+ node.set(qn('w:w'), str(value))
1088
+ node.set(qn('w:type'), 'dxa')
1089
+
1090
+
1091
+ def set_table_grid(table, col_widths):
1092
+ tbl_grid = table._tbl.tblGrid
1093
+ if tbl_grid is None:
1094
+ tbl_grid = OxmlElement('w:tblGrid')
1095
+ table._tbl.insert(1, tbl_grid)
1096
+ for child in list(tbl_grid):
1097
+ tbl_grid.remove(child)
1098
+ for width in col_widths:
1099
+ grid_col = OxmlElement('w:gridCol')
1100
+ grid_col.set(qn('w:w'), str(width))
1101
+ tbl_grid.append(grid_col)
1102
+
1103
+
1104
+ def set_cell_width(cell, width_dxa):
1105
+ tc_pr = cell._tc.get_or_add_tcPr()
1106
+ tc_w = tc_pr.find(qn('w:tcW'))
1107
+ if tc_w is None:
1108
+ tc_w = OxmlElement('w:tcW')
1109
+ tc_pr.append(tc_w)
1110
+ tc_w.set(qn('w:w'), str(width_dxa))
1111
+ tc_w.set(qn('w:type'), 'dxa')
1112
+
1113
+
1114
+ def set_row_cant_split(row):
1115
+ """尽量禁止 Word 将同一表格行拆到两页。"""
1116
+ tr_pr = row._tr.get_or_add_trPr()
1117
+ cant_split = tr_pr.find(qn('w:cantSplit'))
1118
+ if cant_split is None:
1119
+ cant_split = OxmlElement('w:cantSplit')
1120
+ tr_pr.append(cant_split)
1121
+
1122
+
1123
+ def set_table_rows_cant_split(table):
1124
+ """尽量保证同一单元格内容不跨页拆分。"""
1125
+ for row in table.rows:
1126
+ set_row_cant_split(row)
1127
+
1128
+
1129
+ def set_paragraph_keep_with_next(paragraph, keep=True):
1130
+ """让表题尽量和后续表格留在同一页。"""
1131
+ paragraph.paragraph_format.keep_with_next = keep
1132
+
1133
+
1134
+ def text_width_score(text):
1135
+ """估算单元格内容宽度;中文按 2,ASCII 按 1。"""
1136
+ score = 0
1137
+ for char in str(text):
1138
+ score += 1 if ord(char) < 128 else 2
1139
+ return score
1140
+
1141
+
1142
+ def compute_column_widths(table_rows, usable_width_dxa):
1143
+ num_cols = max(len(row) for row in table_rows)
1144
+ scores = []
1145
+ for col_idx in range(num_cols):
1146
+ values = [row[col_idx] if col_idx < len(row) else '' for row in table_rows]
1147
+ max_score = max(text_width_score(value) for value in values) if values else 4
1148
+ avg_score = sum(text_width_score(value) for value in values) / max(len(values), 1)
1149
+ scores.append(max(6, min(28, max_score * 0.65 + avg_score * 0.35)))
1150
+
1151
+ total_score = sum(scores) or num_cols
1152
+ min_width = 900 if num_cols <= 6 else 700
1153
+ widths = [max(min_width, int(usable_width_dxa * score / total_score)) for score in scores]
1154
+ total_width = sum(widths)
1155
+ if total_width != usable_width_dxa and total_width > 0:
1156
+ widths[-1] += usable_width_dxa - total_width
1157
+ return widths
1158
+
1159
+
1160
+ def infer_column_alignment(table_rows, alignments, col_idx):
1161
+ if col_idx < len(alignments) and alignments[col_idx]:
1162
+ return alignments[col_idx]
1163
+
1164
+ values = [row[col_idx].strip() for row in table_rows[1:] if col_idx < len(row) and row[col_idx].strip()]
1165
+ if values and all(re.match(r'^[+-]?\d+(?:\.\d+)?%?$|^[\d,,.]+$', value) for value in values):
1166
+ return 'right'
1167
+ if values and max(text_width_score(value) for value in values) <= 12:
1168
+ return 'center'
1169
+ return 'left'
1170
+
1171
+
1172
+ def alignment_to_word(alignment):
1173
+ return {
1174
+ 'center': WD_ALIGN_PARAGRAPH.CENTER,
1175
+ 'right': WD_ALIGN_PARAGRAPH.RIGHT,
1176
+ 'left': WD_ALIGN_PARAGRAPH.LEFT,
1177
+ }.get(alignment, WD_ALIGN_PARAGRAPH.LEFT)
1178
+
1179
+
1180
+ def should_use_landscape_table(table_rows, forced_landscape=False):
1181
+ if forced_landscape:
1182
+ return True
1183
+ num_cols = max(len(row) for row in table_rows)
1184
+ return num_cols > WIDE_TABLE_COLUMN_THRESHOLD
1185
+
1186
+
1187
+ def is_table_caption(text):
1188
+ """识别表题,如“表1 五省粮食产量对比”。"""
1189
+ return bool(re.match(r'^表\s*\d+\s+.+', text.strip()))
1190
+
1191
+
1192
+ def delete_paragraph(paragraph):
1193
+ """从文档中删除指定段落。"""
1194
+ p = paragraph._element
1195
+ p.getparent().remove(p)
1196
+ paragraph._p = paragraph._element = None
1197
+
1198
+
1199
+ def pop_trailing_table_caption(doc):
1200
+ """
1201
+ 如果文档末尾最近一个可见段落是表题,则移除并返回其文本。
1202
+ 用于宽表自动横排时,把已写入竖版页的表题移入横版页。
1203
+ """
1204
+ for paragraph in reversed(doc.paragraphs):
1205
+ text = paragraph.text.strip()
1206
+ if not text:
1207
+ continue
1208
+ if is_table_caption(text):
1209
+ delete_paragraph(paragraph)
1210
+ return text
1211
+ return None
1212
+ return None
1213
+
1214
+
1215
+ def add_table_caption(doc, caption, body_font, body_size):
1216
+ """添加表题。表题是普通文字,不设置大纲级别。"""
1217
+ if not caption:
1218
+ return
1219
+ para = doc.add_paragraph()
1220
+ add_formatted_text(para, caption, body_font, body_size)
1221
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.CENTER, line_spacing=body_size + 12)
1222
+ set_paragraph_keep_with_next(para)
1223
+
1224
+
1225
+ def next_table_number(doc):
1226
+ """根据已写入文档的表题计算下一个表格编号。"""
1227
+ numbers = []
1228
+ for paragraph in doc.paragraphs:
1229
+ match = re.match(r'^表\s*(\d+)\s+.+', paragraph.text.strip())
1230
+ if match:
1231
+ numbers.append(int(match.group(1)))
1232
+ return max(numbers, default=0) + 1
1233
+
1234
+
1235
+ def fallback_table_caption(doc):
1236
+ """当模型漏写表题时生成兜底表题,避免无名表格进入正式 Word。"""
1237
+ return f"表{next_table_number(doc)} 主要情况汇总"
1238
+
1239
+
1240
+ def add_word_table(doc, table_rows, alignments, body_font, body_size, landscape=False, caption=None):
1241
+ """
1242
+ 将解析后的表格数据添加为Word原生表格。
1243
+
1244
+ 首行作为表头(加粗),其余为数据行。
1245
+ 所有单元格使用公文字体。
1246
+
1247
+ Args:
1248
+ doc: Document 对象
1249
+ table_rows: list[list[str]], 解析后的表格数据
1250
+ body_font: 正文字体名
1251
+ body_size: 正文字号(pt)
1252
+ landscape: 是否为宽表单独使用横向 A4 页面
1253
+ caption: 随表格一起写入的表题
1254
+ """
1255
+ num_cols = max(len(row) for row in table_rows)
1256
+ table_font_size = 15 if landscape or num_cols > WIDE_TABLE_COLUMN_THRESHOLD else body_size
1257
+
1258
+ if landscape:
1259
+ caption = caption or pop_trailing_table_caption(doc)
1260
+ caption = caption or fallback_table_caption(doc)
1261
+ add_landscape_section(doc)
1262
+ add_table_caption(doc, caption, body_font, body_size)
1263
+ else:
1264
+ caption = caption or pop_trailing_table_caption(doc)
1265
+ caption = caption or fallback_table_caption(doc)
1266
+ add_table_caption(doc, caption, body_font, body_size)
1267
+
1268
+ table = doc.add_table(rows=len(table_rows), cols=num_cols)
1269
+ table.style = 'Table Grid'
1270
+ table.alignment = WD_TABLE_ALIGNMENT.CENTER
1271
+ table.autofit = False
1272
+ usable_width = section_usable_width_dxa(doc.sections[-1])
1273
+ col_widths = compute_column_widths(table_rows, usable_width)
1274
+ set_table_width(table, usable_width)
1275
+ set_table_grid(table, col_widths)
1276
+ set_table_cell_margins(table)
1277
+
1278
+ for row_idx, row_data in enumerate(table_rows):
1279
+ for col_idx in range(num_cols):
1280
+ cell = table.rows[row_idx].cells[col_idx]
1281
+ cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
1282
+ set_cell_width(cell, col_widths[col_idx])
1283
+ # 清空默认段落
1284
+ cell.paragraphs[0].clear()
1285
+ text = row_data[col_idx] if col_idx < len(row_data) else ''
1286
+ alignment = 'center' if row_idx == 0 else infer_column_alignment(table_rows, alignments, col_idx)
1287
+ paragraph = cell.paragraphs[0]
1288
+ paragraph.alignment = alignment_to_word(alignment)
1289
+ add_formatted_text(paragraph, text, body_font, table_font_size, bold=(row_idx == 0))
1290
+ set_paragraph_format(
1291
+ paragraph,
1292
+ first_line_indent=False,
1293
+ alignment=alignment_to_word(alignment),
1294
+ line_spacing=table_font_size + 6,
1295
+ )
1296
+ set_table_rows_cant_split(table)
1297
+
1298
+ # 表格后加一个空段落,与后续内容保持间距
1299
+ spacer = doc.add_paragraph()
1300
+ set_paragraph_format(spacer, first_line_indent=False, line_spacing=body_size + 8)
1301
+
1302
+ if landscape:
1303
+ add_portrait_section(doc)
1304
+
1305
+
1306
+ def set_paragraph_mark_font(para, font_name, font_size):
1307
+ """设置空段落的段落标记字体,避免空行高度受默认样式影响。"""
1308
+ pPr = para._p.get_or_add_pPr()
1309
+ rPr = pPr.find(qn('w:rPr'))
1310
+ if rPr is None:
1311
+ rPr = OxmlElement('w:rPr')
1312
+ pPr.append(rPr)
1313
+
1314
+ rFonts = rPr.find(qn('w:rFonts'))
1315
+ if rFonts is None:
1316
+ rFonts = OxmlElement('w:rFonts')
1317
+ rPr.append(rFonts)
1318
+ latin_font = get_latin_font_config()
1319
+ rFonts.set(qn('w:ascii'), latin_font)
1320
+ rFonts.set(qn('w:hAnsi'), latin_font)
1321
+ rFonts.set(qn('w:eastAsia'), font_name)
1322
+ rFonts.set(qn('w:cs'), font_name)
1323
+
1324
+ for tag in ('w:sz', 'w:szCs'):
1325
+ elem = rPr.find(qn(tag))
1326
+ if elem is None:
1327
+ elem = OxmlElement(tag)
1328
+ rPr.append(elem)
1329
+ elem.set(qn('w:val'), str(int(font_size * 2)))
1330
+
1331
+
1332
+ def add_blank_paragraphs(doc, count, line_spacing, font_name=None, font_size=None):
1333
+ """插入指定数量的空段,用于公文固定空行。"""
1334
+ for _ in range(count):
1335
+ para = doc.add_paragraph()
1336
+ set_paragraph_format(para, first_line_indent=False, line_spacing=line_spacing)
1337
+ if font_name and font_size:
1338
+ set_paragraph_mark_font(para, font_name, font_size)
1339
+
1340
+
1341
+ def create_document(content_text, output_path=None):
1342
+ """
1343
+ 创建排版后的普通公文文档(无红头)
1344
+
1345
+ Args:
1346
+ content_text: 正文内容(Markdown格式)
1347
+ output_path: 输出文件路径
1348
+
1349
+ Returns:
1350
+ 输出文件路径
1351
+ """
1352
+ content_text = normalize_content_text(content_text)
1353
+ validate_input(content_text)
1354
+ content_text = fix_reference_format(content_text)
1355
+
1356
+ doc = Document()
1357
+
1358
+ # 设置 A4 纸张和页边距(公文格式规范)
1359
+ for section in doc.sections:
1360
+ configure_section(section, landscape=False)
1361
+ add_gbt_page_numbers(doc, section)
1362
+
1363
+ # 处理正文内容
1364
+ lines = content_text.strip().split('\n')
1365
+ default_title = extract_document_title(lines)
1366
+ if not has_markdown_title(lines):
1367
+ inferred_title = infer_title_from_output_path(output_path)
1368
+ before = list(lines)
1369
+ lines = promote_plain_title(lines)
1370
+ if before == lines and inferred_title:
1371
+ lines = [f"# {inferred_title}", ""] + lines
1372
+ i = 0
1373
+ line_count = len(lines)
1374
+
1375
+ # 从配置获取字体信息
1376
+ title_font, title_size, _ = get_font_config('title')
1377
+ title_line_spacing = FORMAT_CONFIG['title'].get('line_spacing_pt', 33) if FORMAT_CONFIG and 'title' in FORMAT_CONFIG else 33
1378
+ body_font, body_size, _ = get_font_config('body')
1379
+ h1_font, h1_size, _ = get_font_config('heading1')
1380
+ h2_font, h2_size, _ = get_font_config('heading2')
1381
+ h3_font, h3_size, h3_bold = get_font_config('heading3')
1382
+ body_line_spacing = FORMAT_CONFIG['body']['line_spacing_pt'] if FORMAT_CONFIG else 28
1383
+
1384
+ # 独立素材说明不是正文附录,保留专用排版但不在首个栏目之前分页。
1385
+ standalone_source_note = is_standalone_source_note(output_path)
1386
+ # 附录区域标志:素材使用情况、参考来源和知识专库链接统一靠左排版
1387
+ in_appendix_section = False
1388
+ # 知识专库链接区域标志:URL 生成可点击蓝链
1389
+ in_kb_section = False
1390
+ # 知识专库链接前一行标签,用于显示为“标题(点击打开)”
1391
+ pending_kb_label = None
1392
+ kb_link_count = 0
1393
+ # 附件正文首页“附件”后的下一行作为附件标题处理
1394
+ awaiting_attachment_title = False
1395
+ # 正文末尾附件目录后,落款前需要固定空三行
1396
+ attachment_list_pending_sign_gap = False
1397
+ # 表格前一行使用 <!-- landscape-table --> 时,强制下一张表横排。
1398
+ force_next_table_landscape = False
1399
+ pending_landscape_table_caption = None
1400
+
1401
+ while i < line_count:
1402
+ line = lines[i]
1403
+ stripped = line.strip()
1404
+ line_type = get_line_type(stripped)
1405
+
1406
+ if is_legacy_ai_disclaimer(stripped):
1407
+ i += 1
1408
+ continue
1409
+
1410
+ if stripped == LANDSCAPE_TABLE_MARKER:
1411
+ force_next_table_landscape = True
1412
+ i += 1
1413
+ continue
1414
+
1415
+ if force_next_table_landscape and is_table_caption(stripped):
1416
+ pending_landscape_table_caption = stripped
1417
+ i += 1
1418
+ continue
1419
+
1420
+ # Markdown表格检测(必须在其他判断之前)
1421
+ if stripped.startswith('|'):
1422
+ table_rows, alignments, next_i = parse_markdown_table(lines, i)
1423
+ if table_rows:
1424
+ use_landscape = should_use_landscape_table(table_rows, force_next_table_landscape)
1425
+ add_word_table(
1426
+ doc,
1427
+ table_rows,
1428
+ alignments,
1429
+ body_font,
1430
+ body_size,
1431
+ landscape=use_landscape,
1432
+ caption=pending_landscape_table_caption if use_landscape else None,
1433
+ )
1434
+ force_next_table_landscape = False
1435
+ pending_landscape_table_caption = None
1436
+ i = next_i
1437
+ continue
1438
+ # 不是有效表格,当普通文本处理,继续往下走
1439
+
1440
+ # 空行
1441
+ if line_type == 'empty':
1442
+ i += 1
1443
+ continue
1444
+
1445
+ if (
1446
+ attachment_list_pending_sign_gap
1447
+ and not is_attachment_line(stripped)
1448
+ and not is_attachment_continuation(stripped)
1449
+ ):
1450
+ if is_signing_entity(stripped):
1451
+ add_blank_paragraphs(doc, 3, body_line_spacing, body_font, body_size)
1452
+ elif is_date_line(stripped):
1453
+ add_blank_paragraphs(doc, 3, body_line_spacing, body_font, body_size)
1454
+ para = doc.add_paragraph()
1455
+ para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
1456
+ add_formatted_text(para, stripped, body_font, body_size)
1457
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.RIGHT, line_spacing=body_line_spacing)
1458
+ attachment_list_pending_sign_gap = False
1459
+ i += 1
1460
+ continue
1461
+ attachment_list_pending_sign_gap = False
1462
+
1463
+ if awaiting_attachment_title:
1464
+ para = doc.add_paragraph()
1465
+ para.alignment = WD_ALIGN_PARAGRAPH.CENTER
1466
+ add_formatted_text(para, stripped, title_font, title_size)
1467
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.CENTER, line_spacing=title_line_spacing)
1468
+ set_outline_level(para, 0)
1469
+ awaiting_attachment_title = False
1470
+ i += 1
1471
+ continue
1472
+
1473
+ marker_text = strip_markdown_heading(stripped)
1474
+ if marker_text in ("素材使用情况", "参考资料", "参考来源"):
1475
+ if not standalone_source_note:
1476
+ add_page_break_if_needed(doc, body_line_spacing)
1477
+ in_appendix_section = True
1478
+ para = doc.add_paragraph()
1479
+ label = "【素材使用情况】" if marker_text == "素材使用情况" else f"【{marker_text}】"
1480
+ add_formatted_text(para, label, body_font, body_size)
1481
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.LEFT, line_spacing=body_line_spacing)
1482
+ i += 1
1483
+ continue
1484
+
1485
+ if marker_text == "知识专库链接":
1486
+ if not in_appendix_section and not standalone_source_note:
1487
+ add_page_break_if_needed(doc, body_line_spacing)
1488
+ in_appendix_section = True
1489
+ in_kb_section = True
1490
+ pending_kb_label = None
1491
+ kb_link_count = 0
1492
+ para = doc.add_paragraph()
1493
+ add_formatted_text(para, "【知识专库链接】", body_font, body_size)
1494
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.LEFT, line_spacing=body_line_spacing)
1495
+ i += 1
1496
+ continue
1497
+
1498
+ # 检测附录区域开始
1499
+ if (
1500
+ re.match(r'^【素材使用情况】', stripped)
1501
+ or re.match(r'^【参考资料】', stripped)
1502
+ or re.match(r'^【参考来源】', stripped)
1503
+ or stripped in ("素材使用情况", "参考资料", "参考来源")
1504
+ ):
1505
+ if not in_appendix_section and not standalone_source_note:
1506
+ add_page_break_if_needed(doc, body_line_spacing)
1507
+ in_appendix_section = True
1508
+
1509
+ # 检测【知识专库链接】区域开始
1510
+ if re.match(r'^【知识专库链接】', stripped):
1511
+ if not in_appendix_section and not standalone_source_note:
1512
+ add_page_break_if_needed(doc, body_line_spacing)
1513
+ in_appendix_section = True
1514
+ in_kb_section = True
1515
+ pending_kb_label = None
1516
+ kb_link_count = 0
1517
+
1518
+ # 附录区域:统一靠左排版;知识专库 URL 生成可点击蓝链。
1519
+ # 必须早于标题识别,避免“15. XXX”这类素材编号被误判为三级标题。
1520
+ if in_appendix_section:
1521
+ if in_kb_section and re.search(r'https?://', stripped):
1522
+ url_match = re.search(r'(https?://\S+)', stripped)
1523
+ if url_match:
1524
+ url = sanitize_url(url_match.group(1))
1525
+ if is_internal_search_endpoint(url):
1526
+ i += 1
1527
+ continue
1528
+ kb_link_count += 1
1529
+ para = doc.add_paragraph()
1530
+ add_hyperlink(
1531
+ para,
1532
+ url,
1533
+ hyperlink_display_text(pending_kb_label, kb_link_count),
1534
+ font_name=body_font,
1535
+ font_size=body_size,
1536
+ )
1537
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.LEFT, line_spacing=body_line_spacing)
1538
+ pending_kb_label = None
1539
+ i += 1
1540
+ continue
1541
+
1542
+ para = doc.add_paragraph()
1543
+ clean_text = normalize_appendix_text(stripped)
1544
+ if in_kb_section and is_useless_kb_label_line(clean_text):
1545
+ i += 1
1546
+ continue
1547
+ add_formatted_text(para, clean_text, body_font, body_size)
1548
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.LEFT, line_spacing=body_line_spacing)
1549
+ if in_kb_section and clean_text and not clean_text.startswith("【") and not is_generic_kb_label(clean_text):
1550
+ pending_kb_label = clean_text
1551
+ i += 1
1552
+ continue
1553
+
1554
+ # 附件清单续行要先于三级标题识别,避免 “2.附件名” 被误判为三级标题。
1555
+ # 仅在已识别到正文末尾“附件:”清单后生效,避免普通正文连续编号被误排为附件续行。
1556
+ if attachment_list_pending_sign_gap and i > 0 and is_attachment_continuation(stripped):
1557
+ prev_non_empty = ""
1558
+ for prev_idx in range(i - 1, -1, -1):
1559
+ prev_non_empty = lines[prev_idx].strip()
1560
+ if prev_non_empty:
1561
+ break
1562
+ if is_attachment_line(prev_non_empty) or is_attachment_continuation(prev_non_empty):
1563
+ para = doc.add_paragraph()
1564
+ add_formatted_text(para, f" {stripped}", body_font, body_size)
1565
+ set_attachment_list_format(para, continuation=True, line_spacing=body_line_spacing)
1566
+ attachment_list_pending_sign_gap = True
1567
+ i += 1
1568
+ continue
1569
+
1570
+ # 公文标题(# 标题)
1571
+ if line_type == 'title':
1572
+ content = strip_markdown_heading(stripped)
1573
+ para = doc.add_paragraph()
1574
+ para.alignment = WD_ALIGN_PARAGRAPH.CENTER
1575
+ add_formatted_text(para, content, title_font, title_size)
1576
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.CENTER, line_spacing=title_line_spacing)
1577
+ set_outline_level(para, 0) # 文档标题设为1级
1578
+ add_blank_paragraphs(doc, 1, body_line_spacing, body_font, body_size)
1579
+ i += 1
1580
+ continue
1581
+
1582
+ # 一级标题(## 一、XXX)
1583
+ if line_type == 'heading1':
1584
+ content = strip_markdown_heading(stripped)
1585
+ para = doc.add_paragraph()
1586
+ add_formatted_text(para, content, h1_font, h1_size)
1587
+ set_paragraph_format(para, indent_chars=2, line_spacing=body_line_spacing)
1588
+ set_outline_level(para, 1) # 一级标题设为2级
1589
+ i += 1
1590
+ continue
1591
+
1592
+ # 二级标题(### (一)XXX)
1593
+ if line_type == 'heading2':
1594
+ content = strip_markdown_heading(stripped)
1595
+ para = doc.add_paragraph()
1596
+ add_formatted_text(para, content, h2_font, h2_size)
1597
+ set_paragraph_format(para, indent_chars=2, line_spacing=body_line_spacing)
1598
+ set_outline_level(para, 2) # 二级标题设为3级
1599
+ i += 1
1600
+ continue
1601
+
1602
+ # 三级标题(#### 1.XXX)
1603
+ if line_type == 'heading3':
1604
+ content = strip_markdown_heading(stripped)
1605
+ para = doc.add_paragraph()
1606
+ add_formatted_text(para, content, h3_font, h3_size, bold=h3_bold)
1607
+ set_paragraph_format(para, indent_chars=2, line_spacing=body_line_spacing)
1608
+ set_outline_level(para, 3) # 三级标题设为4级
1609
+ i += 1
1610
+ continue
1611
+
1612
+ # 附件
1613
+ if is_attachment_line(stripped):
1614
+ add_blank_paragraphs(doc, 1, body_line_spacing, body_font, body_size)
1615
+ para = doc.add_paragraph()
1616
+ add_formatted_text(para, stripped, body_font, body_size)
1617
+ set_attachment_list_format(para, continuation=False, line_spacing=body_line_spacing)
1618
+ attachment_list_pending_sign_gap = True
1619
+ i += 1
1620
+ continue
1621
+
1622
+ if is_attachment_section_title(stripped):
1623
+ if document_has_visible_content(doc):
1624
+ page_break_para = doc.add_paragraph()
1625
+ page_break_run = page_break_para.add_run()
1626
+ page_break_run.add_break(WD_BREAK.PAGE)
1627
+ set_paragraph_format(page_break_para, first_line_indent=False, line_spacing=body_line_spacing)
1628
+ para = doc.add_paragraph()
1629
+ add_formatted_text(para, stripped, h1_font, h1_size)
1630
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.LEFT, line_spacing=body_line_spacing)
1631
+ awaiting_attachment_title = True
1632
+ i += 1
1633
+ continue
1634
+
1635
+ # 落款单位
1636
+ if is_signing_entity(stripped):
1637
+ para = doc.add_paragraph()
1638
+ para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
1639
+ add_formatted_text(para, stripped, body_font, body_size)
1640
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.RIGHT, line_spacing=body_line_spacing)
1641
+ i += 1
1642
+ continue
1643
+
1644
+ # 联系信息
1645
+ if is_contact_info(stripped):
1646
+ para = doc.add_paragraph()
1647
+ para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
1648
+ add_formatted_text(para, stripped, body_font, body_size)
1649
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.RIGHT, line_spacing=body_line_spacing)
1650
+ i += 1
1651
+ continue
1652
+
1653
+ # 落款日期:优先根据前一行落款单位和后续附录标记判断,避免素材页影响位置比例
1654
+ if should_right_align_date(lines, i):
1655
+ para = doc.add_paragraph()
1656
+ para.alignment = WD_ALIGN_PARAGRAPH.RIGHT
1657
+ add_formatted_text(para, stripped, body_font, body_size)
1658
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.RIGHT, line_spacing=body_line_spacing)
1659
+ i += 1
1660
+ continue
1661
+
1662
+ # 分页符标记
1663
+ if stripped == '[分页符]':
1664
+ para = doc.add_paragraph()
1665
+ run = para.add_run()
1666
+ run.add_break(WD_BREAK.PAGE)
1667
+ i += 1
1668
+ continue
1669
+
1670
+ # 主送机关(前10行内)
1671
+ if is_recipient(stripped) and i < 10:
1672
+ para = doc.add_paragraph()
1673
+ add_formatted_text(para, stripped, body_font, body_size)
1674
+ set_paragraph_format(para, first_line_indent=False, alignment=WD_ALIGN_PARAGRAPH.LEFT, line_spacing=body_line_spacing)
1675
+ i += 1
1676
+ continue
1677
+
1678
+ # 普通正文
1679
+ # 清理Markdown加粗标记
1680
+ clean_text = strip_markdown_bold(stripped)
1681
+ para = doc.add_paragraph()
1682
+ add_formatted_text(para, clean_text, body_font, body_size)
1683
+ set_paragraph_format(para, indent_chars=2, alignment=WD_ALIGN_PARAGRAPH.JUSTIFY, line_spacing=body_line_spacing)
1684
+ i += 1
1685
+
1686
+ # 保存文件
1687
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
1688
+ if not output_path:
1689
+ default_stem = default_title or f'公文_{timestamp}'
1690
+ output_path = os.path.join(get_configured_output_dir(), f'{default_stem}.docx')
1691
+
1692
+ output_path = resolve_output_path(output_path)
1693
+
1694
+ if not output_path.lower().endswith('.docx'):
1695
+ output_path = output_path.rsplit('.', 1)[0] + '.docx' if '.' in output_path else output_path + '.docx'
1696
+
1697
+ # 添加版本号(如果文件已存在)
1698
+ output_path = get_next_version(output_path)
1699
+
1700
+ output_dir = os.path.dirname(output_path)
1701
+ if output_dir and not os.path.exists(output_dir):
1702
+ os.makedirs(output_dir, exist_ok=True)
1703
+
1704
+ add_ai_disclaimer(doc)
1705
+ set_document_core_properties(doc, default_title)
1706
+ doc.save(output_path)
1707
+ return display_path(output_path)
1708
+
1709
+
1710
+ def main():
1711
+ """命令行入口"""
1712
+ parser = argparse.ArgumentParser(description='公文排版工具 v2.0.0 - 只支持普通格式')
1713
+ parser.add_argument('input', nargs='?', help='输入文件路径')
1714
+ parser.add_argument('--output', help='输出文件路径')
1715
+ parser.add_argument('--text', help='直接输入公文文本(如果是文件路径会自动读取)')
1716
+
1717
+ args = parser.parse_args()
1718
+
1719
+ if args.text:
1720
+ # 智能检测:如果 --text 是文件路径,自动读取文件内容
1721
+ try:
1722
+ text_path = resolve_input_text_path(args.text)
1723
+ except ValueError:
1724
+ text_path = None
1725
+ if text_path and os.path.exists(text_path) and os.path.isfile(text_path):
1726
+ print(f'⚠ 检测到 --text 参数是文件路径,自动读取文件内容: {text_path}')
1727
+ with open(text_path, 'r', encoding='utf-8') as f:
1728
+ content = f.read()
1729
+ else:
1730
+ content = args.text
1731
+ elif args.input:
1732
+ input_path = resolve_input_text_path(args.input)
1733
+ if os.path.exists(input_path):
1734
+ with open(input_path, 'r', encoding='utf-8') as f:
1735
+ content = f.read()
1736
+ else:
1737
+ raise FileNotFoundError(f"输入文件不存在: {input_path}")
1738
+ else:
1739
+ parser.print_help()
1740
+ sys.exit(1)
1741
+
1742
+ try:
1743
+ output_path = create_document(
1744
+ content,
1745
+ output_path=args.output
1746
+ )
1747
+
1748
+ print(f'✓ 普通公文已生成: {output_path}')
1749
+ except Exception as e:
1750
+ print(f'✗ 生成失败: {e}')
1751
+ import traceback
1752
+ traceback.print_exc()
1753
+
1754
+
1755
+ if __name__ == '__main__':
1756
+ main()