make_masked_docx.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. # -*- coding: utf-8 -*-
  2. """
  3. 脱敏 Markdown → 带高亮的 Word(.docx)→ Word COM 导出 PDF
  4. 替换掉浏览器打印路线(沙箱下 Chrome/Edge headless 不产出文件)
  5. """
  6. import io, os, re, sys, subprocess
  7. sys.stdout.reconfigure(encoding='utf-8')
  8. from docx import Document
  9. from docx.shared import Pt, RGBColor, Cm
  10. from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_COLOR_INDEX
  11. from docx.enum.table import WD_TABLE_ALIGNMENT
  12. from docx.enum.section import WD_ORIENT
  13. from docx.oxml.ns import qn
  14. from docx.oxml import OxmlElement
  15. BASE = r'E:/cfc/docs/参考资料'
  16. OUT = os.path.join(BASE, '脱敏交付')
  17. os.makedirs(OUT, exist_ok=True)
  18. PURPLE = RGBColor(0x5B, 0x3E, 0x96)
  19. DARK = RGBColor(0x25, 0x23, 0x2B)
  20. GREY = RGBColor(0x5A, 0x54, 0x66)
  21. FONT_CN = '微软雅黑'
  22. FONT_EN = 'Segoe UI'
  23. MASK = [
  24. ('张学红', 'L 女士'),
  25. ('560822024', 'A-2401'),
  26. # 清理带编号/姓名的原始文件名,避免二次可识别
  27. ('`A-2401-L 女士.json`', '报告解析 JSON'),
  28. ('`A-2401-L 女士.pdf`', '原始检测报告 PDF'),
  29. ('`A-2401-L 女士`', '报告解析文件'),
  30. ]
  31. KEY_PHRASES = [
  32. '她不是吃得少,是吃得很讲究——但讲究的方向恰好全在压制铁吸收',
  33. '抓三件事——拆开早餐的铁吸收抑制',
  34. '她的肠道生态底子是好的,问题高度集中,可干预性很强',
  35. '这不是"菌群崩坏",是"关键岗位缺人"',
  36. '铁被早餐堵死了、双歧缺粮塌方了、早绝经让骨与雌激素两个窗口提前了',
  37. '不需要补乳杆菌',
  38. '不必补乳杆菌',
  39. '长双歧杆菌为第一靶点',
  40. '外源益生菌的**定植率很低**',
  41. '益生菌**点火**,瓜尔豆纤维**添柴**',
  42. '不能把"运动少"归因为懒、缺动力或自律不足',
  43. '必须临床区分,不可自行归因',
  44. '不得表述为"她正在抑郁"',
  45. '42 岁绝经 = 早绝经',
  46. '二选一时取瓜尔豆纤维',
  47. '她不吃肉,所以红肉不是她的问题',
  48. '菊粉或瓜尔豆纤维(二选一)→ 推荐瓜尔豆纤维',
  49. '与铁剂错开 2 小时',
  50. ]
  51. # ---------------- 基础排版工具 ----------------
  52. def set_run_font(run, size=10.5, bold=False, color=DARK, italic=False):
  53. run.font.size = Pt(size)
  54. run.font.bold = bold
  55. run.font.italic = italic
  56. run.font.color.rgb = color
  57. run.font.name = FONT_EN
  58. rPr = run._element.get_or_add_rPr()
  59. rFonts = rPr.find(qn('w:rFonts'))
  60. if rFonts is None:
  61. rFonts = OxmlElement('w:rFonts'); rPr.append(rFonts)
  62. rFonts.set(qn('w:eastAsia'), FONT_CN)
  63. rFonts.set(qn('w:ascii'), FONT_EN)
  64. rFonts.set(qn('w:hAnsi'), FONT_EN)
  65. def shade_cell(cell, hexcolor):
  66. tcPr = cell._tc.get_or_add_tcPr()
  67. shd = OxmlElement('w:shd')
  68. shd.set(qn('w:val'), 'clear'); shd.set(qn('w:color'), 'auto')
  69. shd.set(qn('w:fill'), hexcolor)
  70. tcPr.append(shd)
  71. def add_bottom_border(par, color='5B3E96', sz=12):
  72. pPr = par._p.get_or_add_pPr()
  73. pbdr = OxmlElement('w:pBdr')
  74. bottom = OxmlElement('w:bottom')
  75. bottom.set(qn('w:val'), 'single'); bottom.set(qn('w:sz'), str(sz))
  76. bottom.set(qn('w:space'), '4'); bottom.set(qn('w:color'), color)
  77. pbdr.append(bottom); pPr.append(pbdr)
  78. def add_left_bar(par, color='7B5CB8'):
  79. pPr = par._p.get_or_add_pPr()
  80. pbdr = OxmlElement('w:pBdr')
  81. left = OxmlElement('w:left')
  82. left.set(qn('w:val'), 'single'); left.set(qn('w:sz'), '18')
  83. left.set(qn('w:space'), '8'); left.set(qn('w:color'), color)
  84. pbdr.append(left); pPr.append(pbdr)
  85. def shade_paragraph(par, hexcolor):
  86. pPr = par._p.get_or_add_pPr()
  87. shd = OxmlElement('w:shd')
  88. shd.set(qn('w:val'), 'clear'); shd.set(qn('w:color'), 'auto')
  89. shd.set(qn('w:fill'), hexcolor)
  90. pPr.append(shd)
  91. # ---------------- 行内标记解析:**粗体** ==高亮== ----------------
  92. TOKEN = re.compile(r'(\*\*.+?\*\*|==.+?==)')
  93. def add_inline(par, text, size=10.5, base_bold=False, color=DARK):
  94. """解析 **bold** 与 ==highlight==,支持「**粗体里嵌 ==高亮==」的嵌套"""
  95. for seg in TOKEN.split(text):
  96. if not seg:
  97. continue
  98. bold = base_bold
  99. if seg.startswith('**') and seg.endswith('**') and len(seg) > 4:
  100. seg = seg[2:-2]
  101. bold = True
  102. for sub in re.split(r'(==.+?==)', seg):
  103. if not sub:
  104. continue
  105. if sub.startswith('==') and sub.endswith('==') and len(sub) > 4:
  106. r = par.add_run(sub[2:-2])
  107. set_run_font(r, size=size, bold=True, color=RGBColor(0x1A, 0x16, 0x20))
  108. r.font.highlight_color = WD_COLOR_INDEX.YELLOW
  109. else:
  110. r = par.add_run(sub)
  111. set_run_font(r, size=size, bold=bold, color=color)
  112. # ---------------- Markdown 解析 ----------------
  113. def parse_table(lines):
  114. """返回 rows(含表头)"""
  115. rows = []
  116. for ln in lines:
  117. cells = [c.strip() for c in ln.strip().strip('|').split('|')]
  118. if all(re.fullmatch(r':?-{2,}:?', c) for c in cells if c):
  119. continue
  120. rows.append(cells)
  121. return rows
  122. def build_docx(md_path, out_docx, doc_title):
  123. raw = io.open(md_path, encoding='utf-8').read()
  124. for a, b in MASK:
  125. raw = raw.replace(a, b)
  126. # 去掉残留的反引号(docx 里会显示为字面 ` )
  127. raw = re.sub(r'`([^`\n]{1,80})`', r'\1', raw)
  128. # 抬头关键信息高亮(原文已被 ** 包裹,需单独处理)
  129. raw = raw.replace('**42 岁绝经(绝经 10 年,属早绝经)**',
  130. '==42 岁绝经(绝经 10 年,属早绝经)==')
  131. for p in KEY_PHRASES:
  132. if p in raw and ('==' + p + '==') not in raw:
  133. raw = raw.replace(p, '==' + p + '==', 1)
  134. # 脱敏声明插入到首个 --- 之前
  135. raw = raw.replace('\n---\n', '\n> **本文件已脱敏**:受检者姓名与报告编号均已做替换处理,仅保留归因所需的年龄、性别、生理阶段信息。\n\n---\n', 1)
  136. lines = raw.split('\n')
  137. doc = Document()
  138. sec = doc.sections[0]
  139. sec.page_width = Cm(21.0); sec.page_height = Cm(29.7)
  140. sec.left_margin = Cm(1.9); sec.right_margin = Cm(1.9)
  141. sec.top_margin = Cm(1.5); sec.bottom_margin = Cm(1.5)
  142. st = doc.styles['Normal']
  143. st.font.name = FONT_EN; st.font.size = Pt(10.5)
  144. st.element.rPr.rFonts.set(qn('w:eastAsia'), FONT_CN)
  145. i = 0
  146. n = len(lines)
  147. while i < n:
  148. ln = lines[i]
  149. s = ln.strip()
  150. # 空行
  151. if not s:
  152. i += 1; continue
  153. # 表格
  154. if s.startswith('|') and i + 1 < n and lines[i+1].strip().startswith('|'):
  155. block = []
  156. while i < n and lines[i].strip().startswith('|'):
  157. block.append(lines[i]); i += 1
  158. rows = [r for r in parse_table(block) if any(c for c in r)]
  159. if not rows:
  160. continue
  161. ncol = max(len(r) for r in rows)
  162. # --- 自适应列宽:按"该列最长内容"分配,幂压缩避免长文本列吃掉全部宽度 ---
  163. def wlen(s):
  164. return sum(2 if ord(ch) > 127 else 1 for ch in s)
  165. mxs = []
  166. for ci in range(ncol):
  167. mx = 1
  168. for row in rows:
  169. cell_txt = row[ci] if ci < len(row) else ''
  170. mx = max(mx, wlen(cell_txt))
  171. mxs.append(mx)
  172. weights = [m ** 0.7 for m in mxs]
  173. tot = sum(weights)
  174. ratios = [max(0.085, min(0.42, x / tot)) for x in weights]
  175. ssum = sum(ratios)
  176. ratios = [r / ssum for r in ratios]
  177. CONTENT_W = 17.2 # cm,页面宽 21 - 左右边距各 1.9
  178. col_w = [Cm(CONTENT_W * r) for r in ratios]
  179. tbl = doc.add_table(rows=0, cols=ncol)
  180. tbl.style = 'Table Grid'
  181. tbl.alignment = WD_TABLE_ALIGNMENT.CENTER
  182. tbl.autofit = False
  183. for ri, row in enumerate(rows):
  184. cells = tbl.add_row().cells
  185. for ci in range(ncol):
  186. txt = row[ci] if ci < len(row) else ''
  187. cell = cells[ci]
  188. cell.width = col_w[ci]
  189. cell.text = ''
  190. p = cell.paragraphs[0]
  191. p.paragraph_format.space_before = Pt(1.2)
  192. p.paragraph_format.space_after = Pt(1.2)
  193. p.paragraph_format.line_spacing = 1.18
  194. if ri == 0:
  195. shade_cell(cell, '5B3E96')
  196. add_inline(p, txt, size=8.8, base_bold=True,
  197. color=RGBColor(0xFF, 0xFF, 0xFF))
  198. else:
  199. if ri % 2 == 0:
  200. shade_cell(cell, 'FBF9FE')
  201. add_inline(p, txt, size=8.8)
  202. # 表头行跨页重复 + 行不跨页断裂
  203. try:
  204. trPr = tbl.rows[0]._tr.get_or_add_trPr()
  205. th = OxmlElement('w:tblHeader'); th.set(qn('w:val'), 'true')
  206. trPr.append(th)
  207. for r_ in tbl.rows:
  208. trPr_ = r_._tr.get_or_add_trPr()
  209. cs = OxmlElement('w:cantSplit'); cs.set(qn('w:val'), 'true')
  210. trPr_.append(cs)
  211. except Exception:
  212. pass
  213. sp = doc.add_paragraph()
  214. sp.paragraph_format.space_after = Pt(2)
  215. continue
  216. # 标题
  217. if s.startswith('#### '):
  218. p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(8)
  219. p.paragraph_format.space_after = Pt(3)
  220. p.paragraph_format.keep_with_next = True
  221. add_inline(p, s[5:], size=11, base_bold=True, color=RGBColor(0x4A,0x3F,0x63))
  222. i += 1; continue
  223. if s.startswith('### '):
  224. p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(11)
  225. p.paragraph_format.space_after = Pt(4)
  226. p.paragraph_format.keep_with_next = True
  227. add_inline(p, s[4:], size=11.8, base_bold=True, color=RGBColor(0x3F,0x35,0x55))
  228. add_bottom_border(p, color='CFC2E8', sz=6)
  229. i += 1; continue
  230. if s.startswith('## '):
  231. p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(15)
  232. p.paragraph_format.space_after = Pt(6)
  233. p.paragraph_format.left_indent = Cm(0.18)
  234. p.paragraph_format.keep_with_next = True
  235. add_inline(p, s[3:], size=13.4, base_bold=True, color=PURPLE)
  236. add_left_bar(p); shade_paragraph(p, 'F7F4FC')
  237. i += 1; continue
  238. if s.startswith('# '):
  239. p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(2)
  240. p.paragraph_format.space_after = Pt(8)
  241. add_inline(p, s[2:], size=18, base_bold=True, color=PURPLE)
  242. add_bottom_border(p, sz=16)
  243. i += 1; continue
  244. # 分隔线
  245. if re.fullmatch(r'-{3,}', s):
  246. p = doc.add_paragraph(); p.paragraph_format.space_before = Pt(2)
  247. p.paragraph_format.space_after = Pt(2)
  248. add_bottom_border(p, color='E2DCEE', sz=6)
  249. i += 1; continue
  250. # 引用块
  251. if s.startswith('>'):
  252. block = []
  253. while i < n and lines[i].strip().startswith('>'):
  254. block.append(lines[i].strip()[1:].strip()); i += 1
  255. for b in block:
  256. if not b:
  257. continue
  258. p = doc.add_paragraph()
  259. p.paragraph_format.left_indent = Cm(0.35)
  260. p.paragraph_format.space_before = Pt(3)
  261. p.paragraph_format.space_after = Pt(3)
  262. p.paragraph_format.line_spacing = 1.6
  263. txt = re.sub(r'^[-*]\s+', '· ', b)
  264. add_inline(p, txt, size=9.9, color=RGBColor(0x3C,0x34,0x50))
  265. add_left_bar(p, color='A98FE0'); shade_paragraph(p, 'FAF7FE')
  266. continue
  267. # 列表
  268. m = re.match(r'^(\s*)([-*]|\d+\.)\s+(.*)$', ln)
  269. if m:
  270. indent = len(m.group(1)) // 2
  271. marker = m.group(2)
  272. body = m.group(3)
  273. p = doc.add_paragraph()
  274. p.paragraph_format.left_indent = Cm(0.55 + indent * 0.45)
  275. p.paragraph_format.first_line_indent = Cm(-0.42)
  276. p.paragraph_format.space_before = Pt(2)
  277. p.paragraph_format.space_after = Pt(2)
  278. prefix = '· ' if marker in ('-', '*') else marker + ' '
  279. add_inline(p, prefix + body, size=10.4)
  280. i += 1; continue
  281. # 普通段落
  282. p = doc.add_paragraph()
  283. p.paragraph_format.space_before = Pt(3)
  284. p.paragraph_format.space_after = Pt(3)
  285. p.paragraph_format.line_spacing = 1.72
  286. p.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
  287. add_inline(p, s, size=10.5)
  288. i += 1
  289. doc.save(out_docx)
  290. return out_docx
  291. # ---------------- Word COM → PDF ----------------
  292. PS = r'''
  293. param([string]$DocxPath, [string]$PdfPath)
  294. $ErrorActionPreference = 'Stop'
  295. $word = New-Object -ComObject Word.Application
  296. $word.Visible = $false
  297. $word.DisplayAlerts = 0
  298. try {
  299. $doc = $word.Documents.Open($DocxPath, $false, $true)
  300. $doc.SaveAs([ref]$PdfPath, [ref]17)
  301. $doc.Close([ref]0)
  302. Write-Output "PDF_OK"
  303. } finally {
  304. $word.Quit()
  305. [System.Runtime.InteropServices.Marshal]::ReleaseComObject($word) | Out-Null
  306. }
  307. '''
  308. if __name__ == '__main__':
  309. ps_path = os.path.join(OUT, '_topdf.ps1')
  310. io.open(ps_path, 'w', encoding='utf-8-sig').write(PS)
  311. jobs = [
  312. ('560822024-张学红-归因分析-简版.md', 'L女士-归因分析-简版', 'L 女士 · 肠道菌群归因分析(简版)'),
  313. ('560822024-张学红-归因分析-完整版.md', 'L女士-归因分析-完整版', 'L 女士 · 肠道菌群归因分析(完整版)'),
  314. ]
  315. for src, stem, title in jobs:
  316. docx_path = os.path.join(OUT, stem + '.docx')
  317. build_docx(os.path.join(BASE, src), docx_path, title)
  318. print('docx:', os.path.basename(docx_path), f'{os.path.getsize(docx_path)/1024:.0f} KB')