utils.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228
  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. content = "".join(rec_res["rec_texts"])
  456. if label != "reference":
  457. content = _process_text(content)
  458. single_block_layout_parsing_res.append(
  459. {
  460. "block_label": label,
  461. "block_content": content,
  462. "block_bbox": block_bbox,
  463. "seg_start_flag": seg_start_flag,
  464. "seg_end_flag": seg_end_flag,
  465. },
  466. )
  467. single_block_layout_parsing_res = get_layout_ordering(
  468. single_block_layout_parsing_res,
  469. no_mask_labels=[
  470. "text",
  471. "formula",
  472. "algorithm",
  473. "reference",
  474. "content",
  475. "abstract",
  476. ],
  477. )
  478. return single_block_layout_parsing_res
  479. def _projection_by_bboxes(boxes: np.ndarray, axis: int) -> np.ndarray:
  480. """
  481. Generate a 1D projection histogram from bounding boxes along a specified axis.
  482. Args:
  483. boxes: A (N, 4) array of bounding boxes defined by [x_min, y_min, x_max, y_max].
  484. axis: Axis for projection; 0 for horizontal (x-axis), 1 for vertical (y-axis).
  485. Returns:
  486. A 1D numpy array representing the projection histogram based on bounding box intervals.
  487. """
  488. assert axis in [0, 1]
  489. max_length = np.max(boxes[:, axis::2])
  490. projection = np.zeros(max_length, dtype=int)
  491. # Increment projection histogram over the interval defined by each bounding box
  492. for start, end in boxes[:, axis::2]:
  493. projection[start:end] += 1
  494. return projection
  495. def _split_projection_profile(arr_values: np.ndarray, min_value: float, min_gap: float):
  496. """
  497. Split the projection profile into segments based on specified thresholds.
  498. Args:
  499. arr_values: 1D array representing the projection profile.
  500. min_value: Minimum value threshold to consider a profile segment significant.
  501. min_gap: Minimum gap width to consider a separation between segments.
  502. Returns:
  503. A tuple of start and end indices for each segment that meets the criteria.
  504. """
  505. # Identify indices where the projection exceeds the minimum value
  506. significant_indices = np.where(arr_values > min_value)[0]
  507. if not len(significant_indices):
  508. return
  509. # Calculate gaps between significant indices
  510. index_diffs = significant_indices[1:] - significant_indices[:-1]
  511. gap_indices = np.where(index_diffs > min_gap)[0]
  512. # Determine start and end indices of segments
  513. segment_starts = np.insert(
  514. significant_indices[gap_indices + 1],
  515. 0,
  516. significant_indices[0],
  517. )
  518. segment_ends = np.append(
  519. significant_indices[gap_indices],
  520. significant_indices[-1] + 1,
  521. )
  522. return segment_starts, segment_ends
  523. def _recursive_yx_cut(
  524. boxes: np.ndarray, indices: List[int], res: List[int], min_gap: int = 1
  525. ):
  526. """
  527. Recursively project and segment bounding boxes, starting with Y-axis and followed by X-axis.
  528. Args:
  529. boxes: A (N, 4) array representing bounding boxes.
  530. indices: List of indices indicating the original position of boxes.
  531. res: List to store indices of the final segmented bounding boxes.
  532. min_gap (int): Minimum gap width to consider a separation between segments on the X-axis. Defaults to 1.
  533. Returns:
  534. None: This function modifies the `res` list in place.
  535. """
  536. assert len(boxes) == len(
  537. indices
  538. ), "The length of boxes and indices must be the same."
  539. # Sort by y_min for Y-axis projection
  540. y_sorted_indices = boxes[:, 1].argsort()
  541. y_sorted_boxes = boxes[y_sorted_indices]
  542. y_sorted_indices = np.array(indices)[y_sorted_indices]
  543. # Perform Y-axis projection
  544. y_projection = _projection_by_bboxes(boxes=y_sorted_boxes, axis=1)
  545. y_intervals = _split_projection_profile(y_projection, 0, 1)
  546. if not y_intervals:
  547. return
  548. # Process each segment defined by Y-axis projection
  549. for y_start, y_end in zip(*y_intervals):
  550. # Select boxes within the current y interval
  551. y_interval_indices = (y_start <= y_sorted_boxes[:, 1]) & (
  552. y_sorted_boxes[:, 1] < y_end
  553. )
  554. y_boxes_chunk = y_sorted_boxes[y_interval_indices]
  555. y_indices_chunk = y_sorted_indices[y_interval_indices]
  556. # Sort by x_min for X-axis projection
  557. x_sorted_indices = y_boxes_chunk[:, 0].argsort()
  558. x_sorted_boxes_chunk = y_boxes_chunk[x_sorted_indices]
  559. x_sorted_indices_chunk = y_indices_chunk[x_sorted_indices]
  560. # Perform X-axis projection
  561. x_projection = _projection_by_bboxes(boxes=x_sorted_boxes_chunk, axis=0)
  562. x_intervals = _split_projection_profile(x_projection, 0, min_gap)
  563. if not x_intervals:
  564. continue
  565. # If X-axis cannot be further segmented, add current indices to results
  566. if len(x_intervals[0]) == 1:
  567. res.extend(x_sorted_indices_chunk)
  568. continue
  569. # Recursively process each segment defined by X-axis projection
  570. for x_start, x_end in zip(*x_intervals):
  571. x_interval_indices = (x_start <= x_sorted_boxes_chunk[:, 0]) & (
  572. x_sorted_boxes_chunk[:, 0] < x_end
  573. )
  574. _recursive_yx_cut(
  575. x_sorted_boxes_chunk[x_interval_indices],
  576. x_sorted_indices_chunk[x_interval_indices],
  577. res,
  578. )
  579. def _recursive_xy_cut(
  580. boxes: np.ndarray, indices: List[int], res: List[int], min_gap: int = 1
  581. ):
  582. """
  583. Recursively performs X-axis projection followed by Y-axis projection to segment bounding boxes.
  584. Args:
  585. boxes: A (N, 4) array representing bounding boxes with [x_min, y_min, x_max, y_max].
  586. indices: A list of indices representing the position of boxes in the original data.
  587. res: A list to store indices of bounding boxes that meet the criteria.
  588. min_gap (int): Minimum gap width to consider a separation between segments on the X-axis. Defaults to 1.
  589. Returns:
  590. None: This function modifies the `res` list in place.
  591. """
  592. # Ensure boxes and indices have the same length
  593. assert len(boxes) == len(
  594. indices
  595. ), "The length of boxes and indices must be the same."
  596. # Sort by x_min to prepare for X-axis projection
  597. x_sorted_indices = boxes[:, 0].argsort()
  598. x_sorted_boxes = boxes[x_sorted_indices]
  599. x_sorted_indices = np.array(indices)[x_sorted_indices]
  600. # Perform X-axis projection
  601. x_projection = _projection_by_bboxes(boxes=x_sorted_boxes, axis=0)
  602. x_intervals = _split_projection_profile(x_projection, 0, 1)
  603. if not x_intervals:
  604. return
  605. # Process each segment defined by X-axis projection
  606. for x_start, x_end in zip(*x_intervals):
  607. # Select boxes within the current x interval
  608. x_interval_indices = (x_start <= x_sorted_boxes[:, 0]) & (
  609. x_sorted_boxes[:, 0] < x_end
  610. )
  611. x_boxes_chunk = x_sorted_boxes[x_interval_indices]
  612. x_indices_chunk = x_sorted_indices[x_interval_indices]
  613. # Sort selected boxes by y_min to prepare for Y-axis projection
  614. y_sorted_indices = x_boxes_chunk[:, 1].argsort()
  615. y_sorted_boxes_chunk = x_boxes_chunk[y_sorted_indices]
  616. y_sorted_indices_chunk = x_indices_chunk[y_sorted_indices]
  617. # Perform Y-axis projection
  618. y_projection = _projection_by_bboxes(boxes=y_sorted_boxes_chunk, axis=1)
  619. y_intervals = _split_projection_profile(y_projection, 0, min_gap)
  620. if not y_intervals:
  621. continue
  622. # If Y-axis cannot be further segmented, add current indices to results
  623. if len(y_intervals[0]) == 1:
  624. res.extend(y_sorted_indices_chunk)
  625. continue
  626. # Recursively process each segment defined by Y-axis projection
  627. for y_start, y_end in zip(*y_intervals):
  628. y_interval_indices = (y_start <= y_sorted_boxes_chunk[:, 1]) & (
  629. y_sorted_boxes_chunk[:, 1] < y_end
  630. )
  631. _recursive_xy_cut(
  632. y_sorted_boxes_chunk[y_interval_indices],
  633. y_sorted_indices_chunk[y_interval_indices],
  634. res,
  635. )
  636. def sort_by_xycut(
  637. block_bboxes: Union[np.ndarray, List[List[int]]],
  638. direction: int = 0,
  639. min_gap: int = 1,
  640. ) -> List[int]:
  641. """
  642. Sort bounding boxes using recursive XY cut method based on the specified direction.
  643. Args:
  644. block_bboxes (Union[np.ndarray, List[List[int]]]): An array or list of bounding boxes,
  645. where each box is represented as
  646. [x_min, y_min, x_max, y_max].
  647. direction (int): Direction for the initial cut. Use 1 for Y-axis first and 0 for X-axis first.
  648. Defaults to 0.
  649. min_gap (int): Minimum gap width to consider a separation between segments. Defaults to 1.
  650. Returns:
  651. List[int]: A list of indices representing the order of sorted bounding boxes.
  652. """
  653. block_bboxes = np.asarray(block_bboxes).astype(int)
  654. res = []
  655. if direction == 1:
  656. _recursive_yx_cut(
  657. block_bboxes,
  658. np.arange(len(block_bboxes)).tolist(),
  659. res,
  660. min_gap,
  661. )
  662. else:
  663. _recursive_xy_cut(
  664. block_bboxes,
  665. np.arange(len(block_bboxes)).tolist(),
  666. res,
  667. min_gap,
  668. )
  669. return res
  670. def _img_array2path(data: np.ndarray) -> str:
  671. """
  672. Save an image array to disk and return the relative file path.
  673. Args:
  674. data (np.ndarray): An image represented as a numpy array with 3 dimensions (H, W, C).
  675. Returns:
  676. dict: A dictionary with a single key-value pair formatted as:
  677. {"imgs/image_{uuid4_hex}.png": PIL.Image.Image}
  678. Raises:
  679. ValueError: If the input data is not a valid image array.
  680. """
  681. if isinstance(data, np.ndarray) and data.ndim == 3:
  682. # Generate a unique filename using UUID
  683. img_name = f"image_{uuid.uuid4().hex}.png"
  684. return {f"imgs/{img_name}": Image.fromarray(data[:, :, ::-1])}
  685. else:
  686. raise ValueError(
  687. "Input data must be a 3-dimensional numpy array representing an image."
  688. )
  689. def recursive_img_array2path(
  690. data: Union[Dict[str, Any], List[Any]],
  691. labels: List[str] = [],
  692. ) -> None:
  693. """
  694. Recursively process a dictionary or list to save image arrays to disk
  695. and replace them with file paths.
  696. Args:
  697. data (Union[Dict[str, Any], List[Any]]): The data structure that may contain image arrays.
  698. save_path (Union[str, Path]): The base path where images should be saved.
  699. labels (List[str]): List of keys to check for image arrays in dictionaries.
  700. Returns:
  701. None: This function modifies the input data structure in place.
  702. """
  703. if isinstance(data, dict):
  704. for k, v in data.items():
  705. if k in labels and isinstance(v, np.ndarray) and v.ndim == 3:
  706. data[k] = _img_array2path(v)
  707. else:
  708. recursive_img_array2path(v, labels)
  709. elif isinstance(data, list):
  710. for item in data:
  711. recursive_img_array2path(item, labels)
  712. def _get_minbox_if_overlap_by_ratio(
  713. bbox1: Union[List[int], Tuple[int, int, int, int]],
  714. bbox2: Union[List[int], Tuple[int, int, int, int]],
  715. ratio: float,
  716. smaller: bool = True,
  717. ) -> Optional[Union[List[int], Tuple[int, int, int, int]]]:
  718. """
  719. Determine if the overlap area between two bounding boxes exceeds a given ratio
  720. and return the smaller (or larger) bounding box based on the `smaller` flag.
  721. Args:
  722. bbox1 (Union[List[int], Tuple[int, int, int, int]]): Coordinates of the first bounding box [x_min, y_min, x_max, y_max].
  723. bbox2 (Union[List[int], Tuple[int, int, int, int]]): Coordinates of the second bounding box [x_min, y_min, x_max, y_max].
  724. ratio (float): The overlap ratio threshold.
  725. smaller (bool): If True, return the smaller bounding box; otherwise, return the larger one.
  726. Returns:
  727. Optional[Union[List[int], Tuple[int, int, int, int]]]:
  728. The selected bounding box or None if the overlap ratio is not exceeded.
  729. """
  730. # Calculate the areas of both bounding boxes
  731. area1 = (bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1])
  732. area2 = (bbox2[2] - bbox2[0]) * (bbox2[3] - bbox2[1])
  733. # Calculate the overlap ratio using a helper function
  734. overlap_ratio = _calculate_overlap_area_div_minbox_area_ratio(bbox1, bbox2)
  735. # Check if the overlap ratio exceeds the threshold
  736. if overlap_ratio > ratio:
  737. if (area1 <= area2 and smaller) or (area1 >= area2 and not smaller):
  738. return 1
  739. else:
  740. return 2
  741. return None
  742. def _remove_overlap_blocks(
  743. blocks: List[Dict[str, List[int]]], threshold: float = 0.65, smaller: bool = True
  744. ) -> Tuple[List[Dict[str, List[int]]], List[Dict[str, List[int]]]]:
  745. """
  746. Remove overlapping blocks based on a specified overlap ratio threshold.
  747. Args:
  748. blocks (List[Dict[str, List[int]]]): List of block dictionaries, each containing a 'block_bbox' key.
  749. threshold (float): Ratio threshold to determine significant overlap.
  750. smaller (bool): If True, the smaller block in overlap is removed.
  751. Returns:
  752. Tuple[List[Dict[str, List[int]]], List[Dict[str, List[int]]]]:
  753. A tuple containing the updated list of blocks and a list of dropped blocks.
  754. """
  755. dropped_blocks = []
  756. dropped_indexes = set()
  757. # Iterate over each pair of blocks to find overlaps
  758. for i, block1 in enumerate(blocks):
  759. for j in range(i + 1, len(blocks)):
  760. block2 = blocks[j]
  761. # Skip blocks that are already marked for removal
  762. if i in dropped_indexes or j in dropped_indexes:
  763. continue
  764. # Check for overlap and determine which block to remove
  765. overlap_box_index = _get_minbox_if_overlap_by_ratio(
  766. block1["block_bbox"],
  767. block2["block_bbox"],
  768. threshold,
  769. smaller=smaller,
  770. )
  771. if overlap_box_index is not None:
  772. # Determine which block to remove based on overlap_box_index
  773. if overlap_box_index == 1:
  774. drop_index = i
  775. else:
  776. drop_index = j
  777. dropped_indexes.add(drop_index)
  778. # Remove marked blocks from the original list
  779. for index in sorted(dropped_indexes, reverse=True):
  780. dropped_blocks.append(blocks[index])
  781. del blocks[index]
  782. return blocks, dropped_blocks
  783. def _get_text_median_width(blocks: List[Dict[str, any]]) -> float:
  784. """
  785. Calculate the median width of blocks labeled as "text".
  786. Args:
  787. blocks (List[Dict[str, any]]): List of block dictionaries, each containing a 'block_bbox' and 'label'.
  788. Returns:
  789. float: The median width of text blocks, or infinity if no text blocks are found.
  790. """
  791. widths = [
  792. block["block_bbox"][2] - block["block_bbox"][0]
  793. for block in blocks
  794. if block.get("block_label") == "text"
  795. ]
  796. return np.median(widths) if widths else float("inf")
  797. def _get_layout_property(
  798. blocks: List[Dict[str, any]],
  799. median_width: float,
  800. no_mask_labels: List[str],
  801. threshold: float = 0.8,
  802. ) -> Tuple[List[Dict[str, any]], bool]:
  803. """
  804. Determine the layout (single or double column) of text blocks.
  805. Args:
  806. blocks (List[Dict[str, any]]): List of block dictionaries containing 'label' and 'block_bbox'.
  807. median_width (float): Median width of text blocks.
  808. no_mask_labels (List[str]): Labels of blocks to be considered for layout analysis.
  809. threshold (float): Threshold for determining layout overlap.
  810. Returns:
  811. Tuple[List[Dict[str, any]], bool]: Updated list of blocks with layout information and a boolean
  812. indicating if the double layout area is greater than the single layout area.
  813. """
  814. blocks.sort(
  815. key=lambda x: (
  816. x["block_bbox"][0],
  817. (x["block_bbox"][2] - x["block_bbox"][0]),
  818. ),
  819. )
  820. check_single_layout = {}
  821. page_min_x, page_max_x = float("inf"), 0
  822. double_label_area = 0
  823. single_label_area = 0
  824. for i, block in enumerate(blocks):
  825. page_min_x = min(page_min_x, block["block_bbox"][0])
  826. page_max_x = max(page_max_x, block["block_bbox"][2])
  827. page_width = page_max_x - page_min_x
  828. for i, block in enumerate(blocks):
  829. if block["block_label"] not in no_mask_labels:
  830. continue
  831. x_min_i, _, x_max_i, _ = block["block_bbox"]
  832. layout_length = x_max_i - x_min_i
  833. cover_count, cover_with_threshold_count = 0, 0
  834. match_block_with_threshold_indexes = []
  835. for j, other_block in enumerate(blocks):
  836. if i == j or other_block["block_label"] not in no_mask_labels:
  837. continue
  838. x_min_j, _, x_max_j, _ = other_block["block_bbox"]
  839. x_match_min, x_match_max = max(
  840. x_min_i,
  841. x_min_j,
  842. ), min(x_max_i, x_max_j)
  843. match_block_iou = (x_match_max - x_match_min) / (x_max_j - x_min_j)
  844. if match_block_iou > 0:
  845. cover_count += 1
  846. if match_block_iou > threshold:
  847. cover_with_threshold_count += 1
  848. match_block_with_threshold_indexes.append(
  849. (j, match_block_iou),
  850. )
  851. x_min_i = x_match_max
  852. if x_min_i >= x_max_i:
  853. break
  854. if (
  855. layout_length > median_width * 1.3
  856. and (cover_with_threshold_count >= 2 or cover_count >= 2)
  857. ) or layout_length > 0.6 * page_width:
  858. # if layout_length > median_width * 1.3 and (cover_with_threshold_count >= 2):
  859. block["layout"] = "double"
  860. double_label_area += (block["block_bbox"][2] - block["block_bbox"][0]) * (
  861. block["block_bbox"][3] - block["block_bbox"][1]
  862. )
  863. else:
  864. block["layout"] = "single"
  865. check_single_layout[i] = match_block_with_threshold_indexes
  866. # Check single-layout block
  867. for i, single_layout in check_single_layout.items():
  868. if single_layout:
  869. index, match_iou = single_layout[-1]
  870. if match_iou > 0.9 and blocks[index]["layout"] == "double":
  871. blocks[i]["layout"] = "double"
  872. double_label_area += (
  873. blocks[i]["block_bbox"][2] - blocks[i]["block_bbox"][0]
  874. ) * (blocks[i]["block_bbox"][3] - blocks[i]["block_bbox"][1])
  875. else:
  876. single_label_area += (
  877. blocks[i]["block_bbox"][2] - blocks[i]["block_bbox"][0]
  878. ) * (blocks[i]["block_bbox"][3] - blocks[i]["block_bbox"][1])
  879. return blocks, (double_label_area > single_label_area)
  880. def _get_bbox_direction(input_bbox: List[float], ratio: float = 1.0) -> bool:
  881. """
  882. Determine if a bounding box is horizontal or vertical.
  883. Args:
  884. input_bbox (List[float]): Bounding box [x_min, y_min, x_max, y_max].
  885. ratio (float): Ratio for determining orientation. Default is 1.0.
  886. Returns:
  887. bool: True if the bounding box is considered horizontal, False if vertical.
  888. """
  889. width = input_bbox[2] - input_bbox[0]
  890. height = input_bbox[3] - input_bbox[1]
  891. return width * ratio >= height
  892. def _get_projection_iou(
  893. input_bbox: List[float], match_bbox: List[float], is_horizontal: bool = True
  894. ) -> float:
  895. """
  896. Calculate the IoU of lines between two bounding boxes.
  897. Args:
  898. input_bbox (List[float]): First bounding box [x_min, y_min, x_max, y_max].
  899. match_bbox (List[float]): Second bounding box [x_min, y_min, x_max, y_max].
  900. is_horizontal (bool): Whether to compare horizontally or vertically.
  901. Returns:
  902. float: Line IoU. Returns 0 if there is no overlap.
  903. """
  904. if is_horizontal:
  905. x_match_min = max(input_bbox[0], match_bbox[0])
  906. x_match_max = min(input_bbox[2], match_bbox[2])
  907. overlap = max(0, x_match_max - x_match_min)
  908. input_width = min(input_bbox[2] - input_bbox[0], match_bbox[2] - match_bbox[0])
  909. else:
  910. y_match_min = max(input_bbox[1], match_bbox[1])
  911. y_match_max = min(input_bbox[3], match_bbox[3])
  912. overlap = max(0, y_match_max - y_match_min)
  913. input_width = min(input_bbox[3] - input_bbox[1], match_bbox[3] - match_bbox[1])
  914. return overlap / input_width if input_width > 0 else 0.0
  915. def _get_sub_category(
  916. blocks: List[Dict[str, Any]], title_labels: List[str]
  917. ) -> Tuple[List[Dict[str, Any]], List[float]]:
  918. """
  919. Determine the layout of title and text blocks and collect pre_cuts.
  920. Args:
  921. blocks (List[Dict[str, Any]]): List of block dictionaries.
  922. title_labels (List[str]): List of labels considered as titles.
  923. Returns:
  924. List[Dict[str, Any]]: Updated list of blocks with title-text layout information.
  925. Dict[float]: Dict of pre_cuts coordinates.
  926. """
  927. sub_title_labels = ["paragraph_title"]
  928. vision_labels = ["image", "table", "chart", "figure"]
  929. vision_title_labels = ["figure_title", "chart_title", "table_title"]
  930. all_labels = title_labels + sub_title_labels + vision_labels + vision_title_labels
  931. special_pre_cut_labels = sub_title_labels
  932. # single doc title is irregular,pre cut not applicable
  933. num_doc_title = 0
  934. for block in blocks:
  935. if block["block_label"] == "doc_title":
  936. num_doc_title += 1
  937. if num_doc_title == 2:
  938. special_pre_cut_labels = title_labels + sub_title_labels
  939. break
  940. min_x = min(block["block_bbox"][0] for block in blocks)
  941. min_y = min(block["block_bbox"][1] for block in blocks)
  942. max_x = max(block["block_bbox"][2] for block in blocks)
  943. max_y = max(block["block_bbox"][3] for block in blocks)
  944. region_bbox = (min_x, min_y, max_x, max_y)
  945. region_x_center = (region_bbox[0] + region_bbox[2]) / 2
  946. region_y_center = (region_bbox[1] + region_bbox[3]) / 2
  947. region_width = region_bbox[2] - region_bbox[0]
  948. region_height = region_bbox[3] - region_bbox[1]
  949. pre_cuts = {}
  950. for i, block1 in enumerate(blocks):
  951. block1.setdefault("title_text", [])
  952. block1.setdefault("sub_title", [])
  953. block1.setdefault("vision_footnote", [])
  954. block1.setdefault("sub_label", block1["block_label"])
  955. if block1["block_label"] not in all_labels:
  956. continue
  957. bbox1 = block1["block_bbox"]
  958. x1, y1, x2, y2 = bbox1
  959. is_horizontal_1 = _get_bbox_direction(block1["block_bbox"])
  960. left_up_title_text_distance = float("inf")
  961. left_up_title_text_index = -1
  962. left_up_title_text_direction = None
  963. right_down_title_text_distance = float("inf")
  964. right_down_title_text_index = -1
  965. right_down_title_text_direction = None
  966. # pre-cuts
  967. # Condition 1: Length is greater than half of the layout region
  968. if is_horizontal_1:
  969. block_length = x2 - x1
  970. required_length = region_width / 2
  971. else:
  972. block_length = y2 - y1
  973. required_length = region_height / 2
  974. if block1["block_label"] in special_pre_cut_labels:
  975. length_condition = True
  976. else:
  977. length_condition = block_length > required_length
  978. # Condition 2: Centered check (must be within ±20 in both horizontal and vertical directions)
  979. block_x_center = (x1 + x2) / 2
  980. block_y_center = (y1 + y2) / 2
  981. tolerance_len = block_length // 5
  982. if block1["block_label"] in special_pre_cut_labels:
  983. tolerance_len = block_length // 10
  984. if is_horizontal_1:
  985. is_centered = abs(block_x_center - region_x_center) <= tolerance_len
  986. else:
  987. is_centered = abs(block_y_center - region_y_center) <= tolerance_len
  988. # Condition 3: Check for surrounding text
  989. has_left_text = False
  990. has_right_text = False
  991. has_above_text = False
  992. has_below_text = False
  993. for block2 in blocks:
  994. if block2["block_label"] != "text":
  995. continue
  996. bbox2 = block2["block_bbox"]
  997. x1_2, y1_2, x2_2, y2_2 = bbox2
  998. if is_horizontal_1:
  999. if x2_2 <= x1 and not (y2_2 <= y1 or y1_2 >= y2):
  1000. has_left_text = True
  1001. if x1_2 >= x2 and not (y2_2 <= y1 or y1_2 >= y2):
  1002. has_right_text = True
  1003. else:
  1004. if y2_2 <= y1 and not (x2_2 <= x1 or x1_2 >= x2):
  1005. has_above_text = True
  1006. if y1_2 >= y2 and not (x2_2 <= x1 or x1_2 >= x2):
  1007. has_below_text = True
  1008. if (is_horizontal_1 and has_left_text and has_right_text) or (
  1009. not is_horizontal_1 and has_above_text and has_below_text
  1010. ):
  1011. break
  1012. no_text_on_sides = (
  1013. not (has_left_text or has_right_text)
  1014. if is_horizontal_1
  1015. else not (has_above_text or has_below_text)
  1016. )
  1017. # Add coordinates if all conditions are met
  1018. if is_centered and length_condition and no_text_on_sides:
  1019. if is_horizontal_1:
  1020. pre_cuts.setdefault("y", []).append(y1)
  1021. else:
  1022. pre_cuts.setdefault("x", []).append(x1)
  1023. for j, block2 in enumerate(blocks):
  1024. if i == j:
  1025. continue
  1026. bbox2 = block2["block_bbox"]
  1027. x1_prime, y1_prime, x2_prime, y2_prime = bbox2
  1028. is_horizontal_2 = _get_bbox_direction(bbox2)
  1029. match_block_iou = _get_projection_iou(
  1030. bbox2,
  1031. bbox1,
  1032. is_horizontal_1,
  1033. )
  1034. def distance_(is_horizontal, is_left_up):
  1035. if is_horizontal:
  1036. if is_left_up:
  1037. return (y1 - y2_prime + 2) // 5 + x1_prime / 5000
  1038. else:
  1039. return (y1_prime - y2 + 2) // 5 + x1_prime / 5000
  1040. else:
  1041. if is_left_up:
  1042. return (x1 - x2_prime + 2) // 5 + y1_prime / 5000
  1043. else:
  1044. return (x1_prime - x2 + 2) // 5 + y1_prime / 5000
  1045. block_iou_threshold = 0.1
  1046. if block1["block_label"] in sub_title_labels:
  1047. block_iou_threshold = 0.5
  1048. if is_horizontal_1:
  1049. if match_block_iou >= block_iou_threshold:
  1050. left_up_distance = distance_(True, True)
  1051. right_down_distance = distance_(True, False)
  1052. if (
  1053. y2_prime <= y1
  1054. and left_up_distance <= left_up_title_text_distance
  1055. ):
  1056. left_up_title_text_distance = left_up_distance
  1057. left_up_title_text_index = j
  1058. left_up_title_text_direction = is_horizontal_2
  1059. elif (
  1060. y1_prime > y2
  1061. and right_down_distance < right_down_title_text_distance
  1062. ):
  1063. right_down_title_text_distance = right_down_distance
  1064. right_down_title_text_index = j
  1065. right_down_title_text_direction = is_horizontal_2
  1066. else:
  1067. if match_block_iou >= block_iou_threshold:
  1068. left_up_distance = distance_(False, True)
  1069. right_down_distance = distance_(False, False)
  1070. if (
  1071. x2_prime <= x1
  1072. and left_up_distance <= left_up_title_text_distance
  1073. ):
  1074. left_up_title_text_distance = left_up_distance
  1075. left_up_title_text_index = j
  1076. left_up_title_text_direction = is_horizontal_2
  1077. elif (
  1078. x1_prime > x2
  1079. and right_down_distance < right_down_title_text_distance
  1080. ):
  1081. right_down_title_text_distance = right_down_distance
  1082. right_down_title_text_index = j
  1083. right_down_title_text_direction = is_horizontal_2
  1084. height = bbox1[3] - bbox1[1]
  1085. width = bbox1[2] - bbox1[0]
  1086. title_text_weight = [0.8, 0.8]
  1087. title_text, sub_title, vision_footnote = [], [], []
  1088. def get_sub_category_(
  1089. title_text_direction,
  1090. title_text_index,
  1091. label,
  1092. is_left_up=True,
  1093. ):
  1094. direction_ = [1, 3] if is_left_up else [2, 4]
  1095. if (
  1096. title_text_direction == is_horizontal_1
  1097. and title_text_index != -1
  1098. and (label == "text" or label == "paragraph_title")
  1099. ):
  1100. bbox2 = blocks[title_text_index]["block_bbox"]
  1101. if is_horizontal_1:
  1102. height1 = bbox2[3] - bbox2[1]
  1103. width1 = bbox2[2] - bbox2[0]
  1104. if label == "text":
  1105. if (
  1106. _nearest_edge_distance(bbox1, bbox2)[0] <= 15
  1107. and block1["block_label"] in vision_labels
  1108. and width1 < width
  1109. and height1 < 0.5 * height
  1110. ):
  1111. blocks[title_text_index]["sub_label"] = "vision_footnote"
  1112. vision_footnote.append(bbox2)
  1113. elif (
  1114. height1 < height * title_text_weight[0]
  1115. and (width1 < width or width1 > 1.5 * width)
  1116. and block1["block_label"] in title_labels
  1117. ):
  1118. blocks[title_text_index]["sub_label"] = "title_text"
  1119. title_text.append((direction_[0], bbox2))
  1120. elif (
  1121. label == "paragraph_title"
  1122. and block1["block_label"] in sub_title_labels
  1123. ):
  1124. sub_title.append(bbox2)
  1125. else:
  1126. height1 = bbox2[3] - bbox2[1]
  1127. width1 = bbox2[2] - bbox2[0]
  1128. if label == "text":
  1129. if (
  1130. _nearest_edge_distance(bbox1, bbox2)[0] <= 15
  1131. and block1["block_label"] in vision_labels
  1132. and height1 < height
  1133. and width1 < 0.5 * width
  1134. ):
  1135. blocks[title_text_index]["sub_label"] = "vision_footnote"
  1136. vision_footnote.append(bbox2)
  1137. elif (
  1138. width1 < width * title_text_weight[1]
  1139. and block1["block_label"] in title_labels
  1140. ):
  1141. blocks[title_text_index]["sub_label"] = "title_text"
  1142. title_text.append((direction_[1], bbox2))
  1143. elif (
  1144. label == "paragraph_title"
  1145. and block1["block_label"] in sub_title_labels
  1146. ):
  1147. sub_title.append(bbox2)
  1148. if (
  1149. is_horizontal_1
  1150. and abs(left_up_title_text_distance - right_down_title_text_distance) * 5
  1151. > height
  1152. ) or (
  1153. not is_horizontal_1
  1154. and abs(left_up_title_text_distance - right_down_title_text_distance) * 5
  1155. > width
  1156. ):
  1157. if left_up_title_text_distance < right_down_title_text_distance:
  1158. get_sub_category_(
  1159. left_up_title_text_direction,
  1160. left_up_title_text_index,
  1161. blocks[left_up_title_text_index]["block_label"],
  1162. True,
  1163. )
  1164. else:
  1165. get_sub_category_(
  1166. right_down_title_text_direction,
  1167. right_down_title_text_index,
  1168. blocks[right_down_title_text_index]["block_label"],
  1169. False,
  1170. )
  1171. else:
  1172. get_sub_category_(
  1173. left_up_title_text_direction,
  1174. left_up_title_text_index,
  1175. blocks[left_up_title_text_index]["block_label"],
  1176. True,
  1177. )
  1178. get_sub_category_(
  1179. right_down_title_text_direction,
  1180. right_down_title_text_index,
  1181. blocks[right_down_title_text_index]["block_label"],
  1182. False,
  1183. )
  1184. if block1["block_label"] in title_labels:
  1185. if blocks[i].get("title_text") == []:
  1186. blocks[i]["title_text"] = title_text
  1187. if block1["block_label"] in sub_title_labels:
  1188. if blocks[i].get("sub_title") == []:
  1189. blocks[i]["sub_title"] = sub_title
  1190. if block1["block_label"] in vision_labels:
  1191. if blocks[i].get("vision_footnote") == []:
  1192. blocks[i]["vision_footnote"] = vision_footnote
  1193. return blocks, pre_cuts
  1194. def get_layout_ordering(
  1195. parsing_res_list: List[Dict[str, Any]],
  1196. no_mask_labels: List[str] = [],
  1197. ) -> None:
  1198. """
  1199. Process layout parsing results to remove overlapping bounding boxes
  1200. and assign an ordering index based on their positions.
  1201. Modifies:
  1202. The 'parsing_res_list' list by adding an 'index' to each block.
  1203. Args:
  1204. parsing_res_list (List[Dict[str, Any]]): List of block dictionaries with 'block_bbox' and 'block_label'.
  1205. no_mask_labels (List[str]): Labels for which overlapping removal is not performed.
  1206. """
  1207. title_text_labels = ["doc_title"]
  1208. title_labels = ["doc_title", "paragraph_title"]
  1209. vision_labels = ["image", "table", "seal", "chart", "figure"]
  1210. vision_title_labels = ["table_title", "chart_title", "figure_title"]
  1211. parsing_res_list, _ = _remove_overlap_blocks(
  1212. parsing_res_list,
  1213. threshold=0.5,
  1214. smaller=True,
  1215. )
  1216. parsing_res_list, pre_cuts = _get_sub_category(parsing_res_list, title_text_labels)
  1217. parsing_res_by_pre_cuts_list = []
  1218. if len(pre_cuts) > 0:
  1219. block_bboxes = [block["block_bbox"] for block in parsing_res_list]
  1220. for axis, cuts in pre_cuts.items():
  1221. axis_index = 1 if axis == "y" else 0
  1222. max_val = max(bbox[axis_index + 2] for bbox in block_bboxes)
  1223. intervals = []
  1224. prev = 0
  1225. for cut in sorted(cuts):
  1226. intervals.append((prev, cut))
  1227. prev = cut
  1228. intervals.append((prev, max_val))
  1229. for start, end in intervals:
  1230. mask = [
  1231. (bbox[axis_index] >= start) and (bbox[axis_index] < end)
  1232. for bbox in block_bboxes
  1233. ]
  1234. parsing_res_by_pre_cuts_list.append(
  1235. [parsing_res_list[i] for i, m in enumerate(mask) if m]
  1236. )
  1237. else:
  1238. parsing_res_by_pre_cuts_list = [parsing_res_list]
  1239. final_parsing_res_list = []
  1240. num_index = 0
  1241. num_sub_index = 0
  1242. for parsing_res_by_pre_cuts in parsing_res_by_pre_cuts_list:
  1243. doc_flag = False
  1244. median_width = _get_text_median_width(parsing_res_by_pre_cuts)
  1245. parsing_res_by_pre_cuts, projection_direction = _get_layout_property(
  1246. parsing_res_by_pre_cuts,
  1247. median_width,
  1248. no_mask_labels=no_mask_labels,
  1249. threshold=0.3,
  1250. )
  1251. # Convert bounding boxes to float and remove overlaps
  1252. (
  1253. double_text_blocks,
  1254. title_text_blocks,
  1255. title_blocks,
  1256. vision_blocks,
  1257. vision_title_blocks,
  1258. vision_footnote_blocks,
  1259. other_blocks,
  1260. ) = ([], [], [], [], [], [], [])
  1261. drop_indexes = []
  1262. for index, block in enumerate(parsing_res_by_pre_cuts):
  1263. label = block["sub_label"]
  1264. block["block_bbox"] = list(map(int, block["block_bbox"]))
  1265. if label == "doc_title":
  1266. doc_flag = True
  1267. if label in no_mask_labels:
  1268. if block["layout"] == "double":
  1269. double_text_blocks.append(block)
  1270. drop_indexes.append(index)
  1271. elif label == "title_text":
  1272. title_text_blocks.append(block)
  1273. drop_indexes.append(index)
  1274. elif label == "vision_footnote":
  1275. vision_footnote_blocks.append(block)
  1276. drop_indexes.append(index)
  1277. elif label in vision_title_labels:
  1278. vision_title_blocks.append(block)
  1279. drop_indexes.append(index)
  1280. elif label in title_labels:
  1281. title_blocks.append(block)
  1282. drop_indexes.append(index)
  1283. elif label in vision_labels:
  1284. vision_blocks.append(block)
  1285. drop_indexes.append(index)
  1286. else:
  1287. other_blocks.append(block)
  1288. drop_indexes.append(index)
  1289. for index in sorted(drop_indexes, reverse=True):
  1290. del parsing_res_by_pre_cuts[index]
  1291. if len(parsing_res_by_pre_cuts) > 0:
  1292. # single text label
  1293. if (
  1294. len(double_text_blocks) > len(parsing_res_by_pre_cuts)
  1295. or projection_direction
  1296. ):
  1297. parsing_res_by_pre_cuts.extend(title_blocks + double_text_blocks)
  1298. title_blocks = []
  1299. double_text_blocks = []
  1300. block_bboxes = [
  1301. block["block_bbox"] for block in parsing_res_by_pre_cuts
  1302. ]
  1303. block_bboxes.sort(
  1304. key=lambda x: (
  1305. x[0] // max(20, median_width),
  1306. x[1],
  1307. ),
  1308. )
  1309. block_bboxes = np.array(block_bboxes)
  1310. sorted_indices = sort_by_xycut(block_bboxes, direction=1, min_gap=1)
  1311. else:
  1312. block_bboxes = [
  1313. block["block_bbox"] for block in parsing_res_by_pre_cuts
  1314. ]
  1315. block_bboxes.sort(key=lambda x: (x[0] // 20, x[1]))
  1316. block_bboxes = np.array(block_bboxes)
  1317. sorted_indices = sort_by_xycut(block_bboxes, direction=0, min_gap=20)
  1318. sorted_boxes = block_bboxes[sorted_indices].tolist()
  1319. for block in parsing_res_by_pre_cuts:
  1320. block["index"] = num_index + sorted_boxes.index(block["block_bbox"]) + 1
  1321. block["sub_index"] = (
  1322. num_sub_index + sorted_boxes.index(block["block_bbox"]) + 1
  1323. )
  1324. def nearest_match_(input_blocks, distance_type="manhattan", is_add_index=True):
  1325. for block in input_blocks:
  1326. bbox = block["block_bbox"]
  1327. min_distance = float("inf")
  1328. min_distance_config = [
  1329. [float("inf"), float("inf")],
  1330. float("inf"),
  1331. float("inf"),
  1332. ] # for double text
  1333. nearest_gt_index = 0
  1334. for match_block in parsing_res_by_pre_cuts:
  1335. match_bbox = match_block["block_bbox"]
  1336. if distance_type == "nearest_iou_edge_distance":
  1337. distance, min_distance_config = _nearest_iou_edge_distance(
  1338. bbox,
  1339. match_bbox,
  1340. block["sub_label"],
  1341. vision_labels=vision_labels,
  1342. no_mask_labels=no_mask_labels,
  1343. median_width=median_width,
  1344. title_labels=title_labels,
  1345. title_text=block["title_text"],
  1346. sub_title=block["sub_title"],
  1347. min_distance_config=min_distance_config,
  1348. tolerance_len=10,
  1349. )
  1350. elif distance_type == "title_text":
  1351. if (
  1352. match_block["block_label"] in title_labels + ["abstract"]
  1353. and match_block["title_text"] != []
  1354. ):
  1355. iou_left_up = _calculate_overlap_area_div_minbox_area_ratio(
  1356. bbox,
  1357. match_block["title_text"][0][1],
  1358. )
  1359. iou_right_down = (
  1360. _calculate_overlap_area_div_minbox_area_ratio(
  1361. bbox,
  1362. match_block["title_text"][-1][1],
  1363. )
  1364. )
  1365. iou = 1 - max(iou_left_up, iou_right_down)
  1366. distance = _manhattan_distance(bbox, match_bbox) * iou
  1367. else:
  1368. distance = float("inf")
  1369. elif distance_type == "manhattan":
  1370. distance = _manhattan_distance(bbox, match_bbox)
  1371. elif distance_type == "vision_footnote":
  1372. if (
  1373. match_block["block_label"] in vision_labels
  1374. and match_block["vision_footnote"] != []
  1375. ):
  1376. iou_left_up = _calculate_overlap_area_div_minbox_area_ratio(
  1377. bbox,
  1378. match_block["vision_footnote"][0],
  1379. )
  1380. iou_right_down = (
  1381. _calculate_overlap_area_div_minbox_area_ratio(
  1382. bbox,
  1383. match_block["vision_footnote"][-1],
  1384. )
  1385. )
  1386. iou = 1 - max(iou_left_up, iou_right_down)
  1387. distance = _manhattan_distance(bbox, match_bbox) * iou
  1388. else:
  1389. distance = float("inf")
  1390. elif distance_type == "vision_body":
  1391. if (
  1392. match_block["block_label"] in vision_title_labels
  1393. and block["vision_footnote"] != []
  1394. ):
  1395. iou_left_up = _calculate_overlap_area_div_minbox_area_ratio(
  1396. match_bbox,
  1397. block["vision_footnote"][0],
  1398. )
  1399. iou_right_down = (
  1400. _calculate_overlap_area_div_minbox_area_ratio(
  1401. match_bbox,
  1402. block["vision_footnote"][-1],
  1403. )
  1404. )
  1405. iou = 1 - max(iou_left_up, iou_right_down)
  1406. distance = _manhattan_distance(bbox, match_bbox) * iou
  1407. else:
  1408. distance = float("inf")
  1409. else:
  1410. raise NotImplementedError
  1411. if distance < min_distance:
  1412. min_distance = distance
  1413. if is_add_index:
  1414. nearest_gt_index = match_block.get("index", 999)
  1415. else:
  1416. nearest_gt_index = match_block.get("sub_index", 999)
  1417. if is_add_index:
  1418. block["index"] = nearest_gt_index
  1419. else:
  1420. block["sub_index"] = nearest_gt_index
  1421. parsing_res_by_pre_cuts.append(block)
  1422. # double text label
  1423. double_text_blocks.sort(
  1424. key=lambda x: (
  1425. x["block_bbox"][1] // 10,
  1426. x["block_bbox"][0] // median_width,
  1427. x["block_bbox"][1] ** 2 + x["block_bbox"][0] ** 2,
  1428. ),
  1429. )
  1430. nearest_match_(
  1431. double_text_blocks,
  1432. distance_type="nearest_iou_edge_distance",
  1433. )
  1434. parsing_res_by_pre_cuts.sort(
  1435. key=lambda x: (x["index"], x["block_bbox"][1], x["block_bbox"][0]),
  1436. )
  1437. for idx, block in enumerate(parsing_res_by_pre_cuts):
  1438. block["index"] = num_index + idx + 1
  1439. block["sub_index"] = num_sub_index + idx + 1
  1440. # title label
  1441. title_blocks.sort(
  1442. key=lambda x: (
  1443. x["block_bbox"][1] // 10,
  1444. x["block_bbox"][0] // median_width,
  1445. x["block_bbox"][1] ** 2 + x["block_bbox"][0] ** 2,
  1446. ),
  1447. )
  1448. nearest_match_(title_blocks, distance_type="nearest_iou_edge_distance")
  1449. if doc_flag:
  1450. text_sort_labels = ["doc_title"]
  1451. text_label_priority = {
  1452. label: priority for priority, label in enumerate(text_sort_labels)
  1453. }
  1454. doc_titles = []
  1455. for i, block in enumerate(parsing_res_by_pre_cuts):
  1456. if block["block_label"] == "doc_title":
  1457. doc_titles.append(
  1458. (i, block["block_bbox"][1], block["block_bbox"][0]),
  1459. )
  1460. doc_titles.sort(key=lambda x: (x[1], x[2]))
  1461. first_doc_title_index = doc_titles[0][0]
  1462. parsing_res_by_pre_cuts[first_doc_title_index]["index"] = 1
  1463. parsing_res_by_pre_cuts.sort(
  1464. key=lambda x: (
  1465. x["index"],
  1466. text_label_priority.get(x["block_label"], 9999),
  1467. x["block_bbox"][1],
  1468. x["block_bbox"][0],
  1469. ),
  1470. )
  1471. else:
  1472. parsing_res_by_pre_cuts.sort(
  1473. key=lambda x: (
  1474. x["index"],
  1475. x["block_bbox"][1],
  1476. x["block_bbox"][0],
  1477. ),
  1478. )
  1479. for idx, block in enumerate(parsing_res_by_pre_cuts):
  1480. block["index"] = num_index + idx + 1
  1481. block["sub_index"] = num_sub_index + idx + 1
  1482. # title-text label
  1483. nearest_match_(title_text_blocks, distance_type="title_text")
  1484. def hor_tb_and_ver_lr(x):
  1485. input_bbox = x["block_bbox"]
  1486. is_horizontal = _get_bbox_direction(input_bbox)
  1487. if is_horizontal:
  1488. return input_bbox[1]
  1489. else:
  1490. return input_bbox[0]
  1491. parsing_res_by_pre_cuts.sort(
  1492. key=lambda x: (x["index"], hor_tb_and_ver_lr(x)),
  1493. )
  1494. for idx, block in enumerate(parsing_res_by_pre_cuts):
  1495. block["index"] = num_index + idx + 1
  1496. block["sub_index"] = num_sub_index + idx + 1
  1497. # image,figure,chart,seal label
  1498. nearest_match_(
  1499. vision_blocks,
  1500. distance_type="nearest_iou_edge_distance",
  1501. is_add_index=False,
  1502. )
  1503. parsing_res_by_pre_cuts.sort(
  1504. key=lambda x: (
  1505. x["sub_index"],
  1506. x["block_bbox"][1],
  1507. x["block_bbox"][0],
  1508. ),
  1509. )
  1510. for idx, block in enumerate(parsing_res_by_pre_cuts):
  1511. block["sub_index"] = num_sub_index + idx + 1
  1512. # image,figure,chart,seal title label
  1513. nearest_match_(
  1514. vision_title_blocks,
  1515. distance_type="nearest_iou_edge_distance",
  1516. is_add_index=False,
  1517. )
  1518. parsing_res_by_pre_cuts.sort(
  1519. key=lambda x: (
  1520. x["sub_index"],
  1521. x["block_bbox"][1],
  1522. x["block_bbox"][0],
  1523. ),
  1524. )
  1525. for idx, block in enumerate(parsing_res_by_pre_cuts):
  1526. block["sub_index"] = num_sub_index + idx + 1
  1527. # vision footnote label
  1528. nearest_match_(
  1529. vision_footnote_blocks,
  1530. distance_type="vision_footnote",
  1531. is_add_index=False,
  1532. )
  1533. text_label_priority = {"vision_footnote": 9999}
  1534. parsing_res_by_pre_cuts.sort(
  1535. key=lambda x: (
  1536. x["sub_index"],
  1537. text_label_priority.get(x["sub_label"], 0),
  1538. x["block_bbox"][1],
  1539. x["block_bbox"][0],
  1540. ),
  1541. )
  1542. for idx, block in enumerate(parsing_res_by_pre_cuts):
  1543. block["sub_index"] = num_sub_index + idx + 1
  1544. # header、footnote、header_image... label
  1545. nearest_match_(other_blocks, distance_type="manhattan", is_add_index=False)
  1546. # add all parsing result
  1547. final_parsing_res_list.extend(parsing_res_by_pre_cuts)
  1548. # update num index
  1549. num_sub_index += len(parsing_res_by_pre_cuts)
  1550. for parsing_res in parsing_res_by_pre_cuts:
  1551. if parsing_res.get("index"):
  1552. num_index += 1
  1553. parsing_res_list = [
  1554. {
  1555. "block_label": parsing_res["block_label"],
  1556. "block_content": parsing_res["block_content"],
  1557. "block_bbox": parsing_res["block_bbox"],
  1558. "block_image": parsing_res.get("block_image", None),
  1559. "seg_start_flag": parsing_res["seg_start_flag"],
  1560. "seg_end_flag": parsing_res["seg_end_flag"],
  1561. "sub_label": parsing_res["sub_label"],
  1562. "sub_index": parsing_res["sub_index"],
  1563. "index": parsing_res.get("index", None),
  1564. }
  1565. for parsing_res in final_parsing_res_list
  1566. ]
  1567. return parsing_res_list
  1568. def _manhattan_distance(
  1569. point1: Tuple[float, float],
  1570. point2: Tuple[float, float],
  1571. weight_x: float = 1.0,
  1572. weight_y: float = 1.0,
  1573. ) -> float:
  1574. """
  1575. Calculate the weighted Manhattan distance between two points.
  1576. Args:
  1577. point1 (Tuple[float, float]): The first point as (x, y).
  1578. point2 (Tuple[float, float]): The second point as (x, y).
  1579. weight_x (float): The weight for the x-axis distance. Default is 1.0.
  1580. weight_y (float): The weight for the y-axis distance. Default is 1.0.
  1581. Returns:
  1582. float: The weighted Manhattan distance between the two points.
  1583. """
  1584. return weight_x * abs(point1[0] - point2[0]) + weight_y * abs(point1[1] - point2[1])
  1585. def _calculate_horizontal_distance(
  1586. input_bbox: List[int],
  1587. match_bbox: List[int],
  1588. height: int,
  1589. disperse: int,
  1590. title_text: List[Tuple[int, List[int]]],
  1591. ) -> float:
  1592. """
  1593. Calculate the horizontal distance between two bounding boxes, considering title text adjustments.
  1594. Args:
  1595. input_bbox (List[int]): The bounding box coordinates [x1, y1, x2, y2] of the input object.
  1596. match_bbox (List[int]): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
  1597. height (int): The height of the input bounding box used for normalization.
  1598. disperse (int): The dispersion factor used to normalize the horizontal distance.
  1599. title_text (List[Tuple[int, List[int]]]): A list of tuples containing title text information and their bounding box coordinates.
  1600. Format: [(position_indicator, [x1, y1, x2, y2]), ...].
  1601. Returns:
  1602. float: The calculated horizontal distance taking into account the title text adjustments.
  1603. """
  1604. x1, y1, x2, y2 = input_bbox
  1605. x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
  1606. # Determine vertical distance adjustment based on title text
  1607. if y2 < y1_prime:
  1608. if title_text and title_text[-1][0] == 2:
  1609. y2 += title_text[-1][1][3] - title_text[-1][1][1]
  1610. vertical_adjustment = (y1_prime - y2) * 0.5
  1611. else:
  1612. if title_text and title_text[0][0] == 1:
  1613. y1 -= title_text[0][1][3] - title_text[0][1][1]
  1614. vertical_adjustment = y1 - y2_prime
  1615. # Calculate horizontal distance with adjustments
  1616. horizontal_distance = (
  1617. abs(x2_prime - x1) // disperse
  1618. + vertical_adjustment // height
  1619. + vertical_adjustment / 5000
  1620. )
  1621. return horizontal_distance
  1622. def _calculate_vertical_distance(
  1623. input_bbox: List[int],
  1624. match_bbox: List[int],
  1625. width: int,
  1626. disperse: int,
  1627. title_text: List[Tuple[int, List[int]]],
  1628. ) -> float:
  1629. """
  1630. Calculate the vertical distance between two bounding boxes, considering title text adjustments.
  1631. Args:
  1632. input_bbox (List[int]): The bounding box coordinates [x1, y1, x2, y2] of the input object.
  1633. match_bbox (List[int]): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
  1634. width (int): The width of the input bounding box used for normalization.
  1635. disperse (int): The dispersion factor used to normalize the vertical distance.
  1636. title_text (List[Tuple[int, List[int]]]): A list of tuples containing title text information and their bounding box coordinates.
  1637. Format: [(position_indicator, [x1, y1, x2, y2]), ...].
  1638. Returns:
  1639. float: The calculated vertical distance taking into account the title text adjustments.
  1640. """
  1641. x1, y1, x2, y2 = input_bbox
  1642. x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
  1643. # Determine horizontal distance adjustment based on title text
  1644. if x1 > x2_prime:
  1645. if title_text and title_text[0][0] == 3:
  1646. x1 -= title_text[0][1][2] - title_text[0][1][0]
  1647. horizontal_adjustment = (x1 - x2_prime) * 0.5
  1648. else:
  1649. if title_text and title_text[-1][0] == 4:
  1650. x2 += title_text[-1][1][2] - title_text[-1][1][0]
  1651. horizontal_adjustment = x1_prime - x2
  1652. # Calculate vertical distance with adjustments
  1653. vertical_distance = (
  1654. abs(y2_prime - y1) // disperse
  1655. + horizontal_adjustment // width
  1656. + horizontal_adjustment / 5000
  1657. )
  1658. return vertical_distance
  1659. def _nearest_edge_distance(
  1660. input_bbox: List[int],
  1661. match_bbox: List[int],
  1662. weight: List[float] = [1.0, 1.0, 1.0, 1.0],
  1663. label: str = "text",
  1664. no_mask_labels: List[str] = [],
  1665. min_edge_distance_config: List[float] = [],
  1666. tolerance_len: float = 10.0,
  1667. ) -> Tuple[float, List[float]]:
  1668. """
  1669. Calculate the nearest edge distance between two bounding boxes, considering directional weights.
  1670. Args:
  1671. input_bbox (list): The bounding box coordinates [x1, y1, x2, y2] of the input object.
  1672. match_bbox (list): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
  1673. weight (list, optional): Directional weights for the edge distances [left, right, up, down]. Defaults to [1, 1, 1, 1].
  1674. label (str, optional): The label/type of the object in the bounding box (e.g., 'text'). Defaults to 'text'.
  1675. no_mask_labels (list, optional): Labels for which no masking is applied when calculating edge distances. Defaults to an empty list.
  1676. min_edge_distance_config (list, optional): Configuration for minimum edge distances [min_edge_distance_x, min_edge_distance_y].
  1677. Defaults to [float('inf'), float('inf')].
  1678. tolerance_len (float, optional): The tolerance length for adjusting edge distances. Defaults to 10.
  1679. Returns:
  1680. Tuple[float, List[float]]: A tuple containing:
  1681. - The calculated minimum edge distance between the bounding boxes.
  1682. - A list with the minimum edge distances in the x and y directions.
  1683. """
  1684. match_bbox_iou = _calculate_overlap_area_div_minbox_area_ratio(
  1685. input_bbox,
  1686. match_bbox,
  1687. )
  1688. if match_bbox_iou > 0 and label not in no_mask_labels:
  1689. return 0, [0, 0]
  1690. if not min_edge_distance_config:
  1691. min_edge_distance_config = [float("inf"), float("inf")]
  1692. min_edge_distance_x, min_edge_distance_y = min_edge_distance_config
  1693. x1, y1, x2, y2 = input_bbox
  1694. x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
  1695. direction_num = 0
  1696. distance_x = float("inf")
  1697. distance_y = float("inf")
  1698. distance = [float("inf")] * 4
  1699. # input_bbox is to the left of match_bbox
  1700. if x2 < x1_prime:
  1701. direction_num += 1
  1702. distance[0] = x1_prime - x2
  1703. if abs(distance[0] - min_edge_distance_x) <= tolerance_len:
  1704. distance_x = min_edge_distance_x * weight[0]
  1705. else:
  1706. distance_x = distance[0] * weight[0]
  1707. # input_bbox is to the right of match_bbox
  1708. elif x1 > x2_prime:
  1709. direction_num += 1
  1710. distance[1] = x1 - x2_prime
  1711. if abs(distance[1] - min_edge_distance_x) <= tolerance_len:
  1712. distance_x = min_edge_distance_x * weight[1]
  1713. else:
  1714. distance_x = distance[1] * weight[1]
  1715. elif match_bbox_iou > 0:
  1716. distance[0] = 0
  1717. distance_x = 0
  1718. # input_bbox is above match_bbox
  1719. if y2 < y1_prime:
  1720. direction_num += 1
  1721. distance[2] = y1_prime - y2
  1722. if abs(distance[2] - min_edge_distance_y) <= tolerance_len:
  1723. distance_y = min_edge_distance_y * weight[2]
  1724. else:
  1725. distance_y = distance[2] * weight[2]
  1726. if label in no_mask_labels:
  1727. distance_y = max(0.1, distance_y) * 10 # for abstract
  1728. # input_bbox is below match_bbox
  1729. elif y1 > y2_prime:
  1730. direction_num += 1
  1731. distance[3] = y1 - y2_prime
  1732. if abs(distance[3] - min_edge_distance_y) <= tolerance_len:
  1733. distance_y = min_edge_distance_y * weight[3]
  1734. else:
  1735. distance_y = distance[3] * weight[3]
  1736. elif match_bbox_iou > 0:
  1737. distance[2] = 0
  1738. distance_y = 0
  1739. if direction_num == 2:
  1740. return (distance_x + distance_y), [
  1741. min(distance[0], distance[1]),
  1742. min(distance[2], distance[3]),
  1743. ]
  1744. else:
  1745. return min(distance_x, distance_y), [
  1746. min(distance[0], distance[1]),
  1747. min(distance[2], distance[3]),
  1748. ]
  1749. def _get_weights(label, horizontal):
  1750. """Define weights based on the label and orientation."""
  1751. if label == "doc_title":
  1752. return (
  1753. [1, 0.1, 0.1, 1] if horizontal else [0.2, 0.1, 1, 1]
  1754. ) # left-down , right-left
  1755. elif label in [
  1756. "paragraph_title",
  1757. "table_title",
  1758. "abstract",
  1759. "image",
  1760. "seal",
  1761. "chart",
  1762. "figure",
  1763. ]:
  1764. return [1, 1, 0.1, 1] # down
  1765. else:
  1766. return [1, 1, 1, 0.1] # up
  1767. def _nearest_iou_edge_distance(
  1768. input_bbox: List[int],
  1769. match_bbox: List[int],
  1770. label: str,
  1771. vision_labels: List[str],
  1772. no_mask_labels: List[str],
  1773. median_width: int = -1,
  1774. title_labels: List[str] = [],
  1775. title_text: List[Tuple[int, List[int]]] = [],
  1776. sub_title: List[List[int]] = [],
  1777. min_distance_config: List[float] = [],
  1778. tolerance_len: float = 10.0,
  1779. ) -> Tuple[float, List[float]]:
  1780. """
  1781. Calculate the nearest IOU edge distance between two bounding boxes, considering label types, title adjustments, and minimum distance configurations.
  1782. This function computes the edge distance between two bounding boxes while considering their overlap (IOU) and various adjustments based on label types,
  1783. title text, and subtitle information. It also applies minimum distance configurations and tolerance adjustments.
  1784. Args:
  1785. input_bbox (List[int]): The bounding box coordinates [x1, y1, x2, y2] of the input object.
  1786. match_bbox (List[int]): The bounding box coordinates [x1', y1', x2', y2'] of the object to match against.
  1787. label (str): The label/type of the object in the bounding box (e.g., 'image', 'text', etc.).
  1788. vision_labels (List[str]): List of labels for vision-related objects (e.g., images, icons).
  1789. no_mask_labels (List[str]): Labels for which no masking is applied when calculating edge distances.
  1790. median_width (int, optional): The median width for title dispersion calculation. Defaults to -1.
  1791. title_labels (List[str], optional): Labels that indicate the object is a title. Defaults to an empty list.
  1792. title_text (List[Tuple[int, List[int]]], optional): Text content associated with title labels, in the format [(position_indicator, [x1, y1, x2, y2]), ...].
  1793. sub_title (List[List[int]], optional): List of subtitle bounding boxes to adjust the input_bbox. Defaults to an empty list.
  1794. min_distance_config (List[float], optional): Configuration for minimum distances [min_edge_distance_config, up_edge_distances_config, total_distance].
  1795. tolerance_len (float, optional): The tolerance length for adjusting edge distances. Defaults to 10.0.
  1796. Returns:
  1797. Tuple[float, List[float]]: A tuple containing:
  1798. - The calculated distance considering IOU and adjustments.
  1799. - The updated minimum distance configuration.
  1800. """
  1801. x1, y1, x2, y2 = input_bbox
  1802. x1_prime, y1_prime, x2_prime, y2_prime = match_bbox
  1803. min_edge_distance_config, up_edge_distances_config, total_distance = (
  1804. min_distance_config
  1805. )
  1806. iou_distance = 0
  1807. if label in vision_labels:
  1808. horizontal1 = horizontal2 = True
  1809. else:
  1810. horizontal1 = _get_bbox_direction(input_bbox)
  1811. horizontal2 = _get_bbox_direction(match_bbox, 3)
  1812. if (
  1813. horizontal1 != horizontal2
  1814. or _get_projection_iou(input_bbox, match_bbox, horizontal1) < 0.01
  1815. ):
  1816. iou_distance = 1
  1817. if label == "doc_title":
  1818. # Calculate distance for titles
  1819. disperse = max(1, median_width)
  1820. tolerance_len = max(tolerance_len, disperse)
  1821. # Adjust input_bbox based on sub_title
  1822. if sub_title:
  1823. for sub in sub_title:
  1824. x1_, y1_, x2_, y2_ = sub
  1825. x1, y1, x2, y2 = (
  1826. min(x1, x1_),
  1827. min(y1, y1_),
  1828. min(x2, x2_),
  1829. max(y2, y2_),
  1830. )
  1831. input_bbox = [x1, y1, x2, y2]
  1832. if title_text:
  1833. for sub in title_text:
  1834. x1_, y1_, x2_, y2_ = sub[1]
  1835. if horizontal1:
  1836. x1, y1, x2, y2 = (
  1837. min(x1, x1_),
  1838. min(y1, y1_),
  1839. min(x2, x2_),
  1840. max(y2, y2_),
  1841. )
  1842. else:
  1843. x1, y1, x2, y2 = (
  1844. min(x1, x1_),
  1845. min(y1, y1_),
  1846. max(x2, x2_),
  1847. min(y2, y2_),
  1848. )
  1849. input_bbox = [x1, y1, x2, y2]
  1850. # Calculate edge distance
  1851. weight = _get_weights(label, horizontal1)
  1852. if label == "abstract":
  1853. tolerance_len *= 2
  1854. edge_distance, edge_distance_config = _nearest_edge_distance(
  1855. input_bbox,
  1856. match_bbox,
  1857. weight,
  1858. label=label,
  1859. no_mask_labels=no_mask_labels,
  1860. min_edge_distance_config=min_edge_distance_config,
  1861. tolerance_len=tolerance_len,
  1862. )
  1863. # Weights for combining distances
  1864. iou_edge_weight = [10**8, 10**4, 1, 0.0001]
  1865. # Calculate up and left edge distances
  1866. up_edge_distance = y1_prime
  1867. left_edge_distance = x1_prime
  1868. if (
  1869. label in no_mask_labels or label in title_labels or label in vision_labels
  1870. ) and y1 > y2_prime:
  1871. up_edge_distance = -y2_prime
  1872. left_edge_distance = -x2_prime
  1873. min_up_edge_distance = up_edge_distances_config
  1874. if abs(min_up_edge_distance - up_edge_distance) <= tolerance_len:
  1875. up_edge_distance = min_up_edge_distance
  1876. # Calculate total distance
  1877. distance = (
  1878. iou_distance * iou_edge_weight[0]
  1879. + edge_distance * iou_edge_weight[1]
  1880. + up_edge_distance * iou_edge_weight[2]
  1881. + left_edge_distance * iou_edge_weight[3]
  1882. )
  1883. # Update minimum distance configuration if a smaller distance is found
  1884. if total_distance > distance:
  1885. edge_distance_config = [
  1886. edge_distance_config[0],
  1887. edge_distance_config[1],
  1888. ]
  1889. min_distance_config = [
  1890. edge_distance_config,
  1891. up_edge_distance,
  1892. distance,
  1893. ]
  1894. return distance, min_distance_config
  1895. def get_show_color(label: str) -> Tuple:
  1896. label_colors = {
  1897. # Medium Blue (from 'titles_list')
  1898. "paragraph_title": (102, 102, 255, 100),
  1899. "doc_title": (255, 248, 220, 100), # Cornsilk
  1900. # Light Yellow (from 'tables_caption_list')
  1901. "table_title": (255, 255, 102, 100),
  1902. # Sky Blue (from 'imgs_caption_list')
  1903. "figure_title": (102, 178, 255, 100),
  1904. "chart_title": (221, 160, 221, 100), # Plum
  1905. "vision_footnote": (144, 238, 144, 100), # Light Green
  1906. # Deep Purple (from 'texts_list')
  1907. "text": (153, 0, 76, 100),
  1908. # Bright Green (from 'interequations_list')
  1909. "formula": (0, 255, 0, 100),
  1910. "abstract": (255, 239, 213, 100), # Papaya Whip
  1911. # Medium Green (from 'lists_list' and 'indexs_list')
  1912. "content": (40, 169, 92, 100),
  1913. # Neutral Gray (from 'dropped_bbox_list')
  1914. "seal": (158, 158, 158, 100),
  1915. # Olive Yellow (from 'tables_body_list')
  1916. "table": (204, 204, 0, 100),
  1917. # Bright Green (from 'imgs_body_list')
  1918. "image": (153, 255, 51, 100),
  1919. # Bright Green (from 'imgs_body_list')
  1920. "figure": (153, 255, 51, 100),
  1921. "chart": (216, 191, 216, 100), # Thistle
  1922. # Pale Yellow-Green (from 'tables_footnote_list')
  1923. "reference": (229, 255, 204, 100),
  1924. "algorithm": (255, 250, 240, 100), # Floral White
  1925. }
  1926. default_color = (158, 158, 158, 100)
  1927. return label_colors.get(label, default_color)