Ravenveil commited on
Commit
9bb551a
·
verified ·
1 Parent(s): 107ef48

backup 04_physworld 2026-11-08 10:11:26 (part 9)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +10 -0
  2. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/INSTALLER +1 -0
  3. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/METADATA +368 -0
  4. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/RECORD +375 -0
  5. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/REQUESTED +0 -0
  6. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/WHEEL +5 -0
  7. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/entry_points.txt +6 -0
  8. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/licenses/LICENSE +201 -0
  9. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/top_level.txt +1 -0
  10. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/cache.cpython-311.pyc +0 -0
  11. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/collections.cpython-311.pyc +0 -0
  12. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/datasets.cpython-311.pyc +0 -0
  13. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/discussions.cpython-311.pyc +0 -0
  14. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/download.cpython-311.pyc +0 -0
  15. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/extensions.cpython-311.pyc +0 -0
  16. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/hf.cpython-311.pyc +0 -0
  17. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/inference_endpoints.cpython-311.pyc +0 -0
  18. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/jobs.cpython-311.pyc +3 -0
  19. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/lfs.cpython-311.pyc +0 -0
  20. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/models.cpython-311.pyc +0 -0
  21. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/papers.cpython-311.pyc +0 -0
  22. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/repos.cpython-311.pyc +0 -0
  23. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/sandbox.cpython-311.pyc +0 -0
  24. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/skills.cpython-311.pyc +0 -0
  25. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/spaces.cpython-311.pyc +0 -0
  26. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/system.cpython-311.pyc +0 -0
  27. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/upload.cpython-311.pyc +0 -0
  28. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/webhooks.cpython-311.pyc +0 -0
  29. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_city_game.py +661 -0
  30. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_cli_utils.py +1253 -0
  31. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_completion.py +105 -0
  32. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_cp.py +253 -0
  33. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_errors.py +155 -0
  34. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_file_listing.py +225 -0
  35. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_framework.py +657 -0
  36. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_help_formatter.py +34 -0
  37. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_output.py +398 -0
  38. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_skills.py +389 -0
  39. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_uv_script_header.py +230 -0
  40. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/auth.py +174 -0
  41. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/buckets.py +754 -0
  42. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/cache.py +896 -0
  43. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/collections.py +293 -0
  44. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/datasets.py +274 -0
  45. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/discussions.py +497 -0
  46. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/download.py +228 -0
  47. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/extensions.py +766 -0
  48. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/hf.py +183 -0
  49. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/inference_endpoints.py +940 -0
  50. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/jobs.py +2187 -0
.gitattributes CHANGED
@@ -3483,3 +3483,13 @@ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/fsspec/__pycache__/sp
3483
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
3484
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/__pycache__/_sandbox.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3485
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/__pycache__/hf_api.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
3483
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/hf_xet/hf_xet.abi3.so filter=lfs diff=lfs merge=lfs -text
3484
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/__pycache__/_sandbox.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3485
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/__pycache__/hf_api.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3486
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/jobs.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3487
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3488
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3489
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/imageio/plugins/__pycache__/_tifffile.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3490
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/imageio_ffmpeg/binaries/ffmpeg-linux-x86_64-v7.0.2 filter=lfs diff=lfs merge=lfs -text
3491
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/numpy/_core/__pycache__/_add_newdocs.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3492
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/numpy/_core/__pycache__/fromnumeric.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3493
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/numpy/_core/_multiarray_tests.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3494
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/numpy/_core/_multiarray_umath.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3495
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/numpy/_core/_simd.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/METADATA ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: huggingface_hub
3
+ Version: 2.2.0
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: click<9.0.0,>=8.4.2
27
+ Requires-Dist: filelock>=3.10.0
28
+ Requires-Dist: fsspec>=2023.5.0
29
+ Requires-Dist: hf-xet<2.0.0,>=1.6.0; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "ARM64" or platform_machine == "aarch64"
30
+ Requires-Dist: httpx2<3,>=2.0.0
31
+ Requires-Dist: packaging>=20.9
32
+ Requires-Dist: pyyaml>=5.1
33
+ Requires-Dist: tomli>=1.1.0; python_version < "3.11"
34
+ Requires-Dist: tqdm>=4.42.1
35
+ Requires-Dist: typing-extensions>=4.1.0
36
+ Provides-Extra: oauth
37
+ Requires-Dist: authlib>=1.8.0; extra == "oauth"
38
+ Requires-Dist: fastapi; 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.6.0; extra == "hf-xet"
49
+ Provides-Extra: mcp
50
+ Requires-Dist: mcp<2.0.0,>=1.9.4; extra == "mcp"
51
+ Provides-Extra: testing
52
+ Requires-Dist: authlib>=1.8.0; extra == "testing"
53
+ Requires-Dist: fastapi; extra == "testing"
54
+ Requires-Dist: itsdangerous; extra == "testing"
55
+ Requires-Dist: jedi; extra == "testing"
56
+ Requires-Dist: Jinja2; extra == "testing"
57
+ Requires-Dist: pytest>=8.4.2; extra == "testing"
58
+ Requires-Dist: pytest-cov; extra == "testing"
59
+ Requires-Dist: pytest-env; extra == "testing"
60
+ Requires-Dist: pytest-xdist; extra == "testing"
61
+ Requires-Dist: pytest-vcr; extra == "testing"
62
+ Requires-Dist: pytest-asyncio; extra == "testing"
63
+ Requires-Dist: pytest-rerunfailures>=16.2; extra == "testing"
64
+ Requires-Dist: pytest-mock; extra == "testing"
65
+ Requires-Dist: urllib3<2.0; extra == "testing"
66
+ Requires-Dist: soundfile; extra == "testing"
67
+ Requires-Dist: Pillow; extra == "testing"
68
+ Requires-Dist: numpy; extra == "testing"
69
+ Requires-Dist: duckdb; extra == "testing"
70
+ Requires-Dist: fastapi; extra == "testing"
71
+ Provides-Extra: gradio
72
+ Requires-Dist: gradio>=5.0.0; extra == "gradio"
73
+ Requires-Dist: requests; extra == "gradio"
74
+ Provides-Extra: typing
75
+ Requires-Dist: typing-extensions>=4.8.0; extra == "typing"
76
+ Requires-Dist: types-PyYAML; extra == "typing"
77
+ Requires-Dist: types-simplejson; extra == "typing"
78
+ Requires-Dist: types-toml; extra == "typing"
79
+ Requires-Dist: types-tqdm; extra == "typing"
80
+ Requires-Dist: types-urllib3; extra == "typing"
81
+ Provides-Extra: quality
82
+ Requires-Dist: ruff>=0.9.0; extra == "quality"
83
+ Requires-Dist: mypy==1.15.0; extra == "quality"
84
+ Requires-Dist: libcst>=1.4.0; extra == "quality"
85
+ Requires-Dist: ty; extra == "quality"
86
+ Provides-Extra: all
87
+ Requires-Dist: authlib>=1.8.0; extra == "all"
88
+ Requires-Dist: fastapi; extra == "all"
89
+ Requires-Dist: itsdangerous; extra == "all"
90
+ Requires-Dist: jedi; extra == "all"
91
+ Requires-Dist: Jinja2; extra == "all"
92
+ Requires-Dist: pytest>=8.4.2; extra == "all"
93
+ Requires-Dist: pytest-cov; extra == "all"
94
+ Requires-Dist: pytest-env; extra == "all"
95
+ Requires-Dist: pytest-xdist; extra == "all"
96
+ Requires-Dist: pytest-vcr; extra == "all"
97
+ Requires-Dist: pytest-asyncio; extra == "all"
98
+ Requires-Dist: pytest-rerunfailures>=16.2; extra == "all"
99
+ Requires-Dist: pytest-mock; extra == "all"
100
+ Requires-Dist: urllib3<2.0; extra == "all"
101
+ Requires-Dist: soundfile; extra == "all"
102
+ Requires-Dist: Pillow; extra == "all"
103
+ Requires-Dist: numpy; extra == "all"
104
+ Requires-Dist: duckdb; extra == "all"
105
+ Requires-Dist: fastapi; extra == "all"
106
+ Requires-Dist: ruff>=0.9.0; extra == "all"
107
+ Requires-Dist: mypy==1.15.0; extra == "all"
108
+ Requires-Dist: libcst>=1.4.0; extra == "all"
109
+ Requires-Dist: ty; extra == "all"
110
+ Requires-Dist: typing-extensions>=4.8.0; extra == "all"
111
+ Requires-Dist: types-PyYAML; extra == "all"
112
+ Requires-Dist: types-simplejson; extra == "all"
113
+ Requires-Dist: types-toml; extra == "all"
114
+ Requires-Dist: types-tqdm; extra == "all"
115
+ Requires-Dist: types-urllib3; extra == "all"
116
+ Provides-Extra: dev
117
+ Requires-Dist: authlib>=1.8.0; extra == "dev"
118
+ Requires-Dist: fastapi; extra == "dev"
119
+ Requires-Dist: itsdangerous; extra == "dev"
120
+ Requires-Dist: jedi; extra == "dev"
121
+ Requires-Dist: Jinja2; extra == "dev"
122
+ Requires-Dist: pytest>=8.4.2; extra == "dev"
123
+ Requires-Dist: pytest-cov; extra == "dev"
124
+ Requires-Dist: pytest-env; extra == "dev"
125
+ Requires-Dist: pytest-xdist; extra == "dev"
126
+ Requires-Dist: pytest-vcr; extra == "dev"
127
+ Requires-Dist: pytest-asyncio; extra == "dev"
128
+ Requires-Dist: pytest-rerunfailures>=16.2; extra == "dev"
129
+ Requires-Dist: pytest-mock; extra == "dev"
130
+ Requires-Dist: urllib3<2.0; extra == "dev"
131
+ Requires-Dist: soundfile; extra == "dev"
132
+ Requires-Dist: Pillow; extra == "dev"
133
+ Requires-Dist: numpy; extra == "dev"
134
+ Requires-Dist: duckdb; extra == "dev"
135
+ Requires-Dist: fastapi; extra == "dev"
136
+ Requires-Dist: ruff>=0.9.0; extra == "dev"
137
+ Requires-Dist: mypy==1.15.0; extra == "dev"
138
+ Requires-Dist: libcst>=1.4.0; extra == "dev"
139
+ Requires-Dist: ty; extra == "dev"
140
+ Requires-Dist: typing-extensions>=4.8.0; extra == "dev"
141
+ Requires-Dist: types-PyYAML; extra == "dev"
142
+ Requires-Dist: types-simplejson; extra == "dev"
143
+ Requires-Dist: types-toml; extra == "dev"
144
+ Requires-Dist: types-tqdm; extra == "dev"
145
+ Requires-Dist: types-urllib3; extra == "dev"
146
+ Dynamic: author
147
+ Dynamic: author-email
148
+ Dynamic: classifier
149
+ Dynamic: description
150
+ Dynamic: description-content-type
151
+ Dynamic: home-page
152
+ Dynamic: keywords
153
+ Dynamic: license
154
+ Dynamic: license-file
155
+ Dynamic: provides-extra
156
+ Dynamic: requires-dist
157
+ Dynamic: requires-python
158
+ Dynamic: summary
159
+
160
+ <p align="center">
161
+ <picture>
162
+ <source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub-dark.svg">
163
+ <source media="(prefers-color-scheme: light)" srcset="https://huggingface.co/datasets/huggingface/documentation-images/raw/main/huggingface_hub.svg">
164
+ <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%">
165
+ </picture>
166
+ <br/>
167
+ <br/>
168
+ </p>
169
+
170
+ <p align="center">
171
+ <i>The official CLI and Python client for the Hugging Face Hub.</i>
172
+ <br/>
173
+ <a href="#what-is-huggingface_hub">About</a>
174
+ ·
175
+ <a href="https://huggingface.co/docs/huggingface_hub">Documentation</a>
176
+ ·
177
+ <a href="https://huggingface.co/docs/huggingface_hub/en/installation">Install</a>
178
+ ·
179
+ <a href="https://huggingface.co/docs/huggingface_hub/en/guides/cli">CLI Guide</a>
180
+ ·
181
+ <a href="https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md">Contributing</a>
182
+ </p>
183
+
184
+ <p align="center">
185
+ <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>
186
+ <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>
187
+ <a href="https://github.com/huggingface/huggingface_hub"><img alt="PyPi version" src="https://img.shields.io/pypi/pyversions/huggingface_hub.svg"></a>
188
+ <a href="https://pypi.org/project/huggingface-hub"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/dm/huggingface_hub"></a>
189
+ <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>
190
+ </p>
191
+
192
+ <h4 align="center">
193
+ <p>
194
+ <b>English</b> |
195
+ <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_de.md">Deutsch</a> |
196
+ <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_fr.md">Français</a> |
197
+ <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_hi.md">हिंदी</a> |
198
+ <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_ko.md">한국어</a> |
199
+ <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_cn.md">中文 (简体)</a> |
200
+ <a href="https://github.com/huggingface/huggingface_hub/blob/main/i18n/README_kn.md">ಕನ್ನಡ</a>
201
+ </p>
202
+ </h4>
203
+
204
+ ## Quick start
205
+
206
+ Install the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) with the standalone installer:
207
+
208
+ ```bash
209
+ # On macOS and Linux.
210
+ curl -LsSf https://hf.co/cli/install.sh | bash
211
+ ```
212
+
213
+ ```powershell
214
+ # On Windows.
215
+ powershell -ExecutionPolicy ByPass -c "irm https://hf.co/cli/install.ps1 | iex"
216
+ ```
217
+
218
+ Log in, then start working with the Hub:
219
+
220
+ ```bash
221
+ # Log in (use --token $HF_TOKEN in non-interactive environments)
222
+ hf auth login
223
+
224
+ # Find models served by Inference Providers
225
+ hf models ls --warm
226
+
227
+ # Download a model
228
+ hf download Qwen/Qwen3-0.6B
229
+
230
+ # Upload files to your own repo
231
+ hf upload username/my-cool-model ./model.safetensors
232
+
233
+ # Sync a local folder to a storage bucket
234
+ hf buckets sync ./checkpoints hf://buckets/username/my-bucket
235
+
236
+ # Run a job on Hugging Face infrastructure
237
+ hf jobs run python:3.12 python -c "print('Hello from the cloud!')"
238
+
239
+ # Discover everything else
240
+ hf --help
241
+ ```
242
+
243
+ The Hub uses tokens to authenticate applications (see [docs](https://huggingface.co/docs/hub/security-tokens)). Check out the [CLI guide](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for a tour of the main features.
244
+
245
+ ## What is `huggingface_hub`?
246
+
247
+ 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, play with the thousands of machine learning apps hosted on the Hub, or create and share your own models, datasets and demos with the community. Everything ships in one package with two interfaces: the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli) for your terminal and the `huggingface_hub` library for Python — both designed to work well for humans and AI agents. Use them to:
248
+
249
+ - [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub.
250
+ - [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub.
251
+ - [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository).
252
+ - [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models.
253
+ - [Run Jobs](https://huggingface.co/docs/huggingface_hub/en/guides/jobs) on Hugging Face infrastructure.
254
+ - [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces.
255
+ - [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models.
256
+ - [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments.
257
+ - Do all of the above from the terminal with the [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli).
258
+
259
+ ## Built for humans and AI agents
260
+
261
+ The `hf` CLI is designed for people and coding agents alike: the same commands adapt their output when run by an agent. If you use Claude Code, Codex, Cursor, or another coding agent, install the `hf` CLI Skill — a command reference generated from your installed CLI:
262
+
263
+ ```bash
264
+ # works with Claude Code, Codex, Cursor, OpenCode, Pi and any agent that loads skills from `.agents/skills`
265
+ hf skills add
266
+ ```
267
+
268
+ Learn more in the [Hugging Face CLI for AI agents guide](https://huggingface.co/docs/hub/agents-cli) and the [announcement blog post](https://huggingface.co/blog/hf-cli-for-agents).
269
+
270
+ ## Use the Python library
271
+
272
+ Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/) (this also installs the `hf` CLI):
273
+
274
+ ```bash
275
+ pip install huggingface_hub
276
+ ```
277
+
278
+ We recommend using [`uv`](https://docs.astral.sh/uv/) for a fast and reliable install:
279
+
280
+ ```bash
281
+ uv pip install huggingface_hub
282
+ ```
283
+
284
+ 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:
285
+
286
+ ```bash
287
+ pip install "huggingface_hub[mcp]"
288
+ ```
289
+
290
+ To learn more about installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation).
291
+
292
+ ### Download files
293
+
294
+ Download a single file
295
+
296
+ ```py
297
+ from huggingface_hub import hf_hub_download
298
+
299
+ hf_hub_download(repo_id="zai-org/GLM-5.2", filename="config.json")
300
+ ```
301
+
302
+ Or an entire repository
303
+
304
+ ```py
305
+ from huggingface_hub import snapshot_download
306
+
307
+ snapshot_download("sentence-transformers/all-MiniLM-L6-v2")
308
+ ```
309
+
310
+ Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache).
311
+
312
+ ### Create a repository
313
+
314
+ ```py
315
+ from huggingface_hub import create_repo
316
+
317
+ create_repo(repo_id="super-cool-model")
318
+ ```
319
+
320
+ ### Upload files
321
+
322
+ Upload a single file
323
+
324
+ ```py
325
+ from huggingface_hub import upload_file
326
+
327
+ upload_file(
328
+ path_or_fileobj="/home/lysandre/dummy-test/README.md",
329
+ path_in_repo="README.md",
330
+ repo_id="lysandre/test-model",
331
+ )
332
+ ```
333
+
334
+ Or an entire folder
335
+
336
+ ```py
337
+ from huggingface_hub import upload_folder
338
+
339
+ upload_folder(
340
+ folder_path="/path/to/local/space",
341
+ repo_id="username/my-cool-space",
342
+ repo_type="space",
343
+ )
344
+ ```
345
+
346
+ More details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload).
347
+
348
+ ## Integrating with the Hub.
349
+
350
+ 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).
351
+
352
+ The advantages are:
353
+
354
+ - Free model or dataset hosting for libraries and their users.
355
+ - Built-in file versioning, even with very large files, made possible by [Xet](https://huggingface.co/docs/hub/xet/index), the Hub's chunk-deduplicated storage backend.
356
+ - In-browser widgets to play with the uploaded models.
357
+ - Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable.
358
+ - Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe.
359
+ - Usage stats and more features to come.
360
+
361
+ 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.
362
+
363
+ ## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️
364
+
365
+ Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community.
366
+ Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community.
367
+ We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarize
368
+ how to get started to contribute to this repository.
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/RECORD ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/hf,sha256=ItNVED3LHlQHnBJQExoW7TR3GXRt6SvvmqURoKzXGbM,257
2
+ ../../../bin/tiny-agents,sha256=GfQ3Vk_1r5rRaMiPV-B736XUpidcGxo1KZ32Wdecoaw,267
3
+ huggingface_hub-2.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
4
+ huggingface_hub-2.2.0.dist-info/METADATA,sha256=_sf8KHn6kbfL96IbFDQIchXWKGmyvGn7WWVMMo2aPRQ,16210
5
+ huggingface_hub-2.2.0.dist-info/RECORD,,
6
+ huggingface_hub-2.2.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ huggingface_hub-2.2.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
8
+ huggingface_hub-2.2.0.dist-info/entry_points.txt,sha256=j3KnOggx2dIP7NUkPyYgXdRnLxd94aHmqJ8J6tEZwY8,154
9
+ huggingface_hub-2.2.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
10
+ huggingface_hub-2.2.0.dist-info/top_level.txt,sha256=8KzlQJAY4miUvjAssOAJodqKOw3harNzuiwGQ9qLSSk,16
11
+ huggingface_hub/__init__.py,sha256=MAl1cFFsYHw28JpldHZP6BFTpFQScpNBOqsbgiP4zvc,61394
12
+ huggingface_hub/__pycache__/__init__.cpython-311.pyc,,
13
+ huggingface_hub/__pycache__/_buckets.cpython-311.pyc,,
14
+ huggingface_hub/__pycache__/_commit_api.cpython-311.pyc,,
15
+ huggingface_hub/__pycache__/_commit_scheduler.cpython-311.pyc,,
16
+ huggingface_hub/__pycache__/_dataset_viewer.cpython-311.pyc,,
17
+ huggingface_hub/__pycache__/_eval_results.cpython-311.pyc,,
18
+ huggingface_hub/__pycache__/_inference_endpoints.cpython-311.pyc,,
19
+ huggingface_hub/__pycache__/_jobs_api.cpython-311.pyc,,
20
+ huggingface_hub/__pycache__/_local_folder.cpython-311.pyc,,
21
+ huggingface_hub/__pycache__/_login.cpython-311.pyc,,
22
+ huggingface_hub/__pycache__/_oauth.cpython-311.pyc,,
23
+ huggingface_hub/__pycache__/_oidc.cpython-311.pyc,,
24
+ huggingface_hub/__pycache__/_revision.cpython-311.pyc,,
25
+ huggingface_hub/__pycache__/_sandbox.cpython-311.pyc,,
26
+ huggingface_hub/__pycache__/_sandbox_cache.cpython-311.pyc,,
27
+ huggingface_hub/__pycache__/_snapshot_download.cpython-311.pyc,,
28
+ huggingface_hub/__pycache__/_space_api.cpython-311.pyc,,
29
+ huggingface_hub/__pycache__/_tensorboard_logger.cpython-311.pyc,,
30
+ huggingface_hub/__pycache__/_tree_cache.cpython-311.pyc,,
31
+ huggingface_hub/__pycache__/_upload_pipeline.cpython-311.pyc,,
32
+ huggingface_hub/__pycache__/_webhooks_payload.cpython-311.pyc,,
33
+ huggingface_hub/__pycache__/_webhooks_server.cpython-311.pyc,,
34
+ huggingface_hub/__pycache__/community.cpython-311.pyc,,
35
+ huggingface_hub/__pycache__/constants.cpython-311.pyc,,
36
+ huggingface_hub/__pycache__/dataclasses.cpython-311.pyc,,
37
+ huggingface_hub/__pycache__/errors.cpython-311.pyc,,
38
+ huggingface_hub/__pycache__/fastai_utils.cpython-311.pyc,,
39
+ huggingface_hub/__pycache__/file_download.cpython-311.pyc,,
40
+ huggingface_hub/__pycache__/hf_api.cpython-311.pyc,,
41
+ huggingface_hub/__pycache__/hf_file_system.cpython-311.pyc,,
42
+ huggingface_hub/__pycache__/hub_mixin.cpython-311.pyc,,
43
+ huggingface_hub/__pycache__/lfs.cpython-311.pyc,,
44
+ huggingface_hub/__pycache__/repocard.cpython-311.pyc,,
45
+ huggingface_hub/__pycache__/repocard_data.cpython-311.pyc,,
46
+ huggingface_hub/_buckets.py,sha256=EtUkG6OWBkfIF5BmIafMeBHtsC5OhcFcQ9A4GCL2Kbk,46065
47
+ huggingface_hub/_commit_api.py,sha256=_dgylJ67ADsnn7mSUcXHgU7YHr1dQ35BJSqlJvHcueM,45690
48
+ huggingface_hub/_commit_scheduler.py,sha256=Nn00XoWBcxC426nRx8gA835mioX6aXjuCOLWdCG-noc,14707
49
+ huggingface_hub/_dataset_viewer.py,sha256=deMfUXAboEfHP4a4l70KrmB-B6FePFtFUUCmIYuqwn4,5705
50
+ huggingface_hub/_eval_results.py,sha256=toIFXp9cwrwOCr21C8WuDV_o5_WP2Zh_1dYlkXorku8,8389
51
+ huggingface_hub/_hot_reload/__init__.py,sha256=nQEuyVZLAS_463Dff1JH5MorTpkYsBVFCyPhYWY3UyI,606
52
+ huggingface_hub/_hot_reload/__pycache__/__init__.cpython-311.pyc,,
53
+ huggingface_hub/_hot_reload/__pycache__/client.cpython-311.pyc,,
54
+ huggingface_hub/_hot_reload/__pycache__/sse_client.cpython-311.pyc,,
55
+ huggingface_hub/_hot_reload/__pycache__/types.cpython-311.pyc,,
56
+ huggingface_hub/_hot_reload/client.py,sha256=3CrJMyJsIIrg7jZL95BA7YIt6dhSAjUdoy8IVplSg70,4271
57
+ huggingface_hub/_hot_reload/sse_client.py,sha256=49kmsB2P9sxgbZ16ed6F4aLDs3rsHrNpbp6iKlvF90c,4948
58
+ huggingface_hub/_hot_reload/types.py,sha256=d3AOJCLUxT41Fhz4jUrFevm9bfpooe_3PQhpBdgNYSs,2725
59
+ huggingface_hub/_inference_endpoints.py,sha256=K3G50whKgSPCMXm_7yhIqck7jQaEDf9FQ8FxZ-xv4qs,29398
60
+ huggingface_hub/_jobs_api.py,sha256=T24oDg8ZONMjBiU4SyWs2zYKrCkl_iMECoUlwLwTBuI,27226
61
+ huggingface_hub/_local_folder.py,sha256=nvH1s0_dUNlOMhYMgQ9ys_ysMVJdXdRz4msIq5glbHw,19551
62
+ huggingface_hub/_login.py,sha256=wAMdhqMSSh3GBJDozodmk4IIsAvb9J6LaLY9KnXFoyY,21818
63
+ huggingface_hub/_oauth.py,sha256=S8evEd8JLJHz-JiSjGH4WiIi_A7oDox_xH7E9rN1Jic,18628
64
+ huggingface_hub/_oidc.py,sha256=3kcCLavWQ5FQOwizUPzLaBb1ft2FIJo0bSXL24S3r4U,7098
65
+ huggingface_hub/_revision.py,sha256=_8BYj35dJ5u9iOzaCuTEPtWympQw4fvk-j_GSxQu49M,2549
66
+ huggingface_hub/_sandbox.py,sha256=3rNu3C4Md60Ox2QPLPqUqqhSMOeA1mCbRY-LJ6NOlqY,123668
67
+ huggingface_hub/_sandbox_cache.py,sha256=vA409SxJ-QLXxoS4it2Vc1oIwRzazxapkyjjAD-_R8g,15386
68
+ huggingface_hub/_snapshot_download.py,sha256=M66nYxht8tZgDiAI6R67hiz8EpB2OMrquX6YZc8FLZc,31753
69
+ huggingface_hub/_space_api.py,sha256=Vog-KdjNyx_coNYdU6mCWjlIcsVPU_QoKrGs_ez2PEo,14783
70
+ huggingface_hub/_tensorboard_logger.py,sha256=WG4w2LgWxU4ITn1Dr3i9O0PG8Rzry3SPwKBO5vQfCnQ,8239
71
+ huggingface_hub/_tree_cache.py,sha256=mJ3oFOLSdjXQ5Y2zyA_oHgRi4Vza3LXEtTsZeuTR1c0,6111
72
+ huggingface_hub/_upload_pipeline.py,sha256=6u0x3312yYxjb308FRw0TjqJDoMsHRgzEvm0_OxDWIw,32084
73
+ huggingface_hub/_webhooks_payload.py,sha256=B9zqljcm20DGeVxJKba570i6RP-cR9CEupMGBuNDHHA,3544
74
+ huggingface_hub/_webhooks_server.py,sha256=fjEfZztSrLBLW3SoRdcfOHV9gHhR1Zrn_FYqMzWs2FY,15772
75
+ huggingface_hub/cli/__init__.py,sha256=tWu3Is-m2tlJwXhM_vT2mPRgpnt9KhU9qvw5aRsnjU0,664
76
+ huggingface_hub/cli/__pycache__/__init__.cpython-311.pyc,,
77
+ huggingface_hub/cli/__pycache__/_city_game.cpython-311.pyc,,
78
+ huggingface_hub/cli/__pycache__/_cli_utils.cpython-311.pyc,,
79
+ huggingface_hub/cli/__pycache__/_completion.cpython-311.pyc,,
80
+ huggingface_hub/cli/__pycache__/_cp.cpython-311.pyc,,
81
+ huggingface_hub/cli/__pycache__/_errors.cpython-311.pyc,,
82
+ huggingface_hub/cli/__pycache__/_file_listing.cpython-311.pyc,,
83
+ huggingface_hub/cli/__pycache__/_framework.cpython-311.pyc,,
84
+ huggingface_hub/cli/__pycache__/_help_formatter.cpython-311.pyc,,
85
+ huggingface_hub/cli/__pycache__/_output.cpython-311.pyc,,
86
+ huggingface_hub/cli/__pycache__/_skills.cpython-311.pyc,,
87
+ huggingface_hub/cli/__pycache__/_uv_script_header.cpython-311.pyc,,
88
+ huggingface_hub/cli/__pycache__/auth.cpython-311.pyc,,
89
+ huggingface_hub/cli/__pycache__/buckets.cpython-311.pyc,,
90
+ huggingface_hub/cli/__pycache__/cache.cpython-311.pyc,,
91
+ huggingface_hub/cli/__pycache__/collections.cpython-311.pyc,,
92
+ huggingface_hub/cli/__pycache__/datasets.cpython-311.pyc,,
93
+ huggingface_hub/cli/__pycache__/discussions.cpython-311.pyc,,
94
+ huggingface_hub/cli/__pycache__/download.cpython-311.pyc,,
95
+ huggingface_hub/cli/__pycache__/extensions.cpython-311.pyc,,
96
+ huggingface_hub/cli/__pycache__/hf.cpython-311.pyc,,
97
+ huggingface_hub/cli/__pycache__/inference_endpoints.cpython-311.pyc,,
98
+ huggingface_hub/cli/__pycache__/jobs.cpython-311.pyc,,
99
+ huggingface_hub/cli/__pycache__/lfs.cpython-311.pyc,,
100
+ huggingface_hub/cli/__pycache__/models.cpython-311.pyc,,
101
+ huggingface_hub/cli/__pycache__/papers.cpython-311.pyc,,
102
+ huggingface_hub/cli/__pycache__/repos.cpython-311.pyc,,
103
+ huggingface_hub/cli/__pycache__/sandbox.cpython-311.pyc,,
104
+ huggingface_hub/cli/__pycache__/skills.cpython-311.pyc,,
105
+ huggingface_hub/cli/__pycache__/spaces.cpython-311.pyc,,
106
+ huggingface_hub/cli/__pycache__/system.cpython-311.pyc,,
107
+ huggingface_hub/cli/__pycache__/upload.cpython-311.pyc,,
108
+ huggingface_hub/cli/__pycache__/webhooks.cpython-311.pyc,,
109
+ huggingface_hub/cli/_city_game.py,sha256=2qkC9dCtPwf4-aqrnbN-vApf0YqIcGGjn2v-etrTfqg,20585
110
+ huggingface_hub/cli/_cli_utils.py,sha256=GG3Ko6ErsGAtoBlKjBZ7JSnqrBWvF7gd2a7yXKZMKII,49761
111
+ huggingface_hub/cli/_completion.py,sha256=BDP6Vob9TLFp6K3lr0XOY98FyD-rm22KrjwsO_YGNbE,3759
112
+ huggingface_hub/cli/_cp.py,sha256=Z-2Z_tBs1e4XBqRO5R9QnabU4qTi9HDlbA52jTBaCkY,10436
113
+ huggingface_hub/cli/_errors.py,sha256=X0rUTO-3eCK5v_MLGEza1BxcuXGccPY-h7ShzmuQc34,5907
114
+ huggingface_hub/cli/_file_listing.py,sha256=8e-0ZKNFau--fWD7V4pc1BSwnW-Z_grqRyv5Dy7gsI4,8147
115
+ huggingface_hub/cli/_framework.py,sha256=TS48S5K4c36wTOFl5ENGDlx8Q1IvMgvZgDPLLAocYNo,28078
116
+ huggingface_hub/cli/_help_formatter.py,sha256=-vsa3HfHQFkKWms77EGyp9i22t44ETmVt2L-e8qP-KM,1288
117
+ huggingface_hub/cli/_output.py,sha256=oz4PMpTwTlGii8bDSrX5f1WMsTcRXgGrCCsDyEjAmtI,15558
118
+ huggingface_hub/cli/_skills.py,sha256=P2L2acXxKDRrF1z5GYGgX4T43VFDnEzH42TPxDVj1Qk,15109
119
+ huggingface_hub/cli/_uv_script_header.py,sha256=-LYNgaA4i3ZyETASlg5_KA8QL_o8qHPJdQwldNjzt2o,9397
120
+ huggingface_hub/cli/auth.py,sha256=WVxVkOeHCPB1Iy7oeVhtu-OzGck4Fa-VQPmxfGEfobY,6084
121
+ huggingface_hub/cli/buckets.py,sha256=o3jm3vVElrG9yvQykSGhHxjAr3yVWMlM2fWjPyWK_fs,23614
122
+ huggingface_hub/cli/cache.py,sha256=mwCCAm22akHMfMjA69-CbChwUZzHv_2Vc88NFyPb0ug,32461
123
+ huggingface_hub/cli/collections.py,sha256=Ed41zJqrvK-AWkHdkeHWm_aJKR_ZeNIovCGvWG04itk,10120
124
+ huggingface_hub/cli/datasets.py,sha256=X1xMJTFhHH5NJtmjTS6NN1g4ffai6Abh_obDEJM5mvo,10497
125
+ huggingface_hub/cli/discussions.py,sha256=obvvN4mtsFnfMs67YTZaMvHkVaM6A-FYr5n-wGkF_jE,14029
126
+ huggingface_hub/cli/download.py,sha256=jMk5JzOaUy0zR3_ZQNvZ_cJsG0bKqIUn-FTlwdJfN9s,9871
127
+ huggingface_hub/cli/extensions.py,sha256=Hjsk8yTqpzrWUt9pO0R8Lh2jhOgOktelFHnJxucRABo,29396
128
+ huggingface_hub/cli/hf.py,sha256=i4cWibNWtUPPICsa68RUXr37T0i46zjgsOSX_TwRSGY,5983
129
+ huggingface_hub/cli/inference_endpoints.py,sha256=SEo7IG4G77j2NMyAkZmmOsrEtPmxtvUT9Nbpadaspog,33789
130
+ huggingface_hub/cli/jobs.py,sha256=KDLHGNk1Ftq3KnZOW-toBcOSlMI_XvytqxncsDwbAV8,81925
131
+ huggingface_hub/cli/lfs.py,sha256=MAccazVPX0n-ySRaPocaQUHP7oBnVrvWZt0RhmNIavs,5936
132
+ huggingface_hub/cli/models.py,sha256=fyTNJtwt-2KakLTdwqKd0AOmnL8i92tESKqhLJuGLJg,10185
133
+ huggingface_hub/cli/papers.py,sha256=HvT-8zj2fi14ua6awWpHphlbJ362FEJIwSCBJRQZ_cM,4982
134
+ huggingface_hub/cli/repos.py,sha256=Jzki8qknLm-G6LHwlf8Fsj9IKx6i68r03EfOav-yJeg,20163
135
+ huggingface_hub/cli/sandbox.py,sha256=l3ZgwB13RowssIHBc_TppQO_heP5jcluqMGCitmcfvQ,18944
136
+ huggingface_hub/cli/skills.py,sha256=q7HdPwJM_N1zw6ec72UZkwWTnxfS4sbt-JRcaBTFCpo,20257
137
+ huggingface_hub/cli/spaces.py,sha256=RO0CRRIyDhCgfky5Oceu0C74xJSnvhJaURNjlYkwe3c,42011
138
+ huggingface_hub/cli/system.py,sha256=cB2GFlV9si0HbmUkyoj5nAKZf-vWpf9gi9XAq51s05Y,3850
139
+ huggingface_hub/cli/upload.py,sha256=ZcPnxkUB8Rk5EJlfXiUU5fD7oGc_6CwCOCa22M4XIEI,12181
140
+ huggingface_hub/cli/webhooks.py,sha256=XQNtGEPDKX4q1xcCO20kGgfskZ7NIBb41Jz4w7o_J_M,10374
141
+ huggingface_hub/community.py,sha256=RLlbbXs5P_84D8l9nKLPL0tudxZx-EN95oUCxgzGpvQ,12336
142
+ huggingface_hub/constants.py,sha256=-Q1XqkZFfo9-_dwLPLH9_Y0EtL5lZXzWkAH2ADFpNcY,14106
143
+ huggingface_hub/dataclasses.py,sha256=WhbBsZEDwJdUgSMrlamBiY-1ghi5UMAkSFg5BGIbZt8,26285
144
+ huggingface_hub/errors.py,sha256=i31RI8q0ZHHKpB68pNsBJXHInVRtGFS2uSzvCf4Rb0c,19048
145
+ huggingface_hub/fastai_utils.py,sha256=jwKeVXH_VP0zxnOKVNQCVCkF-stH70l-bExbbrYkBKQ,16583
146
+ huggingface_hub/file_download.py,sha256=QMKzFWFirpmW8DutvOkZaXm_h0IZ-qDaQ7w5zugWJRI,94574
147
+ huggingface_hub/hf_api.py,sha256=vNFhFCZ20idew6JXGDiXv4UflCy9And7T96VaKgN-DY,684322
148
+ huggingface_hub/hf_file_system.py,sha256=b6fyJM73Fn7qpI2HU8DbN1TGlSjxW3oYxMhedvK7-lo,64300
149
+ huggingface_hub/hub_mixin.py,sha256=ygXdyZ9re7BGOTwn9nlr7j-ae1q6z3zgUPIaLhGL3Xo,36720
150
+ huggingface_hub/inference/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
151
+ huggingface_hub/inference/__pycache__/__init__.cpython-311.pyc,,
152
+ huggingface_hub/inference/__pycache__/_client.cpython-311.pyc,,
153
+ huggingface_hub/inference/__pycache__/_common.cpython-311.pyc,,
154
+ huggingface_hub/inference/_client.py,sha256=6j7M1Ue-mQzZwY8b8mwFiJhZwbmKQvCKfVH_nu8K76I,156086
155
+ huggingface_hub/inference/_common.py,sha256=0I7-ogOUmW3Rnp-mJ5kCGOPuP5VrQLayrgdUZvmI3_c,15011
156
+ huggingface_hub/inference/_generated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
157
+ huggingface_hub/inference/_generated/__pycache__/__init__.cpython-311.pyc,,
158
+ huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-311.pyc,,
159
+ huggingface_hub/inference/_generated/_async_client.py,sha256=Q1oswmf3U54x8h6Z6q-wC5mAL-5baeLQCYRvaaB-LNg,159299
160
+ huggingface_hub/inference/_generated/types/__init__.py,sha256=e625ENOmTUM4uUL1eAlsZOK7CovNoGBDH-TxSNQhaC4,6869
161
+ huggingface_hub/inference/_generated/types/__pycache__/__init__.cpython-311.pyc,,
162
+ huggingface_hub/inference/_generated/types/__pycache__/audio_classification.cpython-311.pyc,,
163
+ huggingface_hub/inference/_generated/types/__pycache__/audio_to_audio.cpython-311.pyc,,
164
+ huggingface_hub/inference/_generated/types/__pycache__/automatic_speech_recognition.cpython-311.pyc,,
165
+ huggingface_hub/inference/_generated/types/__pycache__/base.cpython-311.pyc,,
166
+ huggingface_hub/inference/_generated/types/__pycache__/chat_completion.cpython-311.pyc,,
167
+ huggingface_hub/inference/_generated/types/__pycache__/depth_estimation.cpython-311.pyc,,
168
+ huggingface_hub/inference/_generated/types/__pycache__/document_question_answering.cpython-311.pyc,,
169
+ huggingface_hub/inference/_generated/types/__pycache__/feature_extraction.cpython-311.pyc,,
170
+ huggingface_hub/inference/_generated/types/__pycache__/fill_mask.cpython-311.pyc,,
171
+ huggingface_hub/inference/_generated/types/__pycache__/image_classification.cpython-311.pyc,,
172
+ huggingface_hub/inference/_generated/types/__pycache__/image_segmentation.cpython-311.pyc,,
173
+ huggingface_hub/inference/_generated/types/__pycache__/image_text_to_image.cpython-311.pyc,,
174
+ huggingface_hub/inference/_generated/types/__pycache__/image_text_to_video.cpython-311.pyc,,
175
+ huggingface_hub/inference/_generated/types/__pycache__/image_to_image.cpython-311.pyc,,
176
+ huggingface_hub/inference/_generated/types/__pycache__/image_to_text.cpython-311.pyc,,
177
+ huggingface_hub/inference/_generated/types/__pycache__/image_to_video.cpython-311.pyc,,
178
+ huggingface_hub/inference/_generated/types/__pycache__/object_detection.cpython-311.pyc,,
179
+ huggingface_hub/inference/_generated/types/__pycache__/question_answering.cpython-311.pyc,,
180
+ huggingface_hub/inference/_generated/types/__pycache__/sentence_similarity.cpython-311.pyc,,
181
+ huggingface_hub/inference/_generated/types/__pycache__/summarization.cpython-311.pyc,,
182
+ huggingface_hub/inference/_generated/types/__pycache__/table_question_answering.cpython-311.pyc,,
183
+ huggingface_hub/inference/_generated/types/__pycache__/text2text_generation.cpython-311.pyc,,
184
+ huggingface_hub/inference/_generated/types/__pycache__/text_classification.cpython-311.pyc,,
185
+ huggingface_hub/inference/_generated/types/__pycache__/text_generation.cpython-311.pyc,,
186
+ huggingface_hub/inference/_generated/types/__pycache__/text_to_audio.cpython-311.pyc,,
187
+ huggingface_hub/inference/_generated/types/__pycache__/text_to_image.cpython-311.pyc,,
188
+ huggingface_hub/inference/_generated/types/__pycache__/text_to_speech.cpython-311.pyc,,
189
+ huggingface_hub/inference/_generated/types/__pycache__/text_to_video.cpython-311.pyc,,
190
+ huggingface_hub/inference/_generated/types/__pycache__/token_classification.cpython-311.pyc,,
191
+ huggingface_hub/inference/_generated/types/__pycache__/translation.cpython-311.pyc,,
192
+ huggingface_hub/inference/_generated/types/__pycache__/video_classification.cpython-311.pyc,,
193
+ huggingface_hub/inference/_generated/types/__pycache__/visual_question_answering.cpython-311.pyc,,
194
+ huggingface_hub/inference/_generated/types/__pycache__/zero_shot_classification.cpython-311.pyc,,
195
+ huggingface_hub/inference/_generated/types/__pycache__/zero_shot_image_classification.cpython-311.pyc,,
196
+ huggingface_hub/inference/_generated/types/__pycache__/zero_shot_object_detection.cpython-311.pyc,,
197
+ huggingface_hub/inference/_generated/types/audio_classification.py,sha256=DGWEvrRPX7xpXlbYY4LMojGcULdEZFTshhNR81rTNcQ,1567
198
+ huggingface_hub/inference/_generated/types/audio_to_audio.py,sha256=2Ep4WkePL7oJwcp5nRJqApwviumGHbft9HhXE9XLHj4,891
199
+ huggingface_hub/inference/_generated/types/automatic_speech_recognition.py,sha256=X0uCj9qwAcOmlKtV3vWH5cAgLGY0PuYIy2eSH7GE1qs,5439
200
+ huggingface_hub/inference/_generated/types/base.py,sha256=EPWp1qudjeEimEAyQ-ptdxpAACoRM8tW342-Ds7pP3I,6938
201
+ huggingface_hub/inference/_generated/types/chat_completion.py,sha256=3yc06ZI0NCZzsaeoxSMWyIHqGc8Vn_6aExncuXa1llE,11100
202
+ huggingface_hub/inference/_generated/types/depth_estimation.py,sha256=5Kn4xNGJg235Cofr1lzO59eRGCuLTZun8z5t6a2do8Q,910
203
+ huggingface_hub/inference/_generated/types/document_question_answering.py,sha256=aUZcrDGexjw8Fnm2rACm_3my77V15NnQHZxj-sa7bjo,3146
204
+ huggingface_hub/inference/_generated/types/feature_extraction.py,sha256=DiO47PqwhdNta_KPDBsXfCPIL6BWNhyCLymxORlqUA0,1509
205
+ huggingface_hub/inference/_generated/types/fill_mask.py,sha256=NhEskgoiMst7U_0cV_S-wryga4_2T5LgpbyQ23vHMp0,1680
206
+ huggingface_hub/inference/_generated/types/image_classification.py,sha256=xWr4OY65EcIIhd7MI610a7xlaAVHQeydi8Gc7tlaPTU,1579
207
+ huggingface_hub/inference/_generated/types/image_segmentation.py,sha256=lZKzbn_gkSi1sYGLb9ryeRr0aDAVrfYh0H5Iiv5JNsY,1935
208
+ huggingface_hub/inference/_generated/types/image_text_to_image.py,sha256=pRQgYKXJbIpEjRBxuIE6NRDtk_km9DSTQ2s2qxkYJRM,2585
209
+ huggingface_hub/inference/_generated/types/image_text_to_video.py,sha256=MVhP8D4eYjpT3hWYkkpuiME-hWY09o7C4rIn_wmnAmY,2450
210
+ huggingface_hub/inference/_generated/types/image_to_image.py,sha256=P9TeMFSnZI_pa6DyinzDPWL0PNm_INJwsqFUEzpwIcU,2262
211
+ huggingface_hub/inference/_generated/types/image_to_text.py,sha256=DCDS0Nqi-4AuATitvZm4EgrzYQuQEQ5lzBcaHuCmHnY,4740
212
+ huggingface_hub/inference/_generated/types/image_to_video.py,sha256=iMCjiFTUza9AW_MyJ1videhYgvMY9QSzQ59kNdTE9QY,2206
213
+ huggingface_hub/inference/_generated/types/object_detection.py,sha256=zNILlyZJh59rNNfqXM5x9uprDCPfEU-bvBtabeKSMzI,1965
214
+ huggingface_hub/inference/_generated/types/question_answering.py,sha256=lIRf8DjRiAsjzWUBEsGt354SB4bvejLokf-8luHw6_o,2845
215
+ huggingface_hub/inference/_generated/types/sentence_similarity.py,sha256=eNGiO4dR-Lft9yOLE0E97jfVyOT_ExDWZW5GeJGdatU,1027
216
+ huggingface_hub/inference/_generated/types/summarization.py,sha256=5Dpt6LRteT-hO9esa3Ty_-xSL5U-zTtVZzy3iKwZRng,1472
217
+ huggingface_hub/inference/_generated/types/table_question_answering.py,sha256=bwn616XJ-eLa5JKzn3m9rZZ3z63INGEUwRSOCWlEh-4,2269
218
+ huggingface_hub/inference/_generated/types/text2text_generation.py,sha256=fotSlPWtIlp_LG26AQvNRXxU-jCUfda5PWsxCkbFeKM,1591
219
+ huggingface_hub/inference/_generated/types/text_classification.py,sha256=uamBzz4YzWQ9mb6yuriykX8r47ZHf0K3eJpOLzB2qJw,1439
220
+ huggingface_hub/inference/_generated/types/text_generation.py,sha256=FRUljypvCSQ2RaiylhlHeLJfHNy8qZvuty6SCB_zcaA,5813
221
+ huggingface_hub/inference/_generated/types/text_to_audio.py,sha256=CiaTUSBdFtOs3gGTosqyQrjCwrN8mVJLRxDDWUtwZpQ,4677
222
+ huggingface_hub/inference/_generated/types/text_to_image.py,sha256=Ju25WIDHE-1n8jlZ_udG4rpAaPYpmghR7-cDgVfuf48,1869
223
+ huggingface_hub/inference/_generated/types/text_to_speech.py,sha256=WqDzWkhZsDcjapkoFrkyjF903SKs7aHhjypsYrn8oBw,4693
224
+ huggingface_hub/inference/_generated/types/text_to_video.py,sha256=KjcDbtChwrIxIdTH6vcesUaMcjL2xjPf2nWEnHazj4Y,1756
225
+ huggingface_hub/inference/_generated/types/token_classification.py,sha256=8KRBlqgFDszaUnPMvdRkZNQaZBtDfBhKZ6SggQldQMM,1894
226
+ huggingface_hub/inference/_generated/types/translation.py,sha256=-j2PC1-qfoxvGMaKesqf5jXelqj0BDlEpfvZ7dsIEJM,1742
227
+ huggingface_hub/inference/_generated/types/video_classification.py,sha256=vfaCqp8MuRMMtGvYCX0x4-AcwEd71kPHgSYJTNIOxLQ,1668
228
+ huggingface_hub/inference/_generated/types/visual_question_answering.py,sha256=sWIB-SuEpW21oU6O5qQF3tt5PavUFsFOa8Xg4upTtek,1654
229
+ huggingface_hub/inference/_generated/types/zero_shot_classification.py,sha256=gx-7WHad7xsNa89iSKSteKHjaHrKbIyzN_nSdJN3HCY,1697
230
+ huggingface_hub/inference/_generated/types/zero_shot_image_classification.py,sha256=JZTQvcbSGrOQlWcPuJvAMT8YziDpBRn1O2RQSw507uY,1449
231
+ huggingface_hub/inference/_generated/types/zero_shot_object_detection.py,sha256=sjdpVUN5zW9aYBymLVUs6i5HVk2qkUBO9ysEjHmsXVM,1605
232
+ huggingface_hub/inference/_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
233
+ huggingface_hub/inference/_mcp/__pycache__/__init__.cpython-311.pyc,,
234
+ huggingface_hub/inference/_mcp/__pycache__/_cli_hacks.cpython-311.pyc,,
235
+ huggingface_hub/inference/_mcp/__pycache__/agent.cpython-311.pyc,,
236
+ huggingface_hub/inference/_mcp/__pycache__/cli.cpython-311.pyc,,
237
+ huggingface_hub/inference/_mcp/__pycache__/constants.cpython-311.pyc,,
238
+ huggingface_hub/inference/_mcp/__pycache__/mcp_client.cpython-311.pyc,,
239
+ huggingface_hub/inference/_mcp/__pycache__/types.cpython-311.pyc,,
240
+ huggingface_hub/inference/_mcp/__pycache__/utils.cpython-311.pyc,,
241
+ huggingface_hub/inference/_mcp/_cli_hacks.py,sha256=kIA8FfRfOWS3SrZrMTbuVOjE6yxfKfMK75Co5egTWHA,3284
242
+ huggingface_hub/inference/_mcp/agent.py,sha256=ufIzMGHore5n252hV5GZPM0ouDXIl6tv5Jl_5gHXnbg,4250
243
+ huggingface_hub/inference/_mcp/cli.py,sha256=RKdVQ_VdEgf1AL_QBCvwrsUQ0Ux4R1yerrE46DrV5C0,9642
244
+ huggingface_hub/inference/_mcp/constants.py,sha256=0Ih6ivEvG-pfF8NwErFngzP4Rof4lQoz6ms_eKSAkUI,2463
245
+ huggingface_hub/inference/_mcp/mcp_client.py,sha256=NxVSp_QZ2616AGi_ECrQKH5wvc1Y3j7qVfJrsUjQgmY,17480
246
+ huggingface_hub/inference/_mcp/types.py,sha256=yHNfPsM9MhD06oeKdkbmrBsW-3WhUeqA26fyfRfx_bk,929
247
+ huggingface_hub/inference/_mcp/utils.py,sha256=gxSB_rBjQ6VrkApKFsxk6-UzhijxkDVNuZrsjW5pL8k,4318
248
+ huggingface_hub/inference/_providers/__init__.py,sha256=fJ2JW4pBXzad2-Yn-q_DozE1PZBIs0pN-dAVFzCJotI,10165
249
+ huggingface_hub/inference/_providers/__pycache__/__init__.cpython-311.pyc,,
250
+ huggingface_hub/inference/_providers/__pycache__/_common.cpython-311.pyc,,
251
+ huggingface_hub/inference/_providers/__pycache__/baseten.cpython-311.pyc,,
252
+ huggingface_hub/inference/_providers/__pycache__/cerebras.cpython-311.pyc,,
253
+ huggingface_hub/inference/_providers/__pycache__/cohere.cpython-311.pyc,,
254
+ huggingface_hub/inference/_providers/__pycache__/deepinfra.cpython-311.pyc,,
255
+ huggingface_hub/inference/_providers/__pycache__/fal_ai.cpython-311.pyc,,
256
+ huggingface_hub/inference/_providers/__pycache__/featherless_ai.cpython-311.pyc,,
257
+ huggingface_hub/inference/_providers/__pycache__/fireworks_ai.cpython-311.pyc,,
258
+ huggingface_hub/inference/_providers/__pycache__/groq.cpython-311.pyc,,
259
+ huggingface_hub/inference/_providers/__pycache__/hf_inference.cpython-311.pyc,,
260
+ huggingface_hub/inference/_providers/__pycache__/novita.cpython-311.pyc,,
261
+ huggingface_hub/inference/_providers/__pycache__/nscale.cpython-311.pyc,,
262
+ huggingface_hub/inference/_providers/__pycache__/openai.cpython-311.pyc,,
263
+ huggingface_hub/inference/_providers/__pycache__/ovhcloud.cpython-311.pyc,,
264
+ huggingface_hub/inference/_providers/__pycache__/publicai.cpython-311.pyc,,
265
+ huggingface_hub/inference/_providers/__pycache__/replicate.cpython-311.pyc,,
266
+ huggingface_hub/inference/_providers/__pycache__/scaleway.cpython-311.pyc,,
267
+ huggingface_hub/inference/_providers/__pycache__/together.cpython-311.pyc,,
268
+ huggingface_hub/inference/_providers/__pycache__/wavespeed.cpython-311.pyc,,
269
+ huggingface_hub/inference/_providers/__pycache__/zai_org.cpython-311.pyc,,
270
+ huggingface_hub/inference/_providers/_common.py,sha256=T3iKT6McNs7GeVfK3q-l7CBbuih2mTFcqkRluQn7GnQ,14308
271
+ huggingface_hub/inference/_providers/baseten.py,sha256=1uucLZp6HiF8OjfeFOkiuJP6WqunP_xzwk3yWPF8vGE,213
272
+ huggingface_hub/inference/_providers/cerebras.py,sha256=QOJ-1U-os7uE7p6eUnn_P_APq-yQhx28be7c3Tq2EuA,210
273
+ huggingface_hub/inference/_providers/cohere.py,sha256=P9kbIuvQ2rXI1yNmgbw5VKFFTE0huLq2k-BCyDkDico,1226
274
+ huggingface_hub/inference/_providers/deepinfra.py,sha256=n8cI9Er-jMRuqBIlyoUQeVuWNJ5cBVNMQu7pwA0hVPA,6661
275
+ huggingface_hub/inference/_providers/fal_ai.py,sha256=XoH1I-3a3FEJF_IBa2FMAYTH4jv6JqRTgFRuo7HSH_Y,12124
276
+ huggingface_hub/inference/_providers/featherless_ai.py,sha256=C8OHdFpoFyA--pawLTekUmUSRq4sw_r0D-cSPekD4kE,1347
277
+ huggingface_hub/inference/_providers/fireworks_ai.py,sha256=go6XPum8u0-g768HJ_r0S4Gb445gZJxnuY_acktz-9c,1188
278
+ huggingface_hub/inference/_providers/groq.py,sha256=JTk2JV4ZOlaohho7zLAFQtk92kGVsPmLJ1hmzcwsqvQ,315
279
+ huggingface_hub/inference/_providers/hf_inference.py,sha256=r6igN2QqILikEm1rOYZLJib5VhKpzmgdMlo2VKctRVo,9328
280
+ huggingface_hub/inference/_providers/novita.py,sha256=ATEoSdPAPLMfx3JpBc0sOyLh4upJYP6xHBuo4YEDYvg,2470
281
+ huggingface_hub/inference/_providers/nscale.py,sha256=T1L2JLI9LqYT9_YEdW76YEtxfDNtdGkoFhH-p2LmSxg,1767
282
+ huggingface_hub/inference/_providers/openai.py,sha256=wwjaaQ55xLmDsDnHpZk52xbuLoGZfWzJkFsE8AdFVaI,1054
283
+ huggingface_hub/inference/_providers/ovhcloud.py,sha256=tdmymlkbddMJKV7NRZ-tH2wymbLPFDTqUSXpWJUXyDQ,314
284
+ huggingface_hub/inference/_providers/publicai.py,sha256=1I2W6rORloB5QHSvky4njZO2XKLTwA-kPdNoauoT5rg,210
285
+ huggingface_hub/inference/_providers/replicate.py,sha256=hte0ZB2RtGFwpAuLrFp2Gbgsn3EOlccCnJkWTDTW__A,6027
286
+ huggingface_hub/inference/_providers/scaleway.py,sha256=MfIc7ZND1sPr__rOmNHZVg0VpECQo0bVyksgIm_32xQ,1174
287
+ huggingface_hub/inference/_providers/together.py,sha256=lrymDZ86n5yoR_Zz7o3AzzSePyo0s7BOBU5digLxb5o,12220
288
+ huggingface_hub/inference/_providers/wavespeed.py,sha256=MGM7Y7r2nQiH_EH0t5UE1o1fT-o3sS7RaQlicS9WHsg,5028
289
+ huggingface_hub/inference/_providers/zai_org.py,sha256=gLJZOEmCPmUZvdM7VDn2nxm4ac3veHdoMgQNR63UeWE,4739
290
+ huggingface_hub/lfs.py,sha256=8ymYNHRXgvgUUM9w0EAnC-vkSOOq_1EFJEJNoevoeE8,16588
291
+ huggingface_hub/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
292
+ huggingface_hub/repocard.py,sha256=XIPt7cAr-MYRROcGgQP0yBJQeqannVm1AuUrOLXeUCw,35596
293
+ huggingface_hub/repocard_data.py,sha256=txcJRf-dVg_h9LN0Lrx45-c9GV1s9q930PzrpJbFhs4,34476
294
+ huggingface_hub/serialization/__init__.py,sha256=jCiw_vVQYW52gwVfWiqgocf2Q19kGTQlRGVpf-4SLP8,963
295
+ huggingface_hub/serialization/__pycache__/__init__.cpython-311.pyc,,
296
+ huggingface_hub/serialization/__pycache__/_base.cpython-311.pyc,,
297
+ huggingface_hub/serialization/__pycache__/_dduf.cpython-311.pyc,,
298
+ huggingface_hub/serialization/__pycache__/_torch.cpython-311.pyc,,
299
+ huggingface_hub/serialization/_base.py,sha256=JWIAmCAjiINVvwszYKeaHXUCK4CsOW-_ELIH2Yuax3A,8397
300
+ huggingface_hub/serialization/_dduf.py,sha256=FmGRg5wkXI5sNCgZgCNJFmqb_nVrrQYOHf4Lqq0d64I,15385
301
+ huggingface_hub/serialization/_torch.py,sha256=q09EfkS8UW5FiFTj3u9gpnJKL9zmBwQyoNxHViLX2K4,55811
302
+ huggingface_hub/templates/datasetcard_template.md,sha256=W-EMqR6wndbrnZorkVv56URWPG49l7MATGeI015kTvs,5503
303
+ huggingface_hub/templates/modelcard_template.md,sha256=4AqArS3cqdtbit5Bo-DhjcnDFR-pza5hErLLTPM4Yuc,6870
304
+ huggingface_hub/utils/__init__.py,sha256=G4B1j5R6VcyVmDA68Q29bRrhFh_SHg03C40oSmCyxAM,13210
305
+ huggingface_hub/utils/__pycache__/__init__.cpython-311.pyc,,
306
+ huggingface_hub/utils/__pycache__/_auth.cpython-311.pyc,,
307
+ huggingface_hub/utils/__pycache__/_cache_assets.cpython-311.pyc,,
308
+ huggingface_hub/utils/__pycache__/_cache_manager.cpython-311.pyc,,
309
+ huggingface_hub/utils/__pycache__/_chunk_utils.cpython-311.pyc,,
310
+ huggingface_hub/utils/__pycache__/_datetime.cpython-311.pyc,,
311
+ huggingface_hub/utils/__pycache__/_deprecation.cpython-311.pyc,,
312
+ huggingface_hub/utils/__pycache__/_detect_agent.cpython-311.pyc,,
313
+ huggingface_hub/utils/__pycache__/_dotenv.cpython-311.pyc,,
314
+ huggingface_hub/utils/__pycache__/_experimental.cpython-311.pyc,,
315
+ huggingface_hub/utils/__pycache__/_fixes.cpython-311.pyc,,
316
+ huggingface_hub/utils/__pycache__/_git_credential.cpython-311.pyc,,
317
+ huggingface_hub/utils/__pycache__/_headers.cpython-311.pyc,,
318
+ huggingface_hub/utils/__pycache__/_hf_uris.cpython-311.pyc,,
319
+ huggingface_hub/utils/__pycache__/_http.cpython-311.pyc,,
320
+ huggingface_hub/utils/__pycache__/_lfs.cpython-311.pyc,,
321
+ huggingface_hub/utils/__pycache__/_oauth_device.cpython-311.pyc,,
322
+ huggingface_hub/utils/__pycache__/_pagination.cpython-311.pyc,,
323
+ huggingface_hub/utils/__pycache__/_parsing.cpython-311.pyc,,
324
+ huggingface_hub/utils/__pycache__/_paths.cpython-311.pyc,,
325
+ huggingface_hub/utils/__pycache__/_runtime.cpython-311.pyc,,
326
+ huggingface_hub/utils/__pycache__/_safetensors.cpython-311.pyc,,
327
+ huggingface_hub/utils/__pycache__/_shared_blobs.cpython-311.pyc,,
328
+ huggingface_hub/utils/__pycache__/_subprocess.cpython-311.pyc,,
329
+ huggingface_hub/utils/__pycache__/_telemetry.cpython-311.pyc,,
330
+ huggingface_hub/utils/__pycache__/_terminal.cpython-311.pyc,,
331
+ huggingface_hub/utils/__pycache__/_typing.cpython-311.pyc,,
332
+ huggingface_hub/utils/__pycache__/_validators.cpython-311.pyc,,
333
+ huggingface_hub/utils/__pycache__/_verification.cpython-311.pyc,,
334
+ huggingface_hub/utils/__pycache__/_xet.cpython-311.pyc,,
335
+ huggingface_hub/utils/__pycache__/_xet_progress_reporting.cpython-311.pyc,,
336
+ huggingface_hub/utils/__pycache__/endpoint_helpers.cpython-311.pyc,,
337
+ huggingface_hub/utils/__pycache__/insecure_hashlib.cpython-311.pyc,,
338
+ huggingface_hub/utils/__pycache__/logging.cpython-311.pyc,,
339
+ huggingface_hub/utils/__pycache__/sha.cpython-311.pyc,,
340
+ huggingface_hub/utils/__pycache__/tqdm.cpython-311.pyc,,
341
+ huggingface_hub/utils/_auth.py,sha256=j0P_kjWjtx4CF8bTQ1TSzpcZyq_OcS_5WeNXtbj6mCU,20355
342
+ huggingface_hub/utils/_cache_assets.py,sha256=nnzHRtQAR50dQeIK6qKddsmjjTW9v9HZ7b9bq7PJqss,5691
343
+ huggingface_hub/utils/_cache_manager.py,sha256=VpWeVo--j5JdBL0entuVZ7nZX85UM740YQSthxGxstA,42376
344
+ huggingface_hub/utils/_chunk_utils.py,sha256=pTjy8Z-KLU4W_6D3OUh3E8lCodWDCd6aJwjNDU0C5U8,2121
345
+ huggingface_hub/utils/_datetime.py,sha256=tbNyI0Dkh27oScPUtLIT_8apqIIkXZYbigjOn9S3aMw,2755
346
+ huggingface_hub/utils/_deprecation.py,sha256=n4kNHbGipquSObJ-gxodcfd6lqoe_8s-VIsTuo3Oruk,4865
347
+ huggingface_hub/utils/_detect_agent.py,sha256=Iw2KW9BUZWfIypn9CtiTmEibHwKK9xx5Ar48z1cMU-Q,7337
348
+ huggingface_hub/utils/_dotenv.py,sha256=uy9Y6Y_C4-tHelJ_IwfOZ5jr7xvbgPP9g5kQ_Xd3Sck,3279
349
+ huggingface_hub/utils/_experimental.py,sha256=q9vUvc1JybVFRQ0GRREG-BLouZEJC_40MxcwbAlOud0,2464
350
+ huggingface_hub/utils/_fixes.py,sha256=jTK1VLmc0ZC9ROSXjKoL5F6kOZFByzirRWIdXxhBfWU,4124
351
+ huggingface_hub/utils/_git_credential.py,sha256=1BhjvIScCOAToDORLOKrR3Szs-m0E5AYHPmC0SD7Nrs,4548
352
+ huggingface_hub/utils/_headers.py,sha256=Q9bu9mvOpm-9rfv-YRlr_Ywy_aMZkmRcN3MbVEcJAJA,8234
353
+ huggingface_hub/utils/_hf_uris.py,sha256=6lQUCBmPa9vqSVXsWORY88CxLKjWReMOOoDvup02ZHM,27559
354
+ huggingface_hub/utils/_http.py,sha256=S9BjQeUjMpa7cPhWIY2Oy-AT84RdqgePzQEmjYDSpsk,49263
355
+ huggingface_hub/utils/_lfs.py,sha256=LwCh0cU0B1UpGMVzDL0QMR6v_u3H6gmCbVbnCO_j0UQ,3974
356
+ huggingface_hub/utils/_oauth_device.py,sha256=lnaqrfd-RiE5onwdcEowbmtPLjIYkGI_myt3G9jylhg,7988
357
+ huggingface_hub/utils/_pagination.py,sha256=Wq-xzJUYrhOvObCrG__uKs_d6erILzdmSdEduhp8Jw8,1912
358
+ huggingface_hub/utils/_parsing.py,sha256=rV7ygUnWsTCukZ11Z2WHHD4Tgv2duk3wbY9V3VmoDuA,3664
359
+ huggingface_hub/utils/_paths.py,sha256=YvUvaePxtLyxzAPclttpKT4O56BThcmG8SSwoxdNhyo,7371
360
+ huggingface_hub/utils/_runtime.py,sha256=vmatlg8IOfnAADS4ylrVSqhApgO7kfEE9tG5RHLKS7o,13778
361
+ huggingface_hub/utils/_safetensors.py,sha256=-8Ak60JNGEnEnepzQdZtGVTm6zJUQOJyhvXjSBqUphc,4438
362
+ huggingface_hub/utils/_shared_blobs.py,sha256=ACd76RULXEJop2dfb1rovyd8tQF09ooMI6cnZNukBV8,23954
363
+ huggingface_hub/utils/_subprocess.py,sha256=tFVBBNot_HLVqQ79y873TGb12C4PUTMwub-GhzDTemE,4542
364
+ huggingface_hub/utils/_telemetry.py,sha256=Tpa3YmOLhK_MEnL2i2fRLQy8aqAEZWbj6MKC18Hs8BA,4824
365
+ huggingface_hub/utils/_terminal.py,sha256=snvsBJL_X1KfszkCFECyh69xdmlOLalZ8_ErWTUdXss,9252
366
+ huggingface_hub/utils/_typing.py,sha256=1LeE785YedppXSR9a1fQDu5rhTxX5v9kBYBaHrP65rA,3542
367
+ huggingface_hub/utils/_validators.py,sha256=vTtNeF5i2qJ_FLpJzi_xrcEdAJFgB9Jm-c3RuMFtmPM,8590
368
+ huggingface_hub/utils/_verification.py,sha256=45uSEyJREMwKb-18waKnegemUqdI-_rK8RrPM6EnvZs,5432
369
+ huggingface_hub/utils/_xet.py,sha256=gKJMQ_hvTJBE9K_dHY9QUw_p0H9_wdzEWsuxVZqALmg,12486
370
+ huggingface_hub/utils/_xet_progress_reporting.py,sha256=6icC9DdyNFNkAyBghKa-7LWBGfR068lzNmEkib9pAb8,17761
371
+ huggingface_hub/utils/endpoint_helpers.py,sha256=9VtIAlxQ5H_4y30sjCAgbu7XCqAtNLC7aRYxaNn0hLI,2366
372
+ huggingface_hub/utils/insecure_hashlib.py,sha256=z3dVUFvdBZ8kQI_8Vzvvlr3ims-EBiY-SYPdnzIKOkw,1008
373
+ huggingface_hub/utils/logging.py,sha256=WaXk5gRa8Ml_LUIH34QCr8suYj8i_8Wot4IDnYJyWyM,4870
374
+ huggingface_hub/utils/sha.py,sha256=h8wxheZpcv671RhtiIFcFmQTDSrogN3kwQx3ZaNEUHg,2121
375
+ huggingface_hub/utils/tqdm.py,sha256=AdrS7egXi6Vx8wn974qoWRVipFgOlTG6WU8g_urd-_g,16730
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/REQUESTED ADDED
File without changes
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [console_scripts]
2
+ hf = huggingface_hub.cli.hf:main
3
+ tiny-agents = huggingface_hub.inference._mcp.cli:app
4
+
5
+ [fsspec.specs]
6
+ hf = huggingface_hub.HfFileSystem
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.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
+ limitations under the License.
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub-2.2.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ huggingface_hub
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/cache.cpython-311.pyc ADDED
Binary file (45.5 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/collections.cpython-311.pyc ADDED
Binary file (12.7 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/datasets.cpython-311.pyc ADDED
Binary file (14.1 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/discussions.cpython-311.pyc ADDED
Binary file (16.7 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/download.cpython-311.pyc ADDED
Binary file (10.7 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/extensions.cpython-311.pyc ADDED
Binary file (40.3 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/hf.cpython-311.pyc ADDED
Binary file (7.13 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/inference_endpoints.cpython-311.pyc ADDED
Binary file (39.1 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/jobs.cpython-311.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35a2740986b84a5f6f0bfe80bdef04c13fe99b0e66caca6f011fe039e73617f8
3
+ size 110851
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/lfs.cpython-311.pyc ADDED
Binary file (7.26 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/models.cpython-311.pyc ADDED
Binary file (12.4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/papers.cpython-311.pyc ADDED
Binary file (7.15 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/repos.cpython-311.pyc ADDED
Binary file (25.5 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/sandbox.cpython-311.pyc ADDED
Binary file (27.4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/skills.cpython-311.pyc ADDED
Binary file (27.4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/spaces.cpython-311.pyc ADDED
Binary file (57.7 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/system.cpython-311.pyc ADDED
Binary file (4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/upload.cpython-311.pyc ADDED
Binary file (11.7 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/__pycache__/webhooks.cpython-311.pyc ADDED
Binary file (14 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_city_game.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interactive isometric city explorer — easter egg for `hf repos ls --explore`."""
2
+
3
+ import dataclasses
4
+ import math
5
+ import os
6
+ import random
7
+ import re
8
+ import select
9
+ import shutil
10
+ import sys
11
+ import time
12
+
13
+ from huggingface_hub.hf_api import RepoStorageInfo
14
+
15
+ from ._file_listing import format_size
16
+
17
+
18
+ Color = tuple[int, int, int]
19
+
20
+ # (top_face, left_face, right_face) — lighter to darker for 3D effect
21
+ _TYPE_COLORS: dict[str, tuple[Color, Color, Color]] = {
22
+ "model": ((175, 148, 240), (138, 112, 208), (105, 80, 180)),
23
+ "dataset": ((245, 128, 128), (222, 92, 92), (190, 60, 60)),
24
+ "space": ((245, 175, 85), (218, 140, 55), (185, 110, 30)),
25
+ "bucket": ((112, 185, 242), (70, 150, 220), (40, 118, 192)),
26
+ }
27
+ _EXTRA_COLORS: tuple[Color, Color, Color] = ((168, 176, 188), (128, 136, 148), (90, 98, 110))
28
+ _GRID_COLOR: Color = (178, 182, 190)
29
+
30
+ _DX = 4 # isometric half-width (pixels)
31
+ _DY = 2 # isometric half-height (pixels)
32
+ _MAX_H = 16 # tallest tile (pixels)
33
+ _MIN_H = 1
34
+ _COLS = 6
35
+ _EXT = 1 # grid extension beyond tiles
36
+ _MAX_TILES = 30
37
+
38
+ # Cursor sprite — pixel art arrow pointer
39
+ _OUTLINE: Color = (30, 30, 30)
40
+ _FILL: Color = (255, 255, 255)
41
+
42
+ _CURSOR_GRID = [
43
+ " X ",
44
+ " XWX ",
45
+ "XWWWX",
46
+ " XWX ",
47
+ " X ",
48
+ ]
49
+ _CURSOR_PALETTE: dict[str, Color] = {
50
+ "X": _OUTLINE,
51
+ "W": _FILL,
52
+ }
53
+ _CURSOR_H = len(_CURSOR_GRID)
54
+
55
+ _MOVE_FRAMES = 8
56
+ _MOVE_DELAY = 0.03
57
+ _CURSOR_PAD = _CURSOR_H + 16
58
+ _GAP = 3
59
+ _MIN_TERM_W = 100
60
+ _MIN_TERM_H = 24
61
+ _SUMMARY_W = 24
62
+
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # Data structures
66
+ # ---------------------------------------------------------------------------
67
+
68
+
69
+ @dataclasses.dataclass
70
+ class TileInfo:
71
+ grid_row: int
72
+ grid_col: int
73
+ height: int
74
+ top: Color
75
+ left: Color
76
+ right: Color
77
+ repo: RepoStorageInfo | None
78
+
79
+
80
+ @dataclasses.dataclass
81
+ class CityData:
82
+ tiles: list[TileInfo]
83
+ rows: int
84
+ cols: int
85
+ x_off: int
86
+ y_off: int
87
+ buf_w: int
88
+ buf_h: int
89
+ total_storage: int
90
+ extra_count: int
91
+ extra_storage: int
92
+ all_repos: list[RepoStorageInfo]
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # City layout
97
+ # ---------------------------------------------------------------------------
98
+
99
+
100
+ def _prepare_city_data(repos: list[RepoStorageInfo]) -> CityData:
101
+ sorted_repos = sorted(repos, key=lambda r: r.storage, reverse=True)
102
+ display = sorted_repos[:_MAX_TILES]
103
+ extra_count = max(0, len(sorted_repos) - _MAX_TILES)
104
+ extra_storage = sum(r.storage for r in sorted_repos[_MAX_TILES:])
105
+ total_storage = sum(r.storage for r in repos)
106
+ max_storage = max(1, display[0].storage)
107
+
108
+ n = len(display) + (1 if extra_count > 0 else 0)
109
+ cols = min(n, _COLS)
110
+ rows = math.ceil(n / cols) if cols > 0 else 1
111
+
112
+ tiles: list[TileInfo] = []
113
+ for i, repo in enumerate(display):
114
+ r, c = divmod(i, cols)
115
+ h = max(_MIN_H, round(math.sqrt(repo.storage / max_storage) * _MAX_H))
116
+ top, left, right = _TYPE_COLORS.get(repo.type, _EXTRA_COLORS)
117
+ tiles.append(TileInfo(r, c, h, top, left, right, repo))
118
+ if extra_count > 0:
119
+ r, c = divmod(len(display), cols)
120
+ h = max(_MIN_H, round(math.sqrt(extra_storage / max_storage) * _MAX_H))
121
+ tiles.append(TileInfo(r, c, h, *_EXTRA_COLORS, None))
122
+
123
+ r_lo, r_hi = -_EXT, rows - 1 + _EXT
124
+ c_lo, c_hi = -_EXT, cols - 1 + _EXT
125
+
126
+ xs: list[int] = []
127
+ ys: list[int] = []
128
+ for rr in range(r_lo, r_hi + 1):
129
+ for cc in range(c_lo, c_hi + 1):
130
+ cx, cy = (cc - rr) * _DX, (cc + rr) * _DY
131
+ xs.extend([cx - _DX, cx + _DX])
132
+ ys.extend([cy, cy + 2 * _DY])
133
+ for tile in tiles:
134
+ ys.append((tile.grid_col + tile.grid_row) * _DY - tile.height)
135
+
136
+ x_off = -min(xs)
137
+ y_off = -min(ys)
138
+ buf_w = max(xs) - min(xs) + 1
139
+ buf_h = max(ys) - min(ys) + 1
140
+ if buf_h % 2:
141
+ buf_h += 1
142
+
143
+ return CityData(
144
+ tiles=tiles,
145
+ rows=rows,
146
+ cols=cols,
147
+ x_off=x_off,
148
+ y_off=y_off,
149
+ buf_w=buf_w,
150
+ buf_h=buf_h,
151
+ total_storage=total_storage,
152
+ extra_count=extra_count,
153
+ extra_storage=extra_storage,
154
+ all_repos=repos,
155
+ )
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # Drawing primitives
160
+ # ---------------------------------------------------------------------------
161
+
162
+
163
+ def _draw_diamond_outline(buf: list[list[Color | None]], cx: int, cy: int) -> None:
164
+ t = (cx, cy)
165
+ r = (cx + _DX, cy + _DY)
166
+ b = (cx, cy + 2 * _DY)
167
+ ll = (cx - _DX, cy + _DY)
168
+ _draw_line(buf, *t, *r, _GRID_COLOR)
169
+ _draw_line(buf, *r, *b, _GRID_COLOR)
170
+ _draw_line(buf, *b, *ll, _GRID_COLOR)
171
+ _draw_line(buf, *ll, *t, _GRID_COLOR)
172
+
173
+
174
+ def _draw_block(
175
+ buf: list[list[Color | None]],
176
+ cx: int,
177
+ cy: int,
178
+ h: int,
179
+ top: Color,
180
+ left: Color,
181
+ right: Color,
182
+ ) -> None:
183
+ _fill_poly(
184
+ buf,
185
+ [(cx - _DX, cy + _DY - h), (cx, cy + 2 * _DY - h), (cx, cy + 2 * _DY), (cx - _DX, cy + _DY)],
186
+ left,
187
+ )
188
+ _fill_poly(
189
+ buf,
190
+ [(cx, cy + 2 * _DY - h), (cx + _DX, cy + _DY - h), (cx + _DX, cy + _DY), (cx, cy + 2 * _DY)],
191
+ right,
192
+ )
193
+ _fill_poly(
194
+ buf,
195
+ [(cx, cy - h), (cx + _DX, cy + _DY - h), (cx, cy + 2 * _DY - h), (cx - _DX, cy + _DY - h)],
196
+ top,
197
+ )
198
+
199
+
200
+ def _fill_poly(buf: list[list[Color | None]], verts: list[tuple[int, int]], color: Color) -> None:
201
+ bh = len(buf)
202
+ bw = len(buf[0]) if buf else 0
203
+ all_y = [v[1] for v in verts]
204
+ y0 = max(0, min(all_y))
205
+ y1 = min(bh - 1, max(all_y))
206
+ n = len(verts)
207
+ for y in range(y0, y1 + 1):
208
+ xl: float = float("inf")
209
+ xr: float = float("-inf")
210
+ for i in range(n):
211
+ ax, ay = verts[i]
212
+ bx, by = verts[(i + 1) % n]
213
+ if ay == by:
214
+ if y == ay:
215
+ xl = min(xl, float(min(ax, bx)))
216
+ xr = max(xr, float(max(ax, bx)))
217
+ continue
218
+ if not (min(ay, by) <= y <= max(ay, by)):
219
+ continue
220
+ t = (y - ay) / (by - ay)
221
+ ix = ax + t * (bx - ax)
222
+ xl = min(xl, ix)
223
+ xr = max(xr, ix)
224
+ if xl <= xr:
225
+ for x in range(max(0, round(xl)), min(bw, round(xr) + 1)):
226
+ buf[y][x] = color
227
+
228
+
229
+ def _draw_line(buf: list[list[Color | None]], x0: int, y0: int, x1: int, y1: int, color: Color) -> None:
230
+ bh = len(buf)
231
+ bw = len(buf[0]) if buf else 0
232
+ dx = abs(x1 - x0)
233
+ dy = abs(y1 - y0)
234
+ steps = max(dx, dy)
235
+ if steps == 0:
236
+ if 0 <= y0 < bh and 0 <= x0 < bw:
237
+ buf[y0][x0] = color
238
+ return
239
+ xi = (x1 - x0) / steps
240
+ yi = (y1 - y0) / steps
241
+ fx, fy = float(x0), float(y0)
242
+ for _ in range(steps + 1):
243
+ px, py = round(fx), round(fy)
244
+ if 0 <= py < bh and 0 <= px < bw:
245
+ buf[py][px] = color
246
+ fx += xi
247
+ fy += yi
248
+
249
+
250
+ # ---------------------------------------------------------------------------
251
+ # Pixel buffer → terminal
252
+ # ---------------------------------------------------------------------------
253
+
254
+ _ANSI_RE = re.compile(r"\033\[[0-9;]*m")
255
+
256
+
257
+ def _strip_ansi(s: str) -> str:
258
+ return _ANSI_RE.sub("", s)
259
+
260
+
261
+ def _visible_len(s: str) -> int:
262
+ return len(_strip_ansi(s))
263
+
264
+
265
+ def _pixels_to_lines(buf: list[list[Color | None]]) -> list[str]:
266
+ height = len(buf)
267
+ width = len(buf[0]) if buf else 0
268
+ lines: list[str] = []
269
+ for row in range(0, height, 2):
270
+ last = -1
271
+ for col in range(width - 1, -1, -1):
272
+ top = buf[row][col]
273
+ bot = buf[row + 1][col] if row + 1 < height else None
274
+ if top or bot:
275
+ last = col
276
+ break
277
+ if last < 0:
278
+ lines.append("")
279
+ continue
280
+
281
+ parts: list[str] = []
282
+ cfg: Color | None = None
283
+ cbg: Color | None = None
284
+
285
+ for col in range(last + 1):
286
+ top = buf[row][col]
287
+ bot = buf[row + 1][col] if row + 1 < height else None
288
+
289
+ if not top and not bot:
290
+ if cfg is not None or cbg is not None:
291
+ parts.append("\033[0m")
292
+ cfg = cbg = None
293
+ parts.append(" ")
294
+ continue
295
+
296
+ if top and bot and top == bot:
297
+ nfg, nbg, ch = top, None, "█"
298
+ elif top and bot:
299
+ nfg, nbg, ch = bot, top, "▄"
300
+ elif top:
301
+ nfg, nbg, ch = top, None, "▀"
302
+ else:
303
+ nfg, nbg, ch = bot, None, "▄" # type: ignore[assignment]
304
+
305
+ esc = ""
306
+ if nfg != cfg:
307
+ esc += f"\033[38;2;{nfg[0]};{nfg[1]};{nfg[2]}m"
308
+ cfg = nfg
309
+ if nbg != cbg:
310
+ esc += "\033[49m" if nbg is None else f"\033[48;2;{nbg[0]};{nbg[1]};{nbg[2]}m"
311
+ cbg = nbg
312
+ parts.append(esc + ch)
313
+
314
+ if cfg is not None or cbg is not None:
315
+ parts.append("\033[0m")
316
+ lines.append("".join(parts))
317
+ return lines
318
+
319
+
320
+ # ---------------------------------------------------------------------------
321
+ # Rendering
322
+ # ---------------------------------------------------------------------------
323
+
324
+
325
+ def _render_base_buffer(city: CityData) -> list[list[Color | None]]:
326
+ buf: list[list[Color | None]] = [[None] * city.buf_w for _ in range(city.buf_h)]
327
+
328
+ for tile in city.tiles:
329
+ cx = city.x_off + (tile.grid_col - tile.grid_row) * _DX
330
+ cy = city.y_off + (tile.grid_col + tile.grid_row) * _DY
331
+ _draw_diamond_outline(buf, cx, cy)
332
+
333
+ sorted_tiles = sorted(city.tiles, key=lambda t: (t.grid_row + t.grid_col, t.grid_col))
334
+ for tile in sorted_tiles:
335
+ cx = city.x_off + (tile.grid_col - tile.grid_row) * _DX
336
+ cy = city.y_off + (tile.grid_col + tile.grid_row) * _DY
337
+ _draw_block(buf, cx, cy, tile.height, tile.top, tile.left, tile.right)
338
+
339
+ return buf
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # Summary panel
344
+ # ---------------------------------------------------------------------------
345
+
346
+
347
+ def _colored_square(color: Color) -> str:
348
+ return f"\033[38;2;{color[0]};{color[1]};{color[2]}m■\033[0m"
349
+
350
+
351
+ def _build_summary(
352
+ repos: list[RepoStorageInfo],
353
+ total_storage: int,
354
+ extra_count: int,
355
+ ) -> list[str]:
356
+ lines: list[str] = [""]
357
+ lines.append(" Storage Overview")
358
+ lines.append(" " + "─" * 16)
359
+ lines.append(f" {format_size(total_storage, human_readable=True)} total")
360
+ lines.append("")
361
+
362
+ order = ["model", "dataset", "space", "bucket"]
363
+ labels = {"model": "Models", "dataset": "Datasets", "space": "Spaces", "bucket": "Buckets"}
364
+ for rtype in order:
365
+ group = [r for r in repos if r.type == rtype]
366
+ if not group:
367
+ continue
368
+ storage = sum(r.storage for r in group)
369
+ sq = _colored_square(_TYPE_COLORS[rtype][0])
370
+ lines.append(f" {sq} {labels[rtype]}")
371
+ lines.append(f" {len(group)} repos · {format_size(storage, human_readable=True)}")
372
+ lines.append("")
373
+
374
+ if extra_count > 0:
375
+ sq = _colored_square(_EXTRA_COLORS[0])
376
+ lines.append(f" {sq} +{extra_count} more repos")
377
+
378
+ return lines
379
+
380
+
381
+ # ---------------------------------------------------------------------------
382
+ # Cursor
383
+ # ---------------------------------------------------------------------------
384
+
385
+
386
+ def _build_cursor() -> list[tuple[int, int, Color]]:
387
+ pixels: list[tuple[int, int, Color]] = []
388
+ for ri, row in enumerate(_CURSOR_GRID):
389
+ for ci, ch in enumerate(row):
390
+ if ch in _CURSOR_PALETTE:
391
+ pixels.append((ci - len(row) // 2, ri - _CURSOR_H + 1, _CURSOR_PALETTE[ch]))
392
+ return pixels
393
+
394
+
395
+ _CURSOR_PIXELS = _build_cursor()
396
+
397
+
398
+ # ---------------------------------------------------------------------------
399
+ # Interactive game
400
+ # ---------------------------------------------------------------------------
401
+
402
+
403
+ def run_city_game(repos: list[RepoStorageInfo]) -> None:
404
+ """Launch the interactive city explorer."""
405
+ if not repos:
406
+ print("No repositories found.")
407
+ return
408
+
409
+ try:
410
+ import termios
411
+ import tty
412
+ except ImportError:
413
+ print("Interactive mode requires a Unix-like terminal (Linux/macOS).")
414
+ return
415
+
416
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
417
+ print("Interactive mode requires a terminal.")
418
+ return
419
+
420
+ term = shutil.get_terminal_size()
421
+ if term.columns < _MIN_TERM_W or term.lines < _MIN_TERM_H:
422
+ print(f"Your terminal is {term.columns}×{term.lines} characters.")
423
+ print(f"Please resize to at least {_MIN_TERM_W}×{_MIN_TERM_H} to explore the city!")
424
+ return
425
+
426
+ city = _prepare_city_data(repos)
427
+
428
+ tiles_with_repos = [t for t in city.tiles if t.repo is not None]
429
+ start_tile = random.choice(tiles_with_repos) if tiles_with_repos else city.tiles[0]
430
+
431
+ fd = sys.stdin.fileno()
432
+ old_settings = termios.tcgetattr(fd)
433
+ try:
434
+ tty.setraw(fd)
435
+ sys.stdout.write("\033[?1049h\033[?25l\033[2J")
436
+ sys.stdout.flush()
437
+ _game_loop(city, start_tile.grid_row, start_tile.grid_col)
438
+ finally:
439
+ sys.stdout.write("\033[?25h\033[?1049l")
440
+ sys.stdout.flush()
441
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
442
+
443
+
444
+ def _game_loop(city: CityData, cur_row: int, cur_col: int) -> None:
445
+ tile_map: dict[tuple[int, int], TileInfo] = {(t.grid_row, t.grid_col): t for t in city.tiles}
446
+ city = dataclasses.replace(city, buf_h=city.buf_h + _CURSOR_PAD, y_off=city.y_off + _CURSOR_PAD)
447
+ base_buf = _render_base_buffer(city)
448
+
449
+ summary = _build_summary(city.all_repos, city.total_storage, city.extra_count)
450
+
451
+ # Intro: cursor drops onto starting tile
452
+ tx, ty = _tile_top_center(city, cur_row, cur_col, tile_map)
453
+ for i in range(1, _MOVE_FRAMES + 1):
454
+ t = i / _MOVE_FRAMES
455
+ t = t * t * (3 - 2 * t)
456
+ drop_y = ty - 16 * (1 - t)
457
+ frame = _copy_buf(base_buf)
458
+ _highlight_tile(frame, city, tile_map[(cur_row, cur_col)])
459
+ _draw_cursor(frame, tx, round(drop_y))
460
+ _present(city, frame, tile_map.get((cur_row, cur_col)), summary)
461
+ time.sleep(_MOVE_DELAY)
462
+
463
+ while True:
464
+ cx, cy = _tile_top_center(city, cur_row, cur_col, tile_map)
465
+ frame = _copy_buf(base_buf)
466
+ _highlight_tile(frame, city, tile_map[(cur_row, cur_col)])
467
+ _draw_cursor(frame, cx, cy)
468
+ _present(city, frame, tile_map.get((cur_row, cur_col)), summary)
469
+
470
+ key = _read_key()
471
+ if key in ("q", "Q", "esc", "\x03"):
472
+ return
473
+
474
+ dr, dc = _key_to_direction(key)
475
+ if dr == 0 and dc == 0:
476
+ continue
477
+
478
+ nr, nc = cur_row + dr, cur_col + dc
479
+ if (nr, nc) not in tile_map:
480
+ continue
481
+
482
+ ex, ey = _tile_top_center(city, nr, nc, tile_map)
483
+ for i in range(1, _MOVE_FRAMES + 1):
484
+ t = i / _MOVE_FRAMES
485
+ t = t * t * (3 - 2 * t)
486
+ bx = cx + (ex - cx) * t
487
+ by = cy + (ey - cy) * t
488
+ frame = _copy_buf(base_buf)
489
+ _highlight_tile(frame, city, tile_map[(nr, nc)])
490
+ _draw_cursor(frame, round(bx), round(by))
491
+ _present(city, frame, tile_map.get((nr, nc)), summary)
492
+ time.sleep(_MOVE_DELAY)
493
+
494
+ cur_row, cur_col = nr, nc
495
+
496
+
497
+ def _tile_top_center(city: CityData, row: int, col: int, tile_map: dict[tuple[int, int], TileInfo]) -> tuple[int, int]:
498
+ tile = tile_map.get((row, col))
499
+ h = tile.height if tile else 1
500
+ cx = city.x_off + (col - row) * _DX
501
+ cy = city.y_off + (col + row) * _DY
502
+ return cx, cy + _DY - h
503
+
504
+
505
+ def _key_to_direction(key: str) -> tuple[int, int]:
506
+ match key:
507
+ case "w" | "W" | "\x1b[A":
508
+ return -1, 0
509
+ case "s" | "S" | "\x1b[B":
510
+ return 1, 0
511
+ case "a" | "A" | "\x1b[D":
512
+ return 0, -1
513
+ case "d" | "D" | "\x1b[C":
514
+ return 0, 1
515
+ case _:
516
+ return 0, 0
517
+
518
+
519
+ def _draw_cursor(buf: list[list[Color | None]], cx: int, cy: int) -> None:
520
+ bh = len(buf)
521
+ bw = len(buf[0]) if buf else 0
522
+ for dx, dy, color in _CURSOR_PIXELS:
523
+ px, py = cx + dx, cy + dy
524
+ if 0 <= py < bh and 0 <= px < bw:
525
+ buf[py][px] = color
526
+
527
+
528
+ def _highlight_tile(buf: list[list[Color | None]], city: CityData, tile: TileInfo) -> None:
529
+ cx = city.x_off + (tile.grid_col - tile.grid_row) * _DX
530
+ cy = city.y_off + (tile.grid_col + tile.grid_row) * _DY
531
+ h = tile.height
532
+ _fill_poly(
533
+ buf,
534
+ [(cx, cy - h), (cx + _DX, cy + _DY - h), (cx, cy + 2 * _DY - h), (cx - _DX, cy + _DY - h)],
535
+ _brighten(tile.top, 35),
536
+ )
537
+
538
+
539
+ def _brighten(color: Color, amount: int) -> Color:
540
+ return (min(255, color[0] + amount), min(255, color[1] + amount), min(255, color[2] + amount))
541
+
542
+
543
+ def _present(
544
+ city: CityData,
545
+ buf: list[list[Color | None]],
546
+ tile: TileInfo | None,
547
+ summary: list[str],
548
+ ) -> None:
549
+ city_lines = _pixels_to_lines(buf)
550
+ while city_lines and not _strip_ansi(city_lines[0]).strip():
551
+ city_lines.pop(0)
552
+ while city_lines and not _strip_ansi(city_lines[-1]).strip():
553
+ city_lines.pop()
554
+
555
+ city_w = max((_visible_len(line) for line in city_lines), default=0)
556
+ term = shutil.get_terminal_size()
557
+ panel_max_w = max(20, term.columns - city_w - _SUMMARY_W - 2 * _GAP)
558
+
559
+ info = _build_info_panel(tile, city, panel_max_w)
560
+
561
+ n = max(len(summary), len(city_lines), len(info))
562
+ summary_lo = max(0, (n - len(summary)) // 2)
563
+ info_lo = max(0, (n - len(info)) // 2)
564
+
565
+ lines: list[str] = []
566
+ for i in range(n):
567
+ si = i - summary_lo
568
+ lt = summary[si] if 0 <= si < len(summary) else ""
569
+ lpad = max(0, _SUMMARY_W - _visible_len(lt))
570
+
571
+ ct = city_lines[i] if i < len(city_lines) else ""
572
+ cpad = max(0, city_w - _visible_len(ct))
573
+
574
+ ri = i - info_lo
575
+ rt = info[ri] if 0 <= ri < len(info) else ""
576
+
577
+ lines.append(lt + " " * lpad + " " * _GAP + ct + " " * cpad + " " * _GAP + rt)
578
+
579
+ lines.append("")
580
+ lines.append(" \033[90mWASD/Arrows: move · Q/ESC: quit\033[0m")
581
+
582
+ while len(lines) < term.lines - 1:
583
+ lines.append("")
584
+
585
+ output = "\033[H"
586
+ for line in lines[: term.lines - 1]:
587
+ output += line + "\033[K\r\n"
588
+ sys.stdout.write(output)
589
+ sys.stdout.flush()
590
+
591
+
592
+ def _build_info_panel(tile: TileInfo | None, city: CityData, max_w: int) -> list[str]:
593
+ reset = "\033[0m"
594
+ gray = "\033[90m"
595
+ bold = "\033[1m"
596
+ indent = " "
597
+ content_w = max_w - len(indent)
598
+
599
+ lines: list[str] = [""]
600
+ lines.append(f"{indent}{bold}City Explorer{reset}")
601
+ lines.append(indent + "─" * min(22, content_w))
602
+ lines.append("")
603
+
604
+ if tile is None:
605
+ lines.append(f"{indent}{gray}Move to a tile")
606
+ lines.append(f"{indent}to see details.{reset}")
607
+ return lines
608
+
609
+ if tile.repo is None:
610
+ lines.append(f"{indent}{gray}+{city.extra_count} more repos{reset}")
611
+ lines.append(f"{indent}{gray}{format_size(city.extra_storage, human_readable=True)} combined{reset}")
612
+ return lines
613
+
614
+ repo = tile.repo
615
+ name = repo.id
616
+ if len(name) > content_w:
617
+ name = name[: content_w - 3] + "..."
618
+ lines.append(f"{indent}{bold}{name}{reset}")
619
+ lines.append("")
620
+
621
+ type_ansi = {
622
+ "model": "\033[38;2;175;148;240m",
623
+ "dataset": "\033[38;2;245;128;128m",
624
+ "space": "\033[38;2;245;175;85m",
625
+ "bucket": "\033[38;2;112;185;242m",
626
+ }
627
+ tc = type_ansi.get(repo.type, "")
628
+
629
+ lines.append(f"{indent}Type {tc}{repo.type}{reset}")
630
+ lines.append(f"{indent}Visibility {repo.visibility}")
631
+ lines.append(f"{indent}Storage {format_size(repo.storage, human_readable=True)}")
632
+ lines.append(f"{indent}Usage {repo.storage_percent:.1f}%")
633
+ lines.append("")
634
+
635
+ bar_w = min(18, content_w)
636
+ filled = max(0, min(bar_w, round(repo.storage_percent / 100 * bar_w)))
637
+ lines.append(f"{indent}{tc}{'█' * filled}{gray}{'░' * (bar_w - filled)}{reset}")
638
+
639
+ return lines
640
+
641
+
642
+ def _copy_buf(buf: list[list[Color | None]]) -> list[list[Color | None]]:
643
+ return [row[:] for row in buf]
644
+
645
+
646
+ def _read_key() -> str:
647
+ fd = sys.stdin.fileno()
648
+ ch = os.read(fd, 1)
649
+ if ch == b"\x1b":
650
+ if _has_input(fd, 0.05):
651
+ ch2 = os.read(fd, 1)
652
+ if ch2 == b"[" and _has_input(fd, 0.05):
653
+ ch3 = os.read(fd, 1)
654
+ return f"\x1b[{ch3.decode()}"
655
+ return "esc"
656
+ return ch.decode("utf-8", errors="replace")
657
+
658
+
659
+ def _has_input(fd: int, timeout: float) -> bool:
660
+ r, _, _ = select.select([fd], [], [], timeout)
661
+ return bool(r)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_cli_utils.py ADDED
@@ -0,0 +1,1253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 CLI utilities (styling, helpers)."""
15
+
16
+ import difflib
17
+ import importlib.metadata
18
+ import logging
19
+ import os
20
+ import re
21
+ import shlex
22
+ import subprocess
23
+ import sys
24
+ import time
25
+ from collections.abc import Callable, Sequence
26
+ from enum import Enum
27
+ from pathlib import Path
28
+ from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeVar, cast
29
+
30
+ import click
31
+
32
+ from huggingface_hub import __version__, constants
33
+ from huggingface_hub.errors import CLIError
34
+ from huggingface_hub.utils._dotenv import load_dotenv
35
+
36
+ from ._framework import Argument, HfCommand, HfGroup, Option, build_command
37
+ from ._help_formatter import StyledContext
38
+ from ._output import OutputFormat, out
39
+
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+ # Arbitrary default limit for models/datasets/spaces list commands.
44
+ REPO_LIST_DEFAULT_LIMIT = 30
45
+
46
+ if TYPE_CHECKING:
47
+ from huggingface_hub import Volume
48
+ from huggingface_hub.hf_api import HfApi
49
+
50
+
51
+ def installation_method() -> str:
52
+ from huggingface_hub.utils import installation_method as _installation_method
53
+
54
+ return _installation_method()
55
+
56
+
57
+ def get_hf_api(token: str | None = None) -> "HfApi":
58
+ # Import here to avoid circular import
59
+ from huggingface_hub.hf_api import HfApi
60
+
61
+ return HfApi(token=token, library_name="huggingface-cli", library_version=__version__)
62
+
63
+
64
+ #### TYPER UTILS
65
+
66
+ CLI_REFERENCE_URL = "https://huggingface.co/docs/huggingface_hub/en/guides/cli"
67
+
68
+
69
+ def generate_epilog(examples: list[str], docs_anchor: str | None = None) -> str:
70
+ """Generate an epilog with examples and a Learn More section.
71
+
72
+ Args:
73
+ examples: List of example commands (without the `$ ` prefix).
74
+ docs_anchor: Optional anchor for the docs URL (e.g., "#hf-download").
75
+
76
+ Returns:
77
+ Formatted epilog string.
78
+ """
79
+ docs_url = f"{CLI_REFERENCE_URL}{docs_anchor}" if docs_anchor else CLI_REFERENCE_URL
80
+ examples_str = "\n".join(f" $ {ex}" for ex in examples)
81
+ return f"""\
82
+ Examples
83
+ {examples_str}
84
+
85
+ Learn more
86
+ Use `hf <command> --help` for more information about a command.
87
+ Read the documentation at {docs_url}
88
+ """
89
+
90
+
91
+ TOPIC_T = Literal["main", "help"] | str
92
+ FallbackHandlerT = Callable[[list[str], set[str]], int | None]
93
+ ExpandPropertyT = TypeVar("ExpandPropertyT", bound=str)
94
+
95
+
96
+ def _format_epilog_no_indent(epilog: str | None, ctx: click.Context, formatter: click.HelpFormatter) -> None:
97
+ """Write the epilog without indentation."""
98
+ if epilog:
99
+ formatter.write_paragraph()
100
+ for line in epilog.split("\n"):
101
+ formatter.write_text(line)
102
+
103
+
104
+ _ALIAS_SPLIT = re.compile(r"\s*\|\s*")
105
+
106
+
107
+ class HFCliTyperGroup(HfGroup):
108
+ """
109
+ CLI Group that:
110
+ - lists commands alphabetically within sections.
111
+ - separates commands by topic (main, help, etc.).
112
+ - formats epilog without extra indentation.
113
+ - supports aliases via pipe-separated names (e.g. ``name="list | ls"``).
114
+ - consumes the global formatting flags (``--format``, ``--json``, ``-q`` / ``--quiet``, ``--no-truncate``)
115
+ anywhere in the args of a leaf command and applies them to ``out``, so leaf
116
+ commands don't need to declare these options themselves.
117
+ - rewrites ``spaces/user/repo`` to ``user/repo --type space`` for commands that accept ``--type``.
118
+ - enriches "No such option" / "No such command" errors with available options or commands.
119
+ """
120
+
121
+ context_class = StyledContext
122
+
123
+ def invoke(self, ctx: click.Context) -> None:
124
+ """Enrich unknown-option errors with available options or subcommands.
125
+
126
+ Catches `NoSuchOption` raised during subcommand `make_context()`
127
+ (option parsing). For leaf commands (e.g. `hf repos create --test`)
128
+ we list the command's options; for groups (e.g. `hf cache --test`)
129
+ we list subcommands since groups have no user-facing options.
130
+ """
131
+ try:
132
+ return super().invoke(ctx)
133
+ except click.NoSuchOption as e:
134
+ if e.ctx is not None and e.ctx.command is not None:
135
+ cmd = e.ctx.command
136
+ if isinstance(cmd, click.Group):
137
+ # Group has no user-facing options -> show subcommands instead
138
+ items = [
139
+ (name, sub.get_short_help_str(limit=80))
140
+ for name in cmd.list_commands(e.ctx)
141
+ if (sub := cmd.get_command(e.ctx, name)) is not None and not sub.hidden
142
+ ]
143
+ _enrich_usage_error(e, "commands", items)
144
+ else:
145
+ # Leaf command -> show its options using Click's rich formatting
146
+ items = [
147
+ record
148
+ for p in cmd.get_params(e.ctx)
149
+ if isinstance(p, click.Option) and not p.hidden and (record := p.get_help_record(e.ctx))
150
+ ]
151
+ _enrich_usage_error(e, "options", items)
152
+ raise
153
+
154
+ def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple:
155
+ cmd_name = args[0] if args and not args[0].startswith("-") else None
156
+ cmd = self.get_command(ctx, cmd_name) if cmd_name else None
157
+
158
+ if isinstance(cmd, (LazyHfCommand, LazyHfGroup)):
159
+ loaded_cmd = cmd.materialize()
160
+ for registered_name, registered_cmd in self.commands.items():
161
+ if registered_cmd is cmd:
162
+ self.commands[registered_name] = loaded_cmd
163
+ cmd = loaded_cmd
164
+
165
+ if cmd is not None:
166
+ self._rewrite_repo_type_prefix(cmd, args)
167
+
168
+ try:
169
+ name, resolved_cmd, sub_args = super().resolve_command(ctx, args)
170
+ except click.UsageError as e:
171
+ # Unknown subcommand -> add fuzzy suggestions and list available commands.
172
+ if cmd is None and cmd_name is not None:
173
+ # Expand aliases ("list | ls" → ["list", "ls"]) for accurate fuzzy matching.
174
+ visible_names = [
175
+ alias
176
+ for key, registered in self.commands.items()
177
+ if not registered.hidden
178
+ for alias in _ALIAS_SPLIT.split(key)
179
+ ]
180
+ matches = difflib.get_close_matches(cmd_name, visible_names)
181
+ if matches:
182
+ suggestions = ", ".join(f"'{m}'" for m in matches)
183
+ setattr(e, "message", f"{e.message.rstrip('.')}. Did you mean {suggestions}?")
184
+ items = [
185
+ (name, sub.get_short_help_str(limit=80))
186
+ for name in self.list_commands(ctx)
187
+ if (sub := self.get_command(ctx, name)) is not None and not sub.hidden
188
+ ]
189
+ _enrich_usage_error(e, "commands", items)
190
+ raise
191
+
192
+ # If we just resolved a leaf command, eagerly consume any global formatting
193
+ # flags (--format / --json / -q / --quiet / --no-truncate) from its args before click parses
194
+ # them. Group resolution is recursive — leaves (and only leaves) need this.
195
+ if resolved_cmd is not None and not isinstance(resolved_cmd, click.Group):
196
+ _consume_format_flags_for_leaf(resolved_cmd, sub_args)
197
+
198
+ return name, resolved_cmd, sub_args
199
+
200
+ @staticmethod
201
+ def _rewrite_repo_type_prefix(cmd: click.Command, args: list[str]) -> None:
202
+ """Rewrite prefixed repo IDs (e.g. ``spaces/user/repo``) to ``user/repo --type space``.
203
+
204
+ Only applies to commands that have a ``--type`` / ``--repo-type`` option and
205
+ at least one repo-ID positional argument (any ``click.Argument`` whose name
206
+ ends with ``_id``, e.g. ``repo_id``, ``from_id``, ``to_id``). When the
207
+ token that maps to such an argument matches ``{prefix}/org/repo`` (where
208
+ *prefix* is one of ``spaces``, ``datasets``, or ``models``), the prefix is
209
+ stripped and an implicit ``--type {type}`` is appended. An error is raised
210
+ if ``--type`` is also provided explicitly or if multiple prefixed arguments
211
+ disagree on the repo type.
212
+
213
+ Only repo-ID positional slots are inspected so that other positional
214
+ arguments (filenames, local paths, patterns …) are never misinterpreted as
215
+ prefixed repo IDs.
216
+ """
217
+ has_type_option = any(isinstance(param, click.Option) and "--type" in param.opts for param in cmd.params)
218
+ if not has_type_option:
219
+ return
220
+
221
+ # Locate all repo-ID positional arguments and their indices among Arguments.
222
+ repo_id_positions: set[int] = set()
223
+ arg_idx = 0
224
+ for param in cmd.params:
225
+ if isinstance(param, click.Argument):
226
+ if param.name in ("repo_id", "from_id", "to_id"):
227
+ repo_id_positions.add(arg_idx)
228
+ arg_idx += 1
229
+
230
+ if not repo_id_positions:
231
+ return
232
+
233
+ # Build a set of option names that consume a following value token.
234
+ value_options: set[str] = set()
235
+ for param in cmd.params:
236
+ if isinstance(param, click.Option) and not param.is_flag:
237
+ for opt in (*param.opts, *param.secondary_opts):
238
+ value_options.add(opt)
239
+
240
+ # Walk through args (skipping args[0] = command name) to map positional
241
+ # slots to their indices in `args`.
242
+ positional_count = 0
243
+ repo_id_arg_indices: list[int] = []
244
+ i = 1
245
+ while i < len(args):
246
+ arg = args[i]
247
+ if arg == "--":
248
+ break # everything after -- is positional literal; stop rewriting
249
+ if arg.startswith("-"):
250
+ if "=" in arg or arg not in value_options:
251
+ i += 1 # flag or --opt=val — single token
252
+ else:
253
+ i += 2 # value-taking option — skip the value too
254
+ else:
255
+ if positional_count in repo_id_positions:
256
+ repo_id_arg_indices.append(i)
257
+ positional_count += 1
258
+ i += 1
259
+
260
+ if not repo_id_arg_indices:
261
+ return
262
+
263
+ # Check each repo-ID arg for a type prefix and collect rewrites.
264
+ inferred_type: str | None = None
265
+ first_prefix: str | None = None
266
+ rewrites: list[tuple[int, str]] = [] # (args index, new value without prefix)
267
+
268
+ for arg_index in repo_id_arg_indices:
269
+ parts = args[arg_index].split("/", 2)
270
+ if len(parts) != 3 or parts[0] not in constants.REPO_TYPES_MAPPING:
271
+ continue
272
+ prefix = parts[0]
273
+ mapped_type = constants.REPO_TYPES_MAPPING[prefix]
274
+ if inferred_type is not None and mapped_type != inferred_type:
275
+ raise click.UsageError(f"Conflicting repo type prefixes: '{first_prefix}/' and '{prefix}/'.")
276
+ inferred_type = mapped_type
277
+ first_prefix = prefix
278
+ rewrites.append((arg_index, f"{parts[1]}/{parts[2]}"))
279
+
280
+ if not rewrites:
281
+ return
282
+
283
+ # Error if --type / --repo-type was also provided explicitly.
284
+ if any(
285
+ arg == "--type" or arg.startswith("--type=") or arg == "--repo-type" or arg.startswith("--repo-type=")
286
+ for arg in args
287
+ ):
288
+ raise click.UsageError(
289
+ f"Ambiguous repo type: got prefix '{first_prefix}/' in repo ID and explicit --type. Use one or the other."
290
+ )
291
+
292
+ # Apply all rewrites and append --type once.
293
+ for arg_index, new_value in rewrites:
294
+ args[arg_index] = new_value
295
+ args.extend(["--type", inferred_type]) # type: ignore
296
+
297
+ def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:
298
+ # Try exact match first
299
+ cmd = super().get_command(ctx, cmd_name)
300
+ if cmd is not None:
301
+ return cmd
302
+ # Fall back to alias lookup: check if cmd_name matches any alias
303
+ # taken from https://github.com/fastapi/typer/issues/132#issuecomment-2417492805
304
+ for registered_name, registered_cmd in self.commands.items():
305
+ aliases = _ALIAS_SPLIT.split(registered_name)
306
+ if cmd_name in aliases:
307
+ return registered_cmd
308
+ return None
309
+
310
+ def _alias_map(self) -> dict[str, list[str]]:
311
+ """Build a mapping from primary command name to its aliases (if any)."""
312
+ result: dict[str, list[str]] = {}
313
+ for registered_name in self.commands:
314
+ parts = _ALIAS_SPLIT.split(registered_name)
315
+ primary = parts[0]
316
+ result[primary] = parts[1:]
317
+ return result
318
+
319
+ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
320
+ topics: dict[str, list] = {}
321
+ alias_map = self._alias_map()
322
+
323
+ for name in self.list_commands(ctx):
324
+ cmd = self.get_command(ctx, name)
325
+ if cmd is None or cmd.hidden:
326
+ continue
327
+ help_text = cmd.get_short_help_str(limit=formatter.width)
328
+ aliases = alias_map.get(name, [])
329
+ if aliases:
330
+ help_text = f"{help_text} [alias: {', '.join(aliases)}]"
331
+ topic = getattr(cmd, "topic", "main")
332
+ topics.setdefault(topic, []).append((name, help_text))
333
+
334
+ with formatter.section("Main commands"):
335
+ formatter.write_dl(topics["main"])
336
+ for topic in sorted(topics.keys()):
337
+ if topic == "main":
338
+ continue
339
+ with formatter.section(f"{topic.capitalize()} commands"):
340
+ formatter.write_dl(topics[topic])
341
+
342
+ def format_epilog(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
343
+ # Collect only the first example from each command (to keep group help concise)
344
+ # Full examples are shown in individual subcommand help (e.g. `hf buckets sync --help`)
345
+ all_examples: list[str] = []
346
+ for name in self.list_commands(ctx):
347
+ cmd = self.get_command(ctx, name)
348
+ if cmd is None or cmd.hidden:
349
+ continue
350
+ cmd_examples = getattr(cmd, "examples", [])
351
+ if cmd_examples:
352
+ all_examples.append(cmd_examples[0])
353
+
354
+ if all_examples:
355
+ epilog = generate_epilog(all_examples)
356
+ _format_epilog_no_indent(epilog, ctx, formatter)
357
+ elif self.epilog:
358
+ _format_epilog_no_indent(self.epilog, ctx, formatter)
359
+
360
+ def list_commands(self, ctx: click.Context) -> list[str]: # type: ignore[name-defined]
361
+ # For aliased commands ("list | ls"), use the primary name (first entry).
362
+ primary_names: list[str] = []
363
+ for name in self.commands:
364
+ primary = _ALIAS_SPLIT.split(name)[0]
365
+ primary_names.append(primary)
366
+ return sorted(primary_names)
367
+
368
+ def command( # type: ignore # adds topic/examples on top of HfGroup.command
369
+ self,
370
+ name: str | None = None,
371
+ *,
372
+ topic: TOPIC_T = "main",
373
+ examples: list[str] | None = None,
374
+ epilog: str | None = None,
375
+ **kwargs: Any,
376
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
377
+ # Generate the epilog from examples when not provided explicitly, then build the
378
+ # command with a topic/examples-aware command class.
379
+ if epilog is None and examples:
380
+ epilog = generate_epilog(examples)
381
+ return super().command(name, cls=HFCliCommand(topic, examples), epilog=epilog, **kwargs)
382
+
383
+
384
+ _FORMAT_HELP = "Output format. Defaults to 'auto' which picks 'agent' or 'human' based on the terminal."
385
+ _JSON_HELP = "JSON output. Equivalent to '--format json'."
386
+ _QUIET_HELP = "Quiet output (one ID per line). Equivalent to '--format quiet'."
387
+
388
+ _FORMATTING_OPTIONS_HELP_RECORDS: list[tuple[str, str]] = [
389
+ ("--format [auto|human|agent|json|quiet]", _FORMAT_HELP),
390
+ ("--json", _JSON_HELP),
391
+ ("-q, --quiet", _QUIET_HELP),
392
+ ("--no-truncate", "Do not truncate scalar values in human tables (list/dict columns stay shortened)."),
393
+ ]
394
+
395
+
396
+ def _format_formatting_options_section(formatter: click.HelpFormatter) -> None:
397
+ with formatter.section("Formatting options"):
398
+ formatter.write_dl(_FORMATTING_OPTIONS_HELP_RECORDS)
399
+
400
+
401
+ # Formatting options for pass-through commands (`ignore_unknown_options=True`, e.g. `hf jobs run`), which
402
+ # `_consume_format_flags_for_leaf` leaves untouched. Such commands must declare the flags explicitly (so click
403
+ # parses them instead of forwarding them to the container command) and apply them with `set_output_format()`.
404
+ FormatOpt = Annotated[OutputFormat | None, Option("--format", help=_FORMAT_HELP)]
405
+ JsonOpt = Annotated[bool, Option("--json", help=_JSON_HELP)]
406
+ QuietOpt = Annotated[bool, Option("-q", "--quiet", help=_QUIET_HELP)]
407
+
408
+
409
+ def set_output_format(format: OutputFormat | None, json: bool, quiet: bool) -> None:
410
+ """Apply the formatting flags declared by a pass-through command to the `out` singleton."""
411
+ flags = [flag for flag, given in (("--format", format is not None), ("--json", json), ("-q", quiet)) if given]
412
+ if len(flags) > 1:
413
+ raise click.UsageError(f"'{flags[0]}' and '{flags[1]}' are mutually exclusive.")
414
+ if format is not None:
415
+ out.set_mode(format)
416
+ elif json:
417
+ out.set_mode(OutputFormat.json)
418
+ elif quiet:
419
+ out.set_mode(OutputFormat.quiet)
420
+
421
+
422
+ def _has_local_formatting_option(cmd: click.Command) -> bool:
423
+ """Return True if the command defines its own --format, --json or --quiet / -q.
424
+
425
+ Used to skip the global formatting flag pre-processor and the duplicated "Formatting options" help section for
426
+ legacy commands like 'hf jobs ls' that have their own format/quiet options.
427
+ """
428
+ for param in cmd.params:
429
+ if not isinstance(param, click.Option):
430
+ continue
431
+ opts = (*param.opts, *param.secondary_opts)
432
+ if "--format" in opts or "--json" in opts or "--quiet" in opts or "-q" in opts:
433
+ return True
434
+ return False
435
+
436
+
437
+ def _consume_format_flags_for_leaf(cmd: click.Command, args: list[str]) -> None:
438
+ """Apply global formatting flags from 'args' to a leaf command.
439
+
440
+ Two modes, depending on the command:
441
+
442
+ * **Pass-through commands** (ignore_unknown_options=True, e.g. 'hf extensions exec'):
443
+ args are forwarded verbatim to an external binary; we don't touch them.
444
+
445
+ * **Legacy commands with a local --format option** (e.g. 'hf jobs ls' whose '--format' accepts Go templates):
446
+ the global flags are rewritten in-place to the legacy form ('--json' → '--format json', '--quiet'/'-q' → '--format quiet'
447
+ when the cmd has no own '--quiet') so click can parse them locally. This preserves backwards compatibility with the previous shorthand behavior.
448
+
449
+ * **Modern commands** (no local format/quiet/json options): the flags '--format <value>' / '--json' / '--quiet' / '-q' are stripped from 'args' and applied to the singleton 'out'.
450
+
451
+ '--no-truncate' is stripped for all non-pass-through commands; when present, human table cells are not truncated.
452
+
453
+ Raises click.UsageError if multiple conflicting flags are supplied (e.g. '--json' together with '--format table').
454
+ """
455
+ if cmd.context_settings.get("ignore_unknown_options"):
456
+ return
457
+
458
+ no_truncate = _consume_no_truncate_flags(args)
459
+ out.set_no_truncate(no_truncate)
460
+
461
+ has_local_format = False
462
+ has_local_quiet = False
463
+ has_local_json = False
464
+ for param in cmd.params:
465
+ if not isinstance(param, click.Option):
466
+ continue
467
+ opts = (*param.opts, *param.secondary_opts)
468
+ if "--format" in opts:
469
+ has_local_format = True
470
+ if "--quiet" in opts or "-q" in opts:
471
+ has_local_quiet = True
472
+ if "--json" in opts:
473
+ has_local_json = True
474
+
475
+ if has_local_format:
476
+ _rewrite_legacy_shorthands(args, rewrite_json=not has_local_json, rewrite_quiet=not has_local_quiet)
477
+ return
478
+
479
+ # Strip --format/--json/-q/--quiet from 'args' and apply to 'out'
480
+ chosen_mode: OutputFormat = OutputFormat.auto
481
+ chosen_flag: str | None = None
482
+
483
+ def _check_conflict(new_flag: str) -> None:
484
+ # Reject any second formatting flag before parsing values, so the user gets
485
+ # a "mutually exclusive" error rather than e.g. an "invalid value" error
486
+ # from the second flag's argument.
487
+ if chosen_flag is not None:
488
+ raise click.UsageError(f"'{chosen_flag}' and '{new_flag}' are mutually exclusive.")
489
+
490
+ i = 0
491
+ while i < len(args):
492
+ arg = args[i]
493
+ if arg == "--":
494
+ break # everything after '--' is a positional literal
495
+ if arg == "--format":
496
+ _check_conflict("--format")
497
+ if i + 1 >= len(args):
498
+ raise click.UsageError("Option '--format' requires a value.")
499
+ chosen_mode = _parse_format_value(args[i + 1])
500
+ chosen_flag = "--format"
501
+ del args[i : i + 2] # --format value => 2 args removed
502
+ continue
503
+ if arg.startswith("--format="):
504
+ _check_conflict("--format")
505
+ chosen_mode = _parse_format_value(arg[len("--format=") :])
506
+ chosen_flag = "--format"
507
+ del args[i : i + 1]
508
+ continue
509
+ if arg == "--json":
510
+ _check_conflict("--json")
511
+ chosen_mode = OutputFormat.json
512
+ chosen_flag = "--json"
513
+ del args[i : i + 1]
514
+ continue
515
+ if arg in ("-q", "--quiet"):
516
+ _check_conflict(arg)
517
+ chosen_mode = OutputFormat.quiet
518
+ chosen_flag = arg
519
+ del args[i : i + 1]
520
+ continue
521
+ i += 1
522
+
523
+ out.set_mode(chosen_mode)
524
+
525
+
526
+ def _consume_no_truncate_flags(args: list[str]) -> bool:
527
+ """Strip all global --no-truncate flags from args and return whether any was provided."""
528
+ no_truncate = False
529
+ i = 0
530
+ while i < len(args):
531
+ arg = args[i]
532
+ if arg == "--":
533
+ break # everything after '--' is a positional literal
534
+ if arg == "--no-truncate":
535
+ no_truncate = True
536
+ del args[i : i + 1]
537
+ continue
538
+ if arg.startswith("--no-truncate="):
539
+ raise click.UsageError("Option '--no-truncate' does not take a value.")
540
+ i += 1
541
+ return no_truncate
542
+
543
+
544
+ def _rewrite_legacy_shorthands(args: list[str], *, rewrite_json: bool, rewrite_quiet: bool) -> None:
545
+ """Rewrite --json / -q / --quiet to --format ... for legacy commands.
546
+
547
+ Used for commands like 'hf jobs ls' that still own their '--format' option.
548
+ The rewrite lets users keep using the global shorthand while click parses
549
+ '--format <value>' locally.
550
+ """
551
+ has_format_in_args = any(arg == "--format" or arg.startswith("--format=") for arg in args)
552
+
553
+ if rewrite_json and "--json" in args:
554
+ if has_format_in_args:
555
+ raise click.UsageError("'--json' and '--format' are mutually exclusive.")
556
+ idx = args.index("--json")
557
+ args[idx : idx + 1] = ["--format", "json"]
558
+ has_format_in_args = True
559
+
560
+ if rewrite_quiet:
561
+ flag = "-q" if "-q" in args else ("--quiet" if "--quiet" in args else None)
562
+ if flag is not None:
563
+ if has_format_in_args:
564
+ raise click.UsageError(f"'{flag}' and '--format' are mutually exclusive.")
565
+ idx = args.index(flag)
566
+ args[idx : idx + 1] = ["--format", "quiet"]
567
+
568
+
569
+ def _parse_format_value(value: str) -> "OutputFormat":
570
+ try:
571
+ return OutputFormat(value)
572
+ except ValueError:
573
+ valid = ", ".join(m.value for m in OutputFormat)
574
+ raise click.UsageError(f"Invalid value for '--format': '{value}'. Valid values: {valid}.") from None
575
+
576
+
577
+ def _enrich_usage_error(error: click.UsageError, label: str, items: list[tuple[str, str]]) -> None:
578
+ """Append a list of available options or commands to a usage error message."""
579
+ if not items or error.ctx is None or f"Available {label} for" in error.message:
580
+ return
581
+ cmd_path = error.ctx.command_path
582
+ lines = [f"\n\nAvailable {label} for '{cmd_path}':"]
583
+ for name, help_text in items:
584
+ lines.append(f" {name:30s} {help_text}")
585
+ lines.append(f"\nRun '{cmd_path} --help' for full details.")
586
+ if isinstance(error, click.NoSuchOption) and error.possibilities:
587
+ lines.append(f"\nDid you mean: {', '.join(sorted(error.possibilities))}?")
588
+ setattr(error, "possibilities", [])
589
+ setattr(error, "message", error.message + "\n".join(lines))
590
+
591
+
592
+ def fallback_typer_group_factory(
593
+ fallback_handler: FallbackHandlerT,
594
+ extra_commands_provider: Callable[[], list[tuple[str, str]]] | None = None,
595
+ ) -> type[HFCliTyperGroup]:
596
+ """Return a Typer group class that runs a fallback handler before command resolution."""
597
+
598
+ class FallbackTyperGroup(HFCliTyperGroup):
599
+ def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple:
600
+ fallback_exit_code = fallback_handler(args, set(self.commands.keys()))
601
+ if fallback_exit_code is not None:
602
+ raise SystemExit(fallback_exit_code)
603
+ return super().resolve_command(ctx, args)
604
+
605
+ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
606
+ super().format_commands(ctx, formatter)
607
+ if extra_commands_provider is not None:
608
+ entries = extra_commands_provider()
609
+ if entries:
610
+ with formatter.section("Extension commands"):
611
+ formatter.write_dl(entries)
612
+
613
+ return FallbackTyperGroup
614
+
615
+
616
+ def HFCliCommand(topic: TOPIC_T, examples: list[str] | None = None) -> type[HfCommand]:
617
+ def format_epilog(self: click.Command, ctx: click.Context, formatter: click.HelpFormatter) -> None:
618
+ _format_epilog_no_indent(self.epilog, ctx, formatter)
619
+
620
+ def format_options(self: HfCommand, ctx: click.Context, formatter: click.HelpFormatter) -> None:
621
+ HfCommand.format_options(self, ctx, formatter)
622
+ # Skip the section for commands that define their own --format / --quiet / --json,
623
+ # or for pass-through commands that forward args to an external binary.
624
+ if _has_local_formatting_option(self):
625
+ return
626
+ if self.context_settings.get("ignore_unknown_options"):
627
+ return
628
+ _format_formatting_options_section(formatter)
629
+
630
+ def parse_args(self: click.Command, ctx: click.Context, args: list[str]) -> list[str]:
631
+ # Show help when a command with required arguments is invoked without any args
632
+ # (mirrors group behavior: `hf jobs` prints help, so `hf download` should too).
633
+ if not args and not ctx.resilient_parsing:
634
+ if any(isinstance(p, click.Argument) and p.required for p in self.params):
635
+ click.echo(ctx.get_help(), color=ctx.color)
636
+ ctx.exit()
637
+ return HfCommand.parse_args(self, ctx, args)
638
+
639
+ return type(
640
+ f"HfCommand{topic.capitalize()}",
641
+ (HfCommand,),
642
+ {
643
+ "context_class": StyledContext,
644
+ "topic": topic,
645
+ "examples": examples or [],
646
+ "format_epilog": format_epilog,
647
+ "format_options": format_options,
648
+ "parse_args": parse_args,
649
+ },
650
+ )
651
+
652
+
653
+ class LazyHfCommand(click.Command):
654
+ """A lightweight command placeholder that imports its implementation when selected."""
655
+
656
+ def __init__(
657
+ self,
658
+ name: str,
659
+ *,
660
+ module: str,
661
+ attribute: str,
662
+ is_factory: bool = False,
663
+ topic: TOPIC_T = "main",
664
+ examples_attribute: str | None = None,
665
+ hidden: bool = False,
666
+ ) -> None:
667
+ super().__init__(name=name, hidden=hidden)
668
+ self.module = module
669
+ self.attribute = attribute
670
+ self.is_factory = is_factory
671
+ self.topic = topic
672
+ self.examples: list[str] = []
673
+ self.examples_attribute = examples_attribute
674
+ self._loaded: click.Command | None = None
675
+
676
+ def materialize(self) -> click.Command:
677
+ if self._loaded is None:
678
+ module = importlib.import_module(self.module)
679
+ callback = getattr(module, self.attribute)
680
+ examples = getattr(module, self.examples_attribute) if self.examples_attribute is not None else []
681
+ if self.is_factory:
682
+ callback = callback()
683
+ if isinstance(callback, click.Command):
684
+ command = callback
685
+ command.name = self.name
686
+ command.hidden = self.hidden
687
+ else:
688
+ epilog = generate_epilog(examples) if examples else None
689
+ command = build_command(
690
+ callback,
691
+ name=self.name,
692
+ cls=HFCliCommand(self.topic, examples),
693
+ epilog=epilog,
694
+ hidden=self.hidden,
695
+ )
696
+ self.examples = getattr(command, "examples", examples)
697
+ self._loaded = command
698
+ return self._loaded
699
+
700
+ def get_short_help_str(self, limit: int = 45) -> str:
701
+ return self.materialize().get_short_help_str(limit)
702
+
703
+
704
+ class LazyHfGroup(click.Group):
705
+ """A lightweight group placeholder that imports its implementation when selected or inspected."""
706
+
707
+ def __init__(self, name: str, *, module: str, attribute: str, hidden: bool = False) -> None:
708
+ super().__init__(name=name, hidden=hidden)
709
+ self.module = module
710
+ self.attribute = attribute
711
+ self._loaded: click.Group | None = None
712
+
713
+ def materialize(self) -> click.Group:
714
+ if self._loaded is None:
715
+ group = getattr(importlib.import_module(self.module), self.attribute)
716
+ if not isinstance(group, click.Group):
717
+ raise TypeError(f"{self.module}.{self.attribute} is not a Click group")
718
+ group.name = self.name
719
+ group.hidden = self.hidden
720
+ self._loaded = group
721
+ return self._loaded
722
+
723
+ def list_commands(self, ctx: click.Context) -> list[str]:
724
+ return self.materialize().list_commands(ctx)
725
+
726
+ def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:
727
+ return self.materialize().get_command(ctx, cmd_name)
728
+
729
+ def get_short_help_str(self, limit: int = 45) -> str:
730
+ return self.materialize().get_short_help_str(limit)
731
+
732
+
733
+ def typer_factory(help: str, epilog: str | None = None, cls: type[HFCliTyperGroup] | None = None) -> "HFCliTyperGroup":
734
+ """Create a CLI command group with consistent settings.
735
+
736
+ The returned group is the app: register commands with ``@group.command(...)``,
737
+ subgroups with ``group.add_group(sub, name=...)``, and a group-level callback
738
+ with ``@group.callback(...)``.
739
+
740
+ Args:
741
+ help: Help text for the group.
742
+ epilog: Optional epilog text (use `generate_epilog` to create one).
743
+ cls: Optional group class to use (defaults to `HFCliTyperGroup`).
744
+
745
+ Returns:
746
+ A configured `HFCliTyperGroup` instance.
747
+ """
748
+ if cls is None:
749
+ cls = HFCliTyperGroup
750
+ return cls(
751
+ help=help,
752
+ epilog=epilog,
753
+ no_args_is_help=True,
754
+ # Increase max content width for better readability
755
+ context_settings={
756
+ "max_content_width": 120,
757
+ "help_option_names": ["-h", "--help"],
758
+ },
759
+ )
760
+
761
+
762
+ class SoftChoice(click.Choice):
763
+ """A click Choice that suggests choices for autocompletion/docs but accepts any string.
764
+
765
+ Unlike `click.Choice`, unknown values are passed through as-is instead of raising an error.
766
+ This makes CLI options future-compatible when new server-side values are added.
767
+
768
+ Accepts either a sequence of strings or an Enum class:
769
+ ```python
770
+ SoftChoice(SpaceHardware) # from an enum
771
+ SoftChoice(["a", "b", "c"]) # from a list
772
+ ```
773
+ """
774
+
775
+ def __init__(self, choices: Sequence[str] | type[Enum]) -> None:
776
+ values = (
777
+ [m.value for m in choices] if isinstance(choices, type) and issubclass(choices, Enum) else list(choices)
778
+ )
779
+ super().__init__(values, case_sensitive=True)
780
+
781
+ def convert(self, value: Any, param: click.Parameter | None, ctx: click.Context | None) -> str:
782
+ try:
783
+ return super().convert(value, param, ctx)
784
+ except click.exceptions.BadParameter:
785
+ return str(value)
786
+
787
+
788
+ class RepoType(str, Enum):
789
+ model = "model"
790
+ dataset = "dataset"
791
+ space = "space"
792
+ kernel = "kernel"
793
+
794
+
795
+ RepoIdArg = Annotated[
796
+ str,
797
+ Argument(
798
+ help="The ID of the repo (e.g. `username/repo-name` or `spaces/username/repo-name`).",
799
+ ),
800
+ ]
801
+
802
+
803
+ RepoTypeOpt = Annotated[
804
+ RepoType,
805
+ Option(
806
+ "--type",
807
+ "--repo-type",
808
+ help="The type of repository (model, dataset, space, or kernel).",
809
+ ),
810
+ ]
811
+
812
+ # Same as `RepoTypeOpt` but optional (defaults to `None` rather than `model`). Used by commands that
813
+ # accept an `hf://` URI as repo id: a `None` default lets us tell apart "user did not pass --repo-type"
814
+ # from "user explicitly passed --repo-type model", which is required to detect conflicts with the URI.
815
+ RepoTypeOptionalOpt = Annotated[
816
+ RepoType | None,
817
+ Option(
818
+ "--type",
819
+ "--repo-type",
820
+ help="The type of repository (model, dataset, space, or kernel).",
821
+ show_default="model",
822
+ ),
823
+ ]
824
+
825
+ # --- Secret hygiene: keep secret material out of argv ---
826
+ #
827
+ # Anything passed as a flag value lands in the shell history file and, on Linux, in
828
+ # `/proc/<pid>/cmdline`, which any process of the same user can read. The CLI already offers
829
+ # argv-free alternatives (`hf auth login`, `HF_TOKEN`, bare `--secrets KEY`, `--secrets-file`);
830
+ # these warnings point at them. They stay warnings on purpose: erroring out would break
831
+ # existing automation.
832
+
833
+
834
+ def _warn_secret_hygiene(message: str) -> None:
835
+ """Emit a secret-hygiene warning on stderr in every output mode."""
836
+ out.warning(message)
837
+
838
+
839
+ def _warn_on_inline_token(token: str | None) -> str | None:
840
+ """Option callback for `TokenOpt`: warn when a token is passed as a flag value."""
841
+ ctx = click.get_current_context(silent=True)
842
+ # `hf auth login --token` is the non-interactive login flow this warning points users *to*,
843
+ # so it is exempt. Matched on a suffix because the root command name depends on how the CLI
844
+ # was invoked (`hf`, `huggingface-cli`, a test runner's prog name...).
845
+ if token is not None and not (ctx is not None and ctx.command_path.endswith("auth login")):
846
+ _warn_secret_hygiene(
847
+ "`--token <value>` leaves your token in your shell history and in process listings. Run "
848
+ "`hf auth login` once, or export `HF_TOKEN`, and drop the flag."
849
+ )
850
+ return token
851
+
852
+
853
+ def _warn_on_inline_secrets(secrets: list[str] | None) -> list[str] | None:
854
+ """Option callback for `SecretsOpt`: warn once if any pair carries an inline value."""
855
+ if secrets and any("=" in secret for secret in secrets):
856
+ _warn_secret_hygiene(
857
+ "`--secrets KEY=value` leaves the value in your shell history and in process listings. Prefer "
858
+ "`--secrets KEY` (value read from your environment), `--secrets-file FILE` or `--secrets-file -`."
859
+ )
860
+ return secrets
861
+
862
+
863
+ TokenOpt = Annotated[
864
+ str | None,
865
+ Option(
866
+ help="A User Access Token generated from https://huggingface.co/settings/tokens.",
867
+ callback=_warn_on_inline_token,
868
+ ),
869
+ ]
870
+
871
+ PrivateOpt = Annotated[
872
+ bool | None,
873
+ Option(
874
+ help="Whether to create a private repo if repo doesn't exist on the Hub. Ignored if the repo already exists.",
875
+ ),
876
+ ]
877
+
878
+ RevisionOpt = Annotated[
879
+ str | None,
880
+ Option(
881
+ help="Git revision id which can be a branch name, a tag, or a commit hash.",
882
+ ),
883
+ ]
884
+
885
+
886
+ LimitOpt = Annotated[
887
+ int,
888
+ Option(help="Limit the number of results."),
889
+ ]
890
+
891
+ AuthorOpt = Annotated[
892
+ str | None,
893
+ Option(help="Filter by author or organization."),
894
+ ]
895
+
896
+ FilterOpt = Annotated[
897
+ list[str] | None,
898
+ Option(help="Filter by tags (e.g. 'text-classification'). Can be used multiple times."),
899
+ ]
900
+
901
+ SearchOpt = Annotated[
902
+ str | None,
903
+ Option(help="Search query."),
904
+ ]
905
+
906
+
907
+ # --- Env / Secrets shared options and parsing helpers (used by jobs, repos, etc.) ---
908
+
909
+ EnvOpt = Annotated[
910
+ list[str] | None,
911
+ Option(
912
+ "-e",
913
+ "--env",
914
+ help="Set environment variables. E.g. --env ENV=value",
915
+ ),
916
+ ]
917
+
918
+ SecretsOpt = Annotated[
919
+ list[str] | None,
920
+ Option(
921
+ "-s",
922
+ "--secrets",
923
+ help=(
924
+ "Set secret environment variables. Prefer `--secrets SECRET` to read the value from your"
925
+ " environment (e.g. `--secrets HF_TOKEN` to pass your Hugging Face token); `--secrets SECRET=value`"
926
+ " puts the value in your shell history."
927
+ ),
928
+ callback=_warn_on_inline_secrets,
929
+ ),
930
+ ]
931
+
932
+ EnvFileOpt = Annotated[
933
+ str | None,
934
+ Option(
935
+ "--env-file",
936
+ help="Read in a file of environment variables. Use `-` to read them from stdin.",
937
+ ),
938
+ ]
939
+
940
+ SecretsFileOpt = Annotated[
941
+ str | None,
942
+ Option(
943
+ help="Read in a file of secret environment variables. Use `-` to read them from stdin.",
944
+ ),
945
+ ]
946
+
947
+
948
+ def _get_extended_environ() -> dict[str, str]:
949
+ """Return a copy of ``os.environ`` with the user's HF token injected (if available)."""
950
+ from huggingface_hub import get_token
951
+
952
+ extended_environ = os.environ.copy()
953
+ if (token := get_token()) is not None:
954
+ extended_environ["HF_TOKEN"] = token
955
+ return extended_environ
956
+
957
+
958
+ def _read_env_file(env_file: str) -> str:
959
+ """Read an env/secrets file, or stdin when ``env_file`` is ``-``.
960
+
961
+ Piping through stdin is the only way to hand the CLI a secret value that touches neither
962
+ argv nor the disk.
963
+ """
964
+ if env_file == "-":
965
+ return sys.stdin.read()
966
+ path = Path(env_file)
967
+ # POSIX only: Windows reports a synthetic 0o666/0o444 mode, so this would always fire there.
968
+ if os.name == "posix" and (mode := path.stat().st_mode & 0o777) & 0o077:
969
+ _warn_secret_hygiene(
970
+ f"'{env_file}' is readable by other users (mode {mode:o}). Run `chmod 600 {env_file}` to restrict it."
971
+ )
972
+ # "utf-8-sig" drops the BOM that Windows tools (e.g. PowerShell 5.1) write at the start of the file
973
+ return path.read_text(encoding="utf-8-sig")
974
+
975
+
976
+ def parse_env_map(
977
+ env: list[str] | None = None,
978
+ env_file: str | None = None,
979
+ ) -> dict[str, str | None]:
980
+ """Parse ``-e``/``--env``/``-s``/``--secrets`` and ``--env-file``/``--secrets-file`` CLI args into a dict.
981
+
982
+ Uses an extended environment that includes the user's HF token so that
983
+ bare ``--secrets HF_TOKEN`` resolves correctly.
984
+ """
985
+ env_map: dict[str, str | None] = {}
986
+ if env_file or env:
987
+ extended_environ = _get_extended_environ()
988
+ if env_file:
989
+ env_map.update(load_dotenv(_read_env_file(env_file), environ=extended_environ))
990
+ for env_value in env or []:
991
+ env_map.update(load_dotenv(env_value, environ=extended_environ))
992
+ return env_map
993
+
994
+
995
+ def env_map_to_key_value_list(env_map: dict[str, str | None]) -> list[dict[str, str]] | None:
996
+ """Convert an env/secrets dict to the ``[{"key": ..., "value": ...}]`` format used by the Hub API."""
997
+ if not env_map:
998
+ return None
999
+ return [{"key": k, "value": v or ""} for k, v in env_map.items()]
1000
+
1001
+
1002
+ VolumesOpt = Annotated[
1003
+ list[str] | None,
1004
+ Option(
1005
+ "-v",
1006
+ "--volume",
1007
+ help="Mount one or more volumes. Format: hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. "
1008
+ "TYPE is one of: models, datasets, spaces, buckets. "
1009
+ "TYPE defaults to models if omitted. "
1010
+ "models, datasets and spaces are always mounted read-only. buckets are read+write by default. "
1011
+ "E.g. -v hf://org/m:/data or -v hf://datasets/org/ds:/data or -v hf://buckets/org/b:/mnt:ro",
1012
+ ),
1013
+ ]
1014
+
1015
+
1016
+ def parse_volumes(volumes: list[str] | None) -> "list[Volume] | None":
1017
+ """Parse volume specs from CLI arguments.
1018
+
1019
+ Format: hf://[TYPE/]SOURCE[/PATH]:/MOUNT_PATH[:ro|:rw]
1020
+ Where TYPE is one of: models, datasets, spaces, buckets (defaults to models if omitted).
1021
+ SOURCE is the repo/bucket identifier (e.g. 'username/my-model').
1022
+ PATH is an optional subfolder inside the repo/bucket.
1023
+ MOUNT_PATH starts with '/'.
1024
+ Optional ':ro' or ':rw' suffix for read-only or read-write.
1025
+
1026
+ Examples:
1027
+ hf://my-org/my-model:/data (model, implicit type)
1028
+ hf://models/my-org/my-model:/data (model, explicit type)
1029
+ hf://datasets/my-org/my-dataset:/data:ro
1030
+ hf://buckets/my-org/my-bucket:/mnt
1031
+ hf://spaces/my-org/my-space:/app
1032
+ hf://datasets/org/ds/train:/data (with path inside repo)
1033
+ hf://buckets/org/b/sub/dir:/mnt (with path inside bucket)
1034
+ """
1035
+ if not volumes:
1036
+ return None
1037
+
1038
+ from huggingface_hub import Volume
1039
+ from huggingface_hub.utils import parse_hf_mount
1040
+
1041
+ result: list[Volume] = []
1042
+ for raw_spec in volumes:
1043
+ mount = parse_hf_mount(raw_spec)
1044
+ result.append(
1045
+ Volume(
1046
+ type=mount.source.type,
1047
+ source=mount.source.id,
1048
+ mount_path=mount.mount_path,
1049
+ read_only=mount.read_only,
1050
+ path=mount.source.path_in_repo or None,
1051
+ revision=mount.source.revision or None,
1052
+ )
1053
+ )
1054
+ return result
1055
+
1056
+
1057
+ def make_expand_properties_parser(valid_properties: Sequence[ExpandPropertyT]):
1058
+ """Create a callback to parse and validate comma-separated expand properties."""
1059
+
1060
+ def _parse_expand_properties(value: str | None) -> list[ExpandPropertyT] | None:
1061
+ if value is None:
1062
+ return None
1063
+ properties = [p.strip() for p in value.split(",")]
1064
+ for prop in properties:
1065
+ if prop not in valid_properties:
1066
+ raise click.BadParameter(
1067
+ f"Invalid expand property: '{prop}'. Valid values are: {', '.join(valid_properties)}"
1068
+ )
1069
+ return [cast(ExpandPropertyT, prop) for prop in properties]
1070
+
1071
+ return _parse_expand_properties
1072
+
1073
+
1074
+ ### SSH
1075
+
1076
+
1077
+ SshIdentityFileOpt = Annotated[
1078
+ Path | None,
1079
+ Option("-i", "--identity-file", help="Path to the SSH identity file (forwarded to `ssh -i`)."),
1080
+ ]
1081
+
1082
+ SshDryRunOpt = Annotated[
1083
+ bool,
1084
+ Option("--dry-run", help="Print the SSH command instead of running it."),
1085
+ ]
1086
+
1087
+
1088
+ def exec_ssh(
1089
+ destination: str, *, port: int | None = None, identity_file: Path | None = None, dry_run: bool = False
1090
+ ) -> None:
1091
+ """Run an interactive `ssh` command to `destination` (`user@host`) and exit with its return code.
1092
+
1093
+ With `dry_run`, print the command instead of running it.
1094
+ """
1095
+ cmd = ["ssh"]
1096
+ if identity_file is not None:
1097
+ cmd += ["-i", str(identity_file)]
1098
+ if port is not None:
1099
+ cmd += ["-p", str(port)]
1100
+ cmd.append(destination)
1101
+ if dry_run:
1102
+ out.text(shlex.join(cmd))
1103
+ return
1104
+ out.text(f"Running `{shlex.join(cmd)}`")
1105
+ result = subprocess.run(cmd)
1106
+ raise click.exceptions.Exit(code=result.returncode)
1107
+
1108
+
1109
+ ### PyPI VERSION CHECKER
1110
+
1111
+
1112
+ def check_cli_update(library: Literal["huggingface_hub", "transformers"]) -> None:
1113
+ """
1114
+ Check whether a newer version of a library is available on PyPI.
1115
+
1116
+ If a newer version is found, print a hint pointing at `hf update`.
1117
+
1118
+ If current version is a pre-release (e.g. `1.0.0.rc1`), or a dev version (e.g. `1.0.0.dev1`), no check is performed.
1119
+ If `HF_HUB_DISABLE_UPDATE_CHECK` is set, the check is skipped entirely.
1120
+
1121
+ This function is called at the entry point of the CLI. It only performs the check once every 24 hours, and any error
1122
+ during the check is caught and logged, to avoid breaking the CLI.
1123
+
1124
+ Args:
1125
+ library: The library to check for updates. Currently supports "huggingface_hub" and "transformers".
1126
+ """
1127
+ try:
1128
+ _check_cli_update(library)
1129
+ except Exception:
1130
+ # We don't want the CLI to fail on version checks, no matter the reason.
1131
+ logger.debug("Error while checking for CLI update.", exc_info=True)
1132
+
1133
+
1134
+ def _check_cli_update(library: Literal["huggingface_hub", "transformers"]) -> None:
1135
+ if constants.HF_HUB_DISABLE_UPDATE_CHECK:
1136
+ return
1137
+
1138
+ current_version = importlib.metadata.version(library)
1139
+
1140
+ # Skip if current version is a pre-release or dev version
1141
+ if any(tag in current_version for tag in ["rc", "dev"]):
1142
+ return
1143
+
1144
+ # Skip if already checked in the last 24 hours
1145
+ if os.path.exists(constants.CHECK_FOR_UPDATE_DONE_PATH):
1146
+ mtime = os.path.getmtime(constants.CHECK_FOR_UPDATE_DONE_PATH)
1147
+ if (time.time() - mtime) < 24 * 3600:
1148
+ return
1149
+
1150
+ # Touch the file to mark that we did the check now
1151
+ Path(constants.CHECK_FOR_UPDATE_DONE_PATH).parent.mkdir(parents=True, exist_ok=True)
1152
+ Path(constants.CHECK_FOR_UPDATE_DONE_PATH).touch()
1153
+
1154
+ # Check latest version from the appropriate registry
1155
+ if library == "huggingface_hub" and installation_method() == "brew":
1156
+ latest_version = _fetch_latest_brew_version()
1157
+ else:
1158
+ latest_version = _fetch_latest_pypi_version(library)
1159
+ if latest_version is None or current_version == latest_version:
1160
+ return
1161
+
1162
+ if library == "huggingface_hub":
1163
+ update_command = _get_huggingface_hub_update_command()
1164
+ else:
1165
+ update_command = _get_transformers_update_command()
1166
+
1167
+ message = f"A new version of {library} ({latest_version}) is available! You are using version {current_version}."
1168
+ if update_command is not None:
1169
+ match library:
1170
+ case "huggingface_hub":
1171
+ message += "\nTo update, run: hf update"
1172
+ case _:
1173
+ message += f"\nTo update, run: {' '.join(update_command)}"
1174
+ out.hint(message)
1175
+
1176
+
1177
+ def _fetch_latest_pypi_version(library: str) -> str | None:
1178
+ """Fetch the latest version of a library from PyPI. Returns None if the request fails."""
1179
+ try:
1180
+ from huggingface_hub.utils import get_session, hf_raise_for_status
1181
+
1182
+ response = get_session().get(f"https://pypi.org/pypi/{library}/json", timeout=2)
1183
+ hf_raise_for_status(response)
1184
+ return response.json()["info"]["version"]
1185
+ except Exception:
1186
+ logger.debug("Error while fetching latest version from PyPI.", exc_info=True)
1187
+ return None
1188
+
1189
+
1190
+ def _fetch_latest_brew_version() -> str | None:
1191
+ """Fetch the latest version of the `hf` formula from the Homebrew registry. Returns None if the request fails."""
1192
+ try:
1193
+ from huggingface_hub.utils import get_session, hf_raise_for_status
1194
+
1195
+ response = get_session().get("https://formulae.brew.sh/api/formula/hf.json", timeout=2)
1196
+ hf_raise_for_status(response)
1197
+ return response.json()["versions"]["stable"]
1198
+ except Exception:
1199
+ logger.debug("Error while fetching latest version from Homebrew.", exc_info=True)
1200
+ return None
1201
+
1202
+
1203
+ def run_update(*, exclude_skill: bool = False) -> int:
1204
+ """Run the install-method-appropriate update command for the `hf` CLI.
1205
+
1206
+ Set `exclude_skill` to tell the standalone installer not to (re)install the `hf-cli` skill.
1207
+
1208
+ Raises CLIError if the installation method can't be determined.
1209
+ Returns the subprocess exit code on success/failure of the update itself.
1210
+ """
1211
+ cmd = _get_huggingface_hub_update_command(exclude_skill=exclude_skill)
1212
+ if cmd is None:
1213
+ raise CLIError(
1214
+ "Cannot determine how to update huggingface_hub (unknown installation method). Please update manually."
1215
+ )
1216
+ return subprocess.call(cmd)
1217
+
1218
+
1219
+ def _get_huggingface_hub_update_command(*, exclude_skill: bool = False) -> list[str] | None:
1220
+ """Return the command to update huggingface_hub as an argv list, or None if the installation method is unknown."""
1221
+ match installation_method():
1222
+ case "brew":
1223
+ return ["brew", "upgrade", "hf"]
1224
+ case "hf_installer" if os.name == "nt":
1225
+ # `iwr ... | iex` cannot take parameters: create a scriptblock so flags reach the installer.
1226
+ flags = " -ExcludeSkill" if exclude_skill else ""
1227
+ script = f"& ([scriptblock]::Create((iwr -useb https://hf.co/cli/install.ps1))){flags}"
1228
+ return ["powershell", "-NoProfile", "-Command", script]
1229
+ case "hf_installer":
1230
+ flags = " -s -- --exclude-skill" if exclude_skill else " -"
1231
+ return ["bash", "-c", f"curl -LsSf https://hf.co/cli/install.sh | bash{flags}"]
1232
+ case "pip":
1233
+ return [sys.executable, "-m", "pip", "install", "-U", "huggingface_hub"]
1234
+ case _:
1235
+ return None
1236
+
1237
+
1238
+ def _get_transformers_update_command() -> list[str] | None:
1239
+ """Return the command to update transformers as an argv list, or None if the installation method is unknown."""
1240
+ match installation_method():
1241
+ case "hf_installer" if os.name == "nt":
1242
+ return [
1243
+ "powershell",
1244
+ "-NoProfile",
1245
+ "-Command",
1246
+ "& ([scriptblock]::Create((iwr -useb https://hf.co/cli/install.ps1))) -WithTransformers",
1247
+ ]
1248
+ case "hf_installer":
1249
+ return ["bash", "-c", "curl -LsSf https://hf.co/cli/install.sh | bash -s -- --with-transformers"]
1250
+ case "pip":
1251
+ return [sys.executable, "-m", "pip", "install", "-U", "transformers"]
1252
+ case _:
1253
+ return None
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_completion.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Shell completion for the ``hf`` CLI, built on Click's native completion.
15
+
16
+ Click generates completion scripts activated by the ``_HF_COMPLETE`` env var (this
17
+ works out of the box because ``hf`` is a Click command). This module exposes the two
18
+ conveniences Typer used to provide — ``--install-completion`` / ``--show-completion``
19
+ — as thin eager options over that machinery.
20
+ """
21
+
22
+ import os
23
+ from pathlib import Path
24
+ from typing import Annotated
25
+
26
+ import click
27
+ from click.shell_completion import get_completion_class
28
+
29
+ from ._framework import Option
30
+
31
+
32
+ _COMPLETE_VAR = "_HF_COMPLETE"
33
+
34
+ # Shells with a shared rc file: the line that activates completion (appended once).
35
+ _RC_ACTIVATION: dict[str, tuple[Path, str]] = {
36
+ "bash": (Path.home() / ".bashrc", f'eval "$({_COMPLETE_VAR}=bash_source hf)"'),
37
+ "zsh": (Path.home() / ".zshrc", f'eval "$({_COMPLETE_VAR}=zsh_source hf)"'),
38
+ }
39
+ # Fish auto-loads per-command files from its completions directory. The file is dedicated
40
+ # to `hf`, so the full script is written there directly (overwriting any stale version)
41
+ # instead of re-generating it via `hf` on every shell startup.
42
+ _FISH_COMPLETION_PATH = Path.home() / ".config" / "fish" / "completions" / "hf.fish"
43
+
44
+
45
+ def _detect_shell() -> str:
46
+ return Path(os.environ.get("SHELL", "")).name or "bash"
47
+
48
+
49
+ def _completion_script(shell: str) -> str:
50
+ # Imported lazily to avoid a circular import (hf.py imports the options below).
51
+ from .hf import app
52
+
53
+ completion_cls = get_completion_class(shell)
54
+ if completion_cls is None:
55
+ raise click.ClickException(f"Shell '{shell}' is not supported for completion.")
56
+ return completion_cls(app, {}, "hf", _COMPLETE_VAR).source()
57
+
58
+
59
+ def _show_completion(value: bool) -> None:
60
+ if not value:
61
+ return
62
+ click.echo(_completion_script(_detect_shell()))
63
+ raise click.exceptions.Exit()
64
+
65
+
66
+ def _install_completion(value: bool) -> None:
67
+ if not value:
68
+ return
69
+ shell = _detect_shell()
70
+ if shell == "fish":
71
+ path = _FISH_COMPLETION_PATH
72
+ path.parent.mkdir(parents=True, exist_ok=True)
73
+ path.write_text(_completion_script("fish"))
74
+ elif shell in _RC_ACTIVATION:
75
+ path, activation = _RC_ACTIVATION[shell]
76
+ path.parent.mkdir(parents=True, exist_ok=True)
77
+ existing = path.read_text() if path.exists() else ""
78
+ if activation not in existing:
79
+ with path.open("a") as file:
80
+ file.write(f"\n{activation}\n")
81
+ else:
82
+ raise click.ClickException(f"Shell '{shell}' is not supported for completion.")
83
+ click.echo(f"{shell} completion installed in {path}. Restart your shell for it to take effect.")
84
+ raise click.exceptions.Exit()
85
+
86
+
87
+ InstallCompletionOpt = Annotated[
88
+ bool,
89
+ Option(
90
+ "--install-completion",
91
+ callback=_install_completion,
92
+ is_eager=True,
93
+ help="Install completion for the current shell.",
94
+ ),
95
+ ]
96
+
97
+ ShowCompletionOpt = Annotated[
98
+ bool,
99
+ Option(
100
+ "--show-completion",
101
+ callback=_show_completion,
102
+ is_eager=True,
103
+ help="Show completion for the current shell, to copy it or customize the installation.",
104
+ ),
105
+ ]
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_cp.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ``cp`` command to copy files between local paths, repositories and buckets.
15
+
16
+ This single command backs three identical CLI entry points: ``hf cp`` (top-level),
17
+ ``hf repos cp`` and ``hf buckets cp``. It supports any source/destination combination
18
+ of local file, repo/bucket ``hf://`` URI, and ``-`` (stdin/stdout), with two exceptions:
19
+ - bucket-to-repo copies are not supported (server limitation), and
20
+ - local-to-local copies (use a regular ``cp`` for that).
21
+ """
22
+
23
+ import os
24
+ import sys
25
+ from dataclasses import replace
26
+ from typing import Annotated, Literal
27
+
28
+ import click
29
+
30
+ from huggingface_hub import HfApi
31
+ from huggingface_hub.errors import CLIError
32
+ from huggingface_hub.utils import HfUri, SoftTemporaryDirectory, disable_progress_bars, is_hf_uri, parse_hf_uri
33
+
34
+ from ._cli_utils import TokenOpt, get_hf_api
35
+ from ._framework import Argument
36
+ from ._output import out
37
+
38
+
39
+ CP_EXAMPLES = [
40
+ # Download (repo or bucket -> local / stdout)
41
+ "hf cp hf://username/my-model/config.json",
42
+ "hf cp hf://username/my-model/config.json ./config.json",
43
+ "hf cp hf://datasets/username/my-dataset/data.csv ./data/",
44
+ "hf cp hf://buckets/username/my-bucket/config.json -",
45
+ # Upload (local / stdin -> repo or bucket)
46
+ "hf cp ./model.safetensors hf://username/my-model/model.safetensors",
47
+ "hf cp ./config.json hf://buckets/username/my-bucket/logs/",
48
+ "hf cp - hf://buckets/username/my-bucket/config.json",
49
+ # Remote to remote (repo/bucket -> repo/bucket, server-side when possible)
50
+ "hf cp hf://username/source-model/ hf://username/dest-model/",
51
+ "hf cp hf://datasets/username/my-dataset/processed/ hf://buckets/username/my-bucket/processed/",
52
+ "hf cp hf://buckets/username/my-bucket/logs/ hf://buckets/username/archive-bucket/ # copies contents only",
53
+ ]
54
+
55
+
56
+ # Which alias registered the command, used to restrict the remote endpoint type (see `_enforce_context`).
57
+ CpContext = Literal["repos", "buckets"]
58
+
59
+
60
+ def make_cp(context: CpContext | None = None):
61
+ """Build the ``cp`` command function for a given alias.
62
+
63
+ The three entry points (`hf cp`, `hf repos cp`, `hf buckets cp`) share the exact same logic;
64
+ 'context' only adds a guardrail on the remote endpoint type (see `_enforce_context`).
65
+ """
66
+
67
+ def cp(
68
+ src: Annotated[
69
+ str,
70
+ Argument(help="Source: local file, hf:// URI (repo or bucket), or - for stdin."),
71
+ ],
72
+ dst: Annotated[
73
+ str | None,
74
+ Argument(help="Destination: local path, hf:// URI (repo or bucket), or - for stdout."),
75
+ ] = None,
76
+ token: TokenOpt = None,
77
+ ) -> None:
78
+ """Copy files between local paths, repositories, and buckets.
79
+
80
+ Handles uploads (local/stdin -> repo/bucket), downloads (repo/bucket -> local/stdout) and
81
+ remote-to-remote copies (repo/bucket -> repo/bucket). Bucket-to-repo and local-to-local
82
+ copies are not supported. For directories, use `hf upload`/`hf download` (repos) or
83
+ `hf buckets sync` (buckets). Remote-to-remote copies only work within the same storage
84
+ region (https://huggingface.co/docs/hub/storage-regions).
85
+ """
86
+ _enforce_context(context, src, dst)
87
+ _run_cp(src, dst, token)
88
+
89
+ return cp
90
+
91
+
92
+ def _enforce_context(context: CpContext | None, src: str, dst: str | None) -> None:
93
+ """Guardrail for the `hf repos cp` / `hf buckets cp` aliases.
94
+
95
+ These aliases are exact duplicates of `hf cp`, so a bare `hf repos cp` could otherwise touch a
96
+ bucket (and vice versa). We validate the type of the remote side: the destination for uploads and
97
+ remote-to-remote copies, or the source when downloading to a local path / stdout. The top-level
98
+ `hf cp` (i.e. 'context' is None) accepts any combination.
99
+ """
100
+ if context is None:
101
+ return
102
+ # The remote endpoint is the destination when it is an hf:// URI, otherwise the source (download).
103
+ remote = dst if (dst is not None and is_hf_uri(dst)) else src
104
+ if not is_hf_uri(remote):
105
+ return
106
+ if context == "repos" and parse_hf_uri(remote).is_bucket:
107
+ raise CLIError("`hf repos cp` only works with repositories. Use `hf cp` or `hf buckets cp` for buckets.")
108
+ if context == "buckets" and not parse_hf_uri(remote).is_bucket:
109
+ raise CLIError("`hf buckets cp` only works with buckets. Use `hf cp` or `hf repos cp` for repositories.")
110
+
111
+
112
+ def _run_cp(src: str, dst: str | None, token: str | None) -> None:
113
+ api = get_hf_api(token=token)
114
+
115
+ src_is_stdin = src == "-"
116
+ dst_is_stdout = dst == "-"
117
+ src_is_hf = is_hf_uri(src)
118
+ dst_is_hf = dst is not None and is_hf_uri(dst)
119
+
120
+ # --- Remote to remote: delegate to copy_files (repo/bucket -> repo/bucket) ---
121
+ if src_is_hf and dst_is_hf:
122
+ assert dst is not None # guaranteed by dst_is_hf
123
+ api.copy_files(src, dst)
124
+ out.result("Copied", src=src, dst=dst)
125
+ return
126
+
127
+ # --- At least one side must be a remote hf:// URI (rules out local->local, stdin->local, etc.) ---
128
+ if not src_is_hf and not dst_is_hf:
129
+ if dst is None:
130
+ raise click.BadParameter("Missing destination. Provide a repo or bucket hf:// URI as DST.")
131
+ raise click.BadParameter(
132
+ "One of SRC or DST must be a repo (hf://username/...) or bucket (hf://buckets/...) URI."
133
+ )
134
+
135
+ # --- Download: repo/bucket -> local file or stdout ---
136
+ if src_is_hf:
137
+ if dst_is_stdout:
138
+ _download_file_to_stdout(api, src)
139
+ return
140
+ _download_file_to_local(api, src, dst)
141
+ return
142
+
143
+ # --- Upload: local file or stdin -> repo/bucket ---
144
+ assert dst is not None # guaranteed: reaching here means dst_is_hf is True
145
+ _upload_file_to_remote(api, src, dst, src_is_stdin=src_is_stdin)
146
+
147
+
148
+ def _download_file_to_stdout(api: HfApi, src: str) -> None:
149
+ uri = parse_hf_uri(src)
150
+ filename = _source_filename(uri, src)
151
+ # Suppress progress bars to avoid polluting the piped output.
152
+ with disable_progress_bars():
153
+ with SoftTemporaryDirectory() as tmp_dir:
154
+ tmp_path = os.path.join(tmp_dir, filename)
155
+ _download_single(api, uri, tmp_path)
156
+ with open(tmp_path, "rb") as f:
157
+ while chunk := f.read(32_000_000): # 32MB chunks
158
+ sys.stdout.buffer.write(chunk)
159
+
160
+
161
+ def _download_file_to_local(api: HfApi, src: str, dst: str | None) -> None:
162
+ uri = parse_hf_uri(src)
163
+ filename = _source_filename(uri, src)
164
+
165
+ if dst is None:
166
+ local_path = filename
167
+ elif os.path.isdir(dst) or dst.endswith(os.sep) or dst.endswith("/"):
168
+ local_path = os.path.join(dst, filename)
169
+ else:
170
+ local_path = dst
171
+
172
+ parent_dir = os.path.dirname(local_path)
173
+ if parent_dir:
174
+ os.makedirs(parent_dir, exist_ok=True)
175
+
176
+ _download_single(api, uri, local_path)
177
+ out.result("Downloaded", src=src, dst=local_path)
178
+
179
+
180
+ def _download_single(api: HfApi, uri: HfUri, local_path: str) -> None:
181
+ """Download a single file (repo or bucket) to ``local_path``.
182
+
183
+ Used by `_download_file_to_local` and `_download_file_to_stdout`.
184
+ """
185
+ if uri.is_bucket:
186
+ api.download_bucket_files(uri.id, [(uri.path_in_repo, local_path)], raise_on_missing_files=True)
187
+ else:
188
+ # Download into a temporary folder next to the destination (rather than the shared cache)
189
+ # so the final move stays on the same filesystem and is instant. The temp folder is
190
+ # cleaned up automatically once the move is complete.
191
+ parent_dir = os.path.dirname(local_path) or "."
192
+ with SoftTemporaryDirectory(prefix=".tmp", dir=parent_dir) as tmp_dir:
193
+ downloaded_path = api.hf_hub_download(
194
+ repo_id=uri.id,
195
+ repo_type=uri.type,
196
+ filename=uri.path_in_repo,
197
+ revision=uri.revision,
198
+ local_dir=tmp_dir,
199
+ )
200
+ os.replace(downloaded_path, local_path)
201
+
202
+
203
+ def _source_filename(uri: HfUri, src: str) -> str:
204
+ if uri.path_in_repo == "" or src.endswith("/"):
205
+ raise click.BadParameter(
206
+ "Source path must include a file name, not just a repo/bucket or directory path."
207
+ " Use `hf download` or `hf buckets sync` to copy directories."
208
+ )
209
+ return uri.path_in_repo.rsplit("/", 1)[-1]
210
+
211
+
212
+ def _upload_file_to_remote(api: HfApi, src: str, dst: str, *, src_is_stdin: bool) -> None:
213
+ uri = parse_hf_uri(dst)
214
+
215
+ if src_is_stdin:
216
+ if uri.path_in_repo == "" or dst.endswith("/"):
217
+ raise click.BadParameter("Stdin upload requires a full destination path including filename.")
218
+ data = sys.stdin.buffer.read()
219
+ _upload_single(api, uri, data, uri.path_in_repo)
220
+ out.result("Uploaded", src="stdin", dst=uri.to_uri())
221
+ return
222
+
223
+ if os.path.isdir(src):
224
+ raise click.BadParameter(
225
+ "Source must be a file, not a directory. Use `hf upload` or `hf buckets sync` for directories."
226
+ )
227
+ if not os.path.isfile(src):
228
+ raise click.BadParameter(f"Source file not found: {src}")
229
+
230
+ prefix = uri.path_in_repo
231
+ if prefix == "":
232
+ remote_path = os.path.basename(src)
233
+ elif dst.endswith("/"):
234
+ remote_path = prefix + "/" + os.path.basename(src)
235
+ else:
236
+ remote_path = prefix
237
+
238
+ _upload_single(api, uri, src, remote_path)
239
+ out.result("Uploaded", src=src, dst=replace(uri, path_in_repo=remote_path).to_uri())
240
+
241
+
242
+ def _upload_single(api: HfApi, uri: HfUri, source: str | bytes, remote_path: str) -> None:
243
+ """Upload a single file or bytes (to a repo or bucket)."""
244
+ if uri.is_bucket:
245
+ api.batch_bucket_files(uri.id, add=[(source, remote_path)])
246
+ else:
247
+ api.upload_file(
248
+ path_or_fileobj=source,
249
+ path_in_repo=remote_path,
250
+ repo_id=uri.id,
251
+ repo_type=uri.type,
252
+ revision=uri.revision,
253
+ )
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_errors.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """CLI error handling utilities."""
15
+
16
+ import traceback
17
+ from collections.abc import Callable
18
+
19
+ from huggingface_hub.errors import (
20
+ BucketNotFoundError,
21
+ CLIError,
22
+ CLIExtensionInstallError,
23
+ DeviceCodeError,
24
+ EntryNotFoundError,
25
+ GatedRepoError,
26
+ HfHubHTTPError,
27
+ HfUriError,
28
+ IncompleteSnapshotError,
29
+ LocalEntryNotFoundError,
30
+ LocalTokenNotFoundError,
31
+ OfflineModeIsEnabled,
32
+ OIDCError,
33
+ RemoteEntryNotFoundError,
34
+ RepositoryNotFoundError,
35
+ RevisionNotFoundError,
36
+ )
37
+
38
+
39
+ def _format_repo_not_found(error: RepositoryNotFoundError) -> str:
40
+ label = error.repo_type.capitalize() if error.repo_type else "Repository"
41
+ if error.repo_id:
42
+ msg = f"{label} '{error.repo_id}' not found."
43
+ else:
44
+ msg = f"{label} not found."
45
+ msg += "\nIf the repo is private, make sure you are authenticated and your token has the required permissions."
46
+
47
+ msg += "\nIf the repo does not exist, create it with: "
48
+ if error.repo_id is not None:
49
+ type_flag = f" --type {error.repo_type}" if error.repo_type and error.repo_type != "model" else ""
50
+ msg += f"hf repos create {error.repo_id}{type_flag}"
51
+ else:
52
+ msg += "hf repos create <repo_id>"
53
+
54
+ return msg
55
+
56
+
57
+ def _format_gated_repo(error: GatedRepoError) -> str:
58
+ label = error.repo_type if error.repo_type else "repository"
59
+ if error.repo_id:
60
+ return f"Access denied. {label.capitalize()} '{error.repo_id}' requires approval."
61
+ return f"Access denied. This {label} requires approval."
62
+
63
+
64
+ def _format_bucket_not_found(error: BucketNotFoundError) -> str:
65
+ if error.bucket_id:
66
+ msg = f"Bucket '{error.bucket_id}' not found."
67
+ cmd = f"hf buckets create {error.bucket_id}"
68
+ else:
69
+ msg = "Bucket not found."
70
+ cmd = "hf buckets create <bucket_id>"
71
+ msg += "\nIf the bucket is private, make sure you are authenticated and your token has the required permissions."
72
+ msg += f"\nIf the bucket does not exist, create it with: {cmd}"
73
+ return msg
74
+
75
+
76
+ def _format_entry_not_found(error: RemoteEntryNotFoundError) -> str:
77
+ label = error.repo_type if error.repo_type else "repository"
78
+ url = str(error.response.url) if error.response else None
79
+ if error.repo_id:
80
+ msg = f"File not found in {label} '{error.repo_id}'."
81
+ else:
82
+ msg = f"File not found in {label}."
83
+ if url:
84
+ msg += f"\nURL: {url}"
85
+ return msg
86
+
87
+
88
+ def _format_local_entry_not_found(error: LocalEntryNotFoundError) -> str:
89
+ cause = error.__cause__
90
+ if cause is not None:
91
+ return f"Local entry not found. {cause}"
92
+ return f"Local entry not found. {error}"
93
+
94
+
95
+ def _format_incomplete_snapshot(error: IncompleteSnapshotError) -> str:
96
+ msg = _format_local_entry_not_found(error)
97
+ msg += f"\nIncomplete snapshot available at: {error.snapshot_path}"
98
+ return msg
99
+
100
+
101
+ def _format_revision_not_found(error: RevisionNotFoundError) -> str:
102
+ label = error.repo_type if error.repo_type else "repository"
103
+ if error.repo_id:
104
+ return f"Revision not found in {label} '{error.repo_id}'."
105
+ return f"Revision not found in {label}. Check the revision parameter."
106
+
107
+
108
+ def _format_cli_error(error: CLIError) -> str:
109
+ """No traceback, just the error message."""
110
+ return str(error)
111
+
112
+
113
+ def _format_cli_extension_install_error(error: CLIExtensionInstallError) -> str:
114
+ """Format a CLI extension installation error.
115
+
116
+ The error is likely to be a tricky subprocess error to investigate. In this specific case we want to format the
117
+ traceback of the root cause while keeping the "nicely formatted" error message of the CLIExtensionInstallError
118
+ as a 1-line message.
119
+ """
120
+ cause_tb = (
121
+ "".join(traceback.format_exception(type(error.__cause__), error.__cause__, error.__cause__.__traceback__))
122
+ if error.__cause__ is not None
123
+ else ""
124
+ )
125
+ return f"{cause_tb}\n{error}"
126
+
127
+
128
+ CLI_ERROR_MAPPINGS: dict[type[Exception], Callable[..., str]] = {
129
+ OfflineModeIsEnabled: lambda error: str(error),
130
+ # GatedRepoError must come before RepositoryNotFoundError (it's a subclass).
131
+ GatedRepoError: _format_gated_repo,
132
+ BucketNotFoundError: _format_bucket_not_found,
133
+ RepositoryNotFoundError: _format_repo_not_found,
134
+ RevisionNotFoundError: _format_revision_not_found,
135
+ LocalTokenNotFoundError: lambda _: "Not logged in. Run 'hf auth login' first.",
136
+ OIDCError: lambda error: f"OIDC Exchange failed. {error}",
137
+ DeviceCodeError: lambda error: f"Login failed: {error}",
138
+ RemoteEntryNotFoundError: _format_entry_not_found,
139
+ # IncompleteSnapshotError must come before LocalEntryNotFoundError (it's a subclass).
140
+ IncompleteSnapshotError: _format_incomplete_snapshot,
141
+ LocalEntryNotFoundError: _format_local_entry_not_found,
142
+ EntryNotFoundError: lambda error: str(error),
143
+ HfHubHTTPError: lambda error: str(error),
144
+ HfUriError: lambda error: f"Invalid HF URI: {error.uri}. {error.msg}",
145
+ ValueError: lambda error: f"Invalid value. {error}",
146
+ CLIExtensionInstallError: _format_cli_extension_install_error,
147
+ CLIError: _format_cli_error,
148
+ }
149
+
150
+
151
+ def format_known_exception(error: Exception) -> str | None:
152
+ for exc_type, formatter in CLI_ERROR_MAPPINGS.items():
153
+ if isinstance(error, exc_type):
154
+ return formatter(error)
155
+ return None
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_file_listing.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 helpers for listing files in buckets and repos (tree view, flat view, formatting)."""
15
+
16
+ import json
17
+ from datetime import datetime
18
+ from typing import Sequence
19
+
20
+ import click
21
+
22
+ from huggingface_hub._buckets import BucketFile, BucketFolder
23
+ from huggingface_hub.hf_api import RepoFile, RepoFolder
24
+
25
+ from ._cli_utils import get_hf_api
26
+ from ._output import OutputFormat, _ascii_safe, _dataclass_to_dict, _escape_control_chars, out
27
+
28
+
29
+ BucketItem = BucketFile | BucketFolder
30
+ RepoItem = RepoFile | RepoFolder
31
+ ListingItem = BucketItem | RepoItem
32
+
33
+
34
+ def get_item_date(item: ListingItem) -> datetime | None:
35
+ """Extract date from an item, supporting both repo items (last_commit.date) and bucket items (mtime/uploaded_at)."""
36
+ match item:
37
+ case BucketFile(mtime=mtime) if mtime is not None:
38
+ return mtime
39
+ case BucketFile(uploaded_at=uploaded_at) | BucketFolder(uploaded_at=uploaded_at) if uploaded_at is not None:
40
+ return uploaded_at
41
+ case RepoFile(last_commit=last_commit) | RepoFolder(last_commit=last_commit) if last_commit is not None:
42
+ return last_commit.date
43
+ case _:
44
+ return None
45
+
46
+
47
+ def format_size(size: int | float, human_readable: bool = False) -> str:
48
+ """Format a size in bytes."""
49
+ if not human_readable:
50
+ return str(size)
51
+
52
+ for unit in ["B", "KB", "MB", "GB", "TB"]:
53
+ if size < 1000:
54
+ if unit == "B":
55
+ return f"{size} {unit}"
56
+ return f"{size:.1f} {unit}"
57
+ size /= 1000
58
+ return f"{size:.1f} PB"
59
+
60
+
61
+ def format_date(dt: datetime | None, human_readable: bool = False) -> str:
62
+ """Format a datetime to a readable date string."""
63
+ if dt is None:
64
+ return ""
65
+ if human_readable:
66
+ return dt.strftime("%b %d %H:%M")
67
+ return dt.strftime("%Y-%m-%d %H:%M:%S")
68
+
69
+
70
+ def build_tree(
71
+ items: Sequence[BucketItem] | Sequence[RepoItem],
72
+ human_readable: bool = False,
73
+ quiet: bool = False,
74
+ ) -> list[str]:
75
+ """Build a tree representation of files and directories.
76
+
77
+ Produces ASCII tree with size and date columns before the tree connector.
78
+ When quiet=True, only the tree structure is shown (no size/date).
79
+ """
80
+ tree: dict = {}
81
+
82
+ for item in items:
83
+ parts = item.path.split("/")
84
+ current = tree
85
+ for part in parts[:-1]:
86
+ if part not in current:
87
+ current[part] = {"__children__": {}}
88
+ current = current[part]["__children__"]
89
+
90
+ final_part = parts[-1]
91
+ if isinstance(item, BucketFolder | RepoFolder):
92
+ if final_part not in current:
93
+ current[final_part] = {"__children__": {}}
94
+ else:
95
+ current[final_part] = {"__item__": item}
96
+
97
+ prefix_width = 0
98
+ max_size_width = 0
99
+ max_date_width = 0
100
+ if not quiet:
101
+ for item in items:
102
+ if isinstance(item, BucketFile | RepoFile):
103
+ size_str = format_size(item.size, human_readable)
104
+ max_size_width = max(max_size_width, len(size_str))
105
+ date_str = format_date(get_item_date(item), human_readable)
106
+ max_date_width = max(max_date_width, len(date_str))
107
+ if max_size_width > 0:
108
+ prefix_width = max_size_width + 2 + max_date_width
109
+
110
+ lines: list[str] = []
111
+ _render_tree(
112
+ tree,
113
+ lines,
114
+ "",
115
+ prefix_width=prefix_width,
116
+ max_size_width=max_size_width,
117
+ human_readable=human_readable,
118
+ )
119
+ return lines
120
+
121
+
122
+ def _render_tree(
123
+ node: dict,
124
+ lines: list[str],
125
+ indent: str,
126
+ prefix_width: int = 0,
127
+ max_size_width: int = 0,
128
+ human_readable: bool = False,
129
+ ) -> None:
130
+ """Recursively render a tree structure with size+date prefix."""
131
+ sorted_items = sorted(node.items())
132
+ for i, (name, value) in enumerate(sorted_items):
133
+ is_last = i == len(sorted_items) - 1
134
+ connector = _ascii_safe("└── ", "`-- ") if is_last else _ascii_safe("├── ", "|-- ")
135
+
136
+ is_dir = "__children__" in value
137
+ children = value.get("__children__", {})
138
+
139
+ if prefix_width > 0:
140
+ if is_dir:
141
+ prefix = " " * prefix_width
142
+ else:
143
+ item = value.get("__item__")
144
+ if item is not None:
145
+ size_str = format_size(item.size, human_readable)
146
+ date_str = format_date(get_item_date(item), human_readable)
147
+ prefix = f"{size_str:>{max_size_width}} {date_str}"
148
+ else:
149
+ prefix = " " * prefix_width
150
+ lines.append(f"{prefix} {indent}{connector}{_escape_control_chars(name)}{'/' if is_dir else ''}")
151
+ else:
152
+ lines.append(f"{indent}{connector}{_escape_control_chars(name)}{'/' if is_dir else ''}")
153
+
154
+ if children:
155
+ child_indent = indent + (" " if is_last else _ascii_safe("│ ", "| "))
156
+ _render_tree(
157
+ children,
158
+ lines,
159
+ child_indent,
160
+ prefix_width=prefix_width,
161
+ max_size_width=max_size_width,
162
+ human_readable=human_readable,
163
+ )
164
+
165
+
166
+ def list_repo_files_cmd(
167
+ repo_id: str,
168
+ repo_type: str,
169
+ human_readable: bool,
170
+ as_tree: bool,
171
+ recursive: bool,
172
+ revision: str | None,
173
+ token: str | None,
174
+ ) -> None:
175
+ """List files in a repo on the Hub. Used by models/datasets/spaces ls commands."""
176
+ if as_tree and out.mode == OutputFormat.json:
177
+ raise click.BadParameter("Cannot use --tree with --format json.")
178
+
179
+ api = get_hf_api(token=token)
180
+ items = list(api.list_repo_tree(repo_id, recursive=recursive, revision=revision, repo_type=repo_type, expand=True))
181
+ print_file_listing(items, human_readable=human_readable, as_tree=as_tree, recursive=recursive)
182
+
183
+
184
+ def print_file_listing(
185
+ items: Sequence[BucketItem] | Sequence[RepoItem],
186
+ *,
187
+ human_readable: bool = False,
188
+ as_tree: bool = False,
189
+ recursive: bool = False,
190
+ ) -> None:
191
+ """Print a file listing in the appropriate format based on the current output mode.
192
+
193
+ Supports tree, json, quiet, and flat human-readable views. Works with both
194
+ BucketFile/BucketFolder and RepoFile/RepoFolder items.
195
+ """
196
+ if not items:
197
+ out.text("(empty)")
198
+ return
199
+
200
+ has_directories = any(isinstance(item, BucketFolder | RepoFolder) for item in items)
201
+
202
+ if as_tree:
203
+ quiet = out.mode == OutputFormat.quiet
204
+ for line in build_tree(items, human_readable=human_readable, quiet=quiet):
205
+ print(line)
206
+ elif out.mode == OutputFormat.json:
207
+ print(json.dumps([_dataclass_to_dict(item) for item in items], indent=2))
208
+ elif out.mode == OutputFormat.quiet:
209
+ for item in items:
210
+ if isinstance(item, BucketFolder | RepoFolder):
211
+ print(f"{_escape_control_chars(item.path)}/")
212
+ else:
213
+ print(_escape_control_chars(item.path))
214
+ else:
215
+ for item in items:
216
+ if isinstance(item, BucketFolder | RepoFolder):
217
+ date_str = format_date(get_item_date(item), human_readable)
218
+ print(f"{'':>12} {date_str:>19} {_escape_control_chars(item.path)}/")
219
+ else:
220
+ size_str = format_size(item.size, human_readable)
221
+ date_str = format_date(get_item_date(item), human_readable)
222
+ print(f"{size_str:>12} {date_str:>19} {_escape_control_chars(item.path)}")
223
+
224
+ if not recursive and has_directories:
225
+ out.hint("Use -R to list files recursively.")
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_framework.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Minimal declaration layer over Click 8.x for the ``hf`` CLI.
15
+
16
+ This module vendors *only* the slice of Typer the CLI actually uses: turning
17
+ annotated function signatures (``Annotated[T, Option(...)]`` / ``Argument(...)``)
18
+ into Click parameters, and rendering argument/option help the way Typer did.
19
+ It exists so the CLI depends on Click's stable public API instead of Typer's
20
+ now-internal vendored Click (``typer._click``), which Typer reserves the right
21
+ to refactor at any release.
22
+
23
+ Deliberately *not* implemented (add a case here only when a command needs it):
24
+ rich rendering, shell-completion install commands, prompts/confirmation options,
25
+ env-var options, ``File``/``UUID`` params, ``count`` options, ``default_factory``.
26
+ Click's own machinery already handles exceptions, aborts, exits, and native
27
+ ``_HF_COMPLETE`` shell completion, so none of Typer's ``main()`` overrides are
28
+ reproduced here.
29
+
30
+ The interesting logic mirrors four Typer functions, kept faithful so ``--help``
31
+ output stays byte-identical:
32
+ - :func:`_get_click_type` <- ``typer.main.get_click_type``
33
+ - :func:`_build_click_param` <- ``typer.main.get_click_param``
34
+ - :func:`_make_handler` <- ``typer.main.get_callback``
35
+ - :class:`HfArgument` / :class:`HfOption` help records <- ``typer.core.Typer*``
36
+ """
37
+
38
+ import enum
39
+ import functools
40
+ import inspect
41
+ from collections.abc import Callable, Sequence
42
+ from datetime import datetime
43
+ from pathlib import Path
44
+ from types import UnionType
45
+ from typing import Annotated, Any, Literal, Union, get_args, get_origin
46
+
47
+ import click
48
+
49
+
50
+ def get_command_name(name: str) -> str:
51
+ """Normalize a Python identifier to a CLI name (``force_download`` -> ``force-download``)."""
52
+ return name.lower().replace("_", "-")
53
+
54
+
55
+ # ---------------------------------------------------------------------------
56
+ # 1. Declaration markers — replace ``typer.Option`` / ``typer.Argument``.
57
+ # Attached in ``Annotated[T, Option(...)]``; the ``= value`` in the function
58
+ # signature carries the default (never the marker).
59
+ # ---------------------------------------------------------------------------
60
+
61
+
62
+ class ParameterInfo:
63
+ """Base marker holding the (tiny) set of Click knobs the CLI actually sets.
64
+
65
+ ``callback`` is a Typer-style value parser ``fn(value) -> parsed`` — it does NOT
66
+ receive Click's ``(ctx, param, value)``. It consumes the enum/list convertors, so
67
+ ``value`` is already converted when it runs.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ *param_decls: str,
73
+ help: str | None = None,
74
+ show_default: bool | str = True,
75
+ hidden: bool = False,
76
+ is_eager: bool = False,
77
+ callback: Callable[..., Any] | None = None,
78
+ min: int | None = None,
79
+ click_type: click.ParamType | None = None,
80
+ ) -> None:
81
+ self.param_decls = list(param_decls)
82
+ self.help = help
83
+ self.show_default = show_default
84
+ self.hidden = hidden
85
+ self.is_eager = is_eager
86
+ self.callback = callback
87
+ self.min = min
88
+ self.click_type = click_type
89
+
90
+
91
+ class Option(ParameterInfo):
92
+ """Declare a CLI option, e.g. ``Annotated[str | None, Option("--revision")]``."""
93
+
94
+
95
+ class Argument(ParameterInfo):
96
+ """Declare a positional CLI argument, e.g. ``Annotated[str, Argument()]``."""
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # 2. Annotation -> Click type + value convertors.
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ def _get_click_type(annotation: Any, info: ParameterInfo) -> click.ParamType:
105
+ """Map a (already unwrapped) annotation to a Click ``ParamType``."""
106
+ if info.click_type is not None:
107
+ return info.click_type
108
+ if annotation is str:
109
+ return click.STRING
110
+ if annotation is bool:
111
+ return click.BOOL
112
+ if annotation is int:
113
+ return click.IntRange(min=info.min) if info.min is not None else click.INT
114
+ if annotation is float:
115
+ return click.FloatRange(min=info.min) if info.min is not None else click.FLOAT
116
+ if annotation is Path:
117
+ return click.Path(path_type=Path)
118
+ if annotation is datetime:
119
+ return click.DateTime()
120
+ if isinstance(annotation, type) and issubclass(annotation, enum.Enum):
121
+ values = [item.value for item in annotation]
122
+ if not all(isinstance(value, str) for value in values):
123
+ # A non-str member default would fail Choice validation at parse time with a
124
+ # cryptic error; fail at build time with a clear one instead.
125
+ raise TypeError(f"Unsupported enum {annotation.__name__!r}: only str-valued enums are supported.")
126
+ return click.Choice(values)
127
+ if get_origin(annotation) is Literal:
128
+ return click.Choice([str(value) for value in get_args(annotation)])
129
+ raise TypeError(f"Unsupported CLI annotation {annotation!r}. Add a case in `_framework._get_click_type()`.")
130
+
131
+
132
+ def _enum_convertor(enum_type: type[enum.Enum]) -> Callable[[Any], Any]:
133
+ """Map a parsed choice string back to its ``Enum`` member (mirrors Typer)."""
134
+ value_map = {str(member.value): member for member in enum_type}
135
+
136
+ def convertor(value: Any) -> Any:
137
+ if value is not None:
138
+ return value_map.get(str(value))
139
+ return None
140
+
141
+ return convertor
142
+
143
+
144
+ def _list_convertor(
145
+ inner: Callable[[Any], Any] | None, default_value: Any | None
146
+ ) -> Callable[[Sequence[Any] | None], list[Any] | None]:
147
+ """Turn Click's tuple (from ``multiple=True``) into a list, applying ``inner`` per item."""
148
+
149
+ def convertor(value: Sequence[Any] | None) -> list[Any] | None:
150
+ if value is None or (default_value is None and len(value) == 0):
151
+ return None
152
+ return [inner(item) if inner else item for item in value]
153
+
154
+ return convertor
155
+
156
+
157
+ def _make_convertor(
158
+ annotation: Any, is_list: bool, default_value: Any | None, info: ParameterInfo
159
+ ) -> Callable[[Any], Any] | None:
160
+ """Build the value convertor for a param (``None`` when no coercion is needed).
161
+
162
+ An explicit ``click_type`` (e.g. ``SoftChoice``) owns its own conversion, so no
163
+ enum convertor is added on top of it.
164
+ """
165
+ inner = None
166
+ if info.click_type is None and isinstance(annotation, type) and issubclass(annotation, enum.Enum):
167
+ inner = _enum_convertor(annotation)
168
+ if is_list:
169
+ return _list_convertor(inner, default_value)
170
+ return inner
171
+
172
+
173
+ def _unwrap_optional_and_list(annotation: Any) -> tuple[Any, bool]:
174
+ """Strip ``T | None`` / ``Optional[T]`` and ``list[T]``; return ``(base_type, is_list)``."""
175
+ origin = get_origin(annotation)
176
+ if origin in (Union, UnionType):
177
+ non_none = [arg for arg in get_args(annotation) if arg is not type(None)]
178
+ if len(non_none) != 1:
179
+ raise TypeError(f"Unsupported union annotation {annotation!r}; only ``T | None`` is supported.")
180
+ annotation = non_none[0]
181
+ origin = get_origin(annotation)
182
+ if origin in (list, Sequence):
183
+ return get_args(annotation)[0], True
184
+ return annotation, False
185
+
186
+
187
+ def _split_annotated(annotation: Any) -> tuple[Any, ParameterInfo | None]:
188
+ """Split ``Annotated[T, Option(...)]`` into ``(T, marker)``; ``(annotation, None)`` otherwise."""
189
+ if get_origin(annotation) is Annotated:
190
+ args = get_args(annotation)
191
+ marker = next((meta for meta in args[1:] if isinstance(meta, ParameterInfo)), None)
192
+ if marker is None and (typer_marker := next((meta for meta in args[1:] if _is_typer_marker(meta)), None)):
193
+ marker = _from_typer_marker(typer_marker, from_annotated=True)
194
+ return args[0], marker
195
+ return annotation, None
196
+
197
+
198
+ # ---------------------------------------------------------------------------
199
+ # Typer-marker compatibility shim (transition helper).
200
+ #
201
+ # ``typer_factory`` is exposed publicly and downstream CLIs (e.g. `transformers`)
202
+ # still register commands whose parameters carry ``typer.Option`` /
203
+ # ``typer.Argument`` markers. Recognize those markers structurally (no typer
204
+ # import required) and translate the fields this framework supports, so such
205
+ # commands keep working while downstream migrates.
206
+ # TODO: remove once transformers pins huggingface_hub>=1.22.0.
207
+ # ---------------------------------------------------------------------------
208
+
209
+
210
+ def _is_typer_marker(obj: Any) -> bool:
211
+ return type(obj).__module__.partition(".")[0] == "typer" and type(obj).__name__ in ("OptionInfo", "ArgumentInfo")
212
+
213
+
214
+ def _from_typer_marker(meta: Any, *, from_annotated: bool) -> ParameterInfo:
215
+ """Translate a ``typer.models.OptionInfo`` / ``ArgumentInfo`` into our marker."""
216
+ param_decls = list(getattr(meta, "param_decls", None) or ())
217
+ if type(meta).__name__ == "OptionInfo":
218
+ # In ``Annotated[...]`` usage typer stores the first flag name in ``default``
219
+ # (``Option("--flag", "-f")`` -> ``default="--flag"``, ``param_decls=("-f",)``).
220
+ default = getattr(meta, "default", ...)
221
+ if from_annotated and isinstance(default, str):
222
+ param_decls = [default, *param_decls]
223
+ cls: type[ParameterInfo] = Option
224
+ else:
225
+ cls = Argument
226
+ return cls(
227
+ *param_decls,
228
+ help=getattr(meta, "help", None),
229
+ show_default=getattr(meta, "show_default", True),
230
+ hidden=getattr(meta, "hidden", False),
231
+ is_eager=getattr(meta, "is_eager", False),
232
+ callback=getattr(meta, "callback", None),
233
+ min=getattr(meta, "min", None),
234
+ click_type=getattr(meta, "click_type", None),
235
+ )
236
+
237
+
238
+ # ---------------------------------------------------------------------------
239
+ # 3. Signature -> Click parameters (mirrors ``typer.main.get_click_param``).
240
+ # ---------------------------------------------------------------------------
241
+
242
+
243
+ def _wrap_param_callback(
244
+ user_callback: Callable[[Any], Any], convertor: Callable[[Any], Any] | None
245
+ ) -> Callable[[click.Context, click.Parameter, Any], Any]:
246
+ """Adapt a Typer-style value parser ``fn(value) -> parsed`` to a Click param callback."""
247
+
248
+ def click_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
249
+ return user_callback(convertor(value) if convertor else value)
250
+
251
+ return click_callback
252
+
253
+
254
+ def _build_click_param(
255
+ name: str, annotation: Any, info: ParameterInfo | None, signature_default: Any
256
+ ) -> tuple[click.Parameter, Callable[[Any], Any] | None]:
257
+ """Build a Click ``Parameter`` (and its post-parse value convertor) for one function param."""
258
+ required = signature_default is inspect.Parameter.empty
259
+ default_value = None if required else signature_default
260
+ if isinstance(default_value, enum.Enum):
261
+ default_value = default_value.value
262
+ if info is None:
263
+ # A bare annotation with no marker: required positional -> Argument, else Option.
264
+ info = Argument() if required else Option()
265
+
266
+ base_type, is_list = _unwrap_optional_and_list(annotation)
267
+ convertor = _make_convertor(base_type, is_list, default_value, info)
268
+
269
+ # A user ``callback`` consumes the value itself (and the convertor with it); otherwise the
270
+ # convertor runs later in the command handler wrapper. This keeps conversion single-pass.
271
+ if info.callback is not None:
272
+ param_callback: Callable[..., Any] | None = _wrap_param_callback(info.callback, convertor)
273
+ handler_convertor: Callable[[Any], Any] | None = None
274
+ else:
275
+ param_callback = None
276
+ handler_convertor = convertor
277
+
278
+ if isinstance(info, Argument):
279
+ argument = HfArgument(
280
+ [name],
281
+ type=_get_click_type(base_type, info),
282
+ required=required,
283
+ default=default_value,
284
+ nargs=-1 if is_list else 1,
285
+ is_eager=info.is_eager,
286
+ callback=param_callback,
287
+ help=info.help,
288
+ show_default=info.show_default,
289
+ hidden=info.hidden,
290
+ )
291
+ return argument, handler_convertor
292
+
293
+ # Option: prepend the Python name so ``click.Parameter.name`` matches the function kwarg,
294
+ # regardless of the user-facing flag names ("-v"/"--version", "--type"/"--repo-type", ...).
295
+ is_flag = base_type is bool
296
+ decls = [name]
297
+ if info.param_decls:
298
+ decls.extend(info.param_decls)
299
+ else:
300
+ kebab = get_command_name(name)
301
+ decls.append(f"--{kebab}/--no-{kebab}" if is_flag else f"--{kebab}")
302
+ option = HfOption(
303
+ decls,
304
+ # Click infers the flag type itself; passing a type alongside ``is_flag`` is rejected.
305
+ type=None if is_flag else _get_click_type(base_type, info),
306
+ required=required,
307
+ default=default_value,
308
+ is_flag=is_flag,
309
+ multiple=is_list,
310
+ is_eager=info.is_eager,
311
+ callback=param_callback,
312
+ help=info.help,
313
+ show_default=info.show_default,
314
+ hidden=info.hidden,
315
+ )
316
+ return option, handler_convertor
317
+
318
+
319
+ def _build_params(
320
+ func: Callable[..., Any],
321
+ ) -> tuple[list[click.Parameter], dict[str, Callable[[Any], Any]], str | None]:
322
+ """Introspect ``func`` and return ``(params, convertors, context_param_name)``."""
323
+ params: list[click.Parameter] = []
324
+ convertors: dict[str, Callable[[Any], Any]] = {}
325
+ context_param_name: str | None = None
326
+ for name, sig_param in inspect.signature(func).parameters.items():
327
+ # Read raw signature annotations rather than ``typing.get_type_hints``: the CLI never uses
328
+ # ``from __future__ import annotations``, so annotations are already live objects, and
329
+ # get_type_hints mangles ``Annotated[X | None, ...]`` on Python 3.10 (drops the origin).
330
+ annotation = sig_param.annotation if sig_param.annotation is not inspect.Parameter.empty else str
331
+ base_type, info = _split_annotated(annotation)
332
+ if isinstance(base_type, type) and (
333
+ issubclass(base_type, click.Context)
334
+ # typer.Context subclasses typer's *vendored* click since typer 0.26, so an
335
+ # issubclass check against real click misses it. Match it structurally.
336
+ or (base_type.__module__.partition(".")[0] == "typer" and base_type.__name__ == "Context")
337
+ ):
338
+ context_param_name = name
339
+ continue
340
+ signature_default = sig_param.default
341
+ if _is_typer_marker(signature_default):
342
+ # Old typer style: the marker *is* the signature default and carries the value.
343
+ if info is None:
344
+ info = _from_typer_marker(signature_default, from_annotated=False)
345
+ marker_default = getattr(signature_default, "default", ...)
346
+ signature_default = inspect.Parameter.empty if marker_default is ... else marker_default
347
+ click_param, convertor = _build_click_param(name, base_type, info, signature_default)
348
+ if convertor is not None and click_param.name is not None:
349
+ convertors[click_param.name] = convertor
350
+ params.append(click_param)
351
+ return params, convertors, context_param_name
352
+
353
+
354
+ def _make_handler(
355
+ func: Callable[..., Any],
356
+ convertors: dict[str, Callable[[Any], Any]],
357
+ context_param_name: str | None,
358
+ ) -> Callable[..., Any]:
359
+ """Wrap ``func`` so Click's kwargs map back to it, applying convertors and injecting the ctx."""
360
+
361
+ def handler(**kwargs: Any) -> Any:
362
+ call_kwargs = {key: (convertors[key](value) if key in convertors else value) for key, value in kwargs.items()}
363
+ if context_param_name is not None:
364
+ call_kwargs[context_param_name] = click.get_current_context()
365
+ return func(**call_kwargs)
366
+
367
+ functools.update_wrapper(handler, func)
368
+ return handler
369
+
370
+
371
+ # ---------------------------------------------------------------------------
372
+ # 4. Click parameter subclasses — port Typer's help records so arguments show up
373
+ # in ``--help`` (plain ``click.Argument`` renders none) and defaults/metavars
374
+ # read identically. Rich/env-var branches are dropped (never enabled here).
375
+ # ---------------------------------------------------------------------------
376
+
377
+
378
+ def _split_opt(opt: str) -> tuple[str, str]:
379
+ """Split an option string into ``(prefix, name)`` (Click's ``split_opt``, inlined)."""
380
+ first = opt[:1]
381
+ if first.isalnum():
382
+ return "", opt
383
+ if opt[1:2] == first:
384
+ return opt[:2], opt[2:]
385
+ return first, opt[1:]
386
+
387
+
388
+ def _extract_default_help_str(param: click.Parameter, ctx: click.Context) -> Any:
389
+ # Resilient parsing avoids type casting failing while rendering the default.
390
+ resilient = ctx.resilient_parsing
391
+ ctx.resilient_parsing = True
392
+ try:
393
+ return param.get_default(ctx, call=False)
394
+ finally:
395
+ ctx.resilient_parsing = resilient
396
+
397
+
398
+ def _default_string(
399
+ param: "HfArgument | HfOption", ctx: click.Context, show_default_is_str: bool, default_value: Any
400
+ ) -> str:
401
+ if show_default_is_str:
402
+ return f"({param.show_default})"
403
+ if isinstance(default_value, (list, tuple)):
404
+ return ", ".join(_default_string(param, ctx, show_default_is_str, item) for item in default_value)
405
+ if isinstance(default_value, enum.Enum):
406
+ return str(default_value.value)
407
+ if inspect.isfunction(default_value):
408
+ return "(dynamic)"
409
+ if isinstance(param, HfOption) and param.is_bool_flag and param.secondary_opts:
410
+ # Boolean toggle: show the opt name (without prefix) matching the current default.
411
+ if default_value:
412
+ return _split_opt(param.opts[0])[1] if param.opts else str(default_value)
413
+ return _split_opt(param.secondary_opts[0])[1]
414
+ if isinstance(param, HfOption) and param.is_bool_flag and not param.secondary_opts and not default_value:
415
+ return ""
416
+ return str(default_value)
417
+
418
+
419
+ def _describe_number_range(param_type: "click.IntRange | click.FloatRange") -> str:
420
+ """Human-readable range hint like ``x>=1`` or ``1<=x<10``.
421
+
422
+ Reproduces click's private ``_NumberRangeBase._describe_range()`` using the public
423
+ ``IntRange``/``FloatRange`` attributes, so the framework stays on Click's public API.
424
+ """
425
+ if param_type.min is None:
426
+ return f"x{'<' if param_type.max_open else '<='}{param_type.max}"
427
+ if param_type.max is None:
428
+ return f"x{'>' if param_type.min_open else '>='}{param_type.min}"
429
+ left = "<" if param_type.min_open else "<="
430
+ right = "<" if param_type.max_open else "<="
431
+ return f"{param_type.min}{left}x{right}{param_type.max}"
432
+
433
+
434
+ def _build_help_extra(param: "HfArgument | HfOption", ctx: click.Context, base_help: str) -> str:
435
+ """Append the ``[default: ...; required]`` suffix to a help string (shared by arg/option)."""
436
+ extra: list[str] = []
437
+ default_value = _extract_default_help_str(param, ctx)
438
+ show_default_is_str = isinstance(param.show_default, str)
439
+ if show_default_is_str or (default_value is not None and (param.show_default or ctx.show_default)):
440
+ default_string = _default_string(param, ctx, show_default_is_str, default_value)
441
+ if default_string:
442
+ extra.append(f"default: {default_string}")
443
+ # Numeric range hints are shown for options only (matches Typer; arguments omit them).
444
+ if isinstance(param, HfOption) and isinstance(param.type, (click.IntRange, click.FloatRange)):
445
+ range_str = _describe_number_range(param.type)
446
+ if range_str:
447
+ extra.append(range_str)
448
+ if param.required:
449
+ extra.append("required")
450
+ if extra:
451
+ suffix = f"[{'; '.join(extra)}]"
452
+ return f"{base_help} {suffix}" if base_help else suffix
453
+ return base_help
454
+
455
+
456
+ class HfArgument(click.Argument):
457
+ """Positional argument that renders help text and a metavar (Click's does neither)."""
458
+
459
+ def __init__(
460
+ self,
461
+ param_decls: Sequence[str],
462
+ *,
463
+ help: str | None = None,
464
+ show_default: bool | str = True,
465
+ hidden: bool = False,
466
+ **attrs: Any,
467
+ ) -> None:
468
+ self.show_default = show_default
469
+ self.hidden = hidden
470
+ super().__init__(param_decls, **attrs)
471
+ # Set *after* ``super().__init__``: Click >= 8.5 gives ``Argument`` its own ``help``
472
+ # parameter and resets ``self.help`` to ``None`` in its constructor.
473
+ self.help = help
474
+
475
+ def make_metavar(self, ctx: click.Context) -> str:
476
+ if self.metavar is not None:
477
+ var = self.metavar
478
+ if not self.required and not var.startswith("["):
479
+ var = f"[{var}]"
480
+ return var
481
+ var = (self.name or "").upper()
482
+ if not self.required:
483
+ var = f"[{var}]"
484
+ type_var = self.type.get_metavar(self, ctx=ctx)
485
+ if type_var:
486
+ var += f":{type_var}"
487
+ if self.nargs != 1:
488
+ var += "..."
489
+ return var
490
+
491
+ def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
492
+ if self.hidden:
493
+ return None
494
+ return self.make_metavar(ctx=ctx), _build_help_extra(self, ctx, self.help or "")
495
+
496
+
497
+ class HfOption(click.Option):
498
+ """Option whose help record ports Typer's default/metavar rendering verbatim."""
499
+
500
+ show_default: bool | str
501
+
502
+ def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
503
+ if self.hidden:
504
+ return None
505
+
506
+ any_prefix_is_slash = False
507
+
508
+ def _write_opts(opts: Sequence[str]) -> str:
509
+ nonlocal any_prefix_is_slash
510
+ rv, any_slashes = click.formatting.join_options(opts)
511
+ if any_slashes:
512
+ any_prefix_is_slash = True
513
+ if not self.is_flag and not self.count:
514
+ rv += f" {self.make_metavar(ctx=ctx)}"
515
+ return rv
516
+
517
+ rv = [_write_opts(self.opts)]
518
+ if self.secondary_opts:
519
+ rv.append(_write_opts(self.secondary_opts))
520
+
521
+ help_text = _build_help_extra(self, ctx, self.help or "")
522
+ return ("; " if any_prefix_is_slash else " / ").join(rv), help_text
523
+
524
+
525
+ # ---------------------------------------------------------------------------
526
+ # 5. Command / group base classes and the decorator API (replace ``typer.Typer``).
527
+ # ---------------------------------------------------------------------------
528
+
529
+
530
+ def _format_params(command: click.Command, ctx: click.Context, formatter: click.HelpFormatter) -> None:
531
+ """Render params split into "Arguments" and "Options" sections (mirrors Typer)."""
532
+ args: list[tuple[str, str]] = []
533
+ opts: list[tuple[str, str]] = []
534
+ for param in command.get_params(ctx):
535
+ record = param.get_help_record(ctx)
536
+ if record is None:
537
+ continue
538
+ if param.param_type_name == "argument":
539
+ args.append(record)
540
+ elif param.param_type_name == "option":
541
+ opts.append(record)
542
+ if args:
543
+ with formatter.section("Arguments"):
544
+ formatter.write_dl(args)
545
+ if opts:
546
+ with formatter.section("Options"):
547
+ formatter.write_dl(opts)
548
+
549
+
550
+ class HfCommand(click.Command):
551
+ """Leaf command that renders arguments and options in separate help sections."""
552
+
553
+ def format_arguments(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
554
+ # Click >= 8.5 added a `format_arguments` step to `format_help` that prints its own
555
+ # "Positional arguments" section. `_format_params` already lists arguments (Typer-style),
556
+ # so this override avoids printing them twice. Never called on Click < 8.5.
557
+ return None
558
+
559
+ def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
560
+ _format_params(self, ctx, formatter)
561
+
562
+
563
+ def build_command(
564
+ func: Callable[..., Any],
565
+ *,
566
+ name: str | None = None,
567
+ cls: type[click.Command] | None = None,
568
+ help: str | None = None,
569
+ epilog: str | None = None,
570
+ short_help: str | None = None,
571
+ options_metavar: str = "[OPTIONS]",
572
+ add_help_option: bool = True,
573
+ no_args_is_help: bool = False,
574
+ hidden: bool = False,
575
+ deprecated: bool = False,
576
+ context_settings: dict[str, Any] | None = None,
577
+ ) -> click.Command:
578
+ """Build a Click ``Command`` from a function with ``Annotated`` params.
579
+
580
+ Replaces ``typer.main.get_command_from_info``.
581
+ """
582
+ params, convertors, context_param_name = _build_params(func)
583
+ handler = _make_handler(func, convertors, context_param_name)
584
+ command_help = inspect.cleandoc(help) if help else inspect.getdoc(func)
585
+ return (cls or HfCommand)(
586
+ name=name if name is not None else get_command_name(func.__name__),
587
+ callback=handler,
588
+ params=params,
589
+ help=command_help,
590
+ epilog=epilog,
591
+ short_help=short_help,
592
+ options_metavar=options_metavar,
593
+ add_help_option=add_help_option,
594
+ no_args_is_help=no_args_is_help,
595
+ hidden=hidden,
596
+ deprecated=deprecated,
597
+ context_settings=context_settings or {},
598
+ )
599
+
600
+
601
+ class HfGroup(click.Group):
602
+ """Command group with the decorator API the CLI relies on (``command``/``callback``/``add_group``).
603
+
604
+ Subclasses (see ``HFCliTyperGroup``) layer on styling, aliases, topics and error
605
+ enrichment; this base only wires functions to Click via :func:`build_command`.
606
+ """
607
+
608
+ #: Command class used by ``@group.command()`` unless overridden per call.
609
+ command_class: type[click.Command] = HfCommand
610
+
611
+ def format_arguments(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
612
+ # See `HfCommand.format_arguments`.
613
+ return None
614
+
615
+ def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
616
+ _format_params(self, ctx, formatter)
617
+ self.format_commands(ctx, formatter)
618
+
619
+ def list_commands(self, ctx: click.Context) -> list[str]:
620
+ # Preserve declaration order rather than Click's alphabetical default.
621
+ return list(self.commands)
622
+
623
+ def command( # type: ignore # deliberately narrows click.Group.command (builds from annotated signatures)
624
+ self, name: str | None = None, *, cls: type[click.Command] | None = None, **kwargs: Any
625
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
626
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
627
+ command = build_command(func, name=name, cls=cls or self.command_class, **kwargs)
628
+ self.add_command(command, command.name)
629
+ return func
630
+
631
+ return decorator
632
+
633
+ def add_group(self, group: click.Group, *, name: str, hidden: bool = False) -> None:
634
+ """Register a subgroup under ``name`` (which may carry pipe aliases, e.g. ``"repos | repo"``)."""
635
+ group.name = name
636
+ group.hidden = hidden
637
+ self.add_command(group, name)
638
+
639
+ def group_callback(
640
+ self, *, invoke_without_command: bool = False
641
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
642
+ """Register the function invoked for this group (named ``group_callback`` because Click
643
+ already uses the ``callback`` attribute for the group's own handler)."""
644
+
645
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
646
+ params, convertors, context_param_name = _build_params(func)
647
+ self.callback = _make_handler(func, convertors, context_param_name)
648
+ self.params = [*self.params, *params]
649
+ self.invoke_without_command = invoke_without_command
650
+ if invoke_without_command:
651
+ # Match Typer: the subcommand is optional when the group runs without one.
652
+ self.subcommand_metavar = "[COMMAND] [ARGS]..."
653
+ if self.help is None and func.__doc__:
654
+ self.help = inspect.cleandoc(func.__doc__)
655
+ return func
656
+
657
+ return decorator
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_help_formatter.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Pretty ANSI help formatter for the `hf` CLI."""
15
+
16
+ from collections.abc import Iterable
17
+
18
+ import click
19
+
20
+ from huggingface_hub.utils import ANSI
21
+
22
+
23
+ class StyledHelpFormatter(click.HelpFormatter):
24
+ def write_heading(self, heading: str) -> None:
25
+ styled = ANSI.underline(heading + ":")
26
+ self.write(f"{'':>{self.current_indent}}{styled}\n")
27
+
28
+ def write_dl(self, rows: Iterable[tuple[str, str]], col_max: int = 30, col_spacing: int = 2) -> None:
29
+ rows = [(ANSI.bold(first), second) for first, second in rows]
30
+ super().write_dl(rows, col_max=col_max, col_spacing=col_spacing)
31
+
32
+
33
+ class StyledContext(click.Context):
34
+ formatter_class = StyledHelpFormatter
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_output.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Output framework for the `hf` CLI."""
15
+
16
+ import dataclasses
17
+ import datetime
18
+ import json
19
+ import re
20
+ import shutil
21
+ import sys
22
+ from collections.abc import Sequence
23
+ from enum import Enum
24
+ from functools import cache
25
+ from typing import Any, cast
26
+
27
+ import click
28
+
29
+ from huggingface_hub import constants
30
+ from huggingface_hub.errors import ConfirmationError
31
+ from huggingface_hub.repocard_data import CardData
32
+ from huggingface_hub.utils import ANSI, StatusLine, disable_progress_bars, enable_progress_bars, is_agent, tabulate
33
+
34
+
35
+ class OutputFormat(str, Enum):
36
+ """Output format for CLI commands with auto detection of agent/human mode."""
37
+
38
+ agent = "agent"
39
+ auto = "auto"
40
+ human = "human"
41
+ json = "json"
42
+ quiet = "quiet"
43
+
44
+
45
+ def _print_flush(*values: Any, **kwargs: Any) -> None:
46
+ """Like `print`, but always flushed: some CLI flows block on user action right after
47
+ printing (e.g. the device-code login), so output must not stay buffered."""
48
+ print(*values, **kwargs, flush=True)
49
+
50
+
51
+ class Output:
52
+ """Output sink for the `hf` CLI.
53
+
54
+ Mode is resolved once at init time based on `is_agent()` auto-detection
55
+ and can be overridden per-command via `set_mode()`.
56
+ """
57
+
58
+ mode: OutputFormat
59
+ no_truncate: bool
60
+
61
+ def __init__(self) -> None:
62
+ self.no_truncate = False
63
+ self.set_mode()
64
+
65
+ def set_mode(self, mode: OutputFormat = OutputFormat.auto) -> None:
66
+ """Override the output mode (called once at startup and again per '--format' flag)."""
67
+ if mode == OutputFormat.auto:
68
+ mode = OutputFormat.agent if is_agent() else OutputFormat.human
69
+ self.mode = mode
70
+ is_human = mode == OutputFormat.human
71
+ ANSI.set_enabled(is_human)
72
+ if constants.HF_HUB_DISABLE_PROGRESS_BARS is None: # env var has priority
73
+ if is_human:
74
+ enable_progress_bars()
75
+ else:
76
+ disable_progress_bars()
77
+
78
+ def set_no_truncate(self, no_truncate: bool) -> None:
79
+ """Toggle off cell truncation for human table output."""
80
+ self.no_truncate = no_truncate
81
+
82
+ def is_quiet(self) -> bool:
83
+ return self.mode == OutputFormat.quiet
84
+
85
+ def text(self, msg: str | None = None, *, human: str | None = None, agent: str | None = None) -> None:
86
+ """Print a free-form text message to stdout."""
87
+ if msg is not None:
88
+ if human is not None or agent is not None:
89
+ raise ValueError("Cannot mix 'msg' with 'human'/'agent'.")
90
+ human = msg
91
+ agent = _strip_ansi(msg)
92
+
93
+ match self.mode:
94
+ case OutputFormat.human:
95
+ if human is not None:
96
+ _print_flush(human)
97
+ case OutputFormat.agent:
98
+ if agent is not None:
99
+ _print_flush(agent)
100
+ # json/quiet: no-op
101
+
102
+ def table(
103
+ self,
104
+ items: Sequence[dict[str, Any]],
105
+ *,
106
+ headers: list[str] | None = None,
107
+ id_key: str | None = None,
108
+ alignments: dict[str, str] | None = None,
109
+ ) -> None:
110
+ """Print tabular data to stdout.
111
+
112
+ Args:
113
+ items: List of dicts. Headers are auto-detected from keys if not provided.
114
+ headers: Explicit column names. If None, derived from dict keys (all-None columns filtered).
115
+ id_key: Key to print in quiet mode. If None, uses the first header.
116
+ alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
117
+ """
118
+ if not items:
119
+ match self.mode:
120
+ case OutputFormat.agent | OutputFormat.human:
121
+ _print_flush("No results found.")
122
+ case OutputFormat.json:
123
+ _print_flush("[]")
124
+ return
125
+
126
+ if headers is None:
127
+ all_columns = list(items[0].keys())
128
+ headers = [col for col in all_columns if any(item.get(col) is not None for item in items)]
129
+ rows = [[item.get(h) for h in headers] for item in items]
130
+
131
+ match self.mode:
132
+ case OutputFormat.human: # padded table, adaptive truncation, SCREAMING_SNAKE headers
133
+ screaming_headers = [_to_header(h) for h in headers]
134
+ formatted_rows: list[list[str]] = [[_format_table_value_human(v) for v in row] for row in rows]
135
+
136
+ is_truncated = _truncate_columns(screaming_headers, formatted_rows, no_truncate=self.no_truncate)
137
+
138
+ inferred = {**_infer_alignments(headers, rows), **(alignments or {})}
139
+ screaming_alignments = {_to_header(k): v for k, v in inferred.items()}
140
+ _print_flush(
141
+ tabulate(
142
+ cast("list[list[str | int]]", formatted_rows),
143
+ headers=screaming_headers,
144
+ alignments=screaming_alignments,
145
+ ),
146
+ )
147
+ if is_truncated:
148
+ self.hint("Use `--no-truncate` or `--format json` to display full values.")
149
+ case OutputFormat.agent: # TSV, no truncation, full timestamps
150
+ _print_flush("\t".join(headers))
151
+ for row in rows:
152
+ _print_flush("\t".join(_format_table_cell_agent(v) for v in row))
153
+ case OutputFormat.json: # compact JSON array
154
+ _print_flush(json.dumps(list(items), default=str))
155
+ case OutputFormat.quiet: # id_key column (or first column), one per line
156
+ quiet_key = id_key or headers[0]
157
+ for item in items:
158
+ _print_flush(_escape_control_chars(str(item.get(quiet_key, ""))))
159
+
160
+ def dict(self, data: Any, *, id_key: str | None = None) -> None:
161
+ """Print structured data as JSON in all modes (indented for human, compact otherwise).
162
+
163
+ Accepts a dict or a dataclass.
164
+ """
165
+ if dataclasses.is_dataclass(data) and not isinstance(data, type):
166
+ data = _dataclass_to_dict(data)
167
+ if self.mode == OutputFormat.quiet and id_key is not None:
168
+ _print_flush(data.get(id_key, ""))
169
+ return
170
+ indent = 2 if self.mode == OutputFormat.human else None
171
+ _print_flush(json.dumps(data, indent=indent, default=str))
172
+
173
+ def result(self, message: str, **data: Any) -> None:
174
+ """Print a success summary to stdout."""
175
+ match self.mode:
176
+ case OutputFormat.human: # ✓ message + key: value lines
177
+ parts = [ANSI.green(f"{_ascii_safe('✓', '[OK]')} {message}")]
178
+ for k, v in data.items():
179
+ if v is not None:
180
+ parts.append(f" {k}: {v}")
181
+ _print_flush("\n".join(parts))
182
+ case OutputFormat.agent: # key=val pairs, space-separated
183
+ parts = [f"{k}={v}" for k, v in data.items() if v is not None]
184
+ _print_flush(" ".join(parts) if parts else message)
185
+ case OutputFormat.json: # json.dumps(data), message ignored
186
+ _print_flush(json.dumps(data, default=str) if data else "")
187
+ case OutputFormat.quiet: # first value only
188
+ values = list(data.values())
189
+ if values:
190
+ _print_flush(values[0])
191
+
192
+ def confirm(self, message: str, *, default: bool = False, yes: bool = False, confirm_param: str = "--yes") -> None:
193
+ """
194
+ Ask for confirmation. Raises `ConfirmationError` in non-human modes.
195
+ """
196
+ if yes:
197
+ return
198
+ if self.mode != OutputFormat.human:
199
+ raise ConfirmationError(f"{message} Use {confirm_param} to skip confirmation.")
200
+ click.confirm(message, default=default, abort=True)
201
+
202
+ def status(self, message: str | None = None) -> StatusLine:
203
+ """Return a status line that emits only in human mode (no-op otherwise)."""
204
+ status = StatusLine(enabled=self.mode == OutputFormat.human)
205
+ if message is not None:
206
+ status.update(message)
207
+ return status
208
+
209
+ def warning(self, message: str) -> None:
210
+ """Print a non-fatal warning to stderr (all modes)."""
211
+ if self.mode == OutputFormat.human:
212
+ _print_flush(ANSI.yellow(f"Warning: {message}"), file=sys.stderr)
213
+ else:
214
+ _print_flush(f"Warning: {message}", file=sys.stderr)
215
+
216
+ def error(self, message: str) -> None:
217
+ """Print an error to stderr (all modes)."""
218
+ if self.mode == OutputFormat.human:
219
+ _print_flush(ANSI.red(f"Error: {message}"), file=sys.stderr)
220
+ else:
221
+ _print_flush(f"Error: {message}", file=sys.stderr)
222
+
223
+ def log(self, message: str) -> None:
224
+ """Print a text message to stderr (human: gray, json/agent: plain text).
225
+
226
+ Suppressed in quiet mode. Kept in json mode (like agent) since agents
227
+ commonly run with ``--format json`` and the message goes to stderr so
228
+ it never pollutes the parsed stdout.
229
+ """
230
+ if self.mode == OutputFormat.quiet:
231
+ return
232
+ if self.mode == OutputFormat.human:
233
+ _print_flush(ANSI.gray(message), file=sys.stderr)
234
+ else:
235
+ _print_flush(message, file=sys.stderr)
236
+
237
+ def hint(self, message: str) -> None:
238
+ """Print a helpful hint to stderr (human: gray, json/agent: plain text).
239
+
240
+ Suppressed in quiet mode. Kept in json mode (like agent) since agents
241
+ commonly run with ``--format json`` and the next-command hints are useful
242
+ there; hints go to stderr so they never pollute the parsed stdout.
243
+ """
244
+ self.log(f"Hint: {message}")
245
+
246
+
247
+ # HELPERS
248
+
249
+
250
+ @cache
251
+ def _ascii_safe(char: str, fallback: str) -> str:
252
+ """Return `char`, or `fallback` if stdout cannot encode it.
253
+
254
+ On Windows, `sys.stdout` uses the ANSI code page (e.g. cp1252) instead of the console
255
+ encoding whenever it is not attached to a console (output redirected, piped, captured by
256
+ a CI step). Printing a decoration like "✓" then raises `UnicodeEncodeError` - a
257
+ `ValueError` subclass, so it surfaces as a confusing "Invalid value." error and aborts
258
+ the command. Cached since the stream encoding is fixed for the lifetime of the process.
259
+ """
260
+ encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
261
+ try:
262
+ char.encode(encoding)
263
+ except (LookupError, UnicodeEncodeError):
264
+ return fallback
265
+ return char
266
+
267
+
268
+ def _serialize_value(v: object) -> object:
269
+ """Recursively serialize a value to be JSON-compatible."""
270
+ if isinstance(v, datetime.datetime):
271
+ return v.isoformat()
272
+ elif isinstance(v, dict):
273
+ return {key: _serialize_value(val) for key, val in v.items() if val is not None}
274
+ elif isinstance(v, list):
275
+ return [_serialize_value(item) for item in v]
276
+ return v
277
+
278
+
279
+ def _dataclass_to_dict(info: Any) -> dict[str, Any]:
280
+ """Convert a dataclass to a json-serializable dict."""
281
+ data = dataclasses.asdict(info)
282
+
283
+ for field in dataclasses.fields(info):
284
+ value = getattr(info, field.name)
285
+ if isinstance(value, CardData):
286
+ data[field.name] = value.to_dict()
287
+
288
+ return {k: _serialize_value(v) for k, v in data.items() if v is not None}
289
+
290
+
291
+ _ANSI_RE = re.compile(r"\033\[[0-9;]*m")
292
+
293
+
294
+ def _strip_ansi(text: str) -> str:
295
+ return _ANSI_RE.sub("", text)
296
+
297
+
298
+ def _escape_control_chars(text: str) -> str:
299
+ """Escape non-printable characters (CR, LF, ESC, ...) so Hub-provided strings cannot alter the terminal output."""
300
+ return "".join(c if c.isprintable() else repr(c)[1:-1] for c in text)
301
+
302
+
303
+ def _single_line(text: str) -> str:
304
+ return _escape_control_chars(" ".join(text.split()))
305
+
306
+
307
+ def _to_header(name: str) -> str:
308
+ """Convert a camelCase or PascalCase string to SCREAMING_SNAKE_CASE."""
309
+ s = re.sub(r"([a-z])([A-Z])", r"\1_\2", name)
310
+ return s.upper()
311
+
312
+
313
+ def _infer_alignments(headers: list[str], rows: list[list[Any]]) -> dict[str, str]:
314
+ """Return ``{"col": "right"}`` for columns where every non-None value is numeric."""
315
+ result: dict[str, str] = {}
316
+ for c, h in enumerate(headers):
317
+ if all(row[c] is None or (isinstance(row[c], (int, float)) and not isinstance(row[c], bool)) for row in rows):
318
+ result[h] = "right"
319
+ return result
320
+
321
+
322
+ def _format_table_value_human(value: Any) -> str:
323
+ """Convert a value to string for terminal display."""
324
+ if value is None:
325
+ return ""
326
+ if isinstance(value, bool):
327
+ return _ascii_safe("✔", "yes") if value else ""
328
+ if isinstance(value, datetime.datetime):
329
+ return value.strftime("%Y-%m-%d")
330
+ if isinstance(value, str) and re.search(r"^\d{4}-\d{2}-\d{2}T", value):
331
+ return value[:10]
332
+ if isinstance(value, str):
333
+ return _single_line(value)
334
+ if isinstance(value, list):
335
+ return ", ".join(_format_table_value_human(v) for v in value)
336
+ elif isinstance(value, dict):
337
+ if "name" in value: # Likely to be a user or org => print name
338
+ return _single_line(str(value["name"]))
339
+ return _single_line(json.dumps(value))
340
+ return _single_line(str(value))
341
+
342
+
343
+ def _truncate_columns(
344
+ headers: list[str],
345
+ rows: list[list[str]],
346
+ *,
347
+ no_truncate: bool,
348
+ ) -> bool:
349
+ """Truncate cells in-place to fit the current terminal width.
350
+
351
+ Returns `True` if any cell was truncated, so the caller can emit a hint.
352
+ `shutil.get_terminal_size` is cross-platform: it honors `$COLUMNS`, then
353
+ queries the OS-native API, then falls back to `(80, 24)`.
354
+ """
355
+ if no_truncate or not rows:
356
+ return False
357
+
358
+ n = len(headers)
359
+ # Per-column natural width: longest of header label and cell values.
360
+ natural = [max(len(headers[c]), *(len(rows[r][c]) for r in range(len(rows)))) for c in range(n)]
361
+
362
+ # `max(0, n - 1)` accounts for the single-space separator between columns.
363
+ budget = shutil.get_terminal_size().columns - max(0, n - 1)
364
+ if sum(natural) <= budget:
365
+ return False
366
+
367
+ # Shrink the widest column 1 char at a time. Floors keep the header label
368
+ # visible; the `4` is the smallest cap that still shows "x..." (one content
369
+ # char plus the "..." marker).
370
+ caps = natural.copy()
371
+ min_widths = [max(len(h), 4) for h in headers]
372
+ while sum(caps) > budget:
373
+ widest = max(
374
+ (i for i, w in enumerate(caps) if w > min_widths[i]),
375
+ key=lambda i: caps[i],
376
+ default=-1,
377
+ )
378
+ if widest < 0:
379
+ break # everything at floor — table wraps slightly
380
+ caps[widest] -= 1
381
+
382
+ truncated = False
383
+ for row in rows:
384
+ for c, cell in enumerate(row):
385
+ if len(cell) > caps[c]:
386
+ truncated = True
387
+ row[c] = cell[: caps[c] - 3] + "..."
388
+ return truncated
389
+
390
+
391
+ def _format_table_cell_agent(value: Any) -> str:
392
+ """Format a cell value for agent TSV output (ISO timestamps, tabs escaped)."""
393
+ if isinstance(value, datetime.datetime):
394
+ return value.isoformat()
395
+ return _single_line(str(value))
396
+
397
+
398
+ out = Output()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_skills.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal helpers for Hugging Face marketplace skill installation and upgrades."""
2
+
3
+ import json
4
+ import re
5
+ import shutil
6
+ import tempfile
7
+ import time
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass, replace
10
+ from pathlib import Path, PurePosixPath
11
+ from typing import Any, Literal
12
+
13
+ from huggingface_hub import __version__, constants
14
+ from huggingface_hub._buckets import BucketFile
15
+ from huggingface_hub.errors import CLIError
16
+
17
+ from ..utils import disable_progress_bars, logging
18
+ from ._cli_utils import get_hf_api
19
+ from ._output import out
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+ DEFAULT_SKILL_ID = "hf-cli"
25
+ DEFAULT_SKILLS_BUCKET_ID = "huggingface/skills"
26
+ MARKETPLACE_PATH = "marketplace.json"
27
+ # Empty marker file dropped into managed skill installs so `hf skills update` knows
28
+ # to touch them and leave user-placed skill dirs alone. Filename is historical (used
29
+ # to be a JSON manifest with a revision); we keep it for backward compat with installs
30
+ # made by previous versions.
31
+ MANAGED_MARKER_FILENAME = ".hf-skill-manifest.json"
32
+
33
+ SkillUpdateStatus = Literal["up_to_date", "unmanaged", "source_unreachable"]
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class MarketplaceSkill:
38
+ name: str
39
+ repo_path: str
40
+ description: str | None = None
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class SkillUpdateInfo:
45
+ name: str
46
+ skill_dir: Path
47
+ status: SkillUpdateStatus
48
+ detail: str | None = None
49
+
50
+
51
+ def add_skill(skill_name: str, destination_root: Path, force: bool = False) -> Path:
52
+ """Resolve a marketplace skill by name and install it."""
53
+ api = get_hf_api()
54
+ with disable_progress_bars():
55
+ marketplace_skills = _load_marketplace_skills(api)
56
+ skill = _select_marketplace_skill(marketplace_skills, skill_name)
57
+ if skill is None:
58
+ raise CLIError(
59
+ f"Skill '{skill_name}' not found in {DEFAULT_SKILLS_BUCKET_ID}. "
60
+ "Try `hf skills add` to install `hf-cli` or use a known skill name."
61
+ )
62
+ return _install_marketplace_skill(api, skill, destination_root, force=force)
63
+
64
+
65
+ def install_generated_skill(content: str, destination_root: Path, force: bool = False) -> Path:
66
+ """Install the `hf-cli` skill from locally generated SKILL.md content (no bucket download)."""
67
+
68
+ def populate(install_dir: Path) -> None:
69
+ install_dir.mkdir(parents=True, exist_ok=True)
70
+ (install_dir / "SKILL.md").write_text(content, encoding="utf-8")
71
+ (install_dir / MANAGED_MARKER_FILENAME).touch()
72
+
73
+ return _install_skill(DEFAULT_SKILL_ID, destination_root, populate=populate, force=force)
74
+
75
+
76
+ def update_skills(roots: list[Path], selector: str | None = None, *, hf_cli_content: str) -> list[SkillUpdateInfo]:
77
+ """Re-sync managed skill installs (`hf-cli` is rewritten from `hf_cli_content`, the rest from the bucket)."""
78
+ skill_dirs = _iter_unique_skill_dirs(roots)
79
+ if selector is not None:
80
+ selector_lower = selector.strip().lower()
81
+ skill_dirs = [d for d in skill_dirs if d.name.lower() == selector_lower]
82
+ if not skill_dirs:
83
+ raise CLIError(f"No installed skill matches '{selector}'. Install it with `hf skills add {selector}`.")
84
+
85
+ # `hf-cli` is regenerated locally, so only hit the marketplace when another managed skill needs it.
86
+ needs_marketplace = any(d.name != DEFAULT_SKILL_ID and (d / MANAGED_MARKER_FILENAME).exists() for d in skill_dirs)
87
+ api = None
88
+ marketplace_skills: dict[str, MarketplaceSkill] = {}
89
+ if needs_marketplace:
90
+ api = get_hf_api()
91
+ with disable_progress_bars():
92
+ marketplace_skills = {skill.name.lower(): skill for skill in _load_marketplace_skills(api)}
93
+
94
+ return [_apply_single_update(api, skill_dir, marketplace_skills, hf_cli_content) for skill_dir in skill_dirs]
95
+
96
+
97
+ def _load_marketplace_skills(api) -> list[MarketplaceSkill]:
98
+ payload = _load_marketplace_payload(api)
99
+ plugins = payload.get("plugins")
100
+ if not isinstance(plugins, list):
101
+ raise CLIError("Invalid marketplace payload: expected a top-level 'plugins' list.")
102
+
103
+ skills: list[MarketplaceSkill] = []
104
+ for plugin in plugins:
105
+ if not isinstance(plugin, dict):
106
+ continue
107
+ name = plugin.get("name")
108
+ source = plugin.get("source")
109
+ if not isinstance(name, str) or not isinstance(source, str):
110
+ continue
111
+ description = plugin.get("description")
112
+ skills.append(
113
+ MarketplaceSkill(
114
+ name=name,
115
+ repo_path=_normalize_repo_path(source),
116
+ description=description if isinstance(description, str) else None,
117
+ )
118
+ )
119
+ return skills
120
+
121
+
122
+ def _install_marketplace_skill(api, skill: MarketplaceSkill, destination_root: Path, force: bool = False) -> Path:
123
+ """Install a marketplace skill into a local skills directory."""
124
+
125
+ def populate(install_dir: Path) -> None:
126
+ install_dir.mkdir(parents=True, exist_ok=True)
127
+ bucket_files = _list_skill_files(api, skill)
128
+ _download_skill_files(api, skill, bucket_files, install_dir)
129
+ _validate_installed_skill_dir(install_dir)
130
+ (install_dir / MANAGED_MARKER_FILENAME).touch()
131
+
132
+ return _install_skill(skill.name, destination_root, populate=populate, force=force)
133
+
134
+
135
+ _VALID_SKILL_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
136
+
137
+
138
+ def _install_skill(
139
+ name: str,
140
+ destination_root: Path,
141
+ populate: Callable[[Path], None],
142
+ force: bool = False,
143
+ ) -> Path:
144
+ """Install a skill into ``destination_root`` by calling ``populate(install_dir)`` to fill it.
145
+
146
+ Used by both the marketplace install (populate = download from bucket) and the
147
+ locally-generated install (populate = write content). When the install already
148
+ exists and ``force`` is set, the new content is staged in a sibling tempdir and
149
+ atomically swapped in, so the existing install stays intact if ``populate``
150
+ fails halfway through.
151
+ """
152
+ # `name` may come from the remote marketplace payload and the install dir is removed on
153
+ # reinstall: validate it as defense-in-depth against path traversal.
154
+ if not _VALID_SKILL_NAME.fullmatch(name):
155
+ raise CLIError(f"Invalid skill name '{name}'.")
156
+ destination_root = destination_root.expanduser().resolve()
157
+ destination_root.mkdir(parents=True, exist_ok=True)
158
+ install_dir = destination_root / name
159
+ already_exists = install_dir.exists()
160
+
161
+ if already_exists and not force:
162
+ raise FileExistsError(f"Skill already exists: {install_dir}")
163
+
164
+ if already_exists:
165
+ with tempfile.TemporaryDirectory(dir=destination_root, prefix=f".{install_dir.name}.install-") as tmp_dir_str:
166
+ staged_dir = Path(tmp_dir_str) / install_dir.name
167
+ populate(staged_dir)
168
+ _atomic_replace_directory(existing_dir=install_dir, staged_dir=staged_dir)
169
+ return install_dir
170
+
171
+ try:
172
+ populate(install_dir)
173
+ except Exception:
174
+ if install_dir.exists():
175
+ shutil.rmtree(install_dir)
176
+ raise
177
+ return install_dir
178
+
179
+
180
+ def _load_marketplace_payload(api) -> dict[str, Any]:
181
+ with tempfile.TemporaryDirectory() as tmp_dir:
182
+ local_path = Path(tmp_dir) / "marketplace.json"
183
+ api.download_bucket_files(
184
+ DEFAULT_SKILLS_BUCKET_ID,
185
+ [(MARKETPLACE_PATH, local_path)],
186
+ raise_on_missing_files=True,
187
+ )
188
+ parsed = json.loads(local_path.read_text(encoding="utf-8"))
189
+
190
+ if not isinstance(parsed, dict):
191
+ raise CLIError("Invalid marketplace payload: expected a JSON object.")
192
+ return parsed
193
+
194
+
195
+ def _select_marketplace_skill(skills: list[MarketplaceSkill], selector: str) -> MarketplaceSkill | None:
196
+ selector_lower = selector.strip().lower()
197
+ for skill in skills:
198
+ if skill.name.lower() == selector_lower:
199
+ return skill
200
+ return None
201
+
202
+
203
+ def _normalize_repo_path(path: str) -> str:
204
+ normalized = path.strip()
205
+ while normalized.startswith("./"):
206
+ normalized = normalized[2:]
207
+ normalized = normalized.strip("/")
208
+ if not normalized:
209
+ raise CLIError("Invalid marketplace entry: empty source path.")
210
+ return normalized
211
+
212
+
213
+ def _validate_installed_skill_dir(skill_dir: Path) -> None:
214
+ skill_file = skill_dir / "SKILL.md"
215
+ if not skill_file.is_file():
216
+ raise RuntimeError(f"Installed skill is missing SKILL.md: {skill_file}")
217
+
218
+
219
+ def _list_skill_files(api, skill: MarketplaceSkill) -> list[BucketFile]:
220
+ """List all files under `skill.repo_path` in the marketplace bucket."""
221
+ prefix = skill.repo_path.rstrip("/")
222
+ files: list[BucketFile] = [
223
+ item
224
+ for item in api.list_bucket_tree(DEFAULT_SKILLS_BUCKET_ID, prefix=prefix, recursive=True)
225
+ if isinstance(item, BucketFile)
226
+ ]
227
+ if not files:
228
+ raise FileNotFoundError(f"Path '{prefix}' not found in bucket '{DEFAULT_SKILLS_BUCKET_ID}'.")
229
+ return files
230
+
231
+
232
+ def _download_skill_files(api, skill: MarketplaceSkill, files: list[BucketFile], install_dir: Path) -> None:
233
+ """Download bucket files into `install_dir`."""
234
+ prefix = skill.repo_path.rstrip("/")
235
+ prefix_with_slash = f"{prefix}/"
236
+
237
+ # `list_bucket_tree(prefix=...)` matches as a raw string prefix, so e.g. asking for
238
+ # "skills/gradio" can also return "skills/gradio-tools/...". Filter on the trailing
239
+ # slash to keep only files actually inside the directory, then strip it so files land
240
+ # directly under `install_dir` preserving any nested structure.
241
+ download_specs: list[tuple[str | BucketFile, str | Path]] = []
242
+ for bucket_file in files:
243
+ if not bucket_file.path.startswith(prefix_with_slash):
244
+ continue
245
+ relative = bucket_file.path[len(prefix_with_slash) :]
246
+ local_file = install_dir.joinpath(*PurePosixPath(relative).parts)
247
+ local_file.parent.mkdir(parents=True, exist_ok=True)
248
+ download_specs.append((bucket_file, local_file))
249
+
250
+ if not download_specs:
251
+ raise FileNotFoundError(f"No files found under '{prefix}' in bucket '{DEFAULT_SKILLS_BUCKET_ID}'.")
252
+
253
+ api.download_bucket_files(DEFAULT_SKILLS_BUCKET_ID, download_specs)
254
+
255
+
256
+ def _atomic_replace_directory(existing_dir: Path, staged_dir: Path) -> None:
257
+ backup_dir = staged_dir.parent / f"{existing_dir.name}.backup"
258
+ try:
259
+ existing_dir.rename(backup_dir)
260
+ staged_dir.rename(existing_dir)
261
+ shutil.rmtree(backup_dir)
262
+ except Exception:
263
+ if backup_dir.exists() and not existing_dir.exists():
264
+ backup_dir.rename(existing_dir)
265
+ raise
266
+
267
+
268
+ def _iter_unique_skill_dirs(roots: list[Path]) -> list[Path]:
269
+ seen: set[Path] = set()
270
+ discovered: list[Path] = []
271
+ for root in roots:
272
+ root = root.expanduser().resolve()
273
+ if not root.is_dir():
274
+ continue
275
+ for child in sorted(root.iterdir()):
276
+ if child.name.startswith("."):
277
+ continue
278
+ if not child.is_dir() and not child.is_symlink():
279
+ continue
280
+ resolved = child.resolve()
281
+ if resolved in seen or not resolved.is_dir():
282
+ continue
283
+ seen.add(resolved)
284
+ discovered.append(resolved)
285
+ return discovered
286
+
287
+
288
+ def _apply_single_update(
289
+ api, skill_dir: Path, marketplace_skills: dict[str, MarketplaceSkill], hf_cli_content: str
290
+ ) -> SkillUpdateInfo:
291
+ base = SkillUpdateInfo(name=skill_dir.name, skill_dir=skill_dir, status="unmanaged")
292
+
293
+ if not (skill_dir / MANAGED_MARKER_FILENAME).exists():
294
+ return base
295
+
296
+ if skill_dir.name == DEFAULT_SKILL_ID:
297
+ try:
298
+ install_generated_skill(hf_cli_content, skill_dir.parent, force=True)
299
+ except Exception as exc:
300
+ return replace(base, status="source_unreachable", detail=str(exc))
301
+ return replace(base, status="up_to_date")
302
+
303
+ skill = marketplace_skills.get(skill_dir.name.lower())
304
+ if skill is None:
305
+ return replace(
306
+ base,
307
+ status="source_unreachable",
308
+ detail=f"Skill '{skill_dir.name}' is no longer available in {DEFAULT_SKILLS_BUCKET_ID}.",
309
+ )
310
+
311
+ try:
312
+ _install_marketplace_skill(api, skill, skill_dir.parent, force=True)
313
+ except Exception as exc:
314
+ return replace(base, status="source_unreachable", detail=str(exc))
315
+
316
+ return replace(base, status="up_to_date")
317
+
318
+
319
+ ### `hf-cli` SKILL CHECKER
320
+
321
+
322
+ # Version stamp written in the generated SKILL.md (see `build_skill_md`).
323
+ _GENERATED_VERSION_RE = re.compile(r"Generated with `huggingface_hub v([^`]+)`")
324
+
325
+
326
+ def check_skill_update() -> None:
327
+ """Hint at installing or updating the `hf-cli` skill, at most once every 24 hours.
328
+
329
+ Only prints a hint: installing or updating stays an explicit user action.
330
+
331
+ Skipped entirely if `HF_HUB_DISABLE_UPDATE_CHECK` is set. Called at the entry point of
332
+ the CLI, so any error is caught and logged to avoid breaking the CLI.
333
+ """
334
+ try:
335
+ _check_skill_update()
336
+ except Exception:
337
+ logger.debug("Error while checking for hf-cli skill update.", exc_info=True)
338
+
339
+
340
+ def _check_skill_update() -> None:
341
+ if constants.HF_HUB_DISABLE_UPDATE_CHECK:
342
+ return
343
+
344
+ # Skip if already checked in the last 24 hours
345
+ stamp_path = Path(constants.CHECK_FOR_SKILL_UPDATE_DONE_PATH)
346
+ if stamp_path.exists() and (time.time() - stamp_path.stat().st_mtime) < 24 * 3600:
347
+ return
348
+ stamp_path.parent.mkdir(parents=True, exist_ok=True)
349
+ stamp_path.touch()
350
+
351
+ global_dirs = _installed_hf_cli_dirs(constants.AGENTS_SKILLS_GLOBAL_PATH, constants.CLAUDE_SKILLS_GLOBAL_PATH)
352
+ local_dirs = _installed_hf_cli_dirs(constants.AGENTS_SKILLS_LOCAL_PATH, constants.CLAUDE_SKILLS_LOCAL_PATH)
353
+
354
+ if not global_dirs and not local_dirs:
355
+ # Don't push the skill on pre-release / dev versions (same rule as the PyPI update check).
356
+ if any(tag in __version__ for tag in ["rc", "dev"]):
357
+ return
358
+ out.hint(
359
+ f"The `{DEFAULT_SKILL_ID}` skill is not installed. Run `hf skills add -g`"
360
+ " to teach your AI agents how to use the `hf` CLI."
361
+ )
362
+ return
363
+
364
+ # Suggest the command matching where the outdated skill is installed (global takes precedence).
365
+ if any(_is_skill_outdated(skill_dir) for skill_dir in global_dirs):
366
+ scope = " -g"
367
+ elif any(_is_skill_outdated(skill_dir) for skill_dir in local_dirs):
368
+ scope = ""
369
+ else:
370
+ return
371
+ out.hint(
372
+ f"The installed `{DEFAULT_SKILL_ID}` skill was generated by another `hf` version."
373
+ f" Run `hf skills update {DEFAULT_SKILL_ID}{scope}` to refresh it."
374
+ )
375
+
376
+
377
+ def _installed_hf_cli_dirs(*roots: Path) -> list[Path]:
378
+ dirs = [(root.expanduser() / DEFAULT_SKILL_ID).resolve() for root in roots]
379
+ return [skill_dir for skill_dir in dict.fromkeys(dirs) if skill_dir.is_dir()]
380
+
381
+
382
+ def _is_skill_outdated(skill_dir: Path) -> bool:
383
+ """Whether the installed `hf-cli` SKILL.md was generated by another `hf` version."""
384
+ try:
385
+ content = (skill_dir / "SKILL.md").read_text(encoding="utf-8")
386
+ except OSError:
387
+ return False
388
+ match = _GENERATED_VERSION_RE.search(content)
389
+ return match is None or match.group(1) != __version__
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/_uv_script_header.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Read launch defaults from a UV script's optional `[tool.hf-jobs]` PEP 723 table.
15
+
16
+ See the CLI guide for the header format and `cli/jobs.py` for the merge rules.
17
+ """
18
+
19
+ import re
20
+ import sys
21
+ from collections.abc import Generator
22
+ from contextlib import contextmanager
23
+ from dataclasses import dataclass, field, fields
24
+ from pathlib import Path
25
+ from typing import Any
26
+ from urllib.parse import urlsplit
27
+
28
+ import httpx2
29
+
30
+ from huggingface_hub import constants
31
+ from huggingface_hub.errors import CLIError
32
+ from huggingface_hub.utils import SoftTemporaryDirectory, get_session
33
+
34
+
35
+ # Reference regex from PEP 723 (https://peps.python.org/pep-0723/#reference-implementation)
36
+ _PEP_723_REGEX = re.compile(r"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$")
37
+
38
+ TABLE_NAME = "tool.hf-jobs"
39
+
40
+
41
+ @dataclass
42
+ class UvScriptHeader:
43
+ """The `[tool.hf-jobs]` table of a UV script: the launch configuration the script carries."""
44
+
45
+ image: str | None = None
46
+ flavor: str | None = None
47
+ python: str | None = None
48
+ timeout: str | None = None
49
+ name: str | None = None
50
+ namespace: str | None = None
51
+ network_group: str | None = None
52
+ env: dict[str, str] = field(default_factory=dict)
53
+ secrets: list[str] = field(default_factory=list)
54
+ labels: dict[str, str] = field(default_factory=dict)
55
+ volumes: list[str] = field(default_factory=list)
56
+ network_aliases: list[str] = field(default_factory=list)
57
+
58
+
59
+ VALID_KEYS = tuple(f.name for f in fields(UvScriptHeader))
60
+
61
+
62
+ @dataclass
63
+ class UvScript:
64
+ """A UV script ready to be submitted, with the launch config it carries (if any)."""
65
+
66
+ script: str
67
+ """Path (or command) to pass to the Jobs API. A URL script is downloaded, so this is a local path."""
68
+
69
+ header: UvScriptHeader | None = None
70
+ """Parsed `[tool.hf-jobs]` table, or `None` if the script has none."""
71
+
72
+
73
+ @contextmanager
74
+ def load_uv_script(script: str) -> Generator[UvScript, None, None]:
75
+ """Resolve a `hf jobs uv run` script argument and read its `[tool.hf-jobs]` header.
76
+
77
+ - a local file is read in place
78
+ - an `http(s)` URL is downloaded to a temporary directory and from there shipped to the Job like
79
+ any local script: the URL is fetched exactly once, at submit time, instead of being fetched
80
+ again by the container (the header has to be read client-side anyway, since `image`, `flavor`,
81
+ `secrets`, ... are all decided before the container exists). The download lives until the
82
+ `with` block exits, i.e. until the Job is submitted.
83
+ - anything else is a command (e.g. `lighteval`) and carries no header
84
+ """
85
+ # Scripts are read as UTF-8, not with the locale encoding: a downloaded script is written as raw
86
+ # bytes and a header with non-ASCII values must not fail to decode depending on the platform.
87
+ if script.startswith(("http://", "https://")):
88
+ with SoftTemporaryDirectory(prefix="hf-jobs-uv-") as tmp_dir:
89
+ local_path = _download_script(script, Path(tmp_dir))
90
+ yield UvScript(
91
+ script=str(local_path), header=parse_uv_script_header(local_path.read_text(encoding="utf-8"))
92
+ )
93
+ return
94
+ path = Path(script)
95
+ if path.is_file():
96
+ yield UvScript(script=script, header=parse_uv_script_header(path.read_text(encoding="utf-8")))
97
+ return
98
+ yield UvScript(script=script)
99
+
100
+
101
+ def parse_uv_script_header(text: str) -> UvScriptHeader | None:
102
+ """Parse the `[tool.hf-jobs]` table out of a script's PEP 723 header. Returns `None` if absent."""
103
+ content = _extract_pep_723_block(text)
104
+ # Cheap pre-check: scripts that don't use the feature never need a TOML parser.
105
+ if content is None or "hf-jobs" not in content:
106
+ return None
107
+ table = _load_toml(content).get("tool", {}).get("hf-jobs")
108
+ if table is None:
109
+ return None
110
+ if not isinstance(table, dict):
111
+ raise CLIError(f"'{TABLE_NAME}' must be a table in the script's PEP 723 header (i.e. `[{TABLE_NAME}]`).")
112
+
113
+ if unknown := sorted(key for key in table if key not in VALID_KEYS):
114
+ raise CLIError(
115
+ f"Unknown key(s) {', '.join(repr(key) for key in unknown)} in the script's [{TABLE_NAME}] table."
116
+ f" Valid keys are: {', '.join(VALID_KEYS)}."
117
+ )
118
+ return UvScriptHeader(
119
+ image=_as_str(table, "image"),
120
+ flavor=_as_str(table, "flavor"),
121
+ python=_as_str(table, "python"),
122
+ timeout=_as_timeout(table),
123
+ name=_as_str(table, "name"),
124
+ namespace=_as_str(table, "namespace"),
125
+ network_group=_as_str(table, "network_group"),
126
+ env=_as_str_table(table, "env"),
127
+ secrets=_as_secret_names(table),
128
+ labels=_as_str_table(table, "labels"),
129
+ volumes=_as_str_list(table, "volumes"),
130
+ network_aliases=_as_str_list(table, "network_aliases"),
131
+ )
132
+
133
+
134
+ def _download_script(url: str, dest_dir: Path) -> Path:
135
+ """Download a remote UV script into `dest_dir` and return its local path."""
136
+ name = Path(urlsplit(url).path).name
137
+ local_path = dest_dir / (name if name.endswith(".py") else "script.py")
138
+ try:
139
+ # Timeout so that an unreachable URL fails the CLI instead of hanging it.
140
+ response = get_session().get(url, timeout=constants.DEFAULT_REQUEST_TIMEOUT)
141
+ response.raise_for_status()
142
+ except httpx2.HTTPError as e:
143
+ raise CLIError(f"Could not download the UV script from '{url}': {e}") from e
144
+ local_path.write_bytes(response.content)
145
+ return local_path
146
+
147
+
148
+ def _extract_pep_723_block(text: str) -> str | None:
149
+ """Return the content of the first PEP 723 `script` block, with the `# ` prefixes stripped."""
150
+ # The PEP 723 regex anchors on '\n': normalize line endings first, otherwise a script written on
151
+ # Windows (or fetched over HTTP) silently parses as "no header at all".
152
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
153
+ for match in _PEP_723_REGEX.finditer(text):
154
+ if match.group("type") == "script":
155
+ return "".join(
156
+ line[2:] if line.startswith("# ") else line[1:]
157
+ for line in match.group("content").splitlines(keepends=True)
158
+ )
159
+ return None
160
+
161
+
162
+ def _load_toml(content: str) -> dict[str, Any]:
163
+ if sys.version_info >= (3, 11):
164
+ import tomllib
165
+ else: # tomllib was added in Python 3.11
166
+ try:
167
+ import tomli as tomllib # type: ignore[import-not-found,no-redef,unused-ignore]
168
+ except ImportError as e:
169
+ raise CLIError(
170
+ f"Reading the [{TABLE_NAME}] table of a UV script requires a TOML parser."
171
+ " Upgrade to Python 3.11+ or install one with `pip install tomli`."
172
+ ) from e
173
+ try:
174
+ return tomllib.loads(content)
175
+ except tomllib.TOMLDecodeError as e:
176
+ raise CLIError(f"Invalid TOML in the script's PEP 723 header: {e}") from e
177
+
178
+
179
+ def _type_error(key: str, value: Any, expected: str) -> CLIError:
180
+ return CLIError(f"'{key}' in the script's [{TABLE_NAME}] table must be {expected}, got: {value!r}.")
181
+
182
+
183
+ def _as_str(table: dict[str, Any], key: str) -> str | None:
184
+ value = table.get(key)
185
+ if value is None:
186
+ return None
187
+ if not isinstance(value, str):
188
+ raise _type_error(key, value, "a string")
189
+ return value
190
+
191
+
192
+ def _as_timeout(table: dict[str, Any]) -> str | None:
193
+ value = table.get("timeout")
194
+ if value is None:
195
+ return None
196
+ if isinstance(value, bool) or not isinstance(value, (str, int)):
197
+ raise _type_error("timeout", value, 'a duration string (e.g. "30m") or a number of seconds')
198
+ return str(value)
199
+
200
+
201
+ def _as_str_table(table: dict[str, Any], key: str) -> dict[str, str]:
202
+ value = table.get(key)
203
+ if value is None:
204
+ return {}
205
+ if not isinstance(value, dict):
206
+ raise _type_error(key, value, "a table of strings")
207
+ for name, item in value.items():
208
+ # Stringifying a bool or an int here would send a value the author never wrote.
209
+ if not isinstance(item, str):
210
+ raise _type_error(f"{key}.{name}", item, "a string")
211
+ return value
212
+
213
+
214
+ def _as_str_list(table: dict[str, Any], key: str) -> list[str]:
215
+ value = table.get(key)
216
+ if value is None:
217
+ return []
218
+ if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
219
+ raise _type_error(key, value, "a list of strings")
220
+ return value
221
+
222
+
223
+ def _as_secret_names(table: dict[str, Any]) -> list[str]:
224
+ if isinstance(table.get("secrets"), dict):
225
+ raise CLIError(
226
+ f"'secrets' in the script's [{TABLE_NAME}] table must be a list of names (e.g. `secrets = [\"HF_TOKEN\"]`),"
227
+ " not a table: scripts travel publicly, so secret values are always read from the environment of"
228
+ " whoever runs the script."
229
+ )
230
+ return _as_str_list(table, "secrets")
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/auth.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import Annotated
17
+
18
+ import click
19
+
20
+ from huggingface_hub.constants import ENDPOINT
21
+ from huggingface_hub.hf_api import whoami
22
+
23
+ from .._login import _save_oauth_token, auth_list, auth_switch, login, logout
24
+ from ..errors import CLIError
25
+ from ..utils import get_stored_tokens, get_token, logging, select_choice
26
+ from ..utils._oauth_device import poll_device_token, request_device_code
27
+ from ._cli_utils import TokenOpt, typer_factory
28
+ from ._framework import Option
29
+ from ._output import OutputFormat, out
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ auth_cli = typer_factory(help="Manage authentication (login, logout, etc.).")
36
+
37
+
38
+ @auth_cli.command(
39
+ "login",
40
+ examples=[
41
+ "hf auth login",
42
+ "hf auth login --token $HF_TOKEN",
43
+ "hf auth login --token $HF_TOKEN --add-to-git-credential",
44
+ "hf auth login --force",
45
+ ],
46
+ )
47
+ def auth_login(
48
+ token: TokenOpt = None,
49
+ add_to_git_credential: Annotated[
50
+ bool,
51
+ Option(
52
+ help="Save to git credential helper. Useful only if you plan to run git commands directly.",
53
+ ),
54
+ ] = False,
55
+ force: Annotated[
56
+ bool,
57
+ Option(
58
+ help="Force re-login even if already logged in.",
59
+ ),
60
+ ] = False,
61
+ ) -> None:
62
+ """Login from your browser, or using a token from huggingface.co/settings/tokens."""
63
+ if token is not None or out.mode == OutputFormat.human:
64
+ # `--token` bypasses any prompt; in human mode the gh-style menu lives in `login()`.
65
+ login(token=token, add_to_git_credential=add_to_git_credential, skip_if_logged_in=not force)
66
+ return
67
+
68
+ # Logging in is an interactive flow: besides human mode, only agent mode is supported.
69
+ if out.mode != OutputFormat.agent:
70
+ raise CLIError(
71
+ "`hf auth login` is interactive and does not support --format json/quiet. "
72
+ "Pass --token for a non-interactive login."
73
+ )
74
+
75
+ # agent mode: never prompt; print instructions the agent can relay to its user.
76
+ if not force and get_token() is not None:
77
+ out.text(agent="Already logged in. Use `hf auth login --force` to re-login.")
78
+ return
79
+ device_info = request_device_code()
80
+ out.text(
81
+ agent=(
82
+ f"Ask the user to open {device_info['verification_uri_complete']} in a browser and enter the code "
83
+ f"{device_info['user_code']}. The code expires in {device_info['expires_in']} seconds. "
84
+ "Waiting for authorization..."
85
+ )
86
+ )
87
+ response = poll_device_token(device_info)
88
+ token_name, username = _save_oauth_token(response)
89
+ out.text(agent=f"Login successful: logged in as {username} (token saved as '{token_name}').")
90
+
91
+
92
+ @auth_cli.command(
93
+ "logout",
94
+ examples=["hf auth logout", "hf auth logout --token-name my-token"],
95
+ )
96
+ def auth_logout(
97
+ token_name: Annotated[
98
+ str | None,
99
+ Option(help="Name of token to logout"),
100
+ ] = None,
101
+ ) -> None:
102
+ """Logout from a specific token."""
103
+ logout(token_name=token_name)
104
+
105
+
106
+ def _select_token_name() -> str | None:
107
+ token_names = list(get_stored_tokens().keys())
108
+
109
+ if not token_names:
110
+ logger.error("No stored tokens found. Please login first.")
111
+ return None
112
+
113
+ if out.mode != OutputFormat.human:
114
+ raise CLIError("Use --token-name to select a token in non-interactive mode.")
115
+ return token_names[select_choice("Select a token to switch to:", token_names)]
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
+ Option(
126
+ help="Name of the token to switch to",
127
+ ),
128
+ ] = None,
129
+ add_to_git_credential: Annotated[
130
+ bool,
131
+ 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 click.exceptions.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("token", examples=["hf auth token", "hf auth token | xargs curl -H 'Authorization: Bearer {}'"])
152
+ def auth_token() -> None:
153
+ """Print the current access token to stdout."""
154
+ token = get_token()
155
+ if token is None:
156
+ out.error("Not logged in. Run `hf auth login` first.")
157
+ raise click.exceptions.Exit(code=1)
158
+ print(token)
159
+ out.hint("Run `hf auth whoami` to see which account this token belongs to.")
160
+
161
+
162
+ @auth_cli.command("whoami", examples=["hf auth whoami", "hf auth whoami --format json"])
163
+ def auth_whoami() -> None:
164
+ """Find out which huggingface.co account you are logged in as."""
165
+
166
+ token = get_token()
167
+ if token is None:
168
+ out.error("Not logged in. Run `hf auth login` first.")
169
+ raise click.exceptions.Exit(code=1)
170
+
171
+ info = whoami(token)
172
+ orgs = ",".join(org["name"] for org in info["orgs"]) or None
173
+ endpoint = ENDPOINT if ENDPOINT != "https://huggingface.co" else None
174
+ out.result("Logged in", user=info["name"], orgs=orgs, endpoint=endpoint)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/buckets.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from collections.abc import Iterable, Iterator
17
+ from typing import Annotated
18
+
19
+ import click
20
+
21
+ from huggingface_hub import logging
22
+ from huggingface_hub._buckets import (
23
+ BUCKET_PREFIX,
24
+ BucketFile,
25
+ BucketFolder,
26
+ FilterMatcher,
27
+ _parse_bucket_uri,
28
+ )
29
+
30
+ from ..hf_api import REPO_REGIONS
31
+ from ._cli_utils import (
32
+ SearchOpt,
33
+ TokenOpt,
34
+ get_hf_api,
35
+ typer_factory,
36
+ )
37
+ from ._cp import make_cp
38
+ from ._file_listing import format_size, print_file_listing
39
+ from ._framework import Argument, Option
40
+ from ._output import OutputFormat, out
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ buckets_cli = typer_factory(help="Commands to interact with buckets.")
47
+
48
+
49
+ @buckets_cli.command(
50
+ name="create",
51
+ examples=[
52
+ "hf buckets create my-bucket",
53
+ "hf buckets create user/my-bucket",
54
+ "hf buckets create hf://buckets/user/my-bucket",
55
+ "hf buckets create user/my-bucket --private",
56
+ "hf buckets create user/my-bucket --exist-ok",
57
+ "hf buckets create user/my-bucket --region us",
58
+ ],
59
+ )
60
+ def create(
61
+ bucket_id: Annotated[
62
+ str,
63
+ Argument(
64
+ help="Bucket ID: bucket_name, namespace/bucket_name, or hf://buckets/namespace/bucket_name",
65
+ ),
66
+ ],
67
+ private: Annotated[
68
+ bool,
69
+ Option(
70
+ "--private",
71
+ help="Create a private bucket.",
72
+ ),
73
+ ] = False,
74
+ region: Annotated[
75
+ REPO_REGIONS | None,
76
+ Option(
77
+ "--region",
78
+ help="Cloud region in which to create the bucket. Can be one of 'us' or 'eu'. Requires Team plan or above.",
79
+ ),
80
+ ] = None,
81
+ exist_ok: Annotated[
82
+ bool,
83
+ Option(
84
+ "--exist-ok",
85
+ help="Do not raise an error if the bucket already exists.",
86
+ ),
87
+ ] = False,
88
+ token: TokenOpt = None,
89
+ ) -> None:
90
+ """Create a new bucket."""
91
+ api = get_hf_api(token=token)
92
+
93
+ if bucket_id.startswith(BUCKET_PREFIX):
94
+ parsed = _parse_bucket_uri(bucket_id)
95
+ if parsed.path_in_repo:
96
+ raise click.BadParameter(
97
+ f"Cannot specify a prefix for bucket creation: {bucket_id}."
98
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
99
+ )
100
+ bucket_id = parsed.id
101
+
102
+ bucket_url = api.create_bucket(
103
+ bucket_id,
104
+ private=private if private else None,
105
+ region=region,
106
+ exist_ok=exist_ok,
107
+ )
108
+ out.result("Bucket created", uri=bucket_url.uri.to_uri(), url=bucket_url.url)
109
+
110
+
111
+ def _is_bucket_id(argument: str) -> bool:
112
+ """Check if argument is a bucket ID (namespace/name) vs just a namespace."""
113
+ if argument.startswith(BUCKET_PREFIX):
114
+ path = argument[len(BUCKET_PREFIX) :]
115
+ else:
116
+ path = argument
117
+ return "/" in path
118
+
119
+
120
+ @buckets_cli.command(
121
+ name="list | ls",
122
+ examples=[
123
+ "hf buckets list",
124
+ "hf buckets list huggingface",
125
+ 'hf buckets list --search "my-prefix"',
126
+ "hf buckets list user/my-bucket",
127
+ "hf buckets list user/my-bucket -R",
128
+ "hf buckets list user/my-bucket -h",
129
+ "hf buckets list user/my-bucket --tree",
130
+ "hf buckets list user/my-bucket --tree -h",
131
+ "hf buckets list hf://buckets/user/my-bucket",
132
+ "hf buckets list user/my-bucket/sub -R",
133
+ ],
134
+ )
135
+ def list_cmd(
136
+ argument: Annotated[
137
+ str | None,
138
+ Argument(
139
+ help=(
140
+ "Namespace (user or org) to list buckets, or bucket ID"
141
+ " (namespace/bucket_name(/prefix) or hf://buckets/...) to list files."
142
+ ),
143
+ ),
144
+ ] = None,
145
+ human_readable: Annotated[
146
+ bool,
147
+ Option(
148
+ "--human-readable",
149
+ "-h",
150
+ help="Show sizes in human readable format.",
151
+ ),
152
+ ] = False,
153
+ as_tree: Annotated[
154
+ bool,
155
+ Option(
156
+ "--tree",
157
+ help="List files in tree format (only for listing files).",
158
+ ),
159
+ ] = False,
160
+ recursive: Annotated[
161
+ bool,
162
+ Option(
163
+ "--recursive",
164
+ "-R",
165
+ help="List files recursively (only for listing files).",
166
+ ),
167
+ ] = False,
168
+ search: SearchOpt = None,
169
+ token: TokenOpt = None,
170
+ ) -> None:
171
+ """List buckets or files in a bucket.
172
+
173
+ When called with no argument or a namespace, lists buckets.
174
+ When called with a bucket ID (namespace/bucket_name), lists files in the bucket.
175
+ """
176
+ # Determine mode: listing buckets or listing files
177
+ is_file_mode = argument is not None and _is_bucket_id(argument)
178
+
179
+ if is_file_mode:
180
+ if search is not None:
181
+ raise click.BadParameter("Cannot use --search when listing files.")
182
+ _list_files(
183
+ argument=argument, # type: ignore
184
+ human_readable=human_readable,
185
+ as_tree=as_tree,
186
+ recursive=recursive,
187
+ token=token,
188
+ )
189
+ else:
190
+ _list_buckets(
191
+ namespace=argument,
192
+ search=search,
193
+ human_readable=human_readable,
194
+ as_tree=as_tree,
195
+ recursive=recursive,
196
+ token=token,
197
+ )
198
+
199
+
200
+ def _list_buckets(
201
+ namespace: str | None,
202
+ search: str | None,
203
+ human_readable: bool,
204
+ as_tree: bool,
205
+ recursive: bool,
206
+ token: str | None,
207
+ ) -> None:
208
+ """List buckets in a namespace."""
209
+ # Validate incompatible flags
210
+ if as_tree:
211
+ raise click.BadParameter("Cannot use --tree when listing buckets.")
212
+ if recursive:
213
+ raise click.BadParameter("Cannot use --recursive when listing buckets.")
214
+
215
+ # Handle hf://buckets/namespace format
216
+ if namespace is not None and namespace.startswith(BUCKET_PREFIX):
217
+ namespace = namespace[len(BUCKET_PREFIX) :]
218
+ # Strip trailing slash if any
219
+ namespace = namespace.rstrip("/")
220
+
221
+ api = get_hf_api(token=token)
222
+ items = [
223
+ {
224
+ "id": bucket.id,
225
+ "private": bucket.private,
226
+ "size": format_size(bucket.size, human_readable) if human_readable else bucket.size,
227
+ "total_files": bucket.total_files,
228
+ "created_at": bucket.created_at,
229
+ }
230
+ for bucket in api.list_buckets(namespace=namespace, search=search)
231
+ ]
232
+ out.table(items, alignments={"size": "right"})
233
+
234
+
235
+ def _iter_under_prefix(items: Iterable[BucketFile | BucketFolder], prefix: str) -> Iterator[BucketFile | BucketFolder]:
236
+ """Drop entries that are not `prefix` itself or below it.
237
+
238
+ The server matches `prefix` lexically, so listing "logs" also returns "logs.json" or "logs_backup/...".
239
+ Filesystem semantics require path components => keep only what's actually under the prefix.
240
+ """
241
+ prefix = prefix.rstrip("/")
242
+ for item in items:
243
+ if not prefix or item.path == prefix or item.path.startswith(f"{prefix}/"):
244
+ yield item
245
+
246
+
247
+ def _list_files(
248
+ argument: str,
249
+ human_readable: bool,
250
+ as_tree: bool,
251
+ recursive: bool,
252
+ token: str | None,
253
+ ) -> None:
254
+ """List files in a bucket."""
255
+ if as_tree and out.mode == OutputFormat.json:
256
+ raise click.BadParameter("Cannot use --tree with --format json.")
257
+
258
+ api = get_hf_api(token=token)
259
+ parsed = _parse_bucket_uri(argument)
260
+ items = list(
261
+ _iter_under_prefix(
262
+ api.list_bucket_tree(
263
+ parsed.id,
264
+ prefix=parsed.path_in_repo or None,
265
+ recursive=recursive,
266
+ ),
267
+ parsed.path_in_repo,
268
+ )
269
+ )
270
+
271
+ print_file_listing(items, human_readable=human_readable, as_tree=as_tree, recursive=recursive)
272
+
273
+
274
+ @buckets_cli.command(
275
+ name="info",
276
+ examples=[
277
+ "hf buckets info user/my-bucket",
278
+ "hf buckets info hf://buckets/user/my-bucket",
279
+ ],
280
+ )
281
+ def info(
282
+ bucket_id: Annotated[
283
+ str,
284
+ Argument(
285
+ help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
286
+ ),
287
+ ],
288
+ token: TokenOpt = None,
289
+ ) -> None:
290
+ """Get info about a bucket."""
291
+ api = get_hf_api(token=token)
292
+ parsed = _parse_bucket_uri(bucket_id)
293
+ bucket = api.bucket_info(parsed.id)
294
+ out.dict(bucket, id_key="id")
295
+
296
+
297
+ @buckets_cli.command(
298
+ name="delete",
299
+ examples=[
300
+ "hf buckets delete user/my-bucket",
301
+ "hf buckets delete hf://buckets/user/my-bucket",
302
+ "hf buckets delete user/my-bucket --yes",
303
+ "hf buckets delete user/my-bucket --missing-ok",
304
+ ],
305
+ )
306
+ def delete(
307
+ bucket_id: Annotated[
308
+ str,
309
+ Argument(
310
+ help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
311
+ ),
312
+ ],
313
+ yes: Annotated[
314
+ bool,
315
+ Option(
316
+ "--yes",
317
+ "-y",
318
+ help="Skip confirmation prompt.",
319
+ ),
320
+ ] = False,
321
+ missing_ok: Annotated[
322
+ bool,
323
+ Option(
324
+ "--missing-ok",
325
+ help="Do not raise an error if the bucket does not exist.",
326
+ ),
327
+ ] = False,
328
+ token: TokenOpt = None,
329
+ ) -> None:
330
+ """Delete a bucket.
331
+
332
+ This deletes the entire bucket and all its contents. Use `hf buckets rm` to remove individual files.
333
+ """
334
+ if bucket_id.startswith(BUCKET_PREFIX):
335
+ parsed = _parse_bucket_uri(bucket_id)
336
+ if parsed.path_in_repo:
337
+ raise click.BadParameter(
338
+ f"Cannot specify a prefix for bucket deletion: {bucket_id}."
339
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
340
+ )
341
+ bucket_id = parsed.id
342
+ elif "/" not in bucket_id:
343
+ raise click.BadParameter(
344
+ f"Invalid bucket ID: {bucket_id}."
345
+ f" Must be in format namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
346
+ )
347
+
348
+ out.confirm(f"Are you sure you want to delete bucket '{bucket_id}'?", yes=yes)
349
+
350
+ api = get_hf_api(token=token)
351
+ api.delete_bucket(bucket_id, missing_ok=missing_ok)
352
+ out.result("Bucket deleted", bucket_id=bucket_id)
353
+
354
+
355
+ @buckets_cli.command(
356
+ name="remove | rm",
357
+ examples=[
358
+ "hf buckets remove user/my-bucket/file.txt",
359
+ "hf buckets rm hf://buckets/user/my-bucket/file.txt",
360
+ "hf buckets rm user/my-bucket/logs/ --recursive",
361
+ 'hf buckets rm user/my-bucket --recursive --include "*.tmp"',
362
+ "hf buckets rm user/my-bucket/data/ --recursive --dry-run",
363
+ ],
364
+ )
365
+ def remove(
366
+ argument: Annotated[
367
+ str,
368
+ Argument(
369
+ help=(
370
+ "Bucket path: namespace/bucket_name/path or hf://buckets/namespace/bucket_name/path."
371
+ " With --recursive, namespace/bucket_name is also accepted to target all files."
372
+ ),
373
+ ),
374
+ ],
375
+ recursive: Annotated[
376
+ bool,
377
+ Option(
378
+ "--recursive",
379
+ "-R",
380
+ help="Remove files recursively under the given prefix.",
381
+ ),
382
+ ] = False,
383
+ yes: Annotated[
384
+ bool,
385
+ Option(
386
+ "--yes",
387
+ "-y",
388
+ help="Skip confirmation prompt.",
389
+ ),
390
+ ] = False,
391
+ dry_run: Annotated[
392
+ bool,
393
+ Option(
394
+ "--dry-run",
395
+ help="Preview what would be deleted without actually deleting.",
396
+ ),
397
+ ] = False,
398
+ include: Annotated[
399
+ list[str] | None,
400
+ Option(
401
+ help="Include only files matching pattern (can specify multiple). Requires --recursive.",
402
+ ),
403
+ ] = None,
404
+ exclude: Annotated[
405
+ list[str] | None,
406
+ Option(
407
+ help="Exclude files matching pattern (can specify multiple). Requires --recursive.",
408
+ ),
409
+ ] = None,
410
+ token: TokenOpt = None,
411
+ ) -> None:
412
+ """Remove files from a bucket.
413
+
414
+ To delete an entire bucket, use `hf buckets delete` instead.
415
+ """
416
+ parsed = _parse_bucket_uri(argument)
417
+ bucket_id = parsed.id
418
+ prefix = parsed.path_in_repo
419
+
420
+ if prefix == "" and not recursive:
421
+ raise click.BadParameter(
422
+ f"No file path specified. To remove files, provide a path"
423
+ f" (e.g. '{bucket_id}/FILE') or use --recursive to remove all files."
424
+ f" To delete the entire bucket, use `hf buckets delete {bucket_id}`."
425
+ )
426
+
427
+ if (include or exclude) and not recursive:
428
+ raise click.BadParameter("--include and --exclude require --recursive.")
429
+
430
+ api = get_hf_api(token=token)
431
+
432
+ if recursive:
433
+ status = out.status("Listing files from remote")
434
+
435
+ all_files: list[BucketFile] = []
436
+ for item in _iter_under_prefix(
437
+ api.list_bucket_tree(
438
+ bucket_id,
439
+ prefix=prefix or None,
440
+ recursive=True,
441
+ ),
442
+ prefix,
443
+ ):
444
+ if isinstance(item, BucketFile):
445
+ all_files.append(item)
446
+ status.update(f"Listing files from remote ({len(all_files)} files)")
447
+ status.done(f"Listing files from remote ({len(all_files)} files)")
448
+
449
+ if include or exclude:
450
+ matcher = FilterMatcher(include_patterns=include, exclude_patterns=exclude)
451
+ matched_files = [f for f in all_files if matcher.matches(f.path)]
452
+ else:
453
+ matched_files = all_files
454
+
455
+ file_paths = [f.path for f in matched_files]
456
+ total_size = sum(f.size for f in matched_files)
457
+ size_str = format_size(total_size, human_readable=True)
458
+
459
+ if not file_paths:
460
+ out.text("No files to remove.")
461
+ return
462
+
463
+ count_label = f"{len(file_paths)} file(s) totaling {size_str}"
464
+
465
+ if not yes and not dry_run:
466
+ out.text("\n".join(f" {path}" for path in file_paths))
467
+ out.confirm(f"Remove {count_label} from '{bucket_id}'?", yes=False)
468
+
469
+ if dry_run:
470
+ out.text("\n".join(f"delete: {BUCKET_PREFIX}{bucket_id}/{path}" for path in file_paths))
471
+ out.text(f"(dry run) {count_label} would be removed.")
472
+ return
473
+
474
+ api.batch_bucket_files(bucket_id, delete=file_paths)
475
+ out.result(
476
+ f"Removed {count_label} from '{bucket_id}'",
477
+ bucket_id=bucket_id,
478
+ files_deleted=len(file_paths),
479
+ size=size_str,
480
+ )
481
+
482
+ else:
483
+ file_path = prefix
484
+ if not file_path:
485
+ raise click.BadParameter("File path cannot be empty.")
486
+
487
+ if dry_run:
488
+ out.text(f"delete: {BUCKET_PREFIX}{bucket_id}/{file_path}")
489
+ out.text("(dry run) 1 file would be removed.")
490
+ return
491
+
492
+ out.confirm(f"Remove '{file_path}' from '{bucket_id}'?", yes=yes)
493
+
494
+ api.batch_bucket_files(bucket_id, delete=[file_path])
495
+ out.result("File removed", path=file_path, bucket_id=bucket_id)
496
+
497
+
498
+ @buckets_cli.command(
499
+ name="move",
500
+ examples=[
501
+ "hf buckets move user/old-bucket user/new-bucket",
502
+ "hf buckets move user/my-bucket my-org/my-bucket",
503
+ "hf buckets move hf://buckets/user/old-bucket hf://buckets/user/new-bucket",
504
+ ],
505
+ )
506
+ def move(
507
+ from_id: Annotated[
508
+ str,
509
+ Argument(
510
+ help="Source bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
511
+ ),
512
+ ],
513
+ to_id: Annotated[
514
+ str,
515
+ Argument(
516
+ help="Destination bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
517
+ ),
518
+ ],
519
+ token: TokenOpt = None,
520
+ ) -> None:
521
+ """Move (rename) a bucket to a new name or namespace."""
522
+ # Parse from_id
523
+ parsed_from = _parse_bucket_uri(from_id)
524
+ if parsed_from.path_in_repo:
525
+ raise click.BadParameter(
526
+ f"Cannot specify a prefix for bucket move: {from_id}."
527
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
528
+ )
529
+
530
+ # Parse to_id
531
+ parsed_to = _parse_bucket_uri(to_id)
532
+ if parsed_to.path_in_repo:
533
+ raise click.BadParameter(
534
+ f"Cannot specify a prefix for bucket move: {to_id}."
535
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
536
+ )
537
+
538
+ api = get_hf_api(token=token)
539
+ api.move_bucket(from_id=parsed_from.id, to_id=parsed_to.id)
540
+ out.result("Bucket moved", from_id=parsed_from.id, to_id=parsed_to.id)
541
+
542
+
543
+ @buckets_cli.command(
544
+ name="settings",
545
+ examples=[
546
+ "hf buckets settings user/my-bucket --private",
547
+ "hf buckets settings user/my-bucket --public",
548
+ "hf buckets settings hf://buckets/user/my-bucket --private",
549
+ ],
550
+ )
551
+ def settings(
552
+ bucket_id: Annotated[
553
+ str,
554
+ Argument(
555
+ help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
556
+ ),
557
+ ],
558
+ private: Annotated[
559
+ bool,
560
+ Option(
561
+ "--private",
562
+ help="Make the bucket private.",
563
+ ),
564
+ ] = False,
565
+ public: Annotated[
566
+ bool,
567
+ Option(
568
+ "--public",
569
+ help="Make the bucket public.",
570
+ ),
571
+ ] = False,
572
+ token: TokenOpt = None,
573
+ ) -> None:
574
+ """Update bucket settings (visibility)."""
575
+ if private == public:
576
+ raise click.BadParameter("Specify exactly one of --private or --public.")
577
+
578
+ if bucket_id.startswith(BUCKET_PREFIX):
579
+ parsed = _parse_bucket_uri(bucket_id)
580
+ if parsed.path_in_repo:
581
+ raise click.BadParameter(
582
+ f"Cannot specify a prefix for bucket settings: {bucket_id}."
583
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
584
+ )
585
+ bucket_id = parsed.id
586
+ elif "/" not in bucket_id:
587
+ raise click.BadParameter(
588
+ f"Invalid bucket ID: {bucket_id}."
589
+ f" Must be in format namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
590
+ )
591
+
592
+ api = get_hf_api(token=token)
593
+ api.update_bucket_settings(bucket_id, private=private)
594
+ out.result("Bucket settings updated", bucket_id=bucket_id, private=private)
595
+ out.hint(f"Run `hf buckets info {bucket_id}` to view bucket details.")
596
+
597
+
598
+ # =============================================================================
599
+ # Sync command
600
+ # =============================================================================
601
+
602
+
603
+ @buckets_cli.command(
604
+ name="sync",
605
+ examples=[
606
+ "hf buckets sync ./data hf://buckets/user/my-bucket",
607
+ "hf buckets sync hf://buckets/user/my-bucket ./data",
608
+ "hf buckets sync ./data hf://buckets/user/my-bucket --delete",
609
+ 'hf buckets sync hf://buckets/user/my-bucket ./data --include "*.safetensors" --exclude "*.tmp"',
610
+ "hf buckets sync ./data hf://buckets/user/my-bucket --plan sync-plan.jsonl",
611
+ "hf buckets sync --apply sync-plan.jsonl",
612
+ "hf buckets sync ./data hf://buckets/user/my-bucket --dry-run",
613
+ "hf buckets sync ./data hf://buckets/user/my-bucket --dry-run | jq .",
614
+ ],
615
+ )
616
+ def sync(
617
+ source: Annotated[
618
+ str | None,
619
+ Argument(
620
+ help="Source path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
621
+ ),
622
+ ] = None,
623
+ dest: Annotated[
624
+ str | None,
625
+ Argument(
626
+ help="Destination path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
627
+ ),
628
+ ] = None,
629
+ delete: Annotated[
630
+ bool,
631
+ Option(
632
+ help="Delete destination files not present in source.",
633
+ ),
634
+ ] = False,
635
+ ignore_times: Annotated[
636
+ bool,
637
+ Option(
638
+ "--ignore-times",
639
+ help="Skip files only based on size, ignoring modification times.",
640
+ ),
641
+ ] = False,
642
+ ignore_sizes: Annotated[
643
+ bool,
644
+ Option(
645
+ "--ignore-sizes",
646
+ help="Skip files only based on modification times, ignoring sizes.",
647
+ ),
648
+ ] = False,
649
+ plan: Annotated[
650
+ str | None,
651
+ Option(
652
+ help="Save sync plan to JSONL file for review instead of executing.",
653
+ ),
654
+ ] = None,
655
+ apply: Annotated[
656
+ str | None,
657
+ Option(
658
+ help="Apply a previously saved plan file.",
659
+ ),
660
+ ] = None,
661
+ dry_run: Annotated[
662
+ bool,
663
+ Option(
664
+ "--dry-run",
665
+ help="Print sync plan to stdout as JSONL without executing.",
666
+ ),
667
+ ] = False,
668
+ include: Annotated[
669
+ list[str] | None,
670
+ Option(
671
+ help="Include files matching pattern (can specify multiple).",
672
+ ),
673
+ ] = None,
674
+ exclude: Annotated[
675
+ list[str] | None,
676
+ Option(
677
+ help="Exclude files matching pattern (can specify multiple).",
678
+ ),
679
+ ] = None,
680
+ filter_from: Annotated[
681
+ str | None,
682
+ Option(
683
+ help="Read include/exclude patterns from file.",
684
+ ),
685
+ ] = None,
686
+ existing: Annotated[
687
+ bool,
688
+ Option(
689
+ "--existing",
690
+ help="Skip creating new files on receiver (only update existing files).",
691
+ ),
692
+ ] = False,
693
+ ignore_existing: Annotated[
694
+ bool,
695
+ Option(
696
+ "--ignore-existing",
697
+ help="Skip updating files that exist on receiver (only create new files).",
698
+ ),
699
+ ] = False,
700
+ verbose: Annotated[
701
+ bool,
702
+ Option(
703
+ "--verbose",
704
+ "-v",
705
+ help="Show detailed logging with reasoning.",
706
+ ),
707
+ ] = False,
708
+ token: TokenOpt = None,
709
+ ) -> None:
710
+ """Sync files between local directory and a bucket."""
711
+ api = get_hf_api(token=token)
712
+ api.sync_bucket(
713
+ source=source,
714
+ dest=dest,
715
+ delete=delete,
716
+ ignore_times=ignore_times,
717
+ ignore_sizes=ignore_sizes,
718
+ existing=existing,
719
+ ignore_existing=ignore_existing,
720
+ include=include,
721
+ exclude=exclude,
722
+ filter_from=filter_from,
723
+ plan=plan,
724
+ apply=apply,
725
+ dry_run=dry_run,
726
+ verbose=verbose,
727
+ quiet=out.is_quiet(),
728
+ )
729
+ if plan and not out.is_quiet():
730
+ out.hint(f"Run `hf buckets sync --apply {plan}` to execute this plan.")
731
+
732
+
733
+ # =============================================================================
734
+ # Cp command
735
+ # =============================================================================
736
+
737
+
738
+ # `hf buckets cp` is an alias for the top-level `hf cp` command (see `cli/_cp.py`).
739
+ buckets_cli.command(
740
+ name="cp",
741
+ examples=[
742
+ # Download (repo or bucket -> local / stdout)
743
+ "hf buckets cp hf://buckets/username/my-bucket/config.json config.json",
744
+ "hf buckets cp hf://buckets/username/my-bucket/data.csv data/",
745
+ "hf buckets cp hf://buckets/username/my-bucket/config.json -",
746
+ # Upload (local / stdin -> bucket)
747
+ "hf buckets cp model.safetensors hf://buckets/username/my-bucket/model.safetensors",
748
+ "hf buckets cp config.json hf://buckets/username/my-bucket/logs/",
749
+ "hf buckets cp - hf://buckets/username/my-bucket/config.json",
750
+ # Remote to remote (repo or bucket -> bucket)
751
+ "hf buckets cp hf://buckets/username/my-bucket/data.csv hf://buckets/username/dest-bucket/",
752
+ "hf buckets cp hf://buckets/username/source-bucket/logs/ hf://buckets/username/dest-bucket/logs/",
753
+ ],
754
+ )(make_cp("buckets"))
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/cache.py ADDED
@@ -0,0 +1,896 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 re
17
+ import time
18
+ from collections import defaultdict
19
+ from collections.abc import Callable, Mapping
20
+ from dataclasses import dataclass, field
21
+ from enum import Enum
22
+ from typing import Annotated, Any
23
+
24
+ import click
25
+
26
+ from huggingface_hub.errors import CLIError
27
+
28
+ from ..utils import (
29
+ ANSI,
30
+ CachedFileInfo,
31
+ CachedRepoInfo,
32
+ CachedRevisionInfo,
33
+ CacheNotFound,
34
+ HFCacheInfo,
35
+ HfUri,
36
+ _format_size,
37
+ _shared_blobs,
38
+ parse_hf_uri,
39
+ scan_cache_dir,
40
+ )
41
+ from ..utils._parsing import parse_duration, parse_size
42
+ from ._cli_utils import RepoIdArg, RepoTypeOpt, RevisionOpt, TokenOpt, get_hf_api, typer_factory
43
+ from ._framework import Argument, Option
44
+ from ._output import out
45
+
46
+
47
+ cache_cli = typer_factory(help="Manage local cache directory.")
48
+
49
+
50
+ #### Cache helper utilities
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class _DeletionResolution:
55
+ revisions: frozenset[str]
56
+ selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]]
57
+ missing: tuple[str, ...]
58
+ files: dict[CachedFileInfo, str] = field(default_factory=dict) # selected files, mapped to their display label
59
+
60
+
61
+ _FILTER_PATTERN = re.compile(r"(?P<key>[a-zA-Z_]+)\s*(?P<op>==|!=|>=|<=|>|<|=)\s*(?P<value>.+)")
62
+ _ALLOWED_OPERATORS = {"=", "!=", ">", "<", ">=", "<="}
63
+ _FILTER_KEYS = {"accessed", "modified", "refs", "size", "type"}
64
+ _SORT_KEYS = {"accessed", "modified", "name", "size"}
65
+ _SORT_PATTERN = re.compile(r"(?P<key>[a-zA-Z_]+)(?::(?P<order>asc|desc))?")
66
+ _SORT_DEFAULT_ORDER = {
67
+ # Default ordering: accessed/modified/size are descending (newest/biggest first), name is ascending
68
+ "accessed": "desc",
69
+ "modified": "desc",
70
+ "size": "desc",
71
+ "name": "asc",
72
+ }
73
+
74
+
75
+ # Dynamically generate SortOptions enum from _SORT_KEYS
76
+ _sort_options_dict = {}
77
+ for key in sorted(_SORT_KEYS):
78
+ _sort_options_dict[key] = key
79
+ _sort_options_dict[f"{key}_asc"] = f"{key}:asc"
80
+ _sort_options_dict[f"{key}_desc"] = f"{key}:desc"
81
+
82
+ SortOptions = Enum("SortOptions", _sort_options_dict, type=str, module=__name__) # type: ignore
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class CacheDeletionCounts:
87
+ """Simple counters summarizing cache deletions for CLI messaging."""
88
+
89
+ repo_count: int
90
+ partial_revision_count: int
91
+ total_revision_count: int
92
+
93
+
94
+ CacheEntry = tuple[CachedRepoInfo, CachedRevisionInfo | None]
95
+ RepoRefsMap = dict[CachedRepoInfo, frozenset[str]]
96
+
97
+
98
+ def summarize_deletions(
99
+ selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]],
100
+ ) -> CacheDeletionCounts:
101
+ """Summarize deletions across repositories."""
102
+ repo_count = 0
103
+ total_revisions = 0
104
+ revisions_in_full_repos = 0
105
+
106
+ for repo, revisions in selected_by_repo.items():
107
+ total_revisions += len(revisions)
108
+ if len(revisions) == len(repo.revisions):
109
+ repo_count += 1
110
+ revisions_in_full_repos += len(revisions)
111
+
112
+ partial_revision_count = total_revisions - revisions_in_full_repos
113
+ return CacheDeletionCounts(repo_count, partial_revision_count, total_revisions)
114
+
115
+
116
+ def _prune_summary(revision_count: int, incomplete_count: int, shared_blob_count: int) -> str:
117
+ """Build the human-readable summary of what `hf cache prune` is about to delete."""
118
+ parts: list[str] = []
119
+ if revision_count:
120
+ parts.append(f"{revision_count} unreferenced revision(s)")
121
+ if incomplete_count:
122
+ parts.append(f"{incomplete_count} incomplete download(s)")
123
+ if shared_blob_count:
124
+ parts.append(f"{shared_blob_count} unreferenced shared blob(s)")
125
+ if len(parts) > 1:
126
+ return ", ".join(parts[:-1]) + " and " + parts[-1]
127
+ return "".join(parts)
128
+
129
+
130
+ def print_cache_selected_revisions(selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]]) -> None:
131
+ """Pretty-print selected cache revisions during confirmation prompts."""
132
+ for repo in sorted(selected_by_repo.keys(), key=lambda repo: (repo.repo_type, repo.repo_id.lower())):
133
+ repo_key = f"{repo.repo_type}/{repo.repo_id}"
134
+ revisions = sorted(selected_by_repo[repo], key=lambda rev: rev.commit_hash)
135
+ if len(revisions) == len(repo.revisions):
136
+ out.text(f" - {repo_key} (entire repo)")
137
+ continue
138
+
139
+ out.text(f" - {repo_key}:")
140
+ for revision in revisions:
141
+ refs = " ".join(sorted(revision.refs)) or "(detached)"
142
+ out.text(f" {revision.commit_hash} [{refs}] {revision.size_on_disk_str}")
143
+
144
+
145
+ def build_cache_index(
146
+ hf_cache_info: HFCacheInfo,
147
+ ) -> tuple[
148
+ dict[str, CachedRepoInfo],
149
+ dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]],
150
+ ]:
151
+ """Create lookup tables so CLI commands can resolve repo ids and revisions quickly."""
152
+ repo_lookup: dict[str, CachedRepoInfo] = {}
153
+ revision_lookup: dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]] = {}
154
+ for repo in hf_cache_info.repos:
155
+ repo_key = repo.cache_id.lower()
156
+ repo_lookup[repo_key] = repo
157
+ for revision in repo.revisions:
158
+ revision_lookup[revision.commit_hash.lower()] = (repo, revision)
159
+ return repo_lookup, revision_lookup
160
+
161
+
162
+ def _parse_hf_uri_target(target: str) -> HfUri:
163
+ """Parse and validate an hf:// target passed to `hf cache rm`."""
164
+ uri = parse_hf_uri(target)
165
+ if not uri.is_repo:
166
+ raise CLIError("Only repository hf:// URIs are supported by `hf cache rm`.")
167
+ if uri.revision is not None:
168
+ hint = (
169
+ "Drop '@<revision>' to delete the file from all cached revisions."
170
+ if uri.path_in_repo
171
+ else "Pass the revision hash instead, see 'hf cache ls --revisions'."
172
+ )
173
+ raise CLIError(f"Revisions in hf:// URIs are not supported by `hf cache rm`. {hint}")
174
+ return uri
175
+
176
+
177
+ def _cache_id(uri: HfUri) -> str:
178
+ """Return the `type/id` cache id of a repo URI."""
179
+ return f"{uri.type}/{uri.id}"
180
+
181
+
182
+ def collect_cache_entries(
183
+ hf_cache_info: HFCacheInfo, *, include_revisions: bool
184
+ ) -> tuple[list[CacheEntry], RepoRefsMap]:
185
+ """Flatten cache metadata into rows consumed by `hf cache ls`."""
186
+ entries: list[CacheEntry] = []
187
+ repo_refs_map: RepoRefsMap = {}
188
+ sorted_repos = sorted(hf_cache_info.repos, key=lambda repo: (repo.repo_type, repo.repo_id.lower()))
189
+ for repo in sorted_repos:
190
+ repo_refs_map[repo] = frozenset({ref for revision in repo.revisions for ref in revision.refs})
191
+ if include_revisions:
192
+ for revision in sorted(repo.revisions, key=lambda rev: rev.commit_hash):
193
+ entries.append((repo, revision))
194
+ else:
195
+ entries.append((repo, None))
196
+ if include_revisions:
197
+ entries.sort(
198
+ key=lambda entry: (
199
+ entry[0].cache_id,
200
+ entry[1].commit_hash if entry[1] is not None else "",
201
+ )
202
+ )
203
+ else:
204
+ entries.sort(key=lambda entry: entry[0].cache_id)
205
+ return entries, repo_refs_map
206
+
207
+
208
+ def compile_cache_filter(
209
+ expr: str, repo_refs_map: RepoRefsMap
210
+ ) -> Callable[[CachedRepoInfo, CachedRevisionInfo | None, float], bool]:
211
+ """Convert a `hf cache ls` filter expression into the yes/no test we apply to each cache entry before displaying it."""
212
+ match = _FILTER_PATTERN.fullmatch(expr.strip())
213
+ if not match:
214
+ raise ValueError(f"Invalid filter expression: '{expr}'.")
215
+
216
+ key = match.group("key").lower()
217
+ op = match.group("op")
218
+ value_raw = match.group("value").strip()
219
+
220
+ if op not in _ALLOWED_OPERATORS:
221
+ raise ValueError(f"Unsupported operator '{op}' in filter '{expr}'. Must be one of {list(_ALLOWED_OPERATORS)}.")
222
+
223
+ if key not in _FILTER_KEYS:
224
+ raise ValueError(f"Unsupported filter key '{key}' in '{expr}'. Must be one of {list(_FILTER_KEYS)}.")
225
+ # at this point we know that key is in `_FILTER_KEYS`
226
+ if key == "size":
227
+ size_threshold = parse_size(value_raw)
228
+ return lambda repo, revision, _: _compare_numeric(
229
+ revision.size_on_disk if revision is not None else repo.size_on_disk,
230
+ op,
231
+ size_threshold,
232
+ )
233
+
234
+ if key in {"modified", "accessed"}:
235
+ seconds = parse_duration(value_raw.strip())
236
+
237
+ def _time_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, now: float) -> bool:
238
+ timestamp = (
239
+ repo.last_accessed
240
+ if key == "accessed"
241
+ else revision.last_modified
242
+ if revision is not None
243
+ else repo.last_modified
244
+ )
245
+ if timestamp is None:
246
+ return False
247
+ return _compare_numeric(now - timestamp, op, seconds)
248
+
249
+ return _time_filter
250
+
251
+ if key == "type":
252
+ expected = value_raw.lower()
253
+
254
+ if op != "=":
255
+ raise ValueError(f"Only '=' is supported for 'type' filters. Got '{op}'.")
256
+
257
+ def _type_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
258
+ return repo.repo_type.lower() == expected
259
+
260
+ return _type_filter
261
+
262
+ else: # key == "refs"
263
+ if op != "=":
264
+ raise ValueError(f"Only '=' is supported for 'refs' filters. Got {op}.")
265
+
266
+ def _refs_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
267
+ refs = revision.refs if revision is not None else repo_refs_map.get(repo, frozenset())
268
+ return value_raw.lower() in [ref.lower() for ref in refs]
269
+
270
+ return _refs_filter
271
+
272
+
273
+ def _compare_numeric(left: float | None, op: str, right: float) -> bool:
274
+ """Evaluate numeric comparisons for filters."""
275
+ if left is None:
276
+ return False
277
+
278
+ comparisons = {
279
+ "=": left == right,
280
+ "!=": left != right,
281
+ ">": left > right,
282
+ "<": left < right,
283
+ ">=": left >= right,
284
+ "<=": left <= right,
285
+ }
286
+
287
+ if op not in comparisons:
288
+ raise ValueError(f"Unsupported numeric comparison operator: {op}")
289
+
290
+ return comparisons[op]
291
+
292
+
293
+ def compile_cache_sort(sort_expr: str) -> tuple[Callable[[CacheEntry], tuple[Any, ...]], bool]:
294
+ """Convert a `hf cache ls` sort expression into a key function for sorting entries.
295
+
296
+ Returns:
297
+ A tuple of (key_function, reverse_flag) where reverse_flag indicates whether
298
+ to sort in descending order (True) or ascending order (False).
299
+ """
300
+ match = _SORT_PATTERN.fullmatch(sort_expr.strip().lower())
301
+ if not match:
302
+ raise ValueError(f"Invalid sort expression: '{sort_expr}'. Expected format: 'key' or 'key:asc' or 'key:desc'.")
303
+
304
+ key = match.group("key").lower()
305
+ explicit_order = match.group("order")
306
+
307
+ if key not in _SORT_KEYS:
308
+ raise ValueError(f"Unsupported sort key '{key}' in '{sort_expr}'. Must be one of {list(_SORT_KEYS)}.")
309
+
310
+ # Use explicit order if provided, otherwise use default for the key
311
+ order = explicit_order if explicit_order else _SORT_DEFAULT_ORDER[key]
312
+ reverse = order == "desc"
313
+
314
+ def _sort_key(entry: CacheEntry) -> tuple[Any, ...]:
315
+ repo, revision = entry
316
+
317
+ if key == "name":
318
+ # Sort by cache_id (repo type/id)
319
+ value: Any = repo.cache_id.lower()
320
+ return (value,)
321
+
322
+ if key == "size":
323
+ # Use revision size if available, otherwise repo size
324
+ value = revision.size_on_disk if revision is not None else repo.size_on_disk
325
+ return (value,)
326
+
327
+ if key == "accessed":
328
+ # For revisions, accessed is not available per-revision, use repo's last_accessed
329
+ # For repos, use repo's last_accessed
330
+ value = repo.last_accessed if repo.last_accessed is not None else 0.0
331
+ return (value,)
332
+
333
+ if key == "modified":
334
+ # Use revision's last_modified if available, otherwise repo's last_modified
335
+ if revision is not None:
336
+ value = revision.last_modified if revision.last_modified is not None else 0.0
337
+ else:
338
+ value = repo.last_modified if repo.last_modified is not None else 0.0
339
+ return (value,)
340
+
341
+ # Should never reach here due to validation above
342
+ raise ValueError(f"Unsupported sort key: {key}")
343
+
344
+ return _sort_key, reverse
345
+
346
+
347
+ def _resolve_deletion_targets(hf_cache_info: HFCacheInfo, targets: list[str]) -> _DeletionResolution:
348
+ """Resolve the deletion targets into a deletion resolution."""
349
+ targets = [stripped for target in targets if (stripped := target.strip())]
350
+ uris = {target: _parse_hf_uri_target(target) for target in targets if target.startswith("hf://")}
351
+ file_uris = {target: uri for target, uri in uris.items() if uri.path_in_repo}
352
+ if file_uris:
353
+ if len(file_uris) != len(set(targets)):
354
+ raise CLIError("File targets cannot be mixed with repository or revision targets.")
355
+ return _resolve_file_targets(hf_cache_info, file_uris)
356
+
357
+ repo_lookup, revision_lookup = build_cache_index(hf_cache_info)
358
+
359
+ selected: dict[CachedRepoInfo, set[CachedRevisionInfo]] = defaultdict(set)
360
+ revisions: set[str] = set()
361
+ missing: list[str] = []
362
+
363
+ for target in targets:
364
+ lowered = target.lower()
365
+
366
+ if re.fullmatch(r"[0-9a-fA-F]{40}", lowered):
367
+ match = revision_lookup.get(lowered)
368
+ if match is None:
369
+ missing.append(target)
370
+ continue
371
+ repo, revision = match
372
+ selected[repo].add(revision)
373
+ revisions.add(revision.commit_hash)
374
+ continue
375
+
376
+ cache_id = _cache_id(uris[target]) if target in uris else target
377
+ matched_repo = repo_lookup.get(cache_id.lower())
378
+ if matched_repo is None:
379
+ missing.append(target)
380
+ continue
381
+
382
+ for revision in matched_repo.revisions:
383
+ selected[matched_repo].add(revision)
384
+ revisions.add(revision.commit_hash)
385
+
386
+ frozen_selected = {repo: frozenset(revs) for repo, revs in selected.items()}
387
+ return _DeletionResolution(
388
+ revisions=frozenset(revisions),
389
+ selected=frozen_selected,
390
+ missing=tuple(missing),
391
+ )
392
+
393
+
394
+ def _resolve_file_targets(hf_cache_info: HFCacheInfo, file_uris: dict[str, HfUri]) -> _DeletionResolution:
395
+ """Select the cached files matching hf:// file URIs, in every cached revision of their repo."""
396
+ repo_lookup, _ = build_cache_index(hf_cache_info)
397
+ files: dict[CachedFileInfo, str] = {}
398
+ missing: list[str] = []
399
+ for target, uri in file_uris.items():
400
+ repo = repo_lookup.get(_cache_id(uri).lower())
401
+ if repo is None:
402
+ missing.append(target)
403
+ continue
404
+ matches = {
405
+ file: f"{repo.cache_id}@{revision.commit_hash}/{uri.path_in_repo}"
406
+ for revision in repo.revisions
407
+ for file in revision.files
408
+ if file.file_path.relative_to(revision.snapshot_path).as_posix() == uri.path_in_repo
409
+ }
410
+ if not matches:
411
+ missing.append(target)
412
+ files.update(matches)
413
+ return _DeletionResolution(revisions=frozenset(), selected={}, missing=tuple(missing), files=files)
414
+
415
+
416
+ #### Cache CLI commands
417
+
418
+
419
+ @cache_cli.command(
420
+ "list | ls",
421
+ examples=[
422
+ "hf cache ls",
423
+ "hf cache ls --revisions",
424
+ 'hf cache ls --filter "size>1GB" --limit 20',
425
+ "hf cache ls --format json",
426
+ ],
427
+ )
428
+ def ls(
429
+ cache_dir: Annotated[
430
+ str | None,
431
+ Option(
432
+ help="Cache directory to scan (defaults to Hugging Face cache).",
433
+ ),
434
+ ] = None,
435
+ revisions: Annotated[
436
+ bool,
437
+ Option(
438
+ help="Include revisions in the output instead of aggregated repositories.",
439
+ ),
440
+ ] = False,
441
+ filter: Annotated[
442
+ list[str] | None,
443
+ Option(
444
+ "-f",
445
+ "--filter",
446
+ help="Filter entries (e.g. 'size>1GB', 'type=model', 'accessed>7d'). Can be used multiple times.",
447
+ ),
448
+ ] = None,
449
+ sort: Annotated[
450
+ SortOptions | None,
451
+ Option(
452
+ help="Sort entries by key. Supported keys: 'accessed', 'modified', 'name', 'size'. "
453
+ "Append ':asc' or ':desc' to explicitly set the order (e.g., 'modified:asc'). "
454
+ "Defaults: 'accessed', 'modified', 'size' default to 'desc' (newest/biggest first); "
455
+ "'name' defaults to 'asc' (alphabetical).",
456
+ ),
457
+ ] = None,
458
+ limit: Annotated[
459
+ int | None,
460
+ Option(
461
+ help="Limit the number of results returned. Returns only the top N entries after sorting.",
462
+ ),
463
+ ] = None,
464
+ show_warnings: Annotated[
465
+ bool,
466
+ Option(
467
+ help="Show warnings about cache inconsistencies.",
468
+ ),
469
+ ] = False,
470
+ ) -> None:
471
+ """List cached repositories or revisions."""
472
+ try:
473
+ hf_cache_info = scan_cache_dir(cache_dir)
474
+ except CacheNotFound as exc:
475
+ raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
476
+
477
+ filters = filter or []
478
+
479
+ entries, repo_refs_map = collect_cache_entries(hf_cache_info, include_revisions=revisions)
480
+ try:
481
+ filter_fns = [compile_cache_filter(expr, repo_refs_map) for expr in filters]
482
+ except ValueError as exc:
483
+ raise click.BadParameter(str(exc)) from exc
484
+
485
+ now = time.time()
486
+ for fn in filter_fns:
487
+ entries = [entry for entry in entries if fn(entry[0], entry[1], now)]
488
+
489
+ # Apply sorting if requested
490
+ if sort:
491
+ try:
492
+ sort_key_fn, reverse = compile_cache_sort(sort.value)
493
+ entries.sort(key=sort_key_fn, reverse=reverse)
494
+ except ValueError as exc:
495
+ raise click.BadParameter(str(exc)) from exc
496
+
497
+ # Apply limit if requested
498
+ if limit is not None:
499
+ if limit < 0:
500
+ raise click.BadParameter(f"Limit must be a positive integer, got {limit}.")
501
+ entries = entries[:limit]
502
+
503
+ if revisions:
504
+ items = [
505
+ {
506
+ "id": repo.cache_id,
507
+ "repo_id": repo.repo_id,
508
+ "repo_type": repo.repo_type,
509
+ "revision": revision.commit_hash,
510
+ "snapshot_path": str(revision.snapshot_path),
511
+ "size": revision.size_on_disk_str,
512
+ "last_modified": revision.last_modified_str,
513
+ "refs": sorted(revision.refs),
514
+ }
515
+ for repo, revision in entries
516
+ if revision is not None
517
+ ]
518
+ out.table(
519
+ items,
520
+ headers=["id", "revision", "size", "last_modified", "refs"],
521
+ id_key="revision",
522
+ alignments={"size": "right"},
523
+ )
524
+ else:
525
+ items = [
526
+ {
527
+ "id": repo.cache_id,
528
+ "repo_id": repo.repo_id,
529
+ "repo_type": repo.repo_type,
530
+ "size": repo.size_on_disk_str,
531
+ "last_accessed": repo.last_accessed_str or "",
532
+ "last_modified": repo.last_modified_str,
533
+ "refs": sorted(repo_refs_map.get(repo, frozenset())),
534
+ }
535
+ for repo, _ in entries
536
+ ]
537
+ out.table(
538
+ items,
539
+ headers=["id", "size", "last_accessed", "last_modified", "refs"],
540
+ id_key="id",
541
+ alignments={"size": "right"},
542
+ )
543
+
544
+ if entries:
545
+ unique_repos = {repo for repo, _ in entries}
546
+ repo_count = len(unique_repos)
547
+ if revisions:
548
+ revision_count = sum(1 for _, rev in entries if rev is not None)
549
+ total_size = sum(rev.size_on_disk for _, rev in entries if rev is not None)
550
+ else:
551
+ revision_count = sum(len(repo.revisions) for repo in unique_repos)
552
+ if filters or limit is not None:
553
+ total_size = sum(repo.size_on_disk for repo in unique_repos)
554
+ else:
555
+ # Per-repo sizes double-count blobs shared across repos: report the physical total.
556
+ total_size = hf_cache_info.size_on_disk
557
+ out.text(
558
+ ANSI.bold(
559
+ f"\nFound {repo_count} repo(s) for a total of {revision_count} revision(s)"
560
+ f" and {_format_size(total_size)} on disk."
561
+ )
562
+ )
563
+
564
+ if len(hf_cache_info.warnings):
565
+ if show_warnings:
566
+ for warning in hf_cache_info.warnings:
567
+ out.warning(str(warning).rstrip(".") + ". Repo ignored.")
568
+ else:
569
+ out.warning(
570
+ f"Found {len(hf_cache_info.warnings)} cache inconsistencies. Re-run with `--show-warnings` to display them."
571
+ )
572
+
573
+ incomplete_files = hf_cache_info.incomplete_files
574
+ if incomplete_files:
575
+ out.hint(
576
+ f"Found {len(incomplete_files)} incomplete download(s) totalling "
577
+ f"{_format_size(hf_cache_info.incomplete_size_on_disk)}. "
578
+ "Remove them with 'hf cache prune'."
579
+ )
580
+
581
+
582
+ @cache_cli.command(
583
+ examples=[
584
+ "hf cache rm model/gpt2",
585
+ "hf cache rm hf://models/openai-community/gpt2",
586
+ "hf cache rm hf://models/openai-community/gpt2/model.safetensors",
587
+ "hf cache rm <revision_hash>",
588
+ "hf cache rm model/gpt2 --dry-run",
589
+ "hf cache rm model/gpt2 --yes",
590
+ ],
591
+ )
592
+ def rm(
593
+ targets: Annotated[
594
+ list[str],
595
+ Argument(
596
+ help="One or more repo IDs (e.g. model/bert-base-uncased), hf:// URIs (repo or file), or revision hashes to delete.",
597
+ ),
598
+ ],
599
+ cache_dir: Annotated[
600
+ str | None,
601
+ Option(
602
+ help="Cache directory to scan (defaults to Hugging Face cache).",
603
+ ),
604
+ ] = None,
605
+ yes: Annotated[
606
+ bool,
607
+ Option(
608
+ "-y",
609
+ "--yes",
610
+ help="Skip confirmation prompt.",
611
+ ),
612
+ ] = False,
613
+ dry_run: Annotated[
614
+ bool,
615
+ Option(
616
+ help="Preview deletions without removing anything.",
617
+ ),
618
+ ] = False,
619
+ ) -> None:
620
+ """Remove cached repositories, revisions or files."""
621
+ try:
622
+ hf_cache_info = scan_cache_dir(cache_dir)
623
+ except CacheNotFound as exc:
624
+ raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
625
+
626
+ resolution = _resolve_deletion_targets(hf_cache_info, targets)
627
+
628
+ if resolution.missing:
629
+ details = "\n".join(f" - {entry}" for entry in resolution.missing)
630
+ out.warning(f"Could not find in cache:\n{details}")
631
+
632
+ if resolution.files:
633
+ strategy = hf_cache_info.delete_files(*resolution.files)
634
+ out.text(f"About to delete {len(resolution.files)} file(s) totalling {strategy.expected_freed_size_str}.")
635
+ for label in sorted(resolution.files.values()):
636
+ out.text(f" - {label}")
637
+ if dry_run:
638
+ out.result(
639
+ "Dry run: no files were deleted.",
640
+ dry_run=True,
641
+ files=len(resolution.files),
642
+ size=strategy.expected_freed_size_str,
643
+ )
644
+ return
645
+ out.confirm("Proceed with deletion?", yes=yes)
646
+ strategy.execute()
647
+ out.result(
648
+ f"Deleted {len(resolution.files)} file(s); freed {strategy.expected_freed_size_str}.",
649
+ files_deleted=len(resolution.files),
650
+ freed=strategy.expected_freed_size_str,
651
+ )
652
+ return
653
+
654
+ if len(resolution.revisions) == 0:
655
+ out.text("Nothing to delete.")
656
+ raise click.exceptions.Exit(code=0)
657
+
658
+ strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions))
659
+ counts = summarize_deletions(resolution.selected)
660
+
661
+ summary_parts: list[str] = []
662
+ if counts.repo_count:
663
+ summary_parts.append(f"{counts.repo_count} repo(s)")
664
+ if counts.partial_revision_count:
665
+ summary_parts.append(f"{counts.partial_revision_count} revision(s)")
666
+ if not summary_parts:
667
+ summary_parts.append(f"{counts.total_revision_count} revision(s)")
668
+
669
+ summary_text = " and ".join(summary_parts)
670
+ out.text(f"About to delete {summary_text} totalling {strategy.expected_freed_size_str}.")
671
+ print_cache_selected_revisions(resolution.selected)
672
+
673
+ if dry_run:
674
+ out.result(
675
+ "Dry run: no files were deleted.",
676
+ dry_run=True,
677
+ repos=counts.repo_count,
678
+ revisions=counts.total_revision_count,
679
+ size=strategy.expected_freed_size_str,
680
+ )
681
+ return
682
+
683
+ out.confirm("Proceed with deletion?", yes=yes)
684
+
685
+ strategy.execute()
686
+ counts = summarize_deletions(resolution.selected)
687
+ out.result(
688
+ f"Deleted {counts.repo_count} repo(s) and {counts.total_revision_count} revision(s);"
689
+ f" freed {strategy.expected_freed_size_str}.",
690
+ repos_deleted=counts.repo_count,
691
+ revisions_deleted=counts.total_revision_count,
692
+ freed=strategy.expected_freed_size_str,
693
+ )
694
+
695
+
696
+ @cache_cli.command(examples=["hf cache prune", "hf cache prune --dry-run"])
697
+ def prune(
698
+ cache_dir: Annotated[
699
+ str | None,
700
+ Option(
701
+ help="Cache directory to scan (defaults to Hugging Face cache).",
702
+ ),
703
+ ] = None,
704
+ yes: Annotated[
705
+ bool,
706
+ Option(
707
+ "-y",
708
+ "--yes",
709
+ help="Skip confirmation prompt.",
710
+ ),
711
+ ] = False,
712
+ dry_run: Annotated[
713
+ bool,
714
+ Option(
715
+ help="Preview deletions without removing anything.",
716
+ ),
717
+ ] = False,
718
+ ) -> None:
719
+ """Remove detached revisions and incomplete downloads from the cache."""
720
+ try:
721
+ hf_cache_info = scan_cache_dir(cache_dir)
722
+ except CacheNotFound as exc:
723
+ raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
724
+
725
+ selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]] = {}
726
+ revisions: set[str] = set()
727
+ for repo in hf_cache_info.repos:
728
+ detached = frozenset(revision for revision in repo.revisions if len(revision.refs) == 0)
729
+ if not detached:
730
+ continue
731
+ selected[repo] = detached
732
+ revisions.update(revision.commit_hash for revision in detached)
733
+
734
+ incomplete_files = hf_cache_info.incomplete_files
735
+ # Shared blobs left behind when a repo folder is deleted manually or by an older client.
736
+ unreferenced_blobs = (
737
+ _shared_blobs.unreferenced_shared_blobs(hf_cache_info.cache_dir) if hf_cache_info.cache_dir is not None else {}
738
+ )
739
+
740
+ if len(revisions) == 0 and not incomplete_files and not unreferenced_blobs:
741
+ out.text("No unreferenced revisions, incomplete downloads or shared blobs found. Nothing to prune.")
742
+ return
743
+
744
+ strategy = hf_cache_info.delete_revisions(*sorted(revisions))
745
+ counts = summarize_deletions(selected)
746
+ total_freed = (
747
+ strategy.expected_freed_size + hf_cache_info.incomplete_size_on_disk + sum(unreferenced_blobs.values())
748
+ )
749
+
750
+ summary = _prune_summary(counts.total_revision_count, len(incomplete_files), len(unreferenced_blobs))
751
+ out.text(f"About to delete {summary} ({_format_size(total_freed)} total).")
752
+ print_cache_selected_revisions(selected)
753
+
754
+ if dry_run:
755
+ out.result(
756
+ "Dry run: no files were deleted.",
757
+ dry_run=True,
758
+ revisions=counts.total_revision_count,
759
+ incomplete=len(incomplete_files), # might be overstated but it's fine
760
+ shared_blobs=len(unreferenced_blobs),
761
+ size=_format_size(total_freed),
762
+ )
763
+ return
764
+
765
+ out.confirm("Proceed?", yes=yes)
766
+
767
+ strategy.execute()
768
+ for incomplete_file in incomplete_files:
769
+ try:
770
+ incomplete_file.file_path.unlink()
771
+ except FileNotFoundError:
772
+ pass # already removed (e.g. by a full-repo deletion above)
773
+ except OSError as exc:
774
+ out.warning(f"Could not delete incomplete file {incomplete_file.file_path}: {exc}")
775
+ if hf_cache_info.cache_dir is not None:
776
+ for store_path in unreferenced_blobs:
777
+ _shared_blobs.sweep_shared_blob(store_path, cache_dir=hf_cache_info.cache_dir)
778
+ out.result(
779
+ f"Deleted {summary}; freed {_format_size(total_freed)}.",
780
+ revisions_deleted=counts.total_revision_count,
781
+ incomplete_deleted=len(incomplete_files),
782
+ shared_blobs_deleted=len(unreferenced_blobs),
783
+ freed=_format_size(total_freed),
784
+ )
785
+
786
+
787
+ @cache_cli.command(
788
+ examples=[
789
+ "hf cache verify gpt2",
790
+ "hf cache verify gpt2 --revision refs/pr/1",
791
+ "hf cache verify my-dataset --repo-type dataset",
792
+ ],
793
+ )
794
+ def verify(
795
+ repo_id: RepoIdArg,
796
+ repo_type: RepoTypeOpt = RepoTypeOpt.model,
797
+ revision: RevisionOpt = None,
798
+ cache_dir: Annotated[
799
+ str | None,
800
+ Option(
801
+ help="Cache directory to use when verifying files from cache (defaults to Hugging Face cache).",
802
+ ),
803
+ ] = None,
804
+ local_dir: Annotated[
805
+ str | None,
806
+ Option(
807
+ help="If set, verify files under this directory instead of the cache.",
808
+ ),
809
+ ] = None,
810
+ fail_on_missing_files: Annotated[
811
+ bool,
812
+ Option(
813
+ "--fail-on-missing-files",
814
+ help="Fail if some files exist on the remote but are missing locally.",
815
+ ),
816
+ ] = False,
817
+ fail_on_extra_files: Annotated[
818
+ bool,
819
+ Option(
820
+ "--fail-on-extra-files",
821
+ help="Fail if some files exist locally but are not present on the remote revision.",
822
+ ),
823
+ ] = False,
824
+ token: TokenOpt = None,
825
+ ) -> None:
826
+ """Verify checksums for a single repo revision from cache or a local directory.
827
+
828
+ Examples:
829
+ - Verify main revision in cache: `hf cache verify gpt2`
830
+ - Verify specific revision: `hf cache verify gpt2 --revision refs/pr/1`
831
+ - Verify dataset: `hf cache verify karpathy/fineweb-edu-100b-shuffle --repo-type dataset`
832
+ - Verify local dir: `hf cache verify deepseek-ai/DeepSeek-OCR --local-dir /path/to/repo`
833
+ """
834
+
835
+ if local_dir is not None and cache_dir is not None:
836
+ out.error("Cannot pass both --local-dir and --cache-dir. Use one or the other.")
837
+ raise click.exceptions.Exit(code=2)
838
+
839
+ api = get_hf_api(token=token)
840
+
841
+ result = api.verify_repo_checksums(
842
+ repo_id=repo_id,
843
+ repo_type=repo_type.value if hasattr(repo_type, "value") else str(repo_type),
844
+ revision=revision,
845
+ local_dir=local_dir,
846
+ cache_dir=cache_dir,
847
+ token=token,
848
+ )
849
+
850
+ exit_code = 0
851
+
852
+ if result.mismatches:
853
+ details = "\n".join(
854
+ f" - {m['path']}: expected {m['expected']} ({m['algorithm']}), got {m['actual']}"
855
+ for m in result.mismatches
856
+ )
857
+ out.text(f"❌ Checksum verification failed for the following file(s):\n{details}")
858
+ exit_code = 1
859
+
860
+ if result.missing_paths:
861
+ if fail_on_missing_files:
862
+ details = "\n".join(f" - {p}" for p in result.missing_paths)
863
+ out.text(f"❌ Missing files (present remotely, absent locally):\n{details}")
864
+ exit_code = 1
865
+ else:
866
+ out.warning(
867
+ f"{len(result.missing_paths)} remote file(s) are missing locally. "
868
+ "Use --fail-on-missing-files for details."
869
+ )
870
+
871
+ if result.extra_paths:
872
+ if fail_on_extra_files:
873
+ details = "\n".join(f" - {p}" for p in result.extra_paths)
874
+ out.text(f"❌ Extra files (present locally, absent remotely):\n{details}")
875
+ exit_code = 1
876
+ else:
877
+ out.warning(
878
+ f"{len(result.extra_paths)} local file(s) do not exist on the remote repo. "
879
+ "Use --fail-on-extra-files for details."
880
+ )
881
+
882
+ verified_location = result.verified_path
883
+
884
+ if exit_code != 0:
885
+ out.error(
886
+ f"Verification failed for '{repo_id}' ({repo_type.value}) in {verified_location}.\n Revision: {result.revision}"
887
+ )
888
+ raise click.exceptions.Exit(code=exit_code)
889
+
890
+ out.result(
891
+ f"Verified {result.checked_count} file(s) for {repo_type.value} '{repo_id}'. All checksums match.",
892
+ repo_id=repo_id,
893
+ repo_type=repo_type.value,
894
+ checked=result.checked_count,
895
+ path=str(verified_location),
896
+ )
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/collections.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import enum
17
+ from typing import Annotated, get_args
18
+
19
+ from huggingface_hub.hf_api import CollectionItemType_T, CollectionSort_T
20
+
21
+ from ._cli_utils import LimitOpt, TokenOpt, get_hf_api, typer_factory
22
+ from ._framework import Argument, Option
23
+ from ._output import _dataclass_to_dict, out
24
+
25
+
26
+ # Build enums dynamically from Literal types to avoid duplication
27
+ _COLLECTION_ITEM_TYPES = get_args(CollectionItemType_T)
28
+ CollectionItemType = enum.Enum("CollectionItemType", {t: t for t in _COLLECTION_ITEM_TYPES}, type=str) # type: ignore[misc]
29
+
30
+ _COLLECTION_SORT_OPTIONS = get_args(CollectionSort_T)
31
+ CollectionSort = enum.Enum("CollectionSort", {s: s for s in _COLLECTION_SORT_OPTIONS}, type=str) # type: ignore[misc]
32
+
33
+
34
+ collections_cli = typer_factory(help="Interact with collections on the Hub.")
35
+
36
+
37
+ @collections_cli.command(
38
+ "list | ls",
39
+ examples=[
40
+ "hf collections ls",
41
+ "hf collections ls --owner nvidia",
42
+ "hf collections ls --item models/teknium/OpenHermes-2.5-Mistral-7B --limit 10",
43
+ ],
44
+ )
45
+ def collections_ls(
46
+ owner: Annotated[
47
+ str | None,
48
+ Option(help="Filter by owner username or organization."),
49
+ ] = None,
50
+ item: Annotated[
51
+ str | None,
52
+ Option(
53
+ help='Filter collections containing a specific item (e.g., "models/gpt2", "datasets/squad", "papers/2311.12983").'
54
+ ),
55
+ ] = None,
56
+ sort: Annotated[
57
+ CollectionSort | None,
58
+ Option(help="Sort results by last modified, trending, or upvotes."),
59
+ ] = None,
60
+ limit: LimitOpt = 10,
61
+ token: TokenOpt = None,
62
+ ) -> None:
63
+ """List collections on the Hub."""
64
+ api = get_hf_api(token=token)
65
+ sort_key = sort.value if sort else None
66
+ results = [
67
+ _dataclass_to_dict(collection)
68
+ for collection in api.list_collections(
69
+ owner=owner,
70
+ item=item,
71
+ sort=sort_key, # type: ignore[arg-type]
72
+ limit=limit,
73
+ )
74
+ ]
75
+ out.table(results)
76
+
77
+
78
+ @collections_cli.command(
79
+ "info",
80
+ examples=[
81
+ "hf collections info username/my-collection-slug",
82
+ ],
83
+ )
84
+ def collections_info(
85
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
86
+ token: TokenOpt = None,
87
+ ) -> None:
88
+ """Get info about a collection on the Hub."""
89
+ api = get_hf_api(token=token)
90
+ collection = api.get_collection(collection_slug)
91
+ out.dict(collection)
92
+
93
+
94
+ @collections_cli.command(
95
+ "create",
96
+ examples=[
97
+ 'hf collections create "My Models"',
98
+ 'hf collections create "My Models" --description "A collection of my favorite models" --private',
99
+ 'hf collections create "Org Collection" --namespace my-org',
100
+ ],
101
+ )
102
+ def collections_create(
103
+ title: Annotated[str, Argument(help="The title of the collection.")],
104
+ namespace: Annotated[
105
+ str | None,
106
+ Option(help="The namespace (username or organization). Defaults to the authenticated user."),
107
+ ] = None,
108
+ description: Annotated[
109
+ str | None,
110
+ Option(help="A description for the collection (max 150 characters)."),
111
+ ] = None,
112
+ private: Annotated[
113
+ bool,
114
+ Option(help="Create a private collection."),
115
+ ] = False,
116
+ exists_ok: Annotated[
117
+ bool,
118
+ Option(help="Do not raise an error if the collection already exists."),
119
+ ] = False,
120
+ token: TokenOpt = None,
121
+ ) -> None:
122
+ """Create a new collection on the Hub."""
123
+ api = get_hf_api(token=token)
124
+ collection = api.create_collection(
125
+ title=title,
126
+ namespace=namespace,
127
+ description=description,
128
+ private=private,
129
+ exists_ok=exists_ok,
130
+ )
131
+ out.result("Collection created", slug=collection.slug, url=collection.url)
132
+
133
+
134
+ @collections_cli.command(
135
+ "update",
136
+ examples=[
137
+ 'hf collections update username/my-collection --title "New Title"',
138
+ 'hf collections update username/my-collection --description "Updated description"',
139
+ "hf collections update username/my-collection --private --theme green",
140
+ ],
141
+ )
142
+ def collections_update(
143
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
144
+ title: Annotated[
145
+ str | None,
146
+ Option(help="The new title for the collection."),
147
+ ] = None,
148
+ description: Annotated[
149
+ str | None,
150
+ Option(help="The new description for the collection (max 150 characters)."),
151
+ ] = None,
152
+ position: Annotated[
153
+ int | None,
154
+ Option(help="The new position of the collection in the owner's list."),
155
+ ] = None,
156
+ private: Annotated[
157
+ bool | None,
158
+ Option(help="Whether the collection should be private."),
159
+ ] = None,
160
+ theme: Annotated[
161
+ str | None,
162
+ Option(help="The theme color for the collection (e.g., 'green', 'blue')."),
163
+ ] = None,
164
+ token: TokenOpt = None,
165
+ ) -> None:
166
+ """Update a collection's metadata on the Hub."""
167
+ api = get_hf_api(token=token)
168
+ collection = api.update_collection_metadata(
169
+ collection_slug=collection_slug,
170
+ title=title,
171
+ description=description,
172
+ position=position,
173
+ private=private,
174
+ theme=theme,
175
+ )
176
+ out.result("Collection updated", slug=collection.slug, url=collection.url)
177
+
178
+
179
+ @collections_cli.command(
180
+ "delete",
181
+ examples=[
182
+ "hf collections delete username/my-collection",
183
+ "hf collections delete username/my-collection --missing-ok",
184
+ ],
185
+ )
186
+ def collections_delete(
187
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
188
+ missing_ok: Annotated[
189
+ bool,
190
+ Option(help="Do not raise an error if the collection doesn't exist."),
191
+ ] = False,
192
+ token: TokenOpt = None,
193
+ ) -> None:
194
+ """Delete a collection from the Hub."""
195
+ api = get_hf_api(token=token)
196
+ api.delete_collection(collection_slug, missing_ok=missing_ok)
197
+ out.result("Collection deleted", slug=collection_slug)
198
+
199
+
200
+ @collections_cli.command(
201
+ "add-item",
202
+ examples=[
203
+ "hf collections add-item username/my-collection moonshotai/kimi-k2 model",
204
+ 'hf collections add-item username/my-collection Qwen/DeepPlanning dataset --note "Useful dataset"',
205
+ "hf collections add-item username/my-collection Tongyi-MAI/Z-Image space",
206
+ ],
207
+ )
208
+ def collections_add_item(
209
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
210
+ item_id: Annotated[str, Argument(help="The ID of the item to add (repo_id for repos, paper ID for papers).")],
211
+ item_type: Annotated[
212
+ CollectionItemType,
213
+ Argument(help="The type of item (model, dataset, space, paper, collection, or bucket)."),
214
+ ],
215
+ note: Annotated[
216
+ str | None,
217
+ Option(help="A note to attach to the item (max 500 characters)."),
218
+ ] = None,
219
+ exists_ok: Annotated[
220
+ bool,
221
+ Option(help="Do not raise an error if the item is already in the collection."),
222
+ ] = False,
223
+ token: TokenOpt = None,
224
+ ) -> None:
225
+ """Add an item to a collection."""
226
+ api = get_hf_api(token=token)
227
+ collection = api.add_collection_item(
228
+ collection_slug=collection_slug,
229
+ item_id=item_id,
230
+ item_type=item_type.value, # type: ignore[arg-type]
231
+ note=note,
232
+ exists_ok=exists_ok,
233
+ )
234
+ out.result("Item added to collection", slug=collection_slug, url=collection.url)
235
+
236
+
237
+ @collections_cli.command(
238
+ "update-item",
239
+ examples=[
240
+ 'hf collections update-item username/my-collection ITEM_OBJECT_ID --note "Updated note"',
241
+ "hf collections update-item username/my-collection ITEM_OBJECT_ID --position 0",
242
+ ],
243
+ )
244
+ def collections_update_item(
245
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
246
+ item_object_id: Annotated[
247
+ str,
248
+ Argument(help="The ID of the item in the collection (from 'item_object_id' field, not the repo_id)."),
249
+ ],
250
+ note: Annotated[
251
+ str | None,
252
+ Option(help="A new note for the item (max 500 characters)."),
253
+ ] = None,
254
+ position: Annotated[
255
+ int | None,
256
+ Option(help="The new position of the item in the collection."),
257
+ ] = None,
258
+ token: TokenOpt = None,
259
+ ) -> None:
260
+ """Update an item in a collection."""
261
+ api = get_hf_api(token=token)
262
+ api.update_collection_item(
263
+ collection_slug=collection_slug,
264
+ item_object_id=item_object_id,
265
+ note=note,
266
+ position=position,
267
+ )
268
+ out.result("Item updated in collection", slug=collection_slug)
269
+
270
+
271
+ @collections_cli.command("delete-item")
272
+ def collections_delete_item(
273
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
274
+ item_object_id: Annotated[
275
+ str,
276
+ Argument(
277
+ help="The ID of the item in the collection (retrieved from `item_object_id` field returned by 'hf collections info'."
278
+ ),
279
+ ],
280
+ missing_ok: Annotated[
281
+ bool,
282
+ Option(help="Do not raise an error if the item doesn't exist."),
283
+ ] = False,
284
+ token: TokenOpt = None,
285
+ ) -> None:
286
+ """Delete an item from a collection."""
287
+ api = get_hf_api(token=token)
288
+ api.delete_collection_item(
289
+ collection_slug=collection_slug,
290
+ item_object_id=item_object_id,
291
+ missing_ok=missing_ok,
292
+ )
293
+ out.result("Item deleted from collection", slug=collection_slug)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/datasets.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import enum
17
+ from typing import Annotated, get_args
18
+
19
+ import click
20
+
21
+ from huggingface_hub._dataset_viewer import execute_raw_sql_query
22
+ from huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundError
23
+ from huggingface_hub.hf_api import DatasetSort_T, ExpandDatasetProperty_T
24
+ from huggingface_hub.repocard import DatasetCard
25
+
26
+ from ._cli_utils import (
27
+ REPO_LIST_DEFAULT_LIMIT,
28
+ AuthorOpt,
29
+ FilterOpt,
30
+ LimitOpt,
31
+ RevisionOpt,
32
+ SearchOpt,
33
+ TokenOpt,
34
+ get_hf_api,
35
+ make_expand_properties_parser,
36
+ typer_factory,
37
+ )
38
+ from ._file_listing import list_repo_files_cmd
39
+ from ._framework import Argument, Option
40
+ from ._output import _dataclass_to_dict, out
41
+
42
+
43
+ _EXPAND_PROPERTIES = sorted(get_args(ExpandDatasetProperty_T))
44
+ _SORT_OPTIONS = get_args(DatasetSort_T)
45
+ DatasetSortEnum = enum.Enum("DatasetSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
46
+
47
+
48
+ ExpandOpt = Annotated[
49
+ str | None,
50
+ Option(
51
+ 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)}.",
52
+ callback=make_expand_properties_parser(_EXPAND_PROPERTIES),
53
+ ),
54
+ ]
55
+
56
+
57
+ datasets_cli = typer_factory(help="Interact with datasets on the Hub.")
58
+
59
+
60
+ @datasets_cli.command(
61
+ "list | ls",
62
+ examples=[
63
+ "hf datasets ls",
64
+ "hf datasets ls --sort downloads --limit 10",
65
+ 'hf datasets ls --search "code"',
66
+ "hf datasets ls --filter benchmark:official",
67
+ "hf datasets ls HuggingFaceFW/fineweb",
68
+ "hf datasets ls HuggingFaceFW/fineweb -R",
69
+ "hf datasets ls HuggingFaceFW/fineweb --tree -h",
70
+ ],
71
+ )
72
+ def datasets_ls(
73
+ repo_id: Annotated[
74
+ str | None,
75
+ Argument(help="Dataset ID (e.g. `username/repo-name`) to list files from. If omitted, lists datasets."),
76
+ ] = None,
77
+ search: SearchOpt = None,
78
+ author: AuthorOpt = None,
79
+ filter: FilterOpt = None,
80
+ sort: Annotated[
81
+ DatasetSortEnum | None,
82
+ Option(help="Sort results."),
83
+ ] = None,
84
+ limit: LimitOpt = REPO_LIST_DEFAULT_LIMIT,
85
+ expand: ExpandOpt = None,
86
+ human_readable: Annotated[
87
+ bool,
88
+ Option("--human-readable", "-h", help="Show sizes in human readable format (only for listing files)."),
89
+ ] = False,
90
+ as_tree: Annotated[
91
+ bool,
92
+ Option("--tree", help="List files in tree format (only for listing files)."),
93
+ ] = False,
94
+ recursive: Annotated[
95
+ bool,
96
+ Option("--recursive", "-R", help="List files recursively (only for listing files)."),
97
+ ] = False,
98
+ revision: RevisionOpt = None,
99
+ token: TokenOpt = None,
100
+ ) -> None:
101
+ """List datasets on the Hub, or files in a dataset repo.
102
+
103
+ When called with no argument, lists datasets on the Hub.
104
+ When called with a dataset ID, lists files in that dataset repo.
105
+ """
106
+ if repo_id is not None:
107
+ if search is not None:
108
+ raise click.BadParameter("Cannot use --search when listing files.")
109
+ if author is not None:
110
+ raise click.BadParameter("Cannot use --author when listing files.")
111
+ if filter is not None:
112
+ raise click.BadParameter("Cannot use --filter when listing files.")
113
+ if sort is not None:
114
+ raise click.BadParameter("Cannot use --sort when listing files.")
115
+ if limit != REPO_LIST_DEFAULT_LIMIT:
116
+ raise click.BadParameter("Cannot use --limit when listing files.")
117
+ if expand is not None:
118
+ raise click.BadParameter("Cannot use --expand when listing files.")
119
+ return list_repo_files_cmd(
120
+ repo_id=repo_id,
121
+ repo_type="dataset",
122
+ human_readable=human_readable,
123
+ as_tree=as_tree,
124
+ recursive=recursive,
125
+ revision=revision,
126
+ token=token,
127
+ )
128
+
129
+ if as_tree:
130
+ raise click.BadParameter("Cannot use --tree when listing datasets.")
131
+ if recursive:
132
+ raise click.BadParameter("Cannot use --recursive when listing datasets.")
133
+ if human_readable:
134
+ raise click.BadParameter("Cannot use --human-readable when listing datasets.")
135
+ if revision is not None:
136
+ raise click.BadParameter("Cannot use --revision when listing datasets.")
137
+
138
+ api = get_hf_api(token=token)
139
+ sort_key = sort.value if sort else None
140
+ results = [
141
+ _dataclass_to_dict(dataset_info)
142
+ for dataset_info in api.list_datasets(
143
+ filter=filter,
144
+ author=author,
145
+ search=search,
146
+ sort=sort_key,
147
+ limit=limit,
148
+ expand=expand, # type: ignore
149
+ )
150
+ ]
151
+ out.table(results)
152
+
153
+
154
+ @datasets_cli.command(
155
+ "leaderboard",
156
+ examples=[
157
+ "hf datasets leaderboard SWE-bench/SWE-bench_Verified",
158
+ "hf datasets leaderboard SWE-bench/SWE-bench_Verified --limit 5 --format json",
159
+ "hf datasets ls --filter benchmark:official # list available leaderboards",
160
+ ],
161
+ )
162
+ def datasets_leaderboard(
163
+ dataset_id: Annotated[str, Argument(help="The benchmark dataset ID (e.g. `SWE-bench/SWE-bench_Verified`).")],
164
+ limit: LimitOpt = 20,
165
+ token: TokenOpt = None,
166
+ ) -> None:
167
+ """List model scores from a dataset leaderboard. This command helps find the best models for a task or compare models by benchmark scores. Use 'hf datasets ls --filter benchmark:official' to list available leaderboards."""
168
+ api = get_hf_api(token=token)
169
+ leaderboard = api.get_dataset_leaderboard(repo_id=dataset_id)
170
+ results = [_dataclass_to_dict(entry) for entry in leaderboard[:limit]]
171
+ out.table(
172
+ results,
173
+ headers=["rank", "model_id", "value", "source"],
174
+ id_key="model_id",
175
+ )
176
+ out.hint("Use 'hf datasets ls --filter benchmark:official' to list available leaderboards.")
177
+ if leaderboard:
178
+ out.hint(f"Use 'hf models info {leaderboard[0].model_id}' to get details about a model.")
179
+
180
+
181
+ @datasets_cli.command(
182
+ "info",
183
+ examples=[
184
+ "hf datasets info HuggingFaceFW/fineweb",
185
+ "hf datasets info my-dataset --expand downloads,likes,tags",
186
+ ],
187
+ )
188
+ def datasets_info(
189
+ dataset_id: Annotated[str, Argument(help="The dataset ID (e.g. `username/repo-name`).")],
190
+ revision: RevisionOpt = None,
191
+ expand: ExpandOpt = None,
192
+ token: TokenOpt = None,
193
+ ) -> None:
194
+ """Get info about a dataset on the Hub."""
195
+ api = get_hf_api(token=token)
196
+ try:
197
+ info = api.dataset_info(repo_id=dataset_id, revision=revision, expand=expand) # type: ignore
198
+ except RepositoryNotFoundError as e:
199
+ raise CLIError(f"Dataset '{dataset_id}' not found.") from e
200
+ except RevisionNotFoundError as e:
201
+ raise CLIError(f"Revision '{revision}' not found on '{dataset_id}'.") from e
202
+ out.dict(info)
203
+
204
+
205
+ @datasets_cli.command(
206
+ "parquet",
207
+ examples=[
208
+ "hf datasets parquet cfahlgren1/hub-stats",
209
+ "hf datasets parquet cfahlgren1/hub-stats --subset models",
210
+ "hf datasets parquet cfahlgren1/hub-stats --split train",
211
+ "hf datasets parquet cfahlgren1/hub-stats --format json",
212
+ ],
213
+ )
214
+ def datasets_parquet(
215
+ dataset_id: Annotated[str, Argument(help="The dataset ID (e.g. `username/repo-name`).")],
216
+ subset: Annotated[str | None, Option("--subset", help="Filter parquet entries by subset/config.")] = None,
217
+ split: Annotated[str | None, Option(help="Filter parquet entries by split.")] = None,
218
+ token: TokenOpt = None,
219
+ ) -> None:
220
+ """List parquet file URLs available for a dataset."""
221
+ api = get_hf_api(token=token)
222
+ entries = api.list_dataset_parquet_files(repo_id=dataset_id, config=subset)
223
+ filtered = [entry for entry in entries if split is None or entry.split == split]
224
+ results = [
225
+ {"subset": entry.config, "split": entry.split, "url": entry.url, "size": entry.size} for entry in filtered
226
+ ]
227
+ out.table(results, headers=["subset", "split", "url", "size"], id_key="url")
228
+
229
+
230
+ @datasets_cli.command(
231
+ "sql",
232
+ examples=[
233
+ "hf datasets sql \"SELECT COUNT(*) AS rows FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet')\"",
234
+ "hf datasets sql \"SELECT * FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet') LIMIT 5\" --format json",
235
+ ],
236
+ )
237
+ def datasets_sql(
238
+ sql: Annotated[str, Argument(help="Raw SQL query to execute.")],
239
+ token: TokenOpt = None,
240
+ ) -> None:
241
+ """Execute a raw SQL query with DuckDB against dataset parquet URLs."""
242
+ try:
243
+ result = execute_raw_sql_query(sql_query=sql, token=token)
244
+ except ImportError as e:
245
+ raise CLIError(str(e)) from e
246
+ out.table(result)
247
+
248
+
249
+ @datasets_cli.command(
250
+ "card",
251
+ examples=[
252
+ "hf datasets card HuggingFaceFW/fineweb",
253
+ "hf datasets card HuggingFaceFW/fineweb --metadata",
254
+ "hf datasets card HuggingFaceFW/fineweb --metadata --format json",
255
+ "hf datasets card HuggingFaceFW/fineweb --text",
256
+ ],
257
+ )
258
+ def datasets_card(
259
+ dataset_id: Annotated[str, Argument(help="The dataset ID (e.g. `username/repo-name`).")],
260
+ metadata: Annotated[bool, Option("--metadata", help="Output only the metadata from the card.")] = False,
261
+ text: Annotated[bool, Option("--text", help="Output only the text body (no metadata).")] = False,
262
+ token: TokenOpt = None,
263
+ ) -> None:
264
+ """Get the dataset card (README) for a dataset on the Hub."""
265
+ if metadata and text:
266
+ raise CLIError("--metadata and --text are mutually exclusive.")
267
+ card = DatasetCard.load(dataset_id, token=token)
268
+ if metadata:
269
+ out.dict(card.data.to_dict())
270
+ elif text:
271
+ out.text(card.text)
272
+ else:
273
+ out.text(card.content)
274
+ out.hint(f"Use `hf datasets card {dataset_id} --metadata` to extract only the card metadata.")
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/discussions.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sys
18
+ from pathlib import Path
19
+ from typing import Annotated
20
+
21
+ import click
22
+
23
+ from huggingface_hub import constants
24
+
25
+ from ._cli_utils import (
26
+ AuthorOpt,
27
+ LimitOpt,
28
+ RepoIdArg,
29
+ RepoType,
30
+ RepoTypeOpt,
31
+ TokenOpt,
32
+ get_hf_api,
33
+ typer_factory,
34
+ )
35
+ from ._framework import Argument, Option
36
+ from ._output import _dataclass_to_dict, out
37
+
38
+
39
+ class DiscussionStatus(str, enum.Enum):
40
+ open = "open"
41
+ closed = "closed"
42
+ merged = "merged"
43
+ draft = "draft"
44
+ all = "all"
45
+
46
+
47
+ class DiscussionKind(str, enum.Enum):
48
+ all = "all"
49
+ discussion = "discussion"
50
+ pull_request = "pull_request"
51
+
52
+
53
+ # "merged" and "draft" are valid Discussion statuses but the Hub API filter
54
+ # (DiscussionStatusFilter) only accepts "all", "open", "closed". When the user
55
+ # asks for merged/draft we fetch with api_status=None (i.e. all) and filter
56
+ # client-side.
57
+ _CLIENT_SIDE_STATUSES = {"merged", "draft"}
58
+
59
+
60
+ DiscussionNumArg = Annotated[
61
+ int,
62
+ Argument(
63
+ help="The discussion or pull request number.",
64
+ min=1,
65
+ ),
66
+ ]
67
+
68
+
69
+ def _read_body(body: str | None, body_file: Path | None) -> str | None:
70
+ """Resolve body text from --body or --body-file (supports '-' for stdin)."""
71
+ if body is not None and body_file is not None:
72
+ raise click.BadParameter("Cannot use both --body and --body-file.")
73
+ if body_file is not None:
74
+ if str(body_file) == "-":
75
+ return sys.stdin.read()
76
+ return body_file.read_text(encoding="utf-8")
77
+ return body
78
+
79
+
80
+ discussions_cli = typer_factory(help="Manage discussions and pull requests on the Hub.")
81
+
82
+
83
+ @discussions_cli.command(
84
+ "list | ls",
85
+ examples=[
86
+ "hf discussions list username/my-model",
87
+ "hf discussions list username/my-model --kind pull_request --status merged",
88
+ "hf discussions list username/my-dataset --type dataset --status closed",
89
+ "hf discussions list username/my-model --author alice --format json",
90
+ ],
91
+ )
92
+ def discussion_list(
93
+ repo_id: RepoIdArg,
94
+ status: Annotated[
95
+ DiscussionStatus,
96
+ Option(
97
+ "-s",
98
+ "--status",
99
+ help="Filter by status (open, closed, merged, draft, all).",
100
+ ),
101
+ ] = DiscussionStatus.open,
102
+ kind: Annotated[
103
+ DiscussionKind,
104
+ Option(
105
+ "-k",
106
+ "--kind",
107
+ help="Filter by kind (discussion, pull_request, all).",
108
+ ),
109
+ ] = DiscussionKind.all,
110
+ author: AuthorOpt = None,
111
+ limit: LimitOpt = 30,
112
+ repo_type: RepoTypeOpt = RepoType.model,
113
+ token: TokenOpt = None,
114
+ ) -> None:
115
+ """List discussions and pull requests on a repo."""
116
+ api = get_hf_api(token=token)
117
+
118
+ api_status: constants.DiscussionStatusFilter | None
119
+ if status == DiscussionStatus.open:
120
+ api_status = "open"
121
+ elif status == DiscussionStatus.closed:
122
+ api_status = "closed"
123
+ else:
124
+ api_status = None
125
+
126
+ api_discussion_type: constants.DiscussionTypeFilter | None
127
+ if kind == DiscussionKind.all:
128
+ api_discussion_type = None
129
+ else:
130
+ api_discussion_type = kind.value # type: ignore[assignment]
131
+
132
+ discussions = []
133
+ for d in api.get_repo_discussions(
134
+ repo_id=repo_id,
135
+ author=author,
136
+ discussion_type=api_discussion_type,
137
+ discussion_status=api_status,
138
+ repo_type=repo_type.value,
139
+ ):
140
+ if status.value in _CLIENT_SIDE_STATUSES and d.status != status.value:
141
+ continue
142
+ discussions.append(d)
143
+ if len(discussions) >= limit:
144
+ break
145
+
146
+ items = [_dataclass_to_dict(d) for d in discussions]
147
+ out.table(
148
+ items,
149
+ headers=["num", "title", "is_pull_request", "status", "author", "created_at"],
150
+ id_key="num",
151
+ )
152
+
153
+
154
+ @discussions_cli.command(
155
+ "info",
156
+ examples=[
157
+ "hf discussions info username/my-model 5",
158
+ "hf discussions info username/my-model 5 --format json",
159
+ ],
160
+ )
161
+ def discussion_info(
162
+ repo_id: RepoIdArg,
163
+ num: DiscussionNumArg,
164
+ repo_type: RepoTypeOpt = RepoType.model,
165
+ token: TokenOpt = None,
166
+ ) -> None:
167
+ """Get info about a discussion or pull request."""
168
+ api = get_hf_api(token=token)
169
+ details = api.get_discussion_details(
170
+ repo_id=repo_id,
171
+ discussion_num=num,
172
+ repo_type=repo_type.value,
173
+ )
174
+ out.dict(details)
175
+
176
+
177
+ @discussions_cli.command(
178
+ "create",
179
+ examples=[
180
+ 'hf discussions create username/my-model --title "Bug report"',
181
+ 'hf discussions create username/my-model --title "Feature request" --body "Please add X"',
182
+ 'hf discussions create username/my-model --title "Fix typo" --pull-request',
183
+ 'hf discussions create username/my-dataset --type dataset --title "Data quality issue"',
184
+ ],
185
+ )
186
+ def discussion_create(
187
+ repo_id: RepoIdArg,
188
+ title: Annotated[
189
+ str,
190
+ Option(
191
+ "--title",
192
+ help="The title of the discussion or pull request.",
193
+ ),
194
+ ],
195
+ body: Annotated[
196
+ str | None,
197
+ Option(
198
+ "--body",
199
+ help="The description (supports Markdown).",
200
+ ),
201
+ ] = None,
202
+ body_file: Annotated[
203
+ Path | None,
204
+ Option(
205
+ "--body-file",
206
+ help="Read the description from a file. Use '-' for stdin.",
207
+ ),
208
+ ] = None,
209
+ pull_request: Annotated[
210
+ bool,
211
+ Option(
212
+ "--pull-request",
213
+ "--pr",
214
+ help="Create a pull request instead of a discussion.",
215
+ ),
216
+ ] = False,
217
+ repo_type: RepoTypeOpt = RepoType.model,
218
+ token: TokenOpt = None,
219
+ ) -> None:
220
+ """Create a new discussion or pull request on a repo."""
221
+ description = _read_body(body, body_file)
222
+ api = get_hf_api(token=token)
223
+ discussion = api.create_discussion(
224
+ repo_id=repo_id,
225
+ title=title,
226
+ description=description,
227
+ repo_type=repo_type.value,
228
+ pull_request=pull_request,
229
+ )
230
+ kind = "pull request" if pull_request else "discussion"
231
+ ref = f"refs/pr/{discussion.num}" if pull_request else None
232
+ out.result(f"Created {kind} #{discussion.num} on {repo_id}", num=discussion.num, url=discussion.url, ref=ref)
233
+
234
+
235
+ @discussions_cli.command(
236
+ "comment",
237
+ examples=[
238
+ 'hf discussions comment username/my-model 5 --body "Thanks for reporting!"',
239
+ 'hf discussions comment username/my-model 5 --body "LGTM!"',
240
+ ],
241
+ )
242
+ def discussion_comment(
243
+ repo_id: RepoIdArg,
244
+ num: DiscussionNumArg,
245
+ body: Annotated[
246
+ str | None,
247
+ Option(
248
+ "--body",
249
+ help="The comment text (supports Markdown).",
250
+ ),
251
+ ] = None,
252
+ body_file: Annotated[
253
+ Path | None,
254
+ Option(
255
+ "--body-file",
256
+ help="Read the comment from a file. Use '-' for stdin.",
257
+ ),
258
+ ] = None,
259
+ repo_type: RepoTypeOpt = RepoType.model,
260
+ token: TokenOpt = None,
261
+ ) -> None:
262
+ """Comment on a discussion or pull request."""
263
+ comment = _read_body(body, body_file)
264
+ if comment is None:
265
+ raise click.BadParameter("Either --body or --body-file is required.")
266
+ api = get_hf_api(token=token)
267
+ api.comment_discussion(
268
+ repo_id=repo_id,
269
+ discussion_num=num,
270
+ comment=comment,
271
+ repo_type=repo_type.value,
272
+ )
273
+ out.result(f"Commented on #{num} in {repo_id}", num=num, repo=repo_id)
274
+
275
+
276
+ @discussions_cli.command(
277
+ "edit",
278
+ examples=[
279
+ 'hf discussions edit username/my-model 5 abc123 --body "Updated comment."',
280
+ "hf discussions edit username/my-model 5 abc123 --body-file fixed.md",
281
+ ],
282
+ )
283
+ def discussion_edit(
284
+ repo_id: RepoIdArg,
285
+ num: DiscussionNumArg,
286
+ comment_id: Annotated[
287
+ str,
288
+ Argument(
289
+ help="The ID of the comment to edit (see 'hf discussions info ... --format json').",
290
+ ),
291
+ ],
292
+ body: Annotated[
293
+ str | None,
294
+ Option(
295
+ "--body",
296
+ help="The new comment text (supports Markdown).",
297
+ ),
298
+ ] = None,
299
+ body_file: Annotated[
300
+ Path | None,
301
+ Option(
302
+ "--body-file",
303
+ help="Read the new comment from a file. Use '-' for stdin.",
304
+ ),
305
+ ] = None,
306
+ repo_type: RepoTypeOpt = RepoType.model,
307
+ token: TokenOpt = None,
308
+ ) -> None:
309
+ """Edit an existing comment on a discussion or pull request."""
310
+ new_content = _read_body(body, body_file)
311
+ if new_content is None:
312
+ raise click.BadParameter("Either --body or --body-file is required.")
313
+ api = get_hf_api(token=token)
314
+ api.edit_discussion_comment(
315
+ repo_id=repo_id,
316
+ discussion_num=num,
317
+ comment_id=comment_id,
318
+ new_content=new_content,
319
+ repo_type=repo_type.value,
320
+ )
321
+ out.result(f"Edited comment {comment_id} on #{num} in {repo_id}", num=num, repo=repo_id, comment_id=comment_id)
322
+
323
+
324
+ @discussions_cli.command(
325
+ "close",
326
+ examples=[
327
+ "hf discussions close username/my-model 5",
328
+ 'hf discussions close username/my-model 5 --comment "Closing as resolved."',
329
+ ],
330
+ )
331
+ def discussion_close(
332
+ repo_id: RepoIdArg,
333
+ num: DiscussionNumArg,
334
+ comment: Annotated[
335
+ str | None,
336
+ Option(
337
+ "--comment",
338
+ help="An optional comment to post when closing.",
339
+ ),
340
+ ] = None,
341
+ yes: Annotated[
342
+ bool,
343
+ Option(
344
+ "--yes",
345
+ "-y",
346
+ help="Skip confirmation prompt.",
347
+ ),
348
+ ] = False,
349
+ repo_type: RepoTypeOpt = RepoType.model,
350
+ token: TokenOpt = None,
351
+ ) -> None:
352
+ """Close a discussion or pull request."""
353
+ out.confirm(f"Close #{num} on '{repo_id}'?", yes=yes)
354
+ api = get_hf_api(token=token)
355
+ api.change_discussion_status(
356
+ repo_id=repo_id,
357
+ discussion_num=num,
358
+ new_status="closed",
359
+ comment=comment,
360
+ repo_type=repo_type.value,
361
+ )
362
+ out.result(f"Closed #{num} in {repo_id}", num=num, repo=repo_id)
363
+
364
+
365
+ @discussions_cli.command(
366
+ "reopen",
367
+ examples=[
368
+ "hf discussions reopen username/my-model 5",
369
+ 'hf discussions reopen username/my-model 5 --comment "Reopening for further investigation."',
370
+ ],
371
+ )
372
+ def discussion_reopen(
373
+ repo_id: RepoIdArg,
374
+ num: DiscussionNumArg,
375
+ comment: Annotated[
376
+ str | None,
377
+ Option(
378
+ "--comment",
379
+ help="An optional comment to post when reopening.",
380
+ ),
381
+ ] = None,
382
+ yes: Annotated[
383
+ bool,
384
+ Option(
385
+ "--yes",
386
+ "-y",
387
+ help="Skip confirmation prompt.",
388
+ ),
389
+ ] = False,
390
+ repo_type: RepoTypeOpt = RepoType.model,
391
+ token: TokenOpt = None,
392
+ ) -> None:
393
+ """Reopen a closed discussion or pull request."""
394
+ out.confirm(f"Reopen #{num} on '{repo_id}'?", yes=yes)
395
+ api = get_hf_api(token=token)
396
+ api.change_discussion_status(
397
+ repo_id=repo_id,
398
+ discussion_num=num,
399
+ new_status="open",
400
+ comment=comment,
401
+ repo_type=repo_type.value,
402
+ )
403
+ out.result(f"Reopened #{num} in {repo_id}", num=num, repo=repo_id)
404
+
405
+
406
+ @discussions_cli.command(
407
+ "rename",
408
+ examples=[
409
+ 'hf discussions rename username/my-model 5 "Updated title"',
410
+ ],
411
+ )
412
+ def discussion_rename(
413
+ repo_id: RepoIdArg,
414
+ num: DiscussionNumArg,
415
+ new_title: Annotated[
416
+ str,
417
+ Argument(
418
+ help="The new title.",
419
+ ),
420
+ ],
421
+ repo_type: RepoTypeOpt = RepoType.model,
422
+ token: TokenOpt = None,
423
+ ) -> None:
424
+ """Rename a discussion or pull request."""
425
+ api = get_hf_api(token=token)
426
+ api.rename_discussion(
427
+ repo_id=repo_id,
428
+ discussion_num=num,
429
+ new_title=new_title,
430
+ repo_type=repo_type.value,
431
+ )
432
+ out.result(f"Renamed #{num} in {repo_id}", num=num, repo=repo_id, title=new_title)
433
+
434
+
435
+ @discussions_cli.command(
436
+ "merge",
437
+ examples=[
438
+ "hf discussions merge username/my-model 5",
439
+ 'hf discussions merge username/my-model 5 --comment "Merging, thanks!"',
440
+ ],
441
+ )
442
+ def discussion_merge(
443
+ repo_id: RepoIdArg,
444
+ num: DiscussionNumArg,
445
+ comment: Annotated[
446
+ str | None,
447
+ Option(
448
+ "--comment",
449
+ help="An optional comment to post when merging.",
450
+ ),
451
+ ] = None,
452
+ yes: Annotated[
453
+ bool,
454
+ Option(
455
+ "--yes",
456
+ "-y",
457
+ help="Skip confirmation prompt.",
458
+ ),
459
+ ] = False,
460
+ repo_type: RepoTypeOpt = RepoType.model,
461
+ token: TokenOpt = None,
462
+ ) -> None:
463
+ """Merge a pull request."""
464
+ out.confirm(f"Merge #{num} on '{repo_id}'?", yes=yes)
465
+ api = get_hf_api(token=token)
466
+ api.merge_pull_request(
467
+ repo_id=repo_id,
468
+ discussion_num=num,
469
+ comment=comment,
470
+ repo_type=repo_type.value,
471
+ )
472
+ out.result(f"Merged #{num} in {repo_id}", num=num, repo=repo_id)
473
+
474
+
475
+ @discussions_cli.command(
476
+ "diff",
477
+ examples=[
478
+ "hf discussions diff username/my-model 5",
479
+ ],
480
+ )
481
+ def discussion_diff(
482
+ repo_id: RepoIdArg,
483
+ num: DiscussionNumArg,
484
+ repo_type: RepoTypeOpt = RepoType.model,
485
+ token: TokenOpt = None,
486
+ ) -> None:
487
+ """Show the diff of a pull request."""
488
+ api = get_hf_api(token=token)
489
+ details = api.get_discussion_details(
490
+ repo_id=repo_id,
491
+ discussion_num=num,
492
+ repo_type=repo_type.value,
493
+ )
494
+ if details.diff:
495
+ out.text(details.diff)
496
+ else:
497
+ out.text("No diff available.")
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/download.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import warnings
17
+ from typing import Annotated
18
+
19
+ from huggingface_hub import constants
20
+ from huggingface_hub._snapshot_download import snapshot_download
21
+ from huggingface_hub.errors import CLIError
22
+ from huggingface_hub.file_download import DryRunFileInfo, hf_hub_download
23
+ from huggingface_hub.utils import _format_size, parse_hf_uri
24
+
25
+ from ._cli_utils import RepoIdArg, RepoType, RepoTypeOptionalOpt, RevisionOpt, TokenOpt
26
+ from ._framework import Argument, Option
27
+ from ._output import out
28
+
29
+
30
+ DOWNLOAD_EXAMPLES = [
31
+ "hf download meta-llama/Llama-3.2-1B-Instruct",
32
+ "hf download meta-llama/Llama-3.2-1B-Instruct config.json tokenizer.json",
33
+ 'hf download meta-llama/Llama-3.2-1B-Instruct --include "*.safetensors" --exclude "*.bin"',
34
+ "hf download meta-llama/Llama-3.2-1B-Instruct --local-dir ./models/llama",
35
+ "hf download HuggingFaceM4/FineVision art/ --repo-type dataset",
36
+ "hf download hf://datasets/HuggingFaceH4/ultrachat_200k",
37
+ ]
38
+
39
+
40
+ def download(
41
+ repo_id: RepoIdArg,
42
+ filenames: Annotated[
43
+ list[str] | None,
44
+ Argument(
45
+ help="Files to download (e.g. `config.json`, `data/metadata.jsonl`).",
46
+ ),
47
+ ] = None,
48
+ repo_type: RepoTypeOptionalOpt = None,
49
+ revision: RevisionOpt = None,
50
+ include: Annotated[
51
+ list[str] | None,
52
+ Option(
53
+ help="Glob patterns to include from files to download. eg: *.json",
54
+ ),
55
+ ] = None,
56
+ exclude: Annotated[
57
+ list[str] | None,
58
+ Option(
59
+ help="Glob patterns to exclude from files to download.",
60
+ ),
61
+ ] = None,
62
+ cache_dir: Annotated[
63
+ str | None,
64
+ Option(
65
+ help="Directory where to save files.",
66
+ ),
67
+ ] = None,
68
+ local_dir: Annotated[
69
+ str | None,
70
+ Option(
71
+ 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.",
72
+ ),
73
+ ] = None,
74
+ force_download: Annotated[
75
+ bool,
76
+ Option(
77
+ help="If True, the files will be downloaded even if they are already cached.",
78
+ ),
79
+ ] = False,
80
+ dry_run: Annotated[
81
+ bool,
82
+ Option(
83
+ help="If True, perform a dry run without actually downloading the file.",
84
+ ),
85
+ ] = False,
86
+ token: TokenOpt = None,
87
+ max_workers: Annotated[
88
+ int,
89
+ Option(
90
+ help="Maximum number of workers to use for downloading files. Default is 8.",
91
+ ),
92
+ ] = 8,
93
+ ) -> None:
94
+ """Download files from the Hub."""
95
+ if local_dir is not None and cache_dir is not None:
96
+ raise CLIError(
97
+ "Cannot use both `--local-dir` and `--cache-dir` at the same time. "
98
+ "Use `--cache-dir` (or set the HF_HOME environment variable) for shared caching, "
99
+ "or `--local-dir` for a one-off download to a specific directory."
100
+ )
101
+
102
+ # `repo_id` may be a plain repo id or an `hf://` URI (e.g. `hf://datasets/my-org/my-dataset@v1.0/data/`).
103
+ # When a URI is provided, it is authoritative for the repo type, revision and (optionally) file path,
104
+ # so explicit `--repo-type` / `--revision` options are forbidden alongside it.
105
+ # We branch on the `hf://` prefix (the user's *intent*) rather than on whether the string parses as a
106
+ # valid URI: a malformed URI then surfaces a precise `HfUriError` (formatted globally in `cli/_errors.py`)
107
+ # instead of silently falling through to the plain-repo-id path and failing later with an opaque error.
108
+ if repo_id.startswith(constants.HF_PROTOCOL):
109
+ if repo_type is not None:
110
+ raise CLIError(f"'--repo-type' cannot be used with an 'hf://' URI ('{repo_id}').")
111
+ if revision is not None:
112
+ raise CLIError(f"'--revision' cannot be used with an 'hf://' URI ('{repo_id}').")
113
+ uri = parse_hf_uri(repo_id)
114
+ if uri.is_bucket:
115
+ raise CLIError("Buckets are not supported by `hf download`. Use `hf sync` instead.")
116
+ # The URI parser strips trailing slashes, but `hf download` uses a trailing '/' to denote a subfolder
117
+ # download (e.g. `data/` -> `data/**`). Re-append it when the URI explicitly ended with '/' so a folder
118
+ # URI keeps routing through the subfolder code path below.
119
+ path_in_repo = uri.path_in_repo
120
+ if path_in_repo and repo_id.endswith("/"):
121
+ path_in_repo += "/"
122
+ repo_id, repo_type_str, revision = uri.id, uri.type, uri.revision
123
+ if path_in_repo:
124
+ if filenames:
125
+ raise CLIError(
126
+ f"Cannot combine a file path in the hf:// URI ('{path_in_repo}') with positional filenames {filenames}."
127
+ )
128
+ filenames = [path_in_repo]
129
+ else:
130
+ repo_type_str = (repo_type or RepoType.model).value
131
+
132
+ def run_download() -> str | DryRunFileInfo | list[DryRunFileInfo]:
133
+ filenames_list = filenames if filenames is not None else []
134
+
135
+ # Separate subfolder patterns (ending with '/') from regular filenames
136
+ # Subfolders like "art/" are converted to include patterns like "art/**"
137
+ subfolders = [f for f in filenames_list if f.endswith("/")]
138
+ subfolder_patterns = [f"{f.rstrip('/')}/**" for f in subfolders]
139
+ regular_filenames = [f for f in filenames_list if not f.endswith("/")]
140
+
141
+ # Error if subfolder patterns are combined with --include/--exclude
142
+ # Guide user to use --include instead of subfolder argument
143
+ if len(subfolder_patterns) > 0:
144
+ if include is not None and len(include) > 0:
145
+ raise CLIError(
146
+ f"Cannot combine subfolder argument ('{subfolders[0]}') with `--include`. "
147
+ f'Please use `--include "{subfolders[0]}*"` instead.'
148
+ )
149
+ if exclude is not None and len(exclude) > 0:
150
+ raise CLIError(
151
+ f"Cannot combine subfolder argument ('{subfolders[0]}') with `--exclude`. "
152
+ f'Please use `--include "{subfolders[0]}*"` with `--exclude` instead.'
153
+ )
154
+
155
+ # Warn user if patterns are ignored (only if regular filenames are provided)
156
+ if len(regular_filenames) > 0:
157
+ if include is not None and len(include) > 0:
158
+ warnings.warn("Ignoring `--include` since filenames have been explicitly set.")
159
+ if exclude is not None and len(exclude) > 0:
160
+ warnings.warn("Ignoring `--exclude` since filenames have been explicitly set.")
161
+
162
+ # Single file to download (not a subfolder): use `hf_hub_download`
163
+ if len(regular_filenames) == 1 and len(subfolder_patterns) == 0:
164
+ return hf_hub_download(
165
+ repo_id=repo_id,
166
+ repo_type=repo_type_str,
167
+ revision=revision,
168
+ filename=regular_filenames[0],
169
+ cache_dir=cache_dir,
170
+ force_download=force_download,
171
+ token=token,
172
+ local_dir=local_dir,
173
+ library_name="huggingface-cli",
174
+ dry_run=dry_run,
175
+ )
176
+
177
+ # Otherwise: use `snapshot_download` to ensure all files comes from same revision
178
+ if len(regular_filenames) == 0 and len(subfolder_patterns) == 0:
179
+ # No filenames provided: use include/exclude patterns
180
+ allow_patterns = include
181
+ ignore_patterns = exclude
182
+ else:
183
+ # Combine regular filenames and subfolder patterns as allow_patterns
184
+ allow_patterns = regular_filenames + subfolder_patterns
185
+ ignore_patterns = None
186
+
187
+ return snapshot_download(
188
+ repo_id=repo_id,
189
+ repo_type=repo_type_str,
190
+ revision=revision,
191
+ allow_patterns=allow_patterns,
192
+ ignore_patterns=ignore_patterns,
193
+ force_download=force_download,
194
+ cache_dir=cache_dir,
195
+ token=token,
196
+ local_dir=local_dir,
197
+ library_name="huggingface-cli",
198
+ max_workers=max_workers,
199
+ dry_run=dry_run,
200
+ )
201
+
202
+ def _print_result(result: str | DryRunFileInfo | list[DryRunFileInfo]) -> None:
203
+ if isinstance(result, str):
204
+ out.result("Downloaded", path=result)
205
+ return
206
+
207
+ # Print dry run info
208
+ if isinstance(result, DryRunFileInfo):
209
+ result = [result]
210
+ will_download = [r for r in result if r.will_download]
211
+ total_size = (
212
+ None if any(r.file_size is None for r in will_download) else sum(r.file_size or 0 for r in will_download)
213
+ )
214
+ out.text(
215
+ f"[dry-run] Will download {len(will_download)} files"
216
+ f" (out of {len(result)})"
217
+ f" totalling {_format_size(total_size) if total_size is not None else 'an unknown size'}."
218
+ )
219
+ items = [
220
+ {
221
+ "file": info.filename,
222
+ "size": _format_size(info.file_size) if info.will_download and info.file_size is not None else "-",
223
+ }
224
+ for info in sorted(result, key=lambda x: x.filename)
225
+ ]
226
+ out.table(items)
227
+
228
+ _print_result(run_download())
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/extensions.py ADDED
@@ -0,0 +1,766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 enum import Enum
26
+ from html import unescape
27
+ from pathlib import Path
28
+ from typing import Annotated, Literal
29
+
30
+ import click
31
+ import httpx2
32
+
33
+ from huggingface_hub.errors import CLIError, CLIExtensionInstallError, ConfirmationError
34
+ from huggingface_hub.utils import get_session, logging
35
+
36
+ from ._cli_utils import typer_factory
37
+ from ._framework import Argument, Option
38
+ from ._output import out
39
+
40
+
41
+ DEFAULT_EXTENSION_OWNER = "huggingface"
42
+ EXTENSIONS_ROOT = Path("~/.local/share/hf/extensions")
43
+ MANIFEST_FILENAME = "manifest.json"
44
+ EXTENSIONS_HELP = (
45
+ "Manage hf CLI extensions.\n\n"
46
+ "Security Warning: extensions are third-party executables or Python packages. "
47
+ "Install only from sources you trust."
48
+ )
49
+ extensions_cli = typer_factory(help=EXTENSIONS_HELP)
50
+ _EXTENSIONS_GITHUB_TOPIC = "hf-extension"
51
+ _EXTENSIONS_DOWNLOAD_TIMEOUT = 10
52
+ _EXTENSIONS_PIP_INSTALL_TIMEOUT = 300
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+
57
+ class _GitHubRateLimitError(CLIError):
58
+ """The GitHub API refused the request because a rate limit is exhausted.
59
+
60
+ Distinguished from other `CLIError`s because it says nothing about the extension being handled:
61
+ it is not worth retrying on the next one, and it must not be mistaken for an install failure.
62
+ """
63
+
64
+
65
+ class _ExtensionUpdateStatus(str, Enum):
66
+ UPDATED = "updated"
67
+ UP_TO_DATE = "up_to_date"
68
+ SKIPPED = "skipped"
69
+
70
+
71
+ @dataclass
72
+ class ExtensionManifest:
73
+ owner: str
74
+ repo: str
75
+ repo_id: str
76
+ short_name: str
77
+ executable_path: str
78
+ type: Literal["binary", "python"]
79
+ installed_at: datetime
80
+ description: str | None = None
81
+ commit_sha: str | None = None
82
+
83
+ @classmethod
84
+ def load(cls, path: Path) -> "ExtensionManifest":
85
+ manifest_path = path / MANIFEST_FILENAME
86
+ if not manifest_path.is_file():
87
+ raise CLIError(f"Manifest file not found at {manifest_path}. Your extension may be corrupted.")
88
+ data = json.loads(manifest_path.read_text())
89
+ # Ignore keys not in the dataclass (e.g. fields dropped since the manifest was written).
90
+ data = {key: value for key, value in data.items() if key in cls.__dataclass_fields__}
91
+ data["installed_at"] = datetime.fromisoformat(data["installed_at"])
92
+ return ExtensionManifest(**data)
93
+
94
+ def save(self, path: Path) -> None:
95
+ manifest_path = path / MANIFEST_FILENAME
96
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
97
+ data = asdict(self)
98
+ data["installed_at"] = self.installed_at.isoformat()
99
+ manifest_path.write_text(json.dumps(data, indent=2, sort_keys=True))
100
+
101
+
102
+ @extensions_cli.command(
103
+ "install",
104
+ examples=[
105
+ "hf extensions install hf-claude",
106
+ "hf extensions install hanouticelina/hf-claude",
107
+ "hf extensions install alvarobartt/hf-mem",
108
+ ],
109
+ )
110
+ def extension_install(
111
+ ctx: click.Context,
112
+ repo_id: Annotated[
113
+ str,
114
+ Argument(help="GitHub extension repository in `[OWNER/]hf-<name>` format."),
115
+ ],
116
+ force: Annotated[bool, Option("--force", help="Overwrite if already installed.")] = False,
117
+ ) -> None:
118
+ """Install an extension from a public GitHub repository.
119
+
120
+ Security warning: this installs a third-party executable or Python package.
121
+ Install only from sources you trust.
122
+ """
123
+ owner, repo_name, short_name = _normalize_repo_id(repo_id)
124
+ root_ctx = ctx.find_root()
125
+ reserved_commands = set(getattr(root_ctx.command, "commands", {}).keys())
126
+ if short_name in reserved_commands:
127
+ raise CLIError(
128
+ f"Cannot install extension '{short_name}' because it conflicts with an existing `hf {short_name}` command."
129
+ )
130
+
131
+ extension_dir = _get_extension_dir(short_name)
132
+ if extension_dir.exists() and not force:
133
+ raise CLIError(f"Extension '{short_name}' is already installed. Use --force to overwrite.")
134
+
135
+ if not _github_repo_exists(owner=owner, repo_name=repo_name):
136
+ raise CLIError(f"GitHub repository '{owner}/{repo_name}' not found. It must exist and be public.")
137
+ if extension_dir.exists():
138
+ # --force reinstall: only remove the previous install once the repo is known to exist.
139
+ shutil.rmtree(extension_dir)
140
+ manifest = _install_extension(owner=owner, repo_name=repo_name, short_name=short_name)
141
+ ext_type = manifest.type.capitalize()
142
+ out.result(
143
+ f"{ext_type} extension installed",
144
+ source=f"{owner}/{repo_name}",
145
+ command=f"hf {short_name}",
146
+ )
147
+ out.hint(f"Run it with: hf {short_name}")
148
+
149
+
150
+ @extensions_cli.command(
151
+ "update",
152
+ examples=[
153
+ "hf extensions update",
154
+ "hf extensions update hf-claude",
155
+ "hf extensions update alvarobartt/hf-mem",
156
+ ],
157
+ )
158
+ def extension_update(
159
+ name: Annotated[
160
+ str | None,
161
+ Argument(
162
+ help=(
163
+ "Extension to update (with or without `hf-` prefix, optionally as `OWNER/hf-<name>`). "
164
+ "If omitted, all installed extensions are checked and the outdated ones are updated."
165
+ ),
166
+ ),
167
+ ] = None,
168
+ ) -> None:
169
+ """Update installed extension(s) to their latest version."""
170
+ if name is not None:
171
+ manifest = _load_installed_extension_for_update(name)
172
+ update_status = _update_installed_extension(manifest)
173
+ match update_status:
174
+ case _ExtensionUpdateStatus.UPDATED:
175
+ out.result("Extension updated", name=manifest.short_name, source=manifest.repo_id)
176
+ case _ExtensionUpdateStatus.UP_TO_DATE:
177
+ out.result(f"Extension '{manifest.short_name}' is already up to date", name=manifest.short_name)
178
+ case _ExtensionUpdateStatus.SKIPPED:
179
+ pass # warning already emitted by _update_installed_extension
180
+ return
181
+
182
+ manifests = _list_installed_extensions()
183
+ if not manifests:
184
+ out.warning("No extensions installed.")
185
+ out.hint("Install one with: hf extensions install <repo_id>")
186
+ return
187
+
188
+ updated = []
189
+ up_to_date = []
190
+ for manifest in manifests:
191
+ out.log(f"Checking '{manifest.short_name}' ({manifest.repo_id})...")
192
+ try:
193
+ update_status = _update_installed_extension(manifest)
194
+ except _GitHubRateLimitError:
195
+ # Every remaining extension would fail the same way, so stop rather than repeat it.
196
+ raise
197
+ except Exception as error:
198
+ # Keep updating the other extensions even if one fails.
199
+ out.warning(f"Could not update '{manifest.short_name}' ({manifest.repo_id}): {error}. Skipping.")
200
+ continue
201
+ match update_status:
202
+ case _ExtensionUpdateStatus.UPDATED:
203
+ updated.append(manifest.short_name)
204
+ case _ExtensionUpdateStatus.UP_TO_DATE:
205
+ up_to_date.append(manifest.short_name)
206
+ case _ExtensionUpdateStatus.SKIPPED:
207
+ pass # warning already emitted by _update_installed_extension
208
+ out.result(
209
+ "Extensions update complete",
210
+ updated=", ".join(updated) if updated else None,
211
+ up_to_date=", ".join(up_to_date) if up_to_date else None,
212
+ )
213
+
214
+
215
+ @extensions_cli.command(
216
+ "exec",
217
+ context_settings={"allow_extra_args": True, "allow_interspersed_args": False, "ignore_unknown_options": True},
218
+ examples=[
219
+ "hf extensions exec claude -- --help",
220
+ "hf extensions exec claude --model zai-org/GLM-5",
221
+ ],
222
+ )
223
+ def extension_exec(
224
+ ctx: click.Context,
225
+ name: Annotated[
226
+ str,
227
+ Argument(help="Extension name (with or without `hf-` prefix)."),
228
+ ],
229
+ ) -> None:
230
+ """Execute an installed extension."""
231
+ short_name = _normalize_extension_name(name)
232
+ executable_path = _resolve_installed_executable_path(short_name)
233
+
234
+ if not executable_path.is_file():
235
+ raise CLIError(f"Extension '{short_name}' is not installed.")
236
+
237
+ exit_code = _execute_extension_binary(executable_path=executable_path, args=list(ctx.args))
238
+ raise click.exceptions.Exit(code=exit_code)
239
+
240
+
241
+ @extensions_cli.command("list | ls", examples=["hf extensions list"])
242
+ def extension_list() -> None:
243
+ """List installed extension commands."""
244
+ rows = [
245
+ {
246
+ "command": f"hf {manifest.short_name}",
247
+ "source": str(manifest.repo_id),
248
+ "type": str(manifest.type),
249
+ "installed": manifest.installed_at.strftime("%Y-%m-%d"),
250
+ "description": manifest.description,
251
+ }
252
+ for manifest in _list_installed_extensions()
253
+ ]
254
+ out.table(rows, id_key="command")
255
+
256
+
257
+ @extensions_cli.command("search", examples=["hf extensions search"])
258
+ def extension_search() -> None:
259
+ """Search extensions available on GitHub (tagged with 'hf-extension' topic)."""
260
+ response = _github_request(
261
+ "GET",
262
+ "https://api.github.com/search/repositories",
263
+ params={"q": f"topic:{_EXTENSIONS_GITHUB_TOPIC}", "sort": "stars", "order": "desc", "per_page": 100},
264
+ )
265
+ data = response.json()
266
+
267
+ installed = {m.short_name for m in _list_installed_extensions()}
268
+
269
+ rows = []
270
+ for repo in data.get("items", []):
271
+ short_name = repo["name"].removeprefix("hf-")
272
+ rows.append(
273
+ {
274
+ "name": short_name,
275
+ "repo": repo["full_name"],
276
+ "stars": repo.get("stargazers_count", 0),
277
+ "description": repo.get("description") or "",
278
+ "installed": "yes" if short_name in installed else "",
279
+ }
280
+ )
281
+
282
+ out.table(rows, id_key="repo")
283
+
284
+
285
+ @extensions_cli.command("remove | rm", examples=["hf extensions remove claude"])
286
+ def extension_remove(
287
+ name: Annotated[
288
+ str,
289
+ Argument(help="Extension name to remove (with or without `hf-` prefix)."),
290
+ ],
291
+ ) -> None:
292
+ """Remove an installed extension."""
293
+ short_name = _normalize_extension_name(name)
294
+ extension_dir = _get_extension_dir(short_name)
295
+
296
+ if not extension_dir.is_dir():
297
+ raise CLIError(f"Extension '{short_name}' is not installed.")
298
+
299
+ shutil.rmtree(extension_dir)
300
+ out.result("Extension removed", name=short_name)
301
+
302
+
303
+ ### HELPER FUNCTIONS
304
+
305
+
306
+ def _list_installed_extensions() -> list[ExtensionManifest]:
307
+ """Return manifests for all validly-installed extensions, sorted by directory name."""
308
+ root_dir = EXTENSIONS_ROOT.expanduser()
309
+ if not root_dir.is_dir():
310
+ return []
311
+ manifests = []
312
+ for extension_dir in sorted(root_dir.iterdir()):
313
+ if not extension_dir.is_dir() or not extension_dir.name.startswith("hf-"):
314
+ continue
315
+ try:
316
+ manifests.append(ExtensionManifest.load(extension_dir))
317
+ except Exception as e:
318
+ logger.debug(f"Failed to load manifest for extension '{extension_dir.name}': {e}")
319
+ continue
320
+ return manifests
321
+
322
+
323
+ def list_installed_extensions_for_help() -> list[tuple[str, str]]:
324
+ entries = []
325
+ for manifest in _list_installed_extensions():
326
+ tag = f"[extension {manifest.repo_id}]"
327
+ help_text = f"{manifest.description} {tag}" if manifest.description is not None else tag
328
+ entries.append((manifest.short_name, help_text))
329
+ return entries
330
+
331
+
332
+ def dispatch_unknown_top_level_extension(args: list[str], known_commands: set[str]) -> int | None:
333
+ if not args:
334
+ return None
335
+
336
+ command_name = args[0]
337
+ if command_name.startswith("-"):
338
+ return None
339
+ all_known = {a.strip() for cmd in known_commands for a in cmd.split("|")}
340
+ if command_name in all_known:
341
+ return None
342
+
343
+ try:
344
+ short_name = _validate_extension_short_name(command_name.removeprefix("hf-"), original_input=command_name)
345
+ except CLIError:
346
+ return None
347
+
348
+ executable_path: Path | None
349
+ try:
350
+ executable_path = _resolve_installed_executable_path(short_name)
351
+ except Exception:
352
+ executable_path = _auto_install_official_extension(short_name)
353
+
354
+ if executable_path is None or not executable_path.is_file():
355
+ return None
356
+
357
+ return _execute_extension_binary(executable_path=executable_path, args=list(args[1:]))
358
+
359
+
360
+ def _auto_install_official_extension(short_name: str) -> Path | None:
361
+ """Try to auto-install huggingface/hf-<name>. Returns executable path or None."""
362
+ owner, repo_name = DEFAULT_EXTENSION_OWNER, f"hf-{short_name}"
363
+ if _get_extension_dir(short_name).exists():
364
+ return None
365
+
366
+ # Every unknown `hf <command>` reaches this point, typos included, so the existence check must
367
+ # not spend REST API quota (see `_github_request`).
368
+ try:
369
+ if not _github_repo_exists(owner=owner, repo_name=repo_name):
370
+ return None
371
+ except Exception:
372
+ return None
373
+
374
+ try:
375
+ out.confirm(f"'{short_name}' is an official Hugging Face extension ({owner}/{repo_name}). Install it?")
376
+ except ConfirmationError:
377
+ return None
378
+ manifest = _install_extension(owner=owner, repo_name=repo_name, short_name=short_name)
379
+ return Path(manifest.executable_path).expanduser()
380
+
381
+
382
+ def _load_installed_extension_for_update(name: str) -> ExtensionManifest:
383
+ short_name = _normalize_extension_name(name)
384
+ extension_dir = _get_extension_dir(short_name)
385
+ if not extension_dir.is_dir():
386
+ owner, _, _ = name.strip().rpartition("/")
387
+ install_target = f"{owner}/hf-{short_name}" if owner else f"hf-{short_name}"
388
+ raise CLIError(
389
+ f"Extension '{short_name}' is not installed. Install it first with: hf extensions install {install_target}"
390
+ )
391
+ return ExtensionManifest.load(extension_dir)
392
+
393
+
394
+ def _update_installed_extension(manifest: ExtensionManifest) -> _ExtensionUpdateStatus:
395
+ owner, repo_name, short_name = manifest.owner, manifest.repo, manifest.short_name
396
+
397
+ try:
398
+ latest_sha = _fetch_latest_commit_sha(owner=owner, repo_name=repo_name)
399
+ except _GitHubRateLimitError:
400
+ # Says nothing about this extension in particular, so let the caller stop the whole run.
401
+ raise
402
+ except Exception as error:
403
+ out.warning(f"Could not check updates for '{short_name}' ({owner}/{repo_name}): {error}. Skipping.")
404
+ return _ExtensionUpdateStatus.SKIPPED
405
+
406
+ if latest_sha == manifest.commit_sha:
407
+ return _ExtensionUpdateStatus.UP_TO_DATE
408
+
409
+ _install_extension(owner=owner, repo_name=repo_name, short_name=short_name, commit_sha=latest_sha)
410
+ return _ExtensionUpdateStatus.UPDATED
411
+
412
+
413
+ def _install_extension(
414
+ *,
415
+ owner: str,
416
+ repo_name: str,
417
+ short_name: str,
418
+ commit_sha: str | None = None,
419
+ ) -> ExtensionManifest:
420
+ """Fetch and install an extension (binary or Python package), then persist its manifest.
421
+
422
+ Installs in place: an existing install is overwritten without being removed first, so a failed
423
+ update keeps the previous version working. A failed fresh install is cleaned up entirely.
424
+ """
425
+ extension_dir = _get_extension_dir(short_name)
426
+ fresh_install = not extension_dir.exists()
427
+ installed = False
428
+ try:
429
+ try:
430
+ binary = _fetch_remote_binary(owner=owner, repo_name=repo_name, short_name=short_name)
431
+ except Exception:
432
+ binary = None
433
+
434
+ if binary is not None:
435
+ if os.name == "nt":
436
+ raise CLIError(
437
+ f"'{owner}/{repo_name}' is a shell-script extension, which is not supported on Windows. "
438
+ "Only Python extensions can be installed on Windows."
439
+ )
440
+ executable_path = _install_binary_extension(
441
+ extension_dir=extension_dir, short_name=short_name, binary=binary
442
+ )
443
+ else:
444
+ executable_path = _install_python_extension(
445
+ extension_dir=extension_dir, owner=owner, repo_name=repo_name, short_name=short_name
446
+ )
447
+
448
+ if commit_sha is None:
449
+ # The extension itself is on disk by now, fetched from the CDN. The SHA only feeds update
450
+ # detection, so a failure here must not throw the install away: without it, the next
451
+ # `hf extensions update` sees no known SHA, considers the extension outdated and reinstalls.
452
+ try:
453
+ commit_sha = _fetch_latest_commit_sha(owner=owner, repo_name=repo_name)
454
+ except Exception as error:
455
+ out.warning(f"Could not record a version for '{owner}/{repo_name}', installing anyway: {error}")
456
+
457
+ manifest = ExtensionManifest(
458
+ owner=owner,
459
+ repo=repo_name,
460
+ repo_id=f"{owner}/{repo_name}",
461
+ short_name=short_name,
462
+ executable_path=str(executable_path),
463
+ type="binary" if binary is not None else "python",
464
+ installed_at=datetime.now(timezone.utc),
465
+ description=_try_fetch_remote_description(owner=owner, repo_name=repo_name),
466
+ commit_sha=commit_sha,
467
+ )
468
+ manifest.save(extension_dir)
469
+ installed = True
470
+ return manifest
471
+ except CLIError:
472
+ raise
473
+ except subprocess.TimeoutExpired as e:
474
+ raise CLIExtensionInstallError(
475
+ f"Pip install timed out after {_EXTENSIONS_PIP_INSTALL_TIMEOUT}s for '{owner}/{repo_name}'. "
476
+ "See pip output above for details."
477
+ ) from e
478
+ except subprocess.CalledProcessError as e:
479
+ raise CLIExtensionInstallError(
480
+ f"Failed to install pip package from '{owner}/{repo_name}' (exit code {e.returncode}). "
481
+ "See pip output above for details."
482
+ ) from e
483
+ except Exception as e:
484
+ raise CLIExtensionInstallError(f"Failed to install extension from '{owner}/{repo_name}': {e}") from e
485
+ finally:
486
+ if not installed and fresh_install:
487
+ shutil.rmtree(extension_dir, ignore_errors=True)
488
+
489
+
490
+ def _fetch_latest_commit_sha(*, owner: str, repo_name: str) -> str:
491
+ """Fetch the latest commit SHA on the default branch, used to detect available updates.
492
+
493
+ The only REST API call left in the install and update paths. Raises on failure: callers decide
494
+ whether a missing SHA is fatal, and report the reason themselves.
495
+ """
496
+ response = _github_request(
497
+ "GET",
498
+ f"https://api.github.com/repos/{owner}/{repo_name}/commits/HEAD",
499
+ headers={"Accept": "application/vnd.github.sha"},
500
+ )
501
+ return response.text.strip()
502
+
503
+
504
+ def _fetch_remote_binary(*, owner: str, repo_name: str, short_name: str) -> bytes:
505
+ raw_url = f"https://raw.githubusercontent.com/{owner}/{repo_name}/HEAD/hf-{short_name}"
506
+ response = _github_request("GET", raw_url)
507
+ return response.content
508
+
509
+
510
+ def _install_binary_extension(*, extension_dir: Path, short_name: str, binary: bytes) -> Path:
511
+ extension_dir.mkdir(parents=True, exist_ok=True)
512
+ executable_path = extension_dir / _get_executable_name(short_name)
513
+ executable_path.write_bytes(binary)
514
+
515
+ if os.name != "nt":
516
+ os.chmod(executable_path, 0o755)
517
+
518
+ return executable_path
519
+
520
+
521
+ def _install_python_extension(*, extension_dir: Path, owner: str, repo_name: str, short_name: str) -> Path:
522
+ source_url = f"https://github.com/{owner}/{repo_name}/archive/HEAD.zip"
523
+ venv_dir = extension_dir / "venv"
524
+ venv_python = _get_venv_bin_path(venv_dir, "python.exe" if os.name == "nt" else "python")
525
+ uv_path = shutil.which("uv")
526
+
527
+ status = out.status()
528
+ if not venv_python.is_file():
529
+ status.update(f"Creating virtual environment in {venv_dir}")
530
+ extension_dir.mkdir(parents=True, exist_ok=True)
531
+ if uv_path:
532
+ subprocess.run([uv_path, "venv", str(venv_dir)], check=True)
533
+ else:
534
+ venv.EnvBuilder(with_pip=True).create(str(venv_dir))
535
+ status.done(f"Virtual environment created in {venv_dir}")
536
+
537
+ status.update(f"Installing package from {source_url}")
538
+ if uv_path:
539
+ # --reinstall: the source URL is the same for every commit, so cached data must be refreshed.
540
+ install_cmd = [uv_path, "pip", "install", "--reinstall", "--python", str(venv_python), source_url]
541
+ else:
542
+ install_cmd = [
543
+ str(venv_python),
544
+ "-m",
545
+ "pip",
546
+ "install",
547
+ "--disable-pip-version-check",
548
+ "--no-input",
549
+ "--force-reinstall",
550
+ source_url,
551
+ ]
552
+ subprocess.run(install_cmd, check=True, timeout=_EXTENSIONS_PIP_INSTALL_TIMEOUT)
553
+ status.done(f"Package installed from {source_url}")
554
+
555
+ executable_name = _get_executable_name(short_name)
556
+ venv_executable = _get_venv_bin_path(venv_dir, executable_name)
557
+ if not venv_executable.is_file():
558
+ raise CLIError(
559
+ f"Installed package from '{owner}/{repo_name}' does not expose the required console script "
560
+ f"'{executable_name}'."
561
+ )
562
+ return venv_executable.resolve()
563
+
564
+
565
+ _GITHUB_ABOUT_RE = re.compile(r'<meta name="description" content="([^"]*)"')
566
+
567
+
568
+ def _try_fetch_remote_description(owner: str, repo_name: str) -> str | None:
569
+ """Try to fetch project description either from:
570
+ - manifest.json
571
+ - pyproject.toml
572
+ - the repository's GitHub "About" field
573
+
574
+ Only best effort, no error handling.
575
+ """
576
+ base = f"https://raw.githubusercontent.com/{owner}/{repo_name}/HEAD"
577
+
578
+ # from manifest.json
579
+ try:
580
+ response = _github_request("GET", f"{base}/{MANIFEST_FILENAME}")
581
+ description = response.json().get("description")
582
+ if isinstance(description, str):
583
+ return description
584
+ except Exception:
585
+ pass
586
+
587
+ # from pyproject.toml
588
+ try:
589
+ response = _github_request("GET", f"{base}/pyproject.toml")
590
+
591
+ # Weak parser but ok for "best effort"
592
+ for line in response.text.splitlines():
593
+ line = line.strip()
594
+ if line.startswith("description"):
595
+ _, _, value = line.partition("=")
596
+ return value.strip().strip("\"'")
597
+ except Exception:
598
+ pass
599
+
600
+ # from the repo page's "About" field. Served by github.com, so it costs no REST API quota.
601
+ try:
602
+ response = _github_request("GET", f"https://github.com/{owner}/{repo_name}")
603
+ if (match := _GITHUB_ABOUT_RE.search(response.text)) is not None:
604
+ # GitHub renders "<about> - <owner>/<repo>", and unrelated boilerplate when About is empty.
605
+ content = unescape(match.group(1))
606
+ if (description := content.removesuffix(f" - {owner}/{repo_name}")) != content:
607
+ return description
608
+ except Exception:
609
+ pass
610
+
611
+ return None
612
+
613
+
614
+ def _get_extension_dir(short_name: str) -> Path:
615
+ # Callers validate at the parse boundary already; re-validate here as defense-in-depth since
616
+ # this path is rmtree'd on removal.
617
+ _validate_extension_short_name(short_name, original_input=short_name)
618
+ return EXTENSIONS_ROOT.expanduser() / f"hf-{short_name}"
619
+
620
+
621
+ def _github_request(
622
+ method: str, url: str, *, params: dict | None = None, headers: dict | None = None
623
+ ) -> httpx2.Response:
624
+ """Perform a GitHub request.
625
+
626
+ Shared by every GitHub/Raw fetch in this module so the timeout, redirect and rate-limit policy are
627
+ shared.
628
+
629
+ Unauthenticated `api.github.com` calls are capped per IP address, and that quota is shared with
630
+ everything else calling GitHub from the same network (NAT, VPN, CI egress). Remote refs are therefore
631
+ always addressed as `HEAD`, which GitHub resolves to the repo's default branch on
632
+ `raw.githubusercontent.com`, on the archive endpoint and on the REST API alike: no
633
+ `GET /repos/{owner}/{repo}` lookup is needed to discover the branch name.
634
+ """
635
+ response = get_session().request(
636
+ method,
637
+ url,
638
+ params=params,
639
+ headers=headers,
640
+ follow_redirects=True,
641
+ timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT,
642
+ )
643
+ # Primary limits report an exhausted quota, secondary ones only ask to back off.
644
+ if response.status_code in (403, 429) and (
645
+ response.headers.get("x-ratelimit-remaining") == "0" or "retry-after" in response.headers
646
+ ):
647
+ raise _GitHubRateLimitError(_rate_limit_message(response.headers))
648
+ response.raise_for_status()
649
+ return response
650
+
651
+
652
+ def _rate_limit_message(headers: httpx2.Headers) -> str:
653
+ """Message for a GitHub rate-limit rejection, built from the response headers.
654
+
655
+ The cap itself is deliberately not quoted: it depends on the endpoint (60/hour on the core API,
656
+ 10/minute on search), so only the wait is reported.
657
+
658
+ `retry-after` wins over `x-ratelimit-reset`: GitHub rides the primary window's reset timestamp on
659
+ every REST response, secondary rate limits included, so on a back-off it would point at an hourly
660
+ window that is not the one being enforced.
661
+ """
662
+ message = (
663
+ "GitHub API rate limit exceeded. Unauthenticated requests are capped per IP address, and that "
664
+ "quota is shared with anything else calling GitHub from your network."
665
+ )
666
+ if (retry_after := headers.get("retry-after")) is not None:
667
+ message += f" Retry in {retry_after}s."
668
+ elif (reset := headers.get("x-ratelimit-reset")) is not None:
669
+ try:
670
+ reset_at = datetime.fromtimestamp(int(reset), tz=timezone.utc).astimezone()
671
+ except (OverflowError, OSError, ValueError):
672
+ pass
673
+ else:
674
+ message += f" It resets at {reset_at:%H:%M:%S %Z}."
675
+ return message
676
+
677
+
678
+ def _github_repo_exists(*, owner: str, repo_name: str) -> bool:
679
+ """Whether a public GitHub repo exists.
680
+
681
+ Resolved against `github.com` rather than `GET /repos/{owner}/{repo}` to keep the check off the
682
+ metered REST API (see `_github_request`). Only a 404 answers `False`: any other failure is reported
683
+ as such, so callers never present an unreachable GitHub as a missing repo.
684
+ """
685
+ try:
686
+ _github_request("HEAD", f"https://github.com/{owner}/{repo_name}")
687
+ except httpx2.HTTPError as error:
688
+ if isinstance(error, httpx2.HTTPStatusError) and error.response.status_code == 404:
689
+ return False
690
+ raise CLIError(f"Could not reach GitHub to check whether '{owner}/{repo_name}' exists: {error}") from error
691
+ return True
692
+
693
+
694
+ def _get_executable_name(short_name: str) -> str:
695
+ name = f"hf-{short_name}"
696
+ if os.name == "nt":
697
+ name += ".exe"
698
+ return name
699
+
700
+
701
+ def _resolve_installed_executable_path(short_name: str) -> Path:
702
+ extension_dir = _get_extension_dir(short_name)
703
+ manifest = ExtensionManifest.load(extension_dir)
704
+ return Path(manifest.executable_path).expanduser()
705
+
706
+
707
+ def _get_venv_bin_path(venv_dir: Path, executable_name: str) -> Path:
708
+ if os.name == "nt":
709
+ return venv_dir / "Scripts" / executable_name
710
+ return venv_dir / "bin" / executable_name
711
+
712
+
713
+ _ALLOWED_EXTENSION_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
714
+
715
+
716
+ def _validate_extension_short_name(short_name: str, *, original_input: str) -> str:
717
+ name = short_name.strip()
718
+ if not name:
719
+ raise CLIError("Extension name cannot be empty.")
720
+ if any(sep in name for sep in ("/", "\\")):
721
+ raise CLIError(f"Invalid extension name '{original_input}'.")
722
+ if ".." in name or ":" in name:
723
+ raise CLIError(f"Invalid extension name '{original_input}'.")
724
+ if not _ALLOWED_EXTENSION_NAME.fullmatch(name):
725
+ raise CLIError(
726
+ f"Invalid extension name '{original_input}'. Allowed characters: letters, digits, '.', '_' and '-'."
727
+ )
728
+ return name
729
+
730
+
731
+ def _normalize_repo_id(repo_id: str) -> tuple[str, str, str]:
732
+ if "://" in repo_id:
733
+ raise CLIError("Only GitHub repositories in `[OWNER/]hf-<name>` format are supported.")
734
+
735
+ parts = repo_id.split("/")
736
+ if len(parts) == 1:
737
+ owner = DEFAULT_EXTENSION_OWNER
738
+ repo_name = parts[0]
739
+ elif len(parts) == 2 and all(parts):
740
+ owner, repo_name = parts
741
+ else:
742
+ raise CLIError(f"Expected `[OWNER/]REPO` format, got '{repo_id}'.")
743
+
744
+ if not repo_name.startswith("hf-"):
745
+ raise CLIError(f"Extension repository name must start with 'hf-', got '{repo_name}'.")
746
+
747
+ short_name = repo_name.removeprefix("hf-")
748
+ if not short_name:
749
+ raise CLIError("Invalid extension repository name 'hf-'.")
750
+ _validate_extension_short_name(short_name, original_input=repo_id)
751
+
752
+ return owner, repo_name, short_name
753
+
754
+
755
+ def _normalize_extension_name(name: str) -> str:
756
+ repo_name = name.strip().rsplit("/", 1)[-1]
757
+ return _validate_extension_short_name(repo_name.removeprefix("hf-"), original_input=name)
758
+
759
+
760
+ def _execute_extension_binary(executable_path: Path, args: list[str]) -> int:
761
+ try:
762
+ return subprocess.call([str(executable_path)] + args)
763
+ except OSError as e:
764
+ if os.name == "nt" or e.errno != errno.ENOEXEC:
765
+ raise
766
+ return subprocess.call(["sh", str(executable_path)] + args)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/hf.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
16
+ import sys
17
+ import traceback
18
+ from typing import Annotated, Any
19
+
20
+ import click
21
+
22
+ from huggingface_hub import __version__, constants
23
+ from huggingface_hub.cli._cli_utils import (
24
+ LazyHfCommand,
25
+ LazyHfGroup,
26
+ check_cli_update,
27
+ fallback_typer_group_factory,
28
+ typer_factory,
29
+ )
30
+ from huggingface_hub.cli._output import out
31
+ from huggingface_hub.utils import logging
32
+
33
+ from ._completion import _COMPLETE_VAR, InstallCompletionOpt, ShowCompletionOpt
34
+ from ._framework import Option
35
+
36
+
37
+ def _dispatch_unknown_top_level_extension(args: list[str], built_in_commands: set[str]) -> int | None:
38
+ from .extensions import dispatch_unknown_top_level_extension
39
+
40
+ return dispatch_unknown_top_level_extension(args, built_in_commands)
41
+
42
+
43
+ def _list_installed_extensions_for_help() -> list[tuple[str, str]]:
44
+ from .extensions import list_installed_extensions_for_help
45
+
46
+ return list_installed_extensions_for_help()
47
+
48
+
49
+ def check_skill_update() -> None:
50
+ from ._skills import check_skill_update as _check_skill_update
51
+
52
+ _check_skill_update()
53
+
54
+
55
+ app = typer_factory(
56
+ help="Hugging Face Hub CLI",
57
+ cls=fallback_typer_group_factory(
58
+ _dispatch_unknown_top_level_extension,
59
+ extra_commands_provider=_list_installed_extensions_for_help,
60
+ ),
61
+ )
62
+
63
+
64
+ def _version_callback(value: bool) -> None:
65
+ if value:
66
+ print(__version__)
67
+ raise click.exceptions.Exit()
68
+
69
+
70
+ def _skills_callback(value: bool) -> None:
71
+ if value:
72
+ from .skills import skills_preview
73
+
74
+ skills_preview()
75
+ raise click.exceptions.Exit()
76
+
77
+
78
+ @app.group_callback(invoke_without_command=True)
79
+ def app_callback(
80
+ version: Annotated[
81
+ bool | None, Option("-v", "--version", callback=_version_callback, is_eager=True, hidden=True)
82
+ ] = None,
83
+ skills: Annotated[
84
+ bool,
85
+ Option(
86
+ "--skills",
87
+ callback=_skills_callback,
88
+ is_eager=True,
89
+ help="Print the `hf-cli` SKILL.md to stdout (alias for `hf skills preview`).",
90
+ ),
91
+ ] = False,
92
+ install_completion: InstallCompletionOpt = False,
93
+ show_completion: ShowCompletionOpt = False,
94
+ ) -> None:
95
+ pass
96
+
97
+
98
+ _LAZY_COMMANDS: list[tuple[str, str, str, dict[str, Any]]] = [
99
+ ("sync", "buckets", "sync", {}),
100
+ ("cp", "_cp", "make_cp", {"examples_attribute": "CP_EXAMPLES", "is_factory": True}),
101
+ ("download", "download", "download", {"examples_attribute": "DOWNLOAD_EXAMPLES"}),
102
+ ("upload", "upload", "upload", {"examples_attribute": "UPLOAD_EXAMPLES"}),
103
+ ("env", "system", "env", {"topic": "help"}),
104
+ ("update", "system", "update", {"topic": "help"}),
105
+ ("version", "system", "version", {"topic": "help"}),
106
+ ("lfs-enable-largefiles", "lfs", "lfs_enable_largefiles", {"hidden": True}),
107
+ ("lfs-multipart-upload", "lfs", "lfs_multipart_upload", {"hidden": True}),
108
+ ]
109
+
110
+
111
+ _LAZY_GROUPS: list[tuple[str, str, str, dict[str, Any]]] = [
112
+ ("auth", "auth", "auth_cli", {}),
113
+ ("buckets", "buckets", "buckets_cli", {}),
114
+ ("cache", "cache", "cache_cli", {}),
115
+ ("collections", "collections", "collections_cli", {}),
116
+ ("datasets", "datasets", "datasets_cli", {}),
117
+ ("discussions", "discussions", "discussions_cli", {}),
118
+ ("jobs", "jobs", "jobs_cli", {}),
119
+ ("models", "models", "models_cli", {}),
120
+ ("papers", "papers", "papers_cli", {}),
121
+ ("repos", "repos", "repos_cli", {}),
122
+ ("sandbox", "sandbox", "sandbox_cli", {}),
123
+ ("skills", "skills", "skills_cli", {}),
124
+ ("spaces", "spaces", "spaces_cli", {}),
125
+ ("webhooks", "webhooks", "webhooks_cli", {}),
126
+ ("endpoints", "inference_endpoints", "ie_cli", {}),
127
+ ("extensions | ext", "extensions", "extensions_cli", {}),
128
+ ]
129
+
130
+ for name, module, attribute, extras in _LAZY_COMMANDS:
131
+ app.add_command(
132
+ LazyHfCommand(
133
+ name,
134
+ module=f"huggingface_hub.cli.{module}",
135
+ attribute=attribute,
136
+ **extras,
137
+ ),
138
+ name,
139
+ )
140
+
141
+ for name, module, attribute, extras in _LAZY_GROUPS:
142
+ app.add_command(
143
+ LazyHfGroup(
144
+ name,
145
+ module=f"huggingface_hub.cli.{module}",
146
+ attribute=attribute,
147
+ **extras,
148
+ ),
149
+ name,
150
+ )
151
+
152
+
153
+ def main():
154
+ # Shell-completion requests must stay fast and emit nothing but candidates:
155
+ # skip the startup work and let click handle the env var inside `app()`.
156
+ if _COMPLETE_VAR not in os.environ:
157
+ if not constants.HF_DEBUG:
158
+ logging.set_verbosity_info()
159
+ check_cli_update("huggingface_hub")
160
+ # Don't nag while the user is already managing skills, nor on `hf update` which handles the
161
+ # skill itself (it would print a redundant or contradictory hint before doing so).
162
+ if sys.argv[1:2] not in (["skills"], ["update"], ["--skills"]):
163
+ check_skill_update()
164
+
165
+ try:
166
+ # Click glob-expands args on Windows by default, even quoted ones like `--exclude "*.bin"`.
167
+ app(windows_expand_args=False)
168
+ except Exception as e:
169
+ from ._errors import format_known_exception
170
+
171
+ message = format_known_exception(e)
172
+ if message:
173
+ out.error(message)
174
+ if constants.HF_DEBUG:
175
+ traceback.print_exc()
176
+ else:
177
+ out.hint("set HF_DEBUG=1 as environment variable for full traceback.")
178
+ sys.exit(1)
179
+ raise
180
+
181
+
182
+ if __name__ == "__main__":
183
+ main()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/inference_endpoints.py ADDED
@@ -0,0 +1,940 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI commands for Hugging Face Inference Endpoints."""
2
+
3
+ import shlex
4
+ from typing import Annotated
5
+
6
+ import click
7
+
8
+ from huggingface_hub._inference_endpoints import (
9
+ InferenceEndpointHardware,
10
+ InferenceEndpointScalingMetric,
11
+ InferenceEndpointType,
12
+ _set_parallelism_in_image,
13
+ )
14
+ from huggingface_hub.errors import CLIError, HfHubHTTPError
15
+
16
+ from ._cli_utils import (
17
+ EnvFileOpt,
18
+ EnvOpt,
19
+ RevisionOpt,
20
+ SearchOpt,
21
+ SecretsFileOpt,
22
+ SecretsOpt,
23
+ SoftChoice,
24
+ TokenOpt,
25
+ get_hf_api,
26
+ parse_env_map,
27
+ typer_factory,
28
+ )
29
+ from ._framework import Argument, Option
30
+ from ._output import _dataclass_to_dict, out
31
+
32
+
33
+ ie_cli = typer_factory(help="Manage Hugging Face Inference Endpoints.")
34
+
35
+ catalog_app = typer_factory(help="Interact with the Inference Endpoints catalog.")
36
+
37
+
38
+ NameArg = Annotated[
39
+ str,
40
+ Argument(help="Endpoint name."),
41
+ ]
42
+ NameOpt = Annotated[
43
+ str | None,
44
+ Option(help="Endpoint name."),
45
+ ]
46
+
47
+ NamespaceOpt = Annotated[
48
+ str | None,
49
+ Option(
50
+ help="The namespace associated with the Inference Endpoint. Defaults to the current user's namespace.",
51
+ ),
52
+ ]
53
+
54
+ # Maps the CLI `--engine` values to the `model.image` variant keys of the API payload. `huggingface` and
55
+ # `huggingfaceNeuron` are left out on purpose: they are the managed Hugging Face images and take no image URL.
56
+ ENGINE_IMAGE_KEYS = {
57
+ "custom": "custom",
58
+ "hf-serve": "hfServe",
59
+ "llamacpp": "llamacpp",
60
+ "sglang": "sGLang",
61
+ "tei": "tei",
62
+ "tgi": "tgi",
63
+ "tgi-neuron": "tgiNeuron",
64
+ "vllm": "vLLM",
65
+ "vllm-neuron": "vLLMNeuron",
66
+ }
67
+
68
+ EngineOpt = Annotated[
69
+ str | None,
70
+ Option(
71
+ "--engine",
72
+ click_type=SoftChoice(list(ENGINE_IMAGE_KEYS)),
73
+ help="Managed engine image to run --custom-image with (e.g. 'vllm'). Defaults to an arbitrary container.",
74
+ ),
75
+ ]
76
+
77
+ HealthRouteOpt = Annotated[
78
+ str | None,
79
+ Option(
80
+ help="Health check route exposed by the container (e.g. '/health'). Requires --custom-image.",
81
+ ),
82
+ ]
83
+
84
+ PortOpt = Annotated[
85
+ int | None,
86
+ Option(
87
+ help="Port the container listens on (e.g. 30000). Requires --custom-image.",
88
+ ),
89
+ ]
90
+
91
+ TensorParallelSizeOpt = Annotated[
92
+ int | None,
93
+ Option(
94
+ "--tensor-parallel-size",
95
+ help="Number of accelerators to shard a single model copy across (vLLM and SGLang engines only).",
96
+ ),
97
+ ]
98
+
99
+ DataParallelSizeOpt = Annotated[
100
+ int | None,
101
+ Option(
102
+ "--data-parallel-size",
103
+ help="Number of model copies to run, one per accelerator (vLLM engine only).",
104
+ ),
105
+ ]
106
+
107
+
108
+ @ie_cli.command("list | ls", examples=["hf endpoints ls", "hf endpoints ls --namespace my-org"])
109
+ def ls(
110
+ namespace: NamespaceOpt = None,
111
+ token: TokenOpt = None,
112
+ ) -> None:
113
+ """Lists all Inference Endpoints for the given namespace."""
114
+ api = get_hf_api(token=token)
115
+ try:
116
+ endpoints = api.list_inference_endpoints(namespace=namespace, token=token)
117
+ except HfHubHTTPError as error:
118
+ out.error(f"Listing failed: {error}")
119
+ raise click.exceptions.Exit(code=error.response.status_code) from error
120
+
121
+ results = []
122
+ for endpoint in endpoints:
123
+ raw = endpoint.raw
124
+ status = raw.get("status", {})
125
+ model = raw.get("model", {})
126
+ compute = raw.get("compute", {})
127
+ provider = raw.get("provider", {})
128
+ results.append(
129
+ {
130
+ "name": raw.get("name", ""),
131
+ "model": model.get("repository", "") if isinstance(model, dict) else "",
132
+ "status": status.get("state", "") if isinstance(status, dict) else "",
133
+ "task": model.get("task", "") if isinstance(model, dict) else "",
134
+ "framework": model.get("framework", "") if isinstance(model, dict) else "",
135
+ "instance": compute.get("instanceType", "") if isinstance(compute, dict) else "",
136
+ "vendor": provider.get("vendor", "") if isinstance(provider, dict) else "",
137
+ "region": provider.get("region", "") if isinstance(provider, dict) else "",
138
+ }
139
+ )
140
+ out.table(results, id_key="name")
141
+
142
+
143
+ # A denylist like the Endpoints UI uses, so a new server-side status shows up instead of silently disappearing.
144
+ _UNDEPLOYABLE_STATUSES = {"deprecated", "not_available"}
145
+
146
+
147
+ def _is_deployable(hw: InferenceEndpointHardware) -> bool:
148
+ """Whether the namespace can deploy one replica on this hardware right now: usable status and enough quota."""
149
+ return (
150
+ hw.status not in _UNDEPLOYABLE_STATUSES and hw.max_accelerators - hw.used_accelerators >= hw.num_accelerators
151
+ )
152
+
153
+
154
+ @ie_cli.command(
155
+ "hardware",
156
+ examples=[
157
+ "hf endpoints hardware",
158
+ "hf endpoints hardware --vendor aws --accelerator gpu",
159
+ ],
160
+ )
161
+ def hardware(
162
+ namespace: NamespaceOpt = None,
163
+ vendor: Annotated[
164
+ str | None,
165
+ Option(help="Only show hardware hosted by this cloud provider (e.g. 'aws')."),
166
+ ] = None,
167
+ region: Annotated[
168
+ str | None,
169
+ Option(help="Only show hardware available in this cloud region (e.g. 'us-east-1')."),
170
+ ] = None,
171
+ accelerator: Annotated[
172
+ str | None,
173
+ Option(help="Only show hardware with this accelerator (e.g. 'cpu', 'gpu', 'neuron')."),
174
+ ] = None,
175
+ instance_type: Annotated[
176
+ str | None,
177
+ Option(help="Only show hardware of this instance type (e.g. 'nvidia-l4')."),
178
+ ] = None,
179
+ show_all: Annotated[
180
+ bool,
181
+ Option(
182
+ "-a",
183
+ "--all",
184
+ help="Also show hardware that cannot be deployed on right now (unavailable, deprecated or out of quota).",
185
+ ),
186
+ ] = False,
187
+ token: TokenOpt = None,
188
+ ) -> None:
189
+ """List the hardware available to deploy an Inference Endpoint on.
190
+
191
+ Only the hardware the namespace can deploy on right now is listed: a usable status, and enough accelerator
192
+ quota left for one replica. Use `--all` to list every combination the API returns.
193
+
194
+ Quota is per namespace, so pass the same `--namespace` you will pass to `hf endpoints deploy`. Prices are in
195
+ USD, per replica per hour.
196
+ """
197
+ api = get_hf_api(token=token)
198
+ hardware_list = api.list_inference_endpoints_hardware(namespace=namespace, token=token)
199
+
200
+ # Both sides lowercased: relying on the server's casing would turn a change into a silently empty result.
201
+ matching = [
202
+ hw
203
+ for hw in hardware_list
204
+ if (vendor is None or hw.vendor.lower() == vendor.lower())
205
+ and (region is None or hw.region.lower() == region.lower())
206
+ and (accelerator is None or hw.accelerator.lower() == accelerator.lower())
207
+ and (instance_type is None or hw.instance_type.lower() == instance_type.lower())
208
+ ]
209
+ visible = [hw for hw in matching if show_all or _is_deployable(hw)]
210
+ # Smallest size first per instance type; 'instance_size' can't be the key, 'x16' sorts before 'x2'.
211
+ visible.sort(key=lambda hw: (hw.vendor, hw.region, hw.accelerator, hw.instance_type, hw.num_accelerators))
212
+
213
+ # Add a quota column, keeping the rest of the dict whole since '--format json' emits it.
214
+ items = [_dataclass_to_dict(hw) | {"quota": f"{hw.used_accelerators}/{hw.max_accelerators}"} for hw in visible]
215
+ out.table(
216
+ items,
217
+ # Redundant and always-null columns are dropped here but stay in the items for '--format json'.
218
+ headers=[
219
+ "vendor",
220
+ "region",
221
+ "accelerator",
222
+ "instance_type",
223
+ "instance_size",
224
+ "memory_gb",
225
+ "gpu_memory_gb",
226
+ "price_per_hour",
227
+ "quota",
228
+ "status",
229
+ ],
230
+ id_key="id",
231
+ )
232
+ # The example must be one 'deploy' accepts, and with '--all' the first row may not be.
233
+ if (hw := next((hw for hw in visible if _is_deployable(hw)), None)) is not None:
234
+ out.hint(
235
+ f"Deploy on one of these, e.g.: hf endpoints deploy my-endpoint --repo <repo> --framework <framework> "
236
+ f"--vendor {hw.vendor} --region {hw.region} --accelerator {hw.accelerator} "
237
+ f"--instance-type {hw.instance_type} --instance-size {hw.instance_size}"
238
+ )
239
+ elif visible: # only reachable with '--all'
240
+ out.hint("None of these can be deployed on right now, see the QUOTA and STATUS columns.")
241
+ elif matching: # all matches were dropped as undeployable
242
+ out.hint("Use '--all' to also show hardware that cannot be deployed on right now.")
243
+ else:
244
+ # Nothing matched at all: a filter value is probably a typo, so name the ones that exist nowhere.
245
+ unknown = [
246
+ f"{flag} '{value}' (valid: {', '.join(sorted(valid))})"
247
+ for flag, value, valid in (
248
+ ("--vendor", vendor, {hw.vendor for hw in hardware_list}),
249
+ ("--region", region, {hw.region for hw in hardware_list}),
250
+ ("--accelerator", accelerator, {hw.accelerator for hw in hardware_list}),
251
+ ("--instance-type", instance_type, {hw.instance_type for hw in hardware_list}),
252
+ )
253
+ if value is not None and value.lower() not in {v.lower() for v in valid}
254
+ ]
255
+ out.hint(
256
+ f"No such hardware: {'; '.join(unknown)}."
257
+ if unknown
258
+ # Each value exists, they just never occur together.
259
+ else "No hardware matches all of these filters at once. Try dropping one."
260
+ )
261
+
262
+
263
+ @ie_cli.command(
264
+ name="deploy",
265
+ examples=[
266
+ "hf endpoints deploy my-endpoint --repo gpt2 --framework pytorch ...",
267
+ "hf endpoints deploy my-endpoint --repo openai/gpt-oss-120b --framework custom --engine vllm "
268
+ "--custom-image vllm/vllm-openai:v0.23.0 --tensor-parallel-size 8 ...",
269
+ ],
270
+ )
271
+ def deploy(
272
+ name: NameArg,
273
+ repo: Annotated[
274
+ str,
275
+ Option(
276
+ help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').",
277
+ ),
278
+ ],
279
+ framework: Annotated[
280
+ str,
281
+ Option(
282
+ help="The machine learning framework used for the model (e.g. 'vllm').",
283
+ ),
284
+ ],
285
+ accelerator: Annotated[
286
+ str,
287
+ Option(
288
+ help="The hardware accelerator to be used for inference (e.g. 'cpu').",
289
+ ),
290
+ ],
291
+ instance_size: Annotated[
292
+ str,
293
+ Option(
294
+ help="The size or type of the instance to be used for hosting the model (e.g. 'x4').",
295
+ ),
296
+ ],
297
+ instance_type: Annotated[
298
+ str,
299
+ Option(
300
+ help="The cloud instance type where the Inference Endpoint will be deployed (e.g. 'intel-icl').",
301
+ ),
302
+ ],
303
+ region: Annotated[
304
+ str,
305
+ Option(
306
+ help="The cloud region in which the Inference Endpoint will be created (e.g. 'us-east-1').",
307
+ ),
308
+ ],
309
+ vendor: Annotated[
310
+ str,
311
+ Option(
312
+ help="The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. 'aws').",
313
+ ),
314
+ ],
315
+ *,
316
+ namespace: NamespaceOpt = None,
317
+ task: Annotated[
318
+ str | None,
319
+ Option(
320
+ help="The task on which to deploy the model (e.g. 'text-classification').",
321
+ ),
322
+ ] = None,
323
+ token: TokenOpt = None,
324
+ min_replica: Annotated[
325
+ int,
326
+ Option(
327
+ help="The minimum number of replicas (instances) to keep running for the Inference Endpoint.",
328
+ ),
329
+ ] = 1,
330
+ max_replica: Annotated[
331
+ int,
332
+ Option(
333
+ help="The maximum number of replicas (instances) to scale to for the Inference Endpoint.",
334
+ ),
335
+ ] = 1,
336
+ scale_to_zero_timeout: Annotated[
337
+ int | None,
338
+ Option(
339
+ help="The duration in minutes before an inactive endpoint is scaled to zero.",
340
+ ),
341
+ ] = None,
342
+ scaling_metric: Annotated[
343
+ InferenceEndpointScalingMetric | None,
344
+ Option(
345
+ help="The metric reference for scaling.",
346
+ ),
347
+ ] = None,
348
+ scaling_threshold: Annotated[
349
+ float | None,
350
+ Option(
351
+ help="The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.",
352
+ ),
353
+ ] = None,
354
+ revision: RevisionOpt = None,
355
+ custom_image: Annotated[
356
+ str | None,
357
+ Option(
358
+ "--custom-image",
359
+ help="Docker image URL for the container to run (e.g. 'nexagi/sglang:v0.5.12'). Requires '--framework custom'.",
360
+ ),
361
+ ] = None,
362
+ engine: EngineOpt = None,
363
+ health_route: HealthRouteOpt = None,
364
+ port: PortOpt = None,
365
+ container_registry_username: Annotated[
366
+ str | None,
367
+ Option(
368
+ help="Username used to authenticate with the registry hosting --custom-image.",
369
+ ),
370
+ ] = None,
371
+ container_registry_password: Annotated[
372
+ str | None,
373
+ Option(
374
+ help="Optional password used to authenticate with the registry hosting --custom-image.",
375
+ ),
376
+ ] = None,
377
+ tensor_parallel_size: TensorParallelSizeOpt = None,
378
+ data_parallel_size: DataParallelSizeOpt = None,
379
+ container_command: Annotated[
380
+ str | None,
381
+ Option(
382
+ "--container-command",
383
+ help=(
384
+ "Override the container entrypoint, as a quoted string split into tokens "
385
+ '(e.g. "python -m sglang.launch_server").'
386
+ ),
387
+ ),
388
+ ] = None,
389
+ container_args: Annotated[
390
+ str | None,
391
+ Option(
392
+ "--container-args",
393
+ help=(
394
+ "Arguments appended to the container entrypoint, as a quoted string split into tokens "
395
+ '(e.g. "--tp 8 --reasoning-parser qwen3").'
396
+ ),
397
+ ),
398
+ ] = None,
399
+ env: EnvOpt = None,
400
+ env_file: EnvFileOpt = None,
401
+ secrets: SecretsOpt = None,
402
+ secrets_file: SecretsFileOpt = None,
403
+ endpoint_type: Annotated[
404
+ str | None,
405
+ Option(
406
+ "--type",
407
+ click_type=SoftChoice(InferenceEndpointType),
408
+ help="Endpoint access type. Defaults to 'authenticated' (token-gated, publicly reachable).",
409
+ ),
410
+ ] = None,
411
+ ) -> None:
412
+ """Deploy an Inference Endpoint from a Hub repository.
413
+
414
+ Run `hf endpoints hardware` to list the valid `--vendor`, `--region`, `--accelerator`, `--instance-type` and
415
+ `--instance-size` combinations.
416
+ """
417
+ custom_image_dict = _build_custom_image(
418
+ custom_image,
419
+ engine=engine,
420
+ health_route=health_route,
421
+ port=port,
422
+ container_registry_username=container_registry_username,
423
+ container_registry_password=container_registry_password,
424
+ tensor_parallel_size=tensor_parallel_size,
425
+ data_parallel_size=data_parallel_size,
426
+ )
427
+
428
+ env_map = {key: value or "" for key, value in parse_env_map(env, env_file).items()}
429
+ secrets_map = {key: value or "" for key, value in parse_env_map(secrets, secrets_file).items()}
430
+
431
+ # Only forward the values the user actually set and let `create_inference_endpoint` own the defaults.
432
+ params: dict = {}
433
+ if endpoint_type is not None:
434
+ params["type"] = endpoint_type
435
+ if custom_image_dict is not None:
436
+ params["custom_image"] = custom_image_dict
437
+ if container_registry_username is not None:
438
+ params["container_registry_username"] = container_registry_username
439
+ if container_registry_password is not None:
440
+ params["container_registry_password"] = container_registry_password
441
+ if container_command:
442
+ params["container_command"] = shlex.split(container_command)
443
+ if container_args:
444
+ params["container_args"] = shlex.split(container_args)
445
+ if env_map:
446
+ params["env"] = env_map
447
+ if secrets_map:
448
+ params["secrets"] = secrets_map
449
+
450
+ api = get_hf_api(token=token)
451
+ endpoint = api.create_inference_endpoint(
452
+ name=name,
453
+ repository=repo,
454
+ framework=framework,
455
+ accelerator=accelerator,
456
+ instance_size=instance_size,
457
+ instance_type=instance_type,
458
+ region=region,
459
+ vendor=vendor,
460
+ namespace=namespace,
461
+ task=task,
462
+ token=token,
463
+ min_replica=min_replica,
464
+ max_replica=max_replica,
465
+ scaling_metric=scaling_metric,
466
+ scaling_threshold=scaling_threshold,
467
+ scale_to_zero_timeout=scale_to_zero_timeout,
468
+ revision=revision,
469
+ **params,
470
+ )
471
+ out.dict(endpoint.raw)
472
+ out.hint(f"Use 'hf endpoints describe {name}' to check the deployment status.")
473
+
474
+
475
+ @catalog_app.command(
476
+ name="deploy",
477
+ examples=[
478
+ "hf endpoints catalog deploy --repo meta-llama/Llama-3.2-1B-Instruct",
479
+ "hf endpoints catalog deploy --recipe sizzling-biryani-g4xsi1ac",
480
+ ],
481
+ )
482
+ def deploy_from_catalog(
483
+ repo: Annotated[
484
+ str | None,
485
+ Option(
486
+ help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b')."
487
+ " Deploys its default recipe. Mutually exclusive with --recipe.",
488
+ ),
489
+ ] = None,
490
+ recipe: Annotated[
491
+ str | None,
492
+ Option(
493
+ help="The id of the catalog recipe to deploy, as listed by 'hf endpoints catalog ls'."
494
+ " Mutually exclusive with --repo.",
495
+ ),
496
+ ] = None,
497
+ name: NameOpt = None,
498
+ accelerator: Annotated[
499
+ str | None,
500
+ Option(
501
+ click_type=SoftChoice(["cpu", "gpu", "neuron"]),
502
+ help="The hardware accelerator to be used for inference. Only with --repo.",
503
+ ),
504
+ ] = None,
505
+ gguf_file: Annotated[
506
+ str | None,
507
+ Option(
508
+ help="The GGUF file to deploy, for models that have one recipe per quant. Only with --repo.",
509
+ ),
510
+ ] = None,
511
+ namespace: NamespaceOpt = None,
512
+ token: TokenOpt = None,
513
+ ) -> None:
514
+ """Deploy an Inference Endpoint from the Model Catalog.
515
+
516
+ Catalog models are deployed through a recipe: a hardware and engine combination that has been tested for them.
517
+ Pass --repo to deploy the default recipe of a model, optionally narrowed down with --accelerator and
518
+ --gguf-file, or pass --recipe to deploy an exact recipe listed by `hf endpoints catalog ls`.
519
+ """
520
+ # `--repo` used to be required, so a bare `catalog deploy` used to fail in click. Keep the message flag-shaped.
521
+ if (repo is None) == (recipe is None):
522
+ raise CLIError("Provide exactly one of --repo or --recipe. List recipes with 'hf endpoints catalog ls'.")
523
+
524
+ api = get_hf_api(token=token)
525
+ try:
526
+ endpoint = api.create_inference_endpoint_from_catalog(
527
+ repo_id=repo,
528
+ recipe_id=recipe,
529
+ name=name,
530
+ accelerator=accelerator,
531
+ gguf_file=gguf_file,
532
+ namespace=namespace,
533
+ token=token,
534
+ )
535
+ except HfHubHTTPError as error:
536
+ out.error(f"Deployment failed: {error}")
537
+ raise click.exceptions.Exit(code=error.response.status_code) from error
538
+
539
+ out.dict(endpoint.raw)
540
+ out.hint(f"Use 'hf endpoints describe {endpoint.name}' to check the deployment status.")
541
+
542
+
543
+ def list_catalog(
544
+ accelerator: Annotated[
545
+ str | None,
546
+ Option(
547
+ click_type=SoftChoice(["cpu", "gpu", "neuron"]),
548
+ help="Only show recipes running on this accelerator.",
549
+ ),
550
+ ] = None,
551
+ engine: Annotated[
552
+ str | None,
553
+ Option(
554
+ click_type=SoftChoice(["llamacpp", "sglang", "tei", "vllm"]),
555
+ help="Only show recipes running this inference engine.",
556
+ ),
557
+ ] = None,
558
+ license: Annotated[
559
+ str | None,
560
+ Option(help="Only show models under this license (e.g. 'Apache 2.0')."),
561
+ ] = None,
562
+ task: Annotated[
563
+ str | None,
564
+ Option(help="Only show models for this task (e.g. 'text-generation')."),
565
+ ] = None,
566
+ search: SearchOpt = None,
567
+ limit: Annotated[int | None, Option(help="Limit the number of models to return.")] = None,
568
+ token: TokenOpt = None,
569
+ ) -> None:
570
+ """List the models available in the Model Catalog.
571
+
572
+ One row per recipe, i.e. per tested way of deploying a model. Deploy one with
573
+ `hf endpoints catalog deploy --recipe <RECIPE_ID>`.
574
+ """
575
+ api = get_hf_api(token=token)
576
+ try:
577
+ models = api.list_inference_catalog(
578
+ accelerator=accelerator,
579
+ engine=engine,
580
+ license=license,
581
+ task=task,
582
+ search=search,
583
+ limit=limit,
584
+ token=token,
585
+ )
586
+ except HfHubHTTPError as error:
587
+ out.error(f"Catalog fetch failed: {error}")
588
+ raise click.exceptions.Exit(code=error.response.status_code) from error
589
+
590
+ items = [
591
+ {
592
+ "repo_id": model.repo_id,
593
+ "task": model.task,
594
+ "license": model.license,
595
+ "accelerator": recipe.accelerator,
596
+ "engine": recipe.engine,
597
+ "gguf_file": recipe.gguf_file,
598
+ "recipe_id": recipe.id,
599
+ }
600
+ for model in models
601
+ for recipe in model.recipes
602
+ ]
603
+ out.table(items, id_key="recipe_id")
604
+ if items:
605
+ out.hint(f"Deploy one with: hf endpoints catalog deploy --recipe {items[0]['recipe_id']}")
606
+
607
+
608
+ catalog_app.command(name="list | ls", examples=["hf endpoints catalog ls", "hf endpoints catalog ls --engine vllm"])(
609
+ list_catalog
610
+ )
611
+ ie_cli.command(name="list-catalog", hidden=True)(list_catalog)
612
+
613
+
614
+ ie_cli.add_group(catalog_app, name="catalog")
615
+
616
+
617
+ @ie_cli.command(examples=["hf endpoints describe my-endpoint"])
618
+ def describe(
619
+ name: NameArg,
620
+ namespace: NamespaceOpt = None,
621
+ token: TokenOpt = None,
622
+ ) -> None:
623
+ """Get information about an existing endpoint."""
624
+ api = get_hf_api(token=token)
625
+ try:
626
+ endpoint = api.get_inference_endpoint(name=name, namespace=namespace, token=token)
627
+ except HfHubHTTPError as error:
628
+ out.error(f"Fetch failed: {error}")
629
+ raise click.exceptions.Exit(code=error.response.status_code) from error
630
+
631
+ out.dict(endpoint.raw)
632
+
633
+
634
+ @ie_cli.command(
635
+ examples=[
636
+ "hf endpoints update my-endpoint --min-replica 2",
637
+ "hf endpoints update my-endpoint --tensor-parallel-size 8",
638
+ 'hf endpoints update my-endpoint --container-args "--enable-auto-tool-choice --tool-call-parser lfm2"',
639
+ ]
640
+ )
641
+ def update(
642
+ name: NameArg,
643
+ namespace: NamespaceOpt = None,
644
+ repo: Annotated[
645
+ str | None,
646
+ Option(
647
+ help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').",
648
+ ),
649
+ ] = None,
650
+ accelerator: Annotated[
651
+ str | None,
652
+ Option(
653
+ help="The hardware accelerator to be used for inference (e.g. 'cpu').",
654
+ ),
655
+ ] = None,
656
+ instance_size: Annotated[
657
+ str | None,
658
+ Option(
659
+ help="The size or type of the instance to be used for hosting the model (e.g. 'x4').",
660
+ ),
661
+ ] = None,
662
+ instance_type: Annotated[
663
+ str | None,
664
+ Option(
665
+ help="The cloud instance type where the Inference Endpoint will be deployed (e.g. 'intel-icl').",
666
+ ),
667
+ ] = None,
668
+ framework: Annotated[
669
+ str | None,
670
+ Option(
671
+ help="The machine learning framework used for the model (e.g. 'custom').",
672
+ ),
673
+ ] = None,
674
+ revision: Annotated[
675
+ str | None,
676
+ Option(
677
+ help="The specific model revision to deploy on the Inference Endpoint (e.g. '6c0e6080953db56375760c0471a8c5f2929baf11').",
678
+ ),
679
+ ] = None,
680
+ task: Annotated[
681
+ str | None,
682
+ Option(
683
+ help="The task on which to deploy the model (e.g. 'text-classification').",
684
+ ),
685
+ ] = None,
686
+ custom_image: Annotated[
687
+ str | None,
688
+ Option(
689
+ "--custom-image",
690
+ help=(
691
+ "Docker image URL for the container to run (e.g. 'nexagi/sglang:v0.5.12'). Replaces the image "
692
+ "currently configured on the endpoint rather than patching it, so pass the engine and container "
693
+ "settings you want to keep along with it, run 'hf endpoints describe NAME' first to see them."
694
+ ),
695
+ ),
696
+ ] = None,
697
+ engine: EngineOpt = None,
698
+ health_route: HealthRouteOpt = None,
699
+ port: PortOpt = None,
700
+ tensor_parallel_size: TensorParallelSizeOpt = None,
701
+ data_parallel_size: DataParallelSizeOpt = None,
702
+ container_command: Annotated[
703
+ str | None,
704
+ Option(
705
+ "--container-command",
706
+ help=(
707
+ "Override the container entrypoint, as a quoted string split into tokens "
708
+ '(e.g. "python -m sglang.launch_server"). Replaces the current value; '
709
+ "pass an empty string to clear it."
710
+ ),
711
+ ),
712
+ ] = None,
713
+ container_args: Annotated[
714
+ str | None,
715
+ Option(
716
+ "--container-args",
717
+ help=(
718
+ "Arguments appended to the container entrypoint, as a quoted string split into tokens "
719
+ '(e.g. "--enable-auto-tool-choice --tool-call-parser lfm2"). Replaces the arguments currently '
720
+ "set on the endpoint rather than adding to them, so include the ones you want to keep, run "
721
+ "'hf endpoints describe NAME' first to see them. Pass an empty string to clear them."
722
+ ),
723
+ ),
724
+ ] = None,
725
+ min_replica: Annotated[
726
+ int | None,
727
+ Option(
728
+ help="The minimum number of replicas (instances) to keep running for the Inference Endpoint.",
729
+ ),
730
+ ] = None,
731
+ max_replica: Annotated[
732
+ int | None,
733
+ Option(
734
+ help="The maximum number of replicas (instances) to scale to for the Inference Endpoint.",
735
+ ),
736
+ ] = None,
737
+ scale_to_zero_timeout: Annotated[
738
+ int | None,
739
+ Option(
740
+ help="The duration in minutes before an inactive endpoint is scaled to zero.",
741
+ ),
742
+ ] = None,
743
+ scaling_metric: Annotated[
744
+ InferenceEndpointScalingMetric | None,
745
+ Option(
746
+ help="The metric reference for scaling.",
747
+ ),
748
+ ] = None,
749
+ scaling_threshold: Annotated[
750
+ float | None,
751
+ Option(
752
+ help="The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.",
753
+ ),
754
+ ] = None,
755
+ token: TokenOpt = None,
756
+ ) -> None:
757
+ """Update an existing endpoint."""
758
+ # Exactly one path carries the sizes: into the image built here when `--custom-image` gives us one, otherwise
759
+ # as kwargs, for `update_inference_endpoint` to merge into the image the endpoint currently runs.
760
+ custom_image_dict = _build_custom_image(
761
+ custom_image,
762
+ engine=engine,
763
+ health_route=health_route,
764
+ port=port,
765
+ tensor_parallel_size=tensor_parallel_size if custom_image is not None else None,
766
+ data_parallel_size=data_parallel_size if custom_image is not None else None,
767
+ )
768
+
769
+ api = get_hf_api(token=token)
770
+ try:
771
+ endpoint = api.update_inference_endpoint(
772
+ name=name,
773
+ namespace=namespace,
774
+ repository=repo,
775
+ framework=framework,
776
+ revision=revision,
777
+ task=task,
778
+ custom_image=custom_image_dict,
779
+ container_command=shlex.split(container_command) if container_command is not None else None,
780
+ container_args=shlex.split(container_args) if container_args is not None else None,
781
+ tensor_parallel_size=tensor_parallel_size if custom_image is None else None,
782
+ data_parallel_size=data_parallel_size if custom_image is None else None,
783
+ accelerator=accelerator,
784
+ instance_size=instance_size,
785
+ instance_type=instance_type,
786
+ min_replica=min_replica,
787
+ max_replica=max_replica,
788
+ scale_to_zero_timeout=scale_to_zero_timeout,
789
+ scaling_metric=scaling_metric,
790
+ scaling_threshold=scaling_threshold,
791
+ token=token,
792
+ )
793
+ except HfHubHTTPError as error:
794
+ out.error(f"Update failed: {error}")
795
+ raise click.exceptions.Exit(code=error.response.status_code) from error
796
+ out.dict(endpoint.raw)
797
+
798
+
799
+ @ie_cli.command(examples=["hf endpoints delete my-endpoint"])
800
+ def delete(
801
+ name: NameArg,
802
+ namespace: NamespaceOpt = None,
803
+ yes: Annotated[
804
+ bool,
805
+ Option("--yes", help="Skip confirmation prompts."),
806
+ ] = False,
807
+ token: TokenOpt = None,
808
+ ) -> None:
809
+ """Delete an Inference Endpoint permanently."""
810
+ out.confirm(f"Delete endpoint '{name}'?", yes=yes)
811
+
812
+ api = get_hf_api(token=token)
813
+ try:
814
+ api.delete_inference_endpoint(name=name, namespace=namespace, token=token)
815
+ except HfHubHTTPError as error:
816
+ out.error(f"Delete failed: {error}")
817
+ raise click.exceptions.Exit(code=error.response.status_code) from error
818
+
819
+ out.result(f"Deleted '{name}'.", name=name)
820
+
821
+
822
+ @ie_cli.command(examples=["hf endpoints pause my-endpoint"])
823
+ def pause(
824
+ name: NameArg,
825
+ namespace: NamespaceOpt = None,
826
+ token: TokenOpt = None,
827
+ ) -> None:
828
+ """Pause an Inference Endpoint."""
829
+ api = get_hf_api(token=token)
830
+ try:
831
+ endpoint = api.pause_inference_endpoint(name=name, namespace=namespace, token=token)
832
+ except HfHubHTTPError as error:
833
+ out.error(f"Pause failed: {error}")
834
+ raise click.exceptions.Exit(code=error.response.status_code) from error
835
+
836
+ out.dict(endpoint.raw)
837
+
838
+
839
+ @ie_cli.command(examples=["hf endpoints resume my-endpoint"])
840
+ def resume(
841
+ name: NameArg,
842
+ namespace: NamespaceOpt = None,
843
+ fail_if_already_running: Annotated[
844
+ bool,
845
+ Option(
846
+ "--fail-if-already-running",
847
+ help="If `True`, the method will raise an error if the Inference Endpoint is already running.",
848
+ ),
849
+ ] = False,
850
+ token: TokenOpt = None,
851
+ ) -> None:
852
+ """Resume an Inference Endpoint."""
853
+ api = get_hf_api(token=token)
854
+ try:
855
+ endpoint = api.resume_inference_endpoint(
856
+ name=name,
857
+ namespace=namespace,
858
+ token=token,
859
+ running_ok=not fail_if_already_running,
860
+ )
861
+ except HfHubHTTPError as error:
862
+ out.error(f"Resume failed: {error}")
863
+ raise click.exceptions.Exit(code=error.response.status_code) from error
864
+ out.dict(endpoint.raw)
865
+
866
+
867
+ @ie_cli.command(examples=["hf endpoints scale-to-zero my-endpoint"])
868
+ def scale_to_zero(
869
+ name: NameArg,
870
+ namespace: NamespaceOpt = None,
871
+ token: TokenOpt = None,
872
+ ) -> None:
873
+ """Scale an Inference Endpoint to zero."""
874
+ api = get_hf_api(token=token)
875
+ try:
876
+ endpoint = api.scale_to_zero_inference_endpoint(name=name, namespace=namespace, token=token)
877
+ except HfHubHTTPError as error:
878
+ out.error(f"Scale To Zero failed: {error}")
879
+ raise click.exceptions.Exit(code=error.response.status_code) from error
880
+
881
+ out.dict(endpoint.raw)
882
+
883
+
884
+ def _build_custom_image(
885
+ custom_image: str | None,
886
+ *,
887
+ engine: str | None = None,
888
+ health_route: str | None = None,
889
+ port: int | None = None,
890
+ container_registry_username: str | None = None,
891
+ container_registry_password: str | None = None,
892
+ tensor_parallel_size: int | None = None,
893
+ data_parallel_size: int | None = None,
894
+ ) -> dict | None:
895
+ """Build the `custom_image` argument of `HfApi` from the flat image flags.
896
+
897
+ A bare image URL describes a custom container and is passed flat, `HfApi` keys it as `custom`. `--engine`
898
+ selects a managed engine image instead, whose config is keyed by the API's variant name. An engine this
899
+ version doesn't know about is forwarded as typed, so the API names the bad variant.
900
+ """
901
+ if custom_image is None:
902
+ # These flags all describe the container image, and the only image these commands can build is the one
903
+ # --custom-image names. Container command/args are top-level model fields, hence not listed here.
904
+ image_flags = {
905
+ "--engine": engine,
906
+ "--health-route": health_route,
907
+ "--port": port,
908
+ "--container-registry-username": container_registry_username,
909
+ "--container-registry-password": container_registry_password,
910
+ "--tensor-parallel-size": tensor_parallel_size,
911
+ "--data-parallel-size": data_parallel_size,
912
+ }
913
+ if used := [flag for flag, value in image_flags.items() if value is not None]:
914
+ raise CLIError(f"--custom-image is required when using {', '.join(used)}.")
915
+ return None
916
+
917
+ if container_registry_password is not None and container_registry_username is None:
918
+ raise CLIError("--container-registry-password requires --container-registry-username.")
919
+ if engine is not None and container_registry_username is not None:
920
+ raise CLIError("Container registry credentials can only be set for a custom container without --engine.")
921
+
922
+ if engine is None and (tensor_parallel_size is not None or data_parallel_size is not None):
923
+ # Without an engine the config is a plain custom container, whose parallelism fields the API ignores
924
+ # rather than rejects. Fail here instead of deploying something that quietly runs on one accelerator.
925
+ raise CLIError("--tensor-parallel-size and --data-parallel-size require --engine (e.g. --engine vllm).")
926
+
927
+ config: dict = {"url": custom_image}
928
+ if health_route is not None:
929
+ config["healthRoute"] = health_route
930
+ if port is not None:
931
+ config["port"] = port
932
+ if engine is None:
933
+ return config
934
+ # Delegate the sizes so this and `update_inference_endpoint` share one rule, including the warning when
935
+ # the engine does not declare the field.
936
+ return _set_parallelism_in_image(
937
+ {ENGINE_IMAGE_KEYS.get(engine, engine): config},
938
+ tensor_parallel_size=tensor_parallel_size,
939
+ data_parallel_size=data_parallel_size,
940
+ )
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/huggingface_hub/cli/jobs.py ADDED
@@ -0,0 +1,2187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import itertools
17
+ import multiprocessing
18
+ import multiprocessing.pool
19
+ import shlex
20
+ import shutil
21
+ import time
22
+ from collections.abc import Callable, Collection, Generator, Iterable
23
+ from contextlib import contextmanager
24
+ from dataclasses import dataclass, field
25
+ from enum import Enum
26
+ from pathlib import Path
27
+ from queue import Empty, Queue
28
+ from typing import Annotated, Any, TypeVar
29
+ from urllib.parse import urlsplit
30
+
31
+ from huggingface_hub import HfApi, JobHardware, JobInfo, JobNetwork, JobStage, Volume, constants
32
+ from huggingface_hub._jobs_api import (
33
+ DEFAULT_UV_IMAGE,
34
+ TERMINAL_JOB_STAGES,
35
+ _default_job_name_from_image,
36
+ _default_job_name_from_script,
37
+ )
38
+ from huggingface_hub.errors import CLIError
39
+ from huggingface_hub.utils import logging
40
+ from huggingface_hub.utils._cache_manager import _format_size
41
+ from huggingface_hub.utils._hf_uris import _split_mount
42
+ from huggingface_hub.utils._parsing import format_duration, parse_duration
43
+
44
+ from ._cli_utils import (
45
+ EnvFileOpt,
46
+ EnvOpt,
47
+ FormatOpt,
48
+ JsonOpt,
49
+ QuietOpt,
50
+ SecretsFileOpt,
51
+ SecretsOpt,
52
+ SoftChoice,
53
+ SshDryRunOpt,
54
+ SshIdentityFileOpt,
55
+ TokenOpt,
56
+ _get_extended_environ,
57
+ exec_ssh,
58
+ get_hf_api,
59
+ parse_env_map,
60
+ parse_volumes,
61
+ set_output_format,
62
+ typer_factory,
63
+ )
64
+ from ._framework import Argument, Option
65
+ from ._output import OutputFormat, _dataclass_to_dict, out
66
+ from ._uv_script_header import TABLE_NAME, UvScriptHeader, load_uv_script
67
+
68
+
69
+ logger = logging.get_logger(__name__)
70
+
71
+
72
+ def _parse_namespace_from_job_id(job_id: str, namespace: str | None) -> tuple[str, str | None]:
73
+ """Extract namespace from job_id if provided in 'namespace/job_id' format.
74
+
75
+ Allows users to pass job IDs copied from the Hub UI (e.g. 'username/job_id')
76
+ instead of only bare job IDs. If the namespace is also provided explicitly via
77
+ --namespace and conflicts, a CLIError is raised.
78
+ """
79
+ if not job_id:
80
+ raise CLIError("Job ID cannot be empty.")
81
+
82
+ if job_id.count("/") > 1:
83
+ raise CLIError(f"Job ID must be in the form 'job_id' or 'namespace/job_id': '{job_id}'.")
84
+
85
+ if "/" not in job_id:
86
+ return job_id, namespace
87
+
88
+ extracted_namespace, parsed_job_id = job_id.split("/", 1)
89
+ if not extracted_namespace or not parsed_job_id:
90
+ raise CLIError(f"Job ID must be in the form 'job_id' or 'namespace/job_id': '{job_id}'.")
91
+
92
+ if namespace is not None and namespace != extracted_namespace:
93
+ raise CLIError(
94
+ f"Conflicting namespace: got --namespace='{namespace}' but job ID implies namespace='{extracted_namespace}'"
95
+ )
96
+
97
+ return parsed_job_id, extracted_namespace
98
+
99
+
100
+ def _parse_and_sync_job_volumes(
101
+ volumes: list[str] | None, *, api: HfApi, namespace: str | None
102
+ ) -> list[Volume] | None:
103
+ """Parse `-v` specs for Jobs commands.
104
+
105
+ Same as [`parse_volumes`] but the source side can also be a local directory: it is synced to a
106
+ bucket via [`HfApi.sync_job_volume`] and the resulting bucket subfolder is mounted (read-only
107
+ unless ':rw' is specified).
108
+ """
109
+ if not volumes:
110
+ return None
111
+
112
+ result: list[Volume] = []
113
+ for raw_spec in volumes:
114
+ if raw_spec.startswith(constants.HF_PROTOCOL):
115
+ result.extend(parse_volumes([raw_spec]) or [])
116
+ continue
117
+
118
+ # Not a 'hf://' URI: treat the source as a local directory.
119
+ source, mount_path, read_only = _split_mount(raw_spec, raw=raw_spec)
120
+ if mount_path is None:
121
+ raise CLIError(
122
+ f"Missing mount path in volume spec '{raw_spec}'. Expected 'LOCAL_DIR:/MOUNT_PATH[:ro|:rw]' (e.g. './data:/data')."
123
+ )
124
+ if not Path(source).expanduser().is_dir():
125
+ raise CLIError(
126
+ f"Volume source '{source}' is not an existing local directory. "
127
+ "To mount a repo or bucket instead, use the 'hf://' syntax (e.g. 'hf://buckets/my-org/my-bucket:/data')."
128
+ )
129
+ volume = api.sync_job_volume(
130
+ source,
131
+ mount_path,
132
+ read_only=read_only if read_only is not None else True,
133
+ namespace=namespace,
134
+ )
135
+ if volume.read_only is False:
136
+ out.hint(
137
+ f"Volume '{mount_path}' is mounted read-write. Once the job is over, pull back its data with:\n"
138
+ f" hf buckets sync hf://buckets/{volume.source}/{volume.path} {source}"
139
+ )
140
+ result.append(volume)
141
+ return result
142
+
143
+
144
+ @dataclass
145
+ class _UvJobConfig:
146
+ """Resolved launch configuration of a UV Job: CLI flags merged with the script's `[tool.hf-jobs]` table."""
147
+
148
+ script: str
149
+ """What is passed to the Jobs API. Same as the CLI argument, except for a URL script (downloaded locally)."""
150
+
151
+ script_args: list[str] = field(default_factory=list)
152
+ image: str | None = None
153
+ flavor: str | None = None
154
+ python: str | None = None
155
+ timeout: str | None = None
156
+ namespace: str | None = None
157
+ network_group: str | None = None
158
+ env: dict[str, str | None] = field(default_factory=dict)
159
+ secrets: dict[str, str | None] = field(default_factory=dict)
160
+ labels: dict[str, str] = field(default_factory=dict)
161
+ volume_specs: list[str] = field(default_factory=list)
162
+ volumes: list[Volume] | None = None
163
+ network_aliases: list[str] = field(default_factory=list)
164
+
165
+ from_script: set[str] = field(default_factory=set)
166
+ """Keys whose value comes from the script's `[tool.hf-jobs]` table, for display purposes."""
167
+
168
+
169
+ @contextmanager
170
+ def _resolve_uv_job_config(
171
+ *,
172
+ api: HfApi,
173
+ script: str,
174
+ script_args: list[str] | None,
175
+ dependencies: list[str] | None,
176
+ image: str | None,
177
+ flavor: str | None,
178
+ python: str | None,
179
+ env: list[str] | None,
180
+ env_file: str | None,
181
+ secrets: list[str] | None,
182
+ secrets_file: str | None,
183
+ timeout: str | None,
184
+ attempts: int | None,
185
+ name: str | None,
186
+ label: list[str] | None,
187
+ volume: list[str] | None,
188
+ namespace: str | None,
189
+ network_group: str | None,
190
+ network_aliases: list[str] | None,
191
+ dry_run: bool,
192
+ ) -> Generator[_UvJobConfig, None, None]:
193
+ """Merge the CLI flags with the `[tool.hf-jobs]` table the script carries, if any.
194
+
195
+ An explicit CLI flag always wins over the script; `env`, `labels`, `secrets` and `volumes` are merged
196
+ entry by entry (by key, by name and by mount path respectively), so a script value and a CLI value
197
+ only ever conflict when they target the same entry. `network_aliases` is the exception: the aliases
198
+ a Job claims form a set, so `--network-alias` replaces the script's list rather than adding to it.
199
+
200
+ A URL script is downloaded to a temporary file that lives until the `with` block exits: submit the
201
+ Job inside the block.
202
+ """
203
+ with load_uv_script(script) as source:
204
+ header = source.header or UvScriptHeader()
205
+ from_script: set[str] = set()
206
+
207
+ def pick(key: str, cli_value: str | None) -> str | None:
208
+ """Keep the CLI value, and fall back to the script's."""
209
+ if cli_value is not None:
210
+ return cli_value
211
+ if (script_value := getattr(header, key)) is not None:
212
+ from_script.add(key)
213
+ return script_value
214
+ return None
215
+
216
+ image = pick("image", image)
217
+ flavor = pick("flavor", flavor)
218
+ python = pick("python", python)
219
+ timeout = pick("timeout", timeout)
220
+ namespace = pick("namespace", namespace)
221
+ network_group = pick("network_group", network_group)
222
+
223
+ if not network_aliases and header.network_aliases:
224
+ from_script.add("network_aliases")
225
+ network_aliases = header.network_aliases
226
+
227
+ env_map = parse_env_map(env, env_file)
228
+ script_env = {key: value for key, value in header.env.items() if key not in env_map}
229
+ from_script.update(f"env.{key}" for key in script_env)
230
+ env_map = {**script_env, **env_map}
231
+
232
+ secrets_map = _parse_secrets_map(secrets, secrets_file, dry_run=dry_run)
233
+ script_secrets = _resolve_script_secrets(header.secrets, secrets_map, dry_run=dry_run)
234
+ from_script.update(f"secrets.{key}" for key in script_secrets)
235
+ secrets_map = {**script_secrets, **secrets_map}
236
+
237
+ labels_map = _parse_labels_map(label, name=name) or {}
238
+ # `name = ...` in the script's table is shorthand for the `name` label.
239
+ script_labels = {**header.labels, **({"name": header.name} if header.name is not None else {})}
240
+ script_labels = {key: value for key, value in script_labels.items() if key not in labels_map}
241
+ from_script.update(f"labels.{key}" for key in script_labels)
242
+ labels_map = {**script_labels, **labels_map}
243
+
244
+ volume_specs, script_volume_specs = _merge_volume_specs(volume or [], header.volumes)
245
+ from_script.update(f"volumes.{spec}" for spec in script_volume_specs)
246
+
247
+ config = _UvJobConfig(
248
+ script=source.script,
249
+ script_args=script_args or [],
250
+ image=image,
251
+ flavor=flavor,
252
+ python=python,
253
+ timeout=timeout,
254
+ namespace=namespace,
255
+ network_group=network_group,
256
+ env=env_map,
257
+ secrets=secrets_map,
258
+ labels=labels_map,
259
+ volume_specs=volume_specs,
260
+ # A dry run must not have side effects: local directories are only synced to a bucket for real runs.
261
+ volumes=None if dry_run else _parse_and_sync_job_volumes(volume_specs, api=api, namespace=namespace),
262
+ network_aliases=network_aliases or [],
263
+ from_script=from_script,
264
+ )
265
+ if "name" not in config.labels:
266
+ # `script` (not `config.script`) so that a URL keeps naming the Job after the URL, not after
267
+ # the temporary file it was downloaded to.
268
+ config.labels["name"] = _default_job_name_from_script(
269
+ script,
270
+ config.script_args,
271
+ config_parts=_name_hash_parts(
272
+ flavor=config.flavor,
273
+ timeout=config.timeout,
274
+ namespace=config.namespace,
275
+ env=config.env,
276
+ secrets=config.secrets,
277
+ volume_specs=config.volume_specs,
278
+ network_group=config.network_group,
279
+ network_aliases=config.network_aliases,
280
+ extra=[
281
+ config.image or DEFAULT_UV_IMAGE,
282
+ config.python or "",
283
+ *(dependencies or []),
284
+ *([str(attempts)] if attempts is not None else []),
285
+ ],
286
+ ),
287
+ )
288
+ yield config
289
+
290
+
291
+ def _parse_secrets_map(
292
+ secrets: list[str] | None, secrets_file: str | None, *, dry_run: bool = False
293
+ ) -> dict[str, str | None]:
294
+ """Parse `--secrets`/`--secrets-file`, failing if a bare `--secrets NAME` is not set locally.
295
+
296
+ Same behavior as for the secrets requested by a script (see `_resolve_script_secrets`): a missing secret
297
+ is an error rather than silently dropped, except in `--dry-run` where it is displayed as `<not set>`.
298
+ """
299
+ secrets_map = parse_env_map(secrets, secrets_file)
300
+ missing = [name for value in secrets or [] if "=" not in value and (name := value.strip()) not in secrets_map]
301
+ if missing and not dry_run:
302
+ raise CLIError(
303
+ f"The following secret(s) are not set in your environment: {', '.join(missing)}."
304
+ f" Export them locally (e.g. `export {missing[0]}=...`) or use `--secrets-file` otherwise."
305
+ )
306
+ return {**secrets_map, **dict.fromkeys(missing)}
307
+
308
+
309
+ def _resolve_script_secrets(
310
+ names: list[str], cli_secrets: dict[str, str | None], *, dry_run: bool = False
311
+ ) -> dict[str, str | None]:
312
+ """Resolve the secrets requested by a script from the caller's environment.
313
+
314
+ A script only lists secret *names*: values always come from whoever runs it (`HF_TOKEN` also
315
+ resolves from `hf auth login`). A requested secret that is not set locally is an error rather than
316
+ an empty value: forgetting to export a secret before launching is easy, and debugging the Job that
317
+ results from it is not.
318
+
319
+ In `--dry-run` a missing secret is not an error but a `None` value, displayed as `<not set>` in the
320
+ summary: nothing is submitted, so the point is to see the full configuration of a script - including
321
+ one whose secrets are not provisioned locally (yet).
322
+ """
323
+ if not names:
324
+ return {}
325
+ environ = _get_extended_environ()
326
+ resolved: dict[str, str | None] = {}
327
+ missing: list[str] = []
328
+ for name in names:
329
+ if name in cli_secrets: # an explicit `--secrets NAME=...` wins
330
+ continue
331
+ if name in environ:
332
+ resolved[name] = environ[name]
333
+ else:
334
+ missing.append(name)
335
+ if missing and not dry_run:
336
+ raise CLIError(
337
+ f"The script requires the following secret(s), which are not set in your environment: {', '.join(missing)}."
338
+ f" Export them locally (e.g. `export {missing[0]}=...`) or use `--secrets-file` otherwise."
339
+ )
340
+ if resolved:
341
+ out.warning(
342
+ f"The script's [{TABLE_NAME}] table requests {', '.join(resolved)}: the value(s) from your local"
343
+ f" environment {'would be' if dry_run else 'will be'} sent to the Job."
344
+ )
345
+ return {**resolved, **dict.fromkeys(missing)}
346
+
347
+
348
+ def _merge_volume_specs(cli_specs: list[str], script_specs: list[str]) -> tuple[list[str], list[str]]:
349
+ """Merge `-v` specs with the ones from the script. Returns `(all specs, specs from the script)`.
350
+
351
+ A CLI mount overrides the script's mount at the same path.
352
+ """
353
+ cli_mount_paths = {_split_mount(spec, raw=spec)[1] for spec in cli_specs}
354
+ kept = [spec for spec in script_specs if _split_mount(spec, raw=spec)[1] not in cli_mount_paths]
355
+ return kept + cli_specs, kept
356
+
357
+
358
+ def _name_hash_parts(
359
+ *,
360
+ flavor: str | None,
361
+ timeout: str | None,
362
+ namespace: str | None,
363
+ env: dict[str, str | None],
364
+ secrets: dict[str, str | None],
365
+ volume_specs: list[str],
366
+ network_group: str | None = None,
367
+ network_aliases: list[str] | None = None,
368
+ extra: list[str] | None = None,
369
+ ) -> list[str]:
370
+ """The resolved launch values hashed into a Job's default name, on top of its image/script.
371
+
372
+ Same inputs for `hf jobs run` and `hf jobs uv run`, so that both name Jobs after what they actually
373
+ submit (`extra` carries what is specific to UV runs). Env *values* are part of the hash since they
374
+ change what the Job does; secrets only contribute their names, never their values.
375
+ """
376
+ return [
377
+ flavor or JobHardware.CPU_BASIC.value,
378
+ timeout or "",
379
+ namespace or "",
380
+ network_group or "",
381
+ *(extra or []),
382
+ *(f"{key}={value}" for key, value in sorted(env.items())),
383
+ *sorted(secrets),
384
+ *volume_specs,
385
+ *(network_aliases or []),
386
+ ]
387
+
388
+
389
+ _FROM_SCRIPT = " (from script)"
390
+
391
+
392
+ def _print_job_summary(values: dict[str, Any], *, from_script: Collection[str] = (), dry_run: bool = False) -> None:
393
+ """Echo the launch configuration of a Job before submitting it.
394
+
395
+ Printed on every run, so that what is sent to the Jobs API is always visible - in particular the
396
+ values injected by a script's `[tool.hf-jobs]` table, which are marked as such. Goes to stderr for a
397
+ real run, and to stdout for `--dry-run`, where it is the output of the command.
398
+ """
399
+ rows = [
400
+ (key, _format_job_value(key, value, from_script))
401
+ for key, value in values.items()
402
+ if value not in (None, "", [], {}, False)
403
+ ]
404
+ width = max(len(key) for key, _ in rows)
405
+ lines = ["Job configuration:"]
406
+ for key, value in rows:
407
+ value += _FROM_SCRIPT if key in from_script else ""
408
+ # Only the first line of a multi-line value is prefixed with the key.
409
+ lines += [
410
+ f" {(key if index == 0 else '').ljust(width)} {line}" for index, line in enumerate(value.split("\n"))
411
+ ]
412
+ summary = "\n".join(lines)
413
+ if dry_run:
414
+ out.text(f"{summary}\n(dry run) Job not submitted.")
415
+ else:
416
+ out.log(summary)
417
+
418
+
419
+ def _format_job_value(key: str, value: Any, from_script: Collection[str]) -> str:
420
+ """Format config entries, redacting secrets and marking values inherited from the script."""
421
+ match key:
422
+ case "env":
423
+ # Keep long prompts or JSON values readable in the summary.
424
+ entries = {}
425
+ for name, item in value.items():
426
+ text = item or ""
427
+ entries[name] = f"{name}={text[:59] + '…' if len(text) > 60 else text}"
428
+ case "secrets":
429
+ entries = {name: f"{name}={'***' if item is not None else '<not set>'}" for name, item in value.items()}
430
+ case "labels":
431
+ entries = {name: f"{name}={item}" for name, item in value.items()}
432
+ case "volumes":
433
+ entries = {spec: spec for spec in value}
434
+ case _:
435
+ return str(value)
436
+ return "\n".join(text + (_FROM_SCRIPT if f"{key}.{name}" in from_script else "") for name, text in entries.items())
437
+
438
+
439
+ STATS_UPDATE_MIN_INTERVAL = 0.1 # we set a limit here since there is one update per second per job
440
+
441
+ # Common job-related options
442
+ ImageArg = Annotated[
443
+ str,
444
+ Argument(
445
+ help="The Docker image to use.",
446
+ ),
447
+ ]
448
+
449
+ ImageOpt = Annotated[
450
+ str | None,
451
+ Option(
452
+ help="Use a custom Docker image with `uv` installed.",
453
+ ),
454
+ ]
455
+
456
+ FlavorOpt = Annotated[
457
+ str | None,
458
+ Option(
459
+ help="Flavor for the hardware. Run 'hf jobs hardware' to list available flavors. Defaults to `cpu-basic`.",
460
+ click_type=SoftChoice(JobHardware),
461
+ ),
462
+ ]
463
+
464
+ LabelsOpt = Annotated[
465
+ list[str] | None,
466
+ Option(
467
+ "-l",
468
+ "--label",
469
+ help="Set labels. E.g. --label KEY=VALUE or --label LABEL",
470
+ ),
471
+ ]
472
+
473
+ NameOpt = Annotated[
474
+ str | None,
475
+ Option(
476
+ "--name",
477
+ help="Name the Job. Stored as the `name` label. Names do not have to be unique. Defaults to the image or script name plus a short hash of the resolved launch configuration.",
478
+ ),
479
+ ]
480
+
481
+ TimeoutOpt = Annotated[
482
+ str | None,
483
+ Option(
484
+ help="Max duration: int with s (seconds, default), m (minutes), h (hours) or d (days).",
485
+ ),
486
+ ]
487
+
488
+ AttemptsOpt = Annotated[
489
+ int | None,
490
+ Option("--attempts", min=1, help="Maximum attempts, including the first run. Defaults to 1."),
491
+ ]
492
+
493
+ DetachOpt = Annotated[
494
+ bool,
495
+ Option(
496
+ "-d",
497
+ "--detach",
498
+ help="Run the Job in the background and print the Job ID.",
499
+ ),
500
+ ]
501
+
502
+ DryRunOpt = Annotated[
503
+ bool,
504
+ Option(
505
+ "--dry-run",
506
+ help="Print the resolved Job configuration without submitting the Job.",
507
+ ),
508
+ ]
509
+
510
+ NamespaceOpt = Annotated[
511
+ str | None,
512
+ Option(
513
+ help="The namespace where the job will be running. Defaults to the current user's namespace.",
514
+ ),
515
+ ]
516
+
517
+ ResourceGroupIdOpt = Annotated[
518
+ str | None,
519
+ Option(
520
+ "--resource-group-id",
521
+ help="The ID of the resource group to create the Job in. Used to control access to resources within an organization and for cost attribution/spending-limit features.",
522
+ ),
523
+ ]
524
+
525
+ ExposeOpt = Annotated[
526
+ list[int] | None,
527
+ Option(
528
+ "--expose",
529
+ help="Expose a container port through the jobs proxy. Repeat the flag for multiple ports (e.g. `--expose 8000 --expose 8001`). Each exposed port is reachable on the public jobs domain; access requires an HF token with read access to the job's namespace.",
530
+ ),
531
+ ]
532
+
533
+ ExposePublicOpt = Annotated[
534
+ list[int] | None,
535
+ Option(
536
+ "--expose-public",
537
+ help="Expose a container port through the jobs proxy without authentication. Repeat the flag for multiple ports. No need to also pass the port with `--expose`.",
538
+ ),
539
+ ]
540
+
541
+
542
+ SshEnabledOpt = Annotated[
543
+ bool,
544
+ Option(
545
+ "--ssh",
546
+ help="Make the job's container reachable over SSH. Connect with `hf jobs ssh <job_id>`. Requires an SSH public key registered on https://huggingface.co/settings/keys.",
547
+ ),
548
+ ]
549
+
550
+ NetworkGroupOpt = Annotated[
551
+ str | None,
552
+ Option(
553
+ "--network-group",
554
+ help="Join a network group. Jobs in the same namespace and resource group sharing a group are placed together and reach each other on every port. Inside each member, `$HF_NETWORK_GROUP_HOSTNAME` resolves to every member. Lowercase alphanumerics and dashes, 46 characters max.",
555
+ ),
556
+ ]
557
+
558
+ NetworkAliasOpt = Annotated[
559
+ list[str] | None,
560
+ Option(
561
+ "--network-alias",
562
+ help="Claim an alias in the network group. Members reach the jobs claiming it at `${HF_NETWORK_GROUP_PREFIX}<alias>`. Repeat the flag for several aliases. Lowercase alphanumerics and dashes, 34 characters max, unique within the job. Requires `--network-group`.",
563
+ ),
564
+ ]
565
+
566
+ WithOpt = Annotated[
567
+ list[str] | None,
568
+ Option(
569
+ "--with",
570
+ help="Run with the given packages installed",
571
+ ),
572
+ ]
573
+
574
+ PythonOpt = Annotated[
575
+ str | None,
576
+ Option(
577
+ "-p",
578
+ "--python",
579
+ help="The Python interpreter to use for the run environment",
580
+ ),
581
+ ]
582
+
583
+ SuspendOpt = Annotated[
584
+ bool | None,
585
+ Option(
586
+ help="Suspend (pause) the scheduled Job",
587
+ ),
588
+ ]
589
+
590
+ ConcurrencyOpt = Annotated[
591
+ bool | None,
592
+ Option(
593
+ help="Allow multiple instances of this Job to run concurrently",
594
+ ),
595
+ ]
596
+
597
+ ScheduleArg = Annotated[
598
+ str,
599
+ Argument(
600
+ help="One of @annually, @yearly, @monthly, @weekly, @daily, @hourly, or a CRON schedule expression.",
601
+ ),
602
+ ]
603
+
604
+ ScriptArg = Annotated[
605
+ str,
606
+ Argument(
607
+ help="UV script to run (local file or URL)",
608
+ ),
609
+ ]
610
+
611
+ ScriptArgsArg = Annotated[
612
+ list[str] | None,
613
+ Argument(
614
+ help="Arguments for the script",
615
+ ),
616
+ ]
617
+
618
+
619
+ CommandArg = Annotated[
620
+ list[str],
621
+ Argument(
622
+ help="The command to run.",
623
+ ),
624
+ ]
625
+
626
+ JobIdArg = Annotated[
627
+ str,
628
+ Argument(
629
+ help="Job ID (or 'namespace/job_id')",
630
+ ),
631
+ ]
632
+
633
+ JobIdsArg = Annotated[
634
+ list[str] | None,
635
+ Argument(
636
+ help="Job IDs (or 'namespace/job_id')",
637
+ ),
638
+ ]
639
+
640
+ ScheduledJobIdArg = Annotated[
641
+ str,
642
+ Argument(
643
+ help="Scheduled Job ID (or 'namespace/scheduled_job_id')",
644
+ ),
645
+ ]
646
+
647
+ JobVolumesOpt = Annotated[
648
+ list[str] | None,
649
+ Option(
650
+ "-v",
651
+ "--volume",
652
+ help="Mount one or more volumes. Format: hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro|:rw] or LOCAL_DIR:/MOUNT_PATH[:ro|:rw]. "
653
+ "TYPE is one of: models, datasets, spaces, buckets. "
654
+ "TYPE defaults to models if omitted. "
655
+ "models, datasets and spaces are always mounted read-only. buckets are read+write by default. "
656
+ "A local directory source is first synced to a bucket and mounted read-only by default. "
657
+ "E.g. -v hf://datasets/org/ds:/data or -v hf://buckets/org/b:/mnt:ro or -v ./inputs:/inputs",
658
+ ),
659
+ ]
660
+
661
+
662
+ jobs_cli = typer_factory(help="Run and manage Jobs on the Hub.")
663
+
664
+
665
+ def _stream_logs_and_check_status(api: HfApi, job: JobInfo) -> None:
666
+ """Stream Job logs until the Job ends, then fail the command if the Job did not complete successfully."""
667
+ for log in api.fetch_job_logs(job_id=job.id, namespace=job.owner.name, follow=True):
668
+ out.text(log)
669
+ # The log stream can end while the Job is still scheduling or shutting down: settle the final state.
670
+ final = api.wait_for_job(job_id=job.id, namespace=job.owner.name)
671
+ if final.status.stage != JobStage.COMPLETED:
672
+ message = f": {final.status.message}" if final.status.message else ""
673
+ raise CLIError(f"Job {final.id} finished with stage '{final.status.stage}'{message}")
674
+ out.text(f"Job {final.id} completed")
675
+
676
+
677
+ def _hint_or_follow_started_job(api: HfApi, job: JobInfo, *, detach: bool) -> None:
678
+ """Print hints about how to reach a started Job, then stream its logs unless `detach` is set."""
679
+ job_ref = f"{job.owner.name}/{job.id}"
680
+ if isinstance(job.status.expose_urls, list):
681
+ urls = "\n".join(f" {url}" for url in job.status.expose_urls)
682
+ out.hint(f"Exposed ports are reachable at:\n{urls}")
683
+ if isinstance(job.status.ssh_url, str):
684
+ out.hint(f"Use `hf jobs ssh {job_ref}` to open an SSH session into the job.")
685
+ if isinstance(job.network, JobNetwork):
686
+ group = job.network.group
687
+ out.hint(
688
+ f"Joined network group '{group}'. Jobs of this namespace and resource group started with "
689
+ f"`--network-group {group}` reach each other at `$HF_NETWORK_GROUP_HOSTNAME` (every member) "
690
+ "or `${HF_NETWORK_GROUP_PREFIX}<alias>` (members claiming an alias)."
691
+ )
692
+ if detach:
693
+ out.hint(f"Use `hf jobs logs -f {job_ref}` to stream logs, or `hf jobs inspect {job_ref}` to check status.")
694
+ out.hint(f"Use `hf jobs wait {job_ref}` to block until it finishes.")
695
+ return
696
+ _stream_logs_and_check_status(api, job)
697
+
698
+
699
+ @jobs_cli.command(
700
+ "run",
701
+ context_settings={"ignore_unknown_options": True},
702
+ examples=[
703
+ "hf jobs run --name hello-world python:3.12 python -c 'print(\"Hello!\")'",
704
+ "hf jobs run --detach python:3.12 python script.py",
705
+ "hf jobs run -e FOO=foo python:3.12 python script.py",
706
+ "hf jobs run --secrets HF_TOKEN python:3.12 python script.py",
707
+ "hf jobs run -v hf://org/my-model:/data -v hf://buckets/org/b:/mnt python:3.12 python script.py",
708
+ ],
709
+ )
710
+ def jobs_run(
711
+ image: ImageArg,
712
+ command: CommandArg,
713
+ env: EnvOpt = None,
714
+ secrets: SecretsOpt = None,
715
+ name: NameOpt = None,
716
+ label: LabelsOpt = None,
717
+ volume: JobVolumesOpt = None,
718
+ env_file: EnvFileOpt = None,
719
+ secrets_file: SecretsFileOpt = None,
720
+ flavor: FlavorOpt = None,
721
+ timeout: TimeoutOpt = None,
722
+ attempts: AttemptsOpt = None,
723
+ detach: DetachOpt = False,
724
+ dry_run: DryRunOpt = False,
725
+ expose: ExposeOpt = None,
726
+ expose_public: ExposePublicOpt = None,
727
+ ssh: SshEnabledOpt = False,
728
+ network_group: NetworkGroupOpt = None,
729
+ network_alias: NetworkAliasOpt = None,
730
+ resource_group_id: ResourceGroupIdOpt = None,
731
+ namespace: NamespaceOpt = None,
732
+ token: TokenOpt = None,
733
+ format: FormatOpt = None,
734
+ json_output: JsonOpt = False,
735
+ quiet: QuietOpt = False,
736
+ ) -> None:
737
+ """Run a Job."""
738
+ set_output_format(format, json_output, quiet)
739
+ env_map = parse_env_map(env, env_file)
740
+ secrets_map = _parse_secrets_map(secrets, secrets_file, dry_run=dry_run)
741
+ labels_map = _parse_labels_map(label, name=name) or {}
742
+ labels_map.setdefault(
743
+ "name",
744
+ _default_job_name_from_image(
745
+ image,
746
+ command,
747
+ config_parts=_name_hash_parts(
748
+ flavor=flavor,
749
+ timeout=timeout,
750
+ extra=[str(attempts)] if attempts is not None else None,
751
+ namespace=namespace,
752
+ env=env_map,
753
+ secrets=secrets_map,
754
+ volume_specs=volume or [],
755
+ network_group=network_group,
756
+ network_aliases=network_alias,
757
+ ),
758
+ ),
759
+ )
760
+
761
+ api = get_hf_api(token=token)
762
+ volumes = None if dry_run else _parse_and_sync_job_volumes(volume, api=api, namespace=namespace)
763
+ _print_job_summary(
764
+ {
765
+ "image": image,
766
+ "command": shlex.join(command),
767
+ "flavor": flavor or JobHardware.CPU_BASIC.value,
768
+ "timeout": timeout,
769
+ "attempts": attempts,
770
+ "env": env_map,
771
+ "secrets": secrets_map,
772
+ "volumes": volume or [],
773
+ "labels": labels_map,
774
+ "expose": " ".join(str(port) for port in expose or []),
775
+ "expose_public": " ".join(str(port) for port in expose_public or []),
776
+ "ssh": ssh,
777
+ "network_group": network_group,
778
+ "network_aliases": " ".join(network_alias or []),
779
+ "resource_group_id": resource_group_id,
780
+ "namespace": namespace,
781
+ },
782
+ dry_run=dry_run,
783
+ )
784
+ if dry_run:
785
+ return
786
+ job = api.run_job(
787
+ image=image,
788
+ command=command,
789
+ env=env_map,
790
+ secrets=secrets_map,
791
+ labels=labels_map,
792
+ volumes=volumes,
793
+ flavor=flavor,
794
+ timeout=timeout,
795
+ attempts=attempts,
796
+ expose=expose,
797
+ expose_public=expose_public,
798
+ ssh=ssh,
799
+ network_group=network_group,
800
+ network_aliases=network_alias,
801
+ resource_group_id=resource_group_id,
802
+ namespace=namespace,
803
+ )
804
+ out.result("Job started", id=job.id, name=(job.labels or {}).get("name"), url=job.url)
805
+ if not _has_explicit_name(name, label):
806
+ auto_name = (job.labels or {}).get("name")
807
+ out.hint(
808
+ f"Job auto-named '{auto_name}'. Pass `--name` or run "
809
+ f"`hf jobs labels {job.owner.name}/{job.id} --name NAME` to rename it."
810
+ )
811
+ _hint_or_follow_started_job(api, job, detach=detach)
812
+
813
+
814
+ @jobs_cli.command(
815
+ "logs",
816
+ examples=[
817
+ "hf jobs logs <job_id>",
818
+ "hf jobs logs -f <job_id>",
819
+ "hf jobs logs --tail 20 <job_id>",
820
+ "hf jobs logs -f --tail 100 <job_id>",
821
+ ],
822
+ )
823
+ def jobs_logs(
824
+ job_id: JobIdArg,
825
+ follow: Annotated[
826
+ bool,
827
+ Option(
828
+ "-f",
829
+ "--follow",
830
+ help="Follow log output (stream until the job completes). Without this flag, only currently available logs are printed.",
831
+ ),
832
+ ] = False,
833
+ tail: Annotated[
834
+ int | None,
835
+ Option(
836
+ "-n",
837
+ "--tail",
838
+ help="Number of lines to show from the end of the logs. When combined with --follow, starts streaming from the last N lines.",
839
+ ),
840
+ ] = None,
841
+ namespace: NamespaceOpt = None,
842
+ token: TokenOpt = None,
843
+ ) -> None:
844
+ """Fetch the logs of a Job.
845
+
846
+ By default, prints currently available logs and exits (non-blocking).
847
+ Use --follow/-f to stream logs in real-time until the job completes.
848
+ Use --tail/-n to limit the number of lines returned (server-side when supported).
849
+
850
+ Note: following exits when the log stream ends, regardless of whether the Job
851
+ succeeded or failed. Run `hf jobs inspect <job_id>` to check the final status.
852
+ """
853
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
854
+
855
+ api = get_hf_api(token=token)
856
+ logs = api.fetch_job_logs(job_id=job_id, namespace=namespace, follow=follow, tail=tail)
857
+ for log in logs:
858
+ out.text(log)
859
+ job_ref = f"{namespace}/{job_id}" if namespace else job_id
860
+ if follow:
861
+ out.hint(f"Stream ended. Run `hf jobs inspect {job_ref}` to check the final status (e.g. COMPLETED or ERROR).")
862
+ else:
863
+ out.hint(
864
+ f"If the job is still running, use `hf jobs logs -f {job_ref}` to stream new logs until it completes."
865
+ )
866
+
867
+
868
+ def _clear_line(n: int) -> None:
869
+ LINE_UP = "\033[1A"
870
+ LINE_CLEAR = "\x1b[2K"
871
+ for i in range(n):
872
+ print(LINE_UP, end=LINE_CLEAR)
873
+
874
+
875
+ def _format_job_stats_rows(job_id: str, metrics: dict[str, Any], table_headers: list[str]) -> list[list[str | int]]:
876
+ row: list[str | int] = [
877
+ job_id,
878
+ f"{metrics['cpu_usage_pct']}%",
879
+ round(metrics["cpu_millicores"] / 1000.0, 1),
880
+ f"{round(100 * metrics['memory_used_bytes'] / metrics['memory_total_bytes'], 2)}%",
881
+ f"{_format_size(metrics['memory_used_bytes'])}B / {_format_size(metrics['memory_total_bytes'])}B",
882
+ f"{_format_size(metrics['rx_bps'])}bps / {_format_size(metrics['tx_bps'])}bps",
883
+ ]
884
+ if metrics["gpus"] and isinstance(metrics["gpus"], dict):
885
+ rows: list[list[str | int]] = [row] + [[""] * len(row) for _ in range(len(metrics["gpus"]) - 1)]
886
+ for row, gpu_id in zip(rows, sorted(metrics["gpus"])):
887
+ gpu = metrics["gpus"][gpu_id]
888
+ row += [
889
+ f"{gpu['utilization']}%",
890
+ f"{round(100 * gpu['memory_used_bytes'] / gpu['memory_total_bytes'], 2)}%",
891
+ f"{_format_size(gpu['memory_used_bytes'])}B / {_format_size(gpu['memory_total_bytes'])}B",
892
+ ]
893
+ return rows
894
+ row += ["N/A"] * (len(table_headers) - len(row))
895
+ return [row]
896
+
897
+
898
+ def _get_jobs_stats_rows(
899
+ job_id: str, metrics_stream: Iterable[dict[str, Any]], table_headers: list[str]
900
+ ) -> Iterable[tuple[bool, str, list[list[str | int]]]]:
901
+ for metrics in metrics_stream:
902
+ yield False, job_id, _format_job_stats_rows(job_id, metrics, table_headers)
903
+ yield True, job_id, []
904
+
905
+
906
+ @jobs_cli.command(
907
+ "stats",
908
+ examples=[
909
+ "hf jobs stats",
910
+ "hf jobs stats <job_id>",
911
+ "hf jobs stats -f <job_id>",
912
+ ],
913
+ )
914
+ def jobs_stats(
915
+ job_ids: JobIdsArg = None,
916
+ follow: Annotated[
917
+ bool,
918
+ Option(
919
+ "-f",
920
+ "--follow",
921
+ help="Follow stats output (live view until the Jobs complete). Without this flag, a single snapshot is printed.",
922
+ ),
923
+ ] = False,
924
+ namespace: NamespaceOpt = None,
925
+ token: TokenOpt = None,
926
+ ) -> None:
927
+ """Fetch the resource usage statistics and metrics of Jobs.
928
+
929
+ By default, prints a snapshot of the current stats and exits (non-blocking).
930
+ Use --follow/-f to display live stats until the Jobs complete.
931
+ """
932
+ if follow and out.mode != OutputFormat.human:
933
+ raise CLIError(
934
+ f"`--follow` displays a live terminal view and is not supported with '{out.mode.value}' output."
935
+ " Run without `--follow` to get a snapshot."
936
+ )
937
+ if job_ids is not None:
938
+ parsed_ids = []
939
+ for job_id in job_ids:
940
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
941
+ parsed_ids.append(job_id)
942
+ job_ids = parsed_ids
943
+ api = get_hf_api(token=token)
944
+ if namespace is None:
945
+ namespace = api.whoami()["name"]
946
+ if job_ids is None:
947
+ job_ids = [
948
+ job.id
949
+ for job in api.list_jobs(namespace=namespace)
950
+ if (job.status.stage if job.status else "UNKNOWN") in ("RUNNING", "UPDATING")
951
+ ]
952
+ if len(job_ids) == 0:
953
+ out.table([])
954
+ out.hint("No running jobs. Use `hf jobs ps -a` to list finished (and failed) jobs.")
955
+ return
956
+ table_headers = [
957
+ "JOB ID",
958
+ "CPU %",
959
+ "NUM CPU",
960
+ "MEM %",
961
+ "MEM USAGE",
962
+ "NET I/O",
963
+ "GPU UTIL %",
964
+ "GPU MEM %",
965
+ "GPU MEM USAGE",
966
+ ]
967
+ if not follow:
968
+
969
+ def fetch_latest_metrics(job_id: str) -> dict[str, Any] | None:
970
+ return next(iter(api.fetch_job_metrics(job_id=job_id, namespace=namespace)), None)
971
+
972
+ with multiprocessing.pool.ThreadPool(len(job_ids)) as pool:
973
+ latest_metrics = pool.map(fetch_latest_metrics, job_ids)
974
+ items = []
975
+ for job_id, metrics in zip(job_ids, latest_metrics):
976
+ if metrics is None:
977
+ out.warning(f"No stats available for Job {job_id}. Is it running?")
978
+ else:
979
+ items.append({"job_id": job_id, **metrics})
980
+ if out.mode == OutputFormat.human and items:
981
+ rows = [row for item in items for row in _format_job_stats_rows(item["job_id"], item, table_headers)]
982
+ out.text(_tabulate(rows, headers=table_headers))
983
+ job_refs = " ".join(f"{namespace}/{item['job_id']}" for item in items)
984
+ out.hint(f"Use `hf jobs stats -f {job_refs}` to follow live stats.")
985
+ else:
986
+ out.table(items, id_key="job_id")
987
+ return
988
+ with multiprocessing.pool.ThreadPool(len(job_ids)) as pool:
989
+ rows_per_job_id: dict[str, list[list[str | int]]] = {}
990
+ for job_id in job_ids:
991
+ row: list[str | int] = [job_id]
992
+ row += ["-- / --" if ("/" in header or "USAGE" in header) else "--" for header in table_headers[1:]]
993
+ rows_per_job_id[job_id] = [row]
994
+ last_update_time = time.time()
995
+ total_rows = [row for job_id in rows_per_job_id for row in rows_per_job_id[job_id]]
996
+ # In-place refresh (cursor-up + clear) requires a fixed line count and layout —
997
+ # `out.table`'s mode-dependent formatting would break it.
998
+ print(_tabulate(total_rows, headers=table_headers))
999
+
1000
+ kwargs_list = [
1001
+ {
1002
+ "job_id": job_id,
1003
+ "metrics_stream": api.fetch_job_metrics(job_id=job_id, namespace=namespace, follow=True),
1004
+ "table_headers": table_headers,
1005
+ }
1006
+ for job_id in job_ids
1007
+ ]
1008
+ for done, job_id, rows in iflatmap_unordered(pool, _get_jobs_stats_rows, kwargs_list=kwargs_list):
1009
+ if done:
1010
+ rows_per_job_id.pop(job_id, None)
1011
+ else:
1012
+ rows_per_job_id[job_id] = rows
1013
+ now = time.time()
1014
+ if now - last_update_time >= STATS_UPDATE_MIN_INTERVAL:
1015
+ _clear_line(2 + len(total_rows))
1016
+ total_rows = [row for job_id in rows_per_job_id for row in rows_per_job_id[job_id]]
1017
+ print(_tabulate(total_rows, headers=table_headers))
1018
+ last_update_time = now
1019
+ job_refs = " ".join(f"{namespace}/{job_id}" for job_id in job_ids)
1020
+ out.hint(f"Stream ended. Run `hf jobs inspect {job_refs}` to check the final status (e.g. COMPLETED or ERROR).")
1021
+
1022
+
1023
+ @jobs_cli.command(
1024
+ "list | ls | ps",
1025
+ examples=[
1026
+ "hf jobs ls",
1027
+ "hf jobs ls -a",
1028
+ "hf jobs ls --status running,scheduling",
1029
+ "hf jobs ls --name training-v2",
1030
+ "hf jobs ls --label env=prod --label team=ml",
1031
+ "hf jobs ls --all --label hf-sandbox=1",
1032
+ ],
1033
+ )
1034
+ def jobs_ps(
1035
+ all: Annotated[
1036
+ bool,
1037
+ Option(
1038
+ "-a",
1039
+ "--all",
1040
+ help="Show all Jobs (default shows running and scheduling). Cannot be combined with --status.",
1041
+ ),
1042
+ ] = False,
1043
+ status: Annotated[
1044
+ list[str] | None,
1045
+ Option(
1046
+ "--status",
1047
+ click_type=SoftChoice(JobStage),
1048
+ help="Only show Jobs with the given status. Comma-separated or repeated, e.g. `--status running,scheduling`.",
1049
+ ),
1050
+ ] = None,
1051
+ label: Annotated[
1052
+ list[str] | None,
1053
+ Option(
1054
+ "-l",
1055
+ "--label",
1056
+ help="Only show Jobs with the given `key=value` label. Repeat to require several labels, e.g. `--label env=prod --label team=ml`.",
1057
+ ),
1058
+ ] = None,
1059
+ name: Annotated[
1060
+ str | None,
1061
+ Option(
1062
+ "--name",
1063
+ help="Only show Jobs with the given name (shortcut for `--label name=NAME`).",
1064
+ ),
1065
+ ] = None,
1066
+ limit: Annotated[
1067
+ int,
1068
+ Option(
1069
+ "--limit",
1070
+ help="Maximum number of Jobs to display. Set to 0 to show all (no limit).",
1071
+ ),
1072
+ ] = 100,
1073
+ namespace: NamespaceOpt = None,
1074
+ token: TokenOpt = None,
1075
+ ) -> None:
1076
+ """List Jobs.
1077
+
1078
+ Use `--status` to filter by status (see [`JobStage`] for possible values) and `--label` to filter by `key=value`
1079
+ labels. A Job must match every filter to be listed.
1080
+ """
1081
+ api = get_hf_api(token=token)
1082
+
1083
+ if all and status:
1084
+ raise CLIError("`-a`/`--all` cannot be combined with `--status`.")
1085
+
1086
+ # Status filtering (default to active Jobs, unless `--all` or `--status` is provided).
1087
+ raw_statuses: list[str] = []
1088
+ for value in status or []:
1089
+ raw_statuses.extend(part.strip() for part in value.split(",") if part.strip())
1090
+
1091
+ server_statuses: list[str] | None
1092
+ if raw_statuses:
1093
+ server_statuses = raw_statuses
1094
+ elif all:
1095
+ server_statuses = None
1096
+ else:
1097
+ server_statuses = [JobStage.RUNNING.value, JobStage.SCHEDULING.value]
1098
+
1099
+ # Labels filtering
1100
+ labels: dict[str, str] = {}
1101
+ for item in label or []:
1102
+ if "=" not in item:
1103
+ raise CLIError(f"Invalid label filter '{item}': must be in the form 'key=value'")
1104
+ key, value = item.split("=")
1105
+ labels[key] = value
1106
+
1107
+ # `--name` is a shortcut for the `name` label.
1108
+ if name is not None:
1109
+ if "name" in labels:
1110
+ raise CLIError("Cannot filter by both `--name` and `--label name=...`.")
1111
+ labels["name"] = name
1112
+
1113
+ jobs_iter = api.list_jobs(namespace=namespace, status=server_statuses, labels=labels or None)
1114
+
1115
+ # Apply the display limit. Fetch one extra Job to detect (and warn about) truncation.
1116
+ truncated = False
1117
+ if limit > 0:
1118
+ jobs = list(itertools.islice(jobs_iter, limit + 1))
1119
+ if len(jobs) > limit:
1120
+ truncated = True
1121
+ jobs = jobs[:limit]
1122
+ else:
1123
+ jobs = list(jobs_iter)
1124
+
1125
+ # Build display items. Augment the raw api dict with curated, table-friendly columns.
1126
+ job_items: list[dict[str, Any]] = []
1127
+ for job in jobs:
1128
+ job_item = _dataclass_to_dict(job)
1129
+ durations = job_item.get("durations") or {}
1130
+ cmd = job_item.get("command") or []
1131
+ job_item["job_id"] = job_item.get("id", "")
1132
+ job_item["name"] = (job_item.get("labels") or {}).get("name") or "N/A"
1133
+ job_item["image/space"] = job_item.get("docker_image") or "N/A"
1134
+ job_item["command"] = " ".join(cmd) if cmd else "N/A"
1135
+ job_item["created"] = job_item["created_at"][:19].replace("T", " ") if job_item.get("created_at") else "N/A"
1136
+ job_item["status"] = (job_item.get("status") or {}).get("stage", "UNKNOWN")
1137
+ job_item["runtime"] = format_duration(durations.get("running_secs"))
1138
+ job_items.append(job_item)
1139
+
1140
+ out.table(
1141
+ job_items,
1142
+ headers=["job_id", "name", "image/space", "command", "created", "status", "runtime"],
1143
+ id_key="job_id",
1144
+ )
1145
+ if truncated:
1146
+ out.hint(f"Output truncated to {limit} Jobs. Use `--limit 0` to show all (or `--limit N`).")
1147
+ if not job_items:
1148
+ if raw_statuses or labels:
1149
+ filters_msg = ", ".join(
1150
+ [*(f"status={s}" for s in raw_statuses), *(f"label={k}={v}" for k, v in labels.items())]
1151
+ )
1152
+ out.text(f"No jobs matched filters: {filters_msg}")
1153
+ elif not all:
1154
+ out.hint("No running jobs. Use `-a`/`--all` to include finished (and failed) jobs.")
1155
+
1156
+
1157
+ @jobs_cli.command("hardware", examples=["hf jobs hardware"])
1158
+ def jobs_hardware() -> None:
1159
+ """List available hardware options for Jobs"""
1160
+ api = get_hf_api()
1161
+ hardware_list = api.list_jobs_hardware()
1162
+ items = []
1163
+ for hw in hardware_list:
1164
+ accelerator_info = ""
1165
+ if hw.accelerator:
1166
+ accelerator_info = f"{hw.accelerator.quantity}x {hw.accelerator.model} ({hw.accelerator.vram})"
1167
+ cost_min = f"${hw.unit_cost_usd:.4f}" if hw.unit_cost_usd else "free"
1168
+ cost_hour = f"${hw.unit_cost_usd * 60:.2f}" if hw.unit_cost_usd else "free"
1169
+ items.append(
1170
+ {
1171
+ "name": hw.name,
1172
+ "pretty name": hw.pretty_name,
1173
+ "cpu": hw.cpu,
1174
+ "ram": hw.ram,
1175
+ "storage": hw.ephemeral_storage,
1176
+ "accelerator": accelerator_info,
1177
+ "cost/min": cost_min,
1178
+ "cost/hour": cost_hour,
1179
+ }
1180
+ )
1181
+ out.table(items)
1182
+ out.hint("Use `hf jobs run --flavor <name> ...` to request a specific hardware flavor.")
1183
+
1184
+
1185
+ @jobs_cli.command("inspect", examples=["hf jobs inspect <job_id>"])
1186
+ def jobs_inspect(
1187
+ job_ids: Annotated[
1188
+ list[str],
1189
+ Argument(
1190
+ help="Job IDs to inspect (or 'namespace/job_id')",
1191
+ ),
1192
+ ],
1193
+ namespace: NamespaceOpt = None,
1194
+ token: TokenOpt = None,
1195
+ ) -> None:
1196
+ """Display detailed information on one or more Jobs"""
1197
+ parsed_ids = []
1198
+ for job_id in job_ids:
1199
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
1200
+ parsed_ids.append(job_id)
1201
+ job_ids = parsed_ids
1202
+ api = get_hf_api(token=token)
1203
+ jobs = [api.inspect_job(job_id=job_id, namespace=namespace) for job_id in job_ids]
1204
+ out.table([_surface_name(_dataclass_to_dict(job), labels=job.labels) for job in jobs], id_key="id")
1205
+
1206
+
1207
+ @jobs_cli.command("rerun", examples=["hf jobs rerun <job_id>", "hf jobs rerun --detach <job_id>"])
1208
+ def jobs_rerun(
1209
+ job_id: JobIdArg,
1210
+ detach: DetachOpt = False,
1211
+ namespace: NamespaceOpt = None,
1212
+ token: TokenOpt = None,
1213
+ ) -> None:
1214
+ """Run a new Job with an existing Job's spec."""
1215
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
1216
+ api = get_hf_api(token=token)
1217
+ job = api.rerun_job(job_id=job_id, namespace=namespace)
1218
+ out.result("Job started", id=job.id, name=(job.labels or {}).get("name"), url=job.url)
1219
+ _hint_or_follow_started_job(api, job, detach=detach)
1220
+
1221
+
1222
+ @jobs_cli.command(
1223
+ "expose",
1224
+ examples=[
1225
+ "hf jobs expose <job_id> 8000",
1226
+ "hf jobs expose <job_id> 8000 --public 9000",
1227
+ "hf jobs expose <job_id> --clear",
1228
+ ],
1229
+ )
1230
+ def jobs_expose(
1231
+ job_id: JobIdArg,
1232
+ ports: Annotated[
1233
+ list[int] | None,
1234
+ Argument(
1235
+ help="Ports to expose through the jobs proxy. Access requires an HF token with read access to the job's namespace."
1236
+ ),
1237
+ ] = None,
1238
+ public: Annotated[
1239
+ list[int] | None,
1240
+ Option(
1241
+ "--public",
1242
+ help="Expose a port without authentication. Repeat the flag for multiple ports. No need to also pass the port as a positional argument.",
1243
+ ),
1244
+ ] = None,
1245
+ clear: Annotated[bool, Option("--clear", help="Close all exposed ports.")] = False,
1246
+ namespace: NamespaceOpt = None,
1247
+ token: TokenOpt = None,
1248
+ ) -> None:
1249
+ """Replace exposed ports on a running Job."""
1250
+ if clear and (ports or public):
1251
+ raise CLIError("`--clear` cannot be combined with ports or `--public`.")
1252
+ if not clear and not ports and not public:
1253
+ raise CLIError("Pass at least one port or `--public` port, or `--clear` to close all ports.")
1254
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
1255
+ api = get_hf_api(token=token)
1256
+ job = api.update_job_expose(job_id=job_id, expose=ports, expose_public=public, namespace=namespace)
1257
+ out.result("Exposed ports updated", id=job.id, ports=job.expose or [], public_ports=job.expose_public or [])
1258
+
1259
+
1260
+ @jobs_cli.command("cancel", examples=["hf jobs cancel <job_id>"])
1261
+ def jobs_cancel(
1262
+ job_id: JobIdArg,
1263
+ namespace: NamespaceOpt = None,
1264
+ token: TokenOpt = None,
1265
+ ) -> None:
1266
+ """Cancel a Job"""
1267
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
1268
+ api = get_hf_api(token=token)
1269
+ api.cancel_job(job_id=job_id, namespace=namespace)
1270
+ out.result("Job cancelled", id=job_id)
1271
+
1272
+
1273
+ @jobs_cli.command(
1274
+ "wait",
1275
+ examples=[
1276
+ "hf jobs wait <job_id>",
1277
+ "hf jobs wait <job_id_1> <job_id_2>",
1278
+ "hf jobs ls -q | xargs hf jobs wait",
1279
+ ],
1280
+ )
1281
+ def jobs_wait(
1282
+ job_ids: Annotated[
1283
+ list[str],
1284
+ Argument(
1285
+ help="Job IDs to wait for (or 'namespace/job_id').",
1286
+ ),
1287
+ ],
1288
+ timeout: Annotated[
1289
+ str | None,
1290
+ Option(
1291
+ help="Max time to wait: int with s (seconds, default), m (minutes), h (hours) or d (days).",
1292
+ ),
1293
+ ] = None,
1294
+ namespace: NamespaceOpt = None,
1295
+ token: TokenOpt = None,
1296
+ ) -> None:
1297
+ """Wait for one or more Jobs to reach a terminal state.
1298
+
1299
+ Blocks until every Job has finished, then exits with code 0 if all Jobs completed
1300
+ successfully, or a non-zero exit code if any Job was canceled, errored or deleted.
1301
+
1302
+ All Jobs must belong to the same namespace.
1303
+ """
1304
+ parsed_ids = []
1305
+ namespaces = set()
1306
+ for job_id in job_ids:
1307
+ parsed_id, parsed_namespace = _parse_namespace_from_job_id(job_id, namespace)
1308
+ parsed_ids.append(parsed_id)
1309
+ namespaces.add(parsed_namespace)
1310
+ if len(namespaces) > 1:
1311
+ raise CLIError(
1312
+ "All Job IDs must be in the same namespace, got: "
1313
+ + ", ".join(str(ns) for ns in sorted(namespaces, key=str))
1314
+ )
1315
+ namespace = namespaces.pop()
1316
+ timeout_secs = parse_duration(timeout) if timeout is not None else None
1317
+
1318
+ api = get_hf_api(token=token)
1319
+ status = out.status(f"Waiting for {len(parsed_ids)} Job(s) to finish...")
1320
+ try:
1321
+ jobs = api.wait_for_job(parsed_ids, timeout=timeout_secs, namespace=namespace)
1322
+ except TimeoutError:
1323
+ status.done("Timed out.")
1324
+ raise CLIError(f"Timed out after {timeout} waiting for Job(s) to finish.") from None
1325
+ status.done(f"{len(jobs)} Job(s) finished.")
1326
+
1327
+ out.table([{"id": job.id, "stage": str(job.status.stage), "message": job.status.message} for job in jobs])
1328
+ failed = [job for job in jobs if job.status.stage != JobStage.COMPLETED]
1329
+ if failed:
1330
+ raise CLIError(
1331
+ f"{len(failed)} of {len(jobs)} Job(s) did not complete successfully: "
1332
+ + ", ".join(f"{job.id} ({job.status.stage})" for job in failed)
1333
+ )
1334
+
1335
+
1336
+ @jobs_cli.command(
1337
+ "labels",
1338
+ examples=[
1339
+ "hf jobs labels <job_id> --name training-v2",
1340
+ "hf jobs labels <job_id> --label env=prod --label team=ml",
1341
+ "hf jobs labels <job_id> --clear",
1342
+ ],
1343
+ )
1344
+ def jobs_labels(
1345
+ job_id: JobIdArg,
1346
+ name: NameOpt = None,
1347
+ label: LabelsOpt = None,
1348
+ clear: Annotated[bool, Option("--clear", help="Remove all labels from the job.")] = False,
1349
+ namespace: NamespaceOpt = None,
1350
+ token: TokenOpt = None,
1351
+ ) -> None:
1352
+ """Update labels on a Job. Passing --label replaces all existing labels; passing --name alone keeps them."""
1353
+ if not label and name is None and not clear:
1354
+ raise CLIError(
1355
+ "Please set a name with --name or at least one label with --label. To remove all labels, pass --clear."
1356
+ )
1357
+ if (label or name is not None) and clear:
1358
+ raise CLIError(
1359
+ "Cannot set a name or labels and clear them at the same time. Please use --name/--label or --clear, not both."
1360
+ )
1361
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
1362
+ api = get_hf_api(token=token)
1363
+ if name is not None and not label:
1364
+ # Naming a Job should not wipe its existing labels: fetch them and merge the name in.
1365
+ current_labels = api.inspect_job(job_id=job_id, namespace=namespace).labels or {}
1366
+ labels = {**current_labels, "name": name}
1367
+ else:
1368
+ labels = _parse_labels_map(label, name=name) or {}
1369
+ job = api.update_job_labels(job_id=job_id, labels=labels, namespace=namespace)
1370
+ out.result("Labels updated", id=job.id, name=labels.get("name"))
1371
+
1372
+
1373
+ @jobs_cli.command(
1374
+ "ssh",
1375
+ examples=[
1376
+ "hf jobs ssh <job_id>",
1377
+ "hf jobs ssh <job_id> --dry-run",
1378
+ "hf jobs ssh <job_id> -i ~/.ssh/id_ed25519",
1379
+ ],
1380
+ )
1381
+ def jobs_ssh(
1382
+ job_id: JobIdArg,
1383
+ identity_file: SshIdentityFileOpt = None,
1384
+ dry_run: SshDryRunOpt = False,
1385
+ namespace: NamespaceOpt = None,
1386
+ token: TokenOpt = None,
1387
+ ) -> None:
1388
+ """SSH into a running Job.
1389
+
1390
+ If the Job is not yet running, waits until it reaches the RUNNING state before
1391
+ connecting. Requires the Job to be started with SSH enabled (`hf jobs run --ssh ...`)
1392
+ and your SSH public key to be registered at https://huggingface.co/settings/keys.
1393
+ """
1394
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
1395
+ api = get_hf_api(token=token)
1396
+ job = api.inspect_job(job_id=job_id, namespace=namespace)
1397
+ if job.status.ssh_url is None:
1398
+ raise CLIError("SSH is not enabled on this job. Start a job with SSH support using `hf jobs run --ssh ...`.")
1399
+ if job.status.stage in TERMINAL_JOB_STAGES:
1400
+ raise CLIError(f"Cannot SSH into job '{job.id}': job has already finished (stage: '{job.status.stage}').")
1401
+ if job.status.stage != JobStage.RUNNING:
1402
+ status = out.status(f"Waiting for job '{job.id}' to be running (stage: '{job.status.stage}')...")
1403
+ job = api.wait_for_job(job_id=job.id, namespace=namespace, stages=[JobStage.RUNNING])
1404
+ if job.status.stage != JobStage.RUNNING:
1405
+ status.done("Job finished.")
1406
+ raise CLIError(
1407
+ f"Cannot SSH into job '{job.id}': job finished before reaching RUNNING (stage: '{job.status.stage}')."
1408
+ )
1409
+ status.done("Job is running.")
1410
+ ssh_url = urlsplit(job.status.ssh_url)
1411
+ exec_ssh(
1412
+ f"{ssh_url.username}@{ssh_url.hostname}", # type: ignore
1413
+ port=ssh_url.port,
1414
+ identity_file=identity_file,
1415
+ dry_run=dry_run,
1416
+ )
1417
+
1418
+
1419
+ uv_app = typer_factory(help="Run UV scripts (Python with inline dependencies) on HF infrastructure.")
1420
+ jobs_cli.add_group(uv_app, name="uv")
1421
+
1422
+
1423
+ @uv_app.command(
1424
+ "run",
1425
+ context_settings={"ignore_unknown_options": True},
1426
+ examples=[
1427
+ "hf jobs uv run --name my-script my_script.py",
1428
+ "hf jobs uv run --detach my_script.py",
1429
+ "hf jobs uv run --flavor a10g-small ml_training.py",
1430
+ "hf jobs uv run --with transformers train.py",
1431
+ "hf jobs uv run -v hf://org/my-model:/data -v hf://buckets/org/b:/mnt script.py",
1432
+ "hf jobs uv run --dry-run script.py",
1433
+ ],
1434
+ )
1435
+ def jobs_uv_run(
1436
+ script: ScriptArg,
1437
+ script_args: ScriptArgsArg = None,
1438
+ image: ImageOpt = None,
1439
+ flavor: FlavorOpt = None,
1440
+ env: EnvOpt = None,
1441
+ secrets: SecretsOpt = None,
1442
+ name: NameOpt = None,
1443
+ label: LabelsOpt = None,
1444
+ volume: JobVolumesOpt = None,
1445
+ env_file: EnvFileOpt = None,
1446
+ secrets_file: SecretsFileOpt = None,
1447
+ timeout: TimeoutOpt = None,
1448
+ attempts: AttemptsOpt = None,
1449
+ detach: DetachOpt = False,
1450
+ dry_run: DryRunOpt = False,
1451
+ expose: ExposeOpt = None,
1452
+ expose_public: ExposePublicOpt = None,
1453
+ ssh: SshEnabledOpt = False,
1454
+ network_group: NetworkGroupOpt = None,
1455
+ network_alias: NetworkAliasOpt = None,
1456
+ resource_group_id: ResourceGroupIdOpt = None,
1457
+ namespace: NamespaceOpt = None,
1458
+ token: TokenOpt = None,
1459
+ with_: WithOpt = None,
1460
+ python: PythonOpt = None,
1461
+ format: FormatOpt = None,
1462
+ json_output: JsonOpt = False,
1463
+ quiet: QuietOpt = False,
1464
+ ) -> None:
1465
+ """Run a UV script (local file or URL) on HF infrastructure"""
1466
+ set_output_format(format, json_output, quiet)
1467
+ api = get_hf_api(token=token)
1468
+ with _resolve_uv_job_config(
1469
+ api=api,
1470
+ script=script,
1471
+ script_args=script_args,
1472
+ dependencies=with_,
1473
+ image=image,
1474
+ flavor=flavor,
1475
+ python=python,
1476
+ env=env,
1477
+ env_file=env_file,
1478
+ secrets=secrets,
1479
+ secrets_file=secrets_file,
1480
+ timeout=timeout,
1481
+ attempts=attempts,
1482
+ name=name,
1483
+ label=label,
1484
+ volume=volume,
1485
+ namespace=namespace,
1486
+ network_group=network_group,
1487
+ network_aliases=network_alias,
1488
+ dry_run=dry_run,
1489
+ ) as config:
1490
+ _print_job_summary(
1491
+ {
1492
+ "script": script,
1493
+ "args": shlex.join(config.script_args),
1494
+ "with": " ".join(with_ or []),
1495
+ "image": config.image or DEFAULT_UV_IMAGE,
1496
+ "flavor": config.flavor or JobHardware.CPU_BASIC.value,
1497
+ "python": config.python,
1498
+ "timeout": config.timeout,
1499
+ "attempts": attempts,
1500
+ "env": config.env,
1501
+ "secrets": config.secrets,
1502
+ "volumes": config.volume_specs,
1503
+ "labels": config.labels,
1504
+ "expose": " ".join(str(port) for port in expose or []),
1505
+ "expose_public": " ".join(str(port) for port in expose_public or []),
1506
+ "ssh": ssh,
1507
+ "network_group": config.network_group,
1508
+ "network_aliases": " ".join(config.network_aliases),
1509
+ "resource_group_id": resource_group_id,
1510
+ "namespace": config.namespace,
1511
+ },
1512
+ from_script=config.from_script,
1513
+ dry_run=dry_run,
1514
+ )
1515
+ if dry_run:
1516
+ return
1517
+ job = api.run_uv_job(
1518
+ script=config.script,
1519
+ script_args=config.script_args,
1520
+ dependencies=with_,
1521
+ python=config.python,
1522
+ image=config.image,
1523
+ env=config.env,
1524
+ secrets=config.secrets,
1525
+ labels=config.labels,
1526
+ volumes=config.volumes,
1527
+ flavor=config.flavor,
1528
+ timeout=config.timeout,
1529
+ attempts=attempts,
1530
+ expose=expose,
1531
+ expose_public=expose_public,
1532
+ ssh=ssh,
1533
+ network_group=config.network_group,
1534
+ network_aliases=config.network_aliases or None,
1535
+ resource_group_id=resource_group_id,
1536
+ namespace=config.namespace,
1537
+ )
1538
+ out.result("Job started", id=job.id, name=(job.labels or {}).get("name"), url=job.url)
1539
+ if not _has_explicit_name(name, label, config.from_script):
1540
+ auto_name = (job.labels or {}).get("name")
1541
+ out.hint(
1542
+ f"Job auto-named '{auto_name}'. Pass `--name` or run "
1543
+ f"`hf jobs labels {job.owner.name}/{job.id} --name NAME` to rename it."
1544
+ )
1545
+ _hint_or_follow_started_job(api, job, detach=detach)
1546
+
1547
+
1548
+ class ScheduledJobStatusFilter(str, Enum):
1549
+ """Possible values for `hf jobs scheduled ls --status`.
1550
+
1551
+ Scheduled Jobs are not "running": they are either active (i.e. they will trigger new runs) or suspended.
1552
+ """
1553
+
1554
+ ACTIVE = "active"
1555
+ SUSPENDED = "suspended"
1556
+
1557
+
1558
+ scheduled_app = typer_factory(help="Create and manage scheduled Jobs on the Hub.")
1559
+ jobs_cli.add_group(scheduled_app, name="scheduled")
1560
+
1561
+
1562
+ @scheduled_app.command(
1563
+ "run",
1564
+ context_settings={"ignore_unknown_options": True},
1565
+ examples=['hf jobs scheduled run "0 0 * * *" --name daily-script python:3.12 python script.py'],
1566
+ )
1567
+ def scheduled_run(
1568
+ schedule: ScheduleArg,
1569
+ image: ImageArg,
1570
+ command: CommandArg,
1571
+ suspend: SuspendOpt = None,
1572
+ concurrency: ConcurrencyOpt = None,
1573
+ env: EnvOpt = None,
1574
+ secrets: SecretsOpt = None,
1575
+ name: NameOpt = None,
1576
+ label: LabelsOpt = None,
1577
+ volume: JobVolumesOpt = None,
1578
+ env_file: EnvFileOpt = None,
1579
+ secrets_file: SecretsFileOpt = None,
1580
+ flavor: FlavorOpt = None,
1581
+ timeout: TimeoutOpt = None,
1582
+ attempts: AttemptsOpt = None,
1583
+ dry_run: DryRunOpt = False,
1584
+ expose: ExposeOpt = None,
1585
+ expose_public: ExposePublicOpt = None,
1586
+ resource_group_id: ResourceGroupIdOpt = None,
1587
+ namespace: NamespaceOpt = None,
1588
+ token: TokenOpt = None,
1589
+ format: FormatOpt = None,
1590
+ json_output: JsonOpt = False,
1591
+ quiet: QuietOpt = False,
1592
+ ) -> None:
1593
+ """Schedule a Job."""
1594
+ set_output_format(format, json_output, quiet)
1595
+ env_map = parse_env_map(env, env_file)
1596
+ secrets_map = _parse_secrets_map(secrets, secrets_file, dry_run=dry_run)
1597
+ labels_map = _parse_labels_map(label, name=name) or {}
1598
+ labels_map.setdefault(
1599
+ "name",
1600
+ _default_job_name_from_image(
1601
+ image,
1602
+ command,
1603
+ config_parts=_name_hash_parts(
1604
+ flavor=flavor,
1605
+ timeout=timeout,
1606
+ extra=[str(attempts)] if attempts is not None else None,
1607
+ namespace=namespace,
1608
+ env=env_map,
1609
+ secrets=secrets_map,
1610
+ volume_specs=volume or [],
1611
+ ),
1612
+ ),
1613
+ )
1614
+
1615
+ api = get_hf_api(token=token)
1616
+ volumes = None if dry_run else _parse_and_sync_job_volumes(volume, api=api, namespace=namespace)
1617
+ _print_job_summary(
1618
+ {
1619
+ "schedule": schedule,
1620
+ "suspend": suspend,
1621
+ "concurrency": concurrency,
1622
+ "image": image,
1623
+ "command": shlex.join(command),
1624
+ "flavor": flavor or JobHardware.CPU_BASIC.value,
1625
+ "timeout": timeout,
1626
+ "attempts": attempts,
1627
+ "env": env_map,
1628
+ "secrets": secrets_map,
1629
+ "volumes": volume or [],
1630
+ "labels": labels_map,
1631
+ "expose": " ".join(str(port) for port in expose or []),
1632
+ "expose_public": " ".join(str(port) for port in expose_public or []),
1633
+ "resource_group_id": resource_group_id,
1634
+ "namespace": namespace,
1635
+ },
1636
+ dry_run=dry_run,
1637
+ )
1638
+ if dry_run:
1639
+ return
1640
+ scheduled_job = api.create_scheduled_job(
1641
+ image=image,
1642
+ command=command,
1643
+ schedule=schedule,
1644
+ suspend=suspend,
1645
+ concurrency=concurrency,
1646
+ env=env_map,
1647
+ secrets=secrets_map,
1648
+ labels=labels_map,
1649
+ volumes=volumes,
1650
+ flavor=flavor,
1651
+ timeout=timeout,
1652
+ attempts=attempts,
1653
+ expose=expose,
1654
+ expose_public=expose_public,
1655
+ resource_group_id=resource_group_id,
1656
+ namespace=namespace,
1657
+ )
1658
+ out.result("Scheduled Job created", id=scheduled_job.id, name=(scheduled_job.job_spec.labels or {}).get("name"))
1659
+ if not _has_explicit_name(name, label):
1660
+ auto_name = (scheduled_job.job_spec.labels or {}).get("name")
1661
+ out.hint(
1662
+ f"Scheduled Job auto-named '{auto_name}'. Pass `--name` or run "
1663
+ f"`hf jobs scheduled labels {scheduled_job.owner.name}/{scheduled_job.id} --name NAME` to rename it."
1664
+ )
1665
+ out.hint(f"Use `hf jobs scheduled inspect {scheduled_job.owner.name}/{scheduled_job.id}` to view its details.")
1666
+
1667
+
1668
+ @scheduled_app.command(
1669
+ "list | ls | ps",
1670
+ examples=[
1671
+ "hf jobs scheduled ls",
1672
+ "hf jobs scheduled ls -a",
1673
+ "hf jobs scheduled ls --status suspended",
1674
+ "hf jobs scheduled ls --name daily-script",
1675
+ "hf jobs scheduled ls --label env=prod --label team=ml",
1676
+ ],
1677
+ )
1678
+ def scheduled_ps(
1679
+ all: Annotated[
1680
+ bool,
1681
+ Option(
1682
+ "-a",
1683
+ "--all",
1684
+ help="Show all scheduled Jobs (default hides suspended). Cannot be combined with --status.",
1685
+ ),
1686
+ ] = False,
1687
+ status: Annotated[
1688
+ list[str] | None,
1689
+ Option(
1690
+ "--status",
1691
+ click_type=SoftChoice(ScheduledJobStatusFilter),
1692
+ help=(
1693
+ "Only show scheduled Jobs with the given status. Comma-separated or repeated, e.g."
1694
+ " `--status suspended`."
1695
+ ),
1696
+ ),
1697
+ ] = None,
1698
+ label: Annotated[
1699
+ list[str] | None,
1700
+ Option(
1701
+ "-l",
1702
+ "--label",
1703
+ help=(
1704
+ "Only show scheduled Jobs with the given `key=value` label. Repeat to require several labels, e.g."
1705
+ " `--label env=prod --label team=ml`."
1706
+ ),
1707
+ ),
1708
+ ] = None,
1709
+ name: Annotated[
1710
+ str | None,
1711
+ Option(
1712
+ "--name",
1713
+ help="Only show scheduled Jobs with the given name (shortcut for `--label name=NAME`).",
1714
+ ),
1715
+ ] = None,
1716
+ namespace: NamespaceOpt = None,
1717
+ token: TokenOpt = None,
1718
+ ) -> None:
1719
+ """List scheduled Jobs.
1720
+
1721
+ Use `--status` to filter by status (`active` or `suspended`) and `--label` to filter by `key=value` labels.
1722
+ A scheduled Job must match every filter to be listed.
1723
+ """
1724
+ api = get_hf_api(token=token)
1725
+
1726
+ if all and status:
1727
+ raise CLIError("`-a`/`--all` cannot be combined with `--status`.")
1728
+
1729
+ # Status filtering (default to active scheduled Jobs, unless `--all` or `--status` is provided).
1730
+ raw_statuses: list[str] = []
1731
+ for value in status or []:
1732
+ raw_statuses.extend(part.strip().lower() for part in value.split(",") if part.strip())
1733
+
1734
+ unknown_statuses = [s for s in raw_statuses if s not in tuple(ScheduledJobStatusFilter)]
1735
+ if unknown_statuses:
1736
+ raise CLIError(
1737
+ f"Invalid status filter(s) {unknown_statuses}: expected one of"
1738
+ f" {[s.value for s in ScheduledJobStatusFilter]}."
1739
+ )
1740
+
1741
+ if raw_statuses:
1742
+ show_active = ScheduledJobStatusFilter.ACTIVE in raw_statuses
1743
+ show_suspended = ScheduledJobStatusFilter.SUSPENDED in raw_statuses
1744
+ else:
1745
+ show_active = True
1746
+ show_suspended = all
1747
+
1748
+ # Labels filtering
1749
+ labels: dict[str, str] = {}
1750
+ for raw_label in label or []:
1751
+ if "=" not in raw_label:
1752
+ raise CLIError(f"Invalid label filter '{raw_label}': must be in the form 'key=value'")
1753
+ key, value = raw_label.split("=", 1)
1754
+ labels[key] = value
1755
+
1756
+ # `--name` is a shortcut for the `name` label.
1757
+ if name is not None:
1758
+ if "name" in labels:
1759
+ raise CLIError("Cannot filter by both `--name` and `--label name=...`.")
1760
+ labels["name"] = name
1761
+
1762
+ scheduled_jobs = api.list_scheduled_jobs(namespace=namespace, labels=labels or None)
1763
+
1764
+ filtered_jobs = []
1765
+ for scheduled_job in scheduled_jobs:
1766
+ suspend = scheduled_job.suspend or False
1767
+ if suspend and not show_suspended:
1768
+ continue
1769
+ if not suspend and not show_active:
1770
+ continue
1771
+ filtered_jobs.append(scheduled_job)
1772
+
1773
+ # Build display items. Augment with curated columns.
1774
+ items: list[dict[str, Any]] = []
1775
+ for sj in filtered_jobs:
1776
+ item = _dataclass_to_dict(sj)
1777
+ job_spec = item.get("job_spec") or {}
1778
+ status_dict = item.get("status") or {}
1779
+ last_job = status_dict.get("last_job")
1780
+ cmd = job_spec.get("command") or []
1781
+ item["name"] = (job_spec.get("labels") or {}).get("name") or "N/A"
1782
+ item["image/space"] = job_spec.get("docker_image") or "N/A"
1783
+ item["command"] = " ".join(cmd) if cmd else "N/A"
1784
+ item["last_run"] = last_job["at"][:19].replace("T", " ") if last_job and last_job.get("at") else "N/A"
1785
+ item["next_run"] = (
1786
+ status_dict["next_job_run_at"][:19].replace("T", " ") if status_dict.get("next_job_run_at") else "N/A"
1787
+ )
1788
+ item["suspend"] = item.get("suspend") or False
1789
+ items.append(item)
1790
+
1791
+ out.table(
1792
+ items,
1793
+ headers=["id", "name", "schedule", "image/space", "command", "last_run", "next_run", "suspend"],
1794
+ id_key="id",
1795
+ )
1796
+ if not items:
1797
+ if raw_statuses or labels:
1798
+ filters_msg = ", ".join(
1799
+ [*(f"status={s}" for s in raw_statuses), *(f"label={k}={v}" for k, v in labels.items())]
1800
+ )
1801
+ out.text(f"No scheduled jobs matched filters: {filters_msg}")
1802
+ elif not all:
1803
+ out.hint("No active scheduled jobs. Use `-a`/`--all` to include suspended ones.")
1804
+ if items:
1805
+ first_item_id = items[0]["id"]
1806
+ out.hint(f"Use `hf jobs scheduled inspect {first_item_id}` to view details about a scheduled job.")
1807
+ out.hint(f"Use `hf jobs scheduled trigger {first_item_id}` to trigger a scheduled job immediately.")
1808
+
1809
+
1810
+ @scheduled_app.command("inspect", examples=["hf jobs scheduled inspect <id>"])
1811
+ def scheduled_inspect(
1812
+ scheduled_job_ids: Annotated[
1813
+ list[str],
1814
+ Argument(
1815
+ help="Scheduled Job IDs to inspect (or 'namespace/scheduled_job_id')",
1816
+ ),
1817
+ ],
1818
+ namespace: NamespaceOpt = None,
1819
+ token: TokenOpt = None,
1820
+ ) -> None:
1821
+ """Display detailed information on one or more scheduled Jobs"""
1822
+ parsed_ids = []
1823
+ for job_id in scheduled_job_ids:
1824
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
1825
+ parsed_ids.append(job_id)
1826
+ scheduled_job_ids = parsed_ids
1827
+ api = get_hf_api(token=token)
1828
+ scheduled_jobs = [
1829
+ api.inspect_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1830
+ for scheduled_job_id in scheduled_job_ids
1831
+ ]
1832
+ out.table([_surface_name(_dataclass_to_dict(sj), labels=sj.job_spec.labels) for sj in scheduled_jobs], id_key="id")
1833
+
1834
+
1835
+ @scheduled_app.command("delete", examples=["hf jobs scheduled delete <id>"])
1836
+ def scheduled_delete(
1837
+ scheduled_job_id: ScheduledJobIdArg,
1838
+ namespace: NamespaceOpt = None,
1839
+ token: TokenOpt = None,
1840
+ ) -> None:
1841
+ """Delete a scheduled Job."""
1842
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1843
+ api = get_hf_api(token=token)
1844
+ api.delete_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1845
+ out.result("Scheduled Job deleted", id=scheduled_job_id)
1846
+
1847
+
1848
+ @scheduled_app.command("suspend", examples=["hf jobs scheduled suspend <id>"])
1849
+ def scheduled_suspend(
1850
+ scheduled_job_id: ScheduledJobIdArg,
1851
+ namespace: NamespaceOpt = None,
1852
+ token: TokenOpt = None,
1853
+ ) -> None:
1854
+ """Suspend (pause) a scheduled Job."""
1855
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1856
+ api = get_hf_api(token=token)
1857
+ api.suspend_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1858
+ out.result("Scheduled Job suspended", id=scheduled_job_id)
1859
+ out.hint(f"Use `hf jobs scheduled resume {scheduled_job_id}` to resume it.")
1860
+
1861
+
1862
+ @scheduled_app.command("resume", examples=["hf jobs scheduled resume <id>"])
1863
+ def scheduled_resume(
1864
+ scheduled_job_id: ScheduledJobIdArg,
1865
+ namespace: NamespaceOpt = None,
1866
+ token: TokenOpt = None,
1867
+ ) -> None:
1868
+ """Resume (unpause) a scheduled Job."""
1869
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1870
+ api = get_hf_api(token=token)
1871
+ api.resume_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1872
+ out.result("Scheduled Job resumed", id=scheduled_job_id)
1873
+
1874
+
1875
+ @scheduled_app.command("reschedule", examples=['hf jobs scheduled reschedule <id> "0 9 * * 1"'])
1876
+ def scheduled_reschedule(
1877
+ scheduled_job_id: ScheduledJobIdArg,
1878
+ schedule: ScheduleArg,
1879
+ namespace: NamespaceOpt = None,
1880
+ token: TokenOpt = None,
1881
+ ) -> None:
1882
+ """Change when a scheduled Job runs."""
1883
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1884
+ api = get_hf_api(token=token)
1885
+ job = api.update_scheduled_job_schedule(scheduled_job_id=scheduled_job_id, schedule=schedule, namespace=namespace)
1886
+ out.result("Scheduled Job rescheduled", id=job.id, schedule=job.schedule)
1887
+ out.hint(f"Use `hf jobs scheduled inspect {job.owner.name}/{job.id}` to see its next run.")
1888
+
1889
+
1890
+ @scheduled_app.command("trigger", examples=["hf jobs scheduled trigger <id>"])
1891
+ def scheduled_trigger(
1892
+ scheduled_job_id: ScheduledJobIdArg,
1893
+ namespace: NamespaceOpt = None,
1894
+ token: TokenOpt = None,
1895
+ ) -> None:
1896
+ """Trigger a scheduled Job to run immediately (does not change the schedule)."""
1897
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1898
+ api = get_hf_api(token=token)
1899
+ job = api.trigger_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1900
+ out.result("Scheduled Job triggered", id=job.id, url=job.url)
1901
+ out.hint(f"Use `hf jobs logs -f {job.owner.name}/{job.id}` to stream logs.")
1902
+
1903
+
1904
+ @scheduled_app.command(
1905
+ "labels",
1906
+ examples=[
1907
+ "hf jobs scheduled labels <id> --name daily-script",
1908
+ "hf jobs scheduled labels <id> --label env=prod --label team=ml",
1909
+ "hf jobs scheduled labels <id> --clear",
1910
+ ],
1911
+ )
1912
+ def scheduled_labels(
1913
+ scheduled_job_id: ScheduledJobIdArg,
1914
+ name: NameOpt = None,
1915
+ label: LabelsOpt = None,
1916
+ clear: Annotated[bool, Option("--clear", help="Remove all labels from the scheduled job.")] = False,
1917
+ namespace: NamespaceOpt = None,
1918
+ token: TokenOpt = None,
1919
+ ) -> None:
1920
+ """Update labels on a scheduled Job. Passing --label replaces all existing labels; passing --name alone keeps them."""
1921
+ if not label and name is None and not clear:
1922
+ raise CLIError(
1923
+ "Please set a name with --name or at least one label with --label. To remove all labels, pass --clear."
1924
+ )
1925
+ if (label or name is not None) and clear:
1926
+ raise CLIError(
1927
+ "Cannot set a name or labels and clear them at the same time. Please use --name/--label or --clear, not both."
1928
+ )
1929
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1930
+ api = get_hf_api(token=token)
1931
+ if name is not None and not label:
1932
+ # Naming a scheduled Job should not wipe its existing labels: fetch them and merge the name in.
1933
+ current_labels = (
1934
+ api.inspect_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace).job_spec.labels or {}
1935
+ )
1936
+ labels = {**current_labels, "name": name}
1937
+ else:
1938
+ labels = _parse_labels_map(label, name=name) or {}
1939
+ scheduled_job = api.update_scheduled_job_labels(
1940
+ scheduled_job_id=scheduled_job_id, labels=labels, namespace=namespace
1941
+ )
1942
+ out.result("Labels updated", id=scheduled_job.id, name=labels.get("name"))
1943
+
1944
+
1945
+ scheduled_uv_app = typer_factory(help="Schedule UV scripts on HF infrastructure.")
1946
+ scheduled_app.add_group(scheduled_uv_app, name="uv")
1947
+
1948
+
1949
+ @scheduled_uv_app.command(
1950
+ "run",
1951
+ context_settings={"ignore_unknown_options": True},
1952
+ examples=[
1953
+ 'hf jobs scheduled uv run "0 0 * * *" --name daily-script script.py',
1954
+ 'hf jobs scheduled uv run "0 0 * * *" script.py --with pandas',
1955
+ ],
1956
+ )
1957
+ def scheduled_uv_run(
1958
+ schedule: ScheduleArg,
1959
+ script: ScriptArg,
1960
+ script_args: ScriptArgsArg = None,
1961
+ suspend: SuspendOpt = None,
1962
+ concurrency: ConcurrencyOpt = None,
1963
+ image: ImageOpt = None,
1964
+ flavor: FlavorOpt = None,
1965
+ env: EnvOpt = None,
1966
+ secrets: SecretsOpt = None,
1967
+ name: NameOpt = None,
1968
+ label: LabelsOpt = None,
1969
+ volume: JobVolumesOpt = None,
1970
+ env_file: EnvFileOpt = None,
1971
+ secrets_file: SecretsFileOpt = None,
1972
+ timeout: TimeoutOpt = None,
1973
+ attempts: AttemptsOpt = None,
1974
+ dry_run: DryRunOpt = False,
1975
+ expose: ExposeOpt = None,
1976
+ expose_public: ExposePublicOpt = None,
1977
+ resource_group_id: ResourceGroupIdOpt = None,
1978
+ namespace: NamespaceOpt = None,
1979
+ token: TokenOpt = None,
1980
+ with_: WithOpt = None,
1981
+ python: PythonOpt = None,
1982
+ format: FormatOpt = None,
1983
+ json_output: JsonOpt = False,
1984
+ quiet: QuietOpt = False,
1985
+ ) -> None:
1986
+ """Run a UV script (local file or URL) on HF infrastructure"""
1987
+ set_output_format(format, json_output, quiet)
1988
+ api = get_hf_api(token=token)
1989
+ with _resolve_uv_job_config(
1990
+ api=api,
1991
+ script=script,
1992
+ script_args=script_args,
1993
+ dependencies=with_,
1994
+ image=image,
1995
+ flavor=flavor,
1996
+ python=python,
1997
+ env=env,
1998
+ env_file=env_file,
1999
+ secrets=secrets,
2000
+ secrets_file=secrets_file,
2001
+ timeout=timeout,
2002
+ attempts=attempts,
2003
+ name=name,
2004
+ label=label,
2005
+ volume=volume,
2006
+ namespace=namespace,
2007
+ # Scheduled Jobs have no network group: a script asking for one is an error, not a silent drop.
2008
+ network_group=None,
2009
+ network_aliases=None,
2010
+ dry_run=dry_run,
2011
+ ) as config:
2012
+ if config.network_group or config.network_aliases:
2013
+ raise CLIError(
2014
+ f"Scheduled Jobs do not support network groups: remove 'network_group'/'network_aliases' from the"
2015
+ f" script's [{TABLE_NAME}] table to schedule it."
2016
+ )
2017
+ _print_job_summary(
2018
+ {
2019
+ "schedule": schedule,
2020
+ "suspend": suspend,
2021
+ "concurrency": concurrency,
2022
+ "script": script,
2023
+ "args": shlex.join(config.script_args),
2024
+ "with": " ".join(with_ or []),
2025
+ "image": config.image or DEFAULT_UV_IMAGE,
2026
+ "flavor": config.flavor or JobHardware.CPU_BASIC.value,
2027
+ "python": config.python,
2028
+ "timeout": config.timeout,
2029
+ "attempts": attempts,
2030
+ "env": config.env,
2031
+ "secrets": config.secrets,
2032
+ "volumes": config.volume_specs,
2033
+ "labels": config.labels,
2034
+ "expose": " ".join(str(port) for port in expose or []),
2035
+ "expose_public": " ".join(str(port) for port in expose_public or []),
2036
+ "resource_group_id": resource_group_id,
2037
+ "namespace": config.namespace,
2038
+ },
2039
+ from_script=config.from_script,
2040
+ dry_run=dry_run,
2041
+ )
2042
+ if dry_run:
2043
+ return
2044
+ job = api.create_scheduled_uv_job(
2045
+ script=config.script,
2046
+ script_args=config.script_args,
2047
+ schedule=schedule,
2048
+ suspend=suspend,
2049
+ concurrency=concurrency,
2050
+ dependencies=with_,
2051
+ python=config.python,
2052
+ image=config.image,
2053
+ env=config.env,
2054
+ secrets=config.secrets,
2055
+ labels=config.labels,
2056
+ volumes=config.volumes,
2057
+ flavor=config.flavor,
2058
+ timeout=config.timeout,
2059
+ attempts=attempts,
2060
+ expose=expose,
2061
+ expose_public=expose_public,
2062
+ resource_group_id=resource_group_id,
2063
+ namespace=config.namespace,
2064
+ )
2065
+ out.result("Scheduled Job created", id=job.id, name=(job.job_spec.labels or {}).get("name"))
2066
+ if not _has_explicit_name(name, label, config.from_script):
2067
+ auto_name = (job.job_spec.labels or {}).get("name")
2068
+ out.hint(
2069
+ f"Scheduled Job auto-named '{auto_name}'. Pass `--name` or run "
2070
+ f"`hf jobs scheduled labels {job.owner.name}/{job.id} --name NAME` to rename it."
2071
+ )
2072
+ out.hint(f"Use `hf jobs scheduled inspect {job.owner.name}/{job.id}` to view its details.")
2073
+
2074
+
2075
+ ### UTILS
2076
+
2077
+
2078
+ def _surface_name(item: dict[str, Any], *, labels: dict[str, str] | None) -> dict[str, Any]:
2079
+ """Promote the `name` label to a top-level `name` field for display.
2080
+
2081
+ The `name` is kept inside `labels` too (the dataclasses and API payloads are unchanged); this
2082
+ only makes it a first-class column/field in command outputs. No-op when there is no name.
2083
+ """
2084
+ name = (labels or {}).get("name")
2085
+ if name is None:
2086
+ return item
2087
+ return {"name": name, **item}
2088
+
2089
+
2090
+ def _has_explicit_name(name: str | None, label: list[str] | None, from_script: Collection[str] = ()) -> bool:
2091
+ """Whether the Job was named on purpose: via `--name`, a `name=` label, or the script's `[tool.hf-jobs]` table."""
2092
+ return (
2093
+ name is not None
2094
+ or "labels.name" in from_script
2095
+ or any(item.split("=", 1)[0] == "name" for item in label or [])
2096
+ )
2097
+
2098
+
2099
+ def _parse_labels_map(labels: list[str] | None, *, name: str | None = None) -> dict[str, str] | None:
2100
+ """Parse label key-value pairs from CLI arguments.
2101
+
2102
+ Args:
2103
+ labels: List of label strings in KEY=VALUE format. If KEY only, then VALUE is set to empty string.
2104
+
2105
+ Returns:
2106
+ Dictionary mapping label keys to values, or None if no labels or name provided.
2107
+ """
2108
+ if not labels and name is None:
2109
+ return None
2110
+ labels_map: dict[str, str] = {}
2111
+ for label_var in labels or []:
2112
+ key, value = label_var.split("=", 1) if "=" in label_var else (label_var, "")
2113
+ labels_map[key] = value
2114
+ if name is not None:
2115
+ if "name" in labels_map:
2116
+ raise CLIError("--name and --label name=... cannot both be provided.")
2117
+ labels_map["name"] = name
2118
+ return labels_map
2119
+
2120
+
2121
+ def _tabulate(rows: list[list[str | int]], headers: list[str]) -> str:
2122
+ """
2123
+ Inspired by:
2124
+
2125
+ - stackoverflow.com/a/8356620/593036
2126
+ - stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
2127
+ """
2128
+ col_widths = [max(len(str(x)) for x in col) for col in zip(*rows, headers)]
2129
+ terminal_width = max(shutil.get_terminal_size().columns, len(headers) * 12)
2130
+ while len(headers) + sum(col_widths) > terminal_width:
2131
+ col_to_minimize = col_widths.index(max(col_widths))
2132
+ col_widths[col_to_minimize] //= 2
2133
+ if len(headers) + sum(col_widths) <= terminal_width:
2134
+ col_widths[col_to_minimize] = terminal_width - sum(col_widths) - len(headers) + col_widths[col_to_minimize]
2135
+ row_format = ("{{:{}}} " * len(headers)).format(*col_widths)
2136
+ lines = []
2137
+ lines.append(row_format.format(*headers))
2138
+ lines.append(row_format.format(*["-" * w for w in col_widths]))
2139
+ for row in rows:
2140
+ row_format_args = [
2141
+ str(x)[: col_width - 3] + "..." if len(str(x)) > col_width else str(x)
2142
+ for x, col_width in zip(row, col_widths)
2143
+ ]
2144
+ lines.append(row_format.format(*row_format_args))
2145
+ return "\n".join(lines)
2146
+
2147
+
2148
+ T = TypeVar("T")
2149
+
2150
+
2151
+ def _write_generator_to_queue(queue: Queue[T], func: Callable[..., Iterable[T]], kwargs: dict) -> None:
2152
+ for result in func(**kwargs):
2153
+ queue.put(result)
2154
+
2155
+
2156
+ def iflatmap_unordered(
2157
+ pool: multiprocessing.pool.ThreadPool,
2158
+ func: Callable[..., Iterable[T]],
2159
+ *,
2160
+ kwargs_list: list[dict],
2161
+ ) -> Iterable[T]:
2162
+ """
2163
+ 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.
2164
+
2165
+ This is inspired by those three `map()` variants, and is the mix of all three:
2166
+
2167
+ * `imap()`: like `map()` but returns an iterable instead of a list of results
2168
+ * `imap_unordered()`: like `imap()` but the output is sorted by time of arrival
2169
+ * `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
2170
+ """
2171
+ queue: Queue[T] = Queue()
2172
+ async_results = [pool.apply_async(_write_generator_to_queue, (queue, func, kwargs)) for kwargs in kwargs_list]
2173
+ try:
2174
+ while True:
2175
+ try:
2176
+ yield queue.get(timeout=0.05)
2177
+ except Empty:
2178
+ if all(async_result.ready() for async_result in async_results) and queue.empty():
2179
+ break
2180
+ except KeyboardInterrupt:
2181
+ pass
2182
+ finally:
2183
+ # we get the result in case there's an error to raise
2184
+ try:
2185
+ [async_result.get(timeout=0.05) for async_result in async_results]
2186
+ except multiprocessing.TimeoutError:
2187
+ pass