health_assessment.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. """健康评估结果只读接口。
  2. 算法服务器/平台导入后的 health.json 与 Word 报告落在 HDKG_OUT_ROOT:
  3. <root>/<fieldCode>/<YYYY-MM>/detail/health.json
  4. <root>/<fieldCode>/<YYYY-MM>/report/internal.docx
  5. <root>/<fieldCode>/<YYYY-MM>/report/external.docx
  6. <root>/<fieldCode>/<YYYY-MM>/registration.json
  7. 本路由只读文件,不触发批次、不写数据库;批次仍由 hdkg-run 或平台导入任务完成。
  8. """
  9. from __future__ import annotations
  10. import json
  11. import os
  12. import re
  13. from pathlib import Path
  14. from typing import Any, Dict, List, Optional
  15. from fastapi import APIRouter, HTTPException
  16. from fastapi.responses import FileResponse
  17. router = APIRouter(prefix="/health-assessment", tags=["health-assessment"])
  18. OUT_ROOT = Path(os.getenv("HDKG_OUT_ROOT", "/data/hdkg/out")).resolve()
  19. FIELD_RE = re.compile(r"^WOF\d{9,}$")
  20. PERIOD_RE = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
  21. def _safe_parts(field_code: str, period: str) -> tuple[str, str]:
  22. if not FIELD_RE.match(field_code or ""):
  23. raise HTTPException(status_code=400, detail="fieldCode 格式不正确")
  24. if not PERIOD_RE.match(period or ""):
  25. raise HTTPException(status_code=400, detail="period 须为 YYYY-MM")
  26. return field_code, period
  27. def _period_dir(field_code: str, period: str) -> Path:
  28. field_code, period = _safe_parts(field_code, period)
  29. p = (OUT_ROOT / field_code / period).resolve()
  30. if OUT_ROOT not in p.parents and p != OUT_ROOT:
  31. raise HTTPException(status_code=400, detail="路径不合法")
  32. return p
  33. def _read_json(path: Path) -> Optional[Dict[str, Any]]:
  34. try:
  35. with open(path, "r", encoding="utf-8") as f:
  36. return json.load(f)
  37. except (OSError, ValueError):
  38. return None
  39. @router.get("/periods")
  40. def periods(fieldCode: str) -> Dict[str, Any]:
  41. """列出某场已发布期次;没有产物时返回空数组,不报 500。"""
  42. if not FIELD_RE.match(fieldCode or ""):
  43. raise HTTPException(status_code=400, detail="fieldCode 格式不正确")
  44. field_dir = (OUT_ROOT / fieldCode).resolve()
  45. if not field_dir.is_dir():
  46. return {"code": 200, "data": []}
  47. out: List[Dict[str, Any]] = []
  48. for period_dir in sorted(field_dir.iterdir(), reverse=True):
  49. if not period_dir.is_dir() or not PERIOD_RE.match(period_dir.name):
  50. continue
  51. reg = _read_json(period_dir / "registration.json") or {}
  52. detail = period_dir / "detail/health.json"
  53. if not detail.is_file() and not reg:
  54. continue
  55. out.append(
  56. {
  57. "fieldCode": fieldCode,
  58. "period": period_dir.name,
  59. "status": reg.get("status") or ("ok" if detail.is_file() else "unknown"),
  60. "detailAvailable": detail.is_file(),
  61. "internalReportAvailable": (period_dir / "report/internal.docx").is_file(),
  62. "externalReportAvailable": (period_dir / "report/external.docx").is_file(),
  63. "tables": reg.get("tables"),
  64. "error": reg.get("error"),
  65. }
  66. )
  67. return {"code": 200, "data": out}
  68. @router.get("/detail")
  69. def detail(fieldCode: str, period: str) -> Dict[str, Any]:
  70. """读取前端版 health.json(不含 health_full 内部版)。"""
  71. period_dir = _period_dir(fieldCode, period)
  72. p = period_dir / "detail/health.json"
  73. if not p.is_file():
  74. raise HTTPException(status_code=404, detail="该场该期暂无 health.json")
  75. doc = _read_json(p)
  76. if not isinstance(doc, dict):
  77. raise HTTPException(status_code=500, detail="health.json 不是合法 JSON 对象")
  78. return {"code": 200, "data": doc}
  79. @router.get("/registration")
  80. def registration(fieldCode: str, period: str) -> Dict[str, Any]:
  81. period_dir = _period_dir(fieldCode, period)
  82. doc = _read_json(period_dir / "registration.json")
  83. if not isinstance(doc, dict):
  84. raise HTTPException(status_code=404, detail="暂无 registration.json")
  85. return {"code": 200, "data": doc}
  86. @router.get("/report")
  87. def report(fieldCode: str, period: str, edition: str = "internal"):
  88. """下载内部版/对外版 Word 报告。"""
  89. if edition not in ("internal", "external"):
  90. raise HTTPException(status_code=400, detail="edition 只支持 internal/external")
  91. period_dir = _period_dir(fieldCode, period)
  92. p = period_dir / "report" / f"{edition}.docx"
  93. if not p.is_file():
  94. raise HTTPException(status_code=404, detail="报告文件不存在")
  95. return FileResponse(
  96. str(p),
  97. media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  98. filename=f"{fieldCode}_{period}_{edition}.docx",
  99. )