vlm_middle_json_mkcontent.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import os
  2. from mineru.utils.config_reader import get_latex_delimiter_config, get_formula_enable, get_table_enable
  3. from mineru.utils.enum_class import MakeMode, BlockType, ContentType
  4. from pygments.lexers import guess_lexer
  5. latex_delimiters_config = get_latex_delimiter_config()
  6. default_delimiters = {
  7. 'display': {'left': '$$', 'right': '$$'},
  8. 'inline': {'left': '$', 'right': '$'}
  9. }
  10. delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters
  11. display_left_delimiter = delimiters['display']['left']
  12. display_right_delimiter = delimiters['display']['right']
  13. inline_left_delimiter = delimiters['inline']['left']
  14. inline_right_delimiter = delimiters['inline']['right']
  15. def merge_para_with_text(para_block, formula_enable=True, img_buket_path=''):
  16. para_text = ''
  17. for line in para_block['lines']:
  18. for j, span in enumerate(line['spans']):
  19. span_type = span['type']
  20. content = ''
  21. if span_type == ContentType.TEXT:
  22. content = span['content']
  23. elif span_type == ContentType.INLINE_EQUATION:
  24. content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
  25. elif span_type == ContentType.INTERLINE_EQUATION:
  26. if formula_enable:
  27. content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
  28. else:
  29. if span.get('image_path', ''):
  30. content = f"![]({img_buket_path}/{span['image_path']})"
  31. # content = content.strip()
  32. if content:
  33. if span_type in [ContentType.TEXT, ContentType.INLINE_EQUATION]:
  34. if j == len(line['spans']) - 1:
  35. para_text += content
  36. else:
  37. para_text += f'{content} '
  38. elif span_type == ContentType.INTERLINE_EQUATION:
  39. para_text += content
  40. return para_text
  41. def mk_blocks_to_markdown(para_blocks, make_mode, formula_enable, table_enable, img_buket_path=''):
  42. page_markdown = []
  43. for para_block in para_blocks:
  44. para_text = ''
  45. para_type = para_block['type']
  46. if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION, BlockType.PHONETIC, BlockType.REF_TEXT]:
  47. para_text = merge_para_with_text(para_block, formula_enable=formula_enable, img_buket_path=img_buket_path)
  48. elif para_type == BlockType.LIST:
  49. for block in para_block['blocks']:
  50. item_text = merge_para_with_text(block, formula_enable=formula_enable, img_buket_path=img_buket_path)
  51. para_text += f"{item_text}\n"
  52. elif para_type == BlockType.TITLE:
  53. title_level = get_title_level(para_block)
  54. para_text = f'{"#" * title_level} {merge_para_with_text(para_block)}'
  55. elif para_type == BlockType.IMAGE:
  56. if make_mode == MakeMode.NLP_MD:
  57. continue
  58. elif make_mode == MakeMode.MM_MD:
  59. # 检测是否存在图片脚注
  60. has_image_footnote = any(block['type'] == BlockType.IMAGE_FOOTNOTE for block in para_block['blocks'])
  61. # 如果存在图片脚注,则将图片脚注拼接到图片正文后面
  62. if has_image_footnote:
  63. for block in para_block['blocks']: # 1st.拼image_caption
  64. if block['type'] == BlockType.IMAGE_CAPTION:
  65. para_text += merge_para_with_text(block) + ' \n'
  66. for block in para_block['blocks']: # 2nd.拼image_body
  67. if block['type'] == BlockType.IMAGE_BODY:
  68. for line in block['lines']:
  69. for span in line['spans']:
  70. if span['type'] == ContentType.IMAGE:
  71. if span.get('image_path', ''):
  72. para_text += f"![]({img_buket_path}/{span['image_path']})"
  73. for block in para_block['blocks']: # 3rd.拼image_footnote
  74. if block['type'] == BlockType.IMAGE_FOOTNOTE:
  75. para_text += ' \n' + merge_para_with_text(block)
  76. else:
  77. for block in para_block['blocks']: # 1st.拼image_body
  78. if block['type'] == BlockType.IMAGE_BODY:
  79. for line in block['lines']:
  80. for span in line['spans']:
  81. if span['type'] == ContentType.IMAGE:
  82. if span.get('image_path', ''):
  83. para_text += f"![]({img_buket_path}/{span['image_path']})"
  84. for block in para_block['blocks']: # 2nd.拼image_caption
  85. if block['type'] == BlockType.IMAGE_CAPTION:
  86. para_text += ' \n' + merge_para_with_text(block)
  87. elif para_type == BlockType.TABLE:
  88. if make_mode == MakeMode.NLP_MD:
  89. continue
  90. elif make_mode == MakeMode.MM_MD:
  91. for block in para_block['blocks']: # 1st.拼table_caption
  92. if block['type'] == BlockType.TABLE_CAPTION:
  93. para_text += merge_para_with_text(block) + ' \n'
  94. for block in para_block['blocks']: # 2nd.拼table_body
  95. if block['type'] == BlockType.TABLE_BODY:
  96. for line in block['lines']:
  97. for span in line['spans']:
  98. if span['type'] == ContentType.TABLE:
  99. # if processed by table model
  100. if table_enable:
  101. if span.get('html', ''):
  102. para_text += f"\n{span['html']}\n"
  103. elif span.get('image_path', ''):
  104. para_text += f"![]({img_buket_path}/{span['image_path']})"
  105. else:
  106. if span.get('image_path', ''):
  107. para_text += f"![]({img_buket_path}/{span['image_path']})"
  108. for block in para_block['blocks']: # 3rd.拼table_footnote
  109. if block['type'] == BlockType.TABLE_FOOTNOTE:
  110. para_text += '\n' + merge_para_with_text(block) + ' '
  111. elif para_type == BlockType.CODE:
  112. sub_type = para_block["sub_type"]
  113. for block in para_block['blocks']: # 1st.拼code_caption
  114. if block['type'] == BlockType.CODE_CAPTION:
  115. para_text += merge_para_with_text(block) + ' \n'
  116. for block in para_block['blocks']: # 2nd.拼code_body
  117. if block['type'] == BlockType.CODE_BODY:
  118. if sub_type == BlockType.CODE:
  119. content_text = merge_para_with_text(block)
  120. lexer = guess_lexer(content_text)
  121. para_text += f"```{lexer.aliases[0]}\n{merge_para_with_text(block)}\n```"
  122. elif sub_type == BlockType.ALGORITHM:
  123. para_text += merge_para_with_text(block)
  124. if para_text.strip() == '':
  125. continue
  126. else:
  127. # page_markdown.append(para_text.strip() + ' ')
  128. page_markdown.append(para_text.strip())
  129. return page_markdown
  130. def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size):
  131. para_type = para_block['type']
  132. para_content = {}
  133. if para_type in [
  134. BlockType.TEXT,
  135. BlockType.REF_TEXT,
  136. BlockType.PHONETIC,
  137. BlockType.HEADER,
  138. BlockType.FOOTER,
  139. BlockType.PAGE_NUMBER,
  140. BlockType.ASIDE_TEXT,
  141. BlockType.PAGE_FOOTNOTE,
  142. ]:
  143. para_content = {
  144. 'type': para_type,
  145. 'text': merge_para_with_text(para_block),
  146. }
  147. elif para_type == BlockType.LIST:
  148. para_content = {
  149. 'type': para_type,
  150. 'sub_type': para_block.get('sub_type', ''),
  151. 'list_items':[],
  152. }
  153. for block in para_block['blocks']:
  154. item_text = merge_para_with_text(block)
  155. if item_text.strip():
  156. para_content['list_items'].append(item_text)
  157. elif para_type == BlockType.TITLE:
  158. title_level = get_title_level(para_block)
  159. para_content = {
  160. 'type': ContentType.TEXT,
  161. 'text': merge_para_with_text(para_block),
  162. }
  163. if title_level != 0:
  164. para_content['text_level'] = title_level
  165. elif para_type == BlockType.INTERLINE_EQUATION:
  166. para_content = {
  167. 'type': ContentType.EQUATION,
  168. 'text': merge_para_with_text(para_block),
  169. 'text_format': 'latex',
  170. }
  171. elif para_type == BlockType.IMAGE:
  172. para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}
  173. for block in para_block['blocks']:
  174. if block['type'] == BlockType.IMAGE_BODY:
  175. for line in block['lines']:
  176. for span in line['spans']:
  177. if span['type'] == ContentType.IMAGE:
  178. if span.get('image_path', ''):
  179. para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
  180. if block['type'] == BlockType.IMAGE_CAPTION:
  181. para_content[BlockType.IMAGE_CAPTION].append(merge_para_with_text(block))
  182. if block['type'] == BlockType.IMAGE_FOOTNOTE:
  183. para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_with_text(block))
  184. elif para_type == BlockType.TABLE:
  185. para_content = {'type': ContentType.TABLE, 'img_path': '', BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}
  186. for block in para_block['blocks']:
  187. if block['type'] == BlockType.TABLE_BODY:
  188. for line in block['lines']:
  189. for span in line['spans']:
  190. if span['type'] == ContentType.TABLE:
  191. if span.get('html', ''):
  192. para_content[BlockType.TABLE_BODY] = f"{span['html']}"
  193. if span.get('image_path', ''):
  194. para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
  195. if block['type'] == BlockType.TABLE_CAPTION:
  196. para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
  197. if block['type'] == BlockType.TABLE_FOOTNOTE:
  198. para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_with_text(block))
  199. elif para_type == BlockType.CODE:
  200. para_content = {'type': BlockType.CODE, 'sub_type': para_block["sub_type"], BlockType.CODE_CAPTION: []}
  201. for block in para_block['blocks']:
  202. if block['type'] == BlockType.CODE_BODY:
  203. para_content[BlockType.CODE_BODY] = merge_para_with_text(block)
  204. if block['type'] == BlockType.CODE_CAPTION:
  205. para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))
  206. page_weight, page_height = page_size
  207. para_bbox = para_block.get('bbox')
  208. if para_bbox:
  209. x0, y0, x1, y1 = para_bbox
  210. para_content['bbox'] = [
  211. int(x0 * 1000 / page_weight),
  212. int(y0 * 1000 / page_height),
  213. int(x1 * 1000 / page_weight),
  214. int(y1 * 1000 / page_height),
  215. ]
  216. para_content['page_idx'] = page_idx
  217. return para_content
  218. def union_make(pdf_info_dict: list,
  219. make_mode: str,
  220. img_buket_path: str = '',
  221. ):
  222. formula_enable = get_formula_enable(os.getenv('MINERU_VLM_FORMULA_ENABLE', 'True').lower() == 'true')
  223. table_enable = get_table_enable(os.getenv('MINERU_VLM_TABLE_ENABLE', 'True').lower() == 'true')
  224. output_content = []
  225. for page_info in pdf_info_dict:
  226. paras_of_layout = page_info.get('para_blocks')
  227. paras_of_discarded = page_info.get('discarded_blocks')
  228. page_idx = page_info.get('page_idx')
  229. page_size = page_info.get('page_size')
  230. if not paras_of_layout:
  231. continue
  232. if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
  233. page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, formula_enable, table_enable, img_buket_path)
  234. output_content.extend(page_markdown)
  235. elif make_mode == MakeMode.CONTENT_LIST:
  236. for para_block in paras_of_layout+paras_of_discarded:
  237. para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)
  238. output_content.append(para_content)
  239. if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
  240. return '\n\n'.join(output_content)
  241. elif make_mode == MakeMode.CONTENT_LIST:
  242. return output_content
  243. return None
  244. def get_title_level(block):
  245. title_level = block.get('level', 1)
  246. if title_level > 4:
  247. title_level = 4
  248. elif title_level < 1:
  249. title_level = 0
  250. return title_level