utils.py 74 KB

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