table_recognition.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 re
  15. import numpy as np
  16. from ..base import BasePipeline
  17. from ...predictors import create_predictor
  18. from ..ocr import OCRPipeline
  19. from ...components import CropByBoxes
  20. from ...results import OCRResult, TableResult, StructureTableResult
  21. from copy import deepcopy
  22. from .utils import *
  23. class TableRecPipeline(BasePipeline):
  24. """Table Recognition Pipeline"""
  25. def __init__(
  26. self,
  27. layout_model,
  28. text_det_model,
  29. text_rec_model,
  30. table_model,
  31. batch_size=1,
  32. device="gpu",
  33. chat_ocr=False,
  34. ):
  35. self.layout_predictor = create_predictor(
  36. model=layout_model, device=device, batch_size=batch_size
  37. )
  38. self.ocr_pipeline = OCRPipeline(
  39. text_det_model, text_rec_model, batch_size, device
  40. )
  41. self.table_predictor = create_predictor(
  42. model=table_model, device=device, batch_size=batch_size
  43. )
  44. self._crop_by_boxes = CropByBoxes()
  45. self._match = TableMatch(filter_ocr_result=False)
  46. self.chat_ocr = chat_ocr
  47. super().__init__()
  48. def predict(self, x):
  49. batch_structure_res = []
  50. for batch_layout_pred, batch_ocr_pred in zip(
  51. self.layout_predictor(x), self.ocr_pipeline(x)
  52. ):
  53. for layout_pred, ocr_pred in zip(batch_layout_pred, batch_ocr_pred):
  54. single_img_structure_res = {
  55. "img_path": "",
  56. "layout_result": {},
  57. "ocr_result": {},
  58. "table_result": [],
  59. }
  60. layout_res = layout_pred["result"]
  61. # update layout result
  62. single_img_structure_res["img_path"] = layout_res["img_path"]
  63. single_img_structure_res["layout_result"] = layout_res
  64. single_img_ocr_res = ocr_pred["result"]
  65. all_subs_of_img = list(self._crop_by_boxes(layout_res))
  66. table_subs_of_img = []
  67. seal_subs_of_img = []
  68. # ocr result without table and seal
  69. ocr_res = deepcopy(single_img_ocr_res)
  70. # ocr result in table and seal, is for batch
  71. table_ocr_res, seal_ocr_res = [], []
  72. # get cropped images and ocr result
  73. for batch_subs in all_subs_of_img:
  74. table_batch_list, seal_batch_list = [], []
  75. table_batch_ocr_res, seal_batch_ocr_res = [], []
  76. for sub in batch_subs:
  77. box = sub["box"]
  78. if sub["label"].lower() == "table":
  79. table_batch_list.append(sub)
  80. relative_res, ocr_res = self.get_ocr_result_by_bbox(
  81. box, ocr_res
  82. )
  83. table_batch_ocr_res.append(
  84. {
  85. "dt_polys": relative_res[0],
  86. "rec_text": relative_res[1],
  87. }
  88. )
  89. elif sub["label"].lower() == "seal":
  90. seal_batch_list.append(sub)
  91. relative_res, ocr_res = self.get_ocr_result_by_bbox(
  92. box, ocr_res
  93. )
  94. seal_batch_ocr_res.append(
  95. {
  96. "dt_polys": relative_res[0],
  97. "rec_text": relative_res[1],
  98. }
  99. )
  100. elif sub["label"].lower() == "figure":
  101. # remove ocr result in figure
  102. _, ocr_res = self.get_ocr_result_by_bbox(box, ocr_res)
  103. table_subs_of_img.append(table_batch_list)
  104. table_ocr_res.append(table_batch_ocr_res)
  105. seal_subs_of_img.append(seal_batch_list)
  106. seal_ocr_res.append(seal_batch_ocr_res)
  107. # get table result
  108. table_res = self.get_table_result(table_subs_of_img, table_ocr_res)
  109. # get seal result
  110. if seal_subs_of_img:
  111. pass
  112. if self.chat_ocr:
  113. # chat ocr does not visualize table results in ocr result
  114. single_img_structure_res["ocr_result"] = OCRResult(ocr_res)
  115. else:
  116. single_img_structure_res["ocr_result"] = single_img_ocr_res
  117. single_img_structure_res["table_result"] = table_res
  118. batch_structure_res.append(
  119. {"result": TableResult(single_img_structure_res)}
  120. )
  121. yield batch_structure_res
  122. def get_ocr_result_by_bbox(self, box, ocr_res):
  123. dt_polys_list = []
  124. rec_text_list = []
  125. unmatched_ocr_res = {"dt_polys": [], "rec_text": []}
  126. for text_box, text_res in zip(ocr_res["dt_polys"], ocr_res["rec_text"]):
  127. text_box_area = convert_4point2rect(text_box)
  128. if is_inside(box, text_box_area):
  129. dt_polys_list.append(text_box)
  130. rec_text_list.append(text_res)
  131. else:
  132. unmatched_ocr_res["dt_polys"].append(text_box)
  133. unmatched_ocr_res["rec_text"].append(text_res)
  134. return (dt_polys_list, rec_text_list), unmatched_ocr_res
  135. def get_table_result(self, input_img, table_ocr_res):
  136. table_res_list = []
  137. table_index = 0
  138. for batch_input, batch_table_res, batch_ocr_res in zip(
  139. input_img, self.table_predictor(input_img), table_ocr_res
  140. ):
  141. batch_res_list = []
  142. for roi_img, table_res, ocr_res in zip(
  143. batch_input, batch_table_res, batch_ocr_res
  144. ):
  145. single_table_res = table_res["result"]
  146. single_table_box = single_table_res["bbox"]
  147. ori_x, ori_y, _, _ = roi_img["box"]
  148. ori_bbox_list = np.array(
  149. get_ori_coordinate_for_table(ori_x, ori_y, single_table_box),
  150. dtype=np.float32,
  151. )
  152. single_table_res["bbox"] = ori_bbox_list
  153. html_res = self._match(single_table_res, ocr_res)
  154. batch_res_list.append(
  155. StructureTableResult(
  156. {
  157. "img_path": roi_img["img_path"],
  158. "img_idx": table_index,
  159. "bbox": ori_bbox_list,
  160. "html": html_res,
  161. "structure": single_table_res["structure"],
  162. }
  163. )
  164. )
  165. table_index += 1
  166. table_res_list.append(batch_res_list)
  167. return table_res_list