utils.py 84 KB

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