result_v2.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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]): whether 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. else:
  361. format_text_func = lambda block: block.content
  362. format_image_func = format_image_plain_func
  363. if self["model_settings"].get("use_chart_recognition", False):
  364. format_chart_func = format_chart2table_func
  365. else:
  366. format_chart_func = format_image_func
  367. if self["model_settings"].get("use_seal_recognition", False):
  368. format_seal_func = lambda block: "\n".join(
  369. [format_image_func(block), format_text_func(block)]
  370. )
  371. else:
  372. format_seal_func = format_image_func
  373. if self["model_settings"].get("use_table_recognition", False):
  374. if pretty:
  375. format_table_func = lambda block: "\n" + format_text_func(block)
  376. else:
  377. format_table_func = lambda block: simplify_table_func(
  378. "\n" + block.content
  379. )
  380. else:
  381. format_table_func = format_image_func
  382. if self["model_settings"].get("use_formula_recognition", False):
  383. format_formula_func = lambda block: f"$${block.content}$$"
  384. else:
  385. format_formula_func = format_image_func
  386. handle_funcs_dict = {
  387. "paragraph_title": format_title_func,
  388. "abstract_title": format_title_func,
  389. "reference_title": format_title_func,
  390. "content_title": format_title_func,
  391. "doc_title": lambda block: f"# {block.content}".replace(
  392. "-\n",
  393. "",
  394. ).replace("\n", " "),
  395. "table_title": format_text_func,
  396. "figure_title": format_text_func,
  397. "chart_title": format_text_func,
  398. "text": lambda block: block.content.replace("\n\n", "\n").replace(
  399. "\n", "\n\n"
  400. ),
  401. "abstract": partial(
  402. format_first_line_func,
  403. templates=["摘要", "abstract"],
  404. format_func=lambda l: f"## {l}\n",
  405. spliter=" ",
  406. ),
  407. "content": lambda block: block.content.replace("-\n", " \n").replace(
  408. "\n", " \n"
  409. ),
  410. "image": format_image_func,
  411. "chart": format_chart_func,
  412. "formula": format_formula_func,
  413. "table": format_table_func,
  414. "reference": partial(
  415. format_first_line_func,
  416. templates=["参考文献", "references"],
  417. format_func=lambda l: f"## {l}",
  418. spliter="\n",
  419. ),
  420. "algorithm": lambda block: block.content.strip("\n"),
  421. "seal": format_seal_func,
  422. }
  423. markdown_content = ""
  424. last_label = None
  425. seg_start_flag = None
  426. seg_end_flag = None
  427. prev_block = None
  428. page_first_element_seg_start_flag = None
  429. page_last_element_seg_end_flag = None
  430. for block in self["parsing_res_list"]:
  431. seg_start_flag, seg_end_flag = get_seg_flag(block, prev_block)
  432. label = block.label
  433. page_first_element_seg_start_flag = (
  434. seg_start_flag
  435. if (page_first_element_seg_start_flag is None)
  436. else page_first_element_seg_start_flag
  437. )
  438. handle_func = handle_funcs_dict.get(label, None)
  439. if handle_func:
  440. prev_block = block
  441. if label == last_label == "text" and seg_start_flag == False:
  442. markdown_content += handle_func(block)
  443. else:
  444. markdown_content += (
  445. "\n\n" + handle_func(block)
  446. if markdown_content
  447. else handle_func(block)
  448. )
  449. last_label = label
  450. page_last_element_seg_end_flag = seg_end_flag
  451. markdown_info = {
  452. "markdown_texts": markdown_content,
  453. "page_continuation_flags": (
  454. page_first_element_seg_start_flag,
  455. page_last_element_seg_end_flag,
  456. ),
  457. }
  458. markdown_info["markdown_images"] = {}
  459. for img in self["imgs_in_doc"]:
  460. markdown_info["markdown_images"][img["path"]] = img["img"]
  461. return markdown_info
  462. class LayoutParsingBlock:
  463. def __init__(self, label, bbox, content="") -> None:
  464. self.label = label
  465. self.order_label = None
  466. self.bbox = list(map(int, bbox))
  467. self.content = content
  468. self.seg_start_coordinate = float("inf")
  469. self.seg_end_coordinate = float("-inf")
  470. self.width = bbox[2] - bbox[0]
  471. self.height = bbox[3] - bbox[1]
  472. self.area = self.width * self.height
  473. self.num_of_lines = 1
  474. self.image = None
  475. self.index = None
  476. self.order_index = None
  477. self.text_line_width = 1
  478. self.text_line_height = 1
  479. self.direction = self.get_bbox_direction()
  480. self.child_blocks = []
  481. self.update_direction_info()
  482. def __str__(self) -> str:
  483. return f"{self.__dict__}"
  484. def __repr__(self) -> str:
  485. _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#################"
  486. return _str
  487. def to_dict(self) -> dict:
  488. return self.__dict__
  489. def update_direction_info(self) -> None:
  490. if self.direction == "horizontal":
  491. self.secondary_direction = "vertical"
  492. self.short_side_length = self.height
  493. self.long_side_length = self.width
  494. self.start_coordinate = self.bbox[0]
  495. self.end_coordinate = self.bbox[2]
  496. self.secondary_direction_start_coordinate = self.bbox[1]
  497. self.secondary_direction_end_coordinate = self.bbox[3]
  498. else:
  499. self.secondary_direction = "horizontal"
  500. self.short_side_length = self.width
  501. self.long_side_length = self.height
  502. self.start_coordinate = self.bbox[1]
  503. self.end_coordinate = self.bbox[3]
  504. self.secondary_direction_start_coordinate = self.bbox[0]
  505. self.secondary_direction_end_coordinate = self.bbox[2]
  506. def append_child_block(self, child_block: LayoutParsingBlock) -> None:
  507. if not self.child_blocks:
  508. self.ori_bbox = self.bbox.copy()
  509. x1, y1, x2, y2 = self.bbox
  510. x1_child, y1_child, x2_child, y2_child = child_block.bbox
  511. union_bbox = (
  512. min(x1, x1_child),
  513. min(y1, y1_child),
  514. max(x2, x2_child),
  515. max(y2, y2_child),
  516. )
  517. self.bbox = union_bbox
  518. self.update_direction_info()
  519. child_blocks = [child_block]
  520. if child_block.child_blocks:
  521. child_blocks.extend(child_block.get_child_blocks())
  522. self.child_blocks.extend(child_blocks)
  523. def get_child_blocks(self) -> list:
  524. self.bbox = self.ori_bbox
  525. child_blocks = self.child_blocks.copy()
  526. self.child_blocks = []
  527. return child_blocks
  528. def get_centroid(self) -> tuple:
  529. x1, y1, x2, y2 = self.bbox
  530. centroid = ((x1 + x2) / 2, (y1 + y2) / 2)
  531. return centroid
  532. def get_bbox_direction(self, direction_ratio: float = 1.0) -> bool:
  533. """
  534. Determine if a bounding box is horizontal or vertical.
  535. Args:
  536. bbox (List[float]): Bounding box [x_min, y_min, x_max, y_max].
  537. direction_ratio (float): Ratio for determining direction. Default is 1.0.
  538. Returns:
  539. str: "horizontal" or "vertical".
  540. """
  541. return (
  542. "horizontal" if self.width * direction_ratio >= self.height else "vertical"
  543. )
  544. class LayoutParsingRegion:
  545. def __init__(
  546. self, bbox, blocks: List[LayoutParsingBlock] = [], image_shape=None
  547. ) -> None:
  548. self.bbox = bbox
  549. self.block_map = {}
  550. self.direction = "horizontal"
  551. self.calculate_bbox_metrics(image_shape)
  552. self.doc_title_block_idxes = []
  553. self.paragraph_title_block_idxes = []
  554. self.vision_block_idxes = []
  555. self.unordered_block_idxes = []
  556. self.vision_title_block_idxes = []
  557. self.normal_text_block_idxes = []
  558. self.header_block_idxes = []
  559. self.footer_block_idxes = []
  560. self.text_line_width = 20
  561. self.text_line_height = 10
  562. self.init_region_info_from_layout(blocks)
  563. self.init_direction_info()
  564. def init_region_info_from_layout(self, blocks: List[LayoutParsingBlock]):
  565. horizontal_normal_text_block_num = 0
  566. text_line_height_list = []
  567. text_line_width_list = []
  568. for idx, block in enumerate(blocks):
  569. self.block_map[idx] = block
  570. block.index = idx
  571. if block.label in BLOCK_LABEL_MAP["header_labels"]:
  572. self.header_block_idxes.append(idx)
  573. elif block.label in BLOCK_LABEL_MAP["doc_title_labels"]:
  574. self.doc_title_block_idxes.append(idx)
  575. elif block.label in BLOCK_LABEL_MAP["paragraph_title_labels"]:
  576. self.paragraph_title_block_idxes.append(idx)
  577. elif block.label in BLOCK_LABEL_MAP["vision_labels"]:
  578. self.vision_block_idxes.append(idx)
  579. elif block.label in BLOCK_LABEL_MAP["vision_title_labels"]:
  580. self.vision_title_block_idxes.append(idx)
  581. elif block.label in BLOCK_LABEL_MAP["footer_labels"]:
  582. self.footer_block_idxes.append(idx)
  583. elif block.label in BLOCK_LABEL_MAP["unordered_labels"]:
  584. self.unordered_block_idxes.append(idx)
  585. else:
  586. self.normal_text_block_idxes.append(idx)
  587. text_line_height_list.append(block.text_line_height)
  588. text_line_width_list.append(block.text_line_width)
  589. if block.direction == "horizontal":
  590. horizontal_normal_text_block_num += 1
  591. self.direction = (
  592. "horizontal"
  593. if horizontal_normal_text_block_num
  594. >= len(self.normal_text_block_idxes) * 0.5
  595. else "vertical"
  596. )
  597. self.text_line_width = (
  598. np.mean(text_line_width_list) if text_line_width_list else 20
  599. )
  600. self.text_line_height = (
  601. np.mean(text_line_height_list) if text_line_height_list else 10
  602. )
  603. def init_direction_info(self):
  604. if self.direction == "horizontal":
  605. self.direction_start_index = 0
  606. self.direction_end_index = 2
  607. self.secondary_direction_start_index = 1
  608. self.secondary_direction_end_index = 3
  609. self.secondary_direction = "vertical"
  610. else:
  611. self.direction_start_index = 1
  612. self.direction_end_index = 3
  613. self.secondary_direction_start_index = 0
  614. self.secondary_direction_end_index = 2
  615. self.secondary_direction = "horizontal"
  616. self.direction_center_coordinate = (
  617. self.bbox[self.direction_start_index] + self.bbox[self.direction_end_index]
  618. ) / 2
  619. self.secondary_direction_center_coordinate = (
  620. self.bbox[self.secondary_direction_start_index]
  621. + self.bbox[self.secondary_direction_end_index]
  622. ) / 2
  623. def calculate_bbox_metrics(self, image_shape):
  624. x1, y1, x2, y2 = self.bbox
  625. width = x2 - x1
  626. image_height, image_width = image_shape
  627. x_center, y_center = (x1 + x2) / 2, (y1 + y2) / 2
  628. self.euclidean_distance = math.sqrt(((x1) ** 2 + (y1) ** 2))
  629. self.center_euclidean_distance = math.sqrt(((x_center) ** 2 + (y_center) ** 2))
  630. self.angle_rad = math.atan2(y_center, x_center)
  631. self.weighted_distance = (
  632. y1 + width + (x1 // (image_width // 10)) * (image_width // 10) * 1.5
  633. )
  634. def sort_normal_blocks(self, blocks):
  635. if self.direction == "horizontal":
  636. blocks.sort(
  637. key=lambda x: (
  638. x.bbox[1] // self.text_line_height,
  639. x.bbox[0] // self.text_line_width,
  640. x.bbox[1] ** 2 + x.bbox[0] ** 2,
  641. ),
  642. )
  643. else:
  644. blocks.sort(
  645. key=lambda x: (
  646. -x.bbox[0] // self.text_line_width,
  647. x.bbox[1] // self.text_line_height,
  648. -(x.bbox[2] ** 2 + x.bbox[1] ** 2),
  649. ),
  650. )
  651. def sort(self):
  652. from .xycut_enhanced import xycut_enhanced
  653. return xycut_enhanced(self)