table_recognition.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 Any, Dict, List
  15. from .....utils.deps import function_requires_deps, is_dep_available
  16. from ...infra import utils as serving_utils
  17. from ...infra.config import AppConfig
  18. from ...infra.models import AIStudioResultResponse
  19. from ...schemas.table_recognition import INFER_ENDPOINT, InferRequest, InferResult
  20. from .._app import create_app, primary_operation
  21. from ._common import common
  22. from ._common import ocr as ocr_common
  23. if is_dep_available("fastapi"):
  24. from fastapi import FastAPI
  25. @function_requires_deps("fastapi")
  26. def create_pipeline_app(pipeline: Any, app_config: AppConfig) -> "FastAPI":
  27. app, ctx = create_app(
  28. pipeline=pipeline, app_config=app_config, app_aiohttp_session=True
  29. )
  30. ocr_common.update_app_context(ctx)
  31. @primary_operation(
  32. app,
  33. INFER_ENDPOINT,
  34. "infer",
  35. )
  36. async def _infer(request: InferRequest) -> AIStudioResultResponse[InferResult]:
  37. pipeline = ctx.pipeline
  38. log_id = serving_utils.generate_log_id()
  39. visualize_enabled = (
  40. request.visualize if request.visualize is not None else ctx.config.visualize
  41. )
  42. images, data_info = await ocr_common.get_images(request, ctx)
  43. result = await pipeline.infer(
  44. images,
  45. use_doc_orientation_classify=request.useDocOrientationClassify,
  46. use_doc_unwarping=request.useDocUnwarping,
  47. use_layout_detection=request.useLayoutDetection,
  48. use_ocr_model=request.useOcrModel,
  49. text_det_limit_side_len=request.textDetLimitSideLen,
  50. text_det_limit_type=request.textDetLimitType,
  51. text_det_thresh=request.textDetThresh,
  52. text_det_box_thresh=request.textDetBoxThresh,
  53. text_det_unclip_ratio=request.textDetUnclipRatio,
  54. text_rec_score_thresh=request.textRecScoreThresh,
  55. use_ocr_results_with_table_cells=request.useOcrResultsWithTableCells,
  56. )
  57. table_rec_results: List[Dict[str, Any]] = []
  58. for i, (img, item) in enumerate(zip(images, result)):
  59. pruned_res = common.prune_result(item.json["res"])
  60. if visualize_enabled:
  61. imgs = {
  62. "input_img": img,
  63. **item.img,
  64. }
  65. imgs = await serving_utils.call_async(
  66. common.postprocess_images,
  67. imgs,
  68. log_id,
  69. filename_template=f"{{key}}_{i}.jpg",
  70. file_storage=ctx.extra["file_storage"],
  71. return_urls=ctx.extra["return_img_urls"],
  72. max_img_size=ctx.extra["max_output_img_size"],
  73. )
  74. else:
  75. imgs = {}
  76. table_rec_results.append(
  77. dict(
  78. prunedResult=pruned_res,
  79. outputImages=(
  80. {k: v for k, v in imgs.items() if k != "input_img"}
  81. if imgs
  82. else None
  83. ),
  84. inputImage=imgs.get("input_img"),
  85. )
  86. )
  87. return AIStudioResultResponse[InferResult](
  88. logId=log_id,
  89. result=InferResult(
  90. tableRecResults=table_rec_results,
  91. dataInfo=data_info,
  92. ),
  93. )
  94. return app