result.py 9.9 KB

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