Explorar el Código

feat: add health assessment read API and platform minute export

zhouyang.xie hace 1 semana
padre
commit
00d6cdc289
Se han modificado 3 ficheros con 250 adiciones y 1 borrados
  1. 2 1
      app/main.py
  2. 119 0
      app/routers/health_assessment.py
  3. 129 0
      scripts/health_assessment_export.py

+ 2 - 1
app/main.py

@@ -4,7 +4,7 @@ from fastapi import FastAPI
 from fastapi.middleware.cors import CORSMiddleware
 from fastapi.staticfiles import StaticFiles
 
-from app.routers import autodiag, cockpit_compat, cms, etl_compat, fault_frequency, health, report, temperature, vibration_alarm
+from app.routers import autodiag, cockpit_compat, cms, etl_compat, fault_frequency, health, health_assessment, report, temperature, vibration_alarm
 
 app = FastAPI(title="Analysis_Multi", version="1.0.0")
 
@@ -25,6 +25,7 @@ app.include_router(cockpit_compat.router)
 app.include_router(report.router)
 app.include_router(vibration_alarm.router)
 app.include_router(fault_frequency.router)
+app.include_router(health_assessment.router)
 
 REPORT_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "output", "reports")
 os.makedirs(REPORT_DIR, exist_ok=True)

+ 119 - 0
app/routers/health_assessment.py

@@ -0,0 +1,119 @@
+"""健康评估结果只读接口。
+
+算法服务器/平台导入后的 health.json 与 Word 报告落在 HDKG_OUT_ROOT:
+  <root>/<fieldCode>/<YYYY-MM>/detail/health.json
+  <root>/<fieldCode>/<YYYY-MM>/report/internal.docx
+  <root>/<fieldCode>/<YYYY-MM>/report/external.docx
+  <root>/<fieldCode>/<YYYY-MM>/registration.json
+
+本路由只读文件,不触发批次、不写数据库;批次仍由 hdkg-run 或平台导入任务完成。
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+from fastapi import APIRouter, HTTPException
+from fastapi.responses import FileResponse
+
+router = APIRouter(prefix="/health-assessment", tags=["health-assessment"])
+
+OUT_ROOT = Path(os.getenv("HDKG_OUT_ROOT", "/data/hdkg/out")).resolve()
+FIELD_RE = re.compile(r"^WOF\d{9,}$")
+PERIOD_RE = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
+
+
+def _safe_parts(field_code: str, period: str) -> tuple[str, str]:
+    if not FIELD_RE.match(field_code or ""):
+        raise HTTPException(status_code=400, detail="fieldCode 格式不正确")
+    if not PERIOD_RE.match(period or ""):
+        raise HTTPException(status_code=400, detail="period 须为 YYYY-MM")
+    return field_code, period
+
+
+def _period_dir(field_code: str, period: str) -> Path:
+    field_code, period = _safe_parts(field_code, period)
+    p = (OUT_ROOT / field_code / period).resolve()
+    if OUT_ROOT not in p.parents and p != OUT_ROOT:
+        raise HTTPException(status_code=400, detail="路径不合法")
+    return p
+
+
+def _read_json(path: Path) -> Optional[Dict[str, Any]]:
+    try:
+        with open(path, "r", encoding="utf-8") as f:
+            return json.load(f)
+    except (OSError, ValueError):
+        return None
+
+
+@router.get("/periods")
+def periods(fieldCode: str) -> Dict[str, Any]:
+    """列出某场已发布期次;没有产物时返回空数组,不报 500。"""
+    if not FIELD_RE.match(fieldCode or ""):
+        raise HTTPException(status_code=400, detail="fieldCode 格式不正确")
+    field_dir = (OUT_ROOT / fieldCode).resolve()
+    if not field_dir.is_dir():
+        return {"code": 200, "data": []}
+    out: List[Dict[str, Any]] = []
+    for period_dir in sorted(field_dir.iterdir(), reverse=True):
+        if not period_dir.is_dir() or not PERIOD_RE.match(period_dir.name):
+            continue
+        reg = _read_json(period_dir / "registration.json") or {}
+        detail = period_dir / "detail/health.json"
+        if not detail.is_file() and not reg:
+            continue
+        out.append(
+            {
+                "fieldCode": fieldCode,
+                "period": period_dir.name,
+                "status": reg.get("status") or ("ok" if detail.is_file() else "unknown"),
+                "detailAvailable": detail.is_file(),
+                "internalReportAvailable": (period_dir / "report/internal.docx").is_file(),
+                "externalReportAvailable": (period_dir / "report/external.docx").is_file(),
+                "tables": reg.get("tables"),
+                "error": reg.get("error"),
+            }
+        )
+    return {"code": 200, "data": out}
+
+
+@router.get("/detail")
+def detail(fieldCode: str, period: str) -> Dict[str, Any]:
+    """读取前端版 health.json(不含 health_full 内部版)。"""
+    period_dir = _period_dir(fieldCode, period)
+    p = period_dir / "detail/health.json"
+    if not p.is_file():
+        raise HTTPException(status_code=404, detail="该场该期暂无 health.json")
+    doc = _read_json(p)
+    if not isinstance(doc, dict):
+        raise HTTPException(status_code=500, detail="health.json 不是合法 JSON 对象")
+    return {"code": 200, "data": doc}
+
+
+@router.get("/registration")
+def registration(fieldCode: str, period: str) -> Dict[str, Any]:
+    period_dir = _period_dir(fieldCode, period)
+    doc = _read_json(period_dir / "registration.json")
+    if not isinstance(doc, dict):
+        raise HTTPException(status_code=404, detail="暂无 registration.json")
+    return {"code": 200, "data": doc}
+
+
+@router.get("/report")
+def report(fieldCode: str, period: str, edition: str = "internal"):
+    """下载内部版/对外版 Word 报告。"""
+    if edition not in ("internal", "external"):
+        raise HTTPException(status_code=400, detail="edition 只支持 internal/external")
+    period_dir = _period_dir(fieldCode, period)
+    p = period_dir / "report" / f"{edition}.docx"
+    if not p.is_file():
+        raise HTTPException(status_code=404, detail="报告文件不存在")
+    return FileResponse(
+        str(p),
+        media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+        filename=f"{fieldCode}_{period}_{edition}.docx",
+    )

+ 129 - 0
scripts/health_assessment_export.py

@@ -0,0 +1,129 @@
+#!/usr/bin/env python
+"""从平台业务库导出 hdkg 分钟级输入(第一阶段数据适配)。
+
+只解决“分钟级”输入;原始秒级/五秒原料不在这里伪造:
+  WOF091200030(张崾先) -> T5 标准 CSV 目录(std minute)
+  WOF046400029(七台河) -> ~/.cache/wind-analytics/hdkg/qitaihe/minute.parquet
+
+用法(算法服务器,使用 hdkg 自带 Python 或装有 pandas/pyarrow 的环境):
+  python health_assessment_export.py --site WOF091200030 --period 2024-08 --out-root /data/hdkg/intake
+  python health_assessment_export.py --site WOF046400029 --period 2024-08 --out-root /data/hdkg/intake
+
+数据库连接从环境变量读取:
+  PLATFORM_DB_HOST / PLATFORM_DB_PORT / PLATFORM_DB_USER / PLATFORM_DB_PASSWORD / PLATFORM_DB_NAME
+默认值与平台当前 energy_data_prod 一致。
+"""
+from __future__ import annotations
+
+import argparse
+import os
+from datetime import date
+from pathlib import Path
+from typing import Iterable
+
+import pandas as pd
+import pymysql
+
+SITES = {
+    "WOF091200030": {
+        "table": "WOF091200030_minute",
+        "kind": "zyx",
+        "t5": "张崾先_华电二期/标准化后数据_WOF091200030_张崾先二期_华电",
+        "minute_dir": "WOF091200030_minute",
+    },
+    "WOF046400029": {
+        "table": "WOF046400029_minute",
+        "kind": "qth",
+        "cache": "qitaihe/minute.parquet",
+    },
+}
+
+
+def db():
+    return pymysql.connect(
+        host=os.getenv("PLATFORM_DB_HOST", "106.120.102.238"),
+        port=int(os.getenv("PLATFORM_DB_PORT", "10336")),
+        user=os.getenv("PLATFORM_DB_USER", "root"),
+        password=os.getenv("PLATFORM_DB_PASSWORD", "admin123456"),
+        database=os.getenv("PLATFORM_DB_NAME", "energy_data_prod"),
+        charset="utf8mb4",
+        cursorclass=pymysql.cursors.DictCursor,
+        connect_timeout=20,
+    )
+
+
+def month_bounds(period: str) -> tuple[date, date]:
+    y, m = map(int, period.split("-"))
+    start = date(y, m, 1)
+    end = date(y + (m == 12), (m % 12) + 1, 1)
+    return start, end
+
+
+def read_minute(table: str, start: date, end: date) -> pd.DataFrame:
+    con = db()
+    try:
+        with con.cursor() as cur:
+            cur.execute(
+                f"SELECT * FROM `{table}` WHERE time_stamp >= %s AND time_stamp < %s ORDER BY wind_turbine_number, time_stamp",
+                (f"{start} 00:00:00", f"{end} 00:00:00"),
+            )
+            rows = cur.fetchall()
+    finally:
+        con.close()
+    if not rows:
+        return pd.DataFrame()
+    df = pd.DataFrame(rows)
+    df["time_stamp"] = pd.to_datetime(df["time_stamp"], errors="coerce")
+    df = df[df["time_stamp"].notna()].copy()
+    return df
+
+
+def export_zyx(df: pd.DataFrame, out_root: Path, period: str) -> Path:
+    root = out_root / SITES["WOF091200030"]["t5"]
+    target = root / SITES["WOF091200030"]["minute_dir"]
+    target.mkdir(parents=True, exist_ok=True)
+    # StdCsvExportSource 按 YYYY/MM/DD/<台号>/<台号>_YYYYMMDD.csv 找文件
+    for ts, part in df.groupby(df["time_stamp"].dt.date):
+        day = pd.Timestamp(ts)
+        day_dir = target / f"{day.year:04d}" / f"{day.month:02d}" / f"{day.day:02d}"
+        for turbine, tpart in part.groupby("wind_turbine_number"):
+            tdir = day_dir / str(turbine)
+            tdir.mkdir(parents=True, exist_ok=True)
+            f = tdir / f"{turbine}_{day.strftime('%Y%m%d')}.csv"
+            tpart.to_csv(f, index=False, encoding="utf-8")
+    return target
+
+
+def export_qth(df: pd.DataFrame, cache_root: Path) -> Path:
+    target = cache_root / SITES["WOF046400029"]["cache"]
+    target.parent.mkdir(parents=True, exist_ok=True)
+    # 写全列,保留平台标准字段;ParquetStdSource 按用途取列
+    df.to_parquet(target, index=False)
+    return target
+
+
+def main():
+    ap = argparse.ArgumentParser()
+    ap.add_argument("--site", required=True, choices=sorted(SITES))
+    ap.add_argument("--period", required=True, help="YYYY-MM")
+    ap.add_argument("--out-root", default="/data/hdkg/intake", help="ZYX 的 intake 根")
+    ap.add_argument("--cache-root", default=str(Path.home() / ".cache/wind-analytics/hdkg"))
+    ap.add_argument("--limit", type=int, default=0, help="调试用:只取前 N 行")
+    args = ap.parse_args()
+
+    start, end = month_bounds(args.period)
+    df = read_minute(SITES[args.site]["table"], start, end)
+    if args.limit:
+        df = df.head(args.limit)
+    if df.empty:
+        raise SystemExit(f"没有读到 {args.site} {args.period} 的分钟数据")
+
+    if SITES[args.site]["kind"] == "zyx":
+        target = export_zyx(df, Path(args.out_root), args.period)
+    else:
+        target = export_qth(df, Path(args.cache_root))
+    print(f"exported {len(df)} rows -> {target}")
+
+
+if __name__ == "__main__":
+    main()