object_detection.py 2.7 KB

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