main.py 8.9 KB

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