anomaly_detection.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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
  18. from .....utils import logging
  19. from ...single_model_pipeline import AnomalyDetection
  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. class InferResult(BaseModel):
  26. labelMap: List[int]
  27. size: Annotated[List[int], Field(min_length=2, max_length=2)]
  28. image: str
  29. def create_pipeline_app(pipeline: AnomalyDetection, app_config: AppConfig) -> FastAPI:
  30. app, ctx = create_app(
  31. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  32. )
  33. @app.post(
  34. "/image-anomaly-detection",
  35. operation_id="infer",
  36. responses={422: {"model": Response}},
  37. )
  38. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  39. pipeline = ctx.pipeline
  40. aiohttp_session = ctx.aiohttp_session
  41. try:
  42. file_bytes = await serving_utils.get_raw_bytes(
  43. request.image, aiohttp_session
  44. )
  45. image = serving_utils.image_bytes_to_array(file_bytes)
  46. result = (await pipeline.infer(image))[0]
  47. pred = result["pred"][0].tolist()
  48. size = [len(pred), len(pred[0])]
  49. label_map = [item for sublist in pred for item in sublist]
  50. output_image_base64 = serving_utils.image_to_base64(
  51. result.img.convert("RGB")
  52. )
  53. return ResultResponse(
  54. logId=serving_utils.generate_log_id(),
  55. errorCode=0,
  56. errorMsg="Success",
  57. result=InferResult(
  58. labelMap=label_map, size=size, image=output_image_base64
  59. ),
  60. )
  61. except Exception as e:
  62. logging.exception(e)
  63. raise HTTPException(status_code=500, detail="Internal server error")
  64. return app