formula_recognition.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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, 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 ...formula_recognition import FormulaRecognitionPipeline
  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[float], Field(min_length=2, max_length=2)]
  26. Polygon: TypeAlias = Annotated[List[Point], Field(min_length=3)]
  27. class Formula(BaseModel):
  28. poly: Polygon
  29. latex: str
  30. class FormulaRecResult(BaseModel):
  31. formulas: List[Formula]
  32. inputImage: str
  33. layoutImage: str
  34. ocrImage: Optional[str] = None
  35. class InferResult(BaseModel):
  36. formulaRecResults: List[FormulaRecResult]
  37. dataInfo: DataInfo
  38. def create_pipeline_app(
  39. pipeline: FormulaRecognitionPipeline, app_config: AppConfig
  40. ) -> FastAPI:
  41. app, ctx = create_app(
  42. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  43. )
  44. ocr_common.update_app_context(ctx)
  45. ctx.extra["return_ocr_imgs"] = False
  46. if ctx.config.extra:
  47. if "return_ocr_imgs" in ctx.config.extra:
  48. ctx.extra["return_ocr_imgs"] = ctx.config.extra["return_ocr_imgs"]
  49. @app.post(
  50. "/formula-recognition",
  51. operation_id="infer",
  52. responses={422: {"model": NoResultResponse}},
  53. response_model_exclude_none=True,
  54. )
  55. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  56. pipeline = ctx.pipeline
  57. log_id = serving_utils.generate_log_id()
  58. if request.inferenceParams:
  59. max_long_side = request.inferenceParams.maxLongSide
  60. if max_long_side:
  61. raise HTTPException(
  62. status_code=422,
  63. detail="`max_long_side` is currently not supported.",
  64. )
  65. images, data_info = await ocr_common.get_images(request, ctx)
  66. try:
  67. result = await pipeline.infer(images)
  68. formula_rec_results: List[FormulaRecResult] = []
  69. for i, (img, item) in enumerate(zip(images, result)):
  70. formulas: List[Formula] = []
  71. for poly, latex in zip(item["dt_polys"], item["rec_formula"]):
  72. formulas.append(
  73. Formula(
  74. poly=poly,
  75. latex=latex,
  76. )
  77. )
  78. layout_img = item["layout_result"].img
  79. if ctx.extra["return_ocr_imgs"]:
  80. ocr_img = item["formula_result"].img
  81. if ocr_img is None:
  82. raise RuntimeError("Failed to get the OCR image")
  83. else:
  84. ocr_img = None
  85. output_imgs = await ocr_common.postprocess_images(
  86. log_id=log_id,
  87. index=i,
  88. app_context=ctx,
  89. input_image=img,
  90. layout_image=layout_img,
  91. ocr_image=ocr_img,
  92. )
  93. if ocr_img is not None:
  94. input_img, layout_img, ocr_img = output_imgs
  95. else:
  96. input_img, layout_img = output_imgs
  97. formula_rec_results.append(
  98. FormulaRecResult(
  99. formulas=formulas,
  100. inputImage=input_img,
  101. layoutImage=layout_img,
  102. ocrImage=ocr_img,
  103. )
  104. )
  105. return ResultResponse[InferResult](
  106. logId=log_id,
  107. result=InferResult(
  108. formulaRecResults=formula_rec_results,
  109. dataInfo=data_info,
  110. ),
  111. )
  112. except Exception:
  113. logging.exception("Unexpected exception")
  114. raise HTTPException(status_code=500, detail="Internal server error")
  115. return app