utils.py 71 KB

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