result_v2.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. 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.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. parsing_res_list: List[LayoutBlock] = self["parsing_res_list"]
  194. parsing_res_list = [
  195. {
  196. "block_label": parsing_res.label,
  197. "block_content": parsing_res.content,
  198. "block_bbox": parsing_res.bbox,
  199. "block_id": parsing_res.index,
  200. "block_order": parsing_res.order_index,
  201. }
  202. for parsing_res in parsing_res_list
  203. ]
  204. data["parsing_res_list"] = parsing_res_list
  205. if self["model_settings"]["use_doc_preprocessor"]:
  206. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  207. data["layout_det_res"] = self["layout_det_res"].str["res"]
  208. data["overall_ocr_res"] = self["overall_ocr_res"].str["res"]
  209. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  210. data["table_res_list"] = []
  211. for sno in range(len(self["table_res_list"])):
  212. table_res = self["table_res_list"][sno]
  213. data["table_res_list"].append(table_res.str["res"])
  214. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  215. data["seal_res_list"] = []
  216. for sno in range(len(self["seal_res_list"])):
  217. seal_res = self["seal_res_list"][sno]
  218. data["seal_res_list"].append(seal_res.str["res"])
  219. if (
  220. model_settings["use_formula_recognition"]
  221. and len(self["formula_res_list"]) > 0
  222. ):
  223. data["formula_res_list"] = []
  224. for sno in range(len(self["formula_res_list"])):
  225. formula_res = self["formula_res_list"][sno]
  226. data["formula_res_list"].append(formula_res.str["res"])
  227. return JsonMixin._to_str(data, *args, **kwargs)
  228. def _to_json(self, *args, **kwargs) -> dict[str, str]:
  229. """
  230. Converts the object's data to a JSON dictionary.
  231. Args:
  232. *args: Positional arguments passed to the JsonMixin._to_json method.
  233. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  234. Returns:
  235. Dict[str, str]: A dictionary containing the object's data in JSON format.
  236. """
  237. if self["model_settings"].get("format_block_content", False):
  238. original_image_width = self["doc_preprocessor_res"]["output_img"].shape[1]
  239. format_text_func = lambda block: format_centered_by_html(
  240. format_text_plain_func(block)
  241. )
  242. format_image_func = lambda block: format_centered_by_html(
  243. format_image_scaled_by_html_func(
  244. block,
  245. original_image_width=original_image_width,
  246. )
  247. )
  248. if self["model_settings"].get("use_chart_recognition", False):
  249. format_chart_func = format_chart2table_func
  250. else:
  251. format_chart_func = format_image_func
  252. if self["model_settings"].get("use_seal_recognition", False):
  253. format_seal_func = lambda block: "\n".join(
  254. [format_image_func(block), format_text_func(block)]
  255. )
  256. else:
  257. format_seal_func = format_image_func
  258. if self["model_settings"].get("use_table_recognition", False):
  259. format_table_func = lambda block: "\n" + format_text_func(
  260. block
  261. ).replace("<table>", '<table border="1">')
  262. else:
  263. format_table_func = format_image_func
  264. if self["model_settings"].get("use_formula_recognition", False):
  265. format_formula_func = lambda block: f"$${block.content}$$"
  266. else:
  267. format_formula_func = format_image_func
  268. handle_funcs_dict = {
  269. "paragraph_title": format_title_func,
  270. "abstract_title": format_title_func,
  271. "reference_title": format_title_func,
  272. "content_title": format_title_func,
  273. "doc_title": lambda block: f"# {block.content}".replace(
  274. "-\n",
  275. "",
  276. ).replace("\n", " "),
  277. "table_title": format_text_func,
  278. "figure_title": format_text_func,
  279. "chart_title": format_text_func,
  280. "vision_footnote": lambda block: block.content.replace(
  281. "\n\n", "\n"
  282. ).replace("\n", "\n\n"),
  283. "text": lambda block: block.content.replace("\n\n", "\n").replace(
  284. "\n", "\n\n"
  285. ),
  286. "abstract": partial(
  287. format_first_line_func,
  288. templates=["摘要", "abstract"],
  289. format_func=lambda l: f"## {l}\n",
  290. spliter=" ",
  291. ),
  292. "content": lambda block: block.content.replace("-\n", " \n").replace(
  293. "\n", " \n"
  294. ),
  295. "image": format_image_func,
  296. "chart": format_chart_func,
  297. "formula": format_formula_func,
  298. "table": format_table_func,
  299. "reference": partial(
  300. format_first_line_func,
  301. templates=["参考文献", "references"],
  302. format_func=lambda l: f"## {l}",
  303. spliter="\n",
  304. ),
  305. "algorithm": lambda block: block.content.strip("\n"),
  306. "seal": format_seal_func,
  307. }
  308. data = {}
  309. data["input_path"] = self["input_path"]
  310. data["page_index"] = self["page_index"]
  311. model_settings = self["model_settings"]
  312. data["model_settings"] = model_settings
  313. parsing_res_list: List[LayoutBlock] = self["parsing_res_list"]
  314. parsing_res_list_json = []
  315. for parsing_res in parsing_res_list:
  316. res_dict = {
  317. "block_label": parsing_res.label,
  318. "block_content": parsing_res.content,
  319. "block_bbox": parsing_res.bbox,
  320. "block_id": parsing_res.index,
  321. "block_order": parsing_res.order_index,
  322. }
  323. if self["model_settings"].get("format_block_content", False):
  324. if handle_funcs_dict.get(parsing_res.label):
  325. res_dict["block_content"] = handle_funcs_dict[parsing_res.label](
  326. parsing_res
  327. )
  328. else:
  329. res_dict["block_content"] = parsing_res.content
  330. parsing_res_list_json.append(res_dict)
  331. data["parsing_res_list"] = parsing_res_list_json
  332. if self["model_settings"]["use_doc_preprocessor"]:
  333. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  334. data["layout_det_res"] = self["layout_det_res"].json["res"]
  335. data["overall_ocr_res"] = self["overall_ocr_res"].json["res"]
  336. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  337. data["table_res_list"] = []
  338. for sno in range(len(self["table_res_list"])):
  339. table_res = self["table_res_list"][sno]
  340. data["table_res_list"].append(table_res.json["res"])
  341. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  342. data["seal_res_list"] = []
  343. for sno in range(len(self["seal_res_list"])):
  344. seal_res = self["seal_res_list"][sno]
  345. data["seal_res_list"].append(seal_res.json["res"])
  346. if (
  347. model_settings["use_formula_recognition"]
  348. and len(self["formula_res_list"]) > 0
  349. ):
  350. data["formula_res_list"] = []
  351. for sno in range(len(self["formula_res_list"])):
  352. formula_res = self["formula_res_list"][sno]
  353. data["formula_res_list"].append(formula_res.json["res"])
  354. return JsonMixin._to_json(data, *args, **kwargs)
  355. def _to_html(self) -> dict[str, str]:
  356. """Converts the prediction to its corresponding HTML representation.
  357. Returns:
  358. Dict[str, str]: The str type HTML representation result.
  359. """
  360. model_settings = self["model_settings"]
  361. res_html_dict = {}
  362. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  363. for sno in range(len(self["table_res_list"])):
  364. table_res = self["table_res_list"][sno]
  365. table_region_id = table_res["table_region_id"]
  366. key = f"table_{table_region_id}"
  367. res_html_dict[key] = table_res.html["pred"]
  368. return res_html_dict
  369. def _to_xlsx(self) -> dict[str, str]:
  370. """Converts the prediction HTML to an XLSX file path.
  371. Returns:
  372. Dict[str, str]: The str type XLSX representation result.
  373. """
  374. model_settings = self["model_settings"]
  375. res_xlsx_dict = {}
  376. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  377. for sno in range(len(self["table_res_list"])):
  378. table_res = self["table_res_list"][sno]
  379. table_region_id = table_res["table_region_id"]
  380. key = f"table_{table_region_id}"
  381. res_xlsx_dict[key] = table_res.xlsx["pred"]
  382. return res_xlsx_dict
  383. def _to_markdown(self, pretty=True) -> dict:
  384. """
  385. Save the parsing result to a Markdown file.
  386. Args:
  387. pretty (Optional[bool]): whether to pretty markdown by HTML, default by True.
  388. Returns:
  389. Dict
  390. """
  391. original_image_width = self["doc_preprocessor_res"]["output_img"].shape[1]
  392. if pretty:
  393. format_text_func = lambda block: format_centered_by_html(
  394. format_text_plain_func(block)
  395. )
  396. format_image_func = lambda block: format_centered_by_html(
  397. format_image_scaled_by_html_func(
  398. block,
  399. original_image_width=original_image_width,
  400. )
  401. )
  402. else:
  403. format_text_func = lambda block: block.content
  404. format_image_func = format_image_plain_func
  405. if self["model_settings"].get("use_chart_recognition", False):
  406. format_chart_func = format_chart2table_func
  407. else:
  408. format_chart_func = format_image_func
  409. if self["model_settings"].get("use_seal_recognition", False):
  410. format_seal_func = lambda block: "\n".join(
  411. [format_image_func(block), format_text_func(block)]
  412. )
  413. else:
  414. format_seal_func = format_image_func
  415. if self["model_settings"].get("use_table_recognition", False):
  416. if pretty:
  417. format_table_func = lambda block: "\n" + format_text_func(
  418. block
  419. ).replace("<table>", '<table border="1">')
  420. else:
  421. format_table_func = lambda block: simplify_table_func(
  422. "\n" + block.content
  423. )
  424. else:
  425. format_table_func = format_image_func
  426. if self["model_settings"].get("use_formula_recognition", False):
  427. format_formula_func = lambda block: f"$${block.content}$$"
  428. else:
  429. format_formula_func = format_image_func
  430. handle_funcs_dict = {
  431. "paragraph_title": format_title_func,
  432. "abstract_title": format_title_func,
  433. "reference_title": format_title_func,
  434. "content_title": format_title_func,
  435. "doc_title": lambda block: f"# {block.content}".replace(
  436. "-\n",
  437. "",
  438. ).replace("\n", " "),
  439. "table_title": format_text_func,
  440. "figure_title": format_text_func,
  441. "chart_title": format_text_func,
  442. "vision_footnote": lambda block: block.content.replace(
  443. "\n\n", "\n"
  444. ).replace("\n", "\n\n"),
  445. "text": lambda block: block.content.replace("\n\n", "\n").replace(
  446. "\n", "\n\n"
  447. ),
  448. "abstract": partial(
  449. format_first_line_func,
  450. templates=["摘要", "abstract"],
  451. format_func=lambda l: f"## {l}\n",
  452. spliter=" ",
  453. ),
  454. "content": lambda block: block.content.replace("-\n", " \n").replace(
  455. "\n", " \n"
  456. ),
  457. "image": format_image_func,
  458. "chart": format_chart_func,
  459. "formula": format_formula_func,
  460. "table": format_table_func,
  461. "reference": partial(
  462. format_first_line_func,
  463. templates=["参考文献", "references"],
  464. format_func=lambda l: f"## {l}",
  465. spliter="\n",
  466. ),
  467. "algorithm": lambda block: block.content.strip("\n"),
  468. "seal": format_seal_func,
  469. }
  470. markdown_content = ""
  471. last_label = None
  472. seg_start_flag = True
  473. seg_end_flag = True
  474. prev_block = None
  475. page_first_element_seg_start_flag = None
  476. page_last_element_seg_end_flag = None
  477. markdown_info = {}
  478. markdown_info["markdown_images"] = {}
  479. for block in self["parsing_res_list"]:
  480. seg_start_flag, seg_end_flag = get_seg_flag(block, prev_block)
  481. label = block.label
  482. if block.image is not None:
  483. markdown_info["markdown_images"][block.image["path"]] = block.image[
  484. "img"
  485. ]
  486. page_first_element_seg_start_flag = (
  487. seg_start_flag
  488. if (page_first_element_seg_start_flag is None)
  489. else page_first_element_seg_start_flag
  490. )
  491. handle_func = handle_funcs_dict.get(label, None)
  492. if handle_func:
  493. prev_block = block
  494. if label == last_label == "text" and seg_start_flag == False:
  495. markdown_content += handle_func(block)
  496. else:
  497. markdown_content += (
  498. "\n\n" + handle_func(block)
  499. if markdown_content
  500. else handle_func(block)
  501. )
  502. last_label = label
  503. page_first_element_seg_start_flag = (
  504. True
  505. if page_first_element_seg_start_flag is None
  506. else page_first_element_seg_start_flag
  507. )
  508. page_last_element_seg_end_flag = seg_end_flag
  509. markdown_info["page_index"] = self["page_index"]
  510. markdown_info["input_path"] = self["input_path"]
  511. markdown_info["markdown_texts"] = markdown_content
  512. markdown_info["page_continuation_flags"] = (
  513. page_first_element_seg_start_flag,
  514. page_last_element_seg_end_flag,
  515. )
  516. for img in self["imgs_in_doc"]:
  517. markdown_info["markdown_images"][img["path"]] = img["img"]
  518. return markdown_info