model_utils.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import time
  2. import torch
  3. from loguru import logger
  4. import numpy as np
  5. from magic_pdf.libs.clean_memory import clean_memory
  6. def crop_img(input_res, input_np_img, crop_paste_x=0, crop_paste_y=0):
  7. crop_xmin, crop_ymin = int(input_res['poly'][0]), int(input_res['poly'][1])
  8. crop_xmax, crop_ymax = int(input_res['poly'][4]), int(input_res['poly'][5])
  9. # Calculate new dimensions
  10. crop_new_width = crop_xmax - crop_xmin + crop_paste_x * 2
  11. crop_new_height = crop_ymax - crop_ymin + crop_paste_y * 2
  12. # Create a white background array
  13. return_image = np.ones((crop_new_height, crop_new_width, 3), dtype=np.uint8) * 255
  14. # Crop the original image using numpy slicing
  15. cropped_img = input_np_img[crop_ymin:crop_ymax, crop_xmin:crop_xmax]
  16. # Paste the cropped image onto the white background
  17. return_image[crop_paste_y:crop_paste_y + (crop_ymax - crop_ymin),
  18. crop_paste_x:crop_paste_x + (crop_xmax - crop_xmin)] = cropped_img
  19. return_list = [crop_paste_x, crop_paste_y, crop_xmin, crop_ymin, crop_xmax, crop_ymax, crop_new_width,
  20. crop_new_height]
  21. return return_image, return_list
  22. def get_coords_and_area(table):
  23. """Extract coordinates and area from a table."""
  24. xmin, ymin = int(table['poly'][0]), int(table['poly'][1])
  25. xmax, ymax = int(table['poly'][4]), int(table['poly'][5])
  26. area = (xmax - xmin) * (ymax - ymin)
  27. return xmin, ymin, xmax, ymax, area
  28. def calculate_intersection(box1, box2):
  29. """Calculate intersection coordinates between two boxes."""
  30. intersection_xmin = max(box1[0], box2[0])
  31. intersection_ymin = max(box1[1], box2[1])
  32. intersection_xmax = min(box1[2], box2[2])
  33. intersection_ymax = min(box1[3], box2[3])
  34. # Check if intersection is valid
  35. if intersection_xmax <= intersection_xmin or intersection_ymax <= intersection_ymin:
  36. return None
  37. return intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax
  38. def calculate_iou(box1, box2):
  39. """Calculate IoU between two boxes."""
  40. intersection = calculate_intersection(box1[:4], box2[:4])
  41. if not intersection:
  42. return 0
  43. intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax = intersection
  44. intersection_area = (intersection_xmax - intersection_xmin) * (intersection_ymax - intersection_ymin)
  45. area1, area2 = box1[4], box2[4]
  46. union_area = area1 + area2 - intersection_area
  47. return intersection_area / union_area if union_area > 0 else 0
  48. def is_inside(small_box, big_box, overlap_threshold=0.8):
  49. """Check if small_box is inside big_box by at least overlap_threshold."""
  50. intersection = calculate_intersection(small_box[:4], big_box[:4])
  51. if not intersection:
  52. return False
  53. intersection_xmin, intersection_ymin, intersection_xmax, intersection_ymax = intersection
  54. intersection_area = (intersection_xmax - intersection_xmin) * (intersection_ymax - intersection_ymin)
  55. # Check if overlap exceeds threshold
  56. return intersection_area >= overlap_threshold * small_box[4]
  57. def do_overlap(box1, box2):
  58. """Check if two boxes overlap."""
  59. return calculate_intersection(box1[:4], box2[:4]) is not None
  60. def merge_high_iou_tables(table_res_list, layout_res, table_indices, iou_threshold=0.7):
  61. """Merge tables with IoU > threshold."""
  62. if len(table_res_list) < 2:
  63. return table_res_list, table_indices
  64. table_info = [get_coords_and_area(table) for table in table_res_list]
  65. merged = True
  66. while merged:
  67. merged = False
  68. i = 0
  69. while i < len(table_res_list) - 1:
  70. j = i + 1
  71. while j < len(table_res_list):
  72. iou = calculate_iou(table_info[i], table_info[j])
  73. if iou > iou_threshold:
  74. # Merge tables by taking their union
  75. x1_min, y1_min, x1_max, y1_max, _ = table_info[i]
  76. x2_min, y2_min, x2_max, y2_max, _ = table_info[j]
  77. union_xmin = min(x1_min, x2_min)
  78. union_ymin = min(y1_min, y2_min)
  79. union_xmax = max(x1_max, x2_max)
  80. union_ymax = max(y1_max, y2_max)
  81. # Create merged table
  82. merged_table = table_res_list[i].copy()
  83. merged_table['poly'][0] = union_xmin
  84. merged_table['poly'][1] = union_ymin
  85. merged_table['poly'][2] = union_xmax
  86. merged_table['poly'][3] = union_ymin
  87. merged_table['poly'][4] = union_xmax
  88. merged_table['poly'][5] = union_ymax
  89. merged_table['poly'][6] = union_xmin
  90. merged_table['poly'][7] = union_ymax
  91. # Update layout_res
  92. to_remove = [table_indices[j], table_indices[i]]
  93. for idx in sorted(to_remove, reverse=True):
  94. del layout_res[idx]
  95. layout_res.append(merged_table)
  96. # Update tracking lists
  97. table_indices = [k if k < min(to_remove) else
  98. k - 1 if k < max(to_remove) else
  99. k - 2 if k > max(to_remove) else
  100. len(layout_res) - 1
  101. for k in table_indices
  102. if k not in to_remove]
  103. table_indices.append(len(layout_res) - 1)
  104. # Update table lists
  105. table_res_list.pop(j)
  106. table_res_list.pop(i)
  107. table_res_list.append(merged_table)
  108. # Update table_info
  109. table_info = [get_coords_and_area(table) for table in table_res_list]
  110. merged = True
  111. break
  112. j += 1
  113. if merged:
  114. break
  115. i += 1
  116. return table_res_list, table_indices
  117. def filter_nested_tables(table_res_list, overlap_threshold=0.8, area_threshold=0.8):
  118. """Remove big tables containing multiple smaller tables within them."""
  119. if len(table_res_list) < 3:
  120. return table_res_list
  121. table_info = [get_coords_and_area(table) for table in table_res_list]
  122. big_tables_idx = []
  123. for i in range(len(table_res_list)):
  124. # Find tables inside this one
  125. tables_inside = [j for j in range(len(table_res_list))
  126. if i != j and is_inside(table_info[j], table_info[i], overlap_threshold)]
  127. # Continue if there are at least 2 tables inside
  128. if len(tables_inside) >= 2:
  129. # Check if inside tables overlap with each other
  130. tables_overlap = any(do_overlap(table_info[tables_inside[idx1]], table_info[tables_inside[idx2]])
  131. for idx1 in range(len(tables_inside))
  132. for idx2 in range(idx1 + 1, len(tables_inside)))
  133. # If no overlaps, check area condition
  134. if not tables_overlap:
  135. total_inside_area = sum(table_info[j][4] for j in tables_inside)
  136. big_table_area = table_info[i][4]
  137. if total_inside_area > area_threshold * big_table_area:
  138. big_tables_idx.append(i)
  139. return [table for i, table in enumerate(table_res_list) if i not in big_tables_idx]
  140. def get_res_list_from_layout_res(layout_res, iou_threshold=0.7, overlap_threshold=0.8, area_threshold=0.8):
  141. """Extract OCR, table and other regions from layout results."""
  142. ocr_res_list = []
  143. table_res_list = []
  144. table_indices = []
  145. single_page_mfdetrec_res = []
  146. # Categorize regions
  147. for i, res in enumerate(layout_res):
  148. category_id = int(res['category_id'])
  149. if category_id in [13, 14]: # Formula regions
  150. single_page_mfdetrec_res.append({
  151. "bbox": [int(res['poly'][0]), int(res['poly'][1]),
  152. int(res['poly'][4]), int(res['poly'][5])],
  153. })
  154. elif category_id in [0, 1, 2, 4, 6, 7]: # OCR regions
  155. ocr_res_list.append(res)
  156. elif category_id == 5: # Table regions
  157. table_res_list.append(res)
  158. table_indices.append(i)
  159. # Process tables: merge high IoU tables first, then filter nested tables
  160. table_res_list, table_indices = merge_high_iou_tables(
  161. table_res_list, layout_res, table_indices, iou_threshold)
  162. filtered_table_res_list = filter_nested_tables(
  163. table_res_list, overlap_threshold, area_threshold)
  164. # Remove filtered out tables from layout_res
  165. if len(filtered_table_res_list) < len(table_res_list):
  166. kept_tables = set(id(table) for table in filtered_table_res_list)
  167. to_remove = [table_indices[i] for i, table in enumerate(table_res_list)
  168. if id(table) not in kept_tables]
  169. for idx in sorted(to_remove, reverse=True):
  170. del layout_res[idx]
  171. return ocr_res_list, filtered_table_res_list, single_page_mfdetrec_res
  172. def clean_vram(device, vram_threshold=8):
  173. total_memory = get_vram(device)
  174. if total_memory and total_memory <= vram_threshold:
  175. gc_start = time.time()
  176. clean_memory(device)
  177. gc_time = round(time.time() - gc_start, 2)
  178. logger.info(f"gc time: {gc_time}")
  179. def get_vram(device):
  180. if torch.cuda.is_available() and str(device).startswith("cuda"):
  181. total_memory = torch.cuda.get_device_properties(device).total_memory / (1024 ** 3) # 将字节转换为 GB
  182. return total_memory
  183. elif str(device).startswith("npu"):
  184. import torch_npu
  185. if torch_npu.npu.is_available():
  186. total_memory = torch_npu.npu.get_device_properties(device).total_memory / (1024 ** 3) # 转为 GB
  187. return total_memory
  188. else:
  189. return None