main.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. class WaveWindowInput(BaseModel):
  15. pointName: str
  16. measurementTypes: list[str]
  17. points: list[TimePointInput]
  18. maxPoints: int = Field(default=200000, ge=256, le=200000)
  19. noSampling: bool = False
  20. firstCycleOnly: bool = False
  21. class AnnotationInput(BaseModel):
  22. wave_file_id: int = Field(gt=0)
  23. label: str = Field(min_length=1, max_length=8)
  24. period_start: int = Field(gt=0)
  25. period_end: int = Field(gt=0)
  26. sample_index_start: int = Field(ge=0)
  27. sample_index_end: int = Field(ge=0)
  28. class AnnotationQueryInput(BaseModel):
  29. wave_file_ids: list[int] = Field(default=[])
  30. class PretrainRecordInput(BaseModel):
  31. id: int = Field(gt=0)
  32. point_name: str = Field(min_length=1)
  33. measurement_type: str = Field(min_length=1)
  34. rpm: float | None = None
  35. sample_time: str = Field(min_length=1)
  36. file_name: str = Field(default="")
  37. class LoginInput(BaseModel):
  38. username: str = Field(min_length=1)
  39. password: str = Field(min_length=1)
  40. app = FastAPI(
  41. title="压缩机故障预测波形服务",
  42. version="0.1.0",
  43. )
  44. app.add_middleware(
  45. CORSMiddleware,
  46. allow_origins=[settings.cors_origin, "http://127.0.0.1:5173"],
  47. allow_credentials=True,
  48. allow_methods=["*"],
  49. allow_headers=["*"],
  50. )
  51. def require_auth(authorization: str | None = Header(default=None)) -> str:
  52. token = (authorization or "").removeprefix("Bearer ").strip()
  53. if not validate_token(token):
  54. raise HTTPException(status_code=401, detail="未登录或登录已过期")
  55. return token
  56. @app.on_event("startup")
  57. def startup() -> None:
  58. try:
  59. ensure_annotation_table()
  60. except Exception:
  61. # 数据库不可达时跳过建表,演示模式仍可正常启动。
  62. pass
  63. @app.post("/api/login")
  64. def login(payload: LoginInput) -> dict[str, Any]:
  65. if not verify_credentials(payload.username, payload.password):
  66. raise HTTPException(status_code=401, detail="用户名或密码错误")
  67. return {"token": create_token(), "username": payload.username}
  68. @app.post("/api/logout")
  69. def logout(authorization: str | None = Header(default=None)) -> dict[str, Any]:
  70. token = (authorization or "").removeprefix("Bearer ").strip()
  71. revoke_token(token)
  72. return {"ok": True}
  73. @app.get("/api/health")
  74. def health(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  75. return data_service.health()
  76. @app.get("/api/query-options")
  77. def query_options(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  78. try:
  79. result = data_service.query_options()
  80. result["pretrainCounts"] = pretrain_service.recorded_counts()
  81. result["abnormalCounts"] = data_service.abnormal_counts()
  82. return result
  83. except Exception as error:
  84. raise HTTPException(status_code=503, detail=str(error)) from error
  85. @app.get("/api/time-points")
  86. def time_points(
  87. point_name: str = Query(min_length=1),
  88. measurement_types: list[str] = Query(default=[]),
  89. min_time: str | None = None,
  90. max_time: str | None = None,
  91. include_stopped: bool = False,
  92. min_status: int | None = Query(default=None, ge=0),
  93. status_filter: list[str] = Query(default=[]),
  94. _auth: str = Depends(require_auth),
  95. ) -> dict[str, Any]:
  96. try:
  97. return data_service.time_points(
  98. point_name,
  99. measurement_types,
  100. min_time,
  101. max_time,
  102. include_stopped,
  103. min_status,
  104. status_filter,
  105. )
  106. except ValueError as error:
  107. raise HTTPException(status_code=400, detail=str(error)) from error
  108. except Exception as error:
  109. raise HTTPException(status_code=503, detail=str(error)) from error
  110. @app.get("/api/tspluse-ruler")
  111. def tspluse_ruler(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  112. try:
  113. return data_service.tspluse_ruler()
  114. except Exception as error:
  115. raise HTTPException(status_code=503, detail=str(error)) from error
  116. @app.post("/api/wave-window")
  117. def wave_window(payload: WaveWindowInput, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  118. try:
  119. return data_service.wave_window(
  120. payload.pointName,
  121. payload.measurementTypes,
  122. [point.model_dump() if hasattr(point, "model_dump") else point.dict() for point in payload.points],
  123. payload.maxPoints,
  124. payload.noSampling,
  125. payload.firstCycleOnly,
  126. )
  127. except ValueError as error:
  128. raise HTTPException(status_code=400, detail=str(error)) from error
  129. except Exception as error:
  130. raise HTTPException(status_code=503, detail=str(error)) from error
  131. @app.get("/api/wave-files/{wave_file_id}/periods/{period_number}")
  132. def period_detail(
  133. wave_file_id: int,
  134. period_number: int,
  135. _auth: str = Depends(require_auth),
  136. ) -> dict[str, Any]:
  137. try:
  138. return data_service.period_detail(wave_file_id, period_number)
  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/annotation-config")
  144. def annotation_config(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  145. return data_service.annotation_config()
  146. @app.get("/api/annotations")
  147. def list_annotations(
  148. wave_file_ids: list[int] = Query(default=[]),
  149. _auth: str = Depends(require_auth),
  150. ) -> dict[str, Any]:
  151. try:
  152. return data_service.list_annotations(wave_file_ids)
  153. except ValueError as error:
  154. raise HTTPException(status_code=400, detail=str(error)) from error
  155. except Exception as error:
  156. raise HTTPException(status_code=503, detail=str(error)) from error
  157. @app.post("/api/annotations/query")
  158. def query_annotations(
  159. payload: AnnotationQueryInput,
  160. _auth: str = Depends(require_auth),
  161. ) -> dict[str, Any]:
  162. try:
  163. return data_service.list_annotations(payload.wave_file_ids)
  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/annotations")
  169. def create_annotation(payload: AnnotationInput, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  170. try:
  171. return data_service.create_annotation(payload.model_dump())
  172. except ValueError as error:
  173. raise HTTPException(status_code=400, detail=str(error)) from error
  174. except Exception as error:
  175. raise HTTPException(status_code=503, detail=str(error)) from error
  176. @app.delete("/api/annotations/{annotation_id}")
  177. def delete_annotation(annotation_id: int, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  178. try:
  179. return data_service.delete_annotation(annotation_id)
  180. except ValueError as error:
  181. raise HTTPException(status_code=404, 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/pretrain-records")
  185. def pretrain_records_status(
  186. ids: list[int] = Query(default=[]),
  187. _auth: str = Depends(require_auth),
  188. ) -> dict[str, Any]:
  189. try:
  190. return {"recorded": pretrain_service.recorded_ids(ids)}
  191. except Exception as error:
  192. raise HTTPException(status_code=503, detail=str(error)) from error
  193. @app.post("/api/pretrain-records")
  194. def create_pretrain_record(
  195. payload: PretrainRecordInput,
  196. _auth: str = Depends(require_auth),
  197. ) -> dict[str, Any]:
  198. try:
  199. recorded, already = pretrain_service.record(payload.model_dump())
  200. except ValueError as error:
  201. raise HTTPException(status_code=400, detail=str(error)) from error
  202. except Exception as error:
  203. raise HTTPException(status_code=503, detail=str(error)) from error
  204. return {"recorded": recorded, "already": already}
  205. @app.delete("/api/pretrain-records/{file_id}")
  206. def delete_pretrain_record(file_id: int, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  207. try:
  208. deleted = pretrain_service.remove(file_id)
  209. except ValueError as error:
  210. raise HTTPException(status_code=400, detail=str(error)) from error
  211. except Exception as error:
  212. raise HTTPException(status_code=503, detail=str(error)) from error
  213. if not deleted:
  214. raise HTTPException(status_code=404, detail="CSV 中不存在该记录")
  215. return {"deleted": deleted}