result_v2.py 27 KB

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