table_recognition.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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 .utils import *
  16. from ..base import BasePipeline
  17. from ..ocr import OCRPipeline
  18. from ....utils import logging
  19. from ...components import CropByBoxes
  20. from ...results import OCRResult, TableResult, StructureTableResult
  21. class TableRecPipeline(BasePipeline):
  22. """Table Recognition Pipeline"""
  23. entities = "table_recognition"
  24. def __init__(
  25. self,
  26. layout_model,
  27. text_det_model,
  28. text_rec_model,
  29. table_model,
  30. layout_batch_size=1,
  31. text_det_batch_size=1,
  32. text_rec_batch_size=1,
  33. table_batch_size=1,
  34. predictor_kwargs=None,
  35. ):
  36. self.layout_model = layout_model
  37. self.text_det_model = text_det_model
  38. self.text_rec_model = text_rec_model
  39. self.table_model = table_model
  40. self.layout_batch_size = layout_batch_size
  41. self.text_det_batch_size = text_det_batch_size
  42. self.text_rec_batch_size = text_rec_batch_size
  43. self.table_batch_size = table_batch_size
  44. self.predictor_kwargs = predictor_kwargs
  45. super().__init__(predictor_kwargs=predictor_kwargs)
  46. self._build_predictor()
  47. def _build_predictor(
  48. self,
  49. ):
  50. self.layout_predictor = self._create_model(model=self.layout_model)
  51. self.ocr_pipeline = OCRPipeline(
  52. text_det_model=self.text_det_model,
  53. text_rec_model=self.text_rec_model,
  54. text_det_batch_size=self.text_det_batch_size,
  55. text_rec_batch_size=self.text_rec_batch_size,
  56. predictor_kwargs=self.predictor_kwargs,
  57. )
  58. self.table_predictor = self._create_model(model=self.table_model)
  59. self._crop_by_boxes = CropByBoxes()
  60. self._match = TableMatch(filter_ocr_result=False)
  61. self.layout_predictor.set_predictor(batch_size=self.layout_batch_size)
  62. self.ocr_pipeline.text_rec_model.set_predictor(
  63. batch_size=self.text_rec_batch_size
  64. )
  65. self.table_predictor.set_predictor(batch_size=self.table_batch_size)
  66. def set_predictor(
  67. self,
  68. layout_batch_size=None,
  69. text_det_batch_size=None,
  70. text_rec_batch_size=None,
  71. table_batch_size=None,
  72. ):
  73. if text_det_batch_size and text_det_batch_size > 1:
  74. logging.warning(
  75. f"text det model only support batch_size=1 now,the setting of text_det_batch_size={text_det_batch_size} will not using! "
  76. )
  77. if layout_batch_size:
  78. self.layout_predictor.set_predictor(batch_size=layout_batch_size)
  79. if text_rec_batch_size:
  80. self.ocr_pipeline.text_rec_model.set_predictor(
  81. batch_size=text_rec_batch_size
  82. )
  83. if table_batch_size:
  84. self.table_predictor.set_predictor(batch_size=table_batch_size)
  85. def predict(self, x):
  86. for layout_pred, ocr_pred in zip(
  87. self.layout_predictor(x), self.ocr_pipeline(x)
  88. ):
  89. single_img_res = {
  90. "input_path": "",
  91. "layout_result": {},
  92. "ocr_result": {},
  93. "table_result": [],
  94. }
  95. # update layout result
  96. single_img_res["input_path"] = layout_pred["input_path"]
  97. single_img_res["layout_result"] = layout_pred
  98. ocr_res = ocr_pred
  99. table_subs = []
  100. if len(layout_pred["boxes"]) > 0:
  101. subs_of_img = list(self._crop_by_boxes(layout_pred))
  102. # get cropped images with label "table"
  103. for sub in subs_of_img:
  104. box = sub["box"]
  105. if sub["label"].lower() == "table":
  106. table_subs.append(sub)
  107. _, ocr_res = self.get_related_ocr_result(box, ocr_res)
  108. table_res, all_table_ocr_res = self.get_table_result(table_subs)
  109. for table_ocr_res in all_table_ocr_res:
  110. ocr_res["dt_polys"].extend(table_ocr_res["dt_polys"])
  111. ocr_res["rec_text"].extend(table_ocr_res["rec_text"])
  112. ocr_res["rec_score"].extend(table_ocr_res["rec_score"])
  113. single_img_res["table_result"] = table_res
  114. single_img_res["ocr_result"] = OCRResult(ocr_res)
  115. yield TableResult(single_img_res)
  116. def get_related_ocr_result(self, box, ocr_res):
  117. dt_polys_list = []
  118. rec_text_list = []
  119. score_list = []
  120. unmatched_ocr_res = {"dt_polys": [], "rec_text": [], "rec_score": []}
  121. unmatched_ocr_res["input_path"] = ocr_res["input_path"]
  122. for i, text_box in enumerate(ocr_res["dt_polys"]):
  123. text_box_area = convert_4point2rect(text_box)
  124. if is_inside(text_box_area, box):
  125. dt_polys_list.append(text_box)
  126. rec_text_list.append(ocr_res["rec_text"][i])
  127. score_list.append(ocr_res["rec_score"][i])
  128. else:
  129. unmatched_ocr_res["dt_polys"].append(text_box)
  130. unmatched_ocr_res["rec_text"].append(ocr_res["rec_text"][i])
  131. unmatched_ocr_res["rec_score"].append(ocr_res["rec_score"][i])
  132. return (dt_polys_list, rec_text_list, score_list), unmatched_ocr_res
  133. def get_table_result(self, input_imgs):
  134. table_res_list = []
  135. ocr_res_list = []
  136. table_index = 0
  137. img_list = [img["img"] for img in input_imgs]
  138. for input_img, table_pred, ocr_pred in zip(
  139. input_imgs, self.table_predictor(img_list), self.ocr_pipeline(img_list)
  140. ):
  141. single_table_box = table_pred["bbox"]
  142. ori_x, ori_y, _, _ = input_img["box"]
  143. ori_bbox_list = np.array(
  144. get_ori_coordinate_for_table(ori_x, ori_y, single_table_box),
  145. dtype=np.float32,
  146. )
  147. ori_ocr_bbox_list = np.array(
  148. get_ori_coordinate_for_table(ori_x, ori_y, ocr_pred["dt_polys"]),
  149. dtype=np.float32,
  150. )
  151. html_res = self._match(table_pred, ocr_pred)
  152. ocr_pred["dt_polys"] = ori_ocr_bbox_list
  153. table_res_list.append(
  154. StructureTableResult(
  155. {
  156. "input_path": input_img["input_path"],
  157. "layout_bbox": [int(x) for x in input_img["box"]],
  158. "bbox": ori_bbox_list,
  159. "img_idx": table_index,
  160. "html": html_res,
  161. }
  162. )
  163. )
  164. ocr_res_list.append(ocr_pred)
  165. table_index += 1
  166. return table_res_list, ocr_res_list