result.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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 copy
  15. from pathlib import Path
  16. from typing import Dict
  17. import numpy as np
  18. from PIL import Image, ImageDraw
  19. from ...common.result import BaseCVResult, HtmlMixin, JsonMixin, XlsxMixin
  20. class SingleTableRecognitionResult(BaseCVResult, HtmlMixin, XlsxMixin):
  21. """single table recognition result"""
  22. def __init__(self, data: Dict) -> None:
  23. super().__init__(data)
  24. HtmlMixin.__init__(self)
  25. XlsxMixin.__init__(self)
  26. def _get_input_fn(self):
  27. fn = super()._get_input_fn()
  28. if (page_idx := self["page_index"]) is not None:
  29. fp = Path(fn)
  30. stem, suffix = fp.stem, fp.suffix
  31. return f"{stem}_{page_idx}{suffix}"
  32. else:
  33. return fn
  34. def _to_html(self) -> Dict[str, str]:
  35. """Converts the prediction to its corresponding HTML representation.
  36. Returns:
  37. Dict[str, str]: The str type HTML representation result.
  38. """
  39. return {"pred": self["pred_html"]}
  40. def _to_xlsx(self) -> Dict[str, str]:
  41. """Converts the prediction HTML to an XLSX file path.
  42. Returns:
  43. str: The path to the XLSX file containing the prediction data.
  44. """
  45. return {"pred": self["pred_html"]}
  46. def _to_str(self, *args, **kwargs) -> Dict[str, str]:
  47. """Converts the instance's attributes to a dictionary and then to a string.
  48. Args:
  49. *args: Additional positional arguments passed to the base class method.
  50. **kwargs: Additional keyword arguments passed to the base class method.
  51. Returns:
  52. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  53. """
  54. data = {}
  55. data["cell_box_list"] = self["cell_box_list"]
  56. data["pred_html"] = self["pred_html"]
  57. data["table_ocr_pred"] = self["table_ocr_pred"]
  58. return JsonMixin._to_str(data, *args, **kwargs)
  59. def _to_json(self, *args, **kwargs) -> Dict[str, str]:
  60. """
  61. Converts the object's data to a JSON dictionary.
  62. Args:
  63. *args: Positional arguments passed to the JsonMixin._to_json method.
  64. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  65. Returns:
  66. Dict[str, str]: A dictionary containing the object's data in JSON format.
  67. """
  68. data = {}
  69. data["cell_box_list"] = self["cell_box_list"]
  70. data["pred_html"] = self["pred_html"]
  71. data["table_ocr_pred"] = self["table_ocr_pred"]
  72. return JsonMixin._to_json(data, *args, **kwargs)
  73. class TableRecognitionResult(BaseCVResult, HtmlMixin, XlsxMixin):
  74. """Table Recognition Result"""
  75. def __init__(self, data: Dict) -> None:
  76. super().__init__(data)
  77. HtmlMixin.__init__(self)
  78. XlsxMixin.__init__(self)
  79. if self["layout_det_res"] is None:
  80. self["layout_det_res"] = {}
  81. def _get_input_fn(self):
  82. fn = super()._get_input_fn()
  83. if (page_idx := self["page_index"]) is not None:
  84. fp = Path(fn)
  85. stem, suffix = fp.stem, fp.suffix
  86. return f"{stem}_{page_idx}{suffix}"
  87. else:
  88. return fn
  89. def _to_img(self) -> Dict[str, np.ndarray]:
  90. res_img_dict = {}
  91. layout_det_res = self["layout_det_res"]
  92. if len(layout_det_res) > 0:
  93. res_img_dict["layout_det_res"] = layout_det_res.img["res"]
  94. model_settings = self["model_settings"]
  95. if model_settings["use_doc_preprocessor"]:
  96. res_img_dict.update(**self["doc_preprocessor_res"].img)
  97. res_img_dict.update(**self["overall_ocr_res"].img)
  98. if len(self["table_res_list"]) > 0:
  99. table_cell_img = Image.fromarray(
  100. copy.deepcopy(self["doc_preprocessor_res"]["output_img"][:, :, ::-1])
  101. )
  102. table_draw = ImageDraw.Draw(table_cell_img)
  103. rectangle_color = (255, 0, 0)
  104. for sno in range(len(self["table_res_list"])):
  105. table_res = self["table_res_list"][sno]
  106. cell_box_list = table_res["cell_box_list"]
  107. for box in cell_box_list:
  108. x1, y1, x2, y2 = [int(pos) for pos in box]
  109. table_draw.rectangle(
  110. [x1, y1, x2, y2], outline=rectangle_color, width=2
  111. )
  112. res_img_dict["table_cell_img"] = table_cell_img
  113. return res_img_dict
  114. def _to_str(self, *args, **kwargs) -> Dict[str, str]:
  115. """Converts the instance's attributes to a dictionary and then to a string.
  116. Args:
  117. *args: Additional positional arguments passed to the base class method.
  118. **kwargs: Additional keyword arguments passed to the base class method.
  119. Returns:
  120. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  121. """
  122. data = {}
  123. data["input_path"] = self["input_path"]
  124. data["page_index"] = self["page_index"]
  125. data["model_settings"] = self["model_settings"]
  126. if self["model_settings"]["use_doc_preprocessor"]:
  127. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  128. if len(self["layout_det_res"]) > 0:
  129. data["layout_det_res"] = self["layout_det_res"].str["res"]
  130. data["overall_ocr_res"] = self["overall_ocr_res"].str["res"]
  131. data["table_res_list"] = []
  132. for sno in range(len(self["table_res_list"])):
  133. table_res = self["table_res_list"][sno]
  134. data["table_res_list"].append(table_res.str["res"])
  135. return JsonMixin._to_str(data, *args, **kwargs)
  136. def _to_json(self, *args, **kwargs) -> Dict[str, str]:
  137. """
  138. Converts the object's data to a JSON dictionary.
  139. Args:
  140. *args: Positional arguments passed to the JsonMixin._to_json method.
  141. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  142. Returns:
  143. Dict[str, str]: A dictionary containing the object's data in JSON format.
  144. """
  145. data = {}
  146. data["input_path"] = self["input_path"]
  147. data["page_index"] = self["page_index"]
  148. data["model_settings"] = self["model_settings"]
  149. if self["model_settings"]["use_doc_preprocessor"]:
  150. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  151. if len(self["layout_det_res"]) > 0:
  152. data["layout_det_res"] = self["layout_det_res"].json["res"]
  153. data["overall_ocr_res"] = self["overall_ocr_res"].json["res"]
  154. data["table_res_list"] = []
  155. for sno in range(len(self["table_res_list"])):
  156. table_res = self["table_res_list"][sno]
  157. data["table_res_list"].append(table_res.json["res"])
  158. return JsonMixin._to_json(data, *args, **kwargs)
  159. def _to_html(self) -> Dict[str, str]:
  160. """Converts the prediction to its corresponding HTML representation.
  161. Returns:
  162. Dict[str, str]: The str type HTML representation result.
  163. """
  164. res_html_dict = {}
  165. for sno in range(len(self["table_res_list"])):
  166. table_res = self["table_res_list"][sno]
  167. table_region_id = table_res["table_region_id"]
  168. key = f"table_{table_region_id}"
  169. res_html_dict[key] = table_res.html["pred"]
  170. res_html_dict[key] = res_html_dict[key].replace(
  171. "<table>", '<table border="1">'
  172. )
  173. return res_html_dict
  174. def _to_xlsx(self) -> Dict[str, str]:
  175. """Converts the prediction HTML to an XLSX file path.
  176. Returns:
  177. Dict[str, str]: The str type XLSX representation result.
  178. """
  179. res_xlsx_dict = {}
  180. for sno in range(len(self["table_res_list"])):
  181. table_res = self["table_res_list"][sno]
  182. table_region_id = table_res["table_region_id"]
  183. key = f"table_{table_region_id}"
  184. res_xlsx_dict[key] = table_res.xlsx["pred"]
  185. return res_xlsx_dict