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