docx_builder.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. """Word 报告组装。"""
  2. from __future__ import annotations
  3. import os
  4. from datetime import datetime
  5. from typing import Any, Dict, List, Optional
  6. from docx import Document
  7. from docx.enum.section import WD_SECTION
  8. from docx.enum.table import WD_TABLE_ALIGNMENT
  9. from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_BREAK
  10. from docx.oxml import OxmlElement
  11. from docx.oxml.ns import qn
  12. from docx.shared import Cm, Inches, Pt, RGBColor
  13. from app.report import charts, narrative
  14. HEADER_TEXT = "基于RCM的风电机组健康度检测系统平台"
  15. PRIMARY = RGBColor(0x1A, 0x3B, 0x7F)
  16. GRAY = RGBColor(0x66, 0x66, 0x66)
  17. def _font(run, size=10.5, bold=False, color=None, name="微软雅黑"):
  18. run.font.name = name
  19. run._element.rPr.rFonts.set(qn("w:eastAsia"), name)
  20. run.font.size = Pt(size)
  21. run.bold = bold
  22. if color is not None:
  23. run.font.color.rgb = color
  24. def _para(doc, text="", size=10.5, bold=False, color=None, align=None, indent=True, space_after=6):
  25. p = doc.add_paragraph()
  26. if align is not None:
  27. p.alignment = align
  28. fmt = p.paragraph_format
  29. fmt.line_spacing = 1.5
  30. fmt.space_after = Pt(space_after)
  31. if indent:
  32. fmt.first_line_indent = Pt(21)
  33. run = p.add_run(text)
  34. _font(run, size, bold, color)
  35. return p
  36. def _heading(doc, text, level=1):
  37. p = doc.add_heading(level=level)
  38. run = p.add_run(text)
  39. sizes = {0: 22, 1: 16, 2: 13, 3: 11.5}
  40. _font(run, sizes.get(level, 11.5), True, PRIMARY, "微软雅黑")
  41. p.paragraph_format.space_before = Pt(12)
  42. p.paragraph_format.space_after = Pt(6)
  43. return p
  44. def _shade(cell, color="1A3B7F"):
  45. tc_pr = cell._tc.get_or_add_tcPr()
  46. shd = OxmlElement("w:shd")
  47. shd.set(qn("w:val"), "clear")
  48. shd.set(qn("w:color"), "auto")
  49. shd.set(qn("w:fill"), color)
  50. tc_pr.append(shd)
  51. def _cell_text(cell, text, bold=False, color=None, size=9, align=WD_ALIGN_PARAGRAPH.CENTER):
  52. cell.text = ""
  53. p = cell.paragraphs[0]
  54. p.alignment = align
  55. run = p.add_run("" if text is None else str(text))
  56. _font(run, size, bold, color)
  57. def _table(doc, headers: List[str], rows: List[List[Any]], widths: Optional[List[float]] = None):
  58. table = doc.add_table(rows=1, cols=len(headers))
  59. table.style = "Table Grid"
  60. table.alignment = WD_TABLE_ALIGNMENT.CENTER
  61. hdr = table.rows[0].cells
  62. for i, h in enumerate(headers):
  63. _cell_text(hdr[i], h, True, RGBColor(0xFF, 0xFF, 0xFF), 9)
  64. _shade(hdr[i])
  65. for row in rows:
  66. cells = table.add_row().cells
  67. for i, v in enumerate(row):
  68. _cell_text(cells[i], v, False, None, 9)
  69. if widths:
  70. total = sum(widths)
  71. if total > 15.5:
  72. widths = [w * 15.5 / total for w in widths]
  73. table.autofit = False
  74. for i, w in enumerate(widths):
  75. table.columns[i].width = Cm(w)
  76. for row in table.rows:
  77. for i, w in enumerate(widths):
  78. row.cells[i].width = Cm(w)
  79. doc.add_paragraph().paragraph_format.space_after = Pt(2)
  80. return table
  81. def _image(doc, path: Optional[str], caption: str):
  82. if not path or not os.path.exists(path):
  83. return
  84. p = doc.add_paragraph()
  85. p.alignment = WD_ALIGN_PARAGRAPH.CENTER
  86. p.add_run().add_picture(path, width=Inches(6.1))
  87. cap = doc.add_paragraph()
  88. cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
  89. run = cap.add_run(caption)
  90. _font(run, 9, False, GRAY)
  91. cap.paragraph_format.space_after = Pt(8)
  92. def _page_field(paragraph):
  93. run = paragraph.add_run()
  94. fld_begin = OxmlElement("w:fldChar")
  95. fld_begin.set(qn("w:fldCharType"), "begin")
  96. instr = OxmlElement("w:instrText")
  97. instr.set(qn("xml:space"), "preserve")
  98. instr.text = "PAGE"
  99. fld_end = OxmlElement("w:fldChar")
  100. fld_end.set(qn("w:fldCharType"), "end")
  101. run._r.append(fld_begin)
  102. run._r.append(instr)
  103. run._r.append(fld_end)
  104. def _setup_header_footer(doc):
  105. for section in doc.sections:
  106. header = section.header
  107. hp = header.paragraphs[0]
  108. hp.alignment = WD_ALIGN_PARAGRAPH.RIGHT
  109. hr = hp.add_run(HEADER_TEXT)
  110. _font(hr, 9, False, GRAY)
  111. footer = section.footer
  112. fp = footer.paragraphs[0]
  113. fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
  114. r1 = fp.add_run("第 ")
  115. _font(r1, 9, False, GRAY)
  116. _page_field(fp)
  117. r2 = fp.add_run(" 页")
  118. _font(r2, 9, False, GRAY)
  119. def _cover(doc, title: str, data: Dict[str, Any]):
  120. for _ in range(4):
  121. doc.add_paragraph()
  122. p = doc.add_paragraph()
  123. p.alignment = WD_ALIGN_PARAGRAPH.CENTER
  124. run = p.add_run(title)
  125. _font(run, 24, True, PRIMARY)
  126. p = doc.add_paragraph()
  127. p.alignment = WD_ALIGN_PARAGRAPH.CENTER
  128. run = p.add_run("——风电机组健康度检测与可靠性分析")
  129. _font(run, 14, False, GRAY)
  130. for _ in range(5):
  131. doc.add_paragraph()
  132. info = [
  133. ("风电场", data["wind"]["name"]),
  134. ("所属单位", data["wind"].get("company") or "—"),
  135. ("分析时段", f"{data['period']['start']} 至 {data['period']['end']}"),
  136. ("装机容量", f"{data['wind'].get('capacity_kw', 0) / 1000:.1f} MW"),
  137. ("机组数量", f"{data['wind'].get('turbine_count', 0)} 台"),
  138. ("生成时间", data["meta"]["generated_at"]),
  139. ]
  140. table = doc.add_table(rows=0, cols=2)
  141. table.alignment = WD_TABLE_ALIGNMENT.CENTER
  142. for k, v in info:
  143. cells = table.add_row().cells
  144. _cell_text(cells[0], k, True, PRIMARY, 11, WD_ALIGN_PARAGRAPH.RIGHT)
  145. _cell_text(cells[1], v, False, None, 11, WD_ALIGN_PARAGRAPH.LEFT)
  146. cells[0].width = Cm(4.0)
  147. cells[1].width = Cm(8.5)
  148. for _ in range(4):
  149. doc.add_paragraph()
  150. p = doc.add_paragraph()
  151. p.alignment = WD_ALIGN_PARAGRAPH.CENTER
  152. run = p.add_run("基于RCM的风电机组健康度检测系统平台")
  153. _font(run, 12, True, PRIMARY)
  154. p = doc.add_paragraph()
  155. p.alignment = WD_ALIGN_PARAGRAPH.CENTER
  156. run = p.add_run("二〇二六年")
  157. _font(run, 11, False, GRAY)
  158. doc.add_page_break()
  159. def _statement(doc):
  160. _heading(doc, "报告说明", 1)
  161. items = [
  162. "本报告由“基于RCM的风电机组健康度检测系统平台”自动生成,数据来源为平台数据库 energy_prod 与业务数据库 energy_data_prod。",
  163. "报告数据与平台「分析概览、健康评估、算法健康评估、故障诊断、振动分析」页面同源;页面无对应时间段结果时,报告明确标注并不回退底层表。",
  164. "报告文字由本机部署的 27B 模型辅助归纳,数值、图表和统计口径由系统程序计算,模型不参与数值计算。",
  165. "受数据接入范围、测点配置、模型适用性和现场检修记录完整性限制,报告结论应作为运维分析的参考,需经专业技术人员复核后使用。",
  166. "本报告所有数据处理与模型调用均在本机完成,不上传互联网。",
  167. ]
  168. for i, t in enumerate(items, 1):
  169. _para(doc, f"{i}. {t}", indent=False)
  170. doc.add_page_break()
  171. def _toc(doc, sections: List[str]):
  172. _heading(doc, "目 录", 1)
  173. for s in sections:
  174. p = doc.add_paragraph()
  175. p.paragraph_format.line_spacing = 2.0
  176. run = p.add_run(s)
  177. _font(run, 11)
  178. doc.add_page_break()
  179. def _section_intro(doc, data: Dict[str, Any]):
  180. _heading(doc, "1 概述", 1)
  181. _heading(doc, "1.1 风场情况", 2)
  182. w = data["wind"]
  183. _table(
  184. doc,
  185. ["项目", "内容"],
  186. [
  187. ["风电场名称", w.get("name")],
  188. ["所属单位", w.get("company") or "—"],
  189. ["装机容量", f"{w.get('capacity_kw', 0) / 1000:.2f} MW"],
  190. ["机组数量", f"{w.get('turbine_count', 0)} 台"],
  191. ["分析时段", f"{data['period']['start']} 至 {data['period']['end']}({data['period']['month_count']} 个月)"],
  192. ],
  193. [4.0, 11.0],
  194. )
  195. _available_dims = []
  196. if (data.get("overview") or {}).get("available"):
  197. _available_dims.append("分析概览")
  198. if (data.get("health") or {}).get("available"):
  199. _available_dims.append("健康评估")
  200. if (data.get("fault") or {}).get("available"):
  201. _available_dims.append("故障诊断")
  202. if (data.get("vibration") or {}).get("available"):
  203. _available_dims.append("振动分析")
  204. _dim_text = "、".join(_available_dims) if _available_dims else "所选数据"
  205. _para(
  206. doc,
  207. f"本报告以{w.get('name')}为分析对象,围绕{_dim_text},"
  208. "对所选时间段内的机组运行状态进行综合分析,识别健康短板与可靠性风险,并提出针对性的运维建议。",
  209. )
  210. _heading(doc, "1.2 分析依据与方法", 2)
  211. _para(
  212. doc,
  213. "分析依据包括风电机组 SCADA 运行数据、故障日志、CMS 振动波形数据以及平台台账与健康评估模型。"
  214. "分析概览采用分钟级数据聚合;健康评估采用风场预训练模型对发电子系统、机舱系统、电网环境和传动系统进行评分;"
  215. "故障诊断按故障发生时间与故障码统计;振动分析对典型测点波形开展时域与频域特征提取。",
  216. )
  217. def _section_data(doc, data: Dict[str, Any]):
  218. _heading(doc, "2 数据与方法", 1)
  219. _heading(doc, "2.1 数据来源", 2)
  220. _table(
  221. doc,
  222. ["数据类别", "来源", "用途"],
  223. [
  224. ["台账数据", "energy_prod.wind_field / wind_engine_group", "风场、机组、机型与容量"],
  225. ["SCADA 分钟数据", f"energy_data_prod.{data['wind']['code']}_minute", "发电量、风速、功率、数据完整率"],
  226. ["健康评估", "健康评估模型 + 平台台账", "机组与子系统健康得分"],
  227. ["故障日志", f"energy_data_prod.{data['wind']['code']}_fault", "故障次数、故障码与影响机组"],
  228. ["振动波形", f"energy_data_prod.{data['wind']['code']}_wave", "测点覆盖、采样频率与频谱特征"],
  229. ],
  230. [4.0, 8.5, 6.0],
  231. )
  232. _heading(doc, "2.2 数据质量与口径", 2)
  233. ov = data.get("overview") or {}
  234. notes = []
  235. if ov.get("available"):
  236. notes.append(f"分钟级数据完整率约 {ov.get('completeness')}%,统计口径为月内实际记录数与应有分钟数之比。")
  237. else:
  238. notes.append(f"分析概览数据不足:{ov.get('error', '未取得分钟级数据')}。")
  239. for key, label in [("health", "健康评估"), ("fault", "故障日志"), ("vibration", "振动波形")]:
  240. sec = data.get(key) or {}
  241. if not sec.get("available"):
  242. notes.append(f"{label}数据不足:{sec.get('error', '未取得有效记录')}。")
  243. if not notes:
  244. notes.append("各类数据均已取得有效记录,具体覆盖范围见各章节。")
  245. for n in notes:
  246. _para(doc, f"· {n}", indent=False, size=10)
  247. def _section_overview(doc, data: Dict[str, Any], tmp: str):
  248. _heading(doc, "3 分析概览", 1)
  249. ov = data.get("overview") or {}
  250. _para(doc, narrative.overview_text(data))
  251. if not ov.get("available"):
  252. return
  253. _heading(doc, "3.1 关键指标", 2)
  254. _table(
  255. doc,
  256. ["指标", "数值", "说明"],
  257. [
  258. ["累计发电量", f"{ov.get('total_mwh'):,.2f} MWh", "分钟级有功功率积分"],
  259. ["等效满负荷小时", f"{ov.get('equivalent_hours')} h", "发电量 / 装机容量"],
  260. ["平均风速", f"{ov.get('avg_wind')} m/s", "按记录数加权"],
  261. ["容量系数", f"{ov.get('capacity_factor')}%", "发电量 /(容量×时段小时数)"],
  262. ["数据完整率", f"{ov.get('completeness')}%", "实际记录 / 应有分钟记录"],
  263. ],
  264. [4.2, 5.0, 7.0],
  265. )
  266. _heading(doc, "3.2 月度趋势", 2)
  267. rows = [
  268. [m["month"], f"{m.get('gen_mwh', 0):,.2f}", f"{m.get('avg_wind')}", f"{m.get('completeness')}%"]
  269. for m in ov.get("monthly", [])
  270. ]
  271. if rows:
  272. _table(doc, ["月份", "发电量(MWh)", "平均风速(m/s)", "完整率"], rows, [3.0, 4.5, 4.5, 3.5])
  273. _image(doc, charts.monthly_generation(ov.get("monthly", []), os.path.join(tmp, "monthly_gen.png")), "图 3-1 月度发电量与平均风速")
  274. _heading(doc, "3.3 机组发电量对比", 2)
  275. _para(
  276. doc,
  277. "按机组统计发电量并排序,可快速识别低效机组。机组间差异需结合机位风速、限电、停机与故障记录综合判断,"
  278. "不宜仅凭发电量排名直接认定机组性能异常。",
  279. )
  280. trows = [
  281. [t.get("rank"), t.get("name"), f"{t.get('gen_mwh', 0):,.2f}", f"{t.get('avg_wind')}", t.get("points")]
  282. for t in ov.get("turbines", [])[:12]
  283. ]
  284. if trows:
  285. _table(doc, ["排名", "机组", "发电量(MWh)", "平均风速(m/s)", "记录数"], trows, [2.0, 4.0, 4.5, 4.0, 3.0])
  286. _image(doc, charts.turbine_generation(ov.get("turbines", []), os.path.join(tmp, "turbine_gen.png")), "图 3-2 机组发电量排名")
  287. def _section_health(doc, data: Dict[str, Any], tmp: str):
  288. _heading(doc, "4 健康评估", 1)
  289. h = data.get("health") or {}
  290. _para(doc, narrative.health_text(data))
  291. if not h.get("available"):
  292. return
  293. _heading(doc, "4.1 总体健康水平", 2)
  294. dist = h.get("distribution") or {}
  295. _table(
  296. doc,
  297. ["指标", "数值"],
  298. [
  299. ["评估机组数", len(h.get("turbines", []))],
  300. ["平均健康得分", h.get("avg_score")],
  301. ["健康 / 亚健康", f"{dist.get('healthy', 0)} / {dist.get('subhealthy', 0)} 台"],
  302. ["一般 / 故障", f"{dist.get('normal', 0)} / {dist.get('fault', 0)} 台"],
  303. ["无数据", f"{dist.get('nodata', 0)} 台"],
  304. ["评估月份", "、".join(h.get("assessed_months", []))],
  305. ],
  306. [5.0, 9.0],
  307. )
  308. _image(doc, charts.health_distribution(dist, os.path.join(tmp, "health_dist.png")), "图 4-1 机组健康等级分布")
  309. _heading(doc, "4.2 子系统健康水平", 2)
  310. sub = h.get("subsystems") or {}
  311. _table(
  312. doc,
  313. ["子系统", "平均得分", "关注点"],
  314. [
  315. ["发电机组", sub.get("generator"), "绕组、轴承温度与电气量"],
  316. ["机舱系统", sub.get("nacelle"), "机舱振动、温度与位置"],
  317. ["电网环境", sub.get("grid"), "电流、功率与并网质量"],
  318. ["传动系统", sub.get("drive_train"), "主轴承、齿轮箱温度"],
  319. ],
  320. [4.5, 4.0, 8.0],
  321. )
  322. _image(doc, charts.health_subsystems(sub, os.path.join(tmp, "health_subsys.png")), "图 4-2 子系统平均健康得分")
  323. _heading(doc, "4.3 机组健康明细", 2)
  324. rows = [
  325. [
  326. t.get("name"),
  327. t.get("score"),
  328. t.get("generator"),
  329. t.get("nacelle"),
  330. t.get("grid"),
  331. t.get("drive_train"),
  332. ]
  333. for t in h.get("turbines", [])[:20]
  334. ]
  335. if rows:
  336. _table(doc, ["机组", "总分", "发电机组", "机舱", "电网", "传动"], rows, [4.0, 2.5, 3.0, 2.6, 2.6, 2.6])
  337. _image(doc, charts.health_ranking(h.get("turbines", []), os.path.join(tmp, "health_rank.png")), "图 4-3 机组健康得分")
  338. if h.get("low_turbines"):
  339. _para(doc, "建议优先关注以下低分机组:", indent=False, bold=True)
  340. for t in h["low_turbines"][:8]:
  341. _para(doc, f"· {t.get('name')}:总分 {t.get('score')},发电机组 {t.get('generator')},机舱 {t.get('nacelle')},电网 {t.get('grid')},传动 {t.get('drive_train')}。", indent=False, size=9.5)
  342. def _section_fault(doc, data: Dict[str, Any], tmp: str):
  343. _heading(doc, "5 故障诊断", 1)
  344. f = data.get("fault") or {}
  345. _para(doc, narrative.fault_text(data))
  346. if not f.get("available"):
  347. return
  348. _heading(doc, "5.1 故障统计", 2)
  349. _table(
  350. doc,
  351. ["指标", "数值"],
  352. [["故障总次数", f.get("total")], ["影响机组数", f.get("affected_turbines")]],
  353. [5.0, 9.0],
  354. )
  355. _image(doc, charts.fault_monthly(f.get("monthly", []), os.path.join(tmp, "fault_monthly.png")), "图 5-1 月度故障次数")
  356. _heading(doc, "5.2 高频故障码", 2)
  357. rows = [[c.get("code"), c.get("count"), c.get("turbines")] for c in f.get("top_codes", [])]
  358. if rows:
  359. _table(doc, ["故障码", "次数", "影响机组数"], rows, [8.0, 3.0, 4.0])
  360. _image(doc, charts.fault_top(f.get("top_codes", []), os.path.join(tmp, "fault_top.png")), "图 5-2 高频故障码")
  361. _heading(doc, "5.3 故障机组分布", 2)
  362. rows = [[t.get("name"), t.get("count")] for t in f.get("turbines", [])]
  363. if rows:
  364. _table(doc, ["机组", "故障次数"], rows, [7.0, 5.0])
  365. def _section_vibration(doc, data: Dict[str, Any], tmp: str):
  366. _heading(doc, "6 振动分析", 1)
  367. v = data.get("vibration") or {}
  368. _para(doc, narrative.vibration_text(data))
  369. if not v.get("available"):
  370. return
  371. _heading(doc, "6.1 波形覆盖情况", 2)
  372. _table(
  373. doc,
  374. ["指标", "数值"],
  375. [
  376. ["波形记录数", v.get("total")],
  377. ["覆盖机组数", v.get("turbine_count")],
  378. ["测点数", v.get("point_count")],
  379. ["最早记录", v.get("min_time")],
  380. ["最新记录", v.get("max_time")],
  381. ],
  382. [5.0, 9.0],
  383. )
  384. _image(doc, charts.vibration_monthly(v.get("monthly", []), os.path.join(tmp, "vib_monthly.png")), "图 6-1 月度振动波形记录量")
  385. _heading(doc, "6.2 测点与采样频率", 2)
  386. rows = [[p.get("point"), p.get("count"), p.get("fs")] for p in v.get("points", [])]
  387. if rows:
  388. _table(doc, ["测点", "记录数", "平均采样频率(Hz)"], rows, [9.0, 3.0, 4.0])
  389. _heading(doc, "6.3 典型频谱", 2)
  390. spec = v.get("spectrum")
  391. if spec:
  392. _para(
  393. doc,
  394. f"示例波形来自 {spec.get('point')},采集时间 {spec.get('time')},采样频率 {spec.get('fs')} Hz,"
  395. f"转速 {spec.get('rpm')} rpm,振动有效值约 {spec.get('rms')}。频谱仅用于展示波形特征,"
  396. "部件级诊断仍需结合轴承参数、测点方向和历史趋势。",
  397. )
  398. _image(doc, charts.vibration_spectrum(spec, os.path.join(tmp, "vib_spectrum.png")), "图 6-2 典型振动频谱")
  399. else:
  400. _para(doc, "所选时间段内未找到可解析的波形记录,无法生成频谱示例。", indent=False)
  401. def _section_conclusion(doc, data: Dict[str, Any]):
  402. _heading(doc, "7 结论与建议", 1)
  403. text = narrative.conclusion_text(data)
  404. for line in text.split("\n"):
  405. line = line.strip()
  406. if not line:
  407. continue
  408. if line.startswith("(") or line.startswith("-") or line[:2].isdigit():
  409. _para(doc, line, indent=False)
  410. else:
  411. _para(doc, line)
  412. def _appendix(doc, data: Dict[str, Any]):
  413. _heading(doc, "附录 数据与模型说明", 1)
  414. _para(
  415. doc,
  416. "1. 健康评估得分范围为0-100分,分数越低表示健康状态越差;-1表示该机组在该月无有效评估结果。",
  417. indent=False,
  418. )
  419. _para(
  420. doc,
  421. "2. 分析概览的发电量由分钟级有功功率积分得到,未扣减场用电、线损及限电损失,与电量结算口径可能存在差异。",
  422. indent=False,
  423. )
  424. _para(
  425. doc,
  426. "3. 故障统计仅基于故障日志表,未区分电网、输变电、计划检修等外部原因,需结合现场记录复核。",
  427. indent=False,
  428. )
  429. _para(
  430. doc,
  431. "4. 振动频谱示例仅取所选时段内一条典型波形,不能代表机组全部运行工况。",
  432. indent=False,
  433. )
  434. _para(
  435. doc,
  436. f"5. 本报告生成时间:{data['meta']['generated_at']};生成模型:{os.getenv('OLLAMA_MODEL', 'qwen3.8:27b-q8_0')}(本机 Ollama),审核模型:{os.getenv('REVIEW_MODEL', 'deepseek-r1:14b')}。",
  437. indent=False,
  438. )
  439. def _section_skipped(doc, title: str):
  440. _heading(doc, title, 1)
  441. _para(doc, "本报告生成时未勾选该章节,故不包含对应分析内容。", indent=False)
  442. def build_report(data: Dict[str, Any], tmp_dir: str, output_path: str, title: Optional[str] = None,
  443. sections: Optional[List[str]] = None):
  444. os.makedirs(tmp_dir, exist_ok=True)
  445. os.makedirs(os.path.dirname(output_path), exist_ok=True)
  446. doc = Document()
  447. section = doc.sections[0]
  448. section.top_margin = Cm(2.2)
  449. section.bottom_margin = Cm(2.2)
  450. section.left_margin = Cm(2.6)
  451. section.right_margin = Cm(2.6)
  452. _setup_header_footer(doc)
  453. normal = doc.styles["Normal"]
  454. normal.font.name = "微软雅黑"
  455. normal.font.size = Pt(10.5)
  456. normal._element.rPr.rFonts.set(qn("w:eastAsia"), "微软雅黑")
  457. report_title = title or f"{data['wind']['name']}风电机组健康度分析报告"
  458. _cover(doc, report_title, data)
  459. _statement(doc)
  460. toc_items = [
  461. "1 概述",
  462. "2 数据与方法",
  463. "3 分析概览",
  464. "4 健康评估",
  465. "5 故障诊断",
  466. "6 振动分析",
  467. "7 结论与建议",
  468. "附录 数据与模型说明",
  469. ]
  470. _toc(doc, toc_items)
  471. _section_intro(doc, data)
  472. _section_data(doc, data)
  473. selected = set(sections or ["overview", "health", "fault", "vibration"])
  474. if "overview" in selected:
  475. _section_overview(doc, data, tmp_dir)
  476. else:
  477. _section_skipped(doc, "3 分析概览")
  478. if "health" in selected:
  479. _section_health(doc, data, tmp_dir)
  480. else:
  481. _section_skipped(doc, "4 健康评估")
  482. if "fault" in selected:
  483. _section_fault(doc, data, tmp_dir)
  484. else:
  485. _section_skipped(doc, "5 故障诊断")
  486. if "vibration" in selected:
  487. _section_vibration(doc, data, tmp_dir)
  488. else:
  489. _section_skipped(doc, "6 振动分析")
  490. _section_conclusion(doc, data)
  491. _appendix(doc, data)
  492. doc.core_properties.title = report_title
  493. doc.core_properties.author = HEADER_TEXT
  494. doc.core_properties.subject = f"{data['wind']['name']} {data['period']['start']} 至 {data['period']['end']}"
  495. doc.save(output_path)
  496. return output_path