result_v2.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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
  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. if block.image:
  94. image_path = block.image["path"]
  95. img_tags.append(
  96. "![]({})".format(image_path.replace("-\n", "").replace("\n", " "))
  97. )
  98. return "\n".join(img_tags)
  99. return ""
  100. def format_chart2table_func(block):
  101. lines_list = block.content.split("\n")
  102. column_num = len(lines_list[0].split("|"))
  103. lines_list.insert(1, "|".join(["---"] * column_num))
  104. lines_list = [f"|{line}|" for line in lines_list]
  105. return "\n".join(lines_list)
  106. def simplify_table_func(table_code):
  107. return "\n" + table_code.replace("<html>", "").replace("</html>", "").replace(
  108. "<body>", ""
  109. ).replace("</body>", "")
  110. def format_first_line_func(block, templates, format_func, spliter):
  111. lines = block.content.split(spliter)
  112. for idx in range(len(lines)):
  113. line = lines[idx]
  114. if line.strip() == "":
  115. continue
  116. if line.lower() in templates:
  117. lines[idx] = format_func(line)
  118. break
  119. return spliter.join(lines)
  120. class LayoutParsingResultV2(BaseCVResult, HtmlMixin, XlsxMixin, MarkdownMixin):
  121. """Layout Parsing Result V2"""
  122. def __init__(self, data) -> None:
  123. """Initializes a new instance of the class with the specified data."""
  124. super().__init__(data)
  125. HtmlMixin.__init__(self)
  126. XlsxMixin.__init__(self)
  127. MarkdownMixin.__init__(self)
  128. JsonMixin.__init__(self)
  129. def _to_img(self) -> dict[str, np.ndarray]:
  130. from .utils import get_show_color
  131. res_img_dict = {}
  132. model_settings = self["model_settings"]
  133. if model_settings["use_doc_preprocessor"]:
  134. for key, value in self["doc_preprocessor_res"].img.items():
  135. res_img_dict[key] = value
  136. res_img_dict["layout_det_res"] = self["layout_det_res"].img["res"]
  137. if model_settings["use_region_detection"]:
  138. res_img_dict["region_det_res"] = self["region_det_res"].img["res"]
  139. res_img_dict["overall_ocr_res"] = self["overall_ocr_res"].img["ocr_res_img"]
  140. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  141. table_cell_img = Image.fromarray(
  142. copy.deepcopy(self["doc_preprocessor_res"]["output_img"][:, :, ::-1])
  143. )
  144. table_draw = ImageDraw.Draw(table_cell_img)
  145. rectangle_color = (255, 0, 0)
  146. for sno in range(len(self["table_res_list"])):
  147. table_res = self["table_res_list"][sno]
  148. cell_box_list = table_res["cell_box_list"]
  149. for box in cell_box_list:
  150. x1, y1, x2, y2 = [int(pos) for pos in box]
  151. table_draw.rectangle(
  152. [x1, y1, x2, y2], outline=rectangle_color, width=2
  153. )
  154. res_img_dict["table_cell_img"] = table_cell_img
  155. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  156. for sno in range(len(self["seal_res_list"])):
  157. seal_res = self["seal_res_list"][sno]
  158. seal_region_id = seal_res["seal_region_id"]
  159. sub_seal_res_dict = seal_res.img
  160. key = f"seal_res_region{seal_region_id}"
  161. res_img_dict[key] = sub_seal_res_dict["ocr_res_img"]
  162. # for layout ordering image
  163. image = Image.fromarray(self["doc_preprocessor_res"]["output_img"][:, :, ::-1])
  164. draw = ImageDraw.Draw(image, "RGBA")
  165. font_size = int(0.018 * int(image.width)) + 2
  166. font = ImageFont.truetype(PINGFANG_FONT.path, font_size, encoding="utf-8")
  167. parsing_result: List[LayoutBlock] = self["parsing_res_list"]
  168. for block in parsing_result:
  169. bbox = block.bbox
  170. index = block.order_index
  171. label = block.label
  172. fill_color = get_show_color(label, False)
  173. draw.rectangle(bbox, fill=fill_color)
  174. if index is not None:
  175. text_position = (bbox[2] + 2, bbox[1] - font_size // 2)
  176. if int(image.width) - bbox[2] < font_size:
  177. text_position = (
  178. int(bbox[2] - font_size * 1.1),
  179. bbox[1] - font_size // 2,
  180. )
  181. draw.text(text_position, str(index), font=font, fill="red")
  182. res_img_dict["layout_order_res"] = image
  183. return res_img_dict
  184. def _to_str(self, *args, **kwargs) -> dict[str, str]:
  185. """Converts the instance's attributes to a dictionary and then to a string.
  186. Args:
  187. *args: Additional positional arguments passed to the base class method.
  188. **kwargs: Additional keyword arguments passed to the base class method.
  189. Returns:
  190. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  191. """
  192. data = {}
  193. data["input_path"] = self["input_path"]
  194. data["page_index"] = self["page_index"]
  195. model_settings = self["model_settings"]
  196. data["model_settings"] = model_settings
  197. parsing_res_list: List[LayoutBlock] = self["parsing_res_list"]
  198. parsing_res_list = [
  199. {
  200. "block_label": parsing_res.label,
  201. "block_content": parsing_res.content,
  202. "block_bbox": parsing_res.bbox,
  203. "block_id": parsing_res.index,
  204. "block_order": parsing_res.order_index,
  205. }
  206. for parsing_res in parsing_res_list
  207. ]
  208. data["parsing_res_list"] = parsing_res_list
  209. if self["model_settings"]["use_doc_preprocessor"]:
  210. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  211. data["layout_det_res"] = self["layout_det_res"].str["res"]
  212. data["overall_ocr_res"] = self["overall_ocr_res"].str["res"]
  213. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  214. data["table_res_list"] = []
  215. for sno in range(len(self["table_res_list"])):
  216. table_res = self["table_res_list"][sno]
  217. data["table_res_list"].append(table_res.str["res"])
  218. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  219. data["seal_res_list"] = []
  220. for sno in range(len(self["seal_res_list"])):
  221. seal_res = self["seal_res_list"][sno]
  222. data["seal_res_list"].append(seal_res.str["res"])
  223. if (
  224. model_settings["use_formula_recognition"]
  225. and len(self["formula_res_list"]) > 0
  226. ):
  227. data["formula_res_list"] = []
  228. for sno in range(len(self["formula_res_list"])):
  229. formula_res = self["formula_res_list"][sno]
  230. data["formula_res_list"].append(formula_res.str["res"])
  231. return JsonMixin._to_str(data, *args, **kwargs)
  232. def _to_json(self, *args, **kwargs) -> dict[str, str]:
  233. """
  234. Converts the object's data to a JSON dictionary.
  235. Args:
  236. *args: Positional arguments passed to the JsonMixin._to_json method.
  237. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  238. Returns:
  239. Dict[str, str]: A dictionary containing the object's data in JSON format.
  240. """
  241. if self["model_settings"].get("format_block_content", False):
  242. original_image_width = self["doc_preprocessor_res"]["output_img"].shape[1]
  243. format_text_func = lambda block: format_centered_by_html(
  244. format_text_plain_func(block)
  245. )
  246. format_image_func = lambda block: format_centered_by_html(
  247. format_image_scaled_by_html_func(
  248. block,
  249. original_image_width=original_image_width,
  250. )
  251. )
  252. if self["model_settings"].get("use_chart_recognition", False):
  253. format_chart_func = format_chart2table_func
  254. else:
  255. format_chart_func = format_image_func
  256. if self["model_settings"].get("use_seal_recognition", False):
  257. format_seal_func = lambda block: "\n".join(
  258. [format_image_func(block), format_text_func(block)]
  259. )
  260. else:
  261. format_seal_func = format_image_func
  262. if self["model_settings"].get("use_table_recognition", False):
  263. format_table_func = lambda block: "\n" + format_text_func(
  264. block
  265. ).replace("<table>", '<table border="1">')
  266. else:
  267. format_table_func = format_image_func
  268. if self["model_settings"].get("use_formula_recognition", False):
  269. format_formula_func = lambda block: f"$${block.content}$$"
  270. else:
  271. format_formula_func = format_image_func
  272. handle_funcs_dict = {
  273. "paragraph_title": format_title_func,
  274. "abstract_title": format_title_func,
  275. "reference_title": format_title_func,
  276. "content_title": format_title_func,
  277. "doc_title": lambda block: f"# {block.content}".replace(
  278. "-\n",
  279. "",
  280. ).replace("\n", " "),
  281. "table_title": format_text_func,
  282. "figure_title": format_text_func,
  283. "chart_title": format_text_func,
  284. "vision_footnote": lambda block: block.content.replace(
  285. "\n\n", "\n"
  286. ).replace("\n", "\n\n"),
  287. "text": lambda block: block.content.replace("\n\n", "\n").replace(
  288. "\n", "\n\n"
  289. ),
  290. "abstract": partial(
  291. format_first_line_func,
  292. templates=["摘要", "abstract"],
  293. format_func=lambda l: f"## {l}\n",
  294. spliter=" ",
  295. ),
  296. "content": lambda block: block.content.replace("-\n", " \n").replace(
  297. "\n", " \n"
  298. ),
  299. "image": format_image_func,
  300. "chart": format_chart_func,
  301. "formula": format_formula_func,
  302. "table": format_table_func,
  303. "reference": partial(
  304. format_first_line_func,
  305. templates=["参考文献", "references"],
  306. format_func=lambda l: f"## {l}",
  307. spliter="\n",
  308. ),
  309. "algorithm": lambda block: block.content.strip("\n"),
  310. "seal": format_seal_func,
  311. }
  312. data = {}
  313. data["input_path"] = self["input_path"]
  314. data["page_index"] = self["page_index"]
  315. model_settings = self["model_settings"]
  316. data["model_settings"] = model_settings
  317. parsing_res_list: List[LayoutBlock] = self["parsing_res_list"]
  318. parsing_res_list_json = []
  319. for parsing_res in parsing_res_list:
  320. res_dict = {
  321. "block_label": parsing_res.label,
  322. "block_content": parsing_res.content,
  323. "block_bbox": parsing_res.bbox,
  324. "block_id": parsing_res.index,
  325. "block_order": parsing_res.order_index,
  326. }
  327. if self["model_settings"].get("format_block_content", False):
  328. if handle_funcs_dict.get(parsing_res.label):
  329. res_dict["block_content"] = handle_funcs_dict[parsing_res.label](
  330. parsing_res
  331. )
  332. else:
  333. res_dict["block_content"] = parsing_res.content
  334. parsing_res_list_json.append(res_dict)
  335. data["parsing_res_list"] = parsing_res_list_json
  336. if self["model_settings"]["use_doc_preprocessor"]:
  337. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  338. data["layout_det_res"] = self["layout_det_res"].json["res"]
  339. data["overall_ocr_res"] = self["overall_ocr_res"].json["res"]
  340. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  341. data["table_res_list"] = []
  342. for sno in range(len(self["table_res_list"])):
  343. table_res = self["table_res_list"][sno]
  344. data["table_res_list"].append(table_res.json["res"])
  345. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  346. data["seal_res_list"] = []
  347. for sno in range(len(self["seal_res_list"])):
  348. seal_res = self["seal_res_list"][sno]
  349. data["seal_res_list"].append(seal_res.json["res"])
  350. if (
  351. model_settings["use_formula_recognition"]
  352. and len(self["formula_res_list"]) > 0
  353. ):
  354. data["formula_res_list"] = []
  355. for sno in range(len(self["formula_res_list"])):
  356. formula_res = self["formula_res_list"][sno]
  357. data["formula_res_list"].append(formula_res.json["res"])
  358. return JsonMixin._to_json(data, *args, **kwargs)
  359. def _to_html(self) -> dict[str, str]:
  360. """Converts the prediction to its corresponding HTML representation.
  361. Returns:
  362. Dict[str, str]: The str type HTML representation result.
  363. """
  364. model_settings = self["model_settings"]
  365. res_html_dict = {}
  366. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  367. for sno in range(len(self["table_res_list"])):
  368. table_res = self["table_res_list"][sno]
  369. table_region_id = table_res["table_region_id"]
  370. key = f"table_{table_region_id}"
  371. res_html_dict[key] = table_res.html["pred"]
  372. return res_html_dict
  373. def _to_xlsx(self) -> dict[str, str]:
  374. """Converts the prediction HTML to an XLSX file path.
  375. Returns:
  376. Dict[str, str]: The str type XLSX representation result.
  377. """
  378. model_settings = self["model_settings"]
  379. res_xlsx_dict = {}
  380. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  381. for sno in range(len(self["table_res_list"])):
  382. table_res = self["table_res_list"][sno]
  383. table_region_id = table_res["table_region_id"]
  384. key = f"table_{table_region_id}"
  385. res_xlsx_dict[key] = table_res.xlsx["pred"]
  386. return res_xlsx_dict
  387. def _to_markdown(self, pretty=True, show_formula_number=False) -> dict:
  388. """
  389. Save the parsing result to a Markdown file.
  390. Args:
  391. pretty (Optional[bool]): whether to pretty markdown by HTML, default by True.
  392. Returns:
  393. Dict
  394. """
  395. original_image_width = self["doc_preprocessor_res"]["output_img"].shape[1]
  396. if pretty:
  397. format_text_func = lambda block: format_centered_by_html(
  398. format_text_plain_func(block)
  399. )
  400. format_image_func = lambda block: format_centered_by_html(
  401. format_image_scaled_by_html_func(
  402. block,
  403. original_image_width=original_image_width,
  404. )
  405. )
  406. else:
  407. format_text_func = lambda block: block.content
  408. format_image_func = format_image_plain_func
  409. if self["model_settings"].get("use_chart_recognition", False):
  410. format_chart_func = format_chart2table_func
  411. else:
  412. format_chart_func = format_image_func
  413. if self["model_settings"].get("use_seal_recognition", False):
  414. format_seal_func = lambda block: "\n".join(
  415. [format_image_func(block), format_text_func(block)]
  416. )
  417. else:
  418. format_seal_func = format_image_func
  419. if self["model_settings"].get("use_table_recognition", False):
  420. if pretty:
  421. format_table_func = lambda block: "\n" + format_text_func(
  422. block
  423. ).replace("<table>", '<table border="1">')
  424. else:
  425. format_table_func = lambda block: simplify_table_func(
  426. "\n" + block.content
  427. )
  428. else:
  429. format_table_func = format_image_func
  430. if self["model_settings"].get("use_formula_recognition", False):
  431. format_formula_func = lambda block: f"$${block.content}$$"
  432. else:
  433. format_formula_func = format_image_func
  434. handle_funcs_dict = {
  435. "paragraph_title": format_title_func,
  436. "abstract_title": format_title_func,
  437. "reference_title": format_title_func,
  438. "content_title": format_title_func,
  439. "doc_title": lambda block: f"# {block.content}".replace(
  440. "-\n",
  441. "",
  442. ).replace("\n", " "),
  443. "table_title": format_text_func,
  444. "figure_title": format_text_func,
  445. "chart_title": format_text_func,
  446. "vision_footnote": lambda block: block.content.replace(
  447. "\n\n", "\n"
  448. ).replace("\n", "\n\n"),
  449. "text": lambda block: block.content.replace("\n\n", "\n").replace(
  450. "\n", "\n\n"
  451. ),
  452. "abstract": partial(
  453. format_first_line_func,
  454. templates=["摘要", "abstract"],
  455. format_func=lambda l: f"## {l}\n",
  456. spliter=" ",
  457. ),
  458. "content": lambda block: block.content.replace("-\n", " \n").replace(
  459. "\n", " \n"
  460. ),
  461. "image": format_image_func,
  462. "chart": format_chart_func,
  463. "formula": format_formula_func,
  464. "table": format_table_func,
  465. "reference": partial(
  466. format_first_line_func,
  467. templates=["参考文献", "references"],
  468. format_func=lambda l: f"## {l}",
  469. spliter="\n",
  470. ),
  471. "algorithm": lambda block: block.content.strip("\n"),
  472. "seal": format_seal_func,
  473. }
  474. markdown_content = ""
  475. last_label = None
  476. seg_start_flag = True
  477. seg_end_flag = True
  478. prev_block = None
  479. page_first_element_seg_start_flag = None
  480. page_last_element_seg_end_flag = None
  481. markdown_info = {}
  482. markdown_info["markdown_images"] = {}
  483. for block in self["parsing_res_list"]:
  484. seg_start_flag, seg_end_flag = get_seg_flag(block, prev_block)
  485. label = block.label
  486. if block.image is not None:
  487. markdown_info["markdown_images"][block.image["path"]] = block.image[
  488. "img"
  489. ]
  490. page_first_element_seg_start_flag = (
  491. seg_start_flag
  492. if (page_first_element_seg_start_flag is None)
  493. else page_first_element_seg_start_flag
  494. )
  495. handle_func = handle_funcs_dict.get(label, None)
  496. if handle_func:
  497. prev_block = block
  498. if label == last_label == "text" and seg_start_flag == False:
  499. markdown_content += handle_func(block)
  500. else:
  501. markdown_content += (
  502. "\n\n" + handle_func(block)
  503. if markdown_content
  504. else handle_func(block)
  505. )
  506. last_label = label
  507. page_first_element_seg_start_flag = (
  508. True
  509. if page_first_element_seg_start_flag is None
  510. else page_first_element_seg_start_flag
  511. )
  512. page_last_element_seg_end_flag = seg_end_flag
  513. markdown_info["page_index"] = self["page_index"]
  514. markdown_info["input_path"] = self["input_path"]
  515. markdown_info["markdown_texts"] = markdown_content
  516. markdown_info["page_continuation_flags"] = (
  517. page_first_element_seg_start_flag,
  518. page_last_element_seg_end_flag,
  519. )
  520. for img in self["imgs_in_doc"]:
  521. markdown_info["markdown_images"][img["path"]] = img["img"]
  522. return markdown_info