utils.py 89 KB

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