video_classification.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. import os
  15. from typing import Any, Dict, List
  16. from fastapi import FastAPI, HTTPException
  17. from ...infra import utils as serving_utils
  18. from ...infra.config import AppConfig
  19. from ...infra.models import ResultResponse
  20. from ...schemas.video_classification import INFER_ENDPOINT, InferRequest, InferResult
  21. from .._app import create_app, primary_operation
  22. def create_pipeline_app(pipeline: Any, app_config: AppConfig) -> FastAPI:
  23. app, ctx = create_app(
  24. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  25. )
  26. @primary_operation(
  27. app,
  28. INFER_ENDPOINT,
  29. "infer",
  30. )
  31. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  32. pipeline = ctx.pipeline
  33. aiohttp_session = ctx.aiohttp_session
  34. file_bytes = await serving_utils.get_raw_bytes_async(
  35. request.video, aiohttp_session
  36. )
  37. ext = serving_utils.infer_file_ext(request.video)
  38. if ext is None:
  39. raise HTTPException(
  40. status_code=422, detail="File extension cannot be inferred"
  41. )
  42. video_path = await serving_utils.call_async(
  43. serving_utils.write_to_temp_file,
  44. file_bytes,
  45. suffix=ext,
  46. )
  47. try:
  48. result = (await pipeline.infer(video_path, topk=request.topk))[0]
  49. finally:
  50. await serving_utils.call_async(os.unlink, video_path)
  51. if "label_names" in result:
  52. cat_names = result["label_names"]
  53. else:
  54. cat_names = [str(id_) for id_ in result["class_ids"]]
  55. categories: List[Dict[str, Any]] = []
  56. for id_, name, score in zip(result["class_ids"], cat_names, result["scores"]):
  57. categories.append(dict(id=id_, name=name, score=score))
  58. return ResultResponse[InferResult](
  59. logId=serving_utils.generate_log_id(),
  60. result=InferResult(categories=categories),
  61. )
  62. return app