detect_footer_header_by_statistics.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. from collections import defaultdict
  2. from pdf_tools.libs.boxbase import calculate_iou
  3. def compare_bbox_with_list(bbox, bbox_list, tolerance=1):
  4. return any(all(abs(a - b) < tolerance for a, b in zip(bbox, common_bbox)) for common_bbox in bbox_list)
  5. def is_single_line_block(block):
  6. # Determine based on the width and height of the block
  7. block_width = block["X1"] - block["X0"]
  8. block_height = block["bbox"][3] - block["bbox"][1]
  9. # If the height of the block is close to the average character height and the width is large, it is considered a single line
  10. return block_height <= block["avg_char_height"] * 3 and block_width > block["avg_char_width"] * 3
  11. def get_most_common_bboxes(bboxes, page_height, position="top", threshold=0.25, num_bboxes=3, min_frequency=2):
  12. """
  13. This function gets the most common bboxes from the bboxes
  14. Parameters
  15. ----------
  16. bboxes : list
  17. bboxes
  18. page_height : float
  19. height of the page
  20. position : str, optional
  21. "top" or "bottom", by default "top"
  22. threshold : float, optional
  23. threshold, by default 0.25
  24. num_bboxes : int, optional
  25. number of bboxes to return, by default 3
  26. min_frequency : int, optional
  27. minimum frequency of the bbox, by default 2
  28. Returns
  29. -------
  30. common_bboxes : list
  31. common bboxes
  32. """
  33. # Filter bbox by position
  34. if position == "top":
  35. filtered_bboxes = [bbox for bbox in bboxes if bbox[1] < page_height * threshold]
  36. else:
  37. filtered_bboxes = [bbox for bbox in bboxes if bbox[3] > page_height * (1 - threshold)]
  38. # Find the most common bbox
  39. bbox_count = defaultdict(int)
  40. for bbox in filtered_bboxes:
  41. bbox_count[tuple(bbox)] += 1
  42. # Get the most frequently occurring bbox, but only consider it when the frequency exceeds min_frequency
  43. common_bboxes = [
  44. bbox for bbox, count in sorted(bbox_count.items(), key=lambda item: item[1], reverse=True) if count >= min_frequency
  45. ][:num_bboxes]
  46. return common_bboxes
  47. def detect_footer_header2(result_dict, similarity_threshold=0.5):
  48. """
  49. This function detects the header and footer of the document.
  50. Parameters
  51. ----------
  52. result_dict : dict
  53. result dictionary
  54. Returns
  55. -------
  56. result_dict : dict
  57. result dictionary
  58. """
  59. # Traverse all blocks in the document
  60. single_line_blocks = 0
  61. total_blocks = 0
  62. single_line_blocks = 0
  63. for page_id, blocks in result_dict.items():
  64. if page_id.startswith("page_"):
  65. for block_key, block in blocks.items():
  66. if block_key.startswith("block_"):
  67. total_blocks += 1
  68. if is_single_line_block(block):
  69. single_line_blocks += 1
  70. # If there are no blocks, skip the header and footer detection
  71. if total_blocks == 0:
  72. print("No blocks found. Skipping header/footer detection.")
  73. return result_dict
  74. # If most of the blocks are single-line, skip the header and footer detection
  75. if single_line_blocks / total_blocks > 0.5: # 50% of the blocks are single-line
  76. # print("Skipping header/footer detection for text-dense document.")
  77. return result_dict
  78. # Collect the bounding boxes of all blocks
  79. all_bboxes = []
  80. all_texts = []
  81. for page_id, blocks in result_dict.items():
  82. if page_id.startswith("page_"):
  83. for block_key, block in blocks.items():
  84. if block_key.startswith("block_"):
  85. all_bboxes.append(block["bbox"])
  86. # Get the height of the page
  87. page_height = max(bbox[3] for bbox in all_bboxes)
  88. # Get the most common bbox lists for headers and footers
  89. common_header_bboxes = get_most_common_bboxes(all_bboxes, page_height, position="top") if all_bboxes else []
  90. common_footer_bboxes = get_most_common_bboxes(all_bboxes, page_height, position="bottom") if all_bboxes else []
  91. # Detect and mark headers and footers
  92. for page_id, blocks in result_dict.items():
  93. if page_id.startswith("page_"):
  94. for block_key, block in blocks.items():
  95. if block_key.startswith("block_"):
  96. bbox = block["bbox"]
  97. text = block["text"]
  98. is_header = compare_bbox_with_list(bbox, common_header_bboxes)
  99. is_footer = compare_bbox_with_list(bbox, common_footer_bboxes)
  100. block["is_header"] = int(is_header)
  101. block["is_footer"] = int(is_footer)
  102. return result_dict
  103. def __get_page_size(page_sizes:list):
  104. """
  105. 页面大小可能不一样
  106. """
  107. w = sum([w for w,h in page_sizes])/len(page_sizes)
  108. h = sum([h for w,h in page_sizes])/len(page_sizes)
  109. return w, h
  110. def __calculate_iou(bbox1, bbox2):
  111. iou = calculate_iou(bbox1, bbox2)
  112. return iou
  113. def __is_same_pos(box1, box2, iou_threshold):
  114. iou = __calculate_iou(box1, box2)
  115. return iou >= iou_threshold
  116. def get_most_common_bbox(bboxes:list, page_size:list, page_cnt:int, page_range_threshold=0.2, iou_threshold=0.9):
  117. """
  118. common bbox必须大于page_cnt的1/3
  119. """
  120. min_occurance_cnt = max(3, page_cnt//4)
  121. header_det_bbox = []
  122. footer_det_bbox = []
  123. hdr_same_pos_group = []
  124. btn_same_pos_group = []
  125. page_w, page_h = __get_page_size(page_size)
  126. top_y, bottom_y = page_w*page_range_threshold, page_h*(1-page_range_threshold)
  127. top_bbox = [b for b in bboxes if b[3]<top_y]
  128. bottom_bbox = [b for b in bboxes if b[1]>bottom_y]
  129. # 然后开始排序,寻找最经常出现的bbox, 寻找的时候如果IOU>iou_threshold就算是一个
  130. for i in range(0, len(top_bbox)):
  131. hdr_same_pos_group.append([top_bbox[i]])
  132. for j in range(i+1, len(top_bbox)):
  133. if __is_same_pos(top_bbox[i], top_bbox[j], iou_threshold):
  134. #header_det_bbox = [min(top_bbox[i][0], top_bbox[j][0]), min(top_bbox[i][1], top_bbox[j][1]), max(top_bbox[i][2], top_bbox[j][2]), max(top_bbox[i][3],top_bbox[j][3])]
  135. hdr_same_pos_group[i].append(top_bbox[j])
  136. for i in range(0, len(bottom_bbox)):
  137. btn_same_pos_group.append([bottom_bbox[i]])
  138. for j in range(i+1, len(bottom_bbox)):
  139. if __is_same_pos(bottom_bbox[i], bottom_bbox[j], iou_threshold):
  140. #footer_det_bbox = [min(bottom_bbox[i][0], bottom_bbox[j][0]), min(bottom_bbox[i][1], bottom_bbox[j][1]), max(bottom_bbox[i][2], bottom_bbox[j][2]), max(bottom_bbox[i][3],bottom_bbox[j][3])]
  141. btn_same_pos_group[i].append(bottom_bbox[j])
  142. # 然后看下每一组的bbox,是否符合大于page_cnt一定比例
  143. hdr_same_pos_group = [g for g in hdr_same_pos_group if len(g)>=min_occurance_cnt]
  144. btn_same_pos_group = [g for g in btn_same_pos_group if len(g)>=min_occurance_cnt]
  145. # 平铺2个list[list]
  146. hdr_same_pos_group = [bbox for g in hdr_same_pos_group for bbox in g]
  147. btn_same_pos_group = [bbox for g in btn_same_pos_group for bbox in g]
  148. # 寻找hdr_same_pos_group中的box[3]最大值,btn_same_pos_group中的box[1]最小值
  149. hdr_same_pos_group.sort(key=lambda b:b[3])
  150. btn_same_pos_group.sort(key=lambda b:b[1])
  151. hdr_y = hdr_same_pos_group[-1][3] if hdr_same_pos_group else 0
  152. btn_y = btn_same_pos_group[0][1] if btn_same_pos_group else page_h
  153. header_det_bbox = [0, 0, page_w, hdr_y]
  154. footer_det_bbox = [0, btn_y, page_w, page_h]
  155. # logger.warning(f"header: {header_det_bbox}, footer: {footer_det_bbox}")
  156. return header_det_bbox, footer_det_bbox, page_w, page_h
  157. def drop_footer_header(pdf_info_dict:dict):
  158. """
  159. 启用规则探测,在全局的视角上通过统计的方法。
  160. """
  161. header = []
  162. footer = []
  163. all_text_bboxes = [blk['bbox'] for _, val in pdf_info_dict.items() for blk in val['preproc_blocks']]
  164. image_bboxes = [img['bbox'] for _, val in pdf_info_dict.items() for img in val['images']] + [img['bbox'] for _, val in pdf_info_dict.items() for img in val['image_backup']]
  165. page_size = [val['page_size'] for _, val in pdf_info_dict.items()]
  166. page_cnt = len(pdf_info_dict.keys()) # 一共多少页
  167. header, footer, page_w, page_h = get_most_common_bbox(all_text_bboxes+image_bboxes, page_size, page_cnt)
  168. """"
  169. 把范围扩展到页面水平的整个方向上
  170. """
  171. if header:
  172. header = [0, 0, page_w, header[3]+1]
  173. if footer:
  174. footer = [0, footer[1]-1, page_w, page_h]
  175. # 找到footer, header范围之后,针对每一页pdf,从text、图片中删除这些范围内的内容
  176. # 移除text block
  177. for _, page_info in pdf_info_dict.items():
  178. header_text_blk = []
  179. footer_text_blk = []
  180. for blk in page_info['preproc_blocks']:
  181. blk_bbox = blk['bbox']
  182. if header and blk_bbox[3]<=header[3]:
  183. blk['tag'] = "header"
  184. header_text_blk.append(blk)
  185. elif footer and blk_bbox[1]>=footer[1]:
  186. blk['tag'] = "footer"
  187. footer_text_blk.append(blk)
  188. # 放入text_block_droped中
  189. page_info['droped_text_block'].extend(header_text_blk)
  190. page_info['droped_text_block'].extend(footer_text_blk)
  191. for blk in header_text_blk:
  192. page_info['preproc_blocks'].remove(blk)
  193. for blk in footer_text_blk:
  194. page_info['preproc_blocks'].remove(blk)
  195. """接下来把footer、header上的图片也删除掉。图片包括正常的和backup的"""
  196. header_image = []
  197. footer_image = []
  198. for image_info in page_info['images']:
  199. img_bbox = image_info['bbox']
  200. if header and img_bbox[3]<=header[3]:
  201. image_info['tag'] = "header"
  202. header_image.append(image_info)
  203. elif footer and img_bbox[1]>=footer[1]:
  204. image_info['tag'] = "footer"
  205. footer_image.append(image_info)
  206. page_info['droped_image_block'].extend(header_image)
  207. page_info['droped_image_block'].extend(footer_image)
  208. for img in header_image:
  209. page_info['images'].remove(img)
  210. for img in footer_image:
  211. page_info['images'].remove(img)
  212. """接下来吧backup的图片也删除掉"""
  213. header_image = []
  214. footer_image = []
  215. for image_info in page_info['image_backup']:
  216. img_bbox = image_info['bbox']
  217. if header and img_bbox[3]<=header[3]:
  218. image_info['tag'] = "header"
  219. header_image.append(image_info)
  220. elif footer and img_bbox[1]>=footer[1]:
  221. image_info['tag'] = "footer"
  222. footer_image.append(image_info)
  223. page_info['droped_image_block'].extend(header_image)
  224. page_info['droped_image_block'].extend(footer_image)
  225. for img in header_image:
  226. page_info['image_backup'].remove(img)
  227. for img in footer_image:
  228. page_info['image_backup'].remove(img)
  229. return header, footer