result.py 8.5 KB

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