cms.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import json
  2. import traceback
  3. from fastapi import APIRouter, HTTPException
  4. from app.logger import logger
  5. from app.models.CmsAnalysisInput import CmsAnalysisInput
  6. from app.services.CMSAnalyst import CMSAnalyst
  7. router = APIRouter()
  8. @router.post("/analysis/{analysisType}")
  9. async def analyze(analysisType: str, input_data: CmsAnalysisInput):
  10. analysis_map = {
  11. # 包络谱分析
  12. "envelope": "envelope_spectrum",
  13. # 频域分析
  14. "frequency": "frequency_domain",
  15. # 时域分析
  16. "time": "time_domain",
  17. # 趋势分析
  18. "trend": "trend_analysis"
  19. }
  20. if analysisType not in analysis_map:
  21. raise HTTPException(status_code=400, detail="非可用的分析类型")
  22. try:
  23. cms = CMSAnalyst(
  24. input_data.fmin,
  25. input_data.fmax,
  26. input_data.windCode,
  27. input_data.ids,
  28. light=(analysisType in ("time", "trend")),
  29. )
  30. if analysisType == "time" and input_data.maxPoints:
  31. cms.max_points = max(1000, min(int(input_data.maxPoints), 20000))
  32. func = getattr(cms, analysis_map[analysisType])
  33. # 用于判断一个对象是否可以被调用,是的话返回true
  34. if callable(func):
  35. func_res = func()
  36. if isinstance(func_res, str):
  37. # 字符串转化为字典形式
  38. func_res = json.loads(func_res)
  39. if isinstance(func_res, dict):
  40. func_res['type'] = analysisType
  41. elif isinstance(func_res, list):
  42. func_res = {'type': analysisType, 'data': func_res}
  43. else:
  44. # 处理其他情况,例如其他数据类型
  45. func_res = {'type': analysisType, 'data': str(func_res)}
  46. # 对象转化为字符串形式
  47. return json.dumps(func_res, ensure_ascii=False)
  48. # return JSONResponse(content=func_res)#返回json格式
  49. except Exception as e:
  50. logger.error(f"analyze is bad {traceback.format_exc()}")
  51. return {"message": "error", "detail": str(e)}