Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/licenses/LICENSE +201 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_buckets.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_commit_api.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_commit_scheduler.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_dataset_viewer.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_eval_results.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_jobs_api.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_local_folder.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_login.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_oauth.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_snapshot_download.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_space_api.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_tensorboard_logger.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_upload_large_folder.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_webhooks_payload.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_webhooks_server.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/community.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/constants.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/dataclasses.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/errors.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/fastai_utils.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/file_download.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/hf_file_system.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/hub_mixin.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/lfs.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/repocard.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/repocard_data.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__init__.py +13 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__pycache__/__init__.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__pycache__/client.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__pycache__/sse_client.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__pycache__/types.cpython-311.pyc +0 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/client.py +130 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/sse_client.py +144 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/types.py +121 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/__init__.py +13 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/_cli_utils.py +1208 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/_errors.py +115 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/_file_listing.py +225 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/_output.py +272 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/_skills.py +252 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/auth.py +174 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/buckets.py +821 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/cache.py +752 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/collections.py +316 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/datasets.py +286 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/deprecated_cli.py +35 -0
- micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/discussions.py +450 -0
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (30.8 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_buckets.cpython-311.pyc
ADDED
|
Binary file (53 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_commit_api.cpython-311.pyc
ADDED
|
Binary file (47.9 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_commit_scheduler.cpython-311.pyc
ADDED
|
Binary file (19.9 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_dataset_viewer.cpython-311.pyc
ADDED
|
Binary file (9.15 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_eval_results.cpython-311.pyc
ADDED
|
Binary file (9.33 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_inference_endpoints.cpython-311.pyc
ADDED
|
Binary file (21.1 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_jobs_api.cpython-311.pyc
ADDED
|
Binary file (21.1 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_local_folder.cpython-311.pyc
ADDED
|
Binary file (24 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_login.cpython-311.pyc
ADDED
|
Binary file (23.6 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_oauth.cpython-311.pyc
ADDED
|
Binary file (23 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_snapshot_download.cpython-311.pyc
ADDED
|
Binary file (21.6 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_space_api.cpython-311.pyc
ADDED
|
Binary file (16.8 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_tensorboard_logger.cpython-311.pyc
ADDED
|
Binary file (8.97 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_upload_large_folder.cpython-311.pyc
ADDED
|
Binary file (43 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_webhooks_payload.cpython-311.pyc
ADDED
|
Binary file (5.73 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/_webhooks_server.cpython-311.pyc
ADDED
|
Binary file (19 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/community.cpython-311.pyc
ADDED
|
Binary file (16.3 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/constants.cpython-311.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/dataclasses.cpython-311.pyc
ADDED
|
Binary file (33 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/errors.cpython-311.pyc
ADDED
|
Binary file (24.2 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/fastai_utils.cpython-311.pyc
ADDED
|
Binary file (19.8 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/file_download.cpython-311.pyc
ADDED
|
Binary file (78.5 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/hf_file_system.cpython-311.pyc
ADDED
|
Binary file (72.3 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/hub_mixin.cpython-311.pyc
ADDED
|
Binary file (39.8 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/lfs.cpython-311.pyc
ADDED
|
Binary file (19.7 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/repocard.cpython-311.pyc
ADDED
|
Binary file (38 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__pycache__/repocard_data.cpython-311.pyc
ADDED
|
Binary file (38.1 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (221 Bytes). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__pycache__/client.cpython-311.pyc
ADDED
|
Binary file (6.76 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__pycache__/sse_client.cpython-311.pyc
ADDED
|
Binary file (6.06 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/__pycache__/types.cpython-311.pyc
ADDED
|
Binary file (6.26 kB). View file
|
|
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/client.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import time
|
| 18 |
+
from collections import deque
|
| 19 |
+
from collections.abc import Iterator
|
| 20 |
+
from typing import Literal, TypedDict
|
| 21 |
+
|
| 22 |
+
import httpx
|
| 23 |
+
|
| 24 |
+
from ..utils._headers import build_hf_headers
|
| 25 |
+
from ..utils._http import hf_raise_for_status
|
| 26 |
+
from .sse_client import SSEClient
|
| 27 |
+
from .types import ApiGetReloadEventSourceData, ApiGetReloadRequest
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
HOT_RELOADING_PORT = 7887
|
| 31 |
+
CLIENT_TIMEOUT = 20
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class MultiReplicaStreamWarning(TypedDict):
|
| 35 |
+
kind: Literal["warning"]
|
| 36 |
+
message: str
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class MultiReplicaStreamEvent(TypedDict):
|
| 40 |
+
kind: Literal["event"]
|
| 41 |
+
event: ApiGetReloadEventSourceData
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class MultiReplicaStreamReplicaHash(TypedDict):
|
| 45 |
+
kind: Literal["replicaHash"]
|
| 46 |
+
hash: str
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class MultiReplicaStreamFullMatch(TypedDict):
|
| 50 |
+
kind: Literal["fullMatch"]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class ReloadClient:
|
| 54 |
+
def __init__(
|
| 55 |
+
self,
|
| 56 |
+
*,
|
| 57 |
+
host: str,
|
| 58 |
+
subdomain: str,
|
| 59 |
+
replica_hash: str,
|
| 60 |
+
token: str | None,
|
| 61 |
+
):
|
| 62 |
+
base_host = host.replace(subdomain, f"{subdomain}--{HOT_RELOADING_PORT}")
|
| 63 |
+
self.replica_hash = replica_hash
|
| 64 |
+
self.client = httpx.Client(
|
| 65 |
+
base_url=f"{base_host}/--replicas/+{replica_hash}",
|
| 66 |
+
headers=build_hf_headers(token=token),
|
| 67 |
+
timeout=CLIENT_TIMEOUT,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def get_reload(self, reload_id: str) -> Iterator[ApiGetReloadEventSourceData] | int:
|
| 71 |
+
req = ApiGetReloadRequest(reloadId=reload_id)
|
| 72 |
+
with self.client.stream("POST", "/get-reload", json=req) as res:
|
| 73 |
+
if res.status_code != 200:
|
| 74 |
+
return res.status_code
|
| 75 |
+
hf_raise_for_status(res)
|
| 76 |
+
for event in SSEClient(res.iter_bytes()).events():
|
| 77 |
+
if event.event == "message":
|
| 78 |
+
yield json.loads(event.data)
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def multi_replica_reload_events(
|
| 83 |
+
commit_sha: str,
|
| 84 |
+
host: str,
|
| 85 |
+
subdomain: str,
|
| 86 |
+
replica_hashes: list[str],
|
| 87 |
+
token: str | None,
|
| 88 |
+
max_retries: int = 10,
|
| 89 |
+
) -> Iterator[
|
| 90 |
+
MultiReplicaStreamWarning | MultiReplicaStreamEvent | MultiReplicaStreamReplicaHash | MultiReplicaStreamFullMatch
|
| 91 |
+
]:
|
| 92 |
+
clients = [
|
| 93 |
+
ReloadClient(
|
| 94 |
+
host=host,
|
| 95 |
+
subdomain=subdomain,
|
| 96 |
+
replica_hash=hash,
|
| 97 |
+
token=token,
|
| 98 |
+
)
|
| 99 |
+
for hash in replica_hashes
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
first_client_events: dict[int, ApiGetReloadEventSourceData] = {}
|
| 103 |
+
for client_index, client in enumerate(clients):
|
| 104 |
+
if len(clients) > 1:
|
| 105 |
+
yield {"kind": "replicaHash", "hash": client.replica_hash}
|
| 106 |
+
|
| 107 |
+
retries = 0
|
| 108 |
+
while isinstance((events := client.get_reload(commit_sha)), int):
|
| 109 |
+
if (retries := retries + 1) > max_retries:
|
| 110 |
+
raise Exception("Too many retries reached")
|
| 111 |
+
if (status_code := events) not in (200, 204):
|
| 112 |
+
raise Exception(f"Unexpected {status_code=} on `ReloadClient.get_reload`")
|
| 113 |
+
subject = "reloadId" if status_code == 204 else "replica"
|
| 114 |
+
yield {"kind": "warning", "message": f"Retrying on unexpected {subject} not found"}
|
| 115 |
+
time.sleep(2)
|
| 116 |
+
|
| 117 |
+
full_match = True
|
| 118 |
+
replay: deque[ApiGetReloadEventSourceData] = deque()
|
| 119 |
+
for event_index, event in enumerate(events):
|
| 120 |
+
if client_index == 0:
|
| 121 |
+
first_client_events[event_index] = event
|
| 122 |
+
elif full_match := full_match and first_client_events.get(event_index) == event:
|
| 123 |
+
replay.append(event)
|
| 124 |
+
continue
|
| 125 |
+
while replay:
|
| 126 |
+
yield {"kind": "event", "event": replay.popleft()}
|
| 127 |
+
yield {"kind": "event", "event": event}
|
| 128 |
+
|
| 129 |
+
if client_index > 0 and full_match:
|
| 130 |
+
yield {"kind": "fullMatch"}
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/sse_client.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Vendored file: Server Side Events (SSE) client for Python.
|
| 3 |
+
|
| 4 |
+
Source:
|
| 5 |
+
- Author: Maxime Petazzoni <maxime.petazzoni@bulix.org>
|
| 6 |
+
- Repository: https://github.com/mpetazzoni/sseclient
|
| 7 |
+
- File: https://github.com/mpetazzoni/sseclient/blob/main/sseclient/__init__.py
|
| 8 |
+
|
| 9 |
+
License:
|
| 10 |
+
- Apache-2.0 (from upstream project)
|
| 11 |
+
|
| 12 |
+
Provides a generator of SSE received through an existing HTTP response.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import logging
|
| 16 |
+
|
| 17 |
+
__author__ = 'Maxime Petazzoni <maxime.petazzoni@bulix.org>'
|
| 18 |
+
__email__ = 'maxime.petazzoni@bulix.org'
|
| 19 |
+
__all__ = ['SSEClient']
|
| 20 |
+
|
| 21 |
+
_FIELD_SEPARATOR = ':'
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class SSEClient:
|
| 25 |
+
"""Implementation of a SSE client.
|
| 26 |
+
|
| 27 |
+
See http://www.w3.org/TR/2009/WD-eventsource-20091029/ for the
|
| 28 |
+
specification.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, event_source, char_enc='utf-8'):
|
| 32 |
+
"""Initialize the SSE client over an existing, ready to consume
|
| 33 |
+
event source.
|
| 34 |
+
|
| 35 |
+
The event source is expected to be a binary stream and have a close()
|
| 36 |
+
method. That would usually be something that implements
|
| 37 |
+
io.BinaryIOBase, like an httplib or urllib3 HTTPResponse object.
|
| 38 |
+
"""
|
| 39 |
+
self._logger = logging.getLogger(self.__class__.__module__)
|
| 40 |
+
self._logger.debug('Initialized SSE client from event source %s',
|
| 41 |
+
event_source)
|
| 42 |
+
self._event_source = event_source
|
| 43 |
+
self._char_enc = char_enc
|
| 44 |
+
|
| 45 |
+
def _read(self):
|
| 46 |
+
"""Read the incoming event source stream and yield event chunks.
|
| 47 |
+
|
| 48 |
+
Unfortunately it is possible for some servers to decide to break an
|
| 49 |
+
event into multiple HTTP chunks in the response. It is thus necessary
|
| 50 |
+
to correctly stitch together consecutive response chunks and find the
|
| 51 |
+
SSE delimiter (empty new line) to yield full, correct event chunks."""
|
| 52 |
+
data = b''
|
| 53 |
+
for chunk in self._event_source:
|
| 54 |
+
for line in chunk.splitlines(True):
|
| 55 |
+
data += line
|
| 56 |
+
if data.endswith((b'\r\r', b'\n\n', b'\r\n\r\n')):
|
| 57 |
+
yield data
|
| 58 |
+
data = b''
|
| 59 |
+
if data:
|
| 60 |
+
yield data
|
| 61 |
+
|
| 62 |
+
def events(self):
|
| 63 |
+
for chunk in self._read():
|
| 64 |
+
event = Event()
|
| 65 |
+
# Split before decoding so splitlines() only uses \r and \n
|
| 66 |
+
for line in chunk.splitlines():
|
| 67 |
+
# Decode the line.
|
| 68 |
+
line = line.decode(self._char_enc)
|
| 69 |
+
|
| 70 |
+
# Lines starting with a separator are comments and are to be
|
| 71 |
+
# ignored.
|
| 72 |
+
if not line.strip() or line.startswith(_FIELD_SEPARATOR):
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
data = line.split(_FIELD_SEPARATOR, 1)
|
| 76 |
+
field = data[0]
|
| 77 |
+
|
| 78 |
+
# Ignore unknown fields.
|
| 79 |
+
if field not in event.__dict__:
|
| 80 |
+
self._logger.debug('Saw invalid field %s while parsing '
|
| 81 |
+
'Server Side Event', field)
|
| 82 |
+
continue
|
| 83 |
+
|
| 84 |
+
if len(data) > 1:
|
| 85 |
+
# From the spec:
|
| 86 |
+
# "If value starts with a single U+0020 SPACE character,
|
| 87 |
+
# remove it from value."
|
| 88 |
+
if data[1].startswith(' '):
|
| 89 |
+
value = data[1][1:]
|
| 90 |
+
else:
|
| 91 |
+
value = data[1]
|
| 92 |
+
else:
|
| 93 |
+
# If no value is present after the separator,
|
| 94 |
+
# assume an empty value.
|
| 95 |
+
value = ''
|
| 96 |
+
|
| 97 |
+
# The data field may come over multiple lines and their values
|
| 98 |
+
# are concatenated with each other.
|
| 99 |
+
if field == 'data':
|
| 100 |
+
event.__dict__[field] += value + '\n'
|
| 101 |
+
else:
|
| 102 |
+
event.__dict__[field] = value
|
| 103 |
+
|
| 104 |
+
# Events with no data are not dispatched.
|
| 105 |
+
if not event.data:
|
| 106 |
+
continue
|
| 107 |
+
|
| 108 |
+
# If the data field ends with a newline, remove it.
|
| 109 |
+
if event.data.endswith('\n'):
|
| 110 |
+
event.data = event.data[0:-1]
|
| 111 |
+
|
| 112 |
+
# Empty event names default to 'message'
|
| 113 |
+
event.event = event.event or 'message'
|
| 114 |
+
|
| 115 |
+
# Dispatch the event
|
| 116 |
+
self._logger.debug('Dispatching %s...', event)
|
| 117 |
+
yield event
|
| 118 |
+
|
| 119 |
+
def close(self):
|
| 120 |
+
"""Manually close the event source stream."""
|
| 121 |
+
self._event_source.close()
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class Event:
|
| 125 |
+
"""Representation of an event from the event stream."""
|
| 126 |
+
|
| 127 |
+
def __init__(self, id=None, event='message', data='', retry=None):
|
| 128 |
+
self.id = id
|
| 129 |
+
self.event = event
|
| 130 |
+
self.data = data
|
| 131 |
+
self.retry = retry
|
| 132 |
+
|
| 133 |
+
def __str__(self):
|
| 134 |
+
s = f'{self.event} event'
|
| 135 |
+
if self.id:
|
| 136 |
+
s += f' #{self.id}'
|
| 137 |
+
if self.data:
|
| 138 |
+
s += ', {} byte{}'.format(len(self.data),
|
| 139 |
+
's' if len(self.data) else '')
|
| 140 |
+
else:
|
| 141 |
+
s += ', no data'
|
| 142 |
+
if self.retry:
|
| 143 |
+
s += f', retry in {self.retry}ms'
|
| 144 |
+
return s
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_hot_reload/types.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 15 |
+
|
| 16 |
+
from typing import Literal, TypedDict
|
| 17 |
+
|
| 18 |
+
from typing_extensions import NotRequired
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ReloadRegion(TypedDict):
|
| 22 |
+
startLine: int
|
| 23 |
+
startCol: int
|
| 24 |
+
endLine: int
|
| 25 |
+
endCol: int
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ReloadOperationObject(TypedDict):
|
| 29 |
+
kind: Literal["add", "update", "delete"]
|
| 30 |
+
region: ReloadRegion
|
| 31 |
+
objectType: str
|
| 32 |
+
objectName: str
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ReloadOperationRun(TypedDict):
|
| 36 |
+
kind: Literal["run"]
|
| 37 |
+
region: ReloadRegion
|
| 38 |
+
codeLines: str
|
| 39 |
+
stdout: NotRequired[str]
|
| 40 |
+
stderr: NotRequired[str]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ReloadOperationException(TypedDict):
|
| 44 |
+
kind: Literal["exception"]
|
| 45 |
+
region: ReloadRegion
|
| 46 |
+
traceback: str
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ReloadOperationError(TypedDict):
|
| 50 |
+
kind: Literal["error"]
|
| 51 |
+
traceback: str
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class ReloadOperationUI(TypedDict):
|
| 55 |
+
kind: Literal["ui"]
|
| 56 |
+
updated: bool
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ReloadOperationFile(TypedDict):
|
| 60 |
+
kind: Literal["file"]
|
| 61 |
+
created: bool
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class ApiCreateReloadRequest(TypedDict):
|
| 65 |
+
filepath: str
|
| 66 |
+
contents: str
|
| 67 |
+
reloadId: NotRequired[str]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class ApiCreateReloadResponseSuccess(TypedDict):
|
| 71 |
+
status: Literal["created"]
|
| 72 |
+
reloadId: str
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class ApiCreateReloadResponseError(TypedDict):
|
| 76 |
+
status: Literal["alreadyReloading", "fileNotFound"]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class ApiCreateReloadResponse(TypedDict):
|
| 80 |
+
res: ApiCreateReloadResponseError | ApiCreateReloadResponseSuccess
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class ApiGetReloadRequest(TypedDict):
|
| 84 |
+
reloadId: str
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class ApiGetReloadEventSourceData(TypedDict):
|
| 88 |
+
data: (
|
| 89 |
+
ReloadOperationError
|
| 90 |
+
| ReloadOperationException
|
| 91 |
+
| ReloadOperationObject
|
| 92 |
+
| ReloadOperationRun
|
| 93 |
+
| ReloadOperationUI
|
| 94 |
+
| ReloadOperationFile
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class ApiGetStatusRequest(TypedDict):
|
| 99 |
+
revision: str
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class ApiGetStatusResponse(TypedDict):
|
| 103 |
+
reloading: bool
|
| 104 |
+
uncommited: list[str]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class ApiFetchContentsRequest(TypedDict):
|
| 108 |
+
filepath: str
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class ApiFetchContentsResponseError(TypedDict):
|
| 112 |
+
status: Literal["fileNotFound"]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class ApiFetchContentsResponseSuccess(TypedDict):
|
| 116 |
+
status: Literal["ok"]
|
| 117 |
+
contents: str
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class ApiFetchContentsResponse(TypedDict):
|
| 121 |
+
res: ApiFetchContentsResponseError | ApiFetchContentsResponseSuccess
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/_cli_utils.py
ADDED
|
@@ -0,0 +1,1208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 dataclasses
|
| 17 |
+
import datetime
|
| 18 |
+
import difflib
|
| 19 |
+
import importlib.metadata
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import re
|
| 23 |
+
import subprocess
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
from collections.abc import Callable, Sequence
|
| 27 |
+
from enum import Enum
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeVar, Union, cast
|
| 30 |
+
|
| 31 |
+
import click
|
| 32 |
+
import typer
|
| 33 |
+
from typer.core import TyperCommand, TyperGroup
|
| 34 |
+
|
| 35 |
+
from huggingface_hub import Volume, __version__, constants
|
| 36 |
+
from huggingface_hub.errors import CLIError
|
| 37 |
+
from huggingface_hub.utils import (
|
| 38 |
+
get_session,
|
| 39 |
+
hf_raise_for_status,
|
| 40 |
+
installation_method,
|
| 41 |
+
logging,
|
| 42 |
+
tabulate,
|
| 43 |
+
)
|
| 44 |
+
from huggingface_hub.utils._dotenv import load_dotenv
|
| 45 |
+
|
| 46 |
+
from ._output import OutputFormatWithAuto, out
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
logger = logging.get_logger()
|
| 50 |
+
|
| 51 |
+
# Arbitrary maximum length of a cell in a table output
|
| 52 |
+
_MAX_CELL_LENGTH = 35
|
| 53 |
+
|
| 54 |
+
# Arbitrary default limit for models/datasets/spaces list commands.
|
| 55 |
+
REPO_LIST_DEFAULT_LIMIT = 30
|
| 56 |
+
|
| 57 |
+
if TYPE_CHECKING:
|
| 58 |
+
from huggingface_hub.hf_api import HfApi
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def get_hf_api(token: str | None = None) -> "HfApi":
|
| 62 |
+
# Import here to avoid circular import
|
| 63 |
+
from huggingface_hub.hf_api import HfApi
|
| 64 |
+
|
| 65 |
+
return HfApi(token=token, library_name="huggingface-cli", library_version=__version__)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
#### TYPER UTILS
|
| 69 |
+
|
| 70 |
+
CLI_REFERENCE_URL = "https://huggingface.co/docs/huggingface_hub/en/guides/cli"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def generate_epilog(examples: list[str], docs_anchor: str | None = None) -> str:
|
| 74 |
+
"""Generate an epilog with examples and a Learn More section.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
examples: List of example commands (without the `$ ` prefix).
|
| 78 |
+
docs_anchor: Optional anchor for the docs URL (e.g., "#hf-download").
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
Formatted epilog string.
|
| 82 |
+
"""
|
| 83 |
+
docs_url = f"{CLI_REFERENCE_URL}{docs_anchor}" if docs_anchor else CLI_REFERENCE_URL
|
| 84 |
+
examples_str = "\n".join(f" $ {ex}" for ex in examples)
|
| 85 |
+
return f"""\
|
| 86 |
+
Examples
|
| 87 |
+
{examples_str}
|
| 88 |
+
|
| 89 |
+
Learn more
|
| 90 |
+
Use `hf <command> --help` for more information about a command.
|
| 91 |
+
Read the documentation at {docs_url}
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
TOPIC_T = Literal["main", "help"] | str
|
| 96 |
+
FallbackHandlerT = Callable[[list[str], set[str]], int | None]
|
| 97 |
+
ExpandPropertyT = TypeVar("ExpandPropertyT", bound=str)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _format_epilog_no_indent(epilog: str | None, ctx: click.Context, formatter: click.HelpFormatter) -> None:
|
| 101 |
+
"""Write the epilog without indentation."""
|
| 102 |
+
if epilog:
|
| 103 |
+
formatter.write_paragraph()
|
| 104 |
+
for line in epilog.split("\n"):
|
| 105 |
+
formatter.write_text(line)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
_ALIAS_SPLIT = re.compile(r"\s*\|\s*")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class HFCliTyperGroup(TyperGroup):
|
| 112 |
+
"""
|
| 113 |
+
Typer Group that:
|
| 114 |
+
- lists commands alphabetically within sections.
|
| 115 |
+
- separates commands by topic (main, help, etc.).
|
| 116 |
+
- formats epilog without extra indentation.
|
| 117 |
+
- supports aliases via pipe-separated names (e.g. ``name="list | ls"``).
|
| 118 |
+
- consumes the global formatting flags (``--format``, ``--json``, ``-q`` / ``--quiet``)
|
| 119 |
+
anywhere in the args of a leaf command and applies them to ``out``, so leaf
|
| 120 |
+
commands don't need to declare these options themselves.
|
| 121 |
+
- rewrites ``spaces/user/repo`` to ``user/repo --type space`` for commands that accept ``--type``.
|
| 122 |
+
- enriches "No such option" / "No such command" errors with available options or commands.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
def invoke(self, ctx: click.Context) -> None:
|
| 126 |
+
"""Enrich unknown-option errors with available options or subcommands.
|
| 127 |
+
|
| 128 |
+
Catches `NoSuchOption` raised during subcommand `make_context()`
|
| 129 |
+
(option parsing). For leaf commands (e.g. `hf repos create --test`)
|
| 130 |
+
we list the command's options; for groups (e.g. `hf cache --test`)
|
| 131 |
+
we list subcommands since groups have no user-facing options.
|
| 132 |
+
"""
|
| 133 |
+
try:
|
| 134 |
+
return super().invoke(ctx)
|
| 135 |
+
except click.NoSuchOption as e:
|
| 136 |
+
if e.ctx is not None and e.ctx.command is not None:
|
| 137 |
+
cmd = e.ctx.command
|
| 138 |
+
if isinstance(cmd, click.Group):
|
| 139 |
+
# Group has no user-facing options -> show subcommands instead
|
| 140 |
+
items = [
|
| 141 |
+
(name, sub.get_short_help_str(limit=80))
|
| 142 |
+
for name in cmd.list_commands(e.ctx)
|
| 143 |
+
if (sub := cmd.get_command(e.ctx, name)) is not None and not sub.hidden
|
| 144 |
+
]
|
| 145 |
+
_enrich_usage_error(e, "commands", items)
|
| 146 |
+
else:
|
| 147 |
+
# Leaf command -> show its options using Click's rich formatting
|
| 148 |
+
items = [
|
| 149 |
+
record
|
| 150 |
+
for p in cmd.get_params(e.ctx)
|
| 151 |
+
if isinstance(p, click.Option) and not p.hidden and (record := p.get_help_record(e.ctx))
|
| 152 |
+
]
|
| 153 |
+
_enrich_usage_error(e, "options", items)
|
| 154 |
+
raise
|
| 155 |
+
|
| 156 |
+
def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple:
|
| 157 |
+
cmd_name = args[0] if args and not args[0].startswith("-") else None
|
| 158 |
+
cmd = self.get_command(ctx, cmd_name) if cmd_name else None
|
| 159 |
+
|
| 160 |
+
if cmd is not None:
|
| 161 |
+
self._rewrite_repo_type_prefix(cmd, args)
|
| 162 |
+
|
| 163 |
+
try:
|
| 164 |
+
name, resolved_cmd, sub_args = super().resolve_command(ctx, args)
|
| 165 |
+
except click.UsageError as e:
|
| 166 |
+
# Unknown subcommand -> add fuzzy suggestions and list available commands.
|
| 167 |
+
if cmd is None and cmd_name is not None:
|
| 168 |
+
# Expand aliases ("list | ls" → ["list", "ls"]) for accurate fuzzy matching.
|
| 169 |
+
visible_names = [
|
| 170 |
+
alias
|
| 171 |
+
for key, registered in self.commands.items()
|
| 172 |
+
if not registered.hidden
|
| 173 |
+
for alias in _ALIAS_SPLIT.split(key)
|
| 174 |
+
]
|
| 175 |
+
matches = difflib.get_close_matches(cmd_name, visible_names)
|
| 176 |
+
if matches:
|
| 177 |
+
suggestions = ", ".join(f"'{m}'" for m in matches)
|
| 178 |
+
e.message = f"{e.message.rstrip('.')}. Did you mean {suggestions}?"
|
| 179 |
+
items = [
|
| 180 |
+
(name, sub.get_short_help_str(limit=80))
|
| 181 |
+
for name in self.list_commands(ctx)
|
| 182 |
+
if (sub := self.get_command(ctx, name)) is not None and not sub.hidden
|
| 183 |
+
]
|
| 184 |
+
_enrich_usage_error(e, "commands", items)
|
| 185 |
+
raise
|
| 186 |
+
|
| 187 |
+
# If we just resolved a leaf command, eagerly consume any global formatting
|
| 188 |
+
# flags (--format / --json / -q / --quiet) from its args before click parses
|
| 189 |
+
# them. Group resolution is recursive — leaves (and only leaves) need this.
|
| 190 |
+
if resolved_cmd is not None and not isinstance(resolved_cmd, click.Group):
|
| 191 |
+
_consume_format_flags_for_leaf(resolved_cmd, sub_args)
|
| 192 |
+
|
| 193 |
+
return name, resolved_cmd, sub_args
|
| 194 |
+
|
| 195 |
+
@staticmethod
|
| 196 |
+
def _rewrite_repo_type_prefix(cmd: click.Command, args: list[str]) -> None:
|
| 197 |
+
"""Rewrite prefixed repo IDs (e.g. ``spaces/user/repo``) to ``user/repo --type space``.
|
| 198 |
+
|
| 199 |
+
Only applies to commands that have a ``--type`` / ``--repo-type`` option and
|
| 200 |
+
at least one repo-ID positional argument (any ``click.Argument`` whose name
|
| 201 |
+
ends with ``_id``, e.g. ``repo_id``, ``from_id``, ``to_id``). When the
|
| 202 |
+
token that maps to such an argument matches ``{prefix}/org/repo`` (where
|
| 203 |
+
*prefix* is one of ``spaces``, ``datasets``, or ``models``), the prefix is
|
| 204 |
+
stripped and an implicit ``--type {type}`` is appended. An error is raised
|
| 205 |
+
if ``--type`` is also provided explicitly or if multiple prefixed arguments
|
| 206 |
+
disagree on the repo type.
|
| 207 |
+
|
| 208 |
+
Only repo-ID positional slots are inspected so that other positional
|
| 209 |
+
arguments (filenames, local paths, patterns …) are never misinterpreted as
|
| 210 |
+
prefixed repo IDs.
|
| 211 |
+
"""
|
| 212 |
+
has_type_option = any(isinstance(param, click.Option) and "--type" in param.opts for param in cmd.params)
|
| 213 |
+
if not has_type_option:
|
| 214 |
+
return
|
| 215 |
+
|
| 216 |
+
# Locate all repo-ID positional arguments and their indices among Arguments.
|
| 217 |
+
repo_id_positions: set[int] = set()
|
| 218 |
+
arg_idx = 0
|
| 219 |
+
for param in cmd.params:
|
| 220 |
+
if isinstance(param, click.Argument):
|
| 221 |
+
if param.name in ("repo_id", "from_id", "to_id"):
|
| 222 |
+
repo_id_positions.add(arg_idx)
|
| 223 |
+
arg_idx += 1
|
| 224 |
+
|
| 225 |
+
if not repo_id_positions:
|
| 226 |
+
return
|
| 227 |
+
|
| 228 |
+
# Build a set of option names that consume a following value token.
|
| 229 |
+
value_options: set[str] = set()
|
| 230 |
+
for param in cmd.params:
|
| 231 |
+
if isinstance(param, click.Option) and not param.is_flag:
|
| 232 |
+
for opt in (*param.opts, *param.secondary_opts):
|
| 233 |
+
value_options.add(opt)
|
| 234 |
+
|
| 235 |
+
# Walk through args (skipping args[0] = command name) to map positional
|
| 236 |
+
# slots to their indices in `args`.
|
| 237 |
+
positional_count = 0
|
| 238 |
+
repo_id_arg_indices: list[int] = []
|
| 239 |
+
i = 1
|
| 240 |
+
while i < len(args):
|
| 241 |
+
arg = args[i]
|
| 242 |
+
if arg == "--":
|
| 243 |
+
break # everything after -- is positional literal; stop rewriting
|
| 244 |
+
if arg.startswith("-"):
|
| 245 |
+
if "=" in arg or arg not in value_options:
|
| 246 |
+
i += 1 # flag or --opt=val — single token
|
| 247 |
+
else:
|
| 248 |
+
i += 2 # value-taking option — skip the value too
|
| 249 |
+
else:
|
| 250 |
+
if positional_count in repo_id_positions:
|
| 251 |
+
repo_id_arg_indices.append(i)
|
| 252 |
+
positional_count += 1
|
| 253 |
+
i += 1
|
| 254 |
+
|
| 255 |
+
if not repo_id_arg_indices:
|
| 256 |
+
return
|
| 257 |
+
|
| 258 |
+
# Check each repo-ID arg for a type prefix and collect rewrites.
|
| 259 |
+
inferred_type: str | None = None
|
| 260 |
+
first_prefix: str | None = None
|
| 261 |
+
rewrites: list[tuple[int, str]] = [] # (args index, new value without prefix)
|
| 262 |
+
|
| 263 |
+
for arg_index in repo_id_arg_indices:
|
| 264 |
+
parts = args[arg_index].split("/", 2)
|
| 265 |
+
if len(parts) != 3 or parts[0] not in constants.REPO_TYPES_MAPPING:
|
| 266 |
+
continue
|
| 267 |
+
prefix = parts[0]
|
| 268 |
+
mapped_type = constants.REPO_TYPES_MAPPING[prefix]
|
| 269 |
+
if inferred_type is not None and mapped_type != inferred_type:
|
| 270 |
+
raise click.UsageError(f"Conflicting repo type prefixes: '{first_prefix}/' and '{prefix}/'.")
|
| 271 |
+
inferred_type = mapped_type
|
| 272 |
+
first_prefix = prefix
|
| 273 |
+
rewrites.append((arg_index, f"{parts[1]}/{parts[2]}"))
|
| 274 |
+
|
| 275 |
+
if not rewrites:
|
| 276 |
+
return
|
| 277 |
+
|
| 278 |
+
# Error if --type / --repo-type was also provided explicitly.
|
| 279 |
+
if any(
|
| 280 |
+
arg == "--type" or arg.startswith("--type=") or arg == "--repo-type" or arg.startswith("--repo-type=")
|
| 281 |
+
for arg in args
|
| 282 |
+
):
|
| 283 |
+
raise click.UsageError(
|
| 284 |
+
f"Ambiguous repo type: got prefix '{first_prefix}/' in repo ID and explicit --type. Use one or the other."
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
# Apply all rewrites and append --type once.
|
| 288 |
+
for arg_index, new_value in rewrites:
|
| 289 |
+
args[arg_index] = new_value
|
| 290 |
+
args.extend(["--type", inferred_type]) # type: ignore
|
| 291 |
+
|
| 292 |
+
def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:
|
| 293 |
+
# Try exact match first
|
| 294 |
+
cmd = super().get_command(ctx, cmd_name)
|
| 295 |
+
if cmd is not None:
|
| 296 |
+
return cmd
|
| 297 |
+
# Fall back to alias lookup: check if cmd_name matches any alias
|
| 298 |
+
# taken from https://github.com/fastapi/typer/issues/132#issuecomment-2417492805
|
| 299 |
+
for registered_name, registered_cmd in self.commands.items():
|
| 300 |
+
aliases = _ALIAS_SPLIT.split(registered_name)
|
| 301 |
+
if cmd_name in aliases:
|
| 302 |
+
return registered_cmd
|
| 303 |
+
return None
|
| 304 |
+
|
| 305 |
+
def _alias_map(self) -> dict[str, list[str]]:
|
| 306 |
+
"""Build a mapping from primary command name to its aliases (if any)."""
|
| 307 |
+
result: dict[str, list[str]] = {}
|
| 308 |
+
for registered_name in self.commands:
|
| 309 |
+
parts = _ALIAS_SPLIT.split(registered_name)
|
| 310 |
+
primary = parts[0]
|
| 311 |
+
result[primary] = parts[1:]
|
| 312 |
+
return result
|
| 313 |
+
|
| 314 |
+
def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
|
| 315 |
+
topics: dict[str, list] = {}
|
| 316 |
+
alias_map = self._alias_map()
|
| 317 |
+
|
| 318 |
+
for name in self.list_commands(ctx):
|
| 319 |
+
cmd = self.get_command(ctx, name)
|
| 320 |
+
if cmd is None or cmd.hidden:
|
| 321 |
+
continue
|
| 322 |
+
help_text = cmd.get_short_help_str(limit=formatter.width)
|
| 323 |
+
aliases = alias_map.get(name, [])
|
| 324 |
+
if aliases:
|
| 325 |
+
help_text = f"{help_text} [alias: {', '.join(aliases)}]"
|
| 326 |
+
topic = getattr(cmd, "topic", "main")
|
| 327 |
+
topics.setdefault(topic, []).append((name, help_text))
|
| 328 |
+
|
| 329 |
+
with formatter.section("Main commands"):
|
| 330 |
+
formatter.write_dl(topics["main"])
|
| 331 |
+
for topic in sorted(topics.keys()):
|
| 332 |
+
if topic == "main":
|
| 333 |
+
continue
|
| 334 |
+
with formatter.section(f"{topic.capitalize()} commands"):
|
| 335 |
+
formatter.write_dl(topics[topic])
|
| 336 |
+
|
| 337 |
+
def format_epilog(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
|
| 338 |
+
# Collect only the first example from each command (to keep group help concise)
|
| 339 |
+
# Full examples are shown in individual subcommand help (e.g. `hf buckets sync --help`)
|
| 340 |
+
all_examples: list[str] = []
|
| 341 |
+
for name in self.list_commands(ctx):
|
| 342 |
+
cmd = self.get_command(ctx, name)
|
| 343 |
+
if cmd is None or cmd.hidden:
|
| 344 |
+
continue
|
| 345 |
+
cmd_examples = getattr(cmd, "examples", [])
|
| 346 |
+
if cmd_examples:
|
| 347 |
+
all_examples.append(cmd_examples[0])
|
| 348 |
+
|
| 349 |
+
if all_examples:
|
| 350 |
+
epilog = generate_epilog(all_examples)
|
| 351 |
+
_format_epilog_no_indent(epilog, ctx, formatter)
|
| 352 |
+
elif self.epilog:
|
| 353 |
+
_format_epilog_no_indent(self.epilog, ctx, formatter)
|
| 354 |
+
|
| 355 |
+
def list_commands(self, ctx: click.Context) -> list[str]: # type: ignore[name-defined]
|
| 356 |
+
# For aliased commands ("list | ls"), use the primary name (first entry).
|
| 357 |
+
primary_names: list[str] = []
|
| 358 |
+
for name in self.commands:
|
| 359 |
+
primary = _ALIAS_SPLIT.split(name)[0]
|
| 360 |
+
primary_names.append(primary)
|
| 361 |
+
return sorted(primary_names)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
_FORMATTING_OPTIONS_HELP_RECORDS: list[tuple[str, str]] = [
|
| 365 |
+
(
|
| 366 |
+
"--format [auto|human|agent|json|quiet]",
|
| 367 |
+
"Output format. Defaults to 'auto' which picks 'agent' or 'human' based on the terminal.",
|
| 368 |
+
),
|
| 369 |
+
("--json", "JSON output. Equivalent to '--format json'."),
|
| 370 |
+
("-q, --quiet", "Quiet output (one ID per line). Equivalent to '--format quiet'."),
|
| 371 |
+
]
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def _format_formatting_options_section(formatter: click.HelpFormatter) -> None:
|
| 375 |
+
with formatter.section("Formatting options"):
|
| 376 |
+
formatter.write_dl(_FORMATTING_OPTIONS_HELP_RECORDS)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _has_local_formatting_option(cmd: click.Command) -> bool:
|
| 380 |
+
"""Return True if the command defines its own --format, --json or --quiet / -q.
|
| 381 |
+
|
| 382 |
+
Used to skip the global formatting flag pre-processor and the duplicated "Formatting options" help section for
|
| 383 |
+
legacy commands like 'hf jobs ps' that have their own format/quiet options.
|
| 384 |
+
"""
|
| 385 |
+
for param in cmd.params:
|
| 386 |
+
if not isinstance(param, click.Option):
|
| 387 |
+
continue
|
| 388 |
+
opts = (*param.opts, *param.secondary_opts)
|
| 389 |
+
if "--format" in opts or "--json" in opts or "--quiet" in opts or "-q" in opts:
|
| 390 |
+
return True
|
| 391 |
+
return False
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _consume_format_flags_for_leaf(cmd: click.Command, args: list[str]) -> None:
|
| 395 |
+
"""Apply global formatting flags from 'args' to a leaf command.
|
| 396 |
+
|
| 397 |
+
Two modes, depending on the command:
|
| 398 |
+
|
| 399 |
+
* **Pass-through commands** (ignore_unknown_options=True, e.g. 'hf extensions exec'):
|
| 400 |
+
args are forwarded verbatim to an external binary; we don't touch them.
|
| 401 |
+
|
| 402 |
+
* **Legacy commands with a local --format option** (e.g. 'hf jobs ps' whose '--format' accepts Go templates):
|
| 403 |
+
the global flags are rewritten in-place to the legacy form ('--json' → '--format json', '--quiet'/'-q' → '--format quiet'
|
| 404 |
+
when the cmd has no own '--quiet') so click can parse them locally. This preserves backwards compatibility with the previous shorthand behavior.
|
| 405 |
+
|
| 406 |
+
* **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'.
|
| 407 |
+
|
| 408 |
+
Raises click.UsageError if multiple conflicting flags are supplied (e.g. '--json' together with '--format table').
|
| 409 |
+
"""
|
| 410 |
+
if cmd.context_settings.get("ignore_unknown_options"):
|
| 411 |
+
return
|
| 412 |
+
|
| 413 |
+
has_local_format = False
|
| 414 |
+
has_local_quiet = False
|
| 415 |
+
has_local_json = False
|
| 416 |
+
for param in cmd.params:
|
| 417 |
+
if not isinstance(param, click.Option):
|
| 418 |
+
continue
|
| 419 |
+
opts = (*param.opts, *param.secondary_opts)
|
| 420 |
+
if "--format" in opts:
|
| 421 |
+
has_local_format = True
|
| 422 |
+
if "--quiet" in opts or "-q" in opts:
|
| 423 |
+
has_local_quiet = True
|
| 424 |
+
if "--json" in opts:
|
| 425 |
+
has_local_json = True
|
| 426 |
+
|
| 427 |
+
if has_local_format:
|
| 428 |
+
_rewrite_legacy_shorthands(args, rewrite_json=not has_local_json, rewrite_quiet=not has_local_quiet)
|
| 429 |
+
return
|
| 430 |
+
|
| 431 |
+
# Strip --format/--json/-q/--quiet from 'args' and apply to 'out'
|
| 432 |
+
chosen_mode: OutputFormatWithAuto = OutputFormatWithAuto.auto
|
| 433 |
+
chosen_flag: str | None = None
|
| 434 |
+
|
| 435 |
+
def _check_conflict(new_flag: str) -> None:
|
| 436 |
+
# Reject any second formatting flag before parsing values, so the user gets
|
| 437 |
+
# a "mutually exclusive" error rather than e.g. an "invalid value" error
|
| 438 |
+
# from the second flag's argument.
|
| 439 |
+
if chosen_flag is not None:
|
| 440 |
+
raise click.UsageError(f"'{chosen_flag}' and '{new_flag}' are mutually exclusive.")
|
| 441 |
+
|
| 442 |
+
i = 0
|
| 443 |
+
while i < len(args):
|
| 444 |
+
arg = args[i]
|
| 445 |
+
if arg == "--":
|
| 446 |
+
break # everything after '--' is a positional literal
|
| 447 |
+
if arg == "--format":
|
| 448 |
+
_check_conflict("--format")
|
| 449 |
+
if i + 1 >= len(args):
|
| 450 |
+
raise click.UsageError("Option '--format' requires a value.")
|
| 451 |
+
chosen_mode = _parse_format_value(args[i + 1])
|
| 452 |
+
chosen_flag = "--format"
|
| 453 |
+
del args[i : i + 2] # --format value => 2 args removed
|
| 454 |
+
continue
|
| 455 |
+
if arg.startswith("--format="):
|
| 456 |
+
_check_conflict("--format")
|
| 457 |
+
chosen_mode = _parse_format_value(arg[len("--format=") :])
|
| 458 |
+
chosen_flag = "--format"
|
| 459 |
+
del args[i : i + 1]
|
| 460 |
+
continue
|
| 461 |
+
if arg == "--json":
|
| 462 |
+
_check_conflict("--json")
|
| 463 |
+
chosen_mode = OutputFormatWithAuto.json
|
| 464 |
+
chosen_flag = "--json"
|
| 465 |
+
del args[i : i + 1]
|
| 466 |
+
continue
|
| 467 |
+
if arg in ("-q", "--quiet"):
|
| 468 |
+
_check_conflict(arg)
|
| 469 |
+
chosen_mode = OutputFormatWithAuto.quiet
|
| 470 |
+
chosen_flag = arg
|
| 471 |
+
del args[i : i + 1]
|
| 472 |
+
continue
|
| 473 |
+
i += 1
|
| 474 |
+
|
| 475 |
+
out.set_mode(chosen_mode)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def _rewrite_legacy_shorthands(args: list[str], *, rewrite_json: bool, rewrite_quiet: bool) -> None:
|
| 479 |
+
"""Rewrite --json / -q / --quiet to --format ... for legacy commands.
|
| 480 |
+
|
| 481 |
+
Used for commands like 'hf jobs ps' that still own their '--format' option.
|
| 482 |
+
The rewrite lets users keep using the global shorthand while click parses
|
| 483 |
+
'--format <value>' locally.
|
| 484 |
+
"""
|
| 485 |
+
has_format_in_args = any(arg == "--format" or arg.startswith("--format=") for arg in args)
|
| 486 |
+
|
| 487 |
+
if rewrite_json and "--json" in args:
|
| 488 |
+
if has_format_in_args:
|
| 489 |
+
raise click.UsageError("'--json' and '--format' are mutually exclusive.")
|
| 490 |
+
idx = args.index("--json")
|
| 491 |
+
args[idx : idx + 1] = ["--format", "json"]
|
| 492 |
+
has_format_in_args = True
|
| 493 |
+
|
| 494 |
+
if rewrite_quiet:
|
| 495 |
+
flag = "-q" if "-q" in args else ("--quiet" if "--quiet" in args else None)
|
| 496 |
+
if flag is not None:
|
| 497 |
+
if has_format_in_args:
|
| 498 |
+
raise click.UsageError(f"'{flag}' and '--format' are mutually exclusive.")
|
| 499 |
+
idx = args.index(flag)
|
| 500 |
+
args[idx : idx + 1] = ["--format", "quiet"]
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def _parse_format_value(value: str) -> "OutputFormatWithAuto":
|
| 504 |
+
try:
|
| 505 |
+
return OutputFormatWithAuto(value)
|
| 506 |
+
except ValueError:
|
| 507 |
+
valid = ", ".join(m.value for m in OutputFormatWithAuto)
|
| 508 |
+
raise click.UsageError(f"Invalid value for '--format': '{value}'. Valid values: {valid}.") from None
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _enrich_usage_error(error: click.UsageError, label: str, items: list[tuple[str, str]]) -> None:
|
| 512 |
+
"""Append a list of available options or commands to a usage error message."""
|
| 513 |
+
if not items or error.ctx is None or f"Available {label} for" in error.message:
|
| 514 |
+
return
|
| 515 |
+
cmd_path = error.ctx.command_path
|
| 516 |
+
lines = [f"\n\nAvailable {label} for '{cmd_path}':"]
|
| 517 |
+
for name, help_text in items:
|
| 518 |
+
lines.append(f" {name:30s} {help_text}")
|
| 519 |
+
lines.append(f"\nRun '{cmd_path} --help' for full details.")
|
| 520 |
+
if isinstance(error, click.NoSuchOption) and error.possibilities:
|
| 521 |
+
lines.append(f"\nDid you mean: {', '.join(sorted(error.possibilities))}?")
|
| 522 |
+
error.possibilities = []
|
| 523 |
+
error.message += "\n".join(lines)
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def fallback_typer_group_factory(
|
| 527 |
+
fallback_handler: FallbackHandlerT,
|
| 528 |
+
extra_commands_provider: Callable[[], list[tuple[str, str]]] | None = None,
|
| 529 |
+
) -> type[HFCliTyperGroup]:
|
| 530 |
+
"""Return a Typer group class that runs a fallback handler before command resolution."""
|
| 531 |
+
|
| 532 |
+
class FallbackTyperGroup(HFCliTyperGroup):
|
| 533 |
+
def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple:
|
| 534 |
+
fallback_exit_code = fallback_handler(args, set(self.commands.keys()))
|
| 535 |
+
if fallback_exit_code is not None:
|
| 536 |
+
raise SystemExit(fallback_exit_code)
|
| 537 |
+
return super().resolve_command(ctx, args)
|
| 538 |
+
|
| 539 |
+
def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
|
| 540 |
+
super().format_commands(ctx, formatter)
|
| 541 |
+
if extra_commands_provider is not None:
|
| 542 |
+
entries = extra_commands_provider()
|
| 543 |
+
if entries:
|
| 544 |
+
with formatter.section("Extension commands"):
|
| 545 |
+
formatter.write_dl(entries)
|
| 546 |
+
|
| 547 |
+
return FallbackTyperGroup
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def HFCliCommand(topic: TOPIC_T, examples: list[str] | None = None) -> type[TyperCommand]:
|
| 551 |
+
def format_epilog(self: click.Command, ctx: click.Context, formatter: click.HelpFormatter) -> None:
|
| 552 |
+
_format_epilog_no_indent(self.epilog, ctx, formatter)
|
| 553 |
+
|
| 554 |
+
def format_options(self: TyperCommand, ctx: click.Context, formatter: click.HelpFormatter) -> None:
|
| 555 |
+
TyperCommand.format_options(self, ctx, formatter)
|
| 556 |
+
# Skip the section for commands that define their own --format / --quiet / --json,
|
| 557 |
+
# or for pass-through commands that forward args to an external binary.
|
| 558 |
+
if _has_local_formatting_option(self):
|
| 559 |
+
return
|
| 560 |
+
if self.context_settings.get("ignore_unknown_options"):
|
| 561 |
+
return
|
| 562 |
+
_format_formatting_options_section(formatter)
|
| 563 |
+
|
| 564 |
+
def parse_args(self: click.Command, ctx: click.Context, args: list[str]) -> list[str]:
|
| 565 |
+
# Show help when a command with required arguments is invoked without any args
|
| 566 |
+
# (mirrors group behavior: `hf jobs` prints help, so `hf download` should too).
|
| 567 |
+
if not args and not ctx.resilient_parsing:
|
| 568 |
+
if any(isinstance(p, click.Argument) and p.required for p in self.params):
|
| 569 |
+
click.echo(ctx.get_help(), color=ctx.color)
|
| 570 |
+
ctx.exit()
|
| 571 |
+
return TyperCommand.parse_args(self, ctx, args)
|
| 572 |
+
|
| 573 |
+
return type(
|
| 574 |
+
f"TyperCommand{topic.capitalize()}",
|
| 575 |
+
(TyperCommand,),
|
| 576 |
+
{
|
| 577 |
+
"topic": topic,
|
| 578 |
+
"examples": examples or [],
|
| 579 |
+
"format_epilog": format_epilog,
|
| 580 |
+
"format_options": format_options,
|
| 581 |
+
"parse_args": parse_args,
|
| 582 |
+
},
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
class HFCliApp(typer.Typer):
|
| 587 |
+
"""Custom Typer app for Hugging Face CLI."""
|
| 588 |
+
|
| 589 |
+
def command( # type: ignore
|
| 590 |
+
self,
|
| 591 |
+
name: str | None = None,
|
| 592 |
+
*,
|
| 593 |
+
topic: TOPIC_T = "main",
|
| 594 |
+
examples: list[str] | None = None,
|
| 595 |
+
context_settings: dict[str, Any] | None = None,
|
| 596 |
+
help: str | None = None,
|
| 597 |
+
epilog: str | None = None,
|
| 598 |
+
short_help: str | None = None,
|
| 599 |
+
options_metavar: str = "[OPTIONS]",
|
| 600 |
+
add_help_option: bool = True,
|
| 601 |
+
no_args_is_help: bool = False,
|
| 602 |
+
hidden: bool = False,
|
| 603 |
+
deprecated: bool = False,
|
| 604 |
+
rich_help_panel: str | None = None,
|
| 605 |
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
| 606 |
+
# Generate epilog from examples if not explicitly provided
|
| 607 |
+
if epilog is None and examples:
|
| 608 |
+
epilog = generate_epilog(examples)
|
| 609 |
+
|
| 610 |
+
def _inner(func: Callable[..., Any]) -> Callable[..., Any]:
|
| 611 |
+
return super(HFCliApp, self).command(
|
| 612 |
+
name,
|
| 613 |
+
cls=HFCliCommand(topic, examples),
|
| 614 |
+
context_settings=context_settings,
|
| 615 |
+
help=help,
|
| 616 |
+
epilog=epilog,
|
| 617 |
+
short_help=short_help,
|
| 618 |
+
options_metavar=options_metavar,
|
| 619 |
+
add_help_option=add_help_option,
|
| 620 |
+
no_args_is_help=no_args_is_help,
|
| 621 |
+
hidden=hidden,
|
| 622 |
+
deprecated=deprecated,
|
| 623 |
+
rich_help_panel=rich_help_panel,
|
| 624 |
+
)(func)
|
| 625 |
+
|
| 626 |
+
return _inner
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def typer_factory(help: str, epilog: str | None = None, cls: type[TyperGroup] | None = None) -> "HFCliApp":
|
| 630 |
+
"""Create a Typer app with consistent settings.
|
| 631 |
+
|
| 632 |
+
Args:
|
| 633 |
+
help: Help text for the app.
|
| 634 |
+
epilog: Optional epilog text (use `generate_epilog` to create one).
|
| 635 |
+
cls: Optional Click group class to use (defaults to `HFCliTyperGroup`).
|
| 636 |
+
|
| 637 |
+
Returns:
|
| 638 |
+
A configured Typer app.
|
| 639 |
+
"""
|
| 640 |
+
if cls is None:
|
| 641 |
+
cls = HFCliTyperGroup
|
| 642 |
+
return HFCliApp(
|
| 643 |
+
help=help,
|
| 644 |
+
epilog=epilog,
|
| 645 |
+
add_completion=True,
|
| 646 |
+
no_args_is_help=True,
|
| 647 |
+
cls=cls,
|
| 648 |
+
# Disable rich completely for consistent experience
|
| 649 |
+
rich_markup_mode=None,
|
| 650 |
+
rich_help_panel=None,
|
| 651 |
+
pretty_exceptions_enable=False,
|
| 652 |
+
# Disable TyperGroup's suggest_commands, it matches against raw aliased
|
| 653 |
+
# keys ("list | ls") leaking pipe syntax into user-facing messages.
|
| 654 |
+
# HFCliTyperGroup.resolve_command() handles suggestions with expanded names.
|
| 655 |
+
suggest_commands=False,
|
| 656 |
+
# Increase max content width for better readability
|
| 657 |
+
context_settings={
|
| 658 |
+
"max_content_width": 120,
|
| 659 |
+
"help_option_names": ["-h", "--help"],
|
| 660 |
+
},
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class RepoType(str, Enum):
|
| 665 |
+
model = "model"
|
| 666 |
+
dataset = "dataset"
|
| 667 |
+
space = "space"
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
RepoIdArg = Annotated[
|
| 671 |
+
str,
|
| 672 |
+
typer.Argument(
|
| 673 |
+
help="The ID of the repo (e.g. `username/repo-name` or `spaces/username/repo-name`).",
|
| 674 |
+
),
|
| 675 |
+
]
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
RepoTypeOpt = Annotated[
|
| 679 |
+
RepoType,
|
| 680 |
+
typer.Option(
|
| 681 |
+
"--type",
|
| 682 |
+
"--repo-type",
|
| 683 |
+
help="The type of repository (model, dataset, or space).",
|
| 684 |
+
),
|
| 685 |
+
]
|
| 686 |
+
|
| 687 |
+
TokenOpt = Annotated[
|
| 688 |
+
str | None,
|
| 689 |
+
typer.Option(
|
| 690 |
+
help="A User Access Token generated from https://huggingface.co/settings/tokens.",
|
| 691 |
+
),
|
| 692 |
+
]
|
| 693 |
+
|
| 694 |
+
PrivateOpt = Annotated[
|
| 695 |
+
bool | None,
|
| 696 |
+
typer.Option(
|
| 697 |
+
help="Whether to create a private repo if repo doesn't exist on the Hub. Ignored if the repo already exists.",
|
| 698 |
+
),
|
| 699 |
+
]
|
| 700 |
+
|
| 701 |
+
RevisionOpt = Annotated[
|
| 702 |
+
str | None,
|
| 703 |
+
typer.Option(
|
| 704 |
+
help="Git revision id which can be a branch name, a tag, or a commit hash.",
|
| 705 |
+
),
|
| 706 |
+
]
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
LimitOpt = Annotated[
|
| 710 |
+
int,
|
| 711 |
+
typer.Option(help="Limit the number of results."),
|
| 712 |
+
]
|
| 713 |
+
|
| 714 |
+
AuthorOpt = Annotated[
|
| 715 |
+
str | None,
|
| 716 |
+
typer.Option(help="Filter by author or organization."),
|
| 717 |
+
]
|
| 718 |
+
|
| 719 |
+
FilterOpt = Annotated[
|
| 720 |
+
list[str] | None,
|
| 721 |
+
typer.Option(help="Filter by tags (e.g. 'text-classification'). Can be used multiple times."),
|
| 722 |
+
]
|
| 723 |
+
|
| 724 |
+
SearchOpt = Annotated[
|
| 725 |
+
str | None,
|
| 726 |
+
typer.Option(help="Search query."),
|
| 727 |
+
]
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
# --- Env / Secrets shared options and parsing helpers (used by jobs, repos, etc.) ---
|
| 731 |
+
|
| 732 |
+
EnvOpt = Annotated[
|
| 733 |
+
list[str] | None,
|
| 734 |
+
typer.Option(
|
| 735 |
+
"-e",
|
| 736 |
+
"--env",
|
| 737 |
+
help="Set environment variables. E.g. --env ENV=value",
|
| 738 |
+
),
|
| 739 |
+
]
|
| 740 |
+
|
| 741 |
+
SecretsOpt = Annotated[
|
| 742 |
+
list[str] | None,
|
| 743 |
+
typer.Option(
|
| 744 |
+
"-s",
|
| 745 |
+
"--secrets",
|
| 746 |
+
help=(
|
| 747 |
+
"Set secret environment variables. E.g. --secrets SECRET=value"
|
| 748 |
+
" or `--secrets HF_TOKEN` to pass your Hugging Face token."
|
| 749 |
+
),
|
| 750 |
+
),
|
| 751 |
+
]
|
| 752 |
+
|
| 753 |
+
EnvFileOpt = Annotated[
|
| 754 |
+
str | None,
|
| 755 |
+
typer.Option(
|
| 756 |
+
"--env-file",
|
| 757 |
+
help="Read in a file of environment variables.",
|
| 758 |
+
),
|
| 759 |
+
]
|
| 760 |
+
|
| 761 |
+
SecretsFileOpt = Annotated[
|
| 762 |
+
str | None,
|
| 763 |
+
typer.Option(
|
| 764 |
+
help="Read in a file of secret environment variables.",
|
| 765 |
+
),
|
| 766 |
+
]
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
def _get_extended_environ() -> dict[str, str]:
|
| 770 |
+
"""Return a copy of ``os.environ`` with the user's HF token injected (if available)."""
|
| 771 |
+
from huggingface_hub import get_token
|
| 772 |
+
|
| 773 |
+
extended_environ = os.environ.copy()
|
| 774 |
+
if (token := get_token()) is not None:
|
| 775 |
+
extended_environ["HF_TOKEN"] = token
|
| 776 |
+
return extended_environ
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
def parse_env_map(
|
| 780 |
+
env: list[str] | None = None,
|
| 781 |
+
env_file: str | None = None,
|
| 782 |
+
) -> dict[str, str | None]:
|
| 783 |
+
"""Parse ``-e``/``--env``/``-s``/``--secrets`` and ``--env-file``/``--secrets-file`` CLI args into a dict.
|
| 784 |
+
|
| 785 |
+
Uses an extended environment that includes the user's HF token so that
|
| 786 |
+
bare ``--secrets HF_TOKEN`` resolves correctly.
|
| 787 |
+
"""
|
| 788 |
+
extended_environ = _get_extended_environ()
|
| 789 |
+
env_map: dict[str, str | None] = {}
|
| 790 |
+
if env_file:
|
| 791 |
+
env_map.update(load_dotenv(Path(env_file).read_text(), environ=extended_environ))
|
| 792 |
+
for env_value in env or []:
|
| 793 |
+
env_map.update(load_dotenv(env_value, environ=extended_environ))
|
| 794 |
+
return env_map
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
def env_map_to_key_value_list(env_map: dict[str, str | None]) -> list[dict[str, str]] | None:
|
| 798 |
+
"""Convert an env/secrets dict to the ``[{"key": ..., "value": ...}]`` format used by the Hub API."""
|
| 799 |
+
if not env_map:
|
| 800 |
+
return None
|
| 801 |
+
return [{"key": k, "value": v or ""} for k, v in env_map.items()]
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
VolumesOpt = Annotated[
|
| 805 |
+
list[str] | None,
|
| 806 |
+
typer.Option(
|
| 807 |
+
"-v",
|
| 808 |
+
"--volume",
|
| 809 |
+
help="Mount one or more volumes. Format: hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. "
|
| 810 |
+
"TYPE is one of: models, datasets, spaces, buckets. "
|
| 811 |
+
"TYPE defaults to models if omitted. "
|
| 812 |
+
"models, datasets and spaces are always mounted read-only. buckets are read+write by default. "
|
| 813 |
+
"E.g. -v hf://org/m:/data or -v hf://datasets/org/ds:/data or -v hf://buckets/org/b:/mnt:ro",
|
| 814 |
+
),
|
| 815 |
+
]
|
| 816 |
+
|
| 817 |
+
_HF_PREFIX = "hf://"
|
| 818 |
+
_HF_VOLUME_TYPES = {
|
| 819 |
+
"models": constants.REPO_TYPE_MODEL,
|
| 820 |
+
"datasets": constants.REPO_TYPE_DATASET,
|
| 821 |
+
"spaces": constants.REPO_TYPE_SPACE,
|
| 822 |
+
"buckets": "bucket",
|
| 823 |
+
}
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
def parse_volumes(volumes: list[str] | None) -> "list[Volume] | None":
|
| 827 |
+
"""Parse volume specs from CLI arguments.
|
| 828 |
+
|
| 829 |
+
Format: hf://[TYPE/]SOURCE[/PATH]:/MOUNT_PATH[:ro|:rw]
|
| 830 |
+
Where TYPE is one of: models, datasets, spaces, buckets (defaults to models if omitted).
|
| 831 |
+
SOURCE is the repo/bucket identifier (e.g. 'username/my-model').
|
| 832 |
+
PATH is an optional subfolder inside the repo/bucket.
|
| 833 |
+
MOUNT_PATH starts with '/'.
|
| 834 |
+
Optional ':ro' or ':rw' suffix for read-only or read-write.
|
| 835 |
+
|
| 836 |
+
Examples:
|
| 837 |
+
hf://my-org/my-model:/data (model, implicit type)
|
| 838 |
+
hf://models/my-org/my-model:/data (model, explicit type)
|
| 839 |
+
hf://datasets/my-org/my-dataset:/data:ro
|
| 840 |
+
hf://buckets/my-org/my-bucket:/mnt
|
| 841 |
+
hf://spaces/my-org/my-space:/app
|
| 842 |
+
hf://datasets/org/ds/train:/data (with path inside repo)
|
| 843 |
+
hf://buckets/org/b/sub/dir:/mnt (with path inside bucket)
|
| 844 |
+
"""
|
| 845 |
+
|
| 846 |
+
if not volumes:
|
| 847 |
+
return None
|
| 848 |
+
|
| 849 |
+
result: list[Volume] = []
|
| 850 |
+
for raw_spec in volumes:
|
| 851 |
+
# Strip :ro/:rw suffix
|
| 852 |
+
spec = raw_spec
|
| 853 |
+
read_only = None
|
| 854 |
+
if spec.endswith(":ro"):
|
| 855 |
+
read_only = True
|
| 856 |
+
spec = spec[:-3]
|
| 857 |
+
elif spec.endswith(":rw"):
|
| 858 |
+
read_only = False
|
| 859 |
+
spec = spec[:-3]
|
| 860 |
+
|
| 861 |
+
# Validate hf:// prefix
|
| 862 |
+
if not spec.startswith(_HF_PREFIX):
|
| 863 |
+
raise CLIError(
|
| 864 |
+
f"Invalid volume format: '{raw_spec}'. Source must start with 'hf://'. "
|
| 865 |
+
f"Expected hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. E.g. hf://org/m:/data"
|
| 866 |
+
)
|
| 867 |
+
spec = spec[len(_HF_PREFIX) :]
|
| 868 |
+
|
| 869 |
+
# Find the mount path: look for :/ pattern
|
| 870 |
+
colon_slash_idx = spec.find(":/")
|
| 871 |
+
if colon_slash_idx == -1:
|
| 872 |
+
raise CLIError(
|
| 873 |
+
f"Invalid volume format: '{raw_spec}'. Expected hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. E.g. hf://org/m:/data"
|
| 874 |
+
)
|
| 875 |
+
source_part = spec[:colon_slash_idx]
|
| 876 |
+
mount_path = spec[colon_slash_idx + 1 :]
|
| 877 |
+
|
| 878 |
+
# Parse type from source_part (first segment before /)
|
| 879 |
+
# Then split remaining into source (namespace/name or name) and optional path.
|
| 880 |
+
slash_idx = source_part.find("/")
|
| 881 |
+
if slash_idx == -1:
|
| 882 |
+
# No slash: bare source like "gpt2" -> model type
|
| 883 |
+
vol_type_str = constants.REPO_TYPE_MODEL
|
| 884 |
+
source = source_part
|
| 885 |
+
path = None
|
| 886 |
+
else:
|
| 887 |
+
first_segment = source_part[:slash_idx]
|
| 888 |
+
if first_segment in _HF_VOLUME_TYPES:
|
| 889 |
+
vol_type_str = _HF_VOLUME_TYPES[first_segment]
|
| 890 |
+
remaining = source_part[slash_idx + 1 :]
|
| 891 |
+
else:
|
| 892 |
+
# First segment isn't a known type -> model type
|
| 893 |
+
vol_type_str = constants.REPO_TYPE_MODEL
|
| 894 |
+
remaining = source_part
|
| 895 |
+
|
| 896 |
+
# Split remaining into source (namespace/name) and optional path.
|
| 897 |
+
# Repo/bucket IDs are "namespace/name" (2 segments) or "name" (1 segment).
|
| 898 |
+
# Any extra segments are the path inside the repo/bucket.
|
| 899 |
+
parts = remaining.split("/", 2)
|
| 900 |
+
if len(parts) >= 3:
|
| 901 |
+
source = parts[0] + "/" + parts[1]
|
| 902 |
+
path = parts[2]
|
| 903 |
+
else:
|
| 904 |
+
source = remaining
|
| 905 |
+
path = None
|
| 906 |
+
|
| 907 |
+
result.append(
|
| 908 |
+
Volume(
|
| 909 |
+
type=vol_type_str,
|
| 910 |
+
source=source,
|
| 911 |
+
mount_path=mount_path,
|
| 912 |
+
read_only=read_only,
|
| 913 |
+
path=path,
|
| 914 |
+
)
|
| 915 |
+
)
|
| 916 |
+
return result
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
class OutputFormat(str, Enum):
|
| 920 |
+
"""Output format for CLI list commands."""
|
| 921 |
+
|
| 922 |
+
table = "table"
|
| 923 |
+
json = "json"
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
FormatOpt = Annotated[
|
| 927 |
+
OutputFormat,
|
| 928 |
+
typer.Option(
|
| 929 |
+
help="Output format (table or json).",
|
| 930 |
+
),
|
| 931 |
+
]
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
def _set_output_mode(value: OutputFormatWithAuto) -> OutputFormatWithAuto:
|
| 935 |
+
"""Callback for the legacy FormatWithAutoOpt option type.
|
| 936 |
+
|
| 937 |
+
Most commands now rely on the global --format / --json / -q flags consumed by _consume_format_flags_for_leaf instead
|
| 938 |
+
of declaring FormatWithAutoOpt themselves. This callback is kept for the rare cases where a command still wires
|
| 939 |
+
FormatWithAutoOpt explicitly.
|
| 940 |
+
"""
|
| 941 |
+
out.set_mode(value)
|
| 942 |
+
return value
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
FormatWithAutoOpt = Annotated[
|
| 946 |
+
OutputFormatWithAuto,
|
| 947 |
+
typer.Option(help="Output format.", callback=_set_output_mode),
|
| 948 |
+
]
|
| 949 |
+
|
| 950 |
+
QuietOpt = Annotated[
|
| 951 |
+
bool,
|
| 952 |
+
typer.Option("-q", "--quiet", help="Print only IDs (one per line)."),
|
| 953 |
+
]
|
| 954 |
+
|
| 955 |
+
|
| 956 |
+
def _to_header(name: str) -> str:
|
| 957 |
+
"""Convert a camelCase or PascalCase string to SCREAMING_SNAKE_CASE to be used as table header."""
|
| 958 |
+
s = re.sub(r"([a-z])([A-Z])", r"\1_\2", name)
|
| 959 |
+
return s.upper()
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
def _format_value(value: Any) -> str:
|
| 963 |
+
"""Convert a value to string for terminal display."""
|
| 964 |
+
if not value:
|
| 965 |
+
return ""
|
| 966 |
+
if isinstance(value, bool):
|
| 967 |
+
return "✔" if value else ""
|
| 968 |
+
if isinstance(value, datetime.datetime):
|
| 969 |
+
return value.strftime("%Y-%m-%d")
|
| 970 |
+
if isinstance(value, str) and re.match(r"^\d{4}-\d{2}-\d{2}T", value):
|
| 971 |
+
return value[:10]
|
| 972 |
+
if isinstance(value, list):
|
| 973 |
+
return ", ".join(_format_value(v) for v in value)
|
| 974 |
+
elif isinstance(value, dict):
|
| 975 |
+
if "name" in value: # Likely to be a user or org => print name
|
| 976 |
+
return str(value["name"])
|
| 977 |
+
# TODO: extend if needed
|
| 978 |
+
return json.dumps(value)
|
| 979 |
+
return str(value)
|
| 980 |
+
|
| 981 |
+
|
| 982 |
+
def _format_cell(value: Any, max_len: int = _MAX_CELL_LENGTH) -> str:
|
| 983 |
+
"""Format a value + truncate it for table display."""
|
| 984 |
+
cell = _format_value(value)
|
| 985 |
+
if len(cell) > max_len:
|
| 986 |
+
cell = cell[: max_len - 3] + "..."
|
| 987 |
+
return cell
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
def print_as_table(
|
| 991 |
+
items: Sequence[dict[str, Any]],
|
| 992 |
+
headers: list[str],
|
| 993 |
+
row_fn: Callable[[dict[str, Any]], list[str]],
|
| 994 |
+
alignments: dict[str, str] | None = None,
|
| 995 |
+
) -> None:
|
| 996 |
+
"""Print items as a formatted table.
|
| 997 |
+
|
| 998 |
+
Args:
|
| 999 |
+
items: Sequence of dictionaries representing the items to display.
|
| 1000 |
+
headers: List of column headers.
|
| 1001 |
+
row_fn: Function that takes an item dict and returns a list of string values for each column.
|
| 1002 |
+
alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
|
| 1003 |
+
"""
|
| 1004 |
+
if not items:
|
| 1005 |
+
print("No results found.")
|
| 1006 |
+
return
|
| 1007 |
+
rows = cast(list[list[Union[str, int]]], [row_fn(item) for item in items])
|
| 1008 |
+
screaming_headers = [_to_header(h) for h in headers]
|
| 1009 |
+
# Remap alignments keys to screaming case to match tabulate headers
|
| 1010 |
+
screaming_alignments = {_to_header(k): v for k, v in (alignments or {}).items()}
|
| 1011 |
+
print(tabulate(rows, headers=screaming_headers, alignments=screaming_alignments))
|
| 1012 |
+
|
| 1013 |
+
|
| 1014 |
+
def print_list_output(
|
| 1015 |
+
items: Sequence[dict[str, Any]],
|
| 1016 |
+
format: OutputFormat,
|
| 1017 |
+
quiet: bool,
|
| 1018 |
+
id_key: str = "id",
|
| 1019 |
+
headers: list[str] | None = None,
|
| 1020 |
+
row_fn: Callable[[dict[str, Any]], list[str]] | None = None,
|
| 1021 |
+
alignments: dict[str, str] | None = None,
|
| 1022 |
+
) -> None:
|
| 1023 |
+
"""Print list command output in the specified format.
|
| 1024 |
+
|
| 1025 |
+
Args:
|
| 1026 |
+
items: Sequence of dictionaries representing the items to display.
|
| 1027 |
+
format: Output format.
|
| 1028 |
+
quiet: If True, print only IDs (one per line).
|
| 1029 |
+
id_key: Key to use for extracting IDs in quiet mode.
|
| 1030 |
+
headers: Optional list of column names for headers. If not provided, auto-detected from keys.
|
| 1031 |
+
row_fn: Optional function to extract row values. If not provided, uses _format_cell on each column.
|
| 1032 |
+
alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
|
| 1033 |
+
"""
|
| 1034 |
+
if quiet:
|
| 1035 |
+
for item in items:
|
| 1036 |
+
print(item[id_key])
|
| 1037 |
+
return
|
| 1038 |
+
|
| 1039 |
+
if format == OutputFormat.json:
|
| 1040 |
+
print(json.dumps(list(items), indent=2, default=str))
|
| 1041 |
+
return
|
| 1042 |
+
|
| 1043 |
+
if headers is None:
|
| 1044 |
+
all_columns = list(items[0].keys()) if items else [id_key]
|
| 1045 |
+
headers = [col for col in all_columns if any(_format_cell(item.get(col)) for item in items)]
|
| 1046 |
+
|
| 1047 |
+
if row_fn is None:
|
| 1048 |
+
|
| 1049 |
+
def row_fn(item: dict[str, Any]) -> list[str]:
|
| 1050 |
+
return [_format_cell(item.get(col)) for col in headers] # type: ignore[union-attr]
|
| 1051 |
+
|
| 1052 |
+
print_as_table(items, headers=headers, row_fn=row_fn, alignments=alignments)
|
| 1053 |
+
|
| 1054 |
+
|
| 1055 |
+
def _serialize_value(v: object) -> object:
|
| 1056 |
+
"""Recursively serialize a value to be JSON-compatible."""
|
| 1057 |
+
if isinstance(v, datetime.datetime):
|
| 1058 |
+
return v.isoformat()
|
| 1059 |
+
elif isinstance(v, dict):
|
| 1060 |
+
return {key: _serialize_value(val) for key, val in v.items() if val is not None}
|
| 1061 |
+
elif isinstance(v, list):
|
| 1062 |
+
return [_serialize_value(item) for item in v]
|
| 1063 |
+
return v
|
| 1064 |
+
|
| 1065 |
+
|
| 1066 |
+
def api_object_to_dict(info: Any) -> dict[str, Any]:
|
| 1067 |
+
"""Convert repo info dataclasses to json-serializable dicts."""
|
| 1068 |
+
return {k: _serialize_value(v) for k, v in dataclasses.asdict(info).items() if v is not None}
|
| 1069 |
+
|
| 1070 |
+
|
| 1071 |
+
def make_expand_properties_parser(valid_properties: Sequence[ExpandPropertyT]):
|
| 1072 |
+
"""Create a callback to parse and validate comma-separated expand properties."""
|
| 1073 |
+
|
| 1074 |
+
def _parse_expand_properties(value: str | None) -> list[ExpandPropertyT] | None:
|
| 1075 |
+
if value is None:
|
| 1076 |
+
return None
|
| 1077 |
+
properties = [p.strip() for p in value.split(",")]
|
| 1078 |
+
for prop in properties:
|
| 1079 |
+
if prop not in valid_properties:
|
| 1080 |
+
raise typer.BadParameter(
|
| 1081 |
+
f"Invalid expand property: '{prop}'. Valid values are: {', '.join(valid_properties)}"
|
| 1082 |
+
)
|
| 1083 |
+
return [cast(ExpandPropertyT, prop) for prop in properties]
|
| 1084 |
+
|
| 1085 |
+
return _parse_expand_properties
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
### PyPI VERSION CHECKER
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
def check_cli_update(library: Literal["huggingface_hub", "transformers"]) -> None:
|
| 1092 |
+
"""
|
| 1093 |
+
Check whether a newer version of a library is available on PyPI.
|
| 1094 |
+
|
| 1095 |
+
If a newer version is found, print a hint pointing at `hf update`.
|
| 1096 |
+
|
| 1097 |
+
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.
|
| 1098 |
+
If `HF_HUB_DISABLE_UPDATE_CHECK` is set, the check is skipped entirely.
|
| 1099 |
+
|
| 1100 |
+
This function is called at the entry point of the CLI. It only performs the check once every 24 hours, and any error
|
| 1101 |
+
during the check is caught and logged, to avoid breaking the CLI.
|
| 1102 |
+
|
| 1103 |
+
Args:
|
| 1104 |
+
library: The library to check for updates. Currently supports "huggingface_hub" and "transformers".
|
| 1105 |
+
"""
|
| 1106 |
+
try:
|
| 1107 |
+
_check_cli_update(library)
|
| 1108 |
+
except Exception:
|
| 1109 |
+
# We don't want the CLI to fail on version checks, no matter the reason.
|
| 1110 |
+
logger.debug("Error while checking for CLI update.", exc_info=True)
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
def _check_cli_update(library: Literal["huggingface_hub", "transformers"]) -> None:
|
| 1114 |
+
if constants.HF_HUB_DISABLE_UPDATE_CHECK:
|
| 1115 |
+
return
|
| 1116 |
+
|
| 1117 |
+
current_version = importlib.metadata.version(library)
|
| 1118 |
+
|
| 1119 |
+
# Skip if current version is a pre-release or dev version
|
| 1120 |
+
if any(tag in current_version for tag in ["rc", "dev"]):
|
| 1121 |
+
return
|
| 1122 |
+
|
| 1123 |
+
# Skip if already checked in the last 24 hours
|
| 1124 |
+
if os.path.exists(constants.CHECK_FOR_UPDATE_DONE_PATH):
|
| 1125 |
+
mtime = os.path.getmtime(constants.CHECK_FOR_UPDATE_DONE_PATH)
|
| 1126 |
+
if (time.time() - mtime) < 24 * 3600:
|
| 1127 |
+
return
|
| 1128 |
+
|
| 1129 |
+
# Touch the file to mark that we did the check now
|
| 1130 |
+
Path(constants.CHECK_FOR_UPDATE_DONE_PATH).parent.mkdir(parents=True, exist_ok=True)
|
| 1131 |
+
Path(constants.CHECK_FOR_UPDATE_DONE_PATH).touch()
|
| 1132 |
+
|
| 1133 |
+
# Check latest version from PyPI
|
| 1134 |
+
latest_version = _fetch_latest_pypi_version(library)
|
| 1135 |
+
if latest_version is None or current_version == latest_version:
|
| 1136 |
+
return
|
| 1137 |
+
|
| 1138 |
+
if library == "huggingface_hub":
|
| 1139 |
+
update_command = _get_huggingface_hub_update_command()
|
| 1140 |
+
else:
|
| 1141 |
+
update_command = _get_transformers_update_command()
|
| 1142 |
+
|
| 1143 |
+
message = f"A new version of {library} ({latest_version}) is available! You are using version {current_version}."
|
| 1144 |
+
if update_command is not None:
|
| 1145 |
+
match library:
|
| 1146 |
+
case "huggingface_hub":
|
| 1147 |
+
message += "\nTo update, run: hf update"
|
| 1148 |
+
case _:
|
| 1149 |
+
message += f"\nTo update, run: {' '.join(update_command)}"
|
| 1150 |
+
out.hint(message)
|
| 1151 |
+
|
| 1152 |
+
|
| 1153 |
+
def _fetch_latest_pypi_version(library: str) -> str | None:
|
| 1154 |
+
"""Fetch the latest version of a library from PyPI. Returns None if the request fails."""
|
| 1155 |
+
try:
|
| 1156 |
+
response = get_session().get(f"https://pypi.org/pypi/{library}/json", timeout=2)
|
| 1157 |
+
hf_raise_for_status(response)
|
| 1158 |
+
return response.json()["info"]["version"]
|
| 1159 |
+
except Exception:
|
| 1160 |
+
logger.debug("Error while fetching latest version from PyPI.", exc_info=True)
|
| 1161 |
+
return None
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
def run_update() -> int:
|
| 1165 |
+
"""Run the install-method-appropriate update command for the `hf` CLI.
|
| 1166 |
+
|
| 1167 |
+
Raises CLIError if the installation method can't be determined.
|
| 1168 |
+
Returns the subprocess exit code on success/failure of the update itself.
|
| 1169 |
+
"""
|
| 1170 |
+
cmd = _get_huggingface_hub_update_command()
|
| 1171 |
+
if cmd is None:
|
| 1172 |
+
raise CLIError(
|
| 1173 |
+
"Cannot determine how to update huggingface_hub (unknown installation method). Please update manually."
|
| 1174 |
+
)
|
| 1175 |
+
return subprocess.call(cmd)
|
| 1176 |
+
|
| 1177 |
+
|
| 1178 |
+
def _get_huggingface_hub_update_command() -> list[str] | None:
|
| 1179 |
+
"""Return the command to update huggingface_hub as an argv list, or None if the installation method is unknown."""
|
| 1180 |
+
match installation_method():
|
| 1181 |
+
case "brew":
|
| 1182 |
+
return ["brew", "upgrade", "hf"]
|
| 1183 |
+
case "hf_installer" if os.name == "nt":
|
| 1184 |
+
return ["powershell", "-NoProfile", "-Command", "iwr -useb https://hf.co/cli/install.ps1 | iex"]
|
| 1185 |
+
case "hf_installer":
|
| 1186 |
+
return ["bash", "-c", "curl -LsSf https://hf.co/cli/install.sh | bash -"]
|
| 1187 |
+
case "pip":
|
| 1188 |
+
return [sys.executable, "-m", "pip", "install", "-U", "huggingface_hub"]
|
| 1189 |
+
case _:
|
| 1190 |
+
return None
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
def _get_transformers_update_command() -> list[str] | None:
|
| 1194 |
+
"""Return the command to update transformers as an argv list, or None if the installation method is unknown."""
|
| 1195 |
+
match installation_method():
|
| 1196 |
+
case "hf_installer" if os.name == "nt":
|
| 1197 |
+
return [
|
| 1198 |
+
"powershell",
|
| 1199 |
+
"-NoProfile",
|
| 1200 |
+
"-Command",
|
| 1201 |
+
"iwr -useb https://hf.co/cli/install.ps1 | iex -WithTransformers",
|
| 1202 |
+
]
|
| 1203 |
+
case "hf_installer":
|
| 1204 |
+
return ["bash", "-c", "curl -LsSf https://hf.co/cli/install.sh | bash -s -- --with-transformers"]
|
| 1205 |
+
case "pip":
|
| 1206 |
+
return [sys.executable, "-m", "pip", "install", "-U", "transformers"]
|
| 1207 |
+
case _:
|
| 1208 |
+
return None
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/_errors.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
EntryNotFoundError,
|
| 24 |
+
GatedRepoError,
|
| 25 |
+
HfHubHTTPError,
|
| 26 |
+
LocalTokenNotFoundError,
|
| 27 |
+
RemoteEntryNotFoundError,
|
| 28 |
+
RepositoryNotFoundError,
|
| 29 |
+
RevisionNotFoundError,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _format_repo_not_found(error: RepositoryNotFoundError) -> str:
|
| 34 |
+
label = error.repo_type.capitalize() if error.repo_type else "Repository"
|
| 35 |
+
if error.repo_id:
|
| 36 |
+
msg = f"{label} '{error.repo_id}' not found."
|
| 37 |
+
else:
|
| 38 |
+
msg = f"{label} not found."
|
| 39 |
+
msg += " If the repo is private, make sure you are authenticated and your token has the required permissions."
|
| 40 |
+
return msg
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _format_gated_repo(error: GatedRepoError) -> str:
|
| 44 |
+
label = error.repo_type if error.repo_type else "repository"
|
| 45 |
+
if error.repo_id:
|
| 46 |
+
return f"Access denied. {label.capitalize()} '{error.repo_id}' requires approval."
|
| 47 |
+
return f"Access denied. This {label} requires approval."
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _format_bucket_not_found(error: BucketNotFoundError) -> str:
|
| 51 |
+
if error.bucket_id:
|
| 52 |
+
return f"Bucket '{error.bucket_id}' not found. If the bucket is private, make sure you are authenticated and your token has the required permissions."
|
| 53 |
+
return "Bucket not found. Check the bucket id (namespace/name). If the bucket is private, make sure you are authenticated and your token has the required permissions."
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _format_entry_not_found(error: RemoteEntryNotFoundError) -> str:
|
| 57 |
+
label = error.repo_type if error.repo_type else "repository"
|
| 58 |
+
url = str(error.response.url) if error.response else None
|
| 59 |
+
if error.repo_id:
|
| 60 |
+
msg = f"File not found in {label} '{error.repo_id}'."
|
| 61 |
+
else:
|
| 62 |
+
msg = f"File not found in {label}."
|
| 63 |
+
if url:
|
| 64 |
+
msg += f"\nURL: {url}"
|
| 65 |
+
return msg
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _format_revision_not_found(error: RevisionNotFoundError) -> str:
|
| 69 |
+
label = error.repo_type if error.repo_type else "repository"
|
| 70 |
+
if error.repo_id:
|
| 71 |
+
return f"Revision not found in {label} '{error.repo_id}'."
|
| 72 |
+
return f"Revision not found in {label}. Check the revision parameter."
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _format_cli_error(error: CLIError) -> str:
|
| 76 |
+
"""No traceback, just the error message."""
|
| 77 |
+
return str(error)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _format_cli_extension_install_error(error: CLIExtensionInstallError) -> str:
|
| 81 |
+
"""Format a CLI extension installation error.
|
| 82 |
+
|
| 83 |
+
The error is likely to be a tricky subprocess error to investigate. In this specific case we want to format the
|
| 84 |
+
traceback of the root cause while keeping the "nicely formatted" error message of the CLIExtensionInstallError
|
| 85 |
+
as a 1-line message.
|
| 86 |
+
"""
|
| 87 |
+
cause_tb = (
|
| 88 |
+
"".join(traceback.format_exception(type(error.__cause__), error.__cause__, error.__cause__.__traceback__))
|
| 89 |
+
if error.__cause__ is not None
|
| 90 |
+
else ""
|
| 91 |
+
)
|
| 92 |
+
return f"{cause_tb}\n{error}"
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
CLI_ERROR_MAPPINGS: dict[type[Exception], Callable[..., str]] = {
|
| 96 |
+
# GatedRepoError must come before RepositoryNotFoundError (it's a subclass).
|
| 97 |
+
GatedRepoError: _format_gated_repo,
|
| 98 |
+
BucketNotFoundError: _format_bucket_not_found,
|
| 99 |
+
RepositoryNotFoundError: _format_repo_not_found,
|
| 100 |
+
RevisionNotFoundError: _format_revision_not_found,
|
| 101 |
+
LocalTokenNotFoundError: lambda _: "Not logged in. Run 'hf auth login' first.",
|
| 102 |
+
RemoteEntryNotFoundError: _format_entry_not_found,
|
| 103 |
+
EntryNotFoundError: lambda error: str(error),
|
| 104 |
+
HfHubHTTPError: lambda error: str(error),
|
| 105 |
+
ValueError: lambda error: f"Invalid value. {error}",
|
| 106 |
+
CLIExtensionInstallError: _format_cli_extension_install_error,
|
| 107 |
+
CLIError: _format_cli_error,
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def format_known_exception(error: Exception) -> str | None:
|
| 112 |
+
for exc_type, formatter in CLI_ERROR_MAPPINGS.items():
|
| 113 |
+
if isin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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Shared 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 typer
|
| 21 |
+
|
| 22 |
+
from huggingface_hub._buckets import BucketFile, BucketFolder
|
| 23 |
+
from huggingface_hub.hf_api import RepoFile, RepoFolder
|
| 24 |
+
|
| 25 |
+
from ._cli_utils import api_object_to_dict, get_hf_api
|
| 26 |
+
from ._output import OutputFormatWithAuto, 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 = "└── " if is_last else "├── "
|
| 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}{name}{'/' if is_dir else ''}")
|
| 151 |
+
else:
|
| 152 |
+
lines.append(f"{indent}{connector}{name}{'/' if is_dir else ''}")
|
| 153 |
+
|
| 154 |
+
if children:
|
| 155 |
+
child_indent = indent + (" " if is_last else "│ ")
|
| 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 == OutputFormatWithAuto.json:
|
| 177 |
+
raise typer.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 == OutputFormatWithAuto.quiet
|
| 204 |
+
for line in build_tree(items, human_readable=human_readable, quiet=quiet):
|
| 205 |
+
print(line)
|
| 206 |
+
elif out.mode == OutputFormatWithAuto.json:
|
| 207 |
+
print(json.dumps([api_object_to_dict(item) for item in items], indent=2))
|
| 208 |
+
elif out.mode == OutputFormatWithAuto.quiet:
|
| 209 |
+
for item in items:
|
| 210 |
+
if isinstance(item, BucketFolder | RepoFolder):
|
| 211 |
+
print(f"{item.path}/")
|
| 212 |
+
else:
|
| 213 |
+
print(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} {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} {item.path}")
|
| 223 |
+
|
| 224 |
+
if not recursive and has_directories:
|
| 225 |
+
out.hint("Use -R to list files recursively.")
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/_output.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Output framework for the `hf` CLI."""
|
| 15 |
+
|
| 16 |
+
import dataclasses
|
| 17 |
+
import datetime
|
| 18 |
+
import json
|
| 19 |
+
import re
|
| 20 |
+
import sys
|
| 21 |
+
from collections.abc import Sequence
|
| 22 |
+
from enum import Enum
|
| 23 |
+
from typing import Any
|
| 24 |
+
|
| 25 |
+
import typer
|
| 26 |
+
|
| 27 |
+
from huggingface_hub.errors import ConfirmationError
|
| 28 |
+
from huggingface_hub.utils import ANSI, StatusLine, disable_progress_bars, is_agent, tabulate
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# TODO: remove OutputFormat in _cli_utils.py once all commands are migrated to OutputFormatWithAuto.
|
| 32 |
+
class OutputFormatWithAuto(str, Enum):
|
| 33 |
+
"""Output format for CLI commands with auto detection of agent/human mode."""
|
| 34 |
+
|
| 35 |
+
agent = "agent"
|
| 36 |
+
auto = "auto"
|
| 37 |
+
human = "human"
|
| 38 |
+
json = "json"
|
| 39 |
+
quiet = "quiet"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Output:
|
| 43 |
+
"""Output sink for the `hf` CLI.
|
| 44 |
+
|
| 45 |
+
Mode is resolved once at init time based on `is_agent()` auto-detection
|
| 46 |
+
and can be overridden per-command via `set_mode()`.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
mode: OutputFormatWithAuto
|
| 50 |
+
|
| 51 |
+
def __init__(self) -> None:
|
| 52 |
+
self.set_mode()
|
| 53 |
+
|
| 54 |
+
def set_mode(self, mode: OutputFormatWithAuto = OutputFormatWithAuto.auto) -> None:
|
| 55 |
+
"""Override the output mode (called once at startup and again per '--format' flag)."""
|
| 56 |
+
if mode == OutputFormatWithAuto.auto:
|
| 57 |
+
mode = OutputFormatWithAuto.agent if is_agent() else OutputFormatWithAuto.human
|
| 58 |
+
self.mode = mode
|
| 59 |
+
if mode != OutputFormatWithAuto.human:
|
| 60 |
+
disable_progress_bars()
|
| 61 |
+
|
| 62 |
+
def is_quiet(self) -> bool:
|
| 63 |
+
return self.mode == OutputFormatWithAuto.quiet
|
| 64 |
+
|
| 65 |
+
def text(self, msg: str | None = None, *, human: str | None = None, agent: str | None = None) -> None:
|
| 66 |
+
"""Print a free-form text message to stdout."""
|
| 67 |
+
if msg is not None:
|
| 68 |
+
if human is not None or agent is not None:
|
| 69 |
+
raise ValueError("Cannot mix 'msg' with 'human'/'agent'.")
|
| 70 |
+
human = msg
|
| 71 |
+
agent = _strip_ansi(msg)
|
| 72 |
+
|
| 73 |
+
match self.mode:
|
| 74 |
+
case OutputFormatWithAuto.human:
|
| 75 |
+
if human is not None:
|
| 76 |
+
print(human)
|
| 77 |
+
case OutputFormatWithAuto.agent:
|
| 78 |
+
if agent is not None:
|
| 79 |
+
print(agent)
|
| 80 |
+
# json/quiet: no-op
|
| 81 |
+
|
| 82 |
+
def table(
|
| 83 |
+
self,
|
| 84 |
+
items: Sequence[dict[str, Any]],
|
| 85 |
+
*,
|
| 86 |
+
headers: list[str] | None = None,
|
| 87 |
+
id_key: str | None = None,
|
| 88 |
+
alignments: dict[str, str] | None = None,
|
| 89 |
+
) -> None:
|
| 90 |
+
"""Print tabular data to stdout.
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
items: List of dicts. Headers are auto-detected from keys if not provided.
|
| 94 |
+
headers: Explicit column names. If None, derived from dict keys (all-None columns filtered).
|
| 95 |
+
id_key: Key to print in quiet mode. If None, uses the first header.
|
| 96 |
+
alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
|
| 97 |
+
"""
|
| 98 |
+
if not items:
|
| 99 |
+
match self.mode:
|
| 100 |
+
case OutputFormatWithAuto.agent | OutputFormatWithAuto.human:
|
| 101 |
+
print("No results found.")
|
| 102 |
+
case OutputFormatWithAuto.json:
|
| 103 |
+
print("[]")
|
| 104 |
+
return
|
| 105 |
+
|
| 106 |
+
if headers is None:
|
| 107 |
+
all_columns = list(items[0].keys())
|
| 108 |
+
headers = [col for col in all_columns if any(item.get(col) is not None for item in items)]
|
| 109 |
+
rows = [[item.get(h) for h in headers] for item in items]
|
| 110 |
+
|
| 111 |
+
match self.mode:
|
| 112 |
+
case OutputFormatWithAuto.human: # padded table, truncated cells, SCREAMING_SNAKE headers
|
| 113 |
+
formatted_rows: list[list[str | int]] = [[_format_table_cell_human(v) for v in row] for row in rows]
|
| 114 |
+
screaming_headers = [_to_header(h) for h in headers]
|
| 115 |
+
screaming_alignments = {_to_header(k): v for k, v in (alignments or {}).items()}
|
| 116 |
+
print(tabulate(formatted_rows, headers=screaming_headers, alignments=screaming_alignments))
|
| 117 |
+
case OutputFormatWithAuto.agent: # TSV, no truncation, full timestamps
|
| 118 |
+
print("\t".join(headers))
|
| 119 |
+
for row in rows:
|
| 120 |
+
print("\t".join(_format_table_cell_agent(v) for v in row))
|
| 121 |
+
case OutputFormatWithAuto.json: # compact JSON array
|
| 122 |
+
print(json.dumps(list(items), default=str))
|
| 123 |
+
case OutputFormatWithAuto.quiet: # id_key column (or first column), one per line
|
| 124 |
+
quiet_key = id_key or headers[0]
|
| 125 |
+
for item in items:
|
| 126 |
+
print(item.get(quiet_key, ""))
|
| 127 |
+
|
| 128 |
+
def dict(self, data: Any, *, id_key: str | None = None) -> None:
|
| 129 |
+
"""Print structured data as JSON in all modes (indented for human, compact otherwise).
|
| 130 |
+
|
| 131 |
+
Accepts a dict or a dataclass.
|
| 132 |
+
"""
|
| 133 |
+
if dataclasses.is_dataclass(data) and not isinstance(data, type):
|
| 134 |
+
data = _dataclass_to_dict(data)
|
| 135 |
+
if self.mode == OutputFormatWithAuto.quiet and id_key is not None:
|
| 136 |
+
print(data.get(id_key, ""))
|
| 137 |
+
return
|
| 138 |
+
indent = 2 if self.mode == OutputFormatWithAuto.human else None
|
| 139 |
+
print(json.dumps(data, indent=indent, default=str))
|
| 140 |
+
|
| 141 |
+
def result(self, message: str, **data: Any) -> None:
|
| 142 |
+
"""Print a success summary to stdout."""
|
| 143 |
+
match self.mode:
|
| 144 |
+
case OutputFormatWithAuto.human: # ✓ message + key: value lines
|
| 145 |
+
parts = [ANSI.green(f"✓ {message}")]
|
| 146 |
+
for k, v in data.items():
|
| 147 |
+
if v is not None:
|
| 148 |
+
parts.append(f" {k}: {v}")
|
| 149 |
+
print("\n".join(parts))
|
| 150 |
+
case OutputFormatWithAuto.agent: # key=val pairs, space-separated
|
| 151 |
+
parts = [f"{k}={v}" for k, v in data.items() if v is not None]
|
| 152 |
+
print(" ".join(parts) if parts else message)
|
| 153 |
+
case OutputFormatWithAuto.json: # json.dumps(data), message ignored
|
| 154 |
+
print(json.dumps(data, default=str) if data else "")
|
| 155 |
+
case OutputFormatWithAuto.quiet: # first value only
|
| 156 |
+
values = list(data.values())
|
| 157 |
+
if values:
|
| 158 |
+
print(values[0])
|
| 159 |
+
|
| 160 |
+
def confirm(self, message: str, *, default: bool = False, yes: bool = False) -> None:
|
| 161 |
+
"""
|
| 162 |
+
Ask for confirmation. Raises `ConfirmationError` in non-human modes.
|
| 163 |
+
"""
|
| 164 |
+
if yes:
|
| 165 |
+
return
|
| 166 |
+
if self.mode != OutputFormatWithAuto.human:
|
| 167 |
+
raise ConfirmationError(f"{message} Use --yes to skip confirmation.")
|
| 168 |
+
typer.confirm(message, default=default, abort=True)
|
| 169 |
+
|
| 170 |
+
def status(self, message: str | None = None) -> StatusLine:
|
| 171 |
+
"""Return a status line that emits only in human mode (no-op otherwise)."""
|
| 172 |
+
status = StatusLine(enabled=self.mode == OutputFormatWithAuto.human)
|
| 173 |
+
if message is not None:
|
| 174 |
+
status.update(message)
|
| 175 |
+
return status
|
| 176 |
+
|
| 177 |
+
def warning(self, message: str) -> None:
|
| 178 |
+
"""Print a non-fatal warning to stderr (all modes)."""
|
| 179 |
+
if self.mode == OutputFormatWithAuto.human:
|
| 180 |
+
print(ANSI.yellow(f"Warning: {message}"), file=sys.stderr)
|
| 181 |
+
else:
|
| 182 |
+
print(f"Warning: {message}", file=sys.stderr)
|
| 183 |
+
|
| 184 |
+
def error(self, message: str) -> None:
|
| 185 |
+
"""Print an error to stderr (all modes)."""
|
| 186 |
+
if self.mode == OutputFormatWithAuto.human:
|
| 187 |
+
print(ANSI.red(f"Error: {message}"), file=sys.stderr)
|
| 188 |
+
else:
|
| 189 |
+
print(f"Error: {message}", file=sys.stderr)
|
| 190 |
+
|
| 191 |
+
def hint(self, message: str) -> None:
|
| 192 |
+
"""Print a helpful hint to stderr (human: gray, agent/json: plain text)."""
|
| 193 |
+
if self.mode == OutputFormatWithAuto.human:
|
| 194 |
+
print(ANSI.gray(f"Hint: {message}"), file=sys.stderr)
|
| 195 |
+
else:
|
| 196 |
+
print(f"Hint: {message}", file=sys.stderr)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# HELPERS
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _serialize_value(v: object) -> object:
|
| 203 |
+
"""Recursively serialize a value to be JSON-compatible."""
|
| 204 |
+
if isinstance(v, datetime.datetime):
|
| 205 |
+
return v.isoformat()
|
| 206 |
+
elif isinstance(v, dict):
|
| 207 |
+
return {key: _serialize_value(val) for key, val in v.items() if val is not None}
|
| 208 |
+
elif isinstance(v, list):
|
| 209 |
+
return [_serialize_value(item) for item in v]
|
| 210 |
+
return v
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _dataclass_to_dict(info: Any) -> dict[str, Any]:
|
| 214 |
+
"""Convert a dataclass to a json-serializable dict."""
|
| 215 |
+
return {k: _serialize_value(v) for k, v in dataclasses.asdict(info).items() if v is not None}
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
_ANSI_RE = re.compile(r"\033\[[0-9;]*m")
|
| 219 |
+
_MAX_CELL_LENGTH = 35
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _strip_ansi(text: str) -> str:
|
| 223 |
+
return _ANSI_RE.sub("", text)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _single_line(text: str) -> str:
|
| 227 |
+
return " ".join(text.split())
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _to_header(name: str) -> str:
|
| 231 |
+
"""Convert a camelCase or PascalCase string to SCREAMING_SNAKE_CASE."""
|
| 232 |
+
s = re.sub(r"([a-z])([A-Z])", r"\1_\2", name)
|
| 233 |
+
return s.upper()
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _format_table_value_human(value: Any) -> str:
|
| 237 |
+
"""Convert a value to string for terminal display."""
|
| 238 |
+
if value is None:
|
| 239 |
+
return ""
|
| 240 |
+
if isinstance(value, bool):
|
| 241 |
+
return "✔" if value else ""
|
| 242 |
+
if isinstance(value, datetime.datetime):
|
| 243 |
+
return value.strftime("%Y-%m-%d")
|
| 244 |
+
if isinstance(value, str) and re.match(r"^\d{4}-\d{2}-\d{2}T", value):
|
| 245 |
+
return value[:10]
|
| 246 |
+
if isinstance(value, str):
|
| 247 |
+
return _single_line(value)
|
| 248 |
+
if isinstance(value, list):
|
| 249 |
+
return ", ".join(_format_table_value_human(v) for v in value)
|
| 250 |
+
elif isinstance(value, dict):
|
| 251 |
+
if "name" in value: # Likely to be a user or org => print name
|
| 252 |
+
return _single_line(str(value["name"]))
|
| 253 |
+
return _single_line(json.dumps(value))
|
| 254 |
+
return _single_line(str(value))
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _format_table_cell_human(value: Any, max_len: int = _MAX_CELL_LENGTH) -> str:
|
| 258 |
+
"""Format a value + truncate it for table display."""
|
| 259 |
+
cell = _format_table_value_human(value)
|
| 260 |
+
if len(cell) > max_len:
|
| 261 |
+
cell = cell[: max_len - 3] + "..."
|
| 262 |
+
return cell
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _format_table_cell_agent(value: Any) -> str:
|
| 266 |
+
"""Format a cell value for agent TSV output (ISO timestamps, tabs escaped)."""
|
| 267 |
+
if isinstance(value, datetime.datetime):
|
| 268 |
+
return value.isoformat()
|
| 269 |
+
return _single_line(str(value))
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
out = Output()
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/_skills.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Internal helpers for Hugging Face marketplace skill installation and upgrades."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import shutil
|
| 5 |
+
import tempfile
|
| 6 |
+
from dataclasses import dataclass, replace
|
| 7 |
+
from pathlib import Path, PurePosixPath
|
| 8 |
+
from typing import Any, Literal
|
| 9 |
+
|
| 10 |
+
from huggingface_hub._buckets import BucketFile
|
| 11 |
+
from huggingface_hub.errors import CLIError
|
| 12 |
+
|
| 13 |
+
from ..utils import disable_progress_bars
|
| 14 |
+
from ._cli_utils import get_hf_api
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
DEFAULT_SKILLS_BUCKET_ID = "huggingface/skills"
|
| 18 |
+
MARKETPLACE_PATH = "marketplace.json"
|
| 19 |
+
# Empty marker file dropped into managed skill installs so `hf skills update` knows
|
| 20 |
+
# to touch them and leave user-placed skill dirs alone. Filename is historical (used
|
| 21 |
+
# to be a JSON manifest with a revision); we keep it for backward compat with installs
|
| 22 |
+
# made by previous versions.
|
| 23 |
+
MANAGED_MARKER_FILENAME = ".hf-skill-manifest.json"
|
| 24 |
+
|
| 25 |
+
SkillUpdateStatus = Literal["up_to_date", "unmanaged", "source_unreachable"]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass(frozen=True)
|
| 29 |
+
class MarketplaceSkill:
|
| 30 |
+
name: str
|
| 31 |
+
repo_path: str
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass(frozen=True)
|
| 35 |
+
class SkillUpdateInfo:
|
| 36 |
+
name: str
|
| 37 |
+
skill_dir: Path
|
| 38 |
+
status: SkillUpdateStatus
|
| 39 |
+
detail: str | None = None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def add_skill(skill_name: str, destination_root: Path, force: bool = False) -> Path:
|
| 43 |
+
"""Resolve a marketplace skill by name and install it."""
|
| 44 |
+
api = get_hf_api()
|
| 45 |
+
with disable_progress_bars():
|
| 46 |
+
marketplace_skills = _load_marketplace_skills(api)
|
| 47 |
+
skill = _select_marketplace_skill(marketplace_skills, skill_name)
|
| 48 |
+
if skill is None:
|
| 49 |
+
raise CLIError(
|
| 50 |
+
f"Skill '{skill_name}' not found in {DEFAULT_SKILLS_BUCKET_ID}. "
|
| 51 |
+
"Try `hf skills add` to install `hf-cli` or use a known skill name."
|
| 52 |
+
)
|
| 53 |
+
return _install_marketplace_skill(api, skill, destination_root, force=force)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def update_skills(roots: list[Path], selector: str | None = None) -> list[SkillUpdateInfo]:
|
| 57 |
+
"""Re-sync managed marketplace skill installs from the bucket."""
|
| 58 |
+
skill_dirs = _iter_unique_skill_dirs(roots)
|
| 59 |
+
if selector is not None:
|
| 60 |
+
selector_lower = selector.strip().lower()
|
| 61 |
+
skill_dirs = [d for d in skill_dirs if d.name.lower() == selector_lower]
|
| 62 |
+
if not skill_dirs:
|
| 63 |
+
raise CLIError(f"No installed skill matches '{selector}'. Install it with `hf skills add {selector}`.")
|
| 64 |
+
|
| 65 |
+
api = get_hf_api()
|
| 66 |
+
with disable_progress_bars():
|
| 67 |
+
marketplace_skills = {skill.name.lower(): skill for skill in _load_marketplace_skills(api)}
|
| 68 |
+
return [_apply_single_update(api, skill_dir, marketplace_skills) for skill_dir in skill_dirs]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _load_marketplace_skills(api) -> list[MarketplaceSkill]:
|
| 72 |
+
payload = _load_marketplace_payload(api)
|
| 73 |
+
plugins = payload.get("plugins")
|
| 74 |
+
if not isinstance(plugins, list):
|
| 75 |
+
raise CLIError("Invalid marketplace payload: expected a top-level 'plugins' list.")
|
| 76 |
+
|
| 77 |
+
skills: list[MarketplaceSkill] = []
|
| 78 |
+
for plugin in plugins:
|
| 79 |
+
if not isinstance(plugin, dict):
|
| 80 |
+
continue
|
| 81 |
+
name = plugin.get("name")
|
| 82 |
+
source = plugin.get("source")
|
| 83 |
+
if not isinstance(name, str) or not isinstance(source, str):
|
| 84 |
+
continue
|
| 85 |
+
skills.append(MarketplaceSkill(name=name, repo_path=_normalize_repo_path(source)))
|
| 86 |
+
return skills
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _install_marketplace_skill(api, skill: MarketplaceSkill, destination_root: Path, force: bool = False) -> Path:
|
| 90 |
+
"""Install a marketplace skill into a local skills directory."""
|
| 91 |
+
destination_root = destination_root.expanduser().resolve()
|
| 92 |
+
destination_root.mkdir(parents=True, exist_ok=True)
|
| 93 |
+
install_dir = destination_root / skill.name
|
| 94 |
+
already_exists = install_dir.exists()
|
| 95 |
+
|
| 96 |
+
if already_exists and not force:
|
| 97 |
+
raise FileExistsError(f"Skill already exists: {install_dir}")
|
| 98 |
+
|
| 99 |
+
if already_exists:
|
| 100 |
+
# Stage the new content in a sibling tempdir and atomically rename, so the
|
| 101 |
+
# existing install stays intact if the download fails halfway through.
|
| 102 |
+
with tempfile.TemporaryDirectory(dir=destination_root, prefix=f".{install_dir.name}.install-") as tmp_dir_str:
|
| 103 |
+
staged_dir = Path(tmp_dir_str) / install_dir.name
|
| 104 |
+
_populate_install_dir(api, skill=skill, install_dir=staged_dir)
|
| 105 |
+
_atomic_replace_directory(existing_dir=install_dir, staged_dir=staged_dir)
|
| 106 |
+
return install_dir
|
| 107 |
+
|
| 108 |
+
try:
|
| 109 |
+
_populate_install_dir(api, skill=skill, install_dir=install_dir)
|
| 110 |
+
except Exception:
|
| 111 |
+
if install_dir.exists():
|
| 112 |
+
shutil.rmtree(install_dir)
|
| 113 |
+
raise
|
| 114 |
+
return install_dir
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _load_marketplace_payload(api) -> dict[str, Any]:
|
| 118 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 119 |
+
local_path = Path(tmp_dir) / "marketplace.json"
|
| 120 |
+
api.download_bucket_files(
|
| 121 |
+
DEFAULT_SKILLS_BUCKET_ID,
|
| 122 |
+
[(MARKETPLACE_PATH, local_path)],
|
| 123 |
+
raise_on_missing_files=True,
|
| 124 |
+
)
|
| 125 |
+
parsed = json.loads(local_path.read_text(encoding="utf-8"))
|
| 126 |
+
|
| 127 |
+
if not isinstance(parsed, dict):
|
| 128 |
+
raise CLIError("Invalid marketplace payload: expected a JSON object.")
|
| 129 |
+
return parsed
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _select_marketplace_skill(skills: list[MarketplaceSkill], selector: str) -> MarketplaceSkill | None:
|
| 133 |
+
selector_lower = selector.strip().lower()
|
| 134 |
+
for skill in skills:
|
| 135 |
+
if skill.name.lower() == selector_lower:
|
| 136 |
+
return skill
|
| 137 |
+
return None
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _normalize_repo_path(path: str) -> str:
|
| 141 |
+
normalized = path.strip()
|
| 142 |
+
while normalized.startswith("./"):
|
| 143 |
+
normalized = normalized[2:]
|
| 144 |
+
normalized = normalized.strip("/")
|
| 145 |
+
if not normalized:
|
| 146 |
+
raise CLIError("Invalid marketplace entry: empty source path.")
|
| 147 |
+
return normalized
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _populate_install_dir(api, skill: MarketplaceSkill, install_dir: Path) -> None:
|
| 151 |
+
install_dir.mkdir(parents=True, exist_ok=True)
|
| 152 |
+
bucket_files = _list_skill_files(api, skill)
|
| 153 |
+
_download_skill_files(api, skill, bucket_files, install_dir)
|
| 154 |
+
_validate_installed_skill_dir(install_dir)
|
| 155 |
+
(install_dir / MANAGED_MARKER_FILENAME).touch()
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _validate_installed_skill_dir(skill_dir: Path) -> None:
|
| 159 |
+
skill_file = skill_dir / "SKILL.md"
|
| 160 |
+
if not skill_file.is_file():
|
| 161 |
+
raise RuntimeError(f"Installed skill is missing SKILL.md: {skill_file}")
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _list_skill_files(api, skill: MarketplaceSkill) -> list[BucketFile]:
|
| 165 |
+
"""List all files under `skill.repo_path` in the marketplace bucket."""
|
| 166 |
+
prefix = skill.repo_path.rstrip("/")
|
| 167 |
+
files: list[BucketFile] = [
|
| 168 |
+
item
|
| 169 |
+
for item in api.list_bucket_tree(DEFAULT_SKILLS_BUCKET_ID, prefix=prefix, recursive=True)
|
| 170 |
+
if isinstance(item, BucketFile)
|
| 171 |
+
]
|
| 172 |
+
if not files:
|
| 173 |
+
raise FileNotFoundError(f"Path '{prefix}' not found in bucket '{DEFAULT_SKILLS_BUCKET_ID}'.")
|
| 174 |
+
return files
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _download_skill_files(api, skill: MarketplaceSkill, files: list[BucketFile], install_dir: Path) -> None:
|
| 178 |
+
"""Download bucket files into `install_dir`."""
|
| 179 |
+
prefix = skill.repo_path.rstrip("/")
|
| 180 |
+
prefix_with_slash = f"{prefix}/"
|
| 181 |
+
|
| 182 |
+
# `list_bucket_tree(prefix=...)` matches as a raw string prefix, so e.g. asking for
|
| 183 |
+
# "skills/gradio" can also return "skills/gradio-tools/...". Filter on the trailing
|
| 184 |
+
# slash to keep only files actually inside the directory, then strip it so files land
|
| 185 |
+
# directly under `install_dir` preserving any nested structure.
|
| 186 |
+
download_specs: list[tuple[str | BucketFile, str | Path]] = []
|
| 187 |
+
for bucket_file in files:
|
| 188 |
+
if not bucket_file.path.startswith(prefix_with_slash):
|
| 189 |
+
continue
|
| 190 |
+
relative = bucket_file.path[len(prefix_with_slash) :]
|
| 191 |
+
local_file = install_dir.joinpath(*PurePosixPath(relative).parts)
|
| 192 |
+
local_file.parent.mkdir(parents=True, exist_ok=True)
|
| 193 |
+
download_specs.append((bucket_file, local_file))
|
| 194 |
+
|
| 195 |
+
if not download_specs:
|
| 196 |
+
raise FileNotFoundError(f"No files found under '{prefix}' in bucket '{DEFAULT_SKILLS_BUCKET_ID}'.")
|
| 197 |
+
|
| 198 |
+
api.download_bucket_files(DEFAULT_SKILLS_BUCKET_ID, download_specs)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _atomic_replace_directory(existing_dir: Path, staged_dir: Path) -> None:
|
| 202 |
+
backup_dir = staged_dir.parent / f"{existing_dir.name}.backup"
|
| 203 |
+
try:
|
| 204 |
+
existing_dir.rename(backup_dir)
|
| 205 |
+
staged_dir.rename(existing_dir)
|
| 206 |
+
shutil.rmtree(backup_dir)
|
| 207 |
+
except Exception:
|
| 208 |
+
if backup_dir.exists() and not existing_dir.exists():
|
| 209 |
+
backup_dir.rename(existing_dir)
|
| 210 |
+
raise
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _iter_unique_skill_dirs(roots: list[Path]) -> list[Path]:
|
| 214 |
+
seen: set[Path] = set()
|
| 215 |
+
discovered: list[Path] = []
|
| 216 |
+
for root in roots:
|
| 217 |
+
root = root.expanduser().resolve()
|
| 218 |
+
if not root.is_dir():
|
| 219 |
+
continue
|
| 220 |
+
for child in sorted(root.iterdir()):
|
| 221 |
+
if child.name.startswith("."):
|
| 222 |
+
continue
|
| 223 |
+
if not child.is_dir() and not child.is_symlink():
|
| 224 |
+
continue
|
| 225 |
+
resolved = child.resolve()
|
| 226 |
+
if resolved in seen or not resolved.is_dir():
|
| 227 |
+
continue
|
| 228 |
+
seen.add(resolved)
|
| 229 |
+
discovered.append(resolved)
|
| 230 |
+
return discovered
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _apply_single_update(api, skill_dir: Path, marketplace_skills: dict[str, MarketplaceSkill]) -> SkillUpdateInfo:
|
| 234 |
+
base = SkillUpdateInfo(name=skill_dir.name, skill_dir=skill_dir, status="unmanaged")
|
| 235 |
+
|
| 236 |
+
if not (skill_dir / MANAGED_MARKER_FILENAME).exists():
|
| 237 |
+
return base
|
| 238 |
+
|
| 239 |
+
skill = marketplace_skills.get(skill_dir.name.lower())
|
| 240 |
+
if skill is None:
|
| 241 |
+
return replace(
|
| 242 |
+
base,
|
| 243 |
+
status="source_unreachable",
|
| 244 |
+
detail=f"Skill '{skill_dir.name}' is no longer available in {DEFAULT_SKILLS_BUCKET_ID}.",
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
try:
|
| 248 |
+
_install_marketplace_skill(api, skill, skill_dir.parent, force=True)
|
| 249 |
+
except Exception as exc:
|
| 250 |
+
return replace(base, status="source_unreachable", detail=str(exc))
|
| 251 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to authenticate to the Hugging Face Hub and interact with your repositories.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# login and save token locally.
|
| 18 |
+
hf auth login --token=hf_*** --add-to-git-credential
|
| 19 |
+
|
| 20 |
+
# switch between tokens
|
| 21 |
+
hf auth switch
|
| 22 |
+
|
| 23 |
+
# list all tokens
|
| 24 |
+
hf auth list
|
| 25 |
+
|
| 26 |
+
# logout from all tokens
|
| 27 |
+
hf auth logout
|
| 28 |
+
|
| 29 |
+
# check which account you are logged in as
|
| 30 |
+
hf auth whoami
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
from typing import Annotated
|
| 34 |
+
|
| 35 |
+
import typer
|
| 36 |
+
|
| 37 |
+
from huggingface_hub.constants import ENDPOINT
|
| 38 |
+
from huggingface_hub.hf_api import whoami
|
| 39 |
+
|
| 40 |
+
from .._login import auth_list, auth_switch, login, logout
|
| 41 |
+
from ..utils import get_stored_tokens, get_token, logging
|
| 42 |
+
from ._cli_utils import TokenOpt, typer_factory
|
| 43 |
+
from ._output import out
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
auth_cli = typer_factory(help="Manage authentication (login, logout, etc.).")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@auth_cli.command(
|
| 53 |
+
"login",
|
| 54 |
+
examples=[
|
| 55 |
+
"hf auth login",
|
| 56 |
+
"hf auth login --token $HF_TOKEN",
|
| 57 |
+
"hf auth login --token $HF_TOKEN --add-to-git-credential",
|
| 58 |
+
"hf auth login --force",
|
| 59 |
+
],
|
| 60 |
+
)
|
| 61 |
+
def auth_login(
|
| 62 |
+
token: TokenOpt = None,
|
| 63 |
+
add_to_git_credential: Annotated[
|
| 64 |
+
bool,
|
| 65 |
+
typer.Option(
|
| 66 |
+
help="Save to git credential helper. Useful only if you plan to run git commands directly.",
|
| 67 |
+
),
|
| 68 |
+
] = False,
|
| 69 |
+
force: Annotated[
|
| 70 |
+
bool,
|
| 71 |
+
typer.Option(
|
| 72 |
+
help="Force re-login even if already logged in.",
|
| 73 |
+
),
|
| 74 |
+
] = False,
|
| 75 |
+
) -> None:
|
| 76 |
+
"""Login using a token from huggingface.co/settings/tokens."""
|
| 77 |
+
login(token=token, add_to_git_credential=add_to_git_credential, skip_if_logged_in=not force)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@auth_cli.command(
|
| 81 |
+
"logout",
|
| 82 |
+
examples=["hf auth logout", "hf auth logout --token-name my-token"],
|
| 83 |
+
)
|
| 84 |
+
def auth_logout(
|
| 85 |
+
token_name: Annotated[
|
| 86 |
+
str | None,
|
| 87 |
+
typer.Option(help="Name of token to logout"),
|
| 88 |
+
] = None,
|
| 89 |
+
) -> None:
|
| 90 |
+
"""Logout from a specific token."""
|
| 91 |
+
logout(token_name=token_name)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _select_token_name() -> str | None:
|
| 95 |
+
token_names = list(get_stored_tokens().keys())
|
| 96 |
+
|
| 97 |
+
if not token_names:
|
| 98 |
+
logger.error("No stored tokens found. Please login first.")
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
print("Available stored tokens:")
|
| 102 |
+
for i, token_name in enumerate(token_names, 1):
|
| 103 |
+
print(f"{i}. {token_name}")
|
| 104 |
+
while True:
|
| 105 |
+
try:
|
| 106 |
+
choice = input("Enter the number of the token to switch to (or 'q' to quit): ")
|
| 107 |
+
if choice.lower() == "q":
|
| 108 |
+
return None
|
| 109 |
+
index = int(choice) - 1
|
| 110 |
+
if 0 <= index < len(token_names):
|
| 111 |
+
return token_names[index]
|
| 112 |
+
else:
|
| 113 |
+
print("Invalid selection. Please try again.")
|
| 114 |
+
except ValueError:
|
| 115 |
+
print("Invalid input. Please enter a number or 'q' to quit.")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@auth_cli.command(
|
| 119 |
+
"switch",
|
| 120 |
+
examples=["hf auth switch", "hf auth switch --token-name my-token"],
|
| 121 |
+
)
|
| 122 |
+
def auth_switch_cmd(
|
| 123 |
+
token_name: Annotated[
|
| 124 |
+
str | None,
|
| 125 |
+
typer.Option(
|
| 126 |
+
help="Name of the token to switch to",
|
| 127 |
+
),
|
| 128 |
+
] = None,
|
| 129 |
+
add_to_git_credential: Annotated[
|
| 130 |
+
bool,
|
| 131 |
+
typer.Option(
|
| 132 |
+
help="Save to git credential helper. Useful only if you plan to run git commands directly.",
|
| 133 |
+
),
|
| 134 |
+
] = False,
|
| 135 |
+
) -> None:
|
| 136 |
+
"""Switch between access tokens."""
|
| 137 |
+
if token_name is None:
|
| 138 |
+
token_name = _select_token_name()
|
| 139 |
+
if token_name is None:
|
| 140 |
+
print("No token name provided. Aborting.")
|
| 141 |
+
raise typer.Exit()
|
| 142 |
+
auth_switch(token_name, add_to_git_credential=add_to_git_credential)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@auth_cli.command("list | ls", examples=["hf auth list"])
|
| 146 |
+
def auth_list_cmd() -> None:
|
| 147 |
+
"""List all stored access tokens."""
|
| 148 |
+
auth_list()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@auth_cli.command("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 typer.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")
|
| 169 |
+
raise typer.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)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/buckets.py
ADDED
|
@@ -0,0 +1,821 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with buckets via the CLI."""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import sys
|
| 18 |
+
from typing import Annotated
|
| 19 |
+
|
| 20 |
+
import typer
|
| 21 |
+
|
| 22 |
+
from huggingface_hub import logging
|
| 23 |
+
from huggingface_hub._buckets import (
|
| 24 |
+
BUCKET_PREFIX,
|
| 25 |
+
BucketFile,
|
| 26 |
+
FilterMatcher,
|
| 27 |
+
_is_bucket_path,
|
| 28 |
+
_parse_bucket_path,
|
| 29 |
+
_split_bucket_id_and_prefix,
|
| 30 |
+
)
|
| 31 |
+
from huggingface_hub.utils import (
|
| 32 |
+
SoftTemporaryDirectory,
|
| 33 |
+
disable_progress_bars,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
from ._cli_utils import (
|
| 37 |
+
SearchOpt,
|
| 38 |
+
TokenOpt,
|
| 39 |
+
get_hf_api,
|
| 40 |
+
typer_factory,
|
| 41 |
+
)
|
| 42 |
+
from ._file_listing import format_size, print_file_listing
|
| 43 |
+
from ._output import OutputFormatWithAuto, out
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
logger = logging.get_logger(__name__)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
buckets_cli = typer_factory(help="Commands to interact with buckets.")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _is_hf_handle(path: str) -> bool:
|
| 53 |
+
return path.startswith("hf://")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _parse_bucket_argument(argument: str) -> tuple[str, str]:
|
| 57 |
+
"""Parse a bucket argument accepting both 'namespace/name(/prefix)' and 'hf://buckets/namespace/name(/prefix)'.
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
tuple: (bucket_id, prefix) where bucket_id is "namespace/bucket_name" and prefix may be empty string.
|
| 61 |
+
"""
|
| 62 |
+
if argument.startswith(BUCKET_PREFIX):
|
| 63 |
+
return _parse_bucket_path(argument)
|
| 64 |
+
try:
|
| 65 |
+
return _split_bucket_id_and_prefix(argument)
|
| 66 |
+
except ValueError:
|
| 67 |
+
raise ValueError(
|
| 68 |
+
f"Invalid bucket argument: {argument}. Must be in format namespace/bucket_name"
|
| 69 |
+
f" or {BUCKET_PREFIX}namespace/bucket_name"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
@buckets_cli.command(
|
| 74 |
+
name="create",
|
| 75 |
+
examples=[
|
| 76 |
+
"hf buckets create my-bucket",
|
| 77 |
+
"hf buckets create user/my-bucket",
|
| 78 |
+
"hf buckets create hf://buckets/user/my-bucket",
|
| 79 |
+
"hf buckets create user/my-bucket --private",
|
| 80 |
+
"hf buckets create user/my-bucket --exist-ok",
|
| 81 |
+
],
|
| 82 |
+
)
|
| 83 |
+
def create(
|
| 84 |
+
bucket_id: Annotated[
|
| 85 |
+
str,
|
| 86 |
+
typer.Argument(
|
| 87 |
+
help="Bucket ID: bucket_name, namespace/bucket_name, or hf://buckets/namespace/bucket_name",
|
| 88 |
+
),
|
| 89 |
+
],
|
| 90 |
+
private: Annotated[
|
| 91 |
+
bool,
|
| 92 |
+
typer.Option(
|
| 93 |
+
"--private",
|
| 94 |
+
help="Create a private bucket.",
|
| 95 |
+
),
|
| 96 |
+
] = False,
|
| 97 |
+
exist_ok: Annotated[
|
| 98 |
+
bool,
|
| 99 |
+
typer.Option(
|
| 100 |
+
"--exist-ok",
|
| 101 |
+
help="Do not raise an error if the bucket already exists.",
|
| 102 |
+
),
|
| 103 |
+
] = False,
|
| 104 |
+
token: TokenOpt = None,
|
| 105 |
+
) -> None:
|
| 106 |
+
"""Create a new bucket."""
|
| 107 |
+
api = get_hf_api(token=token)
|
| 108 |
+
|
| 109 |
+
if bucket_id.startswith(BUCKET_PREFIX):
|
| 110 |
+
try:
|
| 111 |
+
parsed_id, prefix = _parse_bucket_argument(bucket_id)
|
| 112 |
+
except ValueError as e:
|
| 113 |
+
raise typer.BadParameter(str(e))
|
| 114 |
+
if prefix:
|
| 115 |
+
raise typer.BadParameter(
|
| 116 |
+
f"Cannot specify a prefix for bucket creation: {bucket_id}."
|
| 117 |
+
f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 118 |
+
)
|
| 119 |
+
bucket_id = parsed_id
|
| 120 |
+
|
| 121 |
+
bucket_url = api.create_bucket(
|
| 122 |
+
bucket_id,
|
| 123 |
+
private=private if private else None,
|
| 124 |
+
exist_ok=exist_ok,
|
| 125 |
+
)
|
| 126 |
+
out.result("Bucket created", handle=bucket_url.handle, url=bucket_url.url)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _is_bucket_id(argument: str) -> bool:
|
| 130 |
+
"""Check if argument is a bucket ID (namespace/name) vs just a namespace."""
|
| 131 |
+
if argument.startswith(BUCKET_PREFIX):
|
| 132 |
+
path = argument[len(BUCKET_PREFIX) :]
|
| 133 |
+
else:
|
| 134 |
+
path = argument
|
| 135 |
+
return "/" in path
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@buckets_cli.command(
|
| 139 |
+
name="list | ls",
|
| 140 |
+
examples=[
|
| 141 |
+
"hf buckets list",
|
| 142 |
+
"hf buckets list huggingface",
|
| 143 |
+
'hf buckets list --search "my-prefix"',
|
| 144 |
+
"hf buckets list user/my-bucket",
|
| 145 |
+
"hf buckets list user/my-bucket -R",
|
| 146 |
+
"hf buckets list user/my-bucket -h",
|
| 147 |
+
"hf buckets list user/my-bucket --tree",
|
| 148 |
+
"hf buckets list user/my-bucket --tree -h",
|
| 149 |
+
"hf buckets list hf://buckets/user/my-bucket",
|
| 150 |
+
"hf buckets list user/my-bucket/sub -R",
|
| 151 |
+
],
|
| 152 |
+
)
|
| 153 |
+
def list_cmd(
|
| 154 |
+
argument: Annotated[
|
| 155 |
+
str | None,
|
| 156 |
+
typer.Argument(
|
| 157 |
+
help=(
|
| 158 |
+
"Namespace (user or org) to list buckets, or bucket ID"
|
| 159 |
+
" (namespace/bucket_name(/prefix) or hf://buckets/...) to list files."
|
| 160 |
+
),
|
| 161 |
+
),
|
| 162 |
+
] = None,
|
| 163 |
+
human_readable: Annotated[
|
| 164 |
+
bool,
|
| 165 |
+
typer.Option(
|
| 166 |
+
"--human-readable",
|
| 167 |
+
"-h",
|
| 168 |
+
help="Show sizes in human readable format.",
|
| 169 |
+
),
|
| 170 |
+
] = False,
|
| 171 |
+
as_tree: Annotated[
|
| 172 |
+
bool,
|
| 173 |
+
typer.Option(
|
| 174 |
+
"--tree",
|
| 175 |
+
help="List files in tree format (only for listing files).",
|
| 176 |
+
),
|
| 177 |
+
] = False,
|
| 178 |
+
recursive: Annotated[
|
| 179 |
+
bool,
|
| 180 |
+
typer.Option(
|
| 181 |
+
"--recursive",
|
| 182 |
+
"-R",
|
| 183 |
+
help="List files recursively (only for listing files).",
|
| 184 |
+
),
|
| 185 |
+
] = False,
|
| 186 |
+
search: SearchOpt = None,
|
| 187 |
+
token: TokenOpt = None,
|
| 188 |
+
) -> None:
|
| 189 |
+
"""List buckets or files in a bucket.
|
| 190 |
+
|
| 191 |
+
When called with no argument or a namespace, lists buckets.
|
| 192 |
+
When called with a bucket ID (namespace/bucket_name), lists files in the bucket.
|
| 193 |
+
"""
|
| 194 |
+
# Determine mode: listing buckets or listing files
|
| 195 |
+
is_file_mode = argument is not None and _is_bucket_id(argument)
|
| 196 |
+
|
| 197 |
+
if is_file_mode:
|
| 198 |
+
if search is not None:
|
| 199 |
+
raise typer.BadParameter("Cannot use --search when listing files.")
|
| 200 |
+
_list_files(
|
| 201 |
+
argument=argument, # type: ignore
|
| 202 |
+
human_readable=human_readable,
|
| 203 |
+
as_tree=as_tree,
|
| 204 |
+
recursive=recursive,
|
| 205 |
+
token=token,
|
| 206 |
+
)
|
| 207 |
+
else:
|
| 208 |
+
_list_buckets(
|
| 209 |
+
namespace=argument,
|
| 210 |
+
search=search,
|
| 211 |
+
human_readable=human_readable,
|
| 212 |
+
as_tree=as_tree,
|
| 213 |
+
recursive=recursive,
|
| 214 |
+
token=token,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _list_buckets(
|
| 219 |
+
namespace: str | None,
|
| 220 |
+
search: str | None,
|
| 221 |
+
human_readable: bool,
|
| 222 |
+
as_tree: bool,
|
| 223 |
+
recursive: bool,
|
| 224 |
+
token: str | None,
|
| 225 |
+
) -> None:
|
| 226 |
+
"""List buckets in a namespace."""
|
| 227 |
+
# Validate incompatible flags
|
| 228 |
+
if as_tree:
|
| 229 |
+
raise typer.BadParameter("Cannot use --tree when listing buckets.")
|
| 230 |
+
if recursive:
|
| 231 |
+
raise typer.BadParameter("Cannot use --recursive when listing buckets.")
|
| 232 |
+
|
| 233 |
+
# Handle hf://buckets/namespace format
|
| 234 |
+
if namespace is not None and namespace.startswith(BUCKET_PREFIX):
|
| 235 |
+
namespace = namespace[len(BUCKET_PREFIX) :]
|
| 236 |
+
# Strip trailing slash if any
|
| 237 |
+
namespace = namespace.rstrip("/")
|
| 238 |
+
|
| 239 |
+
api = get_hf_api(token=token)
|
| 240 |
+
items = [
|
| 241 |
+
{
|
| 242 |
+
"id": bucket.id,
|
| 243 |
+
"private": bucket.private,
|
| 244 |
+
"size": format_size(bucket.size, human_readable) if human_readable else bucket.size,
|
| 245 |
+
"total_files": bucket.total_files,
|
| 246 |
+
"created_at": bucket.created_at,
|
| 247 |
+
}
|
| 248 |
+
for bucket in api.list_buckets(namespace=namespace, search=search)
|
| 249 |
+
]
|
| 250 |
+
out.table(items, alignments={"size": "right", "total_files": "right"})
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _list_files(
|
| 254 |
+
argument: str,
|
| 255 |
+
human_readable: bool,
|
| 256 |
+
as_tree: bool,
|
| 257 |
+
recursive: bool,
|
| 258 |
+
token: str | None,
|
| 259 |
+
) -> None:
|
| 260 |
+
"""List files in a bucket."""
|
| 261 |
+
if as_tree and out.mode == OutputFormatWithAuto.json:
|
| 262 |
+
raise typer.BadParameter("Cannot use --tree with --format json.")
|
| 263 |
+
|
| 264 |
+
api = get_hf_api(token=token)
|
| 265 |
+
|
| 266 |
+
try:
|
| 267 |
+
bucket_id, prefix = _parse_bucket_argument(argument)
|
| 268 |
+
except ValueError as e:
|
| 269 |
+
raise typer.BadParameter(str(e))
|
| 270 |
+
|
| 271 |
+
items = list(
|
| 272 |
+
api.list_bucket_tree(
|
| 273 |
+
bucket_id,
|
| 274 |
+
prefix=prefix or None,
|
| 275 |
+
recursive=recursive,
|
| 276 |
+
)
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
print_file_listing(items, human_readable=human_readable, as_tree=as_tree, recursive=recursive)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
@buckets_cli.command(
|
| 283 |
+
name="info",
|
| 284 |
+
examples=[
|
| 285 |
+
"hf buckets info user/my-bucket",
|
| 286 |
+
"hf buckets info hf://buckets/user/my-bucket",
|
| 287 |
+
],
|
| 288 |
+
)
|
| 289 |
+
def info(
|
| 290 |
+
bucket_id: Annotated[
|
| 291 |
+
str,
|
| 292 |
+
typer.Argument(
|
| 293 |
+
help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
|
| 294 |
+
),
|
| 295 |
+
],
|
| 296 |
+
token: TokenOpt = None,
|
| 297 |
+
) -> None:
|
| 298 |
+
"""Get info about a bucket."""
|
| 299 |
+
api = get_hf_api(token=token)
|
| 300 |
+
|
| 301 |
+
try:
|
| 302 |
+
parsed_id, _ = _parse_bucket_argument(bucket_id)
|
| 303 |
+
except ValueError as e:
|
| 304 |
+
raise typer.BadParameter(str(e))
|
| 305 |
+
|
| 306 |
+
bucket = api.bucket_info(parsed_id)
|
| 307 |
+
out.dict(bucket, id_key="id")
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
@buckets_cli.command(
|
| 311 |
+
name="delete",
|
| 312 |
+
examples=[
|
| 313 |
+
"hf buckets delete user/my-bucket",
|
| 314 |
+
"hf buckets delete hf://buckets/user/my-bucket",
|
| 315 |
+
"hf buckets delete user/my-bucket --yes",
|
| 316 |
+
"hf buckets delete user/my-bucket --missing-ok",
|
| 317 |
+
],
|
| 318 |
+
)
|
| 319 |
+
def delete(
|
| 320 |
+
bucket_id: Annotated[
|
| 321 |
+
str,
|
| 322 |
+
typer.Argument(
|
| 323 |
+
help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
|
| 324 |
+
),
|
| 325 |
+
],
|
| 326 |
+
yes: Annotated[
|
| 327 |
+
bool,
|
| 328 |
+
typer.Option(
|
| 329 |
+
"--yes",
|
| 330 |
+
"-y",
|
| 331 |
+
help="Skip confirmation prompt.",
|
| 332 |
+
),
|
| 333 |
+
] = False,
|
| 334 |
+
missing_ok: Annotated[
|
| 335 |
+
bool,
|
| 336 |
+
typer.Option(
|
| 337 |
+
"--missing-ok",
|
| 338 |
+
help="Do not raise an error if the bucket does not exist.",
|
| 339 |
+
),
|
| 340 |
+
] = False,
|
| 341 |
+
token: TokenOpt = None,
|
| 342 |
+
) -> None:
|
| 343 |
+
"""Delete a bucket.
|
| 344 |
+
|
| 345 |
+
This deletes the entire bucket and all its contents. Use `hf buckets rm` to remove individual files.
|
| 346 |
+
"""
|
| 347 |
+
if bucket_id.startswith(BUCKET_PREFIX):
|
| 348 |
+
try:
|
| 349 |
+
parsed_id, prefix = _parse_bucket_argument(bucket_id)
|
| 350 |
+
except ValueError as e:
|
| 351 |
+
raise typer.BadParameter(str(e))
|
| 352 |
+
if prefix:
|
| 353 |
+
raise typer.BadParameter(
|
| 354 |
+
f"Cannot specify a prefix for bucket deletion: {bucket_id}."
|
| 355 |
+
f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 356 |
+
)
|
| 357 |
+
bucket_id = parsed_id
|
| 358 |
+
elif "/" not in bucket_id:
|
| 359 |
+
raise typer.BadParameter(
|
| 360 |
+
f"Invalid bucket ID: {bucket_id}."
|
| 361 |
+
f" Must be in format namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
out.confirm(f"Are you sure you want to delete bucket '{bucket_id}'?", yes=yes)
|
| 365 |
+
|
| 366 |
+
api = get_hf_api(token=token)
|
| 367 |
+
api.delete_bucket(bucket_id, missing_ok=missing_ok)
|
| 368 |
+
out.result("Bucket deleted", bucket_id=bucket_id)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
@buckets_cli.command(
|
| 372 |
+
name="remove | rm",
|
| 373 |
+
examples=[
|
| 374 |
+
"hf buckets remove user/my-bucket/file.txt",
|
| 375 |
+
"hf buckets rm hf://buckets/user/my-bucket/file.txt",
|
| 376 |
+
"hf buckets rm user/my-bucket/logs/ --recursive",
|
| 377 |
+
'hf buckets rm user/my-bucket --recursive --include "*.tmp"',
|
| 378 |
+
"hf buckets rm user/my-bucket/data/ --recursive --dry-run",
|
| 379 |
+
],
|
| 380 |
+
)
|
| 381 |
+
def remove(
|
| 382 |
+
argument: Annotated[
|
| 383 |
+
str,
|
| 384 |
+
typer.Argument(
|
| 385 |
+
help=(
|
| 386 |
+
"Bucket path: namespace/bucket_name/path or hf://buckets/namespace/bucket_name/path."
|
| 387 |
+
" With --recursive, namespace/bucket_name is also accepted to target all files."
|
| 388 |
+
),
|
| 389 |
+
),
|
| 390 |
+
],
|
| 391 |
+
recursive: Annotated[
|
| 392 |
+
bool,
|
| 393 |
+
typer.Option(
|
| 394 |
+
"--recursive",
|
| 395 |
+
"-R",
|
| 396 |
+
help="Remove files recursively under the given prefix.",
|
| 397 |
+
),
|
| 398 |
+
] = False,
|
| 399 |
+
yes: Annotated[
|
| 400 |
+
bool,
|
| 401 |
+
typer.Option(
|
| 402 |
+
"--yes",
|
| 403 |
+
"-y",
|
| 404 |
+
help="Skip confirmation prompt.",
|
| 405 |
+
),
|
| 406 |
+
] = False,
|
| 407 |
+
dry_run: Annotated[
|
| 408 |
+
bool,
|
| 409 |
+
typer.Option(
|
| 410 |
+
"--dry-run",
|
| 411 |
+
help="Preview what would be deleted without actually deleting.",
|
| 412 |
+
),
|
| 413 |
+
] = False,
|
| 414 |
+
include: Annotated[
|
| 415 |
+
list[str] | None,
|
| 416 |
+
typer.Option(
|
| 417 |
+
help="Include only files matching pattern (can specify multiple). Requires --recursive.",
|
| 418 |
+
),
|
| 419 |
+
] = None,
|
| 420 |
+
exclude: Annotated[
|
| 421 |
+
list[str] | None,
|
| 422 |
+
typer.Option(
|
| 423 |
+
help="Exclude files matching pattern (can specify multiple). Requires --recursive.",
|
| 424 |
+
),
|
| 425 |
+
] = None,
|
| 426 |
+
token: TokenOpt = None,
|
| 427 |
+
) -> None:
|
| 428 |
+
"""Remove files from a bucket.
|
| 429 |
+
|
| 430 |
+
To delete an entire bucket, use `hf buckets delete` instead.
|
| 431 |
+
"""
|
| 432 |
+
try:
|
| 433 |
+
bucket_id, prefix = _parse_bucket_argument(argument)
|
| 434 |
+
except ValueError as e:
|
| 435 |
+
raise typer.BadParameter(str(e))
|
| 436 |
+
|
| 437 |
+
if prefix == "" and not recursive:
|
| 438 |
+
raise typer.BadParameter(
|
| 439 |
+
f"No file path specified. To remove files, provide a path"
|
| 440 |
+
f" (e.g. '{bucket_id}/FILE') or use --recursive to remove all files."
|
| 441 |
+
f" To delete the entire bucket, use `hf buckets delete {bucket_id}`."
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
if (include or exclude) and not recursive:
|
| 445 |
+
raise typer.BadParameter("--include and --exclude require --recursive.")
|
| 446 |
+
|
| 447 |
+
api = get_hf_api(token=token)
|
| 448 |
+
|
| 449 |
+
if recursive:
|
| 450 |
+
status = out.status("Listing files from remote")
|
| 451 |
+
|
| 452 |
+
all_files: list[BucketFile] = []
|
| 453 |
+
for item in api.list_bucket_tree(
|
| 454 |
+
bucket_id,
|
| 455 |
+
prefix=prefix.rstrip("/") or None,
|
| 456 |
+
recursive=True,
|
| 457 |
+
):
|
| 458 |
+
if isinstance(item, BucketFile):
|
| 459 |
+
all_files.append(item)
|
| 460 |
+
status.update(f"Listing files from remote ({len(all_files)} files)")
|
| 461 |
+
status.done(f"Listing files from remote ({len(all_files)} files)")
|
| 462 |
+
|
| 463 |
+
if include or exclude:
|
| 464 |
+
matcher = FilterMatcher(include_patterns=include, exclude_patterns=exclude)
|
| 465 |
+
matched_files = [f for f in all_files if matcher.matches(f.path)]
|
| 466 |
+
else:
|
| 467 |
+
matched_files = all_files
|
| 468 |
+
|
| 469 |
+
file_paths = [f.path for f in matched_files]
|
| 470 |
+
total_size = sum(f.size for f in matched_files)
|
| 471 |
+
size_str = format_size(total_size, human_readable=True)
|
| 472 |
+
|
| 473 |
+
if not file_paths:
|
| 474 |
+
out.text("No files to remove.")
|
| 475 |
+
return
|
| 476 |
+
|
| 477 |
+
count_label = f"{len(file_paths)} file(s) totaling {size_str}"
|
| 478 |
+
|
| 479 |
+
if not yes and not dry_run:
|
| 480 |
+
out.text("\n".join(f" {path}" for path in file_paths))
|
| 481 |
+
out.confirm(f"Remove {count_label} from '{bucket_id}'?", yes=False)
|
| 482 |
+
|
| 483 |
+
if dry_run:
|
| 484 |
+
out.text("\n".join(f"delete: {BUCKET_PREFIX}{bucket_id}/{path}" for path in file_paths))
|
| 485 |
+
out.text(f"(dry run) {count_label} would be removed.")
|
| 486 |
+
return
|
| 487 |
+
|
| 488 |
+
api.batch_bucket_files(bucket_id, delete=file_paths)
|
| 489 |
+
out.result(
|
| 490 |
+
f"Removed {count_label} from '{bucket_id}'",
|
| 491 |
+
bucket_id=bucket_id,
|
| 492 |
+
files_deleted=len(file_paths),
|
| 493 |
+
size=size_str,
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
else:
|
| 497 |
+
file_path = prefix.rstrip("/")
|
| 498 |
+
if not file_path:
|
| 499 |
+
raise typer.BadParameter("File path cannot be empty.")
|
| 500 |
+
|
| 501 |
+
if dry_run:
|
| 502 |
+
out.text(f"delete: {BUCKET_PREFIX}{bucket_id}/{file_path}")
|
| 503 |
+
out.text("(dry run) 1 file would be removed.")
|
| 504 |
+
return
|
| 505 |
+
|
| 506 |
+
out.confirm(f"Remove '{file_path}' from '{bucket_id}'?", yes=yes)
|
| 507 |
+
|
| 508 |
+
api.batch_bucket_files(bucket_id, delete=[file_path])
|
| 509 |
+
out.result("File removed", path=file_path, bucket_id=bucket_id)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
@buckets_cli.command(
|
| 513 |
+
name="move",
|
| 514 |
+
examples=[
|
| 515 |
+
"hf buckets move user/old-bucket user/new-bucket",
|
| 516 |
+
"hf buckets move user/my-bucket my-org/my-bucket",
|
| 517 |
+
"hf buckets move hf://buckets/user/old-bucket hf://buckets/user/new-bucket",
|
| 518 |
+
],
|
| 519 |
+
)
|
| 520 |
+
def move(
|
| 521 |
+
from_id: Annotated[
|
| 522 |
+
str,
|
| 523 |
+
typer.Argument(
|
| 524 |
+
help="Source bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
|
| 525 |
+
),
|
| 526 |
+
],
|
| 527 |
+
to_id: Annotated[
|
| 528 |
+
str,
|
| 529 |
+
typer.Argument(
|
| 530 |
+
help="Destination bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
|
| 531 |
+
),
|
| 532 |
+
],
|
| 533 |
+
token: TokenOpt = None,
|
| 534 |
+
) -> None:
|
| 535 |
+
"""Move (rename) a bucket to a new name or namespace."""
|
| 536 |
+
# Parse from_id
|
| 537 |
+
parsed_from_id, from_prefix = _parse_bucket_argument(from_id)
|
| 538 |
+
if from_prefix:
|
| 539 |
+
raise typer.BadParameter(
|
| 540 |
+
f"Cannot specify a prefix for bucket move: {from_id}."
|
| 541 |
+
f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
# Parse to_id
|
| 545 |
+
parsed_to_id, to_prefix = _parse_bucket_argument(to_id)
|
| 546 |
+
if to_prefix:
|
| 547 |
+
raise typer.BadParameter(
|
| 548 |
+
f"Cannot specify a prefix for bucket move: {to_id}."
|
| 549 |
+
f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
api = get_hf_api(token=token)
|
| 553 |
+
api.move_bucket(from_id=parsed_from_id, to_id=parsed_to_id)
|
| 554 |
+
out.result("Bucket moved", from_id=parsed_from_id, to_id=parsed_to_id)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
# =============================================================================
|
| 558 |
+
# Sync command
|
| 559 |
+
# =============================================================================
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
@buckets_cli.command(
|
| 563 |
+
name="sync",
|
| 564 |
+
examples=[
|
| 565 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket",
|
| 566 |
+
"hf buckets sync hf://buckets/user/my-bucket ./data",
|
| 567 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket --delete",
|
| 568 |
+
'hf buckets sync hf://buckets/user/my-bucket ./data --include "*.safetensors" --exclude "*.tmp"',
|
| 569 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket --plan sync-plan.jsonl",
|
| 570 |
+
"hf buckets sync --apply sync-plan.jsonl",
|
| 571 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket --dry-run",
|
| 572 |
+
"hf buckets sync ./data hf://buckets/user/my-bucket --dry-run | jq .",
|
| 573 |
+
],
|
| 574 |
+
)
|
| 575 |
+
def sync(
|
| 576 |
+
source: Annotated[
|
| 577 |
+
str | None,
|
| 578 |
+
typer.Argument(
|
| 579 |
+
help="Source path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
|
| 580 |
+
),
|
| 581 |
+
] = None,
|
| 582 |
+
dest: Annotated[
|
| 583 |
+
str | None,
|
| 584 |
+
typer.Argument(
|
| 585 |
+
help="Destination path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
|
| 586 |
+
),
|
| 587 |
+
] = None,
|
| 588 |
+
delete: Annotated[
|
| 589 |
+
bool,
|
| 590 |
+
typer.Option(
|
| 591 |
+
help="Delete destination files not present in source.",
|
| 592 |
+
),
|
| 593 |
+
] = False,
|
| 594 |
+
ignore_times: Annotated[
|
| 595 |
+
bool,
|
| 596 |
+
typer.Option(
|
| 597 |
+
"--ignore-times",
|
| 598 |
+
help="Skip files only based on size, ignoring modification times.",
|
| 599 |
+
),
|
| 600 |
+
] = False,
|
| 601 |
+
ignore_sizes: Annotated[
|
| 602 |
+
bool,
|
| 603 |
+
typer.Option(
|
| 604 |
+
"--ignore-sizes",
|
| 605 |
+
help="Skip files only based on modification times, ignoring sizes.",
|
| 606 |
+
),
|
| 607 |
+
] = False,
|
| 608 |
+
plan: Annotated[
|
| 609 |
+
str | None,
|
| 610 |
+
typer.Option(
|
| 611 |
+
help="Save sync plan to JSONL file for review instead of executing.",
|
| 612 |
+
),
|
| 613 |
+
] = None,
|
| 614 |
+
apply: Annotated[
|
| 615 |
+
str | None,
|
| 616 |
+
typer.Option(
|
| 617 |
+
help="Apply a previously saved plan file.",
|
| 618 |
+
),
|
| 619 |
+
] = None,
|
| 620 |
+
dry_run: Annotated[
|
| 621 |
+
bool,
|
| 622 |
+
typer.Option(
|
| 623 |
+
"--dry-run",
|
| 624 |
+
help="Print sync plan to stdout as JSONL without executing.",
|
| 625 |
+
),
|
| 626 |
+
] = False,
|
| 627 |
+
include: Annotated[
|
| 628 |
+
list[str] | None,
|
| 629 |
+
typer.Option(
|
| 630 |
+
help="Include files matching pattern (can specify multiple).",
|
| 631 |
+
),
|
| 632 |
+
] = None,
|
| 633 |
+
exclude: Annotated[
|
| 634 |
+
list[str] | None,
|
| 635 |
+
typer.Option(
|
| 636 |
+
help="Exclude files matching pattern (can specify multiple).",
|
| 637 |
+
),
|
| 638 |
+
] = None,
|
| 639 |
+
filter_from: Annotated[
|
| 640 |
+
str | None,
|
| 641 |
+
typer.Option(
|
| 642 |
+
help="Read include/exclude patterns from file.",
|
| 643 |
+
),
|
| 644 |
+
] = None,
|
| 645 |
+
existing: Annotated[
|
| 646 |
+
bool,
|
| 647 |
+
typer.Option(
|
| 648 |
+
"--existing",
|
| 649 |
+
help="Skip creating new files on receiver (only update existing files).",
|
| 650 |
+
),
|
| 651 |
+
] = False,
|
| 652 |
+
ignore_existing: Annotated[
|
| 653 |
+
bool,
|
| 654 |
+
typer.Option(
|
| 655 |
+
"--ignore-existing",
|
| 656 |
+
help="Skip updating files that exist on receiver (only create new files).",
|
| 657 |
+
),
|
| 658 |
+
] = False,
|
| 659 |
+
verbose: Annotated[
|
| 660 |
+
bool,
|
| 661 |
+
typer.Option(
|
| 662 |
+
"--verbose",
|
| 663 |
+
"-v",
|
| 664 |
+
help="Show detailed logging with reasoning.",
|
| 665 |
+
),
|
| 666 |
+
] = False,
|
| 667 |
+
token: TokenOpt = None,
|
| 668 |
+
) -> None:
|
| 669 |
+
"""Sync files between local directory and a bucket."""
|
| 670 |
+
api = get_hf_api(token=token)
|
| 671 |
+
api.sync_bucket(
|
| 672 |
+
source=source,
|
| 673 |
+
dest=dest,
|
| 674 |
+
delete=delete,
|
| 675 |
+
ignore_times=ignore_times,
|
| 676 |
+
ignore_sizes=ignore_sizes,
|
| 677 |
+
existing=existing,
|
| 678 |
+
ignore_existing=ignore_existing,
|
| 679 |
+
include=include,
|
| 680 |
+
exclude=exclude,
|
| 681 |
+
filter_from=filter_from,
|
| 682 |
+
plan=plan,
|
| 683 |
+
apply=apply,
|
| 684 |
+
dry_run=dry_run,
|
| 685 |
+
verbose=verbose,
|
| 686 |
+
quiet=out.is_quiet(),
|
| 687 |
+
)
|
| 688 |
+
if plan and not out.is_quiet():
|
| 689 |
+
out.hint(f"Run `hf buckets sync --apply {plan}` to execute this plan.")
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
# =============================================================================
|
| 693 |
+
# Cp command
|
| 694 |
+
# =============================================================================
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
@buckets_cli.command(
|
| 698 |
+
name="cp",
|
| 699 |
+
examples=[
|
| 700 |
+
"hf buckets cp hf://buckets/user/my-bucket/config.json",
|
| 701 |
+
"hf buckets cp hf://buckets/user/my-bucket/config.json ./data/",
|
| 702 |
+
"hf buckets cp hf://buckets/user/my-bucket/config.json my-config.json",
|
| 703 |
+
"hf buckets cp hf://buckets/user/my-bucket/config.json -",
|
| 704 |
+
"hf buckets cp my-config.json hf://buckets/user/my-bucket",
|
| 705 |
+
"hf buckets cp my-config.json hf://buckets/user/my-bucket/logs/",
|
| 706 |
+
"hf buckets cp my-config.json hf://buckets/user/my-bucket/remote-config.json",
|
| 707 |
+
"hf buckets cp - hf://buckets/user/my-bucket/config.json",
|
| 708 |
+
"hf buckets cp hf://buckets/user/my-bucket/logs hf://buckets/user/archive-bucket/ # nests logs/ dir",
|
| 709 |
+
"hf buckets cp hf://buckets/user/my-bucket/logs/ hf://buckets/user/archive-bucket/ # copies contents only",
|
| 710 |
+
"hf buckets cp hf://datasets/user/my-dataset/processed/ hf://buckets/user/my-bucket/dataset/processed/",
|
| 711 |
+
],
|
| 712 |
+
)
|
| 713 |
+
def cp(
|
| 714 |
+
src: Annotated[
|
| 715 |
+
str, typer.Argument(help="Source: local file, any hf:// handle (model, dataset, bucket), or - for stdin")
|
| 716 |
+
],
|
| 717 |
+
dst: Annotated[
|
| 718 |
+
str | None, typer.Argument(help="Destination: local path, bucket hf://... handle, or - for stdout")
|
| 719 |
+
] = None,
|
| 720 |
+
token: TokenOpt = None,
|
| 721 |
+
) -> None:
|
| 722 |
+
"""Copy files to or from buckets."""
|
| 723 |
+
api = get_hf_api(token=token)
|
| 724 |
+
|
| 725 |
+
src_is_hf = _is_hf_handle(src)
|
| 726 |
+
dst_is_hf = dst is not None and _is_hf_handle(dst)
|
| 727 |
+
src_is_bucket = _is_bucket_path(src)
|
| 728 |
+
dst_is_bucket = dst is not None and _is_bucket_path(dst)
|
| 729 |
+
src_is_stdin = src == "-"
|
| 730 |
+
dst_is_stdout = dst == "-"
|
| 731 |
+
|
| 732 |
+
# Remote to remote copy
|
| 733 |
+
if src_is_hf and dst_is_hf:
|
| 734 |
+
try:
|
| 735 |
+
api.copy_files(src, dst) # type: ignore
|
| 736 |
+
except ValueError as e:
|
| 737 |
+
raise typer.BadParameter(str(e))
|
| 738 |
+
|
| 739 |
+
out.result("Copied", src=src, dst=dst)
|
| 740 |
+
return
|
| 741 |
+
|
| 742 |
+
# Local to remote copy
|
| 743 |
+
# --- Validation ---
|
| 744 |
+
if not src_is_bucket and not dst_is_bucket and not src_is_stdin:
|
| 745 |
+
if dst is None:
|
| 746 |
+
raise typer.BadParameter("Missing destination. Provide a bucket path as DST.")
|
| 747 |
+
raise typer.BadParameter("One of SRC or DST must be a bucket path (hf://buckets/...).")
|
| 748 |
+
|
| 749 |
+
if src_is_stdin and not dst_is_bucket:
|
| 750 |
+
raise typer.BadParameter("Stdin upload requires a bucket destination.")
|
| 751 |
+
|
| 752 |
+
if src_is_stdin and dst_is_bucket:
|
| 753 |
+
_, prefix = _parse_bucket_path(dst) # type: ignore
|
| 754 |
+
if prefix == "" or prefix.endswith("/"):
|
| 755 |
+
raise typer.BadParameter("Stdin upload requires a full destination path including filename.")
|
| 756 |
+
|
| 757 |
+
if dst_is_stdout and not src_is_bucket:
|
| 758 |
+
raise typer.BadParameter("Cannot pipe to stdout for uploads.")
|
| 759 |
+
|
| 760 |
+
if not src_is_bucket and not src_is_stdin and os.path.isdir(src):
|
| 761 |
+
raise typer.BadParameter("Source must be a file, not a directory. Use `hf buckets sync` for directories.")
|
| 762 |
+
|
| 763 |
+
# --- Determine direction and execute ---
|
| 764 |
+
if src_is_bucket:
|
| 765 |
+
# Download: remote -> local or stdout
|
| 766 |
+
bucket_id, prefix = _parse_bucket_path(src)
|
| 767 |
+
if prefix == "" or prefix.endswith("/"):
|
| 768 |
+
raise typer.BadParameter("Source path must include a file name, not just a bucket or directory path.")
|
| 769 |
+
filename = prefix.rsplit("/", 1)[-1]
|
| 770 |
+
|
| 771 |
+
if dst_is_stdout:
|
| 772 |
+
# Download to stdout: always suppress progress bars to avoid polluting output
|
| 773 |
+
# Only re-enable if they weren't already disabled by the caller
|
| 774 |
+
with disable_progress_bars():
|
| 775 |
+
with SoftTemporaryDirectory() as tmp_dir:
|
| 776 |
+
tmp_path = os.path.join(tmp_dir, filename)
|
| 777 |
+
api.download_bucket_files(bucket_id, [(prefix, tmp_path)])
|
| 778 |
+
with open(tmp_path, "rb") as f:
|
| 779 |
+
while chunk := f.read(32_000_000): # 32MB chunks
|
| 780 |
+
sys.stdout.buffer.write(chunk)
|
| 781 |
+
else:
|
| 782 |
+
# Download to file
|
| 783 |
+
if dst is None:
|
| 784 |
+
local_path = filename
|
| 785 |
+
elif os.path.isdir(dst) or dst.endswith(os.sep) or dst.endswith("/"):
|
| 786 |
+
local_path = os.path.join(dst, filename)
|
| 787 |
+
else:
|
| 788 |
+
local_path = dst
|
| 789 |
+
|
| 790 |
+
# Ensure parent directory exists
|
| 791 |
+
parent_dir = os.path.dirname(local_path)
|
| 792 |
+
if parent_dir:
|
| 793 |
+
os.makedirs(parent_dir, exist_ok=True)
|
| 794 |
+
|
| 795 |
+
api.download_bucket_files(bucket_id, [(prefix, local_path)])
|
| 796 |
+
out.result("Downloaded", src=src, dst=local_path)
|
| 797 |
+
|
| 798 |
+
elif src_is_stdin:
|
| 799 |
+
# Upload from stdin
|
| 800 |
+
bucket_id, remote_path = _parse_bucket_path(dst) # type: ignore
|
| 801 |
+
data = sys.stdin.buffer.read()
|
| 802 |
+
|
| 803 |
+
api.batch_bucket_files(bucket_id, add=[(data, remote_path)])
|
| 804 |
+
out.result("Uploaded", src="stdin", dst=dst)
|
| 805 |
+
|
| 806 |
+
else:
|
| 807 |
+
# Upload from file
|
| 808 |
+
if not os.path.isfile(src):
|
| 809 |
+
raise typer.BadParameter(f"Source file not found: {src}")
|
| 810 |
+
|
| 811 |
+
bucket_id, prefix = _parse_bucket_path(dst) # type: ignore
|
| 812 |
+
|
| 813 |
+
if prefix == "":
|
| 814 |
+
remote_path = os.path.basename(src)
|
| 815 |
+
elif prefix.endswith("/"):
|
| 816 |
+
remote_path = prefix + os.path.basename(src)
|
| 817 |
+
else:
|
| 818 |
+
remote_path = prefix
|
| 819 |
+
|
| 820 |
+
api.batch_bucket_files(bucket_id, add=[(src, remote_path)])
|
| 821 |
+
out.result("Uploaded", src=src, dst=f"{BUCKET_PREFIX}{bucket_id}/{remote_path}")
|
micromamba_root/envs/p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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present, the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains the 'hf cache' command group with cache management subcommands."""
|
| 15 |
+
|
| 16 |
+
import re
|
| 17 |
+
import time
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from collections.abc import Callable, Mapping
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from enum import Enum
|
| 22 |
+
from typing import Annotated, Any
|
| 23 |
+
|
| 24 |
+
import typer
|
| 25 |
+
|
| 26 |
+
from huggingface_hub.errors import CLIError
|
| 27 |
+
|
| 28 |
+
from ..utils import ANSI, CachedRepoInfo, CachedRevisionInfo, CacheNotFound, HFCacheInfo, _format_size, scan_cache_dir
|
| 29 |
+
from ..utils._parsing import parse_duration, parse_size
|
| 30 |
+
from ._cli_utils import RepoIdArg, RepoTypeOpt, RevisionOpt, TokenOpt, get_hf_api, typer_factory
|
| 31 |
+
from ._output import out
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
cache_cli = typer_factory(help="Manage local cache directory.")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
#### Cache helper utilities
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass(frozen=True)
|
| 41 |
+
class _DeletionResolution:
|
| 42 |
+
revisions: frozenset[str]
|
| 43 |
+
selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]]
|
| 44 |
+
missing: tuple[str, ...]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
_FILTER_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)\s*(?P<op>==|!=|>=|<=|>|<|=)\s*(?P<value>.+)$")
|
| 48 |
+
_ALLOWED_OPERATORS = {"=", "!=", ">", "<", ">=", "<="}
|
| 49 |
+
_FILTER_KEYS = {"accessed", "modified", "refs", "size", "type"}
|
| 50 |
+
_SORT_KEYS = {"accessed", "modified", "name", "size"}
|
| 51 |
+
_SORT_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)(?::(?P<order>asc|desc))?$")
|
| 52 |
+
_SORT_DEFAULT_ORDER = {
|
| 53 |
+
# Default ordering: accessed/modified/size are descending (newest/biggest first), name is ascending
|
| 54 |
+
"accessed": "desc",
|
| 55 |
+
"modified": "desc",
|
| 56 |
+
"size": "desc",
|
| 57 |
+
"name": "asc",
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Dynamically generate SortOptions enum from _SORT_KEYS
|
| 62 |
+
_sort_options_dict = {}
|
| 63 |
+
for key in sorted(_SORT_KEYS):
|
| 64 |
+
_sort_options_dict[key] = key
|
| 65 |
+
_sort_options_dict[f"{key}_asc"] = f"{key}:asc"
|
| 66 |
+
_sort_options_dict[f"{key}_desc"] = f"{key}:desc"
|
| 67 |
+
|
| 68 |
+
SortOptions = Enum("SortOptions", _sort_options_dict, type=str, module=__name__) # type: ignore
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@dataclass(frozen=True)
|
| 72 |
+
class CacheDeletionCounts:
|
| 73 |
+
"""Simple counters summarizing cache deletions for CLI messaging."""
|
| 74 |
+
|
| 75 |
+
repo_count: int
|
| 76 |
+
partial_revision_count: int
|
| 77 |
+
total_revision_count: int
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
CacheEntry = tuple[CachedRepoInfo, CachedRevisionInfo | None]
|
| 81 |
+
RepoRefsMap = dict[CachedRepoInfo, frozenset[str]]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def summarize_deletions(
|
| 85 |
+
selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]],
|
| 86 |
+
) -> CacheDeletionCounts:
|
| 87 |
+
"""Summarize deletions across repositories."""
|
| 88 |
+
repo_count = 0
|
| 89 |
+
total_revisions = 0
|
| 90 |
+
revisions_in_full_repos = 0
|
| 91 |
+
|
| 92 |
+
for repo, revisions in selected_by_repo.items():
|
| 93 |
+
total_revisions += len(revisions)
|
| 94 |
+
if len(revisions) == len(repo.revisions):
|
| 95 |
+
repo_count += 1
|
| 96 |
+
revisions_in_full_repos += len(revisions)
|
| 97 |
+
|
| 98 |
+
partial_revision_count = total_revisions - revisions_in_full_repos
|
| 99 |
+
return CacheDeletionCounts(repo_count, partial_revision_count, total_revisions)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def print_cache_selected_revisions(selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]]) -> None:
|
| 103 |
+
"""Pretty-print selected cache revisions during confirmation prompts."""
|
| 104 |
+
for repo in sorted(selected_by_repo.keys(), key=lambda repo: (repo.repo_type, repo.repo_id.lower())):
|
| 105 |
+
repo_key = f"{repo.repo_type}/{repo.repo_id}"
|
| 106 |
+
revisions = sorted(selected_by_repo[repo], key=lambda rev: rev.commit_hash)
|
| 107 |
+
if len(revisions) == len(repo.revisions):
|
| 108 |
+
out.text(f" - {repo_key} (entire repo)")
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
out.text(f" - {repo_key}:")
|
| 112 |
+
for revision in revisions:
|
| 113 |
+
refs = " ".join(sorted(revision.refs)) or "(detached)"
|
| 114 |
+
out.text(f" {revision.commit_hash} [{refs}] {revision.size_on_disk_str}")
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def build_cache_index(
|
| 118 |
+
hf_cache_info: HFCacheInfo,
|
| 119 |
+
) -> tuple[
|
| 120 |
+
dict[str, CachedRepoInfo],
|
| 121 |
+
dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]],
|
| 122 |
+
]:
|
| 123 |
+
"""Create lookup tables so CLI commands can resolve repo ids and revisions quickly."""
|
| 124 |
+
repo_lookup: dict[str, CachedRepoInfo] = {}
|
| 125 |
+
revision_lookup: dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]] = {}
|
| 126 |
+
for repo in hf_cache_info.repos:
|
| 127 |
+
repo_key = repo.cache_id.lower()
|
| 128 |
+
repo_lookup[repo_key] = repo
|
| 129 |
+
for revision in repo.revisions:
|
| 130 |
+
revision_lookup[revision.commit_hash.lower()] = (repo, revision)
|
| 131 |
+
return repo_lookup, revision_lookup
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def collect_cache_entries(
|
| 135 |
+
hf_cache_info: HFCacheInfo, *, include_revisions: bool
|
| 136 |
+
) -> tuple[list[CacheEntry], RepoRefsMap]:
|
| 137 |
+
"""Flatten cache metadata into rows consumed by `hf cache ls`."""
|
| 138 |
+
entries: list[CacheEntry] = []
|
| 139 |
+
repo_refs_map: RepoRefsMap = {}
|
| 140 |
+
sorted_repos = sorted(hf_cache_info.repos, key=lambda repo: (repo.repo_type, repo.repo_id.lower()))
|
| 141 |
+
for repo in sorted_repos:
|
| 142 |
+
repo_refs_map[repo] = frozenset({ref for revision in repo.revisions for ref in revision.refs})
|
| 143 |
+
if include_revisions:
|
| 144 |
+
for revision in sorted(repo.revisions, key=lambda rev: rev.commit_hash):
|
| 145 |
+
entries.append((repo, revision))
|
| 146 |
+
else:
|
| 147 |
+
entries.append((repo, None))
|
| 148 |
+
if include_revisions:
|
| 149 |
+
entries.sort(
|
| 150 |
+
key=lambda entry: (
|
| 151 |
+
entry[0].cache_id,
|
| 152 |
+
entry[1].commit_hash if entry[1] is not None else "",
|
| 153 |
+
)
|
| 154 |
+
)
|
| 155 |
+
else:
|
| 156 |
+
entries.sort(key=lambda entry: entry[0].cache_id)
|
| 157 |
+
return entries, repo_refs_map
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def compile_cache_filter(
|
| 161 |
+
expr: str, repo_refs_map: RepoRefsMap
|
| 162 |
+
) -> Callable[[CachedRepoInfo, CachedRevisionInfo | None, float], bool]:
|
| 163 |
+
"""Convert a `hf cache ls` filter expression into the yes/no test we apply to each cache entry before displaying it."""
|
| 164 |
+
match = _FILTER_PATTERN.match(expr.strip())
|
| 165 |
+
if not match:
|
| 166 |
+
raise ValueError(f"Invalid filter expression: '{expr}'.")
|
| 167 |
+
|
| 168 |
+
key = match.group("key").lower()
|
| 169 |
+
op = match.group("op")
|
| 170 |
+
value_raw = match.group("value").strip()
|
| 171 |
+
|
| 172 |
+
if op not in _ALLOWED_OPERATORS:
|
| 173 |
+
raise ValueError(f"Unsupported operator '{op}' in filter '{expr}'. Must be one of {list(_ALLOWED_OPERATORS)}.")
|
| 174 |
+
|
| 175 |
+
if key not in _FILTER_KEYS:
|
| 176 |
+
raise ValueError(f"Unsupported filter key '{key}' in '{expr}'. Must be one of {list(_FILTER_KEYS)}.")
|
| 177 |
+
# at this point we know that key is in `_FILTER_KEYS`
|
| 178 |
+
if key == "size":
|
| 179 |
+
size_threshold = parse_size(value_raw)
|
| 180 |
+
return lambda repo, revision, _: _compare_numeric(
|
| 181 |
+
revision.size_on_disk if revision is not None else repo.size_on_disk,
|
| 182 |
+
op,
|
| 183 |
+
size_threshold,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
if key in {"modified", "accessed"}:
|
| 187 |
+
seconds = parse_duration(value_raw.strip())
|
| 188 |
+
|
| 189 |
+
def _time_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, now: float) -> bool:
|
| 190 |
+
timestamp = (
|
| 191 |
+
repo.last_accessed
|
| 192 |
+
if key == "accessed"
|
| 193 |
+
else revision.last_modified
|
| 194 |
+
if revision is not None
|
| 195 |
+
else repo.last_modified
|
| 196 |
+
)
|
| 197 |
+
if timestamp is None:
|
| 198 |
+
return False
|
| 199 |
+
return _compare_numeric(now - timestamp, op, seconds)
|
| 200 |
+
|
| 201 |
+
return _time_filter
|
| 202 |
+
|
| 203 |
+
if key == "type":
|
| 204 |
+
expected = value_raw.lower()
|
| 205 |
+
|
| 206 |
+
if op != "=":
|
| 207 |
+
raise ValueError(f"Only '=' is supported for 'type' filters. Got '{op}'.")
|
| 208 |
+
|
| 209 |
+
def _type_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
|
| 210 |
+
return repo.repo_type.lower() == expected
|
| 211 |
+
|
| 212 |
+
return _type_filter
|
| 213 |
+
|
| 214 |
+
else: # key == "refs"
|
| 215 |
+
if op != "=":
|
| 216 |
+
raise ValueError(f"Only '=' is supported for 'refs' filters. Got {op}.")
|
| 217 |
+
|
| 218 |
+
def _refs_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
|
| 219 |
+
refs = revision.refs if revision is not None else repo_refs_map.get(repo, frozenset())
|
| 220 |
+
return value_raw.lower() in [ref.lower() for ref in refs]
|
| 221 |
+
|
| 222 |
+
return _refs_filter
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _compare_numeric(left: float | None, op: str, right: float) -> bool:
|
| 226 |
+
"""Evaluate numeric comparisons for filters."""
|
| 227 |
+
if left is None:
|
| 228 |
+
return False
|
| 229 |
+
|
| 230 |
+
comparisons = {
|
| 231 |
+
"=": left == right,
|
| 232 |
+
"!=": left != right,
|
| 233 |
+
">": left > right,
|
| 234 |
+
"<": left < right,
|
| 235 |
+
">=": left >= right,
|
| 236 |
+
"<=": left <= right,
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
if op not in comparisons:
|
| 240 |
+
raise ValueError(f"Unsupported numeric comparison operator: {op}")
|
| 241 |
+
|
| 242 |
+
return comparisons[op]
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def compile_cache_sort(sort_expr: str) -> tuple[Callable[[CacheEntry], tuple[Any, ...]], bool]:
|
| 246 |
+
"""Convert a `hf cache ls` sort expression into a key function for sorting entries.
|
| 247 |
+
|
| 248 |
+
Returns:
|
| 249 |
+
A tuple of (key_function, reverse_flag) where reverse_flag indicates whether
|
| 250 |
+
to sort in descending order (True) or ascending order (False).
|
| 251 |
+
"""
|
| 252 |
+
match = _SORT_PATTERN.match(sort_expr.strip().lower())
|
| 253 |
+
if not match:
|
| 254 |
+
raise ValueError(f"Invalid sort expression: '{sort_expr}'. Expected format: 'key' or 'key:asc' or 'key:desc'.")
|
| 255 |
+
|
| 256 |
+
key = match.group("key").lower()
|
| 257 |
+
explicit_order = match.group("order")
|
| 258 |
+
|
| 259 |
+
if key not in _SORT_KEYS:
|
| 260 |
+
raise ValueError(f"Unsupported sort key '{key}' in '{sort_expr}'. Must be one of {list(_SORT_KEYS)}.")
|
| 261 |
+
|
| 262 |
+
# Use explicit order if provided, otherwise use default for the key
|
| 263 |
+
order = explicit_order if explicit_order else _SORT_DEFAULT_ORDER[key]
|
| 264 |
+
reverse = order == "desc"
|
| 265 |
+
|
| 266 |
+
def _sort_key(entry: CacheEntry) -> tuple[Any, ...]:
|
| 267 |
+
repo, revision = entry
|
| 268 |
+
|
| 269 |
+
if key == "name":
|
| 270 |
+
# Sort by cache_id (repo type/id)
|
| 271 |
+
value: Any = repo.cache_id.lower()
|
| 272 |
+
return (value,)
|
| 273 |
+
|
| 274 |
+
if key == "size":
|
| 275 |
+
# Use revision size if available, otherwise repo size
|
| 276 |
+
value = revision.size_on_disk if revision is not None else repo.size_on_disk
|
| 277 |
+
return (value,)
|
| 278 |
+
|
| 279 |
+
if key == "accessed":
|
| 280 |
+
# For revisions, accessed is not available per-revision, use repo's last_accessed
|
| 281 |
+
# For repos, use repo's last_accessed
|
| 282 |
+
value = repo.last_accessed if repo.last_accessed is not None else 0.0
|
| 283 |
+
return (value,)
|
| 284 |
+
|
| 285 |
+
if key == "modified":
|
| 286 |
+
# Use revision's last_modified if available, otherwise repo's last_modified
|
| 287 |
+
if revision is not None:
|
| 288 |
+
value = revision.last_modified if revision.last_modified is not None else 0.0
|
| 289 |
+
else:
|
| 290 |
+
value = repo.last_modified if repo.last_modified is not None else 0.0
|
| 291 |
+
return (value,)
|
| 292 |
+
|
| 293 |
+
# Should never reach here due to validation above
|
| 294 |
+
raise ValueError(f"Unsupported sort key: {key}")
|
| 295 |
+
|
| 296 |
+
return _sort_key, reverse
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def _resolve_deletion_targets(hf_cache_info: HFCacheInfo, targets: list[str]) -> _DeletionResolution:
|
| 300 |
+
"""Resolve the deletion targets into a deletion resolution."""
|
| 301 |
+
repo_lookup, revision_lookup = build_cache_index(hf_cache_info)
|
| 302 |
+
|
| 303 |
+
selected: dict[CachedRepoInfo, set[CachedRevisionInfo]] = defaultdict(set)
|
| 304 |
+
revisions: set[str] = set()
|
| 305 |
+
missing: list[str] = []
|
| 306 |
+
|
| 307 |
+
for raw_target in targets:
|
| 308 |
+
target = raw_target.strip()
|
| 309 |
+
if not target:
|
| 310 |
+
continue
|
| 311 |
+
lowered = target.lower()
|
| 312 |
+
|
| 313 |
+
if re.fullmatch(r"[0-9a-fA-F]{40}", lowered):
|
| 314 |
+
match = revision_lookup.get(lowered)
|
| 315 |
+
if match is None:
|
| 316 |
+
missing.append(raw_target)
|
| 317 |
+
continue
|
| 318 |
+
repo, revision = match
|
| 319 |
+
selected[repo].add(revision)
|
| 320 |
+
revisions.add(revision.commit_hash)
|
| 321 |
+
continue
|
| 322 |
+
|
| 323 |
+
matched_repo = repo_lookup.get(lowered)
|
| 324 |
+
if matched_repo is None:
|
| 325 |
+
missing.append(raw_target)
|
| 326 |
+
continue
|
| 327 |
+
|
| 328 |
+
for revision in matched_repo.revisions:
|
| 329 |
+
selected[matched_repo].add(revision)
|
| 330 |
+
revisions.add(revision.commit_hash)
|
| 331 |
+
|
| 332 |
+
frozen_selected = {repo: frozenset(revs) for repo, revs in selected.items()}
|
| 333 |
+
return _DeletionResolution(
|
| 334 |
+
revisions=frozenset(revisions),
|
| 335 |
+
selected=frozen_selected,
|
| 336 |
+
missing=tuple(missing),
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
#### Cache CLI commands
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
@cache_cli.command(
|
| 344 |
+
"list | ls",
|
| 345 |
+
examples=[
|
| 346 |
+
"hf cache ls",
|
| 347 |
+
"hf cache ls --revisions",
|
| 348 |
+
'hf cache ls --filter "size>1GB" --limit 20',
|
| 349 |
+
"hf cache ls --format json",
|
| 350 |
+
],
|
| 351 |
+
)
|
| 352 |
+
def ls(
|
| 353 |
+
cache_dir: Annotated[
|
| 354 |
+
str | None,
|
| 355 |
+
typer.Option(
|
| 356 |
+
help="Cache directory to scan (defaults to Hugging Face cache).",
|
| 357 |
+
),
|
| 358 |
+
] = None,
|
| 359 |
+
revisions: Annotated[
|
| 360 |
+
bool,
|
| 361 |
+
typer.Option(
|
| 362 |
+
help="Include revisions in the output instead of aggregated repositories.",
|
| 363 |
+
),
|
| 364 |
+
] = False,
|
| 365 |
+
filter: Annotated[
|
| 366 |
+
list[str] | None,
|
| 367 |
+
typer.Option(
|
| 368 |
+
"-f",
|
| 369 |
+
"--filter",
|
| 370 |
+
help="Filter entries (e.g. 'size>1GB', 'type=model', 'accessed>7d'). Can be used multiple times.",
|
| 371 |
+
),
|
| 372 |
+
] = None,
|
| 373 |
+
sort: Annotated[
|
| 374 |
+
SortOptions | None,
|
| 375 |
+
typer.Option(
|
| 376 |
+
help="Sort entries by key. Supported keys: 'accessed', 'modified', 'name', 'size'. "
|
| 377 |
+
"Append ':asc' or ':desc' to explicitly set the order (e.g., 'modified:asc'). "
|
| 378 |
+
"Defaults: 'accessed', 'modified', 'size' default to 'desc' (newest/biggest first); "
|
| 379 |
+
"'name' defaults to 'asc' (alphabetical).",
|
| 380 |
+
),
|
| 381 |
+
] = None,
|
| 382 |
+
limit: Annotated[
|
| 383 |
+
int | None,
|
| 384 |
+
typer.Option(
|
| 385 |
+
help="Limit the number of results returned. Returns only the top N entries after sorting.",
|
| 386 |
+
),
|
| 387 |
+
] = None,
|
| 388 |
+
) -> None:
|
| 389 |
+
"""List cached repositories or revisions."""
|
| 390 |
+
try:
|
| 391 |
+
hf_cache_info = scan_cache_dir(cache_dir)
|
| 392 |
+
except CacheNotFound as exc:
|
| 393 |
+
raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
|
| 394 |
+
|
| 395 |
+
filters = filter or []
|
| 396 |
+
|
| 397 |
+
entries, repo_refs_map = collect_cache_entries(hf_cache_info, include_revisions=revisions)
|
| 398 |
+
try:
|
| 399 |
+
filter_fns = [compile_cache_filter(expr, repo_refs_map) for expr in filters]
|
| 400 |
+
except ValueError as exc:
|
| 401 |
+
raise typer.BadParameter(str(exc)) from exc
|
| 402 |
+
|
| 403 |
+
now = time.time()
|
| 404 |
+
for fn in filter_fns:
|
| 405 |
+
entries = [entry for entry in entries if fn(entry[0], entry[1], now)]
|
| 406 |
+
|
| 407 |
+
# Apply sorting if requested
|
| 408 |
+
if sort:
|
| 409 |
+
try:
|
| 410 |
+
sort_key_fn, reverse = compile_cache_sort(sort.value)
|
| 411 |
+
entries.sort(key=sort_key_fn, reverse=reverse)
|
| 412 |
+
except ValueError as exc:
|
| 413 |
+
raise typer.BadParameter(str(exc)) from exc
|
| 414 |
+
|
| 415 |
+
# Apply limit if requested
|
| 416 |
+
if limit is not None:
|
| 417 |
+
if limit < 0:
|
| 418 |
+
raise typer.BadParameter(f"Limit must be a positive integer, got {limit}.")
|
| 419 |
+
entries = entries[:limit]
|
| 420 |
+
|
| 421 |
+
if revisions:
|
| 422 |
+
items = [
|
| 423 |
+
{
|
| 424 |
+
"id": repo.cache_id,
|
| 425 |
+
"repo_id": repo.repo_id,
|
| 426 |
+
"repo_type": repo.repo_type,
|
| 427 |
+
"revision": revision.commit_hash,
|
| 428 |
+
"snapshot_path": str(revision.snapshot_path),
|
| 429 |
+
"size": revision.size_on_disk_str,
|
| 430 |
+
"last_modified": revision.last_modified_str,
|
| 431 |
+
"refs": sorted(revision.refs),
|
| 432 |
+
}
|
| 433 |
+
for repo, revision in entries
|
| 434 |
+
if revision is not None
|
| 435 |
+
]
|
| 436 |
+
out.table(
|
| 437 |
+
items,
|
| 438 |
+
headers=["id", "revision", "size", "last_modified", "refs"],
|
| 439 |
+
id_key="revision",
|
| 440 |
+
alignments={"size": "right"},
|
| 441 |
+
)
|
| 442 |
+
else:
|
| 443 |
+
items = [
|
| 444 |
+
{
|
| 445 |
+
"id": repo.cache_id,
|
| 446 |
+
"repo_id": repo.repo_id,
|
| 447 |
+
"repo_type": repo.repo_type,
|
| 448 |
+
"size": repo.size_on_disk_str,
|
| 449 |
+
"last_accessed": repo.last_accessed_str or "",
|
| 450 |
+
"last_modified": repo.last_modified_str,
|
| 451 |
+
"refs": sorted(repo_refs_map.get(repo, frozenset())),
|
| 452 |
+
}
|
| 453 |
+
for repo, _ in entries
|
| 454 |
+
]
|
| 455 |
+
out.table(
|
| 456 |
+
items,
|
| 457 |
+
headers=["id", "size", "last_accessed", "last_modified", "refs"],
|
| 458 |
+
id_key="id",
|
| 459 |
+
alignments={"size": "right"},
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
if entries:
|
| 463 |
+
unique_repos = {repo for repo, _ in entries}
|
| 464 |
+
repo_count = len(unique_repos)
|
| 465 |
+
if revisions:
|
| 466 |
+
revision_count = sum(1 for _, rev in entries if rev is not None)
|
| 467 |
+
total_size = sum(rev.size_on_disk for _, rev in entries if rev is not None)
|
| 468 |
+
else:
|
| 469 |
+
revision_count = sum(len(repo.revisions) for repo in unique_repos)
|
| 470 |
+
total_size = sum(repo.size_on_disk for repo in unique_repos)
|
| 471 |
+
out.text(
|
| 472 |
+
ANSI.bold(
|
| 473 |
+
f"\nFound {repo_count} repo(s) for a total of {revision_count} revision(s)"
|
| 474 |
+
f" and {_format_size(total_size)} on disk."
|
| 475 |
+
)
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
@cache_cli.command(
|
| 480 |
+
examples=[
|
| 481 |
+
"hf cache rm model/gpt2",
|
| 482 |
+
"hf cache rm <revision_hash>",
|
| 483 |
+
"hf cache rm model/gpt2 --dry-run",
|
| 484 |
+
"hf cache rm model/gpt2 --yes",
|
| 485 |
+
],
|
| 486 |
+
)
|
| 487 |
+
def rm(
|
| 488 |
+
targets: Annotated[
|
| 489 |
+
list[str],
|
| 490 |
+
typer.Argument(
|
| 491 |
+
help="One or more repo IDs (e.g. model/bert-base-uncased) or revision hashes to delete.",
|
| 492 |
+
),
|
| 493 |
+
],
|
| 494 |
+
cache_dir: Annotated[
|
| 495 |
+
str | None,
|
| 496 |
+
typer.Option(
|
| 497 |
+
help="Cache directory to scan (defaults to Hugging Face cache).",
|
| 498 |
+
),
|
| 499 |
+
] = None,
|
| 500 |
+
yes: Annotated[
|
| 501 |
+
bool,
|
| 502 |
+
typer.Option(
|
| 503 |
+
"-y",
|
| 504 |
+
"--yes",
|
| 505 |
+
help="Skip confirmation prompt.",
|
| 506 |
+
),
|
| 507 |
+
] = False,
|
| 508 |
+
dry_run: Annotated[
|
| 509 |
+
bool,
|
| 510 |
+
typer.Option(
|
| 511 |
+
help="Preview deletions without removing anything.",
|
| 512 |
+
),
|
| 513 |
+
] = False,
|
| 514 |
+
) -> None:
|
| 515 |
+
"""Remove cached repositories or revisions."""
|
| 516 |
+
try:
|
| 517 |
+
hf_cache_info = scan_cache_dir(cache_dir)
|
| 518 |
+
except CacheNotFound as exc:
|
| 519 |
+
raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
|
| 520 |
+
|
| 521 |
+
resolution = _resolve_deletion_targets(hf_cache_info, targets)
|
| 522 |
+
|
| 523 |
+
if resolution.missing:
|
| 524 |
+
details = "\n".join(f" - {entry}" for entry in resolution.missing)
|
| 525 |
+
out.warning(f"Could not find in cache:\n{details}")
|
| 526 |
+
|
| 527 |
+
if len(resolution.revisions) == 0:
|
| 528 |
+
out.text("Nothing to delete.")
|
| 529 |
+
raise typer.Exit(code=0)
|
| 530 |
+
|
| 531 |
+
strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions))
|
| 532 |
+
counts = summarize_deletions(resolution.selected)
|
| 533 |
+
|
| 534 |
+
summary_parts: list[str] = []
|
| 535 |
+
if counts.repo_count:
|
| 536 |
+
summary_parts.append(f"{counts.repo_count} repo(s)")
|
| 537 |
+
if counts.partial_revision_count:
|
| 538 |
+
summary_parts.append(f"{counts.partial_revision_count} revision(s)")
|
| 539 |
+
if not summary_parts:
|
| 540 |
+
summary_parts.append(f"{counts.total_revision_count} revision(s)")
|
| 541 |
+
|
| 542 |
+
summary_text = " and ".join(summary_parts)
|
| 543 |
+
out.text(f"About to delete {summary_text} totalling {strategy.expected_freed_size_str}.")
|
| 544 |
+
print_cache_selected_revisions(resolution.selected)
|
| 545 |
+
|
| 546 |
+
if dry_run:
|
| 547 |
+
out.result(
|
| 548 |
+
"Dry run: no files were deleted.",
|
| 549 |
+
dry_run=True,
|
| 550 |
+
repos=counts.repo_count,
|
| 551 |
+
revisions=counts.total_revision_count,
|
| 552 |
+
size=strategy.expected_freed_size_str,
|
| 553 |
+
)
|
| 554 |
+
return
|
| 555 |
+
|
| 556 |
+
out.confirm("Proceed with deletion?", yes=yes)
|
| 557 |
+
|
| 558 |
+
strategy.execute()
|
| 559 |
+
counts = summarize_deletions(resolution.selected)
|
| 560 |
+
out.result(
|
| 561 |
+
f"Deleted {counts.repo_count} repo(s) and {counts.total_revision_count} revision(s);"
|
| 562 |
+
f" freed {strategy.expected_freed_size_str}.",
|
| 563 |
+
repos_deleted=counts.repo_count,
|
| 564 |
+
revisions_deleted=counts.total_revision_count,
|
| 565 |
+
freed=strategy.expected_freed_size_str,
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
@cache_cli.command(examples=["hf cache prune", "hf cache prune --dry-run"])
|
| 570 |
+
def prune(
|
| 571 |
+
cache_dir: Annotated[
|
| 572 |
+
str | None,
|
| 573 |
+
typer.Option(
|
| 574 |
+
help="Cache directory to scan (defaults to Hugging Face cache).",
|
| 575 |
+
),
|
| 576 |
+
] = None,
|
| 577 |
+
yes: Annotated[
|
| 578 |
+
bool,
|
| 579 |
+
typer.Option(
|
| 580 |
+
"-y",
|
| 581 |
+
"--yes",
|
| 582 |
+
help="Skip confirmation prompt.",
|
| 583 |
+
),
|
| 584 |
+
] = False,
|
| 585 |
+
dry_run: Annotated[
|
| 586 |
+
bool,
|
| 587 |
+
typer.Option(
|
| 588 |
+
help="Preview deletions without removing anything.",
|
| 589 |
+
),
|
| 590 |
+
] = False,
|
| 591 |
+
) -> None:
|
| 592 |
+
"""Remove detached revisions from the cache."""
|
| 593 |
+
try:
|
| 594 |
+
hf_cache_info = scan_cache_dir(cache_dir)
|
| 595 |
+
except CacheNotFound as exc:
|
| 596 |
+
raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
|
| 597 |
+
|
| 598 |
+
selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]] = {}
|
| 599 |
+
revisions: set[str] = set()
|
| 600 |
+
for repo in hf_cache_info.repos:
|
| 601 |
+
detached = frozenset(revision for revision in repo.revisions if len(revision.refs) == 0)
|
| 602 |
+
if not detached:
|
| 603 |
+
continue
|
| 604 |
+
selected[repo] = detached
|
| 605 |
+
revisions.update(revision.commit_hash for revision in detached)
|
| 606 |
+
|
| 607 |
+
if len(revisions) == 0:
|
| 608 |
+
out.text("No unreferenced revisions found. Nothing to prune.")
|
| 609 |
+
return
|
| 610 |
+
|
| 611 |
+
resolution = _DeletionResolution(
|
| 612 |
+
revisions=frozenset(revisions),
|
| 613 |
+
selected=selected,
|
| 614 |
+
missing=(),
|
| 615 |
+
)
|
| 616 |
+
strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions))
|
| 617 |
+
counts = summarize_deletions(selected)
|
| 618 |
+
|
| 619 |
+
out.text(
|
| 620 |
+
f"About to delete {counts.total_revision_count} unreferenced revision(s) ({strategy.expected_freed_size_str} total)."
|
| 621 |
+
)
|
| 622 |
+
print_cache_selected_revisions(selected)
|
| 623 |
+
|
| 624 |
+
if dry_run:
|
| 625 |
+
out.result(
|
| 626 |
+
"Dry run: no files were deleted.",
|
| 627 |
+
dry_run=True,
|
| 628 |
+
revisions=counts.total_revision_count,
|
| 629 |
+
size=strategy.expected_freed_size_str,
|
| 630 |
+
)
|
| 631 |
+
return
|
| 632 |
+
|
| 633 |
+
out.confirm("Proceed?", yes=yes)
|
| 634 |
+
|
| 635 |
+
strategy.execute()
|
| 636 |
+
out.result(
|
| 637 |
+
f"Deleted {counts.total_revision_count} unreferenced revision(s); freed {strategy.expected_freed_size_str}.",
|
| 638 |
+
revisions_deleted=counts.total_revision_count,
|
| 639 |
+
freed=strategy.expected_freed_size_str,
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
@cache_cli.command(
|
| 644 |
+
examples=[
|
| 645 |
+
"hf cache verify gpt2",
|
| 646 |
+
"hf cache verify gpt2 --revision refs/pr/1",
|
| 647 |
+
"hf cache verify my-dataset --repo-type dataset",
|
| 648 |
+
],
|
| 649 |
+
)
|
| 650 |
+
def verify(
|
| 651 |
+
repo_id: RepoIdArg,
|
| 652 |
+
repo_type: RepoTypeOpt = RepoTypeOpt.model,
|
| 653 |
+
revision: RevisionOpt = None,
|
| 654 |
+
cache_dir: Annotated[
|
| 655 |
+
str | None,
|
| 656 |
+
typer.Option(
|
| 657 |
+
help="Cache directory to use when verifying files from cache (defaults to Hugging Face cache).",
|
| 658 |
+
),
|
| 659 |
+
] = None,
|
| 660 |
+
local_dir: Annotated[
|
| 661 |
+
str | None,
|
| 662 |
+
typer.Option(
|
| 663 |
+
help="If set, verify files under this directory instead of the cache.",
|
| 664 |
+
),
|
| 665 |
+
] = None,
|
| 666 |
+
fail_on_missing_files: Annotated[
|
| 667 |
+
bool,
|
| 668 |
+
typer.Option(
|
| 669 |
+
"--fail-on-missing-files",
|
| 670 |
+
help="Fail if some files exist on the remote but are missing locally.",
|
| 671 |
+
),
|
| 672 |
+
] = False,
|
| 673 |
+
fail_on_extra_files: Annotated[
|
| 674 |
+
bool,
|
| 675 |
+
typer.Option(
|
| 676 |
+
"--fail-on-extra-files",
|
| 677 |
+
help="Fail if some files exist locally but are not present on the remote revision.",
|
| 678 |
+
),
|
| 679 |
+
] = False,
|
| 680 |
+
token: TokenOpt = None,
|
| 681 |
+
) -> None:
|
| 682 |
+
"""Verify checksums for a single repo revision from cache or a local directory.
|
| 683 |
+
|
| 684 |
+
Examples:
|
| 685 |
+
- Verify main revision in cache: `hf cache verify gpt2`
|
| 686 |
+
- Verify specific revision: `hf cache verify gpt2 --revision refs/pr/1`
|
| 687 |
+
- Verify dataset: `hf cache verify karpathy/fineweb-edu-100b-shuffle --repo-type dataset`
|
| 688 |
+
- Verify local dir: `hf cache verify deepseek-ai/DeepSeek-OCR --local-dir /path/to/repo`
|
| 689 |
+
"""
|
| 690 |
+
|
| 691 |
+
if local_dir is not None and cache_dir is not None:
|
| 692 |
+
out.error("Cannot pass both --local-dir and --cache-dir. Use one or the other.")
|
| 693 |
+
raise typer.Exit(code=2)
|
| 694 |
+
|
| 695 |
+
api = get_hf_api(token=token)
|
| 696 |
+
|
| 697 |
+
result = api.verify_repo_checksums(
|
| 698 |
+
repo_id=repo_id,
|
| 699 |
+
repo_type=repo_type.value if hasattr(repo_type, "value") else str(repo_type),
|
| 700 |
+
revision=revision,
|
| 701 |
+
local_dir=local_dir,
|
| 702 |
+
cache_dir=cache_dir,
|
| 703 |
+
token=token,
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
exit_code = 0
|
| 707 |
+
|
| 708 |
+
if result.mismatches:
|
| 709 |
+
details = "\n".join(
|
| 710 |
+
f" - {m['path']}: expected {m['expected']} ({m['algorithm']}), got {m['actual']}"
|
| 711 |
+
for m in result.mismatches
|
| 712 |
+
)
|
| 713 |
+
out.text(f"❌ Checksum verification failed for the following file(s):\n{details}")
|
| 714 |
+
exit_code = 1
|
| 715 |
+
|
| 716 |
+
if result.missing_paths:
|
| 717 |
+
if fail_on_missing_files:
|
| 718 |
+
details = "\n".join(f" - {p}" for p in result.missing_paths)
|
| 719 |
+
out.text(f"❌ Missing files (present remotely, absent locally):\n{details}")
|
| 720 |
+
exit_code = 1
|
| 721 |
+
else:
|
| 722 |
+
out.warning(
|
| 723 |
+
f"{len(result.missing_paths)} remote file(s) are missing locally. "
|
| 724 |
+
"Use --fail-on-missing-files for details."
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
if result.extra_paths:
|
| 728 |
+
if fail_on_extra_files:
|
| 729 |
+
details = "\n".join(f" - {p}" for p in result.extra_paths)
|
| 730 |
+
out.text(f"❌ Extra files (present locally, absent remotely):\n{details}")
|
| 731 |
+
exit_code = 1
|
| 732 |
+
else:
|
| 733 |
+
out.warning(
|
| 734 |
+
f"{len(result.extra_paths)} local file(s) do not exist on the remote repo. "
|
| 735 |
+
"Use --fail-on-extra-files for details."
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
verified_location = result.verified_path
|
| 739 |
+
|
| 740 |
+
if exit_code != 0:
|
| 741 |
+
out.error(
|
| 742 |
+
f"Verification failed for '{repo_id}' ({repo_type.value}) in {verified_location}.\n Revision: {result.revision}"
|
| 743 |
+
)
|
| 744 |
+
raise typer.Exit(code=exit_code)
|
| 745 |
+
|
| 746 |
+
out.result(
|
| 747 |
+
f"Verified {result.checked_count} file(s) for {repo_type.value} '{repo_id}'. All checksums match.",
|
| 748 |
+
repo_id=repo_id,
|
| 749 |
+
repo_type=repo_type.value,
|
| 750 |
+
checked=result.checked_count,
|
| 751 |
+
path=str(verified_location),
|
| 752 |
+
)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/collections.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with collections on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# list collections on the Hub
|
| 18 |
+
hf collections ls
|
| 19 |
+
|
| 20 |
+
# list collections for a specific user
|
| 21 |
+
hf collections ls --owner username
|
| 22 |
+
|
| 23 |
+
# get info about a collection
|
| 24 |
+
hf collections info username/collection-slug
|
| 25 |
+
|
| 26 |
+
# create a new collection
|
| 27 |
+
hf collections create "My Collection" --description "A collection of models"
|
| 28 |
+
|
| 29 |
+
# add an item to a collection
|
| 30 |
+
hf collections add-item username/collection-slug username/model-name model
|
| 31 |
+
|
| 32 |
+
# delete a collection
|
| 33 |
+
hf collections delete username/collection-slug
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
import enum
|
| 37 |
+
from typing import Annotated, get_args
|
| 38 |
+
|
| 39 |
+
import typer
|
| 40 |
+
|
| 41 |
+
from huggingface_hub.hf_api import CollectionItemType_T, CollectionSort_T
|
| 42 |
+
|
| 43 |
+
from ._cli_utils import LimitOpt, TokenOpt, api_object_to_dict, get_hf_api, typer_factory
|
| 44 |
+
from ._output import out
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# Build enums dynamically from Literal types to avoid duplication
|
| 48 |
+
_COLLECTION_ITEM_TYPES = get_args(CollectionItemType_T)
|
| 49 |
+
CollectionItemType = enum.Enum("CollectionItemType", {t: t for t in _COLLECTION_ITEM_TYPES}, type=str) # type: ignore[misc]
|
| 50 |
+
|
| 51 |
+
_COLLECTION_SORT_OPTIONS = get_args(CollectionSort_T)
|
| 52 |
+
CollectionSort = enum.Enum("CollectionSort", {s: s for s in _COLLECTION_SORT_OPTIONS}, type=str) # type: ignore[misc]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
collections_cli = typer_factory(help="Interact with collections on the Hub.")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@collections_cli.command(
|
| 59 |
+
"list | ls",
|
| 60 |
+
examples=[
|
| 61 |
+
"hf collections ls",
|
| 62 |
+
"hf collections ls --owner nvidia",
|
| 63 |
+
"hf collections ls --item models/teknium/OpenHermes-2.5-Mistral-7B --limit 10",
|
| 64 |
+
],
|
| 65 |
+
)
|
| 66 |
+
def collections_ls(
|
| 67 |
+
owner: Annotated[
|
| 68 |
+
str | None,
|
| 69 |
+
typer.Option(help="Filter by owner username or organization."),
|
| 70 |
+
] = None,
|
| 71 |
+
item: Annotated[
|
| 72 |
+
str | None,
|
| 73 |
+
typer.Option(
|
| 74 |
+
help='Filter collections containing a specific item (e.g., "models/gpt2", "datasets/squad", "papers/2311.12983").'
|
| 75 |
+
),
|
| 76 |
+
] = None,
|
| 77 |
+
sort: Annotated[
|
| 78 |
+
CollectionSort | None,
|
| 79 |
+
typer.Option(help="Sort results by last modified, trending, or upvotes."),
|
| 80 |
+
] = None,
|
| 81 |
+
limit: LimitOpt = 10,
|
| 82 |
+
token: TokenOpt = None,
|
| 83 |
+
) -> None:
|
| 84 |
+
"""List collections on the Hub."""
|
| 85 |
+
api = get_hf_api(token=token)
|
| 86 |
+
sort_key = sort.value if sort else None
|
| 87 |
+
results = [
|
| 88 |
+
api_object_to_dict(collection)
|
| 89 |
+
for collection in api.list_collections(
|
| 90 |
+
owner=owner,
|
| 91 |
+
item=item,
|
| 92 |
+
sort=sort_key, # type: ignore[arg-type]
|
| 93 |
+
limit=limit,
|
| 94 |
+
)
|
| 95 |
+
]
|
| 96 |
+
out.table(results)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@collections_cli.command(
|
| 100 |
+
"info",
|
| 101 |
+
examples=[
|
| 102 |
+
"hf collections info username/my-collection-slug",
|
| 103 |
+
],
|
| 104 |
+
)
|
| 105 |
+
def collections_info(
|
| 106 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 107 |
+
token: TokenOpt = None,
|
| 108 |
+
) -> None:
|
| 109 |
+
"""Get info about a collection on the Hub."""
|
| 110 |
+
api = get_hf_api(token=token)
|
| 111 |
+
collection = api.get_collection(collection_slug)
|
| 112 |
+
out.dict(collection)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@collections_cli.command(
|
| 116 |
+
"create",
|
| 117 |
+
examples=[
|
| 118 |
+
'hf collections create "My Models"',
|
| 119 |
+
'hf collections create "My Models" --description "A collection of my favorite models" --private',
|
| 120 |
+
'hf collections create "Org Collection" --namespace my-org',
|
| 121 |
+
],
|
| 122 |
+
)
|
| 123 |
+
def collections_create(
|
| 124 |
+
title: Annotated[str, typer.Argument(help="The title of the collection.")],
|
| 125 |
+
namespace: Annotated[
|
| 126 |
+
str | None,
|
| 127 |
+
typer.Option(help="The namespace (username or organization). Defaults to the authenticated user."),
|
| 128 |
+
] = None,
|
| 129 |
+
description: Annotated[
|
| 130 |
+
str | None,
|
| 131 |
+
typer.Option(help="A description for the collection."),
|
| 132 |
+
] = None,
|
| 133 |
+
private: Annotated[
|
| 134 |
+
bool,
|
| 135 |
+
typer.Option(help="Create a private collection."),
|
| 136 |
+
] = False,
|
| 137 |
+
exists_ok: Annotated[
|
| 138 |
+
bool,
|
| 139 |
+
typer.Option(help="Do not raise an error if the collection already exists."),
|
| 140 |
+
] = False,
|
| 141 |
+
token: TokenOpt = None,
|
| 142 |
+
) -> None:
|
| 143 |
+
"""Create a new collection on the Hub."""
|
| 144 |
+
api = get_hf_api(token=token)
|
| 145 |
+
collection = api.create_collection(
|
| 146 |
+
title=title,
|
| 147 |
+
namespace=namespace,
|
| 148 |
+
description=description,
|
| 149 |
+
private=private,
|
| 150 |
+
exists_ok=exists_ok,
|
| 151 |
+
)
|
| 152 |
+
out.result("Collection created", slug=collection.slug, url=collection.url)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@collections_cli.command(
|
| 156 |
+
"update",
|
| 157 |
+
examples=[
|
| 158 |
+
'hf collections update username/my-collection --title "New Title"',
|
| 159 |
+
'hf collections update username/my-collection --description "Updated description"',
|
| 160 |
+
"hf collections update username/my-collection --private --theme green",
|
| 161 |
+
],
|
| 162 |
+
)
|
| 163 |
+
def collections_update(
|
| 164 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 165 |
+
title: Annotated[
|
| 166 |
+
str | None,
|
| 167 |
+
typer.Option(help="The new title for the collection."),
|
| 168 |
+
] = None,
|
| 169 |
+
description: Annotated[
|
| 170 |
+
str | None,
|
| 171 |
+
typer.Option(help="The new description for the collection."),
|
| 172 |
+
] = None,
|
| 173 |
+
position: Annotated[
|
| 174 |
+
int | None,
|
| 175 |
+
typer.Option(help="The new position of the collection in the owner's list."),
|
| 176 |
+
] = None,
|
| 177 |
+
private: Annotated[
|
| 178 |
+
bool | None,
|
| 179 |
+
typer.Option(help="Whether the collection should be private."),
|
| 180 |
+
] = None,
|
| 181 |
+
theme: Annotated[
|
| 182 |
+
str | None,
|
| 183 |
+
typer.Option(help="The theme color for the collection (e.g., 'green', 'blue')."),
|
| 184 |
+
] = None,
|
| 185 |
+
token: TokenOpt = None,
|
| 186 |
+
) -> None:
|
| 187 |
+
"""Update a collection's metadata on the Hub."""
|
| 188 |
+
api = get_hf_api(token=token)
|
| 189 |
+
collection = api.update_collection_metadata(
|
| 190 |
+
collection_slug=collection_slug,
|
| 191 |
+
title=title,
|
| 192 |
+
description=description,
|
| 193 |
+
position=position,
|
| 194 |
+
private=private,
|
| 195 |
+
theme=theme,
|
| 196 |
+
)
|
| 197 |
+
out.result("Collection updated", slug=collection.slug, url=collection.url)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
@collections_cli.command(
|
| 201 |
+
"delete",
|
| 202 |
+
examples=[
|
| 203 |
+
"hf collections delete username/my-collection",
|
| 204 |
+
"hf collections delete username/my-collection --missing-ok",
|
| 205 |
+
],
|
| 206 |
+
)
|
| 207 |
+
def collections_delete(
|
| 208 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 209 |
+
missing_ok: Annotated[
|
| 210 |
+
bool,
|
| 211 |
+
typer.Option(help="Do not raise an error if the collection doesn't exist."),
|
| 212 |
+
] = False,
|
| 213 |
+
token: TokenOpt = None,
|
| 214 |
+
) -> None:
|
| 215 |
+
"""Delete a collection from the Hub."""
|
| 216 |
+
api = get_hf_api(token=token)
|
| 217 |
+
api.delete_collection(collection_slug, missing_ok=missing_ok)
|
| 218 |
+
out.result("Collection deleted", slug=collection_slug)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@collections_cli.command(
|
| 222 |
+
"add-item",
|
| 223 |
+
examples=[
|
| 224 |
+
"hf collections add-item username/my-collection moonshotai/kimi-k2 model",
|
| 225 |
+
'hf collections add-item username/my-collection Qwen/DeepPlanning dataset --note "Useful dataset"',
|
| 226 |
+
"hf collections add-item username/my-collection Tongyi-MAI/Z-Image space",
|
| 227 |
+
],
|
| 228 |
+
)
|
| 229 |
+
def collections_add_item(
|
| 230 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 231 |
+
item_id: Annotated[
|
| 232 |
+
str, typer.Argument(help="The ID of the item to add (repo_id for repos, paper ID for papers).")
|
| 233 |
+
],
|
| 234 |
+
item_type: Annotated[
|
| 235 |
+
CollectionItemType,
|
| 236 |
+
typer.Argument(help="The type of item (model, dataset, space, paper, collection, or bucket)."),
|
| 237 |
+
],
|
| 238 |
+
note: Annotated[
|
| 239 |
+
str | None,
|
| 240 |
+
typer.Option(help="A note to attach to the item (max 500 characters)."),
|
| 241 |
+
] = None,
|
| 242 |
+
exists_ok: Annotated[
|
| 243 |
+
bool,
|
| 244 |
+
typer.Option(help="Do not raise an error if the item is already in the collection."),
|
| 245 |
+
] = False,
|
| 246 |
+
token: TokenOpt = None,
|
| 247 |
+
) -> None:
|
| 248 |
+
"""Add an item to a collection."""
|
| 249 |
+
api = get_hf_api(token=token)
|
| 250 |
+
collection = api.add_collection_item(
|
| 251 |
+
collection_slug=collection_slug,
|
| 252 |
+
item_id=item_id,
|
| 253 |
+
item_type=item_type.value, # type: ignore[arg-type]
|
| 254 |
+
note=note,
|
| 255 |
+
exists_ok=exists_ok,
|
| 256 |
+
)
|
| 257 |
+
out.result("Item added to collection", slug=collection_slug, url=collection.url)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
@collections_cli.command(
|
| 261 |
+
"update-item",
|
| 262 |
+
examples=[
|
| 263 |
+
'hf collections update-item username/my-collection ITEM_OBJECT_ID --note "Updated note"',
|
| 264 |
+
"hf collections update-item username/my-collection ITEM_OBJECT_ID --position 0",
|
| 265 |
+
],
|
| 266 |
+
)
|
| 267 |
+
def collections_update_item(
|
| 268 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 269 |
+
item_object_id: Annotated[
|
| 270 |
+
str,
|
| 271 |
+
typer.Argument(help="The ID of the item in the collection (from 'item_object_id' field, not the repo_id)."),
|
| 272 |
+
],
|
| 273 |
+
note: Annotated[
|
| 274 |
+
str | None,
|
| 275 |
+
typer.Option(help="A new note for the item (max 500 characters)."),
|
| 276 |
+
] = None,
|
| 277 |
+
position: Annotated[
|
| 278 |
+
int | None,
|
| 279 |
+
typer.Option(help="The new position of the item in the collection."),
|
| 280 |
+
] = None,
|
| 281 |
+
token: TokenOpt = None,
|
| 282 |
+
) -> None:
|
| 283 |
+
"""Update an item in a collection."""
|
| 284 |
+
api = get_hf_api(token=token)
|
| 285 |
+
api.update_collection_item(
|
| 286 |
+
collection_slug=collection_slug,
|
| 287 |
+
item_object_id=item_object_id,
|
| 288 |
+
note=note,
|
| 289 |
+
position=position,
|
| 290 |
+
)
|
| 291 |
+
out.result("Item updated in collection", slug=collection_slug)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@collections_cli.command("delete-item")
|
| 295 |
+
def collections_delete_item(
|
| 296 |
+
collection_slug: Annotated[str, typer.Argument(help="The collection slug (e.g., 'username/collection-slug').")],
|
| 297 |
+
item_object_id: Annotated[
|
| 298 |
+
str,
|
| 299 |
+
typer.Argument(
|
| 300 |
+
help="The ID of the item in the collection (retrieved from `item_object_id` field returned by 'hf collections info'."
|
| 301 |
+
),
|
| 302 |
+
],
|
| 303 |
+
missing_ok: Annotated[
|
| 304 |
+
bool,
|
| 305 |
+
typer.Option(help="Do not raise an error if the item doesn't exist."),
|
| 306 |
+
] = False,
|
| 307 |
+
token: TokenOpt = None,
|
| 308 |
+
) -> None:
|
| 309 |
+
"""Delete an item from a collection."""
|
| 310 |
+
api = get_hf_api(token=token)
|
| 311 |
+
api.delete_collection_item(
|
| 312 |
+
collection_slug=collection_slug,
|
| 313 |
+
item_object_id=item_object_id,
|
| 314 |
+
missing_ok=missing_ok,
|
| 315 |
+
)
|
| 316 |
+
out.result("Item deleted from collection", slug=collection_slug)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/datasets.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with datasets on the Hugging Face Hub.
|
| 15 |
+
|
| 16 |
+
Usage:
|
| 17 |
+
# list datasets on the Hub
|
| 18 |
+
hf datasets ls
|
| 19 |
+
|
| 20 |
+
# list datasets with a search query
|
| 21 |
+
hf datasets ls --search "code"
|
| 22 |
+
|
| 23 |
+
# get info about a dataset
|
| 24 |
+
hf datasets info HuggingFaceFW/fineweb
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import enum
|
| 28 |
+
from typing import Annotated, get_args
|
| 29 |
+
|
| 30 |
+
import typer
|
| 31 |
+
|
| 32 |
+
from huggingface_hub._dataset_viewer import execute_raw_sql_query
|
| 33 |
+
from huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundError
|
| 34 |
+
from huggingface_hub.hf_api import DatasetSort_T, ExpandDatasetProperty_T
|
| 35 |
+
from huggingface_hub.repocard import DatasetCard
|
| 36 |
+
|
| 37 |
+
from ._cli_utils import (
|
| 38 |
+
REPO_LIST_DEFAULT_LIMIT,
|
| 39 |
+
AuthorOpt,
|
| 40 |
+
FilterOpt,
|
| 41 |
+
LimitOpt,
|
| 42 |
+
RevisionOpt,
|
| 43 |
+
SearchOpt,
|
| 44 |
+
TokenOpt,
|
| 45 |
+
api_object_to_dict,
|
| 46 |
+
get_hf_api,
|
| 47 |
+
make_expand_properties_parser,
|
| 48 |
+
typer_factory,
|
| 49 |
+
)
|
| 50 |
+
from ._file_listing import list_repo_files_cmd
|
| 51 |
+
from ._output import out
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
_EXPAND_PROPERTIES = sorted(get_args(ExpandDatasetProperty_T))
|
| 55 |
+
_SORT_OPTIONS = get_args(DatasetSort_T)
|
| 56 |
+
DatasetSortEnum = enum.Enum("DatasetSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
ExpandOpt = Annotated[
|
| 60 |
+
str | None,
|
| 61 |
+
typer.Option(
|
| 62 |
+
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)}.",
|
| 63 |
+
callback=make_expand_properties_parser(_EXPAND_PROPERTIES),
|
| 64 |
+
),
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
datasets_cli = typer_factory(help="Interact with datasets on the Hub.")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@datasets_cli.command(
|
| 72 |
+
"list | ls",
|
| 73 |
+
examples=[
|
| 74 |
+
"hf datasets ls",
|
| 75 |
+
"hf datasets ls --sort downloads --limit 10",
|
| 76 |
+
'hf datasets ls --search "code"',
|
| 77 |
+
"hf datasets ls --filter benchmark:official",
|
| 78 |
+
"hf datasets ls HuggingFaceFW/fineweb",
|
| 79 |
+
"hf datasets ls HuggingFaceFW/fineweb -R",
|
| 80 |
+
"hf datasets ls HuggingFaceFW/fineweb --tree -h",
|
| 81 |
+
],
|
| 82 |
+
)
|
| 83 |
+
def datasets_ls(
|
| 84 |
+
repo_id: Annotated[
|
| 85 |
+
str | None,
|
| 86 |
+
typer.Argument(help="Dataset ID (e.g. `username/repo-name`) to list files from. If omitted, lists datasets."),
|
| 87 |
+
] = None,
|
| 88 |
+
search: SearchOpt = None,
|
| 89 |
+
author: AuthorOpt = None,
|
| 90 |
+
filter: FilterOpt = None,
|
| 91 |
+
sort: Annotated[
|
| 92 |
+
DatasetSortEnum | None,
|
| 93 |
+
typer.Option(help="Sort results."),
|
| 94 |
+
] = None,
|
| 95 |
+
limit: LimitOpt = REPO_LIST_DEFAULT_LIMIT,
|
| 96 |
+
expand: ExpandOpt = None,
|
| 97 |
+
human_readable: Annotated[
|
| 98 |
+
bool,
|
| 99 |
+
typer.Option("--human-readable", "-h", help="Show sizes in human readable format (only for listing files)."),
|
| 100 |
+
] = False,
|
| 101 |
+
as_tree: Annotated[
|
| 102 |
+
bool,
|
| 103 |
+
typer.Option("--tree", help="List files in tree format (only for listing files)."),
|
| 104 |
+
] = False,
|
| 105 |
+
recursive: Annotated[
|
| 106 |
+
bool,
|
| 107 |
+
typer.Option("--recursive", "-R", help="List files recursively (only for listing files)."),
|
| 108 |
+
] = False,
|
| 109 |
+
revision: RevisionOpt = None,
|
| 110 |
+
token: TokenOpt = None,
|
| 111 |
+
) -> None:
|
| 112 |
+
"""List datasets on the Hub, or files in a dataset repo.
|
| 113 |
+
|
| 114 |
+
When called with no argument, lists datasets on the Hub.
|
| 115 |
+
When called with a dataset ID, lists files in that dataset repo.
|
| 116 |
+
"""
|
| 117 |
+
if repo_id is not None:
|
| 118 |
+
if search is not None:
|
| 119 |
+
raise typer.BadParameter("Cannot use --search when listing files.")
|
| 120 |
+
if author is not None:
|
| 121 |
+
raise typer.BadParameter("Cannot use --author when listing files.")
|
| 122 |
+
if filter is not None:
|
| 123 |
+
raise typer.BadParameter("Cannot use --filter when listing files.")
|
| 124 |
+
if sort is not None:
|
| 125 |
+
raise typer.BadParameter("Cannot use --sort when listing files.")
|
| 126 |
+
if limit != REPO_LIST_DEFAULT_LIMIT:
|
| 127 |
+
raise typer.BadParameter("Cannot use --limit when listing files.")
|
| 128 |
+
if expand is not None:
|
| 129 |
+
raise typer.BadParameter("Cannot use --expand when listing files.")
|
| 130 |
+
return list_repo_files_cmd(
|
| 131 |
+
repo_id=repo_id,
|
| 132 |
+
repo_type="dataset",
|
| 133 |
+
human_readable=human_readable,
|
| 134 |
+
as_tree=as_tree,
|
| 135 |
+
recursive=recursive,
|
| 136 |
+
revision=revision,
|
| 137 |
+
token=token,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if as_tree:
|
| 141 |
+
raise typer.BadParameter("Cannot use --tree when listing datasets.")
|
| 142 |
+
if recursive:
|
| 143 |
+
raise typer.BadParameter("Cannot use --recursive when listing datasets.")
|
| 144 |
+
if human_readable:
|
| 145 |
+
raise typer.BadParameter("Cannot use --human-readable when listing datasets.")
|
| 146 |
+
if revision is not None:
|
| 147 |
+
raise typer.BadParameter("Cannot use --revision when listing datasets.")
|
| 148 |
+
|
| 149 |
+
api = get_hf_api(token=token)
|
| 150 |
+
sort_key = sort.value if sort else None
|
| 151 |
+
results = [
|
| 152 |
+
api_object_to_dict(dataset_info)
|
| 153 |
+
for dataset_info in api.list_datasets(
|
| 154 |
+
filter=filter,
|
| 155 |
+
author=author,
|
| 156 |
+
search=search,
|
| 157 |
+
sort=sort_key,
|
| 158 |
+
limit=limit,
|
| 159 |
+
expand=expand, # type: ignore
|
| 160 |
+
)
|
| 161 |
+
]
|
| 162 |
+
out.table(results)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@datasets_cli.command(
|
| 166 |
+
"leaderboard",
|
| 167 |
+
examples=[
|
| 168 |
+
"hf datasets leaderboard SWE-bench/SWE-bench_Verified",
|
| 169 |
+
"hf datasets leaderboard SWE-bench/SWE-bench_Verified --limit 5 --format json",
|
| 170 |
+
"hf datasets ls --filter benchmark:official # list available leaderboards",
|
| 171 |
+
],
|
| 172 |
+
)
|
| 173 |
+
def datasets_leaderboard(
|
| 174 |
+
dataset_id: Annotated[str, typer.Argument(help="The benchmark dataset ID (e.g. `SWE-bench/SWE-bench_Verified`).")],
|
| 175 |
+
limit: LimitOpt = 20,
|
| 176 |
+
token: TokenOpt = None,
|
| 177 |
+
) -> None:
|
| 178 |
+
"""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."""
|
| 179 |
+
api = get_hf_api(token=token)
|
| 180 |
+
leaderboard = api.get_dataset_leaderboard(repo_id=dataset_id)
|
| 181 |
+
results = [api_object_to_dict(entry) for entry in leaderboard[:limit]]
|
| 182 |
+
out.table(
|
| 183 |
+
results,
|
| 184 |
+
headers=["rank", "model_id", "value", "source"],
|
| 185 |
+
id_key="model_id",
|
| 186 |
+
alignments={"rank": "right", "value": "right"},
|
| 187 |
+
)
|
| 188 |
+
out.hint("Use 'hf datasets ls --filter benchmark:official' to list available leaderboards.")
|
| 189 |
+
if leaderboard:
|
| 190 |
+
out.hint(f"Use 'hf models info {leaderboard[0].model_id}' to get details about a model.")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@datasets_cli.command(
|
| 194 |
+
"info",
|
| 195 |
+
examples=[
|
| 196 |
+
"hf datasets info HuggingFaceFW/fineweb",
|
| 197 |
+
"hf datasets info my-dataset --expand downloads,likes,tags",
|
| 198 |
+
],
|
| 199 |
+
)
|
| 200 |
+
def datasets_info(
|
| 201 |
+
dataset_id: Annotated[str, typer.Argument(help="The dataset ID (e.g. `username/repo-name`).")],
|
| 202 |
+
revision: RevisionOpt = None,
|
| 203 |
+
expand: ExpandOpt = None,
|
| 204 |
+
token: TokenOpt = None,
|
| 205 |
+
) -> None:
|
| 206 |
+
"""Get info about a dataset on the Hub."""
|
| 207 |
+
api = get_hf_api(token=token)
|
| 208 |
+
try:
|
| 209 |
+
info = api.dataset_info(repo_id=dataset_id, revision=revision, expand=expand) # type: ignore
|
| 210 |
+
except RepositoryNotFoundError as e:
|
| 211 |
+
raise CLIError(f"Dataset '{dataset_id}' not found.") from e
|
| 212 |
+
except RevisionNotFoundError as e:
|
| 213 |
+
raise CLIError(f"Revision '{revision}' not found on '{dataset_id}'.") from e
|
| 214 |
+
out.dict(info)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
@datasets_cli.command(
|
| 218 |
+
"parquet",
|
| 219 |
+
examples=[
|
| 220 |
+
"hf datasets parquet cfahlgren1/hub-stats",
|
| 221 |
+
"hf datasets parquet cfahlgren1/hub-stats --subset models",
|
| 222 |
+
"hf datasets parquet cfahlgren1/hub-stats --split train",
|
| 223 |
+
"hf datasets parquet cfahlgren1/hub-stats --format json",
|
| 224 |
+
],
|
| 225 |
+
)
|
| 226 |
+
def datasets_parquet(
|
| 227 |
+
dataset_id: Annotated[str, typer.Argument(help="The dataset ID (e.g. `username/repo-name`).")],
|
| 228 |
+
subset: Annotated[str | None, typer.Option("--subset", help="Filter parquet entries by subset/config.")] = None,
|
| 229 |
+
split: Annotated[str | None, typer.Option(help="Filter parquet entries by split.")] = None,
|
| 230 |
+
token: TokenOpt = None,
|
| 231 |
+
) -> None:
|
| 232 |
+
"""List parquet file URLs available for a dataset."""
|
| 233 |
+
api = get_hf_api(token=token)
|
| 234 |
+
entries = api.list_dataset_parquet_files(repo_id=dataset_id, config=subset)
|
| 235 |
+
filtered = [entry for entry in entries if split is None or entry.split == split]
|
| 236 |
+
results = [
|
| 237 |
+
{"subset": entry.config, "split": entry.split, "url": entry.url, "size": entry.size} for entry in filtered
|
| 238 |
+
]
|
| 239 |
+
out.table(results, headers=["subset", "split", "url", "size"], id_key="url")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@datasets_cli.command(
|
| 243 |
+
"sql",
|
| 244 |
+
examples=[
|
| 245 |
+
"hf datasets sql \"SELECT COUNT(*) AS rows FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet')\"",
|
| 246 |
+
"hf datasets sql \"SELECT * FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet') LIMIT 5\" --format json",
|
| 247 |
+
],
|
| 248 |
+
)
|
| 249 |
+
def datasets_sql(
|
| 250 |
+
sql: Annotated[str, typer.Argument(help="Raw SQL query to execute.")],
|
| 251 |
+
token: TokenOpt = None,
|
| 252 |
+
) -> None:
|
| 253 |
+
"""Execute a raw SQL query with DuckDB against dataset parquet URLs."""
|
| 254 |
+
try:
|
| 255 |
+
result = execute_raw_sql_query(sql_query=sql, token=token)
|
| 256 |
+
except ImportError as e:
|
| 257 |
+
raise CLIError(str(e)) from e
|
| 258 |
+
out.table(result)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
@datasets_cli.command(
|
| 262 |
+
"card",
|
| 263 |
+
examples=[
|
| 264 |
+
"hf datasets card HuggingFaceFW/fineweb",
|
| 265 |
+
"hf datasets card HuggingFaceFW/fineweb --metadata",
|
| 266 |
+
"hf datasets card HuggingFaceFW/fineweb --metadata --format json",
|
| 267 |
+
"hf datasets card HuggingFaceFW/fineweb --text",
|
| 268 |
+
],
|
| 269 |
+
)
|
| 270 |
+
def datasets_card(
|
| 271 |
+
dataset_id: Annotated[str, typer.Argument(help="The dataset ID (e.g. `username/repo-name`).")],
|
| 272 |
+
metadata: Annotated[bool, typer.Option("--metadata", help="Output only the metadata from the card.")] = False,
|
| 273 |
+
text: Annotated[bool, typer.Option("--text", help="Output only the text body (no metadata).")] = False,
|
| 274 |
+
token: TokenOpt = None,
|
| 275 |
+
) -> None:
|
| 276 |
+
"""Get the dataset card (README) for a dataset on the Hub."""
|
| 277 |
+
if metadata and text:
|
| 278 |
+
raise CLIError("--metadata and --text are mutually exclusive.")
|
| 279 |
+
card = DatasetCard.load(dataset_id, token=token)
|
| 280 |
+
if metadata:
|
| 281 |
+
out.dict(card.data.to_dict())
|
| 282 |
+
elif text:
|
| 283 |
+
out.text(card.text)
|
| 284 |
+
else:
|
| 285 |
+
out.text(card.content)
|
| 286 |
+
out.hint(f"Use `hf datasets card {dataset_id} --metadata` to extract only the card metadata.")
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/deprecated_cli.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deprecated `huggingface-cli` entry point. Warns and exits."""
|
| 2 |
+
|
| 3 |
+
import shutil
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from ._output import out
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main() -> None:
|
| 10 |
+
out.warning("`huggingface-cli` is deprecated and no longer works. Use `hf` instead.\n")
|
| 11 |
+
|
| 12 |
+
if shutil.which("hf"):
|
| 13 |
+
from huggingface_hub.cli._cli_utils import check_cli_update
|
| 14 |
+
|
| 15 |
+
check_cli_update("huggingface_hub")
|
| 16 |
+
out.hint("`hf` is already installed! Use it directly.\n")
|
| 17 |
+
else:
|
| 18 |
+
out.hint(
|
| 19 |
+
"Install `hf`:\n"
|
| 20 |
+
" Standalone (recommended): curl -LsSf https://hf.co/cli/install.sh | bash\n"
|
| 21 |
+
" Using Homebrew: brew install hf\n"
|
| 22 |
+
" Using pip: pip install huggingface_hub\n",
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
out.hint(
|
| 26 |
+
"Examples:\n"
|
| 27 |
+
" hf auth login\n"
|
| 28 |
+
" hf download unsloth/gemma-4-31B-it-GGUF\n"
|
| 29 |
+
" hf upload my-cool-model . .\n"
|
| 30 |
+
' hf models ls --search "gemma"\n'
|
| 31 |
+
" hf repos ls --format json\n"
|
| 32 |
+
" hf jobs run python:3.12 python -c 'print(\"Hello!\")'\n"
|
| 33 |
+
" hf --help\n",
|
| 34 |
+
)
|
| 35 |
+
sys.exit(1)
|
micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/cli/discussions.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains commands to interact with discussions and pull requests on the Hugging Face Hub."""
|
| 15 |
+
|
| 16 |
+
import enum
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Annotated
|
| 20 |
+
|
| 21 |
+
import typer
|
| 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 |
+
api_object_to_dict,
|
| 33 |
+
get_hf_api,
|
| 34 |
+
typer_factory,
|
| 35 |
+
)
|
| 36 |
+
from ._output import 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 |
+
typer.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 typer.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 |
+
typer.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 |
+
typer.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 = [api_object_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 |
+
alignments={"num": "right"},
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@discussions_cli.command(
|
| 156 |
+
"info",
|
| 157 |
+
examples=[
|
| 158 |
+
"hf discussions info username/my-model 5",
|
| 159 |
+
"hf discussions info username/my-model 5 --format json",
|
| 160 |
+
],
|
| 161 |
+
)
|
| 162 |
+
def discussion_info(
|
| 163 |
+
repo_id: RepoIdArg,
|
| 164 |
+
num: DiscussionNumArg,
|
| 165 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 166 |
+
token: TokenOpt = None,
|
| 167 |
+
) -> None:
|
| 168 |
+
"""Get info about a discussion or pull request."""
|
| 169 |
+
api = get_hf_api(token=token)
|
| 170 |
+
details = api.get_discussion_details(
|
| 171 |
+
repo_id=repo_id,
|
| 172 |
+
discussion_num=num,
|
| 173 |
+
repo_type=repo_type.value,
|
| 174 |
+
)
|
| 175 |
+
out.dict(details)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@discussions_cli.command(
|
| 179 |
+
"create",
|
| 180 |
+
examples=[
|
| 181 |
+
'hf discussions create username/my-model --title "Bug report"',
|
| 182 |
+
'hf discussions create username/my-model --title "Feature request" --body "Please add X"',
|
| 183 |
+
'hf discussions create username/my-model --title "Fix typo" --pull-request',
|
| 184 |
+
'hf discussions create username/my-dataset --type dataset --title "Data quality issue"',
|
| 185 |
+
],
|
| 186 |
+
)
|
| 187 |
+
def discussion_create(
|
| 188 |
+
repo_id: RepoIdArg,
|
| 189 |
+
title: Annotated[
|
| 190 |
+
str,
|
| 191 |
+
typer.Option(
|
| 192 |
+
"--title",
|
| 193 |
+
help="The title of the discussion or pull request.",
|
| 194 |
+
),
|
| 195 |
+
],
|
| 196 |
+
body: Annotated[
|
| 197 |
+
str | None,
|
| 198 |
+
typer.Option(
|
| 199 |
+
"--body",
|
| 200 |
+
help="The description (supports Markdown).",
|
| 201 |
+
),
|
| 202 |
+
] = None,
|
| 203 |
+
body_file: Annotated[
|
| 204 |
+
Path | None,
|
| 205 |
+
typer.Option(
|
| 206 |
+
"--body-file",
|
| 207 |
+
help="Read the description from a file. Use '-' for stdin.",
|
| 208 |
+
),
|
| 209 |
+
] = None,
|
| 210 |
+
pull_request: Annotated[
|
| 211 |
+
bool,
|
| 212 |
+
typer.Option(
|
| 213 |
+
"--pull-request",
|
| 214 |
+
"--pr",
|
| 215 |
+
help="Create a pull request instead of a discussion.",
|
| 216 |
+
),
|
| 217 |
+
] = False,
|
| 218 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 219 |
+
token: TokenOpt = None,
|
| 220 |
+
) -> None:
|
| 221 |
+
"""Create a new discussion or pull request on a repo."""
|
| 222 |
+
description = _read_body(body, body_file)
|
| 223 |
+
api = get_hf_api(token=token)
|
| 224 |
+
discussion = api.create_discussion(
|
| 225 |
+
repo_id=repo_id,
|
| 226 |
+
title=title,
|
| 227 |
+
description=description,
|
| 228 |
+
repo_type=repo_type.value,
|
| 229 |
+
pull_request=pull_request,
|
| 230 |
+
)
|
| 231 |
+
kind = "pull request" if pull_request else "discussion"
|
| 232 |
+
ref = f"refs/pr/{discussion.num}" if pull_request else None
|
| 233 |
+
out.result(f"Created {kind} #{discussion.num} on {repo_id}", num=discussion.num, url=discussion.url, ref=ref)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@discussions_cli.command(
|
| 237 |
+
"comment",
|
| 238 |
+
examples=[
|
| 239 |
+
'hf discussions comment username/my-model 5 --body "Thanks for reporting!"',
|
| 240 |
+
'hf discussions comment username/my-model 5 --body "LGTM!"',
|
| 241 |
+
],
|
| 242 |
+
)
|
| 243 |
+
def discussion_comment(
|
| 244 |
+
repo_id: RepoIdArg,
|
| 245 |
+
num: DiscussionNumArg,
|
| 246 |
+
body: Annotated[
|
| 247 |
+
str | None,
|
| 248 |
+
typer.Option(
|
| 249 |
+
"--body",
|
| 250 |
+
help="The comment text (supports Markdown).",
|
| 251 |
+
),
|
| 252 |
+
] = None,
|
| 253 |
+
body_file: Annotated[
|
| 254 |
+
Path | None,
|
| 255 |
+
typer.Option(
|
| 256 |
+
"--body-file",
|
| 257 |
+
help="Read the comment from a file. Use '-' for stdin.",
|
| 258 |
+
),
|
| 259 |
+
] = None,
|
| 260 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 261 |
+
token: TokenOpt = None,
|
| 262 |
+
) -> None:
|
| 263 |
+
"""Comment on a discussion or pull request."""
|
| 264 |
+
comment = _read_body(body, body_file)
|
| 265 |
+
if comment is None:
|
| 266 |
+
raise typer.BadParameter("Either --body or --body-file is required.")
|
| 267 |
+
api = get_hf_api(token=token)
|
| 268 |
+
api.comment_discussion(
|
| 269 |
+
repo_id=repo_id,
|
| 270 |
+
discussion_num=num,
|
| 271 |
+
comment=comment,
|
| 272 |
+
repo_type=repo_type.value,
|
| 273 |
+
)
|
| 274 |
+
out.result(f"Commented on #{num} in {repo_id}", num=num, repo=repo_id)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@discussions_cli.command(
|
| 278 |
+
"close",
|
| 279 |
+
examples=[
|
| 280 |
+
"hf discussions close username/my-model 5",
|
| 281 |
+
'hf discussions close username/my-model 5 --comment "Closing as resolved."',
|
| 282 |
+
],
|
| 283 |
+
)
|
| 284 |
+
def discussion_close(
|
| 285 |
+
repo_id: RepoIdArg,
|
| 286 |
+
num: DiscussionNumArg,
|
| 287 |
+
comment: Annotated[
|
| 288 |
+
str | None,
|
| 289 |
+
typer.Option(
|
| 290 |
+
"--comment",
|
| 291 |
+
help="An optional comment to post when closing.",
|
| 292 |
+
),
|
| 293 |
+
] = None,
|
| 294 |
+
yes: Annotated[
|
| 295 |
+
bool,
|
| 296 |
+
typer.Option(
|
| 297 |
+
"--yes",
|
| 298 |
+
"-y",
|
| 299 |
+
help="Skip confirmation prompt.",
|
| 300 |
+
),
|
| 301 |
+
] = False,
|
| 302 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 303 |
+
token: TokenOpt = None,
|
| 304 |
+
) -> None:
|
| 305 |
+
"""Close a discussion or pull request."""
|
| 306 |
+
out.confirm(f"Close #{num} on '{repo_id}'?", yes=yes)
|
| 307 |
+
api = get_hf_api(token=token)
|
| 308 |
+
api.change_discussion_status(
|
| 309 |
+
repo_id=repo_id,
|
| 310 |
+
discussion_num=num,
|
| 311 |
+
new_status="closed",
|
| 312 |
+
comment=comment,
|
| 313 |
+
repo_type=repo_type.value,
|
| 314 |
+
)
|
| 315 |
+
out.result(f"Closed #{num} in {repo_id}", num=num, repo=repo_id)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@discussions_cli.command(
|
| 319 |
+
"reopen",
|
| 320 |
+
examples=[
|
| 321 |
+
"hf discussions reopen username/my-model 5",
|
| 322 |
+
'hf discussions reopen username/my-model 5 --comment "Reopening for further investigation."',
|
| 323 |
+
],
|
| 324 |
+
)
|
| 325 |
+
def discussion_reopen(
|
| 326 |
+
repo_id: RepoIdArg,
|
| 327 |
+
num: DiscussionNumArg,
|
| 328 |
+
comment: Annotated[
|
| 329 |
+
str | None,
|
| 330 |
+
typer.Option(
|
| 331 |
+
"--comment",
|
| 332 |
+
help="An optional comment to post when reopening.",
|
| 333 |
+
),
|
| 334 |
+
] = None,
|
| 335 |
+
yes: Annotated[
|
| 336 |
+
bool,
|
| 337 |
+
typer.Option(
|
| 338 |
+
"--yes",
|
| 339 |
+
"-y",
|
| 340 |
+
help="Skip confirmation prompt.",
|
| 341 |
+
),
|
| 342 |
+
] = False,
|
| 343 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 344 |
+
token: TokenOpt = None,
|
| 345 |
+
) -> None:
|
| 346 |
+
"""Reopen a closed discussion or pull request."""
|
| 347 |
+
out.confirm(f"Reopen #{num} on '{repo_id}'?", yes=yes)
|
| 348 |
+
api = get_hf_api(token=token)
|
| 349 |
+
api.change_discussion_status(
|
| 350 |
+
repo_id=repo_id,
|
| 351 |
+
discussion_num=num,
|
| 352 |
+
new_status="open",
|
| 353 |
+
comment=comment,
|
| 354 |
+
repo_type=repo_type.value,
|
| 355 |
+
)
|
| 356 |
+
out.result(f"Reopened #{num} in {repo_id}", num=num, repo=repo_id)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
@discussions_cli.command(
|
| 360 |
+
"rename",
|
| 361 |
+
examples=[
|
| 362 |
+
'hf discussions rename username/my-model 5 "Updated title"',
|
| 363 |
+
],
|
| 364 |
+
)
|
| 365 |
+
def discussion_rename(
|
| 366 |
+
repo_id: RepoIdArg,
|
| 367 |
+
num: DiscussionNumArg,
|
| 368 |
+
new_title: Annotated[
|
| 369 |
+
str,
|
| 370 |
+
typer.Argument(
|
| 371 |
+
help="The new title.",
|
| 372 |
+
),
|
| 373 |
+
],
|
| 374 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 375 |
+
token: TokenOpt = None,
|
| 376 |
+
) -> None:
|
| 377 |
+
"""Rename a discussion or pull request."""
|
| 378 |
+
api = get_hf_api(token=token)
|
| 379 |
+
api.rename_discussion(
|
| 380 |
+
repo_id=repo_id,
|
| 381 |
+
discussion_num=num,
|
| 382 |
+
new_title=new_title,
|
| 383 |
+
repo_type=repo_type.value,
|
| 384 |
+
)
|
| 385 |
+
out.result(f"Renamed #{num} in {repo_id}", num=num, repo=repo_id, title=new_title)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
@discussions_cli.command(
|
| 389 |
+
"merge",
|
| 390 |
+
examples=[
|
| 391 |
+
"hf discussions merge username/my-model 5",
|
| 392 |
+
'hf discussions merge username/my-model 5 --comment "Merging, thanks!"',
|
| 393 |
+
],
|
| 394 |
+
)
|
| 395 |
+
def discussion_merge(
|
| 396 |
+
repo_id: RepoIdArg,
|
| 397 |
+
num: DiscussionNumArg,
|
| 398 |
+
comment: Annotated[
|
| 399 |
+
str | None,
|
| 400 |
+
typer.Option(
|
| 401 |
+
"--comment",
|
| 402 |
+
help="An optional comment to post when merging.",
|
| 403 |
+
),
|
| 404 |
+
] = None,
|
| 405 |
+
yes: Annotated[
|
| 406 |
+
bool,
|
| 407 |
+
typer.Option(
|
| 408 |
+
"--yes",
|
| 409 |
+
"-y",
|
| 410 |
+
help="Skip confirmation prompt.",
|
| 411 |
+
),
|
| 412 |
+
] = False,
|
| 413 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 414 |
+
token: TokenOpt = None,
|
| 415 |
+
) -> None:
|
| 416 |
+
"""Merge a pull request."""
|
| 417 |
+
out.confirm(f"Merge #{num} on '{repo_id}'?", yes=yes)
|
| 418 |
+
api = get_hf_api(token=token)
|
| 419 |
+
api.merge_pull_request(
|
| 420 |
+
repo_id=repo_id,
|
| 421 |
+
discussion_num=num,
|
| 422 |
+
comment=comment,
|
| 423 |
+
repo_type=repo_type.value,
|
| 424 |
+
)
|
| 425 |
+
out.result(f"Merged #{num} in {repo_id}", num=num, repo=repo_id)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
@discussions_cli.command(
|
| 429 |
+
"diff",
|
| 430 |
+
examples=[
|
| 431 |
+
"hf discussions diff username/my-model 5",
|
| 432 |
+
],
|
| 433 |
+
)
|
| 434 |
+
def discussion_diff(
|
| 435 |
+
repo_id: RepoIdArg,
|
| 436 |
+
num: DiscussionNumArg,
|
| 437 |
+
repo_type: RepoTypeOpt = RepoType.model,
|
| 438 |
+
token: TokenOpt = None,
|
| 439 |
+
) -> None:
|
| 440 |
+
"""Show the diff of a pull request."""
|
| 441 |
+
api = get_hf_api(token=token)
|
| 442 |
+
details = api.get_discussion_details(
|
| 443 |
+
repo_id=repo_id,
|
| 444 |
+
discussion_num=num,
|
| 445 |
+
repo_type=repo_type.value,
|
| 446 |
+
)
|
| 447 |
+
if details.diff:
|
| 448 |
+
out.text(details.diff)
|
| 449 |
+
else:
|
| 450 |
+
out.text("No diff available.")
|