Skip to content

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

feat: enhance PDF processing with retained and broken page index mapping for improved output consistency

myhlolib75c96fc9d99
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.py
index f2dfad3b..e4cb9769 100644
--- a/mineru/backend/hybrid/hybrid_analyze.py
+++ b/mineru/backend/hybrid/hybrid_analyze.py
@@ -745,6 +745,7 @@ def doc_analyze(
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
+ page_index_map: list[int] | None = None,
**kwargs: object,
) -> tuple[list[PageInfo], list[list[dict[str, Any]]], bool]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
@@ -838,6 +839,7 @@ def doc_analyze(
image_writer,
page_cvt_fn=blocks_to_page_info,
page_start_index=window_start,
+ page_index_map=page_index_map,
_ocr_enable=_ocr_enable,
_vlm_ocr_enable=_vlm_ocr_enable,
progress_bar=progress_bar,
@@ -896,6 +898,7 @@ async def aio_doc_analyze(
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
+ page_index_map: list[int] | None = None,
**kwargs: object,
) -> tuple[list[PageInfo], list[list[dict[str, Any]]], bool]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
@@ -990,6 +993,7 @@ async def aio_doc_analyze(
image_writer,
page_cvt_fn=blocks_to_page_info,
page_start_index=window_start,
+ page_index_map=page_index_map,
_ocr_enable=_ocr_enable,
_vlm_ocr_enable=_vlm_ocr_enable,
progress_bar=progress_bar,
diff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.py
index 5b0ae007..c7595222 100644
--- a/mineru/backend/pipeline/model_output_to_middle_json.py
+++ b/mineru/backend/pipeline/model_output_to_middle_json.py
@@ -7,7 +7,7 @@ from ...utils.hash_utils import bytes_md5
from ...utils.pdfium_guard import pdfium_guard
from ...utils.title_level_postprocess import apply_title_leveling_to_pdf_info
from ..utils.char_utils import full_to_half
-from ..utils.middle_json_utils import append_pages, apply_post_ocr
+from ..utils.middle_json_utils import append_pages, apply_post_ocr, resolve_output_page_idx
from ..utils.runtime_utils import cross_page_table_merge
from ..utils.visual_span_utils import cut_visual_spans_in_blocks
from .model_init import AtomModelSingleton
@@ -67,12 +67,14 @@ def append_batch_results_to_middle_json(
page_start_index: int = 0,
ocr_enable: bool = False,
model_list: list[dict[str, Any]] | None = None,
+ page_index_map: list[int] | None = None,
progress_bar: Any = None,
) -> None:
page_model_infos = []
for offset, (image_dict, page_layout_dets) in enumerate(zip(images_list, batch_results)):
- page_index = page_start_index + offset
- page_model_info = build_page_model_info(page_layout_dets, page_index, image_dict["img_pil"])
+ physical_page_idx = page_start_index + offset
+ output_page_idx = resolve_output_page_idx(physical_page_idx, page_index_map)
+ page_model_info = build_page_model_info(page_layout_dets, output_page_idx, image_dict["img_pil"])
page_model_infos.append(page_model_info)
if model_list is not None:
@@ -86,6 +88,7 @@ def append_batch_results_to_middle_json(
image_writer,
page_cvt_fn=blocks_to_page_info,
page_start_index=page_start_index,
+ page_index_map=page_index_map,
ocr_enable=ocr_enable,
progress_bar=progress_bar,
)
diff --git a/mineru/backend/pipeline/pipeline_analyze.py b/mineru/backend/pipeline/pipeline_analyze.py
index 0cfa5161..e51e352e 100644
--- a/mineru/backend/pipeline/pipeline_analyze.py
+++ b/mineru/backend/pipeline/pipeline_analyze.py
@@ -150,9 +150,12 @@ def doc_analyze_streaming(
formula_enable: bool = True,
table_enable: bool = True,
client_side_output_generation: bool = False,
+ page_index_map_list: list[list[int] | None] | None = None,
) -> None:
if not (len(pdf_bytes_list) == len(image_writer_list) == len(lang_list)):
raise ValueError("pdf_bytes_list, image_writer_list, and lang_list must have the same length")
+ if page_index_map_list is not None and len(page_index_map_list) != len(pdf_bytes_list):
+ raise ValueError("page_index_map_list must have the same length as pdf_bytes_list")
doc_contexts = []
try:
@@ -173,6 +176,7 @@ def doc_analyze_streaming(
"image_writer": image_writer,
"lang": lang,
"ocr_enable": _ocr_enable,
+ "page_index_map": page_index_map_list[doc_index] if page_index_map_list is not None else None,
"closed": False,
}
except Exception:
@@ -278,6 +282,7 @@ def doc_analyze_streaming(
page_start_index=page_start,
ocr_enable=context["ocr_enable"],
model_list=context["model_list"],
+ page_index_map=context["page_index_map"],
progress_bar=progress_bar,
)
result_offset += take_count
diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.py
index e7d8562f..4cb90ec6 100644
--- a/mineru/backend/utils/middle_json_utils.py
+++ b/mineru/backend/utils/middle_json_utils.py
@@ -19,6 +19,18 @@ from ..pipeline.model_init import run_ocr_rec_inference
T = TypeVar("T")
+def resolve_output_page_idx(physical_page_idx: int, page_index_map: list[int] | None = None) -> int:
+ """根据物理页序解析输出页号,确保裁图和 middle_json 使用原始页号。"""
+ if page_index_map is None:
+ return physical_page_idx
+ if physical_page_idx < 0 or physical_page_idx >= len(page_index_map):
+ raise ValueError(
+ f"page_index_map does not cover physical page index {physical_page_idx}: "
+ f"map length={len(page_index_map)}"
+ )
+ return page_index_map[physical_page_idx]
+
+
def append_pages(
middle_json: list[PageInfo],
model_list: list[T],
@@ -32,6 +44,7 @@ def append_pages(
Callable[[T, dict[str, Any], Any, DataWriter | None, int, bool, bool], PageInfo],
],
page_start_index: int = 0,
+ page_index_map: list[int] | None = None,
progress_bar: Any = None,
**kwargs: Any,
) -> None:
@@ -43,18 +56,19 @@ def append_pages(
"""
for offset, (page_data, image_dict) in enumerate(zip(model_list, images_list)):
- page_index = page_start_index + offset
+ physical_page_idx = page_start_index + offset
+ output_page_idx = resolve_output_page_idx(physical_page_idx, page_index_map)
page = None
try:
with pdfium_guard():
- page = pdf_doc[page_index]
- page_info = page_cvt_fn(copy.deepcopy(page_data), image_dict, page, image_writer, page_index, **kwargs)
+ page = pdf_doc[physical_page_idx]
+ page_info = page_cvt_fn(copy.deepcopy(page_data), image_dict, page, image_writer, output_page_idx, **kwargs)
if page_info is None:
with pdfium_guard():
page_w, page_h = map(int, page.get_size())
page_info = PageInfo(
preproc_blocks=[],
- page_idx=page_index,
+ page_idx=output_page_idx,
page_size=(page_w, page_h),
discarded_blocks=[],
_backend=None,
diff --git a/mineru/backend/vlm/vlm_analyze.py b/mineru/backend/vlm/vlm_analyze.py
index e3fb46fc..532fdf03 100644
--- a/mineru/backend/vlm/vlm_analyze.py
+++ b/mineru/backend/vlm/vlm_analyze.py
@@ -455,6 +455,7 @@ def doc_analyze(
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
+ page_index_map: list[int] | None = None,
**kwargs: Any,
) -> tuple[list[PageInfo], list[ExtractResult]]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
@@ -518,6 +519,7 @@ def doc_analyze(
image_writer,
page_cvt_fn=blocks_to_page_info,
page_start_index=window_start,
+ page_index_map=page_index_map,
progress_bar=progress_bar,
)
last_append_end_time = time.time()
@@ -556,6 +558,7 @@ async def aio_doc_analyze(
model_path: str | None = None,
server_url: str | None = None,
image_analysis: bool = True,
+ page_index_map: list[int] | None = None,
**kwargs: Any,
) -> tuple[list[PageInfo], list[ExtractResult]]:
client_side_output_generation = bool(kwargs.pop("client_side_output_generation", False))
@@ -618,6 +621,7 @@ async def aio_doc_analyze(
image_writer,
page_cvt_fn=blocks_to_page_info,
page_start_index=window_start,
+ page_index_map=page_index_map,
progress_bar=progress_bar,
)
last_append_end_time = time.time()
diff --git a/mineru/cli_old/common.py b/mineru/cli_old/common.py
index 143e4c21..9e5d1f0a 100644
--- a/mineru/cli_old/common.py
+++ b/mineru/cli_old/common.py
@@ -7,6 +7,7 @@ import importlib.util
import json
import os
from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Sequence
@@ -17,6 +18,7 @@ from mineru.backend.office.pptx_analyze import office_pptx_analyze
from mineru.backend.office.xlsx_analyze import office_xlsx_analyze
from mineru.backend.vlm.vlm_analyze import aio_doc_analyze as aio_vlm_doc_analyze
from mineru.backend.vlm.vlm_analyze import doc_analyze as vlm_doc_analyze
+from mineru.cli_old.visualization import select_pages_for_pdf_visualization
from mineru.data.data_reader_writer import FileBasedDataWriter
from mineru.parser.base import ParseResult
from mineru.render import render_content_list, render_markdown, render_structured_content
@@ -24,7 +26,7 @@ from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox
from mineru.utils.engine_utils import get_vlm_engine
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_bytes
from mineru.utils.pdf_image_tools import images_bytes_to_pdf_bytes
-from mineru.utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium
+from mineru.utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium, safe_rewrite_pdf_bytes_with_pdfium_result
from ..types import PageInfo
from ..version import __version__
@@ -50,6 +52,15 @@ os.environ["TOKENIZERS_PARALLELISM"] = "false"
MAX_TASK_STEM_BYTES = 200
+@dataclass(frozen=True)
+class PreparedPdfBytes:
+ """记录旧 CLI PDF 预处理结果,避免页号映射在 backend 前丢失。"""
+
+ pdf_bytes: bytes
+ retained_page_indices: list[int] | None = None
+ broken_page_indices: list[int] | None = None
+
+
class HybridDependencyError(RuntimeError):
pass
@@ -192,6 +203,30 @@ def convert_pdf_bytes_to_bytes(pdf_bytes: bytes, start_page_id: int = 0, end_pag
)
+def prepare_pdf_bytes_with_page_map(
+ pdf_bytes: bytes,
+ start_page_id: int = 0,
+ end_page_id: int | None = None,
+) -> PreparedPdfBytes:
+ """重写 PDF 字节并保留小 PDF 物理页到原始页号的映射。"""
+ rewrite_result = safe_rewrite_pdf_bytes_with_pdfium_result(
+ pdf_bytes,
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ )
+ if rewrite_result.used_original:
+ return PreparedPdfBytes(
+ pdf_bytes=rewrite_result.pdf_bytes or pdf_bytes,
+ retained_page_indices=None,
+ broken_page_indices=rewrite_result.broken_page_indices,
+ )
+ return PreparedPdfBytes(
+ pdf_bytes=rewrite_result.pdf_bytes or pdf_bytes,
+ retained_page_indices=rewrite_result.retained_page_indices,
+ broken_page_indices=rewrite_result.broken_page_indices,
+ )
+
+
def _prepare_pdf_bytes(pdf_bytes_list: list[bytes], start_page_id: int, end_page_id: int | None) -> list[bytes]:
"""准备处理PDF字节数据"""
result = []
@@ -201,6 +236,18 @@ def _prepare_pdf_bytes(pdf_bytes_list: list[bytes], start_page_id: int, end_page
return result
+def _prepare_pdf_inputs(
+ pdf_bytes_list: list[bytes],
+ start_page_id: int,
+ end_page_id: int | None,
+) -> list[PreparedPdfBytes]:
+ """批量准备 PDF 输入,并为 backend 保留逐文档页号映射。"""
+ return [
+ prepare_pdf_bytes_with_page_map(pdf_bytes, start_page_id, end_page_id)
+ for pdf_bytes in pdf_bytes_list
+ ]
+
+
def _process_output(
middle_json: list[PageInfo],
pdf_bytes: bytes,
@@ -220,17 +267,20 @@ def _process_output(
*,
process_mode: str,
backend: str,
+ retained_page_indices: list[int] | None = None,
+ broken_page_indices: list[int] | None = None,
) -> None:
"""处理输出文件"""
+ visualization_pages = select_pages_for_pdf_visualization(middle_json, retained_page_indices)
if f_draw_layout_bbox:
try:
- draw_layout_bbox(middle_json, pdf_bytes, local_md_dir, f"{pdf_file_name}_layout.pdf")
+ draw_layout_bbox(visualization_pages, pdf_bytes, local_md_dir, f"{pdf_file_name}_layout.pdf")
except Exception as exc:
logger.warning(f"Skipping layout bbox visualization for {pdf_file_name}: {exc}")
if f_draw_span_bbox:
try:
- draw_span_bbox(middle_json, pdf_bytes, local_md_dir, f"{pdf_file_name}_span.pdf")
+ draw_span_bbox(visualization_pages, pdf_bytes, local_md_dir, f"{pdf_file_name}_span.pdf")
except Exception as exc:
logger.warning(f"Skipping span bbox visualization for {pdf_file_name}: {exc}")
@@ -247,7 +297,11 @@ def _process_output(
)
image_dir = str(os.path.basename(local_image_dir))
- export_result = ParseResult(pages=middle_json)
+ export_result = ParseResult(
+ pages=middle_json,
+ _retained_page_indices=retained_page_indices,
+ _broken_page_indices=broken_page_indices,
+ )
image_writer = FileBasedDataWriter(local_image_dir)
for img_path, img_bytes in export_result.images().items():
image_writer.write(img_path, img_bytes)
@@ -311,6 +365,8 @@ def _process_pipeline(
f_dump_content_list: bool,
f_make_md_mode: str,
client_side_output_generation: bool = False,
+ page_index_map_list: list[list[int] | None] | None = None,
+ broken_page_indices_list: list[list[int] | None] | None = None,
) -> None:
"""处理pipeline后端逻辑"""
from mineru.backend.pipeline.pipeline_analyze import doc_analyze_streaming as pipeline_doc_analyze_streaming
@@ -332,6 +388,8 @@ def _process_pipeline(
pdf_file_name, local_image_dir, local_md_dir = local_output_info[doc_index]
md_writer = md_writer_list[doc_index]
pdf_bytes = pdf_bytes_list[doc_index]
+ retained_page_indices = page_index_map_list[doc_index] if page_index_map_list is not None else None
+ broken_page_indices = broken_page_indices_list[doc_index] if broken_page_indices_list is not None else None
logger.debug(f"Pipeline output start: doc{doc_index}")
try:
_process_output(
@@ -352,6 +410,8 @@ def _process_pipeline(
model_list,
process_mode="pipeline",
backend="pipeline",
+ retained_page_indices=retained_page_indices,
+ broken_page_indices=broken_page_indices,
)
logger.debug(f"Pipeline output complete: doc{doc_index}")
except Exception:
@@ -374,6 +434,7 @@ def _process_pipeline(
formula_enable=p_formula_enable,
table_enable=p_table_enable,
client_side_output_generation=client_side_output_generation,
+ page_index_map_list=page_index_map_list,
)
for future in output_futures:
@@ -395,6 +456,8 @@ async def _async_process_vlm(
f_dump_content_list: bool,
f_make_md_mode: str,
server_url: str | None = None,
+ page_index_map_list: list[list[int] | None] | None = None,
+ broken_page_indices_list: list[list[int] | None] | None = None,
**kwargs: Any,
) -> None:
"""异步处理VLM后端逻辑"""
@@ -413,6 +476,7 @@ async def _async_process_vlm(
image_writer=image_writer,
backend=backend,
server_url=server_url,
+ page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
**kwargs,
)
@@ -434,6 +498,8 @@ async def _async_process_vlm(
infer_result,
process_mode="vlm",
backend="vlm",
+ retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
+ broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
)
@@ -451,6 +517,8 @@ def _process_vlm(
f_dump_content_list: bool,
f_make_md_mode: str,
server_url: str | None = None,
+ page_index_map_list: list[list[int] | None] | None = None,
+ broken_page_indices_list: list[list[int] | None] | None = None,
**kwargs: Any,
) -> None:
"""同步处理VLM后端逻辑"""
@@ -469,6 +537,7 @@ def _process_vlm(
image_writer=image_writer,
backend=backend,
server_url=server_url,
+ page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
**kwargs,
)
@@ -490,6 +559,8 @@ def _process_vlm(
infer_result,
process_mode="vlm",
backend="vlm",
+ retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
+ broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
)
@@ -510,6 +581,8 @@ def _process_hybrid(
f_dump_content_list: bool,
f_make_md_mode: str,
server_url: str | None = None,
+ page_index_map_list: list[list[int] | None] | None = None,
+ broken_page_indices_list: list[list[int] | None] | None = None,
**kwargs: Any,
) -> None:
hybrid_doc_analyze = _load_hybrid_analyze_entrypoint(
@@ -533,6 +606,7 @@ def _process_hybrid(
language=lang,
inline_formula_enable=inline_formula_enable,
server_url=server_url,
+ page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
**kwargs,
)
@@ -557,6 +631,8 @@ def _process_hybrid(
infer_result,
process_mode="vlm",
backend="bybrid",
+ retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
+ broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
)
@@ -577,6 +653,8 @@ async def _async_process_hybrid(
f_dump_content_list: bool,
f_make_md_mode: str,
server_url: str | None = None,
+ page_index_map_list: list[list[int] | None] | None = None,
+ broken_page_indices_list: list[list[int] | None] | None = None,
**kwargs: Any,
) -> None:
aio_hybrid_doc_analyze = _load_hybrid_analyze_entrypoint(
@@ -600,6 +678,7 @@ async def _async_process_hybrid(
language=lang,
inline_formula_enable=inline_formula_enable,
server_url=server_url,
+ page_index_map=page_index_map_list[idx] if page_index_map_list is not None else None,
**kwargs,
)
@@ -624,6 +703,8 @@ async def _async_process_hybrid(
infer_result,
process_mode="vlm",
backend="bybrid",
+ retained_page_indices=page_index_map_list[idx] if page_index_map_list is not None else None,
+ broken_page_indices=broken_page_indices_list[idx] if broken_page_indices_list is not None else None,
)
@@ -731,8 +812,11 @@ def do_parse(
logger.warning("No valid PDF or image files to process.")
return
- # 预处理PDF字节数据
- pdf_bytes_list = _prepare_pdf_bytes(pdf_bytes_list, start_page_id, end_page_id)
+ # 预处理PDF字节数据,同时保留裁剪后 PDF 页序到原始页号的映射。
+ prepared_pdf_inputs = _prepare_pdf_inputs(pdf_bytes_list, start_page_id, end_page_id)
+ pdf_bytes_list = [prepared.pdf_bytes for prepared in prepared_pdf_inputs]
+ page_index_map_list = [prepared.retained_page_indices for prepared in prepared_pdf_inputs]
+ broken_page_indices_list = [prepared.broken_page_indices for prepared in prepared_pdf_inputs]
if backend == "pipeline":
_process_pipeline(
@@ -752,6 +836,8 @@ def do_parse(
f_dump_content_list,
f_make_md_mode,
client_side_output_generation=client_side_output_generation,
+ page_index_map_list=page_index_map_list,
+ broken_page_indices_list=broken_page_indices_list,
)
else:
if backend.startswith("vlm-"):
@@ -782,6 +868,8 @@ def do_parse(
f_dump_content_list,
f_make_md_mode,
server_url,
+ page_index_map_list=page_index_map_list,
+ broken_page_indices_list=broken_page_indices_list,
image_analysis=image_analysis,
client_side_output_generation=client_side_output_generation,
**kwargs,
@@ -818,6 +906,8 @@ def do_parse(
f_dump_content_list,
f_make_md_mode,
server_url,
+ page_index_map_list=page_index_map_list,
+ broken_page_indices_list=broken_page_indices_list,
image_analysis=image_analysis,
client_side_output_generation=client_side_output_generation,
**kwargs,
@@ -869,8 +959,11 @@ async def aio_do_parse(
logger.warning("No valid PDF or image files to process.")
return
- # 预处理PDF字节数据
- pdf_bytes_list = _prepare_pdf_bytes(pdf_bytes_list, start_page_id, end_page_id)
+ # 预处理PDF字节数据,同时保留裁剪后 PDF 页序到原始页号的映射。
+ prepared_pdf_inputs = _prepare_pdf_inputs(pdf_bytes_list, start_page_id, end_page_id)
+ pdf_bytes_list = [prepared.pdf_bytes for prepared in prepared_pdf_inputs]
+ page_index_map_list = [prepared.retained_page_indices for prepared in prepared_pdf_inputs]
+ broken_page_indices_list = [prepared.broken_page_indices for prepared in prepared_pdf_inputs]
if backend == "pipeline":
# pipeline模式暂不支持异步,使用同步处理方式
@@ -891,6 +984,8 @@ async def aio_do_parse(
f_dump_content_list,
f_make_md_mode,
client_side_output_generation=client_side_output_generation,
+ page_index_map_list=page_index_map_list,
+ broken_page_indices_list=broken_page_indices_list,
)
else:
if backend.startswith("vlm-"):
@@ -921,6 +1016,8 @@ async def aio_do_parse(
f_dump_content_list,
f_make_md_mode,
server_url,
+ page_index_map_list=page_index_map_list,
+ broken_page_indices_list=broken_page_indices_list,
image_analysis=image_analysis,
client_side_output_generation=client_side_output_generation,
**kwargs,
@@ -957,6 +1054,8 @@ async def aio_do_parse(
f_dump_content_list,
f_make_md_mode,
server_url,
+ page_index_map_list=page_index_map_list,
+ broken_page_indices_list=broken_page_indices_list,
image_analysis=image_analysis,
client_side_output_generation=client_side_output_generation,
**kwargs,
diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.py
index cc59430b..7c9f2a48 100644
--- a/mineru/parser/pdf.py
+++ b/mineru/parser/pdf.py
@@ -75,8 +75,12 @@ class PdfBaseParser(DocumentParser):
raise FileNotFoundError(path)
prepared = self._prepare_input(path, page_range)
- middle_json = self._run_analysis(prepared.pdf_bytes, image_writer=None)
- self._fix_page_indices(
+ middle_json = self._run_analysis(
+ prepared.pdf_bytes,
+ image_writer=None,
+ page_index_map=prepared.retained_page_indices,
+ )
+ self._insert_broken_pages(
middle_json,
prepared.retained_page_indices,
prepared.broken_page_indices,
@@ -95,8 +99,12 @@ class PdfBaseParser(DocumentParser):
raise FileNotFoundError(path)
prepared = await asyncio.to_thread(self._prepare_input, path, page_range)
- middle_json = await self._arun_analysis(prepared.pdf_bytes, image_writer=None)
- self._fix_page_indices(
+ middle_json = await self._arun_analysis(
+ prepared.pdf_bytes,
+ image_writer=None,
+ page_index_map=prepared.retained_page_indices,
+ )
+ self._insert_broken_pages(
middle_json,
prepared.retained_page_indices,
prepared.broken_page_indices,
@@ -110,11 +118,21 @@ class PdfBaseParser(DocumentParser):
)
@abstractmethod
- def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
+ def _run_analysis(
+ self,
+ pdf_bytes: bytes,
+ image_writer: Any,
+ page_index_map: list[int] | None = None,
+ ) -> list[PageInfo]:
"""Execute backend-specific analysis. Returns (middle_json, model_output)."""
- async def _arun_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
- return await asyncio.to_thread(self._run_analysis, pdf_bytes, image_writer)
+ async def _arun_analysis(
+ self,
+ pdf_bytes: bytes,
+ image_writer: Any,
+ page_index_map: list[int] | None = None,
+ ) -> list[PageInfo]:
+ return await asyncio.to_thread(self._run_analysis, pdf_bytes, image_writer, page_index_map)
def _prepare_input(self, path: Path, page_range: str = "") -> _PreparedPdfInput:
from ..utils.guess_suffix_or_lang import guess_suffix_by_path
@@ -168,27 +186,17 @@ class PdfBaseParser(DocumentParser):
rewrite_result.broken_page_indices,
)
- def _fix_page_indices(
+ def _insert_broken_pages(
self,
pages: list[PageInfo],
retained_page_indices: list[int] | None = None,
broken_page_indices: list[int] | None = None,
) -> None:
- """按 PDF 重写结果修正原始页号,并为跳过的损坏页补空页面。"""
- if retained_page_indices is None:
- return
-
- fixed_pages: list[PageInfo] = []
- for i, p in enumerate(pages):
- if i < len(retained_page_indices):
- p.page_idx = retained_page_indices[i]
- fixed_pages.append(p)
-
- if not broken_page_indices:
- pages[:] = fixed_pages
+ """按 PDF 重写结果补齐坏页空占位,不再修改 backend 已生成的页号。"""
+ if retained_page_indices is None or not broken_page_indices:
return
- pages_by_index = {page.page_idx: page for page in fixed_pages}
+ pages_by_index = {page.page_idx: page for page in pages}
ordered_page_indices = sorted(set(pages_by_index) | set(broken_page_indices))
pages[:] = [
pages_by_index.get(page_idx, PageInfo(page_idx=page_idx))
@@ -217,7 +225,12 @@ class PdfVlmParser(PdfBaseParser):
_parse_method = "vlm"
_backend = "vlm"
- def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
+ def _run_analysis(
+ self,
+ pdf_bytes: bytes,
+ image_writer: Any,
+ page_index_map: list[int] | None = None,
+ ) -> list[PageInfo]:
from ..backend.vlm.vlm_analyze import doc_analyze as vlm_doc_analyze
backend = _resolve_vlm_backend(self.backend)
@@ -230,9 +243,15 @@ class PdfVlmParser(PdfBaseParser):
backend=backend,
server_url=self.server_url,
image_analysis=self.image_analysis,
+ page_index_map=page_index_map,
)[0]
- async def _arun_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
+ async def _arun_analysis(
+ self,
+ pdf_bytes: bytes,
+ image_writer: Any,
+ page_index_map: list[int] | None = None,
+ ) -> list[PageInfo]:
from ..backend.vlm.vlm_analyze import aio_doc_analyze as vlm_aio_doc_analyze
backend = _resolve_vlm_backend(self.backend)
@@ -245,6 +264,7 @@ class PdfVlmParser(PdfBaseParser):
backend=backend,
server_url=self.server_url,
image_analysis=self.image_analysis,
+ page_index_map=page_index_map,
)
return middle_json
@@ -288,13 +308,14 @@ class PdfPipelineParser(PdfBaseParser):
parse_method=self.method,
formula_enable=self.formula_enable,
table_enable=self.table_enable,
+ page_index_map_list=[prepared.retained_page_indices for prepared in prepared_inputs],
)
parse_results: list[ParseResult] = []
for idx in range(len(paths)):
middle_json = results_by_index[idx]
prepared = prepared_inputs[idx]
- self._fix_page_indices(
+ self._insert_broken_pages(
middle_json,
prepared.retained_page_indices,
prepared.broken_page_indices,
@@ -315,7 +336,12 @@ class PdfPipelineParser(PdfBaseParser):
return await asyncio.to_thread(self.parse_batch, paths, page_range=page_range)
- def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
+ def _run_analysis(
+ self,
+ pdf_bytes: bytes,
+ image_writer: Any,
+ page_index_map: list[int] | None = None,
+ ) -> list[PageInfo]:
from ..backend.pipeline.pipeline_analyze import doc_analyze_streaming
result_holder: dict = {}
@@ -331,6 +357,7 @@ class PdfPipelineParser(PdfBaseParser):
parse_method=self.method,
formula_enable=self.formula_enable,
table_enable=self.table_enable,
+ page_index_map_list=[page_index_map],
)
return result_holder["middle_json"]
@@ -350,7 +377,12 @@ class PdfHybridParser(PdfBaseParser):
self._parse_method = f"hybrid_{self.method}"
return await super().parse_async(path, page_range=page_range)
- def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
+ def _run_analysis(
+ self,
+ pdf_bytes: bytes,
+ image_writer: Any,
+ page_index_map: list[int] | None = None,
+ ) -> list[PageInfo]:
from ..backend.hybrid.hybrid_analyze import doc_analyze as hybrid_doc_analyze
backend = _resolve_hybrid_backend(self.backend)
@@ -367,11 +399,17 @@ class PdfHybridParser(PdfBaseParser):
inline_formula_enable=self.formula_enable,
server_url=server_url,
image_analysis=self.image_analysis,
+ page_index_map=page_index_map,
)
return middle_json
- async def _arun_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
+ async def _arun_analysis(
+ self,
+ pdf_bytes: bytes,
+ image_writer: Any,
+ page_index_map: list[int] | None = None,
+ ) -> list[PageInfo]:
from ..backend.hybrid.hybrid_analyze import aio_doc_analyze as hybrid_aio_doc_analyze
backend = _resolve_hybrid_backend(self.backend)
@@ -388,6 +426,7 @@ class PdfHybridParser(PdfBaseParser):
inline_formula_enable=self.formula_enable,
server_url=server_url,
image_analysis=self.image_analysis,
+ page_index_map=page_index_map,
)
return middle_json
@@ -398,9 +437,15 @@ class PdfFlashParser(PdfBaseParser):
_backend = "flash"
- def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
+ def _run_analysis(
+ self,
+ pdf_bytes: bytes,
+ image_writer: Any,
+ page_index_map: list[int] | None = None,
+ ) -> list[PageInfo]:
from ..backend.flash.pdf_extractor import extract_pages_text
from ..types import Block, Line, PageInfo, Span
+ from ..backend.utils.middle_json_utils import resolve_output_page_idx
filepath = self._pdf_bytes_to_tempfile(pdf_bytes)
pages_text = extract_pages_text(filepath)
@@ -408,6 +453,7 @@ class PdfFlashParser(PdfBaseParser):
pages: list[PageInfo] = []
block_idx = 0
for index, pt in enumerate(pages_text):
+ page_idx = resolve_output_page_idx(index, page_index_map)
para_blocks: list[Block] = []
if pt.strip():
span = Span(type="text", bbox=(0.0, 0.0, 0.0, 0.0), content=pt.strip())
@@ -416,7 +462,7 @@ class PdfFlashParser(PdfBaseParser):
para_blocks.append(block)
block_idx += 1
page = PageInfo(
- page_idx=index,
+ page_idx=page_idx,
para_blocks=para_blocks,
)
pages.append(page)
diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.py
index aa3a4fc1..8e19aa3a 100644
--- a/tests/unittest/test_kit_commands.py
+++ b/tests/unittest/test_kit_commands.py
@@ -1,6 +1,9 @@
from __future__ import annotations
from pathlib import Path
+import subprocess
+import sys
+from types import SimpleNamespace
from typing import Any
from typer.testing import CliRunner
@@ -23,6 +26,37 @@ def test_kit_root_and_models_help() -> None:
assert "router" in result.output
+def test_kit_main_import_does_not_import_legacy_router() -> None:
+ repo_root = Path(__file__).resolve().parents[2]
+ code = """
+import importlib.abc
+import sys
+
+
+class BlockLegacyRouterFinder(importlib.abc.MetaPathFinder):
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname == "mineru.cli_old.router":
+ raise ModuleNotFoundError("blocked legacy router import")
+ return None
+
+
+sys.meta_path.insert(0, BlockLegacyRouterFinder())
+import mineru.kit.main
+print("ok")
+"""
+
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ cwd=repo_root,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == "ok"
+
+
def test_models_download_pipeline(monkeypatch: Any) -> None:
monkeypatch.setattr(models, "_download_pipeline_models", lambda: "/tmp/pipeline")
monkeypatch.setattr(models, "_download_vlm_models", lambda: "/tmp/vlm")
@@ -121,7 +155,11 @@ def test_router_forwards_known_and_extra_args(monkeypatch: Any) -> None:
seen["prog_name"] = prog_name
seen["standalone_mode"] = standalone_mode
- monkeypatch.setattr(router.old_router.main, "main", _fake_main)
+ monkeypatch.setattr(
+ router,
+ "_load_old_router",
+ lambda: SimpleNamespace(main=SimpleNamespace(main=_fake_main)),
+ )
result = runner.invoke(
app,
diff --git a/tests/unittest/test_parser_flash.py b/tests/unittest/test_parser_flash.py
index 5517899f..f9548493 100644
--- a/tests/unittest/test_parser_flash.py
+++ b/tests/unittest/test_parser_flash.py
@@ -10,8 +10,7 @@ def test_flash_parser_preserves_page_indices_for_empty_pages(monkeypatch) -> Non
monkeypatch.setattr(PdfFlashParser, "_pdf_bytes_to_tempfile", staticmethod(lambda pdf_bytes: "dummy.pdf"))
monkeypatch.setattr(pdf_extractor, "extract_pages_text", lambda filepath: ["first", "", "third"])
- pages = parser._run_analysis(b"%PDF", image_writer=None)
- parser._fix_page_indices(pages, retained_page_indices=[10, 12, 13])
+ pages = parser._run_analysis(b"%PDF", image_writer=None, page_index_map=[10, 12, 13])
assert [page.page_idx for page in pages] == [10, 12, 13]
assert [len(page.para_blocks) for page in pages] == [1, 0, 1]