video_classification.py 2.7 KB

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