fix_table.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. from magic_pdf.libs.commons import fitz # pyMuPDF库
  2. import re
  3. from magic_pdf.libs.boxbase import _is_in_or_part_overlap, _is_part_overlap, find_bottom_nearest_text_bbox, find_left_nearest_text_bbox, find_right_nearest_text_bbox, find_top_nearest_text_bbox # json
  4. ## version 2
  5. def get_merged_line(page):
  6. """
  7. 这个函数是为了从pymuPDF中提取出的矢量里筛出水平的横线,并且将断开的线段进行了合并。
  8. :param page :fitz读取的当前页的内容
  9. """
  10. drawings_bbox = []
  11. drawings_line = []
  12. drawings = page.get_drawings() # 提取所有的矢量
  13. for p in drawings:
  14. drawings_bbox.append(p["rect"].irect) # (L, U, R, D)
  15. lines = []
  16. for L, U, R, D in drawings_bbox:
  17. if abs(D - U) <= 3: # 筛出水平的横线
  18. lines.append((L, U, R, D))
  19. U_groups = []
  20. visited = [False for _ in range(len(lines))]
  21. for i, (L1, U1, R1, D1) in enumerate(lines):
  22. if visited[i] == True:
  23. continue
  24. tmp_g = [(L1, U1, R1, D1)]
  25. for j, (L2, U2, R2, D2) in enumerate(lines):
  26. if i == j:
  27. continue
  28. if visited[j] == True:
  29. continue
  30. if max(U1, D1, U2, D2) - min(U1, D1, U2, D2) <= 5: # 把高度一致的线放进一个group
  31. tmp_g.append((L2, U2, R2, D2))
  32. visited[j] = True
  33. U_groups.append(tmp_g)
  34. res = []
  35. for group in U_groups:
  36. group.sort(key = lambda LURD: (LURD[0], LURD[2]))
  37. LL, UU, RR, DD = group[0]
  38. for i, (L1, U1, R1, D1) in enumerate(group):
  39. if (L1 - RR) >= 5:
  40. cur_line = (LL, UU, RR, DD)
  41. res.append(cur_line)
  42. LL = L1
  43. else:
  44. RR = max(RR, R1)
  45. cur_line = (LL, UU, RR, DD)
  46. res.append(cur_line)
  47. return res
  48. def fix_tables(page: fitz.Page, table_bboxes: list, include_table_title: bool, scan_line_num: int):
  49. """
  50. :param page :fitz读取的当前页的内容
  51. :param table_bboxes: list类型,每一个元素是一个元祖 (L, U, R, D)
  52. :param include_table_title: 是否将表格的标题也圈进来
  53. :param scan_line_num: 在与表格框临近的上下几个文本框里扫描搜索标题
  54. """
  55. drawings_lines = get_merged_line(page)
  56. fix_table_bboxes = []
  57. for table in table_bboxes:
  58. (L, U, R, D) = table
  59. fix_table_L = []
  60. fix_table_U = []
  61. fix_table_R = []
  62. fix_table_D = []
  63. width = R - L
  64. width_range = width * 0.1 # 只看距离表格整体宽度10%之内偏差的线
  65. height = D - U
  66. height_range = height * 0.1 # 只看距离表格整体高度10%之内偏差的线
  67. for line in drawings_lines:
  68. if (L - width_range) <= line[0] <= (L + width_range) and (R - width_range) <= line[2] <= (R + width_range): # 相近的宽度
  69. if (U - height_range) < line[1] < (U + height_range): # 上边界,在一定的高度范围内
  70. fix_table_U.append(line[1])
  71. fix_table_L.append(line[0])
  72. fix_table_R.append(line[2])
  73. elif (D - height_range) < line[1] < (D + height_range): # 下边界,在一定的高度范围内
  74. fix_table_D.append(line[1])
  75. fix_table_L.append(line[0])
  76. fix_table_R.append(line[2])
  77. if fix_table_U:
  78. U = min(fix_table_U)
  79. if fix_table_D:
  80. D = max(fix_table_D)
  81. if fix_table_L:
  82. L = min(fix_table_L)
  83. if fix_table_R:
  84. R = max(fix_table_R)
  85. if include_table_title: # 需要将表格标题包括
  86. text_blocks = page.get_text("dict", flags=fitz.TEXTFLAGS_TEXT)["blocks"] # 所有的text的block
  87. incolumn_text_blocks = [block for block in text_blocks if not ((block['bbox'][0] < L and block['bbox'][2] < L) or (block['bbox'][0] > R and block['bbox'][2] > R))] # 将与表格完全没有任何遮挡的文字筛除掉(比如另一栏的文字)
  88. upper_text_blocks = [block for block in incolumn_text_blocks if (U - block['bbox'][3]) > 0] # 将在表格线以上的text block筛选出来
  89. sorted_filtered_text_blocks = sorted(upper_text_blocks, key=lambda x: (U - x['bbox'][3], x['bbox'][0])) # 按照text block的下边界距离表格上边界的距离升序排序,如果是同一个高度,则先左再右
  90. for idx in range(scan_line_num):
  91. if idx+1 <= len(sorted_filtered_text_blocks):
  92. line_temp = sorted_filtered_text_blocks[idx]['lines']
  93. if line_temp:
  94. text = line_temp[0]['spans'][0]['text'] # 提取出第一个span里的text内容
  95. check_en = re.match('Table', text) # 检查是否有Table开头的(英文)
  96. check_ch = re.match('表', text) # 检查是否有Table开头的(中文)
  97. if check_en or check_ch:
  98. if sorted_filtered_text_blocks[idx]['bbox'][1] < D: # 以防出现负的bbox
  99. U = sorted_filtered_text_blocks[idx]['bbox'][1]
  100. fix_table_bboxes.append([L-2, U-2, R+2, D+2])
  101. return fix_table_bboxes
  102. def __check_table_title_pattern(text):
  103. """
  104. 检查文本段是否是表格的标题
  105. """
  106. patterns = [r'^table\s\d+']
  107. for pattern in patterns:
  108. match = re.match(pattern, text, re.IGNORECASE)
  109. if match:
  110. return True
  111. else:
  112. return False
  113. def fix_table_text_block(pymu_blocks, table_bboxes: list):
  114. """
  115. 调整table, 如果table和上下的text block有相交区域,则将table的上下边界调整到text block的上下边界
  116. 例如 tmp/unittest/unittest_pdf/纯2列_ViLT_6_文字 表格.pdf
  117. """
  118. for tb in table_bboxes:
  119. (L, U, R, D) = tb
  120. for block in pymu_blocks:
  121. if _is_in_or_part_overlap((L, U, R, D), block['bbox']):
  122. txt = " ".join(span['text'] for line in block['lines'] for span in line['spans'])
  123. if not __check_table_title_pattern(txt) and block.get("_table", False) is False: # 如果是table的title,那么不调整。因为下一步会统一调整,如果这里进行了调整,后面的调整会造成调整到其他table的title上(在连续出现2个table的情况下)。
  124. tb[0] = min(tb[0], block['bbox'][0])
  125. tb[1] = min(tb[1], block['bbox'][1])
  126. tb[2] = max(tb[2], block['bbox'][2])
  127. tb[3] = max(tb[3], block['bbox'][3])
  128. block['_table'] = True # 占位,防止其他table再次占用
  129. """如果是个table的title,但是有部分重叠,那么修正这个title,使得和table不重叠"""
  130. if _is_part_overlap(tb, block['bbox']) and __check_table_title_pattern(txt):
  131. block['bbox'] = list(block['bbox'])
  132. if block['bbox'][3] > U:
  133. block['bbox'][3] = U-1
  134. if block['bbox'][1] < D:
  135. block['bbox'][1] = D+1
  136. return table_bboxes
  137. def __get_table_caption_text(text_block):
  138. txt = " ".join(span['text'] for line in text_block['lines'] for span in line['spans'])
  139. line_cnt = len(text_block['lines'])
  140. txt = txt.replace("Ž . ", '')
  141. return txt, line_cnt
  142. def include_table_title(pymu_blocks, table_bboxes: list):
  143. """
  144. 把表格的title也包含进来,扩展到table_bbox上
  145. """
  146. for tb in table_bboxes:
  147. max_find_cnt = 3 # 上上最多找3次
  148. temp_box = tb.copy()
  149. while max_find_cnt>0:
  150. text_block_top = find_top_nearest_text_bbox(pymu_blocks, temp_box)
  151. if text_block_top:
  152. txt, line_cnt = __get_table_caption_text(text_block_top)
  153. if len(txt.strip())>0:
  154. if not __check_table_title_pattern(txt) and max_find_cnt>0 and line_cnt<3:
  155. max_find_cnt = max_find_cnt -1
  156. temp_box[1] = text_block_top['bbox'][1]
  157. continue
  158. else:
  159. break
  160. else:
  161. temp_box[1] = text_block_top['bbox'][1] # 宽度不变,扩大
  162. max_find_cnt = max_find_cnt - 1
  163. else:
  164. break
  165. max_find_cnt = 3 # 向下找
  166. temp_box = tb.copy()
  167. while max_find_cnt>0:
  168. text_block_bottom = find_bottom_nearest_text_bbox(pymu_blocks, temp_box)
  169. if text_block_bottom:
  170. txt, line_cnt = __get_table_caption_text(text_block_bottom)
  171. if len(txt.strip())>0:
  172. if not __check_table_title_pattern(txt) and max_find_cnt>0 and line_cnt<3:
  173. max_find_cnt = max_find_cnt - 1
  174. temp_box[3] = text_block_bottom['bbox'][3]
  175. continue
  176. else:
  177. break
  178. else:
  179. temp_box[3] = text_block_bottom['bbox'][3]
  180. max_find_cnt = max_find_cnt - 1
  181. else:
  182. break
  183. if text_block_top and text_block_bottom and text_block_top.get("_table_caption", False) is False and text_block_bottom.get("_table_caption", False) is False :
  184. btn_text, _ = __get_table_caption_text(text_block_bottom)
  185. top_text, _ = __get_table_caption_text(text_block_top)
  186. if __check_table_title_pattern(btn_text) and __check_table_title_pattern(top_text): # 上下都有一个tbale的caption
  187. # 取距离最近的
  188. btn_text_distance = text_block_bottom['bbox'][1] - tb[3]
  189. top_text_distance = tb[1] - text_block_top['bbox'][3]
  190. text_block = text_block_bottom if btn_text_distance<top_text_distance else text_block_top
  191. tb[0] = min(tb[0], text_block['bbox'][0])
  192. tb[1] = min(tb[1], text_block['bbox'][1])
  193. tb[2] = max(tb[2], text_block['bbox'][2])
  194. tb[3] = max(tb[3], text_block['bbox'][3])
  195. text_block_bottom['_table_caption'] = True
  196. continue
  197. # 如果以上条件都不满足,那么就向下找
  198. text_block = text_block_top
  199. if text_block and text_block.get("_table_caption", False) is False:
  200. first_text_line = " ".join(span['text'] for line in text_block['lines'] for span in line['spans'])
  201. if __check_table_title_pattern(first_text_line) and text_block.get("_table", False) is False:
  202. tb[0] = min(tb[0], text_block['bbox'][0])
  203. tb[1] = min(tb[1], text_block['bbox'][1])
  204. tb[2] = max(tb[2], text_block['bbox'][2])
  205. tb[3] = max(tb[3], text_block['bbox'][3])
  206. text_block['_table_caption'] = True
  207. continue
  208. text_block = text_block_bottom
  209. if text_block and text_block.get("_table_caption", False) is False:
  210. first_text_line, _ = __get_table_caption_text(text_block)
  211. if __check_table_title_pattern(first_text_line) and text_block.get("_table", False) is False:
  212. tb[0] = min(tb[0], text_block['bbox'][0])
  213. tb[1] = min(tb[1], text_block['bbox'][1])
  214. tb[2] = max(tb[2], text_block['bbox'][2])
  215. tb[3] = max(tb[3], text_block['bbox'][3])
  216. text_block['_table_caption'] = True
  217. continue
  218. """向左、向右寻找,暂时只寻找一次"""
  219. left_text_block = find_left_nearest_text_bbox(pymu_blocks, tb)
  220. if left_text_block and left_text_block.get("_image_caption", False) is False:
  221. first_text_line, _ = __get_table_caption_text(left_text_block)
  222. if __check_table_title_pattern(first_text_line):
  223. tb[0] = min(tb[0], left_text_block['bbox'][0])
  224. tb[1] = min(tb[1], left_text_block['bbox'][1])
  225. tb[2] = max(tb[2], left_text_block['bbox'][2])
  226. tb[3] = max(tb[3], left_text_block['bbox'][3])
  227. left_text_block['_image_caption'] = True
  228. continue
  229. right_text_block = find_right_nearest_text_bbox(pymu_blocks, tb)
  230. if right_text_block and right_text_block.get("_image_caption", False) is False:
  231. first_text_line, _ = __get_table_caption_text(right_text_block)
  232. if __check_table_title_pattern(first_text_line):
  233. tb[0] = min(tb[0], right_text_block['bbox'][0])
  234. tb[1] = min(tb[1], right_text_block['bbox'][1])
  235. tb[2] = max(tb[2], right_text_block['bbox'][2])
  236. tb[3] = max(tb[3], right_text_block['bbox'][3])
  237. right_text_block['_image_caption'] = True
  238. continue
  239. return table_bboxes