result_v2.py 18 KB

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