result_v2.py 16 KB

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