table_recognition.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. import numpy as np
  15. from ..base import BasePipeline
  16. from ...predictors import create_predictor
  17. from ..ocr import OCRPipeline
  18. from ...components import CropByBoxes
  19. from ...results import OCRResult, TableResult, StructureTableResult
  20. from .utils import *
  21. class TableRecPipeline(BasePipeline):
  22. """Table Recognition Pipeline"""
  23. def __init__(
  24. self,
  25. layout_model,
  26. text_det_model,
  27. text_rec_model,
  28. table_model,
  29. batch_size=1,
  30. device="gpu",
  31. chat_ocr=False,
  32. ):
  33. self.layout_predictor = create_predictor(
  34. model=layout_model, device=device, batch_size=batch_size
  35. )
  36. self.ocr_pipeline = OCRPipeline(
  37. text_det_model, text_rec_model, batch_size, device
  38. )
  39. self.table_predictor = create_predictor(
  40. model=table_model, device=device, batch_size=batch_size
  41. )
  42. self._crop_by_boxes = CropByBoxes()
  43. self._match = TableMatch(filter_ocr_result=False)
  44. self.chat_ocr = chat_ocr
  45. super().__init__()
  46. def predict(self, x):
  47. batch_structure_res = []
  48. for batch_layout_pred, batch_ocr_pred in zip(
  49. self.layout_predictor(x), self.ocr_pipeline(x)
  50. ):
  51. for layout_pred, ocr_pred in zip(batch_layout_pred, batch_ocr_pred):
  52. single_img_res = {
  53. "img_path": "",
  54. "layout_result": {},
  55. "ocr_result": {},
  56. "table_result": [],
  57. }
  58. layout_res = layout_pred["result"]
  59. # update layout result
  60. single_img_res["img_path"] = layout_res["img_path"]
  61. single_img_res["layout_result"] = layout_res
  62. ocr_res = ocr_pred["result"]
  63. all_subs_of_img = list(self._crop_by_boxes(layout_res))
  64. # get cropped images with label 'table'
  65. table_subs = []
  66. for batch_subs in all_subs_of_img:
  67. table_sub_list = []
  68. for sub in batch_subs:
  69. box = sub["box"]
  70. if sub["label"].lower() == "table":
  71. table_sub_list.append(sub)
  72. _, ocr_res = self.get_ocr_result_by_bbox(box, ocr_res)
  73. table_subs.append(table_sub_list)
  74. table_res, all_table_ocr_res = self.get_table_result(table_subs)
  75. for batch_table_ocr_res in all_table_ocr_res:
  76. for table_ocr_res in batch_table_ocr_res:
  77. ocr_res["dt_polys"].extend(table_ocr_res["dt_polys"])
  78. ocr_res["rec_text"].extend(table_ocr_res["rec_text"])
  79. ocr_res["rec_score"].extend(table_ocr_res["rec_score"])
  80. single_img_res["table_result"] = table_res
  81. single_img_res["ocr_result"] = OCRResult(ocr_res)
  82. batch_structure_res.append({"result": TableResult(single_img_res)})
  83. yield batch_structure_res
  84. def get_ocr_result_by_bbox(self, box, ocr_res):
  85. dt_polys_list = []
  86. rec_text_list = []
  87. score_list = []
  88. unmatched_ocr_res = {"dt_polys": [], "rec_text": [], "rec_score": []}
  89. unmatched_ocr_res["img_path"] = ocr_res["img_path"]
  90. for i, text_box in enumerate(ocr_res["dt_polys"]):
  91. text_box_area = convert_4point2rect(text_box)
  92. if is_inside(text_box_area, box):
  93. dt_polys_list.append(text_box)
  94. rec_text_list.append(ocr_res["rec_text"][i])
  95. score_list.append(ocr_res["rec_score"][i])
  96. else:
  97. unmatched_ocr_res["dt_polys"].append(text_box)
  98. unmatched_ocr_res["rec_text"].append(ocr_res["rec_text"][i])
  99. unmatched_ocr_res["rec_score"].append(ocr_res["rec_score"][i])
  100. return (dt_polys_list, rec_text_list, score_list), unmatched_ocr_res
  101. def get_table_result(self, input_img):
  102. table_res_list = []
  103. ocr_res_list = []
  104. table_index = 0
  105. for batch_input, batch_table_pred, batch_ocr_pred in zip(
  106. input_img, self.table_predictor(input_img), self.ocr_pipeline(input_img)
  107. ):
  108. batch_table_res = []
  109. batch_ocr_res = []
  110. for input, table_pred, ocr_pred in zip(
  111. batch_input, batch_table_pred, batch_ocr_pred
  112. ):
  113. single_table_res = table_pred["result"]
  114. ocr_res = ocr_pred["result"]
  115. single_table_box = single_table_res["bbox"]
  116. ori_x, ori_y, _, _ = input["box"]
  117. ori_bbox_list = np.array(
  118. get_ori_coordinate_for_table(ori_x, ori_y, single_table_box),
  119. dtype=np.float32,
  120. )
  121. ori_ocr_bbox_list = np.array(
  122. get_ori_coordinate_for_table(ori_x, ori_y, ocr_res["dt_polys"]),
  123. dtype=np.float32,
  124. )
  125. ocr_res["dt_polys"] = ori_ocr_bbox_list
  126. html_res = self._match(single_table_res, ocr_res)
  127. batch_table_res.append(
  128. StructureTableResult(
  129. {
  130. "img_path": input["img_path"],
  131. "bbox": ori_bbox_list,
  132. "img_idx": table_index,
  133. "html": html_res,
  134. }
  135. )
  136. )
  137. batch_ocr_res.append(ocr_res)
  138. table_index += 1
  139. table_res_list.append(batch_table_res)
  140. ocr_res_list.append(batch_ocr_res)
  141. return table_res_list, ocr_res_list