formula_recognition.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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 ...formula_recognition import FormulaRecognitionPipeline
  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[float], Field(min_length=2, max_length=2)]
  29. Polygon: TypeAlias = Annotated[List[Point], Field(min_length=3)]
  30. class Formula(BaseModel):
  31. poly: Polygon
  32. latex: str
  33. class InferResult(BaseModel):
  34. formulas: List[Formula]
  35. layoutImage: str
  36. ocrImage: Optional[str] = None
  37. def create_pipeline_app(
  38. pipeline: FormulaRecognitionPipeline, app_config: AppConfig
  39. ) -> FastAPI:
  40. app, ctx = create_app(
  41. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  42. )
  43. @app.post(
  44. "/formula-recognition",
  45. operation_id="infer",
  46. responses={422: {"model": Response}},
  47. response_model_exclude_none=True,
  48. )
  49. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  50. pipeline = ctx.pipeline
  51. aiohttp_session = ctx.aiohttp_session
  52. if request.inferenceParams:
  53. max_long_side = request.inferenceParams.maxLongSide
  54. if max_long_side:
  55. raise HTTPException(
  56. status_code=422,
  57. detail="`max_long_side` is currently not supported.",
  58. )
  59. try:
  60. file_bytes = await serving_utils.get_raw_bytes(
  61. request.image, aiohttp_session
  62. )
  63. image = serving_utils.image_bytes_to_array(file_bytes)
  64. result = (await pipeline.infer(image))[0]
  65. formulas: List[Formula] = []
  66. for poly, latex in zip(result["dt_polys"], result["rec_formula"]):
  67. formulas.append(
  68. Formula(
  69. poly=poly,
  70. latex=latex,
  71. )
  72. )
  73. layout_image_base64 = serving_utils.base64_encode(
  74. serving_utils.image_to_bytes(result["layout_result"].img)
  75. )
  76. ocr_image = result["formula_result"].img
  77. if ocr_image is not None:
  78. ocr_image_base64 = serving_utils.base64_encode(
  79. serving_utils.image_to_bytes(ocr_image)
  80. )
  81. else:
  82. ocr_image_base64 = None
  83. return ResultResponse(
  84. logId=serving_utils.generate_log_id(),
  85. errorCode=0,
  86. errorMsg="Success",
  87. result=InferResult(
  88. formulas=formulas,
  89. layoutImage=layout_image_base64,
  90. ocrImage=ocr_image_base64,
  91. ),
  92. )
  93. except Exception as e:
  94. logging.exception(e)
  95. raise HTTPException(status_code=500, detail="Internal server error")
  96. return app