model_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. def crop_img(input_res, input_img, crop_paste_x=0, crop_paste_y=0):
  8. crop_xmin, crop_ymin = int(input_res['poly'][0]), int(input_res['poly'][1])
  9. crop_xmax, crop_ymax = int(input_res['poly'][4]), int(input_res['poly'][5])
  10. # Calculate new dimensions
  11. crop_new_width = crop_xmax - crop_xmin + crop_paste_x * 2
  12. crop_new_height = crop_ymax - crop_ymin + crop_paste_y * 2
  13. if isinstance(input_img, np.ndarray):
  14. # Create a white background array
  15. return_image = np.ones((crop_new_height, crop_new_width, 3), dtype=np.uint8) * 255
  16. # Crop the original image using numpy slicing
  17. cropped_img = input_img[crop_ymin:crop_ymax, crop_xmin:crop_xmax]
  18. # Paste the cropped image onto the white background
  19. return_image[crop_paste_y:crop_paste_y + (crop_ymax - crop_ymin),
  20. crop_paste_x:crop_paste_x + (crop_xmax - crop_xmin)] = cropped_img
  21. else:
  22. # Create a white background array
  23. return_image = Image.new('RGB', (crop_new_width, crop_new_height), 'white')
  24. # Crop image
  25. crop_box = (crop_xmin, crop_ymin, crop_xmax, crop_ymax)
  26. cropped_img = input_img.crop(crop_box)
  27. return_image.paste(cropped_img, (crop_paste_x, crop_paste_y))
  28. return_list = [crop_paste_x, crop_paste_y, crop_xmin, crop_ymin, crop_xmax, crop_ymax, crop_new_width,
  29. crop_new_height]
  30. return return_image, return_list
  31. def get_coords_and_area(block_with_poly):
  32. """Extract coordinates and area from a table."""
  33. xmin, ymin = int(block_with_poly['poly'][0]), int(block_with_poly['poly'][1])
  34. xmax, ymax = int(block_with_poly['poly'][4]), int(block_with_poly['poly'][5])
  35. area = (xmax - xmin) * (ymax - ymin)
  36. return xmin, ymin, xmax, ymax, area
  37. def calculate_intersection(box1, box2):
  38. """Calculate intersection coordinates between two boxes."""
  39. intersection_xmin = max(box1[0], box2[0])
  40. intersection_ymin = max(box1[1], box2[1])
  41. intersection_xmax = min(box1[2], box2[2])
  42. intersection_ymax = min(box1[3], box2[3])
  43. # Check if intersection is valid
  44. if intersection_xmax <= intersection_xmin or intersection_ymax <= intersection_ymin:
  45. return None
  46. return intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax
  47. def calculate_iou(box1, box2):
  48. """Calculate IoU between two boxes."""
  49. intersection = calculate_intersection(box1[:4], box2[:4])
  50. if not intersection:
  51. return 0
  52. intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax = intersection
  53. intersection_area = (intersection_xmax - intersection_xmin) * (intersection_ymax - intersection_ymin)
  54. area1, area2 = box1[4], box2[4]
  55. union_area = area1 + area2 - intersection_area
  56. return intersection_area / union_area if union_area > 0 else 0
  57. def is_inside(small_box, big_box, overlap_threshold=0.8):
  58. """Check if small_box is inside big_box by at least overlap_threshold."""
  59. intersection = calculate_intersection(small_box[:4], big_box[:4])
  60. if not intersection:
  61. return False
  62. intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax = intersection
  63. intersection_area = (intersection_xmax - intersection_xmin) * (intersection_ymax - intersection_ymin)
  64. # Check if overlap exceeds threshold
  65. return intersection_area >= overlap_threshold * small_box[4]
  66. def do_overlap(box1, box2):
  67. """Check if two boxes overlap."""
  68. return calculate_intersection(box1[:4], box2[:4]) is not None
  69. def merge_high_iou_tables(table_res_list, layout_res, table_indices, iou_threshold=0.7):
  70. """Merge tables with IoU > threshold."""
  71. if len(table_res_list) < 2:
  72. return table_res_list, table_indices
  73. table_info = [get_coords_and_area(table) for table in table_res_list]
  74. merged = True
  75. while merged:
  76. merged = False
  77. i = 0
  78. while i < len(table_res_list) - 1:
  79. j = i + 1
  80. while j < len(table_res_list):
  81. iou = calculate_iou(table_info[i], table_info[j])
  82. if iou > iou_threshold:
  83. # Merge tables by taking their union
  84. x1_min, y1_min, x1_max, y1_max, _ = table_info[i]
  85. x2_min, y2_min, x2_max, y2_max, _ = table_info[j]
  86. union_xmin = min(x1_min, x2_min)
  87. union_ymin = min(y1_min, y2_min)
  88. union_xmax = max(x1_max, x2_max)
  89. union_ymax = max(y1_max, y2_max)
  90. # Create merged table
  91. merged_table = table_res_list[i].copy()
  92. merged_table['poly'][0] = union_xmin
  93. merged_table['poly'][1] = union_ymin
  94. merged_table['poly'][2] = union_xmax
  95. merged_table['poly'][3] = union_ymin
  96. merged_table['poly'][4] = union_xmax
  97. merged_table['poly'][5] = union_ymax
  98. merged_table['poly'][6] = union_xmin
  99. merged_table['poly'][7] = union_ymax
  100. # Update layout_res
  101. to_remove = [table_indices[j], table_indices[i]]
  102. for idx in sorted(to_remove, reverse=True):
  103. del layout_res[idx]
  104. layout_res.append(merged_table)
  105. # Update tracking lists
  106. table_indices = [k if k < min(to_remove) else
  107. k - 1 if k < max(to_remove) else
  108. k - 2 if k > max(to_remove) else
  109. len(layout_res) - 1
  110. for k in table_indices
  111. if k not in to_remove]
  112. table_indices.append(len(layout_res) - 1)
  113. # Update table lists
  114. table_res_list.pop(j)
  115. table_res_list.pop(i)
  116. table_res_list.append(merged_table)
  117. # Update table_info
  118. table_info = [get_coords_and_area(table) for table in table_res_list]
  119. merged = True
  120. break
  121. j += 1
  122. if merged:
  123. break
  124. i += 1
  125. return table_res_list, table_indices
  126. def filter_nested_tables(table_res_list, overlap_threshold=0.8, area_threshold=0.8):
  127. """Remove big tables containing multiple smaller tables within them."""
  128. if len(table_res_list) < 3:
  129. return table_res_list
  130. table_info = [get_coords_and_area(table) for table in table_res_list]
  131. big_tables_idx = []
  132. for i in range(len(table_res_list)):
  133. # Find tables inside this one
  134. tables_inside = [j for j in range(len(table_res_list))
  135. if i != j and is_inside(table_info[j], table_info[i], overlap_threshold)]
  136. # Continue if there are at least 3 tables inside
  137. if len(tables_inside) >= 3:
  138. # Check if inside tables overlap with each other
  139. tables_overlap = any(do_overlap(table_info[tables_inside[idx1]], table_info[tables_inside[idx2]])
  140. for idx1 in range(len(tables_inside))
  141. for idx2 in range(idx1 + 1, len(tables_inside)))
  142. # If no overlaps, check area condition
  143. if not tables_overlap:
  144. total_inside_area = sum(table_info[j][4] for j in tables_inside)
  145. big_table_area = table_info[i][4]
  146. if total_inside_area > area_threshold * big_table_area:
  147. big_tables_idx.append(i)
  148. return [table for i, table in enumerate(table_res_list) if i not in big_tables_idx]
  149. def remove_overlaps_min_blocks(res_list):
  150. # 重叠block,小的不能直接删除,需要和大的那个合并成一个更大的。
  151. # 删除重叠blocks中较小的那些
  152. need_remove = []
  153. for res1 in res_list:
  154. for res2 in res_list:
  155. if res1 != res2:
  156. overlap_box = get_minbox_if_overlap_by_ratio(
  157. res1['bbox'], res2['bbox'], 0.8
  158. )
  159. if overlap_box is not None:
  160. res_to_remove = next(
  161. (res for res in res_list if res['bbox'] == overlap_box),
  162. None,
  163. )
  164. if (
  165. res_to_remove is not None
  166. and res_to_remove not in need_remove
  167. ):
  168. large_res = res1 if res1 != res_to_remove else res2
  169. x1, y1, x2, y2 = large_res['bbox']
  170. sx1, sy1, sx2, sy2 = res_to_remove['bbox']
  171. x1 = min(x1, sx1)
  172. y1 = min(y1, sy1)
  173. x2 = max(x2, sx2)
  174. y2 = max(y2, sy2)
  175. large_res['bbox'] = [x1, y1, x2, y2]
  176. need_remove.append(res_to_remove)
  177. if len(need_remove) > 0:
  178. for res in need_remove:
  179. res_list.remove(res)
  180. return res_list, need_remove
  181. def get_res_list_from_layout_res(layout_res, iou_threshold=0.7, overlap_threshold=0.8, area_threshold=0.8):
  182. """Extract OCR, table and other regions from layout results."""
  183. ocr_res_list = []
  184. text_res_list = []
  185. table_res_list = []
  186. table_indices = []
  187. single_page_mfdetrec_res = []
  188. # Categorize regions
  189. for i, res in enumerate(layout_res):
  190. category_id = int(res['category_id'])
  191. if category_id in [13, 14]: # Formula regions
  192. single_page_mfdetrec_res.append({
  193. "bbox": [int(res['poly'][0]), int(res['poly'][1]),
  194. int(res['poly'][4]), int(res['poly'][5])],
  195. })
  196. elif category_id in [0, 2, 4, 6, 7, 3]: # OCR regions
  197. ocr_res_list.append(res)
  198. elif category_id == 5: # Table regions
  199. table_res_list.append(res)
  200. table_indices.append(i)
  201. elif category_id in [1]: # Text regions
  202. res['bbox'] = [int(res['poly'][0]), int(res['poly'][1]), int(res['poly'][4]), int(res['poly'][5])]
  203. text_res_list.append(res)
  204. # Process tables: merge high IoU tables first, then filter nested tables
  205. table_res_list, table_indices = merge_high_iou_tables(
  206. table_res_list, layout_res, table_indices, iou_threshold)
  207. filtered_table_res_list = filter_nested_tables(
  208. table_res_list, overlap_threshold, area_threshold)
  209. # Remove filtered out tables from layout_res
  210. if len(filtered_table_res_list) < len(table_res_list):
  211. kept_tables = set(id(table) for table in filtered_table_res_list)
  212. to_remove = [table_indices[i] for i, table in enumerate(table_res_list)
  213. if id(table) not in kept_tables]
  214. for idx in sorted(to_remove, reverse=True):
  215. del layout_res[idx]
  216. # Remove overlaps in OCR and text regions
  217. text_res_list, need_remove = remove_overlaps_min_blocks(text_res_list)
  218. for res in text_res_list:
  219. # 将res的poly使用bbox重构
  220. res['poly'] = [res['bbox'][0], res['bbox'][1], res['bbox'][2], res['bbox'][1],
  221. res['bbox'][2], res['bbox'][3], res['bbox'][0], res['bbox'][3]]
  222. # 删除res的bbox
  223. del res['bbox']
  224. ocr_res_list.extend(text_res_list)
  225. if len(need_remove) > 0:
  226. for res in need_remove:
  227. del res['bbox']
  228. layout_res.remove(res)
  229. return ocr_res_list, filtered_table_res_list, single_page_mfdetrec_res
  230. def clean_memory(device='cuda'):
  231. import torch
  232. if device == 'cuda':
  233. if torch.cuda.is_available():
  234. torch.cuda.empty_cache()
  235. torch.cuda.ipc_collect()
  236. elif str(device).startswith("npu"):
  237. import torch_npu
  238. if torch_npu.npu.is_available():
  239. torch_npu.npu.empty_cache()
  240. elif str(device).startswith("mps"):
  241. torch.mps.empty_cache()
  242. gc.collect()
  243. def clean_vram(device, vram_threshold=8):
  244. total_memory = get_vram(device)
  245. if total_memory and total_memory <= vram_threshold:
  246. gc_start = time.time()
  247. clean_memory(device)
  248. gc_time = round(time.time() - gc_start, 2)
  249. logger.info(f"gc time: {gc_time}")
  250. def get_vram(device):
  251. import torch
  252. if torch.cuda.is_available() and str(device).startswith("cuda"):
  253. total_memory = torch.cuda.get_device_properties(device).total_memory / (1024 ** 3) # 将字节转换为 GB
  254. return total_memory
  255. elif str(device).startswith("npu"):
  256. import torch_npu
  257. if torch_npu.npu.is_available():
  258. total_memory = torch_npu.npu.get_device_properties(device).total_memory / (1024 ** 3) # 转为 GB
  259. return total_memory
  260. else:
  261. return None