video_detection.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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_detection 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 = (
  49. await pipeline.infer(
  50. video_path,
  51. nms_thresh=request.nmsThresh,
  52. score_thresh=request.scoreThresh,
  53. )
  54. )[0]
  55. finally:
  56. await serving_utils.call_async(os.unlink, video_path)
  57. frames: List[Dict[str, Any]] = []
  58. for i, item in enumerate(result["result"]):
  59. objs: List[Dict[str, Any]] = []
  60. for obj in item:
  61. objs.append(
  62. dict(
  63. bbox=obj[0],
  64. categoryName=obj[2],
  65. score=obj[1],
  66. )
  67. )
  68. frames.append(
  69. dict(
  70. index=i,
  71. detectedObjects=objs,
  72. )
  73. )
  74. return ResultResponse[InferResult](
  75. logId=serving_utils.generate_log_id(),
  76. result=InferResult(frames=frames),
  77. )
  78. return app