Skip to content

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

feat: migrate legacy tier cache directories and update schema version

myhloli95eb2f415af0
diff --git a/mineru/doclib/app.py b/mineru/doclib/app.py
index 9ed1ccc3..324f3c21 100644
--- a/mineru/doclib/app.py
+++ b/mineru/doclib/app.py
@@ -6,11 +6,13 @@ import asyncio
import errno
import logging
import os
+import shutil
import socket
import time
from collections.abc import Callable
from contextlib import asynccontextmanager
from logging.handlers import RotatingFileHandler
+from pathlib import Path
from typing import TYPE_CHECKING, Any, AsyncIterator, cast
import uvicorn
@@ -29,6 +31,8 @@ if TYPE_CHECKING:
else:
LoguruMessage = Any
+_LEGACY_TIER_DIR_MAP = {"standard": "medium", "pro": "high"}
+
def create_app(cfg: Config | None = None) -> FastAPI:
"""Create the new interface-backed FastAPI app."""
@@ -66,6 +70,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:
data_dir = os.path.expanduser(cfg.doclib.data_dir)
os.makedirs(data_dir, exist_ok=True)
+ migrate_legacy_tier_cache_dirs(data_dir)
db_path = os.path.expanduser(cfg.doclib.sqlite.path)
os.makedirs(os.path.dirname(db_path), exist_ok=True)
@@ -277,6 +282,63 @@ def create_app(cfg: Config | None = None) -> FastAPI:
return app
+def migrate_legacy_tier_cache_dirs(data_dir: str) -> None:
+ """将 doclib 历史 standard/pro 缓存目录合并到 medium/high,保留已有目标文件。"""
+ parsed_dir = Path(os.path.expanduser(data_dir)) / "parsed"
+ if not parsed_dir.is_dir():
+ return
+ for prefix_dir in parsed_dir.iterdir():
+ if not prefix_dir.is_dir():
+ continue
+ for doc_dir in prefix_dir.iterdir():
+ if not doc_dir.is_dir():
+ continue
+ for legacy_tier, current_tier in _LEGACY_TIER_DIR_MAP.items():
+ _merge_legacy_tier_cache_dir(doc_dir / legacy_tier, doc_dir / current_tier)
+
+
+def _merge_legacy_tier_cache_dir(source_dir: Path, target_dir: Path) -> None:
+ """把一个旧 tier 目录迁移到目标目录;同名文件以目标目录为准,避免覆盖新结果。"""
+ if not source_dir.is_dir():
+ return
+ if target_dir.exists() and not target_dir.is_dir():
+ return
+ if not target_dir.exists():
+ try:
+ source_dir.rename(target_dir)
+ return
+ except OSError:
+ target_dir.mkdir(parents=True, exist_ok=True)
+ else:
+ target_dir.mkdir(parents=True, exist_ok=True)
+
+ for source_path in sorted(source_dir.rglob("*")):
+ relative_path = source_path.relative_to(source_dir)
+ target_path = target_dir / relative_path
+ if source_path.is_dir():
+ if not target_path.exists():
+ target_path.mkdir(parents=True, exist_ok=True)
+ continue
+ if not source_path.is_file() or target_path.exists():
+ continue
+ target_path.parent.mkdir(parents=True, exist_ok=True)
+ shutil.move(str(source_path), str(target_path))
+ _remove_empty_cache_dirs(source_dir)
+
+
+def _remove_empty_cache_dirs(source_dir: Path) -> None:
+ """清理迁移后已经为空的旧缓存目录;存在冲突残留时保留原目录。"""
+ for child_dir in sorted((path for path in source_dir.rglob("*") if path.is_dir()), reverse=True):
+ try:
+ child_dir.rmdir()
+ except OSError:
+ pass
+ try:
+ source_dir.rmdir()
+ except OSError:
+ pass
+
+
class AppState:
def __init__(self) -> None:
self.db: Any = None
diff --git a/mineru/doclib/core/db.py b/mineru/doclib/core/db.py
index 43c954bc..04164e58 100644
--- a/mineru/doclib/core/db.py
+++ b/mineru/doclib/core/db.py
@@ -11,7 +11,7 @@ import aiosqlite
from ...config import SQLiteConfig
from ..config_defaults import CONFIG_DEFAULTS
-SCHEMA_VERSION = 1
+SCHEMA_VERSION = 2
_MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations"
_T = TypeVar("_T")
diff --git a/mineru/parser/pdf.py b/mineru/parser/pdf.py
index 7cabde20..78f6240e 100644
--- a/mineru/parser/pdf.py
+++ b/mineru/parser/pdf.py
@@ -346,7 +346,13 @@ class PdfFlashParser(PdfBaseParser):
from ..utils.page_index import resolve_output_page_idx
filepath = self._pdf_bytes_to_tempfile(pdf_bytes)
- pages_text = extract_pages_text(filepath)
+ try:
+ pages_text = extract_pages_text(filepath)
+ finally:
+ try:
+ os.unlink(filepath)
+ except OSError:
+ pass
pages: list[PageInfo] = []
block_idx = 0
diff --git a/tests/unittest/test_parser_flash.py b/tests/unittest/test_parser_flash.py
index 42184f5f..af71874e 100644
--- a/tests/unittest/test_parser_flash.py
+++ b/tests/unittest/test_parser_flash.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-from contextlib import contextmanager
-
import pytest
from mineru.errors import MineruError
@@ -21,6 +19,39 @@ def test_flash_parser_preserves_page_indices_for_empty_pages(monkeypatch) -> Non
assert [len(page.para_blocks) for page in pages] == [1, 0, 1]
+def test_flash_parser_unlinks_temp_pdf_after_success(monkeypatch, tmp_path) -> None:
+ from mineru.backend.flash import pdf_extractor
+
+ temp_pdf = tmp_path / "flash-success.pdf"
+ temp_pdf.write_bytes(b"%PDF")
+ parser = PdfFlashParser()
+ monkeypatch.setattr(PdfFlashParser, "_pdf_bytes_to_tempfile", staticmethod(lambda pdf_bytes: str(temp_pdf)))
+ monkeypatch.setattr(pdf_extractor, "extract_pages_text", lambda filepath: ["page text"])
+
+ parser._run_analysis(b"%PDF")
+
+ assert not temp_pdf.exists()
+
+
+def test_flash_parser_unlinks_temp_pdf_after_extractor_failure(monkeypatch, tmp_path) -> None:
+ from mineru.backend.flash import pdf_extractor
+
+ temp_pdf = tmp_path / "flash-failure.pdf"
+ temp_pdf.write_bytes(b"%PDF")
+ parser = PdfFlashParser()
+ monkeypatch.setattr(PdfFlashParser, "_pdf_bytes_to_tempfile", staticmethod(lambda pdf_bytes: str(temp_pdf)))
+
+ def _raise(_filepath: str) -> list[str]:
+ raise RuntimeError("extract failed")
+
+ monkeypatch.setattr(pdf_extractor, "extract_pages_text", _raise)
+
+ with pytest.raises(RuntimeError, match="extract failed"):
+ parser._run_analysis(b"%PDF")
+
+ assert not temp_pdf.exists()
+
+
def test_pdf_parser_rejects_explicit_page_range_with_no_selected_pages(monkeypatch) -> None:
from mineru.utils import pdf_document, pdfium_guard
@@ -42,48 +73,29 @@ def test_flash_pdf_extractor_serializes_pdfium_calls(monkeypatch) -> None:
from mineru.backend.flash import pdf_extractor
assert not hasattr(pdf_extractor, "open_pdfium_document")
+ assert not hasattr(pdf_extractor, "pdfium_guard")
- state = {"guard_depth": 0, "closed_children": 0, "closed_doc": False}
-
- @contextmanager
- def _fake_guard():
- state["guard_depth"] += 1
- try:
- yield
- finally:
- state["guard_depth"] -= 1
+ state = {"entered": False, "closed": False, "requested_pages": []}
- class _FakeTextPage:
- def get_text_range(self) -> str:
- assert state["guard_depth"] > 0
- return "page text"
-
- def close(self) -> None:
- state["closed_children"] += 1
-
- class _FakePage:
- def get_textpage(self) -> _FakeTextPage:
- assert state["guard_depth"] > 0
- return _FakeTextPage()
+ class _FakePdfDocument:
+ def __init__(self, filepath: str) -> None:
+ assert filepath == "dummy.pdf"
+ self.page_count = 2
- def close(self) -> None:
- state["closed_children"] += 1
+ def __enter__(self) -> "_FakePdfDocument":
+ state["entered"] = True
+ return self
- class _FakePdf:
- def __len__(self) -> int:
- assert state["guard_depth"] > 0
- return 2
+ def __exit__(self, exc_type, exc, tb) -> None:
+ state["closed"] = True
- def __getitem__(self, index: int) -> _FakePage:
- assert state["guard_depth"] > 0
- assert index in (0, 1)
- return _FakePage()
+ def get_page_text(self, page_idx: int) -> str:
+ assert state["entered"] is True
+ state["requested_pages"].append(page_idx)
+ return "page text"
- monkeypatch.setattr(pdf_extractor, "pdfium_guard", _fake_guard)
- monkeypatch.setattr(pdf_extractor.pypdfium2, "PdfDocument", lambda filepath: _FakePdf())
- monkeypatch.setattr(pdf_extractor, "close_pdfium_child", lambda obj: obj.close())
- monkeypatch.setattr(pdf_extractor, "close_pdfium_document", lambda pdf: state.__setitem__("closed_doc", True))
+ monkeypatch.setattr(pdf_extractor, "PDFDocument", _FakePdfDocument)
assert pdf_extractor.extract_pages_text("dummy.pdf") == ["page text", "page text"]
- assert state["closed_children"] == 4
- assert state["closed_doc"] is True
+ assert state["requested_pages"] == [0, 1]
+ assert state["closed"] is True