vlm_middle_json_mkcontent.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. para_text += f"```{para_block["guess_lang"]}\n{merge_para_with_text(block)}\n```"
  119. elif sub_type == BlockType.ALGORITHM:
  120. para_text += merge_para_with_text(block)
  121. if para_text.strip() == '':
  122. continue
  123. else:
  124. # page_markdown.append(para_text.strip() + ' ')
  125. page_markdown.append(para_text.strip())
  126. return page_markdown
  127. def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size):
  128. para_type = para_block['type']
  129. para_content = {}
  130. if para_type in [
  131. BlockType.TEXT,
  132. BlockType.REF_TEXT,
  133. BlockType.PHONETIC,
  134. BlockType.HEADER,
  135. BlockType.FOOTER,
  136. BlockType.PAGE_NUMBER,
  137. BlockType.ASIDE_TEXT,
  138. BlockType.PAGE_FOOTNOTE,
  139. ]:
  140. para_content = {
  141. 'type': para_type,
  142. 'text': merge_para_with_text(para_block),
  143. }
  144. elif para_type == BlockType.LIST:
  145. para_content = {
  146. 'type': para_type,
  147. 'sub_type': para_block.get('sub_type', ''),
  148. 'list_items':[],
  149. }
  150. for block in para_block['blocks']:
  151. item_text = merge_para_with_text(block)
  152. if item_text.strip():
  153. para_content['list_items'].append(item_text)
  154. elif para_type == BlockType.TITLE:
  155. title_level = get_title_level(para_block)
  156. para_content = {
  157. 'type': ContentType.TEXT,
  158. 'text': merge_para_with_text(para_block),
  159. }
  160. if title_level != 0:
  161. para_content['text_level'] = title_level
  162. elif para_type == BlockType.INTERLINE_EQUATION:
  163. para_content = {
  164. 'type': ContentType.EQUATION,
  165. 'text': merge_para_with_text(para_block),
  166. 'text_format': 'latex',
  167. }
  168. elif para_type == BlockType.IMAGE:
  169. para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}
  170. for block in para_block['blocks']:
  171. if block['type'] == BlockType.IMAGE_BODY:
  172. for line in block['lines']:
  173. for span in line['spans']:
  174. if span['type'] == ContentType.IMAGE:
  175. if span.get('image_path', ''):
  176. para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
  177. if block['type'] == BlockType.IMAGE_CAPTION:
  178. para_content[BlockType.IMAGE_CAPTION].append(merge_para_with_text(block))
  179. if block['type'] == BlockType.IMAGE_FOOTNOTE:
  180. para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_with_text(block))
  181. elif para_type == BlockType.TABLE:
  182. para_content = {'type': ContentType.TABLE, 'img_path': '', BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}
  183. for block in para_block['blocks']:
  184. if block['type'] == BlockType.TABLE_BODY:
  185. for line in block['lines']:
  186. for span in line['spans']:
  187. if span['type'] == ContentType.TABLE:
  188. if span.get('html', ''):
  189. para_content[BlockType.TABLE_BODY] = f"{span['html']}"
  190. if span.get('image_path', ''):
  191. para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
  192. if block['type'] == BlockType.TABLE_CAPTION:
  193. para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
  194. if block['type'] == BlockType.TABLE_FOOTNOTE:
  195. para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_with_text(block))
  196. elif para_type == BlockType.CODE:
  197. para_content = {'type': BlockType.CODE, 'sub_type': para_block["sub_type"], BlockType.CODE_CAPTION: []}
  198. for block in para_block['blocks']:
  199. if block['type'] == BlockType.CODE_BODY:
  200. para_content[BlockType.CODE_BODY] = merge_para_with_text(block)
  201. if para_block["sub_type"] == BlockType.CODE:
  202. para_content["guess_lang"] = para_block["guess_lang"]
  203. if block['type'] == BlockType.CODE_CAPTION:
  204. para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))
  205. page_weight, page_height = page_size
  206. para_bbox = para_block.get('bbox')
  207. if para_bbox:
  208. x0, y0, x1, y1 = para_bbox
  209. para_content['bbox'] = [
  210. int(x0 * 1000 / page_weight),
  211. int(y0 * 1000 / page_height),
  212. int(x1 * 1000 / page_weight),
  213. int(y1 * 1000 / page_height),
  214. ]
  215. para_content['page_idx'] = page_idx
  216. return para_content
  217. def union_make(pdf_info_dict: list,
  218. make_mode: str,
  219. img_buket_path: str = '',
  220. ):
  221. formula_enable = get_formula_enable(os.getenv('MINERU_VLM_FORMULA_ENABLE', 'True').lower() == 'true')
  222. table_enable = get_table_enable(os.getenv('MINERU_VLM_TABLE_ENABLE', 'True').lower() == 'true')
  223. output_content = []
  224. for page_info in pdf_info_dict:
  225. paras_of_layout = page_info.get('para_blocks')
  226. paras_of_discarded = page_info.get('discarded_blocks')
  227. page_idx = page_info.get('page_idx')
  228. page_size = page_info.get('page_size')
  229. if not paras_of_layout:
  230. continue
  231. if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
  232. page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, formula_enable, table_enable, img_buket_path)
  233. output_content.extend(page_markdown)
  234. elif make_mode == MakeMode.CONTENT_LIST:
  235. for para_block in paras_of_layout+paras_of_discarded:
  236. para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)
  237. output_content.append(para_content)
  238. if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
  239. return '\n\n'.join(output_content)
  240. elif make_mode == MakeMode.CONTENT_LIST:
  241. return output_content
  242. return None
  243. def get_title_level(block):
  244. title_level = block.get('level', 1)
  245. if title_level > 4:
  246. title_level = 4
  247. elif title_level < 1:
  248. title_level = 0
  249. return title_level