main.py 8.7 KB

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