xycuts.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 copy import deepcopy
  15. from typing import Dict, List, Tuple
  16. import numpy as np
  17. from ..result_v2 import LayoutParsingBlock, LayoutParsingRegion
  18. from ..setting import BLOCK_LABEL_MAP
  19. from ..utils import calculate_overlap_ratio, calculate_projection_overlap_ratio
  20. from .utils import (
  21. calculate_discontinuous_projection,
  22. get_cut_blocks,
  23. get_nearest_edge_distance,
  24. insert_child_blocks,
  25. manhattan_insert,
  26. recursive_xy_cut,
  27. recursive_yx_cut,
  28. reference_insert,
  29. shrink_overlapping_boxes,
  30. sort_normal_blocks,
  31. update_doc_title_child_blocks,
  32. update_paragraph_title_child_blocks,
  33. update_vision_child_blocks,
  34. weighted_distance_insert,
  35. )
  36. def pre_process(
  37. region: LayoutParsingRegion,
  38. ) -> List:
  39. """
  40. Preprocess the layout for sorting purposes.
  41. This function performs two main tasks:
  42. 1. Pre-cuts the layout to ensure the document is correctly partitioned and sorted.
  43. 2. Match the blocks with their children.
  44. Args:
  45. region: LayoutParsingRegion, the layout region to be pre-processed.
  46. Returns:
  47. List: A list of pre-cutted layout blocks list.
  48. """
  49. mask_labels = [
  50. "header",
  51. "unordered",
  52. "footer",
  53. "vision_footnote",
  54. "sub_paragraph_title",
  55. "doc_title_text",
  56. "vision_title",
  57. ]
  58. pre_cut_block_idxes = []
  59. block_map = region.block_map
  60. blocks: List[LayoutParsingBlock] = list(block_map.values())
  61. for block in blocks:
  62. if block.order_label not in mask_labels:
  63. update_region_label(block, region)
  64. block_direction = block.direction
  65. if block_direction == "horizontal":
  66. tolerance_len = block.long_side_length // 5
  67. else:
  68. tolerance_len = block.short_side_length // 10
  69. block_center = (
  70. block.bbox[region.direction_start_index]
  71. + block.bbox[region.direction_end_index]
  72. ) / 2
  73. center_offset = abs(block_center - region.direction_center_coordinate)
  74. is_centered = center_offset <= tolerance_len
  75. if is_centered:
  76. pre_cut_block_idxes.append(block.index)
  77. pre_cut_list = []
  78. cut_direction = region.secondary_direction
  79. cut_coordinates = []
  80. discontinuous = []
  81. all_boxes = np.array(
  82. [block.bbox for block in blocks if block.order_label not in mask_labels]
  83. )
  84. if len(all_boxes) == 0:
  85. return pre_cut_list
  86. if pre_cut_block_idxes:
  87. discontinuous, num_list = calculate_discontinuous_projection(
  88. all_boxes, direction=cut_direction, return_num=True
  89. )
  90. for idx in pre_cut_block_idxes:
  91. block = block_map[idx]
  92. if (
  93. block.order_label not in mask_labels
  94. and block.secondary_direction == cut_direction
  95. ):
  96. if (
  97. block.secondary_direction_start_coordinate,
  98. block.secondary_direction_end_coordinate,
  99. ) in discontinuous:
  100. idx = discontinuous.index(
  101. (
  102. block.secondary_direction_start_coordinate,
  103. block.secondary_direction_end_coordinate,
  104. )
  105. )
  106. if num_list[idx] == 1:
  107. cut_coordinates.append(
  108. block.secondary_direction_start_coordinate
  109. )
  110. cut_coordinates.append(block.secondary_direction_end_coordinate)
  111. secondary_discontinuous = calculate_discontinuous_projection(
  112. all_boxes, direction=region.direction
  113. )
  114. if len(secondary_discontinuous) == 1:
  115. if not discontinuous:
  116. discontinuous = calculate_discontinuous_projection(
  117. all_boxes, direction=cut_direction
  118. )
  119. current_interval = discontinuous[0]
  120. for interval in discontinuous[1:]:
  121. gap_len = interval[0] - current_interval[1]
  122. if gap_len >= region.text_line_height * 5:
  123. cut_coordinates.append(current_interval[1])
  124. elif gap_len > region.text_line_height * 2:
  125. x1, _, x2, __ = region.bbox
  126. y1 = current_interval[1]
  127. y2 = interval[0]
  128. bbox = [x1, y1, x2, y2]
  129. ref_interval = interval[0] - current_interval[1]
  130. ref_bboxes = []
  131. for block in blocks:
  132. if get_nearest_edge_distance(bbox, block.bbox) < ref_interval * 2:
  133. ref_bboxes.append(block.bbox)
  134. discontinuous = calculate_discontinuous_projection(
  135. ref_bboxes, direction=region.direction
  136. )
  137. if len(discontinuous) != 2:
  138. cut_coordinates.append(current_interval[1])
  139. current_interval = interval
  140. cut_list = get_cut_blocks(
  141. blocks, cut_direction, cut_coordinates, region.bbox, mask_labels
  142. )
  143. pre_cut_list.extend(cut_list)
  144. if region.direction == "vertical":
  145. pre_cut_list = pre_cut_list[::-1]
  146. return pre_cut_list
  147. def update_region_label(
  148. block: LayoutParsingBlock,
  149. region: LayoutParsingRegion,
  150. ) -> None:
  151. """
  152. Update the region label of a block based on its label and match the block with its children.
  153. Args:
  154. blocks (List[LayoutParsingBlock]): The list of blocks to process.
  155. config (Dict[str, Any]): The configuration dictionary containing the necessary information.
  156. block_idx (int): The index of the current block being processed.
  157. Returns:
  158. None
  159. """
  160. if block.label in BLOCK_LABEL_MAP["header_labels"]:
  161. block.order_label = "header"
  162. elif block.label in BLOCK_LABEL_MAP["doc_title_labels"]:
  163. block.order_label = "doc_title"
  164. elif (
  165. block.label in BLOCK_LABEL_MAP["paragraph_title_labels"]
  166. and block.order_label is None
  167. ):
  168. block.order_label = "paragraph_title"
  169. elif block.label in BLOCK_LABEL_MAP["vision_labels"]:
  170. block.order_label = "vision"
  171. block.num_of_lines = 1
  172. block.direction = region.direction
  173. block.update_direction_info()
  174. elif block.label in BLOCK_LABEL_MAP["footer_labels"]:
  175. block.order_label = "footer"
  176. elif block.label in BLOCK_LABEL_MAP["unordered_labels"]:
  177. block.order_label = "unordered"
  178. else:
  179. block.order_label = "normal_text"
  180. # only vision and doc title block can have child block
  181. if block.order_label not in ["vision", "doc_title", "paragraph_title"]:
  182. return
  183. # match doc title text block
  184. if block.order_label == "doc_title":
  185. update_doc_title_child_blocks(block, region)
  186. # match sub title block
  187. elif block.order_label == "paragraph_title":
  188. update_paragraph_title_child_blocks(block, region)
  189. # match vision title block and vision footnote block
  190. elif block.order_label == "vision":
  191. update_vision_child_blocks(block, region)
  192. def get_layout_structure(
  193. blocks: List[LayoutParsingBlock],
  194. region_direction: str,
  195. region_secondary_direction: str,
  196. ) -> Tuple[List[Dict[str, any]], bool]:
  197. """
  198. Determine the layout cross column of blocks.
  199. Args:
  200. blocks (List[Dict[str, any]]): List of block dictionaries containing 'label' and 'block_bbox'.
  201. Returns:
  202. Tuple[List[Dict[str, any]], bool]: Updated list of blocks with layout information and a boolean
  203. indicating if the cross layout area is greater than the single layout area.
  204. """
  205. blocks.sort(
  206. key=lambda x: (x.bbox[0], x.width),
  207. )
  208. mask_labels = ["doc_title", "cross_layout", "cross_reference"]
  209. for block_idx, block in enumerate(blocks):
  210. if block.order_label in mask_labels:
  211. continue
  212. for ref_idx, ref_block in enumerate(blocks):
  213. if block_idx == ref_idx or ref_block.order_label in mask_labels:
  214. continue
  215. bbox_iou = calculate_overlap_ratio(block.bbox, ref_block.bbox)
  216. if bbox_iou > 0:
  217. if ref_block.order_label == "vision":
  218. ref_block.order_label = "cross_layout"
  219. break
  220. if block.order_label == "vision" or block.area < ref_block.area:
  221. block.order_label = "cross_layout"
  222. break
  223. match_projection_iou = calculate_projection_overlap_ratio(
  224. block.bbox,
  225. ref_block.bbox,
  226. region_direction,
  227. )
  228. if match_projection_iou > 0:
  229. for second_ref_idx, second_ref_block in enumerate(blocks):
  230. if (
  231. second_ref_idx in [block_idx, ref_idx]
  232. or second_ref_block.order_label in mask_labels
  233. ):
  234. continue
  235. bbox_iou = calculate_overlap_ratio(
  236. block.bbox, second_ref_block.bbox
  237. )
  238. if bbox_iou > 0.1:
  239. if second_ref_block.order_label == "vision":
  240. second_ref_block.order_label = "cross_layout"
  241. break
  242. if (
  243. block.order_label == "vision"
  244. or block.area < second_ref_block.area
  245. ):
  246. block.order_label = "cross_layout"
  247. break
  248. second_match_projection_iou = calculate_projection_overlap_ratio(
  249. block.bbox,
  250. second_ref_block.bbox,
  251. region_direction,
  252. )
  253. ref_match_projection_iou = calculate_projection_overlap_ratio(
  254. ref_block.bbox,
  255. second_ref_block.bbox,
  256. region_direction,
  257. )
  258. secondary_direction_ref_match_projection_overlap_ratio = (
  259. calculate_projection_overlap_ratio(
  260. ref_block.bbox,
  261. second_ref_block.bbox,
  262. region_secondary_direction,
  263. )
  264. )
  265. if (
  266. second_match_projection_iou > 0
  267. and ref_match_projection_iou == 0
  268. and secondary_direction_ref_match_projection_overlap_ratio > 0
  269. ):
  270. if block.order_label == "vision" or (
  271. ref_block.order_label == "normal_text"
  272. and second_ref_block.order_label == "normal_text"
  273. and ref_block.text_line_width
  274. > ref_block.text_line_height * 5
  275. and second_ref_block.text_line_width
  276. > second_ref_block.text_line_height * 5
  277. ):
  278. block.order_label = (
  279. "cross_reference"
  280. if block.label == "reference"
  281. else "cross_layout"
  282. )
  283. def sort_by_xycut(
  284. block_bboxes: List,
  285. direction: str = "vertical",
  286. min_gap: int = 1,
  287. ) -> List[int]:
  288. """
  289. Sort bounding boxes using recursive XY cut method based on the specified direction.
  290. Args:
  291. block_bboxes (Union[np.ndarray, List[List[int]]]): An array or list of bounding boxes,
  292. where each box is represented as
  293. [x_min, y_min, x_max, y_max].
  294. direction (int): direction for the initial cut. Use 1 for Y-axis first and 0 for X-axis first.
  295. Defaults to 0.
  296. min_gap (int): Minimum gap width to consider a separation between segments. Defaults to 1.
  297. Returns:
  298. List[int]: A list of indices representing the order of sorted bounding boxes.
  299. """
  300. block_bboxes = np.asarray(block_bboxes).astype(int)
  301. res = []
  302. if direction == "vertical":
  303. recursive_yx_cut(
  304. block_bboxes,
  305. np.arange(len(block_bboxes)).tolist(),
  306. res,
  307. min_gap,
  308. )
  309. else:
  310. recursive_xy_cut(
  311. block_bboxes,
  312. np.arange(len(block_bboxes)).tolist(),
  313. res,
  314. min_gap,
  315. )
  316. return res
  317. def match_unsorted_blocks(
  318. sorted_blocks: List[LayoutParsingBlock],
  319. unsorted_blocks: List[LayoutParsingBlock],
  320. region: LayoutParsingRegion,
  321. ) -> List[LayoutParsingBlock]:
  322. """
  323. Match special blocks with the sorted blocks based on their region labels.
  324. Args:
  325. sorted_blocks (List[LayoutParsingBlock]): Sorted blocks to be matched.
  326. unsorted_blocks (List[LayoutParsingBlock]): Unsorted blocks to be matched.
  327. config (Dict): Configuration dictionary containing various parameters.
  328. median_width (int): Median width value used for calculations.
  329. Returns:
  330. List[LayoutParsingBlock]: The updated sorted blocks after matching special blocks.
  331. """
  332. distance_type_map = {
  333. "cross_layout": weighted_distance_insert,
  334. "paragraph_title": weighted_distance_insert,
  335. "doc_title": weighted_distance_insert,
  336. "vision_title": weighted_distance_insert,
  337. "vision": weighted_distance_insert,
  338. "cross_reference": reference_insert,
  339. "unordered": manhattan_insert,
  340. "other": manhattan_insert,
  341. }
  342. unsorted_blocks = sort_normal_blocks(
  343. unsorted_blocks,
  344. region.text_line_height,
  345. region.text_line_width,
  346. region.direction,
  347. )
  348. for idx, block in enumerate(unsorted_blocks):
  349. order_label = block.order_label
  350. if idx == 0 and order_label == "doc_title":
  351. sorted_blocks.insert(0, block)
  352. continue
  353. sorted_blocks = distance_type_map[order_label](block, sorted_blocks, region)
  354. return sorted_blocks
  355. def xycut_enhanced(
  356. region: LayoutParsingRegion,
  357. ) -> LayoutParsingRegion:
  358. """
  359. xycut_enhance function performs the following steps:
  360. 1. Preprocess the input blocks by extracting headers, footers, and pre-cut blocks.
  361. 2. Mask blocks that are crossing different blocks.
  362. 3. Perform xycut_enhanced algorithm on the remaining blocks.
  363. 4. Match unsorted blocks with the sorted blocks based on their order labels.
  364. 5. Update child blocks of the sorted blocks based on their parent blocks.
  365. 6. Return the ordered result list.
  366. Args:
  367. blocks (List[LayoutParsingBlock]): Input blocks to be processed.
  368. Returns:
  369. List[LayoutParsingBlock]: Ordered result list after processing.
  370. """
  371. if len(region.block_map) == 0:
  372. return []
  373. pre_cut_list: List[List[LayoutParsingBlock]] = pre_process(region)
  374. final_order_res_list: List[LayoutParsingBlock] = []
  375. header_blocks: List[LayoutParsingBlock] = [
  376. region.block_map[idx] for idx in region.header_block_idxes
  377. ]
  378. unordered_blocks: List[LayoutParsingBlock] = [
  379. region.block_map[idx] for idx in region.unordered_block_idxes
  380. ]
  381. footer_blocks: List[LayoutParsingBlock] = [
  382. region.block_map[idx] for idx in region.footer_block_idxes
  383. ]
  384. header_blocks: List[LayoutParsingBlock] = sort_normal_blocks(
  385. header_blocks, region.text_line_height, region.text_line_width, region.direction
  386. )
  387. footer_blocks: List[LayoutParsingBlock] = sort_normal_blocks(
  388. footer_blocks, region.text_line_height, region.text_line_width, region.direction
  389. )
  390. unordered_blocks: List[LayoutParsingBlock] = sort_normal_blocks(
  391. unordered_blocks,
  392. region.text_line_height,
  393. region.text_line_width,
  394. region.direction,
  395. )
  396. final_order_res_list.extend(header_blocks)
  397. unsorted_blocks: List[LayoutParsingBlock] = []
  398. sorted_blocks_by_pre_cuts: List[LayoutParsingBlock] = []
  399. for pre_cut_blocks in pre_cut_list:
  400. sorted_blocks: List[LayoutParsingBlock] = []
  401. doc_title_blocks: List[LayoutParsingBlock] = []
  402. xy_cut_blocks: List[LayoutParsingBlock] = []
  403. get_layout_structure(
  404. pre_cut_blocks, region.direction, region.secondary_direction
  405. )
  406. # Get xy cut blocks and add other blocks in special_block_map
  407. for block in pre_cut_blocks:
  408. if block.order_label not in [
  409. "cross_layout",
  410. "cross_reference",
  411. "doc_title",
  412. "unordered",
  413. ]:
  414. xy_cut_blocks.append(block)
  415. elif block.label == "doc_title":
  416. doc_title_blocks.append(block)
  417. else:
  418. unsorted_blocks.append(block)
  419. if len(xy_cut_blocks) > 0:
  420. block_bboxes = np.array([block.bbox for block in xy_cut_blocks])
  421. block_text_lines = [block.num_of_lines for block in xy_cut_blocks]
  422. discontinuous = calculate_discontinuous_projection(
  423. block_bboxes, direction=region.direction
  424. )
  425. if len(discontinuous) > 1:
  426. xy_cut_blocks = [block for block in xy_cut_blocks]
  427. blocks_to_sort = deepcopy(xy_cut_blocks)
  428. if region.direction == "vertical":
  429. for block in blocks_to_sort:
  430. block.bbox = np.array(
  431. [-block.bbox[0], block.bbox[1], -block.bbox[2], block.bbox[3]]
  432. )
  433. if len(discontinuous) == 1 or max(block_text_lines) == 1:
  434. blocks_to_sort.sort(
  435. key=lambda x: (
  436. x.bbox[region.secondary_direction_start_index]
  437. // (region.text_line_height // 2),
  438. x.bbox[region.direction_start_index],
  439. )
  440. )
  441. blocks_to_sort = shrink_overlapping_boxes(
  442. blocks_to_sort, region.secondary_direction
  443. )
  444. block_bboxes = np.array([block.bbox for block in blocks_to_sort])
  445. sorted_indexes = sort_by_xycut(
  446. block_bboxes, direction=region.secondary_direction, min_gap=1
  447. )
  448. else:
  449. blocks_to_sort.sort(
  450. key=lambda x: (
  451. x.bbox[region.direction_start_index]
  452. // (region.text_line_width // 2),
  453. x.bbox[region.secondary_direction_start_index],
  454. )
  455. )
  456. blocks_to_sort = shrink_overlapping_boxes(
  457. blocks_to_sort, region.direction
  458. )
  459. block_bboxes = np.array([block.bbox for block in blocks_to_sort])
  460. sorted_indexes = sort_by_xycut(
  461. block_bboxes, direction=region.direction, min_gap=1
  462. )
  463. sorted_blocks = [
  464. region.block_map[blocks_to_sort[i].index] for i in sorted_indexes
  465. ]
  466. sorted_blocks = match_unsorted_blocks(
  467. sorted_blocks,
  468. doc_title_blocks,
  469. region=region,
  470. )
  471. sorted_blocks_by_pre_cuts.extend(sorted_blocks)
  472. final_order_res_list = match_unsorted_blocks(
  473. sorted_blocks_by_pre_cuts,
  474. unsorted_blocks,
  475. region=region,
  476. )
  477. final_order_res_list.extend(footer_blocks)
  478. final_order_res_list.extend(unordered_blocks)
  479. for block_idx, block in enumerate(final_order_res_list):
  480. final_order_res_list = insert_child_blocks(
  481. block, block_idx, final_order_res_list
  482. )
  483. block = final_order_res_list[block_idx]
  484. return final_order_res_list