ts_cls.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 TSCls
  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. label: str
  25. score: float
  26. def create_pipeline_app(pipeline: TSCls, app_config: AppConfig) -> FastAPI:
  27. app, ctx = create_app(
  28. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  29. )
  30. @app.post(
  31. "/time-series-classification",
  32. operation_id="infer",
  33. responses={422: {"model": Response}},
  34. )
  35. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  36. pipeline = ctx.pipeline
  37. aiohttp_session = ctx.aiohttp_session
  38. try:
  39. file_bytes = await serving_utils.get_raw_bytes(request.csv, aiohttp_session)
  40. df = serving_utils.csv_bytes_to_data_frame(file_bytes)
  41. result = (await pipeline.infer(df))[0]
  42. label = str(result["classification"].at[0, "classid"])
  43. score = float(result["classification"].at[0, "score"])
  44. return ResultResponse(
  45. logId=serving_utils.generate_log_id(),
  46. errorCode=0,
  47. errorMsg="Success",
  48. result=InferResult(label=label, score=score),
  49. )
  50. except Exception as e:
  51. logging.exception(e)
  52. raise HTTPException(status_code=500, detail="Internal server error")
  53. return app