Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
fix: enhance office file handling and improve image base64 conversion in markdown
myhloli4537e099912b
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.pyindex 278aaecd..5d93f2c1 100644--- a/mineru/backend/office/office_middle_json_mkcontent.py+++ b/mineru/backend/office/office_middle_json_mkcontent.py@@ -2,10 +2,8 @@ import osfrom 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.config_reader import get_latex_delimiter_configfrom mineru.utils.enum_class import MakeMode, BlockType, ContentType, ContentTypeV2-from mineru.utils.language import detect_langlatex_delimiters_config = get_latex_delimiter_config()@@ -389,17 +387,10 @@ def merge_para_with_text_v2(para_block):para_content = []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:- span_type = ContentTypeV2.SPAN_TEXT- if span_type == ContentType.INLINE_EQUATION:- span_type = ContentTypeV2.SPAN_EQUATION_INLINE- span_content = {- 'type': span_type,- 'content': span['content'],- }- para_content.append(span_content)+ if span['type'] == ContentType.INLINE_EQUATION:+ span['type'] = ContentTypeV2.SPAN_EQUATION_INLINE+ para_content.append(span)return para_contentdiff --git a/mineru/cli/common.py b/mineru/cli/common.pyindex a47294c8..129e3884 100644--- a/mineru/cli/common.py+++ b/mineru/cli/common.py@@ -435,6 +435,7 @@ def _process_office_doc(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,@@ -454,7 +455,6 @@ def _process_office_doc(image_writer=image_writer,)- f_dump_model_output = Falsef_draw_layout_bbox = Falsef_draw_span_bbox = Falsepdf_info = middle_json["pdf_info"]@@ -503,6 +503,7 @@ def do_parse(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,@@ -593,6 +594,7 @@ async def aio_do_parse(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,diff --git a/mineru/cli/gradio_app.py b/mineru/cli/gradio_app.pyindex 2ab61300..19ff25a9 100644--- a/mineru/cli/gradio_app.py+++ b/mineru/cli/gradio_app.py@@ -17,7 +17,7 @@ log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()logger.remove() # 移除默认handlerlogger.add(sys.stderr, level=log_level) # 添加新handler-from mineru.cli.common import prepare_env, read_fn, aio_do_parse, pdf_suffixes, image_suffixes+from mineru.cli.common import prepare_env, read_fn, aio_do_parse, pdf_suffixes, image_suffixes, office_suffixesfrom mineru.utils.cli_parser import arg_parsefrom mineru.utils.engine_utils import get_vlm_enginefrom mineru.utils.hash_utils import str_sha256@@ -29,17 +29,24 @@ async def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, formula_enable, ttry:file_name = f'{safe_stem(Path(doc_path).stem)}_{time.strftime("%y%m%d_%H%M%S")}'pdf_data = read_fn(doc_path)- # 根据 backend 确定 parse_method- if backend.startswith("vlm"):++ # 检测 office 文件类型+ file_suffix = Path(doc_path).suffix.lower().lstrip('.')+ if file_suffix in office_suffixes:+ # office 文件使用固定的 env_name,parse_method 设为默认值(aio_do_parse 内部会处理)+ env_name = "office"+ parse_method = "auto"+ elif backend.startswith("vlm"):+ # 根据 backend 确定 parse_methodparse_method = "vlm"+ env_name = parse_methodelse:parse_method = 'ocr' if is_ocr else 'auto'-- # 根据 backend 类型准备环境目录- if backend.startswith("hybrid"):- env_name = f"hybrid_{parse_method}"- else:- env_name = parse_method+ # 根据 backend 类型准备环境目录+ if backend.startswith("hybrid"):+ env_name = f"hybrid_{parse_method}"+ else:+ env_name = parse_methodlocal_image_dir, local_md_dir = prepare_env(output_dir, file_name, env_name)@@ -91,20 +98,38 @@ def image_to_base64(image_path):def replace_image_with_base64(markdown_text, image_dir_path):+ # MIME类型映射+ mime_types = {+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.png': 'image/png',+ '.gif': 'image/gif',+ '.webp': 'image/webp',+ }+# 匹配Markdown中的图片标签pattern = r'\!\[(?:[^\]]*)\]\(([^)]+)\)'# 替换图片链接def replace(match):relative_path = match.group(1)- # 只处理以.jpg结尾的图片- if relative_path.endswith('.jpg'):- full_path = os.path.join(image_dir_path, relative_path)- base64_image = image_to_base64(full_path)- return f''+ # 获取文件扩展名(不区分大小写)+ file_ext = os.path.splitext(relative_path)[1].lower()++ # 如果是支持的图片格式,转换为base64+ if file_ext in mime_types:+ try:+ full_path = os.path.join(image_dir_path, relative_path)+ base64_image = image_to_base64(full_path)+ mime_type = mime_types[file_ext]+ return f''+ except Exception as e:+ logger.warning(f"Failed to convert image {relative_path} to base64: {e}")+ return match.group(0)else:# 其他格式的图片保持原样return match.group(0)+# 应用替换return re.sub(pattern, replace, markdown_text)@@ -113,9 +138,17 @@ async def to_markdown(file_path, end_pages=10, is_ocr=False, formula_enable=True# 如果language包含(),则提取括号前的内容作为实际语言if '(' in language and ')' in language:language = language.split('(')[0].strip()- file_path = to_pdf(file_path)++ # office 文件不需要转换为 PDF,直接使用原始文件路径+ file_suffix = Path(file_path).suffix.lower().lstrip('.')+ is_office = file_suffix in office_suffixes+ if is_office:+ parse_file_path = file_path+ else:+ parse_file_path = to_pdf(file_path)+# 获取识别的md文件以及压缩包文件路径- local_md_dir, file_name = await parse_pdf(file_path, './output', end_pages - 1, is_ocr, formula_enable, table_enable, language, backend, url)+ local_md_dir, file_name = await parse_pdf(parse_file_path, './output', end_pages - 1, is_ocr, formula_enable, table_enable, language, backend, url)archive_zip_path = os.path.join('./output', str_sha256(local_md_dir) + '.zip')zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)if zip_archive_success == 0:@@ -126,8 +159,11 @@ async def to_markdown(file_path, end_pages=10, is_ocr=False, formula_enable=Truewith open(md_path, 'r', encoding='utf-8') as f:txt_content = f.read()md_content = replace_image_with_base64(txt_content, local_md_dir)- # 返回转换后的PDF路径- new_pdf_path = os.path.join(local_md_dir, file_name + '_layout.pdf')+ # office 文件没有 layout PDF,返回 None;其他格式返回转换后的 PDF 路径+ if is_office:+ new_pdf_path = None+ else:+ new_pdf_path = os.path.join(local_md_dir, file_name + '_layout.pdf')return md_content, txt_content, archive_zip_path, new_pdf_path@@ -196,6 +232,16 @@ def to_pdf(file_path):return tmp_file_path+def to_pdf_preview(file_path):+ """用于 PDF 预览的转换函数,office 文件不支持预览,返回 None。"""+ if file_path is None:+ return None+ file_suffix = Path(file_path).suffix.lower().lstrip('.')+ if file_suffix in office_suffixes:+ return None+ return to_pdf(file_path)++@click.command(context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))@click.pass_context@click.option(@@ -398,7 +444,7 @@ def main(ctx,except Exception as e:logger.exception(e)- suffixes = [f".{suffix}" for suffix in pdf_suffixes + image_suffixes]+ suffixes = [f".{suffix}" for suffix in pdf_suffixes + image_suffixes + office_suffixes]with gr.Blocks() as demo:gr.HTML(header)with gr.Row():@@ -476,7 +522,7 @@ def main(ctx,clear_bu.add([input_file, md, pdf_show, md_text, output_file, is_ocr])input_file.change(- fn=to_pdf,+ fn=to_pdf_preview,inputs=input_file,outputs=pdf_show,api_name="to_pdf" if api_enable else False, # gradio 6 以下版本使用diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.pyindex fd06a942..84d95505 100644--- a/mineru/model/docx/docx_converter.py+++ b/mineru/model/docx/docx_converter.py@@ -114,7 +114,7 @@ class DocxConverter:@classmethoddef _format_text_with_hyperlink(- cls, text: str, hyperlink: Optional[Union[AnyUrl, Path]]+ cls, text: str, hyperlink: Optional[Union[AnyUrl, Path, str]]) -> str:"""将文本和超链接格式化为 Markdown 格式 [文本](链接)。@@ -146,7 +146,7 @@ class DocxConverter:def _build_text_from_elements(self,paragraph_elements: list[- tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path]]]+ tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]],) -> str:"""@@ -168,7 +168,7 @@ class DocxConverter:def _build_text_with_equations_and_hyperlinks(self,paragraph_elements: list[- tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path]]]+ tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]],text_with_equations: str,equations: list,@@ -635,7 +635,7 @@ class DocxConverter:paragraph: 段落对象Returns:- list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path]]]]:+ list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]]:段落元素列表,每个元素包含文本、格式和超链接信息"""@@ -644,7 +644,7 @@ class DocxConverter:return [("", None, None)]paragraph_elements: list[- tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path]]]+ tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]] = []group_text = ""previous_format = None@@ -653,7 +653,12 @@ class DocxConverter:for c in paragraph.iter_inner_content():if isinstance(c, Hyperlink):text = c.text- hyperlink = Path(c.address)+ # 若地址为 URL(含 ://),直接保留字符串,避免 Path 将 // 规范化为 /+ address = c.address+ if address and "://" in address:+ hyperlink = address+ else:+ hyperlink = Path(address) if address else Path(".")format = (self._get_format_from_run(c.runs[0])if c.runs and len(c.runs) > 0