Ver código fonte

feat: criteria-based conclusions with 27B summary and 14B review

zhouyang.xie 1 semana atrás
pai
commit
2df65b08d8
3 arquivos alterados com 197 adições e 28 exclusões
  1. 145 0
      app/report/criteria.py
  2. 33 0
      app/report/generator.py
  3. 19 28
      app/report/template_builder.py

+ 145 - 0
app/report/criteria.py

@@ -0,0 +1,145 @@
+"""结论判据:从五个页面同源数据中提取可量化判据、阈值与判定,保证结论可靠、明确、判据呼应。"""
+from __future__ import annotations
+
+from typing import Any, Dict, List
+
+
+def _band(score: float) -> str:
+    if score is None:
+        return "未评估"
+    if score >= 85:
+        return "优"
+    if score >= 70:
+        return "良"
+    if score >= 55:
+        return "关注"
+    return "差"
+
+
+def build_criteria(data: Dict[str, Any]) -> Dict[str, Any]:
+    ov = data.get("overview") or {}
+    h = data.get("health") or {}
+    ah = data.get("algorithm_health") or {}
+    f = data.get("fault") or {}
+    v = data.get("vibration") or {}
+
+    rows: List[Dict[str, Any]] = []
+    conclusions: List[str] = []
+    suggestions: List[str] = []
+
+    # 1 能效/分析概览
+    total_mwh = ov.get("total_mwh")
+    eq_hours = ov.get("equivalent_hours")
+    avg_wind = ov.get("avg_wind")
+    if ov.get("available") and total_mwh is not None:
+        verdict = "低" if (eq_hours is not None and eq_hours < 1500) else "正常"
+        rows.append({
+            "dim": "能效",
+            "criterion": "等效满负荷小时 ≥ 1500 h 为正常,< 1500 h 为低",
+            "threshold": "1500 h",
+            "value": f"{eq_hours} h",
+            "verdict": verdict,
+        })
+        conclusions.append(
+            f"能效判据:等效满负荷小时 {eq_hours} h,{('低于' if verdict == '低' else '达到')} 1500 h 判据,"
+            f"判定为能效{verdict};累计发电量 {total_mwh} MWh,平均风速 {avg_wind} m/s。"
+        )
+    else:
+        rows.append({"dim": "能效", "criterion": "分析概览页面需有对应批次结果", "threshold": "有批次", "value": "无", "verdict": "无法判定"})
+        conclusions.append("能效判据:分析概览页面无覆盖所选时间段的已完成分析批次,暂不判定能效。")
+
+    # 2 健康评估
+    avg_score = h.get("avg_score")
+    if h.get("available") and avg_score is not None:
+        band = _band(avg_score)
+        low = len(h.get("low_turbines") or [])
+        rows.append({
+            "dim": "健康评估",
+            "criterion": "健康得分 ≥85 优、70–85 良、55–70 关注、<55 差",
+            "threshold": "70 分(良)",
+            "value": f"{avg_score} 分",
+            "verdict": band,
+        })
+        conclusions.append(
+            f"健康评估判据:平均健康得分 {avg_score} 分,达到“{band}”等级判据;"
+            f"低分机组 {low} 台(<70 分),应优先核查。"
+        )
+    else:
+        rows.append({"dim": "健康评估", "criterion": "健康评估页面需有有效评估结果", "threshold": "有结果", "value": "无", "verdict": "无法判定"})
+        conclusions.append("健康评估判据:页面无有效评估结果,暂不判定健康状态。")
+
+    # 3 算法健康评估
+    ah_turbines = ah.get("turbines") or []
+    if ah.get("available"):
+        scored = sum(1 for t in ah_turbines if (t.get("overall") or {}).get("status") == "scored")
+        not_scored = len(ah_turbines) - scored
+        rows.append({
+            "dim": "算法健康评估",
+            "criterion": "可评分系统数 ≥ 适用系统半数时输出总分,否则总分未评估",
+            "threshold": "可评分系统 ≥ 半数",
+            "value": f"{scored}/{len(ah_turbines)} 台已评分",
+            "verdict": "已评估" if not_scored == 0 else "部分未评估",
+        })
+        conclusions.append(
+            f"算法健康评估判据:期次 {ah.get('period')},共 {len(ah_turbines)} 台,"
+            f"{scored} 台输出总分、{not_scored} 台因可评分系统未达半数显示未评估,符合“半数可评”判据。"
+        )
+    else:
+        rows.append({"dim": "算法健康评估", "criterion": "所选时间段内需有算法健康评估期次", "threshold": "有期次", "value": "无", "verdict": "无法判定"})
+        conclusions.append("算法健康评估判据:所选时间段内无可用期次,暂不判定。")
+
+    # 4 故障诊断
+    f_total = f.get("total") or 0
+    if f.get("available"):
+        affected = f.get("affected_turbines") or 0
+        severity = "重点关注" if affected >= 3 else "关注"
+        rows.append({
+            "dim": "故障诊断",
+            "criterion": "诊断结果 >0 即存在故障风险;影响机组数决定关注等级",
+            "threshold": ">0 次",
+            "value": f"{f_total} 次 / {affected} 台",
+            "verdict": severity,
+        })
+        conclusions.append(
+            f"故障诊断判据:诊断结果 {f_total} 次、影响 {affected} 台机组,满足“>0 次即存在风险”判据,判定为“{severity}”。"
+        )
+    else:
+        rows.append({"dim": "故障诊断", "criterion": "故障诊断页面需有诊断结果", "threshold": ">0 次", "value": "0 次", "verdict": "无诊断结果"})
+        conclusions.append("故障诊断判据:所选时间段无诊断结果,判定为“无诊断结果”,不代表设备无故障。")
+
+    # 5 振动分析
+    v_total = v.get("total") or 0
+    if v.get("available"):
+        rows.append({
+            "dim": "振动分析",
+            "criterion": "CMS 波形记录量覆盖主要测点;频谱特征频率峰值作为复核依据",
+            "threshold": ">0 条",
+            "value": f"{v_total} 条 / {v.get('turbine_count', 0)} 台",
+            "verdict": "已覆盖",
+        })
+        conclusions.append(
+            f"振动分析判据:CMS 波形 {v_total} 条、覆盖 {v.get('turbine_count', 0)} 台机组,"
+            "满足“>0 条”覆盖判据;部件级结论以频谱特征频率复核为准。"
+        )
+    else:
+        rows.append({"dim": "振动分析", "criterion": "振动分析页面需有 CMS 波形", "threshold": ">0 条", "value": "0 条", "verdict": "无数据"})
+        conclusions.append("振动分析判据:无 CMS 波形数据,暂不判定振动状态。")
+
+    # 建议(与结论一一呼应)
+    for c in conclusions:
+        if "能效" in c:
+            suggestions.append("补充完整生产指标与限电/停机标签数据,量化电量损失并制定能效提升措施。")
+        if "健康" in c:
+            suggestions.append("对健康评估低分机组(<70 分)开展传感器、润滑、冷却与控制参数专项检查。")
+        if "算法健康" in c:
+            suggestions.append("对算法健康评估中“未评估”机组补齐可评分系统数据后再判定总分。")
+        if "故障" in c:
+            suggestions.append("对故障诊断结果中高频诊断类型建立治理清单,结合备件、工单闭环跟踪。")
+        if "振动" in c:
+            suggestions.append("对 CMS 频谱特征频率异常测点开展离线振动检测复核。")
+
+    # 去重保序
+    seen = set()
+    suggestions = [s for s in suggestions if not (s in seen or seen.add(s))]
+
+    return {"rows": rows, "conclusions": conclusions, "suggestions": suggestions}

+ 33 - 0
app/report/generator.py

@@ -48,6 +48,24 @@ def _write_manifest(items: List[Dict[str, Any]]):
     os.replace(tmp, MANIFEST)
 
 
+def _facts_for_llm(data: Dict[str, Any]) -> str:
+    ov = data.get("overview") or {}
+    h = data.get("health") or {}
+    ah = data.get("algorithm_health") or {}
+    f = data.get("fault") or {}
+    v = data.get("vibration") or {}
+    lines = [
+        f"风场:{data['wind']['name']},时段 {data['period']['start']} 至 {data['period']['end']}。",
+        f"能效:累计发电量 {ov.get('total_mwh')} MWh,等效满负荷小时 {ov.get('equivalent_hours')} h,平均风速 {ov.get('avg_wind')} m/s。",
+        f"健康评估:平均得分 {h.get('avg_score')},低分机组 {len(h.get('low_turbines') or [])} 台。",
+        f"算法健康评估:期次 {ah.get('period')},机组数 {len(ah.get('turbines') or [])}。",
+        f"故障诊断:诊断结果 {f.get('total') or 0} 次,影响 {f.get('affected_turbines') or 0} 台。",
+        f"振动分析:CMS 波形 {v.get('total') or 0} 条,覆盖 {v.get('turbine_count') or 0} 台。",
+        "判据:能效等效小时<1500为低;健康得分≥85优/70-85良/55-70关注/<55差;故障>0即存在风险;振动以频谱特征频率复核为准。",
+    ]
+    return "\n".join(lines)
+
+
 def list_reports(wind_code: str | None = None, limit: int = 20) -> List[Dict[str, Any]]:
     items = _read_manifest()
     if wind_code:
@@ -82,6 +100,21 @@ def run_job(job_id: str, request: Dict[str, Any], store: Dict[str, Dict[str, Any
             os.path.join(TMP_ROOT, job_id, "page_charts"),
         )
 
+        update(56, f"调用本机 {ollama_client.OLLAMA_MODEL} 撰写结论综述…")
+        facts = _facts_for_llm(data)
+        data["llm_conclusion"] = ollama_client.chat_model(
+            ollama_client.OLLAMA_MODEL,
+            system=(
+                "你是风电场可靠性与能效分析专家。请根据给定判据和本期数据,"
+                "写一段 150 字以内的结论综述,结论明确、可执行,并与判据呼应。"
+                "只输出结论正文,不要输出标题或编号。"
+            ),
+            user=facts,
+            temperature=0.2,
+            num_predict=400,
+            timeout=int(os.getenv("LLM_TIMEOUT", "120")),
+        )
+
         update(55, f"调用本机 {ollama_client.OLLAMA_MODEL} 撰写报告文字…")
         # 文字在 docx_builder 内部按章节调用;此处仅更新阶段提示
         update(65, "生成图表与 Word 文档…")

+ 19 - 28
app/report/template_builder.py

@@ -396,35 +396,26 @@ def _section_power_curve(doc, data: Dict[str, Any]):
 
 
 def _section_conclusion(doc, data: Dict[str, Any]):
+    from app.report import criteria
+
     L._heading(doc, "8 结论及建议", 1)
-    ov, h, f, v = (data.get(k) or {} for k in ("overview", "health", "fault", "vibration"))
-    points = []
-    if ov.get("available"):
-        points.append(
-            f"分析期内累计发电量约 {_num(ov.get('total_mwh'), 2, ' MWh')},平均风速约 "
-            f"{_num(ov.get('avg_wind'), 2, ' m/s')},数据完整率约 {_num(ov.get('completeness'), 2, '%')}。"
-        )
-    if h.get("available"):
-        points.append(
-            f"健康评估覆盖 {len(h.get('turbines') or [])} 台机组,平均健康得分 {_num(h.get('avg_score'), 2)};"
-            "低分机组应优先纳入现场核查。"
-        )
-    if f.get("available"):
-        points.append(f"故障统计共 {f.get('total', 0)} 次,影响 {f.get('affected_turbines', 0)} 台机组,建议优先治理高频故障码。")
-    if v.get("available"):
-        points.append(f"CMS 波形记录 {v.get('total', 0)} 条,覆盖 {v.get('turbine_count', 0)} 台机组;建议对典型频谱异常测点开展复核。")
-    if not points:
-        points.append("本期数据不足,暂不形成具体结论。")
-    for p in points:
-        L._para(doc, f"· {p}", indent=False)
-    L._para(doc, "建议:", indent=False, bold=True)
-    for s in (
-        "对健康评估低分机组和故障集中机组开展专项检查,核实传感器、润滑、冷却和控制参数状态。",
-        "补齐偏航误差、变桨系统、主控参数和功率曲线专项数据,完善后续报告分析。",
-        "对高频故障码建立治理清单,结合备件、工单和现场检修记录闭环跟踪。",
-        "对 CMS 振动异常测点开展频谱复核,必要时开展离线振动检测。",
-    ):
-        L._para(doc, f"· {s}", indent=False, size=10)
+    cr = criteria.build_criteria(data)
+    L._heading(doc, "8.1 判据", 2)
+    L._table(
+        doc,
+        ["维度", "判据", "阈值", "本期值", "判定"],
+        [[r["dim"], r["criterion"], r["threshold"], r["value"], r["verdict"]] for r in cr["rows"]],
+        [2.4, 6.0, 2.4, 2.6, 2.0],
+    )
+    L._heading(doc, "8.2 结论", 2)
+    for i, c in enumerate(cr["conclusions"], 1):
+        L._para(doc, f"{i}. {c}", indent=False)
+    L._heading(doc, "8.3 建议", 2)
+    for i, s in enumerate(cr["suggestions"], 1):
+        L._para(doc, f"{i}. {s}", indent=False, size=10)
+    if data.get("llm_conclusion"):
+        L._heading(doc, "8.4 模型综述", 2)
+        L._para(doc, data["llm_conclusion"], indent=False)
 
 
 def _section_page_images(doc, data: Dict[str, Any]):