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
fix(model): exclude directories from ModelScope file manifests
myhlolid98ed13486af
diff --git a/mineru/model/download.py b/mineru/model/download.pyindex e96f739b..db4e080d 100644--- a/mineru/model/download.py+++ b/mineru/model/download.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport refrom collections.abc import Sequencefrom dataclasses import dataclass, field-from pathlib import Path+from pathlib import Path, PurePosixPathfrom typing import TYPE_CHECKING, Literalimport requests@@ -146,7 +146,9 @@ def ms_model_files(repo_id: str) -> dict[str, int]:from modelscope.utils.constant import DEFAULT_MODEL_REVISIONfiles = HubApi().get_model_files(repo_id, revision=DEFAULT_MODEL_REVISION, recursive=True)- return {item["Path"]: item["Size"] for item in files if item.get("Type") != "tree"}+ # 新版 SDK 的兼容接口不再返回 Type;递归清单中的父路径仍能确定目录,且不会误删零字节文件。+ directories = {parent.as_posix() for item in files for parent in PurePosixPath(item["Path"]).parents}+ return {item["Path"]: item["Size"] for item in files if item.get("Type") != "tree" and item["Path"] not in directories}@dataclass(frozen=True)diff --git a/tests/unittest/test_models_download_utils.py b/tests/unittest/test_models_download_utils.pyindex 5c457ba5..f00c150a 100644--- a/tests/unittest/test_models_download_utils.py+++ b/tests/unittest/test_models_download_utils.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import sysfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any, NoReturn@@ -431,6 +432,69 @@ def test_download_does_not_mark_metadata_only_directory(assert (weights_dir / MODEL_COMPLETE_MARKER).exists() is False[email protected]("legacy_types", [False, True], ids=["sdk-without-type", "legacy-sdk"])[email protected]("weight_state", ["complete", "missing", "truncated"])+def test_modelscope_snapshot_excludes_directories_and_checks_real_files(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ legacy_types: bool,+ weight_state: str,+) -> None:+ """兼容新旧 SDK 的目录清单,同时保留空文件并拒绝缺失或截断的权重。"""+ repo = ModelRepo(name="repo", repos={"modelscope": "Owner/repo"}, paths={"layout": "Layout/PP-DocLayoutV2"})+ monkeypatch.setattr(models_download_utils.get_config().model, "base_dir", str(tmp_path / "models"))+ layout = "Layout/PP-DocLayoutV2"+ payloads = {f"{layout}/config.json": b"{}", f"{layout}/model.safetensors": b"weights", f"{layout}/empty.txt": b""}+ directories = ["Layout", layout, "Unused"]+ # 目录项故意排在文件之后,确保过滤逻辑不依赖 SDK 返回顺序。+ entries = [{"Path": name, "Size": len(content)} for name, content in payloads.items()]+ entries.extend({"Path": name, "Size": 0} for name in directories)+ entries.append({"Path": "Unused/model.bin", "Size": 7})+ if legacy_types:+ for entry in entries:+ entry["Type"] = "tree" if entry["Path"] in directories else "blob"++ class FakeApi:+ def get_model_files(self, repo_id: str, *, revision: str, recursive: bool) -> list[dict[str, Any]]:+ """返回真实接口形状的递归清单,覆盖不再包含 Type 的新版 SDK。"""+ assert repo_id == "Owner/repo"+ assert revision == "master"+ assert recursive+ return entries++ monkeypatch.setitem(sys.modules, "modelscope.hub.api", SimpleNamespace(HubApi=FakeApi))+ monkeypatch.setitem(sys.modules, "modelscope.utils.constant", SimpleNamespace(DEFAULT_MODEL_REVISION="master"))+ requested: list[str] = []++ def fake_ms_snapshot_download(repo_id: str, *, local_dir: str, allow_patterns: list[str]) -> str:+ """模拟下载真实文件,目录项由 SDK 忽略,缺失和截断按测试参数注入。"""+ assert repo_id == "Owner/repo"+ requested.extend(allow_patterns)+ for name, content in payloads.items():+ target = Path(local_dir) / name+ target.parent.mkdir(parents=True, exist_ok=True)+ if name.endswith("model.safetensors"):+ if weight_state == "missing":+ continue+ if weight_state == "truncated":+ content = content[:-1]+ target.write_bytes(content)+ return local_dir++ monkeypatch.setattr(models_download_utils, "ms_snapshot_download", fake_ms_snapshot_download)++ if weight_state != "complete":+ with pytest.raises(FileNotFoundError, match=r"missing or invalid: Layout/PP-DocLayoutV2/model\.safetensors$"):+ repo.layout.ensure(source="modelscope")+ assert not (repo.layout.local_path() / MODEL_COMPLETE_MARKER).exists()+ else:+ assert repo.layout.ensure(source="modelscope") == repo.layout.local_path()+ assert json.loads((repo.layout.local_path() / MODEL_COMPLETE_MARKER).read_text())["files"] == {+ name.removeprefix(f"{layout}/"): len(content) for name, content in payloads.items()+ }+ assert requested == list(payloads)++def test_huggingface_snapshot_rejects_missing_expected_files(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,