result_v2.py 19 KB

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