model_utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import time
  2. import gc
  3. from PIL import Image
  4. from loguru import logger
  5. import numpy as np
  6. from mineru.utils.boxbase import get_minbox_if_overlap_by_ratio
  7. try:
  8. import torch
  9. import torch_npu
  10. except ImportError:
  11. pass
  12. def crop_img(input_res, input_img, crop_paste_x=0, crop_paste_y=0):
  13. crop_xmin, crop_ymin = int(input_res['poly'][0]), int(input_res['poly'][1])
  14. crop_xmax, crop_ymax = int(input_res['poly'][4]), int(input_res['poly'][5])
  15. # Calculate new dimensions
  16. crop_new_width = crop_xmax - crop_xmin + crop_paste_x * 2
  17. crop_new_height = crop_ymax - crop_ymin + crop_paste_y * 2
  18. if isinstance(input_img, np.ndarray):
  19. # Create a white background array
  20. return_image = np.ones((crop_new_height, crop_new_width, 3), dtype=np.uint8) * 255
  21. # Crop the original image using numpy slicing
  22. cropped_img = input_img[crop_ymin:crop_ymax, crop_xmin:crop_xmax]
  23. # Paste the cropped image onto the white background
  24. return_image[crop_paste_y:crop_paste_y + (crop_ymax - crop_ymin),
  25. crop_paste_x:crop_paste_x + (crop_xmax - crop_xmin)] = cropped_img
  26. else:
  27. # Create a white background array
  28. return_image = Image.new('RGB', (crop_new_width, crop_new_height), 'white')
  29. # Crop image
  30. crop_box = (crop_xmin, crop_ymin, crop_xmax, crop_ymax)
  31. cropped_img = input_img.crop(crop_box)
  32. return_image.paste(cropped_img, (crop_paste_x, crop_paste_y))
  33. return_list = [crop_paste_x, crop_paste_y, crop_xmin, crop_ymin, crop_xmax, crop_ymax, crop_new_width,
  34. crop_new_height]
  35. return return_image, return_list
  36. def get_coords_and_area(block_with_poly):
  37. """Extract coordinates and area from a table."""
  38. xmin, ymin = int(block_with_poly['poly'][0]), int(block_with_poly['poly'][1])
  39. xmax, ymax = int(block_with_poly['poly'][4]), int(block_with_poly['poly'][5])
  40. area = (xmax - xmin) * (ymax - ymin)
  41. return xmin, ymin, xmax, ymax, area
  42. def calculate_intersection(box1, box2):
  43. """Calculate intersection coordinates between two boxes."""
  44. intersection_xmin = max(box1[0], box2[0])
  45. intersection_ymin = max(box1[1], box2[1])
  46. intersection_xmax = min(box1[2], box2[2])
  47. intersection_ymax = min(box1[3], box2[3])
  48. # Check if intersection is valid
  49. if intersection_xmax <= intersection_xmin or intersection_ymax <= intersection_ymin:
  50. return None
  51. return intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax
  52. def calculate_iou(box1, box2):
  53. """Calculate IoU between two boxes."""
  54. intersection = calculate_intersection(box1[:4], box2[:4])
  55. if not intersection:
  56. return 0
  57. intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax = intersection
  58. intersection_area = (intersection_xmax - intersection_xmin) * (intersection_ymax - intersection_ymin)
  59. area1, area2 = box1[4], box2[4]
  60. union_area = area1 + area2 - intersection_area
  61. return intersection_area / union_area if union_area > 0 else 0
  62. def is_inside(small_box, big_box, overlap_threshold=0.8):
  63. """Check if small_box is inside big_box by at least overlap_threshold."""
  64. intersection = calculate_intersection(small_box[:4], big_box[:4])
  65. if not intersection:
  66. return False
  67. intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax = intersection
  68. intersection_area = (intersection_xmax - intersection_xmin) * (intersection_ymax - intersection_ymin)
  69. # Check if overlap exceeds threshold
  70. return intersection_area >= overlap_threshold * small_box[4]
  71. def do_overlap(box1, box2):
  72. """Check if two boxes overlap."""
  73. return calculate_intersection(box1[:4], box2[:4]) is not None
  74. def merge_high_iou_tables(table_res_list, layout_res, table_indices, iou_threshold=0.7):
  75. """Merge tables with IoU > threshold."""
  76. if len(table_res_list) < 2:
  77. return table_res_list, table_indices
  78. table_info = [get_coords_and_area(table) for table in table_res_list]
  79. merged = True
  80. while merged:
  81. merged = False
  82. i = 0
  83. while i < len(table_res_list) - 1:
  84. j = i + 1
  85. while j < len(table_res_list):
  86. iou = calculate_iou(table_info[i], table_info[j])
  87. if iou > iou_threshold:
  88. # Merge tables by taking their union
  89. x1_min, y1_min, x1_max, y1_max, _ = table_info[i]
  90. x2_min, y2_min, x2_max, y2_max, _ = table_info[j]
  91. union_xmin = min(x1_min, x2_min)
  92. union_ymin = min(y1_min, y2_min)
  93. union_xmax = max(x1_max, x2_max)
  94. union_ymax = max(y1_max, y2_max)
  95. # Create merged table
  96. merged_table = table_res_list[i].copy()
  97. merged_table['poly'] = [
  98. union_xmin, union_ymin, union_xmax, union_ymin,
  99. union_xmax, union_ymax, union_xmin, union_ymax
  100. ]
  101. # Update layout_res
  102. to_remove = [table_indices[j], table_indices[i]]
  103. for idx in sorted(to_remove, reverse=True):
  104. del layout_res[idx]
  105. layout_res.append(merged_table)
  106. # Update tracking lists
  107. table_indices = [k if k < min(to_remove) else
  108. k - 1 if k < max(to_remove) else
  109. k - 2 if k > max(to_remove) else
  110. len(layout_res) - 1
  111. for k in table_indices
  112. if k not in to_remove]
  113. table_indices.append(len(layout_res) - 1)
  114. # Update table lists
  115. table_res_list.pop(j)
  116. table_res_list.pop(i)
  117. table_res_list.append(merged_table)
  118. # Update table_info
  119. table_info = [get_coords_and_area(table) for table in table_res_list]
  120. merged = True
  121. break
  122. j += 1
  123. if merged:
  124. break
  125. i += 1
  126. return table_res_list, table_indices
  127. def filter_nested_tables(table_res_list, overlap_threshold=0.8, area_threshold=0.8):
  128. """Remove big tables containing multiple smaller tables within them."""
  129. if len(table_res_list) < 3:
  130. return table_res_list
  131. table_info = [get_coords_and_area(table) for table in table_res_list]
  132. big_tables_idx = []
  133. for i in range(len(table_res_list)):
  134. # Find tables inside this one
  135. tables_inside = [j for j in range(len(table_res_list))
  136. if i != j and is_inside(table_info[j], table_info[i], overlap_threshold)]
  137. # Continue if there are at least 3 tables inside
  138. if len(tables_inside) >= 3:
  139. # Check if inside tables overlap with each other
  140. tables_overlap = any(do_overlap(table_info[tables_inside[idx1]], table_info[tables_inside[idx2]])
  141. for idx1 in range(len(tables_inside))
  142. for idx2 in range(idx1 + 1, len(tables_inside)))
  143. # If no overlaps, check area condition
  144. if not tables_overlap:
  145. total_inside_area = sum(table_info[j][4] for j in tables_inside)
  146. big_table_area = table_info[i][4]
  147. if total_inside_area > area_threshold * big_table_area:
  148. big_tables_idx.append(i)
  149. return [table for i, table in enumerate(table_res_list) if i not in big_tables_idx]
  150. def remove_overlaps_min_blocks(res_list):
  151. # 重叠block,小的不能直接删除,需要和大的那个合并成一个更大的。
  152. # 删除重叠blocks中较小的那些
  153. need_remove = []
  154. for i in range(len(res_list)):
  155. # 如果当前元素已在需要移除列表中,则跳过
  156. if res_list[i] in need_remove:
  157. continue
  158. for j in range(i + 1, len(res_list)):
  159. # 如果比较对象已在需要移除列表中,则跳过
  160. if res_list[j] in need_remove:
  161. continue
  162. overlap_box = get_minbox_if_overlap_by_ratio(
  163. res_list[i]['bbox'], res_list[j]['bbox'], 0.8
  164. )
  165. if overlap_box is not None:
  166. res_to_remove = None
  167. large_res = None
  168. # 确定哪个是小块(要移除的)
  169. if overlap_box == res_list[i]['bbox']:
  170. res_to_remove = res_list[i]
  171. large_res = res_list[j]
  172. elif overlap_box == res_list[j]['bbox']:
  173. res_to_remove = res_list[j]
  174. large_res = res_list[i]
  175. if res_to_remove['score'] < large_res['score']:
  176. # 如果小块的分数低于大块,则小块为需要移除的块
  177. if res_to_remove is not None and res_to_remove not in need_remove:
  178. # 更新大块的边界为两者的并集
  179. x1, y1, x2, y2 = large_res['bbox']
  180. sx1, sy1, sx2, sy2 = res_to_remove['bbox']
  181. x1 = min(x1, sx1)
  182. y1 = min(y1, sy1)
  183. x2 = max(x2, sx2)
  184. y2 = max(y2, sy2)
  185. large_res['bbox'] = [x1, y1, x2, y2]
  186. need_remove.append(res_to_remove)
  187. else:
  188. # 如果大块的分数低于小块,则大块为需要移除的块, 这时不需要更新小块的边界
  189. if large_res is not None and large_res not in need_remove:
  190. need_remove.append(large_res)
  191. # 从列表中移除标记的元素
  192. for res in need_remove:
  193. res_list.remove(res)
  194. return res_list, need_remove
  195. def remove_overlaps_low_confidence_blocks(combined_res_list, overlap_threshold=0.8):
  196. """
  197. Remove low-confidence blocks that overlap with other blocks.
  198. This function identifies and removes blocks with low confidence scores that overlap
  199. with other blocks. It calculates the coordinates and area of each block, and checks
  200. for overlaps based on a specified threshold. Blocks that meet the criteria for removal
  201. are returned in a list.
  202. Parameters:
  203. combined_res_list (list): A list of blocks, where each block is a dictionary containing
  204. keys like 'poly' (polygon coordinates) and optionally 'score' (confidence score).
  205. overlap_threshold (float): The threshold for determining overlap between blocks. Default is 0.8.
  206. Returns:
  207. list: A list of blocks to be removed, based on the overlap and confidence criteria.
  208. """
  209. # 计算每个block的坐标和面积
  210. block_info = []
  211. for block in combined_res_list:
  212. xmin, ymin = int(block['poly'][0]), int(block['poly'][1])
  213. xmax, ymax = int(block['poly'][4]), int(block['poly'][5])
  214. area = (xmax - xmin) * (ymax - ymin)
  215. score = block.get('score', 0.5) # 如果没有score字段,默认为0.5
  216. block_info.append((xmin, ymin, xmax, ymax, area, score, block))
  217. blocks_to_remove = []
  218. marked_indices = set() # 跟踪已标记为删除的block索引
  219. # 检查每个block内部是否有3个及以上的小block
  220. for i, (xmin, ymin, xmax, ymax, area, score, block) in enumerate(block_info):
  221. # 如果当前block已标记为删除,则跳过
  222. if i in marked_indices:
  223. continue
  224. # 查找内部的小block (仅考虑尚未被标记为删除的block)
  225. blocks_inside = [(j, j_score, j_block) for j, (xj_min, yj_min, xj_max, yj_max, j_area, j_score, j_block) in
  226. enumerate(block_info)
  227. if i != j and j not in marked_indices and is_inside(block_info[j], block_info[i],
  228. overlap_threshold)]
  229. # 如果内部有3个及以上的小block
  230. if len(blocks_inside) >= 2:
  231. # 计算小block的平均分数
  232. avg_score = sum(s for _, s, _ in blocks_inside) / len(blocks_inside)
  233. # 比较大block的分数和小block的平均分数
  234. if score > avg_score:
  235. # 保留大block,扩展其边界
  236. # 首先将所有小block标记为要删除
  237. for j, _, j_block in blocks_inside:
  238. if j_block not in blocks_to_remove:
  239. blocks_to_remove.append(j_block)
  240. marked_indices.add(j) # 标记索引为已处理
  241. # 扩展大block的边界以包含所有小block
  242. new_xmin, new_ymin, new_xmax, new_ymax = xmin, ymin, xmax, ymax
  243. for _, _, j_block in blocks_inside:
  244. j_xmin, j_ymin = int(j_block['poly'][0]), int(j_block['poly'][1])
  245. j_xmax, j_ymax = int(j_block['poly'][4]), int(j_block['poly'][5])
  246. new_xmin = min(new_xmin, j_xmin)
  247. new_ymin = min(new_ymin, j_ymin)
  248. new_xmax = max(new_xmax, j_xmax)
  249. new_ymax = max(new_ymax, j_ymax)
  250. # 更新大block的边界
  251. block['poly'][0] = block['poly'][6] = new_xmin
  252. block['poly'][1] = block['poly'][3] = new_ymin
  253. block['poly'][2] = block['poly'][4] = new_xmax
  254. block['poly'][5] = block['poly'][7] = new_ymax
  255. else:
  256. # 保留小blocks,删除大block
  257. blocks_to_remove.append(block)
  258. marked_indices.add(i) # 标记当前索引为已处理
  259. return blocks_to_remove
  260. # @todo 这个方法以后需要重构
  261. def get_res_list_from_layout_res(layout_res, iou_threshold=0.7, overlap_threshold=0.8, area_threshold=0.8):
  262. """Extract OCR, table and other regions from layout results."""
  263. ocr_res_list = []
  264. text_res_list = []
  265. table_res_list = []
  266. table_indices = []
  267. single_page_mfdetrec_res = []
  268. # Categorize regions
  269. for i, res in enumerate(layout_res):
  270. category_id = int(res['category_id'])
  271. if category_id in [13, 14]: # Formula regions
  272. single_page_mfdetrec_res.append({
  273. "bbox": [int(res['poly'][0]), int(res['poly'][1]),
  274. int(res['poly'][4]), int(res['poly'][5])],
  275. })
  276. elif category_id in [0, 2, 4, 6, 7, 3]: # OCR regions
  277. ocr_res_list.append(res)
  278. elif category_id == 5: # Table regions
  279. table_res_list.append(res)
  280. table_indices.append(i)
  281. elif category_id in [1]: # Text regions
  282. res['bbox'] = [int(res['poly'][0]), int(res['poly'][1]), int(res['poly'][4]), int(res['poly'][5])]
  283. text_res_list.append(res)
  284. # Process tables: merge high IoU tables first, then filter nested tables
  285. table_res_list, table_indices = merge_high_iou_tables(
  286. table_res_list, layout_res, table_indices, iou_threshold)
  287. filtered_table_res_list = filter_nested_tables(
  288. table_res_list, overlap_threshold, area_threshold)
  289. for table_res in filtered_table_res_list:
  290. table_res['bbox'] = [int(table_res['poly'][0]), int(table_res['poly'][1]), int(table_res['poly'][4]), int(table_res['poly'][5])]
  291. filtered_table_res_list, table_need_remove = remove_overlaps_min_blocks(filtered_table_res_list)
  292. for res in filtered_table_res_list:
  293. # 将res的poly使用bbox重构
  294. res['poly'] = [res['bbox'][0], res['bbox'][1], res['bbox'][2], res['bbox'][1],
  295. res['bbox'][2], res['bbox'][3], res['bbox'][0], res['bbox'][3]]
  296. # 删除res的bbox
  297. del res['bbox']
  298. if len(table_need_remove) > 0:
  299. for res in table_need_remove:
  300. del res['bbox']
  301. if res in layout_res:
  302. layout_res.remove(res)
  303. # Remove filtered out tables from layout_res
  304. if len(filtered_table_res_list) < len(table_res_list):
  305. kept_tables = set(id(table) for table in filtered_table_res_list)
  306. tables_to_remove = [table for table in table_res_list if id(table) not in kept_tables]
  307. for table in tables_to_remove:
  308. if table in layout_res:
  309. layout_res.remove(table)
  310. # Remove overlaps in OCR and text regions
  311. text_res_list, need_remove = remove_overlaps_min_blocks(text_res_list)
  312. for res in text_res_list:
  313. # 将res的poly使用bbox重构
  314. res['poly'] = [res['bbox'][0], res['bbox'][1], res['bbox'][2], res['bbox'][1],
  315. res['bbox'][2], res['bbox'][3], res['bbox'][0], res['bbox'][3]]
  316. # 删除res的bbox
  317. del res['bbox']
  318. ocr_res_list.extend(text_res_list)
  319. if len(need_remove) > 0:
  320. for res in need_remove:
  321. del res['bbox']
  322. if res in layout_res:
  323. layout_res.remove(res)
  324. # 检测大block内部是否包含多个小block, 合并ocr和table列表进行检测
  325. combined_res_list = ocr_res_list + filtered_table_res_list
  326. blocks_to_remove = remove_overlaps_low_confidence_blocks(combined_res_list, overlap_threshold)
  327. # 移除需要删除的blocks
  328. for block in blocks_to_remove:
  329. if block in ocr_res_list:
  330. ocr_res_list.remove(block)
  331. elif block in filtered_table_res_list:
  332. filtered_table_res_list.remove(block)
  333. # 同时从layout_res中删除
  334. if block in layout_res:
  335. layout_res.remove(block)
  336. return ocr_res_list, filtered_table_res_list, single_page_mfdetrec_res
  337. def clean_memory(device='cuda'):
  338. if device == 'cuda':
  339. if torch.cuda.is_available():
  340. torch.cuda.empty_cache()
  341. torch.cuda.ipc_collect()
  342. elif str(device).startswith("npu"):
  343. if torch_npu.npu.is_available():
  344. torch_npu.npu.empty_cache()
  345. elif str(device).startswith("mps"):
  346. torch.mps.empty_cache()
  347. gc.collect()
  348. def clean_vram(device, vram_threshold=8):
  349. total_memory = get_vram(device)
  350. if total_memory and total_memory <= vram_threshold:
  351. gc_start = time.time()
  352. clean_memory(device)
  353. gc_time = round(time.time() - gc_start, 2)
  354. logger.info(f"gc time: {gc_time}")
  355. def get_vram(device):
  356. if torch.cuda.is_available() and str(device).startswith("cuda"):
  357. total_memory = torch.cuda.get_device_properties(device).total_memory / (1024 ** 3) # 将字节转换为 GB
  358. return total_memory
  359. elif str(device).startswith("npu"):
  360. if torch_npu.npu.is_available():
  361. total_memory = torch_npu.npu.get_device_properties(device).total_memory / (1024 ** 3) # 转为 GB
  362. return total_memory
  363. else:
  364. return None