ocr_mkcontent.py 13 KB

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