delivery_docs_build.py 25 KB

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