delivery_docs_build.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. r"""交付文档构建器:`docs/src/*.md` → `docs/*.docx`(用户令 2026-09-22)。
  4. ## 为什么要有它(而不是拿 Word 手排)
  5. 用户令要求三份文档「区分章节目录、文表图并茂、字体字号分类统一」。手排的三份文档**必然**字体字号漂移、
  6. 图表编号对不上、改一处忘一处。所以内容用 markdown 写(可 diff、进版本库),排版由本器**一套样式表**统一执行:
  7. | 元素 | 字体 | 字号 | 对齐 / 缩进 |
  8. |---|---|---|---|
  9. | 封面标题 | 黑体 | 小一(26pt) | 居中 |
  10. | 章标题(一级 `##`) | 黑体 | 三号(16pt) | 左对齐,**章前分页** |
  11. | 节标题(二级 `###`) | 黑体 | 四号(14pt) | 左对齐 |
  12. | 小节标题(三级 `####`) | 黑体 | 小四(12pt) 加粗 | 左对齐 |
  13. | 正文 | 宋体 | 小四(12pt) | 首行缩进 2 字符、1.5 倍行距、两端对齐 |
  14. | 列表 | 宋体 | 小四(12pt) | 悬挂缩进 |
  15. | 表题(表上方) | 黑体 | 五号(10.5pt) | 居中 |
  16. | 表头 | 黑体 | 五号(10.5pt) 加粗 | 居中 + 浅灰底纹 + 跨页重复 |
  17. | 表格正文 | 宋体 | 五号(10.5pt)(≥6 列降 9pt) | 左对齐 |
  18. | 图(居中)与图题(图下方) | 黑体 | 五号(10.5pt) | 居中 |
  19. | 页眉 / 页脚页码 | 宋体 | 小五(9pt) | 居中 |
  20. 英文与数字用 Times New Roman(中式公文惯例:中文宋体/黑体 + 西文 Times New Roman)。
  21. ## markdown 约定(渲染器支持的子集,写手必须照此写)
  22. # 文档标题 (只此一处,进封面)
  23. ## 1 章 / ### 1.1 节 / #### 1.1.1 小节
  24. 普通段落(一行一段,段间空行)
  25. - 无序项 1. 有序项
  26. | 表头 | 表头 | + |---| 分隔行 → 表格
  27. **表 3-1 标题**(紧挨表格上方一行) → 表题
  28. ![图 3-1 标题](figures/xxx.png) → 图片 + 图题
  29. > 引用段
  30. --- → 忽略
  31. ## 用法
  32. python scripts/delivery_docs_build.py # 三份全渲染
  33. python scripts/delivery_docs_build.py --only req # 只渲染一份 (req/des/dat)
  34. python scripts/delivery_docs_build.py --check # 只体检源件(章/节/表/图/字数、图是否在位)
  35. python scripts/delivery_docs_build.py --spec # 打印本器的排版规范表
  36. 退出码: 0 全部成功 · 5 有源件缺件/图缺件(逐条打印,仍会尽力渲染其余内容)
  37. """
  38. from __future__ import annotations
  39. try:
  40. from app_common.common.app_common_guanlan.api import install_root as _install_root
  41. except ImportError: # 理论不可达;包结构异常时回退到按位置上跳
  42. from pathlib import Path as _P
  43. def _install_root(_f): return _P(_f).resolve().parents[4]
  44. import argparse
  45. import pathlib
  46. import re
  47. import sys
  48. ROOT = _install_root(__file__)
  49. from docx import Document # noqa: E402
  50. from docx.enum.section import WD_SECTION # noqa: E402
  51. from docx.enum.table import WD_TABLE_ALIGNMENT # noqa: E402
  52. from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING # noqa: E402
  53. from docx.oxml import OxmlElement # noqa: E402
  54. from docx.oxml.ns import qn # noqa: E402
  55. from docx.shared import Cm, Pt, RGBColor # noqa: E402
  56. VERSION = __import__('importlib').import_module('src.version').VERSION
  57. HEI, SONG, WEST = '黑体', '宋体', 'Times New Roman'
  58. SZ = dict(cover=26, h1=16, h2=14, h3=12, body=12, table=10.5, table_small=9, caption=10.5, header=9)
  59. DOCS = {
  60. 'req': dict(src='docs/src/需求分析_观澜_{v}.md', out='docs/需求分析_观澜_{v}.docx',
  61. title='需求分析', subtitle='观澜 v2 · 风电场智能分析系统'),
  62. 'des': dict(src='docs/src/系统设计说明_观澜_{v}.md', out='docs/系统设计说明_观澜_{v}.docx',
  63. title='系统设计说明', subtitle='观澜 v2 · 风电场智能分析系统'),
  64. 'dat': dict(src='docs/src/数据要求说明_观澜_{v}.md', out='docs/数据要求说明_观澜_{v}.docx',
  65. title='数据要求说明',
  66. subtitle='观澜 v2 · 风电场智能分析系统(结合现场《数据分析收资要求-v3》)',
  67. # ★2026-09-22 用户令: 这份是**纯数据需求规格** —— 不体现样本场接入情况, 也不体现实现细节。
  68. # 下面这组模式由 `--check`/`--verify` 机器扫描, 命中即 FAIL(不靠人自觉)。
  69. strict_terms=True),
  70. }
  71. # 数据要求说明的"不得出现"模式(用户令 2026-09-22):
  72. # 英文测点名称 / 文件名称 / 落盘位置 / 机组名称编号 / 样本场现状字样。
  73. # 中文业务含义名称与「中文(英文简写)」(如 平均无故障间隔(MTBF))不在禁止之列。
  74. STRICT_PATTERNS = (
  75. ('英文测点标识(snake_case)', r'\b[a-z][a-z0-9]*_[a-z0-9_]+\b'),
  76. ('文件扩展名', r'\.(csv|parquet|json|yaml|yml|xlsx|xls|pdf|mdb|xml|docx|doc)\b'),
  77. ('目录/落盘位置', r'(data/raw|outputs/|configs/|scripts/|reference/|docs/|data\\)'),
  78. ('机组名称/编号', r'(WTG\d+|\b\d{2}[A-Z]\b)'),
  79. ('样本场现状字样', r'(已在位|未到位|现状|实测|样本场|本场|催缴)'),
  80. )
  81. # ★去标识化词表(用户令 2026-09-22「内容参考如东风电场,但不体现如东风电场」):
  82. # 三份文档是**对外**交付件, 不得出现样本场的中文名、罗马化形态、业主、地域、OEM 与第三方机构名。
  83. # 词表放在代码里 ⇒ `--check`/`--verify` 与 `guanlan.py check` 都会机器扫描, 不靠人自觉。
  84. # ★2026-09-22 补(数据要求说明起草时实逮): 样本场 CMS 导出包名是 `CMS_RuDong_CGN_202603-04`
  85. # —— **大小写混合**的罗马化场名/业主缩写能绕过精确匹配,所以匹配一律**大小写不敏感**(见 forbidden_hits)。
  86. FORBIDDEN = ('如东', '如海', '广核', '江苏', 'rudong', 'cgn',
  87. '西门子', '上海电气', 'swt', '大生', '4.0-130')
  88. SPEC_ROWS = [
  89. ('封面标题', '黑体', '小一(26pt)', '居中'),
  90. ('章标题(一级)', '黑体', '三号(16pt)', '左对齐,章前分页'),
  91. ('节标题(二级)', '黑体', '四号(14pt)', '左对齐'),
  92. ('小节标题(三级)', '黑体', '小四(12pt)加粗', '左对齐'),
  93. ('正文', '宋体(西文 Times New Roman)', '小四(12pt)', '首行缩进 2 字符,1.5 倍行距,两端对齐'),
  94. ('列表', '宋体', '小四(12pt)', '悬挂缩进 0.74 cm'),
  95. ('表题', '黑体', '五号(10.5pt)', '居中,置于表格上方'),
  96. ('表头', '黑体', '五号(10.5pt)加粗', '居中,浅灰底纹,跨页重复'),
  97. ('表格正文', '宋体', '五号(10.5pt);≥6 列降 9pt', '左对齐,垂直居中'),
  98. ('图', '—', '宽度 ≤ 15 cm', '居中'),
  99. ('图题', '黑体', '五号(10.5pt)', '居中,置于图下方'),
  100. ('页眉', '宋体', '小五(9pt)', '居中'),
  101. ('页脚页码', '宋体', '小五(9pt)', '居中(第 X 页 / 共 Y 页)'),
  102. ]
  103. WARN: list[str] = []
  104. # ── 低层 docx 工具 ─────────────────────────────────────────────────────────────
  105. def _rfonts(el, ascii_font: str, ea_font: str):
  106. rpr = el.get_or_add_rPr()
  107. rf = rpr.find(qn('w:rFonts'))
  108. if rf is None:
  109. rf = OxmlElement('w:rFonts')
  110. rpr.append(rf)
  111. rf.set(qn('w:ascii'), ascii_font)
  112. rf.set(qn('w:hAnsi'), ascii_font)
  113. rf.set(qn('w:eastAsia'), ea_font)
  114. def set_run(run, size: float, *, ea: str = SONG, ascii_font: str = WEST, bold: bool = False):
  115. run.font.size = Pt(size)
  116. run.font.bold = bold
  117. run.font.name = ascii_font
  118. run.font.color.rgb = RGBColor(0, 0, 0)
  119. _rfonts(run._element, ascii_font, ea)
  120. def style_setup(doc: Document):
  121. """把内置样式(Heading 1-4 / Normal / 表格)改成文档的统一口径。"""
  122. normal = doc.styles['Normal']
  123. normal.font.name = WEST
  124. normal.font.size = Pt(SZ['body'])
  125. _rfonts(normal.element, WEST, SONG)
  126. normal.paragraph_format.line_spacing_rule = WD_LINE_SPACING.MULTIPLE
  127. normal.paragraph_format.line_spacing = 1.5
  128. normal.paragraph_format.space_after = Pt(0)
  129. spec = {'Heading 1': (SZ['h1'], True), 'Heading 2': (SZ['h2'], True),
  130. 'Heading 3': (SZ['h3'], True), 'Heading 4': (SZ['h3'], True)}
  131. for name, (size, bold) in spec.items():
  132. st = doc.styles[name]
  133. st.font.name = WEST
  134. st.font.size = Pt(size)
  135. st.font.bold = bold
  136. st.font.italic = False
  137. st.font.color.rgb = RGBColor(0, 0, 0)
  138. _rfonts(st.element, WEST, HEI)
  139. pf = st.paragraph_format
  140. pf.line_spacing_rule = WD_LINE_SPACING.MULTIPLE
  141. pf.line_spacing = 1.5
  142. pf.space_before = Pt(12 if name != 'Heading 1' else 0)
  143. pf.space_after = Pt(6)
  144. pf.first_line_indent = Pt(0)
  145. if name == 'Heading 1':
  146. pf.page_break_before = True
  147. pf.space_after = Pt(12)
  148. sec = doc.sections[0]
  149. sec.page_width, sec.page_height = Cm(21.0), Cm(29.7)
  150. sec.top_margin = sec.bottom_margin = Cm(2.54)
  151. sec.left_margin = sec.right_margin = Cm(3.17)
  152. def add_field(paragraph, instr: str, placeholder: str = ''):
  153. r = paragraph.add_run()
  154. b = OxmlElement('w:fldChar'); b.set(qn('w:fldCharType'), 'begin')
  155. i = OxmlElement('w:instrText'); i.set(qn('xml:space'), 'preserve'); i.text = instr
  156. s = OxmlElement('w:fldChar'); s.set(qn('w:fldCharType'), 'separate')
  157. t = OxmlElement('w:t'); t.text = placeholder
  158. e = OxmlElement('w:fldChar'); e.set(qn('w:fldCharType'), 'end')
  159. for el in (b, i, s, t, e):
  160. r._r.append(el)
  161. return r
  162. def para(doc, text: str = '', *, size=SZ['body'], ea=SONG, bold=False, align='left',
  163. indent_chars=0, space_before=0, space_after=6, hanging=False):
  164. p = doc.add_paragraph()
  165. pf = p.paragraph_format
  166. pf.line_spacing_rule = WD_LINE_SPACING.MULTIPLE
  167. pf.line_spacing = 1.5
  168. pf.space_before = Pt(space_before)
  169. pf.space_after = Pt(space_after)
  170. pf.first_line_indent = Pt(size * indent_chars)
  171. if hanging:
  172. pf.left_indent = Cm(0.74)
  173. pf.first_line_indent = Cm(-0.0)
  174. pf.alignment = {'left': WD_ALIGN_PARAGRAPH.LEFT, 'center': WD_ALIGN_PARAGRAPH.CENTER,
  175. 'justify': WD_ALIGN_PARAGRAPH.JUSTIFY}[align]
  176. if text:
  177. for chunk, is_bold, mono in split_bold(text):
  178. r = p.add_run(chunk)
  179. set_run(r, size, ea=SONG, ascii_font='Consolas' if mono else WEST, bold=bold or is_bold)
  180. return p
  181. INLINE_RE = re.compile(r'\*\*(.+?)\*\*|`([^`]+)`')
  182. CODE_RE = re.compile(r'`([^`]+)`')
  183. BOLD_RE = re.compile(r'\*\*(.+?)\*\*')
  184. def _bold_parts(s: str):
  185. parts, pos = [], 0
  186. for m in BOLD_RE.finditer(s):
  187. if m.start() > pos:
  188. parts.append((s[pos:m.start()], False, False))
  189. parts.append((m.group(1), True, False))
  190. pos = m.end()
  191. tail = s[pos:]
  192. if '**' in tail:
  193. # 落单的 `**`(例如通配路径 `pitch/**` 没包在行内代码里)—— 交付文档里不能留字面量,
  194. # 去掉并记一条告警,让写手回去补行内代码。
  195. WARN.append('落单的 ** 已剔除: ' + tail.strip()[:60])
  196. tail = tail.replace('**', '')
  197. if tail:
  198. parts.append((tail, False, False))
  199. return parts
  200. def split_bold(text: str):
  201. """行内标记 → [(片段, 是否粗体, 是否等宽)]。
  202. ★单遍分词,支持两种嵌套(2026-09-22 两次实逮后的定稿):
  203. ① 代码里含 `**`(如通配路径 `` `pitch/**` ``)—— 不能当成粗体起始;
  204. ② 粗体里含代码(如 ``**体量以 `data/raw` 为准**``)—— 不能按代码先切、把粗体配对切断。
  205. 先按 `**…**` 找配对,配对内部再递归扫代码;代码段内部一律**字面**取,不再解析粗体。
  206. 落单的 `**` 剔除并记告警(交付文档里不能留字面星号)。
  207. """
  208. out: list[tuple[str, bool, bool]] = []
  209. def emit(t: str, bold: bool, mono: bool):
  210. if t:
  211. out.append((t, bold, mono))
  212. def scan(s: str, bold: bool):
  213. i = 0
  214. while i < len(s):
  215. if s.startswith('**', i):
  216. j = s.find('**', i + 2)
  217. if j > i + 2:
  218. scan(s[i + 2:j], True)
  219. i = j + 2
  220. continue
  221. WARN.append('落单的 ** 已剔除: ' + s[max(0, i - 20):i + 20].strip())
  222. i += 2
  223. continue
  224. if s[i] == '`':
  225. j = s.find('`', i + 1)
  226. if j > i:
  227. emit(s[i + 1:j], bold, True)
  228. i = j + 1
  229. continue
  230. nxt = len(s)
  231. for k in range(i, len(s)):
  232. if s[k] == '`' or s.startswith('**', k):
  233. nxt = k
  234. break
  235. emit(s[i:nxt], bold, False)
  236. i = nxt
  237. scan(text, False)
  238. return out or [(text, False, False)]
  239. def shade(cell, fill='F2F2F2'):
  240. tcPr = cell._tc.get_or_add_tcPr()
  241. shd = OxmlElement('w:shd')
  242. shd.set(qn('w:val'), 'clear')
  243. shd.set(qn('w:color'), 'auto')
  244. shd.set(qn('w:fill'), fill)
  245. tcPr.append(shd)
  246. def repeat_header(row):
  247. trPr = row._tr.get_or_add_trPr()
  248. th = OxmlElement('w:tblHeader')
  249. th.set(qn('w:val'), 'true')
  250. trPr.append(th)
  251. def add_table(doc, rows: list[list[str]]):
  252. ncol = max(len(r) for r in rows)
  253. t = doc.add_table(rows=0, cols=ncol)
  254. t.style = 'Table Grid'
  255. t.alignment = WD_TABLE_ALIGNMENT.CENTER
  256. t.autofit = True
  257. size = SZ['table_small'] if ncol >= 6 else SZ['table']
  258. for i, r in enumerate(rows):
  259. cells = t.add_row().cells
  260. for j in range(ncol):
  261. txt = (r[j] if j < len(r) else '').strip()
  262. cell = cells[j]
  263. cell.text = ''
  264. p = cell.paragraphs[0]
  265. p.paragraph_format.line_spacing = 1.15
  266. p.paragraph_format.space_after = Pt(0)
  267. p.paragraph_format.first_line_indent = Pt(0)
  268. p.alignment = WD_ALIGN_PARAGRAPH.CENTER if i == 0 else WD_ALIGN_PARAGRAPH.LEFT
  269. for chunk, is_bold, mono in split_bold(txt):
  270. run = p.add_run(chunk.replace('\\|', '|'))
  271. set_run(run, size, ea=HEI if i == 0 else SONG,
  272. ascii_font='Consolas' if mono else WEST, bold=(i == 0) or is_bold)
  273. if i == 0:
  274. shade(cell)
  275. if t.rows:
  276. repeat_header(t.rows[0])
  277. return t
  278. # ── markdown 解析 ──────────────────────────────────────────────────────────────
  279. IMG_RE = re.compile(r'^!\[(?P<cap>[^\]]*)\]\((?P<path>[^)]+)\)\s*$')
  280. CAP_RE = re.compile(r'^\*\*(?P<cap>表\s*[\d\-–.]+.*?)\*\*\s*$')
  281. def parse_md(text: str):
  282. """→ [('h1'|'h2'|'h3'|'h4'|'p'|'ul'|'ol'|'table'|'img'|'quote', payload)]"""
  283. lines = text.splitlines()
  284. blocks, i = [], 0
  285. if lines and lines[0].startswith('# '):
  286. i = 1
  287. while i < len(lines):
  288. ln = lines[i]
  289. s = ln.strip()
  290. if not s or re.match(r'^([-*_])(\s*\1){2,}$', s):
  291. i += 1 # 空行与分隔线(`---` / `***` / `___`)
  292. continue
  293. m = re.match(r'^(#{2,5})\s+(.*)$', s)
  294. if m:
  295. blocks.append(('h%d' % (len(m.group(1)) - 1), m.group(2).strip()))
  296. i += 1
  297. continue
  298. m = IMG_RE.match(s)
  299. if m:
  300. blocks.append(('img', (m.group('cap'), m.group('path'))))
  301. i += 1
  302. continue
  303. if s.startswith('|'):
  304. rows = []
  305. while i < len(lines) and lines[i].strip().startswith('|'):
  306. raw = lines[i].strip().strip('|')
  307. if not re.match(r'^[\s:\-|]+$', raw):
  308. rows.append([c.strip() for c in raw.split('|')])
  309. i += 1
  310. if rows:
  311. cap = None
  312. if blocks and blocks[-1][0] == 'p' and CAP_RE.match(blocks[-1][1]):
  313. cap = blocks.pop()[1]
  314. blocks.append(('table', (cap, rows)))
  315. continue
  316. if s.startswith('- '):
  317. items = []
  318. while i < len(lines) and lines[i].strip().startswith('- '):
  319. items.append(lines[i].strip()[2:].strip())
  320. i += 1
  321. blocks.append(('ul', items))
  322. continue
  323. if re.match(r'^\d+[.)]\s+', s):
  324. items = []
  325. while i < len(lines) and re.match(r'^\d+[.)]\s+', lines[i].strip()):
  326. items.append(re.sub(r'^\d+[.)]\s+', '', lines[i].strip()))
  327. i += 1
  328. blocks.append(('ol', items))
  329. continue
  330. if s.startswith('> '):
  331. q = []
  332. while i < len(lines) and lines[i].strip().startswith('> '):
  333. q.append(lines[i].strip()[2:].strip())
  334. i += 1
  335. blocks.append(('quote', ' '.join(q)))
  336. continue
  337. blocks.append(('p', s))
  338. i += 1
  339. return blocks
  340. def forbidden_hits(text: str) -> dict:
  341. """扫去标识化词表 → {禁用词: 命中次数}(只回报非零项;**大小写不敏感**)。"""
  342. low = text.lower()
  343. return {w: low.count(w.lower()) for w in FORBIDDEN if low.count(w.lower())}
  344. def strict_hits(text: str) -> dict:
  345. """数据要求说明的"不得出现实现细节/现状"扫描 → {模式名: 命中次数}(只回报非零项)。"""
  346. return {name: len(re.findall(rx, text, re.I)) for name, rx in STRICT_PATTERNS
  347. if re.search(rx, text, re.I)}
  348. def count_md(text: str) -> dict:
  349. blocks = parse_md(text)
  350. body = re.sub(r'!\[[^\]]*\]\([^)]*\)', '', text)
  351. cn = len(re.findall(r'[\u4e00-\u9fff]', body))
  352. return dict(
  353. 章=sum(1 for k, _ in blocks if k == 'h1'),
  354. 节=sum(1 for k, _ in blocks if k == 'h2'),
  355. 小节=sum(1 for k, _ in blocks if k == 'h3'),
  356. 表=sum(1 for k, _ in blocks if k == 'table'),
  357. 图=sum(1 for k, _ in blocks if k == 'img'),
  358. 段落=sum(1 for k, _ in blocks if k == 'p'),
  359. 汉字=cn)
  360. # ── 渲染 ───────────────────────────────────────────────────────────────────────
  361. def cover(doc, title: str, subtitle: str):
  362. for _ in range(4):
  363. para(doc, '', space_after=0)
  364. para(doc, f'{title}', size=SZ['cover'], ea=HEI, bold=True, align='center', space_after=12)
  365. para(doc, subtitle, size=14, ea=HEI, align='center', space_after=6)
  366. for _ in range(3):
  367. para(doc, '', space_after=0)
  368. para(doc, f'版本 {VERSION}(与系统版本一致)', size=14, align='center', space_after=6)
  369. para(doc, f'编制:观澜项目组  日期:2026-09-22', size=12, align='center', space_after=6)
  370. # ★落款不写生成器文件名与源件路径:那会把实现细节带进"对外、不体现文件名/落盘位置"的文档里
  371. # (2026-09-22 实逮: `--check` 扫源件是 clean, 但 `--verify` 扫渲染结果命中 1 处 snake_case + 2 处路径)。
  372. para(doc, '本文件由统一的交付文档生成器排版(样式表固定,可重跑、可 diff;正文源件随交付包提供)',
  373. size=9, align='center', space_after=0)
  374. doc.add_page_break()
  375. def toc(doc):
  376. para(doc, '目录', size=SZ['h1'], ea=HEI, bold=True, align='center', space_after=12)
  377. p = doc.add_paragraph()
  378. p.paragraph_format.line_spacing = 1.5
  379. add_field(p, r'TOC \o "1-3" \h \z \u',
  380. '(目录域:在 Word 中按 Ctrl+A 后 F9,或右键“更新域”即可生成带页码的目录)')
  381. doc.add_page_break()
  382. def render_blocks(doc, blocks, fig_root: pathlib.Path):
  383. """渲染块序列。表号一律**按章编号**「表 <章>-<序>」(附录按字母 A/B/C)——
  384. 与三份稿正文里的引用口径一致(实逮: 原先按出现顺序编成「表 1…表 54」, 正文写「见表 9-2」就指不到)。
  385. """
  386. tno = 0
  387. chap_label = ''
  388. per = 0
  389. caps: list[str] = []
  390. for kind, payload in blocks:
  391. if kind == 'h1':
  392. head = payload.strip()
  393. m = re.match(r'^(\d+)', head)
  394. if m:
  395. chap_label, per = m.group(1), 0
  396. else:
  397. m2 = re.match(r'^附录\s*([A-Za-z])', head)
  398. chap_label, per = (m2.group(1), 0) if m2 else (chap_label, 0)
  399. if kind.startswith('h'):
  400. lvl = int(kind[1])
  401. style = {1: 'Heading 1', 2: 'Heading 2', 3: 'Heading 3', 4: 'Heading 4'}[lvl]
  402. p = doc.add_paragraph(style=style)
  403. size = {1: SZ['h1'], 2: SZ['h2'], 3: SZ['h3'], 4: SZ['h3']}[lvl]
  404. for chunk, _b, _m in split_bold(payload):
  405. set_run(p.add_run(chunk), size, ea=HEI, bold=True)
  406. continue
  407. if kind == 'p':
  408. para(doc, payload, align='justify', indent_chars=2)
  409. continue
  410. if kind in ('ul', 'ol'):
  411. for n, item in enumerate(payload, 1):
  412. mark = '· ' if kind == 'ul' else f'({n})'
  413. para(doc, mark + item, align='justify', hanging=True, space_after=3)
  414. continue
  415. if kind == 'quote':
  416. p = para(doc, payload, align='justify', space_before=6, space_after=6)
  417. p.paragraph_format.left_indent = Cm(0.74)
  418. continue
  419. if kind == 'table':
  420. cap, rows = payload
  421. tno += 1
  422. per += 1
  423. label = f'表 {chap_label}-{per}' if chap_label else f'表 {tno}'
  424. title = re.sub(r'^表\s*[\dA-Za-z]+\s*[-–—]\s*\d+\s*', '', cap or '').strip()
  425. if cap:
  426. author_no = re.match(r'^表\s*([\dA-Za-z]+)\s*[-–—]\s*(\d+)', cap)
  427. if author_no and f'{author_no.group(1)}-{author_no.group(2)}' != f'{chap_label}-{per}':
  428. WARN.append('表号与作者自编不一致: 原「%s」→ 本器按章编号「%s」'
  429. % (cap[:24], label))
  430. caps.append(label)
  431. para(doc, (label + (' ' + title if title else '')), size=SZ['caption'], ea=HEI, bold=True,
  432. align='center', space_before=8, space_after=4)
  433. add_table(doc, rows)
  434. para(doc, '', space_after=2)
  435. continue
  436. if kind == 'img':
  437. cap, rel = payload
  438. # md 里的图路径是相对 `docs/` 的(约定 `figures/xxx.png`);容错:只给文件名也认。
  439. cand = fig_root / rel if (fig_root / rel).exists() else fig_root / 'figures' / pathlib.Path(rel).name
  440. f = cand.resolve()
  441. if f.exists():
  442. p = doc.add_paragraph()
  443. p.alignment = WD_ALIGN_PARAGRAPH.CENTER
  444. p.paragraph_format.space_before = Pt(8)
  445. p.paragraph_format.space_after = Pt(4)
  446. p.paragraph_format.first_line_indent = Pt(0)
  447. p.add_run().add_picture(str(f), width=Cm(15.0) if f.stat().st_size > 90_000 else Cm(13.0))
  448. else:
  449. WARN.append(f'图缺件: {rel}')
  450. para(doc, f'(图缺失:{rel})', size=SZ['caption'], align='center', space_after=4)
  451. para(doc, cap or rel, size=SZ['caption'], ea=HEI, bold=True, align='center', space_after=8)
  452. continue
  453. doc._tab_labels = caps # 供调用方自检(本器 --verify 直接从 docx 回读,不依赖它)
  454. return tno
  455. def header_footer(doc, title: str):
  456. sec = doc.sections[0]
  457. hp = sec.header.paragraphs[0]
  458. hp.alignment = WD_ALIGN_PARAGRAPH.CENTER
  459. set_run(hp.add_run(f'{title} · 观澜 v2 风电场智能分析系统 · 版本 {VERSION}'), SZ['header'])
  460. fp = sec.footer.paragraphs[0]
  461. fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
  462. set_run(fp.add_run('第 '), SZ['header'])
  463. add_field(fp, 'PAGE', '1')
  464. set_run(fp.add_run(' 页 / 共 '), SZ['header'])
  465. add_field(fp, 'NUMPAGES', '1')
  466. set_run(fp.add_run(' 页'), SZ['header'])
  467. def appendix_spec(doc):
  468. para(doc, '附:排版规范(字体字号分类)', size=SZ['h1'], ea=HEI, bold=True, align='left',
  469. space_before=12, space_after=8)
  470. para(doc, '本文件与同批交付的另外两份文档由同一个渲染器生成,字体字号分类完全一致;'
  471. '中文用黑体(标题)/宋体(正文),西文与数字用 Times New Roman。', align='justify',
  472. indent_chars=2)
  473. add_table(doc, [['元素', '字体', '字号', '对齐 / 缩进']] + [list(r) for r in SPEC_ROWS])
  474. def build(key: str) -> int:
  475. spec = DOCS[key]
  476. src = ROOT / spec['src'].format(v=VERSION)
  477. out = ROOT / spec['out'].format(v=VERSION)
  478. if not src.exists():
  479. WARN.append(f'源件缺件: {src.relative_to(ROOT).as_posix()}')
  480. print(f'✗ {key}: 源件不在位 {src}')
  481. return 5
  482. blocks = parse_md(src.read_text(encoding='utf-8'))
  483. doc = Document()
  484. style_setup(doc)
  485. cover(doc, spec['title'], spec['subtitle'])
  486. toc(doc)
  487. ntab = render_blocks(doc, blocks, ROOT / 'docs')
  488. appendix_spec(doc)
  489. header_footer(doc, spec['title'])
  490. out.parent.mkdir(parents=True, exist_ok=True)
  491. doc.save(out)
  492. st = count_md(src.read_text(encoding='utf-8'))
  493. print('%s → %s(%d 章 · %d 节 · %d 表 · %d 图 · 约 %d 汉字 · %.0f KB)'
  494. % (key, out.relative_to(ROOT).as_posix(), st['章'], st['节'], max(ntab, st['表']), st['图'],
  495. st['汉字'], out.stat().st_size / 1024))
  496. return 0
  497. def verify_docx(key: str) -> int:
  498. """回读渲染结果自检(交付前必跑):计数 + 残留 markdown 标记 + 域 + 字体。"""
  499. spec = DOCS[key]
  500. out = ROOT / spec['out'].format(v=VERSION)
  501. if not out.is_file():
  502. print('✗ %-4s 不在位 %s' % (key, out.relative_to(ROOT).as_posix()))
  503. return 5
  504. doc = Document(str(out))
  505. texts = [p.text for p in doc.paragraphs]
  506. cells = [c.text for t in doc.tables for r in t.rows for c in r.cells]
  507. anti = chr(96)
  508. # ★行内代码里的字面量不算残留(实逮: `` `pitch/**` `` 是 glob 通配路径,Word 里就该原样显示)。
  509. mono, plain = [], []
  510. for p in doc.paragraphs:
  511. for r in p.runs:
  512. (mono if (r.font.name or '').startswith('Consolas') else plain).append(r.text)
  513. for t in doc.tables:
  514. for row in t.rows:
  515. for c in row.cells:
  516. for p in c.paragraphs:
  517. for r in p.runs:
  518. (mono if (r.font.name or '').startswith('Consolas') else plain).append(r.text)
  519. allt = '\n'.join(texts + cells)
  520. body = '\n'.join(plain)
  521. heads = [p.text for p in doc.paragraphs if p.style.name.startswith('Heading')]
  522. residual = dict(反引号=body.count(anti), 星号=body.count('**'), 管道=body.count(' | '),
  523. 代码内字面星号='\n'.join(mono).count('**'))
  524. foot = doc.sections[0].footer.paragraphs[0]._p.xml
  525. head = doc.sections[0].header.paragraphs[0].text
  526. ok_field = ('TOC' in doc.element.xml) and ('PAGE' in foot) and ('NUMPAGES' in foot)
  527. # 只把"正文里残留的 markdown 标记"判为不合格;代码内的字面星号是内容本身(glob 通配),只报数。
  528. bad = [k for k, v in residual.items() if v and k != '代码内字面星号']
  529. # ★版本表覆盖检查(2026-09-22 实逮): 升版本时若只改版本串而忘插表行, 表尾会停在旧版本,
  530. # 而正文"共 N 条/十六个版本/中七条·小九条"是手写的 ⇒ 用 HISTORY 机器核对, 缺一行就 FAIL。
  531. if key == 'req':
  532. from src import version as _V
  533. want_v = {h['version'] for h in _V.HISTORY}
  534. got_v = set()
  535. for _tb in doc.tables:
  536. for _row in _tb.rows:
  537. _c = _row.cells[0].text.strip()
  538. if re.fullmatch(r'\d+\.\d+\.\d+', _c):
  539. got_v.add(_c)
  540. _miss_v = sorted(want_v - got_v)
  541. if _miss_v:
  542. bad.append('版本表缺行 %s' % _miss_v)
  543. leak = forbidden_hits(allt + '\n' + head) # ★对外件不得出现样本场标识
  544. strict = strict_hits(allt) if spec.get('strict_terms') else {} # ★数据要求说明: 去实现细节/去现状
  545. # ★表号断链检查(2026-09-22 实逮): 正文写「见表 9-2」,文档里就必须真有「表 9-2」。
  546. cap_labels = set()
  547. for p in doc.paragraphs:
  548. mm = re.match(r'^表\s*([\dA-Za-z]+)\s*[-–—]\s*(\d+)', p.text.strip())
  549. if mm:
  550. cap_labels.add(f'{mm.group(1)}-{mm.group(2)}')
  551. def _refs(text: str) -> set:
  552. """正文里的「表 X-Y」引用。
  553. ★两处实逮的误报都要挡:① `年-月`('报表 2026-09');② **跨单元格拼接** —— 把表格单元用换行
  554. 连起来后, "…如实空表" + "FR-18 至 FR-21" 会拼出 '表\\nFR-18',被当成表号。故分隔符只许空格/制表符。
  555. """
  556. out = set()
  557. for a, b in re.findall(r'表[ \t]*([\dA-Za-z]+)[ \t]*[-–—][ \t]*(\d+)', text):
  558. if re.fullmatch(r'(19|20)\d{2}', a):
  559. continue
  560. out.add(f'{a}-{b}')
  561. return out
  562. refs = _refs('\n'.join(
  563. [p.text for p in doc.paragraphs
  564. if not re.match(r'^(表|图)\s*[\dA-Za-z]+\s*[-–—]\s*\d+', p.text.strip())] + cells))
  565. broken = sorted(refs - cap_labels)
  566. noref = sorted(cap_labels - refs)
  567. print('%-4s %-38s 段落 %3d · 表 %2d · 图 %2d · 标题 %2d · 页眉 %r'
  568. % (key, out.name, len(doc.paragraphs), len(doc.tables), len(doc.inline_shapes),
  569. len(heads), head[:28]))
  570. print(' 域(目录/页码): %s · 残留标记: %s · 去标识化: %s%s · 表号: %s'
  571. % ('OK' if ok_field else '缺', bad or '无',
  572. 'clean' if not leak else '泄漏 %s' % leak,
  573. '' if not spec.get('strict_terms') else
  574. ' · 去实现细节: %s' % ('clean' if not strict else '命中 %s' % strict),
  575. '断链 %s' % broken if broken else '引用闭合(表 %d 张,%d 张无引用)' % (len(cap_labels), len(noref))))
  576. return 0 if ok_field and not bad and not leak and not broken and not strict else 5
  577. def main() -> int:
  578. ap = argparse.ArgumentParser()
  579. ap.add_argument('--only', choices=sorted(DOCS))
  580. ap.add_argument('--check', action='store_true', help='只体检源件与图,不渲染')
  581. ap.add_argument('--verify', action='store_true', help='渲染后回读自检(计数/残留标记/域)')
  582. ap.add_argument('--spec', action='store_true', help='打印排版规范表')
  583. a = ap.parse_args()
  584. if a.spec:
  585. for row in SPEC_ROWS:
  586. print(' | '.join(row))
  587. return 0
  588. rc = 0
  589. if a.verify:
  590. for k in ([a.only] if a.only else sorted(DOCS)):
  591. rc = max(rc, verify_docx(k))
  592. return rc
  593. if a.check:
  594. for k, spec in DOCS.items():
  595. src = ROOT / spec['src'].format(v=VERSION)
  596. if not src.exists():
  597. print('✗ %-4s 源件不在位 %s' % (k, src.relative_to(ROOT).as_posix()))
  598. rc = 5
  599. continue
  600. st = count_md(src.read_text(encoding='utf-8'))
  601. _src_txt = src.read_text(encoding='utf-8')
  602. miss, leak = [], forbidden_hits(_src_txt)
  603. strict = strict_hits(_src_txt) if spec.get('strict_terms') else {}
  604. for _cap, rel in re.findall(r'!\[([^\]]*)\]\(([^)]+)\)', _src_txt):
  605. f = ROOT / 'docs' / rel.split('figures/')[-1]
  606. if not (ROOT / 'docs' / 'figures' / rel.split('figures/')[-1]).exists():
  607. miss.append(rel)
  608. print('%-4s 章 %2d · 节 %2d · 小节 %2d · 表 %2d · 图 %2d · 约 %5d 汉字 · 去标识化 %s%s%s'
  609. % (k, st['章'], st['节'], st['小节'], st['表'], st['图'], st['汉字'],
  610. 'clean' if not leak else '泄漏 %s' % leak,
  611. '' if not spec.get('strict_terms') else
  612. ' · 去实现细节 %s' % ('clean' if not strict else '命中 %s' % strict),
  613. '' if not miss else ' ✗ 缺图 %d: %s' % (len(miss), ', '.join(miss))))
  614. if miss or leak or strict:
  615. rc = 5
  616. return rc
  617. for k in ([a.only] if a.only else sorted(DOCS)):
  618. rc = max(rc, build(k))
  619. if WARN:
  620. print('\n告警:')
  621. for w in sorted(set(WARN)):
  622. print(' -', w)
  623. return rc
  624. if __name__ == '__main__':
  625. raise SystemExit(main())