object_detection.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 typing import Any, Dict, List
  15. from fastapi import FastAPI
  16. from ...infra import utils as serving_utils
  17. from ...infra.config import AppConfig
  18. from ...infra.models import ResultResponse
  19. from ...schemas.object_detection import INFER_ENDPOINT, InferRequest, InferResult
  20. from .._app import create_app, primary_operation
  21. def create_pipeline_app(pipeline: Any, app_config: AppConfig) -> FastAPI:
  22. app, ctx = create_app(
  23. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  24. )
  25. @primary_operation(
  26. app,
  27. INFER_ENDPOINT,
  28. "infer",
  29. )
  30. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  31. pipeline = ctx.pipeline
  32. aiohttp_session = ctx.aiohttp_session
  33. file_bytes = await serving_utils.get_raw_bytes_async(
  34. request.image, aiohttp_session
  35. )
  36. image = serving_utils.image_bytes_to_array(file_bytes)
  37. result = (
  38. await pipeline.infer(
  39. image,
  40. threshold=request.threshold,
  41. )
  42. )[0]
  43. objects: List[Dict[str, Any]] = []
  44. for obj in result["boxes"]:
  45. objects.append(
  46. dict(
  47. bbox=obj["coordinate"],
  48. categoryId=obj["cls_id"],
  49. categoryName=obj["label"],
  50. score=obj["score"],
  51. )
  52. )
  53. if ctx.config.visualize:
  54. output_image_base64 = serving_utils.base64_encode(
  55. serving_utils.image_to_bytes(result.img["res"])
  56. )
  57. else:
  58. output_image_base64 = None
  59. return ResultResponse[InferResult](
  60. logId=serving_utils.generate_log_id(),
  61. result=InferResult(detectedObjects=objects, image=output_image_base64),
  62. )
  63. return app