small_object_detection.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 List
  15. from fastapi import FastAPI, HTTPException
  16. from pydantic import BaseModel, Field
  17. from typing_extensions import Annotated, TypeAlias
  18. from .....utils import logging
  19. from ...single_model_pipeline import SmallObjDet
  20. from .. import utils as serving_utils
  21. from ..app import AppConfig, create_app
  22. from ..models import Response, ResultResponse
  23. class InferRequest(BaseModel):
  24. image: str
  25. BoundingBox: TypeAlias = Annotated[List[float], Field(min_length=4, max_length=4)]
  26. class DetectedObject(BaseModel):
  27. bbox: BoundingBox
  28. categoryId: int
  29. score: float
  30. class InferResult(BaseModel):
  31. detectedObjects: List[DetectedObject]
  32. image: str
  33. def create_pipeline_app(pipeline: SmallObjDet, app_config: AppConfig) -> FastAPI:
  34. app, ctx = create_app(
  35. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  36. )
  37. @app.post(
  38. "/small-object-detection",
  39. operation_id="infer",
  40. responses={422: {"model": Response}},
  41. )
  42. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  43. pipeline = ctx.pipeline
  44. aiohttp_session = ctx.aiohttp_session
  45. try:
  46. file_bytes = await serving_utils.get_raw_bytes(
  47. request.image, aiohttp_session
  48. )
  49. image = serving_utils.image_bytes_to_array(file_bytes)
  50. result = (await pipeline.infer(image))[0]
  51. objects: List[DetectedObject] = []
  52. for obj in result["boxes"]:
  53. objects.append(
  54. DetectedObject(
  55. bbox=obj["coordinate"],
  56. categoryId=obj["cls_id"],
  57. score=obj["score"],
  58. )
  59. )
  60. output_image_base64 = serving_utils.base64_encode(
  61. serving_utils.image_to_bytes(result.img)
  62. )
  63. return ResultResponse(
  64. logId=serving_utils.generate_log_id(),
  65. errorCode=0,
  66. errorMsg="Success",
  67. result=InferResult(detectedObjects=objects, image=output_image_base64),
  68. )
  69. except Exception as e:
  70. logging.exception(e)
  71. raise HTTPException(status_code=500, detail="Internal server error")
  72. return app