result_v2.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. res_img_dict["overall_ocr_res"] = self["overall_ocr_res"].img["ocr_res_img"]
  186. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  187. table_cell_img = Image.fromarray(
  188. copy.deepcopy(self["doc_preprocessor_res"]["output_img"])
  189. )
  190. table_draw = ImageDraw.Draw(table_cell_img)
  191. rectangle_color = (255, 0, 0)
  192. for sno in range(len(self["table_res_list"])):
  193. table_res = self["table_res_list"][sno]
  194. cell_box_list = table_res["cell_box_list"]
  195. for box in cell_box_list:
  196. x1, y1, x2, y2 = [int(pos) for pos in box]
  197. table_draw.rectangle(
  198. [x1, y1, x2, y2], outline=rectangle_color, width=2
  199. )
  200. res_img_dict["table_cell_img"] = table_cell_img
  201. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  202. for sno in range(len(self["seal_res_list"])):
  203. seal_res = self["seal_res_list"][sno]
  204. seal_region_id = seal_res["seal_region_id"]
  205. sub_seal_res_dict = seal_res.img
  206. key = f"seal_res_region{seal_region_id}"
  207. res_img_dict[key] = sub_seal_res_dict["ocr_res_img"]
  208. # for layout ordering image
  209. image = Image.fromarray(self["doc_preprocessor_res"]["output_img"][:, :, ::-1])
  210. draw = ImageDraw.Draw(image, "RGBA")
  211. font_size = int(0.018 * int(image.width)) + 2
  212. font = ImageFont.truetype(PINGFANG_FONT_FILE_PATH, font_size, encoding="utf-8")
  213. parsing_result: List[LayoutParsingBlock] = self["parsing_res_list"]
  214. for block in parsing_result:
  215. bbox = block.bbox
  216. index = block.order_index
  217. label = block.label
  218. fill_color = get_show_color(label, False)
  219. draw.rectangle(bbox, fill=fill_color)
  220. if index is not None:
  221. text_position = (bbox[2] + 2, bbox[1] - font_size // 2)
  222. if int(image.width) - bbox[2] < font_size:
  223. text_position = (
  224. int(bbox[2] - font_size * 1.1),
  225. bbox[1] - font_size // 2,
  226. )
  227. draw.text(text_position, str(index), font=font, fill="red")
  228. res_img_dict["layout_order_res"] = image
  229. return res_img_dict
  230. def _to_str(self, *args, **kwargs) -> dict[str, str]:
  231. """Converts the instance's attributes to a dictionary and then to a string.
  232. Args:
  233. *args: Additional positional arguments passed to the base class method.
  234. **kwargs: Additional keyword arguments passed to the base class method.
  235. Returns:
  236. Dict[str, str]: A dictionary with the instance's attributes converted to strings.
  237. """
  238. data = {}
  239. data["input_path"] = self["input_path"]
  240. data["page_index"] = self["page_index"]
  241. model_settings = self["model_settings"]
  242. data["model_settings"] = model_settings
  243. if self["model_settings"]["use_doc_preprocessor"]:
  244. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].str["res"]
  245. data["layout_det_res"] = self["layout_det_res"].str["res"]
  246. data["overall_ocr_res"] = self["overall_ocr_res"].str["res"]
  247. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  248. data["table_res_list"] = []
  249. for sno in range(len(self["table_res_list"])):
  250. table_res = self["table_res_list"][sno]
  251. data["table_res_list"].append(table_res.str["res"])
  252. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  253. data["seal_res_list"] = []
  254. for sno in range(len(self["seal_res_list"])):
  255. seal_res = self["seal_res_list"][sno]
  256. data["seal_res_list"].append(seal_res.str["res"])
  257. if (
  258. model_settings["use_formula_recognition"]
  259. and len(self["formula_res_list"]) > 0
  260. ):
  261. data["formula_res_list"] = []
  262. for sno in range(len(self["formula_res_list"])):
  263. formula_res = self["formula_res_list"][sno]
  264. data["formula_res_list"].append(formula_res.str["res"])
  265. return JsonMixin._to_str(data, *args, **kwargs)
  266. def _to_json(self, *args, **kwargs) -> dict[str, str]:
  267. """
  268. Converts the object's data to a JSON dictionary.
  269. Args:
  270. *args: Positional arguments passed to the JsonMixin._to_json method.
  271. **kwargs: Keyword arguments passed to the JsonMixin._to_json method.
  272. Returns:
  273. Dict[str, str]: A dictionary containing the object's data in JSON format.
  274. """
  275. data = {}
  276. data["input_path"] = self["input_path"]
  277. data["page_index"] = self["page_index"]
  278. model_settings = self["model_settings"]
  279. data["model_settings"] = model_settings
  280. parsing_res_list = self["parsing_res_list"]
  281. parsing_res_list = [
  282. {
  283. "block_label": parsing_res.label,
  284. "block_content": parsing_res.content,
  285. "block_bbox": parsing_res.bbox,
  286. }
  287. for parsing_res in parsing_res_list
  288. ]
  289. data["parsing_res_list"] = parsing_res_list
  290. if self["model_settings"]["use_doc_preprocessor"]:
  291. data["doc_preprocessor_res"] = self["doc_preprocessor_res"].json["res"]
  292. data["layout_det_res"] = self["layout_det_res"].json["res"]
  293. data["overall_ocr_res"] = self["overall_ocr_res"].json["res"]
  294. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  295. data["table_res_list"] = []
  296. for sno in range(len(self["table_res_list"])):
  297. table_res = self["table_res_list"][sno]
  298. data["table_res_list"].append(table_res.json["res"])
  299. if model_settings["use_seal_recognition"] and len(self["seal_res_list"]) > 0:
  300. data["seal_res_list"] = []
  301. for sno in range(len(self["seal_res_list"])):
  302. seal_res = self["seal_res_list"][sno]
  303. data["seal_res_list"].append(seal_res.json["res"])
  304. if (
  305. model_settings["use_formula_recognition"]
  306. and len(self["formula_res_list"]) > 0
  307. ):
  308. data["formula_res_list"] = []
  309. for sno in range(len(self["formula_res_list"])):
  310. formula_res = self["formula_res_list"][sno]
  311. data["formula_res_list"].append(formula_res.json["res"])
  312. return JsonMixin._to_json(data, *args, **kwargs)
  313. def _to_html(self) -> dict[str, str]:
  314. """Converts the prediction to its corresponding HTML representation.
  315. Returns:
  316. Dict[str, str]: The str type HTML representation result.
  317. """
  318. model_settings = self["model_settings"]
  319. res_html_dict = {}
  320. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  321. for sno in range(len(self["table_res_list"])):
  322. table_res = self["table_res_list"][sno]
  323. table_region_id = table_res["table_region_id"]
  324. key = f"table_{table_region_id}"
  325. res_html_dict[key] = table_res.html["pred"]
  326. return res_html_dict
  327. def _to_xlsx(self) -> dict[str, str]:
  328. """Converts the prediction HTML to an XLSX file path.
  329. Returns:
  330. Dict[str, str]: The str type XLSX representation result.
  331. """
  332. model_settings = self["model_settings"]
  333. res_xlsx_dict = {}
  334. if model_settings["use_table_recognition"] and len(self["table_res_list"]) > 0:
  335. for sno in range(len(self["table_res_list"])):
  336. table_res = self["table_res_list"][sno]
  337. table_region_id = table_res["table_region_id"]
  338. key = f"table_{table_region_id}"
  339. res_xlsx_dict[key] = table_res.xlsx["pred"]
  340. return res_xlsx_dict
  341. def _to_markdown(self, pretty=True) -> dict:
  342. """
  343. Save the parsing result to a Markdown file.
  344. Args:
  345. pretty (Optional[bool]): wheather to pretty markdown by HTML, default by True.
  346. Returns:
  347. Dict
  348. """
  349. original_image_width = self["doc_preprocessor_res"]["output_img"].shape[1]
  350. if pretty:
  351. format_text_func = lambda block: format_centered_by_html(
  352. format_text_plain_func(block)
  353. )
  354. format_image_func = lambda block: format_centered_by_html(
  355. format_image_scaled_by_html_func(
  356. block,
  357. original_image_width=original_image_width,
  358. )
  359. )
  360. format_table = lambda block: "\n" + format_text_func(block)
  361. else:
  362. format_text_func = lambda block: block.content
  363. format_image_func = format_image_plain_func
  364. format_table = lambda block: simplify_table_func("\n" + block.content)
  365. if self["model_settings"].get("use_chart_recognition", False):
  366. format_chart_func = format_chart2table_func
  367. else:
  368. format_chart_func = format_image_func
  369. if self["model_settings"].get("use_seal_recognition", False):
  370. format_seal_func = lambda block: "\n".join(
  371. [format_image_func(block), format_text_func(block)]
  372. )
  373. else:
  374. format_seal_func = format_image_func
  375. handle_funcs_dict = {
  376. "paragraph_title": format_title_func,
  377. "abstract_title": format_title_func,
  378. "reference_title": format_title_func,
  379. "content_title": format_title_func,
  380. "doc_title": lambda block: f"# {block.content}".replace(
  381. "-\n",
  382. "",
  383. ).replace("\n", " "),
  384. "table_title": format_text_func,
  385. "figure_title": format_text_func,
  386. "chart_title": format_text_func,
  387. "text": lambda block: block.content.replace("\n\n", "\n").replace(
  388. "\n", "\n\n"
  389. ),
  390. "abstract": partial(
  391. format_first_line_func,
  392. templates=["摘要", "abstract"],
  393. format_func=lambda l: f"## {l}\n",
  394. spliter=" ",
  395. ),
  396. "content": lambda block: block.content.replace("-\n", " \n").replace(
  397. "\n", " \n"
  398. ),
  399. "image": format_image_func,
  400. "chart": format_chart_func,
  401. "formula": lambda block: f"$${block.content}$$",
  402. "table": format_table,
  403. "reference": partial(
  404. format_first_line_func,
  405. templates=["参考文献", "references"],
  406. format_func=lambda l: f"## {l}",
  407. spliter="\n",
  408. ),
  409. "algorithm": lambda block: block.content.strip("\n"),
  410. "seal": format_seal_func,
  411. }
  412. markdown_content = ""
  413. last_label = None
  414. seg_start_flag = None
  415. seg_end_flag = None
  416. prev_block = None
  417. page_first_element_seg_start_flag = None
  418. page_last_element_seg_end_flag = None
  419. for block in self["parsing_res_list"]:
  420. seg_start_flag, seg_end_flag = get_seg_flag(block, prev_block)
  421. label = block.label
  422. page_first_element_seg_start_flag = (
  423. seg_start_flag
  424. if (page_first_element_seg_start_flag is None)
  425. else page_first_element_seg_start_flag
  426. )
  427. handle_func = handle_funcs_dict.get(label, None)
  428. if handle_func:
  429. prev_block = block
  430. if label == last_label == "text" and seg_start_flag == False:
  431. markdown_content += handle_func(block)
  432. else:
  433. markdown_content += (
  434. "\n\n" + handle_func(block)
  435. if markdown_content
  436. else handle_func(block)
  437. )
  438. last_label = label
  439. page_last_element_seg_end_flag = seg_end_flag
  440. markdown_info = {
  441. "markdown_texts": markdown_content,
  442. "page_continuation_flags": (
  443. page_first_element_seg_start_flag,
  444. page_last_element_seg_end_flag,
  445. ),
  446. }
  447. markdown_info["markdown_images"] = {}
  448. for img in self["imgs_in_doc"]:
  449. markdown_info["markdown_images"][img["path"]] = img["img"]
  450. return markdown_info
  451. class LayoutParsingBlock:
  452. def __init__(self, label, bbox, content="") -> None:
  453. self.label = label
  454. self.order_label = None
  455. self.bbox = list(map(int, bbox))
  456. self.content = content
  457. self.seg_start_coordinate = float("inf")
  458. self.seg_end_coordinate = float("-inf")
  459. self.width = bbox[2] - bbox[0]
  460. self.height = bbox[3] - bbox[1]
  461. self.area = self.width * self.height
  462. self.num_of_lines = 1
  463. self.image = None
  464. self.index = None
  465. self.order_index = None
  466. self.text_line_width = 1
  467. self.text_line_height = 1
  468. self.direction = self.get_bbox_direction()
  469. self.child_blocks = []
  470. self.update_direction_info()
  471. def __str__(self) -> str:
  472. return f"{self.__dict__}"
  473. def __repr__(self) -> str:
  474. _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#################"
  475. return _str
  476. def to_dict(self) -> dict:
  477. return self.__dict__
  478. def update_direction_info(self) -> None:
  479. if self.direction == "horizontal":
  480. self.secondary_direction = "vertical"
  481. self.short_side_length = self.height
  482. self.long_side_length = self.width
  483. self.start_coordinate = self.bbox[0]
  484. self.end_coordinate = self.bbox[2]
  485. self.secondary_direction_start_coordinate = self.bbox[1]
  486. self.secondary_direction_end_coordinate = self.bbox[3]
  487. else:
  488. self.secondary_direction = "horizontal"
  489. self.short_side_length = self.width
  490. self.long_side_length = self.height
  491. self.start_coordinate = self.bbox[1]
  492. self.end_coordinate = self.bbox[3]
  493. self.secondary_direction_start_coordinate = self.bbox[0]
  494. self.secondary_direction_end_coordinate = self.bbox[2]
  495. def append_child_block(self, child_block: LayoutParsingBlock) -> None:
  496. if not self.child_blocks:
  497. self.ori_bbox = self.bbox.copy()
  498. x1, y1, x2, y2 = self.bbox
  499. x1_child, y1_child, x2_child, y2_child = child_block.bbox
  500. union_bbox = (
  501. min(x1, x1_child),
  502. min(y1, y1_child),
  503. max(x2, x2_child),
  504. max(y2, y2_child),
  505. )
  506. self.bbox = union_bbox
  507. self.update_direction_info()
  508. child_blocks = [child_block]
  509. if child_block.child_blocks:
  510. child_blocks.extend(child_block.get_child_blocks())
  511. self.child_blocks.extend(child_blocks)
  512. def get_child_blocks(self) -> list:
  513. self.bbox = self.ori_bbox
  514. child_blocks = self.child_blocks.copy()
  515. self.child_blocks = []
  516. return child_blocks
  517. def get_centroid(self) -> tuple:
  518. x1, y1, x2, y2 = self.bbox
  519. centroid = ((x1 + x2) / 2, (y1 + y2) / 2)
  520. return centroid
  521. def get_bbox_direction(self, direction_ratio: float = 1.0) -> bool:
  522. """
  523. Determine if a bounding box is horizontal or vertical.
  524. Args:
  525. bbox (List[float]): Bounding box [x_min, y_min, x_max, y_max].
  526. direction_ratio (float): Ratio for determining direction. Default is 1.0.
  527. Returns:
  528. str: "horizontal" or "vertical".
  529. """
  530. return (
  531. "horizontal" if self.width * direction_ratio >= self.height else "vertical"
  532. )
  533. class LayoutParsingRegion:
  534. def __init__(
  535. self, bbox, blocks: List[LayoutParsingBlock] = [], image_shape=None
  536. ) -> None:
  537. self.bbox = bbox
  538. self.block_map = {}
  539. self.direction = "horizontal"
  540. self.calculate_bbox_metrics(image_shape)
  541. self.doc_title_block_idxes = []
  542. self.paragraph_title_block_idxes = []
  543. self.vision_block_idxes = []
  544. self.unordered_block_idxes = []
  545. self.vision_title_block_idxes = []
  546. self.normal_text_block_idxes = []
  547. self.header_block_idxes = []
  548. self.footer_block_idxes = []
  549. self.text_line_width = 20
  550. self.text_line_height = 10
  551. self.init_region_info_from_layout(blocks)
  552. self.init_direction_info()
  553. def init_region_info_from_layout(self, blocks: List[LayoutParsingBlock]):
  554. horizontal_normal_text_block_num = 0
  555. text_line_height_list = []
  556. text_line_width_list = []
  557. for idx, block in enumerate(blocks):
  558. self.block_map[idx] = block
  559. block.index = idx
  560. if block.label in BLOCK_LABEL_MAP["header_labels"]:
  561. self.header_block_idxes.append(idx)
  562. elif block.label in BLOCK_LABEL_MAP["doc_title_labels"]:
  563. self.doc_title_block_idxes.append(idx)
  564. elif block.label in BLOCK_LABEL_MAP["paragraph_title_labels"]:
  565. self.paragraph_title_block_idxes.append(idx)
  566. elif block.label in BLOCK_LABEL_MAP["vision_labels"]:
  567. self.vision_block_idxes.append(idx)
  568. elif block.label in BLOCK_LABEL_MAP["vision_title_labels"]:
  569. self.vision_title_block_idxes.append(idx)
  570. elif block.label in BLOCK_LABEL_MAP["footer_labels"]:
  571. self.footer_block_idxes.append(idx)
  572. elif block.label in BLOCK_LABEL_MAP["unordered_labels"]:
  573. self.unordered_block_idxes.append(idx)
  574. else:
  575. self.normal_text_block_idxes.append(idx)
  576. text_line_height_list.append(block.text_line_height)
  577. text_line_width_list.append(block.text_line_width)
  578. if block.direction == "horizontal":
  579. horizontal_normal_text_block_num += 1
  580. self.direction = (
  581. "horizontal"
  582. if horizontal_normal_text_block_num
  583. >= len(self.normal_text_block_idxes) * 0.5
  584. else "vertical"
  585. )
  586. self.text_line_width = (
  587. np.mean(text_line_width_list) if text_line_width_list else 20
  588. )
  589. self.text_line_height = (
  590. np.mean(text_line_height_list) if text_line_height_list else 10
  591. )
  592. def init_direction_info(self):
  593. if self.direction == "horizontal":
  594. self.direction_start_index = 0
  595. self.direction_end_index = 2
  596. self.secondary_direction_start_index = 1
  597. self.secondary_direction_end_index = 3
  598. self.secondary_direction = "vertical"
  599. else:
  600. self.direction_start_index = 1
  601. self.direction_end_index = 3
  602. self.secondary_direction_start_index = 0
  603. self.secondary_direction_end_index = 2
  604. self.secondary_direction = "horizontal"
  605. self.direction_center_coordinate = (
  606. self.bbox[self.direction_start_index] + self.bbox[self.direction_end_index]
  607. ) / 2
  608. self.secondary_direction_center_coordinate = (
  609. self.bbox[self.secondary_direction_start_index]
  610. + self.bbox[self.secondary_direction_end_index]
  611. ) / 2
  612. def calculate_bbox_metrics(self, image_shape):
  613. x1, y1, x2, y2 = self.bbox
  614. width = x2 - x1
  615. image_height, image_width = image_shape
  616. x_center, y_center = (x1 + x2) / 2, (y1 + y2) / 2
  617. self.euclidean_distance = math.sqrt(((x1) ** 2 + (y1) ** 2))
  618. self.center_euclidean_distance = math.sqrt(((x_center) ** 2 + (y_center) ** 2))
  619. self.angle_rad = math.atan2(y_center, x_center)
  620. self.weighted_distance = (
  621. y1 + width + (x1 // (image_width // 10)) * (image_width // 10) * 1.5
  622. )
  623. def sort_normal_blocks(self, blocks):
  624. if self.direction == "horizontal":
  625. blocks.sort(
  626. key=lambda x: (
  627. x.bbox[1] // self.text_line_height,
  628. x.bbox[0] // self.text_line_width,
  629. x.bbox[1] ** 2 + x.bbox[0] ** 2,
  630. ),
  631. )
  632. else:
  633. blocks.sort(
  634. key=lambda x: (
  635. -x.bbox[0] // self.text_line_width,
  636. x.bbox[1] // self.text_line_height,
  637. -(x.bbox[2] ** 2 + x.bbox[1] ** 2),
  638. ),
  639. )
  640. def sort(self):
  641. from .xycut_enhanced import xycut_enhanced
  642. return xycut_enhanced(self)