utils.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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. __all__ = [
  15. "get_sub_regions_ocr_res",
  16. "get_layout_ordering",
  17. "get_single_block_parsing_res",
  18. "recursive_img_array2path",
  19. "get_show_color",
  20. "sorted_layout_boxes",
  21. ]
  22. import numpy as np
  23. import copy
  24. import cv2
  25. from PIL import Image
  26. import uuid
  27. from pathlib import Path
  28. from typing import Optional, Union, List, Tuple, Dict, Any
  29. from ..ocr.result import OCRResult
  30. from ...models.object_detection.result import DetResult
  31. from ..components import convert_points_to_boxes
  32. def get_overlap_boxes_idx(src_boxes: np.ndarray, ref_boxes: np.ndarray) -> List:
  33. """
  34. Get the indices of source boxes that overlap with reference boxes based on a specified threshold.
  35. Args:
  36. src_boxes (np.ndarray): A 2D numpy array of source bounding boxes.
  37. ref_boxes (np.ndarray): A 2D numpy array of reference bounding boxes.
  38. Returns:
  39. match_idx_list (list): A list of indices of source boxes that overlap with reference boxes.
  40. """
  41. match_idx_list = []
  42. src_boxes_num = len(src_boxes)
  43. if src_boxes_num > 0 and len(ref_boxes) > 0:
  44. for rno in range(len(ref_boxes)):
  45. ref_box = ref_boxes[rno]
  46. x1 = np.maximum(ref_box[0], src_boxes[:, 0])
  47. y1 = np.maximum(ref_box[1], src_boxes[:, 1])
  48. x2 = np.minimum(ref_box[2], src_boxes[:, 2])
  49. y2 = np.minimum(ref_box[3], src_boxes[:, 3])
  50. pub_w = x2 - x1
  51. pub_h = y2 - y1
  52. match_idx = np.where((pub_w > 3) & (pub_h > 3))[0]
  53. match_idx_list.extend(match_idx)
  54. return match_idx_list
  55. def get_sub_regions_ocr_res(
  56. overall_ocr_res: OCRResult,
  57. object_boxes: List,
  58. flag_within: bool = True,
  59. return_match_idx: bool = False,
  60. ) -> OCRResult:
  61. """
  62. Filters OCR results to only include text boxes within specified object boxes based on a flag.
  63. Args:
  64. overall_ocr_res (OCRResult): The original OCR result containing all text boxes.
  65. object_boxes (list): A list of bounding boxes for the objects of interest.
  66. flag_within (bool): If True, only include text boxes within the object boxes. If False, exclude text boxes within the object boxes.
  67. return_match_idx (bool): If True, return the list of matching indices.
  68. Returns:
  69. OCRResult: A filtered OCR result containing only the relevant text boxes.
  70. """
  71. sub_regions_ocr_res = {}
  72. sub_regions_ocr_res["rec_polys"] = []
  73. sub_regions_ocr_res["rec_texts"] = []
  74. sub_regions_ocr_res["rec_scores"] = []
  75. sub_regions_ocr_res["rec_boxes"] = []
  76. overall_text_boxes = overall_ocr_res["rec_boxes"]
  77. match_idx_list = get_overlap_boxes_idx(overall_text_boxes, object_boxes)
  78. match_idx_list = list(set(match_idx_list))
  79. for box_no in range(len(overall_text_boxes)):
  80. if flag_within:
  81. if box_no in match_idx_list:
  82. flag_match = True
  83. else:
  84. flag_match = False
  85. else:
  86. if box_no not in match_idx_list:
  87. flag_match = True
  88. else:
  89. flag_match = False
  90. if flag_match:
  91. sub_regions_ocr_res["rec_polys"].append(
  92. overall_ocr_res["rec_polys"][box_no]
  93. )
  94. sub_regions_ocr_res["rec_texts"].append(
  95. overall_ocr_res["rec_texts"][box_no]
  96. )
  97. sub_regions_ocr_res["rec_scores"].append(
  98. overall_ocr_res["rec_scores"][box_no]
  99. )
  100. sub_regions_ocr_res["rec_boxes"].append(
  101. overall_ocr_res["rec_boxes"][box_no]
  102. )
  103. for key in ["rec_polys", "rec_scores", "rec_boxes"]:
  104. sub_regions_ocr_res[key] = np.array(sub_regions_ocr_res[key])
  105. return (
  106. (sub_regions_ocr_res, match_idx_list)
  107. if return_match_idx
  108. else sub_regions_ocr_res
  109. )
  110. def sorted_layout_boxes(res, w):
  111. """
  112. Sort text boxes in order from top to bottom, left to right
  113. Args:
  114. res: List of dictionaries containing layout information.
  115. w: Width of image.
  116. Returns:
  117. List of dictionaries containing sorted layout information.
  118. """
  119. num_boxes = len(res)
  120. if num_boxes == 1:
  121. res[0]["layout"] = "single"
  122. return res
  123. # Sort on the y axis first or sort it on the x axis
  124. sorted_boxes = sorted(res, key=lambda x: (x["layout_bbox"][1], x["layout_bbox"][0]))
  125. _boxes = list(sorted_boxes)
  126. new_res = []
  127. res_left = []
  128. res_right = []
  129. i = 0
  130. while True:
  131. if i >= num_boxes:
  132. break
  133. # Check that the bbox is on the left
  134. elif (
  135. _boxes[i]["layout_bbox"][0] < w / 4
  136. and _boxes[i]["layout_bbox"][2] < 3 * w / 5
  137. ):
  138. _boxes[i]["layout"] = "double"
  139. res_left.append(_boxes[i])
  140. i += 1
  141. elif _boxes[i]["layout_bbox"][0] > 2 * w / 5:
  142. _boxes[i]["layout"] = "double"
  143. res_right.append(_boxes[i])
  144. i += 1
  145. else:
  146. new_res += res_left
  147. new_res += res_right
  148. _boxes[i]["layout"] = "single"
  149. new_res.append(_boxes[i])
  150. res_left = []
  151. res_right = []
  152. i += 1
  153. res_left = sorted(res_left, key=lambda x: (x["layout_bbox"][1]))
  154. res_right = sorted(res_right, key=lambda x: (x["layout_bbox"][1]))
  155. if res_left:
  156. new_res += res_left
  157. if res_right:
  158. new_res += res_right
  159. return new_res
  160. def _calculate_overlap_area_div_minbox_area_ratio(
  161. bbox1: Union[list, tuple],
  162. bbox2: Union[list, tuple],
  163. ) -> float:
  164. """
  165. Calculate the ratio of the overlap area between bbox1 and bbox2
  166. to the area of the smaller bounding box.
  167. Args:
  168. bbox1 (list or tuple): Coordinates of the first bounding box [x_min, y_min, x_max, y_max].
  169. bbox2 (list or tuple): Coordinates of the second bounding box [x_min, y_min, x_max, y_max].
  170. Returns:
  171. float: The ratio of the overlap area to the area of the smaller bounding box.
  172. """
  173. bbox1 = list(map(int, bbox1))
  174. bbox2 = list(map(int, bbox2))
  175. x_left = max(bbox1[0], bbox2[0])
  176. y_top = max(bbox1[1], bbox2[1])
  177. x_right = min(bbox1[2], bbox2[2])
  178. y_bottom = min(bbox1[3], bbox2[3])
  179. if x_right <= x_left or y_bottom <= y_top:
  180. return 0.0
  181. intersection_area = (x_right - x_left) * (y_bottom - y_top)
  182. area_bbox1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
  183. area_bbox2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
  184. min_box_area = min(area_bbox1, area_bbox2)
  185. if min_box_area <= 0:
  186. return 0.0
  187. return intersection_area / min_box_area
  188. def _whether_y_overlap_exceeds_threshold(
  189. bbox1: Union[list, tuple],
  190. bbox2: Union[list, tuple],
  191. overlap_ratio_threshold: float = 0.6,
  192. ) -> bool:
  193. """
  194. Determines whether the vertical overlap between two bounding boxes exceeds a given threshold.
  195. Args:
  196. bbox1 (list or tuple): The first bounding box defined as (left, top, right, bottom).
  197. bbox2 (list or tuple): The second bounding box defined as (left, top, right, bottom).
  198. overlap_ratio_threshold (float): The threshold ratio to determine if the overlap is significant.
  199. Defaults to 0.6.
  200. Returns:
  201. bool: True if the vertical overlap divided by the minimum height of the two bounding boxes
  202. exceeds the overlap_ratio_threshold, otherwise False.
  203. """
  204. _, y1_0, _, y1_1 = bbox1
  205. _, y2_0, _, y2_1 = bbox2
  206. overlap = max(0, min(y1_1, y2_1) - max(y1_0, y2_0))
  207. min_height = min(y1_1 - y1_0, y2_1 - y2_0)
  208. return (overlap / min_height) > overlap_ratio_threshold
  209. def _adjust_span_text(span: List[str], prepend: bool = False, append: bool = False):
  210. """
  211. Adjust the text of a span by prepending or appending a newline.
  212. Args:
  213. span (list): A list where the second element is the text of the span.
  214. prepend (bool): If True, prepend a newline to the text.
  215. append (bool): If True, append a newline to the text.
  216. Returns:
  217. None: The function modifies the span in place.
  218. """
  219. if prepend:
  220. span[1] = "\n" + span[1]
  221. if append:
  222. span[1] = span[1] + "\n"
  223. def _format_line(
  224. line: List[List[Union[List[int], str]]],
  225. layout_min: int,
  226. layout_max: int,
  227. is_reference: bool = False,
  228. ) -> None:
  229. """
  230. Format a line of text spans based on layout constraints.
  231. Args:
  232. line (list): A list of spans, where each span is a list containing a bounding box and text.
  233. layout_min (int): The minimum x-coordinate of the layout bounding box.
  234. layout_max (int): The maximum x-coordinate of the layout bounding box.
  235. is_reference (bool): A flag indicating whether the line is a reference line, which affects formatting rules.
  236. Returns:
  237. None: The function modifies the line in place.
  238. """
  239. first_span = line[0]
  240. end_span = line[-1]
  241. if not is_reference:
  242. if first_span[0][0] - layout_min > 10:
  243. _adjust_span_text(first_span, prepend=True)
  244. if layout_max - end_span[0][2] > 10:
  245. _adjust_span_text(end_span, append=True)
  246. else:
  247. if first_span[0][0] - layout_min < 5:
  248. _adjust_span_text(first_span, prepend=True)
  249. if layout_max - end_span[0][2] > 20:
  250. _adjust_span_text(end_span, append=True)
  251. def _sort_ocr_res_by_y_projection(
  252. label: Any,
  253. layout_bbox: Tuple[int, int, int, int],
  254. ocr_res: Dict[str, List[Any]],
  255. line_height_iou_threshold: float = 0.7,
  256. ) -> Dict[str, List[Any]]:
  257. """
  258. Sorts OCR results based on their spatial arrangement, grouping them into lines and blocks.
  259. Args:
  260. label (Any): The label associated with the OCR results. It's not used in the function but might be
  261. relevant for other parts of the calling context.
  262. layout_bbox (Tuple[int, int, int, int]): A tuple representing the layout bounding box, defined as
  263. (left, top, right, bottom).
  264. ocr_res (Dict[str, List[Any]]): A dictionary containing OCR results with the following keys:
  265. - "boxes": A list of bounding boxes, each defined as [left, top, right, bottom].
  266. - "rec_texts": A corresponding list of recognized text strings for each box.
  267. line_height_iou_threshold (float): The threshold for determining whether two boxes belong to
  268. the same line based on their vertical overlap. Defaults to 0.7.
  269. Returns:
  270. Dict[str, List[Any]]: A dictionary with the same structure as `ocr_res`, but with boxes and texts sorted
  271. and grouped into lines and blocks.
  272. """
  273. assert (
  274. ocr_res["boxes"] and ocr_res["rec_texts"]
  275. ), "OCR results must contain 'boxes' and 'rec_texts'"
  276. boxes = ocr_res["boxes"]
  277. rec_texts = ocr_res["rec_texts"]
  278. x_min, _, x_max, _ = layout_bbox
  279. inline_x_min = min([box[0] for box in boxes])
  280. inline_x_max = max([box[2] for box in boxes])
  281. spans = list(zip(boxes, rec_texts))
  282. spans.sort(key=lambda span: span[0][1])
  283. spans = [list(span) for span in spans]
  284. lines = []
  285. current_line = [spans[0]]
  286. current_y0, current_y1 = spans[0][0][1], spans[0][0][3]
  287. for span in spans[1:]:
  288. y0, y1 = span[0][1], span[0][3]
  289. if _whether_y_overlap_exceeds_threshold(
  290. (0, current_y0, 0, current_y1),
  291. (0, y0, 0, y1),
  292. line_height_iou_threshold,
  293. ):
  294. current_line.append(span)
  295. current_y0 = min(current_y0, y0)
  296. current_y1 = max(current_y1, y1)
  297. else:
  298. lines.append(current_line)
  299. current_line = [span]
  300. current_y0, current_y1 = y0, y1
  301. if current_line:
  302. lines.append(current_line)
  303. for line in lines:
  304. line.sort(key=lambda span: span[0][0])
  305. if label == "reference":
  306. line = _format_line(line, inline_x_min, inline_x_max, is_reference=True)
  307. else:
  308. line = _format_line(line, x_min, x_max)
  309. # Flatten lines back into a single list for boxes and texts
  310. ocr_res["boxes"] = [span[0] for line in lines for span in line]
  311. ocr_res["rec_texts"] = [span[1] + " " for line in lines for span in line]
  312. return ocr_res
  313. def get_single_block_parsing_res(
  314. overall_ocr_res: OCRResult,
  315. layout_det_res: DetResult,
  316. table_res_list: list,
  317. seal_res_list: list,
  318. ) -> OCRResult:
  319. """
  320. Extract structured information from OCR and layout detection results.
  321. Args:
  322. overall_ocr_res (OCRResult): An object containing the overall OCR results, including detected text boxes and recognized text. The structure is expected to have:
  323. - "input_img": The image on which OCR was performed.
  324. - "dt_boxes": A list of detected text box coordinates.
  325. - "rec_texts": A list of recognized text corresponding to the detected boxes.
  326. layout_det_res (DetResult): An object containing the layout detection results, including detected layout boxes and their labels. The structure is expected to have:
  327. - "boxes": A list of dictionaries with keys "coordinate" for box coordinates and "label" for the type of content.
  328. table_res_list (list): A list of table detection results, where each item is a dictionary containing:
  329. - "layout_bbox": The bounding box of the table layout.
  330. - "pred_html": The predicted HTML representation of the table.
  331. seal_res_list (List): A list of seal detection results. The details of each item depend on the specific application context.
  332. Returns:
  333. list: A list of structured boxes where each item is a dictionary containing:
  334. - "label": The label of the content (e.g., 'table', 'chart', 'image').
  335. - The label as a key with either table HTML or image data and text.
  336. - "layout_bbox": The coordinates of the layout box.
  337. """
  338. single_block_layout_parsing_res = []
  339. input_img = overall_ocr_res["doc_preprocessor_res"]["output_img"]
  340. for box_info in layout_det_res["boxes"]:
  341. layout_bbox = box_info["coordinate"]
  342. label = box_info["label"]
  343. rec_res = {"boxes": [], "rec_texts": [], "flag": False}
  344. seg_start_flag = True
  345. seg_end_flag = True
  346. if label == "table":
  347. for i, table_res in enumerate(table_res_list):
  348. if (
  349. _calculate_overlap_area_div_minbox_area_ratio(
  350. layout_bbox, table_res["cell_box_list"][0]
  351. )
  352. > 0.5
  353. ):
  354. single_block_layout_parsing_res.append(
  355. {
  356. "label": label,
  357. f"{label}": table_res["pred_html"],
  358. "layout_bbox": layout_bbox,
  359. "seg_start_flag": seg_start_flag,
  360. "seg_end_flag": seg_end_flag,
  361. },
  362. )
  363. del table_res_list[i]
  364. break
  365. else:
  366. overall_text_boxes = overall_ocr_res["rec_boxes"]
  367. for box_no in range(len(overall_text_boxes)):
  368. if (
  369. _calculate_overlap_area_div_minbox_area_ratio(
  370. layout_bbox, overall_text_boxes[box_no]
  371. )
  372. > 0.5
  373. ):
  374. rec_res["boxes"].append(overall_text_boxes[box_no])
  375. rec_res["rec_texts"].append(
  376. overall_ocr_res["rec_texts"][box_no],
  377. )
  378. rec_res["flag"] = True
  379. if rec_res["flag"]:
  380. rec_res = _sort_ocr_res_by_y_projection(
  381. label, layout_bbox, rec_res, 0.7
  382. )
  383. rec_res_first_bbox = rec_res["boxes"][0]
  384. rec_res_end_bbox = rec_res["boxes"][-1]
  385. if rec_res_first_bbox[0] - layout_bbox[0] < 10:
  386. seg_start_flag = False
  387. if layout_bbox[2] - rec_res_end_bbox[2] < 10:
  388. seg_end_flag = False
  389. if label == "formula":
  390. rec_res["rec_texts"] = [
  391. rec_res_text.replace("$", "")
  392. for rec_res_text in rec_res["rec_texts"]
  393. ]
  394. if label in ["chart", "image", "seal"]:
  395. single_block_layout_parsing_res.append(
  396. {
  397. "label": label,
  398. f"{label}": {
  399. "img": input_img[
  400. int(layout_bbox[1]) : int(layout_bbox[3]),
  401. int(layout_bbox[0]) : int(layout_bbox[2]),
  402. ],
  403. },
  404. "layout_bbox": layout_bbox,
  405. "seg_start_flag": seg_start_flag,
  406. "seg_end_flag": seg_end_flag,
  407. },
  408. )
  409. else:
  410. single_block_layout_parsing_res.append(
  411. {
  412. "label": label,
  413. f"{label}": "".join(rec_res["rec_texts"]),
  414. "layout_bbox": layout_bbox,
  415. "seg_start_flag": seg_start_flag,
  416. "seg_end_flag": seg_end_flag,
  417. },
  418. )
  419. return single_block_layout_parsing_res
  420. def _projection_by_bboxes(boxes: np.ndarray, axis: int) -> np.ndarray:
  421. """
  422. Generate a 1D projection histogram from bounding boxes along a specified axis.
  423. Args:
  424. boxes: A (N, 4) array of bounding boxes defined by [x_min, y_min, x_max, y_max].
  425. axis: Axis for projection; 0 for horizontal (x-axis), 1 for vertical (y-axis).
  426. Returns:
  427. A 1D numpy array representing the projection histogram based on bounding box intervals.
  428. """
  429. assert axis in [0, 1]
  430. max_length = np.max(boxes[:, axis::2])
  431. projection = np.zeros(max_length, dtype=int)
  432. # Increment projection histogram over the interval defined by each bounding box
  433. for start, end in boxes[:, axis::2]:
  434. projection[start:end] += 1
  435. return projection
  436. def _split_projection_profile(arr_values: np.ndarray, min_value: float, min_gap: float):
  437. """
  438. Split the projection profile into segments based on specified thresholds.
  439. Args:
  440. arr_values: 1D array representing the projection profile.
  441. min_value: Minimum value threshold to consider a profile segment significant.
  442. min_gap: Minimum gap width to consider a separation between segments.
  443. Returns:
  444. A tuple of start and end indices for each segment that meets the criteria.
  445. """
  446. # Identify indices where the projection exceeds the minimum value
  447. significant_indices = np.where(arr_values > min_value)[0]
  448. if not len(significant_indices):
  449. return
  450. # Calculate gaps between significant indices
  451. index_diffs = significant_indices[1:] - significant_indices[:-1]
  452. gap_indices = np.where(index_diffs > min_gap)[0]
  453. # Determine start and end indices of segments
  454. segment_starts = np.insert(
  455. significant_indices[gap_indices + 1],
  456. 0,
  457. significant_indices[0],
  458. )
  459. segment_ends = np.append(
  460. significant_indices[gap_indices],
  461. significant_indices[-1] + 1,
  462. )
  463. return segment_starts, segment_ends
  464. def _recursive_yx_cut(
  465. boxes: np.ndarray, indices: List[int], res: List[int], min_gap: int = 1
  466. ):
  467. """
  468. Recursively project and segment bounding boxes, starting with Y-axis and followed by X-axis.
  469. Args:
  470. boxes: A (N, 4) array representing bounding boxes.
  471. indices: List of indices indicating the original position of boxes.
  472. res: List to store indices of the final segmented bounding boxes.
  473. min_gap (int): Minimum gap width to consider a separation between segments on the X-axis. Defaults to 1.
  474. Returns:
  475. None: This function modifies the `res` list in place.
  476. """
  477. assert len(boxes) == len(
  478. indices
  479. ), "The length of boxes and indices must be the same."
  480. # Sort by y_min for Y-axis projection
  481. y_sorted_indices = boxes[:, 1].argsort()
  482. y_sorted_boxes = boxes[y_sorted_indices]
  483. y_sorted_indices = np.array(indices)[y_sorted_indices]
  484. # Perform Y-axis projection
  485. y_projection = _projection_by_bboxes(boxes=y_sorted_boxes, axis=1)
  486. y_intervals = _split_projection_profile(y_projection, 0, 1)
  487. if not y_intervals:
  488. return
  489. # Process each segment defined by Y-axis projection
  490. for y_start, y_end in zip(*y_intervals):
  491. # Select boxes within the current y interval
  492. y_interval_indices = (y_start <= y_sorted_boxes[:, 1]) & (
  493. y_sorted_boxes[:, 1] < y_end
  494. )
  495. y_boxes_chunk = y_sorted_boxes[y_interval_indices]
  496. y_indices_chunk = y_sorted_indices[y_interval_indices]
  497. # Sort by x_min for X-axis projection
  498. x_sorted_indices = y_boxes_chunk[:, 0].argsort()
  499. x_sorted_boxes_chunk = y_boxes_chunk[x_sorted_indices]
  500. x_sorted_indices_chunk = y_indices_chunk[x_sorted_indices]
  501. # Perform X-axis projection
  502. x_projection = _projection_by_bboxes(boxes=x_sorted_boxes_chunk, axis=0)
  503. x_intervals = _split_projection_profile(x_projection, 0, min_gap)
  504. if not x_intervals:
  505. continue
  506. # If X-axis cannot be further segmented, add current indices to results
  507. if len(x_intervals[0]) == 1:
  508. res.extend(x_sorted_indices_chunk)
  509. continue
  510. # Recursively process each segment defined by X-axis projection
  511. for x_start, x_end in zip(*x_intervals):
  512. x_interval_indices = (x_start <= x_sorted_boxes_chunk[:, 0]) & (
  513. x_sorted_boxes_chunk[:, 0] < x_end
  514. )
  515. _recursive_yx_cut(
  516. x_sorted_boxes_chunk[x_interval_indices],
  517. x_sorted_indices_chunk[x_interval_indices],
  518. res,
  519. )
  520. def _recursive_xy_cut(
  521. boxes: np.ndarray, indices: List[int], res: List[int], min_gap: int = 1
  522. ):
  523. """
  524. Recursively performs X-axis projection followed by Y-axis projection to segment bounding boxes.
  525. Args:
  526. boxes: A (N, 4) array representing bounding boxes with [x_min, y_min, x_max, y_max].
  527. indices: A list of indices representing the position of boxes in the original data.
  528. res: A list to store indices of bounding boxes that meet the criteria.
  529. min_gap (int): Minimum gap width to consider a separation between segments on the X-axis. Defaults to 1.
  530. Returns:
  531. None: This function modifies the `res` list in place.
  532. """
  533. # Ensure boxes and indices have the same length
  534. assert len(boxes) == len(
  535. indices
  536. ), "The length of boxes and indices must be the same."
  537. # Sort by x_min to prepare for X-axis projection
  538. x_sorted_indices = boxes[:, 0].argsort()
  539. x_sorted_boxes = boxes[x_sorted_indices]
  540. x_sorted_indices = np.array(indices)[x_sorted_indices]
  541. # Perform X-axis projection
  542. x_projection = _projection_by_bboxes(boxes=x_sorted_boxes, axis=0)
  543. x_intervals = _split_projection_profile(x_projection, 0, 1)
  544. if not x_intervals:
  545. return
  546. # Process each segment defined by X-axis projection
  547. for x_start, x_end in zip(*x_intervals):
  548. # Select boxes within the current x interval
  549. x_interval_indices = (x_start <= x_sorted_boxes[:, 0]) & (
  550. x_sorted_boxes[:, 0] < x_end
  551. )
  552. x_boxes_chunk = x_sorted_boxes[x_interval_indices]
  553. x_indices_chunk = x_sorted_indices[x_interval_indices]
  554. # Sort selected boxes by y_min to prepare for Y-axis projection
  555. y_sorted_indices = x_boxes_chunk[:, 1].argsort()
  556. y_sorted_boxes_chunk = x_boxes_chunk[y_sorted_indices]
  557. y_sorted_indices_chunk = x_indices_chunk[y_sorted_indices]
  558. # Perform Y-axis projection
  559. y_projection = _projection_by_bboxes(boxes=y_sorted_boxes_chunk, axis=1)
  560. y_intervals = _split_projection_profile(y_projection, 0, min_gap)
  561. if not y_intervals:
  562. continue
  563. # If Y-axis cannot be further segmented, add current indices to results
  564. if len(y_intervals[0]) == 1:
  565. res.extend(y_sorted_indices_chunk)
  566. continue
  567. # Recursively process each segment defined by Y-axis projection
  568. for y_start, y_end in zip(*y_intervals):
  569. y_interval_indices = (y_start <= y_sorted_boxes_chunk[:, 1]) & (
  570. y_sorted_boxes_chunk[:, 1] < y_end
  571. )
  572. _recursive_xy_cut(
  573. y_sorted_boxes_chunk[y_interval_indices],
  574. y_sorted_indices_chunk[y_interval_indices],
  575. res,
  576. )
  577. def sort_by_xycut(
  578. block_bboxes: Union[np.ndarray, List[List[int]]],
  579. direction: int = 0,
  580. min_gap: int = 1,
  581. ) -> List[int]:
  582. """
  583. Sort bounding boxes using recursive XY cut method based on the specified direction.
  584. Args:
  585. block_bboxes (Union[np.ndarray, List[List[int]]]): An array or list of bounding boxes,
  586. where each box is represented as
  587. [x_min, y_min, x_max, y_max].
  588. direction (int): Direction for the initial cut. Use 1 for Y-axis first and 0 for X-axis first.
  589. Defaults to 0.
  590. min_gap (int): Minimum gap width to consider a separation between segments. Defaults to 1.
  591. Returns:
  592. List[int]: A list of indices representing the order of sorted bounding boxes.
  593. """
  594. block_bboxes = np.asarray(block_bboxes).astype(int)
  595. res = []
  596. if direction == 1:
  597. _recursive_yx_cut(
  598. block_bboxes,
  599. np.arange(len(block_bboxes)),
  600. res,
  601. min_gap,
  602. )
  603. else:
  604. _recursive_xy_cut(
  605. block_bboxes,
  606. np.arange(len(block_bboxes)),
  607. res,
  608. min_gap,
  609. )
  610. return res
  611. def _img_array2path(data: np.ndarray) -> str:
  612. """
  613. Save an image array to disk and return the relative file path.
  614. Args:
  615. data (np.ndarray): An image represented as a numpy array with 3 dimensions (H, W, C).
  616. Returns:
  617. dict: A dictionary with a single key-value pair formatted as:
  618. {"imgs/image_{uuid4_hex}.png": PIL.Image.Image}
  619. Raises:
  620. ValueError: If the input data is not a valid image array.
  621. """
  622. if isinstance(data, np.ndarray) and data.ndim == 3:
  623. # Generate a unique filename using UUID
  624. img_name = f"image_{uuid.uuid4().hex}.png"
  625. return {f"imgs/{img_name}": Image.fromarray(data[:, :, ::-1])}
  626. else:
  627. raise ValueError(
  628. "Input data must be a 3-dimensional numpy array representing an image."
  629. )
  630. def recursive_img_array2path(
  631. data: Union[Dict[str, Any], List[Any]],
  632. labels: List[str] = [],
  633. ) -> None:
  634. """
  635. Recursively process a dictionary or list to save image arrays to disk
  636. and replace them with file paths.
  637. Args:
  638. data (Union[Dict[str, Any], List[Any]]): The data structure that may contain image arrays.
  639. save_path (Union[str, Path]): The base path where images should be saved.
  640. labels (List[str]): List of keys to check for image arrays in dictionaries.
  641. Returns:
  642. None: This function modifies the input data structure in place.
  643. """
  644. if isinstance(data, dict):
  645. for k, v in data.items():
  646. if k in labels and isinstance(v, np.ndarray) and v.ndim == 3:
  647. data[k] = _img_array2path(v)
  648. else:
  649. recursive_img_array2path(v, labels)
  650. elif isinstance(data, list):
  651. for item in data:
  652. recursive_img_array2path(item, labels)
  653. def _get_minbox_if_overlap_by_ratio(
  654. bbox1: Union[List[int], Tuple[int, int, int, int]],
  655. bbox2: Union[List[int], Tuple[int, int, int, int]],
  656. ratio: float,
  657. smaller: bool = True,
  658. ) -> Optional[Union[List[int], Tuple[int, int, int, int]]]:
  659. """
  660. Determine if the overlap area between two bounding boxes exceeds a given ratio
  661. and return the smaller (or larger) bounding box based on the `smaller` flag.
  662. Args:
  663. bbox1 (Union[List[int], Tuple[int, int, int, int]]): Coordinates of the first bounding box [x_min, y_min, x_max, y_max].
  664. bbox2 (Union[List[int], Tuple[int, int, int, int]]): Coordinates of the second bounding box [x_min, y_min, x_max, y_max].
  665. ratio (float): The overlap ratio threshold.
  666. smaller (bool): If True, return the smaller bounding box; otherwise, return the larger one.
  667. Returns:
  668. Optional[Union[List[int], Tuple[int, int, int, int]]]:
  669. The selected bounding box or None if the overlap ratio is not exceeded.
  670. """
  671. # Calculate the areas of both bounding boxes
  672. area1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
  673. area2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
  674. # Calculate the overlap ratio using a helper function
  675. overlap_ratio = _calculate_overlap_area_div_minbox_area_ratio(bbox1, bbox2)
  676. # Check if the overlap ratio exceeds the threshold
  677. if overlap_ratio > ratio:
  678. if (area1 <= area2 and smaller) or (area1 >= area2 and not smaller):
  679. return 1
  680. else:
  681. return 2
  682. return None
  683. def _remove_overlap_blocks(
  684. blocks: List[Dict[str, List[int]]], threshold: float = 0.65, smaller: bool = True
  685. ) -> Tuple[List[Dict[str, List[int]]], List[Dict[str, List[int]]]]:
  686. """
  687. Remove overlapping blocks based on a specified overlap ratio threshold.
  688. Args:
  689. blocks (List[Dict[str, List[int]]]): List of block dictionaries, each containing a 'layout_bbox' key.
  690. threshold (float): Ratio threshold to determine significant overlap.
  691. smaller (bool): If True, the smaller block in overlap is removed.
  692. Returns:
  693. Tuple[List[Dict[str, List[int]]], List[Dict[str, List[int]]]]:
  694. A tuple containing the updated list of blocks and a list of dropped blocks.
  695. """
  696. dropped_blocks = []
  697. dropped_indexes = set()
  698. # Iterate over each pair of blocks to find overlaps
  699. for i, block1 in enumerate(blocks):
  700. for j in range(i + 1, len(blocks)):
  701. block2 = blocks[j]
  702. # Skip blocks that are already marked for removal
  703. if i in dropped_indexes or j in dropped_indexes:
  704. continue
  705. # Check for overlap and determine which block to remove
  706. overlap_box_index = _get_minbox_if_overlap_by_ratio(
  707. block1["layout_bbox"],
  708. block2["layout_bbox"],
  709. threshold,
  710. smaller=smaller,
  711. )
  712. if overlap_box_index is not None:
  713. # Determine which block to remove based on overlap_box_index
  714. if overlap_box_index == 1:
  715. drop_index = i
  716. else:
  717. drop_index = j
  718. dropped_indexes.add(drop_index)
  719. # Remove marked blocks from the original list
  720. for index in sorted(dropped_indexes, reverse=True):
  721. dropped_blocks.append(blocks[index])
  722. del blocks[index]
  723. return blocks, dropped_blocks
  724. def _get_text_median_width(blocks: List[Dict[str, any]]) -> float:
  725. """
  726. Calculate the median width of blocks labeled as "text".
  727. Args:
  728. blocks (List[Dict[str, any]]): List of block dictionaries, each containing a 'layout_bbox' and 'label'.
  729. Returns:
  730. float: The median width of text blocks, or infinity if no text blocks are found.
  731. """
  732. widths = [
  733. block["layout_bbox"][2] - block["layout_bbox"][0]
  734. for block in blocks
  735. if block.get("label") == "text"
  736. ]
  737. return np.median(widths) if widths else float("inf")
  738. def _get_layout_property(
  739. blocks: List[Dict[str, any]],
  740. median_width: float,
  741. no_mask_labels: List[str],
  742. threshold: float = 0.8,
  743. ) -> Tuple[List[Dict[str, any]], bool]:
  744. """
  745. Determine the layout (single or double column) of text blocks.
  746. Args:
  747. blocks (List[Dict[str, any]]): List of block dictionaries containing 'label' and 'layout_bbox'.
  748. median_width (float): Median width of text blocks.
  749. no_mask_labels (List[str]): Labels of blocks to be considered for layout analysis.
  750. threshold (float): Threshold for determining layout overlap.
  751. Returns:
  752. Tuple[List[Dict[str, any]], bool]: Updated list of blocks with layout information and a boolean
  753. indicating if the double layout area is greater than the single layout area.
  754. """
  755. blocks.sort(
  756. key=lambda x: (
  757. x["layout_bbox"][0],
  758. (x["layout_bbox"][2] - x["layout_bbox"][0]),
  759. ),
  760. )
  761. check_single_layout = {}
  762. page_min_x, page_max_x = float("inf"), 0
  763. double_label_area = 0
  764. single_label_area = 0
  765. for i, block in enumerate(blocks):
  766. page_min_x = min(page_min_x, block["layout_bbox"][0])
  767. page_max_x = max(page_max_x, block["layout_bbox"][2])
  768. page_width = page_max_x - page_min_x
  769. for i, block in enumerate(blocks):
  770. if block["label"] not in no_mask_labels:
  771. continue
  772. x_min_i, _, x_max_i, _ = block["layout_bbox"]
  773. layout_length = x_max_i - x_min_i
  774. cover_count, cover_with_threshold_count = 0, 0
  775. match_block_with_threshold_indexes = []
  776. for j, other_block in enumerate(blocks):
  777. if i == j or other_block["label"] not in no_mask_labels:
  778. continue
  779. x_min_j, _, x_max_j, _ = other_block["layout_bbox"]
  780. x_match_min, x_match_max = max(
  781. x_min_i,
  782. x_min_j,
  783. ), min(x_max_i, x_max_j)
  784. match_block_iou = (x_match_max - x_match_min) / (x_max_j - x_min_j)
  785. if match_block_iou > 0:
  786. cover_count += 1
  787. if match_block_iou > threshold:
  788. cover_with_threshold_count += 1
  789. match_block_with_threshold_indexes.append(
  790. (j, match_block_iou),
  791. )
  792. x_min_i = x_match_max
  793. if x_min_i >= x_max_i:
  794. break
  795. if (
  796. layout_length > median_width * 1.3
  797. and (cover_with_threshold_count >= 2 or cover_count >= 2)
  798. ) or layout_length > 0.6 * page_width:
  799. # if layout_length > median_width * 1.3 and (cover_with_threshold_count >= 2):
  800. block["layout"] = "double"
  801. double_label_area += (block["layout_bbox"][2] - block["layout_bbox"][0]) * (
  802. block["layout_bbox"][3] - block["layout_bbox"][1]
  803. )
  804. else:
  805. block["layout"] = "single"
  806. check_single_layout[i] = match_block_with_threshold_indexes
  807. # Check single-layout block
  808. for i, single_layout in check_single_layout.items():
  809. if single_layout:
  810. index, match_iou = single_layout[-1]
  811. if match_iou > 0.9 and blocks[index]["layout"] == "double":
  812. blocks[i]["layout"] = "double"
  813. double_label_area += (
  814. blocks[i]["layout_bbox"][2] - blocks[i]["layout_bbox"][0]
  815. ) * (blocks[i]["layout_bbox"][3] - blocks[i]["layout_bbox"][1])
  816. else:
  817. single_label_area += (
  818. blocks[i]["layout_bbox"][2] - blocks[i]["layout_bbox"][0]
  819. ) * (blocks[i]["layout_bbox"][3] - blocks[i]["layout_bbox"][1])
  820. return blocks, (double_label_area > single_label_area)
  821. def _get_bbox_direction(input_bbox: List[float], ratio: float = 1.0) -> bool:
  822. """
  823. Determine if a bounding box is horizontal or vertical.
  824. Args:
  825. input_bbox (List[float]): Bounding box [x_min, y_min, x_max, y_max].
  826. ratio (float): Ratio for determining orientation. Default is 1.0.
  827. Returns:
  828. bool: True if the bounding box is considered horizontal, False if vertical.
  829. """
  830. width = input_bbox[2] - input_bbox[0]
  831. height = input_bbox[3] - input_bbox[1]
  832. return width * ratio >= height
  833. def _get_projection_iou(
  834. input_bbox: List[float], match_bbox: List[float], is_horizontal: bool = True
  835. ) -> float:
  836. """
  837. Calculate the IoU of lines between two bounding boxes.
  838. Args:
  839. input_bbox (List[float]): First bounding box [x_min, y_min, x_max, y_max].
  840. match_bbox (List[float]): Second bounding box [x_min, y_min, x_max, y_max].
  841. is_horizontal (bool): Whether to compare horizontally or vertically.
  842. Returns:
  843. float: Line IoU. Returns 0 if there is no overlap.
  844. """
  845. if is_horizontal:
  846. x_match_min = max(input_bbox[0], match_bbox[0])
  847. x_match_max = min(input_bbox[2], match_bbox[2])
  848. overlap = max(0, x_match_max - x_match_min)
  849. input_width = input_bbox[2] - input_bbox[0]
  850. else:
  851. y_match_min = max(input_bbox[1], match_bbox[1])
  852. y_match_max = min(input_bbox[3], match_bbox[3])
  853. overlap = max(0, y_match_max - y_match_min)
  854. input_width = input_bbox[3] - input_bbox[1]
  855. return overlap / input_width if input_width > 0 else 0.0
  856. def _get_sub_category(
  857. blocks: List[Dict[str, Any]], title_labels: List[str]
  858. ) -> List[Dict[str, Any]]:
  859. """
  860. Determine the layout of title and text blocks.
  861. Args:
  862. blocks (List[Dict[str, Any]]): List of block dictionaries.
  863. title_labels (List[str]): List of labels considered as titles.
  864. Returns:
  865. List[Dict[str, Any]]: Updated list of blocks with title-text layout information.
  866. """
  867. sub_title_labels = ["paragraph_title"]
  868. vision_labels = ["image", "table", "chart", "figure"]
  869. for i, block1 in enumerate(blocks):
  870. block1.setdefault("title_text", [])
  871. block1.setdefault("sub_title", [])
  872. block1.setdefault("vision_footnote", [])
  873. block1.setdefault("sub_label", block1["label"])
  874. if (
  875. block1["label"] not in title_labels
  876. and block1["label"] not in sub_title_labels
  877. and block1["label"] not in vision_labels
  878. ):
  879. continue
  880. bbox1 = block1["layout_bbox"]
  881. x1, y1, x2, y2 = bbox1
  882. is_horizontal_1 = _get_bbox_direction(block1["layout_bbox"])
  883. left_up_title_text_distance = float("inf")
  884. left_up_title_text_index = -1
  885. left_up_title_text_direction = None
  886. right_down_title_text_distance = float("inf")
  887. right_down_title_text_index = -1
  888. right_down_title_text_direction = None
  889. for j, block2 in enumerate(blocks):
  890. if i == j:
  891. continue
  892. bbox2 = block2["layout_bbox"]
  893. x1_prime, y1_prime, x2_prime, y2_prime = bbox2
  894. is_horizontal_2 = _get_bbox_direction(bbox2)
  895. match_block_iou = _get_projection_iou(
  896. bbox2,
  897. bbox1,
  898. is_horizontal_1,
  899. )
  900. def distance_(is_horizontal, is_left_up):
  901. if is_horizontal:
  902. if is_left_up:
  903. return (y1 - y2_prime + 2) // 5 + x1_prime / 5000
  904. else:
  905. return (y1_prime - y2 + 2) // 5 + x1_prime / 5000
  906. else:
  907. if is_left_up:
  908. return (x1 - x2_prime + 2) // 5 + y1_prime / 5000
  909. else:
  910. return (x1_prime - x2 + 2) // 5 + y1_prime / 5000
  911. block_iou_threshold = 0.1
  912. if block1["label"] in sub_title_labels:
  913. match_block_iou = _calculate_overlap_area_div_minbox_area_ratio(
  914. bbox2,
  915. bbox1,
  916. )
  917. block_iou_threshold = 0.7
  918. if is_horizontal_1:
  919. if match_block_iou >= block_iou_threshold:
  920. left_up_distance = distance_(True, True)
  921. right_down_distance = distance_(True, False)
  922. if (
  923. y2_prime <= y1
  924. and left_up_distance <= left_up_title_text_distance
  925. ):
  926. left_up_title_text_distance = left_up_distance
  927. left_up_title_text_index = j
  928. left_up_title_text_direction = is_horizontal_2
  929. elif (
  930. y1_prime > y2
  931. and right_down_distance < right_down_title_text_distance
  932. ):
  933. right_down_title_text_distance = right_down_distance
  934. right_down_title_text_index = j
  935. right_down_title_text_direction = is_horizontal_2
  936. else:
  937. if match_block_iou >= block_iou_threshold:
  938. left_up_distance = distance_(False, True)
  939. right_down_distance = distance_(False, False)
  940. if (
  941. x2_prime <= x1
  942. and left_up_distance <= left_up_title_text_distance
  943. ):
  944. left_up_title_text_distance = left_up_distance
  945. left_up_title_text_index = j
  946. left_up_title_text_direction = is_horizontal_2
  947. elif (
  948. x1_prime > x2
  949. and right_down_distance < right_down_title_text_distance
  950. ):
  951. right_down_title_text_distance = right_down_distance
  952. right_down_title_text_index = j
  953. right_down_title_text_direction = is_horizontal_2
  954. height = bbox1[3] - bbox1[1]
  955. width = bbox1[2] - bbox1[0]
  956. title_text_weight = [0.8, 0.8]
  957. title_text, sub_title, vision_footnote = [], [], []
  958. def get_sub_category_(
  959. title_text_direction,
  960. title_text_index,
  961. label,
  962. is_left_up=True,
  963. ):
  964. direction_ = [1, 3] if is_left_up else [2, 4]
  965. if (
  966. title_text_direction == is_horizontal_1
  967. and title_text_index != -1
  968. and (label == "text" or label == "paragraph_title")
  969. ):
  970. bbox2 = blocks[title_text_index]["layout_bbox"]
  971. if is_horizontal_1:
  972. height1 = bbox2[3] - bbox2[1]
  973. width1 = bbox2[2] - bbox2[0]
  974. if label == "text":
  975. if (
  976. _nearest_edge_distance(bbox1, bbox2)[0] <= 15
  977. and block1["label"] in vision_labels
  978. and width1 < width
  979. and height1 < 0.5 * height
  980. ):
  981. blocks[title_text_index]["sub_label"] = "vision_footnote"
  982. vision_footnote.append(bbox2)
  983. elif (
  984. height1 < height * title_text_weight[0]
  985. and (width1 < width or width1 > 1.5 * width)
  986. and block1["label"] in title_labels
  987. ):
  988. blocks[title_text_index]["sub_label"] = "title_text"
  989. title_text.append((direction_[0], bbox2))
  990. elif (
  991. label == "paragraph_title"
  992. and block1["label"] in sub_title_labels
  993. ):
  994. sub_title.append(bbox2)
  995. else:
  996. height1 = bbox2[3] - bbox2[1]
  997. width1 = bbox2[2] - bbox2[0]
  998. if label == "text":
  999. if (
  1000. _nearest_edge_distance(bbox1, bbox2)[0] <= 15
  1001. and block1["label"] in vision_labels
  1002. and height1 < height
  1003. and width1 < 0.5 * width
  1004. ):
  1005. blocks[title_text_index]["sub_label"] = "vision_footnote"
  1006. vision_footnote.append(bbox2)
  1007. elif (
  1008. width1 < width * title_text_weight[1]
  1009. and block1["label"] in title_labels
  1010. ):
  1011. blocks[title_text_index]["sub_label"] = "title_text"
  1012. title_text.append((direction_[1], bbox2))
  1013. elif (
  1014. label == "paragraph_title"
  1015. and block1["label"] in sub_title_labels
  1016. ):
  1017. sub_title.append(bbox2)
  1018. if (
  1019. is_horizontal_1
  1020. and abs(left_up_title_text_distance - right_down_title_text_distance) * 5
  1021. > height
  1022. ) or (
  1023. not is_horizontal_1
  1024. and abs(left_up_title_text_distance - right_down_title_text_distance) * 5
  1025. > width
  1026. ):
  1027. if left_up_title_text_distance < right_down_title_text_distance:
  1028. get_sub_category_(
  1029. left_up_title_text_direction,
  1030. left_up_title_text_index,
  1031. blocks[left_up_title_text_index]["label"],
  1032. True,
  1033. )
  1034. else:
  1035. get_sub_category_(
  1036. right_down_title_text_direction,
  1037. right_down_title_text_index,
  1038. blocks[right_down_title_text_index]["label"],
  1039. False,
  1040. )
  1041. else:
  1042. get_sub_category_(
  1043. left_up_title_text_direction,
  1044. left_up_title_text_index,
  1045. blocks[left_up_title_text_index]["label"],
  1046. True,
  1047. )
  1048. get_sub_category_(
  1049. right_down_title_text_direction,
  1050. right_down_title_text_index,
  1051. blocks[right_down_title_text_index]["label"],
  1052. False,
  1053. )
  1054. if block1["label"] in title_labels:
  1055. if blocks[i].get("title_text") == []:
  1056. blocks[i]["title_text"] = title_text
  1057. if block1["label"] in sub_title_labels:
  1058. if blocks[i].get("sub_title") == []:
  1059. blocks[i]["sub_title"] = sub_title
  1060. if block1["label"] in vision_labels:
  1061. if blocks[i].get("vision_footnote") == []:
  1062. blocks[i]["vision_footnote"] = vision_footnote
  1063. return blocks
  1064. def get_layout_ordering(
  1065. data: List[Dict[str, Any]],
  1066. no_mask_labels: List[str] = [],
  1067. already_sorted: bool = False,
  1068. ) -> None:
  1069. """
  1070. Process layout parsing results to remove overlapping bounding boxes
  1071. and assign an ordering index based on their positions.
  1072. Modifies:
  1073. The 'data' list by adding an 'index' to each block.
  1074. Args:
  1075. data (List[Dict[str, Any]]): List of block dictionaries with 'layout_bbox' and 'label'.
  1076. no_mask_labels (List[str]): Labels for which overlapping removal is not performed.
  1077. already_sorted (bool): Assumes data is already sorted by position if True.
  1078. """
  1079. if already_sorted:
  1080. return data
  1081. title_text_labels = ["doc_title"]
  1082. title_labels = ["doc_title", "paragraph_title"]
  1083. vision_labels = ["image", "table", "seal", "chart", "figure"]
  1084. vision_title_labels = ["table_title", "chart_title", "figure_title"]
  1085. parsing_result = data["sub_blocks"]
  1086. parsing_result, _ = _remove_overlap_blocks(
  1087. parsing_result,
  1088. threshold=0.5,
  1089. smaller=True,
  1090. )
  1091. parsing_result = _get_sub_category(parsing_result, title_text_labels)
  1092. doc_flag = False
  1093. median_width = _get_text_median_width(parsing_result)
  1094. parsing_result, projection_direction = _get_layout_property(
  1095. parsing_result,
  1096. median_width,
  1097. no_mask_labels=no_mask_labels,
  1098. threshold=0.3,
  1099. )
  1100. # Convert bounding boxes to float and remove overlaps
  1101. (
  1102. double_text_blocks,
  1103. title_text_blocks,
  1104. title_blocks,
  1105. vision_blocks,
  1106. vision_title_blocks,
  1107. vision_footnote_blocks,
  1108. other_blocks,
  1109. ) = ([], [], [], [], [], [], [])
  1110. drop_indexes = []
  1111. for index, block in enumerate(parsing_result):
  1112. label = block["sub_label"]
  1113. block["layout_bbox"] = list(map(int, block["layout_bbox"]))
  1114. if label == "doc_title":
  1115. doc_flag = True
  1116. if label in no_mask_labels:
  1117. if block["layout"] == "double":
  1118. double_text_blocks.append(block)
  1119. drop_indexes.append(index)
  1120. elif label == "title_text":
  1121. title_text_blocks.append(block)
  1122. drop_indexes.append(index)
  1123. elif label == "vision_footnote":
  1124. vision_footnote_blocks.append(block)
  1125. drop_indexes.append(index)
  1126. elif label in vision_title_labels:
  1127. vision_title_blocks.append(block)
  1128. drop_indexes.append(index)
  1129. elif label in title_labels:
  1130. title_blocks.append(block)
  1131. drop_indexes.append(index)
  1132. elif label in vision_labels:
  1133. vision_blocks.append(block)
  1134. drop_indexes.append(index)
  1135. else:
  1136. other_blocks.append(block)
  1137. drop_indexes.append(index)
  1138. for index in sorted(drop_indexes, reverse=True):
  1139. del parsing_result[index]
  1140. if len(parsing_result) > 0:
  1141. # single text label
  1142. if len(double_text_blocks) > len(parsing_result) or projection_direction:
  1143. parsing_result.extend(title_blocks + double_text_blocks)
  1144. title_blocks = []
  1145. double_text_blocks = []
  1146. block_bboxes = [block["layout_bbox"] for block in parsing_result]
  1147. block_bboxes.sort(
  1148. key=lambda x: (
  1149. x[0] // max(20, median_width),
  1150. x[1],
  1151. ),
  1152. )
  1153. block_bboxes = np.array(block_bboxes)
  1154. sorted_indices = sort_by_xycut(
  1155. block_bboxes,
  1156. direction=1,
  1157. min_gap=1,
  1158. )
  1159. else:
  1160. block_bboxes = [block["layout_bbox"] for block in parsing_result]
  1161. block_bboxes.sort(key=lambda x: (x[0] // 20, x[1]))
  1162. block_bboxes = np.array(block_bboxes)
  1163. sorted_indices = sort_by_xycut(
  1164. block_bboxes,
  1165. direction=0,
  1166. min_gap=20,
  1167. )
  1168. sorted_boxes = block_bboxes[sorted_indices].tolist()
  1169. for block in parsing_result:
  1170. block["index"] = sorted_boxes.index(block["layout_bbox"]) + 1
  1171. block["sub_index"] = sorted_boxes.index(block["layout_bbox"]) + 1
  1172. def nearest_match_(input_blocks, distance_type="manhattan", is_add_index=True):
  1173. for block in input_blocks:
  1174. bbox = block["layout_bbox"]
  1175. min_distance = float("inf")
  1176. min_distance_config = [
  1177. [float("inf"), float("inf")],
  1178. float("inf"),
  1179. float("inf"),
  1180. ] # for double text
  1181. nearest_gt_index = 0
  1182. for match_block in parsing_result:
  1183. match_bbox = match_block["layout_bbox"]
  1184. if distance_type == "nearest_iou_edge_distance":
  1185. distance, min_distance_config = _nearest_iou_edge_distance(
  1186. bbox,
  1187. match_bbox,
  1188. block["sub_label"],
  1189. vision_labels=vision_labels,
  1190. no_mask_labels=no_mask_labels,
  1191. median_width=median_width,
  1192. title_labels=title_labels,
  1193. title_text=block["title_text"],
  1194. sub_title=block["sub_title"],
  1195. min_distance_config=min_distance_config,
  1196. tolerance_len=10,
  1197. )
  1198. elif distance_type == "title_text":
  1199. if (
  1200. match_block["label"] in title_labels + ["abstract"]
  1201. and match_block["title_text"] != []
  1202. ):
  1203. iou_left_up = _calculate_overlap_area_div_minbox_area_ratio(
  1204. bbox,
  1205. match_block["title_text"][0][1],
  1206. )
  1207. iou_right_down = _calculate_overlap_area_div_minbox_area_ratio(
  1208. bbox,
  1209. match_block["title_text"][-1][1],
  1210. )
  1211. iou = 1 - max(iou_left_up, iou_right_down)
  1212. distance = _manhattan_distance(bbox, match_bbox) * iou
  1213. else:
  1214. distance = float("inf")
  1215. elif distance_type == "manhattan":
  1216. distance = _manhattan_distance(bbox, match_bbox)
  1217. elif distance_type == "vision_footnote":
  1218. if (
  1219. match_block["label"] in vision_labels
  1220. and match_block["vision_footnote"] != []
  1221. ):
  1222. iou_left_up = _calculate_overlap_area_div_minbox_area_ratio(
  1223. bbox,
  1224. match_block["vision_footnote"][0],
  1225. )
  1226. iou_right_down = _calculate_overlap_area_div_minbox_area_ratio(
  1227. bbox,
  1228. match_block["vision_footnote"][-1],
  1229. )
  1230. iou = 1 - max(iou_left_up, iou_right_down)
  1231. distance = _manhattan_distance(bbox, match_bbox) * iou
  1232. else:
  1233. distance = float("inf")
  1234. elif distance_type == "vision_body":
  1235. if (
  1236. match_block["label"] in vision_title_labels
  1237. and block["vision_footnote"] != []
  1238. ):
  1239. iou_left_up = _calculate_overlap_area_div_minbox_area_ratio(
  1240. match_bbox,
  1241. block["vision_footnote"][0],
  1242. )
  1243. iou_right_down = _calculate_overlap_area_div_minbox_area_ratio(
  1244. match_bbox,
  1245. block["vision_footnote"][-1],
  1246. )
  1247. iou = 1 - max(iou_left_up, iou_right_down)
  1248. distance = _manhattan_distance(bbox, match_bbox) * iou
  1249. else:
  1250. distance = float("inf")
  1251. else:
  1252. raise NotImplementedError
  1253. if distance < min_distance:
  1254. min_distance = distance
  1255. if is_add_index:
  1256. nearest_gt_index = match_block.get("index", 999)
  1257. else:
  1258. nearest_gt_index = match_block.get("sub_index", 999)
  1259. if is_add_index:
  1260. block["index"] = nearest_gt_index
  1261. else:
  1262. block["sub_index"] = nearest_gt_index
  1263. parsing_result.append(block)
  1264. # double text label
  1265. double_text_blocks.sort(
  1266. key=lambda x: (
  1267. x["layout_bbox"][1] // 10,
  1268. x["layout_bbox"][0] // median_width,
  1269. x["layout_bbox"][1] ** 2 + x["layout_bbox"][0] ** 2,
  1270. ),
  1271. )
  1272. nearest_match_(
  1273. double_text_blocks,
  1274. distance_type="nearest_iou_edge_distance",
  1275. )
  1276. parsing_result.sort(
  1277. key=lambda x: (x["index"], x["layout_bbox"][1], x["layout_bbox"][0]),
  1278. )
  1279. for idx, block in enumerate(parsing_result):
  1280. block["index"] = idx + 1
  1281. block["sub_index"] = idx + 1
  1282. # title label
  1283. title_blocks.sort(
  1284. key=lambda x: (
  1285. x["layout_bbox"][1] // 10,
  1286. x["layout_bbox"][0] // median_width,
  1287. x["layout_bbox"][1] ** 2 + x["layout_bbox"][0] ** 2,
  1288. ),
  1289. )
  1290. nearest_match_(title_blocks, distance_type="nearest_iou_edge_distance")
  1291. if doc_flag:
  1292. text_sort_labels = ["doc_title"]
  1293. text_label_priority = {
  1294. label: priority for priority, label in enumerate(text_sort_labels)
  1295. }
  1296. doc_titles = []
  1297. for i, block in enumerate(parsing_result):
  1298. if block["label"] == "doc_title":
  1299. doc_titles.append(
  1300. (i, block["layout_bbox"][1], block["layout_bbox"][0]),
  1301. )
  1302. doc_titles.sort(key=lambda x: (x[1], x[2]))
  1303. first_doc_title_index = doc_titles[0][0]
  1304. parsing_result[first_doc_title_index]["index"] = 1
  1305. parsing_result.sort(
  1306. key=lambda x: (
  1307. x["index"],
  1308. text_label_priority.get(x["label"], 9999),
  1309. x["layout_bbox"][1],
  1310. x["layout_bbox"][0],
  1311. ),
  1312. )
  1313. else:
  1314. parsing_result.sort(
  1315. key=lambda x: (
  1316. x["index"],
  1317. x["layout_bbox"][1],
  1318. x["layout_bbox"][0],
  1319. ),
  1320. )
  1321. for idx, block in enumerate(parsing_result):
  1322. block["index"] = idx + 1
  1323. block["sub_index"] = idx + 1
  1324. # title-text label
  1325. nearest_match_(title_text_blocks, distance_type="title_text")
  1326. text_sort_labels = ["doc_title", "paragraph_title", "title_text"]
  1327. text_label_priority = {
  1328. label: priority for priority, label in enumerate(text_sort_labels)
  1329. }
  1330. parsing_result.sort(
  1331. key=lambda x: (
  1332. x["index"],
  1333. text_label_priority.get(x["sub_label"], 9999),
  1334. x["layout_bbox"][1],
  1335. x["layout_bbox"][0],
  1336. ),
  1337. )
  1338. for idx, block in enumerate(parsing_result):
  1339. block["index"] = idx + 1
  1340. block["sub_index"] = idx + 1
  1341. # image,figure,chart,seal label
  1342. nearest_match_(
  1343. vision_title_blocks,
  1344. distance_type="nearest_iou_edge_distance",
  1345. is_add_index=False,
  1346. )
  1347. parsing_result.sort(
  1348. key=lambda x: (
  1349. x["sub_index"],
  1350. x["layout_bbox"][1],
  1351. x["layout_bbox"][0],
  1352. ),
  1353. )
  1354. for idx, block in enumerate(parsing_result):
  1355. block["sub_index"] = idx + 1
  1356. # image,figure,chart,seal label
  1357. nearest_match_(
  1358. vision_blocks,
  1359. distance_type="nearest_iou_edge_distance",
  1360. is_add_index=False,
  1361. )
  1362. parsing_result.sort(
  1363. key=lambda x: (
  1364. x["sub_index"],
  1365. x["layout_bbox"][1],
  1366. x["layout_bbox"][0],
  1367. ),
  1368. )
  1369. for idx, block in enumerate(parsing_result):
  1370. block["sub_index"] = idx + 1
  1371. # vision footnote label
  1372. nearest_match_(
  1373. vision_footnote_blocks,
  1374. distance_type="vision_footnote",
  1375. is_add_index=False,
  1376. )
  1377. text_label_priority = {"vision_footnote": 9999}
  1378. parsing_result.sort(
  1379. key=lambda x: (
  1380. x["sub_index"],
  1381. text_label_priority.get(x["sub_label"], 0),
  1382. x["layout_bbox"][1],
  1383. x["layout_bbox"][0],
  1384. ),
  1385. )
  1386. for idx, block in enumerate(parsing_result):
  1387. block["sub_index"] = idx + 1
  1388. # header、footnote、header_image... label
  1389. nearest_match_(other_blocks, distance_type="manhattan", is_add_index=False)
  1390. return data
  1391. def _manhattan_distance(
  1392. point1: Tuple[float, float],
  1393. point2: Tuple[float, float],
  1394. weight_x: float = 1.0,
  1395. weight_y: float = 1.0,
  1396. ) -> float:
  1397. """
  1398. Calculate the weighted Manhattan distance between two points.
  1399. Args:
  1400. point1 (Tuple[float, float]): The first point as (x, y).
  1401. point2 (Tuple[float, float]): The second point as (x, y).
  1402. weight_x (float): The weight for the x-axis distance. Default is 1.0.
  1403. weight_y (float): The weight for the y-axis distance. Default is 1.0.
  1404. Returns:
  1405. float: The weighted Manhattan distance between the two points.
  1406. """
  1407. return weight_x * abs(point1[0] - point2[0]) + weight_y * abs(point1[1] - point2[1])
  1408. def _calculate_horizontal_distance(
  1409. input_bbox: List[int],
  1410. match_bbox: List[int],
  1411. height: int,
  1412. disperse: int,
  1413. title_text: List[Tuple[int, List[int]]],
  1414. ) -> float:
  1415. """
  1416. Calculate the horizontal distance between two bounding boxes, considering title text adjustments.
  1417. Args:
  1418. input_bbox (List[int]): The bounding box coordinates [x1, y1, x2, y2] of the input object.
  1419. match_bbox (List[int]): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
  1420. height (int): The height of the input bounding box used for normalization.
  1421. disperse (int): The dispersion factor used to normalize the horizontal distance.
  1422. title_text (List[Tuple[int, List[int]]]): A list of tuples containing title text information and their bounding box coordinates.
  1423. Format: [(position_indicator, [x1, y1, x2, y2]), ...].
  1424. Returns:
  1425. float: The calculated horizontal distance taking into account the title text adjustments.
  1426. """
  1427. x1, y1, x2, y2 = input_bbox
  1428. x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
  1429. # Determine vertical distance adjustment based on title text
  1430. if y2 < y1_prime:
  1431. if title_text and title_text[-1][0] == 2:
  1432. y2 += title_text[-1][1][3] - title_text[-1][1][1]
  1433. vertical_adjustment = (y1_prime - y2) * 0.5
  1434. else:
  1435. if title_text and title_text[0][0] == 1:
  1436. y1 -= title_text[0][1][3] - title_text[0][1][1]
  1437. vertical_adjustment = y1 - y2_prime
  1438. # Calculate horizontal distance with adjustments
  1439. horizontal_distance = (
  1440. abs(x2_prime - x1) // disperse
  1441. + vertical_adjustment // height
  1442. + vertical_adjustment / 5000
  1443. )
  1444. return horizontal_distance
  1445. def _calculate_vertical_distance(
  1446. input_bbox: List[int],
  1447. match_bbox: List[int],
  1448. width: int,
  1449. disperse: int,
  1450. title_text: List[Tuple[int, List[int]]],
  1451. ) -> float:
  1452. """
  1453. Calculate the vertical distance between two bounding boxes, considering title text adjustments.
  1454. Args:
  1455. input_bbox (List[int]): The bounding box coordinates [x1, y1, x2, y2] of the input object.
  1456. match_bbox (List[int]): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
  1457. width (int): The width of the input bounding box used for normalization.
  1458. disperse (int): The dispersion factor used to normalize the vertical distance.
  1459. title_text (List[Tuple[int, List[int]]]): A list of tuples containing title text information and their bounding box coordinates.
  1460. Format: [(position_indicator, [x1, y1, x2, y2]), ...].
  1461. Returns:
  1462. float: The calculated vertical distance taking into account the title text adjustments.
  1463. """
  1464. x1, y1, x2, y2 = input_bbox
  1465. x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
  1466. # Determine horizontal distance adjustment based on title text
  1467. if x1 > x2_prime:
  1468. if title_text and title_text[0][0] == 3:
  1469. x1 -= title_text[0][1][2] - title_text[0][1][0]
  1470. horizontal_adjustment = (x1 - x2_prime) * 0.5
  1471. else:
  1472. if title_text and title_text[-1][0] == 4:
  1473. x2 += title_text[-1][1][2] - title_text[-1][1][0]
  1474. horizontal_adjustment = x1_prime - x2
  1475. # Calculate vertical distance with adjustments
  1476. vertical_distance = (
  1477. abs(y2_prime - y1) // disperse
  1478. + horizontal_adjustment // width
  1479. + horizontal_adjustment / 5000
  1480. )
  1481. return vertical_distance
  1482. def _nearest_edge_distance(
  1483. input_bbox: List[int],
  1484. match_bbox: List[int],
  1485. weight: List[float] = [1.0, 1.0, 1.0, 1.0],
  1486. label: str = "text",
  1487. no_mask_labels: List[str] = [],
  1488. min_edge_distances_config: List[float] = [],
  1489. tolerance_len: float = 10.0,
  1490. ) -> Tuple[float, List[float]]:
  1491. """
  1492. Calculate the nearest edge distance between two bounding boxes, considering directional weights.
  1493. Args:
  1494. input_bbox (list): The bounding box coordinates [x1, y1, x2, y2] of the input object.
  1495. match_bbox (list): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
  1496. weight (list, optional): Directional weights for the edge distances [left, right, up, down]. Defaults to [1, 1, 1, 1].
  1497. label (str, optional): The label/type of the object in the bounding box (e.g., 'text'). Defaults to 'text'.
  1498. no_mask_labels (list, optional): Labels for which no masking is applied when calculating edge distances. Defaults to an empty list.
  1499. min_edge_distances_config (list, optional): Configuration for minimum edge distances [min_edge_distance_x, min_edge_distance_y].
  1500. Defaults to [float('inf'), float('inf')].
  1501. tolerance_len (float, optional): The tolerance length for adjusting edge distances. Defaults to 10.
  1502. Returns:
  1503. Tuple[float, List[float]]: A tuple containing:
  1504. - The calculated minimum edge distance between the bounding boxes.
  1505. - A list with the minimum edge distances in the x and y directions.
  1506. """
  1507. match_bbox_iou = _calculate_overlap_area_div_minbox_area_ratio(
  1508. input_bbox,
  1509. match_bbox,
  1510. )
  1511. if match_bbox_iou > 0 and label not in no_mask_labels:
  1512. return 0, [0, 0]
  1513. if not min_edge_distances_config:
  1514. min_edge_distances_config = [float("inf"), float("inf")]
  1515. min_edge_distance_x, min_edge_distance_y = min_edge_distances_config
  1516. x1, y1, x2, y2 = input_bbox
  1517. x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
  1518. direction_num = 0
  1519. distance_x = float("inf")
  1520. distance_y = float("inf")
  1521. distance = [float("inf")] * 4
  1522. # input_bbox is to the left of match_bbox
  1523. if x2 < x1_prime:
  1524. direction_num += 1
  1525. distance[0] = x1_prime - x2
  1526. if abs(distance[0] - min_edge_distance_x) <= tolerance_len:
  1527. distance_x = min_edge_distance_x * weight[0]
  1528. else:
  1529. distance_x = distance[0] * weight[0]
  1530. # input_bbox is to the right of match_bbox
  1531. elif x1 > x2_prime:
  1532. direction_num += 1
  1533. distance[1] = x1 - x2_prime
  1534. if abs(distance[1] - min_edge_distance_x) <= tolerance_len:
  1535. distance_x = min_edge_distance_x * weight[1]
  1536. else:
  1537. distance_x = distance[1] * weight[1]
  1538. elif match_bbox_iou > 0:
  1539. distance[0] = 0
  1540. distance_x = 0
  1541. # input_bbox is above match_bbox
  1542. if y2 < y1_prime:
  1543. direction_num += 1
  1544. distance[2] = y1_prime - y2
  1545. if abs(distance[2] - min_edge_distance_y) <= tolerance_len:
  1546. distance_y = min_edge_distance_y * weight[2]
  1547. else:
  1548. distance_y = distance[2] * weight[2]
  1549. if label in no_mask_labels:
  1550. distance_y = max(0.1, distance_y) * 100
  1551. # input_bbox is below match_bbox
  1552. elif y1 > y2_prime:
  1553. direction_num += 1
  1554. distance[3] = y1 - y2_prime
  1555. if abs(distance[3] - min_edge_distance_y) <= tolerance_len:
  1556. distance_y = min_edge_distance_y * weight[3]
  1557. else:
  1558. distance_y = distance[3] * weight[3]
  1559. elif match_bbox_iou > 0:
  1560. distance[2] = 0
  1561. distance_y = 0
  1562. if direction_num == 2:
  1563. return (distance_x + distance_y), [
  1564. min(distance[0], distance[1]),
  1565. min(distance[2], distance[3]),
  1566. ]
  1567. else:
  1568. return min(distance_x, distance_y), [
  1569. min(distance[0], distance[1]),
  1570. min(distance[2], distance[3]),
  1571. ]
  1572. def _get_weights(label, horizontal):
  1573. """Define weights based on the label and orientation."""
  1574. if label == "doc_title":
  1575. return (
  1576. [1, 0.1, 0.1, 1] if horizontal else [0.2, 0.1, 1, 1]
  1577. ) # left-down , right-left
  1578. elif label in [
  1579. "paragraph_title",
  1580. "abstract",
  1581. "figure_title",
  1582. "chart_title",
  1583. "image",
  1584. "seal",
  1585. "chart",
  1586. "figure",
  1587. ]:
  1588. return [1, 1, 0.1, 1] # down
  1589. else:
  1590. return [1, 1, 1, 0.1] # up
  1591. def _nearest_iou_edge_distance(
  1592. input_bbox: List[int],
  1593. match_bbox: List[int],
  1594. label: str,
  1595. vision_labels: List[str],
  1596. no_mask_labels: List[str],
  1597. median_width: int = -1,
  1598. title_labels: List[str] = [],
  1599. title_text: List[Tuple[int, List[int]]] = [],
  1600. sub_title: List[List[int]] = [],
  1601. min_distance_config: List[float] = [],
  1602. tolerance_len: float = 10.0,
  1603. ) -> Tuple[float, List[float]]:
  1604. """
  1605. Calculate the nearest IOU edge distance between two bounding boxes, considering label types, title adjustments, and minimum distance configurations.
  1606. This function computes the edge distance between two bounding boxes while considering their overlap (IOU) and various adjustments based on label types,
  1607. title text, and subtitle information. It also applies minimum distance configurations and tolerance adjustments.
  1608. Args:
  1609. input_bbox (List[int]): The bounding box coordinates [x1, y1, x2, y2] of the input object.
  1610. match_bbox (List[int]): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
  1611. label (str): The label/type of the object in the bounding box (e.g., 'image', 'text', etc.).
  1612. vision_labels (List[str]): List of labels for vision-related objects (e.g., images, icons).
  1613. no_mask_labels (List[str]): Labels for which no masking is applied when calculating edge distances.
  1614. median_width (int, optional): The median width for title dispersion calculation. Defaults to -1.
  1615. title_labels (List[str], optional): Labels that indicate the object is a title. Defaults to an empty list.
  1616. title_text (List[Tuple[int, List[int]]], optional): Text content associated with title labels, in the format [(position_indicator, [x1, y1, x2, y2]), ...].
  1617. sub_title (List[List[int]], optional): List of subtitle bounding boxes to adjust the input_bbox. Defaults to an empty list.
  1618. min_distance_config (List[float], optional): Configuration for minimum distances [min_edge_distances_config, up_edge_distances_config, total_distance].
  1619. tolerance_len (float, optional): The tolerance length for adjusting edge distances. Defaults to 10.0.
  1620. Returns:
  1621. Tuple[float, List[float]]: A tuple containing:
  1622. - The calculated distance considering IOU and adjustments.
  1623. - The updated minimum distance configuration.
  1624. """
  1625. x1, y1, x2, y2 = input_bbox
  1626. x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
  1627. min_edge_distances_config, up_edge_distances_config, total_distance = (
  1628. min_distance_config
  1629. )
  1630. iou_distance = 0
  1631. if label in vision_labels:
  1632. horizontal1 = horizontal2 = True
  1633. else:
  1634. horizontal1 = _get_bbox_direction(input_bbox)
  1635. horizontal2 = _get_bbox_direction(match_bbox, 3)
  1636. if (
  1637. horizontal1 != horizontal2
  1638. or _get_projection_iou(input_bbox, match_bbox, horizontal1) < 0.01
  1639. ):
  1640. iou_distance = 1
  1641. elif label == "doc_title" or (label in title_labels and title_text):
  1642. # Calculate distance for titles
  1643. disperse = max(1, median_width)
  1644. width = x2 - x1
  1645. height = y2 - y1
  1646. if horizontal1:
  1647. return (
  1648. _calculate_horizontal_distance(
  1649. input_bbox,
  1650. match_bbox,
  1651. height,
  1652. disperse,
  1653. title_text,
  1654. ),
  1655. min_distance_config,
  1656. )
  1657. else:
  1658. return (
  1659. _calculate_vertical_distance(
  1660. input_bbox,
  1661. match_bbox,
  1662. width,
  1663. disperse,
  1664. title_text,
  1665. ),
  1666. min_distance_config,
  1667. )
  1668. # Adjust input_bbox based on sub_title
  1669. if sub_title:
  1670. for sub in sub_title:
  1671. x1_, y1_, x2_, y2_ = sub
  1672. x1, y1, x2, y2 = (
  1673. min(x1, x1_),
  1674. min(
  1675. y1,
  1676. y1_,
  1677. ),
  1678. max(x2, x2_),
  1679. max(y2, y2_),
  1680. )
  1681. input_bbox = [x1, y1, x2, y2]
  1682. # Calculate edge distance
  1683. weight = _get_weights(label, horizontal1)
  1684. if label == "abstract":
  1685. tolerance_len *= 3
  1686. edge_distance, edge_distance_config = _nearest_edge_distance(
  1687. input_bbox,
  1688. match_bbox,
  1689. weight,
  1690. label=label,
  1691. no_mask_labels=no_mask_labels,
  1692. min_edge_distances_config=min_edge_distances_config,
  1693. tolerance_len=tolerance_len,
  1694. )
  1695. # Weights for combining distances
  1696. iou_edge_weight = [10**6, 10**3, 1, 0.001]
  1697. # Calculate up and left edge distances
  1698. up_edge_distance = y1_prime
  1699. left_edge_distance = x1_prime
  1700. if (
  1701. label in no_mask_labels or label == "paragraph_title" or label in vision_labels
  1702. ) and y1 > y2_prime:
  1703. up_edge_distance = -y2_prime
  1704. left_edge_distance = -x2_prime
  1705. min_up_edge_distance = up_edge_distances_config
  1706. if abs(min_up_edge_distance - up_edge_distance) <= tolerance_len:
  1707. up_edge_distance = min_up_edge_distance
  1708. # Calculate total distance
  1709. distance = (
  1710. iou_distance * iou_edge_weight[0]
  1711. + edge_distance * iou_edge_weight[1]
  1712. + up_edge_distance * iou_edge_weight[2]
  1713. + left_edge_distance * iou_edge_weight[3]
  1714. )
  1715. # Update minimum distance configuration if a smaller distance is found
  1716. if total_distance > distance:
  1717. edge_distance_config = [
  1718. min(min_edge_distances_config[0], edge_distance_config[0]),
  1719. min(min_edge_distances_config[1], edge_distance_config[1]),
  1720. ]
  1721. min_distance_config = [
  1722. edge_distance_config,
  1723. min(up_edge_distance, up_edge_distances_config),
  1724. distance,
  1725. ]
  1726. return distance, min_distance_config
  1727. def get_show_color(label: str) -> Tuple:
  1728. label_colors = {
  1729. # Medium Blue (from 'titles_list')
  1730. "paragraph_title": (102, 102, 255, 100),
  1731. "doc_title": (255, 248, 220, 100), # Cornsilk
  1732. # Light Yellow (from 'tables_caption_list')
  1733. "table_title": (255, 255, 102, 100),
  1734. # Sky Blue (from 'imgs_caption_list')
  1735. "figure_title": (102, 178, 255, 100),
  1736. "chart_title": (221, 160, 221, 100), # Plum
  1737. "vision_footnote": (144, 238, 144, 100), # Light Green
  1738. # Deep Purple (from 'texts_list')
  1739. "text": (153, 0, 76, 100),
  1740. # Bright Green (from 'interequations_list')
  1741. "formula": (0, 255, 0, 100),
  1742. "abstract": (255, 239, 213, 100), # Papaya Whip
  1743. # Medium Green (from 'lists_list' and 'indexs_list')
  1744. "content": (40, 169, 92, 100),
  1745. # Neutral Gray (from 'dropped_bbox_list')
  1746. "seal": (158, 158, 158, 100),
  1747. # Olive Yellow (from 'tables_body_list')
  1748. "table": (204, 204, 0, 100),
  1749. # Bright Green (from 'imgs_body_list')
  1750. "image": (153, 255, 51, 100),
  1751. # Bright Green (from 'imgs_body_list')
  1752. "figure": (153, 255, 51, 100),
  1753. "chart": (216, 191, 216, 100), # Thistle
  1754. # Pale Yellow-Green (from 'tables_footnote_list')
  1755. "reference": (229, 255, 204, 100),
  1756. "algorithm": (255, 250, 240, 100), # Floral White
  1757. }
  1758. default_color = (158, 158, 158, 100)
  1759. return label_colors.get(label, default_color)