result_v2.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. from typing import List
  19. import numpy as np
  20. from PIL import Image, ImageDraw
  21. from ...common.result import (
  22. BaseCVResult,
  23. HtmlMixin,
  24. JsonMixin,
  25. MarkdownMixin,
  26. XlsxMixin,
  27. )
  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. from .utils import get_show_color
  59. res_img_dict = {}
  60. model_settings = self["model_settings"]
  61. if model_settings["use_doc_preprocessor"]:
  62. for key, value in self["doc_preprocessor_res"].img.items():
  63. res_img_dict[key] = value
  64. res_img_dict["layout_det_res"] = self["layout_det_res"].img["res"]
  65. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  66. res_img_dict["overall_ocr_res"] = self["overall_ocr_res"].img["ocr_res_img"]
  67. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  68. table_cell_img = Image.fromarray(
  69. copy.deepcopy(self["doc_preprocessor_res"]["output_img"])
  70. )
  71. table_draw = ImageDraw.Draw(table_cell_img)
  72. rectangle_color = (255, 0, 0)
  73. for sno in range(len(self["table_res_list"])):
  74. table_res = self["table_res_list"][sno]
  75. cell_box_list = table_res["cell_box_list"]
  76. for box in cell_box_list:
  77. x1, y1, x2, y2 = [int(pos) for pos in box]
  78. table_draw.rectangle(
  79. [x1, y1, x2, y2], outline=rectangle_color, width=2
  80. )
  81. res_img_dict["table_cell_img"] = table_cell_img
  82. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  83. for sno in range(len(self["seal_res_list"])):
  84. seal_res = self["seal_res_list"][sno]
  85. seal_region_id = seal_res["seal_region_id"]
  86. sub_seal_res_dict = seal_res.img
  87. key = f"seal_res_region{seal_region_id}"
  88. res_img_dict[key] = sub_seal_res_dict["ocr_res_img"]
  89. # for layout ordering image
  90. image = Image.fromarray(self["doc_preprocessor_res"]["output_img"][:, :, ::-1])
  91. draw = ImageDraw.Draw(image, "RGBA")
  92. parsing_result: List[LayoutParsingBlock] = self["parsing_res_list"]
  93. for block in parsing_result:
  94. bbox = block.bbox
  95. index = block.index
  96. label = block.label
  97. fill_color = get_show_color(label)
  98. draw.rectangle(bbox, fill=fill_color)
  99. if index is not None:
  100. text_position = (bbox[2] + 2, bbox[1] - 10)
  101. draw.text(text_position, str(index), fill="red")
  102. res_img_dict["layout_order_res"] = image
  103. return res_img_dict
  104. def _to_str(self, *args, **kwargs) -> dict[str, str]:
  105. """Converts the instance's attributes to a dictionary and then to a string.
  106. Args:
  107. *args: Additional positional arguments passed to the base class method.
  108. **kwargs: Additional keyword arguments passed to the base class method.
  109. Returns:
  110. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  111. """
  112. data = {}
  113. data["input_path"] = self["input_path"]
  114. data["page_index"] = self["page_index"]
  115. model_settings = self["model_settings"]
  116. data["model_settings"] = model_settings
  117. if self["model_settings"]["use_doc_preprocessor"]:
  118. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  119. data["layout_det_res"] = self["layout_det_res"].str["res"]
  120. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  121. data["overall_ocr_res"] = self["overall_ocr_res"].str["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 JsonMixin._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. data["page_index"] = self["page_index"]
  153. model_settings = self["model_settings"]
  154. data["model_settings"] = model_settings
  155. parsing_res_list = self["parsing_res_list"]
  156. parsing_res_list = [
  157. {
  158. "block_label": parsing_res.label,
  159. "block_content": parsing_res.content,
  160. "block_bbox": parsing_res.bbox,
  161. }
  162. for parsing_res in parsing_res_list
  163. ]
  164. data["parsing_res_list"] = parsing_res_list
  165. if self["model_settings"]["use_doc_preprocessor"]:
  166. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  167. data["layout_det_res"] = self["layout_det_res"].json["res"]
  168. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  169. data["overall_ocr_res"] = self["overall_ocr_res"].json["res"]
  170. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  171. data["table_res_list"] = []
  172. for sno in range(len(self["table_res_list"])):
  173. table_res = self["table_res_list"][sno]
  174. data["table_res_list"].append(table_res.json["res"])
  175. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  176. data["seal_res_list"] = []
  177. for sno in range(len(self["seal_res_list"])):
  178. seal_res = self["seal_res_list"][sno]
  179. data["seal_res_list"].append(seal_res.json["res"])
  180. if (
  181. model_settings["use_formula_recognition"]
  182. and len(self["formula_res_list"]) > 0
  183. ):
  184. data["formula_res_list"] = []
  185. for sno in range(len(self["formula_res_list"])):
  186. formula_res = self["formula_res_list"][sno]
  187. data["formula_res_list"].append(formula_res.json["res"])
  188. return JsonMixin._to_json(data, *args, **kwargs)
  189. def _to_html(self) -> dict[str, str]:
  190. """Converts the prediction to its corresponding HTML representation.
  191. Returns:
  192. Dict[str, str]: The str type HTML representation result.
  193. """
  194. model_settings = self["model_settings"]
  195. res_html_dict = {}
  196. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  197. for sno in range(len(self["table_res_list"])):
  198. table_res = self["table_res_list"][sno]
  199. table_region_id = table_res["table_region_id"]
  200. key = f"table_{table_region_id}"
  201. res_html_dict[key] = table_res.html["pred"]
  202. return res_html_dict
  203. def _to_xlsx(self) -> dict[str, str]:
  204. """Converts the prediction HTML to an XLSX file path.
  205. Returns:
  206. Dict[str, str]: The str type XLSX representation result.
  207. """
  208. model_settings = self["model_settings"]
  209. res_xlsx_dict = {}
  210. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  211. for sno in range(len(self["table_res_list"])):
  212. table_res = self["table_res_list"][sno]
  213. table_region_id = table_res["table_region_id"]
  214. key = f"table_{table_region_id}"
  215. res_xlsx_dict[key] = table_res.xlsx["pred"]
  216. return res_xlsx_dict
  217. def _to_markdown(self) -> dict:
  218. """
  219. Save the parsing result to a Markdown file.
  220. Returns:
  221. Dict
  222. """
  223. def _format_data(obj):
  224. def format_title(title):
  225. """
  226. Normalize chapter title.
  227. Add the '#' to indicate the level of the title.
  228. If numbering exists, ensure there's exactly one space between it and the title content.
  229. If numbering does not exist, return the original title unchanged.
  230. :param title: Original chapter title string.
  231. :return: Normalized chapter title string.
  232. """
  233. match = self.title_pattern.match(title)
  234. if match:
  235. numbering = match.group(1).strip()
  236. title_content = match.group(3).lstrip()
  237. # Return numbering and title content separated by one space
  238. title = numbering + " " + title_content
  239. title = title.rstrip(".")
  240. level = (
  241. title.count(
  242. ".",
  243. )
  244. + 1
  245. if "." in title
  246. else 1
  247. )
  248. return f"#{'#' * level} {title}".replace("-\n", "").replace(
  249. "\n",
  250. " ",
  251. )
  252. def format_centered_text():
  253. return (
  254. f'<div style="text-align: center;">{block.content}</div>'.replace(
  255. "-\n",
  256. "",
  257. ).replace("\n", " ")
  258. + "\n"
  259. )
  260. def format_image():
  261. img_tags = []
  262. image_path = "".join(block.image.keys())
  263. img_tags.append(
  264. '<div style="text-align: center;"><img src="{}" alt="Image" /></div>'.format(
  265. image_path.replace("-\n", "").replace("\n", " "),
  266. ),
  267. )
  268. return "\n".join(img_tags)
  269. def format_first_line(templates, format_func, spliter):
  270. lines = block.content.split(spliter)
  271. for idx in range(len(lines)):
  272. line = lines[idx]
  273. if line.strip() == "":
  274. continue
  275. if line.lower() in templates:
  276. lines[idx] = format_func(line)
  277. break
  278. return spliter.join(lines)
  279. def format_table():
  280. return "\n" + block.content
  281. def get_seg_flag(block: LayoutParsingBlock, prev_block: LayoutParsingBlock):
  282. seg_start_flag = True
  283. seg_end_flag = True
  284. block_box = block.bbox
  285. context_left_coordinate = block_box[0]
  286. context_right_coordinate = block_box[2]
  287. seg_start_coordinate = block.seg_start_coordinate
  288. seg_end_coordinate = block.seg_end_coordinate
  289. if prev_block is not None:
  290. prev_block_bbox = prev_block.bbox
  291. num_of_prev_lines = prev_block.num_of_lines
  292. pre_block_seg_end_coordinate = prev_block.seg_end_coordinate
  293. prev_end_space_small = (
  294. context_right_coordinate - pre_block_seg_end_coordinate < 10
  295. )
  296. prev_lines_more_than_one = num_of_prev_lines > 1
  297. overlap_blocks = context_left_coordinate < prev_block_bbox[2]
  298. # update context_left_coordinate and context_right_coordinate
  299. if overlap_blocks:
  300. context_left_coordinate = min(
  301. prev_block_bbox[0], context_left_coordinate
  302. )
  303. context_right_coordinate = max(
  304. prev_block_bbox[2], context_right_coordinate
  305. )
  306. prev_end_space_small = (
  307. prev_block_bbox[2] - pre_block_seg_end_coordinate < 10
  308. )
  309. current_start_space_small = (
  310. seg_start_coordinate - context_left_coordinate < 10
  311. )
  312. if (
  313. prev_end_space_small
  314. and current_start_space_small
  315. and prev_lines_more_than_one
  316. ):
  317. seg_start_flag = False
  318. else:
  319. if seg_start_coordinate - context_left_coordinate < 10:
  320. seg_start_flag = False
  321. if context_right_coordinate - seg_end_coordinate < 10:
  322. seg_end_flag = False
  323. return seg_start_flag, seg_end_flag
  324. handlers = {
  325. "paragraph_title": lambda: format_title(block.content),
  326. "doc_title": lambda: f"# {block.content}".replace(
  327. "-\n",
  328. "",
  329. ).replace("\n", " "),
  330. "table_title": lambda: format_centered_text(),
  331. "figure_title": lambda: format_centered_text(),
  332. "chart_title": lambda: format_centered_text(),
  333. "text": lambda: block.content.replace("-\n", " ").replace("\n", " "),
  334. "abstract": lambda: format_first_line(
  335. ["摘要", "abstract"], lambda l: f"## {l}\n", " "
  336. ),
  337. "content": lambda: block.content.replace("-\n", " \n").replace(
  338. "\n", " \n"
  339. ),
  340. "image": lambda: format_image(),
  341. "chart": lambda: format_image(),
  342. "formula": lambda: f"$${block.content}$$",
  343. "table": format_table,
  344. "reference": lambda: format_first_line(
  345. ["参考文献", "references"], lambda l: f"## {l}", "\n"
  346. ),
  347. "algorithm": lambda: block.content.strip("\n"),
  348. "seal": lambda: f"Words of Seals:\n{block.content}",
  349. }
  350. parsing_res_list = obj["parsing_res_list"]
  351. markdown_content = ""
  352. last_label = None
  353. seg_start_flag = None
  354. seg_end_flag = None
  355. prev_block = None
  356. page_first_element_seg_start_flag = None
  357. page_last_element_seg_end_flag = None
  358. for block in parsing_res_list:
  359. seg_start_flag, seg_end_flag = get_seg_flag(block, prev_block)
  360. label = block.label
  361. page_first_element_seg_start_flag = (
  362. seg_start_flag
  363. if (page_first_element_seg_start_flag is None)
  364. else page_first_element_seg_start_flag
  365. )
  366. handler = handlers.get(label)
  367. if handler:
  368. prev_block = block
  369. if label == last_label == "text" and seg_start_flag == False:
  370. last_char_of_markdown = (
  371. markdown_content[-1] if markdown_content else ""
  372. )
  373. first_char_of_handler = handler()[0] if handler() else ""
  374. last_is_chinese_char = (
  375. re.match(r"[\u4e00-\u9fff]", last_char_of_markdown)
  376. if last_char_of_markdown
  377. else False
  378. )
  379. first_is_chinese_char = (
  380. re.match(r"[\u4e00-\u9fff]", first_char_of_handler)
  381. if first_char_of_handler
  382. else False
  383. )
  384. if not (last_is_chinese_char or first_is_chinese_char):
  385. markdown_content += " " + handler()
  386. else:
  387. markdown_content += handler()
  388. else:
  389. markdown_content += (
  390. "\n\n" + handler() if markdown_content else handler()
  391. )
  392. last_label = label
  393. page_last_element_seg_end_flag = seg_end_flag
  394. return markdown_content, (
  395. page_first_element_seg_start_flag,
  396. page_last_element_seg_end_flag,
  397. )
  398. markdown_info = dict()
  399. markdown_info["markdown_texts"], (
  400. page_first_element_seg_start_flag,
  401. page_last_element_seg_end_flag,
  402. ) = _format_data(self)
  403. markdown_info["page_continuation_flags"] = (
  404. page_first_element_seg_start_flag,
  405. page_last_element_seg_end_flag,
  406. )
  407. markdown_info["markdown_images"] = {}
  408. for img in self["imgs_in_doc"]:
  409. markdown_info["markdown_images"][img["path"]] = img["img"]
  410. return markdown_info
  411. class LayoutParsingBlock:
  412. def __init__(self, label, bbox, content="") -> None:
  413. self.label = label
  414. self.region_label = "other"
  415. self.bbox = [int(item) for item in bbox]
  416. self.content = content
  417. self.seg_start_coordinate = float("inf")
  418. self.seg_end_coordinate = float("-inf")
  419. self.width = bbox[2] - bbox[0]
  420. self.height = bbox[3] - bbox[1]
  421. self.area = self.width * self.height
  422. self.num_of_lines = 1
  423. self.image = None
  424. self.index = None
  425. self.visual_index = None
  426. self.direction = self.get_bbox_direction()
  427. self.child_blocks = []
  428. self.update_direction_info()
  429. def __str__(self) -> str:
  430. return f"{self.__dict__}"
  431. def __repr__(self) -> str:
  432. _str = f"\n\n#################\nlabel:\t{self.label}\nregion_label:\t{self.region_label}\nbbox:\t{self.bbox}\ncontent:\t{self.content}\n#################"
  433. return _str
  434. def to_dict(self) -> dict:
  435. return self.__dict__
  436. def update_direction_info(self) -> None:
  437. if self.region_label == "vision":
  438. self.direction = "horizontal"
  439. if self.direction == "horizontal":
  440. self.secondary_direction = "vertical"
  441. self.short_side_length = self.height
  442. self.long_side_length = self.width
  443. self.start_coordinate = self.bbox[0]
  444. self.end_coordinate = self.bbox[2]
  445. self.secondary_direction_start_coordinate = self.bbox[1]
  446. self.secondary_direction_end_coordinate = self.bbox[3]
  447. else:
  448. self.secondary_direction = "horizontal"
  449. self.short_side_length = self.width
  450. self.long_side_length = self.height
  451. self.start_coordinate = self.bbox[1]
  452. self.end_coordinate = self.bbox[3]
  453. self.secondary_direction_start_coordinate = self.bbox[0]
  454. self.secondary_direction_end_coordinate = self.bbox[2]
  455. def append_child_block(self, child_block: LayoutParsingBlock) -> None:
  456. if not self.child_blocks:
  457. self.ori_bbox = self.bbox.copy()
  458. x1, y1, x2, y2 = self.bbox
  459. x1_child, y1_child, x2_child, y2_child = child_block.bbox
  460. union_bbox = (
  461. min(x1, x1_child),
  462. min(y1, y1_child),
  463. max(x2, x2_child),
  464. max(y2, y2_child),
  465. )
  466. self.bbox = union_bbox
  467. self.update_direction_info()
  468. child_blocks = [child_block]
  469. if child_block.child_blocks:
  470. child_blocks.extend(child_block.get_child_blocks())
  471. self.child_blocks.extend(child_blocks)
  472. def get_child_blocks(self) -> list:
  473. self.bbox = self.ori_bbox
  474. child_blocks = self.child_blocks.copy()
  475. self.child_blocks = []
  476. return child_blocks
  477. def get_centroid(self) -> tuple:
  478. x1, y1, x2, y2 = self.bbox
  479. centroid = ((x1 + x2) / 2, (y1 + y2) / 2)
  480. return centroid
  481. def get_bbox_direction(self, orientation_ratio: float = 1.0) -> bool:
  482. """
  483. Determine if a bounding box is horizontal or vertical.
  484. Args:
  485. bbox (List[float]): Bounding box [x_min, y_min, x_max, y_max].
  486. orientation_ratio (float): Ratio for determining orientation. Default is 1.0.
  487. Returns:
  488. str: "horizontal" or "vertical".
  489. """
  490. return (
  491. "horizontal"
  492. if self.width * orientation_ratio >= self.height
  493. else "vertical"
  494. )