result_v2.py 18 KB

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