utils.py 75 KB

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