Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: implement task stem normalization and improve filename handling in uploads
myhloli616649183156
diff --git a/mineru/cli/common.py b/mineru/cli/common.pyindex 240f52f2..683521b6 100644--- a/mineru/cli/common.py+++ b/mineru/cli/common.py@@ -34,29 +34,70 @@ xlsx_suffixes = ["xlsx"]office_suffixes = docx_suffixes + pptx_suffixes + xlsx_suffixesos.environ["TOKENIZERS_PARALLELISM"] = "false"+MAX_TASK_STEM_BYTES = 200+++def utf8_byte_length(value: str) -> int:+ return len(value.encode("utf-8"))+++def truncate_to_utf8_bytes(value: str, max_bytes: int) -> str:+ if max_bytes <= 0:+ return ""++ encoded = value.encode("utf-8")+ if len(encoded) <= max_bytes:+ return value++ truncated = encoded[:max_bytes]+ while truncated:+ try:+ return truncated.decode("utf-8")+ except UnicodeDecodeError as exc:+ truncated = truncated[:exc.start]+ return ""+++def normalize_task_stem(stem: str, max_bytes: int = MAX_TASK_STEM_BYTES) -> str:+ return truncate_to_utf8_bytes(stem, max_bytes)+++def build_task_stem_candidate(+ stem: str,+ suffix: str = "",+ max_bytes: int = MAX_TASK_STEM_BYTES,+) -> str:+ if utf8_byte_length(f"{stem}{suffix}") <= max_bytes:+ return f"{stem}{suffix}"+ suffix_bytes = utf8_byte_length(suffix)+ if suffix_bytes >= max_bytes:+ return truncate_to_utf8_bytes(suffix, max_bytes)+ return f"{truncate_to_utf8_bytes(stem, max_bytes - suffix_bytes)}{suffix}"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}+ normalized_inputs = [normalize_task_stem(stem) for stem in stems]+ raw_keys = {stem.casefold() for stem in normalized_inputs}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()+ for stem, normalized_stem in zip(stems, normalized_inputs):+ stem_base = normalized_stem or stem+ stem_key = stem_base.casefold()seen_count = occurrence_counts.get(stem_key, 0)occurrence_counts[stem_key] = seen_count + 1if seen_count == 0 and stem_key not in assigned_keys:- effective_stem = stem+ effective_stem = stem_baseelse:suffix = seen_count + 1while True:- candidate = f"{stem}_{suffix}"+ candidate = build_task_stem_candidate(stem_base, f"_{suffix}")candidate_key = candidate.casefold()if candidate_key not in raw_keys and candidate_key not in assigned_keys:effective_stem = candidatediff --git a/mineru/cli/fast_api.py b/mineru/cli/fast_api.pyindex 6fc5804d..ab17c9b0 100644--- a/mineru/cli/fast_api.py+++ b/mineru/cli/fast_api.py@@ -37,6 +37,7 @@ from mineru.cli.common import (image_suffixes,office_suffixes,pdf_suffixes,+ normalize_task_stem,read_fn,uniquify_task_stems,)@@ -748,7 +749,10 @@ async def save_upload_files(upload_dir: str, files: list[UploadFile]) -> list[Stfor upload in files:original_name = upload.filename or f"upload-{uuid.uuid4()}"- filename = Path(original_name).name+ sanitized_name = Path(original_name).name+ sanitized_path = Path(sanitized_name)+ normalized_stem = normalize_task_stem(sanitized_path.stem)+ filename = f"{normalized_stem}{sanitized_path.suffix}"destination = build_upload_destination(upload_dir, filename)try:with open(destination, "wb") as handle:@@ -769,7 +773,7 @@ async def save_upload_files(upload_dir: str, files: list[UploadFile]) -> list[Stuploads.append(StoredUpload(original_name=original_name,- stem=Path(filename).stem,+ stem=normalized_stem,path=str(destination),))diff --git a/mineru/cli/gradio_app.py b/mineru/cli/gradio_app.pyindex cc3f9d6f..04cd8053 100644--- a/mineru/cli/gradio_app.py+++ b/mineru/cli/gradio_app.py@@ -32,6 +32,7 @@ logger.add(sys.stderr, level=log_level) # 添加新handlerfrom mineru.cli.common import (docx_suffixes,image_suffixes,+ normalize_task_stem,office_suffixes,pdf_suffixes,read_fn,@@ -506,6 +507,11 @@ def create_gradio_run_paths(file_path, output_root="./output"):return run_root, extract_root, archive_zip_path+def build_gradio_upload_name(file_path):+ path = Path(file_path)+ return f"{normalize_task_stem(path.stem)}{path.suffix}"++def resolve_result_file_name(submit_response, extract_root, file_path):if submit_response.file_names:return submit_response.file_names[0]@@ -513,7 +519,7 @@ def resolve_result_file_name(submit_response, extract_root, file_path):candidate_dirs = sorted(path.name for path in Path(extract_root).iterdir() if path.is_dir())if len(candidate_dirs) == 1:return candidate_dirs[0]- return Path(file_path).stem+ return normalize_task_stem(Path(file_path).stem)async def resolve_server_health(http_client, api_url):@@ -613,7 +619,7 @@ async def _run_to_markdown_job(upload_assets = [_api_client.UploadAsset(path=Path(file_path),- upload_name=Path(file_path).name,+ upload_name=build_gradio_upload_name(file_path),)]