generator.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. """报告任务执行与文件落盘。"""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import re
  6. import threading
  7. import traceback
  8. from datetime import datetime
  9. from typing import Any, Dict, List
  10. from app.report import collector, docx_builder, ollama_client, reviewer
  11. BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  12. REPORT_DIR = os.path.join(BASE_DIR, "output", "reports")
  13. TMP_ROOT = os.path.join(BASE_DIR, "output", "report_tmp")
  14. MANIFEST = os.path.join(REPORT_DIR, "manifest.json")
  15. _LOCK = threading.Lock()
  16. def ensure_dirs():
  17. os.makedirs(REPORT_DIR, exist_ok=True)
  18. os.makedirs(TMP_ROOT, exist_ok=True)
  19. def _safe_name(value: str) -> str:
  20. value = re.sub(r"[\\/:*?\"<>|\r\n]+", "_", value or "")
  21. return value[:80]
  22. def _read_manifest() -> List[Dict[str, Any]]:
  23. ensure_dirs()
  24. if not os.path.exists(MANIFEST):
  25. return []
  26. try:
  27. with open(MANIFEST, "r", encoding="utf-8") as f:
  28. data = json.load(f)
  29. return data if isinstance(data, list) else []
  30. except Exception:
  31. return []
  32. def _write_manifest(items: List[Dict[str, Any]]):
  33. ensure_dirs()
  34. tmp = MANIFEST + ".tmp"
  35. with open(tmp, "w", encoding="utf-8") as f:
  36. json.dump(items[-200:], f, ensure_ascii=False, indent=2, default=str)
  37. os.replace(tmp, MANIFEST)
  38. def list_reports(wind_code: str | None = None, limit: int = 20) -> List[Dict[str, Any]]:
  39. items = _read_manifest()
  40. if wind_code:
  41. items = [x for x in items if x.get("wind_code") == wind_code]
  42. items.sort(key=lambda x: x.get("created_at", ""), reverse=True)
  43. return items[:limit]
  44. def run_job(job_id: str, request: Dict[str, Any], store: Dict[str, Dict[str, Any]]):
  45. job = store[job_id]
  46. job["status"] = "running"
  47. def update(progress: int, message: str):
  48. job.update(progress=progress, message=message, updated_at=datetime.now().isoformat(timespec="seconds"))
  49. try:
  50. ensure_dirs()
  51. update(5, "校验风场与时间范围…")
  52. wind_code = request["windCode"]
  53. start_month = request["startMonth"]
  54. end_month = request["endMonth"]
  55. collector.month_list(start_month, end_month) # 校验
  56. update(10, "采集分析概览、故障与振动数据…")
  57. data = collector.collect_all(
  58. wind_code, start_month, end_month, sections=request.get("sections")
  59. )
  60. update(55, f"调用本机 {ollama_client.OLLAMA_MODEL} 撰写报告文字…")
  61. # 文字在 docx_builder 内部按章节调用;此处仅更新阶段提示
  62. update(65, "生成图表与 Word 文档…")
  63. ts = datetime.now().strftime("%Y%m%d_%H%M%S")
  64. title = request.get("title") or f"{data['wind']['name']}风电机组健康度分析报告"
  65. filename = f"{_safe_name(data['wind']['name'])}_{start_month}_{end_month}_健康度分析报告_{ts}.docx"
  66. output_path = os.path.join(REPORT_DIR, filename)
  67. tmp_dir = os.path.join(TMP_ROOT, job_id)
  68. docx_builder.build_report(
  69. data, tmp_dir, output_path, title=title, sections=request.get("sections")
  70. )
  71. update(84, f"调用本机 {ollama_client.REVIEW_MODEL} 审核报告…")
  72. review_text = reviewer.review_report(output_path, data)
  73. review_status = reviewer.append_review(
  74. output_path,
  75. review_text,
  76. report_model=ollama_client.OLLAMA_MODEL,
  77. review_model=ollama_client.REVIEW_MODEL,
  78. )
  79. update(95, "报告已生成,正在登记…")
  80. record = {
  81. "job_id": job_id,
  82. "wind_code": wind_code,
  83. "wind_name": data["wind"]["name"],
  84. "period": f"{start_month} 至 {end_month}",
  85. "title": title,
  86. "file_name": filename,
  87. "download_url": f"/reports/{filename}",
  88. "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  89. "model": ollama_client.OLLAMA_MODEL,
  90. "review_model": ollama_client.REVIEW_MODEL,
  91. "review_status": review_status,
  92. "review_excerpt": (review_text or "")[:500],
  93. "summary": {
  94. "total_mwh": (data.get("overview") or {}).get("total_mwh"),
  95. "avg_health": (data.get("health") or {}).get("avg_score"),
  96. "fault_total": (data.get("fault") or {}).get("total"),
  97. "vibration_total": (data.get("vibration") or {}).get("total"),
  98. },
  99. }
  100. with _LOCK:
  101. items = _read_manifest()
  102. items.append(record)
  103. _write_manifest(items)
  104. job.update(
  105. status="done",
  106. progress=100,
  107. message="报告生成完成(27B 生成 + 14B 审核)",
  108. file_name=filename,
  109. download_url=record["download_url"],
  110. wind_name=record["wind_name"],
  111. summary=record["summary"],
  112. model=record["model"],
  113. review_model=record["review_model"],
  114. review_status=record["review_status"],
  115. finished_at=datetime.now().isoformat(timespec="seconds"),
  116. )
  117. except Exception as exc:
  118. job.update(
  119. status="failed",
  120. progress=100,
  121. message="报告生成失败",
  122. error=str(exc),
  123. traceback=traceback.format_exc()[-4000:],
  124. finished_at=datetime.now().isoformat(timespec="seconds"),
  125. )