result_v2.py 18 KB

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