pdf2text_recogFootnoteLine.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. import re
  2. from magic_pdf.libs import _is_in_or_part_overlap
  3. from magic_pdf.libs import fitz
  4. import collections
  5. def calculate_overlapRatio_between_rect1_and_rect2(L1: float, U1: float, R1: float, D1: float, L2: float, U2: float, R2: float, D2: float) -> (float, float):
  6. # 计算两个rect,重叠面积各占2个rect面积的比例
  7. if min(R1, R2) < max(L1, L2) or min(D1, D2) < max(U1, U2):
  8. return 0, 0
  9. square_1 = (R1 - L1) * (D1 - U1)
  10. square_2 = (R2 - L2) * (D2 - U2)
  11. if square_1 == 0 or square_2 == 0:
  12. return 0, 0
  13. square_overlap = (min(R1, R2) - max(L1, L2)) * (min(D1, D2) - max(U1, U2))
  14. return square_overlap / square_1, square_overlap / square_2
  15. def calculate_overlapRatio_between_line1_and_line2(L1: float, R1: float, L2: float, R2: float) -> (float, float):
  16. # 计算两个line,重叠区间各占2个line长度的比例
  17. if max(L1, L2) > min(R1, R2):
  18. return 0, 0
  19. if L1 == R1 or L2 == R2:
  20. return 0, 0
  21. overlap_line = min(R1, R2) - max(L1, L2)
  22. return overlap_line / (R1 - L1), overlap_line / (R2 - L2)
  23. def parse_footnoteLine(page_ID: int, page: fitz.Page, json_from_DocXchain_obj, exclude_bboxes):
  24. """
  25. :param page_ID: int类型,当前page在当前pdf文档中是第page_D页。
  26. :param page :fitz读取的当前页的内容
  27. :param res_dir_path: str类型,是每一个pdf文档,在当前.py文件的目录下生成一个与pdf文档同名的文件夹,res_dir_path就是文件夹的dir
  28. :param json_from_DocXchain_obj: dict类型,把pdf文档送入DocXChain模型中后,提取bbox,结果保存到pdf文档同名文件夹下的 page_ID.json文件中了。json_from_DocXchain_obj就是打开后的dict
  29. """
  30. DPI = 72 # use this resolution
  31. pix = page.get_pixmap(dpi=DPI)
  32. pageL = 0
  33. pageR = int(pix.w)
  34. pageU = 0
  35. pageD = int(pix.h)
  36. #---------------------- PyMuPDF解析text --------------------#
  37. textSize_freq = collections.defaultdict(float) # text块中,textSize的频率
  38. textBlock_bboxs = []
  39. textLine_bboxs = []
  40. text_blocks = page.get_text(
  41. "dict",
  42. flags=fitz.TEXTFLAGS_TEXT,
  43. #clip=clip,
  44. )["blocks"]
  45. totText_list = []
  46. for i in range(len(text_blocks)):
  47. # print(blocks[i]) #### print
  48. bbox = text_blocks[i]['bbox']
  49. textBlock_bboxs.append(bbox)
  50. # print(bbox)
  51. cur_block_text_list = []
  52. for tt in text_blocks[i]['lines']:
  53. # 当前line
  54. cur_line_text_list = []
  55. cur_line_bbox = None # 当前line,最右侧的section的bbox
  56. for xf in tt['spans']:
  57. L, U, R, D = xf['bbox']
  58. L, R = min(L, R), max(L, R)
  59. U, D = min(U, D), max(U, D)
  60. textLine_bboxs.append((L, U, R, D))
  61. cur_line_text_list.append(xf['text'])
  62. textSize_freq[xf['size']] += len(xf['text'])
  63. cur_lines_text = ' '.join(cur_line_text_list)
  64. cur_block_text_list.append(cur_lines_text)
  65. totText_list.append('\n'.join(cur_block_text_list))
  66. totText = '\n'.join(totText_list)
  67. # print(totText) # 打印Text
  68. textLine_bboxs.sort(key = lambda LURD: (LURD[0], LURD[1]))
  69. textBlock_bboxs.sort(key = lambda LURD: (LURD[0], LURD[1]))
  70. # print('------------ textSize_freq -----------')
  71. max_sizeFreq = 0 # 出现频率最高的textSize
  72. textSize_withMaxFreq = 0
  73. for x, f in textSize_freq.items():
  74. # print(x, f)
  75. if f > max_sizeFreq:
  76. max_sizeFreq = f
  77. textSize_withMaxFreq = x
  78. #**********************************************************#
  79. #------------------ PyMuPDF读取drawings -----------------#
  80. horizon_lines = []
  81. drawings = page.get_cdrawings()
  82. for drawing in drawings:
  83. try:
  84. rect = drawing['rect']
  85. L, U, R, D = rect
  86. # if (L, U, R, D) in exclude_bboxes:
  87. # continue # 如果是Fiugre, Table, Equation。注释掉是因为,可以暂时先不消,先自我对消。最后再判读需不需要排除。
  88. # 如果是水平线
  89. if U <= D and D - U <= 3:
  90. # 如果长度够
  91. if (pageR - pageL) / 15 <= R - L:
  92. if not(80/800 * pageD <= U <= 750/800 * pageD):
  93. continue # 很可能是页眉和页脚的线
  94. horizon_lines.append((L, U, R, D))
  95. # print((L, U, R, D))
  96. except:
  97. pass
  98. horizon_lines.sort(key = lambda LURD: (LURD[1]))
  99. #********************************************************#
  100. #----------------- 两条线可能是在表格中 ------------------#
  101. def has_text_below_line(L: float, U: float, R: float, D: float, inLowerArea: bool) -> bool:
  102. """
  103. 检查线下是否紧挨着text
  104. """
  105. Uu, Du = U - textSize_withMaxFreq, U # 线上的一个矩形
  106. Lu, Ru = L, R
  107. Ud, Dd = U, U + textSize_withMaxFreq # 线下的一个矩形
  108. Ld, Rd = L, R
  109. find = 0 # 在线下的文字。统计面积。
  110. leftTextCnt = 0 # 不在线底下的文字(整体在线左侧的文字),说明不是个脚注线。统计面积。
  111. English_alpha_cnt = 0 # 英文字母个数
  112. nonEnglish_alpha_cnt = 0 # 非英文字母个数
  113. punctuation_mark_cnt = 0 # 常见标点符号个数
  114. digit_cnt = 0 # 数字个数
  115. distance_nearest_up_line = None
  116. distance_nearest_down_line = None
  117. for i in range(len(text_blocks)):
  118. # print(blocks[i]) #### print
  119. bbox = text_blocks[i]['bbox']
  120. L0, U0, R0, D0 = bbox
  121. if 0< (R0 - L0) < pageR / 6 and (D0 - U0) / (R0 - L0) > 10 :
  122. continue # 一个很窄的,竖直的长条。比如,arXiv预印本,左侧的arXiv标志信息。
  123. textBlock_bboxs.append(bbox)
  124. # print(bbox)
  125. cur_block_text_list = []
  126. for tt in text_blocks[i]['lines']:
  127. # 当前line
  128. cur_line_text_list = []
  129. cur_line_bbox = None # 当前line,最右侧的section的bbox
  130. for xf in tt['spans']:
  131. L2, U2, R2, D2 = xf['bbox']
  132. L2, R2 = min(L2, R2), max(L2, R2)
  133. U2, D2 = min(U2, D2), max(U2, D2)
  134. textLine = xf['text']
  135. if L>0 and L2 < L and (L - L2) / L > 0.2:
  136. leftTextCnt += abs(R2 - L2) * abs(D2 - U2)
  137. else:
  138. ## 线下的部分
  139. ratio_1, ratio_2 = calculate_overlapRatio_between_line1_and_line2(Ud, Dd, U2, D2)
  140. ratio_3, ratio_4 = calculate_overlapRatio_between_line1_and_line2(Ld, Rd, L2, R2)
  141. if U < (U2 + D2) / 2 and ratio_1 > 0 and ratio_2 > 0:
  142. if max(ratio_3, ratio_4) > 0.8:
  143. # if 444 <= U1 < 445 and 55 <= L2 < 56:
  144. # print('匹配的框', L2, U2, R2, D2)
  145. # if xf['size'] > 1.2 * textSize_withMaxFreq:
  146. # return False # 可能是个标题。不能这样卡
  147. find += abs(R2 - L2) * abs(D2 - U2)
  148. distance_nearest_down_line = (U2 + D2) / 2 - U
  149. for c in textLine:
  150. if c == ' ':
  151. continue
  152. elif c.isdigit() == True:
  153. digit_cnt += 1
  154. elif c in ',.:!?[]()%,。、!?:【】()《》-':
  155. punctuation_mark_cnt += 1
  156. elif c.isalpha() == True:
  157. English_alpha_cnt += 1
  158. else:
  159. nonEnglish_alpha_cnt += 1
  160. ## 线上的部分
  161. ratio_5, ratio_6 = calculate_overlapRatio_between_line1_and_line2(Uu, Du, U2, D2)
  162. ratio_7, ratio_8 = calculate_overlapRatio_between_line1_and_line2(Lu, Ru, L2, R2)
  163. if (U2 + D2) / 2 < U and ratio_5 > 0 and ratio_6 > 0:
  164. if max(ratio_7, ratio_8) > 0.8:
  165. distance_nearest_up_line = U - (U2 + D2) / 2
  166. # if distance_nearest_up_line < 0:
  167. # print(Lu, Uu, Ru, Du, L2, U2, R2, D2)
  168. # print(distance_nearest_up_line, distance_nearest_down_line)
  169. if distance_nearest_up_line != None and distance_nearest_down_line != None:
  170. if distance_nearest_up_line * 1.5 < distance_nearest_down_line:
  171. return False # 如果,一根线。距离上面的文字line更近。说明是个下划线,而不是footnoteLine
  172. ## 在上面的线条,要考虑左侧的text块儿。在很靠下的线条,就暂时不考虑左侧text块儿了。
  173. if inLowerArea == False:
  174. if leftTextCnt >= 2000/500000 * pageR * pageD:
  175. return False
  176. return find >= 0 and (English_alpha_cnt + nonEnglish_alpha_cnt + digit_cnt) >= 10
  177. ## 最下面区域的线条,判断时。
  178. # print(English_alpha_cnt, nonEnglish_alpha_cnt, digit_cnt)
  179. if (English_alpha_cnt + nonEnglish_alpha_cnt + digit_cnt) == 0:
  180. return False
  181. if (English_alpha_cnt + digit_cnt) / (English_alpha_cnt + nonEnglish_alpha_cnt + digit_cnt) > 0.5:
  182. if nonEnglish_alpha_cnt / (English_alpha_cnt + nonEnglish_alpha_cnt + digit_cnt) > 0.4:
  183. return False
  184. else:
  185. return True
  186. return True
  187. visited = [False for _ in range(len(horizon_lines))]
  188. for i, b1 in enumerate(horizon_lines):
  189. for j in range(i + 1, len(horizon_lines)):
  190. L1, U1, R1, D1 = horizon_lines[i]
  191. L2, U2, R2, D2 = horizon_lines[j]
  192. ## 在一条水平线,且挨着
  193. if L1 > L2:
  194. L1, U1, R1, D1, L2, U2, R2, D2 = L2, U2, R2, D2, L1, U1, R1, D1
  195. in_horizontal_line_flag = (max(U1, D1, U2, D2) - min(U1, D1, U2, D2) <= 5) and (L2 - R1 <= pageR/10)
  196. if in_horizontal_line_flag == True:
  197. visited[i] = True
  198. visited[j] = True
  199. ## 在竖直方向上是一致的。(表格,或者有的文章就是喜欢划线)
  200. L1, U1, R1, D1 = horizon_lines[i]
  201. L2, U2, R2, D2 = horizon_lines[j]
  202. ratio_1, ratio_2 = calculate_overlapRatio_between_line1_and_line2(L1, R1, L2, R2)
  203. # print(L1, U1, R1, D1, L2, U2, R2, D2, ratio_1, ratio_2)
  204. in_vertical_line_flag = (ratio_1 > 0.9 and ratio_2 > 0.9) or (max(ratio_1, ratio_2) > 0.95)
  205. if in_vertical_line_flag == True:
  206. visited[i] = True
  207. # if (U2 < pageD * 0.8 or (U2 - U1) < pageD * 0.3) and has_text_below_line(L2, U2, R2, D2, False) == False:
  208. # visited[j] = True # 最最底下的线先不要动
  209. else:
  210. if ratio_1 > 0 and (R2 - L2) / (R1 - L1) > 1:
  211. visited[i] = True
  212. # print(horizon_lines)
  213. horizon_lines = [horizon_lines[i] for i in range(len(horizon_lines)) if visited[i] == False]
  214. # print(horizon_lines)
  215. #*****************************************************************#
  216. #------- 靠上的,就不是脚注。用一个THRESHOLD直接卡掉位于上半页的 -------#
  217. visited = [False for _ in range(len(horizon_lines))]
  218. THRESHOLD = (pageD - pageU) * 0.5
  219. for i, (L, U, R, D) in enumerate(horizon_lines):
  220. if U < THRESHOLD:
  221. visited[i] = True
  222. horizon_lines = [horizon_lines[i] for i in range(len(horizon_lines)) if visited[i] == False]
  223. #******************************************************#
  224. #--------------- 此时,还有遮挡的,上面的丢弃 ---------------#
  225. visited = [False for _ in range(len(horizon_lines))]
  226. for i, (L1, U1, R1, D1) in enumerate(horizon_lines):
  227. for j in range(i + 1, len(horizon_lines)):
  228. L2, U2, R2, D2 = horizon_lines[j]
  229. ratio_1, ratio_2 = calculate_overlapRatio_between_line1_and_line2(L1, R1, L2, R2)
  230. if (ratio_1 > 0.2 and ratio_2 > 0.2) or max(ratio_1, ratio_2) > 0.7:
  231. visited[i] = True
  232. horizon_lines = [horizon_lines[i] for i in range(len(horizon_lines)) if visited[i] == False]
  233. #********************************************************#
  234. # print(horizon_lines)
  235. ## 检查,线下面有没有紧挨着的text
  236. horizon_lines = [LURD for LURD in horizon_lines if has_text_below_line(*(LURD), True) == True]
  237. # print(horizon_lines)
  238. ## 卡一下长度
  239. # horizon_lines = [LURD for LURD in horizon_lines if (LURD[2] - LURD[0] >= pageR / 10)]
  240. ## 上面最多保留2条
  241. horizon_lines = horizon_lines[max(-2, -len(horizon_lines)) :]
  242. #----------------------------------------------------- 第2段 -----------------------------------------------------------#
  243. #----------------------------------- 最下面的情形,用距离硬卡。还有在右侧的情形就被包含了 -----------------------------------#
  244. #------------------ PyMuPDF读取drawings -----------------#
  245. down_horizon_lines = []
  246. drawings = page.get_cdrawings()
  247. for drawing in drawings:
  248. try:
  249. rect = drawing['rect']
  250. L, U, R, D = rect
  251. # if (L, U, R, D) in exclude_bboxes:
  252. # continue # 如果是Fiugre, Table, Equation。目前是Figure识别的比较好。但是Table和Equation识别的不好
  253. # 如果是水平线
  254. if U <= D and D - U <= 3 and U > pageD * 0.85:
  255. # 如果长度够
  256. if (pageR - pageL) / 15 <= R - L:
  257. down_horizon_lines.append((L, U, R, D))
  258. # print((L, U, R, D))
  259. except:
  260. pass
  261. down_horizon_lines.sort(key = lambda LURD: (LURD[0], LURD[2], LURD[1]))
  262. visited = [False for _ in range(len(down_horizon_lines))]
  263. for i in range(len(down_horizon_lines) - 1):
  264. L1, U1, R1, D1 = down_horizon_lines[i]
  265. L2, U2, R2, D2 = down_horizon_lines[i + 1]
  266. ratio_1, ratio_2 = calculate_overlapRatio_between_line1_and_line2(L1, R1, L2, R2)
  267. if ratio_1 <= 0.1 and ratio_2 <= 0.1:
  268. if L2 - R1 <= pageR / 3:
  269. visited[i] = True
  270. visited[i + 1] = True
  271. down_horizon_lines = [down_horizon_lines[i] for i in range(len(down_horizon_lines)) if visited[i] == False]
  272. down_horizon_lines = [LURD for LURD in down_horizon_lines if has_text_below_line(*(LURD), True) == True]
  273. # for LURD in down_horizon_lines:
  274. # print('第2阶段,LURD是: ', LURD)
  275. # print(has_text_below_line(*(LURD), True))
  276. footnoteLines = horizon_lines + down_horizon_lines
  277. footnoteLines = list(set(footnoteLines))
  278. footnoteLines = footnoteLines[max(-2, -len(footnoteLines)) : ]
  279. #-------------------------- 最后再检查一遍。是否在图片、表格、公式中。 ------------------------------#
  280. def line_in_specialBboxes(L: float, U: float, R: float, D: float, specialBboxes) -> bool:
  281. L2, U2, R2, D2 = L, U, R, D # 当前这根线
  282. for L1, U1, R1, D1 in specialBboxes:
  283. if U1 <= U2 <= D2 < D1:
  284. ratio_1, ratio_2 = calculate_overlapRatio_between_line1_and_line2(L1, R1, L2, R2)
  285. if ratio_1 > 0 and ratio_2 > 0.6:
  286. return True
  287. # else:
  288. # U1 -= min(textSize_withMaxFreq * 2, 20)
  289. # D1 += min(textSize_withMaxFreq * 2, 20)
  290. # if U1 <= U2 <= D2 < D1:
  291. # ratio_1, ratio_2 = calculate_overlapRatio_between_line1_and_line2(L1, R1, L2, R2)
  292. # if ratio_1 > 0 and ratio_2 > 0.8:
  293. # return True
  294. return False
  295. footnoteLines = [LURD for LURD in footnoteLines if line_in_specialBboxes(*(LURD), exclude_bboxes) == False]
  296. #-------------------------- 检查,线,是否在当前column的左侧,而不是在一段文字的中间 (通过DocXChain识别的column或者徐超老师写的Layout识别)------------------------------#
  297. # #--------- 通过json_from_DocXchain来获取 column ---------#
  298. # column_bbox_from_DocXChain = []
  299. # xf_json = json_from_DocXchain_obj
  300. # width_from_json = xf_json['page_info']['width']
  301. # height_from_json = xf_json['page_info']['height']
  302. # LR_scaleRatio = width_from_json / (pageR - pageL)
  303. # UD_scaleRatio = height_from_json / (pageD - pageU)
  304. # # {0: 'title', # 标题
  305. # # 1: 'figure', # 图片
  306. # # 2: 'plain text', # 文本
  307. # # 3: 'header', # 页眉
  308. # # 4: 'page number', # 页码
  309. # # 5: 'footnote', # 脚注
  310. # # 6: 'footer', # 页脚
  311. # # 7: 'table', # 表格
  312. # # 8: 'table caption', # 表格描述
  313. # # 9: 'figure caption', # 图片描述
  314. # # 10: 'equation', # 公式
  315. # # 11: 'full column', # 单栏
  316. # # 12: 'sub column', # 多栏
  317. # # 13: 'embedding', # 嵌入公式
  318. # # 14: 'isolated'} # 单行公式
  319. # for xf in xf_json['layout_dets']:
  320. # L = xf['poly'][0] / LR_scaleRatio
  321. # U = xf['poly'][1] / UD_scaleRatio
  322. # R = xf['poly'][2] / LR_scaleRatio
  323. # D = xf['poly'][5] / UD_scaleRatio
  324. # # L += pageL # 有的页面,artBox偏移了。不在(0,0)
  325. # # R += pageL
  326. # # U += pageU
  327. # # D += pageU
  328. # L, R = min(L, R), max(L, R)
  329. # U, D = min(U, D), max(U, D)
  330. # if (xf['category_id'] == 11 or xf['category_id'] == 12) and xf['score'] >= 0.3:
  331. # column_bbox_from_DocXChain.append((L, U, R, D))
  332. #---------------手写,检查,线是否是与某个column的左端对齐 ------------------#
  333. def check_isOnTheLeftOfColumn(L: float, U: float, R: float, D: float) -> bool:
  334. LL = L - textSize_withMaxFreq
  335. RR = LL
  336. UU = max(pageD * 0.02, U - 100/800 * pageD)
  337. DD = min(U + 50/800 * pageD, pageD * 0.98)
  338. # print(LL, UU, RR, DD)
  339. cnt = 0
  340. for bbox in textLine_bboxs:
  341. L2, U2, R2, D2 = bbox
  342. ratio_1, ratio_2 = calculate_overlapRatio_between_line1_and_line2(UU, DD, U2, D2)
  343. ratio_3, ratio_4 = calculate_overlapRatio_between_line1_and_line2(L, R, L2, R2)
  344. if ratio_1 > 0 and ratio_2 > 0:
  345. if max(ratio_3, ratio_4) > 0.8:
  346. if abs(LL - L2) <= 20/700 * pageR:
  347. cnt += 1
  348. # else:
  349. # if (R2 - L2) >= 30/700 * pageR:
  350. # print(LL, UU, RR, DD, L2, U2, R2, D2)
  351. # return False # 不能这样卡。有些注释里面,单独的特殊符号就是一个textLineBbox
  352. # print('cnt: ', cnt)
  353. return cnt >= 4
  354. # def check_isOnTheLeftOfColumn_considerLayout(L0: float, U0: float, R0: float, D0: float) -> bool:
  355. # LL = L0 - textSize_withMaxFreq * 1.5
  356. # RR = LL
  357. # UU = 100/800 * pageD
  358. # DD = 700/800 * pageD
  359. # STEP = textSize_withMaxFreq / 2
  360. # def check_ok(L: float, U: float, R: float, D: float) -> bool:
  361. # for bbox in textBlock_bboxs:
  362. # L2, U2, R2, D2 = bbox
  363. # ratio_3, ratio_4 = calculate_overlapRatio_between_line1_and_line2(L, R, L2, R2)
  364. # if max(ratio_3, ratio_4) > 0.8:
  365. # if (R2 - L2) > 1/4 * pageR and L2 < LL <= RR < R2:
  366. # if abs(LL - L2) < 50/700 * pageR or abs(RR - R2) < 50/700 * pageR:
  367. # continue
  368. # else:
  369. # return False
  370. # return True
  371. # ## 先探上面
  372. # u = UU
  373. # d = U0
  374. # while u + STEP/2 < d:
  375. # mid = (u + d) / 2
  376. # if check_ok(L0, mid, R0, U0) == True:
  377. # d = mid
  378. # else:
  379. # u = mid + STEP
  380. # print(mid)
  381. # dist_up = U0 - u
  382. # print(u)
  383. # ## 再探下面
  384. # u = D0
  385. # d = DD
  386. # while u + STEP/2 < d:
  387. # mid = (u + d) / 2
  388. # if check_ok(L0, mid, R0, D0) == True:
  389. # u = mid
  390. # else:
  391. # d = mid - STEP
  392. # print(u)
  393. # print('^^^^^^^^^^^^^^')
  394. # dist_down = u - D0
  395. # if dist_up + dist_down < textSize_withMaxFreq * 10:
  396. # return False
  397. # return True
  398. footnoteLines = [LURD for LURD in footnoteLines if check_isOnTheLeftOfColumn(*(LURD)) == True]
  399. # footnoteLines = [LURD for LURD in footnoteLines if check_isOnTheLeftOfColumn_considerLayout(*(LURD)) == True] # 不具有泛化性。不用了。
  400. #--------------------------------- 通过footnoteLine获取bbox -------------------------------#
  401. def get_footnoteBbox(L: float, U: float, R: float, D: float) -> (float, float, float, float):
  402. """
  403. 检查线下是否紧挨着text
  404. """
  405. L1, U1, R1, D1 = L, U, R, D
  406. raw_bboxes = []
  407. for i in range(len(text_blocks)):
  408. bbox = text_blocks[i]['bbox']
  409. L2, U2, R2, D2 = bbox
  410. if (D2 - U2) / (R2 - L2) > 10 and (R2 - L2) < pageR / 6:
  411. continue # 一个很窄的,竖直的长条。比如,arXiv预印本,左侧的arXiv标志信息。
  412. if U2 < D2 < U1:
  413. continue # 在线上面
  414. under_THRESHOLD = min(D1 + textSize_withMaxFreq * 20, pageD * 0.98)
  415. if U2 < under_THRESHOLD:
  416. ratio_1, ratio_2 = calculate_overlapRatio_between_line1_and_line2(L1, R1, L2, R2)
  417. if max(ratio_1, ratio_2) > 0.8:
  418. raw_bboxes.append((L2, U2, R2, D2))
  419. # print(L1, U1, R1, D1)
  420. # print(raw_bboxes)
  421. if len(raw_bboxes) == 0:
  422. return []
  423. raw_bboxes.sort(key = lambda LURD: (LURD[1], LURD[0]))
  424. raw_bboxes = [LURD for LURD in raw_bboxes if (abs(LURD[0] - L1) < textSize_withMaxFreq * 6 or L1 < LURD[0])] # footnote的bbox,应该都是左端对齐的
  425. if len(raw_bboxes) == 0:
  426. return []
  427. #------------------ full column和sub column混合,肯定也不行 ------------------#
  428. LL, UU, RR, DD = raw_bboxes[0]
  429. for L, U, R, D in raw_bboxes:
  430. LL, UU, RR, DD = min(LL, L), min(UU, U), max(RR, R), max(DD, D)
  431. for L, U, R, D in raw_bboxes:
  432. if (RR - LL) > pageR*0.8 and (R - L) > pageR * 0.15 and (RR - LL) / (R - L) > 2:
  433. return []
  434. if abs(LL - L) > textSize_withMaxFreq * 3:
  435. return []
  436. #-------------------- 太高了的,full column的框。不行 ----------------------#
  437. if UU < 650/800 * pageD and (RR - LL) > 0.5 * pageR:
  438. return []
  439. #-------------- 第一段字数很少。后面的段字数很多,也不行 ----------------#
  440. if len(raw_bboxes) > 1:
  441. bbox_square = []
  442. for L, U, R, D in raw_bboxes:
  443. cur_s = abs(R - L) * abs(D - U)
  444. bbox_square.append(cur_s)
  445. s0 = bbox_square[0]
  446. s1n = sum(bbox_square[1: ]) / len(bbox_square[1: ])
  447. if s1n / s0 > 10 or max(bbox_square) / s0 > 15:
  448. return []
  449. raw_bboxes += [(LL, UU, RR, DD)]
  450. return raw_bboxes
  451. # print(footnoteLines)
  452. footnoteBboxes = []
  453. for L, U, R, D in footnoteLines:
  454. cur = get_footnoteBbox(L, U, R, D)
  455. if len(cur) > 0:
  456. footnoteBboxes.append((L, U, R, D))
  457. footnoteBboxes += cur
  458. footnoteBboxes = list(set(footnoteBboxes))
  459. return footnoteBboxes
  460. def __bbox_in(box1, box2):
  461. """
  462. box1是否在box2中
  463. """
  464. L1, U1, R1, D1 = box1
  465. L2, U2, R2, D2 = box2
  466. if int(L2) <= int(L1) and int(U2) <= int(U1) and int(R1) <= int(R2) and int(D1) <= int(D2):
  467. return True
  468. return False
  469. def remove_footnote_text(raw_text_block, footnote_bboxes):
  470. """
  471. :param raw_text_block: str类型,是当前页的文本内容
  472. :param footnoteBboxes: list类型,是当前页的脚注bbox
  473. """
  474. footnote_text_blocks = []
  475. for block in raw_text_block:
  476. text_bbox = block['bbox']
  477. # TODO 更严谨点在line级别做
  478. if any([_is_in_or_part_overlap(text_bbox, footnote_bbox) for footnote_bbox in footnote_bboxes]):
  479. #if any([text_bbox[3]>=footnote_bbox[1] for footnote_bbox in footnote_bboxes]):
  480. block['tag'] = 'footnote'
  481. footnote_text_blocks.append(block)
  482. #raw_text_block.remove(block)
  483. # 移除,不能再内部移除,否则会出错
  484. for block in footnote_text_blocks:
  485. raw_text_block.remove(block)
  486. return raw_text_block, footnote_text_blocks
  487. def remove_footnote_image(image_blocks, footnote_bboxes):
  488. """
  489. :param image_bboxes: list类型,是当前页的图片bbox(结构体)
  490. :param footnoteBboxes: list类型,是当前页的脚注bbox
  491. """
  492. footnote_imgs_blocks = []
  493. for image_block in image_blocks:
  494. if any([__bbox_in(image_block['bbox'], footnote_bbox) for footnote_bbox in footnote_bboxes]):
  495. footnote_imgs_blocks.append(image_block)
  496. for footnote_imgs_block in footnote_imgs_blocks:
  497. image_blocks.remove(footnote_imgs_block)
  498. return image_blocks, footnote_imgs_blocks
  499. def remove_headder_footer_one_page(text_raw_blocks, image_bboxes, table_bboxes, header_bboxs, footer_bboxs, page_no_bboxs, page_w, page_h):
  500. """
  501. 删除页眉页脚,页码
  502. 从line级别进行删除,删除之后观察这个text-block是否是空的,如果是空的,则移动到remove_list中
  503. """
  504. header = []
  505. footer = []
  506. if len(header)==0:
  507. model_header = header_bboxs
  508. if model_header:
  509. x0 = min([x for x,_,_,_ in model_header])
  510. y0 = min([y for _,y,_,_ in model_header])
  511. x1 = max([x1 for _,_,x1,_ in model_header])
  512. y1 = max([y1 for _,_,_,y1 in model_header])
  513. header = [x0, y0, x1, y1]
  514. if len(footer)==0:
  515. model_footer = footer_bboxs
  516. if model_footer:
  517. x0 = min([x for x,_,_,_ in model_footer])
  518. y0 = min([y for _,y,_,_ in model_footer])
  519. x1 = max([x1 for _,_,x1,_ in model_footer])
  520. y1 = max([y1 for _,_,_,y1 in model_footer])
  521. footer = [x0, y0, x1, y1]
  522. header_y0 = 0 if len(header) == 0 else header[3]
  523. footer_y0 = page_h if len(footer) == 0 else footer[1]
  524. if page_no_bboxs:
  525. top_part = [b for b in page_no_bboxs if b[3] < page_h/2]
  526. btn_part = [b for b in page_no_bboxs if b[1] > page_h/2]
  527. top_max_y0 = max([b[1] for b in top_part]) if top_part else 0
  528. btn_min_y1 = min([b[3] for b in btn_part]) if btn_part else page_h
  529. header_y0 = max(header_y0, top_max_y0)
  530. footer_y0 = min(footer_y0, btn_min_y1)
  531. content_boundry = [0, header_y0, page_w, footer_y0]
  532. header = [0,0, page_w, header_y0]
  533. footer = [0, footer_y0, page_w, page_h]
  534. """以上计算出来了页眉页脚的边界,下面开始进行删除"""
  535. text_block_to_remove = []
  536. # 首先检查每个textblock
  537. for blk in text_raw_blocks:
  538. if len(blk['lines']) > 0:
  539. for line in blk['lines']:
  540. line_del = []
  541. for span in line['spans']:
  542. span_del = []
  543. if span['bbox'][3] < header_y0:
  544. span_del.append(span)
  545. elif _is_in_or_part_overlap(span['bbox'], header) or _is_in_or_part_overlap(span['bbox'], footer):
  546. span_del.append(span)
  547. for span in span_del:
  548. line['spans'].remove(span)
  549. if not line['spans']:
  550. line_del.append(line)
  551. for line in line_del:
  552. blk['lines'].remove(line)
  553. else:
  554. # if not blk['lines']:
  555. blk['tag'] = 'in-foot-header-area'
  556. text_block_to_remove.append(blk)
  557. """有的时候由于pageNo太小了,总是会有一点和content_boundry重叠一点,被放入正文,因此对于pageNo,进行span粒度的删除"""
  558. page_no_block_2_remove = []
  559. if page_no_bboxs:
  560. for pagenobox in page_no_bboxs:
  561. for block in text_raw_blocks:
  562. if _is_in_or_part_overlap(pagenobox, block['bbox']): # 在span级别删除页码
  563. for line in block['lines']:
  564. for span in line['spans']:
  565. if _is_in_or_part_overlap(pagenobox, span['bbox']):
  566. #span['text'] = ''
  567. span['tag'] = "page-no"
  568. # 检查这个block是否只有这一个span,如果是,那么就把这个block也删除
  569. if len(line['spans']) == 1 and len(block['lines'])==1:
  570. page_no_block_2_remove.append(block)
  571. else:
  572. # 测试最后一个是不是页码:规则是,最后一个block仅有1个line,一个span,且text是数字,空格,符号组成,不含字母,并且包含数字
  573. if len(text_raw_blocks) > 0:
  574. text_raw_blocks.sort(key=lambda x: x['bbox'][1], reverse=True)
  575. last_block = text_raw_blocks[0]
  576. if len(last_block['lines']) == 1:
  577. last_line = last_block['lines'][0]
  578. if len(last_line['spans']) == 1:
  579. last_span = last_line['spans'][0]
  580. if last_span['text'].strip() and not re.search('[a-zA-Z]', last_span['text']) and re.search('[0-9]', last_span['text']):
  581. last_span['tag'] = "page-no"
  582. page_no_block_2_remove.append(last_block)
  583. for b in page_no_block_2_remove:
  584. text_block_to_remove.append(b)
  585. for blk in text_block_to_remove:
  586. if blk in text_raw_blocks:
  587. text_raw_blocks.remove(blk)
  588. text_block_remain = text_raw_blocks
  589. image_bbox_to_remove = [bbox for bbox in image_bboxes if not _is_in_or_part_overlap(bbox, content_boundry)]
  590. image_bbox_remain = [bbox for bbox in image_bboxes if _is_in_or_part_overlap(bbox, content_boundry)]
  591. table_bbox_to_remove = [bbox for bbox in table_bboxes if not _is_in_or_part_overlap(bbox, content_boundry)]
  592. table_bbox_remain = [bbox for bbox in table_bboxes if _is_in_or_part_overlap(bbox, content_boundry)]
  593. return image_bbox_remain, table_bbox_remain, text_block_remain, text_block_to_remove, image_bbox_to_remove, table_bbox_to_remove