seal_recognition.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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, Type
  15. from fastapi import FastAPI, HTTPException
  16. from pydantic import BaseModel, Field
  17. from typing_extensions import Annotated, TypeAlias
  18. from ._common import ocr as ocr_common
  19. from .....utils import logging
  20. from ...seal_recognition import SealOCRPipeline
  21. from .. import utils as serving_utils
  22. from ..app import AppConfig, create_app
  23. from ..models import NoResultResponse, ResultResponse, DataInfo
  24. InferRequest: Type[ocr_common.InferRequest] = ocr_common.InferRequest
  25. Point: TypeAlias = Annotated[List[int], Field(min_length=2, max_length=2)]
  26. Polygon: TypeAlias = Annotated[List[Point], Field(min_length=3)]
  27. class Text(BaseModel):
  28. poly: Polygon
  29. text: str
  30. score: float
  31. class SealRecResult(BaseModel):
  32. texts: List[Text]
  33. inputImage: str
  34. layoutImage: str
  35. ocrImage: str
  36. class InferResult(BaseModel):
  37. sealRecResults: List[SealRecResult]
  38. dataInfo: DataInfo
  39. def create_pipeline_app(pipeline: SealOCRPipeline, app_config: AppConfig) -> FastAPI:
  40. app, ctx = create_app(
  41. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  42. )
  43. ocr_common.update_app_context(ctx)
  44. @app.post(
  45. "/seal-recognition",
  46. operation_id="infer",
  47. responses={422: {"model": NoResultResponse}},
  48. response_model_exclude_none=True,
  49. )
  50. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  51. pipeline = ctx.pipeline
  52. log_id = serving_utils.generate_log_id()
  53. if request.inferenceParams:
  54. max_long_side = request.inferenceParams.maxLongSide
  55. if max_long_side:
  56. raise HTTPException(
  57. status_code=422,
  58. detail="`max_long_side` is currently not supported.",
  59. )
  60. images, data_info = await ocr_common.get_images(request, ctx)
  61. try:
  62. result = await pipeline.infer(images)
  63. seal_rec_results: List[SealRecResult] = []
  64. for i, (img, item) in enumerate(zip(images, result)):
  65. texts: List[Text] = []
  66. for poly, text, score in zip(
  67. item["ocr_result"]["dt_polys"],
  68. item["ocr_result"]["rec_text"],
  69. item["ocr_result"]["rec_score"],
  70. ):
  71. texts.append(Text(poly=poly, text=text, score=score))
  72. input_img, layout_img, ocr_img = await ocr_common.postprocess_images(
  73. log_id=log_id,
  74. index=i,
  75. app_context=ctx,
  76. input_image=img,
  77. layout_image=item["layout_result"].img,
  78. ocr_image=item["ocr_result"].img,
  79. )
  80. seal_rec_results.append(
  81. SealRecResult(
  82. texts=texts,
  83. inputImage=input_img,
  84. layoutImage=layout_img,
  85. ocrImage=ocr_img,
  86. )
  87. )
  88. return ResultResponse[InferResult](
  89. logId=log_id,
  90. result=InferResult(
  91. sealRecResults=seal_rec_results,
  92. dataInfo=data_info,
  93. ),
  94. )
  95. except Exception:
  96. logging.exception("Unexpected exception")
  97. raise HTTPException(status_code=500, detail="Internal server error")
  98. return app