ocr_mkcontent.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. def merge_para_with_text(para_block):
  107. para_text = ''
  108. for i, line in enumerate(para_block['lines']):
  109. if i >= 1 and line.get(ListLineTag.IS_LIST_START_LINE, False):
  110. para_text += ' \n'
  111. line_text = ''
  112. line_lang = ''
  113. for span in line['spans']:
  114. span_type = span['type']
  115. if span_type == ContentType.Text:
  116. line_text += span['content'].strip()
  117. if line_text != '':
  118. line_lang = detect_lang(line_text)
  119. for span in line['spans']:
  120. span_type = span['type']
  121. content = ''
  122. if span_type == ContentType.Text:
  123. content = ocr_escape_special_markdown_char(span['content'])
  124. elif span_type == ContentType.InlineEquation:
  125. content = f" ${span['content']}$ "
  126. elif span_type == ContentType.InterlineEquation:
  127. content = f"\n$$\n{span['content']}\n$$\n"
  128. if content != '':
  129. langs = ['zh', 'ja', 'ko']
  130. if line_lang in langs: # 遇到一些一个字一个span的文档,这种单字语言判断不准,需要用整行文本判断
  131. para_text += content # 中文/日语/韩文语境下,content间不需要空格分隔
  132. elif line_lang == 'en':
  133. # 如果是前一行带有-连字符,那么末尾不应该加空格
  134. if __is_hyphen_at_line_end(content):
  135. para_text += content[:-1]
  136. else:
  137. para_text += content + ' '
  138. else:
  139. para_text += content + ' ' # 西方文本语境下 content间需要空格分隔
  140. return para_text
  141. def para_to_standard_format_v2(para_block, img_buket_path, page_idx, drop_reason=None):
  142. para_type = para_block['type']
  143. para_content = {}
  144. if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
  145. para_content = {
  146. 'type': 'text',
  147. 'text': merge_para_with_text(para_block),
  148. }
  149. elif para_type == BlockType.Title:
  150. para_content = {
  151. 'type': 'text',
  152. 'text': merge_para_with_text(para_block),
  153. 'text_level': 1,
  154. }
  155. elif para_type == BlockType.InterlineEquation:
  156. para_content = {
  157. 'type': 'equation',
  158. 'text': merge_para_with_text(para_block),
  159. 'text_format': 'latex',
  160. }
  161. elif para_type == BlockType.Image:
  162. para_content = {'type': 'image', 'img_path': '', 'img_caption': [], 'img_footnote': []}
  163. for block in para_block['blocks']:
  164. if block['type'] == BlockType.ImageBody:
  165. for line in block['lines']:
  166. for span in line['spans']:
  167. if span['type'] == ContentType.Image:
  168. if span.get('image_path', ''):
  169. para_content['img_path'] = join_path(img_buket_path, span['image_path'])
  170. if block['type'] == BlockType.ImageCaption:
  171. para_content['img_caption'].append(merge_para_with_text(block))
  172. if block['type'] == BlockType.ImageFootnote:
  173. para_content['img_footnote'].append(merge_para_with_text(block))
  174. elif para_type == BlockType.Table:
  175. para_content = {'type': 'table', 'img_path': '', 'table_caption': [], 'table_footnote': []}
  176. for block in para_block['blocks']:
  177. if block['type'] == BlockType.TableBody:
  178. for line in block['lines']:
  179. for span in line['spans']:
  180. if span['type'] == ContentType.Table:
  181. if span.get('latex', ''):
  182. para_content['table_body'] = f"\n\n$\n {span['latex']}\n$\n\n"
  183. elif span.get('html', ''):
  184. para_content['table_body'] = f"\n\n{span['html']}\n\n"
  185. if span.get('image_path', ''):
  186. para_content['img_path'] = join_path(img_buket_path, span['image_path'])
  187. if block['type'] == BlockType.TableCaption:
  188. para_content['table_caption'].append(merge_para_with_text(block))
  189. if block['type'] == BlockType.TableFootnote:
  190. para_content['table_footnote'].append(merge_para_with_text(block))
  191. para_content['page_idx'] = page_idx
  192. if drop_reason is not None:
  193. para_content['drop_reason'] = drop_reason
  194. return para_content
  195. def union_make(pdf_info_dict: list,
  196. make_mode: str,
  197. drop_mode: str,
  198. img_buket_path: str = '',
  199. ):
  200. output_content = []
  201. for page_info in pdf_info_dict:
  202. drop_reason_flag = False
  203. drop_reason = None
  204. if page_info.get('need_drop', False):
  205. drop_reason = page_info.get('drop_reason')
  206. if drop_mode == DropMode.NONE:
  207. pass
  208. elif drop_mode == DropMode.NONE_WITH_REASON:
  209. drop_reason_flag = True
  210. elif drop_mode == DropMode.WHOLE_PDF:
  211. raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
  212. f'drop_reason is {drop_reason}'))
  213. elif drop_mode == DropMode.SINGLE_PAGE:
  214. logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
  215. f'drop_reason is {drop_reason}'))
  216. continue
  217. else:
  218. raise Exception('drop_mode can not be null')
  219. paras_of_layout = page_info.get('para_blocks')
  220. page_idx = page_info.get('page_idx')
  221. if not paras_of_layout:
  222. continue
  223. if make_mode == MakeMode.MM_MD:
  224. page_markdown = ocr_mk_markdown_with_para_core_v2(
  225. paras_of_layout, 'mm', img_buket_path)
  226. output_content.extend(page_markdown)
  227. elif make_mode == MakeMode.NLP_MD:
  228. page_markdown = ocr_mk_markdown_with_para_core_v2(
  229. paras_of_layout, 'nlp')
  230. output_content.extend(page_markdown)
  231. elif make_mode == MakeMode.STANDARD_FORMAT:
  232. for para_block in paras_of_layout:
  233. if drop_reason_flag:
  234. para_content = para_to_standard_format_v2(
  235. para_block, img_buket_path, page_idx)
  236. else:
  237. para_content = para_to_standard_format_v2(
  238. para_block, img_buket_path, page_idx)
  239. output_content.append(para_content)
  240. if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
  241. return '\n\n'.join(output_content)
  242. elif make_mode == MakeMode.STANDARD_FORMAT:
  243. return output_content