ts_ad.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from fastapi import FastAPI, HTTPException
  15. from pydantic import BaseModel
  16. from .....utils import logging
  17. from ...single_model_pipeline import TSAd
  18. from .. import utils as serving_utils
  19. from ..app import AppConfig, create_app
  20. from ..models import Response, ResultResponse
  21. class InferRequest(BaseModel):
  22. csv: str
  23. class InferResult(BaseModel):
  24. csv: str
  25. def create_pipeline_app(pipeline: TSAd, app_config: AppConfig) -> FastAPI:
  26. app, ctx = create_app(
  27. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  28. )
  29. @app.post(
  30. "/time-series-anomaly-detection",
  31. operation_id="infer",
  32. responses={422: {"model": Response}},
  33. )
  34. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  35. pipeline = ctx.pipeline
  36. aiohttp_session = ctx.aiohttp_session
  37. try:
  38. file_bytes = await serving_utils.get_raw_bytes(request.csv, aiohttp_session)
  39. df = serving_utils.csv_bytes_to_data_frame(file_bytes)
  40. result = (await pipeline.infer(df))[0]
  41. output_csv = serving_utils.data_frame_to_base64(result["anomaly"])
  42. return ResultResponse(
  43. logId=serving_utils.generate_log_id(),
  44. errorCode=0,
  45. errorMsg="Success",
  46. result=InferResult(csv=output_csv),
  47. )
  48. except Exception as e:
  49. logging.exception(e)
  50. raise HTTPException(status_code=500, detail="Internal server error")
  51. return app