utils.py 89 KB

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