para_split_v3.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import copy
  2. from loguru import logger
  3. from magic_pdf.libs.Constants import LINES_DELETED, CROSS_PAGE
  4. from magic_pdf.libs.ocr_content_type import BlockType, ContentType
  5. LINE_STOP_FLAG = ('.', '!', '?', '。', '!', '?', ')', ')', '"', '”', ':', ':', ';', ';')
  6. LIST_END_FLAG = ('.', '。', ';', ';')
  7. class ListLineTag:
  8. IS_LIST_START_LINE = "is_list_start_line"
  9. IS_LIST_END_LINE = "is_list_end_line"
  10. def __process_blocks(blocks):
  11. # 对所有block预处理
  12. # 1.通过title和interline_equation将block分组
  13. # 2.bbox边界根据line信息重置
  14. result = []
  15. current_group = []
  16. for i in range(len(blocks)):
  17. current_block = blocks[i]
  18. # 如果当前块是 text 类型
  19. if current_block['type'] == 'text':
  20. current_block["bbox_fs"] = copy.deepcopy(current_block["bbox"])
  21. if 'lines' in current_block and len(current_block["lines"]) > 0:
  22. current_block['bbox_fs'] = [min([line['bbox'][0] for line in current_block['lines']]),
  23. min([line['bbox'][1] for line in current_block['lines']]),
  24. max([line['bbox'][2] for line in current_block['lines']]),
  25. max([line['bbox'][3] for line in current_block['lines']])]
  26. current_group.append(current_block)
  27. # 检查下一个块是否存在
  28. if i + 1 < len(blocks):
  29. next_block = blocks[i + 1]
  30. # 如果下一个块不是 text 类型且是 title 或 interline_equation 类型
  31. if next_block['type'] in ['title', 'interline_equation']:
  32. result.append(current_group)
  33. current_group = []
  34. # 处理最后一个 group
  35. if current_group:
  36. result.append(current_group)
  37. return result
  38. def __is_list_or_index_block(block):
  39. # 一个block如果是list block 应该同时满足以下特征
  40. # 1.block内有多个line 2.block 内有多个line左侧顶格写 3.block内有多个line 右侧不顶格(狗牙状)
  41. # 1.block内有多个line 2.block 内有多个line左侧顶格写 3.多个line以endflag结尾
  42. # 1.block内有多个line 2.block 内有多个line左侧顶格写 3.block内有多个line 左侧不顶格
  43. # index block 是一种特殊的list block
  44. # 一个block如果是index block 应该同时满足以下特征
  45. # 1.block内有多个line 2.block 内有多个line两侧均顶格写 3.line的开头或者结尾均为数字
  46. if len(block['lines']) >= 2:
  47. first_line = block['lines'][0]
  48. line_height = first_line['bbox'][3] - first_line['bbox'][1]
  49. block_weight = block['bbox_fs'][2] - block['bbox_fs'][0]
  50. block_height = block['bbox_fs'][3] - block['bbox_fs'][1]
  51. page_weight, page_height = block['page_size']
  52. left_close_num = 0
  53. left_not_close_num = 0
  54. right_not_close_num = 0
  55. right_close_num = 0
  56. lines_text_list = []
  57. center_close_num = 0
  58. external_sides_not_close_num = 0
  59. multiple_para_flag = False
  60. last_line = block['lines'][-1]
  61. if page_weight == 0:
  62. block_weight_radio = 0
  63. else:
  64. block_weight_radio = block_weight / page_weight
  65. # logger.info(f"block_weight_radio: {block_weight_radio}")
  66. # 如果首行左边不顶格而右边顶格,末行左边顶格而右边不顶格 (第一行可能可以右边不顶格)
  67. if (first_line['bbox'][0] - block['bbox_fs'][0] > line_height / 2 and
  68. abs(last_line['bbox'][0] - block['bbox_fs'][0]) < line_height / 2 and
  69. block['bbox_fs'][2] - last_line['bbox'][2] > line_height
  70. ):
  71. multiple_para_flag = True
  72. for line in block['lines']:
  73. line_mid_x = (line['bbox'][0] + line['bbox'][2]) / 2
  74. block_mid_x = (block['bbox_fs'][0] + block['bbox_fs'][2]) / 2
  75. if (
  76. line['bbox'][0] - block['bbox_fs'][0] > 0.8 * line_height and
  77. block['bbox_fs'][2] - line['bbox'][2] > 0.8 * line_height
  78. ):
  79. external_sides_not_close_num += 1
  80. if abs(line_mid_x - block_mid_x) < line_height / 2:
  81. center_close_num += 1
  82. line_text = ""
  83. for span in line['spans']:
  84. span_type = span['type']
  85. if span_type == ContentType.Text:
  86. line_text += span['content'].strip()
  87. # 添加所有文本,包括空行,保持与block['lines']长度一致
  88. lines_text_list.append(line_text)
  89. # 计算line左侧顶格数量是否大于2,是否顶格用abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height/2 来判断
  90. if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
  91. left_close_num += 1
  92. elif line['bbox'][0] - block['bbox_fs'][0] > line_height:
  93. left_not_close_num += 1
  94. # 计算右侧是否顶格
  95. if abs(block['bbox_fs'][2] - line['bbox'][2]) < line_height:
  96. right_close_num += 1
  97. else:
  98. # 右侧不顶格情况下是否有一段距离,拍脑袋用0.3block宽度做阈值
  99. # 0.26
  100. closed_area = 0.35 * block_weight
  101. if block['bbox_fs'][2] - line['bbox'][2] > closed_area:
  102. right_not_close_num += 1
  103. # 判断lines_text_list中的元素是否有超过80%都以LIST_END_FLAG结尾
  104. line_end_flag = False
  105. # 判断lines_text_list中的元素是否有超过80%都以数字开头或都以数字结尾
  106. line_num_flag = False
  107. num_start_count = 0
  108. num_end_count = 0
  109. flag_end_count = 0
  110. if len(lines_text_list) > 0:
  111. for line_text in lines_text_list:
  112. if len(line_text) > 0:
  113. if line_text[-1] in LIST_END_FLAG:
  114. flag_end_count += 1
  115. if line_text[0].isdigit():
  116. num_start_count += 1
  117. if line_text[-1].isdigit():
  118. num_end_count += 1
  119. if num_start_count / len(lines_text_list) >= 0.8 or num_end_count / len(lines_text_list) >= 0.8:
  120. line_num_flag = True
  121. if flag_end_count / len(lines_text_list) >= 0.8:
  122. line_end_flag = True
  123. # 有的目录右侧不贴边, 目前认为左边或者右边有一边全贴边,且符合数字规则极为index
  124. if ((left_close_num / len(block['lines']) >= 0.8 or right_close_num / len(block['lines']) >= 0.8)
  125. and line_num_flag
  126. ):
  127. for line in block['lines']:
  128. line[ListLineTag.IS_LIST_START_LINE] = True
  129. return BlockType.Index
  130. # 全部line都居中的特殊list识别,每行都需要换行,特征是多行,且大多数行都前后not_close,每line中点x坐标接近
  131. # 补充条件block的长宽比有要求
  132. elif (
  133. external_sides_not_close_num >= 2 and
  134. center_close_num == len(block['lines']) and
  135. external_sides_not_close_num / len(block['lines']) >= 0.5 and
  136. block_height / block_weight > 0.4
  137. ):
  138. for line in block['lines']:
  139. line[ListLineTag.IS_LIST_START_LINE] = True
  140. return BlockType.List
  141. elif (
  142. left_close_num >= 2
  143. and (right_not_close_num >= 2 or line_end_flag or left_not_close_num >= 2)
  144. and not multiple_para_flag
  145. # and block_weight_radio > 0.27
  146. ):
  147. # 处理一种特殊的没有缩进的list,所有行都贴左边,通过右边的空隙判断是否是item尾
  148. if left_close_num / len(block['lines']) > 0.8:
  149. # 这种是每个item只有一行,且左边都贴边的短item list
  150. if flag_end_count == 0 and right_close_num / len(block['lines']) < 0.5:
  151. for line in block['lines']:
  152. if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
  153. line[ListLineTag.IS_LIST_START_LINE] = True
  154. # 这种是大部分line item 都有结束标识符的情况,按结束标识符区分不同item
  155. elif line_end_flag:
  156. for i, line in enumerate(block['lines']):
  157. if len(lines_text_list[i]) > 0 and lines_text_list[i][-1] in LIST_END_FLAG:
  158. line[ListLineTag.IS_LIST_END_LINE] = True
  159. if i + 1 < len(block['lines']):
  160. block['lines'][i + 1][ListLineTag.IS_LIST_START_LINE] = True
  161. # line item基本没有结束标识符,而且也没有缩进,按右侧空隙判断哪些是item end
  162. else:
  163. line_start_flag = False
  164. for i, line in enumerate(block['lines']):
  165. if line_start_flag:
  166. line[ListLineTag.IS_LIST_START_LINE] = True
  167. line_start_flag = False
  168. if abs(block['bbox_fs'][2] - line['bbox'][2]) > 0.1 * block_weight:
  169. line[ListLineTag.IS_LIST_END_LINE] = True
  170. line_start_flag = True
  171. # 一种有缩进的特殊有序list,start line 左侧不贴边且以数字开头,end line 以 IS_LIST_END_FLAG 结尾且数量和start line 一致
  172. elif num_start_count >= 2 and num_start_count == flag_end_count:
  173. for i, line in enumerate(block['lines']):
  174. if len(lines_text_list[i]) > 0:
  175. if lines_text_list[i][0].isdigit():
  176. line[ListLineTag.IS_LIST_START_LINE] = True
  177. if lines_text_list[i][-1] in LIST_END_FLAG:
  178. line[ListLineTag.IS_LIST_END_LINE] = True
  179. else:
  180. # 正常有缩进的list处理
  181. for line in block['lines']:
  182. if abs(block['bbox_fs'][0] - line['bbox'][0]) < line_height / 2:
  183. line[ListLineTag.IS_LIST_START_LINE] = True
  184. if abs(block['bbox_fs'][2] - line['bbox'][2]) > line_height:
  185. line[ListLineTag.IS_LIST_END_LINE] = True
  186. return BlockType.List
  187. else:
  188. return BlockType.Text
  189. else:
  190. return BlockType.Text
  191. def __merge_2_text_blocks(block1, block2):
  192. if len(block1['lines']) > 0:
  193. first_line = block1['lines'][0]
  194. line_height = first_line['bbox'][3] - first_line['bbox'][1]
  195. block1_weight = block1['bbox'][2] - block1['bbox'][0]
  196. block2_weight = block2['bbox'][2] - block2['bbox'][0]
  197. min_block_weight = min(block1_weight, block2_weight)
  198. if abs(block1['bbox_fs'][0] - first_line['bbox'][0]) < line_height / 2:
  199. last_line = block2['lines'][-1]
  200. if len(last_line['spans']) > 0:
  201. last_span = last_line['spans'][-1]
  202. line_height = last_line['bbox'][3] - last_line['bbox'][1]
  203. if len(first_line['spans']) > 0:
  204. first_span = first_line['spans'][0]
  205. if len(first_span['content']) > 0:
  206. span_start_with_num = first_span['content'][0].isdigit()
  207. if (abs(block2['bbox_fs'][2] - last_line['bbox'][2]) < line_height
  208. and not last_span['content'].endswith(LINE_STOP_FLAG)
  209. # 两个block宽度差距超过2倍也不合并
  210. and abs(block1_weight - block2_weight) < min_block_weight
  211. and not span_start_with_num
  212. ):
  213. if block1['page_num'] != block2['page_num']:
  214. for line in block1['lines']:
  215. for span in line['spans']:
  216. span[CROSS_PAGE] = True
  217. block2['lines'].extend(block1['lines'])
  218. block1['lines'] = []
  219. block1[LINES_DELETED] = True
  220. return block1, block2
  221. def __merge_2_list_blocks(block1, block2):
  222. if block1['page_num'] != block2['page_num']:
  223. for line in block1['lines']:
  224. for span in line['spans']:
  225. span[CROSS_PAGE] = True
  226. block2['lines'].extend(block1['lines'])
  227. block1['lines'] = []
  228. block1[LINES_DELETED] = True
  229. return block1, block2
  230. def __is_list_group(text_blocks_group):
  231. # list group的特征是一个group内的所有block都满足以下条件
  232. # 1.每个block都不超过3行 2. 每个block 的左边界都比较接近(逻辑简单点先不加这个规则)
  233. for block in text_blocks_group:
  234. if len(block['lines']) > 3:
  235. return False
  236. return True
  237. def __para_merge_page(blocks):
  238. page_text_blocks_groups = __process_blocks(blocks)
  239. for text_blocks_group in page_text_blocks_groups:
  240. if len(text_blocks_group) > 0:
  241. # 需要先在合并前对所有block判断是否为list or index block
  242. for block in text_blocks_group:
  243. block_type = __is_list_or_index_block(block)
  244. block['type'] = block_type
  245. # logger.info(f"{block['type']}:{block}")
  246. if len(text_blocks_group) > 1:
  247. # 在合并前判断这个group 是否是一个 list group
  248. is_list_group = __is_list_group(text_blocks_group)
  249. # 倒序遍历
  250. for i in range(len(text_blocks_group) - 1, -1, -1):
  251. current_block = text_blocks_group[i]
  252. # 检查是否有前一个块
  253. if i - 1 >= 0:
  254. prev_block = text_blocks_group[i - 1]
  255. if current_block['type'] == 'text' and prev_block['type'] == 'text' and not is_list_group:
  256. __merge_2_text_blocks(current_block, prev_block)
  257. elif (
  258. (current_block['type'] == BlockType.List and prev_block['type'] == BlockType.List) or
  259. (current_block['type'] == BlockType.Index and prev_block['type'] == BlockType.Index)
  260. ):
  261. __merge_2_list_blocks(current_block, prev_block)
  262. else:
  263. continue
  264. def para_split(pdf_info_dict, debug_mode=False):
  265. all_blocks = []
  266. for page_num, page in pdf_info_dict.items():
  267. blocks = copy.deepcopy(page['preproc_blocks'])
  268. for block in blocks:
  269. block['page_num'] = page_num
  270. block['page_size'] = page['page_size']
  271. all_blocks.extend(blocks)
  272. __para_merge_page(all_blocks)
  273. for page_num, page in pdf_info_dict.items():
  274. page['para_blocks'] = []
  275. for block in all_blocks:
  276. if block['page_num'] == page_num:
  277. page['para_blocks'].append(block)
  278. if __name__ == '__main__':
  279. input_blocks = []
  280. # 调用函数
  281. groups = __process_blocks(input_blocks)
  282. for group_index, group in enumerate(groups):
  283. print(f"Group {group_index}: {group}")