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
refactor: migrate Office rendering to render/ layer, unify V2 content list
jinzhenj4c42213ed347
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.pyindex 2543e506..f2dfad3b 100644--- a/mineru/backend/hybrid/hybrid_analyze.py+++ b/mineru/backend/hybrid/hybrid_analyze.py@@ -17,10 +17,10 @@ from PIL import Imagefrom tqdm import tqdmfrom ...data.data_reader_writer import DataWriter-from ...types import BBox, PageInfo+from ...types import NOT_EXTRACT_TYPES, BBox, PageInfo+from ...types import BlockType as MineruBlockTypefrom ...utils.config_reader import get_device, get_processing_window_size-from ...utils.enum_class import BlockType as MineruBlockType-from ...utils.enum_class import ImageType, NotExtractType+from ...utils.enum_class import ImageTypefrom ...utils.model_utils import clean_memory, crop_img, get_vramfrom ...utils.ocr_utils import (OcrConfidence,@@ -64,13 +64,10 @@ MFR_BASE_BATCH_SIZE = 16OCR_DET_BASE_BATCH_SIZE = 8LAYOUT_TITLE_SPLIT_OVERLAP_THRESHOLD = 0.8-not_extract_list = [item.value for item in NotExtractType]-HYBRID_OCR_DET_TEXT_TYPES = set(not_extract_list)-def _is_hybrid_ocr_det_candidate(block: dict[str, Any]) -> bool:"""判断 Hybrid 文本类块是否需要 OCR det 生成行级视觉信息。"""- return (block.get("type") or block.get("label")) in HYBRID_OCR_DET_TEXT_TYPES+ return (block.get("type") or block.get("label")) in NOT_EXTRACT_TYPESdef ocr_classify(@@ -812,7 +809,7 @@ def doc_analyze(with predictor_execution_guard(predictor):window_model_list = predictor.batch_two_step_extract(images=images_pil_list,- not_extract_list=not_extract_list,+ not_extract_list=list(NOT_EXTRACT_TYPES),image_analysis=image_analysis,)window_model_list, hybrid_pipeline_model = _process_ocr_and_formulas(@@ -963,7 +960,7 @@ async def aio_doc_analyze(async with aio_predictor_execution_guard(predictor):window_model_list = await predictor.aio_batch_two_step_extract(images=images_pil_list,- not_extract_list=not_extract_list,+ not_extract_list=list(NOT_EXTRACT_TYPES),image_analysis=image_analysis,)window_model_list, hybrid_pipeline_model = await asyncio.to_thread(diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.pyindex 92854c44..f2bf1bab 100644--- a/mineru/backend/hybrid/hybrid_magic_model.py+++ b/mineru/backend/hybrid/hybrid_magic_model.py@@ -8,8 +8,7 @@ from typing import Anyfrom loguru import loggerfrom PIL import Image-from ...types import EMPTY_BBOX, BBox, Block, IntBBox, Line, Span-from ...utils.enum_class import BlockType, ContentType, NotExtractType+from ...types import EMPTY_BBOX, NOT_EXTRACT_TYPES, BBox, Block, BlockType, ContentType, IntBBox, Line, Spanfrom ...utils.guess_suffix_or_lang import guess_language_by_textfrom ..utils.boxbase import calculate_overlap_area_in_bbox1_area_ratiofrom ..utils.span_block_fix import fix_text_block@@ -26,13 +25,16 @@ from ..utils.visual_magic_model_utils import (regroup_visual_blocks,)-not_extract_list = [item.value for item in NotExtractType] + [+not_extract_list = [+ *NOT_EXTRACT_TYPES,BlockType.CAPTION,BlockType.FOOTNOTE,BlockType.DOC_TITLE,BlockType.PARAGRAPH_TITLE,]-OCR_DET_LINE_BLOCK_TYPES = set(not_extract_list) | {++OCR_DET_LINE_BLOCK_TYPES = {+ *not_extract_list,BlockType.LIST,BlockType.INDEX,BlockType.ABSTRACT,@@ -173,7 +175,7 @@ class MagicModel:span_type = ContentType.INTERLINE_EQUATIONif span_type == ContentType.TEXT and block_content is None:- # 文本类块缺失 content 时按空文本处理,避免 VLM mkcontent 渲染阶段遇到 None。+ # 文本类块缺失 content 时按空文本处理,避免 VLM 渲染阶段遇到 None。block_content = ""# code 和 algorithm 类型的块,如果内容中包含行内公式,则需要将块类型切换为 algorithmdiff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.pyindex 6d97d630..fc80592b 100644--- a/mineru/backend/hybrid/model_output_to_middle_json.py+++ b/mineru/backend/hybrid/model_output_to_middle_json.py@@ -6,10 +6,9 @@ import osfrom typing import Anyfrom ...data.data_reader_writer import DataWriter-from ...types import Block, PageInfo+from ...types import Block, BlockType, ContentType, PageInfofrom ...utils.config_reader import get_table_enablefrom ...utils.cut_image import cut_image_and_table-from ...utils.enum_class import BlockType, ContentTypefrom ...utils.hash_utils import bytes_md5from ...utils.pdfium_guard import pdfium_guardfrom ...utils.title_level_postprocess import apply_title_leveling_to_pdf_infodiff --git a/mineru/backend/office/mkcontent/__init__.py b/mineru/backend/office/mkcontent/__init__.pydeleted file mode 100644index 1e17167c..00000000--- a/mineru/backend/office/mkcontent/__init__.py+++ /dev/null@@ -1 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.pyindex e5c2c799..8db262eb 100644--- a/mineru/backend/office/model_output_to_middle_json.py+++ b/mineru/backend/office/model_output_to_middle_json.py@@ -5,8 +5,7 @@ import refrom collections import defaultdictfrom typing import Any-from ...types import Block, PageInfo-from ...utils.enum_class import BlockType+from ...types import Block, BlockType, PageInfofrom ..utils.html_image_utils import replace_inline_table_images, save_span_image_if_neededfrom .office_magic_model import MagicModeldiff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.pyindex 8c131132..14c50c70 100644--- a/mineru/backend/office/office_magic_model.py+++ b/mineru/backend/office/office_magic_model.py@@ -6,8 +6,7 @@ import refrom typing import Any, Literalfrom urllib.parse import urlparse-from ...types import EMPTY_BBOX, Block, Line, Span-from ...utils.enum_class import BlockType, ContentType+from ...types import EMPTY_BBOX, Block, BlockType, ContentType, Line, Spanfrom ..utils.magic_model_utils import tie_up_category_by_indexdiff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.pydeleted file mode 100644index 1fd4fe86..00000000--- a/mineru/backend/office/office_middle_json_mkcontent.py+++ /dev/null@@ -1,36 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-from .mkcontent.inline_renderer import (- display_left_delimiter,- display_right_delimiter,- get_title_level,- inline_left_delimiter,- inline_right_delimiter,- merge_para_with_text,-)-from .mkcontent.output_builders import (- get_body_data,- make_blocks_to_content_list,- make_blocks_to_content_list_v2,- merge_index_to_markdown,- merge_list_to_markdown,- merge_para_with_text_v2,- mk_blocks_to_markdown,- union_make,-)--__all__ = [- "display_left_delimiter",- "display_right_delimiter",- "get_body_data",- "get_title_level",- "inline_left_delimiter",- "inline_right_delimiter",- "make_blocks_to_content_list",- "make_blocks_to_content_list_v2",- "merge_index_to_markdown",- "merge_list_to_markdown",- "merge_para_with_text",- "merge_para_with_text_v2",- "mk_blocks_to_markdown",- "union_make",-]diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.pyindex 80a9d368..cb0c8810 100644--- a/mineru/backend/pipeline/model_output_to_middle_json.py+++ b/mineru/backend/pipeline/model_output_to_middle_json.py@@ -2,9 +2,8 @@from typing import Anyfrom ...data.data_reader_writer import DataWriter-from ...types import Block, PageInfo, Span+from ...types import Block, BlockType, ContentType, PageInfo, Spanfrom ...utils.cut_image import cut_image_and_table-from ...utils.enum_class import BlockType, ContentTypefrom ...utils.hash_utils import bytes_md5from ...utils.pdfium_guard import pdfium_guardfrom ...utils.title_level_postprocess import apply_title_leveling_to_pdf_infodiff --git a/mineru/backend/pipeline/para_split.py b/mineru/backend/pipeline/para_split.pyindex 2e6b94ed..45264e4e 100644--- a/mineru/backend/pipeline/para_split.py+++ b/mineru/backend/pipeline/para_split.py@@ -3,8 +3,7 @@ from __future__ import annotationsimport copy-from ...types import Block, PageInfo-from ...utils.enum_class import BlockType, ContentType+from ...types import Block, BlockType, ContentType, PageInfofrom ...utils.language import detect_langLINE_STOP_FLAG = (".", "!", "?", "。", "!", "?", ")", ")", '"', "”", ":", ":", ";", ";")diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.pyindex 3adca705..95864a03 100644--- a/mineru/backend/pipeline/pipeline_magic_model.py+++ b/mineru/backend/pipeline/pipeline_magic_model.py@@ -5,8 +5,7 @@ from copy import deepcopyfrom typing import TYPE_CHECKING, Anyfrom ...render.merge import _merge_para_text-from ...types import EMPTY_BBOX, BBox, Block, Line, Span-from ...utils.enum_class import BlockType, ContentType+from ...types import EMPTY_BBOX, BBox, Block, BlockType, ContentType, Line, Spanfrom ...utils.guess_suffix_or_lang import guess_language_by_textfrom ..utils.boxbase import calculate_overlap_area_2_minbox_area_ratio, calculate_overlap_area_in_bbox1_area_ratiofrom ..utils.span_block_fix import (diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.pyindex 67525798..9a6c7f0c 100644--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py@@ -3,10 +3,7 @@ from __future__ import annotationsfrom typing import Any-from loguru import logger--from ...render.content_list import block_to_content_list-from ...render.markdown import _get_title_level, blocks_to_markdown+from ...render.markdown import _get_title_levelfrom ...render.merge import (CJK_LANGS,_collect_text_for_lang_detection,@@ -14,11 +11,9 @@ from ...render.merge import (_normalize_text_content,)from ...render.merge_visual import _format_embedded_html, _normalize_visual_content-from ...types import BBox, Block, IntBBox, Line, PageInfo-from ...utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeMode+from ...types import BBox, Block, BlockType, ContentType, ContentTypeV2, IntBBox, Linefrom ...utils.language import detect_langfrom ..utils.char_utils import is_hyphen_at_line_end-from ..utils.markdown_utils import escape_conservative_markdown_textdef _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:@@ -421,61 +416,3 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str, pagepara_content["bbox"] = bboxreturn para_content---def union_make(- pdf_info_dict: list[PageInfo],- make_mode: str,- img_bucket_path: str = "",-) -> str | list[dict[str, Any]] | list[list[dict[str, Any]]] | None:- output_markdowns: list[str] = []- output_content_items: list[dict[str, Any]] = []- output_content_lists: list[list[dict[str, Any]]] = []- for page_info in pdf_info_dict:- paras_of_layout = page_info.para_blocks- paras_of_discarded = page_info.discarded_blocks- page_idx = page_info.page_idx- page_size = page_info.page_size- if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:- if not paras_of_layout:- continue- page_markdown = blocks_to_markdown(- para_blocks=paras_of_layout,- img_bucket_path=img_bucket_path,- no_rich_content=(make_mode == MakeMode.NLP_MD),- )- output_markdowns.extend(page_markdown)- elif make_mode == MakeMode.CONTENT_LIST:- para_blocks = merge_adjacent_ref_text_blocks_for_content((paras_of_layout or []) + (paras_of_discarded or []))- if not para_blocks:- continue- for para_block in para_blocks:- para_content = block_to_content_list(para_block, img_bucket_path, page_idx, page_size)- if para_content:- output_content_items.append(para_content.to_dict())- elif make_mode == MakeMode.CONTENT_LIST_V2:- para_blocks = merge_adjacent_ref_text_blocks_for_content((paras_of_layout or []) + (paras_of_discarded or []))- page_contents: list[dict[str, Any]] = []- if para_blocks:- for para_block in para_blocks:- para_content = make_blocks_to_content_list_v2(para_block, img_bucket_path, page_size)- if para_content:- page_contents.append(para_content)- output_content_lists.append(page_contents)-- if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:- return "\n\n".join(output_markdowns)- elif make_mode == MakeMode.CONTENT_LIST:- return output_content_items- elif make_mode == MakeMode.CONTENT_LIST_V2:- return output_content_lists- else:- logger.error(f"Unsupported make mode: {make_mode}")- return None---def escape_special_markdown_char(content: str) -> str:- """- 转义正文里对markdown语法有特殊意义的字符- """- return escape_conservative_markdown_text(content)diff --git a/mineru/backend/utils/html_image_utils.py b/mineru/backend/utils/html_image_utils.pyindex e84daed6..3006f859 100644--- a/mineru/backend/utils/html_image_utils.py+++ b/mineru/backend/utils/html_image_utils.py@@ -7,8 +7,7 @@ import refrom loguru import loggerfrom ...data.data_reader_writer import DataWriter-from ...types import Block, Span-from ...utils.enum_class import BlockType, ContentType+from ...types import Block, BlockType, ContentType, Spanfrom ...utils.hash_utils import str_sha256from .office_image import is_vector_image_part, serialize_office_imagediff --git a/mineru/backend/utils/para_block_utils.py b/mineru/backend/utils/para_block_utils.pyindex e43ce066..5eef36ca 100644--- a/mineru/backend/utils/para_block_utils.py+++ b/mineru/backend/utils/para_block_utils.py@@ -2,8 +2,7 @@import copyfrom collections.abc import Generator-from ...types import BBox, Block, Line, PageInfo, Span-from ...utils.enum_class import BlockType+from ...types import BBox, Block, BlockType, Line, PageInfo, SpanLINE_STOP_FLAG = (".", "!", "?", "。", "!", "?", ")", ")", '"', "”", ":", ":", ";", ";")SECTION_MERGE_BARRIER_TYPES = {diff --git a/mineru/backend/utils/span_block_fix.py b/mineru/backend/utils/span_block_fix.pyindex 97eb8ff7..6db91e9e 100644--- a/mineru/backend/utils/span_block_fix.py+++ b/mineru/backend/utils/span_block_fix.py@@ -1,6 +1,5 @@# Copyright (c) Opendatalab. All rights reserved.-from ...types import Block, Line, Span-from ...utils.enum_class import ContentType+from ...types import Block, ContentType, Line, Spanfrom ...utils.ocr_utils import _is_overlaps_x_exceeds_threshold, _is_overlaps_y_exceeds_thresholdVERTICAL_SPAN_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2diff --git a/mineru/backend/utils/span_pre_proc.py b/mineru/backend/utils/span_pre_proc.pyindex 3ef8885d..b250eba1 100644--- a/mineru/backend/utils/span_pre_proc.py+++ b/mineru/backend/utils/span_pre_proc.py@@ -11,8 +11,7 @@ import cv2import numpy as npfrom loguru import logger-from ...types import BBox, Span-from ...utils.enum_class import BlockType, ContentType+from ...types import BBox, BlockType, ContentType, Spanfrom ...utils.image_utils import calculate_contrastfrom ...utils.pdf_image_tools import get_crop_imgfrom ...utils.pdf_text_tool import get_lines_from_chars, get_page_charsdiff --git a/mineru/backend/utils/table_merge.py b/mineru/backend/utils/table_merge.pyindex 7d64d806..55c00d9c 100644--- a/mineru/backend/utils/table_merge.py+++ b/mineru/backend/utils/table_merge.py@@ -8,8 +8,7 @@ from typing import Anyfrom bs4 import BeautifulSoup, Tagfrom ...render.merge import merge_para_text-from ...types import BBox, Block, PageInfo, Span-from ...utils.enum_class import BlockType+from ...types import BBox, Block, BlockType, PageInfo, Spanfrom .char_utils import full_to_halffrom .table_continuation import is_table_continuation_textdiff --git a/mineru/backend/utils/visual_magic_model_utils.py b/mineru/backend/utils/visual_magic_model_utils.pyindex 8834a6e8..1b699f32 100644--- a/mineru/backend/utils/visual_magic_model_utils.py+++ b/mineru/backend/utils/visual_magic_model_utils.py@@ -5,8 +5,7 @@ import refrom copy import deepcopyfrom typing import Any-from ...types import BBox, Block-from ...utils.enum_class import BlockType+from ...types import BBox, Block, BlockTypefrom .boxbase import bbox_center_distance, bbox_distance, calculate_overlap_area_in_bbox1_area_ratiofrom .table_continuation import is_table_continuation_textdiff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.pyindex 1d43cb99..9295f284 100644--- a/mineru/backend/vlm/model_output_to_middle_json.py+++ b/mineru/backend/vlm/model_output_to_middle_json.py@@ -7,10 +7,9 @@ from typing import Anyfrom mineru_vl_utils.structs import ExtractResultfrom ...data.data_reader_writer import DataWriter-from ...types import PageInfo+from ...types import ContentType, PageInfofrom ...utils.config_reader import get_table_enablefrom ...utils.cut_image import cut_image_and_table-from ...utils.enum_class import ContentTypefrom ...utils.hash_utils import bytes_md5from ...utils.pdfium_guard import pdfium_guardfrom ...utils.title_level_postprocess import apply_title_leveling_to_pdf_infodiff --git a/mineru/backend/vlm/vlm_magic_model.py b/mineru/backend/vlm/vlm_magic_model.pyindex 9bde1ed3..d55e8061 100644--- a/mineru/backend/vlm/vlm_magic_model.py+++ b/mineru/backend/vlm/vlm_magic_model.py@@ -6,8 +6,7 @@ import refrom loguru import loggerfrom mineru_vl_utils.structs import ContentBlock, ExtractResult-from ...types import Block, Line, Span-from ...utils.enum_class import BlockType, ContentType+from ...types import Block, BlockType, ContentType, Line, Spanfrom ...utils.guess_suffix_or_lang import guess_language_by_textfrom ..utils.boxbase import calculate_overlap_area_in_bbox1_area_ratiofrom ..utils.visual_magic_model_utils import (@@ -106,7 +105,7 @@ class MagicModel:span_type = ContentType.INTERLINE_EQUATIONif span_type == ContentType.TEXT and block_content is None:- # 文本类块缺失 content 时按空文本处理,避免下游 mkcontent 遇到 None。+ # 文本类块缺失 content 时按空文本处理,避免下游 render 遇到 None。block_content = ""# code 和 algorithm 类型的块,如果内容中包含行内公式,则需要将块类型切换为 algorithmdiff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.pyindex e095b3b1..7e212dc7 100644--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py@@ -1,16 +1,12 @@# Copyright (c) Opendatalab. All rights reserved.-import osfrom typing import Anyfrom loguru import logger-from ...render.content_list import block_to_content_list-from ...render.markdown import _get_title_level, blocks_to_markdown+from ...render.markdown import _get_title_levelfrom ...render.merge import _normalize_text_contentfrom ...render.merge_visual import _build_media_path, _format_embedded_html-from ...types import Block, Line, PageInfo-from ...utils.config_reader import get_formula_enable, get_table_enable-from ...utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeMode+from ...types import Block, BlockType, ContentType, ContentTypeV2, Linefrom ...utils.language import detect_langfrom ..utils.char_utils import is_hyphen_at_line_end@@ -368,55 +364,3 @@ def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]: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[PageInfo],- make_mode: str,- img_bucket_path: str = "",-) -> str | list | None:- 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.para_blocks- paras_of_discarded = page_info.discarded_blocks- page_idx = page_info.page_idx- page_size = page_info.page_size- assert page_size is not None-- if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:- if not paras_of_layout:- continue- page_markdown = blocks_to_markdown(- para_blocks=paras_of_layout,- img_bucket_path=img_bucket_path,- table_as_image=not table_enable,- formula_as_image=not formula_enable,- no_rich_content=(make_mode == MakeMode.NLP_MD),- )- 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 = block_to_content_list(para_block, img_bucket_path, page_idx, page_size)- if para_content is not None:- output_content.append(para_content.to_dict())- 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_bucket_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 Nonediff --git a/mineru/cli/client_side_output.py b/mineru/cli/client_side_output.pyindex ec690866..329b924e 100644--- a/mineru/cli/client_side_output.py+++ b/mineru/cli/client_side_output.py@@ -3,23 +3,15 @@ from __future__ import annotationsimport jsonfrom pathlib import Path-from typing import Any, Callable+from typing import Any-from mineru.utils.enum_class import MakeMode+from mineru.render import render_content_list, render_content_list_v2, render_markdownfrom mineru.utils.title_level_postprocess import finalize_client_side_middle_json-PDF_BACKENDS = {"pipeline", "vlm", "hybrid"}SUPPORTED_BACKENDS = {*PDF_BACKENDS, "office"}-def _select_union_make(backend: str) -> Callable[[list, str, str], Any]:- """根据 middle json 后端选择对应的 Markdown/content list 渲染函数。"""- from mineru.render import render_markdown-- return render_markdown--def _write_json(path: Path, payload: Any) -> None:"""按项目现有格式写入 JSON 文件,保持中文内容可读。"""path.write_text(@@ -48,9 +40,7 @@ def regenerate_client_side_outputs(backend = middle_json.get("_backend")pdf_info = middle_json.get("pdf_info")if backend not in SUPPORTED_BACKENDS:- raise ValueError(- f"Unsupported middle json backend for client-side output generation: {backend}"- )+ raise ValueError(f"Unsupported middle json backend for client-side output generation: {backend}")if not isinstance(pdf_info, list):raise ValueError("middle_json must contain a list field named pdf_info.")@@ -58,20 +48,19 @@ def regenerate_client_side_outputs(finalize_client_side_middle_json(middle_json)pdf_info = middle_json["pdf_info"]- make_func = _select_union_make(backend)image_dir = "images"markdown_path.write_text(- make_func(pdf_info, MakeMode.MM_MD, image_dir),+ render_markdown(pdf_info, image_dir),encoding="utf-8",)_write_json(content_list_path,- make_func(pdf_info, MakeMode.CONTENT_LIST, image_dir),+ render_content_list(pdf_info, image_dir),)_write_json(content_list_v2_path,- make_func(pdf_info, MakeMode.CONTENT_LIST_V2, image_dir),+ render_content_list_v2(pdf_info, image_dir),)if backend in PDF_BACKENDS:_write_json(middle_json_path, middle_json)diff --git a/mineru/cli/common.py b/mineru/cli/common.pyindex d259e38e..b2d305eb 100644--- a/mineru/cli/common.py+++ b/mineru/cli/common.py@@ -21,7 +21,6 @@ from mineru.data.data_reader_writer import FileBasedDataWriterfrom mineru.render import render_content_list, render_content_list_v2, render_markdownfrom mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bboxfrom mineru.utils.engine_utils import get_vlm_engine-from mineru.utils.enum_class import MakeModefrom mineru.utils.guess_suffix_or_lang import guess_suffix_by_bytesfrom mineru.utils.pdf_image_tools import images_bytes_to_pdf_bytesfrom mineru.utils.pdfium_guard import get_loadable_pdfium_page_indices, rewrite_pdf_bytes_with_pdfium@@ -283,7 +282,11 @@ def _process_output(image_dir = str(os.path.basename(local_image_dir))if f_dump_md:- md_content_str = render_markdown(middle_json, image_dir, make_mode=f_make_md_mode)+ md_content_str = render_markdown(+ middle_json,+ image_dir,+ no_rich_content=(f_make_md_mode != "mm_markdown"),+ )md_writer.write_string(f"{pdf_file_name}.md",md_content_str,@@ -664,7 +667,7 @@ def _process_office_doc(f_dump_model_output: bool = True,f_dump_orig_file: bool = True,f_dump_content_list: bool = True,- f_make_md_mode: MakeMode = MakeMode.MM_MD,+ f_make_md_mode: str = "mm_markdown",) -> list[int]:need_remove_index = []for i, file_bytes in enumerate(pdf_bytes_list):@@ -733,7 +736,7 @@ def do_parse(f_dump_model_output: bool = True,f_dump_orig_pdf: bool = True,f_dump_content_list: bool = True,- f_make_md_mode: MakeMode = MakeMode.MM_MD,+ f_make_md_mode: str = "mm_markdown",start_page_id: int = 0,end_page_id: int | None = None,image_analysis: bool = True,@@ -869,7 +872,7 @@ async def aio_do_parse(f_dump_model_output: bool = True,f_dump_orig_pdf: bool = True,f_dump_content_list: bool = True,- f_make_md_mode: MakeMode = MakeMode.MM_MD,+ f_make_md_mode: str = "mm_markdown",start_page_id: int = 0,end_page_id: int | None = None,image_analysis: bool = True,diff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.pyindex 284286a7..cc837171 100644--- a/mineru/model/docx/docx_converter.py+++ b/mineru/model/docx/docx_converter.py@@ -2,26 +2,30 @@import refrom io import BytesIOfrom pathlib import Path-from typing import BinaryIO, Optional, Union, Any, Final, Iterator+from typing import Any, BinaryIO, Final, Iterator, Optional, Union-from loguru import loggerfrom docx import Documentfrom docx.document import Document as DocxDocumentfrom docx.enum.style import WD_STYLE_TYPEfrom docx.oxml.xmlchemy import BaseOxmlElement-from docx.text.paragraph import Paragraphfrom docx.text.hyperlink import Hyperlink+from docx.text.paragraph import Paragraphfrom docx.text.run import Run+from loguru import loggerfrom lxml import etree-from pydantic import AnyUrlfrom mammoth.conversion import convert_document_element_to_htmlfrom mammoth.docx import body_xml+from pydantic import AnyUrl+from mineru.backend.utils.office_chart import extract_chart_html_from_ooxml+from mineru.backend.utils.office_image import (+ serialize_office_image,+)from mineru.model.docx.package_normalizer import normalize_docx_package-from mineru.model.docx.tools.office_xml import read_strfrom mineru.model.docx.tools.math.omml import oMath2Latex+from mineru.model.docx.tools.office_xml import read_str+from mineru.types import BlockTypefrom mineru.utils.docx_formatting import Formatting, Script-from mineru.utils.enum_class import BlockType, ContentTypefrom mineru.utils.office_rich_text import (append_rich_text_element,build_text_mappings_from_elements,@@ -35,10 +39,7 @@ from mineru.utils.office_rich_text import (normalize_format_for_text,should_keep_group_text,)-from mineru.backend.utils.office_image import (- serialize_office_image,-)-from mineru.backend.utils.office_chart import extract_chart_html_from_ooxml+class DocxConverter:_BLIP_NAMESPACES: Final = {@@ -78,27 +79,19 @@ class DocxConverter:"""def __init__(self):- self.XML_KEY = (- "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val"- )- self.xml_namespaces = {- "w": "http://schemas.microsoft.com/office/word/2003/wordml"- }- self.picture_xpath_expr = etree.XPath(- ".//a:blip | .//v:imagedata", namespaces=DocxConverter._BLIP_NAMESPACES- )+ self.XML_KEY = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val"+ self.xml_namespaces = {"w": "http://schemas.microsoft.com/office/word/2003/wordml"}+ self.picture_xpath_expr = etree.XPath(".//a:blip | .//v:imagedata", namespaces=DocxConverter._BLIP_NAMESPACES)self.docx_obj = Noneself.pages = []self.cur_page = []- self._mammoth_tables_html: list = [] # 与正文顶层表格对齐的 mammoth 预解析 HTML,None 表示回退解析- self._mammoth_table_idx: int = 0 # 当前预解析表格游标+ self._mammoth_tables_html: list = [] # 与正文顶层表格对齐的 mammoth 预解析 HTML,None 表示回退解析+ self._mammoth_table_idx: int = 0 # 当前预解析表格游标self.pre_num_id: int = -1 # 上一个处理元素的 numIdself.pre_ilevel: int = -1 # 上一个处理元素的缩进等级, 用于判断列表层级self.list_block_stack: list = [] # 列表块堆栈- self.list_counters: dict[tuple[int, int], int] = (- {}- ) # 列表计数器 (numId, ilvl) -> count+ self.list_counters: dict[tuple[int, int], int] = {} # 列表计数器 (numId, ilvl) -> countself.index_block_stack: list = [] # 目录索引块堆栈self.pre_index_ilevel: int = -1 # 上一个目录项的缩进等级self.plain_toc_base_level: Optional[int] = None # 普通目录段落的起始层级@@ -108,9 +101,7 @@ class DocxConverter:self.toc_anchor_set: set[str] = set() # TOC 超链接目标锚点集合self._numbering_root: Optional[BaseOxmlElement] = Noneself._numbering_root_loaded: bool = False- self._numbering_level_cache: dict[- tuple[int, int], Optional[BaseOxmlElement]- ] = {}+ self._numbering_level_cache: dict[tuple[int, int], Optional[BaseOxmlElement]] = {}self._numbering_start_cache: dict[tuple[int, int], int] = {}self._style_lookup_cache: dict[tuple[Any, Optional[str]], Any] = {}self._style_bool_cache: dict[tuple[int, str], Optional[bool]] = {}@@ -361,9 +352,7 @@ class DocxConverter:@staticmethoddef _append_paragraph_element(- paragraph_elements: list[- tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]- ],+ paragraph_elements: list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]],text: str,format_obj: Optional[Formatting],hyperlink: Optional[Union[AnyUrl, Path, str]],@@ -429,9 +418,7 @@ class DocxConverter:@classmethoddef _format_hyperlink_group(cls,- group: list[- tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]- ],+ group: list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]],) -> str:"""将连续同 URL 的 hyperlink 片段输出为一个外层 hyperlink 标记。"""return format_hyperlink_group(group)@@ -439,18 +426,14 @@ class DocxConverter:@classmethoddef _build_text_mappings_from_elements(cls,- paragraph_elements: list[- tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]- ],+ paragraph_elements: list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]],) -> list[tuple[str, str]]:"""按连续同 URL hyperlink 分组,生成原文到富文本标记的映射。"""return build_text_mappings_from_elements(paragraph_elements)def _build_text_from_elements(self,- paragraph_elements: list[- tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]- ],+ paragraph_elements: list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]],) -> str:"""从 paragraph_elements 重组文本,应用超链接格式和字体样式。@@ -461,12 +444,7 @@ class DocxConverter:Returns:str: 重组后的文本"""- result_parts = [- formatted_text- for _, formatted_text in self._build_text_mappings_from_elements(- paragraph_elements- )- ]+ result_parts = [formatted_text for _, formatted_text in self._build_text_mappings_from_elements(paragraph_elements)]return "".join(result_parts) if result_parts else ""@staticmethod@@ -510,7 +488,7 @@ class DocxConverter:# 计算各非公式片段的累积结束位置,作为分割边界boundaries: set[int] = set()pos = 0- for seg in non_eq_segments[:-1]: # 最后一个片段后无需分割+ for seg in non_eq_segments[:-1]: # 最后一个片段后无需分割pos += len(seg)boundaries.add(pos)@@ -527,7 +505,7 @@ class DocxConverter:# 在边界处分割元素result = []text_pos = 0- for (text, fmt, hyperlink) in paragraph_elements:+ for text, fmt, hyperlink in paragraph_elements:if not text:result.append((text, fmt, hyperlink))text_pos += len(text)@@ -538,9 +516,7 @@ class DocxConverter:text_pos = elem_end# 找到落在该元素内部的分割点- splits_in_elem = sorted(- b - elem_start for b in boundaries if elem_start < b < elem_end- )+ splits_in_elem = sorted(b - elem_start for b in boundaries if elem_start < b < elem_end)if not splits_in_elem:result.append((text, fmt, hyperlink))@@ -594,10 +570,7 @@ class DocxConverter:current_group = []current_len = 0segment_index += 1- while (- segment_index < len(non_eq_segments)- and non_eq_segments[segment_index] == ""- ):+ while segment_index < len(non_eq_segments) and non_eq_segments[segment_index] == "":groups.append([])segment_index += 1elif current_len > target_len:@@ -609,9 +582,7 @@ class DocxConverter:def _build_text_with_equations_and_hyperlinks(self,- paragraph_elements: list[- tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]- ],+ paragraph_elements: list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]],text_with_equations: str,equations: list,) -> str:@@ -632,20 +603,13 @@ class DocxConverter:# 检查是否有超链接has_hyperlink = any(- hyperlink is not None and str(hyperlink).strip() not in ("", ".")- for _, _, hyperlink in paragraph_elements+ hyperlink is not None and str(hyperlink).strip() not in ("", ".") for _, _, hyperlink in paragraph_elements)# 检查是否有字体样式has_style = any(- fmt is not None and (- fmt.bold- or fmt.italic- or fmt.underline- or fmt.emphasis- or fmt.strikethrough- or fmt.script != Script.BASELINE- )+ fmt is not None+ and (fmt.bold or fmt.italic or fmt.underline or fmt.emphasis or fmt.strikethrough or fmt.script != Script.BASELINE)for _, fmt, _ in paragraph_elements)@@ -657,13 +621,11 @@ class DocxConverter:# 策略:在带公式的文本基础上,将样式/超链接标记插入到正确的位置# 0. 拆分 text_with_equations,获取各非公式片段,用于解决跨公式边界的元素合并问题- eq_split_pattern = re.compile(r'<eq>.*?</eq>', re.DOTALL)+ eq_split_pattern = re.compile(r"<eq>.*?</eq>", re.DOTALL)non_eq_segments = eq_split_pattern.split(text_with_equations)# 在公式边界处重新拆分段落元素,避免单个元素跨越多个非公式片段- paragraph_elements = self._split_paragraph_elements_at_eq_boundaries(- paragraph_elements, non_eq_segments- )+ paragraph_elements = self._split_paragraph_elements_at_eq_boundaries(paragraph_elements, non_eq_segments)# 1. 记录每个元素的原始文本和对应的格式化结果element_mappings = []@@ -671,24 +633,18 @@ class DocxConverter:paragraph_elements,non_eq_segments,):- element_mappings.extend(- self._build_text_mappings_from_elements(segment_elements)- )+ element_mappings.extend(self._build_text_mappings_from_elements(segment_elements))# 2. 在 text_with_equations 中定位每个元素的原始文本,然后替换为格式化后的文本result_text = text_with_equationsfor original_text, formatted_text in element_mappings:if original_text != formatted_text:# 只有当文本被格式化(添加样式或超链接)时才需要替换- result_text = self._replace_text_outside_equations(- result_text, original_text, formatted_text- )+ result_text = self._replace_text_outside_equations(result_text, original_text, formatted_text)return result_text- def _replace_text_outside_equations(- self, text: str, old_text: str, new_text: str- ) -> str:+ def _replace_text_outside_equations(self, text: str, old_text: str, new_text: str) -> str:"""在公式标记外替换文本。@@ -738,10 +694,7 @@ class DocxConverter:return Falsesect_type = sect_pr.find(f"{{{w_ns}}}type")- sect_val = (- sect_type.get(f"{{{w_ns}}}val", "continuous")- if sect_type is not None else "continuous"- )+ sect_val = sect_type.get(f"{{{w_ns}}}val", "continuous") if sect_type is not None else "continuous"if sect_val != "continuous":return False@@ -803,13 +756,9 @@ class DocxConverter:def _collect_toc_anchor_set(self) -> set[str]:"""Collect TOC hyperlink anchors from the entire document body."""- anchor_attr = (- "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}anchor"- )+ anchor_attr = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}anchor"anchors: set[str] = set()- for hl in self.docx_obj.element.body.findall(- ".//w:hyperlink", namespaces=DocxConverter._BLIP_NAMESPACES- ):+ for hl in self.docx_obj.element.body.findall(".//w:hyperlink", namespaces=DocxConverter._BLIP_NAMESPACES):anchor = hl.get(anchor_attr, "").strip()if anchor and anchor.startswith("_Toc"):anchors.add(anchor)@@ -828,9 +777,7 @@ class DocxConverter:picture_refs = self.picture_xpath_expr(element)# 查找所有绘图元素(用于处理DrawingML)- drawingml_els = element.findall(- ".//w:drawing", namespaces=DocxConverter._BLIP_NAMESPACES- )+ drawingml_els = element.findall(".//w:drawing", namespaces=DocxConverter._BLIP_NAMESPACES)if drawingml_els:self._handle_drawingml(drawingml_els)@@ -862,16 +809,10 @@ class DocxConverter:shape_text_elements = shape_text_xpath(element)if shape_text_elements:# 从形状文本创建自定义文本元素- text_content = " ".join(- [t.text for t in shape_text_elements if t.text]- )- text_content = self._normalize_text_block_content(- text_content- )+ text_content = " ".join([t.text for t in shape_text_elements if t.text])+ text_content = self._normalize_text_block_content(text_content)if text_content.strip():- logger.debug(- f"Found shape text: {text_content[:50]}..."- )+ logger.debug(f"Found shape text: {text_content[:50]}...")self.cur_page.append({"type": BlockType.TEXT,@@ -883,9 +824,7 @@ class DocxConverter:for tb_element in textbox_elements:self.processed_textbox_elements.append(tb_element)- logger.debug(- f"Found textbox content with {len(textbox_elements)} elements"- )+ logger.debug(f"Found textbox content with {len(textbox_elements)} elements")self._handle_textbox_content(textbox_elements)if tag_name == "tbl":@@ -921,18 +860,14 @@ class DocxConverter:self._handle_text_elements(element)# 检查 sdt 元素elif tag_name == "sdt":- sdt_content = element.find(- ".//w:sdtContent", namespaces=DocxConverter._BLIP_NAMESPACES- )+ sdt_content = element.find(".//w:sdtContent", namespaces=DocxConverter._BLIP_NAMESPACES)if sdt_content is not None:if self._is_toc_sdt(element):# 处理目录SDT,转换为INDEX块self._handle_sdt_as_index(sdt_content)else:# 其他SDT元素,按普通文本处理- paragraphs = sdt_content.findall(- ".//w:p", namespaces=DocxConverter._BLIP_NAMESPACES- )+ paragraphs = sdt_content.findall(".//w:p", namespaces=DocxConverter._BLIP_NAMESPACES)for p in paragraphs:self._handle_text_elements(p)# 检查文本段落元素@@ -949,13 +884,7 @@ class DocxConverter:"""只保留 DOCX 正文顶层表格节点,避免 Mammoth 转换非表格正文。"""from mammoth import documents as _mammoth_documents- return document.copy(- children=[- child- for child in document.children- if isinstance(child, _mammoth_documents.Table)- ]- )+ return document.copy(children=[child for child in document.children if isinstance(child, _mammoth_documents.Table)])def _preparse_tables_with_mammoth(self, file_bytes: bytes) -> list:"""@@ -986,26 +915,19 @@ class DocxConverter:BytesIO(file_bytes),transform_document=self._mammoth_top_level_table_document,)- soup = _BeautifulSoup(result.value, 'html.parser')+ soup = _BeautifulSoup(result.value, "html.parser")# 仅保留顶层表格,排除嵌套在其他表格单元格内的子表格- all_tables = soup.find_all('table')- top_level_tables = [t for t in all_tables if not t.find_parent('table')]+ all_tables = soup.find_all("table")+ top_level_tables = [t for t in all_tables if not t.find_parent("table")]# 同步加载 DOCX XML,获取所有顶层表格元素,用于公式注入docx_obj = Document(BytesIO(file_bytes))- xml_top_tables = [- elem for elem in docx_obj.element.body- if self._local_name(elem) == 'tbl'- ]+ xml_top_tables = [elem for elem in docx_obj.element.body if self._local_name(elem) == "tbl"]- logger.debug(- f"Pre-parsed {len(top_level_tables)} top-level tables via filtered mammoth conversion"- )+ logger.debug(f"Pre-parsed {len(top_level_tables)} top-level tables via filtered mammoth conversion")- result_tables = self._align_mammoth_tables_to_xml_tables(- top_level_tables, xml_top_tables- )+ result_tables = self._align_mammoth_tables_to_xml_tables(top_level_tables, xml_top_tables)return result_tablesexcept Exception as e:logger.debug(f"Could not pre-parse tables with filtered mammoth conversion: {e}")@@ -1041,16 +963,11 @@ class DocxConverter:aligned_tables.append(None)continue- matched_html_table = self._inject_equations_into_table(- matched_html_table, xml_table- )+ matched_html_table = self._inject_equations_into_table(matched_html_table, xml_table)aligned_tables.append(str(matched_html_table))if len(html_tables) != len(xml_tables):- logger.debug(- f"Aligned {matched_count}/{len(xml_tables)} body tables from "- f"{len(html_tables)} mammoth tables"- )+ logger.debug(f"Aligned {matched_count}/{len(xml_tables)} body tables from {len(html_tables)} mammoth tables")return aligned_tables@staticmethod@@ -1065,9 +982,7 @@ class DocxConverter:html_signature = DocxConverter._html_table_signature(html_table)if xml_signature["text"] or html_signature["text"]:- if not DocxConverter._table_text_matches(- xml_signature["text"], html_signature["text"]- ):+ if not DocxConverter._table_text_matches(xml_signature["text"], html_signature["text"]):return Falsereturn (xml_signature["cell_count"] == html_signature["cell_count"]@@ -1083,11 +998,7 @@ class DocxConverter:@staticmethoddef _xml_table_signature(xml_table) -> dict:"""提取 XML 表格的轻量签名,用于与 Mammoth HTML 表格对齐。"""- text = "".join(- node.text or ""- for node in xml_table.xpath('.//*[local-name()="t"]')- if node.text- )+ text = "".join(node.text or "" for node in xml_table.xpath('.//*[local-name()="t"]') if node.text)return {"row_count": len(xml_table.xpath('./*[local-name()="tr"]')),"cell_count": len(xml_table.xpath('.//*[local-name()="tc"]')),@@ -1102,9 +1013,7 @@ class DocxConverter:"row_count": len(html_table.find_all("tr")),"cell_count": len(html_table.find_all(["td", "th"])),"image_count": len(html_table.find_all("img")),- "text": DocxConverter._normalize_table_match_text(- html_table.get_text("", strip=True)- ),+ "text": DocxConverter._normalize_table_match_text(html_table.get_text("", strip=True)),}@staticmethod@@ -1146,18 +1055,15 @@ class DocxConverter:from bs4 import BeautifulSoup- html_rows = html_table.find_all('tr')+ html_rows = html_table.find_all("tr")xml_rows = xml_table.findall(f"{{{W_NS}}}tr")if len(html_rows) != len(xml_rows):- logger.debug(- f"Table row count mismatch when injecting equations: "- f"HTML {len(html_rows)} vs XML {len(xml_rows)}"- )+ logger.debug(f"Table row count mismatch when injecting equations: HTML {len(html_rows)} vs XML {len(xml_rows)}")return html_tablefor html_row, xml_row in zip(html_rows, xml_rows):- html_cells = html_row.find_all(['td', 'th'])+ html_cells = html_row.find_all(["td", "th"])xml_cells = xml_row.findall(f"{{{W_NS}}}tc")if len(html_cells) != len(xml_cells):@@ -1171,7 +1077,7 @@ class DocxConverter:new_content = self._build_cell_html_with_equations(xml_cell)if new_content:html_cell.clear()- new_soup = BeautifulSoup(new_content, 'html.parser')+ new_soup = BeautifulSoup(new_content, "html.parser")for child in list(new_soup.children):html_cell.append(child)@@ -1198,12 +1104,12 @@ class DocxConverter:child_tag = self._local_name(child)if child_tag is None:continue- if child_tag == 'p':+ if child_tag == "p":para_html = self._build_paragraph_html_with_equations(child)if para_html is not None:parts.append(para_html)# 嵌套表格暂不处理,由外层逻辑负责- return ''.join(parts)+ return "".join(parts)def _build_paragraph_html_with_equations(self, xml_para) -> Optional[str]:"""@@ -1228,11 +1134,11 @@ class DocxConverter:continuetag = subt.tag# 普通文本节点(排除 math 命名空间下的 <m:t>)- if tag_name == 't' and 'math' not in tag:+ if tag_name == "t" and "math" not in tag:if isinstance(subt.text, str) and subt.text:items.append(subt.text)# OMML 公式元素(排除 oMathPara 容器避免重复处理)- elif 'oMath' in tag and 'oMathPara' not in tag:+ elif "oMath" in tag and "oMathPara" not in tag:try:latex = str(oMath2Latex(subt)).strip()if latex:@@ -1242,7 +1148,7 @@ class DocxConverter:if not items:return None- return f'<p>{"".join(items)}</p>'+ return f"<p>{''.join(items)}</p>"def _handle_tables(self, element: BaseOxmlElement):"""@@ -1305,15 +1211,16 @@ class DocxConverter:str: 修正后的 HTML 字符串"""try:- from bs4 import BeautifulSoupfrom collections import Counter- soup = BeautifulSoup(html, 'html.parser')- tables = soup.find_all('table')+ from bs4 import BeautifulSoup++ soup = BeautifulSoup(html, "html.parser")+ tables = soup.find_all("table")modified = Falsefor table in tables:- rows = table.find_all('tr')+ rows = table.find_all("tr")if not rows:continue@@ -1321,15 +1228,15 @@ class DocxConverter:# 无法反映真实网格宽度(被 rowspan 占据的列不出现在后续行的 td# 列表中),此时算法的假设不成立,跳过该表格以避免误修改合法的# colspan。- all_cells = table.find_all(['td', 'th'])- if any(int(c.get('rowspan', 1)) > 1 for c in all_cells):+ all_cells = table.find_all(["td", "th"])+ if any(int(c.get("rowspan", 1)) > 1 for c in all_cells):continue# 计算每行的有效列数(所有单元格的 colspan 之和)row_col_counts = []for row in rows:- cells = row.find_all(['td', 'th'])- total = sum(int(c.get('colspan', 1)) for c in cells)+ cells = row.find_all(["td", "th"])+ total = sum(int(c.get("colspan", 1)) for c in cells)row_col_counts.append(total)if not row_col_counts:@@ -1348,20 +1255,20 @@ class DocxConverter:continueexcess = col_count - target- cells = row.find_all(['td', 'th'])+ cells = row.find_all(["td", "th"])for cell in cells:if excess <= 0:break- span = int(cell.get('colspan', 1))+ span = int(cell.get("colspan", 1))if span > 1:reduce_by = min(span - 1, excess)new_span = span - reduce_byif new_span == 1:- if 'colspan' in cell.attrs:- del cell['colspan']+ if "colspan" in cell.attrs:+ del cell["colspan"]else:- cell['colspan'] = str(new_span)+ cell["colspan"] = str(new_span)excess -= reduce_bymodified = True@@ -1387,9 +1294,7 @@ class DocxConverter:"""is_section_end = False- has_section_break = (- element.find(".//w:sectPr", namespaces=DocxConverter._BLIP_NAMESPACES) is not None- )+ has_section_break = element.find(".//w:sectPr", namespaces=DocxConverter._BLIP_NAMESPACES) is not Noneif has_section_break and not self._is_layout_only_section_break(element):# 如果没有text内容if element.text == "":@@ -1401,9 +1306,7 @@ class DocxConverter:paragraph_elements = self._get_paragraph_elements(paragraph)paragraph_text = self._get_paragraph_text(paragraph)paragraph_anchor = self._extract_paragraph_bookmark(element)- text, equations = self._handle_equations_in_text(- element=element, text=paragraph_text- )+ text, equations = self._handle_equations_in_text(element=element, text=paragraph_text)if text is None:return None@@ -1436,11 +1339,7 @@ class DocxConverter:numid = None# 处理列表- if (- numid is not None- and ilevel is not None- and p_style_id not in ["Title", "Heading"]- ):+ if numid is not None and ilevel is not None and p_style_id not in ["Title", "Heading"]:# 通过检查 numFmt 来确认这是否实际上是编号列表is_numbered = self._is_numbered_list(numid, ilevel)@@ -1449,9 +1348,7 @@ class DocxConverter:# 先关闭任何活跃的普通列表if self.pre_num_id != -1:self._close_active_list()- content_text = self._build_text_with_equations_and_hyperlinks(- paragraph_elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(paragraph_elements, text, equations)if content_text:title_block = {"type": BlockType.TITLE,@@ -1474,18 +1371,14 @@ class DocxConverter:# 列表项已处理,返回return Noneelif ( # 列表结束处理- numid is None- and self.pre_num_id != -1- and p_style_id not in ["Title", "Heading"]+ numid is None and self.pre_num_id != -1 and p_style_id not in ["Title", "Heading"]): # 关闭列表# 重置列表状态self._close_active_list()if p_style_id in ["Title"]:# 构建包含公式和超链接的文本- content_text = self._build_text_with_equations_and_hyperlinks(- paragraph_elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(paragraph_elements, text, equations)if content_text != "":title_block = {"type": BlockType.TITLE,@@ -1498,15 +1391,9 @@ class DocxConverter:self.cur_page.append(title_block)elif "Heading" in p_style_id:- is_numbered_style = (- numid is not None- and ilevel is not None- and self._is_numbered_list(numid, ilevel)- )+ is_numbered_style = numid is not None and ilevel is not None and self._is_numbered_list(numid, ilevel)# 构建包含公式和超链接的文本- content_text = self._build_text_with_equations_and_hyperlinks(- paragraph_elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(paragraph_elements, text, equations)if content_text != "":h_block = {"type": BlockType.TITLE,@@ -1519,9 +1406,7 @@ class DocxConverter:self.cur_page.append(h_block)elif len(equations) > 0:- if (paragraph_text is None or len(paragraph_text.strip()) == 0) and len(- text- ) > 0:+ if (paragraph_text is None or len(paragraph_text.strip()) == 0) and len(text) > 0:# 独立公式eq_block = {"type": BlockType.EQUATION,@@ -1530,9 +1415,7 @@ class DocxConverter:self.cur_page.append(eq_block)else:# 包含行内公式的文本块,同时支持超链接- content_text = self._build_text_with_equations_and_hyperlinks(- paragraph_elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(paragraph_elements, text, equations)content_text = self._normalize_text_block_content(content_text)if content_text != "":text_with_inline_eq_block = {@@ -1553,9 +1436,7 @@ class DocxConverter:"Quote",]:# 构建包含公式和超链接的文本- content_text = self._build_text_with_equations_and_hyperlinks(- paragraph_elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(paragraph_elements, text, equations)content_text = self._normalize_text_block_content(content_text)if content_text != "":text_block = {@@ -1568,9 +1449,7 @@ class DocxConverter:# 判断是否是 Captionelif self._is_caption(element):# 构建包含公式和超链接的文本- content_text = self._build_text_with_equations_and_hyperlinks(- paragraph_elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(paragraph_elements, text, equations)if content_text != "":caption_block = {"type": BlockType.CAPTION,@@ -1581,9 +1460,7 @@ class DocxConverter:# 文本样式名称不仅有默认值,还可能有用户自定义值# 因此我们将所有其他标签视为纯文本# 构建包含公式和超链接的文本- content_text = self._build_text_with_equations_and_hyperlinks(- paragraph_elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(paragraph_elements, text, equations)content_text = self._normalize_text_block_content(content_text)if content_text != "":text_block = {@@ -1609,13 +1486,9 @@ class DocxConverter:"""def get_docx_image_rel_id(image: Any) -> Optional[str]:- rel_id = image.get(- "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed"- )+ rel_id = image.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed")if not rel_id:- rel_id = image.get(- "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"- )+ rel_id = image.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id")return rel_iddef get_docx_image_part(image: Any) -> Optional[Any]:@@ -1683,24 +1556,21 @@ class DocxConverter:# 有可见样式的空白文本(如带下划线的空格)在视觉上是可见的,应予保留,# 因此跳过提前返回,交由后续完整 run 处理流程处理。has_visible_style_run = any(- isinstance(c, Run) and c.text and self._has_visible_style(self._get_format_from_run(c))- for c in inner_contents+ isinstance(c, Run) and c.text and self._has_visible_style(self._get_format_from_run(c)) for c in inner_contents)if not has_visible_style_run:return [("", None, None)]- paragraph_elements: list[- tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]- ] = []+ paragraph_elements: list[tuple[str, Optional[Formatting], Optional[Union[AnyUrl, Path, str]]]] = []group_text = ""previous_format = None# 字段代码超链接内联检测状态(处理 w:fldChar + w:instrText 形式的超链接)_W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"- _field_in = False # 当前是否在字段域内- _field_url = None # 当前字段域解析出的 URL- _field_phase = None # 'instr' 或 'result'- _field_acc_text = "" # 累积的显示文本+ _field_in = False # 当前是否在字段域内+ _field_url = None # 当前字段域解析出的 URL+ _field_phase = None # 'instr' 或 'result'+ _field_acc_text = "" # 累积的显示文本_field_acc_format = None # 首个显示 run 的格式# 遍历段落的 runs 并按格式分组@@ -1811,13 +1681,11 @@ class DocxConverter:text = c.texthyperlink = Noneraw_format = self._get_format_from_run(c)- preserve_blank_non_visible_style = (- self._should_preserve_blank_non_visible_style(- inner_contents,- content_index,- text,- raw_format,- )+ preserve_blank_non_visible_style = self._should_preserve_blank_non_visible_style(+ inner_contents,+ content_index,+ text,+ raw_format,)format = self._normalize_format_for_text(raw_format,@@ -1831,27 +1699,14 @@ class DocxConverter:has_visible_content = len(text.strip()) > 0 or self._has_visible_style(format)is_blank_text = bool(text) and not text.strip()format_changed = format != previous_format- has_visible_boundary = (- self._has_visible_style(previous_format)- or self._has_visible_style(format)- )- should_split_blank_boundary = (- is_blank_text- and bool(group_text)- and format_changed- and has_visible_boundary- )- if (has_visible_content and format_changed) or should_split_blank_boundary or (- hyperlink is not None- ):+ has_visible_boundary = self._has_visible_style(previous_format) or self._has_visible_style(format)+ should_split_blank_boundary = is_blank_text and bool(group_text) and format_changed and has_visible_boundary+ if (has_visible_content and format_changed) or should_split_blank_boundary or (hyperlink is not None):# 前一组有实质内容(非空或带可见样式的空白)时才保存preserve_plain_blank = (bool(group_text)and not group_text.strip()- and (- self._has_visible_style(previous_format)- or self._has_visible_style(format)- )+ and (self._has_visible_style(previous_format) or self._has_visible_style(format)))prev_has_visible = self._should_keep_group_text(group_text,@@ -1859,9 +1714,7 @@ class DocxConverter:preserve_plain_blank=preserve_plain_blank,)if prev_has_visible:- paragraph_elements.append(- (group_text, previous_format, None)- )+ paragraph_elements.append((group_text, previous_format, None))group_text = ""# 如果有超链接,则立即添加@@ -1928,9 +1781,7 @@ class DocxConverter:def _get_paragraph_text(self, paragraph: Paragraph) -> str:"""Return paragraph plain text, including inline ``w:sdt`` content."""- return self._get_paragraph_text_from_contents(- list(self._iter_paragraph_inner_content(paragraph))- )+ return self._get_paragraph_text_from_contents(list(self._iter_paragraph_inner_content(paragraph)))def _resolve_style_chain_bool(self,@@ -1984,9 +1835,7 @@ class DocxConverter:run_style = self._get_run_style(run)run_style_id = str(getattr(run_style, "style_id", "") or "").lower()run_style_name = str(getattr(run_style, "name", "") or "").lower()- is_hyperlink_style = (- run_style_id == "hyperlink" or "hyperlink" in run_style_name- )+ is_hyperlink_style = run_style_id == "hyperlink" or "hyperlink" in run_style_nameif not is_hyperlink_style:inherited = self._resolve_style_chain_bool(run_style, attr_name)if inherited is not None:@@ -2034,12 +1883,12 @@ class DocxConverter:# 检测着重符号 (w:em):独立保留为 emphasis,避免和真实下划线混淆。is_emphasis = False_W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"- rPr = run._element.find(f'{{{_W}}}rPr')+ rPr = run._element.find(f"{{{_W}}}rPr")if rPr is not None:- em = rPr.find(f'{{{_W}}}em')+ em = rPr.find(f"{{{_W}}}em")if em is not None:- em_val = em.get(f'{{{_W}}}val', '')- if em_val and em_val != 'none':+ em_val = em.get(f"{{{_W}}}val", "")+ if em_val and em_val != "none":is_emphasis = Trueis_sub = run.font.subscript or False@@ -2086,20 +1935,13 @@ class DocxConverter:logger.debug(f"Failed to convert OMML equation to LaTeX: {e}")continueif len(latex_equation) > 0:- only_equations.append(- self.equation_bookends.format(EQ=latex_equation)- )- texts_and_equations.append(- self.equation_bookends.format(EQ=latex_equation)- )+ only_equations.append(self.equation_bookends.format(EQ=latex_equation))+ texts_and_equations.append(self.equation_bookends.format(EQ=latex_equation))if len(only_equations) < 1:return text, []- if (- re.sub(r"\s+", "", "".join(only_texts)).strip()- != re.sub(r"\s+", "", text).strip()- ):+ if re.sub(r"\s+", "", "".join(only_texts)).strip() != re.sub(r"\s+", "", text).strip():# 如果我们无法重构初始原始文本# 不要尝试解析公式并返回原始文本return text, []@@ -2187,9 +2029,7 @@ class DocxConverter:return Nonereturn pPr.find(child_tag, namespaces=namespaces)- def _get_effective_numPr(- self, paragraph: Paragraph- ) -> Optional[BaseOxmlElement]:+ def _get_effective_numPr(self, paragraph: Paragraph) -> Optional[BaseOxmlElement]:"""Resolve paragraph numbering from direct properties, then style inheritance."""numPr = self._get_paragraph_property_child(paragraph._element, "w:numPr")if numPr is not None:@@ -2205,15 +2045,11 @@ class DocxConverter:def _get_effective_outline_level(self, paragraph: Paragraph) -> Optional[int]:"""Resolve outline level from paragraph properties or inherited styles."""- outline_lvl = self._get_paragraph_property_child(- paragraph._element, "w:outlineLvl"- )+ outline_lvl = self._get_paragraph_property_child(paragraph._element, "w:outlineLvl")if outline_lvl is None:for style in self._iter_style_chain(self._get_paragraph_style(paragraph)):style_element = getattr(style, "element", None)- outline_lvl = self._get_paragraph_property_child(- style_element, "w:outlineLvl"- )+ outline_lvl = self._get_paragraph_property_child(style_element, "w:outlineLvl")if outline_lvl is not None:break@@ -2222,9 +2058,7 @@ class DocxConverter:return self._str_to_int(outline_lvl.get(self.XML_KEY), None)- def _get_numId_and_ilvl(- self, paragraph: Paragraph- ) -> tuple[Optional[int], Optional[int]]:+ def _get_numId_and_ilvl(self, paragraph: Paragraph) -> tuple[Optional[int], Optional[int]]:"""获取段落的列表编号ID和层级。@@ -2250,9 +2084,7 @@ class DocxConverter:# numId=0 是 Word 中显式取消编号的信号,不能继续从样式继承编号层级。return numId_int, ilvl_intif numId_int is not None and ilvl_int is None:- ilvl_int = self._infer_numbering_ilvl_from_style(- numId_int, paragraph- )+ ilvl_int = self._infer_numbering_ilvl_from_style(numId_int, paragraph)return numId_int, ilvl_int@@ -2264,22 +2096,16 @@ class DocxConverter:if numbering_root is None:return None- namespaces = {- "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"- }+ namespaces = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}return numbering_root.find(f".//w:num[@w:numId='{numId}']",namespaces=namespaces,)- def _get_abstract_numbering_element(- self, numId: int- ) -> Optional[BaseOxmlElement]:+ def _get_abstract_numbering_element(self, numId: int) -> Optional[BaseOxmlElement]:"""根据 numId 获取对应的 abstractNum 定义,用于复用编号层级解析逻辑。"""numbering_root = self._get_numbering_root()- namespaces = {- "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"- }+ namespaces = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}if numbering_root is None:return None@@ -2287,9 +2113,7 @@ class DocxConverter:if num_element is None:return None- abstract_num_id_elem = num_element.find(- ".//w:abstractNumId", namespaces=namespaces- )+ abstract_num_id_elem = num_element.find(".//w:abstractNumId", namespaces=namespaces)if abstract_num_id_elem is None:return None@@ -2300,29 +2124,22 @@ class DocxConverter:abstract_num_xpath = f".//w:abstractNum[@w:abstractNumId='{abstract_num_id}']"return numbering_root.find(abstract_num_xpath, namespaces=namespaces)- def _infer_numbering_ilvl_from_style(- self, numId: int, paragraph: Paragraph- ) -> Optional[int]:+ def _infer_numbering_ilvl_from_style(self, numId: int, paragraph: Paragraph) -> Optional[int]:"""当 numPr 只有 numId 时,根据 numbering.xml 中的 pStyle 反查编号层级。"""abstract_num_element = self._get_abstract_numbering_element(numId)if abstract_num_element is None:return Nonestyle_ids = {- str(getattr(style, "style_id", "") or "")- for style in self._iter_style_chain(self._get_paragraph_style(paragraph))+ str(getattr(style, "style_id", "") or "") for style in self._iter_style_chain(self._get_paragraph_style(paragraph))}style_ids.discard("")if not style_ids:return None- namespaces = {- "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"- }+ namespaces = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}ilvl_attr = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}ilvl"- for lvl_element in abstract_num_element.findall(- ".//w:lvl", namespaces=namespaces- ):+ for lvl_element in abstract_num_element.findall(".//w:lvl", namespaces=namespaces):p_style = lvl_element.find("w:pStyle", namespaces=namespaces)if p_style is None:continue@@ -2347,26 +2164,20 @@ class DocxConverter:return self._numbering_root- def _get_numbering_level_definition(- self, numId: int, ilvl: int- ) -> Optional[BaseOxmlElement]:+ def _get_numbering_level_definition(self, numId: int, ilvl: int) -> Optional[BaseOxmlElement]:"""Resolve and cache the numbering level definition for a numId/ilvl pair."""cache_key = (numId, ilvl)if cache_key in self._numbering_level_cache:return self._numbering_level_cache[cache_key]numbering_root = self._get_numbering_root()- namespaces = {- "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"- }+ namespaces = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}lvl_element: Optional[BaseOxmlElement] = Noneabstract_num_element = self._get_abstract_numbering_element(numId)if numbering_root is not None and abstract_num_element is not None:lvl_xpath = f".//w:lvl[@w:ilvl='{ilvl}']"- lvl_element = abstract_num_element.find(- lvl_xpath, namespaces=namespaces- )+ lvl_element = abstract_num_element.find(lvl_xpath, namespaces=namespaces)self._numbering_level_cache[cache_key] = lvl_elementreturn lvl_element@@ -2377,9 +2188,7 @@ class DocxConverter:if cache_key in self._numbering_start_cache:return self._numbering_start_cache[cache_key]- namespaces = {- "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"- }+ namespaces = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}start = 1num_element = self._get_numbering_num_element(numId)if num_element is not None:@@ -2438,18 +2247,14 @@ class DocxConverter:lvl_element = self._get_numbering_level_definition(numId, ilvl)if lvl_element is None:return False- namespaces = {- "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"- }+ namespaces = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}# 获取 numFmt 元素num_fmt_element = lvl_element.find(".//w:numFmt", namespaces=namespaces)if num_fmt_element is None:return False- num_fmt = num_fmt_element.get(- "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val"- )+ num_fmt = num_fmt_element.get("{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val")# 编号格式包括: decimal, lowerRoman, upperRoman, lowerLetter, upperLetter# 项目符号格式包括: bullet@@ -2510,18 +2315,14 @@ class DocxConverter:return None# 构建 content_text,处理行内公式和超链接- content_text = self._build_text_with_equations_and_hyperlinks(- elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(elements, text, equations)content_text = self._normalize_text_block_content(content_text)if content_text == "":return None# 确定列表属性list_attribute = "ordered" if is_numbered else "unordered"- list_start = (- self._advance_list_counter(numid, ilevel) if is_numbered else None- )+ list_start = self._advance_list_counter(numid, ilevel) if is_numbered else None# 情况 1: 不存在上一个列表ID,或遇到了不同 numId 的新列表,创建新的顶层列表if self.pre_num_id == -1 or self.pre_num_id != numid:@@ -2568,8 +2369,7 @@ class DocxConverter:if not self.list_block_stack:logger.warning(- "Missing DOCX list parent for increased indent; "- f"numid={numid}, ilevel={ilevel}. Starting a new list block."+ f"Missing DOCX list parent for increased indent; numid={numid}, ilevel={ilevel}. Starting a new list block.")self.cur_page.append(child_list_block)self.list_block_stack.append(child_list_block)@@ -2612,10 +2412,7 @@ class DocxConverter:breakself.list_block_stack.pop()if not self.list_block_stack:- logger.warning(- "Malformed DOCX list nesting; "- f"numid={numid}, ilevel={ilevel}. Starting a new list block."- )+ logger.warning(f"Malformed DOCX list nesting; numid={numid}, ilevel={ilevel}. Starting a new list block.")list_block = {"type": BlockType.LIST,"attribute": list_attribute,@@ -2640,8 +2437,7 @@ class DocxConverter:elif self.pre_num_id == numid and self.pre_ilevel == ilevel:if not self.list_block_stack:logger.warning(- "Missing DOCX list block for same indent; "- f"numid={numid}, ilevel={ilevel}. Starting a new list block."+ f"Missing DOCX list block for same indent; numid={numid}, ilevel={ilevel}. Starting a new list block.")list_block = {"type": BlockType.LIST,@@ -2706,12 +2502,7 @@ class DocxConverter:except Exception:continue- if (- numid is not None- and ilevel is not None- and p_style_id not in ["Title", "Heading"]- and text- ):+ if numid is not None and ilevel is not None and p_style_id not in ["Title", "Heading"] and text:items.append(("list", numid, ilevel))if numid not in numid_ilvels:numid_ilvels[numid] = set()@@ -2738,15 +2529,10 @@ class DocxConverter:# 条件2:只保留真正的多级列表(出现过多于1种ilevel的numId)# 单级列表(如只有ilevel=0的内容条目列表)即使有正文段落穿插也不应转换为标题- heading_numids = {- nid for nid in heading_numids- if len(numid_ilvels.get(nid, set())) > 1- }+ heading_numids = {nid for nid in heading_numids if len(numid_ilvels.get(nid, set())) > 1}if heading_numids:- logger.debug(- f"Detected heading-style list numIds (will convert to title blocks): {heading_numids}"- )+ logger.debug(f"Detected heading-style list numIds (will convert to title blocks): {heading_numids}")return heading_numids@@ -2767,9 +2553,7 @@ class DocxConverter:# 方法1: 检查 w:sdtPr 中的 docPartGallerysdt_pr = element.find("w:sdtPr", namespaces=DocxConverter._BLIP_NAMESPACES)if sdt_pr is not None:- doc_part_gallery = sdt_pr.find(- ".//w:docPartGallery", namespaces=DocxConverter._BLIP_NAMESPACES- )+ doc_part_gallery = sdt_pr.find(".//w:docPartGallery", namespaces=DocxConverter._BLIP_NAMESPACES)if doc_part_gallery is not None:val = doc_part_gallery.get(self.XML_KEY, "")if "Table of Contents" in val or "toc" in val.lower():@@ -2783,21 +2567,16 @@ class DocxConverter:return True# 方法2: 检查内容段落的样式是否为 "TOC N" 格式- sdt_content = element.find(- "w:sdtContent", namespaces=DocxConverter._BLIP_NAMESPACES- )+ sdt_content = element.find("w:sdtContent", namespaces=DocxConverter._BLIP_NAMESPACES)if sdt_content is not None:- paragraphs = sdt_content.findall(- "w:p", namespaces=DocxConverter._BLIP_NAMESPACES- )+ paragraphs = sdt_content.findall("w:p", namespaces=DocxConverter._BLIP_NAMESPACES)for p in paragraphs[:5]: # 只检查前5个段落即可判断try:p_obj = Paragraph(p, self.docx_obj)paragraph_style = self._get_paragraph_style(p_obj)if paragraph_style and paragraph_style.name:style_name = paragraph_style.name- if re.match(r'^TOC\s*\d+$', style_name, re.IGNORECASE) or \- re.match(r'^目录\s*\d+$', style_name):+ if re.match(r"^TOC\s*\d+$", style_name, re.IGNORECASE) or re.match(r"^目录\s*\d+$", style_name):return Trueexcept Exception:continue@@ -2823,15 +2602,13 @@ class DocxConverter:return Nonestyle_name = paragraph_style.nameif style_name:- match = re.match(r'^(?:TOC|目录)\s*(\d+)$', style_name, re.IGNORECASE)+ match = re.match(r"^(?:TOC|目录)\s*(\d+)$", style_name, re.IGNORECASE)if match:level = int(match.group(1))return level - 1 # 转换为 0-basedreturn None- def _is_flat_list_toc(- self, items: list[tuple[int, str, list, list, Optional[str]]]- ) -> bool:+ def _is_flat_list_toc(self, items: list[tuple[int, str, list, list, Optional[str]]]) -> bool:"""检测目录是否为扁平列表(插图清单、列表清单等),这类目录的所有条目应在同一层级,不应嵌套。@@ -2845,9 +2622,7 @@ class DocxConverter:if not stripped:continuetotal_count += 1- if re.match(r'^[图表][\d\s.]', stripped) or re.match(- r'^(Figure|Table)\s+\d', stripped, re.IGNORECASE- ):+ if re.match(r"^[图表][\d\s.]", stripped) or re.match(r"^(Figure|Table)\s+\d", stripped, re.IGNORECASE):match_count += 1if total_count == 0:return False@@ -2866,7 +2641,7 @@ class DocxConverter:if toc_level == 0:return 0stripped = text.strip()- match = re.match(r'^(\d+(?:\.\d+)+)(?![\d.])', stripped)+ match = re.match(r"^(\d+(?:\.\d+)+)(?![\d.])", stripped)if match:parts = match.group(1).split(".")# 只用明确的多级章节号把异常偏深的 TOC 样式修浅,避免普通列表编号被提升层级。@@ -2908,9 +2683,7 @@ class DocxConverter:if not elements:return- content_text = self._build_text_with_equations_and_hyperlinks(- elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(elements, text, equations)content_text = self._normalize_text_block_content(content_text)if content_text == "":return@@ -3002,13 +2775,9 @@ class DocxConverter:def _extract_paragraph_bookmark(self, paragraph_element: BaseOxmlElement) -> Optional[str]:"""Extract a bookmark name from a paragraph, prioritizing TOC bookmarks."""- bookmark_name_attr = (- "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}name"- )+ bookmark_name_attr = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}name"names = []- for bm in paragraph_element.findall(- ".//w:bookmarkStart", namespaces=DocxConverter._BLIP_NAMESPACES- ):+ for bm in paragraph_element.findall(".//w:bookmarkStart", namespaces=DocxConverter._BLIP_NAMESPACES):name = bm.get(bookmark_name_attr, "").strip()if not name:continue@@ -3029,13 +2798,9 @@ class DocxConverter:def _extract_toc_target_anchor(self, paragraph_element: BaseOxmlElement) -> Optional[str]:"""Extract internal bookmark target from a TOC paragraph hyperlink."""- anchor_attr = (- "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}anchor"- )+ anchor_attr = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}anchor"anchors = []- for hl in paragraph_element.findall(- ".//w:hyperlink", namespaces=DocxConverter._BLIP_NAMESPACES- ):+ for hl in paragraph_element.findall(".//w:hyperlink", namespaces=DocxConverter._BLIP_NAMESPACES):anchor = hl.get(anchor_attr, "").strip()if anchor:anchors.append(anchor)@@ -3093,9 +2858,7 @@ class DocxConverter:Args:sdt_content: w:sdtContent XML元素"""- paragraphs = sdt_content.findall(- ".//w:p", namespaces=DocxConverter._BLIP_NAMESPACES- )+ paragraphs = sdt_content.findall(".//w:p", namespaces=DocxConverter._BLIP_NAMESPACES)# --- 第一阶段:收集所有条目 ---toc_items: list[tuple[int, str, list, list, Optional[str]]] = []@@ -3103,9 +2866,7 @@ class DocxConverter:try:p_obj = Paragraph(p, self.docx_obj)paragraph_elements = self._get_paragraph_elements(p_obj)- text, equations = self._handle_equations_in_text(- element=p, text=p_obj.text- )+ text, equations = self._handle_equations_in_text(element=p, text=p_obj.text)target_anchor = self._extract_toc_target_anchor(p)if target_anchor and target_anchor.startswith("_Toc"):self.toc_anchor_set.add(target_anchor)@@ -3119,9 +2880,7 @@ class DocxConverter:if toc_level is None:toc_level = 0- toc_items.append(- (toc_level, text, paragraph_elements, equations, target_anchor)- )+ toc_items.append((toc_level, text, paragraph_elements, equations, target_anchor))except Exception as e:logger.debug(f"Error collecting TOC paragraph: {e}")continue@@ -3194,9 +2953,7 @@ class DocxConverter:else:return [input_string]- def _str_to_int(- self, s: Optional[str], default: Optional[int] = 0- ) -> Optional[int]:+ def _str_to_int(self, s: Optional[str], default: Optional[int] = 0) -> Optional[int]:"""将字符串转换为整数。@@ -3226,9 +2983,7 @@ class DocxConverter:"""paragraph_elements = self._get_paragraph_elements(paragraph)paragraph_text = self._get_paragraph_text(paragraph)- text, equations = self._handle_equations_in_text(- element=paragraph._element, text=paragraph_text- )+ text, equations = self._handle_equations_in_text(element=paragraph._element, text=paragraph_text)if text is None:return ""@@ -3238,9 +2993,7 @@ class DocxConverter:return ""# 构建包含公式和超链接的文本- content_text = self._build_text_with_equations_and_hyperlinks(- paragraph_elements, text, equations- )+ content_text = self._build_text_with_equations_and_hyperlinks(paragraph_elements, text, equations)return content_text@@ -3316,16 +3069,14 @@ class DocxConverter:Returns:bool: 如果是标题返回 True,否则返回 False"""- instr_texts = element.findall(- ".//w:instrText", namespaces=DocxConverter._BLIP_NAMESPACES- )+ instr_texts = element.findall(".//w:instrText", namespaces=DocxConverter._BLIP_NAMESPACES)for instr in instr_texts:if instr.text and "SEQ" in instr.text:return Truereturn False-+def _handle_drawingml(self, elements: list[BaseOxmlElement]):"""处理 DrawingML 元素,目前先处理 chart 元素。@@ -3344,13 +3095,9 @@ class DocxConverter:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/package","http://purl.oclc.org/ooxml/officeDocument/relationships/package",}- rel_id_attr = (- "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"- )+ rel_id_attr = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"for element in elements:- chart = element.find(- ".//c:chart", namespaces=DocxConverter._BLIP_NAMESPACES- )+ chart = element.find(".//c:chart", namespaces=DocxConverter._BLIP_NAMESPACES)if chart is None:continue@@ -3437,9 +3184,7 @@ class DocxConverter:# 如果该段落(相同内容和位置)已处理,则跳过if paragraph_id in processed_paragraphs:- logger.debug(- f"Skipping duplicate paragraph: content='{text_content[:50]}...', position={position}"- )+ logger.debug(f"Skipping duplicate paragraph: content='{text_content[:50]}...', position={position}")continue# 将该段落标记为已处理@@ -3477,9 +3222,7 @@ class DocxConverter:if container_id not in container_paragraphs:container_paragraphs[container_id] = []- container_paragraphs[container_id].append(- (element, self._get_paragraph_position(element))- )+ container_paragraphs[container_id].append((element, self._get_paragraph_position(element)))# 处理 txbxContent 元素(Word DrawingML 文本框)elif tag_name == "txbxContent":@@ -3492,9 +3235,7 @@ class DocxConverter:p_id = id(p)if p_id not in processed_paragraphs:processed_paragraphs.append(p_id)- container_paragraphs[container_id].append(- (p, self._get_paragraph_position(p))- )+ container_paragraphs[container_id].append((p, self._get_paragraph_position(p)))else:# 尝试从未知元素中提取任何段落paragraphs = element.findall(".//w:p", namespaces=element.nsmap)@@ -3506,9 +3247,7 @@ class DocxConverter:p_id = id(p)if p_id not in processed_paragraphs:processed_paragraphs.append(p_id)- container_paragraphs[container_id].append(- (p, self._get_paragraph_position(p))- )+ container_paragraphs[container_id].append((p, self._get_paragraph_position(p)))return container_paragraphs@@ -3517,15 +3256,10 @@ class DocxConverter:从段落元素提取垂直位置信息。"""# 先尝试直接从包含顺序相关属性的 w:p 元素获取索引- if (- hasattr(paragraph_element, "getparent")- and paragraph_element.getparent() is not None- ):+ if hasattr(paragraph_element, "getparent") and paragraph_element.getparent() is not None:parent = paragraph_element.getparent()# 获取所有段落兄弟节点- paragraphs = [- p for p in parent.getchildren() if self._local_name(p) == "p"- ]+ paragraphs = [p for p in parent.getchildren() if self._local_name(p) == "p"]# 查找当前段落在其兄弟节点中的索引try:paragraph_index = paragraphs.index(paragraph_element)@@ -3578,8 +3312,4 @@ class DocxConverter:pass# 如果没有更好的位置指示,则使用 XML 源行号作为顺序的代理- return (- paragraph_element.sourceline- if hasattr(paragraph_element, "sourceline")- else None- )+ return paragraph_element.sourceline if hasattr(paragraph_element, "sourceline") else Nonediff --git a/mineru/model/pptx/pptx_converter.py b/mineru/model/pptx/pptx_converter.pyindex 799b6c45..6a64a290 100644--- a/mineru/model/pptx/pptx_converter.py+++ b/mineru/model/pptx/pptx_converter.py@@ -3,30 +3,23 @@ import base64from collections import Counterfrom dataclasses import dataclassfrom io import BytesIO-from typing import Any, Final, BinaryIO, Optional+from typing import Any, BinaryIO, Final, Optional+from loguru import loggerfrom lxml import etree+from PIL import Imagefrom pptx import Presentation, presentationfrom pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDERfrom pptx.oxml.text import CT_TextLineBreak-from loguru import logger-from PIL import Image-from mineru.utils.enum_class import BlockType-from mineru.backend.utils.office_image import (- PIL_IMAGE_LOAD_ERRORS,- is_vector_image,- serialize_vector_image_with_placeholder,-)-from mineru.model.docx.tools.math.omml import oMath2Latexfrom mineru.backend.utils.office_chart import extract_chart_html_from_ooxml+from mineru.backend.utils.office_image import PIL_IMAGE_LOAD_ERRORS, is_vector_image, serialize_vector_image_with_placeholder+from mineru.model.docx.tools.math.omml import oMath2Latexfrom mineru.model.office_stream import read_stream_bytes_from_start, rewind_streamfrom mineru.model.pptx.package_normalizer import normalize_pptx_packagefrom mineru.model.pptx.xycut_pp_sorter import sort_entries-from mineru.utils.office_rich_text import (- OfficeRichTextSegment,- build_rich_text_from_segments,-)+from mineru.types import BlockType+from mineru.utils.office_rich_text import OfficeRichTextSegment, build_rich_text_from_segmentsfrom mineru.utils.pdf_reader import image_to_b64strIGNORED_NOTES_PLACEHOLDER_TYPES: Final = {@@ -86,7 +79,6 @@ class _FlattenedShape:class PptxConverter:-def __init__(self):self.namespaces = {"a": "http://schemas.openxmlformats.org/drawingml/2006/main",@@ -341,11 +333,7 @@ class PptxConverter:@staticmethoddef _group_shape_transform(shape) -> _SlideTransform:group_properties = getattr(shape._element, "grpSpPr", None)- xfrm = (- getattr(group_properties, "xfrm", None)- if group_properties is not None- else None- )+ xfrm = getattr(group_properties, "xfrm", None) if group_properties is not None else Noneif xfrm is None:return _SlideTransform()@@ -366,12 +354,7 @@ class PptxConverter:except Exception:return _SlideTransform()- if (- extent_x <= 0- or extent_y <= 0- or child_extent_x <= 0- or child_extent_y <= 0- ):+ if extent_x <= 0 or extent_y <= 0 or child_extent_x <= 0 or child_extent_y <= 0:return _SlideTransform()scale_x = extent_x / child_extent_x@@ -524,10 +507,7 @@ class PptxConverter:return Falsecovered_area = self._rectangles_union_area(overlap_bboxes)- return (- covered_area / picture_area- >= BACKGROUND_PICTURE_TEXT_COVERAGE_RATIO- )+ return covered_area / picture_area >= BACKGROUND_PICTURE_TEXT_COVERAGE_RATIOdef _should_skip_picture(self,@@ -566,9 +546,7 @@ class PptxConverter:returnfor paragraph in shape.text_frame.paragraphs:- note_text = self._normalize_text_block_content(- self._build_paragraph_rich_text(paragraph, shape)- )+ note_text = self._normalize_text_block_content(self._build_paragraph_rich_text(paragraph, shape))if not note_text:continueself.cur_page.append(@@ -628,9 +606,7 @@ class PptxConverter:if (row_idx, col_idx) in occupied_cells:continue# 获取单元格XML以读取跨度信息- cell_xml = table_xml.xpath(- f".//a:tbl/a:tr[{row_idx + 1}]/a:tc[{col_idx + 1}]"- )+ cell_xml = table_xml.xpath(f".//a:tbl/a:tr[{row_idx + 1}]/a:tc[{col_idx + 1}]")if not cell_xml:continue@@ -665,11 +641,7 @@ class PptxConverter:# 获取单元格文本内容cell_text = cell.text.strip() if cell.text else ""# 转义HTML特殊字符,防止XSS- cell_text = (- cell_text.replace("&", "&")- .replace("<", "<")- .replace(">", ">")- )+ cell_text = cell_text.replace("&", "&").replace("<", "<").replace(">", ">")html_parts.append(f" <{tag}{attr_str}>{cell_text}</{tag}>")@@ -766,9 +738,7 @@ class PptxConverter:pil_image.load()return image_to_b64str(pil_image, image_format="JPEG")- if pil_image.mode in {"RGBA", "LA"} or (- pil_image.mode == "P" and "transparency" in pil_image.info- ):+ if pil_image.mode in {"RGBA", "LA"} or (pil_image.mode == "P" and "transparency" in pil_image.info):return image_to_b64str(pil_image.convert("RGBA"), image_format="PNG")return image_to_b64str(pil_image.convert("RGB"), image_format="JPEG")@@ -808,9 +778,7 @@ class PptxConverter:return Falsefor blip in blips:- if blip.get(f"{{{RELATIONSHIP_NS}}}embed") or blip.get(- f"{{{RELATIONSHIP_NS}}}link"- ):+ if blip.get(f"{{{RELATIONSHIP_NS}}}embed") or blip.get(f"{{{RELATIONSHIP_NS}}}link"):return Falsereturn True@@ -824,9 +792,7 @@ class PptxConverter:image_part = shape.part.related_part(relationship_id)image_bytes = image_part.blobexcept Exception as e:- logger.warning(- f"Warning: embedded image relation {relationship_id} cannot be loaded: {e}"- )+ logger.warning(f"Warning: embedded image relation {relationship_id} cannot be loaded: {e}")else:return image_bytes, getattr(image_part, "content_type", None)@@ -1046,9 +1012,7 @@ class PptxConverter:if hlink_click is None:return None- rid = hlink_click.get(- "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"- )+ rid = hlink_click.get("{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id")if not rid:return None@@ -1098,17 +1062,9 @@ class PptxConverter:@staticmethoddef _strip_math_delimiters(math_text: str) -> str:stripped = math_text.strip()- if (- stripped.startswith("$$")- and stripped.endswith("$$")- and len(stripped) >= 4- ):+ if stripped.startswith("$$") and stripped.endswith("$$") and len(stripped) >= 4:return stripped[2:-2].strip()- if (- stripped.startswith("$")- and stripped.endswith("$")- and len(stripped) >= 2- ):+ if stripped.startswith("$") and stripped.endswith("$") and len(stripped) >= 2:return stripped[1:-1].strip()return stripped@@ -1240,7 +1196,7 @@ class PptxConverter:if end_idx < 0:return []- return trimmed_segments[:end_idx + 1]+ return trimmed_segments[: end_idx + 1]@staticmethoddef _normalize_text_block_content(content: str) -> str:@@ -1406,9 +1362,7 @@ class PptxConverter:".//p:txBody",namespaces=self.namespaces,)- sources.extend(- self._get_font_sources_from_text_body(layout_tx_body, level)- )+ sources.extend(self._get_font_sources_from_text_body(layout_tx_body, level))try:placeholder_type = shape.placeholder_format.type@@ -1477,10 +1431,7 @@ class PptxConverter:run_font_size_pt,)- if (- self._resolve_effective_run_bold(run, paragraph_font_sources)- is not True- ):+ if self._resolve_effective_run_bold(run, paragraph_font_sources) is not True:all_bold = Falsereturn {@@ -1629,11 +1580,7 @@ class PptxConverter:start = int(list_block.get("start", 1))except (TypeError, ValueError):start = 1- direct_item_count = sum(- 1- for item in list_block.get("content", [])- if item.get("type") != BlockType.LIST- )+ direct_item_count = sum(1 for item in list_block.get("content", []) if item.get("type") != BlockType.LIST)return start + direct_item_countdef _should_restart_ordered_list(@@ -1737,32 +1684,19 @@ class PptxConverter:returnbold_font_sizes = sorted(- {- block[_EFFECTIVE_FONT_SIZE_KEY]- for block in bold_text_blocks- },+ {block[_EFFECTIVE_FONT_SIZE_KEY] for block in bold_text_blocks},reverse=True,)level2_font_size_pt = bold_font_sizes[0]- level2_candidates = [- block- for block in bold_text_blocks- if block[_EFFECTIVE_FONT_SIZE_KEY] == level2_font_size_pt- ]+ level2_candidates = [block for block in bold_text_blocks if block[_EFFECTIVE_FONT_SIZE_KEY] == level2_font_size_pt]if len(level2_candidates) != 1:return- if (- body_font_size_pt is not None- and level2_font_size_pt < body_font_size_pt + 4- ):+ if body_font_size_pt is not None and level2_font_size_pt < body_font_size_pt + 4:return- if (- len(bold_font_sizes) > 1- and level2_font_size_pt < bold_font_sizes[1] + 2- ):+ if len(bold_font_sizes) > 1 and level2_font_size_pt < bold_font_sizes[1] + 2:returnlevel2_candidates[0]["type"] = BlockType.TITLE@@ -1838,9 +1772,7 @@ class PptxConverter:list_info = self._get_paragraph_list_info(shape, paragraph)if list_info["is_list"]:- rich_text = self._normalize_text_block_content(- self._build_paragraph_rich_text(paragraph, shape)- )+ rich_text = self._normalize_text_block_content(self._build_paragraph_rich_text(paragraph, shape))if rich_text:if list_level_base is None:list_level_base = list_info["level"]@@ -1861,9 +1793,7 @@ class PptxConverter:self.list_block_stack.clear()list_level_base = None- p_text = self._normalize_text_block_content(- self._build_paragraph_rich_text(paragraph, shape)- )+ p_text = self._normalize_text_block_content(self._build_paragraph_rich_text(paragraph, shape))if not p_text:continue@@ -1929,9 +1859,7 @@ class PptxConverter:p = paragraph._elementif p.find(".//a:buChar", namespaces={"a": self.namespaces["a"]}) is not None:return (True, "Bullet")- elif (- p.find(".//a:buAutoNum", namespaces={"a": self.namespaces["a"]}) is not None- ):+ elif p.find(".//a:buAutoNum", namespaces={"a": self.namespaces["a"]}) is not None:return (True, "Numbered")elif paragraph.level > 0:# 很可能是子列表项(缩进表示嵌套)@@ -1977,9 +1905,7 @@ class PptxConverter:# 2) 形状级别的列表样式(txBody/a:lstStyle)txBody = shape._element.find(".//p:txBody", namespaces=self.namespaces)- is_list, kind, detail, start = self._parse_bullet_from_text_body_list_style(- txBody, lvl- )+ is_list, kind, detail, start = self._parse_bullet_from_text_body_list_style(txBody, lvl)if is_list is not None:return {"is_list": is_list,@@ -1996,9 +1922,7 @@ class PptxConverter:layout_ph = self._resolve_layout_placeholder(shape)if layout_ph is not None:- layout_tx = layout_ph._element.find(- ".//p:txBody", namespaces=self.namespaces- )+ layout_tx = layout_ph._element.find(".//p:txBody", namespaces=self.namespaces)(is_list,kind,@@ -2216,9 +2140,7 @@ class PptxConverter:tag = f"a:lvl{lvl + 1}pPr"return lstStyle.find(tag, namespaces=self.namespaces)- def _get_master_text_style_node(- self, slide_master, placeholder_type- ) -> Optional[etree._Element]:+ def _get_master_text_style_node(self, slide_master, placeholder_type) -> Optional[etree._Element]:"""获取占位符的相应主文本样式节点。大多数内容占位符(BODY/OBJECT)使用'p:bodyStyle',而标题使用'p:titleStyle'。@@ -2231,9 +2153,7 @@ class PptxConverter:Returns:从主幻灯片的'p:txStyles'中匹配的样式节点('p:bodyStyle'、'p:titleStyle'或'p:otherStyle'),或当未定义样式时返回None。"""- txStyles = slide_master._element.find(- ".//p:txStyles", namespaces=self.namespaces- )+ txStyles = slide_master._element.find(".//p:txStyles", namespaces=self.namespaces)if txStyles is None:return Nonediff --git a/mineru/model/xlsx/xlsx_converter.py b/mineru/model/xlsx/xlsx_converter.pyindex e62b0f93..b1c02830 100644--- a/mineru/model/xlsx/xlsx_converter.py+++ b/mineru/model/xlsx/xlsx_converter.py@@ -2,33 +2,29 @@import collectionsimport htmlimport posixpath-import zipfileimport reimport xml.etree.ElementTree as ET+import zipfilefrom io import BytesIO+from typing import Annotated, BinaryIO, castfrom urllib.parse import urlparse-from typing import BinaryIO, Annotated, cast-+from loguru import loggerfrom openpyxl import load_workbookfrom openpyxl.cell.rich_text import CellRichText+from openpyxl.drawing.image import Image as XlsImagefrom openpyxl.utils.cell import range_to_tuplefrom openpyxl.worksheet.worksheet import Worksheet-from openpyxl.drawing.image import Image as XlsImagefrom PIL import Image-from loguru import logger-from pydantic import PositiveInt, Field, BaseModel, NonNegativeInt+from pydantic import BaseModel, Field, NonNegativeInt, PositiveIntfrom pydantic.dataclasses import dataclass-from mineru.utils.enum_class import BlockType-from mineru.backend.utils.office_image import (- is_vector_image,- serialize_vector_image_with_placeholder,-)-from mineru.utils.pdf_reader import image_to_b64str+from mineru.backend.utils.office_image import is_vector_image, serialize_vector_image_with_placeholderfrom mineru.model.docx.tools.math.omml import oMath2Latexfrom mineru.model.office_stream import read_stream_bytes_from_start, rewind_streamfrom mineru.model.xlsx.package_normalizer import normalize_xlsx_package+from mineru.types import BlockType+from mineru.utils.pdf_reader import image_to_b64strAUTO_GAP_TOLERANCE_CANDIDATES = (0, 1, 2)AUTO_GAP_TOLERANCE_PREFERENCE = {1: 0, 0: 1, 2: 2}@@ -39,18 +35,10 @@ AUTO_GAP_TOLERANCE_PREFERENCE_MARGIN = 0.15class DataRegion:"""表示工作表中非空单元格的边界矩形区域。"""- min_row: Annotated[- PositiveInt, Field(description="Smallest row index (1-based index).")- ]- max_row: Annotated[- PositiveInt, Field(description="Largest row index (1-based index).")- ]- min_col: Annotated[- PositiveInt, Field(description="Smallest column index (1-based index).")- ]- max_col: Annotated[- PositiveInt, Field(description="Largest column index (1-based index).")- ]+ min_row: Annotated[PositiveInt, Field(description="Smallest row index (1-based index).")]+ max_row: Annotated[PositiveInt, Field(description="Largest row index (1-based index).")]+ min_col: Annotated[PositiveInt, Field(description="Smallest column index (1-based index).")]+ max_col: Annotated[PositiveInt, Field(description="Largest column index (1-based index).")]def width(self) -> PositiveInt:"""返回数据区域的列数。"""@@ -105,12 +93,8 @@ class _MergedCellLookup:def __init__(self, sheet: Worksheet):"""从工作表合并区域构建 0-based 坐标索引。"""- self._merged_row_intervals: dict[int, list[tuple[int, int]]] = (- collections.defaultdict(list)- )- self._hidden_row_intervals: dict[int, list[tuple[int, int]]] = (- collections.defaultdict(list)- )+ self._merged_row_intervals: dict[int, list[tuple[int, int]]] = collections.defaultdict(list)+ self._hidden_row_intervals: dict[int, list[tuple[int, int]]] = collections.defaultdict(list)self._anchor_spans: dict[tuple[int, int], tuple[int, int]] = {}for merged in sheet.merged_cells.ranges:@@ -128,9 +112,7 @@ class _MergedCellLookup:self._merged_row_intervals[row].append((min_col, max_col))hidden_start_col = min_col + 1 if row == min_row else min_colif hidden_start_col <= max_col:- self._hidden_row_intervals[row].append(- (hidden_start_col, max_col)- )+ self._hidden_row_intervals[row].append((hidden_start_col, max_col))for intervals in self._merged_row_intervals.values():intervals.sort()@@ -248,9 +230,7 @@ class XlsxConverter:self.cur_page = []self._convert_sheet(sheet)sheet_pages.append((sheet.title, self.cur_page))- if self._should_emit_sheet_titles(- [page for _, page in sheet_pages]- ):+ if self._should_emit_sheet_titles([page for _, page in sheet_pages]):self._prepend_sheet_titles(sheet_pages)self.pages.extend(page for _, page in sheet_pages)else:@@ -277,10 +257,7 @@ class XlsxConverter:returnfor sheet in self.workbook.worksheets:- if (- not self.include_hidden_sheets- and sheet.sheet_state != Worksheet.SHEETSTATE_VISIBLE- ):+ if not self.include_hidden_sheets and sheet.sheet_state != Worksheet.SHEETSTATE_VISIBLE:logger.debug(f"跳过隐藏工作表:{sheet.title}")continueyield sheet@@ -315,9 +292,7 @@ class XlsxConverter:anchor = image_info["anchor"]if anchor[0] is None or anchor[1] is None:continue- self.table_image_map[anchor].append(- f'<img src="{image_info["base64"]}" />'- )+ self.table_image_map[anchor].append(f'<img src="{image_info["base64"]}" />')used_cells, visual_artifacts = self._find_tables_in_sheet(sheet)visual_artifacts.extend(self._find_charts_in_sheet(sheet))@@ -449,19 +424,13 @@ class XlsxConverter:return anchor._from.row, anchor._from.colreturn None, None- def _get_block_sort_anchor(- self, row: int | None, col: int | None- ) -> tuple[int, int]:+ def _get_block_sort_anchor(self, row: int | None, col: int | None) -> tuple[int, int]:if row is None or col is None:return (10**9, 10**9)return row, coldef _build_block_from_excel_table(self, excel_table: ExcelTable) -> dict:- if (- self.treat_singleton_as_text- and len(excel_table.data) == 1- and self._can_render_singleton_as_text(excel_table)- ):+ if self.treat_singleton_as_text and len(excel_table.data) == 1 and self._can_render_singleton_as_text(excel_table):return {"type": BlockType.TEXT,"content": excel_table.data[0].text,@@ -472,9 +441,7 @@ class XlsxConverter:"content": self.excel_table_to_html(excel_table),}- def _find_tables_in_sheet(- self, sheet: Worksheet- ) -> tuple[set[tuple[int, int]], list[tuple[tuple[int, int], int, dict]]]:+ def _find_tables_in_sheet(self, sheet: Worksheet) -> tuple[set[tuple[int, int]], list[tuple[tuple[int, int], int, dict]]]:used_cells = set()visual_artifacts = []if self.workbook is not None:@@ -516,9 +483,7 @@ class XlsxConverter:def _iter_chart_reference_formulas(self, chart):for series in getattr(chart, "ser", []):for attr_name in ("cat", "val", "xVal", "yVal", "bubbleSize"):- formula = self._extract_chart_range_formula(- getattr(series, attr_name, None)- )+ formula = self._extract_chart_range_formula(getattr(series, attr_name, None))if formula:yield formula@@ -527,15 +492,16 @@ class XlsxConverter:if tx_formula:yield tx_formula- def _parse_chart_reference_formula(- self, formula: str, sheet_title: str- ) -> tuple[list[int], list[int]] | None:+ def _parse_chart_reference_formula(self, formula: str, sheet_title: str) -> tuple[list[int], list[int]] | None:try:- formula_sheet_name, (- min_col,- min_row,- max_col,- max_row,+ (+ formula_sheet_name,+ (+ min_col,+ min_row,+ max_col,+ max_row,+ ),) = range_to_tuple(formula)except ValueError:logger.debug("Skip unsupported chart reference formula: {}", formula)@@ -549,10 +515,7 @@ class XlsxConverter:)return None- if not all(- isinstance(bound, int)- for bound in (min_col, min_row, max_col, max_row)- ):+ if not all(isinstance(bound, int) for bound in (min_col, min_row, max_col, max_row)):logger.debug("Skip chart reference formula with open-ended bounds: {}",formula,@@ -563,9 +526,7 @@ class XlsxConverter:cols = list(range(min_col - 1, max_col))return rows, cols- def _collect_chart_source_axes(- self, sheet: Worksheet, chart- ) -> tuple[list[int], list[int]] | None:+ def _collect_chart_source_axes(self, sheet: Worksheet, chart) -> tuple[list[int], list[int]] | None:referenced_rows = set()referenced_cols = set()formulas_found = False@@ -621,9 +582,7 @@ class XlsxConverter:source_col=source_col,)- def _build_synthetic_table_from_sheet_selection(- self, sheet: Worksheet, rows: list[int], cols: list[int]- ) -> ExcelTable:+ def _build_synthetic_table_from_sheet_selection(self, sheet: Worksheet, rows: list[int], cols: list[int]) -> ExcelTable:selected_coords = {(row, col) for row in rows for col in cols}hidden_merge_cells = set()merge_spans = {}@@ -633,12 +592,8 @@ class XlsxConverter:if top_left not in selected_coords:continue- selected_rows = [- row for row in rows if mr.min_row - 1 <= row <= mr.max_row - 1- ]- selected_cols = [- col for col in cols if mr.min_col - 1 <= col <= mr.max_col - 1- ]+ selected_rows = [row for row in rows if mr.min_row - 1 <= row <= mr.max_row - 1]+ selected_cols = [col for col in cols if mr.min_col - 1 <= col <= mr.max_col - 1]if not selected_rows or not selected_cols:continue@@ -674,9 +629,7 @@ class XlsxConverter:data=data,)- def _find_charts_in_sheet(- self, sheet: Worksheet- ) -> list[tuple[tuple[int, int], int, dict]]:+ def _find_charts_in_sheet(self, sheet: Worksheet) -> list[tuple[tuple[int, int], int, dict]]:chart_artifacts = []for order, chart in enumerate(getattr(sheet, "_charts", [])):axes = self._collect_chart_source_axes(sheet, chart)@@ -753,18 +706,14 @@ class XlsxConverter:))- def _cell_has_semantic_content(- self, excel_table: ExcelTable, cell: ExcelCell- ) -> bool:+ def _cell_has_semantic_content(self, excel_table: ExcelTable, cell: ExcelCell) -> bool:return bool(cell.text.strip()or any(media.strip() for media in cell.media)or self._get_cell_math_formulas(excel_table.anchor, excel_cell=cell))- def _get_table_semantic_positions(- self, excel_table: ExcelTable- ) -> set[tuple[int, int]]:+ def _get_table_semantic_positions(self, excel_table: ExcelTable) -> set[tuple[int, int]]:semantic_positions = set()for cell in excel_table.data:if not self._cell_has_semantic_content(excel_table, cell):@@ -777,12 +726,8 @@ class XlsxConverter:)return semantic_positions- def _filter_semantic_subset_tables(- self, tables: list[ExcelTable]- ) -> list[ExcelTable]:- semantic_positions = [- self._get_table_semantic_positions(table) for table in tables- ]+ def _filter_semantic_subset_tables(self, tables: list[ExcelTable]) -> list[ExcelTable]:+ semantic_positions = [self._get_table_semantic_positions(table) for table in tables]filtered_tables = []for table_idx, table in enumerate(tables):@@ -797,17 +742,12 @@ class XlsxConverter:return filtered_tablesdef _build_table_content_mask(self, excel_table: ExcelTable) -> list[list[bool]]:- mask = [- [False for _ in range(excel_table.num_cols)]- for _ in range(excel_table.num_rows)- ]+ mask = [[False for _ in range(excel_table.num_cols)] for _ in range(excel_table.num_rows)]for cell in excel_table.data:if not self._cell_has_semantic_content(excel_table, cell):continuefor row_idx in range(cell.row, min(cell.row + cell.row_span, excel_table.num_rows)):- for col_idx in range(- cell.col, min(cell.col + cell.col_span, excel_table.num_cols)- ):+ for col_idx in range(cell.col, min(cell.col + cell.col_span, excel_table.num_cols)):mask[row_idx][col_idx] = Truereturn mask@@ -825,27 +765,18 @@ class XlsxConverter:@staticmethoddef _is_real_singleton_table(excel_table: ExcelTable) -> bool:- if (- excel_table.num_rows != 1- or excel_table.num_cols != 1- or len(excel_table.data) != 1- ):+ if excel_table.num_rows != 1 or excel_table.num_cols != 1 or len(excel_table.data) != 1:return Falsecell = excel_table.data[0]return cell.row_span == 1 and cell.col_span == 1- def _summarize_table_for_gap_selection(- self, excel_table: ExcelTable- ) -> dict[str, float | int | bool]:+ def _summarize_table_for_gap_selection(self, excel_table: ExcelTable) -> dict[str, float | int | bool]:table_area = excel_table.num_rows * excel_table.num_colscontent_mask = self._build_table_content_mask(excel_table)content_area = sum(sum(1 for flag in row if flag) for row in content_mask)blank_ratio = 1.0 - (content_area / max(table_area, 1))- interior_blank_rows = [- not any(content_mask[row_idx])- for row_idx in range(1, max(excel_table.num_rows - 1, 1))- ]+ interior_blank_rows = [not any(content_mask[row_idx]) for row_idx in range(1, max(excel_table.num_rows - 1, 1))]interior_blank_cols = [not any(content_mask[row_idx][col_idx] for row_idx in range(excel_table.num_rows))for col_idx in range(1, max(excel_table.num_cols - 1, 1))@@ -872,9 +803,7 @@ class XlsxConverter:"real_singleton": self._is_real_singleton_table(excel_table),}- def _summarize_candidate_tables(- self, tables: list[ExcelTable]- ) -> dict[str, float | int]:+ def _summarize_candidate_tables(self, tables: list[ExcelTable]) -> dict[str, float | int]:table_count = len(tables)real_singleton_count = 0severe_separator_count = 0@@ -891,18 +820,12 @@ class XlsxConverter:blank_ratio = float(table_summary["blank_ratio"])interior_blank_row_count = int(table_summary["interior_blank_row_count"])interior_blank_col_count = int(table_summary["interior_blank_col_count"])- max_consecutive_interior_blank_lines = int(- table_summary["max_consecutive_interior_blank_lines"]- )+ max_consecutive_interior_blank_lines = int(table_summary["max_consecutive_interior_blank_lines"])total_area += table_areaweighted_blank_numerator += table_area * blank_ratio- total_interior_blank_lines += (- interior_blank_row_count + interior_blank_col_count- )- total_possible_interior_lines += max(table.num_rows - 2, 0) + max(- table.num_cols - 2, 0- )+ total_interior_blank_lines += interior_blank_row_count + interior_blank_col_count+ total_possible_interior_lines += max(table.num_rows - 2, 0) + max(table.num_cols - 2, 0)for row_idx in range(table.anchor[1], table.anchor[1] + table.num_rows):row_cover_count[row_idx] += 1@@ -914,23 +837,18 @@ class XlsxConverter:severe_separator_count += 1occupied_row_count = max(len(row_cover_count), 1)- row_overlap_excess_ratio = sum(- max(0, count - 1) for count in row_cover_count.values()- ) / occupied_row_count+ row_overlap_excess_ratio = sum(max(0, count - 1) for count in row_cover_count.values()) / occupied_row_countreturn {"real_singleton_ratio": real_singleton_count / max(table_count, 1),"weighted_blank_ratio": weighted_blank_numerator / max(total_area, 1),- "interior_blank_line_ratio": total_interior_blank_lines- / max(total_possible_interior_lines, 1),+ "interior_blank_line_ratio": total_interior_blank_lines / max(total_possible_interior_lines, 1),"sparse_large_table_ratio": sparse_large_table_count / max(table_count, 1),"severe_separator_count": severe_separator_count,"row_overlap_excess_ratio": row_overlap_excess_ratio,}- def _select_best_gap_candidate(- self, sheet: Worksheet- ) -> tuple[int, float, list[ExcelTable]]:+ def _select_best_gap_candidate(self, sheet: Worksheet) -> tuple[int, float, list[ExcelTable]]:candidates = []for gap_tolerance in AUTO_GAP_TOLERANCE_CANDIDATES:raw_tables = self._find_data_tables_with_gap_raw(sheet, gap_tolerance)@@ -956,8 +874,7 @@ class XlsxConverter:near_best_candidates = [candidatefor candidate in candidates- if float(candidate["penalty"])- <= (min_penalty + AUTO_GAP_TOLERANCE_PREFERENCE_MARGIN)+ if float(candidate["penalty"]) <= (min_penalty + AUTO_GAP_TOLERANCE_PREFERENCE_MARGIN)]best_candidate = min(@@ -1065,12 +982,7 @@ class XlsxConverter:if self.workbook is not None:for image_info in self.sheet_images:r, c = image_info["anchor"]- if (- used_cells- and r is not None- and c is not None- and (r, c) in used_cells- ):+ if used_cells and r is not None and c is not None and (r, c) in used_cells:continueself.cur_page.append(@@ -1095,16 +1007,10 @@ class XlsxConverter:return self._select_best_tables(sheet)return self._find_data_tables_with_gap(sheet, self.gap_tolerance)- def _find_data_tables_with_gap(- self, sheet: Worksheet, gap_tolerance: int- ) -> list[ExcelTable]:- return self._filter_semantic_subset_tables(- self._find_data_tables_with_gap_raw(sheet, gap_tolerance)- )+ def _find_data_tables_with_gap(self, sheet: Worksheet, gap_tolerance: int) -> list[ExcelTable]:+ return self._filter_semantic_subset_tables(self._find_data_tables_with_gap_raw(sheet, gap_tolerance))- def _find_data_tables_with_gap_raw(- self, sheet: Worksheet, gap_tolerance: int- ) -> list[ExcelTable]:+ def _find_data_tables_with_gap_raw(self, sheet: Worksheet, gap_tolerance: int) -> list[ExcelTable]:"""在固定 gap_tolerance 下查找工作表中的所有数据表格。"""bounds: DataRegion = self._find_true_data_bounds(sheet) # 获取真实数据边界tables: list[ExcelTable] = [] # 存储已发现的表格@@ -1140,10 +1046,7 @@ class XlsxConverter:for cell in sheet._cells.values():if cell.value is None:continue- if not (- bounds.min_row <= cell.row <= bounds.max_row- and bounds.min_col <= cell.column <= bounds.max_col- ):+ if not (bounds.min_row <= cell.row <= bounds.max_row and bounds.min_col <= cell.column <= bounds.max_col):continuepositions.append((cell.row - 1, cell.column - 1))return sorted(positions)@@ -1175,12 +1078,8 @@ class XlsxConverter:# 将合并单元格的范围也纳入边界计算for merged in sheet.merged_cells.ranges:- min_row = (- merged.min_row if min_row is None else min(min_row, merged.min_row)- )- min_col = (- merged.min_col if min_col is None else min(min_col, merged.min_col)- )+ min_row = merged.min_row if min_row is None else min(min_row, merged.min_row)+ min_col = merged.min_col if min_col is None else min(min_col, merged.min_col)max_row = max(max_row, merged.max_row)max_col = max(max_col, merged.max_col)@@ -1345,9 +1244,7 @@ class XlsxConverter:zip_target_path = posixpath.normpath(posixpath.join("xl", cell_image_map.get(image_id, "")))if self.zf is None or zip_target_path not in self.zf.namelist():- logger.warning(- f"图片目标文件不存在,image_id={image_id}, target={zip_target_path}"- )+ logger.warning(f"图片目标文件不存在,image_id={image_id}, target={zip_target_path}")return ""try:@@ -1365,9 +1262,7 @@ class XlsxConverter:img_base64 = image_to_b64str(pil_image, image_format="JPEG")return rf'<img src="{img_base64}" />'except Exception as e:- logger.warning(- f"读取单元格图片失败,image_id={image_id}, target={zip_target_path}, error={e}"- )+ logger.warning(f"读取单元格图片失败,image_id={image_id}, target={zip_target_path}, error={e}")return ""def _load_cell_image_mappings(self):@@ -1379,10 +1274,7 @@ class XlsxConverter:cell_image_embed_to_name = {}cellimages_path = "xl/cellimages.xml"rels_path = "xl/_rels/cellimages.xml.rels"- if (- cellimages_path not in self.zf.namelist()- or rels_path not in self.zf.namelist()- ):+ if cellimages_path not in self.zf.namelist() or rels_path not in self.zf.namelist():return {}try:@@ -1403,25 +1295,21 @@ class XlsxConverter:continueimage_name = c_nv_pr.attrib.get("name")- embed_id = blip.attrib.get(f'{{{ns["r"]}}}embed')+ embed_id = blip.attrib.get(f"{{{ns['r']}}}embed")if image_name and embed_id:cell_image_embed_to_name[embed_id] = image_namewith self.zf.open(rels_path) as f:rel_root = ET.parse(f).getroot()- rel_ns = {- "pr": "http://schemas.openxmlformats.org/package/2006/relationships"- }+ rel_ns = {"pr": "http://schemas.openxmlformats.org/package/2006/relationships"}for rel in rel_root.findall("pr:Relationship", rel_ns):rel_id = rel.attrib.get("Id")target = rel.attrib.get("Target")if rel_id and target:image_name = cell_image_embed_to_name.get(rel_id)if not image_name:- logger.warning(- f"跳过缺少 cellImage 名称映射的关系: {rel_id}"- )+ logger.warning(f"跳过缺少 cellImage 名称映射的关系: {rel_id}")continueself.cell_image_map[image_name] = target@@ -1433,12 +1321,7 @@ class XlsxConverter:@staticmethoddef _escape_text_with_line_breaks(text: str) -> str:- return (- html.escape(text)- .replace("\r\n", "\n")- .replace("\r", "\n")- .replace("\n", "<br>")- )+ return html.escape(text).replace("\r\n", "\n").replace("\r", "\n").replace("\n", "<br>")@staticmethoddef _get_cell_hyperlink_target(cell) -> str:@@ -1521,17 +1404,13 @@ class XlsxConverter:if cell.value is None:return "", False- link_target = self._sanitize_hyperlink_target(- self._get_cell_hyperlink_target(cell)- )+ link_target = self._sanitize_hyperlink_target(self._get_cell_hyperlink_target(cell))if isinstance(cell.value, CellRichText):html_parts = []for part in cell.value:if hasattr(part, "text"):- part_text = self._escape_text_with_line_breaks(- str(getattr(part, "text", ""))- )+ part_text = self._escape_text_with_line_breaks(str(getattr(part, "text", "")))html_parts.append(self._apply_inline_font_tags(part_text,@@ -1565,11 +1444,7 @@ class XlsxConverter:style["text-decoration"] = "underline"if cell.font.strike:style["text-decoration"] = "line-through"- if (- cell.font.color- and hasattr(cell.font.color, "rgb")- and cell.font.color.rgb- ):+ if cell.font.color and hasattr(cell.font.color, "rgb") and cell.font.color.rgb:# Color might be ARGB "FF000000"color = cell.font.color.rgbif isinstance(color, str) and len(color) == 8:@@ -1586,11 +1461,7 @@ class XlsxConverter:if cell.fill and cell.fill.patternType == "solid" and cell.fill.fgColor:# handle bg colorcolor = cell.fill.fgColor.rgb- if (- hasattr(cell.fill.fgColor, "type")- and cell.fill.fgColor.type == "rgb"- and color- ):+ if hasattr(cell.fill.fgColor, "type") and cell.fill.fgColor.type == "rgb" and color:if isinstance(color, str) and len(color) == 8:style["background-color"] = "#" + color[2:]return style@@ -1607,6 +1478,4 @@ class XlsxConverter:返回:ContentLayer.INVISIBLE 或 None。"""- return (- None if sheet.sheet_state == Worksheet.SHEETSTATE_VISIBLE else "INVISIBLE"- )+ return None if sheet.sheet_state == Worksheet.SHEETSTATE_VISIBLE else "INVISIBLE"diff --git a/mineru/parser/parse_result.py b/mineru/parser/parse_result.pyindex e0614b1e..5ebec6c6 100644--- a/mineru/parser/parse_result.py+++ b/mineru/parser/parse_result.py@@ -11,26 +11,21 @@ from typing import Anyfrom mineru.render import render_content_list, render_content_list_v2, render_markdownfrom mineru.types import PageInfo-from ..utils.enum_class import MakeModefrom ..utils.pdf_document import PDFDocument_INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,([^\"]+)", re.DOTALL)-def _render_flash_markdown(pages: list, mode) -> str | list:+def _render_flash_markdown(pages: list) -> str | list:"""Minimal markdown renderer for flash: just concatenate text from spans."""- from ..utils.enum_class import MakeMode-- if mode == MakeMode.MM_MD:- parts: list[str] = []- for p in pages:- for block in getattr(p, "para_blocks", []):- for line in getattr(block, "lines", []):- for span in getattr(line, "spans", []):- if getattr(span, "content", ""):- parts.append(span.content)- return "\n\n".join(parts)- return []+ parts: list[str] = []+ for p in pages:+ for block in getattr(p, "para_blocks", []):+ for line in getattr(block, "lines", []):+ for span in getattr(line, "spans", []):+ if getattr(span, "content", ""):+ parts.append(span.content)+ return "\n\n".join(parts)@dataclass@@ -67,7 +62,7 @@ class ParseResult:def markdown(self) -> str:if self._backend == "flash":- return _render_flash_markdown(self.pages, MakeMode.MM_MD) # type: ignore[return-value]+ return _render_flash_markdown(self.pages)return render_markdown(self.pages)def markdown_with_markers(self, *, page_count: int | None = None) -> str:diff --git a/mineru/render/content_list.py b/mineru/render/content_list.pyindex f781e27b..2bd0ac1d 100644--- a/mineru/render/content_list.py+++ b/mineru/render/content_list.py@@ -1,8 +1,7 @@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations-from ..types import EMPTY_BBOX, BBox, Block, ContentItem, IntBBox-from ..utils.enum_class import BlockType, ContentType+from ..types import EMPTY_BBOX, BBox, Block, BlockType, ContentItem, ContentType, IntBBoxfrom .markdown import _build_media_path, _get_title_levelfrom .merge import _merge_para_text, merge_para_textfrom .merge_visual import _format_embedded_html, _inherit_parent_code_render_metadata, _normalize_visual_contentdiff --git a/mineru/render/markdown.py b/mineru/render/markdown.pyindex 6ed7bca6..42d54396 100644--- a/mineru/render/markdown.py+++ b/mineru/render/markdown.py@@ -1,5 +1,4 @@-from ..types import Block-from ..utils.enum_class import BlockType, ContentType+from ..types import Block, BlockType, ContentTypefrom .merge import merge_para_textfrom .merge_visual import _build_media_path, merge_visual_para_textdiff --git a/mineru/render/merge.py b/mineru/render/merge.pyindex 5346154d..53619071 100644--- a/mineru/render/merge.py+++ b/mineru/render/merge.py@@ -9,9 +9,8 @@ Markdown escaping.from __future__ import annotationsfrom ..backend.utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end-from ..types import Block, Line, Span+from ..types import Block, BlockType, ContentType, Line, Spanfrom ..utils.config_reader import get_latex_delimiter_config-from ..utils.enum_class import BlockType, ContentTypefrom ..utils.language import detect_langCJK_LANGS = frozenset({"zh", "ja", "ko"})diff --git a/mineru/render/merge_visual.py b/mineru/render/merge_visual.pyindex ab7e29ae..fc0f5753 100644--- a/mineru/render/merge_visual.py+++ b/mineru/render/merge_visual.py@@ -5,8 +5,7 @@ from copy import deepcopyfrom html import unescapefrom typing import Any-from ..types import Block-from ..utils.enum_class import BlockType, ContentType+from ..types import Block, BlockType, ContentTypefrom .merge import inline_left, inline_right, merge_para_text# --------------------------------------------------------------------------- #diff --git a/mineru/backend/office/mkcontent/inline_renderer.py b/mineru/render/office/merge.pysimilarity index 99%rename from mineru/backend/office/mkcontent/inline_renderer.pyrename to mineru/render/office/merge.pyindex 3b50bb9f..e024b723 100644--- a/mineru/backend/office/mkcontent/inline_renderer.py+++ b/mineru/render/office/merge.py@@ -7,10 +7,9 @@ from dataclasses import dataclass, fieldfrom html import escapefrom typing import Any-from ....types import Block, Span-from ....utils.config_reader import get_latex_delimiter_config-from ....utils.enum_class import BlockType, ContentType-from ...utils.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix+from ...backend.utils.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix+from ...types import Block, BlockType, ContentType, Span+from ...utils.config_reader import get_latex_delimiter_configlatex_delimiters_config = get_latex_delimiter_config()diff --git a/mineru/backend/office/mkcontent/output_builders.py b/mineru/render/office/output.pysimilarity index 91%rename from mineru/backend/office/mkcontent/output_builders.pyrename to mineru/render/office/output.pyindex 8cc6dbbb..4074f51c 100644--- a/mineru/backend/office/mkcontent/output_builders.py+++ b/mineru/render/office/output.py@@ -6,9 +6,8 @@ from collections.abc import Generatorfrom dataclasses import asdictfrom typing import Any-from ....types import Block, Line, PageInfo, Span-from ....utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeMode-from .inline_renderer import (+from ...types import Block, BlockType, ContentType, ContentTypeV2, Line, Span+from .merge import (_append_hyperlink_part,_append_text_part,_apply_configured_style,@@ -357,8 +356,10 @@ def _collect_caption_v2(para_block: Block, caption_type: str) -> list[dict[str,return caption_content-def mk_blocks_to_markdown(- para_blocks: list[Block], make_mode: MakeMode, img_bucket_path: str = "", page_idx: int | None = None+def blocks_to_markdown(+ para_blocks: list[Block],+ img_bucket_path: str = "",+ no_rich_content: bool = False,) -> list[str]:page_markdown = []for para_block in para_blocks:@@ -383,9 +384,8 @@ def mk_blocks_to_markdown(else:para_text = f"{'#' * title_level} {title_text}"elif para_type == BlockType.IMAGE:- # if make_mode == MakeMode.NLP_MD:- # continue- # elif make_mode == MakeMode.MM_MD:+ if no_rich_content:+ continuefor span in _iter_body_spans(para_block, BlockType.IMAGE_BODY, ContentType.IMAGE):if span:para_text += f""@@ -393,17 +393,15 @@ def mk_blocks_to_markdown(para_text += " \n" + caption_textelif para_type == BlockType.TABLE:- # if make_mode == MakeMode.NLP_MD:- # continue- # elif make_mode == MakeMode.MM_MD:+ if no_rich_content:+ continuefor span in _iter_body_spans(para_block, BlockType.TABLE_BODY, ContentType.TABLE):para_text += f"\n{_format_embedded_html(span.html, img_bucket_path)}\n"for caption_text in _collect_caption_texts(para_block, BlockType.TABLE_CAPTION):para_text += " \n" + caption_textelif para_type == BlockType.CHART:- # if make_mode == MakeMode.NLP_MD:- # continue- # elif make_mode == MakeMode.MM_MD:+ if no_rich_content:+ continueimage_path, chart_content = get_body_data(para_block)if chart_content:para_text += f"\n{_format_embedded_html(chart_content, img_bucket_path)}\n"@@ -714,42 +712,3 @@ def merge_para_with_text_v2(para_block: Block) -> list[dict[str, Any]]:rendered_span["type"] = ContentTypeV2.SPAN_EQUATION_INLINEpara_content.append(rendered_span)return para_content---def union_make(- pdf_info_dict: list[PageInfo],- make_mode: MakeMode,- img_bucket_path: str = "",-) -> list[str] | None:- output_content = []- for page_info in pdf_info_dict:- paras_of_layout = page_info.para_blocks- paras_of_discarded = page_info.discarded_blocks- page_idx = page_info.page_idx- 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, img_bucket_path, page_idx=page_idx)- 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_bucket_path, page_idx)- 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_bucket_path)- 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 Nonediff --git a/mineru/render/union_make.py b/mineru/render/union_make.pyindex 2b704dfc..43eaf510 100644--- a/mineru/render/union_make.py+++ b/mineru/render/union_make.py@@ -3,9 +3,9 @@ from __future__ import annotationsfrom typing import Any, Literal-from ..render.markdown import blocks_to_markdownfrom ..types import PageInfo-from ..utils.enum_class import MakeMode+from .markdown import blocks_to_markdown+from .office.output import blocks_to_markdown as office_blocks_to_markdownBackend = Literal["pipeline", "vlm", "hybrid", "office"]@@ -29,11 +29,11 @@ def _dispatch_make_content_list(page_size: Any,) -> Any:if backend == "office":- from ..backend.office.mkcontent.output_builders import make_blocks_to_content_list+ from .office.output import make_blocks_to_content_listreturn make_blocks_to_content_list(para_block, img_bucket_path, page_idx)- from ..render.content_list import block_to_content_list+ from .content_list import block_to_content_listitem = block_to_content_list(para_block, img_bucket_path, page_idx, page_size)if item is None:@@ -52,7 +52,7 @@ def _dispatch_make_content_list_v2(return make_blocks_to_content_list_v2(para_block, img_bucket_path, page_size)if backend == "office":- from ..backend.office.mkcontent.output_builders import make_blocks_to_content_list_v2+ from .office.output import make_blocks_to_content_list_v2return make_blocks_to_content_list_v2(para_block, img_bucket_path)# vlm / hybrid@@ -84,28 +84,31 @@ def render_markdown(pdf_info: list[PageInfo],img_bucket_path: str = "",*,- formula_enable: bool = True,- table_enable: bool = True,- make_mode: str = MakeMode.MM_MD,+ formula_enable: bool = True, # TODO+ table_enable: bool = True, # TODO+ no_rich_content: bool = False,) -> str:"""Render pages to a single Markdown string."""backend = _backend_from_pages(pdf_info)- if backend is None:- return ""- assert backend != "office", "temp not support"output_md: list[str] = []- for page_info in pdf_info:- paras_of_layout = page_info.para_blocks- if not paras_of_layout:- continue- page_md = blocks_to_markdown(- para_blocks=paras_of_layout,- img_bucket_path=img_bucket_path,- table_as_image=not table_enable,- formula_as_image=not formula_enable,- no_rich_content=(make_mode == MakeMode.NLP_MD),- )- output_md.extend(page_md)+ if backend == "office":+ for page_info in pdf_info:+ page_md = office_blocks_to_markdown(+ para_blocks=page_info.para_blocks,+ img_bucket_path=img_bucket_path,+ no_rich_content=no_rich_content,+ )+ output_md.extend(page_md)+ else: # PDF+ for page_info in pdf_info:+ page_md = blocks_to_markdown(+ para_blocks=page_info.para_blocks,+ img_bucket_path=img_bucket_path,+ table_as_image=not table_enable,+ formula_as_image=not formula_enable,+ no_rich_content=no_rich_content,+ )+ output_md.extend(page_md)return "\n\n".join(output_md)diff --git a/mineru/types.py b/mineru/types.pyindex af2ab0f0..dc65f680 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -9,20 +9,29 @@ T = TypeVar("T", bound="_DocElement")class BlockType:IMAGE = "image"- TABLE = "table"- CHART = "chart"IMAGE_BODY = "image_body"- TABLE_BODY = "table_body"- CHART_BODY = "chart_body"- CAPTION = "caption" # generic caption type (e.g., for Word documents)IMAGE_CAPTION = "image_caption"+ IMAGE_FOOTNOTE = "image_footnote"++ TABLE = "table"+ TABLE_BODY = "table_body"TABLE_CAPTION = "table_caption"+ TABLE_FOOTNOTE = "table_footnote"++ CHART = "chart"+ CHART_BODY = "chart_body"CHART_CAPTION = "chart_caption"+ CHART_FOOTNOTE = "chart_footnote"++ # Added in vlm 2.5+ CODE = "code"+ CODE_BODY = "code_body"+ CODE_CAPTION = "code_caption"+ CODE_FOOTNOTE = "code_footnote"++ CAPTION = "caption" # generic caption type (e.g., for Word documents)ALGORITHM_CAPTION = "algorithm_caption"FOOTNOTE = "footnote" # pp_layout中的vision_footnote- IMAGE_FOOTNOTE = "image_footnote"- TABLE_FOOTNOTE = "table_footnote"- CHART_FOOTNOTE = "chart_footnote"TEXT = "text"TITLE = "title"INTERLINE_EQUATION = "interline_equation"@@ -32,10 +41,6 @@ class BlockType:DISCARDED = "discarded"# Added in vlm 2.5- CODE = "code"- CODE_BODY = "code_body"- CODE_CAPTION = "code_caption"- CODE_FOOTNOTE = "code_footnote"ALGORITHM = "algorithm"REF_TEXT = "ref_text"PHONETIC = "phonetic"@@ -181,55 +186,51 @@ BLOCK_TYPES = {BlockType.FORMULA_NUMBER,}+NOT_EXTRACT_TYPES = {+ BlockType.TEXT,+ BlockType.TITLE,+ BlockType.HEADER,+ BlockType.FOOTER,+ BlockType.PAGE_NUMBER,+ BlockType.PAGE_FOOTNOTE,+ BlockType.REF_TEXT,+ BlockType.TABLE_CAPTION,+ BlockType.IMAGE_CAPTION,+ BlockType.TABLE_FOOTNOTE,+ BlockType.IMAGE_FOOTNOTE,+ BlockType.CODE_CAPTION,+ BlockType.PHONETIC,+}+# NOT_EXTRACT_TYPES = {# BlockType.TEXT,-# BlockType.TITLE,# BlockType.HEADER,# BlockType.FOOTER,# BlockType.PAGE_NUMBER,# BlockType.PAGE_FOOTNOTE,# BlockType.REF_TEXT,-# BlockType.TABLE_CAPTION,-# BlockType.IMAGE_CAPTION,-# BlockType.TABLE_FOOTNOTE,-# BlockType.IMAGE_FOOTNOTE,-# BlockType.CODE_CAPTION,# BlockType.PHONETIC,-# }-# HYBRID_OCR_DET_TEXT_TYPES = NOT_EXTRACT_TYPES-#-#-# class NotExtractType(Enum):-# TEXT = BlockType.TEXT-# TITLE = BlockType.TITLE-# HEADER = BlockType.HEADER-# FOOTER = BlockType.FOOTER-# PAGE_NUMBER = BlockType.PAGE_NUMBER-# PAGE_FOOTNOTE = BlockType.PAGE_FOOTNOTE-# REF_TEXT = BlockType.REF_TEXT-# TABLE_CAPTION = BlockType.TABLE_CAPTION-# IMAGE_CAPTION = BlockType.IMAGE_CAPTION-# TABLE_FOOTNOTE = BlockType.TABLE_FOOTNOTE-# IMAGE_FOOTNOTE = BlockType.IMAGE_FOOTNOTE-# CODE_CAPTION = BlockType.CODE_CAPTION-# PHONETIC = BlockType.PHONETIC-#-#-# not_extract_list = [item.value for item in NotExtractType] + [-# BlockType.CAPTION,-# BlockType.FOOTNOTE,+# # Titles+# BlockType.TITLE,# BlockType.DOC_TITLE,# BlockType.PARAGRAPH_TITLE,-# ]-# OCR_DET_LINE_BLOCK_TYPES = set(not_extract_list) | {+# # Captions+# BlockType.CAPTION,+# BlockType.IMAGE_CAPTION,+# BlockType.TABLE_CAPTION,+# BlockType.CHART_CAPTION,+# BlockType.CODE_CAPTION,+# # Footnotes+# BlockType.FOOTNOTE,+# BlockType.IMAGE_FOOTNOTE,+# BlockType.TABLE_FOOTNOTE,+# BlockType.CHART_FOOTNOTE,+# BlockType.CODE_FOOTNOTE,+# # Others# BlockType.LIST,# BlockType.INDEX,# BlockType.ABSTRACT,# BlockType.ASIDE_TEXT,-# BlockType.PHONETIC,-# BlockType.CHART_CAPTION,-# BlockType.CHART_FOOTNOTE,-# BlockType.CODE_FOOTNOTE,# }diff --git a/mineru/utils/draw_bbox.py b/mineru/utils/draw_bbox.pyindex 05e58d7c..9596b889 100644--- a/mineru/utils/draw_bbox.py+++ b/mineru/utils/draw_bbox.py@@ -9,8 +9,7 @@ from loguru import loggerfrom pypdf import PageObject, PdfReader, PdfWriterfrom reportlab.pdfgen import canvas-from ..types import BBox, Block, PageInfo, Span-from .enum_class import BlockType, ContentType+from ..types import BBox, Block, BlockType, ContentType, PageInfo, Span# 文本类 block 共用 text bbox 样式,避免新增文本形态时遗漏多个绘制入口。TEXT_LIKE_BLOCK_TYPES_FOR_BBOX = {diff --git a/mineru/utils/enum_class.py b/mineru/utils/enum_class.pyindex 7d2eb1ae..faebe92b 100644--- a/mineru/utils/enum_class.py+++ b/mineru/utils/enum_class.py@@ -1,103 +1,4 @@# Copyright (c) Opendatalab. All rights reserved.-from enum import Enum---class BlockType:- IMAGE = "image"- IMAGE_BODY = "image_body"- IMAGE_CAPTION = "image_caption"- IMAGE_FOOTNOTE = "image_footnote"-- TABLE = "table"- TABLE_BODY = "table_body"- TABLE_CAPTION = "table_caption"- TABLE_FOOTNOTE = "table_footnote"-- CHART = "chart"- CHART_BODY = "chart_body"- CHART_CAPTION = "chart_caption"- CHART_FOOTNOTE = "chart_footnote"-- # Added in vlm 2.5- CODE = "code"- CODE_BODY = "code_body"- CODE_CAPTION = "code_caption"- CODE_FOOTNOTE = "code_footnote"-- CAPTION = "caption" # generic caption type (e.g., for Word documents)- ALGORITHM_CAPTION = "algorithm_caption"- FOOTNOTE = "footnote" # pp_layout中的vision_footnote- TEXT = "text"- TITLE = "title"- INTERLINE_EQUATION = "interline_equation"- EQUATION = "equation" # 公式(独立公式)- LIST = "list"- INDEX = "index"- DISCARDED = "discarded"-- # Added in vlm 2.5- ALGORITHM = "algorithm"- REF_TEXT = "ref_text"- PHONETIC = "phonetic"- HEADER = "header"- FOOTER = "footer"- PAGE_NUMBER = "page_number"- ASIDE_TEXT = "aside_text"- PAGE_FOOTNOTE = "page_footnote"-- # Added in pp_doclayout_v2- ABSTRACT = "abstract"- DOC_TITLE = "doc_title"- PARAGRAPH_TITLE = "paragraph_title"- VERTICAL_TEXT = "vertical_text"- HEADER_IMAGE = "header_image"- FOOTER_IMAGE = "footer_image"- FORMULA_NUMBER = "formula_number"---class ContentType:- IMAGE = "image"- TABLE = "table"- CHART = "chart"- TEXT = "text"- INTERLINE_EQUATION = "interline_equation"- INLINE_EQUATION = "inline_equation"- EQUATION = "equation"- HYPERLINK = "hyperlink"---class ContentTypeV2:- CODE = "code"- ALGORITHM = "algorithm"- EQUATION_INTERLINE = "equation_interline"- IMAGE = "image"- TABLE = "table"- CHART = "chart"- TABLE_SIMPLE = "simple_table"- TABLE_COMPLEX = "complex_table"- LIST = "list"- LIST_TEXT = "text_list"- LIST_REF = "reference_list"- INDEX = "index"- TITLE = "title"- PARAGRAPH = "paragraph"- SPAN_TEXT = "text"- SPAN_EQUATION_INLINE = "equation_inline"- SPAN_PHONETIC = "phonetic"- SPAN_MD = "md"- SPAN_CODE_INLINE = "code_inline"- PAGE_HEADER = "page_header"- PAGE_FOOTER = "page_footer"- PAGE_NUMBER = "page_number"- PAGE_ASIDE_TEXT = "page_aside_text"- PAGE_FOOTNOTE = "page_footnote"---class MakeMode:- MM_MD = "mm_markdown"- NLP_MD = "nlp_markdown"- CONTENT_LIST = "content_list"- CONTENT_LIST_V2 = "content_list_v2"class ModelPath:@@ -114,27 +15,6 @@ class ModelPath:paddle_table_cls = "models/TabCls/paddle_table_cls/PP-LCNet_x1_0_table_cls.onnx"-class SplitFlag:- CROSS_PAGE = "cross_page"- LINES_DELETED = "lines_deleted"--class ImageType:PIL = "pil_img"BASE64 = "base64_img"---class NotExtractType(Enum):- TEXT = BlockType.TEXT- TITLE = BlockType.TITLE- HEADER = BlockType.HEADER- FOOTER = BlockType.FOOTER- PAGE_NUMBER = BlockType.PAGE_NUMBER- PAGE_FOOTNOTE = BlockType.PAGE_FOOTNOTE- REF_TEXT = BlockType.REF_TEXT- TABLE_CAPTION = BlockType.TABLE_CAPTION- IMAGE_CAPTION = BlockType.IMAGE_CAPTION- TABLE_FOOTNOTE = BlockType.TABLE_FOOTNOTE- IMAGE_FOOTNOTE = BlockType.IMAGE_FOOTNOTE- CODE_CAPTION = BlockType.CODE_CAPTION- PHONETIC = BlockType.PHONETICdiff --git a/mineru/utils/llm_aided.py b/mineru/utils/llm_aided.pyindex e86e5a07..acbb00b1 100644--- a/mineru/utils/llm_aided.py+++ b/mineru/utils/llm_aided.py@@ -10,8 +10,7 @@ from loguru import loggerfrom openai import OpenAIfrom ..render.merge import merge_para_text-from ..types import BBox, Block, PageInfo-from .enum_class import BlockType+from ..types import BBox, Block, BlockType, PageInfoTITLE_BLOCK_TYPES = {BlockType.TITLE,diff --git a/tests/unittest/test_e2e.py b/tests/unittest/test_e2e.pyindex cb7cb206..f8ad4ae2 100644--- a/tests/unittest/test_e2e.py+++ b/tests/unittest/test_e2e.py@@ -2,22 +2,15 @@import jsonimport osfrom pathlib import Path-from loguru import logger+from bs4 import BeautifulSoupfrom fuzzywuzzy import fuzz-from mineru.cli.common import (- convert_pdf_bytes_to_bytes,- prepare_env,- read_fn,-)+from loguru import logger++from mineru.backend.pipeline.pipeline_analyze import doc_analyze_streaming as pipeline_doc_analyze_streaming+from mineru.cli.common import convert_pdf_bytes_to_bytes, prepare_env, read_fnfrom mineru.data.data_reader_writer import FileBasedDataWriter-from mineru.utils.enum_class import MakeMode-from mineru.backend.pipeline.pipeline_analyze import (- doc_analyze_streaming as pipeline_doc_analyze_streaming,-)-from mineru.backend.pipeline.pipeline_middle_json_mkcontent import (- union_make as pipeline_union_make,-)+from mineru.render import render_content_list, render_markdowndef test_pipeline_with_two_config():@@ -54,9 +47,7 @@ def test_pipeline_with_two_config():output_dir,parse_method="txt",)- res_json_path = (- Path(__file__).parent / "output" / "test" / "txt" / "test_content_list.json"- ).as_posix()+ res_json_path = (Path(__file__).parent / "output" / "test" / "txt" / "test_content_list.json").as_posix()assert_content(res_json_path, parse_method="txt")run_pipeline_parse(pdf_file_names,@@ -65,9 +56,7 @@ def test_pipeline_with_two_config():output_dir,parse_method="ocr",)- res_json_path = (- Path(__file__).parent / "output" / "test" / "ocr" / "test_content_list.json"- ).as_posix()+ res_json_path = (Path(__file__).parent / "output" / "test" / "ocr" / "test_content_list.json").as_posix()assert_content(res_json_path, parse_method="ocr")@@ -116,13 +105,13 @@ def write_infer_result(pdf_info = middle_json["pdf_info"]image_dir = str(os.path.basename(local_image_dir))- md_content_str = pipeline_union_make(pdf_info, MakeMode.MM_MD, image_dir)+ md_content_str = render_markdown(pdf_info, image_dir)md_writer.write_string(f"{pdf_file_name}.md",md_content_str,)- content_list = pipeline_union_make(pdf_info, MakeMode.CONTENT_LIST, image_dir)+ content_list = render_content_list(pdf_info, image_dir)md_writer.write_string(f"{pdf_file_name}_content_list.json",json.dumps(content_list, ensure_ascii=False, indent=4),