result_v2.py 19 KB

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