para_split_v3.py 17 KB

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