result_v2.py 28 KB

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