delivery_docs_build.py 31 KB

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