main.py 9.9 KB

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