main.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. return result
  81. except Exception as error:
  82. raise HTTPException(status_code=503, detail=str(error)) from error
  83. @app.get("/api/time-points")
  84. def time_points(
  85. point_name: str = Query(min_length=1),
  86. measurement_types: list[str] = Query(default=[]),
  87. min_time: str | None = None,
  88. max_time: str | None = None,
  89. include_stopped: bool = False,
  90. min_status: int | None = Query(default=None, ge=0),
  91. status_filter: list[str] = Query(default=[]),
  92. _auth: str = Depends(require_auth),
  93. ) -> dict[str, Any]:
  94. try:
  95. return data_service.time_points(
  96. point_name,
  97. measurement_types,
  98. min_time,
  99. max_time,
  100. include_stopped,
  101. min_status,
  102. status_filter,
  103. )
  104. except ValueError as error:
  105. raise HTTPException(status_code=400, detail=str(error)) from error
  106. except Exception as error:
  107. raise HTTPException(status_code=503, detail=str(error)) from error
  108. @app.get("/api/tspluse-ruler")
  109. def tspluse_ruler(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  110. try:
  111. return data_service.tspluse_ruler()
  112. except Exception as error:
  113. raise HTTPException(status_code=503, detail=str(error)) from error
  114. @app.post("/api/wave-window")
  115. def wave_window(payload: WaveWindowInput, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  116. try:
  117. return data_service.wave_window(
  118. payload.pointName,
  119. payload.measurementTypes,
  120. [point.model_dump() if hasattr(point, "model_dump") else point.dict() for point in payload.points],
  121. payload.maxPoints,
  122. payload.noSampling,
  123. )
  124. except ValueError as error:
  125. raise HTTPException(status_code=400, detail=str(error)) from error
  126. except Exception as error:
  127. raise HTTPException(status_code=503, detail=str(error)) from error
  128. @app.get("/api/wave-files/{wave_file_id}/periods/{period_number}")
  129. def period_detail(
  130. wave_file_id: int,
  131. period_number: int,
  132. _auth: str = Depends(require_auth),
  133. ) -> dict[str, Any]:
  134. try:
  135. return data_service.period_detail(wave_file_id, period_number)
  136. except ValueError as error:
  137. raise HTTPException(status_code=400, detail=str(error)) from error
  138. except Exception as error:
  139. raise HTTPException(status_code=503, detail=str(error)) from error
  140. @app.get("/api/annotation-config")
  141. def annotation_config(_auth: str = Depends(require_auth)) -> dict[str, Any]:
  142. return data_service.annotation_config()
  143. @app.get("/api/annotations")
  144. def list_annotations(
  145. wave_file_ids: list[int] = Query(default=[]),
  146. _auth: str = Depends(require_auth),
  147. ) -> dict[str, Any]:
  148. try:
  149. return data_service.list_annotations(wave_file_ids)
  150. except ValueError as error:
  151. raise HTTPException(status_code=400, detail=str(error)) from error
  152. except Exception as error:
  153. raise HTTPException(status_code=503, detail=str(error)) from error
  154. @app.post("/api/annotations/query")
  155. def query_annotations(
  156. payload: AnnotationQueryInput,
  157. _auth: str = Depends(require_auth),
  158. ) -> dict[str, Any]:
  159. try:
  160. return data_service.list_annotations(payload.wave_file_ids)
  161. except ValueError as error:
  162. raise HTTPException(status_code=400, detail=str(error)) from error
  163. except Exception as error:
  164. raise HTTPException(status_code=503, detail=str(error)) from error
  165. @app.post("/api/annotations")
  166. def create_annotation(payload: AnnotationInput, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  167. try:
  168. return data_service.create_annotation(payload.model_dump())
  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.delete("/api/annotations/{annotation_id}")
  174. def delete_annotation(annotation_id: int, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  175. try:
  176. return data_service.delete_annotation(annotation_id)
  177. except ValueError as error:
  178. raise HTTPException(status_code=404, detail=str(error)) from error
  179. except Exception as error:
  180. raise HTTPException(status_code=503, detail=str(error)) from error
  181. @app.get("/api/pretrain-records")
  182. def pretrain_records_status(
  183. ids: list[int] = Query(default=[]),
  184. _auth: str = Depends(require_auth),
  185. ) -> dict[str, Any]:
  186. try:
  187. return {"recorded": pretrain_service.recorded_ids(ids)}
  188. except Exception as error:
  189. raise HTTPException(status_code=503, detail=str(error)) from error
  190. @app.post("/api/pretrain-records")
  191. def create_pretrain_record(
  192. payload: PretrainRecordInput,
  193. _auth: str = Depends(require_auth),
  194. ) -> dict[str, Any]:
  195. try:
  196. recorded, already = pretrain_service.record(payload.model_dump())
  197. except ValueError as error:
  198. raise HTTPException(status_code=400, detail=str(error)) from error
  199. except Exception as error:
  200. raise HTTPException(status_code=503, detail=str(error)) from error
  201. return {"recorded": recorded, "already": already}
  202. @app.delete("/api/pretrain-records/{file_id}")
  203. def delete_pretrain_record(file_id: int, _auth: str = Depends(require_auth)) -> dict[str, Any]:
  204. try:
  205. deleted = pretrain_service.remove(file_id)
  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. if not deleted:
  211. raise HTTPException(status_code=404, detail="CSV 中不存在该记录")
  212. return {"deleted": deleted}