ocr_mkcontent.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import re
  2. from loguru import logger
  3. from magic_pdf.config.make_content_config import DropMode, MakeMode
  4. from magic_pdf.config.ocr_content_type import BlockType, ContentType
  5. from magic_pdf.libs.commons import join_path
  6. from magic_pdf.libs.markdown_utils import ocr_escape_special_markdown_char
  7. from magic_pdf.para.para_split_v3 import ListLineTag
  8. def __is_hyphen_at_line_end(line):
  9. """Check if a line ends with one or more letters followed by a hyphen.
  10. Args:
  11. line (str): The line of text to check.
  12. Returns:
  13. bool: True if the line ends with one or more letters followed by a hyphen, False otherwise.
  14. """
  15. # Use regex to check if the line ends with one or more letters followed by a hyphen
  16. return bool(re.search(r'[A-Za-z]+-\s*$', line))
  17. def ocr_mk_mm_markdown_with_para_and_pagination(pdf_info_dict: list,
  18. img_buket_path):
  19. markdown_with_para_and_pagination = []
  20. page_no = 0
  21. for page_info in pdf_info_dict:
  22. paras_of_layout = page_info.get('para_blocks')
  23. if not paras_of_layout:
  24. markdown_with_para_and_pagination.append({
  25. 'page_no':
  26. page_no,
  27. 'md_content':
  28. '',
  29. })
  30. page_no += 1
  31. continue
  32. page_markdown = ocr_mk_markdown_with_para_core_v2(
  33. paras_of_layout, 'mm', img_buket_path)
  34. markdown_with_para_and_pagination.append({
  35. 'page_no':
  36. page_no,
  37. 'md_content':
  38. '\n\n'.join(page_markdown)
  39. })
  40. page_no += 1
  41. return markdown_with_para_and_pagination
  42. def ocr_mk_markdown_with_para_core_v2(paras_of_layout,
  43. mode,
  44. img_buket_path='',
  45. ):
  46. page_markdown = []
  47. for para_block in paras_of_layout:
  48. para_text = ''
  49. para_type = para_block['type']
  50. if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
  51. para_text = merge_para_with_text(para_block)
  52. elif para_type == BlockType.Title:
  53. para_text = f'# {merge_para_with_text(para_block)}'
  54. elif para_type == BlockType.InterlineEquation:
  55. para_text = merge_para_with_text(para_block)
  56. elif para_type == BlockType.Image:
  57. if mode == 'nlp':
  58. continue
  59. elif mode == 'mm':
  60. for block in para_block['blocks']: # 1st.拼image_body
  61. if block['type'] == BlockType.ImageBody:
  62. for line in block['lines']:
  63. for span in line['spans']:
  64. if span['type'] == ContentType.Image:
  65. if span.get('image_path', ''):
  66. para_text += f"\n![]({join_path(img_buket_path, span['image_path'])}) \n"
  67. for block in para_block['blocks']: # 2nd.拼image_caption
  68. if block['type'] == BlockType.ImageCaption:
  69. para_text += merge_para_with_text(block) + ' \n'
  70. for block in para_block['blocks']: # 3rd.拼image_footnote
  71. if block['type'] == BlockType.ImageFootnote:
  72. para_text += merge_para_with_text(block) + ' \n'
  73. elif para_type == BlockType.Table:
  74. if mode == 'nlp':
  75. continue
  76. elif mode == 'mm':
  77. for block in para_block['blocks']: # 1st.拼table_caption
  78. if block['type'] == BlockType.TableCaption:
  79. para_text += merge_para_with_text(block) + ' \n'
  80. for block in para_block['blocks']: # 2nd.拼table_body
  81. if block['type'] == BlockType.TableBody:
  82. for line in block['lines']:
  83. for span in line['spans']:
  84. if span['type'] == ContentType.Table:
  85. # if processed by table model
  86. if span.get('latex', ''):
  87. para_text += f"\n\n$\n {span['latex']}\n$\n\n"
  88. elif span.get('html', ''):
  89. para_text += f"\n\n{span['html']}\n\n"
  90. elif span.get('image_path', ''):
  91. para_text += f"\n![]({join_path(img_buket_path, span['image_path'])}) \n"
  92. for block in para_block['blocks']: # 3rd.拼table_footnote
  93. if block['type'] == BlockType.TableFootnote:
  94. para_text += merge_para_with_text(block) + ' \n'
  95. if para_text.strip() == '':
  96. continue
  97. else:
  98. page_markdown.append(para_text.strip() + ' ')
  99. return page_markdown
  100. def detect_language(text):
  101. en_pattern = r'[a-zA-Z]+'
  102. en_matches = re.findall(en_pattern, text)
  103. en_length = sum(len(match) for match in en_matches)
  104. if len(text) > 0:
  105. if en_length / len(text) >= 0.5:
  106. return 'en'
  107. else:
  108. return 'unknown'
  109. else:
  110. return 'empty'
  111. # 连写字符拆分
  112. def __replace_ligatures(text: str):
  113. text = re.sub(r'fi', 'fi', text) # 替换 fi 连写符
  114. text = re.sub(r'fl', 'fl', text) # 替换 fl 连写符
  115. text = re.sub(r'ff', 'ff', text) # 替换 ff 连写符
  116. text = re.sub(r'ffi', 'ffi', text) # 替换 ffi 连写符
  117. text = re.sub(r'ffl', 'ffl', text) # 替换 ffl 连写符
  118. return text
  119. def merge_para_with_text(para_block):
  120. para_text = ''
  121. for i, line in enumerate(para_block['lines']):
  122. if i >= 1 and line.get(ListLineTag.IS_LIST_START_LINE, False):
  123. para_text += ' \n'
  124. line_text = ''
  125. for span in line['spans']:
  126. span_type = span['type']
  127. if span_type == ContentType.Text:
  128. line_text += span['content'].strip()
  129. for j, span in enumerate(line['spans']):
  130. span_type = span['type']
  131. content = ''
  132. if span_type == ContentType.Text:
  133. content = ocr_escape_special_markdown_char(span['content'])
  134. elif span_type == ContentType.InlineEquation:
  135. content = f"${span['content']}$"
  136. elif span_type == ContentType.InterlineEquation:
  137. content = f"\n$$\n{span['content']}\n$$\n"
  138. content = content.strip()
  139. if content != '':
  140. if span_type in [ContentType.Text, ContentType.InlineEquation]:
  141. # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
  142. if j == len(line['spans'])-1 and __is_hyphen_at_line_end(content):
  143. para_text += content[:-1]
  144. else: # content间需要空格分隔
  145. para_text += f'{content} '
  146. elif span_type == ContentType.InterlineEquation:
  147. para_text += content
  148. else:
  149. continue
  150. # 连写字符拆分
  151. # para_text = __replace_ligatures(para_text)
  152. return para_text
  153. def para_to_standard_format_v2(para_block, img_buket_path, page_idx, drop_reason=None):
  154. para_type = para_block['type']
  155. para_content = {}
  156. if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
  157. para_content = {
  158. 'type': 'text',
  159. 'text': merge_para_with_text(para_block),
  160. }
  161. elif para_type == BlockType.Title:
  162. para_content = {
  163. 'type': 'text',
  164. 'text': merge_para_with_text(para_block),
  165. 'text_level': 1,
  166. }
  167. elif para_type == BlockType.InterlineEquation:
  168. para_content = {
  169. 'type': 'equation',
  170. 'text': merge_para_with_text(para_block),
  171. 'text_format': 'latex',
  172. }
  173. elif para_type == BlockType.Image:
  174. para_content = {'type': 'image', 'img_path': '', 'img_caption': [], 'img_footnote': []}
  175. for block in para_block['blocks']:
  176. if block['type'] == BlockType.ImageBody:
  177. for line in block['lines']:
  178. for span in line['spans']:
  179. if span['type'] == ContentType.Image:
  180. if span.get('image_path', ''):
  181. para_content['img_path'] = join_path(img_buket_path, span['image_path'])
  182. if block['type'] == BlockType.ImageCaption:
  183. para_content['img_caption'].append(merge_para_with_text(block))
  184. if block['type'] == BlockType.ImageFootnote:
  185. para_content['img_footnote'].append(merge_para_with_text(block))
  186. elif para_type == BlockType.Table:
  187. para_content = {'type': 'table', 'img_path': '', 'table_caption': [], 'table_footnote': []}
  188. for block in para_block['blocks']:
  189. if block['type'] == BlockType.TableBody:
  190. for line in block['lines']:
  191. for span in line['spans']:
  192. if span['type'] == ContentType.Table:
  193. if span.get('latex', ''):
  194. para_content['table_body'] = f"\n\n$\n {span['latex']}\n$\n\n"
  195. elif span.get('html', ''):
  196. para_content['table_body'] = f"\n\n{span['html']}\n\n"
  197. if span.get('image_path', ''):
  198. para_content['img_path'] = join_path(img_buket_path, span['image_path'])
  199. if block['type'] == BlockType.TableCaption:
  200. para_content['table_caption'].append(merge_para_with_text(block))
  201. if block['type'] == BlockType.TableFootnote:
  202. para_content['table_footnote'].append(merge_para_with_text(block))
  203. para_content['page_idx'] = page_idx
  204. if drop_reason is not None:
  205. para_content['drop_reason'] = drop_reason
  206. return para_content
  207. def union_make(pdf_info_dict: list,
  208. make_mode: str,
  209. drop_mode: str,
  210. img_buket_path: str = '',
  211. ):
  212. output_content = []
  213. for page_info in pdf_info_dict:
  214. drop_reason_flag = False
  215. drop_reason = None
  216. if page_info.get('need_drop', False):
  217. drop_reason = page_info.get('drop_reason')
  218. if drop_mode == DropMode.NONE:
  219. pass
  220. elif drop_mode == DropMode.NONE_WITH_REASON:
  221. drop_reason_flag = True
  222. elif drop_mode == DropMode.WHOLE_PDF:
  223. raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
  224. f'drop_reason is {drop_reason}'))
  225. elif drop_mode == DropMode.SINGLE_PAGE:
  226. logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
  227. f'drop_reason is {drop_reason}'))
  228. continue
  229. else:
  230. raise Exception('drop_mode can not be null')
  231. paras_of_layout = page_info.get('para_blocks')
  232. page_idx = page_info.get('page_idx')
  233. if not paras_of_layout:
  234. continue
  235. if make_mode == MakeMode.MM_MD:
  236. page_markdown = ocr_mk_markdown_with_para_core_v2(
  237. paras_of_layout, 'mm', img_buket_path)
  238. output_content.extend(page_markdown)
  239. elif make_mode == MakeMode.NLP_MD:
  240. page_markdown = ocr_mk_markdown_with_para_core_v2(
  241. paras_of_layout, 'nlp')
  242. output_content.extend(page_markdown)
  243. elif make_mode == MakeMode.STANDARD_FORMAT:
  244. for para_block in paras_of_layout:
  245. if drop_reason_flag:
  246. para_content = para_to_standard_format_v2(
  247. para_block, img_buket_path, page_idx)
  248. else:
  249. para_content = para_to_standard_format_v2(
  250. para_block, img_buket_path, page_idx)
  251. output_content.append(para_content)
  252. if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
  253. return '\n\n'.join(output_content)
  254. elif make_mode == MakeMode.STANDARD_FORMAT:
  255. return output_content