Skip to content

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

feat: add uniquify_task_stems function for handling duplicate document stems and implement visualization job processing

myhloli834dd496a314
diff --git a/mineru/cli/client.py b/mineru/cli/client.py
index 341ef9af..fd42f2cb 100644
--- a/mineru/cli/client.py
+++ b/mineru/cli/client.py
@@ -34,7 +34,12 @@ from mineru.utils.pdfium_guard import (
)
from ..version import __version__
-from .common import image_suffixes, office_suffixes, pdf_suffixes
+from .common import (
+ image_suffixes,
+ office_suffixes,
+ pdf_suffixes,
+ uniquify_task_stems,
+)
from .output_paths import resolve_parse_dir
from .visualization import (
VisualizationJob,
@@ -532,20 +537,28 @@ def collect_input_documents(
if not collected:
raise click.ClickException(f"No supported documents found under {input_path}")
- stem_to_paths: dict[str, list[Path]] = {}
- for document in collected:
- stem_to_paths.setdefault(document.stem, []).append(document.path)
- duplicate_stems = {
- stem: paths for stem, paths in stem_to_paths.items() if len(paths) > 1
- }
- if duplicate_stems:
- details = "; ".join(
- f"{stem}: {', '.join(str(path) for path in paths)}"
- for stem, paths in sorted(duplicate_stems.items())
+ normalized_stems, renamed_stems = uniquify_task_stems(
+ [document.stem for document in collected]
+ )
+ if renamed_stems:
+ rename_details = ", ".join(
+ f"{document.path.name} -> {effective_stem}"
+ for document, effective_stem in zip(collected, normalized_stems)
+ if document.stem != effective_stem
)
- raise click.ClickException(
- f"Duplicate output stems detected. Rename inputs to avoid collisions: {details}"
+ logger.warning(
+ f"Normalized duplicate document stems within this run: {rename_details}"
)
+ return [
+ InputDocument(
+ path=document.path,
+ suffix=document.suffix,
+ stem=effective_stem,
+ effective_pages=document.effective_pages,
+ order=document.order,
+ )
+ for document, effective_stem in zip(collected, normalized_stems)
+ ]
return collected
diff --git a/mineru/cli/common.py b/mineru/cli/common.py
index 302da4b5..240f52f2 100644
--- a/mineru/cli/common.py
+++ b/mineru/cli/common.py
@@ -3,6 +3,7 @@ import json
import os
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
+from typing import Sequence
from loguru import logger
@@ -34,6 +35,42 @@ office_suffixes = docx_suffixes + pptx_suffixes + xlsx_suffixes
os.environ["TOKENIZERS_PARALLELISM"] = "false"
+
+def uniquify_task_stems(
+ stems: Sequence[str],
+) -> tuple[list[str], list[tuple[str, str]]]:
+ """Assign task-local unique stems while preserving input order."""
+ raw_keys = {stem.casefold() for stem in stems}
+ occurrence_counts: dict[str, int] = {}
+ assigned_keys: set[str] = set()
+ unique_stems: list[str] = []
+ renamed: list[tuple[str, str]] = []
+
+ for stem in stems:
+ stem_key = stem.casefold()
+ seen_count = occurrence_counts.get(stem_key, 0)
+ occurrence_counts[stem_key] = seen_count + 1
+
+ if seen_count == 0 and stem_key not in assigned_keys:
+ effective_stem = stem
+ else:
+ suffix = seen_count + 1
+ while True:
+ candidate = f"{stem}_{suffix}"
+ candidate_key = candidate.casefold()
+ if candidate_key not in raw_keys and candidate_key not in assigned_keys:
+ effective_stem = candidate
+ break
+ suffix += 1
+
+ assigned_keys.add(effective_stem.casefold())
+ unique_stems.append(effective_stem)
+ if effective_stem != stem:
+ renamed.append((stem, effective_stem))
+
+ return unique_stems, renamed
+
+
def read_fn(path, file_suffix: str | None = None):
if not isinstance(path, Path):
path = Path(path)
diff --git a/mineru/cli/fast_api.py b/mineru/cli/fast_api.py
index b8074249..7571f36b 100644
--- a/mineru/cli/fast_api.py
+++ b/mineru/cli/fast_api.py
@@ -39,6 +39,7 @@ from mineru.cli.common import (
office_suffixes,
pdf_suffixes,
read_fn,
+ uniquify_task_stems,
)
from mineru.cli.output_paths import resolve_parse_dir
from mineru.cli.api_protocol import (
@@ -133,6 +134,7 @@ class AsyncParseTask:
return_original_file: bool
start_page_id: int
end_page_id: int
+ upload_names: list[str]
uploads: list[str]
started_at: Optional[str] = None
completed_at: Optional[str] = None
@@ -286,6 +288,21 @@ def cleanup_file(file_path: str) -> None:
logger.warning(f"fail clean file {file_path}: {e}")
+def build_upload_destination(upload_dir: str, filename: str) -> Path:
+ destination = Path(upload_dir) / filename
+ if not destination.exists():
+ return destination
+
+ base_name = Path(filename).stem
+ suffix = Path(filename).suffix
+ index = 2
+ while True:
+ candidate = Path(upload_dir) / f"{base_name}__upload_{index}{suffix}"
+ if not candidate.exists():
+ return candidate
+ index += 1
+
+
def encode_image(image_path: str) -> str:
"""Encode image using base64"""
with open(image_path, "rb") as f:
@@ -736,7 +753,7 @@ async def save_upload_files(upload_dir: str, files: list[UploadFile]) -> list[St
for upload in files:
original_name = upload.filename or f"upload-{uuid.uuid4()}"
filename = Path(original_name).name
- destination = Path(upload_dir) / filename
+ destination = build_upload_destination(upload_dir, filename)
try:
with open(destination, "wb") as handle:
while True:
@@ -765,6 +782,27 @@ async def save_upload_files(upload_dir: str, files: list[UploadFile]) -> list[St
raise
finally:
await upload.close()
+
+ normalized_stems, renamed_stems = uniquify_task_stems(
+ [upload.stem for upload in uploads]
+ )
+ if renamed_stems:
+ rename_details = ", ".join(
+ f"{Path(upload.original_name).name} -> {effective_stem}"
+ for upload, effective_stem in zip(uploads, normalized_stems)
+ if upload.stem != effective_stem
+ )
+ logger.warning(
+ f"Normalized duplicate upload stems within request: {rename_details}"
+ )
+ uploads = [
+ StoredUpload(
+ original_name=upload.original_name,
+ stem=effective_stem,
+ path=upload.path,
+ )
+ for upload, effective_stem in zip(uploads, normalized_stems)
+ ]
return uploads
@@ -883,6 +921,7 @@ async def create_async_parse_task(
return_original_file=request_options.return_original_file,
start_page_id=request_options.start_page_id,
end_page_id=request_options.end_page_id,
+ upload_names=[upload.original_name for upload in uploads],
uploads=[upload.path for upload in uploads],
)
await task_manager.submit(task)
@@ -1102,11 +1141,15 @@ class AsyncTaskManager:
uploads = [
StoredUpload(
- original_name=Path(upload_path).name,
- stem=Path(upload_path).stem,
+ original_name=upload_name,
+ stem=file_name,
path=upload_path,
)
- for upload_path in task.uploads
+ for upload_name, file_name, upload_path in zip(
+ task.upload_names,
+ task.file_names,
+ task.uploads,
+ )
]
config = getattr(self.app.state, "config", {})
await run_parse_job(
diff --git a/mineru/cli/output_paths.py b/mineru/cli/output_paths.py
new file mode 100644
index 00000000..47df276f
--- /dev/null
+++ b/mineru/cli/output_paths.py
@@ -0,0 +1,57 @@
+from pathlib import Path
+
+
+OFFICE_PARSE_DIR_NAME = "office"
+VLM_PARSE_DIR_NAME = "vlm"
+
+
+def build_parse_dir(
+ output_dir: str | Path,
+ pdf_name: str,
+ backend: str,
+ parse_method: str,
+ *,
+ is_office: bool = False,
+) -> Path:
+ output_root = Path(output_dir)
+ if is_office:
+ return output_root / pdf_name / OFFICE_PARSE_DIR_NAME
+ if backend.startswith("pipeline"):
+ return output_root / pdf_name / parse_method
+ if backend.startswith("vlm"):
+ return output_root / pdf_name / VLM_PARSE_DIR_NAME
+ if backend.startswith("hybrid"):
+ return output_root / pdf_name / f"hybrid_{parse_method}"
+ raise ValueError(f"Unknown backend type: {backend}")
+
+
+def resolve_parse_dir(
+ output_dir: str | Path,
+ pdf_name: str,
+ backend: str,
+ parse_method: str,
+ *,
+ is_office: bool = False,
+ allow_office_fallback: bool = False,
+) -> Path:
+ parse_dir = build_parse_dir(
+ output_dir,
+ pdf_name,
+ backend,
+ parse_method,
+ is_office=is_office,
+ )
+ if is_office:
+ return parse_dir
+
+ if allow_office_fallback and not parse_dir.exists():
+ office_dir = build_parse_dir(
+ output_dir,
+ pdf_name,
+ backend,
+ parse_method,
+ is_office=True,
+ )
+ if office_dir.exists():
+ return office_dir
+ return parse_dir
diff --git a/mineru/cli/visualization.py b/mineru/cli/visualization.py
new file mode 100644
index 00000000..3017a8fa
--- /dev/null
+++ b/mineru/cli/visualization.py
@@ -0,0 +1,89 @@
+import json
+from dataclasses import dataclass
+from pathlib import Path
+
+from mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bbox
+
+
+VISUALIZATION_FINISHED = "finished"
+VISUALIZATION_SKIPPED = "skipped"
+
+
+@dataclass(frozen=True)
+class VisualizationJob:
+ document_stem: str
+ backend: str
+ parse_method: str
+ parse_dir: Path
+ draw_span: bool
+
+
+@dataclass(frozen=True)
+class VisualizationResult:
+ document_stem: str
+ parse_dir: Path
+ status: str
+ message: str
+ generated_files: tuple[str, ...] = ()
+
+
+def run_visualization_job(job: VisualizationJob) -> VisualizationResult:
+ middle_json_path = job.parse_dir / f"{job.document_stem}_middle.json"
+ origin_pdf_path = job.parse_dir / f"{job.document_stem}_origin.pdf"
+
+ if not middle_json_path.exists():
+ return VisualizationResult(
+ document_stem=job.document_stem,
+ parse_dir=job.parse_dir,
+ status=VISUALIZATION_SKIPPED,
+ message=f"missing middle.json: {middle_json_path.name}",
+ )
+ if not origin_pdf_path.exists():
+ return VisualizationResult(
+ document_stem=job.document_stem,
+ parse_dir=job.parse_dir,
+ status=VISUALIZATION_SKIPPED,
+ message=f"missing origin.pdf: {origin_pdf_path.name}",
+ )
+
+ try:
+ payload = json.loads(middle_json_path.read_text(encoding="utf-8"))
+ except Exception as exc:
+ return VisualizationResult(
+ document_stem=job.document_stem,
+ parse_dir=job.parse_dir,
+ status=VISUALIZATION_SKIPPED,
+ message=f"failed to read middle.json: {exc}",
+ )
+
+ pdf_info = payload.get("pdf_info")
+ if not isinstance(pdf_info, list):
+ return VisualizationResult(
+ document_stem=job.document_stem,
+ parse_dir=job.parse_dir,
+ status=VISUALIZATION_SKIPPED,
+ message="invalid middle.json: missing pdf_info",
+ )
+
+ try:
+ pdf_bytes = origin_pdf_path.read_bytes()
+ generated_files = [f"{job.document_stem}_layout.pdf"]
+ draw_layout_bbox(pdf_info, pdf_bytes, str(job.parse_dir), generated_files[0])
+ if job.draw_span:
+ generated_files.append(f"{job.document_stem}_span.pdf")
+ draw_span_bbox(pdf_info, pdf_bytes, str(job.parse_dir), generated_files[1])
+ except Exception as exc:
+ return VisualizationResult(
+ document_stem=job.document_stem,
+ parse_dir=job.parse_dir,
+ status=VISUALIZATION_SKIPPED,
+ message=f"visualization failed: {exc}",
+ )
+
+ return VisualizationResult(
+ document_stem=job.document_stem,
+ parse_dir=job.parse_dir,
+ status=VISUALIZATION_FINISHED,
+ message="generated visualization pdf(s)",
+ generated_files=tuple(generated_files),
+ )