Download tools/oxt_hf_upload_cache.py from Alan0928/IDEALFT_OXT: direct link, hf CLI and curl.
- Browser
- Download file 6.55 kB
-
https://huggingface.co/datasets/Alan0928/IDEALFT_OXT/resolve/main/tools/oxt_hf_upload_cache.py
- Command line
-
hf download hf://datasets/Alan0928/IDEALFT_OXT/tools/oxt_hf_upload_cache.py
-
curl -L -o oxt_hf_upload_cache.py https://huggingface.co/datasets/Alan0928/IDEALFT_OXT/resolve/main/tools/oxt_hf_upload_cache.py
6.55 kB
| """Seed isolated HF upload metadata with already verified file hashes. | |
| Importing this module does not import Hugging Face. The caller must isolate its | |
| HF environment and verify the staged bytes before calling the public function. | |
| Only the staging folder's ``.cache/huggingface`` tree is written; no API calls, | |
| credentials, or global Hugging Face configuration are used. | |
| """ | |
| import os | |
| from pathlib import Path, PurePosixPath | |
| import re | |
| SUPPORTED_HF_VERSION = "1.3.0" | |
| class UploadCacheError(RuntimeError): | |
| """A sanitized, local explanation suitable for the upload script.""" | |
| def _helpers(): | |
| # This private metadata format is pinned deliberately. A future SDK must be | |
| # reviewed before its resumable state can safely be rewritten. | |
| try: | |
| from huggingface_hub import __version__ | |
| from huggingface_hub._local_folder import ( | |
| LocalUploadFileMetadata, | |
| get_local_upload_paths, | |
| read_upload_metadata, | |
| ) | |
| except ImportError: | |
| raise UploadCacheError( | |
| "Hugging Face upload-cache helpers are unavailable; " | |
| "use huggingface_hub==1.3.0." | |
| ) from None | |
| if __version__ != SUPPORTED_HF_VERSION: | |
| raise UploadCacheError( | |
| "Upload-cache integrity support requires huggingface_hub==1.3.0." | |
| ) | |
| if not all(callable(value) for value in ( | |
| LocalUploadFileMetadata, get_local_upload_paths, read_upload_metadata)): | |
| raise UploadCacheError("Hugging Face upload-cache helpers are incompatible.") | |
| return LocalUploadFileMetadata, get_local_upload_paths, read_upload_metadata | |
| def _validate_paths(folder, files): | |
| """Check the complete inventory before any cache directories are created.""" | |
| if not folder.is_dir(): | |
| raise UploadCacheError("Verified staging folder is unavailable.") | |
| for name, expected in files.items(): | |
| if not isinstance(name, str) or not name or "\\" in name: | |
| raise UploadCacheError("Unsafe path in verified upload inventory.") | |
| relative = PurePosixPath(name) | |
| if (relative.is_absolute() or str(relative) != name | |
| or any(part in ("", ".", "..") for part in relative.parts) | |
| or relative.parts[0] in (".cache", ".git")): | |
| raise UploadCacheError("Unsafe path in verified upload inventory.") | |
| if (not isinstance(expected, dict) | |
| or type(expected.get("bytes")) is not int | |
| or expected["bytes"] < 0 | |
| or not isinstance(expected.get("sha256"), str) | |
| or re.fullmatch(r"[0-9a-f]{64}", expected["sha256"]) is None): | |
| raise UploadCacheError("Invalid verified size or SHA256 for upload cache.") | |
| candidate = folder | |
| for part in relative.parts: | |
| candidate = candidate / part | |
| if candidate.is_symlink(): | |
| raise UploadCacheError("Staged files must not use symbolic links.") | |
| if not candidate.is_file() or candidate.stat().st_size != expected["bytes"]: | |
| raise UploadCacheError("Staged file size changed before upload-cache preparation.") | |
| cache = folder / ".cache" | |
| if cache.is_symlink(): | |
| raise UploadCacheError("Upload cache must not use symbolic links.") | |
| if cache.exists(): | |
| if not cache.is_dir(): | |
| raise UploadCacheError("Upload cache path must be a directory.") | |
| for current, directories, names in os.walk(cache, followlinks=False): | |
| if any((Path(current) / name).is_symlink() for name in directories + names): | |
| raise UploadCacheError("Upload cache must not use symbolic links.") | |
| def prepare_hf_upload_metadata(checked, remote_names): | |
| """Return counts after seeding verified hashes into HF 1.3.0 upload state. | |
| ``checked`` has ``folder`` and ``files`` (relative name -> ``bytes`` and | |
| ``sha256``). The caller has verified those exact bytes. ``remote_names`` | |
| contains existing files already checked against that inventory, including | |
| bootstrap files committed by this run. Matching pending LFS-upload state is | |
| preserved; conflicting hashes/sizes discard all old per-file state. A cached | |
| committed flag is cleared if its file is absent from the verified remote. | |
| This function does not authenticate, contact the network, or inspect any | |
| global token. Call it only after process-local HF environment isolation. | |
| """ | |
| folder = Path(checked["folder"]).resolve(strict=True) | |
| files = checked["files"] | |
| remote_names = set(remote_names) | |
| _validate_paths(folder, files) | |
| Metadata, get_paths, read_metadata = _helpers() | |
| counts = {"files": len(files), "saved": 0, "seeded": 0, | |
| "reset_conflicting": 0, "reset_inconsistent": 0, | |
| "preserved_uploaded": 0, "cleared_committed": 0} | |
| required = ("size", "sha256", "upload_mode", "should_ignore", "remote_oid", | |
| "is_uploaded", "is_committed", "save") | |
| for name in sorted(files): | |
| expected = files[name] | |
| metadata = read_metadata(folder, name) | |
| if not all(hasattr(metadata, attr) for attr in required) or not callable(metadata.save): | |
| raise UploadCacheError("Hugging Face upload metadata has an unsupported structure.") | |
| if metadata.size != expected["bytes"] or ( | |
| metadata.sha256 is not None and metadata.sha256 != expected["sha256"]): | |
| metadata = Metadata(size=expected["bytes"]) | |
| counts["reset_conflicting"] += 1 | |
| elif metadata.sha256 is None: | |
| # Uploaded/committed flags or a mode without a trustworthy hash are | |
| # not resumable evidence. A brand-new record also takes this path. | |
| if (metadata.is_uploaded or metadata.is_committed | |
| or metadata.upload_mode is not None or metadata.remote_oid is not None): | |
| counts["reset_inconsistent"] += 1 | |
| metadata = Metadata(size=expected["bytes"]) | |
| if metadata.sha256 is None: | |
| counts["seeded"] += 1 | |
| metadata.size = expected["bytes"] | |
| metadata.sha256 = expected["sha256"] | |
| metadata.should_ignore = False | |
| if metadata.is_uploaded and metadata.upload_mode == "lfs": | |
| counts["preserved_uploaded"] += 1 | |
| else: | |
| metadata.is_uploaded = False | |
| if metadata.is_committed and name not in remote_names: | |
| metadata.is_committed = False | |
| counts["cleared_committed"] += 1 | |
| metadata.save(get_paths(folder, name)) | |
| counts["saved"] += 1 | |
| return counts | |