Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/METADATA +324 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/WHEEL +5 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/entry_points.txt +7 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/licenses/LICENSE +201 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/top_level.txt +1 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/__init__.py +1717 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_buckets.py +1193 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_commit_api.py +976 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_commit_scheduler.py +353 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_dataset_viewer.py +172 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_eval_results.py +211 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_inference_endpoints.py +418 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_jobs_api.py +410 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_local_folder.py +473 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_login.py +494 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_oauth.py +460 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_snapshot_download.py +471 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_space_api.py +251 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_tensorboard_logger.py +189 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_upload_large_folder.py +766 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_webhooks_payload.py +136 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_webhooks_server.py +376 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/auth.py +165 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/buckets.py +1082 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/cache.py +812 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/collections.py +331 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/datasets.py +175 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/deprecated_cli.py +35 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/discussions.py +595 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/download.py +224 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/extensions.py +620 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/hf.py +127 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/inference_endpoints.py +463 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/jobs.py +1150 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/lfs.py +175 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/models.py +133 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/papers.py +203 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/repo_files.py +86 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/repos.py +524 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/skills.py +446 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/spaces.py +437 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/system.py +28 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/upload.py +300 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/upload_large_folder.py +130 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/webhooks.py +310 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/community.py +363 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/constants.py +291 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/dataclasses.py +684 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/errors.py +473 -0
- .cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/fastai_utils.py +414 -0
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/METADATA
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: huggingface_hub
|
| 3 |
+
Version: 1.10.1
|
| 4 |
+
Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hub
|
| 5 |
+
Home-page: https://github.com/huggingface/huggingface_hub
|
| 6 |
+
Author: Hugging Face, Inc.
|
| 7 |
+
Author-email: julien@huggingface.co
|
| 8 |
+
License: Apache-2.0
|
| 9 |
+
Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-models
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: Intended Audience :: Education
|
| 12 |
+
Classifier: Intended Audience :: Science/Research
|
| 13 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 14 |
+
Classifier: Operating System :: OS Independent
|
| 15 |
+
Classifier: Programming Language :: Python :: 3
|
| 16 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 22 |
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
| 23 |
+
Requires-Python: >=3.10.0
|
| 24 |
+
Description-Content-Type: text/markdown
|
| 25 |
+
License-File: LICENSE
|
| 26 |
+
Requires-Dist: filelock>=3.10.0
|
| 27 |
+
Requires-Dist: fsspec>=2023.5.0
|
| 28 |
+
Requires-Dist: hf-xet<2.0.0,>=1.4.3; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64"
|
| 29 |
+
Requires-Dist: httpx<1,>=0.23.0
|
| 30 |
+
Requires-Dist: packaging>=20.9
|
| 31 |
+
Requires-Dist: pyyaml>=5.1
|
| 32 |
+
Requires-Dist: tqdm>=4.42.1
|
| 33 |
+
Requires-Dist: typer
|
| 34 |
+
Requires-Dist: typing-extensions>=4.1.0
|
| 35 |
+
Provides-Extra: oauth
|
| 36 |
+
Requires-Dist: authlib>=1.3.2; extra == "oauth"
|
| 37 |
+
Requires-Dist: fastapi; extra == "oauth"
|
| 38 |
+
Requires-Dist: httpx; extra == "oauth"
|
| 39 |
+
Requires-Dist: itsdangerous; extra == "oauth"
|
| 40 |
+
Provides-Extra: torch
|
| 41 |
+
Requires-Dist: torch; extra == "torch"
|
| 42 |
+
Requires-Dist: safetensors[torch]; extra == "torch"
|
| 43 |
+
Provides-Extra: fastai
|
| 44 |
+
Requires-Dist: toml; extra == "fastai"
|
| 45 |
+
Requires-Dist: fastai>=2.4; extra == "fastai"
|
| 46 |
+
Requires-Dist: fastcore>=1.3.27; extra == "fastai"
|
| 47 |
+
Provides-Extra: hf-xet
|
| 48 |
+
Requires-Dist: hf-xet<2.0.0,>=1.4.3; extra == "hf-xet"
|
| 49 |
+
Provides-Extra: mcp
|
| 50 |
+
Requires-Dist: mcp>=1.8.0; extra == "mcp"
|
| 51 |
+
Provides-Extra: testing
|
| 52 |
+
Requires-Dist: authlib>=1.3.2; extra == "testing"
|
| 53 |
+
Requires-Dist: fastapi; extra == "testing"
|
| 54 |
+
Requires-Dist: httpx; extra == "testing"
|
| 55 |
+
Requires-Dist: itsdangerous; extra == "testing"
|
| 56 |
+
Requires-Dist: jedi; extra == "testing"
|
| 57 |
+
Requires-Dist: Jinja2; extra == "testing"
|
| 58 |
+
Requires-Dist: pytest>=8.4.2; extra == "testing"
|
| 59 |
+
Requires-Dist: pytest-cov; extra == "testing"
|
| 60 |
+
Requires-Dist: pytest-env; extra == "testing"
|
| 61 |
+
Requires-Dist: pytest-xdist; extra == "testing"
|
| 62 |
+
Requires-Dist: pytest-vcr; extra == "testing"
|
| 63 |
+
Requires-Dist: pytest-asyncio; extra == "testing"
|
| 64 |
+
Requires-Dist: pytest-rerunfailures<16.0; extra == "testing"
|
| 65 |
+
Requires-Dist: pytest-mock; extra == "testing"
|
| 66 |
+
Requires-Dist: urllib3<2.0; extra == "testing"
|
| 67 |
+
Requires-Dist: soundfile; extra == "testing"
|
| 68 |
+
Requires-Dist: Pillow; extra == "testing"
|
| 69 |
+
Requires-Dist: numpy; extra == "testing"
|
| 70 |
+
Requires-Dist: duckdb; extra == "testing"
|
| 71 |
+
Requires-Dist: fastapi; extra == "testing"
|
| 72 |
+
Provides-Extra: gradio
|
| 73 |
+
Requires-Dist: gradio>=5.0.0; extra == "gradio"
|
| 74 |
+
Requires-Dist: requests; extra == "gradio"
|
| 75 |
+
Provides-Extra: typing
|
| 76 |
+
Requires-Dist: typing-extensions>=4.8.0; extra == "typing"
|
| 77 |
+
Requires-Dist: types-PyYAML; extra == "typing"
|
| 78 |
+
Requires-Dist: types-simplejson; extra == "typing"
|
| 79 |
+
Requires-Dist: types-toml; extra == "typing"
|
| 80 |
+
Requires-Dist: types-tqdm; extra == "typing"
|
| 81 |
+
Requires-Dist: types-urllib3; extra == "typing"
|
| 82 |
+
Provides-Extra: quality
|
| 83 |
+
Requires-Dist: ruff>=0.9.0; extra == "quality"
|
| 84 |
+
Requires-Dist: mypy==1.15.0; extra == "quality"
|
| 85 |
+
Requires-Dist: libcst>=1.4.0; extra == "quality"
|
| 86 |
+
Requires-Dist: ty; extra == "quality"
|
| 87 |
+
Provides-Extra: all
|
| 88 |
+
Requires-Dist: authlib>=1.3.2; extra == "all"
|
| 89 |
+
Requires-Dist: fastapi; extra == "all"
|
| 90 |
+
Requires-Dist: httpx; extra == "all"
|
| 91 |
+
Requires-Dist: itsdangerous; extra == "all"
|
| 92 |
+
Requires-Dist: jedi; extra == "all"
|
| 93 |
+
Requires-Dist: Jinja2; extra == "all"
|
| 94 |
+
Requires-Dist: pytest>=8.4.2; extra == "all"
|
| 95 |
+
Requires-Dist: pytest-cov; extra == "all"
|
| 96 |
+
Requires-Dist: pytest-env; extra == "all"
|
| 97 |
+
Requires-Dist: pytest-xdist; extra == "all"
|
| 98 |
+
Requires-Dist: pytest-vcr; extra == "all"
|
| 99 |
+
Requires-Dist: pytest-asyncio; extra == "all"
|
| 100 |
+
Requires-Dist: pytest-rerunfailures<16.0; extra == "all"
|
| 101 |
+
Requires-Dist: pytest-mock; extra == "all"
|
| 102 |
+
Requires-Dist: urllib3<2.0; extra == "all"
|
| 103 |
+
Requires-Dist: soundfile; extra == "all"
|
| 104 |
+
Requires-Dist: Pillow; extra == "all"
|
| 105 |
+
Requires-Dist: numpy; extra == "all"
|
| 106 |
+
Requires-Dist: duckdb; extra == "all"
|
| 107 |
+
Requires-Dist: fastapi; extra == "all"
|
| 108 |
+
Requires-Dist: ruff>=0.9.0; extra == "all"
|
| 109 |
+
Requires-Dist: mypy==1.15.0; extra == "all"
|
| 110 |
+
Requires-Dist: libcst>=1.4.0; extra == "all"
|
| 111 |
+
Requires-Dist: ty; extra == "all"
|
| 112 |
+
Requires-Dist: typing-extensions>=4.8.0; extra == "all"
|
| 113 |
+
Requires-Dist: types-PyYAML; extra == "all"
|
| 114 |
+
Requires-Dist: types-simplejson; extra == "all"
|
| 115 |
+
Requires-Dist: types-toml; extra == "all"
|
| 116 |
+
Requires-Dist: types-tqdm; extra == "all"
|
| 117 |
+
Requires-Dist: types-urllib3; extra == "all"
|
| 118 |
+
Provides-Extra: dev
|
| 119 |
+
Requires-Dist: authlib>=1.3.2; extra == "dev"
|
| 120 |
+
Requires-Dist: fastapi; extra == "dev"
|
| 121 |
+
Requires-Dist: httpx; extra == "dev"
|
| 122 |
+
Requires-Dist: itsdangerous; extra == "dev"
|
| 123 |
+
Requires-Dist: jedi; extra == "dev"
|
| 124 |
+
Requires-Dist: Jinja2; extra == "dev"
|
| 125 |
+
Requires-Dist: pytest>=8.4.2; extra == "dev"
|
| 126 |
+
Requires-Dist: pytest-cov; extra == "dev"
|
| 127 |
+
Requires-Dist: pytest-env; extra == "dev"
|
| 128 |
+
Requires-Dist: pytest-xdist; extra == "dev"
|
| 129 |
+
Requires-Dist: pytest-vcr; extra == "dev"
|
| 130 |
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
| 131 |
+
Requires-Dist: pytest-rerunfailures<16.0; extra == "dev"
|
| 132 |
+
Requires-Dist: pytest-mock; extra == "dev"
|
| 133 |
+
Requires-Dist: urllib3<2.0; extra == "dev"
|
| 134 |
+
Requires-Dist: soundfile; extra == "dev"
|
| 135 |
+
Requires-Dist: Pillow; extra == "dev"
|
| 136 |
+
Requires-Dist: numpy; extra == "dev"
|
| 137 |
+
Requires-Dist: duckdb; extra == "dev"
|
| 138 |
+
Requires-Dist: fastapi; extra == "dev"
|
| 139 |
+
Requires-Dist: ruff>=0.9.0; extra == "dev"
|
| 140 |
+
Requires-Dist: mypy==1.15.0; extra == "dev"
|
| 141 |
+
Requires-Dist: libcst>=1.4.0; extra == "dev"
|
| 142 |
+
Requires-Dist: ty; extra == "dev"
|
| 143 |
+
Requires-Dist: typing-extensions>=4.8.0; extra == "dev"
|
| 144 |
+
Requires-Dist: types-PyYAML; extra == "dev"
|
| 145 |
+
Requires-Dist: types-simplejson; extra == "dev"
|
| 146 |
+
Requires-Dist: types-toml; extra == "dev"
|
| 147 |
+
Requires-Dist: types-tqdm; extra == "dev"
|
| 148 |
+
Requires-Dist: types-urllib3; extra == "dev"
|
| 149 |
+
Dynamic: author
|
| 150 |
+
Dynamic: author-email
|
| 151 |
+
Dynamic: classifier
|
| 152 |
+
Dynamic: description
|
| 153 |
+
Dynamic: description-content-type
|
| 154 |
+
Dynamic: home-page
|
| 155 |
+
Dynamic: keywords
|
| 156 |
+
Dynamic: license
|
| 157 |
+
Dynamic: license-file
|
| 158 |
+
Dynamic: provides-extra
|
| 159 |
+
Dynamic: requires-dist
|
| 160 |
+
Dynamic: requires-python
|
| 161 |
+
Dynamic: summary
|
| 162 |
+
|
| 163 |
+
<p align="center">
|
| 164 |
+
<picture>
|
| 165 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub-dark.svg">
|
| 166 |
+
<source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg">
|
| 167 |
+
<img alt="huggingface_hub library logo" src="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg" width="352" height="59" style="max-width: 100%">
|
| 168 |
+
</picture>
|
| 169 |
+
<br/>
|
| 170 |
+
<br/>
|
| 171 |
+
</p>
|
| 172 |
+
|
| 173 |
+
<p align="center">
|
| 174 |
+
<i>The official Python client for the Huggingface Hub.</i>
|
| 175 |
+
</p>
|
| 176 |
+
|
| 177 |
+
<p align="center">
|
| 178 |
+
<a href="https://huggingface.co/docs/huggingface_hub/en/index"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/huggingface_hub/index.svg?down_color=red&down_message=offline&up_message=online&label=doc"></a>
|
| 179 |
+
<a href="https://github.com/huggingface/huggingface_hub/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/huggingface_hub.svg"></a>
|
| 180 |
+
<a href="https://github.com/huggingface/huggingface_hub"><img alt="PyPi version" src="https://img.shields.io/pypi/pyversions/huggingface_hub.svg"></a>
|
| 181 |
+
<a href="https://pypi.org/project/huggingface-hub"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/huggingface_hub"></a>
|
| 182 |
+
<a href="https://codecov.io/gh/huggingface/huggingface_hub"><img alt="Code coverage" src="https://codecov.io/gh/huggingface/huggingface_hub/branch/main/graph/badge.svg?token=RXP95LE2XL"></a>
|
| 183 |
+
</p>
|
| 184 |
+
|
| 185 |
+
<h4 align="center">
|
| 186 |
+
<p>
|
| 187 |
+
<b>English</b> |
|
| 188 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_de.md">Deutsch</a> |
|
| 189 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_fr.md">Français</a> |
|
| 190 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_hi.md">हिंदी</a> |
|
| 191 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_ko.md">한국어</a> |
|
| 192 |
+
<a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_cn.md">中文 (简体)</a>
|
| 193 |
+
<p>
|
| 194 |
+
</h4>
|
| 195 |
+
|
| 196 |
+
---
|
| 197 |
+
|
| 198 |
+
**Documentation**: <a href="https://hf.co/docs/huggingface_hub" target="_blank">https://hf.co/docs/huggingface_hub</a>
|
| 199 |
+
|
| 200 |
+
**Source Code**: <a href="https://github.com/huggingface/huggingface_hub" target="_blank">https://github.com/huggingface/huggingface_hub</a>
|
| 201 |
+
|
| 202 |
+
---
|
| 203 |
+
|
| 204 |
+
## Welcome to the huggingface_hub library
|
| 205 |
+
|
| 206 |
+
The `huggingface_hub` library allows you to interact with the [Hugging Face Hub](https://huggingface.co/), a platform democratizing open-source Machine Learning for creators and collaborators. Discover pre-trained models and datasets for your projects or play with the thousands of machine learning apps hosted on the Hub. You can also create and share your own models, datasets and demos with the community. The `huggingface_hub` library provides a simple way to do all these things with Python.
|
| 207 |
+
|
| 208 |
+
## Key features
|
| 209 |
+
|
| 210 |
+
- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub.
|
| 211 |
+
- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub.
|
| 212 |
+
- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository).
|
| 213 |
+
- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models.
|
| 214 |
+
- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces.
|
| 215 |
+
- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models.
|
| 216 |
+
- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments.
|
| 217 |
+
|
| 218 |
+
## Installation
|
| 219 |
+
|
| 220 |
+
Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/):
|
| 221 |
+
|
| 222 |
+
```bash
|
| 223 |
+
pip install huggingface_hub
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
If you prefer, you can also install it with [conda](https://huggingface.co/docs/huggingface_hub/en/installation#install-with-conda).
|
| 227 |
+
|
| 228 |
+
In order to keep the package minimal by default, `huggingface_hub` comes with optional dependencies useful for some use cases. For example, if you want to use the MCP module, run:
|
| 229 |
+
|
| 230 |
+
```bash
|
| 231 |
+
pip install "huggingface_hub[mcp]"
|
| 232 |
+
```
|
| 233 |
+
|
| 234 |
+
To learn more installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation).
|
| 235 |
+
|
| 236 |
+
## Quick start
|
| 237 |
+
|
| 238 |
+
### Download files
|
| 239 |
+
|
| 240 |
+
Download a single file
|
| 241 |
+
|
| 242 |
+
```py
|
| 243 |
+
from huggingface_hub import hf_hub_download
|
| 244 |
+
|
| 245 |
+
hf_hub_download(repo_id="tiiuae/falcon-7b-instruct", filename="config.json")
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
Or an entire repository
|
| 249 |
+
|
| 250 |
+
```py
|
| 251 |
+
from huggingface_hub import snapshot_download
|
| 252 |
+
|
| 253 |
+
snapshot_download("stabilityai/stable-diffusion-2-1")
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache).
|
| 257 |
+
|
| 258 |
+
### Login
|
| 259 |
+
|
| 260 |
+
The Hugging Face Hub uses tokens to authenticate applications (see [docs](https://huggingface.co/docs/hub/security-tokens)). To log in your machine, run the following CLI:
|
| 261 |
+
|
| 262 |
+
```bash
|
| 263 |
+
hf auth login
|
| 264 |
+
# or using an environment variable
|
| 265 |
+
hf auth login --token $HUGGINGFACE_TOKEN
|
| 266 |
+
```
|
| 267 |
+
|
| 268 |
+
### Create a repository
|
| 269 |
+
|
| 270 |
+
```py
|
| 271 |
+
from huggingface_hub import create_repo
|
| 272 |
+
|
| 273 |
+
create_repo(repo_id="super-cool-model")
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
### Upload files
|
| 277 |
+
|
| 278 |
+
Upload a single file
|
| 279 |
+
|
| 280 |
+
```py
|
| 281 |
+
from huggingface_hub import upload_file
|
| 282 |
+
|
| 283 |
+
upload_file(
|
| 284 |
+
path_or_fileobj="/home/lysandre/dummy-test/README.md",
|
| 285 |
+
path_in_repo="README.md",
|
| 286 |
+
repo_id="lysandre/test-model",
|
| 287 |
+
)
|
| 288 |
+
```
|
| 289 |
+
|
| 290 |
+
Or an entire folder
|
| 291 |
+
|
| 292 |
+
```py
|
| 293 |
+
from huggingface_hub import upload_folder
|
| 294 |
+
|
| 295 |
+
upload_folder(
|
| 296 |
+
folder_path="/path/to/local/space",
|
| 297 |
+
repo_id="username/my-cool-space",
|
| 298 |
+
repo_type="space",
|
| 299 |
+
)
|
| 300 |
+
```
|
| 301 |
+
|
| 302 |
+
For details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload).
|
| 303 |
+
|
| 304 |
+
## Integrating to the Hub.
|
| 305 |
+
|
| 306 |
+
We're partnering with cool open source ML libraries to provide free model hosting and versioning. You can find the existing integrations [here](https://huggingface.co/docs/hub/libraries).
|
| 307 |
+
|
| 308 |
+
The advantages are:
|
| 309 |
+
|
| 310 |
+
- Free model or dataset hosting for libraries and their users.
|
| 311 |
+
- Built-in file versioning, even with very large files, thanks to a git-based approach.
|
| 312 |
+
- In-browser widgets to play with the uploaded models.
|
| 313 |
+
- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable.
|
| 314 |
+
- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe.
|
| 315 |
+
- Usage stats and more features to come.
|
| 316 |
+
|
| 317 |
+
If you would like to integrate your library, feel free to open an issue to begin the discussion. We wrote a [step-by-step guide](https://huggingface.co/docs/hub/adding-a-library) with ❤️ showing how to do this integration.
|
| 318 |
+
|
| 319 |
+
## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️
|
| 320 |
+
|
| 321 |
+
Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community.
|
| 322 |
+
Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community.
|
| 323 |
+
We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarize
|
| 324 |
+
how to get started to contribute to this repository.
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (79.0.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
hf = huggingface_hub.cli.hf:main
|
| 3 |
+
huggingface-cli = huggingface_hub.cli.deprecated_cli:main
|
| 4 |
+
tiny-agents = huggingface_hub.inference._mcp.cli:app
|
| 5 |
+
|
| 6 |
+
[fsspec.specs]
|
| 7 |
+
hf = huggingface_hub.HfFileSystem
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub-1.10.1.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# ***********
|
| 16 |
+
# `huggingface_hub` init has 2 modes:
|
| 17 |
+
# - Normal usage:
|
| 18 |
+
# If imported to use it, all modules and functions are lazy-loaded. This means
|
| 19 |
+
# they exist at top level in module but are imported only the first time they are
|
| 20 |
+
# used. This way, `from huggingface_hub import something` will import `something`
|
| 21 |
+
# quickly without the hassle of importing all the features from `huggingface_hub`.
|
| 22 |
+
# - Static check:
|
| 23 |
+
# If statically analyzed, all modules and functions are loaded normally. This way
|
| 24 |
+
# static typing check works properly as well as autocomplete in text editors and
|
| 25 |
+
# IDEs.
|
| 26 |
+
#
|
| 27 |
+
# The static model imports are done inside the `if TYPE_CHECKING:` statement at
|
| 28 |
+
# the bottom of this file. Since module/functions imports are duplicated, it is
|
| 29 |
+
# mandatory to make sure to add them twice when adding one. This is checked in the
|
| 30 |
+
# `make quality` command.
|
| 31 |
+
#
|
| 32 |
+
# To update the static imports, please run the following command and commit the changes.
|
| 33 |
+
# ```
|
| 34 |
+
# # Use script
|
| 35 |
+
# python utils/check_static_imports.py --update-file
|
| 36 |
+
#
|
| 37 |
+
# # Or run style on codebase
|
| 38 |
+
# make style
|
| 39 |
+
# ```
|
| 40 |
+
#
|
| 41 |
+
# ***********
|
| 42 |
+
# Lazy loader vendored from https://github.com/scientific-python/lazy_loader
|
| 43 |
+
import importlib
|
| 44 |
+
import os
|
| 45 |
+
import sys
|
| 46 |
+
from typing import TYPE_CHECKING
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
__version__ = "1.10.1"
|
| 50 |
+
|
| 51 |
+
# Alphabetical order of definitions is ensured in tests
|
| 52 |
+
# WARNING: any comment added in this dictionary definition will be lost when
|
| 53 |
+
# re-generating the file !
|
| 54 |
+
_SUBMOD_ATTRS = {
|
| 55 |
+
"_buckets": [
|
| 56 |
+
"BucketFile",
|
| 57 |
+
"BucketFileMetadata",
|
| 58 |
+
"BucketFolder",
|
| 59 |
+
"BucketInfo",
|
| 60 |
+
"BucketUrl",
|
| 61 |
+
"SyncOperation",
|
| 62 |
+
"SyncPlan",
|
| 63 |
+
],
|
| 64 |
+
"_commit_scheduler": [
|
| 65 |
+
"CommitScheduler",
|
| 66 |
+
],
|
| 67 |
+
"_eval_results": [
|
| 68 |
+
"EvalResultEntry",
|
| 69 |
+
"eval_result_entries_to_yaml",
|
| 70 |
+
"parse_eval_result_entries",
|
| 71 |
+
],
|
| 72 |
+
"_inference_endpoints": [
|
| 73 |
+
"InferenceEndpoint",
|
| 74 |
+
"InferenceEndpointError",
|
| 75 |
+
"InferenceEndpointStatus",
|
| 76 |
+
"InferenceEndpointTimeoutError",
|
| 77 |
+
"InferenceEndpointType",
|
| 78 |
+
],
|
| 79 |
+
"_jobs_api": [
|
| 80 |
+
"JobAccelerator",
|
| 81 |
+
"JobHardware",
|
| 82 |
+
"JobInfo",
|
| 83 |
+
"JobOwner",
|
| 84 |
+
"JobStage",
|
| 85 |
+
"JobStatus",
|
| 86 |
+
],
|
| 87 |
+
"_login": [
|
| 88 |
+
"auth_list",
|
| 89 |
+
"auth_switch",
|
| 90 |
+
"interpreter_login",
|
| 91 |
+
"login",
|
| 92 |
+
"logout",
|
| 93 |
+
"notebook_login",
|
| 94 |
+
],
|
| 95 |
+
"_oauth": [
|
| 96 |
+
"OAuthInfo",
|
| 97 |
+
"OAuthOrgInfo",
|
| 98 |
+
"OAuthUserInfo",
|
| 99 |
+
"attach_huggingface_oauth",
|
| 100 |
+
"parse_huggingface_oauth",
|
| 101 |
+
],
|
| 102 |
+
"_snapshot_download": [
|
| 103 |
+
"snapshot_download",
|
| 104 |
+
],
|
| 105 |
+
"_space_api": [
|
| 106 |
+
"SpaceHardware",
|
| 107 |
+
"SpaceRuntime",
|
| 108 |
+
"SpaceStage",
|
| 109 |
+
"SpaceStorage",
|
| 110 |
+
"SpaceVariable",
|
| 111 |
+
"Volume",
|
| 112 |
+
],
|
| 113 |
+
"_tensorboard_logger": [
|
| 114 |
+
"HFSummaryWriter",
|
| 115 |
+
],
|
| 116 |
+
"_webhooks_payload": [
|
| 117 |
+
"WebhookPayload",
|
| 118 |
+
"WebhookPayloadComment",
|
| 119 |
+
"WebhookPayloadDiscussion",
|
| 120 |
+
"WebhookPayloadDiscussionChanges",
|
| 121 |
+
"WebhookPayloadEvent",
|
| 122 |
+
"WebhookPayloadMovedTo",
|
| 123 |
+
"WebhookPayloadRepo",
|
| 124 |
+
"WebhookPayloadUrl",
|
| 125 |
+
"WebhookPayloadWebhook",
|
| 126 |
+
],
|
| 127 |
+
"_webhooks_server": [
|
| 128 |
+
"WebhooksServer",
|
| 129 |
+
"webhook_endpoint",
|
| 130 |
+
],
|
| 131 |
+
"cli._cli_utils": [
|
| 132 |
+
"check_cli_update",
|
| 133 |
+
"typer_factory",
|
| 134 |
+
],
|
| 135 |
+
"community": [
|
| 136 |
+
"Discussion",
|
| 137 |
+
"DiscussionComment",
|
| 138 |
+
"DiscussionCommit",
|
| 139 |
+
"DiscussionEvent",
|
| 140 |
+
"DiscussionStatusChange",
|
| 141 |
+
"DiscussionTitleChange",
|
| 142 |
+
"DiscussionWithDetails",
|
| 143 |
+
],
|
| 144 |
+
"constants": [
|
| 145 |
+
"CONFIG_NAME",
|
| 146 |
+
"FLAX_WEIGHTS_NAME",
|
| 147 |
+
"HUGGINGFACE_CO_URL_HOME",
|
| 148 |
+
"HUGGINGFACE_CO_URL_TEMPLATE",
|
| 149 |
+
"PYTORCH_WEIGHTS_NAME",
|
| 150 |
+
"REPO_TYPE_DATASET",
|
| 151 |
+
"REPO_TYPE_MODEL",
|
| 152 |
+
"REPO_TYPE_SPACE",
|
| 153 |
+
"TF2_WEIGHTS_NAME",
|
| 154 |
+
"TF_WEIGHTS_NAME",
|
| 155 |
+
"is_offline_mode",
|
| 156 |
+
],
|
| 157 |
+
"fastai_utils": [
|
| 158 |
+
"_save_pretrained_fastai",
|
| 159 |
+
"from_pretrained_fastai",
|
| 160 |
+
"push_to_hub_fastai",
|
| 161 |
+
],
|
| 162 |
+
"file_download": [
|
| 163 |
+
"DryRunFileInfo",
|
| 164 |
+
"HfFileMetadata",
|
| 165 |
+
"_CACHED_NO_EXIST",
|
| 166 |
+
"get_hf_file_metadata",
|
| 167 |
+
"hf_hub_download",
|
| 168 |
+
"hf_hub_url",
|
| 169 |
+
"try_to_load_from_cache",
|
| 170 |
+
],
|
| 171 |
+
"hf_api": [
|
| 172 |
+
"Collection",
|
| 173 |
+
"CollectionItem",
|
| 174 |
+
"CommitInfo",
|
| 175 |
+
"CommitOperation",
|
| 176 |
+
"CommitOperationAdd",
|
| 177 |
+
"CommitOperationCopy",
|
| 178 |
+
"CommitOperationDelete",
|
| 179 |
+
"DatasetInfo",
|
| 180 |
+
"DatasetLeaderboardEntry",
|
| 181 |
+
"GitCommitInfo",
|
| 182 |
+
"GitRefInfo",
|
| 183 |
+
"GitRefs",
|
| 184 |
+
"HfApi",
|
| 185 |
+
"KernelInfo",
|
| 186 |
+
"ModelInfo",
|
| 187 |
+
"Organization",
|
| 188 |
+
"RepoFile",
|
| 189 |
+
"RepoFolder",
|
| 190 |
+
"RepoUrl",
|
| 191 |
+
"SpaceInfo",
|
| 192 |
+
"User",
|
| 193 |
+
"UserLikes",
|
| 194 |
+
"WebhookInfo",
|
| 195 |
+
"WebhookWatchedItem",
|
| 196 |
+
"accept_access_request",
|
| 197 |
+
"add_collection_item",
|
| 198 |
+
"add_space_secret",
|
| 199 |
+
"add_space_variable",
|
| 200 |
+
"auth_check",
|
| 201 |
+
"batch_bucket_files",
|
| 202 |
+
"bucket_info",
|
| 203 |
+
"cancel_access_request",
|
| 204 |
+
"cancel_job",
|
| 205 |
+
"change_discussion_status",
|
| 206 |
+
"comment_discussion",
|
| 207 |
+
"copy_files",
|
| 208 |
+
"create_branch",
|
| 209 |
+
"create_bucket",
|
| 210 |
+
"create_collection",
|
| 211 |
+
"create_commit",
|
| 212 |
+
"create_discussion",
|
| 213 |
+
"create_inference_endpoint",
|
| 214 |
+
"create_inference_endpoint_from_catalog",
|
| 215 |
+
"create_pull_request",
|
| 216 |
+
"create_repo",
|
| 217 |
+
"create_scheduled_job",
|
| 218 |
+
"create_scheduled_uv_job",
|
| 219 |
+
"create_tag",
|
| 220 |
+
"create_webhook",
|
| 221 |
+
"dataset_info",
|
| 222 |
+
"delete_branch",
|
| 223 |
+
"delete_bucket",
|
| 224 |
+
"delete_collection",
|
| 225 |
+
"delete_collection_item",
|
| 226 |
+
"delete_file",
|
| 227 |
+
"delete_folder",
|
| 228 |
+
"delete_inference_endpoint",
|
| 229 |
+
"delete_repo",
|
| 230 |
+
"delete_scheduled_job",
|
| 231 |
+
"delete_space_secret",
|
| 232 |
+
"delete_space_storage",
|
| 233 |
+
"delete_space_variable",
|
| 234 |
+
"delete_space_volumes",
|
| 235 |
+
"delete_tag",
|
| 236 |
+
"delete_webhook",
|
| 237 |
+
"disable_space_dev_mode",
|
| 238 |
+
"disable_webhook",
|
| 239 |
+
"download_bucket_files",
|
| 240 |
+
"duplicate_repo",
|
| 241 |
+
"duplicate_space",
|
| 242 |
+
"edit_discussion_comment",
|
| 243 |
+
"enable_space_dev_mode",
|
| 244 |
+
"enable_webhook",
|
| 245 |
+
"fetch_job_logs",
|
| 246 |
+
"fetch_job_metrics",
|
| 247 |
+
"file_exists",
|
| 248 |
+
"get_bucket_file_metadata",
|
| 249 |
+
"get_bucket_paths_info",
|
| 250 |
+
"get_collection",
|
| 251 |
+
"get_dataset_leaderboard",
|
| 252 |
+
"get_dataset_tags",
|
| 253 |
+
"get_discussion_details",
|
| 254 |
+
"get_full_repo_name",
|
| 255 |
+
"get_inference_endpoint",
|
| 256 |
+
"get_local_safetensors_metadata",
|
| 257 |
+
"get_model_tags",
|
| 258 |
+
"get_organization_overview",
|
| 259 |
+
"get_paths_info",
|
| 260 |
+
"get_repo_discussions",
|
| 261 |
+
"get_safetensors_metadata",
|
| 262 |
+
"get_space_runtime",
|
| 263 |
+
"get_space_variables",
|
| 264 |
+
"get_user_overview",
|
| 265 |
+
"get_webhook",
|
| 266 |
+
"grant_access",
|
| 267 |
+
"inspect_job",
|
| 268 |
+
"inspect_scheduled_job",
|
| 269 |
+
"kernel_info",
|
| 270 |
+
"list_accepted_access_requests",
|
| 271 |
+
"list_bucket_tree",
|
| 272 |
+
"list_buckets",
|
| 273 |
+
"list_collections",
|
| 274 |
+
"list_daily_papers",
|
| 275 |
+
"list_dataset_parquet_files",
|
| 276 |
+
"list_datasets",
|
| 277 |
+
"list_inference_catalog",
|
| 278 |
+
"list_inference_endpoints",
|
| 279 |
+
"list_jobs",
|
| 280 |
+
"list_jobs_hardware",
|
| 281 |
+
"list_lfs_files",
|
| 282 |
+
"list_liked_repos",
|
| 283 |
+
"list_models",
|
| 284 |
+
"list_organization_followers",
|
| 285 |
+
"list_organization_members",
|
| 286 |
+
"list_papers",
|
| 287 |
+
"list_pending_access_requests",
|
| 288 |
+
"list_rejected_access_requests",
|
| 289 |
+
"list_repo_commits",
|
| 290 |
+
"list_repo_files",
|
| 291 |
+
"list_repo_likers",
|
| 292 |
+
"list_repo_refs",
|
| 293 |
+
"list_repo_tree",
|
| 294 |
+
"list_spaces",
|
| 295 |
+
"list_user_followers",
|
| 296 |
+
"list_user_following",
|
| 297 |
+
"list_webhooks",
|
| 298 |
+
"merge_pull_request",
|
| 299 |
+
"model_info",
|
| 300 |
+
"move_bucket",
|
| 301 |
+
"move_repo",
|
| 302 |
+
"paper_info",
|
| 303 |
+
"parse_local_safetensors_file_metadata",
|
| 304 |
+
"parse_safetensors_file_metadata",
|
| 305 |
+
"pause_inference_endpoint",
|
| 306 |
+
"pause_space",
|
| 307 |
+
"permanently_delete_lfs_files",
|
| 308 |
+
"preupload_lfs_files",
|
| 309 |
+
"read_paper",
|
| 310 |
+
"reject_access_request",
|
| 311 |
+
"rename_discussion",
|
| 312 |
+
"repo_exists",
|
| 313 |
+
"repo_info",
|
| 314 |
+
"repo_type_and_id_from_hf_id",
|
| 315 |
+
"request_space_hardware",
|
| 316 |
+
"request_space_storage",
|
| 317 |
+
"restart_space",
|
| 318 |
+
"resume_inference_endpoint",
|
| 319 |
+
"resume_scheduled_job",
|
| 320 |
+
"revision_exists",
|
| 321 |
+
"run_as_future",
|
| 322 |
+
"run_job",
|
| 323 |
+
"run_uv_job",
|
| 324 |
+
"scale_to_zero_inference_endpoint",
|
| 325 |
+
"set_space_sleep_time",
|
| 326 |
+
"set_space_volumes",
|
| 327 |
+
"space_info",
|
| 328 |
+
"super_squash_history",
|
| 329 |
+
"suspend_scheduled_job",
|
| 330 |
+
"sync_bucket",
|
| 331 |
+
"unlike",
|
| 332 |
+
"update_collection_item",
|
| 333 |
+
"update_collection_metadata",
|
| 334 |
+
"update_inference_endpoint",
|
| 335 |
+
"update_repo_settings",
|
| 336 |
+
"update_webhook",
|
| 337 |
+
"upload_file",
|
| 338 |
+
"upload_folder",
|
| 339 |
+
"upload_large_folder",
|
| 340 |
+
"verify_repo_checksums",
|
| 341 |
+
"whoami",
|
| 342 |
+
],
|
| 343 |
+
"hf_file_system": [
|
| 344 |
+
"HfFileSystem",
|
| 345 |
+
"HfFileSystemFile",
|
| 346 |
+
"HfFileSystemResolvedPath",
|
| 347 |
+
"HfFileSystemStreamFile",
|
| 348 |
+
"hffs",
|
| 349 |
+
],
|
| 350 |
+
"hub_mixin": [
|
| 351 |
+
"ModelHubMixin",
|
| 352 |
+
"PyTorchModelHubMixin",
|
| 353 |
+
],
|
| 354 |
+
"inference._client": [
|
| 355 |
+
"InferenceClient",
|
| 356 |
+
"InferenceTimeoutError",
|
| 357 |
+
],
|
| 358 |
+
"inference._generated._async_client": [
|
| 359 |
+
"AsyncInferenceClient",
|
| 360 |
+
],
|
| 361 |
+
"inference._generated.types": [
|
| 362 |
+
"AudioClassificationInput",
|
| 363 |
+
"AudioClassificationOutputElement",
|
| 364 |
+
"AudioClassificationOutputTransform",
|
| 365 |
+
"AudioClassificationParameters",
|
| 366 |
+
"AudioToAudioInput",
|
| 367 |
+
"AudioToAudioOutputElement",
|
| 368 |
+
"AutomaticSpeechRecognitionEarlyStoppingEnum",
|
| 369 |
+
"AutomaticSpeechRecognitionGenerationParameters",
|
| 370 |
+
"AutomaticSpeechRecognitionInput",
|
| 371 |
+
"AutomaticSpeechRecognitionOutput",
|
| 372 |
+
"AutomaticSpeechRecognitionOutputChunk",
|
| 373 |
+
"AutomaticSpeechRecognitionParameters",
|
| 374 |
+
"ChatCompletionInput",
|
| 375 |
+
"ChatCompletionInputFunctionDefinition",
|
| 376 |
+
"ChatCompletionInputFunctionName",
|
| 377 |
+
"ChatCompletionInputGrammarType",
|
| 378 |
+
"ChatCompletionInputJSONSchema",
|
| 379 |
+
"ChatCompletionInputMessage",
|
| 380 |
+
"ChatCompletionInputMessageChunk",
|
| 381 |
+
"ChatCompletionInputMessageChunkType",
|
| 382 |
+
"ChatCompletionInputResponseFormatJSONObject",
|
| 383 |
+
"ChatCompletionInputResponseFormatJSONSchema",
|
| 384 |
+
"ChatCompletionInputResponseFormatText",
|
| 385 |
+
"ChatCompletionInputStreamOptions",
|
| 386 |
+
"ChatCompletionInputTool",
|
| 387 |
+
"ChatCompletionInputToolCall",
|
| 388 |
+
"ChatCompletionInputToolChoiceClass",
|
| 389 |
+
"ChatCompletionInputToolChoiceEnum",
|
| 390 |
+
"ChatCompletionInputURL",
|
| 391 |
+
"ChatCompletionOutput",
|
| 392 |
+
"ChatCompletionOutputComplete",
|
| 393 |
+
"ChatCompletionOutputFunctionDefinition",
|
| 394 |
+
"ChatCompletionOutputLogprob",
|
| 395 |
+
"ChatCompletionOutputLogprobs",
|
| 396 |
+
"ChatCompletionOutputMessage",
|
| 397 |
+
"ChatCompletionOutputToolCall",
|
| 398 |
+
"ChatCompletionOutputTopLogprob",
|
| 399 |
+
"ChatCompletionOutputUsage",
|
| 400 |
+
"ChatCompletionStreamOutput",
|
| 401 |
+
"ChatCompletionStreamOutputChoice",
|
| 402 |
+
"ChatCompletionStreamOutputDelta",
|
| 403 |
+
"ChatCompletionStreamOutputDeltaToolCall",
|
| 404 |
+
"ChatCompletionStreamOutputFunction",
|
| 405 |
+
"ChatCompletionStreamOutputLogprob",
|
| 406 |
+
"ChatCompletionStreamOutputLogprobs",
|
| 407 |
+
"ChatCompletionStreamOutputTopLogprob",
|
| 408 |
+
"ChatCompletionStreamOutputUsage",
|
| 409 |
+
"DepthEstimationInput",
|
| 410 |
+
"DepthEstimationOutput",
|
| 411 |
+
"DocumentQuestionAnsweringInput",
|
| 412 |
+
"DocumentQuestionAnsweringInputData",
|
| 413 |
+
"DocumentQuestionAnsweringOutputElement",
|
| 414 |
+
"DocumentQuestionAnsweringParameters",
|
| 415 |
+
"FeatureExtractionInput",
|
| 416 |
+
"FeatureExtractionInputTruncationDirection",
|
| 417 |
+
"FillMaskInput",
|
| 418 |
+
"FillMaskOutputElement",
|
| 419 |
+
"FillMaskParameters",
|
| 420 |
+
"ImageClassificationInput",
|
| 421 |
+
"ImageClassificationOutputElement",
|
| 422 |
+
"ImageClassificationOutputTransform",
|
| 423 |
+
"ImageClassificationParameters",
|
| 424 |
+
"ImageSegmentationInput",
|
| 425 |
+
"ImageSegmentationOutputElement",
|
| 426 |
+
"ImageSegmentationParameters",
|
| 427 |
+
"ImageSegmentationSubtask",
|
| 428 |
+
"ImageTextToImageInput",
|
| 429 |
+
"ImageTextToImageOutput",
|
| 430 |
+
"ImageTextToImageParameters",
|
| 431 |
+
"ImageTextToImageTargetSize",
|
| 432 |
+
"ImageTextToVideoInput",
|
| 433 |
+
"ImageTextToVideoOutput",
|
| 434 |
+
"ImageTextToVideoParameters",
|
| 435 |
+
"ImageTextToVideoTargetSize",
|
| 436 |
+
"ImageToImageInput",
|
| 437 |
+
"ImageToImageOutput",
|
| 438 |
+
"ImageToImageParameters",
|
| 439 |
+
"ImageToImageTargetSize",
|
| 440 |
+
"ImageToTextEarlyStoppingEnum",
|
| 441 |
+
"ImageToTextGenerationParameters",
|
| 442 |
+
"ImageToTextInput",
|
| 443 |
+
"ImageToTextOutput",
|
| 444 |
+
"ImageToTextParameters",
|
| 445 |
+
"ImageToVideoInput",
|
| 446 |
+
"ImageToVideoOutput",
|
| 447 |
+
"ImageToVideoParameters",
|
| 448 |
+
"ImageToVideoTargetSize",
|
| 449 |
+
"ObjectDetectionBoundingBox",
|
| 450 |
+
"ObjectDetectionInput",
|
| 451 |
+
"ObjectDetectionOutputElement",
|
| 452 |
+
"ObjectDetectionParameters",
|
| 453 |
+
"Padding",
|
| 454 |
+
"QuestionAnsweringInput",
|
| 455 |
+
"QuestionAnsweringInputData",
|
| 456 |
+
"QuestionAnsweringOutputElement",
|
| 457 |
+
"QuestionAnsweringParameters",
|
| 458 |
+
"SentenceSimilarityInput",
|
| 459 |
+
"SentenceSimilarityInputData",
|
| 460 |
+
"SummarizationInput",
|
| 461 |
+
"SummarizationOutput",
|
| 462 |
+
"SummarizationParameters",
|
| 463 |
+
"SummarizationTruncationStrategy",
|
| 464 |
+
"TableQuestionAnsweringInput",
|
| 465 |
+
"TableQuestionAnsweringInputData",
|
| 466 |
+
"TableQuestionAnsweringOutputElement",
|
| 467 |
+
"TableQuestionAnsweringParameters",
|
| 468 |
+
"Text2TextGenerationInput",
|
| 469 |
+
"Text2TextGenerationOutput",
|
| 470 |
+
"Text2TextGenerationParameters",
|
| 471 |
+
"Text2TextGenerationTruncationStrategy",
|
| 472 |
+
"TextClassificationInput",
|
| 473 |
+
"TextClassificationOutputElement",
|
| 474 |
+
"TextClassificationOutputTransform",
|
| 475 |
+
"TextClassificationParameters",
|
| 476 |
+
"TextGenerationInput",
|
| 477 |
+
"TextGenerationInputGenerateParameters",
|
| 478 |
+
"TextGenerationInputGrammarType",
|
| 479 |
+
"TextGenerationOutput",
|
| 480 |
+
"TextGenerationOutputBestOfSequence",
|
| 481 |
+
"TextGenerationOutputDetails",
|
| 482 |
+
"TextGenerationOutputFinishReason",
|
| 483 |
+
"TextGenerationOutputPrefillToken",
|
| 484 |
+
"TextGenerationOutputToken",
|
| 485 |
+
"TextGenerationStreamOutput",
|
| 486 |
+
"TextGenerationStreamOutputStreamDetails",
|
| 487 |
+
"TextGenerationStreamOutputToken",
|
| 488 |
+
"TextToAudioEarlyStoppingEnum",
|
| 489 |
+
"TextToAudioGenerationParameters",
|
| 490 |
+
"TextToAudioInput",
|
| 491 |
+
"TextToAudioOutput",
|
| 492 |
+
"TextToAudioParameters",
|
| 493 |
+
"TextToImageInput",
|
| 494 |
+
"TextToImageOutput",
|
| 495 |
+
"TextToImageParameters",
|
| 496 |
+
"TextToSpeechEarlyStoppingEnum",
|
| 497 |
+
"TextToSpeechGenerationParameters",
|
| 498 |
+
"TextToSpeechInput",
|
| 499 |
+
"TextToSpeechOutput",
|
| 500 |
+
"TextToSpeechParameters",
|
| 501 |
+
"TextToVideoInput",
|
| 502 |
+
"TextToVideoOutput",
|
| 503 |
+
"TextToVideoParameters",
|
| 504 |
+
"TokenClassificationAggregationStrategy",
|
| 505 |
+
"TokenClassificationInput",
|
| 506 |
+
"TokenClassificationOutputElement",
|
| 507 |
+
"TokenClassificationParameters",
|
| 508 |
+
"TranslationInput",
|
| 509 |
+
"TranslationOutput",
|
| 510 |
+
"TranslationParameters",
|
| 511 |
+
"TranslationTruncationStrategy",
|
| 512 |
+
"TypeEnum",
|
| 513 |
+
"VideoClassificationInput",
|
| 514 |
+
"VideoClassificationOutputElement",
|
| 515 |
+
"VideoClassificationOutputTransform",
|
| 516 |
+
"VideoClassificationParameters",
|
| 517 |
+
"VisualQuestionAnsweringInput",
|
| 518 |
+
"VisualQuestionAnsweringInputData",
|
| 519 |
+
"VisualQuestionAnsweringOutputElement",
|
| 520 |
+
"VisualQuestionAnsweringParameters",
|
| 521 |
+
"ZeroShotClassificationInput",
|
| 522 |
+
"ZeroShotClassificationOutputElement",
|
| 523 |
+
"ZeroShotClassificationParameters",
|
| 524 |
+
"ZeroShotImageClassificationInput",
|
| 525 |
+
"ZeroShotImageClassificationOutputElement",
|
| 526 |
+
"ZeroShotImageClassificationParameters",
|
| 527 |
+
"ZeroShotObjectDetectionBoundingBox",
|
| 528 |
+
"ZeroShotObjectDetectionInput",
|
| 529 |
+
"ZeroShotObjectDetectionOutputElement",
|
| 530 |
+
"ZeroShotObjectDetectionParameters",
|
| 531 |
+
],
|
| 532 |
+
"inference._mcp.agent": [
|
| 533 |
+
"Agent",
|
| 534 |
+
],
|
| 535 |
+
"inference._mcp.mcp_client": [
|
| 536 |
+
"MCPClient",
|
| 537 |
+
],
|
| 538 |
+
"repocard": [
|
| 539 |
+
"DatasetCard",
|
| 540 |
+
"ModelCard",
|
| 541 |
+
"RepoCard",
|
| 542 |
+
"SpaceCard",
|
| 543 |
+
"metadata_eval_result",
|
| 544 |
+
"metadata_load",
|
| 545 |
+
"metadata_save",
|
| 546 |
+
"metadata_update",
|
| 547 |
+
],
|
| 548 |
+
"repocard_data": [
|
| 549 |
+
"CardData",
|
| 550 |
+
"DatasetCardData",
|
| 551 |
+
"EvalResult",
|
| 552 |
+
"ModelCardData",
|
| 553 |
+
"SpaceCardData",
|
| 554 |
+
],
|
| 555 |
+
"serialization": [
|
| 556 |
+
"StateDictSplit",
|
| 557 |
+
"get_torch_storage_id",
|
| 558 |
+
"get_torch_storage_size",
|
| 559 |
+
"load_state_dict_from_file",
|
| 560 |
+
"load_torch_model",
|
| 561 |
+
"save_torch_model",
|
| 562 |
+
"save_torch_state_dict",
|
| 563 |
+
"split_state_dict_into_shards_factory",
|
| 564 |
+
"split_torch_state_dict_into_shards",
|
| 565 |
+
],
|
| 566 |
+
"serialization._dduf": [
|
| 567 |
+
"DDUFEntry",
|
| 568 |
+
"export_entries_as_dduf",
|
| 569 |
+
"export_folder_as_dduf",
|
| 570 |
+
"read_dduf_file",
|
| 571 |
+
],
|
| 572 |
+
"utils": [
|
| 573 |
+
"ASYNC_CLIENT_FACTORY_T",
|
| 574 |
+
"CLIENT_FACTORY_T",
|
| 575 |
+
"CacheNotFound",
|
| 576 |
+
"CachedFileInfo",
|
| 577 |
+
"CachedRepoInfo",
|
| 578 |
+
"CachedRevisionInfo",
|
| 579 |
+
"CorruptedCacheException",
|
| 580 |
+
"DeleteCacheStrategy",
|
| 581 |
+
"HFCacheInfo",
|
| 582 |
+
"cached_assets_path",
|
| 583 |
+
"close_session",
|
| 584 |
+
"dump_environment_info",
|
| 585 |
+
"get_async_session",
|
| 586 |
+
"get_session",
|
| 587 |
+
"get_token",
|
| 588 |
+
"hf_raise_for_status",
|
| 589 |
+
"logging",
|
| 590 |
+
"scan_cache_dir",
|
| 591 |
+
"set_async_client_factory",
|
| 592 |
+
"set_client_factory",
|
| 593 |
+
],
|
| 594 |
+
}
|
| 595 |
+
|
| 596 |
+
# WARNING: __all__ is generated automatically, Any manual edit will be lost when re-generating this file !
|
| 597 |
+
#
|
| 598 |
+
# To update the static imports, please run the following command and commit the changes.
|
| 599 |
+
# ```
|
| 600 |
+
# # Use script
|
| 601 |
+
# python utils/check_all_variable.py --update
|
| 602 |
+
#
|
| 603 |
+
# # Or run style on codebase
|
| 604 |
+
# make style
|
| 605 |
+
# ```
|
| 606 |
+
|
| 607 |
+
__all__ = [
|
| 608 |
+
"ASYNC_CLIENT_FACTORY_T",
|
| 609 |
+
"Agent",
|
| 610 |
+
"AsyncInferenceClient",
|
| 611 |
+
"AudioClassificationInput",
|
| 612 |
+
"AudioClassificationOutputElement",
|
| 613 |
+
"AudioClassificationOutputTransform",
|
| 614 |
+
"AudioClassificationParameters",
|
| 615 |
+
"AudioToAudioInput",
|
| 616 |
+
"AudioToAudioOutputElement",
|
| 617 |
+
"AutomaticSpeechRecognitionEarlyStoppingEnum",
|
| 618 |
+
"AutomaticSpeechRecognitionGenerationParameters",
|
| 619 |
+
"AutomaticSpeechRecognitionInput",
|
| 620 |
+
"AutomaticSpeechRecognitionOutput",
|
| 621 |
+
"AutomaticSpeechRecognitionOutputChunk",
|
| 622 |
+
"AutomaticSpeechRecognitionParameters",
|
| 623 |
+
"BucketFile",
|
| 624 |
+
"BucketFileMetadata",
|
| 625 |
+
"BucketFolder",
|
| 626 |
+
"BucketInfo",
|
| 627 |
+
"BucketUrl",
|
| 628 |
+
"CLIENT_FACTORY_T",
|
| 629 |
+
"CONFIG_NAME",
|
| 630 |
+
"CacheNotFound",
|
| 631 |
+
"CachedFileInfo",
|
| 632 |
+
"CachedRepoInfo",
|
| 633 |
+
"CachedRevisionInfo",
|
| 634 |
+
"CardData",
|
| 635 |
+
"ChatCompletionInput",
|
| 636 |
+
"ChatCompletionInputFunctionDefinition",
|
| 637 |
+
"ChatCompletionInputFunctionName",
|
| 638 |
+
"ChatCompletionInputGrammarType",
|
| 639 |
+
"ChatCompletionInputJSONSchema",
|
| 640 |
+
"ChatCompletionInputMessage",
|
| 641 |
+
"ChatCompletionInputMessageChunk",
|
| 642 |
+
"ChatCompletionInputMessageChunkType",
|
| 643 |
+
"ChatCompletionInputResponseFormatJSONObject",
|
| 644 |
+
"ChatCompletionInputResponseFormatJSONSchema",
|
| 645 |
+
"ChatCompletionInputResponseFormatText",
|
| 646 |
+
"ChatCompletionInputStreamOptions",
|
| 647 |
+
"ChatCompletionInputTool",
|
| 648 |
+
"ChatCompletionInputToolCall",
|
| 649 |
+
"ChatCompletionInputToolChoiceClass",
|
| 650 |
+
"ChatCompletionInputToolChoiceEnum",
|
| 651 |
+
"ChatCompletionInputURL",
|
| 652 |
+
"ChatCompletionOutput",
|
| 653 |
+
"ChatCompletionOutputComplete",
|
| 654 |
+
"ChatCompletionOutputFunctionDefinition",
|
| 655 |
+
"ChatCompletionOutputLogprob",
|
| 656 |
+
"ChatCompletionOutputLogprobs",
|
| 657 |
+
"ChatCompletionOutputMessage",
|
| 658 |
+
"ChatCompletionOutputToolCall",
|
| 659 |
+
"ChatCompletionOutputTopLogprob",
|
| 660 |
+
"ChatCompletionOutputUsage",
|
| 661 |
+
"ChatCompletionStreamOutput",
|
| 662 |
+
"ChatCompletionStreamOutputChoice",
|
| 663 |
+
"ChatCompletionStreamOutputDelta",
|
| 664 |
+
"ChatCompletionStreamOutputDeltaToolCall",
|
| 665 |
+
"ChatCompletionStreamOutputFunction",
|
| 666 |
+
"ChatCompletionStreamOutputLogprob",
|
| 667 |
+
"ChatCompletionStreamOutputLogprobs",
|
| 668 |
+
"ChatCompletionStreamOutputTopLogprob",
|
| 669 |
+
"ChatCompletionStreamOutputUsage",
|
| 670 |
+
"Collection",
|
| 671 |
+
"CollectionItem",
|
| 672 |
+
"CommitInfo",
|
| 673 |
+
"CommitOperation",
|
| 674 |
+
"CommitOperationAdd",
|
| 675 |
+
"CommitOperationCopy",
|
| 676 |
+
"CommitOperationDelete",
|
| 677 |
+
"CommitScheduler",
|
| 678 |
+
"CorruptedCacheException",
|
| 679 |
+
"DDUFEntry",
|
| 680 |
+
"DatasetCard",
|
| 681 |
+
"DatasetCardData",
|
| 682 |
+
"DatasetInfo",
|
| 683 |
+
"DatasetLeaderboardEntry",
|
| 684 |
+
"DeleteCacheStrategy",
|
| 685 |
+
"DepthEstimationInput",
|
| 686 |
+
"DepthEstimationOutput",
|
| 687 |
+
"Discussion",
|
| 688 |
+
"DiscussionComment",
|
| 689 |
+
"DiscussionCommit",
|
| 690 |
+
"DiscussionEvent",
|
| 691 |
+
"DiscussionStatusChange",
|
| 692 |
+
"DiscussionTitleChange",
|
| 693 |
+
"DiscussionWithDetails",
|
| 694 |
+
"DocumentQuestionAnsweringInput",
|
| 695 |
+
"DocumentQuestionAnsweringInputData",
|
| 696 |
+
"DocumentQuestionAnsweringOutputElement",
|
| 697 |
+
"DocumentQuestionAnsweringParameters",
|
| 698 |
+
"DryRunFileInfo",
|
| 699 |
+
"EvalResult",
|
| 700 |
+
"EvalResultEntry",
|
| 701 |
+
"FLAX_WEIGHTS_NAME",
|
| 702 |
+
"FeatureExtractionInput",
|
| 703 |
+
"FeatureExtractionInputTruncationDirection",
|
| 704 |
+
"FillMaskInput",
|
| 705 |
+
"FillMaskOutputElement",
|
| 706 |
+
"FillMaskParameters",
|
| 707 |
+
"GitCommitInfo",
|
| 708 |
+
"GitRefInfo",
|
| 709 |
+
"GitRefs",
|
| 710 |
+
"HFCacheInfo",
|
| 711 |
+
"HFSummaryWriter",
|
| 712 |
+
"HUGGINGFACE_CO_URL_HOME",
|
| 713 |
+
"HUGGINGFACE_CO_URL_TEMPLATE",
|
| 714 |
+
"HfApi",
|
| 715 |
+
"HfFileMetadata",
|
| 716 |
+
"HfFileSystem",
|
| 717 |
+
"HfFileSystemFile",
|
| 718 |
+
"HfFileSystemResolvedPath",
|
| 719 |
+
"HfFileSystemStreamFile",
|
| 720 |
+
"ImageClassificationInput",
|
| 721 |
+
"ImageClassificationOutputElement",
|
| 722 |
+
"ImageClassificationOutputTransform",
|
| 723 |
+
"ImageClassificationParameters",
|
| 724 |
+
"ImageSegmentationInput",
|
| 725 |
+
"ImageSegmentationOutputElement",
|
| 726 |
+
"ImageSegmentationParameters",
|
| 727 |
+
"ImageSegmentationSubtask",
|
| 728 |
+
"ImageTextToImageInput",
|
| 729 |
+
"ImageTextToImageOutput",
|
| 730 |
+
"ImageTextToImageParameters",
|
| 731 |
+
"ImageTextToImageTargetSize",
|
| 732 |
+
"ImageTextToVideoInput",
|
| 733 |
+
"ImageTextToVideoOutput",
|
| 734 |
+
"ImageTextToVideoParameters",
|
| 735 |
+
"ImageTextToVideoTargetSize",
|
| 736 |
+
"ImageToImageInput",
|
| 737 |
+
"ImageToImageOutput",
|
| 738 |
+
"ImageToImageParameters",
|
| 739 |
+
"ImageToImageTargetSize",
|
| 740 |
+
"ImageToTextEarlyStoppingEnum",
|
| 741 |
+
"ImageToTextGenerationParameters",
|
| 742 |
+
"ImageToTextInput",
|
| 743 |
+
"ImageToTextOutput",
|
| 744 |
+
"ImageToTextParameters",
|
| 745 |
+
"ImageToVideoInput",
|
| 746 |
+
"ImageToVideoOutput",
|
| 747 |
+
"ImageToVideoParameters",
|
| 748 |
+
"ImageToVideoTargetSize",
|
| 749 |
+
"InferenceClient",
|
| 750 |
+
"InferenceEndpoint",
|
| 751 |
+
"InferenceEndpointError",
|
| 752 |
+
"InferenceEndpointStatus",
|
| 753 |
+
"InferenceEndpointTimeoutError",
|
| 754 |
+
"InferenceEndpointType",
|
| 755 |
+
"InferenceTimeoutError",
|
| 756 |
+
"JobAccelerator",
|
| 757 |
+
"JobHardware",
|
| 758 |
+
"JobInfo",
|
| 759 |
+
"JobOwner",
|
| 760 |
+
"JobStage",
|
| 761 |
+
"JobStatus",
|
| 762 |
+
"KernelInfo",
|
| 763 |
+
"MCPClient",
|
| 764 |
+
"ModelCard",
|
| 765 |
+
"ModelCardData",
|
| 766 |
+
"ModelHubMixin",
|
| 767 |
+
"ModelInfo",
|
| 768 |
+
"OAuthInfo",
|
| 769 |
+
"OAuthOrgInfo",
|
| 770 |
+
"OAuthUserInfo",
|
| 771 |
+
"ObjectDetectionBoundingBox",
|
| 772 |
+
"ObjectDetectionInput",
|
| 773 |
+
"ObjectDetectionOutputElement",
|
| 774 |
+
"ObjectDetectionParameters",
|
| 775 |
+
"Organization",
|
| 776 |
+
"PYTORCH_WEIGHTS_NAME",
|
| 777 |
+
"Padding",
|
| 778 |
+
"PyTorchModelHubMixin",
|
| 779 |
+
"QuestionAnsweringInput",
|
| 780 |
+
"QuestionAnsweringInputData",
|
| 781 |
+
"QuestionAnsweringOutputElement",
|
| 782 |
+
"QuestionAnsweringParameters",
|
| 783 |
+
"REPO_TYPE_DATASET",
|
| 784 |
+
"REPO_TYPE_MODEL",
|
| 785 |
+
"REPO_TYPE_SPACE",
|
| 786 |
+
"RepoCard",
|
| 787 |
+
"RepoFile",
|
| 788 |
+
"RepoFolder",
|
| 789 |
+
"RepoUrl",
|
| 790 |
+
"SentenceSimilarityInput",
|
| 791 |
+
"SentenceSimilarityInputData",
|
| 792 |
+
"SpaceCard",
|
| 793 |
+
"SpaceCardData",
|
| 794 |
+
"SpaceHardware",
|
| 795 |
+
"SpaceInfo",
|
| 796 |
+
"SpaceRuntime",
|
| 797 |
+
"SpaceStage",
|
| 798 |
+
"SpaceStorage",
|
| 799 |
+
"SpaceVariable",
|
| 800 |
+
"StateDictSplit",
|
| 801 |
+
"SummarizationInput",
|
| 802 |
+
"SummarizationOutput",
|
| 803 |
+
"SummarizationParameters",
|
| 804 |
+
"SummarizationTruncationStrategy",
|
| 805 |
+
"SyncOperation",
|
| 806 |
+
"SyncPlan",
|
| 807 |
+
"TF2_WEIGHTS_NAME",
|
| 808 |
+
"TF_WEIGHTS_NAME",
|
| 809 |
+
"TableQuestionAnsweringInput",
|
| 810 |
+
"TableQuestionAnsweringInputData",
|
| 811 |
+
"TableQuestionAnsweringOutputElement",
|
| 812 |
+
"TableQuestionAnsweringParameters",
|
| 813 |
+
"Text2TextGenerationInput",
|
| 814 |
+
"Text2TextGenerationOutput",
|
| 815 |
+
"Text2TextGenerationParameters",
|
| 816 |
+
"Text2TextGenerationTruncationStrategy",
|
| 817 |
+
"TextClassificationInput",
|
| 818 |
+
"TextClassificationOutputElement",
|
| 819 |
+
"TextClassificationOutputTransform",
|
| 820 |
+
"TextClassificationParameters",
|
| 821 |
+
"TextGenerationInput",
|
| 822 |
+
"TextGenerationInputGenerateParameters",
|
| 823 |
+
"TextGenerationInputGrammarType",
|
| 824 |
+
"TextGenerationOutput",
|
| 825 |
+
"TextGenerationOutputBestOfSequence",
|
| 826 |
+
"TextGenerationOutputDetails",
|
| 827 |
+
"TextGenerationOutputFinishReason",
|
| 828 |
+
"TextGenerationOutputPrefillToken",
|
| 829 |
+
"TextGenerationOutputToken",
|
| 830 |
+
"TextGenerationStreamOutput",
|
| 831 |
+
"TextGenerationStreamOutputStreamDetails",
|
| 832 |
+
"TextGenerationStreamOutputToken",
|
| 833 |
+
"TextToAudioEarlyStoppingEnum",
|
| 834 |
+
"TextToAudioGenerationParameters",
|
| 835 |
+
"TextToAudioInput",
|
| 836 |
+
"TextToAudioOutput",
|
| 837 |
+
"TextToAudioParameters",
|
| 838 |
+
"TextToImageInput",
|
| 839 |
+
"TextToImageOutput",
|
| 840 |
+
"TextToImageParameters",
|
| 841 |
+
"TextToSpeechEarlyStoppingEnum",
|
| 842 |
+
"TextToSpeechGenerationParameters",
|
| 843 |
+
"TextToSpeechInput",
|
| 844 |
+
"TextToSpeechOutput",
|
| 845 |
+
"TextToSpeechParameters",
|
| 846 |
+
"TextToVideoInput",
|
| 847 |
+
"TextToVideoOutput",
|
| 848 |
+
"TextToVideoParameters",
|
| 849 |
+
"TokenClassificationAggregationStrategy",
|
| 850 |
+
"TokenClassificationInput",
|
| 851 |
+
"TokenClassificationOutputElement",
|
| 852 |
+
"TokenClassificationParameters",
|
| 853 |
+
"TranslationInput",
|
| 854 |
+
"TranslationOutput",
|
| 855 |
+
"TranslationParameters",
|
| 856 |
+
"TranslationTruncationStrategy",
|
| 857 |
+
"TypeEnum",
|
| 858 |
+
"User",
|
| 859 |
+
"UserLikes",
|
| 860 |
+
"VideoClassificationInput",
|
| 861 |
+
"VideoClassificationOutputElement",
|
| 862 |
+
"VideoClassificationOutputTransform",
|
| 863 |
+
"VideoClassificationParameters",
|
| 864 |
+
"VisualQuestionAnsweringInput",
|
| 865 |
+
"VisualQuestionAnsweringInputData",
|
| 866 |
+
"VisualQuestionAnsweringOutputElement",
|
| 867 |
+
"VisualQuestionAnsweringParameters",
|
| 868 |
+
"Volume",
|
| 869 |
+
"WebhookInfo",
|
| 870 |
+
"WebhookPayload",
|
| 871 |
+
"WebhookPayloadComment",
|
| 872 |
+
"WebhookPayloadDiscussion",
|
| 873 |
+
"WebhookPayloadDiscussionChanges",
|
| 874 |
+
"WebhookPayloadEvent",
|
| 875 |
+
"WebhookPayloadMovedTo",
|
| 876 |
+
"WebhookPayloadRepo",
|
| 877 |
+
"WebhookPayloadUrl",
|
| 878 |
+
"WebhookPayloadWebhook",
|
| 879 |
+
"WebhookWatchedItem",
|
| 880 |
+
"WebhooksServer",
|
| 881 |
+
"ZeroShotClassificationInput",
|
| 882 |
+
"ZeroShotClassificationOutputElement",
|
| 883 |
+
"ZeroShotClassificationParameters",
|
| 884 |
+
"ZeroShotImageClassificationInput",
|
| 885 |
+
"ZeroShotImageClassificationOutputElement",
|
| 886 |
+
"ZeroShotImageClassificationParameters",
|
| 887 |
+
"ZeroShotObjectDetectionBoundingBox",
|
| 888 |
+
"ZeroShotObjectDetectionInput",
|
| 889 |
+
"ZeroShotObjectDetectionOutputElement",
|
| 890 |
+
"ZeroShotObjectDetectionParameters",
|
| 891 |
+
"_CACHED_NO_EXIST",
|
| 892 |
+
"_save_pretrained_fastai",
|
| 893 |
+
"accept_access_request",
|
| 894 |
+
"add_collection_item",
|
| 895 |
+
"add_space_secret",
|
| 896 |
+
"add_space_variable",
|
| 897 |
+
"attach_huggingface_oauth",
|
| 898 |
+
"auth_check",
|
| 899 |
+
"auth_list",
|
| 900 |
+
"auth_switch",
|
| 901 |
+
"batch_bucket_files",
|
| 902 |
+
"bucket_info",
|
| 903 |
+
"cached_assets_path",
|
| 904 |
+
"cancel_access_request",
|
| 905 |
+
"cancel_job",
|
| 906 |
+
"change_discussion_status",
|
| 907 |
+
"check_cli_update",
|
| 908 |
+
"close_session",
|
| 909 |
+
"comment_discussion",
|
| 910 |
+
"copy_files",
|
| 911 |
+
"create_branch",
|
| 912 |
+
"create_bucket",
|
| 913 |
+
"create_collection",
|
| 914 |
+
"create_commit",
|
| 915 |
+
"create_discussion",
|
| 916 |
+
"create_inference_endpoint",
|
| 917 |
+
"create_inference_endpoint_from_catalog",
|
| 918 |
+
"create_pull_request",
|
| 919 |
+
"create_repo",
|
| 920 |
+
"create_scheduled_job",
|
| 921 |
+
"create_scheduled_uv_job",
|
| 922 |
+
"create_tag",
|
| 923 |
+
"create_webhook",
|
| 924 |
+
"dataset_info",
|
| 925 |
+
"delete_branch",
|
| 926 |
+
"delete_bucket",
|
| 927 |
+
"delete_collection",
|
| 928 |
+
"delete_collection_item",
|
| 929 |
+
"delete_file",
|
| 930 |
+
"delete_folder",
|
| 931 |
+
"delete_inference_endpoint",
|
| 932 |
+
"delete_repo",
|
| 933 |
+
"delete_scheduled_job",
|
| 934 |
+
"delete_space_secret",
|
| 935 |
+
"delete_space_storage",
|
| 936 |
+
"delete_space_variable",
|
| 937 |
+
"delete_space_volumes",
|
| 938 |
+
"delete_tag",
|
| 939 |
+
"delete_webhook",
|
| 940 |
+
"disable_space_dev_mode",
|
| 941 |
+
"disable_webhook",
|
| 942 |
+
"download_bucket_files",
|
| 943 |
+
"dump_environment_info",
|
| 944 |
+
"duplicate_repo",
|
| 945 |
+
"duplicate_space",
|
| 946 |
+
"edit_discussion_comment",
|
| 947 |
+
"enable_space_dev_mode",
|
| 948 |
+
"enable_webhook",
|
| 949 |
+
"eval_result_entries_to_yaml",
|
| 950 |
+
"export_entries_as_dduf",
|
| 951 |
+
"export_folder_as_dduf",
|
| 952 |
+
"fetch_job_logs",
|
| 953 |
+
"fetch_job_metrics",
|
| 954 |
+
"file_exists",
|
| 955 |
+
"from_pretrained_fastai",
|
| 956 |
+
"get_async_session",
|
| 957 |
+
"get_bucket_file_metadata",
|
| 958 |
+
"get_bucket_paths_info",
|
| 959 |
+
"get_collection",
|
| 960 |
+
"get_dataset_leaderboard",
|
| 961 |
+
"get_dataset_tags",
|
| 962 |
+
"get_discussion_details",
|
| 963 |
+
"get_full_repo_name",
|
| 964 |
+
"get_hf_file_metadata",
|
| 965 |
+
"get_inference_endpoint",
|
| 966 |
+
"get_local_safetensors_metadata",
|
| 967 |
+
"get_model_tags",
|
| 968 |
+
"get_organization_overview",
|
| 969 |
+
"get_paths_info",
|
| 970 |
+
"get_repo_discussions",
|
| 971 |
+
"get_safetensors_metadata",
|
| 972 |
+
"get_session",
|
| 973 |
+
"get_space_runtime",
|
| 974 |
+
"get_space_variables",
|
| 975 |
+
"get_token",
|
| 976 |
+
"get_torch_storage_id",
|
| 977 |
+
"get_torch_storage_size",
|
| 978 |
+
"get_user_overview",
|
| 979 |
+
"get_webhook",
|
| 980 |
+
"grant_access",
|
| 981 |
+
"hf_hub_download",
|
| 982 |
+
"hf_hub_url",
|
| 983 |
+
"hf_raise_for_status",
|
| 984 |
+
"hffs",
|
| 985 |
+
"inspect_job",
|
| 986 |
+
"inspect_scheduled_job",
|
| 987 |
+
"interpreter_login",
|
| 988 |
+
"is_offline_mode",
|
| 989 |
+
"kernel_info",
|
| 990 |
+
"list_accepted_access_requests",
|
| 991 |
+
"list_bucket_tree",
|
| 992 |
+
"list_buckets",
|
| 993 |
+
"list_collections",
|
| 994 |
+
"list_daily_papers",
|
| 995 |
+
"list_dataset_parquet_files",
|
| 996 |
+
"list_datasets",
|
| 997 |
+
"list_inference_catalog",
|
| 998 |
+
"list_inference_endpoints",
|
| 999 |
+
"list_jobs",
|
| 1000 |
+
"list_jobs_hardware",
|
| 1001 |
+
"list_lfs_files",
|
| 1002 |
+
"list_liked_repos",
|
| 1003 |
+
"list_models",
|
| 1004 |
+
"list_organization_followers",
|
| 1005 |
+
"list_organization_members",
|
| 1006 |
+
"list_papers",
|
| 1007 |
+
"list_pending_access_requests",
|
| 1008 |
+
"list_rejected_access_requests",
|
| 1009 |
+
"list_repo_commits",
|
| 1010 |
+
"list_repo_files",
|
| 1011 |
+
"list_repo_likers",
|
| 1012 |
+
"list_repo_refs",
|
| 1013 |
+
"list_repo_tree",
|
| 1014 |
+
"list_spaces",
|
| 1015 |
+
"list_user_followers",
|
| 1016 |
+
"list_user_following",
|
| 1017 |
+
"list_webhooks",
|
| 1018 |
+
"load_state_dict_from_file",
|
| 1019 |
+
"load_torch_model",
|
| 1020 |
+
"logging",
|
| 1021 |
+
"login",
|
| 1022 |
+
"logout",
|
| 1023 |
+
"merge_pull_request",
|
| 1024 |
+
"metadata_eval_result",
|
| 1025 |
+
"metadata_load",
|
| 1026 |
+
"metadata_save",
|
| 1027 |
+
"metadata_update",
|
| 1028 |
+
"model_info",
|
| 1029 |
+
"move_bucket",
|
| 1030 |
+
"move_repo",
|
| 1031 |
+
"notebook_login",
|
| 1032 |
+
"paper_info",
|
| 1033 |
+
"parse_eval_result_entries",
|
| 1034 |
+
"parse_huggingface_oauth",
|
| 1035 |
+
"parse_local_safetensors_file_metadata",
|
| 1036 |
+
"parse_safetensors_file_metadata",
|
| 1037 |
+
"pause_inference_endpoint",
|
| 1038 |
+
"pause_space",
|
| 1039 |
+
"permanently_delete_lfs_files",
|
| 1040 |
+
"preupload_lfs_files",
|
| 1041 |
+
"push_to_hub_fastai",
|
| 1042 |
+
"read_dduf_file",
|
| 1043 |
+
"read_paper",
|
| 1044 |
+
"reject_access_request",
|
| 1045 |
+
"rename_discussion",
|
| 1046 |
+
"repo_exists",
|
| 1047 |
+
"repo_info",
|
| 1048 |
+
"repo_type_and_id_from_hf_id",
|
| 1049 |
+
"request_space_hardware",
|
| 1050 |
+
"request_space_storage",
|
| 1051 |
+
"restart_space",
|
| 1052 |
+
"resume_inference_endpoint",
|
| 1053 |
+
"resume_scheduled_job",
|
| 1054 |
+
"revision_exists",
|
| 1055 |
+
"run_as_future",
|
| 1056 |
+
"run_job",
|
| 1057 |
+
"run_uv_job",
|
| 1058 |
+
"save_torch_model",
|
| 1059 |
+
"save_torch_state_dict",
|
| 1060 |
+
"scale_to_zero_inference_endpoint",
|
| 1061 |
+
"scan_cache_dir",
|
| 1062 |
+
"set_async_client_factory",
|
| 1063 |
+
"set_client_factory",
|
| 1064 |
+
"set_space_sleep_time",
|
| 1065 |
+
"set_space_volumes",
|
| 1066 |
+
"snapshot_download",
|
| 1067 |
+
"space_info",
|
| 1068 |
+
"split_state_dict_into_shards_factory",
|
| 1069 |
+
"split_torch_state_dict_into_shards",
|
| 1070 |
+
"super_squash_history",
|
| 1071 |
+
"suspend_scheduled_job",
|
| 1072 |
+
"sync_bucket",
|
| 1073 |
+
"try_to_load_from_cache",
|
| 1074 |
+
"typer_factory",
|
| 1075 |
+
"unlike",
|
| 1076 |
+
"update_collection_item",
|
| 1077 |
+
"update_collection_metadata",
|
| 1078 |
+
"update_inference_endpoint",
|
| 1079 |
+
"update_repo_settings",
|
| 1080 |
+
"update_webhook",
|
| 1081 |
+
"upload_file",
|
| 1082 |
+
"upload_folder",
|
| 1083 |
+
"upload_large_folder",
|
| 1084 |
+
"verify_repo_checksums",
|
| 1085 |
+
"webhook_endpoint",
|
| 1086 |
+
"whoami",
|
| 1087 |
+
]
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
def _attach(package_name, submodules=None, submod_attrs=None):
|
| 1091 |
+
"""Attach lazily loaded submodules, functions, or other attributes.
|
| 1092 |
+
|
| 1093 |
+
Typically, modules import submodules and attributes as follows:
|
| 1094 |
+
|
| 1095 |
+
```py
|
| 1096 |
+
import mysubmodule
|
| 1097 |
+
import anothersubmodule
|
| 1098 |
+
|
| 1099 |
+
from .foo import someattr
|
| 1100 |
+
```
|
| 1101 |
+
|
| 1102 |
+
The idea is to replace a package's `__getattr__`, `__dir__`, such that all imports
|
| 1103 |
+
work exactly the way they would with normal imports, except that the import occurs
|
| 1104 |
+
upon first use.
|
| 1105 |
+
|
| 1106 |
+
The typical way to call this function, replacing the above imports, is:
|
| 1107 |
+
|
| 1108 |
+
```python
|
| 1109 |
+
__getattr__, __dir__ = lazy.attach(
|
| 1110 |
+
__name__,
|
| 1111 |
+
['mysubmodule', 'anothersubmodule'],
|
| 1112 |
+
{'foo': ['someattr']}
|
| 1113 |
+
)
|
| 1114 |
+
```
|
| 1115 |
+
This functionality requires Python 3.7 or higher.
|
| 1116 |
+
|
| 1117 |
+
Args:
|
| 1118 |
+
package_name (`str`):
|
| 1119 |
+
Typically use `__name__`.
|
| 1120 |
+
submodules (`set`):
|
| 1121 |
+
List of submodules to attach.
|
| 1122 |
+
submod_attrs (`dict`):
|
| 1123 |
+
Dictionary of submodule -> list of attributes / functions.
|
| 1124 |
+
These attributes are imported as they are used.
|
| 1125 |
+
|
| 1126 |
+
Returns:
|
| 1127 |
+
__getattr__, __dir__, __all__
|
| 1128 |
+
|
| 1129 |
+
"""
|
| 1130 |
+
if submod_attrs is None:
|
| 1131 |
+
submod_attrs = {}
|
| 1132 |
+
|
| 1133 |
+
if submodules is None:
|
| 1134 |
+
submodules = set()
|
| 1135 |
+
else:
|
| 1136 |
+
submodules = set(submodules)
|
| 1137 |
+
|
| 1138 |
+
attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}
|
| 1139 |
+
|
| 1140 |
+
def __getattr__(name):
|
| 1141 |
+
if name in submodules:
|
| 1142 |
+
try:
|
| 1143 |
+
return importlib.import_module(f"{package_name}.{name}")
|
| 1144 |
+
except Exception as e:
|
| 1145 |
+
print(f"Error importing {package_name}.{name}: {e}")
|
| 1146 |
+
raise
|
| 1147 |
+
elif name in attr_to_modules:
|
| 1148 |
+
submod_path = f"{package_name}.{attr_to_modules[name]}"
|
| 1149 |
+
try:
|
| 1150 |
+
submod = importlib.import_module(submod_path)
|
| 1151 |
+
except Exception as e:
|
| 1152 |
+
print(f"Error importing {submod_path}: {e}")
|
| 1153 |
+
raise
|
| 1154 |
+
attr = getattr(submod, name)
|
| 1155 |
+
|
| 1156 |
+
# If the attribute lives in a file (module) with the same
|
| 1157 |
+
# name as the attribute, ensure that the attribute and *not*
|
| 1158 |
+
# the module is accessible on the package.
|
| 1159 |
+
if name == attr_to_modules[name]:
|
| 1160 |
+
pkg = sys.modules[package_name]
|
| 1161 |
+
pkg.__dict__[name] = attr
|
| 1162 |
+
|
| 1163 |
+
return attr
|
| 1164 |
+
else:
|
| 1165 |
+
raise AttributeError(f"No {package_name} attribute {name}")
|
| 1166 |
+
|
| 1167 |
+
def __dir__():
|
| 1168 |
+
return __all__
|
| 1169 |
+
|
| 1170 |
+
return __getattr__, __dir__
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
__getattr__, __dir__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)
|
| 1174 |
+
|
| 1175 |
+
if os.environ.get("EAGER_IMPORT", ""):
|
| 1176 |
+
for attr in __all__:
|
| 1177 |
+
__getattr__(attr)
|
| 1178 |
+
|
| 1179 |
+
# WARNING: any content below this statement is generated automatically. Any manual edit
|
| 1180 |
+
# will be lost when re-generating this file !
|
| 1181 |
+
#
|
| 1182 |
+
# To update the static imports, please run the following command and commit the changes.
|
| 1183 |
+
# ```
|
| 1184 |
+
# # Use script
|
| 1185 |
+
# python utils/check_static_imports.py --update
|
| 1186 |
+
#
|
| 1187 |
+
# # Or run style on codebase
|
| 1188 |
+
# make style
|
| 1189 |
+
# ```
|
| 1190 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 1191 |
+
from ._buckets import (
|
| 1192 |
+
BucketFile, # noqa: F401
|
| 1193 |
+
BucketFileMetadata, # noqa: F401
|
| 1194 |
+
BucketFolder, # noqa: F401
|
| 1195 |
+
BucketInfo, # noqa: F401
|
| 1196 |
+
BucketUrl, # noqa: F401
|
| 1197 |
+
SyncOperation, # noqa: F401
|
| 1198 |
+
SyncPlan, # noqa: F401
|
| 1199 |
+
)
|
| 1200 |
+
from ._commit_scheduler import CommitScheduler # noqa: F401
|
| 1201 |
+
from ._eval_results import (
|
| 1202 |
+
EvalResultEntry, # noqa: F401
|
| 1203 |
+
eval_result_entries_to_yaml, # noqa: F401
|
| 1204 |
+
parse_eval_result_entries, # noqa: F401
|
| 1205 |
+
)
|
| 1206 |
+
from ._inference_endpoints import (
|
| 1207 |
+
InferenceEndpoint, # noqa: F401
|
| 1208 |
+
InferenceEndpointError, # noqa: F401
|
| 1209 |
+
InferenceEndpointStatus, # noqa: F401
|
| 1210 |
+
InferenceEndpointTimeoutError, # noqa: F401
|
| 1211 |
+
InferenceEndpointType, # noqa: F401
|
| 1212 |
+
)
|
| 1213 |
+
from ._jobs_api import (
|
| 1214 |
+
JobAccelerator, # noqa: F401
|
| 1215 |
+
JobHardware, # noqa: F401
|
| 1216 |
+
JobInfo, # noqa: F401
|
| 1217 |
+
JobOwner, # noqa: F401
|
| 1218 |
+
JobStage, # noqa: F401
|
| 1219 |
+
JobStatus, # noqa: F401
|
| 1220 |
+
)
|
| 1221 |
+
from ._login import (
|
| 1222 |
+
auth_list, # noqa: F401
|
| 1223 |
+
auth_switch, # noqa: F401
|
| 1224 |
+
interpreter_login, # noqa: F401
|
| 1225 |
+
login, # noqa: F401
|
| 1226 |
+
logout, # noqa: F401
|
| 1227 |
+
notebook_login, # noqa: F401
|
| 1228 |
+
)
|
| 1229 |
+
from ._oauth import (
|
| 1230 |
+
OAuthInfo, # noqa: F401
|
| 1231 |
+
OAuthOrgInfo, # noqa: F401
|
| 1232 |
+
OAuthUserInfo, # noqa: F401
|
| 1233 |
+
attach_huggingface_oauth, # noqa: F401
|
| 1234 |
+
parse_huggingface_oauth, # noqa: F401
|
| 1235 |
+
)
|
| 1236 |
+
from ._snapshot_download import snapshot_download # noqa: F401
|
| 1237 |
+
from ._space_api import (
|
| 1238 |
+
SpaceHardware, # noqa: F401
|
| 1239 |
+
SpaceRuntime, # noqa: F401
|
| 1240 |
+
SpaceStage, # noqa: F401
|
| 1241 |
+
SpaceStorage, # noqa: F401
|
| 1242 |
+
SpaceVariable, # noqa: F401
|
| 1243 |
+
Volume, # noqa: F401
|
| 1244 |
+
)
|
| 1245 |
+
from ._tensorboard_logger import HFSummaryWriter # noqa: F401
|
| 1246 |
+
from ._webhooks_payload import (
|
| 1247 |
+
WebhookPayload, # noqa: F401
|
| 1248 |
+
WebhookPayloadComment, # noqa: F401
|
| 1249 |
+
WebhookPayloadDiscussion, # noqa: F401
|
| 1250 |
+
WebhookPayloadDiscussionChanges, # noqa: F401
|
| 1251 |
+
WebhookPayloadEvent, # noqa: F401
|
| 1252 |
+
WebhookPayloadMovedTo, # noqa: F401
|
| 1253 |
+
WebhookPayloadRepo, # noqa: F401
|
| 1254 |
+
WebhookPayloadUrl, # noqa: F401
|
| 1255 |
+
WebhookPayloadWebhook, # noqa: F401
|
| 1256 |
+
)
|
| 1257 |
+
from ._webhooks_server import (
|
| 1258 |
+
WebhooksServer, # noqa: F401
|
| 1259 |
+
webhook_endpoint, # noqa: F401
|
| 1260 |
+
)
|
| 1261 |
+
from .cli._cli_utils import (
|
| 1262 |
+
check_cli_update, # noqa: F401
|
| 1263 |
+
typer_factory, # noqa: F401
|
| 1264 |
+
)
|
| 1265 |
+
from .community import (
|
| 1266 |
+
Discussion, # noqa: F401
|
| 1267 |
+
DiscussionComment, # noqa: F401
|
| 1268 |
+
DiscussionCommit, # noqa: F401
|
| 1269 |
+
DiscussionEvent, # noqa: F401
|
| 1270 |
+
DiscussionStatusChange, # noqa: F401
|
| 1271 |
+
DiscussionTitleChange, # noqa: F401
|
| 1272 |
+
DiscussionWithDetails, # noqa: F401
|
| 1273 |
+
)
|
| 1274 |
+
from .constants import (
|
| 1275 |
+
CONFIG_NAME, # noqa: F401
|
| 1276 |
+
FLAX_WEIGHTS_NAME, # noqa: F401
|
| 1277 |
+
HUGGINGFACE_CO_URL_HOME, # noqa: F401
|
| 1278 |
+
HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401
|
| 1279 |
+
PYTORCH_WEIGHTS_NAME, # noqa: F401
|
| 1280 |
+
REPO_TYPE_DATASET, # noqa: F401
|
| 1281 |
+
REPO_TYPE_MODEL, # noqa: F401
|
| 1282 |
+
REPO_TYPE_SPACE, # noqa: F401
|
| 1283 |
+
TF2_WEIGHTS_NAME, # noqa: F401
|
| 1284 |
+
TF_WEIGHTS_NAME, # noqa: F401
|
| 1285 |
+
is_offline_mode, # noqa: F401
|
| 1286 |
+
)
|
| 1287 |
+
from .fastai_utils import (
|
| 1288 |
+
_save_pretrained_fastai, # noqa: F401
|
| 1289 |
+
from_pretrained_fastai, # noqa: F401
|
| 1290 |
+
push_to_hub_fastai, # noqa: F401
|
| 1291 |
+
)
|
| 1292 |
+
from .file_download import (
|
| 1293 |
+
_CACHED_NO_EXIST, # noqa: F401
|
| 1294 |
+
DryRunFileInfo, # noqa: F401
|
| 1295 |
+
HfFileMetadata, # noqa: F401
|
| 1296 |
+
get_hf_file_metadata, # noqa: F401
|
| 1297 |
+
hf_hub_download, # noqa: F401
|
| 1298 |
+
hf_hub_url, # noqa: F401
|
| 1299 |
+
try_to_load_from_cache, # noqa: F401
|
| 1300 |
+
)
|
| 1301 |
+
from .hf_api import (
|
| 1302 |
+
Collection, # noqa: F401
|
| 1303 |
+
CollectionItem, # noqa: F401
|
| 1304 |
+
CommitInfo, # noqa: F401
|
| 1305 |
+
CommitOperation, # noqa: F401
|
| 1306 |
+
CommitOperationAdd, # noqa: F401
|
| 1307 |
+
CommitOperationCopy, # noqa: F401
|
| 1308 |
+
CommitOperationDelete, # noqa: F401
|
| 1309 |
+
DatasetInfo, # noqa: F401
|
| 1310 |
+
DatasetLeaderboardEntry, # noqa: F401
|
| 1311 |
+
GitCommitInfo, # noqa: F401
|
| 1312 |
+
GitRefInfo, # noqa: F401
|
| 1313 |
+
GitRefs, # noqa: F401
|
| 1314 |
+
HfApi, # noqa: F401
|
| 1315 |
+
KernelInfo, # noqa: F401
|
| 1316 |
+
ModelInfo, # noqa: F401
|
| 1317 |
+
Organization, # noqa: F401
|
| 1318 |
+
RepoFile, # noqa: F401
|
| 1319 |
+
RepoFolder, # noqa: F401
|
| 1320 |
+
RepoUrl, # noqa: F401
|
| 1321 |
+
SpaceInfo, # noqa: F401
|
| 1322 |
+
User, # noqa: F401
|
| 1323 |
+
UserLikes, # noqa: F401
|
| 1324 |
+
WebhookInfo, # noqa: F401
|
| 1325 |
+
WebhookWatchedItem, # noqa: F401
|
| 1326 |
+
accept_access_request, # noqa: F401
|
| 1327 |
+
add_collection_item, # noqa: F401
|
| 1328 |
+
add_space_secret, # noqa: F401
|
| 1329 |
+
add_space_variable, # noqa: F401
|
| 1330 |
+
auth_check, # noqa: F401
|
| 1331 |
+
batch_bucket_files, # noqa: F401
|
| 1332 |
+
bucket_info, # noqa: F401
|
| 1333 |
+
cancel_access_request, # noqa: F401
|
| 1334 |
+
cancel_job, # noqa: F401
|
| 1335 |
+
change_discussion_status, # noqa: F401
|
| 1336 |
+
comment_discussion, # noqa: F401
|
| 1337 |
+
copy_files, # noqa: F401
|
| 1338 |
+
create_branch, # noqa: F401
|
| 1339 |
+
create_bucket, # noqa: F401
|
| 1340 |
+
create_collection, # noqa: F401
|
| 1341 |
+
create_commit, # noqa: F401
|
| 1342 |
+
create_discussion, # noqa: F401
|
| 1343 |
+
create_inference_endpoint, # noqa: F401
|
| 1344 |
+
create_inference_endpoint_from_catalog, # noqa: F401
|
| 1345 |
+
create_pull_request, # noqa: F401
|
| 1346 |
+
create_repo, # noqa: F401
|
| 1347 |
+
create_scheduled_job, # noqa: F401
|
| 1348 |
+
create_scheduled_uv_job, # noqa: F401
|
| 1349 |
+
create_tag, # noqa: F401
|
| 1350 |
+
create_webhook, # noqa: F401
|
| 1351 |
+
dataset_info, # noqa: F401
|
| 1352 |
+
delete_branch, # noqa: F401
|
| 1353 |
+
delete_bucket, # noqa: F401
|
| 1354 |
+
delete_collection, # noqa: F401
|
| 1355 |
+
delete_collection_item, # noqa: F401
|
| 1356 |
+
delete_file, # noqa: F401
|
| 1357 |
+
delete_folder, # noqa: F401
|
| 1358 |
+
delete_inference_endpoint, # noqa: F401
|
| 1359 |
+
delete_repo, # noqa: F401
|
| 1360 |
+
delete_scheduled_job, # noqa: F401
|
| 1361 |
+
delete_space_secret, # noqa: F401
|
| 1362 |
+
delete_space_storage, # noqa: F401
|
| 1363 |
+
delete_space_variable, # noqa: F401
|
| 1364 |
+
delete_space_volumes, # noqa: F401
|
| 1365 |
+
delete_tag, # noqa: F401
|
| 1366 |
+
delete_webhook, # noqa: F401
|
| 1367 |
+
disable_space_dev_mode, # noqa: F401
|
| 1368 |
+
disable_webhook, # noqa: F401
|
| 1369 |
+
download_bucket_files, # noqa: F401
|
| 1370 |
+
duplicate_repo, # noqa: F401
|
| 1371 |
+
duplicate_space, # noqa: F401
|
| 1372 |
+
edit_discussion_comment, # noqa: F401
|
| 1373 |
+
enable_space_dev_mode, # noqa: F401
|
| 1374 |
+
enable_webhook, # noqa: F401
|
| 1375 |
+
fetch_job_logs, # noqa: F401
|
| 1376 |
+
fetch_job_metrics, # noqa: F401
|
| 1377 |
+
file_exists, # noqa: F401
|
| 1378 |
+
get_bucket_file_metadata, # noqa: F401
|
| 1379 |
+
get_bucket_paths_info, # noqa: F401
|
| 1380 |
+
get_collection, # noqa: F401
|
| 1381 |
+
get_dataset_leaderboard, # noqa: F401
|
| 1382 |
+
get_dataset_tags, # noqa: F401
|
| 1383 |
+
get_discussion_details, # noqa: F401
|
| 1384 |
+
get_full_repo_name, # noqa: F401
|
| 1385 |
+
get_inference_endpoint, # noqa: F401
|
| 1386 |
+
get_local_safetensors_metadata, # noqa: F401
|
| 1387 |
+
get_model_tags, # noqa: F401
|
| 1388 |
+
get_organization_overview, # noqa: F401
|
| 1389 |
+
get_paths_info, # noqa: F401
|
| 1390 |
+
get_repo_discussions, # noqa: F401
|
| 1391 |
+
get_safetensors_metadata, # noqa: F401
|
| 1392 |
+
get_space_runtime, # noqa: F401
|
| 1393 |
+
get_space_variables, # noqa: F401
|
| 1394 |
+
get_user_overview, # noqa: F401
|
| 1395 |
+
get_webhook, # noqa: F401
|
| 1396 |
+
grant_access, # noqa: F401
|
| 1397 |
+
inspect_job, # noqa: F401
|
| 1398 |
+
inspect_scheduled_job, # noqa: F401
|
| 1399 |
+
kernel_info, # noqa: F401
|
| 1400 |
+
list_accepted_access_requests, # noqa: F401
|
| 1401 |
+
list_bucket_tree, # noqa: F401
|
| 1402 |
+
list_buckets, # noqa: F401
|
| 1403 |
+
list_collections, # noqa: F401
|
| 1404 |
+
list_daily_papers, # noqa: F401
|
| 1405 |
+
list_dataset_parquet_files, # noqa: F401
|
| 1406 |
+
list_datasets, # noqa: F401
|
| 1407 |
+
list_inference_catalog, # noqa: F401
|
| 1408 |
+
list_inference_endpoints, # noqa: F401
|
| 1409 |
+
list_jobs, # noqa: F401
|
| 1410 |
+
list_jobs_hardware, # noqa: F401
|
| 1411 |
+
list_lfs_files, # noqa: F401
|
| 1412 |
+
list_liked_repos, # noqa: F401
|
| 1413 |
+
list_models, # noqa: F401
|
| 1414 |
+
list_organization_followers, # noqa: F401
|
| 1415 |
+
list_organization_members, # noqa: F401
|
| 1416 |
+
list_papers, # noqa: F401
|
| 1417 |
+
list_pending_access_requests, # noqa: F401
|
| 1418 |
+
list_rejected_access_requests, # noqa: F401
|
| 1419 |
+
list_repo_commits, # noqa: F401
|
| 1420 |
+
list_repo_files, # noqa: F401
|
| 1421 |
+
list_repo_likers, # noqa: F401
|
| 1422 |
+
list_repo_refs, # noqa: F401
|
| 1423 |
+
list_repo_tree, # noqa: F401
|
| 1424 |
+
list_spaces, # noqa: F401
|
| 1425 |
+
list_user_followers, # noqa: F401
|
| 1426 |
+
list_user_following, # noqa: F401
|
| 1427 |
+
list_webhooks, # noqa: F401
|
| 1428 |
+
merge_pull_request, # noqa: F401
|
| 1429 |
+
model_info, # noqa: F401
|
| 1430 |
+
move_bucket, # noqa: F401
|
| 1431 |
+
move_repo, # noqa: F401
|
| 1432 |
+
paper_info, # noqa: F401
|
| 1433 |
+
parse_local_safetensors_file_metadata, # noqa: F401
|
| 1434 |
+
parse_safetensors_file_metadata, # noqa: F401
|
| 1435 |
+
pause_inference_endpoint, # noqa: F401
|
| 1436 |
+
pause_space, # noqa: F401
|
| 1437 |
+
permanently_delete_lfs_files, # noqa: F401
|
| 1438 |
+
preupload_lfs_files, # noqa: F401
|
| 1439 |
+
read_paper, # noqa: F401
|
| 1440 |
+
reject_access_request, # noqa: F401
|
| 1441 |
+
rename_discussion, # noqa: F401
|
| 1442 |
+
repo_exists, # noqa: F401
|
| 1443 |
+
repo_info, # noqa: F401
|
| 1444 |
+
repo_type_and_id_from_hf_id, # noqa: F401
|
| 1445 |
+
request_space_hardware, # noqa: F401
|
| 1446 |
+
request_space_storage, # noqa: F401
|
| 1447 |
+
restart_space, # noqa: F401
|
| 1448 |
+
resume_inference_endpoint, # noqa: F401
|
| 1449 |
+
resume_scheduled_job, # noqa: F401
|
| 1450 |
+
revision_exists, # noqa: F401
|
| 1451 |
+
run_as_future, # noqa: F401
|
| 1452 |
+
run_job, # noqa: F401
|
| 1453 |
+
run_uv_job, # noqa: F401
|
| 1454 |
+
scale_to_zero_inference_endpoint, # noqa: F401
|
| 1455 |
+
set_space_sleep_time, # noqa: F401
|
| 1456 |
+
set_space_volumes, # noqa: F401
|
| 1457 |
+
space_info, # noqa: F401
|
| 1458 |
+
super_squash_history, # noqa: F401
|
| 1459 |
+
suspend_scheduled_job, # noqa: F401
|
| 1460 |
+
sync_bucket, # noqa: F401
|
| 1461 |
+
unlike, # noqa: F401
|
| 1462 |
+
update_collection_item, # noqa: F401
|
| 1463 |
+
update_collection_metadata, # noqa: F401
|
| 1464 |
+
update_inference_endpoint, # noqa: F401
|
| 1465 |
+
update_repo_settings, # noqa: F401
|
| 1466 |
+
update_webhook, # noqa: F401
|
| 1467 |
+
upload_file, # noqa: F401
|
| 1468 |
+
upload_folder, # noqa: F401
|
| 1469 |
+
upload_large_folder, # noqa: F401
|
| 1470 |
+
verify_repo_checksums, # noqa: F401
|
| 1471 |
+
whoami, # noqa: F401
|
| 1472 |
+
)
|
| 1473 |
+
from .hf_file_system import (
|
| 1474 |
+
HfFileSystem, # noqa: F401
|
| 1475 |
+
HfFileSystemFile, # noqa: F401
|
| 1476 |
+
HfFileSystemResolvedPath, # noqa: F401
|
| 1477 |
+
HfFileSystemStreamFile, # noqa: F401
|
| 1478 |
+
hffs, # noqa: F401
|
| 1479 |
+
)
|
| 1480 |
+
from .hub_mixin import (
|
| 1481 |
+
ModelHubMixin, # noqa: F401
|
| 1482 |
+
PyTorchModelHubMixin, # noqa: F401
|
| 1483 |
+
)
|
| 1484 |
+
from .inference._client import (
|
| 1485 |
+
InferenceClient, # noqa: F401
|
| 1486 |
+
InferenceTimeoutError, # noqa: F401
|
| 1487 |
+
)
|
| 1488 |
+
from .inference._generated._async_client import AsyncInferenceClient # noqa: F401
|
| 1489 |
+
from .inference._generated.types import (
|
| 1490 |
+
AudioClassificationInput, # noqa: F401
|
| 1491 |
+
AudioClassificationOutputElement, # noqa: F401
|
| 1492 |
+
AudioClassificationOutputTransform, # noqa: F401
|
| 1493 |
+
AudioClassificationParameters, # noqa: F401
|
| 1494 |
+
AudioToAudioInput, # noqa: F401
|
| 1495 |
+
AudioToAudioOutputElement, # noqa: F401
|
| 1496 |
+
AutomaticSpeechRecognitionEarlyStoppingEnum, # noqa: F401
|
| 1497 |
+
AutomaticSpeechRecognitionGenerationParameters, # noqa: F401
|
| 1498 |
+
AutomaticSpeechRecognitionInput, # noqa: F401
|
| 1499 |
+
AutomaticSpeechRecognitionOutput, # noqa: F401
|
| 1500 |
+
AutomaticSpeechRecognitionOutputChunk, # noqa: F401
|
| 1501 |
+
AutomaticSpeechRecognitionParameters, # noqa: F401
|
| 1502 |
+
ChatCompletionInput, # noqa: F401
|
| 1503 |
+
ChatCompletionInputFunctionDefinition, # noqa: F401
|
| 1504 |
+
ChatCompletionInputFunctionName, # noqa: F401
|
| 1505 |
+
ChatCompletionInputGrammarType, # noqa: F401
|
| 1506 |
+
ChatCompletionInputJSONSchema, # noqa: F401
|
| 1507 |
+
ChatCompletionInputMessage, # noqa: F401
|
| 1508 |
+
ChatCompletionInputMessageChunk, # noqa: F401
|
| 1509 |
+
ChatCompletionInputMessageChunkType, # noqa: F401
|
| 1510 |
+
ChatCompletionInputResponseFormatJSONObject, # noqa: F401
|
| 1511 |
+
ChatCompletionInputResponseFormatJSONSchema, # noqa: F401
|
| 1512 |
+
ChatCompletionInputResponseFormatText, # noqa: F401
|
| 1513 |
+
ChatCompletionInputStreamOptions, # noqa: F401
|
| 1514 |
+
ChatCompletionInputTool, # noqa: F401
|
| 1515 |
+
ChatCompletionInputToolCall, # noqa: F401
|
| 1516 |
+
ChatCompletionInputToolChoiceClass, # noqa: F401
|
| 1517 |
+
ChatCompletionInputToolChoiceEnum, # noqa: F401
|
| 1518 |
+
ChatCompletionInputURL, # noqa: F401
|
| 1519 |
+
ChatCompletionOutput, # noqa: F401
|
| 1520 |
+
ChatCompletionOutputComplete, # noqa: F401
|
| 1521 |
+
ChatCompletionOutputFunctionDefinition, # noqa: F401
|
| 1522 |
+
ChatCompletionOutputLogprob, # noqa: F401
|
| 1523 |
+
ChatCompletionOutputLogprobs, # noqa: F401
|
| 1524 |
+
ChatCompletionOutputMessage, # noqa: F401
|
| 1525 |
+
ChatCompletionOutputToolCall, # noqa: F401
|
| 1526 |
+
ChatCompletionOutputTopLogprob, # noqa: F401
|
| 1527 |
+
ChatCompletionOutputUsage, # noqa: F401
|
| 1528 |
+
ChatCompletionStreamOutput, # noqa: F401
|
| 1529 |
+
ChatCompletionStreamOutputChoice, # noqa: F401
|
| 1530 |
+
ChatCompletionStreamOutputDelta, # noqa: F401
|
| 1531 |
+
ChatCompletionStreamOutputDeltaToolCall, # noqa: F401
|
| 1532 |
+
ChatCompletionStreamOutputFunction, # noqa: F401
|
| 1533 |
+
ChatCompletionStreamOutputLogprob, # noqa: F401
|
| 1534 |
+
ChatCompletionStreamOutputLogprobs, # noqa: F401
|
| 1535 |
+
ChatCompletionStreamOutputTopLogprob, # noqa: F401
|
| 1536 |
+
ChatCompletionStreamOutputUsage, # noqa: F401
|
| 1537 |
+
DepthEstimationInput, # noqa: F401
|
| 1538 |
+
DepthEstimationOutput, # noqa: F401
|
| 1539 |
+
DocumentQuestionAnsweringInput, # noqa: F401
|
| 1540 |
+
DocumentQuestionAnsweringInputData, # noqa: F401
|
| 1541 |
+
DocumentQuestionAnsweringOutputElement, # noqa: F401
|
| 1542 |
+
DocumentQuestionAnsweringParameters, # noqa: F401
|
| 1543 |
+
FeatureExtractionInput, # noqa: F401
|
| 1544 |
+
FeatureExtractionInputTruncationDirection, # noqa: F401
|
| 1545 |
+
FillMaskInput, # noqa: F401
|
| 1546 |
+
FillMaskOutputElement, # noqa: F401
|
| 1547 |
+
FillMaskParameters, # noqa: F401
|
| 1548 |
+
ImageClassificationInput, # noqa: F401
|
| 1549 |
+
ImageClassificationOutputElement, # noqa: F401
|
| 1550 |
+
ImageClassificationOutputTransform, # noqa: F401
|
| 1551 |
+
ImageClassificationParameters, # noqa: F401
|
| 1552 |
+
ImageSegmentationInput, # noqa: F401
|
| 1553 |
+
ImageSegmentationOutputElement, # noqa: F401
|
| 1554 |
+
ImageSegmentationParameters, # noqa: F401
|
| 1555 |
+
ImageSegmentationSubtask, # noqa: F401
|
| 1556 |
+
ImageTextToImageInput, # noqa: F401
|
| 1557 |
+
ImageTextToImageOutput, # noqa: F401
|
| 1558 |
+
ImageTextToImageParameters, # noqa: F401
|
| 1559 |
+
ImageTextToImageTargetSize, # noqa: F401
|
| 1560 |
+
ImageTextToVideoInput, # noqa: F401
|
| 1561 |
+
ImageTextToVideoOutput, # noqa: F401
|
| 1562 |
+
ImageTextToVideoParameters, # noqa: F401
|
| 1563 |
+
ImageTextToVideoTargetSize, # noqa: F401
|
| 1564 |
+
ImageToImageInput, # noqa: F401
|
| 1565 |
+
ImageToImageOutput, # noqa: F401
|
| 1566 |
+
ImageToImageParameters, # noqa: F401
|
| 1567 |
+
ImageToImageTargetSize, # noqa: F401
|
| 1568 |
+
ImageToTextEarlyStoppingEnum, # noqa: F401
|
| 1569 |
+
ImageToTextGenerationParameters, # noqa: F401
|
| 1570 |
+
ImageToTextInput, # noqa: F401
|
| 1571 |
+
ImageToTextOutput, # noqa: F401
|
| 1572 |
+
ImageToTextParameters, # noqa: F401
|
| 1573 |
+
ImageToVideoInput, # noqa: F401
|
| 1574 |
+
ImageToVideoOutput, # noqa: F401
|
| 1575 |
+
ImageToVideoParameters, # noqa: F401
|
| 1576 |
+
ImageToVideoTargetSize, # noqa: F401
|
| 1577 |
+
ObjectDetectionBoundingBox, # noqa: F401
|
| 1578 |
+
ObjectDetectionInput, # noqa: F401
|
| 1579 |
+
ObjectDetectionOutputElement, # noqa: F401
|
| 1580 |
+
ObjectDetectionParameters, # noqa: F401
|
| 1581 |
+
Padding, # noqa: F401
|
| 1582 |
+
QuestionAnsweringInput, # noqa: F401
|
| 1583 |
+
QuestionAnsweringInputData, # noqa: F401
|
| 1584 |
+
QuestionAnsweringOutputElement, # noqa: F401
|
| 1585 |
+
QuestionAnsweringParameters, # noqa: F401
|
| 1586 |
+
SentenceSimilarityInput, # noqa: F401
|
| 1587 |
+
SentenceSimilarityInputData, # noqa: F401
|
| 1588 |
+
SummarizationInput, # noqa: F401
|
| 1589 |
+
SummarizationOutput, # noqa: F401
|
| 1590 |
+
SummarizationParameters, # noqa: F401
|
| 1591 |
+
SummarizationTruncationStrategy, # noqa: F401
|
| 1592 |
+
TableQuestionAnsweringInput, # noqa: F401
|
| 1593 |
+
TableQuestionAnsweringInputData, # noqa: F401
|
| 1594 |
+
TableQuestionAnsweringOutputElement, # noqa: F401
|
| 1595 |
+
TableQuestionAnsweringParameters, # noqa: F401
|
| 1596 |
+
Text2TextGenerationInput, # noqa: F401
|
| 1597 |
+
Text2TextGenerationOutput, # noqa: F401
|
| 1598 |
+
Text2TextGenerationParameters, # noqa: F401
|
| 1599 |
+
Text2TextGenerationTruncationStrategy, # noqa: F401
|
| 1600 |
+
TextClassificationInput, # noqa: F401
|
| 1601 |
+
TextClassificationOutputElement, # noqa: F401
|
| 1602 |
+
TextClassificationOutputTransform, # noqa: F401
|
| 1603 |
+
TextClassificationParameters, # noqa: F401
|
| 1604 |
+
TextGenerationInput, # noqa: F401
|
| 1605 |
+
TextGenerationInputGenerateParameters, # noqa: F401
|
| 1606 |
+
TextGenerationInputGrammarType, # noqa: F401
|
| 1607 |
+
TextGenerationOutput, # noqa: F401
|
| 1608 |
+
TextGenerationOutputBestOfSequence, # noqa: F401
|
| 1609 |
+
TextGenerationOutputDetails, # noqa: F401
|
| 1610 |
+
TextGenerationOutputFinishReason, # noqa: F401
|
| 1611 |
+
TextGenerationOutputPrefillToken, # noqa: F401
|
| 1612 |
+
TextGenerationOutputToken, # noqa: F401
|
| 1613 |
+
TextGenerationStreamOutput, # noqa: F401
|
| 1614 |
+
TextGenerationStreamOutputStreamDetails, # noqa: F401
|
| 1615 |
+
TextGenerationStreamOutputToken, # noqa: F401
|
| 1616 |
+
TextToAudioEarlyStoppingEnum, # noqa: F401
|
| 1617 |
+
TextToAudioGenerationParameters, # noqa: F401
|
| 1618 |
+
TextToAudioInput, # noqa: F401
|
| 1619 |
+
TextToAudioOutput, # noqa: F401
|
| 1620 |
+
TextToAudioParameters, # noqa: F401
|
| 1621 |
+
TextToImageInput, # noqa: F401
|
| 1622 |
+
TextToImageOutput, # noqa: F401
|
| 1623 |
+
TextToImageParameters, # noqa: F401
|
| 1624 |
+
TextToSpeechEarlyStoppingEnum, # noqa: F401
|
| 1625 |
+
TextToSpeechGenerationParameters, # noqa: F401
|
| 1626 |
+
TextToSpeechInput, # noqa: F401
|
| 1627 |
+
TextToSpeechOutput, # noqa: F401
|
| 1628 |
+
TextToSpeechParameters, # noqa: F401
|
| 1629 |
+
TextToVideoInput, # noqa: F401
|
| 1630 |
+
TextToVideoOutput, # noqa: F401
|
| 1631 |
+
TextToVideoParameters, # noqa: F401
|
| 1632 |
+
TokenClassificationAggregationStrategy, # noqa: F401
|
| 1633 |
+
TokenClassificationInput, # noqa: F401
|
| 1634 |
+
TokenClassificationOutputElement, # noqa: F401
|
| 1635 |
+
TokenClassificationParameters, # noqa: F401
|
| 1636 |
+
TranslationInput, # noqa: F401
|
| 1637 |
+
TranslationOutput, # noqa: F401
|
| 1638 |
+
TranslationParameters, # noqa: F401
|
| 1639 |
+
TranslationTruncationStrategy, # noqa: F401
|
| 1640 |
+
TypeEnum, # noqa: F401
|
| 1641 |
+
VideoClassificationInput, # noqa: F401
|
| 1642 |
+
VideoClassificationOutputElement, # noqa: F401
|
| 1643 |
+
VideoClassificationOutputTransform, # noqa: F401
|
| 1644 |
+
VideoClassificationParameters, # noqa: F401
|
| 1645 |
+
VisualQuestionAnsweringInput, # noqa: F401
|
| 1646 |
+
VisualQuestionAnsweringInputData, # noqa: F401
|
| 1647 |
+
VisualQuestionAnsweringOutputElement, # noqa: F401
|
| 1648 |
+
VisualQuestionAnsweringParameters, # noqa: F401
|
| 1649 |
+
ZeroShotClassificationInput, # noqa: F401
|
| 1650 |
+
ZeroShotClassificationOutputElement, # noqa: F401
|
| 1651 |
+
ZeroShotClassificationParameters, # noqa: F401
|
| 1652 |
+
ZeroShotImageClassificationInput, # noqa: F401
|
| 1653 |
+
ZeroShotImageClassificationOutputElement, # noqa: F401
|
| 1654 |
+
ZeroShotImageClassificationParameters, # noqa: F401
|
| 1655 |
+
ZeroShotObjectDetectionBoundingBox, # noqa: F401
|
| 1656 |
+
ZeroShotObjectDetectionInput, # noqa: F401
|
| 1657 |
+
ZeroShotObjectDetectionOutputElement, # noqa: F401
|
| 1658 |
+
ZeroShotObjectDetectionParameters, # noqa: F401
|
| 1659 |
+
)
|
| 1660 |
+
from .inference._mcp.agent import Agent # noqa: F401
|
| 1661 |
+
from .inference._mcp.mcp_client import MCPClient # noqa: F401
|
| 1662 |
+
from .repocard import (
|
| 1663 |
+
DatasetCard, # noqa: F401
|
| 1664 |
+
ModelCard, # noqa: F401
|
| 1665 |
+
RepoCard, # noqa: F401
|
| 1666 |
+
SpaceCard, # noqa: F401
|
| 1667 |
+
metadata_eval_result, # noqa: F401
|
| 1668 |
+
metadata_load, # noqa: F401
|
| 1669 |
+
metadata_save, # noqa: F401
|
| 1670 |
+
metadata_update, # noqa: F401
|
| 1671 |
+
)
|
| 1672 |
+
from .repocard_data import (
|
| 1673 |
+
CardData, # noqa: F401
|
| 1674 |
+
DatasetCardData, # noqa: F401
|
| 1675 |
+
EvalResult, # noqa: F401
|
| 1676 |
+
ModelCardData, # noqa: F401
|
| 1677 |
+
SpaceCardData, # noqa: F401
|
| 1678 |
+
)
|
| 1679 |
+
from .serialization import (
|
| 1680 |
+
StateDictSplit, # noqa: F401
|
| 1681 |
+
get_torch_storage_id, # noqa: F401
|
| 1682 |
+
get_torch_storage_size, # noqa: F401
|
| 1683 |
+
load_state_dict_from_file, # noqa: F401
|
| 1684 |
+
load_torch_model, # noqa: F401
|
| 1685 |
+
save_torch_model, # noqa: F401
|
| 1686 |
+
save_torch_state_dict, # noqa: F401
|
| 1687 |
+
split_state_dict_into_shards_factory, # noqa: F401
|
| 1688 |
+
split_torch_state_dict_into_shards, # noqa: F401
|
| 1689 |
+
)
|
| 1690 |
+
from .serialization._dduf import (
|
| 1691 |
+
DDUFEntry, # noqa: F401
|
| 1692 |
+
export_entries_as_dduf, # noqa: F401
|
| 1693 |
+
export_folder_as_dduf, # noqa: F401
|
| 1694 |
+
read_dduf_file, # noqa: F401
|
| 1695 |
+
)
|
| 1696 |
+
from .utils import (
|
| 1697 |
+
ASYNC_CLIENT_FACTORY_T, # noqa: F401
|
| 1698 |
+
CLIENT_FACTORY_T, # noqa: F401
|
| 1699 |
+
CachedFileInfo, # noqa: F401
|
| 1700 |
+
CachedRepoInfo, # noqa: F401
|
| 1701 |
+
CachedRevisionInfo, # noqa: F401
|
| 1702 |
+
CacheNotFound, # noqa: F401
|
| 1703 |
+
CorruptedCacheException, # noqa: F401
|
| 1704 |
+
DeleteCacheStrategy, # noqa: F401
|
| 1705 |
+
HFCacheInfo, # noqa: F401
|
| 1706 |
+
cached_assets_path, # noqa: F401
|
| 1707 |
+
close_session, # noqa: F401
|
| 1708 |
+
dump_environment_info, # noqa: F401
|
| 1709 |
+
get_async_session, # noqa: F401
|
| 1710 |
+
get_session, # noqa: F401
|
| 1711 |
+
get_token, # noqa: F401
|
| 1712 |
+
hf_raise_for_status, # noqa: F401
|
| 1713 |
+
logging, # noqa: F401
|
| 1714 |
+
scan_cache_dir, # noqa: F401
|
| 1715 |
+
set_async_client_factory, # noqa: F401
|
| 1716 |
+
set_client_factory, # noqa: F401
|
| 1717 |
+
)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_buckets.py
ADDED
|
@@ -0,0 +1,1193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Shared logic for bucket operations.
|
| 15 |
+
|
| 16 |
+
This module contains the core buckets logic used by both the CLI and the Python API.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import fnmatch
|
| 20 |
+
import json
|
| 21 |
+
import mimetypes
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
from collections.abc import Iterator
|
| 26 |
+
from dataclasses import dataclass, field
|
| 27 |
+
from datetime import datetime, timezone
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import TYPE_CHECKING, Any, Literal
|
| 30 |
+
|
| 31 |
+
from . import constants, logging
|
| 32 |
+
from .errors import BucketNotFoundError
|
| 33 |
+
from .utils import XetFileData, disable_progress_bars, enable_progress_bars, parse_datetime
|
| 34 |
+
from .utils._terminal import StatusLine
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if TYPE_CHECKING:
|
| 38 |
+
from .hf_api import HfApi
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
BUCKET_PREFIX = "hf://buckets/"
|
| 45 |
+
_SYNC_TIME_WINDOW_MS = 1000 # 1s safety-window for file modification time comparisons
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# =============================================================================
|
| 49 |
+
# Bucket data structures
|
| 50 |
+
# =============================================================================
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _split_bucket_id_and_prefix(path: str) -> tuple[str, str]:
|
| 54 |
+
"""Split 'namespace/name(/optional/prefix)' into ('namespace/name', 'prefix').
|
| 55 |
+
|
| 56 |
+
Returns (bucket_id, prefix) where prefix may be empty string.
|
| 57 |
+
Raises ValueError if path doesn't contain at least namespace/name.
|
| 58 |
+
"""
|
| 59 |
+
parts = path.split("/", 2)
|
| 60 |
+
if len(parts) < 2 or not parts[0] or not parts[1]:
|
| 61 |
+
raise ValueError(f"Invalid bucket path: '{path}'. Expected format: namespace/bucket_name")
|
| 62 |
+
bucket_id = f"{parts[0]}/{parts[1]}"
|
| 63 |
+
prefix = parts[2] if len(parts) > 2 else ""
|
| 64 |
+
return bucket_id, prefix
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass
|
| 68 |
+
class BucketInfo:
|
| 69 |
+
"""
|
| 70 |
+
Contains information about a bucket on the Hub. This object is returned by [`bucket_info`] and [`list_buckets`].
|
| 71 |
+
|
| 72 |
+
Attributes:
|
| 73 |
+
id (`str`):
|
| 74 |
+
ID of the bucket.
|
| 75 |
+
private (`bool`):
|
| 76 |
+
Is the bucket private.
|
| 77 |
+
created_at (`datetime`):
|
| 78 |
+
Date of creation of the bucket on the Hub.
|
| 79 |
+
size (`int`):
|
| 80 |
+
Size of the bucket in bytes.
|
| 81 |
+
total_files (`int`):
|
| 82 |
+
Total number of files in the bucket.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
id: str
|
| 86 |
+
private: bool
|
| 87 |
+
created_at: datetime
|
| 88 |
+
size: int
|
| 89 |
+
total_files: int
|
| 90 |
+
|
| 91 |
+
def __init__(self, **kwargs):
|
| 92 |
+
self.id = kwargs.pop("id")
|
| 93 |
+
self.private = kwargs.pop("private")
|
| 94 |
+
self.created_at = parse_datetime(kwargs.pop("createdAt"))
|
| 95 |
+
self.size = kwargs.pop("size")
|
| 96 |
+
self.total_files = kwargs.pop("totalFiles")
|
| 97 |
+
self.__dict__.update(**kwargs)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@dataclass
|
| 101 |
+
class _BucketAddFile:
|
| 102 |
+
source: str | Path | bytes
|
| 103 |
+
destination: str
|
| 104 |
+
|
| 105 |
+
xet_hash: str | None = field(default=None)
|
| 106 |
+
size: int | None = field(default=None)
|
| 107 |
+
mtime: int = field(init=False)
|
| 108 |
+
content_type: str | None = field(init=False)
|
| 109 |
+
|
| 110 |
+
def __post_init__(self) -> None:
|
| 111 |
+
self.content_type = None
|
| 112 |
+
if isinstance(self.source, (str, Path)): # guess content type from source path
|
| 113 |
+
self.content_type = mimetypes.guess_type(self.source)[0]
|
| 114 |
+
if self.content_type is None: # or default to destination path content type
|
| 115 |
+
self.content_type = mimetypes.guess_type(self.destination)[0]
|
| 116 |
+
|
| 117 |
+
self.mtime = int(
|
| 118 |
+
os.path.getmtime(self.source) * 1000 if not isinstance(self.source, bytes) else time.time() * 1000
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class _BucketCopyFile:
|
| 124 |
+
destination: str
|
| 125 |
+
xet_hash: str
|
| 126 |
+
source_repo_type: str # "model", "dataset", "space", "bucket"
|
| 127 |
+
source_repo_id: str
|
| 128 |
+
size: int | None = field(default=None)
|
| 129 |
+
mtime: int = field(init=False)
|
| 130 |
+
content_type: str | None = field(init=False)
|
| 131 |
+
|
| 132 |
+
def __post_init__(self) -> None:
|
| 133 |
+
self.content_type = mimetypes.guess_type(self.destination)[0]
|
| 134 |
+
self.mtime = int(time.time() * 1000)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@dataclass
|
| 138 |
+
class _BucketDeleteFile:
|
| 139 |
+
path: str
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@dataclass(frozen=True)
|
| 143 |
+
class BucketFileMetadata:
|
| 144 |
+
"""Data structure containing information about a file in a bucket.
|
| 145 |
+
|
| 146 |
+
Returned by [`get_bucket_file_metadata`].
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
size (`int`):
|
| 150 |
+
Size of the file in bytes.
|
| 151 |
+
xet_file_data (`XetFileData`):
|
| 152 |
+
Xet information for the file (hash and refresh route).
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
size: int
|
| 156 |
+
xet_file_data: XetFileData
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@dataclass
|
| 160 |
+
class BucketUrl:
|
| 161 |
+
"""Describes a bucket URL on the Hub.
|
| 162 |
+
|
| 163 |
+
`BucketUrl` is returned by [`create_bucket`]. At initialization, the URL is parsed to populate properties:
|
| 164 |
+
- endpoint (`str`)
|
| 165 |
+
- namespace (`str`)
|
| 166 |
+
- bucket_id (`str`)
|
| 167 |
+
- url (`str`)
|
| 168 |
+
- handle (`str`)
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
url (`str`):
|
| 172 |
+
String value of the bucket url.
|
| 173 |
+
endpoint (`str`, *optional*):
|
| 174 |
+
Endpoint of the Hub. Defaults to <https://huggingface.co>.
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
url: str
|
| 178 |
+
endpoint: str = ""
|
| 179 |
+
namespace: str = field(init=False)
|
| 180 |
+
bucket_id: str = field(init=False)
|
| 181 |
+
handle: str = field(init=False)
|
| 182 |
+
|
| 183 |
+
def __post_init__(self) -> None:
|
| 184 |
+
self.endpoint = self.endpoint or constants.ENDPOINT
|
| 185 |
+
|
| 186 |
+
# Parse URL: expected format is `{endpoint}/buckets/{namespace}/{bucket_name}`
|
| 187 |
+
url_path = self.url.replace(self.endpoint, "").strip("/")
|
| 188 |
+
# Remove leading "buckets/" prefix
|
| 189 |
+
if url_path.startswith("buckets/"):
|
| 190 |
+
url_path = url_path[len("buckets/") :]
|
| 191 |
+
bucket_id, prefix = _split_bucket_id_and_prefix(url_path)
|
| 192 |
+
if prefix:
|
| 193 |
+
raise ValueError(f"Unable to parse bucket URL: {self.url}")
|
| 194 |
+
self.namespace = bucket_id.split("/")[0]
|
| 195 |
+
self.bucket_id = bucket_id
|
| 196 |
+
|
| 197 |
+
self.handle = f"hf://buckets/{self.bucket_id}"
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@dataclass
|
| 201 |
+
class BucketFile:
|
| 202 |
+
"""
|
| 203 |
+
Contains information about a file in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
|
| 204 |
+
|
| 205 |
+
Similar to [`RepoFile`] but for files in buckets.
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
type: Literal["file"]
|
| 209 |
+
path: str
|
| 210 |
+
size: int
|
| 211 |
+
xet_hash: str
|
| 212 |
+
mtime: datetime | None
|
| 213 |
+
uploaded_at: datetime | None
|
| 214 |
+
|
| 215 |
+
def __init__(self, **kwargs):
|
| 216 |
+
self.type = kwargs.pop("type")
|
| 217 |
+
self.path = kwargs.pop("path")
|
| 218 |
+
self.size = kwargs.pop("size")
|
| 219 |
+
self.xet_hash = kwargs.pop("xetHash")
|
| 220 |
+
mtime = kwargs.pop("mtime", None)
|
| 221 |
+
self.mtime = parse_datetime(mtime) if mtime else None
|
| 222 |
+
uploaded_at = kwargs.pop("uploadedAt", None)
|
| 223 |
+
self.uploaded_at = parse_datetime(uploaded_at) if uploaded_at else None
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@dataclass
|
| 227 |
+
class BucketFolder:
|
| 228 |
+
"""
|
| 229 |
+
Contains information about a directory in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
|
| 230 |
+
|
| 231 |
+
Similar to [`RepoFolder`] but for directories in buckets.
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
type: Literal["directory"]
|
| 235 |
+
path: str
|
| 236 |
+
uploaded_at: datetime | None
|
| 237 |
+
|
| 238 |
+
def __init__(self, **kwargs):
|
| 239 |
+
self.type = kwargs.pop("type")
|
| 240 |
+
self.path = kwargs.pop("path")
|
| 241 |
+
uploaded_at = kwargs.pop("uploadedAt", None) or kwargs.pop("uploaded_at", None)
|
| 242 |
+
self.uploaded_at = (
|
| 243 |
+
(uploaded_at if isinstance(uploaded_at, datetime) else parse_datetime(uploaded_at))
|
| 244 |
+
if uploaded_at
|
| 245 |
+
else None
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# =============================================================================
|
| 250 |
+
# Bucket path parsing
|
| 251 |
+
# =============================================================================
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _parse_bucket_path(path: str) -> tuple[str, str]:
|
| 255 |
+
"""Parse a bucket path like hf://buckets/namespace/bucket_name/prefix into (bucket_id, prefix).
|
| 256 |
+
|
| 257 |
+
Returns:
|
| 258 |
+
tuple: (bucket_id, prefix) where bucket_id is "namespace/bucket_name" and prefix may be empty string.
|
| 259 |
+
"""
|
| 260 |
+
if not path.startswith(BUCKET_PREFIX):
|
| 261 |
+
raise ValueError(f"Invalid bucket path: {path}. Must start with {BUCKET_PREFIX}")
|
| 262 |
+
return _split_bucket_id_and_prefix(path.removeprefix(BUCKET_PREFIX))
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _is_bucket_path(path: str) -> bool:
|
| 266 |
+
"""Check if a path is a bucket path."""
|
| 267 |
+
return path.startswith(BUCKET_PREFIX)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
# =============================================================================
|
| 271 |
+
# Sync data structures
|
| 272 |
+
# =============================================================================
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@dataclass
|
| 276 |
+
class SyncOperation:
|
| 277 |
+
"""Represents a sync operation to be performed."""
|
| 278 |
+
|
| 279 |
+
action: Literal["upload", "download", "delete", "skip"]
|
| 280 |
+
path: str
|
| 281 |
+
size: int | None = None
|
| 282 |
+
reason: str = ""
|
| 283 |
+
local_mtime: str | None = None
|
| 284 |
+
remote_mtime: str | None = None
|
| 285 |
+
bucket_file: BucketFile | None = None # BucketFile when available (not serialized to plan file)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@dataclass
|
| 289 |
+
class SyncPlan:
|
| 290 |
+
"""Represents a complete sync plan."""
|
| 291 |
+
|
| 292 |
+
source: str
|
| 293 |
+
dest: str
|
| 294 |
+
timestamp: str
|
| 295 |
+
operations: list[SyncOperation] = field(default_factory=list)
|
| 296 |
+
|
| 297 |
+
def summary(self) -> dict[str, int | str]:
|
| 298 |
+
uploads = sum(1 for op in self.operations if op.action == "upload")
|
| 299 |
+
downloads = sum(1 for op in self.operations if op.action == "download")
|
| 300 |
+
deletes = sum(1 for op in self.operations if op.action == "delete")
|
| 301 |
+
skips = sum(1 for op in self.operations if op.action == "skip")
|
| 302 |
+
total_size = sum(op.size or 0 for op in self.operations if op.action in ("upload", "download"))
|
| 303 |
+
return {
|
| 304 |
+
"uploads": uploads,
|
| 305 |
+
"downloads": downloads,
|
| 306 |
+
"deletes": deletes,
|
| 307 |
+
"skips": skips,
|
| 308 |
+
"total_size": total_size,
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# =============================================================================
|
| 313 |
+
# Filter matching
|
| 314 |
+
# =============================================================================
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class FilterMatcher:
|
| 318 |
+
"""Matches file paths against include/exclude patterns."""
|
| 319 |
+
|
| 320 |
+
def __init__(
|
| 321 |
+
self,
|
| 322 |
+
include_patterns: list[str] | None = None,
|
| 323 |
+
exclude_patterns: list[str] | None = None,
|
| 324 |
+
filter_rules: list[tuple[str, str]] | None = None,
|
| 325 |
+
):
|
| 326 |
+
"""Initialize the filter matcher.
|
| 327 |
+
|
| 328 |
+
Args:
|
| 329 |
+
include_patterns: Patterns to include (from --include)
|
| 330 |
+
exclude_patterns: Patterns to exclude (from --exclude)
|
| 331 |
+
filter_rules: Rules from filter file as list of ("+"/"-", pattern) tuples
|
| 332 |
+
"""
|
| 333 |
+
self.include_patterns = include_patterns or []
|
| 334 |
+
self.exclude_patterns = exclude_patterns or []
|
| 335 |
+
self.filter_rules = filter_rules or []
|
| 336 |
+
|
| 337 |
+
def matches(self, path: str) -> bool:
|
| 338 |
+
"""Check if a path should be included based on the filter rules.
|
| 339 |
+
|
| 340 |
+
Filtering rules:
|
| 341 |
+
- Filters are evaluated in order, first matching rule decides
|
| 342 |
+
- If no rules match, include by default (unless include patterns are specified)
|
| 343 |
+
"""
|
| 344 |
+
# First check filter rules from file (in order)
|
| 345 |
+
for sign, pattern in self.filter_rules:
|
| 346 |
+
if fnmatch.fnmatch(path, pattern):
|
| 347 |
+
return sign == "+"
|
| 348 |
+
|
| 349 |
+
# Then check CLI patterns
|
| 350 |
+
for pattern in self.exclude_patterns:
|
| 351 |
+
if fnmatch.fnmatch(path, pattern):
|
| 352 |
+
return False
|
| 353 |
+
|
| 354 |
+
for pattern in self.include_patterns:
|
| 355 |
+
if fnmatch.fnmatch(path, pattern):
|
| 356 |
+
return True
|
| 357 |
+
|
| 358 |
+
# If include patterns were specified but none matched, exclude
|
| 359 |
+
if self.include_patterns:
|
| 360 |
+
return False
|
| 361 |
+
|
| 362 |
+
# Default: include
|
| 363 |
+
return True
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _parse_filter_file(filter_file: str) -> list[tuple[str, str]]:
|
| 367 |
+
"""Parse a filter file and return a list of (sign, pattern) tuples.
|
| 368 |
+
|
| 369 |
+
Filter file format:
|
| 370 |
+
- Lines starting with "+" are include patterns
|
| 371 |
+
- Lines starting with "-" are exclude patterns
|
| 372 |
+
- Empty lines and lines starting with "#" are ignored
|
| 373 |
+
"""
|
| 374 |
+
rules = []
|
| 375 |
+
with open(filter_file) as f:
|
| 376 |
+
for line in f:
|
| 377 |
+
line = line.strip()
|
| 378 |
+
if not line or line.startswith("#"):
|
| 379 |
+
continue
|
| 380 |
+
if line.startswith("+"):
|
| 381 |
+
rules.append(("+", line[1:].strip()))
|
| 382 |
+
elif line.startswith("-"):
|
| 383 |
+
rules.append(("-", line[1:].strip()))
|
| 384 |
+
else:
|
| 385 |
+
# Default to include if no prefix
|
| 386 |
+
rules.append(("+", line))
|
| 387 |
+
return rules
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
# =============================================================================
|
| 391 |
+
# File listing
|
| 392 |
+
# =============================================================================
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def _list_local_files(local_path: str) -> Iterator[tuple[str, int, float]]:
|
| 396 |
+
"""List all files in a local directory.
|
| 397 |
+
|
| 398 |
+
Yields:
|
| 399 |
+
tuple: (relative_path, size, mtime_ms) for each file
|
| 400 |
+
"""
|
| 401 |
+
local_path = os.path.abspath(local_path)
|
| 402 |
+
if not os.path.isdir(local_path):
|
| 403 |
+
raise ValueError(f"Local path must be a directory: {local_path}")
|
| 404 |
+
|
| 405 |
+
for root, _, files in os.walk(local_path):
|
| 406 |
+
for filename in files:
|
| 407 |
+
full_path = os.path.join(root, filename)
|
| 408 |
+
rel_path = os.path.relpath(full_path, local_path)
|
| 409 |
+
# Normalize to forward slashes for consistency
|
| 410 |
+
rel_path = rel_path.replace(os.sep, "/")
|
| 411 |
+
size = os.path.getsize(full_path)
|
| 412 |
+
mtime_ms = os.path.getmtime(full_path) * 1000
|
| 413 |
+
yield rel_path, size, mtime_ms
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def _list_remote_files(api: "HfApi", bucket_id: str, prefix: str) -> Iterator[tuple[str, int, float, Any]]:
|
| 417 |
+
"""List all files in a bucket with a given prefix.
|
| 418 |
+
|
| 419 |
+
Yields:
|
| 420 |
+
tuple: (relative_path, size, mtime_ms, bucket_file) for each file.
|
| 421 |
+
bucket_file is the BucketFile object from list_bucket_tree.
|
| 422 |
+
"""
|
| 423 |
+
for item in api.list_bucket_tree(bucket_id, prefix=prefix or None, recursive=True):
|
| 424 |
+
if isinstance(item, BucketFolder):
|
| 425 |
+
continue
|
| 426 |
+
path = item.path
|
| 427 |
+
# Remove prefix from path to get relative path
|
| 428 |
+
# Only strip prefix if it's followed by "/" (directory boundary) or is exact match
|
| 429 |
+
if prefix:
|
| 430 |
+
if path.startswith(prefix + "/"):
|
| 431 |
+
rel_path = path[len(prefix) + 1 :]
|
| 432 |
+
elif path == prefix:
|
| 433 |
+
# Exact match: the file IS the prefix (e.g., single file download)
|
| 434 |
+
rel_path = path.rsplit("/", 1)[-1] if "/" in path else path
|
| 435 |
+
else:
|
| 436 |
+
# Path doesn't match prefix pattern (e.g., "submarine.txt" for prefix "sub")
|
| 437 |
+
# Skip this file - it was returned by the API but doesn't belong to this prefix
|
| 438 |
+
continue
|
| 439 |
+
else:
|
| 440 |
+
rel_path = path
|
| 441 |
+
mtime_ms = item.mtime.timestamp() * 1000 if item.mtime else 0
|
| 442 |
+
yield rel_path, item.size, mtime_ms, item
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
# =============================================================================
|
| 446 |
+
# Sync plan computation
|
| 447 |
+
# =============================================================================
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _mtime_to_iso(mtime_ms: float) -> str:
|
| 451 |
+
"""Convert mtime in milliseconds to ISO format string."""
|
| 452 |
+
return datetime.fromtimestamp(mtime_ms / 1000, tz=timezone.utc).isoformat()
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def _compare_files_for_sync(
|
| 456 |
+
*,
|
| 457 |
+
path: str,
|
| 458 |
+
action: Literal["upload", "download"],
|
| 459 |
+
source_size: int,
|
| 460 |
+
source_mtime: float,
|
| 461 |
+
dest_size: int,
|
| 462 |
+
dest_mtime: float,
|
| 463 |
+
source_newer_label: str,
|
| 464 |
+
dest_newer_label: str,
|
| 465 |
+
ignore_sizes: bool,
|
| 466 |
+
ignore_times: bool,
|
| 467 |
+
ignore_existing: bool,
|
| 468 |
+
bucket_file: Any | None = None,
|
| 469 |
+
) -> SyncOperation:
|
| 470 |
+
"""Compare source and dest files and return the appropriate sync operation.
|
| 471 |
+
|
| 472 |
+
This is a unified helper for both upload and download directions.
|
| 473 |
+
|
| 474 |
+
Args:
|
| 475 |
+
path: Relative file path
|
| 476 |
+
action: "upload" or "download"
|
| 477 |
+
source_size: Size of the source file (bytes)
|
| 478 |
+
source_mtime: Mtime of the source file (milliseconds)
|
| 479 |
+
dest_size: Size of the destination file (bytes)
|
| 480 |
+
dest_mtime: Mtime of the destination file (milliseconds)
|
| 481 |
+
source_newer_label: Label when source is newer (e.g., "local newer" or "remote newer")
|
| 482 |
+
dest_newer_label: Label when dest is newer (e.g., "remote newer" or "local newer")
|
| 483 |
+
ignore_sizes: Only compare mtime
|
| 484 |
+
ignore_times: Only compare size
|
| 485 |
+
ignore_existing: Skip files that exist on receiver
|
| 486 |
+
bucket_file: BucketFile object (for downloads only)
|
| 487 |
+
|
| 488 |
+
Returns:
|
| 489 |
+
SyncOperation describing the action to take
|
| 490 |
+
"""
|
| 491 |
+
local_mtime_iso = _mtime_to_iso(source_mtime if action == "upload" else dest_mtime)
|
| 492 |
+
remote_mtime_iso = _mtime_to_iso(dest_mtime if action == "upload" else source_mtime)
|
| 493 |
+
|
| 494 |
+
base_kwargs: dict[str, Any] = {
|
| 495 |
+
"path": path,
|
| 496 |
+
"size": source_size,
|
| 497 |
+
"local_mtime": local_mtime_iso,
|
| 498 |
+
"remote_mtime": remote_mtime_iso,
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
if ignore_existing:
|
| 502 |
+
return SyncOperation(action="skip", reason="exists on receiver (--ignore-existing)", **base_kwargs)
|
| 503 |
+
|
| 504 |
+
size_differs = source_size != dest_size
|
| 505 |
+
source_newer = (source_mtime - dest_mtime) > _SYNC_TIME_WINDOW_MS
|
| 506 |
+
|
| 507 |
+
if ignore_sizes:
|
| 508 |
+
if source_newer:
|
| 509 |
+
return SyncOperation(action=action, reason=source_newer_label, bucket_file=bucket_file, **base_kwargs)
|
| 510 |
+
else:
|
| 511 |
+
dest_newer = (dest_mtime - source_mtime) > _SYNC_TIME_WINDOW_MS
|
| 512 |
+
skip_reason = dest_newer_label if dest_newer else "same mtime"
|
| 513 |
+
return SyncOperation(action="skip", reason=skip_reason, **base_kwargs)
|
| 514 |
+
elif ignore_times:
|
| 515 |
+
if size_differs:
|
| 516 |
+
return SyncOperation(action=action, reason="size differs", bucket_file=bucket_file, **base_kwargs)
|
| 517 |
+
else:
|
| 518 |
+
return SyncOperation(action="skip", reason="same size", **base_kwargs)
|
| 519 |
+
else:
|
| 520 |
+
if size_differs or source_newer:
|
| 521 |
+
reason = "size differs" if size_differs else source_newer_label
|
| 522 |
+
return SyncOperation(action=action, reason=reason, bucket_file=bucket_file, **base_kwargs)
|
| 523 |
+
else:
|
| 524 |
+
return SyncOperation(action="skip", reason="identical", **base_kwargs)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def _compute_sync_plan(
|
| 528 |
+
source: str,
|
| 529 |
+
dest: str,
|
| 530 |
+
api: "HfApi",
|
| 531 |
+
delete: bool = False,
|
| 532 |
+
ignore_times: bool = False,
|
| 533 |
+
ignore_sizes: bool = False,
|
| 534 |
+
existing: bool = False,
|
| 535 |
+
ignore_existing: bool = False,
|
| 536 |
+
filter_matcher: FilterMatcher | None = None,
|
| 537 |
+
status: Any | None = None,
|
| 538 |
+
) -> SyncPlan:
|
| 539 |
+
"""Compute the sync plan by comparing source and destination.
|
| 540 |
+
|
| 541 |
+
Returns:
|
| 542 |
+
SyncPlan with all operations to be performed
|
| 543 |
+
"""
|
| 544 |
+
filter_matcher = filter_matcher or FilterMatcher()
|
| 545 |
+
is_upload = not _is_bucket_path(source) and _is_bucket_path(dest)
|
| 546 |
+
is_download = _is_bucket_path(source) and not _is_bucket_path(dest)
|
| 547 |
+
|
| 548 |
+
if not is_upload and not is_download:
|
| 549 |
+
raise ValueError("One of source or dest must be a bucket path (hf://buckets/...) and the other must be local.")
|
| 550 |
+
|
| 551 |
+
plan = SyncPlan(
|
| 552 |
+
source=source,
|
| 553 |
+
dest=dest,
|
| 554 |
+
timestamp=datetime.now(timezone.utc).isoformat(),
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
remote_total: int | None = None
|
| 558 |
+
if is_upload:
|
| 559 |
+
# Local -> Remote
|
| 560 |
+
local_path = os.path.abspath(source)
|
| 561 |
+
bucket_id, prefix = _parse_bucket_path(dest)
|
| 562 |
+
|
| 563 |
+
if not os.path.isdir(local_path):
|
| 564 |
+
raise ValueError(f"Source must be a directory: {local_path}")
|
| 565 |
+
|
| 566 |
+
# Get local and remote file lists
|
| 567 |
+
local_files = {}
|
| 568 |
+
for rel_path, size, mtime_ms in _list_local_files(local_path):
|
| 569 |
+
if filter_matcher.matches(rel_path):
|
| 570 |
+
local_files[rel_path] = (size, mtime_ms)
|
| 571 |
+
if status:
|
| 572 |
+
status.update(f"Scanning local directory ({len(local_files)} files)")
|
| 573 |
+
if status:
|
| 574 |
+
status.done(f"Scanning local directory ({len(local_files)} files)")
|
| 575 |
+
|
| 576 |
+
remote_files = {}
|
| 577 |
+
if status:
|
| 578 |
+
try:
|
| 579 |
+
remote_total = api.bucket_info(bucket_id).total_files
|
| 580 |
+
except Exception:
|
| 581 |
+
pass
|
| 582 |
+
try:
|
| 583 |
+
for rel_path, size, mtime_ms, _ in _list_remote_files(api, bucket_id, prefix):
|
| 584 |
+
if filter_matcher.matches(rel_path):
|
| 585 |
+
remote_files[rel_path] = (size, mtime_ms)
|
| 586 |
+
if status:
|
| 587 |
+
total_str = f"/{remote_total}" if remote_total is not None else ""
|
| 588 |
+
status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)")
|
| 589 |
+
except BucketNotFoundError:
|
| 590 |
+
# Bucket doesn't exist yet - this is expected for new uploads
|
| 591 |
+
logger.debug(f"Bucket '{bucket_id}' not found, treating as empty.")
|
| 592 |
+
if status:
|
| 593 |
+
status.done(f"Scanning remote bucket ({len(remote_files)} files)")
|
| 594 |
+
|
| 595 |
+
# Compare files
|
| 596 |
+
all_paths = set(local_files.keys()) | set(remote_files.keys())
|
| 597 |
+
if status:
|
| 598 |
+
status.done(f"Comparing files ({len(all_paths)} paths)")
|
| 599 |
+
for path in sorted(all_paths):
|
| 600 |
+
local_info = local_files.get(path)
|
| 601 |
+
remote_info = remote_files.get(path)
|
| 602 |
+
|
| 603 |
+
if local_info and not remote_info:
|
| 604 |
+
# New file
|
| 605 |
+
if existing:
|
| 606 |
+
# --existing: skip new files
|
| 607 |
+
plan.operations.append(
|
| 608 |
+
SyncOperation(
|
| 609 |
+
action="skip",
|
| 610 |
+
path=path,
|
| 611 |
+
size=local_info[0],
|
| 612 |
+
reason="new file (--existing)",
|
| 613 |
+
local_mtime=_mtime_to_iso(local_info[1]),
|
| 614 |
+
)
|
| 615 |
+
)
|
| 616 |
+
else:
|
| 617 |
+
plan.operations.append(
|
| 618 |
+
SyncOperation(
|
| 619 |
+
action="upload",
|
| 620 |
+
path=path,
|
| 621 |
+
size=local_info[0],
|
| 622 |
+
reason="new file",
|
| 623 |
+
local_mtime=_mtime_to_iso(local_info[1]),
|
| 624 |
+
)
|
| 625 |
+
)
|
| 626 |
+
elif local_info and remote_info:
|
| 627 |
+
# File exists in both - use helper to determine action
|
| 628 |
+
local_size, local_mtime = local_info
|
| 629 |
+
remote_size, remote_mtime = remote_info
|
| 630 |
+
plan.operations.append(
|
| 631 |
+
_compare_files_for_sync(
|
| 632 |
+
path=path,
|
| 633 |
+
action="upload",
|
| 634 |
+
source_size=local_size,
|
| 635 |
+
source_mtime=local_mtime,
|
| 636 |
+
dest_size=remote_size,
|
| 637 |
+
dest_mtime=remote_mtime,
|
| 638 |
+
source_newer_label="local newer",
|
| 639 |
+
dest_newer_label="remote newer",
|
| 640 |
+
ignore_sizes=ignore_sizes,
|
| 641 |
+
ignore_times=ignore_times,
|
| 642 |
+
ignore_existing=ignore_existing,
|
| 643 |
+
)
|
| 644 |
+
)
|
| 645 |
+
elif not local_info and remote_info and delete:
|
| 646 |
+
# File only in remote and --delete mode
|
| 647 |
+
plan.operations.append(
|
| 648 |
+
SyncOperation(
|
| 649 |
+
action="delete",
|
| 650 |
+
path=path,
|
| 651 |
+
size=remote_info[0],
|
| 652 |
+
reason="not in source (--delete)",
|
| 653 |
+
remote_mtime=_mtime_to_iso(remote_info[1]),
|
| 654 |
+
)
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
else:
|
| 658 |
+
# Remote -> Local (download)
|
| 659 |
+
bucket_id, prefix = _parse_bucket_path(source)
|
| 660 |
+
local_path = os.path.abspath(dest)
|
| 661 |
+
|
| 662 |
+
# Get remote and local file lists
|
| 663 |
+
remote_files = {}
|
| 664 |
+
bucket_file_map: dict[str, Any] = {}
|
| 665 |
+
if status:
|
| 666 |
+
try:
|
| 667 |
+
remote_total = api.bucket_info(bucket_id).total_files
|
| 668 |
+
except Exception:
|
| 669 |
+
pass
|
| 670 |
+
for rel_path, size, mtime_ms, bucket_file in _list_remote_files(api, bucket_id, prefix):
|
| 671 |
+
if filter_matcher.matches(rel_path):
|
| 672 |
+
remote_files[rel_path] = (size, mtime_ms)
|
| 673 |
+
bucket_file_map[rel_path] = bucket_file
|
| 674 |
+
if status:
|
| 675 |
+
total_str = f"/{remote_total}" if remote_total is not None else ""
|
| 676 |
+
status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)")
|
| 677 |
+
if status:
|
| 678 |
+
status.done(f"Scanning remote bucket ({len(remote_files)} files)")
|
| 679 |
+
|
| 680 |
+
local_files = {}
|
| 681 |
+
if os.path.isdir(local_path):
|
| 682 |
+
for rel_path, size, mtime_ms in _list_local_files(local_path):
|
| 683 |
+
if filter_matcher.matches(rel_path):
|
| 684 |
+
local_files[rel_path] = (size, mtime_ms)
|
| 685 |
+
if status:
|
| 686 |
+
status.update(f"Scanning local directory ({len(local_files)} files)")
|
| 687 |
+
if status:
|
| 688 |
+
status.done(f"Scanning local directory ({len(local_files)} files)")
|
| 689 |
+
|
| 690 |
+
# Compare files
|
| 691 |
+
all_paths = set(remote_files.keys()) | set(local_files.keys())
|
| 692 |
+
if status:
|
| 693 |
+
status.done(f"Comparing files ({len(all_paths)} paths)")
|
| 694 |
+
for path in sorted(all_paths):
|
| 695 |
+
remote_info = remote_files.get(path)
|
| 696 |
+
local_info = local_files.get(path)
|
| 697 |
+
|
| 698 |
+
if remote_info and not local_info:
|
| 699 |
+
# New file
|
| 700 |
+
if existing:
|
| 701 |
+
# --existing: skip new files
|
| 702 |
+
plan.operations.append(
|
| 703 |
+
SyncOperation(
|
| 704 |
+
action="skip",
|
| 705 |
+
path=path,
|
| 706 |
+
size=remote_info[0],
|
| 707 |
+
reason="new file (--existing)",
|
| 708 |
+
remote_mtime=_mtime_to_iso(remote_info[1]),
|
| 709 |
+
)
|
| 710 |
+
)
|
| 711 |
+
else:
|
| 712 |
+
plan.operations.append(
|
| 713 |
+
SyncOperation(
|
| 714 |
+
action="download",
|
| 715 |
+
path=path,
|
| 716 |
+
size=remote_info[0],
|
| 717 |
+
reason="new file",
|
| 718 |
+
remote_mtime=_mtime_to_iso(remote_info[1]),
|
| 719 |
+
bucket_file=bucket_file_map.get(path),
|
| 720 |
+
)
|
| 721 |
+
)
|
| 722 |
+
elif remote_info and local_info:
|
| 723 |
+
# File exists in both - use helper to determine action
|
| 724 |
+
remote_size, remote_mtime = remote_info
|
| 725 |
+
local_size, local_mtime = local_info
|
| 726 |
+
plan.operations.append(
|
| 727 |
+
_compare_files_for_sync(
|
| 728 |
+
path=path,
|
| 729 |
+
action="download",
|
| 730 |
+
source_size=remote_size,
|
| 731 |
+
source_mtime=remote_mtime,
|
| 732 |
+
dest_size=local_size,
|
| 733 |
+
dest_mtime=local_mtime,
|
| 734 |
+
source_newer_label="remote newer",
|
| 735 |
+
dest_newer_label="local newer",
|
| 736 |
+
ignore_sizes=ignore_sizes,
|
| 737 |
+
ignore_times=ignore_times,
|
| 738 |
+
ignore_existing=ignore_existing,
|
| 739 |
+
bucket_file=bucket_file_map.get(path),
|
| 740 |
+
)
|
| 741 |
+
)
|
| 742 |
+
elif not remote_info and local_info and delete:
|
| 743 |
+
# File only in local and --delete mode
|
| 744 |
+
plan.operations.append(
|
| 745 |
+
SyncOperation(
|
| 746 |
+
action="delete",
|
| 747 |
+
path=path,
|
| 748 |
+
size=local_info[0],
|
| 749 |
+
reason="not in source (--delete)",
|
| 750 |
+
local_mtime=_mtime_to_iso(local_info[1]),
|
| 751 |
+
)
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
return plan
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
# =============================================================================
|
| 758 |
+
# Plan serialization
|
| 759 |
+
# =============================================================================
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def _write_plan(plan: SyncPlan, f) -> None:
|
| 763 |
+
"""Write a sync plan as JSONL to a file-like object."""
|
| 764 |
+
# Write header
|
| 765 |
+
header = {
|
| 766 |
+
"type": "header",
|
| 767 |
+
"source": plan.source,
|
| 768 |
+
"dest": plan.dest,
|
| 769 |
+
"timestamp": plan.timestamp,
|
| 770 |
+
"summary": plan.summary(),
|
| 771 |
+
}
|
| 772 |
+
f.write(json.dumps(header) + "\n")
|
| 773 |
+
|
| 774 |
+
# Write operations
|
| 775 |
+
for op in plan.operations:
|
| 776 |
+
op_dict: dict[str, Any] = {
|
| 777 |
+
"type": "operation",
|
| 778 |
+
"action": op.action,
|
| 779 |
+
"path": op.path,
|
| 780 |
+
"reason": op.reason,
|
| 781 |
+
}
|
| 782 |
+
if op.size is not None:
|
| 783 |
+
op_dict["size"] = op.size
|
| 784 |
+
if op.local_mtime is not None:
|
| 785 |
+
op_dict["local_mtime"] = op.local_mtime
|
| 786 |
+
if op.remote_mtime is not None:
|
| 787 |
+
op_dict["remote_mtime"] = op.remote_mtime
|
| 788 |
+
f.write(json.dumps(op_dict) + "\n")
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def _save_plan(plan: SyncPlan, plan_file: str) -> None:
|
| 792 |
+
"""Save a sync plan to a JSONL file."""
|
| 793 |
+
with open(plan_file, "w") as f:
|
| 794 |
+
_write_plan(plan, f)
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
def _load_plan(plan_file: str) -> SyncPlan:
|
| 798 |
+
"""Load a sync plan from a JSONL file."""
|
| 799 |
+
with open(plan_file) as f:
|
| 800 |
+
lines = f.readlines()
|
| 801 |
+
|
| 802 |
+
if not lines:
|
| 803 |
+
raise ValueError(f"Empty plan file: {plan_file}")
|
| 804 |
+
|
| 805 |
+
# Parse header
|
| 806 |
+
header = json.loads(lines[0])
|
| 807 |
+
if header.get("type") != "header":
|
| 808 |
+
raise ValueError("Invalid plan file: expected header as first line")
|
| 809 |
+
|
| 810 |
+
plan = SyncPlan(
|
| 811 |
+
source=header["source"],
|
| 812 |
+
dest=header["dest"],
|
| 813 |
+
timestamp=header["timestamp"],
|
| 814 |
+
)
|
| 815 |
+
|
| 816 |
+
# Parse operations
|
| 817 |
+
for line in lines[1:]:
|
| 818 |
+
op_dict = json.loads(line)
|
| 819 |
+
if op_dict.get("type") != "operation":
|
| 820 |
+
continue
|
| 821 |
+
plan.operations.append(
|
| 822 |
+
SyncOperation(
|
| 823 |
+
action=op_dict["action"],
|
| 824 |
+
path=op_dict["path"],
|
| 825 |
+
size=op_dict.get("size"),
|
| 826 |
+
reason=op_dict.get("reason", ""),
|
| 827 |
+
local_mtime=op_dict.get("local_mtime"),
|
| 828 |
+
remote_mtime=op_dict.get("remote_mtime"),
|
| 829 |
+
)
|
| 830 |
+
)
|
| 831 |
+
|
| 832 |
+
return plan
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
# =============================================================================
|
| 836 |
+
# Plan execution
|
| 837 |
+
# =============================================================================
|
| 838 |
+
|
| 839 |
+
|
| 840 |
+
def _execute_plan(plan: SyncPlan, api: "HfApi", verbose: bool = False, status: Any | None = None) -> None:
|
| 841 |
+
"""Execute a sync plan."""
|
| 842 |
+
is_upload = not _is_bucket_path(plan.source) and _is_bucket_path(plan.dest)
|
| 843 |
+
is_download = _is_bucket_path(plan.source) and not _is_bucket_path(plan.dest)
|
| 844 |
+
|
| 845 |
+
if is_upload:
|
| 846 |
+
local_path = os.path.abspath(plan.source)
|
| 847 |
+
bucket_id, prefix = _parse_bucket_path(plan.dest)
|
| 848 |
+
prefix = prefix.rstrip("/") # Avoid double slashes in remote paths
|
| 849 |
+
|
| 850 |
+
# Collect operations
|
| 851 |
+
add_files: list[tuple[str | Path | bytes, str]] = []
|
| 852 |
+
delete_paths: list[str] = []
|
| 853 |
+
|
| 854 |
+
for op in plan.operations:
|
| 855 |
+
match op.action:
|
| 856 |
+
case "upload":
|
| 857 |
+
local_file = os.path.join(local_path, op.path)
|
| 858 |
+
remote_path = f"{prefix}/{op.path}" if prefix else op.path
|
| 859 |
+
if verbose:
|
| 860 |
+
print(f" Uploading: {op.path} ({op.reason})")
|
| 861 |
+
add_files.append((local_file, remote_path))
|
| 862 |
+
case "delete":
|
| 863 |
+
remote_path = f"{prefix}/{op.path}" if prefix else op.path
|
| 864 |
+
if verbose:
|
| 865 |
+
print(f" Deleting: {op.path} ({op.reason})")
|
| 866 |
+
delete_paths.append(remote_path)
|
| 867 |
+
case "skip" if verbose:
|
| 868 |
+
print(f" Skipping: {op.path} ({op.reason})")
|
| 869 |
+
|
| 870 |
+
# Execute batch operations
|
| 871 |
+
if add_files or delete_paths:
|
| 872 |
+
if status:
|
| 873 |
+
parts = []
|
| 874 |
+
if add_files:
|
| 875 |
+
parts.append(f"uploading {len(add_files)} files")
|
| 876 |
+
if delete_paths:
|
| 877 |
+
parts.append(f"deleting {len(delete_paths)} files")
|
| 878 |
+
status.done(", ".join(parts).capitalize())
|
| 879 |
+
api.batch_bucket_files(
|
| 880 |
+
bucket_id,
|
| 881 |
+
add=add_files or None,
|
| 882 |
+
delete=delete_paths or None,
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
elif is_download:
|
| 886 |
+
bucket_id, prefix = _parse_bucket_path(plan.source)
|
| 887 |
+
prefix = prefix.rstrip("/") # Avoid double slashes in remote paths
|
| 888 |
+
local_path = os.path.abspath(plan.dest)
|
| 889 |
+
|
| 890 |
+
# Ensure local directory exists
|
| 891 |
+
os.makedirs(local_path, exist_ok=True)
|
| 892 |
+
|
| 893 |
+
# Collect download operations
|
| 894 |
+
download_files: list[tuple[str | BucketFile, str | Path]] = []
|
| 895 |
+
delete_files: list[str] = []
|
| 896 |
+
|
| 897 |
+
for op in plan.operations:
|
| 898 |
+
if op.action == "download":
|
| 899 |
+
local_file = os.path.join(local_path, op.path)
|
| 900 |
+
# Ensure parent directory exists
|
| 901 |
+
os.makedirs(os.path.dirname(local_file), exist_ok=True)
|
| 902 |
+
if verbose:
|
| 903 |
+
print(f" Downloading: {op.path} ({op.reason})")
|
| 904 |
+
# Use BucketFile when available (avoids extra metadata fetch per file)
|
| 905 |
+
if op.bucket_file is not None:
|
| 906 |
+
download_files.append((op.bucket_file, local_file))
|
| 907 |
+
else:
|
| 908 |
+
remote_path = f"{prefix}/{op.path}" if prefix else op.path
|
| 909 |
+
download_files.append((remote_path, local_file))
|
| 910 |
+
elif op.action == "delete":
|
| 911 |
+
local_file = os.path.join(local_path, op.path)
|
| 912 |
+
if verbose:
|
| 913 |
+
print(f" Deleting: {op.path} ({op.reason})")
|
| 914 |
+
delete_files.append(local_file)
|
| 915 |
+
elif op.action == "skip" and verbose:
|
| 916 |
+
print(f" Skipping: {op.path} ({op.reason})")
|
| 917 |
+
|
| 918 |
+
# Execute downloads
|
| 919 |
+
if len(download_files) > 0:
|
| 920 |
+
if status:
|
| 921 |
+
status.done(f"Downloading {len(download_files)} files")
|
| 922 |
+
api.download_bucket_files(bucket_id, download_files)
|
| 923 |
+
|
| 924 |
+
# Execute deletes
|
| 925 |
+
if status and delete_files:
|
| 926 |
+
status.done(f"Deleting {len(delete_files)} local files")
|
| 927 |
+
for file_path in delete_files:
|
| 928 |
+
if os.path.exists(file_path):
|
| 929 |
+
os.remove(file_path)
|
| 930 |
+
# Remove empty parent directories
|
| 931 |
+
parent = os.path.dirname(file_path)
|
| 932 |
+
while parent != local_path:
|
| 933 |
+
try:
|
| 934 |
+
os.rmdir(parent)
|
| 935 |
+
parent = os.path.dirname(parent)
|
| 936 |
+
except OSError:
|
| 937 |
+
break
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
def _print_plan_summary(plan: SyncPlan) -> None:
|
| 941 |
+
"""Print a summary of the sync plan."""
|
| 942 |
+
summary = plan.summary()
|
| 943 |
+
print(f"Sync plan: {plan.source} -> {plan.dest}")
|
| 944 |
+
print(f" Uploads: {summary['uploads']}")
|
| 945 |
+
print(f" Downloads: {summary['downloads']}")
|
| 946 |
+
print(f" Deletes: {summary['deletes']}")
|
| 947 |
+
print(f" Skips: {summary['skips']}")
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
# =============================================================================
|
| 951 |
+
# Public sync function (Python API)
|
| 952 |
+
# =============================================================================
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
def sync_bucket_internal(
|
| 956 |
+
source: str | None = None,
|
| 957 |
+
dest: str | None = None,
|
| 958 |
+
*,
|
| 959 |
+
api: "HfApi",
|
| 960 |
+
delete: bool = False,
|
| 961 |
+
ignore_times: bool = False,
|
| 962 |
+
ignore_sizes: bool = False,
|
| 963 |
+
existing: bool = False,
|
| 964 |
+
ignore_existing: bool = False,
|
| 965 |
+
include: list[str] | None = None,
|
| 966 |
+
exclude: list[str] | None = None,
|
| 967 |
+
filter_from: str | None = None,
|
| 968 |
+
plan: str | None = None,
|
| 969 |
+
apply: str | None = None,
|
| 970 |
+
dry_run: bool = False,
|
| 971 |
+
verbose: bool = False,
|
| 972 |
+
quiet: bool = False,
|
| 973 |
+
token: bool | str | None = None,
|
| 974 |
+
) -> SyncPlan:
|
| 975 |
+
"""Sync files between a local directory and a bucket.
|
| 976 |
+
|
| 977 |
+
This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path
|
| 978 |
+
(``hf://buckets/...``) and the other must be a local directory path.
|
| 979 |
+
|
| 980 |
+
Args:
|
| 981 |
+
source (`str`, *optional*):
|
| 982 |
+
Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
|
| 983 |
+
Required unless using ``apply``.
|
| 984 |
+
dest (`str`, *optional*):
|
| 985 |
+
Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
|
| 986 |
+
Required unless using ``apply``.
|
| 987 |
+
api ([`HfApi`]):
|
| 988 |
+
The HfApi instance to use for API calls.
|
| 989 |
+
delete (`bool`, *optional*, defaults to `False`):
|
| 990 |
+
Delete destination files not present in source.
|
| 991 |
+
ignore_times (`bool`, *optional*, defaults to `False`):
|
| 992 |
+
Skip files only based on size, ignoring modification times.
|
| 993 |
+
ignore_sizes (`bool`, *optional*, defaults to `False`):
|
| 994 |
+
Skip files only based on modification times, ignoring sizes.
|
| 995 |
+
existing (`bool`, *optional*, defaults to `False`):
|
| 996 |
+
Skip creating new files on receiver (only update existing files).
|
| 997 |
+
ignore_existing (`bool`, *optional*, defaults to `False`):
|
| 998 |
+
Skip updating files that exist on receiver (only create new files).
|
| 999 |
+
include (`list[str]`, *optional*):
|
| 1000 |
+
Include files matching patterns (fnmatch-style).
|
| 1001 |
+
exclude (`list[str]`, *optional*):
|
| 1002 |
+
Exclude files matching patterns (fnmatch-style).
|
| 1003 |
+
filter_from (`str`, *optional*):
|
| 1004 |
+
Path to a filter file with include/exclude rules.
|
| 1005 |
+
plan (`str`, *optional*):
|
| 1006 |
+
Save sync plan to this JSONL file instead of executing.
|
| 1007 |
+
apply (`str`, *optional*):
|
| 1008 |
+
Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed.
|
| 1009 |
+
dry_run (`bool`, *optional*, defaults to `False`):
|
| 1010 |
+
Print sync plan to stdout as JSONL without executing.
|
| 1011 |
+
verbose (`bool`, *optional*, defaults to `False`):
|
| 1012 |
+
Show detailed per-file operations.
|
| 1013 |
+
quiet (`bool`, *optional*, defaults to `False`):
|
| 1014 |
+
Suppress all output and progress bars.
|
| 1015 |
+
token (Union[bool, str, None], optional):
|
| 1016 |
+
A valid user access token. If not provided, the locally saved token will be used.
|
| 1017 |
+
|
| 1018 |
+
Returns:
|
| 1019 |
+
[`SyncPlan`]: The computed (or loaded) sync plan.
|
| 1020 |
+
|
| 1021 |
+
Raises:
|
| 1022 |
+
`ValueError`: If arguments are invalid (e.g., both paths are remote, conflicting options).
|
| 1023 |
+
|
| 1024 |
+
Example:
|
| 1025 |
+
```python
|
| 1026 |
+
>>> from huggingface_hub import HfApi
|
| 1027 |
+
>>> api = HfApi()
|
| 1028 |
+
|
| 1029 |
+
# Upload local directory to bucket
|
| 1030 |
+
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
|
| 1031 |
+
|
| 1032 |
+
# Download bucket to local directory
|
| 1033 |
+
>>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
|
| 1034 |
+
|
| 1035 |
+
# Sync with delete and filtering
|
| 1036 |
+
>>> api.sync_bucket(
|
| 1037 |
+
... "./data",
|
| 1038 |
+
... "hf://buckets/username/my-bucket",
|
| 1039 |
+
... delete=True,
|
| 1040 |
+
... include=["*.safetensors"],
|
| 1041 |
+
... )
|
| 1042 |
+
|
| 1043 |
+
# Dry run: preview what would be synced
|
| 1044 |
+
>>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
|
| 1045 |
+
>>> plan.summary()
|
| 1046 |
+
{'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
|
| 1047 |
+
|
| 1048 |
+
# Save plan for review, then apply
|
| 1049 |
+
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
|
| 1050 |
+
>>> api.sync_bucket(apply="sync-plan.jsonl")
|
| 1051 |
+
```
|
| 1052 |
+
"""
|
| 1053 |
+
# Build API with token if needed
|
| 1054 |
+
if token is not None:
|
| 1055 |
+
from .hf_api import HfApi
|
| 1056 |
+
|
| 1057 |
+
api = HfApi(token=token)
|
| 1058 |
+
# --- Apply mode ---
|
| 1059 |
+
if apply:
|
| 1060 |
+
if source or dest:
|
| 1061 |
+
raise ValueError("Cannot specify source/dest when using apply.")
|
| 1062 |
+
if plan is not None:
|
| 1063 |
+
raise ValueError("Cannot specify both plan and apply.")
|
| 1064 |
+
if delete:
|
| 1065 |
+
raise ValueError("Cannot specify delete when using apply.")
|
| 1066 |
+
if ignore_times:
|
| 1067 |
+
raise ValueError("Cannot specify ignore_times when using apply.")
|
| 1068 |
+
if ignore_sizes:
|
| 1069 |
+
raise ValueError("Cannot specify ignore_sizes when using apply.")
|
| 1070 |
+
if include:
|
| 1071 |
+
raise ValueError("Cannot specify include when using apply.")
|
| 1072 |
+
if exclude:
|
| 1073 |
+
raise ValueError("Cannot specify exclude when using apply.")
|
| 1074 |
+
if filter_from:
|
| 1075 |
+
raise ValueError("Cannot specify filter_from when using apply.")
|
| 1076 |
+
if existing:
|
| 1077 |
+
raise ValueError("Cannot specify existing when using apply.")
|
| 1078 |
+
if ignore_existing:
|
| 1079 |
+
raise ValueError("Cannot specify ignore_existing when using apply.")
|
| 1080 |
+
if dry_run:
|
| 1081 |
+
raise ValueError("Cannot specify dry_run when using apply.")
|
| 1082 |
+
|
| 1083 |
+
sync_plan = _load_plan(apply)
|
| 1084 |
+
status = StatusLine(enabled=not quiet)
|
| 1085 |
+
if not quiet:
|
| 1086 |
+
_print_plan_summary(sync_plan)
|
| 1087 |
+
print("Executing plan...")
|
| 1088 |
+
|
| 1089 |
+
if quiet:
|
| 1090 |
+
disable_progress_bars()
|
| 1091 |
+
try:
|
| 1092 |
+
_execute_plan(sync_plan, api, verbose=verbose, status=status)
|
| 1093 |
+
finally:
|
| 1094 |
+
if quiet:
|
| 1095 |
+
enable_progress_bars()
|
| 1096 |
+
|
| 1097 |
+
if not quiet:
|
| 1098 |
+
print("Sync completed.")
|
| 1099 |
+
|
| 1100 |
+
return sync_plan
|
| 1101 |
+
|
| 1102 |
+
# --- Normal mode ---
|
| 1103 |
+
if not source or not dest:
|
| 1104 |
+
raise ValueError("Both source and dest are required (unless using apply).")
|
| 1105 |
+
|
| 1106 |
+
source_is_bucket = _is_bucket_path(source)
|
| 1107 |
+
dest_is_bucket = _is_bucket_path(dest)
|
| 1108 |
+
|
| 1109 |
+
if source_is_bucket and dest_is_bucket:
|
| 1110 |
+
raise ValueError("Remote to remote sync is not supported. One path must be local.")
|
| 1111 |
+
|
| 1112 |
+
if not source_is_bucket and not dest_is_bucket:
|
| 1113 |
+
raise ValueError("One of source or dest must be a bucket path (hf://buckets/...).")
|
| 1114 |
+
|
| 1115 |
+
if ignore_times and ignore_sizes:
|
| 1116 |
+
raise ValueError("Cannot specify both ignore_times and ignore_sizes.")
|
| 1117 |
+
|
| 1118 |
+
if existing and ignore_existing:
|
| 1119 |
+
raise ValueError("Cannot specify both existing and ignore_existing.")
|
| 1120 |
+
|
| 1121 |
+
if dry_run and plan:
|
| 1122 |
+
raise ValueError("Cannot specify both dry_run and plan.")
|
| 1123 |
+
|
| 1124 |
+
# Validate local path
|
| 1125 |
+
if source_is_bucket:
|
| 1126 |
+
if os.path.exists(dest) and not os.path.isdir(dest):
|
| 1127 |
+
raise ValueError(f"Destination must be a directory: {dest}")
|
| 1128 |
+
else:
|
| 1129 |
+
if not os.path.isdir(source):
|
| 1130 |
+
raise ValueError(f"Source must be an existing directory: {source}")
|
| 1131 |
+
|
| 1132 |
+
# Build filter matcher
|
| 1133 |
+
filter_rules = None
|
| 1134 |
+
if filter_from:
|
| 1135 |
+
filter_rules = _parse_filter_file(filter_from)
|
| 1136 |
+
|
| 1137 |
+
filter_matcher = FilterMatcher(
|
| 1138 |
+
include_patterns=include,
|
| 1139 |
+
exclude_patterns=exclude,
|
| 1140 |
+
filter_rules=filter_rules,
|
| 1141 |
+
)
|
| 1142 |
+
|
| 1143 |
+
# Compute sync plan
|
| 1144 |
+
status = StatusLine(enabled=not quiet and not dry_run)
|
| 1145 |
+
sync_plan = _compute_sync_plan(
|
| 1146 |
+
source=source,
|
| 1147 |
+
dest=dest,
|
| 1148 |
+
api=api,
|
| 1149 |
+
delete=delete,
|
| 1150 |
+
ignore_times=ignore_times,
|
| 1151 |
+
ignore_sizes=ignore_sizes,
|
| 1152 |
+
existing=existing,
|
| 1153 |
+
ignore_existing=ignore_existing,
|
| 1154 |
+
filter_matcher=filter_matcher,
|
| 1155 |
+
status=status,
|
| 1156 |
+
)
|
| 1157 |
+
|
| 1158 |
+
if dry_run:
|
| 1159 |
+
_write_plan(sync_plan, sys.stdout)
|
| 1160 |
+
return sync_plan
|
| 1161 |
+
|
| 1162 |
+
if plan:
|
| 1163 |
+
_save_plan(sync_plan, plan)
|
| 1164 |
+
if not quiet:
|
| 1165 |
+
_print_plan_summary(sync_plan)
|
| 1166 |
+
print(f"Plan saved to: {plan}")
|
| 1167 |
+
return sync_plan
|
| 1168 |
+
|
| 1169 |
+
# Execute plan
|
| 1170 |
+
if not quiet:
|
| 1171 |
+
_print_plan_summary(sync_plan)
|
| 1172 |
+
|
| 1173 |
+
summary = sync_plan.summary()
|
| 1174 |
+
if summary["uploads"] == 0 and summary["downloads"] == 0 and summary["deletes"] == 0:
|
| 1175 |
+
if not quiet:
|
| 1176 |
+
print("Nothing to sync.")
|
| 1177 |
+
return sync_plan
|
| 1178 |
+
|
| 1179 |
+
if not quiet:
|
| 1180 |
+
print("Syncing...")
|
| 1181 |
+
|
| 1182 |
+
if quiet:
|
| 1183 |
+
disable_progress_bars()
|
| 1184 |
+
try:
|
| 1185 |
+
_execute_plan(sync_plan, api, verbose=verbose, status=status)
|
| 1186 |
+
finally:
|
| 1187 |
+
if quiet:
|
| 1188 |
+
enable_progress_bars()
|
| 1189 |
+
|
| 1190 |
+
if not quiet:
|
| 1191 |
+
print("Sync completed.")
|
| 1192 |
+
|
| 1193 |
+
return sync_plan
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_commit_api.py
ADDED
|
@@ -0,0 +1,976 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
"""
|
| 4 |
+
|
| 5 |
+
import base64
|
| 6 |
+
import io
|
| 7 |
+
import os
|
| 8 |
+
import warnings
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from collections.abc import Iterable, Iterator
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from dataclasses import dataclass, field
|
| 13 |
+
from itertools import groupby
|
| 14 |
+
from pathlib import Path, PurePosixPath
|
| 15 |
+
from typing import TYPE_CHECKING, Any, BinaryIO, Literal, Union
|
| 16 |
+
|
| 17 |
+
from tqdm.contrib.concurrent import thread_map
|
| 18 |
+
|
| 19 |
+
from . import constants
|
| 20 |
+
from .errors import EntryNotFoundError, HfHubHTTPError, XetAuthorizationError, XetRefreshTokenError
|
| 21 |
+
from .file_download import hf_hub_url
|
| 22 |
+
from .lfs import UploadInfo, lfs_upload, post_lfs_batch_info
|
| 23 |
+
from .utils import (
|
| 24 |
+
FORBIDDEN_FOLDERS,
|
| 25 |
+
XetTokenType,
|
| 26 |
+
are_progress_bars_disabled,
|
| 27 |
+
chunk_iterable,
|
| 28 |
+
fetch_xet_connection_info_from_repo_info,
|
| 29 |
+
get_session,
|
| 30 |
+
hf_raise_for_status,
|
| 31 |
+
http_backoff,
|
| 32 |
+
logging,
|
| 33 |
+
sha,
|
| 34 |
+
tqdm_stream_file,
|
| 35 |
+
validate_hf_hub_args,
|
| 36 |
+
)
|
| 37 |
+
from .utils import tqdm as hf_tqdm
|
| 38 |
+
from .utils._runtime import is_xet_available
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if TYPE_CHECKING:
|
| 42 |
+
from .hf_api import RepoFile
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
logger = logging.get_logger(__name__)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
UploadMode = Literal["lfs", "regular"]
|
| 49 |
+
|
| 50 |
+
# Max is 1,000 per request on the Hub for HfApi.get_paths_info
|
| 51 |
+
# Otherwise we get:
|
| 52 |
+
# HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters
|
| 53 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1503
|
| 54 |
+
FETCH_LFS_BATCH_SIZE = 500
|
| 55 |
+
|
| 56 |
+
UPLOAD_BATCH_MAX_NUM_FILES = 256
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@dataclass
|
| 60 |
+
class CommitOperationDelete:
|
| 61 |
+
"""
|
| 62 |
+
Data structure holding necessary info to delete a file or a folder from a repository
|
| 63 |
+
on the Hub.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
path_in_repo (`str`):
|
| 67 |
+
Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
|
| 68 |
+
for a file or `"checkpoints/1fec34a/"` for a folder.
|
| 69 |
+
is_folder (`bool` or `Literal["auto"]`, *optional*)
|
| 70 |
+
Whether the Delete Operation applies to a folder or not. If "auto", the path
|
| 71 |
+
type (file or folder) is guessed automatically by looking if path ends with
|
| 72 |
+
a "/" (folder) or not (file). To explicitly set the path type, you can set
|
| 73 |
+
`is_folder=True` or `is_folder=False`.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
path_in_repo: str
|
| 77 |
+
is_folder: bool | Literal["auto"] = "auto"
|
| 78 |
+
|
| 79 |
+
def __post_init__(self):
|
| 80 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
| 81 |
+
|
| 82 |
+
if self.is_folder == "auto":
|
| 83 |
+
self.is_folder = self.path_in_repo.endswith("/")
|
| 84 |
+
if not isinstance(self.is_folder, bool):
|
| 85 |
+
raise ValueError(
|
| 86 |
+
f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@dataclass
|
| 91 |
+
class CommitOperationCopy:
|
| 92 |
+
"""
|
| 93 |
+
Data structure holding necessary info to copy a file in a repository on the Hub.
|
| 94 |
+
|
| 95 |
+
Limitations:
|
| 96 |
+
- Only LFS files can be copied. To copy a regular file, you need to download it locally and re-upload it
|
| 97 |
+
- Cross-repository copies are not supported.
|
| 98 |
+
|
| 99 |
+
Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
src_path_in_repo (`str`):
|
| 103 |
+
Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`.
|
| 104 |
+
path_in_repo (`str`):
|
| 105 |
+
Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`.
|
| 106 |
+
src_revision (`str`, *optional*):
|
| 107 |
+
The git revision of the file to be copied. Can be any valid git revision.
|
| 108 |
+
Default to the target commit revision.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
src_path_in_repo: str
|
| 112 |
+
path_in_repo: str
|
| 113 |
+
src_revision: str | None = None
|
| 114 |
+
# set to the OID of the file to be copied if it has already been uploaded
|
| 115 |
+
# useful to determine if a commit will be empty or not.
|
| 116 |
+
_src_oid: str | None = None
|
| 117 |
+
# set to the OID of the file to copy to if it has already been uploaded
|
| 118 |
+
# useful to determine if a commit will be empty or not.
|
| 119 |
+
_dest_oid: str | None = None
|
| 120 |
+
|
| 121 |
+
def __post_init__(self):
|
| 122 |
+
self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo)
|
| 123 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@dataclass
|
| 127 |
+
class CommitOperationAdd:
|
| 128 |
+
"""
|
| 129 |
+
Data structure holding necessary info to upload a file to a repository on the Hub.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
path_in_repo (`str`):
|
| 133 |
+
Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
|
| 134 |
+
path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`):
|
| 135 |
+
Either:
|
| 136 |
+
- a path to a local file (as `str` or `pathlib.Path`) to upload
|
| 137 |
+
- a buffer of bytes (`bytes`) holding the content of the file to upload
|
| 138 |
+
- a "file object" (subclass of `io.BufferedIOBase`), typically obtained
|
| 139 |
+
with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
|
| 140 |
+
|
| 141 |
+
Raises:
|
| 142 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 143 |
+
If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`.
|
| 144 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 145 |
+
If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file.
|
| 146 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 147 |
+
If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both
|
| 148 |
+
`seek()` and `tell()`.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
path_in_repo: str
|
| 152 |
+
path_or_fileobj: str | Path | bytes | BinaryIO
|
| 153 |
+
upload_info: UploadInfo = field(init=False, repr=False)
|
| 154 |
+
|
| 155 |
+
# Internal attributes
|
| 156 |
+
|
| 157 |
+
# set to "lfs" or "regular" once known
|
| 158 |
+
_upload_mode: UploadMode | None = field(init=False, repr=False, default=None)
|
| 159 |
+
|
| 160 |
+
# set to True if .gitignore rules prevent the file from being uploaded as LFS
|
| 161 |
+
# (server-side check)
|
| 162 |
+
_should_ignore: bool | None = field(init=False, repr=False, default=None)
|
| 163 |
+
|
| 164 |
+
# set to the remote OID of the file if it has already been uploaded
|
| 165 |
+
# useful to determine if a commit will be empty or not
|
| 166 |
+
_remote_oid: str | None = field(init=False, repr=False, default=None)
|
| 167 |
+
|
| 168 |
+
# set to True once the file has been uploaded as LFS
|
| 169 |
+
_is_uploaded: bool = field(init=False, repr=False, default=False)
|
| 170 |
+
|
| 171 |
+
# set to True once the file has been committed
|
| 172 |
+
_is_committed: bool = field(init=False, repr=False, default=False)
|
| 173 |
+
|
| 174 |
+
def __post_init__(self) -> None:
|
| 175 |
+
"""Validates `path_or_fileobj` and compute `upload_info`."""
|
| 176 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
| 177 |
+
|
| 178 |
+
# Validate `path_or_fileobj` value
|
| 179 |
+
if isinstance(self.path_or_fileobj, Path):
|
| 180 |
+
self.path_or_fileobj = str(self.path_or_fileobj)
|
| 181 |
+
if isinstance(self.path_or_fileobj, str):
|
| 182 |
+
path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj))
|
| 183 |
+
if not os.path.isfile(path_or_fileobj):
|
| 184 |
+
raise ValueError(f"Provided path: '{path_or_fileobj}' is not a file on the local file system")
|
| 185 |
+
elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)):
|
| 186 |
+
# ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode
|
| 187 |
+
raise ValueError(
|
| 188 |
+
"path_or_fileobj must be either an instance of str, bytes or"
|
| 189 |
+
" io.BufferedIOBase. If you passed a file-like object, make sure it is"
|
| 190 |
+
" in binary mode."
|
| 191 |
+
)
|
| 192 |
+
if isinstance(self.path_or_fileobj, io.BufferedIOBase):
|
| 193 |
+
try:
|
| 194 |
+
self.path_or_fileobj.tell()
|
| 195 |
+
self.path_or_fileobj.seek(0, os.SEEK_CUR)
|
| 196 |
+
except (OSError, AttributeError) as exc:
|
| 197 |
+
raise ValueError(
|
| 198 |
+
"path_or_fileobj is a file-like object but does not implement seek() and tell()"
|
| 199 |
+
) from exc
|
| 200 |
+
|
| 201 |
+
# Compute "upload_info" attribute
|
| 202 |
+
if isinstance(self.path_or_fileobj, str):
|
| 203 |
+
self.upload_info = UploadInfo.from_path(self.path_or_fileobj)
|
| 204 |
+
elif isinstance(self.path_or_fileobj, bytes):
|
| 205 |
+
self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj)
|
| 206 |
+
else:
|
| 207 |
+
self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj)
|
| 208 |
+
|
| 209 |
+
@contextmanager
|
| 210 |
+
def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]:
|
| 211 |
+
"""
|
| 212 |
+
A context manager that yields a file-like object allowing to read the underlying
|
| 213 |
+
data behind `path_or_fileobj`.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
with_tqdm (`bool`, *optional*, defaults to `False`):
|
| 217 |
+
If True, iterating over the file object will display a progress bar. Only
|
| 218 |
+
works if the file-like object is a path to a file. Pure bytes and buffers
|
| 219 |
+
are not supported.
|
| 220 |
+
|
| 221 |
+
Example:
|
| 222 |
+
|
| 223 |
+
```python
|
| 224 |
+
>>> operation = CommitOperationAdd(
|
| 225 |
+
... path_in_repo="remote/dir/weights.h5",
|
| 226 |
+
... path_or_fileobj="./local/weights.h5",
|
| 227 |
+
... )
|
| 228 |
+
CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
|
| 229 |
+
|
| 230 |
+
>>> with operation.as_file() as file:
|
| 231 |
+
... content = file.read()
|
| 232 |
+
|
| 233 |
+
>>> with operation.as_file(with_tqdm=True) as file:
|
| 234 |
+
... while True:
|
| 235 |
+
... data = file.read(1024)
|
| 236 |
+
... if not data:
|
| 237 |
+
... break
|
| 238 |
+
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
|
| 239 |
+
|
| 240 |
+
>>> with operation.as_file(with_tqdm=True) as file:
|
| 241 |
+
... httpx.put(..., data=file)
|
| 242 |
+
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
|
| 243 |
+
```
|
| 244 |
+
"""
|
| 245 |
+
if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path):
|
| 246 |
+
if with_tqdm:
|
| 247 |
+
with tqdm_stream_file(self.path_or_fileobj) as file:
|
| 248 |
+
yield file
|
| 249 |
+
else:
|
| 250 |
+
with open(self.path_or_fileobj, "rb") as file:
|
| 251 |
+
yield file
|
| 252 |
+
elif isinstance(self.path_or_fileobj, bytes):
|
| 253 |
+
yield io.BytesIO(self.path_or_fileobj)
|
| 254 |
+
elif isinstance(self.path_or_fileobj, io.BufferedIOBase):
|
| 255 |
+
prev_pos = self.path_or_fileobj.tell()
|
| 256 |
+
yield self.path_or_fileobj
|
| 257 |
+
self.path_or_fileobj.seek(prev_pos, io.SEEK_SET)
|
| 258 |
+
|
| 259 |
+
def b64content(self) -> bytes:
|
| 260 |
+
"""
|
| 261 |
+
The base64-encoded content of `path_or_fileobj`
|
| 262 |
+
|
| 263 |
+
Returns: `bytes`
|
| 264 |
+
"""
|
| 265 |
+
with self.as_file() as file:
|
| 266 |
+
return base64.b64encode(file.read())
|
| 267 |
+
|
| 268 |
+
@property
|
| 269 |
+
def _local_oid(self) -> str | None:
|
| 270 |
+
"""Return the OID of the local file.
|
| 271 |
+
|
| 272 |
+
This OID is then compared to `self._remote_oid` to check if the file has changed compared to the remote one.
|
| 273 |
+
If the file did not change, we won't upload it again to prevent empty commits.
|
| 274 |
+
|
| 275 |
+
For LFS files, the OID corresponds to the SHA256 of the file content (used a LFS ref).
|
| 276 |
+
For regular files, the OID corresponds to the SHA1 of the file content.
|
| 277 |
+
Note: this is slightly different to git OID computation since the oid of an LFS file is usually the git-SHA1 of the
|
| 278 |
+
pointer file content (not the actual file content). However, using the SHA256 is enough to detect changes
|
| 279 |
+
and more convenient client-side.
|
| 280 |
+
"""
|
| 281 |
+
if self._upload_mode is None:
|
| 282 |
+
return None
|
| 283 |
+
elif self._upload_mode == "lfs":
|
| 284 |
+
return self.upload_info.sha256.hex()
|
| 285 |
+
else:
|
| 286 |
+
# Regular file => compute sha1
|
| 287 |
+
# => no need to read by chunk since the file is guaranteed to be <=5MB.
|
| 288 |
+
with self.as_file() as file:
|
| 289 |
+
return sha.git_hash(file.read())
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def _validate_path_in_repo(path_in_repo: str) -> str:
|
| 293 |
+
# Validate `path_in_repo` value to prevent a server-side issue
|
| 294 |
+
if path_in_repo.startswith("/"):
|
| 295 |
+
path_in_repo = path_in_repo[1:]
|
| 296 |
+
if path_in_repo == "." or path_in_repo == ".." or path_in_repo.startswith("../"):
|
| 297 |
+
raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'")
|
| 298 |
+
if path_in_repo.startswith("./"):
|
| 299 |
+
path_in_repo = path_in_repo[2:]
|
| 300 |
+
for forbidden in FORBIDDEN_FOLDERS:
|
| 301 |
+
if any(part == forbidden for part in path_in_repo.split("/")):
|
| 302 |
+
raise ValueError(
|
| 303 |
+
f"Invalid `path_in_repo` in CommitOperation: cannot update files under a '{forbidden}/' folder (path:"
|
| 304 |
+
f" '{path_in_repo}')."
|
| 305 |
+
)
|
| 306 |
+
return path_in_repo
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete]
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def _warn_on_overwriting_operations(operations: list[CommitOperation]) -> None:
|
| 313 |
+
"""
|
| 314 |
+
Warn user when a list of operations is expected to overwrite itself in a single
|
| 315 |
+
commit.
|
| 316 |
+
|
| 317 |
+
Rules:
|
| 318 |
+
- If a filepath is updated by multiple `CommitOperationAdd` operations, a warning
|
| 319 |
+
message is triggered.
|
| 320 |
+
- If a filepath is updated at least once by a `CommitOperationAdd` and then deleted
|
| 321 |
+
by a `CommitOperationDelete`, a warning is triggered.
|
| 322 |
+
- If a `CommitOperationDelete` deletes a filepath that is then updated by a
|
| 323 |
+
`CommitOperationAdd`, no warning is triggered. This is usually useless (no need to
|
| 324 |
+
delete before upload) but can happen if a user deletes an entire folder and then
|
| 325 |
+
add new files to it.
|
| 326 |
+
"""
|
| 327 |
+
nb_additions_per_path: dict[str, int] = defaultdict(int)
|
| 328 |
+
for operation in operations:
|
| 329 |
+
path_in_repo = operation.path_in_repo
|
| 330 |
+
if isinstance(operation, CommitOperationAdd):
|
| 331 |
+
if nb_additions_per_path[path_in_repo] > 0:
|
| 332 |
+
warnings.warn(
|
| 333 |
+
"About to update multiple times the same file in the same commit:"
|
| 334 |
+
f" '{path_in_repo}'. This can cause undesired inconsistencies in"
|
| 335 |
+
" your repo."
|
| 336 |
+
)
|
| 337 |
+
nb_additions_per_path[path_in_repo] += 1
|
| 338 |
+
for parent in PurePosixPath(path_in_repo).parents:
|
| 339 |
+
# Also keep track of number of updated files per folder
|
| 340 |
+
# => warns if deleting a folder overwrite some contained files
|
| 341 |
+
nb_additions_per_path[str(parent)] += 1
|
| 342 |
+
if isinstance(operation, CommitOperationDelete):
|
| 343 |
+
if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0:
|
| 344 |
+
if operation.is_folder:
|
| 345 |
+
warnings.warn(
|
| 346 |
+
"About to delete a folder containing files that have just been"
|
| 347 |
+
f" updated within the same commit: '{path_in_repo}'. This can"
|
| 348 |
+
" cause undesired inconsistencies in your repo."
|
| 349 |
+
)
|
| 350 |
+
else:
|
| 351 |
+
warnings.warn(
|
| 352 |
+
"About to delete a file that have just been updated within the"
|
| 353 |
+
f" same commit: '{path_in_repo}'. This can cause undesired"
|
| 354 |
+
" inconsistencies in your repo."
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
@validate_hf_hub_args
|
| 359 |
+
def _upload_files(
|
| 360 |
+
*,
|
| 361 |
+
additions: list[CommitOperationAdd],
|
| 362 |
+
repo_type: str,
|
| 363 |
+
repo_id: str,
|
| 364 |
+
headers: dict[str, str],
|
| 365 |
+
endpoint: str | None = None,
|
| 366 |
+
num_threads: int = 5,
|
| 367 |
+
revision: str | None = None,
|
| 368 |
+
create_pr: bool | None = None,
|
| 369 |
+
):
|
| 370 |
+
"""
|
| 371 |
+
Negotiates per-file transfer (LFS vs Xet) and uploads in batches.
|
| 372 |
+
"""
|
| 373 |
+
xet_additions: list[CommitOperationAdd] = []
|
| 374 |
+
lfs_actions: list[dict[str, Any]] = []
|
| 375 |
+
lfs_oid2addop: dict[str, CommitOperationAdd] = {}
|
| 376 |
+
|
| 377 |
+
for chunk in chunk_iterable(additions, chunk_size=UPLOAD_BATCH_MAX_NUM_FILES):
|
| 378 |
+
chunk_list = [op for op in chunk]
|
| 379 |
+
|
| 380 |
+
transfers: list[str] = ["basic", "multipart"]
|
| 381 |
+
has_buffered_io_data = any(isinstance(op.path_or_fileobj, io.BufferedIOBase) for op in chunk_list)
|
| 382 |
+
if is_xet_available():
|
| 383 |
+
if not has_buffered_io_data:
|
| 384 |
+
transfers.append("xet")
|
| 385 |
+
else:
|
| 386 |
+
logger.warning(
|
| 387 |
+
"Uploading files as a binary IO buffer is not supported by Xet Storage. "
|
| 388 |
+
"Falling back to HTTP upload."
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
actions_chunk, errors_chunk, chosen_transfer = post_lfs_batch_info(
|
| 392 |
+
upload_infos=[op.upload_info for op in chunk_list],
|
| 393 |
+
repo_id=repo_id,
|
| 394 |
+
repo_type=repo_type,
|
| 395 |
+
revision=revision,
|
| 396 |
+
endpoint=endpoint,
|
| 397 |
+
headers=headers,
|
| 398 |
+
token=None, # already passed in 'headers'
|
| 399 |
+
transfers=transfers,
|
| 400 |
+
)
|
| 401 |
+
if errors_chunk:
|
| 402 |
+
message = "\n".join(
|
| 403 |
+
[
|
| 404 |
+
f"Encountered error for file with OID {err.get('oid')}: `{err.get('error', {}).get('message')}"
|
| 405 |
+
for err in errors_chunk
|
| 406 |
+
]
|
| 407 |
+
)
|
| 408 |
+
raise ValueError(f"LFS batch API returned errors:\n{message}")
|
| 409 |
+
|
| 410 |
+
# If server returns a transfer we didn't offer (e.g "xet" while uploading from BytesIO),
|
| 411 |
+
# fall back to LFS for this chunk.
|
| 412 |
+
if chosen_transfer == "xet" and ("xet" in transfers):
|
| 413 |
+
xet_additions.extend(chunk_list)
|
| 414 |
+
else:
|
| 415 |
+
lfs_actions.extend(actions_chunk)
|
| 416 |
+
for op in chunk_list:
|
| 417 |
+
lfs_oid2addop[op.upload_info.sha256.hex()] = op
|
| 418 |
+
|
| 419 |
+
if len(lfs_actions) > 0:
|
| 420 |
+
_upload_lfs_files(
|
| 421 |
+
actions=lfs_actions,
|
| 422 |
+
oid2addop=lfs_oid2addop,
|
| 423 |
+
headers=headers,
|
| 424 |
+
endpoint=endpoint,
|
| 425 |
+
num_threads=num_threads,
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
if len(xet_additions) > 0:
|
| 429 |
+
_upload_xet_files(
|
| 430 |
+
additions=xet_additions,
|
| 431 |
+
repo_type=repo_type,
|
| 432 |
+
repo_id=repo_id,
|
| 433 |
+
headers=headers,
|
| 434 |
+
endpoint=endpoint,
|
| 435 |
+
revision=revision,
|
| 436 |
+
create_pr=create_pr,
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
@validate_hf_hub_args
|
| 441 |
+
def _upload_lfs_files(
|
| 442 |
+
*,
|
| 443 |
+
actions: list[dict[str, Any]],
|
| 444 |
+
oid2addop: dict[str, CommitOperationAdd],
|
| 445 |
+
headers: dict[str, str],
|
| 446 |
+
endpoint: str | None = None,
|
| 447 |
+
num_threads: int = 5,
|
| 448 |
+
):
|
| 449 |
+
"""
|
| 450 |
+
Uploads the content of `additions` to the Hub using the large file storage protocol.
|
| 451 |
+
|
| 452 |
+
Relevant external documentation:
|
| 453 |
+
- LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
|
| 454 |
+
|
| 455 |
+
Args:
|
| 456 |
+
actions (`list[dict[str, Any]]`):
|
| 457 |
+
LFS batch actions returned by the server.
|
| 458 |
+
oid2addop (`dict[str, CommitOperationAdd]`):
|
| 459 |
+
A dictionary mapping the OID of the file to the corresponding `CommitOperationAdd` object.
|
| 460 |
+
headers (`dict[str, str]`):
|
| 461 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 462 |
+
endpoint (`str`, *optional*):
|
| 463 |
+
The endpoint to use for the request. Defaults to `constants.ENDPOINT`.
|
| 464 |
+
num_threads (`int`, *optional*):
|
| 465 |
+
The number of concurrent threads to use when uploading. Defaults to 5.
|
| 466 |
+
|
| 467 |
+
Raises:
|
| 468 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 469 |
+
If an upload failed for any reason
|
| 470 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 471 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 472 |
+
repo_id (`str`):
|
| 473 |
+
A namespace (user or an organization) and a repo name separated
|
| 474 |
+
by a `/`.
|
| 475 |
+
headers (`dict[str, str]`):
|
| 476 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 477 |
+
num_threads (`int`, *optional*):
|
| 478 |
+
The number of concurrent threads to use when uploading. Defaults to 5.
|
| 479 |
+
revision (`str`, *optional*):
|
| 480 |
+
The git revision to upload to.
|
| 481 |
+
|
| 482 |
+
Raises:
|
| 483 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 484 |
+
If an upload failed for any reason
|
| 485 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 486 |
+
If the server returns malformed responses
|
| 487 |
+
[`HfHubHTTPError`]
|
| 488 |
+
If the LFS batch endpoint returned an HTTP error.
|
| 489 |
+
"""
|
| 490 |
+
# Filter out files already present upstream
|
| 491 |
+
filtered_actions = []
|
| 492 |
+
for action in actions:
|
| 493 |
+
if action.get("actions") is None:
|
| 494 |
+
logger.debug(
|
| 495 |
+
f"Content of file {oid2addop[action['oid']].path_in_repo} is already present upstream - skipping upload."
|
| 496 |
+
)
|
| 497 |
+
else:
|
| 498 |
+
filtered_actions.append(action)
|
| 499 |
+
|
| 500 |
+
# Upload according to server-provided actions
|
| 501 |
+
def _wrapped_lfs_upload(batch_action) -> None:
|
| 502 |
+
try:
|
| 503 |
+
operation = oid2addop[batch_action["oid"]]
|
| 504 |
+
lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint)
|
| 505 |
+
except Exception as exc:
|
| 506 |
+
raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc
|
| 507 |
+
|
| 508 |
+
if len(filtered_actions) == 1:
|
| 509 |
+
logger.debug("Uploading 1 LFS file to the Hub")
|
| 510 |
+
_wrapped_lfs_upload(filtered_actions[0])
|
| 511 |
+
else:
|
| 512 |
+
logger.debug(
|
| 513 |
+
f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently"
|
| 514 |
+
)
|
| 515 |
+
thread_map(
|
| 516 |
+
_wrapped_lfs_upload,
|
| 517 |
+
filtered_actions,
|
| 518 |
+
desc=f"Upload {len(filtered_actions)} LFS files",
|
| 519 |
+
max_workers=num_threads,
|
| 520 |
+
tqdm_class=hf_tqdm,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
@validate_hf_hub_args
|
| 525 |
+
def _upload_xet_files(
|
| 526 |
+
*,
|
| 527 |
+
additions: list[CommitOperationAdd],
|
| 528 |
+
repo_type: str,
|
| 529 |
+
repo_id: str,
|
| 530 |
+
headers: dict[str, str],
|
| 531 |
+
endpoint: str | None = None,
|
| 532 |
+
revision: str | None = None,
|
| 533 |
+
create_pr: bool | None = None,
|
| 534 |
+
):
|
| 535 |
+
"""
|
| 536 |
+
Uploads the content of `additions` to the Hub using the xet storage protocol.
|
| 537 |
+
This chunks the files and deduplicates the chunks before uploading them to xetcas storage.
|
| 538 |
+
|
| 539 |
+
Args:
|
| 540 |
+
additions (`` of `CommitOperationAdd`):
|
| 541 |
+
The files to be uploaded.
|
| 542 |
+
repo_type (`str`):
|
| 543 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 544 |
+
repo_id (`str`):
|
| 545 |
+
A namespace (user or an organization) and a repo name separated
|
| 546 |
+
by a `/`.
|
| 547 |
+
headers (`dict[str, str]`):
|
| 548 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 549 |
+
endpoint: (`str`, *optional*):
|
| 550 |
+
The endpoint to use for the xetcas service. Defaults to `constants.ENDPOINT`.
|
| 551 |
+
revision (`str`, *optional*):
|
| 552 |
+
The git revision to upload to.
|
| 553 |
+
create_pr (`bool`, *optional*):
|
| 554 |
+
Whether or not to create a Pull Request with that commit.
|
| 555 |
+
|
| 556 |
+
Raises:
|
| 557 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 558 |
+
If an upload failed for any reason.
|
| 559 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 560 |
+
If the server returns malformed responses or if the user is unauthorized to upload to xet storage.
|
| 561 |
+
[`HfHubHTTPError`]
|
| 562 |
+
If the LFS batch endpoint returned an HTTP error.
|
| 563 |
+
|
| 564 |
+
**How it works:**
|
| 565 |
+
The file download system uses Xet storage, which is a content-addressable storage system that breaks files into chunks
|
| 566 |
+
for efficient storage and transfer.
|
| 567 |
+
|
| 568 |
+
`hf_xet.upload_files` manages uploading files by:
|
| 569 |
+
- Taking a list of file paths to upload
|
| 570 |
+
- Breaking files into smaller chunks for efficient storage
|
| 571 |
+
- Avoiding duplicate storage by recognizing identical chunks across files
|
| 572 |
+
- Connecting to a storage server (CAS server) that manages these chunks
|
| 573 |
+
|
| 574 |
+
The upload process works like this:
|
| 575 |
+
1. Create a local folder at ~/.cache/huggingface/xet/chunk-cache to store file chunks for reuse.
|
| 576 |
+
2. Process files in parallel (up to 8 files at once):
|
| 577 |
+
2.1. Read the file content.
|
| 578 |
+
2.2. Split the file content into smaller chunks based on content patterns: each chunk gets a unique ID based on what's in it.
|
| 579 |
+
2.3. For each chunk:
|
| 580 |
+
- Check if it already exists in storage.
|
| 581 |
+
- Skip uploading chunks that already exist.
|
| 582 |
+
2.4. Group chunks into larger blocks for efficient transfer.
|
| 583 |
+
2.5. Upload these blocks to the storage server.
|
| 584 |
+
2.6. Create and upload information about how the file is structured.
|
| 585 |
+
3. Return reference files that contain information about the uploaded files, which can be used later to download them.
|
| 586 |
+
"""
|
| 587 |
+
if len(additions) == 0:
|
| 588 |
+
return
|
| 589 |
+
|
| 590 |
+
# at this point, we know that hf_xet is installed
|
| 591 |
+
from hf_xet import upload_bytes, upload_files
|
| 592 |
+
|
| 593 |
+
from .utils._xet_progress_reporting import XetProgressReporter
|
| 594 |
+
|
| 595 |
+
try:
|
| 596 |
+
xet_connection_info = fetch_xet_connection_info_from_repo_info(
|
| 597 |
+
token_type=XetTokenType.WRITE,
|
| 598 |
+
repo_id=repo_id,
|
| 599 |
+
repo_type=repo_type,
|
| 600 |
+
revision=revision,
|
| 601 |
+
headers=headers,
|
| 602 |
+
endpoint=endpoint,
|
| 603 |
+
params={"create_pr": "1"} if create_pr else None,
|
| 604 |
+
)
|
| 605 |
+
except HfHubHTTPError as e:
|
| 606 |
+
if e.response.status_code == 401:
|
| 607 |
+
raise XetAuthorizationError(
|
| 608 |
+
f"You are unauthorized to upload to xet storage for {repo_type}/{repo_id}. "
|
| 609 |
+
f"Please check that you have configured your access token with write access to the repo."
|
| 610 |
+
) from e
|
| 611 |
+
raise
|
| 612 |
+
|
| 613 |
+
xet_endpoint = xet_connection_info.endpoint
|
| 614 |
+
access_token_info = (xet_connection_info.access_token, xet_connection_info.expiration_unix_epoch)
|
| 615 |
+
|
| 616 |
+
def token_refresher() -> tuple[str, int]:
|
| 617 |
+
new_xet_connection = fetch_xet_connection_info_from_repo_info(
|
| 618 |
+
token_type=XetTokenType.WRITE,
|
| 619 |
+
repo_id=repo_id,
|
| 620 |
+
repo_type=repo_type,
|
| 621 |
+
revision=revision,
|
| 622 |
+
headers=headers,
|
| 623 |
+
endpoint=endpoint,
|
| 624 |
+
params={"create_pr": "1"} if create_pr else None,
|
| 625 |
+
)
|
| 626 |
+
if new_xet_connection is None:
|
| 627 |
+
raise XetRefreshTokenError("Failed to refresh xet token")
|
| 628 |
+
return new_xet_connection.access_token, new_xet_connection.expiration_unix_epoch
|
| 629 |
+
|
| 630 |
+
if not are_progress_bars_disabled():
|
| 631 |
+
progress = XetProgressReporter()
|
| 632 |
+
progress_callback = progress.update_progress
|
| 633 |
+
else:
|
| 634 |
+
progress, progress_callback = None, None
|
| 635 |
+
|
| 636 |
+
try:
|
| 637 |
+
all_bytes_ops = [op for op in additions if isinstance(op.path_or_fileobj, bytes)]
|
| 638 |
+
all_paths_ops = [op for op in additions if isinstance(op.path_or_fileobj, (str, Path))]
|
| 639 |
+
|
| 640 |
+
xet_headers = headers.copy()
|
| 641 |
+
xet_headers.pop("authorization", None)
|
| 642 |
+
|
| 643 |
+
if len(all_paths_ops) > 0:
|
| 644 |
+
all_paths = [str(op.path_or_fileobj) for op in all_paths_ops]
|
| 645 |
+
all_sha256s = [op.upload_info.sha256.hex() for op in all_paths_ops]
|
| 646 |
+
upload_files(
|
| 647 |
+
all_paths,
|
| 648 |
+
xet_endpoint,
|
| 649 |
+
access_token_info,
|
| 650 |
+
token_refresher,
|
| 651 |
+
progress_callback,
|
| 652 |
+
repo_type,
|
| 653 |
+
request_headers=xet_headers,
|
| 654 |
+
sha256s=all_sha256s,
|
| 655 |
+
)
|
| 656 |
+
|
| 657 |
+
if len(all_bytes_ops) > 0:
|
| 658 |
+
all_bytes = [op.path_or_fileobj for op in all_bytes_ops]
|
| 659 |
+
all_sha256s = [op.upload_info.sha256.hex() for op in all_bytes_ops]
|
| 660 |
+
upload_bytes(
|
| 661 |
+
all_bytes,
|
| 662 |
+
xet_endpoint,
|
| 663 |
+
access_token_info,
|
| 664 |
+
token_refresher,
|
| 665 |
+
progress_callback,
|
| 666 |
+
repo_type,
|
| 667 |
+
request_headers=xet_headers,
|
| 668 |
+
sha256s=all_sha256s,
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
finally:
|
| 672 |
+
if progress is not None:
|
| 673 |
+
progress.close(False)
|
| 674 |
+
|
| 675 |
+
return
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def _validate_preupload_info(preupload_info: dict):
|
| 679 |
+
files = preupload_info.get("files")
|
| 680 |
+
if not isinstance(files, list):
|
| 681 |
+
raise ValueError("preupload_info is improperly formatted")
|
| 682 |
+
for file_info in files:
|
| 683 |
+
if not (
|
| 684 |
+
isinstance(file_info, dict)
|
| 685 |
+
and isinstance(file_info.get("path"), str)
|
| 686 |
+
and isinstance(file_info.get("uploadMode"), str)
|
| 687 |
+
and (file_info["uploadMode"] in ("lfs", "regular"))
|
| 688 |
+
):
|
| 689 |
+
raise ValueError("preupload_info is improperly formatted:")
|
| 690 |
+
return preupload_info
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
@validate_hf_hub_args
|
| 694 |
+
def _fetch_upload_modes(
|
| 695 |
+
additions: Iterable[CommitOperationAdd],
|
| 696 |
+
repo_type: str,
|
| 697 |
+
repo_id: str,
|
| 698 |
+
headers: dict[str, str],
|
| 699 |
+
revision: str,
|
| 700 |
+
endpoint: str | None = None,
|
| 701 |
+
create_pr: bool = False,
|
| 702 |
+
gitignore_content: str | None = None,
|
| 703 |
+
) -> None:
|
| 704 |
+
"""
|
| 705 |
+
Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob,
|
| 706 |
+
as a git LFS blob, or as a XET file. Input `additions` are mutated in-place with the upload mode.
|
| 707 |
+
|
| 708 |
+
Args:
|
| 709 |
+
additions (`Iterable` of :class:`CommitOperationAdd`):
|
| 710 |
+
Iterable of :class:`CommitOperationAdd` describing the files to
|
| 711 |
+
upload to the Hub.
|
| 712 |
+
repo_type (`str`):
|
| 713 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 714 |
+
repo_id (`str`):
|
| 715 |
+
A namespace (user or an organization) and a repo name separated
|
| 716 |
+
by a `/`.
|
| 717 |
+
headers (`dict[str, str]`):
|
| 718 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 719 |
+
revision (`str`):
|
| 720 |
+
The git revision to upload the files to. Can be any valid git revision.
|
| 721 |
+
gitignore_content (`str`, *optional*):
|
| 722 |
+
The content of the `.gitignore` file to know which files should be ignored. The order of priority
|
| 723 |
+
is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
|
| 724 |
+
in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
|
| 725 |
+
(if any).
|
| 726 |
+
Raises:
|
| 727 |
+
[`~utils.HfHubHTTPError`]
|
| 728 |
+
If the Hub API returned an error.
|
| 729 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 730 |
+
If the Hub API response is improperly formatted.
|
| 731 |
+
"""
|
| 732 |
+
endpoint = endpoint if endpoint is not None else constants.ENDPOINT
|
| 733 |
+
|
| 734 |
+
# Fetch upload mode (LFS or regular) chunk by chunk.
|
| 735 |
+
upload_modes: dict[str, UploadMode] = {}
|
| 736 |
+
should_ignore_info: dict[str, bool] = {}
|
| 737 |
+
oid_info: dict[str, str | None] = {}
|
| 738 |
+
|
| 739 |
+
for chunk in chunk_iterable(additions, 256):
|
| 740 |
+
payload: dict = {
|
| 741 |
+
"files": [
|
| 742 |
+
{
|
| 743 |
+
"path": op.path_in_repo,
|
| 744 |
+
"sample": base64.b64encode(op.upload_info.sample).decode("ascii"),
|
| 745 |
+
"size": op.upload_info.size,
|
| 746 |
+
}
|
| 747 |
+
for op in chunk
|
| 748 |
+
]
|
| 749 |
+
}
|
| 750 |
+
if gitignore_content is not None:
|
| 751 |
+
payload["gitIgnore"] = gitignore_content
|
| 752 |
+
|
| 753 |
+
resp = http_backoff(
|
| 754 |
+
"POST",
|
| 755 |
+
f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}",
|
| 756 |
+
json=payload,
|
| 757 |
+
headers=headers,
|
| 758 |
+
params={"create_pr": "1"} if create_pr else None,
|
| 759 |
+
)
|
| 760 |
+
hf_raise_for_status(resp)
|
| 761 |
+
preupload_info = _validate_preupload_info(resp.json())
|
| 762 |
+
upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]})
|
| 763 |
+
should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]})
|
| 764 |
+
oid_info.update(**{file["path"]: file.get("oid") for file in preupload_info["files"]})
|
| 765 |
+
|
| 766 |
+
# Set upload mode for each addition operation
|
| 767 |
+
for addition in additions:
|
| 768 |
+
addition._upload_mode = upload_modes[addition.path_in_repo]
|
| 769 |
+
addition._should_ignore = should_ignore_info[addition.path_in_repo]
|
| 770 |
+
addition._remote_oid = oid_info[addition.path_in_repo]
|
| 771 |
+
|
| 772 |
+
# Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented)
|
| 773 |
+
# => empty files are uploaded as "regular" to still allow users to commit them.
|
| 774 |
+
for addition in additions:
|
| 775 |
+
if addition.upload_info.size == 0:
|
| 776 |
+
addition._upload_mode = "regular"
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
@validate_hf_hub_args
|
| 780 |
+
def _fetch_files_to_copy(
|
| 781 |
+
copies: Iterable[CommitOperationCopy],
|
| 782 |
+
repo_type: str,
|
| 783 |
+
repo_id: str,
|
| 784 |
+
headers: dict[str, str],
|
| 785 |
+
revision: str,
|
| 786 |
+
endpoint: str | None = None,
|
| 787 |
+
) -> dict[tuple[str, str | None], Union["RepoFile", bytes]]:
|
| 788 |
+
"""
|
| 789 |
+
Fetch information about the files to copy.
|
| 790 |
+
|
| 791 |
+
For LFS files, we only need their metadata (file size and sha256) while for regular files
|
| 792 |
+
we need to download the raw content from the Hub.
|
| 793 |
+
|
| 794 |
+
Args:
|
| 795 |
+
copies (`Iterable` of :class:`CommitOperationCopy`):
|
| 796 |
+
Iterable of :class:`CommitOperationCopy` describing the files to
|
| 797 |
+
copy on the Hub.
|
| 798 |
+
repo_type (`str`):
|
| 799 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 800 |
+
repo_id (`str`):
|
| 801 |
+
A namespace (user or an organization) and a repo name separated
|
| 802 |
+
by a `/`.
|
| 803 |
+
headers (`dict[str, str]`):
|
| 804 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 805 |
+
revision (`str`):
|
| 806 |
+
The git revision to upload the files to. Can be any valid git revision.
|
| 807 |
+
|
| 808 |
+
Returns: `dict[tuple[str, Optional[str]], Union[RepoFile, bytes]]]`
|
| 809 |
+
Key is the file path and revision of the file to copy.
|
| 810 |
+
Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files).
|
| 811 |
+
|
| 812 |
+
Raises:
|
| 813 |
+
[`~utils.HfHubHTTPError`]
|
| 814 |
+
If the Hub API returned an error.
|
| 815 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 816 |
+
If the Hub API response is improperly formatted.
|
| 817 |
+
"""
|
| 818 |
+
from .hf_api import HfApi, RepoFolder
|
| 819 |
+
|
| 820 |
+
hf_api = HfApi(endpoint=endpoint, headers=headers)
|
| 821 |
+
files_to_copy: dict[tuple[str, str | None], Union["RepoFile", bytes]] = {}
|
| 822 |
+
# Store (path, revision) -> oid mapping
|
| 823 |
+
oid_info: dict[tuple[str, str | None], str | None] = {}
|
| 824 |
+
# 1. Fetch OIDs for destination paths in batches.
|
| 825 |
+
dest_paths = [op.path_in_repo for op in copies]
|
| 826 |
+
for offset in range(0, len(dest_paths), FETCH_LFS_BATCH_SIZE):
|
| 827 |
+
dest_repo_files = hf_api.get_paths_info(
|
| 828 |
+
repo_id=repo_id,
|
| 829 |
+
paths=dest_paths[offset : offset + FETCH_LFS_BATCH_SIZE],
|
| 830 |
+
revision=revision,
|
| 831 |
+
repo_type=repo_type,
|
| 832 |
+
)
|
| 833 |
+
for file in dest_repo_files:
|
| 834 |
+
if not isinstance(file, RepoFolder):
|
| 835 |
+
oid_info[(file.path, revision)] = file.blob_id
|
| 836 |
+
|
| 837 |
+
# 2. Group by source revision and fetch source file info in batches.
|
| 838 |
+
for src_revision, operations in groupby(copies, key=lambda op: op.src_revision):
|
| 839 |
+
operations = list(operations) # type: ignore
|
| 840 |
+
src_paths = [op.src_path_in_repo for op in operations]
|
| 841 |
+
for offset in range(0, len(src_paths), FETCH_LFS_BATCH_SIZE):
|
| 842 |
+
src_repo_files = hf_api.get_paths_info(
|
| 843 |
+
repo_id=repo_id,
|
| 844 |
+
paths=src_paths[offset : offset + FETCH_LFS_BATCH_SIZE],
|
| 845 |
+
revision=src_revision or revision,
|
| 846 |
+
repo_type=repo_type,
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
for src_repo_file in src_repo_files:
|
| 850 |
+
if isinstance(src_repo_file, RepoFolder):
|
| 851 |
+
raise NotImplementedError("Copying a folder is not implemented.")
|
| 852 |
+
oid_info[(src_repo_file.path, src_revision)] = src_repo_file.blob_id
|
| 853 |
+
# If it's an LFS file, store the RepoFile object. Otherwise, download raw bytes.
|
| 854 |
+
if src_repo_file.lfs:
|
| 855 |
+
files_to_copy[(src_repo_file.path, src_revision)] = src_repo_file
|
| 856 |
+
else:
|
| 857 |
+
# TODO: (optimization) download regular files to copy concurrently
|
| 858 |
+
url = hf_hub_url(
|
| 859 |
+
endpoint=endpoint,
|
| 860 |
+
repo_type=repo_type,
|
| 861 |
+
repo_id=repo_id,
|
| 862 |
+
revision=src_revision or revision,
|
| 863 |
+
filename=src_repo_file.path,
|
| 864 |
+
)
|
| 865 |
+
response = get_session().get(url, headers=headers)
|
| 866 |
+
hf_raise_for_status(response)
|
| 867 |
+
files_to_copy[(src_repo_file.path, src_revision)] = response.content
|
| 868 |
+
# 3. Ensure all operations found a corresponding file in the Hub
|
| 869 |
+
# and track src/dest OIDs for each operation.
|
| 870 |
+
for operation in operations:
|
| 871 |
+
if (operation.src_path_in_repo, src_revision) not in files_to_copy:
|
| 872 |
+
raise EntryNotFoundError(
|
| 873 |
+
f"Cannot copy {operation.src_path_in_repo} at revision "
|
| 874 |
+
f"{src_revision or revision}: file is missing on repo."
|
| 875 |
+
)
|
| 876 |
+
operation._src_oid = oid_info.get((operation.src_path_in_repo, operation.src_revision))
|
| 877 |
+
operation._dest_oid = oid_info.get((operation.path_in_repo, revision))
|
| 878 |
+
return files_to_copy
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
def _prepare_commit_payload(
|
| 882 |
+
operations: Iterable[CommitOperation],
|
| 883 |
+
files_to_copy: dict[tuple[str, str | None], Union["RepoFile", bytes]],
|
| 884 |
+
commit_message: str,
|
| 885 |
+
commit_description: str | None = None,
|
| 886 |
+
parent_commit: str | None = None,
|
| 887 |
+
) -> Iterable[dict[str, Any]]:
|
| 888 |
+
"""
|
| 889 |
+
Builds the payload to POST to the `/commit` API of the Hub.
|
| 890 |
+
|
| 891 |
+
Payload is returned as an iterator so that it can be streamed as a ndjson in the
|
| 892 |
+
POST request.
|
| 893 |
+
|
| 894 |
+
For more information, see:
|
| 895 |
+
- https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
|
| 896 |
+
- http://ndjson.org/
|
| 897 |
+
"""
|
| 898 |
+
commit_description = commit_description if commit_description is not None else ""
|
| 899 |
+
|
| 900 |
+
# 1. Send a header item with the commit metadata
|
| 901 |
+
header_value = {"summary": commit_message, "description": commit_description}
|
| 902 |
+
if parent_commit is not None:
|
| 903 |
+
header_value["parentCommit"] = parent_commit
|
| 904 |
+
yield {"key": "header", "value": header_value}
|
| 905 |
+
|
| 906 |
+
nb_ignored_files = 0
|
| 907 |
+
|
| 908 |
+
# 2. Send operations, one per line
|
| 909 |
+
for operation in operations:
|
| 910 |
+
# Skip ignored files
|
| 911 |
+
if isinstance(operation, CommitOperationAdd) and operation._should_ignore:
|
| 912 |
+
logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).")
|
| 913 |
+
nb_ignored_files += 1
|
| 914 |
+
continue
|
| 915 |
+
|
| 916 |
+
# 2.a. Case adding a regular file
|
| 917 |
+
if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular":
|
| 918 |
+
yield {
|
| 919 |
+
"key": "file",
|
| 920 |
+
"value": {
|
| 921 |
+
"content": operation.b64content().decode(),
|
| 922 |
+
"path": operation.path_in_repo,
|
| 923 |
+
"encoding": "base64",
|
| 924 |
+
},
|
| 925 |
+
}
|
| 926 |
+
# 2.b. Case adding an LFS file
|
| 927 |
+
elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs":
|
| 928 |
+
yield {
|
| 929 |
+
"key": "lfsFile",
|
| 930 |
+
"value": {
|
| 931 |
+
"path": operation.path_in_repo,
|
| 932 |
+
"algo": "sha256",
|
| 933 |
+
"oid": operation.upload_info.sha256.hex(),
|
| 934 |
+
"size": operation.upload_info.size,
|
| 935 |
+
},
|
| 936 |
+
}
|
| 937 |
+
# 2.c. Case deleting a file or folder
|
| 938 |
+
elif isinstance(operation, CommitOperationDelete):
|
| 939 |
+
yield {
|
| 940 |
+
"key": "deletedFolder" if operation.is_folder else "deletedFile",
|
| 941 |
+
"value": {"path": operation.path_in_repo},
|
| 942 |
+
}
|
| 943 |
+
# 2.d. Case copying a file or folder
|
| 944 |
+
elif isinstance(operation, CommitOperationCopy):
|
| 945 |
+
file_to_copy = files_to_copy[(operation.src_path_in_repo, operation.src_revision)]
|
| 946 |
+
if isinstance(file_to_copy, bytes):
|
| 947 |
+
yield {
|
| 948 |
+
"key": "file",
|
| 949 |
+
"value": {
|
| 950 |
+
"content": base64.b64encode(file_to_copy).decode(),
|
| 951 |
+
"path": operation.path_in_repo,
|
| 952 |
+
"encoding": "base64",
|
| 953 |
+
},
|
| 954 |
+
}
|
| 955 |
+
elif file_to_copy.lfs:
|
| 956 |
+
yield {
|
| 957 |
+
"key": "lfsFile",
|
| 958 |
+
"value": {
|
| 959 |
+
"path": operation.path_in_repo,
|
| 960 |
+
"algo": "sha256",
|
| 961 |
+
"oid": file_to_copy.lfs.sha256,
|
| 962 |
+
},
|
| 963 |
+
}
|
| 964 |
+
else:
|
| 965 |
+
raise ValueError(
|
| 966 |
+
"Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info."
|
| 967 |
+
)
|
| 968 |
+
# 2.e. Never expected to happen
|
| 969 |
+
else:
|
| 970 |
+
raise ValueError(
|
| 971 |
+
f"Unknown operation to commit. Operation: {operation}. Upload mode:"
|
| 972 |
+
f" {getattr(operation, '_upload_mode', None)}"
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
if nb_ignored_files > 0:
|
| 976 |
+
logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).")
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_commit_scheduler.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import atexit
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
from concurrent.futures import Future
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from io import SEEK_END, SEEK_SET, BytesIO
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from threading import Lock, Thread
|
| 10 |
+
from typing import Optional
|
| 11 |
+
|
| 12 |
+
from .hf_api import DEFAULT_IGNORE_PATTERNS, CommitInfo, CommitOperationAdd, HfApi
|
| 13 |
+
from .utils import filter_repo_objects
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass(frozen=True)
|
| 20 |
+
class _FileToUpload:
|
| 21 |
+
"""Temporary dataclass to store info about files to upload. Not meant to be used directly."""
|
| 22 |
+
|
| 23 |
+
local_path: Path
|
| 24 |
+
path_in_repo: str
|
| 25 |
+
size_limit: int
|
| 26 |
+
last_modified: float
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class CommitScheduler:
|
| 30 |
+
"""
|
| 31 |
+
Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
|
| 32 |
+
|
| 33 |
+
The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is
|
| 34 |
+
properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually
|
| 35 |
+
with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
|
| 36 |
+
to learn more about how to use it.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
repo_id (`str`):
|
| 40 |
+
The id of the repo to commit to.
|
| 41 |
+
folder_path (`str` or `Path`):
|
| 42 |
+
Path to the local folder to upload regularly.
|
| 43 |
+
every (`int` or `float`, *optional*):
|
| 44 |
+
The number of minutes between each commit. Defaults to 5 minutes.
|
| 45 |
+
path_in_repo (`str`, *optional*):
|
| 46 |
+
Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
|
| 47 |
+
of the repository.
|
| 48 |
+
repo_type (`str`, *optional*):
|
| 49 |
+
The type of the repo to commit to. Defaults to `model`.
|
| 50 |
+
revision (`str`, *optional*):
|
| 51 |
+
The revision of the repo to commit to. Defaults to `main`.
|
| 52 |
+
private (`bool`, *optional*):
|
| 53 |
+
Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
|
| 54 |
+
token (`str`, *optional*):
|
| 55 |
+
The token to use to commit to the repo. Defaults to the token saved on the machine.
|
| 56 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 57 |
+
If provided, only files matching at least one pattern are uploaded.
|
| 58 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 59 |
+
If provided, files matching any of the patterns are not uploaded.
|
| 60 |
+
squash_history (`bool`, *optional*):
|
| 61 |
+
Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
|
| 62 |
+
useful to avoid degraded performances on the repo when it grows too large.
|
| 63 |
+
hf_api (`HfApi`, *optional*):
|
| 64 |
+
The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
|
| 65 |
+
|
| 66 |
+
Example:
|
| 67 |
+
```py
|
| 68 |
+
>>> from pathlib import Path
|
| 69 |
+
>>> from huggingface_hub import CommitScheduler
|
| 70 |
+
|
| 71 |
+
# Scheduler uploads every 10 minutes
|
| 72 |
+
>>> csv_path = Path("watched_folder/data.csv")
|
| 73 |
+
>>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
|
| 74 |
+
|
| 75 |
+
>>> with csv_path.open("a") as f:
|
| 76 |
+
... f.write("first line")
|
| 77 |
+
|
| 78 |
+
# Some time later (...)
|
| 79 |
+
>>> with csv_path.open("a") as f:
|
| 80 |
+
... f.write("second line")
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
Example using a context manager:
|
| 84 |
+
```py
|
| 85 |
+
>>> from pathlib import Path
|
| 86 |
+
>>> from huggingface_hub import CommitScheduler
|
| 87 |
+
|
| 88 |
+
>>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
|
| 89 |
+
... csv_path = Path("watched_folder/data.csv")
|
| 90 |
+
... with csv_path.open("a") as f:
|
| 91 |
+
... f.write("first line")
|
| 92 |
+
... (...)
|
| 93 |
+
... with csv_path.open("a") as f:
|
| 94 |
+
... f.write("second line")
|
| 95 |
+
|
| 96 |
+
# Scheduler is now stopped and last commit have been triggered
|
| 97 |
+
```
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
*,
|
| 103 |
+
repo_id: str,
|
| 104 |
+
folder_path: str | Path,
|
| 105 |
+
every: int | float = 5,
|
| 106 |
+
path_in_repo: str | None = None,
|
| 107 |
+
repo_type: str | None = None,
|
| 108 |
+
revision: str | None = None,
|
| 109 |
+
private: bool | None = None,
|
| 110 |
+
token: str | None = None,
|
| 111 |
+
allow_patterns: list[str] | str | None = None,
|
| 112 |
+
ignore_patterns: list[str] | str | None = None,
|
| 113 |
+
squash_history: bool = False,
|
| 114 |
+
hf_api: Optional["HfApi"] = None,
|
| 115 |
+
) -> None:
|
| 116 |
+
self.api = hf_api or HfApi(token=token)
|
| 117 |
+
|
| 118 |
+
# Folder
|
| 119 |
+
self.folder_path = Path(folder_path).expanduser().resolve()
|
| 120 |
+
self.path_in_repo = path_in_repo or ""
|
| 121 |
+
self.allow_patterns = allow_patterns
|
| 122 |
+
|
| 123 |
+
if ignore_patterns is None:
|
| 124 |
+
ignore_patterns = []
|
| 125 |
+
elif isinstance(ignore_patterns, str):
|
| 126 |
+
ignore_patterns = [ignore_patterns]
|
| 127 |
+
self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
|
| 128 |
+
|
| 129 |
+
if self.folder_path.is_file():
|
| 130 |
+
raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.")
|
| 131 |
+
self.folder_path.mkdir(parents=True, exist_ok=True)
|
| 132 |
+
|
| 133 |
+
# Repository
|
| 134 |
+
repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True)
|
| 135 |
+
self.repo_id = repo_url.repo_id
|
| 136 |
+
self.repo_type = repo_type
|
| 137 |
+
self.revision = revision
|
| 138 |
+
self.token = token
|
| 139 |
+
|
| 140 |
+
# Keep track of already uploaded files
|
| 141 |
+
self.last_uploaded: dict[Path, float] = {} # key is local path, value is timestamp
|
| 142 |
+
|
| 143 |
+
# Scheduler
|
| 144 |
+
if not every > 0:
|
| 145 |
+
raise ValueError(f"'every' must be a positive integer, not '{every}'.")
|
| 146 |
+
self.lock = Lock()
|
| 147 |
+
self.every = every
|
| 148 |
+
self.squash_history = squash_history
|
| 149 |
+
|
| 150 |
+
logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.")
|
| 151 |
+
self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True)
|
| 152 |
+
self._scheduler_thread.start()
|
| 153 |
+
atexit.register(self._push_to_hub)
|
| 154 |
+
|
| 155 |
+
self.__stopped = False
|
| 156 |
+
|
| 157 |
+
def stop(self) -> None:
|
| 158 |
+
"""Stop the scheduler.
|
| 159 |
+
|
| 160 |
+
A stopped scheduler cannot be restarted. Mostly for tests purposes.
|
| 161 |
+
"""
|
| 162 |
+
self.__stopped = True
|
| 163 |
+
|
| 164 |
+
def __enter__(self) -> "CommitScheduler":
|
| 165 |
+
return self
|
| 166 |
+
|
| 167 |
+
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
| 168 |
+
# Upload last changes before exiting
|
| 169 |
+
self.trigger().result()
|
| 170 |
+
self.stop()
|
| 171 |
+
return
|
| 172 |
+
|
| 173 |
+
def _run_scheduler(self) -> None:
|
| 174 |
+
"""Dumb thread waiting between each scheduled push to Hub."""
|
| 175 |
+
while True:
|
| 176 |
+
self.last_future = self.trigger()
|
| 177 |
+
time.sleep(self.every * 60)
|
| 178 |
+
if self.__stopped:
|
| 179 |
+
break
|
| 180 |
+
|
| 181 |
+
def trigger(self) -> Future:
|
| 182 |
+
"""Trigger a `push_to_hub` and return a future.
|
| 183 |
+
|
| 184 |
+
This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
|
| 185 |
+
immediately, without waiting for the next scheduled commit.
|
| 186 |
+
"""
|
| 187 |
+
return self.api.run_as_future(self._push_to_hub)
|
| 188 |
+
|
| 189 |
+
def _push_to_hub(self) -> CommitInfo | None:
|
| 190 |
+
if self.__stopped: # If stopped, already scheduled commits are ignored
|
| 191 |
+
return None
|
| 192 |
+
|
| 193 |
+
logger.info("(Background) scheduled commit triggered.")
|
| 194 |
+
try:
|
| 195 |
+
value = self.push_to_hub()
|
| 196 |
+
if self.squash_history:
|
| 197 |
+
logger.info("(Background) squashing repo history.")
|
| 198 |
+
self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision)
|
| 199 |
+
return value
|
| 200 |
+
except Exception as e:
|
| 201 |
+
logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced
|
| 202 |
+
raise
|
| 203 |
+
|
| 204 |
+
def push_to_hub(self) -> CommitInfo | None:
|
| 205 |
+
"""
|
| 206 |
+
Push folder to the Hub and return the commit info.
|
| 207 |
+
|
| 208 |
+
> [!WARNING]
|
| 209 |
+
> This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
|
| 210 |
+
> queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
|
| 211 |
+
> issues.
|
| 212 |
+
|
| 213 |
+
The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
|
| 214 |
+
uploads only changed files. If no changes are found, the method returns without committing anything. If you want
|
| 215 |
+
to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
|
| 216 |
+
for example to compress data together in a single file before committing. For more details and examples, check
|
| 217 |
+
out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
|
| 218 |
+
"""
|
| 219 |
+
# Check files to upload (with lock)
|
| 220 |
+
with self.lock:
|
| 221 |
+
logger.debug("Listing files to upload for scheduled commit.")
|
| 222 |
+
|
| 223 |
+
# List files from folder (taken from `_prepare_upload_folder_additions`)
|
| 224 |
+
relpath_to_abspath = {
|
| 225 |
+
path.relative_to(self.folder_path).as_posix(): path
|
| 226 |
+
for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic
|
| 227 |
+
if path.is_file()
|
| 228 |
+
}
|
| 229 |
+
prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
|
| 230 |
+
|
| 231 |
+
# Filter with pattern + filter out unchanged files + retrieve current file size
|
| 232 |
+
files_to_upload: list[_FileToUpload] = []
|
| 233 |
+
for relpath in filter_repo_objects(
|
| 234 |
+
relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns
|
| 235 |
+
):
|
| 236 |
+
local_path = relpath_to_abspath[relpath]
|
| 237 |
+
stat = local_path.stat()
|
| 238 |
+
if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime:
|
| 239 |
+
files_to_upload.append(
|
| 240 |
+
_FileToUpload(
|
| 241 |
+
local_path=local_path,
|
| 242 |
+
path_in_repo=prefix + relpath,
|
| 243 |
+
size_limit=stat.st_size,
|
| 244 |
+
last_modified=stat.st_mtime,
|
| 245 |
+
)
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
# Return if nothing to upload
|
| 249 |
+
if len(files_to_upload) == 0:
|
| 250 |
+
logger.debug("Dropping schedule commit: no changed file to upload.")
|
| 251 |
+
return None
|
| 252 |
+
|
| 253 |
+
# Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size)
|
| 254 |
+
logger.debug("Removing unchanged files since previous scheduled commit.")
|
| 255 |
+
add_operations = [
|
| 256 |
+
CommitOperationAdd(
|
| 257 |
+
# Cap the file to its current size, even if the user append data to it while a scheduled commit is happening
|
| 258 |
+
path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit),
|
| 259 |
+
path_in_repo=file_to_upload.path_in_repo,
|
| 260 |
+
)
|
| 261 |
+
for file_to_upload in files_to_upload
|
| 262 |
+
]
|
| 263 |
+
|
| 264 |
+
# Upload files (append mode expected - no need for lock)
|
| 265 |
+
logger.debug("Uploading files for scheduled commit.")
|
| 266 |
+
commit_info = self.api.create_commit(
|
| 267 |
+
repo_id=self.repo_id,
|
| 268 |
+
repo_type=self.repo_type,
|
| 269 |
+
operations=add_operations,
|
| 270 |
+
commit_message="Scheduled Commit",
|
| 271 |
+
revision=self.revision,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
# Successful commit: keep track of the latest "last_modified" for each file
|
| 275 |
+
for file in files_to_upload:
|
| 276 |
+
self.last_uploaded[file.local_path] = file.last_modified
|
| 277 |
+
return commit_info
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class PartialFileIO(BytesIO):
|
| 281 |
+
"""A file-like object that reads only the first part of a file.
|
| 282 |
+
|
| 283 |
+
Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the
|
| 284 |
+
file is uploaded (i.e. the part that was available when the filesystem was first scanned).
|
| 285 |
+
|
| 286 |
+
In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal
|
| 287 |
+
disturbance for the user. The object is passed to `CommitOperationAdd`.
|
| 288 |
+
|
| 289 |
+
Only supports `read`, `tell` and `seek` methods.
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
file_path (`str` or `Path`):
|
| 293 |
+
Path to the file to read.
|
| 294 |
+
size_limit (`int`):
|
| 295 |
+
The maximum number of bytes to read from the file. If the file is larger than this, only the first part
|
| 296 |
+
will be read (and uploaded).
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
def __init__(self, file_path: str | Path, size_limit: int) -> None:
|
| 300 |
+
self._file_path = Path(file_path)
|
| 301 |
+
self._file = self._file_path.open("rb")
|
| 302 |
+
self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
|
| 303 |
+
|
| 304 |
+
def __del__(self) -> None:
|
| 305 |
+
self._file.close()
|
| 306 |
+
return super().__del__()
|
| 307 |
+
|
| 308 |
+
def __repr__(self) -> str:
|
| 309 |
+
return f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
|
| 310 |
+
|
| 311 |
+
def __len__(self) -> int:
|
| 312 |
+
return self._size_limit
|
| 313 |
+
|
| 314 |
+
def __getattribute__(self, name: str):
|
| 315 |
+
if name.startswith("_") or name in ("read", "tell", "seek", "fileno"): # only 4 public methods supported
|
| 316 |
+
return super().__getattribute__(name)
|
| 317 |
+
raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
|
| 318 |
+
|
| 319 |
+
def fileno(self):
|
| 320 |
+
raise AttributeError("PartialFileIO does not have a fileno.")
|
| 321 |
+
|
| 322 |
+
def tell(self) -> int:
|
| 323 |
+
"""Return the current file position."""
|
| 324 |
+
return self._file.tell()
|
| 325 |
+
|
| 326 |
+
def seek(self, __offset: int, __whence: int = SEEK_SET) -> int:
|
| 327 |
+
"""Change the stream position to the given offset.
|
| 328 |
+
|
| 329 |
+
Behavior is the same as a regular file, except that the position is capped to the size limit.
|
| 330 |
+
"""
|
| 331 |
+
if __whence == SEEK_END:
|
| 332 |
+
# SEEK_END => set from the truncated end
|
| 333 |
+
__offset = len(self) + __offset
|
| 334 |
+
__whence = SEEK_SET
|
| 335 |
+
|
| 336 |
+
pos = self._file.seek(__offset, __whence)
|
| 337 |
+
if pos > self._size_limit:
|
| 338 |
+
return self._file.seek(self._size_limit)
|
| 339 |
+
return pos
|
| 340 |
+
|
| 341 |
+
def read(self, __size: int | None = -1) -> bytes:
|
| 342 |
+
"""Read at most `__size` bytes from the file.
|
| 343 |
+
|
| 344 |
+
Behavior is the same as a regular file, except that it is capped to the size limit.
|
| 345 |
+
"""
|
| 346 |
+
current = self._file.tell()
|
| 347 |
+
if __size is None or __size < 0:
|
| 348 |
+
# Read until file limit
|
| 349 |
+
truncated_size = self._size_limit - current
|
| 350 |
+
else:
|
| 351 |
+
# Read until file limit or __size
|
| 352 |
+
truncated_size = min(__size, self._size_limit - current)
|
| 353 |
+
return self._file.read(truncated_size)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_dataset_viewer.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import shutil
|
| 17 |
+
import subprocess
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import TYPE_CHECKING, Any, Union
|
| 20 |
+
|
| 21 |
+
from . import constants
|
| 22 |
+
from .utils import get_token
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
import duckdb
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass(frozen=True)
|
| 30 |
+
class DatasetParquetEntry:
|
| 31 |
+
"""Represents a single parquet file available for a dataset on the Hub."""
|
| 32 |
+
|
| 33 |
+
config: str
|
| 34 |
+
split: str
|
| 35 |
+
url: str
|
| 36 |
+
size: int
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def execute_raw_sql_query(sql_query: str, *, token: str | bool | None = None) -> list[dict[str, Any]]:
|
| 40 |
+
normalized_query = sql_query.strip().rstrip(";").strip()
|
| 41 |
+
_raise_on_forbidden_query(normalized_query)
|
| 42 |
+
|
| 43 |
+
connection = None
|
| 44 |
+
try:
|
| 45 |
+
connection = _get_duckdb_connection(token=token)
|
| 46 |
+
relation = connection.sql(normalized_query)
|
| 47 |
+
if relation is None:
|
| 48 |
+
raise ValueError("SQL query must return rows.")
|
| 49 |
+
|
| 50 |
+
if isinstance(relation, _DuckDBCliRelation):
|
| 51 |
+
# DuckDB binary => run CLI => parse JSON
|
| 52 |
+
return relation.execute()
|
| 53 |
+
else:
|
| 54 |
+
# DuckDB Python API => fetch columns + rows => convert to dicts
|
| 55 |
+
columns = tuple(column[0] for column in relation.description)
|
| 56 |
+
rows = tuple(tuple(row) for row in relation.fetchall())
|
| 57 |
+
return [dict(zip(columns, row)) for row in rows]
|
| 58 |
+
finally:
|
| 59 |
+
if connection is not None:
|
| 60 |
+
connection.close()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _raise_on_forbidden_query(query: str) -> None:
|
| 64 |
+
if len(query) == 0:
|
| 65 |
+
raise ValueError("SQL query cannot be empty.")
|
| 66 |
+
|
| 67 |
+
# DuckDB CLI meta-commands are dot-prefixed words (e.g. `.shell`, `.output`).
|
| 68 |
+
# Let's forbid them for now but allow SQL expressions like `.5` that can legitimately start a line.
|
| 69 |
+
for line in query.splitlines():
|
| 70 |
+
stripped = line.lstrip()
|
| 71 |
+
if stripped.startswith(".") and stripped[1:2].isalpha():
|
| 72 |
+
raise ValueError("DuckDB CLI meta-commands are not allowed in SQL queries.")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _get_duckdb_connection(
|
| 76 |
+
token: str | bool | None,
|
| 77 |
+
) -> Union["duckdb.DuckDBPyConnection", "_DuckDBCliConnection"]:
|
| 78 |
+
try:
|
| 79 |
+
# If DuckDB is installed as a Python package, use it!
|
| 80 |
+
import duckdb
|
| 81 |
+
except ImportError as error:
|
| 82 |
+
# Otherwise, use the DuckDB CLI binary.
|
| 83 |
+
duckdb_binary = shutil.which("duckdb")
|
| 84 |
+
if duckdb_binary is None:
|
| 85 |
+
raise ImportError(
|
| 86 |
+
"DuckDB is required for `hf datasets sql`. Install the Python package with `pip install duckdb` or "
|
| 87 |
+
"install the DuckDB CLI binary (for example `brew install duckdb`)."
|
| 88 |
+
) from error
|
| 89 |
+
return _DuckDBCliConnection(binary_path=duckdb_binary, token=token)
|
| 90 |
+
|
| 91 |
+
# Create a new connection (Python API).
|
| 92 |
+
connection = duckdb.connect()
|
| 93 |
+
try:
|
| 94 |
+
for statement in _build_duckdb_secret_statements(token):
|
| 95 |
+
connection.execute(statement)
|
| 96 |
+
return connection
|
| 97 |
+
except Exception:
|
| 98 |
+
connection.close()
|
| 99 |
+
raise
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@dataclass
|
| 103 |
+
class _DuckDBCliConnection:
|
| 104 |
+
"""DuckDB connection.
|
| 105 |
+
|
| 106 |
+
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary.
|
| 107 |
+
"""
|
| 108 |
+
|
| 109 |
+
binary_path: str
|
| 110 |
+
token: str | bool | None
|
| 111 |
+
|
| 112 |
+
def __post_init__(self) -> None:
|
| 113 |
+
self._setup_statements = _build_duckdb_secret_statements(self.token)
|
| 114 |
+
|
| 115 |
+
def sql(self, query: str) -> "_DuckDBCliRelation":
|
| 116 |
+
return _DuckDBCliRelation(binary_path=self.binary_path, setup_statements=self._setup_statements, query=query)
|
| 117 |
+
|
| 118 |
+
def close(self) -> None:
|
| 119 |
+
pass
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class _DuckDBCliRelation:
|
| 124 |
+
"""DuckDB relation.
|
| 125 |
+
|
| 126 |
+
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
binary_path: str
|
| 130 |
+
setup_statements: list[str]
|
| 131 |
+
query: str
|
| 132 |
+
|
| 133 |
+
def execute(self) -> list[dict[str, Any]]:
|
| 134 |
+
# Build the DuckDB CLI input.
|
| 135 |
+
setup = []
|
| 136 |
+
if self.setup_statements:
|
| 137 |
+
setup = [
|
| 138 |
+
f".output {os.devnull}",
|
| 139 |
+
*(f"{stmt};" for stmt in self.setup_statements),
|
| 140 |
+
".output",
|
| 141 |
+
]
|
| 142 |
+
full_query = "\n".join(setup + [self.query + ";"])
|
| 143 |
+
|
| 144 |
+
# Run DuckDB binary
|
| 145 |
+
result = subprocess.run(
|
| 146 |
+
[self.binary_path, "-json"],
|
| 147 |
+
input=full_query,
|
| 148 |
+
capture_output=True,
|
| 149 |
+
text=True,
|
| 150 |
+
check=False,
|
| 151 |
+
)
|
| 152 |
+
if result.returncode != 0:
|
| 153 |
+
error_message = result.stderr.strip() or result.stdout.strip() or "DuckDB CLI command failed."
|
| 154 |
+
raise RuntimeError(error_message)
|
| 155 |
+
|
| 156 |
+
# Parse JSON output and return
|
| 157 |
+
return json.loads(result.stdout.strip())
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _build_duckdb_secret_statements(token: str | bool | None) -> list[str]:
|
| 161 |
+
if token is None or token is True:
|
| 162 |
+
token = get_token()
|
| 163 |
+
|
| 164 |
+
if not token:
|
| 165 |
+
return []
|
| 166 |
+
|
| 167 |
+
escaped_token = token.replace("'", "''")
|
| 168 |
+
escaped_endpoint = constants.ENDPOINT.replace("'", "''")
|
| 169 |
+
return [
|
| 170 |
+
f"CREATE OR REPLACE SECRET hf_hub_token (TYPE HTTP, BEARER_TOKEN '{escaped_token}', SCOPE '{escaped_endpoint}')",
|
| 171 |
+
f"CREATE OR REPLACE SECRET hf_token (TYPE HUGGINGFACE, TOKEN '{escaped_token}')",
|
| 172 |
+
]
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_eval_results.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evaluation results utilities for the `.eval_results/*.yaml` format.
|
| 2 |
+
|
| 3 |
+
See https://huggingface.co/docs/hub/eval-results for more details.
|
| 4 |
+
Specifications are available at https://github.com/huggingface/hub-docs/blob/main/eval_results.yaml.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class EvalResultEntry:
|
| 13 |
+
"""
|
| 14 |
+
Evaluation result entry for the `.eval_results/*.yaml` format.
|
| 15 |
+
|
| 16 |
+
Represents evaluation scores stored in model repos that automatically appear on
|
| 17 |
+
the model page and the benchmark dataset's leaderboard.
|
| 18 |
+
|
| 19 |
+
For the legacy `model-index` format in `README.md`, use [`EvalResult`] instead.
|
| 20 |
+
|
| 21 |
+
See https://huggingface.co/docs/hub/eval-results for more details.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
dataset_id (`str`):
|
| 25 |
+
Benchmark dataset ID from the Hub. Example: "cais/hle", "Idavidrein/gpqa".
|
| 26 |
+
task_id (`str`):
|
| 27 |
+
Task identifier within the benchmark. Example: "gpqa_diamond".
|
| 28 |
+
value (`Any`):
|
| 29 |
+
The metric value. Example: 20.90.
|
| 30 |
+
dataset_revision (`str`, *optional*):
|
| 31 |
+
Git SHA of the benchmark dataset.
|
| 32 |
+
verify_token (`str`, *optional*):
|
| 33 |
+
A signature that can be used to prove that evaluation is provably auditable and reproducible.
|
| 34 |
+
date (`str`, *optional*):
|
| 35 |
+
When the evaluation was run (ISO-8601 datetime). Defaults to git commit time.
|
| 36 |
+
source_url (`str`, *optional*):
|
| 37 |
+
Link to the evaluation source (e.g., https://huggingface.co/spaces/SaylorTwift/smollm3-mmlu-pro). Required if `source_name`, `source_user`, or `source_org` is provided.
|
| 38 |
+
source_name (`str`, *optional*):
|
| 39 |
+
Display name for the source. Example: "Eval Logs".
|
| 40 |
+
source_user (`str`, *optional*):
|
| 41 |
+
HF user name for attribution. Example: "celinah".
|
| 42 |
+
source_org (`str`, *optional*):
|
| 43 |
+
HF org name for attribution. Example: "cais".
|
| 44 |
+
notes (`str`, *optional*):
|
| 45 |
+
Details about the evaluation setup. Example: "tools", "no-tools", "chain-of-thought".
|
| 46 |
+
|
| 47 |
+
Example:
|
| 48 |
+
```python
|
| 49 |
+
>>> from huggingface_hub import EvalResultEntry
|
| 50 |
+
>>> # Minimal example with required fields only
|
| 51 |
+
>>> result = EvalResultEntry(
|
| 52 |
+
... dataset_id="Idavidrein/gpqa",
|
| 53 |
+
... task_id="gpqa_diamond",
|
| 54 |
+
... value=0.412,
|
| 55 |
+
... )
|
| 56 |
+
>>> # Full example with all fields
|
| 57 |
+
>>> result = EvalResultEntry(
|
| 58 |
+
... dataset_id="cais/hle",
|
| 59 |
+
... task_id="default",
|
| 60 |
+
... value=20.90,
|
| 61 |
+
... dataset_revision="5503434ddd753f426f4b38109466949a1217c2bb",
|
| 62 |
+
... verify_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
| 63 |
+
... date="2025-01-15T10:30:00Z",
|
| 64 |
+
... source_url="https://huggingface.co/datasets/cais/hle",
|
| 65 |
+
... source_name="CAIS HLE",
|
| 66 |
+
... source_org="cais",
|
| 67 |
+
... notes="no-tools",
|
| 68 |
+
... )
|
| 69 |
+
|
| 70 |
+
```
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
dataset_id: str
|
| 74 |
+
task_id: str
|
| 75 |
+
value: Any
|
| 76 |
+
dataset_revision: str | None = None
|
| 77 |
+
verify_token: str | None = None
|
| 78 |
+
date: str | None = None
|
| 79 |
+
source_url: str | None = None
|
| 80 |
+
source_name: str | None = None
|
| 81 |
+
source_user: str | None = None
|
| 82 |
+
source_org: str | None = None
|
| 83 |
+
notes: str | None = None
|
| 84 |
+
|
| 85 |
+
def __post_init__(self) -> None:
|
| 86 |
+
if (
|
| 87 |
+
self.source_name is not None or self.source_user is not None or self.source_org is not None
|
| 88 |
+
) and self.source_url is None:
|
| 89 |
+
raise ValueError(
|
| 90 |
+
"If `source_name`, `source_user`, or `source_org` is provided, `source_url` must also be provided."
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def eval_result_entries_to_yaml(entries: list[EvalResultEntry]) -> list[dict[str, Any]]:
|
| 95 |
+
"""Convert a list of [`EvalResultEntry`] objects to a YAML-serializable list of dicts.
|
| 96 |
+
|
| 97 |
+
This produces the format expected in `.eval_results/*.yaml` files.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
entries (`list[EvalResultEntry]`):
|
| 101 |
+
List of evaluation result entries to serialize.
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
`list[dict[str, Any]]`: A list of dictionaries ready to be dumped to YAML.
|
| 105 |
+
|
| 106 |
+
Example:
|
| 107 |
+
```python
|
| 108 |
+
>>> from huggingface_hub import EvalResultEntry, eval_result_entries_to_yaml
|
| 109 |
+
>>> entries = [
|
| 110 |
+
... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90),
|
| 111 |
+
... EvalResultEntry(dataset_id="Idavidrein/gpqa", task_id="gpqa_diamond", value=0.412),
|
| 112 |
+
... ]
|
| 113 |
+
>>> yaml_data = eval_result_entries_to_yaml(entries)
|
| 114 |
+
>>> yaml_data[0]
|
| 115 |
+
{'dataset': {'id': 'cais/hle', 'task_id': 'default'}, 'value': 20.9}
|
| 116 |
+
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
To upload eval results to the Hub:
|
| 120 |
+
```python
|
| 121 |
+
>>> import yaml
|
| 122 |
+
>>> from huggingface_hub import upload_file, EvalResultEntry, eval_result_entries_to_yaml
|
| 123 |
+
>>> entries = [
|
| 124 |
+
... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90),
|
| 125 |
+
... ]
|
| 126 |
+
>>> yaml_content = yaml.dump(eval_result_entries_to_yaml(entries))
|
| 127 |
+
>>> upload_file(
|
| 128 |
+
... path_or_fileobj=yaml_content.encode(),
|
| 129 |
+
... path_in_repo=".eval_results/hle.yaml",
|
| 130 |
+
... repo_id="your-username/your-model",
|
| 131 |
+
... )
|
| 132 |
+
|
| 133 |
+
```
|
| 134 |
+
"""
|
| 135 |
+
result = []
|
| 136 |
+
for entry in entries:
|
| 137 |
+
# build the dataset object
|
| 138 |
+
dataset: dict[str, Any] = {"id": entry.dataset_id, "task_id": entry.task_id}
|
| 139 |
+
if entry.dataset_revision is not None:
|
| 140 |
+
dataset["revision"] = entry.dataset_revision
|
| 141 |
+
|
| 142 |
+
data: dict[str, Any] = {"dataset": dataset, "value": entry.value}
|
| 143 |
+
if entry.verify_token is not None:
|
| 144 |
+
data["verifyToken"] = entry.verify_token
|
| 145 |
+
if entry.date is not None:
|
| 146 |
+
data["date"] = entry.date
|
| 147 |
+
# build the source object
|
| 148 |
+
if entry.source_url is not None:
|
| 149 |
+
source: dict[str, Any] = {"url": entry.source_url}
|
| 150 |
+
if entry.source_name is not None:
|
| 151 |
+
source["name"] = entry.source_name
|
| 152 |
+
if entry.source_user is not None:
|
| 153 |
+
source["user"] = entry.source_user
|
| 154 |
+
if entry.source_org is not None:
|
| 155 |
+
source["org"] = entry.source_org
|
| 156 |
+
data["source"] = source
|
| 157 |
+
if entry.notes is not None:
|
| 158 |
+
data["notes"] = entry.notes
|
| 159 |
+
|
| 160 |
+
result.append(data)
|
| 161 |
+
return result
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def parse_eval_result_entries(data: list[dict[str, Any]]) -> list[EvalResultEntry]:
|
| 165 |
+
"""Parse a list of dicts into [`EvalResultEntry`] objects.
|
| 166 |
+
|
| 167 |
+
This parses the `.eval_results/*.yaml` format. For the legacy `model-index` format,
|
| 168 |
+
use [`model_index_to_eval_results`] instead.
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
data (`list[dict[str, Any]]`):
|
| 172 |
+
A list of dictionaries (e.g., parsed from YAML or API response).
|
| 173 |
+
|
| 174 |
+
Returns:
|
| 175 |
+
`list[EvalResultEntry]`: A list of evaluation result entry objects.
|
| 176 |
+
|
| 177 |
+
Example:
|
| 178 |
+
```python
|
| 179 |
+
>>> from huggingface_hub import parse_eval_result_entries
|
| 180 |
+
>>> data = [
|
| 181 |
+
... {"dataset": {"id": "cais/hle", "task_id": "default"}, "value": 20.90},
|
| 182 |
+
... {"dataset": {"id": "Idavidrein/gpqa", "task_id": "gpqa_diamond"}, "value": 0.412},
|
| 183 |
+
... ]
|
| 184 |
+
>>> entries = parse_eval_result_entries(data)
|
| 185 |
+
>>> entries[0].dataset_id
|
| 186 |
+
'cais/hle'
|
| 187 |
+
>>> entries[0].value
|
| 188 |
+
20.9
|
| 189 |
+
|
| 190 |
+
```
|
| 191 |
+
"""
|
| 192 |
+
entries = []
|
| 193 |
+
for item in data:
|
| 194 |
+
entry_data = item.get("data", item)
|
| 195 |
+
dataset = entry_data.get("dataset", {})
|
| 196 |
+
source = entry_data.get("source", {})
|
| 197 |
+
entry = EvalResultEntry(
|
| 198 |
+
dataset_id=dataset["id"],
|
| 199 |
+
value=entry_data["value"],
|
| 200 |
+
task_id=dataset["task_id"],
|
| 201 |
+
dataset_revision=dataset.get("revision"),
|
| 202 |
+
verify_token=entry_data.get("verifyToken"),
|
| 203 |
+
date=entry_data.get("date"),
|
| 204 |
+
source_url=source.get("url") if source else None,
|
| 205 |
+
source_name=source.get("name") if source else None,
|
| 206 |
+
source_user=source.get("user") if source else None,
|
| 207 |
+
source_org=source.get("org") if source else None,
|
| 208 |
+
notes=entry_data.get("notes"),
|
| 209 |
+
)
|
| 210 |
+
entries.append(entry)
|
| 211 |
+
return entries
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_inference_endpoints.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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1 |
+
import time
|
| 2 |
+
from dataclasses import dataclass, field
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from enum import Enum
|
| 5 |
+
from typing import TYPE_CHECKING, Optional
|
| 6 |
+
|
| 7 |
+
from huggingface_hub.errors import InferenceEndpointError, InferenceEndpointTimeoutError
|
| 8 |
+
|
| 9 |
+
from .utils import get_session, logging, parse_datetime
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from .hf_api import HfApi
|
| 14 |
+
from .inference._client import InferenceClient
|
| 15 |
+
from .inference._generated._async_client import AsyncInferenceClient
|
| 16 |
+
|
| 17 |
+
logger = logging.get_logger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class InferenceEndpointStatus(str, Enum):
|
| 21 |
+
PENDING = "pending"
|
| 22 |
+
INITIALIZING = "initializing"
|
| 23 |
+
UPDATING = "updating"
|
| 24 |
+
UPDATE_FAILED = "updateFailed"
|
| 25 |
+
RUNNING = "running"
|
| 26 |
+
PAUSED = "paused"
|
| 27 |
+
FAILED = "failed"
|
| 28 |
+
SCALED_TO_ZERO = "scaledToZero"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class InferenceEndpointType(str, Enum):
|
| 32 |
+
PUBlIC = "public"
|
| 33 |
+
PROTECTED = "protected"
|
| 34 |
+
PRIVATE = "private"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class InferenceEndpointScalingMetric(str, Enum):
|
| 38 |
+
PENDING_REQUESTS = "pendingRequests"
|
| 39 |
+
HARDWARE_USAGE = "hardwareUsage"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class InferenceEndpoint:
|
| 44 |
+
"""
|
| 45 |
+
Contains information about a deployed Inference Endpoint.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
name (`str`):
|
| 49 |
+
The unique name of the Inference Endpoint.
|
| 50 |
+
namespace (`str`):
|
| 51 |
+
The namespace where the Inference Endpoint is located.
|
| 52 |
+
repository (`str`):
|
| 53 |
+
The name of the model repository deployed on this Inference Endpoint.
|
| 54 |
+
status ([`InferenceEndpointStatus`]):
|
| 55 |
+
The current status of the Inference Endpoint.
|
| 56 |
+
url (`str`, *optional*):
|
| 57 |
+
The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL.
|
| 58 |
+
framework (`str`):
|
| 59 |
+
The machine learning framework used for the model.
|
| 60 |
+
revision (`str`):
|
| 61 |
+
The specific model revision deployed on the Inference Endpoint.
|
| 62 |
+
task (`str`):
|
| 63 |
+
The task associated with the deployed model.
|
| 64 |
+
created_at (`datetime.datetime`):
|
| 65 |
+
The timestamp when the Inference Endpoint was created.
|
| 66 |
+
updated_at (`datetime.datetime`):
|
| 67 |
+
The timestamp of the last update of the Inference Endpoint.
|
| 68 |
+
type ([`InferenceEndpointType`]):
|
| 69 |
+
The type of the Inference Endpoint (public, protected, private).
|
| 70 |
+
raw (`dict`):
|
| 71 |
+
The raw dictionary data returned from the API.
|
| 72 |
+
token (`str` or `bool`, *optional*):
|
| 73 |
+
Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the
|
| 74 |
+
locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server.
|
| 75 |
+
|
| 76 |
+
Example:
|
| 77 |
+
```python
|
| 78 |
+
>>> from huggingface_hub import get_inference_endpoint
|
| 79 |
+
>>> endpoint = get_inference_endpoint("my-text-to-image")
|
| 80 |
+
>>> endpoint
|
| 81 |
+
InferenceEndpoint(name='my-text-to-image', ...)
|
| 82 |
+
|
| 83 |
+
# Get status
|
| 84 |
+
>>> endpoint.status
|
| 85 |
+
'running'
|
| 86 |
+
>>> endpoint.url
|
| 87 |
+
'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
|
| 88 |
+
|
| 89 |
+
# Run inference
|
| 90 |
+
>>> endpoint.client.text_to_image(...)
|
| 91 |
+
|
| 92 |
+
# Pause endpoint to save $$$
|
| 93 |
+
>>> endpoint.pause()
|
| 94 |
+
|
| 95 |
+
# ...
|
| 96 |
+
# Resume and wait for deployment
|
| 97 |
+
>>> endpoint.resume()
|
| 98 |
+
>>> endpoint.wait()
|
| 99 |
+
>>> endpoint.client.text_to_image(...)
|
| 100 |
+
```
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
# Field in __repr__
|
| 104 |
+
name: str = field(init=False)
|
| 105 |
+
namespace: str
|
| 106 |
+
repository: str = field(init=False)
|
| 107 |
+
status: InferenceEndpointStatus = field(init=False)
|
| 108 |
+
health_route: str = field(init=False)
|
| 109 |
+
url: str | None = field(init=False)
|
| 110 |
+
|
| 111 |
+
# Other fields
|
| 112 |
+
framework: str = field(repr=False, init=False)
|
| 113 |
+
revision: str = field(repr=False, init=False)
|
| 114 |
+
task: str = field(repr=False, init=False)
|
| 115 |
+
created_at: datetime = field(repr=False, init=False)
|
| 116 |
+
updated_at: datetime = field(repr=False, init=False)
|
| 117 |
+
type: InferenceEndpointType = field(repr=False, init=False)
|
| 118 |
+
|
| 119 |
+
# Raw dict from the API
|
| 120 |
+
raw: dict = field(repr=False)
|
| 121 |
+
|
| 122 |
+
# Internal fields
|
| 123 |
+
_token: str | bool | None = field(repr=False, compare=False)
|
| 124 |
+
_api: "HfApi" = field(repr=False, compare=False)
|
| 125 |
+
|
| 126 |
+
@classmethod
|
| 127 |
+
def from_raw(
|
| 128 |
+
cls, raw: dict, namespace: str, token: str | bool | None = None, api: Optional["HfApi"] = None
|
| 129 |
+
) -> "InferenceEndpoint":
|
| 130 |
+
"""Initialize object from raw dictionary."""
|
| 131 |
+
if api is None:
|
| 132 |
+
from .hf_api import HfApi
|
| 133 |
+
|
| 134 |
+
api = HfApi()
|
| 135 |
+
if token is None:
|
| 136 |
+
token = api.token
|
| 137 |
+
|
| 138 |
+
# All other fields are populated in __post_init__
|
| 139 |
+
return cls(raw=raw, namespace=namespace, _token=token, _api=api)
|
| 140 |
+
|
| 141 |
+
def __post_init__(self) -> None:
|
| 142 |
+
"""Populate fields from raw dictionary."""
|
| 143 |
+
self._populate_from_raw()
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def client(self) -> "InferenceClient":
|
| 147 |
+
"""Returns a client to make predictions on this Inference Endpoint.
|
| 148 |
+
|
| 149 |
+
Returns:
|
| 150 |
+
[`InferenceClient`]: an inference client pointing to the deployed endpoint.
|
| 151 |
+
|
| 152 |
+
Raises:
|
| 153 |
+
[`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
|
| 154 |
+
"""
|
| 155 |
+
if self.url is None:
|
| 156 |
+
raise InferenceEndpointError(
|
| 157 |
+
"Cannot create a client for this Inference Endpoint as it is not yet deployed. "
|
| 158 |
+
"Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
|
| 159 |
+
)
|
| 160 |
+
from .inference._client import InferenceClient
|
| 161 |
+
|
| 162 |
+
return InferenceClient(
|
| 163 |
+
model=self.url,
|
| 164 |
+
token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok.
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def async_client(self) -> "AsyncInferenceClient":
|
| 169 |
+
"""Returns a client to make predictions on this Inference Endpoint.
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
[`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint.
|
| 173 |
+
|
| 174 |
+
Raises:
|
| 175 |
+
[`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
|
| 176 |
+
"""
|
| 177 |
+
if self.url is None:
|
| 178 |
+
raise InferenceEndpointError(
|
| 179 |
+
"Cannot create a client for this Inference Endpoint as it is not yet deployed. "
|
| 180 |
+
"Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
|
| 181 |
+
)
|
| 182 |
+
from .inference._generated._async_client import AsyncInferenceClient
|
| 183 |
+
|
| 184 |
+
return AsyncInferenceClient(
|
| 185 |
+
model=self.url,
|
| 186 |
+
token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok.
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
def wait(self, timeout: int | None = None, refresh_every: int = 5) -> "InferenceEndpoint":
|
| 190 |
+
"""Wait for the Inference Endpoint to be deployed.
|
| 191 |
+
|
| 192 |
+
Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout`
|
| 193 |
+
seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest
|
| 194 |
+
data.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
timeout (`int`, *optional*):
|
| 198 |
+
The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait
|
| 199 |
+
indefinitely.
|
| 200 |
+
refresh_every (`int`, *optional*):
|
| 201 |
+
The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s.
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| 205 |
+
|
| 206 |
+
Raises:
|
| 207 |
+
[`InferenceEndpointError`]
|
| 208 |
+
If the Inference Endpoint ended up in a failed state.
|
| 209 |
+
[`InferenceEndpointTimeoutError`]
|
| 210 |
+
If the Inference Endpoint is not deployed after `timeout` seconds.
|
| 211 |
+
"""
|
| 212 |
+
if timeout is not None and timeout < 0:
|
| 213 |
+
raise ValueError("`timeout` cannot be negative.")
|
| 214 |
+
if refresh_every <= 0:
|
| 215 |
+
raise ValueError("`refresh_every` must be positive.")
|
| 216 |
+
|
| 217 |
+
start = time.time()
|
| 218 |
+
while True:
|
| 219 |
+
if self.status == InferenceEndpointStatus.FAILED:
|
| 220 |
+
raise InferenceEndpointError(
|
| 221 |
+
f"Inference Endpoint {self.name} failed to deploy. Please check the logs for more information."
|
| 222 |
+
)
|
| 223 |
+
if self.status == InferenceEndpointStatus.UPDATE_FAILED:
|
| 224 |
+
raise InferenceEndpointError(
|
| 225 |
+
f"Inference Endpoint {self.name} failed to update. Please check the logs for more information."
|
| 226 |
+
)
|
| 227 |
+
if self.status == InferenceEndpointStatus.RUNNING and self.url is not None:
|
| 228 |
+
# Verify the endpoint is actually reachable
|
| 229 |
+
_health_url = f"{self.url.rstrip('/')}/{self.health_route.lstrip('/')}"
|
| 230 |
+
response = get_session().get(_health_url, headers=self._api._build_hf_headers(token=self._token))
|
| 231 |
+
if response.status_code == 200:
|
| 232 |
+
logger.info("Inference Endpoint is ready to be used.")
|
| 233 |
+
return self
|
| 234 |
+
|
| 235 |
+
if timeout is not None:
|
| 236 |
+
if time.time() - start > timeout:
|
| 237 |
+
raise InferenceEndpointTimeoutError("Timeout while waiting for Inference Endpoint to be deployed.")
|
| 238 |
+
logger.info(f"Inference Endpoint is not deployed yet ({self.status}). Waiting {refresh_every}s...")
|
| 239 |
+
time.sleep(refresh_every)
|
| 240 |
+
self.fetch()
|
| 241 |
+
|
| 242 |
+
def fetch(self) -> "InferenceEndpoint":
|
| 243 |
+
"""Fetch latest information about the Inference Endpoint.
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| 247 |
+
"""
|
| 248 |
+
obj = self._api.get_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
|
| 249 |
+
self.raw = obj.raw
|
| 250 |
+
self._populate_from_raw()
|
| 251 |
+
return self
|
| 252 |
+
|
| 253 |
+
def update(
|
| 254 |
+
self,
|
| 255 |
+
*,
|
| 256 |
+
# Compute update
|
| 257 |
+
accelerator: str | None = None,
|
| 258 |
+
instance_size: str | None = None,
|
| 259 |
+
instance_type: str | None = None,
|
| 260 |
+
min_replica: int | None = None,
|
| 261 |
+
max_replica: int | None = None,
|
| 262 |
+
scale_to_zero_timeout: int | None = None,
|
| 263 |
+
# Model update
|
| 264 |
+
repository: str | None = None,
|
| 265 |
+
framework: str | None = None,
|
| 266 |
+
revision: str | None = None,
|
| 267 |
+
task: str | None = None,
|
| 268 |
+
custom_image: dict | None = None,
|
| 269 |
+
secrets: dict[str, str] | None = None,
|
| 270 |
+
) -> "InferenceEndpoint":
|
| 271 |
+
"""Update the Inference Endpoint.
|
| 272 |
+
|
| 273 |
+
This method allows the update of either the compute configuration, the deployed model, or both. All arguments are
|
| 274 |
+
optional but at least one must be provided.
|
| 275 |
+
|
| 276 |
+
This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the
|
| 277 |
+
latest data from the server.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
accelerator (`str`, *optional*):
|
| 281 |
+
The hardware accelerator to be used for inference (e.g. `"cpu"`).
|
| 282 |
+
instance_size (`str`, *optional*):
|
| 283 |
+
The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
|
| 284 |
+
instance_type (`str`, *optional*):
|
| 285 |
+
The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
|
| 286 |
+
min_replica (`int`, *optional*):
|
| 287 |
+
The minimum number of replicas (instances) to keep running for the Inference Endpoint.
|
| 288 |
+
max_replica (`int`, *optional*):
|
| 289 |
+
The maximum number of replicas (instances) to scale to for the Inference Endpoint.
|
| 290 |
+
scale_to_zero_timeout (`int`, *optional*):
|
| 291 |
+
The duration in minutes before an inactive endpoint is scaled to zero.
|
| 292 |
+
|
| 293 |
+
repository (`str`, *optional*):
|
| 294 |
+
The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
|
| 295 |
+
framework (`str`, *optional*):
|
| 296 |
+
The machine learning framework used for the model (e.g. `"custom"`).
|
| 297 |
+
revision (`str`, *optional*):
|
| 298 |
+
The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
|
| 299 |
+
task (`str`, *optional*):
|
| 300 |
+
The task on which to deploy the model (e.g. `"text-classification"`).
|
| 301 |
+
custom_image (`dict`, *optional*):
|
| 302 |
+
A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
|
| 303 |
+
Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
|
| 304 |
+
secrets (`dict[str, str]`, *optional*):
|
| 305 |
+
Secret values to inject in the container environment.
|
| 306 |
+
Returns:
|
| 307 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| 308 |
+
"""
|
| 309 |
+
# Make API call
|
| 310 |
+
obj = self._api.update_inference_endpoint(
|
| 311 |
+
name=self.name,
|
| 312 |
+
namespace=self.namespace,
|
| 313 |
+
accelerator=accelerator,
|
| 314 |
+
instance_size=instance_size,
|
| 315 |
+
instance_type=instance_type,
|
| 316 |
+
min_replica=min_replica,
|
| 317 |
+
max_replica=max_replica,
|
| 318 |
+
scale_to_zero_timeout=scale_to_zero_timeout,
|
| 319 |
+
repository=repository,
|
| 320 |
+
framework=framework,
|
| 321 |
+
revision=revision,
|
| 322 |
+
task=task,
|
| 323 |
+
custom_image=custom_image,
|
| 324 |
+
secrets=secrets,
|
| 325 |
+
token=self._token, # type: ignore [arg-type]
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
# Mutate current object
|
| 329 |
+
self.raw = obj.raw
|
| 330 |
+
self._populate_from_raw()
|
| 331 |
+
return self
|
| 332 |
+
|
| 333 |
+
def pause(self) -> "InferenceEndpoint":
|
| 334 |
+
"""Pause the Inference Endpoint.
|
| 335 |
+
|
| 336 |
+
A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`].
|
| 337 |
+
This is different from scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which
|
| 338 |
+
would be automatically restarted when a request is made to it.
|
| 339 |
+
|
| 340 |
+
This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the
|
| 341 |
+
latest data from the server.
|
| 342 |
+
|
| 343 |
+
Returns:
|
| 344 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| 345 |
+
"""
|
| 346 |
+
obj = self._api.pause_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
|
| 347 |
+
self.raw = obj.raw
|
| 348 |
+
self._populate_from_raw()
|
| 349 |
+
return self
|
| 350 |
+
|
| 351 |
+
def resume(self, running_ok: bool = True) -> "InferenceEndpoint":
|
| 352 |
+
"""Resume the Inference Endpoint.
|
| 353 |
+
|
| 354 |
+
This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the
|
| 355 |
+
latest data from the server.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
running_ok (`bool`, *optional*):
|
| 359 |
+
If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
|
| 360 |
+
`True`.
|
| 361 |
+
|
| 362 |
+
Returns:
|
| 363 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| 364 |
+
"""
|
| 365 |
+
obj = self._api.resume_inference_endpoint(
|
| 366 |
+
name=self.name, namespace=self.namespace, running_ok=running_ok, token=self._token
|
| 367 |
+
) # type: ignore [arg-type]
|
| 368 |
+
self.raw = obj.raw
|
| 369 |
+
self._populate_from_raw()
|
| 370 |
+
return self
|
| 371 |
+
|
| 372 |
+
def scale_to_zero(self) -> "InferenceEndpoint":
|
| 373 |
+
"""Scale Inference Endpoint to zero.
|
| 374 |
+
|
| 375 |
+
An Inference Endpoint scaled to zero will not be charged. It will be resumed on the next request to it, with a
|
| 376 |
+
cold start delay. This is different from pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which
|
| 377 |
+
would require a manual resume with [`InferenceEndpoint.resume`].
|
| 378 |
+
|
| 379 |
+
This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the
|
| 380 |
+
latest data from the server.
|
| 381 |
+
|
| 382 |
+
Returns:
|
| 383 |
+
[`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
|
| 384 |
+
"""
|
| 385 |
+
obj = self._api.scale_to_zero_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
|
| 386 |
+
self.raw = obj.raw
|
| 387 |
+
self._populate_from_raw()
|
| 388 |
+
return self
|
| 389 |
+
|
| 390 |
+
def delete(self) -> None:
|
| 391 |
+
"""Delete the Inference Endpoint.
|
| 392 |
+
|
| 393 |
+
This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
|
| 394 |
+
to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`].
|
| 395 |
+
|
| 396 |
+
This is an alias for [`HfApi.delete_inference_endpoint`].
|
| 397 |
+
"""
|
| 398 |
+
self._api.delete_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
|
| 399 |
+
|
| 400 |
+
def _populate_from_raw(self) -> None:
|
| 401 |
+
"""Populate fields from raw dictionary.
|
| 402 |
+
|
| 403 |
+
Called in __post_init__ + each time the Inference Endpoint is updated.
|
| 404 |
+
"""
|
| 405 |
+
# Repr fields
|
| 406 |
+
self.name = self.raw["name"]
|
| 407 |
+
self.repository = self.raw["model"]["repository"]
|
| 408 |
+
self.status = self.raw["status"]["state"]
|
| 409 |
+
self.url = self.raw["status"].get("url")
|
| 410 |
+
self.health_route = self.raw["healthRoute"]
|
| 411 |
+
|
| 412 |
+
# Other fields
|
| 413 |
+
self.framework = self.raw["model"]["framework"]
|
| 414 |
+
self.revision = self.raw["model"]["revision"]
|
| 415 |
+
self.task = self.raw["model"]["task"]
|
| 416 |
+
self.created_at = parse_datetime(self.raw["status"]["createdAt"])
|
| 417 |
+
self.updated_at = parse_datetime(self.raw["status"]["updatedAt"])
|
| 418 |
+
self.type = self.raw["type"]
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_jobs_api.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
from enum import Enum
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
from huggingface_hub import constants
|
| 20 |
+
from huggingface_hub._space_api import SpaceHardware, Volume
|
| 21 |
+
from huggingface_hub.utils._datetime import parse_datetime
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class JobStage(str, Enum):
|
| 25 |
+
"""
|
| 26 |
+
Enumeration of possible stage of a Job on the Hub.
|
| 27 |
+
|
| 28 |
+
Value can be compared to a string:
|
| 29 |
+
```py
|
| 30 |
+
assert JobStage.COMPLETED == "COMPLETED"
|
| 31 |
+
```
|
| 32 |
+
Possible values are: `COMPLETED`, `CANCELED`, `ERROR`, `DELETED`, `RUNNING`.
|
| 33 |
+
Taken from https://github.com/huggingface/moon-landing/blob/main/server/job_types/JobInfo.ts#L61 (private url).
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
# Copied from moon-landing > server > lib > Job.ts
|
| 37 |
+
COMPLETED = "COMPLETED"
|
| 38 |
+
CANCELED = "CANCELED"
|
| 39 |
+
ERROR = "ERROR"
|
| 40 |
+
DELETED = "DELETED"
|
| 41 |
+
RUNNING = "RUNNING"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@dataclass
|
| 45 |
+
class JobStatus:
|
| 46 |
+
stage: JobStage
|
| 47 |
+
message: str | None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class JobOwner:
|
| 52 |
+
id: str
|
| 53 |
+
name: str
|
| 54 |
+
type: str
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
class JobInfo:
|
| 59 |
+
"""
|
| 60 |
+
Contains information about a Job.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
id (`str`):
|
| 64 |
+
Job ID.
|
| 65 |
+
created_at (`datetime` or `None`):
|
| 66 |
+
When the Job was created.
|
| 67 |
+
docker_image (`str` or `None`):
|
| 68 |
+
The Docker image from Docker Hub used for the Job.
|
| 69 |
+
Can be None if space_id is present instead.
|
| 70 |
+
space_id (`str` or `None`):
|
| 71 |
+
The Docker image from Hugging Face Spaces used for the Job.
|
| 72 |
+
Can be None if docker_image is present instead.
|
| 73 |
+
command (`list[str]` or `None`):
|
| 74 |
+
Command of the Job, e.g. `["python", "-c", "print('hello world')"]`
|
| 75 |
+
arguments (`list[str]` or `None`):
|
| 76 |
+
Arguments passed to the command
|
| 77 |
+
environment (`dict[str]` or `None`):
|
| 78 |
+
Environment variables of the Job as a dictionary.
|
| 79 |
+
secrets (`dict[str]` or `None`):
|
| 80 |
+
Secret environment variables of the Job (encrypted).
|
| 81 |
+
flavor (`str` or `None`):
|
| 82 |
+
Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
|
| 83 |
+
E.g. `"cpu-basic"`.
|
| 84 |
+
labels (`dict[str, str]` or `None`):
|
| 85 |
+
Labels to attach to the job (key-value pairs).
|
| 86 |
+
volumes (`list[Volume]` or `None`):
|
| 87 |
+
Volumes mounted in the job container (buckets, models, datasets, spaces).
|
| 88 |
+
status: (`JobStatus` or `None`):
|
| 89 |
+
Status of the Job, e.g. `JobStatus(stage="RUNNING", message=None)`
|
| 90 |
+
See [`JobStage`] for possible stage values.
|
| 91 |
+
owner: (`JobOwner` or `None`):
|
| 92 |
+
Owner of the Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")`
|
| 93 |
+
|
| 94 |
+
Example:
|
| 95 |
+
|
| 96 |
+
```python
|
| 97 |
+
>>> from huggingface_hub import run_job
|
| 98 |
+
>>> job = run_job(
|
| 99 |
+
... image="python:3.12",
|
| 100 |
+
... command=["python", "-c", "print('Hello from the cloud!')"]
|
| 101 |
+
... )
|
| 102 |
+
>>> job
|
| 103 |
+
JobInfo(id='687fb701029421ae5549d998', created_at=datetime.datetime(2025, 7, 22, 16, 6, 25, 79000, tzinfo=datetime.timezone.utc), docker_image='python:3.12', space_id=None, command=['python', '-c', "print('Hello from the cloud!')"], arguments=[], environment={}, secrets={}, flavor='cpu-basic', labels=None, status=JobStatus(stage='RUNNING', message=None), owner=JobOwner(id='5e9ecfc04957053f60648a3e', name='lhoestq', type='user'), endpoint='https://huggingface.co', url='https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998')
|
| 104 |
+
>>> job.id
|
| 105 |
+
'687fb701029421ae5549d998'
|
| 106 |
+
>>> job.url
|
| 107 |
+
'https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998'
|
| 108 |
+
>>> job.status.stage
|
| 109 |
+
'RUNNING'
|
| 110 |
+
```
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
id: str
|
| 114 |
+
created_at: datetime | None
|
| 115 |
+
docker_image: str | None
|
| 116 |
+
space_id: str | None
|
| 117 |
+
command: list[str] | None
|
| 118 |
+
arguments: list[str] | None
|
| 119 |
+
environment: dict[str, Any] | None
|
| 120 |
+
secrets: dict[str, Any] | None
|
| 121 |
+
flavor: SpaceHardware | None
|
| 122 |
+
labels: dict[str, str] | None
|
| 123 |
+
volumes: list[Volume] | None
|
| 124 |
+
status: JobStatus
|
| 125 |
+
owner: JobOwner
|
| 126 |
+
|
| 127 |
+
# Inferred fields
|
| 128 |
+
endpoint: str
|
| 129 |
+
url: str
|
| 130 |
+
|
| 131 |
+
def __init__(self, **kwargs) -> None:
|
| 132 |
+
self.id = kwargs["id"]
|
| 133 |
+
created_at = kwargs.get("createdAt") or kwargs.get("created_at")
|
| 134 |
+
self.created_at = parse_datetime(created_at) if created_at else None
|
| 135 |
+
self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image")
|
| 136 |
+
self.space_id = kwargs.get("spaceId") or kwargs.get("space_id")
|
| 137 |
+
owner = kwargs.get("owner", {})
|
| 138 |
+
self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"])
|
| 139 |
+
self.command = kwargs.get("command")
|
| 140 |
+
self.arguments = kwargs.get("arguments")
|
| 141 |
+
self.environment = kwargs.get("environment")
|
| 142 |
+
self.secrets = kwargs.get("secrets")
|
| 143 |
+
self.flavor = kwargs.get("flavor")
|
| 144 |
+
self.labels = kwargs.get("labels")
|
| 145 |
+
volumes = kwargs.get("volumes")
|
| 146 |
+
self.volumes = [Volume(**v) for v in volumes] if volumes else None
|
| 147 |
+
status = kwargs.get("status", {})
|
| 148 |
+
self.status = JobStatus(stage=status["stage"], message=status.get("message"))
|
| 149 |
+
|
| 150 |
+
# Inferred fields
|
| 151 |
+
self.endpoint = kwargs.get("endpoint", constants.ENDPOINT)
|
| 152 |
+
self.url = f"{self.endpoint}/jobs/{self.owner.name}/{self.id}"
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@dataclass
|
| 156 |
+
class JobSpec:
|
| 157 |
+
docker_image: str | None
|
| 158 |
+
space_id: str | None
|
| 159 |
+
command: list[str] | None
|
| 160 |
+
arguments: list[str] | None
|
| 161 |
+
environment: dict[str, Any] | None
|
| 162 |
+
secrets: dict[str, Any] | None
|
| 163 |
+
flavor: SpaceHardware | None
|
| 164 |
+
timeout: int | None
|
| 165 |
+
tags: list[str] | None
|
| 166 |
+
arch: str | None
|
| 167 |
+
labels: dict[str, str] | None
|
| 168 |
+
volumes: list[Volume] | None
|
| 169 |
+
|
| 170 |
+
def __init__(self, **kwargs) -> None:
|
| 171 |
+
self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image")
|
| 172 |
+
self.space_id = kwargs.get("spaceId") or kwargs.get("space_id")
|
| 173 |
+
self.command = kwargs.get("command")
|
| 174 |
+
self.arguments = kwargs.get("arguments")
|
| 175 |
+
self.environment = kwargs.get("environment")
|
| 176 |
+
self.secrets = kwargs.get("secrets")
|
| 177 |
+
self.flavor = kwargs.get("flavor")
|
| 178 |
+
self.timeout = kwargs.get("timeout")
|
| 179 |
+
self.tags = kwargs.get("tags")
|
| 180 |
+
self.arch = kwargs.get("arch")
|
| 181 |
+
self.labels = kwargs.get("labels")
|
| 182 |
+
volumes = kwargs.get("volumes")
|
| 183 |
+
self.volumes = [Volume(**v) for v in volumes] if volumes else None
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
@dataclass
|
| 187 |
+
class LastJobInfo:
|
| 188 |
+
id: str
|
| 189 |
+
at: datetime
|
| 190 |
+
|
| 191 |
+
def __init__(self, **kwargs) -> None:
|
| 192 |
+
self.id = kwargs["id"]
|
| 193 |
+
self.at = parse_datetime(kwargs["at"])
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@dataclass
|
| 197 |
+
class ScheduledJobStatus:
|
| 198 |
+
last_job: LastJobInfo | None
|
| 199 |
+
next_job_run_at: datetime | None
|
| 200 |
+
|
| 201 |
+
def __init__(self, **kwargs) -> None:
|
| 202 |
+
last_job = kwargs.get("lastJob") or kwargs.get("last_job")
|
| 203 |
+
self.last_job = LastJobInfo(**last_job) if last_job else None
|
| 204 |
+
next_job_run_at = kwargs.get("nextJobRunAt") or kwargs.get("next_job_run_at")
|
| 205 |
+
self.next_job_run_at = parse_datetime(str(next_job_run_at)) if next_job_run_at else None
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@dataclass
|
| 209 |
+
class ScheduledJobInfo:
|
| 210 |
+
"""
|
| 211 |
+
Contains information about a Job.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
id (`str`):
|
| 215 |
+
Scheduled Job ID.
|
| 216 |
+
created_at (`datetime` or `None`):
|
| 217 |
+
When the scheduled Job was created.
|
| 218 |
+
tags (`list[str]` or `None`):
|
| 219 |
+
The tags of the scheduled Job.
|
| 220 |
+
schedule (`str` or `None`):
|
| 221 |
+
One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
|
| 222 |
+
CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
|
| 223 |
+
suspend (`bool` or `None`):
|
| 224 |
+
Whether the scheduled job is suspended (paused).
|
| 225 |
+
concurrency (`bool` or `None`):
|
| 226 |
+
Whether multiple instances of this Job can run concurrently.
|
| 227 |
+
status (`ScheduledJobStatus` or `None`):
|
| 228 |
+
Status of the scheduled Job.
|
| 229 |
+
owner: (`JobOwner` or `None`):
|
| 230 |
+
Owner of the scheduled Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")`
|
| 231 |
+
job_spec: (`JobSpec` or `None`):
|
| 232 |
+
Specifications of the Job.
|
| 233 |
+
|
| 234 |
+
Example:
|
| 235 |
+
|
| 236 |
+
```python
|
| 237 |
+
>>> from huggingface_hub import run_job
|
| 238 |
+
>>> scheduled_job = create_scheduled_job(
|
| 239 |
+
... image="python:3.12",
|
| 240 |
+
... command=["python", "-c", "print('Hello from the cloud!')"],
|
| 241 |
+
... schedule="@hourly",
|
| 242 |
+
... )
|
| 243 |
+
>>> scheduled_job.id
|
| 244 |
+
'687fb701029421ae5549d999'
|
| 245 |
+
>>> scheduled_job.status.next_job_run_at
|
| 246 |
+
datetime.datetime(2025, 7, 22, 17, 6, 25, 79000, tzinfo=datetime.timezone.utc)
|
| 247 |
+
```
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
id: str
|
| 251 |
+
created_at: datetime | None
|
| 252 |
+
job_spec: JobSpec
|
| 253 |
+
schedule: str | None
|
| 254 |
+
suspend: bool | None
|
| 255 |
+
concurrency: bool | None
|
| 256 |
+
status: ScheduledJobStatus
|
| 257 |
+
owner: JobOwner
|
| 258 |
+
|
| 259 |
+
def __init__(self, **kwargs) -> None:
|
| 260 |
+
self.id = kwargs["id"]
|
| 261 |
+
created_at = kwargs.get("createdAt") or kwargs.get("created_at")
|
| 262 |
+
self.created_at = parse_datetime(created_at) if created_at else None
|
| 263 |
+
self.job_spec = JobSpec(**(kwargs.get("job_spec") or kwargs.get("jobSpec", {})))
|
| 264 |
+
self.schedule = kwargs.get("schedule")
|
| 265 |
+
self.suspend = kwargs.get("suspend")
|
| 266 |
+
self.concurrency = kwargs.get("concurrency")
|
| 267 |
+
status = kwargs.get("status", {})
|
| 268 |
+
self.status = ScheduledJobStatus(
|
| 269 |
+
last_job=status.get("last_job") or status.get("lastJob"),
|
| 270 |
+
next_job_run_at=status.get("next_job_run_at") or status.get("nextJobRunAt"),
|
| 271 |
+
)
|
| 272 |
+
owner = kwargs.get("owner", {})
|
| 273 |
+
self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"])
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
@dataclass
|
| 277 |
+
class JobAccelerator:
|
| 278 |
+
"""
|
| 279 |
+
Contains information about a Job accelerator (GPU).
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
type (`str`):
|
| 283 |
+
Type of accelerator, e.g. `"gpu"`.
|
| 284 |
+
model (`str`):
|
| 285 |
+
Model of accelerator, e.g. `"T4"`, `"A10G"`, `"A100"`, `"L4"`, `"L40S"`.
|
| 286 |
+
quantity (`str`):
|
| 287 |
+
Number of accelerators, e.g. `"1"`, `"2"`, `"4"`, `"8"`.
|
| 288 |
+
vram (`str`):
|
| 289 |
+
Total VRAM, e.g. `"16 GB"`, `"24 GB"`.
|
| 290 |
+
manufacturer (`str`):
|
| 291 |
+
Manufacturer of the accelerator, e.g. `"Nvidia"`.
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
type: str
|
| 295 |
+
model: str
|
| 296 |
+
quantity: str
|
| 297 |
+
vram: str
|
| 298 |
+
manufacturer: str
|
| 299 |
+
|
| 300 |
+
def __init__(self, **kwargs) -> None:
|
| 301 |
+
self.type = kwargs["type"]
|
| 302 |
+
self.model = kwargs["model"]
|
| 303 |
+
self.quantity = kwargs["quantity"]
|
| 304 |
+
self.vram = kwargs["vram"]
|
| 305 |
+
self.manufacturer = kwargs["manufacturer"]
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
@dataclass
|
| 309 |
+
class JobHardware:
|
| 310 |
+
"""
|
| 311 |
+
Contains information about available Job hardware.
|
| 312 |
+
|
| 313 |
+
Args:
|
| 314 |
+
name (`str`):
|
| 315 |
+
Machine identifier, e.g. `"cpu-basic"`, `"a10g-large"`.
|
| 316 |
+
pretty_name (`str`):
|
| 317 |
+
Human-readable name, e.g. `"CPU Basic"`, `"Nvidia A10G - large"`.
|
| 318 |
+
cpu (`str`):
|
| 319 |
+
CPU specification, e.g. `"2 vCPU"`, `"12 vCPU"`.
|
| 320 |
+
ram (`str`):
|
| 321 |
+
RAM specification, e.g. `"16 GB"`, `"46 GB"`.
|
| 322 |
+
accelerator (`JobAccelerator` or `None`):
|
| 323 |
+
GPU/accelerator details if available.
|
| 324 |
+
unit_cost_micro_usd (`int`):
|
| 325 |
+
Cost in micro-dollars per unit, e.g. `167` (= $0.000167).
|
| 326 |
+
unit_cost_usd (`float`):
|
| 327 |
+
Cost in USD per unit, e.g. `0.000167`.
|
| 328 |
+
unit_label (`str`):
|
| 329 |
+
Cost unit period, e.g. `"minute"`.
|
| 330 |
+
|
| 331 |
+
Example:
|
| 332 |
+
|
| 333 |
+
```python
|
| 334 |
+
>>> from huggingface_hub import list_jobs_hardware
|
| 335 |
+
>>> hardware_list = list_jobs_hardware()
|
| 336 |
+
>>> hardware_list[0]
|
| 337 |
+
JobHardware(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute')
|
| 338 |
+
>>> hardware_list[0].name
|
| 339 |
+
'cpu-basic'
|
| 340 |
+
```
|
| 341 |
+
"""
|
| 342 |
+
|
| 343 |
+
name: str
|
| 344 |
+
pretty_name: str
|
| 345 |
+
cpu: str
|
| 346 |
+
ram: str
|
| 347 |
+
accelerator: JobAccelerator | None
|
| 348 |
+
unit_cost_micro_usd: int
|
| 349 |
+
unit_cost_usd: float
|
| 350 |
+
unit_label: str
|
| 351 |
+
|
| 352 |
+
def __init__(self, **kwargs) -> None:
|
| 353 |
+
self.name = kwargs["name"]
|
| 354 |
+
self.pretty_name = kwargs["prettyName"]
|
| 355 |
+
self.cpu = kwargs["cpu"]
|
| 356 |
+
self.ram = kwargs["ram"]
|
| 357 |
+
accelerator = kwargs.get("accelerator")
|
| 358 |
+
self.accelerator = JobAccelerator(**accelerator) if accelerator else None
|
| 359 |
+
self.unit_cost_micro_usd = kwargs["unitCostMicroUSD"]
|
| 360 |
+
self.unit_cost_usd = kwargs["unitCostUSD"]
|
| 361 |
+
self.unit_label = kwargs["unitLabel"]
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _create_job_spec(
|
| 365 |
+
*,
|
| 366 |
+
image: str,
|
| 367 |
+
command: list[str],
|
| 368 |
+
env: dict[str, Any] | None,
|
| 369 |
+
secrets: dict[str, Any] | None,
|
| 370 |
+
flavor: SpaceHardware | None,
|
| 371 |
+
timeout: int | float | str | None,
|
| 372 |
+
labels: dict[str, str] | None = None,
|
| 373 |
+
volumes: list[Volume] | None = None,
|
| 374 |
+
) -> dict[str, Any]:
|
| 375 |
+
# prepare job spec to send to HF Jobs API
|
| 376 |
+
job_spec: dict[str, Any] = {
|
| 377 |
+
"command": command,
|
| 378 |
+
"arguments": [],
|
| 379 |
+
"environment": env or {},
|
| 380 |
+
"flavor": flavor or SpaceHardware.CPU_BASIC,
|
| 381 |
+
}
|
| 382 |
+
# secrets are optional
|
| 383 |
+
if secrets:
|
| 384 |
+
job_spec["secrets"] = secrets
|
| 385 |
+
# timeout is optional
|
| 386 |
+
if timeout:
|
| 387 |
+
time_units_factors = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24}
|
| 388 |
+
if isinstance(timeout, str) and timeout[-1] in time_units_factors:
|
| 389 |
+
job_spec["timeoutSeconds"] = int(float(timeout[:-1]) * time_units_factors[timeout[-1]])
|
| 390 |
+
else:
|
| 391 |
+
job_spec["timeoutSeconds"] = int(timeout)
|
| 392 |
+
# labels are optional
|
| 393 |
+
if labels:
|
| 394 |
+
job_spec["labels"] = labels
|
| 395 |
+
# volumes are optional
|
| 396 |
+
if volumes:
|
| 397 |
+
job_spec["volumes"] = [vol.to_dict() for vol in volumes]
|
| 398 |
+
# input is either from docker hub or from HF spaces
|
| 399 |
+
for prefix in (
|
| 400 |
+
"https://huggingface.co/spaces/",
|
| 401 |
+
"https://hf.co/spaces/",
|
| 402 |
+
"huggingface.co/spaces/",
|
| 403 |
+
"hf.co/spaces/",
|
| 404 |
+
):
|
| 405 |
+
if image.startswith(prefix):
|
| 406 |
+
job_spec["spaceId"] = image[len(prefix) :]
|
| 407 |
+
break
|
| 408 |
+
else:
|
| 409 |
+
job_spec["dockerImage"] = image
|
| 410 |
+
return job_spec
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_local_folder.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains utilities to handle the `../.cache/huggingface` folder in local directories.
|
| 15 |
+
|
| 16 |
+
First discussed in https://github.com/huggingface/huggingface_hub/issues/1738 to store
|
| 17 |
+
download metadata when downloading files from the hub to a local directory (without
|
| 18 |
+
using the cache).
|
| 19 |
+
|
| 20 |
+
./.cache/huggingface folder structure:
|
| 21 |
+
[4.0K] data
|
| 22 |
+
├── [4.0K] .cache
|
| 23 |
+
│ └── [4.0K] huggingface
|
| 24 |
+
│ └── [4.0K] download
|
| 25 |
+
│ ├── [ 16] file.parquet.metadata
|
| 26 |
+
│ ├── [ 16] file.txt.metadata
|
| 27 |
+
│ └── [4.0K] folder
|
| 28 |
+
│ └── [ 16] file.parquet.metadata
|
| 29 |
+
│
|
| 30 |
+
├── [6.5G] file.parquet
|
| 31 |
+
├── [1.5K] file.txt
|
| 32 |
+
└── [4.0K] folder
|
| 33 |
+
└── [ 16] file.parquet
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
Download metadata file structure:
|
| 37 |
+
```
|
| 38 |
+
# file.txt.metadata
|
| 39 |
+
11c5a3d5811f50298f278a704980280950aedb10
|
| 40 |
+
a16a55fda99d2f2e7b69cce5cf93ff4ad3049930
|
| 41 |
+
1712656091.123
|
| 42 |
+
|
| 43 |
+
# file.parquet.metadata
|
| 44 |
+
11c5a3d5811f50298f278a704980280950aedb10
|
| 45 |
+
7c5d3f4b8b76583b422fcb9189ad6c89d5d97a094541ce8932dce3ecabde1421
|
| 46 |
+
1712656091.123
|
| 47 |
+
}
|
| 48 |
+
```
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
import base64
|
| 52 |
+
import hashlib
|
| 53 |
+
import logging
|
| 54 |
+
import os
|
| 55 |
+
import time
|
| 56 |
+
from dataclasses import dataclass
|
| 57 |
+
from pathlib import Path
|
| 58 |
+
|
| 59 |
+
from .utils import WeakFileLock
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
logger = logging.getLogger(__name__)
|
| 63 |
+
|
| 64 |
+
CACHEDIR_TAG_CONTENT = (
|
| 65 |
+
"Signature: 8a477f597d28d172789f06886806bc55\n"
|
| 66 |
+
"# This file is a cache directory tag created by huggingface_hub.\n"
|
| 67 |
+
"# For information about cache directory tags, see:\n"
|
| 68 |
+
"#\thttps://bford.info/cachedir/\n"
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass
|
| 73 |
+
class LocalDownloadFilePaths:
|
| 74 |
+
"""
|
| 75 |
+
Paths to the files related to a download process in a local dir.
|
| 76 |
+
|
| 77 |
+
Returned by [`get_local_download_paths`].
|
| 78 |
+
|
| 79 |
+
Attributes:
|
| 80 |
+
file_path (`Path`):
|
| 81 |
+
Path where the file will be saved.
|
| 82 |
+
lock_path (`Path`):
|
| 83 |
+
Path to the lock file used to ensure atomicity when reading/writing metadata.
|
| 84 |
+
metadata_path (`Path`):
|
| 85 |
+
Path to the metadata file.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
file_path: Path
|
| 89 |
+
lock_path: Path
|
| 90 |
+
metadata_path: Path
|
| 91 |
+
|
| 92 |
+
def incomplete_path(self, etag: str) -> Path:
|
| 93 |
+
"""Return the path where a file will be temporarily downloaded before being moved to `file_path`."""
|
| 94 |
+
path = self.metadata_path.parent / f"{_short_hash(self.metadata_path.name)}.{etag}.incomplete"
|
| 95 |
+
resolved_path = str(path.resolve())
|
| 96 |
+
# Some Windows versions do not allow for paths longer than 255 characters.
|
| 97 |
+
# In this case, we must specify it as an extended path by using the "\\?\" prefix.
|
| 98 |
+
if os.name == "nt" and len(resolved_path) > 255 and not resolved_path.startswith("\\\\?\\"):
|
| 99 |
+
path = Path("\\\\?\\" + resolved_path)
|
| 100 |
+
return path
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass(frozen=True)
|
| 104 |
+
class LocalUploadFilePaths:
|
| 105 |
+
"""
|
| 106 |
+
Paths to the files related to an upload process in a local dir.
|
| 107 |
+
|
| 108 |
+
Returned by [`get_local_upload_paths`].
|
| 109 |
+
|
| 110 |
+
Attributes:
|
| 111 |
+
path_in_repo (`str`):
|
| 112 |
+
Path of the file in the repo.
|
| 113 |
+
file_path (`Path`):
|
| 114 |
+
Path where the file will be saved.
|
| 115 |
+
lock_path (`Path`):
|
| 116 |
+
Path to the lock file used to ensure atomicity when reading/writing metadata.
|
| 117 |
+
metadata_path (`Path`):
|
| 118 |
+
Path to the metadata file.
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
path_in_repo: str
|
| 122 |
+
file_path: Path
|
| 123 |
+
lock_path: Path
|
| 124 |
+
metadata_path: Path
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@dataclass
|
| 128 |
+
class LocalDownloadFileMetadata:
|
| 129 |
+
"""
|
| 130 |
+
Metadata about a file in the local directory related to a download process.
|
| 131 |
+
|
| 132 |
+
Attributes:
|
| 133 |
+
filename (`str`):
|
| 134 |
+
Path of the file in the repo.
|
| 135 |
+
commit_hash (`str`):
|
| 136 |
+
Commit hash of the file in the repo.
|
| 137 |
+
etag (`str`):
|
| 138 |
+
ETag of the file in the repo. Used to check if the file has changed.
|
| 139 |
+
For LFS files, this is the sha256 of the file. For regular files, it corresponds to the git hash.
|
| 140 |
+
timestamp (`int`):
|
| 141 |
+
Unix timestamp of when the metadata was saved i.e. when the metadata was accurate.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
filename: str
|
| 145 |
+
commit_hash: str
|
| 146 |
+
etag: str
|
| 147 |
+
timestamp: float
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@dataclass
|
| 151 |
+
class LocalUploadFileMetadata:
|
| 152 |
+
"""
|
| 153 |
+
Metadata about a file in the local directory related to an upload process.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
size: int
|
| 157 |
+
|
| 158 |
+
# Default values correspond to "we don't know yet"
|
| 159 |
+
timestamp: float | None = None
|
| 160 |
+
should_ignore: bool | None = None
|
| 161 |
+
sha256: str | None = None
|
| 162 |
+
upload_mode: str | None = None
|
| 163 |
+
remote_oid: str | None = None
|
| 164 |
+
is_uploaded: bool = False
|
| 165 |
+
is_committed: bool = False
|
| 166 |
+
|
| 167 |
+
def save(self, paths: LocalUploadFilePaths) -> None:
|
| 168 |
+
"""Save the metadata to disk."""
|
| 169 |
+
with WeakFileLock(paths.lock_path):
|
| 170 |
+
with paths.metadata_path.open("w") as f:
|
| 171 |
+
new_timestamp = time.time()
|
| 172 |
+
f.write(str(new_timestamp) + "\n")
|
| 173 |
+
|
| 174 |
+
f.write(str(self.size)) # never None
|
| 175 |
+
f.write("\n")
|
| 176 |
+
|
| 177 |
+
if self.should_ignore is not None:
|
| 178 |
+
f.write(str(int(self.should_ignore)))
|
| 179 |
+
f.write("\n")
|
| 180 |
+
|
| 181 |
+
if self.sha256 is not None:
|
| 182 |
+
f.write(self.sha256)
|
| 183 |
+
f.write("\n")
|
| 184 |
+
|
| 185 |
+
if self.upload_mode is not None:
|
| 186 |
+
f.write(self.upload_mode)
|
| 187 |
+
f.write("\n")
|
| 188 |
+
|
| 189 |
+
if self.remote_oid is not None:
|
| 190 |
+
f.write(self.remote_oid)
|
| 191 |
+
f.write("\n")
|
| 192 |
+
|
| 193 |
+
f.write(str(int(self.is_uploaded)) + "\n")
|
| 194 |
+
f.write(str(int(self.is_committed)) + "\n")
|
| 195 |
+
|
| 196 |
+
self.timestamp = new_timestamp
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_local_download_paths(local_dir: Path, filename: str) -> LocalDownloadFilePaths:
|
| 200 |
+
"""Compute paths to the files related to a download process.
|
| 201 |
+
|
| 202 |
+
Folders containing the paths are all guaranteed to exist.
|
| 203 |
+
|
| 204 |
+
Args:
|
| 205 |
+
local_dir (`Path`):
|
| 206 |
+
Path to the local directory in which files are downloaded.
|
| 207 |
+
filename (`str`):
|
| 208 |
+
Path of the file in the repo.
|
| 209 |
+
|
| 210 |
+
Return:
|
| 211 |
+
[`LocalDownloadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path, incomplete_path).
|
| 212 |
+
"""
|
| 213 |
+
# filename is the path in the Hub repository (separated by '/')
|
| 214 |
+
# make sure to have a cross-platform transcription
|
| 215 |
+
sanitized_filename = os.path.join(*filename.split("/"))
|
| 216 |
+
if os.name == "nt":
|
| 217 |
+
if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename:
|
| 218 |
+
raise ValueError(
|
| 219 |
+
f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository"
|
| 220 |
+
" owner to rename this file."
|
| 221 |
+
)
|
| 222 |
+
file_path = local_dir / sanitized_filename
|
| 223 |
+
metadata_path = _huggingface_dir(local_dir) / "download" / f"{sanitized_filename}.metadata"
|
| 224 |
+
lock_path = metadata_path.with_suffix(".lock")
|
| 225 |
+
|
| 226 |
+
# Some Windows versions do not allow for paths longer than 255 characters.
|
| 227 |
+
# In this case, we must specify it as an extended path by using the "\\?\" prefix
|
| 228 |
+
if os.name == "nt":
|
| 229 |
+
if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255:
|
| 230 |
+
file_path = Path("\\\\?\\" + os.path.abspath(file_path))
|
| 231 |
+
lock_path = Path("\\\\?\\" + os.path.abspath(lock_path))
|
| 232 |
+
metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
|
| 233 |
+
|
| 234 |
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
| 235 |
+
metadata_path.parent.mkdir(parents=True, exist_ok=True)
|
| 236 |
+
return LocalDownloadFilePaths(file_path=file_path, lock_path=lock_path, metadata_path=metadata_path)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def get_local_upload_paths(local_dir: Path, filename: str) -> LocalUploadFilePaths:
|
| 240 |
+
"""Compute paths to the files related to an upload process.
|
| 241 |
+
|
| 242 |
+
Folders containing the paths are all guaranteed to exist.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
local_dir (`Path`):
|
| 246 |
+
Path to the local directory that is uploaded.
|
| 247 |
+
filename (`str`):
|
| 248 |
+
Path of the file in the repo.
|
| 249 |
+
|
| 250 |
+
Return:
|
| 251 |
+
[`LocalUploadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path).
|
| 252 |
+
"""
|
| 253 |
+
# filename is the path in the Hub repository (separated by '/')
|
| 254 |
+
# make sure to have a cross-platform transcription
|
| 255 |
+
sanitized_filename = os.path.join(*filename.split("/"))
|
| 256 |
+
if os.name == "nt":
|
| 257 |
+
if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename:
|
| 258 |
+
raise ValueError(
|
| 259 |
+
f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository"
|
| 260 |
+
" owner to rename this file."
|
| 261 |
+
)
|
| 262 |
+
file_path = local_dir / sanitized_filename
|
| 263 |
+
metadata_path = _huggingface_dir(local_dir) / "upload" / f"{sanitized_filename}.metadata"
|
| 264 |
+
lock_path = metadata_path.with_suffix(".lock")
|
| 265 |
+
|
| 266 |
+
# Some Windows versions do not allow for paths longer than 255 characters.
|
| 267 |
+
# In this case, we must specify it as an extended path by using the "\\?\" prefix
|
| 268 |
+
if os.name == "nt":
|
| 269 |
+
if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255:
|
| 270 |
+
file_path = Path("\\\\?\\" + os.path.abspath(file_path))
|
| 271 |
+
lock_path = Path("\\\\?\\" + os.path.abspath(lock_path))
|
| 272 |
+
metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
|
| 273 |
+
|
| 274 |
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
| 275 |
+
metadata_path.parent.mkdir(parents=True, exist_ok=True)
|
| 276 |
+
return LocalUploadFilePaths(
|
| 277 |
+
path_in_repo=filename, file_path=file_path, lock_path=lock_path, metadata_path=metadata_path
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def read_download_metadata(local_dir: Path, filename: str) -> LocalDownloadFileMetadata | None:
|
| 282 |
+
"""Read metadata about a file in the local directory related to a download process.
|
| 283 |
+
|
| 284 |
+
Args:
|
| 285 |
+
local_dir (`Path`):
|
| 286 |
+
Path to the local directory in which files are downloaded.
|
| 287 |
+
filename (`str`):
|
| 288 |
+
Path of the file in the repo.
|
| 289 |
+
|
| 290 |
+
Return:
|
| 291 |
+
`[LocalDownloadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise.
|
| 292 |
+
"""
|
| 293 |
+
paths = get_local_download_paths(local_dir, filename)
|
| 294 |
+
with WeakFileLock(paths.lock_path):
|
| 295 |
+
if paths.metadata_path.exists():
|
| 296 |
+
try:
|
| 297 |
+
with paths.metadata_path.open() as f:
|
| 298 |
+
commit_hash = f.readline().strip()
|
| 299 |
+
etag = f.readline().strip()
|
| 300 |
+
timestamp = float(f.readline().strip())
|
| 301 |
+
metadata = LocalDownloadFileMetadata(
|
| 302 |
+
filename=filename,
|
| 303 |
+
commit_hash=commit_hash,
|
| 304 |
+
etag=etag,
|
| 305 |
+
timestamp=timestamp,
|
| 306 |
+
)
|
| 307 |
+
except Exception as e:
|
| 308 |
+
# remove the metadata file if it is corrupted / not the right format
|
| 309 |
+
logger.warning(
|
| 310 |
+
f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue."
|
| 311 |
+
)
|
| 312 |
+
try:
|
| 313 |
+
paths.metadata_path.unlink()
|
| 314 |
+
except Exception as e:
|
| 315 |
+
logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
|
| 316 |
+
return None
|
| 317 |
+
|
| 318 |
+
try:
|
| 319 |
+
# check if the file exists and hasn't been modified since the metadata was saved
|
| 320 |
+
stat = paths.file_path.stat()
|
| 321 |
+
if (
|
| 322 |
+
stat.st_mtime - 1 <= metadata.timestamp
|
| 323 |
+
): # allow 1s difference as stat.st_mtime might not be precise
|
| 324 |
+
return metadata
|
| 325 |
+
logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.")
|
| 326 |
+
except FileNotFoundError:
|
| 327 |
+
# file does not exist => metadata is outdated
|
| 328 |
+
return None
|
| 329 |
+
return None
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def read_upload_metadata(local_dir: Path, filename: str) -> LocalUploadFileMetadata:
|
| 333 |
+
"""Read metadata about a file in the local directory related to an upload process.
|
| 334 |
+
|
| 335 |
+
TODO: factorize logic with `read_download_metadata`.
|
| 336 |
+
|
| 337 |
+
Args:
|
| 338 |
+
local_dir (`Path`):
|
| 339 |
+
Path to the local directory in which files are downloaded.
|
| 340 |
+
filename (`str`):
|
| 341 |
+
Path of the file in the repo.
|
| 342 |
+
|
| 343 |
+
Return:
|
| 344 |
+
`[LocalUploadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise.
|
| 345 |
+
"""
|
| 346 |
+
paths = get_local_upload_paths(local_dir, filename)
|
| 347 |
+
with WeakFileLock(paths.lock_path):
|
| 348 |
+
if paths.metadata_path.exists():
|
| 349 |
+
try:
|
| 350 |
+
with paths.metadata_path.open() as f:
|
| 351 |
+
timestamp = float(f.readline().strip())
|
| 352 |
+
|
| 353 |
+
size = int(f.readline().strip()) # never None
|
| 354 |
+
|
| 355 |
+
_should_ignore = f.readline().strip()
|
| 356 |
+
should_ignore = None if _should_ignore == "" else bool(int(_should_ignore))
|
| 357 |
+
|
| 358 |
+
_sha256 = f.readline().strip()
|
| 359 |
+
sha256 = None if _sha256 == "" else _sha256
|
| 360 |
+
|
| 361 |
+
_upload_mode = f.readline().strip()
|
| 362 |
+
upload_mode = None if _upload_mode == "" else _upload_mode
|
| 363 |
+
if upload_mode not in (None, "regular", "lfs"):
|
| 364 |
+
raise ValueError(f"Invalid upload mode in metadata {paths.path_in_repo}: {upload_mode}")
|
| 365 |
+
|
| 366 |
+
_remote_oid = f.readline().strip()
|
| 367 |
+
remote_oid = None if _remote_oid == "" else _remote_oid
|
| 368 |
+
|
| 369 |
+
is_uploaded = bool(int(f.readline().strip()))
|
| 370 |
+
is_committed = bool(int(f.readline().strip()))
|
| 371 |
+
|
| 372 |
+
metadata = LocalUploadFileMetadata(
|
| 373 |
+
timestamp=timestamp,
|
| 374 |
+
size=size,
|
| 375 |
+
should_ignore=should_ignore,
|
| 376 |
+
sha256=sha256,
|
| 377 |
+
upload_mode=upload_mode,
|
| 378 |
+
remote_oid=remote_oid,
|
| 379 |
+
is_uploaded=is_uploaded,
|
| 380 |
+
is_committed=is_committed,
|
| 381 |
+
)
|
| 382 |
+
except Exception as e:
|
| 383 |
+
# remove the metadata file if it is corrupted / not the right format
|
| 384 |
+
logger.warning(
|
| 385 |
+
f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue."
|
| 386 |
+
)
|
| 387 |
+
try:
|
| 388 |
+
paths.metadata_path.unlink()
|
| 389 |
+
except Exception as e:
|
| 390 |
+
logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
|
| 391 |
+
|
| 392 |
+
# corrupted metadata => we don't know anything expect its size
|
| 393 |
+
return LocalUploadFileMetadata(size=paths.file_path.stat().st_size)
|
| 394 |
+
|
| 395 |
+
# TODO: can we do better?
|
| 396 |
+
if (
|
| 397 |
+
metadata.timestamp is not None
|
| 398 |
+
and metadata.is_uploaded # file was uploaded
|
| 399 |
+
and not metadata.is_committed # but not committed
|
| 400 |
+
and time.time() - metadata.timestamp > 20 * 3600 # and it's been more than 20 hours
|
| 401 |
+
): # => we consider it as garbage-collected by S3
|
| 402 |
+
metadata.is_uploaded = False
|
| 403 |
+
|
| 404 |
+
# check if the file exists and hasn't been modified since the metadata was saved
|
| 405 |
+
try:
|
| 406 |
+
if metadata.timestamp is not None and paths.file_path.stat().st_mtime <= metadata.timestamp:
|
| 407 |
+
return metadata
|
| 408 |
+
logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.")
|
| 409 |
+
except FileNotFoundError:
|
| 410 |
+
# file does not exist => metadata is outdated
|
| 411 |
+
pass
|
| 412 |
+
|
| 413 |
+
# empty metadata => we don't know anything expect its size
|
| 414 |
+
return LocalUploadFileMetadata(size=paths.file_path.stat().st_size)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def write_download_metadata(local_dir: Path, filename: str, commit_hash: str, etag: str) -> None:
|
| 418 |
+
"""Write metadata about a file in the local directory related to a download process.
|
| 419 |
+
|
| 420 |
+
Args:
|
| 421 |
+
local_dir (`Path`):
|
| 422 |
+
Path to the local directory in which files are downloaded.
|
| 423 |
+
"""
|
| 424 |
+
paths = get_local_download_paths(local_dir, filename)
|
| 425 |
+
with WeakFileLock(paths.lock_path):
|
| 426 |
+
with paths.metadata_path.open("w") as f:
|
| 427 |
+
f.write(f"{commit_hash}\n{etag}\n{time.time()}\n")
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def _huggingface_dir(local_dir: Path) -> Path:
|
| 431 |
+
"""Return the path to the `.cache/huggingface` directory in a local directory."""
|
| 432 |
+
# Wrap in lru_cache to avoid overwriting the .gitignore file if called multiple times
|
| 433 |
+
path = local_dir / ".cache" / "huggingface"
|
| 434 |
+
path.mkdir(exist_ok=True, parents=True)
|
| 435 |
+
|
| 436 |
+
# Create a CACHEDIR.TAG so backup tools can skip this directory.
|
| 437 |
+
_create_cachedir_tag(path)
|
| 438 |
+
|
| 439 |
+
# Create a .gitignore file in the .cache/huggingface directory if it doesn't exist
|
| 440 |
+
# Should be thread-safe enough like this.
|
| 441 |
+
gitignore = path / ".gitignore"
|
| 442 |
+
gitignore_lock = path / ".gitignore.lock"
|
| 443 |
+
if not gitignore.exists():
|
| 444 |
+
try:
|
| 445 |
+
with WeakFileLock(gitignore_lock, timeout=0.1):
|
| 446 |
+
gitignore.write_text("*")
|
| 447 |
+
except IndexError:
|
| 448 |
+
pass
|
| 449 |
+
except OSError: # TimeoutError, FileNotFoundError, PermissionError, etc.
|
| 450 |
+
pass
|
| 451 |
+
try:
|
| 452 |
+
gitignore_lock.unlink()
|
| 453 |
+
except OSError:
|
| 454 |
+
pass
|
| 455 |
+
return path
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def _create_cachedir_tag(cache_dir: Path) -> None:
|
| 459 |
+
"""Create a CACHEDIR.TAG file in ``cache_dir`` if one does not already exist.
|
| 460 |
+
|
| 461 |
+
The tag follows the `Cache Directory Tagging Standard <http://www.brynosaurus.com/cachedir/>`_
|
| 462 |
+
so that backup tools can recognize and skip cache directories.
|
| 463 |
+
"""
|
| 464 |
+
tag_path = cache_dir / "CACHEDIR.TAG"
|
| 465 |
+
if not tag_path.exists():
|
| 466 |
+
try:
|
| 467 |
+
tag_path.write_text(CACHEDIR_TAG_CONTENT)
|
| 468 |
+
except OSError:
|
| 469 |
+
pass
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def _short_hash(filename: str) -> str:
|
| 473 |
+
return base64.urlsafe_b64encode(hashlib.sha1(filename.encode()).digest()).decode()
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_login.py
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains methods to log in to the Hub."""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import subprocess
|
| 18 |
+
from getpass import getpass
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import typer
|
| 22 |
+
|
| 23 |
+
from . import constants
|
| 24 |
+
from .utils import (
|
| 25 |
+
ANSI,
|
| 26 |
+
capture_output,
|
| 27 |
+
get_token,
|
| 28 |
+
is_google_colab,
|
| 29 |
+
is_notebook,
|
| 30 |
+
list_credential_helpers,
|
| 31 |
+
logging,
|
| 32 |
+
run_subprocess,
|
| 33 |
+
set_git_credential,
|
| 34 |
+
unset_git_credential,
|
| 35 |
+
)
|
| 36 |
+
from .utils._auth import (
|
| 37 |
+
_get_token_by_name,
|
| 38 |
+
_get_token_from_environment,
|
| 39 |
+
_get_token_from_file,
|
| 40 |
+
_get_token_from_google_colab,
|
| 41 |
+
_save_stored_tokens,
|
| 42 |
+
_save_token,
|
| 43 |
+
get_stored_tokens,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
_HF_LOGO_ASCII = """
|
| 50 |
+
_| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_|
|
| 51 |
+
_| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
|
| 52 |
+
_|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_|
|
| 53 |
+
_| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
|
| 54 |
+
_| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def login(
|
| 59 |
+
token: str | None = None,
|
| 60 |
+
*,
|
| 61 |
+
add_to_git_credential: bool = False,
|
| 62 |
+
skip_if_logged_in: bool = True,
|
| 63 |
+
) -> None:
|
| 64 |
+
"""Login the machine to access the Hub.
|
| 65 |
+
|
| 66 |
+
The `token` is persisted in cache and set as a git credential. Once done, the machine
|
| 67 |
+
is logged in and the access token will be available across all `huggingface_hub`
|
| 68 |
+
components. If `token` is not provided, it will be prompted to the user either with
|
| 69 |
+
a widget (in a notebook) or via the terminal.
|
| 70 |
+
|
| 71 |
+
To log in from outside of a script, one can also use `hf auth login` which is
|
| 72 |
+
a cli command that wraps [`login`].
|
| 73 |
+
|
| 74 |
+
> [!TIP]
|
| 75 |
+
> [`login`] is a drop-in replacement method for [`notebook_login`] as it wraps and
|
| 76 |
+
> extends its capabilities.
|
| 77 |
+
|
| 78 |
+
> [!TIP]
|
| 79 |
+
> When the token is not passed, [`login`] will automatically detect if the script runs
|
| 80 |
+
> in a notebook or not. However, this detection might not be accurate due to the
|
| 81 |
+
> variety of notebooks that exists nowadays. If that is the case, you can always force
|
| 82 |
+
> the UI by using [`notebook_login`] or [`interpreter_login`].
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
token (`str`, *optional*):
|
| 86 |
+
User access token to generate from https://huggingface.co/settings/token.
|
| 87 |
+
add_to_git_credential (`bool`, defaults to `False`):
|
| 88 |
+
If `True`, token will be set as git credential. If no git credential helper
|
| 89 |
+
is configured, a warning will be displayed to the user. If `token` is `None`,
|
| 90 |
+
the value of `add_to_git_credential` is ignored and will be prompted again
|
| 91 |
+
to the end user.
|
| 92 |
+
skip_if_logged_in (`bool`, defaults to `True`):
|
| 93 |
+
If `True`, do not prompt for token if user is already logged in.
|
| 94 |
+
Set to `False` to force re-login. In CLI, use `--force` instead.
|
| 95 |
+
Raises:
|
| 96 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 97 |
+
If an organization token is passed. Only personal account tokens are valid
|
| 98 |
+
to log in.
|
| 99 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 100 |
+
If token is invalid.
|
| 101 |
+
[`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 102 |
+
If running in a notebook but `ipywidgets` is not installed.
|
| 103 |
+
"""
|
| 104 |
+
if token is not None:
|
| 105 |
+
if not add_to_git_credential:
|
| 106 |
+
logger.info(
|
| 107 |
+
"The token has not been saved to the git credentials helper. Pass "
|
| 108 |
+
"`add_to_git_credential=True` in this function directly or "
|
| 109 |
+
"`--add-to-git-credential` if using via `hf`CLI if "
|
| 110 |
+
"you want to set the git credential as well."
|
| 111 |
+
)
|
| 112 |
+
_login(token, add_to_git_credential=add_to_git_credential)
|
| 113 |
+
elif is_notebook():
|
| 114 |
+
notebook_login(skip_if_logged_in=skip_if_logged_in)
|
| 115 |
+
else:
|
| 116 |
+
interpreter_login(skip_if_logged_in=skip_if_logged_in)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def logout(token_name: str | None = None) -> None:
|
| 120 |
+
"""Logout the machine from the Hub.
|
| 121 |
+
|
| 122 |
+
Token is deleted from the machine and removed from git credential.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
token_name (`str`, *optional*):
|
| 126 |
+
Name of the access token to logout from. If `None`, will log out from all saved access tokens.
|
| 127 |
+
Raises:
|
| 128 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
|
| 129 |
+
If the access token name is not found.
|
| 130 |
+
"""
|
| 131 |
+
if get_token() is None and not get_stored_tokens(): # No active token and no saved access tokens
|
| 132 |
+
logger.warning("Not logged in!")
|
| 133 |
+
return
|
| 134 |
+
if not token_name:
|
| 135 |
+
# Delete all saved access tokens and token
|
| 136 |
+
for file_path in (constants.HF_TOKEN_PATH, constants.HF_STORED_TOKENS_PATH):
|
| 137 |
+
try:
|
| 138 |
+
Path(file_path).unlink()
|
| 139 |
+
except FileNotFoundError:
|
| 140 |
+
pass
|
| 141 |
+
logger.info("Successfully logged out from all access tokens.")
|
| 142 |
+
else:
|
| 143 |
+
_logout_from_token(token_name)
|
| 144 |
+
logger.info(f"Successfully logged out from access token: {token_name}.")
|
| 145 |
+
|
| 146 |
+
unset_git_credential()
|
| 147 |
+
|
| 148 |
+
# Check if still logged in
|
| 149 |
+
if _get_token_from_google_colab() is not None:
|
| 150 |
+
raise OSError(
|
| 151 |
+
"You are automatically logged in using a Google Colab secret.\n"
|
| 152 |
+
"To log out, you must unset the `HF_TOKEN` secret in your Colab settings."
|
| 153 |
+
)
|
| 154 |
+
if _get_token_from_environment() is not None:
|
| 155 |
+
raise OSError(
|
| 156 |
+
"Token has been deleted from your machine but you are still logged in.\n"
|
| 157 |
+
"To log out, you must clear out both `HF_TOKEN` and `HUGGING_FACE_HUB_TOKEN` environment variables."
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def auth_switch(token_name: str, add_to_git_credential: bool = False) -> None:
|
| 162 |
+
"""Switch to a different access token.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
token_name (`str`):
|
| 166 |
+
Name of the access token to switch to.
|
| 167 |
+
add_to_git_credential (`bool`, defaults to `False`):
|
| 168 |
+
If `True`, token will be set as git credential. If no git credential helper
|
| 169 |
+
is configured, a warning will be displayed to the user. If `token` is `None`,
|
| 170 |
+
the value of `add_to_git_credential` is ignored and will be prompted again
|
| 171 |
+
to the end user.
|
| 172 |
+
|
| 173 |
+
Raises:
|
| 174 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
|
| 175 |
+
If the access token name is not found.
|
| 176 |
+
"""
|
| 177 |
+
token = _get_token_by_name(token_name)
|
| 178 |
+
if not token:
|
| 179 |
+
raise ValueError(f"Access token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}")
|
| 180 |
+
# Write token to HF_TOKEN_PATH
|
| 181 |
+
_set_active_token(token_name, add_to_git_credential)
|
| 182 |
+
logger.info(f"The current active token is: {token_name}")
|
| 183 |
+
token_from_environment = _get_token_from_environment()
|
| 184 |
+
if token_from_environment is not None and token_from_environment != token:
|
| 185 |
+
logger.warning(
|
| 186 |
+
"The environment variable `HF_TOKEN` is set and will override the access token you've just switched to."
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def auth_list() -> None:
|
| 191 |
+
"""List all stored access tokens."""
|
| 192 |
+
tokens = get_stored_tokens()
|
| 193 |
+
|
| 194 |
+
if not tokens:
|
| 195 |
+
if _get_token_from_environment():
|
| 196 |
+
logger.info("No stored access tokens found.")
|
| 197 |
+
logger.warning("Note: Environment variable `HF_TOKEN` is set and is the current active token.")
|
| 198 |
+
else:
|
| 199 |
+
logger.info("No access tokens found.")
|
| 200 |
+
return
|
| 201 |
+
# Find current token
|
| 202 |
+
current_token = get_token()
|
| 203 |
+
current_token_name = None
|
| 204 |
+
for token_name in tokens:
|
| 205 |
+
if tokens.get(token_name) == current_token:
|
| 206 |
+
current_token_name = token_name
|
| 207 |
+
# Print header
|
| 208 |
+
max_offset = max(len("token"), max(len(token) for token in tokens)) + 2
|
| 209 |
+
print(f" {{:<{max_offset}}}| {{:<15}}".format("name", "token"))
|
| 210 |
+
print("-" * (max_offset + 2) + "|" + "-" * 15)
|
| 211 |
+
|
| 212 |
+
# Print saved access tokens
|
| 213 |
+
for token_name in tokens:
|
| 214 |
+
token = tokens.get(token_name, "<not set>")
|
| 215 |
+
masked_token = f"{token[:3]}****{token[-4:]}" if token != "<not set>" else token
|
| 216 |
+
is_current = "*" if token == current_token else " "
|
| 217 |
+
|
| 218 |
+
print(f"{is_current} {{:<{max_offset}}}| {{:<15}}".format(token_name, masked_token))
|
| 219 |
+
|
| 220 |
+
if _get_token_from_environment():
|
| 221 |
+
logger.warning(
|
| 222 |
+
"\nNote: Environment variable `HF_TOKEN` is set and is the current active token independently from the stored tokens listed above."
|
| 223 |
+
)
|
| 224 |
+
elif current_token_name is None:
|
| 225 |
+
logger.warning(
|
| 226 |
+
"\nNote: No active token is set and no environment variable `HF_TOKEN` is found. Use `hf auth login` to log in."
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
###
|
| 231 |
+
# Interpreter-based login (text)
|
| 232 |
+
###
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def interpreter_login(*, skip_if_logged_in: bool = True) -> None:
|
| 236 |
+
"""
|
| 237 |
+
Displays a prompt to log in to the HF website and store the token.
|
| 238 |
+
|
| 239 |
+
This is equivalent to [`login`] without passing a token when not run in a notebook.
|
| 240 |
+
[`interpreter_login`] is useful if you want to force the use of the terminal prompt
|
| 241 |
+
instead of a notebook widget.
|
| 242 |
+
|
| 243 |
+
For more details, see [`login`].
|
| 244 |
+
|
| 245 |
+
Args:
|
| 246 |
+
skip_if_logged_in (`bool`, defaults to `True`):
|
| 247 |
+
If `True`, do not prompt for token if user is already logged in.
|
| 248 |
+
Set to `False` to force re-login. In CLI, use `--force` instead.
|
| 249 |
+
"""
|
| 250 |
+
if skip_if_logged_in and get_token() is not None:
|
| 251 |
+
logger.info("User is already logged in. Use `hf auth login --force` to force re-login.")
|
| 252 |
+
return
|
| 253 |
+
|
| 254 |
+
print(_HF_LOGO_ASCII)
|
| 255 |
+
if get_token() is not None:
|
| 256 |
+
logger.info(
|
| 257 |
+
" A token is already saved on your machine. Run `hf auth whoami`"
|
| 258 |
+
" to get more information or `hf auth logout` if you want"
|
| 259 |
+
" to log out."
|
| 260 |
+
)
|
| 261 |
+
logger.info(" Setting a new token will erase the existing one.")
|
| 262 |
+
|
| 263 |
+
logger.info(
|
| 264 |
+
" To log in, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens ."
|
| 265 |
+
)
|
| 266 |
+
if os.name == "nt":
|
| 267 |
+
logger.info("Token can be pasted using 'Right-Click'.")
|
| 268 |
+
token = getpass("Enter your token (input will not be visible): ")
|
| 269 |
+
add_to_git_credential = typer.confirm("Add token as git credential?")
|
| 270 |
+
|
| 271 |
+
_login(token=token, add_to_git_credential=add_to_git_credential)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
###
|
| 275 |
+
# Notebook-based login (widget)
|
| 276 |
+
###
|
| 277 |
+
|
| 278 |
+
NOTEBOOK_LOGIN_PASSWORD_HTML = """<center> <img
|
| 279 |
+
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
|
| 280 |
+
alt='Hugging Face'> <br> Immediately click login after typing your password or
|
| 281 |
+
it might be stored in plain text in this notebook file. </center>"""
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
NOTEBOOK_LOGIN_TOKEN_HTML_START = """<center> <img
|
| 285 |
+
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
|
| 286 |
+
alt='Hugging Face'> <br> Copy a token from <a
|
| 287 |
+
href="https://huggingface.co/settings/tokens" target="_blank">your Hugging Face
|
| 288 |
+
tokens page</a> and paste it below. <br> Immediately click login after copying
|
| 289 |
+
your token or it might be stored in plain text in this notebook file. </center>"""
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
NOTEBOOK_LOGIN_TOKEN_HTML_END = """
|
| 293 |
+
<b>Pro Tip:</b> If you don't already have one, you can create a dedicated
|
| 294 |
+
'notebooks' token with 'write' access, that you can then easily reuse for all
|
| 295 |
+
notebooks. </center>"""
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def notebook_login(*, skip_if_logged_in: bool = True) -> None:
|
| 299 |
+
"""
|
| 300 |
+
Displays a widget to log in to the HF website and store the token.
|
| 301 |
+
|
| 302 |
+
This is equivalent to [`login`] without passing a token when run in a notebook.
|
| 303 |
+
[`notebook_login`] is useful if you want to force the use of the notebook widget
|
| 304 |
+
instead of a prompt in the terminal.
|
| 305 |
+
|
| 306 |
+
For more details, see [`login`].
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
skip_if_logged_in (`bool`, defaults to `True`):
|
| 310 |
+
If `True`, do not prompt for token if user is already logged in.
|
| 311 |
+
Set to `False` to force re-login. In CLI, use `--force` instead.
|
| 312 |
+
"""
|
| 313 |
+
try:
|
| 314 |
+
import ipywidgets.widgets as widgets # type: ignore
|
| 315 |
+
from IPython.display import display # type: ignore
|
| 316 |
+
except ImportError:
|
| 317 |
+
raise ImportError(
|
| 318 |
+
"The `notebook_login` function can only be used in a notebook (Jupyter or"
|
| 319 |
+
" Colab) and you need the `ipywidgets` module: `pip install ipywidgets`."
|
| 320 |
+
)
|
| 321 |
+
if skip_if_logged_in and get_token() is not None:
|
| 322 |
+
logger.info("User is already logged in. Use `hf auth login --force` to force re-login.")
|
| 323 |
+
return
|
| 324 |
+
|
| 325 |
+
box_layout = widgets.Layout(display="flex", flex_flow="column", align_items="center", width="50%")
|
| 326 |
+
|
| 327 |
+
token_widget = widgets.Password(description="Token:")
|
| 328 |
+
git_checkbox_widget = widgets.Checkbox(value=True, description="Add token as git credential?")
|
| 329 |
+
token_finish_button = widgets.Button(description="Login")
|
| 330 |
+
|
| 331 |
+
login_token_widget = widgets.VBox(
|
| 332 |
+
[
|
| 333 |
+
widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_START),
|
| 334 |
+
token_widget,
|
| 335 |
+
git_checkbox_widget,
|
| 336 |
+
token_finish_button,
|
| 337 |
+
widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_END),
|
| 338 |
+
],
|
| 339 |
+
layout=box_layout,
|
| 340 |
+
)
|
| 341 |
+
display(login_token_widget)
|
| 342 |
+
|
| 343 |
+
# On click events
|
| 344 |
+
def login_token_event(t):
|
| 345 |
+
"""Event handler for the login button."""
|
| 346 |
+
token = token_widget.value
|
| 347 |
+
add_to_git_credential = git_checkbox_widget.value
|
| 348 |
+
# Erase token and clear value to make sure it's not saved in the notebook.
|
| 349 |
+
token_widget.value = ""
|
| 350 |
+
# Hide inputs
|
| 351 |
+
login_token_widget.children = [widgets.Label("Connecting...")]
|
| 352 |
+
try:
|
| 353 |
+
with capture_output() as captured:
|
| 354 |
+
_login(token, add_to_git_credential=add_to_git_credential)
|
| 355 |
+
message = captured.getvalue()
|
| 356 |
+
except Exception as error:
|
| 357 |
+
message = str(error)
|
| 358 |
+
# Print result (success message or error)
|
| 359 |
+
login_token_widget.children = [widgets.Label(line) for line in message.split("\n") if line.strip()]
|
| 360 |
+
|
| 361 |
+
token_finish_button.on_click(login_token_event)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
###
|
| 365 |
+
# Login private helpers
|
| 366 |
+
###
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _login(
|
| 370 |
+
token: str,
|
| 371 |
+
add_to_git_credential: bool,
|
| 372 |
+
) -> None:
|
| 373 |
+
from .hf_api import whoami # avoid circular import
|
| 374 |
+
|
| 375 |
+
if token.startswith("api_org"):
|
| 376 |
+
raise ValueError("You must use your personal account token, not an organization token.")
|
| 377 |
+
|
| 378 |
+
token_info = whoami(token)
|
| 379 |
+
permission = token_info["auth"]["accessToken"]["role"]
|
| 380 |
+
logger.info(f"Token is valid (permission: {permission}).")
|
| 381 |
+
|
| 382 |
+
token_name = token_info["auth"]["accessToken"]["displayName"]
|
| 383 |
+
# Store token locally
|
| 384 |
+
_save_token(token=token, token_name=token_name)
|
| 385 |
+
# Set active token
|
| 386 |
+
_set_active_token(token_name=token_name, add_to_git_credential=add_to_git_credential)
|
| 387 |
+
logger.info("Login successful.")
|
| 388 |
+
if _get_token_from_environment():
|
| 389 |
+
logger.warning(
|
| 390 |
+
"Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured."
|
| 391 |
+
)
|
| 392 |
+
else:
|
| 393 |
+
logger.info(f"The current active token is: `{token_name}`")
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def _logout_from_token(token_name: str) -> None:
|
| 397 |
+
"""Logout from a specific access token.
|
| 398 |
+
|
| 399 |
+
Args:
|
| 400 |
+
token_name (`str`):
|
| 401 |
+
The name of the access token to logout from.
|
| 402 |
+
Raises:
|
| 403 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
|
| 404 |
+
If the access token name is not found.
|
| 405 |
+
"""
|
| 406 |
+
stored_tokens = get_stored_tokens()
|
| 407 |
+
# If there is no access tokens saved or the access token name is not found, do nothing
|
| 408 |
+
if not stored_tokens or token_name not in stored_tokens:
|
| 409 |
+
return
|
| 410 |
+
|
| 411 |
+
token = stored_tokens.pop(token_name)
|
| 412 |
+
_save_stored_tokens(stored_tokens)
|
| 413 |
+
|
| 414 |
+
if token == _get_token_from_file():
|
| 415 |
+
logger.warning(f"Active token '{token_name}' has been deleted.")
|
| 416 |
+
Path(constants.HF_TOKEN_PATH).unlink(missing_ok=True)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def _set_active_token(
|
| 420 |
+
token_name: str,
|
| 421 |
+
add_to_git_credential: bool,
|
| 422 |
+
) -> None:
|
| 423 |
+
"""Set the active access token.
|
| 424 |
+
|
| 425 |
+
Args:
|
| 426 |
+
token_name (`str`):
|
| 427 |
+
The name of the token to set as active.
|
| 428 |
+
"""
|
| 429 |
+
token = _get_token_by_name(token_name)
|
| 430 |
+
if not token:
|
| 431 |
+
raise ValueError(f"Token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}")
|
| 432 |
+
if add_to_git_credential:
|
| 433 |
+
if _is_git_credential_helper_configured():
|
| 434 |
+
set_git_credential(token)
|
| 435 |
+
logger.info(
|
| 436 |
+
"Your token has been saved in your configured git credential helpers"
|
| 437 |
+
+ f" ({','.join(list_credential_helpers())})."
|
| 438 |
+
)
|
| 439 |
+
else:
|
| 440 |
+
logger.warning("Token has not been saved to git credential helper.")
|
| 441 |
+
# Write token to HF_TOKEN_PATH
|
| 442 |
+
path = Path(constants.HF_TOKEN_PATH)
|
| 443 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 444 |
+
path.write_text(token)
|
| 445 |
+
logger.info(f"Your token has been saved to {constants.HF_TOKEN_PATH}")
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def _is_git_credential_helper_configured() -> bool:
|
| 449 |
+
"""Check if a git credential helper is configured.
|
| 450 |
+
|
| 451 |
+
Warns user if not the case (except for Google Colab where "store" is set by default
|
| 452 |
+
by `huggingface_hub`).
|
| 453 |
+
"""
|
| 454 |
+
helpers = list_credential_helpers()
|
| 455 |
+
if len(helpers) > 0:
|
| 456 |
+
return True # Do not warn: at least 1 helper is set
|
| 457 |
+
|
| 458 |
+
# Only in Google Colab to avoid the warning message
|
| 459 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1043#issuecomment-1247010710
|
| 460 |
+
if is_google_colab():
|
| 461 |
+
_set_store_as_git_credential_helper_globally()
|
| 462 |
+
return True # Do not warn: "store" is used by default in Google Colab
|
| 463 |
+
|
| 464 |
+
# Otherwise, warn user
|
| 465 |
+
print(
|
| 466 |
+
ANSI.red(
|
| 467 |
+
"Cannot authenticate through git-credential as no helper is defined on your"
|
| 468 |
+
" machine.\nYou might have to re-authenticate when pushing to the Hugging"
|
| 469 |
+
" Face Hub.\nRun the following command in your terminal in case you want to"
|
| 470 |
+
" set the 'store' credential helper as default.\n\ngit config --global"
|
| 471 |
+
" credential.helper store\n\nRead"
|
| 472 |
+
" https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more"
|
| 473 |
+
" details."
|
| 474 |
+
)
|
| 475 |
+
)
|
| 476 |
+
return False
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def _set_store_as_git_credential_helper_globally() -> None:
|
| 480 |
+
"""Set globally the credential.helper to `store`.
|
| 481 |
+
|
| 482 |
+
To be used only in Google Colab as we assume the user doesn't care about the git
|
| 483 |
+
credential config. It is the only particular case where we don't want to display the
|
| 484 |
+
warning message in [`notebook_login()`].
|
| 485 |
+
|
| 486 |
+
Related:
|
| 487 |
+
- https://github.com/huggingface/huggingface_hub/issues/1043
|
| 488 |
+
- https://github.com/huggingface/huggingface_hub/issues/1051
|
| 489 |
+
- https://git-scm.com/docs/git-credential-store
|
| 490 |
+
"""
|
| 491 |
+
try:
|
| 492 |
+
run_subprocess("git config --global credential.helper store")
|
| 493 |
+
except subprocess.CalledProcessError as exc:
|
| 494 |
+
raise OSError(exc.stderr)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_oauth.py
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import hashlib
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import urllib.parse
|
| 7 |
+
import warnings
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import TYPE_CHECKING, Literal
|
| 10 |
+
|
| 11 |
+
from . import constants
|
| 12 |
+
from .hf_api import whoami
|
| 13 |
+
from .utils import experimental, get_token
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
import fastapi
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class OAuthOrgInfo:
|
| 24 |
+
"""
|
| 25 |
+
Information about an organization linked to a user logged in with OAuth.
|
| 26 |
+
|
| 27 |
+
Attributes:
|
| 28 |
+
sub (`str`):
|
| 29 |
+
Unique identifier for the org. OpenID Connect field.
|
| 30 |
+
name (`str`):
|
| 31 |
+
The org's full name. OpenID Connect field.
|
| 32 |
+
preferred_username (`str`):
|
| 33 |
+
The org's username. OpenID Connect field.
|
| 34 |
+
picture (`str`):
|
| 35 |
+
The org's profile picture URL. OpenID Connect field.
|
| 36 |
+
plan (`str`, *optional*):
|
| 37 |
+
The org's plan (e.g., "enterprise", "team"). Hugging Face field.
|
| 38 |
+
can_pay (`Optional[bool]`, *optional*):
|
| 39 |
+
Whether the org has a payment method set up. Hugging Face field.
|
| 40 |
+
role_in_org (`Optional[str]`, *optional*):
|
| 41 |
+
The user's role in the org. Hugging Face field.
|
| 42 |
+
security_restrictions (`Optional[list[Literal["ip", "token-policy", "mfa", "sso"]]]`, *optional*):
|
| 43 |
+
Array of security restrictions that the user hasn't completed for this org. Possible values: "ip", "token-policy", "mfa", "sso". Hugging Face field.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
sub: str
|
| 47 |
+
name: str
|
| 48 |
+
preferred_username: str
|
| 49 |
+
picture: str
|
| 50 |
+
plan: str | None = None
|
| 51 |
+
can_pay: bool | None = None
|
| 52 |
+
role_in_org: str | None = None
|
| 53 |
+
security_restrictions: list[Literal["ip", "token-policy", "mfa", "sso"]] | None = None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@dataclass
|
| 57 |
+
class OAuthUserInfo:
|
| 58 |
+
"""
|
| 59 |
+
Information about a user logged in with OAuth.
|
| 60 |
+
|
| 61 |
+
Attributes:
|
| 62 |
+
sub (`str`):
|
| 63 |
+
Unique identifier for the user, even in case of rename. OpenID Connect field.
|
| 64 |
+
name (`str`):
|
| 65 |
+
The user's full name. OpenID Connect field.
|
| 66 |
+
preferred_username (`str`):
|
| 67 |
+
The user's username. OpenID Connect field.
|
| 68 |
+
email_verified (`Optional[bool]`, *optional*):
|
| 69 |
+
Indicates if the user's email is verified. OpenID Connect field.
|
| 70 |
+
email (`Optional[str]`, *optional*):
|
| 71 |
+
The user's email address. OpenID Connect field.
|
| 72 |
+
picture (`str`):
|
| 73 |
+
The user's profile picture URL. OpenID Connect field.
|
| 74 |
+
profile (`str`):
|
| 75 |
+
The user's profile URL. OpenID Connect field.
|
| 76 |
+
website (`Optional[str]`, *optional*):
|
| 77 |
+
The user's website URL. OpenID Connect field.
|
| 78 |
+
is_pro (`bool`):
|
| 79 |
+
Whether the user is a pro user. Hugging Face field.
|
| 80 |
+
can_pay (`Optional[bool]`, *optional*):
|
| 81 |
+
Whether the user has a payment method set up. Hugging Face field.
|
| 82 |
+
orgs (`Optional[list[OrgInfo]]`, *optional*):
|
| 83 |
+
List of organizations the user is part of. Hugging Face field.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
sub: str
|
| 87 |
+
name: str
|
| 88 |
+
preferred_username: str
|
| 89 |
+
email_verified: bool | None
|
| 90 |
+
email: str | None
|
| 91 |
+
picture: str
|
| 92 |
+
profile: str
|
| 93 |
+
website: str | None
|
| 94 |
+
is_pro: bool
|
| 95 |
+
can_pay: bool | None
|
| 96 |
+
orgs: list[OAuthOrgInfo] | None
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@dataclass
|
| 100 |
+
class OAuthInfo:
|
| 101 |
+
"""
|
| 102 |
+
Information about the OAuth login.
|
| 103 |
+
|
| 104 |
+
Attributes:
|
| 105 |
+
access_token (`str`):
|
| 106 |
+
The access token.
|
| 107 |
+
access_token_expires_at (`datetime.datetime`):
|
| 108 |
+
The expiration date of the access token.
|
| 109 |
+
user_info ([`OAuthUserInfo`]):
|
| 110 |
+
The user information.
|
| 111 |
+
state (`str`, *optional*):
|
| 112 |
+
State passed to the OAuth provider in the original request to the OAuth provider.
|
| 113 |
+
scope (`str`):
|
| 114 |
+
Granted scope.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
access_token: str
|
| 118 |
+
access_token_expires_at: datetime.datetime
|
| 119 |
+
user_info: OAuthUserInfo
|
| 120 |
+
state: str | None
|
| 121 |
+
scope: str
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@experimental
|
| 125 |
+
def attach_huggingface_oauth(app: "fastapi.FastAPI", route_prefix: str = "/"):
|
| 126 |
+
"""
|
| 127 |
+
Add OAuth endpoints to a FastAPI app to enable OAuth login with Hugging Face.
|
| 128 |
+
|
| 129 |
+
How to use:
|
| 130 |
+
- Call this method on your FastAPI app to add the OAuth endpoints.
|
| 131 |
+
- Inside your route handlers, call `parse_huggingface_oauth(request)` to retrieve the OAuth info.
|
| 132 |
+
- If user is logged in, an [`OAuthInfo`] object is returned with the user's info. If not, `None` is returned.
|
| 133 |
+
- In your app, make sure to add links to `/oauth/huggingface/login` and `/oauth/huggingface/logout` for the user to log in and out.
|
| 134 |
+
|
| 135 |
+
Example:
|
| 136 |
+
```py
|
| 137 |
+
from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth
|
| 138 |
+
|
| 139 |
+
# Create a FastAPI app
|
| 140 |
+
app = FastAPI()
|
| 141 |
+
|
| 142 |
+
# Add OAuth endpoints to the FastAPI app
|
| 143 |
+
attach_huggingface_oauth(app)
|
| 144 |
+
|
| 145 |
+
# Add a route that greets the user if they are logged in
|
| 146 |
+
@app.get("/")
|
| 147 |
+
def greet_json(request: Request):
|
| 148 |
+
# Retrieve the OAuth info from the request
|
| 149 |
+
oauth_info = parse_huggingface_oauth(request) # e.g. OAuthInfo dataclass
|
| 150 |
+
if oauth_info is None:
|
| 151 |
+
return {"msg": "Not logged in!"}
|
| 152 |
+
return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"}
|
| 153 |
+
```
|
| 154 |
+
"""
|
| 155 |
+
# TODO: handle generic case (handling OAuth in a non-Space environment with custom dev values) (low priority)
|
| 156 |
+
|
| 157 |
+
# Add SessionMiddleware to the FastAPI app to store the OAuth info in the session.
|
| 158 |
+
# Session Middleware requires a secret key to sign the cookies. Let's use a hash
|
| 159 |
+
# of the OAuth secret key to make it unique to the Space + updated in case OAuth
|
| 160 |
+
# config gets updated. When ran locally, we use an empty string as a secret key.
|
| 161 |
+
try:
|
| 162 |
+
from starlette.middleware.sessions import SessionMiddleware
|
| 163 |
+
except ImportError as e:
|
| 164 |
+
raise ImportError(
|
| 165 |
+
"Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add "
|
| 166 |
+
"`huggingface_hub[oauth]` to your requirements.txt file in order to install the required dependencies."
|
| 167 |
+
) from e
|
| 168 |
+
session_secret = (constants.OAUTH_CLIENT_SECRET or "") + "-v1"
|
| 169 |
+
app.add_middleware(
|
| 170 |
+
SessionMiddleware, # type: ignore
|
| 171 |
+
secret_key=hashlib.sha256(session_secret.encode()).hexdigest(),
|
| 172 |
+
same_site="none",
|
| 173 |
+
https_only=True,
|
| 174 |
+
) # type: ignore
|
| 175 |
+
|
| 176 |
+
# Add OAuth endpoints to the FastAPI app:
|
| 177 |
+
# - {route_prefix}/oauth/huggingface/login
|
| 178 |
+
# - {route_prefix}/oauth/huggingface/callback
|
| 179 |
+
# - {route_prefix}/oauth/huggingface/logout
|
| 180 |
+
# If the app is running in a Space, OAuth is enabled normally.
|
| 181 |
+
# Otherwise, we mock the endpoints to make the user log in with a fake user profile - without any calls to hf.co.
|
| 182 |
+
route_prefix = route_prefix.strip("/")
|
| 183 |
+
if os.getenv("SPACE_ID") is not None:
|
| 184 |
+
logger.info("OAuth is enabled in the Space. Adding OAuth routes.")
|
| 185 |
+
_add_oauth_routes(app, route_prefix=route_prefix)
|
| 186 |
+
else:
|
| 187 |
+
logger.info("App is not running in a Space. Adding mocked OAuth routes.")
|
| 188 |
+
_add_mocked_oauth_routes(app, route_prefix=route_prefix)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def parse_huggingface_oauth(request: "fastapi.Request") -> OAuthInfo | None:
|
| 192 |
+
"""
|
| 193 |
+
Returns the information from a logged-in user as a [`OAuthInfo`] object.
|
| 194 |
+
|
| 195 |
+
For flexibility and future-proofing, this method is very lax in its parsing and does not raise errors.
|
| 196 |
+
Missing fields are set to `None` without a warning.
|
| 197 |
+
|
| 198 |
+
Return `None`, if the user is not logged in (no info in session cookie).
|
| 199 |
+
|
| 200 |
+
See [`attach_huggingface_oauth`] for an example on how to use this method.
|
| 201 |
+
"""
|
| 202 |
+
if "oauth_info" not in request.session:
|
| 203 |
+
logger.debug("No OAuth info in session.")
|
| 204 |
+
return None
|
| 205 |
+
|
| 206 |
+
logger.debug("Parsing OAuth info from session.")
|
| 207 |
+
oauth_data = request.session["oauth_info"]
|
| 208 |
+
user_data = oauth_data.get("userinfo", {})
|
| 209 |
+
orgs_data = user_data.get("orgs", [])
|
| 210 |
+
|
| 211 |
+
orgs = (
|
| 212 |
+
[
|
| 213 |
+
OAuthOrgInfo(
|
| 214 |
+
sub=org.get("sub"),
|
| 215 |
+
name=org.get("name"),
|
| 216 |
+
preferred_username=org.get("preferred_username"),
|
| 217 |
+
picture=org.get("picture"),
|
| 218 |
+
plan=org.get("plan"),
|
| 219 |
+
can_pay=org.get("canPay"),
|
| 220 |
+
role_in_org=org.get("roleInOrg"),
|
| 221 |
+
security_restrictions=org.get("securityRestrictions"),
|
| 222 |
+
)
|
| 223 |
+
for org in orgs_data
|
| 224 |
+
]
|
| 225 |
+
if orgs_data
|
| 226 |
+
else None
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
user_info = OAuthUserInfo(
|
| 230 |
+
sub=user_data.get("sub"),
|
| 231 |
+
name=user_data.get("name"),
|
| 232 |
+
preferred_username=user_data.get("preferred_username"),
|
| 233 |
+
email_verified=user_data.get("email_verified"),
|
| 234 |
+
email=user_data.get("email"),
|
| 235 |
+
picture=user_data.get("picture"),
|
| 236 |
+
profile=user_data.get("profile"),
|
| 237 |
+
website=user_data.get("website"),
|
| 238 |
+
is_pro=user_data.get("isPro"),
|
| 239 |
+
can_pay=user_data.get("canPay"),
|
| 240 |
+
orgs=orgs,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
return OAuthInfo(
|
| 244 |
+
access_token=oauth_data.get("access_token"),
|
| 245 |
+
access_token_expires_at=datetime.datetime.fromtimestamp(oauth_data.get("expires_at")),
|
| 246 |
+
user_info=user_info,
|
| 247 |
+
state=oauth_data.get("state"),
|
| 248 |
+
scope=oauth_data.get("scope"),
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _add_oauth_routes(app: "fastapi.FastAPI", route_prefix: str) -> None:
|
| 253 |
+
"""Add OAuth routes to the FastAPI app (login, callback handler and logout)."""
|
| 254 |
+
try:
|
| 255 |
+
import fastapi
|
| 256 |
+
from authlib.integrations.base_client.errors import MismatchingStateError
|
| 257 |
+
from authlib.integrations.starlette_client import OAuth
|
| 258 |
+
from fastapi.responses import RedirectResponse
|
| 259 |
+
except ImportError as e:
|
| 260 |
+
raise ImportError(
|
| 261 |
+
"Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add "
|
| 262 |
+
"`huggingface_hub[oauth]` to your requirements.txt file."
|
| 263 |
+
) from e
|
| 264 |
+
|
| 265 |
+
# Check environment variables
|
| 266 |
+
msg = (
|
| 267 |
+
"OAuth is required but '{}' environment variable is not set. Make sure you've enabled OAuth in your Space by"
|
| 268 |
+
" setting `hf_oauth: true` in the Space metadata."
|
| 269 |
+
)
|
| 270 |
+
if constants.OAUTH_CLIENT_ID is None:
|
| 271 |
+
raise ValueError(msg.format("OAUTH_CLIENT_ID"))
|
| 272 |
+
if constants.OAUTH_CLIENT_SECRET is None:
|
| 273 |
+
raise ValueError(msg.format("OAUTH_CLIENT_SECRET"))
|
| 274 |
+
if constants.OAUTH_SCOPES is None:
|
| 275 |
+
raise ValueError(msg.format("OAUTH_SCOPES"))
|
| 276 |
+
if constants.OPENID_PROVIDER_URL is None:
|
| 277 |
+
raise ValueError(msg.format("OPENID_PROVIDER_URL"))
|
| 278 |
+
|
| 279 |
+
# Register OAuth server
|
| 280 |
+
oauth = OAuth()
|
| 281 |
+
oauth.register(
|
| 282 |
+
name="huggingface",
|
| 283 |
+
client_id=constants.OAUTH_CLIENT_ID,
|
| 284 |
+
client_secret=constants.OAUTH_CLIENT_SECRET,
|
| 285 |
+
client_kwargs={"scope": constants.OAUTH_SCOPES},
|
| 286 |
+
server_metadata_url=constants.OPENID_PROVIDER_URL + "/.well-known/openid-configuration",
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix)
|
| 290 |
+
|
| 291 |
+
# Register OAuth endpoints
|
| 292 |
+
@app.get(login_uri)
|
| 293 |
+
async def oauth_login(request: fastapi.Request) -> RedirectResponse:
|
| 294 |
+
"""Endpoint that redirects to HF OAuth page."""
|
| 295 |
+
redirect_uri = _generate_redirect_uri(request)
|
| 296 |
+
return await oauth.huggingface.authorize_redirect(request, redirect_uri) # type: ignore
|
| 297 |
+
|
| 298 |
+
@app.get(callback_uri)
|
| 299 |
+
async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse:
|
| 300 |
+
"""Endpoint that handles the OAuth callback."""
|
| 301 |
+
try:
|
| 302 |
+
oauth_info = await oauth.huggingface.authorize_access_token(request) # type: ignore
|
| 303 |
+
except MismatchingStateError:
|
| 304 |
+
# Parse query params
|
| 305 |
+
nb_redirects = int(request.query_params.get("_nb_redirects", 0))
|
| 306 |
+
target_url = request.query_params.get("_target_url")
|
| 307 |
+
|
| 308 |
+
# Build redirect URI with the same query params as before and bump nb_redirects count
|
| 309 |
+
query_params: dict[str, int | str] = {"_nb_redirects": nb_redirects + 1}
|
| 310 |
+
if target_url:
|
| 311 |
+
query_params["_target_url"] = target_url
|
| 312 |
+
|
| 313 |
+
redirect_uri = f"{login_uri}?{urllib.parse.urlencode(query_params)}"
|
| 314 |
+
|
| 315 |
+
# If the user is redirected more than 3 times, it is very likely that the cookie is not working properly.
|
| 316 |
+
# (e.g. browser is blocking third-party cookies in iframe). In this case, redirect the user in the
|
| 317 |
+
# non-iframe view.
|
| 318 |
+
if nb_redirects > constants.OAUTH_MAX_REDIRECTS:
|
| 319 |
+
host = os.environ.get("SPACE_HOST")
|
| 320 |
+
if host is None: # cannot happen in a Space
|
| 321 |
+
raise RuntimeError(
|
| 322 |
+
"App is not running in a Space (SPACE_HOST environment variable is not set). Cannot redirect to non-iframe view."
|
| 323 |
+
) from None
|
| 324 |
+
host_url = "https://" + host.rstrip("/")
|
| 325 |
+
return RedirectResponse(host_url + redirect_uri)
|
| 326 |
+
|
| 327 |
+
# Redirect the user to the login page again
|
| 328 |
+
return RedirectResponse(redirect_uri)
|
| 329 |
+
|
| 330 |
+
# OAuth login worked => store the user info in the session and redirect
|
| 331 |
+
logger.debug("Successfully logged in with OAuth. Storing user info in session.")
|
| 332 |
+
request.session["oauth_info"] = oauth_info
|
| 333 |
+
return RedirectResponse(_get_redirect_target(request))
|
| 334 |
+
|
| 335 |
+
@app.get(logout_uri)
|
| 336 |
+
async def oauth_logout(request: fastapi.Request) -> RedirectResponse:
|
| 337 |
+
"""Endpoint that logs out the user (e.g. delete info from cookie session)."""
|
| 338 |
+
logger.debug("Logged out with OAuth. Removing user info from session.")
|
| 339 |
+
request.session.pop("oauth_info", None)
|
| 340 |
+
return RedirectResponse(_get_redirect_target(request))
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def _add_mocked_oauth_routes(app: "fastapi.FastAPI", route_prefix: str = "/") -> None:
|
| 344 |
+
"""Add fake oauth routes if app is run locally and OAuth is enabled.
|
| 345 |
+
|
| 346 |
+
Using OAuth will have the same behavior as in a Space but instead of authenticating with HF, a mocked user profile
|
| 347 |
+
is added to the session.
|
| 348 |
+
"""
|
| 349 |
+
try:
|
| 350 |
+
import fastapi
|
| 351 |
+
from fastapi.responses import RedirectResponse
|
| 352 |
+
from starlette.datastructures import URL
|
| 353 |
+
except ImportError as e:
|
| 354 |
+
raise ImportError(
|
| 355 |
+
"Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add "
|
| 356 |
+
"`huggingface_hub[oauth]` to your requirements.txt file."
|
| 357 |
+
) from e
|
| 358 |
+
|
| 359 |
+
warnings.warn(
|
| 360 |
+
"OAuth is not supported outside of a Space environment. To help you debug your app locally, the oauth endpoints"
|
| 361 |
+
" are mocked to return your profile and token. To make it work, your machine must be logged in to Huggingface."
|
| 362 |
+
)
|
| 363 |
+
mocked_oauth_info = _get_mocked_oauth_info()
|
| 364 |
+
|
| 365 |
+
login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix)
|
| 366 |
+
|
| 367 |
+
# Define OAuth routes
|
| 368 |
+
@app.get(login_uri)
|
| 369 |
+
async def oauth_login(request: fastapi.Request) -> RedirectResponse:
|
| 370 |
+
"""Fake endpoint that redirects to HF OAuth page."""
|
| 371 |
+
# Define target (where to redirect after login)
|
| 372 |
+
redirect_uri = _generate_redirect_uri(request)
|
| 373 |
+
return RedirectResponse(callback_uri + "?" + urllib.parse.urlencode({"_target_url": redirect_uri}))
|
| 374 |
+
|
| 375 |
+
@app.get(callback_uri)
|
| 376 |
+
async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse:
|
| 377 |
+
"""Endpoint that handles the OAuth callback."""
|
| 378 |
+
request.session["oauth_info"] = mocked_oauth_info
|
| 379 |
+
return RedirectResponse(_get_redirect_target(request))
|
| 380 |
+
|
| 381 |
+
@app.get(logout_uri)
|
| 382 |
+
async def oauth_logout(request: fastapi.Request) -> RedirectResponse:
|
| 383 |
+
"""Endpoint that logs out the user (e.g. delete cookie session)."""
|
| 384 |
+
request.session.pop("oauth_info", None)
|
| 385 |
+
logout_url = URL("/").include_query_params(**request.query_params)
|
| 386 |
+
return RedirectResponse(url=logout_url, status_code=302) # see https://github.com/gradio-app/gradio/pull/9659
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def _generate_redirect_uri(request: "fastapi.Request") -> str:
|
| 390 |
+
if "_target_url" in request.query_params:
|
| 391 |
+
# if `_target_url` already in query params => respect it
|
| 392 |
+
target = request.query_params["_target_url"]
|
| 393 |
+
else:
|
| 394 |
+
# otherwise => keep query params
|
| 395 |
+
target = "/?" + urllib.parse.urlencode(request.query_params)
|
| 396 |
+
|
| 397 |
+
redirect_uri = request.url_for("oauth_redirect_callback").include_query_params(_target_url=target)
|
| 398 |
+
redirect_uri_as_str = str(redirect_uri)
|
| 399 |
+
if redirect_uri.netloc.endswith(".hf.space"):
|
| 400 |
+
# In Space, FastAPI redirect as http but we want https
|
| 401 |
+
redirect_uri_as_str = redirect_uri_as_str.replace("http://", "https://")
|
| 402 |
+
return redirect_uri_as_str
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def _get_redirect_target(request: "fastapi.Request", default_target: str = "/") -> str:
|
| 406 |
+
return request.query_params.get("_target_url", default_target)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _get_mocked_oauth_info() -> dict:
|
| 410 |
+
token = get_token()
|
| 411 |
+
if token is None:
|
| 412 |
+
raise ValueError(
|
| 413 |
+
"Your machine must be logged in to HF to debug an OAuth app locally. Please"
|
| 414 |
+
" run `hf auth login` or set `HF_TOKEN` as environment variable "
|
| 415 |
+
"with one of your access token. You can generate a new token in your "
|
| 416 |
+
"settings page (https://huggingface.co/settings/tokens)."
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
user = whoami()
|
| 420 |
+
if user["type"] != "user":
|
| 421 |
+
raise ValueError(
|
| 422 |
+
"Your machine is not logged in with a personal account. Please use a "
|
| 423 |
+
"personal access token. You can generate a new token in your settings page"
|
| 424 |
+
" (https://huggingface.co/settings/tokens)."
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
return {
|
| 428 |
+
"access_token": token,
|
| 429 |
+
"token_type": "bearer",
|
| 430 |
+
"expires_in": 8 * 60 * 60, # 8 hours
|
| 431 |
+
"id_token": "FOOBAR",
|
| 432 |
+
"scope": "openid profile",
|
| 433 |
+
"refresh_token": "hf_oauth__refresh_token",
|
| 434 |
+
"expires_at": int(time.time()) + 8 * 60 * 60, # 8 hours
|
| 435 |
+
"userinfo": {
|
| 436 |
+
"sub": "0123456789",
|
| 437 |
+
"name": user["fullname"],
|
| 438 |
+
"preferred_username": user["name"],
|
| 439 |
+
"profile": f"https://huggingface.co/{user['name']}",
|
| 440 |
+
"picture": user["avatarUrl"],
|
| 441 |
+
"website": "",
|
| 442 |
+
"aud": "00000000-0000-0000-0000-000000000000",
|
| 443 |
+
"auth_time": 1691672844,
|
| 444 |
+
"nonce": "aaaaaaaaaaaaaaaaaaa",
|
| 445 |
+
"iat": 1691672844,
|
| 446 |
+
"exp": 1691676444,
|
| 447 |
+
"iss": "https://huggingface.co",
|
| 448 |
+
},
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def _get_oauth_uris(route_prefix: str = "/") -> tuple[str, str, str]:
|
| 453 |
+
route_prefix = route_prefix.strip("/")
|
| 454 |
+
if route_prefix:
|
| 455 |
+
route_prefix = f"/{route_prefix}"
|
| 456 |
+
return (
|
| 457 |
+
f"{route_prefix}/oauth/huggingface/login",
|
| 458 |
+
f"{route_prefix}/oauth/huggingface/callback",
|
| 459 |
+
f"{route_prefix}/oauth/huggingface/logout",
|
| 460 |
+
)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_snapshot_download.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from collections.abc import Iterable
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Literal, overload
|
| 5 |
+
|
| 6 |
+
import httpx
|
| 7 |
+
from tqdm.auto import tqdm as base_tqdm
|
| 8 |
+
from tqdm.contrib.concurrent import thread_map
|
| 9 |
+
|
| 10 |
+
from . import constants
|
| 11 |
+
from .errors import (
|
| 12 |
+
DryRunError,
|
| 13 |
+
GatedRepoError,
|
| 14 |
+
HfHubHTTPError,
|
| 15 |
+
LocalEntryNotFoundError,
|
| 16 |
+
RepositoryNotFoundError,
|
| 17 |
+
RevisionNotFoundError,
|
| 18 |
+
)
|
| 19 |
+
from .file_download import REGEX_COMMIT_HASH, DryRunFileInfo, hf_hub_download, repo_folder_name
|
| 20 |
+
from .hf_api import DatasetInfo, HfApi, KernelInfo, ModelInfo, RepoFile, SpaceInfo
|
| 21 |
+
from .utils import OfflineModeIsEnabled, filter_repo_objects, logging, validate_hf_hub_args
|
| 22 |
+
from .utils.tqdm import _create_progress_bar
|
| 23 |
+
from .utils.tqdm import tqdm as hf_tqdm
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
LARGE_REPO_THRESHOLD = 1000 # After this limit, we don't consider `repo_info.siblings` to be reliable enough
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@overload
|
| 32 |
+
def snapshot_download(
|
| 33 |
+
repo_id: str,
|
| 34 |
+
*,
|
| 35 |
+
repo_type: str | None = None,
|
| 36 |
+
revision: str | None = None,
|
| 37 |
+
cache_dir: str | Path | None = None,
|
| 38 |
+
local_dir: str | Path | None = None,
|
| 39 |
+
library_name: str | None = None,
|
| 40 |
+
library_version: str | None = None,
|
| 41 |
+
user_agent: dict | str | None = None,
|
| 42 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 43 |
+
force_download: bool = False,
|
| 44 |
+
token: bool | str | None = None,
|
| 45 |
+
local_files_only: bool = False,
|
| 46 |
+
allow_patterns: list[str] | str | None = None,
|
| 47 |
+
ignore_patterns: list[str] | str | None = None,
|
| 48 |
+
max_workers: int = 8,
|
| 49 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 50 |
+
headers: dict[str, str] | None = None,
|
| 51 |
+
endpoint: str | None = None,
|
| 52 |
+
dry_run: Literal[False] = False,
|
| 53 |
+
) -> str: ...
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@overload
|
| 57 |
+
def snapshot_download(
|
| 58 |
+
repo_id: str,
|
| 59 |
+
*,
|
| 60 |
+
repo_type: str | None = None,
|
| 61 |
+
revision: str | None = None,
|
| 62 |
+
cache_dir: str | Path | None = None,
|
| 63 |
+
local_dir: str | Path | None = None,
|
| 64 |
+
library_name: str | None = None,
|
| 65 |
+
library_version: str | None = None,
|
| 66 |
+
user_agent: dict | str | None = None,
|
| 67 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 68 |
+
force_download: bool = False,
|
| 69 |
+
token: bool | str | None = None,
|
| 70 |
+
local_files_only: bool = False,
|
| 71 |
+
allow_patterns: list[str] | str | None = None,
|
| 72 |
+
ignore_patterns: list[str] | str | None = None,
|
| 73 |
+
max_workers: int = 8,
|
| 74 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 75 |
+
headers: dict[str, str] | None = None,
|
| 76 |
+
endpoint: str | None = None,
|
| 77 |
+
dry_run: Literal[True] = True,
|
| 78 |
+
) -> list[DryRunFileInfo]: ...
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@overload
|
| 82 |
+
def snapshot_download(
|
| 83 |
+
repo_id: str,
|
| 84 |
+
*,
|
| 85 |
+
repo_type: str | None = None,
|
| 86 |
+
revision: str | None = None,
|
| 87 |
+
cache_dir: str | Path | None = None,
|
| 88 |
+
local_dir: str | Path | None = None,
|
| 89 |
+
library_name: str | None = None,
|
| 90 |
+
library_version: str | None = None,
|
| 91 |
+
user_agent: dict | str | None = None,
|
| 92 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 93 |
+
force_download: bool = False,
|
| 94 |
+
token: bool | str | None = None,
|
| 95 |
+
local_files_only: bool = False,
|
| 96 |
+
allow_patterns: list[str] | str | None = None,
|
| 97 |
+
ignore_patterns: list[str] | str | None = None,
|
| 98 |
+
max_workers: int = 8,
|
| 99 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 100 |
+
headers: dict[str, str] | None = None,
|
| 101 |
+
endpoint: str | None = None,
|
| 102 |
+
dry_run: bool = False,
|
| 103 |
+
) -> str | list[DryRunFileInfo]: ...
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@validate_hf_hub_args
|
| 107 |
+
def snapshot_download(
|
| 108 |
+
repo_id: str,
|
| 109 |
+
*,
|
| 110 |
+
repo_type: str | None = None,
|
| 111 |
+
revision: str | None = None,
|
| 112 |
+
cache_dir: str | Path | None = None,
|
| 113 |
+
local_dir: str | Path | None = None,
|
| 114 |
+
library_name: str | None = None,
|
| 115 |
+
library_version: str | None = None,
|
| 116 |
+
user_agent: dict | str | None = None,
|
| 117 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 118 |
+
force_download: bool = False,
|
| 119 |
+
token: bool | str | None = None,
|
| 120 |
+
local_files_only: bool = False,
|
| 121 |
+
allow_patterns: list[str] | str | None = None,
|
| 122 |
+
ignore_patterns: list[str] | str | None = None,
|
| 123 |
+
max_workers: int = 8,
|
| 124 |
+
tqdm_class: type[base_tqdm] | None = None,
|
| 125 |
+
headers: dict[str, str] | None = None,
|
| 126 |
+
endpoint: str | None = None,
|
| 127 |
+
dry_run: bool = False,
|
| 128 |
+
) -> str | list[DryRunFileInfo]:
|
| 129 |
+
"""Download repo files.
|
| 130 |
+
|
| 131 |
+
Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
|
| 132 |
+
a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
|
| 133 |
+
to keep their actual filename relative to that folder. You can also filter which files to download using
|
| 134 |
+
`allow_patterns` and `ignore_patterns`.
|
| 135 |
+
|
| 136 |
+
If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
|
| 137 |
+
option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
|
| 138 |
+
to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
|
| 139 |
+
cache-system, it's optimized for regularly pulling the latest version of a repository.
|
| 140 |
+
|
| 141 |
+
An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
|
| 142 |
+
configured. It is also not possible to filter which files to download when cloning a repository using git.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
repo_id (`str`):
|
| 146 |
+
A user or an organization name and a repo name separated by a `/`.
|
| 147 |
+
repo_type (`str`, *optional*):
|
| 148 |
+
Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo,
|
| 149 |
+
`None` or `"model"` if downloading from a model. Default is `None`.
|
| 150 |
+
revision (`str`, *optional*):
|
| 151 |
+
An optional Git revision id which can be a branch name, a tag, or a
|
| 152 |
+
commit hash.
|
| 153 |
+
cache_dir (`str`, `Path`, *optional*):
|
| 154 |
+
Path to the folder where cached files are stored.
|
| 155 |
+
local_dir (`str` or `Path`, *optional*):
|
| 156 |
+
If provided, the downloaded files will be placed under this directory.
|
| 157 |
+
library_name (`str`, *optional*):
|
| 158 |
+
The name of the library to which the object corresponds.
|
| 159 |
+
library_version (`str`, *optional*):
|
| 160 |
+
The version of the library.
|
| 161 |
+
user_agent (`str`, `dict`, *optional*):
|
| 162 |
+
The user-agent info in the form of a dictionary or a string.
|
| 163 |
+
etag_timeout (`float`, *optional*, defaults to `10`):
|
| 164 |
+
When fetching ETag, how many seconds to wait for the server to send
|
| 165 |
+
data before giving up which is passed to `httpx.request`.
|
| 166 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 167 |
+
Whether the file should be downloaded even if it already exists in the local cache.
|
| 168 |
+
token (`str`, `bool`, *optional*):
|
| 169 |
+
A token to be used for the download.
|
| 170 |
+
- If `True`, the token is read from the HuggingFace config
|
| 171 |
+
folder.
|
| 172 |
+
- If a string, it's used as the authentication token.
|
| 173 |
+
headers (`dict`, *optional*):
|
| 174 |
+
Additional headers to include in the request. Those headers take precedence over the others.
|
| 175 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 176 |
+
If `True`, avoid downloading the file and return the path to the
|
| 177 |
+
local cached file if it exists.
|
| 178 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 179 |
+
If provided, only files matching at least one pattern are downloaded.
|
| 180 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 181 |
+
If provided, files matching any of the patterns are not downloaded.
|
| 182 |
+
max_workers (`int`, *optional*):
|
| 183 |
+
Number of concurrent threads to download files (1 thread = 1 file download).
|
| 184 |
+
Defaults to 8.
|
| 185 |
+
tqdm_class (`tqdm`, *optional*):
|
| 186 |
+
If provided, overwrites the default behavior for the progress bar. Passed
|
| 187 |
+
argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
|
| 188 |
+
Note that the `tqdm_class` is not passed to each individual download.
|
| 189 |
+
Defaults to the custom HF progress bar that can be disabled by setting
|
| 190 |
+
`HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
|
| 191 |
+
dry_run (`bool`, *optional*, defaults to `False`):
|
| 192 |
+
If `True`, perform a dry run without actually downloading the files. Returns a list of
|
| 193 |
+
[`DryRunFileInfo`] objects containing information about what would be downloaded.
|
| 194 |
+
|
| 195 |
+
Returns:
|
| 196 |
+
`str` or list of [`DryRunFileInfo`]:
|
| 197 |
+
- If `dry_run=False`: Local snapshot path.
|
| 198 |
+
- If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information.
|
| 199 |
+
|
| 200 |
+
Raises:
|
| 201 |
+
[`~utils.RepositoryNotFoundError`]
|
| 202 |
+
If the repository to download from cannot be found. This may be because it doesn't exist,
|
| 203 |
+
or because it is set to `private` and you do not have access.
|
| 204 |
+
[`~utils.RevisionNotFoundError`]
|
| 205 |
+
If the revision to download from cannot be found.
|
| 206 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 207 |
+
If `token=True` and the token cannot be found.
|
| 208 |
+
[`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
|
| 209 |
+
ETag cannot be determined.
|
| 210 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 211 |
+
if some parameter value is invalid.
|
| 212 |
+
"""
|
| 213 |
+
if cache_dir is None:
|
| 214 |
+
cache_dir = constants.HF_HUB_CACHE
|
| 215 |
+
if revision is None:
|
| 216 |
+
revision = constants.DEFAULT_REVISION
|
| 217 |
+
if isinstance(cache_dir, Path):
|
| 218 |
+
cache_dir = str(cache_dir)
|
| 219 |
+
|
| 220 |
+
if repo_type is None:
|
| 221 |
+
repo_type = "model"
|
| 222 |
+
if repo_type not in constants.REPO_TYPES_WITH_KERNEL:
|
| 223 |
+
raise ValueError(
|
| 224 |
+
f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES_WITH_KERNEL)}"
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
|
| 228 |
+
|
| 229 |
+
api = HfApi(
|
| 230 |
+
library_name=library_name,
|
| 231 |
+
library_version=library_version,
|
| 232 |
+
user_agent=user_agent,
|
| 233 |
+
endpoint=endpoint,
|
| 234 |
+
headers=headers,
|
| 235 |
+
token=token,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
repo_info: ModelInfo | DatasetInfo | SpaceInfo | KernelInfo | None = None
|
| 239 |
+
api_call_error: Exception | None = None
|
| 240 |
+
if not local_files_only:
|
| 241 |
+
# try/except logic to handle different errors => taken from `hf_hub_download`
|
| 242 |
+
try:
|
| 243 |
+
# if we have internet connection we want to list files to download
|
| 244 |
+
repo_info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 245 |
+
except httpx.ProxyError:
|
| 246 |
+
# Actually raise on proxy error
|
| 247 |
+
raise
|
| 248 |
+
except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled) as error:
|
| 249 |
+
# Internet connection is down
|
| 250 |
+
# => will try to use local files only
|
| 251 |
+
api_call_error = error
|
| 252 |
+
pass
|
| 253 |
+
except RevisionNotFoundError:
|
| 254 |
+
# The repo was found but the revision doesn't exist on the Hub (never existed or got deleted)
|
| 255 |
+
raise
|
| 256 |
+
except HfHubHTTPError as error:
|
| 257 |
+
# Multiple reasons for an http error:
|
| 258 |
+
# - Repository is private and invalid/missing token sent
|
| 259 |
+
# - Repository is gated and invalid/missing token sent
|
| 260 |
+
# - Hub is down (error 500 or 504)
|
| 261 |
+
# => let's switch to 'local_files_only=True' to check if the files are already cached.
|
| 262 |
+
# (if it's not the case, the error will be re-raised)
|
| 263 |
+
api_call_error = error
|
| 264 |
+
pass
|
| 265 |
+
|
| 266 |
+
# At this stage, if `repo_info` is None it means either:
|
| 267 |
+
# - internet connection is down
|
| 268 |
+
# - internet connection is deactivated (local_files_only=True or HF_HUB_OFFLINE=True)
|
| 269 |
+
# - repo is private/gated and invalid/missing token sent
|
| 270 |
+
# - Hub is down
|
| 271 |
+
# => let's look if we can find the appropriate folder in the cache:
|
| 272 |
+
# - if the specified revision is a commit hash, look inside "snapshots".
|
| 273 |
+
# - f the specified revision is a branch or tag, look inside "refs".
|
| 274 |
+
# => if local_dir is not None, we will return the path to the local folder if it exists.
|
| 275 |
+
if repo_info is None:
|
| 276 |
+
if dry_run:
|
| 277 |
+
raise DryRunError(
|
| 278 |
+
"Dry run cannot be performed as the repository cannot be accessed. Please check your internet connection or authentication token."
|
| 279 |
+
) from api_call_error
|
| 280 |
+
|
| 281 |
+
# Try to get which commit hash corresponds to the specified revision
|
| 282 |
+
commit_hash = None
|
| 283 |
+
if REGEX_COMMIT_HASH.match(revision):
|
| 284 |
+
commit_hash = revision
|
| 285 |
+
else:
|
| 286 |
+
ref_path = os.path.join(storage_folder, "refs", revision)
|
| 287 |
+
if os.path.exists(ref_path):
|
| 288 |
+
# retrieve commit_hash from refs file
|
| 289 |
+
with open(ref_path) as f:
|
| 290 |
+
commit_hash = f.read()
|
| 291 |
+
|
| 292 |
+
# Try to locate snapshot folder for this commit hash
|
| 293 |
+
if commit_hash is not None and local_dir is None:
|
| 294 |
+
snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
|
| 295 |
+
if os.path.exists(snapshot_folder):
|
| 296 |
+
# Snapshot folder exists => let's return it
|
| 297 |
+
# (but we can't check if all the files are actually there)
|
| 298 |
+
return snapshot_folder
|
| 299 |
+
|
| 300 |
+
# If local_dir is not None, return it if it exists and is not empty
|
| 301 |
+
if local_dir is not None:
|
| 302 |
+
local_dir = Path(local_dir)
|
| 303 |
+
if local_dir.is_dir() and any(local_dir.iterdir()):
|
| 304 |
+
logger.warning(
|
| 305 |
+
f"Returning existing local_dir `{local_dir}` as remote repo cannot be accessed in `snapshot_download` ({api_call_error})."
|
| 306 |
+
)
|
| 307 |
+
return str(local_dir.resolve())
|
| 308 |
+
# If we couldn't find the appropriate folder on disk, raise an error.
|
| 309 |
+
if local_files_only:
|
| 310 |
+
raise LocalEntryNotFoundError(
|
| 311 |
+
"Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
|
| 312 |
+
"outgoing traffic has been disabled. To enable repo look-ups and downloads online, pass "
|
| 313 |
+
"'local_files_only=False' as input."
|
| 314 |
+
)
|
| 315 |
+
elif isinstance(api_call_error, OfflineModeIsEnabled):
|
| 316 |
+
raise LocalEntryNotFoundError(
|
| 317 |
+
"Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
|
| 318 |
+
"outgoing traffic has been disabled. To enable repo look-ups and downloads online, set "
|
| 319 |
+
"'HF_HUB_OFFLINE=0' as environment variable."
|
| 320 |
+
) from api_call_error
|
| 321 |
+
elif isinstance(api_call_error, (RepositoryNotFoundError, GatedRepoError)) or (
|
| 322 |
+
isinstance(api_call_error, HfHubHTTPError) and api_call_error.response.status_code == 401
|
| 323 |
+
):
|
| 324 |
+
# Repo not found, gated, or specific authentication error => let's raise the actual error
|
| 325 |
+
raise api_call_error
|
| 326 |
+
else:
|
| 327 |
+
# Otherwise: most likely a connection issue or Hub downtime => let's warn the user
|
| 328 |
+
raise LocalEntryNotFoundError(
|
| 329 |
+
f"Got: {api_call_error.__class__.__name__}: {api_call_error}"
|
| 330 |
+
"\nAn error happened while trying to locate the files on the Hub and we cannot find the appropriate"
|
| 331 |
+
" snapshot folder for the specified revision on the local disk. Please check your internet connection"
|
| 332 |
+
" and try again."
|
| 333 |
+
) from api_call_error
|
| 334 |
+
|
| 335 |
+
# At this stage, internet connection is up and running
|
| 336 |
+
# => let's download the files!
|
| 337 |
+
assert repo_info.sha is not None, "Repo info returned from server must have a revision sha."
|
| 338 |
+
|
| 339 |
+
# Corner case: on very large repos, the siblings list in `repo_info` might not contain all files.
|
| 340 |
+
# In that case, we need to use the `list_repo_tree` method to prevent caching issues.
|
| 341 |
+
# Note: kernel repos don't expose siblings in their info response, so we always fall back to `list_repo_tree`.
|
| 342 |
+
siblings = getattr(repo_info, "siblings", None)
|
| 343 |
+
repo_files: Iterable[str] = [f.rfilename for f in siblings] if siblings is not None else []
|
| 344 |
+
unreliable_nb_files = siblings is None or len(siblings) == 0 or len(siblings) > LARGE_REPO_THRESHOLD
|
| 345 |
+
if unreliable_nb_files:
|
| 346 |
+
logger.info(
|
| 347 |
+
"Number of files in the repo is unreliable. Using `list_repo_tree` to ensure all files are listed."
|
| 348 |
+
)
|
| 349 |
+
repo_files = (
|
| 350 |
+
f.rfilename
|
| 351 |
+
for f in api.list_repo_tree(repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type)
|
| 352 |
+
if isinstance(f, RepoFile)
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
filtered_repo_files: Iterable[str] = filter_repo_objects(
|
| 356 |
+
items=repo_files,
|
| 357 |
+
allow_patterns=allow_patterns,
|
| 358 |
+
ignore_patterns=ignore_patterns,
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
if not unreliable_nb_files:
|
| 362 |
+
filtered_repo_files = list(filtered_repo_files)
|
| 363 |
+
tqdm_desc = f"Fetching {len(filtered_repo_files)} files"
|
| 364 |
+
else:
|
| 365 |
+
tqdm_desc = "Fetching ... files"
|
| 366 |
+
if dry_run:
|
| 367 |
+
tqdm_desc = "[dry-run] " + tqdm_desc
|
| 368 |
+
|
| 369 |
+
commit_hash = repo_info.sha
|
| 370 |
+
snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
|
| 371 |
+
# if passed revision is not identical to commit_hash
|
| 372 |
+
# then revision has to be a branch name or tag name.
|
| 373 |
+
# In that case store a ref.
|
| 374 |
+
if revision != commit_hash:
|
| 375 |
+
ref_path = os.path.join(storage_folder, "refs", revision)
|
| 376 |
+
try:
|
| 377 |
+
os.makedirs(os.path.dirname(ref_path), exist_ok=True)
|
| 378 |
+
with open(ref_path, "w") as f:
|
| 379 |
+
f.write(commit_hash)
|
| 380 |
+
except OSError as e:
|
| 381 |
+
logger.warning(f"Ignored error while writing commit hash to {ref_path}: {e}.")
|
| 382 |
+
|
| 383 |
+
results: list[str | DryRunFileInfo] = []
|
| 384 |
+
|
| 385 |
+
# User can use its own tqdm class or the default one from `huggingface_hub.utils`
|
| 386 |
+
tqdm_class = tqdm_class or hf_tqdm
|
| 387 |
+
|
| 388 |
+
# Create a progress bar for the bytes downloaded
|
| 389 |
+
# This progress bar is shared across threads/files and gets updated each time we fetch
|
| 390 |
+
# metadata for a file.
|
| 391 |
+
bytes_progress = _create_progress_bar(
|
| 392 |
+
cls=tqdm_class,
|
| 393 |
+
log_level=logger.getEffectiveLevel(),
|
| 394 |
+
name="huggingface_hub.snapshot_download",
|
| 395 |
+
desc="Downloading (incomplete total...)",
|
| 396 |
+
total=0,
|
| 397 |
+
initial=0,
|
| 398 |
+
unit="B",
|
| 399 |
+
unit_scale=True,
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
class _AggregatedTqdm:
|
| 403 |
+
"""Fake tqdm object to aggregate progress into the parent `bytes_progress` bar.
|
| 404 |
+
|
| 405 |
+
In practice the `_AggregatedTqdm` object won't be displayed, it's just used to update
|
| 406 |
+
the `bytes_progress` bar from each thread/file download.
|
| 407 |
+
"""
|
| 408 |
+
|
| 409 |
+
def __init__(self, *args, **kwargs):
|
| 410 |
+
# Adjust the total of the parent progress bar
|
| 411 |
+
total = kwargs.pop("total", None)
|
| 412 |
+
if total is not None:
|
| 413 |
+
bytes_progress.total += total
|
| 414 |
+
bytes_progress.refresh()
|
| 415 |
+
|
| 416 |
+
# Adjust initial of the parent progress bar
|
| 417 |
+
initial = kwargs.pop("initial", 0)
|
| 418 |
+
if initial:
|
| 419 |
+
bytes_progress.update(initial)
|
| 420 |
+
|
| 421 |
+
def __enter__(self):
|
| 422 |
+
return self
|
| 423 |
+
|
| 424 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 425 |
+
pass
|
| 426 |
+
|
| 427 |
+
def update(self, n: int | float | None = 1) -> None:
|
| 428 |
+
bytes_progress.update(n)
|
| 429 |
+
|
| 430 |
+
# we pass the commit_hash to hf_hub_download
|
| 431 |
+
# so no network call happens if we already
|
| 432 |
+
# have the file locally.
|
| 433 |
+
def _inner_hf_hub_download(repo_file: str) -> None:
|
| 434 |
+
results.append(
|
| 435 |
+
hf_hub_download( # type: ignore
|
| 436 |
+
repo_id,
|
| 437 |
+
filename=repo_file,
|
| 438 |
+
repo_type=repo_type,
|
| 439 |
+
revision=commit_hash,
|
| 440 |
+
endpoint=endpoint,
|
| 441 |
+
cache_dir=cache_dir,
|
| 442 |
+
local_dir=local_dir,
|
| 443 |
+
library_name=library_name,
|
| 444 |
+
library_version=library_version,
|
| 445 |
+
user_agent=user_agent,
|
| 446 |
+
etag_timeout=etag_timeout,
|
| 447 |
+
force_download=force_download,
|
| 448 |
+
token=token,
|
| 449 |
+
headers=headers,
|
| 450 |
+
tqdm_class=_AggregatedTqdm, # type: ignore
|
| 451 |
+
dry_run=dry_run,
|
| 452 |
+
)
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
thread_map(
|
| 456 |
+
_inner_hf_hub_download,
|
| 457 |
+
filtered_repo_files,
|
| 458 |
+
desc=tqdm_desc,
|
| 459 |
+
max_workers=max_workers,
|
| 460 |
+
tqdm_class=tqdm_class,
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
bytes_progress.set_description("Download complete")
|
| 464 |
+
|
| 465 |
+
if dry_run:
|
| 466 |
+
assert all(isinstance(r, DryRunFileInfo) for r in results)
|
| 467 |
+
return results # type: ignore
|
| 468 |
+
|
| 469 |
+
if local_dir is not None:
|
| 470 |
+
return str(os.path.realpath(local_dir))
|
| 471 |
+
return snapshot_folder
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_space_api.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2019-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
from enum import Enum
|
| 17 |
+
from typing import Literal
|
| 18 |
+
|
| 19 |
+
from huggingface_hub.utils import parse_datetime
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class SpaceStage(str, Enum):
|
| 23 |
+
"""
|
| 24 |
+
Enumeration of possible stage of a Space on the Hub.
|
| 25 |
+
|
| 26 |
+
Value can be compared to a string:
|
| 27 |
+
```py
|
| 28 |
+
assert SpaceStage.BUILDING == "BUILDING"
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L61 (private url).
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
# Copied from moon-landing > server > repo_types > SpaceInfo.ts (private repo)
|
| 35 |
+
NO_APP_FILE = "NO_APP_FILE"
|
| 36 |
+
CONFIG_ERROR = "CONFIG_ERROR"
|
| 37 |
+
BUILDING = "BUILDING"
|
| 38 |
+
BUILD_ERROR = "BUILD_ERROR"
|
| 39 |
+
RUNNING = "RUNNING"
|
| 40 |
+
RUNNING_BUILDING = "RUNNING_BUILDING"
|
| 41 |
+
RUNTIME_ERROR = "RUNTIME_ERROR"
|
| 42 |
+
DELETING = "DELETING"
|
| 43 |
+
STOPPED = "STOPPED"
|
| 44 |
+
PAUSED = "PAUSED"
|
| 45 |
+
APP_STARTING = "APP_STARTING"
|
| 46 |
+
RUNNING_APP_STARTING = "RUNNING_APP_STARTING"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class SpaceHardware(str, Enum):
|
| 50 |
+
"""
|
| 51 |
+
Enumeration of hardwares available to run your Space on the Hub.
|
| 52 |
+
|
| 53 |
+
Value can be compared to a string:
|
| 54 |
+
```py
|
| 55 |
+
assert SpaceHardware.CPU_BASIC == "cpu-basic"
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
Taken from https://github.com/huggingface-internal/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts (private url).
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
# CPU
|
| 62 |
+
CPU_BASIC = "cpu-basic"
|
| 63 |
+
CPU_UPGRADE = "cpu-upgrade"
|
| 64 |
+
CPU_PERFORMANCE = "cpu-performance"
|
| 65 |
+
CPU_XL = "cpu-xl"
|
| 66 |
+
SPRX8 = "sprx8"
|
| 67 |
+
|
| 68 |
+
# ZeroGPU
|
| 69 |
+
ZERO_A10G = "zero-a10g"
|
| 70 |
+
|
| 71 |
+
# GPU
|
| 72 |
+
T4_SMALL = "t4-small"
|
| 73 |
+
T4_MEDIUM = "t4-medium"
|
| 74 |
+
L4X1 = "l4x1"
|
| 75 |
+
L4X4 = "l4x4"
|
| 76 |
+
L40SX1 = "l40sx1"
|
| 77 |
+
L40SX4 = "l40sx4"
|
| 78 |
+
L40SX8 = "l40sx8"
|
| 79 |
+
A10G_SMALL = "a10g-small"
|
| 80 |
+
A10G_LARGE = "a10g-large"
|
| 81 |
+
A10G_LARGEX2 = "a10g-largex2"
|
| 82 |
+
A10G_LARGEX4 = "a10g-largex4"
|
| 83 |
+
A100_LARGE = "a100-large"
|
| 84 |
+
A100X4 = "a100x4"
|
| 85 |
+
A100X8 = "a100x8"
|
| 86 |
+
H200 = "h200"
|
| 87 |
+
H200X2 = "h200x2"
|
| 88 |
+
H200X4 = "h200x4"
|
| 89 |
+
H200X8 = "h200x8"
|
| 90 |
+
|
| 91 |
+
# Neuron
|
| 92 |
+
INF2X6 = "inf2x6"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class SpaceStorage(str, Enum):
|
| 96 |
+
"""
|
| 97 |
+
Enumeration of persistent storage available for your Space on the Hub.
|
| 98 |
+
|
| 99 |
+
Value can be compared to a string:
|
| 100 |
+
```py
|
| 101 |
+
assert SpaceStorage.SMALL == "small"
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts#L24 (private url).
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
SMALL = "small"
|
| 108 |
+
MEDIUM = "medium"
|
| 109 |
+
LARGE = "large"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@dataclass
|
| 113 |
+
class Volume:
|
| 114 |
+
"""
|
| 115 |
+
Describes a volume to mount in a Space or Job container.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
type (`str`):
|
| 119 |
+
Type of volume: `"bucket"`, `"model"`, `"dataset"`, or `"space"`.
|
| 120 |
+
source (`str`):
|
| 121 |
+
Source identifier, e.g. `"username/my-bucket"` or `"username/my-model"`.
|
| 122 |
+
mount_path (`str`):
|
| 123 |
+
Mount path inside the container, e.g. `"/data"`. Must start with `/`.
|
| 124 |
+
revision (`str` or `None`):
|
| 125 |
+
Git revision (only for repos, defaults to `"main"`).
|
| 126 |
+
read_only (`bool` or `None`):
|
| 127 |
+
Read-only mount. Forced `True` for repos, defaults to `False` for buckets.
|
| 128 |
+
path (`str` or `None`):
|
| 129 |
+
Subfolder prefix inside the bucket/repo to mount, e.g. `"path/to/dir"`.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
type: Literal["bucket", "model", "dataset", "space"]
|
| 133 |
+
source: str
|
| 134 |
+
mount_path: str
|
| 135 |
+
revision: str | None = None
|
| 136 |
+
read_only: bool | None = None
|
| 137 |
+
path: str | None = None
|
| 138 |
+
|
| 139 |
+
def __init__(self, **kwargs) -> None:
|
| 140 |
+
self.type = kwargs.get("type", "model")
|
| 141 |
+
self.source = kwargs["source"]
|
| 142 |
+
mount_path = kwargs.get("mountPath")
|
| 143 |
+
self.mount_path = mount_path if mount_path is not None else kwargs["mount_path"]
|
| 144 |
+
self.revision = kwargs.get("revision")
|
| 145 |
+
read_only = kwargs.get("readOnly")
|
| 146 |
+
self.read_only = read_only if read_only is not None else kwargs.get("read_only")
|
| 147 |
+
self.path = kwargs.get("path")
|
| 148 |
+
|
| 149 |
+
def to_dict(self) -> dict:
|
| 150 |
+
"""Serialize to the JSON payload expected by the Hub API."""
|
| 151 |
+
data: dict = {
|
| 152 |
+
"type": self.type,
|
| 153 |
+
"source": self.source,
|
| 154 |
+
"mountPath": self.mount_path,
|
| 155 |
+
}
|
| 156 |
+
if self.revision is not None:
|
| 157 |
+
data["revision"] = self.revision
|
| 158 |
+
if self.read_only is not None:
|
| 159 |
+
data["readOnly"] = self.read_only
|
| 160 |
+
if self.path is not None:
|
| 161 |
+
data["path"] = self.path
|
| 162 |
+
return data
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@dataclass
|
| 166 |
+
class SpaceHotReloading:
|
| 167 |
+
status: Literal["created", "canceled"]
|
| 168 |
+
replica_statuses: list[tuple[str, str]] # See _hot_reloading_types.ApiCreateReloadResponse.res.status
|
| 169 |
+
raw: dict
|
| 170 |
+
|
| 171 |
+
def __init__(self, data: dict) -> None:
|
| 172 |
+
self.status = data["status"]
|
| 173 |
+
self.replica_statuses = data["replicaStatuses"]
|
| 174 |
+
self.raw = data
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@dataclass
|
| 178 |
+
class SpaceRuntime:
|
| 179 |
+
"""
|
| 180 |
+
Contains information about the current runtime of a Space.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
stage (`str`):
|
| 184 |
+
Current stage of the space. Example: RUNNING.
|
| 185 |
+
hardware (`str` or `None`):
|
| 186 |
+
Current hardware of the space. Example: "cpu-basic". Can be `None` if Space
|
| 187 |
+
is `BUILDING` for the first time.
|
| 188 |
+
requested_hardware (`str` or `None`):
|
| 189 |
+
Requested hardware. Can be different from `hardware` especially if the request
|
| 190 |
+
has just been made. Example: "t4-medium". Can be `None` if no hardware has
|
| 191 |
+
been requested yet.
|
| 192 |
+
sleep_time (`int` or `None`):
|
| 193 |
+
Number of seconds the Space will be kept alive after the last request. By default (if value is `None`), the
|
| 194 |
+
Space will never go to sleep if it's running on an upgraded hardware, while it will go to sleep after 48
|
| 195 |
+
hours on a free 'cpu-basic' hardware. For more details, see https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
|
| 196 |
+
volumes (`list[Volume]` or `None`):
|
| 197 |
+
List of volumes mounted in the Space. Each volume is a [`Volume`] object describing its type, source,
|
| 198 |
+
mount path, and optional settings. `None` if no volumes are attached.
|
| 199 |
+
raw (`dict`):
|
| 200 |
+
Raw response from the server. Contains more information about the Space
|
| 201 |
+
runtime like number of replicas, number of cpu, memory size,...
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
stage: SpaceStage
|
| 205 |
+
hardware: SpaceHardware | None
|
| 206 |
+
requested_hardware: SpaceHardware | None
|
| 207 |
+
sleep_time: int | None
|
| 208 |
+
storage: SpaceStorage | None
|
| 209 |
+
hot_reloading: SpaceHotReloading | None
|
| 210 |
+
volumes: list[Volume] | None
|
| 211 |
+
raw: dict
|
| 212 |
+
|
| 213 |
+
def __init__(self, data: dict) -> None:
|
| 214 |
+
self.stage = data["stage"]
|
| 215 |
+
self.hardware = data.get("hardware", {}).get("current")
|
| 216 |
+
self.requested_hardware = data.get("hardware", {}).get("requested")
|
| 217 |
+
self.sleep_time = data.get("gcTimeout")
|
| 218 |
+
self.storage = data.get("storage")
|
| 219 |
+
self.hot_reloading = SpaceHotReloading(raw_hr) if (raw_hr := data.get("hotReloading")) is not None else None
|
| 220 |
+
raw_volumes = data.get("volumes")
|
| 221 |
+
self.volumes = [Volume(**v) for v in raw_volumes] if raw_volumes is not None else None
|
| 222 |
+
self.raw = data
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@dataclass
|
| 226 |
+
class SpaceVariable:
|
| 227 |
+
"""
|
| 228 |
+
Contains information about the current variables of a Space.
|
| 229 |
+
|
| 230 |
+
Args:
|
| 231 |
+
key (`str`):
|
| 232 |
+
Variable key. Example: `"MODEL_REPO_ID"`
|
| 233 |
+
value (`str`):
|
| 234 |
+
Variable value. Example: `"the_model_repo_id"`.
|
| 235 |
+
description (`str` or None):
|
| 236 |
+
Description of the variable. Example: `"Model Repo ID of the implemented model"`.
|
| 237 |
+
updatedAt (`datetime` or None):
|
| 238 |
+
datetime of the last update of the variable (if the variable has been updated at least once).
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
key: str
|
| 242 |
+
value: str
|
| 243 |
+
description: str | None
|
| 244 |
+
updated_at: datetime | None
|
| 245 |
+
|
| 246 |
+
def __init__(self, key: str, values: dict) -> None:
|
| 247 |
+
self.key = key
|
| 248 |
+
self.value = values["value"]
|
| 249 |
+
self.description = values.get("description")
|
| 250 |
+
updated_at = values.get("updatedA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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains a logger to push training logs to the Hub, using Tensorboard."""
|
| 15 |
+
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
from ._commit_scheduler import CommitScheduler
|
| 19 |
+
from .errors import EntryNotFoundError
|
| 20 |
+
from .repocard import ModelCard
|
| 21 |
+
from .utils import experimental
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# Depending on user's setup, SummaryWriter can come either from 'tensorboardX'
|
| 25 |
+
# or from 'torch.utils.tensorboard'. Both are compatible so let's try to load
|
| 26 |
+
# from either of them.
|
| 27 |
+
try:
|
| 28 |
+
from tensorboardX import SummaryWriter as _RuntimeSummaryWriter
|
| 29 |
+
|
| 30 |
+
is_summary_writer_available = True
|
| 31 |
+
except ImportError:
|
| 32 |
+
try:
|
| 33 |
+
from torch.utils.tensorboard import SummaryWriter as _RuntimeSummaryWriter
|
| 34 |
+
|
| 35 |
+
is_summary_writer_available = True
|
| 36 |
+
except ImportError:
|
| 37 |
+
# Dummy class to avoid failing at import. Will raise on instance creation.
|
| 38 |
+
class _DummySummaryWriter:
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
_RuntimeSummaryWriter = _DummySummaryWriter # type: ignore[assignment]
|
| 42 |
+
is_summary_writer_available = False
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class HFSummaryWriter(_RuntimeSummaryWriter):
|
| 46 |
+
"""
|
| 47 |
+
Wrapper around the tensorboard's `SummaryWriter` to push training logs to the Hub.
|
| 48 |
+
|
| 49 |
+
Data is logged locally and then pushed to the Hub asynchronously. Pushing data to the Hub is done in a separate
|
| 50 |
+
thread to avoid blocking the training script. In particular, if the upload fails for any reason (e.g. a connection
|
| 51 |
+
issue), the main script will not be interrupted. Data is automatically pushed to the Hub every `commit_every`
|
| 52 |
+
minutes (default to every 5 minutes).
|
| 53 |
+
|
| 54 |
+
> [!WARNING]
|
| 55 |
+
> `HFSummaryWriter` is experimental. Its API is subject to change in the future without prior notice.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
repo_id (`str`):
|
| 59 |
+
The id of the repo to which the logs will be pushed.
|
| 60 |
+
logdir (`str`, *optional*):
|
| 61 |
+
The directory where the logs will be written. If not specified, a local directory will be created by the
|
| 62 |
+
underlying `SummaryWriter` object.
|
| 63 |
+
commit_every (`int` or `float`, *optional*):
|
| 64 |
+
The frequency (in minutes) at which the logs will be pushed to the Hub. Defaults to 5 minutes.
|
| 65 |
+
squash_history (`bool`, *optional*):
|
| 66 |
+
Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
|
| 67 |
+
useful to avoid degraded performances on the repo when it grows too large.
|
| 68 |
+
repo_type (`str`, *optional*):
|
| 69 |
+
The type of the repo to which the logs will be pushed. Defaults to "model".
|
| 70 |
+
repo_revision (`str`, *optional*):
|
| 71 |
+
The revision of the repo to which the logs will be pushed. Defaults to "main".
|
| 72 |
+
repo_private (`bool`, *optional*):
|
| 73 |
+
Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
|
| 74 |
+
path_in_repo (`str`, *optional*):
|
| 75 |
+
The path to the folder in the repo where the logs will be pushed. Defaults to "tensorboard/".
|
| 76 |
+
repo_allow_patterns (`list[str]` or `str`, *optional*):
|
| 77 |
+
A list of patterns to include in the upload. Defaults to `"*.tfevents.*"`. Check out the
|
| 78 |
+
[upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
|
| 79 |
+
repo_ignore_patterns (`list[str]` or `str`, *optional*):
|
| 80 |
+
A list of patterns to exclude in the upload. Check out the
|
| 81 |
+
[upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
|
| 82 |
+
token (`str`, *optional*):
|
| 83 |
+
Authentication token. Will default to the stored token. See https://huggingface.co/settings/token for more
|
| 84 |
+
details
|
| 85 |
+
kwargs:
|
| 86 |
+
Additional keyword arguments passed to `SummaryWriter`.
|
| 87 |
+
|
| 88 |
+
Examples:
|
| 89 |
+
```diff
|
| 90 |
+
# Taken from https://pytorch.org/docs/stable/tensorboard.html
|
| 91 |
+
- from torch.utils.tensorboard import SummaryWriter
|
| 92 |
+
+ from huggingface_hub import HFSummaryWriter
|
| 93 |
+
|
| 94 |
+
import numpy as np
|
| 95 |
+
|
| 96 |
+
- writer = SummaryWriter()
|
| 97 |
+
+ writer = HFSummaryWriter(repo_id="username/my-trained-model")
|
| 98 |
+
|
| 99 |
+
for n_iter in range(100):
|
| 100 |
+
writer.add_scalar('Loss/train', np.random.random(), n_iter)
|
| 101 |
+
writer.add_scalar('Loss/test', np.random.random(), n_iter)
|
| 102 |
+
writer.add_scalar('Accuracy/train', np.random.random(), n_iter)
|
| 103 |
+
writer.add_scalar('Accuracy/test', np.random.random(), n_iter)
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
```py
|
| 107 |
+
>>> from huggingface_hub import HFSummaryWriter
|
| 108 |
+
|
| 109 |
+
# Logs are automatically pushed every 15 minutes (5 by default) + when exiting the context manager
|
| 110 |
+
>>> with HFSummaryWriter(repo_id="test_hf_logger", commit_every=15) as logger:
|
| 111 |
+
... logger.add_scalar("a", 1)
|
| 112 |
+
... logger.add_scalar("b", 2)
|
| 113 |
+
```
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
@experimental
|
| 117 |
+
def __new__(cls, *args, **kwargs) -> "HFSummaryWriter":
|
| 118 |
+
if not is_summary_writer_available:
|
| 119 |
+
raise ImportError(
|
| 120 |
+
"You must have `tensorboard` installed to use `HFSummaryWriter`. Please run `pip install --upgrade"
|
| 121 |
+
" tensorboardX` first."
|
| 122 |
+
)
|
| 123 |
+
return super().__new__(cls)
|
| 124 |
+
|
| 125 |
+
def __init__(
|
| 126 |
+
self,
|
| 127 |
+
repo_id: str,
|
| 128 |
+
*,
|
| 129 |
+
logdir: str | None = None,
|
| 130 |
+
commit_every: int | float = 5,
|
| 131 |
+
squash_history: bool = False,
|
| 132 |
+
repo_type: str | None = None,
|
| 133 |
+
repo_revision: str | None = None,
|
| 134 |
+
repo_private: bool | None = None,
|
| 135 |
+
path_in_repo: str | None = "tensorboard",
|
| 136 |
+
repo_allow_patterns: list[str] | str | None = "*.tfevents.*",
|
| 137 |
+
repo_ignore_patterns: list[str] | str | None = None,
|
| 138 |
+
token: str | None = None,
|
| 139 |
+
**kwargs,
|
| 140 |
+
):
|
| 141 |
+
# Initialize SummaryWriter
|
| 142 |
+
super().__init__(logdir=logdir, **kwargs)
|
| 143 |
+
|
| 144 |
+
# Check logdir has been correctly initialized and fail early otherwise. In practice, SummaryWriter takes care of it.
|
| 145 |
+
if not isinstance(self.logdir, str):
|
| 146 |
+
raise ValueError(f"`self.logdir` must be a string. Got '{self.logdir}' of type {type(self.logdir)}.")
|
| 147 |
+
|
| 148 |
+
# Append logdir name to `path_in_repo`
|
| 149 |
+
if path_in_repo is None or path_in_repo == "":
|
| 150 |
+
path_in_repo = Path(self.logdir).name
|
| 151 |
+
else:
|
| 152 |
+
path_in_repo = path_in_repo.strip("/") + "/" + Path(self.logdir).name
|
| 153 |
+
|
| 154 |
+
# Initialize scheduler
|
| 155 |
+
self.scheduler = CommitScheduler(
|
| 156 |
+
folder_path=self.logdir,
|
| 157 |
+
path_in_repo=path_in_repo,
|
| 158 |
+
repo_id=repo_id,
|
| 159 |
+
repo_type=repo_type,
|
| 160 |
+
revision=repo_revision,
|
| 161 |
+
private=repo_private,
|
| 162 |
+
token=token,
|
| 163 |
+
allow_patterns=repo_allow_patterns,
|
| 164 |
+
ignore_patterns=repo_ignore_patterns,
|
| 165 |
+
every=commit_every,
|
| 166 |
+
squash_history=squash_history,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
# Exposing some high-level info at root level
|
| 170 |
+
self.repo_id = self.scheduler.repo_id
|
| 171 |
+
self.repo_type = self.scheduler.repo_type
|
| 172 |
+
self.repo_revision = self.scheduler.revision
|
| 173 |
+
|
| 174 |
+
# Add `hf-summary-writer` tag to the model card metadata
|
| 175 |
+
try:
|
| 176 |
+
card = ModelCard.load(repo_id_or_path=self.repo_id, repo_type=self.repo_type)
|
| 177 |
+
except EntryNotFoundError:
|
| 178 |
+
card = ModelCard("")
|
| 179 |
+
tags = card.data.get("tags", [])
|
| 180 |
+
if "hf-summary-writer" not in tags:
|
| 181 |
+
tags.append("hf-summary-writer")
|
| 182 |
+
card.data["tags"] = tags
|
| 183 |
+
card.push_to_hub(repo_id=self.repo_id, repo_type=self.repo_type)
|
| 184 |
+
|
| 185 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 186 |
+
"""Push to hub in a non-blocking way when exiting the logger's context manager."""
|
| 187 |
+
super().__exit__(exc_type, exc_val, exc_tb)
|
| 188 |
+
future = self.scheduler.trigger()
|
| 189 |
+
future.result()
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_upload_large_fol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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import enum
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
import queue
|
| 18 |
+
import shutil
|
| 19 |
+
import sys
|
| 20 |
+
import threading
|
| 21 |
+
import time
|
| 22 |
+
import traceback
|
| 23 |
+
from datetime import datetime
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from threading import Lock
|
| 26 |
+
from typing import TYPE_CHECKING, Any
|
| 27 |
+
from urllib.parse import quote
|
| 28 |
+
|
| 29 |
+
from ._commit_api import CommitOperationAdd, UploadInfo, _fetch_upload_modes
|
| 30 |
+
from ._local_folder import LocalUploadFileMetadata, LocalUploadFilePaths, get_local_upload_paths, read_upload_metadata
|
| 31 |
+
from .constants import DEFAULT_REVISION, REPO_TYPES
|
| 32 |
+
from .utils import DEFAULT_IGNORE_PATTERNS, _format_size, filter_repo_objects, tqdm
|
| 33 |
+
from .utils._runtime import is_xet_available
|
| 34 |
+
from .utils.sha import sha_fileobj
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if TYPE_CHECKING:
|
| 38 |
+
from .hf_api import HfApi
|
| 39 |
+
|
| 40 |
+
logger = logging.getLogger(__name__)
|
| 41 |
+
|
| 42 |
+
WAITING_TIME_IF_NO_TASKS = 10 # seconds
|
| 43 |
+
MAX_NB_FILES_FETCH_UPLOAD_MODE = 100
|
| 44 |
+
COMMIT_SIZE_SCALE: list[int] = [20, 50, 75, 100, 125, 200, 250, 400, 600, 1000]
|
| 45 |
+
|
| 46 |
+
UPLOAD_BATCH_SIZE_XET = 256 # Max 256 files per upload batch for XET-enabled repos
|
| 47 |
+
UPLOAD_BATCH_SIZE_LFS = 1 # Otherwise, batches of 1 for regular LFS upload
|
| 48 |
+
|
| 49 |
+
# Repository limits (from https://huggingface.co/docs/hub/repositories-recommendations)
|
| 50 |
+
MAX_FILES_PER_REPO = 100_000 # Recommended maximum number of files per repository
|
| 51 |
+
MAX_FILES_PER_FOLDER = 10_000 # Recommended maximum number of files per folder
|
| 52 |
+
MAX_FILE_SIZE_GB = 200 # Recommended maximum for individual file size (split larger files)
|
| 53 |
+
RECOMMENDED_FILE_SIZE_GB = 20 # Recommended maximum for individual file size
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _validate_upload_limits(paths_list: list[LocalUploadFilePaths]) -> None:
|
| 57 |
+
"""
|
| 58 |
+
Validate upload against repository limits and warn about potential issues.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
paths_list: List of file paths to be uploaded
|
| 62 |
+
|
| 63 |
+
Warns about:
|
| 64 |
+
- Too many files in the repository (>100k)
|
| 65 |
+
- Too many entries (files or subdirectories) in a single folder (>10k)
|
| 66 |
+
- Files exceeding size limits (>20GB recommended, >200GB maximum)
|
| 67 |
+
"""
|
| 68 |
+
logger.info("Running validation checks on files to upload...")
|
| 69 |
+
|
| 70 |
+
# Check 1: Total file count
|
| 71 |
+
if len(paths_list) > MAX_FILES_PER_REPO:
|
| 72 |
+
logger.warning(
|
| 73 |
+
f"You are about to upload {len(paths_list):,} files. "
|
| 74 |
+
f"This exceeds the recommended limit of {MAX_FILES_PER_REPO:,} files per repository.\n"
|
| 75 |
+
f"Consider:\n"
|
| 76 |
+
f" - Splitting your data into multiple repositories\n"
|
| 77 |
+
f" - Using fewer, larger files (e.g., parquet files)\n"
|
| 78 |
+
f" - See: https://huggingface.co/docs/hub/repositories-recommendations"
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# Check 2: Files and subdirectories per folder
|
| 82 |
+
# Track immediate children (files and subdirs) for each folder
|
| 83 |
+
from collections import defaultdict
|
| 84 |
+
|
| 85 |
+
entries_per_folder: dict[str, Any] = defaultdict(lambda: {"files": 0, "subdirs": set()})
|
| 86 |
+
|
| 87 |
+
for paths in paths_list:
|
| 88 |
+
path = Path(paths.path_in_repo)
|
| 89 |
+
parts = path.parts
|
| 90 |
+
|
| 91 |
+
# Count this file in its immediate parent directory
|
| 92 |
+
parent = str(path.parent) if str(path.parent) != "." else "."
|
| 93 |
+
entries_per_folder[parent]["files"] += 1
|
| 94 |
+
|
| 95 |
+
# Track immediate subdirectories for each parent folder
|
| 96 |
+
# Walk through the path components to track parent-child relationships
|
| 97 |
+
for i, child in enumerate(parts[:-1]):
|
| 98 |
+
parent = "." if i == 0 else "/".join(parts[:i])
|
| 99 |
+
entries_per_folder[parent]["subdirs"].add(child)
|
| 100 |
+
|
| 101 |
+
# Check limits for each folder
|
| 102 |
+
for folder, data in entries_per_folder.items():
|
| 103 |
+
file_count = data["files"]
|
| 104 |
+
subdir_count = len(data["subdirs"])
|
| 105 |
+
total_entries = file_count + subdir_count
|
| 106 |
+
|
| 107 |
+
if total_entries > MAX_FILES_PER_FOLDER:
|
| 108 |
+
folder_display = "root" if folder == "." else folder
|
| 109 |
+
logger.warning(
|
| 110 |
+
f"Folder '{folder_display}' contains {total_entries:,} entries "
|
| 111 |
+
f"({file_count:,} files and {subdir_count:,} subdirectories). "
|
| 112 |
+
f"This exceeds the recommended {MAX_FILES_PER_FOLDER:,} entries per folder.\n"
|
| 113 |
+
"Consider reorganising into sub-folders."
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
# Check 3: File sizes
|
| 117 |
+
large_files = []
|
| 118 |
+
very_large_files = []
|
| 119 |
+
|
| 120 |
+
for paths in paths_list:
|
| 121 |
+
size = paths.file_path.stat().st_size
|
| 122 |
+
size_gb = size / 1_000_000_000 # Use decimal GB as per Hub limits
|
| 123 |
+
|
| 124 |
+
if size_gb > MAX_FILE_SIZE_GB:
|
| 125 |
+
very_large_files.append((paths.path_in_repo, size_gb))
|
| 126 |
+
elif size_gb > RECOMMENDED_FILE_SIZE_GB:
|
| 127 |
+
large_files.append((paths.path_in_repo, size_gb))
|
| 128 |
+
|
| 129 |
+
# Warn about very large files (>200GB)
|
| 130 |
+
if very_large_files:
|
| 131 |
+
files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in very_large_files[:5])
|
| 132 |
+
more_str = f"\n ... and {len(very_large_files) - 5} more files" if len(very_large_files) > 5 else ""
|
| 133 |
+
logger.warning(
|
| 134 |
+
f"Found {len(very_large_files)} files exceeding the {MAX_FILE_SIZE_GB}GB recommended maximum:\n"
|
| 135 |
+
f" - {files_str}{more_str}\n"
|
| 136 |
+
f"Consider splitting these files into smaller chunks."
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# Warn about large files (>20GB)
|
| 140 |
+
if large_files:
|
| 141 |
+
files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in large_files[:5])
|
| 142 |
+
more_str = f"\n ... and {len(large_files) - 5} more files" if len(large_files) > 5 else ""
|
| 143 |
+
logger.warning(
|
| 144 |
+
f"Found {len(large_files)} files larger than {RECOMMENDED_FILE_SIZE_GB}GB (recommended limit):\n"
|
| 145 |
+
f" - {files_str}{more_str}\n"
|
| 146 |
+
f"Large files may slow down loading and processing."
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
logger.info("Validation checks complete.")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def upload_large_folder_internal(
|
| 153 |
+
api: "HfApi",
|
| 154 |
+
repo_id: str,
|
| 155 |
+
folder_path: str | Path,
|
| 156 |
+
*,
|
| 157 |
+
repo_type: str, # Repo type is required!
|
| 158 |
+
revision: str | None = None,
|
| 159 |
+
private: bool | None = None,
|
| 160 |
+
allow_patterns: list[str] | str | None = None,
|
| 161 |
+
ignore_patterns: list[str] | str | None = None,
|
| 162 |
+
num_workers: int | None = None,
|
| 163 |
+
print_report: bool = True,
|
| 164 |
+
print_report_every: int = 60,
|
| 165 |
+
):
|
| 166 |
+
"""Upload a large folder to the Hub in the most resilient way possible.
|
| 167 |
+
|
| 168 |
+
See [`HfApi.upload_large_folder`] for the full documentation.
|
| 169 |
+
"""
|
| 170 |
+
# 1. Check args and setup
|
| 171 |
+
if repo_type is None:
|
| 172 |
+
raise ValueError(
|
| 173 |
+
"For large uploads, `repo_type` is explicitly required. Please set it to `model`, `dataset` or `space`."
|
| 174 |
+
" If you are using the CLI, pass it as `--repo-type=model`."
|
| 175 |
+
)
|
| 176 |
+
if repo_type not in REPO_TYPES:
|
| 177 |
+
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
|
| 178 |
+
if revision is None:
|
| 179 |
+
revision = DEFAULT_REVISION
|
| 180 |
+
|
| 181 |
+
folder_path = Path(folder_path).expanduser().resolve()
|
| 182 |
+
if not folder_path.is_dir():
|
| 183 |
+
raise ValueError(f"Provided path: '{folder_path}' is not a directory")
|
| 184 |
+
|
| 185 |
+
if ignore_patterns is None:
|
| 186 |
+
ignore_patterns = []
|
| 187 |
+
elif isinstance(ignore_patterns, str):
|
| 188 |
+
ignore_patterns = [ignore_patterns]
|
| 189 |
+
ignore_patterns += DEFAULT_IGNORE_PATTERNS
|
| 190 |
+
|
| 191 |
+
if num_workers is None:
|
| 192 |
+
nb_cores = os.cpu_count() or 1
|
| 193 |
+
num_workers = max(nb_cores // 2, 1) # Use at most half of cpu cores
|
| 194 |
+
|
| 195 |
+
# 2. Create repo if missing
|
| 196 |
+
repo_url = api.create_repo(repo_id=repo_id, repo_type=repo_type, private=private, exist_ok=True)
|
| 197 |
+
logger.info(f"Repo created: {repo_url}")
|
| 198 |
+
repo_id = repo_url.repo_id
|
| 199 |
+
|
| 200 |
+
# Warn on too many commits
|
| 201 |
+
try:
|
| 202 |
+
commits = api.list_repo_commits(repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 203 |
+
commit_count = len(commits)
|
| 204 |
+
if commit_count > 500:
|
| 205 |
+
logger.warning(
|
| 206 |
+
f"\n{'=' * 80}\n"
|
| 207 |
+
f"WARNING: This repository has {commit_count} commits.\n"
|
| 208 |
+
f"Repositories with a large number of commits can experience performance issues.\n"
|
| 209 |
+
f"\n"
|
| 210 |
+
f"Consider squashing your commit history using `super_squash_history()`.\n"
|
| 211 |
+
"To do so, you need to stop this process, run the snippet below and restart the upload command."
|
| 212 |
+
f" from huggingface_hub import super_squash_history\n"
|
| 213 |
+
f" super_squash_history(repo_id='{repo_id}', repo_type='{repo_type}')\n"
|
| 214 |
+
f"\n"
|
| 215 |
+
f"Note: This is a non-revertible operation. See the documentation for more details:\n"
|
| 216 |
+
f"https://huggingface.co/docs/huggingface_hub/main/en/package_reference/hf_api#huggingface_hub.HfApi.super_squash_history\n"
|
| 217 |
+
f"{'=' * 80}\n"
|
| 218 |
+
)
|
| 219 |
+
except Exception as e:
|
| 220 |
+
# Don't fail the upload if we can't check commit count
|
| 221 |
+
logger.debug(f"Could not check commit count: {e}")
|
| 222 |
+
|
| 223 |
+
# 2.1 Check if xet is enabled to set batch file upload size
|
| 224 |
+
upload_batch_size = UPLOAD_BATCH_SIZE_XET if is_xet_available() else UPLOAD_BATCH_SIZE_LFS
|
| 225 |
+
|
| 226 |
+
# 3. List files to upload
|
| 227 |
+
filtered_paths_list = filter_repo_objects(
|
| 228 |
+
(path.relative_to(folder_path).as_posix() for path in folder_path.glob("**/*") if path.is_file()),
|
| 229 |
+
allow_patterns=allow_patterns,
|
| 230 |
+
ignore_patterns=ignore_patterns,
|
| 231 |
+
)
|
| 232 |
+
paths_list = [get_local_upload_paths(folder_path, relpath) for relpath in filtered_paths_list]
|
| 233 |
+
logger.info(f"Found {len(paths_list)} candidate files to upload")
|
| 234 |
+
|
| 235 |
+
# Validate upload against repository limits
|
| 236 |
+
_validate_upload_limits(paths_list)
|
| 237 |
+
|
| 238 |
+
logger.info("Starting upload...")
|
| 239 |
+
|
| 240 |
+
# Read metadata for each file
|
| 241 |
+
items = [
|
| 242 |
+
(paths, read_upload_metadata(folder_path, paths.path_in_repo))
|
| 243 |
+
for paths in tqdm(paths_list, desc="Recovering from metadata files")
|
| 244 |
+
]
|
| 245 |
+
|
| 246 |
+
# 4. Start workers
|
| 247 |
+
status = LargeUploadStatus(items, upload_batch_size)
|
| 248 |
+
threads = [
|
| 249 |
+
threading.Thread(
|
| 250 |
+
target=_worker_job,
|
| 251 |
+
kwargs={
|
| 252 |
+
"status": status,
|
| 253 |
+
"api": api,
|
| 254 |
+
"repo_id": repo_id,
|
| 255 |
+
"repo_type": repo_type,
|
| 256 |
+
"revision": revision,
|
| 257 |
+
},
|
| 258 |
+
)
|
| 259 |
+
for _ in range(num_workers)
|
| 260 |
+
]
|
| 261 |
+
|
| 262 |
+
for thread in threads:
|
| 263 |
+
thread.start()
|
| 264 |
+
|
| 265 |
+
# 5. Print regular reports
|
| 266 |
+
if print_report:
|
| 267 |
+
print("\n\n" + status.current_report())
|
| 268 |
+
last_report_ts = time.time()
|
| 269 |
+
while True:
|
| 270 |
+
time.sleep(1)
|
| 271 |
+
if time.time() - last_report_ts >= print_report_every:
|
| 272 |
+
if print_report:
|
| 273 |
+
_print_overwrite(status.current_report())
|
| 274 |
+
last_report_ts = time.time()
|
| 275 |
+
if status.is_done():
|
| 276 |
+
logger.info("Is done: exiting main loop")
|
| 277 |
+
break
|
| 278 |
+
|
| 279 |
+
for thread in threads:
|
| 280 |
+
thread.join()
|
| 281 |
+
|
| 282 |
+
logger.info(status.current_report())
|
| 283 |
+
logger.info("Upload is complete!")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
####################
|
| 287 |
+
# Logic to manage workers and synchronize tasks
|
| 288 |
+
####################
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class WorkerJob(enum.Enum):
|
| 292 |
+
SHA256 = enum.auto()
|
| 293 |
+
GET_UPLOAD_MODE = enum.auto()
|
| 294 |
+
PREUPLOAD_LFS = enum.auto()
|
| 295 |
+
COMMIT = enum.auto()
|
| 296 |
+
WAIT = enum.auto() # if no tasks are available but we don't want to exit
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
JOB_ITEM_T = tuple[LocalUploadFilePaths, LocalUploadFileMetadata]
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class LargeUploadStatus:
|
| 303 |
+
"""Contains information, queues and tasks for a large upload process."""
|
| 304 |
+
|
| 305 |
+
def __init__(self, items: list[JOB_ITEM_T], upload_batch_size: int = 1):
|
| 306 |
+
self.items = items
|
| 307 |
+
self.queue_sha256: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
|
| 308 |
+
self.queue_get_upload_mode: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
|
| 309 |
+
self.queue_preupload_lfs: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
|
| 310 |
+
self.queue_commit: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
|
| 311 |
+
self.lock = Lock()
|
| 312 |
+
|
| 313 |
+
self.nb_workers_sha256: int = 0
|
| 314 |
+
self.nb_workers_get_upload_mode: int = 0
|
| 315 |
+
self.nb_workers_preupload_lfs: int = 0
|
| 316 |
+
self.upload_batch_size: int = upload_batch_size
|
| 317 |
+
self.nb_workers_commit: int = 0
|
| 318 |
+
self.nb_workers_waiting: int = 0
|
| 319 |
+
self.last_commit_attempt: float | None = None
|
| 320 |
+
|
| 321 |
+
self._started_at = datetime.now()
|
| 322 |
+
self._chunk_idx: int = 1
|
| 323 |
+
self._chunk_lock: Lock = Lock()
|
| 324 |
+
|
| 325 |
+
# Setup queues
|
| 326 |
+
for item in self.items:
|
| 327 |
+
paths, metadata = item
|
| 328 |
+
if metadata.sha256 is None:
|
| 329 |
+
self.queue_sha256.put(item)
|
| 330 |
+
elif metadata.upload_mode is None:
|
| 331 |
+
self.queue_get_upload_mode.put(item)
|
| 332 |
+
elif metadata.upload_mode == "lfs" and not metadata.is_uploaded:
|
| 333 |
+
self.queue_preupload_lfs.put(item)
|
| 334 |
+
elif not metadata.is_committed:
|
| 335 |
+
self.queue_commit.put(item)
|
| 336 |
+
else:
|
| 337 |
+
logger.debug(f"Skipping file {paths.path_in_repo} (already uploaded and committed)")
|
| 338 |
+
|
| 339 |
+
def target_chunk(self) -> int:
|
| 340 |
+
with self._chunk_lock:
|
| 341 |
+
return COMMIT_SIZE_SCALE[self._chunk_idx]
|
| 342 |
+
|
| 343 |
+
def update_chunk(self, success: bool, nb_items: int, duration: float) -> None:
|
| 344 |
+
with self._chunk_lock:
|
| 345 |
+
if not success:
|
| 346 |
+
logger.warning(f"Failed to commit {nb_items} files at once. Will retry with less files in next batch.")
|
| 347 |
+
self._chunk_idx -= 1
|
| 348 |
+
elif nb_items >= COMMIT_SIZE_SCALE[self._chunk_idx] and duration < 40:
|
| 349 |
+
logger.info(f"Successfully committed {nb_items} at once. Increasing the limit for next batch.")
|
| 350 |
+
self._chunk_idx += 1
|
| 351 |
+
|
| 352 |
+
self._chunk_idx = max(0, min(self._chunk_idx, len(COMMIT_SIZE_SCALE) - 1))
|
| 353 |
+
|
| 354 |
+
def current_report(self) -> str:
|
| 355 |
+
"""Generate a report of the current status of the large upload."""
|
| 356 |
+
nb_hashed = 0
|
| 357 |
+
size_hashed = 0
|
| 358 |
+
nb_preuploaded = 0
|
| 359 |
+
nb_lfs = 0
|
| 360 |
+
nb_lfs_unsure = 0
|
| 361 |
+
size_preuploaded = 0
|
| 362 |
+
nb_committed = 0
|
| 363 |
+
size_committed = 0
|
| 364 |
+
total_size = 0
|
| 365 |
+
ignored_files = 0
|
| 366 |
+
total_files = 0
|
| 367 |
+
|
| 368 |
+
with self.lock:
|
| 369 |
+
for _, metadata in self.items:
|
| 370 |
+
if metadata.should_ignore:
|
| 371 |
+
ignored_files += 1
|
| 372 |
+
continue
|
| 373 |
+
total_size += metadata.size
|
| 374 |
+
total_files += 1
|
| 375 |
+
if metadata.sha256 is not None:
|
| 376 |
+
nb_hashed += 1
|
| 377 |
+
size_hashed += metadata.size
|
| 378 |
+
if metadata.upload_mode == "lfs":
|
| 379 |
+
nb_lfs += 1
|
| 380 |
+
if metadata.upload_mode is None:
|
| 381 |
+
nb_lfs_unsure += 1
|
| 382 |
+
if metadata.is_uploaded:
|
| 383 |
+
nb_preuploaded += 1
|
| 384 |
+
size_preuploaded += metadata.size
|
| 385 |
+
if metadata.is_committed:
|
| 386 |
+
nb_committed += 1
|
| 387 |
+
size_committed += metadata.size
|
| 388 |
+
total_size_str = _format_size(total_size)
|
| 389 |
+
|
| 390 |
+
now = datetime.now()
|
| 391 |
+
now_str = now.strftime("%Y-%m-%d %H:%M:%S")
|
| 392 |
+
elapsed = now - self._started_at
|
| 393 |
+
elapsed_str = str(elapsed).split(".")[0] # remove milliseconds
|
| 394 |
+
|
| 395 |
+
message = "\n" + "-" * 10
|
| 396 |
+
message += f" {now_str} ({elapsed_str}) "
|
| 397 |
+
message += "-" * 10 + "\n"
|
| 398 |
+
|
| 399 |
+
message += "Files: "
|
| 400 |
+
message += f"hashed {nb_hashed}/{total_files} ({_format_size(size_hashed)}/{total_size_str}) | "
|
| 401 |
+
message += f"pre-uploaded: {nb_preuploaded}/{nb_lfs} ({_format_size(size_preuploaded)}/{total_size_str})"
|
| 402 |
+
if nb_lfs_unsure > 0:
|
| 403 |
+
message += f" (+{nb_lfs_unsure} unsure)"
|
| 404 |
+
message += f" | committed: {nb_committed}/{total_files} ({_format_size(size_committed)}/{total_size_str})"
|
| 405 |
+
message += f" | ignored: {ignored_files}\n"
|
| 406 |
+
|
| 407 |
+
message += "Workers: "
|
| 408 |
+
message += f"hashing: {self.nb_workers_sha256} | "
|
| 409 |
+
message += f"get upload mode: {self.nb_workers_get_upload_mode} | "
|
| 410 |
+
message += f"pre-uploading: {self.nb_workers_preupload_lfs} | "
|
| 411 |
+
message += f"committing: {self.nb_workers_commit} | "
|
| 412 |
+
message += f"waiting: {self.nb_workers_waiting}\n"
|
| 413 |
+
message += "-" * 51
|
| 414 |
+
|
| 415 |
+
return message
|
| 416 |
+
|
| 417 |
+
def is_done(self) -> bool:
|
| 418 |
+
with self.lock:
|
| 419 |
+
return all(metadata.is_committed or metadata.should_ignore for _, metadata in self.items)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def _worker_job(
|
| 423 |
+
status: LargeUploadStatus,
|
| 424 |
+
api: "HfApi",
|
| 425 |
+
repo_id: str,
|
| 426 |
+
repo_type: str,
|
| 427 |
+
revision: str,
|
| 428 |
+
):
|
| 429 |
+
"""
|
| 430 |
+
Main process for a worker. The worker will perform tasks based on the priority list until all files are uploaded
|
| 431 |
+
and committed. If no tasks are available, the worker will wait for 10 seconds before checking again.
|
| 432 |
+
|
| 433 |
+
If a task fails for any reason, the item(s) are put back in the queue for another worker to pick up.
|
| 434 |
+
|
| 435 |
+
Read `upload_large_folder` docstring for more information on how tasks are prioritized.
|
| 436 |
+
"""
|
| 437 |
+
while True:
|
| 438 |
+
next_job: tuple[WorkerJob, list[JOB_ITEM_T]] | None = None
|
| 439 |
+
|
| 440 |
+
# Determine next task
|
| 441 |
+
next_job = _determine_next_job(status)
|
| 442 |
+
if next_job is None:
|
| 443 |
+
return
|
| 444 |
+
job, items = next_job
|
| 445 |
+
|
| 446 |
+
# Perform task
|
| 447 |
+
match job:
|
| 448 |
+
case WorkerJob.SHA256:
|
| 449 |
+
item = items[0] # single item
|
| 450 |
+
try:
|
| 451 |
+
_compute_sha256(item)
|
| 452 |
+
status.queue_get_upload_mode.put(item)
|
| 453 |
+
except KeyboardInterrupt:
|
| 454 |
+
raise
|
| 455 |
+
except Exception as e:
|
| 456 |
+
logger.error(f"Failed to compute sha256: {e}")
|
| 457 |
+
traceback.format_exc()
|
| 458 |
+
status.queue_sha256.put(item)
|
| 459 |
+
|
| 460 |
+
with status.lock:
|
| 461 |
+
status.nb_workers_sha256 -= 1
|
| 462 |
+
|
| 463 |
+
case WorkerJob.GET_UPLOAD_MODE:
|
| 464 |
+
try:
|
| 465 |
+
_get_upload_mode(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 466 |
+
except KeyboardInterrupt:
|
| 467 |
+
raise
|
| 468 |
+
except Exception as e:
|
| 469 |
+
logger.error(f"Failed to get upload mode: {e}")
|
| 470 |
+
traceback.format_exc()
|
| 471 |
+
|
| 472 |
+
# Items are either:
|
| 473 |
+
# - dropped (if should_ignore)
|
| 474 |
+
# - put in LFS queue (if LFS)
|
| 475 |
+
# - put in commit queue (if regular)
|
| 476 |
+
# - or put back (if error occurred).
|
| 477 |
+
for item in items:
|
| 478 |
+
_, metadata = item
|
| 479 |
+
if metadata.should_ignore:
|
| 480 |
+
continue
|
| 481 |
+
match metadata.upload_mode:
|
| 482 |
+
case "lfs":
|
| 483 |
+
status.queue_preupload_lfs.put(item)
|
| 484 |
+
case "regular":
|
| 485 |
+
status.queue_commit.put(item)
|
| 486 |
+
case _:
|
| 487 |
+
status.queue_get_upload_mode.put(item)
|
| 488 |
+
|
| 489 |
+
with status.lock:
|
| 490 |
+
status.nb_workers_get_upload_mode -= 1
|
| 491 |
+
|
| 492 |
+
case WorkerJob.PREUPLOAD_LFS:
|
| 493 |
+
try:
|
| 494 |
+
_preupload_lfs(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 495 |
+
for item in items:
|
| 496 |
+
status.queue_commit.put(item)
|
| 497 |
+
except KeyboardInterrupt:
|
| 498 |
+
raise
|
| 499 |
+
except Exception as e:
|
| 500 |
+
logger.error(f"Failed to preupload LFS: {e}")
|
| 501 |
+
traceback.format_exc()
|
| 502 |
+
for item in items:
|
| 503 |
+
status.queue_preupload_lfs.put(item)
|
| 504 |
+
|
| 505 |
+
with status.lock:
|
| 506 |
+
status.nb_workers_preupload_lfs -= 1
|
| 507 |
+
|
| 508 |
+
case WorkerJob.COMMIT:
|
| 509 |
+
start_ts = time.time()
|
| 510 |
+
success = True
|
| 511 |
+
try:
|
| 512 |
+
_commit(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 513 |
+
except KeyboardInterrupt:
|
| 514 |
+
raise
|
| 515 |
+
except Exception as e:
|
| 516 |
+
logger.error(f"Failed to commit: {e}")
|
| 517 |
+
traceback.format_exc()
|
| 518 |
+
for item in items:
|
| 519 |
+
status.queue_commit.put(item)
|
| 520 |
+
success = False
|
| 521 |
+
duration = time.time() - start_ts
|
| 522 |
+
status.update_chunk(success, len(items), duration)
|
| 523 |
+
with status.lock:
|
| 524 |
+
status.last_commit_attempt = time.time()
|
| 525 |
+
status.nb_workers_commit -= 1
|
| 526 |
+
|
| 527 |
+
case WorkerJob.WAIT:
|
| 528 |
+
time.sleep(WAITING_TIME_IF_NO_TASKS)
|
| 529 |
+
with status.lock:
|
| 530 |
+
status.nb_workers_waiting -= 1
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def _determine_next_job(status: LargeUploadStatus) -> tuple[WorkerJob, list[JOB_ITEM_T]] | None:
|
| 534 |
+
with status.lock:
|
| 535 |
+
# 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file)
|
| 536 |
+
if (
|
| 537 |
+
status.nb_workers_commit == 0
|
| 538 |
+
and status.queue_commit.qsize() > 0
|
| 539 |
+
and status.last_commit_attempt is not None
|
| 540 |
+
and time.time() - status.last_commit_attempt > 5 * 60
|
| 541 |
+
):
|
| 542 |
+
status.nb_workers_commit += 1
|
| 543 |
+
logger.debug("Job: commit (more than 5 minutes since last commit attempt)")
|
| 544 |
+
return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
|
| 545 |
+
|
| 546 |
+
# 2. Commit if at least 100 files are ready to commit
|
| 547 |
+
elif status.nb_workers_commit == 0 and status.queue_commit.qsize() >= 150:
|
| 548 |
+
status.nb_workers_commit += 1
|
| 549 |
+
logger.debug("Job: commit (>100 files ready)")
|
| 550 |
+
return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
|
| 551 |
+
|
| 552 |
+
# 3. Get upload mode if at least 100 files
|
| 553 |
+
elif status.queue_get_upload_mode.qsize() >= MAX_NB_FILES_FETCH_UPLOAD_MODE:
|
| 554 |
+
status.nb_workers_get_upload_mode += 1
|
| 555 |
+
logger.debug(f"Job: get upload mode (>{MAX_NB_FILES_FETCH_UPLOAD_MODE} files ready)")
|
| 556 |
+
return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
|
| 557 |
+
|
| 558 |
+
# 4. Preupload LFS file if at least `status.upload_batch_size` files and no worker is preuploading LFS
|
| 559 |
+
elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size and status.nb_workers_preupload_lfs == 0:
|
| 560 |
+
status.nb_workers_preupload_lfs += 1
|
| 561 |
+
logger.debug("Job: preupload LFS (no other worker preuploading LFS)")
|
| 562 |
+
return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
|
| 563 |
+
|
| 564 |
+
# 5. Compute sha256 if at least 1 file and no worker is computing sha256
|
| 565 |
+
elif status.queue_sha256.qsize() > 0 and status.nb_workers_sha256 == 0:
|
| 566 |
+
status.nb_workers_sha256 += 1
|
| 567 |
+
logger.debug("Job: sha256 (no other worker computing sha256)")
|
| 568 |
+
return (WorkerJob.SHA256, _get_one(status.queue_sha256))
|
| 569 |
+
|
| 570 |
+
# 6. Get upload mode if at least 1 file and no worker is getting upload mode
|
| 571 |
+
elif status.queue_get_upload_mode.qsize() > 0 and status.nb_workers_get_upload_mode == 0:
|
| 572 |
+
status.nb_workers_get_upload_mode += 1
|
| 573 |
+
logger.debug("Job: get upload mode (no other worker getting upload mode)")
|
| 574 |
+
return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
|
| 575 |
+
|
| 576 |
+
# 7. Preupload LFS file if at least `status.upload_batch_size` files
|
| 577 |
+
elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size:
|
| 578 |
+
status.nb_workers_preupload_lfs += 1
|
| 579 |
+
logger.debug("Job: preupload LFS")
|
| 580 |
+
return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
|
| 581 |
+
|
| 582 |
+
# 8. Compute sha256 if at least 1 file
|
| 583 |
+
elif status.queue_sha256.qsize() > 0:
|
| 584 |
+
status.nb_workers_sha256 += 1
|
| 585 |
+
logger.debug("Job: sha256")
|
| 586 |
+
return (WorkerJob.SHA256, _get_one(status.queue_sha256))
|
| 587 |
+
|
| 588 |
+
# 9. Get upload mode if at least 1 file
|
| 589 |
+
elif status.queue_get_upload_mode.qsize() > 0:
|
| 590 |
+
status.nb_workers_get_upload_mode += 1
|
| 591 |
+
logger.debug("Job: get upload mode")
|
| 592 |
+
return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
|
| 593 |
+
|
| 594 |
+
# 10. Preupload LFS file if at least 1 file
|
| 595 |
+
elif status.queue_preupload_lfs.qsize() > 0:
|
| 596 |
+
status.nb_workers_preupload_lfs += 1
|
| 597 |
+
logger.debug("Job: preupload LFS")
|
| 598 |
+
return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
|
| 599 |
+
|
| 600 |
+
# 11. Commit if at least 1 file and 1 min since last commit attempt
|
| 601 |
+
elif (
|
| 602 |
+
status.nb_workers_commit == 0
|
| 603 |
+
and status.queue_commit.qsize() > 0
|
| 604 |
+
and status.last_commit_attempt is not None
|
| 605 |
+
and time.time() - status.last_commit_attempt > 1 * 60
|
| 606 |
+
):
|
| 607 |
+
status.nb_workers_commit += 1
|
| 608 |
+
logger.debug("Job: commit (1 min since last commit attempt)")
|
| 609 |
+
return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
|
| 610 |
+
|
| 611 |
+
# 12. Commit if at least 1 file all other queues are empty and all workers are waiting
|
| 612 |
+
# e.g. when it's the last commit
|
| 613 |
+
elif (
|
| 614 |
+
status.nb_workers_commit == 0
|
| 615 |
+
and status.queue_commit.qsize() > 0
|
| 616 |
+
and status.queue_sha256.qsize() == 0
|
| 617 |
+
and status.queue_get_upload_mode.qsize() == 0
|
| 618 |
+
and status.queue_preupload_lfs.qsize() == 0
|
| 619 |
+
and status.nb_workers_sha256 == 0
|
| 620 |
+
and status.nb_workers_get_upload_mode == 0
|
| 621 |
+
and status.nb_workers_preupload_lfs == 0
|
| 622 |
+
):
|
| 623 |
+
status.nb_workers_commit += 1
|
| 624 |
+
logger.debug("Job: commit")
|
| 625 |
+
return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
|
| 626 |
+
|
| 627 |
+
# 13. If all queues are empty, exit
|
| 628 |
+
elif all(metadata.is_committed or metadata.should_ignore for _, metadata in status.items):
|
| 629 |
+
logger.info("All files have been processed! Exiting worker.")
|
| 630 |
+
return None
|
| 631 |
+
|
| 632 |
+
# 14. If no task is available, wait
|
| 633 |
+
else:
|
| 634 |
+
status.nb_workers_waiting += 1
|
| 635 |
+
logger.debug(f"No task available, waiting... ({WAITING_TIME_IF_NO_TASKS}s)")
|
| 636 |
+
return (WorkerJob.WAIT, [])
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
####################
|
| 640 |
+
# Atomic jobs (sha256, get_upload_mode, preupload_lfs, commit)
|
| 641 |
+
####################
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def _compute_sha256(item: JOB_ITEM_T) -> None:
|
| 645 |
+
"""Compute sha256 of a file and save it in metadata."""
|
| 646 |
+
paths, metadata = item
|
| 647 |
+
if metadata.sha256 is None:
|
| 648 |
+
with paths.file_path.open("rb") as f:
|
| 649 |
+
metadata.sha256 = sha_fileobj(f).hex()
|
| 650 |
+
metadata.save(paths)
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def _get_upload_mode(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
|
| 654 |
+
"""Get upload mode for each file and update metadata.
|
| 655 |
+
|
| 656 |
+
Also receive info if the file should be ignored.
|
| 657 |
+
"""
|
| 658 |
+
additions = [_build_hacky_operation(item) for item in items]
|
| 659 |
+
_fetch_upload_modes(
|
| 660 |
+
additions=additions,
|
| 661 |
+
repo_type=repo_type,
|
| 662 |
+
repo_id=repo_id,
|
| 663 |
+
headers=api._build_hf_headers(),
|
| 664 |
+
revision=quote(revision, safe=""),
|
| 665 |
+
endpoint=api.endpoint,
|
| 666 |
+
)
|
| 667 |
+
for item, addition in zip(items, additions):
|
| 668 |
+
paths, metadata = item
|
| 669 |
+
metadata.upload_mode = addition._upload_mode
|
| 670 |
+
metadata.should_ignore = addition._should_ignore
|
| 671 |
+
metadata.remote_oid = addition._remote_oid
|
| 672 |
+
metadata.save(paths)
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def _preupload_lfs(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
|
| 676 |
+
"""Preupload LFS files and update metadata."""
|
| 677 |
+
additions = [_build_hacky_operation(item) for item in items]
|
| 678 |
+
api.preupload_lfs_files(
|
| 679 |
+
repo_id=repo_id,
|
| 680 |
+
repo_type=repo_type,
|
| 681 |
+
revision=revision,
|
| 682 |
+
additions=additions,
|
| 683 |
+
)
|
| 684 |
+
|
| 685 |
+
for paths, metadata in items:
|
| 686 |
+
metadata.is_uploaded = True
|
| 687 |
+
metadata.save(paths)
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def _commit(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
|
| 691 |
+
"""Commit files to the repo."""
|
| 692 |
+
additions = [_build_hacky_operation(item) for item in items]
|
| 693 |
+
api.create_commit(
|
| 694 |
+
repo_id=repo_id,
|
| 695 |
+
repo_type=repo_type,
|
| 696 |
+
revision=revision,
|
| 697 |
+
operations=additions,
|
| 698 |
+
commit_message="Add files using upload-large-folder tool",
|
| 699 |
+
)
|
| 700 |
+
for paths, metadata in items:
|
| 701 |
+
metadata.is_committed = True
|
| 702 |
+
metadata.save(paths)
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
####################
|
| 706 |
+
# Hacks with CommitOperationAdd to bypass checks/sha256 calculation
|
| 707 |
+
####################
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
class HackyCommitOperationAdd(CommitOperationAdd):
|
| 711 |
+
def __post_init__(self) -> None:
|
| 712 |
+
if isinstance(self.path_or_fileobj, Path):
|
| 713 |
+
self.path_or_fileobj = str(self.path_or_fileobj)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def _build_hacky_operation(item: JOB_ITEM_T) -> HackyCommitOperationAdd:
|
| 717 |
+
paths, metadata = item
|
| 718 |
+
operation = HackyCommitOperationAdd(path_in_repo=paths.path_in_repo, path_or_fileobj=paths.file_path)
|
| 719 |
+
with paths.file_path.open("rb") as file:
|
| 720 |
+
sample = file.peek(512)[:512]
|
| 721 |
+
if metadata.sha256 is None:
|
| 722 |
+
raise ValueError("sha256 must have been computed by now!")
|
| 723 |
+
operation.upload_info = UploadInfo(sha256=bytes.fromhex(metadata.sha256), size=metadata.size, sample=sample)
|
| 724 |
+
operation._upload_mode = metadata.upload_mode # type: ignore
|
| 725 |
+
operation._should_ignore = metadata.should_ignore
|
| 726 |
+
operation._remote_oid = metadata.remote_oid
|
| 727 |
+
return operation
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
####################
|
| 731 |
+
# Misc helpers
|
| 732 |
+
####################
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
def _get_one(queue: "queue.Queue[JOB_ITEM_T]") -> list[JOB_ITEM_T]:
|
| 736 |
+
return [queue.get()]
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def _get_n(queue: "queue.Queue[JOB_ITEM_T]", n: int) -> list[JOB_ITEM_T]:
|
| 740 |
+
return [queue.get() for _ in range(min(queue.qsize(), n))]
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def _print_overwrite(report: str) -> None:
|
| 744 |
+
"""Print a report, overwriting the previous lines.
|
| 745 |
+
|
| 746 |
+
Since tqdm in using `sys.stderr` to (re-)write progress bars, we need to use `sys.stdout`
|
| 747 |
+
to print the report.
|
| 748 |
+
|
| 749 |
+
Note: works well only if no other process is writing to `sys.stdout`!
|
| 750 |
+
"""
|
| 751 |
+
report += "\n"
|
| 752 |
+
# Get terminal width
|
| 753 |
+
terminal_width = shutil.get_terminal_size().columns
|
| 754 |
+
|
| 755 |
+
# Count number of lines that should be cleared
|
| 756 |
+
nb_lines = sum(len(line) // terminal_width + 1 for line in report.splitlines())
|
| 757 |
+
|
| 758 |
+
# Clear previous lines based on the number of lines in the report
|
| 759 |
+
for _ in range(nb_lines):
|
| 760 |
+
sys.stdout.write("\r\033[K") # Clear line
|
| 761 |
+
sys.stdout.write("\033[F") # Move cursor up one line
|
| 762 |
+
|
| 763 |
+
# Print the new report, filling remaining space with whitespace
|
| 764 |
+
sys.stdout.write(report)
|
| 765 |
+
sys.stdout.write(" " * (terminal_width - len(report.splitlines()[-1])))
|
| 766 |
+
sys.stdout.flush()
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_webhooks_payload.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains data structures to parse the webhooks payload."""
|
| 15 |
+
|
| 16 |
+
from typing import Literal
|
| 17 |
+
|
| 18 |
+
from .utils import is_pydantic_available
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if is_pydantic_available():
|
| 22 |
+
from pydantic import BaseModel
|
| 23 |
+
else:
|
| 24 |
+
# Define a dummy BaseModel to avoid import errors when pydantic is not installed
|
| 25 |
+
# Import error will be raised when trying to use the class
|
| 26 |
+
|
| 27 |
+
class BaseModel: # type: ignore [no-redef]
|
| 28 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 29 |
+
raise ImportError(
|
| 30 |
+
"You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that"
|
| 31 |
+
" should be installed separately. Please run `pip install --upgrade pydantic` and retry."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# This is an adaptation of the ReportV3 interface implemented in moon-landing. V0, V1 and V2 have been ignored as they
|
| 36 |
+
# are not in used anymore. To keep in sync when format is updated in
|
| 37 |
+
# https://github.com/huggingface/moon-landing/blob/main/server/lib/HFWebhooks.ts (internal link).
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
WebhookEvent_T = Literal[
|
| 41 |
+
"create",
|
| 42 |
+
"delete",
|
| 43 |
+
"move",
|
| 44 |
+
"update",
|
| 45 |
+
]
|
| 46 |
+
RepoChangeEvent_T = Literal[
|
| 47 |
+
"add",
|
| 48 |
+
"move",
|
| 49 |
+
"remove",
|
| 50 |
+
"update",
|
| 51 |
+
]
|
| 52 |
+
RepoType_T = Literal[
|
| 53 |
+
"dataset",
|
| 54 |
+
"model",
|
| 55 |
+
"space",
|
| 56 |
+
]
|
| 57 |
+
DiscussionStatus_T = Literal[
|
| 58 |
+
"closed",
|
| 59 |
+
"draft",
|
| 60 |
+
"open",
|
| 61 |
+
"merged",
|
| 62 |
+
]
|
| 63 |
+
SupportedWebhookVersion = Literal[3]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class ObjectId(BaseModel):
|
| 67 |
+
id: str
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class WebhookPayloadUrl(BaseModel):
|
| 71 |
+
web: str
|
| 72 |
+
api: str | None = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class WebhookPayloadMovedTo(BaseModel):
|
| 76 |
+
name: str
|
| 77 |
+
owner: ObjectId
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class WebhookPayloadWebhook(ObjectId):
|
| 81 |
+
version: SupportedWebhookVersion
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class WebhookPayloadEvent(BaseModel):
|
| 85 |
+
action: WebhookEvent_T
|
| 86 |
+
scope: str
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class WebhookPayloadDiscussionChanges(BaseModel):
|
| 90 |
+
base: str
|
| 91 |
+
mergeCommitId: str | None = None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class WebhookPayloadComment(ObjectId):
|
| 95 |
+
author: ObjectId
|
| 96 |
+
hidden: bool
|
| 97 |
+
content: str | None = None
|
| 98 |
+
url: WebhookPayloadUrl
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class WebhookPayloadDiscussion(ObjectId):
|
| 102 |
+
num: int
|
| 103 |
+
author: ObjectId
|
| 104 |
+
url: WebhookPayloadUrl
|
| 105 |
+
title: str
|
| 106 |
+
isPullRequest: bool
|
| 107 |
+
status: DiscussionStatus_T
|
| 108 |
+
changes: WebhookPayloadDiscussionChanges | None = None
|
| 109 |
+
pinned: bool | None = None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class WebhookPayloadRepo(ObjectId):
|
| 113 |
+
owner: ObjectId
|
| 114 |
+
head_sha: str | None = None
|
| 115 |
+
name: str
|
| 116 |
+
private: bool
|
| 117 |
+
subdomain: str | None = None
|
| 118 |
+
tags: list[str] | None = None
|
| 119 |
+
type: Literal["dataset", "model", "space"]
|
| 120 |
+
url: WebhookPayloadUrl
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class WebhookPayloadUpdatedRef(BaseModel):
|
| 124 |
+
ref: str
|
| 125 |
+
oldSha: str | None = None
|
| 126 |
+
newSha: str | None = None
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class WebhookPayload(BaseModel):
|
| 130 |
+
event: WebhookPayloadEvent
|
| 131 |
+
repo: WebhookPayloadRepo
|
| 132 |
+
discussion: WebhookPayloadDiscussion | None = None
|
| 133 |
+
comment: WebhookPayloadComment | None = None
|
| 134 |
+
webhook: WebhookPayloadWebhook
|
| 135 |
+
movedTo: WebhookPayloadMovedTo | None = None
|
| 136 |
+
updatedRefs: list[WebhookPayloadUpdatedRef] | None = None
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/_webhooks_server.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains `WebhooksServer` and `webhook_endpoint` to create a webhook server easily."""
|
| 15 |
+
|
| 16 |
+
import atexit
|
| 17 |
+
import inspect
|
| 18 |
+
import os
|
| 19 |
+
from collections.abc import Callable
|
| 20 |
+
from functools import wraps
|
| 21 |
+
from typing import TYPE_CHECKING, Any, Optional
|
| 22 |
+
|
| 23 |
+
from .utils import experimental, is_fastapi_available, is_gradio_available
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
import gradio as gr
|
| 28 |
+
from fastapi import Request
|
| 29 |
+
|
| 30 |
+
if is_fastapi_available():
|
| 31 |
+
from fastapi import FastAPI, Request
|
| 32 |
+
from fastapi.responses import JSONResponse
|
| 33 |
+
else:
|
| 34 |
+
# Will fail at runtime if FastAPI is not available
|
| 35 |
+
FastAPI = Request = JSONResponse = None # type: ignore
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
_global_app: Optional["WebhooksServer"] = None
|
| 39 |
+
_is_local = os.environ.get("SPACE_ID") is None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@experimental
|
| 43 |
+
class WebhooksServer:
|
| 44 |
+
"""
|
| 45 |
+
The [`WebhooksServer`] class lets you create an instance of a Gradio app that can receive Huggingface webhooks.
|
| 46 |
+
These webhooks can be registered using the [`~WebhooksServer.add_webhook`] decorator. Webhook endpoints are added to
|
| 47 |
+
the app as a POST endpoint to the FastAPI router. Once all the webhooks are registered, the `launch` method has to be
|
| 48 |
+
called to start the app.
|
| 49 |
+
|
| 50 |
+
It is recommended to accept [`WebhookPayload`] as the first argument of the webhook function. It is a Pydantic
|
| 51 |
+
model that contains all the information about the webhook event. The data will be parsed automatically for you.
|
| 52 |
+
|
| 53 |
+
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your
|
| 54 |
+
WebhooksServer and deploy it on a Space.
|
| 55 |
+
|
| 56 |
+
> [!WARNING]
|
| 57 |
+
> `WebhooksServer` is experimental. Its API is subject to change in the future.
|
| 58 |
+
|
| 59 |
+
> [!WARNING]
|
| 60 |
+
> You must have `gradio` installed to use `WebhooksServer` (`pip install --upgrade gradio`).
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
ui (`gradio.Blocks`, optional):
|
| 64 |
+
A Gradio UI instance to be used as the Space landing page. If `None`, a UI displaying instructions
|
| 65 |
+
about the configured webhooks is created.
|
| 66 |
+
webhook_secret (`str`, optional):
|
| 67 |
+
A secret key to verify incoming webhook requests. You can set this value to any secret you want as long as
|
| 68 |
+
you also configure it in your [webhooks settings panel](https://huggingface.co/settings/webhooks). You
|
| 69 |
+
can also set this value as the `WEBHOOK_SECRET` environment variable. If no secret is provided, the
|
| 70 |
+
webhook endpoints are opened without any security.
|
| 71 |
+
|
| 72 |
+
Example:
|
| 73 |
+
|
| 74 |
+
```python
|
| 75 |
+
import gradio as gr
|
| 76 |
+
from huggingface_hub import WebhooksServer, WebhookPayload
|
| 77 |
+
|
| 78 |
+
with gr.Blocks() as ui:
|
| 79 |
+
...
|
| 80 |
+
|
| 81 |
+
app = WebhooksServer(ui=ui, webhook_secret="my_secret_key")
|
| 82 |
+
|
| 83 |
+
@app.add_webhook("/say_hello")
|
| 84 |
+
async def hello(payload: WebhookPayload):
|
| 85 |
+
return {"message": "hello"}
|
| 86 |
+
|
| 87 |
+
app.launch()
|
| 88 |
+
```
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def __new__(cls, *args, **kwargs) -> "WebhooksServer":
|
| 92 |
+
if not is_gradio_available():
|
| 93 |
+
raise ImportError(
|
| 94 |
+
"You must have `gradio` installed to use `WebhooksServer`. Please run `pip install --upgrade gradio`"
|
| 95 |
+
" first."
|
| 96 |
+
)
|
| 97 |
+
if not is_fastapi_available():
|
| 98 |
+
raise ImportError(
|
| 99 |
+
"You must have `fastapi` installed to use `WebhooksServer`. Please run `pip install --upgrade fastapi`"
|
| 100 |
+
" first."
|
| 101 |
+
)
|
| 102 |
+
return super().__new__(cls)
|
| 103 |
+
|
| 104 |
+
def __init__(
|
| 105 |
+
self,
|
| 106 |
+
ui: Optional["gr.Blocks"] = None,
|
| 107 |
+
webhook_secret: str | None = None,
|
| 108 |
+
) -> None:
|
| 109 |
+
self._ui = ui
|
| 110 |
+
|
| 111 |
+
self.webhook_secret = webhook_secret or os.getenv("WEBHOOK_SECRET")
|
| 112 |
+
self.registered_webhooks: dict[str, Callable] = {}
|
| 113 |
+
_warn_on_empty_secret(self.webhook_secret)
|
| 114 |
+
|
| 115 |
+
def add_webhook(self, path: str | None = None) -> Callable:
|
| 116 |
+
"""
|
| 117 |
+
Decorator to add a webhook to the [`WebhooksServer`] server.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
path (`str`, optional):
|
| 121 |
+
The URL path to register the webhook function. If not provided, the function name will be used as the
|
| 122 |
+
path. In any case, all webhooks are registered under `/webhooks`.
|
| 123 |
+
|
| 124 |
+
Raises:
|
| 125 |
+
ValueError: If the provided path is already registered as a webhook.
|
| 126 |
+
|
| 127 |
+
Example:
|
| 128 |
+
```python
|
| 129 |
+
from huggingface_hub import WebhooksServer, WebhookPayload
|
| 130 |
+
|
| 131 |
+
app = WebhooksServer()
|
| 132 |
+
|
| 133 |
+
@app.add_webhook
|
| 134 |
+
async def trigger_training(payload: WebhookPayload):
|
| 135 |
+
if payload.repo.type == "dataset" and payload.event.action == "update":
|
| 136 |
+
# Trigger a training job if a dataset is updated
|
| 137 |
+
...
|
| 138 |
+
|
| 139 |
+
app.launch()
|
| 140 |
+
```
|
| 141 |
+
"""
|
| 142 |
+
# Usage: directly as decorator. Example: `@app.add_webhook`
|
| 143 |
+
if callable(path):
|
| 144 |
+
# If path is a function, it means it was used as a decorator without arguments
|
| 145 |
+
return self.add_webhook()(path)
|
| 146 |
+
|
| 147 |
+
# Usage: provide a path. Example: `@app.add_webhook(...)`
|
| 148 |
+
@wraps(FastAPI.post)
|
| 149 |
+
def _inner_post(*args, **kwargs):
|
| 150 |
+
func = args[0]
|
| 151 |
+
abs_path = f"/webhooks/{(path or func.__name__).strip('/')}"
|
| 152 |
+
if abs_path in self.registered_webhooks:
|
| 153 |
+
raise ValueError(f"Webhook {abs_path} already exists.")
|
| 154 |
+
self.registered_webhooks[abs_path] = func
|
| 155 |
+
|
| 156 |
+
return _inner_post
|
| 157 |
+
|
| 158 |
+
def launch(self, prevent_thread_lock: bool = False, **launch_kwargs: Any) -> None:
|
| 159 |
+
"""Launch the Gradio app and register webhooks to the underlying FastAPI server.
|
| 160 |
+
|
| 161 |
+
Input parameters are forwarded to Gradio when launching the app.
|
| 162 |
+
"""
|
| 163 |
+
ui = self._ui or self._get_default_ui()
|
| 164 |
+
|
| 165 |
+
# Start Gradio App
|
| 166 |
+
# - as non-blocking so that webhooks can be added afterwards
|
| 167 |
+
# - as shared if launch locally (to debug webhooks)
|
| 168 |
+
launch_kwargs.setdefault("share", _is_local)
|
| 169 |
+
self.fastapi_app, _, _ = ui.launch(prevent_thread_lock=True, **launch_kwargs)
|
| 170 |
+
|
| 171 |
+
# Register webhooks to FastAPI app
|
| 172 |
+
for path, func in self.registered_webhooks.items():
|
| 173 |
+
# Add secret check if required
|
| 174 |
+
if self.webhook_secret is not None:
|
| 175 |
+
func = _wrap_webhook_to_check_secret(func, webhook_secret=self.webhook_secret)
|
| 176 |
+
|
| 177 |
+
# Add route to FastAPI app
|
| 178 |
+
self.fastapi_app.post(path)(func)
|
| 179 |
+
|
| 180 |
+
# Print instructions and block main thread
|
| 181 |
+
space_host = os.environ.get("SPACE_HOST")
|
| 182 |
+
url = "https://" + space_host if space_host is not None else (ui.share_url or ui.local_url)
|
| 183 |
+
if url is None:
|
| 184 |
+
raise ValueError("Cannot find the URL of the app. Please provide a valid `ui` or update `gradio` version.")
|
| 185 |
+
url = url.strip("/")
|
| 186 |
+
message = "\nWebhooks are correctly setup and ready to use:"
|
| 187 |
+
message += "\n" + "\n".join(f" - POST {url}{webhook}" for webhook in self.registered_webhooks)
|
| 188 |
+
message += "\nGo to https://huggingface.co/settings/webhooks to setup your webhooks."
|
| 189 |
+
print(message)
|
| 190 |
+
|
| 191 |
+
if not prevent_thread_lock:
|
| 192 |
+
ui.block_thread()
|
| 193 |
+
|
| 194 |
+
def _get_default_ui(self) -> "gr.Blocks":
|
| 195 |
+
"""Default UI if not provided (lists webhooks and provides basic instructions)."""
|
| 196 |
+
import gradio as gr
|
| 197 |
+
|
| 198 |
+
with gr.Blocks() as ui:
|
| 199 |
+
gr.Markdown("# This is an app to process 🤗 Webhooks")
|
| 200 |
+
gr.Markdown(
|
| 201 |
+
"Webhooks are a foundation for MLOps-related features. They allow you to listen for new changes on"
|
| 202 |
+
" specific repos or to all repos belonging to particular set of users/organizations (not just your"
|
| 203 |
+
" repos, but any repo). Check out this [guide](https://huggingface.co/docs/hub/webhooks) to get to"
|
| 204 |
+
" know more about webhooks on the Huggingface Hub."
|
| 205 |
+
)
|
| 206 |
+
gr.Markdown(
|
| 207 |
+
f"{len(self.registered_webhooks)} webhook(s) are registered:"
|
| 208 |
+
+ "\n\n"
|
| 209 |
+
+ "\n ".join(
|
| 210 |
+
f"- [{webhook_path}]({_get_webhook_doc_url(webhook.__name__, webhook_path)})"
|
| 211 |
+
for webhook_path, webhook in self.registered_webhooks.items()
|
| 212 |
+
)
|
| 213 |
+
)
|
| 214 |
+
gr.Markdown(
|
| 215 |
+
"Go to https://huggingface.co/settings/webhooks to setup your webhooks."
|
| 216 |
+
+ "\nYou app is running locally. Please look at the logs to check the full URL you need to set."
|
| 217 |
+
if _is_local
|
| 218 |
+
else (
|
| 219 |
+
"\nThis app is running on a Space. You can find the corresponding URL in the options menu"
|
| 220 |
+
" (top-right) > 'Embed the Space'. The URL looks like 'https://{username}-{repo_name}.hf.space'."
|
| 221 |
+
)
|
| 222 |
+
)
|
| 223 |
+
return ui
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@experimental
|
| 227 |
+
def webhook_endpoint(path: str | None = None) -> Callable:
|
| 228 |
+
"""Decorator to start a [`WebhooksServer`] and register the decorated function as a webhook endpoint.
|
| 229 |
+
|
| 230 |
+
This is a helper to get started quickly. If you need more flexibility (custom landing page or webhook secret),
|
| 231 |
+
you can use [`WebhooksServer`] directly. You can register multiple webhook endpoints (to the same server) by using
|
| 232 |
+
this decorator multiple times.
|
| 233 |
+
|
| 234 |
+
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your
|
| 235 |
+
server and deploy it on a Space.
|
| 236 |
+
|
| 237 |
+
> [!WARNING]
|
| 238 |
+
> `webhook_endpoint` is experimental. Its API is subject to change in the future.
|
| 239 |
+
|
| 240 |
+
> [!WARNING]
|
| 241 |
+
> You must have `gradio` installed to use `webhook_endpoint` (`pip install --upgrade gradio`).
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
path (`str`, optional):
|
| 245 |
+
The URL path to register the webhook function. If not provided, the function name will be used as the path.
|
| 246 |
+
In any case, all webhooks are registered under `/webhooks`.
|
| 247 |
+
|
| 248 |
+
Examples:
|
| 249 |
+
The default usage is to register a function as a webhook endpoint. The function name will be used as the path.
|
| 250 |
+
The server will be started automatically at exit (i.e. at the end of the script).
|
| 251 |
+
|
| 252 |
+
```python
|
| 253 |
+
from huggingface_hub import webhook_endpoint, WebhookPayload
|
| 254 |
+
|
| 255 |
+
@webhook_endpoint
|
| 256 |
+
async def trigger_training(payload: WebhookPayload):
|
| 257 |
+
if payload.repo.type == "dataset" and payload.event.action == "update":
|
| 258 |
+
# Trigger a training job if a dataset is updated
|
| 259 |
+
...
|
| 260 |
+
|
| 261 |
+
# Server is automatically started at the end of the script.
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
Advanced usage: register a function as a webhook endpoint and start the server manually. This is useful if you
|
| 265 |
+
are running it in a notebook.
|
| 266 |
+
|
| 267 |
+
```python
|
| 268 |
+
from huggingface_hub import webhook_endpoint, WebhookPayload
|
| 269 |
+
|
| 270 |
+
@webhook_endpoint
|
| 271 |
+
async def trigger_training(payload: WebhookPayload):
|
| 272 |
+
if payload.repo.type == "dataset" and payload.event.action == "update":
|
| 273 |
+
# Trigger a training job if a dataset is updated
|
| 274 |
+
...
|
| 275 |
+
|
| 276 |
+
# Start the server manually
|
| 277 |
+
trigger_training.launch()
|
| 278 |
+
```
|
| 279 |
+
"""
|
| 280 |
+
if callable(path):
|
| 281 |
+
# If path is a function, it means it was used as a decorator without arguments
|
| 282 |
+
return webhook_endpoint()(path)
|
| 283 |
+
|
| 284 |
+
@wraps(WebhooksServer.add_webhook)
|
| 285 |
+
def _inner(func: Callable) -> Callable:
|
| 286 |
+
app = _get_global_app()
|
| 287 |
+
app.add_webhook(path)(func)
|
| 288 |
+
if len(app.registered_webhooks) == 1:
|
| 289 |
+
# Register `app.launch` to run at exit (only once)
|
| 290 |
+
atexit.register(app.launch)
|
| 291 |
+
|
| 292 |
+
@wraps(app.launch)
|
| 293 |
+
def _launch_now():
|
| 294 |
+
# Run the app directly (without waiting atexit)
|
| 295 |
+
atexit.unregister(app.launch)
|
| 296 |
+
app.launch()
|
| 297 |
+
|
| 298 |
+
func.launch = _launch_now # type: ignore
|
| 299 |
+
return func
|
| 300 |
+
|
| 301 |
+
return _inner
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _get_global_app() -> WebhooksServer:
|
| 305 |
+
global _global_app
|
| 306 |
+
if _global_app is None:
|
| 307 |
+
_global_app = WebhooksServer()
|
| 308 |
+
return _global_app
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _warn_on_empty_secret(webhook_secret: str | None) -> None:
|
| 312 |
+
if webhook_secret is None:
|
| 313 |
+
print("Webhook secret is not defined. This means your webhook endpoints will be open to everyone.")
|
| 314 |
+
print(
|
| 315 |
+
"To add a secret, set `WEBHOOK_SECRET` as environment variable or pass it at initialization: "
|
| 316 |
+
"\n\t`app = WebhooksServer(webhook_secret='my_secret', ...)`"
|
| 317 |
+
)
|
| 318 |
+
print(
|
| 319 |
+
"For more details about webhook secrets, please refer to"
|
| 320 |
+
" https://huggingface.co/docs/hub/webhooks#webhook-secret."
|
| 321 |
+
)
|
| 322 |
+
else:
|
| 323 |
+
print("Webhook secret is correctly defined.")
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _get_webhook_doc_url(webhook_name: str, webhook_path: str) -> str:
|
| 327 |
+
"""Returns the anchor to a given webhook in the docs (experimental)"""
|
| 328 |
+
return "/docs#/default/" + webhook_name + webhook_path.replace("/", "_") + "_post"
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _wrap_webhook_to_check_secret(func: Callable, webhook_secret: str) -> Callable:
|
| 332 |
+
"""Wraps a webhook function to check the webhook secret before calling the function.
|
| 333 |
+
|
| 334 |
+
This is a hacky way to add the `request` parameter to the function signature. Since FastAPI based itself on route
|
| 335 |
+
parameters to inject the values to the function, we need to hack the function signature to retrieve the `Request`
|
| 336 |
+
object (and hence the headers). A far cleaner solution would be to use a middleware. However, since
|
| 337 |
+
`fastapi==0.90.1`, a middleware cannot be added once the app has started. And since the FastAPI app is started by
|
| 338 |
+
Gradio internals (and not by us), we cannot add a middleware.
|
| 339 |
+
|
| 340 |
+
This method is called only when a secret has been defined by the user. If a request is sent without the
|
| 341 |
+
"x-webhook-secret", the function will return a 401 error (unauthorized). If the header is sent but is incorrect,
|
| 342 |
+
the function will return a 403 error (forbidden).
|
| 343 |
+
|
| 344 |
+
Inspired by https://stackoverflow.com/a/33112180.
|
| 345 |
+
"""
|
| 346 |
+
initial_sig = inspect.signature(func)
|
| 347 |
+
|
| 348 |
+
@wraps(func)
|
| 349 |
+
async def _protected_func(request: Request, **kwargs):
|
| 350 |
+
request_secret = request.headers.get("x-webhook-secret")
|
| 351 |
+
if request_secret is None:
|
| 352 |
+
return JSONResponse({"error": "x-webhook-secret header not set."}, status_code=401)
|
| 353 |
+
if request_secret != webhook_secret:
|
| 354 |
+
return JSONResponse({"error": "Invalid webhook secret."}, status_code=403)
|
| 355 |
+
|
| 356 |
+
# Inject `request` in kwargs if required
|
| 357 |
+
if "request" in initial_sig.parameters:
|
| 358 |
+
kwargs["request"] = request
|
| 359 |
+
|
| 360 |
+
# Handle both sync and async routes
|
| 361 |
+
if inspect.iscoroutinefunction(func):
|
| 362 |
+
return await func(**kwargs)
|
| 363 |
+
else:
|
| 364 |
+
return func(**kwargs)
|
| 365 |
+
|
| 366 |
+
# Update signature to include request
|
| 367 |
+
if "request" not in initial_sig.parameters:
|
| 368 |
+
_protected_func.__signature__ = initial_sig.replace( # type: ignore
|
| 369 |
+
parameters=(
|
| 370 |
+
inspect.Parameter(name="request", kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Request),
|
| 371 |
+
)
|
| 372 |
+
+ tuple(initial_sig.parameters.values())
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
# Return protected route
|
| 376 |
+
return _protected_func
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/auth.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to authenticate to the Hugging Face Hub and interact with your repositories.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# login and save token locally.
|
| 18 |
+
hf auth login --token=hf_*** --add-to-git-credential
|
| 19 |
+
|
| 20 |
+
# switch between tokens
|
| 21 |
+
hf auth switch
|
| 22 |
+
|
| 23 |
+
# list all tokens
|
| 24 |
+
hf auth list
|
| 25 |
+
|
| 26 |
+
# logout from all tokens
|
| 27 |
+
hf auth logout
|
| 28 |
+
|
| 29 |
+
# check which account you are logged in as
|
| 30 |
+
hf auth whoami
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
from typing import Annotated
|
| 34 |
+
|
| 35 |
+
import typer
|
| 36 |
+
|
| 37 |
+
from huggingface_hub.constants import ENDPOINT
|
| 38 |
+
from huggingface_hub.hf_api import whoami
|
| 39 |
+
|
| 40 |
+
from .._login import auth_list, auth_switch, login, logout
|
| 41 |
+
from ..utils import get_stored_tokens, get_token, logging
|
| 42 |
+
from ._cli_utils import FormatWithAutoOpt, OutputFormatWithAuto, TokenOpt, typer_factory
|
| 43 |
+
from ._output import out
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
auth_cli = typer_factory(help="Manage authentication (login, logout, etc.).")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@auth_cli.command(
|
| 53 |
+
"login",
|
| 54 |
+
examples=[
|
| 55 |
+
"hf auth login",
|
| 56 |
+
"hf auth login --token $HF_TOKEN",
|
| 57 |
+
"hf auth login --token $HF_TOKEN --add-to-git-credential",
|
| 58 |
+
"hf auth login --force",
|
| 59 |
+
],
|
| 60 |
+
)
|
| 61 |
+
def auth_login(
|
| 62 |
+
token: TokenOpt = None,
|
| 63 |
+
add_to_git_credential: Annotated[
|
| 64 |
+
bool,
|
| 65 |
+
typer.Option(
|
| 66 |
+
help="Save to git credential helper. Useful only if you plan to run git commands directly.",
|
| 67 |
+
),
|
| 68 |
+
] = False,
|
| 69 |
+
force: Annotated[
|
| 70 |
+
bool,
|
| 71 |
+
typer.Option(
|
| 72 |
+
help="Force re-login even if already logged in.",
|
| 73 |
+
),
|
| 74 |
+
] = False,
|
| 75 |
+
) -> None:
|
| 76 |
+
"""Login using a token from huggingface.co/settings/tokens."""
|
| 77 |
+
login(token=token, add_to_git_credential=add_to_git_credential, skip_if_logged_in=not force)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@auth_cli.command(
|
| 81 |
+
"logout",
|
| 82 |
+
examples=["hf auth logout", "hf auth logout --token-name my-token"],
|
| 83 |
+
)
|
| 84 |
+
def auth_logout(
|
| 85 |
+
token_name: Annotated[
|
| 86 |
+
str | None,
|
| 87 |
+
typer.Option(help="Name of token to logout"),
|
| 88 |
+
] = None,
|
| 89 |
+
) -> None:
|
| 90 |
+
"""Logout from a specific token."""
|
| 91 |
+
logout(token_name=token_name)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _select_token_name() -> str | None:
|
| 95 |
+
token_names = list(get_stored_tokens().keys())
|
| 96 |
+
|
| 97 |
+
if not token_names:
|
| 98 |
+
logger.error("No stored tokens found. Please login first.")
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
print("Available stored tokens:")
|
| 102 |
+
for i, token_name in enumerate(token_names, 1):
|
| 103 |
+
print(f"{i}. {token_name}")
|
| 104 |
+
while True:
|
| 105 |
+
try:
|
| 106 |
+
choice = input("Enter the number of the token to switch to (or 'q' to quit): ")
|
| 107 |
+
if choice.lower() == "q":
|
| 108 |
+
return None
|
| 109 |
+
index = int(choice) - 1
|
| 110 |
+
if 0 <= index < len(token_names):
|
| 111 |
+
return token_names[index]
|
| 112 |
+
else:
|
| 113 |
+
print("Invalid selection. Please try again.")
|
| 114 |
+
except ValueError:
|
| 115 |
+
print("Invalid input. Please enter a number or 'q' to quit.")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@auth_cli.command(
|
| 119 |
+
"switch",
|
| 120 |
+
examples=["hf auth switch", "hf auth switch --token-name my-token"],
|
| 121 |
+
)
|
| 122 |
+
def auth_switch_cmd(
|
| 123 |
+
token_name: Annotated[
|
| 124 |
+
str | None,
|
| 125 |
+
typer.Option(
|
| 126 |
+
help="Name of the token to switch to",
|
| 127 |
+
),
|
| 128 |
+
] = None,
|
| 129 |
+
add_to_git_credential: Annotated[
|
| 130 |
+
bool,
|
| 131 |
+
typer.Option(
|
| 132 |
+
help="Save to git credential helper. Useful only if you plan to run git commands directly.",
|
| 133 |
+
),
|
| 134 |
+
] = False,
|
| 135 |
+
) -> None:
|
| 136 |
+
"""Switch between access tokens."""
|
| 137 |
+
if token_name is None:
|
| 138 |
+
token_name = _select_token_name()
|
| 139 |
+
if token_name is None:
|
| 140 |
+
print("No token name provided. Aborting.")
|
| 141 |
+
raise typer.Exit()
|
| 142 |
+
auth_switch(token_name, add_to_git_credential=add_to_git_credential)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@auth_cli.command("list | ls", examples=["hf auth list"])
|
| 146 |
+
def auth_list_cmd() -> None:
|
| 147 |
+
"""List all stored access tokens."""
|
| 148 |
+
auth_list()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@auth_cli.command("whoami", examples=["hf auth whoami", "hf auth whoami --format json"])
|
| 152 |
+
def auth_whoami(
|
| 153 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 154 |
+
) -> None:
|
| 155 |
+
"""Find out which huggingface.co account you are logged in as."""
|
| 156 |
+
|
| 157 |
+
token = get_token()
|
| 158 |
+
if token is None:
|
| 159 |
+
out.error("Not logged in")
|
| 160 |
+
raise typer.Exit(code=1)
|
| 161 |
+
|
| 162 |
+
info = whoami(token)
|
| 163 |
+
orgs = ",".join(org["name"] for org in info["orgs"]) or None
|
| 164 |
+
endpo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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with buckets via the CLI."""
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
from datetime import datetime
|
| 20 |
+
from typing import Annotated
|
| 21 |
+
|
| 22 |
+
import typer
|
| 23 |
+
|
| 24 |
+
from huggingface_hub import logging
|
| 25 |
+
from huggingface_hub._buckets import (
|
| 26 |
+
BUCKET_PREFIX,
|
| 27 |
+
BucketFile,
|
| 28 |
+
BucketFolder,
|
| 29 |
+
FilterMatcher,
|
| 30 |
+
_is_bucket_path,
|
| 31 |
+
_parse_bucket_path,
|
| 32 |
+
_split_bucket_id_and_prefix,
|
| 33 |
+
)
|
| 34 |
+
from huggingface_hub.utils import (
|
| 35 |
+
SoftTemporaryDirectory,
|
| 36 |
+
StatusLine,
|
| 37 |
+
are_progress_bars_disabled,
|
| 38 |
+
disable_progress_bars,
|
| 39 |
+
enable_progress_bars,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
from ._cli_utils import (
|
| 43 |
+
FormatOpt,
|
| 44 |
+
OutputFormat,
|
| 45 |
+
QuietOpt,
|
| 46 |
+
TokenOpt,
|
| 47 |
+
api_object_to_dict,
|
| 48 |
+
get_hf_api,
|
| 49 |
+
print_list_output,
|
| 50 |
+
typer_factory,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
logger = logging.get_logger(__name__)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
buckets_cli = typer_factory(help="Commands to interact with buckets.")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _is_hf_handle(path: str) -> bool:
|
| 61 |
+
return path.startswith("hf://")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _parse_bucket_argument(argument: str) -> tuple[str, str]:
|
| 65 |
+
"""Parse a bucket argument accepting both 'namespace/name(/prefix)' and 'hf://buckets/namespace/name(/prefix)'.
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
tuple: (bucket_id, prefix) where bucket_id is "namespace/bucket_name" and prefix may be empty string.
|
| 69 |
+
"""
|
| 70 |
+
if argument.startswith(BUCKET_PREFIX):
|
| 71 |
+
return _parse_bucket_path(argument)
|
| 72 |
+
try:
|
| 73 |
+
return _split_bucket_id_and_prefix(argument)
|
| 74 |
+
except ValueError:
|
| 75 |
+
raise ValueError(
|
| 76 |
+
f"Invalid bucket argument: {argument}. Must be in format namespace/bucket_name"
|
| 77 |
+
f" or {BUCKET_PREFIX}namespace/bucket_name"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _format_size(size: int | float, human_readable: bool = False) -> str:
|
| 82 |
+
"""Format a size in bytes."""
|
| 83 |
+
if not human_readable:
|
| 84 |
+
return str(size)
|
| 85 |
+
|
| 86 |
+
for unit in ["B", "KB", "MB", "GB", "TB"]:
|
| 87 |
+
if size < 1000:
|
| 88 |
+
if unit == "B":
|
| 89 |
+
return f"{size} {unit}"
|
| 90 |
+
return f"{size:.1f} {unit}"
|
| 91 |
+
size /= 1000
|
| 92 |
+
return f"{size:.1f} PB"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _format_mtime(mtime: datetime | None, human_readable: bool = False) -> str:
|
| 96 |
+
"""Format mtime datetime to a readable date string."""
|
| 97 |
+
if mtime is None:
|
| 98 |
+
return ""
|
| 99 |
+
if human_readable:
|
| 100 |
+
return mtime.strftime("%b %d %H:%M")
|
| 101 |
+
return mtime.strftime("%Y-%m-%d %H:%M:%S")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _build_tree(
|
| 105 |
+
items: list[BucketFile | BucketFolder],
|
| 106 |
+
human_readable: bool = False,
|
| 107 |
+
quiet: bool = False,
|
| 108 |
+
) -> list[str]:
|
| 109 |
+
"""Build a tree representation of files and directories.
|
| 110 |
+
|
| 111 |
+
Produces ASCII tree with size and date columns before the tree connector.
|
| 112 |
+
When quiet=True, only the tree structure is shown (no size/date).
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
items: List of BucketFile/BucketFolder items
|
| 116 |
+
human_readable: Whether to show human-readable sizes and short dates
|
| 117 |
+
quiet: If True, show only the tree structure without sizes/dates
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
List of formatted tree lines
|
| 121 |
+
"""
|
| 122 |
+
# Build a nested structure
|
| 123 |
+
tree: dict = {}
|
| 124 |
+
|
| 125 |
+
for item in items:
|
| 126 |
+
parts = item.path.split("/")
|
| 127 |
+
current = tree
|
| 128 |
+
for part in parts[:-1]:
|
| 129 |
+
if part not in current:
|
| 130 |
+
current[part] = {"__children__": {}}
|
| 131 |
+
current = current[part]["__children__"]
|
| 132 |
+
|
| 133 |
+
final_part = parts[-1]
|
| 134 |
+
if isinstance(item, BucketFolder):
|
| 135 |
+
if final_part not in current:
|
| 136 |
+
current[final_part] = {"__children__": {}}
|
| 137 |
+
else:
|
| 138 |
+
current[final_part] = {"__item__": item}
|
| 139 |
+
|
| 140 |
+
# Compute prefix width for alignment (size + date columns)
|
| 141 |
+
prefix_width = 0
|
| 142 |
+
max_size_width = 0
|
| 143 |
+
max_date_width = 0
|
| 144 |
+
if not quiet:
|
| 145 |
+
for item in items:
|
| 146 |
+
if isinstance(item, BucketFile):
|
| 147 |
+
size_str = _format_size(item.size, human_readable)
|
| 148 |
+
max_size_width = max(max_size_width, len(size_str))
|
| 149 |
+
date_str = _format_mtime(item.mtime, human_readable)
|
| 150 |
+
max_date_width = max(max_date_width, len(date_str))
|
| 151 |
+
if max_size_width > 0:
|
| 152 |
+
prefix_width = max_size_width + 2 + max_date_width
|
| 153 |
+
|
| 154 |
+
# Render tree
|
| 155 |
+
lines: list[str] = []
|
| 156 |
+
_render_tree(
|
| 157 |
+
tree,
|
| 158 |
+
lines,
|
| 159 |
+
"",
|
| 160 |
+
prefix_width=prefix_width,
|
| 161 |
+
max_size_width=max_size_width,
|
| 162 |
+
human_readable=human_readable,
|
| 163 |
+
)
|
| 164 |
+
return lines
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _render_tree(
|
| 168 |
+
node: dict,
|
| 169 |
+
lines: list[str],
|
| 170 |
+
indent: str,
|
| 171 |
+
prefix_width: int = 0,
|
| 172 |
+
max_size_width: int = 0,
|
| 173 |
+
human_readable: bool = False,
|
| 174 |
+
) -> None:
|
| 175 |
+
"""Recursively render a tree structure with size+date prefix."""
|
| 176 |
+
items = sorted(node.items())
|
| 177 |
+
for i, (name, value) in enumerate(items):
|
| 178 |
+
is_last = i == len(items) - 1
|
| 179 |
+
connector = "└── " if is_last else "├── "
|
| 180 |
+
|
| 181 |
+
is_dir = "__children__" in value
|
| 182 |
+
children = value.get("__children__", {})
|
| 183 |
+
|
| 184 |
+
if prefix_width > 0:
|
| 185 |
+
if is_dir:
|
| 186 |
+
prefix = " " * prefix_width
|
| 187 |
+
else:
|
| 188 |
+
item = value.get("__item__")
|
| 189 |
+
if item is not None:
|
| 190 |
+
size_str = _format_size(item.size, human_readable)
|
| 191 |
+
date_str = _format_mtime(item.mtime, human_readable)
|
| 192 |
+
prefix = f"{size_str:>{max_size_width}} {date_str}"
|
| 193 |
+
else:
|
| 194 |
+
prefix = " " * prefix_width
|
| 195 |
+
lines.append(f"{prefix} {indent}{connector}{name}{'/' if is_dir else ''}")
|
| 196 |
+
else:
|
| 197 |
+
lines.append(f"{indent}{connector}{name}{'/' if is_dir else ''}")
|
| 198 |
+
|
| 199 |
+
if children:
|
| 200 |
+
child_indent = indent + (" " if is_last else "│ ")
|
| 201 |
+
_render_tree(
|
| 202 |
+
children,
|
| 203 |
+
lines,
|
| 204 |
+
child_indent,
|
| 205 |
+
prefix_width=prefix_width,
|
| 206 |
+
max_size_width=max_size_width,
|
| 207 |
+
human_readable=human_readable,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@buckets_cli.command(
|
| 212 |
+
name="create",
|
| 213 |
+
examples=[
|
| 214 |
+
"hf buckets create my-bucket",
|
| 215 |
+
"hf buckets create user/my-bucket",
|
| 216 |
+
"hf buckets create hf://buckets/user/my-bucket",
|
| 217 |
+
"hf buckets create user/my-bucket --private",
|
| 218 |
+
"hf buckets create user/my-bucket --exist-ok",
|
| 219 |
+
],
|
| 220 |
+
)
|
| 221 |
+
def create(
|
| 222 |
+
bucket_id: Annotated[
|
| 223 |
+
str,
|
| 224 |
+
typer.Argument(
|
| 225 |
+
help="Bucket ID: bucket_name, namespace/bucket_name, or hf://buckets/namespace/bucket_name",
|
| 226 |
+
),
|
| 227 |
+
],
|
| 228 |
+
private: Annotated[
|
| 229 |
+
bool,
|
| 230 |
+
typer.Option(
|
| 231 |
+
"--private",
|
| 232 |
+
help="Create a private bucket.",
|
| 233 |
+
),
|
| 234 |
+
] = False,
|
| 235 |
+
exist_ok: Annotated[
|
| 236 |
+
bool,
|
| 237 |
+
typer.Option(
|
| 238 |
+
"--exist-ok",
|
| 239 |
+
help="Do not raise an error if the bucket already exists.",
|
| 240 |
+
),
|
| 241 |
+
] = False,
|
| 242 |
+
quiet: QuietOpt = False,
|
| 243 |
+
token: TokenOpt = None,
|
| 244 |
+
) -> None:
|
| 245 |
+
"""Create a new bucket."""
|
| 246 |
+
api = get_hf_api(token=token)
|
| 247 |
+
|
| 248 |
+
if bucket_id.startswith(BUCKET_PREFIX):
|
| 249 |
+
try:
|
| 250 |
+
parsed_id, prefix = _parse_bucket_argument(bucket_id)
|
| 251 |
+
except ValueError as e:
|
| 252 |
+
raise typer.BadParameter(str(e))
|
| 253 |
+
if prefix:
|
| 254 |
+
raise typer.BadParameter(
|
| 255 |
+
f"Cannot specify a prefix for bucket creation: {bucket_id}."
|
| 256 |
+
f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 257 |
+
)
|
| 258 |
+
bucket_id = parsed_id
|
| 259 |
+
|
| 260 |
+
bucket_url = api.create_bucket(
|
| 261 |
+
bucket_id,
|
| 262 |
+
private=private if private else None,
|
| 263 |
+
exist_ok=exist_ok,
|
| 264 |
+
)
|
| 265 |
+
if quiet:
|
| 266 |
+
print(bucket_url.handle)
|
| 267 |
+
else:
|
| 268 |
+
print(f"Bucket created: {bucket_url.url} (handle: {bucket_url.handle})")
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _is_bucket_id(argument: str) -> bool:
|
| 272 |
+
"""Check if argument is a bucket ID (namespace/name) vs just a namespace."""
|
| 273 |
+
if argument.startswith(BUCKET_PREFIX):
|
| 274 |
+
path = argument[len(BUCKET_PREFIX) :]
|
| 275 |
+
else:
|
| 276 |
+
path = argument
|
| 277 |
+
return "/" in path
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
@buckets_cli.command(
|
| 281 |
+
name="list | ls",
|
| 282 |
+
examples=[
|
| 283 |
+
"hf buckets list",
|
| 284 |
+
"hf buckets list huggingface",
|
| 285 |
+
"hf buckets list user/my-bucket",
|
| 286 |
+
"hf buckets list user/my-bucket -R",
|
| 287 |
+
"hf buckets list user/my-bucket -h",
|
| 288 |
+
"hf buckets list user/my-bucket --tree",
|
| 289 |
+
"hf buckets list user/my-bucket --tree -h",
|
| 290 |
+
"hf buckets list hf://buckets/user/my-bucket",
|
| 291 |
+
"hf buckets list user/my-bucket/sub -R",
|
| 292 |
+
],
|
| 293 |
+
)
|
| 294 |
+
def list_cmd(
|
| 295 |
+
argument: Annotated[
|
| 296 |
+
str | None,
|
| 297 |
+
typer.Argument(
|
| 298 |
+
help=(
|
| 299 |
+
"Namespace (user or org) to list buckets, or bucket ID"
|
| 300 |
+
" (namespace/bucket_name(/prefix) or hf://buckets/...) to list files."
|
| 301 |
+
),
|
| 302 |
+
),
|
| 303 |
+
] = None,
|
| 304 |
+
human_readable: Annotated[
|
| 305 |
+
bool,
|
| 306 |
+
typer.Option(
|
| 307 |
+
"--human-readable",
|
| 308 |
+
"-h",
|
| 309 |
+
help="Show sizes in human readable format.",
|
| 310 |
+
),
|
| 311 |
+
] = False,
|
| 312 |
+
as_tree: Annotated[
|
| 313 |
+
bool,
|
| 314 |
+
typer.Option(
|
| 315 |
+
"--tree",
|
| 316 |
+
help="List files in tree format (only for listing files).",
|
| 317 |
+
),
|
| 318 |
+
] = False,
|
| 319 |
+
recursive: Annotated[
|
| 320 |
+
bool,
|
| 321 |
+
typer.Option(
|
| 322 |
+
"--recursive",
|
| 323 |
+
"-R",
|
| 324 |
+
help="List files recursively (only for listing files).",
|
| 325 |
+
),
|
| 326 |
+
] = False,
|
| 327 |
+
format: FormatOpt = OutputFormat.table,
|
| 328 |
+
quiet: QuietOpt = False,
|
| 329 |
+
token: TokenOpt = None,
|
| 330 |
+
) -> None:
|
| 331 |
+
"""List buckets or files in a bucket.
|
| 332 |
+
|
| 333 |
+
When called with no argument or a namespace, lists buckets.
|
| 334 |
+
When called with a bucket ID (namespace/bucket_name), lists files in the bucket.
|
| 335 |
+
"""
|
| 336 |
+
# Determine mode: listing buckets or listing files
|
| 337 |
+
is_file_mode = argument is not None and _is_bucket_id(argument)
|
| 338 |
+
|
| 339 |
+
if is_file_mode:
|
| 340 |
+
_list_files(
|
| 341 |
+
argument=argument, # type: ignore
|
| 342 |
+
human_readable=human_readable,
|
| 343 |
+
as_tree=as_tree,
|
| 344 |
+
recursive=recursive,
|
| 345 |
+
format=format,
|
| 346 |
+
quiet=quiet,
|
| 347 |
+
token=token,
|
| 348 |
+
)
|
| 349 |
+
else:
|
| 350 |
+
_list_buckets(
|
| 351 |
+
namespace=argument,
|
| 352 |
+
human_readable=human_readable,
|
| 353 |
+
as_tree=as_tree,
|
| 354 |
+
recursive=recursive,
|
| 355 |
+
format=format,
|
| 356 |
+
quiet=quiet,
|
| 357 |
+
token=token,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _list_buckets(
|
| 362 |
+
namespace: str | None,
|
| 363 |
+
human_readable: bool,
|
| 364 |
+
as_tree: bool,
|
| 365 |
+
recursive: bool,
|
| 366 |
+
format: OutputFormat,
|
| 367 |
+
quiet: bool,
|
| 368 |
+
token: str | None,
|
| 369 |
+
) -> None:
|
| 370 |
+
"""List buckets in a namespace."""
|
| 371 |
+
# Validate incompatible flags
|
| 372 |
+
if as_tree:
|
| 373 |
+
raise typer.BadParameter("Cannot use --tree when listing buckets.")
|
| 374 |
+
if recursive:
|
| 375 |
+
raise typer.BadParameter("Cannot use --recursive when listing buckets.")
|
| 376 |
+
|
| 377 |
+
# Handle hf://buckets/namespace format
|
| 378 |
+
if namespace is not None and namespace.startswith(BUCKET_PREFIX):
|
| 379 |
+
namespace = namespace[len(BUCKET_PREFIX) :]
|
| 380 |
+
# Strip trailing slash if any
|
| 381 |
+
namespace = namespace.rstrip("/")
|
| 382 |
+
|
| 383 |
+
api = get_hf_api(token=token)
|
| 384 |
+
results = [api_object_to_dict(bucket) for bucket in api.list_buckets(namespace=namespace)]
|
| 385 |
+
|
| 386 |
+
if not results:
|
| 387 |
+
if not quiet and format != OutputFormat.json:
|
| 388 |
+
resolved_namespace = namespace if namespace is not None else api.whoami()["name"]
|
| 389 |
+
print(f"No buckets found under namespace '{resolved_namespace}'.")
|
| 390 |
+
return
|
| 391 |
+
|
| 392 |
+
headers = ["id", "private", "size", "total_files", "created_at"]
|
| 393 |
+
|
| 394 |
+
def row_fn(item: dict) -> list[str]:
|
| 395 |
+
from ._cli_utils import _format_cell
|
| 396 |
+
|
| 397 |
+
return [
|
| 398 |
+
_format_cell(item.get("id")),
|
| 399 |
+
_format_cell(item.get("private")),
|
| 400 |
+
_format_size(item.get("size", 0), human_readable=human_readable),
|
| 401 |
+
_format_cell(item.get("total_files")),
|
| 402 |
+
_format_cell(item.get("created_at")),
|
| 403 |
+
]
|
| 404 |
+
|
| 405 |
+
alignments = {"size": "right", "total_files": "right"}
|
| 406 |
+
print_list_output(results, format=format, quiet=quiet, headers=headers, row_fn=row_fn, alignments=alignments)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _list_files(
|
| 410 |
+
argument: str,
|
| 411 |
+
human_readable: bool,
|
| 412 |
+
as_tree: bool,
|
| 413 |
+
recursive: bool,
|
| 414 |
+
format: OutputFormat,
|
| 415 |
+
quiet: bool,
|
| 416 |
+
token: str | None,
|
| 417 |
+
) -> None:
|
| 418 |
+
"""List files in a bucket."""
|
| 419 |
+
# Validate incompatible flags
|
| 420 |
+
if as_tree and format == OutputFormat.json:
|
| 421 |
+
raise typer.BadParameter("Cannot use --tree with --format json.")
|
| 422 |
+
|
| 423 |
+
api = get_hf_api(token=token)
|
| 424 |
+
|
| 425 |
+
try:
|
| 426 |
+
bucket_id, prefix = _parse_bucket_argument(argument)
|
| 427 |
+
except ValueError as e:
|
| 428 |
+
raise typer.BadParameter(str(e))
|
| 429 |
+
|
| 430 |
+
# Fetch items from the bucket
|
| 431 |
+
items = list(
|
| 432 |
+
api.list_bucket_tree(
|
| 433 |
+
bucket_id,
|
| 434 |
+
prefix=prefix or None,
|
| 435 |
+
recursive=recursive,
|
| 436 |
+
)
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
if not items:
|
| 440 |
+
print("(empty)")
|
| 441 |
+
return
|
| 442 |
+
|
| 443 |
+
has_directories = any(isinstance(item, BucketFolder) for item in items)
|
| 444 |
+
|
| 445 |
+
if format == OutputFormat.json:
|
| 446 |
+
results = [api_object_to_dict(item) for item in items]
|
| 447 |
+
print(json.dumps(results, indent=2))
|
| 448 |
+
elif as_tree:
|
| 449 |
+
# Tree format with size+date prefix, or quiet for structure only
|
| 450 |
+
tree_lines = _build_tree(items, human_readable=human_readable, quiet=quiet)
|
| 451 |
+
for line in tree_lines:
|
| 452 |
+
print(line)
|
| 453 |
+
elif quiet:
|
| 454 |
+
for item in items:
|
| 455 |
+
if isinstance(item, BucketFolder):
|
| 456 |
+
print(f"{item.path}/")
|
| 457 |
+
else:
|
| 458 |
+
print(item.path)
|
| 459 |
+
else:
|
| 460 |
+
# Flat table format
|
| 461 |
+
for item in items:
|
| 462 |
+
if isinstance(item, BucketFolder):
|
| 463 |
+
mtime_str = _format_mtime(item.uploaded_at, human_readable)
|
| 464 |
+
print(f"{'':>12} {mtime_str:>19} {item.path}/")
|
| 465 |
+
else:
|
| 466 |
+
size_str = _format_size(item.size, human_readable)
|
| 467 |
+
mtime_str = _format_mtime(item.mtime, human_readable)
|
| 468 |
+
print(f"{size_str:>12} {mtime_str:>19} {item.path}")
|
| 469 |
+
|
| 470 |
+
if not recursive and has_directories:
|
| 471 |
+
StatusLine().done("Use -R to list files recursively.")
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
@buckets_cli.command(
|
| 475 |
+
name="info",
|
| 476 |
+
examples=[
|
| 477 |
+
"hf buckets info user/my-bucket",
|
| 478 |
+
"hf buckets info hf://buckets/user/my-bucket",
|
| 479 |
+
],
|
| 480 |
+
)
|
| 481 |
+
def info(
|
| 482 |
+
bucket_id: Annotated[
|
| 483 |
+
str,
|
| 484 |
+
typer.Argument(
|
| 485 |
+
help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
|
| 486 |
+
),
|
| 487 |
+
],
|
| 488 |
+
quiet: QuietOpt = False,
|
| 489 |
+
token: TokenOpt = None,
|
| 490 |
+
) -> None:
|
| 491 |
+
"""Get info about a bucket."""
|
| 492 |
+
api = get_hf_api(token=token)
|
| 493 |
+
|
| 494 |
+
try:
|
| 495 |
+
parsed_id, _ = _parse_bucket_argument(bucket_id)
|
| 496 |
+
except ValueError as e:
|
| 497 |
+
raise typer.BadParameter(str(e))
|
| 498 |
+
|
| 499 |
+
bucket = api.bucket_info(parsed_id)
|
| 500 |
+
if quiet:
|
| 501 |
+
print(bucket.id)
|
| 502 |
+
else:
|
| 503 |
+
print(json.dumps(api_object_to_dict(bucket), indent=2))
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
@buckets_cli.command(
|
| 507 |
+
name="delete",
|
| 508 |
+
examples=[
|
| 509 |
+
"hf buckets delete user/my-bucket",
|
| 510 |
+
"hf buckets delete hf://buckets/user/my-bucket",
|
| 511 |
+
"hf buckets delete user/my-bucket --yes",
|
| 512 |
+
"hf buckets delete user/my-bucket --missing-ok",
|
| 513 |
+
],
|
| 514 |
+
)
|
| 515 |
+
def delete(
|
| 516 |
+
bucket_id: Annotated[
|
| 517 |
+
str,
|
| 518 |
+
typer.Argument(
|
| 519 |
+
help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
|
| 520 |
+
),
|
| 521 |
+
],
|
| 522 |
+
yes: Annotated[
|
| 523 |
+
bool,
|
| 524 |
+
typer.Option(
|
| 525 |
+
"--yes",
|
| 526 |
+
"-y",
|
| 527 |
+
help="Skip confirmation prompt.",
|
| 528 |
+
),
|
| 529 |
+
] = False,
|
| 530 |
+
missing_ok: Annotated[
|
| 531 |
+
bool,
|
| 532 |
+
typer.Option(
|
| 533 |
+
"--missing-ok",
|
| 534 |
+
help="Do not raise an error if the bucket does not exist.",
|
| 535 |
+
),
|
| 536 |
+
] = False,
|
| 537 |
+
quiet: QuietOpt = False,
|
| 538 |
+
token: TokenOpt = None,
|
| 539 |
+
) -> None:
|
| 540 |
+
"""Delete a bucket.
|
| 541 |
+
|
| 542 |
+
This deletes the entire bucket and all its contents. Use `hf buckets rm` to remove individual files.
|
| 543 |
+
"""
|
| 544 |
+
if bucket_id.startswith(BUCKET_PREFIX):
|
| 545 |
+
try:
|
| 546 |
+
parsed_id, prefix = _parse_bucket_argument(bucket_id)
|
| 547 |
+
except ValueError as e:
|
| 548 |
+
raise typer.BadParameter(str(e))
|
| 549 |
+
if prefix:
|
| 550 |
+
raise typer.BadParameter(
|
| 551 |
+
f"Cannot specify a prefix for bucket deletion: {bucket_id}."
|
| 552 |
+
f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 553 |
+
)
|
| 554 |
+
bucket_id = parsed_id
|
| 555 |
+
elif "/" not in bucket_id:
|
| 556 |
+
raise typer.BadParameter(
|
| 557 |
+
f"Invalid bucket ID: {bucket_id}."
|
| 558 |
+
f" Must be in format namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
if not yes:
|
| 562 |
+
confirm = typer.confirm(f"Are you sure you want to delete bucket '{bucket_id}'?")
|
| 563 |
+
if not confirm:
|
| 564 |
+
print("Aborted.")
|
| 565 |
+
raise typer.Abort()
|
| 566 |
+
|
| 567 |
+
api = get_hf_api(token=token)
|
| 568 |
+
api.delete_bucket(bucket_id, missing_ok=missing_ok)
|
| 569 |
+
if quiet:
|
| 570 |
+
print(bucket_id)
|
| 571 |
+
else:
|
| 572 |
+
print(f"Bucket deleted: {bucket_id}")
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
@buckets_cli.command(
|
| 576 |
+
name="remove | rm",
|
| 577 |
+
examples=[
|
| 578 |
+
"hf buckets remove user/my-bucket/file.txt",
|
| 579 |
+
"hf buckets rm hf://buckets/user/my-bucket/file.txt",
|
| 580 |
+
"hf buckets rm user/my-bucket/logs/ --recursive",
|
| 581 |
+
'hf buckets rm user/my-bucket --recursive --include "*.tmp"',
|
| 582 |
+
"hf buckets rm user/my-bucket/data/ --recursive --dry-run",
|
| 583 |
+
],
|
| 584 |
+
)
|
| 585 |
+
def remove(
|
| 586 |
+
argument: Annotated[
|
| 587 |
+
str,
|
| 588 |
+
typer.Argument(
|
| 589 |
+
help=(
|
| 590 |
+
"Bucket path: namespace/bucket_name/path or hf://buckets/namespace/bucket_name/path."
|
| 591 |
+
" With --recursive, namespace/bucket_name is also accepted to target all files."
|
| 592 |
+
),
|
| 593 |
+
),
|
| 594 |
+
],
|
| 595 |
+
recursive: Annotated[
|
| 596 |
+
bool,
|
| 597 |
+
typer.Option(
|
| 598 |
+
"--recursive",
|
| 599 |
+
"-R",
|
| 600 |
+
help="Remove files recursively under the given prefix.",
|
| 601 |
+
),
|
| 602 |
+
] = False,
|
| 603 |
+
yes: Annotated[
|
| 604 |
+
bool,
|
| 605 |
+
typer.Option(
|
| 606 |
+
"--yes",
|
| 607 |
+
"-y",
|
| 608 |
+
help="Skip confirmation prompt.",
|
| 609 |
+
),
|
| 610 |
+
] = False,
|
| 611 |
+
dry_run: Annotated[
|
| 612 |
+
bool,
|
| 613 |
+
typer.Option(
|
| 614 |
+
"--dry-run",
|
| 615 |
+
help="Preview what would be deleted without actually deleting.",
|
| 616 |
+
),
|
| 617 |
+
] = False,
|
| 618 |
+
include: Annotated[
|
| 619 |
+
list[str] | None,
|
| 620 |
+
typer.Option(
|
| 621 |
+
help="Include only files matching pattern (can specify multiple). Requires --recursive.",
|
| 622 |
+
),
|
| 623 |
+
] = None,
|
| 624 |
+
exclude: Annotated[
|
| 625 |
+
list[str] | None,
|
| 626 |
+
typer.Option(
|
| 627 |
+
help="Exclude files matching pattern (can specify multiple). Requires --recursive.",
|
| 628 |
+
),
|
| 629 |
+
] = None,
|
| 630 |
+
quiet: QuietOpt = False,
|
| 631 |
+
token: TokenOpt = None,
|
| 632 |
+
) -> None:
|
| 633 |
+
"""Remove files from a bucket.
|
| 634 |
+
|
| 635 |
+
To delete an entire bucket, use `hf buckets delete` instead.
|
| 636 |
+
"""
|
| 637 |
+
try:
|
| 638 |
+
bucket_id, prefix = _parse_bucket_argument(argument)
|
| 639 |
+
except ValueError as e:
|
| 640 |
+
raise typer.BadParameter(str(e))
|
| 641 |
+
|
| 642 |
+
if prefix == "" and not recursive:
|
| 643 |
+
raise typer.BadParameter(
|
| 644 |
+
f"No file path specified. To remove files, provide a path"
|
| 645 |
+
f" (e.g. '{bucket_id}/FILE') or use --recursive to remove all files."
|
| 646 |
+
f" To delete the entire bucket, use `hf buckets delete {bucket_id}`."
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
if (include or exclude) and not recursive:
|
| 650 |
+
raise typer.BadParameter("--include and --exclude require --recursive.")
|
| 651 |
+
|
| 652 |
+
api = get_hf_api(token=token)
|
| 653 |
+
|
| 654 |
+
if recursive:
|
| 655 |
+
status = StatusLine(enabled=not quiet)
|
| 656 |
+
status.update("Listing files from remote")
|
| 657 |
+
|
| 658 |
+
all_files: list[BucketFile] = []
|
| 659 |
+
for item in api.list_bucket_tree(
|
| 660 |
+
bucket_id,
|
| 661 |
+
prefix=prefix.rstrip("/") or None,
|
| 662 |
+
recursive=True,
|
| 663 |
+
):
|
| 664 |
+
if isinstance(item, BucketFile):
|
| 665 |
+
all_files.append(item)
|
| 666 |
+
status.update(f"Listing files from remote ({len(all_files)} files)")
|
| 667 |
+
status.done(f"Listing files from remote ({len(all_files)} files)")
|
| 668 |
+
|
| 669 |
+
if include or exclude:
|
| 670 |
+
matcher = FilterMatcher(include_patterns=include, exclude_patterns=exclude)
|
| 671 |
+
matched_files = [f for f in all_files if matcher.matches(f.path)]
|
| 672 |
+
else:
|
| 673 |
+
matched_files = all_files
|
| 674 |
+
|
| 675 |
+
file_paths = [f.path for f in matched_files]
|
| 676 |
+
total_size = sum(f.size for f in matched_files)
|
| 677 |
+
size_str = _format_size(total_size, human_readable=True)
|
| 678 |
+
|
| 679 |
+
if not file_paths:
|
| 680 |
+
if not quiet:
|
| 681 |
+
print("No files to remove.")
|
| 682 |
+
return
|
| 683 |
+
|
| 684 |
+
count_label = f"{len(file_paths)} file(s) totaling {size_str}"
|
| 685 |
+
|
| 686 |
+
if not yes and not dry_run:
|
| 687 |
+
if not quiet:
|
| 688 |
+
for path in file_paths:
|
| 689 |
+
print(f" {path}")
|
| 690 |
+
confirm = typer.confirm(f"Remove {count_label} from '{bucket_id}'?")
|
| 691 |
+
if not confirm:
|
| 692 |
+
print("Aborted.")
|
| 693 |
+
raise typer.Abort()
|
| 694 |
+
|
| 695 |
+
if dry_run:
|
| 696 |
+
for path in file_paths:
|
| 697 |
+
print(f"delete: {BUCKET_PREFIX}{bucket_id}/{path}")
|
| 698 |
+
print(f"(dry run) {count_label} would be removed.")
|
| 699 |
+
return
|
| 700 |
+
|
| 701 |
+
api.batch_bucket_files(bucket_id, delete=file_paths)
|
| 702 |
+
if quiet:
|
| 703 |
+
for path in file_paths:
|
| 704 |
+
print(path)
|
| 705 |
+
else:
|
| 706 |
+
for path in file_paths:
|
| 707 |
+
print(f"delete: {BUCKET_PREFIX}{bucket_id}/{path}")
|
| 708 |
+
print(f"Removed {count_label} from '{bucket_id}'.")
|
| 709 |
+
|
| 710 |
+
else:
|
| 711 |
+
file_path = prefix.rstrip("/")
|
| 712 |
+
if not file_path:
|
| 713 |
+
raise typer.BadParameter("File path cannot be empty.")
|
| 714 |
+
|
| 715 |
+
if dry_run:
|
| 716 |
+
print(f"delete: {BUCKET_PREFIX}{bucket_id}/{file_path}")
|
| 717 |
+
print("(dry run) 1 file would be removed.")
|
| 718 |
+
return
|
| 719 |
+
|
| 720 |
+
if not yes:
|
| 721 |
+
confirm = typer.confirm(f"Remove '{file_path}' from '{bucket_id}'?")
|
| 722 |
+
if not confirm:
|
| 723 |
+
print("Aborted.")
|
| 724 |
+
raise typer.Abort()
|
| 725 |
+
|
| 726 |
+
api.batch_bucket_files(bucket_id, delete=[file_path])
|
| 727 |
+
if quiet:
|
| 728 |
+
print(file_path)
|
| 729 |
+
else:
|
| 730 |
+
print(f"delete: {BUCKET_PREFIX}{bucket_id}/{file_path}")
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
@buckets_cli.command(
|
| 734 |
+
name="move",
|
| 735 |
+
examples=[
|
| 736 |
+
"hf buckets move user/old-bucket user/new-bucket",
|
| 737 |
+
"hf buckets move user/my-bucket my-org/my-bucket",
|
| 738 |
+
"hf buckets move hf://buckets/user/old-bucket hf://buckets/user/new-bucket",
|
| 739 |
+
],
|
| 740 |
+
)
|
| 741 |
+
def move(
|
| 742 |
+
from_id: Annotated[
|
| 743 |
+
str,
|
| 744 |
+
typer.Argument(
|
| 745 |
+
help="Source bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
|
| 746 |
+
),
|
| 747 |
+
],
|
| 748 |
+
to_id: Annotated[
|
| 749 |
+
str,
|
| 750 |
+
typer.Argument(
|
| 751 |
+
help="Destination bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
|
| 752 |
+
),
|
| 753 |
+
],
|
| 754 |
+
token: TokenOpt = None,
|
| 755 |
+
) -> None:
|
| 756 |
+
"""Move (rename) a bucket to a new name or namespace."""
|
| 757 |
+
# Parse from_id
|
| 758 |
+
parsed_from_id, from_prefix = _parse_bucket_argument(from_id)
|
| 759 |
+
if from_prefix:
|
| 760 |
+
raise typer.BadParameter(
|
| 761 |
+
f"Cannot specify a prefix for bucket move: {from_id}."
|
| 762 |
+
f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
# Parse to_id
|
| 766 |
+
parsed_to_id, to_prefix = _parse_bucket_argument(to_id)
|
| 767 |
+
if to_prefix:
|
| 768 |
+
raise typer.BadParameter(
|
| 769 |
+
f"Cannot specify a prefix for bucket move: {to_id}."
|
| 770 |
+
f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
+
api = get_hf_api(token=token)
|
| 774 |
+
api.move_bucket(from_id=parsed_from_id, to_id=parsed_to_id)
|
| 775 |
+
print(f"Bucket moved: {parsed_from_id} -> {parsed_to_id}")
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
# =============================================================================
|
| 779 |
+
# Sync command
|
| 780 |
+
# =============================================================================
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
@buckets_cli.command(
|
| 784 |
+
name="sync",
|
| 785 |
+
examples=[
|
| 786 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket",
|
| 787 |
+
"hf buckets sync hf://buckets/user/my-bucket ./data",
|
| 788 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket --delete",
|
| 789 |
+
'hf buckets sync hf://buckets/user/my-bucket ./data --include "*.safetensors" --exclude "*.tmp"',
|
| 790 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket --plan sync-plan.jsonl",
|
| 791 |
+
"hf buckets sync --apply sync-plan.jsonl",
|
| 792 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket --dry-run",
|
| 793 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket --dry-run | jq .",
|
| 794 |
+
],
|
| 795 |
+
)
|
| 796 |
+
def sync(
|
| 797 |
+
source: Annotated[
|
| 798 |
+
str | None,
|
| 799 |
+
typer.Argument(
|
| 800 |
+
help="Source path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
|
| 801 |
+
),
|
| 802 |
+
] = None,
|
| 803 |
+
dest: Annotated[
|
| 804 |
+
str | None,
|
| 805 |
+
typer.Argument(
|
| 806 |
+
help="Destination path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
|
| 807 |
+
),
|
| 808 |
+
] = None,
|
| 809 |
+
delete: Annotated[
|
| 810 |
+
bool,
|
| 811 |
+
typer.Option(
|
| 812 |
+
help="Delete destination files not present in source.",
|
| 813 |
+
),
|
| 814 |
+
] = False,
|
| 815 |
+
ignore_times: Annotated[
|
| 816 |
+
bool,
|
| 817 |
+
typer.Option(
|
| 818 |
+
"--ignore-times",
|
| 819 |
+
help="Skip files only based on size, ignoring modification times.",
|
| 820 |
+
),
|
| 821 |
+
] = False,
|
| 822 |
+
ignore_sizes: Annotated[
|
| 823 |
+
bool,
|
| 824 |
+
typer.Option(
|
| 825 |
+
"--ignore-sizes",
|
| 826 |
+
help="Skip files only based on modification times, ignoring sizes.",
|
| 827 |
+
),
|
| 828 |
+
] = False,
|
| 829 |
+
plan: Annotated[
|
| 830 |
+
str | None,
|
| 831 |
+
typer.Option(
|
| 832 |
+
help="Save sync plan to JSONL file for review instead of executing.",
|
| 833 |
+
),
|
| 834 |
+
] = None,
|
| 835 |
+
apply: Annotated[
|
| 836 |
+
str | None,
|
| 837 |
+
typer.Option(
|
| 838 |
+
help="Apply a previously saved plan file.",
|
| 839 |
+
),
|
| 840 |
+
] = None,
|
| 841 |
+
dry_run: Annotated[
|
| 842 |
+
bool,
|
| 843 |
+
typer.Option(
|
| 844 |
+
"--dry-run",
|
| 845 |
+
help="Print sync plan to stdout as JSONL without executing.",
|
| 846 |
+
),
|
| 847 |
+
] = False,
|
| 848 |
+
include: Annotated[
|
| 849 |
+
list[str] | None,
|
| 850 |
+
typer.Option(
|
| 851 |
+
help="Include files matching pattern (can specify multiple).",
|
| 852 |
+
),
|
| 853 |
+
] = None,
|
| 854 |
+
exclude: Annotated[
|
| 855 |
+
list[str] | None,
|
| 856 |
+
typer.Option(
|
| 857 |
+
help="Exclude files matching pattern (can specify multiple).",
|
| 858 |
+
),
|
| 859 |
+
] = None,
|
| 860 |
+
filter_from: Annotated[
|
| 861 |
+
str | None,
|
| 862 |
+
typer.Option(
|
| 863 |
+
help="Read include/exclude patterns from file.",
|
| 864 |
+
),
|
| 865 |
+
] = None,
|
| 866 |
+
existing: Annotated[
|
| 867 |
+
bool,
|
| 868 |
+
typer.Option(
|
| 869 |
+
"--existing",
|
| 870 |
+
help="Skip creating new files on receiver (only update existing files).",
|
| 871 |
+
),
|
| 872 |
+
] = False,
|
| 873 |
+
ignore_existing: Annotated[
|
| 874 |
+
bool,
|
| 875 |
+
typer.Option(
|
| 876 |
+
"--ignore-existing",
|
| 877 |
+
help="Skip updating files that exist on receiver (only create new files).",
|
| 878 |
+
),
|
| 879 |
+
] = False,
|
| 880 |
+
verbose: Annotated[
|
| 881 |
+
bool,
|
| 882 |
+
typer.Option(
|
| 883 |
+
"--verbose",
|
| 884 |
+
"-v",
|
| 885 |
+
help="Show detailed logging with reasoning.",
|
| 886 |
+
),
|
| 887 |
+
] = False,
|
| 888 |
+
quiet: Annotated[
|
| 889 |
+
bool,
|
| 890 |
+
typer.Option(
|
| 891 |
+
"--quiet",
|
| 892 |
+
"-q",
|
| 893 |
+
help="Minimal output.",
|
| 894 |
+
),
|
| 895 |
+
] = False,
|
| 896 |
+
token: TokenOpt = None,
|
| 897 |
+
) -> None:
|
| 898 |
+
"""Sync files between local directory and a bucket."""
|
| 899 |
+
api = get_hf_api(token=token)
|
| 900 |
+
api.sync_bucket(
|
| 901 |
+
source=source,
|
| 902 |
+
dest=dest,
|
| 903 |
+
delete=delete,
|
| 904 |
+
ignore_times=ignore_times,
|
| 905 |
+
ignore_sizes=ignore_sizes,
|
| 906 |
+
existing=existing,
|
| 907 |
+
ignore_existing=ignore_existing,
|
| 908 |
+
include=include,
|
| 909 |
+
exclude=exclude,
|
| 910 |
+
filter_from=filter_from,
|
| 911 |
+
plan=plan,
|
| 912 |
+
apply=apply,
|
| 913 |
+
dry_run=dry_run,
|
| 914 |
+
verbose=verbose,
|
| 915 |
+
quiet=quiet,
|
| 916 |
+
)
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
# =============================================================================
|
| 920 |
+
# Cp command
|
| 921 |
+
# =============================================================================
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
@buckets_cli.command(
|
| 925 |
+
name="cp",
|
| 926 |
+
examples=[
|
| 927 |
+
"hf buckets cp hf://buckets/user/my-bucket/config.json",
|
| 928 |
+
"hf buckets cp hf://buckets/user/my-bucket/config.json ./data/",
|
| 929 |
+
"hf buckets cp hf://buckets/user/my-bucket/config.json my-config.json",
|
| 930 |
+
"hf buckets cp hf://buckets/user/my-bucket/config.json -",
|
| 931 |
+
"hf buckets cp my-config.json hf://buckets/user/my-bucket",
|
| 932 |
+
"hf buckets cp my-config.json hf://buckets/user/my-bucket/logs/",
|
| 933 |
+
"hf buckets cp my-config.json hf://buckets/user/my-bucket/remote-config.json",
|
| 934 |
+
"hf buckets cp - hf://buckets/user/my-bucket/config.json",
|
| 935 |
+
"hf buckets cp hf://buckets/user/my-bucket/logs/ hf://buckets/user/archive-bucket/logs/",
|
| 936 |
+
"hf buckets cp hf://datasets/user/my-dataset/processed/ hf://buckets/user/my-bucket/dataset/processed/",
|
| 937 |
+
],
|
| 938 |
+
)
|
| 939 |
+
def cp(
|
| 940 |
+
src: Annotated[str, typer.Argument(help="Source: local file, HF handle (hf://...), or - for stdin")],
|
| 941 |
+
dst: Annotated[
|
| 942 |
+
str | None, typer.Argument(help="Destination: local path, HF handle (hf://...), or - for stdout")
|
| 943 |
+
] = None,
|
| 944 |
+
quiet: QuietOpt = False,
|
| 945 |
+
token: TokenOpt = None,
|
| 946 |
+
) -> None:
|
| 947 |
+
"""Copy files to or from buckets."""
|
| 948 |
+
api = get_hf_api(token=token)
|
| 949 |
+
|
| 950 |
+
src_is_hf = _is_hf_handle(src)
|
| 951 |
+
dst_is_hf = dst is not None and _is_hf_handle(dst)
|
| 952 |
+
src_is_bucket = _is_bucket_path(src)
|
| 953 |
+
dst_is_bucket = dst is not None and _is_bucket_path(dst)
|
| 954 |
+
src_is_stdin = src == "-"
|
| 955 |
+
dst_is_stdout = dst == "-"
|
| 956 |
+
|
| 957 |
+
# Remote to remote copy
|
| 958 |
+
if src_is_hf and dst_is_hf:
|
| 959 |
+
if quiet:
|
| 960 |
+
disable_progress_bars()
|
| 961 |
+
try:
|
| 962 |
+
api.copy_files(src, dst) # type: ignore
|
| 963 |
+
except ValueError as e:
|
| 964 |
+
raise typer.BadParameter(str(e))
|
| 965 |
+
finally:
|
| 966 |
+
if quiet:
|
| 967 |
+
enable_progress_bars()
|
| 968 |
+
|
| 969 |
+
if not quiet:
|
| 970 |
+
print(f"Copied: {src} -> {dst}")
|
| 971 |
+
return
|
| 972 |
+
|
| 973 |
+
# Local to remote copy
|
| 974 |
+
# --- Validation ---
|
| 975 |
+
if not src_is_bucket and not dst_is_bucket and not src_is_stdin:
|
| 976 |
+
if dst is None:
|
| 977 |
+
raise typer.BadParameter("Missing destination. Provide a bucket path as DST.")
|
| 978 |
+
raise typer.BadParameter("One of SRC or DST must be a bucket path (hf://buckets/...).")
|
| 979 |
+
|
| 980 |
+
if src_is_stdin and not dst_is_bucket:
|
| 981 |
+
raise typer.BadParameter("Stdin upload requires a bucket destination.")
|
| 982 |
+
|
| 983 |
+
if src_is_stdin and dst_is_bucket:
|
| 984 |
+
_, prefix = _parse_bucket_path(dst) # type: ignore
|
| 985 |
+
if prefix == "" or prefix.endswith("/"):
|
| 986 |
+
raise typer.BadParameter("Stdin upload requires a full destination path including filename.")
|
| 987 |
+
|
| 988 |
+
if dst_is_stdout and not src_is_bucket:
|
| 989 |
+
raise typer.BadParameter("Cannot pipe to stdout for uploads.")
|
| 990 |
+
|
| 991 |
+
if not src_is_bucket and not src_is_stdin and os.path.isdir(src):
|
| 992 |
+
raise typer.BadParameter("Source must be a file, not a directory. Use `hf buckets sync` for directories.")
|
| 993 |
+
|
| 994 |
+
# --- Determine direction and execute ---
|
| 995 |
+
if src_is_bucket:
|
| 996 |
+
# Download: remote -> local or stdout
|
| 997 |
+
bucket_id, prefix = _parse_bucket_path(src)
|
| 998 |
+
if prefix == "" or prefix.endswith("/"):
|
| 999 |
+
raise typer.BadParameter("Source path must include a file name, not just a bucket or directory path.")
|
| 1000 |
+
filename = prefix.rsplit("/", 1)[-1]
|
| 1001 |
+
|
| 1002 |
+
if dst_is_stdout:
|
| 1003 |
+
# Download to stdout: always suppress progress bars to avoid polluting output
|
| 1004 |
+
# Only re-enable if they weren't already disabled by the caller
|
| 1005 |
+
pbar_was_disabled = are_progress_bars_disabled()
|
| 1006 |
+
if not pbar_was_disabled:
|
| 1007 |
+
disable_progress_bars()
|
| 1008 |
+
try:
|
| 1009 |
+
with SoftTemporaryDirectory() as tmp_dir:
|
| 1010 |
+
tmp_path = os.path.join(tmp_dir, filename)
|
| 1011 |
+
api.download_bucket_files(bucket_id, [(prefix, tmp_path)])
|
| 1012 |
+
with open(tmp_path, "rb") as f:
|
| 1013 |
+
while chunk := f.read(32_000_000): # 32MB chunks
|
| 1014 |
+
sys.stdout.buffer.write(chunk)
|
| 1015 |
+
finally:
|
| 1016 |
+
if not pbar_was_disabled:
|
| 1017 |
+
enable_progress_bars()
|
| 1018 |
+
else:
|
| 1019 |
+
# Download to file
|
| 1020 |
+
if dst is None:
|
| 1021 |
+
local_path = filename
|
| 1022 |
+
elif os.path.isdir(dst) or dst.endswith(os.sep) or dst.endswith("/"):
|
| 1023 |
+
local_path = os.path.join(dst, filename)
|
| 1024 |
+
else:
|
| 1025 |
+
local_path = dst
|
| 1026 |
+
|
| 1027 |
+
# Ensure parent directory exists
|
| 1028 |
+
parent_dir = os.path.dirname(local_path)
|
| 1029 |
+
if parent_dir:
|
| 1030 |
+
os.makedirs(parent_dir, exist_ok=True)
|
| 1031 |
+
|
| 1032 |
+
if quiet:
|
| 1033 |
+
disable_progress_bars()
|
| 1034 |
+
try:
|
| 1035 |
+
api.download_bucket_files(bucket_id, [(prefix, local_path)])
|
| 1036 |
+
finally:
|
| 1037 |
+
if quiet:
|
| 1038 |
+
enable_progress_bars()
|
| 1039 |
+
|
| 1040 |
+
if not quiet:
|
| 1041 |
+
print(f"Downloaded: {src} -> {local_path}")
|
| 1042 |
+
|
| 1043 |
+
elif src_is_stdin:
|
| 1044 |
+
# Upload from stdin
|
| 1045 |
+
bucket_id, remote_path = _parse_bucket_path(dst) # type: ignore
|
| 1046 |
+
data = sys.stdin.buffer.read()
|
| 1047 |
+
|
| 1048 |
+
if quiet:
|
| 1049 |
+
disable_progress_bars()
|
| 1050 |
+
try:
|
| 1051 |
+
api.batch_bucket_files(bucket_id, add=[(data, remote_path)])
|
| 1052 |
+
finally:
|
| 1053 |
+
if quiet:
|
| 1054 |
+
enable_progress_bars()
|
| 1055 |
+
|
| 1056 |
+
if not quiet:
|
| 1057 |
+
print(f"Uploaded: stdin -> {dst}")
|
| 1058 |
+
|
| 1059 |
+
else:
|
| 1060 |
+
# Upload from file
|
| 1061 |
+
if not os.path.isfile(src):
|
| 1062 |
+
raise typer.BadParameter(f"Source file not found: {src}")
|
| 1063 |
+
|
| 1064 |
+
bucket_id, prefix = _parse_bucket_path(dst) # type: ignore
|
| 1065 |
+
|
| 1066 |
+
if prefix == "":
|
| 1067 |
+
remote_path = os.path.basename(src)
|
| 1068 |
+
elif prefix.endswith("/"):
|
| 1069 |
+
remote_path = prefix + os.path.basename(src)
|
| 1070 |
+
else:
|
| 1071 |
+
remote_path = prefix
|
| 1072 |
+
|
| 1073 |
+
if quiet:
|
| 1074 |
+
disable_progress_bars()
|
| 1075 |
+
try:
|
| 1076 |
+
api.batch_bucket_files(bucket_id, add=[(src, remote_path)])
|
| 1077 |
+
finally:
|
| 1078 |
+
if quiet:
|
| 1079 |
+
enable_progress_bars()
|
| 1080 |
+
|
| 1081 |
+
if not quiet:
|
| 1082 |
+
print(f"Uploaded: {src} -> {BUCKET_PREFIX}{bucket_id}/{remote_path}")
|
.c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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains the 'hf cache' command group with cache management subcommands."""
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import re
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
from collections import defaultdict
|
| 21 |
+
from collections.abc import Callable, Mapping
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from enum import Enum
|
| 24 |
+
from typing import Annotated, Any
|
| 25 |
+
|
| 26 |
+
import typer
|
| 27 |
+
|
| 28 |
+
from huggingface_hub.errors import CLIError
|
| 29 |
+
|
| 30 |
+
from ..utils import (
|
| 31 |
+
ANSI,
|
| 32 |
+
CachedRepoInfo,
|
| 33 |
+
CachedRevisionInfo,
|
| 34 |
+
CacheNotFound,
|
| 35 |
+
HFCacheInfo,
|
| 36 |
+
_format_size,
|
| 37 |
+
scan_cache_dir,
|
| 38 |
+
tabulate,
|
| 39 |
+
)
|
| 40 |
+
from ..utils._parsing import parse_duration, parse_size
|
| 41 |
+
from ._cli_utils import (
|
| 42 |
+
OutputFormat,
|
| 43 |
+
RepoIdArg,
|
| 44 |
+
RepoTypeOpt,
|
| 45 |
+
RevisionOpt,
|
| 46 |
+
TokenOpt,
|
| 47 |
+
get_hf_api,
|
| 48 |
+
typer_factory,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
cache_cli = typer_factory(help="Manage local cache directory.")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
#### Cache helper utilities
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass(frozen=True)
|
| 59 |
+
class _DeletionResolution:
|
| 60 |
+
revisions: frozenset[str]
|
| 61 |
+
selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]]
|
| 62 |
+
missing: tuple[str, ...]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
_FILTER_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)\s*(?P<op>==|!=|>=|<=|>|<|=)\s*(?P<value>.+)$")
|
| 66 |
+
_ALLOWED_OPERATORS = {"=", "!=", ">", "<", ">=", "<="}
|
| 67 |
+
_FILTER_KEYS = {"accessed", "modified", "refs", "size", "type"}
|
| 68 |
+
_SORT_KEYS = {"accessed", "modified", "name", "size"}
|
| 69 |
+
_SORT_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)(?::(?P<order>asc|desc))?$")
|
| 70 |
+
_SORT_DEFAULT_ORDER = {
|
| 71 |
+
# Default ordering: accessed/modified/size are descending (newest/biggest first), name is ascending
|
| 72 |
+
"accessed": "desc",
|
| 73 |
+
"modified": "desc",
|
| 74 |
+
"size": "desc",
|
| 75 |
+
"name": "asc",
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# Dynamically generate SortOptions enum from _SORT_KEYS
|
| 80 |
+
_sort_options_dict = {}
|
| 81 |
+
for key in sorted(_SORT_KEYS):
|
| 82 |
+
_sort_options_dict[key] = key
|
| 83 |
+
_sort_options_dict[f"{key}_asc"] = f"{key}:asc"
|
| 84 |
+
_sort_options_dict[f"{key}_desc"] = f"{key}:desc"
|
| 85 |
+
|
| 86 |
+
SortOptions = Enum("SortOptions", _sort_options_dict, type=str, module=__name__) # type: ignore
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dataclass(frozen=True)
|
| 90 |
+
class CacheDeletionCounts:
|
| 91 |
+
"""Simple counters summarizing cache deletions for CLI messaging."""
|
| 92 |
+
|
| 93 |
+
repo_count: int
|
| 94 |
+
partial_revision_count: int
|
| 95 |
+
total_revision_count: int
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
CacheEntry = tuple[CachedRepoInfo, CachedRevisionInfo | None]
|
| 99 |
+
RepoRefsMap = dict[CachedRepoInfo, frozenset[str]]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def summarize_deletions(
|
| 103 |
+
selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]],
|
| 104 |
+
) -> CacheDeletionCounts:
|
| 105 |
+
"""Summarize deletions across repositories."""
|
| 106 |
+
repo_count = 0
|
| 107 |
+
total_revisions = 0
|
| 108 |
+
revisions_in_full_repos = 0
|
| 109 |
+
|
| 110 |
+
for repo, revisions in selected_by_repo.items():
|
| 111 |
+
total_revisions += len(revisions)
|
| 112 |
+
if len(revisions) == len(repo.revisions):
|
| 113 |
+
repo_count += 1
|
| 114 |
+
revisions_in_full_repos += len(revisions)
|
| 115 |
+
|
| 116 |
+
partial_revision_count = total_revisions - revisions_in_full_repos
|
| 117 |
+
return CacheDeletionCounts(repo_count, partial_revision_count, total_revisions)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def print_cache_selected_revisions(selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]]) -> None:
|
| 121 |
+
"""Pretty-print selected cache revisions during confirmation prompts."""
|
| 122 |
+
for repo in sorted(selected_by_repo.keys(), key=lambda repo: (repo.repo_type, repo.repo_id.lower())):
|
| 123 |
+
repo_key = f"{repo.repo_type}/{repo.repo_id}"
|
| 124 |
+
revisions = sorted(selected_by_repo[repo], key=lambda rev: rev.commit_hash)
|
| 125 |
+
if len(revisions) == len(repo.revisions):
|
| 126 |
+
print(f" - {repo_key} (entire repo)")
|
| 127 |
+
continue
|
| 128 |
+
|
| 129 |
+
print(f" - {repo_key}:")
|
| 130 |
+
for revision in revisions:
|
| 131 |
+
refs = " ".join(sorted(revision.refs)) or "(detached)"
|
| 132 |
+
print(f" {revision.commit_hash} [{refs}] {revision.size_on_disk_str}")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def build_cache_index(
|
| 136 |
+
hf_cache_info: HFCacheInfo,
|
| 137 |
+
) -> tuple[
|
| 138 |
+
dict[str, CachedRepoInfo],
|
| 139 |
+
dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]],
|
| 140 |
+
]:
|
| 141 |
+
"""Create lookup tables so CLI commands can resolve repo ids and revisions quickly."""
|
| 142 |
+
repo_lookup: dict[str, CachedRepoInfo] = {}
|
| 143 |
+
revision_lookup: dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]] = {}
|
| 144 |
+
for repo in hf_cache_info.repos:
|
| 145 |
+
repo_key = repo.cache_id.lower()
|
| 146 |
+
repo_lookup[repo_key] = repo
|
| 147 |
+
for revision in repo.revisions:
|
| 148 |
+
revision_lookup[revision.commit_hash.lower()] = (repo, revision)
|
| 149 |
+
return repo_lookup, revision_lookup
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def collect_cache_entries(
|
| 153 |
+
hf_cache_info: HFCacheInfo, *, include_revisions: bool
|
| 154 |
+
) -> tuple[list[CacheEntry], RepoRefsMap]:
|
| 155 |
+
"""Flatten cache metadata into rows consumed by `hf cache ls`."""
|
| 156 |
+
entries: list[CacheEntry] = []
|
| 157 |
+
repo_refs_map: RepoRefsMap = {}
|
| 158 |
+
sorted_repos = sorted(hf_cache_info.repos, key=lambda repo: (repo.repo_type, repo.repo_id.lower()))
|
| 159 |
+
for repo in sorted_repos:
|
| 160 |
+
repo_refs_map[repo] = frozenset({ref for revision in repo.revisions for ref in revision.refs})
|
| 161 |
+
if include_revisions:
|
| 162 |
+
for revision in sorted(repo.revisions, key=lambda rev: rev.commit_hash):
|
| 163 |
+
entries.append((repo, revision))
|
| 164 |
+
else:
|
| 165 |
+
entries.append((repo, None))
|
| 166 |
+
if include_revisions:
|
| 167 |
+
entries.sort(
|
| 168 |
+
key=lambda entry: (
|
| 169 |
+
entry[0].cache_id,
|
| 170 |
+
entry[1].commit_hash if entry[1] is not None else "",
|
| 171 |
+
)
|
| 172 |
+
)
|
| 173 |
+
else:
|
| 174 |
+
entries.sort(key=lambda entry: entry[0].cache_id)
|
| 175 |
+
return entries, repo_refs_map
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def compile_cache_filter(
|
| 179 |
+
expr: str, repo_refs_map: RepoRefsMap
|
| 180 |
+
) -> Callable[[CachedRepoInfo, CachedRevisionInfo | None, float], bool]:
|
| 181 |
+
"""Convert a `hf cache ls` filter expression into the yes/no test we apply to each cache entry before displaying it."""
|
| 182 |
+
match = _FILTER_PATTERN.match(expr.strip())
|
| 183 |
+
if not match:
|
| 184 |
+
raise ValueError(f"Invalid filter expression: '{expr}'.")
|
| 185 |
+
|
| 186 |
+
key = match.group("key").lower()
|
| 187 |
+
op = match.group("op")
|
| 188 |
+
value_raw = match.group("value").strip()
|
| 189 |
+
|
| 190 |
+
if op not in _ALLOWED_OPERATORS:
|
| 191 |
+
raise ValueError(f"Unsupported operator '{op}' in filter '{expr}'. Must be one of {list(_ALLOWED_OPERATORS)}.")
|
| 192 |
+
|
| 193 |
+
if key not in _FILTER_KEYS:
|
| 194 |
+
raise ValueError(f"Unsupported filter key '{key}' in '{expr}'. Must be one of {list(_FILTER_KEYS)}.")
|
| 195 |
+
# at this point we know that key is in `_FILTER_KEYS`
|
| 196 |
+
if key == "size":
|
| 197 |
+
size_threshold = parse_size(value_raw)
|
| 198 |
+
return lambda repo, revision, _: _compare_numeric(
|
| 199 |
+
revision.size_on_disk if revision is not None else repo.size_on_disk,
|
| 200 |
+
op,
|
| 201 |
+
size_threshold,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
if key in {"modified", "accessed"}:
|
| 205 |
+
seconds = parse_duration(value_raw.strip())
|
| 206 |
+
|
| 207 |
+
def _time_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, now: float) -> bool:
|
| 208 |
+
timestamp = (
|
| 209 |
+
repo.last_accessed
|
| 210 |
+
if key == "accessed"
|
| 211 |
+
else revision.last_modified
|
| 212 |
+
if revision is not None
|
| 213 |
+
else repo.last_modified
|
| 214 |
+
)
|
| 215 |
+
if timestamp is None:
|
| 216 |
+
return False
|
| 217 |
+
return _compare_numeric(now - timestamp, op, seconds)
|
| 218 |
+
|
| 219 |
+
return _time_filter
|
| 220 |
+
|
| 221 |
+
if key == "type":
|
| 222 |
+
expected = value_raw.lower()
|
| 223 |
+
|
| 224 |
+
if op != "=":
|
| 225 |
+
raise ValueError(f"Only '=' is supported for 'type' filters. Got '{op}'.")
|
| 226 |
+
|
| 227 |
+
def _type_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
|
| 228 |
+
return repo.repo_type.lower() == expected
|
| 229 |
+
|
| 230 |
+
return _type_filter
|
| 231 |
+
|
| 232 |
+
else: # key == "refs"
|
| 233 |
+
if op != "=":
|
| 234 |
+
raise ValueError(f"Only '=' is supported for 'refs' filters. Got {op}.")
|
| 235 |
+
|
| 236 |
+
def _refs_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
|
| 237 |
+
refs = revision.refs if revision is not None else repo_refs_map.get(repo, frozenset())
|
| 238 |
+
return value_raw.lower() in [ref.lower() for ref in refs]
|
| 239 |
+
|
| 240 |
+
return _refs_filter
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _build_cache_export_payload(
|
| 244 |
+
entries: list[CacheEntry], *, include_revisions: bool, repo_refs_map: RepoRefsMap
|
| 245 |
+
) -> list[dict[str, Any]]:
|
| 246 |
+
"""Normalize cache entries into serializable records for JSON/CSV exports."""
|
| 247 |
+
payload: list[dict[str, Any]] = []
|
| 248 |
+
for repo, revision in entries:
|
| 249 |
+
if include_revisions:
|
| 250 |
+
if revision is None:
|
| 251 |
+
continue
|
| 252 |
+
record: dict[str, Any] = {
|
| 253 |
+
"repo_id": repo.repo_id,
|
| 254 |
+
"repo_type": repo.repo_type,
|
| 255 |
+
"revision": revision.commit_hash,
|
| 256 |
+
"snapshot_path": str(revision.snapshot_path),
|
| 257 |
+
"size_on_disk": revision.size_on_disk,
|
| 258 |
+
"last_accessed": repo.last_accessed,
|
| 259 |
+
"last_modified": revision.last_modified,
|
| 260 |
+
"refs": sorted(revision.refs),
|
| 261 |
+
}
|
| 262 |
+
else:
|
| 263 |
+
record = {
|
| 264 |
+
"repo_id": repo.repo_id,
|
| 265 |
+
"repo_type": repo.repo_type,
|
| 266 |
+
"size_on_disk": repo.size_on_disk,
|
| 267 |
+
"last_accessed": repo.last_accessed,
|
| 268 |
+
"last_modified": repo.last_modified,
|
| 269 |
+
"refs": sorted(repo_refs_map.get(repo, frozenset())),
|
| 270 |
+
}
|
| 271 |
+
payload.append(record)
|
| 272 |
+
return payload
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def print_cache_entries_table(
|
| 276 |
+
entries: list[CacheEntry], *, include_revisions: bool, repo_refs_map: RepoRefsMap
|
| 277 |
+
) -> None:
|
| 278 |
+
"""Render cache entries as a table and show a human-readable summary."""
|
| 279 |
+
if not entries:
|
| 280 |
+
message = "No cached revisions found." if include_revisions else "No cached repositories found."
|
| 281 |
+
print(message)
|
| 282 |
+
return
|
| 283 |
+
table_rows: list[list[str | int]]
|
| 284 |
+
if include_revisions:
|
| 285 |
+
headers = ["ID", "REVISION", "SIZE", "LAST_MODIFIED", "REFS"]
|
| 286 |
+
table_rows = [
|
| 287 |
+
[
|
| 288 |
+
repo.cache_id,
|
| 289 |
+
revision.commit_hash,
|
| 290 |
+
revision.size_on_disk_str.rjust(8),
|
| 291 |
+
revision.last_modified_str,
|
| 292 |
+
" ".join(sorted(revision.refs)),
|
| 293 |
+
]
|
| 294 |
+
for repo, revision in entries
|
| 295 |
+
if revision is not None
|
| 296 |
+
]
|
| 297 |
+
else:
|
| 298 |
+
headers = ["ID", "SIZE", "LAST_ACCESSED", "LAST_MODIFIED", "REFS"]
|
| 299 |
+
table_rows = [
|
| 300 |
+
[
|
| 301 |
+
repo.cache_id,
|
| 302 |
+
repo.size_on_disk_str.rjust(8),
|
| 303 |
+
repo.last_accessed_str or "",
|
| 304 |
+
repo.last_modified_str,
|
| 305 |
+
" ".join(sorted(repo_refs_map.get(repo, frozenset()))),
|
| 306 |
+
]
|
| 307 |
+
for repo, _ in entries
|
| 308 |
+
]
|
| 309 |
+
|
| 310 |
+
print(tabulate(table_rows, headers=headers))
|
| 311 |
+
|
| 312 |
+
unique_repos = {repo for repo, _ in entries}
|
| 313 |
+
repo_count = len(unique_repos)
|
| 314 |
+
if include_revisions:
|
| 315 |
+
revision_count = sum(1 for _, revision in entries if revision is not None)
|
| 316 |
+
total_size = sum(revision.size_on_disk for _, revision in entries if revision is not None)
|
| 317 |
+
else:
|
| 318 |
+
revision_count = sum(len(repo.revisions) for repo in unique_repos)
|
| 319 |
+
total_size = sum(repo.size_on_disk for repo in unique_repos)
|
| 320 |
+
|
| 321 |
+
summary = f"\nFound {repo_count} repo(s) for a total of {revision_count} revision(s) and {_format_size(total_size)} on disk."
|
| 322 |
+
print(ANSI.bold(summary))
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def print_cache_entries_json(
|
| 326 |
+
entries: list[CacheEntry], *, include_revisions: bool, repo_refs_map: RepoRefsMap
|
| 327 |
+
) -> None:
|
| 328 |
+
"""Dump cache entries as JSON for scripting or automation."""
|
| 329 |
+
payload = _build_cache_export_payload(entries, include_revisions=include_revisions, repo_refs_map=repo_refs_map)
|
| 330 |
+
json.dump(payload, sys.stdout, indent=2)
|
| 331 |
+
sys.stdout.write("\n")
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def _compare_numeric(left: float | None, op: str, right: float) -> bool:
|
| 335 |
+
"""Evaluate numeric comparisons for filters."""
|
| 336 |
+
if left is None:
|
| 337 |
+
return False
|
| 338 |
+
|
| 339 |
+
comparisons = {
|
| 340 |
+
"=": left == right,
|
| 341 |
+
"!=": left != right,
|
| 342 |
+
">": left > right,
|
| 343 |
+
"<": left < right,
|
| 344 |
+
">=": left >= right,
|
| 345 |
+
"<=": left <= right,
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
if op not in comparisons:
|
| 349 |
+
raise ValueError(f"Unsupported numeric comparison operator: {op}")
|
| 350 |
+
|
| 351 |
+
return comparisons[op]
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def compile_cache_sort(sort_expr: str) -> tuple[Callable[[CacheEntry], tuple[Any, ...]], bool]:
|
| 355 |
+
"""Convert a `hf cache ls` sort expression into a key function for sorting entries.
|
| 356 |
+
|
| 357 |
+
Returns:
|
| 358 |
+
A tuple of (key_function, reverse_flag) where reverse_flag indicates whether
|
| 359 |
+
to sort in descending order (True) or ascending order (False).
|
| 360 |
+
"""
|
| 361 |
+
match = _SORT_PATTERN.match(sort_expr.strip().lower())
|
| 362 |
+
if not match:
|
| 363 |
+
raise ValueError(f"Invalid sort expression: '{sort_expr}'. Expected format: 'key' or 'key:asc' or 'key:desc'.")
|
| 364 |
+
|
| 365 |
+
key = match.group("key").lower()
|
| 366 |
+
explicit_order = match.group("order")
|
| 367 |
+
|
| 368 |
+
if key not in _SORT_KEYS:
|
| 369 |
+
raise ValueError(f"Unsupported sort key '{key}' in '{sort_expr}'. Must be one of {list(_SORT_KEYS)}.")
|
| 370 |
+
|
| 371 |
+
# Use explicit order if provided, otherwise use default for the key
|
| 372 |
+
order = explicit_order if explicit_order else _SORT_DEFAULT_ORDER[key]
|
| 373 |
+
reverse = order == "desc"
|
| 374 |
+
|
| 375 |
+
def _sort_key(entry: CacheEntry) -> tuple[Any, ...]:
|
| 376 |
+
repo, revision = entry
|
| 377 |
+
|
| 378 |
+
if key == "name":
|
| 379 |
+
# Sort by cache_id (repo type/id)
|
| 380 |
+
value: Any = repo.cache_id.lower()
|
| 381 |
+
return (value,)
|
| 382 |
+
|
| 383 |
+
if key == "size":
|
| 384 |
+
# Use revision size if available, otherwise repo size
|
| 385 |
+
value = revision.size_on_disk if revision is not None else repo.size_on_disk
|
| 386 |
+
return (value,)
|
| 387 |
+
|
| 388 |
+
if key == "accessed":
|
| 389 |
+
# For revisions, accessed is not available per-revision, use repo's last_accessed
|
| 390 |
+
# For repos, use repo's last_accessed
|
| 391 |
+
value = repo.last_accessed if repo.last_accessed is not None else 0.0
|
| 392 |
+
return (value,)
|
| 393 |
+
|
| 394 |
+
if key == "modified":
|
| 395 |
+
# Use revision's last_modified if available, otherwise repo's last_modified
|
| 396 |
+
if revision is not None:
|
| 397 |
+
value = revision.last_modified if revision.last_modified is not None else 0.0
|
| 398 |
+
else:
|
| 399 |
+
value = repo.last_modified if repo.last_modified is not None else 0.0
|
| 400 |
+
return (value,)
|
| 401 |
+
|
| 402 |
+
# Should never reach here due to validation above
|
| 403 |
+
raise ValueError(f"Unsupported sort key: {key}")
|
| 404 |
+
|
| 405 |
+
return _sort_key, reverse
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _resolve_deletion_targets(hf_cache_info: HFCacheInfo, targets: list[str]) -> _DeletionResolution:
|
| 409 |
+
"""Resolve the deletion targets into a deletion resolution."""
|
| 410 |
+
repo_lookup, revision_lookup = build_cache_index(hf_cache_info)
|
| 411 |
+
|
| 412 |
+
selected: dict[CachedRepoInfo, set[CachedRevisionInfo]] = defaultdict(set)
|
| 413 |
+
revisions: set[str] = set()
|
| 414 |
+
missing: list[str] = []
|
| 415 |
+
|
| 416 |
+
for raw_target in targets:
|
| 417 |
+
target = raw_target.strip()
|
| 418 |
+
if not target:
|
| 419 |
+
continue
|
| 420 |
+
lowered = target.lower()
|
| 421 |
+
|
| 422 |
+
if re.fullmatch(r"[0-9a-fA-F]{40}", lowered):
|
| 423 |
+
match = revision_lookup.get(lowered)
|
| 424 |
+
if match is None:
|
| 425 |
+
missing.append(raw_target)
|
| 426 |
+
continue
|
| 427 |
+
repo, revision = match
|
| 428 |
+
selected[repo].add(revision)
|
| 429 |
+
revisions.add(revision.commit_hash)
|
| 430 |
+
continue
|
| 431 |
+
|
| 432 |
+
matched_repo = repo_lookup.get(lowered)
|
| 433 |
+
if matched_repo is None:
|
| 434 |
+
missing.append(raw_target)
|
| 435 |
+
continue
|
| 436 |
+
|
| 437 |
+
for revision in matched_repo.revisions:
|
| 438 |
+
selected[matched_repo].add(revision)
|
| 439 |
+
revisions.add(revision.commit_hash)
|
| 440 |
+
|
| 441 |
+
frozen_selected = {repo: frozenset(revs) for repo, revs in selected.items()}
|
| 442 |
+
return _DeletionResolution(
|
| 443 |
+
revisions=frozenset(revisions),
|
| 444 |
+
selected=frozen_selected,
|
| 445 |
+
missing=tuple(missing),
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
#### Cache CLI commands
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
@cache_cli.command(
|
| 453 |
+
"list | ls",
|
| 454 |
+
examples=[
|
| 455 |
+
"hf cache ls",
|
| 456 |
+
"hf cache ls --revisions",
|
| 457 |
+
'hf cache ls --filter "size>1GB" --limit 20',
|
| 458 |
+
"hf cache ls --format json",
|
| 459 |
+
],
|
| 460 |
+
)
|
| 461 |
+
def ls(
|
| 462 |
+
cache_dir: Annotated[
|
| 463 |
+
str | None,
|
| 464 |
+
typer.Option(
|
| 465 |
+
help="Cache directory to scan (defaults to Hugging Face cache).",
|
| 466 |
+
),
|
| 467 |
+
] = None,
|
| 468 |
+
revisions: Annotated[
|
| 469 |
+
bool,
|
| 470 |
+
typer.Option(
|
| 471 |
+
help="Include revisions in the output instead of aggregated repositories.",
|
| 472 |
+
),
|
| 473 |
+
] = False,
|
| 474 |
+
filter: Annotated[
|
| 475 |
+
list[str] | None,
|
| 476 |
+
typer.Option(
|
| 477 |
+
"-f",
|
| 478 |
+
"--filter",
|
| 479 |
+
help="Filter entries (e.g. 'size>1GB', 'type=model', 'accessed>7d'). Can be used multiple times.",
|
| 480 |
+
),
|
| 481 |
+
] = None,
|
| 482 |
+
format: Annotated[
|
| 483 |
+
OutputFormat,
|
| 484 |
+
typer.Option(
|
| 485 |
+
help="Output format.",
|
| 486 |
+
),
|
| 487 |
+
] = OutputFormat.table,
|
| 488 |
+
quiet: Annotated[
|
| 489 |
+
bool,
|
| 490 |
+
typer.Option(
|
| 491 |
+
"-q",
|
| 492 |
+
"--quiet",
|
| 493 |
+
help="Print only IDs (repo IDs or revision hashes).",
|
| 494 |
+
),
|
| 495 |
+
] = False,
|
| 496 |
+
sort: Annotated[
|
| 497 |
+
SortOptions | None,
|
| 498 |
+
typer.Option(
|
| 499 |
+
help="Sort entries by key. Supported keys: 'accessed', 'modified', 'name', 'size'. "
|
| 500 |
+
"Append ':asc' or ':desc' to explicitly set the order (e.g., 'modified:asc'). "
|
| 501 |
+
"Defaults: 'accessed', 'modified', 'size' default to 'desc' (newest/biggest first); "
|
| 502 |
+
"'name' defaults to 'asc' (alphabetical).",
|
| 503 |
+
),
|
| 504 |
+
] = None,
|
| 505 |
+
limit: Annotated[
|
| 506 |
+
int | None,
|
| 507 |
+
typer.Option(
|
| 508 |
+
help="Limit the number of results returned. Returns only the top N entries after sorting.",
|
| 509 |
+
),
|
| 510 |
+
] = None,
|
| 511 |
+
) -> None:
|
| 512 |
+
"""List cached repositories or revisions."""
|
| 513 |
+
try:
|
| 514 |
+
hf_cache_info = scan_cache_dir(cache_dir)
|
| 515 |
+
except CacheNotFound as exc:
|
| 516 |
+
raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
|
| 517 |
+
|
| 518 |
+
filters = filter or []
|
| 519 |
+
|
| 520 |
+
entries, repo_refs_map = collect_cache_entries(hf_cache_info, include_revisions=revisions)
|
| 521 |
+
try:
|
| 522 |
+
filter_fns = [compile_cache_filter(expr, repo_refs_map) for expr in filters]
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
raise typer.BadParameter(str(exc)) from exc
|
| 525 |
+
|
| 526 |
+
now = time.time()
|
| 527 |
+
for fn in filter_fns:
|
| 528 |
+
entries = [entry for entry in entries if fn(entry[0], entry[1], now)]
|
| 529 |
+
|
| 530 |
+
# Apply sorting if requested
|
| 531 |
+
if sort:
|
| 532 |
+
try:
|
| 533 |
+
sort_key_fn, reverse = compile_cache_sort(sort.value)
|
| 534 |
+
entries.sort(key=sort_key_fn, reverse=reverse)
|
| 535 |
+
except ValueError as exc:
|
| 536 |
+
raise typer.BadParameter(str(exc)) from exc
|
| 537 |
+
|
| 538 |
+
# Apply limit if requested
|
| 539 |
+
if limit is not None:
|
| 540 |
+
if limit < 0:
|
| 541 |
+
raise typer.BadParameter(f"Limit must be a positive integer, got {limit}.")
|
| 542 |
+
entries = entries[:limit]
|
| 543 |
+
|
| 544 |
+
if quiet:
|
| 545 |
+
for repo, revision in entries:
|
| 546 |
+
print(revision.commit_hash if revision is not None else repo.cache_id)
|
| 547 |
+
return
|
| 548 |
+
|
| 549 |
+
formatters = {
|
| 550 |
+
OutputFormat.table: print_cache_entries_table,
|
| 551 |
+
OutputFormat.json: print_cache_entries_json,
|
| 552 |
+
}
|
| 553 |
+
return formatters[format](entries, include_revisions=revisions, repo_refs_map=repo_refs_map)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
@cache_cli.command(
|
| 557 |
+
examples=[
|
| 558 |
+
"hf cache rm model/gpt2",
|
| 559 |
+
"hf cache rm <revision_hash>",
|
| 560 |
+
"hf cache rm model/gpt2 --dry-run",
|
| 561 |
+
"hf cache rm model/gpt2 --yes",
|
| 562 |
+
],
|
| 563 |
+
)
|
| 564 |
+
def rm(
|
| 565 |
+
targets: Annotated[
|
| 566 |
+
list[str],
|
| 567 |
+
typer.Argument(
|
| 568 |
+
help="One or more repo IDs (e.g. model/bert-base-uncased) or revision hashes to delete.",
|
| 569 |
+
),
|
| 570 |
+
],
|
| 571 |
+
cache_dir: Annotated[
|
| 572 |
+
str | None,
|
| 573 |
+
typer.Option(
|
| 574 |
+
help="Cache directory to scan (defaults to Hugging Face cache).",
|
| 575 |
+
),
|
| 576 |
+
] = None,
|
| 577 |
+
yes: Annotated[
|
| 578 |
+
bool,
|
| 579 |
+
typer.Option(
|
| 580 |
+
"-y",
|
| 581 |
+
"--yes",
|
| 582 |
+
help="Skip confirmation prompt.",
|
| 583 |
+
),
|
| 584 |
+
] = False,
|
| 585 |
+
dry_run: Annotated[
|
| 586 |
+
bool,
|
| 587 |
+
typer.Option(
|
| 588 |
+
help="Preview deletions without removing anything.",
|
| 589 |
+
),
|
| 590 |
+
] = False,
|
| 591 |
+
) -> None:
|
| 592 |
+
"""Remove cached repositories or revisions."""
|
| 593 |
+
try:
|
| 594 |
+
hf_cache_info = scan_cache_dir(cache_dir)
|
| 595 |
+
except CacheNotFound as exc:
|
| 596 |
+
raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
|
| 597 |
+
|
| 598 |
+
resolution = _resolve_deletion_targets(hf_cache_info, targets)
|
| 599 |
+
|
| 600 |
+
if resolution.missing:
|
| 601 |
+
print("Could not find the following targets in the cache:")
|
| 602 |
+
for entry in resolution.missing:
|
| 603 |
+
print(f" - {entry}")
|
| 604 |
+
|
| 605 |
+
if len(resolution.revisions) == 0:
|
| 606 |
+
print("Nothing to delete.")
|
| 607 |
+
raise typer.Exit(code=0)
|
| 608 |
+
|
| 609 |
+
strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions))
|
| 610 |
+
counts = summarize_deletions(resolution.selected)
|
| 611 |
+
|
| 612 |
+
summary_parts: list[str] = []
|
| 613 |
+
if counts.repo_count:
|
| 614 |
+
summary_parts.append(f"{counts.repo_count} repo(s)")
|
| 615 |
+
if counts.partial_revision_count:
|
| 616 |
+
summary_parts.append(f"{counts.partial_revision_count} revision(s)")
|
| 617 |
+
if not summary_parts:
|
| 618 |
+
summary_parts.append(f"{counts.total_revision_count} revision(s)")
|
| 619 |
+
|
| 620 |
+
summary_text = " and ".join(summary_parts)
|
| 621 |
+
print(f"About to delete {summary_text} totalling {strategy.expected_freed_size_str}.")
|
| 622 |
+
print_cache_selected_revisions(resolution.selected)
|
| 623 |
+
|
| 624 |
+
if dry_run:
|
| 625 |
+
print("Dry run: no files were deleted.")
|
| 626 |
+
return
|
| 627 |
+
|
| 628 |
+
if not yes and not typer.confirm("Proceed with deletion?", default=False):
|
| 629 |
+
print("Deletion cancelled.")
|
| 630 |
+
return
|
| 631 |
+
|
| 632 |
+
strategy.execute()
|
| 633 |
+
counts = summarize_deletions(resolution.selected)
|
| 634 |
+
print(
|
| 635 |
+
f"Deleted {counts.repo_count} repo(s) and {counts.total_revision_count} revision(s); freed {strategy.expected_freed_size_str}."
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
@cache_cli.command(examples=["hf cache prune", "hf cache prune --dry-run"])
|
| 640 |
+
def prune(
|
| 641 |
+
cache_dir: Annotated[
|
| 642 |
+
str | None,
|
| 643 |
+
typer.Option(
|
| 644 |
+
help="Cache directory to scan (defaults to Hugging Face cache).",
|
| 645 |
+
),
|
| 646 |
+
] = None,
|
| 647 |
+
yes: Annotated[
|
| 648 |
+
bool,
|
| 649 |
+
typer.Option(
|
| 650 |
+
"-y",
|
| 651 |
+
"--yes",
|
| 652 |
+
help="Skip confirmation prompt.",
|
| 653 |
+
),
|
| 654 |
+
] = False,
|
| 655 |
+
dry_run: Annotated[
|
| 656 |
+
bool,
|
| 657 |
+
typer.Option(
|
| 658 |
+
help="Preview deletions without removing anything.",
|
| 659 |
+
),
|
| 660 |
+
] = False,
|
| 661 |
+
) -> None:
|
| 662 |
+
"""Remove detached revisions from the cache."""
|
| 663 |
+
try:
|
| 664 |
+
hf_cache_info = scan_cache_dir(cache_dir)
|
| 665 |
+
except CacheNotFound as exc:
|
| 666 |
+
raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
|
| 667 |
+
|
| 668 |
+
selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]] = {}
|
| 669 |
+
revisions: set[str] = set()
|
| 670 |
+
for repo in hf_cache_info.repos:
|
| 671 |
+
detached = frozenset(revision for revision in repo.revisions if len(revision.refs) == 0)
|
| 672 |
+
if not detached:
|
| 673 |
+
continue
|
| 674 |
+
selected[repo] = detached
|
| 675 |
+
revisions.update(revision.commit_hash for revision in detached)
|
| 676 |
+
|
| 677 |
+
if len(revisions) == 0:
|
| 678 |
+
print("No unreferenced revisions found. Nothing to prune.")
|
| 679 |
+
return
|
| 680 |
+
|
| 681 |
+
resolution = _DeletionResolution(
|
| 682 |
+
revisions=frozenset(revisions),
|
| 683 |
+
selected=selected,
|
| 684 |
+
missing=(),
|
| 685 |
+
)
|
| 686 |
+
strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions))
|
| 687 |
+
counts = summarize_deletions(selected)
|
| 688 |
+
|
| 689 |
+
print(
|
| 690 |
+
f"About to delete {counts.total_revision_count} unreferenced revision(s) ({strategy.expected_freed_size_str} total)."
|
| 691 |
+
)
|
| 692 |
+
print_cache_selected_revisions(selected)
|
| 693 |
+
|
| 694 |
+
if dry_run:
|
| 695 |
+
print("Dry run: no files were deleted.")
|
| 696 |
+
return
|
| 697 |
+
|
| 698 |
+
if not yes and not typer.confirm("Proceed?"):
|
| 699 |
+
print("Pruning cancelled.")
|
| 700 |
+
return
|
| 701 |
+
|
| 702 |
+
strategy.execute()
|
| 703 |
+
print(f"Deleted {counts.total_revision_count} unreferenced revision(s); freed {strategy.expected_freed_size_str}.")
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
@cache_cli.command(
|
| 707 |
+
examples=[
|
| 708 |
+
"hf cache verify gpt2",
|
| 709 |
+
"hf cache verify gpt2 --revision refs/pr/1",
|
| 710 |
+
"hf cache verify my-dataset --repo-type dataset",
|
| 711 |
+
],
|
| 712 |
+
)
|
| 713 |
+
def verify(
|
| 714 |
+
repo_id: RepoIdArg,
|
| 715 |
+
repo_type: RepoTypeOpt = RepoTypeOpt.model,
|
| 716 |
+
revision: RevisionOpt = None,
|
| 717 |
+
cache_dir: Annotated[
|
| 718 |
+
str | None,
|
| 719 |
+
typer.Option(
|
| 720 |
+
help="Cache directory to use when verifying files from cache (defaults to Hugging Face cache).",
|
| 721 |
+
),
|
| 722 |
+
] = None,
|
| 723 |
+
local_dir: Annotated[
|
| 724 |
+
str | None,
|
| 725 |
+
typer.Option(
|
| 726 |
+
help="If set, verify files under this directory instead of the cache.",
|
| 727 |
+
),
|
| 728 |
+
] = None,
|
| 729 |
+
fail_on_missing_files: Annotated[
|
| 730 |
+
bool,
|
| 731 |
+
typer.Option(
|
| 732 |
+
"--fail-on-missing-files",
|
| 733 |
+
help="Fail if some files exist on the remote but are missing locally.",
|
| 734 |
+
),
|
| 735 |
+
] = False,
|
| 736 |
+
fail_on_extra_files: Annotated[
|
| 737 |
+
bool,
|
| 738 |
+
typer.Option(
|
| 739 |
+
"--fail-on-extra-files",
|
| 740 |
+
help="Fail if some files exist locally but are not present on the remote revision.",
|
| 741 |
+
),
|
| 742 |
+
] = False,
|
| 743 |
+
token: TokenOpt = None,
|
| 744 |
+
) -> None:
|
| 745 |
+
"""Verify checksums for a single repo revision from cache or a local directory.
|
| 746 |
+
|
| 747 |
+
Examples:
|
| 748 |
+
- Verify main revision in cache: `hf cache verify gpt2`
|
| 749 |
+
- Verify specific revision: `hf cache verify gpt2 --revision refs/pr/1`
|
| 750 |
+
- Verify dataset: `hf cache verify karpathy/fineweb-edu-100b-shuffle --repo-type dataset`
|
| 751 |
+
- Verify local dir: `hf cache verify deepseek-ai/DeepSeek-OCR --local-dir /path/to/repo`
|
| 752 |
+
"""
|
| 753 |
+
|
| 754 |
+
if local_dir is not None and cache_dir is not None:
|
| 755 |
+
print("Cannot pass both --local-dir and --cache-dir. Use one or the other.")
|
| 756 |
+
raise typer.Exit(code=2)
|
| 757 |
+
|
| 758 |
+
api = get_hf_api(token=token)
|
| 759 |
+
|
| 760 |
+
result = api.verify_repo_checksums(
|
| 761 |
+
repo_id=repo_id,
|
| 762 |
+
repo_type=repo_type.value if hasattr(repo_type, "value") else str(repo_type),
|
| 763 |
+
revision=revision,
|
| 764 |
+
local_dir=local_dir,
|
| 765 |
+
cache_dir=cache_dir,
|
| 766 |
+
token=token,
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
exit_code = 0
|
| 770 |
+
|
| 771 |
+
has_mismatches = bool(result.mismatches)
|
| 772 |
+
if has_mismatches:
|
| 773 |
+
print("❌ Checksum verification failed for the following file(s):")
|
| 774 |
+
for m in result.mismatches:
|
| 775 |
+
print(f" - {m['path']}: expected {m['expected']} ({m['algorithm']}), got {m['actual']}")
|
| 776 |
+
exit_code = 1
|
| 777 |
+
|
| 778 |
+
if result.missing_paths:
|
| 779 |
+
if fail_on_missing_files:
|
| 780 |
+
print("Missing files (present remotely, absent locally):")
|
| 781 |
+
for p in result.missing_paths:
|
| 782 |
+
print(f" - {p}")
|
| 783 |
+
exit_code = 1
|
| 784 |
+
else:
|
| 785 |
+
warning = (
|
| 786 |
+
f"{len(result.missing_paths)} remote file(s) are missing locally. "
|
| 787 |
+
"Use --fail-on-missing-files for details."
|
| 788 |
+
)
|
| 789 |
+
print(f"⚠️ {warning}")
|
| 790 |
+
|
| 791 |
+
if result.extra_paths:
|
| 792 |
+
if fail_on_extra_files:
|
| 793 |
+
print("Extra files (present locally, absent remotely):")
|
| 794 |
+
for p in result.extra_paths:
|
| 795 |
+
print(f" - {p}")
|
| 796 |
+
exit_code = 1
|
| 797 |
+
else:
|
| 798 |
+
warning = (
|
| 799 |
+
f"{len(result.extra_paths)} local file(s) do not exist on the remote repo. "
|
| 800 |
+
"Use --fail-on-extra-files for details."
|
| 801 |
+
)
|
| 802 |
+
print(f"⚠️ {warning}")
|
| 803 |
+
|
| 804 |
+
verified_location = result.verified_path
|
| 805 |
+
|
| 806 |
+
if exit_code != 0:
|
| 807 |
+
print(f"❌ Verification failed for '{repo_id}' ({repo_type.value}) in {verified_location}.")
|
| 808 |
+
print(f" Revision: {result.revision}")
|
| 809 |
+
raise typer.Exit(code=exit_code)
|
| 810 |
+
|
| 811 |
+
print(f"✅ Verified {result.checked_count} file(s) for '{repo_id}' ({repo_type.value}) in {verified_location}")
|
| 812 |
+
print(" All checksums match.")
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/collections.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with collections on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# list collections on the Hub
|
| 18 |
+
hf collections ls
|
| 19 |
+
|
| 20 |
+
# list collections for a specific user
|
| 21 |
+
hf collections ls --owner username
|
| 22 |
+
|
| 23 |
+
# get info about a collection
|
| 24 |
+
hf collections info username/collection-slug
|
| 25 |
+
|
| 26 |
+
# create a new collection
|
| 27 |
+
hf collections create "My Collection" --description "A collection of models"
|
| 28 |
+
|
| 29 |
+
# add an item to a collection
|
| 30 |
+
hf collections add-item username/collection-slug username/model-name model
|
| 31 |
+
|
| 32 |
+
# delete a collection
|
| 33 |
+
hf collections delete username/collection-slug
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
import enum
|
| 37 |
+
import json
|
| 38 |
+
from typing import Annotated, get_args
|
| 39 |
+
|
| 40 |
+
import typer
|
| 41 |
+
|
| 42 |
+
from huggingface_hub.hf_api import CollectionItemType_T, CollectionSort_T
|
| 43 |
+
|
| 44 |
+
from ._cli_utils import (
|
| 45 |
+
FormatOpt,
|
| 46 |
+
LimitOpt,
|
| 47 |
+
OutputFormat,
|
| 48 |
+
QuietOpt,
|
| 49 |
+
TokenOpt,
|
| 50 |
+
api_object_to_dict,
|
| 51 |
+
get_hf_api,
|
| 52 |
+
print_list_output,
|
| 53 |
+
typer_factory,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# Build enums dynamically from Literal types to avoid duplication
|
| 58 |
+
_COLLECTION_ITEM_TYPES = get_args(CollectionItemType_T)
|
| 59 |
+
CollectionItemType = enum.Enum("CollectionItemType", {t: t for t in _COLLECTION_ITEM_TYPES}, type=str) # type: ignore[misc]
|
| 60 |
+
|
| 61 |
+
_COLLECTION_SORT_OPTIONS = get_args(CollectionSort_T)
|
| 62 |
+
CollectionSort = enum.Enum("CollectionSort", {s: s for s in _COLLECTION_SORT_OPTIONS}, type=str) # type: ignore[misc]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
collections_cli = typer_factory(help="Interact with collections on the Hub.")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@collections_cli.command(
|
| 69 |
+
"list | ls",
|
| 70 |
+
examples=[
|
| 71 |
+
"hf collections ls",
|
| 72 |
+
"hf collections ls --owner nvidia",
|
| 73 |
+
"hf collections ls --item models/teknium/OpenHermes-2.5-Mistral-7B --limit 10",
|
| 74 |
+
],
|
| 75 |
+
)
|
| 76 |
+
def collections_ls(
|
| 77 |
+
owner: Annotated[
|
| 78 |
+
str | None,
|
| 79 |
+
typer.Option(help="Filter by owner username or organization."),
|
| 80 |
+
] = None,
|
| 81 |
+
item: Annotated[
|
| 82 |
+
str | None,
|
| 83 |
+
typer.Option(
|
| 84 |
+
help='Filter collections containing a specific item (e.g., "models/gpt2", "datasets/squad", "papers/2311.12983").'
|
| 85 |
+
),
|
| 86 |
+
] = None,
|
| 87 |
+
sort: Annotated[
|
| 88 |
+
CollectionSort | None,
|
| 89 |
+
typer.Option(help="Sort results by last modified, trending, or upvotes."),
|
| 90 |
+
] = None,
|
| 91 |
+
limit: LimitOpt = 10,
|
| 92 |
+
format: FormatOpt = OutputFormat.table,
|
| 93 |
+
quiet: QuietOpt = False,
|
| 94 |
+
token: TokenOpt = None,
|
| 95 |
+
) -> None:
|
| 96 |
+
"""List collections on the Hub."""
|
| 97 |
+
api = get_hf_api(token=token)
|
| 98 |
+
sort_key = sort.value if sort else None
|
| 99 |
+
results = [
|
| 100 |
+
api_object_to_dict(collection)
|
| 101 |
+
for collection in api.list_collections(
|
| 102 |
+
owner=owner,
|
| 103 |
+
item=item,
|
| 104 |
+
sort=sort_key, # type: ignore[arg-type]
|
| 105 |
+
limit=limit,
|
| 106 |
+
)
|
| 107 |
+
]
|
| 108 |
+
print_list_output(results, format=format, quiet=quiet)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@collections_cli.command(
|
| 112 |
+
"info",
|
| 113 |
+
examples=[
|
| 114 |
+
"hf collections info username/my-collection-slug",
|
| 115 |
+
],
|
| 116 |
+
)
|
| 117 |
+
def collections_info(
|
| 118 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 119 |
+
token: TokenOpt = None,
|
| 120 |
+
) -> None:
|
| 121 |
+
"""Get info about a collection on the Hub. Output is in JSON format."""
|
| 122 |
+
api = get_hf_api(token=token)
|
| 123 |
+
collection = api.get_collection(collection_slug)
|
| 124 |
+
print(json.dumps(api_object_to_dict(collection), indent=2))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@collections_cli.command(
|
| 128 |
+
"create",
|
| 129 |
+
examples=[
|
| 130 |
+
'hf collections create "My Models"',
|
| 131 |
+
'hf collections create "My Models" --description "A collection of my favorite models" --private',
|
| 132 |
+
'hf collections create "Org Collection" --namespace my-org',
|
| 133 |
+
],
|
| 134 |
+
)
|
| 135 |
+
def collections_create(
|
| 136 |
+
title: Annotated[str, typer.Argument(help="The title of the collection.")],
|
| 137 |
+
namespace: Annotated[
|
| 138 |
+
str | None,
|
| 139 |
+
typer.Option(help="The namespace (username or organization). Defaults to the authenticated user."),
|
| 140 |
+
] = None,
|
| 141 |
+
description: Annotated[
|
| 142 |
+
str | None,
|
| 143 |
+
typer.Option(help="A description for the collection."),
|
| 144 |
+
] = None,
|
| 145 |
+
private: Annotated[
|
| 146 |
+
bool,
|
| 147 |
+
typer.Option(help="Create a private collection."),
|
| 148 |
+
] = False,
|
| 149 |
+
exists_ok: Annotated[
|
| 150 |
+
bool,
|
| 151 |
+
typer.Option(help="Do not raise an error if the collection already exists."),
|
| 152 |
+
] = False,
|
| 153 |
+
token: TokenOpt = None,
|
| 154 |
+
) -> None:
|
| 155 |
+
"""Create a new collection on the Hub."""
|
| 156 |
+
api = get_hf_api(token=token)
|
| 157 |
+
collection = api.create_collection(
|
| 158 |
+
title=title,
|
| 159 |
+
namespace=namespace,
|
| 160 |
+
description=description,
|
| 161 |
+
private=private,
|
| 162 |
+
exists_ok=exists_ok,
|
| 163 |
+
)
|
| 164 |
+
print(f"Collection created: {collection.url}")
|
| 165 |
+
print(json.dumps(api_object_to_dict(collection), indent=2))
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
@collections_cli.command(
|
| 169 |
+
"update",
|
| 170 |
+
examples=[
|
| 171 |
+
'hf collections update username/my-collection --title "New Title"',
|
| 172 |
+
'hf collections update username/my-collection --description "Updated description"',
|
| 173 |
+
"hf collections update username/my-collection --private --theme green",
|
| 174 |
+
],
|
| 175 |
+
)
|
| 176 |
+
def collections_update(
|
| 177 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 178 |
+
title: Annotated[
|
| 179 |
+
str | None,
|
| 180 |
+
typer.Option(help="The new title for the collection."),
|
| 181 |
+
] = None,
|
| 182 |
+
description: Annotated[
|
| 183 |
+
str | None,
|
| 184 |
+
typer.Option(help="The new description for the collection."),
|
| 185 |
+
] = None,
|
| 186 |
+
position: Annotated[
|
| 187 |
+
int | None,
|
| 188 |
+
typer.Option(help="The new position of the collection in the owner's list."),
|
| 189 |
+
] = None,
|
| 190 |
+
private: Annotated[
|
| 191 |
+
bool | None,
|
| 192 |
+
typer.Option(help="Whether the collection should be private."),
|
| 193 |
+
] = None,
|
| 194 |
+
theme: Annotated[
|
| 195 |
+
str | None,
|
| 196 |
+
typer.Option(help="The theme color for the collection (e.g., 'green', 'blue')."),
|
| 197 |
+
] = None,
|
| 198 |
+
token: TokenOpt = None,
|
| 199 |
+
) -> None:
|
| 200 |
+
"""Update a collection's metadata on the Hub."""
|
| 201 |
+
api = get_hf_api(token=token)
|
| 202 |
+
collection = api.update_collection_metadata(
|
| 203 |
+
collection_slug=collection_slug,
|
| 204 |
+
title=title,
|
| 205 |
+
description=description,
|
| 206 |
+
position=position,
|
| 207 |
+
private=private,
|
| 208 |
+
theme=theme,
|
| 209 |
+
)
|
| 210 |
+
print(f"Collection updated: {collection.url}")
|
| 211 |
+
print(json.dumps(api_object_to_dict(collection), indent=2))
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@collections_cli.command(
|
| 215 |
+
"delete",
|
| 216 |
+
examples=[
|
| 217 |
+
"hf collections delete username/my-collection",
|
| 218 |
+
"hf collections delete username/my-collection --missing-ok",
|
| 219 |
+
],
|
| 220 |
+
)
|
| 221 |
+
def collections_delete(
|
| 222 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 223 |
+
missing_ok: Annotated[
|
| 224 |
+
bool,
|
| 225 |
+
typer.Option(help="Do not raise an error if the collection doesn't exist."),
|
| 226 |
+
] = False,
|
| 227 |
+
token: TokenOpt = None,
|
| 228 |
+
) -> None:
|
| 229 |
+
"""Delete a collection from the Hub."""
|
| 230 |
+
api = get_hf_api(token=token)
|
| 231 |
+
api.delete_collection(collection_slug, missing_ok=missing_ok)
|
| 232 |
+
print(f"Collection deleted: {collection_slug}")
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@collections_cli.command(
|
| 236 |
+
"add-item",
|
| 237 |
+
examples=[
|
| 238 |
+
"hf collections add-item username/my-collection moonshotai/kimi-k2 model",
|
| 239 |
+
'hf collections add-item username/my-collection Qwen/DeepPlanning dataset --note "Useful dataset"',
|
| 240 |
+
"hf collections add-item username/my-collection Tongyi-MAI/Z-Image space",
|
| 241 |
+
],
|
| 242 |
+
)
|
| 243 |
+
def collections_add_item(
|
| 244 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 245 |
+
item_id: Annotated[
|
| 246 |
+
str, typer.Argument(help="The ID of the item to add (repo_id for repos, paper ID for papers).")
|
| 247 |
+
],
|
| 248 |
+
item_type: Annotated[
|
| 249 |
+
CollectionItemType,
|
| 250 |
+
typer.Argument(help="The type of item (model, dataset, space, paper, collection, or bucket)."),
|
| 251 |
+
],
|
| 252 |
+
note: Annotated[
|
| 253 |
+
str | None,
|
| 254 |
+
typer.Option(help="A note to attach to the item (max 500 characters)."),
|
| 255 |
+
] = None,
|
| 256 |
+
exists_ok: Annotated[
|
| 257 |
+
bool,
|
| 258 |
+
typer.Option(help="Do not raise an error if the item is already in the collection."),
|
| 259 |
+
] = False,
|
| 260 |
+
token: TokenOpt = None,
|
| 261 |
+
) -> None:
|
| 262 |
+
"""Add an item to a collection."""
|
| 263 |
+
api = get_hf_api(token=token)
|
| 264 |
+
collection = api.add_collection_item(
|
| 265 |
+
collection_slug=collection_slug,
|
| 266 |
+
item_id=item_id,
|
| 267 |
+
item_type=item_type.value, # type: ignore[arg-type]
|
| 268 |
+
note=note,
|
| 269 |
+
exists_ok=exists_ok,
|
| 270 |
+
)
|
| 271 |
+
print(f"Item added to collection: {collection_slug}")
|
| 272 |
+
print(json.dumps(api_object_to_dict(collection), indent=2))
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@collections_cli.command(
|
| 276 |
+
"update-item",
|
| 277 |
+
examples=[
|
| 278 |
+
'hf collections update-item username/my-collection ITEM_OBJECT_ID --note "Updated note"',
|
| 279 |
+
"hf collections update-item username/my-collection ITEM_OBJECT_ID --position 0",
|
| 280 |
+
],
|
| 281 |
+
)
|
| 282 |
+
def collections_update_item(
|
| 283 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 284 |
+
item_object_id: Annotated[
|
| 285 |
+
str,
|
| 286 |
+
typer.Argument(help="The ID of the item in the collection (from 'item_object_id' field, not the repo_id)."),
|
| 287 |
+
],
|
| 288 |
+
note: Annotated[
|
| 289 |
+
str | None,
|
| 290 |
+
typer.Option(help="A new note for the item (max 500 characters)."),
|
| 291 |
+
] = None,
|
| 292 |
+
position: Annotated[
|
| 293 |
+
int | None,
|
| 294 |
+
typer.Option(help="The new position of the item in the collection."),
|
| 295 |
+
] = None,
|
| 296 |
+
token: TokenOpt = None,
|
| 297 |
+
) -> None:
|
| 298 |
+
"""Update an item in a collection."""
|
| 299 |
+
api = get_hf_api(token=token)
|
| 300 |
+
api.update_collection_item(
|
| 301 |
+
collection_slug=collection_slug,
|
| 302 |
+
item_object_id=item_object_id,
|
| 303 |
+
note=note,
|
| 304 |
+
position=position,
|
| 305 |
+
)
|
| 306 |
+
print(f"Item updated in collection: {collection_slug}")
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
@collections_cli.command("delete-item")
|
| 310 |
+
def collections_delete_item(
|
| 311 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 312 |
+
item_object_id: Annotated[
|
| 313 |
+
str,
|
| 314 |
+
typer.Argument(
|
| 315 |
+
help="The ID of the item in the collection (retrieved from `item_object_id` field returned by 'hf collections info'."
|
| 316 |
+
),
|
| 317 |
+
],
|
| 318 |
+
missing_ok: Annotated[
|
| 319 |
+
bool,
|
| 320 |
+
typer.Option(help="Do not raise an error if the item doesn't exist."),
|
| 321 |
+
] = False,
|
| 322 |
+
token: TokenOpt = None,
|
| 323 |
+
) -> None:
|
| 324 |
+
"""Delete an item from a collection."""
|
| 325 |
+
api = get_hf_api(token=token)
|
| 326 |
+
api.delete_collection_item(
|
| 327 |
+
collection_slug=collection_slug,
|
| 328 |
+
item_object_id=item_object_id,
|
| 329 |
+
missing_ok=missing_ok,
|
| 330 |
+
)
|
| 331 |
+
print(f"Item deleted from collection: {collection_slug}")
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/datasets.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with datasets on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# list datasets on the Hub
|
| 18 |
+
hf datasets ls
|
| 19 |
+
|
| 20 |
+
# list datasets with a search query
|
| 21 |
+
hf datasets ls --search "code"
|
| 22 |
+
|
| 23 |
+
# get info about a dataset
|
| 24 |
+
hf datasets info HuggingFaceFW/fineweb
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import enum
|
| 28 |
+
from typing import Annotated, get_args
|
| 29 |
+
|
| 30 |
+
import typer
|
| 31 |
+
|
| 32 |
+
from huggingface_hub._dataset_viewer import execute_raw_sql_query
|
| 33 |
+
from huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundError
|
| 34 |
+
from huggingface_hub.hf_api import DatasetSort_T, ExpandDatasetProperty_T
|
| 35 |
+
|
| 36 |
+
from ._cli_utils import (
|
| 37 |
+
AuthorOpt,
|
| 38 |
+
FilterOpt,
|
| 39 |
+
FormatWithAutoOpt,
|
| 40 |
+
LimitOpt,
|
| 41 |
+
RevisionOpt,
|
| 42 |
+
SearchOpt,
|
| 43 |
+
TokenOpt,
|
| 44 |
+
api_object_to_dict,
|
| 45 |
+
get_hf_api,
|
| 46 |
+
make_expand_properties_parser,
|
| 47 |
+
typer_factory,
|
| 48 |
+
)
|
| 49 |
+
from ._output import OutputFormatWithAuto, out
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
_EXPAND_PROPERTIES = sorted(get_args(ExpandDatasetProperty_T))
|
| 53 |
+
_SORT_OPTIONS = get_args(DatasetSort_T)
|
| 54 |
+
DatasetSortEnum = enum.Enum("DatasetSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
ExpandOpt = Annotated[
|
| 58 |
+
str | None,
|
| 59 |
+
typer.Option(
|
| 60 |
+
help=f"Comma-separated properties to return. When used, only the listed properties (and id) are returned. Example: '--expand=downloads,likes,tags'. Valid: {', '.join(_EXPAND_PROPERTIES)}.",
|
| 61 |
+
callback=make_expand_properties_parser(_EXPAND_PROPERTIES),
|
| 62 |
+
),
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
datasets_cli = typer_factory(help="Interact with datasets on the Hub.")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@datasets_cli.command(
|
| 70 |
+
"list | ls",
|
| 71 |
+
examples=[
|
| 72 |
+
"hf datasets ls",
|
| 73 |
+
"hf datasets ls --sort downloads --limit 10",
|
| 74 |
+
'hf datasets ls --search "code"',
|
| 75 |
+
],
|
| 76 |
+
)
|
| 77 |
+
def datasets_ls(
|
| 78 |
+
search: SearchOpt = None,
|
| 79 |
+
author: AuthorOpt = None,
|
| 80 |
+
filter: FilterOpt = None,
|
| 81 |
+
sort: Annotated[
|
| 82 |
+
DatasetSortEnum | None,
|
| 83 |
+
typer.Option(help="Sort results."),
|
| 84 |
+
] = None,
|
| 85 |
+
limit: LimitOpt = 10,
|
| 86 |
+
expand: ExpandOpt = None,
|
| 87 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 88 |
+
token: TokenOpt = None,
|
| 89 |
+
) -> None:
|
| 90 |
+
"""List datasets on the Hub."""
|
| 91 |
+
api = get_hf_api(token=token)
|
| 92 |
+
sort_key = sort.value if sort else None
|
| 93 |
+
results = [
|
| 94 |
+
api_object_to_dict(dataset_info)
|
| 95 |
+
for dataset_info in api.list_datasets(
|
| 96 |
+
filter=filter,
|
| 97 |
+
author=author,
|
| 98 |
+
search=search,
|
| 99 |
+
sort=sort_key,
|
| 100 |
+
limit=limit,
|
| 101 |
+
expand=expand, # type: ignore
|
| 102 |
+
)
|
| 103 |
+
]
|
| 104 |
+
out.table(results)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@datasets_cli.command(
|
| 108 |
+
"info",
|
| 109 |
+
examples=[
|
| 110 |
+
"hf datasets info HuggingFaceFW/fineweb",
|
| 111 |
+
"hf datasets info my-dataset --expand downloads,likes,tags",
|
| 112 |
+
],
|
| 113 |
+
)
|
| 114 |
+
def datasets_info(
|
| 115 |
+
dataset_id: Annotated[str, typer.Argument(help="The dataset ID (e.g. `username/repo-name`).")],
|
| 116 |
+
revision: RevisionOpt = None,
|
| 117 |
+
expand: ExpandOpt = None,
|
| 118 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 119 |
+
token: TokenOpt = None,
|
| 120 |
+
) -> None:
|
| 121 |
+
"""Get info about a dataset on the Hub."""
|
| 122 |
+
api = get_hf_api(token=token)
|
| 123 |
+
try:
|
| 124 |
+
info = api.dataset_info(repo_id=dataset_id, revision=revision, expand=expand) # type: ignore
|
| 125 |
+
except RepositoryNotFoundError as e:
|
| 126 |
+
raise CLIError(f"Dataset '{dataset_id}' not found.") from e
|
| 127 |
+
except RevisionNotFoundError as e:
|
| 128 |
+
raise CLIError(f"Revision '{revision}' not found on '{dataset_id}'.") from e
|
| 129 |
+
out.dict(info)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@datasets_cli.command(
|
| 133 |
+
"parquet",
|
| 134 |
+
examples=[
|
| 135 |
+
"hf datasets parquet cfahlgren1/hub-stats",
|
| 136 |
+
"hf datasets parquet cfahlgren1/hub-stats --subset models",
|
| 137 |
+
"hf datasets parquet cfahlgren1/hub-stats --split train",
|
| 138 |
+
"hf datasets parquet cfahlgren1/hub-stats --format json",
|
| 139 |
+
],
|
| 140 |
+
)
|
| 141 |
+
def datasets_parquet(
|
| 142 |
+
dataset_id: Annotated[str, typer.Argument(help="The dataset ID (e.g. `username/repo-name`).")],
|
| 143 |
+
subset: Annotated[str | None, typer.Option("--subset", help="Filter parquet entries by subset/config.")] = None,
|
| 144 |
+
split: Annotated[str | None, typer.Option(help="Filter parquet entries by split.")] = None,
|
| 145 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 146 |
+
token: TokenOpt = None,
|
| 147 |
+
) -> None:
|
| 148 |
+
"""List parquet file URLs available for a dataset."""
|
| 149 |
+
api = get_hf_api(token=token)
|
| 150 |
+
entries = api.list_dataset_parquet_files(repo_id=dataset_id, config=subset)
|
| 151 |
+
filtered = [entry for entry in entries if split is None or entry.split == split]
|
| 152 |
+
results = [
|
| 153 |
+
{"subset": entry.config, "split": entry.split, "url": entry.url, "size": entry.size} for entry in filtered
|
| 154 |
+
]
|
| 155 |
+
out.table(results, headers=["subset", "split", "url", "size"], id_key="url")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@datasets_cli.command(
|
| 159 |
+
"sql",
|
| 160 |
+
examples=[
|
| 161 |
+
"hf datasets sql \"SELECT COUNT(*) AS rows FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet')\"",
|
| 162 |
+
"hf datasets sql \"SELECT * FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet') LIMIT 5\" --format json",
|
| 163 |
+
],
|
| 164 |
+
)
|
| 165 |
+
def datasets_sql(
|
| 166 |
+
sql: Annotated[str, typer.Argument(help="Raw SQL query to execute.")],
|
| 167 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 168 |
+
token: TokenOpt = None,
|
| 169 |
+
) -> None:
|
| 170 |
+
"""Execute a raw SQL query with DuckDB against dataset parquet URLs."""
|
| 171 |
+
try:
|
| 172 |
+
result = execute_raw_sql_query(sql_query=sql, token=token)
|
| 173 |
+
except ImportError as e:
|
| 174 |
+
raise CLIError(str(e)) from e
|
| 175 |
+
out.table(result)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/deprecated_cli.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deprecated `huggingface-cli` entry point. Warns and exits."""
|
| 2 |
+
|
| 3 |
+
import shutil
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from ._output import out
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main() -> None:
|
| 10 |
+
out.warning("`huggingface-cli` is deprecated and no longer works. Use `hf` instead.\n")
|
| 11 |
+
|
| 12 |
+
if shutil.which("hf"):
|
| 13 |
+
from huggingface_hub.cli._cli_utils import check_cli_update
|
| 14 |
+
|
| 15 |
+
check_cli_update("huggingface_hub")
|
| 16 |
+
out.hint("`hf` is already installed! Use it directly.\n")
|
| 17 |
+
else:
|
| 18 |
+
out.hint(
|
| 19 |
+
"Install `hf`:\n"
|
| 20 |
+
" Standalone (recommended): curl -LsSf https://hf.co/cli/install.sh | bash\n"
|
| 21 |
+
" Using Homebrew: brew install hf\n"
|
| 22 |
+
" Using pip: pip install huggingface_hub\n",
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
out.hint(
|
| 26 |
+
"Examples:\n"
|
| 27 |
+
" hf auth login\n"
|
| 28 |
+
" hf download unsloth/gemma-4-31B-it-GGUF\n"
|
| 29 |
+
" hf upload my-cool-model . .\n"
|
| 30 |
+
' hf models ls --search "gemma"\n'
|
| 31 |
+
" hf repos ls --format json\n"
|
| 32 |
+
" hf jobs run python:3.12 python -c 'print(\"Hello!\")'\n"
|
| 33 |
+
" hf --help\n",
|
| 34 |
+
)
|
| 35 |
+
sys.exit(1)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/discussions.py
ADDED
|
@@ -0,0 +1,595 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with discussions and pull requests on the Hugging Face Hub."""
|
| 15 |
+
|
| 16 |
+
import enum
|
| 17 |
+
import json
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Annotated
|
| 21 |
+
|
| 22 |
+
import typer
|
| 23 |
+
|
| 24 |
+
from huggingface_hub import constants
|
| 25 |
+
from huggingface_hub.community import DiscussionComment, DiscussionWithDetails
|
| 26 |
+
from huggingface_hub.utils import ANSI
|
| 27 |
+
|
| 28 |
+
from ._cli_utils import (
|
| 29 |
+
AuthorOpt,
|
| 30 |
+
FormatOpt,
|
| 31 |
+
LimitOpt,
|
| 32 |
+
OutputFormat,
|
| 33 |
+
QuietOpt,
|
| 34 |
+
RepoIdArg,
|
| 35 |
+
RepoType,
|
| 36 |
+
RepoTypeOpt,
|
| 37 |
+
TokenOpt,
|
| 38 |
+
_format_cell,
|
| 39 |
+
api_object_to_dict,
|
| 40 |
+
get_hf_api,
|
| 41 |
+
print_list_output,
|
| 42 |
+
typer_factory,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class DiscussionStatus(str, enum.Enum):
|
| 47 |
+
open = "open"
|
| 48 |
+
closed = "closed"
|
| 49 |
+
merged = "merged"
|
| 50 |
+
draft = "draft"
|
| 51 |
+
all = "all"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class DiscussionKind(str, enum.Enum):
|
| 55 |
+
all = "all"
|
| 56 |
+
discussion = "discussion"
|
| 57 |
+
pull_request = "pull_request"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class InfoFormat(str, enum.Enum):
|
| 61 |
+
"""Output format for the info command."""
|
| 62 |
+
|
| 63 |
+
text = "text"
|
| 64 |
+
json = "json"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# "merged" and "draft" are valid Discussion statuses but the Hub API filter
|
| 68 |
+
# (DiscussionStatusFilter) only accepts "all", "open", "closed". When the user
|
| 69 |
+
# asks for merged/draft we fetch with api_status=None (i.e. all) and filter
|
| 70 |
+
# client-side.
|
| 71 |
+
_CLIENT_SIDE_STATUSES = {"merged", "draft"}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
DiscussionNumArg = Annotated[
|
| 75 |
+
int,
|
| 76 |
+
typer.Argument(
|
| 77 |
+
help="The discussion or pull request number.",
|
| 78 |
+
min=1,
|
| 79 |
+
),
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _format_status(status: str) -> str:
|
| 84 |
+
match status:
|
| 85 |
+
case "open":
|
| 86 |
+
return ANSI.green("open")
|
| 87 |
+
case "closed":
|
| 88 |
+
return ANSI.red("closed")
|
| 89 |
+
case "merged":
|
| 90 |
+
return ANSI.blue("merged")
|
| 91 |
+
case "draft":
|
| 92 |
+
return ANSI.yellow("draft")
|
| 93 |
+
case _:
|
| 94 |
+
return status
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _read_body(body: str | None, body_file: Path | None) -> str | None:
|
| 98 |
+
"""Resolve body text from --body or --body-file (supports '-' for stdin)."""
|
| 99 |
+
if body is not None and body_file is not None:
|
| 100 |
+
raise typer.BadParameter("Cannot use both --body and --body-file.")
|
| 101 |
+
if body_file is not None:
|
| 102 |
+
if str(body_file) == "-":
|
| 103 |
+
return sys.stdin.read()
|
| 104 |
+
return body_file.read_text(encoding="utf-8")
|
| 105 |
+
return body
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _print_discussion_info(details: DiscussionWithDetails, show_comments: bool = False) -> None:
|
| 109 |
+
kind = "Pull Request" if details.is_pull_request else "Discussion"
|
| 110 |
+
|
| 111 |
+
print(f"{ANSI.bold(details.title)} {ANSI.gray(f'#{details.num}')}")
|
| 112 |
+
parts = [_format_status(details.status), details.author, details.created_at.strftime("%Y-%m-%d %H:%M")]
|
| 113 |
+
if details.is_pull_request and details.target_branch:
|
| 114 |
+
parts.append(f"into {ANSI.bold(details.target_branch)}")
|
| 115 |
+
print(f"{kind}: {' · '.join(parts)}")
|
| 116 |
+
|
| 117 |
+
if details.is_pull_request and details.conflicting_files:
|
| 118 |
+
if details.conflicting_files is True:
|
| 119 |
+
print(ANSI.yellow("Has conflicting files"))
|
| 120 |
+
else:
|
| 121 |
+
print(ANSI.yellow(f"Conflicting files: {', '.join(details.conflicting_files)}"))
|
| 122 |
+
|
| 123 |
+
body = None
|
| 124 |
+
comments = []
|
| 125 |
+
for event in details.events:
|
| 126 |
+
if isinstance(event, DiscussionComment) and not event.hidden:
|
| 127 |
+
if body is None:
|
| 128 |
+
body = event
|
| 129 |
+
else:
|
| 130 |
+
comments.append(event)
|
| 131 |
+
|
| 132 |
+
if body and body.content.strip():
|
| 133 |
+
print()
|
| 134 |
+
print(body.content.strip())
|
| 135 |
+
|
| 136 |
+
if show_comments and comments:
|
| 137 |
+
print()
|
| 138 |
+
print(ANSI.gray("─" * 60))
|
| 139 |
+
for comment in comments:
|
| 140 |
+
print()
|
| 141 |
+
print(f"{ANSI.bold(comment.author)} · {comment.created_at.strftime('%Y-%m-%d %H:%M')}")
|
| 142 |
+
print(comment.content.strip())
|
| 143 |
+
elif comments:
|
| 144 |
+
print()
|
| 145 |
+
print(ANSI.gray(f"{len(comments)} comment{'s' if len(comments) != 1 else ''} (use --comments to show)"))
|
| 146 |
+
|
| 147 |
+
print()
|
| 148 |
+
print(f"View on Hub: {ANSI.blue(details.url)}")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
discussions_cli = typer_factory(help="Manage discussions and pull requests on the Hub.")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@discussions_cli.command(
|
| 155 |
+
"list | ls",
|
| 156 |
+
examples=[
|
| 157 |
+
"hf discussions list username/my-model",
|
| 158 |
+
"hf discussions list username/my-model --kind pull_request --status merged",
|
| 159 |
+
"hf discussions list username/my-dataset --type dataset --status closed",
|
| 160 |
+
"hf discussions list username/my-model --author alice --format json",
|
| 161 |
+
],
|
| 162 |
+
)
|
| 163 |
+
def discussion_list(
|
| 164 |
+
repo_id: RepoIdArg,
|
| 165 |
+
status: Annotated[
|
| 166 |
+
DiscussionStatus,
|
| 167 |
+
typer.Option(
|
| 168 |
+
"-s",
|
| 169 |
+
"--status",
|
| 170 |
+
help="Filter by status (open, closed, merged, draft, all).",
|
| 171 |
+
),
|
| 172 |
+
] = DiscussionStatus.open,
|
| 173 |
+
kind: Annotated[
|
| 174 |
+
DiscussionKind,
|
| 175 |
+
typer.Option(
|
| 176 |
+
"-k",
|
| 177 |
+
"--kind",
|
| 178 |
+
help="Filter by kind (discussion, pull_request, all).",
|
| 179 |
+
),
|
| 180 |
+
] = DiscussionKind.all,
|
| 181 |
+
author: AuthorOpt = None,
|
| 182 |
+
limit: LimitOpt = 30,
|
| 183 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 184 |
+
format: FormatOpt = OutputFormat.table,
|
| 185 |
+
quiet: QuietOpt = False,
|
| 186 |
+
token: TokenOpt = None,
|
| 187 |
+
) -> None:
|
| 188 |
+
"""List discussions and pull requests on a repo."""
|
| 189 |
+
api = get_hf_api(token=token)
|
| 190 |
+
|
| 191 |
+
api_status: constants.DiscussionStatusFilter | None
|
| 192 |
+
if status == DiscussionStatus.open:
|
| 193 |
+
api_status = "open"
|
| 194 |
+
elif status == DiscussionStatus.closed:
|
| 195 |
+
api_status = "closed"
|
| 196 |
+
else:
|
| 197 |
+
api_status = None
|
| 198 |
+
|
| 199 |
+
api_discussion_type: constants.DiscussionTypeFilter | None
|
| 200 |
+
if kind == DiscussionKind.all:
|
| 201 |
+
api_discussion_type = None
|
| 202 |
+
else:
|
| 203 |
+
api_discussion_type = kind.value # type: ignore[assignment]
|
| 204 |
+
|
| 205 |
+
discussions = []
|
| 206 |
+
for d in api.get_repo_discussions(
|
| 207 |
+
repo_id=repo_id,
|
| 208 |
+
author=author,
|
| 209 |
+
discussion_type=api_discussion_type,
|
| 210 |
+
discussion_status=api_status,
|
| 211 |
+
repo_type=repo_type.value,
|
| 212 |
+
):
|
| 213 |
+
if status.value in _CLIENT_SIDE_STATUSES and d.status != status.value:
|
| 214 |
+
continue
|
| 215 |
+
discussions.append(d)
|
| 216 |
+
if len(discussions) >= limit:
|
| 217 |
+
break
|
| 218 |
+
|
| 219 |
+
items = [api_object_to_dict(d) for d in discussions]
|
| 220 |
+
|
| 221 |
+
print_list_output(
|
| 222 |
+
items,
|
| 223 |
+
format=format,
|
| 224 |
+
quiet=quiet,
|
| 225 |
+
id_key="num",
|
| 226 |
+
headers=["num", "title", "is_pull_request", "status", "author", "created_at"],
|
| 227 |
+
row_fn=lambda item: [
|
| 228 |
+
f"#{item['num']}",
|
| 229 |
+
_format_cell(item.get("title", ""), max_len=50),
|
| 230 |
+
"PR" if item.get("is_pull_request") else "",
|
| 231 |
+
_format_status(str(item.get("status", ""))),
|
| 232 |
+
str(item.get("author", "")),
|
| 233 |
+
_format_cell(item.get("created_at", "")),
|
| 234 |
+
],
|
| 235 |
+
alignments={"num": "right"},
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@discussions_cli.command(
|
| 240 |
+
"info",
|
| 241 |
+
examples=[
|
| 242 |
+
"hf discussions info username/my-model 5",
|
| 243 |
+
"hf discussions info username/my-model 5 --comments",
|
| 244 |
+
"hf discussions info username/my-model 5 --diff",
|
| 245 |
+
"hf discussions info username/my-model 5 --format json",
|
| 246 |
+
],
|
| 247 |
+
)
|
| 248 |
+
def discussion_info(
|
| 249 |
+
repo_id: RepoIdArg,
|
| 250 |
+
num: DiscussionNumArg,
|
| 251 |
+
comments: Annotated[
|
| 252 |
+
bool,
|
| 253 |
+
typer.Option(
|
| 254 |
+
"--comments",
|
| 255 |
+
help="Show all comments.",
|
| 256 |
+
),
|
| 257 |
+
] = False,
|
| 258 |
+
diff: Annotated[
|
| 259 |
+
bool,
|
| 260 |
+
typer.Option(
|
| 261 |
+
"--diff",
|
| 262 |
+
help="Show the diff (for pull requests).",
|
| 263 |
+
),
|
| 264 |
+
] = False,
|
| 265 |
+
no_color: Annotated[
|
| 266 |
+
bool,
|
| 267 |
+
typer.Option(
|
| 268 |
+
"--no-color",
|
| 269 |
+
help="Disable colored output.",
|
| 270 |
+
),
|
| 271 |
+
] = False,
|
| 272 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 273 |
+
format: Annotated[
|
| 274 |
+
InfoFormat,
|
| 275 |
+
typer.Option(
|
| 276 |
+
help="Output format (text or json).",
|
| 277 |
+
),
|
| 278 |
+
] = InfoFormat.text,
|
| 279 |
+
token: TokenOpt = None,
|
| 280 |
+
) -> None:
|
| 281 |
+
"""Get info about a discussion or pull request."""
|
| 282 |
+
import os
|
| 283 |
+
|
| 284 |
+
if no_color:
|
| 285 |
+
os.environ["NO_COLOR"] = "1"
|
| 286 |
+
|
| 287 |
+
api = get_hf_api(token=token)
|
| 288 |
+
details = api.get_discussion_details(
|
| 289 |
+
repo_id=repo_id,
|
| 290 |
+
discussion_num=num,
|
| 291 |
+
repo_type=repo_type.value,
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
if format == InfoFormat.json:
|
| 295 |
+
result = api_object_to_dict(details)
|
| 296 |
+
if not diff:
|
| 297 |
+
result.pop("diff", None)
|
| 298 |
+
print(json.dumps(result, indent=2))
|
| 299 |
+
return
|
| 300 |
+
|
| 301 |
+
_print_discussion_info(details, show_comments=comments)
|
| 302 |
+
|
| 303 |
+
if diff and details.diff:
|
| 304 |
+
print()
|
| 305 |
+
print(ANSI.gray("─" * 60))
|
| 306 |
+
print(details.diff)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
@discussions_cli.command(
|
| 310 |
+
"create",
|
| 311 |
+
examples=[
|
| 312 |
+
'hf discussions create username/my-model --title "Bug report"',
|
| 313 |
+
'hf discussions create username/my-model --title "Feature request" --body "Please add X"',
|
| 314 |
+
'hf discussions create username/my-model --title "Fix typo" --pull-request',
|
| 315 |
+
'hf discussions create username/my-dataset --type dataset --title "Data quality issue"',
|
| 316 |
+
],
|
| 317 |
+
)
|
| 318 |
+
def discussion_create(
|
| 319 |
+
repo_id: RepoIdArg,
|
| 320 |
+
title: Annotated[
|
| 321 |
+
str,
|
| 322 |
+
typer.Option(
|
| 323 |
+
"--title",
|
| 324 |
+
help="The title of the discussion or pull request.",
|
| 325 |
+
),
|
| 326 |
+
],
|
| 327 |
+
body: Annotated[
|
| 328 |
+
str | None,
|
| 329 |
+
typer.Option(
|
| 330 |
+
"--body",
|
| 331 |
+
help="The description (supports Markdown).",
|
| 332 |
+
),
|
| 333 |
+
] = None,
|
| 334 |
+
body_file: Annotated[
|
| 335 |
+
Path | None,
|
| 336 |
+
typer.Option(
|
| 337 |
+
"--body-file",
|
| 338 |
+
help="Read the description from a file. Use '-' for stdin.",
|
| 339 |
+
),
|
| 340 |
+
] = None,
|
| 341 |
+
pull_request: Annotated[
|
| 342 |
+
bool,
|
| 343 |
+
typer.Option(
|
| 344 |
+
"--pull-request",
|
| 345 |
+
"--pr",
|
| 346 |
+
help="Create a pull request instead of a discussion.",
|
| 347 |
+
),
|
| 348 |
+
] = False,
|
| 349 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 350 |
+
token: TokenOpt = None,
|
| 351 |
+
) -> None:
|
| 352 |
+
"""Create a new discussion or pull request on a repo."""
|
| 353 |
+
description = _read_body(body, body_file)
|
| 354 |
+
api = get_hf_api(token=token)
|
| 355 |
+
discussion = api.create_discussion(
|
| 356 |
+
repo_id=repo_id,
|
| 357 |
+
title=title,
|
| 358 |
+
description=description,
|
| 359 |
+
repo_type=repo_type.value,
|
| 360 |
+
pull_request=pull_request,
|
| 361 |
+
)
|
| 362 |
+
kind = "pull request" if pull_request else "discussion"
|
| 363 |
+
print(f"Created {kind} {ANSI.bold(f'#{discussion.num}')} on {ANSI.bold(repo_id)}")
|
| 364 |
+
if pull_request:
|
| 365 |
+
print(f"Push changes to: {ANSI.bold(f'refs/pr/{discussion.num}')}")
|
| 366 |
+
print(f"View on Hub: {ANSI.blue(discussion.url)}")
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@discussions_cli.command(
|
| 370 |
+
"comment",
|
| 371 |
+
examples=[
|
| 372 |
+
'hf discussions comment username/my-model 5 --body "Thanks for reporting!"',
|
| 373 |
+
'hf discussions comment username/my-model 5 --body "LGTM!"',
|
| 374 |
+
],
|
| 375 |
+
)
|
| 376 |
+
def discussion_comment(
|
| 377 |
+
repo_id: RepoIdArg,
|
| 378 |
+
num: DiscussionNumArg,
|
| 379 |
+
body: Annotated[
|
| 380 |
+
str | None,
|
| 381 |
+
typer.Option(
|
| 382 |
+
"--body",
|
| 383 |
+
help="The comment text (supports Markdown).",
|
| 384 |
+
),
|
| 385 |
+
] = None,
|
| 386 |
+
body_file: Annotated[
|
| 387 |
+
Path | None,
|
| 388 |
+
typer.Option(
|
| 389 |
+
"--body-file",
|
| 390 |
+
help="Read the comment from a file. Use '-' for stdin.",
|
| 391 |
+
),
|
| 392 |
+
] = None,
|
| 393 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 394 |
+
token: TokenOpt = None,
|
| 395 |
+
) -> None:
|
| 396 |
+
"""Comment on a discussion or pull request."""
|
| 397 |
+
comment = _read_body(body, body_file)
|
| 398 |
+
if comment is None:
|
| 399 |
+
raise typer.BadParameter("Either --body or --body-file is required.")
|
| 400 |
+
api = get_hf_api(token=token)
|
| 401 |
+
api.comment_discussion(
|
| 402 |
+
repo_id=repo_id,
|
| 403 |
+
discussion_num=num,
|
| 404 |
+
comment=comment,
|
| 405 |
+
repo_type=repo_type.value,
|
| 406 |
+
)
|
| 407 |
+
print(f"Commented on #{num} in {ANSI.bold(repo_id)}")
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
@discussions_cli.command(
|
| 411 |
+
"close",
|
| 412 |
+
examples=[
|
| 413 |
+
"hf discussions close username/my-model 5",
|
| 414 |
+
'hf discussions close username/my-model 5 --comment "Closing as resolved."',
|
| 415 |
+
],
|
| 416 |
+
)
|
| 417 |
+
def discussion_close(
|
| 418 |
+
repo_id: RepoIdArg,
|
| 419 |
+
num: DiscussionNumArg,
|
| 420 |
+
comment: Annotated[
|
| 421 |
+
str | None,
|
| 422 |
+
typer.Option(
|
| 423 |
+
"--comment",
|
| 424 |
+
help="An optional comment to post when closing.",
|
| 425 |
+
),
|
| 426 |
+
] = None,
|
| 427 |
+
yes: Annotated[
|
| 428 |
+
bool,
|
| 429 |
+
typer.Option(
|
| 430 |
+
"--yes",
|
| 431 |
+
"-y",
|
| 432 |
+
help="Skip confirmation prompt.",
|
| 433 |
+
),
|
| 434 |
+
] = False,
|
| 435 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 436 |
+
token: TokenOpt = None,
|
| 437 |
+
) -> None:
|
| 438 |
+
"""Close a discussion or pull request."""
|
| 439 |
+
if not yes:
|
| 440 |
+
confirm = typer.confirm(f"Close #{num} on '{repo_id}'?")
|
| 441 |
+
if not confirm:
|
| 442 |
+
print("Aborted.")
|
| 443 |
+
raise typer.Exit()
|
| 444 |
+
api = get_hf_api(token=token)
|
| 445 |
+
api.change_discussion_status(
|
| 446 |
+
repo_id=repo_id,
|
| 447 |
+
discussion_num=num,
|
| 448 |
+
new_status="closed",
|
| 449 |
+
comment=comment,
|
| 450 |
+
repo_type=repo_type.value,
|
| 451 |
+
)
|
| 452 |
+
print(f"Closed #{num} in {ANSI.bold(repo_id)}")
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
@discussions_cli.command(
|
| 456 |
+
"reopen",
|
| 457 |
+
examples=[
|
| 458 |
+
"hf discussions reopen username/my-model 5",
|
| 459 |
+
'hf discussions reopen username/my-model 5 --comment "Reopening for further investigation."',
|
| 460 |
+
],
|
| 461 |
+
)
|
| 462 |
+
def discussion_reopen(
|
| 463 |
+
repo_id: RepoIdArg,
|
| 464 |
+
num: DiscussionNumArg,
|
| 465 |
+
comment: Annotated[
|
| 466 |
+
str | None,
|
| 467 |
+
typer.Option(
|
| 468 |
+
"--comment",
|
| 469 |
+
help="An optional comment to post when reopening.",
|
| 470 |
+
),
|
| 471 |
+
] = None,
|
| 472 |
+
yes: Annotated[
|
| 473 |
+
bool,
|
| 474 |
+
typer.Option(
|
| 475 |
+
"--yes",
|
| 476 |
+
"-y",
|
| 477 |
+
help="Skip confirmation prompt.",
|
| 478 |
+
),
|
| 479 |
+
] = False,
|
| 480 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 481 |
+
token: TokenOpt = None,
|
| 482 |
+
) -> None:
|
| 483 |
+
"""Reopen a closed discussion or pull request."""
|
| 484 |
+
if not yes:
|
| 485 |
+
confirm = typer.confirm(f"Reopen #{num} on '{repo_id}'?")
|
| 486 |
+
if not confirm:
|
| 487 |
+
print("Aborted.")
|
| 488 |
+
raise typer.Exit()
|
| 489 |
+
api = get_hf_api(token=token)
|
| 490 |
+
api.change_discussion_status(
|
| 491 |
+
repo_id=repo_id,
|
| 492 |
+
discussion_num=num,
|
| 493 |
+
new_status="open",
|
| 494 |
+
comment=comment,
|
| 495 |
+
repo_type=repo_type.value,
|
| 496 |
+
)
|
| 497 |
+
print(f"Reopened #{num} in {ANSI.bold(repo_id)}")
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
@discussions_cli.command(
|
| 501 |
+
"rename",
|
| 502 |
+
examples=[
|
| 503 |
+
'hf discussions rename username/my-model 5 "Updated title"',
|
| 504 |
+
],
|
| 505 |
+
)
|
| 506 |
+
def discussion_rename(
|
| 507 |
+
repo_id: RepoIdArg,
|
| 508 |
+
num: DiscussionNumArg,
|
| 509 |
+
new_title: Annotated[
|
| 510 |
+
str,
|
| 511 |
+
typer.Argument(
|
| 512 |
+
help="The new title.",
|
| 513 |
+
),
|
| 514 |
+
],
|
| 515 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 516 |
+
token: TokenOpt = None,
|
| 517 |
+
) -> None:
|
| 518 |
+
"""Rename a discussion or pull request."""
|
| 519 |
+
api = get_hf_api(token=token)
|
| 520 |
+
api.rename_discussion(
|
| 521 |
+
repo_id=repo_id,
|
| 522 |
+
discussion_num=num,
|
| 523 |
+
new_title=new_title,
|
| 524 |
+
repo_type=repo_type.value,
|
| 525 |
+
)
|
| 526 |
+
print(f"Renamed #{num} to {ANSI.bold(new_title)} in {ANSI.bold(repo_id)}")
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
@discussions_cli.command(
|
| 530 |
+
"merge",
|
| 531 |
+
examples=[
|
| 532 |
+
"hf discussions merge username/my-model 5",
|
| 533 |
+
'hf discussions merge username/my-model 5 --comment "Merging, thanks!"',
|
| 534 |
+
],
|
| 535 |
+
)
|
| 536 |
+
def discussion_merge(
|
| 537 |
+
repo_id: RepoIdArg,
|
| 538 |
+
num: DiscussionNumArg,
|
| 539 |
+
comment: Annotated[
|
| 540 |
+
str | None,
|
| 541 |
+
typer.Option(
|
| 542 |
+
"--comment",
|
| 543 |
+
help="An optional comment to post when merging.",
|
| 544 |
+
),
|
| 545 |
+
] = None,
|
| 546 |
+
yes: Annotated[
|
| 547 |
+
bool,
|
| 548 |
+
typer.Option(
|
| 549 |
+
"--yes",
|
| 550 |
+
"-y",
|
| 551 |
+
help="Skip confirmation prompt.",
|
| 552 |
+
),
|
| 553 |
+
] = False,
|
| 554 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 555 |
+
token: TokenOpt = None,
|
| 556 |
+
) -> None:
|
| 557 |
+
"""Merge a pull request."""
|
| 558 |
+
if not yes:
|
| 559 |
+
confirm = typer.confirm(f"Merge #{num} on '{repo_id}'?")
|
| 560 |
+
if not confirm:
|
| 561 |
+
print("Aborted.")
|
| 562 |
+
raise typer.Exit()
|
| 563 |
+
api = get_hf_api(token=token)
|
| 564 |
+
api.merge_pull_request(
|
| 565 |
+
repo_id=repo_id,
|
| 566 |
+
discussion_num=num,
|
| 567 |
+
comment=comment,
|
| 568 |
+
repo_type=repo_type.value,
|
| 569 |
+
)
|
| 570 |
+
print(f"Merged #{num} in {ANSI.bold(repo_id)}")
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
@discussions_cli.command(
|
| 574 |
+
"diff",
|
| 575 |
+
examples=[
|
| 576 |
+
"hf discussions diff username/my-model 5",
|
| 577 |
+
],
|
| 578 |
+
)
|
| 579 |
+
def discussion_diff(
|
| 580 |
+
repo_id: RepoIdArg,
|
| 581 |
+
num: DiscussionNumArg,
|
| 582 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 583 |
+
token: TokenOpt = None,
|
| 584 |
+
) -> None:
|
| 585 |
+
"""Show the diff of a pull request."""
|
| 586 |
+
api = get_hf_api(token=token)
|
| 587 |
+
details = api.get_discussion_details(
|
| 588 |
+
repo_id=repo_id,
|
| 589 |
+
discussion_num=num,
|
| 590 |
+
repo_type=repo_type.value,
|
| 591 |
+
)
|
| 592 |
+
if details.diff:
|
| 593 |
+
print(details.diff)
|
| 594 |
+
else:
|
| 595 |
+
print("No diff available.")
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/download.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 202-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains command to download files from the Hub with the CLI.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
hf download --help
|
| 18 |
+
|
| 19 |
+
# Download file
|
| 20 |
+
hf download gpt2 config.json
|
| 21 |
+
|
| 22 |
+
# Download entire repo
|
| 23 |
+
hf download fffiloni/zeroscope --repo-type=space --revision=refs/pr/78
|
| 24 |
+
|
| 25 |
+
# Download repo with filters
|
| 26 |
+
hf download gpt2 --include="*.safetensors"
|
| 27 |
+
|
| 28 |
+
# Download with token
|
| 29 |
+
hf download Wauplin/private-model --token=hf_***
|
| 30 |
+
|
| 31 |
+
# Download quietly (no progress bar, no warnings, only the returned path)
|
| 32 |
+
hf download gpt2 config.json --quiet
|
| 33 |
+
|
| 34 |
+
# Download to local dir
|
| 35 |
+
hf download gpt2 --local-dir=./models/gpt2
|
| 36 |
+
|
| 37 |
+
# Download a subfolder
|
| 38 |
+
hf download HuggingFaceM4/FineVision art/ --repo-type=dataset
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
import warnings
|
| 42 |
+
from typing import Annotated
|
| 43 |
+
|
| 44 |
+
import typer
|
| 45 |
+
|
| 46 |
+
from huggingface_hub import logging
|
| 47 |
+
from huggingface_hub._snapshot_download import snapshot_download
|
| 48 |
+
from huggingface_hub.errors import CLIError
|
| 49 |
+
from huggingface_hub.file_download import DryRunFileInfo, hf_hub_download
|
| 50 |
+
from huggingface_hub.utils import _format_size, disable_progress_bars, enable_progress_bars, tabulate
|
| 51 |
+
|
| 52 |
+
from ._cli_utils import RepoIdArg, RepoTypeOpt, RevisionOpt, TokenOpt
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
DOWNLOAD_EXAMPLES = [
|
| 56 |
+
"hf download meta-llama/Llama-3.2-1B-Instruct",
|
| 57 |
+
"hf download meta-llama/Llama-3.2-1B-Instruct config.json tokenizer.json",
|
| 58 |
+
'hf download meta-llama/Llama-3.2-1B-Instruct --include "*.safetensors" --exclude "*.bin"',
|
| 59 |
+
"hf download meta-llama/Llama-3.2-1B-Instruct --local-dir ./models/llama",
|
| 60 |
+
"hf download HuggingFaceM4/FineVision art/ --repo-type dataset",
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
logger = logging.get_logger(__name__)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def download(
|
| 68 |
+
repo_id: RepoIdArg,
|
| 69 |
+
filenames: Annotated[
|
| 70 |
+
list[str] | None,
|
| 71 |
+
typer.Argument(
|
| 72 |
+
help="Files to download (e.g. `config.json`, `data/metadata.jsonl`).",
|
| 73 |
+
),
|
| 74 |
+
] = None,
|
| 75 |
+
repo_type: RepoTypeOpt = RepoTypeOpt.model,
|
| 76 |
+
revision: RevisionOpt = None,
|
| 77 |
+
include: Annotated[
|
| 78 |
+
list[str] | None,
|
| 79 |
+
typer.Option(
|
| 80 |
+
help="Glob patterns to include from files to download. eg: *.json",
|
| 81 |
+
),
|
| 82 |
+
] = None,
|
| 83 |
+
exclude: Annotated[
|
| 84 |
+
list[str] | None,
|
| 85 |
+
typer.Option(
|
| 86 |
+
help="Glob patterns to exclude from files to download.",
|
| 87 |
+
),
|
| 88 |
+
] = None,
|
| 89 |
+
cache_dir: Annotated[
|
| 90 |
+
str | None,
|
| 91 |
+
typer.Option(
|
| 92 |
+
help="Directory where to save files.",
|
| 93 |
+
),
|
| 94 |
+
] = None,
|
| 95 |
+
local_dir: Annotated[
|
| 96 |
+
str | None,
|
| 97 |
+
typer.Option(
|
| 98 |
+
help="If set, the downloaded file will be placed under this directory. Check out https://huggingface.co/docs/huggingface_hub/guides/download#download-files-to-a-local-folder for more details.",
|
| 99 |
+
),
|
| 100 |
+
] = None,
|
| 101 |
+
force_download: Annotated[
|
| 102 |
+
bool,
|
| 103 |
+
typer.Option(
|
| 104 |
+
help="If True, the files will be downloaded even if they are already cached.",
|
| 105 |
+
),
|
| 106 |
+
] = False,
|
| 107 |
+
dry_run: Annotated[
|
| 108 |
+
bool,
|
| 109 |
+
typer.Option(
|
| 110 |
+
help="If True, perform a dry run without actually downloading the file.",
|
| 111 |
+
),
|
| 112 |
+
] = False,
|
| 113 |
+
token: TokenOpt = None,
|
| 114 |
+
quiet: Annotated[
|
| 115 |
+
bool,
|
| 116 |
+
typer.Option(
|
| 117 |
+
help="If True, progress bars are disabled and only the path to the download files is printed.",
|
| 118 |
+
),
|
| 119 |
+
] = False,
|
| 120 |
+
max_workers: Annotated[
|
| 121 |
+
int,
|
| 122 |
+
typer.Option(
|
| 123 |
+
help="Maximum number of workers to use for downloading files. Default is 8.",
|
| 124 |
+
),
|
| 125 |
+
] = 8,
|
| 126 |
+
) -> None:
|
| 127 |
+
"""Download files from the Hub."""
|
| 128 |
+
|
| 129 |
+
def run_download() -> str | DryRunFileInfo | list[DryRunFileInfo]:
|
| 130 |
+
filenames_list = filenames if filenames is not None else []
|
| 131 |
+
|
| 132 |
+
# Separate subfolder patterns (ending with '/') from regular filenames
|
| 133 |
+
# Subfolders like "art/" are converted to include patterns like "art/**"
|
| 134 |
+
subfolders = [f for f in filenames_list if f.endswith("/")]
|
| 135 |
+
subfolder_patterns = [f"{f.rstrip('/')}/**" for f in subfolders]
|
| 136 |
+
regular_filenames = [f for f in filenames_list if not f.endswith("/")]
|
| 137 |
+
|
| 138 |
+
# Error if subfolder patterns are combined with --include/--exclude
|
| 139 |
+
# Guide user to use --include instead of subfolder argument
|
| 140 |
+
if len(subfolder_patterns) > 0:
|
| 141 |
+
if include is not None and len(include) > 0:
|
| 142 |
+
raise CLIError(
|
| 143 |
+
f"Cannot combine subfolder argument ('{subfolders[0]}') with `--include`. "
|
| 144 |
+
f'Please use `--include "{subfolders[0]}*"` instead.'
|
| 145 |
+
)
|
| 146 |
+
if exclude is not None and len(exclude) > 0:
|
| 147 |
+
raise CLIError(
|
| 148 |
+
f"Cannot combine subfolder argument ('{subfolders[0]}') with `--exclude`. "
|
| 149 |
+
f'Please use `--include "{subfolders[0]}*"` with `--exclude` instead.'
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# Warn user if patterns are ignored (only if regular filenames are provided)
|
| 153 |
+
if len(regular_filenames) > 0:
|
| 154 |
+
if include is not None and len(include) > 0:
|
| 155 |
+
warnings.warn("Ignoring `--include` since filenames have being explicitly set.")
|
| 156 |
+
if exclude is not None and len(exclude) > 0:
|
| 157 |
+
warnings.warn("Ignoring `--exclude` since filenames have being explicitly set.")
|
| 158 |
+
|
| 159 |
+
# Single file to download (not a subfolder): use `hf_hub_download`
|
| 160 |
+
if len(regular_filenames) == 1 and len(subfolder_patterns) == 0:
|
| 161 |
+
return hf_hub_download(
|
| 162 |
+
repo_id=repo_id,
|
| 163 |
+
repo_type=repo_type.value,
|
| 164 |
+
revision=revision,
|
| 165 |
+
filename=regular_filenames[0],
|
| 166 |
+
cache_dir=cache_dir,
|
| 167 |
+
force_download=force_download,
|
| 168 |
+
token=token,
|
| 169 |
+
local_dir=local_dir,
|
| 170 |
+
library_name="huggingface-cli",
|
| 171 |
+
dry_run=dry_run,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
# Otherwise: use `snapshot_download` to ensure all files comes from same revision
|
| 175 |
+
if len(regular_filenames) == 0 and len(subfolder_patterns) == 0:
|
| 176 |
+
# No filenames provided: use include/exclude patterns
|
| 177 |
+
allow_patterns = include
|
| 178 |
+
ignore_patterns = exclude
|
| 179 |
+
else:
|
| 180 |
+
# Combine regular filenames and subfolder patterns as allow_patterns
|
| 181 |
+
allow_patterns = regular_filenames + subfolder_patterns
|
| 182 |
+
ignore_patterns = None
|
| 183 |
+
|
| 184 |
+
return snapshot_download(
|
| 185 |
+
repo_id=repo_id,
|
| 186 |
+
repo_type=repo_type.value,
|
| 187 |
+
revision=revision,
|
| 188 |
+
allow_patterns=allow_patterns,
|
| 189 |
+
ignore_patterns=ignore_patterns,
|
| 190 |
+
force_download=force_download,
|
| 191 |
+
cache_dir=cache_dir,
|
| 192 |
+
token=token,
|
| 193 |
+
local_dir=local_dir,
|
| 194 |
+
library_name="huggingface-cli",
|
| 195 |
+
max_workers=max_workers,
|
| 196 |
+
dry_run=dry_run,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
def _print_result(result: str | DryRunFileInfo | list[DryRunFileInfo]) -> None:
|
| 200 |
+
if isinstance(result, str):
|
| 201 |
+
print(result)
|
| 202 |
+
return
|
| 203 |
+
|
| 204 |
+
# Print dry run info
|
| 205 |
+
if isinstance(result, DryRunFileInfo):
|
| 206 |
+
result = [result]
|
| 207 |
+
print(
|
| 208 |
+
f"[dry-run] Will download {len([r for r in result if r.will_download])} files (out of {len(result)}) totalling {_format_size(sum(r.file_size for r in result if r.will_download))}."
|
| 209 |
+
)
|
| 210 |
+
columns = ["File", "Bytes to download"]
|
| 211 |
+
items: list[list[str | int]] = []
|
| 212 |
+
for info in sorted(result, key=lambda x: x.filename):
|
| 213 |
+
items.append([info.filename, _format_size(info.file_size) if info.will_download else "-"])
|
| 214 |
+
print(tabulate(items, headers=columns))
|
| 215 |
+
|
| 216 |
+
if quiet:
|
| 217 |
+
disable_progress_bars()
|
| 218 |
+
with warnings.catch_warnings():
|
| 219 |
+
warnings.simplefilter("ignore")
|
| 220 |
+
_print_result(run_download())
|
| 221 |
+
enable_progress_bars()
|
| 222 |
+
else:
|
| 223 |
+
_print_result(run_download())
|
| 224 |
+
logging.set_verbosity_warning()
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/extensions.py
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains helper utilities for hf CLI extensions."""
|
| 15 |
+
|
| 16 |
+
import errno
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import shutil
|
| 21 |
+
import subprocess
|
| 22 |
+
import venv
|
| 23 |
+
from dataclasses import asdict, dataclass
|
| 24 |
+
from datetime import datetime, timezone
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Annotated, Literal
|
| 27 |
+
|
| 28 |
+
import typer
|
| 29 |
+
|
| 30 |
+
from huggingface_hub.errors import CLIError, CLIExtensionInstallError
|
| 31 |
+
from huggingface_hub.utils import StatusLine, get_session, logging
|
| 32 |
+
|
| 33 |
+
from ._cli_utils import FormatOpt, OutputFormat, QuietOpt, print_list_output, typer_factory
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
DEFAULT_EXTENSION_OWNER = "huggingface"
|
| 37 |
+
EXTENSIONS_ROOT = Path("~/.local/share/hf/extensions")
|
| 38 |
+
MANIFEST_FILENAME = "manifest.json"
|
| 39 |
+
EXTENSIONS_HELP = (
|
| 40 |
+
"Manage hf CLI extensions.\n\n"
|
| 41 |
+
"Security Warning: extensions are third-party executables or Python packages. "
|
| 42 |
+
"Install only from sources you trust."
|
| 43 |
+
)
|
| 44 |
+
extensions_cli = typer_factory(help=EXTENSIONS_HELP)
|
| 45 |
+
_EXTENSIONS_DEFAULT_BRANCH = "main" # Fallback when the GitHub API is unreachable.
|
| 46 |
+
_EXTENSIONS_GITHUB_TOPIC = "hf-extension"
|
| 47 |
+
_EXTENSIONS_DOWNLOAD_TIMEOUT = 10
|
| 48 |
+
_EXTENSIONS_PIP_INSTALL_TIMEOUT = 300
|
| 49 |
+
|
| 50 |
+
logger = logging.get_logger(__name__)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass
|
| 54 |
+
class ExtensionManifest:
|
| 55 |
+
owner: str
|
| 56 |
+
repo: str
|
| 57 |
+
repo_id: str
|
| 58 |
+
short_name: str
|
| 59 |
+
executable_name: str
|
| 60 |
+
executable_path: str
|
| 61 |
+
type: Literal["binary", "python"]
|
| 62 |
+
installed_at: datetime
|
| 63 |
+
source: str
|
| 64 |
+
description: str | None = None
|
| 65 |
+
|
| 66 |
+
@classmethod
|
| 67 |
+
def load(cls, path: Path) -> "ExtensionManifest":
|
| 68 |
+
manifest_path = path / MANIFEST_FILENAME
|
| 69 |
+
if not manifest_path.is_file():
|
| 70 |
+
raise CLIError(f"Manifest file not found at {manifest_path}. Your extension may be corrupted.")
|
| 71 |
+
data = json.loads(manifest_path.read_text())
|
| 72 |
+
data["installed_at"] = datetime.fromisoformat(data["installed_at"])
|
| 73 |
+
return ExtensionManifest(**data)
|
| 74 |
+
|
| 75 |
+
def save(self, path: Path) -> None:
|
| 76 |
+
manifest_path = path / MANIFEST_FILENAME
|
| 77 |
+
manifest_path.parent.mkdir(parents=True, exist_ok=True)
|
| 78 |
+
data = asdict(self)
|
| 79 |
+
data["installed_at"] = self.installed_at.isoformat()
|
| 80 |
+
manifest_path.write_text(json.dumps(data, indent=2, sort_keys=True))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@extensions_cli.command(
|
| 84 |
+
"install",
|
| 85 |
+
examples=[
|
| 86 |
+
"hf extensions install hf-claude",
|
| 87 |
+
"hf extensions install hanouticelina/hf-claude",
|
| 88 |
+
"hf extensions install alvarobartt/hf-mem",
|
| 89 |
+
],
|
| 90 |
+
)
|
| 91 |
+
def extension_install(
|
| 92 |
+
ctx: typer.Context,
|
| 93 |
+
repo_id: Annotated[
|
| 94 |
+
str,
|
| 95 |
+
typer.Argument(help="GitHub extension repository in `[OWNER/]hf-<name>` format."),
|
| 96 |
+
],
|
| 97 |
+
force: Annotated[bool, typer.Option("--force", help="Overwrite if already installed.")] = False,
|
| 98 |
+
) -> None:
|
| 99 |
+
"""Install an extension from a public GitHub repository.
|
| 100 |
+
|
| 101 |
+
Security warning: this installs a third-party executable or Python package.
|
| 102 |
+
Install only from sources you trust.
|
| 103 |
+
"""
|
| 104 |
+
owner, repo_name, short_name = _normalize_repo_id(repo_id)
|
| 105 |
+
root_ctx = ctx.find_root()
|
| 106 |
+
reserved_commands = set(getattr(root_ctx.command, "commands", {}).keys())
|
| 107 |
+
if short_name in reserved_commands:
|
| 108 |
+
raise CLIError(
|
| 109 |
+
f"Cannot install extension '{short_name}' because it conflicts with an existing `hf {short_name}` command."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
extension_dir = _get_extension_dir(short_name)
|
| 113 |
+
extension_exists = extension_dir.exists()
|
| 114 |
+
if extension_exists and not force:
|
| 115 |
+
raise CLIError(f"Extension '{short_name}' is already installed. Use --force to overwrite.")
|
| 116 |
+
|
| 117 |
+
branch, description = _resolve_github_repo_info(owner=owner, repo_name=repo_name)
|
| 118 |
+
|
| 119 |
+
if extension_exists:
|
| 120 |
+
shutil.rmtree(extension_dir)
|
| 121 |
+
|
| 122 |
+
manifest = _install_extension_from_github(
|
| 123 |
+
owner=owner,
|
| 124 |
+
repo_name=repo_name,
|
| 125 |
+
short_name=short_name,
|
| 126 |
+
extension_dir=extension_dir,
|
| 127 |
+
branch=branch,
|
| 128 |
+
description=description,
|
| 129 |
+
)
|
| 130 |
+
ext_type = manifest.type.capitalize()
|
| 131 |
+
print(f"{ext_type} extension installed successfully from {owner}/{repo_name}.")
|
| 132 |
+
print(f"Run it with: hf {short_name}")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@extensions_cli.command(
|
| 136 |
+
"exec",
|
| 137 |
+
context_settings={"allow_extra_args": True, "allow_interspersed_args": False, "ignore_unknown_options": True},
|
| 138 |
+
examples=[
|
| 139 |
+
"hf extensions exec claude -- --help",
|
| 140 |
+
"hf extensions exec claude --model zai-org/GLM-5",
|
| 141 |
+
],
|
| 142 |
+
)
|
| 143 |
+
def extension_exec(
|
| 144 |
+
ctx: typer.Context,
|
| 145 |
+
name: Annotated[
|
| 146 |
+
str,
|
| 147 |
+
typer.Argument(help="Extension name (with or without `hf-` prefix)."),
|
| 148 |
+
],
|
| 149 |
+
) -> None:
|
| 150 |
+
"""Execute an installed extension."""
|
| 151 |
+
short_name = _normalize_extension_name(name)
|
| 152 |
+
executable_path = _resolve_installed_executable_path(short_name)
|
| 153 |
+
|
| 154 |
+
if not executable_path.is_file():
|
| 155 |
+
raise CLIError(f"Extension '{short_name}' is not installed.")
|
| 156 |
+
|
| 157 |
+
exit_code = _execute_extension_binary(executable_path=executable_path, args=list(ctx.args))
|
| 158 |
+
raise typer.Exit(code=exit_code)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@extensions_cli.command("list | ls", examples=["hf extensions list"])
|
| 162 |
+
def extension_list(format: FormatOpt = OutputFormat.table, quiet: QuietOpt = False) -> None:
|
| 163 |
+
"""List installed extension commands."""
|
| 164 |
+
rows = [
|
| 165 |
+
{
|
| 166 |
+
"command": f"hf {manifest.short_name}",
|
| 167 |
+
"source": str(manifest.repo_id),
|
| 168 |
+
"type": str(manifest.type),
|
| 169 |
+
"installed": manifest.installed_at.strftime("%Y-%m-%d"),
|
| 170 |
+
"description": manifest.description,
|
| 171 |
+
}
|
| 172 |
+
for manifest in _list_installed_extensions()
|
| 173 |
+
]
|
| 174 |
+
print_list_output(rows, format=format, quiet=quiet, id_key="command")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@extensions_cli.command("search", examples=["hf extensions search"])
|
| 178 |
+
def extension_search(format: FormatOpt = OutputFormat.table, quiet: QuietOpt = False) -> None:
|
| 179 |
+
"""Search extensions available on GitHub (tagged with 'hf-extension' topic)."""
|
| 180 |
+
response = get_session().get(
|
| 181 |
+
"https://api.github.com/search/repositories",
|
| 182 |
+
params={"q": f"topic:{_EXTENSIONS_GITHUB_TOPIC}", "sort": "stars", "order": "desc", "per_page": 100},
|
| 183 |
+
follow_redirects=True,
|
| 184 |
+
timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT,
|
| 185 |
+
)
|
| 186 |
+
response.raise_for_status()
|
| 187 |
+
data = response.json()
|
| 188 |
+
|
| 189 |
+
installed = {m.short_name for m in _list_installed_extensions()}
|
| 190 |
+
|
| 191 |
+
rows = []
|
| 192 |
+
for repo in data.get("items", []):
|
| 193 |
+
repo_name = repo["name"]
|
| 194 |
+
short_name = repo_name[3:] if repo_name.startswith("hf-") else repo_name
|
| 195 |
+
rows.append(
|
| 196 |
+
{
|
| 197 |
+
"name": short_name,
|
| 198 |
+
"repo": repo["full_name"],
|
| 199 |
+
"stars": repo.get("stargazers_count", 0),
|
| 200 |
+
"description": repo.get("description") or "",
|
| 201 |
+
"installed": "yes" if short_name in installed else "",
|
| 202 |
+
}
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
print_list_output(rows, format=format, quiet=quiet, id_key="repo", alignments={"stars": "right"})
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@extensions_cli.command("remove | rm", examples=["hf extensions remove claude"])
|
| 209 |
+
def extension_remove(
|
| 210 |
+
name: Annotated[
|
| 211 |
+
str,
|
| 212 |
+
typer.Argument(help="Extension name to remove (with or without `hf-` prefix)."),
|
| 213 |
+
],
|
| 214 |
+
) -> None:
|
| 215 |
+
"""Remove an installed extension."""
|
| 216 |
+
short_name = _normalize_extension_name(name)
|
| 217 |
+
extension_dir = _get_extension_dir(short_name)
|
| 218 |
+
|
| 219 |
+
if not extension_dir.is_dir():
|
| 220 |
+
raise CLIError(f"Extension '{short_name}' is not installed.")
|
| 221 |
+
|
| 222 |
+
shutil.rmtree(extension_dir)
|
| 223 |
+
print(f"Removed extension '{short_name}'.")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
### HELPER FUNCTIONS
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _list_installed_extensions() -> list[ExtensionManifest]:
|
| 230 |
+
"""Return manifests for all validly-installed extensions, sorted by directory name."""
|
| 231 |
+
root_dir = EXTENSIONS_ROOT.expanduser()
|
| 232 |
+
if not root_dir.is_dir():
|
| 233 |
+
return []
|
| 234 |
+
manifests = []
|
| 235 |
+
for extension_dir in sorted(root_dir.iterdir()):
|
| 236 |
+
if not extension_dir.is_dir() or not extension_dir.name.startswith("hf-"):
|
| 237 |
+
continue
|
| 238 |
+
try:
|
| 239 |
+
manifests.append(ExtensionManifest.load(extension_dir))
|
| 240 |
+
except Exception as e:
|
| 241 |
+
logger.debug(f"Failed to load manifest for extension '{extension_dir.name}': {e}")
|
| 242 |
+
continue
|
| 243 |
+
return manifests
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def list_installed_extensions_for_help() -> list[tuple[str, str]]:
|
| 247 |
+
entries = []
|
| 248 |
+
for manifest in _list_installed_extensions():
|
| 249 |
+
tag = f"[extension {manifest.repo_id}]"
|
| 250 |
+
help_text = f"{manifest.description} {tag}" if manifest.description is not None else tag
|
| 251 |
+
entries.append((manifest.short_name, help_text))
|
| 252 |
+
return entries
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def dispatch_unknown_top_level_extension(args: list[str], known_commands: set[str]) -> int | None:
|
| 256 |
+
if not args:
|
| 257 |
+
return None
|
| 258 |
+
|
| 259 |
+
command_name = args[0]
|
| 260 |
+
if command_name.startswith("-"):
|
| 261 |
+
return None
|
| 262 |
+
all_known = {a.strip() for cmd in known_commands for a in cmd.split("|")}
|
| 263 |
+
if command_name in all_known:
|
| 264 |
+
return None
|
| 265 |
+
|
| 266 |
+
short_name = command_name[3:] if command_name.startswith("hf-") else command_name
|
| 267 |
+
if not short_name:
|
| 268 |
+
return None
|
| 269 |
+
|
| 270 |
+
executable_path: Path | None = None
|
| 271 |
+
try:
|
| 272 |
+
executable_path = _resolve_installed_executable_path(short_name)
|
| 273 |
+
except Exception:
|
| 274 |
+
executable_path = _auto_install_official_extension(short_name)
|
| 275 |
+
|
| 276 |
+
if executable_path is None or not executable_path.is_file():
|
| 277 |
+
return None
|
| 278 |
+
|
| 279 |
+
return _execute_extension_binary(executable_path=executable_path, args=list(args[1:]))
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _auto_install_official_extension(short_name: str) -> Path | None:
|
| 283 |
+
"""Try to auto-install huggingface/hf-<name>. Returns executable path or None."""
|
| 284 |
+
owner, repo_name = DEFAULT_EXTENSION_OWNER, f"hf-{short_name}"
|
| 285 |
+
try:
|
| 286 |
+
extension_dir = _get_extension_dir(short_name)
|
| 287 |
+
except Exception:
|
| 288 |
+
return None
|
| 289 |
+
if extension_dir.exists():
|
| 290 |
+
return None
|
| 291 |
+
try:
|
| 292 |
+
response = get_session().get(
|
| 293 |
+
f"https://api.github.com/repos/{owner}/{repo_name}",
|
| 294 |
+
follow_redirects=True,
|
| 295 |
+
timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT,
|
| 296 |
+
)
|
| 297 |
+
if response.status_code == 404:
|
| 298 |
+
return None
|
| 299 |
+
response.raise_for_status()
|
| 300 |
+
branch = response.json()["default_branch"]
|
| 301 |
+
except Exception:
|
| 302 |
+
return None
|
| 303 |
+
if not typer.confirm(f"'{short_name}' is an official Hugging Face extension ({owner}/{repo_name}). Install it?"):
|
| 304 |
+
return None
|
| 305 |
+
try:
|
| 306 |
+
manifest = _install_extension_from_github(
|
| 307 |
+
owner=owner, repo_name=repo_name, short_name=short_name, extension_dir=extension_dir, branch=branch
|
| 308 |
+
)
|
| 309 |
+
return Path(manifest.executable_path).expanduser()
|
| 310 |
+
except Exception:
|
| 311 |
+
shutil.rmtree(extension_dir, ignore_errors=True)
|
| 312 |
+
return None
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def _install_extension_from_github(
|
| 316 |
+
*,
|
| 317 |
+
owner: str,
|
| 318 |
+
repo_name: str,
|
| 319 |
+
short_name: str,
|
| 320 |
+
extension_dir: Path,
|
| 321 |
+
branch: str,
|
| 322 |
+
description: str | None = None,
|
| 323 |
+
) -> ExtensionManifest:
|
| 324 |
+
"""Fetch, install (binary or Python), and save manifest for a GitHub extension."""
|
| 325 |
+
try:
|
| 326 |
+
binary = _fetch_remote_binary(owner=owner, repo_name=repo_name, branch=branch, short_name=short_name)
|
| 327 |
+
except Exception:
|
| 328 |
+
binary = None
|
| 329 |
+
if binary is not None:
|
| 330 |
+
manifest = _install_binary_extension(
|
| 331 |
+
owner=owner, repo_name=repo_name, short_name=short_name, extension_dir=extension_dir, binary=binary
|
| 332 |
+
)
|
| 333 |
+
else:
|
| 334 |
+
manifest = _install_python_extension(
|
| 335 |
+
owner=owner, repo_name=repo_name, short_name=short_name, extension_dir=extension_dir, branch=branch
|
| 336 |
+
)
|
| 337 |
+
manifest.description = _try_fetch_remote_description(
|
| 338 |
+
owner=owner, repo_name=repo_name, branch=branch, candidate_description=description
|
| 339 |
+
)
|
| 340 |
+
manifest.save(extension_dir)
|
| 341 |
+
return manifest
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def _fetch_remote_binary(owner: str, repo_name: str, branch: str, short_name: str) -> bytes:
|
| 345 |
+
executable_name = _get_executable_name(short_name)
|
| 346 |
+
raw_url = f"https://raw.githubusercontent.com/{owner}/{repo_name}/refs/heads/{branch}/{executable_name}"
|
| 347 |
+
response = get_session().get(raw_url, follow_redirects=True, timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT)
|
| 348 |
+
response.raise_for_status()
|
| 349 |
+
return response.content
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _install_binary_extension(
|
| 353 |
+
*, owner: str, repo_name: str, short_name: str, extension_dir: Path, binary: bytes
|
| 354 |
+
) -> ExtensionManifest:
|
| 355 |
+
# Save extension binary
|
| 356 |
+
executable_name = _get_executable_name(short_name)
|
| 357 |
+
extension_dir.mkdir(parents=True, exist_ok=False)
|
| 358 |
+
executable_path = extension_dir / executable_name
|
| 359 |
+
executable_path.write_bytes(binary)
|
| 360 |
+
|
| 361 |
+
# Make it executable
|
| 362 |
+
if os.name != "nt":
|
| 363 |
+
os.chmod(executable_path, 0o755)
|
| 364 |
+
|
| 365 |
+
# Create manifest
|
| 366 |
+
return ExtensionManifest(
|
| 367 |
+
owner=owner,
|
| 368 |
+
repo=repo_name,
|
| 369 |
+
repo_id=f"{owner}/{repo_name}",
|
| 370 |
+
short_name=short_name,
|
| 371 |
+
executable_name=executable_name,
|
| 372 |
+
executable_path=str(executable_path),
|
| 373 |
+
type="binary",
|
| 374 |
+
installed_at=datetime.now(timezone.utc),
|
| 375 |
+
source=f"https://github.com/{owner}/{repo_name}",
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _install_python_extension(
|
| 380 |
+
*, owner: str, repo_name: str, short_name: str, extension_dir: Path, branch: str
|
| 381 |
+
) -> ExtensionManifest:
|
| 382 |
+
source_url = f"https://github.com/{owner}/{repo_name}/archive/refs/heads/{branch}.zip"
|
| 383 |
+
venv_dir = extension_dir / "venv"
|
| 384 |
+
installed = False
|
| 385 |
+
|
| 386 |
+
status = StatusLine()
|
| 387 |
+
try:
|
| 388 |
+
status.update(f"Creating virtual environment in {venv_dir}")
|
| 389 |
+
if extension_dir.exists():
|
| 390 |
+
shutil.rmtree(extension_dir, ignore_errors=True)
|
| 391 |
+
extension_dir.mkdir(parents=True, exist_ok=False)
|
| 392 |
+
|
| 393 |
+
uv_path = shutil.which("uv")
|
| 394 |
+
venv_python = _get_venv_python_path(venv_dir)
|
| 395 |
+
if uv_path:
|
| 396 |
+
subprocess.run([uv_path, "venv", str(venv_dir)], check=True)
|
| 397 |
+
status.done(f"Virtual environment created in {venv_dir}")
|
| 398 |
+
|
| 399 |
+
status.update(f"Installing package from {source_url}")
|
| 400 |
+
subprocess.run(
|
| 401 |
+
[uv_path, "pip", "install", "--python", str(venv_python), source_url],
|
| 402 |
+
check=True,
|
| 403 |
+
timeout=_EXTENSIONS_PIP_INSTALL_TIMEOUT,
|
| 404 |
+
)
|
| 405 |
+
else:
|
| 406 |
+
venv.EnvBuilder(with_pip=True).create(str(venv_dir))
|
| 407 |
+
status.done(f"Virtual environment created in {venv_dir}")
|
| 408 |
+
|
| 409 |
+
status.update(f"Installing package from {source_url}")
|
| 410 |
+
subprocess.run(
|
| 411 |
+
[
|
| 412 |
+
str(venv_python),
|
| 413 |
+
"-m",
|
| 414 |
+
"pip",
|
| 415 |
+
"install",
|
| 416 |
+
"--disable-pip-version-check",
|
| 417 |
+
"--no-input",
|
| 418 |
+
source_url,
|
| 419 |
+
],
|
| 420 |
+
check=True,
|
| 421 |
+
timeout=_EXTENSIONS_PIP_INSTALL_TIMEOUT,
|
| 422 |
+
)
|
| 423 |
+
status.done(f"Package installed from {source_url}")
|
| 424 |
+
|
| 425 |
+
executable_name = _get_executable_name(short_name)
|
| 426 |
+
venv_executable = _get_venv_extension_executable_path(venv_dir, short_name)
|
| 427 |
+
if not venv_executable.is_file():
|
| 428 |
+
raise CLIError(
|
| 429 |
+
f"Installed package from '{owner}/{repo_name}' does not expose the required console script "
|
| 430 |
+
f"'{executable_name}'."
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
manifest = ExtensionManifest(
|
| 434 |
+
owner=owner,
|
| 435 |
+
repo=repo_name,
|
| 436 |
+
repo_id=f"{owner}/{repo_name}",
|
| 437 |
+
short_name=short_name,
|
| 438 |
+
executable_name=executable_name,
|
| 439 |
+
executable_path=str(venv_executable.resolve()),
|
| 440 |
+
type="python",
|
| 441 |
+
installed_at=datetime.now(timezone.utc),
|
| 442 |
+
source=f"https://github.com/{owner}/{repo_name}",
|
| 443 |
+
)
|
| 444 |
+
installed = True
|
| 445 |
+
return manifest
|
| 446 |
+
except CLIError:
|
| 447 |
+
raise
|
| 448 |
+
except subprocess.TimeoutExpired as e:
|
| 449 |
+
raise CLIExtensionInstallError(
|
| 450 |
+
f"Pip install timed out after {_EXTENSIONS_PIP_INSTALL_TIMEOUT}s for '{owner}/{repo_name}'. "
|
| 451 |
+
"See pip output above for details."
|
| 452 |
+
) from e
|
| 453 |
+
except subprocess.CalledProcessError as e:
|
| 454 |
+
raise CLIExtensionInstallError(
|
| 455 |
+
f"Failed to install pip package from '{owner}/{repo_name}' (exit code {e.returncode}). "
|
| 456 |
+
"See pip output above for details."
|
| 457 |
+
) from e
|
| 458 |
+
except Exception as e:
|
| 459 |
+
raise CLIExtensionInstallError(f"Failed to set up pip extension from '{owner}/{repo_name}': {e}") from e
|
| 460 |
+
finally:
|
| 461 |
+
if not installed:
|
| 462 |
+
shutil.rmtree(extension_dir, ignore_errors=True)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def _try_fetch_remote_description(
|
| 466 |
+
owner: str, repo_name: str, branch: str, candidate_description: str | None
|
| 467 |
+
) -> str | None:
|
| 468 |
+
"""Try to fetch project description either from:
|
| 469 |
+
- manifest.json
|
| 470 |
+
- pyproject.toml
|
| 471 |
+
|
| 472 |
+
Only best effort, no error handling.
|
| 473 |
+
"""
|
| 474 |
+
# from manifest.json
|
| 475 |
+
try:
|
| 476 |
+
response = get_session().get(
|
| 477 |
+
f"https://raw.githubusercontent.com/{owner}/{repo_name}/refs/heads/{branch}/{MANIFEST_FILENAME}",
|
| 478 |
+
follow_redirects=True,
|
| 479 |
+
)
|
| 480 |
+
response.raise_for_status()
|
| 481 |
+
data = response.json()
|
| 482 |
+
description = data.get("description")
|
| 483 |
+
if isinstance(description, str):
|
| 484 |
+
return description
|
| 485 |
+
except Exception:
|
| 486 |
+
pass
|
| 487 |
+
|
| 488 |
+
# from pyproject.toml
|
| 489 |
+
try:
|
| 490 |
+
response = get_session().get(
|
| 491 |
+
f"https://raw.githubusercontent.com/{owner}/{repo_name}/refs/heads/{branch}/pyproject.toml",
|
| 492 |
+
follow_redirects=True,
|
| 493 |
+
)
|
| 494 |
+
response.raise_for_status()
|
| 495 |
+
|
| 496 |
+
# Weak parser but ok for "best effort"
|
| 497 |
+
for line in response.text.splitlines():
|
| 498 |
+
line = line.strip()
|
| 499 |
+
if line.startswith("description"):
|
| 500 |
+
_, _, value = line.partition("=")
|
| 501 |
+
return value.strip().strip("\"'")
|
| 502 |
+
except Exception:
|
| 503 |
+
pass
|
| 504 |
+
|
| 505 |
+
# fallback to value fetched from GH API directly
|
| 506 |
+
return candidate_description
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def _get_extensions_root() -> Path:
|
| 510 |
+
root_dir = EXTENSIONS_ROOT.expanduser()
|
| 511 |
+
root_dir.mkdir(parents=True, exist_ok=True)
|
| 512 |
+
return root_dir
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def _get_extension_dir(short_name: str) -> Path:
|
| 516 |
+
safe_name = _validate_extension_short_name(short_name, original_input=short_name)
|
| 517 |
+
root = _get_extensions_root().resolve()
|
| 518 |
+
target = (root / f"hf-{safe_name}").resolve()
|
| 519 |
+
if root not in target.parents:
|
| 520 |
+
raise CLIError(f"Invalid extension name '{short_name}'.")
|
| 521 |
+
return target
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def _resolve_github_repo_info(owner: str, repo_name: str) -> tuple[str, str | None]:
|
| 525 |
+
try:
|
| 526 |
+
response = get_session().get(
|
| 527 |
+
f"https://api.github.com/repos/{owner}/{repo_name}",
|
| 528 |
+
follow_redirects=True,
|
| 529 |
+
timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT,
|
| 530 |
+
)
|
| 531 |
+
response.raise_for_status()
|
| 532 |
+
data = response.json()
|
| 533 |
+
return data["default_branch"], data.get("description")
|
| 534 |
+
except Exception:
|
| 535 |
+
return _EXTENSIONS_DEFAULT_BRANCH, None
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def _get_executable_name(short_name: str) -> str:
|
| 539 |
+
name = f"hf-{short_name}"
|
| 540 |
+
if os.name == "nt":
|
| 541 |
+
name += ".exe"
|
| 542 |
+
return name
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def _resolve_installed_executable_path(short_name: str) -> Path:
|
| 546 |
+
extension_dir = _get_extension_dir(short_name)
|
| 547 |
+
manifest = ExtensionManifest.load(extension_dir)
|
| 548 |
+
return Path(manifest.executable_path).expanduser()
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def _get_venv_python_path(venv_dir: Path) -> Path:
|
| 552 |
+
if os.name == "nt":
|
| 553 |
+
return venv_dir / "Scripts" / "python.exe"
|
| 554 |
+
return venv_dir / "bin" / "python"
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def _get_venv_extension_executable_path(venv_dir: Path, short_name: str) -> Path:
|
| 558 |
+
executable_name = _get_executable_name(short_name)
|
| 559 |
+
if os.name == "nt":
|
| 560 |
+
return venv_dir / "Scripts" / executable_name
|
| 561 |
+
return venv_dir / "bin" / executable_name
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
_ALLOWED_EXTENSION_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def _validate_extension_short_name(short_name: str, *, original_input: str) -> str:
|
| 568 |
+
name = short_name.strip()
|
| 569 |
+
if not name:
|
| 570 |
+
raise CLIError("Extension name cannot be empty.")
|
| 571 |
+
if any(sep in name for sep in ("/", "\\")):
|
| 572 |
+
raise CLIError(f"Invalid extension name '{original_input}'.")
|
| 573 |
+
if ".." in name or ":" in name:
|
| 574 |
+
raise CLIError(f"Invalid extension name '{original_input}'.")
|
| 575 |
+
if not _ALLOWED_EXTENSION_NAME.fullmatch(name):
|
| 576 |
+
raise CLIError(
|
| 577 |
+
f"Invalid extension name '{original_input}'. Allowed characters: letters, digits, '.', '_' and '-'."
|
| 578 |
+
)
|
| 579 |
+
return name
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def _normalize_repo_id(repo_id: str) -> tuple[str, str, str]:
|
| 583 |
+
if "://" in repo_id:
|
| 584 |
+
raise CLIError("Only GitHub repositories in `[OWNER/]hf-<name>` format are supported.")
|
| 585 |
+
|
| 586 |
+
parts = repo_id.split("/")
|
| 587 |
+
if len(parts) == 1:
|
| 588 |
+
owner = DEFAULT_EXTENSION_OWNER
|
| 589 |
+
repo_name = parts[0]
|
| 590 |
+
elif len(parts) == 2 and all(parts):
|
| 591 |
+
owner, repo_name = parts
|
| 592 |
+
else:
|
| 593 |
+
raise CLIError(f"Expected `[OWNER/]REPO` format, got '{repo_id}'.")
|
| 594 |
+
|
| 595 |
+
if not repo_name.startswith("hf-"):
|
| 596 |
+
raise CLIError(f"Extension repository name must start with 'hf-', got '{repo_name}'.")
|
| 597 |
+
|
| 598 |
+
short_name = repo_name[3:]
|
| 599 |
+
if not short_name:
|
| 600 |
+
raise CLIError("Invalid extension repository name 'hf-'.")
|
| 601 |
+
_validate_extension_short_name(short_name, original_input=repo_id)
|
| 602 |
+
|
| 603 |
+
return owner, repo_name, short_name
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _normalize_extension_name(name: str) -> str:
|
| 607 |
+
candidate = name.strip()
|
| 608 |
+
if not candidate:
|
| 609 |
+
raise CLIError("Extension name cannot be empty.")
|
| 610 |
+
normalized = candidate[3:] if candidate.startswith("hf-") else candidate
|
| 611 |
+
return _validate_extension_short_name(normalized, original_input=name)
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def _execute_extension_binary(executable_path: Path, args: list[str]) -> int:
|
| 615 |
+
try:
|
| 616 |
+
return subprocess.call([str(executable_path)] + args)
|
| 617 |
+
except OSError as e:
|
| 618 |
+
if os.name == "nt" or e.errno != errno.ENOEXEC:
|
| 619 |
+
raise
|
| 620 |
+
return subprocess.call(["sh", str(executable_path)] + args)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/hf.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import sys
|
| 16 |
+
import traceback
|
| 17 |
+
from typing import Annotated
|
| 18 |
+
|
| 19 |
+
import typer
|
| 20 |
+
|
| 21 |
+
from huggingface_hub import __version__, constants
|
| 22 |
+
from huggingface_hub.cli._cli_utils import check_cli_update, fallback_typer_group_factory, typer_factory
|
| 23 |
+
from huggingface_hub.cli._errors import format_known_exception
|
| 24 |
+
from huggingface_hub.cli.auth import auth_cli
|
| 25 |
+
from huggingface_hub.cli.buckets import buckets_cli, sync
|
| 26 |
+
from huggingface_hub.cli.cache import cache_cli
|
| 27 |
+
from huggingface_hub.cli.collections import collections_cli
|
| 28 |
+
from huggingface_hub.cli.datasets import datasets_cli
|
| 29 |
+
from huggingface_hub.cli.discussions import discussions_cli
|
| 30 |
+
from huggingface_hub.cli.download import DOWNLOAD_EXAMPLES, download
|
| 31 |
+
from huggingface_hub.cli.extensions import (
|
| 32 |
+
dispatch_unknown_top_level_extension,
|
| 33 |
+
extensions_cli,
|
| 34 |
+
list_installed_extensions_for_help,
|
| 35 |
+
)
|
| 36 |
+
from huggingface_hub.cli.inference_endpoints import ie_cli
|
| 37 |
+
from huggingface_hub.cli.jobs import jobs_cli
|
| 38 |
+
from huggingface_hub.cli.lfs import lfs_enable_largefiles, lfs_multipart_upload
|
| 39 |
+
from huggingface_hub.cli.models import models_cli
|
| 40 |
+
from huggingface_hub.cli.papers import papers_cli
|
| 41 |
+
from huggingface_hub.cli.repo_files import repo_files_cli
|
| 42 |
+
from huggingface_hub.cli.repos import repos_cli
|
| 43 |
+
from huggingface_hub.cli.skills import skills_cli
|
| 44 |
+
from huggingface_hub.cli.spaces import spaces_cli
|
| 45 |
+
from huggingface_hub.cli.system import env, version
|
| 46 |
+
from huggingface_hub.cli.upload import UPLOAD_EXAMPLES, upload
|
| 47 |
+
from huggingface_hub.cli.upload_large_folder import UPLOAD_LARGE_FOLDER_EXAMPLES, upload_large_folder
|
| 48 |
+
from huggingface_hub.cli.webhooks import webhooks_cli
|
| 49 |
+
from huggingface_hub.utils import ANSI, logging
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
app = typer_factory(
|
| 53 |
+
help="Hugging Face Hub CLI",
|
| 54 |
+
cls=fallback_typer_group_factory(
|
| 55 |
+
dispatch_unknown_top_level_extension,
|
| 56 |
+
extra_commands_provider=list_installed_extensions_for_help,
|
| 57 |
+
),
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _version_callback(value: bool) -> None:
|
| 62 |
+
if value:
|
| 63 |
+
print(__version__)
|
| 64 |
+
raise typer.Exit()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@app.callback(invoke_without_command=True)
|
| 68 |
+
def app_callback(
|
| 69 |
+
version: Annotated[
|
| 70 |
+
bool | None, typer.Option("--version", callback=_version_callback, is_eager=True, hidden=True)
|
| 71 |
+
] = None,
|
| 72 |
+
) -> None:
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# top level single commands (defined in their respective files)
|
| 77 |
+
app.command()(sync)
|
| 78 |
+
app.command(examples=DOWNLOAD_EXAMPLES)(download)
|
| 79 |
+
app.command(examples=UPLOAD_EXAMPLES)(upload)
|
| 80 |
+
app.command(examples=UPLOAD_LARGE_FOLDER_EXAMPLES)(upload_large_folder)
|
| 81 |
+
|
| 82 |
+
app.command(topic="help")(env)
|
| 83 |
+
app.command(topic="help")(version)
|
| 84 |
+
|
| 85 |
+
app.command(hidden=True)(lfs_enable_largefiles)
|
| 86 |
+
app.command(hidden=True)(lfs_multipart_upload)
|
| 87 |
+
|
| 88 |
+
# command groups
|
| 89 |
+
app.add_typer(auth_cli, name="auth")
|
| 90 |
+
app.add_typer(buckets_cli, name="buckets")
|
| 91 |
+
app.add_typer(cache_cli, name="cache")
|
| 92 |
+
app.add_typer(collections_cli, name="collections")
|
| 93 |
+
app.add_typer(datasets_cli, name="datasets")
|
| 94 |
+
app.add_typer(discussions_cli, name="discussions")
|
| 95 |
+
app.add_typer(jobs_cli, name="jobs")
|
| 96 |
+
app.add_typer(models_cli, name="models")
|
| 97 |
+
app.add_typer(papers_cli, name="papers")
|
| 98 |
+
app.add_typer(repos_cli, name="repos | repo")
|
| 99 |
+
app.add_typer(repo_files_cli, name="repo-files", hidden=True)
|
| 100 |
+
app.add_typer(skills_cli, name="skills")
|
| 101 |
+
app.add_typer(spaces_cli, name="spaces")
|
| 102 |
+
app.add_typer(webhooks_cli, name="webhooks")
|
| 103 |
+
app.add_typer(ie_cli, name="endpoints")
|
| 104 |
+
app.add_typer(extensions_cli, name="extensions | ext")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main():
|
| 108 |
+
if not constants.HF_DEBUG:
|
| 109 |
+
logging.set_verbosity_info()
|
| 110 |
+
check_cli_update("huggingface_hub")
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
app()
|
| 114 |
+
except Exception as e:
|
| 115 |
+
message = format_known_exception(e)
|
| 116 |
+
if message:
|
| 117 |
+
print(f"Error: {message}", file=sys.stderr)
|
| 118 |
+
if constants.HF_DEBUG:
|
| 119 |
+
traceback.print_exc()
|
| 120 |
+
else:
|
| 121 |
+
print(ANSI.gray("Set HF_DEBUG=1 as environment variable for full traceback."))
|
| 122 |
+
sys.exit(1)
|
| 123 |
+
raise
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
main()
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/inference_endpoints.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI commands for Hugging Face Inference Endpoints."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from typing import Annotated, Any
|
| 5 |
+
|
| 6 |
+
import typer
|
| 7 |
+
|
| 8 |
+
from huggingface_hub._inference_endpoints import InferenceEndpoint, InferenceEndpointScalingMetric
|
| 9 |
+
from huggingface_hub.errors import HfHubHTTPError
|
| 10 |
+
|
| 11 |
+
from ._cli_utils import (
|
| 12 |
+
FormatOpt,
|
| 13 |
+
OutputFormat,
|
| 14 |
+
QuietOpt,
|
| 15 |
+
TokenOpt,
|
| 16 |
+
get_hf_api,
|
| 17 |
+
print_list_output,
|
| 18 |
+
typer_factory,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
ie_cli = typer_factory(help="Manage Hugging Face Inference Endpoints.")
|
| 23 |
+
|
| 24 |
+
catalog_app = typer_factory(help="Interact with the Inference Endpoints catalog.")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
NameArg = Annotated[
|
| 28 |
+
str,
|
| 29 |
+
typer.Argument(help="Endpoint name."),
|
| 30 |
+
]
|
| 31 |
+
NameOpt = Annotated[
|
| 32 |
+
str | None,
|
| 33 |
+
typer.Option(help="Endpoint name."),
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
NamespaceOpt = Annotated[
|
| 37 |
+
str | None,
|
| 38 |
+
typer.Option(
|
| 39 |
+
help="The namespace associated with the Inference Endpoint. Defaults to the current user's namespace.",
|
| 40 |
+
),
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _print_endpoint(endpoint: InferenceEndpoint) -> None:
|
| 45 |
+
typer.echo(json.dumps(endpoint.raw, indent=2, sort_keys=True))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@ie_cli.command("list | ls", examples=["hf endpoints ls", "hf endpoints ls --namespace my-org"])
|
| 49 |
+
def ls(
|
| 50 |
+
namespace: NamespaceOpt = None,
|
| 51 |
+
format: FormatOpt = OutputFormat.table,
|
| 52 |
+
quiet: QuietOpt = False,
|
| 53 |
+
token: TokenOpt = None,
|
| 54 |
+
) -> None:
|
| 55 |
+
"""Lists all Inference Endpoints for the given namespace."""
|
| 56 |
+
api = get_hf_api(token=token)
|
| 57 |
+
try:
|
| 58 |
+
endpoints = api.list_inference_endpoints(namespace=namespace, token=token)
|
| 59 |
+
except HfHubHTTPError as error:
|
| 60 |
+
typer.echo(f"Listing failed: {error}")
|
| 61 |
+
raise typer.Exit(code=error.response.status_code) from error
|
| 62 |
+
|
| 63 |
+
results = [endpoint.raw for endpoint in endpoints]
|
| 64 |
+
|
| 65 |
+
def row_fn(item: dict[str, Any]) -> list[str]:
|
| 66 |
+
status = item.get("status", {})
|
| 67 |
+
model = item.get("model", {})
|
| 68 |
+
compute = item.get("compute", {})
|
| 69 |
+
provider = item.get("provider", {})
|
| 70 |
+
return [
|
| 71 |
+
str(item.get("name", "")),
|
| 72 |
+
str(model.get("repository", "") if isinstance(model, dict) else ""),
|
| 73 |
+
str(status.get("state", "") if isinstance(status, dict) else ""),
|
| 74 |
+
str(model.get("task", "") if isinstance(model, dict) else ""),
|
| 75 |
+
str(model.get("framework", "") if isinstance(model, dict) else ""),
|
| 76 |
+
str(compute.get("instanceType", "") if isinstance(compute, dict) else ""),
|
| 77 |
+
str(provider.get("vendor", "") if isinstance(provider, dict) else ""),
|
| 78 |
+
str(provider.get("region", "") if isinstance(provider, dict) else ""),
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
print_list_output(
|
| 82 |
+
items=results,
|
| 83 |
+
format=format,
|
| 84 |
+
quiet=quiet,
|
| 85 |
+
id_key="name",
|
| 86 |
+
headers=["NAME", "MODEL", "STATUS", "TASK", "FRAMEWORK", "INSTANCE", "VENDOR", "REGION"],
|
| 87 |
+
row_fn=row_fn,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@ie_cli.command(name="deploy", examples=["hf endpoints deploy my-endpoint --repo gpt2 --framework pytorch ..."])
|
| 92 |
+
def deploy(
|
| 93 |
+
name: NameArg,
|
| 94 |
+
repo: Annotated[
|
| 95 |
+
str,
|
| 96 |
+
typer.Option(
|
| 97 |
+
help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').",
|
| 98 |
+
),
|
| 99 |
+
],
|
| 100 |
+
framework: Annotated[
|
| 101 |
+
str,
|
| 102 |
+
typer.Option(
|
| 103 |
+
help="The machine learning framework used for the model (e.g. 'vllm').",
|
| 104 |
+
),
|
| 105 |
+
],
|
| 106 |
+
accelerator: Annotated[
|
| 107 |
+
str,
|
| 108 |
+
typer.Option(
|
| 109 |
+
help="The hardware accelerator to be used for inference (e.g. 'cpu').",
|
| 110 |
+
),
|
| 111 |
+
],
|
| 112 |
+
instance_size: Annotated[
|
| 113 |
+
str,
|
| 114 |
+
typer.Option(
|
| 115 |
+
help="The size or type of the instance to be used for hosting the model (e.g. 'x4').",
|
| 116 |
+
),
|
| 117 |
+
],
|
| 118 |
+
instance_type: Annotated[
|
| 119 |
+
str,
|
| 120 |
+
typer.Option(
|
| 121 |
+
help="The cloud instance type where the Inference Endpoint will be deployed (e.g. 'intel-icl').",
|
| 122 |
+
),
|
| 123 |
+
],
|
| 124 |
+
region: Annotated[
|
| 125 |
+
str,
|
| 126 |
+
typer.Option(
|
| 127 |
+
help="The cloud region in which the Inference Endpoint will be created (e.g. 'us-east-1').",
|
| 128 |
+
),
|
| 129 |
+
],
|
| 130 |
+
vendor: Annotated[
|
| 131 |
+
str,
|
| 132 |
+
typer.Option(
|
| 133 |
+
help="The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. 'aws').",
|
| 134 |
+
),
|
| 135 |
+
],
|
| 136 |
+
*,
|
| 137 |
+
namespace: NamespaceOpt = None,
|
| 138 |
+
task: Annotated[
|
| 139 |
+
str | None,
|
| 140 |
+
typer.Option(
|
| 141 |
+
help="The task on which to deploy the model (e.g. 'text-classification').",
|
| 142 |
+
),
|
| 143 |
+
] = None,
|
| 144 |
+
token: TokenOpt = None,
|
| 145 |
+
min_replica: Annotated[
|
| 146 |
+
int,
|
| 147 |
+
typer.Option(
|
| 148 |
+
help="The minimum number of replicas (instances) to keep running for the Inference Endpoint.",
|
| 149 |
+
),
|
| 150 |
+
] = 1,
|
| 151 |
+
max_replica: Annotated[
|
| 152 |
+
int,
|
| 153 |
+
typer.Option(
|
| 154 |
+
help="The maximum number of replicas (instances) to scale to for the Inference Endpoint.",
|
| 155 |
+
),
|
| 156 |
+
] = 1,
|
| 157 |
+
scale_to_zero_timeout: Annotated[
|
| 158 |
+
int | None,
|
| 159 |
+
typer.Option(
|
| 160 |
+
help="The duration in minutes before an inactive endpoint is scaled to zero.",
|
| 161 |
+
),
|
| 162 |
+
] = None,
|
| 163 |
+
scaling_metric: Annotated[
|
| 164 |
+
InferenceEndpointScalingMetric | None,
|
| 165 |
+
typer.Option(
|
| 166 |
+
help="The metric reference for scaling.",
|
| 167 |
+
),
|
| 168 |
+
] = None,
|
| 169 |
+
scaling_threshold: Annotated[
|
| 170 |
+
float | None,
|
| 171 |
+
typer.Option(
|
| 172 |
+
help="The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.",
|
| 173 |
+
),
|
| 174 |
+
] = None,
|
| 175 |
+
) -> None:
|
| 176 |
+
"""Deploy an Inference Endpoint from a Hub repository."""
|
| 177 |
+
api = get_hf_api(token=token)
|
| 178 |
+
endpoint = api.create_inference_endpoint(
|
| 179 |
+
name=name,
|
| 180 |
+
repository=repo,
|
| 181 |
+
framework=framework,
|
| 182 |
+
accelerator=accelerator,
|
| 183 |
+
instance_size=instance_size,
|
| 184 |
+
instance_type=instance_type,
|
| 185 |
+
region=region,
|
| 186 |
+
vendor=vendor,
|
| 187 |
+
namespace=namespace,
|
| 188 |
+
task=task,
|
| 189 |
+
token=token,
|
| 190 |
+
min_replica=min_replica,
|
| 191 |
+
max_replica=max_replica,
|
| 192 |
+
scaling_metric=scaling_metric,
|
| 193 |
+
scaling_threshold=scaling_threshold,
|
| 194 |
+
scale_to_zero_timeout=scale_to_zero_timeout,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
_print_endpoint(endpoint)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@catalog_app.command(name="deploy", examples=["hf endpoints catalog deploy --repo meta-llama/Llama-3.2-1B-Instruct"])
|
| 201 |
+
def deploy_from_catalog(
|
| 202 |
+
repo: Annotated[
|
| 203 |
+
str,
|
| 204 |
+
typer.Option(
|
| 205 |
+
help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').",
|
| 206 |
+
),
|
| 207 |
+
],
|
| 208 |
+
name: NameOpt = None,
|
| 209 |
+
accelerator: Annotated[
|
| 210 |
+
str | None,
|
| 211 |
+
typer.Option(
|
| 212 |
+
help="The hardware accelerator to be used for inference (e.g. 'cpu', 'gpu', 'neuron').",
|
| 213 |
+
),
|
| 214 |
+
] = None,
|
| 215 |
+
namespace: NamespaceOpt = None,
|
| 216 |
+
token: TokenOpt = None,
|
| 217 |
+
) -> None:
|
| 218 |
+
"""Deploy an Inference Endpoint from the Model Catalog."""
|
| 219 |
+
api = get_hf_api(token=token)
|
| 220 |
+
try:
|
| 221 |
+
endpoint = api.create_inference_endpoint_from_catalog(
|
| 222 |
+
repo_id=repo,
|
| 223 |
+
name=name,
|
| 224 |
+
accelerator=accelerator,
|
| 225 |
+
namespace=namespace,
|
| 226 |
+
token=token,
|
| 227 |
+
)
|
| 228 |
+
except HfHubHTTPError as error:
|
| 229 |
+
typer.echo(f"Deployment failed: {error}")
|
| 230 |
+
raise typer.Exit(code=error.response.status_code) from error
|
| 231 |
+
|
| 232 |
+
_print_endpoint(endpoint)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def list_catalog(
|
| 236 |
+
token: TokenOpt = None,
|
| 237 |
+
) -> None:
|
| 238 |
+
"""List available Catalog models."""
|
| 239 |
+
api = get_hf_api(token=token)
|
| 240 |
+
try:
|
| 241 |
+
models = api.list_inference_catalog(token=token)
|
| 242 |
+
except HfHubHTTPError as error:
|
| 243 |
+
typer.echo(f"Catalog fetch failed: {error}")
|
| 244 |
+
raise typer.Exit(code=error.response.status_code) from error
|
| 245 |
+
|
| 246 |
+
typer.echo(json.dumps({"models": models}, indent=2, sort_keys=True))
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
catalog_app.command(name="list | ls", examples=["hf endpoints catalog ls"])(list_catalog)
|
| 250 |
+
ie_cli.command(name="list-catalog", hidden=True)(list_catalog)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
ie_cli.add_typer(catalog_app, name="catalog")
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
@ie_cli.command(examples=["hf endpoints describe my-endpoint"])
|
| 257 |
+
def describe(
|
| 258 |
+
name: NameArg,
|
| 259 |
+
namespace: NamespaceOpt = None,
|
| 260 |
+
token: TokenOpt = None,
|
| 261 |
+
) -> None:
|
| 262 |
+
"""Get information about an existing endpoint."""
|
| 263 |
+
api = get_hf_api(token=token)
|
| 264 |
+
try:
|
| 265 |
+
endpoint = api.get_inference_endpoint(name=name, namespace=namespace, token=token)
|
| 266 |
+
except HfHubHTTPError as error:
|
| 267 |
+
typer.echo(f"Fetch failed: {error}")
|
| 268 |
+
raise typer.Exit(code=error.response.status_code) from error
|
| 269 |
+
|
| 270 |
+
_print_endpoint(endpoint)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@ie_cli.command(examples=["hf endpoints update my-endpoint --min-replica 2"])
|
| 274 |
+
def update(
|
| 275 |
+
name: NameArg,
|
| 276 |
+
namespace: NamespaceOpt = None,
|
| 277 |
+
repo: Annotated[
|
| 278 |
+
str | None,
|
| 279 |
+
typer.Option(
|
| 280 |
+
help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').",
|
| 281 |
+
),
|
| 282 |
+
] = None,
|
| 283 |
+
accelerator: Annotated[
|
| 284 |
+
str | None,
|
| 285 |
+
typer.Option(
|
| 286 |
+
help="The hardware accelerator to be used for inference (e.g. 'cpu').",
|
| 287 |
+
),
|
| 288 |
+
] = None,
|
| 289 |
+
instance_size: Annotated[
|
| 290 |
+
str | None,
|
| 291 |
+
typer.Option(
|
| 292 |
+
help="The size or type of the instance to be used for hosting the model (e.g. 'x4').",
|
| 293 |
+
),
|
| 294 |
+
] = None,
|
| 295 |
+
instance_type: Annotated[
|
| 296 |
+
str | None,
|
| 297 |
+
typer.Option(
|
| 298 |
+
help="The cloud instance type where the Inference Endpoint will be deployed (e.g. 'intel-icl').",
|
| 299 |
+
),
|
| 300 |
+
] = None,
|
| 301 |
+
framework: Annotated[
|
| 302 |
+
str | None,
|
| 303 |
+
typer.Option(
|
| 304 |
+
help="The machine learning framework used for the model (e.g. 'custom').",
|
| 305 |
+
),
|
| 306 |
+
] = None,
|
| 307 |
+
revision: Annotated[
|
| 308 |
+
str | None,
|
| 309 |
+
typer.Option(
|
| 310 |
+
help="The specific model revision to deploy on the Inference Endpoint (e.g. '6c0e6080953db56375760c0471a8c5f2929baf11').",
|
| 311 |
+
),
|
| 312 |
+
] = None,
|
| 313 |
+
task: Annotated[
|
| 314 |
+
str | None,
|
| 315 |
+
typer.Option(
|
| 316 |
+
help="The task on which to deploy the model (e.g. 'text-classification').",
|
| 317 |
+
),
|
| 318 |
+
] = None,
|
| 319 |
+
min_replica: Annotated[
|
| 320 |
+
int | None,
|
| 321 |
+
typer.Option(
|
| 322 |
+
help="The minimum number of replicas (instances) to keep running for the Inference Endpoint.",
|
| 323 |
+
),
|
| 324 |
+
] = None,
|
| 325 |
+
max_replica: Annotated[
|
| 326 |
+
int | None,
|
| 327 |
+
typer.Option(
|
| 328 |
+
help="The maximum number of replicas (instances) to scale to for the Inference Endpoint.",
|
| 329 |
+
),
|
| 330 |
+
] = None,
|
| 331 |
+
scale_to_zero_timeout: Annotated[
|
| 332 |
+
int | None,
|
| 333 |
+
typer.Option(
|
| 334 |
+
help="The duration in minutes before an inactive endpoint is scaled to zero.",
|
| 335 |
+
),
|
| 336 |
+
] = None,
|
| 337 |
+
scaling_metric: Annotated[
|
| 338 |
+
InferenceEndpointScalingMetric | None,
|
| 339 |
+
typer.Option(
|
| 340 |
+
help="The metric reference for scaling.",
|
| 341 |
+
),
|
| 342 |
+
] = None,
|
| 343 |
+
scaling_threshold: Annotated[
|
| 344 |
+
float | None,
|
| 345 |
+
typer.Option(
|
| 346 |
+
help="The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.",
|
| 347 |
+
),
|
| 348 |
+
] = None,
|
| 349 |
+
token: TokenOpt = None,
|
| 350 |
+
) -> None:
|
| 351 |
+
"""Update an existing endpoint."""
|
| 352 |
+
api = get_hf_api(token=token)
|
| 353 |
+
try:
|
| 354 |
+
endpoint = api.update_inference_endpoint(
|
| 355 |
+
name=name,
|
| 356 |
+
namespace=namespace,
|
| 357 |
+
repository=repo,
|
| 358 |
+
framework=framework,
|
| 359 |
+
revision=revision,
|
| 360 |
+
task=task,
|
| 361 |
+
accelerator=accelerator,
|
| 362 |
+
instance_size=instance_size,
|
| 363 |
+
instance_type=instance_type,
|
| 364 |
+
min_replica=min_replica,
|
| 365 |
+
max_replica=max_replica,
|
| 366 |
+
scale_to_zero_timeout=scale_to_zero_timeout,
|
| 367 |
+
scaling_metric=scaling_metric,
|
| 368 |
+
scaling_threshold=scaling_threshold,
|
| 369 |
+
token=token,
|
| 370 |
+
)
|
| 371 |
+
except HfHubHTTPError as error:
|
| 372 |
+
typer.echo(f"Update failed: {error}")
|
| 373 |
+
raise typer.Exit(code=error.response.status_code) from error
|
| 374 |
+
_print_endpoint(endpoint)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@ie_cli.command(examples=["hf endpoints delete my-endpoint"])
|
| 378 |
+
def delete(
|
| 379 |
+
name: NameArg,
|
| 380 |
+
namespace: NamespaceOpt = None,
|
| 381 |
+
yes: Annotated[
|
| 382 |
+
bool,
|
| 383 |
+
typer.Option("--yes", help="Skip confirmation prompts."),
|
| 384 |
+
] = False,
|
| 385 |
+
token: TokenOpt = None,
|
| 386 |
+
) -> None:
|
| 387 |
+
"""Delete an Inference Endpoint permanently."""
|
| 388 |
+
if not yes:
|
| 389 |
+
confirmation = typer.prompt(f"Delete endpoint '{name}'? Type the name to confirm.")
|
| 390 |
+
if confirmation != name:
|
| 391 |
+
typer.echo("Aborted.")
|
| 392 |
+
raise typer.Exit(code=2)
|
| 393 |
+
|
| 394 |
+
api = get_hf_api(token=token)
|
| 395 |
+
try:
|
| 396 |
+
api.delete_inference_endpoint(name=name, namespace=namespace, token=token)
|
| 397 |
+
except HfHubHTTPError as error:
|
| 398 |
+
typer.echo(f"Delete failed: {error}")
|
| 399 |
+
raise typer.Exit(code=error.response.status_code) from error
|
| 400 |
+
|
| 401 |
+
typer.echo(f"Deleted '{name}'.")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
@ie_cli.command(examples=["hf endpoints pause my-endpoint"])
|
| 405 |
+
def pause(
|
| 406 |
+
name: NameArg,
|
| 407 |
+
namespace: NamespaceOpt = None,
|
| 408 |
+
token: TokenOpt = None,
|
| 409 |
+
) -> None:
|
| 410 |
+
"""Pause an Inference Endpoint."""
|
| 411 |
+
api = get_hf_api(token=token)
|
| 412 |
+
try:
|
| 413 |
+
endpoint = api.pause_inference_endpoint(name=name, namespace=namespace, token=token)
|
| 414 |
+
except HfHubHTTPError as error:
|
| 415 |
+
typer.echo(f"Pause failed: {error}")
|
| 416 |
+
raise typer.Exit(code=error.response.status_code) from error
|
| 417 |
+
|
| 418 |
+
_print_endpoint(endpoint)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
@ie_cli.command(examples=["hf endpoints resume my-endpoint"])
|
| 422 |
+
def resume(
|
| 423 |
+
name: NameArg,
|
| 424 |
+
namespace: NamespaceOpt = None,
|
| 425 |
+
fail_if_already_running: Annotated[
|
| 426 |
+
bool,
|
| 427 |
+
typer.Option(
|
| 428 |
+
"--fail-if-already-running",
|
| 429 |
+
help="If `True`, the method will raise an error if the Inference Endpoint is already running.",
|
| 430 |
+
),
|
| 431 |
+
] = False,
|
| 432 |
+
token: TokenOpt = None,
|
| 433 |
+
) -> None:
|
| 434 |
+
"""Resume an Inference Endpoint."""
|
| 435 |
+
api = get_hf_api(token=token)
|
| 436 |
+
try:
|
| 437 |
+
endpoint = api.resume_inference_endpoint(
|
| 438 |
+
name=name,
|
| 439 |
+
namespace=namespace,
|
| 440 |
+
token=token,
|
| 441 |
+
running_ok=not fail_if_already_running,
|
| 442 |
+
)
|
| 443 |
+
except HfHubHTTPError as error:
|
| 444 |
+
typer.echo(f"Resume failed: {error}")
|
| 445 |
+
raise typer.Exit(code=error.response.status_code) from error
|
| 446 |
+
_print_endpoint(endpoint)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
@ie_cli.command(examples=["hf endpoints scale-to-zero my-endpoint"])
|
| 450 |
+
def scale_to_zero(
|
| 451 |
+
name: NameArg,
|
| 452 |
+
namespace: NamespaceOpt = None,
|
| 453 |
+
token: TokenOpt = None,
|
| 454 |
+
) -> None:
|
| 455 |
+
"""Scale an Inference Endpoint to zero."""
|
| 456 |
+
api = get_hf_api(token=token)
|
| 457 |
+
try:
|
| 458 |
+
endpoint = api.scale_to_zero_inference_endpoint(name=name, namespace=namespace, token=token)
|
| 459 |
+
except HfHubHTTPError as error:
|
| 460 |
+
typer.echo(f"Scale To Zero failed: {error}")
|
| 461 |
+
raise typer.Exit(code=error.response.status_code) from error
|
| 462 |
+
|
| 463 |
+
_print_endpoint(endpoint)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttEL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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with jobs on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# run a job
|
| 18 |
+
hf jobs run <image> <command>
|
| 19 |
+
|
| 20 |
+
# List running or completed jobs
|
| 21 |
+
hf jobs ps [-a] [-f key=value] [--format table|json|TEMPLATE] [-q]
|
| 22 |
+
|
| 23 |
+
# Print logs from a job (non-blocking)
|
| 24 |
+
hf jobs logs <job-id>
|
| 25 |
+
|
| 26 |
+
# Stream logs from a job (blocking, like `docker logs -f`)
|
| 27 |
+
hf jobs logs -f <job-id>
|
| 28 |
+
|
| 29 |
+
# Stream resources usage stats and metrics from a job
|
| 30 |
+
hf jobs stats <job-id>
|
| 31 |
+
|
| 32 |
+
# Inspect detailed information about a job
|
| 33 |
+
hf jobs inspect <job-id>
|
| 34 |
+
|
| 35 |
+
# Cancel a running job
|
| 36 |
+
hf jobs cancel <job-id>
|
| 37 |
+
|
| 38 |
+
# List available hardware options
|
| 39 |
+
hf jobs hardware
|
| 40 |
+
|
| 41 |
+
# Run a UV script
|
| 42 |
+
hf jobs uv run <script>
|
| 43 |
+
|
| 44 |
+
# Schedule a job
|
| 45 |
+
hf jobs scheduled run <schedule> <image> <command>
|
| 46 |
+
|
| 47 |
+
# List scheduled jobs
|
| 48 |
+
hf jobs scheduled ps [-a] [-f key=value] [--format table|json] [-q]
|
| 49 |
+
|
| 50 |
+
# Inspect a scheduled job
|
| 51 |
+
hf jobs scheduled inspect <scheduled_job_id>
|
| 52 |
+
|
| 53 |
+
# Suspend a scheduled job
|
| 54 |
+
hf jobs scheduled suspend <scheduled_job_id>
|
| 55 |
+
|
| 56 |
+
# Resume a scheduled job
|
| 57 |
+
hf jobs scheduled resume <scheduled_job_id>
|
| 58 |
+
|
| 59 |
+
# Delete a scheduled job
|
| 60 |
+
hf jobs scheduled delete <scheduled_job_id>
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
import json
|
| 65 |
+
import multiprocessing
|
| 66 |
+
import multiprocessing.pool
|
| 67 |
+
import shutil
|
| 68 |
+
import time
|
| 69 |
+
from collections import deque
|
| 70 |
+
from collections.abc import Callable, Iterable
|
| 71 |
+
from dataclasses import asdict
|
| 72 |
+
from fnmatch import fnmatch
|
| 73 |
+
from queue import Empty, Queue
|
| 74 |
+
from typing import Annotated, Any, TypeVar
|
| 75 |
+
|
| 76 |
+
import typer
|
| 77 |
+
|
| 78 |
+
from huggingface_hub import SpaceHardware
|
| 79 |
+
from huggingface_hub.errors import CLIError, HfHubHTTPError
|
| 80 |
+
from huggingface_hub.utils import logging
|
| 81 |
+
from huggingface_hub.utils._cache_manager import _format_size
|
| 82 |
+
|
| 83 |
+
from ._cli_utils import (
|
| 84 |
+
EnvFileOpt,
|
| 85 |
+
EnvOpt,
|
| 86 |
+
OutputFormat,
|
| 87 |
+
QuietOpt,
|
| 88 |
+
SecretsFileOpt,
|
| 89 |
+
SecretsOpt,
|
| 90 |
+
TokenOpt,
|
| 91 |
+
VolumesOpt,
|
| 92 |
+
_format_cell,
|
| 93 |
+
api_object_to_dict,
|
| 94 |
+
get_hf_api,
|
| 95 |
+
parse_env_map,
|
| 96 |
+
parse_volumes,
|
| 97 |
+
print_list_output,
|
| 98 |
+
typer_factory,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
logger = logging.get_logger(__name__)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _parse_namespace_from_job_id(job_id: str, namespace: str | None) -> tuple[str, str | None]:
|
| 106 |
+
"""Extract namespace from job_id if provided in 'namespace/job_id' format.
|
| 107 |
+
|
| 108 |
+
Allows users to pass job IDs copied from the Hub UI (e.g. 'username/job_id')
|
| 109 |
+
instead of only bare job IDs. If the namespace is also provided explicitly via
|
| 110 |
+
--namespace and conflicts, a CLIError is raised.
|
| 111 |
+
"""
|
| 112 |
+
if not job_id:
|
| 113 |
+
raise CLIError("Job ID cannot be empty.")
|
| 114 |
+
|
| 115 |
+
if job_id.count("/") > 1:
|
| 116 |
+
raise CLIError(f"Job ID must be in the form 'job_id' or 'namespace/job_id': '{job_id}'.")
|
| 117 |
+
|
| 118 |
+
if "/" not in job_id:
|
| 119 |
+
return job_id, namespace
|
| 120 |
+
|
| 121 |
+
extracted_namespace, parsed_job_id = job_id.split("/", 1)
|
| 122 |
+
if not extracted_namespace or not parsed_job_id:
|
| 123 |
+
raise CLIError(f"Job ID must be in the form 'job_id' or 'namespace/job_id': '{job_id}'.")
|
| 124 |
+
|
| 125 |
+
if namespace is not None and namespace != extracted_namespace:
|
| 126 |
+
raise CLIError(
|
| 127 |
+
f"Conflicting namespace: got --namespace='{namespace}' but job ID implies namespace='{extracted_namespace}'"
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
return parsed_job_id, extracted_namespace
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
SUGGESTED_FLAVORS = [item.value for item in SpaceHardware if item.value != "zero-a10g"]
|
| 134 |
+
STATS_UPDATE_MIN_INTERVAL = 0.1 # we set a limit here since there is one update per second per job
|
| 135 |
+
|
| 136 |
+
# Common job-related options
|
| 137 |
+
ImageArg = Annotated[
|
| 138 |
+
str,
|
| 139 |
+
typer.Argument(
|
| 140 |
+
help="The Docker image to use.",
|
| 141 |
+
),
|
| 142 |
+
]
|
| 143 |
+
|
| 144 |
+
ImageOpt = Annotated[
|
| 145 |
+
str | None,
|
| 146 |
+
typer.Option(
|
| 147 |
+
help="Use a custom Docker image with `uv` installed.",
|
| 148 |
+
),
|
| 149 |
+
]
|
| 150 |
+
|
| 151 |
+
FlavorOpt = Annotated[
|
| 152 |
+
SpaceHardware | None,
|
| 153 |
+
typer.Option(
|
| 154 |
+
help="Flavor for the hardware, as in HF Spaces. Run 'hf jobs hardware' to list available flavors. Defaults to `cpu-basic`.",
|
| 155 |
+
),
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
LabelsOpt = Annotated[
|
| 159 |
+
list[str] | None,
|
| 160 |
+
typer.Option(
|
| 161 |
+
"-l",
|
| 162 |
+
"--label",
|
| 163 |
+
help="Set labels. E.g. --label KEY=VALUE or --label LABEL",
|
| 164 |
+
),
|
| 165 |
+
]
|
| 166 |
+
|
| 167 |
+
TimeoutOpt = Annotated[
|
| 168 |
+
str | None,
|
| 169 |
+
typer.Option(
|
| 170 |
+
help="Max duration: int/float with s (seconds, default), m (minutes), h (hours) or d (days).",
|
| 171 |
+
),
|
| 172 |
+
]
|
| 173 |
+
|
| 174 |
+
DetachOpt = Annotated[
|
| 175 |
+
bool,
|
| 176 |
+
typer.Option(
|
| 177 |
+
"-d",
|
| 178 |
+
"--detach",
|
| 179 |
+
help="Run the Job in the background and print the Job ID.",
|
| 180 |
+
),
|
| 181 |
+
]
|
| 182 |
+
|
| 183 |
+
NamespaceOpt = Annotated[
|
| 184 |
+
str | None,
|
| 185 |
+
typer.Option(
|
| 186 |
+
help="The namespace where the job will be running. Defaults to the current user's namespace.",
|
| 187 |
+
),
|
| 188 |
+
]
|
| 189 |
+
|
| 190 |
+
WithOpt = Annotated[
|
| 191 |
+
list[str] | None,
|
| 192 |
+
typer.Option(
|
| 193 |
+
"--with",
|
| 194 |
+
help="Run with the given packages installed",
|
| 195 |
+
),
|
| 196 |
+
]
|
| 197 |
+
|
| 198 |
+
PythonOpt = Annotated[
|
| 199 |
+
str | None,
|
| 200 |
+
typer.Option(
|
| 201 |
+
"-p",
|
| 202 |
+
"--python",
|
| 203 |
+
help="The Python interpreter to use for the run environment",
|
| 204 |
+
),
|
| 205 |
+
]
|
| 206 |
+
|
| 207 |
+
SuspendOpt = Annotated[
|
| 208 |
+
bool | None,
|
| 209 |
+
typer.Option(
|
| 210 |
+
help="Suspend (pause) the scheduled Job",
|
| 211 |
+
),
|
| 212 |
+
]
|
| 213 |
+
|
| 214 |
+
ConcurrencyOpt = Annotated[
|
| 215 |
+
bool | None,
|
| 216 |
+
typer.Option(
|
| 217 |
+
help="Allow multiple instances of this Job to run concurrently",
|
| 218 |
+
),
|
| 219 |
+
]
|
| 220 |
+
|
| 221 |
+
ScheduleArg = Annotated[
|
| 222 |
+
str,
|
| 223 |
+
typer.Argument(
|
| 224 |
+
help="One of annually, yearly, monthly, weekly, daily, hourly, or a CRON schedule expression.",
|
| 225 |
+
),
|
| 226 |
+
]
|
| 227 |
+
|
| 228 |
+
ScriptArg = Annotated[
|
| 229 |
+
str,
|
| 230 |
+
typer.Argument(
|
| 231 |
+
help="UV script to run (local file or URL)",
|
| 232 |
+
),
|
| 233 |
+
]
|
| 234 |
+
|
| 235 |
+
ScriptArgsArg = Annotated[
|
| 236 |
+
list[str] | None,
|
| 237 |
+
typer.Argument(
|
| 238 |
+
help="Arguments for the script",
|
| 239 |
+
),
|
| 240 |
+
]
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
CommandArg = Annotated[
|
| 244 |
+
list[str],
|
| 245 |
+
typer.Argument(
|
| 246 |
+
help="The command to run.",
|
| 247 |
+
),
|
| 248 |
+
]
|
| 249 |
+
|
| 250 |
+
JobIdArg = Annotated[
|
| 251 |
+
str,
|
| 252 |
+
typer.Argument(
|
| 253 |
+
help="Job ID (or 'namespace/job_id')",
|
| 254 |
+
),
|
| 255 |
+
]
|
| 256 |
+
|
| 257 |
+
JobIdsArg = Annotated[
|
| 258 |
+
list[str] | None,
|
| 259 |
+
typer.Argument(
|
| 260 |
+
help="Job IDs (or 'namespace/job_id')",
|
| 261 |
+
),
|
| 262 |
+
]
|
| 263 |
+
|
| 264 |
+
ScheduledJobIdArg = Annotated[
|
| 265 |
+
str,
|
| 266 |
+
typer.Argument(
|
| 267 |
+
help="Scheduled Job ID (or 'namespace/scheduled_job_id')",
|
| 268 |
+
),
|
| 269 |
+
]
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
jobs_cli = typer_factory(help="Run and manage Jobs on the Hub.")
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@jobs_cli.command(
|
| 276 |
+
"run",
|
| 277 |
+
context_settings={"ignore_unknown_options": True},
|
| 278 |
+
examples=[
|
| 279 |
+
"hf jobs run python:3.12 python -c 'print(\"Hello!\")'",
|
| 280 |
+
"hf jobs run -e FOO=foo python:3.12 python script.py",
|
| 281 |
+
"hf jobs run --secrets HF_TOKEN python:3.12 python script.py",
|
| 282 |
+
"hf jobs run -v hf://gpt2:/data -v hf://buckets/org/b:/mnt python:3.12 python script.py",
|
| 283 |
+
],
|
| 284 |
+
)
|
| 285 |
+
def jobs_run(
|
| 286 |
+
image: ImageArg,
|
| 287 |
+
command: CommandArg,
|
| 288 |
+
env: EnvOpt = None,
|
| 289 |
+
secrets: SecretsOpt = None,
|
| 290 |
+
label: LabelsOpt = None,
|
| 291 |
+
volume: VolumesOpt = None,
|
| 292 |
+
env_file: EnvFileOpt = None,
|
| 293 |
+
secrets_file: SecretsFileOpt = None,
|
| 294 |
+
flavor: FlavorOpt = None,
|
| 295 |
+
timeout: TimeoutOpt = None,
|
| 296 |
+
detach: DetachOpt = False,
|
| 297 |
+
namespace: NamespaceOpt = None,
|
| 298 |
+
token: TokenOpt = None,
|
| 299 |
+
) -> None:
|
| 300 |
+
"""Run a Job."""
|
| 301 |
+
env_map = parse_env_map(env, env_file)
|
| 302 |
+
secrets_map = parse_env_map(secrets, secrets_file)
|
| 303 |
+
|
| 304 |
+
api = get_hf_api(token=token)
|
| 305 |
+
job = api.run_job(
|
| 306 |
+
image=image,
|
| 307 |
+
command=command,
|
| 308 |
+
env=env_map,
|
| 309 |
+
secrets=secrets_map,
|
| 310 |
+
labels=_parse_labels_map(label),
|
| 311 |
+
volumes=parse_volumes(volume),
|
| 312 |
+
flavor=flavor,
|
| 313 |
+
timeout=timeout,
|
| 314 |
+
namespace=namespace,
|
| 315 |
+
)
|
| 316 |
+
# Always print the job ID to the user
|
| 317 |
+
print(f"Job started with ID: {job.id}")
|
| 318 |
+
print(f"View at: {job.url}")
|
| 319 |
+
|
| 320 |
+
if detach:
|
| 321 |
+
return
|
| 322 |
+
# Now let's stream the logs
|
| 323 |
+
for log in api.fetch_job_logs(job_id=job.id, namespace=job.owner.name, follow=True):
|
| 324 |
+
print(log)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
@jobs_cli.command(
|
| 328 |
+
"logs", examples=["hf jobs logs <job_id>", "hf jobs logs -f <job_id>", "hf jobs logs --tail 20 <job_id>"]
|
| 329 |
+
)
|
| 330 |
+
def jobs_logs(
|
| 331 |
+
job_id: JobIdArg,
|
| 332 |
+
follow: Annotated[
|
| 333 |
+
bool,
|
| 334 |
+
typer.Option(
|
| 335 |
+
"-f",
|
| 336 |
+
"--follow",
|
| 337 |
+
help="Follow log output (stream until the job completes). Without this flag, only currently available logs are printed.",
|
| 338 |
+
),
|
| 339 |
+
] = False,
|
| 340 |
+
tail: Annotated[
|
| 341 |
+
int | None,
|
| 342 |
+
typer.Option(
|
| 343 |
+
"-n",
|
| 344 |
+
"--tail",
|
| 345 |
+
help="Number of lines to show from the end of the logs.",
|
| 346 |
+
),
|
| 347 |
+
] = None,
|
| 348 |
+
namespace: NamespaceOpt = None,
|
| 349 |
+
token: TokenOpt = None,
|
| 350 |
+
) -> None:
|
| 351 |
+
"""Fetch the logs of a Job.
|
| 352 |
+
|
| 353 |
+
By default, prints currently available logs and exits (non-blocking).
|
| 354 |
+
Use --follow/-f to stream logs in real-time until the job completes.
|
| 355 |
+
"""
|
| 356 |
+
job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
|
| 357 |
+
if follow and tail is not None:
|
| 358 |
+
raise CLIError(
|
| 359 |
+
"Cannot use --follow and --tail together. Use --follow to stream logs or --tail to show recent logs."
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
api = get_hf_api(token=token)
|
| 363 |
+
try:
|
| 364 |
+
logs = api.fetch_job_logs(job_id=job_id, namespace=namespace, follow=follow)
|
| 365 |
+
if tail is not None:
|
| 366 |
+
logs = deque(logs, maxlen=tail)
|
| 367 |
+
for log in logs:
|
| 368 |
+
print(log)
|
| 369 |
+
except HfHubHTTPError as e:
|
| 370 |
+
status = e.response.status_code if e.response is not None else None
|
| 371 |
+
if status == 404:
|
| 372 |
+
raise CLIError("Job not found. Please check the job ID.") from e
|
| 373 |
+
elif status == 403:
|
| 374 |
+
raise CLIError("Access denied. You may not have permission to view this job.") from e
|
| 375 |
+
else:
|
| 376 |
+
raise CLIError(f"Failed to fetch job logs: {e}") from e
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _matches_filters(job_properties: dict[str, str], filters: list[tuple[str, str, str]]) -> bool:
|
| 380 |
+
"""Check if scheduled job matches all specified filters."""
|
| 381 |
+
for key, op_str, pattern in filters:
|
| 382 |
+
value = job_properties.get(key)
|
| 383 |
+
if value is None:
|
| 384 |
+
if op_str == "!=":
|
| 385 |
+
continue
|
| 386 |
+
return False
|
| 387 |
+
match = fnmatch(value.lower(), pattern.lower())
|
| 388 |
+
if (op_str == "=" and not match) or (op_str == "!=" and match):
|
| 389 |
+
return False
|
| 390 |
+
return True
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _print_output(rows: list[list[str | int]], headers: list[str], aliases: list[str], fmt: str | None) -> None:
|
| 394 |
+
"""Print output according to the chosen format."""
|
| 395 |
+
if fmt:
|
| 396 |
+
# Use custom template if provided
|
| 397 |
+
template = fmt
|
| 398 |
+
for row in rows:
|
| 399 |
+
line = template
|
| 400 |
+
for i, field in enumerate(aliases):
|
| 401 |
+
placeholder = f"{{{{.{field}}}}}"
|
| 402 |
+
if placeholder in line:
|
| 403 |
+
line = line.replace(placeholder, str(row[i]))
|
| 404 |
+
print(line)
|
| 405 |
+
else:
|
| 406 |
+
# Default tabular format
|
| 407 |
+
print(_tabulate(rows, headers=headers))
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def _clear_line(n: int) -> None:
|
| 411 |
+
LINE_UP = "\033[1A"
|
| 412 |
+
LINE_CLEAR = "\x1b[2K"
|
| 413 |
+
for i in range(n):
|
| 414 |
+
print(LINE_UP, end=LINE_CLEAR)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _get_jobs_stats_rows(
|
| 418 |
+
job_id: str, metrics_stream: Iterable[dict[str, Any]], table_headers: list[str]
|
| 419 |
+
) -> Iterable[tuple[bool, str, list[list[str | int]]]]:
|
| 420 |
+
for metrics in metrics_stream:
|
| 421 |
+
row = [
|
| 422 |
+
job_id,
|
| 423 |
+
f"{metrics['cpu_usage_pct']}%",
|
| 424 |
+
round(metrics["cpu_millicores"] / 1000.0, 1),
|
| 425 |
+
f"{round(100 * metrics['memory_used_bytes'] / metrics['memory_total_bytes'], 2)}%",
|
| 426 |
+
f"{_format_size(metrics['memory_used_bytes'])}B / {_format_size(metrics['memory_total_bytes'])}B",
|
| 427 |
+
f"{_format_size(metrics['rx_bps'])}bps / {_format_size(metrics['tx_bps'])}bps",
|
| 428 |
+
]
|
| 429 |
+
if metrics["gpus"] and isinstance(metrics["gpus"], dict):
|
| 430 |
+
rows = [row] + [[""] * len(row)] * (len(metrics["gpus"]) - 1)
|
| 431 |
+
for row, gpu_id in zip(rows, sorted(metrics["gpus"])):
|
| 432 |
+
gpu = metrics["gpus"][gpu_id]
|
| 433 |
+
row += [
|
| 434 |
+
f"{gpu['utilization']}%",
|
| 435 |
+
f"{round(100 * gpu['memory_used_bytes'] / gpu['memory_total_bytes'], 2)}%",
|
| 436 |
+
f"{_format_size(gpu['memory_used_bytes'])}B / {_format_size(gpu['memory_total_bytes'])}B",
|
| 437 |
+
]
|
| 438 |
+
else:
|
| 439 |
+
row += ["N/A"] * (len(table_headers) - len(row))
|
| 440 |
+
rows = [row]
|
| 441 |
+
yield False, job_id, rows
|
| 442 |
+
yield True, job_id, []
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
@jobs_cli.command("stats", examples=["hf jobs stats <job_id>"])
|
| 446 |
+
def jobs_stats(
|
| 447 |
+
job_ids: JobIdsArg = None,
|
| 448 |
+
namespace: NamespaceOpt = None,
|
| 449 |
+
token: TokenOpt = None,
|
| 450 |
+
) -> None:
|
| 451 |
+
"""Fetch the resource usage statistics and metrics of Jobs"""
|
| 452 |
+
if job_ids is not None:
|
| 453 |
+
parsed_ids = []
|
| 454 |
+
for job_id in job_ids:
|
| 455 |
+
job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
|
| 456 |
+
parsed_ids.append(job_id)
|
| 457 |
+
job_ids = parsed_ids
|
| 458 |
+
api = get_hf_api(token=token)
|
| 459 |
+
if namespace is None:
|
| 460 |
+
namespace = api.whoami()["name"]
|
| 461 |
+
if job_ids is None:
|
| 462 |
+
job_ids = [
|
| 463 |
+
job.id
|
| 464 |
+
for job in api.list_jobs(namespace=namespace)
|
| 465 |
+
if (job.status.stage if job.status else "UNKNOWN") in ("RUNNING", "UPDATING")
|
| 466 |
+
]
|
| 467 |
+
if len(job_ids) == 0:
|
| 468 |
+
print("No running jobs found")
|
| 469 |
+
return
|
| 470 |
+
table_headers = [
|
| 471 |
+
"JOB ID",
|
| 472 |
+
"CPU %",
|
| 473 |
+
"NUM CPU",
|
| 474 |
+
"MEM %",
|
| 475 |
+
"MEM USAGE",
|
| 476 |
+
"NET I/O",
|
| 477 |
+
"GPU UTIL %",
|
| 478 |
+
"GPU MEM %",
|
| 479 |
+
"GPU MEM USAGE",
|
| 480 |
+
]
|
| 481 |
+
headers_aliases = [
|
| 482 |
+
"id",
|
| 483 |
+
"cpu_usage_pct",
|
| 484 |
+
"cpu_millicores",
|
| 485 |
+
"memory_used_bytes_pct",
|
| 486 |
+
"memory_used_bytes_and_total_bytes",
|
| 487 |
+
"rx_bps_and_tx_bps",
|
| 488 |
+
"gpu_utilization",
|
| 489 |
+
"gpu_memory_used_bytes_pct",
|
| 490 |
+
"gpu_memory_used_bytes_and_total_bytes",
|
| 491 |
+
]
|
| 492 |
+
try:
|
| 493 |
+
with multiprocessing.pool.ThreadPool(len(job_ids)) as pool:
|
| 494 |
+
rows_per_job_id: dict[str, list[list[str | int]]] = {}
|
| 495 |
+
for job_id in job_ids:
|
| 496 |
+
row: list[str | int] = [job_id]
|
| 497 |
+
row += ["-- / --" if ("/" in header or "USAGE" in header) else "--" for header in table_headers[1:]]
|
| 498 |
+
rows_per_job_id[job_id] = [row]
|
| 499 |
+
last_update_time = time.time()
|
| 500 |
+
total_rows = [row for job_id in rows_per_job_id for row in rows_per_job_id[job_id]]
|
| 501 |
+
_print_output(total_rows, table_headers, headers_aliases, None)
|
| 502 |
+
|
| 503 |
+
kwargs_list = [
|
| 504 |
+
{
|
| 505 |
+
"job_id": job_id,
|
| 506 |
+
"metrics_stream": api.fetch_job_metrics(job_id=job_id, namespace=namespace),
|
| 507 |
+
"table_headers": table_headers,
|
| 508 |
+
}
|
| 509 |
+
for job_id in job_ids
|
| 510 |
+
]
|
| 511 |
+
for done, job_id, rows in iflatmap_unordered(pool, _get_jobs_stats_rows, kwargs_list=kwargs_list):
|
| 512 |
+
if done:
|
| 513 |
+
rows_per_job_id.pop(job_id, None)
|
| 514 |
+
else:
|
| 515 |
+
rows_per_job_id[job_id] = rows
|
| 516 |
+
now = time.time()
|
| 517 |
+
if now - last_update_time >= STATS_UPDATE_MIN_INTERVAL:
|
| 518 |
+
_clear_line(2 + len(total_rows))
|
| 519 |
+
total_rows = [row for job_id in rows_per_job_id for row in rows_per_job_id[job_id]]
|
| 520 |
+
_print_output(total_rows, table_headers, headers_aliases, None)
|
| 521 |
+
last_update_time = now
|
| 522 |
+
except HfHubHTTPError as e:
|
| 523 |
+
status = e.response.status_code if e.response is not None else None
|
| 524 |
+
if status == 404:
|
| 525 |
+
raise CLIError("Job not found. Please check the job ID.") from e
|
| 526 |
+
elif status == 403:
|
| 527 |
+
raise CLIError("Access denied. You may not have permission to view this job.") from e
|
| 528 |
+
else:
|
| 529 |
+
raise CLIError(f"Failed to fetch job stats: {e}") from e
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
@jobs_cli.command("ps", examples=["hf jobs ps", "hf jobs ps -a"])
|
| 533 |
+
def jobs_ps(
|
| 534 |
+
all: Annotated[
|
| 535 |
+
bool,
|
| 536 |
+
typer.Option(
|
| 537 |
+
"-a",
|
| 538 |
+
"--all",
|
| 539 |
+
help="Show all Jobs (default shows just running)",
|
| 540 |
+
),
|
| 541 |
+
] = False,
|
| 542 |
+
namespace: NamespaceOpt = None,
|
| 543 |
+
token: TokenOpt = None,
|
| 544 |
+
filter: Annotated[
|
| 545 |
+
list[str] | None,
|
| 546 |
+
typer.Option(
|
| 547 |
+
"-f",
|
| 548 |
+
"--filter",
|
| 549 |
+
help="Filter output based on conditions provided (format: key=value)",
|
| 550 |
+
),
|
| 551 |
+
] = None,
|
| 552 |
+
format: Annotated[
|
| 553 |
+
str | None,
|
| 554 |
+
typer.Option(help="Output format: 'table' (default), 'json', or a Go template (e.g. '{{.id}}')"),
|
| 555 |
+
] = None,
|
| 556 |
+
quiet: QuietOpt = False,
|
| 557 |
+
) -> None:
|
| 558 |
+
"""List Jobs."""
|
| 559 |
+
api = get_hf_api(token=token)
|
| 560 |
+
# Fetch jobs data
|
| 561 |
+
jobs = api.list_jobs(namespace=namespace)
|
| 562 |
+
|
| 563 |
+
filters: list[tuple[str, str, str]] = []
|
| 564 |
+
labels_filters: list[tuple[str, str, str]] = []
|
| 565 |
+
for f in filter or []:
|
| 566 |
+
if f.startswith("label!=") or f.startswith("label="):
|
| 567 |
+
if f.startswith("label!="):
|
| 568 |
+
label_part = f[len("label!=") :]
|
| 569 |
+
if "=" in label_part:
|
| 570 |
+
print(
|
| 571 |
+
f"Warning: Ignoring invalid label filter format 'label!={label_part}'. Use label!=key format."
|
| 572 |
+
)
|
| 573 |
+
continue
|
| 574 |
+
label_key, op, label_value = label_part, "!=", "*"
|
| 575 |
+
else:
|
| 576 |
+
label_part = f[len("label=") :]
|
| 577 |
+
if "=" in label_part:
|
| 578 |
+
label_key, label_value = label_part.split("=", 1)
|
| 579 |
+
else:
|
| 580 |
+
label_key, label_value = label_part, "*"
|
| 581 |
+
# Negate predicate in case of key!=value
|
| 582 |
+
if label_key.endswith("!"):
|
| 583 |
+
op = "!="
|
| 584 |
+
label_key = label_key[:-1]
|
| 585 |
+
else:
|
| 586 |
+
op = "="
|
| 587 |
+
labels_filters.append((label_key.lower(), op, label_value.lower()))
|
| 588 |
+
elif "=" in f:
|
| 589 |
+
key, value = f.split("=", 1)
|
| 590 |
+
# Negate predicate in case of key!=value
|
| 591 |
+
if key.endswith("!"):
|
| 592 |
+
op = "!="
|
| 593 |
+
key = key[:-1]
|
| 594 |
+
else:
|
| 595 |
+
op = "="
|
| 596 |
+
filters.append((key.lower(), op, value.lower()))
|
| 597 |
+
else:
|
| 598 |
+
print(f"Warning: Ignoring invalid filter format '{f}'. Use key=value format.")
|
| 599 |
+
|
| 600 |
+
# Filter jobs (operating on JobInfo objects to preserve existing filter behavior)
|
| 601 |
+
filtered_jobs = []
|
| 602 |
+
for job in jobs:
|
| 603 |
+
status = job.status.stage if job.status else "UNKNOWN"
|
| 604 |
+
if not all and status not in ("RUNNING", "UPDATING"):
|
| 605 |
+
continue
|
| 606 |
+
image_or_space = job.docker_image or "N/A"
|
| 607 |
+
cmd = job.command or []
|
| 608 |
+
command_str = " ".join(cmd) if cmd else "N/A"
|
| 609 |
+
props = {"id": job.id, "image": image_or_space, "status": status.lower(), "command": command_str}
|
| 610 |
+
if not _matches_filters(props, filters):
|
| 611 |
+
continue
|
| 612 |
+
if not _matches_filters(job.labels or {}, labels_filters):
|
| 613 |
+
continue
|
| 614 |
+
filtered_jobs.append(job)
|
| 615 |
+
|
| 616 |
+
if not filtered_jobs:
|
| 617 |
+
if not quiet and format != "json":
|
| 618 |
+
filters_msg = f" matching filters: {', '.join([f'{k}{o}{v}' for k, o, v in filters])}" if filters else ""
|
| 619 |
+
print(f"No jobs found{filters_msg}")
|
| 620 |
+
elif format == "json":
|
| 621 |
+
print("[]")
|
| 622 |
+
return
|
| 623 |
+
|
| 624 |
+
headers = ["JOB ID", "IMAGE/SPACE", "COMMAND", "CREATED", "STATUS"]
|
| 625 |
+
aliases = ["id", "image", "command", "created", "status"]
|
| 626 |
+
items = [api_object_to_dict(job) for job in filtered_jobs]
|
| 627 |
+
|
| 628 |
+
def row_fn(item: dict[str, Any]) -> list[str]:
|
| 629 |
+
status = item.get("status", {})
|
| 630 |
+
cmd = item.get("command") or []
|
| 631 |
+
command_str = " ".join(cmd) if cmd else "N/A"
|
| 632 |
+
return [
|
| 633 |
+
str(item.get("id", "")),
|
| 634 |
+
_format_cell(item.get("docker_image") or "N/A"),
|
| 635 |
+
_format_cell(command_str),
|
| 636 |
+
item["created_at"][:19].replace("T", " ") if item.get("created_at") else "N/A",
|
| 637 |
+
str(status.get("stage", "UNKNOWN")),
|
| 638 |
+
]
|
| 639 |
+
|
| 640 |
+
# Custom template format
|
| 641 |
+
if format and format not in ("table", "json"):
|
| 642 |
+
_print_output([row_fn(item) for item in items], headers, aliases, format) # type: ignore
|
| 643 |
+
else:
|
| 644 |
+
output_format = OutputFormat.json if format == "json" else OutputFormat.table
|
| 645 |
+
print_list_output(
|
| 646 |
+
items=items,
|
| 647 |
+
format=output_format,
|
| 648 |
+
quiet=quiet,
|
| 649 |
+
id_key="id",
|
| 650 |
+
headers=headers,
|
| 651 |
+
row_fn=row_fn,
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
@jobs_cli.command("hardware", examples=["hf jobs hardware"])
|
| 656 |
+
def jobs_hardware() -> None:
|
| 657 |
+
"""List available hardware options for Jobs"""
|
| 658 |
+
api = get_hf_api()
|
| 659 |
+
hardware_list = api.list_jobs_hardware()
|
| 660 |
+
table_headers = ["NAME", "PRETTY NAME", "CPU", "RAM", "ACCELERATOR", "COST/MIN", "COST/HOUR"]
|
| 661 |
+
headers_aliases = ["name", "prettyName", "cpu", "ram", "accelerator", "costMin", "costHour"]
|
| 662 |
+
rows: list[list[str | int]] = []
|
| 663 |
+
|
| 664 |
+
for hw in hardware_list:
|
| 665 |
+
accelerator_info = "N/A"
|
| 666 |
+
if hw.accelerator:
|
| 667 |
+
accelerator_info = f"{hw.accelerator.quantity}x {hw.accelerator.model} ({hw.accelerator.vram})"
|
| 668 |
+
cost_min = f"${hw.unit_cost_usd:.4f}" if hw.unit_cost_usd is not None else "N/A"
|
| 669 |
+
cost_hour = f"${hw.unit_cost_usd * 60:.2f}" if hw.unit_cost_usd is not None else "N/A"
|
| 670 |
+
rows.append([hw.name, hw.pretty_name or "N/A", hw.cpu, hw.ram, accelerator_info, cost_min, cost_hour])
|
| 671 |
+
|
| 672 |
+
if not rows:
|
| 673 |
+
print("No hardware options found")
|
| 674 |
+
return
|
| 675 |
+
_print_output(rows, table_headers, headers_aliases, None)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
@jobs_cli.command("inspect", examples=["hf jobs inspect <job_id>"])
|
| 679 |
+
def jobs_inspect(
|
| 680 |
+
job_ids: Annotated[
|
| 681 |
+
list[str],
|
| 682 |
+
typer.Argument(
|
| 683 |
+
help="Job IDs to inspect (or 'namespace/job_id')",
|
| 684 |
+
),
|
| 685 |
+
],
|
| 686 |
+
namespace: NamespaceOpt = None,
|
| 687 |
+
token: TokenOpt = None,
|
| 688 |
+
) -> None:
|
| 689 |
+
"""Display detailed information on one or more Jobs"""
|
| 690 |
+
parsed_ids = []
|
| 691 |
+
for job_id in job_ids:
|
| 692 |
+
job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
|
| 693 |
+
parsed_ids.append(job_id)
|
| 694 |
+
job_ids = parsed_ids
|
| 695 |
+
api = get_hf_api(token=token)
|
| 696 |
+
try:
|
| 697 |
+
jobs = [api.inspect_job(job_id=job_id, namespace=namespace) for job_id in job_ids]
|
| 698 |
+
print(json.dumps([asdict(job) for job in jobs], indent=4, default=str))
|
| 699 |
+
except HfHubHTTPError as e:
|
| 700 |
+
status = e.response.status_code if e.response is not None else None
|
| 701 |
+
if status == 404:
|
| 702 |
+
raise CLIError("Job not found. Please check the job ID.") from e
|
| 703 |
+
elif status == 403:
|
| 704 |
+
raise CLIError("Access denied. You may not have permission to view this job.") from e
|
| 705 |
+
else:
|
| 706 |
+
raise CLIError(f"Failed to inspect job: {e}") from e
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
@jobs_cli.command("cancel", examples=["hf jobs cancel <job_id>"])
|
| 710 |
+
def jobs_cancel(
|
| 711 |
+
job_id: JobIdArg,
|
| 712 |
+
namespace: NamespaceOpt = None,
|
| 713 |
+
token: TokenOpt = None,
|
| 714 |
+
) -> None:
|
| 715 |
+
"""Cancel a Job"""
|
| 716 |
+
job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
|
| 717 |
+
api = get_hf_api(token=token)
|
| 718 |
+
try:
|
| 719 |
+
api.cancel_job(job_id=job_id, namespace=namespace)
|
| 720 |
+
except HfHubHTTPError as e:
|
| 721 |
+
status = e.response.status_code if e.response is not None else None
|
| 722 |
+
if status == 404:
|
| 723 |
+
raise CLIError("Job not found. Please check the job ID.") from e
|
| 724 |
+
elif status == 403:
|
| 725 |
+
raise CLIError("Access denied. You may not have permission to cancel this job.") from e
|
| 726 |
+
else:
|
| 727 |
+
raise CLIError(f"Failed to cancel job: {e}") from e
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
uv_app = typer_factory(help="Run UV scripts (Python with inline dependencies) on HF infrastructure.")
|
| 731 |
+
jobs_cli.add_typer(uv_app, name="uv")
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
@uv_app.command(
|
| 735 |
+
"run",
|
| 736 |
+
context_settings={"ignore_unknown_options": True},
|
| 737 |
+
examples=[
|
| 738 |
+
"hf jobs uv run my_script.py",
|
| 739 |
+
"hf jobs uv run ml_training.py --flavor a10g-small",
|
| 740 |
+
"hf jobs uv run --with transformers train.py",
|
| 741 |
+
"hf jobs uv run -v hf://gpt2:/data -v hf://buckets/org/b:/mnt script.py",
|
| 742 |
+
],
|
| 743 |
+
)
|
| 744 |
+
def jobs_uv_run(
|
| 745 |
+
script: ScriptArg,
|
| 746 |
+
script_args: ScriptArgsArg = None,
|
| 747 |
+
image: ImageOpt = None,
|
| 748 |
+
flavor: FlavorOpt = None,
|
| 749 |
+
env: EnvOpt = None,
|
| 750 |
+
secrets: SecretsOpt = None,
|
| 751 |
+
label: LabelsOpt = None,
|
| 752 |
+
volume: VolumesOpt = None,
|
| 753 |
+
env_file: EnvFileOpt = None,
|
| 754 |
+
secrets_file: SecretsFileOpt = None,
|
| 755 |
+
timeout: TimeoutOpt = None,
|
| 756 |
+
detach: DetachOpt = False,
|
| 757 |
+
namespace: NamespaceOpt = None,
|
| 758 |
+
token: TokenOpt = None,
|
| 759 |
+
with_: WithOpt = None,
|
| 760 |
+
python: PythonOpt = None,
|
| 761 |
+
) -> None:
|
| 762 |
+
"""Run a UV script (local file or URL) on HF infrastructure"""
|
| 763 |
+
env_map = parse_env_map(env, env_file)
|
| 764 |
+
secrets_map = parse_env_map(secrets, secrets_file)
|
| 765 |
+
|
| 766 |
+
api = get_hf_api(token=token)
|
| 767 |
+
job = api.run_uv_job(
|
| 768 |
+
script=script,
|
| 769 |
+
script_args=script_args or [],
|
| 770 |
+
dependencies=with_,
|
| 771 |
+
python=python,
|
| 772 |
+
image=image,
|
| 773 |
+
env=env_map,
|
| 774 |
+
secrets=secrets_map,
|
| 775 |
+
labels=_parse_labels_map(label),
|
| 776 |
+
volumes=parse_volumes(volume),
|
| 777 |
+
flavor=flavor, # type: ignore[arg-type,misc]
|
| 778 |
+
timeout=timeout,
|
| 779 |
+
namespace=namespace,
|
| 780 |
+
)
|
| 781 |
+
# Always print the job ID to the user
|
| 782 |
+
print(f"Job started with ID: {job.id}")
|
| 783 |
+
print(f"View at: {job.url}")
|
| 784 |
+
if detach:
|
| 785 |
+
return
|
| 786 |
+
# Now let's stream the logs
|
| 787 |
+
for log in api.fetch_job_logs(job_id=job.id, namespace=job.owner.name, follow=True):
|
| 788 |
+
print(log)
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
scheduled_app = typer_factory(help="Create and manage scheduled Jobs on the Hub.")
|
| 792 |
+
jobs_cli.add_typer(scheduled_app, name="scheduled")
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
@scheduled_app.command(
|
| 796 |
+
"run",
|
| 797 |
+
context_settings={"ignore_unknown_options": True},
|
| 798 |
+
examples=['hf jobs scheduled run "0 0 * * *" python:3.12 python script.py'],
|
| 799 |
+
)
|
| 800 |
+
def scheduled_run(
|
| 801 |
+
schedule: ScheduleArg,
|
| 802 |
+
image: ImageArg,
|
| 803 |
+
command: CommandArg,
|
| 804 |
+
suspend: SuspendOpt = None,
|
| 805 |
+
concurrency: ConcurrencyOpt = None,
|
| 806 |
+
env: EnvOpt = None,
|
| 807 |
+
secrets: SecretsOpt = None,
|
| 808 |
+
label: LabelsOpt = None,
|
| 809 |
+
volume: VolumesOpt = None,
|
| 810 |
+
env_file: EnvFileOpt = None,
|
| 811 |
+
secrets_file: SecretsFileOpt = None,
|
| 812 |
+
flavor: FlavorOpt = None,
|
| 813 |
+
timeout: TimeoutOpt = None,
|
| 814 |
+
namespace: NamespaceOpt = None,
|
| 815 |
+
token: TokenOpt = None,
|
| 816 |
+
) -> None:
|
| 817 |
+
"""Schedule a Job."""
|
| 818 |
+
env_map = parse_env_map(env, env_file)
|
| 819 |
+
secrets_map = parse_env_map(secrets, secrets_file)
|
| 820 |
+
|
| 821 |
+
api = get_hf_api(token=token)
|
| 822 |
+
scheduled_job = api.create_scheduled_job(
|
| 823 |
+
image=image,
|
| 824 |
+
command=command,
|
| 825 |
+
schedule=schedule,
|
| 826 |
+
suspend=suspend,
|
| 827 |
+
concurrency=concurrency,
|
| 828 |
+
env=env_map,
|
| 829 |
+
secrets=secrets_map,
|
| 830 |
+
labels=_parse_labels_map(label),
|
| 831 |
+
volumes=parse_volumes(volume),
|
| 832 |
+
flavor=flavor,
|
| 833 |
+
timeout=timeout,
|
| 834 |
+
namespace=namespace,
|
| 835 |
+
)
|
| 836 |
+
print(f"Scheduled Job created with ID: {scheduled_job.id}")
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
@scheduled_app.command("ps", examples=["hf jobs scheduled ps"])
|
| 840 |
+
def scheduled_ps(
|
| 841 |
+
all: Annotated[
|
| 842 |
+
bool,
|
| 843 |
+
typer.Option(
|
| 844 |
+
"-a",
|
| 845 |
+
"--all",
|
| 846 |
+
help="Show all scheduled Jobs (default hides suspended)",
|
| 847 |
+
),
|
| 848 |
+
] = False,
|
| 849 |
+
namespace: NamespaceOpt = None,
|
| 850 |
+
token: TokenOpt = None,
|
| 851 |
+
filter: Annotated[
|
| 852 |
+
list[str] | None,
|
| 853 |
+
typer.Option(
|
| 854 |
+
"-f",
|
| 855 |
+
"--filter",
|
| 856 |
+
help="Filter output based on conditions provided (format: key=value)",
|
| 857 |
+
),
|
| 858 |
+
] = None,
|
| 859 |
+
format: Annotated[
|
| 860 |
+
str | None,
|
| 861 |
+
typer.Option(help="Output format: 'table' (default), 'json', or a Go template (e.g. '{{.id}}')"),
|
| 862 |
+
] = None,
|
| 863 |
+
quiet: QuietOpt = False,
|
| 864 |
+
) -> None:
|
| 865 |
+
"""List scheduled Jobs"""
|
| 866 |
+
api = get_hf_api(token=token)
|
| 867 |
+
scheduled_jobs = api.list_scheduled_jobs(namespace=namespace)
|
| 868 |
+
filters: list[tuple[str, str, str]] = []
|
| 869 |
+
for f in filter or []:
|
| 870 |
+
if "=" in f:
|
| 871 |
+
key, value = f.split("=", 1)
|
| 872 |
+
# Negate predicate in case of key!=value
|
| 873 |
+
if key.endswith("!"):
|
| 874 |
+
op = "!="
|
| 875 |
+
key = key[:-1]
|
| 876 |
+
else:
|
| 877 |
+
op = "="
|
| 878 |
+
filters.append((key.lower(), op, value.lower()))
|
| 879 |
+
else:
|
| 880 |
+
print(f"Warning: Ignoring invalid filter format '{f}'. Use key=value format.")
|
| 881 |
+
|
| 882 |
+
# Filter scheduled jobs (operating on ScheduledJobInfo objects to preserve existing filter behavior)
|
| 883 |
+
filtered_jobs = []
|
| 884 |
+
for scheduled_job in scheduled_jobs:
|
| 885 |
+
suspend = scheduled_job.suspend or False
|
| 886 |
+
if not all and suspend:
|
| 887 |
+
continue
|
| 888 |
+
image_or_space = scheduled_job.job_spec.docker_image or "N/A"
|
| 889 |
+
cmd = scheduled_job.job_spec.command or []
|
| 890 |
+
command_str = " ".join(cmd) if cmd else "N/A"
|
| 891 |
+
props = {"id": scheduled_job.id, "image": image_or_space, "suspend": str(suspend), "command": command_str}
|
| 892 |
+
if not _matches_filters(props, filters):
|
| 893 |
+
continue
|
| 894 |
+
filtered_jobs.append(scheduled_job)
|
| 895 |
+
|
| 896 |
+
if not filtered_jobs:
|
| 897 |
+
if not quiet and format != "json":
|
| 898 |
+
filters_msg = f" matching filters: {', '.join([f'{k}{o}{v}' for k, o, v in filters])}" if filters else ""
|
| 899 |
+
print(f"No scheduled jobs found{filters_msg}")
|
| 900 |
+
elif format == "json":
|
| 901 |
+
print("[]")
|
| 902 |
+
return
|
| 903 |
+
|
| 904 |
+
headers = ["ID", "SCHEDULE", "IMAGE/SPACE", "COMMAND", "LAST RUN", "NEXT RUN", "SUSPEND"]
|
| 905 |
+
aliases = ["id", "schedule", "image", "command", "last", "next", "suspend"]
|
| 906 |
+
items = [api_object_to_dict(sj) for sj in filtered_jobs]
|
| 907 |
+
|
| 908 |
+
def row_fn(item: dict[str, Any]) -> list[str]:
|
| 909 |
+
job_spec = item.get("job_spec", {})
|
| 910 |
+
status = item.get("status", {})
|
| 911 |
+
last_job = status.get("last_job")
|
| 912 |
+
cmd = job_spec.get("command") or []
|
| 913 |
+
last_job_at = "N/A"
|
| 914 |
+
if last_job and last_job.get("at"):
|
| 915 |
+
last_job_at = last_job["at"][:19].replace("T", " ")
|
| 916 |
+
next_run = "N/A"
|
| 917 |
+
if status.get("next_job_run_at"):
|
| 918 |
+
next_run = status["next_job_run_at"][:19].replace("T", " ")
|
| 919 |
+
command_str = " ".join(cmd) if cmd else "N/A"
|
| 920 |
+
return [
|
| 921 |
+
str(item.get("id", "")),
|
| 922 |
+
str(item.get("schedule") or "N/A"),
|
| 923 |
+
_format_cell(job_spec.get("docker_image") or "N/A"),
|
| 924 |
+
_format_cell(command_str),
|
| 925 |
+
last_job_at,
|
| 926 |
+
next_run,
|
| 927 |
+
str(item.get("suspend", False)),
|
| 928 |
+
]
|
| 929 |
+
|
| 930 |
+
# Custom template format (e.g. --format '{{.id}} {{.schedule}}')
|
| 931 |
+
if format and format not in ("table", "json"):
|
| 932 |
+
_print_output([row_fn(item) for item in items], headers, aliases, format) # type: ignore
|
| 933 |
+
else:
|
| 934 |
+
output_format = OutputFormat.json if format == "json" else OutputFormat.table
|
| 935 |
+
print_list_output(
|
| 936 |
+
items=items,
|
| 937 |
+
format=output_format,
|
| 938 |
+
quiet=quiet,
|
| 939 |
+
id_key="id",
|
| 940 |
+
headers=headers,
|
| 941 |
+
row_fn=row_fn,
|
| 942 |
+
)
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
@scheduled_app.command("inspect", examples=["hf jobs scheduled inspect <id>"])
|
| 946 |
+
def scheduled_inspect(
|
| 947 |
+
scheduled_job_ids: Annotated[
|
| 948 |
+
list[str],
|
| 949 |
+
typer.Argument(
|
| 950 |
+
help="Scheduled Job IDs to inspect (or 'namespace/scheduled_job_id')",
|
| 951 |
+
),
|
| 952 |
+
],
|
| 953 |
+
namespace: NamespaceOpt = None,
|
| 954 |
+
token: TokenOpt = None,
|
| 955 |
+
) -> None:
|
| 956 |
+
"""Display detailed information on one or more scheduled Jobs"""
|
| 957 |
+
parsed_ids = []
|
| 958 |
+
for job_id in scheduled_job_ids:
|
| 959 |
+
job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
|
| 960 |
+
parsed_ids.append(job_id)
|
| 961 |
+
scheduled_job_ids = parsed_ids
|
| 962 |
+
api = get_hf_api(token=token)
|
| 963 |
+
scheduled_jobs = [
|
| 964 |
+
api.inspect_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
|
| 965 |
+
for scheduled_job_id in scheduled_job_ids
|
| 966 |
+
]
|
| 967 |
+
print(json.dumps([asdict(scheduled_job) for scheduled_job in scheduled_jobs], indent=4, default=str))
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
@scheduled_app.command("delete", examples=["hf jobs scheduled delete <id>"])
|
| 971 |
+
def scheduled_delete(
|
| 972 |
+
scheduled_job_id: ScheduledJobIdArg,
|
| 973 |
+
namespace: NamespaceOpt = None,
|
| 974 |
+
token: TokenOpt = None,
|
| 975 |
+
) -> None:
|
| 976 |
+
"""Delete a scheduled Job."""
|
| 977 |
+
scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
|
| 978 |
+
api = get_hf_api(token=token)
|
| 979 |
+
api.delete_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
@scheduled_app.command("suspend", examples=["hf jobs scheduled suspend <id>"])
|
| 983 |
+
def scheduled_suspend(
|
| 984 |
+
scheduled_job_id: ScheduledJobIdArg,
|
| 985 |
+
namespace: NamespaceOpt = None,
|
| 986 |
+
token: TokenOpt = None,
|
| 987 |
+
) -> None:
|
| 988 |
+
"""Suspend (pause) a scheduled Job."""
|
| 989 |
+
scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
|
| 990 |
+
api = get_hf_api(token=token)
|
| 991 |
+
api.suspend_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
@scheduled_app.command("resume", examples=["hf jobs scheduled resume <id>"])
|
| 995 |
+
def scheduled_resume(
|
| 996 |
+
scheduled_job_id: ScheduledJobIdArg,
|
| 997 |
+
namespace: NamespaceOpt = None,
|
| 998 |
+
token: TokenOpt = None,
|
| 999 |
+
) -> None:
|
| 1000 |
+
"""Resume (unpause) a scheduled Job."""
|
| 1001 |
+
scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
|
| 1002 |
+
api = get_hf_api(token=token)
|
| 1003 |
+
api.resume_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
|
| 1004 |
+
|
| 1005 |
+
|
| 1006 |
+
scheduled_uv_app = typer_factory(help="Schedule UV scripts on HF infrastructure.")
|
| 1007 |
+
scheduled_app.add_typer(scheduled_uv_app, name="uv")
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
@scheduled_uv_app.command(
|
| 1011 |
+
"run",
|
| 1012 |
+
context_settings={"ignore_unknown_options": True},
|
| 1013 |
+
examples=[
|
| 1014 |
+
'hf jobs scheduled uv run "0 0 * * *" script.py',
|
| 1015 |
+
'hf jobs scheduled uv run "0 0 * * *" script.py --with pandas',
|
| 1016 |
+
],
|
| 1017 |
+
)
|
| 1018 |
+
def scheduled_uv_run(
|
| 1019 |
+
schedule: ScheduleArg,
|
| 1020 |
+
script: ScriptArg,
|
| 1021 |
+
script_args: ScriptArgsArg = None,
|
| 1022 |
+
suspend: SuspendOpt = None,
|
| 1023 |
+
concurrency: ConcurrencyOpt = None,
|
| 1024 |
+
image: ImageOpt = None,
|
| 1025 |
+
flavor: FlavorOpt = None,
|
| 1026 |
+
env: EnvOpt = None,
|
| 1027 |
+
secrets: SecretsOpt = None,
|
| 1028 |
+
label: LabelsOpt = None,
|
| 1029 |
+
volume: VolumesOpt = None,
|
| 1030 |
+
env_file: EnvFileOpt = None,
|
| 1031 |
+
secrets_file: SecretsFileOpt = None,
|
| 1032 |
+
timeout: TimeoutOpt = None,
|
| 1033 |
+
namespace: NamespaceOpt = None,
|
| 1034 |
+
token: TokenOpt = None,
|
| 1035 |
+
with_: WithOpt = None,
|
| 1036 |
+
python: PythonOpt = None,
|
| 1037 |
+
) -> None:
|
| 1038 |
+
"""Run a UV script (local file or URL) on HF infrastructure"""
|
| 1039 |
+
env_map = parse_env_map(env, env_file)
|
| 1040 |
+
secrets_map = parse_env_map(secrets, secrets_file)
|
| 1041 |
+
|
| 1042 |
+
api = get_hf_api(token=token)
|
| 1043 |
+
job = api.create_scheduled_uv_job(
|
| 1044 |
+
script=script,
|
| 1045 |
+
script_args=script_args or [],
|
| 1046 |
+
schedule=schedule,
|
| 1047 |
+
suspend=suspend,
|
| 1048 |
+
concurrency=concurrency,
|
| 1049 |
+
dependencies=with_,
|
| 1050 |
+
python=python,
|
| 1051 |
+
image=image,
|
| 1052 |
+
env=env_map,
|
| 1053 |
+
secrets=secrets_map,
|
| 1054 |
+
labels=_parse_labels_map(label),
|
| 1055 |
+
volumes=parse_volumes(volume),
|
| 1056 |
+
flavor=flavor, # type: ignore[arg-type,misc]
|
| 1057 |
+
timeout=timeout,
|
| 1058 |
+
namespace=namespace,
|
| 1059 |
+
)
|
| 1060 |
+
print(f"Scheduled Job created with ID: {job.id}")
|
| 1061 |
+
|
| 1062 |
+
|
| 1063 |
+
### UTILS
|
| 1064 |
+
|
| 1065 |
+
|
| 1066 |
+
def _parse_labels_map(labels: list[str] | None) -> dict[str, str] | None:
|
| 1067 |
+
"""Parse label key-value pairs from CLI arguments.
|
| 1068 |
+
|
| 1069 |
+
Args:
|
| 1070 |
+
labels: List of label strings in KEY=VALUE format. If KEY only, then VALUE is set to empty string.
|
| 1071 |
+
|
| 1072 |
+
Returns:
|
| 1073 |
+
Dictionary mapping label keys to values, or None if no labels provided.
|
| 1074 |
+
"""
|
| 1075 |
+
if not labels:
|
| 1076 |
+
return None
|
| 1077 |
+
labels_map: dict[str, str] = {}
|
| 1078 |
+
for label_var in labels:
|
| 1079 |
+
key, value = label_var.split("=", 1) if "=" in label_var else (label_var, "")
|
| 1080 |
+
labels_map[key] = value
|
| 1081 |
+
return labels_map
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
def _tabulate(rows: list[list[str | int]], headers: list[str]) -> str:
|
| 1085 |
+
"""
|
| 1086 |
+
Inspired by:
|
| 1087 |
+
|
| 1088 |
+
- stackoverflow.com/a/8356620/593036
|
| 1089 |
+
- stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
|
| 1090 |
+
"""
|
| 1091 |
+
col_widths = [max(len(str(x)) for x in col) for col in zip(*rows, headers)]
|
| 1092 |
+
terminal_width = max(shutil.get_terminal_size().columns, len(headers) * 12)
|
| 1093 |
+
while len(headers) + sum(col_widths) > terminal_width:
|
| 1094 |
+
col_to_minimize = col_widths.index(max(col_widths))
|
| 1095 |
+
col_widths[col_to_minimize] //= 2
|
| 1096 |
+
if len(headers) + sum(col_widths) <= terminal_width:
|
| 1097 |
+
col_widths[col_to_minimize] = terminal_width - sum(col_widths) - len(headers) + col_widths[col_to_minimize]
|
| 1098 |
+
row_format = ("{{:{}}} " * len(headers)).format(*col_widths)
|
| 1099 |
+
lines = []
|
| 1100 |
+
lines.append(row_format.format(*headers))
|
| 1101 |
+
lines.append(row_format.format(*["-" * w for w in col_widths]))
|
| 1102 |
+
for row in rows:
|
| 1103 |
+
row_format_args = [
|
| 1104 |
+
str(x)[: col_width - 3] + "..." if len(str(x)) > col_width else str(x)
|
| 1105 |
+
for x, col_width in zip(row, col_widths)
|
| 1106 |
+
]
|
| 1107 |
+
lines.append(row_format.format(*row_format_args))
|
| 1108 |
+
return "\n".join(lines)
|
| 1109 |
+
|
| 1110 |
+
|
| 1111 |
+
T = TypeVar("T")
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
def _write_generator_to_queue(queue: Queue[T], func: Callable[..., Iterable[T]], kwargs: dict) -> None:
|
| 1115 |
+
for result in func(**kwargs):
|
| 1116 |
+
queue.put(result)
|
| 1117 |
+
|
| 1118 |
+
|
| 1119 |
+
def iflatmap_unordered(
|
| 1120 |
+
pool: multiprocessing.pool.ThreadPool,
|
| 1121 |
+
func: Callable[..., Iterable[T]],
|
| 1122 |
+
*,
|
| 1123 |
+
kwargs_list: list[dict],
|
| 1124 |
+
) -> Iterable[T]:
|
| 1125 |
+
"""
|
| 1126 |
+
Takes a function that returns an iterable of items, and run it in parallel using threads to return the flattened iterable of items as they arrive.
|
| 1127 |
+
|
| 1128 |
+
This is inspired by those three `map()` variants, and is the mix of all three:
|
| 1129 |
+
|
| 1130 |
+
* `imap()`: like `map()` but returns an iterable instead of a list of results
|
| 1131 |
+
* `imap_unordered()`: like `imap()` but the output is sorted by time of arrival
|
| 1132 |
+
* `flatmap()`: like `map()` but given a function which returns a list, `flatmap()` returns the flattened list that is the concatenation of all the output lists
|
| 1133 |
+
"""
|
| 1134 |
+
queue: Queue[T] = Queue()
|
| 1135 |
+
async_results = [pool.apply_async(_write_generator_to_queue, (queue, func, kwargs)) for kwargs in kwargs_list]
|
| 1136 |
+
try:
|
| 1137 |
+
while True:
|
| 1138 |
+
try:
|
| 1139 |
+
yield queue.get(timeout=0.05)
|
| 1140 |
+
except Empty:
|
| 1141 |
+
if all(async_result.ready() for async_result in async_results) and queue.empty():
|
| 1142 |
+
break
|
| 1143 |
+
except KeyboardInterrupt:
|
| 1144 |
+
pass
|
| 1145 |
+
finally:
|
| 1146 |
+
# we get the result in case there's an error to raise
|
| 1147 |
+
try:
|
| 1148 |
+
[async_result.get(timeout=0.05) for async_result in async_results]
|
| 1149 |
+
except multiprocessing.TimeoutError:
|
| 1150 |
+
pass
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/lfs.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Implementation of a custom transfer agent for the transfer type "multipart" for
|
| 3 |
+
git-lfs.
|
| 4 |
+
|
| 5 |
+
Inspired by:
|
| 6 |
+
github.com/cbartz/git-lfs-swift-transfer-agent/blob/master/git_lfs_swift_transfer.py
|
| 7 |
+
|
| 8 |
+
Spec is: github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
To launch debugger while developing:
|
| 12 |
+
|
| 13 |
+
``` [lfs "customtransfer.multipart"]
|
| 14 |
+
path = /path/to/huggingface_hub/.venv/bin/python args = -m debugpy --listen 5678
|
| 15 |
+
--wait-for-client
|
| 16 |
+
/path/to/huggingface_hub/src/huggingface_hub/commands/huggingface_cli.py
|
| 17 |
+
lfs-multipart-upload ```"""
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import subprocess
|
| 22 |
+
import sys
|
| 23 |
+
from typing import Annotated
|
| 24 |
+
|
| 25 |
+
import typer
|
| 26 |
+
|
| 27 |
+
from huggingface_hub.errors import CLIError
|
| 28 |
+
from huggingface_hub.lfs import LFS_MULTIPART_UPLOAD_COMMAND
|
| 29 |
+
|
| 30 |
+
from ..utils import get_session, hf_raise_for_status, logging
|
| 31 |
+
from ..utils._lfs import SliceFileObj
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
logger = logging.get_logger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def lfs_enable_largefiles(
|
| 38 |
+
path: Annotated[
|
| 39 |
+
str,
|
| 40 |
+
typer.Argument(
|
| 41 |
+
help="Local path to repository you want to configure.",
|
| 42 |
+
),
|
| 43 |
+
],
|
| 44 |
+
) -> None:
|
| 45 |
+
"""
|
| 46 |
+
Configure your repository to enable upload of files > 5GB.
|
| 47 |
+
|
| 48 |
+
This command sets up git-lfs to use the custom multipart transfer agent
|
| 49 |
+
which enables efficient uploading of large files in chunks.
|
| 50 |
+
"""
|
| 51 |
+
local_path = os.path.abspath(path)
|
| 52 |
+
if not os.path.isdir(local_path):
|
| 53 |
+
raise CLIError("This does not look like a valid git repo.")
|
| 54 |
+
subprocess.run(
|
| 55 |
+
"git config lfs.customtransfer.multipart.path hf".split(),
|
| 56 |
+
check=True,
|
| 57 |
+
cwd=local_path,
|
| 58 |
+
)
|
| 59 |
+
subprocess.run(
|
| 60 |
+
f"git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}".split(),
|
| 61 |
+
check=True,
|
| 62 |
+
cwd=local_path,
|
| 63 |
+
)
|
| 64 |
+
print("Local repo set up for largefiles")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def write_msg(msg: dict):
|
| 68 |
+
"""Write out the message in Line delimited JSON."""
|
| 69 |
+
msg_str = json.dumps(msg) + "\n"
|
| 70 |
+
sys.stdout.write(msg_str)
|
| 71 |
+
sys.stdout.flush()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def read_msg() -> dict | None:
|
| 75 |
+
"""Read Line delimited JSON from stdin."""
|
| 76 |
+
msg = json.loads(sys.stdin.readline().strip())
|
| 77 |
+
|
| 78 |
+
if "terminate" in (msg.get("type"), msg.get("event")):
|
| 79 |
+
# terminate message received
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
if msg.get("event") not in ("download", "upload"):
|
| 83 |
+
logger.critical("Received unexpected message")
|
| 84 |
+
sys.exit(1)
|
| 85 |
+
|
| 86 |
+
return msg
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def lfs_multipart_upload() -> None:
|
| 90 |
+
"""Internal git-lfs custom transfer agent for multipart uploads.
|
| 91 |
+
|
| 92 |
+
This function implements the custom transfer protocol for git-lfs multipart uploads.
|
| 93 |
+
Handles chunked uploads of large files to Hugging Face Hub.
|
| 94 |
+
"""
|
| 95 |
+
# Immediately after invoking a custom transfer process, git-lfs
|
| 96 |
+
# sends initiation data to the process over stdin.
|
| 97 |
+
# This tells the process useful information about the configuration.
|
| 98 |
+
init_msg = json.loads(sys.stdin.readline().strip())
|
| 99 |
+
if not (init_msg.get("event") == "init" and init_msg.get("operation") == "upload"):
|
| 100 |
+
write_msg({"error": {"code": 32, "message": "Wrong lfs init operation"}})
|
| 101 |
+
sys.exit(1)
|
| 102 |
+
|
| 103 |
+
# The transfer process should use the information it needs from the
|
| 104 |
+
# initiation structure, and also perform any one-off setup tasks it
|
| 105 |
+
# needs to do. It should then respond on stdout with a simple empty
|
| 106 |
+
# confirmation structure, as follows:
|
| 107 |
+
write_msg({})
|
| 108 |
+
|
| 109 |
+
# After the initiation exchange, git-lfs will send any number of
|
| 110 |
+
# transfer requests to the stdin of the transfer process, in a serial sequence.
|
| 111 |
+
while True:
|
| 112 |
+
msg = read_msg()
|
| 113 |
+
if msg is None:
|
| 114 |
+
# When all transfers have been processed, git-lfs will send
|
| 115 |
+
# a terminate event to the stdin of the transfer process.
|
| 116 |
+
# On receiving this message the transfer process should
|
| 117 |
+
# clean up and terminate. No response is expected.
|
| 118 |
+
sys.exit(0)
|
| 119 |
+
|
| 120 |
+
oid = msg["oid"]
|
| 121 |
+
filepath = msg["path"]
|
| 122 |
+
completion_url = msg["action"]["href"]
|
| 123 |
+
header = msg["action"]["header"]
|
| 124 |
+
chunk_size = int(header.pop("chunk_size"))
|
| 125 |
+
presigned_urls: list[str] = list(header.values())
|
| 126 |
+
|
| 127 |
+
# Send a "started" progress event to allow other workers to start.
|
| 128 |
+
# Otherwise they're delayed until first "progress" event is reported,
|
| 129 |
+
# i.e. after the first 5GB by default (!)
|
| 130 |
+
write_msg(
|
| 131 |
+
{
|
| 132 |
+
"event": "progress",
|
| 133 |
+
"oid": oid,
|
| 134 |
+
"bytesSoFar": 1,
|
| 135 |
+
"bytesSinceLast": 0,
|
| 136 |
+
}
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
parts = []
|
| 140 |
+
with open(filepath, "rb") as file:
|
| 141 |
+
for i, presigned_url in enumerate(presigned_urls):
|
| 142 |
+
with SliceFileObj(
|
| 143 |
+
file,
|
| 144 |
+
seek_from=i * chunk_size,
|
| 145 |
+
read_limit=chunk_size,
|
| 146 |
+
) as data:
|
| 147 |
+
r = get_session().put(presigned_url, data=data)
|
| 148 |
+
hf_raise_for_status(r)
|
| 149 |
+
parts.append(
|
| 150 |
+
{
|
| 151 |
+
"etag": r.headers.get("etag"),
|
| 152 |
+
"partNumber": i + 1,
|
| 153 |
+
}
|
| 154 |
+
)
|
| 155 |
+
# In order to support progress reporting while data is uploading / downloading,
|
| 156 |
+
# the transfer process should post messages to stdout
|
| 157 |
+
write_msg(
|
| 158 |
+
{
|
| 159 |
+
"event": "progress",
|
| 160 |
+
"oid": oid,
|
| 161 |
+
"bytesSoFar": (i + 1) * chunk_size,
|
| 162 |
+
"bytesSinceLast": chunk_size,
|
| 163 |
+
}
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
r = get_session().post(
|
| 167 |
+
completion_url,
|
| 168 |
+
json={
|
| 169 |
+
"oid": oid,
|
| 170 |
+
"parts": parts,
|
| 171 |
+
},
|
| 172 |
+
)
|
| 173 |
+
hf_raise_for_status(r)
|
| 174 |
+
|
| 175 |
+
write_msg({"event": "complete", "oid": oid})
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/models.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with models on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# list models on the Hub
|
| 18 |
+
hf models ls
|
| 19 |
+
|
| 20 |
+
# list models with a search query
|
| 21 |
+
hf models ls --search "llama"
|
| 22 |
+
|
| 23 |
+
# get info about a model
|
| 24 |
+
hf models info Lightricks/LTX-2
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import enum
|
| 28 |
+
from typing import Annotated, get_args
|
| 29 |
+
|
| 30 |
+
import typer
|
| 31 |
+
|
| 32 |
+
from huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundError
|
| 33 |
+
from huggingface_hub.hf_api import ExpandModelProperty_T, ModelSort_T
|
| 34 |
+
|
| 35 |
+
from ._cli_utils import (
|
| 36 |
+
AuthorOpt,
|
| 37 |
+
FilterOpt,
|
| 38 |
+
FormatWithAutoOpt,
|
| 39 |
+
LimitOpt,
|
| 40 |
+
RevisionOpt,
|
| 41 |
+
SearchOpt,
|
| 42 |
+
TokenOpt,
|
| 43 |
+
api_object_to_dict,
|
| 44 |
+
get_hf_api,
|
| 45 |
+
make_expand_properties_parser,
|
| 46 |
+
typer_factory,
|
| 47 |
+
)
|
| 48 |
+
from ._output import OutputFormatWithAuto, out
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
_EXPAND_PROPERTIES = sorted(get_args(ExpandModelProperty_T))
|
| 52 |
+
_SORT_OPTIONS = get_args(ModelSort_T)
|
| 53 |
+
ModelSortEnum = enum.Enum("ModelSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
ExpandOpt = Annotated[
|
| 57 |
+
str | None,
|
| 58 |
+
typer.Option(
|
| 59 |
+
help=f"Comma-separated properties to return. When used, only the listed properties (and id) are returned. Example: '--expand=downloads,likes,tags'. Valid: {', '.join(_EXPAND_PROPERTIES)}.",
|
| 60 |
+
callback=make_expand_properties_parser(_EXPAND_PROPERTIES),
|
| 61 |
+
),
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
models_cli = typer_factory(help="Interact with models on the Hub.")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@models_cli.command(
|
| 69 |
+
"list | ls",
|
| 70 |
+
examples=[
|
| 71 |
+
"hf models ls --sort downloads --limit 10",
|
| 72 |
+
'hf models ls --search "llama" --author meta-llama',
|
| 73 |
+
"hf models ls --num-parameters min:6B,max:128B --sort likes",
|
| 74 |
+
],
|
| 75 |
+
)
|
| 76 |
+
def models_ls(
|
| 77 |
+
search: SearchOpt = None,
|
| 78 |
+
author: AuthorOpt = None,
|
| 79 |
+
filter: FilterOpt = None,
|
| 80 |
+
num_parameters: Annotated[
|
| 81 |
+
str | None,
|
| 82 |
+
typer.Option(help="Filter by parameter count, e.g. 'min:6B,max:128B'."),
|
| 83 |
+
] = None,
|
| 84 |
+
sort: Annotated[
|
| 85 |
+
ModelSortEnum | None,
|
| 86 |
+
typer.Option(help="Sort results."),
|
| 87 |
+
] = None,
|
| 88 |
+
limit: LimitOpt = 10,
|
| 89 |
+
expand: ExpandOpt = None,
|
| 90 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 91 |
+
token: TokenOpt = None,
|
| 92 |
+
) -> None:
|
| 93 |
+
"""List models on the Hub."""
|
| 94 |
+
api = get_hf_api(token=token)
|
| 95 |
+
sort_key = sort.value if sort else None
|
| 96 |
+
results = [
|
| 97 |
+
api_object_to_dict(model_info)
|
| 98 |
+
for model_info in api.list_models(
|
| 99 |
+
filter=filter,
|
| 100 |
+
author=author,
|
| 101 |
+
search=search,
|
| 102 |
+
num_parameters=num_parameters,
|
| 103 |
+
sort=sort_key,
|
| 104 |
+
limit=limit,
|
| 105 |
+
expand=expand, # type: ignore
|
| 106 |
+
)
|
| 107 |
+
]
|
| 108 |
+
out.table(results)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@models_cli.command(
|
| 112 |
+
"info",
|
| 113 |
+
examples=[
|
| 114 |
+
"hf models info meta-llama/Llama-3.2-1B-Instruct",
|
| 115 |
+
"hf models info Qwen/Qwen3.5-9B --expand downloads,likes,tags",
|
| 116 |
+
],
|
| 117 |
+
)
|
| 118 |
+
def models_info(
|
| 119 |
+
model_id: Annotated[str, typer.Argument(help="The model ID (e.g. `username/repo-name`).")],
|
| 120 |
+
revision: RevisionOpt = None,
|
| 121 |
+
expand: ExpandOpt = None,
|
| 122 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 123 |
+
token: TokenOpt = None,
|
| 124 |
+
) -> None:
|
| 125 |
+
"""Get info about a model on the Hub."""
|
| 126 |
+
api = get_hf_api(token=token)
|
| 127 |
+
try:
|
| 128 |
+
info = api.model_info(repo_id=model_id, revision=revision, expand=expand) # type: ignore
|
| 129 |
+
except RepositoryNotFoundError as e:
|
| 130 |
+
raise CLIError(f"Model '{model_id}' not found.") from e
|
| 131 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with papers on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# list daily papers (most recently submitted)
|
| 18 |
+
hf papers ls
|
| 19 |
+
|
| 20 |
+
# list trending papers
|
| 21 |
+
hf papers ls --sort=trending
|
| 22 |
+
|
| 23 |
+
# list papers from a specific date, ordered by upvotes
|
| 24 |
+
hf papers ls --date=2025-01-23
|
| 25 |
+
|
| 26 |
+
# list today's papers, ordered by upvotes
|
| 27 |
+
hf papers ls --date=today
|
| 28 |
+
|
| 29 |
+
# list papers from a specific week
|
| 30 |
+
hf papers ls --week=2025-W09
|
| 31 |
+
|
| 32 |
+
# list papers by a specific submitter
|
| 33 |
+
hf papers ls --submitter=someuser
|
| 34 |
+
|
| 35 |
+
# search papers
|
| 36 |
+
hf papers search "vision language"
|
| 37 |
+
|
| 38 |
+
# get info about a paper
|
| 39 |
+
hf papers info 2502.08025
|
| 40 |
+
|
| 41 |
+
# read a paper as markdown
|
| 42 |
+
hf papers read 2502.08025
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
import datetime
|
| 46 |
+
import enum
|
| 47 |
+
from typing import Annotated, get_args
|
| 48 |
+
|
| 49 |
+
import typer
|
| 50 |
+
|
| 51 |
+
from huggingface_hub.errors import CLIError, HfHubHTTPError
|
| 52 |
+
from huggingface_hub.hf_api import DailyPapersSort_T
|
| 53 |
+
|
| 54 |
+
from ._cli_utils import (
|
| 55 |
+
FormatWithAutoOpt,
|
| 56 |
+
LimitOpt,
|
| 57 |
+
TokenOpt,
|
| 58 |
+
api_object_to_dict,
|
| 59 |
+
get_hf_api,
|
| 60 |
+
typer_factory,
|
| 61 |
+
)
|
| 62 |
+
from ._output import OutputFormatWithAuto, out
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
_SORT_OPTIONS = get_args(DailyPapersSort_T)
|
| 66 |
+
PaperSortEnum = enum.Enum("PaperSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _parse_date(value: str | None) -> str | None:
|
| 70 |
+
"""Parse date option, converting 'today' to current date."""
|
| 71 |
+
if value is None:
|
| 72 |
+
return None
|
| 73 |
+
if value.lower() == "today":
|
| 74 |
+
return datetime.date.today().isoformat()
|
| 75 |
+
return value
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
papers_cli = typer_factory(help="Interact with papers on the Hub.")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@papers_cli.command(
|
| 82 |
+
"list | ls",
|
| 83 |
+
examples=[
|
| 84 |
+
"hf papers ls",
|
| 85 |
+
"hf papers ls --sort trending",
|
| 86 |
+
"hf papers ls --date 2025-01-23",
|
| 87 |
+
"hf papers ls --week 2025-W09",
|
| 88 |
+
"hf papers ls --submitter akhaliq",
|
| 89 |
+
"hf papers ls --format json",
|
| 90 |
+
],
|
| 91 |
+
)
|
| 92 |
+
def papers_ls(
|
| 93 |
+
date: Annotated[
|
| 94 |
+
str | None,
|
| 95 |
+
typer.Option(
|
| 96 |
+
help="Date in ISO format (YYYY-MM-DD) or 'today'.",
|
| 97 |
+
callback=_parse_date,
|
| 98 |
+
),
|
| 99 |
+
] = None,
|
| 100 |
+
week: Annotated[
|
| 101 |
+
str | None,
|
| 102 |
+
typer.Option(help="ISO week to filter by, e.g. '2025-W09'."),
|
| 103 |
+
] = None,
|
| 104 |
+
month: Annotated[
|
| 105 |
+
str | None,
|
| 106 |
+
typer.Option(help="Month to filter by in ISO format (YYYY-MM), e.g. '2025-02'."),
|
| 107 |
+
] = None,
|
| 108 |
+
submitter: Annotated[
|
| 109 |
+
str | None,
|
| 110 |
+
typer.Option(help="Filter by username of the submitter."),
|
| 111 |
+
] = None,
|
| 112 |
+
sort: Annotated[
|
| 113 |
+
PaperSortEnum | None,
|
| 114 |
+
typer.Option(help="Sort results."),
|
| 115 |
+
] = None,
|
| 116 |
+
limit: LimitOpt = 50,
|
| 117 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 118 |
+
token: TokenOpt = None,
|
| 119 |
+
) -> None:
|
| 120 |
+
"""List daily papers on the Hub."""
|
| 121 |
+
api = get_hf_api(token=token)
|
| 122 |
+
sort_key = sort.value if sort else None
|
| 123 |
+
results = []
|
| 124 |
+
for paper_info in api.list_daily_papers(
|
| 125 |
+
date=date,
|
| 126 |
+
week=week,
|
| 127 |
+
month=month,
|
| 128 |
+
submitter=submitter,
|
| 129 |
+
sort=sort_key,
|
| 130 |
+
limit=limit,
|
| 131 |
+
):
|
| 132 |
+
item = api_object_to_dict(paper_info)
|
| 133 |
+
submitted_by = item.get("submitted_by") or {}
|
| 134 |
+
item["submitted_by_name"] = submitted_by.get("fullname") or submitted_by.get("username") or ""
|
| 135 |
+
results.append(item)
|
| 136 |
+
out.table(
|
| 137 |
+
results,
|
| 138 |
+
headers=["id", "title", "upvotes", "comments", "published_at", "submitted_by_name"],
|
| 139 |
+
alignments={"upvotes": "right", "comments": "right"},
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@papers_cli.command(
|
| 144 |
+
"search",
|
| 145 |
+
examples=[
|
| 146 |
+
'hf papers search "vision language"',
|
| 147 |
+
'hf papers search "attention mechanism" --limit 10',
|
| 148 |
+
'hf papers search "diffusion" --format json',
|
| 149 |
+
],
|
| 150 |
+
)
|
| 151 |
+
def papers_search(
|
| 152 |
+
query: Annotated[str, typer.Argument(help="Search query string.")],
|
| 153 |
+
limit: LimitOpt = 20,
|
| 154 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 155 |
+
token: TokenOpt = None,
|
| 156 |
+
) -> None:
|
| 157 |
+
"""Search papers on the Hub."""
|
| 158 |
+
api = get_hf_api(token=token)
|
| 159 |
+
results = [api_object_to_dict(paper_info) for paper_info in api.list_papers(query=query, limit=limit)]
|
| 160 |
+
out.table(results, headers=["id", "title", "summary", "upvotes", "published_at"], alignments={"upvotes": "right"})
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@papers_cli.command(
|
| 164 |
+
"info",
|
| 165 |
+
examples=[
|
| 166 |
+
"hf papers info 2601.15621",
|
| 167 |
+
],
|
| 168 |
+
)
|
| 169 |
+
def papers_info(
|
| 170 |
+
paper_id: Annotated[str, typer.Argument(help="The arXiv paper ID (e.g. '2502.08025').")],
|
| 171 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 172 |
+
token: TokenOpt = None,
|
| 173 |
+
) -> None:
|
| 174 |
+
"""Get info about a paper on the Hub."""
|
| 175 |
+
api = get_hf_api(token=token)
|
| 176 |
+
try:
|
| 177 |
+
info = api.paper_info(id=paper_id)
|
| 178 |
+
except HfHubHTTPError as e:
|
| 179 |
+
if e.response.status_code == 404:
|
| 180 |
+
raise CLIError(f"Paper '{paper_id}' not found on the Hub.") from e
|
| 181 |
+
raise
|
| 182 |
+
out.dict(info)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@papers_cli.command(
|
| 186 |
+
"read",
|
| 187 |
+
examples=[
|
| 188 |
+
"hf papers read 2601.15621",
|
| 189 |
+
],
|
| 190 |
+
)
|
| 191 |
+
def papers_read(
|
| 192 |
+
paper_id: Annotated[str, typer.Argument(help="The arXiv paper ID (e.g. '2502.08025').")],
|
| 193 |
+
token: TokenOpt = None,
|
| 194 |
+
) -> None:
|
| 195 |
+
"""Read a paper as markdown."""
|
| 196 |
+
api = get_hf_api(token=token)
|
| 197 |
+
try:
|
| 198 |
+
content = api.read_paper(id=paper_id)
|
| 199 |
+
except HfHubHTTPError as e:
|
| 200 |
+
if e.response.status_code == 404:
|
| 201 |
+
raise CLIError(f"Paper '{paper_id}' not found on the Hub.") from e
|
| 202 |
+
raise
|
| 203 |
+
out.text(content)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/repo_files.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Legacy `hf repo-files` command.
|
| 15 |
+
|
| 16 |
+
Kept for backward compatibility. Users are nudged to use `hf repos delete-files` instead.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import sys
|
| 20 |
+
from typing import Annotated
|
| 21 |
+
|
| 22 |
+
import typer
|
| 23 |
+
|
| 24 |
+
from huggingface_hub import logging
|
| 25 |
+
from huggingface_hub.utils import ANSI
|
| 26 |
+
|
| 27 |
+
from ._cli_utils import RepoIdArg, RepoType, RepoTypeOpt, RevisionOpt, TokenOpt, get_hf_api, typer_factory
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
logger = logging.get_logger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
repo_files_cli = typer_factory(
|
| 34 |
+
help="(Deprecated) Manage files in a repo on the Hub. Use `hf repos delete-files` instead."
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@repo_files_cli.command(
|
| 39 |
+
"delete",
|
| 40 |
+
)
|
| 41 |
+
def repo_files_delete(
|
| 42 |
+
repo_id: RepoIdArg,
|
| 43 |
+
patterns: Annotated[
|
| 44 |
+
list[str],
|
| 45 |
+
typer.Argument(
|
| 46 |
+
help="Glob patterns to match files to delete. Based on fnmatch, '*' matches files recursively.",
|
| 47 |
+
),
|
| 48 |
+
],
|
| 49 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 50 |
+
revision: RevisionOpt = None,
|
| 51 |
+
commit_message: Annotated[
|
| 52 |
+
str | None,
|
| 53 |
+
typer.Option(
|
| 54 |
+
help="The summary / title / first line of the generated commit.",
|
| 55 |
+
),
|
| 56 |
+
] = None,
|
| 57 |
+
commit_description: Annotated[
|
| 58 |
+
str | None,
|
| 59 |
+
typer.Option(
|
| 60 |
+
help="The description of the generated commit.",
|
| 61 |
+
),
|
| 62 |
+
] = None,
|
| 63 |
+
create_pr: Annotated[
|
| 64 |
+
bool,
|
| 65 |
+
typer.Option(
|
| 66 |
+
help="Whether to create a new Pull Request for these changes.",
|
| 67 |
+
),
|
| 68 |
+
] = False,
|
| 69 |
+
token: TokenOpt = None,
|
| 70 |
+
) -> None:
|
| 71 |
+
print(
|
| 72 |
+
ANSI.yellow("FutureWarning: `hf repo-files delete` is deprecated. Use `hf repos delete-files` instead."),
|
| 73 |
+
file=sys.stderr,
|
| 74 |
+
)
|
| 75 |
+
api = get_hf_api(token=token)
|
| 76 |
+
url = api.delete_files(
|
| 77 |
+
delete_patterns=patterns,
|
| 78 |
+
repo_id=repo_id,
|
| 79 |
+
repo_type=repo_type.value,
|
| 80 |
+
revision=revision,
|
| 81 |
+
commit_message=commit_message,
|
| 82 |
+
commit_description=commit_description,
|
| 83 |
+
create_pr=create_pr,
|
| 84 |
+
)
|
| 85 |
+
print(f"Files correctly deleted from repo. Commit: {url}.")
|
| 86 |
+
logging.set_verbosity_warning()
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/repos.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with repositories on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# create a new dataset repo on the Hub
|
| 18 |
+
hf repos create my-cool-dataset --repo-type=dataset
|
| 19 |
+
|
| 20 |
+
# create a private model repo on the Hub
|
| 21 |
+
hf repos create my-cool-model --private
|
| 22 |
+
|
| 23 |
+
# delete files from a repo on the Hub
|
| 24 |
+
hf repos delete-files my-model file.txt
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import enum
|
| 28 |
+
import sys
|
| 29 |
+
from typing import Annotated
|
| 30 |
+
|
| 31 |
+
import typer
|
| 32 |
+
|
| 33 |
+
from huggingface_hub import SpaceHardware, SpaceStorage
|
| 34 |
+
from huggingface_hub.errors import CLIError, HfHubHTTPError, RepositoryNotFoundError, RevisionNotFoundError
|
| 35 |
+
from huggingface_hub.utils import ANSI
|
| 36 |
+
|
| 37 |
+
from ._cli_utils import (
|
| 38 |
+
EnvFileOpt,
|
| 39 |
+
EnvOpt,
|
| 40 |
+
PrivateOpt,
|
| 41 |
+
RepoIdArg,
|
| 42 |
+
RepoType,
|
| 43 |
+
RepoTypeOpt,
|
| 44 |
+
RevisionOpt,
|
| 45 |
+
SecretsFileOpt,
|
| 46 |
+
SecretsOpt,
|
| 47 |
+
TokenOpt,
|
| 48 |
+
VolumesOpt,
|
| 49 |
+
env_map_to_key_value_list,
|
| 50 |
+
get_hf_api,
|
| 51 |
+
parse_env_map,
|
| 52 |
+
parse_volumes,
|
| 53 |
+
typer_factory,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
repos_cli = typer_factory(help="Manage repos on the Hub.")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@repos_cli.callback(invoke_without_command=True)
|
| 61 |
+
def _repos_callback(ctx: typer.Context) -> None:
|
| 62 |
+
if ctx.info_name == "repo":
|
| 63 |
+
print(
|
| 64 |
+
ANSI.yellow("FutureWarning: `hf repo` is deprecated in favor of `hf repos`."),
|
| 65 |
+
file=sys.stderr,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
tag_cli = typer_factory(help="Manage tags for a repo on the Hub.")
|
| 70 |
+
branch_cli = typer_factory(help="Manage branches for a repo on the Hub.")
|
| 71 |
+
repos_cli.add_typer(tag_cli, name="tag")
|
| 72 |
+
repos_cli.add_typer(branch_cli, name="branch")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class GatedChoices(str, enum.Enum):
|
| 76 |
+
auto = "auto"
|
| 77 |
+
manual = "manual"
|
| 78 |
+
false = "false"
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
PublicOpt = Annotated[
|
| 82 |
+
bool | None,
|
| 83 |
+
typer.Option(
|
| 84 |
+
"--public",
|
| 85 |
+
help="Whether to make the repo public. Ignored if the repo already exists.",
|
| 86 |
+
),
|
| 87 |
+
]
|
| 88 |
+
|
| 89 |
+
ProtectedOpt = Annotated[
|
| 90 |
+
bool | None,
|
| 91 |
+
typer.Option(
|
| 92 |
+
"--protected",
|
| 93 |
+
help="Whether to make the Space protected (Spaces only). Ignored if the repo already exists.",
|
| 94 |
+
),
|
| 95 |
+
]
|
| 96 |
+
SpaceHardwareOpt = Annotated[
|
| 97 |
+
SpaceHardware | None,
|
| 98 |
+
typer.Option(
|
| 99 |
+
"--flavor",
|
| 100 |
+
help="Space hardware flavor (e.g. 'cpu-basic', 't4-medium', 'l4x4'). Only for Spaces.",
|
| 101 |
+
),
|
| 102 |
+
]
|
| 103 |
+
|
| 104 |
+
SpaceStorageOpt = Annotated[
|
| 105 |
+
SpaceStorage | None,
|
| 106 |
+
typer.Option(
|
| 107 |
+
"--storage",
|
| 108 |
+
help="(Deprecated, use volumes instead) Space persistent storage tier ('small', 'medium', or 'large'). Only for Spaces.",
|
| 109 |
+
),
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
SpaceSleepTimeOpt = Annotated[
|
| 113 |
+
int | None,
|
| 114 |
+
typer.Option(
|
| 115 |
+
"--sleep-time",
|
| 116 |
+
help="Seconds of inactivity before the Space is put to sleep. Use -1 to disable. Only for Spaces.",
|
| 117 |
+
),
|
| 118 |
+
]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@repos_cli.command(
|
| 122 |
+
"create",
|
| 123 |
+
examples=[
|
| 124 |
+
"hf repos create my-model",
|
| 125 |
+
"hf repos create my-dataset --repo-type dataset --private",
|
| 126 |
+
"hf repos create my-space --type space --space-sdk gradio --flavor t4-medium --secrets HF_TOKEN -e THEME=dark --protected",
|
| 127 |
+
"hf repos create my-space --type space --space-sdk gradio -v hf://gpt2:/models -v hf://buckets/org/b:/data",
|
| 128 |
+
],
|
| 129 |
+
)
|
| 130 |
+
def repo_create(
|
| 131 |
+
repo_id: RepoIdArg,
|
| 132 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 133 |
+
space_sdk: Annotated[
|
| 134 |
+
str | None,
|
| 135 |
+
typer.Option(
|
| 136 |
+
help="Hugging Face Spaces SDK type. Required when --type is set to 'space'.",
|
| 137 |
+
),
|
| 138 |
+
] = None,
|
| 139 |
+
private: PrivateOpt = None,
|
| 140 |
+
public: PublicOpt = None,
|
| 141 |
+
protected: ProtectedOpt = None,
|
| 142 |
+
token: TokenOpt = None,
|
| 143 |
+
exist_ok: Annotated[
|
| 144 |
+
bool,
|
| 145 |
+
typer.Option(
|
| 146 |
+
help="Do not raise an error if repo already exists.",
|
| 147 |
+
),
|
| 148 |
+
] = False,
|
| 149 |
+
resource_group_id: Annotated[
|
| 150 |
+
str | None,
|
| 151 |
+
typer.Option(
|
| 152 |
+
help="Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations.",
|
| 153 |
+
),
|
| 154 |
+
] = None,
|
| 155 |
+
hardware: SpaceHardwareOpt = None,
|
| 156 |
+
storage: SpaceStorageOpt = None,
|
| 157 |
+
sleep_time: SpaceSleepTimeOpt = None,
|
| 158 |
+
secrets: SecretsOpt = None,
|
| 159 |
+
secrets_file: SecretsFileOpt = None,
|
| 160 |
+
env: EnvOpt = None,
|
| 161 |
+
env_file: EnvFileOpt = None,
|
| 162 |
+
volume: VolumesOpt = None,
|
| 163 |
+
) -> None:
|
| 164 |
+
"""Create a new repo on the Hub."""
|
| 165 |
+
api = get_hf_api(token=token)
|
| 166 |
+
repo_url = api.create_repo(
|
| 167 |
+
repo_id=repo_id,
|
| 168 |
+
repo_type=repo_type.value,
|
| 169 |
+
visibility="private" if private else "public" if public else "protected" if protected else None, # type: ignore [arg-type]
|
| 170 |
+
token=token,
|
| 171 |
+
exist_ok=exist_ok,
|
| 172 |
+
resource_group_id=resource_group_id,
|
| 173 |
+
space_sdk=space_sdk,
|
| 174 |
+
space_hardware=hardware,
|
| 175 |
+
space_storage=storage,
|
| 176 |
+
space_sleep_time=sleep_time,
|
| 177 |
+
space_secrets=env_map_to_key_value_list(parse_env_map(secrets, secrets_file)),
|
| 178 |
+
space_variables=env_map_to_key_value_list(parse_env_map(env, env_file)),
|
| 179 |
+
space_volumes=parse_volumes(volume),
|
| 180 |
+
)
|
| 181 |
+
print(f"Successfully created {ANSI.bold(repo_url.repo_id)} on the Hub.")
|
| 182 |
+
print(f"Your repo is now available at {ANSI.bold(repo_url)}")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@repos_cli.command(
|
| 186 |
+
"duplicate",
|
| 187 |
+
examples=[
|
| 188 |
+
"hf repos duplicate openai/gdpval --type dataset",
|
| 189 |
+
"hf repos duplicate multimodalart/dreambooth-training my-dreambooth --type space --flavor l4x4 --secrets HF_TOKEN --private",
|
| 190 |
+
"hf repos duplicate org/my-space my-space --type space -v hf://gpt2:/models -v hf://buckets/org/b:/data",
|
| 191 |
+
],
|
| 192 |
+
)
|
| 193 |
+
def repo_duplicate(
|
| 194 |
+
from_id: RepoIdArg,
|
| 195 |
+
to_id: Annotated[
|
| 196 |
+
str | None,
|
| 197 |
+
typer.Argument(
|
| 198 |
+
help="Destination repo ID (e.g. `myorg/my-copy`). Defaults to your namespace with the same repo name.",
|
| 199 |
+
),
|
| 200 |
+
] = None,
|
| 201 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 202 |
+
private: PrivateOpt = None,
|
| 203 |
+
public: PublicOpt = None,
|
| 204 |
+
protected: ProtectedOpt = None,
|
| 205 |
+
token: TokenOpt = None,
|
| 206 |
+
exist_ok: Annotated[
|
| 207 |
+
bool,
|
| 208 |
+
typer.Option(
|
| 209 |
+
help="Do not raise an error if repo already exists.",
|
| 210 |
+
),
|
| 211 |
+
] = False,
|
| 212 |
+
hardware: SpaceHardwareOpt = None,
|
| 213 |
+
storage: SpaceStorageOpt = None,
|
| 214 |
+
sleep_time: SpaceSleepTimeOpt = None,
|
| 215 |
+
secrets: SecretsOpt = None,
|
| 216 |
+
secrets_file: SecretsFileOpt = None,
|
| 217 |
+
env: EnvOpt = None,
|
| 218 |
+
env_file: EnvFileOpt = None,
|
| 219 |
+
volume: VolumesOpt = None,
|
| 220 |
+
) -> None:
|
| 221 |
+
"""Duplicate a repo on the Hub (model, dataset, or Space)."""
|
| 222 |
+
api = get_hf_api(token=token)
|
| 223 |
+
repo_url = api.duplicate_repo(
|
| 224 |
+
from_id=from_id,
|
| 225 |
+
to_id=to_id,
|
| 226 |
+
repo_type=repo_type.value,
|
| 227 |
+
visibility="private" if private else "public" if public else "protected" if protected else None, # type: ignore [arg-type]
|
| 228 |
+
token=token,
|
| 229 |
+
exist_ok=exist_ok,
|
| 230 |
+
space_hardware=hardware,
|
| 231 |
+
space_storage=storage,
|
| 232 |
+
space_sleep_time=sleep_time,
|
| 233 |
+
space_secrets=env_map_to_key_value_list(parse_env_map(secrets, secrets_file)),
|
| 234 |
+
space_variables=env_map_to_key_value_list(parse_env_map(env, env_file)),
|
| 235 |
+
space_volumes=parse_volumes(volume),
|
| 236 |
+
)
|
| 237 |
+
print(f"Successfully duplicated {ANSI.bold(from_id)} to {ANSI.bold(repo_url.repo_id)} on the Hub.")
|
| 238 |
+
print(f"Your repo is now available at {ANSI.bold(repo_url)}")
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@repos_cli.command("delete", examples=["hf repos delete my-model"])
|
| 242 |
+
def repo_delete(
|
| 243 |
+
repo_id: RepoIdArg,
|
| 244 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 245 |
+
token: TokenOpt = None,
|
| 246 |
+
missing_ok: Annotated[
|
| 247 |
+
bool,
|
| 248 |
+
typer.Option(
|
| 249 |
+
help="If set to True, do not raise an error if repo does not exist.",
|
| 250 |
+
),
|
| 251 |
+
] = False,
|
| 252 |
+
) -> None:
|
| 253 |
+
"""Delete a repo from the Hub. This is an irreversible operation."""
|
| 254 |
+
api = get_hf_api(token=token)
|
| 255 |
+
api.delete_repo(
|
| 256 |
+
repo_id=repo_id,
|
| 257 |
+
repo_type=repo_type.value,
|
| 258 |
+
missing_ok=missing_ok,
|
| 259 |
+
)
|
| 260 |
+
print(f"Successfully deleted {ANSI.bold(repo_id)} on the Hub.")
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@repos_cli.command("move", examples=["hf repos move old-namespace/my-model new-namespace/my-model"])
|
| 264 |
+
def repo_move(
|
| 265 |
+
from_id: RepoIdArg,
|
| 266 |
+
to_id: RepoIdArg,
|
| 267 |
+
token: TokenOpt = None,
|
| 268 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 269 |
+
) -> None:
|
| 270 |
+
"""Move a repository from a namespace to another namespace."""
|
| 271 |
+
api = get_hf_api(token=token)
|
| 272 |
+
api.move_repo(
|
| 273 |
+
from_id=from_id,
|
| 274 |
+
to_id=to_id,
|
| 275 |
+
repo_type=repo_type.value,
|
| 276 |
+
)
|
| 277 |
+
print(f"Successfully moved {ANSI.bold(from_id)} to {ANSI.bold(to_id)} on the Hub.")
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
@repos_cli.command(
|
| 281 |
+
"settings",
|
| 282 |
+
examples=[
|
| 283 |
+
"hf repos settings my-model --private",
|
| 284 |
+
"hf repos settings my-model --gated auto",
|
| 285 |
+
"hf repos settings my-space --repo-type space --protected",
|
| 286 |
+
],
|
| 287 |
+
)
|
| 288 |
+
def repo_settings(
|
| 289 |
+
repo_id: RepoIdArg,
|
| 290 |
+
gated: Annotated[
|
| 291 |
+
GatedChoices | None,
|
| 292 |
+
typer.Option(
|
| 293 |
+
help="The gated status for the repository.",
|
| 294 |
+
),
|
| 295 |
+
] = None,
|
| 296 |
+
private: PrivateOpt = None,
|
| 297 |
+
public: PublicOpt = None,
|
| 298 |
+
protected: ProtectedOpt = None,
|
| 299 |
+
token: TokenOpt = None,
|
| 300 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 301 |
+
) -> None:
|
| 302 |
+
"""Update the settings of a repository."""
|
| 303 |
+
api = get_hf_api(token=token)
|
| 304 |
+
api.update_repo_settings(
|
| 305 |
+
repo_id=repo_id,
|
| 306 |
+
gated=(None if gated is None else False if gated is GatedChoices.false else gated.value),
|
| 307 |
+
visibility="private" if private else "public" if public else "protected" if protected else None, # type: ignore [arg-type]
|
| 308 |
+
repo_type=repo_type.value,
|
| 309 |
+
)
|
| 310 |
+
print(f"Successfully updated the settings of {ANSI.bold(repo_id)} on the Hub.")
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@repos_cli.command(
|
| 314 |
+
"delete-files",
|
| 315 |
+
examples=[
|
| 316 |
+
"hf repos delete-files my-model file.txt",
|
| 317 |
+
'hf repos delete-files my-model "*.json"',
|
| 318 |
+
"hf repos delete-files my-model folder/",
|
| 319 |
+
],
|
| 320 |
+
)
|
| 321 |
+
def repo_delete_files(
|
| 322 |
+
repo_id: RepoIdArg,
|
| 323 |
+
patterns: Annotated[
|
| 324 |
+
list[str],
|
| 325 |
+
typer.Argument(
|
| 326 |
+
help="Glob patterns to match files to delete. Based on fnmatch, '*' matches files recursively.",
|
| 327 |
+
),
|
| 328 |
+
],
|
| 329 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 330 |
+
revision: RevisionOpt = None,
|
| 331 |
+
commit_message: Annotated[
|
| 332 |
+
str | None,
|
| 333 |
+
typer.Option(
|
| 334 |
+
help="The summary / title / first line of the generated commit.",
|
| 335 |
+
),
|
| 336 |
+
] = None,
|
| 337 |
+
commit_description: Annotated[
|
| 338 |
+
str | None,
|
| 339 |
+
typer.Option(
|
| 340 |
+
help="The description of the generated commit.",
|
| 341 |
+
),
|
| 342 |
+
] = None,
|
| 343 |
+
create_pr: Annotated[
|
| 344 |
+
bool,
|
| 345 |
+
typer.Option(
|
| 346 |
+
help="Whether to create a new Pull Request for these changes.",
|
| 347 |
+
),
|
| 348 |
+
] = False,
|
| 349 |
+
token: TokenOpt = None,
|
| 350 |
+
) -> None:
|
| 351 |
+
"""Delete files from a repo on the Hub."""
|
| 352 |
+
api = get_hf_api(token=token)
|
| 353 |
+
url = api.delete_files(
|
| 354 |
+
delete_patterns=patterns,
|
| 355 |
+
repo_id=repo_id,
|
| 356 |
+
repo_type=repo_type.value,
|
| 357 |
+
revision=revision,
|
| 358 |
+
commit_message=commit_message,
|
| 359 |
+
commit_description=commit_description,
|
| 360 |
+
create_pr=create_pr,
|
| 361 |
+
)
|
| 362 |
+
print(f"Files correctly deleted from repo. Commit: {url}.")
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
@branch_cli.command(
|
| 366 |
+
"create",
|
| 367 |
+
examples=[
|
| 368 |
+
"hf repos branch create my-model dev",
|
| 369 |
+
"hf repos branch create my-model dev --revision abc123",
|
| 370 |
+
],
|
| 371 |
+
)
|
| 372 |
+
def branch_create(
|
| 373 |
+
repo_id: RepoIdArg,
|
| 374 |
+
branch: Annotated[
|
| 375 |
+
str,
|
| 376 |
+
typer.Argument(
|
| 377 |
+
help="The name of the branch to create.",
|
| 378 |
+
),
|
| 379 |
+
],
|
| 380 |
+
revision: RevisionOpt = None,
|
| 381 |
+
token: TokenOpt = None,
|
| 382 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 383 |
+
exist_ok: Annotated[
|
| 384 |
+
bool,
|
| 385 |
+
typer.Option(
|
| 386 |
+
help="If set to True, do not raise an error if branch already exists.",
|
| 387 |
+
),
|
| 388 |
+
] = False,
|
| 389 |
+
) -> None:
|
| 390 |
+
"""Create a new branch for a repo on the Hub."""
|
| 391 |
+
api = get_hf_api(token=token)
|
| 392 |
+
api.create_branch(
|
| 393 |
+
repo_id=repo_id,
|
| 394 |
+
branch=branch,
|
| 395 |
+
revision=revision,
|
| 396 |
+
repo_type=repo_type.value,
|
| 397 |
+
exist_ok=exist_ok,
|
| 398 |
+
)
|
| 399 |
+
print(f"Successfully created {ANSI.bold(branch)} branch on {repo_type.value} {ANSI.bold(repo_id)}")
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
@branch_cli.command("delete", examples=["hf repos branch delete my-model dev"])
|
| 403 |
+
def branch_delete(
|
| 404 |
+
repo_id: RepoIdArg,
|
| 405 |
+
branch: Annotated[
|
| 406 |
+
str,
|
| 407 |
+
typer.Argument(
|
| 408 |
+
help="The name of the branch to delete.",
|
| 409 |
+
),
|
| 410 |
+
],
|
| 411 |
+
token: TokenOpt = None,
|
| 412 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 413 |
+
) -> None:
|
| 414 |
+
"""Delete a branch from a repo on the Hub."""
|
| 415 |
+
api = get_hf_api(token=token)
|
| 416 |
+
api.delete_branch(
|
| 417 |
+
repo_id=repo_id,
|
| 418 |
+
branch=branch,
|
| 419 |
+
repo_type=repo_type.value,
|
| 420 |
+
)
|
| 421 |
+
print(f"Successfully deleted {ANSI.bold(branch)} branch on {repo_type.value} {ANSI.bold(repo_id)}")
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
@tag_cli.command(
|
| 425 |
+
"create",
|
| 426 |
+
examples=[
|
| 427 |
+
"hf repos tag create my-model v1.0",
|
| 428 |
+
'hf repos tag create my-model v1.0 -m "First release"',
|
| 429 |
+
],
|
| 430 |
+
)
|
| 431 |
+
def tag_create(
|
| 432 |
+
repo_id: RepoIdArg,
|
| 433 |
+
tag: Annotated[
|
| 434 |
+
str,
|
| 435 |
+
typer.Argument(
|
| 436 |
+
help="The name of the tag to create.",
|
| 437 |
+
),
|
| 438 |
+
],
|
| 439 |
+
message: Annotated[
|
| 440 |
+
str | None,
|
| 441 |
+
typer.Option(
|
| 442 |
+
"-m",
|
| 443 |
+
"--message",
|
| 444 |
+
help="The description of the tag to create.",
|
| 445 |
+
),
|
| 446 |
+
] = None,
|
| 447 |
+
revision: RevisionOpt = None,
|
| 448 |
+
token: TokenOpt = None,
|
| 449 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 450 |
+
) -> None:
|
| 451 |
+
"""Create a tag for a repo."""
|
| 452 |
+
repo_type_str = repo_type.value
|
| 453 |
+
api = get_hf_api(token=token)
|
| 454 |
+
print(f"You are about to create tag {ANSI.bold(tag)} on {repo_type_str} {ANSI.bold(repo_id)}")
|
| 455 |
+
try:
|
| 456 |
+
api.create_tag(repo_id=repo_id, tag=tag, tag_message=message, revision=revision, repo_type=repo_type_str)
|
| 457 |
+
except RepositoryNotFoundError as e:
|
| 458 |
+
raise CLIError(f"{repo_type_str.capitalize()} '{repo_id}' not found.") from e
|
| 459 |
+
except RevisionNotFoundError as e:
|
| 460 |
+
raise CLIError(f"Revision '{revision}' not found.") from e
|
| 461 |
+
except HfHubHTTPError as e:
|
| 462 |
+
if e.response.status_code == 409:
|
| 463 |
+
raise CLIError(f"Tag '{tag}' already exists on '{repo_id}'.") from e
|
| 464 |
+
raise
|
| 465 |
+
print(f"Tag {ANSI.bold(tag)} created on {ANSI.bold(repo_id)}")
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
@tag_cli.command("list | ls", examples=["hf repos tag list my-model"])
|
| 469 |
+
def tag_list(
|
| 470 |
+
repo_id: RepoIdArg,
|
| 471 |
+
token: TokenOpt = None,
|
| 472 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 473 |
+
) -> None:
|
| 474 |
+
"""List tags for a repo."""
|
| 475 |
+
repo_type_str = repo_type.value
|
| 476 |
+
api = get_hf_api(token=token)
|
| 477 |
+
try:
|
| 478 |
+
refs = api.list_repo_refs(repo_id=repo_id, repo_type=repo_type_str)
|
| 479 |
+
except RepositoryNotFoundError as e:
|
| 480 |
+
raise CLIError(f"{repo_type_str.capitalize()} '{repo_id}' not found.") from e
|
| 481 |
+
if len(refs.tags) == 0:
|
| 482 |
+
print("No tags found")
|
| 483 |
+
raise typer.Exit(code=0)
|
| 484 |
+
print(f"Tags for {repo_type_str} {ANSI.bold(repo_id)}:")
|
| 485 |
+
for t in refs.tags:
|
| 486 |
+
print(t.name)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
@tag_cli.command("delete", examples=["hf repos tag delete my-model v1.0"])
|
| 490 |
+
def tag_delete(
|
| 491 |
+
repo_id: RepoIdArg,
|
| 492 |
+
tag: Annotated[
|
| 493 |
+
str,
|
| 494 |
+
typer.Argument(
|
| 495 |
+
help="The name of the tag to delete.",
|
| 496 |
+
),
|
| 497 |
+
],
|
| 498 |
+
yes: Annotated[
|
| 499 |
+
bool,
|
| 500 |
+
typer.Option(
|
| 501 |
+
"-y",
|
| 502 |
+
"--yes",
|
| 503 |
+
help="Answer Yes to prompt automatically",
|
| 504 |
+
),
|
| 505 |
+
] = False,
|
| 506 |
+
token: TokenOpt = None,
|
| 507 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 508 |
+
) -> None:
|
| 509 |
+
"""Delete a tag for a repo."""
|
| 510 |
+
repo_type_str = repo_type.value
|
| 511 |
+
print(f"You are about to delete tag {ANSI.bold(tag)} on {repo_type_str} {ANSI.bold(repo_id)}")
|
| 512 |
+
if not yes:
|
| 513 |
+
choice = input("Proceed? [Y/n] ").lower()
|
| 514 |
+
if choice not in ("", "y", "yes"):
|
| 515 |
+
print("Abort")
|
| 516 |
+
raise typer.Exit()
|
| 517 |
+
api = get_hf_api(token=token)
|
| 518 |
+
try:
|
| 519 |
+
api.delete_tag(repo_id=repo_id, tag=tag, repo_type=repo_type_str)
|
| 520 |
+
except RepositoryNotFoundError as e:
|
| 521 |
+
raise CLIError(f"{repo_type_str.capitalize()} '{repo_id}' not found.") from e
|
| 522 |
+
except RevisionNotFoundError as e:
|
| 523 |
+
raise CLIError(f"Tag '{tag}' not found on '{repo_id}'.") from e
|
| 524 |
+
print(f"Tag {ANSI.bold(tag)} deleted on {ANSI.bold(repo_id)}")
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/skills.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to manage skills for AI assistants.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# install the hf-cli skill in common .agents/skills directory (either in current directory or user-level)
|
| 18 |
+
hf skills add
|
| 19 |
+
hf skills add --global
|
| 20 |
+
|
| 21 |
+
# install the hf-cli skill for Claude (project-level, in current directory)
|
| 22 |
+
hf skills add --claude
|
| 23 |
+
|
| 24 |
+
# install globally (user-level)
|
| 25 |
+
hf skills add --claude --global
|
| 26 |
+
|
| 27 |
+
# install to a custom directory
|
| 28 |
+
hf skills add --dest=~/my-skills
|
| 29 |
+
|
| 30 |
+
# overwrite an existing skill
|
| 31 |
+
hf skills add --claude --force
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
import os
|
| 35 |
+
import shutil
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
from typing import Annotated
|
| 38 |
+
|
| 39 |
+
import typer
|
| 40 |
+
from click import Command, Context, Group
|
| 41 |
+
from typer.main import get_command
|
| 42 |
+
|
| 43 |
+
from huggingface_hub.errors import CLIError
|
| 44 |
+
|
| 45 |
+
from . import _skills
|
| 46 |
+
from ._cli_utils import typer_factory
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
DEFAULT_SKILL_ID = "hf-cli"
|
| 50 |
+
|
| 51 |
+
_SKILL_DESCRIPTION = (
|
| 52 |
+
"Hugging Face Hub CLI (`hf`) for downloading, uploading, and managing"
|
| 53 |
+
" models, datasets, spaces, buckets, repos, papers, jobs, and more on the Hugging Face Hub."
|
| 54 |
+
" Use when: handling authentication;"
|
| 55 |
+
" managing local cache;"
|
| 56 |
+
" managing Hugging Face Buckets;"
|
| 57 |
+
" running or scheduling jobs on Hugging Face infrastructure;"
|
| 58 |
+
" managing Hugging Face repos;"
|
| 59 |
+
" discussions and pull requests;"
|
| 60 |
+
" browsing models, datasets and spaces;"
|
| 61 |
+
" reading, searching, or browsing academic papers;"
|
| 62 |
+
" managing collections;"
|
| 63 |
+
" querying datasets;"
|
| 64 |
+
" configuring spaces;"
|
| 65 |
+
" setting up webhooks;"
|
| 66 |
+
" or deploying and managing HF Inference Endpoints."
|
| 67 |
+
" Make sure to use this skill whenever the user mentions"
|
| 68 |
+
" 'hf', 'huggingface', 'Hugging Face', 'huggingface-cli', or 'hugging face cli',"
|
| 69 |
+
" or wants to do anything related to the Hugging Face ecosystem and to AI and ML in general."
|
| 70 |
+
" Also use for cloud storage needs like training checkpoints, data pipelines, or agent traces."
|
| 71 |
+
" Use even if the user doesn't explicitly ask for a CLI command."
|
| 72 |
+
" Replaces the deprecated `huggingface-cli`."
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
_SKILL_YAML_PREFIX = f"""\
|
| 76 |
+
---
|
| 77 |
+
name: hf-cli
|
| 78 |
+
description: "{_SKILL_DESCRIPTION}"
|
| 79 |
+
---
|
| 80 |
+
|
| 81 |
+
Install: `curl -LsSf https://hf.co/cli/install.sh | bash -s`.
|
| 82 |
+
|
| 83 |
+
The Hugging Face Hub CLI tool `hf` is available. IMPORTANT: The `hf` command replaces the deprecated `huggingface-cli` command.
|
| 84 |
+
|
| 85 |
+
Use `hf --help` to view available functions. Note that auth commands are now all under `hf auth` e.g. `hf auth whoami`.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
_SKILL_TIPS = """
|
| 89 |
+
## Mounting repos as local filesystems
|
| 90 |
+
|
| 91 |
+
To mount Hub repositories or buckets as local filesystems — no download, no copy, no waiting — use `hf-mount`. Files are fetched on demand. GitHub: https://github.com/huggingface/hf-mount
|
| 92 |
+
|
| 93 |
+
Install: `curl -fsSL https://raw.githubusercontent.com/huggingface/hf-mount/main/install.sh | sh`
|
| 94 |
+
|
| 95 |
+
Some command examples:
|
| 96 |
+
- `hf-mount start repo openai-community/gpt2 /tmp/gpt2` — mount a repo (read-only)
|
| 97 |
+
- `hf-mount start --hf-token $HF_TOKEN bucket myuser/my-bucket /tmp/data` — mount a bucket (read-write)
|
| 98 |
+
- `hf-mount status` / `hf-mount stop /tmp/data` — list or unmount
|
| 99 |
+
|
| 100 |
+
## Tips
|
| 101 |
+
|
| 102 |
+
- Use `hf <command> --help` for full options, descriptions, usage, and real-world examples
|
| 103 |
+
- Authenticate with `HF_TOKEN` env var (recommended) or with `--token`
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
CENTRAL_LOCAL = Path(".agents/skills")
|
| 107 |
+
CENTRAL_GLOBAL = Path("~/.agents/skills")
|
| 108 |
+
CLAUDE_LOCAL = Path(".claude/skills")
|
| 109 |
+
CLAUDE_GLOBAL = Path("~/.claude/skills")
|
| 110 |
+
# Flags worth explaining in the common-options glossary. Self-explanatory flags
|
| 111 |
+
# (--namespace, --yes, --private, …) are omitted even if they appear frequently.
|
| 112 |
+
_COMMON_FLAG_ALLOWLIST = {"--token", "--quiet", "--type", "--format", "--revision"}
|
| 113 |
+
# Keep token out of inline command signatures to encourage env based auth.
|
| 114 |
+
_INLINE_FLAG_EXCLUDE = {"--token"}
|
| 115 |
+
|
| 116 |
+
_COMMON_FLAG_HELP_OVERRIDES: dict[str, str] = {
|
| 117 |
+
"--format": "Output format: `--format json` (or `--json`) or `--format table` (default).",
|
| 118 |
+
"--token": "Use a User Access Token. Prefer setting `HF_TOKEN` env var instead of passing `--token`.",
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
skills_cli = typer_factory(help="Manage skills for AI assistants.")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _format_params(cmd: Command) -> str:
|
| 125 |
+
"""Format required params: positional as UPPER_CASE, options as ``--name TYPE``."""
|
| 126 |
+
parts = []
|
| 127 |
+
for p in cmd.params:
|
| 128 |
+
if not p.required or p.human_readable_name == "--help":
|
| 129 |
+
continue
|
| 130 |
+
if p.name and p.name.startswith("_"):
|
| 131 |
+
continue
|
| 132 |
+
long_name = next((o for o in getattr(p, "opts", []) if o.startswith("--")), None)
|
| 133 |
+
if long_name is not None:
|
| 134 |
+
type_name = getattr(p.type, "name", "").upper() or "VALUE"
|
| 135 |
+
parts.append(f"{long_name} {type_name}")
|
| 136 |
+
elif p.name:
|
| 137 |
+
parts.append(p.human_readable_name)
|
| 138 |
+
return " ".join(parts)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _collect_leaf_commands(group: Group, ctx: Context, path_parts: list[str]) -> list[tuple[list[str], Command]]:
|
| 142 |
+
"""Recursively walk a Click Group, returning (full_path_parts, cmd) for every leaf command."""
|
| 143 |
+
leaves: list[tuple[list[str], Command]] = []
|
| 144 |
+
sub_ctx = Context(group, parent=ctx, info_name=path_parts[-1])
|
| 145 |
+
for name in group.list_commands(sub_ctx):
|
| 146 |
+
cmd = group.get_command(sub_ctx, name)
|
| 147 |
+
if cmd is None or cmd.hidden:
|
| 148 |
+
continue
|
| 149 |
+
child_path = [*path_parts, name]
|
| 150 |
+
if isinstance(cmd, Group):
|
| 151 |
+
leaves.extend(_collect_leaf_commands(cmd, sub_ctx, child_path))
|
| 152 |
+
else:
|
| 153 |
+
leaves.append((child_path, cmd))
|
| 154 |
+
return leaves
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _iter_optional_params(cmd: Command):
|
| 158 |
+
"""Yield (param, long_name, short_name) for each optional, non-internal param."""
|
| 159 |
+
for p in cmd.params:
|
| 160 |
+
if p.required or p.human_readable_name == "--help":
|
| 161 |
+
continue
|
| 162 |
+
if p.name and p.name.startswith("_"):
|
| 163 |
+
continue
|
| 164 |
+
long_name = None
|
| 165 |
+
short_name = None
|
| 166 |
+
for opt in getattr(p, "opts", []):
|
| 167 |
+
if opt.startswith("--"):
|
| 168 |
+
long_name = long_name or opt
|
| 169 |
+
elif opt.startswith("-"):
|
| 170 |
+
short_name = opt
|
| 171 |
+
if long_name:
|
| 172 |
+
yield p, long_name, short_name
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _get_flag_names(cmd: Command, *, exclude: set[str] | None = None) -> list[str]:
|
| 176 |
+
"""Return long-form flag names (--foo) for optional, non-internal params.
|
| 177 |
+
|
| 178 |
+
Boolean flags are bare (``--dry-run``). Value-taking options include a
|
| 179 |
+
type hint (``--include TEXT``, ``--max-workers INTEGER``).
|
| 180 |
+
"""
|
| 181 |
+
flags: list[str] = []
|
| 182 |
+
for p, long_name, _short in _iter_optional_params(cmd):
|
| 183 |
+
if exclude and long_name in exclude:
|
| 184 |
+
continue
|
| 185 |
+
if getattr(p, "is_flag", False):
|
| 186 |
+
flags.append(long_name)
|
| 187 |
+
else:
|
| 188 |
+
type_name = getattr(p.type, "name", "").upper() or "VALUE"
|
| 189 |
+
flags.append(f"{long_name} {type_name}")
|
| 190 |
+
return flags
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _compute_common_flags(
|
| 194 |
+
leaf_commands: list[tuple[list[str], Command]],
|
| 195 |
+
) -> dict[str, tuple[str, str]]:
|
| 196 |
+
"""Collect display info for flags in the allowlist."""
|
| 197 |
+
flag_info: dict[str, tuple[str, str]] = {}
|
| 198 |
+
|
| 199 |
+
for _path, cmd in leaf_commands:
|
| 200 |
+
for p, long_name, short_name in _iter_optional_params(cmd):
|
| 201 |
+
if long_name not in _COMMON_FLAG_ALLOWLIST:
|
| 202 |
+
continue
|
| 203 |
+
# Prefer the version with a short form (e.g. "-q / --quiet" over just "--quiet")
|
| 204 |
+
if long_name not in flag_info or (short_name and " / " not in flag_info[long_name][0]):
|
| 205 |
+
display = f"{short_name} / {long_name}" if short_name else long_name
|
| 206 |
+
help_text = (getattr(p, "help", None) or "").split("\n")[0].strip()
|
| 207 |
+
flag_info[long_name] = (display, help_text)
|
| 208 |
+
|
| 209 |
+
return flag_info
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _render_leaf(path_parts: list[str], cmd: Command) -> str:
|
| 213 |
+
"""Render a single leaf command as a markdown list entry."""
|
| 214 |
+
help_text = (cmd.help or "").split("\n")[0].strip()
|
| 215 |
+
params = _format_params(cmd)
|
| 216 |
+
parts = ["hf", *path_parts] + ([params] if params else [])
|
| 217 |
+
entry = f"- `{' '.join(parts)}` — {help_text}"
|
| 218 |
+
flags = _get_flag_names(cmd, exclude=_INLINE_FLAG_EXCLUDE)
|
| 219 |
+
if flags:
|
| 220 |
+
entry += f" `[{' '.join(flags)}]`"
|
| 221 |
+
return entry
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def build_skill_md() -> str:
|
| 225 |
+
# Lazy import to avoid circular dependency (hf.py imports skills_cli from this module)
|
| 226 |
+
from huggingface_hub import __version__
|
| 227 |
+
from huggingface_hub.cli.hf import app
|
| 228 |
+
|
| 229 |
+
click_app = get_command(app)
|
| 230 |
+
ctx = Context(click_app, info_name="hf")
|
| 231 |
+
|
| 232 |
+
top_level: list[tuple[list[str], Command]] = []
|
| 233 |
+
groups: list[tuple[str, Group]] = []
|
| 234 |
+
for name in sorted(click_app.list_commands(ctx)): # type: ignore[attr-defined]
|
| 235 |
+
cmd = click_app.get_command(ctx, name) # type: ignore[attr-defined]
|
| 236 |
+
if cmd is None or cmd.hidden:
|
| 237 |
+
continue
|
| 238 |
+
if isinstance(cmd, Group):
|
| 239 |
+
groups.append((name, cmd))
|
| 240 |
+
else:
|
| 241 |
+
top_level.append(([name], cmd))
|
| 242 |
+
|
| 243 |
+
group_leaves: list[tuple[str, list[tuple[list[str], Command]]]] = []
|
| 244 |
+
all_leaf_commands: list[tuple[list[str], Command]] = list(top_level)
|
| 245 |
+
for name, group in groups:
|
| 246 |
+
leaves = _collect_leaf_commands(group, ctx, [name])
|
| 247 |
+
group_leaves.append((name, leaves))
|
| 248 |
+
all_leaf_commands.extend(leaves)
|
| 249 |
+
|
| 250 |
+
common_flags = _compute_common_flags(all_leaf_commands)
|
| 251 |
+
|
| 252 |
+
# wrap in list to widen list[LiteralString] -> list[str] for `ty`
|
| 253 |
+
lines: list[str] = list(_SKILL_YAML_PREFIX.splitlines())
|
| 254 |
+
lines.append("")
|
| 255 |
+
lines.append(f"Generated with `huggingface_hub v{__version__}`. Run `hf skills add --force` to regenerate.")
|
| 256 |
+
lines.append("")
|
| 257 |
+
lines.append("## Commands")
|
| 258 |
+
lines.append("")
|
| 259 |
+
|
| 260 |
+
for path_parts, cmd in top_level:
|
| 261 |
+
lines.append(_render_leaf(path_parts, cmd))
|
| 262 |
+
|
| 263 |
+
groups_dict = dict(groups)
|
| 264 |
+
for name, leaves in group_leaves:
|
| 265 |
+
group_cmd = groups_dict[name]
|
| 266 |
+
help_text = (group_cmd.help or "").split("\n")[0].strip()
|
| 267 |
+
lines.append("")
|
| 268 |
+
lines.append(f"### `hf {name}` — {help_text}")
|
| 269 |
+
lines.append("")
|
| 270 |
+
for path_parts, cmd in leaves:
|
| 271 |
+
lines.append(_render_leaf(path_parts, cmd))
|
| 272 |
+
|
| 273 |
+
if common_flags:
|
| 274 |
+
lines.append("")
|
| 275 |
+
lines.append("## Common options")
|
| 276 |
+
lines.append("")
|
| 277 |
+
for long_name, (display, help_text) in sorted(common_flags.items()):
|
| 278 |
+
help_text = _COMMON_FLAG_HELP_OVERRIDES.get(long_name, help_text)
|
| 279 |
+
if help_text:
|
| 280 |
+
lines.append(f"- `{display}` — {help_text}")
|
| 281 |
+
else:
|
| 282 |
+
lines.append(f"- `{display}`")
|
| 283 |
+
|
| 284 |
+
lines.extend(_SKILL_TIPS.splitlines())
|
| 285 |
+
|
| 286 |
+
return "\n".join(lines)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def _remove_existing(path: Path, force: bool) -> None:
|
| 290 |
+
"""Remove existing file/directory/symlink if force is True, otherwise raise an error."""
|
| 291 |
+
if not (path.exists() or path.is_symlink()):
|
| 292 |
+
return
|
| 293 |
+
if not force:
|
| 294 |
+
raise CLIError(f"Skill already exists at {path}.\nRe-run with --force to overwrite.")
|
| 295 |
+
if path.is_dir() and not path.is_symlink():
|
| 296 |
+
shutil.rmtree(path)
|
| 297 |
+
else:
|
| 298 |
+
path.unlink()
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def _install_to(skills_dir: Path, skill_name: str, force: bool) -> Path:
|
| 302 |
+
"""Install a marketplace skill into a skills directory. Returns the installed path."""
|
| 303 |
+
skill = _skills.get_marketplace_skill(skill_name)
|
| 304 |
+
try:
|
| 305 |
+
return _skills.install_marketplace_skill(skill, skills_dir, force=force)
|
| 306 |
+
except FileExistsError as exc:
|
| 307 |
+
raise CLIError(f"{exc}\nRe-run with --force to overwrite.") from exc
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _create_symlink(agent_skills_dir: Path, skill_name: str, central_skill_path: Path, force: bool) -> Path:
|
| 311 |
+
"""Create a relative symlink from agent directory to the central skill location."""
|
| 312 |
+
agent_skills_dir = agent_skills_dir.expanduser().resolve()
|
| 313 |
+
agent_skills_dir.mkdir(parents=True, exist_ok=True)
|
| 314 |
+
link_path = agent_skills_dir / skill_name
|
| 315 |
+
|
| 316 |
+
_remove_existing(link_path, force)
|
| 317 |
+
link_path.symlink_to(os.path.relpath(central_skill_path, agent_skills_dir))
|
| 318 |
+
|
| 319 |
+
return link_path
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _resolve_update_roots(
|
| 323 |
+
*,
|
| 324 |
+
claude: bool,
|
| 325 |
+
global_: bool,
|
| 326 |
+
dest: Path | None,
|
| 327 |
+
) -> list[Path]:
|
| 328 |
+
if dest is not None:
|
| 329 |
+
if claude or global_:
|
| 330 |
+
raise CLIError("--dest cannot be combined with --claude or --global.")
|
| 331 |
+
return [dest.expanduser().resolve()]
|
| 332 |
+
|
| 333 |
+
roots: list[Path] = [CENTRAL_GLOBAL if global_ else CENTRAL_LOCAL]
|
| 334 |
+
if claude:
|
| 335 |
+
roots.append(CLAUDE_GLOBAL if global_ else CLAUDE_LOCAL)
|
| 336 |
+
return [root.expanduser().resolve() for root in roots]
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@skills_cli.command("preview")
|
| 340 |
+
def skills_preview() -> None:
|
| 341 |
+
"""Print the generated `hf-cli` SKILL.md to stdout."""
|
| 342 |
+
print(build_skill_md())
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
@skills_cli.command(
|
| 346 |
+
"add",
|
| 347 |
+
examples=[
|
| 348 |
+
"hf skills add",
|
| 349 |
+
"hf skills add huggingface-gradio --dest=~/my-skills",
|
| 350 |
+
"hf skills add --global",
|
| 351 |
+
"hf skills add --claude",
|
| 352 |
+
"hf skills add huggingface-gradio --claude --global",
|
| 353 |
+
],
|
| 354 |
+
)
|
| 355 |
+
def skills_add(
|
| 356 |
+
name: Annotated[
|
| 357 |
+
str,
|
| 358 |
+
typer.Argument(help="Marketplace skill name.", show_default=False),
|
| 359 |
+
] = DEFAULT_SKILL_ID,
|
| 360 |
+
claude: Annotated[bool, typer.Option("--claude", help="Install for Claude.")] = False,
|
| 361 |
+
global_: Annotated[
|
| 362 |
+
bool,
|
| 363 |
+
typer.Option(
|
| 364 |
+
"--global",
|
| 365 |
+
"-g",
|
| 366 |
+
help="Install globally (user-level) instead of in the current project directory.",
|
| 367 |
+
),
|
| 368 |
+
] = False,
|
| 369 |
+
dest: Annotated[
|
| 370 |
+
Path | None,
|
| 371 |
+
typer.Option(
|
| 372 |
+
help="Install into a custom destination (path to skills directory).",
|
| 373 |
+
),
|
| 374 |
+
] = None,
|
| 375 |
+
force: Annotated[
|
| 376 |
+
bool,
|
| 377 |
+
typer.Option(
|
| 378 |
+
"--force",
|
| 379 |
+
help="Overwrite existing skills in the destination.",
|
| 380 |
+
),
|
| 381 |
+
] = False,
|
| 382 |
+
) -> None:
|
| 383 |
+
"""Download a Hugging Face skill and install it for an AI assistant.
|
| 384 |
+
|
| 385 |
+
Default location is in the current directory (.agents/skills) or user-level (~/.agents/skills).
|
| 386 |
+
If `--claude` is specified, the skill is also symlinked into Claude's legacy skills directory.
|
| 387 |
+
"""
|
| 388 |
+
if dest is not None:
|
| 389 |
+
if claude or global_:
|
| 390 |
+
raise CLIError("--dest cannot be combined with --claude or --global.")
|
| 391 |
+
skill_dest = _install_to(dest, name, force)
|
| 392 |
+
print(f"Installed '{name}' to {skill_dest}")
|
| 393 |
+
return
|
| 394 |
+
|
| 395 |
+
# Install to central location
|
| 396 |
+
central_path = CENTRAL_GLOBAL if global_ else CENTRAL_LOCAL
|
| 397 |
+
central_skill_path = _install_to(central_path, name, force)
|
| 398 |
+
print(f"Installed '{name}' to central location: {central_skill_path}")
|
| 399 |
+
|
| 400 |
+
if claude:
|
| 401 |
+
agent_target = CLAUDE_GLOBAL if global_ else CLAUDE_LOCAL
|
| 402 |
+
link_path = _create_symlink(agent_target, name, central_skill_path, force)
|
| 403 |
+
print(f"Created symlink: {link_path}")
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
@skills_cli.command(
|
| 407 |
+
"upgrade",
|
| 408 |
+
examples=[
|
| 409 |
+
"hf skills upgrade",
|
| 410 |
+
"hf skills upgrade hf-cli",
|
| 411 |
+
"hf skills upgrade huggingface-gradio --dest=~/my-skills",
|
| 412 |
+
"hf skills upgrade --claude",
|
| 413 |
+
],
|
| 414 |
+
)
|
| 415 |
+
def skills_upgrade(
|
| 416 |
+
name: Annotated[
|
| 417 |
+
str | None,
|
| 418 |
+
typer.Argument(help="Optional installed skill name to upgrade.", show_default=False),
|
| 419 |
+
] = None,
|
| 420 |
+
claude: Annotated[bool, typer.Option("--claude", help="Upgrade skills installed for Claude.")] = False,
|
| 421 |
+
global_: Annotated[
|
| 422 |
+
bool,
|
| 423 |
+
typer.Option(
|
| 424 |
+
"--global",
|
| 425 |
+
"-g",
|
| 426 |
+
help="Use global skills directories instead of the current project.",
|
| 427 |
+
),
|
| 428 |
+
] = False,
|
| 429 |
+
dest: Annotated[
|
| 430 |
+
Path | None,
|
| 431 |
+
typer.Option(
|
| 432 |
+
help="Upgrade skills in a custom skills directory.",
|
| 433 |
+
),
|
| 434 |
+
] = None,
|
| 435 |
+
) -> None:
|
| 436 |
+
"""Upgrade installed Hugging Face marketplace skills."""
|
| 437 |
+
roots = _resolve_update_roots(claude=claude, global_=global_, dest=dest)
|
| 438 |
+
|
| 439 |
+
results = _skills.apply_updates(roots, selector=name)
|
| 440 |
+
if not results:
|
| 441 |
+
print("No installed skills found.")
|
| 442 |
+
return
|
| 443 |
+
|
| 444 |
+
for result in results:
|
| 445 |
+
detail = f" ({result.detail})" if result.detail else ""
|
| 446 |
+
print(f"{result.name}: {result.status}{detail}")
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/spaces.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with spaces on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# list spaces on the Hub
|
| 18 |
+
hf spaces ls
|
| 19 |
+
|
| 20 |
+
# list spaces with a search query
|
| 21 |
+
hf spaces ls --search "chatbot"
|
| 22 |
+
|
| 23 |
+
# get info about a space
|
| 24 |
+
hf spaces info enzostvs/deepsite
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import enum
|
| 28 |
+
import functools
|
| 29 |
+
import os
|
| 30 |
+
import shlex
|
| 31 |
+
import shutil
|
| 32 |
+
import subprocess
|
| 33 |
+
import sys
|
| 34 |
+
import tempfile
|
| 35 |
+
import time
|
| 36 |
+
from typing import Annotated, Literal, get_args
|
| 37 |
+
|
| 38 |
+
import typer
|
| 39 |
+
from packaging import version
|
| 40 |
+
from typing_extensions import assert_never
|
| 41 |
+
|
| 42 |
+
from huggingface_hub._hot_reload.client import multi_replica_reload_events
|
| 43 |
+
from huggingface_hub._hot_reload.types import ApiGetReloadEventSourceData, ReloadRegion
|
| 44 |
+
from huggingface_hub._space_api import SpaceStage
|
| 45 |
+
from huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundError
|
| 46 |
+
from huggingface_hub.file_download import hf_hub_download
|
| 47 |
+
from huggingface_hub.hf_api import ExpandSpaceProperty_T, HfApi, SpaceSort_T
|
| 48 |
+
from huggingface_hub.utils import StatusLine, are_progress_bars_disabled, disable_progress_bars, enable_progress_bars
|
| 49 |
+
|
| 50 |
+
from ._cli_utils import (
|
| 51 |
+
AuthorOpt,
|
| 52 |
+
FilterOpt,
|
| 53 |
+
FormatWithAutoOpt,
|
| 54 |
+
LimitOpt,
|
| 55 |
+
RevisionOpt,
|
| 56 |
+
SearchOpt,
|
| 57 |
+
TokenOpt,
|
| 58 |
+
api_object_to_dict,
|
| 59 |
+
get_hf_api,
|
| 60 |
+
make_expand_properties_parser,
|
| 61 |
+
typer_factory,
|
| 62 |
+
)
|
| 63 |
+
from ._output import OutputFormatWithAuto, out
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
HOT_RELOADING_MIN_GRADIO = "6.1.0"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
_EXPAND_PROPERTIES = sorted(get_args(ExpandSpaceProperty_T))
|
| 70 |
+
_SORT_OPTIONS = get_args(SpaceSort_T)
|
| 71 |
+
SpaceSortEnum = enum.Enum("SpaceSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
ExpandOpt = Annotated[
|
| 75 |
+
str | None,
|
| 76 |
+
typer.Option(
|
| 77 |
+
help=f"Comma-separated properties to return. When used, only the listed properties (and id) are returned. Example: '--expand=likes,tags'. Valid: {', '.join(_EXPAND_PROPERTIES)}.",
|
| 78 |
+
callback=make_expand_properties_parser(_EXPAND_PROPERTIES),
|
| 79 |
+
),
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
spaces_cli = typer_factory(help="Interact with spaces on the Hub.")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@spaces_cli.command(
|
| 86 |
+
"list | ls",
|
| 87 |
+
examples=[
|
| 88 |
+
"hf spaces ls --limit 10",
|
| 89 |
+
'hf spaces ls --search "chatbot" --author huggingface',
|
| 90 |
+
],
|
| 91 |
+
)
|
| 92 |
+
def spaces_ls(
|
| 93 |
+
search: SearchOpt = None,
|
| 94 |
+
author: AuthorOpt = None,
|
| 95 |
+
filter: FilterOpt = None,
|
| 96 |
+
sort: Annotated[
|
| 97 |
+
SpaceSortEnum | None,
|
| 98 |
+
typer.Option(help="Sort results."),
|
| 99 |
+
] = None,
|
| 100 |
+
limit: LimitOpt = 10,
|
| 101 |
+
expand: ExpandOpt = None,
|
| 102 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 103 |
+
token: TokenOpt = None,
|
| 104 |
+
) -> None:
|
| 105 |
+
"""List spaces on the Hub."""
|
| 106 |
+
api = get_hf_api(token=token)
|
| 107 |
+
sort_key = sort.value if sort else None
|
| 108 |
+
results = [
|
| 109 |
+
api_object_to_dict(space_info)
|
| 110 |
+
for space_info in api.list_spaces(
|
| 111 |
+
filter=filter,
|
| 112 |
+
author=author,
|
| 113 |
+
search=search,
|
| 114 |
+
sort=sort_key,
|
| 115 |
+
limit=limit,
|
| 116 |
+
expand=expand, # type: ignore[arg-type]
|
| 117 |
+
)
|
| 118 |
+
]
|
| 119 |
+
out.table(results)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@spaces_cli.command(
|
| 123 |
+
"info",
|
| 124 |
+
examples=[
|
| 125 |
+
"hf spaces info enzostvs/deepsite",
|
| 126 |
+
"hf spaces info gradio/theme_builder --expand sdk,runtime,likes",
|
| 127 |
+
],
|
| 128 |
+
)
|
| 129 |
+
def spaces_info(
|
| 130 |
+
space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")],
|
| 131 |
+
revision: RevisionOpt = None,
|
| 132 |
+
expand: ExpandOpt = None,
|
| 133 |
+
format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
|
| 134 |
+
token: TokenOpt = None,
|
| 135 |
+
) -> None:
|
| 136 |
+
"""Get info about a space on the Hub."""
|
| 137 |
+
api = get_hf_api(token=token)
|
| 138 |
+
try:
|
| 139 |
+
info = api.space_info(repo_id=space_id, revision=revision, expand=expand) # type: ignore[arg-type]
|
| 140 |
+
except RepositoryNotFoundError as e:
|
| 141 |
+
raise CLIError(f"Space '{space_id}' not found.") from e
|
| 142 |
+
except RevisionNotFoundError as e:
|
| 143 |
+
raise CLIError(f"Revision '{revision}' not found on '{space_id}'.") from e
|
| 144 |
+
out.dict(info)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@spaces_cli.command(
|
| 148 |
+
"dev-mode",
|
| 149 |
+
examples=[
|
| 150 |
+
"hf spaces dev-mode my-user-name/deepsite",
|
| 151 |
+
],
|
| 152 |
+
)
|
| 153 |
+
def dev_mode(
|
| 154 |
+
space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")],
|
| 155 |
+
stop: Annotated[bool, typer.Option(help="Stop dev mode.")] = False,
|
| 156 |
+
token: TokenOpt = None,
|
| 157 |
+
):
|
| 158 |
+
"""
|
| 159 |
+
Enable or disable dev mode on a Space.
|
| 160 |
+
|
| 161 |
+
Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you to
|
| 162 |
+
restart your application without stopping the Space container itself. This feature is available as part of a PRO
|
| 163 |
+
or Team & Enterprise plan.
|
| 164 |
+
|
| 165 |
+
See docs: https://huggingface.co/docs/hub/spaces-dev-mode
|
| 166 |
+
"""
|
| 167 |
+
api = get_hf_api(token=token)
|
| 168 |
+
if stop:
|
| 169 |
+
api.disable_space_dev_mode(space_id)
|
| 170 |
+
print(f"Dev mode disabled for '{space_id}'")
|
| 171 |
+
return
|
| 172 |
+
api.enable_space_dev_mode(space_id)
|
| 173 |
+
info = api.space_info(space_id)
|
| 174 |
+
folder = getattr(info.card_data, "dev-mode-folder", "" if info.sdk == "docker" else "/home/user/app")
|
| 175 |
+
folder_query_param = f"folder={folder}" if folder else ""
|
| 176 |
+
print(f"Dev mode is currently building, track the progress here: https://huggingface.co/spaces/{info.id}")
|
| 177 |
+
intermediate_statuses_and_messages = {
|
| 178 |
+
SpaceStage.BUILDING: "building...",
|
| 179 |
+
SpaceStage.RUNNING_BUILDING: "building...",
|
| 180 |
+
SpaceStage.APP_STARTING: "app starting...",
|
| 181 |
+
SpaceStage.RUNNING_APP_STARTING: "app starting...",
|
| 182 |
+
}
|
| 183 |
+
status = StatusLine()
|
| 184 |
+
while True:
|
| 185 |
+
info = api.space_info(space_id)
|
| 186 |
+
if info.runtime is None:
|
| 187 |
+
print("Runtime of the space unavailable")
|
| 188 |
+
return
|
| 189 |
+
if info.runtime.stage not in intermediate_statuses_and_messages:
|
| 190 |
+
break
|
| 191 |
+
status.update(intermediate_statuses_and_messages[info.runtime.stage])
|
| 192 |
+
time.sleep(1)
|
| 193 |
+
if info.runtime.stage != SpaceStage.RUNNING:
|
| 194 |
+
status.done(f"Dev mode is not ready (stage='{info.runtime.stage}')")
|
| 195 |
+
return
|
| 196 |
+
status.done("Dev mode ready!")
|
| 197 |
+
print("Connect to dev environment:")
|
| 198 |
+
print("")
|
| 199 |
+
print("Web:")
|
| 200 |
+
vscode_web_url = f"https://huggingface.co/spaces/{info.id}/dev-mode/vscode-web"
|
| 201 |
+
if folder_query_param:
|
| 202 |
+
vscode_web_url += f"?{folder_query_param}"
|
| 203 |
+
ssh_host = f"{info.subdomain}@ssh.hf.space"
|
| 204 |
+
print(f" * VSCode: {vscode_web_url}")
|
| 205 |
+
print("")
|
| 206 |
+
print("Local:")
|
| 207 |
+
print("1. Add your SSH key to https://huggingface.co/settings/keys")
|
| 208 |
+
print(f"2. SSH with `ssh -i <your_key> {ssh_host}`")
|
| 209 |
+
print(" Or open")
|
| 210 |
+
print(f" * VSCode: vscode://vscode-remote/ssh-remote+{ssh_host}{folder}")
|
| 211 |
+
print(f" * Cursor: cursor://vscode-remote/ssh-remote+{ssh_host}{folder}")
|
| 212 |
+
print("")
|
| 213 |
+
print("PS: Dev mode stops after 48h of inactivity, don't forget to save your changes regularly.")
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@spaces_cli.command(
|
| 217 |
+
"hot-reload",
|
| 218 |
+
examples=[
|
| 219 |
+
"hf spaces hot-reload username/repo-name app.py # Open an interactive editor to the remote app.py file",
|
| 220 |
+
"hf spaces hot-reload username/repo-name -f app.py # Take local version from ./app.py and patch app.py remotely",
|
| 221 |
+
"hf spaces hot-reload username/repo-name app.py -f src/app.py # Take local version from ./src/app.py",
|
| 222 |
+
],
|
| 223 |
+
)
|
| 224 |
+
def spaces_hot_reload(
|
| 225 |
+
space_id: Annotated[
|
| 226 |
+
str,
|
| 227 |
+
typer.Argument(
|
| 228 |
+
help="The space ID (e.g. `username/repo-name`).",
|
| 229 |
+
),
|
| 230 |
+
],
|
| 231 |
+
filename: Annotated[
|
| 232 |
+
str | None,
|
| 233 |
+
typer.Argument(
|
| 234 |
+
help="Path to the Python file in the Space repository. Can be omitted when --local-file is specified and path in repository matches."
|
| 235 |
+
),
|
| 236 |
+
] = None,
|
| 237 |
+
local_file: Annotated[
|
| 238 |
+
str | None,
|
| 239 |
+
typer.Option(
|
| 240 |
+
"--local-file",
|
| 241 |
+
"-f",
|
| 242 |
+
help="Path of local file. Interactive editor mode if not specified",
|
| 243 |
+
),
|
| 244 |
+
] = None,
|
| 245 |
+
skip_checks: Annotated[bool, typer.Option(help="Skip hot-reload compatibility checks.")] = False,
|
| 246 |
+
skip_summary: Annotated[bool, typer.Option(help="Skip summary display after hot-reload is triggered")] = False,
|
| 247 |
+
token: TokenOpt = None,
|
| 248 |
+
) -> None:
|
| 249 |
+
"""
|
| 250 |
+
Hot-reload any Python file of a Space without a full rebuild + restart.
|
| 251 |
+
|
| 252 |
+
⚠ This feature is experimental ⚠
|
| 253 |
+
|
| 254 |
+
Only works with Gradio SDK (6.1+)
|
| 255 |
+
Opens an interactive editor unless --local-file/-f is specified.
|
| 256 |
+
|
| 257 |
+
This command patches the live Python process using https://github.com/breuleux/jurigged
|
| 258 |
+
(AST-based diffing, in-place function updates, etc.), integrated with Gradio's native hot-reload support
|
| 259 |
+
(meaning that Gradio demo object changes are reflected in the UI)
|
| 260 |
+
|
| 261 |
+
The command creates a remote commit.
|
| 262 |
+
If you are working from a local clone, run `git pull --autostash` afterwards
|
| 263 |
+
to bring the commit back and keep your local git state in sync.
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
typer.secho("This feature is experimental and subject to change", fg=typer.colors.BRIGHT_BLACK)
|
| 267 |
+
|
| 268 |
+
api = get_hf_api(token=token)
|
| 269 |
+
|
| 270 |
+
if not skip_checks:
|
| 271 |
+
space_info = api.space_info(space_id)
|
| 272 |
+
if space_info.sdk != "gradio":
|
| 273 |
+
raise CLIError(f"Hot-reloading is only available on Gradio SDK. Found {space_info.sdk} SDK")
|
| 274 |
+
if (card_data := space_info.card_data) is None:
|
| 275 |
+
raise CLIError(f"Unable to read cardData for Space {space_id}")
|
| 276 |
+
if (sdk_version := card_data.sdk_version) is None:
|
| 277 |
+
raise CLIError(f"Unable to read sdk_version from {space_id} cardData")
|
| 278 |
+
if version.parse(sdk_version) < version.Version(HOT_RELOADING_MIN_GRADIO):
|
| 279 |
+
raise CLIError(f"Hot-reloading requires Gradio >= {HOT_RELOADING_MIN_GRADIO} (found {sdk_version})")
|
| 280 |
+
|
| 281 |
+
if local_file:
|
| 282 |
+
local_path = local_file
|
| 283 |
+
filename = local_file if filename is None else filename
|
| 284 |
+
elif filename:
|
| 285 |
+
if not skip_checks:
|
| 286 |
+
try:
|
| 287 |
+
api.auth_check(
|
| 288 |
+
repo_type="space",
|
| 289 |
+
repo_id=space_id,
|
| 290 |
+
write=True,
|
| 291 |
+
)
|
| 292 |
+
except RepositoryNotFoundError as e:
|
| 293 |
+
raise CLIError(
|
| 294 |
+
f"Write access check to {space_id} repository failed. Make sure that you are authenticated"
|
| 295 |
+
) from e
|
| 296 |
+
temp_dir = tempfile.TemporaryDirectory()
|
| 297 |
+
local_path = os.path.join(temp_dir.name, filename)
|
| 298 |
+
if not (pbar_disabled := are_progress_bars_disabled()):
|
| 299 |
+
disable_progress_bars()
|
| 300 |
+
try:
|
| 301 |
+
hf_hub_download(
|
| 302 |
+
repo_type="space",
|
| 303 |
+
repo_id=space_id,
|
| 304 |
+
filename=filename,
|
| 305 |
+
local_dir=temp_dir.name,
|
| 306 |
+
)
|
| 307 |
+
finally:
|
| 308 |
+
if not pbar_disabled:
|
| 309 |
+
enable_progress_bars()
|
| 310 |
+
editor_res = _editor_open(local_path)
|
| 311 |
+
if editor_res == "no-tty":
|
| 312 |
+
raise CLIError("Cannot open an editor (no TTY). Use -f flag to hot-reload from local path")
|
| 313 |
+
if editor_res == "no-editor":
|
| 314 |
+
raise CLIError("No editor found in local environment. Use -f flag to hot-reload from local path")
|
| 315 |
+
if editor_res != 0:
|
| 316 |
+
raise CLIError(f"Editor returned a non-zero exit code while attempting to edit {local_path}")
|
| 317 |
+
else:
|
| 318 |
+
raise CLIError("Either filename or --local-file/-f must be specified")
|
| 319 |
+
|
| 320 |
+
commit_info = api.upload_file(
|
| 321 |
+
repo_type="space",
|
| 322 |
+
repo_id=space_id,
|
| 323 |
+
path_or_fileobj=local_path,
|
| 324 |
+
path_in_repo=filename,
|
| 325 |
+
_hot_reload=True,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
if not skip_summary:
|
| 329 |
+
_spaces_hot_reload_summary(
|
| 330 |
+
api=api,
|
| 331 |
+
space_id=space_id,
|
| 332 |
+
commit_sha=commit_info.oid,
|
| 333 |
+
local_path=local_path if local_file else os.path.basename(local_path),
|
| 334 |
+
token=token,
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _spaces_hot_reload_summary(
|
| 339 |
+
api: HfApi,
|
| 340 |
+
space_id: str,
|
| 341 |
+
commit_sha: str,
|
| 342 |
+
local_path: str | None,
|
| 343 |
+
token: str | None,
|
| 344 |
+
) -> None:
|
| 345 |
+
space_info = api.space_info(space_id)
|
| 346 |
+
if (runtime := space_info.runtime) is None:
|
| 347 |
+
raise CLIError(f"Unable to read SpaceRuntime from {space_id} infos")
|
| 348 |
+
if (hot_reloading := runtime.hot_reloading) is None:
|
| 349 |
+
raise CLIError(f"Space {space_id} current running version has not been hot-reloaded")
|
| 350 |
+
if hot_reloading.status != "created":
|
| 351 |
+
typer.echo(f"Failed creating hot-reloaded commit. {hot_reloading.replica_statuses=}")
|
| 352 |
+
return
|
| 353 |
+
|
| 354 |
+
if (space_host := space_info.host) is None:
|
| 355 |
+
raise CLIError("Unexpected None host on hotReloaded Space")
|
| 356 |
+
if (space_subdomain := space_info.subdomain) is None:
|
| 357 |
+
raise CLIError("Unexpected None subdomain on hotReloaded Space")
|
| 358 |
+
|
| 359 |
+
def render_region(region: ReloadRegion) -> str:
|
| 360 |
+
res = ""
|
| 361 |
+
if local_path is not None:
|
| 362 |
+
res += f"{local_path}, "
|
| 363 |
+
if region["startLine"] == region["endLine"]:
|
| 364 |
+
res += f"line {region['startLine'] - 1}"
|
| 365 |
+
else:
|
| 366 |
+
res += f"lines {region['startLine'] - 1}-{region['endLine']}"
|
| 367 |
+
return res
|
| 368 |
+
|
| 369 |
+
def display_event(event: ApiGetReloadEventSourceData) -> None:
|
| 370 |
+
if event["data"]["kind"] == "error":
|
| 371 |
+
typer.secho("✘ Unexpected hot-reloading error", bold=True)
|
| 372 |
+
typer.secho(event["data"]["traceback"], italic=True)
|
| 373 |
+
elif event["data"]["kind"] == "exception":
|
| 374 |
+
typer.secho(f"✘ Exception at {render_region(event['data']['region'])}", bold=True)
|
| 375 |
+
typer.secho(event["data"]["traceback"], italic=True)
|
| 376 |
+
elif event["data"]["kind"] == "add":
|
| 377 |
+
typer.secho(f"✔︎ Created {event['data']['objectName']} {event['data']['objectType']}", bold=True)
|
| 378 |
+
elif event["data"]["kind"] == "delete":
|
| 379 |
+
typer.secho(f"∅ Deleted {event['data']['objectName']} {event['data']['objectType']}", bold=True)
|
| 380 |
+
elif event["data"]["kind"] == "update":
|
| 381 |
+
typer.secho(f"✔︎ Updated {event['data']['objectName']} {event['data']['objectType']}", bold=True)
|
| 382 |
+
elif event["data"]["kind"] == "run":
|
| 383 |
+
typer.secho(f"▶ Run {render_region(event['data']['region'])}", bold=True)
|
| 384 |
+
typer.secho(event["data"]["codeLines"], italic=True)
|
| 385 |
+
elif event["data"]["kind"] == "ui":
|
| 386 |
+
if event["data"]["updated"]:
|
| 387 |
+
typer.secho("⟳ UI updated", bold=True)
|
| 388 |
+
else:
|
| 389 |
+
typer.secho("∅ UI untouched", bold=True)
|
| 390 |
+
else:
|
| 391 |
+
assert_never(event["data"]["kind"])
|
| 392 |
+
|
| 393 |
+
for replica_stream_event in multi_replica_reload_events(
|
| 394 |
+
commit_sha=commit_sha,
|
| 395 |
+
host=space_host,
|
| 396 |
+
subdomain=space_subdomain,
|
| 397 |
+
replica_hashes=[hash for hash, _ in hot_reloading.replica_statuses],
|
| 398 |
+
token=token,
|
| 399 |
+
):
|
| 400 |
+
if replica_stream_event["kind"] == "event":
|
| 401 |
+
display_event(replica_stream_event["event"])
|
| 402 |
+
elif replica_stream_event["kind"] == "replicaHash":
|
| 403 |
+
typer.secho(f"---- Replica {replica_stream_event['hash']} ----")
|
| 404 |
+
elif replica_stream_event["kind"] == "fullMatch":
|
| 405 |
+
typer.echo("✔︎ Same as first replica")
|
| 406 |
+
else:
|
| 407 |
+
assert_never(replica_stream_event)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
PREFERRED_EDITORS = (
|
| 411 |
+
("code", "code --wait"),
|
| 412 |
+
("nvim", "nvim"),
|
| 413 |
+
("nano", "nano"),
|
| 414 |
+
("vim", "vim"),
|
| 415 |
+
("vi", "vi"),
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@functools.cache
|
| 420 |
+
def _get_editor_command() -> str | None:
|
| 421 |
+
for env in ("HF_EDITOR", "VISUAL", "EDITOR"):
|
| 422 |
+
if command := os.getenv(env, "").strip():
|
| 423 |
+
return command
|
| 424 |
+
for binary_path, editor_command in PREFERRED_EDITORS:
|
| 425 |
+
if shutil.which(binary_path) is not None:
|
| 426 |
+
return editor_command
|
| 427 |
+
return None
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def _editor_open(local_path: str) -> int | Literal["no-tty", "no-editor"]:
|
| 431 |
+
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
| 432 |
+
return "no-tty"
|
| 433 |
+
if (editor_command := _get_editor_command()) is None:
|
| 434 |
+
return "no-editor"
|
| 435 |
+
command = [*shlex.split(editor_command), local_path]
|
| 436 |
+
res = subprocess.run(command, start_new_session=True)
|
| 437 |
+
return res.returncode
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/system.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to print information about the environment and version."""
|
| 15 |
+
|
| 16 |
+
from huggingface_hub import __version__
|
| 17 |
+
|
| 18 |
+
from ..utils import dump_environment_info
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def env() -> None:
|
| 22 |
+
"""Print information about the environment."""
|
| 23 |
+
dump_environment_info()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def version() -> None:
|
| 27 |
+
"""Print information about the hf version."""
|
| 28 |
+
print(__version__)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/upload.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains command to upload a repo or file with the CLI.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# Upload file (implicit)
|
| 18 |
+
hf upload my-cool-model ./my-cool-model.safetensors
|
| 19 |
+
|
| 20 |
+
# Upload file (explicit)
|
| 21 |
+
hf upload my-cool-model ./my-cool-model.safetensors model.safetensors
|
| 22 |
+
|
| 23 |
+
# Upload directory (implicit). If `my-cool-model/` is a directory it will be uploaded, otherwise an exception is raised.
|
| 24 |
+
hf upload my-cool-model
|
| 25 |
+
|
| 26 |
+
# Upload directory (explicit)
|
| 27 |
+
hf upload my-cool-model ./models/my-cool-model .
|
| 28 |
+
|
| 29 |
+
# Upload filtered directory (example: tensorboard logs except for the last run)
|
| 30 |
+
hf upload my-cool-model ./model/training /logs --include "*.tfevents.*" --exclude "*20230905*"
|
| 31 |
+
|
| 32 |
+
# Upload with wildcard
|
| 33 |
+
hf upload my-cool-model "./model/training/*.safetensors"
|
| 34 |
+
|
| 35 |
+
# Upload private dataset
|
| 36 |
+
hf upload Wauplin/my-cool-dataset ./data . --repo-type=dataset --private
|
| 37 |
+
|
| 38 |
+
# Upload with token
|
| 39 |
+
hf upload Wauplin/my-cool-model --token=hf_****
|
| 40 |
+
|
| 41 |
+
# Sync local Space with Hub (upload new files, delete removed files)
|
| 42 |
+
hf upload Wauplin/space-example --repo-type=space --exclude="/logs/*" --delete="*" --commit-message="Sync local Space with Hub"
|
| 43 |
+
|
| 44 |
+
# Schedule commits every 30 minutes
|
| 45 |
+
hf upload Wauplin/my-cool-model --every=30
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
import os
|
| 49 |
+
import time
|
| 50 |
+
import warnings
|
| 51 |
+
from typing import Annotated
|
| 52 |
+
|
| 53 |
+
import typer
|
| 54 |
+
|
| 55 |
+
from huggingface_hub import logging
|
| 56 |
+
from huggingface_hub._commit_scheduler import CommitScheduler
|
| 57 |
+
from huggingface_hub.errors import RevisionNotFoundError
|
| 58 |
+
from huggingface_hub.utils import disable_progress_bars, enable_progress_bars
|
| 59 |
+
|
| 60 |
+
from ._cli_utils import (
|
| 61 |
+
PrivateOpt,
|
| 62 |
+
RepoIdArg,
|
| 63 |
+
RepoType,
|
| 64 |
+
RepoTypeOpt,
|
| 65 |
+
RevisionOpt,
|
| 66 |
+
TokenOpt,
|
| 67 |
+
get_hf_api,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
logger = logging.get_logger(__name__)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
UPLOAD_EXAMPLES = [
|
| 75 |
+
"hf upload my-cool-model . .",
|
| 76 |
+
"hf upload Wauplin/my-cool-model ./models/model.safetensors",
|
| 77 |
+
"hf upload Wauplin/my-cool-dataset ./data /train --repo-type=dataset",
|
| 78 |
+
'hf upload Wauplin/my-cool-model ./models . --commit-message="Epoch 34/50" --commit-description="Val accuracy: 68%"',
|
| 79 |
+
"hf upload bigcode/the-stack . . --repo-type dataset --create-pr",
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def upload(
|
| 84 |
+
repo_id: RepoIdArg,
|
| 85 |
+
local_path: Annotated[
|
| 86 |
+
str | None,
|
| 87 |
+
typer.Argument(
|
| 88 |
+
help="Local path to the file or folder to upload. Wildcard patterns are supported. Defaults to current directory.",
|
| 89 |
+
),
|
| 90 |
+
] = None,
|
| 91 |
+
path_in_repo: Annotated[
|
| 92 |
+
str | None,
|
| 93 |
+
typer.Argument(
|
| 94 |
+
help="Path of the file or folder in the repo. Defaults to the relative path of the file or folder.",
|
| 95 |
+
),
|
| 96 |
+
] = None,
|
| 97 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 98 |
+
revision: RevisionOpt = None,
|
| 99 |
+
private: PrivateOpt = None,
|
| 100 |
+
include: Annotated[
|
| 101 |
+
list[str] | None,
|
| 102 |
+
typer.Option(
|
| 103 |
+
help="Glob patterns to match files to upload.",
|
| 104 |
+
),
|
| 105 |
+
] = None,
|
| 106 |
+
exclude: Annotated[
|
| 107 |
+
list[str] | None,
|
| 108 |
+
typer.Option(
|
| 109 |
+
help="Glob patterns to exclude from files to upload.",
|
| 110 |
+
),
|
| 111 |
+
] = None,
|
| 112 |
+
delete: Annotated[
|
| 113 |
+
list[str] | None,
|
| 114 |
+
typer.Option(
|
| 115 |
+
help="Glob patterns for file to be deleted from the repo while committing.",
|
| 116 |
+
),
|
| 117 |
+
] = None,
|
| 118 |
+
commit_message: Annotated[
|
| 119 |
+
str | None,
|
| 120 |
+
typer.Option(
|
| 121 |
+
help="The summary / title / first line of the generated commit.",
|
| 122 |
+
),
|
| 123 |
+
] = None,
|
| 124 |
+
commit_description: Annotated[
|
| 125 |
+
str | None,
|
| 126 |
+
typer.Option(
|
| 127 |
+
help="The description of the generated commit.",
|
| 128 |
+
),
|
| 129 |
+
] = None,
|
| 130 |
+
create_pr: Annotated[
|
| 131 |
+
bool,
|
| 132 |
+
typer.Option(
|
| 133 |
+
help="Whether to upload content as a new Pull Request.",
|
| 134 |
+
),
|
| 135 |
+
] = False,
|
| 136 |
+
every: Annotated[
|
| 137 |
+
float | None,
|
| 138 |
+
typer.Option(
|
| 139 |
+
help="If set, a background job is scheduled to create commits every `every` minutes.",
|
| 140 |
+
),
|
| 141 |
+
] = None,
|
| 142 |
+
token: TokenOpt = None,
|
| 143 |
+
quiet: Annotated[
|
| 144 |
+
bool,
|
| 145 |
+
typer.Option(
|
| 146 |
+
help="Disable progress bars and warnings; print only the returned path.",
|
| 147 |
+
),
|
| 148 |
+
] = False,
|
| 149 |
+
) -> None:
|
| 150 |
+
"""Upload a file or a folder to the Hub. Recommended for single-commit uploads."""
|
| 151 |
+
|
| 152 |
+
if every is not None and every <= 0:
|
| 153 |
+
raise typer.BadParameter("--every must be a positive value", param_hint="every")
|
| 154 |
+
|
| 155 |
+
repo_type_str = repo_type.value
|
| 156 |
+
|
| 157 |
+
api = get_hf_api(token=token)
|
| 158 |
+
|
| 159 |
+
# Resolve local_path and path_in_repo based on implicit/explicit rules
|
| 160 |
+
resolved_local_path, resolved_path_in_repo, resolved_include = _resolve_upload_paths(
|
| 161 |
+
repo_id=repo_id, local_path=local_path, path_in_repo=path_in_repo, include=include
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def run_upload() -> str:
|
| 165 |
+
if os.path.isfile(resolved_local_path):
|
| 166 |
+
if resolved_include is not None and len(resolved_include) > 0 and isinstance(resolved_include, list):
|
| 167 |
+
warnings.warn("Ignoring --include since a single file is uploaded.")
|
| 168 |
+
if exclude is not None and len(exclude) > 0:
|
| 169 |
+
warnings.warn("Ignoring --exclude since a single file is uploaded.")
|
| 170 |
+
if delete is not None and len(delete) > 0:
|
| 171 |
+
warnings.warn("Ignoring --delete since a single file is uploaded.")
|
| 172 |
+
|
| 173 |
+
# Schedule commits if `every` is set
|
| 174 |
+
if every is not None:
|
| 175 |
+
allow_patterns: list[str] | None
|
| 176 |
+
ignore_patterns: list[str] | None
|
| 177 |
+
if os.path.isfile(resolved_local_path):
|
| 178 |
+
# If file => watch entire folder + use allow_patterns
|
| 179 |
+
folder_path = os.path.dirname(resolved_local_path)
|
| 180 |
+
pi = (
|
| 181 |
+
resolved_path_in_repo[: -len(resolved_local_path)]
|
| 182 |
+
if resolved_path_in_repo.endswith(resolved_local_path)
|
| 183 |
+
else resolved_path_in_repo
|
| 184 |
+
)
|
| 185 |
+
allow_patterns = [resolved_local_path]
|
| 186 |
+
ignore_patterns = []
|
| 187 |
+
else:
|
| 188 |
+
folder_path = resolved_local_path
|
| 189 |
+
pi = resolved_path_in_repo
|
| 190 |
+
allow_patterns = resolved_include
|
| 191 |
+
ignore_patterns = exclude
|
| 192 |
+
if delete is not None and len(delete) > 0:
|
| 193 |
+
warnings.warn("Ignoring --delete when uploading with scheduled commits.")
|
| 194 |
+
|
| 195 |
+
scheduler = CommitScheduler(
|
| 196 |
+
folder_path=folder_path,
|
| 197 |
+
repo_id=repo_id,
|
| 198 |
+
repo_type=repo_type_str,
|
| 199 |
+
revision=revision,
|
| 200 |
+
allow_patterns=allow_patterns,
|
| 201 |
+
ignore_patterns=ignore_patterns,
|
| 202 |
+
path_in_repo=pi,
|
| 203 |
+
private=private,
|
| 204 |
+
every=every,
|
| 205 |
+
hf_api=api,
|
| 206 |
+
)
|
| 207 |
+
print(f"Scheduling commits every {every} minutes to {scheduler.repo_id}.")
|
| 208 |
+
try:
|
| 209 |
+
while True:
|
| 210 |
+
time.sleep(100)
|
| 211 |
+
except KeyboardInterrupt:
|
| 212 |
+
scheduler.stop()
|
| 213 |
+
return "Stopped scheduled commits."
|
| 214 |
+
|
| 215 |
+
# Otherwise, create repo and proceed with the upload
|
| 216 |
+
if not os.path.isfile(resolved_local_path) and not os.path.isdir(resolved_local_path):
|
| 217 |
+
raise FileNotFoundError(f"No such file or directory: '{resolved_local_path}'.")
|
| 218 |
+
created = api.create_repo(
|
| 219 |
+
repo_id=repo_id,
|
| 220 |
+
repo_type=repo_type_str,
|
| 221 |
+
exist_ok=True,
|
| 222 |
+
private=private,
|
| 223 |
+
space_sdk="gradio" if repo_type_str == "space" else None,
|
| 224 |
+
# ^ We don't want it to fail when uploading to a Space => let's set Gradio by default.
|
| 225 |
+
# ^ I'd rather not add CLI args to set it explicitly as we already have `hf repos create` for that.
|
| 226 |
+
).repo_id
|
| 227 |
+
|
| 228 |
+
# Check if branch already exists and if not, create it
|
| 229 |
+
if revision is not None and not create_pr:
|
| 230 |
+
try:
|
| 231 |
+
api.repo_info(repo_id=created, repo_type=repo_type_str, revision=revision)
|
| 232 |
+
except RevisionNotFoundError:
|
| 233 |
+
logger.info(f"Branch '{revision}' not found. Creating it...")
|
| 234 |
+
api.create_branch(repo_id=created, repo_type=repo_type_str, branch=revision, exist_ok=True)
|
| 235 |
+
# ^ `exist_ok=True` to avoid race concurrency issues
|
| 236 |
+
|
| 237 |
+
# File-based upload
|
| 238 |
+
if os.path.isfile(resolved_local_path):
|
| 239 |
+
return api.upload_file(
|
| 240 |
+
path_or_fileobj=resolved_local_path,
|
| 241 |
+
path_in_repo=resolved_path_in_repo,
|
| 242 |
+
repo_id=created,
|
| 243 |
+
repo_type=repo_type_str,
|
| 244 |
+
revision=revision,
|
| 245 |
+
commit_message=commit_message,
|
| 246 |
+
commit_description=commit_description,
|
| 247 |
+
create_pr=create_pr,
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
# Folder-based upload
|
| 251 |
+
return api.upload_folder(
|
| 252 |
+
folder_path=resolved_local_path,
|
| 253 |
+
path_in_repo=resolved_path_in_repo,
|
| 254 |
+
repo_id=created,
|
| 255 |
+
repo_type=repo_type_str,
|
| 256 |
+
revision=revision,
|
| 257 |
+
commit_message=commit_message,
|
| 258 |
+
commit_description=commit_description,
|
| 259 |
+
create_pr=create_pr,
|
| 260 |
+
allow_patterns=resolved_include,
|
| 261 |
+
ignore_patterns=exclude,
|
| 262 |
+
delete_patterns=delete,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
if quiet:
|
| 266 |
+
disable_progress_bars()
|
| 267 |
+
with warnings.catch_warnings():
|
| 268 |
+
warnings.simplefilter("ignore")
|
| 269 |
+
print(run_upload())
|
| 270 |
+
enable_progress_bars()
|
| 271 |
+
else:
|
| 272 |
+
print(run_upload())
|
| 273 |
+
logging.set_verbosity_warning()
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _resolve_upload_paths(
|
| 277 |
+
*, repo_id: str, local_path: str | None, path_in_repo: str | None, include: list[str] | None
|
| 278 |
+
) -> tuple[str, str, list[str] | None]:
|
| 279 |
+
repo_name = repo_id.split("/")[-1]
|
| 280 |
+
resolved_include = include
|
| 281 |
+
|
| 282 |
+
if local_path is not None and any(c in local_path for c in ["*", "?", "["]):
|
| 283 |
+
if include is not None:
|
| 284 |
+
raise ValueError("Cannot set --include when local_path contains a wildcard.")
|
| 285 |
+
if path_in_repo is not None and path_in_repo != ".":
|
| 286 |
+
raise ValueError("Cannot set path_in_repo when local_path contains a wildcard.")
|
| 287 |
+
return ".", local_path, ["."] # will be adjusted below; placeholder for type
|
| 288 |
+
|
| 289 |
+
if local_path is None and os.path.isfile(repo_name):
|
| 290 |
+
return repo_name, repo_name, resolved_include
|
| 291 |
+
if local_path is None and os.path.isdir(repo_name):
|
| 292 |
+
return repo_name, ".", resolved_include
|
| 293 |
+
if local_path is None:
|
| 294 |
+
raise ValueError(f"'{repo_name}' is not a local file or folder. Please set local_path explicitly.")
|
| 295 |
+
|
| 296 |
+
if path_in_repo is None and os.path.isfile(local_path):
|
| 297 |
+
return local_path, os.path.basename(local_path), resolved_include
|
| 298 |
+
if path_in_repo is None:
|
| 299 |
+
return local_path, ".", resolved_include
|
| 300 |
+
return local_path, path_in_repo, resolved_include
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/upload_large_folder.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains command to upload a large folder with the CLI."""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
from typing import Annotated
|
| 18 |
+
|
| 19 |
+
import typer
|
| 20 |
+
|
| 21 |
+
from huggingface_hub import logging
|
| 22 |
+
from huggingface_hub.utils import ANSI, disable_progress_bars
|
| 23 |
+
|
| 24 |
+
from ._cli_utils import (
|
| 25 |
+
PrivateOpt,
|
| 26 |
+
RepoIdArg,
|
| 27 |
+
RepoType,
|
| 28 |
+
RepoTypeOpt,
|
| 29 |
+
RevisionOpt,
|
| 30 |
+
TokenOpt,
|
| 31 |
+
get_hf_api,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
UPLOAD_LARGE_FOLDER_EXAMPLES = [
|
| 39 |
+
"hf upload-large-folder Wauplin/my-cool-model ./large_model_dir",
|
| 40 |
+
"hf upload-large-folder Wauplin/my-cool-model ./large_model_dir --revision v1.0",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def upload_large_folder(
|
| 45 |
+
repo_id: RepoIdArg,
|
| 46 |
+
local_path: Annotated[
|
| 47 |
+
str,
|
| 48 |
+
typer.Argument(
|
| 49 |
+
help="Local path to the folder to upload.",
|
| 50 |
+
),
|
| 51 |
+
],
|
| 52 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 53 |
+
revision: RevisionOpt = None,
|
| 54 |
+
private: PrivateOpt = None,
|
| 55 |
+
include: Annotated[
|
| 56 |
+
list[str] | None,
|
| 57 |
+
typer.Option(
|
| 58 |
+
help="Glob patterns to match files to upload.",
|
| 59 |
+
),
|
| 60 |
+
] = None,
|
| 61 |
+
exclude: Annotated[
|
| 62 |
+
list[str] | None,
|
| 63 |
+
typer.Option(
|
| 64 |
+
help="Glob patterns to exclude from files to upload.",
|
| 65 |
+
),
|
| 66 |
+
] = None,
|
| 67 |
+
token: TokenOpt = None,
|
| 68 |
+
num_workers: Annotated[
|
| 69 |
+
int | None,
|
| 70 |
+
typer.Option(
|
| 71 |
+
help="Number of workers to use to hash, upload and commit files.",
|
| 72 |
+
),
|
| 73 |
+
] = None,
|
| 74 |
+
no_report: Annotated[
|
| 75 |
+
bool,
|
| 76 |
+
typer.Option(
|
| 77 |
+
help="Whether to disable regular status report.",
|
| 78 |
+
),
|
| 79 |
+
] = False,
|
| 80 |
+
no_bars: Annotated[
|
| 81 |
+
bool,
|
| 82 |
+
typer.Option(
|
| 83 |
+
help="Whether to disable progress bars.",
|
| 84 |
+
),
|
| 85 |
+
] = False,
|
| 86 |
+
) -> None:
|
| 87 |
+
"""Upload a large folder to the Hub. Recommended for resumable uploads."""
|
| 88 |
+
if not os.path.isdir(local_path):
|
| 89 |
+
raise typer.BadParameter("Large upload is only supported for folders.", param_hint="local_path")
|
| 90 |
+
|
| 91 |
+
print(
|
| 92 |
+
ANSI.yellow(
|
| 93 |
+
"You are about to upload a large folder to the Hub using `hf upload-large-folder`. "
|
| 94 |
+
"This is a new feature so feedback is very welcome!\n"
|
| 95 |
+
"\n"
|
| 96 |
+
"A few things to keep in mind:\n"
|
| 97 |
+
" - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations\n"
|
| 98 |
+
" - Do not start several processes in parallel.\n"
|
| 99 |
+
" - You can interrupt and resume the process at any time. "
|
| 100 |
+
"The script will pick up where it left off except for partially uploaded files that would have to be entirely reuploaded.\n"
|
| 101 |
+
" - Do not upload the same folder to several repositories. If you need to do so, you must delete the `./.cache/huggingface/` folder first.\n"
|
| 102 |
+
"\n"
|
| 103 |
+
f"Some temporary metadata will be stored under `{local_path}/.cache/huggingface`.\n"
|
| 104 |
+
" - You must not modify those files manually.\n"
|
| 105 |
+
" - You must not delete the `./.cache/huggingface/` folder while a process is running.\n"
|
| 106 |
+
" - You can delete the `./.cache/huggingface/` folder to reinitialize the upload state when process is not running. Files will have to be hashed and preuploaded again, except for already committed files.\n"
|
| 107 |
+
"\n"
|
| 108 |
+
"If the process output is too verbose, you can disable the progress bars with `--no-bars`. "
|
| 109 |
+
"You can also entirely disable the status report with `--no-report`.\n"
|
| 110 |
+
"\n"
|
| 111 |
+
"For more details, run `hf upload-large-folder --help` or check the documentation at "
|
| 112 |
+
"https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-large-folder."
|
| 113 |
+
)
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if no_bars:
|
| 117 |
+
disable_progress_bars()
|
| 118 |
+
|
| 119 |
+
api = get_hf_api(token=token)
|
| 120 |
+
api.upload_large_folder(
|
| 121 |
+
repo_id=repo_id,
|
| 122 |
+
folder_path=local_path,
|
| 123 |
+
repo_type=repo_type.value,
|
| 124 |
+
revision=revision,
|
| 125 |
+
private=private,
|
| 126 |
+
allow_patterns=include,
|
| 127 |
+
ignore_patterns=exclude,
|
| 128 |
+
num_workers=num_workers,
|
| 129 |
+
print_report=not no_report,
|
| 130 |
+
)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/cli/webhooks.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to manage webhooks on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# list all webhooks
|
| 18 |
+
hf webhooks ls
|
| 19 |
+
|
| 20 |
+
# show details of a single webhook
|
| 21 |
+
hf webhooks info <webhook_id>
|
| 22 |
+
|
| 23 |
+
# create a new webhook
|
| 24 |
+
hf webhooks create --url https://example.com/hook --watch model:bert-base-uncased
|
| 25 |
+
|
| 26 |
+
# create a webhook watching multiple items and domains
|
| 27 |
+
hf webhooks create --url https://example.com/hook --watch org:HuggingFace --watch model:gpt2 --domain repo
|
| 28 |
+
|
| 29 |
+
# update a webhook
|
| 30 |
+
hf webhooks update <webhook_id> --url https://new-url.com/hook
|
| 31 |
+
|
| 32 |
+
# enable / disable a webhook
|
| 33 |
+
hf webhooks enable <webhook_id>
|
| 34 |
+
hf webhooks disable <webhook_id>
|
| 35 |
+
|
| 36 |
+
# delete a webhook
|
| 37 |
+
hf webhooks delete <webhook_id>
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
import enum
|
| 41 |
+
import json
|
| 42 |
+
from typing import Annotated, get_args, get_type_hints
|
| 43 |
+
|
| 44 |
+
import typer
|
| 45 |
+
|
| 46 |
+
from huggingface_hub.constants import WEBHOOK_DOMAIN_T
|
| 47 |
+
from huggingface_hub.hf_api import WebhookWatchedItem
|
| 48 |
+
|
| 49 |
+
from ._cli_utils import (
|
| 50 |
+
FormatOpt,
|
| 51 |
+
OutputFormat,
|
| 52 |
+
QuietOpt,
|
| 53 |
+
TokenOpt,
|
| 54 |
+
api_object_to_dict,
|
| 55 |
+
get_hf_api,
|
| 56 |
+
print_list_output,
|
| 57 |
+
typer_factory,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Build enums dynamically from Literal types to avoid duplication
|
| 62 |
+
_WATCHED_TYPES = get_args(get_type_hints(WebhookWatchedItem)["type"])
|
| 63 |
+
WatchedItemType = enum.Enum("WatchedItemType", {t: t for t in _WATCHED_TYPES}, type=str) # type: ignore[misc]
|
| 64 |
+
|
| 65 |
+
_DOMAIN_TYPES = get_args(WEBHOOK_DOMAIN_T)
|
| 66 |
+
WebhookDomain = enum.Enum("WebhookDomain", {d: d for d in _DOMAIN_TYPES}, type=str) # type: ignore[misc]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _parse_watch(values: list[str]) -> list[WebhookWatchedItem]:
|
| 70 |
+
"""Parse 'type:name' strings into WebhookWatchedItem objects.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
values: List of strings in the format 'type:name'
|
| 74 |
+
(e.g., 'model:bert-base-uncased', 'org:HuggingFace').
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
List of WebhookWatchedItem objects.
|
| 78 |
+
|
| 79 |
+
Raises:
|
| 80 |
+
typer.BadParameter: If any value doesn't match the expected format.
|
| 81 |
+
"""
|
| 82 |
+
items = []
|
| 83 |
+
valid_types = tuple(_WATCHED_TYPES)
|
| 84 |
+
for v in values:
|
| 85 |
+
if ":" not in v:
|
| 86 |
+
raise typer.BadParameter(
|
| 87 |
+
f"Expected format 'type:name' (e.g. 'model:bert-base-uncased'), got '{v}'."
|
| 88 |
+
f" Valid types: {', '.join(valid_types)}."
|
| 89 |
+
)
|
| 90 |
+
kind, name = v.split(":", 1)
|
| 91 |
+
if kind not in valid_types:
|
| 92 |
+
raise typer.BadParameter(f"Invalid type '{kind}'. Valid types: {', '.join(valid_types)}.")
|
| 93 |
+
items.append(WebhookWatchedItem(type=kind, name=name)) # type: ignore
|
| 94 |
+
return items
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
webhooks_cli = typer_factory(help="Manage webhooks on the Hub.")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@webhooks_cli.command(
|
| 101 |
+
"list | ls",
|
| 102 |
+
examples=[
|
| 103 |
+
"hf webhooks ls",
|
| 104 |
+
"hf webhooks ls --format json",
|
| 105 |
+
"hf webhooks ls -q",
|
| 106 |
+
],
|
| 107 |
+
)
|
| 108 |
+
def webhooks_ls(
|
| 109 |
+
format: FormatOpt = OutputFormat.table,
|
| 110 |
+
quiet: QuietOpt = False,
|
| 111 |
+
token: TokenOpt = None,
|
| 112 |
+
) -> None:
|
| 113 |
+
"""List all webhooks for the current user."""
|
| 114 |
+
api = get_hf_api(token=token)
|
| 115 |
+
results = [api_object_to_dict(w) for w in api.list_webhooks()]
|
| 116 |
+
print_list_output(
|
| 117 |
+
results,
|
| 118 |
+
format=format,
|
| 119 |
+
quiet=quiet,
|
| 120 |
+
headers=["id", "url", "disabled", "domains", "watched"],
|
| 121 |
+
row_fn=lambda item: [
|
| 122 |
+
item.get("id", ""),
|
| 123 |
+
item.get("url") or "(job)",
|
| 124 |
+
str(item.get("disabled", False)),
|
| 125 |
+
", ".join(item.get("domains") or []),
|
| 126 |
+
", ".join(
|
| 127 |
+
f"{w['type']}:{w['name']}" if isinstance(w, dict) else str(w) for w in (item.get("watched") or [])
|
| 128 |
+
),
|
| 129 |
+
],
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@webhooks_cli.command(
|
| 134 |
+
"info",
|
| 135 |
+
examples=[
|
| 136 |
+
"hf webhooks info abc123",
|
| 137 |
+
],
|
| 138 |
+
)
|
| 139 |
+
def webhooks_info(
|
| 140 |
+
webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook.")],
|
| 141 |
+
token: TokenOpt = None,
|
| 142 |
+
) -> None:
|
| 143 |
+
"""Show full details for a single webhook as JSON."""
|
| 144 |
+
api = get_hf_api(token=token)
|
| 145 |
+
webhook = api.get_webhook(webhook_id)
|
| 146 |
+
print(json.dumps(api_object_to_dict(webhook), indent=2))
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
@webhooks_cli.command(
|
| 150 |
+
"create",
|
| 151 |
+
examples=[
|
| 152 |
+
"hf webhooks create --url https://example.com/hook --watch model:bert-base-uncased",
|
| 153 |
+
"hf webhooks create --url https://example.com/hook --watch org:HuggingFace --watch model:gpt2 --domain repo",
|
| 154 |
+
"hf webhooks create --job-id 687f911eaea852de79c4a50a --watch user:julien-c",
|
| 155 |
+
],
|
| 156 |
+
)
|
| 157 |
+
def webhooks_create(
|
| 158 |
+
watch: Annotated[
|
| 159 |
+
list[str],
|
| 160 |
+
typer.Option(
|
| 161 |
+
"--watch",
|
| 162 |
+
help="Item to watch, in 'type:name' format (e.g. 'model:bert-base-uncased'). Repeatable.",
|
| 163 |
+
),
|
| 164 |
+
],
|
| 165 |
+
url: Annotated[
|
| 166 |
+
str | None,
|
| 167 |
+
typer.Option(help="URL to send webhook payloads to. Mutually exclusive with --job-id."),
|
| 168 |
+
] = None,
|
| 169 |
+
job_id: Annotated[
|
| 170 |
+
str | None,
|
| 171 |
+
typer.Option(
|
| 172 |
+
"--job-id",
|
| 173 |
+
help="ID of a Job to trigger (from job.id) instead of pinging a URL. Mutually exclusive with --url.",
|
| 174 |
+
),
|
| 175 |
+
] = None,
|
| 176 |
+
domain: Annotated[
|
| 177 |
+
list[WebhookDomain] | None,
|
| 178 |
+
typer.Option(
|
| 179 |
+
"--domain",
|
| 180 |
+
help="Domain to watch: 'repo' or 'discussions'. Repeatable. Defaults to all domains.",
|
| 181 |
+
),
|
| 182 |
+
] = None,
|
| 183 |
+
secret: Annotated[
|
| 184 |
+
str | None,
|
| 185 |
+
typer.Option(help="Optional secret used to sign webhook payloads."),
|
| 186 |
+
] = None,
|
| 187 |
+
token: TokenOpt = None,
|
| 188 |
+
) -> None:
|
| 189 |
+
"""Create a new webhook.
|
| 190 |
+
|
| 191 |
+
Provide either --url (to ping a remote server) or --job-id (to trigger a Job), but not both.
|
| 192 |
+
"""
|
| 193 |
+
if url is not None and job_id is not None:
|
| 194 |
+
raise typer.BadParameter("Provide either --url or --job-id, not both.")
|
| 195 |
+
if url is None and job_id is None:
|
| 196 |
+
raise typer.BadParameter("Provide either --url or --job-id.")
|
| 197 |
+
api = get_hf_api(token=token)
|
| 198 |
+
watched_items = _parse_watch(watch)
|
| 199 |
+
domains = [d.value for d in domain] if domain else None
|
| 200 |
+
webhook = api.create_webhook(url=url, job_id=job_id, watched=watched_items, domains=domains, secret=secret) # type: ignore
|
| 201 |
+
print(f"Webhook created: {webhook.id}")
|
| 202 |
+
print(json.dumps(api_object_to_dict(webhook), indent=2))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
@webhooks_cli.command(
|
| 206 |
+
"update",
|
| 207 |
+
examples=[
|
| 208 |
+
"hf webhooks update abc123 --url https://new-url.com/hook",
|
| 209 |
+
"hf webhooks update abc123 --watch model:gpt2 --domain repo",
|
| 210 |
+
"hf webhooks update abc123 --secret newsecret",
|
| 211 |
+
],
|
| 212 |
+
)
|
| 213 |
+
def webhooks_update(
|
| 214 |
+
webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook to update.")],
|
| 215 |
+
url: Annotated[
|
| 216 |
+
str | None,
|
| 217 |
+
typer.Option(help="New URL to send webhook payloads to."),
|
| 218 |
+
] = None,
|
| 219 |
+
watch: Annotated[
|
| 220 |
+
list[str] | None,
|
| 221 |
+
typer.Option(
|
| 222 |
+
"--watch",
|
| 223 |
+
help=(
|
| 224 |
+
"New list of items to watch, in 'type:name' format. "
|
| 225 |
+
"Repeatable. Replaces the entire existing watched list."
|
| 226 |
+
),
|
| 227 |
+
),
|
| 228 |
+
] = None,
|
| 229 |
+
domain: Annotated[
|
| 230 |
+
list[WebhookDomain] | None,
|
| 231 |
+
typer.Option(
|
| 232 |
+
"--domain",
|
| 233 |
+
help="New list of domains to watch: 'repo' or 'discussions'. Repeatable.",
|
| 234 |
+
),
|
| 235 |
+
] = None,
|
| 236 |
+
secret: Annotated[
|
| 237 |
+
str | None,
|
| 238 |
+
typer.Option(help="New secret used to sign webhook payloads."),
|
| 239 |
+
] = None,
|
| 240 |
+
token: TokenOpt = None,
|
| 241 |
+
) -> None:
|
| 242 |
+
"""Update an existing webhook. Only provided options are changed."""
|
| 243 |
+
api = get_hf_api(token=token)
|
| 244 |
+
watched_items = _parse_watch(watch) if watch else None
|
| 245 |
+
domains = [d.value for d in domain] if domain else None
|
| 246 |
+
webhook = api.update_webhook(webhook_id, url=url, watched=watched_items, domains=domains, secret=secret) # type: ignore
|
| 247 |
+
print(f"Webhook updated: {webhook.id}")
|
| 248 |
+
print(json.dumps(api_object_to_dict(webhook), indent=2))
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
@webhooks_cli.command(
|
| 252 |
+
"enable",
|
| 253 |
+
examples=[
|
| 254 |
+
"hf webhooks enable abc123",
|
| 255 |
+
],
|
| 256 |
+
)
|
| 257 |
+
def webhooks_enable(
|
| 258 |
+
webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook to enable.")],
|
| 259 |
+
token: TokenOpt = None,
|
| 260 |
+
) -> None:
|
| 261 |
+
"""Enable a disabled webhook."""
|
| 262 |
+
api = get_hf_api(token=token)
|
| 263 |
+
webhook = api.enable_webhook(webhook_id)
|
| 264 |
+
print(f"Webhook enabled: {webhook.id}")
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
@webhooks_cli.command(
|
| 268 |
+
"disable",
|
| 269 |
+
examples=[
|
| 270 |
+
"hf webhooks disable abc123",
|
| 271 |
+
],
|
| 272 |
+
)
|
| 273 |
+
def webhooks_disable(
|
| 274 |
+
webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook to disable.")],
|
| 275 |
+
token: TokenOpt = None,
|
| 276 |
+
) -> None:
|
| 277 |
+
"""Disable an active webhook."""
|
| 278 |
+
api = get_hf_api(token=token)
|
| 279 |
+
webhook = api.disable_webhook(webhook_id)
|
| 280 |
+
print(f"Webhook disabled: {webhook.id}")
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
@webhooks_cli.command(
|
| 284 |
+
"delete",
|
| 285 |
+
examples=[
|
| 286 |
+
"hf webhooks delete abc123",
|
| 287 |
+
"hf webhooks delete abc123 --yes",
|
| 288 |
+
],
|
| 289 |
+
)
|
| 290 |
+
def webhooks_delete(
|
| 291 |
+
webhook_id: Annotated[str, typer.Argument(help="The ID of the webhook to delete.")],
|
| 292 |
+
yes: Annotated[
|
| 293 |
+
bool,
|
| 294 |
+
typer.Option(
|
| 295 |
+
"--yes",
|
| 296 |
+
"-y",
|
| 297 |
+
help="Skip confirmation prompt.",
|
| 298 |
+
),
|
| 299 |
+
] = False,
|
| 300 |
+
token: TokenOpt = None,
|
| 301 |
+
) -> None:
|
| 302 |
+
"""Delete a webhook permanently."""
|
| 303 |
+
if not yes:
|
| 304 |
+
confirm = typer.confirm(f"Are you sure you want to delete webhook '{webhook_id}'?")
|
| 305 |
+
if not confirm:
|
| 306 |
+
print("Aborted.")
|
| 307 |
+
raise typer.Abort()
|
| 308 |
+
api = get_hf_api(token=token)
|
| 309 |
+
api.delete_webhook(webhook_id)
|
| 310 |
+
print(f"Webhook deleted: {webhook_id}")
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/community.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Data structures to interact with Discussions and Pull Requests on the Hub.
|
| 3 |
+
|
| 4 |
+
See [the Discussions and Pull Requests guide](https://huggingface.co/docs/hub/repositories-pull-requests-discussions)
|
| 5 |
+
for more information on Pull Requests, Discussions, and the community tab.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from typing import Literal, TypedDict
|
| 11 |
+
|
| 12 |
+
from . import constants
|
| 13 |
+
from .utils import parse_datetime
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
DiscussionStatus = Literal["open", "closed", "merged", "draft"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class Discussion:
|
| 21 |
+
"""
|
| 22 |
+
A Discussion or Pull Request on the Hub.
|
| 23 |
+
|
| 24 |
+
This dataclass is not intended to be instantiated directly.
|
| 25 |
+
|
| 26 |
+
Attributes:
|
| 27 |
+
title (`str`):
|
| 28 |
+
The title of the Discussion / Pull Request
|
| 29 |
+
status (`str`):
|
| 30 |
+
The status of the Discussion / Pull Request.
|
| 31 |
+
It must be one of:
|
| 32 |
+
* `"open"`
|
| 33 |
+
* `"closed"`
|
| 34 |
+
* `"merged"` (only for Pull Requests )
|
| 35 |
+
* `"draft"` (only for Pull Requests )
|
| 36 |
+
num (`int`):
|
| 37 |
+
The number of the Discussion / Pull Request.
|
| 38 |
+
repo_id (`str`):
|
| 39 |
+
The id (`"{namespace}/{repo_name}"`) of the repo on which
|
| 40 |
+
the Discussion / Pull Request was open.
|
| 41 |
+
repo_type (`str`):
|
| 42 |
+
The type of the repo on which the Discussion / Pull Request was open.
|
| 43 |
+
Possible values are: `"model"`, `"dataset"`, `"space"`.
|
| 44 |
+
author (`str`):
|
| 45 |
+
The username of the Discussion / Pull Request author.
|
| 46 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 47 |
+
is_pull_request (`bool`):
|
| 48 |
+
Whether or not this is a Pull Request.
|
| 49 |
+
created_at (`datetime`):
|
| 50 |
+
The `datetime` of creation of the Discussion / Pull Request.
|
| 51 |
+
endpoint (`str`):
|
| 52 |
+
Endpoint of the Hub. Default is https://huggingface.co.
|
| 53 |
+
git_reference (`str`, *optional*):
|
| 54 |
+
(property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
|
| 55 |
+
url (`str`):
|
| 56 |
+
(property) URL of the discussion on the Hub.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
title: str
|
| 60 |
+
status: DiscussionStatus
|
| 61 |
+
num: int
|
| 62 |
+
repo_id: str
|
| 63 |
+
repo_type: str
|
| 64 |
+
author: str
|
| 65 |
+
is_pull_request: bool
|
| 66 |
+
created_at: datetime
|
| 67 |
+
endpoint: str
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def git_reference(self) -> str | None:
|
| 71 |
+
"""
|
| 72 |
+
If this is a Pull Request , returns the git reference to which changes can be pushed.
|
| 73 |
+
Returns `None` otherwise.
|
| 74 |
+
"""
|
| 75 |
+
if self.is_pull_request:
|
| 76 |
+
return f"refs/pr/{self.num}"
|
| 77 |
+
return None
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def url(self) -> str:
|
| 81 |
+
"""Returns the URL of the discussion on the Hub."""
|
| 82 |
+
if self.repo_type is None or self.repo_type == constants.REPO_TYPE_MODEL:
|
| 83 |
+
return f"{self.endpoint}/{self.repo_id}/discussions/{self.num}"
|
| 84 |
+
return f"{self.endpoint}/{self.repo_type}s/{self.repo_id}/discussions/{self.num}"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@dataclass
|
| 88 |
+
class DiscussionWithDetails(Discussion):
|
| 89 |
+
"""
|
| 90 |
+
Subclass of [`Discussion`].
|
| 91 |
+
|
| 92 |
+
Attributes:
|
| 93 |
+
title (`str`):
|
| 94 |
+
The title of the Discussion / Pull Request
|
| 95 |
+
status (`str`):
|
| 96 |
+
The status of the Discussion / Pull Request.
|
| 97 |
+
It can be one of:
|
| 98 |
+
* `"open"`
|
| 99 |
+
* `"closed"`
|
| 100 |
+
* `"merged"` (only for Pull Requests )
|
| 101 |
+
* `"draft"` (only for Pull Requests )
|
| 102 |
+
num (`int`):
|
| 103 |
+
The number of the Discussion / Pull Request.
|
| 104 |
+
repo_id (`str`):
|
| 105 |
+
The id (`"{namespace}/{repo_name}"`) of the repo on which
|
| 106 |
+
the Discussion / Pull Request was open.
|
| 107 |
+
repo_type (`str`):
|
| 108 |
+
The type of the repo on which the Discussion / Pull Request was open.
|
| 109 |
+
Possible values are: `"model"`, `"dataset"`, `"space"`.
|
| 110 |
+
author (`str`):
|
| 111 |
+
The username of the Discussion / Pull Request author.
|
| 112 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 113 |
+
is_pull_request (`bool`):
|
| 114 |
+
Whether or not this is a Pull Request.
|
| 115 |
+
created_at (`datetime`):
|
| 116 |
+
The `datetime` of creation of the Discussion / Pull Request.
|
| 117 |
+
events (`list` of [`DiscussionEvent`])
|
| 118 |
+
The list of [`DiscussionEvents`] in this Discussion or Pull Request.
|
| 119 |
+
conflicting_files (`Union[list[str], bool, None]`, *optional*):
|
| 120 |
+
A list of conflicting files if this is a Pull Request.
|
| 121 |
+
`None` if `self.is_pull_request` is `False`.
|
| 122 |
+
`True` if there are conflicting files but the list can't be retrieved.
|
| 123 |
+
target_branch (`str`, *optional*):
|
| 124 |
+
The branch into which changes are to be merged if this is a
|
| 125 |
+
Pull Request . `None` if `self.is_pull_request` is `False`.
|
| 126 |
+
merge_commit_oid (`str`, *optional*):
|
| 127 |
+
If this is a merged Pull Request , this is set to the OID / SHA of
|
| 128 |
+
the merge commit, `None` otherwise.
|
| 129 |
+
diff (`str`, *optional*):
|
| 130 |
+
The git diff if this is a Pull Request , `None` otherwise.
|
| 131 |
+
endpoint (`str`):
|
| 132 |
+
Endpoint of the Hub. Default is https://huggingface.co.
|
| 133 |
+
git_reference (`str`, *optional*):
|
| 134 |
+
(property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
|
| 135 |
+
url (`str`):
|
| 136 |
+
(property) URL of the discussion on the Hub.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
events: list["DiscussionEvent"]
|
| 140 |
+
conflicting_files: list[str] | bool | None
|
| 141 |
+
target_branch: str | None
|
| 142 |
+
merge_commit_oid: str | None
|
| 143 |
+
diff: str | None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class DiscussionEventArgs(TypedDict):
|
| 147 |
+
id: str
|
| 148 |
+
type: str
|
| 149 |
+
created_at: datetime
|
| 150 |
+
author: str
|
| 151 |
+
_event: dict
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@dataclass
|
| 155 |
+
class DiscussionEvent:
|
| 156 |
+
"""
|
| 157 |
+
An event in a Discussion or Pull Request.
|
| 158 |
+
|
| 159 |
+
Use concrete classes:
|
| 160 |
+
* [`DiscussionComment`]
|
| 161 |
+
* [`DiscussionStatusChange`]
|
| 162 |
+
* [`DiscussionCommit`]
|
| 163 |
+
* [`DiscussionTitleChange`]
|
| 164 |
+
|
| 165 |
+
Attributes:
|
| 166 |
+
id (`str`):
|
| 167 |
+
The ID of the event. An hexadecimal string.
|
| 168 |
+
type (`str`):
|
| 169 |
+
The type of the event.
|
| 170 |
+
created_at (`datetime`):
|
| 171 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 172 |
+
object holding the creation timestamp for the event.
|
| 173 |
+
author (`str`):
|
| 174 |
+
The username of the Discussion / Pull Request author.
|
| 175 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
id: str
|
| 179 |
+
type: str
|
| 180 |
+
created_at: datetime
|
| 181 |
+
author: str
|
| 182 |
+
|
| 183 |
+
_event: dict
|
| 184 |
+
"""Stores the original event data, in case we need to access it later."""
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@dataclass
|
| 188 |
+
class DiscussionComment(DiscussionEvent):
|
| 189 |
+
"""A comment in a Discussion / Pull Request.
|
| 190 |
+
|
| 191 |
+
Subclass of [`DiscussionEvent`].
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
Attributes:
|
| 195 |
+
id (`str`):
|
| 196 |
+
The ID of the event. An hexadecimal string.
|
| 197 |
+
type (`str`):
|
| 198 |
+
The type of the event.
|
| 199 |
+
created_at (`datetime`):
|
| 200 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 201 |
+
object holding the creation timestamp for the event.
|
| 202 |
+
author (`str`):
|
| 203 |
+
The username of the Discussion / Pull Request author.
|
| 204 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 205 |
+
content (`str`):
|
| 206 |
+
The raw markdown content of the comment. Mentions, links and images are not rendered.
|
| 207 |
+
edited (`bool`):
|
| 208 |
+
Whether or not this comment has been edited.
|
| 209 |
+
hidden (`bool`):
|
| 210 |
+
Whether or not this comment has been hidden.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
content: str
|
| 214 |
+
edited: bool
|
| 215 |
+
hidden: bool
|
| 216 |
+
|
| 217 |
+
@property
|
| 218 |
+
def rendered(self) -> str:
|
| 219 |
+
"""The rendered comment, as a HTML string"""
|
| 220 |
+
return self._event["data"]["latest"]["html"]
|
| 221 |
+
|
| 222 |
+
@property
|
| 223 |
+
def last_edited_at(self) -> datetime:
|
| 224 |
+
"""The last edit time, as a `datetime` object."""
|
| 225 |
+
return parse_datetime(self._event["data"]["latest"]["updatedAt"])
|
| 226 |
+
|
| 227 |
+
@property
|
| 228 |
+
def last_edited_by(self) -> str:
|
| 229 |
+
"""The last edit time, as a `datetime` object."""
|
| 230 |
+
return self._event["data"]["latest"].get("author", {}).get("name", "deleted")
|
| 231 |
+
|
| 232 |
+
@property
|
| 233 |
+
def edit_history(self) -> list[dict]:
|
| 234 |
+
"""The edit history of the comment"""
|
| 235 |
+
return self._event["data"]["history"]
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def number_of_edits(self) -> int:
|
| 239 |
+
return len(self.edit_history)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@dataclass
|
| 243 |
+
class DiscussionStatusChange(DiscussionEvent):
|
| 244 |
+
"""A change of status in a Discussion / Pull Request.
|
| 245 |
+
|
| 246 |
+
Subclass of [`DiscussionEvent`].
|
| 247 |
+
|
| 248 |
+
Attributes:
|
| 249 |
+
id (`str`):
|
| 250 |
+
The ID of the event. An hexadecimal string.
|
| 251 |
+
type (`str`):
|
| 252 |
+
The type of the event.
|
| 253 |
+
created_at (`datetime`):
|
| 254 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 255 |
+
object holding the creation timestamp for the event.
|
| 256 |
+
author (`str`):
|
| 257 |
+
The username of the Discussion / Pull Request author.
|
| 258 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 259 |
+
new_status (`str`):
|
| 260 |
+
The status of the Discussion / Pull Request after the change.
|
| 261 |
+
It can be one of:
|
| 262 |
+
* `"open"`
|
| 263 |
+
* `"closed"`
|
| 264 |
+
* `"merged"` (only for Pull Requests )
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
new_status: str
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@dataclass
|
| 271 |
+
class DiscussionCommit(DiscussionEvent):
|
| 272 |
+
"""A commit in a Pull Request.
|
| 273 |
+
|
| 274 |
+
Subclass of [`DiscussionEvent`].
|
| 275 |
+
|
| 276 |
+
Attributes:
|
| 277 |
+
id (`str`):
|
| 278 |
+
The ID of the event. An hexadecimal string.
|
| 279 |
+
type (`str`):
|
| 280 |
+
The type of the event.
|
| 281 |
+
created_at (`datetime`):
|
| 282 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 283 |
+
object holding the creation timestamp for the event.
|
| 284 |
+
author (`str`):
|
| 285 |
+
The username of the Discussion / Pull Request author.
|
| 286 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 287 |
+
summary (`str`):
|
| 288 |
+
The summary of the commit.
|
| 289 |
+
oid (`str`):
|
| 290 |
+
The OID / SHA of the commit, as a hexadecimal string.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
summary: str
|
| 294 |
+
oid: str
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@dataclass
|
| 298 |
+
class DiscussionTitleChange(DiscussionEvent):
|
| 299 |
+
"""A rename event in a Discussion / Pull Request.
|
| 300 |
+
|
| 301 |
+
Subclass of [`DiscussionEvent`].
|
| 302 |
+
|
| 303 |
+
Attributes:
|
| 304 |
+
id (`str`):
|
| 305 |
+
The ID of the event. An hexadecimal string.
|
| 306 |
+
type (`str`):
|
| 307 |
+
The type of the event.
|
| 308 |
+
created_at (`datetime`):
|
| 309 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 310 |
+
object holding the creation timestamp for the event.
|
| 311 |
+
author (`str`):
|
| 312 |
+
The username of the Discussion / Pull Request author.
|
| 313 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 314 |
+
old_title (`str`):
|
| 315 |
+
The previous title for the Discussion / Pull Request.
|
| 316 |
+
new_title (`str`):
|
| 317 |
+
The new title.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
old_title: str
|
| 321 |
+
new_title: str
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def deserialize_event(event: dict) -> DiscussionEvent:
|
| 325 |
+
"""Instantiates a [`DiscussionEvent`] from a dict"""
|
| 326 |
+
event_id: str = event["id"]
|
| 327 |
+
event_type: str = event["type"]
|
| 328 |
+
created_at = parse_datetime(event["createdAt"])
|
| 329 |
+
|
| 330 |
+
common_args: DiscussionEventArgs = {
|
| 331 |
+
"id": event_id,
|
| 332 |
+
"type": event_type,
|
| 333 |
+
"created_at": created_at,
|
| 334 |
+
"author": event.get("author", {}).get("name", "deleted"),
|
| 335 |
+
"_event": event,
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
if event_type == "comment":
|
| 339 |
+
return DiscussionComment(
|
| 340 |
+
**common_args,
|
| 341 |
+
edited=event["data"]["edited"],
|
| 342 |
+
hidden=event["data"]["hidden"],
|
| 343 |
+
content=event["data"]["latest"]["raw"],
|
| 344 |
+
)
|
| 345 |
+
if event_type == "status-change":
|
| 346 |
+
return DiscussionStatusChange(
|
| 347 |
+
**common_args,
|
| 348 |
+
new_status=event["data"]["status"],
|
| 349 |
+
)
|
| 350 |
+
if event_type == "commit":
|
| 351 |
+
return DiscussionCommit(
|
| 352 |
+
**common_args,
|
| 353 |
+
summary=event["data"]["subject"],
|
| 354 |
+
oid=event["data"]["oid"],
|
| 355 |
+
)
|
| 356 |
+
if event_type == "title-change":
|
| 357 |
+
return DiscussionTitleChange(
|
| 358 |
+
**common_args,
|
| 359 |
+
old_title=event["data"]["from"],
|
| 360 |
+
new_title=event["data"]["to"],
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
return DiscussionEvent(**common_args)
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/constants.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 10 |
+
ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
|
| 11 |
+
ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _is_true(value: str | None) -> bool:
|
| 15 |
+
if value is None:
|
| 16 |
+
return False
|
| 17 |
+
return value.upper() in ENV_VARS_TRUE_VALUES
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _as_int(value: str | None) -> int | None:
|
| 21 |
+
if value is None:
|
| 22 |
+
return None
|
| 23 |
+
return int(value)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Constants for file downloads
|
| 27 |
+
|
| 28 |
+
PYTORCH_WEIGHTS_NAME = "pytorch_model.bin"
|
| 29 |
+
TF2_WEIGHTS_NAME = "tf_model.h5"
|
| 30 |
+
TF_WEIGHTS_NAME = "model.ckpt"
|
| 31 |
+
FLAX_WEIGHTS_NAME = "flax_model.msgpack"
|
| 32 |
+
CONFIG_NAME = "config.json"
|
| 33 |
+
REPOCARD_NAME = "README.md"
|
| 34 |
+
EVAL_RESULTS_FOLDER = ".eval_results"
|
| 35 |
+
DEFAULT_ETAG_TIMEOUT = 10
|
| 36 |
+
DEFAULT_DOWNLOAD_TIMEOUT = 10
|
| 37 |
+
DEFAULT_REQUEST_TIMEOUT = 10
|
| 38 |
+
DOWNLOAD_CHUNK_SIZE = 10 * 1024 * 1024
|
| 39 |
+
MAX_HTTP_DOWNLOAD_SIZE = 50 * 1000 * 1000 * 1000 # 50 GB
|
| 40 |
+
|
| 41 |
+
# Constants for serialization
|
| 42 |
+
|
| 43 |
+
PYTORCH_WEIGHTS_FILE_PATTERN = "pytorch_model{suffix}.bin" # Unsafe pickle: use safetensors instead
|
| 44 |
+
SAFETENSORS_WEIGHTS_FILE_PATTERN = "model{suffix}.safetensors"
|
| 45 |
+
TF2_WEIGHTS_FILE_PATTERN = "tf_model{suffix}.h5"
|
| 46 |
+
|
| 47 |
+
# Constants for safetensors repos
|
| 48 |
+
|
| 49 |
+
SAFETENSORS_SINGLE_FILE = "model.safetensors"
|
| 50 |
+
SAFETENSORS_INDEX_FILE = "model.safetensors.index.json"
|
| 51 |
+
SAFETENSORS_MAX_HEADER_LENGTH = 25_000_000
|
| 52 |
+
|
| 53 |
+
# Timeout of aquiring file lock and logging the attempt
|
| 54 |
+
FILELOCK_LOG_EVERY_SECONDS = 10
|
| 55 |
+
|
| 56 |
+
# Git-related constants
|
| 57 |
+
|
| 58 |
+
DEFAULT_REVISION = "main"
|
| 59 |
+
REGEX_COMMIT_OID = re.compile(r"[A-Fa-f0-9]{5,40}")
|
| 60 |
+
|
| 61 |
+
HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/"
|
| 62 |
+
|
| 63 |
+
_staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING"))
|
| 64 |
+
|
| 65 |
+
_HF_DEFAULT_ENDPOINT = "https://huggingface.co"
|
| 66 |
+
_HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co"
|
| 67 |
+
ENDPOINT = os.getenv("HF_ENDPOINT", _HF_DEFAULT_ENDPOINT).rstrip("/")
|
| 68 |
+
HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
|
| 69 |
+
|
| 70 |
+
if _staging_mode:
|
| 71 |
+
ENDPOINT = _HF_DEFAULT_STAGING_ENDPOINT
|
| 72 |
+
HUGGINGFACE_CO_URL_TEMPLATE = _HF_DEFAULT_STAGING_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
|
| 73 |
+
|
| 74 |
+
DATASETS_SERVER_ENDPOINT = "https://datasets-server.huggingface.co"
|
| 75 |
+
|
| 76 |
+
HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit"
|
| 77 |
+
HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag"
|
| 78 |
+
HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size"
|
| 79 |
+
HUGGINGFACE_HEADER_X_BILL_TO = "X-HF-Bill-To"
|
| 80 |
+
|
| 81 |
+
INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-inference.huggingface.co")
|
| 82 |
+
|
| 83 |
+
# See https://huggingface.co/docs/inference-endpoints/index
|
| 84 |
+
INFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2"
|
| 85 |
+
INFERENCE_CATALOG_ENDPOINT = "https://endpoints.huggingface.co/api/catalog"
|
| 86 |
+
|
| 87 |
+
# See https://api.endpoints.huggingface.cloud/#post-/v2/endpoint/-namespace-
|
| 88 |
+
INFERENCE_ENDPOINT_IMAGE_KEYS = [
|
| 89 |
+
"custom",
|
| 90 |
+
"huggingface",
|
| 91 |
+
"huggingfaceNeuron",
|
| 92 |
+
"llamacpp",
|
| 93 |
+
"tei",
|
| 94 |
+
"tgi",
|
| 95 |
+
"tgiNeuron",
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
# Proxy for third-party providers
|
| 99 |
+
INFERENCE_PROXY_TEMPLATE = "https://router.huggingface.co/{provider}"
|
| 100 |
+
|
| 101 |
+
REPO_ID_SEPARATOR = "--"
|
| 102 |
+
# ^ this substring is not allowed in repo_ids on hf.co
|
| 103 |
+
# and is the canonical one we use for serialization of repo ids elsewhere.
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
REPO_TYPE_DATASET = "dataset"
|
| 107 |
+
REPO_TYPE_SPACE = "space"
|
| 108 |
+
REPO_TYPE_MODEL = "model"
|
| 109 |
+
REPO_TYPE_KERNEL = "kernel"
|
| 110 |
+
REPO_TYPES = [None, REPO_TYPE_MODEL, REPO_TYPE_DATASET, REPO_TYPE_SPACE]
|
| 111 |
+
REPO_TYPES_WITH_KERNEL = REPO_TYPES + [REPO_TYPE_KERNEL]
|
| 112 |
+
SPACES_SDK_TYPES = ["gradio", "streamlit", "docker", "static"]
|
| 113 |
+
|
| 114 |
+
REPO_TYPES_URL_PREFIXES = {
|
| 115 |
+
REPO_TYPE_DATASET: "datasets/",
|
| 116 |
+
REPO_TYPE_SPACE: "spaces/",
|
| 117 |
+
REPO_TYPE_KERNEL: "kernels/",
|
| 118 |
+
}
|
| 119 |
+
REPO_TYPES_MAPPING = {
|
| 120 |
+
"datasets": REPO_TYPE_DATASET,
|
| 121 |
+
"spaces": REPO_TYPE_SPACE,
|
| 122 |
+
"models": REPO_TYPE_MODEL,
|
| 123 |
+
"kernels": REPO_TYPE_KERNEL,
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
DiscussionTypeFilter = Literal["all", "discussion", "pull_request"]
|
| 128 |
+
DISCUSSION_TYPES: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionTypeFilter)
|
| 129 |
+
DiscussionStatusFilter = Literal["all", "open", "closed"]
|
| 130 |
+
DISCUSSION_STATUS: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionStatusFilter)
|
| 131 |
+
|
| 132 |
+
# Webhook subscription types
|
| 133 |
+
WEBHOOK_DOMAIN_T = Literal["repo", "discussions"]
|
| 134 |
+
|
| 135 |
+
# default cache
|
| 136 |
+
default_home = os.path.join(os.path.expanduser("~"), ".cache")
|
| 137 |
+
HF_HOME = os.path.expandvars(
|
| 138 |
+
os.path.expanduser(
|
| 139 |
+
os.getenv(
|
| 140 |
+
"HF_HOME",
|
| 141 |
+
os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "huggingface"),
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
default_cache_path = os.path.join(HF_HOME, "hub")
|
| 147 |
+
default_assets_cache_path = os.path.join(HF_HOME, "assets")
|
| 148 |
+
|
| 149 |
+
# Legacy env variables
|
| 150 |
+
HUGGINGFACE_HUB_CACHE = os.getenv("HUGGINGFACE_HUB_CACHE", default_cache_path)
|
| 151 |
+
HUGGINGFACE_ASSETS_CACHE = os.getenv("HUGGINGFACE_ASSETS_CACHE", default_assets_cache_path)
|
| 152 |
+
|
| 153 |
+
# New env variables
|
| 154 |
+
HF_HUB_CACHE = os.path.expandvars(
|
| 155 |
+
os.path.expanduser(
|
| 156 |
+
os.getenv(
|
| 157 |
+
"HF_HUB_CACHE",
|
| 158 |
+
HUGGINGFACE_HUB_CACHE,
|
| 159 |
+
)
|
| 160 |
+
)
|
| 161 |
+
)
|
| 162 |
+
HF_ASSETS_CACHE = os.path.expandvars(
|
| 163 |
+
os.path.expanduser(
|
| 164 |
+
os.getenv(
|
| 165 |
+
"HF_ASSETS_CACHE",
|
| 166 |
+
HUGGINGFACE_ASSETS_CACHE,
|
| 167 |
+
)
|
| 168 |
+
)
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
HF_HUB_OFFLINE = _is_true(os.environ.get("HF_HUB_OFFLINE") or os.environ.get("TRANSFORMERS_OFFLINE"))
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def is_offline_mode() -> bool:
|
| 175 |
+
"""Returns whether we are in offline mode for the Hub.
|
| 176 |
+
|
| 177 |
+
When offline mode is enabled, all HTTP requests made with `get_session` will raise an `OfflineModeIsEnabled` exception.
|
| 178 |
+
|
| 179 |
+
Example:
|
| 180 |
+
```py
|
| 181 |
+
from huggingface_hub import is_offline_mode
|
| 182 |
+
|
| 183 |
+
def list_files(repo_id: str):
|
| 184 |
+
if is_offline_mode():
|
| 185 |
+
... # list files from local cache (degraded experience but still functional)
|
| 186 |
+
else:
|
| 187 |
+
... # list files from Hub (complete experience)
|
| 188 |
+
```
|
| 189 |
+
"""
|
| 190 |
+
return HF_HUB_OFFLINE
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# File created to mark that the version check has been done.
|
| 194 |
+
# Check is performed once per 24 hours at most.
|
| 195 |
+
CHECK_FOR_UPDATE_DONE_PATH = os.path.join(HF_HOME, ".check_for_update_done")
|
| 196 |
+
|
| 197 |
+
# If set, log level will be set to DEBUG and all requests made to the Hub will be logged
|
| 198 |
+
# as curl commands for reproducibility.
|
| 199 |
+
HF_DEBUG = _is_true(os.environ.get("HF_DEBUG"))
|
| 200 |
+
|
| 201 |
+
# Opt-out from telemetry requests
|
| 202 |
+
HF_HUB_DISABLE_TELEMETRY = (
|
| 203 |
+
_is_true(os.environ.get("HF_HUB_DISABLE_TELEMETRY")) # HF-specific env variable
|
| 204 |
+
or _is_true(os.environ.get("DISABLE_TELEMETRY"))
|
| 205 |
+
or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
HF_TOKEN_PATH = os.path.expandvars(
|
| 209 |
+
os.path.expanduser(
|
| 210 |
+
os.getenv(
|
| 211 |
+
"HF_TOKEN_PATH",
|
| 212 |
+
os.path.join(HF_HOME, "token"),
|
| 213 |
+
)
|
| 214 |
+
)
|
| 215 |
+
)
|
| 216 |
+
HF_STORED_TOKENS_PATH = os.path.join(os.path.dirname(HF_TOKEN_PATH), "stored_tokens")
|
| 217 |
+
|
| 218 |
+
if _staging_mode:
|
| 219 |
+
# In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens
|
| 220 |
+
# In practice in `huggingface_hub` tests, we monkeypatch these values with temporary directories. The following
|
| 221 |
+
# lines are only used in third-party libraries tests (e.g. `transformers`, `diffusers`, etc.).
|
| 222 |
+
_staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging")
|
| 223 |
+
HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub")
|
| 224 |
+
HF_TOKEN_PATH = os.path.join(_staging_home, "token")
|
| 225 |
+
|
| 226 |
+
# Here, `True` will disable progress bars globally without possibility of enabling it
|
| 227 |
+
# programmatically. `False` will enable them without possibility of disabling them.
|
| 228 |
+
# If environment variable is not set (None), then the user is free to enable/disable
|
| 229 |
+
# them programmatically.
|
| 230 |
+
# TL;DR: env variable has priority over code
|
| 231 |
+
__HF_HUB_DISABLE_PROGRESS_BARS = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")
|
| 232 |
+
HF_HUB_DISABLE_PROGRESS_BARS: bool | None = (
|
| 233 |
+
_is_true(__HF_HUB_DISABLE_PROGRESS_BARS) if __HF_HUB_DISABLE_PROGRESS_BARS is not None else None
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# Disable symlinks in the cache (files are copied instead of symlinked)
|
| 237 |
+
HF_HUB_DISABLE_SYMLINKS: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS"))
|
| 238 |
+
|
| 239 |
+
# Disable warning on machines that do not support symlinks (e.g. Windows non-developer)
|
| 240 |
+
HF_HUB_DISABLE_SYMLINKS_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS_WARNING"))
|
| 241 |
+
|
| 242 |
+
# Disable warning when using experimental features
|
| 243 |
+
HF_HUB_DISABLE_EXPERIMENTAL_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_EXPERIMENTAL_WARNING"))
|
| 244 |
+
|
| 245 |
+
# Disable sending the cached token by default is all HTTP requests to the Hub
|
| 246 |
+
HF_HUB_DISABLE_IMPLICIT_TOKEN: bool = _is_true(os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN"))
|
| 247 |
+
|
| 248 |
+
HF_XET_HIGH_PERFORMANCE: bool = _is_true(os.environ.get("HF_XET_HIGH_PERFORMANCE"))
|
| 249 |
+
|
| 250 |
+
# hf_transfer is not used anymore. Let's warn user is case they set the env variable
|
| 251 |
+
if _is_true(os.environ.get("HF_HUB_ENABLE_HF_TRANSFER")) and not HF_XET_HIGH_PERFORMANCE:
|
| 252 |
+
import warnings
|
| 253 |
+
|
| 254 |
+
warnings.warn(
|
| 255 |
+
"The `HF_HUB_ENABLE_HF_TRANSFER` environment variable is deprecated as 'hf_transfer' is not used anymore. "
|
| 256 |
+
"Please use `HF_XET_HIGH_PERFORMANCE` instead to enable high performance transfer with Xet. "
|
| 257 |
+
"Visit https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfxethighperformance for more details.",
|
| 258 |
+
DeprecationWarning,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
# Used to override the etag timeout on a system level
|
| 262 |
+
HF_HUB_ETAG_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_ETAG_TIMEOUT")) or DEFAULT_ETAG_TIMEOUT
|
| 263 |
+
|
| 264 |
+
# Used to override the get request timeout on a system level
|
| 265 |
+
# Also used as a default timeout for other requests if not specified (kept the naming for legacy reasons)
|
| 266 |
+
HF_HUB_DOWNLOAD_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_DOWNLOAD_TIMEOUT")) or DEFAULT_DOWNLOAD_TIMEOUT
|
| 267 |
+
|
| 268 |
+
# Allows to add information about the requester in the user-agent (e.g. partner name)
|
| 269 |
+
HF_HUB_USER_AGENT_ORIGIN: str | None = os.environ.get("HF_HUB_USER_AGENT_ORIGIN")
|
| 270 |
+
|
| 271 |
+
# If OAuth didn't work after 2 redirects, there's likely a third-party cookie issue in the Space iframe view.
|
| 272 |
+
# In this case, we redirect the user to the non-iframe view.
|
| 273 |
+
OAUTH_MAX_REDIRECTS = 2
|
| 274 |
+
|
| 275 |
+
# OAuth-related environment variables injected by the Space
|
| 276 |
+
OAUTH_CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")
|
| 277 |
+
OAUTH_CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET")
|
| 278 |
+
OAUTH_SCOPES = os.environ.get("OAUTH_SCOPES")
|
| 279 |
+
OPENID_PROVIDER_URL = os.environ.get("OPENID_PROVIDER_URL")
|
| 280 |
+
|
| 281 |
+
# Xet constants
|
| 282 |
+
HUGGINGFACE_HEADER_X_XET_ENDPOINT = "X-Xet-Cas-Url"
|
| 283 |
+
HUGGINGFACE_HEADER_X_XET_ACCESS_TOKEN = "X-Xet-Access-Token"
|
| 284 |
+
HUGGINGFACE_HEADER_X_XET_EXPIRATION = "X-Xet-Token-Expiration"
|
| 285 |
+
HUGGINGFACE_HEADER_X_XET_HASH = "X-Xet-Hash"
|
| 286 |
+
HUGGINGFACE_HEADER_X_XET_REFRESH_ROUTE = "X-Xet-Refresh-Route"
|
| 287 |
+
HUGGINGFACE_HEADER_LINK_XET_AUTH_KEY = "xet-auth"
|
| 288 |
+
|
| 289 |
+
default_xet_cache_path = os.path.join(HF_HOME, "xet")
|
| 290 |
+
HF_XET_CACHE = os.getenv("HF_XET_CACHE", default_xet_cache_path)
|
| 291 |
+
HF_HUB_DISABLE_XET: bool = _is_true(os.environ.get("HF_HUB_DISABLE_XET"))
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/dataclasses.py
ADDED
|
@@ -0,0 +1,684 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections.abc
|
| 2 |
+
import inspect
|
| 3 |
+
import types
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from dataclasses import _MISSING_TYPE, MISSING, Field, field, fields, make_dataclass
|
| 6 |
+
from functools import lru_cache, wraps
|
| 7 |
+
from typing import (
|
| 8 |
+
Annotated,
|
| 9 |
+
Any,
|
| 10 |
+
ForwardRef,
|
| 11 |
+
Literal,
|
| 12 |
+
Type,
|
| 13 |
+
TypeVar,
|
| 14 |
+
Union,
|
| 15 |
+
get_args,
|
| 16 |
+
get_origin,
|
| 17 |
+
overload,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
# Python 3.11+
|
| 23 |
+
from typing import NotRequired, Required # type: ignore
|
| 24 |
+
except ImportError:
|
| 25 |
+
try:
|
| 26 |
+
# In case typing_extensions is installed
|
| 27 |
+
from typing_extensions import NotRequired, Required # type: ignore
|
| 28 |
+
except ImportError:
|
| 29 |
+
# Fallback: create dummy types that will never match
|
| 30 |
+
Required = type("Required", (), {}) # type: ignore
|
| 31 |
+
NotRequired = type("NotRequired", (), {}) # type: ignore
|
| 32 |
+
|
| 33 |
+
from .errors import (
|
| 34 |
+
StrictDataclassClassValidationError,
|
| 35 |
+
StrictDataclassDefinitionError,
|
| 36 |
+
StrictDataclassFieldValidationError,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Validator_T = Callable[[Any], None]
|
| 41 |
+
T = TypeVar("T")
|
| 42 |
+
TypedDictType = TypeVar("TypedDictType", bound=dict[str, Any])
|
| 43 |
+
|
| 44 |
+
_TYPED_DICT_DEFAULT_VALUE = object() # used as default value in TypedDict fields (to distinguish from None)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# The overload decorator helps type checkers understand the different return types
|
| 48 |
+
@overload
|
| 49 |
+
def strict(cls: Type[T]) -> Type[T]: ...
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@overload
|
| 53 |
+
def strict(*, accept_kwargs: bool = False) -> Callable[[Type[T]], Type[T]]: ...
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def strict(cls: Type[T] | None = None, *, accept_kwargs: bool = False) -> Type[T] | Callable[[Type[T]], Type[T]]:
|
| 57 |
+
"""
|
| 58 |
+
Decorator to add strict validation to a dataclass.
|
| 59 |
+
|
| 60 |
+
This decorator must be used on top of `@dataclass` to ensure IDEs and static typing tools
|
| 61 |
+
recognize the class as a dataclass.
|
| 62 |
+
|
| 63 |
+
Can be used with or without arguments:
|
| 64 |
+
- `@strict`
|
| 65 |
+
- `@strict(accept_kwargs=True)`
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
cls:
|
| 69 |
+
The class to convert to a strict dataclass.
|
| 70 |
+
accept_kwargs (`bool`, *optional*):
|
| 71 |
+
If True, allows arbitrary keyword arguments in `__init__`. Defaults to False.
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
The enhanced dataclass with strict validation on field assignment.
|
| 75 |
+
|
| 76 |
+
Example:
|
| 77 |
+
```py
|
| 78 |
+
>>> from dataclasses import dataclass
|
| 79 |
+
>>> from huggingface_hub.dataclasses import as_validated_field, strict, validated_field
|
| 80 |
+
|
| 81 |
+
>>> @as_validated_field
|
| 82 |
+
>>> def positive_int(value: int):
|
| 83 |
+
... if not value >= 0:
|
| 84 |
+
... raise ValueError(f"Value must be positive, got {value}")
|
| 85 |
+
|
| 86 |
+
>>> @strict(accept_kwargs=True)
|
| 87 |
+
... @dataclass
|
| 88 |
+
... class User:
|
| 89 |
+
... name: str
|
| 90 |
+
... age: int = positive_int(default=10)
|
| 91 |
+
|
| 92 |
+
# Initialize
|
| 93 |
+
>>> User(name="John")
|
| 94 |
+
User(name='John', age=10)
|
| 95 |
+
|
| 96 |
+
# Extra kwargs are accepted
|
| 97 |
+
>>> User(name="John", age=30, lastname="Doe")
|
| 98 |
+
User(name='John', age=30, *lastname='Doe')
|
| 99 |
+
|
| 100 |
+
# Invalid type => raises
|
| 101 |
+
>>> User(name="John", age="30")
|
| 102 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 103 |
+
TypeError: Field 'age' expected int, got str (value: '30')
|
| 104 |
+
|
| 105 |
+
# Invalid value => raises
|
| 106 |
+
>>> User(name="John", age=-1)
|
| 107 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 108 |
+
ValueError: Value must be positive, got -1
|
| 109 |
+
```
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def wrap(cls: Type[T]) -> Type[T]:
|
| 113 |
+
if not hasattr(cls, "__dataclass_fields__"):
|
| 114 |
+
raise StrictDataclassDefinitionError(
|
| 115 |
+
f"Class '{cls.__name__}' must be a dataclass before applying @strict."
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# List and store validators
|
| 119 |
+
field_validators: dict[str, list[Validator_T]] = {}
|
| 120 |
+
for f in fields(cls): # type: ignore [arg-type]
|
| 121 |
+
validators = []
|
| 122 |
+
validators.append(_create_type_validator(f))
|
| 123 |
+
custom_validator = f.metadata.get("validator")
|
| 124 |
+
if custom_validator is not None:
|
| 125 |
+
if not isinstance(custom_validator, list):
|
| 126 |
+
custom_validator = [custom_validator]
|
| 127 |
+
for validator in custom_validator:
|
| 128 |
+
if not _is_validator(validator):
|
| 129 |
+
raise StrictDataclassDefinitionError(
|
| 130 |
+
f"Invalid validator for field '{f.name}': {validator}. Must be a callable taking a single argument."
|
| 131 |
+
)
|
| 132 |
+
validators.extend(custom_validator)
|
| 133 |
+
field_validators[f.name] = validators
|
| 134 |
+
cls.__validators__ = field_validators # type: ignore
|
| 135 |
+
|
| 136 |
+
# Override __setattr__ to validate fields on assignment
|
| 137 |
+
original_setattr = cls.__setattr__
|
| 138 |
+
|
| 139 |
+
def __strict_setattr__(self: Any, name: str, value: Any) -> None:
|
| 140 |
+
"""Custom __setattr__ method for strict dataclasses."""
|
| 141 |
+
# Run all validators
|
| 142 |
+
for validator in self.__validators__.get(name, []):
|
| 143 |
+
try:
|
| 144 |
+
validator(value)
|
| 145 |
+
except (ValueError, TypeError) as e:
|
| 146 |
+
raise StrictDataclassFieldValidationError(field=name, cause=e) from e
|
| 147 |
+
|
| 148 |
+
# If validation passed, set the attribute
|
| 149 |
+
original_setattr(self, name, value)
|
| 150 |
+
|
| 151 |
+
cls.__setattr__ = __strict_setattr__ # type: ignore
|
| 152 |
+
|
| 153 |
+
if accept_kwargs:
|
| 154 |
+
# (optional) Override __init__ to accept arbitrary keyword arguments
|
| 155 |
+
original_init = cls.__init__
|
| 156 |
+
|
| 157 |
+
@wraps(original_init)
|
| 158 |
+
def __init__(self, *args, **kwargs: Any) -> None:
|
| 159 |
+
# Extract only the fields that are part of the dataclass
|
| 160 |
+
dataclass_fields = {f.name for f in fields(cls)} # type: ignore [arg-type]
|
| 161 |
+
standard_kwargs = {k: v for k, v in kwargs.items() if k in dataclass_fields}
|
| 162 |
+
|
| 163 |
+
# User shouldn't define custom `__init__` when `accepts_kwargs`, and instead
|
| 164 |
+
# are advised to move field manipulation to `__post_init__` (e.g., derive new field from existing ones)
|
| 165 |
+
# We need to call bare `__init__` here without `__post_init__` but the``original_init`` would call
|
| 166 |
+
# post-init right away with no kwargs.
|
| 167 |
+
if len(args) > 0:
|
| 168 |
+
raise ValueError(
|
| 169 |
+
f"When `accept_kwargs=True`, {cls.__name__} accepts only keyword arguments, "
|
| 170 |
+
f"but found `{len(args)}` positional args."
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
for f in fields(cls): # type: ignore
|
| 174 |
+
if f.name in standard_kwargs:
|
| 175 |
+
setattr(self, f.name, standard_kwargs[f.name])
|
| 176 |
+
elif f.default is not MISSING:
|
| 177 |
+
setattr(self, f.name, f.default)
|
| 178 |
+
elif f.default_factory is not MISSING:
|
| 179 |
+
setattr(self, f.name, f.default_factory())
|
| 180 |
+
else:
|
| 181 |
+
raise TypeError(f"Missing required field - '{f.name}'")
|
| 182 |
+
|
| 183 |
+
# Pass any additional kwargs to `__post_init__` and let the object
|
| 184 |
+
# decide whether to set the attr or use for different purposes (e.g. BC checks)
|
| 185 |
+
additional_kwargs = {}
|
| 186 |
+
for name, value in kwargs.items():
|
| 187 |
+
if name not in dataclass_fields:
|
| 188 |
+
additional_kwargs[name] = value
|
| 189 |
+
|
| 190 |
+
self.__post_init__(**additional_kwargs)
|
| 191 |
+
|
| 192 |
+
cls.__init__ = __init__ # type: ignore
|
| 193 |
+
|
| 194 |
+
# Define a default __post_init__ if not defined
|
| 195 |
+
if not hasattr(cls, "__post_init__"):
|
| 196 |
+
|
| 197 |
+
def __post_init__(self, **kwargs: Any) -> None:
|
| 198 |
+
"""Default __post_init__ to accept additional kwargs."""
|
| 199 |
+
for name, value in kwargs.items():
|
| 200 |
+
setattr(self, name, value)
|
| 201 |
+
|
| 202 |
+
cls.__post_init__ = __post_init__ # type: ignore
|
| 203 |
+
|
| 204 |
+
# (optional) Override __repr__ to include additional kwargs
|
| 205 |
+
original_repr = cls.__repr__
|
| 206 |
+
|
| 207 |
+
@wraps(original_repr)
|
| 208 |
+
def __repr__(self) -> str:
|
| 209 |
+
# Call the original __repr__ to get the standard fields
|
| 210 |
+
standard_repr = original_repr(self)
|
| 211 |
+
|
| 212 |
+
# Get additional kwargs
|
| 213 |
+
additional_kwargs = [
|
| 214 |
+
# add a '*' in front of additional kwargs to let the user know they are not part of the dataclass
|
| 215 |
+
f"*{k}={v!r}"
|
| 216 |
+
for k, v in self.__dict__.items()
|
| 217 |
+
if k not in cls.__dataclass_fields__ # type: ignore [attr-defined]
|
| 218 |
+
]
|
| 219 |
+
additional_repr = ", ".join(additional_kwargs)
|
| 220 |
+
|
| 221 |
+
# Combine both representations
|
| 222 |
+
return f"{standard_repr[:-1]}, {additional_repr})" if additional_kwargs else standard_repr
|
| 223 |
+
|
| 224 |
+
if cls.__dataclass_params__.repr is True: # type: ignore [attr-defined]
|
| 225 |
+
cls.__repr__ = __repr__ # type: ignore
|
| 226 |
+
|
| 227 |
+
# List all public methods starting with `validate_` => class validators.
|
| 228 |
+
class_validators = []
|
| 229 |
+
|
| 230 |
+
for name in dir(cls):
|
| 231 |
+
if not name.startswith("validate_"):
|
| 232 |
+
continue
|
| 233 |
+
method = getattr(cls, name)
|
| 234 |
+
if not callable(method):
|
| 235 |
+
continue
|
| 236 |
+
if len(inspect.signature(method).parameters) != 1:
|
| 237 |
+
raise StrictDataclassDefinitionError(
|
| 238 |
+
f"Class '{cls.__name__}' has a class validator '{name}' that takes more than one argument."
|
| 239 |
+
" Class validators must take only 'self' as an argument. Methods starting with 'validate_'"
|
| 240 |
+
" are considered to be class validators."
|
| 241 |
+
)
|
| 242 |
+
class_validators.append(method)
|
| 243 |
+
|
| 244 |
+
cls.__class_validators__ = class_validators # type: ignore
|
| 245 |
+
|
| 246 |
+
# Add `validate` method to the class, but first check if it already exists
|
| 247 |
+
def validate(self: T) -> None:
|
| 248 |
+
"""Run class validators on the instance."""
|
| 249 |
+
for validator in cls.__class_validators__: # type: ignore [attr-defined]
|
| 250 |
+
try:
|
| 251 |
+
validator(self)
|
| 252 |
+
except (ValueError, TypeError) as e:
|
| 253 |
+
raise StrictDataclassClassValidationError(validator=validator.__name__, cause=e) from e
|
| 254 |
+
|
| 255 |
+
# Hack to be able to raise if `.validate()` already exists except if it was created by this decorator on a parent class
|
| 256 |
+
# (in which case we just override it)
|
| 257 |
+
validate.__is_defined_by_strict_decorator__ = True # type: ignore [attr-defined]
|
| 258 |
+
|
| 259 |
+
if hasattr(cls, "validate"):
|
| 260 |
+
if not getattr(cls.validate, "__is_defined_by_strict_decorator__", False): # type: ignore [attr-defined]
|
| 261 |
+
raise StrictDataclassDefinitionError(
|
| 262 |
+
f"Class '{cls.__name__}' already implements a method called 'validate'."
|
| 263 |
+
" This method name is reserved when using the @strict decorator on a dataclass."
|
| 264 |
+
" If you want to keep your own method, please rename it."
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
cls.validate = validate # type: ignore
|
| 268 |
+
|
| 269 |
+
# Run class validators after initialization
|
| 270 |
+
initial_init = cls.__init__
|
| 271 |
+
|
| 272 |
+
@wraps(initial_init)
|
| 273 |
+
def init_with_validate(self, *args, **kwargs) -> None:
|
| 274 |
+
"""Run class validators after initialization."""
|
| 275 |
+
initial_init(self, *args, **kwargs) # type: ignore [call-arg]
|
| 276 |
+
cls.validate(self) # type: ignore [attr-defined]
|
| 277 |
+
|
| 278 |
+
setattr(cls, "__init__", init_with_validate)
|
| 279 |
+
|
| 280 |
+
return cls
|
| 281 |
+
|
| 282 |
+
# Return wrapped class or the decorator itself
|
| 283 |
+
return wrap(cls) if cls is not None else wrap
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def validate_typed_dict(schema: type[TypedDictType], data: dict) -> None:
|
| 287 |
+
"""
|
| 288 |
+
Validate that a dictionary conforms to the types defined in a TypedDict class.
|
| 289 |
+
|
| 290 |
+
Under the hood, the typed dict is converted to a strict dataclass and validated using the `@strict` decorator.
|
| 291 |
+
|
| 292 |
+
Args:
|
| 293 |
+
schema (`type[TypedDictType]`):
|
| 294 |
+
The TypedDict class defining the expected structure and types.
|
| 295 |
+
data (`dict`):
|
| 296 |
+
The dictionary to validate.
|
| 297 |
+
|
| 298 |
+
Raises:
|
| 299 |
+
`StrictDataclassFieldValidationError`:
|
| 300 |
+
If any field in the dictionary does not conform to the expected type.
|
| 301 |
+
|
| 302 |
+
Example:
|
| 303 |
+
```py
|
| 304 |
+
>>> from typing import Annotated, TypedDict
|
| 305 |
+
>>> from huggingface_hub.dataclasses import validate_typed_dict
|
| 306 |
+
|
| 307 |
+
>>> def positive_int(value: int):
|
| 308 |
+
... if not value >= 0:
|
| 309 |
+
... raise ValueError(f"Value must be positive, got {value}")
|
| 310 |
+
|
| 311 |
+
>>> class User(TypedDict):
|
| 312 |
+
... name: str
|
| 313 |
+
... age: Annotated[int, positive_int]
|
| 314 |
+
|
| 315 |
+
>>> # Valid data
|
| 316 |
+
>>> validate_typed_dict(User, {"name": "John", "age": 30})
|
| 317 |
+
|
| 318 |
+
>>> # Invalid type for age
|
| 319 |
+
>>> validate_typed_dict(User, {"name": "John", "age": "30"})
|
| 320 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 321 |
+
TypeError: Field 'age' expected int, got str (value: '30')
|
| 322 |
+
|
| 323 |
+
>>> # Invalid value for age
|
| 324 |
+
>>> validate_typed_dict(User, {"name": "John", "age": -1})
|
| 325 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 326 |
+
ValueError: Value must be positive, got -1
|
| 327 |
+
```
|
| 328 |
+
"""
|
| 329 |
+
# Convert typed dict to dataclass
|
| 330 |
+
strict_cls = _build_strict_cls_from_typed_dict(schema)
|
| 331 |
+
|
| 332 |
+
# Validate the data by instantiating the strict dataclass
|
| 333 |
+
strict_cls(**data) # will raise if validation fails
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@lru_cache
|
| 337 |
+
def _build_strict_cls_from_typed_dict(schema: type[TypedDictType]) -> Type:
|
| 338 |
+
# Extract type hints from the TypedDict class
|
| 339 |
+
type_hints = _get_typed_dict_annotations(schema)
|
| 340 |
+
|
| 341 |
+
# If the TypedDict is not total, wrap fields as NotRequired (unless explicitly Required or NotRequired)
|
| 342 |
+
if not getattr(schema, "__total__", True):
|
| 343 |
+
for key, value in type_hints.items():
|
| 344 |
+
origin = get_origin(value)
|
| 345 |
+
|
| 346 |
+
if origin is Annotated:
|
| 347 |
+
base, *meta = get_args(value)
|
| 348 |
+
if not _is_required_or_notrequired(base):
|
| 349 |
+
base = NotRequired[base]
|
| 350 |
+
type_hints[key] = Annotated[tuple([base] + list(meta))] # type: ignore
|
| 351 |
+
elif not _is_required_or_notrequired(value):
|
| 352 |
+
type_hints[key] = NotRequired[value]
|
| 353 |
+
|
| 354 |
+
# Convert type hints to dataclass fields
|
| 355 |
+
fields = []
|
| 356 |
+
for key, value in type_hints.items():
|
| 357 |
+
if get_origin(value) is Annotated:
|
| 358 |
+
base, *meta = get_args(value)
|
| 359 |
+
fields.append((key, base, field(default=_TYPED_DICT_DEFAULT_VALUE, metadata={"validator": meta[0]})))
|
| 360 |
+
else:
|
| 361 |
+
fields.append((key, value, field(default=_TYPED_DICT_DEFAULT_VALUE)))
|
| 362 |
+
|
| 363 |
+
# Create a strict dataclass from the TypedDict fields
|
| 364 |
+
return strict(make_dataclass(schema.__name__, fields))
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _get_typed_dict_annotations(schema: type[TypedDictType]) -> dict[str, Any]:
|
| 368 |
+
"""Extract type annotations from a TypedDict class."""
|
| 369 |
+
try:
|
| 370 |
+
# Available in Python 3.14+
|
| 371 |
+
import annotationlib
|
| 372 |
+
|
| 373 |
+
return annotationlib.get_annotations(schema)
|
| 374 |
+
except ImportError:
|
| 375 |
+
return {
|
| 376 |
+
# We do not use `get_type_hints` here to avoid evaluating ForwardRefs (which might fail).
|
| 377 |
+
# ForwardRefs are not validated by @strict anyway.
|
| 378 |
+
name: value if value is not None else type(None)
|
| 379 |
+
for name, value in schema.__dict__.get("__annotations__", {}).items()
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def validated_field(
|
| 384 |
+
validator: list[Validator_T] | Validator_T,
|
| 385 |
+
default: Any | _MISSING_TYPE = MISSING,
|
| 386 |
+
default_factory: Callable[[], Any] | _MISSING_TYPE = MISSING,
|
| 387 |
+
init: bool = True,
|
| 388 |
+
repr: bool = True,
|
| 389 |
+
hash: bool | None = None,
|
| 390 |
+
compare: bool = True,
|
| 391 |
+
metadata: dict | None = None,
|
| 392 |
+
**kwargs: Any,
|
| 393 |
+
) -> Any:
|
| 394 |
+
"""
|
| 395 |
+
Create a dataclass field with a custom validator.
|
| 396 |
+
|
| 397 |
+
Useful to apply several checks to a field. If only applying one rule, check out the [`as_validated_field`] decorator.
|
| 398 |
+
|
| 399 |
+
Args:
|
| 400 |
+
validator (`Callable` or `list[Callable]`):
|
| 401 |
+
A method that takes a value as input and raises ValueError/TypeError if the value is invalid.
|
| 402 |
+
Can be a list of validators to apply multiple checks.
|
| 403 |
+
**kwargs:
|
| 404 |
+
Additional arguments to pass to `dataclasses.field()`.
|
| 405 |
+
|
| 406 |
+
Returns:
|
| 407 |
+
A field with the validator attached in metadata
|
| 408 |
+
"""
|
| 409 |
+
if not isinstance(validator, list):
|
| 410 |
+
validator = [validator]
|
| 411 |
+
if metadata is None:
|
| 412 |
+
metadata = {}
|
| 413 |
+
metadata["validator"] = validator
|
| 414 |
+
return field( # type: ignore
|
| 415 |
+
default=default, # type: ignore [arg-type]
|
| 416 |
+
default_factory=default_factory, # type: ignore [arg-type]
|
| 417 |
+
init=init,
|
| 418 |
+
repr=repr,
|
| 419 |
+
hash=hash,
|
| 420 |
+
compare=compare,
|
| 421 |
+
metadata=metadata,
|
| 422 |
+
**kwargs,
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def as_validated_field(validator: Validator_T):
|
| 427 |
+
"""
|
| 428 |
+
Decorates a validator function as a [`validated_field`] (i.e. a dataclass field with a custom validator).
|
| 429 |
+
|
| 430 |
+
Args:
|
| 431 |
+
validator (`Callable`):
|
| 432 |
+
A method that takes a value as input and raises ValueError/TypeError if the value is invalid.
|
| 433 |
+
"""
|
| 434 |
+
|
| 435 |
+
def _inner(
|
| 436 |
+
default: Any | _MISSING_TYPE = MISSING,
|
| 437 |
+
default_factory: Callable[[], Any] | _MISSING_TYPE = MISSING,
|
| 438 |
+
init: bool = True,
|
| 439 |
+
repr: bool = True,
|
| 440 |
+
hash: bool | None = None,
|
| 441 |
+
compare: bool = True,
|
| 442 |
+
metadata: dict | None = None,
|
| 443 |
+
**kwargs: Any,
|
| 444 |
+
):
|
| 445 |
+
return validated_field(
|
| 446 |
+
validator,
|
| 447 |
+
default=default,
|
| 448 |
+
default_factory=default_factory,
|
| 449 |
+
init=init,
|
| 450 |
+
repr=repr,
|
| 451 |
+
hash=hash,
|
| 452 |
+
compare=compare,
|
| 453 |
+
metadata=metadata,
|
| 454 |
+
**kwargs,
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
return _inner
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def type_validator(name: str, value: Any, expected_type: Any) -> None:
|
| 461 |
+
"""Validate that 'value' matches 'expected_type'."""
|
| 462 |
+
origin = get_origin(expected_type)
|
| 463 |
+
args = get_args(expected_type)
|
| 464 |
+
|
| 465 |
+
if expected_type is Any:
|
| 466 |
+
return
|
| 467 |
+
elif expected_type is None:
|
| 468 |
+
_validate_none(name, value)
|
| 469 |
+
elif validator := _BASIC_TYPE_VALIDATORS.get(origin):
|
| 470 |
+
validator(name, value, args)
|
| 471 |
+
elif isinstance(expected_type, type): # simple types
|
| 472 |
+
_validate_simple_type(name, value, expected_type)
|
| 473 |
+
elif isinstance(expected_type, ForwardRef) or isinstance(expected_type, str):
|
| 474 |
+
return
|
| 475 |
+
elif origin is Required:
|
| 476 |
+
if value is _TYPED_DICT_DEFAULT_VALUE:
|
| 477 |
+
raise TypeError(f"Field '{name}' is required but missing.")
|
| 478 |
+
type_validator(name, value, args[0])
|
| 479 |
+
elif origin is NotRequired:
|
| 480 |
+
if value is _TYPED_DICT_DEFAULT_VALUE:
|
| 481 |
+
return
|
| 482 |
+
type_validator(name, value, args[0])
|
| 483 |
+
else:
|
| 484 |
+
raise TypeError(f"Unsupported type for field '{name}': {expected_type}")
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _validate_none(name: str, value: Any) -> None:
|
| 488 |
+
"""Validate None type.
|
| 489 |
+
|
| 490 |
+
'None' is not a type, it's a special value. Type should be `NoneType` instead.
|
| 491 |
+
But in type annotations 'None' is accepted so we must support it.
|
| 492 |
+
"""
|
| 493 |
+
if value is not None:
|
| 494 |
+
raise TypeError(f"Field '{name}' expected None, got {type(value).__name__}")
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def _validate_union(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 498 |
+
"""Validate that value matches one of the types in a Union."""
|
| 499 |
+
errors = []
|
| 500 |
+
for t in args:
|
| 501 |
+
try:
|
| 502 |
+
type_validator(name, value, t)
|
| 503 |
+
return # Valid if any type matches
|
| 504 |
+
except TypeError as e:
|
| 505 |
+
errors.append(str(e))
|
| 506 |
+
|
| 507 |
+
raise TypeError(
|
| 508 |
+
f"Field '{name}' with value {repr(value)} doesn't match any type in {args}. Errors: {'; '.join(errors)}"
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _validate_literal(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 513 |
+
"""Validate Literal type."""
|
| 514 |
+
if isinstance(value, bool):
|
| 515 |
+
if value not in [arg for arg in args if isinstance(arg, bool)]:
|
| 516 |
+
raise TypeError(f"Field '{name}' expected one of {args}, got {value}")
|
| 517 |
+
elif isinstance(value, int):
|
| 518 |
+
if value not in [arg for arg in args if isinstance(arg, int) and not isinstance(arg, bool)]:
|
| 519 |
+
raise TypeError(f"Field '{name}' expected one of {args}, got {value}")
|
| 520 |
+
elif value not in args:
|
| 521 |
+
raise TypeError(f"Field '{name}' expected one of {args}, got {value}")
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def _validate_list(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 525 |
+
"""Validate list[T] type."""
|
| 526 |
+
if not isinstance(value, list):
|
| 527 |
+
raise TypeError(f"Field '{name}' expected a list, got {type(value).__name__}")
|
| 528 |
+
|
| 529 |
+
# Validate each item in the list
|
| 530 |
+
item_type = args[0]
|
| 531 |
+
for i, item in enumerate(value):
|
| 532 |
+
try:
|
| 533 |
+
type_validator(f"{name}[{i}]", item, item_type)
|
| 534 |
+
except TypeError as e:
|
| 535 |
+
raise TypeError(f"Invalid item at index {i} in list '{name}'") from e
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def _validate_dict(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 539 |
+
"""Validate dict[K, V] type."""
|
| 540 |
+
if not isinstance(value, dict):
|
| 541 |
+
raise TypeError(f"Field '{name}' expected a dict, got {type(value).__name__}")
|
| 542 |
+
|
| 543 |
+
# Validate keys and values
|
| 544 |
+
key_type, value_type = args
|
| 545 |
+
for k, v in value.items():
|
| 546 |
+
try:
|
| 547 |
+
type_validator(f"{name}.key", k, key_type)
|
| 548 |
+
type_validator(f"{name}[{k!r}]", v, value_type)
|
| 549 |
+
except TypeError as e:
|
| 550 |
+
raise TypeError(f"Invalid key or value in dict '{name}'") from e
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def _validate_tuple(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 554 |
+
"""Validate Tuple type."""
|
| 555 |
+
if not isinstance(value, tuple):
|
| 556 |
+
raise TypeError(f"Field '{name}' expected a tuple, got {type(value).__name__}")
|
| 557 |
+
|
| 558 |
+
# Handle variable-length tuples: tuple[T, ...]
|
| 559 |
+
if len(args) == 2 and args[1] is Ellipsis:
|
| 560 |
+
for i, item in enumerate(value):
|
| 561 |
+
try:
|
| 562 |
+
type_validator(f"{name}[{i}]", item, args[0])
|
| 563 |
+
except TypeError as e:
|
| 564 |
+
raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e
|
| 565 |
+
# Handle fixed-length tuples: tuple[T1, T2, ...]
|
| 566 |
+
elif len(args) != len(value):
|
| 567 |
+
raise TypeError(f"Field '{name}' expected a tuple of length {len(args)}, got {len(value)}")
|
| 568 |
+
else:
|
| 569 |
+
for i, (item, expected) in enumerate(zip(value, args)):
|
| 570 |
+
try:
|
| 571 |
+
type_validator(f"{name}[{i}]", item, expected)
|
| 572 |
+
except TypeError as e:
|
| 573 |
+
raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def _validate_set(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 577 |
+
"""Validate set[T] type."""
|
| 578 |
+
if not isinstance(value, set):
|
| 579 |
+
raise TypeError(f"Field '{name}' expected a set, got {type(value).__name__}")
|
| 580 |
+
|
| 581 |
+
# Validate each item in the set
|
| 582 |
+
item_type = args[0]
|
| 583 |
+
for i, item in enumerate(value):
|
| 584 |
+
try:
|
| 585 |
+
type_validator(f"{name} item", item, item_type)
|
| 586 |
+
except TypeError as e:
|
| 587 |
+
raise TypeError(f"Invalid item in set '{name}'") from e
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def _validate_sequence(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 591 |
+
"""Validate Sequence or Sequence[T] type."""
|
| 592 |
+
if not isinstance(value, collections.abc.Sequence):
|
| 593 |
+
raise TypeError(f"Field '{name}' expected a Sequence, got {type(value).__name__}")
|
| 594 |
+
|
| 595 |
+
# If no type argument is provided (i.e., just `Sequence`), skip item validation
|
| 596 |
+
if not args:
|
| 597 |
+
return
|
| 598 |
+
|
| 599 |
+
# Validate each item in the sequence
|
| 600 |
+
item_type = args[0]
|
| 601 |
+
for i, item in enumerate(value):
|
| 602 |
+
try:
|
| 603 |
+
type_validator(f"{name}[{i}]", item, item_type)
|
| 604 |
+
except TypeError as e:
|
| 605 |
+
raise TypeError(f"Invalid item at index {i} in sequence '{name}'") from e
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def _validate_simple_type(name: str, value: Any, expected_type: type) -> None:
|
| 609 |
+
"""Validate simple type (int, str, etc.)."""
|
| 610 |
+
if expected_type is int and isinstance(value, bool):
|
| 611 |
+
raise TypeError(
|
| 612 |
+
f"Field '{name}' expected {expected_type.__name__}, got {type(value).__name__} (value: {repr(value)})"
|
| 613 |
+
)
|
| 614 |
+
if not isinstance(value, expected_type):
|
| 615 |
+
raise TypeError(
|
| 616 |
+
f"Field '{name}' expected {expected_type.__name__}, got {type(value).__name__} (value: {repr(value)})"
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def _create_type_validator(field: Field) -> Validator_T:
|
| 621 |
+
"""Create a type validator function for a field."""
|
| 622 |
+
# Hacky: we cannot use a lambda here because of reference issues
|
| 623 |
+
|
| 624 |
+
def validator(value: Any) -> None:
|
| 625 |
+
type_validator(field.name, value, field.type)
|
| 626 |
+
|
| 627 |
+
return validator
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
def _is_validator(validator: Any) -> bool:
|
| 631 |
+
"""Check if a function is a validator.
|
| 632 |
+
|
| 633 |
+
A validator is a Callable that can be called with a single positional argument.
|
| 634 |
+
The validator can have more arguments with default values.
|
| 635 |
+
|
| 636 |
+
Basically, returns True if `validator(value)` is possible.
|
| 637 |
+
"""
|
| 638 |
+
if not callable(validator):
|
| 639 |
+
return False
|
| 640 |
+
|
| 641 |
+
signature = inspect.signature(validator)
|
| 642 |
+
parameters = list(signature.parameters.values())
|
| 643 |
+
if len(parameters) == 0:
|
| 644 |
+
return False
|
| 645 |
+
if parameters[0].kind not in (
|
| 646 |
+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
| 647 |
+
inspect.Parameter.POSITIONAL_ONLY,
|
| 648 |
+
inspect.Parameter.VAR_POSITIONAL,
|
| 649 |
+
):
|
| 650 |
+
return False
|
| 651 |
+
for parameter in parameters[1:]:
|
| 652 |
+
if parameter.default == inspect.Parameter.empty:
|
| 653 |
+
return False
|
| 654 |
+
return True
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def _is_required_or_notrequired(type_hint: Any) -> bool:
|
| 658 |
+
"""Helper to check if a type is Required/NotRequired."""
|
| 659 |
+
return type_hint in (Required, NotRequired) or (get_origin(type_hint) in (Required, NotRequired))
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
_BASIC_TYPE_VALIDATORS: dict[Any, Callable[[str, Any, tuple[Any, ...]], None]] = {
|
| 663 |
+
Union: _validate_union,
|
| 664 |
+
Literal: _validate_literal,
|
| 665 |
+
list: _validate_list,
|
| 666 |
+
dict: _validate_dict,
|
| 667 |
+
tuple: _validate_tuple,
|
| 668 |
+
set: _validate_set,
|
| 669 |
+
collections.abc.Sequence: _validate_sequence,
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
# TODO: make it first class citizen when bumping to Python 3.10+
|
| 673 |
+
_BASIC_TYPE_VALIDATORS[types.UnionType] = _validate_union # x | y syntax, available only Python 3.10+
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
__all__ = [
|
| 677 |
+
"strict",
|
| 678 |
+
"validate_typed_dict",
|
| 679 |
+
"validated_field",
|
| 680 |
+
"Validator_T",
|
| 681 |
+
"StrictDataclassClassValidationError",
|
| 682 |
+
"StrictDataclassDefinitionError",
|
| 683 |
+
"StrictDataclassFieldValidationError",
|
| 684 |
+
]
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/errors.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contains all custom errors."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from httpx import HTTPError, Response
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# CACHE ERRORS
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class CacheNotFound(Exception):
|
| 12 |
+
"""Exception thrown when the Huggingface cache is not found."""
|
| 13 |
+
|
| 14 |
+
cache_dir: str | Path
|
| 15 |
+
|
| 16 |
+
def __init__(self, msg: str, cache_dir: str | Path, *args, **kwargs):
|
| 17 |
+
super().__init__(msg, *args, **kwargs)
|
| 18 |
+
self.cache_dir = cache_dir
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class CorruptedCacheException(Exception):
|
| 22 |
+
"""Exception for any unexpected structure in the Huggingface cache-system."""
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# HEADERS ERRORS
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class LocalTokenNotFoundError(EnvironmentError):
|
| 29 |
+
"""Raised if local token is required but not found."""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# HTTP ERRORS
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class OfflineModeIsEnabled(ConnectionError):
|
| 36 |
+
"""Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable."""
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class HfHubHTTPError(HTTPError, OSError):
|
| 40 |
+
"""
|
| 41 |
+
HTTPError to inherit from for any custom HTTP Error raised in HF Hub.
|
| 42 |
+
|
| 43 |
+
Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is
|
| 44 |
+
sent back by the server, it will be added to the error message.
|
| 45 |
+
|
| 46 |
+
Added details:
|
| 47 |
+
- Request ID sourced from headers in order of precedence: "X-Request-Id", "X-Amzn-Trace-Id", "X-Amz-Cf-Id".
|
| 48 |
+
- Server error message from the header "X-Error-Message".
|
| 49 |
+
- Server error message if we can found one in the response body.
|
| 50 |
+
|
| 51 |
+
Example:
|
| 52 |
+
```py
|
| 53 |
+
import httpx
|
| 54 |
+
from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
|
| 55 |
+
|
| 56 |
+
response = get_session().post(...)
|
| 57 |
+
try:
|
| 58 |
+
hf_raise_for_status(response)
|
| 59 |
+
except HfHubHTTPError as e:
|
| 60 |
+
print(str(e)) # formatted message
|
| 61 |
+
e.request_id, e.server_message # details returned by server
|
| 62 |
+
|
| 63 |
+
# Complete the error message with additional information once it's raised
|
| 64 |
+
e.append_to_message("\n`create_commit` expects the repository to exist.")
|
| 65 |
+
raise
|
| 66 |
+
```
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(
|
| 70 |
+
self,
|
| 71 |
+
message: str,
|
| 72 |
+
*,
|
| 73 |
+
response: Response,
|
| 74 |
+
server_message: str | None = None,
|
| 75 |
+
):
|
| 76 |
+
self.request_id = (
|
| 77 |
+
response.headers.get("x-request-id")
|
| 78 |
+
or response.headers.get("X-Amzn-Trace-Id")
|
| 79 |
+
or response.headers.get("x-amz-cf-id")
|
| 80 |
+
)
|
| 81 |
+
self.server_message = server_message
|
| 82 |
+
self.response = response
|
| 83 |
+
self.request = response.request
|
| 84 |
+
super().__init__(message)
|
| 85 |
+
|
| 86 |
+
def append_to_message(self, additional_message: str) -> None:
|
| 87 |
+
"""Append additional information to the `HfHubHTTPError` initial message."""
|
| 88 |
+
self.args = (self.args[0] + additional_message,) + self.args[1:]
|
| 89 |
+
|
| 90 |
+
@classmethod
|
| 91 |
+
def _reconstruct_hf_hub_http_error(
|
| 92 |
+
cls, message: str, response: Response, server_message: str | None
|
| 93 |
+
) -> "HfHubHTTPError":
|
| 94 |
+
return cls(message, response=response, server_message=server_message)
|
| 95 |
+
|
| 96 |
+
def __reduce_ex__(self, protocol):
|
| 97 |
+
"""Fix pickling of Exception subclass with kwargs. We need to override __reduce_ex__ of the parent class"""
|
| 98 |
+
return (self.__class__._reconstruct_hf_hub_http_error, (str(self), self.response, self.server_message))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# INFERENCE CLIENT ERRORS
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class InferenceTimeoutError(HTTPError, TimeoutError):
|
| 105 |
+
"""Error raised when a model is unavailable or the request times out."""
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# INFERENCE ENDPOINT ERRORS
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class InferenceEndpointError(Exception):
|
| 112 |
+
"""Generic exception when dealing with Inference Endpoints."""
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError):
|
| 116 |
+
"""Exception for timeouts while waiting for Inference Endpoint."""
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
# SAFETENSORS ERRORS
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class SafetensorsParsingError(Exception):
|
| 123 |
+
"""Raised when failing to parse a safetensors file metadata.
|
| 124 |
+
|
| 125 |
+
This can be the case if the file is not a safetensors file or does not respect the specification.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class NotASafetensorsRepoError(Exception):
|
| 130 |
+
"""Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a
|
| 131 |
+
`model.safetensors.index.json` file.
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# TEXT GENERATION ERRORS
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class TextGenerationError(HTTPError):
|
| 139 |
+
"""Generic error raised if text-generation went wrong."""
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# Text Generation Inference Errors
|
| 143 |
+
class ValidationError(TextGenerationError):
|
| 144 |
+
"""Server-side validation error."""
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class GenerationError(TextGenerationError):
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class OverloadedError(TextGenerationError):
|
| 152 |
+
pass
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class IncompleteGenerationError(TextGenerationError):
|
| 156 |
+
pass
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class UnknownError(TextGenerationError):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# VALIDATION ERRORS
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class HFValidationError(ValueError):
|
| 167 |
+
"""Generic exception thrown by `huggingface_hub` validators.
|
| 168 |
+
|
| 169 |
+
Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# FILE METADATA ERRORS
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class DryRunError(OSError):
|
| 177 |
+
"""Error triggered when a dry run is requested but cannot be performed (e.g. invalid repo)."""
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class FileMetadataError(OSError):
|
| 181 |
+
"""Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).
|
| 182 |
+
|
| 183 |
+
Inherits from `OSError` for backward compatibility.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# BUCKET ERRORS
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class BucketNotFoundError(HfHubHTTPError):
|
| 191 |
+
"""
|
| 192 |
+
Raised when trying to access a bucket that does not exist.
|
| 193 |
+
|
| 194 |
+
Attributes:
|
| 195 |
+
bucket_id (`str` or `None`):
|
| 196 |
+
The bucket id (namespace/name) that was not found, if it could be determined from the request URL.
|
| 197 |
+
|
| 198 |
+
Example:
|
| 199 |
+
|
| 200 |
+
```py
|
| 201 |
+
>>> from huggingface_hub import bucket_info
|
| 202 |
+
>>> bucket_info("<non_existent_bucket>")
|
| 203 |
+
(...)
|
| 204 |
+
huggingface_hub.errors.BucketNotFoundError: 404 Client Error. (Request ID: XXX)
|
| 205 |
+
|
| 206 |
+
Bucket Not Found for url: https://huggingface.co/api/buckets/namespace/name.
|
| 207 |
+
Please make sure you specified the correct bucket id (namespace/name).
|
| 208 |
+
If the bucket is private, make sure you are authenticated and your token has the required permissions.
|
| 209 |
+
```
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
bucket_id: str | None = None
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# REPOSITORY ERRORS
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class RepositoryNotFoundError(HfHubHTTPError):
|
| 219 |
+
"""
|
| 220 |
+
Raised when trying to access a hf.co URL with an invalid repository name, or
|
| 221 |
+
with a private repo name the user does not have access to.
|
| 222 |
+
|
| 223 |
+
Attributes:
|
| 224 |
+
repo_id (`str` or `None`):
|
| 225 |
+
The repo id that was not found, if it could be determined from the request URL.
|
| 226 |
+
repo_type (`str` or `None`):
|
| 227 |
+
The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.
|
| 228 |
+
|
| 229 |
+
Example:
|
| 230 |
+
|
| 231 |
+
```py
|
| 232 |
+
>>> from huggingface_hub import model_info
|
| 233 |
+
>>> model_info("<non_existent_repository>")
|
| 234 |
+
(...)
|
| 235 |
+
huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)
|
| 236 |
+
|
| 237 |
+
Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
|
| 238 |
+
Please make sure you specified the correct `repo_id` and `repo_type`.
|
| 239 |
+
If the repo is private, make sure you are authenticated and your token has the required permissions.
|
| 240 |
+
Invalid username or password.
|
| 241 |
+
```
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
repo_id: str | None = None
|
| 245 |
+
repo_type: str | None = None
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class GatedRepoError(RepositoryNotFoundError):
|
| 249 |
+
"""
|
| 250 |
+
Raised when trying to access a gated repository for which the user is not on the
|
| 251 |
+
authorized list.
|
| 252 |
+
|
| 253 |
+
Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.
|
| 254 |
+
|
| 255 |
+
Example:
|
| 256 |
+
|
| 257 |
+
```py
|
| 258 |
+
>>> from huggingface_hub import model_info
|
| 259 |
+
>>> model_info("<gated_repository>")
|
| 260 |
+
(...)
|
| 261 |
+
huggingface_hub.errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)
|
| 262 |
+
|
| 263 |
+
Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
|
| 264 |
+
Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
|
| 265 |
+
Visit https://huggingface.co/ardent-figment/gated-model to ask for access.
|
| 266 |
+
```
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class DisabledRepoError(HfHubHTTPError):
|
| 271 |
+
"""
|
| 272 |
+
Raised when trying to access a repository that has been disabled by its author.
|
| 273 |
+
|
| 274 |
+
Example:
|
| 275 |
+
|
| 276 |
+
```py
|
| 277 |
+
>>> from huggingface_hub import dataset_info
|
| 278 |
+
>>> dataset_info("laion/laion-art")
|
| 279 |
+
(...)
|
| 280 |
+
huggingface_hub.errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)
|
| 281 |
+
|
| 282 |
+
Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art.
|
| 283 |
+
Access to this resource is disabled.
|
| 284 |
+
```
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
# REVISION ERROR
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class RevisionNotFoundError(HfHubHTTPError):
|
| 292 |
+
"""
|
| 293 |
+
Raised when trying to access a hf.co URL with a valid repository but an invalid
|
| 294 |
+
revision.
|
| 295 |
+
|
| 296 |
+
Attributes:
|
| 297 |
+
repo_id (`str` or `None`):
|
| 298 |
+
The repo id, if it could be determined from the request URL.
|
| 299 |
+
repo_type (`str` or `None`):
|
| 300 |
+
The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.
|
| 301 |
+
|
| 302 |
+
Example:
|
| 303 |
+
|
| 304 |
+
```py
|
| 305 |
+
>>> from huggingface_hub import hf_hub_download
|
| 306 |
+
>>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
|
| 307 |
+
(...)
|
| 308 |
+
huggingface_hub.errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)
|
| 309 |
+
|
| 310 |
+
Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.
|
| 311 |
+
```
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
repo_id: str | None = None
|
| 315 |
+
repo_type: str | None = None
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
# ENTRY ERRORS
|
| 319 |
+
class EntryNotFoundError(Exception):
|
| 320 |
+
"""
|
| 321 |
+
Raised when entry not found, either locally or remotely.
|
| 322 |
+
|
| 323 |
+
Example:
|
| 324 |
+
|
| 325 |
+
```py
|
| 326 |
+
>>> from huggingface_hub import hf_hub_download
|
| 327 |
+
>>> hf_hub_download('bert-base-cased', '<non-existent-file>')
|
| 328 |
+
(...)
|
| 329 |
+
huggingface_hub.errors.RemoteEntryNotFoundError (...)
|
| 330 |
+
>>> hf_hub_download('bert-base-cased', '<non-existent-file>', local_files_only=True)
|
| 331 |
+
(...)
|
| 332 |
+
huggingface_hub.utils.errors.LocalEntryNotFoundError (...)
|
| 333 |
+
```
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class RemoteEntryNotFoundError(HfHubHTTPError, EntryNotFoundError):
|
| 338 |
+
"""
|
| 339 |
+
Raised when trying to access a hf.co URL with a valid repository and revision
|
| 340 |
+
but an invalid filename.
|
| 341 |
+
|
| 342 |
+
Attributes:
|
| 343 |
+
repo_id (`str` or `None`):
|
| 344 |
+
The repo id, if it could be determined from the request URL.
|
| 345 |
+
repo_type (`str` or `None`):
|
| 346 |
+
The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.
|
| 347 |
+
|
| 348 |
+
Example:
|
| 349 |
+
|
| 350 |
+
```py
|
| 351 |
+
>>> from huggingface_hub import hf_hub_download
|
| 352 |
+
>>> hf_hub_download('bert-base-cased', '<non-existent-file>')
|
| 353 |
+
(...)
|
| 354 |
+
huggingface_hub.errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)
|
| 355 |
+
|
| 356 |
+
Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.
|
| 357 |
+
```
|
| 358 |
+
"""
|
| 359 |
+
|
| 360 |
+
repo_id: str | None = None
|
| 361 |
+
repo_type: str | None = None
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class LocalEntryNotFoundError(FileNotFoundError, EntryNotFoundError):
|
| 365 |
+
"""
|
| 366 |
+
Raised when trying to access a file or snapshot that is not on the disk when network is
|
| 367 |
+
disabled or unavailable (connection issue). The entry may exist on the Hub.
|
| 368 |
+
|
| 369 |
+
Example:
|
| 370 |
+
|
| 371 |
+
```py
|
| 372 |
+
>>> from huggingface_hub import hf_hub_download
|
| 373 |
+
>>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)
|
| 374 |
+
(...)
|
| 375 |
+
huggingface_hub.errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False.
|
| 376 |
+
```
|
| 377 |
+
"""
|
| 378 |
+
|
| 379 |
+
def __init__(self, message: str):
|
| 380 |
+
super().__init__(message)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
# REQUEST ERROR
|
| 384 |
+
class BadRequestError(HfHubHTTPError, ValueError):
|
| 385 |
+
"""
|
| 386 |
+
Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.
|
| 387 |
+
|
| 388 |
+
Example:
|
| 389 |
+
|
| 390 |
+
```py
|
| 391 |
+
>>> resp = httpx.post("hf.co/api/check", ...)
|
| 392 |
+
>>> hf_raise_for_status(resp, endpoint_name="check")
|
| 393 |
+
huggingface_hub.errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)
|
| 394 |
+
```
|
| 395 |
+
"""
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
# DDUF file format ERROR
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
class DDUFError(Exception):
|
| 402 |
+
"""Base exception for errors related to the DDUF format."""
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class DDUFCorruptedFileError(DDUFError):
|
| 406 |
+
"""Exception thrown when the DDUF file is corrupted."""
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
class DDUFExportError(DDUFError):
|
| 410 |
+
"""Base exception for errors during DDUF export."""
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
class DDUFInvalidEntryNameError(DDUFExportError):
|
| 414 |
+
"""Exception thrown when the entry name is invalid."""
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
# STRICT DATACLASSES ERRORS
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
class StrictDataclassError(Exception):
|
| 421 |
+
"""Base exception for strict dataclasses."""
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class StrictDataclassDefinitionError(StrictDataclassError):
|
| 425 |
+
"""Exception thrown when a strict dataclass is defined incorrectly."""
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class StrictDataclassFieldValidationError(StrictDataclassError):
|
| 429 |
+
"""Exception thrown when a strict dataclass fails validation for a given field."""
|
| 430 |
+
|
| 431 |
+
def __init__(self, field: str, cause: Exception):
|
| 432 |
+
error_message = f"Validation error for field '{field}':"
|
| 433 |
+
error_message += f"\n {cause.__class__.__name__}: {cause}"
|
| 434 |
+
super().__init__(error_message)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class StrictDataclassClassValidationError(StrictDataclassError):
|
| 438 |
+
"""Exception thrown when a strict dataclass fails validation on a class validator."""
|
| 439 |
+
|
| 440 |
+
def __init__(self, validator: str, cause: Exception):
|
| 441 |
+
error_message = f"Class validation error for validator '{validator}':"
|
| 442 |
+
error_message += f"\n {cause.__class__.__name__}: {cause}"
|
| 443 |
+
super().__init__(error_message)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
# XET ERRORS
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
class XetError(Exception):
|
| 450 |
+
"""Base exception for errors related to Xet Storage."""
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
class XetAuthorizationError(XetError):
|
| 454 |
+
"""Exception thrown when the user does not have the right authorization to use Xet Storage."""
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
class XetRefreshTokenError(XetError):
|
| 458 |
+
"""Exception thrown when the refresh token is invalid."""
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
class XetDownloadError(Exception):
|
| 462 |
+
"""Exception thrown when the download from Xet Storage fails."""
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
# CLI ERRORS
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
class CLIError(Exception):
|
| 469 |
+
"""CLI error with clean message (no traceback by default)."""
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
class CLIExtensionInstallError(CLIError):
|
| 473 |
+
"""Error during CLI extension installation."""
|
.cache/uv/archive-v0/FEnMHFy3LOtQOffttELVc/huggingface_hub/fastai_utils.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from pickle import DEFAULT_PROTOCOL, PicklingError
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from packaging import version
|
| 8 |
+
|
| 9 |
+
from huggingface_hub import constants, snapshot_download
|
| 10 |
+
from huggingface_hub.hf_api import HfApi
|
| 11 |
+
from huggingface_hub.utils import (
|
| 12 |
+
SoftTemporaryDirectory,
|
| 13 |
+
get_fastai_version,
|
| 14 |
+
get_fastcore_version,
|
| 15 |
+
get_python_version,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
from .utils import logging, validate_hf_hub_args
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _check_fastai_fastcore_versions(
|
| 25 |
+
fastai_min_version: str = "2.4",
|
| 26 |
+
fastcore_min_version: str = "1.3.27",
|
| 27 |
+
):
|
| 28 |
+
"""
|
| 29 |
+
Checks that the installed fastai and fastcore versions are compatible for pickle serialization.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
fastai_min_version (`str`, *optional*):
|
| 33 |
+
The minimum fastai version supported.
|
| 34 |
+
fastcore_min_version (`str`, *optional*):
|
| 35 |
+
The minimum fastcore version supported.
|
| 36 |
+
|
| 37 |
+
> [!TIP]
|
| 38 |
+
> Raises the following error:
|
| 39 |
+
>
|
| 40 |
+
> - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 41 |
+
> if the fastai or fastcore libraries are not available or are of an invalid version.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
if (get_fastcore_version() or get_fastai_version()) == "N/A":
|
| 45 |
+
raise ImportError(
|
| 46 |
+
f"fastai>={fastai_min_version} and fastcore>={fastcore_min_version} are"
|
| 47 |
+
f" required. Currently using fastai=={get_fastai_version()} and"
|
| 48 |
+
f" fastcore=={get_fastcore_version()}."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
current_fastai_version = version.Version(get_fastai_version())
|
| 52 |
+
current_fastcore_version = version.Version(get_fastcore_version())
|
| 53 |
+
|
| 54 |
+
if current_fastai_version < version.Version(fastai_min_version):
|
| 55 |
+
raise ImportError(
|
| 56 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require a"
|
| 57 |
+
f" fastai>={fastai_min_version} version, but you are using fastai version"
|
| 58 |
+
f" {get_fastai_version()} which is incompatible. Upgrade with `pip install"
|
| 59 |
+
" fastai==2.5.6`."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if current_fastcore_version < version.Version(fastcore_min_version):
|
| 63 |
+
raise ImportError(
|
| 64 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require a"
|
| 65 |
+
f" fastcore>={fastcore_min_version} version, but you are using fastcore"
|
| 66 |
+
f" version {get_fastcore_version()} which is incompatible. Upgrade with"
|
| 67 |
+
" `pip install fastcore==1.3.27`."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _check_fastai_fastcore_pyproject_versions(
|
| 72 |
+
storage_folder: str,
|
| 73 |
+
fastai_min_version: str = "2.4",
|
| 74 |
+
fastcore_min_version: str = "1.3.27",
|
| 75 |
+
):
|
| 76 |
+
"""
|
| 77 |
+
Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions
|
| 78 |
+
that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist
|
| 79 |
+
or does not contain versions for fastai and fastcore, then it logs a warning.
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
storage_folder (`str`):
|
| 83 |
+
Folder to look for the `pyproject.toml` file.
|
| 84 |
+
fastai_min_version (`str`, *optional*):
|
| 85 |
+
The minimum fastai version supported.
|
| 86 |
+
fastcore_min_version (`str`, *optional*):
|
| 87 |
+
The minimum fastcore version supported.
|
| 88 |
+
|
| 89 |
+
> [!TIP]
|
| 90 |
+
> Raises the following errors:
|
| 91 |
+
>
|
| 92 |
+
> - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 93 |
+
> if the `toml` module is not installed.
|
| 94 |
+
> - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 95 |
+
> if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
import toml
|
| 100 |
+
except ModuleNotFoundError:
|
| 101 |
+
raise ImportError(
|
| 102 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module."
|
| 103 |
+
" Install it with `pip install toml`."
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Checks that a `pyproject.toml`, with `build-system` and `requires` sections, exists in the repository. If so, get a list of required packages.
|
| 107 |
+
if not os.path.isfile(f"{storage_folder}/pyproject.toml"):
|
| 108 |
+
logger.warning(
|
| 109 |
+
"There is no `pyproject.toml` in the repository that contains the fastai"
|
| 110 |
+
" `Learner`. The `pyproject.toml` would allow us to verify that your fastai"
|
| 111 |
+
" and fastcore versions are compatible with those of the model you want to"
|
| 112 |
+
" load."
|
| 113 |
+
)
|
| 114 |
+
return
|
| 115 |
+
pyproject_toml = toml.load(f"{storage_folder}/pyproject.toml")
|
| 116 |
+
|
| 117 |
+
if "build-system" not in pyproject_toml.keys():
|
| 118 |
+
logger.warning(
|
| 119 |
+
"There is no `build-system` section in the pyproject.toml of the repository"
|
| 120 |
+
" that contains the fastai `Learner`. The `build-system` would allow us to"
|
| 121 |
+
" verify that your fastai and fastcore versions are compatible with those"
|
| 122 |
+
" of the model you want to load."
|
| 123 |
+
)
|
| 124 |
+
return
|
| 125 |
+
build_system_toml = pyproject_toml["build-system"]
|
| 126 |
+
|
| 127 |
+
if "requires" not in build_system_toml.keys():
|
| 128 |
+
logger.warning(
|
| 129 |
+
"There is no `requires` section in the pyproject.toml of the repository"
|
| 130 |
+
" that contains the fastai `Learner`. The `requires` would allow us to"
|
| 131 |
+
" verify that your fastai and fastcore versions are compatible with those"
|
| 132 |
+
" of the model you want to load."
|
| 133 |
+
)
|
| 134 |
+
return
|
| 135 |
+
package_versions = build_system_toml["requires"]
|
| 136 |
+
|
| 137 |
+
# Extracts contains fastai and fastcore versions from `pyproject.toml` if available.
|
| 138 |
+
# If the package is specified but not the version (e.g. "fastai" instead of "fastai=2.4"), the default versions are the highest.
|
| 139 |
+
fastai_packages = [pck for pck in package_versions if pck.startswith("fastai")]
|
| 140 |
+
if len(fastai_packages) == 0:
|
| 141 |
+
logger.warning("The repository does not have a fastai version specified in the `pyproject.toml`.")
|
| 142 |
+
# fastai_version is an empty string if not specified
|
| 143 |
+
else:
|
| 144 |
+
fastai_version = str(fastai_packages[0]).partition("=")[2]
|
| 145 |
+
if fastai_version != "" and version.Version(fastai_version) < version.Version(fastai_min_version):
|
| 146 |
+
raise ImportError(
|
| 147 |
+
"`from_pretrained_fastai` requires"
|
| 148 |
+
f" fastai>={fastai_min_version} version but the model to load uses"
|
| 149 |
+
f" {fastai_version} which is incompatible."
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
fastcore_packages = [pck for pck in package_versions if pck.startswith("fastcore")]
|
| 153 |
+
if len(fastcore_packages) == 0:
|
| 154 |
+
logger.warning("The repository does not have a fastcore version specified in the `pyproject.toml`.")
|
| 155 |
+
# fastcore_version is an empty string if not specified
|
| 156 |
+
else:
|
| 157 |
+
fastcore_version = str(fastcore_packages[0]).partition("=")[2]
|
| 158 |
+
if fastcore_version != "" and version.Version(fastcore_version) < version.Version(fastcore_min_version):
|
| 159 |
+
raise ImportError(
|
| 160 |
+
"`from_pretrained_fastai` requires"
|
| 161 |
+
f" fastcore>={fastcore_min_version} version, but you are using fastcore"
|
| 162 |
+
f" version {fastcore_version} which is incompatible."
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
README_TEMPLATE = """---
|
| 167 |
+
tags:
|
| 168 |
+
- fastai
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
# Amazing!
|
| 172 |
+
|
| 173 |
+
🥳 Congratulations on hosting your fastai model on the Hugging Face Hub!
|
| 174 |
+
|
| 175 |
+
# Some next steps
|
| 176 |
+
1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))!
|
| 177 |
+
|
| 178 |
+
2. Create a demo in Gradio or Streamlit using 🤗 Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)).
|
| 179 |
+
|
| 180 |
+
3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)!
|
| 181 |
+
|
| 182 |
+
Greetings fellow fastlearner 🤝! Don't forget to delete this content from your model card.
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
---
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# Model card
|
| 189 |
+
|
| 190 |
+
## Model description
|
| 191 |
+
More information needed
|
| 192 |
+
|
| 193 |
+
## Intended uses & limitations
|
| 194 |
+
More information needed
|
| 195 |
+
|
| 196 |
+
## Training and evaluation data
|
| 197 |
+
More information needed
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
PYPROJECT_TEMPLATE = f"""[build-system]
|
| 201 |
+
requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"]
|
| 202 |
+
build-backend = "setuptools.build_meta:__legacy__"
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _create_model_card(repo_dir: Path):
|
| 207 |
+
"""
|
| 208 |
+
Creates a model card for the repository.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
repo_dir (`Path`):
|
| 212 |
+
Directory where model card is created.
|
| 213 |
+
"""
|
| 214 |
+
readme_path = repo_dir / "README.md"
|
| 215 |
+
|
| 216 |
+
if not readme_path.exists():
|
| 217 |
+
with readme_path.open("w", encoding="utf-8") as f:
|
| 218 |
+
f.write(README_TEMPLATE)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _create_model_pyproject(repo_dir: Path):
|
| 222 |
+
"""
|
| 223 |
+
Creates a `pyproject.toml` for the repository.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
repo_dir (`Path`):
|
| 227 |
+
Directory where `pyproject.toml` is created.
|
| 228 |
+
"""
|
| 229 |
+
pyproject_path = repo_dir / "pyproject.toml"
|
| 230 |
+
|
| 231 |
+
if not pyproject_path.exists():
|
| 232 |
+
with pyproject_path.open("w", encoding="utf-8") as f:
|
| 233 |
+
f.write(PYPROJECT_TEMPLATE)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _save_pretrained_fastai(
|
| 237 |
+
learner,
|
| 238 |
+
save_directory: str | Path,
|
| 239 |
+
config: dict[str, Any] | None = None,
|
| 240 |
+
):
|
| 241 |
+
"""
|
| 242 |
+
Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
learner (`Learner`):
|
| 246 |
+
The `fastai.Learner` you'd like to save.
|
| 247 |
+
save_directory (`str` or `Path`):
|
| 248 |
+
Specific directory in which you want to save the fastai learner.
|
| 249 |
+
config (`dict`, *optional*):
|
| 250 |
+
Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'.
|
| 251 |
+
|
| 252 |
+
> [!TIP]
|
| 253 |
+
> Raises the following error:
|
| 254 |
+
>
|
| 255 |
+
> - [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError)
|
| 256 |
+
> if the config file provided is not a dictionary.
|
| 257 |
+
"""
|
| 258 |
+
_check_fastai_fastcore_versions()
|
| 259 |
+
|
| 260 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 261 |
+
|
| 262 |
+
# if the user provides config then we update it with the fastai and fastcore versions in CONFIG_TEMPLATE.
|
| 263 |
+
if config is not None:
|
| 264 |
+
if not isinstance(config, dict):
|
| 265 |
+
raise RuntimeError(f"Provided config should be a dict. Got: '{type(config)}'")
|
| 266 |
+
path = os.path.join(save_directory, constants.CONFIG_NAME)
|
| 267 |
+
with open(path, "w") as f:
|
| 268 |
+
json.dump(config, f)
|
| 269 |
+
|
| 270 |
+
_create_model_card(Path(save_directory))
|
| 271 |
+
_create_model_pyproject(Path(save_directory))
|
| 272 |
+
|
| 273 |
+
# learner.export saves the model in `self.path`.
|
| 274 |
+
learner.path = Path(save_directory)
|
| 275 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 276 |
+
try:
|
| 277 |
+
learner.export(
|
| 278 |
+
fname="model.pkl",
|
| 279 |
+
pickle_protocol=DEFAULT_PROTOCOL,
|
| 280 |
+
)
|
| 281 |
+
except PicklingError:
|
| 282 |
+
raise PicklingError(
|
| 283 |
+
"You are using a lambda function, i.e., an anonymous function. `pickle`"
|
| 284 |
+
" cannot pickle function objects and requires that all functions have"
|
| 285 |
+
" names. One possible solution is to name the function."
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
@validate_hf_hub_args
|
| 290 |
+
def from_pretrained_fastai(
|
| 291 |
+
repo_id: str,
|
| 292 |
+
revision: str | None = None,
|
| 293 |
+
):
|
| 294 |
+
"""
|
| 295 |
+
Load pretrained fastai model from the Hub or from a local directory.
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
repo_id (`str`):
|
| 299 |
+
The location where the pickled fastai.Learner is. It can be either of the two:
|
| 300 |
+
- Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'.
|
| 301 |
+
You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`.
|
| 302 |
+
Revision is the specific model version to use. Since we use a git-based system for storing models and other
|
| 303 |
+
artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id.
|
| 304 |
+
- Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml
|
| 305 |
+
indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`.
|
| 306 |
+
revision (`str`, *optional*):
|
| 307 |
+
Revision at which the repo's files are downloaded. See documentation of `snapshot_download`.
|
| 308 |
+
|
| 309 |
+
Returns:
|
| 310 |
+
The `fastai.Learner` model in the `repo_id` repo.
|
| 311 |
+
"""
|
| 312 |
+
_check_fastai_fastcore_versions()
|
| 313 |
+
|
| 314 |
+
# Load the `repo_id` repo.
|
| 315 |
+
# `snapshot_download` returns the folder where the model was stored.
|
| 316 |
+
# `cache_dir` will be the default '/root/.cache/huggingface/hub'
|
| 317 |
+
if not os.path.isdir(repo_id):
|
| 318 |
+
storage_folder = snapshot_download(
|
| 319 |
+
repo_id=repo_id,
|
| 320 |
+
revision=revision,
|
| 321 |
+
library_name="fastai",
|
| 322 |
+
library_version=get_fastai_version(),
|
| 323 |
+
)
|
| 324 |
+
else:
|
| 325 |
+
storage_folder = repo_id
|
| 326 |
+
|
| 327 |
+
_check_fastai_fastcore_pyproject_versions(storage_folder)
|
| 328 |
+
|
| 329 |
+
from fastai.learner import load_learner # type: ignore
|
| 330 |
+
|
| 331 |
+
return load_learner(os.path.join(storage_folder, "model.pkl"))
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@validate_hf_hub_args
|
| 335 |
+
def push_to_hub_fastai(
|
| 336 |
+
learner,
|
| 337 |
+
*,
|
| 338 |
+
repo_id: str,
|
| 339 |
+
commit_message: str = "Push FastAI model using huggingface_hub.",
|
| 340 |
+
private: bool | None = None,
|
| 341 |
+
token: str | None = None,
|
| 342 |
+
config: dict | None = None,
|
| 343 |
+
branch: str | None = None,
|
| 344 |
+
create_pr: bool | None = None,
|
| 345 |
+
allow_patterns: list[str] | str | None = None,
|
| 346 |
+
ignore_patterns: list[str] | str | None = None,
|
| 347 |
+
delete_patterns: list[str] | str | None = None,
|
| 348 |
+
api_endpoint: str | None = None,
|
| 349 |
+
):
|
| 350 |
+
"""
|
| 351 |
+
Upload learner checkpoint files to the Hub.
|
| 352 |
+
|
| 353 |
+
Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
|
| 354 |
+
`delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
|
| 355 |
+
details.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
learner (`Learner`):
|
| 359 |
+
The `fastai.Learner' you'd like to push to the Hub.
|
| 360 |
+
repo_id (`str`):
|
| 361 |
+
The repository id for your model in Hub in the format of "namespace/repo_name". The namespace can be your individual account or an organization to which you have write access (for example, 'stanfordnlp/stanza-de').
|
| 362 |
+
commit_message (`str`, *optional*):
|
| 363 |
+
Message to commit while pushing. Will default to :obj:`"add model"`.
|
| 364 |
+
private (`bool`, *optional*):
|
| 365 |
+
Whether or not the repository created should be private.
|
| 366 |
+
If `None` (default), will default to been public except if the organization's default is private.
|
| 367 |
+
token (`str`, *optional*):
|
| 368 |
+
The Hugging Face account token to use as HTTP bearer authorization for remote files. If :obj:`None`, the token will be asked by a prompt.
|
| 369 |
+
config (`dict`, *optional*):
|
| 370 |
+
Configuration object to be saved alongside the model weights.
|
| 371 |
+
branch (`str`, *optional*):
|
| 372 |
+
The git branch on which to push the model. This defaults to
|
| 373 |
+
the default branch as specified in your repository, which
|
| 374 |
+
defaults to `"main"`.
|
| 375 |
+
create_pr (`boolean`, *optional*):
|
| 376 |
+
Whether or not to create a Pull Request from `branch` with that commit.
|
| 377 |
+
Defaults to `False`.
|
| 378 |
+
api_endpoint (`str`, *optional*):
|
| 379 |
+
The API endpoint to use when pushing the model to the hub.
|
| 380 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 381 |
+
If provided, only files matching at least one pattern are pushed.
|
| 382 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 383 |
+
If provided, files matching any of the patterns are not pushed.
|
| 384 |
+
delete_patterns (`list[str]` or `str`, *optional*):
|
| 385 |
+
If provided, remote files matching any of the patterns will be deleted from the repo.
|
| 386 |
+
|
| 387 |
+
Returns:
|
| 388 |
+
The url of the commit of your model in the given repository.
|
| 389 |
+
|
| 390 |
+
> [!TIP]
|
| 391 |
+
> Raises the following error:
|
| 392 |
+
>
|
| 393 |
+
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 394 |
+
> if the user is not log on to the Hugging Face Hub.
|
| 395 |
+
"""
|
| 396 |
+
_check_fastai_fastcore_versions()
|
| 397 |
+
api = HfApi(endpoint=api_endpoint)
|
| 398 |
+
repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id
|
| 399 |
+
|
| 400 |
+
# Push the files to the repo in a single commit
|
| 401 |
+
with SoftTemporaryDirectory() as tmp:
|
| 402 |
+
saved_path = Path(tmp) / repo_id
|
| 403 |
+
_save_pretrained_fastai(learner, saved_path, config=config)
|
| 404 |
+
return api.upload_folder(
|
| 405 |
+
repo_id=repo_id,
|
| 406 |
+
token=token,
|
| 407 |
+
folder_path=saved_path,
|
| 408 |
+
commit_message=commit_message,
|
| 409 |
+
revision=branch,
|
| 410 |
+
create_pr=create_pr,
|
| 411 |
+
allow_patterns=allow_patterns,
|
| 412 |
+
ignore_patterns=ignore_patterns,
|
| 413 |
+
delete_patterns=delete_patterns,
|
| 414 |
+
)
|