result_v2.py 20 KB

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