para_split_v2.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. import copy
  2. import re
  3. import numpy as np
  4. from loguru import logger
  5. from sklearn.cluster import DBSCAN
  6. from magic_pdf.config.constants import * # noqa: F403
  7. from magic_pdf.config.ocr_content_type import BlockType, ContentType
  8. from magic_pdf.libs.boxbase import \
  9. _is_in_or_part_overlap_with_area_ratio as is_in_layout
  10. LINE_STOP_FLAG = ['.', '!', '?', '。', '!', '?', ':', ':', ')', ')', ';']
  11. INLINE_EQUATION = ContentType.InlineEquation
  12. INTERLINE_EQUATION = ContentType.InterlineEquation
  13. TEXT = ContentType.Text
  14. debug_able = False
  15. def __get_span_text(span):
  16. c = span.get('content', '')
  17. if len(c) == 0:
  18. c = span.get('image_path', '')
  19. return c
  20. def __detect_list_lines(lines, new_layout_bboxes, lang):
  21. global debug_able
  22. """
  23. 探测是否包含了列表,并且把列表的行分开.
  24. 这样的段落特点是,顶格字母大写/数字,紧跟着几行缩进的。缩进的行首字母含小写的。
  25. """
  26. def find_repeating_patterns2(lst):
  27. indices = []
  28. ones_indices = []
  29. i = 0
  30. while i < len(lst): # Loop through the entire list
  31. if (
  32. lst[i] == 1
  33. ): # If we encounter a '1', we might be at the start of a pattern
  34. start = i
  35. ones_in_this_interval = [i]
  36. i += 1
  37. # Traverse elements that are 1, 2 or 3, until we encounter something else
  38. while i < len(lst) and lst[i] in [1, 2, 3]:
  39. if lst[i] == 1:
  40. ones_in_this_interval.append(i)
  41. i += 1
  42. if len(ones_in_this_interval) > 1 or (
  43. start < len(lst) - 1
  44. and ones_in_this_interval
  45. and lst[start + 1] in [2, 3]
  46. ):
  47. indices.append((start, i - 1))
  48. ones_indices.append(ones_in_this_interval)
  49. else:
  50. i += 1
  51. return indices, ones_indices
  52. def find_repeating_patterns(lst):
  53. indices = []
  54. ones_indices = []
  55. i = 0
  56. while i < len(lst) - 1: # 确保余下元素至少有2个
  57. if lst[i] == 1 and lst[i + 1] in [2, 3]: # 额外检查以防止连续出现的1
  58. start = i
  59. ones_in_this_interval = [i]
  60. i += 1
  61. while i < len(lst) and lst[i] in [2, 3]:
  62. i += 1
  63. # 验证下一个序列是否符合条件
  64. if (
  65. i < len(lst) - 1
  66. and lst[i] == 1
  67. and lst[i + 1] in [2, 3]
  68. and lst[i - 1] in [2, 3]
  69. ):
  70. while i < len(lst) and lst[i] in [1, 2, 3]:
  71. if lst[i] == 1:
  72. ones_in_this_interval.append(i)
  73. i += 1
  74. indices.append((start, i - 1))
  75. ones_indices.append(ones_in_this_interval)
  76. else:
  77. i += 1
  78. else:
  79. i += 1
  80. return indices, ones_indices
  81. """===================="""
  82. def split_indices(slen, index_array):
  83. result = []
  84. last_end = 0
  85. for start, end in sorted(index_array):
  86. if start > last_end:
  87. # 前一个区间结束到下一个区间开始之间的部分标记为"text"
  88. result.append(('text', last_end, start - 1))
  89. # 区间内标记为"list"
  90. result.append(('list', start, end))
  91. last_end = end + 1
  92. if last_end < slen:
  93. # 如果最后一个区间结束后还有剩余的字符串,将其标记为"text"
  94. result.append(('text', last_end, slen - 1))
  95. return result
  96. """===================="""
  97. if lang != 'en':
  98. return lines, None
  99. total_lines = len(lines)
  100. line_fea_encode = []
  101. """
  102. 对每一行进行特征编码,编码规则如下:
  103. 1. 如果行顶格,且大写字母开头或者数字开头,编码为1
  104. 2. 如果顶格,其他非大写开头编码为4
  105. 3. 如果非顶格,首字符大写,编码为2
  106. 4. 如果非顶格,首字符非大写编码为3
  107. """
  108. if len(lines) > 0:
  109. x_map_tag_dict, min_x_tag = cluster_line_x(lines)
  110. for l in lines: # noqa: E741
  111. span_text = __get_span_text(l['spans'][0])
  112. if not span_text:
  113. line_fea_encode.append(0)
  114. continue
  115. first_char = span_text[0]
  116. layout = __find_layout_bbox_by_line(l['bbox'], new_layout_bboxes)
  117. if not layout:
  118. line_fea_encode.append(0)
  119. else:
  120. #
  121. if x_map_tag_dict[round(l['bbox'][0])] == min_x_tag:
  122. # if first_char.isupper() or first_char.isdigit() or not first_char.isalnum():
  123. if not first_char.isalnum() or if_match_reference_list(span_text):
  124. line_fea_encode.append(1)
  125. else:
  126. line_fea_encode.append(4)
  127. else:
  128. if first_char.isupper():
  129. line_fea_encode.append(2)
  130. else:
  131. line_fea_encode.append(3)
  132. # 然后根据编码进行分段, 选出来 1,2,3连续出现至少2次的行,认为是列表。
  133. list_indice, list_start_idx = find_repeating_patterns2(line_fea_encode)
  134. if len(list_indice) > 0:
  135. if debug_able:
  136. logger.info(f'发现了列表,列表行数:{list_indice}, {list_start_idx}')
  137. # TODO check一下这个特列表里缩进的行左侧是不是对齐的。
  138. for start, end in list_indice:
  139. for i in range(start, end + 1):
  140. if i > 0:
  141. if line_fea_encode[i] == 4:
  142. if debug_able:
  143. logger.info(f'列表行的第{i}行不是顶格的')
  144. break
  145. else:
  146. if debug_able:
  147. logger.info(f'列表行的第{start}到第{end}行是列表')
  148. return split_indices(total_lines, list_indice), list_start_idx
  149. def cluster_line_x(lines: list) -> dict:
  150. """对一个block内所有lines的bbox的x0聚类."""
  151. min_distance = 5
  152. min_sample = 1
  153. x0_lst = np.array([[round(line['bbox'][0]), 0] for line in lines])
  154. x0_clusters = DBSCAN(eps=min_distance, min_samples=min_sample).fit(x0_lst)
  155. x0_uniq_label = np.unique(x0_clusters.labels_)
  156. # x1_lst = np.array([[line['bbox'][2], 0] for line in lines])
  157. x0_2_new_val = {} # 存储旧值对应的新值映射
  158. min_x0 = round(lines[0]['bbox'][0])
  159. for label in x0_uniq_label:
  160. if label == -1:
  161. continue
  162. x0_index_of_label = np.where(x0_clusters.labels_ == label)
  163. x0_raw_val = x0_lst[x0_index_of_label][:, 0]
  164. x0_new_val = np.min(x0_lst[x0_index_of_label][:, 0])
  165. x0_2_new_val.update(
  166. {round(raw_val): round(x0_new_val) for raw_val in x0_raw_val}
  167. )
  168. if x0_new_val < min_x0:
  169. min_x0 = x0_new_val
  170. return x0_2_new_val, min_x0
  171. def if_match_reference_list(text: str) -> bool:
  172. pattern = re.compile(r'^\d+\..*')
  173. if pattern.match(text):
  174. return True
  175. else:
  176. return False
  177. def __valign_lines(blocks, layout_bboxes):
  178. """在一个layoutbox内对齐行的左侧和右侧。 扫描行的左侧和右侧,如果x0,
  179. x1差距不超过一个阈值,就强行对齐到所处layout的左右两侧(和layout有一段距离)。
  180. 3是个经验值,TODO,计算得来,可以设置为1.5个正文字符。"""
  181. min_distance = 3
  182. min_sample = 2
  183. new_layout_bboxes = []
  184. # add bbox_fs for para split calculation
  185. for block in blocks:
  186. block['bbox_fs'] = copy.deepcopy(block['bbox'])
  187. for layout_box in layout_bboxes:
  188. blocks_in_layoutbox = [
  189. b
  190. for b in blocks
  191. if b['type'] == BlockType.Text
  192. and is_in_layout(b['bbox'], layout_box['layout_bbox'])
  193. ]
  194. if len(blocks_in_layoutbox) == 0 or len(blocks_in_layoutbox[0]['lines']) == 0:
  195. new_layout_bboxes.append(layout_box['layout_bbox'])
  196. continue
  197. x0_lst = np.array(
  198. [
  199. [line['bbox'][0], 0]
  200. for block in blocks_in_layoutbox
  201. for line in block['lines']
  202. ]
  203. )
  204. x1_lst = np.array(
  205. [
  206. [line['bbox'][2], 0]
  207. for block in blocks_in_layoutbox
  208. for line in block['lines']
  209. ]
  210. )
  211. x0_clusters = DBSCAN(eps=min_distance, min_samples=min_sample).fit(x0_lst)
  212. x1_clusters = DBSCAN(eps=min_distance, min_samples=min_sample).fit(x1_lst)
  213. x0_uniq_label = np.unique(x0_clusters.labels_)
  214. x1_uniq_label = np.unique(x1_clusters.labels_)
  215. x0_2_new_val = {} # 存储旧值对应的新值映射
  216. x1_2_new_val = {}
  217. for label in x0_uniq_label:
  218. if label == -1:
  219. continue
  220. x0_index_of_label = np.where(x0_clusters.labels_ == label)
  221. x0_raw_val = x0_lst[x0_index_of_label][:, 0]
  222. x0_new_val = np.min(x0_lst[x0_index_of_label][:, 0])
  223. x0_2_new_val.update({idx: x0_new_val for idx in x0_raw_val})
  224. for label in x1_uniq_label:
  225. if label == -1:
  226. continue
  227. x1_index_of_label = np.where(x1_clusters.labels_ == label)
  228. x1_raw_val = x1_lst[x1_index_of_label][:, 0]
  229. x1_new_val = np.max(x1_lst[x1_index_of_label][:, 0])
  230. x1_2_new_val.update({idx: x1_new_val for idx in x1_raw_val})
  231. for block in blocks_in_layoutbox:
  232. for line in block['lines']:
  233. x0, x1 = line['bbox'][0], line['bbox'][2]
  234. if x0 in x0_2_new_val:
  235. line['bbox'][0] = int(x0_2_new_val[x0])
  236. if x1 in x1_2_new_val:
  237. line['bbox'][2] = int(x1_2_new_val[x1])
  238. # 其余对不齐的保持不动
  239. # 由于修改了block里的line长度,现在需要重新计算block的bbox
  240. for block in blocks_in_layoutbox:
  241. if len(block['lines']) > 0:
  242. block['bbox_fs'] = [
  243. min([line['bbox'][0] for line in block['lines']]),
  244. min([line['bbox'][1] for line in block['lines']]),
  245. max([line['bbox'][2] for line in block['lines']]),
  246. max([line['bbox'][3] for line in block['lines']]),
  247. ]
  248. """新计算layout的bbox,因为block的bbox变了。"""
  249. layout_x0 = min([block['bbox_fs'][0] for block in blocks_in_layoutbox])
  250. layout_y0 = min([block['bbox_fs'][1] for block in blocks_in_layoutbox])
  251. layout_x1 = max([block['bbox_fs'][2] for block in blocks_in_layoutbox])
  252. layout_y1 = max([block['bbox_fs'][3] for block in blocks_in_layoutbox])
  253. new_layout_bboxes.append([layout_x0, layout_y0, layout_x1, layout_y1])
  254. return new_layout_bboxes
  255. def __align_text_in_layout(blocks, layout_bboxes):
  256. """由于ocr出来的line,有时候会在前后有一段空白,这个时候需要对文本进行对齐,超出的部分被layout左右侧截断。"""
  257. for layout in layout_bboxes:
  258. lb = layout['layout_bbox']
  259. blocks_in_layoutbox = [
  260. block
  261. for block in blocks
  262. if block['type'] == BlockType.Text and is_in_layout(block['bbox'], lb)
  263. ]
  264. if len(blocks_in_layoutbox) == 0:
  265. continue
  266. for block in blocks_in_layoutbox:
  267. for line in block.get('lines', []):
  268. x0, x1 = line['bbox'][0], line['bbox'][2]
  269. if x0 < lb[0]:
  270. line['bbox'][0] = lb[0]
  271. if x1 > lb[2]:
  272. line['bbox'][2] = lb[2]
  273. def __common_pre_proc(blocks, layout_bboxes):
  274. """不分语言的,对文本进行预处理."""
  275. # __add_line_period(blocks, layout_bboxes)
  276. __align_text_in_layout(blocks, layout_bboxes)
  277. aligned_layout_bboxes = __valign_lines(blocks, layout_bboxes)
  278. return aligned_layout_bboxes
  279. def __pre_proc_zh_blocks(blocks, layout_bboxes):
  280. """对中文文本进行分段预处理."""
  281. pass
  282. def __pre_proc_en_blocks(blocks, layout_bboxes):
  283. """对英文文本进行分段预处理."""
  284. pass
  285. def __group_line_by_layout(blocks, layout_bboxes):
  286. """每个layout内的行进行聚合."""
  287. # 因为只是一个block一行目前, 一个block就是一个段落
  288. blocks_group = []
  289. for lyout in layout_bboxes:
  290. blocks_in_layout = [
  291. block
  292. for block in blocks
  293. if is_in_layout(block.get('bbox_fs', None), lyout['layout_bbox'])
  294. ]
  295. blocks_group.append(blocks_in_layout)
  296. return blocks_group
  297. def __split_para_in_layoutbox(blocks_group, new_layout_bbox, lang='en'):
  298. """
  299. lines_group 进行行分段——layout内部进行分段。lines_group内每个元素是一个Layoutbox内的所有行。
  300. 1. 先计算每个group的左右边界。
  301. 2. 然后根据行末尾特征进行分段。
  302. 末尾特征:以句号等结束符结尾。并且距离右侧边界有一定距离。
  303. 且下一行开头不留空白。
  304. """
  305. list_info = [] # 这个layout最后是不是列表,记录每一个layout里是不是列表开头,列表结尾
  306. for blocks in blocks_group:
  307. is_start_list = None
  308. is_end_list = None
  309. if len(blocks) == 0:
  310. list_info.append([False, False])
  311. continue
  312. if blocks[0]['type'] != BlockType.Text and blocks[-1]['type'] != BlockType.Text:
  313. list_info.append([False, False])
  314. continue
  315. if blocks[0]['type'] != BlockType.Text:
  316. is_start_list = False
  317. if blocks[-1]['type'] != BlockType.Text:
  318. is_end_list = False
  319. lines = [
  320. line
  321. for block in blocks
  322. if block['type'] == BlockType.Text
  323. for line in block['lines']
  324. ]
  325. total_lines = len(lines)
  326. if total_lines == 1 or total_lines == 0:
  327. list_info.append([False, False])
  328. continue
  329. """在进入到真正的分段之前,要对文字块从统计维度进行对齐方式的探测,
  330. 对齐方式分为以下:
  331. 1. 左对齐的文本块(特点是左侧顶格,或者左侧不顶格但是右侧顶格的行数大于非顶格的行数,顶格的首字母有大写也有小写)
  332. 1) 右侧对齐的行,单独成一段
  333. 2) 中间对齐的行,按照字体/行高聚合成一段
  334. 2. 左对齐的列表块(其特点是左侧顶格的行数小于等于非顶格的行数,非定格首字母会有小写,顶格90%是大写。并且左侧顶格行数大于1,大于1是为了这种模式连续出现才能称之为列表)
  335. 这样的文本块,顶格的为一个段落开头,紧随其后非顶格的行属于这个段落。
  336. """
  337. text_segments, list_start_line = __detect_list_lines(
  338. lines, new_layout_bbox, lang
  339. )
  340. """根据list_range,把lines分成几个部分
  341. """
  342. for list_start in list_start_line:
  343. if len(list_start) > 1:
  344. for i in range(0, len(list_start)):
  345. index = list_start[i] - 1
  346. if index >= 0:
  347. if 'content' in lines[index]['spans'][-1] and lines[index][
  348. 'spans'
  349. ][-1].get('type', '') not in [
  350. ContentType.InlineEquation,
  351. ContentType.InterlineEquation,
  352. ]:
  353. lines[index]['spans'][-1]['content'] += '\n\n'
  354. layout_list_info = [
  355. False,
  356. False,
  357. ] # 这个layout最后是不是列表,记录每一个layout里是不是列表开头,列表结尾
  358. for content_type, start, end in text_segments:
  359. if content_type == 'list':
  360. if start == 0 and is_start_list is None:
  361. layout_list_info[0] = True
  362. if end == total_lines - 1 and is_end_list is None:
  363. layout_list_info[1] = True
  364. list_info.append(layout_list_info)
  365. return list_info
  366. def __split_para_lines(lines: list, text_blocks: list) -> list:
  367. text_paras = []
  368. other_paras = []
  369. text_lines = []
  370. for line in lines:
  371. spans_types = [span['type'] for span in line]
  372. if ContentType.Table in spans_types:
  373. other_paras.append([line])
  374. continue
  375. if ContentType.Image in spans_types:
  376. other_paras.append([line])
  377. continue
  378. if ContentType.InterlineEquation in spans_types:
  379. other_paras.append([line])
  380. continue
  381. text_lines.append(line)
  382. for block in text_blocks:
  383. block_bbox = block['bbox']
  384. para = []
  385. for line in text_lines:
  386. bbox = line['bbox']
  387. if is_in_layout(bbox, block_bbox):
  388. para.append(line)
  389. if len(para) > 0:
  390. text_paras.append(para)
  391. paras = other_paras.extend(text_paras)
  392. paras_sorted = sorted(paras, key=lambda x: x[0]['bbox'][1])
  393. return paras_sorted
  394. def __connect_list_inter_layout(
  395. blocks_group, new_layout_bbox, layout_list_info, page_num, lang
  396. ):
  397. global debug_able
  398. """
  399. 如果上个layout的最后一个段落是列表,下一个layout的第一个段落也是列表,那么将他们连接起来。 TODO 因为没有区分列表和段落,所以这个方法暂时不实现。
  400. 根据layout_list_info判断是不是列表。,下个layout的第一个段如果不是列表,那么看他们是否有几行都有相同的缩进。
  401. """
  402. if len(blocks_group) == 0 or len(blocks_group) == 0: # 0的时候最后的return 会出错
  403. return blocks_group, [False, False]
  404. for i in range(1, len(blocks_group)):
  405. if len(blocks_group[i]) == 0 or len(blocks_group[i - 1]) == 0:
  406. continue
  407. pre_layout_list_info = layout_list_info[i - 1]
  408. next_layout_list_info = layout_list_info[i]
  409. pre_last_para = blocks_group[i - 1][-1].get('lines', [])
  410. next_paras = blocks_group[i]
  411. next_first_para = next_paras[0]
  412. if (
  413. pre_layout_list_info[1]
  414. and not next_layout_list_info[0]
  415. and next_first_para['type'] == BlockType.Text
  416. ): # 前一个是列表结尾,后一个是非列表开头,此时检测是否有相同的缩进
  417. if debug_able:
  418. logger.info(f'连接page {page_num} 内的list')
  419. # 向layout_paras[i] 寻找开头具有相同缩进的连续的行
  420. may_list_lines = []
  421. lines = next_first_para.get('lines', [])
  422. for line in lines:
  423. if (
  424. line['bbox'][0]
  425. > __find_layout_bbox_by_line(line['bbox'], new_layout_bbox)[0]
  426. ):
  427. may_list_lines.append(line)
  428. else:
  429. break
  430. # 如果这些行的缩进是相等的,那么连到上一个layout的最后一个段落上。
  431. if (
  432. len(may_list_lines) > 0
  433. and len(set([x['bbox'][0] for x in may_list_lines])) == 1
  434. ):
  435. pre_last_para.extend(may_list_lines)
  436. next_first_para['lines'] = next_first_para['lines'][
  437. len(may_list_lines) :
  438. ]
  439. return blocks_group, [
  440. layout_list_info[0][0],
  441. layout_list_info[-1][1],
  442. ] # 同时还返回了这个页面级别的开头、结尾是不是列表的信息
  443. def __connect_list_inter_page(
  444. pre_page_paras,
  445. next_page_paras,
  446. pre_page_layout_bbox,
  447. next_page_layout_bbox,
  448. pre_page_list_info,
  449. next_page_list_info,
  450. page_num,
  451. lang,
  452. ):
  453. """如果上个layout的最后一个段落是列表,下一个layout的第一个段落也是列表,那么将他们连接起来。 TODO
  454. 因为没有区分列表和段落,所以这个方法暂时不实现。
  455. 根据layout_list_info判断是不是列表。,下个layout的第一个段如果不是列表,那么看他们是否有几行都有相同的缩进。"""
  456. if (
  457. len(pre_page_paras) == 0 or len(next_page_paras) == 0
  458. ): # 0的时候最后的return 会出错
  459. return False
  460. if len(pre_page_paras[-1]) == 0 or len(next_page_paras[0]) == 0:
  461. return False
  462. if (
  463. pre_page_paras[-1][-1]['type'] != BlockType.Text
  464. or next_page_paras[0][0]['type'] != BlockType.Text
  465. ):
  466. return False
  467. if (
  468. pre_page_list_info[1] and not next_page_list_info[0]
  469. ): # 前一个是列表结尾,后一个是非列表开头,此时检测是否有相同的缩进
  470. if debug_able:
  471. logger.info(f'连接page {page_num} 内的list')
  472. # 向layout_paras[i] 寻找开头具有相同缩进的连续的行
  473. may_list_lines = []
  474. next_page_first_para = next_page_paras[0][0]
  475. if next_page_first_para['type'] == BlockType.Text:
  476. lines = next_page_first_para['lines']
  477. for line in lines:
  478. if (
  479. line['bbox'][0]
  480. > __find_layout_bbox_by_line(line['bbox'], next_page_layout_bbox)[0]
  481. ):
  482. may_list_lines.append(line)
  483. else:
  484. break
  485. # 如果这些行的缩进是相等的,那么连到上一个layout的最后一个段落上。
  486. if (
  487. len(may_list_lines) > 0
  488. and len(set([x['bbox'][0] for x in may_list_lines])) == 1
  489. ):
  490. # pre_page_paras[-1].append(may_list_lines)
  491. # 下一页合并到上一页最后一段,打一个cross_page的标签
  492. for line in may_list_lines:
  493. for span in line['spans']:
  494. span[CROSS_PAGE] = True # noqa: F405
  495. pre_page_paras[-1][-1]['lines'].extend(may_list_lines)
  496. next_page_first_para['lines'] = next_page_first_para['lines'][
  497. len(may_list_lines) :
  498. ]
  499. return True
  500. return False
  501. def __find_layout_bbox_by_line(line_bbox, layout_bboxes):
  502. """根据line找到所在的layout."""
  503. for layout in layout_bboxes:
  504. if is_in_layout(line_bbox, layout):
  505. return layout
  506. return None
  507. def __connect_para_inter_layoutbox(blocks_group, new_layout_bbox):
  508. """
  509. layout之间进行分段。
  510. 主要是计算前一个layOut的最后一行和后一个layout的第一行是否可以连接。
  511. 连接的条件需要同时满足:
  512. 1. 上一个layout的最后一行沾满整个行。并且没有结尾符号。
  513. 2. 下一行开头不留空白。
  514. """
  515. connected_layout_blocks = []
  516. if len(blocks_group) == 0:
  517. return connected_layout_blocks
  518. connected_layout_blocks.append(blocks_group[0])
  519. for i in range(1, len(blocks_group)):
  520. try:
  521. if len(blocks_group[i]) == 0:
  522. continue
  523. if len(blocks_group[i - 1]) == 0: # TODO 考虑连接问题,
  524. connected_layout_blocks.append(blocks_group[i])
  525. continue
  526. # text类型的段才需要考虑layout间的合并
  527. if (
  528. blocks_group[i - 1][-1]['type'] != BlockType.Text
  529. or blocks_group[i][0]['type'] != BlockType.Text
  530. ):
  531. connected_layout_blocks.append(blocks_group[i])
  532. continue
  533. if (
  534. len(blocks_group[i - 1][-1]['lines']) == 0
  535. or len(blocks_group[i][0]['lines']) == 0
  536. ):
  537. connected_layout_blocks.append(blocks_group[i])
  538. continue
  539. pre_last_line = blocks_group[i - 1][-1]['lines'][-1]
  540. next_first_line = blocks_group[i][0]['lines'][0]
  541. except Exception:
  542. logger.error(f'page layout {i} has no line')
  543. continue
  544. pre_last_line_text = ''.join(
  545. [__get_span_text(span) for span in pre_last_line['spans']]
  546. )
  547. pre_last_line_type = pre_last_line['spans'][-1]['type']
  548. next_first_line_text = ''.join(
  549. [__get_span_text(span) for span in next_first_line['spans']]
  550. )
  551. next_first_line_type = next_first_line['spans'][0]['type']
  552. if pre_last_line_type not in [
  553. TEXT,
  554. INLINE_EQUATION,
  555. ] or next_first_line_type not in [TEXT, INLINE_EQUATION]:
  556. connected_layout_blocks.append(blocks_group[i])
  557. continue
  558. pre_layout = __find_layout_bbox_by_line(pre_last_line['bbox'], new_layout_bbox)
  559. next_layout = __find_layout_bbox_by_line(
  560. next_first_line['bbox'], new_layout_bbox
  561. )
  562. pre_x2_max = pre_layout[2] if pre_layout else -1
  563. next_x0_min = next_layout[0] if next_layout else -1
  564. pre_last_line_text = pre_last_line_text.strip()
  565. next_first_line_text = next_first_line_text.strip()
  566. if (
  567. pre_last_line['bbox'][2] == pre_x2_max
  568. and pre_last_line_text
  569. and pre_last_line_text[-1] not in LINE_STOP_FLAG
  570. and next_first_line['bbox'][0] == next_x0_min
  571. ): # 前面一行沾满了整个行,并且没有结尾符号.下一行没有空白开头。
  572. """连接段落条件成立,将前一个layout的段落和后一个layout的段落连接。"""
  573. connected_layout_blocks[-1][-1]['lines'].extend(blocks_group[i][0]['lines'])
  574. blocks_group[i][0][
  575. 'lines'
  576. ] = [] # 删除后一个layout第一个段落中的lines,因为他已经被合并到前一个layout的最后一个段落了
  577. blocks_group[i][0][LINES_DELETED] = True # noqa: F405
  578. # if len(layout_paras[i]) == 0:
  579. # layout_paras.pop(i)
  580. # else:
  581. # connected_layout_paras.append(layout_paras[i])
  582. connected_layout_blocks.append(blocks_group[i])
  583. else:
  584. """连接段落条件不成立,将前一个layout的段落加入到结果中。"""
  585. connected_layout_blocks.append(blocks_group[i])
  586. return connected_layout_blocks
  587. def __connect_para_inter_page(
  588. pre_page_paras,
  589. next_page_paras,
  590. pre_page_layout_bbox,
  591. next_page_layout_bbox,
  592. page_num,
  593. lang,
  594. ):
  595. """
  596. 连接起来相邻两个页面的段落——前一个页面最后一个段落和后一个页面的第一个段落。
  597. 是否可以连接的条件:
  598. 1. 前一个页面的最后一个段落最后一行沾满整个行。并且没有结尾符号。
  599. 2. 后一个页面的第一个段落第一行没有空白开头。
  600. """
  601. # 有的页面可能压根没有文字
  602. if (
  603. len(pre_page_paras) == 0
  604. or len(next_page_paras) == 0
  605. or len(pre_page_paras[0]) == 0
  606. or len(next_page_paras[0]) == 0
  607. ): # TODO [[]]为什么出现在pre_page_paras里?
  608. return False
  609. pre_last_block = pre_page_paras[-1][-1]
  610. next_first_block = next_page_paras[0][0]
  611. if (
  612. pre_last_block['type'] != BlockType.Text
  613. or next_first_block['type'] != BlockType.Text
  614. ):
  615. return False
  616. if len(pre_last_block['lines']) == 0 or len(next_first_block['lines']) == 0:
  617. return False
  618. pre_last_para = pre_last_block['lines']
  619. next_first_para = next_first_block['lines']
  620. pre_last_line = pre_last_para[-1]
  621. next_first_line = next_first_para[0]
  622. pre_last_line_text = ''.join(
  623. [__get_span_text(span) for span in pre_last_line['spans']]
  624. )
  625. pre_last_line_type = pre_last_line['spans'][-1]['type']
  626. next_first_line_text = ''.join(
  627. [__get_span_text(span) for span in next_first_line['spans']]
  628. )
  629. next_first_line_type = next_first_line['spans'][0]['type']
  630. if pre_last_line_type not in [
  631. TEXT,
  632. INLINE_EQUATION,
  633. ] or next_first_line_type not in [
  634. TEXT,
  635. INLINE_EQUATION,
  636. ]: # TODO,真的要做好,要考虑跨table, image, 行间的情况
  637. # 不是文本,不连接
  638. return False
  639. pre_x2_max_bbox = __find_layout_bbox_by_line(
  640. pre_last_line['bbox'], pre_page_layout_bbox
  641. )
  642. if not pre_x2_max_bbox:
  643. return False
  644. next_x0_min_bbox = __find_layout_bbox_by_line(
  645. next_first_line['bbox'], next_page_layout_bbox
  646. )
  647. if not next_x0_min_bbox:
  648. return False
  649. pre_x2_max = pre_x2_max_bbox[2]
  650. next_x0_min = next_x0_min_bbox[0]
  651. pre_last_line_text = pre_last_line_text.strip()
  652. next_first_line_text = next_first_line_text.strip()
  653. if (
  654. pre_last_line['bbox'][2] == pre_x2_max
  655. and pre_last_line_text[-1] not in LINE_STOP_FLAG
  656. and next_first_line['bbox'][0] == next_x0_min
  657. ): # 前面一行沾满了整个行,并且没有结尾符号.下一行没有空白开头。
  658. """连接段落条件成立,将前一个layout的段落和后一个layout的段落连接。"""
  659. # 下一页合并到上一页最后一段,打一个cross_page的标签
  660. for line in next_first_para:
  661. for span in line['spans']:
  662. span[CROSS_PAGE] = True # noqa: F405
  663. pre_last_para.extend(next_first_para)
  664. # next_page_paras[0].pop(0) # 删除后一个页面的第一个段落, 因为他已经被合并到前一个页面的最后一个段落了。
  665. next_page_paras[0][0]['lines'] = []
  666. next_page_paras[0][0][LINES_DELETED] = True # noqa: F405
  667. return True
  668. else:
  669. return False
  670. def find_consecutive_true_regions(input_array):
  671. start_index = None # 连续True区域的起始索引
  672. regions = [] # 用于保存所有连续True区域的起始和结束索引
  673. for i in range(len(input_array)):
  674. # 如果我们找到了一个True值,并且当前并没有在连续True区域中
  675. if input_array[i] and start_index is None:
  676. start_index = i # 记录连续True区域的起始索引
  677. # 如果我们找到了一个False值,并且当前在连续True区域中
  678. elif not input_array[i] and start_index is not None:
  679. # 如果连续True区域长度大于1,那么将其添加到结果列表中
  680. if i - start_index > 1:
  681. regions.append((start_index, i - 1))
  682. start_index = None # 重置起始索引
  683. # 如果最后一个元素是True,那么需要将最后一个连续True区域加入到结果列表中
  684. if start_index is not None and len(input_array) - start_index > 1:
  685. regions.append((start_index, len(input_array) - 1))
  686. return regions
  687. def __connect_middle_align_text(page_paras, new_layout_bbox, page_num, lang):
  688. global debug_able
  689. """
  690. 找出来中间对齐的连续单行文本,如果连续行高度相同,那么合并为一个段落。
  691. 一个line居中的条件是:
  692. 1. 水平中心点跨越layout的中心点。
  693. 2. 左右两侧都有空白
  694. """
  695. for layout_i, layout_para in enumerate(page_paras):
  696. layout_box = new_layout_bbox[layout_i]
  697. single_line_paras_tag = []
  698. for i in range(len(layout_para)):
  699. # single_line_paras_tag.append(len(layout_para[i]) == 1 and layout_para[i][0]['spans'][0]['type'] == TEXT)
  700. single_line_paras_tag.append(
  701. layout_para[i]['type'] == BlockType.Text
  702. and len(layout_para[i]['lines']) == 1
  703. )
  704. """找出来连续的单行文本,如果连续行高度相同,那么合并为一个段落。"""
  705. consecutive_single_line_indices = find_consecutive_true_regions(
  706. single_line_paras_tag
  707. )
  708. if len(consecutive_single_line_indices) > 0:
  709. """检查这些行是否是高度相同的,居中的."""
  710. for start, end in consecutive_single_line_indices:
  711. # start += index_offset
  712. # end += index_offset
  713. line_hi = np.array(
  714. [
  715. block['lines'][0]['bbox'][3] - block['lines'][0]['bbox'][1]
  716. for block in layout_para[start : end + 1]
  717. ]
  718. )
  719. first_line_text = ''.join(
  720. [
  721. __get_span_text(span)
  722. for span in layout_para[start]['lines'][0]['spans']
  723. ]
  724. )
  725. if 'Table' in first_line_text or 'Figure' in first_line_text:
  726. pass
  727. if debug_able:
  728. logger.info(line_hi.std())
  729. if line_hi.std() < 2:
  730. """行高度相同,那么判断是否居中."""
  731. all_left_x0 = [
  732. block['lines'][0]['bbox'][0]
  733. for block in layout_para[start : end + 1]
  734. ]
  735. all_right_x1 = [
  736. block['lines'][0]['bbox'][2]
  737. for block in layout_para[start : end + 1]
  738. ]
  739. layout_center = (layout_box[0] + layout_box[2]) / 2
  740. if (
  741. all(
  742. [
  743. x0 < layout_center < x1
  744. for x0, x1 in zip(all_left_x0, all_right_x1)
  745. ]
  746. )
  747. and not all([x0 == layout_box[0] for x0 in all_left_x0])
  748. and not all([x1 == layout_box[2] for x1 in all_right_x1])
  749. ):
  750. merge_para = [
  751. block['lines'][0] for block in layout_para[start : end + 1]
  752. ]
  753. para_text = ''.join(
  754. [
  755. __get_span_text(span)
  756. for line in merge_para
  757. for span in line['spans']
  758. ]
  759. )
  760. if debug_able:
  761. logger.info(para_text)
  762. layout_para[start]['lines'] = merge_para
  763. for i_para in range(start + 1, end + 1):
  764. layout_para[i_para]['lines'] = []
  765. layout_para[i_para][LINES_DELETED] = True # noqa: F405
  766. # layout_para[start:end + 1] = [merge_para]
  767. # index_offset -= end - start
  768. return
  769. def __merge_signle_list_text(page_paras, new_layout_bbox, page_num, lang):
  770. """找出来连续的单行文本,如果首行顶格,接下来的几个单行段落缩进对齐,那么合并为一个段落。"""
  771. pass
  772. def __do_split_page(blocks, layout_bboxes, new_layout_bbox, page_num, lang):
  773. """根据line和layout情况进行分段 先实现一个根据行末尾特征分段的简单方法。"""
  774. """
  775. 算法思路:
  776. 1. 扫描layout里每一行,找出来行尾距离layout有边界有一定距离的行。
  777. 2. 从上述行中找到末尾是句号等可作为断行标志的行。
  778. 3. 参照上述行尾特征进行分段。
  779. 4. 图、表,目前独占一行,不考虑分段。
  780. """
  781. blocks_group = __group_line_by_layout(blocks, layout_bboxes) # block内分段
  782. layout_list_info = __split_para_in_layoutbox(
  783. blocks_group, new_layout_bbox, lang
  784. ) # layout内分段
  785. blocks_group, page_list_info = __connect_list_inter_layout(
  786. blocks_group, new_layout_bbox, layout_list_info, page_num, lang
  787. ) # layout之间连接列表段落
  788. connected_layout_blocks = __connect_para_inter_layoutbox(
  789. blocks_group, new_layout_bbox
  790. ) # layout间链接段落
  791. return connected_layout_blocks, page_list_info
  792. def para_split(pdf_info_dict, debug_mode, lang='en'):
  793. global debug_able
  794. debug_able = debug_mode
  795. new_layout_of_pages = [] # 数组的数组,每个元素是一个页面的layoutS
  796. all_page_list_info = [] # 保存每个页面开头和结尾是否是列表
  797. for page_num, page in pdf_info_dict.items():
  798. blocks = copy.deepcopy(page['preproc_blocks'])
  799. layout_bboxes = page['layout_bboxes']
  800. new_layout_bbox = __common_pre_proc(blocks, layout_bboxes)
  801. new_layout_of_pages.append(new_layout_bbox)
  802. splited_blocks, page_list_info = __do_split_page(
  803. blocks, layout_bboxes, new_layout_bbox, page_num, lang
  804. )
  805. all_page_list_info.append(page_list_info)
  806. page['para_blocks'] = splited_blocks
  807. """连接页面与页面之间的可能合并的段落"""
  808. pdf_infos = list(pdf_info_dict.values())
  809. for page_num, page in enumerate(pdf_info_dict.values()):
  810. if page_num == 0:
  811. continue
  812. pre_page_paras = pdf_infos[page_num - 1]['para_blocks']
  813. next_page_paras = pdf_infos[page_num]['para_blocks']
  814. pre_page_layout_bbox = new_layout_of_pages[page_num - 1]
  815. next_page_layout_bbox = new_layout_of_pages[page_num]
  816. is_conn = __connect_para_inter_page(
  817. pre_page_paras,
  818. next_page_paras,
  819. pre_page_layout_bbox,
  820. next_page_layout_bbox,
  821. page_num,
  822. lang,
  823. )
  824. if debug_able:
  825. if is_conn:
  826. logger.info(f'连接了第{page_num - 1}页和第{page_num}页的段落')
  827. is_list_conn = __connect_list_inter_page(
  828. pre_page_paras,
  829. next_page_paras,
  830. pre_page_layout_bbox,
  831. next_page_layout_bbox,
  832. all_page_list_info[page_num - 1],
  833. all_page_list_info[page_num],
  834. page_num,
  835. lang,
  836. )
  837. if debug_able:
  838. if is_list_conn:
  839. logger.info(f'连接了第{page_num - 1}页和第{page_num}页的列表段落')
  840. """接下来可能会漏掉一些特别的一些可以合并的内容,对他们进行段落连接
  841. 1. 正文中有时出现一个行顶格,接下来几行缩进的情况。
  842. 2. 居中的一些连续单行,如果高度相同,那么可能是一个段落。
  843. """
  844. for page_num, page in enumerate(pdf_info_dict.values()):
  845. page_paras = page['para_blocks']
  846. new_layout_bbox = new_layout_of_pages[page_num]
  847. __connect_middle_align_text(page_paras, new_layout_bbox, page_num, lang)
  848. __merge_signle_list_text(page_paras, new_layout_bbox, page_num, lang)
  849. # layout展平
  850. for page_num, page in enumerate(pdf_info_dict.values()):
  851. page_paras = page['para_blocks']
  852. page_blocks = [block for layout in page_paras for block in layout]
  853. page['para_blocks'] = page_blocks