ocr.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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, Optional
  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 ...ocr import OCRPipeline
  20. from .. import utils as serving_utils
  21. from ..app import AppConfig, create_app
  22. from ..models import Response, ResultResponse
  23. class InferenceParams(BaseModel):
  24. maxLongSide: Optional[Annotated[int, Field(gt=0)]] = None
  25. class InferRequest(BaseModel):
  26. image: str
  27. inferenceParams: Optional[InferenceParams] = None
  28. Point: TypeAlias = Annotated[List[int], Field(min_length=2, max_length=2)]
  29. Polygon: TypeAlias = Annotated[List[Point], Field(min_length=3)]
  30. class Text(BaseModel):
  31. poly: Polygon
  32. text: str
  33. score: float
  34. class InferResult(BaseModel):
  35. texts: List[Text]
  36. image: str
  37. def create_pipeline_app(pipeline: OCRPipeline, app_config: AppConfig) -> FastAPI:
  38. app, ctx = create_app(
  39. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  40. )
  41. @app.post("/ocr", operation_id="infer", responses={422: {"model": Response}})
  42. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  43. pipeline = ctx.pipeline
  44. aiohttp_session = ctx.aiohttp_session
  45. if request.inferenceParams:
  46. max_long_side = request.inferenceParams.maxLongSide
  47. if max_long_side:
  48. raise HTTPException(
  49. status_code=422,
  50. detail="`max_long_side` is currently not supported.",
  51. )
  52. try:
  53. file_bytes = await serving_utils.get_raw_bytes(
  54. request.image, aiohttp_session
  55. )
  56. image = serving_utils.image_bytes_to_array(file_bytes)
  57. result = (await pipeline.infer(image))[0]
  58. texts: List[Text] = []
  59. for poly, text, score in zip(
  60. result["dt_polys"], result["rec_text"], result["rec_score"]
  61. ):
  62. texts.append(Text(poly=poly, text=text, score=score))
  63. output_image_base64 = serving_utils.base64_encode(
  64. serving_utils.image_to_bytes(result.img)
  65. )
  66. return ResultResponse(
  67. logId=serving_utils.generate_log_id(),
  68. errorCode=0,
  69. errorMsg="Success",
  70. result=InferResult(texts=texts, image=output_image_base64),
  71. )
  72. except Exception as e:
  73. logging.exception(e)
  74. raise HTTPException(status_code=500, detail="Internal server error")
  75. return app