vlm_middle_json_mkcontent.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. latex_delimiters_config = get_latex_delimiter_config()
  5. default_delimiters = {
  6. 'display': {'left': '$$', 'right': '$$'},
  7. 'inline': {'left': '$', 'right': '$'}
  8. }
  9. delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters
  10. display_left_delimiter = delimiters['display']['left']
  11. display_right_delimiter = delimiters['display']['right']
  12. inline_left_delimiter = delimiters['inline']['left']
  13. inline_right_delimiter = delimiters['inline']['right']
  14. def merge_para_with_text(para_block, formula_enable=True, img_buket_path=''):
  15. para_text = ''
  16. for line in para_block['lines']:
  17. for j, span in enumerate(line['spans']):
  18. span_type = span['type']
  19. content = ''
  20. if span_type == ContentType.TEXT:
  21. content = span['content']
  22. elif span_type == ContentType.INLINE_EQUATION:
  23. content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
  24. elif span_type == ContentType.INTERLINE_EQUATION:
  25. if formula_enable:
  26. content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
  27. else:
  28. if span.get('image_path', ''):
  29. content = f"![]({img_buket_path}/{span['image_path']})"
  30. # content = content.strip()
  31. if content:
  32. if span_type in [ContentType.TEXT, ContentType.INLINE_EQUATION]:
  33. if j == len(line['spans']) - 1:
  34. para_text += content
  35. else:
  36. para_text += f'{content} '
  37. elif span_type == ContentType.INTERLINE_EQUATION:
  38. para_text += content
  39. return para_text
  40. def mk_blocks_to_markdown(para_blocks, make_mode, formula_enable, table_enable, img_buket_path=''):
  41. page_markdown = []
  42. for para_block in para_blocks:
  43. para_text = ''
  44. para_type = para_block['type']
  45. if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION, BlockType.PHONETIC, BlockType.REF_TEXT]:
  46. para_text = merge_para_with_text(para_block, formula_enable=formula_enable, img_buket_path=img_buket_path)
  47. elif para_type == BlockType.LIST:
  48. for block in para_block['blocks']:
  49. item_text = merge_para_with_text(block, formula_enable=formula_enable, img_buket_path=img_buket_path)
  50. para_text += f"{item_text}\n"
  51. elif para_type == BlockType.TITLE:
  52. title_level = get_title_level(para_block)
  53. para_text = f'{"#" * title_level} {merge_para_with_text(para_block)}'
  54. elif para_type == BlockType.IMAGE:
  55. if make_mode == MakeMode.NLP_MD:
  56. continue
  57. elif make_mode == MakeMode.MM_MD:
  58. # 检测是否存在图片脚注
  59. has_image_footnote = any(block['type'] == BlockType.IMAGE_FOOTNOTE for block in para_block['blocks'])
  60. # 如果存在图片脚注,则将图片脚注拼接到图片正文后面
  61. if has_image_footnote:
  62. for block in para_block['blocks']: # 1st.拼image_caption
  63. if block['type'] == BlockType.IMAGE_CAPTION:
  64. para_text += merge_para_with_text(block) + ' \n'
  65. for block in para_block['blocks']: # 2nd.拼image_body
  66. if block['type'] == BlockType.IMAGE_BODY:
  67. for line in block['lines']:
  68. for span in line['spans']:
  69. if span['type'] == ContentType.IMAGE:
  70. if span.get('image_path', ''):
  71. para_text += f"![]({img_buket_path}/{span['image_path']})"
  72. for block in para_block['blocks']: # 3rd.拼image_footnote
  73. if block['type'] == BlockType.IMAGE_FOOTNOTE:
  74. para_text += ' \n' + merge_para_with_text(block)
  75. else:
  76. for block in para_block['blocks']: # 1st.拼image_body
  77. if block['type'] == BlockType.IMAGE_BODY:
  78. for line in block['lines']:
  79. for span in line['spans']:
  80. if span['type'] == ContentType.IMAGE:
  81. if span.get('image_path', ''):
  82. para_text += f"![]({img_buket_path}/{span['image_path']})"
  83. for block in para_block['blocks']: # 2nd.拼image_caption
  84. if block['type'] == BlockType.IMAGE_CAPTION:
  85. para_text += ' \n' + merge_para_with_text(block)
  86. elif para_type == BlockType.TABLE:
  87. if make_mode == MakeMode.NLP_MD:
  88. continue
  89. elif make_mode == MakeMode.MM_MD:
  90. for block in para_block['blocks']: # 1st.拼table_caption
  91. if block['type'] == BlockType.TABLE_CAPTION:
  92. para_text += merge_para_with_text(block) + ' \n'
  93. for block in para_block['blocks']: # 2nd.拼table_body
  94. if block['type'] == BlockType.TABLE_BODY:
  95. for line in block['lines']:
  96. for span in line['spans']:
  97. if span['type'] == ContentType.TABLE:
  98. # if processed by table model
  99. if table_enable:
  100. if span.get('html', ''):
  101. para_text += f"\n{span['html']}\n"
  102. elif span.get('image_path', ''):
  103. para_text += f"![]({img_buket_path}/{span['image_path']})"
  104. else:
  105. if span.get('image_path', ''):
  106. para_text += f"![]({img_buket_path}/{span['image_path']})"
  107. for block in para_block['blocks']: # 3rd.拼table_footnote
  108. if block['type'] == BlockType.TABLE_FOOTNOTE:
  109. para_text += '\n' + merge_para_with_text(block) + ' '
  110. elif para_type == BlockType.CODE:
  111. sub_type = para_block["sub_type"]
  112. for block in para_block['blocks']: # 1st.拼code_caption
  113. if block['type'] == BlockType.CODE_CAPTION:
  114. para_text += merge_para_with_text(block) + ' \n'
  115. for block in para_block['blocks']: # 2nd.拼code_body
  116. if block['type'] == BlockType.CODE_BODY:
  117. if sub_type == BlockType.CODE:
  118. guess_lang = para_block["guess_lang"]
  119. para_text += f"```{guess_lang}\n{merge_para_with_text(block)}\n```"
  120. elif sub_type == BlockType.ALGORITHM:
  121. para_text += merge_para_with_text(block)
  122. if para_text.strip() == '':
  123. continue
  124. else:
  125. # page_markdown.append(para_text.strip() + ' ')
  126. page_markdown.append(para_text.strip())
  127. return page_markdown
  128. def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size):
  129. para_type = para_block['type']
  130. para_content = {}
  131. if para_type in [
  132. BlockType.TEXT,
  133. BlockType.REF_TEXT,
  134. BlockType.PHONETIC,
  135. BlockType.HEADER,
  136. BlockType.FOOTER,
  137. BlockType.PAGE_NUMBER,
  138. BlockType.ASIDE_TEXT,
  139. BlockType.PAGE_FOOTNOTE,
  140. ]:
  141. para_content = {
  142. 'type': para_type,
  143. 'text': merge_para_with_text(para_block),
  144. }
  145. elif para_type == BlockType.LIST:
  146. para_content = {
  147. 'type': para_type,
  148. 'sub_type': para_block.get('sub_type', ''),
  149. 'list_items':[],
  150. }
  151. for block in para_block['blocks']:
  152. item_text = merge_para_with_text(block)
  153. if item_text.strip():
  154. para_content['list_items'].append(item_text)
  155. elif para_type == BlockType.TITLE:
  156. title_level = get_title_level(para_block)
  157. para_content = {
  158. 'type': ContentType.TEXT,
  159. 'text': merge_para_with_text(para_block),
  160. }
  161. if title_level != 0:
  162. para_content['text_level'] = title_level
  163. elif para_type == BlockType.INTERLINE_EQUATION:
  164. para_content = {
  165. 'type': ContentType.EQUATION,
  166. 'text': merge_para_with_text(para_block),
  167. 'text_format': 'latex',
  168. }
  169. elif para_type == BlockType.IMAGE:
  170. para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}
  171. for block in para_block['blocks']:
  172. if block['type'] == BlockType.IMAGE_BODY:
  173. for line in block['lines']:
  174. for span in line['spans']:
  175. if span['type'] == ContentType.IMAGE:
  176. if span.get('image_path', ''):
  177. para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
  178. if block['type'] == BlockType.IMAGE_CAPTION:
  179. para_content[BlockType.IMAGE_CAPTION].append(merge_para_with_text(block))
  180. if block['type'] == BlockType.IMAGE_FOOTNOTE:
  181. para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_with_text(block))
  182. elif para_type == BlockType.TABLE:
  183. para_content = {'type': ContentType.TABLE, 'img_path': '', BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}
  184. for block in para_block['blocks']:
  185. if block['type'] == BlockType.TABLE_BODY:
  186. for line in block['lines']:
  187. for span in line['spans']:
  188. if span['type'] == ContentType.TABLE:
  189. if span.get('html', ''):
  190. para_content[BlockType.TABLE_BODY] = f"{span['html']}"
  191. if span.get('image_path', ''):
  192. para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
  193. if block['type'] == BlockType.TABLE_CAPTION:
  194. para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
  195. if block['type'] == BlockType.TABLE_FOOTNOTE:
  196. para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_with_text(block))
  197. elif para_type == BlockType.CODE:
  198. para_content = {'type': BlockType.CODE, 'sub_type': para_block["sub_type"], BlockType.CODE_CAPTION: []}
  199. for block in para_block['blocks']:
  200. if block['type'] == BlockType.CODE_BODY:
  201. para_content[BlockType.CODE_BODY] = merge_para_with_text(block)
  202. if para_block["sub_type"] == BlockType.CODE:
  203. para_content["guess_lang"] = para_block["guess_lang"]
  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