processors.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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.benchmark import benchmark
  16. from ..common.vision import funcs as F
  17. @benchmark.timeit
  18. class Pad:
  19. """Pad the image."""
  20. def __init__(self, target_size, val=127.5):
  21. """
  22. Initialize the instance.
  23. Args:
  24. target_size (list|tuple|int): Target width and height of the image after
  25. padding.
  26. val (float, optional): Value to fill the padded area. Default: 127.5.
  27. """
  28. super().__init__()
  29. if isinstance(target_size, int):
  30. target_size = [target_size, target_size]
  31. self.target_size = target_size
  32. self.val = val
  33. def apply(self, img):
  34. """apply"""
  35. h, w = img.shape[:2]
  36. tw, th = self.target_size
  37. ph = th - h
  38. pw = tw - w
  39. if ph < 0 or pw < 0:
  40. raise ValueError(
  41. f"Input image ({w}, {h}) smaller than the target size ({tw}, {th})."
  42. )
  43. else:
  44. img = F.pad(img, pad=(0, ph, 0, pw), val=self.val)
  45. return [img, [img.shape[1], img.shape[0]]]
  46. def __call__(self, imgs):
  47. """apply"""
  48. return [self.apply(img) for img in imgs]
  49. @benchmark.timeit
  50. class TableLabelDecode:
  51. """decode the table model outputs(probs) to character str"""
  52. ENABLE_BATCH = True
  53. INPUT_KEYS = ["pred", "img_size", "ori_img_size"]
  54. OUTPUT_KEYS = ["bbox", "structure", "structure_score"]
  55. DEAULT_INPUTS = {
  56. "pred": "pred",
  57. "img_size": "img_size",
  58. "ori_img_size": "ori_img_size",
  59. }
  60. DEAULT_OUTPUTS = {
  61. "bbox": "bbox",
  62. "structure": "structure",
  63. "structure_score": "structure_score",
  64. }
  65. def __init__(self, model_name, merge_no_span_structure=True, dict_character=[]):
  66. super().__init__()
  67. if merge_no_span_structure:
  68. if "<td></td>" not in dict_character:
  69. dict_character.append("<td></td>")
  70. if "<td>" in dict_character:
  71. dict_character.remove("<td>")
  72. self.model_name = model_name
  73. dict_character = self.add_special_char(dict_character)
  74. self.dict = {}
  75. for i, char in enumerate(dict_character):
  76. self.dict[char] = i
  77. self.character = dict_character
  78. self.td_token = ["<td>", "<td", "<td></td>"]
  79. def add_special_char(self, dict_character):
  80. """add_special_char"""
  81. self.beg_str = "sos"
  82. self.end_str = "eos"
  83. dict_character = dict_character
  84. dict_character = [self.beg_str] + dict_character + [self.end_str]
  85. return dict_character
  86. def get_ignored_tokens(self):
  87. """get_ignored_tokens"""
  88. beg_idx = self.get_beg_end_flag_idx("beg")
  89. end_idx = self.get_beg_end_flag_idx("end")
  90. return [beg_idx, end_idx]
  91. def get_beg_end_flag_idx(self, beg_or_end):
  92. """get_beg_end_flag_idx"""
  93. if beg_or_end == "beg":
  94. idx = np.array(self.dict[self.beg_str])
  95. elif beg_or_end == "end":
  96. idx = np.array(self.dict[self.end_str])
  97. else:
  98. assert False, "unsupported type %s in get_beg_end_flag_idx" % beg_or_end
  99. return idx
  100. def __call__(self, pred, img_size, ori_img_size):
  101. """apply"""
  102. bbox_preds = np.array([list(pred[0][0])])
  103. structure_probs = np.array([list(pred[1][0])])
  104. bbox_list, structure_str_list, structure_score = self.decode(
  105. structure_probs, bbox_preds, img_size, ori_img_size
  106. )
  107. structure_str_list = [
  108. (
  109. ["<html>", "<body>", "<table>"]
  110. + structure
  111. + ["</table>", "</body>", "</html>"]
  112. )
  113. for structure in structure_str_list
  114. ]
  115. return [
  116. {"bbox": bbox, "structure": structure, "structure_score": structure_score}
  117. for bbox, structure in zip(bbox_list, structure_str_list)
  118. ]
  119. def decode(self, structure_probs, bbox_preds, padding_size, ori_img_size):
  120. """convert text-label into text-index."""
  121. ignored_tokens = self.get_ignored_tokens()
  122. end_idx = self.dict[self.end_str]
  123. structure_idx = structure_probs.argmax(axis=2)
  124. structure_probs = structure_probs.max(axis=2)
  125. structure_batch_list = []
  126. bbox_batch_list = []
  127. batch_size = len(structure_idx)
  128. bbox_list = []
  129. scale_list = []
  130. scales = [0] * 8
  131. for batch_idx in range(batch_size):
  132. structure_list = []
  133. score_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. text = self.character[char_idx]
  141. if text in self.td_token:
  142. bbox = bbox_preds[batch_idx, idx]
  143. h_scale, w_scale = self._get_bbox_scales(
  144. padding_size[batch_idx], ori_img_size[batch_idx]
  145. )
  146. scales[0::2] = [h_scale] * 4
  147. scales[1::2] = [w_scale] * 4
  148. bbox_list.append(bbox)
  149. scale_list.append(scales)
  150. structure_list.append(text)
  151. score_list.append(structure_probs[batch_idx, idx])
  152. structure_batch_list.append(structure_list)
  153. structure_score = np.mean(score_list)
  154. bbox_batch_array = np.multiply(np.array(bbox_list), np.array(scale_list))
  155. bbox_batch_list = [bbox_batch_array.astype(int).tolist()]
  156. return bbox_batch_list, structure_batch_list, structure_score
  157. def decode_label(self, batch):
  158. """convert text-label into text-index."""
  159. structure_idx = batch[1]
  160. gt_bbox_list = batch[2]
  161. shape_list = batch[-1]
  162. ignored_tokens = self.get_ignored_tokens()
  163. end_idx = self.dict[self.end_str]
  164. structure_batch_list = []
  165. bbox_batch_list = []
  166. batch_size = len(structure_idx)
  167. for batch_idx in range(batch_size):
  168. structure_list = []
  169. bbox_list = []
  170. for idx in range(len(structure_idx[batch_idx])):
  171. char_idx = int(structure_idx[batch_idx][idx])
  172. if idx > 0 and char_idx == end_idx:
  173. break
  174. if char_idx in ignored_tokens:
  175. continue
  176. structure_list.append(self.character[char_idx])
  177. bbox = gt_bbox_list[batch_idx][idx]
  178. if bbox.sum() != 0:
  179. bbox = self._bbox_decode(bbox, shape_list[batch_idx])
  180. bbox_list.append(bbox.astype(int))
  181. structure_batch_list.append(structure_list)
  182. bbox_batch_list.append(bbox_list)
  183. return bbox_batch_list, structure_batch_list
  184. def _get_bbox_scales(self, padding_shape, ori_shape):
  185. if self.model_name == "SLANet":
  186. w, h = ori_shape
  187. return w, h
  188. else:
  189. w, h = padding_shape
  190. ori_w, ori_h = ori_shape
  191. ratio_w = w / ori_w
  192. ratio_h = h / ori_h
  193. ratio = min(ratio_w, ratio_h)
  194. return w / ratio, h / ratio