result_v2.py 15 KB

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