model_utils.py 18 KB

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