result.py 11 KB

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