formula_recognition.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. image: str
  36. def create_pipeline_app(
  37. pipeline: FormulaRecognitionPipeline, app_config: AppConfig
  38. ) -> FastAPI:
  39. app, ctx = create_app(
  40. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  41. )
  42. @app.post(
  43. "/formula-recognition",
  44. operation_id="infer",
  45. responses={422: {"model": Response}},
  46. )
  47. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  48. pipeline = ctx.pipeline
  49. aiohttp_session = ctx.aiohttp_session
  50. if request.inferenceParams:
  51. max_long_side = request.inferenceParams.maxLongSide
  52. if max_long_side:
  53. raise HTTPException(
  54. status_code=422,
  55. detail="`max_long_side` is currently not supported.",
  56. )
  57. try:
  58. file_bytes = await serving_utils.get_raw_bytes(
  59. request.image, aiohttp_session
  60. )
  61. image = serving_utils.image_bytes_to_array(file_bytes)
  62. result = (await pipeline.infer(image))[0]
  63. formulas: List[Formula] = []
  64. for poly, latex in zip(result["dt_polys"], result["rec_formula"]):
  65. formulas.append(
  66. Formula(
  67. poly=poly,
  68. latex=latex,
  69. )
  70. )
  71. output_image_base64 = serving_utils.image_to_base64(result.img)
  72. return ResultResponse(
  73. logId=serving_utils.generate_log_id(),
  74. errorCode=0,
  75. errorMsg="Success",
  76. result=InferResult(
  77. formulas=formulas,
  78. image=output_image_base64,
  79. ),
  80. )
  81. except Exception as e:
  82. logging.exception(e)
  83. raise HTTPException(status_code=500, detail="Internal server error")
  84. return app