table_rec.py 6.1 KB

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