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
Add model download completion markers
jinzhenj468848b70521
diff --git a/docs/en/usage/model_source.md b/docs/en/usage/model_source.mdindex e6add670..5cdbbd84 100644--- a/docs/en/usage/model_source.md+++ b/docs/en/usage/model_source.md@@ -46,6 +46,7 @@ mineru-kit models download --tier high>- If you need a custom model directory, set `model.base_dir` in `config.yaml` before downloading.>- If you need to update model files, run `mineru-kit models download --tier high` again. Existing files in the same `model.base_dir` are incrementally reused by the provider SDK.>- `mineru-kit models download` must use a remote model source to perform a real download. If your current config sets `model.source: local`, this command temporarily treats it as `auto` for this invocation.+>- MinerU marks a fully downloaded repository with an empty `.mineru_complete` file at its root. Repositories downloaded by required paths instead mark each completed model directory. A directory left by an older release or an interrupted download without its marker is checked through an incremental provider download before use. With `model.source: local`, such a directory is reported as not ready instead of accessing the network.### 2. Use Local Models for Parsingdiff --git a/docs/next/decisions/0025-model-download-local-dir.md b/docs/next/decisions/0025-model-download-local-dir.mdindex f3bd65fe..6fa499c7 100644--- a/docs/next/decisions/0025-model-download-local-dir.md+++ b/docs/next/decisions/0025-model-download-local-dir.md@@ -272,7 +272,7 @@ repo 同时声明默认下载策略:- `download_mode="full"`: `download_model_repo(repo)` 下载完整仓库。- `download_mode="required_paths"`: `download_model_repo(repo)` 只下载 `repo.required_paths()` 对应的文件/目录。-当前 `PDF-Extract-Kit-1.0` 使用 `required_paths`,避免拉取仓库中未被 runtime 使用的大量历史/可选权重。`MinerU2.5-Pro-2605-1.2B` 保持 `full`,因为 VLM 模型加载通常需要完整 tokenizer/config/weights 文件集,registry 中的 paths 只作为 readiness marker。+当前 `PDF-Extract-Kit-1.0` 使用 `required_paths`,避免拉取仓库中未被 runtime 使用的大量历史/可选权重。`MinerU2.5-Pro-2605-1.2B` 保持 `full`,因为 VLM 模型加载通常需要完整 tokenizer/config/weights 文件集;整仓 readiness 由仓库根目录的 `.mineru_complete` 表示,不再维护逐文件 paths 清单。### 7. 下载 API@@ -352,6 +352,12 @@ def verify_model_tier(tier: Tier) -> ModelReadyResult:- `mineru-kit models verify --tier <tier>` 检查该 tier 需要的 repo 集合。- managed local parse server 的 tier readiness 检查基于 `REPOS_FOR_TIER`。- partial download 只验证本次请求 paths,不要求整仓 ready。+- 最终文件存在时视为 ready;Hugging Face 和 ModelScope 都先写临时文件,完成后再移动到最终路径。+- `full` 模式在 ModelRepo 根目录写入空白 `.mineru_complete`,表示整仓 ready;`required_paths` 模式在每个目录型 ModelPath 下分别写入 marker,文件型 ModelPath 仍按最终文件是否存在判断。+- marker 只由 MinerU 在 provider 下载成功返回且下载后 payload 检查通过后创建。+- 下载或更新目录前删除旧 marker;下载失败、payload 缺失或进程中断时不创建 marker。+- provider 的 `.cache/huggingface`、`._____temp`、`.msc`、`.mdl` 和 `.mv` 等元数据或临时内容不能单独作为模型 payload。+- 旧版本留下但没有 marker 的目录按未确认完整处理;远端 source 会通过 provider 增量补齐并创建 marker,`local` source 则报告 not ready。### 10. 并发安全diff --git a/docs/zh/usage/model_source.md b/docs/zh/usage/model_source.mdindex e67d3a38..3359d0fd 100644--- a/docs/zh/usage/model_source.md+++ b/docs/zh/usage/model_source.md@@ -47,6 +47,7 @@ mineru-kit models download --tier high>- 如需自定义模型目录,请先在 `config.yaml` 中设置 `model.base_dir`,再执行下载。>- 如需更新模型文件,可以再次运行 `mineru-kit models download --tier high`;在同一个 `model.base_dir` 下,provider SDK 会尽量复用已有文件做增量更新。>- `mineru-kit models download` 必须使用远端模型源执行真实下载;如果当前配置为 `model.source: local`,该命令会仅在本次执行中临时按 `auto` 处理。+>- MinerU 会在整仓下载完成后于仓库根目录写入空白 `.mineru_complete`;按指定路径下载时,则分别标记已完成的模型目录。旧版本或中断下载留下但没有相应 marker 的目录,会在使用前通过 provider 增量下载确认;当 `model.source: local` 时,这类目录会报告为未 ready,而不会访问网络。### 2. 使用本地模型进行解析diff --git a/mineru/utils/model_registry.py b/mineru/utils/model_registry.pyindex 72a9e4f3..0b16c5cc 100644--- a/mineru/utils/model_registry.py+++ b/mineru/utils/model_registry.py@@ -1,6 +1,5 @@from __future__ import annotations-import osimport refrom dataclasses import dataclassfrom pathlib import Path@@ -13,6 +12,7 @@ if TYPE_CHECKING:from ..config import ModelSourceDownloadMode = Literal["full", "required_paths"]+MODEL_COMPLETE_MARKER = ".mineru_complete"def _join_model_path(*parts: str) -> str:@@ -44,7 +44,7 @@ class ModelPath:def ensure(self, *, source: "ModelSource | None" = None) -> Path:from .models_download_utils import download_model_files- download_model_files(self.repo, [self], source=source)+ download_model_files(self.repo, [self], source=source, reuse_ready=True)return self.local_path()@@ -82,7 +82,7 @@ class ModelRepo:def ensure(self, *, source: "ModelSource | None" = None) -> Path:from .models_download_utils import download_model_repo- return download_model_repo(self, source=source)+ return download_model_repo(self, source=source, reuse_ready=True)PDF_EXTRACT_KIT = ModelRepo(@@ -110,13 +110,7 @@ MINERU_2_5_PRO_2605_1_2B = ModelRepo("huggingface": "opendatalab/MinerU2.5-Pro-2605-1.2B","modelscope": "OpenDataLab/MinerU2.5-Pro-2605-1.2B",},- paths={- "config_json": "config.json",- "model_safetensors": "model.safetensors",- "preprocessor_config_json": "preprocessor_config.json",- "tokenizer_config_json": "tokenizer_config.json",- "tokenizer_json": "tokenizer.json",- },+ paths={},)MODEL_REPOS: tuple[ModelRepo, ...] = (@@ -156,11 +150,22 @@ def model_path_exists(path: ModelPath) -> bool:return Trueif not local_path.is_dir():return False- return any(files for _root, _dirs, files in os.walk(local_path))+ repo_root = path.repo.local_dir()+ try:+ local_path.relative_to(repo_root)+ except ValueError:+ return False+ for directory in (local_path, *local_path.parents):+ if (directory / MODEL_COMPLETE_MARKER).is_file():+ return True+ if directory == repo_root:+ break+ return False__all__ = ["MINERU_2_5_PRO_2605_1_2B",+ "MODEL_COMPLETE_MARKER","MODEL_REPOS","MODEL_REPOS_BY_NAME","DownloadMode",diff --git a/mineru/utils/models_download_utils.py b/mineru/utils/models_download_utils.pyindex b10d4d26..50c3f0a2 100644--- a/mineru/utils/models_download_utils.py+++ b/mineru/utils/models_download_utils.py@@ -1,19 +1,22 @@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations+import os+from collections.abc import Sequencefrom dataclasses import dataclass, fieldfrom pathlib import Path-from collections.abc import Sequencefrom typing import Literal+import requestsfrom filelock import FileLock+from huggingface_hub import HfApifrom huggingface_hub import snapshot_download as hf_snapshot_download+from huggingface_hub.utils import filter_repo_objectsfrom loguru import loggerfrom modelscope import snapshot_download as ms_snapshot_download-import requestsfrom ..config import config, get_config_source, update_config_file-from .model_registry import ModelPath, ModelRepo, model_path_exists+from .model_registry import MODEL_COMPLETE_MARKER, ModelPath, ModelRepo, model_path_existsMODEL_SOURCE_ENV_VAR = "MINERU_MODEL_SOURCE"_HUGGINGFACE_MODELS_PAGE_URL = "https://huggingface.co/models"@@ -23,6 +26,8 @@ _REMOTE_MODEL_SOURCES = ("huggingface", "modelscope")DOWNLOAD_MODEL_SOURCES = ("auto", *_REMOTE_MODEL_SOURCES)ResolvedRemoteModelSource = Literal["huggingface", "modelscope"]ResolvedModelSource = Literal["huggingface", "modelscope", "local"]+_PROVIDER_METADATA_DIR_NAMES = {".cache", "._____temp"}+_PROVIDER_METADATA_FILE_NAMES = {MODEL_COMPLETE_MARKER, ".msc", ".mdl", ".mv"}@dataclass(frozen=True)@@ -117,7 +122,17 @@ def _snapshot_download(model_source: ResolvedRemoteModelSource, repo: ModelRepo,if patterns is not None:kwargs["allow_patterns"] = patternsif model_source == "huggingface":- return hf_snapshot_download(repo_id, **kwargs)+ # Hugging Face may return a non-empty local_dir when the remote repo is unavailable, so verify the expected+ # remote manifest before treating the snapshot as complete.+ expected_files = list(filter_repo_objects(HfApi().list_repo_files(repo_id), allow_patterns=patterns))+ if not expected_files:+ raise FileNotFoundError(f"Hugging Face snapshot for {repo.name} has no files matching the requested paths.")+ root = hf_snapshot_download(repo_id, **kwargs)+ missing_files = [path for path in expected_files if not (local_dir / path).is_file()]+ if missing_files:+ missing = ", ".join(missing_files)+ raise FileNotFoundError(f"Hugging Face snapshot for {repo.name} is incomplete; missing: {missing}")+ return rootreturn ms_snapshot_download(repo_id, **kwargs)@@ -136,9 +151,7 @@ def _relative_paths(repo: ModelRepo, paths: Sequence[str | ModelPath]) -> list[sfor path in paths:if isinstance(path, ModelPath):if path.repo is not repo:- raise ValueError(- f"Model path {path.relative_path!r} belongs to repo {path.repo.name!r}, not {repo.name!r}."- )+ raise ValueError(f"Model path {path.relative_path!r} belongs to repo {path.repo.name!r}, not {repo.name!r}.")relative_paths.append(path.relative_path)else:relative_paths.append(str(path).strip("/"))@@ -151,28 +164,101 @@ def _verify_paths(repo: ModelRepo, paths: Sequence[str | ModelPath]) -> ModelReareturn ModelReadyResult(ready=not missing, root=repo.local_dir(), missing_paths=missing)+def _directory_has_payload(path: Path) -> bool:+ for _root, dir_names, file_names in os.walk(path):+ dir_names[:] = [name for name in dir_names if name not in _PROVIDER_METADATA_DIR_NAMES]+ if any(name not in _PROVIDER_METADATA_FILE_NAMES for name in file_names):+ return True+ return False+++def _payload_path_exists(path: ModelPath) -> bool:+ local_path = path.local_path()+ if local_path.is_file():+ return True+ if not local_path.is_dir():+ return False+ return _directory_has_payload(local_path)+++def _verify_downloaded_paths(repo: ModelRepo, paths: Sequence[str | ModelPath]) -> ModelReadyResult:+ model_paths = [path if isinstance(path, ModelPath) else repo.path(path) for path in paths]+ missing = [path.relative_path for path in model_paths if not _payload_path_exists(path)]+ return ModelReadyResult(ready=not missing, root=repo.local_dir(), missing_paths=missing)+++def _repo_completion_paths(repo: ModelRepo) -> list[ModelPath]:+ if repo.download_mode == "full":+ return [repo.path("")]+ return list(repo.required_paths())+++def _remove_directory_markers(paths: Sequence[ModelPath]) -> list[Path]:+ removed_markers: list[Path] = []+ for path in paths:+ local_path = path.local_path()+ if not local_path.is_dir():+ continue+ repo_root = path.repo.local_dir()+ for directory in (local_path, *local_path.parents):+ marker = directory / MODEL_COMPLETE_MARKER+ if marker.is_file():+ marker.unlink()+ removed_markers.append(marker)+ if directory == repo_root:+ break+ return removed_markers+++def _mark_directories_complete(paths: Sequence[ModelPath]) -> None:+ for path in paths:+ local_path = path.local_path()+ if local_path.is_dir():+ (local_path / MODEL_COMPLETE_MARKER).touch(exist_ok=True)+++def _restore_directory_markers(markers: Sequence[Path]) -> None:+ for marker in markers:+ marker.touch(exist_ok=True)++def _raise_not_ready(repo: ModelRepo, result: ModelReadyResult) -> None:missing = ", ".join(result.missing_paths)raise FileNotFoundError(f"Model repo {repo.name} is not ready under {result.root}; missing: {missing}")-def download_model_repo(repo: ModelRepo, *, source: str | None = None, local_as_auto: bool = False) -> Path:- resolved_source = resolve_model_source(source, allow_auto=True, local_as_auto=local_as_auto)- if resolved_source == "local":- result = verify_model_repo(repo)- if not result.ready:- _raise_not_ready(repo, result)- return result.root-- relative_paths = [path.relative_path for path in repo.required_paths()] if repo.download_mode == "required_paths" else None+def download_model_repo(+ repo: ModelRepo,+ *,+ source: str | None = None,+ local_as_auto: bool = False,+ reuse_ready: bool = False,+) -> Path:+ completion_paths = _repo_completion_paths(repo)+ relative_paths = [path.relative_path for path in completion_paths] if repo.download_mode == "required_paths" else Nonelock_path = repo.lock_path()lock_path.parent.mkdir(parents=True, exist_ok=True)with FileLock(str(lock_path)):+ if reuse_ready:+ ready_result = verify_model_repo(repo)+ if ready_result.ready:+ return ready_result.root++ resolved_source = resolve_model_source(source, allow_auto=True, local_as_auto=local_as_auto)+ if resolved_source == "local":+ result = verify_model_repo(repo)+ if not result.ready:+ _raise_not_ready(repo, result)+ return result.root++ removed_markers = _remove_directory_markers(completion_paths)_snapshot_download(resolved_source, repo, None if relative_paths is None else _path_patterns(relative_paths))- result = verify_model_repo(repo)- if not result.ready:- _raise_not_ready(repo, result)- return result.root+ downloaded_result = _verify_downloaded_paths(repo, completion_paths)+ if not downloaded_result.ready:+ _raise_not_ready(repo, downloaded_result)+ _mark_directories_complete(completion_paths)+ _restore_directory_markers(removed_markers)+ return downloaded_result.rootdef download_model_files(@@ -181,29 +267,47 @@ def download_model_files(*,source: str | None = None,local_as_auto: bool = False,+ reuse_ready: bool = False,) -> Path:if not paths:return repo.local_dir()- resolved_source = resolve_model_source(source, allow_auto=True, local_as_auto=local_as_auto)- if resolved_source == "local":- result = _verify_paths(repo, paths)- if not result.ready:- _raise_not_ready(repo, result)- return result.root-+ model_paths = [path if isinstance(path, ModelPath) else repo.path(path) for path in paths]relative_paths = _relative_paths(repo, paths)lock_path = repo.lock_path()lock_path.parent.mkdir(parents=True, exist_ok=True)with FileLock(str(lock_path)):+ if reuse_ready:+ ready_result = _verify_paths(repo, model_paths)+ if ready_result.ready:+ return ready_result.root++ resolved_source = resolve_model_source(source, allow_auto=True, local_as_auto=local_as_auto)+ if resolved_source == "local":+ result = _verify_paths(repo, model_paths)+ if not result.ready:+ _raise_not_ready(repo, result)+ return result.root++ removed_markers = _remove_directory_markers(model_paths)_snapshot_download(resolved_source, repo, _path_patterns(relative_paths))- result = _verify_paths(repo, paths)- if not result.ready:- _raise_not_ready(repo, result)- return result.root+ downloaded_result = _verify_downloaded_paths(repo, model_paths)+ if not downloaded_result.ready:+ _raise_not_ready(repo, downloaded_result)+ _mark_directories_complete(model_paths)+ _restore_directory_markers(removed_markers)+ return downloaded_result.rootdef verify_model_repo(repo: ModelRepo) -> ModelReadyResult:+ if repo.download_mode == "full":+ marker = repo.local_dir() / MODEL_COMPLETE_MARKER+ ready = marker.is_file()+ return ModelReadyResult(+ ready=ready,+ root=repo.local_dir(),+ missing_paths=[] if ready else [MODEL_COMPLETE_MARKER],+ )return _verify_paths(repo, list(repo.required_paths()))diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.pyindex c2b9146a..f6898e5a 100644--- a/tests/unittest/test_kit_commands.py+++ b/tests/unittest/test_kit_commands.py@@ -24,6 +24,7 @@ from mineru.kit.vlm_server import mlx_vlm_serverfrom mineru.parser.base import ParseResultfrom mineru.types import Block, BlockType, ContentType, Line, PageInfo, Spanfrom mineru.utils.image_payload import ImagePayloadCache+from mineru.utils.model_registry import MODEL_COMPLETE_MARKERrunner = CliRunner()@@ -269,6 +270,10 @@ def test_models_show_and_verify(tmp_path: Path, monkeypatch: Any) -> None:base_dir = tmp_path / "models"monkeypatch.setattr(models.config.model, "base_dir", str(base_dir))for repo in models.MODEL_REPOS:+ if repo.download_mode == "full":+ repo.local_dir().mkdir(parents=True, exist_ok=True)+ (repo.local_dir() / MODEL_COMPLETE_MARKER).touch()+ continuefor model_path in repo.required_paths():target = repo.local_dir() / model_path.relative_pathif Path(model_path.relative_path).suffix:@@ -276,7 +281,7 @@ def test_models_show_and_verify(tmp_path: Path, monkeypatch: Any) -> None:target.write_text("x", encoding="utf-8")continuetarget.mkdir(parents=True, exist_ok=True)- (target / "marker").write_text("x", encoding="utf-8")+ (target / MODEL_COMPLETE_MARKER).touch()show_result = runner.invoke(app, ["models", "show"])verify_result = runner.invoke(app, ["models", "verify"])diff --git a/tests/unittest/test_models_download_utils.py b/tests/unittest/test_models_download_utils.pyindex 743356ea..2e6cdadb 100644--- a/tests/unittest/test_models_download_utils.py+++ b/tests/unittest/test_models_download_utils.py@@ -1,11 +1,12 @@from __future__ import annotationsfrom pathlib import Path+from typing import Any, NoReturnimport pytestfrom mineru.utils import models_download_utils-from mineru.utils.model_registry import MINERU_2_5_PRO_2605_1_2B, ModelRepo+from mineru.utils.model_registry import MODEL_COMPLETE_MARKER, MINERU_2_5_PRO_2605_1_2B, ModelRepo, model_path_existsdef test_resolve_model_source_does_not_persist_env_auto(monkeypatch: pytest.MonkeyPatch) -> None:@@ -71,6 +72,7 @@ def test_download_model_repo_uses_required_path_patterns("repo": "partial-repo","patterns": ["models/weights", "models/weights/*"],}+ assert (repo.local_dir() / "models/weights" / MODEL_COMPLETE_MARKER).is_file()def test_download_model_repo_keeps_full_download_as_default(@@ -107,24 +109,334 @@ def test_download_model_repo_keeps_full_download_as_default("repo": "full-repo","patterns": None,}+ assert (repo.local_dir() / MODEL_COMPLETE_MARKER).read_bytes() == b""-def test_vlm_repo_verify_requires_core_model_files(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+def test_vlm_repo_verify_requires_root_completion_marker(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))repo_dir = MINERU_2_5_PRO_2605_1_2B.local_dir()repo_dir.mkdir(parents=True)- for filename in ("config.json", "preprocessor_config.json", "tokenizer_config.json", "tokenizer.json"):- (repo_dir / filename).write_text("{}", encoding="utf-8")+ assert MINERU_2_5_PRO_2605_1_2B.required_paths() == ()- missing_weight = models_download_utils.verify_model_repo(MINERU_2_5_PRO_2605_1_2B)+ unmarked = models_download_utils.verify_model_repo(MINERU_2_5_PRO_2605_1_2B)- assert missing_weight.ready is False- assert missing_weight.missing_paths == ["model.safetensors"]+ assert unmarked.ready is False+ assert unmarked.missing_paths == [MODEL_COMPLETE_MARKER]- (repo_dir / "model.safetensors").write_bytes(b"weights")+ (repo_dir / MODEL_COMPLETE_MARKER).touch()ready = models_download_utils.verify_model_repo(MINERU_2_5_PRO_2605_1_2B)assert ready.ready is Trueassert ready.missing_paths == []+++def test_model_path_exists_requires_completion_marker_for_directory(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"weights": "models/weights", "config": "config.json"},+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))++ weights_dir = repo.weights.local_path()+ weights_dir.mkdir(parents=True)+ (weights_dir / "model.bin").write_bytes(b"weights")+ assert model_path_exists(repo.weights) is False++ (weights_dir / MODEL_COMPLETE_MARKER).touch()+ assert model_path_exists(repo.weights) is True++ nested_weights = repo.weights.path("det")+ nested_weights.local_path().mkdir()+ (nested_weights.local_path() / "det.bin").write_bytes(b"weights")+ assert model_path_exists(nested_weights) is True++ config_path = repo.config.local_path()+ config_path.write_text("{}", encoding="utf-8")+ assert model_path_exists(repo.config) is True+++def test_model_path_ensure_reuses_completed_directory_without_resolving_source(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"weights": "models/weights"},+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))+ weights_dir = repo.weights.local_path()+ weights_dir.mkdir(parents=True)+ (weights_dir / "model.bin").write_bytes(b"weights")+ (weights_dir / MODEL_COMPLETE_MARKER).touch()++ def fail_resolve(*args: object, **kwargs: object) -> NoReturn:+ raise AssertionError("ready model paths must not resolve a remote source")++ monkeypatch.setattr(models_download_utils, "resolve_model_source", fail_resolve)++ assert repo.weights.ensure() == weights_dir+++def test_model_repo_ensure_reuses_completed_full_repo_without_resolving_source(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"config": "config.json", "weights": "model.bin"},+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))+ repo.local_dir().mkdir(parents=True)+ repo.config.local_path().write_text("{}", encoding="utf-8")+ repo.weights.local_path().write_bytes(b"weights")+ (repo.local_dir() / MODEL_COMPLETE_MARKER).touch()++ def fail_resolve(*args: object, **kwargs: object) -> NoReturn:+ raise AssertionError("ready model repos must not resolve a remote source")++ monkeypatch.setattr(models_download_utils, "resolve_model_source", fail_resolve)++ assert repo.ensure() == repo.local_dir()+++def test_model_path_ensure_repairs_unmarked_directory_and_writes_marker(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"weights": "models/weights"},+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))+ weights_dir = repo.weights.local_path()+ weights_dir.mkdir(parents=True)+ (weights_dir / "existing.bin").write_bytes(b"existing")+ calls = 0++ def fake_snapshot_download(model_source: str, target_repo: ModelRepo, patterns: list[str] | None) -> str:+ nonlocal calls+ calls += 1+ assert model_source == "modelscope"+ assert patterns == ["models/weights", "models/weights/*"]+ (weights_dir / "missing.bin").write_bytes(b"repaired")+ return str(target_repo.local_dir())++ monkeypatch.setattr(models_download_utils, "_snapshot_download", fake_snapshot_download)++ assert repo.weights.ensure(source="modelscope") == weights_dir+ assert calls == 1+ assert (weights_dir / MODEL_COMPLETE_MARKER).is_file()+++def test_local_source_rejects_unmarked_directory(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"weights": "models/weights"},+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))+ monkeypatch.setattr(models_download_utils.config.model, "source", "local")+ weights_dir = repo.weights.local_path()+ weights_dir.mkdir(parents=True)+ (weights_dir / "partial.bin").write_bytes(b"partial")++ with pytest.raises(FileNotFoundError, match="models/weights"):+ repo.weights.ensure()++ assert (weights_dir / MODEL_COMPLETE_MARKER).exists() is False+++def test_download_failure_removes_stale_directory_marker(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"weights": "models/weights"},+ download_mode="required_paths",+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))+ weights_dir = repo.weights.local_path()+ weights_dir.mkdir(parents=True)+ marker = weights_dir / MODEL_COMPLETE_MARKER+ marker.touch()++ def fail_snapshot_download(*args: object, **kwargs: object) -> NoReturn:+ raise RuntimeError("download interrupted")++ monkeypatch.setattr(models_download_utils, "_snapshot_download", fail_snapshot_download)++ with pytest.raises(RuntimeError, match="download interrupted"):+ models_download_utils.download_model_repo(repo, source="modelscope")++ assert marker.exists() is False+++def test_full_download_failure_removes_root_marker(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"config": "config.json"},+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))+ repo.local_dir().mkdir(parents=True)+ marker = repo.local_dir() / MODEL_COMPLETE_MARKER+ marker.touch()++ def fail_snapshot_download(*args: object, **kwargs: object) -> NoReturn:+ raise RuntimeError("download interrupted")++ monkeypatch.setattr(models_download_utils, "_snapshot_download", fail_snapshot_download)++ with pytest.raises(RuntimeError, match="download interrupted"):+ models_download_utils.download_model_repo(repo, source="modelscope")++ assert marker.exists() is False+++def test_nested_download_failure_invalidates_parent_directory_marker(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"weights": "models/weights"},+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))+ nested_weights = repo.weights.path("det")+ nested_weights.local_path().mkdir(parents=True)+ parent_marker = repo.weights.local_path() / MODEL_COMPLETE_MARKER+ parent_marker.touch()++ def fail_snapshot_download(*args: object, **kwargs: object) -> NoReturn:+ raise RuntimeError("download interrupted")++ monkeypatch.setattr(models_download_utils, "_snapshot_download", fail_snapshot_download)++ with pytest.raises(RuntimeError, match="download interrupted"):+ models_download_utils.download_model_files(repo, [nested_weights], source="modelscope")++ assert parent_marker.exists() is False+++def test_nested_download_success_restores_parent_directory_marker(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"weights": "models/weights"},+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))+ nested_weights = repo.weights.path("det")+ nested_weights.local_path().mkdir(parents=True)+ parent_marker = repo.weights.local_path() / MODEL_COMPLETE_MARKER+ parent_marker.touch()++ def fake_snapshot_download(model_source: str, target_repo: ModelRepo, patterns: list[str] | None) -> str:+ assert model_source == "modelscope"+ assert target_repo is repo+ assert patterns == ["models/weights/det", "models/weights/det/*"]+ (nested_weights.local_path() / "det.bin").write_bytes(b"weights")+ return str(repo.local_dir())++ monkeypatch.setattr(models_download_utils, "_snapshot_download", fake_snapshot_download)++ models_download_utils.download_model_files(repo, [nested_weights], source="modelscope")++ assert parent_marker.is_file()+ assert (nested_weights.local_path() / MODEL_COMPLETE_MARKER).is_file()+++def test_download_does_not_mark_metadata_only_directory(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"weights": "models/weights"},+ download_mode="required_paths",+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))+ weights_dir = repo.weights.local_path()++ def fake_snapshot_download(model_source: str, target_repo: ModelRepo, patterns: list[str] | None) -> str:+ assert model_source == "modelscope"+ assert target_repo is repo+ assert patterns == ["models/weights", "models/weights/*"]+ (weights_dir / ".cache/huggingface").mkdir(parents=True)+ (weights_dir / ".cache/huggingface/metadata").write_text("metadata", encoding="utf-8")+ (weights_dir / ".msc").write_text("metadata", encoding="utf-8")+ return str(repo.local_dir())++ monkeypatch.setattr(models_download_utils, "_snapshot_download", fake_snapshot_download)++ with pytest.raises(FileNotFoundError, match="models/weights"):+ models_download_utils.download_model_repo(repo, source="modelscope")++ assert (weights_dir / MODEL_COMPLETE_MARKER).exists() is False+++def test_huggingface_snapshot_rejects_missing_expected_files(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ repo = ModelRepo(+ name="repo",+ local_name="repo",+ repos={"huggingface": "owner/repo", "modelscope": "Owner/repo"},+ paths={"weights": "models/weights"},+ )+ monkeypatch.setattr(models_download_utils.config.model, "base_dir", str(tmp_path / "models"))++ class FakeApi:+ def list_repo_files(self, repo_id: str) -> list[str]:+ assert repo_id == "owner/repo"+ return ["models/weights/config.json", "models/weights/model.bin"]++ monkeypatch.setattr(models_download_utils, "HfApi", FakeApi)++ def fake_hf_snapshot_download(repo_id: str, **kwargs: Any) -> str:+ assert repo_id == "owner/repo"+ target = Path(kwargs["local_dir"]) / "models/weights"+ target.mkdir(parents=True)+ (target / "config.json").write_text("{}", encoding="utf-8")+ return kwargs["local_dir"]++ monkeypatch.setattr(models_download_utils, "hf_snapshot_download", fake_hf_snapshot_download)++ with pytest.raises(FileNotFoundError, match="models/weights/model.bin"):+ models_download_utils._snapshot_download(+ "huggingface",+ repo,+ ["models/weights", "models/weights/*"],+ )