ocr_mkcontent.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. para_text += f"\n![]({join_path(img_buket_path, span['image_path'])}) \n"
  61. for block in para_block['blocks']: # 2nd.拼image_caption
  62. if block['type'] == BlockType.ImageCaption:
  63. para_text += merge_para_with_text(block) + ' \n'
  64. for block in para_block['blocks']: # 3rd.拼image_footnote
  65. if block['type'] == BlockType.ImageFootnote:
  66. para_text += merge_para_with_text(block) + ' \n'
  67. elif para_type == BlockType.Table:
  68. if mode == 'nlp':
  69. continue
  70. elif mode == 'mm':
  71. for block in para_block['blocks']: # 1st.拼table_caption
  72. if block['type'] == BlockType.TableCaption:
  73. para_text += merge_para_with_text(block) + ' \n'
  74. for block in para_block['blocks']: # 2nd.拼table_body
  75. if block['type'] == BlockType.TableBody:
  76. for line in block['lines']:
  77. for span in line['spans']:
  78. if span['type'] == ContentType.Table:
  79. # if processed by table model
  80. if span.get('latex', ''):
  81. para_text += f"\n\n$\n {span['latex']}\n$\n\n"
  82. elif span.get('html', ''):
  83. para_text += f"\n\n{span['html']}\n\n"
  84. else:
  85. para_text += f"\n![]({join_path(img_buket_path, span['image_path'])}) \n"
  86. for block in para_block['blocks']: # 3rd.拼table_footnote
  87. if block['type'] == BlockType.TableFootnote:
  88. para_text += merge_para_with_text(block) + ' \n'
  89. if para_text.strip() == '':
  90. continue
  91. else:
  92. page_markdown.append(para_text.strip() + ' ')
  93. return page_markdown
  94. def detect_language(text):
  95. en_pattern = r'[a-zA-Z]+'
  96. en_matches = re.findall(en_pattern, text)
  97. en_length = sum(len(match) for match in en_matches)
  98. if len(text) > 0:
  99. if en_length / len(text) >= 0.5:
  100. return 'en'
  101. else:
  102. return 'unknown'
  103. else:
  104. return 'empty'
  105. def merge_para_with_text(para_block):
  106. para_text = ''
  107. for i, line in enumerate(para_block['lines']):
  108. if i >= 1 and line.get(ListLineTag.IS_LIST_START_LINE, False):
  109. para_text += ' \n'
  110. line_text = ''
  111. line_lang = ''
  112. for span in line['spans']:
  113. span_type = span['type']
  114. if span_type == ContentType.Text:
  115. line_text += span['content'].strip()
  116. if line_text != '':
  117. line_lang = detect_lang(line_text)
  118. for span in line['spans']:
  119. span_type = span['type']
  120. content = ''
  121. if span_type == ContentType.Text:
  122. content = ocr_escape_special_markdown_char(span['content'])
  123. elif span_type == ContentType.InlineEquation:
  124. content = f" ${span['content']}$ "
  125. elif span_type == ContentType.InterlineEquation:
  126. content = f"\n$$\n{span['content']}\n$$\n"
  127. if content != '':
  128. langs = ['zh', 'ja', 'ko']
  129. if line_lang in langs: # 遇到一些一个字一个span的文档,这种单字语言判断不准,需要用整行文本判断
  130. para_text += content # 中文/日语/韩文语境下,content间不需要空格分隔
  131. elif line_lang == 'en':
  132. # 如果是前一行带有-连字符,那么末尾不应该加空格
  133. if __is_hyphen_at_line_end(content):
  134. para_text += content[:-1]
  135. else:
  136. para_text += content + ' '
  137. else:
  138. para_text += content + ' ' # 西方文本语境下 content间需要空格分隔
  139. return para_text
  140. def para_to_standard_format_v2(para_block, img_buket_path, page_idx, drop_reason=None):
  141. para_type = para_block['type']
  142. para_content = {}
  143. if para_type in [BlockType.Text, BlockType.List, BlockType.Index]:
  144. para_content = {
  145. 'type': 'text',
  146. 'text': merge_para_with_text(para_block),
  147. }
  148. elif para_type == BlockType.Title:
  149. para_content = {
  150. 'type': 'text',
  151. 'text': merge_para_with_text(para_block),
  152. 'text_level': 1,
  153. }
  154. elif para_type == BlockType.InterlineEquation:
  155. para_content = {
  156. 'type': 'equation',
  157. 'text': merge_para_with_text(para_block),
  158. 'text_format': 'latex',
  159. }
  160. elif para_type == BlockType.Image:
  161. para_content = {'type': 'image', 'img_caption': [], 'img_footnote': []}
  162. for block in para_block['blocks']:
  163. if block['type'] == BlockType.ImageBody:
  164. para_content['img_path'] = join_path(
  165. img_buket_path,
  166. block['lines'][0]['spans'][0]['image_path'])
  167. if block['type'] == BlockType.ImageCaption:
  168. para_content['img_caption'].append(merge_para_with_text(block))
  169. if block['type'] == BlockType.ImageFootnote:
  170. para_content['img_footnote'].append(merge_para_with_text(block))
  171. elif para_type == BlockType.Table:
  172. para_content = {'type': 'table', 'table_caption': [], 'table_footnote': []}
  173. for block in para_block['blocks']:
  174. if block['type'] == BlockType.TableBody:
  175. if block["lines"][0]["spans"][0].get('latex', ''):
  176. para_content['table_body'] = f"\n\n$\n {block['lines'][0]['spans'][0]['latex']}\n$\n\n"
  177. elif block["lines"][0]["spans"][0].get('html', ''):
  178. para_content['table_body'] = f"\n\n{block['lines'][0]['spans'][0]['html']}\n\n"
  179. para_content['img_path'] = join_path(img_buket_path, block["lines"][0]["spans"][0]['image_path'])
  180. if block['type'] == BlockType.TableCaption:
  181. para_content['table_caption'].append(merge_para_with_text(block))
  182. if block['type'] == BlockType.TableFootnote:
  183. para_content['table_footnote'].append(merge_para_with_text(block))
  184. para_content['page_idx'] = page_idx
  185. if drop_reason is not None:
  186. para_content['drop_reason'] = drop_reason
  187. return para_content
  188. def union_make(pdf_info_dict: list,
  189. make_mode: str,
  190. drop_mode: str,
  191. img_buket_path: str = '',
  192. ):
  193. output_content = []
  194. for page_info in pdf_info_dict:
  195. drop_reason_flag = False
  196. drop_reason = None
  197. if page_info.get('need_drop', False):
  198. drop_reason = page_info.get('drop_reason')
  199. if drop_mode == DropMode.NONE:
  200. pass
  201. elif drop_mode == DropMode.NONE_WITH_REASON:
  202. drop_reason_flag = True
  203. elif drop_mode == DropMode.WHOLE_PDF:
  204. raise Exception((f'drop_mode is {DropMode.WHOLE_PDF} ,'
  205. f'drop_reason is {drop_reason}'))
  206. elif drop_mode == DropMode.SINGLE_PAGE:
  207. logger.warning((f'drop_mode is {DropMode.SINGLE_PAGE} ,'
  208. f'drop_reason is {drop_reason}'))
  209. continue
  210. else:
  211. raise Exception('drop_mode can not be null')
  212. paras_of_layout = page_info.get('para_blocks')
  213. page_idx = page_info.get('page_idx')
  214. if not paras_of_layout:
  215. continue
  216. if make_mode == MakeMode.MM_MD:
  217. page_markdown = ocr_mk_markdown_with_para_core_v2(
  218. paras_of_layout, 'mm', img_buket_path)
  219. output_content.extend(page_markdown)
  220. elif make_mode == MakeMode.NLP_MD:
  221. page_markdown = ocr_mk_markdown_with_para_core_v2(
  222. paras_of_layout, 'nlp')
  223. output_content.extend(page_markdown)
  224. elif make_mode == MakeMode.STANDARD_FORMAT:
  225. for para_block in paras_of_layout:
  226. if drop_reason_flag:
  227. para_content = para_to_standard_format_v2(
  228. para_block, img_buket_path, page_idx)
  229. else:
  230. para_content = para_to_standard_format_v2(
  231. para_block, img_buket_path, page_idx)
  232. output_content.append(para_content)
  233. if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
  234. return '\n\n'.join(output_content)
  235. elif make_mode == MakeMode.STANDARD_FORMAT:
  236. return output_content