utils.py 89 KB

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