main.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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/tspluse-ruler")
  126. def tspluse_ruler(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  127. try:
  128. return data_service.tspluse_ruler()
  129. except Exception as error:
  130. raise HTTPException(status_code=503, detail=str(error)) from error
  131. @app.post("/api/wave-window")
  132. def wave_window(payload: WaveWindowInput, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  133. try:
  134. return data_service.wave_window(
  135. payload.devicePart,
  136. payload.devicePoints,
  137. [point.model_dump() if hasattr(point, "model_dump") else point.dict() for point in payload.points],
  138. payload.maxPoints,
  139. payload.noSampling,
  140. payload.firstCycleOnly,
  141. payload.sitePoints,
  142. )
  143. except ValueError as error:
  144. raise HTTPException(status_code=400, detail=str(error)) from error
  145. except Exception as error:
  146. raise HTTPException(status_code=503, detail=str(error)) from error
  147. @app.get("/api/wave-files/{wave_file_id}/periods/{period_number}")
  148. def period_detail(
  149. wave_file_id: int,
  150. period_number: int,
  151. _auth: str = Depends(require_auth),
  152. ) -> dict[str, Any]:
  153. try:
  154. return data_service.period_detail(wave_file_id, period_number)
  155. except ValueError as error:
  156. raise HTTPException(status_code=400, detail=str(error)) from error
  157. except Exception as error:
  158. raise HTTPException(status_code=503, detail=str(error)) from error
  159. @app.get("/api/annotation-config")
  160. def annotation_config(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  161. return data_service.annotation_config()
  162. @app.get("/api/annotations")
  163. def list_annotations(
  164. wave_file_ids: list[int] = Query(default=[]),
  165. _auth: str = Depends(require_auth),
  166. ) -> dict[str, Any]:
  167. try:
  168. return data_service.list_annotations(wave_file_ids)
  169. except ValueError as error:
  170. raise HTTPException(status_code=400, detail=str(error)) from error
  171. except Exception as error:
  172. raise HTTPException(status_code=503, detail=str(error)) from error
  173. @app.post("/api/annotations/query")
  174. def query_annotations(
  175. payload: AnnotationQueryInput,
  176. _auth: str = Depends(require_auth),
  177. ) -> dict[str, Any]:
  178. try:
  179. return data_service.list_annotations(payload.wave_file_ids)
  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.post("/api/annotations")
  185. def create_annotation(payload: AnnotationInput, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  186. try:
  187. return data_service.create_annotation(payload.model_dump())
  188. except ValueError as error:
  189. raise HTTPException(status_code=400, detail=str(error)) from error
  190. except Exception as error:
  191. raise HTTPException(status_code=503, detail=str(error)) from error
  192. @app.delete("/api/annotations/{annotation_id}")
  193. def delete_annotation(annotation_id: int, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  194. try:
  195. return data_service.delete_annotation(annotation_id)
  196. except ValueError as error:
  197. raise HTTPException(status_code=404, detail=str(error)) from error
  198. except Exception as error:
  199. raise HTTPException(status_code=503, detail=str(error)) from error
  200. @app.get("/api/pretrain-records")
  201. def pretrain_records_status(
  202. ids: list[int] = Query(default=[]),
  203. _auth: str = Depends(require_auth),
  204. ) -> dict[str, Any]:
  205. try:
  206. return {"recorded": pretrain_service.recorded_ids(ids)}
  207. except Exception as error:
  208. raise HTTPException(status_code=503, detail=str(error)) from error
  209. @app.post("/api/pretrain-records")
  210. def create_pretrain_record(
  211. payload: PretrainRecordInput,
  212. _auth: str = Depends(require_auth),
  213. ) -> dict[str, Any]:
  214. try:
  215. recorded, already = pretrain_service.record(payload.model_dump())
  216. except ValueError as error:
  217. raise HTTPException(status_code=400, detail=str(error)) from error
  218. except Exception as error:
  219. raise HTTPException(status_code=503, detail=str(error)) from error
  220. return {"recorded": recorded, "already": already}
  221. @app.delete("/api/pretrain-records/{file_id}")
  222. def delete_pretrain_record(file_id: int, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  223. try:
  224. deleted = pretrain_service.remove(file_id)
  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. if not deleted:
  230. raise HTTPException(status_code=404, detail="CSV 中不存在该记录")
  231. return {"deleted": deleted}