table_rec.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 BaseComponent
  16. __all__ = ["TableLabelDecode"]
  17. class TableLabelDecode(BaseComponent):
  18. """decode the table model outputs(probs) to character str"""
  19. ENABLE_BATCH = True
  20. INPUT_KEYS = ["pred", "img_size", "ori_img_size"]
  21. OUTPUT_KEYS = ["bbox", "structure", "structure_score"]
  22. DEAULT_INPUTS = {
  23. "pred": "pred",
  24. "img_size": "img_size",
  25. "ori_img_size": "ori_img_size",
  26. }
  27. DEAULT_OUTPUTS = {
  28. "bbox": "bbox",
  29. "structure": "structure",
  30. "structure_score": "structure_score",
  31. }
  32. def __init__(self, merge_no_span_structure=True, dict_character=[]):
  33. super().__init__()
  34. if merge_no_span_structure:
  35. if "<td></td>" not in dict_character:
  36. dict_character.append("<td></td>")
  37. if "<td>" in dict_character:
  38. dict_character.remove("<td>")
  39. dict_character = self.add_special_char(dict_character)
  40. self.dict = {}
  41. for i, char in enumerate(dict_character):
  42. self.dict[char] = i
  43. self.character = dict_character
  44. self.td_token = ["<td>", "<td", "<td></td>"]
  45. def add_special_char(self, dict_character):
  46. """add_special_char"""
  47. self.beg_str = "sos"
  48. self.end_str = "eos"
  49. dict_character = dict_character
  50. dict_character = [self.beg_str] + dict_character + [self.end_str]
  51. return dict_character
  52. def get_ignored_tokens(self):
  53. """get_ignored_tokens"""
  54. beg_idx = self.get_beg_end_flag_idx("beg")
  55. end_idx = self.get_beg_end_flag_idx("end")
  56. return [beg_idx, end_idx]
  57. def get_beg_end_flag_idx(self, beg_or_end):
  58. """get_beg_end_flag_idx"""
  59. if beg_or_end == "beg":
  60. idx = np.array(self.dict[self.beg_str])
  61. elif beg_or_end == "end":
  62. idx = np.array(self.dict[self.end_str])
  63. else:
  64. assert False, "unsupported type %s in get_beg_end_flag_idx" % beg_or_end
  65. return idx
  66. def apply(self, pred, img_size, ori_img_size):
  67. """apply"""
  68. bbox_preds, structure_probs = [], []
  69. for bbox_pred, stru_prob in pred:
  70. bbox_preds.append(bbox_pred)
  71. structure_probs.append(stru_prob)
  72. bbox_preds = np.array(bbox_preds)
  73. structure_probs = np.array(structure_probs)
  74. bbox_list, structure_str_list, structure_score = self.decode(
  75. structure_probs, bbox_preds, img_size, ori_img_size
  76. )
  77. structure_str_list = [
  78. (
  79. ["<html>", "<body>", "<table>"]
  80. + structure
  81. + ["</table>", "</body>", "</html>"]
  82. )
  83. for structure in structure_str_list
  84. ]
  85. return [
  86. {"bbox": bbox, "structure": structure, "structure_score": structure_score}
  87. for bbox, structure in zip(bbox_list, structure_str_list)
  88. ]
  89. def decode(self, structure_probs, bbox_preds, padding_size, ori_img_size):
  90. """convert text-label into text-index."""
  91. ignored_tokens = self.get_ignored_tokens()
  92. end_idx = self.dict[self.end_str]
  93. structure_idx = structure_probs.argmax(axis=2)
  94. structure_probs = structure_probs.max(axis=2)
  95. structure_batch_list = []
  96. bbox_batch_list = []
  97. batch_size = len(structure_idx)
  98. for batch_idx in range(batch_size):
  99. structure_list = []
  100. bbox_list = []
  101. score_list = []
  102. for idx in range(len(structure_idx[batch_idx])):
  103. char_idx = int(structure_idx[batch_idx][idx])
  104. if idx > 0 and char_idx == end_idx:
  105. break
  106. if char_idx in ignored_tokens:
  107. continue
  108. text = self.character[char_idx]
  109. if text in self.td_token:
  110. bbox = bbox_preds[batch_idx, idx]
  111. bbox = self._bbox_decode(
  112. bbox, padding_size[batch_idx], ori_img_size[batch_idx]
  113. )
  114. bbox_list.append(bbox.astype(int))
  115. structure_list.append(text)
  116. score_list.append(structure_probs[batch_idx, idx])
  117. structure_batch_list.append(structure_list)
  118. structure_score = np.mean(score_list)
  119. bbox_batch_list.append(bbox_list)
  120. return bbox_batch_list, structure_batch_list, structure_score
  121. def decode_label(self, batch):
  122. """convert text-label into text-index."""
  123. structure_idx = batch[1]
  124. gt_bbox_list = batch[2]
  125. shape_list = batch[-1]
  126. ignored_tokens = self.get_ignored_tokens()
  127. end_idx = self.dict[self.end_str]
  128. structure_batch_list = []
  129. bbox_batch_list = []
  130. batch_size = len(structure_idx)
  131. for batch_idx in range(batch_size):
  132. structure_list = []
  133. bbox_list = []
  134. for idx in range(len(structure_idx[batch_idx])):
  135. char_idx = int(structure_idx[batch_idx][idx])
  136. if idx > 0 and char_idx == end_idx:
  137. break
  138. if char_idx in ignored_tokens:
  139. continue
  140. structure_list.append(self.character[char_idx])
  141. bbox = gt_bbox_list[batch_idx][idx]
  142. if bbox.sum() != 0:
  143. bbox = self._bbox_decode(bbox, shape_list[batch_idx])
  144. bbox_list.append(bbox.astype(int))
  145. structure_batch_list.append(structure_list)
  146. bbox_batch_list.append(bbox_list)
  147. return bbox_batch_list, structure_batch_list
  148. def _bbox_decode(self, bbox, padding_shape, ori_shape):
  149. pad_w, pad_h = padding_shape
  150. w, h = ori_shape
  151. ratio_w = pad_w / w
  152. ratio_h = pad_h / h
  153. ratio = min(ratio_w, ratio_h)
  154. bbox[0::2] *= pad_w
  155. bbox[1::2] *= pad_h
  156. bbox[0::2] /= ratio
  157. bbox[1::2] /= ratio
  158. return bbox