main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. from typing import Any
  2. from fastapi import Depends, FastAPI, Header, HTTPException, Query
  3. from fastapi.middleware.cors import CORSMiddleware
  4. from pydantic import BaseModel, Field
  5. from .auth import create_token, revoke_token, validate_token, verify_credentials
  6. from .config import settings
  7. from .db import ensure_annotation_table
  8. from .services.data_service import data_service
  9. from .services.pretrain_service import pretrain_service
  10. class TimePointInput(BaseModel):
  11. index: int = Field(ge=0)
  12. sampleTime: str
  13. files: dict[str, Any]
  14. siteValues: dict[str, float | None] = Field(default={})
  15. class WaveWindowInput(BaseModel):
  16. devicePart: str = Field(min_length=1)
  17. devicePoints: list[str]
  18. points: list[TimePointInput]
  19. maxPoints: int = Field(default=200000, ge=256, le=200000)
  20. noSampling: bool = False
  21. firstCycleOnly: bool = False
  22. sitePoints: list[str] = Field(default=[])
  23. class AnnotationInput(BaseModel):
  24. wave_file_id: int = Field(gt=0)
  25. label: str = Field(min_length=1, max_length=8)
  26. period_start: int = Field(gt=0)
  27. period_end: int = Field(gt=0)
  28. sample_index_start: int = Field(ge=0)
  29. sample_index_end: int = Field(ge=0)
  30. class AnnotationQueryInput(BaseModel):
  31. wave_file_ids: list[int] = Field(default=[])
  32. class AlarmScanInput(BaseModel):
  33. forecast_time: str = Field(min_length=1)
  34. device_code: str = Field(min_length=1)
  35. alarm_type: str = Field(min_length=1)
  36. hours: float = Field(gt=0)
  37. class PretrainRecordInput(BaseModel):
  38. id: int = Field(gt=0)
  39. point_name: str = Field(min_length=1)
  40. measurement_type: str = Field(min_length=1)
  41. rpm: float | None = None
  42. sample_time: str = Field(min_length=1)
  43. file_name: str = Field(default="")
  44. class LoginInput(BaseModel):
  45. username: str = Field(min_length=1)
  46. password: str = Field(min_length=1)
  47. app = FastAPI(
  48. title="压缩机故障预测波形服务",
  49. version="0.1.0",
  50. )
  51. app.add_middleware(
  52. CORSMiddleware,
  53. allow_origins=[settings.cors_origin, "http://127.0.0.1:5173"],
  54. allow_credentials=True,
  55. allow_methods=["*"],
  56. allow_headers=["*"],
  57. )
  58. def require_auth(authorization: str | None = Header(default=None)) -> str:
  59. token = (authorization or "").removeprefix("Bearer ").strip()
  60. if not validate_token(token):
  61. raise HTTPException(status_code=401, detail="未登录或登录已过期")
  62. return token
  63. @app.on_event("startup")
  64. def startup() -> None:
  65. try:
  66. ensure_annotation_table()
  67. except Exception:
  68. # 数据库不可达时跳过建表,演示模式仍可正常启动。
  69. pass
  70. @app.post("/api/login")
  71. def login(payload: LoginInput) -> dict[str, Any]:
  72. if not verify_credentials(payload.username, payload.password):
  73. raise HTTPException(status_code=401, detail="用户名或密码错误")
  74. return {"token": create_token(), "username": payload.username}
  75. @app.post("/api/logout")
  76. def logout(authorization: str | None = Header(default=None)) -> dict[str, Any]:
  77. token = (authorization or "").removeprefix("Bearer ").strip()
  78. revoke_token(token)
  79. return {"ok": True}
  80. @app.get("/api/health")
  81. def health(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  82. return data_service.health()
  83. @app.get("/api/query-options")
  84. def query_options(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  85. try:
  86. result = data_service.query_options()
  87. # Counts are keyed by the full point_name so the UI can scope them to
  88. # the currently selected device_part.
  89. result["pretrainCounts"] = pretrain_service.recorded_counts()
  90. result["abnormalCounts"] = data_service.abnormal_counts()
  91. return result
  92. except Exception as error:
  93. raise HTTPException(status_code=503, detail=str(error)) from error
  94. @app.get("/api/time-points")
  95. def time_points(
  96. device_part: str = Query(min_length=1),
  97. device_points: list[str] = Query(default=[]),
  98. min_time: str | None = None,
  99. max_time: str | None = None,
  100. include_stopped: bool = False,
  101. min_status: int | None = Query(default=None, ge=0),
  102. status_filter: list[str] = Query(default=[]),
  103. site_points: list[str] = Query(default=[]),
  104. _auth: str = Depends(require_auth),
  105. ) -> dict[str, Any]:
  106. try:
  107. return data_service.time_points(
  108. device_part,
  109. device_points,
  110. min_time,
  111. max_time,
  112. include_stopped,
  113. min_status,
  114. status_filter,
  115. site_points,
  116. )
  117. except ValueError as error:
  118. raise HTTPException(status_code=400, detail=str(error)) from error
  119. except Exception as error:
  120. raise HTTPException(status_code=503, detail=str(error)) from error
  121. @app.get("/api/site-points")
  122. def site_points(
  123. device_part: str = Query(min_length=1),
  124. _auth: str = Depends(require_auth),
  125. ) -> dict[str, Any]:
  126. try:
  127. return data_service.site_points(device_part)
  128. except Exception as error:
  129. raise HTTPException(status_code=503, detail=str(error)) from error
  130. @app.get("/api/faults")
  131. def faults(
  132. device_part: str = Query(min_length=1),
  133. min_time: str | None = None,
  134. max_time: str | None = None,
  135. _auth: str = Depends(require_auth),
  136. ) -> dict[str, Any]:
  137. try:
  138. return data_service.faults(device_part, min_time, max_time)
  139. except ValueError as error:
  140. raise HTTPException(status_code=400, detail=str(error)) from error
  141. except Exception as error:
  142. raise HTTPException(status_code=503, detail=str(error)) from error
  143. @app.get("/api/tspluse-ruler")
  144. def tspluse_ruler(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  145. try:
  146. return data_service.tspluse_ruler()
  147. except Exception as error:
  148. raise HTTPException(status_code=503, detail=str(error)) from error
  149. @app.get("/api/alarms")
  150. def list_alarms(
  151. current_time: str | None = None,
  152. _auth: str = Depends(require_auth),
  153. ) -> dict[str, Any]:
  154. try:
  155. return data_service.list_alarms(current_time)
  156. except ValueError as error:
  157. raise HTTPException(status_code=400, detail=str(error)) from error
  158. except Exception as error:
  159. raise HTTPException(status_code=503, detail=str(error)) from error
  160. @app.post("/api/alarm-scan")
  161. def alarm_scan(payload: AlarmScanInput, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  162. try:
  163. return data_service.scan_alarm(payload.model_dump())
  164. except ValueError as error:
  165. raise HTTPException(status_code=400, detail=str(error)) from error
  166. except Exception as error:
  167. raise HTTPException(status_code=503, detail=str(error)) from error
  168. @app.post("/api/wave-window")
  169. def wave_window(payload: WaveWindowInput, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  170. try:
  171. return data_service.wave_window(
  172. payload.devicePart,
  173. payload.devicePoints,
  174. [point.model_dump() if hasattr(point, "model_dump") else point.dict() for point in payload.points],
  175. payload.maxPoints,
  176. payload.noSampling,
  177. payload.firstCycleOnly,
  178. payload.sitePoints,
  179. )
  180. except ValueError as error:
  181. raise HTTPException(status_code=400, detail=str(error)) from error
  182. except Exception as error:
  183. raise HTTPException(status_code=503, detail=str(error)) from error
  184. @app.get("/api/wave-files/{wave_file_id}/periods/{period_number}")
  185. def period_detail(
  186. wave_file_id: int,
  187. period_number: int,
  188. _auth: str = Depends(require_auth),
  189. ) -> dict[str, Any]:
  190. try:
  191. return data_service.period_detail(wave_file_id, period_number)
  192. except ValueError as error:
  193. raise HTTPException(status_code=400, detail=str(error)) from error
  194. except Exception as error:
  195. raise HTTPException(status_code=503, detail=str(error)) from error
  196. @app.get("/api/annotation-config")
  197. def annotation_config(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  198. return data_service.annotation_config()
  199. @app.get("/api/annotations")
  200. def list_annotations(
  201. wave_file_ids: list[int] = Query(default=[]),
  202. _auth: str = Depends(require_auth),
  203. ) -> dict[str, Any]:
  204. try:
  205. return data_service.list_annotations(wave_file_ids)
  206. except ValueError as error:
  207. raise HTTPException(status_code=400, detail=str(error)) from error
  208. except Exception as error:
  209. raise HTTPException(status_code=503, detail=str(error)) from error
  210. @app.post("/api/annotations/query")
  211. def query_annotations(
  212. payload: AnnotationQueryInput,
  213. _auth: str = Depends(require_auth),
  214. ) -> dict[str, Any]:
  215. try:
  216. return data_service.list_annotations(payload.wave_file_ids)
  217. except ValueError as error:
  218. raise HTTPException(status_code=400, detail=str(error)) from error
  219. except Exception as error:
  220. raise HTTPException(status_code=503, detail=str(error)) from error
  221. @app.post("/api/annotations")
  222. def create_annotation(payload: AnnotationInput, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  223. try:
  224. return data_service.create_annotation(payload.model_dump())
  225. except ValueError as error:
  226. raise HTTPException(status_code=400, detail=str(error)) from error
  227. except Exception as error:
  228. raise HTTPException(status_code=503, detail=str(error)) from error
  229. @app.delete("/api/annotations/{annotation_id}")
  230. def delete_annotation(annotation_id: int, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  231. try:
  232. return data_service.delete_annotation(annotation_id)
  233. except ValueError as error:
  234. raise HTTPException(status_code=404, detail=str(error)) from error
  235. except Exception as error:
  236. raise HTTPException(status_code=503, detail=str(error)) from error
  237. @app.get("/api/pretrain-records")
  238. def pretrain_records_status(
  239. ids: list[int] = Query(default=[]),
  240. _auth: str = Depends(require_auth),
  241. ) -> dict[str, Any]:
  242. try:
  243. return {"recorded": pretrain_service.recorded_ids(ids)}
  244. except Exception as error:
  245. raise HTTPException(status_code=503, detail=str(error)) from error
  246. @app.post("/api/pretrain-records")
  247. def create_pretrain_record(
  248. payload: PretrainRecordInput,
  249. _auth: str = Depends(require_auth),
  250. ) -> dict[str, Any]:
  251. try:
  252. recorded, already = pretrain_service.record(payload.model_dump())
  253. except ValueError as error:
  254. raise HTTPException(status_code=400, detail=str(error)) from error
  255. except Exception as error:
  256. raise HTTPException(status_code=503, detail=str(error)) from error
  257. return {"recorded": recorded, "already": already}
  258. @app.delete("/api/pretrain-records/{file_id}")
  259. def delete_pretrain_record(file_id: int, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  260. try:
  261. deleted = pretrain_service.remove(file_id)
  262. except ValueError as error:
  263. raise HTTPException(status_code=400, detail=str(error)) from error
  264. except Exception as error:
  265. raise HTTPException(status_code=503, detail=str(error)) from error
  266. if not deleted:
  267. raise HTTPException(status_code=404, detail="CSV 中不存在该记录")
  268. return {"deleted": deleted}