Skip to content

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

feat: enhance PDF handling with retained and broken page indices for improved processing

myhloli1100d10d8270
diff --git a/mineru/cli_old/visualization.py b/mineru/cli_old/visualization.py
index 3dd7f033..e0ccf302 100644
--- a/mineru/cli_old/visualization.py
+++ b/mineru/cli_old/visualization.py
@@ -4,6 +4,7 @@ from dataclasses import dataclass
from pathlib import Path
from mineru.parser.base import ParseResult
+from mineru.types import PageInfo
from mineru.utils.pdf_document import PDFDocument
VISUALIZATION_FINISHED = "finished"
@@ -28,6 +29,21 @@ class VisualizationResult:
generated_files: tuple[str, ...] = ()
+def select_pages_for_pdf_visualization(
+ pages: list[PageInfo],
+ retained_page_indices: list[int] | None,
+) -> list[PageInfo]:
+ """按重写 PDF 的实际页序筛选页面,避免坏页空占位参与 bbox 绘制。"""
+ if retained_page_indices is None:
+ return pages
+ pages_by_original_index = {page.page_idx: page for page in pages}
+ return [
+ pages_by_original_index[page_idx]
+ for page_idx in retained_page_indices
+ if page_idx in pages_by_original_index
+ ]
+
+
def run_visualization_job(job: VisualizationJob) -> VisualizationResult:
middle_json_path = job.parse_dir / f"{job.document_stem}_middle.json"
origin_pdf_path = job.parse_dir / f"{job.document_stem}_origin.pdf"
@@ -66,7 +82,11 @@ def run_visualization_job(job: VisualizationJob) -> VisualizationResult:
)
try:
- pages = ParseResult.from_dict(payload).pages
+ parse_result = ParseResult.from_dict(payload)
+ pages = select_pages_for_pdf_visualization(
+ parse_result.pages,
+ parse_result._retained_page_indices,
+ )
pdf_bytes = origin_pdf_path.read_bytes()
doc = PDFDocument(pdf_bytes)
generated_files = [f"{job.document_stem}_layout.pdf"]
diff --git a/mineru/parser/base.py b/mineru/parser/base.py
index 74ad7a54..8c26ed30 100644
--- a/mineru/parser/base.py
+++ b/mineru/parser/base.py
@@ -18,6 +18,21 @@ from ..utils.image_payload import (
replace_inline_data_uri_sources,
)
+_PDF_RETAINED_PAGE_INDICES_KEY = "_pdf_retained_page_indices"
+_PDF_BROKEN_PAGE_INDICES_KEY = "_pdf_broken_page_indices"
+
+
+def _parse_optional_int_list(value: Any) -> list[int] | None:
+ """解析内部页映射列表;旧 payload 或非法类型直接按缺省处理。"""
+ if not isinstance(value, list):
+ return None
+ parsed: list[int] = []
+ for item in value:
+ if not isinstance(item, int):
+ return None
+ parsed.append(item)
+ return parsed
+
@dataclass
class ParseResult:
@@ -31,6 +46,8 @@ class ParseResult:
_pdf_doc: object | None = None
_model_output: Any = None
_images_cache: dict[str, bytes] | None = None
+ _retained_page_indices: list[int] | None = None
+ _broken_page_indices: list[int] | None = None
@staticmethod
def from_dict(d: dict[str, Any]) -> ParseResult:
@@ -53,20 +70,37 @@ class ParseResult:
if isinstance(backend, str):
page._backend = backend
pages.append(page)
- return ParseResult(pages=pages)
+ retained_page_indices = _parse_optional_int_list(d.get(_PDF_RETAINED_PAGE_INDICES_KEY))
+ broken_page_indices = _parse_optional_int_list(d.get(_PDF_BROKEN_PAGE_INDICES_KEY))
+ return ParseResult(
+ pages=pages,
+ _retained_page_indices=retained_page_indices,
+ _broken_page_indices=broken_page_indices,
+ )
def to_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:
- return {
+ payload = {
"schema_version": MIDDLE_JSON_SCHEMA_VERSION,
"pages": [page.to_dict(skip_defaults=skip_defaults) for page in self.pages],
}
+ self._append_private_pdf_page_mapping(payload)
+ return payload
def to_export_dict(self, *, skip_defaults: bool = True) -> dict[str, Any]:
"""生成 public middle_json 视图:图片已落盘引用,base64 临时载荷不再输出。"""
- return {
+ payload = {
"schema_version": MIDDLE_JSON_SCHEMA_VERSION,
"pages": [page.to_dict(skip_defaults=skip_defaults) for page in self.export_pages()],
}
+ self._append_private_pdf_page_mapping(payload)
+ return payload
+
+ def _append_private_pdf_page_mapping(self, payload: dict[str, Any]) -> None:
+ """附加 PDF 重写页映射的内部元数据,供本地可视化按实际 PDF 页序绘制。"""
+ if self._retained_page_indices is not None:
+ payload[_PDF_RETAINED_PAGE_INDICES_KEY] = list(self._retained_page_indices)
+ if self._broken_page_indices:
+ payload[_PDF_BROKEN_PAGE_INDICES_KEY] = list(self._broken_page_indices)
@staticmethod
def from_json(s: str) -> ParseResult:
diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.py
index aa8a8f4e..cc59430b 100644
--- a/mineru/parser/pdf.py
+++ b/mineru/parser/pdf.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import os
from abc import abstractmethod
+from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -13,6 +14,16 @@ from .base import DocumentParser, ParseResult
_IMAGE_SUFFIXES = frozenset({"png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"})
+@dataclass
+class _PreparedPdfInput:
+ """记录 PDF 输入准备结果,避免跨文档复用 parser 实例状态。"""
+
+ file_name: str
+ pdf_bytes: bytes
+ retained_page_indices: list[int] | None = None
+ broken_page_indices: list[int] | None = None
+
+
def _resolve_vlm_backend(backend: str) -> str:
"""Strip the ``vlm-`` prefix and resolve ``auto-engine`` to the concrete engine."""
if not backend.startswith("vlm-"):
@@ -63,20 +74,40 @@ class PdfBaseParser(DocumentParser):
if not path.exists():
raise FileNotFoundError(path)
- file_name, pdf_bytes = self._prepare_input(path, page_range)
- middle_json = self._run_analysis(pdf_bytes, image_writer=None)
- self._fix_page_indices(middle_json)
- return self._build_result(middle_json, pdf_bytes, file_name)
+ prepared = self._prepare_input(path, page_range)
+ middle_json = self._run_analysis(prepared.pdf_bytes, image_writer=None)
+ self._fix_page_indices(
+ middle_json,
+ prepared.retained_page_indices,
+ prepared.broken_page_indices,
+ )
+ return self._build_result(
+ middle_json,
+ prepared.pdf_bytes,
+ prepared.file_name,
+ retained_page_indices=prepared.retained_page_indices,
+ broken_page_indices=prepared.broken_page_indices,
+ )
async def parse_async(self, path: str | Path, *, page_range: str = "") -> ParseResult:
path = Path(path)
if not path.exists():
raise FileNotFoundError(path)
- file_name, pdf_bytes = await asyncio.to_thread(self._prepare_input, path, page_range)
- middle_json = await self._arun_analysis(pdf_bytes, image_writer=None)
- self._fix_page_indices(middle_json)
- return self._build_result(middle_json, pdf_bytes, file_name)
+ 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,
+ prepared.retained_page_indices,
+ prepared.broken_page_indices,
+ )
+ return self._build_result(
+ middle_json,
+ prepared.pdf_bytes,
+ prepared.file_name,
+ retained_page_indices=prepared.retained_page_indices,
+ broken_page_indices=prepared.broken_page_indices,
+ )
@abstractmethod
def _run_analysis(self, pdf_bytes: bytes, image_writer: Any) -> list[PageInfo]:
@@ -85,7 +116,7 @@ class PdfBaseParser(DocumentParser):
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)
- def _prepare_input(self, path: Path, page_range: str = "") -> tuple[str, bytes]:
+ def _prepare_input(self, path: Path, page_range: str = "") -> _PreparedPdfInput:
from ..utils.guess_suffix_or_lang import guess_suffix_by_path
from ..utils.pdf_document import PDFDocument
@@ -96,44 +127,88 @@ class PdfBaseParser(DocumentParser):
if suffix in _IMAGE_SUFFIXES:
pdf_bytes = PDFDocument.from_image(pdf_bytes).bytes
- pdf_bytes = self._maybe_adjust_pdf_bytes(pdf_bytes, suffix, page_range)
- return file_name, pdf_bytes
+ pdf_bytes, retained_page_indices, broken_page_indices = self._maybe_adjust_pdf_bytes(
+ pdf_bytes,
+ suffix,
+ page_range,
+ )
+ return _PreparedPdfInput(
+ file_name=file_name,
+ pdf_bytes=pdf_bytes,
+ retained_page_indices=retained_page_indices,
+ broken_page_indices=broken_page_indices,
+ )
- def _maybe_adjust_pdf_bytes(self, pdf_bytes: bytes, suffix: str, page_range: str = "") -> bytes:
+ def _maybe_adjust_pdf_bytes(
+ self,
+ pdf_bytes: bytes,
+ suffix: str,
+ page_range: str = "",
+ ) -> tuple[bytes, list[int] | None, list[int] | None]:
if suffix != "pdf":
- return pdf_bytes
+ return pdf_bytes, None, None
from ..utils.pdf_document import PDFDocument
from ..utils.pdf_page_id import parse_page_range
doc = PDFDocument(pdf_bytes)
- self._page_indices = parse_page_range(page_range, doc.page_count)
+ page_indices = parse_page_range(page_range, doc.page_count)
- if self._page_indices == list(range(doc.page_count)):
- return pdf_bytes
+ if page_indices == list(range(doc.page_count)):
+ return pdf_bytes, None, None
- from ..utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium
+ from ..utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium_result
- extracted = safe_rewrite_pdf_bytes_with_pdfium(pdf_bytes, page_indices=self._page_indices)
- return extracted or pdf_bytes
+ rewrite_result = safe_rewrite_pdf_bytes_with_pdfium_result(pdf_bytes, page_indices=page_indices)
+ if rewrite_result.used_original:
+ return rewrite_result.pdf_bytes or pdf_bytes, None, rewrite_result.broken_page_indices
+ return (
+ rewrite_result.pdf_bytes or pdf_bytes,
+ rewrite_result.retained_page_indices,
+ rewrite_result.broken_page_indices,
+ )
- def _fix_page_indices(self, pages: list[PageInfo]) -> None:
- """Rewrite ``page_idx`` so it reflects the original document position
- when pages were cropped from a subset."""
- mapping = getattr(self, "_page_indices", None)
- if not mapping:
+ def _fix_page_indices(
+ 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(mapping):
- p.page_idx = mapping[i]
+ 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
+ return
+
+ pages_by_index = {page.page_idx: page for page in fixed_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))
+ for page_idx in ordered_page_indices
+ ]
def _build_result(
self,
middle_json: list[PageInfo],
pdf_bytes: bytes,
file_name: str,
+ *,
+ retained_page_indices: list[int] | None = None,
+ broken_page_indices: list[int] | None = None,
) -> ParseResult:
- return ParseResult(pages=middle_json)
+ return ParseResult(
+ pages=middle_json,
+ _retained_page_indices=retained_page_indices,
+ _broken_page_indices=broken_page_indices,
+ )
class PdfVlmParser(PdfBaseParser):
@@ -193,12 +268,12 @@ class PdfPipelineParser(PdfBaseParser):
from ..backend.pipeline.pipeline_analyze import doc_analyze_streaming
- file_names: list[str] = []
+ prepared_inputs: list[_PreparedPdfInput] = []
pdf_bytes_list: list[bytes] = []
for p in paths:
- fn, pb = self._prepare_input(Path(p), page_range)
- file_names.append(fn)
- pdf_bytes_list.append(pb)
+ prepared = self._prepare_input(Path(p), page_range)
+ prepared_inputs.append(prepared)
+ pdf_bytes_list.append(prepared.pdf_bytes)
results_by_index: dict[int, list[PageInfo]] = {}
@@ -218,7 +293,19 @@ class PdfPipelineParser(PdfBaseParser):
parse_results: list[ParseResult] = []
for idx in range(len(paths)):
middle_json = results_by_index[idx]
- result = self._build_result(middle_json, pdf_bytes_list[idx], file_names[idx])
+ prepared = prepared_inputs[idx]
+ self._fix_page_indices(
+ middle_json,
+ prepared.retained_page_indices,
+ prepared.broken_page_indices,
+ )
+ result = self._build_result(
+ middle_json,
+ prepared.pdf_bytes,
+ prepared.file_name,
+ retained_page_indices=prepared.retained_page_indices,
+ broken_page_indices=prepared.broken_page_indices,
+ )
parse_results.append(result)
return parse_results
@@ -320,9 +407,7 @@ class PdfFlashParser(PdfBaseParser):
pages: list[PageInfo] = []
block_idx = 0
- page_indices = self._page_indices if getattr(self, "_page_indices", None) else list(range(len(pages_text)))
for index, pt in enumerate(pages_text):
- page_idx = page_indices[index] if index < len(page_indices) else index
para_blocks: list[Block] = []
if pt.strip():
span = Span(type="text", bbox=(0.0, 0.0, 0.0, 0.0), content=pt.strip())
@@ -331,7 +416,7 @@ class PdfFlashParser(PdfBaseParser):
para_blocks.append(block)
block_idx += 1
page = PageInfo(
- page_idx=page_idx,
+ page_idx=index,
para_blocks=para_blocks,
)
pages.append(page)
diff --git a/mineru/utils/pdfium_guard.py b/mineru/utils/pdfium_guard.py
index 2c5f3e82..a58827a1 100644
--- a/mineru/utils/pdfium_guard.py
+++ b/mineru/utils/pdfium_guard.py
@@ -1,6 +1,7 @@
# Copyright (c) Opendatalab. All rights reserved.
import threading
from contextlib import contextmanager
+from dataclasses import dataclass, field
from io import BytesIO
from typing import Any, Callable, Iterator, Sequence, TypeVar
@@ -12,6 +13,16 @@ _pdfium_lock = threading.RLock()
T = TypeVar("T")
+@dataclass
+class PdfiumRewriteResult:
+ """记录 PDFium 安全重写结果,供调用方按实际保留页修正原始页号。"""
+
+ pdf_bytes: bytes
+ retained_page_indices: list[int] | None = None
+ broken_page_indices: list[int] = field(default_factory=list)
+ used_original: bool = False
+
+
@contextmanager
def pdfium_guard() -> Iterator[None]:
with _pdfium_lock:
@@ -80,7 +91,11 @@ def get_loadable_pdfium_page_indices(
return [], []
normalized_start_page_id = max(0, start_page_id)
- normalized_end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else total_page_count - 1
+ normalized_end_page_id = (
+ end_page_id
+ if end_page_id is not None and end_page_id >= 0
+ else total_page_count - 1
+ )
if normalized_end_page_id > total_page_count - 1:
normalized_end_page_id = total_page_count - 1
if normalized_start_page_id > normalized_end_page_id:
@@ -105,6 +120,55 @@ def get_loadable_pdfium_page_indices(
return loadable_page_indices, broken_page_indices
+def _normalize_rewrite_page_indices(
+ total_page_count: int,
+ start_page_id: int = 0,
+ end_page_id: int | None = None,
+ page_indices: Sequence[int] | None = None,
+) -> list[int]:
+ """按 rewrite_pdf_bytes_with_pdfium 的规则归一化实际导出的 0-based 页号。"""
+ if total_page_count == 0:
+ return []
+
+ if page_indices is not None:
+ return sorted({int(page_index) for page_index in page_indices if 0 <= int(page_index) < total_page_count})
+
+ normalized_start_page_id = max(0, start_page_id)
+ normalized_end_page_id = (
+ end_page_id
+ if end_page_id is not None and end_page_id >= 0
+ else total_page_count - 1
+ )
+ if normalized_end_page_id > total_page_count - 1:
+ normalized_end_page_id = total_page_count - 1
+ if normalized_start_page_id > normalized_end_page_id:
+ return []
+ return list(range(normalized_start_page_id, normalized_end_page_id + 1))
+
+
+def _get_rewrite_page_indices_from_pdf(
+ src_pdf_bytes: bytes,
+ start_page_id: int = 0,
+ end_page_id: int | None = None,
+ page_indices: Sequence[int] | None = None,
+) -> list[int]:
+ """读取源 PDF 页数并计算本次重写会保留的原始页号。"""
+ import pypdfium2 as pdfium
+
+ pdf_doc = None
+ try:
+ with pdfium_guard():
+ pdf_doc = pdfium.PdfDocument(src_pdf_bytes)
+ return _normalize_rewrite_page_indices(
+ len(pdf_doc),
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ page_indices=page_indices,
+ )
+ finally:
+ close_pdfium_document(pdf_doc)
+
+
def rewrite_pdf_bytes_with_pdfium(
src_pdf_bytes: bytes,
start_page_id: int = 0,
@@ -122,17 +186,14 @@ def rewrite_pdf_bytes_with_pdfium(
if total_page_count == 0:
return b""
- if page_indices is not None:
- normalized_page_indices = sorted(
- {page_index for page_index in page_indices if 0 <= page_index < total_page_count}
- )
- if not normalized_page_indices:
- return b""
- else:
- normalized_end_page_id = end_page_id if end_page_id is not None and end_page_id >= 0 else total_page_count - 1
- if normalized_end_page_id > total_page_count - 1:
- normalized_end_page_id = total_page_count - 1
- normalized_page_indices = list(range(start_page_id, normalized_end_page_id + 1))
+ normalized_page_indices = _normalize_rewrite_page_indices(
+ total_page_count,
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ page_indices=page_indices,
+ )
+ if not normalized_page_indices:
+ return b""
output_doc = pdfium.PdfDocument.new()
output_doc.import_pages(pdf_doc, normalized_page_indices)
@@ -155,6 +216,21 @@ def safe_rewrite_pdf_bytes_with_pdfium(
page_indices: Sequence[int] | None = None,
) -> bytes:
"""安全重写 PDF 字节;常规重写失败时跳过损坏页并保留可加载页面。"""
+ return safe_rewrite_pdf_bytes_with_pdfium_result(
+ src_pdf_bytes,
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ page_indices=page_indices,
+ ).pdf_bytes
+
+
+def safe_rewrite_pdf_bytes_with_pdfium_result(
+ src_pdf_bytes: bytes,
+ start_page_id: int = 0,
+ end_page_id: int | None = None,
+ page_indices: Sequence[int] | None = None,
+) -> PdfiumRewriteResult:
+ """安全重写 PDF 字节,并返回重写后 PDF 对应的原始页号映射。"""
try:
rebuilt_pdf_bytes = rewrite_pdf_bytes_with_pdfium(
src_pdf_bytes,
@@ -163,7 +239,16 @@ def safe_rewrite_pdf_bytes_with_pdfium(
page_indices=page_indices,
)
if rebuilt_pdf_bytes:
- return rebuilt_pdf_bytes
+ retained_page_indices = _get_rewrite_page_indices_from_pdf(
+ src_pdf_bytes,
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ page_indices=page_indices,
+ )
+ return PdfiumRewriteResult(
+ pdf_bytes=rebuilt_pdf_bytes,
+ retained_page_indices=retained_page_indices,
+ )
logger.warning("PDFium rewrite returned empty bytes, trying to skip broken pages.")
except Exception as fallback_error:
logger.warning(
@@ -177,7 +262,7 @@ def safe_rewrite_pdf_bytes_with_pdfium(
)
if not requested_page_indices:
logger.warning("PDFium safe rewrite received no valid requested pages, using original PDF bytes.")
- return src_pdf_bytes
+ return PdfiumRewriteResult(pdf_bytes=src_pdf_bytes, retained_page_indices=None, used_original=True)
probe_start_page_id = requested_page_indices[0]
probe_end_page_id = requested_page_indices[-1]
else:
@@ -208,7 +293,12 @@ def safe_rewrite_pdf_bytes_with_pdfium(
logger.warning(f"Skipped broken PDF pages during PDFium rewrite: {skipped_pages}")
if not loadable_page_indices:
logger.warning("PDFium skip-broken-page rewrite found no loadable pages, using original PDF bytes.")
- return src_pdf_bytes
+ return PdfiumRewriteResult(
+ pdf_bytes=src_pdf_bytes,
+ retained_page_indices=None,
+ broken_page_indices=broken_page_indices,
+ used_original=True,
+ )
rebuilt_pdf_bytes = rewrite_pdf_bytes_with_pdfium(
src_pdf_bytes,
@@ -217,10 +307,14 @@ def safe_rewrite_pdf_bytes_with_pdfium(
page_indices=loadable_page_indices,
)
if rebuilt_pdf_bytes:
- return rebuilt_pdf_bytes
+ return PdfiumRewriteResult(
+ pdf_bytes=rebuilt_pdf_bytes,
+ retained_page_indices=loadable_page_indices,
+ broken_page_indices=broken_page_indices,
+ )
logger.warning("PDFium skip-broken-page rewrite returned empty bytes, using original PDF bytes.")
except Exception as fallback_error:
logger.warning(
f"Error in converting PDF bytes with skip-broken-page fallback: {fallback_error}, using original PDF bytes."
)
- return src_pdf_bytes
+ return PdfiumRewriteResult(pdf_bytes=src_pdf_bytes, retained_page_indices=None, used_original=True)
diff --git a/tests/unittest/test_parser_flash.py b/tests/unittest/test_parser_flash.py
index ec4a4ba2..5517899f 100644
--- a/tests/unittest/test_parser_flash.py
+++ b/tests/unittest/test_parser_flash.py
@@ -7,12 +7,11 @@ def test_flash_parser_preserves_page_indices_for_empty_pages(monkeypatch) -> Non
from mineru.backend.flash import pdf_extractor
parser = PdfFlashParser()
- parser._page_indices = [10, 12, 13]
-
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])
assert [page.page_idx for page in pages] == [10, 12, 13]
assert [len(page.para_blocks) for page in pages] == [1, 0, 1]