delivery_docs_build.py 29 KB

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