utils.py 83 KB

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