para_split_v3.py 17 KB

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