result_v2.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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. import re
  17. from pathlib import Path
  18. import numpy as np
  19. from PIL import Image, ImageDraw
  20. from ...common.result import (
  21. BaseCVResult,
  22. HtmlMixin,
  23. JsonMixin,
  24. MarkdownMixin,
  25. XlsxMixin,
  26. )
  27. from .utils import get_show_color
  28. class LayoutParsingResultV2(BaseCVResult, HtmlMixin, XlsxMixin, MarkdownMixin):
  29. """Layout Parsing Result V2"""
  30. def __init__(self, data) -> None:
  31. """Initializes a new instance of the class with the specified data."""
  32. super().__init__(data)
  33. HtmlMixin.__init__(self)
  34. XlsxMixin.__init__(self)
  35. MarkdownMixin.__init__(self)
  36. JsonMixin.__init__(self)
  37. self.title_pattern = self._build_title_pattern()
  38. def _build_title_pattern(self):
  39. # Precompiled regex pattern for matching numbering at the beginning of the title
  40. numbering_pattern = (
  41. r"(?:"
  42. + r"[1-9][0-9]*(?:\.[1-9][0-9]*)*[\.、]?|"
  43. + r"[\(\(](?:[1-9][0-9]*|["
  44. r"一二三四五六七八九十百千万亿零壹贰叁肆伍陆柒捌玖拾]+)[\)\)]|" + r"["
  45. r"一二三四五六七八九十百千万亿零壹贰叁肆伍陆柒捌玖拾]+"
  46. r"[、\.]?|" + r"(?:I|II|III|IV|V|VI|VII|VIII|IX|X)\.?" + r")"
  47. )
  48. return re.compile(r"^\s*(" + numbering_pattern + r")(\s*)(.*)$")
  49. def _get_input_fn(self):
  50. fn = super()._get_input_fn()
  51. if (page_idx := self["page_index"]) is not None:
  52. fp = Path(fn)
  53. stem, suffix = fp.stem, fp.suffix
  54. return f"{stem}_{page_idx}{suffix}"
  55. else:
  56. return fn
  57. def _to_img(self) -> dict[str, np.ndarray]:
  58. res_img_dict = {}
  59. model_settings = self["model_settings"]
  60. if model_settings["use_doc_preprocessor"]:
  61. for key, value in self["doc_preprocessor_res"].img.items():
  62. res_img_dict[key] = value
  63. res_img_dict["layout_det_res"] = self["layout_det_res"].img["res"]
  64. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  65. res_img_dict["overall_ocr_res"] = self["overall_ocr_res"].img["ocr_res_img"]
  66. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  67. table_cell_img = Image.fromarray(
  68. copy.deepcopy(self["doc_preprocessor_res"]["output_img"])
  69. )
  70. table_draw = ImageDraw.Draw(table_cell_img)
  71. rectangle_color = (255, 0, 0)
  72. for sno in range(len(self["table_res_list"])):
  73. table_res = self["table_res_list"][sno]
  74. cell_box_list = table_res["cell_box_list"]
  75. for box in cell_box_list:
  76. x1, y1, x2, y2 = [int(pos) for pos in box]
  77. table_draw.rectangle(
  78. [x1, y1, x2, y2], outline=rectangle_color, width=2
  79. )
  80. res_img_dict["table_cell_img"] = table_cell_img
  81. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  82. for sno in range(len(self["seal_res_list"])):
  83. seal_res = self["seal_res_list"][sno]
  84. seal_region_id = seal_res["seal_region_id"]
  85. sub_seal_res_dict = seal_res.img
  86. key = f"seal_res_region{seal_region_id}"
  87. res_img_dict[key] = sub_seal_res_dict["ocr_res_img"]
  88. # for layout ordering image
  89. image = Image.fromarray(self["doc_preprocessor_res"]["output_img"][:, :, ::-1])
  90. draw = ImageDraw.Draw(image, "RGBA")
  91. parsing_result = self["parsing_res_list"]
  92. for block in parsing_result:
  93. bbox = block["block_bbox"]
  94. index = block.get("index", None)
  95. label = block["sub_label"]
  96. fill_color = get_show_color(label)
  97. draw.rectangle(bbox, fill=fill_color)
  98. if index is not None:
  99. text_position = (bbox[2] + 2, bbox[1] - 10)
  100. draw.text(text_position, str(index), fill="red")
  101. res_img_dict["layout_order_res"] = image
  102. return res_img_dict
  103. def _to_str(self, *args, **kwargs) -> dict[str, str]:
  104. """Converts the instance's attributes to a dictionary and then to a string.
  105. Args:
  106. *args: Additional positional arguments passed to the base class method.
  107. **kwargs: Additional keyword arguments passed to the base class method.
  108. Returns:
  109. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  110. """
  111. data = {}
  112. data["input_path"] = self["input_path"]
  113. data["page_index"] = self["page_index"]
  114. model_settings = self["model_settings"]
  115. data["model_settings"] = model_settings
  116. if self["model_settings"]["use_doc_preprocessor"]:
  117. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  118. data["layout_det_res"] = self["layout_det_res"].str["res"]
  119. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  120. data["overall_ocr_res"] = self["overall_ocr_res"].str["res"]
  121. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  122. data["table_res_list"] = []
  123. for sno in range(len(self["table_res_list"])):
  124. table_res = self["table_res_list"][sno]
  125. data["table_res_list"].append(table_res.str["res"])
  126. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  127. data["seal_res_list"] = []
  128. for sno in range(len(self["seal_res_list"])):
  129. seal_res = self["seal_res_list"][sno]
  130. data["seal_res_list"].append(seal_res.str["res"])
  131. if (
  132. model_settings["use_formula_recognition"]
  133. and len(self["formula_res_list"]) > 0
  134. ):
  135. data["formula_res_list"] = []
  136. for sno in range(len(self["formula_res_list"])):
  137. formula_res = self["formula_res_list"][sno]
  138. data["formula_res_list"].append(formula_res.str["res"])
  139. return JsonMixin._to_str(data, *args, **kwargs)
  140. def _to_json(self, *args, **kwargs) -> dict[str, str]:
  141. """
  142. Converts the object's data to a JSON dictionary.
  143. Args:
  144. *args: Positional arguments passed to the JsonMixin._to_json method.
  145. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  146. Returns:
  147. Dict[str, str]: A dictionary containing the object's data in JSON format.
  148. """
  149. data = {}
  150. data["input_path"] = self["input_path"]
  151. data["page_index"] = self["page_index"]
  152. model_settings = self["model_settings"]
  153. data["model_settings"] = model_settings
  154. parsing_res_list = self["parsing_res_list"]
  155. parsing_res_list = [
  156. {
  157. "block_label": parsing_res["block_label"],
  158. "block_content": parsing_res["block_content"],
  159. "block_bbox": parsing_res["block_bbox"],
  160. }
  161. for parsing_res in parsing_res_list
  162. ]
  163. data["parsing_res_list"] = parsing_res_list
  164. if self["model_settings"]["use_doc_preprocessor"]:
  165. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  166. data["layout_det_res"] = self["layout_det_res"].json["res"]
  167. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  168. data["overall_ocr_res"] = self["overall_ocr_res"].json["res"]
  169. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  170. data["table_res_list"] = []
  171. for sno in range(len(self["table_res_list"])):
  172. table_res = self["table_res_list"][sno]
  173. data["table_res_list"].append(table_res.json["res"])
  174. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  175. data["seal_res_list"] = []
  176. for sno in range(len(self["seal_res_list"])):
  177. seal_res = self["seal_res_list"][sno]
  178. data["seal_res_list"].append(seal_res.json["res"])
  179. if (
  180. model_settings["use_formula_recognition"]
  181. and len(self["formula_res_list"]) > 0
  182. ):
  183. data["formula_res_list"] = []
  184. for sno in range(len(self["formula_res_list"])):
  185. formula_res = self["formula_res_list"][sno]
  186. data["formula_res_list"].append(formula_res.json["res"])
  187. return JsonMixin._to_json(data, *args, **kwargs)
  188. def _to_html(self) -> dict[str, str]:
  189. """Converts the prediction to its corresponding HTML representation.
  190. Returns:
  191. Dict[str, str]: The str type HTML representation result.
  192. """
  193. model_settings = self["model_settings"]
  194. res_html_dict = {}
  195. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  196. for sno in range(len(self["table_res_list"])):
  197. table_res = self["table_res_list"][sno]
  198. table_region_id = table_res["table_region_id"]
  199. key = f"table_{table_region_id}"
  200. res_html_dict[key] = table_res.html["pred"]
  201. return res_html_dict
  202. def _to_xlsx(self) -> dict[str, str]:
  203. """Converts the prediction HTML to an XLSX file path.
  204. Returns:
  205. Dict[str, str]: The str type XLSX representation result.
  206. """
  207. model_settings = self["model_settings"]
  208. res_xlsx_dict = {}
  209. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  210. for sno in range(len(self["table_res_list"])):
  211. table_res = self["table_res_list"][sno]
  212. table_region_id = table_res["table_region_id"]
  213. key = f"table_{table_region_id}"
  214. res_xlsx_dict[key] = table_res.xlsx["pred"]
  215. return res_xlsx_dict
  216. def _to_markdown(self) -> dict:
  217. """
  218. Save the parsing result to a Markdown file.
  219. Returns:
  220. Dict
  221. """
  222. def _format_data(obj):
  223. def format_title(title):
  224. """
  225. Normalize chapter title.
  226. Add the '#' to indicate the level of the title.
  227. If numbering exists, ensure there's exactly one space between it and the title content.
  228. If numbering does not exist, return the original title unchanged.
  229. :param title: Original chapter title string.
  230. :return: Normalized chapter title string.
  231. """
  232. match = self.title_pattern.match(title)
  233. if match:
  234. numbering = match.group(1).strip()
  235. title_content = match.group(3).lstrip()
  236. # Return numbering and title content separated by one space
  237. title = numbering + " " + title_content
  238. title = title.rstrip(".")
  239. level = (
  240. title.count(
  241. ".",
  242. )
  243. + 1
  244. if "." in title
  245. else 1
  246. )
  247. return f"#{'#' * level} {title}".replace("-\n", "").replace(
  248. "\n",
  249. " ",
  250. )
  251. def format_centered_text(key):
  252. return (
  253. f'<div style="text-align: center;">{block[key]}</div>'.replace(
  254. "-\n",
  255. "",
  256. ).replace("\n", " ")
  257. + "\n"
  258. )
  259. def format_image(label):
  260. img_tags = []
  261. image_path = "".join(block[label].keys())
  262. img_tags.append(
  263. '<div style="text-align: center;"><img src="{}" alt="Image" /></div>'.format(
  264. image_path.replace("-\n", "").replace("\n", " "),
  265. ),
  266. )
  267. return "\n".join(img_tags)
  268. def format_first_line(templates, format_func, spliter):
  269. lines = block["block_content"].split(spliter)
  270. for idx in range(len(lines)):
  271. line = lines[idx]
  272. if line.strip() == "":
  273. continue
  274. if line.lower() in templates:
  275. lines[idx] = format_func(line)
  276. break
  277. return spliter.join(lines)
  278. def format_table():
  279. return "\n" + block["block_content"]
  280. def get_seg_flag(block, prev_block):
  281. seg_start_flag = True
  282. seg_end_flag = True
  283. block_box = block["block_bbox"]
  284. context_left_coordinate = block_box[0]
  285. context_right_coordinate = block_box[2]
  286. seg_start_coordinate = block.get("seg_start_coordinate")
  287. seg_end_coordinate = block.get("seg_end_coordinate")
  288. if prev_block is not None:
  289. prev_block_bbox = prev_block["block_bbox"]
  290. num_of_prev_lines = prev_block.get("num_of_lines")
  291. pre_block_seg_end_coordinate = prev_block.get("seg_end_coordinate")
  292. prev_end_space_small = (
  293. context_right_coordinate - pre_block_seg_end_coordinate < 10
  294. )
  295. prev_lines_more_than_one = num_of_prev_lines > 1
  296. overlap_blocks = context_left_coordinate < prev_block_bbox[2]
  297. # update context_left_coordinate and context_right_coordinate
  298. if overlap_blocks:
  299. context_left_coordinate = min(
  300. prev_block_bbox[0], context_left_coordinate
  301. )
  302. context_right_coordinate = max(
  303. prev_block_bbox[2], context_right_coordinate
  304. )
  305. prev_end_space_small = (
  306. prev_block_bbox[2] - pre_block_seg_end_coordinate < 10
  307. )
  308. current_start_space_small = (
  309. seg_start_coordinate - context_left_coordinate < 10
  310. )
  311. if (
  312. prev_end_space_small
  313. and current_start_space_small
  314. and prev_lines_more_than_one
  315. ):
  316. seg_start_flag = False
  317. else:
  318. if seg_start_coordinate - context_left_coordinate < 10:
  319. seg_start_flag = False
  320. if context_right_coordinate - seg_end_coordinate < 10:
  321. seg_end_flag = False
  322. return seg_start_flag, seg_end_flag
  323. handlers = {
  324. "paragraph_title": lambda: format_title(block["block_content"]),
  325. "doc_title": lambda: f"# {block['block_content']}".replace(
  326. "-\n",
  327. "",
  328. ).replace("\n", " "),
  329. "table_title": lambda: format_centered_text("block_content"),
  330. "figure_title": lambda: format_centered_text("block_content"),
  331. "chart_title": lambda: format_centered_text("block_content"),
  332. "text": lambda: block["block_content"]
  333. .replace("-\n", " ")
  334. .replace("\n", " "),
  335. "abstract": lambda: format_first_line(
  336. ["摘要", "abstract"], lambda l: f"## {l}\n", " "
  337. ),
  338. "content": lambda: block["block_content"]
  339. .replace("-\n", " \n")
  340. .replace("\n", " \n"),
  341. "image": lambda: format_image("block_image"),
  342. "chart": lambda: format_image("block_image"),
  343. "formula": lambda: f"$${block['block_content']}$$",
  344. "table": format_table,
  345. "reference": lambda: format_first_line(
  346. ["参考文献", "references"], lambda l: f"## {l}", "\n"
  347. ),
  348. "algorithm": lambda: block["block_content"].strip("\n"),
  349. "seal": lambda: f"Words of Seals:\n{block['block_content']}",
  350. }
  351. parsing_res_list = obj["parsing_res_list"]
  352. markdown_content = ""
  353. last_label = None
  354. seg_start_flag = None
  355. seg_end_flag = None
  356. prev_block = None
  357. page_first_element_seg_start_flag = None
  358. page_last_element_seg_end_flag = None
  359. parsing_res_list = sorted(
  360. parsing_res_list,
  361. key=lambda x: x.get("sub_index", 999),
  362. )
  363. for block in parsing_res_list:
  364. seg_start_flag, seg_end_flag = get_seg_flag(block, prev_block)
  365. label = block.get("block_label")
  366. page_first_element_seg_start_flag = (
  367. seg_start_flag
  368. if (page_first_element_seg_start_flag is None)
  369. else page_first_element_seg_start_flag
  370. )
  371. handler = handlers.get(label)
  372. if handler:
  373. prev_block = block
  374. if label == last_label == "text" and seg_start_flag == False:
  375. last_char_of_markdown = (
  376. markdown_content[-1] if markdown_content else ""
  377. )
  378. first_char_of_handler = handler()[0] if handler() else ""
  379. last_is_chinese_char = (
  380. re.match(r"[\u4e00-\u9fff]", last_char_of_markdown)
  381. if last_char_of_markdown
  382. else False
  383. )
  384. first_is_chinese_char = (
  385. re.match(r"[\u4e00-\u9fff]", first_char_of_handler)
  386. if first_char_of_handler
  387. else False
  388. )
  389. if not (last_is_chinese_char or first_is_chinese_char):
  390. markdown_content += " " + handler()
  391. else:
  392. markdown_content += handler()
  393. else:
  394. markdown_content += (
  395. "\n\n" + handler() if markdown_content else handler()
  396. )
  397. last_label = label
  398. page_last_element_seg_end_flag = seg_end_flag
  399. return markdown_content, (
  400. page_first_element_seg_start_flag,
  401. page_last_element_seg_end_flag,
  402. )
  403. markdown_info = dict()
  404. markdown_info["markdown_texts"], (
  405. page_first_element_seg_start_flag,
  406. page_last_element_seg_end_flag,
  407. ) = _format_data(self)
  408. markdown_info["page_continuation_flags"] = (
  409. page_first_element_seg_start_flag,
  410. page_last_element_seg_end_flag,
  411. )
  412. markdown_info["markdown_images"] = {}
  413. for img in self["imgs_in_doc"]:
  414. markdown_info["markdown_images"][img["path"]] = img["img"]
  415. return markdown_info