Skip to content

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

feat: fix several issues, add CI

jinzhenj5c864671c13d
diff --git a/.github/scripts/next_dev_release.py b/.github/scripts/next_dev_release.py
new file mode 100644
index 00000000..62cf9a35
--- /dev/null
+++ b/.github/scripts/next_dev_release.py
@@ -0,0 +1,165 @@
+from __future__ import annotations
+
+import argparse
+import json
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+
+
+DEFAULT_BASE_VERSION = "4.0.0"
+
+
+@dataclass(frozen=True)
+class ReleaseState:
+ package: str
+ version: str
+ source_branch: str
+ source_commit: str
+ published_at: str
+
+
+def build_version(base_version: str = DEFAULT_BASE_VERSION, now: datetime | None = None) -> str:
+ current = now or datetime.now(UTC)
+ return f"{base_version}.dev{current.strftime('%Y%m%d')}"
+
+
+def read_state(state_file: str | Path) -> ReleaseState | None:
+ path = Path(state_file)
+ if not path.is_file():
+ return None
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ return ReleaseState(
+ package=payload["package"],
+ version=payload["version"],
+ source_branch=payload["source_branch"],
+ source_commit=payload["source_commit"],
+ published_at=payload["published_at"],
+ )
+
+
+def write_state(
+ state_file: str | Path,
+ *,
+ package: str,
+ version: str,
+ source_branch: str,
+ source_commit: str,
+ published_at: str | None = None,
+) -> None:
+ path = Path(state_file)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ payload = {
+ "package": package,
+ "version": version,
+ "source_branch": source_branch,
+ "source_commit": source_commit,
+ "published_at": published_at or datetime.now(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
+ }
+ path.write_text(f"{json.dumps(payload, ensure_ascii=True, indent=2)}\n", encoding="utf-8")
+
+
+def patch_pyproject_package_name(pyproject_path: str | Path, package_name: str) -> None:
+ path = Path(pyproject_path)
+ lines = path.read_text(encoding="utf-8").splitlines()
+ in_project_section = False
+ replaced = False
+ updated_lines: list[str] = []
+
+ for line in lines:
+ stripped = line.strip()
+ if stripped.startswith("[") and stripped.endswith("]"):
+ in_project_section = stripped == "[project]"
+ if in_project_section and stripped.startswith("name = "):
+ updated_lines.append(f'name = "{package_name}"')
+ replaced = True
+ else:
+ updated_lines.append(line)
+
+ if not replaced:
+ raise ValueError(f"Could not find [project].name in {path}")
+
+ path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")
+
+
+def patch_version_file(version_file_path: str | Path, version: str) -> None:
+ Path(version_file_path).write_text(f'__version__ = "{version}"\n', encoding="utf-8")
+
+
+def patch_workspace(
+ *,
+ pyproject_path: str | Path,
+ version_file_path: str | Path,
+ package_name: str,
+ version: str,
+) -> None:
+ patch_pyproject_package_name(pyproject_path, package_name)
+ patch_version_file(version_file_path, version)
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="Helper utilities for mineru-next-dev daily release workflow.")
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ version_parser = subparsers.add_parser("version", help="Generate the next-dev package version.")
+ version_parser.add_argument("--base-version", default=DEFAULT_BASE_VERSION)
+
+ state_commit_parser = subparsers.add_parser("state-commit", help="Print the last published source commit from state.")
+ state_commit_parser.add_argument("--state-file", required=True)
+
+ write_state_parser = subparsers.add_parser("write-state", help="Write release state JSON.")
+ write_state_parser.add_argument("--state-file", required=True)
+ write_state_parser.add_argument("--package", required=True)
+ write_state_parser.add_argument("--version", required=True)
+ write_state_parser.add_argument("--source-branch", required=True)
+ write_state_parser.add_argument("--source-commit", required=True)
+ write_state_parser.add_argument("--published-at")
+
+ patch_parser = subparsers.add_parser("patch-workspace", help="Patch package name and version in the workspace.")
+ patch_parser.add_argument("--pyproject", required=True)
+ patch_parser.add_argument("--version-file", required=True)
+ patch_parser.add_argument("--package-name", required=True)
+ patch_parser.add_argument("--version", required=True)
+
+ return parser
+
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+
+ if args.command == "version":
+ print(build_version(base_version=args.base_version))
+ return 0
+
+ if args.command == "state-commit":
+ state = read_state(args.state_file)
+ print("" if state is None else state.source_commit)
+ return 0
+
+ if args.command == "write-state":
+ write_state(
+ args.state_file,
+ package=args.package,
+ version=args.version,
+ source_branch=args.source_branch,
+ source_commit=args.source_commit,
+ published_at=args.published_at,
+ )
+ return 0
+
+ if args.command == "patch-workspace":
+ patch_workspace(
+ pyproject_path=args.pyproject,
+ version_file_path=args.version_file,
+ package_name=args.package_name,
+ version=args.version,
+ )
+ return 0
+
+ parser.error(f"Unsupported command: {args.command}")
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/.github/workflows/next-dev-release.yml b/.github/workflows/next-dev-release.yml
new file mode 100644
index 00000000..d9b14c91
--- /dev/null
+++ b/.github/workflows/next-dev-release.yml
@@ -0,0 +1,122 @@
+name: mineru-next-dev-release
+
+on:
+ schedule:
+ - cron: "20 2 * * *"
+ workflow_dispatch:
+
+permissions:
+ contents: write
+
+jobs:
+ publish-next-dev:
+ if: github.repository == 'johnking0099/MinerU-Repo'
+ runs-on: ubuntu-latest
+ env:
+ PACKAGE_NAME: mineru-next-dev
+ BASE_VERSION: 4.0.0
+ SOURCE_BRANCH: next
+ STATE_BRANCH: release-state
+ STATE_FILE: .github/release-state/mineru-next-dev.json
+ steps:
+ - name: Checkout next
+ uses: actions/checkout@v6
+ with:
+ ref: next
+ fetch-depth: 0
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.12"
+
+ - name: Resolve release metadata
+ id: release_meta
+ run: |
+ echo "current_commit=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
+ echo "version=$(python .github/scripts/next_dev_release.py version --base-version "$BASE_VERSION")" >> "$GITHUB_OUTPUT"
+
+ - name: Prepare release-state worktree
+ id: release_state
+ run: |
+ state_dir="$RUNNER_TEMP/release-state"
+ git fetch origin "$STATE_BRANCH" || true
+
+ if git show-ref --verify --quiet "refs/remotes/origin/$STATE_BRANCH"; then
+ git worktree add --force "$state_dir" "refs/remotes/origin/$STATE_BRANCH"
+ else
+ git worktree add --detach "$state_dir" HEAD
+ git -C "$state_dir" checkout --orphan "$STATE_BRANCH"
+ git -C "$state_dir" rm -rf --ignore-unmatch . >/dev/null 2>&1 || true
+ git -C "$state_dir" clean -fdx >/dev/null 2>&1 || true
+ fi
+
+ previous_commit="$(python .github/scripts/next_dev_release.py state-commit --state-file "$state_dir/$STATE_FILE")"
+ should_publish=true
+ if [ -n "$previous_commit" ] && [ "$previous_commit" = "${{ steps.release_meta.outputs.current_commit }}" ]; then
+ should_publish=false
+ fi
+
+ echo "state_dir=$state_dir" >> "$GITHUB_OUTPUT"
+ echo "previous_commit=$previous_commit" >> "$GITHUB_OUTPUT"
+ echo "should_publish=$should_publish" >> "$GITHUB_OUTPUT"
+
+ - name: Stop when next has no changes since last publish
+ if: steps.release_state.outputs.should_publish != 'true'
+ run: |
+ echo "Skip publish because $SOURCE_BRANCH commit ${GITHUB_SHA} matches the last successful release state."
+
+ - name: Install build tooling
+ if: steps.release_state.outputs.should_publish == 'true'
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install build twine
+
+ - name: Patch package metadata for next-dev release
+ if: steps.release_state.outputs.should_publish == 'true'
+ run: |
+ python .github/scripts/next_dev_release.py patch-workspace \
+ --pyproject pyproject.toml \
+ --version-file mineru/version.py \
+ --package-name "$PACKAGE_NAME" \
+ --version "${{ steps.release_meta.outputs.version }}"
+
+ - name: Build distribution
+ if: steps.release_state.outputs.should_publish == 'true'
+ run: |
+ python -m build --wheel
+ python -m twine check dist/*
+
+ - name: Publish to PyPI
+ if: steps.release_state.outputs.should_publish == 'true'
+ env:
+ PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
+ run: |
+ python -m twine upload dist/* -u __token__ -p "$PYPI_TOKEN"
+
+ - name: Update release-state branch
+ if: steps.release_state.outputs.should_publish == 'true'
+ run: |
+ state_dir="${{ steps.release_state.outputs.state_dir }}"
+ python .github/scripts/next_dev_release.py write-state \
+ --state-file "$state_dir/$STATE_FILE" \
+ --package "$PACKAGE_NAME" \
+ --version "${{ steps.release_meta.outputs.version }}" \
+ --source-branch "$SOURCE_BRANCH" \
+ --source-commit "${{ steps.release_meta.outputs.current_commit }}"
+
+ git -C "$state_dir" config user.name "github-actions[bot]"
+ git -C "$state_dir" config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+ git -C "$state_dir" add "$STATE_FILE"
+
+ if git -C "$state_dir" diff --cached --quiet; then
+ echo "No release-state changes to commit."
+ else
+ git -C "$state_dir" commit -m "Update mineru-next-dev release state for ${{ steps.release_meta.outputs.version }}"
+ git -C "$state_dir" push origin HEAD:"$STATE_BRANCH"
+ fi
+
+ - name: Remove release-state worktree
+ if: always() && steps.release_state.outputs.state_dir != ''
+ run: |
+ git worktree remove --force "${{ steps.release_state.outputs.state_dir }}" || true
diff --git a/docs/plans/2026-06-24-mineru-next-dev-release-design.md b/docs/plans/2026-06-24-mineru-next-dev-release-design.md
new file mode 100644
index 00000000..8081e762
--- /dev/null
+++ b/docs/plans/2026-06-24-mineru-next-dev-release-design.md
@@ -0,0 +1,196 @@
+# MinerU Next Dev Daily Release Design
+
+## Goal
+
+Add a new GitHub Actions workflow in the personal repository `johnking0099/MinerU-Repo` to publish a daily development package for the `next` branch.
+
+The published package is separate from the official package:
+
+- package name: `mineru-next-dev`
+- version scheme: `4.0.0.devYYYYMMDD`
+
+The workflow should run once per day. It should publish only when the `next` branch source commit changed since the last successful publish.
+
+## Scope
+
+This design covers:
+
+- workflow trigger strategy
+- package naming and versioning
+- source-change detection
+- release state persistence
+- PyPI publishing flow
+
+This design does not cover:
+
+- changing the official `mineru` release workflow
+- changing upstream `opendatalab/MinerU` workflows
+- supporting multiple scheduled publishes per day
+
+## Requirements
+
+1. The workflow runs in the personal repository, not the upstream repository.
+2. The workflow checks out the `next` branch as the release source.
+3. The workflow runs once per day on a schedule.
+4. If `next` has no source change since the last successful publish, the workflow exits without publishing.
+5. If `next` changed, the workflow publishes a package to the real PyPI index.
+6. The published package name is `mineru-next-dev`.
+7. The published version is `4.0.0.devYYYYMMDD`.
+8. The workflow must support manual execution through `workflow_dispatch`.
+9. Release state must not mutate the `next` branch itself.
+
+## Chosen Approach
+
+Use two branches with distinct roles:
+
+- `next`: source branch used to build the package
+- `release-state`: state-only branch used to record the last successful published commit
+
+The workflow will:
+
+1. Checkout `next`
+2. Resolve the current `next` HEAD commit SHA
+3. Read the last published SHA from a state file on `release-state`
+4. Compare the two SHAs
+5. Skip publish when they match
+6. Patch package metadata locally in the workflow workspace
+7. Build and upload the distribution to PyPI
+8. Update the state file on `release-state` after a successful publish
+
+This avoids the main failure mode of writing state back to `next`, which would otherwise change `HEAD` and force false-positive daily releases.
+
+## State File
+
+State is stored in the repository on branch `release-state`.
+
+Suggested path:
+
+`/.github/release-state/mineru-next-dev.json`
+
+Suggested format:
+
+```json
+{
+ "package": "mineru-next-dev",
+ "version": "4.0.0.dev20260624",
+ "source_branch": "next",
+ "source_commit": "abc123def456",
+ "published_at": "2026-06-24T02:00:00Z"
+}
+```
+
+## Versioning Rules
+
+The package version is always generated from the current UTC date:
+
+- `4.0.0.devYYYYMMDD`
+
+Examples:
+
+- `4.0.0.dev20260624`
+- `4.0.0.dev20260625`
+
+Daily scheduled execution means the normal path produces at most one publish attempt per day. Manual reruns are expected to be for recovery or inspection, not for additional same-day release numbering.
+
+## Package Metadata Strategy
+
+The workflow should patch package metadata only in the transient workflow workspace.
+
+Recommended local modifications before build:
+
+1. patch `[project].name` in `pyproject.toml` from `mineru` to `mineru-next-dev`
+2. patch `mineru/version.py` to the generated `4.0.0.devYYYYMMDD`
+
+These changes should not be committed back to `next`.
+
+This keeps the release package separate from the official package without creating repository noise.
+
+## Workflow Trigger Strategy
+
+The new workflow should support:
+
+- `schedule`
+- `workflow_dispatch`
+
+The schedule should run once per day at a fixed UTC time. The exact cron expression can be tuned later, but the design assumes one scheduled run per day.
+
+## Publish Decision Logic
+
+The workflow should publish only when:
+
+- current `next` HEAD SHA differs from the stored `source_commit` on `release-state`
+
+If the state file does not exist yet, the workflow should treat the run as the initial publish and continue.
+
+If the publish fails, the state file must not be updated.
+
+## Authentication and Secrets
+
+Required repository secrets:
+
+- `PYPI_TOKEN`: used to upload `mineru-next-dev` to PyPI
+
+Required workflow permissions:
+
+- `contents: write`
+
+`contents: write` is needed only for updating the `release-state` branch after a successful publish.
+
+## Failure Handling
+
+1. State write must happen only after PyPI upload succeeds.
+2. If build or upload fails, the workflow should leave `release-state` unchanged.
+3. If `release-state` is missing, the workflow should initialize it.
+4. If the package version already exists on PyPI for the day, manual rerun behavior should fail clearly instead of mutating state incorrectly.
+
+## Alternatives Considered
+
+### Alternative 1: store state on `next`
+
+Rejected.
+
+Reason:
+
+- writing state to `next` changes the branch `HEAD`
+- future runs would always see a changed commit
+- this creates false-positive daily publishes
+
+### Alternative 2: query PyPI for the last published version and infer commit
+
+Rejected.
+
+Reason:
+
+- harder to reconstruct source commit accurately
+- introduces external-state coupling
+- more complex than repository-controlled state
+
+### Alternative 3: use GitHub Releases or artifacts as state
+
+Rejected.
+
+Reason:
+
+- possible, but less transparent and harder to inspect manually
+- repository file state is simpler and easier to repair
+
+## Implementation Plan
+
+Implementation should add:
+
+1. a new workflow under `.github/workflows/`
+2. a small helper script to:
+ - compute the release version
+ - read/write the release-state JSON
+ - patch package metadata in the workspace
+3. initial bootstrap handling for the `release-state` branch
+
+## Open Decisions Already Resolved
+
+- publish target: real PyPI
+- source branch: `next`
+- package name: `mineru-next-dev`
+- version scheme: `4.0.0.devYYYYMMDD`
+- state storage: repository branch `release-state`
+- scheduled frequency: once per day
+
diff --git a/mineru/backend/flash/pdf_extractor.py b/mineru/backend/flash/pdf_extractor.py
index 77be79ea..9840a914 100644
--- a/mineru/backend/flash/pdf_extractor.py
+++ b/mineru/backend/flash/pdf_extractor.py
@@ -4,14 +4,13 @@ from __future__ import annotations
import pypdfium2
-from mineru.utils.pdfium_guard import close_pdfium_objects_safely, pdfium_guard
+from ...utils.pdfium_guard import close_pdfium_child, close_pdfium_document, open_pdfium_document, pdfium_guard
def extract_pages_text(filepath: str, start_page: int = 0, end_page: int | None = None) -> list[str]:
"""Extract plain text from each PDF page, preserving empty pages."""
- with pdfium_guard():
- pdf = pypdfium2.PdfDocument(filepath)
+ pdf = open_pdfium_document(pypdfium2.PdfDocument, filepath)
try:
with pdfium_guard():
total = len(pdf)
@@ -20,17 +19,18 @@ def extract_pages_text(filepath: str, start_page: int = 0, end_page: int | None
pages: list[str] = []
for i in range(start_page, end):
page = None
- tp = None
+ text_page = None
try:
with pdfium_guard():
page = pdf[i]
- tp = page.get_textpage()
- pages.append(tp.get_text_range() or "")
+ text_page = page.get_textpage()
+ pages.append(text_page.get_text_range() or "")
finally:
- close_pdfium_objects_safely(tp, page, owner="flash page text extraction")
+ close_pdfium_child(text_page)
+ close_pdfium_child(page)
return pages
finally:
- close_pdfium_objects_safely(pdf, owner="flash pdf extraction")
+ close_pdfium_document(pdf)
def extract_text(filepath: str, start_page: int = 0, end_page: int | None = None) -> str:
diff --git a/mineru/backend/utils/magic_model_utils.py b/mineru/backend/utils/magic_model_utils.py
index f9775780..8ce4b0a4 100644
--- a/mineru/backend/utils/magic_model_utils.py
+++ b/mineru/backend/utils/magic_model_utils.py
@@ -7,6 +7,7 @@ from typing import Any, Callable, Dict, List, TypeVar
from loguru import logger
+from ...types import Block
from .boxbase import bbox_center_distance, bbox_distance, is_in
T = TypeVar("T")
@@ -38,10 +39,10 @@ def reduct_overlap(bboxes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
def tie_up_category_by_index(
- get_subjects_func: Callable,
- get_objects_func: Callable,
- extract_subject_func: Callable[..., Any] | None = None,
- extract_object_func: Callable[..., Any] | None = None,
+ get_subjects_func: Callable[[], list[Block]],
+ get_objects_func: Callable[[], list[Block]],
+ extract_subject_func: Callable[[Block], Any] | None = None,
+ extract_object_func: Callable[[Block], Any] | None = None,
object_block_type: str = "object",
include_bbox: bool = True,
) -> list[dict[str, Any]]:
@@ -82,7 +83,7 @@ def tie_up_category_by_index(
}
# 提取所有客体的index集合,用于计算有效index差值
- object_indices = {obj["index"] for obj in objects}
+ object_indices = {obj.index for obj in objects}
def calc_effective_index_diff(obj_index: int, sub_index: int) -> int: # noqa: ANN202
"""
@@ -110,13 +111,13 @@ def tie_up_category_by_index(
# 如果没有主体,跳过客体
continue
- obj_index = obj["index"]
+ obj_index = obj.index
min_index_diff = float("inf")
best_subject_indices = []
# 找出有效index差值最小的所有主体
for i, subject in enumerate(subjects):
- sub_index = subject["index"]
+ sub_index = subject.index
index_diff = calc_effective_index_diff(obj_index, sub_index)
if index_diff < min_index_diff:
@@ -132,41 +133,41 @@ def tie_up_category_by_index(
# 只有在包含bbox信息时才进行边缘距离的计算和比较,否则直接匹配第一个主体
if include_bbox:
# 计算所有候选主体的边缘距离
- edge_distances = [(idx, bbox_distance(obj["bbox"], subjects[idx]["bbox"])) for idx in best_subject_indices]
+ edge_distances = [(idx, bbox_distance(obj.bbox, subjects[idx].bbox)) for idx in best_subject_indices]
edge_dist_diff = abs(edge_distances[0][1] - edge_distances[1][1])
for idx, edge_dist in edge_distances:
- logger.debug(f"Obj index: {obj_index}, Sub index: {subjects[idx]['index']}, Edge distance: {edge_dist}")
+ logger.debug(f"Obj index: {obj_index}, Sub index: {subjects[idx].index}, Edge distance: {edge_dist}")
if edge_dist_diff > 2:
# 边缘距离差值大于2,匹配边缘距离更小的主体
best_subject_idx = min(edge_distances, key=lambda x: x[1])[0]
logger.debug(
f"Obj index: {obj_index}, edge_dist_diff > 2, matching to subject with min edge distance,"
- f" index: {subjects[best_subject_idx]['index']}"
+ f" index: {subjects[best_subject_idx].index}"
)
elif object_block_type == "table_caption":
# 边缘距离差值<=2且为table_caption,匹配index更大的主体
- best_subject_idx = max(best_subject_indices, key=lambda idx: subjects[idx]["index"])
+ best_subject_idx = max(best_subject_indices, key=lambda idx: subjects[idx].index)
logger.debug(
f"Obj index: {obj_index}, edge_dist_diff <= 2 and table_caption,"
- f" matching to later subject with index: {subjects[best_subject_idx]['index']}"
+ f" matching to later subject with index: {subjects[best_subject_idx].index}"
)
elif object_block_type.endswith("footnote"):
# 边缘距离差值<=2且为footnote,匹配index更小的主体
- best_subject_idx = min(best_subject_indices, key=lambda idx: subjects[idx]["index"])
+ best_subject_idx = min(best_subject_indices, key=lambda idx: subjects[idx].index)
logger.debug(
f"Obj index: {obj_index}, edge_dist_diff <= 2 and footnote,"
- f" matching to earlier subject with index: {subjects[best_subject_idx]['index']}"
+ f" matching to earlier subject with index: {subjects[best_subject_idx].index}"
)
else:
# 边缘距离差值<=2 且不适用特殊匹配规则,使用中心点距离匹配
center_distances = [
- (idx, bbox_center_distance(obj["bbox"], subjects[idx]["bbox"])) for idx in best_subject_indices
+ (idx, bbox_center_distance(obj.bbox, subjects[idx].bbox)) for idx in best_subject_indices
]
for idx, center_dist in center_distances:
logger.debug(
- f"Obj index: {obj_index}, Sub index: {subjects[idx]['index']}, Center distance: {center_dist}"
+ f"Obj index: {obj_index}, Sub index: {subjects[idx].index}, Center distance: {center_dist}"
)
best_subject_idx = min(center_distances, key=lambda x: x[1])[0]
else:
diff --git a/mineru/backend/utils/office_image.py b/mineru/backend/utils/office_image.py
index f47f8a07..ee0f1def 100644
--- a/mineru/backend/utils/office_image.py
+++ b/mineru/backend/utils/office_image.py
@@ -148,7 +148,7 @@ def serialize_vector_part_with_placeholder(
size: tuple[int, int] = (320, 180),
) -> str:
image_format = _vector_image_format_label(part_name, content_type)
- logger.warning(
+ logger.debug(
f"Skipping {image_format} image part before Pillow load, "
f"part_name={part_name}, content_type={content_type}, requested_size={size}"
)
diff --git a/mineru/cli/commands/search.py b/mineru/cli/commands/search.py
index fa2ee087..1c03847e 100644
--- a/mineru/cli/commands/search.py
+++ b/mineru/cli/commands/search.py
@@ -7,12 +7,16 @@ import typer
from ...doclib.client import DoclibClient
from ...types import Tier
from ..json_errors import exit_with_error
-from ..output import format_search_results, print_error
+from ..output import format_find_results, format_search_results
def search_cmd(
query: str = typer.Argument(..., help="Search query"),
- file_type: str | None = typer.Option(None, "--type", help="File type filter (pdf, docx, ...)"),
+ file_type: str | None = typer.Option(
+ None,
+ "--type",
+ help="File type filter: pdf, docx, pptx, xlsx, html, markdown, csv, rst, tex, txt",
+ ),
tier: Tier | None = typer.Option(None, "--tier", help="Exact search index tier: flash, standard, pro"),
min_tier: Tier | None = typer.Option(None, "--min-tier", help="Minimum search index tier: flash, standard, pro"),
limit: int = typer.Option(20, "--limit", "-n", help="Max results"),
@@ -30,7 +34,11 @@ def search_cmd(
def find_cmd(
query: str = typer.Argument(..., help="Filename search query"),
- ext: str | None = typer.Option(None, "--ext", help="File extension filter, e.g. pdf"),
+ ext: str | None = typer.Option(
+ None,
+ "--ext",
+ help="File extension filter: pdf, docx, pptx, xlsx, html, htm, md, markdown, csv, rst, tex, txt",
+ ),
limit: int = typer.Option(50, "--limit", "-n", help="Max results"),
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
@@ -38,6 +46,6 @@ def find_cmd(
try:
client = DoclibClient(timeout=10)
result = client.find(query, ext=ext, limit=limit)
- format_search_results(result, json_mode=json_mode)
+ format_find_results(result, json_mode=json_mode)
except Exception as exc:
exit_with_error(exc, json_mode=json_mode)
diff --git a/mineru/cli/main.py b/mineru/cli/main.py
index a0c27978..42012313 100644
--- a/mineru/cli/main.py
+++ b/mineru/cli/main.py
@@ -135,7 +135,11 @@ app.add_typer(watch.app, name="watch")
@app.command()
def search(
query: str = typer.Argument(..., help="Search query"),
- file_type: str | None = typer.Option(None, "--type", help="File type filter"),
+ file_type: str | None = typer.Option(
+ None,
+ "--type",
+ help="File type filter: pdf, docx, pptx, xlsx, html, markdown, csv, rst, tex, txt",
+ ),
tier: Tier | None = typer.Option(None, "--tier", help="Exact search index tier: flash, standard, pro"),
min_tier: Tier | None = typer.Option(None, "--min-tier", help="Minimum search index tier: flash, standard, pro"),
limit: int = typer.Option(20, "--limit", "-n", help="Max results"),
@@ -151,7 +155,11 @@ def search(
@app.command()
def find(
query: str = typer.Argument(..., help="Filename search query"),
- ext: str | None = typer.Option(None, "--ext", help="File extension filter, e.g. pdf"),
+ ext: str | None = typer.Option(
+ None,
+ "--ext",
+ help="File extension filter: pdf, docx, pptx, xlsx, html, htm, md, markdown, csv, rst, tex, txt",
+ ),
limit: int = typer.Option(50, "--limit", "-n", help="Max results"),
json_mode: bool = typer.Option(False, "--json", help="JSON output"),
) -> None:
diff --git a/mineru/cli/output.py b/mineru/cli/output.py
index ced3bad6..3d8e58e3 100644
--- a/mineru/cli/output.py
+++ b/mineru/cli/output.py
@@ -60,6 +60,16 @@ def _get(data: Any, key: str, default: Any = None) -> Any:
return getattr(data, key, default)
+def _format_result_path(paths: Any) -> str:
+ if not paths:
+ return ""
+ return f" ({paths[0]})"
+
+
+def _format_snippet(snippet: Any) -> str:
+ return str(snippet or "").replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ")[:80]
+
+
# ── parse ──────────────────────────────────────────────────────
@@ -94,25 +104,53 @@ def format_search_results(data: Any, json_mode: bool = False) -> None:
print_info("No results found.")
return
- table = Table(title=f"Search results ({total} total)")
- table.add_column("File", style="cyan", no_wrap=True)
- table.add_column("Tier", style="green", width=10)
- table.add_column("Snippet", style="dim")
- table.add_column("Paths", style="dim")
+ lines = [f"Search results ({total} total)"]
+ for index, result in enumerate(results, start=1):
+ filename = _get(result, "title") or _get(result, "filename", "?")
+ tier = _get(result, "tier", "")
+ snippet = _format_snippet(_get(result, "snippet", ""))
+ path = _format_result_path(_get(result, "paths", []))
+ item_line = f"{index}. {filename}{path}"
+ if tier:
+ item_line += f" Tier: {tier}"
+ lines.append(item_line)
+ if snippet:
+ lines.append(f" {snippet}")
+ if index < len(results):
+ lines.append("")
+
+ output = "\n".join(lines)
+ if console:
+ console.print(Text(output))
+ else:
+ print(output)
+
- for r in results:
- table.add_row(
- _get(r, "title") or _get(r, "filename", "?"),
- _get(r, "tier", ""),
- (_get(r, "snippet", "") or "")[:80],
- ", ".join(_get(r, "paths", [])[:3]),
- )
+def format_find_results(data: Any, json_mode: bool = False) -> None:
+ results = _get(data, "results", [])
+ total = _get(data, "total", 0)
+ if json_mode:
+ print_json(data)
+ return
+
+ if not results:
+ print_info("No results found.")
+ return
+
+ lines = [f"Search results ({total} total)"]
+ for index, result in enumerate(results, start=1):
+ filename = _get(result, "title") or _get(result, "filename", "?")
+ path = _format_result_path(_get(result, "paths", []))
+ lines.append(f"{index}. {filename}{path}")
+ if index < len(results):
+ lines.append("")
+
+ output = "\n".join(lines)
if console:
- console.print(table)
+ console.print(Text(output))
else:
- for r in results:
- print(f"{_get(r, 'title')} [{_get(r, 'tier')}] — {', '.join(_get(r, 'paths', []))}")
+ print(output)
# ── server status ──────────────────────────────────────────────
diff --git a/mineru/doclib/app.py b/mineru/doclib/app.py
index b4a0b9e8..34e87579 100644
--- a/mineru/doclib/app.py
+++ b/mineru/doclib/app.py
@@ -13,17 +13,23 @@ import time
from collections.abc import Callable
from contextlib import asynccontextmanager
from logging.handlers import RotatingFileHandler
-from typing import Any
+from typing import TYPE_CHECKING, Any, AsyncIterator
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
+from loguru import logger as loguru_logger
-from ..errors import MineruError, error_response, http_status_for
from ..config import Config, LogConfig, _mineru_home, config
+from ..errors import MineruError, error_response, http_status_for
from .endpoint import EndpointTransport, remove_endpoint_file, uds_available, write_endpoint_file
from .server import DoclibServer
-from .types import PARSE_STATUS_FAILED, PARSE_STATUS_PARSING
+from .types import PARSE_STATUS_FAILED, PARSE_STATUS_PARSING, SCAN_STATUS_FAILED, SCAN_STATUS_RUNNING
+
+if TYPE_CHECKING:
+ from loguru import Message as LoguruMessage
+else:
+ LoguruMessage = Any
def create_app(cfg: Config | None = None) -> FastAPI:
@@ -93,6 +99,20 @@ def create_app(cfg: Config | None = None) -> FastAPI:
"UPDATE parses SET locked_at = NULL, status = ? WHERE status = ?",
(PARSE_STATUS_FAILED, PARSE_STATUS_PARSING),
)
+ now_ms = int(time.time() * 1000)
+ await state.db.execute(
+ "UPDATE scans SET locked_at = NULL, status = ?, error_code = COALESCE(error_code, ?), "
+ "error_msg = COALESCE(error_msg, ?), finished_at = COALESCE(finished_at, ?), updated_at = ? "
+ "WHERE status = ?",
+ (
+ SCAN_STATUS_FAILED,
+ "scan_interrupted",
+ "Scan was interrupted by server shutdown or crash.",
+ now_ms,
+ now_ms,
+ SCAN_STATUS_RUNNING,
+ ),
+ )
state.parse_server_proc = None
local_mode = (await state.config_svc.get("parse_server.local.mode")) or "disabled"
@@ -198,11 +218,13 @@ def create_app(cfg: Config | None = None) -> FastAPI:
if c and hasattr(c, "stop"):
await c.stop()
+ await _cancel_background_tasks(state)
+
if state.db:
await state.db.close()
@asynccontextmanager
- async def lifespan(_app: FastAPI):
+ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
await startup()
try:
yield
@@ -268,6 +290,7 @@ class AppState:
self.compaction: Any = None
self.health_check: Any = None
self.telemetry_flush: Any = None
+ self.background_tasks: list[asyncio.Task[Any]] = []
self.start_time: float = 0.0
self.pid: int = 0
self.mineru_home: str = ""
@@ -310,7 +333,52 @@ async def _assert_required_schema(db: Any) -> None:
def _create_background_task(state: AppState, name: str, runner: Callable[[], Any]) -> asyncio.Task:
- return asyncio.create_task(_run_after_db_ready(state, name, runner))
+ task = asyncio.create_task(_run_after_db_ready(state, name, runner), name=f"doclib:{name}")
+ state.background_tasks.append(task)
+ task.add_done_callback(lambda completed: _finish_background_task(state, name, completed))
+ return task
+
+
+def _finish_background_task(state: AppState, name: str, task: asyncio.Task[Any]) -> None:
+ _log_background_task_result(name, task)
+ if task in state.background_tasks:
+ state.background_tasks.remove(task)
+
+
+def _log_background_task_result(name: str, task: asyncio.Task[Any]) -> None:
+ if task.cancelled():
+ return
+ try:
+ exc = task.exception()
+ except asyncio.CancelledError:
+ return
+ if exc is not None:
+ logging.error(
+ "Background task %s crashed: %s",
+ name,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
+
+
+async def _cancel_background_tasks(state: AppState) -> None:
+ tasks = list(state.background_tasks)
+ for task in tasks:
+ if not task.done():
+ task.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ state.background_tasks.clear()
+
+
+def _cancel_pending_loop_tasks(loop: asyncio.AbstractEventLoop) -> None:
+ if loop.is_closed():
+ return
+ tasks = [task for task in asyncio.all_tasks(loop) if not task.done()]
+ for task in tasks:
+ task.cancel()
+ if tasks:
+ loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
async def _run_after_db_ready(state: AppState, name: str, runner: Callable[[], Any]) -> None:
@@ -337,7 +405,9 @@ def main() -> None:
if not uds_enabled and not tcp_enabled:
raise RuntimeError("At least one doclib local transport must be enabled.")
if uds_enabled and not uds_available():
- raise RuntimeError("Unix domain socket is enabled but is not available in this Python runtime. Enable doclib.tcp or disable doclib.uds.")
+ raise RuntimeError(
+ "Unix domain socket is enabled but is not available in this Python runtime. Enable doclib.tcp or disable doclib.uds."
+ )
app = create_app(cfg)
uv_config = uvicorn.Config(
@@ -403,6 +473,7 @@ def main() -> None:
except OSError:
pass
remove_endpoint_file(endpoint_path)
+ _cancel_pending_loop_tasks(loop)
loop.close()
@@ -441,6 +512,7 @@ def _setup_logging(log_cfg: LogConfig) -> None:
logger.addHandler(access_handler)
logging.captureWarnings(True)
+ _setup_loguru_bridge(log_cfg.level.upper())
def _ensure_log_dir(path: str) -> None:
@@ -449,6 +521,31 @@ def _ensure_log_dir(path: str) -> None:
os.makedirs(log_dir, exist_ok=True)
+def _setup_loguru_bridge(level_name: str) -> None:
+ loguru_logger.remove()
+ loguru_logger.add(
+ _forward_loguru_to_logging,
+ level=level_name,
+ backtrace=False,
+ diagnose=False,
+ format="{message}",
+ )
+
+
+def _forward_loguru_to_logging(message: LoguruMessage) -> None:
+ record = message.record
+ logger_name = record["name"] or "mineru.loguru"
+ exc = record["exception"]
+ exc_info = None
+ if exc is not None and exc.type is not None and exc.value is not None:
+ exc_info = (exc.type, exc.value, exc.traceback)
+ logging.getLogger(logger_name).log(
+ record["level"].no,
+ record["message"],
+ exc_info=exc_info,
+ )
+
+
def _rotating_log_handler(path: str, level: int) -> RotatingFileHandler:
handler = RotatingFileHandler(path, maxBytes=5 * 1024 * 1024, backupCount=3)
handler.setLevel(level)
diff --git a/mineru/doclib/background/ingest.py b/mineru/doclib/background/ingest.py
index f883a19c..b71c8e4a 100644
--- a/mineru/doclib/background/ingest.py
+++ b/mineru/doclib/background/ingest.py
@@ -25,6 +25,8 @@ class IngestWorkerPool:
async def run(self) -> None:
self.running = True
self._tasks = [asyncio.create_task(self._worker(i)) for i in range(self.num_workers)]
+ for index, task in enumerate(self._tasks):
+ task.add_done_callback(lambda completed, worker_id=index: self._log_task_result(worker_id, completed))
async def _worker(self, worker_id: int) -> None:
logger.info(f"Ingest worker {worker_id} started")
@@ -54,7 +56,13 @@ class IngestWorkerPool:
if processed % 100 == 0:
logger.info(f"Ingest worker {worker_id} ingested {processed} files")
except Exception as exc:
- logger.error(f"Ingest worker {worker_id} error on {task.get('path')}: {exc}")
+ logger.error(
+ "Ingest worker %s error on %s: %s",
+ worker_id,
+ task.get("path"),
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
await self._handle_ingest_error(task, exc)
logger.info(f"Ingest worker {worker_id} stopped, processed {processed} total")
@@ -107,3 +115,19 @@ class IngestWorkerPool:
t.cancel()
if self._tasks:
await asyncio.gather(*self._tasks, return_exceptions=True)
+
+ @staticmethod
+ def _log_task_result(worker_id: int, task: asyncio.Task[None]) -> None:
+ if task.cancelled():
+ return
+ try:
+ exc = task.exception()
+ except asyncio.CancelledError:
+ return
+ if exc is not None:
+ logger.error(
+ "Ingest worker %s crashed: %s",
+ worker_id,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
diff --git a/mineru/doclib/background/parse_worker.py b/mineru/doclib/background/parse_worker.py
index dc6afb9a..7fa5f5df 100644
--- a/mineru/doclib/background/parse_worker.py
+++ b/mineru/doclib/background/parse_worker.py
@@ -24,6 +24,8 @@ class ParseWorkerPool:
self._tasks = [
asyncio.create_task(self._worker(i)) for i in range(self.num_workers)
]
+ for index, task in enumerate(self._tasks):
+ task.add_done_callback(lambda completed, worker_id=index: self._log_task_result(worker_id, completed))
async def _worker(self, worker_id: int) -> None:
logger.info(f"Parse worker {worker_id} started")
@@ -51,7 +53,11 @@ class ParseWorkerPool:
)
except Exception as exc:
logger.error(
- f"Parse worker {worker_id} error on {task.get('sha256')}: {exc}"
+ "Parse worker %s error on %s: %s",
+ worker_id,
+ task.get("sha256"),
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
)
try:
now = int(time.time() * 1000)
@@ -71,3 +77,19 @@ class ParseWorkerPool:
t.cancel()
if self._tasks:
await asyncio.gather(*self._tasks, return_exceptions=True)
+
+ @staticmethod
+ def _log_task_result(worker_id: int, task: asyncio.Task[None]) -> None:
+ if task.cancelled():
+ return
+ try:
+ exc = task.exception()
+ except asyncio.CancelledError:
+ return
+ if exc is not None:
+ logger.error(
+ "Parse worker %s crashed: %s",
+ worker_id,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
diff --git a/mineru/doclib/background/scan_worker.py b/mineru/doclib/background/scan_worker.py
index 41b18ee0..1b3c4438 100644
--- a/mineru/doclib/background/scan_worker.py
+++ b/mineru/doclib/background/scan_worker.py
@@ -20,6 +20,8 @@ class ScanWorkerPool:
async def run(self) -> None:
self.running = True
self._tasks = [asyncio.create_task(self._worker(i)) for i in range(self.num_workers)]
+ for index, task in enumerate(self._tasks):
+ task.add_done_callback(lambda completed, worker_id=index: self._log_task_result(worker_id, completed))
async def _worker(self, worker_id: int) -> None:
logger.info("Scan worker %s started", worker_id)
@@ -34,7 +36,13 @@ class ScanWorkerPool:
if success:
processed += 1
except Exception as exc:
- logger.error("Scan worker %s error on scan %s: %s", worker_id, task.get("id"), exc)
+ logger.error(
+ "Scan worker %s error on scan %s: %s",
+ worker_id,
+ task.get("id"),
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
logger.info("Scan worker %s stopped, processed %s total", worker_id, processed)
async def stop(self) -> None:
@@ -43,3 +51,19 @@ class ScanWorkerPool:
task.cancel()
if self._tasks:
await asyncio.gather(*self._tasks, return_exceptions=True)
+
+ @staticmethod
+ def _log_task_result(worker_id: int, task: asyncio.Task[None]) -> None:
+ if task.cancelled():
+ return
+ try:
+ exc = task.exception()
+ except asyncio.CancelledError:
+ return
+ if exc is not None:
+ logger.error(
+ "Scan worker %s crashed: %s",
+ worker_id,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
diff --git a/mineru/doclib/background/watch.py b/mineru/doclib/background/watch.py
index 7cf21f58..a926fc64 100644
--- a/mineru/doclib/background/watch.py
+++ b/mineru/doclib/background/watch.py
@@ -3,18 +3,21 @@
from __future__ import annotations
import asyncio
+import logging
import os
from pathlib import Path
from watchfiles import awatch
from ..core.db import DatabaseManager
-from ..constants import ALLOWED_EXTENSIONS
+from ..constants import ALLOWED_EXTENSIONS, is_office_temp_lock_file
from ..services.config_svc import ConfigService
from ..services.parse_svc import ParseService
from ..services.scan_svc import ScanService
from ..types import FILE_STATUS_ACTIVE, WATCH_STATUS_ACTIVE, WATCH_STATUS_UNREACHABLE
+logger = logging.getLogger("mineru.watch")
+
class WatchLoop:
def __init__(
@@ -33,6 +36,7 @@ class WatchLoop:
self.scan_interval_sec = scan_interval_sec
self.running = False
self._active_watchers: dict[int, asyncio.Task] = {}
+ self._wakeup_event = asyncio.Event()
async def run(self) -> None:
self.running = True
@@ -46,17 +50,26 @@ class WatchLoop:
active_ids.add(w["id"])
if w["id"] not in self._active_watchers:
- await self._initial_scan(w["path"], w["id"])
task = asyncio.create_task(self._watch_one(w["path"], w["id"]))
+ task.add_done_callback(
+ lambda completed, wid=w["id"], path=w["path"]: self._log_watcher_result(wid, path, completed)
+ )
self._active_watchers[w["id"]] = task
+ await asyncio.sleep(0)
+ await self._initial_scan(w["path"], w["id"])
# cancel watchers for removed watches
for wid in list(self._active_watchers):
if wid not in active_ids:
self._active_watchers[wid].cancel()
- del self._active_watchers[wid]
+ task = self._active_watchers.pop(wid)
+ await asyncio.gather(task, return_exceptions=True)
- await asyncio.sleep(self.scan_interval_sec)
+ try:
+ await asyncio.wait_for(self._wakeup_event.wait(), timeout=self.scan_interval_sec)
+ except asyncio.TimeoutError:
+ pass
+ self._wakeup_event.clear()
async def _initial_scan(self, path: str, watch_id: int) -> None:
"""Verify known files, then walk directory tree to discover current files."""
@@ -84,15 +97,21 @@ class WatchLoop:
for fname in files:
filepath = os.path.join(root, fname)
ext = Path(filepath).suffix.lstrip(".").lower()
- if ext not in ALLOWED_EXTENSIONS:
+ if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(filepath):
continue
if await self.config_svc.is_path_excluded(filepath):
continue
await self._refresh_file(filepath, watch_id)
file_count += 1
await self.config_svc.update_watch_scan_stats(watch_id, file_count)
- except Exception:
- pass
+ except Exception as exc:
+ logger.error(
+ "Watch initial scan failed for watch_id=%s path=%s: %s",
+ watch_id,
+ path,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
async def _watch_one(self, path: str, watch_id: int) -> None:
try:
@@ -101,12 +120,18 @@ class WatchLoop:
break
for _change_type, filepath in changes:
await self._handle_event(filepath, watch_id)
- except Exception:
- pass
+ except Exception as exc:
+ logger.error(
+ "Watch loop failed for watch_id=%s path=%s: %s",
+ watch_id,
+ path,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
async def _handle_event(self, filepath: str, watch_id: int) -> None:
ext = Path(filepath).suffix.lstrip(".").lower()
- if ext not in ALLOWED_EXTENSIONS:
+ if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(filepath):
return
if await self.config_svc.is_path_excluded(filepath):
return
@@ -117,5 +142,30 @@ class WatchLoop:
async def stop(self) -> None:
self.running = False
- for t in self._active_watchers.values():
+ self.wakeup()
+ tasks = list(self._active_watchers.values())
+ for t in tasks:
t.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ self._active_watchers.clear()
+
+ def wakeup(self) -> None:
+ self._wakeup_event.set()
+
+ @staticmethod
+ def _log_watcher_result(watch_id: int, path: str, task: asyncio.Task[None]) -> None:
+ if task.cancelled():
+ return
+ try:
+ exc = task.exception()
+ except asyncio.CancelledError:
+ return
+ if exc is not None:
+ logger.error(
+ "Watch task crashed for watch_id=%s path=%s: %s",
+ watch_id,
+ path,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
diff --git a/mineru/doclib/constants.py b/mineru/doclib/constants.py
index 2d5254e5..af7233be 100644
--- a/mineru/doclib/constants.py
+++ b/mineru/doclib/constants.py
@@ -2,8 +2,16 @@
from __future__ import annotations
+from pathlib import Path
+
# ── file types ─────────────────────────────────────────────────────
+OFFICE_EXTENSIONS: set[str] = {
+ "docx",
+ "pptx",
+ "xlsx",
+}
+
TEXT_EXTENSIONS: set[str] = {
"csv",
"md",
@@ -15,9 +23,7 @@ TEXT_EXTENSIONS: set[str] = {
ALLOWED_EXTENSIONS: set[str] = {
"pdf",
- "docx",
- "pptx",
- "xlsx",
+ *OFFICE_EXTENSIONS,
"html",
"htm",
*TEXT_EXTENSIONS,
@@ -39,6 +45,11 @@ ALLOWED_EXTENSIONS: set[str] = {
# "mbox",
}
+
+def is_office_temp_lock_file(path: str | Path) -> bool:
+ file_path = Path(path)
+ return file_path.name.startswith("~$") and file_path.suffix.lower().lstrip(".") in OFFICE_EXTENSIONS
+
DEFAULT_EXCLUDE_PATTERNS: list[str] = [
"*/Library/*",
"*/.git/*",
diff --git a/mineru/doclib/core/file_io.py b/mineru/doclib/core/file_io.py
index 1bc4b4df..6317bef8 100644
--- a/mineru/doclib/core/file_io.py
+++ b/mineru/doclib/core/file_io.py
@@ -10,6 +10,8 @@ from pathlib import Path
import pypdfium2
+from ...utils.pdfium_guard import close_pdfium_document, open_pdfium_document, pdfium_guard
+
# Optional office doc support
try:
from docx import Document
@@ -105,18 +107,19 @@ async def extract_metadata(filepath: str) -> dict:
async def _extract_pdf_meta(filepath: str, result: dict) -> None:
def _extract() -> None:
- pdf = pypdfium2.PdfDocument(filepath)
+ pdf = open_pdfium_document(pypdfium2.PdfDocument, filepath)
try:
- result["page_count"] = len(pdf)
+ with pdfium_guard():
+ result["page_count"] = len(pdf)
+ meta = pdf.get_metadata_dict() or {}
- meta = pdf.get_metadata_dict() or {}
result["title"] = meta.get("Title") or None
result["author"] = meta.get("Author") or None
result["subject"] = meta.get("Subject") or None
result["keywords"] = meta.get("Keywords") or None
finally:
- pdf.close()
+ close_pdfium_document(pdf)
await asyncio.to_thread(_extract)
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 1d9f3378..6882e0e1 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -224,7 +224,10 @@ class DoclibServer(AsyncDoclibInterface):
"SELECT COUNT(*) as cnt FROM scans WHERE status IN (?, ?)",
("pending", "running"),
)
- last_scan = await self.state.db.fetchone("SELECT MAX(updated_at) as ts FROM scans")
+ last_scan = await self.state.db.fetchone(
+ "SELECT MAX(COALESCE(finished_at, updated_at)) as ts FROM scans WHERE status IN (?, ?)",
+ ("done", "failed"),
+ )
ingest_q = await self.state.db.fetchone(
"SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND status=? AND error_code IS NULL",
(FILE_STATUS_ACTIVE,),
@@ -799,6 +802,9 @@ class DoclibServer(AsyncDoclibInterface):
await _record_telemetry_count(self.state, "watch.add.count")
try:
row = await self.state.config_svc.add_watch(request.path, removable=request.removable, label=request.label)
+ watch_loop = getattr(self.state, "watch", None)
+ if watch_loop is not None:
+ watch_loop.wakeup()
await _record_telemetry_count(self.state, "watch.add.finished.count", dimensions={"status": "succeeded"})
return _watch_info(row)
except Exception:
diff --git a/mineru/doclib/services/config_svc.py b/mineru/doclib/services/config_svc.py
index b6269343..0f7c809e 100644
--- a/mineru/doclib/services/config_svc.py
+++ b/mineru/doclib/services/config_svc.py
@@ -3,12 +3,11 @@
from __future__ import annotations
import fnmatch
+import hashlib
import os
import time
from typing import cast
-import fnvhash
-
from ...errors import InvalidRequestError
from ...types import Tier
from ..config_defaults import CONFIG_DEFAULTS, CONFIG_SOURCE_DEFAULT, CONFIG_SOURCE_OVERRIDE, ConfigSource
@@ -79,6 +78,11 @@ class ConfigService:
# ── watch targets ───────────────────────────────────────────
+ @staticmethod
+ def _watch_id_for_path(path: str) -> int:
+ digest = hashlib.blake2b(path.encode("utf-8"), digest_size=8).digest()
+ return int.from_bytes(digest, "big") & ((1 << 63) - 1)
+
async def add_watch(
self, path: str, removable: bool = False, label: str | None = None
) -> WatchTargetRow:
@@ -89,7 +93,7 @@ class ConfigService:
if not os.path.isdir(path):
raise InvalidRequestError("invalid_request", f"Watch path does not exist or is not a directory: {path}", "path")
- wid = fnvhash.fnv1a_64(path.encode()) & ((1 << 63) - 1)
+ wid = self._watch_id_for_path(path)
now = int(time.time() * 1000)
await self.db.execute(
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index d5dba129..957aed9a 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import json
+import logging
import os
import time
from collections.abc import Sequence
@@ -16,7 +17,7 @@ from ...errors import MineruError
from ...parser.base import ParseResult
from ...types import TIER_ORDER, PageInfo, Tier
from ...utils.image_payload import parse_image_data_uri
-from ..constants import ALLOWED_EXTENSIONS, TEXT_EXTENSIONS
+from ..constants import ALLOWED_EXTENSIONS, TEXT_EXTENSIONS, is_office_temp_lock_file
from ..core.db import DatabaseManager
from ..core.file_io import FileStat, compute_sha256, extract_metadata, get_file_stat
from ..core.fts import FTSManager
@@ -37,6 +38,8 @@ from ..types import (
)
from .config_svc import ConfigService
+logger = logging.getLogger("mineru.parse")
+
def _now_ms() -> int:
return int(time.time() * 1000)
@@ -273,7 +276,7 @@ class ParseService:
"""
ext = Path(path).suffix.lower().lstrip(".")
existing = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))
- if ext not in ALLOWED_EXTENSIONS:
+ if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(path):
return FileRefreshResult(file=_file_info(existing), status="unsupported")
try:
@@ -412,7 +415,7 @@ class ParseService:
async def ensure_ingested(self, path: str, watch_id: int | None = None) -> FileRow | None:
"""Synchronously discover and ingest a source path when needed."""
refreshed = await self.refresh_file(path, watch_id=watch_id, ensure_ingested=True)
- if refreshed.file is None:
+ if refreshed.file is None or refreshed.status == "unsupported":
return None
return cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))
@@ -433,7 +436,7 @@ class ParseService:
async def _ingest_file(self, path: str, watch_id: int | None = None) -> FileRow | None:
"""Ingest implementation without telemetry wrapper."""
ext = Path(path).suffix.lower().lstrip(".")
- if ext not in ALLOWED_EXTENSIONS:
+ if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(path):
return None
stat = await get_file_stat(path)
@@ -589,17 +592,16 @@ class ParseService:
# insert parse batch
parse_page_range = expand_page_range(initial_page_range, page_count or 1)
+ await self.db.execute(
+ "UPDATE files SET sha256=?, locked_at=NULL, updated_at=? WHERE path=?",
+ (sha256, now, path),
+ )
await self.db.execute(
"INSERT INTO parses (sha256, tier, page_range, status, priority, created_at, updated_at) VALUES (?, ?, ?, ?, 0, ?, ?)",
(sha256, tier, parse_page_range, PARSE_STATUS_PENDING, now, now),
)
await self._record_count("parse_task.created.count", dimensions={"tier": tier})
- await self.db.execute(
- "UPDATE files SET sha256=?, locked_at=NULL, updated_at=? WHERE path=?",
- (sha256, now, path),
- )
-
return cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))
# ── parse request ───────────────────────────────────────────
@@ -778,6 +780,15 @@ class ParseService:
error_code="no_accessible_file",
)
return False
+ if is_office_temp_lock_file(file_row["path"]):
+ await self._fail_task(task["id"], "file_type_unsupported", "Office temporary lock files are not supported")
+ await self._record_parse_task_finished(
+ task_start_ms,
+ tier=tier,
+ status="failed",
+ error_code="file_type_unsupported",
+ )
+ return False
output_dir = os.path.join(self.data_dir, "parsed", sha256[:2], sha256, tier)
@@ -803,6 +814,15 @@ class ParseService:
await self._record_parse_task_finished(task_start_ms, tier=tier, status="failed", error_code=exc.code)
return False
except Exception as exc:
+ logger.error(
+ "Parse execution failed for task_id=%s path=%s tier=%s page_range=%s: %s",
+ task["id"],
+ file_row["path"],
+ tier,
+ page_range,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
await self._record_execute(
execute_start_ms,
tier=tier,
@@ -832,6 +852,15 @@ class ParseService:
with open(json_path, "w", encoding="utf-8") as f:
json.dump(export_payload, f, ensure_ascii=False, indent=4)
except Exception as exc:
+ logger.error(
+ "Parse post-write finalization failed for task_id=%s path=%s tier=%s page_range=%s: %s",
+ task["id"],
+ file_row["path"],
+ tier,
+ page_range,
+ exc,
+ exc_info=(type(exc), exc, exc.__traceback__),
+ )
await self._fail_task(task["id"], "parse_json_write_failed", str(exc)[:500])
await self._record_write(
write_start_ms,
diff --git a/mineru/doclib/services/scan_svc.py b/mineru/doclib/services/scan_svc.py
index d0ec2b04..4cc53d0b 100644
--- a/mineru/doclib/services/scan_svc.py
+++ b/mineru/doclib/services/scan_svc.py
@@ -9,7 +9,7 @@ from pathlib import Path
from typing import Any, cast
from ...errors import InvalidRequestError, NotFoundError
-from ..constants import ALLOWED_EXTENSIONS
+from ..constants import ALLOWED_EXTENSIONS, is_office_temp_lock_file
from ..core.file_io import get_file_stat
from ..rows import PathRow, ScanRow, WatchTargetRow
from ..types import (
@@ -95,6 +95,8 @@ class ScanService:
elif watch_id is not None:
raise InvalidRequestError("invalid_request", "watch_id is only valid for watch scans.", "watch_id")
+ await self._fail_stale_running_scans(kind=kind, path=normalized_path)
+
active = cast(
ScanRow | None,
await self.db.fetchone(
@@ -220,6 +222,26 @@ class ScanService:
await self._record_scan_file_counts(counters)
return True
+ async def _fail_stale_running_scans(self, *, kind: ScanKind, path: str) -> None:
+ now = _now_ms()
+ timeout = now - self.scan_lock_timeout_ms
+ await self.db.execute(
+ "UPDATE scans SET status=?, locked_at=NULL, error_code=COALESCE(error_code, ?), "
+ "error_msg=COALESCE(error_msg, ?), finished_at=COALESCE(finished_at, ?), updated_at=? "
+ "WHERE kind=? AND path=? AND status=? AND locked_at IS NOT NULL AND locked_at < ?",
+ (
+ SCAN_STATUS_FAILED,
+ "scan_interrupted",
+ "Scan lock expired before completion.",
+ now,
+ now,
+ kind,
+ path,
+ SCAN_STATUS_RUNNING,
+ timeout,
+ ),
+ )
+
async def cleanup_terminal_scan_logs(self, *, keep: int = SCAN_LOG_RETENTION_LIMIT) -> None:
try:
await self.db.execute(
@@ -276,7 +298,7 @@ class ScanService:
filepath = os.path.join(root, fname)
counters.files_seen += 1
ext = Path(filepath).suffix.lstrip(".").lower()
- if ext not in ALLOWED_EXTENSIONS:
+ if ext not in ALLOWED_EXTENSIONS or is_office_temp_lock_file(filepath):
counters.files_unsupported += 1
continue
if apply_excludes and await self.config_svc.is_path_excluded(filepath):
diff --git a/mineru/parser/__init__.py b/mineru/parser/__init__.py
index d73e5cfa..6ccceaea 100644
--- a/mineru/parser/__init__.py
+++ b/mineru/parser/__init__.py
@@ -30,6 +30,21 @@ __all__ = [
"resolve_tier_and_backend",
]
+_OFFICE_SUFFIXES = frozenset({"docx", "pptx", "xlsx"})
+_HTML_SUFFIXES = frozenset({"html", "htm"})
+_PDF_INPUT_SUFFIXES = frozenset({"pdf", "png", "jpeg", "jp2", "webp", "gif", "bmp", "jpg", "tiff"})
+_PATH_PRIORITY_SUFFIXES = _OFFICE_SUFFIXES | _HTML_SUFFIXES | _PDF_INPUT_SUFFIXES
+
+
+def _resolve_input_suffix(path: Path) -> str:
+ from ..utils.guess_suffix_or_lang import guess_suffix_by_path
+
+ guessed_suffix = guess_suffix_by_path(path)
+ path_suffix = path.suffix.lower().lstrip(".")
+ if path_suffix in _PATH_PRIORITY_SUFFIXES:
+ return path_suffix
+ return guessed_suffix
+
def _build_parser(
path: str | Path,
@@ -48,10 +63,8 @@ def _build_parser(
formula_enable: bool | None = None,
image_analysis: bool | None = None,
) -> DocumentParser:
- from ..utils.guess_suffix_or_lang import guess_suffix_by_path
-
path = Path(path)
- suffix = guess_suffix_by_path(path)
+ suffix = _resolve_input_suffix(path)
_, resolved_backend = resolve_tier_and_backend(tier=tier, backend=backend)
resolved_ocr_mode = method or ocr_mode
resolved_language = lang or language
@@ -59,16 +72,20 @@ def _build_parser(
resolved_formula_enable = (not disable_formula) if formula_enable is None else formula_enable
resolved_image_analysis = (not disable_image_analysis) if image_analysis is None else image_analysis
- if suffix in ("docx", "pptx", "xlsx"):
+ if suffix in _OFFICE_SUFFIXES:
parser_cls: type[DocumentParser] = {
"docx": DocxParser,
"pptx": PptxParser,
"xlsx": XlsxParser,
}[suffix]
return parser_cls()
- elif suffix in ("html", "htm"):
+ elif suffix in _HTML_SUFFIXES:
return HtmlParser()
- elif resolved_backend == "pipeline":
+
+ if suffix not in _PDF_INPUT_SUFFIXES:
+ raise ValueError(f"Unsupported file type: {suffix or path.suffix or 'unknown'}")
+
+ if resolved_backend == "pipeline":
return PdfPipelineParser(
backend=resolved_backend,
method=resolved_ocr_mode,
diff --git a/mineru/parser/html.py b/mineru/parser/html.py
index c0be04e4..89941cae 100644
--- a/mineru/parser/html.py
+++ b/mineru/parser/html.py
@@ -77,12 +77,17 @@ def _build_span(element: Tag) -> Span:
return Span(type="text", bbox=EMPTY_BBOX, content=content)
+def _append_block(blocks: list[Block], block: Block) -> None:
+ block.index = len(blocks)
+ blocks.append(block)
+
+
def _walk_elements(parent: Tag, blocks: list[Block]) -> None: # type: ignore[type-arg]
for child in parent.children:
if not isinstance(child, Tag):
text = str(child).strip()
if text:
- blocks.append(Block(
+ _append_block(blocks, Block(
index=0,
type="text",
bbox=EMPTY_BBOX,
@@ -93,25 +98,25 @@ def _walk_elements(parent: Tag, blocks: list[Block]) -> None: # type: ignore[ty
tag_name = child.name
if tag_name in _HEADING_TAGS:
- blocks.append(_build_heading(child))
+ _append_block(blocks, _build_heading(child))
elif tag_name in ("p", "span"):
- blocks.append(_build_text_block(child))
+ _append_block(blocks, _build_text_block(child))
elif tag_name in _BLOCK_CONTAINER_TAGS:
_walk_elements(child, blocks)
elif tag_name in ("ul", "ol"):
- blocks.append(_build_list(child))
+ _append_block(blocks, _build_list(child))
elif tag_name == "table":
- blocks.append(_build_table(child))
+ _append_block(blocks, _build_table(child))
elif tag_name == "pre":
- blocks.append(_build_code(child))
+ _append_block(blocks, _build_code(child))
elif tag_name in ("img",):
- blocks.append(_build_image_block(child))
+ _append_block(blocks, _build_image_block(child))
elif tag_name in ("br",):
pass
else:
# fallback: treat unknown inline tags as text
if child.get_text(strip=True):
- blocks.append(_build_text_block(child))
+ _append_block(blocks, _build_text_block(child))
def _build_heading(element: Tag) -> Block:
@@ -151,7 +156,7 @@ def _build_list(element: Tag) -> Block:
nested_blocks: list[Block] = []
_walk_elements(li, nested_blocks)
items.append(Block(
- index=0,
+ index=len(items),
type="list_item",
bbox=EMPTY_BBOX,
lines=[_line_with_spans([Span(type="text", bbox=EMPTY_BBOX, content=_extract_text(li))])],
diff --git a/pyproject.toml b/pyproject.toml
index 9254c375..acfe0f79 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -59,7 +59,6 @@ dependencies = [
"lxml>=4.0.0,<7.0.0",
"openpyxl>=3.1.5,<4",
"aiosqlite>=0.20.0,<1",
- "fnvhash>=0.2.1,<1",
"watchfiles>=1.0.0,<2",
"fastapi",
"python-multipart",
diff --git a/skills/mineru/SKILL.md b/skills/mineru/SKILL.md
new file mode 100644
index 00000000..ac428028
--- /dev/null
+++ b/skills/mineru/SKILL.md
@@ -0,0 +1,774 @@
+---
+name: mineru-document-parser
+description: Use when an agent needs to read, parse, OCR, search, inspect, or cite local documents with MinerU, including PDFs, scanned documents, images, DOCX, PPTX, XLSX, academic papers, long documents, tables, formulas, and document locators. Use for agent-native document reading workflows that should prefer local privacy, structured errors, continuation, and stable page/block locators.
+metadata:
+ openclaw:
+ emoji: "📄"
+ privacy: "MinerU defaults to local parsing and local storage. Document content is not uploaded unless the user explicitly allows remote parsing with --remote or an equivalent parsing rule."
+ requires:
+ bins: ["mineru"]
+ optional:
+ env: ["MINERU_HOME", "MINERU_API_KEY"]
+ install:
+ - id: "uv"
+ kind: "python"
+ package: "mineru"
+ bins: ["mineru"]
+ label: "Install via uv tool"
+ - id: "pipx"
+ kind: "python"
+ package: "mineru"
+ bins: ["mineru"]
+ label: "Install via pipx"
+ - id: "pip"
+ kind: "python"
+ package: "mineru"
+ bins: ["mineru"]
+ label: "Install via pip fallback"
+allowed-tools: Bash(mineru:*), Bash(command:*), Bash(test:*), Bash(uv:*), Bash(pipx:*), Bash(pip:*), Bash(python:*), Bash(python3:*), Bash(which:*)
+---
+
+# MinerU Document Parser
+
+## What MinerU Is
+
+MinerU is a command-line document reader for agents. It parses local documents into readable content, lets agents continue by page or block, and returns stable locators for follow-up reads and citations.
+
+## What MinerU Is Not
+
+MinerU is not a browser, RAG framework, embedding system, vector database, or chat-with-doc application. It can be used as the document parsing step in a larger pipeline, but this skill only uses the `mineru` command.
+
+## When To Use MinerU
+
+Use this skill when the user asks an agent to:
+
+- Read, inspect, summarize, quote, cite, or answer questions about a local document.
+- Convert document content into Markdown for analysis.
+- OCR scanned PDFs or images.
+- Extract content from PDFs, DOCX, PPTX, XLSX, images, or other MinerU-supported document formats.
+- Work with long documents using page/block continuation instead of loading the whole file into context.
+- Search documents MinerU has already indexed.
+- Retrieve page or block images for visual inspection.
+- Keep stable references to document locations using `doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}` locators.
+
+## Supported Inputs
+
+Use MinerU for local document files such as:
+
+| Type | Examples |
+|---|---|
+| PDF | `.pdf`, including scanned PDFs and academic papers |
+| Images | `.png`, `.jpg`, `.jpeg`, `.webp`, `.bmp`, and similar image files |
+| Word | `.docx` |
+| PowerPoint | `.pptx` |
+| Excel | `.xlsx` |
+
+MinerU is especially useful when documents contain OCR text, tables, formulas, figures, or complex page layouts.
+
+## Do Not
+
+Do not:
+
+- Summarize a document before reading it with `mineru`.
+- Reimplement PDF/OCR extraction when `mineru` can read the document.
+
+## Agent Contract
+
+- Use `mineru` as the command entrypoint.
+- Use `--json` when making control-flow decisions.
+- Follow continuation commands and `next_request`.
+- Preserve locators for citations and follow-up reads.
+- Ask before using `--remote`, changing persistent config, adding watches, stopping or restarting the server, invalidating caches, or running destructive maintenance such as `forget --no-dry-run` or `cleanup --no-dry-run`.
+
+## Core Decision Tree
+
+Use this decision tree before running commands:
+
+1. User provided a file path and wants content: run `mineru parse <file>`.
+2. User provided a `doc:...` locator: run `mineru read <locator>`.
+3. User asks to continue from a previous output: follow the `<!-- Next: ... -->` command exactly.
+4. User asks for a specific page or block after parsing: use `mineru read <locator>`, not a fresh parse.
+5. User asks to find a document by filename: use `mineru find`.
+6. User asks to search inside known indexed documents: use `mineru search`.
+7. User asks for parse/file/doc status: use `mineru show` or `mineru list`.
+8. User asks to add or refresh a watched folder: use `mineru watch` or `mineru scan`.
+9. User asks MinerU to forget a file or folder without deleting it: use `mineru forget`.
+10. User asks to force a reparse: use `mineru parse --force` or `mineru invalidate`.
+
+## Common Workflows
+
+### First read from a file
+
+```bash
+mineru parse "document.pdf" --json
+```
+
+Then answer from `content.content`. If `next_request` exists and the question needs more context, continue.
+
+### Continue progressively
+
+```bash
+mineru parse "book.pdf" --pages 1~10 --limit 12000 --json
+mineru read "doc:ab12cd3/tier:standard/page:11" --limit 12000 --json
+```
+
+Continue with returned `next_request.locator`.
+
+### Read or inspect a known location
+
+```bash
+mineru read "doc:ab12cd3/tier:standard/page:42" --context 1 --json
+mineru read "doc:ab12cd3/tier:standard/page:12/block:5" --format image --output ./page12-block5.png
+```
+
+### Search local library, then read
+
+```bash
+mineru search "liquidated damages" --min-tier standard --json
+mineru read "doc:ab12cd3/tier:standard/page:18" --json
+```
+
+## Installation And Setup
+
+Always check whether `mineru` is already available before installing.
+
+```bash
+command -v mineru
+mineru --help
+```
+
+If `mineru` is not installed, install it with the first available isolated CLI installer.
+MinerU requires Python `>=3.10,<3.14`.
+
+### Install with `uv` (preferred)
+
+If `uv` is available, use any supported Python version for the tool environment.
+If no supported interpreter is available, install Python 3.12 with `uv` as a conservative fallback:
+
+```bash
+command -v uv
+uv python find 3.12
+uv python find 3.13
+uv python find 3.11
+uv python find 3.10
+```
+
+If all `uv python find` commands failed, download Python 3.12 with `uv`:
+
+```bash
+uv python install 3.12
+```
+
+Then install MinerU with the supported interpreter that was found, or with Python 3.12 if it was installed as the fallback:
+
+```bash
+uv tool install --python 3.12 mineru@https://github.com/johnking0099/MinerU-Repo/archive/refs/heads/next.zip
+```
+
+### Install with `pipx`
+
+If `uv` is unavailable but `pipx` is available, inspect `pipx`'s default Python before installing:
+
+```bash
+command -v pipx
+pipx environment --value PIPX_DEFAULT_PYTHON
+PIPX_DEFAULT_PYTHON="$(pipx environment --value PIPX_DEFAULT_PYTHON)"
+"$PIPX_DEFAULT_PYTHON" --version
+```
+
+Check the `PIPX_DEFAULT_PYTHON` path reported by `pipx`. If that interpreter satisfies `>=3.10,<3.14`, install with `pipx`:
+
+```bash
+pipx install mineru@https://github.com/johnking0099/MinerU-Repo/archive/refs/heads/next.zip
+```
+
+If `PIPX_DEFAULT_PYTHON` is unsupported, but a supported Python interpreter can be found on the current system, pass it explicitly. `python3.12` is an example; use any interpreter that satisfies `>=3.10,<3.14`.
+
+```bash
+command -v python3.12
+python3.12 --version
+pipx install --python python3.12 mineru@https://github.com/johnking0099/MinerU-Repo/archive/refs/heads/next.zip
+```
+
+If no supported system interpreter is available and `pipx` supports Python fetching, ask for approval before downloading a standalone Python:
+
+```bash
+pipx install --python 3.12 --fetch-python=missing mineru@https://github.com/johnking0099/MinerU-Repo/archive/refs/heads/next.zip
+```
+
+### Install with global `pip`
+
+If neither `uv` nor `pipx` is available, but `pip` or `pip3` is available, check the Python version of the `pip` command, and ask the user before installing into the global python environment:
+
+```bash
+which -a pip pip3 pip3.10 pip3.11 pip3.12 pip3.13 # find all available pips
+pip --version
+```
+
+If a `pip` command reports Python `>=3.10,<3.14`, and the user confirms, install with the exact supported `pip` command that was verified. Replace `pip` below with the verified pip command if needed:
+
+```bash
+pip install mineru@https://github.com/johnking0099/MinerU-Repo/archive/refs/heads/next.zip
+```
+
+### If No Supported Installer Is Available
+
+If `uv`, `pipx`, `pip`, and `pip3` are all unavailable, or none of them can install with Python `>=3.10,<3.14`, recommend that the user install `uv` first.
+
+### After Installation
+
+Verify the installed CLI:
+
+```bash
+mineru --help
+```
+
+## Privacy Rules
+
+MinerU is privacy-first.
+
+- By default, `mineru` parses documents locally. A document is sent for remote parsing only when the command uses the `--remote` CLI parameter.
+- Use local parsing first. If local parsing is not configured or cannot satisfy the request, and the document does not involve private or sensitive content, ask the user before retrying with `--remote`.
+- Even if remote parsing is configured, do not upload a document until the user agrees.
+- Local failure cannot silently fall back to remote.
+- Remote failure may fall back to local if the request can still be satisfied locally.
+
+When remote parsing is acceptable:
+
+```bash
+mineru parse "document.pdf" --remote
+```
+
+If the request is sensitive, confidential, legal, medical, financial, personal, or proprietary, stay local unless the user gives explicit remote permission.
+
+## Telemetry
+
+MinerU may collect anonymous, locally aggregated usage and diagnostic telemetry to understand command usage, success or failure rates, tier choices, coarse environment categories, and performance timing buckets.
+
+Telemetry does not collect document contents, extracted text or images, file names, file paths, search queries, prompts, snippets, API keys, usernames, hostnames, raw tracebacks, or exact hardware identifiers.
+
+Telemetry starts in an unset consent state. In this state MinerU may keep local aggregate data but will not upload it. Users can enable or disable telemetry explicitly; disabling telemetry stops new telemetry aggregation and removes unsent local telemetry data.
+
+Do not prompt for telemetry consent in agent or non-interactive contexts. If the user asks about telemetry, use:
+
+```bash
+mineru telemetry status
+mineru telemetry enable
+mineru telemetry disable
+mineru telemetry preview
+mineru telemetry flush
+```
+
+## Quality Tiers
+
+MinerU has three quality tiers:
+
+| Tier | Use for | How to use |
+|---|---|---|
+| `flash` | Fast discovery, preview, and search indexing | Never use as default final reading quality |
+| `standard` | Local high-quality reading on typical supported hardware | Minimum default quality for active reading |
+| `pro` | Highest quality, local high-end hardware or remote API | Use for complex or high-value documents when available |
+
+Default tier behavior:
+
+- Omit `--tier` when the user wants normal reading quality.
+- MinerU will choose the highest available non-`flash` tier, usually `standard` or `pro`.
+- If normal reading quality is unavailable, there are usually three options:
+ - Use remote parsing with `--remote`.
+ - Start or configure a local parse server if the hardware supports it.
+ - Explicitly accept the lower-quality local `flash` tier.
+- Use `--tier flash` only when the user explicitly asks for fastest/preview/low-cost parsing or accepts lower quality.
+
+Examples:
+
+```bash
+mineru parse "paper.pdf"
+mineru parse "paper.pdf" --tier standard
+mineru parse "paper.pdf" --tier pro
+mineru parse "paper.pdf" --tier flash
+```
+
+## Server Rules
+
+Most `mineru` commands use the local MinerU background service. If a command fails with `server_not_running`, start it:
+
+```bash
+mineru server start
+```
+
+Check status when MinerU is not responding, parsing is stuck, or you need to see available tiers:
+
+```bash
+mineru server status
+mineru server status --json
+```
+
+Server commands:
+
+```bash
+mineru server start
+mineru server stop
+mineru server restart
+mineru server status
+```
+
+Agent rules:
+
+- Start the server when `mineru` reports it is not running.
+- Do not restart the server repeatedly without a reason.
+- Use `server status --json` when you need machine-readable status.
+- If high-quality local parsing is unavailable, report the error and suggested action. Do not switch to remote without permission.
+
+## Local Parse Server
+
+Use a local parse server when the user wants `standard` or `pro` quality without sending the document to remote parsing.
+
+Hardware guidance:
+
+| Tier | Local hardware guidance |
+|---|---|
+| `standard` | macOS with Apple Silicon and about 4 GB unified memory, or Windows/Linux with an NVIDIA GPU and at least 4 GB VRAM |
+| `pro` | High-end GPU or accelerator hardware with the matching model environment; otherwise prefer remote parsing if the user allows it |
+
+Change local parse-server config or restart the server only when the user asks for or approves local high-quality parsing.
+
+Start managed local parsing for `standard`:
+
+```bash
+mineru server start
+mineru config set parse_server.local.mode managed
+mineru config set parse_server.local.managed_tier standard
+mineru server restart
+mineru server status
+```
+
+Start managed local parsing for `pro`:
+
+```bash
+mineru server start
+mineru config set parse_server.local.mode managed
+mineru config set parse_server.local.managed_tier pro
+mineru server restart
+mineru server status
+```
+
+Rules:
+
+- Use `standard` as the practical local default when supported by the user's machine.
+- Use local `pro` only when the user has suitable high-end hardware and model setup.
+- If local `standard` or `pro` cannot start, do not add `--remote` automatically; ask the user first.
+
+## First Read From A File
+
+Use `mineru parse` for the first active read from a local file path.
+
+```bash
+mineru parse "report.pdf"
+```
+
+By default, readable content is printed to stdout. Use `--output` only when the user wants the result saved to a file.
+
+Use JSON when you need structured status, tier, content, and continuation:
+
+```bash
+mineru parse "report.pdf" --json
+```
+
+For a specific page range:
+
+```bash
+mineru parse "report.pdf" --pages 1~10
+mineru parse "report.pdf" --pages all
+```
+
+For bounded context:
+
+```bash
+mineru parse "report.pdf" --limit 12000
+```
+
+For no synchronous wait:
+
+```bash
+mineru parse "report.pdf" --no-wait --json
+```
+
+For longer wait:
+
+```bash
+mineru parse "report.pdf" --wait 180 --json
+```
+
+For output to a file:
+
+```bash
+mineru parse "report.pdf" --output ./report.md
+```
+
+Rules:
+
+- Quote paths with spaces.
+- For paged documents, the default active read range is the first page window, usually `1~10`; continue with the returned marker or `next_request` instead of reading the whole document by default.
+- Use the default tier unless the user has a quality/speed/privacy preference.
+- Use `--pages all` only when the user asks for the whole document or the document is known to be small enough.
+- Prefer `--limit` and continuation for long documents.
+- Once you have a locator, switch to `mineru read`.
+
+## Continue Reading
+
+MinerU output may include a command to continue reading:
+
+```text
+<!-- Next: mineru read doc:ab12cd3/tier:standard/page:11 -->
+```
+
+or:
+
+```text
+<!-- Next: mineru parse report.pdf --pages 11~20 -->
+```
+
+Run the suggested command exactly unless the user asks for a different page, block, format, or limit.
+
+Agent rules:
+
+- Do not guess the next page or block if MinerU provides a next command.
+- Do not restart parsing from page 1 when continuing.
+- For non-paged long documents, continuation may use an `--after` cursor from `next_request.after`; use that exact cursor.
+- Prefer `mineru read` when the next command or JSON output gives a locator.
+- Use `--limit` to keep output within the conversation budget.
+- Preserve locators for citations and follow-up reads.
+
+## Read By Locator
+
+Use `mineru read` when a document has already been parsed or when the user gives a locator.
+
+Locator forms:
+
+```text
+doc:{short_id}
+doc:{short_id}/tier:{tier}
+doc:{short_id}/tier:{tier}/page:{page_no}
+doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}
+doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}
+```
+
+Examples:
+
+```bash
+mineru read "doc:ab12cd3/tier:standard/page:4"
+mineru read "doc:ab12cd3/tier:standard/page:4/block:7"
+mineru read "doc:ab12cd3/tier:standard/page:4/block:7" --context 2
+mineru read "doc:ab12cd3/tier:standard/page:4" --limit 8000 --json
+```
+
+Rules:
+
+- Page and block numbers are 1-based.
+- Character offsets are 0-based within the block text.
+- `--context N` means surrounding pages for page locators and surrounding blocks for block locators.
+- If only `doc:{short_id}` is provided, MinerU should choose the highest cached non-`flash` tier. If none exists, parse the document first or report the error.
+
+## Read Page Or Block Images
+
+Use image output only when the user needs visual inspection, layout evidence, cropped figures, page screenshots, or block-level visual verification.
+
+```bash
+mineru read "doc:ab12cd3/tier:standard/page:4" --format image
+mineru read "doc:ab12cd3/tier:standard/page:4/block:7" --format image
+mineru read "doc:ab12cd3/tier:standard/page:4/block:7" --format image --output ./block-7.png
+```
+
+Rules:
+
+- PDF page image is supported for page locators.
+- PDF block image requires a valid non-empty bbox.
+- Office block image is only expected for image blocks.
+- Multi-page image export is not the default reading workflow.
+- If no `--output` is provided, MinerU prints the generated asset path.
+
+## Search And Find
+
+Use `find` for filenames and local paths:
+
+```bash
+mineru find "annual report"
+mineru find "contract" --ext pdf
+mineru find "invoice" --json
+```
+
+Use `search` for parsed document content:
+
+```bash
+mineru search "revenue recognition"
+mineru search "transformer architecture" --type pdf
+mineru search "appendix" --min-tier standard --limit 10 --json
+```
+
+Rules:
+
+- `find` does not search document content.
+- `search` only searches content MinerU has already indexed.
+- If search returns only low-quality or `flash` snippets and the user needs an answer, parse or read the target document at default quality before relying on the content.
+- Do not repeat sensitive search snippets in final output unless needed to answer the user.
+
+## Inspect Status
+
+Use `show` for one resource:
+
+```bash
+mineru show file "report.pdf"
+mineru show file "report.pdf" --json
+mineru show parse 123 --json
+mineru show doc "<sha256>" --json
+mineru show scan 456 --json
+```
+
+Use `list` for collections:
+
+```bash
+mineru list docs
+mineru list files --ext pdf
+mineru list parses --status parsing
+mineru list scans --status running
+mineru list docs --json
+```
+
+Rules:
+
+- Use `show file` after parse timeout to see active parses and cached tiers.
+- Use `list parses` to inspect queued, parsing, failed, or done parse tasks.
+- Use JSON modes when you need structured output.
+
+## Watch, Scan, And Local Library Maintenance
+
+Use `scan` for one-time discovery or refresh:
+
+```bash
+mineru scan "~/Documents/report.pdf"
+mineru scan "~/Documents/project"
+mineru scan "~/Documents/project" --no-wait --json
+```
+
+Use `watch` for persistent folders:
+
+```bash
+mineru watch add "~/Documents"
+mineru watch add "/Volumes/Archive" --removable
+mineru watch list
+mineru watch rescan "~/Documents"
+mineru watch remove "~/Documents"
+```
+
+Watch rules:
+
+- Watch is for discovery and search indexing.
+- Watch defaults to `flash`.
+- Watch results are not final reading quality.
+- Active reading should still use `mineru parse` or `mineru read`.
+- The CLI normalizes local path arguments with user-home expansion, absolute paths, and normalized separators.
+- For `watch rescan` and `watch remove`, use either a watch id or the watch root path.
+- Watch will not trigger remote parsing unless a parsing rule explicitly allows remote.
+
+Use parsing rules only when the user wants automatic parse policy for paths:
+
+```bash
+mineru config parsing-rules add "*/papers/*" --tier standard --pages all
+mineru config parsing-rules add "*/contracts/*" --tier pro --remote
+mineru config parsing-rules list
+mineru config parsing-rules remove 3
+```
+
+Use exclude rules to prevent discovery:
+
+```bash
+mineru config exclude-rules add "*/node_modules/*"
+mineru config exclude-rules list
+mineru config exclude-rules remove 5
+```
+
+Use `forget` to forget a file or folder from MinerU without deleting source files:
+
+```bash
+mineru forget "~/Documents/old.pdf"
+mineru forget "~/Documents/project"
+mineru forget "~/Documents/project" --no-dry-run
+```
+
+Use cleanup for local maintenance:
+
+```bash
+mineru cleanup deleted-files
+mineru cleanup deleted-files --no-dry-run
+mineru cleanup orphan-docs
+mineru cleanup orphan-docs --no-dry-run
+mineru cleanup temp
+mineru cleanup temp --older-than 14
+```
+
+Rules:
+
+- `forget` does not delete source files.
+- `forget` does not prevent a watched path from being rediscovered.
+- If the target is a watch root, remove the watch first. If the target is inside an active watch, warn that a later scan may rediscover it.
+- `scan` does not create a watch.
+- `scan` refreshes file discovery state only; it does not mean ingest or parsing has completed.
+- `cleanup deleted-files` and `cleanup orphan-docs` default to dry-run; add `--no-dry-run` only when the user wants actual cleanup.
+- `cleanup orphan-docs --no-dry-run` can delete cached parsed content for documents no longer linked to any known file path; use it only for maintenance.
+
+## Reparse And Cache Control
+
+MinerU caches parse results for the same document and tier.
+
+Force a new parse for the current request:
+
+```bash
+mineru parse "report.pdf" --force
+```
+
+Invalidate cached parse results:
+
+```bash
+mineru invalidate "report.pdf"
+mineru invalidate "report.pdf" --tier standard
+```
+
+Rules:
+
+- Prefer cached results for normal reading.
+- Use `--force` when the user asks to reparse or when cached output is known stale or wrong; it skips done cache for this request but does not invalidate or delete old results.
+- Use `invalidate` when the user wants future parses and reads to avoid existing done results; invalidation does not automatically start a new parse.
+- Do not delete user files as part of cache control.
+
+## Configuration
+
+Show configuration:
+
+```bash
+mineru config show
+mineru config show --json
+```
+
+Set or unset a value only when the user gives an explicit configuration key:
+
+```bash
+mineru config get "<key>"
+mineru config set "<key>" "<value>"
+mineru config unset "<key>"
+```
+
+Important environment variables:
+
+| Variable | Meaning |
+|---|---|
+| `MINERU_HOME` | MinerU home, default `~/.mineru` |
+| `MINERU_API_KEY` | API key for remote parsing when remote is explicitly allowed |
+
+Rules:
+
+- Remote URL/API key configuration does not authorize upload by itself.
+- `--remote` or a remote-enabled parsing rule is still required.
+- Avoid printing secrets from config.
+
+## JSON Output
+
+Use `--json` when an agent needs stable machine-readable fields.
+
+`mineru parse --json` returns:
+
+```json
+{
+ "parse": { "...": "parse summary" },
+ "content": { "...": "readable content and continuation data" }
+}
+```
+
+If parsing is still pending, timed out, or `--no-wait` is used, `content` may be `null`.
+
+Errors use:
+
+```json
+{
+ "error": {
+ "type": "engine_error",
+ "code": "quality_tier_unavailable",
+ "message": "...",
+ "param": "tier",
+ "retryable": false,
+ "user_action": "...",
+ "docs_url": null
+ }
+}
+```
+
+Agent rules:
+
+- Branch on `error.code`, not on prose in `message`.
+- Respect `retryable`.
+- Use `user_action` to decide the next command or user-facing suggestion.
+- Do not strip locator fields from parsed content; they are needed for continuation and citation.
+
+## Error Recovery
+
+Use this table for common error codes:
+
+| Code | Meaning | Agent action |
+|---|---|---|
+| `server_not_running` | MinerU background service is unavailable | Run `mineru server start`, then retry once |
+| `quality_tier_unavailable` | Normal reading quality is unavailable | Suggest enabling local high-quality parsing, ask before `--remote`, or ask whether `--tier flash` is acceptable |
+| `no_engine` | Requested tier is unavailable locally | Suggest another tier or enable local high-quality parsing |
+| `engine_unavailable` | Engine process unavailable | Retry if `retryable`; otherwise check `mineru server status` |
+| `parse_server_unavailable` | Parsing service cannot be reached | Check `mineru server status`; do not switch privacy boundary |
+| `tier_mismatch` | Requested tier unsupported | Ask user to choose a supported tier |
+| `parse_failed` | MinerU could not parse the file | Report failure; suggest a different tier only if privacy rules allow |
+| `parse_timeout` | Parse exceeded timeout | Retry with longer `--wait`, inspect status, or use lower tier if user accepts |
+| `parse_oom` | Memory or VRAM exhausted | Suggest lower quality, smaller `--pages`, or remote only with permission |
+| `remote_not_allowed` | Remote might be needed but was not authorized | Ask user whether uploading is acceptable; do not add `--remote` yourself |
+| `invalid_api_key` | API key invalid | Ask user to set a valid key |
+| `quota_exceeded` | Remote quota exhausted | Suggest waiting or using local |
+| `rate_limit_exceeded` | Remote rate limit | Retry later if appropriate |
+| `file_not_found` | Path or file id missing | Ask for correct path or run `mineru find` |
+| `file_permission_denied` | Local file unreadable | Ask user to fix permissions |
+| `file_type_unsupported` | Format unsupported | Report unsupported type |
+| `file_encrypted` | Password-protected file | Ask user for an unlocked copy |
+| `file_corrupted` | File cannot be read | Ask for a valid copy |
+| `page_range_invalid` | Bad `--pages` value | Correct to forms such as `1~5`, `1,3,8~10`, or `all` |
+| `not_cached` / `cache_miss` | Requested cached content does not exist | Run `mineru parse` |
+
+Retry rules:
+
+- Retry once for transient server startup or explicitly retryable errors.
+- Do not retry parse failures indefinitely.
+- Do not change tier, pages, or remote/local privacy boundary without a reason.
+- Do not add `--remote` during recovery without user permission.
+
+## Answering Users With MinerU Output
+
+When answering after reading a document:
+
+- Use the parsed content, not assumptions about the document.
+- Cite locators when the user needs traceability.
+- Prefer concise quotations and page/block references over large copied passages.
+- If content was truncated, say that the answer is based on the pages/blocks read so far.
+- Continue reading before making claims that require unread sections.
+- For tables, formulas, figures, or layout-sensitive questions, read the relevant page/block and use image output if needed.
+
+Citation style examples:
+
+```text
+The warranty period is 24 months (doc:ab12cd3/tier:standard/page:7/block:3).
+```
+
+```text
+The method is described across pages 4-5; I checked doc:ab12cd3/tier:pro/page:4 and doc:ab12cd3/tier:pro/page:5.
+```
+
+## Operating Rules
+
+- Do not use `flash` as default final reading quality.
+- Do not reparse when a valid locator and cached result are enough.
+- Do not ignore continuation commands.
+- Do not load a whole long document when page/block continuation can answer the question.
+- Do not delete source files.
+- Do not expose secrets, API keys, or unnecessary local paths.
+- Do not branch on human prose when JSON `error.code` or `next_request` is available.
diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.py
index cbcc5537..948c7fac 100644
--- a/tests/unittest/test_cli_next_command_design.py
+++ b/tests/unittest/test_cli_next_command_design.py
@@ -72,6 +72,19 @@ def test_telemetry_command_tree_is_available() -> None:
assert "flush" in result.output
+def test_search_and_find_help_list_filter_values() -> None:
+ search_result = runner.invoke(app, ["search", "--help"])
+ find_result = runner.invoke(app, ["find", "--help"])
+
+ assert search_result.exit_code == 0
+ assert find_result.exit_code == 0
+ assert "File type filter: pdf, docx, pptx," in search_result.output
+ assert "xlsx, html, markdown, csv, rst," in search_result.output
+ assert "tex, txt" in search_result.output
+ assert "File extension filter: pdf, docx, pptx, xlsx," in find_result.output
+ assert "html, htm, md, markdown, csv, rst, tex, txt" in find_result.output
+
+
def test_print_error_uses_single_rich_render(monkeypatch: Any) -> None:
calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
@@ -92,6 +105,67 @@ def test_print_error_uses_single_rich_render(monkeypatch: Any) -> None:
assert "--tier flash" in rendered
+def test_find_results_render_as_list_without_empty_search_columns(monkeypatch: Any) -> None:
+ printed: list[Any] = []
+
+ class _Console:
+ def print(self, item: Any, *args: Any, **kwargs: Any) -> None:
+ printed.append(item)
+
+ monkeypatch.setattr(output_mod, "console", _Console())
+
+ output_mod.format_find_results(
+ {
+ "total": 2,
+ "results": [
+ {"filename": "resume.pdf", "paths": ["/tmp/resume.pdf"]},
+ {"filename": "cv.docx", "paths": ["/tmp/cv.docx"]},
+ ],
+ }
+ )
+
+ assert len(printed) == 1
+ rendered = str(printed[0])
+ assert "Search results (2 total)" in rendered
+ assert "1. resume.pdf (/tmp/resume.pdf)" in rendered
+ assert "\n\n2. cv.docx (/tmp/cv.docx)" in rendered
+ assert "Tier" not in rendered
+ assert "Snippet" not in rendered
+ assert "Paths" not in rendered
+
+
+def test_search_results_render_as_list_without_table(monkeypatch: Any) -> None:
+ printed: list[Any] = []
+
+ class _Console:
+ def print(self, item: Any, *args: Any, **kwargs: Any) -> None:
+ printed.append(item)
+
+ monkeypatch.setattr(output_mod, "console", _Console())
+
+ output_mod.format_search_results(
+ {
+ "total": 1,
+ "results": [
+ {
+ "filename": "resume.pdf",
+ "tier": "standard",
+ "snippet": "Python\nengineer",
+ "paths": ["/tmp/resume.pdf"],
+ }
+ ],
+ }
+ )
+
+ assert len(printed) == 1
+ rendered = str(printed[0])
+ assert "Search results (1 total)" in rendered
+ assert "1. resume.pdf (/tmp/resume.pdf) Tier: standard" in rendered
+ assert " Python engineer" in rendered
+ assert "Snippet:" not in rendered
+ assert not hasattr(printed[0], "columns")
+
+
def test_server_status_renders_separate_recent_log_panels(monkeypatch: Any) -> None:
printed: list[Any] = []
panels: list[dict[str, Any]] = []
diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.py
index 3e35ad53..7baa0423 100644
--- a/tests/unittest/test_doclib_app_startup.py
+++ b/tests/unittest/test_doclib_app_startup.py
@@ -6,6 +6,7 @@ from pathlib import Path
import pytest
from fastapi.testclient import TestClient
+from loguru import logger as loguru_logger
from mineru.config import LogConfig, PatchedConfig, config as mineru_config
from mineru.doclib import app as doclib_app
@@ -47,10 +48,57 @@ def test_doclib_runtime_dependencies_are_in_base_install() -> None:
dependency_names = {dependency.split(">", 1)[0].split("=", 1)[0].lower() for dependency in dependencies}
assert "aiosqlite" in dependency_names
- assert "fnvhash" in dependency_names
assert "watchfiles" in dependency_names
+def test_background_task_crash_is_logged(caplog: pytest.LogCaptureFixture) -> None:
+ async def _boom() -> None:
+ raise RuntimeError("boom")
+
+ async def _run() -> None:
+ task = asyncio.create_task(_boom())
+ await asyncio.sleep(0)
+ doclib_app._log_background_task_result("test-task", task)
+
+ with caplog.at_level(logging.ERROR):
+ asyncio.run(_run())
+
+ assert "Background task test-task crashed: boom" in caplog.text
+
+
+def test_background_tasks_are_cancelled_and_awaited_on_shutdown() -> None:
+ async def _run() -> None:
+ state = doclib_app.AppState()
+ state.db_ready = asyncio.Event()
+
+ async def _blocked() -> None:
+ await asyncio.Event().wait()
+
+ task = doclib_app._create_background_task(state, "blocked", _blocked)
+ await asyncio.sleep(0)
+
+ await doclib_app._cancel_background_tasks(state)
+
+ assert task.cancelled()
+ assert task.done()
+ assert state.background_tasks == []
+
+ asyncio.run(_run())
+
+
+def test_pending_loop_tasks_are_cancelled_before_loop_close() -> None:
+ loop = asyncio.new_event_loop()
+ try:
+ task = loop.create_task(asyncio.Event().wait())
+
+ doclib_app._cancel_pending_loop_tasks(loop)
+
+ assert task.cancelled()
+ assert task.done()
+ finally:
+ loop.close()
+
+
def test_setup_logging_routes_application_logs_to_rotating_file_without_stderr_duplication(tmp_path: Path) -> None:
_clear_test_loggers()
log_path = tmp_path / "doclib.log"
@@ -87,6 +135,26 @@ def test_setup_logging_routes_application_logs_to_rotating_file_without_stderr_d
_clear_test_loggers()
+def test_setup_logging_routes_loguru_records_to_application_log(tmp_path: Path) -> None:
+ _clear_test_loggers()
+ log_path = tmp_path / "doclib.log"
+ access_log_path = tmp_path / "doclib.access.log"
+ try:
+ doclib_app._setup_logging(LogConfig(app_path=str(log_path), access_path=str(access_log_path)))
+
+ patched_logger = loguru_logger.patch(lambda record: record.update(name="mineru.test_loguru"))
+ patched_logger.error("loguru bridged message")
+
+ for handler in logging.getLogger("mineru").handlers:
+ handler.flush()
+
+ content = log_path.read_text(encoding="utf-8")
+ assert "mineru.test_loguru" in content
+ assert "loguru bridged message" in content
+ finally:
+ _clear_test_loggers()
+
+
def test_server_status_reports_configured_socket_path(monkeypatch, tmp_path) -> None:
app_log_path = tmp_path / "doclib.log"
access_log_path = tmp_path / "doclib.access.log"
@@ -168,6 +236,41 @@ def test_doclib_app_uses_lifespan_instead_of_deprecated_event_handlers(monkeypat
assert response.status_code == 200
+def test_startup_resets_running_scans_to_failed(monkeypatch, tmp_path) -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ asyncio.run(db.initialize())
+ asyncio.run(
+ db.execute(
+ "INSERT INTO scans (path, kind, source, status, locked_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (str(tmp_path / "watch-root"), "watch", "watch", "running", 123, 1000, 1000),
+ )
+ )
+
+ cfg = PatchedConfig(
+ doclib={
+ "data_dir": str(tmp_path),
+ "sqlite": {"path": str(tmp_path / "doclib.db")},
+ "log": {
+ "app_path": str(tmp_path / "doclib.log"),
+ "access_path": str(tmp_path / "doclib.access.log"),
+ },
+ "uds": {"path": str(tmp_path / "doclib.sock")},
+ }
+ )
+
+ def _skip_background_task(*args, **kwargs):
+ return None
+
+ monkeypatch.setattr(doclib_app, "_create_background_task", _skip_background_task)
+
+ with TestClient(doclib_app.create_app(cfg)) as client:
+ response = client.get("/api/v1/server/status")
+
+ assert response.status_code == 200
+ row = asyncio.run(db.fetchone("SELECT status, locked_at, error_code FROM scans"))
+ assert row == {"status": "failed", "locked_at": None, "error_code": "scan_interrupted"}
+
+
def test_telemetry_observation_route_uses_context_headers(monkeypatch, tmp_path) -> None:
cfg = PatchedConfig(
doclib={
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index 0c9567d8..e638b9f9 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -36,7 +36,7 @@ from mineru.doclib.services.scan_svc import ScanService
from mineru.doclib.services.search_svc import SearchService
from mineru.doclib.locators import ContentCursor
from mineru.doclib.server import DoclibServer, _ReadPlan, _render_progressive_markdown
-from mineru.doclib.types import ParseResponse
+from mineru.doclib.types import ParseResponse, WatchRequest
from mineru.parser import backend_for_tier, resolve_tier_and_backend
from mineru.parser.base import ParseResult
from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION
@@ -192,6 +192,27 @@ class _FakeFTS:
self.replaced.append(kwargs)
+class _FilenameOnlyFTS:
+ async def upsert_filename(self, file_id: int, stem: str, ext: str) -> None:
+ pass
+
+
+class _OrderRecordingDB:
+ def __init__(self, db: DatabaseManager) -> None:
+ self.db = db
+ self.events: list[str] = []
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self.db, name)
+
+ async def execute(self, sql: str, params: tuple[Any, ...] | None = None) -> Any:
+ if sql.startswith("UPDATE files SET sha256=?"):
+ self.events.append("update_file_sha")
+ elif sql.startswith("INSERT INTO parses"):
+ self.events.append("insert_parse")
+ return await self.db.execute(sql, params)
+
+
def _write_batch(data_dir: Path, sha256: str, tier: Tier, page_range: str, done_at: int, json_pages: list[dict]) -> None:
path = Path(parse_batch_json_path(str(data_dir), sha256, tier, page_range, done_at))
path.parent.mkdir(parents=True, exist_ok=True)
@@ -453,6 +474,51 @@ def test_invalidate_rebuilds_fts_from_highest_remaining_done_tier(tmp_path: Path
assert fts.replaced[0]["tier"] == "flash"
+def test_ingest_binds_file_sha_before_creating_parse_task(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ class _NoRulesConfig:
+ async def match_rules(self, path: str, rule_type: str) -> list[dict[str, Any]]:
+ return []
+
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ recording_db = _OrderRecordingDB(db)
+ service = ParseService(
+ db=recording_db,
+ fts=_FilenameOnlyFTS(),
+ config_svc=_NoRulesConfig(),
+ data_dir=str(tmp_path / "data"),
+ parse_lock_timeout_sec=1800,
+ )
+ source = tmp_path / "doc.pdf"
+ source.write_bytes(b"%PDF-1.4\n")
+
+ async def _metadata(path: str) -> dict[str, Any]:
+ return {
+ "page_count": 1,
+ "title": None,
+ "author": None,
+ "subject": None,
+ "keywords": None,
+ "is_image_based": 0,
+ }
+
+ monkeypatch.setattr(parse_svc_module, "extract_metadata", _metadata)
+
+ row = await service.ingest_file(str(source))
+ dangling_parses = await db.fetchall(
+ "SELECT p.id FROM parses p "
+ "LEFT JOIN files f ON f.sha256=p.sha256 AND f.status='active' "
+ "WHERE f.id IS NULL",
+ )
+
+ assert row is not None
+ assert recording_db.events.index("update_file_sha") < recording_db.events.index("insert_parse")
+ assert dangling_parses == []
+
+ asyncio.run(_run())
+
+
def test_force_request_reuses_active_and_creates_only_uncovered_parse(tmp_path: Path) -> None:
sha256 = "e" * 64
source = tmp_path / "doc.pdf"
@@ -1163,6 +1229,106 @@ def test_scan_service_directory_scan_applies_excludes_and_counts_unsupported(tmp
asyncio.run(_run())
+def test_refresh_file_ignores_office_temp_lock_files(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ParseService(db=db, fts=FTSManager(db), config_svc=ConfigService(db), data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ source = tmp_path / "~$package-size.xlsx"
+ source.write_bytes(b"\x15Microsoft Office lock")
+
+ refreshed = await service.refresh_file(str(source), ensure_ingested=True)
+ row = await db.fetchone("SELECT path FROM files WHERE path=?", (str(source),))
+
+ assert refreshed.status == "unsupported"
+ assert refreshed.file is None
+ assert row is None
+
+ asyncio.run(_run())
+
+
+def test_ensure_ingested_ignores_existing_office_temp_lock_file_row(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ParseService(db=db, fts=FTSManager(db), config_svc=ConfigService(db), data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ source = tmp_path / "~$package-size.xlsx"
+ source.write_bytes(b"\x15Microsoft Office lock")
+ now = 1000
+ await db.execute(
+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, watch_id, status, first_seen_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (str(source), source.name, "xlsx", source.stat().st_size, now, None, "active", now, now),
+ )
+
+ ingested = await service.ensure_ingested(str(source))
+
+ assert ingested is None
+
+ asyncio.run(_run())
+
+
+def test_scan_service_directory_scan_ignores_office_temp_lock_files(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ config_svc = ConfigService(db)
+ parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1800)
+ root = tmp_path / "docs"
+ root.mkdir()
+ regular = root / "regular.txt"
+ lock_file = root / "~$package-size.xlsx"
+ regular.write_text("regular", encoding="utf-8")
+ lock_file.write_bytes(b"\x15Microsoft Office lock")
+
+ scan = await scan_svc.create_scan(str(root), kind="manual", source="cli")
+ task = await scan_svc.acquire_task()
+ assert task is not None
+ assert await scan_svc.process_scan(task) is True
+
+ done = await scan_svc.get_scan(scan.id)
+ rows = await db.fetchall("SELECT path FROM files ORDER BY path")
+
+ assert done.files_seen == 2
+ assert done.files_refreshed == 1
+ assert done.files_new == 1
+ assert done.files_unsupported == 1
+ assert rows == [{"path": str(regular)}]
+
+ asyncio.run(_run())
+
+
+def test_watch_event_ignores_office_temp_lock_files(tmp_path: Path) -> None:
+ async def _run() -> None:
+ class _ConfigService:
+ async def is_path_excluded(self, path: str) -> bool:
+ return False
+
+ class _ParseService:
+ def __init__(self) -> None:
+ self.refreshed: list[str] = []
+
+ async def refresh_file(self, filepath: str, watch_id: int) -> None:
+ self.refreshed.append(filepath)
+
+ parse_svc = _ParseService()
+ watch_loop = WatchLoop(
+ db=SimpleNamespace(),
+ config_svc=_ConfigService(),
+ parse_svc=parse_svc,
+ scan_interval_sec=300,
+ )
+ lock_file = tmp_path / "~$package-size.xlsx"
+ lock_file.write_bytes(b"\x15Microsoft Office lock")
+
+ await watch_loop._handle_event(str(lock_file), watch_id=1)
+
+ assert parse_svc.refreshed == []
+
+ asyncio.run(_run())
+
+
def test_scan_service_reuses_pending_scan_for_same_kind_and_path(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
@@ -1183,6 +1349,30 @@ def test_scan_service_reuses_pending_scan_for_same_kind_and_path(tmp_path: Path)
asyncio.run(_run())
+def test_scan_service_does_not_reuse_stale_running_scan_for_same_kind_and_path(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ config_svc = ConfigService(db)
+ parse_svc = ParseService(db=db, fts=FTSManager(db), config_svc=config_svc, data_dir=str(tmp_path / "data"), parse_lock_timeout_sec=1800)
+ scan_svc = ScanService(db=db, config_svc=config_svc, parse_svc=parse_svc, scan_lock_timeout_sec=1)
+ root = tmp_path / "docs"
+ root.mkdir()
+
+ await db.execute(
+ "INSERT INTO scans (path, kind, source, status, locked_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (str(root), "manual", "cli", "running", 1, 10, 10),
+ )
+
+ fresh = await scan_svc.create_scan(str(root), kind="manual", source="sdk")
+ scans = await scan_svc.list_scans()
+
+ assert len(scans) == 2
+ assert fresh.id != scans[-1].id
+
+ asyncio.run(_run())
+
+
def test_watch_ids_are_non_negative_for_cli_arguments(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
@@ -1198,6 +1388,24 @@ def test_watch_ids_are_non_negative_for_cli_arguments(tmp_path: Path) -> None:
asyncio.run(_run())
+def test_watch_ids_are_stable_standard_library_hashes(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ config_svc = ConfigService(db)
+ root = tmp_path / "watch-root"
+ root.mkdir()
+
+ watch = await config_svc.add_watch(str(root))
+ expected = int.from_bytes(hashlib.blake2b(str(root).encode("utf-8"), digest_size=8).digest(), "big") & (
+ (1 << 63) - 1
+ )
+
+ assert watch["id"] == expected
+
+ asyncio.run(_run())
+
+
def test_doclib_server_list_responses_include_pagination_metadata(tmp_path: Path) -> None:
async def _run() -> None:
db = DatabaseManager(str(tmp_path / "doclib.db"))
@@ -1384,6 +1592,106 @@ def test_cleanup_orphans_keeps_docs_referenced_by_deleted_or_unreachable_files(t
asyncio.run(_run())
+def test_watch_loop_starts_watcher_before_initial_scan() -> None:
+ async def _run() -> None:
+ class _ConfigService:
+ async def list_watches(self) -> list[dict[str, Any]]:
+ return [{"id": 1, "path": "/watched", "status": "active"}]
+
+ order: list[str] = []
+ watch_loop = WatchLoop(
+ db=None,
+ config_svc=_ConfigService(),
+ parse_svc=None,
+ scan_interval_sec=0,
+ )
+
+ async def _watch_one(path: str, watch_id: int) -> None:
+ order.append("watch")
+ await asyncio.Event().wait()
+
+ async def _initial_scan(path: str, watch_id: int) -> None:
+ order.append("initial")
+ watch_loop.running = False
+
+ watch_loop._watch_one = _watch_one
+ watch_loop._initial_scan = _initial_scan
+
+ await watch_loop.run()
+ await watch_loop.stop()
+
+ assert order[:2] == ["watch", "initial"]
+
+ asyncio.run(_run())
+
+
+def test_watch_loop_wakeup_triggers_next_poll_without_interval_delay() -> None:
+ async def _run() -> None:
+ poll_count = 0
+ second_poll = asyncio.Event()
+
+ class _ConfigService:
+ async def list_watches(self) -> list[dict[str, Any]]:
+ nonlocal poll_count
+ poll_count += 1
+ if poll_count == 2:
+ second_poll.set()
+ return []
+
+ watch_loop = WatchLoop(
+ db=None,
+ config_svc=_ConfigService(),
+ parse_svc=None,
+ scan_interval_sec=300,
+ )
+ task = asyncio.create_task(watch_loop.run())
+
+ while poll_count == 0:
+ await asyncio.sleep(0)
+
+ watch_loop.wakeup()
+ await asyncio.wait_for(second_poll.wait(), timeout=1)
+ await watch_loop.stop()
+ await asyncio.wait_for(task, timeout=1)
+
+ assert poll_count == 2
+
+ asyncio.run(_run())
+
+
+def test_add_watch_wakes_background_watch_loop() -> None:
+ async def _run() -> None:
+ class _ConfigService:
+ async def add_watch(self, path: str, removable: bool, label: str | None) -> dict[str, Any]:
+ return {
+ "id": 1,
+ "path": path,
+ "label": label,
+ "removable": int(removable),
+ "enabled": 1,
+ "recursive": 1,
+ "status": "active",
+ }
+
+ class _WatchLoop:
+ def __init__(self) -> None:
+ self.wakeup_count = 0
+
+ def wakeup(self) -> None:
+ self.wakeup_count += 1
+
+ watch = _WatchLoop()
+ state = SimpleNamespace(config_svc=_ConfigService(), telemetry_svc=None, watch=watch)
+ server = DoclibServer(state)
+
+ info = await server.add_watch(WatchRequest(path="/watched", removable=True, label="Docs"))
+
+ assert info.id == 1
+ assert watch.wakeup_count == 1
+
+ asyncio.run(_run())
+
+
def test_server_status_includes_watch_stats_and_error_summary(tmp_path: Path) -> None:
class _ParseQueue:
async def get_queue_length(self) -> int:
@@ -1393,6 +1701,7 @@ def test_server_status_includes_watch_stats_and_error_summary(tmp_path: Path) ->
db = DatabaseManager(str(tmp_path / "doclib.db"))
await db.initialize()
config_svc = ConfigService(db)
+ (tmp_path / "watched").mkdir()
watch = await config_svc.add_watch(str(tmp_path / "watched"), removable=True)
now = 1000
sha_done = "5" * 64
@@ -1465,6 +1774,10 @@ def test_server_status_includes_watch_stats_and_error_summary(tmp_path: Path) ->
now + index,
),
)
+ await db.execute(
+ "INSERT INTO scans (path, kind, source, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
+ (str(tmp_path / "still-running.pdf"), "manual", "cli", "running", now + 99, now + 99),
+ )
state = SimpleNamespace(
db=db,
@@ -1474,6 +1787,13 @@ def test_server_status_includes_watch_stats_and_error_summary(tmp_path: Path) ->
pid=123,
socket_path="/tmp/doclib.sock",
data_dir=str(tmp_path / "data"),
+ watch=SimpleNamespace(running=False),
+ scan_workers=SimpleNamespace(running=False, num_workers=1),
+ ingest_workers=SimpleNamespace(running=False, num_workers=2),
+ parse_workers=SimpleNamespace(running=False, num_workers=2),
+ device_monitor=SimpleNamespace(running=False),
+ compaction=SimpleNamespace(running=False),
+ health_check=SimpleNamespace(running=False),
)
status = await DoclibServer(state).get_server_status()
@@ -1489,9 +1809,14 @@ def test_server_status_includes_watch_stats_and_error_summary(tmp_path: Path) ->
assert stats.doc_count == 2
assert stats.parse_done_count == 1
assert stats.parse_failed_count == 1
- assert [scan.path for scan in status.recent_scans] == [str(tmp_path / f"scan-{index}.pdf") for index in range(5, 0, -1)]
- assert status.recent_scans[0].error_code == "scan_failed"
- assert status.recent_scans[0].error_msg == "hidden message"
+ assert [scan.path for scan in status.recent_scans] == [
+ str(tmp_path / "still-running.pdf"),
+ *[str(tmp_path / f"scan-{index}.pdf") for index in range(5, 1, -1)],
+ ]
+ assert status.recent_scans[0].status == "running"
+ assert status.recent_scans[1].error_code == "scan_failed"
+ assert status.recent_scans[1].error_msg == "hidden message"
+ assert status.last_scan_at == now + 5
assert status.error_summary is not None
assert [(bucket.code, bucket.count) for bucket in status.error_summary.file_errors] == [("ingest_failed", 1), ("stat_failed", 1)]
assert [(bucket.code, bucket.count) for bucket in status.error_summary.doc_errors] == [("metadata_failed", 1)]
@@ -1652,6 +1977,52 @@ def test_ingest_records_doc_error_when_metadata_extraction_fails(tmp_path: Path,
asyncio.run(_run())
+def test_process_doc_rejects_existing_office_temp_lock_file_task(tmp_path: Path) -> None:
+ sha256 = "c" * 64
+ task = {
+ "id": 1,
+ "sha256": sha256,
+ "tier": "flash",
+ "page_range": "1",
+ "status": "parsing",
+ "privacy": "local",
+ }
+ parses = [
+ {
+ **task,
+ "error_code": None,
+ "error_msg": None,
+ "done_at": None,
+ "locked_at": 123,
+ "updated_at": 123,
+ }
+ ]
+ db = _FakeDB(
+ parses=parses,
+ file_row={
+ "path": "/tmp/~$package-size.xlsx",
+ "sha256": sha256,
+ "status": "active",
+ "filename": "~$package-size.xlsx",
+ "title": "",
+ "author": "",
+ },
+ )
+ service = ParseService(db=db, fts=_FakeFTS(), config_svc=None, data_dir=str(tmp_path), parse_lock_timeout_sec=1800)
+
+ async def _unexpected_parse(file_row: dict, tier: Tier, page_range: str) -> ParseResult:
+ raise AssertionError("temporary lock files should not reach parser execution")
+
+ service._parse_via_local = _unexpected_parse # type: ignore[method-assign]
+
+ success = asyncio.run(service.process_doc(task))
+
+ assert success is False
+ assert parses[0]["status"] == "failed"
+ assert parses[0]["error_code"] == "file_type_unsupported"
+ assert "temporary lock" in parses[0]["error_msg"]
+
+
def test_process_doc_marks_empty_page_result_failed(tmp_path: Path) -> None:
sha256 = "a" * 64
task = {
diff --git a/tests/unittest/test_doclib_file_io.py b/tests/unittest/test_doclib_file_io.py
new file mode 100644
index 00000000..d96e93ea
--- /dev/null
+++ b/tests/unittest/test_doclib_file_io.py
@@ -0,0 +1,53 @@
+from __future__ import annotations
+
+import asyncio
+from contextlib import contextmanager
+
+from mineru.doclib.core import file_io
+
+
+def test_extract_pdf_meta_serializes_pdfium_calls(monkeypatch) -> None:
+ state = {"guard_depth": 0, "closed_doc": False}
+
+ @contextmanager
+ def _fake_guard():
+ state["guard_depth"] += 1
+ try:
+ yield
+ finally:
+ state["guard_depth"] -= 1
+
+ class _FakePdf:
+ def __len__(self) -> int:
+ assert state["guard_depth"] > 0
+ return 7
+
+ def get_metadata_dict(self) -> dict[str, str]:
+ assert state["guard_depth"] > 0
+ return {
+ "Title": "Test Title",
+ "Author": "Test Author",
+ "Subject": "Test Subject",
+ "Keywords": "alpha,beta",
+ }
+
+ monkeypatch.setattr(file_io, "pdfium_guard", _fake_guard)
+ monkeypatch.setattr(file_io, "open_pdfium_document", lambda opener, filepath: _FakePdf())
+ monkeypatch.setattr(file_io, "close_pdfium_document", lambda pdf: state.__setitem__("closed_doc", True))
+
+ result = {
+ "page_count": None,
+ "title": None,
+ "author": None,
+ "subject": None,
+ "keywords": None,
+ "is_image_based": 0,
+ }
+ asyncio.run(file_io._extract_pdf_meta("dummy.pdf", result))
+
+ assert result["page_count"] == 7
+ assert result["title"] == "Test Title"
+ assert result["author"] == "Test Author"
+ assert result["subject"] == "Test Subject"
+ assert result["keywords"] == "alpha,beta"
+ assert state["closed_doc"] is True
diff --git a/tests/unittest/test_next_dev_release.py b/tests/unittest/test_next_dev_release.py
new file mode 100644
index 00000000..4dc71410
--- /dev/null
+++ b/tests/unittest/test_next_dev_release.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+import importlib.util
+import json
+import sys
+from datetime import UTC, datetime
+from pathlib import Path
+
+
+def _load_release_module():
+ module_path = Path(__file__).resolve().parents[2] / ".github" / "scripts" / "next_dev_release.py"
+ spec = importlib.util.spec_from_file_location("next_dev_release", module_path)
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_build_version_uses_utc_date() -> None:
+ module = _load_release_module()
+
+ version = module.build_version("4.0.0", datetime(2026, 6, 25, 1, 2, 3, tzinfo=UTC))
+
+ assert version == "4.0.0.dev20260625"
+
+
+def test_write_and_read_release_state(tmp_path: Path) -> None:
+ module = _load_release_module()
+ state_file = tmp_path / "state.json"
+
+ module.write_state(
+ state_file,
+ package="mineru-next-dev",
+ version="4.0.0.dev20260625",
+ source_branch="next",
+ source_commit="abc123",
+ published_at="2026-06-25T02:20:00Z",
+ )
+
+ payload = json.loads(state_file.read_text(encoding="utf-8"))
+ assert payload["source_commit"] == "abc123"
+
+ state = module.read_state(state_file)
+ assert state is not None
+ assert state.package == "mineru-next-dev"
+ assert state.version == "4.0.0.dev20260625"
+ assert state.source_branch == "next"
+ assert state.source_commit == "abc123"
+ assert state.published_at == "2026-06-25T02:20:00Z"
+
+
+def test_patch_workspace_updates_package_name_and_version(tmp_path: Path) -> None:
+ module = _load_release_module()
+ pyproject_path = tmp_path / "pyproject.toml"
+ version_file_path = tmp_path / "version.py"
+
+ pyproject_path.write_text(
+ '[project]\nname = "mineru"\ndynamic = ["version"]\n\n[tool.example]\nvalue = 1\n',
+ encoding="utf-8",
+ )
+ version_file_path.write_text('__version__ = "3.2.1"\n', encoding="utf-8")
+
+ module.patch_workspace(
+ pyproject_path=pyproject_path,
+ version_file_path=version_file_path,
+ package_name="mineru-next-dev",
+ version="4.0.0.dev20260625",
+ )
+
+ assert 'name = "mineru-next-dev"' in pyproject_path.read_text(encoding="utf-8")
+ assert version_file_path.read_text(encoding="utf-8") == '__version__ = "4.0.0.dev20260625"\n'
diff --git a/tests/unittest/test_office_parser_regressions.py b/tests/unittest/test_office_parser_regressions.py
new file mode 100644
index 00000000..d163ce97
--- /dev/null
+++ b/tests/unittest/test_office_parser_regressions.py
@@ -0,0 +1,96 @@
+from pathlib import Path
+
+from mineru.backend.office.office_magic_model import fix_two_layer_blocks
+from mineru.backend.utils import office_image
+from mineru.parser.html import HtmlParser
+from mineru.types import EMPTY_BBOX, Block, BlockType, ContentType, Line, Span
+
+
+def test_html_parser_populates_required_bbox_and_index_fields(tmp_path: Path) -> None:
+ html_file = tmp_path / "sample.html"
+ html_file.write_text(
+ "<html><body><h1>Hello</h1><p>World</p></body></html>", encoding="utf-8"
+ )
+
+ result = HtmlParser().parse(html_file)
+
+ blocks = result.pages[0].para_blocks
+ assert [block.index for block in blocks] == [0, 1]
+ assert [block.bbox for block in blocks] == [EMPTY_BBOX, EMPTY_BBOX]
+ assert all(line.bbox == EMPTY_BBOX for block in blocks for line in block.lines)
+ assert all(
+ span.bbox == EMPTY_BBOX
+ for block in blocks
+ for line in block.lines
+ for span in line.spans
+ )
+
+
+def test_office_two_layer_blocks_accept_block_dataclasses() -> None:
+ caption = Block(
+ index=0,
+ type=BlockType.IMAGE_CAPTION,
+ bbox=EMPTY_BBOX,
+ lines=[
+ Line(
+ bbox=EMPTY_BBOX,
+ spans=[
+ Span(type=ContentType.TEXT, bbox=EMPTY_BBOX, content="Figure 1")
+ ],
+ )
+ ],
+ )
+ body = Block(
+ index=1,
+ type=BlockType.IMAGE_BODY,
+ bbox=EMPTY_BBOX,
+ lines=[
+ Line(
+ bbox=EMPTY_BBOX,
+ spans=[
+ Span(type=ContentType.IMAGE, bbox=EMPTY_BBOX, image_base64="data")
+ ],
+ )
+ ],
+ )
+
+ fixed_blocks, not_included = fix_two_layer_blocks([caption, body], BlockType.IMAGE)
+
+ assert not_included == []
+ assert len(fixed_blocks) == 1
+ assert fixed_blocks[0].type == BlockType.IMAGE
+ assert [block.type for block in fixed_blocks[0].blocks] == [
+ BlockType.IMAGE_CAPTION,
+ BlockType.IMAGE_BODY,
+ ]
+
+
+def test_vector_image_part_skip_log_is_debug(monkeypatch) -> None:
+ class _Logger:
+ def __init__(self) -> None:
+ self.debug_messages: list[str] = []
+ self.warning_messages: list[str] = []
+
+ def debug(self, message: str) -> None:
+ self.debug_messages.append(message)
+
+ def warning(self, message: str) -> None:
+ self.warning_messages.append(message)
+
+ fake_logger = _Logger()
+ monkeypatch.setattr(office_image, "logger", fake_logger)
+ monkeypatch.setattr(
+ office_image,
+ "get_standard_vector_placeholder_data_uri",
+ lambda: "data:image/jpeg;base64,placeholder",
+ )
+
+ assert (
+ office_image.serialize_vector_part_with_placeholder(
+ "/word/media/image3.wmf", "image/x-wmf"
+ )
+ == "data:image/jpeg;base64,placeholder"
+ )
+ assert len(fake_logger.debug_messages) == 1
+ assert "Skipping WMF image part before Pillow load" in fake_logger.debug_messages[0]
+ assert fake_logger.warning_messages == []
diff --git a/tests/unittest/test_parser_flash.py b/tests/unittest/test_parser_flash.py
index 24da6787..c16b79f6 100644
--- a/tests/unittest/test_parser_flash.py
+++ b/tests/unittest/test_parser_flash.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from contextlib import contextmanager
+
from mineru.parser.pdf import PdfFlashParser
@@ -14,3 +16,52 @@ def test_flash_parser_preserves_page_indices_for_empty_pages(monkeypatch) -> Non
assert [page.page_idx for page in pages] == [10, 12, 13]
assert [len(page.para_blocks) for page in pages] == [1, 0, 1]
+
+
+def test_flash_pdf_extractor_serializes_pdfium_calls(monkeypatch) -> None:
+ from mineru.backend.flash import pdf_extractor
+
+ 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
+
+ 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()
+
+ def close(self) -> None:
+ state["closed_children"] += 1
+
+ class _FakePdf:
+ def __len__(self) -> int:
+ assert state["guard_depth"] > 0
+ return 2
+
+ def __getitem__(self, index: int) -> _FakePage:
+ assert state["guard_depth"] > 0
+ assert index in (0, 1)
+ return _FakePage()
+
+ monkeypatch.setattr(pdf_extractor, "pdfium_guard", _fake_guard)
+ monkeypatch.setattr(pdf_extractor, "open_pdfium_document", lambda opener, 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))
+
+ assert pdf_extractor.extract_pages_text("dummy.pdf") == ["page text", "page text"]
+ assert state["closed_children"] == 4
+ assert state["closed_doc"] is True
diff --git a/tests/unittest/test_parser_routing.py b/tests/unittest/test_parser_routing.py
new file mode 100644
index 00000000..c9f248b5
--- /dev/null
+++ b/tests/unittest/test_parser_routing.py
@@ -0,0 +1,63 @@
+from pathlib import Path
+
+import pytest
+
+from mineru.parser import _build_parser
+from mineru.parser.html import HtmlParser
+from mineru.parser.office import XlsxParser
+from mineru.parser.pdf import PdfFlashParser
+
+
+def test_build_parser_prefers_html_extension_when_content_guess_is_plain_text(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ html_file = tmp_path / "sample.html"
+ html_file.write_text("<div>hello</div>", encoding="utf-8")
+
+ monkeypatch.setattr("mineru.utils.guess_suffix_or_lang.guess_suffix_by_path", lambda path: "txt")
+
+ parser = _build_parser(html_file, tier="flash")
+
+ assert isinstance(parser, HtmlParser)
+
+
+def test_build_parser_prefers_xlsx_extension_when_content_guess_is_legacy_doc(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ xlsx_file = tmp_path / "legacy.xlsx"
+ xlsx_file.write_bytes(b"\xd0\xcf\x11\xe0")
+
+ monkeypatch.setattr("mineru.utils.guess_suffix_or_lang.guess_suffix_by_path", lambda path: "doc")
+
+ parser = _build_parser(xlsx_file, tier="flash")
+
+ assert isinstance(parser, XlsxParser)
+
+
+def test_build_parser_rejects_unsupported_suffix_instead_of_falling_back_to_pdf(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ text_file = tmp_path / "sample.txt"
+ text_file.write_text("hello", encoding="utf-8")
+
+ monkeypatch.setattr("mineru.utils.guess_suffix_or_lang.guess_suffix_by_path", lambda path: "txt")
+
+ with pytest.raises(ValueError, match="Unsupported file type"):
+ _build_parser(text_file, tier="flash")
+
+
+def test_build_parser_keeps_pdf_extension_routing_when_content_guess_is_html(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pdf_file = tmp_path / "sample.pdf"
+ pdf_file.write_bytes(b"%PDF")
+
+ monkeypatch.setattr("mineru.utils.guess_suffix_or_lang.guess_suffix_by_path", lambda path: "html")
+
+ parser = _build_parser(pdf_file, tier="flash")
+
+ assert isinstance(parser, PdfFlashParser)