result_v2.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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 math
  17. import re
  18. from functools import partial
  19. from pathlib import Path
  20. from typing import List
  21. import numpy as np
  22. from PIL import Image, ImageDraw, ImageFont
  23. from ....utils.fonts import PINGFANG_FONT_FILE_PATH
  24. from ...common.result import (
  25. BaseCVResult,
  26. HtmlMixin,
  27. JsonMixin,
  28. MarkdownMixin,
  29. XlsxMixin,
  30. )
  31. from .setting import BLOCK_LABEL_MAP
  32. def compile_title_pattern():
  33. # Precompiled regex pattern for matching numbering at the beginning of the title
  34. numbering_pattern = (
  35. r"(?:" + r"[1-9][0-9]*(?:\.[1-9][0-9]*)*[\.、]?|" + r"[\(\(](?:[1-9][0-9]*|["
  36. r"一二三四五六七八九十百千万亿零壹贰叁肆伍陆柒捌玖拾]+)[\)\)]|" + r"["
  37. r"一二三四五六七八九十百千万亿零壹贰叁肆伍陆柒捌玖拾]+"
  38. r"[、\.]?|" + r"(?:I|II|III|IV|V|VI|VII|VIII|IX|X)\.?" + r")"
  39. )
  40. return re.compile(r"^\s*(" + numbering_pattern + r")(\s*)(.*)$")
  41. TITLE_RE_PATTERN = compile_title_pattern()
  42. def format_title_func(block):
  43. """
  44. Normalize chapter title.
  45. Add the '#' to indicate the level of the title.
  46. If numbering exists, ensure there's exactly one space between it and the title content.
  47. If numbering does not exist, return the original title unchanged.
  48. :param title: Original chapter title string.
  49. :return: Normalized chapter title string.
  50. """
  51. title = block.content
  52. match = TITLE_RE_PATTERN.match(title)
  53. if match:
  54. numbering = match.group(1).strip()
  55. title_content = match.group(3).lstrip()
  56. # Return numbering and title content separated by one space
  57. title = numbering + " " + title_content
  58. title = title.rstrip(".")
  59. level = (
  60. title.count(
  61. ".",
  62. )
  63. + 1
  64. if "." in title
  65. else 1
  66. )
  67. return f"#{'#' * level} {title}".replace("-\n", "").replace(
  68. "\n",
  69. " ",
  70. )
  71. def format_centered_by_html(string):
  72. return (
  73. f'<div style="text-align: center;">{string}</div>'.replace(
  74. "-\n",
  75. "",
  76. ).replace("\n", " ")
  77. + "\n"
  78. )
  79. def format_text_plain_func(block):
  80. return block.content
  81. def format_image_scaled_by_html_func(block, original_image_width):
  82. img_tags = []
  83. image_path = "".join(block.image.keys())
  84. image_width = block.image[image_path].width
  85. scale = int(image_width / original_image_width * 100)
  86. img_tags.append(
  87. '<img src="{}" alt="Image" width="{}%" />'.format(
  88. image_path.replace("-\n", "").replace("\n", " "), scale
  89. ),
  90. )
  91. return "\n".join(img_tags)
  92. def format_image_plain_func(block):
  93. img_tags = []
  94. image_path = "".join(block.image.keys())
  95. img_tags.append("![]({})".format(image_path.replace("-\n", "").replace("\n", " ")))
  96. return "\n".join(img_tags)
  97. def format_chart2table_func(block):
  98. lines_list = block.content.split("\n")
  99. column_num = len(lines_list[0].split("|"))
  100. lines_list.insert(1, "|".join(["---"] * column_num))
  101. lines_list = [f"|{line}|" for line in lines_list]
  102. return "\n".join(lines_list)
  103. def simplify_table_func(table_code):
  104. return "\n" + table_code.replace("<html>", "").replace("</html>", "").replace(
  105. "<body>", ""
  106. ).replace("</body>", "")
  107. def format_first_line_func(block, templates, format_func, spliter):
  108. lines = block.content.split(spliter)
  109. for idx in range(len(lines)):
  110. line = lines[idx]
  111. if line.strip() == "":
  112. continue
  113. if line.lower() in templates:
  114. lines[idx] = format_func(line)
  115. break
  116. return spliter.join(lines)
  117. def get_seg_flag(block: LayoutParsingBlock, prev_block: LayoutParsingBlock):
  118. seg_start_flag = True
  119. seg_end_flag = True
  120. block_box = block.bbox
  121. context_left_coordinate = block_box[0]
  122. context_right_coordinate = block_box[2]
  123. seg_start_coordinate = block.seg_start_coordinate
  124. seg_end_coordinate = block.seg_end_coordinate
  125. if prev_block is not None:
  126. prev_block_bbox = prev_block.bbox
  127. num_of_prev_lines = prev_block.num_of_lines
  128. pre_block_seg_end_coordinate = prev_block.seg_end_coordinate
  129. prev_end_space_small = (
  130. abs(prev_block_bbox[2] - pre_block_seg_end_coordinate) < 10
  131. )
  132. prev_lines_more_than_one = num_of_prev_lines > 1
  133. overlap_blocks = context_left_coordinate < prev_block_bbox[2]
  134. # update context_left_coordinate and context_right_coordinate
  135. if overlap_blocks:
  136. context_left_coordinate = min(prev_block_bbox[0], context_left_coordinate)
  137. context_right_coordinate = max(prev_block_bbox[2], context_right_coordinate)
  138. prev_end_space_small = (
  139. abs(context_right_coordinate - pre_block_seg_end_coordinate) < 10
  140. )
  141. edge_distance = 0
  142. else:
  143. edge_distance = abs(block_box[0] - prev_block_bbox[2])
  144. current_start_space_small = seg_start_coordinate - context_left_coordinate < 10
  145. if (
  146. prev_end_space_small
  147. and current_start_space_small
  148. and prev_lines_more_than_one
  149. and edge_distance < max(prev_block.width, block.width)
  150. ):
  151. seg_start_flag = False
  152. else:
  153. if seg_start_coordinate - context_left_coordinate < 10:
  154. seg_start_flag = False
  155. if context_right_coordinate - seg_end_coordinate < 10:
  156. seg_end_flag = False
  157. return seg_start_flag, seg_end_flag
  158. class LayoutParsingResultV2(BaseCVResult, HtmlMixin, XlsxMixin, MarkdownMixin):
  159. """Layout Parsing Result V2"""
  160. def __init__(self, data) -> None:
  161. """Initializes a new instance of the class with the specified data."""
  162. super().__init__(data)
  163. HtmlMixin.__init__(self)
  164. XlsxMixin.__init__(self)
  165. MarkdownMixin.__init__(self)
  166. JsonMixin.__init__(self)
  167. def _get_input_fn(self):
  168. fn = super()._get_input_fn()
  169. if (page_idx := self["page_index"]) is not None:
  170. fp = Path(fn)
  171. stem, suffix = fp.stem, fp.suffix
  172. return f"{stem}_{page_idx}{suffix}"
  173. else:
  174. return fn
  175. def _to_img(self) -> dict[str, np.ndarray]:
  176. from .utils import get_show_color
  177. res_img_dict = {}
  178. model_settings = self["model_settings"]
  179. if model_settings["use_doc_preprocessor"]:
  180. for key, value in self["doc_preprocessor_res"].img.items():
  181. res_img_dict[key] = value
  182. res_img_dict["layout_det_res"] = self["layout_det_res"].img["res"]
  183. if model_settings["use_region_detection"]:
  184. res_img_dict["region_det_res"] = self["region_det_res"].img["res"]
  185. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  186. res_img_dict["overall_ocr_res"] = self["overall_ocr_res"].img["ocr_res_img"]
  187. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  188. table_cell_img = Image.fromarray(
  189. copy.deepcopy(self["doc_preprocessor_res"]["output_img"])
  190. )
  191. table_draw = ImageDraw.Draw(table_cell_img)
  192. rectangle_color = (255, 0, 0)
  193. for sno in range(len(self["table_res_list"])):
  194. table_res = self["table_res_list"][sno]
  195. cell_box_list = table_res["cell_box_list"]
  196. for box in cell_box_list:
  197. x1, y1, x2, y2 = [int(pos) for pos in box]
  198. table_draw.rectangle(
  199. [x1, y1, x2, y2], outline=rectangle_color, width=2
  200. )
  201. res_img_dict["table_cell_img"] = table_cell_img
  202. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  203. for sno in range(len(self["seal_res_list"])):
  204. seal_res = self["seal_res_list"][sno]
  205. seal_region_id = seal_res["seal_region_id"]
  206. sub_seal_res_dict = seal_res.img
  207. key = f"seal_res_region{seal_region_id}"
  208. res_img_dict[key] = sub_seal_res_dict["ocr_res_img"]
  209. # for layout ordering image
  210. image = Image.fromarray(self["doc_preprocessor_res"]["output_img"][:, :, ::-1])
  211. draw = ImageDraw.Draw(image, "RGBA")
  212. font_size = int(0.018 * int(image.width)) + 2
  213. font = ImageFont.truetype(PINGFANG_FONT_FILE_PATH, font_size, encoding="utf-8")
  214. parsing_result: List[LayoutParsingBlock] = self["parsing_res_list"]
  215. for block in parsing_result:
  216. bbox = block.bbox
  217. index = block.order_index
  218. label = block.label
  219. fill_color = get_show_color(label, False)
  220. draw.rectangle(bbox, fill=fill_color)
  221. if index is not None:
  222. text_position = (bbox[2] + 2, bbox[1] - font_size // 2)
  223. if int(image.width) - bbox[2] < font_size:
  224. text_position = (
  225. int(bbox[2] - font_size * 1.1),
  226. bbox[1] - font_size // 2,
  227. )
  228. draw.text(text_position, str(index), font=font, fill="red")
  229. res_img_dict["layout_order_res"] = image
  230. return res_img_dict
  231. def _to_str(self, *args, **kwargs) -> dict[str, str]:
  232. """Converts the instance's attributes to a dictionary and then to a string.
  233. Args:
  234. *args: Additional positional arguments passed to the base class method.
  235. **kwargs: Additional keyword arguments passed to the base class method.
  236. Returns:
  237. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  238. """
  239. data = {}
  240. data["input_path"] = self["input_path"]
  241. data["page_index"] = self["page_index"]
  242. model_settings = self["model_settings"]
  243. data["model_settings"] = model_settings
  244. if self["model_settings"]["use_doc_preprocessor"]:
  245. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  246. data["layout_det_res"] = self["layout_det_res"].str["res"]
  247. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  248. data["overall_ocr_res"] = self["overall_ocr_res"].str["res"]
  249. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  250. data["table_res_list"] = []
  251. for sno in range(len(self["table_res_list"])):
  252. table_res = self["table_res_list"][sno]
  253. data["table_res_list"].append(table_res.str["res"])
  254. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  255. data["seal_res_list"] = []
  256. for sno in range(len(self["seal_res_list"])):
  257. seal_res = self["seal_res_list"][sno]
  258. data["seal_res_list"].append(seal_res.str["res"])
  259. if (
  260. model_settings["use_formula_recognition"]
  261. and len(self["formula_res_list"]) > 0
  262. ):
  263. data["formula_res_list"] = []
  264. for sno in range(len(self["formula_res_list"])):
  265. formula_res = self["formula_res_list"][sno]
  266. data["formula_res_list"].append(formula_res.str["res"])
  267. return JsonMixin._to_str(data, *args, **kwargs)
  268. def _to_json(self, *args, **kwargs) -> dict[str, str]:
  269. """
  270. Converts the object's data to a JSON dictionary.
  271. Args:
  272. *args: Positional arguments passed to the JsonMixin._to_json method.
  273. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  274. Returns:
  275. Dict[str, str]: A dictionary containing the object's data in JSON format.
  276. """
  277. data = {}
  278. data["input_path"] = self["input_path"]
  279. data["page_index"] = self["page_index"]
  280. model_settings = self["model_settings"]
  281. data["model_settings"] = model_settings
  282. parsing_res_list = self["parsing_res_list"]
  283. parsing_res_list = [
  284. {
  285. "block_label": parsing_res.label,
  286. "block_content": parsing_res.content,
  287. "block_bbox": parsing_res.bbox,
  288. }
  289. for parsing_res in parsing_res_list
  290. ]
  291. data["parsing_res_list"] = parsing_res_list
  292. if self["model_settings"]["use_doc_preprocessor"]:
  293. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  294. data["layout_det_res"] = self["layout_det_res"].json["res"]
  295. if model_settings["use_general_ocr"] or model_settings["use_table_recognition"]:
  296. data["overall_ocr_res"] = self["overall_ocr_res"].json["res"]
  297. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  298. data["table_res_list"] = []
  299. for sno in range(len(self["table_res_list"])):
  300. table_res = self["table_res_list"][sno]
  301. data["table_res_list"].append(table_res.json["res"])
  302. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  303. data["seal_res_list"] = []
  304. for sno in range(len(self["seal_res_list"])):
  305. seal_res = self["seal_res_list"][sno]
  306. data["seal_res_list"].append(seal_res.json["res"])
  307. if (
  308. model_settings["use_formula_recognition"]
  309. and len(self["formula_res_list"]) > 0
  310. ):
  311. data["formula_res_list"] = []
  312. for sno in range(len(self["formula_res_list"])):
  313. formula_res = self["formula_res_list"][sno]
  314. data["formula_res_list"].append(formula_res.json["res"])
  315. return JsonMixin._to_json(data, *args, **kwargs)
  316. def _to_html(self) -> dict[str, str]:
  317. """Converts the prediction to its corresponding HTML representation.
  318. Returns:
  319. Dict[str, str]: The str type HTML representation result.
  320. """
  321. model_settings = self["model_settings"]
  322. res_html_dict = {}
  323. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  324. for sno in range(len(self["table_res_list"])):
  325. table_res = self["table_res_list"][sno]
  326. table_region_id = table_res["table_region_id"]
  327. key = f"table_{table_region_id}"
  328. res_html_dict[key] = table_res.html["pred"]
  329. return res_html_dict
  330. def _to_xlsx(self) -> dict[str, str]:
  331. """Converts the prediction HTML to an XLSX file path.
  332. Returns:
  333. Dict[str, str]: The str type XLSX representation result.
  334. """
  335. model_settings = self["model_settings"]
  336. res_xlsx_dict = {}
  337. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  338. for sno in range(len(self["table_res_list"])):
  339. table_res = self["table_res_list"][sno]
  340. table_region_id = table_res["table_region_id"]
  341. key = f"table_{table_region_id}"
  342. res_xlsx_dict[key] = table_res.xlsx["pred"]
  343. return res_xlsx_dict
  344. def _to_markdown(self, pretty=True) -> dict:
  345. """
  346. Save the parsing result to a Markdown file.
  347. Args:
  348. pretty (Optional[bool]): wheather to pretty markdown by HTML, default by True.
  349. Returns:
  350. Dict
  351. """
  352. original_image_width = self["doc_preprocessor_res"]["output_img"].shape[1]
  353. if pretty:
  354. format_text_func = lambda block: format_centered_by_html(
  355. format_text_plain_func(block)
  356. )
  357. format_image_func = lambda block: format_centered_by_html(
  358. format_image_scaled_by_html_func(
  359. block,
  360. original_image_width=original_image_width,
  361. )
  362. )
  363. format_table = lambda block: "\n" + format_text_func(block)
  364. else:
  365. format_text_func = lambda block: block.content
  366. format_image_func = format_image_plain_func
  367. format_table = lambda block: simplify_table_func("\n" + block.content)
  368. if self["model_settings"].get("use_chart_recognition", False):
  369. format_chart_func = format_chart2table_func
  370. else:
  371. format_chart_func = format_image_func
  372. if self["model_settings"].get("use_seal_recognition", False):
  373. format_seal_func = lambda block: "\n".join(
  374. [format_image_func(block), format_text_func(block)]
  375. )
  376. else:
  377. format_seal_func = format_image_func
  378. handle_funcs_dict = {
  379. "paragraph_title": format_title_func,
  380. "abstract_title": format_title_func,
  381. "reference_title": format_title_func,
  382. "content_title": format_title_func,
  383. "doc_title": lambda block: f"# {block.content}".replace(
  384. "-\n",
  385. "",
  386. ).replace("\n", " "),
  387. "table_title": format_text_func,
  388. "figure_title": format_text_func,
  389. "chart_title": format_text_func,
  390. "text": lambda block: block.content.replace("\n\n", "\n").replace(
  391. "\n", "\n\n"
  392. ),
  393. "abstract": partial(
  394. format_first_line_func,
  395. templates=["摘要", "abstract"],
  396. format_func=lambda l: f"## {l}\n",
  397. spliter=" ",
  398. ),
  399. "content": lambda block: block.content.replace("-\n", " \n").replace(
  400. "\n", " \n"
  401. ),
  402. "image": format_image_func,
  403. "chart": format_chart_func,
  404. "formula": lambda block: f"$${block.content}$$",
  405. "table": format_table,
  406. "reference": partial(
  407. format_first_line_func,
  408. templates=["参考文献", "references"],
  409. format_func=lambda l: f"## {l}",
  410. spliter="\n",
  411. ),
  412. "algorithm": lambda block: block.content.strip("\n"),
  413. "seal": format_seal_func,
  414. }
  415. markdown_content = ""
  416. last_label = None
  417. seg_start_flag = None
  418. seg_end_flag = None
  419. prev_block = None
  420. page_first_element_seg_start_flag = None
  421. page_last_element_seg_end_flag = None
  422. for block in self["parsing_res_list"]:
  423. seg_start_flag, seg_end_flag = get_seg_flag(block, prev_block)
  424. label = block.label
  425. page_first_element_seg_start_flag = (
  426. seg_start_flag
  427. if (page_first_element_seg_start_flag is None)
  428. else page_first_element_seg_start_flag
  429. )
  430. handle_func = handle_funcs_dict.get(label, None)
  431. if handle_func:
  432. prev_block = block
  433. if label == last_label == "text" and seg_start_flag == False:
  434. markdown_content += handle_func(block)
  435. else:
  436. markdown_content += (
  437. "\n\n" + handle_func(block)
  438. if markdown_content
  439. else handle_func(block)
  440. )
  441. last_label = label
  442. page_last_element_seg_end_flag = seg_end_flag
  443. markdown_info = {
  444. "markdown_texts": markdown_content,
  445. "page_continuation_flags": (
  446. page_first_element_seg_start_flag,
  447. page_last_element_seg_end_flag,
  448. ),
  449. }
  450. markdown_info["markdown_images"] = {}
  451. for img in self["imgs_in_doc"]:
  452. markdown_info["markdown_images"][img["path"]] = img["img"]
  453. return markdown_info
  454. class LayoutParsingBlock:
  455. def __init__(self, label, bbox, content="") -> None:
  456. self.label = label
  457. self.order_label = None
  458. self.bbox = list(map(int, bbox))
  459. self.content = content
  460. self.seg_start_coordinate = float("inf")
  461. self.seg_end_coordinate = float("-inf")
  462. self.width = bbox[2] - bbox[0]
  463. self.height = bbox[3] - bbox[1]
  464. self.area = self.width * self.height
  465. self.num_of_lines = 1
  466. self.image = None
  467. self.index = None
  468. self.order_index = None
  469. self.text_line_width = 1
  470. self.text_line_height = 1
  471. self.direction = self.get_bbox_direction()
  472. self.child_blocks = []
  473. self.update_direction_info()
  474. def __str__(self) -> str:
  475. return f"{self.__dict__}"
  476. def __repr__(self) -> str:
  477. _str = f"\n\n#################\nindex:\t{self.index}\nlabel:\t{self.label}\nregion_label:\t{self.order_label}\nbbox:\t{self.bbox}\ncontent:\t{self.content}\n#################"
  478. return _str
  479. def to_dict(self) -> dict:
  480. return self.__dict__
  481. def update_direction_info(self) -> None:
  482. if self.direction == "horizontal":
  483. self.secondary_direction = "vertical"
  484. self.short_side_length = self.height
  485. self.long_side_length = self.width
  486. self.start_coordinate = self.bbox[0]
  487. self.end_coordinate = self.bbox[2]
  488. self.secondary_direction_start_coordinate = self.bbox[1]
  489. self.secondary_direction_end_coordinate = self.bbox[3]
  490. else:
  491. self.secondary_direction = "horizontal"
  492. self.short_side_length = self.width
  493. self.long_side_length = self.height
  494. self.start_coordinate = self.bbox[1]
  495. self.end_coordinate = self.bbox[3]
  496. self.secondary_direction_start_coordinate = self.bbox[0]
  497. self.secondary_direction_end_coordinate = self.bbox[2]
  498. def append_child_block(self, child_block: LayoutParsingBlock) -> None:
  499. if not self.child_blocks:
  500. self.ori_bbox = self.bbox.copy()
  501. x1, y1, x2, y2 = self.bbox
  502. x1_child, y1_child, x2_child, y2_child = child_block.bbox
  503. union_bbox = (
  504. min(x1, x1_child),
  505. min(y1, y1_child),
  506. max(x2, x2_child),
  507. max(y2, y2_child),
  508. )
  509. self.bbox = union_bbox
  510. self.update_direction_info()
  511. child_blocks = [child_block]
  512. if child_block.child_blocks:
  513. child_blocks.extend(child_block.get_child_blocks())
  514. self.child_blocks.extend(child_blocks)
  515. def get_child_blocks(self) -> list:
  516. self.bbox = self.ori_bbox
  517. child_blocks = self.child_blocks.copy()
  518. self.child_blocks = []
  519. return child_blocks
  520. def get_centroid(self) -> tuple:
  521. x1, y1, x2, y2 = self.bbox
  522. centroid = ((x1 + x2) / 2, (y1 + y2) / 2)
  523. return centroid
  524. def get_bbox_direction(self, direction_ratio: float = 1.0) -> bool:
  525. """
  526. Determine if a bounding box is horizontal or vertical.
  527. Args:
  528. bbox (List[float]): Bounding box [x_min, y_min, x_max, y_max].
  529. direction_ratio (float): Ratio for determining direction. Default is 1.0.
  530. Returns:
  531. str: "horizontal" or "vertical".
  532. """
  533. return (
  534. "horizontal" if self.width * direction_ratio >= self.height else "vertical"
  535. )
  536. class LayoutParsingRegion:
  537. def __init__(
  538. self, bbox, blocks: List[LayoutParsingBlock] = [], image_shape=None
  539. ) -> None:
  540. self.bbox = bbox
  541. self.block_map = {}
  542. self.direction = "horizontal"
  543. self.calculate_bbox_metrics(image_shape)
  544. self.doc_title_block_idxes = []
  545. self.paragraph_title_block_idxes = []
  546. self.vision_block_idxes = []
  547. self.unordered_block_idxes = []
  548. self.vision_title_block_idxes = []
  549. self.normal_text_block_idxes = []
  550. self.header_block_idxes = []
  551. self.footer_block_idxes = []
  552. self.text_line_width = 20
  553. self.text_line_height = 10
  554. self.init_region_info_from_layout(blocks)
  555. self.init_direction_info()
  556. def init_region_info_from_layout(self, blocks: List[LayoutParsingBlock]):
  557. horizontal_normal_text_block_num = 0
  558. text_line_height_list = []
  559. text_line_width_list = []
  560. for idx, block in enumerate(blocks):
  561. self.block_map[idx] = block
  562. block.index = idx
  563. if block.label in BLOCK_LABEL_MAP["header_labels"]:
  564. self.header_block_idxes.append(idx)
  565. elif block.label in BLOCK_LABEL_MAP["doc_title_labels"]:
  566. self.doc_title_block_idxes.append(idx)
  567. elif block.label in BLOCK_LABEL_MAP["paragraph_title_labels"]:
  568. self.paragraph_title_block_idxes.append(idx)
  569. elif block.label in BLOCK_LABEL_MAP["vision_labels"]:
  570. self.vision_block_idxes.append(idx)
  571. elif block.label in BLOCK_LABEL_MAP["vision_title_labels"]:
  572. self.vision_title_block_idxes.append(idx)
  573. elif block.label in BLOCK_LABEL_MAP["footer_labels"]:
  574. self.footer_block_idxes.append(idx)
  575. elif block.label in BLOCK_LABEL_MAP["unordered_labels"]:
  576. self.unordered_block_idxes.append(idx)
  577. else:
  578. self.normal_text_block_idxes.append(idx)
  579. text_line_height_list.append(block.text_line_height)
  580. text_line_width_list.append(block.text_line_width)
  581. if block.direction == "horizontal":
  582. horizontal_normal_text_block_num += 1
  583. self.direction = (
  584. "horizontal"
  585. if horizontal_normal_text_block_num
  586. >= len(self.normal_text_block_idxes) * 0.5
  587. else "vertical"
  588. )
  589. self.text_line_width = (
  590. np.mean(text_line_width_list) if text_line_width_list else 20
  591. )
  592. self.text_line_height = (
  593. np.mean(text_line_height_list) if text_line_height_list else 10
  594. )
  595. def init_direction_info(self):
  596. if self.direction == "horizontal":
  597. self.direction_start_index = 0
  598. self.direction_end_index = 2
  599. self.secondary_direction_start_index = 1
  600. self.secondary_direction_end_index = 3
  601. self.secondary_direction = "vertical"
  602. else:
  603. self.direction_start_index = 1
  604. self.direction_end_index = 3
  605. self.secondary_direction_start_index = 0
  606. self.secondary_direction_end_index = 2
  607. self.secondary_direction = "horizontal"
  608. self.direction_center_coordinate = (
  609. self.bbox[self.direction_start_index] + self.bbox[self.direction_end_index]
  610. ) / 2
  611. self.secondary_direction_center_coordinate = (
  612. self.bbox[self.secondary_direction_start_index]
  613. + self.bbox[self.secondary_direction_end_index]
  614. ) / 2
  615. def calculate_bbox_metrics(self, image_shape):
  616. x1, y1, x2, y2 = self.bbox
  617. width = x2 - x1
  618. image_height, image_width = image_shape
  619. x_center, y_center = (x1 + x2) / 2, (y1 + y2) / 2
  620. self.euclidean_distance = math.sqrt(((x1) ** 2 + (y1) ** 2))
  621. self.center_euclidean_distance = math.sqrt(((x_center) ** 2 + (y_center) ** 2))
  622. self.angle_rad = math.atan2(y_center, x_center)
  623. self.weighted_distance = (
  624. y1 + width + (x1 // (image_width // 10)) * (image_width // 10) * 1.5
  625. )
  626. def sort_normal_blocks(self, blocks):
  627. if self.direction == "horizontal":
  628. blocks.sort(
  629. key=lambda x: (
  630. x.bbox[1] // self.text_line_height,
  631. x.bbox[0] // self.text_line_width,
  632. x.bbox[1] ** 2 + x.bbox[0] ** 2,
  633. ),
  634. )
  635. else:
  636. blocks.sort(
  637. key=lambda x: (
  638. -x.bbox[0] // self.text_line_width,
  639. x.bbox[1] // self.text_line_height,
  640. -(x.bbox[2] ** 2 + x.bbox[1] ** 2),
  641. ),
  642. )
  643. def sort(self):
  644. from .xycut_enhanced import xycut_enhanced
  645. return xycut_enhanced(self)