utils.py 70 KB

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