Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: enhance DOCX processing by adding support for office file types and refactoring related functions

myhloli0cbe965d97fb
diff --git a/demo/demo.py b/demo/demo.py
index 14c075c5..02668f17 100644
--- a/demo/demo.py
+++ b/demo/demo.py
@@ -6,7 +6,8 @@ from pathlib import Path
from loguru import logger
-from mineru.cli.common import convert_pdf_bytes_to_bytes_by_pypdfium2, prepare_env, read_fn, _process_office_doc
+from mineru.cli.common import convert_pdf_bytes_to_bytes_by_pypdfium2, prepare_env, read_fn, pptx_suffixes, \
+ xlsx_suffixes, pdf_suffixes, image_suffixes, office_suffixes, docx_suffixes
from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox
from mineru.utils.engine_utils import get_vlm_engine
@@ -17,7 +18,9 @@ from mineru.backend.pipeline.pipeline_middle_json_mkcontent import union_make as
from mineru.backend.pipeline.model_json_to_middle_json import result_to_middle_json as pipeline_result_to_middle_json
from mineru.backend.vlm.vlm_middle_json_mkcontent import union_make as vlm_union_make
from mineru.backend.hybrid.hybrid_analyze import doc_analyze as hybrid_doc_analyze
-from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
+from mineru.backend.office.office_middle_json_mkcontent import union_make as office_union_make
+from mineru.backend.office.docx_analyze import office_docx_analyze
+from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path, guess_suffix_by_bytes
def do_parse(
@@ -41,10 +44,16 @@ def do_parse(
start_page_id=0, # Start page ID for parsing, default is 0
end_page_id=None, # End page ID for parsing, default is None (parse all pages until the end of the document)
):
-
need_remove_index = _process_office_doc(
output_dir,
- pdf_bytes_list,
+ pdf_file_names=pdf_file_names,
+ pdf_bytes_list=pdf_bytes_list,
+ f_dump_md=f_dump_md,
+ f_dump_middle_json=f_dump_middle_json,
+ f_dump_model_output=f_dump_model_output,
+ f_dump_orig_file=f_dump_orig_pdf,
+ f_dump_content_list=f_dump_content_list,
+ f_make_md_mode=f_make_md_mode,
)
for index in sorted(need_remove_index, reverse=True):
del pdf_bytes_list[index]
@@ -80,7 +89,7 @@ def do_parse(
pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
- f_make_md_mode, middle_json, model_json, is_pipeline=True
+ f_make_md_mode, middle_json, model_json, process_mode="pipeline"
)
else:
f_draw_span_bbox = False
@@ -105,7 +114,7 @@ def do_parse(
pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
- f_make_md_mode, middle_json, infer_result, is_pipeline=False
+ f_make_md_mode, middle_json, infer_result, process_mode="vlm"
)
elif backend.startswith("hybrid-"):
backend = backend[7:]
@@ -135,9 +144,56 @@ def do_parse(
pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
- f_make_md_mode, middle_json, infer_result, is_pipeline=False
+ f_make_md_mode, middle_json, infer_result, process_mode="vlm"
)
+
+def _process_office_doc(
+ output_dir,
+ pdf_file_names: list[str],
+ pdf_bytes_list: list[bytes],
+ f_dump_md=True,
+ f_dump_middle_json=True,
+ f_dump_model_output=True,
+ f_dump_orig_file=True,
+ f_dump_content_list=True,
+ f_make_md_mode=MakeMode.MM_MD,
+):
+ need_remove_index = []
+ for i, file_bytes in enumerate(pdf_bytes_list):
+ pdf_file_name = pdf_file_names[i]
+ file_suffix = guess_suffix_by_bytes(file_bytes)
+ if file_suffix in docx_suffixes:
+
+ need_remove_index.append(i)
+
+ local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"office")
+ image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)
+ middle_json, infer_result = office_docx_analyze(
+ file_bytes,
+ image_writer=image_writer,
+ )
+
+ f_draw_layout_bbox = False
+ f_draw_span_bbox = False
+ pdf_info = middle_json["pdf_info"]
+
+ _process_output(
+ pdf_info, file_bytes, pdf_file_name, local_md_dir, local_image_dir,
+ md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_file,
+ f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
+ f_make_md_mode, middle_json, infer_result, process_mode="docx"
+ )
+ elif file_suffix in pptx_suffixes:
+ need_remove_index.append(i)
+ logger.warning(f"Currently, PPTX files are not supported: {pdf_file_name}")
+ elif file_suffix in xlsx_suffixes:
+ need_remove_index.append(i)
+ logger.warning(f"Currently, XLSX files are not supported: {pdf_file_name}")
+
+ return need_remove_index
+
+
def _process_output(
pdf_info,
pdf_bytes,
@@ -155,8 +211,18 @@ def _process_output(
f_make_md_mode,
middle_json,
model_output=None,
- is_pipeline=True
+ process_mode="vlm"
):
+
+ if process_mode == "pipeline":
+ make_func = pipeline_union_make
+ elif process_mode == "vlm":
+ make_func = vlm_union_make
+ elif process_mode == "office":
+ make_func = office_union_make
+ else:
+ raise Exception(f"Unknown process_mode: {process_mode}")
+
"""处理输出文件"""
if f_draw_layout_bbox:
draw_layout_bbox(pdf_info, pdf_bytes, local_md_dir, f"{pdf_file_name}_layout.pdf")
@@ -165,15 +231,20 @@ def _process_output(
draw_span_bbox(pdf_info, pdf_bytes, local_md_dir, f"{pdf_file_name}_span.pdf")
if f_dump_orig_pdf:
- md_writer.write(
- f"{pdf_file_name}_origin.pdf",
- pdf_bytes,
- )
+ if process_mode in ["pipeline", "vlm"]:
+ md_writer.write(
+ f"{pdf_file_name}_origin.pdf",
+ pdf_bytes,
+ )
+ elif process_mode in office_suffixes:
+ md_writer.write(
+ f"{pdf_file_name}_origin.{process_mode}",
+ pdf_bytes,
+ )
image_dir = str(os.path.basename(local_image_dir))
if f_dump_md:
- make_func = pipeline_union_make if is_pipeline else vlm_union_make
md_content_str = make_func(pdf_info, f_make_md_mode, image_dir)
md_writer.write_string(
f"{pdf_file_name}.md",
@@ -181,13 +252,19 @@ def _process_output(
)
if f_dump_content_list:
- make_func = pipeline_union_make if is_pipeline else vlm_union_make
content_list = make_func(pdf_info, MakeMode.CONTENT_LIST, image_dir)
md_writer.write_string(
f"{pdf_file_name}_content_list.json",
json.dumps(content_list, ensure_ascii=False, indent=4),
)
+ if process_mode != "pipeline":
+ content_list_v2 = make_func(pdf_info, MakeMode.CONTENT_LIST_V2, image_dir)
+ md_writer.write_string(
+ f"{pdf_file_name}_content_list_v2.json",
+ json.dumps(content_list_v2, ensure_ascii=False, indent=4),
+ )
+
if f_dump_middle_json:
md_writer.write_string(
f"{pdf_file_name}_middle.json",
@@ -268,13 +345,10 @@ if __name__ == '__main__':
__dir__ = os.path.dirname(os.path.abspath(__file__))
pdf_files_dir = os.path.join(__dir__, "docx")
output_dir = os.path.join(__dir__, "output")
- pdf_suffixes = ["pdf"]
- docx_suffixes = ["docx"]
- image_suffixes = ["png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg"]
doc_path_list = []
for doc_path in Path(pdf_files_dir).glob('*'):
- if guess_suffix_by_path(doc_path) in pdf_suffixes + image_suffixes + docx_suffixes:
+ if guess_suffix_by_path(doc_path) in pdf_suffixes + image_suffixes + office_suffixes:
doc_path_list.append(doc_path)
"""如果您由于网络问题无法下载模型,可以设置环境变量MINERU_MODEL_SOURCE为modelscope使用免代理仓库下载模型"""
diff --git a/mineru/backend/office/docx.py b/mineru/backend/office/docx.py
deleted file mode 100644
index 1e17167c..00000000
--- a/mineru/backend/office/docx.py
+++ /dev/null
@@ -1 +0,0 @@
-# Copyright (c) Opendatalab. All rights reserved.
diff --git a/mineru/backend/office/docx_analyze.py b/mineru/backend/office/docx_analyze.py
new file mode 100644
index 00000000..3a4a1ee9
--- /dev/null
+++ b/mineru/backend/office/docx_analyze.py
@@ -0,0 +1,28 @@
+# Copyright (c) Opendatalab. All rights reserved.
+import time
+from io import BytesIO
+
+from loguru import logger
+
+from mineru.model.docx.main import convert_binary
+
+
+def office_docx_analyze(
+ file_bytes,
+ image_writer=None
+):
+ infer_start = time.time()
+
+ file_stream = BytesIO(file_bytes)
+ results = convert_binary(file_stream)
+
+ infer_time = round(time.time() - infer_start, 2)
+ logger.debug(f"infer finished, cost: {infer_time}, speed: {round(len(results) / infer_time, 3)} page/s")
+
+ # middle_json = result_to_middle_json(
+ # results,
+ # image_writer,
+ # )
+ middle_json= []
+
+ return middle_json, results
\ No newline at end of file
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.py
new file mode 100644
index 00000000..0c66a6d9
--- /dev/null
+++ b/mineru/backend/office/model_output_to_middle_json.py
@@ -0,0 +1,123 @@
+import os
+import time
+
+import cv2
+import numpy as np
+from loguru import logger
+
+from mineru.backend.utils import cross_page_table_merge
+from mineru.backend.vlm.vlm_magic_model import MagicModel
+from mineru.utils.config_reader import get_table_enable, get_llm_aided_config
+from mineru.utils.cut_image import cut_image_and_table
+from mineru.utils.enum_class import ContentType
+from mineru.utils.hash_utils import bytes_md5
+from mineru.utils.pdf_image_tools import get_crop_img
+from mineru.version import __version__
+
+
+heading_level_import_success = False
+llm_aided_config = get_llm_aided_config()
+if llm_aided_config:
+ title_aided_config = llm_aided_config.get('title_aided', {})
+ if title_aided_config.get('enable', False):
+ try:
+ from mineru.utils.llm_aided import llm_aided_title
+ from mineru.backend.pipeline.model_init import AtomModelSingleton
+ heading_level_import_success = True
+ except Exception as e:
+ logger.warning("The heading level feature cannot be used. If you need to use the heading level feature, "
+ "please execute `pip install mineru[core]` to install the required packages.")
+
+
+def blocks_to_page_info(page_blocks, image_dict, page, image_writer, page_index) -> dict:
+ """将blocks转换为页面信息"""
+
+ scale = image_dict["scale"]
+ # page_pil_img = image_dict["img_pil"]
+ page_pil_img = image_dict["img_pil"]
+ page_img_md5 = bytes_md5(page_pil_img.tobytes())
+ width, height = map(int, page.get_size())
+
+ magic_model = MagicModel(page_blocks, width, height)
+ image_blocks = magic_model.get_image_blocks()
+ table_blocks = magic_model.get_table_blocks()
+ title_blocks = magic_model.get_title_blocks()
+ discarded_blocks = magic_model.get_discarded_blocks()
+ code_blocks = magic_model.get_code_blocks()
+ ref_text_blocks = magic_model.get_ref_text_blocks()
+ phonetic_blocks = magic_model.get_phonetic_blocks()
+ list_blocks = magic_model.get_list_blocks()
+
+ # 如果有标题优化需求,则对title_blocks截图det
+ if heading_level_import_success:
+ atom_model_manager = AtomModelSingleton()
+ ocr_model = atom_model_manager.get_atom_model(
+ atom_model_name='ocr',
+ ocr_show_log=False,
+ det_db_box_thresh=0.3,
+ lang='ch_lite'
+ )
+ for title_block in title_blocks:
+ title_pil_img = get_crop_img(title_block['bbox'], page_pil_img, scale)
+ title_np_img = np.array(title_pil_img)
+ # 给title_pil_img添加上下左右各50像素白边padding
+ title_np_img = cv2.copyMakeBorder(
+ title_np_img, 50, 50, 50, 50, cv2.BORDER_CONSTANT, value=[255, 255, 255]
+ )
+ title_img = cv2.cvtColor(title_np_img, cv2.COLOR_RGB2BGR)
+ ocr_det_res = ocr_model.ocr(title_img, rec=False)[0]
+ if len(ocr_det_res) > 0:
+ # 计算所有res的平均高度
+ avg_height = np.mean([box[2][1] - box[0][1] for box in ocr_det_res])
+ title_block['line_avg_height'] = round(avg_height/scale)
+
+ text_blocks = magic_model.get_text_blocks()
+ interline_equation_blocks = magic_model.get_interline_equation_blocks()
+
+ all_spans = magic_model.get_all_spans()
+ # 对image/table/interline_equation的span截图
+ for span in all_spans:
+ if span["type"] in [ContentType.IMAGE, ContentType.TABLE, ContentType.INTERLINE_EQUATION]:
+ span = cut_image_and_table(span, page_pil_img, page_img_md5, page_index, image_writer, scale=scale)
+
+ page_blocks = []
+ page_blocks.extend([
+ *image_blocks,
+ *table_blocks,
+ *code_blocks,
+ *ref_text_blocks,
+ *phonetic_blocks,
+ *title_blocks,
+ *text_blocks,
+ *interline_equation_blocks,
+ *list_blocks,
+ ])
+ # 对page_blocks根据index的值进行排序
+ page_blocks.sort(key=lambda x: x["index"])
+
+ page_info = {"para_blocks": page_blocks, "discarded_blocks": discarded_blocks, "page_size": [width, height], "page_idx": page_index}
+ return page_info
+
+
+def result_to_middle_json(model_output_blocks_list, images_list, pdf_doc, image_writer):
+ middle_json = {"pdf_info": [], "_backend":"vlm", "_version_name": __version__}
+ for index, page_blocks in enumerate(model_output_blocks_list):
+ page = pdf_doc[index]
+ image_dict = images_list[index]
+ page_info = blocks_to_page_info(page_blocks, image_dict, page, image_writer, index)
+ middle_json["pdf_info"].append(page_info)
+
+ """表格跨页合并"""
+ table_enable = get_table_enable(os.getenv('MINERU_VLM_TABLE_ENABLE', 'True').lower() == 'true')
+ if table_enable:
+ cross_page_table_merge(middle_json["pdf_info"])
+
+ """llm优化标题分级"""
+ if heading_level_import_success:
+ llm_aided_title_start_time = time.time()
+ llm_aided_title(middle_json["pdf_info"], title_aided_config)
+ logger.info(f'llm aided title time: {round(time.time() - llm_aided_title_start_time, 2)}')
+
+ # 关闭pdf文档
+ pdf_doc.close()
+ return middle_json
\ No newline at end of file
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.py
new file mode 100644
index 00000000..c081cd6f
--- /dev/null
+++ b/mineru/backend/office/office_middle_json_mkcontent.py
@@ -0,0 +1,658 @@
+import os
+
+from loguru import logger
+
+from mineru.utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end
+from mineru.utils.config_reader import get_latex_delimiter_config, get_formula_enable, get_table_enable
+from mineru.utils.enum_class import MakeMode, BlockType, ContentType, ContentTypeV2
+from mineru.utils.language import detect_lang
+
+latex_delimiters_config = get_latex_delimiter_config()
+
+default_delimiters = {
+ 'display': {'left': '$$', 'right': '$$'},
+ 'inline': {'left': '$', 'right': '$'}
+}
+
+delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters
+
+display_left_delimiter = delimiters['display']['left']
+display_right_delimiter = delimiters['display']['right']
+inline_left_delimiter = delimiters['inline']['left']
+inline_right_delimiter = delimiters['inline']['right']
+
+
+def merge_para_with_text(para_block, formula_enable=True, img_buket_path=''):
+ block_text = ''
+ for line in para_block['lines']:
+ for span in line['spans']:
+ if span['type'] in [ContentType.TEXT]:
+ span['content'] = full_to_half_exclude_marks(span['content'])
+ block_text += span['content']
+ block_lang = detect_lang(block_text)
+
+ para_text = ''
+ for i, line in enumerate(para_block['lines']):
+ for j, span in enumerate(line['spans']):
+ span_type = span['type']
+ content = ''
+ if span_type == ContentType.TEXT:
+ content = span['content']
+ elif span_type == ContentType.INLINE_EQUATION:
+ content = f"{inline_left_delimiter}{span['content']}{inline_right_delimiter}"
+ elif span_type == ContentType.INTERLINE_EQUATION:
+ if formula_enable:
+ content = f"\n{display_left_delimiter}\n{span['content']}\n{display_right_delimiter}\n"
+ else:
+ if span.get('image_path', ''):
+ content = f"![]({img_buket_path}/{span['image_path']})"
+
+ content = content.strip()
+ if content:
+
+ if span_type == ContentType.INTERLINE_EQUATION:
+ para_text += content
+ continue
+
+ # 定义CJK语言集合(中日韩)
+ cjk_langs = {'zh', 'ja', 'ko'}
+ # logger.info(f'block_lang: {block_lang}, content: {content}')
+
+ # 判断是否为行末span
+ is_last_span = j == len(line['spans']) - 1
+
+ if block_lang in cjk_langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
+ if is_last_span and span_type != ContentType.INLINE_EQUATION:
+ para_text += content
+ else:
+ para_text += f'{content} '
+ else:
+ # 西方文本语境下 每行的最后一个span判断是否要去除连字符
+ if span_type in [ContentType.TEXT, ContentType.INLINE_EQUATION]:
+ # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
+ if (
+ is_last_span
+ and span_type == ContentType.TEXT
+ and is_hyphen_at_line_end(content)
+ ):
+ # 如果下一行的第一个span是小写字母开头,删除连字符
+ if (
+ i+1 < len(para_block['lines'])
+ and para_block['lines'][i + 1].get('spans')
+ and para_block['lines'][i + 1]['spans'][0].get('type') == ContentType.TEXT
+ and para_block['lines'][i + 1]['spans'][0].get('content', '')
+ and para_block['lines'][i + 1]['spans'][0]['content'][0].islower()
+ ):
+ para_text += content[:-1]
+ else: # 如果没有下一行,或者下一行的第一个span不是小写字母开头,则保留连字符但不加空格
+ para_text += content
+ else: # 西方文本语境下 content间需要空格分隔
+ para_text += f'{content} '
+ return para_text
+
+
+def mk_blocks_to_markdown(para_blocks, make_mode, formula_enable, table_enable, img_buket_path=''):
+ page_markdown = []
+ for para_block in para_blocks:
+ para_text = ''
+ para_type = para_block['type']
+ if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION, BlockType.PHONETIC, BlockType.REF_TEXT]:
+ para_text = merge_para_with_text(para_block, formula_enable=formula_enable, img_buket_path=img_buket_path)
+ elif para_type == BlockType.LIST:
+ for block in para_block['blocks']:
+ item_text = merge_para_with_text(block, formula_enable=formula_enable, img_buket_path=img_buket_path)
+ para_text += f"{item_text} \n"
+ elif para_type == BlockType.TITLE:
+ title_level = get_title_level(para_block)
+ para_text = f'{"#" * title_level} {merge_para_with_text(para_block)}'
+ elif para_type == BlockType.IMAGE:
+ if make_mode == MakeMode.NLP_MD:
+ continue
+ elif make_mode == MakeMode.MM_MD:
+ # 检测是否存在图片脚注
+ has_image_footnote = any(block['type'] == BlockType.IMAGE_FOOTNOTE for block in para_block['blocks'])
+ # 如果存在图片脚注,则将图片脚注拼接到图片正文后面
+ if has_image_footnote:
+ for block in para_block['blocks']: # 1st.拼image_caption
+ if block['type'] == BlockType.IMAGE_CAPTION:
+ para_text += merge_para_with_text(block) + ' \n'
+ for block in para_block['blocks']: # 2nd.拼image_body
+ if block['type'] == BlockType.IMAGE_BODY:
+ for line in block['lines']:
+ for span in line['spans']:
+ if span['type'] == ContentType.IMAGE:
+ if span.get('image_path', ''):
+ para_text += f"![]({img_buket_path}/{span['image_path']})"
+ for block in para_block['blocks']: # 3rd.拼image_footnote
+ if block['type'] == BlockType.IMAGE_FOOTNOTE:
+ para_text += ' \n' + merge_para_with_text(block)
+ else:
+ for block in para_block['blocks']: # 1st.拼image_body
+ if block['type'] == BlockType.IMAGE_BODY:
+ for line in block['lines']:
+ for span in line['spans']:
+ if span['type'] == ContentType.IMAGE:
+ if span.get('image_path', ''):
+ para_text += f"![]({img_buket_path}/{span['image_path']})"
+ for block in para_block['blocks']: # 2nd.拼image_caption
+ if block['type'] == BlockType.IMAGE_CAPTION:
+ para_text += ' \n' + merge_para_with_text(block)
+
+ elif para_type == BlockType.TABLE:
+ if make_mode == MakeMode.NLP_MD:
+ continue
+ elif make_mode == MakeMode.MM_MD:
+ for block in para_block['blocks']: # 1st.拼table_caption
+ if block['type'] == BlockType.TABLE_CAPTION:
+ para_text += merge_para_with_text(block) + ' \n'
+ for block in para_block['blocks']: # 2nd.拼table_body
+ if block['type'] == BlockType.TABLE_BODY:
+ for line in block['lines']:
+ for span in line['spans']:
+ if span['type'] == ContentType.TABLE:
+ # if processed by table model
+ if table_enable:
+ if span.get('html', ''):
+ para_text += f"\n{span['html']}\n"
+ elif span.get('image_path', ''):
+ para_text += f"![]({img_buket_path}/{span['image_path']})"
+ else:
+ if span.get('image_path', ''):
+ para_text += f"![]({img_buket_path}/{span['image_path']})"
+ for block in para_block['blocks']: # 3rd.拼table_footnote
+ if block['type'] == BlockType.TABLE_FOOTNOTE:
+ para_text += '\n' + merge_para_with_text(block) + ' '
+ elif para_type == BlockType.CODE:
+ sub_type = para_block["sub_type"]
+ for block in para_block['blocks']: # 1st.拼code_caption
+ if block['type'] == BlockType.CODE_CAPTION:
+ para_text += merge_para_with_text(block) + ' \n'
+ for block in para_block['blocks']: # 2nd.拼code_body
+ if block['type'] == BlockType.CODE_BODY:
+ if sub_type == BlockType.CODE:
+ guess_lang = para_block["guess_lang"]
+ para_text += f"```{guess_lang}\n{merge_para_with_text(block)}\n```"
+ elif sub_type == BlockType.ALGORITHM:
+ para_text += merge_para_with_text(block)
+
+ if para_text.strip() == '':
+ continue
+ else:
+ # page_markdown.append(para_text.strip() + ' ')
+ page_markdown.append(para_text.strip())
+
+ return page_markdown
+
+
+def make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size):
+ para_type = para_block['type']
+ para_content = {}
+ if para_type in [
+ BlockType.TEXT,
+ BlockType.REF_TEXT,
+ BlockType.PHONETIC,
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.PAGE_NUMBER,
+ BlockType.ASIDE_TEXT,
+ BlockType.PAGE_FOOTNOTE,
+ ]:
+ para_content = {
+ 'type': para_type,
+ 'text': merge_para_with_text(para_block),
+ }
+ elif para_type == BlockType.LIST:
+ para_content = {
+ 'type': para_type,
+ 'sub_type': para_block.get('sub_type', ''),
+ 'list_items':[],
+ }
+ for block in para_block['blocks']:
+ item_text = merge_para_with_text(block)
+ if item_text.strip():
+ para_content['list_items'].append(item_text)
+ elif para_type == BlockType.TITLE:
+ title_level = get_title_level(para_block)
+ para_content = {
+ 'type': ContentType.TEXT,
+ 'text': merge_para_with_text(para_block),
+ }
+ if title_level != 0:
+ para_content['text_level'] = title_level
+ elif para_type == BlockType.INTERLINE_EQUATION:
+ para_content = {
+ 'type': ContentType.EQUATION,
+ 'text': merge_para_with_text(para_block),
+ 'text_format': 'latex',
+ }
+ elif para_type == BlockType.IMAGE:
+ para_content = {'type': ContentType.IMAGE, 'img_path': '', BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}
+ for block in para_block['blocks']:
+ if block['type'] == BlockType.IMAGE_BODY:
+ for line in block['lines']:
+ for span in line['spans']:
+ if span['type'] == ContentType.IMAGE:
+ if span.get('image_path', ''):
+ para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
+ if block['type'] == BlockType.IMAGE_CAPTION:
+ para_content[BlockType.IMAGE_CAPTION].append(merge_para_with_text(block))
+ if block['type'] == BlockType.IMAGE_FOOTNOTE:
+ para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_with_text(block))
+ elif para_type == BlockType.TABLE:
+ para_content = {'type': ContentType.TABLE, 'img_path': '', BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}
+ for block in para_block['blocks']:
+ if block['type'] == BlockType.TABLE_BODY:
+ for line in block['lines']:
+ for span in line['spans']:
+ if span['type'] == ContentType.TABLE:
+
+ if span.get('html', ''):
+ para_content[BlockType.TABLE_BODY] = f"{span['html']}"
+
+ if span.get('image_path', ''):
+ para_content['img_path'] = f"{img_buket_path}/{span['image_path']}"
+
+ if block['type'] == BlockType.TABLE_CAPTION:
+ para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))
+ if block['type'] == BlockType.TABLE_FOOTNOTE:
+ para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_with_text(block))
+ elif para_type == BlockType.CODE:
+ para_content = {'type': BlockType.CODE, 'sub_type': para_block["sub_type"], BlockType.CODE_CAPTION: []}
+ for block in para_block['blocks']:
+ if block['type'] == BlockType.CODE_BODY:
+ para_content[BlockType.CODE_BODY] = merge_para_with_text(block)
+ if para_block["sub_type"] == BlockType.CODE:
+ para_content["guess_lang"] = para_block["guess_lang"]
+ if block['type'] == BlockType.CODE_CAPTION:
+ para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))
+
+ page_width, page_height = page_size
+ para_bbox = para_block.get('bbox')
+ if para_bbox:
+ x0, y0, x1, y1 = para_bbox
+ para_content['bbox'] = [
+ int(x0 * 1000 / page_width),
+ int(y0 * 1000 / page_height),
+ int(x1 * 1000 / page_width),
+ int(y1 * 1000 / page_height),
+ ]
+
+ para_content['page_idx'] = page_idx
+
+ return para_content
+
+
+def make_blocks_to_content_list_v2(para_block, img_buket_path, page_size):
+ para_type = para_block['type']
+ para_content = {}
+ if para_type in [
+ BlockType.HEADER,
+ BlockType.FOOTER,
+ BlockType.ASIDE_TEXT,
+ BlockType.PAGE_NUMBER,
+ BlockType.PAGE_FOOTNOTE,
+ ]:
+ if para_type == BlockType.HEADER:
+ content_type = ContentTypeV2.PAGE_HEADER
+ elif para_type == BlockType.FOOTER:
+ content_type = ContentTypeV2.PAGE_FOOTER
+ elif para_type == BlockType.ASIDE_TEXT:
+ content_type = ContentTypeV2.PAGE_ASIDE_TEXT
+ elif para_type == BlockType.PAGE_NUMBER:
+ content_type = ContentTypeV2.PAGE_NUMBER
+ elif para_type == BlockType.PAGE_FOOTNOTE:
+ content_type = ContentTypeV2.PAGE_FOOTNOTE
+ else:
+ raise ValueError(f"Unknown para_type: {para_type}")
+ para_content = {
+ 'type': content_type,
+ 'content': {
+ f"{content_type}_content": merge_para_with_text_v2(para_block),
+ }
+ }
+ elif para_type == BlockType.TITLE:
+ title_level = get_title_level(para_block)
+ if title_level != 0:
+ para_content = {
+ 'type': ContentTypeV2.TITLE,
+ 'content': {
+ "title_content": merge_para_with_text_v2(para_block),
+ "level": title_level
+ }
+ }
+ else:
+ para_content = {
+ 'type': ContentTypeV2.PARAGRAPH,
+ 'content': {
+ "paragraph_content": merge_para_with_text_v2(para_block),
+ }
+ }
+ elif para_type in [
+ BlockType.TEXT,
+ BlockType.PHONETIC
+ ]:
+ para_content = {
+ 'type': ContentTypeV2.PARAGRAPH,
+ 'content': {
+ 'paragraph_content': merge_para_with_text_v2(para_block),
+ }
+ }
+ elif para_type == BlockType.INTERLINE_EQUATION:
+ image_path, math_content = get_body_data(para_block)
+ para_content = {
+ 'type': ContentTypeV2.EQUATION_INTERLINE,
+ 'content': {
+ 'math_content': math_content,
+ 'math_type': 'latex',
+ 'image_source': {'path': f"{img_buket_path}/{image_path}"},
+ }
+ }
+ elif para_type == BlockType.IMAGE:
+ image_caption = []
+ image_footnote = []
+ image_path, _ = get_body_data(para_block)
+ image_source = {
+ 'path': f"{img_buket_path}/{image_path}",
+ }
+ for block in para_block['blocks']:
+ if block['type'] == BlockType.IMAGE_CAPTION:
+ image_caption.extend(merge_para_with_text_v2(block))
+ if block['type'] == BlockType.IMAGE_FOOTNOTE:
+ image_footnote.extend(merge_para_with_text_v2(block))
+ para_content = {
+ 'type': ContentTypeV2.IMAGE,
+ 'content': {
+ 'image_source': image_source,
+ 'image_caption': image_caption,
+ 'image_footnote': image_footnote,
+ }
+ }
+ elif para_type == BlockType.TABLE:
+ table_caption = []
+ table_footnote = []
+ image_path, html = get_body_data(para_block)
+ image_source = {
+ 'path': f"{img_buket_path}/{image_path}",
+ }
+ if html.count("<table") > 1:
+ table_nest_level = 2
+ else:
+ table_nest_level = 1
+ if (
+ "colspan" in html or
+ "rowspan" in html or
+ table_nest_level > 1
+ ):
+ table_type = ContentTypeV2.TABLE_COMPLEX
+ else:
+ table_type = ContentTypeV2.TABLE_SIMPLE
+
+ for block in para_block['blocks']:
+ if block['type'] == BlockType.TABLE_CAPTION:
+ table_caption.extend(merge_para_with_text_v2(block))
+ if block['type'] == BlockType.TABLE_FOOTNOTE:
+ table_footnote.extend(merge_para_with_text_v2(block))
+ para_content = {
+ 'type': ContentTypeV2.TABLE,
+ 'content': {
+ 'image_source': image_source,
+ 'table_caption': table_caption,
+ 'table_footnote': table_footnote,
+ 'html': html,
+ 'table_type': table_type,
+ 'table_nest_level': table_nest_level,
+ }
+ }
+ elif para_type == BlockType.CODE:
+ code_caption = []
+ code_content = []
+ for block in para_block['blocks']:
+ if block['type'] == BlockType.CODE_CAPTION:
+ code_caption.extend(merge_para_with_text_v2(block))
+ if block['type'] == BlockType.CODE_BODY:
+ code_content = merge_para_with_text_v2(block)
+ sub_type = para_block["sub_type"]
+ if sub_type == BlockType.CODE:
+ para_content = {
+ 'type': ContentTypeV2.CODE,
+ 'content': {
+ 'code_caption': code_caption,
+ 'code_content': code_content,
+ 'code_language': para_block.get('guess_lang', 'txt'),
+ }
+ }
+ elif sub_type == BlockType.ALGORITHM:
+ para_content = {
+ 'type': ContentTypeV2.ALGORITHM,
+ 'content': {
+ 'algorithm_caption': code_caption,
+ 'algorithm_content': code_content,
+ }
+ }
+ else:
+ raise ValueError(f"Unknown code sub_type: {sub_type}")
+ elif para_type == BlockType.REF_TEXT:
+ para_content = {
+ 'type': ContentTypeV2.LIST,
+ 'content': {
+ 'list_type': ContentTypeV2.LIST_REF,
+ 'list_items': [
+ {
+ 'item_type': 'text',
+ 'item_content': merge_para_with_text_v2(para_block),
+ }
+ ],
+ }
+ }
+ elif para_type == BlockType.LIST:
+ if 'sub_type' in para_block:
+ if para_block['sub_type'] == BlockType.REF_TEXT:
+ list_type = ContentTypeV2.LIST_REF
+ elif para_block['sub_type'] == BlockType.TEXT:
+ list_type = ContentTypeV2.LIST_TEXT
+ else:
+ raise ValueError(f"Unknown list sub_type: {para_block['sub_type']}")
+ else:
+ list_type = ContentTypeV2.LIST_TEXT
+ list_items = []
+ for block in para_block['blocks']:
+ item_content = merge_para_with_text_v2(block)
+ if item_content:
+ list_items.append({
+ 'item_type': 'text',
+ 'item_content': item_content,
+ })
+ para_content = {
+ 'type': ContentTypeV2.LIST,
+ 'content': {
+ 'list_type': list_type,
+ 'list_items': list_items,
+ }
+ }
+
+ page_width, page_height = page_size
+ para_bbox = para_block.get('bbox')
+ if para_bbox:
+ x0, y0, x1, y1 = para_bbox
+ para_content['bbox'] = [
+ int(x0 * 1000 / page_width),
+ int(y0 * 1000 / page_height),
+ int(x1 * 1000 / page_width),
+ int(y1 * 1000 / page_height),
+ ]
+
+ return para_content
+
+
+
+
+
+def get_body_data(para_block):
+ """
+ Extract image_path and html from para_block
+ Returns:
+ - For IMAGE/INTERLINE_EQUATION: (image_path, '')
+ - For TABLE: (image_path, html)
+ - Default: ('', '')
+ """
+
+ def get_data_from_spans(lines):
+ for line in lines:
+ for span in line.get('spans', []):
+ span_type = span.get('type')
+ if span_type == ContentType.TABLE:
+ return span.get('image_path', ''), span.get('html', '')
+ elif span_type == ContentType.IMAGE:
+ return span.get('image_path', ''), ''
+ elif span_type == ContentType.INTERLINE_EQUATION:
+ return span.get('image_path', ''), span.get('content', '')
+ elif span_type == ContentType.TEXT:
+ return '', span.get('content', '')
+ return '', ''
+
+ # 处理嵌套的 blocks 结构
+ if 'blocks' in para_block:
+ for block in para_block['blocks']:
+ block_type = block.get('type')
+ if block_type in [BlockType.IMAGE_BODY, BlockType.TABLE_BODY, BlockType.CODE_BODY]:
+ result = get_data_from_spans(block.get('lines', []))
+ if result != ('', ''):
+ return result
+ return '', ''
+
+ # 处理直接包含 lines 的结构
+ return get_data_from_spans(para_block.get('lines', []))
+
+
+def merge_para_with_text_v2(para_block):
+ block_text = ''
+ for line in para_block['lines']:
+ for span in line['spans']:
+ if span['type'] in [ContentType.TEXT]:
+ span['content'] = full_to_half_exclude_marks(span['content'])
+ block_text += span['content']
+ block_lang = detect_lang(block_text)
+
+ para_content = []
+ para_type = para_block['type']
+ for i, line in enumerate(para_block['lines']):
+ for j, span in enumerate(line['spans']):
+ span_type = span['type']
+ if span.get("content", '').strip():
+ if span_type == ContentType.TEXT:
+ if para_type == BlockType.PHONETIC:
+ span_type = ContentTypeV2.SPAN_PHONETIC
+ else:
+ span_type = ContentTypeV2.SPAN_TEXT
+ if span_type == ContentType.INLINE_EQUATION:
+ span_type = ContentTypeV2.SPAN_EQUATION_INLINE
+ if span_type in [
+ ContentTypeV2.SPAN_TEXT,
+ ]:
+ # 定义CJK语言集合(中日韩)
+ cjk_langs = {'zh', 'ja', 'ko'}
+ # logger.info(f'block_lang: {block_lang}, content: {content}')
+
+ # 判断是否为行末span
+ is_last_span = j == len(line['spans']) - 1
+
+ if block_lang in cjk_langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格
+ if is_last_span:
+ span_content = span['content']
+ else:
+ span_content = f"{span['content']} "
+ else:
+ # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除
+ if (
+ is_last_span
+ and is_hyphen_at_line_end(span['content'])
+ ):
+ # 如果下一行的第一个span是小写字母开头,删除连字符
+ if (
+ i + 1 < len(para_block['lines'])
+ and para_block['lines'][i + 1].get('spans')
+ and para_block['lines'][i + 1]['spans'][0].get('type') == ContentType.TEXT
+ and para_block['lines'][i + 1]['spans'][0].get('content', '')
+ and para_block['lines'][i + 1]['spans'][0]['content'][0].islower()
+ ):
+ span_content = span['content'][:-1]
+ else: # 如果没有下一行,或者下一行的第一个span不是小写字母开头,则保留连字符但不加空格
+ span_content = span['content']
+ else:
+ # 西方文本语境下content间需要空格分隔
+ span_content = f"{span['content']} "
+
+ if para_content and para_content[-1]['type'] == span_type:
+ # 合并相同类型的span
+ para_content[-1]['content'] += span_content
+ else:
+ span_content = {
+ 'type': span_type,
+ 'content': span_content,
+ }
+ para_content.append(span_content)
+
+ elif span_type in [
+ ContentTypeV2.SPAN_PHONETIC,
+ ContentTypeV2.SPAN_EQUATION_INLINE,
+ ]:
+ span_content = {
+ 'type': span_type,
+ 'content': span['content'],
+ }
+ para_content.append(span_content)
+ else:
+ logger.warning(f"Unknown span type in merge_para_with_text_v2: {span_type}")
+ return para_content
+
+
+def union_make(pdf_info_dict: list,
+ make_mode: str,
+ img_buket_path: str = '',
+ ):
+
+ formula_enable = get_formula_enable(os.getenv('MINERU_VLM_FORMULA_ENABLE', 'True').lower() == 'true')
+ table_enable = get_table_enable(os.getenv('MINERU_VLM_TABLE_ENABLE', 'True').lower() == 'true')
+
+ output_content = []
+ for page_info in pdf_info_dict:
+ paras_of_layout = page_info.get('para_blocks')
+ paras_of_discarded = page_info.get('discarded_blocks')
+ page_idx = page_info.get('page_idx')
+ page_size = page_info.get('page_size')
+ if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
+ if not paras_of_layout:
+ continue
+ page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, formula_enable, table_enable, img_buket_path)
+ output_content.extend(page_markdown)
+ elif make_mode == MakeMode.CONTENT_LIST:
+ para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])
+ if not para_blocks:
+ continue
+ for para_block in para_blocks:
+ para_content = make_blocks_to_content_list(para_block, img_buket_path, page_idx, page_size)
+ output_content.append(para_content)
+ elif make_mode == MakeMode.CONTENT_LIST_V2:
+ # https://github.com/drunkpig/llm-webkit-mirror/blob/dev6/docs/specification/output_format/content_list_spec.md
+ para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])
+ page_contents = []
+ if para_blocks:
+ for para_block in para_blocks:
+ para_content = make_blocks_to_content_list_v2(para_block, img_buket_path, page_size)
+ page_contents.append(para_content)
+ output_content.append(page_contents)
+
+ if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:
+ return '\n\n'.join(output_content)
+ elif make_mode in [MakeMode.CONTENT_LIST, MakeMode.CONTENT_LIST_V2]:
+ return output_content
+ return None
+
+
+def get_title_level(block):
+ title_level = block.get('level', 1)
+ if title_level > 4:
+ title_level = 4
+ elif title_level < 1:
+ title_level = 0
+ return title_level
diff --git a/mineru/cli/client.py b/mineru/cli/client.py
index 297e028f..72c9cc8c 100644
--- a/mineru/cli/client.py
+++ b/mineru/cli/client.py
@@ -15,7 +15,7 @@ from mineru.utils.config_reader import get_device
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
from mineru.utils.model_utils import get_vram
from ..version import __version__
-from .common import do_parse, read_fn, pdf_suffixes, image_suffixes
+from .common import do_parse, read_fn, pdf_suffixes, image_suffixes, office_suffixes
@click.command(context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@@ -213,7 +213,7 @@ def main(
if os.path.isdir(input_path):
doc_path_list = []
for doc_path in Path(input_path).glob('*'):
- if guess_suffix_by_path(doc_path) in pdf_suffixes + image_suffixes:
+ if guess_suffix_by_path(doc_path) in pdf_suffixes + image_suffixes + office_suffixes:
doc_path_list.append(doc_path)
parse_doc(doc_path_list)
else:
diff --git a/mineru/cli/common.py b/mineru/cli/common.py
index 76f369a3..c8554882 100644
--- a/mineru/cli/common.py
+++ b/mineru/cli/common.py
@@ -9,17 +9,18 @@ from loguru import logger
import pypdfium2 as pdfium
from mineru.data.data_reader_writer import FileBasedDataWriter
-from mineru.model.docx.main import convert_binary
from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox, draw_line_sort_bbox
from mineru.utils.engine_utils import get_vlm_engine
from mineru.utils.enum_class import MakeMode
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_bytes
from mineru.utils.pdf_image_tools import images_bytes_to_pdf_bytes
from mineru.backend.vlm.vlm_middle_json_mkcontent import union_make as vlm_union_make
+from mineru.backend.office.office_middle_json_mkcontent import union_make as office_union_make
from mineru.backend.vlm.vlm_analyze import doc_analyze as vlm_doc_analyze
from mineru.backend.vlm.vlm_analyze import aio_doc_analyze as aio_vlm_doc_analyze
from mineru.backend.hybrid.hybrid_analyze import doc_analyze as hybrid_doc_analyze
from mineru.backend.hybrid.hybrid_analyze import aio_doc_analyze as aio_hybrid_doc_analyze
+from mineru.backend.office.docx_analyze import office_docx_analyze
from mineru.utils.pdf_page_id import get_end_page_id
if os.getenv("MINERU_LMDEPLOY_DEVICE", "") == "maca":
@@ -30,6 +31,9 @@ if os.getenv("MINERU_LMDEPLOY_DEVICE", "") == "maca":
pdf_suffixes = ["pdf"]
image_suffixes = ["png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"]
docx_suffixes = ["docx"]
+pptx_suffixes = ["pptx"]
+xlsx_suffixes = ["xlsx"]
+office_suffixes = docx_suffixes + pptx_suffixes + xlsx_suffixes
os.environ["TOKENIZERS_PARALLELISM"] = "false"
@@ -41,7 +45,7 @@ def read_fn(path):
file_suffix = guess_suffix_by_bytes(file_bytes, path)
if file_suffix in image_suffixes:
return images_bytes_to_pdf_bytes(file_bytes)
- elif file_suffix in pdf_suffixes + docx_suffixes:
+ elif file_suffix in pdf_suffixes + office_suffixes:
return file_bytes
else:
raise Exception(f"Unknown file suffix: {file_suffix}")
@@ -112,10 +116,18 @@ def _process_output(
f_make_md_mode,
middle_json,
model_output=None,
- is_pipeline=True
+ process_mode="vlm",
):
f_draw_line_sort_bbox = False
from mineru.backend.pipeline.pipeline_middle_json_mkcontent import union_make as pipeline_union_make
+ if process_mode == "pipeline":
+ make_func = pipeline_union_make
+ elif process_mode == "vlm":
+ make_func = vlm_union_make
+ elif process_mode in office_suffixes:
+ make_func = office_union_make
+ else:
+ raise Exception(f"Unknown process_mode: {process_mode}")
"""处理输出文件"""
if f_draw_layout_bbox:
draw_layout_bbox(pdf_info, pdf_bytes, local_md_dir, f"{pdf_file_name}_layout.pdf")
@@ -124,10 +136,16 @@ def _process_output(
draw_span_bbox(pdf_info, pdf_bytes, local_md_dir, f"{pdf_file_name}_span.pdf")
if f_dump_orig_pdf:
- md_writer.write(
- f"{pdf_file_name}_origin.pdf",
- pdf_bytes,
- )
+ if process_mode in ["pipeline", "vlm"]:
+ md_writer.write(
+ f"{pdf_file_name}_origin.pdf",
+ pdf_bytes,
+ )
+ elif process_mode in office_suffixes:
+ md_writer.write(
+ f"{pdf_file_name}_origin.{process_mode}",
+ pdf_bytes,
+ )
if f_draw_line_sort_bbox:
draw_line_sort_bbox(pdf_info, pdf_bytes, local_md_dir, f"{pdf_file_name}_line_sort.pdf")
@@ -135,7 +153,6 @@ def _process_output(
image_dir = str(os.path.basename(local_image_dir))
if f_dump_md:
- make_func = pipeline_union_make if is_pipeline else vlm_union_make
md_content_str = make_func(pdf_info, f_make_md_mode, image_dir)
md_writer.write_string(
f"{pdf_file_name}.md",
@@ -143,13 +160,12 @@ def _process_output(
)
if f_dump_content_list:
- make_func = pipeline_union_make if is_pipeline else vlm_union_make
content_list = make_func(pdf_info, MakeMode.CONTENT_LIST, image_dir)
md_writer.write_string(
f"{pdf_file_name}_content_list.json",
json.dumps(content_list, ensure_ascii=False, indent=4),
)
- if not is_pipeline:
+ if process_mode != "pipeline":
content_list_v2 = make_func(pdf_info, MakeMode.CONTENT_LIST_V2, image_dir)
md_writer.write_string(
f"{pdf_file_name}_content_list_v2.json",
@@ -223,7 +239,7 @@ def _process_pipeline(
pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
- f_make_md_mode, middle_json, model_json, is_pipeline=True
+ f_make_md_mode, middle_json, model_json, process_mode="pipeline"
)
@@ -264,7 +280,7 @@ async def _async_process_vlm(
pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
- f_make_md_mode, middle_json, infer_result, is_pipeline=False
+ f_make_md_mode, middle_json, infer_result, process_mode="vlm"
)
@@ -305,7 +321,7 @@ def _process_vlm(
pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
- f_make_md_mode, middle_json, infer_result, is_pipeline=False
+ f_make_md_mode, middle_json, infer_result, process_mode="vlm"
)
@@ -357,7 +373,7 @@ def _process_hybrid(
pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
- f_make_md_mode, middle_json, infer_result, is_pipeline=False
+ f_make_md_mode, middle_json, infer_result, process_mode="vlm"
)
@@ -410,22 +426,53 @@ async def _async_process_hybrid(
pdf_info, pdf_bytes, pdf_file_name, local_md_dir, local_image_dir,
md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_pdf,
f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
- f_make_md_mode, middle_json, infer_result, is_pipeline=False
+ f_make_md_mode, middle_json, infer_result, process_mode="vlm"
)
def _process_office_doc(
output_dir,
+ pdf_file_names: list[str],
pdf_bytes_list: list[bytes],
+ f_dump_md=True,
+ f_dump_middle_json=True,
+ f_dump_model_output=True,
+ f_dump_orig_file=True,
+ f_dump_content_list=True,
+ f_make_md_mode=MakeMode.MM_MD,
):
need_remove_index = []
for i, file_bytes in enumerate(pdf_bytes_list):
+ pdf_file_name = pdf_file_names[i]
file_suffix = guess_suffix_by_bytes(file_bytes)
if file_suffix in docx_suffixes:
+
need_remove_index.append(i)
- # docx解析流程
- result = convert_binary(io.BytesIO(file_bytes))
- pass
+
+ local_image_dir, local_md_dir = prepare_env(output_dir, pdf_file_name, f"office")
+ image_writer, md_writer = FileBasedDataWriter(local_image_dir), FileBasedDataWriter(local_md_dir)
+ middle_json, infer_result = office_docx_analyze(
+ file_bytes,
+ image_writer=image_writer,
+ )
+
+ f_draw_layout_bbox = False
+ f_draw_span_bbox = False
+ pdf_info = middle_json["pdf_info"]
+
+ _process_output(
+ pdf_info, file_bytes, pdf_file_name, local_md_dir, local_image_dir,
+ md_writer, f_draw_layout_bbox, f_draw_span_bbox, f_dump_orig_file,
+ f_dump_md, f_dump_content_list, f_dump_middle_json, f_dump_model_output,
+ f_make_md_mode, middle_json, infer_result, process_mode="docx"
+ )
+ elif file_suffix in pptx_suffixes:
+ need_remove_index.append(i)
+ logger.warning(f"Currently, PPTX files are not supported: {pdf_file_name}")
+ elif file_suffix in xlsx_suffixes:
+ need_remove_index.append(i)
+ logger.warning(f"Currently, XLSX files are not supported: {pdf_file_name}")
+
return need_remove_index
@@ -453,7 +500,14 @@ def do_parse(
):
need_remove_index = _process_office_doc(
output_dir,
- pdf_bytes_list,
+ pdf_file_names=pdf_file_names,
+ pdf_bytes_list=pdf_bytes_list,
+ f_dump_md=f_dump_md,
+ f_dump_middle_json=f_dump_middle_json,
+ f_dump_model_output=f_dump_model_output,
+ f_dump_orig_file=f_dump_orig_pdf,
+ f_dump_content_list=f_dump_content_list,
+ f_make_md_mode=f_make_md_mode,
)
for index in sorted(need_remove_index, reverse=True):
del pdf_bytes_list[index]
@@ -537,7 +591,14 @@ async def aio_do_parse(
):
need_remove_index = _process_office_doc(
output_dir,
- pdf_bytes_list,
+ pdf_file_names=pdf_file_names,
+ pdf_bytes_list=pdf_bytes_list,
+ f_dump_md=f_dump_md,
+ f_dump_middle_json=f_dump_middle_json,
+ f_dump_model_output=f_dump_model_output,
+ f_dump_orig_file=f_dump_orig_pdf,
+ f_dump_content_list=f_dump_content_list,
+ f_make_md_mode=f_make_md_mode,
)
for index in sorted(need_remove_index, reverse=True):
del pdf_bytes_list[index]
diff --git a/mineru/cli/fast_api.py b/mineru/cli/fast_api.py
index 06fd7ad0..e39c1c8a 100644
--- a/mineru/cli/fast_api.py
+++ b/mineru/cli/fast_api.py
@@ -22,7 +22,7 @@ logger.add(sys.stderr, level=log_level) # 添加新handler
from base64 import b64encode
-from mineru.cli.common import aio_do_parse, read_fn, pdf_suffixes, image_suffixes
+from mineru.cli.common import aio_do_parse, read_fn, pdf_suffixes, image_suffixes, office_suffixes
from mineru.utils.cli_parser import arg_parse
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
from mineru.version import __version__
@@ -187,7 +187,7 @@ async def parse_pdf(
# 如果是图像文件或PDF,使用read_fn处理
file_suffix = guess_suffix_by_path(temp_path)
- if file_suffix in pdf_suffixes + image_suffixes:
+ if file_suffix in pdf_suffixes + image_suffixes + office_suffixes:
try:
pdf_bytes = read_fn(temp_path)
pdf_bytes_list.append(pdf_bytes)