report.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """报告生成 API。"""
  2. from __future__ import annotations
  3. import uuid
  4. from typing import Any, Dict, List, Optional
  5. from fastapi import APIRouter, BackgroundTasks, HTTPException
  6. from pydantic import BaseModel, Field
  7. from app.report import generator, ollama_client
  8. router = APIRouter(prefix="/report", tags=["report"])
  9. JOBS: Dict[str, Dict[str, Any]] = {}
  10. class ReportRequest(BaseModel):
  11. windCode: str = Field(..., min_length=3, max_length=32)
  12. startMonth: str = Field(..., pattern=r"^\d{4}-\d{2}$")
  13. endMonth: str = Field(..., pattern=r"^\d{4}-\d{2}$")
  14. title: Optional[str] = ""
  15. sections: List[str] = ["overview", "health", "fault", "vibration"]
  16. @router.post("/generate")
  17. async def generate(request: ReportRequest, background_tasks: BackgroundTasks):
  18. generator.ensure_dirs()
  19. job_id = uuid.uuid4().hex[:12]
  20. JOBS[job_id] = {
  21. "job_id": job_id,
  22. "status": "queued",
  23. "progress": 0,
  24. "message": "任务已创建",
  25. "wind_code": request.windCode,
  26. "period": f"{request.startMonth} 至 {request.endMonth}",
  27. "created_at": __import__("datetime").datetime.now().isoformat(timespec="seconds"),
  28. }
  29. background_tasks.add_task(generator.run_job, job_id, request.dict(), JOBS)
  30. return {"job_id": job_id, "status": "queued"}
  31. @router.get("/status/{job_id}")
  32. async def status(job_id: str):
  33. job = JOBS.get(job_id)
  34. if not job:
  35. raise HTTPException(status_code=404, detail="任务不存在或已过期")
  36. return job
  37. @router.get("/list")
  38. async def list_reports(windCode: Optional[str] = None):
  39. return {"reports": generator.list_reports(windCode)}
  40. @router.get("/health")
  41. async def health():
  42. return {"ollama": ollama_client.health_check(), "model": ollama_client.OLLAMA_MODEL}