table_recognition.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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 ...table_recognition import TableRecPipeline
  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. BoundingBox: TypeAlias = Annotated[List[float], Field(min_length=4, max_length=4)]
  30. class Table(BaseModel):
  31. bbox: BoundingBox
  32. html: str
  33. class InferResult(BaseModel):
  34. tables: List[Table]
  35. layoutImage: str
  36. ocrImage: str
  37. def create_pipeline_app(pipeline: TableRecPipeline, app_config: AppConfig) -> FastAPI:
  38. app, ctx = create_app(
  39. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  40. )
  41. @app.post(
  42. "/table-recognition", operation_id="infer", responses={422: {"model": Response}}
  43. )
  44. async def _infer(request: InferRequest) -> ResultResponse[InferResult]:
  45. pipeline = ctx.pipeline
  46. aiohttp_session = ctx.aiohttp_session
  47. if request.inferenceParams:
  48. max_long_side = request.inferenceParams.maxLongSide
  49. if max_long_side:
  50. raise HTTPException(
  51. status_code=422,
  52. detail="`max_long_side` is currently not supported.",
  53. )
  54. try:
  55. file_bytes = await serving_utils.get_raw_bytes(
  56. request.image, aiohttp_session
  57. )
  58. image = serving_utils.image_bytes_to_array(file_bytes)
  59. result = (await pipeline.infer(image))[0]
  60. tables: List[Table] = []
  61. for item in result["table_result"]:
  62. tables.append(
  63. Table(
  64. bbox=item["layout_bbox"],
  65. html=item["html"],
  66. )
  67. )
  68. layout_image_base64 = serving_utils.image_to_base64(
  69. result["layout_result"].img
  70. )
  71. ocr_iamge_base64 = serving_utils.image_to_base64(result["ocr_result"].img)
  72. return ResultResponse(
  73. logId=serving_utils.generate_log_id(),
  74. errorCode=0,
  75. errorMsg="Success",
  76. result=InferResult(
  77. tables=tables,
  78. layoutImage=layout_image_base64,
  79. ocrImage=ocr_iamge_base64,
  80. ),
  81. )
  82. except Exception as e:
  83. logging.exception(e)
  84. raise HTTPException(status_code=500, detail="Internal server error")
  85. return app