utils.py 71 KB

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