utils.py 69 KB

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