result_v2.py 28 KB

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