result_v2.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 __future__ import annotations
  15. import copy
  16. from pathlib import Path
  17. from PIL import Image, ImageDraw
  18. import re
  19. import numpy as np
  20. from PIL import Image
  21. from PIL import ImageDraw
  22. from ...common.result import (
  23. BaseCVResult,
  24. HtmlMixin,
  25. JsonMixin,
  26. MarkdownMixin,
  27. XlsxMixin,
  28. )
  29. from .utils import get_layout_ordering
  30. from .utils import recursive_img_array2path
  31. from .utils import get_show_color
  32. class LayoutParsingResultV2(BaseCVResult, HtmlMixin, XlsxMixin, MarkdownMixin):
  33. """Layout Parsing Result V2"""
  34. def __init__(self, data) -> None:
  35. """Initializes a new instance of the class with the specified data."""
  36. super().__init__(data)
  37. HtmlMixin.__init__(self)
  38. XlsxMixin.__init__(self)
  39. MarkdownMixin.__init__(self)
  40. JsonMixin.__init__(self)
  41. def _get_input_fn(self):
  42. fn = super()._get_input_fn()
  43. if (page_idx := self["page_index"]) is not None:
  44. fp = Path(fn)
  45. stem, suffix = fp.stem, fp.suffix
  46. return f"{stem}_{page_idx}{suffix}"
  47. else:
  48. return fn
  49. def _to_img(self) -> dict[str, np.ndarray]:
  50. res_img_dict = {}
  51. model_settings = self["model_settings"]
  52. if model_settings["use_doc_preprocessor"]:
  53. for key, value in self["doc_preprocessor_res"].img.items():
  54. res_img_dict[key] = value
  55. res_img_dict["layout_det_res"] = self["layout_det_res"].img["res"]
  56. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  57. res_img_dict["overall_ocr_res"] = self["overall_ocr_res"].img["ocr_res_img"]
  58. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  59. table_cell_img = Image.fromarray(
  60. copy.deepcopy(self["doc_preprocessor_res"]["output_img"])
  61. )
  62. table_draw = ImageDraw.Draw(table_cell_img)
  63. rectangle_color = (255, 0, 0)
  64. for sno in range(len(self["table_res_list"])):
  65. table_res = self["table_res_list"][sno]
  66. cell_box_list = table_res["cell_box_list"]
  67. for box in cell_box_list:
  68. x1, y1, x2, y2 = [int(pos) for pos in box]
  69. table_draw.rectangle(
  70. [x1, y1, x2, y2], outline=rectangle_color, width=2
  71. )
  72. res_img_dict["table_cell_img"] = table_cell_img
  73. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  74. for sno in range(len(self["seal_res_list"])):
  75. seal_res = self["seal_res_list"][sno]
  76. seal_region_id = seal_res["seal_region_id"]
  77. sub_seal_res_dict = seal_res.img
  78. key = f"seal_res_region{seal_region_id}"
  79. res_img_dict[key] = sub_seal_res_dict["ocr_res_img"]
  80. # for layout ordering image
  81. image = Image.fromarray(self["doc_preprocessor_res"]["output_img"])
  82. draw = ImageDraw.Draw(image, "RGBA")
  83. parsing_result = self["parsing_res_list"]
  84. for block in parsing_result:
  85. bbox = block["block_bbox"]
  86. index = block.get("index", None)
  87. label = block["sub_label"]
  88. fill_color = get_show_color(label)
  89. draw.rectangle(bbox, fill=fill_color)
  90. if index is not None:
  91. text_position = (bbox[2] + 2, bbox[1] - 10)
  92. draw.text(text_position, str(index), fill="red")
  93. res_img_dict["layout_order_res"] = image
  94. return res_img_dict
  95. def _to_str(self, *args, **kwargs) -> dict[str, str]:
  96. """Converts the instance's attributes to a dictionary and then to a string.
  97. Args:
  98. *args: Additional positional arguments passed to the base class method.
  99. **kwargs: Additional keyword arguments passed to the base class method.
  100. Returns:
  101. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  102. """
  103. data = {}
  104. data["input_path"] = self["input_path"]
  105. data["page_index"] = self["page_index"]
  106. model_settings = self["model_settings"]
  107. data["model_settings"] = model_settings
  108. if self["model_settings"]["use_doc_preprocessor"]:
  109. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  110. data["layout_det_res"] = self["layout_det_res"].str["res"]
  111. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  112. data["overall_ocr_res"] = self["overall_ocr_res"].str["res"]
  113. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  114. data["table_res_list"] = []
  115. for sno in range(len(self["table_res_list"])):
  116. table_res = self["table_res_list"][sno]
  117. data["table_res_list"].append(table_res.str["res"])
  118. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  119. data["seal_res_list"] = []
  120. for sno in range(len(self["seal_res_list"])):
  121. seal_res = self["seal_res_list"][sno]
  122. data["seal_res_list"].append(seal_res.str["res"])
  123. if (
  124. model_settings["use_formula_recognition"]
  125. and len(self["formula_res_list"]) > 0
  126. ):
  127. data["formula_res_list"] = []
  128. for sno in range(len(self["formula_res_list"])):
  129. formula_res = self["formula_res_list"][sno]
  130. data["formula_res_list"].append(formula_res.str["res"])
  131. return JsonMixin._to_str(data, *args, **kwargs)
  132. def _to_json(self, *args, **kwargs) -> dict[str, str]:
  133. """
  134. Converts the object's data to a JSON dictionary.
  135. Args:
  136. *args: Positional arguments passed to the JsonMixin._to_json method.
  137. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  138. Returns:
  139. Dict[str, str]: A dictionary containing the object's data in JSON format.
  140. """
  141. data = {}
  142. data["input_path"] = self["input_path"]
  143. data["page_index"] = self["page_index"]
  144. model_settings = self["model_settings"]
  145. data["model_settings"] = model_settings
  146. parsing_res_list = self["parsing_res_list"]
  147. parsing_res_list = [
  148. {
  149. "block_label": parsing_res["block_label"],
  150. "block_content": parsing_res["block_content"],
  151. "block_bbox": parsing_res["block_bbox"],
  152. }
  153. for parsing_res in parsing_res_list
  154. ]
  155. data["parsing_res_list"] = parsing_res_list
  156. if self["model_settings"]["use_doc_preprocessor"]:
  157. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  158. data["layout_det_res"] = self["layout_det_res"].json["res"]
  159. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  160. data["overall_ocr_res"] = self["overall_ocr_res"].json["res"]
  161. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  162. data["table_res_list"] = []
  163. for sno in range(len(self["table_res_list"])):
  164. table_res = self["table_res_list"][sno]
  165. data["table_res_list"].append(table_res.json["res"])
  166. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  167. data["seal_res_list"] = []
  168. for sno in range(len(self["seal_res_list"])):
  169. seal_res = self["seal_res_list"][sno]
  170. data["seal_res_list"].append(seal_res.json["res"])
  171. if (
  172. model_settings["use_formula_recognition"]
  173. and len(self["formula_res_list"]) > 0
  174. ):
  175. data["formula_res_list"] = []
  176. for sno in range(len(self["formula_res_list"])):
  177. formula_res = self["formula_res_list"][sno]
  178. data["formula_res_list"].append(formula_res.json["res"])
  179. return JsonMixin._to_json(data, *args, **kwargs)
  180. def _to_html(self) -> dict[str, str]:
  181. """Converts the prediction to its corresponding HTML representation.
  182. Returns:
  183. Dict[str, str]: The str type HTML representation result.
  184. """
  185. model_settings = self["model_settings"]
  186. res_html_dict = {}
  187. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  188. for sno in range(len(self["table_res_list"])):
  189. table_res = self["table_res_list"][sno]
  190. table_region_id = table_res["table_region_id"]
  191. key = f"table_{table_region_id}"
  192. res_html_dict[key] = table_res.html["pred"]
  193. return res_html_dict
  194. def _to_xlsx(self) -> dict[str, str]:
  195. """Converts the prediction HTML to an XLSX file path.
  196. Returns:
  197. Dict[str, str]: The str type XLSX representation result.
  198. """
  199. model_settings = self["model_settings"]
  200. res_xlsx_dict = {}
  201. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  202. for sno in range(len(self["table_res_list"])):
  203. table_res = self["table_res_list"][sno]
  204. table_region_id = table_res["table_region_id"]
  205. key = f"table_{table_region_id}"
  206. res_xlsx_dict[key] = table_res.xlsx["pred"]
  207. return res_xlsx_dict
  208. def _to_markdown(self) -> dict:
  209. """
  210. Save the parsing result to a Markdown file.
  211. Returns:
  212. Dict
  213. """
  214. recursive_img_array2path(self["parsing_res_list"], labels=["block_image"])
  215. def _format_data(obj):
  216. def format_title(content_value):
  217. content_value = content_value.rstrip(".")
  218. level = (
  219. content_value.count(
  220. ".",
  221. )
  222. + 1
  223. if "." in content_value
  224. else 1
  225. )
  226. return f"{'#' * level} {content_value}".replace("-\n", "").replace(
  227. "\n",
  228. " ",
  229. )
  230. def format_centered_text(key):
  231. return (
  232. f'<div style="text-align: center;">{block[key]}</div>'.replace(
  233. "-\n",
  234. "",
  235. ).replace("\n", " ")
  236. + "\n"
  237. )
  238. def format_image(label):
  239. img_tags = []
  240. image_path = "".join(block[label].keys())
  241. img_tags.append(
  242. '<div style="text-align: center;"><img src="{}" alt="Image" /></div>'.format(
  243. image_path.replace("-\n", "").replace("\n", " "),
  244. ),
  245. )
  246. return "\n".join(img_tags)
  247. def format_reference():
  248. pattern = r"\s*\[\s*\d+\s*\]\s*"
  249. res = re.sub(
  250. pattern,
  251. lambda match: "\n" + match.group(),
  252. block["reference"].replace("\n", ""),
  253. )
  254. return "\n" + res
  255. def format_table():
  256. return "\n" + block["block_content"]
  257. handlers = {
  258. "paragraph_title": lambda: format_title(block["block_content"]),
  259. "doc_title": lambda: f"# {block['block_content']}".replace(
  260. "-\n",
  261. "",
  262. ).replace("\n", " "),
  263. "table_title": lambda: format_centered_text("block_content"),
  264. "figure_title": lambda: format_centered_text("block_content"),
  265. "chart_title": lambda: format_centered_text("block_content"),
  266. "text": lambda: block["block_content"]
  267. .replace("-\n", " ")
  268. .replace("\n", " "),
  269. "abstract": lambda: block["block_content"]
  270. .replace("-\n", " ")
  271. .replace("\n", " "),
  272. "content": lambda: block["block_content"]
  273. .replace("-\n", " ")
  274. .replace("\n", " "),
  275. "image": lambda: format_image("block_image"),
  276. "chart": lambda: format_image("block_image"),
  277. "formula": lambda: f"$${block['block_content']}$$",
  278. "table": format_table,
  279. "reference": lambda: block["block_content"],
  280. "algorithm": lambda: block["block_content"].strip("\n"),
  281. "seal": lambda: format_image("block_content"),
  282. }
  283. parsing_res_list = obj["parsing_res_list"]
  284. markdown_content = ""
  285. last_label = None
  286. seg_start_flag = None
  287. seg_end_flag = None
  288. for block in sorted(
  289. parsing_res_list,
  290. key=lambda x: x.get("sub_index", 999),
  291. ):
  292. label = block.get("block_label")
  293. seg_start_flag = block.get("seg_start_flag")
  294. handler = handlers.get(label)
  295. if handler:
  296. if (
  297. label == last_label == "text"
  298. and seg_start_flag == seg_end_flag == False
  299. ):
  300. markdown_content += " " + handler()
  301. else:
  302. markdown_content += "\n\n" + handler()
  303. last_label = label
  304. seg_end_flag = block.get("seg_end_flag")
  305. return markdown_content
  306. markdown_info = dict()
  307. markdown_info["markdown_texts"] = _format_data(self)
  308. markdown_info["markdown_images"] = dict()
  309. for block in self["parsing_res_list"]:
  310. if block["block_label"] in ["image", "chart"]:
  311. image_path, image_value = next(iter(block["block_image"].items()))
  312. markdown_info["markdown_images"][image_path] = image_value
  313. return markdown_info