Ahmad2005 commited on
Commit
b4e2096
·
verified ·
1 Parent(s): 8e372eb

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub-1.23.0.dist-info/licenses/LICENSE +201 -0
  2. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/__init__.py +1804 -0
  3. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_buckets.py +1244 -0
  4. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_commit_api.py +1075 -0
  5. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_commit_scheduler.py +353 -0
  6. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_dataset_viewer.py +172 -0
  7. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_eval_results.py +211 -0
  8. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_hot_reload/__init__.py +13 -0
  9. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_hot_reload/client.py +130 -0
  10. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_hot_reload/sse_client.py +144 -0
  11. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_hot_reload/types.py +121 -0
  12. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_inference_endpoints.py +419 -0
  13. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_jobs_api.py +567 -0
  14. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_local_folder.py +473 -0
  15. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_login.py +559 -0
  16. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_oauth.py +460 -0
  17. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_oidc.py +163 -0
  18. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_sandbox.py +1764 -0
  19. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_sandbox_cache.py +159 -0
  20. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_snapshot_download.py +681 -0
  21. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_space_api.py +395 -0
  22. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_tensorboard_logger.py +189 -0
  23. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_tree_cache.py +138 -0
  24. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_upload_large_folder.py +769 -0
  25. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_upload_pipeline.py +682 -0
  26. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_webhooks_payload.py +136 -0
  27. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_webhooks_server.py +376 -0
  28. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/__init__.py +14 -0
  29. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_city_game.py +661 -0
  30. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_cli_utils.py +1069 -0
  31. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_completion.py +105 -0
  32. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_cp.py +253 -0
  33. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_errors.py +155 -0
  34. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_file_listing.py +225 -0
  35. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_framework.py +645 -0
  36. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_help_formatter.py +34 -0
  37. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_output.py +360 -0
  38. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_skills.py +311 -0
  39. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/auth.py +174 -0
  40. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/buckets.py +679 -0
  41. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/cache.py +800 -0
  42. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/collections.py +293 -0
  43. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/datasets.py +274 -0
  44. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/deprecated_cli.py +35 -0
  45. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/discussions.py +497 -0
  46. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/download.py +225 -0
  47. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/extensions.py +697 -0
  48. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/hf.py +142 -0
  49. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/inference_endpoints.py +535 -0
  50. .cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/jobs.py +1335 -0
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub-1.23.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/__init__.py ADDED
@@ -0,0 +1,1804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # ***********
16
+ # `huggingface_hub` init has 2 modes:
17
+ # - Normal usage:
18
+ # If imported to use it, all modules and functions are lazy-loaded. This means
19
+ # they exist at top level in module but are imported only the first time they are
20
+ # used. This way, `from huggingface_hub import something` will import `something`
21
+ # quickly without the hassle of importing all the features from `huggingface_hub`.
22
+ # - Static check:
23
+ # If statically analyzed, all modules and functions are loaded normally. This way
24
+ # static typing check works properly as well as autocomplete in text editors and
25
+ # IDEs.
26
+ #
27
+ # The static model imports are done inside the `if TYPE_CHECKING:` statement at
28
+ # the bottom of this file. Since module/functions imports are duplicated, it is
29
+ # mandatory to make sure to add them twice when adding one. This is checked in the
30
+ # `make quality` command.
31
+ #
32
+ # To update the static imports, please run the following command and commit the changes.
33
+ # ```
34
+ # # Use script
35
+ # python utils/check_static_imports.py --update-file
36
+ #
37
+ # # Or run style on codebase
38
+ # make style
39
+ # ```
40
+ #
41
+ # ***********
42
+ # Lazy loader vendored from https://github.com/scientific-python/lazy_loader
43
+ import importlib
44
+ import os
45
+ import sys
46
+ from typing import TYPE_CHECKING
47
+
48
+
49
+ __version__ = "1.23.0"
50
+
51
+ # Alphabetical order of definitions is ensured in tests
52
+ # WARNING: any comment added in this dictionary definition will be lost when
53
+ # re-generating the file !
54
+ _SUBMOD_ATTRS = {
55
+ "_buckets": [
56
+ "BucketFile",
57
+ "BucketFileMetadata",
58
+ "BucketFolder",
59
+ "BucketInfo",
60
+ "BucketUrl",
61
+ "SyncOperation",
62
+ "SyncPlan",
63
+ ],
64
+ "_commit_scheduler": [
65
+ "CommitScheduler",
66
+ ],
67
+ "_eval_results": [
68
+ "EvalResultEntry",
69
+ "eval_result_entries_to_yaml",
70
+ "parse_eval_result_entries",
71
+ ],
72
+ "_inference_endpoints": [
73
+ "InferenceEndpoint",
74
+ "InferenceEndpointError",
75
+ "InferenceEndpointStatus",
76
+ "InferenceEndpointTimeoutError",
77
+ "InferenceEndpointType",
78
+ ],
79
+ "_jobs_api": [
80
+ "JobAccelerator",
81
+ "JobDurations",
82
+ "JobHardware",
83
+ "JobHardwareInfo",
84
+ "JobInfo",
85
+ "JobInitiator",
86
+ "JobOwner",
87
+ "JobStage",
88
+ "JobStatus",
89
+ ],
90
+ "_login": [
91
+ "auth_list",
92
+ "auth_switch",
93
+ "interpreter_login",
94
+ "login",
95
+ "logout",
96
+ "notebook_login",
97
+ ],
98
+ "_oauth": [
99
+ "OAuthInfo",
100
+ "OAuthOrgInfo",
101
+ "OAuthUserInfo",
102
+ "attach_huggingface_oauth",
103
+ "parse_huggingface_oauth",
104
+ ],
105
+ "_sandbox": [
106
+ "Sandbox",
107
+ "SandboxCommandResult",
108
+ "SandboxPool",
109
+ "SandboxProcess",
110
+ ],
111
+ "_snapshot_download": [
112
+ "get_cached_repo_tree",
113
+ "snapshot_download",
114
+ ],
115
+ "_space_api": [
116
+ "SpaceHardware",
117
+ "SpaceRuntime",
118
+ "SpaceSecret",
119
+ "SpaceStage",
120
+ "SpaceStorage",
121
+ "SpaceVariable",
122
+ "Volume",
123
+ ],
124
+ "_tensorboard_logger": [
125
+ "HFSummaryWriter",
126
+ ],
127
+ "_webhooks_payload": [
128
+ "WebhookPayload",
129
+ "WebhookPayloadComment",
130
+ "WebhookPayloadDiscussion",
131
+ "WebhookPayloadDiscussionChanges",
132
+ "WebhookPayloadEvent",
133
+ "WebhookPayloadMovedTo",
134
+ "WebhookPayloadRepo",
135
+ "WebhookPayloadUrl",
136
+ "WebhookPayloadWebhook",
137
+ ],
138
+ "_webhooks_server": [
139
+ "WebhooksServer",
140
+ "webhook_endpoint",
141
+ ],
142
+ "cli._cli_utils": [
143
+ "check_cli_update",
144
+ "typer_factory",
145
+ ],
146
+ "community": [
147
+ "Discussion",
148
+ "DiscussionComment",
149
+ "DiscussionCommit",
150
+ "DiscussionEvent",
151
+ "DiscussionStatusChange",
152
+ "DiscussionTitleChange",
153
+ "DiscussionWithDetails",
154
+ ],
155
+ "constants": [
156
+ "CONFIG_NAME",
157
+ "FLAX_WEIGHTS_NAME",
158
+ "HUGGINGFACE_CO_URL_HOME",
159
+ "HUGGINGFACE_CO_URL_TEMPLATE",
160
+ "PYTORCH_WEIGHTS_NAME",
161
+ "REPO_TYPE_DATASET",
162
+ "REPO_TYPE_MODEL",
163
+ "REPO_TYPE_SPACE",
164
+ "TF2_WEIGHTS_NAME",
165
+ "TF_WEIGHTS_NAME",
166
+ "is_offline_mode",
167
+ ],
168
+ "fastai_utils": [
169
+ "_save_pretrained_fastai",
170
+ "from_pretrained_fastai",
171
+ "push_to_hub_fastai",
172
+ ],
173
+ "file_download": [
174
+ "DryRunFileInfo",
175
+ "HfFileMetadata",
176
+ "_CACHED_NO_EXIST",
177
+ "get_hf_file_metadata",
178
+ "hf_hub_download",
179
+ "hf_hub_url",
180
+ "try_to_load_from_cache",
181
+ ],
182
+ "hf_api": [
183
+ "Collection",
184
+ "CollectionItem",
185
+ "CommitInfo",
186
+ "CommitOperation",
187
+ "CommitOperationAdd",
188
+ "CommitOperationCopy",
189
+ "CommitOperationDelete",
190
+ "DatasetInfo",
191
+ "DatasetLeaderboardEntry",
192
+ "GitCommitInfo",
193
+ "GitRefInfo",
194
+ "GitRefs",
195
+ "HfApi",
196
+ "KernelInfo",
197
+ "ModelInfo",
198
+ "Organization",
199
+ "RepoFile",
200
+ "RepoFolder",
201
+ "RepoStorageInfo",
202
+ "RepoUrl",
203
+ "SpaceInfo",
204
+ "SpaceSearchResult",
205
+ "SpaceTemplate",
206
+ "User",
207
+ "UserLikes",
208
+ "WebhookInfo",
209
+ "WebhookWatchedItem",
210
+ "accept_access_request",
211
+ "add_collection_item",
212
+ "add_space_secret",
213
+ "add_space_variable",
214
+ "auth_check",
215
+ "batch_bucket_files",
216
+ "bucket_info",
217
+ "cancel_access_request",
218
+ "cancel_job",
219
+ "change_discussion_status",
220
+ "comment_discussion",
221
+ "copy_files",
222
+ "create_branch",
223
+ "create_bucket",
224
+ "create_collection",
225
+ "create_commit",
226
+ "create_discussion",
227
+ "create_inference_endpoint",
228
+ "create_inference_endpoint_from_catalog",
229
+ "create_pull_request",
230
+ "create_repo",
231
+ "create_scheduled_job",
232
+ "create_scheduled_uv_job",
233
+ "create_tag",
234
+ "create_webhook",
235
+ "dataset_info",
236
+ "delete_branch",
237
+ "delete_bucket",
238
+ "delete_collection",
239
+ "delete_collection_item",
240
+ "delete_file",
241
+ "delete_folder",
242
+ "delete_inference_endpoint",
243
+ "delete_repo",
244
+ "delete_scheduled_job",
245
+ "delete_space_secret",
246
+ "delete_space_storage",
247
+ "delete_space_variable",
248
+ "delete_space_volumes",
249
+ "delete_tag",
250
+ "delete_webhook",
251
+ "disable_space_dev_mode",
252
+ "disable_webhook",
253
+ "download_bucket_files",
254
+ "duplicate_repo",
255
+ "duplicate_space",
256
+ "edit_discussion_comment",
257
+ "enable_space_dev_mode",
258
+ "enable_webhook",
259
+ "fetch_job_logs",
260
+ "fetch_job_metrics",
261
+ "fetch_space_logs",
262
+ "file_exists",
263
+ "get_bucket_file_metadata",
264
+ "get_bucket_paths_info",
265
+ "get_collection",
266
+ "get_dataset_leaderboard",
267
+ "get_dataset_tags",
268
+ "get_discussion_details",
269
+ "get_full_repo_name",
270
+ "get_inference_endpoint",
271
+ "get_local_safetensors_metadata",
272
+ "get_model_tags",
273
+ "get_organization_overview",
274
+ "get_paths_info",
275
+ "get_repo_discussions",
276
+ "get_safetensors_metadata",
277
+ "get_space_runtime",
278
+ "get_space_secrets",
279
+ "get_space_variables",
280
+ "get_user_overview",
281
+ "get_webhook",
282
+ "grant_access",
283
+ "inspect_job",
284
+ "inspect_scheduled_job",
285
+ "kernel_info",
286
+ "list_accepted_access_requests",
287
+ "list_bucket_tree",
288
+ "list_buckets",
289
+ "list_collections",
290
+ "list_daily_papers",
291
+ "list_dataset_parquet_files",
292
+ "list_datasets",
293
+ "list_inference_catalog",
294
+ "list_inference_endpoints",
295
+ "list_jobs",
296
+ "list_jobs_hardware",
297
+ "list_lfs_files",
298
+ "list_liked_repos",
299
+ "list_models",
300
+ "list_organization_followers",
301
+ "list_organization_members",
302
+ "list_papers",
303
+ "list_pending_access_requests",
304
+ "list_rejected_access_requests",
305
+ "list_repo_commits",
306
+ "list_repo_files",
307
+ "list_repo_likers",
308
+ "list_repo_refs",
309
+ "list_repo_tree",
310
+ "list_space_templates",
311
+ "list_spaces",
312
+ "list_spaces_hardware",
313
+ "list_user_followers",
314
+ "list_user_following",
315
+ "list_user_repos",
316
+ "list_webhooks",
317
+ "merge_pull_request",
318
+ "model_info",
319
+ "move_bucket",
320
+ "move_repo",
321
+ "paper_info",
322
+ "parse_local_safetensors_file_metadata",
323
+ "parse_safetensors_file_metadata",
324
+ "pause_inference_endpoint",
325
+ "pause_space",
326
+ "permanently_delete_lfs_files",
327
+ "preupload_lfs_files",
328
+ "read_paper",
329
+ "reject_access_request",
330
+ "rename_discussion",
331
+ "repo_exists",
332
+ "repo_info",
333
+ "repo_type_and_id_from_hf_id",
334
+ "request_space_hardware",
335
+ "request_space_storage",
336
+ "restart_space",
337
+ "resume_inference_endpoint",
338
+ "resume_scheduled_job",
339
+ "revision_exists",
340
+ "run_as_future",
341
+ "run_job",
342
+ "run_uv_job",
343
+ "scale_to_zero_inference_endpoint",
344
+ "search_spaces",
345
+ "set_space_sleep_time",
346
+ "set_space_volumes",
347
+ "space_info",
348
+ "super_squash_history",
349
+ "suspend_scheduled_job",
350
+ "sync_bucket",
351
+ "sync_job_volume",
352
+ "trigger_scheduled_job",
353
+ "unlike",
354
+ "update_collection_item",
355
+ "update_collection_metadata",
356
+ "update_inference_endpoint",
357
+ "update_job_labels",
358
+ "update_repo_settings",
359
+ "update_scheduled_job_labels",
360
+ "update_webhook",
361
+ "upload_file",
362
+ "upload_folder",
363
+ "upload_large_folder",
364
+ "verify_repo_checksums",
365
+ "wait_for_job",
366
+ "wait_for_space",
367
+ "whoami",
368
+ ],
369
+ "hf_file_system": [
370
+ "HfFileSystem",
371
+ "HfFileSystemFile",
372
+ "HfFileSystemResolvedPath",
373
+ "HfFileSystemStreamFile",
374
+ "hffs",
375
+ ],
376
+ "hub_mixin": [
377
+ "ModelHubMixin",
378
+ "PyTorchModelHubMixin",
379
+ ],
380
+ "inference._client": [
381
+ "InferenceClient",
382
+ "InferenceTimeoutError",
383
+ ],
384
+ "inference._generated._async_client": [
385
+ "AsyncInferenceClient",
386
+ ],
387
+ "inference._generated.types": [
388
+ "AudioClassificationInput",
389
+ "AudioClassificationOutputElement",
390
+ "AudioClassificationOutputTransform",
391
+ "AudioClassificationParameters",
392
+ "AudioToAudioInput",
393
+ "AudioToAudioOutputElement",
394
+ "AutomaticSpeechRecognitionEarlyStoppingEnum",
395
+ "AutomaticSpeechRecognitionGenerationParameters",
396
+ "AutomaticSpeechRecognitionInput",
397
+ "AutomaticSpeechRecognitionOutput",
398
+ "AutomaticSpeechRecognitionOutputChunk",
399
+ "AutomaticSpeechRecognitionParameters",
400
+ "ChatCompletionInput",
401
+ "ChatCompletionInputFunctionDefinition",
402
+ "ChatCompletionInputFunctionName",
403
+ "ChatCompletionInputGrammarType",
404
+ "ChatCompletionInputJSONSchema",
405
+ "ChatCompletionInputMessage",
406
+ "ChatCompletionInputMessageChunk",
407
+ "ChatCompletionInputMessageChunkType",
408
+ "ChatCompletionInputResponseFormatJSONObject",
409
+ "ChatCompletionInputResponseFormatJSONSchema",
410
+ "ChatCompletionInputResponseFormatText",
411
+ "ChatCompletionInputStreamOptions",
412
+ "ChatCompletionInputTool",
413
+ "ChatCompletionInputToolCall",
414
+ "ChatCompletionInputToolChoiceClass",
415
+ "ChatCompletionInputToolChoiceEnum",
416
+ "ChatCompletionInputURL",
417
+ "ChatCompletionOutput",
418
+ "ChatCompletionOutputComplete",
419
+ "ChatCompletionOutputFunctionDefinition",
420
+ "ChatCompletionOutputLogprob",
421
+ "ChatCompletionOutputLogprobs",
422
+ "ChatCompletionOutputMessage",
423
+ "ChatCompletionOutputToolCall",
424
+ "ChatCompletionOutputTopLogprob",
425
+ "ChatCompletionOutputUsage",
426
+ "ChatCompletionStreamOutput",
427
+ "ChatCompletionStreamOutputChoice",
428
+ "ChatCompletionStreamOutputDelta",
429
+ "ChatCompletionStreamOutputDeltaToolCall",
430
+ "ChatCompletionStreamOutputFunction",
431
+ "ChatCompletionStreamOutputLogprob",
432
+ "ChatCompletionStreamOutputLogprobs",
433
+ "ChatCompletionStreamOutputTopLogprob",
434
+ "ChatCompletionStreamOutputUsage",
435
+ "DepthEstimationInput",
436
+ "DepthEstimationOutput",
437
+ "DocumentQuestionAnsweringInput",
438
+ "DocumentQuestionAnsweringInputData",
439
+ "DocumentQuestionAnsweringOutputElement",
440
+ "DocumentQuestionAnsweringParameters",
441
+ "FeatureExtractionInput",
442
+ "FeatureExtractionInputTruncationDirection",
443
+ "FillMaskInput",
444
+ "FillMaskOutputElement",
445
+ "FillMaskParameters",
446
+ "ImageClassificationInput",
447
+ "ImageClassificationOutputElement",
448
+ "ImageClassificationOutputTransform",
449
+ "ImageClassificationParameters",
450
+ "ImageSegmentationInput",
451
+ "ImageSegmentationOutputElement",
452
+ "ImageSegmentationParameters",
453
+ "ImageSegmentationSubtask",
454
+ "ImageTextToImageInput",
455
+ "ImageTextToImageOutput",
456
+ "ImageTextToImageParameters",
457
+ "ImageTextToImageTargetSize",
458
+ "ImageTextToVideoInput",
459
+ "ImageTextToVideoOutput",
460
+ "ImageTextToVideoParameters",
461
+ "ImageTextToVideoTargetSize",
462
+ "ImageToImageInput",
463
+ "ImageToImageOutput",
464
+ "ImageToImageParameters",
465
+ "ImageToImageTargetSize",
466
+ "ImageToTextEarlyStoppingEnum",
467
+ "ImageToTextGenerationParameters",
468
+ "ImageToTextInput",
469
+ "ImageToTextOutput",
470
+ "ImageToTextParameters",
471
+ "ImageToVideoInput",
472
+ "ImageToVideoOutput",
473
+ "ImageToVideoParameters",
474
+ "ImageToVideoTargetSize",
475
+ "ObjectDetectionBoundingBox",
476
+ "ObjectDetectionInput",
477
+ "ObjectDetectionOutputElement",
478
+ "ObjectDetectionParameters",
479
+ "Padding",
480
+ "QuestionAnsweringInput",
481
+ "QuestionAnsweringInputData",
482
+ "QuestionAnsweringOutputElement",
483
+ "QuestionAnsweringParameters",
484
+ "SentenceSimilarityInput",
485
+ "SentenceSimilarityInputData",
486
+ "SummarizationInput",
487
+ "SummarizationOutput",
488
+ "SummarizationParameters",
489
+ "SummarizationTruncationStrategy",
490
+ "TableQuestionAnsweringInput",
491
+ "TableQuestionAnsweringInputData",
492
+ "TableQuestionAnsweringOutputElement",
493
+ "TableQuestionAnsweringParameters",
494
+ "Text2TextGenerationInput",
495
+ "Text2TextGenerationOutput",
496
+ "Text2TextGenerationParameters",
497
+ "Text2TextGenerationTruncationStrategy",
498
+ "TextClassificationInput",
499
+ "TextClassificationOutputElement",
500
+ "TextClassificationOutputTransform",
501
+ "TextClassificationParameters",
502
+ "TextGenerationInput",
503
+ "TextGenerationInputGenerateParameters",
504
+ "TextGenerationInputGrammarType",
505
+ "TextGenerationOutput",
506
+ "TextGenerationOutputBestOfSequence",
507
+ "TextGenerationOutputDetails",
508
+ "TextGenerationOutputFinishReason",
509
+ "TextGenerationOutputPrefillToken",
510
+ "TextGenerationOutputToken",
511
+ "TextGenerationStreamOutput",
512
+ "TextGenerationStreamOutputStreamDetails",
513
+ "TextGenerationStreamOutputToken",
514
+ "TextToAudioEarlyStoppingEnum",
515
+ "TextToAudioGenerationParameters",
516
+ "TextToAudioInput",
517
+ "TextToAudioOutput",
518
+ "TextToAudioParameters",
519
+ "TextToImageInput",
520
+ "TextToImageOutput",
521
+ "TextToImageParameters",
522
+ "TextToSpeechEarlyStoppingEnum",
523
+ "TextToSpeechGenerationParameters",
524
+ "TextToSpeechInput",
525
+ "TextToSpeechOutput",
526
+ "TextToSpeechParameters",
527
+ "TextToVideoInput",
528
+ "TextToVideoOutput",
529
+ "TextToVideoParameters",
530
+ "TokenClassificationAggregationStrategy",
531
+ "TokenClassificationInput",
532
+ "TokenClassificationOutputElement",
533
+ "TokenClassificationParameters",
534
+ "TranslationInput",
535
+ "TranslationOutput",
536
+ "TranslationParameters",
537
+ "TranslationTruncationStrategy",
538
+ "TypeEnum",
539
+ "VideoClassificationInput",
540
+ "VideoClassificationOutputElement",
541
+ "VideoClassificationOutputTransform",
542
+ "VideoClassificationParameters",
543
+ "VisualQuestionAnsweringInput",
544
+ "VisualQuestionAnsweringInputData",
545
+ "VisualQuestionAnsweringOutputElement",
546
+ "VisualQuestionAnsweringParameters",
547
+ "ZeroShotClassificationInput",
548
+ "ZeroShotClassificationOutputElement",
549
+ "ZeroShotClassificationParameters",
550
+ "ZeroShotImageClassificationInput",
551
+ "ZeroShotImageClassificationOutputElement",
552
+ "ZeroShotImageClassificationParameters",
553
+ "ZeroShotObjectDetectionBoundingBox",
554
+ "ZeroShotObjectDetectionInput",
555
+ "ZeroShotObjectDetectionOutputElement",
556
+ "ZeroShotObjectDetectionParameters",
557
+ ],
558
+ "inference._mcp.agent": [
559
+ "Agent",
560
+ ],
561
+ "inference._mcp.mcp_client": [
562
+ "MCPClient",
563
+ ],
564
+ "repocard": [
565
+ "DatasetCard",
566
+ "ModelCard",
567
+ "RepoCard",
568
+ "SpaceCard",
569
+ "metadata_eval_result",
570
+ "metadata_load",
571
+ "metadata_save",
572
+ "metadata_update",
573
+ ],
574
+ "repocard_data": [
575
+ "CardData",
576
+ "DatasetCardData",
577
+ "EvalResult",
578
+ "ModelCardData",
579
+ "SpaceCardData",
580
+ ],
581
+ "serialization": [
582
+ "StateDictSplit",
583
+ "get_torch_storage_id",
584
+ "get_torch_storage_size",
585
+ "load_state_dict_from_file",
586
+ "load_torch_model",
587
+ "save_torch_model",
588
+ "save_torch_state_dict",
589
+ "split_state_dict_into_shards_factory",
590
+ "split_torch_state_dict_into_shards",
591
+ ],
592
+ "serialization._dduf": [
593
+ "DDUFEntry",
594
+ "export_entries_as_dduf",
595
+ "export_folder_as_dduf",
596
+ "read_dduf_file",
597
+ ],
598
+ "utils": [
599
+ "ASYNC_CLIENT_FACTORY_T",
600
+ "CLIENT_FACTORY_T",
601
+ "CacheNotFound",
602
+ "CachedFileInfo",
603
+ "CachedIncompleteFileInfo",
604
+ "CachedRepoInfo",
605
+ "CachedRevisionInfo",
606
+ "CorruptedCacheException",
607
+ "DeleteCacheStrategy",
608
+ "HFCacheInfo",
609
+ "HfUri",
610
+ "cached_assets_path",
611
+ "close_session",
612
+ "dump_environment_info",
613
+ "get_async_session",
614
+ "get_session",
615
+ "get_token",
616
+ "hf_raise_for_status",
617
+ "logging",
618
+ "parse_hf_uri",
619
+ "scan_cache_dir",
620
+ "set_async_client_factory",
621
+ "set_client_factory",
622
+ ],
623
+ }
624
+
625
+ # WARNING: __all__ is generated automatically, Any manual edit will be lost when re-generating this file !
626
+ #
627
+ # To update the static imports, please run the following command and commit the changes.
628
+ # ```
629
+ # # Use script
630
+ # python utils/check_all_variable.py --update
631
+ #
632
+ # # Or run style on codebase
633
+ # make style
634
+ # ```
635
+
636
+ __all__ = [
637
+ "ASYNC_CLIENT_FACTORY_T",
638
+ "Agent",
639
+ "AsyncInferenceClient",
640
+ "AudioClassificationInput",
641
+ "AudioClassificationOutputElement",
642
+ "AudioClassificationOutputTransform",
643
+ "AudioClassificationParameters",
644
+ "AudioToAudioInput",
645
+ "AudioToAudioOutputElement",
646
+ "AutomaticSpeechRecognitionEarlyStoppingEnum",
647
+ "AutomaticSpeechRecognitionGenerationParameters",
648
+ "AutomaticSpeechRecognitionInput",
649
+ "AutomaticSpeechRecognitionOutput",
650
+ "AutomaticSpeechRecognitionOutputChunk",
651
+ "AutomaticSpeechRecognitionParameters",
652
+ "BucketFile",
653
+ "BucketFileMetadata",
654
+ "BucketFolder",
655
+ "BucketInfo",
656
+ "BucketUrl",
657
+ "CLIENT_FACTORY_T",
658
+ "CONFIG_NAME",
659
+ "CacheNotFound",
660
+ "CachedFileInfo",
661
+ "CachedIncompleteFileInfo",
662
+ "CachedRepoInfo",
663
+ "CachedRevisionInfo",
664
+ "CardData",
665
+ "ChatCompletionInput",
666
+ "ChatCompletionInputFunctionDefinition",
667
+ "ChatCompletionInputFunctionName",
668
+ "ChatCompletionInputGrammarType",
669
+ "ChatCompletionInputJSONSchema",
670
+ "ChatCompletionInputMessage",
671
+ "ChatCompletionInputMessageChunk",
672
+ "ChatCompletionInputMessageChunkType",
673
+ "ChatCompletionInputResponseFormatJSONObject",
674
+ "ChatCompletionInputResponseFormatJSONSchema",
675
+ "ChatCompletionInputResponseFormatText",
676
+ "ChatCompletionInputStreamOptions",
677
+ "ChatCompletionInputTool",
678
+ "ChatCompletionInputToolCall",
679
+ "ChatCompletionInputToolChoiceClass",
680
+ "ChatCompletionInputToolChoiceEnum",
681
+ "ChatCompletionInputURL",
682
+ "ChatCompletionOutput",
683
+ "ChatCompletionOutputComplete",
684
+ "ChatCompletionOutputFunctionDefinition",
685
+ "ChatCompletionOutputLogprob",
686
+ "ChatCompletionOutputLogprobs",
687
+ "ChatCompletionOutputMessage",
688
+ "ChatCompletionOutputToolCall",
689
+ "ChatCompletionOutputTopLogprob",
690
+ "ChatCompletionOutputUsage",
691
+ "ChatCompletionStreamOutput",
692
+ "ChatCompletionStreamOutputChoice",
693
+ "ChatCompletionStreamOutputDelta",
694
+ "ChatCompletionStreamOutputDeltaToolCall",
695
+ "ChatCompletionStreamOutputFunction",
696
+ "ChatCompletionStreamOutputLogprob",
697
+ "ChatCompletionStreamOutputLogprobs",
698
+ "ChatCompletionStreamOutputTopLogprob",
699
+ "ChatCompletionStreamOutputUsage",
700
+ "Collection",
701
+ "CollectionItem",
702
+ "CommitInfo",
703
+ "CommitOperation",
704
+ "CommitOperationAdd",
705
+ "CommitOperationCopy",
706
+ "CommitOperationDelete",
707
+ "CommitScheduler",
708
+ "CorruptedCacheException",
709
+ "DDUFEntry",
710
+ "DatasetCard",
711
+ "DatasetCardData",
712
+ "DatasetInfo",
713
+ "DatasetLeaderboardEntry",
714
+ "DeleteCacheStrategy",
715
+ "DepthEstimationInput",
716
+ "DepthEstimationOutput",
717
+ "Discussion",
718
+ "DiscussionComment",
719
+ "DiscussionCommit",
720
+ "DiscussionEvent",
721
+ "DiscussionStatusChange",
722
+ "DiscussionTitleChange",
723
+ "DiscussionWithDetails",
724
+ "DocumentQuestionAnsweringInput",
725
+ "DocumentQuestionAnsweringInputData",
726
+ "DocumentQuestionAnsweringOutputElement",
727
+ "DocumentQuestionAnsweringParameters",
728
+ "DryRunFileInfo",
729
+ "EvalResult",
730
+ "EvalResultEntry",
731
+ "FLAX_WEIGHTS_NAME",
732
+ "FeatureExtractionInput",
733
+ "FeatureExtractionInputTruncationDirection",
734
+ "FillMaskInput",
735
+ "FillMaskOutputElement",
736
+ "FillMaskParameters",
737
+ "GitCommitInfo",
738
+ "GitRefInfo",
739
+ "GitRefs",
740
+ "HFCacheInfo",
741
+ "HFSummaryWriter",
742
+ "HUGGINGFACE_CO_URL_HOME",
743
+ "HUGGINGFACE_CO_URL_TEMPLATE",
744
+ "HfApi",
745
+ "HfFileMetadata",
746
+ "HfFileSystem",
747
+ "HfFileSystemFile",
748
+ "HfFileSystemResolvedPath",
749
+ "HfFileSystemStreamFile",
750
+ "HfUri",
751
+ "ImageClassificationInput",
752
+ "ImageClassificationOutputElement",
753
+ "ImageClassificationOutputTransform",
754
+ "ImageClassificationParameters",
755
+ "ImageSegmentationInput",
756
+ "ImageSegmentationOutputElement",
757
+ "ImageSegmentationParameters",
758
+ "ImageSegmentationSubtask",
759
+ "ImageTextToImageInput",
760
+ "ImageTextToImageOutput",
761
+ "ImageTextToImageParameters",
762
+ "ImageTextToImageTargetSize",
763
+ "ImageTextToVideoInput",
764
+ "ImageTextToVideoOutput",
765
+ "ImageTextToVideoParameters",
766
+ "ImageTextToVideoTargetSize",
767
+ "ImageToImageInput",
768
+ "ImageToImageOutput",
769
+ "ImageToImageParameters",
770
+ "ImageToImageTargetSize",
771
+ "ImageToTextEarlyStoppingEnum",
772
+ "ImageToTextGenerationParameters",
773
+ "ImageToTextInput",
774
+ "ImageToTextOutput",
775
+ "ImageToTextParameters",
776
+ "ImageToVideoInput",
777
+ "ImageToVideoOutput",
778
+ "ImageToVideoParameters",
779
+ "ImageToVideoTargetSize",
780
+ "InferenceClient",
781
+ "InferenceEndpoint",
782
+ "InferenceEndpointError",
783
+ "InferenceEndpointStatus",
784
+ "InferenceEndpointTimeoutError",
785
+ "InferenceEndpointType",
786
+ "InferenceTimeoutError",
787
+ "JobAccelerator",
788
+ "JobDurations",
789
+ "JobHardware",
790
+ "JobHardwareInfo",
791
+ "JobInfo",
792
+ "JobInitiator",
793
+ "JobOwner",
794
+ "JobStage",
795
+ "JobStatus",
796
+ "KernelInfo",
797
+ "MCPClient",
798
+ "ModelCard",
799
+ "ModelCardData",
800
+ "ModelHubMixin",
801
+ "ModelInfo",
802
+ "OAuthInfo",
803
+ "OAuthOrgInfo",
804
+ "OAuthUserInfo",
805
+ "ObjectDetectionBoundingBox",
806
+ "ObjectDetectionInput",
807
+ "ObjectDetectionOutputElement",
808
+ "ObjectDetectionParameters",
809
+ "Organization",
810
+ "PYTORCH_WEIGHTS_NAME",
811
+ "Padding",
812
+ "PyTorchModelHubMixin",
813
+ "QuestionAnsweringInput",
814
+ "QuestionAnsweringInputData",
815
+ "QuestionAnsweringOutputElement",
816
+ "QuestionAnsweringParameters",
817
+ "REPO_TYPE_DATASET",
818
+ "REPO_TYPE_MODEL",
819
+ "REPO_TYPE_SPACE",
820
+ "RepoCard",
821
+ "RepoFile",
822
+ "RepoFolder",
823
+ "RepoStorageInfo",
824
+ "RepoUrl",
825
+ "Sandbox",
826
+ "SandboxCommandResult",
827
+ "SandboxPool",
828
+ "SandboxProcess",
829
+ "SentenceSimilarityInput",
830
+ "SentenceSimilarityInputData",
831
+ "SpaceCard",
832
+ "SpaceCardData",
833
+ "SpaceHardware",
834
+ "SpaceInfo",
835
+ "SpaceRuntime",
836
+ "SpaceSearchResult",
837
+ "SpaceSecret",
838
+ "SpaceStage",
839
+ "SpaceStorage",
840
+ "SpaceTemplate",
841
+ "SpaceVariable",
842
+ "StateDictSplit",
843
+ "SummarizationInput",
844
+ "SummarizationOutput",
845
+ "SummarizationParameters",
846
+ "SummarizationTruncationStrategy",
847
+ "SyncOperation",
848
+ "SyncPlan",
849
+ "TF2_WEIGHTS_NAME",
850
+ "TF_WEIGHTS_NAME",
851
+ "TableQuestionAnsweringInput",
852
+ "TableQuestionAnsweringInputData",
853
+ "TableQuestionAnsweringOutputElement",
854
+ "TableQuestionAnsweringParameters",
855
+ "Text2TextGenerationInput",
856
+ "Text2TextGenerationOutput",
857
+ "Text2TextGenerationParameters",
858
+ "Text2TextGenerationTruncationStrategy",
859
+ "TextClassificationInput",
860
+ "TextClassificationOutputElement",
861
+ "TextClassificationOutputTransform",
862
+ "TextClassificationParameters",
863
+ "TextGenerationInput",
864
+ "TextGenerationInputGenerateParameters",
865
+ "TextGenerationInputGrammarType",
866
+ "TextGenerationOutput",
867
+ "TextGenerationOutputBestOfSequence",
868
+ "TextGenerationOutputDetails",
869
+ "TextGenerationOutputFinishReason",
870
+ "TextGenerationOutputPrefillToken",
871
+ "TextGenerationOutputToken",
872
+ "TextGenerationStreamOutput",
873
+ "TextGenerationStreamOutputStreamDetails",
874
+ "TextGenerationStreamOutputToken",
875
+ "TextToAudioEarlyStoppingEnum",
876
+ "TextToAudioGenerationParameters",
877
+ "TextToAudioInput",
878
+ "TextToAudioOutput",
879
+ "TextToAudioParameters",
880
+ "TextToImageInput",
881
+ "TextToImageOutput",
882
+ "TextToImageParameters",
883
+ "TextToSpeechEarlyStoppingEnum",
884
+ "TextToSpeechGenerationParameters",
885
+ "TextToSpeechInput",
886
+ "TextToSpeechOutput",
887
+ "TextToSpeechParameters",
888
+ "TextToVideoInput",
889
+ "TextToVideoOutput",
890
+ "TextToVideoParameters",
891
+ "TokenClassificationAggregationStrategy",
892
+ "TokenClassificationInput",
893
+ "TokenClassificationOutputElement",
894
+ "TokenClassificationParameters",
895
+ "TranslationInput",
896
+ "TranslationOutput",
897
+ "TranslationParameters",
898
+ "TranslationTruncationStrategy",
899
+ "TypeEnum",
900
+ "User",
901
+ "UserLikes",
902
+ "VideoClassificationInput",
903
+ "VideoClassificationOutputElement",
904
+ "VideoClassificationOutputTransform",
905
+ "VideoClassificationParameters",
906
+ "VisualQuestionAnsweringInput",
907
+ "VisualQuestionAnsweringInputData",
908
+ "VisualQuestionAnsweringOutputElement",
909
+ "VisualQuestionAnsweringParameters",
910
+ "Volume",
911
+ "WebhookInfo",
912
+ "WebhookPayload",
913
+ "WebhookPayloadComment",
914
+ "WebhookPayloadDiscussion",
915
+ "WebhookPayloadDiscussionChanges",
916
+ "WebhookPayloadEvent",
917
+ "WebhookPayloadMovedTo",
918
+ "WebhookPayloadRepo",
919
+ "WebhookPayloadUrl",
920
+ "WebhookPayloadWebhook",
921
+ "WebhookWatchedItem",
922
+ "WebhooksServer",
923
+ "ZeroShotClassificationInput",
924
+ "ZeroShotClassificationOutputElement",
925
+ "ZeroShotClassificationParameters",
926
+ "ZeroShotImageClassificationInput",
927
+ "ZeroShotImageClassificationOutputElement",
928
+ "ZeroShotImageClassificationParameters",
929
+ "ZeroShotObjectDetectionBoundingBox",
930
+ "ZeroShotObjectDetectionInput",
931
+ "ZeroShotObjectDetectionOutputElement",
932
+ "ZeroShotObjectDetectionParameters",
933
+ "_CACHED_NO_EXIST",
934
+ "_save_pretrained_fastai",
935
+ "accept_access_request",
936
+ "add_collection_item",
937
+ "add_space_secret",
938
+ "add_space_variable",
939
+ "attach_huggingface_oauth",
940
+ "auth_check",
941
+ "auth_list",
942
+ "auth_switch",
943
+ "batch_bucket_files",
944
+ "bucket_info",
945
+ "cached_assets_path",
946
+ "cancel_access_request",
947
+ "cancel_job",
948
+ "change_discussion_status",
949
+ "check_cli_update",
950
+ "close_session",
951
+ "comment_discussion",
952
+ "copy_files",
953
+ "create_branch",
954
+ "create_bucket",
955
+ "create_collection",
956
+ "create_commit",
957
+ "create_discussion",
958
+ "create_inference_endpoint",
959
+ "create_inference_endpoint_from_catalog",
960
+ "create_pull_request",
961
+ "create_repo",
962
+ "create_scheduled_job",
963
+ "create_scheduled_uv_job",
964
+ "create_tag",
965
+ "create_webhook",
966
+ "dataset_info",
967
+ "delete_branch",
968
+ "delete_bucket",
969
+ "delete_collection",
970
+ "delete_collection_item",
971
+ "delete_file",
972
+ "delete_folder",
973
+ "delete_inference_endpoint",
974
+ "delete_repo",
975
+ "delete_scheduled_job",
976
+ "delete_space_secret",
977
+ "delete_space_storage",
978
+ "delete_space_variable",
979
+ "delete_space_volumes",
980
+ "delete_tag",
981
+ "delete_webhook",
982
+ "disable_space_dev_mode",
983
+ "disable_webhook",
984
+ "download_bucket_files",
985
+ "dump_environment_info",
986
+ "duplicate_repo",
987
+ "duplicate_space",
988
+ "edit_discussion_comment",
989
+ "enable_space_dev_mode",
990
+ "enable_webhook",
991
+ "eval_result_entries_to_yaml",
992
+ "export_entries_as_dduf",
993
+ "export_folder_as_dduf",
994
+ "fetch_job_logs",
995
+ "fetch_job_metrics",
996
+ "fetch_space_logs",
997
+ "file_exists",
998
+ "from_pretrained_fastai",
999
+ "get_async_session",
1000
+ "get_bucket_file_metadata",
1001
+ "get_bucket_paths_info",
1002
+ "get_cached_repo_tree",
1003
+ "get_collection",
1004
+ "get_dataset_leaderboard",
1005
+ "get_dataset_tags",
1006
+ "get_discussion_details",
1007
+ "get_full_repo_name",
1008
+ "get_hf_file_metadata",
1009
+ "get_inference_endpoint",
1010
+ "get_local_safetensors_metadata",
1011
+ "get_model_tags",
1012
+ "get_organization_overview",
1013
+ "get_paths_info",
1014
+ "get_repo_discussions",
1015
+ "get_safetensors_metadata",
1016
+ "get_session",
1017
+ "get_space_runtime",
1018
+ "get_space_secrets",
1019
+ "get_space_variables",
1020
+ "get_token",
1021
+ "get_torch_storage_id",
1022
+ "get_torch_storage_size",
1023
+ "get_user_overview",
1024
+ "get_webhook",
1025
+ "grant_access",
1026
+ "hf_hub_download",
1027
+ "hf_hub_url",
1028
+ "hf_raise_for_status",
1029
+ "hffs",
1030
+ "inspect_job",
1031
+ "inspect_scheduled_job",
1032
+ "interpreter_login",
1033
+ "is_offline_mode",
1034
+ "kernel_info",
1035
+ "list_accepted_access_requests",
1036
+ "list_bucket_tree",
1037
+ "list_buckets",
1038
+ "list_collections",
1039
+ "list_daily_papers",
1040
+ "list_dataset_parquet_files",
1041
+ "list_datasets",
1042
+ "list_inference_catalog",
1043
+ "list_inference_endpoints",
1044
+ "list_jobs",
1045
+ "list_jobs_hardware",
1046
+ "list_lfs_files",
1047
+ "list_liked_repos",
1048
+ "list_models",
1049
+ "list_organization_followers",
1050
+ "list_organization_members",
1051
+ "list_papers",
1052
+ "list_pending_access_requests",
1053
+ "list_rejected_access_requests",
1054
+ "list_repo_commits",
1055
+ "list_repo_files",
1056
+ "list_repo_likers",
1057
+ "list_repo_refs",
1058
+ "list_repo_tree",
1059
+ "list_space_templates",
1060
+ "list_spaces",
1061
+ "list_spaces_hardware",
1062
+ "list_user_followers",
1063
+ "list_user_following",
1064
+ "list_user_repos",
1065
+ "list_webhooks",
1066
+ "load_state_dict_from_file",
1067
+ "load_torch_model",
1068
+ "logging",
1069
+ "login",
1070
+ "logout",
1071
+ "merge_pull_request",
1072
+ "metadata_eval_result",
1073
+ "metadata_load",
1074
+ "metadata_save",
1075
+ "metadata_update",
1076
+ "model_info",
1077
+ "move_bucket",
1078
+ "move_repo",
1079
+ "notebook_login",
1080
+ "paper_info",
1081
+ "parse_eval_result_entries",
1082
+ "parse_hf_uri",
1083
+ "parse_huggingface_oauth",
1084
+ "parse_local_safetensors_file_metadata",
1085
+ "parse_safetensors_file_metadata",
1086
+ "pause_inference_endpoint",
1087
+ "pause_space",
1088
+ "permanently_delete_lfs_files",
1089
+ "preupload_lfs_files",
1090
+ "push_to_hub_fastai",
1091
+ "read_dduf_file",
1092
+ "read_paper",
1093
+ "reject_access_request",
1094
+ "rename_discussion",
1095
+ "repo_exists",
1096
+ "repo_info",
1097
+ "repo_type_and_id_from_hf_id",
1098
+ "request_space_hardware",
1099
+ "request_space_storage",
1100
+ "restart_space",
1101
+ "resume_inference_endpoint",
1102
+ "resume_scheduled_job",
1103
+ "revision_exists",
1104
+ "run_as_future",
1105
+ "run_job",
1106
+ "run_uv_job",
1107
+ "save_torch_model",
1108
+ "save_torch_state_dict",
1109
+ "scale_to_zero_inference_endpoint",
1110
+ "scan_cache_dir",
1111
+ "search_spaces",
1112
+ "set_async_client_factory",
1113
+ "set_client_factory",
1114
+ "set_space_sleep_time",
1115
+ "set_space_volumes",
1116
+ "snapshot_download",
1117
+ "space_info",
1118
+ "split_state_dict_into_shards_factory",
1119
+ "split_torch_state_dict_into_shards",
1120
+ "super_squash_history",
1121
+ "suspend_scheduled_job",
1122
+ "sync_bucket",
1123
+ "sync_job_volume",
1124
+ "trigger_scheduled_job",
1125
+ "try_to_load_from_cache",
1126
+ "typer_factory",
1127
+ "unlike",
1128
+ "update_collection_item",
1129
+ "update_collection_metadata",
1130
+ "update_inference_endpoint",
1131
+ "update_job_labels",
1132
+ "update_repo_settings",
1133
+ "update_scheduled_job_labels",
1134
+ "update_webhook",
1135
+ "upload_file",
1136
+ "upload_folder",
1137
+ "upload_large_folder",
1138
+ "verify_repo_checksums",
1139
+ "wait_for_job",
1140
+ "wait_for_space",
1141
+ "webhook_endpoint",
1142
+ "whoami",
1143
+ ]
1144
+
1145
+
1146
+ def _attach(package_name, submodules=None, submod_attrs=None):
1147
+ """Attach lazily loaded submodules, functions, or other attributes.
1148
+
1149
+ Typically, modules import submodules and attributes as follows:
1150
+
1151
+ ```py
1152
+ import mysubmodule
1153
+ import anothersubmodule
1154
+
1155
+ from .foo import someattr
1156
+ ```
1157
+
1158
+ The idea is to replace a package's `__getattr__`, `__dir__`, such that all imports
1159
+ work exactly the way they would with normal imports, except that the import occurs
1160
+ upon first use.
1161
+
1162
+ The typical way to call this function, replacing the above imports, is:
1163
+
1164
+ ```python
1165
+ __getattr__, __dir__ = lazy.attach(
1166
+ __name__,
1167
+ ['mysubmodule', 'anothersubmodule'],
1168
+ {'foo': ['someattr']}
1169
+ )
1170
+ ```
1171
+ This functionality requires Python 3.7 or higher.
1172
+
1173
+ Args:
1174
+ package_name (`str`):
1175
+ Typically use `__name__`.
1176
+ submodules (`set`):
1177
+ List of submodules to attach.
1178
+ submod_attrs (`dict`):
1179
+ Dictionary of submodule -> list of attributes / functions.
1180
+ These attributes are imported as they are used.
1181
+
1182
+ Returns:
1183
+ __getattr__, __dir__, __all__
1184
+
1185
+ """
1186
+ if submod_attrs is None:
1187
+ submod_attrs = {}
1188
+
1189
+ if submodules is None:
1190
+ submodules = set()
1191
+ else:
1192
+ submodules = set(submodules)
1193
+
1194
+ attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}
1195
+
1196
+ def __getattr__(name):
1197
+ if name in submodules:
1198
+ try:
1199
+ return importlib.import_module(f"{package_name}.{name}")
1200
+ except Exception as e:
1201
+ print(f"Error importing {package_name}.{name}: {e}")
1202
+ raise
1203
+ elif name in attr_to_modules:
1204
+ submod_path = f"{package_name}.{attr_to_modules[name]}"
1205
+ try:
1206
+ submod = importlib.import_module(submod_path)
1207
+ except Exception as e:
1208
+ print(f"Error importing {submod_path}: {e}")
1209
+ raise
1210
+ attr = getattr(submod, name)
1211
+
1212
+ # If the attribute lives in a file (module) with the same
1213
+ # name as the attribute, ensure that the attribute and *not*
1214
+ # the module is accessible on the package.
1215
+ if name == attr_to_modules[name]:
1216
+ pkg = sys.modules[package_name]
1217
+ pkg.__dict__[name] = attr
1218
+
1219
+ return attr
1220
+ else:
1221
+ raise AttributeError(f"No {package_name} attribute {name}")
1222
+
1223
+ def __dir__():
1224
+ return __all__
1225
+
1226
+ return __getattr__, __dir__
1227
+
1228
+
1229
+ __getattr__, __dir__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)
1230
+
1231
+ if os.environ.get("EAGER_IMPORT", ""):
1232
+ for attr in __all__:
1233
+ __getattr__(attr)
1234
+
1235
+ # WARNING: any content below this statement is generated automatically. Any manual edit
1236
+ # will be lost when re-generating this file !
1237
+ #
1238
+ # To update the static imports, please run the following command and commit the changes.
1239
+ # ```
1240
+ # # Use script
1241
+ # python utils/check_static_imports.py --update
1242
+ #
1243
+ # # Or run style on codebase
1244
+ # make style
1245
+ # ```
1246
+ if TYPE_CHECKING: # pragma: no cover
1247
+ from ._buckets import (
1248
+ BucketFile, # noqa: F401
1249
+ BucketFileMetadata, # noqa: F401
1250
+ BucketFolder, # noqa: F401
1251
+ BucketInfo, # noqa: F401
1252
+ BucketUrl, # noqa: F401
1253
+ SyncOperation, # noqa: F401
1254
+ SyncPlan, # noqa: F401
1255
+ )
1256
+ from ._commit_scheduler import CommitScheduler # noqa: F401
1257
+ from ._eval_results import (
1258
+ EvalResultEntry, # noqa: F401
1259
+ eval_result_entries_to_yaml, # noqa: F401
1260
+ parse_eval_result_entries, # noqa: F401
1261
+ )
1262
+ from ._inference_endpoints import (
1263
+ InferenceEndpoint, # noqa: F401
1264
+ InferenceEndpointError, # noqa: F401
1265
+ InferenceEndpointStatus, # noqa: F401
1266
+ InferenceEndpointTimeoutError, # noqa: F401
1267
+ InferenceEndpointType, # noqa: F401
1268
+ )
1269
+ from ._jobs_api import (
1270
+ JobAccelerator, # noqa: F401
1271
+ JobDurations, # noqa: F401
1272
+ JobHardware, # noqa: F401
1273
+ JobHardwareInfo, # noqa: F401
1274
+ JobInfo, # noqa: F401
1275
+ JobInitiator, # noqa: F401
1276
+ JobOwner, # noqa: F401
1277
+ JobStage, # noqa: F401
1278
+ JobStatus, # noqa: F401
1279
+ )
1280
+ from ._login import (
1281
+ auth_list, # noqa: F401
1282
+ auth_switch, # noqa: F401
1283
+ interpreter_login, # noqa: F401
1284
+ login, # noqa: F401
1285
+ logout, # noqa: F401
1286
+ notebook_login, # noqa: F401
1287
+ )
1288
+ from ._oauth import (
1289
+ OAuthInfo, # noqa: F401
1290
+ OAuthOrgInfo, # noqa: F401
1291
+ OAuthUserInfo, # noqa: F401
1292
+ attach_huggingface_oauth, # noqa: F401
1293
+ parse_huggingface_oauth, # noqa: F401
1294
+ )
1295
+ from ._sandbox import (
1296
+ Sandbox, # noqa: F401
1297
+ SandboxCommandResult, # noqa: F401
1298
+ SandboxPool, # noqa: F401
1299
+ SandboxProcess, # noqa: F401
1300
+ )
1301
+ from ._snapshot_download import (
1302
+ get_cached_repo_tree, # noqa: F401
1303
+ snapshot_download, # noqa: F401
1304
+ )
1305
+ from ._space_api import (
1306
+ SpaceHardware, # noqa: F401
1307
+ SpaceRuntime, # noqa: F401
1308
+ SpaceSecret, # noqa: F401
1309
+ SpaceStage, # noqa: F401
1310
+ SpaceStorage, # noqa: F401
1311
+ SpaceVariable, # noqa: F401
1312
+ Volume, # noqa: F401
1313
+ )
1314
+ from ._tensorboard_logger import HFSummaryWriter # noqa: F401
1315
+ from ._webhooks_payload import (
1316
+ WebhookPayload, # noqa: F401
1317
+ WebhookPayloadComment, # noqa: F401
1318
+ WebhookPayloadDiscussion, # noqa: F401
1319
+ WebhookPayloadDiscussionChanges, # noqa: F401
1320
+ WebhookPayloadEvent, # noqa: F401
1321
+ WebhookPayloadMovedTo, # noqa: F401
1322
+ WebhookPayloadRepo, # noqa: F401
1323
+ WebhookPayloadUrl, # noqa: F401
1324
+ WebhookPayloadWebhook, # noqa: F401
1325
+ )
1326
+ from ._webhooks_server import (
1327
+ WebhooksServer, # noqa: F401
1328
+ webhook_endpoint, # noqa: F401
1329
+ )
1330
+ from .cli._cli_utils import (
1331
+ check_cli_update, # noqa: F401
1332
+ typer_factory, # noqa: F401
1333
+ )
1334
+ from .community import (
1335
+ Discussion, # noqa: F401
1336
+ DiscussionComment, # noqa: F401
1337
+ DiscussionCommit, # noqa: F401
1338
+ DiscussionEvent, # noqa: F401
1339
+ DiscussionStatusChange, # noqa: F401
1340
+ DiscussionTitleChange, # noqa: F401
1341
+ DiscussionWithDetails, # noqa: F401
1342
+ )
1343
+ from .constants import (
1344
+ CONFIG_NAME, # noqa: F401
1345
+ FLAX_WEIGHTS_NAME, # noqa: F401
1346
+ HUGGINGFACE_CO_URL_HOME, # noqa: F401
1347
+ HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401
1348
+ PYTORCH_WEIGHTS_NAME, # noqa: F401
1349
+ REPO_TYPE_DATASET, # noqa: F401
1350
+ REPO_TYPE_MODEL, # noqa: F401
1351
+ REPO_TYPE_SPACE, # noqa: F401
1352
+ TF2_WEIGHTS_NAME, # noqa: F401
1353
+ TF_WEIGHTS_NAME, # noqa: F401
1354
+ is_offline_mode, # noqa: F401
1355
+ )
1356
+ from .fastai_utils import (
1357
+ _save_pretrained_fastai, # noqa: F401
1358
+ from_pretrained_fastai, # noqa: F401
1359
+ push_to_hub_fastai, # noqa: F401
1360
+ )
1361
+ from .file_download import (
1362
+ _CACHED_NO_EXIST, # noqa: F401
1363
+ DryRunFileInfo, # noqa: F401
1364
+ HfFileMetadata, # noqa: F401
1365
+ get_hf_file_metadata, # noqa: F401
1366
+ hf_hub_download, # noqa: F401
1367
+ hf_hub_url, # noqa: F401
1368
+ try_to_load_from_cache, # noqa: F401
1369
+ )
1370
+ from .hf_api import (
1371
+ Collection, # noqa: F401
1372
+ CollectionItem, # noqa: F401
1373
+ CommitInfo, # noqa: F401
1374
+ CommitOperation, # noqa: F401
1375
+ CommitOperationAdd, # noqa: F401
1376
+ CommitOperationCopy, # noqa: F401
1377
+ CommitOperationDelete, # noqa: F401
1378
+ DatasetInfo, # noqa: F401
1379
+ DatasetLeaderboardEntry, # noqa: F401
1380
+ GitCommitInfo, # noqa: F401
1381
+ GitRefInfo, # noqa: F401
1382
+ GitRefs, # noqa: F401
1383
+ HfApi, # noqa: F401
1384
+ KernelInfo, # noqa: F401
1385
+ ModelInfo, # noqa: F401
1386
+ Organization, # noqa: F401
1387
+ RepoFile, # noqa: F401
1388
+ RepoFolder, # noqa: F401
1389
+ RepoStorageInfo, # noqa: F401
1390
+ RepoUrl, # noqa: F401
1391
+ SpaceInfo, # noqa: F401
1392
+ SpaceSearchResult, # noqa: F401
1393
+ SpaceTemplate, # noqa: F401
1394
+ User, # noqa: F401
1395
+ UserLikes, # noqa: F401
1396
+ WebhookInfo, # noqa: F401
1397
+ WebhookWatchedItem, # noqa: F401
1398
+ accept_access_request, # noqa: F401
1399
+ add_collection_item, # noqa: F401
1400
+ add_space_secret, # noqa: F401
1401
+ add_space_variable, # noqa: F401
1402
+ auth_check, # noqa: F401
1403
+ batch_bucket_files, # noqa: F401
1404
+ bucket_info, # noqa: F401
1405
+ cancel_access_request, # noqa: F401
1406
+ cancel_job, # noqa: F401
1407
+ change_discussion_status, # noqa: F401
1408
+ comment_discussion, # noqa: F401
1409
+ copy_files, # noqa: F401
1410
+ create_branch, # noqa: F401
1411
+ create_bucket, # noqa: F401
1412
+ create_collection, # noqa: F401
1413
+ create_commit, # noqa: F401
1414
+ create_discussion, # noqa: F401
1415
+ create_inference_endpoint, # noqa: F401
1416
+ create_inference_endpoint_from_catalog, # noqa: F401
1417
+ create_pull_request, # noqa: F401
1418
+ create_repo, # noqa: F401
1419
+ create_scheduled_job, # noqa: F401
1420
+ create_scheduled_uv_job, # noqa: F401
1421
+ create_tag, # noqa: F401
1422
+ create_webhook, # noqa: F401
1423
+ dataset_info, # noqa: F401
1424
+ delete_branch, # noqa: F401
1425
+ delete_bucket, # noqa: F401
1426
+ delete_collection, # noqa: F401
1427
+ delete_collection_item, # noqa: F401
1428
+ delete_file, # noqa: F401
1429
+ delete_folder, # noqa: F401
1430
+ delete_inference_endpoint, # noqa: F401
1431
+ delete_repo, # noqa: F401
1432
+ delete_scheduled_job, # noqa: F401
1433
+ delete_space_secret, # noqa: F401
1434
+ delete_space_storage, # noqa: F401
1435
+ delete_space_variable, # noqa: F401
1436
+ delete_space_volumes, # noqa: F401
1437
+ delete_tag, # noqa: F401
1438
+ delete_webhook, # noqa: F401
1439
+ disable_space_dev_mode, # noqa: F401
1440
+ disable_webhook, # noqa: F401
1441
+ download_bucket_files, # noqa: F401
1442
+ duplicate_repo, # noqa: F401
1443
+ duplicate_space, # noqa: F401
1444
+ edit_discussion_comment, # noqa: F401
1445
+ enable_space_dev_mode, # noqa: F401
1446
+ enable_webhook, # noqa: F401
1447
+ fetch_job_logs, # noqa: F401
1448
+ fetch_job_metrics, # noqa: F401
1449
+ fetch_space_logs, # noqa: F401
1450
+ file_exists, # noqa: F401
1451
+ get_bucket_file_metadata, # noqa: F401
1452
+ get_bucket_paths_info, # noqa: F401
1453
+ get_collection, # noqa: F401
1454
+ get_dataset_leaderboard, # noqa: F401
1455
+ get_dataset_tags, # noqa: F401
1456
+ get_discussion_details, # noqa: F401
1457
+ get_full_repo_name, # noqa: F401
1458
+ get_inference_endpoint, # noqa: F401
1459
+ get_local_safetensors_metadata, # noqa: F401
1460
+ get_model_tags, # noqa: F401
1461
+ get_organization_overview, # noqa: F401
1462
+ get_paths_info, # noqa: F401
1463
+ get_repo_discussions, # noqa: F401
1464
+ get_safetensors_metadata, # noqa: F401
1465
+ get_space_runtime, # noqa: F401
1466
+ get_space_secrets, # noqa: F401
1467
+ get_space_variables, # noqa: F401
1468
+ get_user_overview, # noqa: F401
1469
+ get_webhook, # noqa: F401
1470
+ grant_access, # noqa: F401
1471
+ inspect_job, # noqa: F401
1472
+ inspect_scheduled_job, # noqa: F401
1473
+ kernel_info, # noqa: F401
1474
+ list_accepted_access_requests, # noqa: F401
1475
+ list_bucket_tree, # noqa: F401
1476
+ list_buckets, # noqa: F401
1477
+ list_collections, # noqa: F401
1478
+ list_daily_papers, # noqa: F401
1479
+ list_dataset_parquet_files, # noqa: F401
1480
+ list_datasets, # noqa: F401
1481
+ list_inference_catalog, # noqa: F401
1482
+ list_inference_endpoints, # noqa: F401
1483
+ list_jobs, # noqa: F401
1484
+ list_jobs_hardware, # noqa: F401
1485
+ list_lfs_files, # noqa: F401
1486
+ list_liked_repos, # noqa: F401
1487
+ list_models, # noqa: F401
1488
+ list_organization_followers, # noqa: F401
1489
+ list_organization_members, # noqa: F401
1490
+ list_papers, # noqa: F401
1491
+ list_pending_access_requests, # noqa: F401
1492
+ list_rejected_access_requests, # noqa: F401
1493
+ list_repo_commits, # noqa: F401
1494
+ list_repo_files, # noqa: F401
1495
+ list_repo_likers, # noqa: F401
1496
+ list_repo_refs, # noqa: F401
1497
+ list_repo_tree, # noqa: F401
1498
+ list_space_templates, # noqa: F401
1499
+ list_spaces, # noqa: F401
1500
+ list_spaces_hardware, # noqa: F401
1501
+ list_user_followers, # noqa: F401
1502
+ list_user_following, # noqa: F401
1503
+ list_user_repos, # noqa: F401
1504
+ list_webhooks, # noqa: F401
1505
+ merge_pull_request, # noqa: F401
1506
+ model_info, # noqa: F401
1507
+ move_bucket, # noqa: F401
1508
+ move_repo, # noqa: F401
1509
+ paper_info, # noqa: F401
1510
+ parse_local_safetensors_file_metadata, # noqa: F401
1511
+ parse_safetensors_file_metadata, # noqa: F401
1512
+ pause_inference_endpoint, # noqa: F401
1513
+ pause_space, # noqa: F401
1514
+ permanently_delete_lfs_files, # noqa: F401
1515
+ preupload_lfs_files, # noqa: F401
1516
+ read_paper, # noqa: F401
1517
+ reject_access_request, # noqa: F401
1518
+ rename_discussion, # noqa: F401
1519
+ repo_exists, # noqa: F401
1520
+ repo_info, # noqa: F401
1521
+ repo_type_and_id_from_hf_id, # noqa: F401
1522
+ request_space_hardware, # noqa: F401
1523
+ request_space_storage, # noqa: F401
1524
+ restart_space, # noqa: F401
1525
+ resume_inference_endpoint, # noqa: F401
1526
+ resume_scheduled_job, # noqa: F401
1527
+ revision_exists, # noqa: F401
1528
+ run_as_future, # noqa: F401
1529
+ run_job, # noqa: F401
1530
+ run_uv_job, # noqa: F401
1531
+ scale_to_zero_inference_endpoint, # noqa: F401
1532
+ search_spaces, # noqa: F401
1533
+ set_space_sleep_time, # noqa: F401
1534
+ set_space_volumes, # noqa: F401
1535
+ space_info, # noqa: F401
1536
+ super_squash_history, # noqa: F401
1537
+ suspend_scheduled_job, # noqa: F401
1538
+ sync_bucket, # noqa: F401
1539
+ sync_job_volume, # noqa: F401
1540
+ trigger_scheduled_job, # noqa: F401
1541
+ unlike, # noqa: F401
1542
+ update_collection_item, # noqa: F401
1543
+ update_collection_metadata, # noqa: F401
1544
+ update_inference_endpoint, # noqa: F401
1545
+ update_job_labels, # noqa: F401
1546
+ update_repo_settings, # noqa: F401
1547
+ update_scheduled_job_labels, # noqa: F401
1548
+ update_webhook, # noqa: F401
1549
+ upload_file, # noqa: F401
1550
+ upload_folder, # noqa: F401
1551
+ upload_large_folder, # noqa: F401
1552
+ verify_repo_checksums, # noqa: F401
1553
+ wait_for_job, # noqa: F401
1554
+ wait_for_space, # noqa: F401
1555
+ whoami, # noqa: F401
1556
+ )
1557
+ from .hf_file_system import (
1558
+ HfFileSystem, # noqa: F401
1559
+ HfFileSystemFile, # noqa: F401
1560
+ HfFileSystemResolvedPath, # noqa: F401
1561
+ HfFileSystemStreamFile, # noqa: F401
1562
+ hffs, # noqa: F401
1563
+ )
1564
+ from .hub_mixin import (
1565
+ ModelHubMixin, # noqa: F401
1566
+ PyTorchModelHubMixin, # noqa: F401
1567
+ )
1568
+ from .inference._client import (
1569
+ InferenceClient, # noqa: F401
1570
+ InferenceTimeoutError, # noqa: F401
1571
+ )
1572
+ from .inference._generated._async_client import AsyncInferenceClient # noqa: F401
1573
+ from .inference._generated.types import (
1574
+ AudioClassificationInput, # noqa: F401
1575
+ AudioClassificationOutputElement, # noqa: F401
1576
+ AudioClassificationOutputTransform, # noqa: F401
1577
+ AudioClassificationParameters, # noqa: F401
1578
+ AudioToAudioInput, # noqa: F401
1579
+ AudioToAudioOutputElement, # noqa: F401
1580
+ AutomaticSpeechRecognitionEarlyStoppingEnum, # noqa: F401
1581
+ AutomaticSpeechRecognitionGenerationParameters, # noqa: F401
1582
+ AutomaticSpeechRecognitionInput, # noqa: F401
1583
+ AutomaticSpeechRecognitionOutput, # noqa: F401
1584
+ AutomaticSpeechRecognitionOutputChunk, # noqa: F401
1585
+ AutomaticSpeechRecognitionParameters, # noqa: F401
1586
+ ChatCompletionInput, # noqa: F401
1587
+ ChatCompletionInputFunctionDefinition, # noqa: F401
1588
+ ChatCompletionInputFunctionName, # noqa: F401
1589
+ ChatCompletionInputGrammarType, # noqa: F401
1590
+ ChatCompletionInputJSONSchema, # noqa: F401
1591
+ ChatCompletionInputMessage, # noqa: F401
1592
+ ChatCompletionInputMessageChunk, # noqa: F401
1593
+ ChatCompletionInputMessageChunkType, # noqa: F401
1594
+ ChatCompletionInputResponseFormatJSONObject, # noqa: F401
1595
+ ChatCompletionInputResponseFormatJSONSchema, # noqa: F401
1596
+ ChatCompletionInputResponseFormatText, # noqa: F401
1597
+ ChatCompletionInputStreamOptions, # noqa: F401
1598
+ ChatCompletionInputTool, # noqa: F401
1599
+ ChatCompletionInputToolCall, # noqa: F401
1600
+ ChatCompletionInputToolChoiceClass, # noqa: F401
1601
+ ChatCompletionInputToolChoiceEnum, # noqa: F401
1602
+ ChatCompletionInputURL, # noqa: F401
1603
+ ChatCompletionOutput, # noqa: F401
1604
+ ChatCompletionOutputComplete, # noqa: F401
1605
+ ChatCompletionOutputFunctionDefinition, # noqa: F401
1606
+ ChatCompletionOutputLogprob, # noqa: F401
1607
+ ChatCompletionOutputLogprobs, # noqa: F401
1608
+ ChatCompletionOutputMessage, # noqa: F401
1609
+ ChatCompletionOutputToolCall, # noqa: F401
1610
+ ChatCompletionOutputTopLogprob, # noqa: F401
1611
+ ChatCompletionOutputUsage, # noqa: F401
1612
+ ChatCompletionStreamOutput, # noqa: F401
1613
+ ChatCompletionStreamOutputChoice, # noqa: F401
1614
+ ChatCompletionStreamOutputDelta, # noqa: F401
1615
+ ChatCompletionStreamOutputDeltaToolCall, # noqa: F401
1616
+ ChatCompletionStreamOutputFunction, # noqa: F401
1617
+ ChatCompletionStreamOutputLogprob, # noqa: F401
1618
+ ChatCompletionStreamOutputLogprobs, # noqa: F401
1619
+ ChatCompletionStreamOutputTopLogprob, # noqa: F401
1620
+ ChatCompletionStreamOutputUsage, # noqa: F401
1621
+ DepthEstimationInput, # noqa: F401
1622
+ DepthEstimationOutput, # noqa: F401
1623
+ DocumentQuestionAnsweringInput, # noqa: F401
1624
+ DocumentQuestionAnsweringInputData, # noqa: F401
1625
+ DocumentQuestionAnsweringOutputElement, # noqa: F401
1626
+ DocumentQuestionAnsweringParameters, # noqa: F401
1627
+ FeatureExtractionInput, # noqa: F401
1628
+ FeatureExtractionInputTruncationDirection, # noqa: F401
1629
+ FillMaskInput, # noqa: F401
1630
+ FillMaskOutputElement, # noqa: F401
1631
+ FillMaskParameters, # noqa: F401
1632
+ ImageClassificationInput, # noqa: F401
1633
+ ImageClassificationOutputElement, # noqa: F401
1634
+ ImageClassificationOutputTransform, # noqa: F401
1635
+ ImageClassificationParameters, # noqa: F401
1636
+ ImageSegmentationInput, # noqa: F401
1637
+ ImageSegmentationOutputElement, # noqa: F401
1638
+ ImageSegmentationParameters, # noqa: F401
1639
+ ImageSegmentationSubtask, # noqa: F401
1640
+ ImageTextToImageInput, # noqa: F401
1641
+ ImageTextToImageOutput, # noqa: F401
1642
+ ImageTextToImageParameters, # noqa: F401
1643
+ ImageTextToImageTargetSize, # noqa: F401
1644
+ ImageTextToVideoInput, # noqa: F401
1645
+ ImageTextToVideoOutput, # noqa: F401
1646
+ ImageTextToVideoParameters, # noqa: F401
1647
+ ImageTextToVideoTargetSize, # noqa: F401
1648
+ ImageToImageInput, # noqa: F401
1649
+ ImageToImageOutput, # noqa: F401
1650
+ ImageToImageParameters, # noqa: F401
1651
+ ImageToImageTargetSize, # noqa: F401
1652
+ ImageToTextEarlyStoppingEnum, # noqa: F401
1653
+ ImageToTextGenerationParameters, # noqa: F401
1654
+ ImageToTextInput, # noqa: F401
1655
+ ImageToTextOutput, # noqa: F401
1656
+ ImageToTextParameters, # noqa: F401
1657
+ ImageToVideoInput, # noqa: F401
1658
+ ImageToVideoOutput, # noqa: F401
1659
+ ImageToVideoParameters, # noqa: F401
1660
+ ImageToVideoTargetSize, # noqa: F401
1661
+ ObjectDetectionBoundingBox, # noqa: F401
1662
+ ObjectDetectionInput, # noqa: F401
1663
+ ObjectDetectionOutputElement, # noqa: F401
1664
+ ObjectDetectionParameters, # noqa: F401
1665
+ Padding, # noqa: F401
1666
+ QuestionAnsweringInput, # noqa: F401
1667
+ QuestionAnsweringInputData, # noqa: F401
1668
+ QuestionAnsweringOutputElement, # noqa: F401
1669
+ QuestionAnsweringParameters, # noqa: F401
1670
+ SentenceSimilarityInput, # noqa: F401
1671
+ SentenceSimilarityInputData, # noqa: F401
1672
+ SummarizationInput, # noqa: F401
1673
+ SummarizationOutput, # noqa: F401
1674
+ SummarizationParameters, # noqa: F401
1675
+ SummarizationTruncationStrategy, # noqa: F401
1676
+ TableQuestionAnsweringInput, # noqa: F401
1677
+ TableQuestionAnsweringInputData, # noqa: F401
1678
+ TableQuestionAnsweringOutputElement, # noqa: F401
1679
+ TableQuestionAnsweringParameters, # noqa: F401
1680
+ Text2TextGenerationInput, # noqa: F401
1681
+ Text2TextGenerationOutput, # noqa: F401
1682
+ Text2TextGenerationParameters, # noqa: F401
1683
+ Text2TextGenerationTruncationStrategy, # noqa: F401
1684
+ TextClassificationInput, # noqa: F401
1685
+ TextClassificationOutputElement, # noqa: F401
1686
+ TextClassificationOutputTransform, # noqa: F401
1687
+ TextClassificationParameters, # noqa: F401
1688
+ TextGenerationInput, # noqa: F401
1689
+ TextGenerationInputGenerateParameters, # noqa: F401
1690
+ TextGenerationInputGrammarType, # noqa: F401
1691
+ TextGenerationOutput, # noqa: F401
1692
+ TextGenerationOutputBestOfSequence, # noqa: F401
1693
+ TextGenerationOutputDetails, # noqa: F401
1694
+ TextGenerationOutputFinishReason, # noqa: F401
1695
+ TextGenerationOutputPrefillToken, # noqa: F401
1696
+ TextGenerationOutputToken, # noqa: F401
1697
+ TextGenerationStreamOutput, # noqa: F401
1698
+ TextGenerationStreamOutputStreamDetails, # noqa: F401
1699
+ TextGenerationStreamOutputToken, # noqa: F401
1700
+ TextToAudioEarlyStoppingEnum, # noqa: F401
1701
+ TextToAudioGenerationParameters, # noqa: F401
1702
+ TextToAudioInput, # noqa: F401
1703
+ TextToAudioOutput, # noqa: F401
1704
+ TextToAudioParameters, # noqa: F401
1705
+ TextToImageInput, # noqa: F401
1706
+ TextToImageOutput, # noqa: F401
1707
+ TextToImageParameters, # noqa: F401
1708
+ TextToSpeechEarlyStoppingEnum, # noqa: F401
1709
+ TextToSpeechGenerationParameters, # noqa: F401
1710
+ TextToSpeechInput, # noqa: F401
1711
+ TextToSpeechOutput, # noqa: F401
1712
+ TextToSpeechParameters, # noqa: F401
1713
+ TextToVideoInput, # noqa: F401
1714
+ TextToVideoOutput, # noqa: F401
1715
+ TextToVideoParameters, # noqa: F401
1716
+ TokenClassificationAggregationStrategy, # noqa: F401
1717
+ TokenClassificationInput, # noqa: F401
1718
+ TokenClassificationOutputElement, # noqa: F401
1719
+ TokenClassificationParameters, # noqa: F401
1720
+ TranslationInput, # noqa: F401
1721
+ TranslationOutput, # noqa: F401
1722
+ TranslationParameters, # noqa: F401
1723
+ TranslationTruncationStrategy, # noqa: F401
1724
+ TypeEnum, # noqa: F401
1725
+ VideoClassificationInput, # noqa: F401
1726
+ VideoClassificationOutputElement, # noqa: F401
1727
+ VideoClassificationOutputTransform, # noqa: F401
1728
+ VideoClassificationParameters, # noqa: F401
1729
+ VisualQuestionAnsweringInput, # noqa: F401
1730
+ VisualQuestionAnsweringInputData, # noqa: F401
1731
+ VisualQuestionAnsweringOutputElement, # noqa: F401
1732
+ VisualQuestionAnsweringParameters, # noqa: F401
1733
+ ZeroShotClassificationInput, # noqa: F401
1734
+ ZeroShotClassificationOutputElement, # noqa: F401
1735
+ ZeroShotClassificationParameters, # noqa: F401
1736
+ ZeroShotImageClassificationInput, # noqa: F401
1737
+ ZeroShotImageClassificationOutputElement, # noqa: F401
1738
+ ZeroShotImageClassificationParameters, # noqa: F401
1739
+ ZeroShotObjectDetectionBoundingBox, # noqa: F401
1740
+ ZeroShotObjectDetectionInput, # noqa: F401
1741
+ ZeroShotObjectDetectionOutputElement, # noqa: F401
1742
+ ZeroShotObjectDetectionParameters, # noqa: F401
1743
+ )
1744
+ from .inference._mcp.agent import Agent # noqa: F401
1745
+ from .inference._mcp.mcp_client import MCPClient # noqa: F401
1746
+ from .repocard import (
1747
+ DatasetCard, # noqa: F401
1748
+ ModelCard, # noqa: F401
1749
+ RepoCard, # noqa: F401
1750
+ SpaceCard, # noqa: F401
1751
+ metadata_eval_result, # noqa: F401
1752
+ metadata_load, # noqa: F401
1753
+ metadata_save, # noqa: F401
1754
+ metadata_update, # noqa: F401
1755
+ )
1756
+ from .repocard_data import (
1757
+ CardData, # noqa: F401
1758
+ DatasetCardData, # noqa: F401
1759
+ EvalResult, # noqa: F401
1760
+ ModelCardData, # noqa: F401
1761
+ SpaceCardData, # noqa: F401
1762
+ )
1763
+ from .serialization import (
1764
+ StateDictSplit, # noqa: F401
1765
+ get_torch_storage_id, # noqa: F401
1766
+ get_torch_storage_size, # noqa: F401
1767
+ load_state_dict_from_file, # noqa: F401
1768
+ load_torch_model, # noqa: F401
1769
+ save_torch_model, # noqa: F401
1770
+ save_torch_state_dict, # noqa: F401
1771
+ split_state_dict_into_shards_factory, # noqa: F401
1772
+ split_torch_state_dict_into_shards, # noqa: F401
1773
+ )
1774
+ from .serialization._dduf import (
1775
+ DDUFEntry, # noqa: F401
1776
+ export_entries_as_dduf, # noqa: F401
1777
+ export_folder_as_dduf, # noqa: F401
1778
+ read_dduf_file, # noqa: F401
1779
+ )
1780
+ from .utils import (
1781
+ ASYNC_CLIENT_FACTORY_T, # noqa: F401
1782
+ CLIENT_FACTORY_T, # noqa: F401
1783
+ CachedFileInfo, # noqa: F401
1784
+ CachedIncompleteFileInfo, # noqa: F401
1785
+ CachedRepoInfo, # noqa: F401
1786
+ CachedRevisionInfo, # noqa: F401
1787
+ CacheNotFound, # noqa: F401
1788
+ CorruptedCacheException, # noqa: F401
1789
+ DeleteCacheStrategy, # noqa: F401
1790
+ HFCacheInfo, # noqa: F401
1791
+ HfUri, # noqa: F401
1792
+ cached_assets_path, # noqa: F401
1793
+ close_session, # noqa: F401
1794
+ dump_environment_info, # noqa: F401
1795
+ get_async_session, # noqa: F401
1796
+ get_session, # noqa: F401
1797
+ get_token, # noqa: F401
1798
+ hf_raise_for_status, # noqa: F401
1799
+ logging, # noqa: F401
1800
+ parse_hf_uri, # noqa: F401
1801
+ scan_cache_dir, # noqa: F401
1802
+ set_async_client_factory, # noqa: F401
1803
+ set_client_factory, # noqa: F401
1804
+ )
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_buckets.py ADDED
@@ -0,0 +1,1244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Shared logic for bucket operations.
15
+
16
+ This module contains the core buckets logic used by both the CLI and the Python API.
17
+ """
18
+
19
+ import fnmatch
20
+ import json
21
+ import mimetypes
22
+ import os
23
+ import stat
24
+ import sys
25
+ import time
26
+ from collections.abc import Iterator
27
+ from dataclasses import dataclass, field
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+ from typing import TYPE_CHECKING, Any, Literal
31
+
32
+ from . import constants, logging
33
+ from .errors import BucketNotFoundError
34
+ from .utils import (
35
+ HfUri,
36
+ StatusLine,
37
+ XetFileData,
38
+ disable_progress_bars,
39
+ enable_progress_bars,
40
+ parse_datetime,
41
+ parse_hf_uri,
42
+ )
43
+ from .utils._hf_uris import _looks_like_hf_url
44
+
45
+
46
+ if TYPE_CHECKING:
47
+ from .hf_api import HfApi
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+
53
+ BUCKET_PREFIX = "hf://buckets/"
54
+ _SYNC_TIME_WINDOW_MS = 1000 # 1s safety-window for file modification time comparisons
55
+
56
+
57
+ # =============================================================================
58
+ # Bucket data structures
59
+ # =============================================================================
60
+
61
+
62
+ @dataclass
63
+ class BucketInfo:
64
+ """
65
+ Contains information about a bucket on the Hub. This object is returned by [`bucket_info`] and [`list_buckets`].
66
+
67
+ Attributes:
68
+ id (`str`):
69
+ ID of the bucket.
70
+ private (`bool`):
71
+ Is the bucket private.
72
+ created_at (`datetime`):
73
+ Date of creation of the bucket on the Hub.
74
+ size (`int`):
75
+ Size of the bucket in bytes.
76
+ total_files (`int`):
77
+ Total number of files in the bucket.
78
+ """
79
+
80
+ id: str
81
+ private: bool
82
+ created_at: datetime
83
+ size: int
84
+ total_files: int
85
+
86
+ def __init__(self, **kwargs):
87
+ self.id = kwargs.pop("id")
88
+ self.private = kwargs.pop("private")
89
+ self.created_at = parse_datetime(kwargs.pop("createdAt"))
90
+ self.size = kwargs.pop("size")
91
+ self.total_files = kwargs.pop("totalFiles")
92
+ self.__dict__.update(**kwargs)
93
+
94
+
95
+ @dataclass
96
+ class _BucketAddFile:
97
+ source: str | Path | bytes
98
+ destination: str
99
+
100
+ xet_hash: str | None = field(default=None)
101
+ size: int | None = field(default=None)
102
+ mtime: int = field(init=False)
103
+ content_type: str | None = field(init=False)
104
+
105
+ def __post_init__(self) -> None:
106
+ self.content_type = None
107
+ if isinstance(self.source, (str, Path)): # guess content type from source path
108
+ self.content_type = mimetypes.guess_type(self.source)[0]
109
+ if self.content_type is None: # or default to destination path content type
110
+ self.content_type = mimetypes.guess_type(self.destination)[0]
111
+
112
+ self.mtime = int(
113
+ os.path.getmtime(self.source) * 1000 if not isinstance(self.source, bytes) else time.time() * 1000
114
+ )
115
+
116
+
117
+ @dataclass
118
+ class _BucketCopyFile:
119
+ destination: str
120
+ xet_hash: str
121
+ source_repo_type: str # "model", "dataset", "space", "bucket"
122
+ source_repo_id: str
123
+ size: int | None = field(default=None)
124
+ mtime: int = field(init=False)
125
+ content_type: str | None = field(init=False)
126
+
127
+ def __post_init__(self) -> None:
128
+ self.content_type = mimetypes.guess_type(self.destination)[0]
129
+ self.mtime = int(time.time() * 1000)
130
+
131
+
132
+ @dataclass
133
+ class _BucketDeleteFile:
134
+ path: str
135
+
136
+
137
+ @dataclass(frozen=True)
138
+ class BucketFileMetadata:
139
+ """Data structure containing information about a file in a bucket.
140
+
141
+ Returned by [`get_bucket_file_metadata`].
142
+
143
+ Args:
144
+ size (`int`):
145
+ Size of the file in bytes.
146
+ xet_file_data (`XetFileData`):
147
+ Xet information for the file (hash and refresh route).
148
+ """
149
+
150
+ size: int
151
+ xet_file_data: XetFileData
152
+
153
+
154
+ @dataclass
155
+ class BucketUrl:
156
+ """Describes a bucket URL on the Hub.
157
+
158
+ `BucketUrl` is returned by [`create_bucket`]. At initialization, the URL is parsed to populate properties:
159
+ - endpoint (`str`)
160
+ - namespace (`str`)
161
+ - bucket_id (`str`)
162
+ - url (`str`)
163
+ - uri (`HfUri`)
164
+
165
+ Args:
166
+ url (`str`):
167
+ String value of the bucket url.
168
+ endpoint (`str`, *optional*):
169
+ Endpoint of the Hub. Defaults to <https://huggingface.co>.
170
+ """
171
+
172
+ url: str
173
+ endpoint: str = ""
174
+ namespace: str = field(init=False)
175
+ bucket_id: str = field(init=False)
176
+ uri: HfUri = field(init=False)
177
+
178
+ def __post_init__(self) -> None:
179
+ self.endpoint = self.endpoint or constants.ENDPOINT
180
+
181
+ # Parse URL: expected format is `{endpoint}/buckets/{namespace}/{bucket_name}`
182
+ url_path = self.url.replace(self.endpoint, "").strip("/")
183
+ # Remove leading "buckets/" prefix
184
+ if url_path.startswith("buckets/"):
185
+ url_path = url_path[len("buckets/") :]
186
+ parsed = _parse_bucket_uri(url_path)
187
+ if parsed.path_in_repo:
188
+ raise ValueError(f"Unable to parse bucket URL: {self.url}")
189
+ self.namespace = parsed.id.split("/")[0]
190
+ self.bucket_id = parsed.id
191
+ self.uri = parsed
192
+
193
+
194
+ @dataclass
195
+ class BucketFile:
196
+ """
197
+ Contains information about a file in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
198
+
199
+ Similar to [`RepoFile`] but for files in buckets.
200
+ """
201
+
202
+ type: Literal["file"]
203
+ path: str
204
+ size: int
205
+ xet_hash: str
206
+ mtime: datetime | None
207
+ uploaded_at: datetime | None
208
+
209
+ def __init__(self, **kwargs):
210
+ self.type = kwargs.pop("type")
211
+ self.path = kwargs.pop("path")
212
+ self.size = kwargs.pop("size")
213
+ self.xet_hash = kwargs.pop("xetHash")
214
+ mtime = kwargs.pop("mtime", None)
215
+ self.mtime = parse_datetime(mtime) if mtime else None
216
+ uploaded_at = kwargs.pop("uploadedAt", None)
217
+ self.uploaded_at = parse_datetime(uploaded_at) if uploaded_at else None
218
+
219
+
220
+ @dataclass
221
+ class BucketFolder:
222
+ """
223
+ Contains information about a directory in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
224
+
225
+ Similar to [`RepoFolder`] but for directories in buckets.
226
+ """
227
+
228
+ type: Literal["directory"]
229
+ path: str
230
+ uploaded_at: datetime | None
231
+
232
+ def __init__(self, **kwargs):
233
+ self.type = kwargs.pop("type")
234
+ self.path = kwargs.pop("path")
235
+ uploaded_at = kwargs.pop("uploadedAt", None) or kwargs.pop("uploaded_at", None)
236
+ self.uploaded_at = (
237
+ (uploaded_at if isinstance(uploaded_at, datetime) else parse_datetime(uploaded_at))
238
+ if uploaded_at
239
+ else None
240
+ )
241
+
242
+
243
+ # =============================================================================
244
+ # Bucket path parsing
245
+ # =============================================================================
246
+
247
+
248
+ def _parse_bucket_uri(path: str) -> HfUri:
249
+ """Parse a bucket path into a HfUri.
250
+
251
+ Accepts:
252
+ - `hf://buckets/namespace/name(/path/in/repo)` URIs,
253
+ - Hugging Face web URLs such as `https://huggingface.co/buckets/namespace/name(/tree/path)`,
254
+ - plain `namespace/name(/path/in/repo)` paths.
255
+ """
256
+ if path.startswith(constants.HF_PROTOCOL) or _looks_like_hf_url(path):
257
+ # Don't use 'if is_hf_uri(...)' here as we prefer 'parse_hf_uri(...)' to raise the exact error message.
258
+ parsed = parse_hf_uri(path)
259
+ if not parsed.is_bucket:
260
+ raise ValueError(f"Invalid bucket path: {path}. Must be a bucket URI (hf://buckets/...).")
261
+ return parsed
262
+ parts = path.split("/", 2)
263
+ if len(parts) < 2 or not parts[0] or not parts[1]:
264
+ raise ValueError(f"Invalid bucket path: '{path}'. Expected format: namespace/bucket_name")
265
+ bucket_id = f"{parts[0]}/{parts[1]}"
266
+ prefix = "/".join(parts[2:])
267
+ return HfUri(type="bucket", id=bucket_id, path_in_repo=prefix)
268
+
269
+
270
+ def _is_bucket_path(path: str) -> bool:
271
+ """Check if a path is a bucket path.
272
+
273
+ Do not raise if the path is not a hf:// URI.
274
+ Raise if the path is a hf:// URI but with an incorrect format.
275
+ """
276
+ if not path.startswith(constants.HF_PROTOCOL):
277
+ return False
278
+ return parse_hf_uri(path).is_bucket
279
+
280
+
281
+ # =============================================================================
282
+ # Sync data structures
283
+ # =============================================================================
284
+
285
+
286
+ @dataclass
287
+ class SyncOperation:
288
+ """Represents a sync operation to be performed."""
289
+
290
+ action: Literal["upload", "download", "delete", "skip"]
291
+ path: str
292
+ size: int | None = None
293
+ reason: str = ""
294
+ local_mtime: str | None = None
295
+ remote_mtime: str | None = None
296
+ bucket_file: BucketFile | None = None # BucketFile when available (not serialized to plan file)
297
+
298
+
299
+ @dataclass
300
+ class SyncPlan:
301
+ """Represents a complete sync plan."""
302
+
303
+ source: str
304
+ dest: str
305
+ timestamp: str
306
+ operations: list[SyncOperation] = field(default_factory=list)
307
+
308
+ def summary(self) -> dict[str, int | str]:
309
+ uploads = sum(1 for op in self.operations if op.action == "upload")
310
+ downloads = sum(1 for op in self.operations if op.action == "download")
311
+ deletes = sum(1 for op in self.operations if op.action == "delete")
312
+ skips = sum(1 for op in self.operations if op.action == "skip")
313
+ total_size = sum(op.size or 0 for op in self.operations if op.action in ("upload", "download"))
314
+ return {
315
+ "uploads": uploads,
316
+ "downloads": downloads,
317
+ "deletes": deletes,
318
+ "skips": skips,
319
+ "total_size": total_size,
320
+ }
321
+
322
+
323
+ # =============================================================================
324
+ # Filter matching
325
+ # =============================================================================
326
+
327
+
328
+ class FilterMatcher:
329
+ """Matches file paths against include/exclude patterns."""
330
+
331
+ def __init__(
332
+ self,
333
+ include_patterns: list[str] | None = None,
334
+ exclude_patterns: list[str] | None = None,
335
+ filter_rules: list[tuple[str, str]] | None = None,
336
+ ):
337
+ """Initialize the filter matcher.
338
+
339
+ Args:
340
+ include_patterns: Patterns to include (from --include)
341
+ exclude_patterns: Patterns to exclude (from --exclude)
342
+ filter_rules: Rules from filter file as list of ("+"/"-", pattern) tuples
343
+ """
344
+ self.include_patterns = include_patterns or []
345
+ self.exclude_patterns = exclude_patterns or []
346
+ self.filter_rules = filter_rules or []
347
+
348
+ def matches(self, path: str) -> bool:
349
+ """Check if a path should be included based on the filter rules.
350
+
351
+ Filtering rules:
352
+ - Filters are evaluated in order, first matching rule decides
353
+ - If no rules match, include by default (unless include patterns are specified)
354
+ """
355
+ # First check filter rules from file (in order)
356
+ for sign, pattern in self.filter_rules:
357
+ if fnmatch.fnmatch(path, pattern):
358
+ return sign == "+"
359
+
360
+ # Then check CLI patterns
361
+ for pattern in self.exclude_patterns:
362
+ if fnmatch.fnmatch(path, pattern):
363
+ return False
364
+
365
+ for pattern in self.include_patterns:
366
+ if fnmatch.fnmatch(path, pattern):
367
+ return True
368
+
369
+ # If include patterns were specified but none matched, exclude
370
+ if self.include_patterns:
371
+ return False
372
+
373
+ # Default: include
374
+ return True
375
+
376
+
377
+ def _parse_filter_file(filter_file: str) -> list[tuple[str, str]]:
378
+ """Parse a filter file and return a list of (sign, pattern) tuples.
379
+
380
+ Filter file format:
381
+ - Lines starting with "+" are include patterns
382
+ - Lines starting with "-" are exclude patterns
383
+ - Empty lines and lines starting with "#" are ignored
384
+ """
385
+ rules = []
386
+ with open(filter_file) as f:
387
+ for line in f:
388
+ line = line.strip()
389
+ if not line or line.startswith("#"):
390
+ continue
391
+ if line.startswith("+"):
392
+ rules.append(("+", line[1:].strip()))
393
+ elif line.startswith("-"):
394
+ rules.append(("-", line[1:].strip()))
395
+ else:
396
+ # Default to include if no prefix
397
+ rules.append(("+", line))
398
+ return rules
399
+
400
+
401
+ # =============================================================================
402
+ # File listing
403
+ # =============================================================================
404
+
405
+
406
+ def _stat_local(path: str) -> tuple[int, float] | None:
407
+ """Stat a local file and return (size, mtime_ms).
408
+
409
+ Returns None if the path is missing or is a directory. Uses a single
410
+ ``os.stat`` call so callers don't pay for multiple syscalls per file.
411
+ """
412
+ try:
413
+ st = os.stat(path)
414
+ except OSError:
415
+ return None
416
+ if stat.S_ISDIR(st.st_mode):
417
+ return None
418
+ return st.st_size, st.st_mtime * 1000
419
+
420
+
421
+ def _list_local_files(local_path: str) -> Iterator[tuple[str, int, float]]:
422
+ """List all files in a local directory.
423
+
424
+ Yields:
425
+ tuple: (relative_path, size, mtime_ms) for each file
426
+ """
427
+ local_path = os.path.abspath(local_path)
428
+ if not os.path.isdir(local_path):
429
+ raise ValueError(f"Local path must be a directory: {local_path}")
430
+
431
+ for root, _, files in os.walk(local_path):
432
+ for filename in files:
433
+ full_path = os.path.join(root, filename)
434
+ stat_info = _stat_local(full_path)
435
+ if stat_info is None:
436
+ continue
437
+ rel_path = os.path.relpath(full_path, local_path)
438
+ # Normalize to forward slashes for consistency
439
+ rel_path = rel_path.replace(os.sep, "/")
440
+ yield rel_path, stat_info[0], stat_info[1]
441
+
442
+
443
+ def _list_remote_files(api: "HfApi", bucket_id: str, prefix: str) -> Iterator[tuple[str, int, float, Any]]:
444
+ """List all files in a bucket with a given prefix.
445
+
446
+ Yields:
447
+ tuple: (relative_path, size, mtime_ms, bucket_file) for each file.
448
+ bucket_file is the BucketFile object from list_bucket_tree.
449
+ """
450
+ for item in api.list_bucket_tree(bucket_id, prefix=prefix or None, recursive=True):
451
+ if isinstance(item, BucketFolder):
452
+ continue
453
+ path = item.path
454
+ # Remove prefix from path to get relative path
455
+ # Only strip prefix if it's followed by "/" (directory boundary) or is exact match
456
+ if prefix:
457
+ if path.startswith(prefix + "/"):
458
+ rel_path = path[len(prefix) + 1 :]
459
+ elif path == prefix:
460
+ # Exact match: the file IS the prefix (e.g., single file download)
461
+ rel_path = path.rsplit("/", 1)[-1] if "/" in path else path
462
+ else:
463
+ # Path doesn't match prefix pattern (e.g., "submarine.txt" for prefix "sub")
464
+ # Skip this file - it was returned by the API but doesn't belong to this prefix
465
+ continue
466
+ else:
467
+ rel_path = path
468
+ mtime_ms = item.mtime.timestamp() * 1000 if item.mtime else 0
469
+ yield rel_path, item.size, mtime_ms, item
470
+
471
+
472
+ # =============================================================================
473
+ # Sync plan computation
474
+ # =============================================================================
475
+
476
+
477
+ def _mtime_to_iso(mtime_ms: float) -> str:
478
+ """Convert mtime in milliseconds to ISO format string."""
479
+ return datetime.fromtimestamp(mtime_ms / 1000, tz=timezone.utc).isoformat()
480
+
481
+
482
+ def _compare_files_for_sync(
483
+ *,
484
+ path: str,
485
+ action: Literal["upload", "download"],
486
+ source_size: int,
487
+ source_mtime: float,
488
+ dest_size: int,
489
+ dest_mtime: float,
490
+ source_newer_label: str,
491
+ dest_newer_label: str,
492
+ ignore_sizes: bool,
493
+ ignore_times: bool,
494
+ ignore_existing: bool,
495
+ bucket_file: Any | None = None,
496
+ ) -> SyncOperation:
497
+ """Compare source and dest files and return the appropriate sync operation.
498
+
499
+ This is a unified helper for both upload and download directions.
500
+
501
+ Args:
502
+ path: Relative file path
503
+ action: "upload" or "download"
504
+ source_size: Size of the source file (bytes)
505
+ source_mtime: Mtime of the source file (milliseconds)
506
+ dest_size: Size of the destination file (bytes)
507
+ dest_mtime: Mtime of the destination file (milliseconds)
508
+ source_newer_label: Label when source is newer (e.g., "local newer" or "remote newer")
509
+ dest_newer_label: Label when dest is newer (e.g., "remote newer" or "local newer")
510
+ ignore_sizes: Only compare mtime
511
+ ignore_times: Only compare size
512
+ ignore_existing: Skip files that exist on receiver
513
+ bucket_file: BucketFile object (for downloads only)
514
+
515
+ Returns:
516
+ SyncOperation describing the action to take
517
+ """
518
+ local_mtime_iso = _mtime_to_iso(source_mtime if action == "upload" else dest_mtime)
519
+ remote_mtime_iso = _mtime_to_iso(dest_mtime if action == "upload" else source_mtime)
520
+
521
+ base_kwargs: dict[str, Any] = {
522
+ "path": path,
523
+ "size": source_size,
524
+ "local_mtime": local_mtime_iso,
525
+ "remote_mtime": remote_mtime_iso,
526
+ }
527
+
528
+ if ignore_existing:
529
+ return SyncOperation(action="skip", reason="exists on receiver (--ignore-existing)", **base_kwargs)
530
+
531
+ size_differs = source_size != dest_size
532
+ source_newer = (source_mtime - dest_mtime) > _SYNC_TIME_WINDOW_MS
533
+
534
+ if ignore_sizes:
535
+ if source_newer:
536
+ return SyncOperation(action=action, reason=source_newer_label, bucket_file=bucket_file, **base_kwargs)
537
+ else:
538
+ dest_newer = (dest_mtime - source_mtime) > _SYNC_TIME_WINDOW_MS
539
+ skip_reason = dest_newer_label if dest_newer else "same mtime"
540
+ return SyncOperation(action="skip", reason=skip_reason, **base_kwargs)
541
+ elif ignore_times:
542
+ if size_differs:
543
+ return SyncOperation(action=action, reason="size differs", bucket_file=bucket_file, **base_kwargs)
544
+ else:
545
+ return SyncOperation(action="skip", reason="same size", **base_kwargs)
546
+ else:
547
+ if size_differs or source_newer:
548
+ reason = "size differs" if size_differs else source_newer_label
549
+ return SyncOperation(action=action, reason=reason, bucket_file=bucket_file, **base_kwargs)
550
+ else:
551
+ return SyncOperation(action="skip", reason="identical", **base_kwargs)
552
+
553
+
554
+ def _compute_sync_plan(
555
+ source: str,
556
+ dest: str,
557
+ api: "HfApi",
558
+ delete: bool = False,
559
+ ignore_times: bool = False,
560
+ ignore_sizes: bool = False,
561
+ existing: bool = False,
562
+ ignore_existing: bool = False,
563
+ filter_matcher: FilterMatcher | None = None,
564
+ status: Any | None = None,
565
+ ) -> SyncPlan:
566
+ """Compute the sync plan by comparing source and destination.
567
+
568
+ Returns:
569
+ SyncPlan with all operations to be performed
570
+ """
571
+ filter_matcher = filter_matcher or FilterMatcher()
572
+ is_upload = not _is_bucket_path(source) and _is_bucket_path(dest)
573
+ is_download = _is_bucket_path(source) and not _is_bucket_path(dest)
574
+
575
+ if not is_upload and not is_download:
576
+ raise ValueError("One of source or dest must be a bucket path (hf://buckets/...) and the other must be local.")
577
+
578
+ plan = SyncPlan(
579
+ source=source,
580
+ dest=dest,
581
+ timestamp=datetime.now(timezone.utc).isoformat(),
582
+ )
583
+
584
+ remote_total: int | None = None
585
+ if is_upload:
586
+ # Local -> Remote
587
+ local_path = os.path.abspath(source)
588
+ parsed = _parse_bucket_uri(dest)
589
+ bucket_id, prefix = parsed.id, parsed.path_in_repo
590
+
591
+ if not os.path.isdir(local_path):
592
+ raise ValueError(f"Source must be a directory: {local_path}")
593
+
594
+ # Get local and remote file lists
595
+ local_files = {}
596
+ for rel_path, size, mtime_ms in _list_local_files(local_path):
597
+ if filter_matcher.matches(rel_path):
598
+ local_files[rel_path] = (size, mtime_ms)
599
+ if status:
600
+ status.update(f"Scanning local directory ({len(local_files)} files)")
601
+ if status:
602
+ status.done(f"Scanning local directory ({len(local_files)} files)")
603
+
604
+ remote_files = {}
605
+ if status:
606
+ try:
607
+ remote_total = api.bucket_info(bucket_id).total_files
608
+ except Exception:
609
+ pass
610
+ try:
611
+ for rel_path, size, mtime_ms, _ in _list_remote_files(api, bucket_id, prefix):
612
+ if filter_matcher.matches(rel_path):
613
+ remote_files[rel_path] = (size, mtime_ms)
614
+ if status:
615
+ total_str = f"/{remote_total}" if remote_total is not None else ""
616
+ status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)")
617
+ except BucketNotFoundError:
618
+ # Bucket doesn't exist yet - this is expected for new uploads
619
+ logger.debug(f"Bucket '{bucket_id}' not found, treating as empty.")
620
+ if status:
621
+ status.done(f"Scanning remote bucket ({len(remote_files)} files)")
622
+
623
+ # Compare files
624
+ all_paths = set(local_files.keys()) | set(remote_files.keys())
625
+ if status:
626
+ status.done(f"Comparing files ({len(all_paths)} paths)")
627
+ for path in sorted(all_paths):
628
+ local_info = local_files.get(path)
629
+ remote_info = remote_files.get(path)
630
+
631
+ if local_info and not remote_info:
632
+ # New file
633
+ if existing:
634
+ # --existing: skip new files
635
+ plan.operations.append(
636
+ SyncOperation(
637
+ action="skip",
638
+ path=path,
639
+ size=local_info[0],
640
+ reason="new file (--existing)",
641
+ local_mtime=_mtime_to_iso(local_info[1]),
642
+ )
643
+ )
644
+ else:
645
+ plan.operations.append(
646
+ SyncOperation(
647
+ action="upload",
648
+ path=path,
649
+ size=local_info[0],
650
+ reason="new file",
651
+ local_mtime=_mtime_to_iso(local_info[1]),
652
+ )
653
+ )
654
+ elif local_info and remote_info:
655
+ # File exists in both - use helper to determine action
656
+ local_size, local_mtime = local_info
657
+ remote_size, remote_mtime = remote_info
658
+ plan.operations.append(
659
+ _compare_files_for_sync(
660
+ path=path,
661
+ action="upload",
662
+ source_size=local_size,
663
+ source_mtime=local_mtime,
664
+ dest_size=remote_size,
665
+ dest_mtime=remote_mtime,
666
+ source_newer_label="local newer",
667
+ dest_newer_label="remote newer",
668
+ ignore_sizes=ignore_sizes,
669
+ ignore_times=ignore_times,
670
+ ignore_existing=ignore_existing,
671
+ )
672
+ )
673
+ elif not local_info and remote_info and delete:
674
+ # File only in remote and --delete mode
675
+ plan.operations.append(
676
+ SyncOperation(
677
+ action="delete",
678
+ path=path,
679
+ size=remote_info[0],
680
+ reason="not in source (--delete)",
681
+ remote_mtime=_mtime_to_iso(remote_info[1]),
682
+ )
683
+ )
684
+
685
+ else:
686
+ # Remote -> Local (download)
687
+ parsed = _parse_bucket_uri(source)
688
+ bucket_id, prefix = parsed.id, parsed.path_in_repo
689
+ local_path = os.path.abspath(dest)
690
+
691
+ # Get remote and local file lists
692
+ remote_files = {}
693
+ bucket_file_map: dict[str, Any] = {}
694
+ if status:
695
+ try:
696
+ remote_total = api.bucket_info(bucket_id).total_files
697
+ except Exception:
698
+ pass
699
+ for rel_path, size, mtime_ms, bucket_file in _list_remote_files(api, bucket_id, prefix):
700
+ if filter_matcher.matches(rel_path):
701
+ remote_files[rel_path] = (size, mtime_ms)
702
+ bucket_file_map[rel_path] = bucket_file
703
+ if status:
704
+ total_str = f"/{remote_total}" if remote_total is not None else ""
705
+ status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)")
706
+ if status:
707
+ status.done(f"Scanning remote bucket ({len(remote_files)} files)")
708
+
709
+ local_files = {}
710
+ if os.path.isdir(local_path):
711
+ if delete:
712
+ # Full walk needed to discover local-only files for deletion.
713
+ for rel_path, size, mtime_ms in _list_local_files(local_path):
714
+ if filter_matcher.matches(rel_path):
715
+ local_files[rel_path] = (size, mtime_ms)
716
+ if status:
717
+ status.update(f"Scanning local directory ({len(local_files)} files)")
718
+ else:
719
+ # Without --delete, the plan only depends on paths that exist
720
+ # remotely. Stat just those instead of walking the whole tree,
721
+ # which can take minutes when dest sits in a large directory
722
+ # like ~/.cache/huggingface/.
723
+ for rel_path in remote_files:
724
+ local_file = os.path.join(local_path, rel_path)
725
+ stat_info = _stat_local(local_file)
726
+ if stat_info is None:
727
+ continue
728
+ local_files[rel_path] = stat_info
729
+ if status:
730
+ status.update(f"Scanning local directory ({len(local_files)} files)")
731
+ if status:
732
+ status.done(f"Scanning local directory ({len(local_files)} files)")
733
+
734
+ # Compare files
735
+ all_paths = set(remote_files.keys()) | set(local_files.keys())
736
+ if status:
737
+ status.done(f"Comparing files ({len(all_paths)} paths)")
738
+ for path in sorted(all_paths):
739
+ remote_info = remote_files.get(path)
740
+ local_info = local_files.get(path)
741
+
742
+ if remote_info and not local_info:
743
+ # New file
744
+ if existing:
745
+ # --existing: skip new files
746
+ plan.operations.append(
747
+ SyncOperation(
748
+ action="skip",
749
+ path=path,
750
+ size=remote_info[0],
751
+ reason="new file (--existing)",
752
+ remote_mtime=_mtime_to_iso(remote_info[1]),
753
+ )
754
+ )
755
+ else:
756
+ plan.operations.append(
757
+ SyncOperation(
758
+ action="download",
759
+ path=path,
760
+ size=remote_info[0],
761
+ reason="new file",
762
+ remote_mtime=_mtime_to_iso(remote_info[1]),
763
+ bucket_file=bucket_file_map.get(path),
764
+ )
765
+ )
766
+ elif remote_info and local_info:
767
+ # File exists in both - use helper to determine action
768
+ remote_size, remote_mtime = remote_info
769
+ local_size, local_mtime = local_info
770
+ plan.operations.append(
771
+ _compare_files_for_sync(
772
+ path=path,
773
+ action="download",
774
+ source_size=remote_size,
775
+ source_mtime=remote_mtime,
776
+ dest_size=local_size,
777
+ dest_mtime=local_mtime,
778
+ source_newer_label="remote newer",
779
+ dest_newer_label="local newer",
780
+ ignore_sizes=ignore_sizes,
781
+ ignore_times=ignore_times,
782
+ ignore_existing=ignore_existing,
783
+ bucket_file=bucket_file_map.get(path),
784
+ )
785
+ )
786
+ elif not remote_info and local_info and delete:
787
+ # File only in local and --delete mode
788
+ plan.operations.append(
789
+ SyncOperation(
790
+ action="delete",
791
+ path=path,
792
+ size=local_info[0],
793
+ reason="not in source (--delete)",
794
+ local_mtime=_mtime_to_iso(local_info[1]),
795
+ )
796
+ )
797
+
798
+ return plan
799
+
800
+
801
+ # =============================================================================
802
+ # Plan serialization
803
+ # =============================================================================
804
+
805
+
806
+ def _write_plan(plan: SyncPlan, f) -> None:
807
+ """Write a sync plan as JSONL to a file-like object."""
808
+ # Write header
809
+ header = {
810
+ "type": "header",
811
+ "source": plan.source,
812
+ "dest": plan.dest,
813
+ "timestamp": plan.timestamp,
814
+ "summary": plan.summary(),
815
+ }
816
+ f.write(json.dumps(header) + "\n")
817
+
818
+ # Write operations
819
+ for op in plan.operations:
820
+ op_dict: dict[str, Any] = {
821
+ "type": "operation",
822
+ "action": op.action,
823
+ "path": op.path,
824
+ "reason": op.reason,
825
+ }
826
+ if op.size is not None:
827
+ op_dict["size"] = op.size
828
+ if op.local_mtime is not None:
829
+ op_dict["local_mtime"] = op.local_mtime
830
+ if op.remote_mtime is not None:
831
+ op_dict["remote_mtime"] = op.remote_mtime
832
+ f.write(json.dumps(op_dict) + "\n")
833
+
834
+
835
+ def _save_plan(plan: SyncPlan, plan_file: str) -> None:
836
+ """Save a sync plan to a JSONL file."""
837
+ with open(plan_file, "w") as f:
838
+ _write_plan(plan, f)
839
+
840
+
841
+ def _load_plan(plan_file: str) -> SyncPlan:
842
+ """Load a sync plan from a JSONL file."""
843
+ with open(plan_file) as f:
844
+ lines = f.readlines()
845
+
846
+ if not lines:
847
+ raise ValueError(f"Empty plan file: {plan_file}")
848
+
849
+ # Parse header
850
+ header = json.loads(lines[0])
851
+ if header.get("type") != "header":
852
+ raise ValueError("Invalid plan file: expected header as first line")
853
+
854
+ plan = SyncPlan(
855
+ source=header["source"],
856
+ dest=header["dest"],
857
+ timestamp=header["timestamp"],
858
+ )
859
+
860
+ # Parse operations
861
+ for line in lines[1:]:
862
+ op_dict = json.loads(line)
863
+ if op_dict.get("type") != "operation":
864
+ continue
865
+ plan.operations.append(
866
+ SyncOperation(
867
+ action=op_dict["action"],
868
+ path=op_dict["path"],
869
+ size=op_dict.get("size"),
870
+ reason=op_dict.get("reason", ""),
871
+ local_mtime=op_dict.get("local_mtime"),
872
+ remote_mtime=op_dict.get("remote_mtime"),
873
+ )
874
+ )
875
+
876
+ return plan
877
+
878
+
879
+ # =============================================================================
880
+ # Plan execution
881
+ # =============================================================================
882
+
883
+
884
+ def _execute_plan(plan: SyncPlan, api: "HfApi", verbose: bool = False, status: Any | None = None) -> None:
885
+ """Execute a sync plan."""
886
+ is_upload = not _is_bucket_path(plan.source) and _is_bucket_path(plan.dest)
887
+ is_download = _is_bucket_path(plan.source) and not _is_bucket_path(plan.dest)
888
+
889
+ if is_upload:
890
+ local_path = os.path.abspath(plan.source)
891
+ parsed = _parse_bucket_uri(plan.dest)
892
+ bucket_id, prefix = parsed.id, parsed.path_in_repo
893
+
894
+ # Collect operations
895
+ add_files: list[tuple[str | Path | bytes, str]] = []
896
+ delete_paths: list[str] = []
897
+
898
+ for op in plan.operations:
899
+ match op.action:
900
+ case "upload":
901
+ local_file = os.path.join(local_path, op.path)
902
+ remote_path = f"{prefix}/{op.path}" if prefix else op.path
903
+ if verbose:
904
+ print(f" Uploading: {op.path} ({op.reason})")
905
+ add_files.append((local_file, remote_path))
906
+ case "delete":
907
+ remote_path = f"{prefix}/{op.path}" if prefix else op.path
908
+ if verbose:
909
+ print(f" Deleting: {op.path} ({op.reason})")
910
+ delete_paths.append(remote_path)
911
+ case "skip" if verbose:
912
+ print(f" Skipping: {op.path} ({op.reason})")
913
+
914
+ # Execute batch operations
915
+ if add_files or delete_paths:
916
+ if status:
917
+ parts = []
918
+ if add_files:
919
+ parts.append(f"uploading {len(add_files)} files")
920
+ if delete_paths:
921
+ parts.append(f"deleting {len(delete_paths)} files")
922
+ status.done(", ".join(parts).capitalize())
923
+ api.batch_bucket_files(
924
+ bucket_id,
925
+ add=add_files or None,
926
+ delete=delete_paths or None,
927
+ )
928
+
929
+ elif is_download:
930
+ parsed = _parse_bucket_uri(plan.source)
931
+ bucket_id, prefix = parsed.id, parsed.path_in_repo
932
+ local_path = os.path.abspath(plan.dest)
933
+
934
+ # Ensure local directory exists
935
+ os.makedirs(local_path, exist_ok=True)
936
+
937
+ # Collect download operations
938
+ download_files: list[tuple[str | BucketFile, str | Path]] = []
939
+ delete_files: list[str] = []
940
+
941
+ for op in plan.operations:
942
+ if op.action == "download":
943
+ local_file = os.path.join(local_path, op.path)
944
+ # Ensure parent directory exists
945
+ os.makedirs(os.path.dirname(local_file), exist_ok=True)
946
+ if verbose:
947
+ print(f" Downloading: {op.path} ({op.reason})")
948
+ # Use BucketFile when available (avoids extra metadata fetch per file)
949
+ if op.bucket_file is not None:
950
+ download_files.append((op.bucket_file, local_file))
951
+ else:
952
+ remote_path = f"{prefix}/{op.path}" if prefix else op.path
953
+ download_files.append((remote_path, local_file))
954
+ elif op.action == "delete":
955
+ local_file = os.path.join(local_path, op.path)
956
+ if verbose:
957
+ print(f" Deleting: {op.path} ({op.reason})")
958
+ delete_files.append(local_file)
959
+ elif op.action == "skip" and verbose:
960
+ print(f" Skipping: {op.path} ({op.reason})")
961
+
962
+ # Execute downloads
963
+ if len(download_files) > 0:
964
+ if status:
965
+ status.done(f"Downloading {len(download_files)} files")
966
+ api.download_bucket_files(bucket_id, download_files)
967
+
968
+ # Execute deletes
969
+ if status and delete_files:
970
+ status.done(f"Deleting {len(delete_files)} local files")
971
+ for file_path in delete_files:
972
+ if os.path.exists(file_path):
973
+ os.remove(file_path)
974
+ # Remove empty parent directories
975
+ parent = os.path.dirname(file_path)
976
+ while parent != local_path:
977
+ try:
978
+ os.rmdir(parent)
979
+ parent = os.path.dirname(parent)
980
+ except OSError:
981
+ break
982
+
983
+
984
+ def _print_plan_summary(plan: SyncPlan) -> None:
985
+ """Print a summary of the sync plan."""
986
+ summary = plan.summary()
987
+ print(f"Sync plan: {plan.source} -> {plan.dest}")
988
+ print(f" Uploads: {summary['uploads']}")
989
+ print(f" Downloads: {summary['downloads']}")
990
+ print(f" Deletes: {summary['deletes']}")
991
+ print(f" Skips: {summary['skips']}")
992
+
993
+
994
+ # =============================================================================
995
+ # Public sync function (Python API)
996
+ # =============================================================================
997
+
998
+
999
+ def sync_bucket_internal(
1000
+ source: str | None = None,
1001
+ dest: str | None = None,
1002
+ *,
1003
+ api: "HfApi",
1004
+ delete: bool = False,
1005
+ ignore_times: bool = False,
1006
+ ignore_sizes: bool = False,
1007
+ existing: bool = False,
1008
+ ignore_existing: bool = False,
1009
+ include: list[str] | None = None,
1010
+ exclude: list[str] | None = None,
1011
+ filter_from: str | None = None,
1012
+ plan: str | None = None,
1013
+ apply: str | None = None,
1014
+ dry_run: bool = False,
1015
+ verbose: bool = False,
1016
+ quiet: bool = False,
1017
+ token: bool | str | None = None,
1018
+ ) -> SyncPlan:
1019
+ """Sync files between a local directory and a bucket.
1020
+
1021
+ This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path
1022
+ (``hf://buckets/...``) and the other must be a local directory path.
1023
+
1024
+ Args:
1025
+ source (`str`, *optional*):
1026
+ Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
1027
+ Required unless using ``apply``.
1028
+ dest (`str`, *optional*):
1029
+ Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
1030
+ Required unless using ``apply``.
1031
+ api ([`HfApi`]):
1032
+ The HfApi instance to use for API calls.
1033
+ delete (`bool`, *optional*, defaults to `False`):
1034
+ Delete destination files not present in source.
1035
+ ignore_times (`bool`, *optional*, defaults to `False`):
1036
+ Skip files only based on size, ignoring modification times.
1037
+ ignore_sizes (`bool`, *optional*, defaults to `False`):
1038
+ Skip files only based on modification times, ignoring sizes.
1039
+ existing (`bool`, *optional*, defaults to `False`):
1040
+ Skip creating new files on receiver (only update existing files).
1041
+ ignore_existing (`bool`, *optional*, defaults to `False`):
1042
+ Skip updating files that exist on receiver (only create new files).
1043
+ include (`list[str]`, *optional*):
1044
+ Include files matching patterns (fnmatch-style).
1045
+ exclude (`list[str]`, *optional*):
1046
+ Exclude files matching patterns (fnmatch-style).
1047
+ filter_from (`str`, *optional*):
1048
+ Path to a filter file with include/exclude rules.
1049
+ plan (`str`, *optional*):
1050
+ Save sync plan to this JSONL file instead of executing.
1051
+ apply (`str`, *optional*):
1052
+ Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed.
1053
+ dry_run (`bool`, *optional*, defaults to `False`):
1054
+ Print sync plan to stdout as JSONL without executing.
1055
+ verbose (`bool`, *optional*, defaults to `False`):
1056
+ Show detailed per-file operations.
1057
+ quiet (`bool`, *optional*, defaults to `False`):
1058
+ Suppress all output and progress bars.
1059
+ token (Union[bool, str, None], optional):
1060
+ A valid user access token. If not provided, the locally saved token will be used.
1061
+
1062
+ Returns:
1063
+ [`SyncPlan`]: The computed (or loaded) sync plan.
1064
+
1065
+ Raises:
1066
+ `ValueError`: If arguments are invalid (e.g., both paths are remote, conflicting options).
1067
+
1068
+ Example:
1069
+ ```python
1070
+ >>> from huggingface_hub import HfApi
1071
+ >>> api = HfApi()
1072
+
1073
+ # Upload local directory to bucket
1074
+ >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
1075
+
1076
+ # Download bucket to local directory
1077
+ >>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
1078
+
1079
+ # Sync with delete and filtering
1080
+ >>> api.sync_bucket(
1081
+ ... "./data",
1082
+ ... "hf://buckets/username/my-bucket",
1083
+ ... delete=True,
1084
+ ... include=["*.safetensors"],
1085
+ ... )
1086
+
1087
+ # Dry run: preview what would be synced
1088
+ >>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
1089
+ >>> plan.summary()
1090
+ {'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
1091
+
1092
+ # Save plan for review, then apply
1093
+ >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
1094
+ >>> api.sync_bucket(apply="sync-plan.jsonl")
1095
+ ```
1096
+ """
1097
+ # Build API with token if needed
1098
+ if token is not None:
1099
+ from .hf_api import HfApi
1100
+
1101
+ api = HfApi(
1102
+ endpoint=api.endpoint,
1103
+ token=token,
1104
+ library_name=api.library_name,
1105
+ library_version=api.library_version,
1106
+ user_agent=api.user_agent,
1107
+ headers=api.headers,
1108
+ )
1109
+ # --- Apply mode ---
1110
+ if apply:
1111
+ if source or dest:
1112
+ raise ValueError("Cannot specify source/dest when using apply.")
1113
+ if plan is not None:
1114
+ raise ValueError("Cannot specify both plan and apply.")
1115
+ if delete:
1116
+ raise ValueError("Cannot specify delete when using apply.")
1117
+ if ignore_times:
1118
+ raise ValueError("Cannot specify ignore_times when using apply.")
1119
+ if ignore_sizes:
1120
+ raise ValueError("Cannot specify ignore_sizes when using apply.")
1121
+ if include:
1122
+ raise ValueError("Cannot specify include when using apply.")
1123
+ if exclude:
1124
+ raise ValueError("Cannot specify exclude when using apply.")
1125
+ if filter_from:
1126
+ raise ValueError("Cannot specify filter_from when using apply.")
1127
+ if existing:
1128
+ raise ValueError("Cannot specify existing when using apply.")
1129
+ if ignore_existing:
1130
+ raise ValueError("Cannot specify ignore_existing when using apply.")
1131
+ if dry_run:
1132
+ raise ValueError("Cannot specify dry_run when using apply.")
1133
+
1134
+ sync_plan = _load_plan(apply)
1135
+ status = StatusLine(enabled=not quiet)
1136
+ if not quiet:
1137
+ _print_plan_summary(sync_plan)
1138
+ print("Executing plan...")
1139
+
1140
+ if quiet:
1141
+ disable_progress_bars()
1142
+ try:
1143
+ _execute_plan(sync_plan, api, verbose=verbose, status=status)
1144
+ finally:
1145
+ if quiet:
1146
+ enable_progress_bars()
1147
+
1148
+ if not quiet:
1149
+ print("Sync completed.")
1150
+
1151
+ return sync_plan
1152
+
1153
+ # --- Normal mode ---
1154
+ if not source or not dest:
1155
+ raise ValueError("Both source and dest are required (unless using apply).")
1156
+
1157
+ source_is_bucket = _is_bucket_path(source)
1158
+ dest_is_bucket = _is_bucket_path(dest)
1159
+
1160
+ if source_is_bucket and dest_is_bucket:
1161
+ raise ValueError("Remote to remote sync is not supported. One path must be local.")
1162
+
1163
+ if not source_is_bucket and not dest_is_bucket:
1164
+ raise ValueError("One of source or dest must be a bucket path (hf://buckets/...).")
1165
+
1166
+ if ignore_times and ignore_sizes:
1167
+ raise ValueError("Cannot specify both ignore_times and ignore_sizes.")
1168
+
1169
+ if existing and ignore_existing:
1170
+ raise ValueError("Cannot specify both existing and ignore_existing.")
1171
+
1172
+ if dry_run and plan:
1173
+ raise ValueError("Cannot specify both dry_run and plan.")
1174
+
1175
+ # Validate local path
1176
+ if source_is_bucket:
1177
+ if os.path.exists(dest) and not os.path.isdir(dest):
1178
+ raise ValueError(f"Destination must be a directory: {dest}")
1179
+ else:
1180
+ if not os.path.isdir(source):
1181
+ raise ValueError(f"Source must be an existing directory: {source}")
1182
+
1183
+ # Build filter matcher
1184
+ filter_rules = None
1185
+ if filter_from:
1186
+ filter_rules = _parse_filter_file(filter_from)
1187
+
1188
+ filter_matcher = FilterMatcher(
1189
+ include_patterns=include,
1190
+ exclude_patterns=exclude,
1191
+ filter_rules=filter_rules,
1192
+ )
1193
+
1194
+ # Compute sync plan
1195
+ status = StatusLine(enabled=not quiet and not dry_run)
1196
+ sync_plan = _compute_sync_plan(
1197
+ source=source,
1198
+ dest=dest,
1199
+ api=api,
1200
+ delete=delete,
1201
+ ignore_times=ignore_times,
1202
+ ignore_sizes=ignore_sizes,
1203
+ existing=existing,
1204
+ ignore_existing=ignore_existing,
1205
+ filter_matcher=filter_matcher,
1206
+ status=status,
1207
+ )
1208
+
1209
+ if dry_run:
1210
+ _write_plan(sync_plan, sys.stdout)
1211
+ return sync_plan
1212
+
1213
+ if plan:
1214
+ _save_plan(sync_plan, plan)
1215
+ if not quiet:
1216
+ _print_plan_summary(sync_plan)
1217
+ print(f"Plan saved to: {plan}")
1218
+ return sync_plan
1219
+
1220
+ # Execute plan
1221
+ if not quiet:
1222
+ _print_plan_summary(sync_plan)
1223
+
1224
+ summary = sync_plan.summary()
1225
+ if summary["uploads"] == 0 and summary["downloads"] == 0 and summary["deletes"] == 0:
1226
+ if not quiet:
1227
+ print("Nothing to sync.")
1228
+ return sync_plan
1229
+
1230
+ if not quiet:
1231
+ print("Syncing...")
1232
+
1233
+ if quiet:
1234
+ disable_progress_bars()
1235
+ try:
1236
+ _execute_plan(sync_plan, api, verbose=verbose, status=status)
1237
+ finally:
1238
+ if quiet:
1239
+ enable_progress_bars()
1240
+
1241
+ if not quiet:
1242
+ print("Sync completed.")
1243
+
1244
+ return sync_plan
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_commit_api.py ADDED
@@ -0,0 +1,1075 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Type definitions and utilities for the `create_commit` API
3
+ """
4
+
5
+ import base64
6
+ import io
7
+ import json
8
+ import os
9
+ import warnings
10
+ from collections import defaultdict
11
+ from collections.abc import Iterable, Iterator
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ from contextlib import contextmanager
14
+ from dataclasses import dataclass, field
15
+ from itertools import groupby
16
+ from pathlib import Path, PurePosixPath
17
+ from typing import TYPE_CHECKING, Any, BinaryIO, Literal, NamedTuple, Union
18
+
19
+ from tqdm.contrib.concurrent import thread_map
20
+
21
+ from . import constants
22
+ from .errors import EntryNotFoundError
23
+ from .file_download import hf_hub_url
24
+ from .lfs import UploadInfo, lfs_upload, post_lfs_batch_info
25
+ from .utils import (
26
+ FORBIDDEN_FOLDERS,
27
+ are_progress_bars_disabled,
28
+ chunk_iterable,
29
+ get_session,
30
+ hf_raise_for_status,
31
+ http_backoff,
32
+ logging,
33
+ sha,
34
+ tqdm_stream_file,
35
+ validate_hf_hub_args,
36
+ )
37
+ from .utils import tqdm as hf_tqdm
38
+ from .utils._runtime import is_xet_available
39
+
40
+
41
+ if TYPE_CHECKING:
42
+ from .hf_api import CommitInfo, RepoFile
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ UploadMode = Literal["lfs", "regular"]
49
+
50
+ # Max is 1,000 per request on the Hub for HfApi.get_paths_info
51
+ # Otherwise we get:
52
+ # HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters
53
+ # See https://github.com/huggingface/huggingface_hub/issues/1503
54
+ FETCH_LFS_BATCH_SIZE = 500
55
+ DUPLICATE_LFS_BATCH_SIZE = 500
56
+
57
+ UPLOAD_BATCH_MAX_NUM_FILES = 256
58
+
59
+
60
+ @dataclass
61
+ class CommitOperationDelete:
62
+ """
63
+ Data structure holding necessary info to delete a file or a folder from a repository
64
+ on the Hub.
65
+
66
+ Args:
67
+ path_in_repo (`str`):
68
+ Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
69
+ for a file or `"checkpoints/1fec34a/"` for a folder.
70
+ is_folder (`bool` or `Literal["auto"]`, *optional*)
71
+ Whether the Delete Operation applies to a folder or not. If "auto", the path
72
+ type (file or folder) is guessed automatically by looking if path ends with
73
+ a "/" (folder) or not (file). To explicitly set the path type, you can set
74
+ `is_folder=True` or `is_folder=False`.
75
+ """
76
+
77
+ path_in_repo: str
78
+ is_folder: bool | Literal["auto"] = "auto"
79
+
80
+ def __post_init__(self):
81
+ self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
82
+
83
+ if self.is_folder == "auto":
84
+ self.is_folder = self.path_in_repo.endswith("/")
85
+ if not isinstance(self.is_folder, bool):
86
+ raise ValueError(
87
+ f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'."
88
+ )
89
+
90
+
91
+ @dataclass
92
+ class CommitOperationCopy:
93
+ """
94
+ Data structure holding necessary info to copy a file in a repository on the Hub.
95
+
96
+ Both LFS files and regular files are supported. LFS files are copied server-side while regular files are
97
+ downloaded and re-uploaded as part of the commit.
98
+
99
+ Cross-repository copies are supported by setting `src_repo_id` and `src_repo_type`. For cross-repo LFS copies,
100
+ the LFS objects are duplicated to the destination repository before the commit is created. This is handled
101
+ automatically by [`create_commit`]. Note that cross-repository copies only work within the same
102
+ [storage region](https://huggingface.co/docs/hub/storage-regions); copying across regions is not supported.
103
+
104
+ Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub.
105
+
106
+ Args:
107
+ src_path_in_repo (`str`):
108
+ Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`.
109
+ path_in_repo (`str`):
110
+ Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`.
111
+ src_revision (`str`, *optional*):
112
+ The git revision of the file to be copied. Can be any valid git revision.
113
+ Default to the target commit revision.
114
+ src_repo_id (`str`, *optional*):
115
+ The source repository to copy from (e.g. `"username/source-model"`).
116
+ Default to the destination repository (intra-repo copy).
117
+ src_repo_type (`str`, *optional*):
118
+ The type of the source repository (`"model"`, `"dataset"` or `"space"`).
119
+ Required when `src_repo_id` is set.
120
+ """
121
+
122
+ src_path_in_repo: str
123
+ path_in_repo: str
124
+ src_revision: str | None = None
125
+ src_repo_id: str | None = None
126
+ src_repo_type: str | None = None
127
+ # set to the OID of the file to be copied if it has already been uploaded
128
+ # useful to determine if a commit will be empty or not.
129
+ _src_oid: str | None = None
130
+ # set to the OID of the file to copy to if it has already been uploaded
131
+ # useful to determine if a commit will be empty or not.
132
+ _dest_oid: str | None = None
133
+ # set to True once cross-repo LFS files have been duplicated to the destination repo
134
+ _is_duplicated: bool = False
135
+
136
+ def __post_init__(self):
137
+ self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo)
138
+ self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
139
+ if self.src_repo_id is not None and self.src_repo_type is None:
140
+ raise ValueError("`src_repo_type` is required when `src_repo_id` is set.")
141
+ if self.src_repo_type is not None and self.src_repo_id is None:
142
+ raise ValueError("`src_repo_id` is required when `src_repo_type` is set.")
143
+
144
+
145
+ @dataclass
146
+ class CommitOperationAdd:
147
+ """
148
+ Data structure holding necessary info to upload a file to a repository on the Hub.
149
+
150
+ Args:
151
+ path_in_repo (`str`):
152
+ Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
153
+ path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`):
154
+ Either:
155
+ - a path to a local file (as `str` or `pathlib.Path`) to upload
156
+ - a buffer of bytes (`bytes`) holding the content of the file to upload
157
+ - a "file object" (subclass of `io.BufferedIOBase`), typically obtained
158
+ with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
159
+
160
+ Raises:
161
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
162
+ If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`.
163
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
164
+ If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file.
165
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
166
+ If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both
167
+ `seek()` and `tell()`.
168
+ """
169
+
170
+ path_in_repo: str
171
+ path_or_fileobj: str | Path | bytes | BinaryIO
172
+ upload_info: UploadInfo = field(init=False, repr=False)
173
+
174
+ # Internal attributes
175
+
176
+ # set to "lfs" or "regular" once known
177
+ _upload_mode: UploadMode | None = field(init=False, repr=False, default=None)
178
+
179
+ # set to True if .gitignore rules prevent the file from being uploaded as LFS
180
+ # (server-side check)
181
+ _should_ignore: bool | None = field(init=False, repr=False, default=None)
182
+
183
+ # set to the remote OID of the file if it has already been uploaded
184
+ # useful to determine if a commit will be empty or not
185
+ _remote_oid: str | None = field(init=False, repr=False, default=None)
186
+
187
+ # set to True once the file has been uploaded as LFS
188
+ _is_uploaded: bool = field(init=False, repr=False, default=False)
189
+
190
+ # set to True once the file has been committed
191
+ _is_committed: bool = field(init=False, repr=False, default=False)
192
+
193
+ def __post_init__(self) -> None:
194
+ """Validates `path_or_fileobj` and compute `upload_info`."""
195
+ self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
196
+
197
+ # Validate `path_or_fileobj` value
198
+ if isinstance(self.path_or_fileobj, Path):
199
+ self.path_or_fileobj = str(self.path_or_fileobj)
200
+ if isinstance(self.path_or_fileobj, str):
201
+ path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj))
202
+ if not os.path.isfile(path_or_fileobj):
203
+ raise ValueError(f"Provided path: '{path_or_fileobj}' is not a file on the local file system")
204
+ elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)):
205
+ # ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode
206
+ raise ValueError(
207
+ "path_or_fileobj must be either an instance of str, bytes or"
208
+ " io.BufferedIOBase. If you passed a file-like object, make sure it is"
209
+ " in binary mode."
210
+ )
211
+ if isinstance(self.path_or_fileobj, io.BufferedIOBase):
212
+ try:
213
+ self.path_or_fileobj.tell()
214
+ self.path_or_fileobj.seek(0, os.SEEK_CUR)
215
+ except (OSError, AttributeError) as exc:
216
+ raise ValueError(
217
+ "path_or_fileobj is a file-like object but does not implement seek() and tell()"
218
+ ) from exc
219
+
220
+ # Compute "upload_info" attribute
221
+ if isinstance(self.path_or_fileobj, str):
222
+ self.upload_info = UploadInfo.from_path(self.path_or_fileobj)
223
+ elif isinstance(self.path_or_fileobj, bytes):
224
+ self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj)
225
+ else:
226
+ self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj)
227
+
228
+ @contextmanager
229
+ def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]:
230
+ """
231
+ A context manager that yields a file-like object allowing to read the underlying
232
+ data behind `path_or_fileobj`.
233
+
234
+ Args:
235
+ with_tqdm (`bool`, *optional*, defaults to `False`):
236
+ If True, iterating over the file object will display a progress bar. Only
237
+ works if the file-like object is a path to a file. Pure bytes and buffers
238
+ are not supported.
239
+
240
+ Example:
241
+
242
+ ```python
243
+ >>> operation = CommitOperationAdd(
244
+ ... path_in_repo="remote/dir/weights.h5",
245
+ ... path_or_fileobj="./local/weights.h5",
246
+ ... )
247
+ CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
248
+
249
+ >>> with operation.as_file() as file:
250
+ ... content = file.read()
251
+
252
+ >>> with operation.as_file(with_tqdm=True) as file:
253
+ ... while True:
254
+ ... data = file.read(1024)
255
+ ... if not data:
256
+ ... break
257
+ config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
258
+
259
+ >>> with operation.as_file(with_tqdm=True) as file:
260
+ ... httpx.put(..., data=file)
261
+ config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
262
+ ```
263
+ """
264
+ if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path):
265
+ if with_tqdm:
266
+ with tqdm_stream_file(self.path_or_fileobj) as file:
267
+ yield file
268
+ else:
269
+ with open(self.path_or_fileobj, "rb") as file:
270
+ yield file
271
+ elif isinstance(self.path_or_fileobj, bytes):
272
+ yield io.BytesIO(self.path_or_fileobj)
273
+ elif isinstance(self.path_or_fileobj, io.BufferedIOBase):
274
+ prev_pos = self.path_or_fileobj.tell()
275
+ yield self.path_or_fileobj
276
+ self.path_or_fileobj.seek(prev_pos, io.SEEK_SET)
277
+
278
+ def b64content(self) -> bytes:
279
+ """
280
+ The base64-encoded content of `path_or_fileobj`
281
+
282
+ Returns: `bytes`
283
+ """
284
+ with self.as_file() as file:
285
+ return base64.b64encode(file.read())
286
+
287
+ @property
288
+ def _local_oid(self) -> str | None:
289
+ """Return the OID of the local file.
290
+
291
+ This OID is then compared to `self._remote_oid` to check if the file has changed compared to the remote one.
292
+ If the file did not change, we won't upload it again to prevent empty commits.
293
+
294
+ For LFS files, the OID corresponds to the SHA256 of the file content (used a LFS ref).
295
+ For regular files, the OID corresponds to the SHA1 of the file content.
296
+ Note: this is slightly different to git OID computation since the oid of an LFS file is usually the git-SHA1 of the
297
+ pointer file content (not the actual file content). However, using the SHA256 is enough to detect changes
298
+ and more convenient client-side.
299
+ """
300
+ if self._upload_mode is None:
301
+ return None
302
+ elif self._upload_mode == "lfs":
303
+ return self.upload_info.sha256.hex()
304
+ else:
305
+ # Regular file => compute sha1
306
+ # => no need to read by chunk since the file is guaranteed to be <=5MB.
307
+ with self.as_file() as file:
308
+ return sha.git_hash(file.read())
309
+
310
+
311
+ def _validate_path_in_repo(path_in_repo: str) -> str:
312
+ # Validate `path_in_repo` value to prevent a server-side issue
313
+ if path_in_repo.startswith("/"):
314
+ path_in_repo = path_in_repo[1:]
315
+ if path_in_repo == "." or path_in_repo == ".." or path_in_repo.startswith("../"):
316
+ raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'")
317
+ if path_in_repo.startswith("./"):
318
+ path_in_repo = path_in_repo[2:]
319
+ for forbidden in FORBIDDEN_FOLDERS:
320
+ if any(part == forbidden for part in path_in_repo.split("/")):
321
+ raise ValueError(
322
+ f"Invalid `path_in_repo` in CommitOperation: cannot update files under a '{forbidden}/' folder (path:"
323
+ f" '{path_in_repo}')."
324
+ )
325
+ return path_in_repo
326
+
327
+
328
+ CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete]
329
+
330
+
331
+ def _warn_on_overwriting_operations(operations: list[CommitOperation]) -> None:
332
+ """
333
+ Warn user when a list of operations is expected to overwrite itself in a single
334
+ commit.
335
+
336
+ Rules:
337
+ - If a filepath is updated by multiple `CommitOperationAdd` operations, a warning
338
+ message is triggered.
339
+ - If a filepath is updated at least once by a `CommitOperationAdd` and then deleted
340
+ by a `CommitOperationDelete`, a warning is triggered.
341
+ - If a `CommitOperationDelete` deletes a filepath that is then updated by a
342
+ `CommitOperationAdd`, no warning is triggered. This is usually useless (no need to
343
+ delete before upload) but can happen if a user deletes an entire folder and then
344
+ add new files to it.
345
+ """
346
+ nb_additions_per_path: dict[str, int] = defaultdict(int)
347
+ for operation in operations:
348
+ path_in_repo = operation.path_in_repo
349
+ if isinstance(operation, CommitOperationAdd):
350
+ if nb_additions_per_path[path_in_repo] > 0:
351
+ warnings.warn(
352
+ "About to update multiple times the same file in the same commit:"
353
+ f" '{path_in_repo}'. This can cause undesired inconsistencies in"
354
+ " your repo."
355
+ )
356
+ nb_additions_per_path[path_in_repo] += 1
357
+ for parent in PurePosixPath(path_in_repo).parents:
358
+ # Also keep track of number of updated files per folder
359
+ # => warns if deleting a folder overwrite some contained files
360
+ nb_additions_per_path[str(parent)] += 1
361
+ if isinstance(operation, CommitOperationDelete):
362
+ if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0:
363
+ if operation.is_folder:
364
+ warnings.warn(
365
+ "About to delete a folder containing files that have just been"
366
+ f" updated within the same commit: '{path_in_repo}'. This can"
367
+ " cause undesired inconsistencies in your repo."
368
+ )
369
+ else:
370
+ warnings.warn(
371
+ "About to delete a file that have just been updated within the"
372
+ f" same commit: '{path_in_repo}'. This can cause undesired"
373
+ " inconsistencies in your repo."
374
+ )
375
+
376
+
377
+ @validate_hf_hub_args
378
+ def _upload_files(
379
+ *,
380
+ additions: list[CommitOperationAdd],
381
+ repo_type: str,
382
+ repo_id: str,
383
+ headers: dict[str, str],
384
+ endpoint: str | None = None,
385
+ num_threads: int = 5,
386
+ revision: str | None = None,
387
+ create_pr: bool | None = None,
388
+ ):
389
+ """
390
+ Uploads the files through the Xet protocol if possible, otherwise through the legacy LFS protocol.
391
+
392
+ The Xet path does not require any Python-side sha256 computation: hashing happens inside `hf_xet`
393
+ while chunking the files (single read pass) and is backfilled on the operations afterwards.
394
+ """
395
+ has_buffered_io_data = any(isinstance(op.path_or_fileobj, io.BufferedIOBase) for op in additions)
396
+ if is_xet_available():
397
+ if not has_buffered_io_data:
398
+ _upload_xet_files(
399
+ additions=additions,
400
+ repo_type=repo_type,
401
+ repo_id=repo_id,
402
+ headers=headers,
403
+ endpoint=endpoint,
404
+ revision=revision,
405
+ create_pr=create_pr,
406
+ )
407
+ return
408
+ logger.warning(
409
+ "Uploading files as a binary IO buffer is not supported by Xet Storage. Falling back to HTTP upload."
410
+ )
411
+
412
+ # Legacy LFS path: sha256 is required by the LFS batch endpoint => compute missing ones (in parallel).
413
+ _compute_missing_sha256s(additions, num_threads=num_threads)
414
+
415
+ lfs_actions: list[dict[str, Any]] = []
416
+ lfs_oid2addop: dict[str, CommitOperationAdd] = {}
417
+ for chunk in chunk_iterable(additions, chunk_size=UPLOAD_BATCH_MAX_NUM_FILES):
418
+ chunk_list = [op for op in chunk]
419
+ actions_chunk, errors_chunk, _ = post_lfs_batch_info(
420
+ upload_infos=[op.upload_info for op in chunk_list],
421
+ repo_id=repo_id,
422
+ repo_type=repo_type,
423
+ revision=revision,
424
+ endpoint=endpoint,
425
+ headers=headers,
426
+ token=None, # already passed in 'headers'
427
+ transfers=["basic", "multipart"],
428
+ )
429
+ if errors_chunk:
430
+ message = "\n".join(
431
+ [
432
+ f"Encountered error for file with OID {err.get('oid')}: `{err.get('error', {}).get('message')}"
433
+ for err in errors_chunk
434
+ ]
435
+ )
436
+ raise ValueError(f"LFS batch API returned errors:\n{message}")
437
+ lfs_actions.extend(actions_chunk)
438
+ for op in chunk_list:
439
+ lfs_oid2addop[op.upload_info.sha256.hex()] = op
440
+
441
+ if len(lfs_actions) > 0:
442
+ _upload_lfs_files(
443
+ actions=lfs_actions,
444
+ oid2addop=lfs_oid2addop,
445
+ headers=headers,
446
+ endpoint=endpoint,
447
+ num_threads=num_threads,
448
+ )
449
+
450
+
451
+ def _compute_missing_sha256s(additions: list[CommitOperationAdd], num_threads: int) -> None:
452
+ """Compute the sha256 of the operations that don't have one yet, in parallel."""
453
+ not_hashed = [op for op in additions if not op.upload_info.is_hashed]
454
+ if len(not_hashed) == 0:
455
+ return
456
+ logger.info(f"Computing sha256 for {len(not_hashed)} files.")
457
+ if len(not_hashed) == 1:
458
+ _ = not_hashed[0].upload_info.sha256
459
+ return
460
+ with ThreadPoolExecutor(max_workers=num_threads) as executor:
461
+ list(executor.map(lambda op: op.upload_info.sha256, not_hashed))
462
+
463
+
464
+ @validate_hf_hub_args
465
+ def _upload_lfs_files(
466
+ *,
467
+ actions: list[dict[str, Any]],
468
+ oid2addop: dict[str, CommitOperationAdd],
469
+ headers: dict[str, str],
470
+ endpoint: str | None = None,
471
+ num_threads: int = 5,
472
+ ):
473
+ """
474
+ Uploads the content of `additions` to the Hub using the large file storage protocol.
475
+
476
+ Relevant external documentation:
477
+ - LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
478
+
479
+ Args:
480
+ actions (`list[dict[str, Any]]`):
481
+ LFS batch actions returned by the server.
482
+ oid2addop (`dict[str, CommitOperationAdd]`):
483
+ A dictionary mapping the OID of the file to the corresponding `CommitOperationAdd` object.
484
+ headers (`dict[str, str]`):
485
+ Headers to use for the request, including authorization headers and user agent.
486
+ endpoint (`str`, *optional*):
487
+ The endpoint to use for the request. Defaults to `constants.ENDPOINT`.
488
+ num_threads (`int`, *optional*):
489
+ The number of concurrent threads to use when uploading. Defaults to 5.
490
+
491
+ Raises:
492
+ [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
493
+ If an upload failed for any reason
494
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
495
+ Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
496
+ repo_id (`str`):
497
+ A namespace (user or an organization) and a repo name separated
498
+ by a `/`.
499
+ headers (`dict[str, str]`):
500
+ Headers to use for the request, including authorization headers and user agent.
501
+ num_threads (`int`, *optional*):
502
+ The number of concurrent threads to use when uploading. Defaults to 5.
503
+ revision (`str`, *optional*):
504
+ The git revision to upload to.
505
+
506
+ Raises:
507
+ [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
508
+ If an upload failed for any reason
509
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
510
+ If the server returns malformed responses
511
+ [`HfHubHTTPError`]
512
+ If the LFS batch endpoint returned an HTTP error.
513
+ """
514
+ # Filter out files already present upstream
515
+ filtered_actions = []
516
+ for action in actions:
517
+ if action.get("actions") is None:
518
+ logger.debug(
519
+ f"Content of file {oid2addop[action['oid']].path_in_repo} is already present upstream - skipping upload."
520
+ )
521
+ else:
522
+ filtered_actions.append(action)
523
+
524
+ # Upload according to server-provided actions
525
+ def _wrapped_lfs_upload(batch_action) -> None:
526
+ try:
527
+ operation = oid2addop[batch_action["oid"]]
528
+ lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint)
529
+ except Exception as exc:
530
+ raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc
531
+
532
+ if len(filtered_actions) == 1:
533
+ logger.debug("Uploading 1 LFS file to the Hub")
534
+ _wrapped_lfs_upload(filtered_actions[0])
535
+ else:
536
+ logger.debug(
537
+ f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently"
538
+ )
539
+ thread_map(
540
+ _wrapped_lfs_upload,
541
+ filtered_actions,
542
+ desc=f"Upload {len(filtered_actions)} LFS files",
543
+ max_workers=num_threads,
544
+ tqdm_class=hf_tqdm,
545
+ )
546
+
547
+
548
+ @validate_hf_hub_args
549
+ def _upload_xet_files(
550
+ *,
551
+ additions: list[CommitOperationAdd],
552
+ repo_type: str,
553
+ repo_id: str,
554
+ headers: dict[str, str],
555
+ endpoint: str | None = None,
556
+ revision: str | None = None,
557
+ create_pr: bool | None = None,
558
+ ):
559
+ """
560
+ Uploads the content of `additions` to the Hub using the xet storage protocol.
561
+ This chunks the files and deduplicates the chunks before uploading them to xetcas storage.
562
+
563
+ Args:
564
+ additions (`` of `CommitOperationAdd`):
565
+ The files to be uploaded.
566
+ repo_type (`str`):
567
+ Type of the repo (e.g. `"model"`, `"dataset"`, `"space"`).
568
+ repo_id (`str`):
569
+ A namespace (user or an organization) and a repo name separated
570
+ by a `/`.
571
+ headers (`dict[str, str]`):
572
+ Headers to use for the request, including authorization headers and user agent.
573
+ endpoint: (`str`, *optional*):
574
+ The endpoint to use for the xetcas service. Defaults to `constants.ENDPOINT`.
575
+ revision (`str`, *optional*):
576
+ The git revision to upload to.
577
+ create_pr (`bool`, *optional*):
578
+ Whether or not to create a Pull Request with that commit.
579
+
580
+ Raises:
581
+ [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
582
+ If an upload failed for any reason.
583
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
584
+ If the server returns malformed responses or if the user is unauthorized to upload to xet storage.
585
+ [`HfHubHTTPError`]
586
+ If the LFS batch endpoint returned an HTTP error.
587
+
588
+ **How it works:**
589
+ The file upload system uses Xet storage, which is a content-addressable storage system that breaks files into chunks
590
+ for efficient storage and transfer.
591
+
592
+ ``session.new_upload_commit()`` manages uploading files by:
593
+ - Registering upload tasks and starting upload immediately in the background
594
+ - Breaking files into smaller chunks for efficient storage
595
+ - Avoiding duplicate storage by recognizing identical chunks across files
596
+ - Connecting to a storage server (CAS server) that manages these chunks
597
+
598
+ Authentication works transparently: the upload commit accepts a ``token_refresh_url``
599
+ that is used to refresh the short-lived xet write token as needed.
600
+
601
+ The upload process works like this:
602
+ 1. Upload tasks run in parallel:
603
+ 1.1. Read the file content from a path, bytes array, or a stream.
604
+ 1.2. Split the file content into smaller chunks based on content patterns: each chunk gets a unique ID based on what's in it.
605
+ 1.3. For each chunk:
606
+ - Check if it already exists in storage.
607
+ - Skip uploading chunks that already exist.
608
+ 1.4. Group chunks into larger blocks for efficient transfer.
609
+ 1.5. Upload these blocks to the storage server.
610
+ 1.6. Assemble the file manifest locally and send it to the server for validation.
611
+ 2. Return reference files that contain information about the uploaded files, which can be used later to download them.
612
+ """
613
+ if len(additions) == 0:
614
+ return
615
+
616
+ # at this point, we know that hf_xet is installed
617
+ from .utils._xet import (
618
+ XetTokenType,
619
+ abort_xet_session,
620
+ get_xet_session,
621
+ xet_connection_info_refresh_url,
622
+ xet_headers_without_auth,
623
+ )
624
+ from .utils._xet_progress_reporting import XetUploadProgressReporter
625
+
626
+ refresh_url = xet_connection_info_refresh_url(
627
+ token_type=XetTokenType.WRITE,
628
+ repo_id=repo_id,
629
+ repo_type=repo_type,
630
+ revision=revision,
631
+ endpoint=endpoint,
632
+ )
633
+ if create_pr:
634
+ refresh_url += "?create_pr=1"
635
+
636
+ xet_headers = xet_headers_without_auth(headers)
637
+
638
+ import hf_xet
639
+
640
+ session = get_xet_session()
641
+ progress = None
642
+
643
+ def _sha256_arg(op: CommitOperationAdd):
644
+ # If the sha256 is already known, pass it to avoid recomputation. Otherwise let hf_xet
645
+ # compute it while chunking the file (single read pass) and backfill it afterwards.
646
+ return op.upload_info.sha256.hex() if op.upload_info.is_hashed else hf_xet.COMPUTE_SHA256
647
+
648
+ try:
649
+ if not are_progress_bars_disabled():
650
+ progress = XetUploadProgressReporter()
651
+ progress_callback = progress.update_progress
652
+ else:
653
+ progress_callback = None
654
+
655
+ all_bytes_ops = [op for op in additions if isinstance(op.path_or_fileobj, bytes)]
656
+ all_paths_ops = [op for op in additions if isinstance(op.path_or_fileobj, (str, Path))]
657
+
658
+ handles: list[tuple[CommitOperationAdd, Any]] = []
659
+ with session.new_upload_commit(
660
+ token_refresh_url=refresh_url,
661
+ token_refresh_headers=headers,
662
+ custom_headers=xet_headers,
663
+ progress_callback=progress_callback,
664
+ ) as commit:
665
+ for op in all_paths_ops:
666
+ handles.append((op, commit.start_upload_file(str(op.path_or_fileobj), sha256=_sha256_arg(op))))
667
+ for op in all_bytes_ops:
668
+ handles.append((op, commit.start_upload_bytes(op.path_or_fileobj, sha256=_sha256_arg(op))))
669
+
670
+ # Backfill sha256 computed by hf_xet (needed later for the commit payload).
671
+ for op, handle in handles:
672
+ if not op.upload_info.is_hashed:
673
+ op.upload_info.sha256 = bytes.fromhex(handle.result().xet_info.sha256)
674
+ except KeyboardInterrupt:
675
+ abort_xet_session()
676
+ raise
677
+ finally:
678
+ if progress is not None:
679
+ progress.close()
680
+
681
+
682
+ def _validate_preupload_info(preupload_info: dict):
683
+ files = preupload_info.get("files")
684
+ if not isinstance(files, list):
685
+ raise ValueError("preupload_info is improperly formatted")
686
+ for file_info in files:
687
+ if not (
688
+ isinstance(file_info, dict)
689
+ and isinstance(file_info.get("path"), str)
690
+ and isinstance(file_info.get("uploadMode"), str)
691
+ and (file_info["uploadMode"] in ("lfs", "regular"))
692
+ ):
693
+ raise ValueError("preupload_info is improperly formatted:")
694
+ return preupload_info
695
+
696
+
697
+ @validate_hf_hub_args
698
+ def _fetch_upload_modes(
699
+ additions: Iterable[CommitOperationAdd],
700
+ repo_type: str,
701
+ repo_id: str,
702
+ headers: dict[str, str],
703
+ revision: str,
704
+ endpoint: str | None = None,
705
+ create_pr: bool = False,
706
+ gitignore_content: str | None = None,
707
+ ) -> None:
708
+ """
709
+ Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob,
710
+ as a git LFS blob, or as a XET file. Input `additions` are mutated in-place with the upload mode.
711
+
712
+ Args:
713
+ additions (`Iterable` of :class:`CommitOperationAdd`):
714
+ Iterable of :class:`CommitOperationAdd` describing the files to
715
+ upload to the Hub.
716
+ repo_type (`str`):
717
+ Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
718
+ repo_id (`str`):
719
+ A namespace (user or an organization) and a repo name separated
720
+ by a `/`.
721
+ headers (`dict[str, str]`):
722
+ Headers to use for the request, including authorization headers and user agent.
723
+ revision (`str`):
724
+ The git revision to upload the files to. Can be any valid git revision.
725
+ gitignore_content (`str`, *optional*):
726
+ The content of the `.gitignore` file to know which files should be ignored. The order of priority
727
+ is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
728
+ in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
729
+ (if any).
730
+ Raises:
731
+ [`~utils.HfHubHTTPError`]
732
+ If the Hub API returned an error.
733
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
734
+ If the Hub API response is improperly formatted.
735
+ """
736
+ endpoint = endpoint if endpoint is not None else constants.ENDPOINT
737
+
738
+ # Fetch upload mode (LFS or regular) chunk by chunk.
739
+ upload_modes: dict[str, UploadMode] = {}
740
+ should_ignore_info: dict[str, bool] = {}
741
+ oid_info: dict[str, str | None] = {}
742
+
743
+ for chunk in chunk_iterable(additions, 256):
744
+ payload: dict = {
745
+ "files": [
746
+ {
747
+ "path": op.path_in_repo,
748
+ "sample": base64.b64encode(op.upload_info.sample).decode("ascii"),
749
+ "size": op.upload_info.size,
750
+ }
751
+ for op in chunk
752
+ ]
753
+ }
754
+ if gitignore_content is not None:
755
+ payload["gitIgnore"] = gitignore_content
756
+
757
+ resp = http_backoff(
758
+ "POST",
759
+ f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}",
760
+ json=payload,
761
+ headers=headers,
762
+ params={"create_pr": "1"} if create_pr else None,
763
+ )
764
+ hf_raise_for_status(resp)
765
+ preupload_info = _validate_preupload_info(resp.json())
766
+ upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]})
767
+ should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]})
768
+ oid_info.update(**{file["path"]: file.get("oid") for file in preupload_info["files"]})
769
+
770
+ # Set upload mode for each addition operation
771
+ for addition in additions:
772
+ addition._upload_mode = upload_modes[addition.path_in_repo]
773
+ addition._should_ignore = should_ignore_info[addition.path_in_repo]
774
+ addition._remote_oid = oid_info[addition.path_in_repo]
775
+
776
+ # Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented)
777
+ # => empty files are uploaded as "regular" to still allow users to commit them.
778
+ for addition in additions:
779
+ if addition.upload_info.size == 0:
780
+ addition._upload_mode = "regular"
781
+
782
+
783
+ class _CopySource(NamedTuple):
784
+ src_repo_id: str | None
785
+ src_repo_type: str | None
786
+ path: str
787
+ revision: str | None
788
+
789
+
790
+ @validate_hf_hub_args
791
+ def _fetch_files_to_copy(
792
+ copies: Iterable[CommitOperationCopy],
793
+ repo_type: str,
794
+ repo_id: str,
795
+ headers: dict[str, str],
796
+ revision: str,
797
+ endpoint: str | None = None,
798
+ ) -> dict[_CopySource, Union["RepoFile", bytes]]:
799
+ """
800
+ Fetch information about the files to copy.
801
+
802
+ For LFS files, we only need their metadata (file size and sha256) while for regular files
803
+ we need to download the raw content from the Hub.
804
+
805
+ Args:
806
+ copies (`Iterable` of :class:`CommitOperationCopy`):
807
+ Iterable of :class:`CommitOperationCopy` describing the files to
808
+ copy on the Hub.
809
+ repo_type (`str`):
810
+ Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
811
+ repo_id (`str`):
812
+ A namespace (user or an organization) and a repo name separated
813
+ by a `/`.
814
+ headers (`dict[str, str]`):
815
+ Headers to use for the request, including authorization headers and user agent.
816
+ revision (`str`):
817
+ The git revision to upload the files to. Can be any valid git revision.
818
+
819
+ Returns: `dict[_CopySource, Union[RepoFile, bytes]]]`
820
+ Key is `(src_repo_id, src_repo_type, path, revision)`. For intra-repo copies,
821
+ `src_repo_id` and `src_repo_type` are `None`.
822
+ Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files).
823
+
824
+ Raises:
825
+ [`~utils.HfHubHTTPError`]
826
+ If the Hub API returned an error.
827
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
828
+ If the Hub API response is improperly formatted.
829
+ """
830
+ from .hf_api import HfApi, RepoFolder
831
+
832
+ hf_api = HfApi(endpoint=endpoint, headers=headers)
833
+ copies = list(copies)
834
+ files_to_copy: dict[_CopySource, Union["RepoFile", bytes]] = {}
835
+ oid_info: dict[tuple[str, str | None], str | None] = {}
836
+
837
+ # 1. Fetch OIDs for destination paths in batches.
838
+ dest_paths = [op.path_in_repo for op in copies]
839
+ for batch in chunk_iterable(dest_paths, FETCH_LFS_BATCH_SIZE):
840
+ dest_repo_files = hf_api.get_paths_info(
841
+ repo_id=repo_id,
842
+ paths=list(batch),
843
+ revision=revision,
844
+ repo_type=repo_type,
845
+ )
846
+ for file in dest_repo_files:
847
+ if not isinstance(file, RepoFolder):
848
+ oid_info[(file.path, revision)] = file.blob_id
849
+
850
+ # 2. Fetch source file info, grouped by (src_repo_id, src_repo_type, src_revision).
851
+ copies.sort(key=lambda op: (op.src_repo_id or "", op.src_repo_type or "", op.src_revision or ""))
852
+ for (src_repo_id_key, src_repo_type_key, src_revision_key), group in groupby(
853
+ copies, key=lambda op: (op.src_repo_id, op.src_repo_type, op.src_revision)
854
+ ):
855
+ operations = list(group)
856
+ is_cross_repo = src_repo_id_key is not None
857
+ eff_repo_id = src_repo_id_key or repo_id
858
+ eff_repo_type = src_repo_type_key or repo_type
859
+ eff_revision = src_revision_key or ("main" if is_cross_repo else revision)
860
+
861
+ src_paths = [op.src_path_in_repo for op in operations]
862
+ for paths_batch in chunk_iterable(src_paths, FETCH_LFS_BATCH_SIZE):
863
+ src_repo_files = hf_api.get_paths_info(
864
+ repo_id=eff_repo_id,
865
+ paths=list(paths_batch),
866
+ revision=eff_revision,
867
+ repo_type=eff_repo_type,
868
+ )
869
+ for src_repo_file in src_repo_files:
870
+ if isinstance(src_repo_file, RepoFolder):
871
+ raise NotImplementedError("Copying a folder is not implemented.")
872
+ source = _CopySource(src_repo_id_key, src_repo_type_key, src_repo_file.path, src_revision_key)
873
+ if src_repo_file.lfs:
874
+ files_to_copy[source] = src_repo_file
875
+ else:
876
+ url = hf_hub_url(
877
+ endpoint=endpoint,
878
+ repo_type=eff_repo_type,
879
+ repo_id=eff_repo_id,
880
+ revision=eff_revision,
881
+ filename=src_repo_file.path,
882
+ )
883
+ response = get_session().get(url, headers=headers)
884
+ hf_raise_for_status(response)
885
+ files_to_copy[source] = response.content
886
+ if not is_cross_repo:
887
+ oid_info[(src_repo_file.path, src_revision_key)] = src_repo_file.blob_id
888
+
889
+ for operation in operations:
890
+ key = _CopySource(src_repo_id_key, src_repo_type_key, operation.src_path_in_repo, src_revision_key)
891
+ if key not in files_to_copy:
892
+ source_desc = f" from {eff_repo_type}s/{eff_repo_id}" if is_cross_repo else ""
893
+ raise EntryNotFoundError(
894
+ f"Cannot copy {operation.src_path_in_repo} at revision "
895
+ f"{eff_revision}{source_desc}: file is missing on repo."
896
+ )
897
+ operation._dest_oid = oid_info.get((operation.path_in_repo, revision))
898
+ if not is_cross_repo:
899
+ operation._src_oid = oid_info.get((operation.src_path_in_repo, operation.src_revision))
900
+
901
+ return files_to_copy
902
+
903
+
904
+ def _prepare_commit_payload(
905
+ operations: Iterable[CommitOperation],
906
+ files_to_copy: dict[_CopySource, Union["RepoFile", bytes]],
907
+ commit_message: str,
908
+ commit_description: str | None = None,
909
+ parent_commit: str | None = None,
910
+ ) -> Iterable[dict[str, Any]]:
911
+ """
912
+ Builds the payload to POST to the `/commit` API of the Hub.
913
+
914
+ Payload is returned as an iterator so that it can be streamed as a ndjson in the
915
+ POST request.
916
+
917
+ For more information, see:
918
+ - https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
919
+ - http://ndjson.org/
920
+ """
921
+ commit_description = commit_description if commit_description is not None else ""
922
+
923
+ # 1. Send a header item with the commit metadata
924
+ header_value = {"summary": commit_message, "description": commit_description}
925
+ if parent_commit is not None:
926
+ header_value["parentCommit"] = parent_commit
927
+ yield {"key": "header", "value": header_value}
928
+
929
+ nb_ignored_files = 0
930
+
931
+ # 2. Send operations, one per line
932
+ for operation in operations:
933
+ # Skip ignored files
934
+ if isinstance(operation, CommitOperationAdd) and operation._should_ignore:
935
+ logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).")
936
+ nb_ignored_files += 1
937
+ continue
938
+
939
+ # 2.a. Case adding a regular file
940
+ if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular":
941
+ yield {
942
+ "key": "file",
943
+ "value": {
944
+ "content": operation.b64content().decode(),
945
+ "path": operation.path_in_repo,
946
+ "encoding": "base64",
947
+ },
948
+ }
949
+ # 2.b. Case adding an LFS file
950
+ elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs":
951
+ yield {
952
+ "key": "lfsFile",
953
+ "value": {
954
+ "path": operation.path_in_repo,
955
+ "algo": "sha256",
956
+ "oid": operation.upload_info.sha256.hex(),
957
+ "size": operation.upload_info.size,
958
+ },
959
+ }
960
+ # 2.c. Case deleting a file or folder
961
+ elif isinstance(operation, CommitOperationDelete):
962
+ yield {
963
+ "key": "deletedFolder" if operation.is_folder else "deletedFile",
964
+ "value": {"path": operation.path_in_repo},
965
+ }
966
+ # 2.d. Case copying a file or folder
967
+ elif isinstance(operation, CommitOperationCopy):
968
+ source = _CopySource(
969
+ operation.src_repo_id,
970
+ operation.src_repo_type,
971
+ operation.src_path_in_repo,
972
+ operation.src_revision,
973
+ )
974
+ file_to_copy = files_to_copy[source]
975
+ if isinstance(file_to_copy, bytes):
976
+ yield {
977
+ "key": "file",
978
+ "value": {
979
+ "content": base64.b64encode(file_to_copy).decode(),
980
+ "path": operation.path_in_repo,
981
+ "encoding": "base64",
982
+ },
983
+ }
984
+ elif file_to_copy.lfs:
985
+ yield {
986
+ "key": "lfsFile",
987
+ "value": {
988
+ "path": operation.path_in_repo,
989
+ "algo": "sha256",
990
+ "oid": file_to_copy.lfs.sha256,
991
+ },
992
+ }
993
+ else:
994
+ raise ValueError(
995
+ "Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info."
996
+ )
997
+ # 2.e. Never expected to happen
998
+ else:
999
+ raise ValueError(
1000
+ f"Unknown operation to commit. Operation: {operation}. Upload mode:"
1001
+ f" {getattr(operation, '_upload_mode', None)}"
1002
+ )
1003
+
1004
+ if nb_ignored_files > 0:
1005
+ logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).")
1006
+
1007
+
1008
+ def _send_commit(
1009
+ *,
1010
+ operations: Iterable[CommitOperation],
1011
+ files_to_copy: dict[_CopySource, Union["RepoFile", bytes]],
1012
+ commit_message: str,
1013
+ commit_description: str,
1014
+ repo_type: str,
1015
+ repo_id: str,
1016
+ headers: dict[str, str],
1017
+ revision: str,
1018
+ endpoint: str | None = None,
1019
+ parent_commit: str | None = None,
1020
+ create_pr: bool = False,
1021
+ hot_reload: bool = False,
1022
+ retry_on_error: bool = False,
1023
+ ) -> "CommitInfo":
1024
+ """
1025
+ Build the ndjson payload for `operations` and POST it to the `/commit` endpoint of the Hub.
1026
+
1027
+ `revision` must already be URL-quoted. Operations must be ready to commit: upload modes fetched
1028
+ and LFS/Xet content uploaded.
1029
+
1030
+ If `retry_on_error` is `True`, the POST is retried with exponential backoff on transient errors.
1031
+ Caution: if a commit succeeds but its response is lost, the retry will create a duplicate commit
1032
+ (and a duplicate pull request if `create_pr` is set) — only enable it when this is acceptable.
1033
+
1034
+ Returns a [`CommitInfo`] built from the server response.
1035
+
1036
+ Raises:
1037
+ [`~utils.HfHubHTTPError`]
1038
+ If the Hub API returned an error.
1039
+ """
1040
+ endpoint = endpoint if endpoint is not None else constants.ENDPOINT
1041
+ payload = _prepare_commit_payload(
1042
+ operations=operations,
1043
+ files_to_copy=files_to_copy,
1044
+ commit_message=commit_message,
1045
+ commit_description=commit_description,
1046
+ parent_commit=parent_commit,
1047
+ )
1048
+ data = b"".join(json.dumps(item).encode() + b"\n" for item in payload)
1049
+ # See https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
1050
+ headers = {"Content-Type": "application/x-ndjson", **headers}
1051
+ url = f"{endpoint}/api/{repo_type}s/{repo_id}/commit/{revision}"
1052
+
1053
+ params: dict[str, str] = {}
1054
+ if create_pr:
1055
+ params["create_pr"] = "1"
1056
+ if hot_reload:
1057
+ params["hot_reload"] = "1"
1058
+
1059
+ if retry_on_error:
1060
+ response = http_backoff("POST", url, headers=headers, content=data, params=params)
1061
+ else:
1062
+ response = get_session().post(url, headers=headers, content=data, params=params)
1063
+ hf_raise_for_status(response, endpoint_name="commit")
1064
+
1065
+ commit_data = response.json()
1066
+ from .hf_api import CommitInfo
1067
+
1068
+ return CommitInfo(
1069
+ commit_url=commit_data["commitUrl"],
1070
+ commit_message=commit_message,
1071
+ commit_description=commit_description,
1072
+ oid=commit_data["commitOid"],
1073
+ pr_url=commit_data["pullRequestUrl"] if create_pr else None,
1074
+ _endpoint=endpoint,
1075
+ )
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_commit_scheduler.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import logging
3
+ import os
4
+ import time
5
+ from concurrent.futures import Future
6
+ from dataclasses import dataclass
7
+ from io import SEEK_END, SEEK_SET, BytesIO
8
+ from pathlib import Path
9
+ from threading import Lock, Thread
10
+ from typing import Optional
11
+
12
+ from .hf_api import DEFAULT_IGNORE_PATTERNS, CommitInfo, CommitOperationAdd, HfApi
13
+ from .utils import filter_repo_objects
14
+
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class _FileToUpload:
21
+ """Temporary dataclass to store info about files to upload. Not meant to be used directly."""
22
+
23
+ local_path: Path
24
+ path_in_repo: str
25
+ size_limit: int
26
+ last_modified: float
27
+
28
+
29
+ class CommitScheduler:
30
+ """
31
+ Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
32
+
33
+ The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is
34
+ properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually
35
+ with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
36
+ to learn more about how to use it.
37
+
38
+ Args:
39
+ repo_id (`str`):
40
+ The id of the repo to commit to.
41
+ folder_path (`str` or `Path`):
42
+ Path to the local folder to upload regularly.
43
+ every (`int` or `float`, *optional*):
44
+ The number of minutes between each commit. Defaults to 5 minutes.
45
+ path_in_repo (`str`, *optional*):
46
+ Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
47
+ of the repository.
48
+ repo_type (`str`, *optional*):
49
+ The type of the repo to commit to. Defaults to `model`.
50
+ revision (`str`, *optional*):
51
+ The revision of the repo to commit to. Defaults to `main`.
52
+ private (`bool`, *optional*):
53
+ Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
54
+ token (`str`, *optional*):
55
+ The token to use to commit to the repo. Defaults to the token saved on the machine.
56
+ allow_patterns (`list[str]` or `str`, *optional*):
57
+ If provided, only files matching at least one pattern are uploaded.
58
+ ignore_patterns (`list[str]` or `str`, *optional*):
59
+ If provided, files matching any of the patterns are not uploaded.
60
+ squash_history (`bool`, *optional*):
61
+ Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
62
+ useful to avoid degraded performances on the repo when it grows too large.
63
+ hf_api (`HfApi`, *optional*):
64
+ The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
65
+
66
+ Example:
67
+ ```py
68
+ >>> from pathlib import Path
69
+ >>> from huggingface_hub import CommitScheduler
70
+
71
+ # Scheduler uploads every 10 minutes
72
+ >>> csv_path = Path("watched_folder/data.csv")
73
+ >>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
74
+
75
+ >>> with csv_path.open("a") as f:
76
+ ... f.write("first line")
77
+
78
+ # Some time later (...)
79
+ >>> with csv_path.open("a") as f:
80
+ ... f.write("second line")
81
+ ```
82
+
83
+ Example using a context manager:
84
+ ```py
85
+ >>> from pathlib import Path
86
+ >>> from huggingface_hub import CommitScheduler
87
+
88
+ >>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
89
+ ... csv_path = Path("watched_folder/data.csv")
90
+ ... with csv_path.open("a") as f:
91
+ ... f.write("first line")
92
+ ... (...)
93
+ ... with csv_path.open("a") as f:
94
+ ... f.write("second line")
95
+
96
+ # Scheduler is now stopped and last commit have been triggered
97
+ ```
98
+ """
99
+
100
+ def __init__(
101
+ self,
102
+ *,
103
+ repo_id: str,
104
+ folder_path: str | Path,
105
+ every: int | float = 5,
106
+ path_in_repo: str | None = None,
107
+ repo_type: str | None = None,
108
+ revision: str | None = None,
109
+ private: bool | None = None,
110
+ token: str | None = None,
111
+ allow_patterns: list[str] | str | None = None,
112
+ ignore_patterns: list[str] | str | None = None,
113
+ squash_history: bool = False,
114
+ hf_api: Optional["HfApi"] = None,
115
+ ) -> None:
116
+ self.api = hf_api or HfApi(token=token)
117
+
118
+ # Folder
119
+ self.folder_path = Path(folder_path).expanduser().resolve()
120
+ self.path_in_repo = path_in_repo or ""
121
+ self.allow_patterns = allow_patterns
122
+
123
+ if ignore_patterns is None:
124
+ ignore_patterns = []
125
+ elif isinstance(ignore_patterns, str):
126
+ ignore_patterns = [ignore_patterns]
127
+ self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
128
+
129
+ if self.folder_path.is_file():
130
+ raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.")
131
+ self.folder_path.mkdir(parents=True, exist_ok=True)
132
+
133
+ # Repository
134
+ repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True)
135
+ self.repo_id = repo_url.repo_id
136
+ self.repo_type = repo_type
137
+ self.revision = revision
138
+ self.token = token
139
+
140
+ # Keep track of already uploaded files
141
+ self.last_uploaded: dict[Path, float] = {} # key is local path, value is timestamp
142
+
143
+ # Scheduler
144
+ if not every > 0:
145
+ raise ValueError(f"'every' must be a positive integer, not '{every}'.")
146
+ self.lock = Lock()
147
+ self.every = every
148
+ self.squash_history = squash_history
149
+
150
+ logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.")
151
+ self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True)
152
+ self._scheduler_thread.start()
153
+ atexit.register(self._push_to_hub)
154
+
155
+ self.__stopped = False
156
+
157
+ def stop(self) -> None:
158
+ """Stop the scheduler.
159
+
160
+ A stopped scheduler cannot be restarted. Mostly for tests purposes.
161
+ """
162
+ self.__stopped = True
163
+
164
+ def __enter__(self) -> "CommitScheduler":
165
+ return self
166
+
167
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
168
+ # Upload last changes before exiting
169
+ self.trigger().result()
170
+ self.stop()
171
+ return
172
+
173
+ def _run_scheduler(self) -> None:
174
+ """Dumb thread waiting between each scheduled push to Hub."""
175
+ while True:
176
+ self.last_future = self.trigger()
177
+ time.sleep(self.every * 60)
178
+ if self.__stopped:
179
+ break
180
+
181
+ def trigger(self) -> Future:
182
+ """Trigger a `push_to_hub` and return a future.
183
+
184
+ This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
185
+ immediately, without waiting for the next scheduled commit.
186
+ """
187
+ return self.api.run_as_future(self._push_to_hub)
188
+
189
+ def _push_to_hub(self) -> CommitInfo | None:
190
+ if self.__stopped: # If stopped, already scheduled commits are ignored
191
+ return None
192
+
193
+ logger.info("(Background) scheduled commit triggered.")
194
+ try:
195
+ value = self.push_to_hub()
196
+ if self.squash_history:
197
+ logger.info("(Background) squashing repo history.")
198
+ self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision)
199
+ return value
200
+ except Exception as e:
201
+ logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced
202
+ raise
203
+
204
+ def push_to_hub(self) -> CommitInfo | None:
205
+ """
206
+ Push folder to the Hub and return the commit info.
207
+
208
+ > [!WARNING]
209
+ > This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
210
+ > queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
211
+ > issues.
212
+
213
+ The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
214
+ uploads only changed files. If no changes are found, the method returns without committing anything. If you want
215
+ to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
216
+ for example to compress data together in a single file before committing. For more details and examples, check
217
+ out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
218
+ """
219
+ # Check files to upload (with lock)
220
+ with self.lock:
221
+ logger.debug("Listing files to upload for scheduled commit.")
222
+
223
+ # List files from folder (taken from `_prepare_upload_folder_additions`)
224
+ relpath_to_abspath = {
225
+ path.relative_to(self.folder_path).as_posix(): path
226
+ for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic
227
+ if path.is_file()
228
+ }
229
+ prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
230
+
231
+ # Filter with pattern + filter out unchanged files + retrieve current file size
232
+ files_to_upload: list[_FileToUpload] = []
233
+ for relpath in filter_repo_objects(
234
+ relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns
235
+ ):
236
+ local_path = relpath_to_abspath[relpath]
237
+ stat = local_path.stat()
238
+ if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime:
239
+ files_to_upload.append(
240
+ _FileToUpload(
241
+ local_path=local_path,
242
+ path_in_repo=prefix + relpath,
243
+ size_limit=stat.st_size,
244
+ last_modified=stat.st_mtime,
245
+ )
246
+ )
247
+
248
+ # Return if nothing to upload
249
+ if len(files_to_upload) == 0:
250
+ logger.debug("Dropping schedule commit: no changed file to upload.")
251
+ return None
252
+
253
+ # Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size)
254
+ logger.debug("Removing unchanged files since previous scheduled commit.")
255
+ add_operations = [
256
+ CommitOperationAdd(
257
+ # Cap the file to its current size, even if the user append data to it while a scheduled commit is happening
258
+ path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit),
259
+ path_in_repo=file_to_upload.path_in_repo,
260
+ )
261
+ for file_to_upload in files_to_upload
262
+ ]
263
+
264
+ # Upload files (append mode expected - no need for lock)
265
+ logger.debug("Uploading files for scheduled commit.")
266
+ commit_info = self.api.create_commit(
267
+ repo_id=self.repo_id,
268
+ repo_type=self.repo_type,
269
+ operations=add_operations,
270
+ commit_message="Scheduled Commit",
271
+ revision=self.revision,
272
+ )
273
+
274
+ # Successful commit: keep track of the latest "last_modified" for each file
275
+ for file in files_to_upload:
276
+ self.last_uploaded[file.local_path] = file.last_modified
277
+ return commit_info
278
+
279
+
280
+ class PartialFileIO(BytesIO):
281
+ """A file-like object that reads only the first part of a file.
282
+
283
+ Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the
284
+ file is uploaded (i.e. the part that was available when the filesystem was first scanned).
285
+
286
+ In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal
287
+ disturbance for the user. The object is passed to `CommitOperationAdd`.
288
+
289
+ Only supports `read`, `tell` and `seek` methods.
290
+
291
+ Args:
292
+ file_path (`str` or `Path`):
293
+ Path to the file to read.
294
+ size_limit (`int`):
295
+ The maximum number of bytes to read from the file. If the file is larger than this, only the first part
296
+ will be read (and uploaded).
297
+ """
298
+
299
+ def __init__(self, file_path: str | Path, size_limit: int) -> None:
300
+ self._file_path = Path(file_path)
301
+ self._file = self._file_path.open("rb")
302
+ self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
303
+
304
+ def __del__(self) -> None:
305
+ self._file.close()
306
+ return super().__del__()
307
+
308
+ def __repr__(self) -> str:
309
+ return f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
310
+
311
+ def __len__(self) -> int:
312
+ return self._size_limit
313
+
314
+ def __getattribute__(self, name: str):
315
+ if name.startswith("_") or name in ("read", "tell", "seek", "fileno"): # only 4 public methods supported
316
+ return super().__getattribute__(name)
317
+ raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
318
+
319
+ def fileno(self):
320
+ raise AttributeError("PartialFileIO does not have a fileno.")
321
+
322
+ def tell(self) -> int:
323
+ """Return the current file position."""
324
+ return self._file.tell()
325
+
326
+ def seek(self, __offset: int, __whence: int = SEEK_SET) -> int:
327
+ """Change the stream position to the given offset.
328
+
329
+ Behavior is the same as a regular file, except that the position is capped to the size limit.
330
+ """
331
+ if __whence == SEEK_END:
332
+ # SEEK_END => set from the truncated end
333
+ __offset = len(self) + __offset
334
+ __whence = SEEK_SET
335
+
336
+ pos = self._file.seek(__offset, __whence)
337
+ if pos > self._size_limit:
338
+ return self._file.seek(self._size_limit)
339
+ return pos
340
+
341
+ def read(self, __size: int | None = -1) -> bytes:
342
+ """Read at most `__size` bytes from the file.
343
+
344
+ Behavior is the same as a regular file, except that it is capped to the size limit.
345
+ """
346
+ current = self._file.tell()
347
+ if __size is None or __size < 0:
348
+ # Read until file limit
349
+ truncated_size = self._size_limit - current
350
+ else:
351
+ # Read until file limit or __size
352
+ truncated_size = min(__size, self._size_limit - current)
353
+ return self._file.read(truncated_size)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_dataset_viewer.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import json
15
+ import os
16
+ import shutil
17
+ import subprocess
18
+ from dataclasses import dataclass
19
+ from typing import TYPE_CHECKING, Any, Union
20
+
21
+ from . import constants
22
+ from .utils import get_token
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ import duckdb
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class DatasetParquetEntry:
31
+ """Represents a single parquet file available for a dataset on the Hub."""
32
+
33
+ config: str
34
+ split: str
35
+ url: str
36
+ size: int
37
+
38
+
39
+ def execute_raw_sql_query(sql_query: str, *, token: str | bool | None = None) -> list[dict[str, Any]]:
40
+ normalized_query = sql_query.strip().rstrip(";").strip()
41
+ _raise_on_forbidden_query(normalized_query)
42
+
43
+ connection = None
44
+ try:
45
+ connection = _get_duckdb_connection(token=token)
46
+ relation = connection.sql(normalized_query)
47
+ if relation is None:
48
+ raise ValueError("SQL query must return rows.")
49
+
50
+ if isinstance(relation, _DuckDBCliRelation):
51
+ # DuckDB binary => run CLI => parse JSON
52
+ return relation.execute()
53
+ else:
54
+ # DuckDB Python API => fetch columns + rows => convert to dicts
55
+ columns = tuple(column[0] for column in relation.description)
56
+ rows = tuple(tuple(row) for row in relation.fetchall())
57
+ return [dict(zip(columns, row)) for row in rows]
58
+ finally:
59
+ if connection is not None:
60
+ connection.close()
61
+
62
+
63
+ def _raise_on_forbidden_query(query: str) -> None:
64
+ if len(query) == 0:
65
+ raise ValueError("SQL query cannot be empty.")
66
+
67
+ # DuckDB CLI meta-commands are dot-prefixed words (e.g. `.shell`, `.output`).
68
+ # Let's forbid them for now but allow SQL expressions like `.5` that can legitimately start a line.
69
+ for line in query.splitlines():
70
+ stripped = line.lstrip()
71
+ if stripped.startswith(".") and stripped[1:2].isalpha():
72
+ raise ValueError("DuckDB CLI meta-commands are not allowed in SQL queries.")
73
+
74
+
75
+ def _get_duckdb_connection(
76
+ token: str | bool | None,
77
+ ) -> Union["duckdb.DuckDBPyConnection", "_DuckDBCliConnection"]:
78
+ try:
79
+ # If DuckDB is installed as a Python package, use it!
80
+ import duckdb
81
+ except ImportError as error:
82
+ # Otherwise, use the DuckDB CLI binary.
83
+ duckdb_binary = shutil.which("duckdb")
84
+ if duckdb_binary is None:
85
+ raise ImportError(
86
+ "DuckDB is required for `hf datasets sql`. Install the Python package with `pip install duckdb` or "
87
+ "install the DuckDB CLI binary (for example `brew install duckdb`)."
88
+ ) from error
89
+ return _DuckDBCliConnection(binary_path=duckdb_binary, token=token)
90
+
91
+ # Create a new connection (Python API).
92
+ connection = duckdb.connect()
93
+ try:
94
+ for statement in _build_duckdb_secret_statements(token):
95
+ connection.execute(statement)
96
+ return connection
97
+ except Exception:
98
+ connection.close()
99
+ raise
100
+
101
+
102
+ @dataclass
103
+ class _DuckDBCliConnection:
104
+ """DuckDB connection.
105
+
106
+ Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary.
107
+ """
108
+
109
+ binary_path: str
110
+ token: str | bool | None
111
+
112
+ def __post_init__(self) -> None:
113
+ self._setup_statements = _build_duckdb_secret_statements(self.token)
114
+
115
+ def sql(self, query: str) -> "_DuckDBCliRelation":
116
+ return _DuckDBCliRelation(binary_path=self.binary_path, setup_statements=self._setup_statements, query=query)
117
+
118
+ def close(self) -> None:
119
+ pass
120
+
121
+
122
+ @dataclass
123
+ class _DuckDBCliRelation:
124
+ """DuckDB relation.
125
+
126
+ Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary.
127
+ """
128
+
129
+ binary_path: str
130
+ setup_statements: list[str]
131
+ query: str
132
+
133
+ def execute(self) -> list[dict[str, Any]]:
134
+ # Build the DuckDB CLI input.
135
+ setup = []
136
+ if self.setup_statements:
137
+ setup = [
138
+ f".output {os.devnull}",
139
+ *(f"{stmt};" for stmt in self.setup_statements),
140
+ ".output",
141
+ ]
142
+ full_query = "\n".join(setup + [self.query + ";"])
143
+
144
+ # Run DuckDB binary
145
+ result = subprocess.run(
146
+ [self.binary_path, "-json"],
147
+ input=full_query,
148
+ capture_output=True,
149
+ text=True,
150
+ check=False,
151
+ )
152
+ if result.returncode != 0:
153
+ error_message = result.stderr.strip() or result.stdout.strip() or "DuckDB CLI command failed."
154
+ raise RuntimeError(error_message)
155
+
156
+ # Parse JSON output and return
157
+ return json.loads(result.stdout.strip())
158
+
159
+
160
+ def _build_duckdb_secret_statements(token: str | bool | None) -> list[str]:
161
+ if token is None or token is True:
162
+ token = get_token()
163
+
164
+ if not token:
165
+ return []
166
+
167
+ escaped_token = token.replace("'", "''")
168
+ escaped_endpoint = constants.ENDPOINT.replace("'", "''")
169
+ return [
170
+ f"CREATE OR REPLACE SECRET hf_hub_token (TYPE HTTP, BEARER_TOKEN '{escaped_token}', SCOPE '{escaped_endpoint}')",
171
+ f"CREATE OR REPLACE SECRET hf_token (TYPE HUGGINGFACE, TOKEN '{escaped_token}')",
172
+ ]
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_eval_results.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluation results utilities for the `.eval_results/*.yaml` format.
2
+
3
+ See https://huggingface.co/docs/hub/eval-results for more details.
4
+ Specifications are available at https://github.com/huggingface/hub-docs/blob/main/eval_results.yaml.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+
11
+ @dataclass
12
+ class EvalResultEntry:
13
+ """
14
+ Evaluation result entry for the `.eval_results/*.yaml` format.
15
+
16
+ Represents evaluation scores stored in model repos that automatically appear on
17
+ the model page and the benchmark dataset's leaderboard.
18
+
19
+ For the legacy `model-index` format in `README.md`, use [`EvalResult`] instead.
20
+
21
+ See https://huggingface.co/docs/hub/eval-results for more details.
22
+
23
+ Args:
24
+ dataset_id (`str`):
25
+ Benchmark dataset ID from the Hub. Example: "cais/hle", "Idavidrein/gpqa".
26
+ task_id (`str`):
27
+ Task identifier within the benchmark. Example: "gpqa_diamond".
28
+ value (`Any`):
29
+ The metric value. Example: 20.90.
30
+ dataset_revision (`str`, *optional*):
31
+ Git SHA of the benchmark dataset.
32
+ verify_token (`str`, *optional*):
33
+ A signature that can be used to prove that evaluation is provably auditable and reproducible.
34
+ date (`str`, *optional*):
35
+ When the evaluation was run (ISO-8601 datetime). Defaults to git commit time.
36
+ source_url (`str`, *optional*):
37
+ Link to the evaluation source (e.g., https://huggingface.co/spaces/SaylorTwift/smollm3-mmlu-pro). Required if `source_name`, `source_user`, or `source_org` is provided.
38
+ source_name (`str`, *optional*):
39
+ Display name for the source. Example: "Eval Logs".
40
+ source_user (`str`, *optional*):
41
+ HF user name for attribution. Example: "celinah".
42
+ source_org (`str`, *optional*):
43
+ HF org name for attribution. Example: "cais".
44
+ notes (`str`, *optional*):
45
+ Details about the evaluation setup. Example: "tools", "no-tools", "chain-of-thought".
46
+
47
+ Example:
48
+ ```python
49
+ >>> from huggingface_hub import EvalResultEntry
50
+ >>> # Minimal example with required fields only
51
+ >>> result = EvalResultEntry(
52
+ ... dataset_id="Idavidrein/gpqa",
53
+ ... task_id="gpqa_diamond",
54
+ ... value=0.412,
55
+ ... )
56
+ >>> # Full example with all fields
57
+ >>> result = EvalResultEntry(
58
+ ... dataset_id="cais/hle",
59
+ ... task_id="default",
60
+ ... value=20.90,
61
+ ... dataset_revision="5503434ddd753f426f4b38109466949a1217c2bb",
62
+ ... verify_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
63
+ ... date="2025-01-15T10:30:00Z",
64
+ ... source_url="https://huggingface.co/datasets/cais/hle",
65
+ ... source_name="CAIS HLE",
66
+ ... source_org="cais",
67
+ ... notes="no-tools",
68
+ ... )
69
+
70
+ ```
71
+ """
72
+
73
+ dataset_id: str
74
+ task_id: str
75
+ value: Any
76
+ dataset_revision: str | None = None
77
+ verify_token: str | None = None
78
+ date: str | None = None
79
+ source_url: str | None = None
80
+ source_name: str | None = None
81
+ source_user: str | None = None
82
+ source_org: str | None = None
83
+ notes: str | None = None
84
+
85
+ def __post_init__(self) -> None:
86
+ if (
87
+ self.source_name is not None or self.source_user is not None or self.source_org is not None
88
+ ) and self.source_url is None:
89
+ raise ValueError(
90
+ "If `source_name`, `source_user`, or `source_org` is provided, `source_url` must also be provided."
91
+ )
92
+
93
+
94
+ def eval_result_entries_to_yaml(entries: list[EvalResultEntry]) -> list[dict[str, Any]]:
95
+ """Convert a list of [`EvalResultEntry`] objects to a YAML-serializable list of dicts.
96
+
97
+ This produces the format expected in `.eval_results/*.yaml` files.
98
+
99
+ Args:
100
+ entries (`list[EvalResultEntry]`):
101
+ List of evaluation result entries to serialize.
102
+
103
+ Returns:
104
+ `list[dict[str, Any]]`: A list of dictionaries ready to be dumped to YAML.
105
+
106
+ Example:
107
+ ```python
108
+ >>> from huggingface_hub import EvalResultEntry, eval_result_entries_to_yaml
109
+ >>> entries = [
110
+ ... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90),
111
+ ... EvalResultEntry(dataset_id="Idavidrein/gpqa", task_id="gpqa_diamond", value=0.412),
112
+ ... ]
113
+ >>> yaml_data = eval_result_entries_to_yaml(entries)
114
+ >>> yaml_data[0]
115
+ {'dataset': {'id': 'cais/hle', 'task_id': 'default'}, 'value': 20.9}
116
+
117
+ ```
118
+
119
+ To upload eval results to the Hub:
120
+ ```python
121
+ >>> import yaml
122
+ >>> from huggingface_hub import upload_file, EvalResultEntry, eval_result_entries_to_yaml
123
+ >>> entries = [
124
+ ... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90),
125
+ ... ]
126
+ >>> yaml_content = yaml.dump(eval_result_entries_to_yaml(entries))
127
+ >>> upload_file(
128
+ ... path_or_fileobj=yaml_content.encode(),
129
+ ... path_in_repo=".eval_results/hle.yaml",
130
+ ... repo_id="your-username/your-model",
131
+ ... )
132
+
133
+ ```
134
+ """
135
+ result = []
136
+ for entry in entries:
137
+ # build the dataset object
138
+ dataset: dict[str, Any] = {"id": entry.dataset_id, "task_id": entry.task_id}
139
+ if entry.dataset_revision is not None:
140
+ dataset["revision"] = entry.dataset_revision
141
+
142
+ data: dict[str, Any] = {"dataset": dataset, "value": entry.value}
143
+ if entry.verify_token is not None:
144
+ data["verifyToken"] = entry.verify_token
145
+ if entry.date is not None:
146
+ data["date"] = entry.date
147
+ # build the source object
148
+ if entry.source_url is not None:
149
+ source: dict[str, Any] = {"url": entry.source_url}
150
+ if entry.source_name is not None:
151
+ source["name"] = entry.source_name
152
+ if entry.source_user is not None:
153
+ source["user"] = entry.source_user
154
+ if entry.source_org is not None:
155
+ source["org"] = entry.source_org
156
+ data["source"] = source
157
+ if entry.notes is not None:
158
+ data["notes"] = entry.notes
159
+
160
+ result.append(data)
161
+ return result
162
+
163
+
164
+ def parse_eval_result_entries(data: list[dict[str, Any]]) -> list[EvalResultEntry]:
165
+ """Parse a list of dicts into [`EvalResultEntry`] objects.
166
+
167
+ This parses the `.eval_results/*.yaml` format. For the legacy `model-index` format,
168
+ use [`model_index_to_eval_results`] instead.
169
+
170
+ Args:
171
+ data (`list[dict[str, Any]]`):
172
+ A list of dictionaries (e.g., parsed from YAML or API response).
173
+
174
+ Returns:
175
+ `list[EvalResultEntry]`: A list of evaluation result entry objects.
176
+
177
+ Example:
178
+ ```python
179
+ >>> from huggingface_hub import parse_eval_result_entries
180
+ >>> data = [
181
+ ... {"dataset": {"id": "cais/hle", "task_id": "default"}, "value": 20.90},
182
+ ... {"dataset": {"id": "Idavidrein/gpqa", "task_id": "gpqa_diamond"}, "value": 0.412},
183
+ ... ]
184
+ >>> entries = parse_eval_result_entries(data)
185
+ >>> entries[0].dataset_id
186
+ 'cais/hle'
187
+ >>> entries[0].value
188
+ 20.9
189
+
190
+ ```
191
+ """
192
+ entries = []
193
+ for item in data:
194
+ entry_data = item.get("data", item)
195
+ dataset = entry_data.get("dataset", {})
196
+ source = entry_data.get("source", {})
197
+ entry = EvalResultEntry(
198
+ dataset_id=dataset["id"],
199
+ value=entry_data["value"],
200
+ task_id=dataset["task_id"],
201
+ dataset_revision=dataset.get("revision"),
202
+ verify_token=entry_data.get("verifyToken"),
203
+ date=entry_data.get("date"),
204
+ source_url=source.get("url") if source else None,
205
+ source_name=source.get("name") if source else None,
206
+ source_user=source.get("user") if source else None,
207
+ source_org=source.get("org") if source else None,
208
+ notes=entry_data.get("notes"),
209
+ )
210
+ entries.append(entry)
211
+ return entries
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/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.
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/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"}
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/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
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/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
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_inference_endpoints.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from dataclasses import dataclass, field
3
+ from datetime import datetime
4
+ from enum import Enum
5
+ from typing import TYPE_CHECKING, Optional
6
+
7
+ from huggingface_hub.errors import InferenceEndpointError, InferenceEndpointTimeoutError
8
+
9
+ from .utils import get_session, logging, parse_datetime
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from .hf_api import HfApi
14
+ from .inference._client import InferenceClient
15
+ from .inference._generated._async_client import AsyncInferenceClient
16
+
17
+ logger = logging.get_logger(__name__)
18
+
19
+
20
+ class InferenceEndpointStatus(str, Enum):
21
+ PENDING = "pending"
22
+ INITIALIZING = "initializing"
23
+ UPDATING = "updating"
24
+ UPDATE_FAILED = "updateFailed"
25
+ RUNNING = "running"
26
+ PAUSED = "paused"
27
+ FAILED = "failed"
28
+ SCALED_TO_ZERO = "scaledToZero"
29
+
30
+
31
+ class InferenceEndpointType(str, Enum):
32
+ PUBlIC = "public"
33
+ PROTECTED = "protected" # deprecated, use AUTHENTICATED instead
34
+ AUTHENTICATED = "authenticated"
35
+ PRIVATE = "private"
36
+
37
+
38
+ class InferenceEndpointScalingMetric(str, Enum):
39
+ PENDING_REQUESTS = "pendingRequests"
40
+ HARDWARE_USAGE = "hardwareUsage"
41
+
42
+
43
+ @dataclass
44
+ class InferenceEndpoint:
45
+ """
46
+ Contains information about a deployed Inference Endpoint.
47
+
48
+ Args:
49
+ name (`str`):
50
+ The unique name of the Inference Endpoint.
51
+ namespace (`str`):
52
+ The namespace where the Inference Endpoint is located.
53
+ repository (`str`):
54
+ The name of the model repository deployed on this Inference Endpoint.
55
+ status ([`InferenceEndpointStatus`]):
56
+ The current status of the Inference Endpoint.
57
+ url (`str`, *optional*):
58
+ The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL.
59
+ framework (`str`):
60
+ The machine learning framework used for the model.
61
+ revision (`str`):
62
+ The specific model revision deployed on the Inference Endpoint.
63
+ task (`str`):
64
+ The task associated with the deployed model.
65
+ created_at (`datetime.datetime`):
66
+ The timestamp when the Inference Endpoint was created.
67
+ updated_at (`datetime.datetime`):
68
+ The timestamp of the last update of the Inference Endpoint.
69
+ type ([`InferenceEndpointType`]):
70
+ The type of the Inference Endpoint (public, authenticated, private).
71
+ raw (`dict`):
72
+ The raw dictionary data returned from the API.
73
+ token (`str` or `bool`, *optional*):
74
+ Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the
75
+ locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server.
76
+
77
+ Example:
78
+ ```python
79
+ >>> from huggingface_hub import get_inference_endpoint
80
+ >>> endpoint = get_inference_endpoint("my-text-to-image")
81
+ >>> endpoint
82
+ InferenceEndpoint(name='my-text-to-image', ...)
83
+
84
+ # Get status
85
+ >>> endpoint.status
86
+ 'running'
87
+ >>> endpoint.url
88
+ 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud'
89
+
90
+ # Run inference
91
+ >>> endpoint.client.text_to_image(...)
92
+
93
+ # Pause endpoint to save $$$
94
+ >>> endpoint.pause()
95
+
96
+ # ...
97
+ # Resume and wait for deployment
98
+ >>> endpoint.resume()
99
+ >>> endpoint.wait()
100
+ >>> endpoint.client.text_to_image(...)
101
+ ```
102
+ """
103
+
104
+ # Field in __repr__
105
+ name: str = field(init=False)
106
+ namespace: str
107
+ repository: str = field(init=False)
108
+ status: InferenceEndpointStatus = field(init=False)
109
+ health_route: str = field(init=False)
110
+ url: str | None = field(init=False)
111
+
112
+ # Other fields
113
+ framework: str = field(repr=False, init=False)
114
+ revision: str = field(repr=False, init=False)
115
+ task: str = field(repr=False, init=False)
116
+ created_at: datetime = field(repr=False, init=False)
117
+ updated_at: datetime = field(repr=False, init=False)
118
+ type: InferenceEndpointType = field(repr=False, init=False)
119
+
120
+ # Raw dict from the API
121
+ raw: dict = field(repr=False)
122
+
123
+ # Internal fields
124
+ _token: str | bool | None = field(repr=False, compare=False)
125
+ _api: "HfApi" = field(repr=False, compare=False)
126
+
127
+ @classmethod
128
+ def from_raw(
129
+ cls, raw: dict, namespace: str, token: str | bool | None = None, api: Optional["HfApi"] = None
130
+ ) -> "InferenceEndpoint":
131
+ """Initialize object from raw dictionary."""
132
+ if api is None:
133
+ from .hf_api import HfApi
134
+
135
+ api = HfApi()
136
+ if token is None:
137
+ token = api.token
138
+
139
+ # All other fields are populated in __post_init__
140
+ return cls(raw=raw, namespace=namespace, _token=token, _api=api)
141
+
142
+ def __post_init__(self) -> None:
143
+ """Populate fields from raw dictionary."""
144
+ self._populate_from_raw()
145
+
146
+ @property
147
+ def client(self) -> "InferenceClient":
148
+ """Returns a client to make predictions on this Inference Endpoint.
149
+
150
+ Returns:
151
+ [`InferenceClient`]: an inference client pointing to the deployed endpoint.
152
+
153
+ Raises:
154
+ [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
155
+ """
156
+ if self.url is None:
157
+ raise InferenceEndpointError(
158
+ "Cannot create a client for this Inference Endpoint as it is not yet deployed. "
159
+ "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
160
+ )
161
+ from .inference._client import InferenceClient
162
+
163
+ return InferenceClient(
164
+ model=self.url,
165
+ token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok.
166
+ )
167
+
168
+ @property
169
+ def async_client(self) -> "AsyncInferenceClient":
170
+ """Returns a client to make predictions on this Inference Endpoint.
171
+
172
+ Returns:
173
+ [`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint.
174
+
175
+ Raises:
176
+ [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed.
177
+ """
178
+ if self.url is None:
179
+ raise InferenceEndpointError(
180
+ "Cannot create a client for this Inference Endpoint as it is not yet deployed. "
181
+ "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again."
182
+ )
183
+ from .inference._generated._async_client import AsyncInferenceClient
184
+
185
+ return AsyncInferenceClient(
186
+ model=self.url,
187
+ token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok.
188
+ )
189
+
190
+ def wait(self, timeout: int | None = None, refresh_every: int = 5) -> "InferenceEndpoint":
191
+ """Wait for the Inference Endpoint to be deployed.
192
+
193
+ Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout`
194
+ seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest
195
+ data.
196
+
197
+ Args:
198
+ timeout (`int`, *optional*):
199
+ The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait
200
+ indefinitely.
201
+ refresh_every (`int`, *optional*):
202
+ The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s.
203
+
204
+ Returns:
205
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
206
+
207
+ Raises:
208
+ [`InferenceEndpointError`]
209
+ If the Inference Endpoint ended up in a failed state.
210
+ [`InferenceEndpointTimeoutError`]
211
+ If the Inference Endpoint is not deployed after `timeout` seconds.
212
+ """
213
+ if timeout is not None and timeout < 0:
214
+ raise ValueError("`timeout` cannot be negative.")
215
+ if refresh_every <= 0:
216
+ raise ValueError("`refresh_every` must be positive.")
217
+
218
+ start = time.time()
219
+ while True:
220
+ if self.status == InferenceEndpointStatus.FAILED:
221
+ raise InferenceEndpointError(
222
+ f"Inference Endpoint {self.name} failed to deploy. Please check the logs for more information."
223
+ )
224
+ if self.status == InferenceEndpointStatus.UPDATE_FAILED:
225
+ raise InferenceEndpointError(
226
+ f"Inference Endpoint {self.name} failed to update. Please check the logs for more information."
227
+ )
228
+ if self.status == InferenceEndpointStatus.RUNNING and self.url is not None:
229
+ # Verify the endpoint is actually reachable
230
+ _health_url = f"{self.url.rstrip('/')}/{self.health_route.lstrip('/')}"
231
+ response = get_session().get(_health_url, headers=self._api._build_hf_headers(token=self._token))
232
+ if response.status_code == 200:
233
+ logger.info("Inference Endpoint is ready to be used.")
234
+ return self
235
+
236
+ if timeout is not None:
237
+ if time.time() - start > timeout:
238
+ raise InferenceEndpointTimeoutError("Timeout while waiting for Inference Endpoint to be deployed.")
239
+ logger.info(f"Inference Endpoint is not deployed yet ({self.status}). Waiting {refresh_every}s...")
240
+ time.sleep(refresh_every)
241
+ self.fetch()
242
+
243
+ def fetch(self) -> "InferenceEndpoint":
244
+ """Fetch latest information about the Inference Endpoint.
245
+
246
+ Returns:
247
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
248
+ """
249
+ obj = self._api.get_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
250
+ self.raw = obj.raw
251
+ self._populate_from_raw()
252
+ return self
253
+
254
+ def update(
255
+ self,
256
+ *,
257
+ # Compute update
258
+ accelerator: str | None = None,
259
+ instance_size: str | None = None,
260
+ instance_type: str | None = None,
261
+ min_replica: int | None = None,
262
+ max_replica: int | None = None,
263
+ scale_to_zero_timeout: int | None = None,
264
+ # Model update
265
+ repository: str | None = None,
266
+ framework: str | None = None,
267
+ revision: str | None = None,
268
+ task: str | None = None,
269
+ custom_image: dict | None = None,
270
+ secrets: dict[str, str] | None = None,
271
+ ) -> "InferenceEndpoint":
272
+ """Update the Inference Endpoint.
273
+
274
+ This method allows the update of either the compute configuration, the deployed model, or both. All arguments are
275
+ optional but at least one must be provided.
276
+
277
+ This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the
278
+ latest data from the server.
279
+
280
+ Args:
281
+ accelerator (`str`, *optional*):
282
+ The hardware accelerator to be used for inference (e.g. `"cpu"`).
283
+ instance_size (`str`, *optional*):
284
+ The size or type of the instance to be used for hosting the model (e.g. `"x4"`).
285
+ instance_type (`str`, *optional*):
286
+ The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`).
287
+ min_replica (`int`, *optional*):
288
+ The minimum number of replicas (instances) to keep running for the Inference Endpoint.
289
+ max_replica (`int`, *optional*):
290
+ The maximum number of replicas (instances) to scale to for the Inference Endpoint.
291
+ scale_to_zero_timeout (`int`, *optional*):
292
+ The duration in minutes before an inactive endpoint is scaled to zero.
293
+
294
+ repository (`str`, *optional*):
295
+ The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`).
296
+ framework (`str`, *optional*):
297
+ The machine learning framework used for the model (e.g. `"custom"`).
298
+ revision (`str`, *optional*):
299
+ The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`).
300
+ task (`str`, *optional*):
301
+ The task on which to deploy the model (e.g. `"text-classification"`).
302
+ custom_image (`dict`, *optional*):
303
+ A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an
304
+ Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples).
305
+ secrets (`dict[str, str]`, *optional*):
306
+ Secret values to inject in the container environment.
307
+ Returns:
308
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
309
+ """
310
+ # Make API call
311
+ obj = self._api.update_inference_endpoint(
312
+ name=self.name,
313
+ namespace=self.namespace,
314
+ accelerator=accelerator,
315
+ instance_size=instance_size,
316
+ instance_type=instance_type,
317
+ min_replica=min_replica,
318
+ max_replica=max_replica,
319
+ scale_to_zero_timeout=scale_to_zero_timeout,
320
+ repository=repository,
321
+ framework=framework,
322
+ revision=revision,
323
+ task=task,
324
+ custom_image=custom_image,
325
+ secrets=secrets,
326
+ token=self._token, # type: ignore [arg-type]
327
+ )
328
+
329
+ # Mutate current object
330
+ self.raw = obj.raw
331
+ self._populate_from_raw()
332
+ return self
333
+
334
+ def pause(self) -> "InferenceEndpoint":
335
+ """Pause the Inference Endpoint.
336
+
337
+ A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`].
338
+ This is different from scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which
339
+ would be automatically restarted when a request is made to it.
340
+
341
+ This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the
342
+ latest data from the server.
343
+
344
+ Returns:
345
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
346
+ """
347
+ obj = self._api.pause_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
348
+ self.raw = obj.raw
349
+ self._populate_from_raw()
350
+ return self
351
+
352
+ def resume(self, running_ok: bool = True) -> "InferenceEndpoint":
353
+ """Resume the Inference Endpoint.
354
+
355
+ This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the
356
+ latest data from the server.
357
+
358
+ Args:
359
+ running_ok (`bool`, *optional*):
360
+ If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to
361
+ `True`.
362
+
363
+ Returns:
364
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
365
+ """
366
+ obj = self._api.resume_inference_endpoint(
367
+ name=self.name, namespace=self.namespace, running_ok=running_ok, token=self._token
368
+ ) # type: ignore [arg-type]
369
+ self.raw = obj.raw
370
+ self._populate_from_raw()
371
+ return self
372
+
373
+ def scale_to_zero(self) -> "InferenceEndpoint":
374
+ """Scale Inference Endpoint to zero.
375
+
376
+ An Inference Endpoint scaled to zero will not be charged. It will be resumed on the next request to it, with a
377
+ cold start delay. This is different from pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which
378
+ would require a manual resume with [`InferenceEndpoint.resume`].
379
+
380
+ This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the
381
+ latest data from the server.
382
+
383
+ Returns:
384
+ [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data.
385
+ """
386
+ obj = self._api.scale_to_zero_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
387
+ self.raw = obj.raw
388
+ self._populate_from_raw()
389
+ return self
390
+
391
+ def delete(self) -> None:
392
+ """Delete the Inference Endpoint.
393
+
394
+ This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable
395
+ to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`].
396
+
397
+ This is an alias for [`HfApi.delete_inference_endpoint`].
398
+ """
399
+ self._api.delete_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type]
400
+
401
+ def _populate_from_raw(self) -> None:
402
+ """Populate fields from raw dictionary.
403
+
404
+ Called in __post_init__ + each time the Inference Endpoint is updated.
405
+ """
406
+ # Repr fields
407
+ self.name = self.raw["name"]
408
+ self.repository = self.raw["model"]["repository"]
409
+ self.status = self.raw["status"]["state"]
410
+ self.url = self.raw["status"].get("url")
411
+ self.health_route = self.raw["healthRoute"]
412
+
413
+ # Other fields
414
+ self.framework = self.raw["model"]["framework"]
415
+ self.revision = self.raw["model"]["revision"]
416
+ self.task = self.raw["model"]["task"]
417
+ self.created_at = parse_datetime(self.raw["status"]["createdAt"])
418
+ self.updated_at = parse_datetime(self.raw["status"]["updatedAt"])
419
+ self.type = self.raw["type"]
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_jobs_api.py ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import hashlib
15
+ import platform
16
+ from dataclasses import dataclass
17
+ from datetime import datetime
18
+ from enum import Enum
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from huggingface_hub import constants
23
+ from huggingface_hub._space_api import Volume
24
+ from huggingface_hub.utils._datetime import parse_datetime
25
+
26
+
27
+ class JobHardware(str, Enum):
28
+ """
29
+ Enumeration of hardware flavors available to run Jobs on the Hub.
30
+
31
+ Value can be compared to a string:
32
+ ```py
33
+ assert JobHardware.CPU_BASIC == "cpu-basic"
34
+ ```
35
+
36
+ Both enums are kept in sync with the Hub API by `utils/check_hardware_flavors.py`.
37
+ """
38
+
39
+ # CPU
40
+ CPU_BASIC = "cpu-basic"
41
+ CPU_UPGRADE = "cpu-upgrade"
42
+ CPU_PERFORMANCE = "cpu-performance"
43
+ CPU_XL = "cpu-xl"
44
+
45
+ # GPU
46
+ T4_SMALL = "t4-small"
47
+ T4_MEDIUM = "t4-medium"
48
+ L4X1 = "l4x1"
49
+ L4X4 = "l4x4"
50
+ L40SX1 = "l40sx1"
51
+ L40SX4 = "l40sx4"
52
+ L40SX8 = "l40sx8"
53
+ A10G_SMALL = "a10g-small"
54
+ A10G_LARGE = "a10g-large"
55
+ A10G_LARGEX2 = "a10g-largex2"
56
+ A10G_LARGEX4 = "a10g-largex4"
57
+ A100_LARGE = "a100-large"
58
+ A100X4 = "a100x4"
59
+ A100X8 = "a100x8"
60
+ H200 = "h200"
61
+ H200X2 = "h200x2"
62
+ H200X4 = "h200x4"
63
+ H200X8 = "h200x8"
64
+ RTX_PRO_6000 = "rtx-pro-6000"
65
+ RTX_PRO_6000X2 = "rtx-pro-6000x2"
66
+ RTX_PRO_6000X4 = "rtx-pro-6000x4"
67
+ RTX_PRO_6000X8 = "rtx-pro-6000x8"
68
+
69
+
70
+ class JobStage(str, Enum):
71
+ """
72
+ Enumeration of possible stage of a Job on the Hub.
73
+
74
+ Value can be compared to a string:
75
+ ```py
76
+ assert JobStage.COMPLETED == "COMPLETED"
77
+ ```
78
+ Possible values are: `COMPLETED`, `CANCELED`, `ERROR`, `DELETED`, `SCHEDULING`, `RUNNING`.
79
+ Taken from https://github.com/huggingface/moon-landing/blob/main/server/job_types/JobInfo.ts#L61 (private url).
80
+ """
81
+
82
+ # Copied from moon-landing > server > lib > Job.ts
83
+ COMPLETED = "COMPLETED"
84
+ CANCELED = "CANCELED"
85
+ ERROR = "ERROR"
86
+ DELETED = "DELETED"
87
+ SCHEDULING = "SCHEDULING"
88
+ RUNNING = "RUNNING"
89
+
90
+
91
+ # Stages indicating the Job has reached a terminal state and will not run further.
92
+ TERMINAL_JOB_STAGES = (JobStage.COMPLETED, JobStage.CANCELED, JobStage.ERROR, JobStage.DELETED)
93
+
94
+
95
+ @dataclass
96
+ class JobStatus:
97
+ stage: JobStage
98
+ message: str | None
99
+ expose_urls: list[str] | None
100
+ ssh_url: str | None
101
+
102
+
103
+ @dataclass
104
+ class JobOwner:
105
+ id: str
106
+ name: str
107
+ type: str
108
+
109
+
110
+ @dataclass
111
+ class JobDurations:
112
+ """
113
+ Timing breakdown for a Job, computed server-side.
114
+
115
+ Args:
116
+ scheduling_secs (`int` or `None`):
117
+ Seconds the job spent in the scheduling stage before starting to run.
118
+ `None` if the job never reached the running stage.
119
+ running_secs (`int` or `None`):
120
+ Seconds the job has been or was running. Recomputed on each request
121
+ while the job is in progress. `None` if the job never started running.
122
+ total_secs (`int` or `None`):
123
+ Total seconds elapsed since the job was created. Recomputed on each
124
+ request while the job is in progress.
125
+ """
126
+
127
+ scheduling_secs: int | None
128
+ running_secs: int | None
129
+ total_secs: int | None
130
+
131
+ def __init__(self, **kwargs) -> None:
132
+ self.scheduling_secs = kwargs.get("schedulingSecs", kwargs.get("scheduling_secs"))
133
+ self.running_secs = kwargs.get("runningSecs", kwargs.get("running_secs"))
134
+ self.total_secs = kwargs.get("totalSecs", kwargs.get("total_secs"))
135
+
136
+
137
+ @dataclass
138
+ class JobInitiator:
139
+ """
140
+ Contains information about what triggered a Job.
141
+
142
+ Args:
143
+ type (`str`): Initiator kind, for example `"user"`, `"org"`, `"scheduled-job"`, or `"duplicated-job"`.
144
+ id (`str`): Identifier of the initiator.
145
+ name (`str` or `None`): Human-readable name when available, usually for user/org initiators.
146
+ """
147
+
148
+ type: str
149
+ id: str
150
+ name: str | None = None
151
+
152
+
153
+ @dataclass
154
+ class JobInfo:
155
+ """
156
+ Contains information about a Job.
157
+
158
+ Args:
159
+ id (`str`):
160
+ Job ID.
161
+ created_at (`datetime` or `None`):
162
+ When the Job was created.
163
+ started_at (`datetime` or `None`):
164
+ When the Job started running. None while the Job is still scheduling.
165
+ finished_at (`datetime` or `None`):
166
+ When the Job finished. None while the Job is still scheduling or running.
167
+ docker_image (`str` or `None`):
168
+ The Docker image from Docker Hub used for the Job.
169
+ Can be None if space_id is present instead.
170
+ space_id (`str` or `None`):
171
+ The Docker image from Hugging Face Spaces used for the Job.
172
+ Can be None if docker_image is present instead.
173
+ command (`list[str]` or `None`):
174
+ Command of the Job, e.g. `["python", "-c", "print('hello world')"]`
175
+ arguments (`list[str]` or `None`):
176
+ Arguments passed to the command
177
+ environment (`dict[str]` or `None`):
178
+ Environment variables of the Job as a dictionary.
179
+ secrets (`dict[str]` or `None`):
180
+ Secret environment variables of the Job (encrypted).
181
+ flavor (`str` or `None`):
182
+ Flavor for the hardware. See [`JobHardware`] for possible values.
183
+ E.g. `"cpu-basic"`.
184
+ labels (`dict[str, str]` or `None`):
185
+ Labels to attach to the job (key-value pairs).
186
+ volumes (`list[Volume]` or `None`):
187
+ Volumes mounted in the job container (buckets, models, datasets, spaces).
188
+ status: (`JobStatus` or `None`):
189
+ Status of the Job, e.g. `JobStatus(stage="RUNNING", message=None)`
190
+ See [`JobStage`] for possible stage values.
191
+ durations (`JobDurations` or `None`):
192
+ Timing breakdown of the Job. Present for all job states including SCHEDULING.
193
+ owner: (`JobOwner` or `None`):
194
+ Owner of the Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")`
195
+ initiator (`JobInitiator` or `None`):
196
+ What triggered the Job, e.g. `JobInitiator(type="scheduled-job", id="...")` for a cron-triggered run.
197
+ expose_urls (`list[str]` or `None`):
198
+ Public URLs through which the Job's exposed ports are reachable (one per port exposed via `expose=`),
199
+ e.g. `["https://687fb701029421ae5549d998--8000.hf.jobs"]`. `None` when no port is exposed.
200
+ Accessing a URL requires an HF token with read access to the Job's namespace.
201
+ ssh_url (`str` or `None`):
202
+ SSH endpoint of the Job, e.g. `"ssh://687fb701029421ae5549d998@ssh.hf.jobs"`. Only present when the Job
203
+ was started with `ssh=True`. Connecting requires write access to the Job's namespace and an SSH public
204
+ key registered on the Hub (https://huggingface.co/settings/keys).
205
+
206
+ Example:
207
+
208
+ ```python
209
+ >>> from huggingface_hub import run_job
210
+ >>> job = run_job(
211
+ ... image="python:3.12",
212
+ ... command=["python", "-c", "print('Hello from the cloud!')"]
213
+ ... )
214
+ >>> job
215
+ JobInfo(id='687fb701029421ae5549d998', created_at=datetime.datetime(2025, 7, 22, 16, 6, 25, 79000, tzinfo=datetime.timezone.utc), started_at=datetime.datetime(2025, 7, 22, 16, 6, 31, 79000, tzinfo=datetime.timezone.utc), finished_at=None, docker_image='python:3.12', space_id=None, command=['python', '-c', "print('Hello from the cloud!')"], arguments=[], environment={}, secrets={}, flavor='cpu-basic', labels=None, status=JobStatus(stage='RUNNING', message=None), durations=JobDurations(scheduling_secs=6, running_secs=2, total_secs=8), owner=JobOwner(id='5e9ecfc04957053f60648a3e', name='lhoestq', type='user'), initiator=JobInitiator(type='user', id='5e9ecfc04957053f60648a3e', name='lhoestq'), endpoint='https://huggingface.co', url='https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998')
216
+ >>> job.id
217
+ '687fb701029421ae5549d998'
218
+ >>> job.url
219
+ 'https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998'
220
+ >>> job.status.stage
221
+ 'RUNNING'
222
+ ```
223
+ """
224
+
225
+ id: str
226
+ created_at: datetime | None
227
+ started_at: datetime | None
228
+ finished_at: datetime | None
229
+ docker_image: str | None
230
+ space_id: str | None
231
+ command: list[str] | None
232
+ arguments: list[str] | None
233
+ environment: dict[str, Any] | None
234
+ secrets: dict[str, Any] | None
235
+ flavor: JobHardware | None
236
+ labels: dict[str, str] | None
237
+ volumes: list[Volume] | None
238
+ status: JobStatus
239
+ durations: JobDurations | None
240
+ owner: JobOwner
241
+ initiator: JobInitiator | None
242
+
243
+ # Inferred fields
244
+ endpoint: str
245
+ url: str
246
+
247
+ def __init__(self, **kwargs) -> None:
248
+ self.id = kwargs["id"]
249
+ created_at = kwargs.get("createdAt") or kwargs.get("created_at")
250
+ self.created_at = parse_datetime(created_at) if created_at else None
251
+ started_at = kwargs.get("startedAt") or kwargs.get("started_at")
252
+ self.started_at = parse_datetime(started_at) if started_at else None
253
+ finished_at = kwargs.get("finishedAt") or kwargs.get("finished_at")
254
+ self.finished_at = parse_datetime(finished_at) if finished_at else None
255
+ self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image")
256
+ self.space_id = kwargs.get("spaceId") or kwargs.get("space_id")
257
+ owner = kwargs.get("owner", {})
258
+ self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"])
259
+ self.command = kwargs.get("command")
260
+ self.arguments = kwargs.get("arguments")
261
+ self.environment = kwargs.get("environment")
262
+ self.secrets = kwargs.get("secrets")
263
+ self.flavor = kwargs.get("flavor")
264
+ self.labels = kwargs.get("labels")
265
+ volumes = kwargs.get("volumes")
266
+ self.volumes = [Volume(**v) for v in volumes] if volumes else None
267
+ status = kwargs.get("status", {})
268
+ self.status = JobStatus(
269
+ stage=status["stage"],
270
+ message=status.get("message"),
271
+ expose_urls=status.get("exposeUrls"),
272
+ ssh_url=status.get("sshUrl"),
273
+ )
274
+ durations = kwargs.get("durations")
275
+ self.durations = JobDurations(**durations) if durations else None
276
+ initiator = kwargs.get("initiator")
277
+ self.initiator = (
278
+ JobInitiator(type=initiator["type"], id=initiator["id"], name=initiator.get("name")) if initiator else None
279
+ )
280
+
281
+ # Inferred fields
282
+ self.endpoint = kwargs.get("endpoint", constants.ENDPOINT)
283
+ self.url = f"{self.endpoint}/jobs/{self.owner.name}/{self.id}"
284
+
285
+
286
+ @dataclass
287
+ class JobSpec:
288
+ docker_image: str | None
289
+ space_id: str | None
290
+ command: list[str] | None
291
+ arguments: list[str] | None
292
+ environment: dict[str, Any] | None
293
+ secrets: dict[str, Any] | None
294
+ flavor: JobHardware | None
295
+ timeout: int | None
296
+ tags: list[str] | None
297
+ arch: str | None
298
+ labels: dict[str, str] | None
299
+ volumes: list[Volume] | None
300
+
301
+ def __init__(self, **kwargs) -> None:
302
+ self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image")
303
+ self.space_id = kwargs.get("spaceId") or kwargs.get("space_id")
304
+ self.command = kwargs.get("command")
305
+ self.arguments = kwargs.get("arguments")
306
+ self.environment = kwargs.get("environment")
307
+ self.secrets = kwargs.get("secrets")
308
+ self.flavor = kwargs.get("flavor")
309
+ self.timeout = kwargs.get("timeout")
310
+ self.tags = kwargs.get("tags")
311
+ self.arch = kwargs.get("arch")
312
+ self.labels = kwargs.get("labels")
313
+ volumes = kwargs.get("volumes")
314
+ self.volumes = [Volume(**v) for v in volumes] if volumes else None
315
+
316
+
317
+ @dataclass
318
+ class LastJobInfo:
319
+ id: str
320
+ at: datetime
321
+
322
+ def __init__(self, **kwargs) -> None:
323
+ self.id = kwargs["id"]
324
+ self.at = parse_datetime(kwargs["at"])
325
+
326
+
327
+ @dataclass
328
+ class ScheduledJobStatus:
329
+ last_job: LastJobInfo | None
330
+ next_job_run_at: datetime | None
331
+
332
+ def __init__(self, **kwargs) -> None:
333
+ last_job = kwargs.get("lastJob") or kwargs.get("last_job")
334
+ self.last_job = LastJobInfo(**last_job) if last_job else None
335
+ next_job_run_at = kwargs.get("nextJobRunAt") or kwargs.get("next_job_run_at")
336
+ self.next_job_run_at = parse_datetime(str(next_job_run_at)) if next_job_run_at else None
337
+
338
+
339
+ @dataclass
340
+ class ScheduledJobInfo:
341
+ """
342
+ Contains information about a Job.
343
+
344
+ Args:
345
+ id (`str`):
346
+ Scheduled Job ID.
347
+ created_at (`datetime` or `None`):
348
+ When the scheduled Job was created.
349
+ tags (`list[str]` or `None`):
350
+ The tags of the scheduled Job.
351
+ schedule (`str` or `None`):
352
+ One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
353
+ CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
354
+ suspend (`bool` or `None`):
355
+ Whether the scheduled job is suspended (paused).
356
+ concurrency (`bool` or `None`):
357
+ Whether multiple instances of this Job can run concurrently.
358
+ status (`ScheduledJobStatus` or `None`):
359
+ Status of the scheduled Job.
360
+ owner: (`JobOwner` or `None`):
361
+ Owner of the scheduled Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")`
362
+ job_spec: (`JobSpec` or `None`):
363
+ Specifications of the Job.
364
+
365
+ Example:
366
+
367
+ ```python
368
+ >>> from huggingface_hub import run_job
369
+ >>> scheduled_job = create_scheduled_job(
370
+ ... image="python:3.12",
371
+ ... command=["python", "-c", "print('Hello from the cloud!')"],
372
+ ... schedule="@hourly",
373
+ ... )
374
+ >>> scheduled_job.id
375
+ '687fb701029421ae5549d999'
376
+ >>> scheduled_job.status.next_job_run_at
377
+ datetime.datetime(2025, 7, 22, 17, 6, 25, 79000, tzinfo=datetime.timezone.utc)
378
+ ```
379
+ """
380
+
381
+ id: str
382
+ created_at: datetime | None
383
+ job_spec: JobSpec
384
+ schedule: str | None
385
+ suspend: bool | None
386
+ concurrency: bool | None
387
+ status: ScheduledJobStatus
388
+ owner: JobOwner
389
+
390
+ def __init__(self, **kwargs) -> None:
391
+ self.id = kwargs["id"]
392
+ created_at = kwargs.get("createdAt") or kwargs.get("created_at")
393
+ self.created_at = parse_datetime(created_at) if created_at else None
394
+ self.job_spec = JobSpec(**(kwargs.get("job_spec") or kwargs.get("jobSpec", {})))
395
+ self.schedule = kwargs.get("schedule")
396
+ self.suspend = kwargs.get("suspend")
397
+ self.concurrency = kwargs.get("concurrency")
398
+ status = kwargs.get("status", {})
399
+ self.status = ScheduledJobStatus(
400
+ last_job=status.get("last_job") or status.get("lastJob"),
401
+ next_job_run_at=status.get("next_job_run_at") or status.get("nextJobRunAt"),
402
+ )
403
+ owner = kwargs.get("owner", {})
404
+ self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"])
405
+
406
+
407
+ @dataclass
408
+ class JobAccelerator:
409
+ """
410
+ Contains information about a Job accelerator (GPU).
411
+
412
+ Args:
413
+ type (`str`):
414
+ Type of accelerator, e.g. `"gpu"`.
415
+ model (`str`):
416
+ Model of accelerator, e.g. `"T4"`, `"A10G"`, `"A100"`, `"L4"`, `"L40S"`.
417
+ quantity (`str`):
418
+ Number of accelerators, e.g. `"1"`, `"2"`, `"4"`, `"8"`.
419
+ vram (`str`):
420
+ Total VRAM, e.g. `"16 GB"`, `"24 GB"`.
421
+ manufacturer (`str`):
422
+ Manufacturer of the accelerator, e.g. `"Nvidia"`.
423
+ """
424
+
425
+ type: str
426
+ model: str
427
+ quantity: str
428
+ vram: str
429
+ manufacturer: str
430
+
431
+ def __init__(self, **kwargs) -> None:
432
+ self.type = kwargs["type"]
433
+ self.model = kwargs["model"]
434
+ self.quantity = kwargs["quantity"]
435
+ self.vram = kwargs["vram"]
436
+ self.manufacturer = kwargs["manufacturer"]
437
+
438
+
439
+ @dataclass
440
+ class JobHardwareInfo:
441
+ """
442
+ Contains information about available Job hardware.
443
+
444
+ Args:
445
+ name (`str`):
446
+ Machine identifier, e.g. `"cpu-basic"`, `"a10g-large"`.
447
+ pretty_name (`str`):
448
+ Human-readable name, e.g. `"CPU Basic"`, `"Nvidia A10G - large"`.
449
+ cpu (`str`):
450
+ CPU specification, e.g. `"2 vCPU"`, `"12 vCPU"`.
451
+ ram (`str`):
452
+ RAM specification, e.g. `"16 GB"`, `"46 GB"`.
453
+ ephemeral_storage (`str`):
454
+ Ephemeral storage specification, e.g. `"20 GB"`, `"100 GB"`.
455
+ accelerator (`JobAccelerator` or `None`):
456
+ GPU/accelerator details if available.
457
+ unit_cost_micro_usd (`int`):
458
+ Cost in micro-dollars per unit, e.g. `167` (= $0.000167).
459
+ unit_cost_usd (`float`):
460
+ Cost in USD per unit, e.g. `0.000167`.
461
+ unit_label (`str`):
462
+ Cost unit period, e.g. `"minute"`.
463
+
464
+ Example:
465
+
466
+ ```python
467
+ >>> from huggingface_hub import list_jobs_hardware
468
+ >>> hardware_list = list_jobs_hardware()
469
+ >>> hardware_list[0]
470
+ JobHardwareInfo(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ephemeral_storage='20 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute')
471
+ >>> hardware_list[0].name
472
+ 'cpu-basic'
473
+ ```
474
+ """
475
+
476
+ name: str
477
+ pretty_name: str
478
+ cpu: str
479
+ ram: str
480
+ ephemeral_storage: str
481
+ accelerator: JobAccelerator | None
482
+ unit_cost_micro_usd: int
483
+ unit_cost_usd: float
484
+ unit_label: str
485
+
486
+ def __init__(self, **kwargs) -> None:
487
+ self.name = kwargs["name"]
488
+ self.pretty_name = kwargs["prettyName"]
489
+ self.cpu = kwargs["cpu"]
490
+ self.ram = kwargs["ram"]
491
+ self.ephemeral_storage = kwargs.get("ephemeralStorage", "N/A")
492
+ accelerator = kwargs.get("accelerator")
493
+ self.accelerator = JobAccelerator(**accelerator) if accelerator else None
494
+ self.unit_cost_micro_usd = kwargs["unitCostMicroUSD"]
495
+ self.unit_cost_usd = kwargs["unitCostUSD"]
496
+ self.unit_label = kwargs["unitLabel"]
497
+
498
+
499
+ def _derive_job_volume_name(source: str | Path) -> str:
500
+ """Derive a stable remote folder name for a local directory synced as a Job volume.
501
+
502
+ The name is `{dirname}-{hash}` where the hash fingerprints the absolute path and the machine's
503
+ hostname: re-syncing the same directory from the same machine reuses the same remote folder
504
+ (so only changed files are re-uploaded), while same-named directories from different paths or
505
+ machines don't collide.
506
+ """
507
+ resolved = Path(source).expanduser().resolve()
508
+ digest = hashlib.sha256(f"{platform.node()}:{resolved}".encode()).hexdigest()[:8]
509
+ dirname = resolved.name.replace(" ", "_") or "root"
510
+ return f"{dirname}-{digest}"
511
+
512
+
513
+ def _create_job_spec(
514
+ *,
515
+ image: str,
516
+ command: list[str],
517
+ env: dict[str, Any] | None,
518
+ secrets: dict[str, Any] | None,
519
+ flavor: JobHardware | str | None,
520
+ timeout: int | float | str | None,
521
+ labels: dict[str, str] | None = None,
522
+ volumes: list[Volume] | None = None,
523
+ expose: list[int] | None = None,
524
+ ssh: bool = False,
525
+ ) -> dict[str, Any]:
526
+ # prepare job spec to send to HF Jobs API
527
+ job_spec: dict[str, Any] = {
528
+ "command": command,
529
+ "arguments": [],
530
+ "environment": env or {},
531
+ "flavor": flavor or JobHardware.CPU_BASIC,
532
+ }
533
+ # secrets are optional
534
+ if secrets:
535
+ job_spec["secrets"] = secrets
536
+ # timeout is optional
537
+ if timeout:
538
+ time_units_factors = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24}
539
+ if isinstance(timeout, str) and timeout[-1] in time_units_factors:
540
+ job_spec["timeoutSeconds"] = int(float(timeout[:-1]) * time_units_factors[timeout[-1]])
541
+ else:
542
+ job_spec["timeoutSeconds"] = int(timeout)
543
+ # labels are optional
544
+ if labels:
545
+ job_spec["labels"] = labels
546
+ # volumes are optional
547
+ if volumes:
548
+ job_spec["volumes"] = [vol.to_dict() for vol in volumes]
549
+ # expose ports through the jobs proxy
550
+ if expose:
551
+ job_spec["expose"] = {"ports": expose}
552
+ # make the job container reachable over SSH
553
+ if ssh:
554
+ job_spec["ssh"] = {"enabled": True}
555
+ # input is either from docker hub or from HF spaces
556
+ for prefix in (
557
+ "https://huggingface.co/spaces/",
558
+ "https://hf.co/spaces/",
559
+ "huggingface.co/spaces/",
560
+ "hf.co/spaces/",
561
+ ):
562
+ if image.startswith(prefix):
563
+ job_spec["spaceId"] = image[len(prefix) :]
564
+ break
565
+ else:
566
+ job_spec["dockerImage"] = image
567
+ return job_spec
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_local_folder.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains utilities to handle the `../.cache/huggingface` folder in local directories.
15
+
16
+ First discussed in https://github.com/huggingface/huggingface_hub/issues/1738 to store
17
+ download metadata when downloading files from the hub to a local directory (without
18
+ using the cache).
19
+
20
+ ./.cache/huggingface folder structure:
21
+ [4.0K] data
22
+ ├── [4.0K] .cache
23
+ │ └── [4.0K] huggingface
24
+ │ └── [4.0K] download
25
+ │ ├── [ 16] file.parquet.metadata
26
+ │ ├── [ 16] file.txt.metadata
27
+ │ └── [4.0K] folder
28
+ │ └── [ 16] file.parquet.metadata
29
+ │
30
+ ├── [6.5G] file.parquet
31
+ ├── [1.5K] file.txt
32
+ └── [4.0K] folder
33
+ └── [ 16] file.parquet
34
+
35
+
36
+ Download metadata file structure:
37
+ ```
38
+ # file.txt.metadata
39
+ 11c5a3d5811f50298f278a704980280950aedb10
40
+ a16a55fda99d2f2e7b69cce5cf93ff4ad3049930
41
+ 1712656091.123
42
+
43
+ # file.parquet.metadata
44
+ 11c5a3d5811f50298f278a704980280950aedb10
45
+ 7c5d3f4b8b76583b422fcb9189ad6c89d5d97a094541ce8932dce3ecabde1421
46
+ 1712656091.123
47
+ }
48
+ ```
49
+ """
50
+
51
+ import base64
52
+ import hashlib
53
+ import logging
54
+ import os
55
+ import time
56
+ from dataclasses import dataclass
57
+ from pathlib import Path
58
+
59
+ from .utils import WeakFileLock
60
+
61
+
62
+ logger = logging.getLogger(__name__)
63
+
64
+ CACHEDIR_TAG_CONTENT = (
65
+ "Signature: 8a477f597d28d172789f06886806bc55\n"
66
+ "# This file is a cache directory tag created by huggingface_hub.\n"
67
+ "# For information about cache directory tags, see:\n"
68
+ "#\thttps://bford.info/cachedir/\n"
69
+ )
70
+
71
+
72
+ @dataclass
73
+ class LocalDownloadFilePaths:
74
+ """
75
+ Paths to the files related to a download process in a local dir.
76
+
77
+ Returned by [`get_local_download_paths`].
78
+
79
+ Attributes:
80
+ file_path (`Path`):
81
+ Path where the file will be saved.
82
+ lock_path (`Path`):
83
+ Path to the lock file used to ensure atomicity when reading/writing metadata.
84
+ metadata_path (`Path`):
85
+ Path to the metadata file.
86
+ """
87
+
88
+ file_path: Path
89
+ lock_path: Path
90
+ metadata_path: Path
91
+
92
+ def incomplete_path(self, etag: str) -> Path:
93
+ """Return the path where a file will be temporarily downloaded before being moved to `file_path`."""
94
+ path = self.metadata_path.parent / f"{_short_hash(self.metadata_path.name)}.{etag}.incomplete"
95
+ resolved_path = str(path.resolve())
96
+ # Some Windows versions do not allow for paths longer than 255 characters.
97
+ # In this case, we must specify it as an extended path by using the "\\?\" prefix.
98
+ if os.name == "nt" and len(resolved_path) > 255 and not resolved_path.startswith("\\\\?\\"):
99
+ path = Path("\\\\?\\" + resolved_path)
100
+ return path
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class LocalUploadFilePaths:
105
+ """
106
+ Paths to the files related to an upload process in a local dir.
107
+
108
+ Returned by [`get_local_upload_paths`].
109
+
110
+ Attributes:
111
+ path_in_repo (`str`):
112
+ Path of the file in the repo.
113
+ file_path (`Path`):
114
+ Path where the file will be saved.
115
+ lock_path (`Path`):
116
+ Path to the lock file used to ensure atomicity when reading/writing metadata.
117
+ metadata_path (`Path`):
118
+ Path to the metadata file.
119
+ """
120
+
121
+ path_in_repo: str
122
+ file_path: Path
123
+ lock_path: Path
124
+ metadata_path: Path
125
+
126
+
127
+ @dataclass
128
+ class LocalDownloadFileMetadata:
129
+ """
130
+ Metadata about a file in the local directory related to a download process.
131
+
132
+ Attributes:
133
+ filename (`str`):
134
+ Path of the file in the repo.
135
+ commit_hash (`str`):
136
+ Commit hash of the file in the repo.
137
+ etag (`str`):
138
+ ETag of the file in the repo. Used to check if the file has changed.
139
+ For LFS files, this is the sha256 of the file. For regular files, it corresponds to the git hash.
140
+ timestamp (`int`):
141
+ Unix timestamp of when the metadata was saved i.e. when the metadata was accurate.
142
+ """
143
+
144
+ filename: str
145
+ commit_hash: str
146
+ etag: str
147
+ timestamp: float
148
+
149
+
150
+ @dataclass
151
+ class LocalUploadFileMetadata:
152
+ """
153
+ Metadata about a file in the local directory related to an upload process.
154
+ """
155
+
156
+ size: int
157
+
158
+ # Default values correspond to "we don't know yet"
159
+ timestamp: float | None = None
160
+ should_ignore: bool | None = None
161
+ sha256: str | None = None
162
+ upload_mode: str | None = None
163
+ remote_oid: str | None = None
164
+ is_uploaded: bool = False
165
+ is_committed: bool = False
166
+
167
+ def save(self, paths: LocalUploadFilePaths) -> None:
168
+ """Save the metadata to disk."""
169
+ with WeakFileLock(paths.lock_path):
170
+ with paths.metadata_path.open("w") as f:
171
+ new_timestamp = time.time()
172
+ f.write(str(new_timestamp) + "\n")
173
+
174
+ f.write(str(self.size)) # never None
175
+ f.write("\n")
176
+
177
+ if self.should_ignore is not None:
178
+ f.write(str(int(self.should_ignore)))
179
+ f.write("\n")
180
+
181
+ if self.sha256 is not None:
182
+ f.write(self.sha256)
183
+ f.write("\n")
184
+
185
+ if self.upload_mode is not None:
186
+ f.write(self.upload_mode)
187
+ f.write("\n")
188
+
189
+ if self.remote_oid is not None:
190
+ f.write(self.remote_oid)
191
+ f.write("\n")
192
+
193
+ f.write(str(int(self.is_uploaded)) + "\n")
194
+ f.write(str(int(self.is_committed)) + "\n")
195
+
196
+ self.timestamp = new_timestamp
197
+
198
+
199
+ def get_local_download_paths(local_dir: Path, filename: str) -> LocalDownloadFilePaths:
200
+ """Compute paths to the files related to a download process.
201
+
202
+ Folders containing the paths are all guaranteed to exist.
203
+
204
+ Args:
205
+ local_dir (`Path`):
206
+ Path to the local directory in which files are downloaded.
207
+ filename (`str`):
208
+ Path of the file in the repo.
209
+
210
+ Return:
211
+ [`LocalDownloadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path, incomplete_path).
212
+ """
213
+ # filename is the path in the Hub repository (separated by '/')
214
+ # make sure to have a cross-platform transcription
215
+ sanitized_filename = os.path.join(*filename.split("/"))
216
+ if os.name == "nt":
217
+ if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename:
218
+ raise ValueError(
219
+ f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository"
220
+ " owner to rename this file."
221
+ )
222
+ file_path = local_dir / sanitized_filename
223
+ metadata_path = _huggingface_dir(local_dir) / "download" / f"{sanitized_filename}.metadata"
224
+ lock_path = metadata_path.with_suffix(".lock")
225
+
226
+ # Some Windows versions do not allow for paths longer than 255 characters.
227
+ # In this case, we must specify it as an extended path by using the "\\?\" prefix
228
+ if os.name == "nt":
229
+ if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255:
230
+ file_path = Path("\\\\?\\" + os.path.abspath(file_path))
231
+ lock_path = Path("\\\\?\\" + os.path.abspath(lock_path))
232
+ metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
233
+
234
+ file_path.parent.mkdir(parents=True, exist_ok=True)
235
+ metadata_path.parent.mkdir(parents=True, exist_ok=True)
236
+ return LocalDownloadFilePaths(file_path=file_path, lock_path=lock_path, metadata_path=metadata_path)
237
+
238
+
239
+ def get_local_upload_paths(local_dir: Path, filename: str) -> LocalUploadFilePaths:
240
+ """Compute paths to the files related to an upload process.
241
+
242
+ Folders containing the paths are all guaranteed to exist.
243
+
244
+ Args:
245
+ local_dir (`Path`):
246
+ Path to the local directory that is uploaded.
247
+ filename (`str`):
248
+ Path of the file in the repo.
249
+
250
+ Return:
251
+ [`LocalUploadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path).
252
+ """
253
+ # filename is the path in the Hub repository (separated by '/')
254
+ # make sure to have a cross-platform transcription
255
+ sanitized_filename = os.path.join(*filename.split("/"))
256
+ if os.name == "nt":
257
+ if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename:
258
+ raise ValueError(
259
+ f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository"
260
+ " owner to rename this file."
261
+ )
262
+ file_path = local_dir / sanitized_filename
263
+ metadata_path = _huggingface_dir(local_dir) / "upload" / f"{sanitized_filename}.metadata"
264
+ lock_path = metadata_path.with_suffix(".lock")
265
+
266
+ # Some Windows versions do not allow for paths longer than 255 characters.
267
+ # In this case, we must specify it as an extended path by using the "\\?\" prefix
268
+ if os.name == "nt":
269
+ if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255:
270
+ file_path = Path("\\\\?\\" + os.path.abspath(file_path))
271
+ lock_path = Path("\\\\?\\" + os.path.abspath(lock_path))
272
+ metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
273
+
274
+ file_path.parent.mkdir(parents=True, exist_ok=True)
275
+ metadata_path.parent.mkdir(parents=True, exist_ok=True)
276
+ return LocalUploadFilePaths(
277
+ path_in_repo=filename, file_path=file_path, lock_path=lock_path, metadata_path=metadata_path
278
+ )
279
+
280
+
281
+ def read_download_metadata(local_dir: Path, filename: str) -> LocalDownloadFileMetadata | None:
282
+ """Read metadata about a file in the local directory related to a download process.
283
+
284
+ Args:
285
+ local_dir (`Path`):
286
+ Path to the local directory in which files are downloaded.
287
+ filename (`str`):
288
+ Path of the file in the repo.
289
+
290
+ Return:
291
+ `[LocalDownloadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise.
292
+ """
293
+ paths = get_local_download_paths(local_dir, filename)
294
+ with WeakFileLock(paths.lock_path):
295
+ if paths.metadata_path.exists():
296
+ try:
297
+ with paths.metadata_path.open() as f:
298
+ commit_hash = f.readline().strip()
299
+ etag = f.readline().strip()
300
+ timestamp = float(f.readline().strip())
301
+ metadata = LocalDownloadFileMetadata(
302
+ filename=filename,
303
+ commit_hash=commit_hash,
304
+ etag=etag,
305
+ timestamp=timestamp,
306
+ )
307
+ except Exception as e:
308
+ # remove the metadata file if it is corrupted / not the right format
309
+ logger.warning(
310
+ f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue."
311
+ )
312
+ try:
313
+ paths.metadata_path.unlink()
314
+ except Exception as e:
315
+ logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
316
+ return None
317
+
318
+ try:
319
+ # check if the file exists and hasn't been modified since the metadata was saved
320
+ stat = paths.file_path.stat()
321
+ if (
322
+ stat.st_mtime - 1 <= metadata.timestamp
323
+ ): # allow 1s difference as stat.st_mtime might not be precise
324
+ return metadata
325
+ logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.")
326
+ except FileNotFoundError:
327
+ # file does not exist => metadata is outdated
328
+ return None
329
+ return None
330
+
331
+
332
+ def read_upload_metadata(local_dir: Path, filename: str) -> LocalUploadFileMetadata:
333
+ """Read metadata about a file in the local directory related to an upload process.
334
+
335
+ TODO: factorize logic with `read_download_metadata`.
336
+
337
+ Args:
338
+ local_dir (`Path`):
339
+ Path to the local directory in which files are downloaded.
340
+ filename (`str`):
341
+ Path of the file in the repo.
342
+
343
+ Return:
344
+ `[LocalUploadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise.
345
+ """
346
+ paths = get_local_upload_paths(local_dir, filename)
347
+ with WeakFileLock(paths.lock_path):
348
+ if paths.metadata_path.exists():
349
+ try:
350
+ with paths.metadata_path.open() as f:
351
+ timestamp = float(f.readline().strip())
352
+
353
+ size = int(f.readline().strip()) # never None
354
+
355
+ _should_ignore = f.readline().strip()
356
+ should_ignore = None if _should_ignore == "" else bool(int(_should_ignore))
357
+
358
+ _sha256 = f.readline().strip()
359
+ sha256 = None if _sha256 == "" else _sha256
360
+
361
+ _upload_mode = f.readline().strip()
362
+ upload_mode = None if _upload_mode == "" else _upload_mode
363
+ if upload_mode not in (None, "regular", "lfs"):
364
+ raise ValueError(f"Invalid upload mode in metadata {paths.path_in_repo}: {upload_mode}")
365
+
366
+ _remote_oid = f.readline().strip()
367
+ remote_oid = None if _remote_oid == "" else _remote_oid
368
+
369
+ is_uploaded = bool(int(f.readline().strip()))
370
+ is_committed = bool(int(f.readline().strip()))
371
+
372
+ metadata = LocalUploadFileMetadata(
373
+ timestamp=timestamp,
374
+ size=size,
375
+ should_ignore=should_ignore,
376
+ sha256=sha256,
377
+ upload_mode=upload_mode,
378
+ remote_oid=remote_oid,
379
+ is_uploaded=is_uploaded,
380
+ is_committed=is_committed,
381
+ )
382
+ except Exception as e:
383
+ # remove the metadata file if it is corrupted / not the right format
384
+ logger.warning(
385
+ f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue."
386
+ )
387
+ try:
388
+ paths.metadata_path.unlink()
389
+ except Exception as e:
390
+ logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
391
+
392
+ # corrupted metadata => we don't know anything expect its size
393
+ return LocalUploadFileMetadata(size=paths.file_path.stat().st_size)
394
+
395
+ # TODO: can we do better?
396
+ if (
397
+ metadata.timestamp is not None
398
+ and metadata.is_uploaded # file was uploaded
399
+ and not metadata.is_committed # but not committed
400
+ and time.time() - metadata.timestamp > 20 * 3600 # and it's been more than 20 hours
401
+ ): # => we consider it as garbage-collected by S3
402
+ metadata.is_uploaded = False
403
+
404
+ # check if the file exists and hasn't been modified since the metadata was saved
405
+ try:
406
+ if metadata.timestamp is not None and paths.file_path.stat().st_mtime <= metadata.timestamp:
407
+ return metadata
408
+ logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.")
409
+ except FileNotFoundError:
410
+ # file does not exist => metadata is outdated
411
+ pass
412
+
413
+ # empty metadata => we don't know anything expect its size
414
+ return LocalUploadFileMetadata(size=paths.file_path.stat().st_size)
415
+
416
+
417
+ def write_download_metadata(local_dir: Path, filename: str, commit_hash: str, etag: str) -> None:
418
+ """Write metadata about a file in the local directory related to a download process.
419
+
420
+ Args:
421
+ local_dir (`Path`):
422
+ Path to the local directory in which files are downloaded.
423
+ """
424
+ paths = get_local_download_paths(local_dir, filename)
425
+ with WeakFileLock(paths.lock_path):
426
+ with paths.metadata_path.open("w") as f:
427
+ f.write(f"{commit_hash}\n{etag}\n{time.time()}\n")
428
+
429
+
430
+ def _huggingface_dir(local_dir: Path) -> Path:
431
+ """Return the path to the `.cache/huggingface` directory in a local directory."""
432
+ # Wrap in lru_cache to avoid overwriting the .gitignore file if called multiple times
433
+ path = local_dir / ".cache" / "huggingface"
434
+ path.mkdir(exist_ok=True, parents=True)
435
+
436
+ # Create a CACHEDIR.TAG so backup tools can skip this directory.
437
+ _create_cachedir_tag(path)
438
+
439
+ # Create a .gitignore file in the .cache/huggingface directory if it doesn't exist
440
+ # Should be thread-safe enough like this.
441
+ gitignore = path / ".gitignore"
442
+ gitignore_lock = path / ".gitignore.lock"
443
+ if not gitignore.exists():
444
+ try:
445
+ with WeakFileLock(gitignore_lock, timeout=0.1):
446
+ gitignore.write_text("*")
447
+ except IndexError:
448
+ pass
449
+ except OSError: # TimeoutError, FileNotFoundError, PermissionError, etc.
450
+ pass
451
+ try:
452
+ gitignore_lock.unlink()
453
+ except OSError:
454
+ pass
455
+ return path
456
+
457
+
458
+ def _create_cachedir_tag(cache_dir: Path) -> None:
459
+ """Create a CACHEDIR.TAG file in ``cache_dir`` if one does not already exist.
460
+
461
+ The tag follows the `Cache Directory Tagging Standard <http://www.brynosaurus.com/cachedir/>`_
462
+ so that backup tools can recognize and skip cache directories.
463
+ """
464
+ tag_path = cache_dir / "CACHEDIR.TAG"
465
+ if not tag_path.exists():
466
+ try:
467
+ tag_path.write_text(CACHEDIR_TAG_CONTENT)
468
+ except OSError:
469
+ pass
470
+
471
+
472
+ def _short_hash(filename: str) -> str:
473
+ return base64.urlsafe_b64encode(hashlib.sha1(filename.encode()).digest()).decode()
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_login.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains methods to log in to the Hub."""
15
+
16
+ import html
17
+ import os
18
+ import subprocess
19
+ import sys
20
+ import time
21
+ from datetime import datetime
22
+ from getpass import getpass
23
+ from pathlib import Path
24
+
25
+ from . import constants
26
+ from .errors import DeviceCodeError
27
+ from .utils import (
28
+ ANSI,
29
+ get_token,
30
+ is_google_colab,
31
+ is_notebook,
32
+ list_credential_helpers,
33
+ logging,
34
+ run_subprocess,
35
+ select_choice,
36
+ set_git_credential,
37
+ tabulate,
38
+ unset_git_credential,
39
+ )
40
+ from .utils._auth import (
41
+ _get_token_by_name,
42
+ _get_token_from_environment,
43
+ _get_token_from_file,
44
+ _get_token_from_google_colab,
45
+ _read_stored_tokens_full,
46
+ _save_stored_tokens_full,
47
+ _save_token,
48
+ _write_secret,
49
+ get_stored_tokens,
50
+ )
51
+ from .utils._oauth_device import OAuthTokenResponse, poll_device_token, request_device_code
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+
57
+ def login(
58
+ token: str | None = None,
59
+ *,
60
+ add_to_git_credential: bool = False,
61
+ skip_if_logged_in: bool = True,
62
+ ) -> None:
63
+ """Login the machine to access the Hub.
64
+
65
+ The `token` is persisted in cache and set as a git credential. Once done, the machine
66
+ is logged in and the access token will be available across all `huggingface_hub`
67
+ components. If `token` is not provided, a browser-based OAuth flow is used to
68
+ authenticate: open a URL, enter a short code, and the token is retrieved and saved.
69
+ In a terminal, you can also choose to paste an existing access token instead.
70
+
71
+ To log in from outside of a script, one can also use `hf auth login` which is
72
+ a cli command that wraps [`login`].
73
+
74
+ > [!TIP]
75
+ > When the token is not passed, [`login`] will automatically detect if the script runs
76
+ > in a notebook or not. However, this detection might not be accurate due to the
77
+ > variety of notebooks that exists nowadays. If that is the case, you can always force
78
+ > the UI by using [`notebook_login`] or [`interpreter_login`].
79
+
80
+ Args:
81
+ token (`str`, *optional*):
82
+ User access token to generate from https://huggingface.co/settings/token.
83
+ add_to_git_credential (`bool`, defaults to `False`):
84
+ If `True`, token will be set as git credential. If no git credential helper
85
+ is configured, a warning will be displayed to the user. Only used when `token`
86
+ is provided; ignored by the browser-based flow.
87
+ skip_if_logged_in (`bool`, defaults to `True`):
88
+ If `True`, do not prompt for token if user is already logged in.
89
+ Set to `False` to force re-login. In CLI, use `--force` instead.
90
+ Raises:
91
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
92
+ If an organization token is passed. Only personal account tokens are valid
93
+ to log in.
94
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
95
+ If token is invalid.
96
+ [`DeviceCodeError`]
97
+ If the browser-based login fails (authorization denied, code expired, ...).
98
+ """
99
+ if token is not None:
100
+ if not add_to_git_credential:
101
+ logger.info(
102
+ "The token has not been saved to the git credentials helper. Pass "
103
+ "`add_to_git_credential=True` in this function directly or "
104
+ "`--add-to-git-credential` if using via `hf`CLI if "
105
+ "you want to set the git credential as well."
106
+ )
107
+ _validate_and_save_token(token, add_to_git_credential=add_to_git_credential)
108
+ return
109
+ if add_to_git_credential:
110
+ logger.warning(
111
+ "`add_to_git_credential=True` is only supported when a token is passed directly. "
112
+ "It is ignored by the browser-based login."
113
+ )
114
+ if is_notebook():
115
+ notebook_login(skip_if_logged_in=skip_if_logged_in)
116
+ else:
117
+ interpreter_login(skip_if_logged_in=skip_if_logged_in)
118
+
119
+
120
+ def logout(token_name: str | None = None) -> None:
121
+ """Logout the machine from the Hub.
122
+
123
+ Token is deleted from the machine and removed from git credential.
124
+
125
+ Args:
126
+ token_name (`str`, *optional*):
127
+ Name of the access token to logout from. If `None`, will log out from all saved access tokens.
128
+ Raises:
129
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
130
+ If the access token name is not found.
131
+ """
132
+ if get_token() is None and not get_stored_tokens(): # No active token and no saved access tokens
133
+ logger.warning("Not logged in!")
134
+ return
135
+ if not token_name:
136
+ # Delete all saved access tokens and token
137
+ for file_path in (constants.HF_TOKEN_PATH, constants.HF_STORED_TOKENS_PATH):
138
+ try:
139
+ Path(file_path).unlink()
140
+ except FileNotFoundError:
141
+ pass
142
+ logger.info("Successfully logged out from all access tokens.")
143
+ else:
144
+ _logout_from_token(token_name)
145
+ logger.info(f"Successfully logged out from access token: {token_name}.")
146
+
147
+ unset_git_credential()
148
+
149
+ # Check if still logged in
150
+ if _get_token_from_google_colab() is not None:
151
+ raise OSError(
152
+ "You are automatically logged in using a Google Colab secret.\n"
153
+ "To log out, you must unset the `HF_TOKEN` secret in your Colab settings."
154
+ )
155
+ if _get_token_from_environment() is not None:
156
+ raise OSError(
157
+ "Token has been deleted from your machine but you are still logged in.\n"
158
+ "To log out, you must clear out both `HF_TOKEN` and `HUGGING_FACE_HUB_TOKEN` environment variables."
159
+ )
160
+
161
+
162
+ def auth_switch(token_name: str, add_to_git_credential: bool = False) -> None:
163
+ """Switch to a different access token.
164
+
165
+ Args:
166
+ token_name (`str`):
167
+ Name of the access token to switch to.
168
+ add_to_git_credential (`bool`, defaults to `False`):
169
+ If `True`, token will be set as git credential. If no git credential helper
170
+ is configured, a warning will be displayed to the user. If `token` is `None`,
171
+ the value of `add_to_git_credential` is ignored and will be prompted again
172
+ to the end user.
173
+
174
+ Raises:
175
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
176
+ If the access token name is not found.
177
+ """
178
+ token = _get_token_by_name(token_name)
179
+ if not token:
180
+ raise ValueError(f"Access token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}")
181
+ # Write token to HF_TOKEN_PATH
182
+ _set_active_token(token_name, add_to_git_credential)
183
+ logger.info(f"The current active token is: {token_name}")
184
+ token_from_environment = _get_token_from_environment()
185
+ if token_from_environment is not None and token_from_environment != token:
186
+ logger.warning(
187
+ "The environment variable `HF_TOKEN` is set and will override the access token you've just switched to."
188
+ )
189
+
190
+
191
+ def auth_list() -> None:
192
+ """List all stored access tokens."""
193
+ # Resolve the current token before reading the file: `get_token()` may refresh an OAuth
194
+ # token and rewrite the stored tokens on the way.
195
+ current_token = get_token()
196
+ stored_tokens = _read_stored_tokens_full()
197
+
198
+ if not stored_tokens:
199
+ if _get_token_from_environment():
200
+ logger.info("No stored access tokens found.")
201
+ logger.warning("Note: Environment variable `HF_TOKEN` is set and is the current active token.")
202
+ else:
203
+ logger.info("No access tokens found.")
204
+ return
205
+ show_expires = any("expires_at" in fields for fields in stored_tokens.values())
206
+ headers = [" ", "name", "token"] + (["expires"] if show_expires else [])
207
+
208
+ current_token_name = None
209
+ rows: list[list[str | int]] = []
210
+ for token_name, fields in stored_tokens.items():
211
+ token = fields.get("hf_token", "<not set>")
212
+ if token == current_token:
213
+ current_token_name = token_name
214
+ masked_token = f"{token[:3]}****{token[-4:]}" if token != "<not set>" else token
215
+ row: list[str | int] = ["*" if token == current_token else "", token_name, masked_token]
216
+ if show_expires:
217
+ row.append(_format_expiration(fields.get("expires_at")))
218
+ rows.append(row)
219
+ print(tabulate(rows, headers=headers))
220
+
221
+ if _get_token_from_environment():
222
+ logger.warning(
223
+ "\nNote: Environment variable `HF_TOKEN` is set and is the current active token independently from the stored tokens listed above."
224
+ )
225
+ elif current_token_name is None:
226
+ logger.warning(
227
+ "\nNote: No active token is set and no environment variable `HF_TOKEN` is found. Use `hf auth login` to log in."
228
+ )
229
+
230
+
231
+ ###
232
+ # Device Code OAuth login (RFC 8628)
233
+ ###
234
+
235
+
236
+ def _device_code_login() -> None:
237
+ """Run the Device Code OAuth flow: request a code, prompt the user to authorize it in a browser,
238
+ poll for the token and save it."""
239
+ device_info = request_device_code()
240
+
241
+ # The complete URI has the code pre-filled when the server supports it.
242
+ print(f"\n Open this URL in your browser:\n {device_info['verification_uri_complete']}\n")
243
+ print(f" And enter the code: {device_info['user_code']}\n")
244
+
245
+ print(" Waiting for authorization", end="", flush=True)
246
+ try:
247
+ response = poll_device_token(device_info, on_pending=lambda: print(".", end="", flush=True))
248
+ finally:
249
+ print() # newline after the progress dots, also on failure
250
+
251
+ _save_oauth_token(response)
252
+
253
+
254
+ def _save_oauth_token(response: OAuthTokenResponse) -> tuple[str, str]:
255
+ """Validate and persist a token response from the device code flow, including refresh metadata."""
256
+ expires_in = response.get("expires_in")
257
+ token_name, username = _validate_and_save_token(
258
+ response["access_token"],
259
+ add_to_git_credential=False,
260
+ refresh_token=response.get("refresh_token"),
261
+ expires_at=int(time.time()) + int(expires_in) if expires_in else None,
262
+ )
263
+ if note := _expiration_note(response):
264
+ logger.info(f"Note: {note}")
265
+ return token_name, username
266
+
267
+
268
+ def _expiration_note(response: OAuthTokenResponse) -> str | None:
269
+ """Human-readable note about the lifetime of a freshly obtained OAuth token, if known."""
270
+ expires_in = response.get("expires_in")
271
+ if not expires_in:
272
+ return None
273
+ if response.get("refresh_token"):
274
+ return "This token will be refreshed automatically when it expires."
275
+ days = max(1, int(expires_in) // 86400)
276
+ return f"This token expires in {days} days. Log in again to renew it."
277
+
278
+
279
+ ###
280
+ # Interpreter-based login (text)
281
+ ###
282
+
283
+
284
+ def interpreter_login(*, skip_if_logged_in: bool = True) -> None:
285
+ """
286
+ Displays a prompt to log in to the HF website and store the token.
287
+
288
+ This is equivalent to [`login`] without passing a token when not run in a notebook.
289
+ [`interpreter_login`] is useful if you want to force the use of the terminal prompt
290
+ instead of a notebook flow.
291
+
292
+ For more details, see [`login`].
293
+
294
+ Args:
295
+ skip_if_logged_in (`bool`, defaults to `True`):
296
+ If `True`, do not prompt for token if user is already logged in.
297
+ Set to `False` to force re-login. In CLI, use `--force` instead.
298
+ """
299
+ if skip_if_logged_in and get_token() is not None:
300
+ logger.info("User is already logged in. Use `hf auth login --force` to force re-login.")
301
+ return
302
+
303
+ if get_token() is not None:
304
+ logger.info("Note: a token is already saved on this machine. Logging in again will replace the active token.")
305
+
306
+ if _prompt_login_method() == "token":
307
+ _paste_token_login()
308
+ else:
309
+ _device_code_login()
310
+
311
+
312
+ def _prompt_login_method() -> str:
313
+ """Ask the user how to log in: "browser" (default) or "token". Never prompts without a TTY."""
314
+ if sys.stdin is None or not sys.stdin.isatty():
315
+ return "browser"
316
+ choice = select_choice("How would you like to log in?", ["Log in with your browser", "Paste an access token"])
317
+ return "browser" if choice == 0 else "token"
318
+
319
+
320
+ def _paste_token_login() -> None:
321
+ logger.info(
322
+ " To log in, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens ."
323
+ )
324
+ if os.name == "nt":
325
+ logger.info("Token can be pasted using 'Right-Click'.")
326
+ token = getpass("Enter your token (input will not be visible): ")
327
+ _validate_and_save_token(token=token, add_to_git_credential=False)
328
+
329
+
330
+ ###
331
+ # Notebook-based login
332
+ ###
333
+
334
+
335
+ def notebook_login(*, skip_if_logged_in: bool = True) -> None:
336
+ """
337
+ Displays a prompt to log in to the HF website and store the token.
338
+
339
+ This is equivalent to [`login`] without passing a token when run in a notebook.
340
+ [`notebook_login`] is useful if you want to force the use of the notebook flow
341
+ instead of a prompt in the terminal.
342
+
343
+ For more details, see [`login`].
344
+
345
+ Args:
346
+ skip_if_logged_in (`bool`, defaults to `True`):
347
+ If `True`, do not prompt for token if user is already logged in.
348
+ Set to `False` to force re-login. In CLI, use `--force` instead.
349
+ """
350
+ if skip_if_logged_in and get_token() is not None:
351
+ logger.info("User is already logged in. Use `hf auth login --force` to force re-login.")
352
+ return
353
+
354
+ try:
355
+ from IPython.display import HTML, display # type: ignore
356
+ except ImportError:
357
+ # Not in a notebook environment: fall back to the terminal flow
358
+ interpreter_login(skip_if_logged_in=False)
359
+ return
360
+
361
+ device_info = request_device_code()
362
+ # Escape server-provided values: they end up in raw notebook HTML.
363
+ verification_uri = html.escape(device_info["verification_uri"])
364
+ verification_uri_complete = html.escape(device_info["verification_uri_complete"])
365
+
366
+ display(
367
+ HTML(
368
+ '<center><img src="https://huggingface.co/front/assets/huggingface_logo-noborder.svg"'
369
+ ' width="100" alt="Hugging Face"><br><br>'
370
+ "<p>To log in, open this URL and enter the code:</p>"
371
+ f'<p><a href="{verification_uri_complete}" target="_blank"><b>{verification_uri}</b></a></p>'
372
+ '<p style="font-size: 1.6em; letter-spacing: 0.3em; font-family: monospace;">'
373
+ f"<b>{html.escape(device_info['user_code'])}</b></p></center>"
374
+ )
375
+ )
376
+ display(HTML("<center><i>Waiting for authorization...</i></center>"))
377
+ try:
378
+ response = poll_device_token(device_info)
379
+ except DeviceCodeError as e:
380
+ display(HTML(f"<center><b style='color: red;'>Login failed: {html.escape(str(e))}</b></center>"))
381
+ return
382
+
383
+ try:
384
+ token_name, username = _save_oauth_token(response)
385
+ except Exception as error:
386
+ display(HTML(f"<center><b style='color: red;'>{html.escape(str(error))}</b></center>"))
387
+ return
388
+
389
+ message = f"Login successful. Logged in as <b>{html.escape(username)}</b> (token: <code>{html.escape(token_name)}</code>)."
390
+ if note := _expiration_note(response):
391
+ message += f"<br>{html.escape(note)}"
392
+ display(HTML(f"<center>{message}</center>"))
393
+
394
+
395
+ ###
396
+ # Login private helpers
397
+ ###
398
+
399
+
400
+ def _validate_and_save_token(
401
+ token: str,
402
+ add_to_git_credential: bool,
403
+ refresh_token: str | None = None,
404
+ expires_at: int | None = None,
405
+ ) -> tuple[str, str]:
406
+ """Validate a token against the Hub, save it to the stored tokens file and set it as active.
407
+
408
+ The token is stored under its `displayName` from the whoami response, or `oauth-{username}`
409
+ for OAuth tokens (which have no display name).
410
+
411
+ Args:
412
+ token (`str`):
413
+ The access token.
414
+ add_to_git_credential (`bool`):
415
+ Whether to save the token to the git credential helpers.
416
+ refresh_token (`str`, *optional*):
417
+ OAuth refresh token to persist alongside the access token.
418
+ expires_at (`int`, *optional*):
419
+ Unix timestamp at which the access token expires.
420
+
421
+ Returns:
422
+ `tuple[str, str]`: The token name and the username.
423
+ """
424
+ from .hf_api import whoami # avoid circular import
425
+
426
+ if token.startswith("api_org"):
427
+ raise ValueError("You must use your personal account token, not an organization token.")
428
+
429
+ token_info = whoami(token)
430
+ username = token_info["name"]
431
+
432
+ access_token_info = (token_info.get("auth") or {}).get("accessToken") or {}
433
+ if role := access_token_info.get("role"):
434
+ logger.info(f"Token is valid (permission: {role}).")
435
+ else:
436
+ logger.info("Token is valid.")
437
+
438
+ token_name = access_token_info.get("displayName") or f"oauth-{username}"
439
+
440
+ # Store token locally
441
+ _save_token(token=token, token_name=token_name, refresh_token=refresh_token, expires_at=expires_at)
442
+ # Set active token
443
+ _set_active_token(token_name=token_name, add_to_git_credential=add_to_git_credential)
444
+ logger.info("Login successful.")
445
+ if _get_token_from_environment():
446
+ logger.warning(
447
+ "Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured."
448
+ )
449
+ else:
450
+ logger.info(f"The current active token is: `{token_name}`")
451
+ return token_name, username
452
+
453
+
454
+ def _logout_from_token(token_name: str) -> None:
455
+ """Logout from a specific access token.
456
+
457
+ Args:
458
+ token_name (`str`):
459
+ The name of the access token to logout from.
460
+ """
461
+ stored_tokens = _read_stored_tokens_full()
462
+ # If there is no access tokens saved or the access token name is not found, do nothing
463
+ if token_name not in stored_tokens:
464
+ return
465
+
466
+ fields = stored_tokens.pop(token_name)
467
+ _save_stored_tokens_full(stored_tokens)
468
+
469
+ if fields.get("hf_token") == _get_token_from_file():
470
+ logger.warning(f"Active token '{token_name}' has been deleted.")
471
+ Path(constants.HF_TOKEN_PATH).unlink(missing_ok=True)
472
+
473
+
474
+ def _format_expiration(expires_at: str | None) -> str:
475
+ """Format an `expires_at` unix timestamp for display in `auth list`."""
476
+ if not expires_at:
477
+ return ""
478
+ try:
479
+ timestamp = int(expires_at)
480
+ except ValueError:
481
+ return ""
482
+ date_str = datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d")
483
+ return f"{date_str} (expired)" if timestamp < time.time() else date_str
484
+
485
+
486
+ def _set_active_token(
487
+ token_name: str,
488
+ add_to_git_credential: bool,
489
+ ) -> None:
490
+ """Set the active access token.
491
+
492
+ Args:
493
+ token_name (`str`):
494
+ The name of the token to set as active.
495
+ """
496
+ token = _get_token_by_name(token_name)
497
+ if not token:
498
+ raise ValueError(f"Token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}")
499
+ if add_to_git_credential:
500
+ if _is_git_credential_helper_configured():
501
+ set_git_credential(token)
502
+ logger.info(
503
+ "Your token has been saved in your configured git credential helpers"
504
+ + f" ({','.join(list_credential_helpers())})."
505
+ )
506
+ else:
507
+ logger.warning("Token has not been saved to git credential helper.")
508
+ # Write token to HF_TOKEN_PATH
509
+ _write_secret(Path(constants.HF_TOKEN_PATH), token)
510
+ logger.info(f"Your token has been saved to {constants.HF_TOKEN_PATH}")
511
+
512
+
513
+ def _is_git_credential_helper_configured() -> bool:
514
+ """Check if a git credential helper is configured.
515
+
516
+ Warns user if not the case (except for Google Colab where "store" is set by default
517
+ by `huggingface_hub`).
518
+ """
519
+ helpers = list_credential_helpers()
520
+ if len(helpers) > 0:
521
+ return True # Do not warn: at least 1 helper is set
522
+
523
+ # Only in Google Colab to avoid the warning message
524
+ # See https://github.com/huggingface/huggingface_hub/issues/1043#issuecomment-1247010710
525
+ if is_google_colab():
526
+ _set_store_as_git_credential_helper_globally()
527
+ return True # Do not warn: "store" is used by default in Google Colab
528
+
529
+ # Otherwise, warn user
530
+ print(
531
+ ANSI.red(
532
+ "Cannot authenticate through git-credential as no helper is defined on your"
533
+ " machine.\nYou might have to re-authenticate when pushing to the Hugging"
534
+ " Face Hub.\nRun the following command in your terminal in case you want to"
535
+ " set the 'store' credential helper as default.\n\ngit config --global"
536
+ " credential.helper store\n\nRead"
537
+ " https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more"
538
+ " details."
539
+ )
540
+ )
541
+ return False
542
+
543
+
544
+ def _set_store_as_git_credential_helper_globally() -> None:
545
+ """Set globally the credential.helper to `store`.
546
+
547
+ To be used only in Google Colab as we assume the user doesn't care about the git
548
+ credential config. It is the only particular case where we don't want to display the
549
+ warning message in [`notebook_login()`].
550
+
551
+ Related:
552
+ - https://github.com/huggingface/huggingface_hub/issues/1043
553
+ - https://github.com/huggingface/huggingface_hub/issues/1051
554
+ - https://git-scm.com/docs/git-credential-store
555
+ """
556
+ try:
557
+ run_subprocess("git config --global credential.helper store")
558
+ except subprocess.CalledProcessError as exc:
559
+ raise OSError(exc.stderr)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_oauth.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import hashlib
3
+ import logging
4
+ import os
5
+ import time
6
+ import urllib.parse
7
+ import warnings
8
+ from dataclasses import dataclass
9
+ from typing import TYPE_CHECKING, Literal
10
+
11
+ from . import constants
12
+ from .hf_api import whoami
13
+ from .utils import experimental, get_token
14
+
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ if TYPE_CHECKING:
19
+ import fastapi
20
+
21
+
22
+ @dataclass
23
+ class OAuthOrgInfo:
24
+ """
25
+ Information about an organization linked to a user logged in with OAuth.
26
+
27
+ Attributes:
28
+ sub (`str`):
29
+ Unique identifier for the org. OpenID Connect field.
30
+ name (`str`):
31
+ The org's full name. OpenID Connect field.
32
+ preferred_username (`str`):
33
+ The org's username. OpenID Connect field.
34
+ picture (`str`):
35
+ The org's profile picture URL. OpenID Connect field.
36
+ plan (`str`, *optional*):
37
+ The org's plan (e.g., "enterprise", "team"). Hugging Face field.
38
+ can_pay (`Optional[bool]`, *optional*):
39
+ Whether the org has a payment method set up. Hugging Face field.
40
+ role_in_org (`Optional[str]`, *optional*):
41
+ The user's role in the org. Hugging Face field.
42
+ security_restrictions (`Optional[list[Literal["ip", "token-policy", "mfa", "sso"]]]`, *optional*):
43
+ Array of security restrictions that the user hasn't completed for this org. Possible values: "ip", "token-policy", "mfa", "sso". Hugging Face field.
44
+ """
45
+
46
+ sub: str
47
+ name: str
48
+ preferred_username: str
49
+ picture: str
50
+ plan: str | None = None
51
+ can_pay: bool | None = None
52
+ role_in_org: str | None = None
53
+ security_restrictions: list[Literal["ip", "token-policy", "mfa", "sso"]] | None = None
54
+
55
+
56
+ @dataclass
57
+ class OAuthUserInfo:
58
+ """
59
+ Information about a user logged in with OAuth.
60
+
61
+ Attributes:
62
+ sub (`str`):
63
+ Unique identifier for the user, even in case of rename. OpenID Connect field.
64
+ name (`str`):
65
+ The user's full name. OpenID Connect field.
66
+ preferred_username (`str`):
67
+ The user's username. OpenID Connect field.
68
+ email_verified (`Optional[bool]`, *optional*):
69
+ Indicates if the user's email is verified. OpenID Connect field.
70
+ email (`Optional[str]`, *optional*):
71
+ The user's email address. OpenID Connect field.
72
+ picture (`str`):
73
+ The user's profile picture URL. OpenID Connect field.
74
+ profile (`str`):
75
+ The user's profile URL. OpenID Connect field.
76
+ website (`Optional[str]`, *optional*):
77
+ The user's website URL. OpenID Connect field.
78
+ is_pro (`bool`):
79
+ Whether the user is a pro user. Hugging Face field.
80
+ can_pay (`Optional[bool]`, *optional*):
81
+ Whether the user has a payment method set up. Hugging Face field.
82
+ orgs (`Optional[list[OrgInfo]]`, *optional*):
83
+ List of organizations the user is part of. Hugging Face field.
84
+ """
85
+
86
+ sub: str
87
+ name: str
88
+ preferred_username: str
89
+ email_verified: bool | None
90
+ email: str | None
91
+ picture: str
92
+ profile: str
93
+ website: str | None
94
+ is_pro: bool
95
+ can_pay: bool | None
96
+ orgs: list[OAuthOrgInfo] | None
97
+
98
+
99
+ @dataclass
100
+ class OAuthInfo:
101
+ """
102
+ Information about the OAuth login.
103
+
104
+ Attributes:
105
+ access_token (`str`):
106
+ The access token.
107
+ access_token_expires_at (`datetime.datetime`):
108
+ The expiration date of the access token.
109
+ user_info ([`OAuthUserInfo`]):
110
+ The user information.
111
+ state (`str`, *optional*):
112
+ State passed to the OAuth provider in the original request to the OAuth provider.
113
+ scope (`str`):
114
+ Granted scope.
115
+ """
116
+
117
+ access_token: str
118
+ access_token_expires_at: datetime.datetime
119
+ user_info: OAuthUserInfo
120
+ state: str | None
121
+ scope: str
122
+
123
+
124
+ @experimental
125
+ def attach_huggingface_oauth(app: "fastapi.FastAPI", route_prefix: str = "/"):
126
+ """
127
+ Add OAuth endpoints to a FastAPI app to enable OAuth login with Hugging Face.
128
+
129
+ How to use:
130
+ - Call this method on your FastAPI app to add the OAuth endpoints.
131
+ - Inside your route handlers, call `parse_huggingface_oauth(request)` to retrieve the OAuth info.
132
+ - If user is logged in, an [`OAuthInfo`] object is returned with the user's info. If not, `None` is returned.
133
+ - In your app, make sure to add links to `/oauth/huggingface/login` and `/oauth/huggingface/logout` for the user to log in and out.
134
+
135
+ Example:
136
+ ```py
137
+ from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth
138
+
139
+ # Create a FastAPI app
140
+ app = FastAPI()
141
+
142
+ # Add OAuth endpoints to the FastAPI app
143
+ attach_huggingface_oauth(app)
144
+
145
+ # Add a route that greets the user if they are logged in
146
+ @app.get("/")
147
+ def greet_json(request: Request):
148
+ # Retrieve the OAuth info from the request
149
+ oauth_info = parse_huggingface_oauth(request) # e.g. OAuthInfo dataclass
150
+ if oauth_info is None:
151
+ return {"msg": "Not logged in!"}
152
+ return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"}
153
+ ```
154
+ """
155
+ # TODO: handle generic case (handling OAuth in a non-Space environment with custom dev values) (low priority)
156
+
157
+ # Add SessionMiddleware to the FastAPI app to store the OAuth info in the session.
158
+ # Session Middleware requires a secret key to sign the cookies. Let's use a hash
159
+ # of the OAuth secret key to make it unique to the Space + updated in case OAuth
160
+ # config gets updated. When ran locally, we use an empty string as a secret key.
161
+ try:
162
+ from starlette.middleware.sessions import SessionMiddleware
163
+ except ImportError as e:
164
+ raise ImportError(
165
+ "Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add "
166
+ "`huggingface_hub[oauth]` to your requirements.txt file in order to install the required dependencies."
167
+ ) from e
168
+ session_secret = (constants.OAUTH_CLIENT_SECRET or "") + "-v1"
169
+ app.add_middleware(
170
+ SessionMiddleware, # type: ignore
171
+ secret_key=hashlib.sha256(session_secret.encode()).hexdigest(),
172
+ same_site="none",
173
+ https_only=True,
174
+ ) # type: ignore
175
+
176
+ # Add OAuth endpoints to the FastAPI app:
177
+ # - {route_prefix}/oauth/huggingface/login
178
+ # - {route_prefix}/oauth/huggingface/callback
179
+ # - {route_prefix}/oauth/huggingface/logout
180
+ # If the app is running in a Space, OAuth is enabled normally.
181
+ # Otherwise, we mock the endpoints to make the user log in with a fake user profile - without any calls to hf.co.
182
+ route_prefix = route_prefix.strip("/")
183
+ if os.getenv("SPACE_ID") is not None:
184
+ logger.info("OAuth is enabled in the Space. Adding OAuth routes.")
185
+ _add_oauth_routes(app, route_prefix=route_prefix)
186
+ else:
187
+ logger.info("App is not running in a Space. Adding mocked OAuth routes.")
188
+ _add_mocked_oauth_routes(app, route_prefix=route_prefix)
189
+
190
+
191
+ def parse_huggingface_oauth(request: "fastapi.Request") -> OAuthInfo | None:
192
+ """
193
+ Returns the information from a logged-in user as a [`OAuthInfo`] object.
194
+
195
+ For flexibility and future-proofing, this method is very lax in its parsing and does not raise errors.
196
+ Missing fields are set to `None` without a warning.
197
+
198
+ Return `None`, if the user is not logged in (no info in session cookie).
199
+
200
+ See [`attach_huggingface_oauth`] for an example on how to use this method.
201
+ """
202
+ if "oauth_info" not in request.session:
203
+ logger.debug("No OAuth info in session.")
204
+ return None
205
+
206
+ logger.debug("Parsing OAuth info from session.")
207
+ oauth_data = request.session["oauth_info"]
208
+ user_data = oauth_data.get("userinfo", {})
209
+ orgs_data = user_data.get("orgs", [])
210
+
211
+ orgs = (
212
+ [
213
+ OAuthOrgInfo(
214
+ sub=org.get("sub"),
215
+ name=org.get("name"),
216
+ preferred_username=org.get("preferred_username"),
217
+ picture=org.get("picture"),
218
+ plan=org.get("plan"),
219
+ can_pay=org.get("canPay"),
220
+ role_in_org=org.get("roleInOrg"),
221
+ security_restrictions=org.get("securityRestrictions"),
222
+ )
223
+ for org in orgs_data
224
+ ]
225
+ if orgs_data
226
+ else None
227
+ )
228
+
229
+ user_info = OAuthUserInfo(
230
+ sub=user_data.get("sub"),
231
+ name=user_data.get("name"),
232
+ preferred_username=user_data.get("preferred_username"),
233
+ email_verified=user_data.get("email_verified"),
234
+ email=user_data.get("email"),
235
+ picture=user_data.get("picture"),
236
+ profile=user_data.get("profile"),
237
+ website=user_data.get("website"),
238
+ is_pro=user_data.get("isPro"),
239
+ can_pay=user_data.get("canPay"),
240
+ orgs=orgs,
241
+ )
242
+
243
+ return OAuthInfo(
244
+ access_token=oauth_data.get("access_token"),
245
+ access_token_expires_at=datetime.datetime.fromtimestamp(oauth_data.get("expires_at")),
246
+ user_info=user_info,
247
+ state=oauth_data.get("state"),
248
+ scope=oauth_data.get("scope"),
249
+ )
250
+
251
+
252
+ def _add_oauth_routes(app: "fastapi.FastAPI", route_prefix: str) -> None:
253
+ """Add OAuth routes to the FastAPI app (login, callback handler and logout)."""
254
+ try:
255
+ import fastapi
256
+ from authlib.integrations.base_client.errors import MismatchingStateError
257
+ from authlib.integrations.starlette_client import OAuth
258
+ from fastapi.responses import RedirectResponse
259
+ except ImportError as e:
260
+ raise ImportError(
261
+ "Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add "
262
+ "`huggingface_hub[oauth]` to your requirements.txt file."
263
+ ) from e
264
+
265
+ # Check environment variables
266
+ msg = (
267
+ "OAuth is required but '{}' environment variable is not set. Make sure you've enabled OAuth in your Space by"
268
+ " setting `hf_oauth: true` in the Space metadata."
269
+ )
270
+ if constants.OAUTH_CLIENT_ID is None:
271
+ raise ValueError(msg.format("OAUTH_CLIENT_ID"))
272
+ if constants.OAUTH_CLIENT_SECRET is None:
273
+ raise ValueError(msg.format("OAUTH_CLIENT_SECRET"))
274
+ if constants.OAUTH_SCOPES is None:
275
+ raise ValueError(msg.format("OAUTH_SCOPES"))
276
+ if constants.OPENID_PROVIDER_URL is None:
277
+ raise ValueError(msg.format("OPENID_PROVIDER_URL"))
278
+
279
+ # Register OAuth server
280
+ oauth = OAuth()
281
+ oauth.register(
282
+ name="huggingface",
283
+ client_id=constants.OAUTH_CLIENT_ID,
284
+ client_secret=constants.OAUTH_CLIENT_SECRET,
285
+ client_kwargs={"scope": constants.OAUTH_SCOPES},
286
+ server_metadata_url=constants.OPENID_PROVIDER_URL + "/.well-known/openid-configuration",
287
+ )
288
+
289
+ login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix)
290
+
291
+ # Register OAuth endpoints
292
+ @app.get(login_uri)
293
+ async def oauth_login(request: fastapi.Request) -> RedirectResponse:
294
+ """Endpoint that redirects to HF OAuth page."""
295
+ redirect_uri = _generate_redirect_uri(request)
296
+ return await oauth.huggingface.authorize_redirect(request, redirect_uri) # type: ignore
297
+
298
+ @app.get(callback_uri)
299
+ async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse:
300
+ """Endpoint that handles the OAuth callback."""
301
+ try:
302
+ oauth_info = await oauth.huggingface.authorize_access_token(request) # type: ignore
303
+ except MismatchingStateError:
304
+ # Parse query params
305
+ nb_redirects = int(request.query_params.get("_nb_redirects", 0))
306
+ target_url = request.query_params.get("_target_url")
307
+
308
+ # Build redirect URI with the same query params as before and bump nb_redirects count
309
+ query_params: dict[str, int | str] = {"_nb_redirects": nb_redirects + 1}
310
+ if target_url:
311
+ query_params["_target_url"] = target_url
312
+
313
+ redirect_uri = f"{login_uri}?{urllib.parse.urlencode(query_params)}"
314
+
315
+ # If the user is redirected more than 3 times, it is very likely that the cookie is not working properly.
316
+ # (e.g. browser is blocking third-party cookies in iframe). In this case, redirect the user in the
317
+ # non-iframe view.
318
+ if nb_redirects > constants.OAUTH_MAX_REDIRECTS:
319
+ host = os.environ.get("SPACE_HOST")
320
+ if host is None: # cannot happen in a Space
321
+ raise RuntimeError(
322
+ "App is not running in a Space (SPACE_HOST environment variable is not set). Cannot redirect to non-iframe view."
323
+ ) from None
324
+ host_url = "https://" + host.rstrip("/")
325
+ return RedirectResponse(host_url + redirect_uri)
326
+
327
+ # Redirect the user to the login page again
328
+ return RedirectResponse(redirect_uri)
329
+
330
+ # OAuth login worked => store the user info in the session and redirect
331
+ logger.debug("Successfully logged in with OAuth. Storing user info in session.")
332
+ request.session["oauth_info"] = oauth_info
333
+ return RedirectResponse(_get_redirect_target(request))
334
+
335
+ @app.get(logout_uri)
336
+ async def oauth_logout(request: fastapi.Request) -> RedirectResponse:
337
+ """Endpoint that logs out the user (e.g. delete info from cookie session)."""
338
+ logger.debug("Logged out with OAuth. Removing user info from session.")
339
+ request.session.pop("oauth_info", None)
340
+ return RedirectResponse(_get_redirect_target(request))
341
+
342
+
343
+ def _add_mocked_oauth_routes(app: "fastapi.FastAPI", route_prefix: str = "/") -> None:
344
+ """Add fake oauth routes if app is run locally and OAuth is enabled.
345
+
346
+ Using OAuth will have the same behavior as in a Space but instead of authenticating with HF, a mocked user profile
347
+ is added to the session.
348
+ """
349
+ try:
350
+ import fastapi
351
+ from fastapi.responses import RedirectResponse
352
+ from starlette.datastructures import URL
353
+ except ImportError as e:
354
+ raise ImportError(
355
+ "Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add "
356
+ "`huggingface_hub[oauth]` to your requirements.txt file."
357
+ ) from e
358
+
359
+ warnings.warn(
360
+ "OAuth is not supported outside of a Space environment. To help you debug your app locally, the oauth endpoints"
361
+ " are mocked to return your profile and token. To make it work, your machine must be logged in to Huggingface."
362
+ )
363
+ mocked_oauth_info = _get_mocked_oauth_info()
364
+
365
+ login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix)
366
+
367
+ # Define OAuth routes
368
+ @app.get(login_uri)
369
+ async def oauth_login(request: fastapi.Request) -> RedirectResponse:
370
+ """Fake endpoint that redirects to HF OAuth page."""
371
+ # Define target (where to redirect after login)
372
+ redirect_uri = _generate_redirect_uri(request)
373
+ return RedirectResponse(callback_uri + "?" + urllib.parse.urlencode({"_target_url": redirect_uri}))
374
+
375
+ @app.get(callback_uri)
376
+ async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse:
377
+ """Endpoint that handles the OAuth callback."""
378
+ request.session["oauth_info"] = mocked_oauth_info
379
+ return RedirectResponse(_get_redirect_target(request))
380
+
381
+ @app.get(logout_uri)
382
+ async def oauth_logout(request: fastapi.Request) -> RedirectResponse:
383
+ """Endpoint that logs out the user (e.g. delete cookie session)."""
384
+ request.session.pop("oauth_info", None)
385
+ logout_url = URL("/").include_query_params(**request.query_params)
386
+ return RedirectResponse(url=logout_url, status_code=302) # see https://github.com/gradio-app/gradio/pull/9659
387
+
388
+
389
+ def _generate_redirect_uri(request: "fastapi.Request") -> str:
390
+ if "_target_url" in request.query_params:
391
+ # if `_target_url` already in query params => respect it
392
+ target = request.query_params["_target_url"]
393
+ else:
394
+ # otherwise => keep query params
395
+ target = "/?" + urllib.parse.urlencode(request.query_params)
396
+
397
+ redirect_uri = request.url_for("oauth_redirect_callback").include_query_params(_target_url=target)
398
+ redirect_uri_as_str = str(redirect_uri)
399
+ if redirect_uri.netloc.endswith(".hf.space"):
400
+ # In Space, FastAPI redirect as http but we want https
401
+ redirect_uri_as_str = redirect_uri_as_str.replace("http://", "https://")
402
+ return redirect_uri_as_str
403
+
404
+
405
+ def _get_redirect_target(request: "fastapi.Request", default_target: str = "/") -> str:
406
+ return request.query_params.get("_target_url", default_target)
407
+
408
+
409
+ def _get_mocked_oauth_info() -> dict:
410
+ token = get_token()
411
+ if token is None:
412
+ raise ValueError(
413
+ "Your machine must be logged in to HF to debug an OAuth app locally. Please"
414
+ " run `hf auth login` or set `HF_TOKEN` as environment variable "
415
+ "with one of your access token. You can generate a new token in your "
416
+ "settings page (https://huggingface.co/settings/tokens)."
417
+ )
418
+
419
+ user = whoami()
420
+ if user["type"] != "user":
421
+ raise ValueError(
422
+ "Your machine is not logged in with a personal account. Please use a "
423
+ "personal access token. You can generate a new token in your settings page"
424
+ " (https://huggingface.co/settings/tokens)."
425
+ )
426
+
427
+ return {
428
+ "access_token": token,
429
+ "token_type": "bearer",
430
+ "expires_in": 8 * 60 * 60, # 8 hours
431
+ "id_token": "FOOBAR",
432
+ "scope": "openid profile",
433
+ "refresh_token": "hf_oauth__refresh_token",
434
+ "expires_at": int(time.time()) + 8 * 60 * 60, # 8 hours
435
+ "userinfo": {
436
+ "sub": "0123456789",
437
+ "name": user["fullname"],
438
+ "preferred_username": user["name"],
439
+ "profile": f"https://huggingface.co/{user['name']}",
440
+ "picture": user["avatarUrl"],
441
+ "website": "",
442
+ "aud": "00000000-0000-0000-0000-000000000000",
443
+ "auth_time": 1691672844,
444
+ "nonce": "aaaaaaaaaaaaaaaaaaa",
445
+ "iat": 1691672844,
446
+ "exp": 1691676444,
447
+ "iss": "https://huggingface.co",
448
+ },
449
+ }
450
+
451
+
452
+ def _get_oauth_uris(route_prefix: str = "/") -> tuple[str, str, str]:
453
+ route_prefix = route_prefix.strip("/")
454
+ if route_prefix:
455
+ route_prefix = f"/{route_prefix}"
456
+ return (
457
+ f"{route_prefix}/oauth/huggingface/login",
458
+ f"{route_prefix}/oauth/huggingface/callback",
459
+ f"{route_prefix}/oauth/huggingface/logout",
460
+ )
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_oidc.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Keyless CI/CD authentication via OIDC token exchange ("Trusted Publishers").
15
+
16
+ A CI job proves its identity to the Hub with a short-lived OIDC id token minted by its CI
17
+ provider (e.g. GitHub Actions), then exchanges it at ``POST {ENDPOINT}/oauth/token`` (RFC 8693)
18
+ for a short-lived Hugging Face token — no long-lived ``HF_TOKEN`` secret to store.
19
+
20
+ This module is self-contained: it only handles minting the provider id token and the exchange.
21
+ It deliberately does not register a public API or a CLI verb; the integration point is the token
22
+ resolution in ``utils/_auth.py`` (see ``_get_token_from_oidc``).
23
+
24
+ Docs: https://huggingface.co/docs/hub/trusted-publishers
25
+ """
26
+
27
+ import os
28
+ from enum import Enum
29
+
30
+ from . import constants
31
+ from .errors import OIDCError
32
+ from .utils import get_session, hf_raise_for_status
33
+
34
+
35
+ # RFC 8693 token-exchange grant + id-token subject type (see trusted-publishers docs).
36
+ _TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
37
+ _ID_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:id_token"
38
+
39
+
40
+ class Provider(str, Enum):
41
+ """CI providers that can mint an OIDC id token natively. GitHub Actions only for now."""
42
+
43
+ GITHUB = "github"
44
+
45
+
46
+ def detect_provider() -> Provider | None:
47
+ """Detect the CI provider able to mint an OIDC id token, or `None` if not in a supported CI."""
48
+ if os.environ.get("GITHUB_ACTIONS") == "true":
49
+ return Provider.GITHUB
50
+ return None
51
+
52
+
53
+ def _get_github_oidc_token(audience: str) -> str:
54
+ """Mint an OIDC id token from the GitHub Actions runtime.
55
+
56
+ Relies on the `ACTIONS_ID_TOKEN_REQUEST_URL` / `ACTIONS_ID_TOKEN_REQUEST_TOKEN` env vars,
57
+ which GitHub only injects when the job declares `permissions: id-token: write`.
58
+ """
59
+ request_url = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL")
60
+ request_token = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
61
+ if not request_url or not request_token:
62
+ raise OIDCError(
63
+ "Cannot request an OIDC id token from GitHub Actions. Make sure the workflow job sets "
64
+ "`permissions: id-token: write`. See "
65
+ "https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect"
66
+ )
67
+ response = get_session().get(
68
+ request_url,
69
+ params={"audience": audience},
70
+ headers={"Authorization": f"Bearer {request_token}"},
71
+ )
72
+ hf_raise_for_status(response)
73
+ return response.json()["value"]
74
+
75
+
76
+ def get_oidc_token(*, provider: Provider | str | None = None, audience: str | None = None) -> str:
77
+ """Mint a raw OIDC id token (JWT) from the current CI provider.
78
+
79
+ Args:
80
+ provider (`str`, *optional*):
81
+ CI provider to use. Auto-detected from the environment when omitted.
82
+ audience (`str`, *optional*):
83
+ The `aud` claim to request. Defaults to `constants.ENDPOINT` so it matches the endpoint
84
+ that validates it (respects `HF_ENDPOINT`/staging).
85
+
86
+ Returns:
87
+ `str`: The raw id token (JWT) to pass to [`exchange_oidc_token`].
88
+ """
89
+ audience = audience or constants.ENDPOINT
90
+ provider = provider or detect_provider()
91
+ supported = ", ".join(p.value for p in Provider)
92
+ if provider is None:
93
+ raise OIDCError(f"No supported CI OIDC provider detected. Trusted Publishers currently supports: {supported}.")
94
+ if provider == Provider.GITHUB:
95
+ return _get_github_oidc_token(audience)
96
+ raise NotImplementedError(f"OIDC provider '{provider}' is not supported yet. Supported: {supported}.")
97
+
98
+
99
+ def exchange_oidc_token(*, subject_token: str, resource: str, endpoint: str | None = None) -> dict:
100
+ """Exchange a CI OIDC id token for a short-lived Hugging Face token (RFC 8693).
101
+
102
+ Args:
103
+ subject_token (`str`):
104
+ The raw OIDC id token (JWT) from the CI provider. Its `aud` claim must be the Hub URL.
105
+ resource (`str`):
106
+ What to scope the token to: a Hub repo (`namespace/name`, `datasets/namespace/name`,
107
+ `spaces/namespace/name`, `kernels/namespace/name`) for a write token, or a bare Hub
108
+ username for a read-only `gated-repos` token.
109
+ endpoint (`str`, *optional*):
110
+ Hub endpoint. Defaults to `constants.ENDPOINT` (respects `HF_ENDPOINT`/staging).
111
+
112
+ Returns:
113
+ `dict`: The token-exchange response, e.g.
114
+ `{"access_token": "hf_jwt_…", "token_type": "bearer", "expires_in": 3600, ...}`.
115
+ """
116
+ response = get_session().post(
117
+ f"{endpoint or constants.ENDPOINT}/oauth/token",
118
+ json={
119
+ "grant_type": _TOKEN_EXCHANGE_GRANT_TYPE,
120
+ "subject_token_type": _ID_TOKEN_TYPE,
121
+ "subject_token": subject_token,
122
+ "resource": resource,
123
+ },
124
+ )
125
+ hf_raise_for_status(response)
126
+ return response.json()
127
+
128
+
129
+ def oidc_login(
130
+ *,
131
+ resource: str,
132
+ subject_token: str | None = None,
133
+ provider: Provider | str | None = None,
134
+ audience: str | None = None,
135
+ endpoint: str | None = None,
136
+ ) -> dict:
137
+ """Mint a CI OIDC id token and exchange it for a Hugging Face token.
138
+
139
+ Convenience wrapper around [`get_oidc_token`] + [`exchange_oidc_token`]. Returns the raw
140
+ exchange response (it does not persist anything — the caller decides what to do with the token).
141
+
142
+ Args:
143
+ resource (`str`):
144
+ Repo or username to scope the token to. See [`exchange_oidc_token`].
145
+ subject_token (`str`, *optional*):
146
+ A pre-minted OIDC id token to exchange directly. Use this for CI providers not yet
147
+ supported natively (e.g. GitLab): mint the id token in your job and pass it here. When
148
+ omitted, the token is minted from the detected `provider`.
149
+ provider (`str`, *optional*):
150
+ CI provider. Auto-detected when omitted. Ignored when `subject_token` is provided.
151
+ audience (`str`, *optional*):
152
+ The `aud` claim to request. Defaults to the resolved `endpoint`, so it matches the
153
+ endpoint that validates it.
154
+ endpoint (`str`, *optional*):
155
+ Hub endpoint. Defaults to `constants.ENDPOINT`.
156
+
157
+ Returns:
158
+ `dict`: The token-exchange response (`access_token`, `token_type`, `expires_in`, ...).
159
+ """
160
+ endpoint = endpoint or constants.ENDPOINT
161
+ if subject_token is None:
162
+ subject_token = get_oidc_token(provider=provider, audience=audience or endpoint)
163
+ return exchange_oidc_token(subject_token=subject_token, resource=resource, endpoint=endpoint)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_sandbox.py ADDED
@@ -0,0 +1,1764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2026-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import hashlib
16
+ import hmac
17
+ import json
18
+ import threading
19
+ import time
20
+ from concurrent.futures import ThreadPoolExecutor
21
+ from contextlib import contextmanager
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+ from secrets import token_hex
25
+ from typing import Any, BinaryIO, Callable, Iterator, List, Literal, overload
26
+
27
+ import httpx
28
+
29
+ from . import constants
30
+ from ._sandbox_cache import (
31
+ CachedHost,
32
+ delete_pool_cache,
33
+ read_pool_cache,
34
+ save_pool_cache,
35
+ )
36
+ from ._space_api import Volume
37
+ from .errors import HfHubHTTPError, SandboxCommandError, SandboxError
38
+ from .hf_api import HfApi, JobInfo
39
+ from .utils import get_token, logging
40
+ from .utils._parsing import parse_duration
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ # Port the sandbox server listens on inside the job. Deliberately uncommon so that typical user ports stay free.
46
+ SANDBOX_SERVER_PORT = 49983
47
+
48
+ # Stable marker present on every sandbox job to ease filtering
49
+ SANDBOX_LABEL = "hf-sandbox"
50
+ # Sandbox mode: "dedicated" or "pool" to ease filtering
51
+ MODE_LABEL = "hf-sandbox-mode"
52
+ MODE_DEDICATED = "dedicated"
53
+ MODE_POOL = "pool"
54
+ # Pool name, to scope host reuse to a named group (see SandboxPool(name=...)). Present on pool
55
+ # host jobs only. Pool config (capacity, idle timeout) lives in the host's env vars, read via
56
+ # inspect_job — labels are kept for filtering/grouping only.
57
+ POOL_LABEL = "hf-sandbox-pool"
58
+ # Per-job public nonce the sandbox token is derived from (see _derive_sandbox_token), so
59
+ # `Sandbox.connect(id)` can recompute the token from any machine with no local state.
60
+ NONCE_LABEL = "hf-sandbox-nonce"
61
+
62
+ DEFAULT_IMAGE = "python:3.12"
63
+
64
+ DEFAULT_IDLE_TIMEOUT = 10 * 60 # 10 minutes
65
+ SANDBOX_MAX_LIFETIME = "24h"
66
+
67
+ DEFAULT_SANDBOXES_PER_HOST = 50
68
+
69
+ SHARED_ID_SEP = "."
70
+
71
+ # Job stages in which a sandbox/host is finished and needs no teardown.
72
+ _TERMINAL_STAGES = ("COMPLETED", "ERROR", "DELETED", "CANCELED")
73
+
74
+ # Safety bound on create()'s pack-retry loop
75
+ _MAX_PACK_ROUNDS = 8
76
+
77
+ # hf-mount path where the server bucket is mounted on every sandbox job
78
+ _SERVER_MOUNT_PATH = "/.hf-sbx-server"
79
+
80
+ # Job startup script (needs only /bin/sh)
81
+ _BOOTSTRAP_DOWNLOAD = """\
82
+ set -e
83
+ d=/tmp/.sbx-server
84
+ if command -v wget >/dev/null 2>&1; then wget -q --header "Authorization: Bearer $SBX_DL_TOKEN" -O "$d" "$SBX_SERVER_URL"
85
+ elif command -v curl >/dev/null 2>&1; then curl -fsSL -H "Authorization: Bearer $SBX_DL_TOKEN" -o "$d" "$SBX_SERVER_URL"
86
+ else cp "$SBX_SERVER_MOUNT/sbx-server" "$d"; fi
87
+ chmod +x "$d"
88
+ unset SBX_DL_TOKEN SBX_SERVER_URL SBX_SERVER_MOUNT
89
+ exec "$d"
90
+ """
91
+
92
+
93
+ def _derive_sandbox_token(hf_token: str, nonce: str) -> str:
94
+ """Derive the per-sandbox auth token from the user's HF token and the sandbox nonce.
95
+
96
+ Stateless: any machine holding the same HF token can recompute it from the
97
+ nonce stored in the job's labels, so `Sandbox.connect(job_id)` needs no local state.
98
+ The HF token itself is never sent to the sandbox.
99
+ """
100
+ return hmac.new(hf_token.encode(), f"hf-sandbox:{nonce}".encode(), hashlib.sha256).hexdigest()
101
+
102
+
103
+ def _duration_to_secs(duration: int | float | str) -> int:
104
+ """Parse a duration like 300, "300s", "10m", "2h", "1d" into seconds."""
105
+ if isinstance(duration, (int, float)):
106
+ return int(duration)
107
+ return parse_duration(duration)
108
+
109
+
110
+ @dataclass
111
+ class SandboxCommandResult:
112
+ """Result of a command executed in a sandbox with [`Sandbox.run`]."""
113
+
114
+ exit_code: int | None
115
+ stdout: str
116
+ stderr: str
117
+ signal: int | None = None
118
+ timed_out: bool = False
119
+ duration_ms: int = 0
120
+
121
+ @property
122
+ def ok(self) -> bool:
123
+ return self.exit_code == 0
124
+
125
+ def __repr__(self) -> str:
126
+ out = self.stdout if len(self.stdout) <= 80 else self.stdout[:77] + "..."
127
+ return f"SandboxCommandResult(exit_code={self.exit_code}, stdout={out!r}, duration_ms={self.duration_ms})"
128
+
129
+
130
+ @dataclass
131
+ class SandboxProcess:
132
+ """A background process started in a sandbox with [`Sandbox.run`]`(..., background=True)`.
133
+
134
+ List a sandbox's processes with [`Sandbox.processes`] and stop one with [`SandboxProcess.kill`].
135
+ Completed processes stay in the listing until the sandbox is deleted, so `running` and
136
+ `exit_code` tell whether a process is still alive or already exited (as of when it was listed).
137
+ """
138
+
139
+ pid: int
140
+ cmd: str | List[str]
141
+ # Back-reference to the sandbox, used by `kill()`. Excluded from repr/eq so a process
142
+ # stays a plain data object (and two with the same pid compare equal).
143
+ _sandbox: "Sandbox" = field(repr=False, compare=False)
144
+ tag: str | None = None
145
+ started_at_ms: int | None = None
146
+ running: bool = True
147
+ exit_code: int | None = None
148
+
149
+ def kill(self) -> None:
150
+ """Terminate the background process (idempotent server-side)."""
151
+ self._sandbox._request("DELETE", f"/processes/{self.pid}")
152
+
153
+
154
+ @dataclass
155
+ class FileEntry:
156
+ """A file or directory inside a sandbox."""
157
+
158
+ name: str
159
+ path: str
160
+ type: Literal["file", "dir", "symlink"]
161
+ size: int
162
+ mtime_ms: int | None = None
163
+ mode: str = ""
164
+
165
+
166
+ class SandboxFiles:
167
+ """Filesystem operations inside a sandbox, available as [`Sandbox.files`].
168
+
169
+ In shared (pool) mode, paths are rooted at the sandbox's private home — the
170
+ only place its code can write — so a leading `/` is taken relative to that
171
+ home. In dedicated mode, paths are absolute on the container filesystem.
172
+ """
173
+
174
+ # Above this size, transfers are split into ranged requests over parallel
175
+ # connections: a single TCP stream through the jobs proxy is limited by the
176
+ # bandwidth-delay product (~2 MiB/s at ~100ms RTT); parallel streams scale it.
177
+ PARALLEL_THRESHOLD = 2 * 1024 * 1024
178
+ PARALLEL_CHUNK_SIZE = 1 * 1024 * 1024
179
+ PARALLEL_MAX_WORKERS = 16
180
+
181
+ def __init__(self, sandbox: "Sandbox") -> None:
182
+ self._sandbox = sandbox
183
+
184
+ def read(self, path: str) -> bytes:
185
+ """Read a file from the sandbox and return its content as bytes."""
186
+ size = self.stat(path).size
187
+ if size > self.PARALLEL_THRESHOLD:
188
+ return b"".join(self._read_ranges(path, size))
189
+ response = self._sandbox._request("GET", "/files/read", params={"path": path})
190
+ return response.content
191
+
192
+ def read_text(self, path: str, encoding: str = "utf-8") -> str:
193
+ """Read a file from the sandbox and return its content as a string."""
194
+ return self.read(path).decode(encoding)
195
+
196
+ def write(self, path: str, data: str | bytes | BinaryIO, mode: str | None = None) -> None:
197
+ """Write content to a file in the sandbox (parent directories are created)."""
198
+ if isinstance(data, str):
199
+ data = data.encode()
200
+ elif not isinstance(data, bytes):
201
+ data = data.read() # binary file object
202
+ if len(data) > self.PARALLEL_THRESHOLD:
203
+ self._write_ranges(path, data, mode)
204
+ return
205
+ params = {"path": path}
206
+ if mode is not None:
207
+ params["mode"] = mode
208
+ self._sandbox._request("PUT", "/files/write", params=params, content=data)
209
+
210
+ def upload(self, local_path: str | Path, path: str, mode: str | None = None) -> None:
211
+ """Upload a local file to the sandbox."""
212
+ size = Path(local_path).stat().st_size
213
+ if size > self.PARALLEL_THRESHOLD:
214
+ self._write_ranges(path, Path(local_path).read_bytes(), mode)
215
+ return
216
+ with open(local_path, "rb") as f:
217
+ self.write(path, f, mode=mode)
218
+
219
+ def download(self, path: str, local_path: str | Path) -> None:
220
+ """Download a file from the sandbox."""
221
+ size = self.stat(path).size
222
+ if size > self.PARALLEL_THRESHOLD:
223
+ with open(local_path, "wb") as f:
224
+ for part in self._read_ranges(path, size):
225
+ f.write(part)
226
+ return
227
+ with self._sandbox._stream("GET", "/files/read", params={"path": path}) as response:
228
+ with open(local_path, "wb") as f:
229
+ for chunk in response.iter_bytes(chunk_size=1024 * 1024):
230
+ f.write(chunk)
231
+
232
+ def _ranges(self, size: int) -> List[tuple[int, int]]:
233
+ chunk = self.PARALLEL_CHUNK_SIZE
234
+ return [(offset, min(chunk, size - offset)) for offset in range(0, size, chunk)]
235
+
236
+ def _parallel(self, items: List[Any], fn: Callable[[Any], Any]) -> List[Any]:
237
+ """Run `fn(item)` over items concurrently.
238
+
239
+ All workers share the sandbox's `httpx.Client`, which is thread-safe and pools
240
+ connections, so parallel transfers fan out over several streams at once.
241
+ """
242
+ workers = min(self.PARALLEL_MAX_WORKERS, len(items))
243
+ with ThreadPoolExecutor(workers) as executor:
244
+ return list(executor.map(fn, items))
245
+
246
+ def _read_ranges(self, path: str, size: int) -> List[bytes]:
247
+ def fetch(rng: tuple[int, int]) -> bytes:
248
+ offset, length = rng
249
+ response = self._sandbox._request(
250
+ "GET", "/files/read", params={"path": path, "offset": offset, "length": length}
251
+ )
252
+ return response.content
253
+
254
+ return self._parallel(self._ranges(size), fetch)
255
+
256
+ def _write_ranges(self, path: str, data: bytes, mode: str | None) -> None:
257
+ def push(rng: tuple[int, int]) -> None:
258
+ offset, length = rng
259
+ params: dict[str, Any] = {"path": path, "offset": offset}
260
+ if mode is not None:
261
+ params["mode"] = mode
262
+ self._sandbox._request("PUT", "/files/write", params=params, content=data[offset : offset + length])
263
+
264
+ self._parallel(self._ranges(len(data)), push)
265
+
266
+ def list(self, path: str) -> List[FileEntry]:
267
+ """List a directory in the sandbox."""
268
+ response = self._sandbox._request("GET", "/files/list", params={"path": path})
269
+ return [FileEntry(**entry) for entry in response.json()["entries"]]
270
+
271
+ def stat(self, path: str) -> FileEntry:
272
+ """Get metadata of a file or directory in the sandbox."""
273
+ response = self._sandbox._request("GET", "/files/stat", params={"path": path})
274
+ return FileEntry(**response.json())
275
+
276
+ def exists(self, path: str) -> bool:
277
+ """Check whether a path exists in the sandbox."""
278
+ try:
279
+ self.stat(path)
280
+ return True
281
+ except SandboxError as e:
282
+ if e.status_code == 404:
283
+ return False
284
+ raise # network/auth/server errors must not be silently reported as "missing"
285
+
286
+ def delete(self, path: str, recursive: bool = False) -> None:
287
+ """Delete a file or directory in the sandbox."""
288
+ params = {"path": path}
289
+ if recursive:
290
+ params["recursive"] = "1"
291
+ self._sandbox._request("DELETE", "/files/delete", params=params)
292
+
293
+ def mkdir(self, path: str) -> None:
294
+ """Create a directory (and parents) in the sandbox."""
295
+ self._sandbox._request("POST", "/files/mkdir", params={"path": path})
296
+
297
+
298
+ def _exec_payload(cmd: str | List[str], shell: bool | None) -> dict[str, Any]:
299
+ """Build the `cmd`/`shell` part of an `/exec` payload, validating their consistency."""
300
+ if shell is True and not isinstance(cmd, str):
301
+ raise ValueError("shell=True requires `cmd` to be a shell command string, not a list.")
302
+ if shell is False and isinstance(cmd, str):
303
+ raise ValueError("shell=False requires `cmd` to be an argv list (e.g. ['echo', 'hi']), not a string.")
304
+ payload: dict[str, Any] = {"cmd": cmd}
305
+ if shell is not None:
306
+ payload["shell"] = shell
307
+ return payload
308
+
309
+
310
+ def _iter_events(response: httpx.Response) -> Iterator[dict]:
311
+ """Iterate NDJSON events from a streaming response, skipping keepalive pings."""
312
+ for line in response.iter_lines():
313
+ if not line:
314
+ continue
315
+ event = json.loads(line)
316
+ if event.get("event") != "ping":
317
+ yield event
318
+
319
+
320
+ def _raise_for_status(response: httpx.Response) -> None:
321
+ """Read the error body and raise a SandboxError (works for streaming responses too)."""
322
+ response.read() # no-op for buffered responses, reads the body for streaming ones
323
+ try:
324
+ message = response.json()["error"]
325
+ except Exception:
326
+ message = response.text[:500]
327
+ raise SandboxError(f"Sandbox API error ({response.status_code}): {message}", status_code=response.status_code)
328
+
329
+
330
+ class _SandboxServer:
331
+ """HTTP transport to one `sbx-server` instance — a dedicated job or a shared host.
332
+
333
+ Owns the `httpx.Client`, the base URL and the auth headers.
334
+ In dedicated mode a server is paired 1:1 with its [`Sandbox`
335
+ In pool mode one server (one host job) is shared by many sandboxes, and `live`/`capacity` track packing.
336
+ """
337
+
338
+ def __init__(
339
+ self,
340
+ *,
341
+ job_id: str,
342
+ owner: str,
343
+ image: str | None,
344
+ base_url: str,
345
+ nonce: str,
346
+ sandbox_token: str,
347
+ api: HfApi,
348
+ max_connections: int = 10,
349
+ capacity: int = 0,
350
+ ) -> None:
351
+ self.job_id = job_id
352
+ self.owner = owner
353
+ self._image = image
354
+ self.base_url = base_url
355
+ # Public nonce the sandbox token is derived from; kept so a host can be persisted
356
+ # to (and rebuilt from) the pool cache without re-reading the job labels.
357
+ self.nonce = nonce
358
+ self._api = api
359
+ self._auth_token = _effective_token(api)
360
+ self._sandbox_token = sandbox_token
361
+ # Packing bookkeeping (shared mode only).
362
+ self.capacity = capacity
363
+ self.live = 0
364
+ # False only for hosts rebuilt from the (best-effort) pool cache: their job may
365
+ # be gone, so the first failed request drops them instead of failing the create.
366
+ self.verified = True
367
+ # httpx.Client is thread-safe, so a single client serves both sequential requests
368
+ # and the concurrent workers used for parallel file transfers / many sandboxes.
369
+ self._client = httpx.Client(
370
+ headers={
371
+ "Authorization": f"Bearer {self._auth_token}",
372
+ "X-Sandbox-Token": sandbox_token,
373
+ },
374
+ limits=httpx.Limits(max_connections=max_connections, max_keepalive_connections=max_connections),
375
+ follow_redirects=True,
376
+ )
377
+
378
+ @classmethod
379
+ def from_job(
380
+ cls,
381
+ *,
382
+ job: JobInfo,
383
+ nonce: str,
384
+ sandbox_token: str,
385
+ api: HfApi,
386
+ max_connections: int = 10,
387
+ capacity: int = 0,
388
+ ) -> "_SandboxServer":
389
+ """Build a server from a freshly fetched job (reads its exposed server URL)."""
390
+ return cls(
391
+ job_id=job.id,
392
+ owner=job.owner.name,
393
+ image=job.docker_image or job.space_id,
394
+ base_url=_find_server_url(job),
395
+ nonce=nonce,
396
+ sandbox_token=sandbox_token,
397
+ api=api,
398
+ max_connections=max_connections,
399
+ capacity=capacity,
400
+ )
401
+
402
+ @property
403
+ def image(self) -> str | None:
404
+ return self._image
405
+
406
+ def request(self, method: str, path: str, **kwargs) -> httpx.Response:
407
+ """Request to the in-job server. Raises SandboxError on API errors."""
408
+ timeout = kwargs.pop("timeout", httpx.Timeout(60.0, connect=10.0))
409
+ response = self._client.request(method, self.base_url + path, timeout=timeout, **kwargs)
410
+ if response.status_code >= 400:
411
+ _raise_for_status(response)
412
+ return response
413
+
414
+ @contextmanager
415
+ def stream(self, method: str, path: str, **kwargs) -> Iterator[httpx.Response]:
416
+ """Streaming request to the in-job server. Raises SandboxError on API errors."""
417
+ timeout = kwargs.pop("timeout", httpx.Timeout(70.0, connect=10.0)) # server pings every 15s
418
+ with self._client.stream(method, self.base_url + path, timeout=timeout, **kwargs) as response:
419
+ if response.status_code >= 400:
420
+ _raise_for_status(response)
421
+ yield response
422
+
423
+ def close(self) -> None:
424
+ self._client.close()
425
+
426
+ def cancel_job(self) -> None:
427
+ self._api.cancel_job(job_id=self.job_id, namespace=self.owner)
428
+
429
+ def wait_ready(self, start_timeout: float) -> None:
430
+ """Poll /health until the server answers; fail fast (with logs) if the job dies."""
431
+ deadline = time.time() + start_timeout
432
+ last_job_check = 0.0
433
+ while time.time() < deadline:
434
+ try:
435
+ response = self._client.get(self.base_url + "/health", timeout=httpx.Timeout(5.0))
436
+ if response.status_code == 200:
437
+ return
438
+ except httpx.RequestError:
439
+ pass
440
+ if time.time() - last_job_check > 2.0:
441
+ last_job_check = time.time()
442
+ job = self._api.inspect_job(job_id=self.job_id, namespace=self.owner)
443
+ if job.status.stage in _TERMINAL_STAGES:
444
+ logs = _tail_job_logs(self._api, self.job_id, namespace=self.owner)
445
+ raise SandboxError(
446
+ f"Sandbox job {self.job_id} terminated during startup "
447
+ f"(status: {job.status.stage}, message: {job.status.message}).{logs}"
448
+ )
449
+ time.sleep(0.15)
450
+ raise SandboxError(f"Sandbox job {self.job_id} did not become ready within {start_timeout:.0f}s.")
451
+
452
+
453
+ class _KillMethod:
454
+ """Lets `kill` work both as a classmethod and an instance method."""
455
+
456
+ @overload
457
+ def __get__(self, instance: None, owner: type) -> Callable[..., None]: ...
458
+ @overload
459
+ def __get__(self, instance: "Sandbox", owner: type) -> Callable[[], None]: ...
460
+ def __get__(self, instance: "Sandbox | None", owner: type) -> Callable[..., None]:
461
+ if instance is not None:
462
+ return instance._kill
463
+
464
+ def kill(sandbox_id: str, *, namespace: str | None = None, token: str | None = None) -> None:
465
+ owner.connect(sandbox_id, namespace=namespace, token=token).kill() # type: ignore[attr-defined]
466
+
467
+ return kill
468
+
469
+
470
+ class Sandbox:
471
+ """An isolated cloud machine running on Hugging Face Jobs.
472
+
473
+ Create a dedicated one with [`Sandbox.create`] (one job per sandbox), or get many cheap shared ones from a [`SandboxPool`].
474
+ Reattach to a running sandbox from anywhere with [`Sandbox.connect`]. Use as a context manager to terminate it on exit:
475
+
476
+ ```python
477
+ >>> from huggingface_hub import Sandbox
478
+ >>> with Sandbox.create(image="python:3.12") as sbx:
479
+ ... print(sbx.run("python --version").stdout)
480
+ ```
481
+ """
482
+
483
+ def __init__(
484
+ self,
485
+ *,
486
+ id: str,
487
+ server: _SandboxServer,
488
+ local_id: str | None,
489
+ owns_sandbox: bool,
490
+ owns_server: bool,
491
+ ) -> None:
492
+ self.id = id
493
+ self._server = server
494
+ # None in dedicated mode; the host-local sandbox id in shared mode.
495
+ self._local_id = local_id
496
+ # Path prefix for all in-server operations: dedicated routes live under
497
+ # /v1/*, shared ones under /v1/sandboxes/<local_id>/*.
498
+ self._base_path = "/v1" if local_id is None else f"/v1/sandboxes/{local_id}"
499
+ # Whether exiting a `with` block terminates the sandbox (True for sandboxes
500
+ # we created, False for ones reattached via connect()).
501
+ self._owns_sandbox = owns_sandbox
502
+ # Whether closing/killing this sandbox also closes the HTTP client. False
503
+ # for pool sandboxes, whose client (the host) is owned by the pool.
504
+ self._owns_server = owns_server
505
+ # Set by SandboxPool to free a packing slot when a shared sandbox is killed.
506
+ self._on_kill: Callable[["Sandbox"], None] | None = None
507
+ self._killed = False
508
+ self.files = SandboxFiles(self)
509
+
510
+ # ------------------------------------------------------------------ lifecycle
511
+
512
+ @classmethod
513
+ def create(
514
+ cls,
515
+ image: str = DEFAULT_IMAGE,
516
+ *,
517
+ flavor: str = "cpu-basic",
518
+ idle_timeout: int | float | str | None = DEFAULT_IDLE_TIMEOUT,
519
+ env: dict[str, Any] | None = None,
520
+ secrets: dict[str, Any] | None = None,
521
+ volumes: List[Volume] | None = None,
522
+ namespace: str | None = None,
523
+ forward_hf_token: bool = False,
524
+ start_timeout: float = 120.0,
525
+ token: str | None = None,
526
+ ) -> "Sandbox":
527
+ """Create a dedicated sandbox (one HF Job) and block until it is ready (~7s on cpu-basic).
528
+
529
+ Each sandbox is a full isolated VM, so this is the right choice for GPU
530
+ workloads or untrusted code. To fan out many cheap CPU sandboxes instead, use
531
+ [`SandboxPool`].
532
+
533
+ The job runs with a fixed 24h maximum lifetime; `idle_timeout` is the real
534
+ keeper — an idle sandbox shuts itself down well before that.
535
+
536
+ Args:
537
+ image (`str`, *optional*, defaults to `"python:3.12"`):
538
+ Any Docker image with `/bin/sh` (Docker Hub or `hf.co/spaces/...`).
539
+ flavor (`str`, *optional*, defaults to `"cpu-basic"`):
540
+ Hardware flavor, e.g. `"cpu-basic"`, `"a10g-small"`. See `hf jobs hardware`.
541
+ idle_timeout (`int` or `float` or `str`, *optional*, defaults to `600`):
542
+ Auto-shutdown after this much inactivity (no API calls, no running
543
+ processes). Defaults to 10 minutes; pass `None` to disable.
544
+ env (`dict[str, Any]`, *optional*):
545
+ Environment variables available in the sandbox.
546
+ secrets (`dict[str, Any]`, *optional*):
547
+ Secret environment variables (encrypted server-side).
548
+ volumes (`List[Volume]`, *optional*):
549
+ HF repos/buckets to mount, see [`Volume`].
550
+ namespace (`str`, *optional*):
551
+ User or org namespace to run under (defaults to current user).
552
+ forward_hf_token (`bool`, *optional*, defaults to `False`):
553
+ If True, your HF token is injected as `HF_TOKEN` (opt-in).
554
+ start_timeout (`float`, *optional*, defaults to `120.0`):
555
+ Max seconds to wait for the sandbox to become ready.
556
+ token (`str`, *optional*):
557
+ HF token override.
558
+
559
+ The image only needs `/bin/sh`. The sandbox server is downloaded at startup with
560
+ `wget`/`curl` if available, otherwise read off an always-mounted server bucket (which
561
+ adds ~2-3s to cold start, so shipping `wget`/`curl` keeps it fast).
562
+ """
563
+ api = HfApi(token=token)
564
+ hf_token = _effective_token(api)
565
+ nonce = token_hex(16)
566
+ sandbox_token = _derive_sandbox_token(hf_token, nonce)
567
+
568
+ command, job_env, job_secrets, job_volumes = _bootstrap_job_spec(
569
+ api,
570
+ hf_token,
571
+ env=env,
572
+ secrets=secrets,
573
+ volumes=volumes,
574
+ idle_timeout=idle_timeout,
575
+ forward_hf_token=forward_hf_token,
576
+ sandbox_token=sandbox_token,
577
+ )
578
+
579
+ job = api.run_job(
580
+ image=image,
581
+ command=command,
582
+ env=job_env,
583
+ secrets=job_secrets,
584
+ flavor=flavor,
585
+ timeout=SANDBOX_MAX_LIFETIME,
586
+ labels={SANDBOX_LABEL: "1", MODE_LABEL: MODE_DEDICATED, NONCE_LABEL: nonce},
587
+ volumes=job_volumes or None,
588
+ expose=[SANDBOX_SERVER_PORT],
589
+ namespace=namespace,
590
+ )
591
+ server: "_SandboxServer | None" = None
592
+ try:
593
+ server = _SandboxServer.from_job(
594
+ job=job,
595
+ nonce=nonce,
596
+ sandbox_token=sandbox_token,
597
+ api=api,
598
+ max_connections=SandboxFiles.PARALLEL_MAX_WORKERS + 2,
599
+ )
600
+ server.wait_ready(start_timeout)
601
+ except Exception:
602
+ # run_job already started a billable job; cancel it before re-raising so it
603
+ # doesn't linger as an orphan (e.g. if the server port isn't exposed or startup fails).
604
+ try:
605
+ api.cancel_job(job_id=job.id, namespace=job.owner.name)
606
+ except Exception as e:
607
+ logger.warning(f"Failed to cancel sandbox job {job.id} after startup failure: {e}")
608
+ if server is not None:
609
+ server.close()
610
+ raise
611
+ return cls(id=job.id, server=server, local_id=None, owns_sandbox=True, owns_server=True)
612
+
613
+ @classmethod
614
+ def connect(cls, sandbox_id: str, *, namespace: str | None = None, token: str | None = None) -> "Sandbox":
615
+ """Reattach to a running sandbox from anywhere, using only its id."""
616
+ api = HfApi(token=token)
617
+ sandbox_id, namespace = _split_sandbox_id(sandbox_id, namespace)
618
+ if SHARED_ID_SEP in sandbox_id:
619
+ host_job_id, local_id = sandbox_id.split(SHARED_ID_SEP, 1)
620
+ server = _connect_host(api, host_job_id, namespace=namespace)
621
+ try:
622
+ existing = {item["id"] for item in server.request("GET", "/v1/sandboxes").json()}
623
+ if local_id not in existing:
624
+ raise SandboxError(f"Sandbox {sandbox_id} no longer exists on host {host_job_id}.")
625
+ except Exception:
626
+ server.close() # don't leak the HTTP client when the host is gone/unreachable
627
+ raise
628
+ return cls(id=sandbox_id, server=server, local_id=local_id, owns_sandbox=False, owns_server=True)
629
+
630
+ job = api.inspect_job(job_id=sandbox_id, namespace=namespace)
631
+ labels = job.labels or {}
632
+ nonce = labels.get(NONCE_LABEL)
633
+ if labels.get(SANDBOX_LABEL) != "1" or nonce is None:
634
+ raise SandboxError(f"Job {sandbox_id} is not a sandbox (missing '{SANDBOX_LABEL}' label).")
635
+ if labels.get(MODE_LABEL) == MODE_POOL:
636
+ raise SandboxError(
637
+ f"Job {sandbox_id} is a sandbox host, not a single sandbox. Connect to one of its "
638
+ f"sandboxes with id '<host_job_id>{SHARED_ID_SEP}<local_id>'."
639
+ )
640
+ if job.status.stage != "RUNNING":
641
+ raise SandboxError(f"Sandbox {sandbox_id} is not running (status: {job.status.stage}).")
642
+ sandbox_token = _derive_sandbox_token(_effective_token(api), nonce)
643
+ server = _SandboxServer.from_job(
644
+ job=job,
645
+ nonce=nonce,
646
+ sandbox_token=sandbox_token,
647
+ api=api,
648
+ max_connections=SandboxFiles.PARALLEL_MAX_WORKERS + 2,
649
+ )
650
+ return cls(id=job.id, server=server, local_id=None, owns_sandbox=False, owns_server=True)
651
+
652
+ # `kill` is both a classmethod (`Sandbox.kill(id)`) and an instance method (`sbx.kill()`),
653
+ # dispatched by the `_KillMethod` descriptor; `_kill` holds the instance behaviour.
654
+ kill = _KillMethod()
655
+
656
+ def _kill(self) -> None:
657
+ """Terminate the sandbox. Idempotent.
658
+
659
+ Dedicated sandboxes cancel their underlying job; shared sandboxes are
660
+ removed from their host (freeing a slot) while the host keeps running.
661
+ """
662
+ if self._killed:
663
+ return
664
+ try:
665
+ if self._local_id is None:
666
+ self._server.cancel_job()
667
+ else:
668
+ self._server.request("DELETE", f"/v1/sandboxes/{self._local_id}")
669
+ except Exception as e:
670
+ # Don't mark as killed: a later kill() call should retry so nothing leaks.
671
+ logger.warning(f"Failed to kill sandbox {self.id}: {e}")
672
+ return
673
+ self._killed = True
674
+ if self._on_kill is not None:
675
+ self._on_kill(self)
676
+ if self._owns_server:
677
+ self._server.close()
678
+
679
+ def close(self) -> None:
680
+ """Release the local HTTP client without terminating the sandbox. Idempotent.
681
+
682
+ No-op for pool sandboxes (the client belongs to the pool's host).
683
+ """
684
+ if self._owns_server:
685
+ self._server.close()
686
+
687
+ def __enter__(self) -> "Sandbox":
688
+ return self
689
+
690
+ def __exit__(self, *exc_info) -> None:
691
+ if self._owns_sandbox:
692
+ self.kill()
693
+ else:
694
+ self.close()
695
+
696
+ # ------------------------------------------------------------------ exec
697
+
698
+ @overload
699
+ def run(
700
+ self,
701
+ cmd: str | List[str],
702
+ *,
703
+ shell: bool | None = ...,
704
+ env: dict[str, Any] | None = ...,
705
+ cwd: str | None = ...,
706
+ timeout: float | None = ...,
707
+ stdin: str | None = ...,
708
+ on_stdout: Callable[[str], None] | None = ...,
709
+ on_stderr: Callable[[str], None] | None = ...,
710
+ check: bool = ...,
711
+ background: Literal[False] = ...,
712
+ ) -> SandboxCommandResult: ...
713
+
714
+ @overload
715
+ def run(
716
+ self,
717
+ cmd: str | List[str],
718
+ *,
719
+ shell: bool | None = ...,
720
+ env: dict[str, Any] | None = ...,
721
+ cwd: str | None = ...,
722
+ background: Literal[True],
723
+ ) -> SandboxProcess: ...
724
+
725
+ def run(
726
+ self,
727
+ cmd: str | List[str],
728
+ *,
729
+ shell: bool | None = None,
730
+ env: dict[str, Any] | None = None,
731
+ cwd: str | None = None,
732
+ timeout: float | None = None,
733
+ stdin: str | None = None,
734
+ on_stdout: Callable[[str], None] | None = None,
735
+ on_stderr: Callable[[str], None] | None = None,
736
+ check: bool = True,
737
+ background: bool = False,
738
+ ) -> SandboxCommandResult | SandboxProcess:
739
+ """Run a command in the sandbox and wait for it, streaming output live.
740
+
741
+ With `background=True` the command is started detached and `run` returns a
742
+ [`SandboxProcess`] immediately, without waiting for it to finish — handy for
743
+ servers and other long-running processes. List them later with [`Sandbox.processes`]
744
+ and stop one with [`SandboxProcess.kill`]. The streaming/wait-only options
745
+ (`timeout`, `stdin`, `on_stdout`, `on_stderr`, `check`) don't apply in that mode.
746
+
747
+ Args:
748
+ cmd (`str` or `List[str]`):
749
+ A shell command string (run with `/bin/sh -c`) or an argv list (exec'd directly).
750
+ shell (`bool`, *optional*):
751
+ Force the execution mode instead of inferring it from the type of `cmd`.
752
+ `True` runs through `/bin/sh -c` and requires `cmd` to be a string; `False`
753
+ exec's `cmd` directly and requires it to be an argv list. `None` (default)
754
+ infers from the type. Set it explicitly to avoid the type-driven footgun (e.g.
755
+ `["echo hi"]` being exec'd as a single program named `"echo hi"`).
756
+ env (`dict[str, Any]`, *optional*):
757
+ Extra environment variables for this command.
758
+ cwd (`str`, *optional*):
759
+ Working directory.
760
+ timeout (`float`, *optional*):
761
+ Kill the command (whole process group) after this many seconds.
762
+ stdin (`str`, *optional*):
763
+ Data to write to the command's stdin.
764
+ on_stdout (`Callable[[str], None]`, *optional*):
765
+ Callback invoked with stdout chunks as they arrive.
766
+ on_stderr (`Callable[[str], None]`, *optional*):
767
+ Callback invoked with stderr chunks as they arrive.
768
+ check (`bool`, *optional*, defaults to `True`):
769
+ If True, raise [`SandboxCommandError`] on non-zero exit.
770
+ background (`bool`, *optional*, defaults to `False`):
771
+ If True, start the command detached and return a [`SandboxProcess`] right
772
+ away instead of waiting for it and returning a [`SandboxCommandResult`].
773
+
774
+ Returns: a [`SandboxCommandResult`] (with `exit_code`, `stdout`, `stderr`,
775
+ `duration_ms`), or a [`SandboxProcess`] when `background=True`.
776
+ """
777
+ payload = _exec_payload(cmd, shell)
778
+ if env:
779
+ payload["env"] = env
780
+ if cwd:
781
+ payload["cwd"] = cwd
782
+ if background:
783
+ data = self._request("POST", "/processes", json=payload).json()
784
+ return SandboxProcess(pid=data["pid"], cmd=cmd, tag=data.get("tag"), _sandbox=self)
785
+ if timeout is not None:
786
+ payload["timeout"] = timeout
787
+ if stdin is not None:
788
+ payload["stdin"] = stdin
789
+
790
+ stdout_parts: list[str] = []
791
+ stderr_parts: list[str] = []
792
+ result: SandboxCommandResult | None = None
793
+ with self._stream("POST", "/exec", json=payload) as response:
794
+ for event in _iter_events(response):
795
+ if event["event"] == "stdout":
796
+ stdout_parts.append(event["data"])
797
+ if on_stdout is not None:
798
+ on_stdout(event["data"])
799
+ elif event["event"] == "stderr":
800
+ stderr_parts.append(event["data"])
801
+ if on_stderr is not None:
802
+ on_stderr(event["data"])
803
+ elif event["event"] == "exit":
804
+ result = SandboxCommandResult(
805
+ exit_code=event["exit_code"],
806
+ stdout="".join(stdout_parts),
807
+ stderr="".join(stderr_parts),
808
+ signal=event.get("signal"),
809
+ timed_out=event.get("timed_out", False),
810
+ duration_ms=event.get("duration_ms", 0),
811
+ )
812
+ if result is None:
813
+ raise SandboxError("connection lost while running command")
814
+ if check and (result.exit_code != 0 or result.timed_out):
815
+ raise SandboxCommandError(cmd=cmd, result=result)
816
+ return result
817
+
818
+ def processes(self) -> List[SandboxProcess]:
819
+ """List the background processes of this sandbox.
820
+
821
+ Returns the processes started with [`Sandbox.run`]`(..., background=True)`; stop one
822
+ with [`SandboxProcess.kill`]. Completed processes stay listed (with `running=False` and
823
+ their `exit_code`) until the sandbox is deleted.
824
+ """
825
+ data = self._request("GET", "/processes").json()
826
+ return [
827
+ SandboxProcess(
828
+ pid=p["pid"],
829
+ cmd=p["cmd"],
830
+ tag=p.get("tag"),
831
+ started_at_ms=p.get("started_at_ms"),
832
+ running=p["running"],
833
+ exit_code=p.get("exit_code"),
834
+ _sandbox=self,
835
+ )
836
+ for p in data
837
+ ]
838
+
839
+ # ------------------------------------------------------------------ misc
840
+
841
+ @property
842
+ def image(self) -> str | None:
843
+ return self._server.image
844
+
845
+ @property
846
+ def host_id(self) -> str | None:
847
+ """For a shared/pool sandbox, the job id of the host running it (else None)."""
848
+ return self._server.job_id if self._local_id is not None else None
849
+
850
+ # ------------------------------------------------------------------ port proxy
851
+
852
+ def proxy_url_for(self, port: int | str, path: str = "/", *, scheme: str = "https://") -> str:
853
+ """Public URL that proxies through to a server running *inside* this sandbox.
854
+
855
+ Requests to the returned URL are forwarded by the in-job sandbox server to a
856
+ server you started in the sandbox on `port`, including WebSocket (`ws(s)://`)
857
+ upgrades and streamed responses. Pair it with [`proxy_headers`] for auth.
858
+
859
+ How the sandbox must listen on `port`:
860
+
861
+ - **Pool / shared sandbox**: it cannot bind a TCP port (Landlock), so bind a
862
+ **unix socket** at `$SBX_PROXY_DIR/<port>.sock` (the `SBX_PROXY_DIR` env var
863
+ is set in every sandbox). E.g. `uvicorn app:app --uds $SBX_PROXY_DIR/8000.sock`.
864
+ - **Dedicated sandbox**: bind a normal TCP port on `127.0.0.1:<port>`. (You can
865
+ also expose the port directly via the job proxy without going through here.)
866
+
867
+ Args:
868
+ port (`int` or `str`):
869
+ The port (pool: the `<port>` of the unix socket) the inner server listens on.
870
+ path (`str`, *optional*, defaults to `"/"`):
871
+ Path on the inner server to point at, e.g. `"/ws"`.
872
+ scheme (`str`, *optional*, defaults to `"https://"`):
873
+ URL scheme to build the link with. Defaults to `"https://"`; pass
874
+ `"wss://"` for a WebSocket client (the proxy is protocol-agnostic, so only
875
+ the client-side scheme changes).
876
+
877
+ Returns:
878
+ `str`: a URL like `https://<job_id>--49983.hf.jobs/v1/.../proxy/8000/ws` (or
879
+ `wss://...` with `scheme="wss://"`).
880
+
881
+ Example:
882
+ ```python
883
+ >>> url = sandbox.proxy_url_for(8000, "/ws", scheme="wss://")
884
+ >>> import websockets
885
+ >>> async with websockets.connect(url, additional_headers=sandbox.proxy_headers) as ws:
886
+ ... await ws.send("hello")
887
+ ```
888
+ """
889
+ # base_url is always https://...; swap in the requested scheme (e.g. wss://) for the client.
890
+ host_and_rest = self._server.base_url.split("://", 1)[-1]
891
+ path = path if path.startswith("/") else "/" + path
892
+ return f"{scheme}{host_and_rest}{self._base_path}/proxy/{port}{path}"
893
+
894
+ @property
895
+ def proxy_headers(self) -> dict[str, str]:
896
+ """Auth headers to send with [`proxy_url_for`] requests (HF token + sandbox token)."""
897
+ return {
898
+ "Authorization": f"Bearer {self._server._auth_token}",
899
+ "X-Sandbox-Token": self._server._sandbox_token,
900
+ }
901
+
902
+ def __repr__(self) -> str:
903
+ return f"Sandbox(id={self.id!r}, image={self.image!r})"
904
+
905
+ # ------------------------------------------------------------------ internals
906
+
907
+ def _request(self, method: str, resource: str, **kwargs) -> httpx.Response:
908
+ return self._server.request(method, self._base_path + resource, **kwargs)
909
+
910
+ @contextmanager
911
+ def _stream(self, method: str, resource: str, **kwargs) -> Iterator[httpx.Response]:
912
+ with self._server.stream(method, self._base_path + resource, **kwargs) as response:
913
+ yield response
914
+
915
+
916
+ class SandboxPool:
917
+ """A fleet of shared "host" jobs, each packing many landlock-isolated sandboxes.
918
+
919
+ One host is one billed HF Job (a VM); it runs the sandbox server and multiplexes
920
+ up to `sandboxes_per_host` lightweight sandboxes, isolated from each other by
921
+ uid + the Landlock LSM. This makes large fan-outs cheap (the VM cost is shared
922
+ across all its sandboxes) and fast (creating a sandbox is ~one proxy round-trip
923
+ once a host is warm). Best for many parallel CPU sandboxes such as RL rollouts;
924
+ for GPU or strong VM-level isolation between mutually-distrusting workloads, use
925
+ [`Sandbox.create`] instead.
926
+
927
+ The constructor pre-provisions `warm_up` hosts (default 1) and blocks until they are
928
+ ready; further hosts are then provisioned on demand as sandboxes are requested, and all
929
+ are torn down on `close()` (or when idle, via `idle_timeout`). The user never manages jobs:
930
+
931
+ ```python
932
+ >>> from huggingface_hub import SandboxPool
933
+ >>> with SandboxPool(image="python:3.12", flavor="cpu-basic", warm_up=2) as pool:
934
+ ... boxes = [pool.create() for _ in range(100)] # packed across the warm hosts
935
+ ... print(boxes[0].run("echo hi").stdout)
936
+ hi
937
+ ```
938
+
939
+ `create()` makes **one** sandbox at a time: it reuses a host that still has free
940
+ capacity before booting a new one, so you grow on demand as work arrives. To avoid
941
+ a cold start on the first few calls, pre-provision hosts with `warm_up` (or
942
+ [`warm`]). Warm hosts are discovered via job labels, so reuse works **across
943
+ processes** too (a fresh pool with the same `image`/`flavor`/`name` attaches to
944
+ hosts an earlier run left behind):
945
+
946
+ ```python
947
+ >>> pool = SandboxPool(image="python:3.12")
948
+ >>> sbx = pool.create() # finds a warm host (here or in another process), else boots one
949
+ ```
950
+ """
951
+
952
+ def __init__(
953
+ self,
954
+ image: str = DEFAULT_IMAGE,
955
+ *,
956
+ flavor: str = "cpu-basic",
957
+ sandboxes_per_host: int = DEFAULT_SANDBOXES_PER_HOST,
958
+ warm_up: int = 1,
959
+ max_hosts: int | None = None,
960
+ name: str | None = None,
961
+ idle_timeout: int | float | str | None = DEFAULT_IDLE_TIMEOUT,
962
+ namespace: str | None = None,
963
+ start_timeout: float = 120.0,
964
+ token: str | None = None,
965
+ _connect_mode: bool = False,
966
+ ) -> None:
967
+ """Configure a pool and pre-provision `warm_up` hosts (blocks until they are ready).
968
+
969
+ Env/secrets are *not* set here: they belong to each sandbox and are passed to
970
+ `create(env=...)`, so sandboxes in the same pool can have different environments.
971
+
972
+ Args:
973
+ image (`str`, *optional*, defaults to `"python:3.12"`):
974
+ Docker image for the hosts (needs `/bin/sh`). All sandboxes in the
975
+ pool share this image.
976
+ flavor (`str`, *optional*, defaults to `"cpu-basic"`):
977
+ Hardware flavor for the host jobs (e.g. `"cpu-basic"`).
978
+ sandboxes_per_host (`int`, *optional*, defaults to `50`):
979
+ How many sandboxes to pack per host (per VM density).
980
+ warm_up (`int`, *optional*, defaults to `1`):
981
+ How many hosts to pre-provision in the constructor (which blocks
982
+ until they are ready), so an initial burst of `create()` calls doesn't pay
983
+ a host cold start each. Existing warm hosts (from the cache / other processes)
984
+ count towards it, so only the shortfall is booted; capped by `max_hosts`.
985
+ Defaults to 1 (a single host).
986
+ max_hosts (`int`, *optional*):
987
+ Optional cap on the number of host jobs (a cost ceiling). When
988
+ reached and all hosts are full, `create()` raises.
989
+ name (`str`, *optional*):
990
+ Pool name, used as the `hf-sandbox-pool` job label so the pool is
991
+ discoverable (e.g. `hf sandbox pool ls`, `connect()`). `create()` reuses
992
+ running hosts carrying this label (including from other processes) before
993
+ booting new ones, so distinct names keep separate pools from sharing hosts.
994
+ A random name is generated when omitted.
995
+ idle_timeout (`int` or `float` or `str`, *optional*, defaults to `600`):
996
+ Host idle timeout — a host shuts down once it has had no
997
+ sandboxes for this long (a billing backstop). Each sandbox also has its
998
+ own idle timeout, set at `create()`. Pass `None` to disable.
999
+ namespace (`str`, *optional*):
1000
+ User or org namespace to run hosts under.
1001
+ start_timeout (`float`, *optional*, defaults to `120.0`):
1002
+ Max seconds to wait for a host to become ready.
1003
+ token (`str`, *optional*):
1004
+ HF token override.
1005
+ """
1006
+ if sandboxes_per_host < 1:
1007
+ raise ValueError("sandboxes_per_host must be >= 1.")
1008
+ if warm_up < 1:
1009
+ raise ValueError("warm_up must be >= 1.")
1010
+ self._api = HfApi(token=token)
1011
+ self.image = image
1012
+ self.flavor = flavor
1013
+ self.sandboxes_per_host = sandboxes_per_host
1014
+ self._warm_up = warm_up
1015
+ self.max_hosts = max_hosts
1016
+ self.name = name if name is not None else f"pool-{token_hex(6)}"
1017
+ self._idle_timeout = idle_timeout
1018
+ self._namespace = namespace
1019
+ self._start_timeout = start_timeout
1020
+ self._hosts: List[_SandboxServer] = []
1021
+ self._lock = threading.Lock()
1022
+ # Held across the whole one-time warm-up so concurrent first create() calls block until
1023
+ # it finishes (and see the warm hosts) instead of racing past a half-set flag.
1024
+ self._warmup_lock = threading.Lock()
1025
+ # Serializes on-demand host creation within the process: a burst of create() calls that
1026
+ # all find every host full boots one host at a time (each new host frees
1027
+ # `sandboxes_per_host` slots for the threads still queued behind the lock) instead of
1028
+ # one host per thread. The CLI is a single process per command, so this is a no-op there.
1029
+ self._boot_lock = threading.Lock()
1030
+ self._closed = False
1031
+ # Whether the one-time warm-up (seed cache + pre-provision `warm_up` hosts) ran.
1032
+ self._warmed_up = False
1033
+ # Set for connect()'d handles: the pool must already exist, so create() refuses to
1034
+ # silently resurrect it by booting a fresh host if discovery confirms every host is gone.
1035
+ # Such a handle also never boots during construction — it attaches lazily on create().
1036
+ self._require_live_host = _connect_mode
1037
+ # Whether close()/`__exit__` cancels the host jobs. True for a pool we created; False
1038
+ # for a connect()'d handle, which only releases its HTTP clients on exit — the shared
1039
+ # hosts (possibly serving other clients) are left running, like Sandbox.connect().
1040
+ self._owns_hosts = not _connect_mode
1041
+ # Job ids of cached hosts we found dead this session; pruned from the cache on save.
1042
+ self._dead_host_ids: set[str] = set()
1043
+
1044
+ # Pre-provision `warm_up` hosts now so the constructor returns only once the pool is
1045
+ # warm. A connect()'d handle skips this: it must never boot during construction (it can
1046
+ # only attach to existing hosts, lazily on the first create()).
1047
+ if not _connect_mode:
1048
+ self._ensure_warmed_up()
1049
+
1050
+ # ------------------------------------------------------------------ public API
1051
+
1052
+ @classmethod
1053
+ def connect(cls, pool_id: str, *, namespace: str | None = None, token: str | None = None) -> "SandboxPool":
1054
+ """Reattach to a running pool by id, from any machine — no local state needed.
1055
+
1056
+ Finds a running host labelled with `pool_id` and rebuilds the pool's config
1057
+ (image/flavor/density/host-idle) from that host job's spec and env vars, returning
1058
+ a [`SandboxPool`] ready to `create()` more sandboxes — packing onto the running
1059
+ hosts, or booting a duplicate (same config) when they are full.
1060
+
1061
+ Raises [`SandboxError`] if no running host is found (a pool stops existing once
1062
+ all of its hosts are gone — idle-timed-out or killed).
1063
+
1064
+ Args:
1065
+ pool_id (`str`):
1066
+ The id returned when the pool was first created.
1067
+ namespace (`str`, *optional*):
1068
+ Namespace to search for the pool's hosts (defaults to yours).
1069
+ token (`str`, *optional*):
1070
+ HF token override.
1071
+ """
1072
+ # Fast path: rebuild the pool from the local best-effort cache, with no HTTP at all.
1073
+ # The cached hosts are seeded (and verified) lazily on the next create(); if they are
1074
+ # all stale, create() falls back to label discovery exactly like a cold connect would.
1075
+ cache = read_pool_cache(pool_id)
1076
+ if cache is not None:
1077
+ return cls(
1078
+ image=cache.image,
1079
+ flavor=cache.flavor,
1080
+ sandboxes_per_host=cache.sandboxes_per_host,
1081
+ max_hosts=cache.max_hosts,
1082
+ name=pool_id,
1083
+ idle_timeout=cache.idle_timeout,
1084
+ namespace=cache.namespace if namespace is None else namespace,
1085
+ token=token,
1086
+ _connect_mode=True, # attach to existing hosts; never boot during construction
1087
+ )
1088
+
1089
+ # Cold path: find a running host via labels and rebuild the config from its job spec.
1090
+ api = HfApi(token=token)
1091
+ job = _find_pool_host_job(api, pool_id, namespace=namespace)
1092
+ env = _host_env(api, job, namespace=namespace)
1093
+ idle_raw = env.get("SBX_IDLE_TIMEOUT")
1094
+ max_hosts_raw = env.get("SBX_MAX_HOSTS")
1095
+ return cls(
1096
+ image=job.docker_image or job.space_id or DEFAULT_IMAGE,
1097
+ flavor=str(job.flavor) if job.flavor is not None else "cpu-basic",
1098
+ sandboxes_per_host=int(env.get("SBX_CAPACITY", DEFAULT_SANDBOXES_PER_HOST)),
1099
+ max_hosts=int(max_hosts_raw) if max_hosts_raw is not None else None,
1100
+ name=pool_id,
1101
+ idle_timeout=int(idle_raw) if idle_raw is not None else None,
1102
+ namespace=namespace,
1103
+ token=token,
1104
+ _connect_mode=True, # attach to existing hosts; never boot during construction
1105
+ )
1106
+
1107
+ def warm(self, num_hosts: int = 1) -> List[str]:
1108
+ """Ensure `num_hosts` empty host(s) are running and leave them running. Returns the
1109
+ pool's host job ids.
1110
+
1111
+ Used to "create" a pool up front: the hosts carry the pool label and config (in
1112
+ their env vars), so a later `SandboxPool.connect(pool_id)` (even from another
1113
+ machine) finds them and spawns sandboxes without a cold start. The hosts keep
1114
+ billing until killed or idle.
1115
+
1116
+ Adopts hosts already running for this pool (found via job labels) before booting,
1117
+ so a `warm()` after `connect()` — or a repeated `warm()` — tops up to `num_hosts`
1118
+ instead of duplicating live hosts and blowing past `max_hosts`.
1119
+ """
1120
+ if self._closed:
1121
+ raise SandboxError("This SandboxPool is closed.")
1122
+ self._discover_hosts()
1123
+ with self._lock:
1124
+ shortfall = num_hosts - len(self._hosts)
1125
+ if shortfall > 0:
1126
+ booted = self._provision_hosts(shortfall)
1127
+ with self._lock:
1128
+ self._hosts.extend(booted)
1129
+ with self._warmup_lock:
1130
+ self._warmed_up = True # explicit warm-up satisfies create()'s one-time warm-up
1131
+ self._save_cache()
1132
+ return self.host_ids
1133
+
1134
+ def create(
1135
+ self,
1136
+ *,
1137
+ env: dict[str, Any] | None = None,
1138
+ idle_timeout: int | float | str | None = DEFAULT_IDLE_TIMEOUT,
1139
+ forward_hf_token: bool = False,
1140
+ ) -> "Sandbox":
1141
+ """Create one sandbox, provisioning a host if needed.
1142
+
1143
+ Reuses a host with free capacity (this pool's, or a warm host found via job labels
1144
+ / the local cache) before booting a new one, so a `create()` against a warm host
1145
+ costs ~one round-trip. Call it repeatedly to fan out; use `warm_up` (or [`warm`])
1146
+ to pre-provision hosts and avoid a cold start on the first calls. If a host fills
1147
+ up under us (another process packed it) or a cached host is gone, the sandbox is
1148
+ re-placed on another host (or a fresh one).
1149
+
1150
+ Args:
1151
+ env (`dict[str, Any]`, *optional*):
1152
+ Environment variables for this sandbox (each sandbox gets its own).
1153
+ idle_timeout (`int` or `float` or `str`, *optional*, defaults to `600`):
1154
+ Per-sandbox idle timeout — a sandbox is evicted from its host
1155
+ after this much inactivity (no API calls, no running process). Distinct
1156
+ from the host idle timeout. Pass `None` to disable.
1157
+ forward_hf_token (`bool`, *optional*, defaults to `False`):
1158
+ If True, inject your HF token as `HF_TOKEN` in the sandbox
1159
+ (opt-in). Unlike a dedicated sandbox's `secrets`, a pooled sandbox's env is
1160
+ delivered to the host server at creation (never stored in the host job), so
1161
+ it doesn't appear in any job's metadata.
1162
+ """
1163
+ if self._closed:
1164
+ raise SandboxError("This SandboxPool is closed.")
1165
+ sandbox_env = dict(env or {})
1166
+ if forward_hf_token:
1167
+ sandbox_env["HF_TOKEN"] = _effective_token(self._api)
1168
+ # None disables per-sandbox idle eviction (mirrors Sandbox.create): leave it out of
1169
+ # the create body entirely rather than sending 0, which the server reads as "evict now".
1170
+ idle_secs = _duration_to_secs(idle_timeout) if idle_timeout is not None else None
1171
+
1172
+ new_hosts: List[_SandboxServer] = []
1173
+ discovered = False
1174
+ rounds = 0
1175
+ try:
1176
+ # One-time warm-up: seed from cache (no HTTP) and pre-provision `warm_up` hosts.
1177
+ # Warm-up hosts are pool-level (like `warm()`), so they survive a failed create().
1178
+ self._ensure_warmed_up()
1179
+ while True:
1180
+ # 1. Reserve a slot on a host we already track.
1181
+ host = self._reserve_one()
1182
+ # 2. If none free, attach (once) to warm hosts discovered via labels.
1183
+ if host is None and not discovered:
1184
+ discovered = True
1185
+ self._discover_hosts()
1186
+ host = self._reserve_one()
1187
+ # 3. Still none? Boot one host (unless we must not resurrect a dead pool).
1188
+ if host is None:
1189
+ if self._require_live_host and discovered and not self._hosts:
1190
+ # connect()'d to a pool whose hosts are all gone (stale cache + nothing
1191
+ # found via labels): don't resurrect it under the same id, just report it.
1192
+ delete_pool_cache(self.name)
1193
+ raise SandboxError(
1194
+ f"No running host found for pool '{self.name}'. The pool has stopped "
1195
+ "(all its hosts were killed or idle-timed-out); create a new one."
1196
+ )
1197
+ host = self._boot_one_host(new_hosts)
1198
+ # 4. Create the sandbox on the reserved host. `None` means the host filled up
1199
+ # (another process packed it) or a stale cached host is gone — retry.
1200
+ if host is not None:
1201
+ try:
1202
+ sandbox = self._create_one(host, sandbox_env, idle_secs)
1203
+ except Exception:
1204
+ # The create POST failed on a live host: release the slot we optimistically
1205
+ # reserved so the host isn't left permanently one sandbox short.
1206
+ with self._lock:
1207
+ host.live = max(0, host.live - 1)
1208
+ raise
1209
+ if sandbox is not None:
1210
+ self._save_cache()
1211
+ return sandbox
1212
+ # sandbox is None: the host is full (packed by another process) or gone.
1213
+ # Either way it's no longer a host we exclusively own, so stop tracking it
1214
+ # for teardown — cancelling it on a later round's failure would kill another
1215
+ # tenant's sandboxes (full host) or hit an already-dead job (gone host).
1216
+ if host in new_hosts:
1217
+ new_hosts.remove(host)
1218
+ discovered = False # re-scan for room / boot a host next round
1219
+ rounds += 1
1220
+ if rounds > _MAX_PACK_ROUNDS:
1221
+ raise SandboxError(
1222
+ "Could not place sandbox: hosts kept reporting full. Raise max_hosts or sandboxes_per_host."
1223
+ )
1224
+ except Exception:
1225
+ # All-or-nothing: tear down hosts we booted in this call.
1226
+ with self._lock:
1227
+ self._hosts = [h for h in self._hosts if h not in new_hosts]
1228
+ for host in new_hosts:
1229
+ try:
1230
+ host.cancel_job()
1231
+ except Exception:
1232
+ pass
1233
+ finally:
1234
+ host.close()
1235
+ raise
1236
+
1237
+ @property
1238
+ def num_hosts(self) -> int:
1239
+ """Number of host jobs currently provisioned."""
1240
+ with self._lock:
1241
+ return len(self._hosts)
1242
+
1243
+ @property
1244
+ def num_sandboxes(self) -> int:
1245
+ """Number of sandboxes currently handed out (across all hosts)."""
1246
+ with self._lock:
1247
+ return sum(host.live for host in self._hosts)
1248
+
1249
+ @property
1250
+ def host_ids(self) -> List[str]:
1251
+ """Job ids of the provisioned hosts."""
1252
+ with self._lock:
1253
+ return [host.job_id for host in self._hosts]
1254
+
1255
+ def close(self) -> None:
1256
+ """Release the pool. Idempotent.
1257
+
1258
+ For a pool we created, this terminates all host jobs (and therefore all their
1259
+ sandboxes). For a `connect()`'d handle it only releases the local HTTP clients: the
1260
+ shared hosts may be serving other clients, so — like [`Sandbox.connect`] — leaving a
1261
+ `with` block must not tear them down. Terminate a connected pool's hosts explicitly
1262
+ with `hf sandbox pool delete <id>`.
1263
+ """
1264
+ with self._lock:
1265
+ hosts = self._hosts
1266
+ self._hosts = []
1267
+ self._closed = True
1268
+ for host in hosts:
1269
+ try:
1270
+ if self._owns_hosts:
1271
+ host.cancel_job()
1272
+ except Exception as e:
1273
+ logger.warning(f"Failed to cancel sandbox host {host.job_id}: {e}")
1274
+ finally:
1275
+ host.close()
1276
+ if self._owns_hosts:
1277
+ delete_pool_cache(self.name) # the pool's hosts are gone; don't leave a stale entry
1278
+
1279
+ def __enter__(self) -> "SandboxPool":
1280
+ return self
1281
+
1282
+ def __exit__(self, *exc_info) -> None:
1283
+ self.close()
1284
+
1285
+ # ------------------------------------------------------------------ internals
1286
+
1287
+ def _ensure_warmed_up(self) -> None:
1288
+ """One-time: seed from the cache and pre-provision up to `warm_up` hosts.
1289
+
1290
+ Cheap by default: seeding is local (no HTTP), and if the cache already gives at
1291
+ least `warm_up` hosts we trust them and skip discovery/booting (dead ones are
1292
+ pruned lazily by `create()`). Only when short do we list_jobs and boot the
1293
+ shortfall in parallel, capped by `max_hosts`.
1294
+
1295
+ Runs at most once per pool, under `_warmup_lock`: concurrent first `create()` calls
1296
+ block here until the warm-up completes — and see its hosts — rather than racing past
1297
+ a half-set flag and each booting their own. `_warmed_up` is only set once the work
1298
+ succeeds, so a failed warm-up is retried (seeding/discovery dedupe by job id).
1299
+
1300
+ Warm-up hosts are pool-level (like [`warm`]): they are not torn down if the
1301
+ triggering `create()` later fails — `close()` (or the `with` block) reclaims them.
1302
+ """
1303
+ with self._warmup_lock:
1304
+ if self._warmed_up:
1305
+ return
1306
+ self._seed_hosts_from_cache()
1307
+ target = self._warm_up if self.max_hosts is None else min(self._warm_up, self.max_hosts)
1308
+ with self._lock:
1309
+ shortfall = target - len(self._hosts)
1310
+ if shortfall > 0:
1311
+ self._discover_hosts()
1312
+ # A connect()'d pool must never boot during warm-up: it may only attach to
1313
+ # existing hosts. Booting is left to create()'s loop, guarded by
1314
+ # `_require_live_host`, so a stopped pool is reported instead of resurrected.
1315
+ if not self._require_live_host:
1316
+ with self._lock:
1317
+ shortfall = target - len(self._hosts)
1318
+ if shortfall > 0:
1319
+ booted = self._provision_hosts(shortfall)
1320
+ with self._lock:
1321
+ self._hosts.extend(booted)
1322
+ self._warmed_up = True
1323
+ # Persist the warmed hosts so the next process (e.g. `hf sandbox create --pool` after a
1324
+ # bare `hf sandbox pool create`) hits the cache fast path instead of re-discovering.
1325
+ if self._hosts:
1326
+ self._save_cache()
1327
+
1328
+ def _reserve_one(self) -> "_SandboxServer | None":
1329
+ """Reserve one slot on the first host with free capacity (under lock), else None."""
1330
+ with self._lock:
1331
+ for host in self._hosts:
1332
+ if host.capacity - host.live > 0:
1333
+ host.live += 1
1334
+ return host
1335
+ return None
1336
+
1337
+ def _boot_one_host(self, new_hosts: List["_SandboxServer"]) -> "_SandboxServer | None":
1338
+ """Provision (or adopt) one host and reserve a slot on it. Returns None to retry.
1339
+
1340
+ Held under `_boot_lock` so that, within a process, only one host is booted at a time:
1341
+ a burst of create() calls that all found every host full queue here, and each new host
1342
+ frees `sandboxes_per_host` slots for the threads still waiting — so they reuse it instead
1343
+ of each booting their own. Before booting, we reuse a slot freed by a concurrent boot and,
1344
+ failing that, adopt a host already SCHEDULING for this pool (here or in another process)
1345
+ rather than piling on a duplicate.
1346
+ """
1347
+ with self._boot_lock:
1348
+ # A concurrent boot (this process) may have added a host with free slots while we
1349
+ # waited for the lock — reuse it instead of booting another.
1350
+ host = self._reserve_one()
1351
+ if host is not None:
1352
+ return host
1353
+ # A host already coming up for this pool (ours, or another process'): wait for it
1354
+ # to start and adopt it instead of booting a duplicate.
1355
+ if self._adopt_pending_host():
1356
+ host = self._reserve_one()
1357
+ if host is not None:
1358
+ return host
1359
+ booted = self._provision_hosts(1)
1360
+ new_hosts.extend(booted)
1361
+ with self._lock:
1362
+ self._hosts.extend(booted)
1363
+ return self._reserve_one()
1364
+
1365
+ def _adopt_pending_host(self) -> bool:
1366
+ """Wait for and adopt a host already SCHEDULING for this pool, if any.
1367
+
1368
+ Avoids over-provisioning when a host is already on its way up for this pool (started by
1369
+ another process, or an earlier create() in this one): rather than booting a duplicate,
1370
+ wait for it to reach RUNNING and adopt it via discovery. Returns True if a pending host
1371
+ was found (whether or not it eventually came up), False if none is scheduling.
1372
+ """
1373
+ known = {host.job_id for host in self._hosts}
1374
+ pending = next(
1375
+ (
1376
+ job
1377
+ for job in self._api.list_jobs(
1378
+ status="SCHEDULING",
1379
+ labels={MODE_LABEL: MODE_POOL, POOL_LABEL: self.name},
1380
+ namespace=self._namespace,
1381
+ )
1382
+ if job.id not in known
1383
+ ),
1384
+ None,
1385
+ )
1386
+ if pending is None:
1387
+ return False
1388
+ logger.debug(f"Pool '{self.name}' host {pending.id} is already SCHEDULING; waiting for it instead of booting.")
1389
+ deadline = time.time() + self._start_timeout
1390
+ while time.time() < deadline:
1391
+ stage = self._api.inspect_job(job_id=pending.id, namespace=self._namespace).status.stage
1392
+ if stage not in ("SCHEDULING", "RUNNING"):
1393
+ return False # it died before starting up; let the caller boot a fresh one
1394
+ if stage == "RUNNING":
1395
+ # RUNNING precedes "server ready" (the host still has to fetch + exec sbx-server),
1396
+ # so discovery only adopts it once its server answers — keep polling until it does.
1397
+ self._discover_hosts()
1398
+ if any(host.job_id == pending.id for host in self._hosts):
1399
+ return True
1400
+ time.sleep(1.0)
1401
+ return False
1402
+
1403
+ def _discover_hosts(self) -> None:
1404
+ """Attach to running host jobs that match this pool (image/flavor/name).
1405
+
1406
+ Lets `create()` reuse a host warmed by an earlier call or another process
1407
+ instead of booting a new one. Hosts are found via job labels; each adopted
1408
+ host's free capacity is read from the server, so packing stays accurate.
1409
+ """
1410
+ known = {host.job_id for host in self._hosts}
1411
+ matches = [
1412
+ job
1413
+ for job in self._api.list_jobs(
1414
+ status="RUNNING",
1415
+ labels={MODE_LABEL: MODE_POOL, POOL_LABEL: self.name},
1416
+ namespace=self._namespace,
1417
+ )
1418
+ if job.id not in known
1419
+ ]
1420
+
1421
+ for job in matches:
1422
+ server = None
1423
+ try:
1424
+ server = _connect_host(self._api, job.id, namespace=self._namespace)
1425
+ # Capacity comes from the host's SBX_CAPACITY env; otherwise an adopted host
1426
+ # would silently pack at the pool default and mis-pack.
1427
+ env = _host_env(self._api, job, namespace=self._namespace)
1428
+ server.capacity = int(env.get("SBX_CAPACITY", self.sandboxes_per_host))
1429
+ server.live = len(server.request("GET", "/v1/sandboxes").json())
1430
+ except (SandboxError, httpx.HTTPError, HfHubHTTPError) as e:
1431
+ # Host died (e.g. deleted between list_jobs and inspect_job), is still starting
1432
+ # up, or is unreachable: skip it, closing the client if one was opened.
1433
+ logger.debug(f"Skipping host {job.id} during discovery: {e}")
1434
+ if server is not None:
1435
+ server.close()
1436
+ continue
1437
+ with self._lock:
1438
+ if any(host.job_id == job.id for host in self._hosts):
1439
+ server.close() # adopted concurrently by another thread
1440
+ else:
1441
+ self._hosts.append(server)
1442
+
1443
+ def _provision_hosts(self, num_new: int) -> List[_SandboxServer]:
1444
+ """Boot `num_new` host jobs in parallel, respecting `max_hosts`."""
1445
+ with self._lock:
1446
+ current = len(self._hosts)
1447
+ if self.max_hosts is not None and current + num_new > self.max_hosts:
1448
+ allowed = self.max_hosts - current
1449
+ raise SandboxError(
1450
+ f"Pool needs {num_new} more host(s) but max_hosts={self.max_hosts} "
1451
+ f"allows only {max(0, allowed)} more. Raise max_hosts or kill some sandboxes."
1452
+ )
1453
+ # Boot in parallel, but collect every result before re-raising: if one boot fails,
1454
+ # the others may have already started billable host jobs, so cancel those instead of
1455
+ # leaking them (executor.map would surface the first error and drop the rest).
1456
+ with ThreadPoolExecutor(max_workers=min(num_new, 32)) as executor:
1457
+ futures = [executor.submit(self._boot_host) for _ in range(num_new)]
1458
+ booted: List[_SandboxServer] = []
1459
+ error: Exception | None = None
1460
+ for future in futures:
1461
+ try:
1462
+ booted.append(future.result())
1463
+ except Exception as e:
1464
+ error = e
1465
+ if error is not None:
1466
+ for server in booted:
1467
+ try:
1468
+ server.cancel_job()
1469
+ except Exception:
1470
+ pass
1471
+ finally:
1472
+ server.close()
1473
+ raise error
1474
+ return booted
1475
+
1476
+ def _boot_host(self) -> _SandboxServer:
1477
+ """Start one host job and wait until its server is ready."""
1478
+ hf_token = _effective_token(self._api)
1479
+ nonce = token_hex(16)
1480
+ sandbox_token = _derive_sandbox_token(hf_token, nonce)
1481
+ command, job_env, job_secrets, job_volumes = _bootstrap_job_spec(
1482
+ self._api,
1483
+ hf_token,
1484
+ env=None, # host job carries no user env; sandboxes get env per create request
1485
+ secrets=None,
1486
+ volumes=None,
1487
+ idle_timeout=self._idle_timeout,
1488
+ forward_hf_token=False,
1489
+ sandbox_token=sandbox_token,
1490
+ )
1491
+ # Host mode: per-sandbox idle eviction + empty-host shutdown (vs the dedicated
1492
+ # whole-job watchdog).
1493
+ job_env["SBX_HOST_MODE"] = "1"
1494
+ # Server-authoritative packing cap: the host refuses creates past this (the client
1495
+ # then packs onto / boots another host). Avoids cross-process over-commit. Read
1496
+ # back (with SBX_IDLE_TIMEOUT) by `connect()` to rebuild the pool — labels stay for
1497
+ # filtering only.
1498
+ job_env["SBX_CAPACITY"] = str(self.sandboxes_per_host)
1499
+ # Persist the optional cost ceiling on the host too, so a later connect() (e.g. the CLI
1500
+ # `pool create --max-hosts N` then `create --pool <id>` flow) rebuilds the cap instead of
1501
+ # defaulting to unlimited and provisioning past it.
1502
+ if self.max_hosts is not None:
1503
+ job_env["SBX_MAX_HOSTS"] = str(self.max_hosts)
1504
+ labels = {SANDBOX_LABEL: "1", MODE_LABEL: MODE_POOL, POOL_LABEL: self.name, NONCE_LABEL: nonce}
1505
+ job = self._api.run_job(
1506
+ image=self.image,
1507
+ command=command,
1508
+ env=job_env,
1509
+ secrets=job_secrets,
1510
+ flavor=self.flavor,
1511
+ timeout=SANDBOX_MAX_LIFETIME,
1512
+ labels=labels,
1513
+ volumes=job_volumes or None,
1514
+ expose=[SANDBOX_SERVER_PORT],
1515
+ namespace=self._namespace,
1516
+ )
1517
+ server: "_SandboxServer | None" = None
1518
+ try:
1519
+ # from_job is inside the try: if it raises (e.g. the server port isn't exposed),
1520
+ # the already-started host job must still be cancelled so it doesn't linger billing.
1521
+ server = _SandboxServer.from_job(
1522
+ job=job,
1523
+ nonce=nonce,
1524
+ sandbox_token=sandbox_token,
1525
+ api=self._api,
1526
+ max_connections=min(self.sandboxes_per_host + 8, 256),
1527
+ capacity=self.sandboxes_per_host,
1528
+ )
1529
+ server.wait_ready(self._start_timeout)
1530
+ except Exception:
1531
+ try:
1532
+ self._api.cancel_job(job_id=job.id, namespace=job.owner.name)
1533
+ except Exception as e:
1534
+ logger.warning(f"Failed to cancel sandbox host {job.id} after startup failure: {e}")
1535
+ if server is not None:
1536
+ server.close()
1537
+ raise
1538
+ return server
1539
+
1540
+ def _create_one(self, host: "_SandboxServer", env: dict[str, Any], idle_secs: int | None) -> "Sandbox | None":
1541
+ """Create one sandbox on a reserved `host`. Returns the sandbox, or None to retry.
1542
+
1543
+ None means either the host filled up between our reservation and the create
1544
+ (server-authoritative capacity — another client packed it, so we mark it full and
1545
+ place the sandbox elsewhere) or a host rebuilt from the cache is gone/unreachable
1546
+ (dropped and re-placed via discovery / a fresh boot).
1547
+ """
1548
+ body: dict[str, Any] = {"count": 1}
1549
+ if idle_secs is not None:
1550
+ body["idle_timeout_secs"] = idle_secs
1551
+ if env:
1552
+ body["env"] = env
1553
+ try:
1554
+ data = host.request("POST", "/v1/sandboxes", json=body).json()
1555
+ except (SandboxError, httpx.HTTPError) as e:
1556
+ if host.verified:
1557
+ raise # a host we booted/discovered this session failing is a real error
1558
+ logger.debug(f"Dropping unreachable cached host {host.job_id}: {e}")
1559
+ self._drop_host(host)
1560
+ return None
1561
+ host.verified = True # it answered, so it's a real live host now
1562
+ sandboxes = data.get("sandboxes") or []
1563
+ if int(data.get("rejected", 0)) or not sandboxes:
1564
+ with self._lock:
1565
+ host.live = host.capacity # the host is full; stop reserving it
1566
+ return None
1567
+ item = sandboxes[0]
1568
+ sandbox = Sandbox(
1569
+ id=f"{host.job_id}{SHARED_ID_SEP}{item['id']}",
1570
+ server=host,
1571
+ local_id=item["id"],
1572
+ owns_sandbox=True,
1573
+ owns_server=False,
1574
+ )
1575
+ sandbox._on_kill = self._on_sandbox_killed
1576
+ return sandbox
1577
+
1578
+ def _on_sandbox_killed(self, sandbox: Sandbox) -> None:
1579
+ """Free the packing slot of a shared sandbox that was killed."""
1580
+ with self._lock:
1581
+ sandbox._server.live = max(0, sandbox._server.live - 1)
1582
+
1583
+ def _drop_host(self, host: _SandboxServer) -> None:
1584
+ """Forget a host found dead this session (and mark it for cache pruning)."""
1585
+ with self._lock:
1586
+ self._hosts = [h for h in self._hosts if h is not host]
1587
+ self._dead_host_ids.add(host.job_id)
1588
+ host.close()
1589
+
1590
+ # ------------------------------------------------------------------ cache (best effort)
1591
+
1592
+ def _seed_hosts_from_cache(self) -> None:
1593
+ """Adopt the pool's cached hosts without any HTTP (rebuilt from cached URL + nonce).
1594
+
1595
+ Best-effort and unverified: each adopted host is confirmed on the first successful
1596
+ request (and dropped on the first failure, see `_create_one`). Hosts the cache
1597
+ believes are full are skipped — label discovery re-checks them with fresh counts if
1598
+ the seeded ones don't satisfy the request, so a stale-full entry never blocks a create.
1599
+ """
1600
+ cache = read_pool_cache(self.name)
1601
+ if cache is None:
1602
+ return
1603
+ hf_token = _effective_token(self._api)
1604
+ with self._lock:
1605
+ known = {host.job_id for host in self._hosts}
1606
+ for ch in cache.hosts:
1607
+ if ch.job_id in known or ch.live >= ch.capacity:
1608
+ continue
1609
+ server = _SandboxServer(
1610
+ job_id=ch.job_id,
1611
+ owner=ch.owner,
1612
+ image=self.image,
1613
+ base_url=ch.base_url,
1614
+ nonce=ch.nonce,
1615
+ sandbox_token=_derive_sandbox_token(hf_token, ch.nonce),
1616
+ api=self._api,
1617
+ max_connections=min(self.sandboxes_per_host + 8, 256),
1618
+ capacity=ch.capacity,
1619
+ )
1620
+ server.live = ch.live
1621
+ server.verified = False
1622
+ self._hosts.append(server)
1623
+
1624
+ def _save_cache(self) -> None:
1625
+ """Persist the pool config + current hosts (with their live counts) for next time."""
1626
+ with self._lock:
1627
+ hosts = [
1628
+ CachedHost(
1629
+ job_id=host.job_id,
1630
+ owner=host.owner,
1631
+ base_url=host.base_url,
1632
+ nonce=host.nonce,
1633
+ capacity=host.capacity,
1634
+ live=host.live,
1635
+ updated_at=time.time(),
1636
+ )
1637
+ for host in self._hosts
1638
+ ]
1639
+ dead = set(self._dead_host_ids)
1640
+ save_pool_cache(
1641
+ self.name,
1642
+ image=self.image,
1643
+ flavor=self.flavor,
1644
+ sandboxes_per_host=self.sandboxes_per_host,
1645
+ max_hosts=self.max_hosts,
1646
+ idle_timeout=_duration_to_secs(self._idle_timeout) if self._idle_timeout is not None else None,
1647
+ namespace=self._namespace,
1648
+ hosts=hosts,
1649
+ dead_host_ids=dead,
1650
+ )
1651
+
1652
+
1653
+ def _effective_token(api: HfApi) -> str:
1654
+ token = api.token if isinstance(api.token, str) else get_token()
1655
+ if not token:
1656
+ raise SandboxError("A Hugging Face token is required to use sandboxes. Run `hf auth login` first.")
1657
+ return token
1658
+
1659
+
1660
+ def _bootstrap_job_spec(
1661
+ api: HfApi,
1662
+ hf_token: str,
1663
+ *,
1664
+ env: dict[str, Any] | None,
1665
+ secrets: dict[str, Any] | None,
1666
+ volumes: List[Volume] | None,
1667
+ idle_timeout: int | float | str | None,
1668
+ forward_hf_token: bool,
1669
+ sandbox_token: str,
1670
+ ) -> tuple[list[str], dict[str, Any], dict[str, Any], List[Volume]]:
1671
+ """Build the (command, env, secrets, volumes) to launch a job running sbx-server.
1672
+
1673
+ Shared by dedicated sandboxes and shared hosts: both fetch and exec the same unified
1674
+ `sbx-server` binary at startup (via `/bin/sh`), downloading it with wget/curl, or
1675
+ reading it off the always-mounted server bucket when the image ships neither.
1676
+ """
1677
+ # Reserved SBX_* keys go last so user-provided env/secrets can't override them
1678
+ # (e.g. clobbering SBX_PORT would break the proxy, SBX_TOKEN would break auth).
1679
+ job_env: dict[str, Any] = {**(env or {}), "SBX_PORT": str(SANDBOX_SERVER_PORT)}
1680
+ job_secrets: dict[str, Any] = {**(secrets or {}), "SBX_TOKEN": sandbox_token}
1681
+ job_volumes = list(volumes or [])
1682
+ if idle_timeout is not None:
1683
+ job_env["SBX_IDLE_TIMEOUT"] = str(_duration_to_secs(idle_timeout))
1684
+ if forward_hf_token:
1685
+ job_secrets["HF_TOKEN"] = hf_token
1686
+
1687
+ job_env["SBX_SERVER_URL"] = f"{api.endpoint}/buckets/{constants.SANDBOX_SERVER_BUCKET}/resolve/sbx-server"
1688
+ job_secrets["SBX_DL_TOKEN"] = hf_token
1689
+ # Always mount the server bucket as a transparent fallback for images without wget/curl.
1690
+ # It's only read (paying the ~2-3s FUSE cost) when the bootstrap script can't download.
1691
+ job_env["SBX_SERVER_MOUNT"] = _SERVER_MOUNT_PATH
1692
+ job_volumes.append(
1693
+ Volume(type="bucket", source=constants.SANDBOX_SERVER_BUCKET, mount_path=_SERVER_MOUNT_PATH, read_only=True)
1694
+ )
1695
+ command = ["/bin/sh", "-c", _BOOTSTRAP_DOWNLOAD]
1696
+ return command, job_env, job_secrets, job_volumes
1697
+
1698
+
1699
+ def _host_env(api: HfApi, job: JobInfo, *, namespace: str | None) -> dict[str, Any]:
1700
+ """Return a host job's env vars (where pool config lives)"""
1701
+ env = job.environment if isinstance(job.environment, dict) else {}
1702
+ if "SBX_CAPACITY" not in env:
1703
+ env = api.inspect_job(job_id=job.id, namespace=namespace).environment or {}
1704
+ env = env if isinstance(env, dict) else {}
1705
+ return env
1706
+
1707
+
1708
+ def _find_pool_host_job(api: HfApi, pool_id: str, *, namespace: str | None = None) -> JobInfo:
1709
+ """Return any running host job belonging to `pool_id` (found via the pool label)."""
1710
+ for job in api.list_jobs(
1711
+ status="RUNNING", labels={MODE_LABEL: MODE_POOL, POOL_LABEL: pool_id}, namespace=namespace
1712
+ ):
1713
+ return job
1714
+ raise SandboxError(
1715
+ f"No running host found for pool '{pool_id}'. The pool has stopped "
1716
+ "(all its hosts were killed or idle-timed-out); create a new one."
1717
+ )
1718
+
1719
+
1720
+ def _connect_host(api: HfApi, host_job_id: str, *, namespace: str | None = None) -> _SandboxServer:
1721
+ """Reattach to a running host job and return its server transport."""
1722
+ job = api.inspect_job(job_id=host_job_id, namespace=namespace)
1723
+ labels = job.labels or {}
1724
+ nonce = labels.get(NONCE_LABEL)
1725
+ if nonce is None or labels.get(MODE_LABEL) != MODE_POOL:
1726
+ raise SandboxError(f"Job {host_job_id} is not a sandbox host.")
1727
+ if job.status.stage != "RUNNING":
1728
+ raise SandboxError(f"Sandbox host {host_job_id} is not running (status: {job.status.stage}).")
1729
+ return _SandboxServer.from_job(
1730
+ job=job,
1731
+ nonce=nonce,
1732
+ sandbox_token=_derive_sandbox_token(_effective_token(api), nonce),
1733
+ api=api,
1734
+ max_connections=SandboxFiles.PARALLEL_MAX_WORKERS + 2,
1735
+ )
1736
+
1737
+
1738
+ def _split_sandbox_id(sandbox_id: str, namespace: str | None) -> tuple[str, str | None]:
1739
+ """Accept `namespace/sandbox_id` ids (as shown in the Hub UI), like `hf jobs` does."""
1740
+ if "/" not in sandbox_id:
1741
+ return sandbox_id, namespace
1742
+ extracted_namespace, parsed_id = sandbox_id.split("/", 1)
1743
+ if not extracted_namespace or not parsed_id or "/" in parsed_id:
1744
+ raise SandboxError(f"Sandbox id must be 'sandbox_id' or 'namespace/sandbox_id', got {sandbox_id!r}.")
1745
+ if namespace is not None and namespace != extracted_namespace:
1746
+ raise SandboxError(
1747
+ f"Conflicting namespace: got namespace={namespace!r} but sandbox id implies namespace={extracted_namespace!r}."
1748
+ )
1749
+ return parsed_id, extracted_namespace
1750
+
1751
+
1752
+ def _find_server_url(job: JobInfo) -> str:
1753
+ for url in job.status.expose_urls or []:
1754
+ if f"--{SANDBOX_SERVER_PORT}." in url:
1755
+ return url
1756
+ raise SandboxError(f"Job {job.id} does not expose the sandbox server port {SANDBOX_SERVER_PORT}.")
1757
+
1758
+
1759
+ def _tail_job_logs(api: HfApi, job_id: str, *, namespace: str | None = None, limit: int = 20) -> str:
1760
+ try:
1761
+ lines = list(api.fetch_job_logs(job_id=job_id, namespace=namespace))[-limit:]
1762
+ except Exception:
1763
+ return ""
1764
+ return " Last logs:\n" + "\n".join(f" {line}" for line in lines) if lines else ""
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_sandbox_cache.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2026-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Best-effort local cache for SandboxPool hosts (host/pool mode)."""
16
+
17
+ import json
18
+ import os
19
+ import time
20
+ from dataclasses import asdict, dataclass, field
21
+ from pathlib import Path
22
+ from typing import List
23
+
24
+ from . import constants
25
+ from .utils import WeakFileLock, logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+ # Bump if the on-disk layout changes incompatibly; older/newer files are ignored on read.
31
+ _CACHE_VERSION = 1
32
+
33
+ # A write should never block a sandbox creation for long: the cache is best-effort, so we
34
+ # rather skip persisting than wait on a stuck lock.
35
+ _LOCK_TIMEOUT = 5.0
36
+
37
+
38
+ @dataclass
39
+ class CachedHost:
40
+ """A single host Job of a pool, as last seen by some process.
41
+
42
+ `base_url` + `nonce` are everything needed to rebuild the in-job server transport
43
+ (`_SandboxServer`) without an `inspect_job` round-trip: the per-sandbox auth token is
44
+ re-derived from the user's HF token and `nonce` (see `_derive_sandbox_token`).
45
+ """
46
+
47
+ job_id: str
48
+ owner: str # namespace the host job runs under (for cancel/inspect)
49
+ base_url: str # exposed sbx-server URL (does not change while the job lives)
50
+ nonce: str # public nonce from the job label; derives the sandbox auth token
51
+ capacity: int # SBX_CAPACITY: max sandboxes the host packs
52
+ live: int # sandboxes last observed on the host (best-effort, may be stale)
53
+ updated_at: float = 0.0
54
+
55
+
56
+ @dataclass
57
+ class PoolCache:
58
+ """Cached view of one pool: its config (to boot new hosts) + its known hosts."""
59
+
60
+ pool_id: str
61
+ image: str
62
+ flavor: str
63
+ sandboxes_per_host: int
64
+ max_hosts: int | None
65
+ idle_timeout: int | None
66
+ namespace: str | None
67
+ hosts: List[CachedHost] = field(default_factory=list)
68
+ version: int = _CACHE_VERSION
69
+ updated_at: float = 0.0
70
+
71
+
72
+ def _pools_dir() -> Path:
73
+ return Path(constants.HF_HOME) / "sandbox" / "pools"
74
+
75
+
76
+ def pool_cache_path(pool_id: str) -> Path:
77
+ """Path of the cache file for `pool_id` (no I/O)."""
78
+ if any(c in pool_id for c in ("/", "\\", "\x00")) or pool_id in (".", ".."):
79
+ raise ValueError(f"Invalid pool id: {pool_id!r}")
80
+ return _pools_dir() / f"{pool_id}.json"
81
+
82
+
83
+ def read_pool_cache(pool_id: str) -> PoolCache | None:
84
+ """Return the cached view of `pool_id`, or `None` if missing/corrupt/incompatible."""
85
+ try:
86
+ path = pool_cache_path(pool_id)
87
+ with path.open("r", encoding="utf-8") as f:
88
+ data = json.load(f)
89
+ if data.get("version") != _CACHE_VERSION:
90
+ return None
91
+ hosts = [CachedHost(**h) for h in data.pop("hosts", [])]
92
+ return PoolCache(**data, hosts=hosts)
93
+ except FileNotFoundError:
94
+ return None
95
+ except Exception as e:
96
+ logger.debug(f"Ignoring unreadable sandbox pool cache for {pool_id!r}: {e}")
97
+ return None
98
+
99
+
100
+ def save_pool_cache(
101
+ pool_id: str,
102
+ *,
103
+ image: str,
104
+ flavor: str,
105
+ sandboxes_per_host: int,
106
+ max_hosts: int | None,
107
+ idle_timeout: int | None,
108
+ namespace: str | None,
109
+ hosts: List[CachedHost],
110
+ dead_host_ids: set[str] | None = None,
111
+ ) -> None:
112
+ """Merge `hosts` into the cache for `pool_id` (best-effort, never raises).
113
+
114
+ Concurrency-safe: under a file lock, the on-disk hosts are read, then `hosts` are
115
+ upserted by `job_id` and `dead_host_ids` removed, so a process only adds/updates what
116
+ it learned and never drops hosts another process discovered. The result is written
117
+ atomically. The pool config is refreshed from the arguments.
118
+ """
119
+ dead = dead_host_ids or set()
120
+ try:
121
+ path = pool_cache_path(pool_id)
122
+ path.parent.mkdir(parents=True, exist_ok=True)
123
+ with WeakFileLock(str(path) + ".lock", timeout=_LOCK_TIMEOUT):
124
+ existing = read_pool_cache(pool_id)
125
+ merged = {h.job_id: h for h in (existing.hosts if existing else [])}
126
+ for host in hosts:
127
+ merged[host.job_id] = host
128
+ for job_id in dead:
129
+ merged.pop(job_id, None)
130
+ cache = PoolCache(
131
+ pool_id=pool_id,
132
+ image=image,
133
+ flavor=flavor,
134
+ sandboxes_per_host=sandboxes_per_host,
135
+ max_hosts=max_hosts,
136
+ idle_timeout=idle_timeout,
137
+ namespace=namespace,
138
+ hosts=list(merged.values()),
139
+ updated_at=time.time(),
140
+ )
141
+ _atomic_write(path, cache)
142
+ except Exception as e:
143
+ logger.debug(f"Could not write sandbox pool cache for {pool_id!r}: {e}")
144
+
145
+
146
+ def delete_pool_cache(pool_id: str) -> None:
147
+ """Remove the cache file for `pool_id` (best-effort, never raises)."""
148
+ try:
149
+ pool_cache_path(pool_id).unlink(missing_ok=True)
150
+ except Exception as e:
151
+ logger.debug(f"Could not delete sandbox pool cache for {pool_id}: {e}")
152
+
153
+
154
+ def _atomic_write(path: Path, cache: PoolCache) -> None:
155
+ """Write the cache via a temp file + `os.replace` so readers never see a partial file."""
156
+ tmp = path.parent / f"{path.name}.{os.getpid()}.tmp"
157
+ with tmp.open("w", encoding="utf-8") as f:
158
+ json.dump(asdict(cache), f, indent=2)
159
+ os.replace(tmp, path)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_snapshot_download.py ADDED
@@ -0,0 +1,681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Literal, overload
4
+
5
+ import httpx
6
+ from tqdm.auto import tqdm as base_tqdm
7
+ from tqdm.contrib.concurrent import thread_map
8
+
9
+ from . import constants
10
+ from ._tree_cache import TreeCacheEntry, read_tree_cache, tree_cache_folder_for_local_dir, write_tree_cache
11
+ from .errors import (
12
+ CachedRepoTreeNotFoundError,
13
+ DryRunError,
14
+ GatedRepoError,
15
+ HfHubHTTPError,
16
+ IncompleteSnapshotError,
17
+ LocalEntryNotFoundError,
18
+ RepositoryNotFoundError,
19
+ RevisionNotFoundError,
20
+ )
21
+ from .file_download import REGEX_COMMIT_HASH, DryRunFileInfo, hf_hub_download, repo_folder_name
22
+ from .hf_api import DatasetInfo, HfApi, KernelInfo, ModelInfo, RepoFile, SpaceInfo
23
+ from .utils import OfflineModeIsEnabled, filter_repo_objects, logging, validate_hf_hub_args
24
+ from .utils._xet_progress_reporting import (
25
+ XET_BYTES_BAR_FORMAT,
26
+ XET_TRANSFER_BAR_FORMAT,
27
+ _finish_transfer_bar,
28
+ _update_transfer_bar,
29
+ )
30
+ from .utils.tqdm import _create_progress_bar
31
+ from .utils.tqdm import tqdm as hf_tqdm
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ @overload
38
+ def snapshot_download(
39
+ repo_id: str,
40
+ *,
41
+ repo_type: str | None = None,
42
+ revision: str | None = None,
43
+ cache_dir: str | Path | None = None,
44
+ local_dir: str | Path | None = None,
45
+ library_name: str | None = None,
46
+ library_version: str | None = None,
47
+ user_agent: dict | str | None = None,
48
+ etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
49
+ force_download: bool = False,
50
+ token: bool | str | None = None,
51
+ local_files_only: bool = False,
52
+ allow_patterns: list[str] | str | None = None,
53
+ ignore_patterns: list[str] | str | None = None,
54
+ max_workers: int = 8,
55
+ tqdm_class: type[base_tqdm] | None = None,
56
+ headers: dict[str, str] | None = None,
57
+ endpoint: str | None = None,
58
+ dry_run: Literal[False] = False,
59
+ ) -> str: ...
60
+
61
+
62
+ @overload
63
+ def snapshot_download(
64
+ repo_id: str,
65
+ *,
66
+ repo_type: str | None = None,
67
+ revision: str | None = None,
68
+ cache_dir: str | Path | None = None,
69
+ local_dir: str | Path | None = None,
70
+ library_name: str | None = None,
71
+ library_version: str | None = None,
72
+ user_agent: dict | str | None = None,
73
+ etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
74
+ force_download: bool = False,
75
+ token: bool | str | None = None,
76
+ local_files_only: bool = False,
77
+ allow_patterns: list[str] | str | None = None,
78
+ ignore_patterns: list[str] | str | None = None,
79
+ max_workers: int = 8,
80
+ tqdm_class: type[base_tqdm] | None = None,
81
+ headers: dict[str, str] | None = None,
82
+ endpoint: str | None = None,
83
+ dry_run: Literal[True] = True,
84
+ ) -> list[DryRunFileInfo]: ...
85
+
86
+
87
+ @overload
88
+ def snapshot_download(
89
+ repo_id: str,
90
+ *,
91
+ repo_type: str | None = None,
92
+ revision: str | None = None,
93
+ cache_dir: str | Path | None = None,
94
+ local_dir: str | Path | None = None,
95
+ library_name: str | None = None,
96
+ library_version: str | None = None,
97
+ user_agent: dict | str | None = None,
98
+ etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
99
+ force_download: bool = False,
100
+ token: bool | str | None = None,
101
+ local_files_only: bool = False,
102
+ allow_patterns: list[str] | str | None = None,
103
+ ignore_patterns: list[str] | str | None = None,
104
+ max_workers: int = 8,
105
+ tqdm_class: type[base_tqdm] | None = None,
106
+ headers: dict[str, str] | None = None,
107
+ endpoint: str | None = None,
108
+ dry_run: bool = False,
109
+ ) -> str | list[DryRunFileInfo]: ...
110
+
111
+
112
+ @validate_hf_hub_args
113
+ def snapshot_download(
114
+ repo_id: str,
115
+ *,
116
+ repo_type: str | None = None,
117
+ revision: str | None = None,
118
+ cache_dir: str | Path | None = None,
119
+ local_dir: str | Path | None = None,
120
+ library_name: str | None = None,
121
+ library_version: str | None = None,
122
+ user_agent: dict | str | None = None,
123
+ etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
124
+ force_download: bool = False,
125
+ token: bool | str | None = None,
126
+ local_files_only: bool = False,
127
+ allow_patterns: list[str] | str | None = None,
128
+ ignore_patterns: list[str] | str | None = None,
129
+ max_workers: int = 8,
130
+ tqdm_class: type[base_tqdm] | None = None,
131
+ headers: dict[str, str] | None = None,
132
+ endpoint: str | None = None,
133
+ dry_run: bool = False,
134
+ ) -> str | list[DryRunFileInfo]:
135
+ """Download repo files.
136
+
137
+ Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
138
+ a repo because you don't know which ones you will need _a priori_. All files are nested in a folder to keep their
139
+ path and filename relative to that folder. You can also filter which files to download by using `allow_patterns`
140
+ and `ignore_patterns`.
141
+
142
+ If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
143
+ option, the `cache_dir` will not be used, and a `.cache/huggingface/` folder will be created at the root of `local_dir`
144
+ to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
145
+ cache system, it's optimized for regularly pulling the latest version of a repository.
146
+
147
+ An alternative would be to clone the repo, but this requires git and git-lfs to be installed and properly
148
+ configured. It is also not possible to filter which files to download when cloning a repository using git.
149
+
150
+ Args:
151
+ repo_id (`str`):
152
+ A user or an organization name and a repo name separated by a `/`.
153
+ repo_type (`str`, *optional*):
154
+ Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo,
155
+ `None` or `"model"` if downloading from a model. Default is `None`.
156
+ revision (`str`, *optional*):
157
+ An optional Git revision id, which can be a branch name, a tag, or a
158
+ commit hash.
159
+ cache_dir (`str`, `Path`, *optional*):
160
+ Path to the folder where cached files are stored.
161
+ local_dir (`str` or `Path`, *optional*):
162
+ If provided, the downloaded files will be placed under this directory.
163
+ library_name (`str`, *optional*):
164
+ The name of the library to which the object corresponds.
165
+ library_version (`str`, *optional*):
166
+ The version of the library.
167
+ user_agent (`str`, `dict`, *optional*):
168
+ The user-agent info in the form of a dictionary or a string.
169
+ etag_timeout (`float`, *optional*, defaults to `10`):
170
+ When fetching ETag, how many seconds to wait for the server to send
171
+ data before giving up, which is passed to `httpx.request`.
172
+ force_download (`bool`, *optional*, defaults to `False`):
173
+ Whether the file should be downloaded even if it already exists in the local cache.
174
+ token (`str`, `bool`, *optional*):
175
+ A token to be used for the download.
176
+ - If `True`, the token is read from the HuggingFace config
177
+ folder.
178
+ - If a string, it's used as the authentication token.
179
+ headers (`dict`, *optional*):
180
+ Additional headers to include in the request. Those headers take precedence over the others.
181
+ endpoint (`str`, *optional*):
182
+ The Hub endpoint to send the request to. Defaults to the value of `HF_ENDPOINT`.
183
+ local_files_only (`bool`, *optional*, defaults to `False`):
184
+ If `True`, do not download any files even if they are not in `cache_dir` or `local_dir`.
185
+ allow_patterns (`list[str]` or `str`, *optional*):
186
+ If provided, only files matching at least one pattern are downloaded.
187
+ ignore_patterns (`list[str]` or `str`, *optional*):
188
+ If provided, files matching any of the patterns are not downloaded.
189
+ max_workers (`int`, *optional*):
190
+ Number of concurrent threads to download files (1 thread = 1 file download).
191
+ Defaults to 8.
192
+ tqdm_class (`tqdm`, *optional*):
193
+ If provided, overwrites the default behavior for the progress bar. Passed
194
+ argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
195
+ Note that the `tqdm_class` is not passed to each individual download.
196
+ Defaults to the custom HF progress bar that can be disabled by setting
197
+ `HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
198
+ dry_run (`bool`, *optional*, defaults to `False`):
199
+ If `True`, perform a dry run without actually downloading the files. Returns a list of
200
+ [`DryRunFileInfo`] objects containing information about what would be downloaded.
201
+
202
+ Returns:
203
+ `str` or list of [`DryRunFileInfo`]:
204
+ - If `dry_run=False`: Local snapshot path.
205
+ - If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information.
206
+
207
+ Raises:
208
+ [`~utils.RepositoryNotFoundError`]
209
+ If the repository to download from cannot be found. This may be because it doesn't exist
210
+ or because it is set to `private` and you do not have access.
211
+ [`~utils.RevisionNotFoundError`]
212
+ If the revision to download from cannot be found.
213
+ [`~errors.IncompleteSnapshotError`]
214
+ If the Hub cannot be reached (offline, connection issue, or `local_files_only=True`) and the
215
+ cached snapshot is missing some of the requested files.
216
+ [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
217
+ If `token=True` and the token cannot be found.
218
+ [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
219
+ ETag cannot be determined.
220
+ [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
221
+ If some parameter value is invalid.
222
+ """
223
+ if cache_dir is None:
224
+ cache_dir = constants.HF_HUB_CACHE
225
+ cache_dir = str(Path(cache_dir).expanduser().resolve())
226
+ if local_dir is not None:
227
+ local_dir = str(Path(local_dir).expanduser().resolve())
228
+ if revision is None:
229
+ revision = constants.DEFAULT_REVISION
230
+
231
+ if repo_type is None:
232
+ repo_type = "model"
233
+ if repo_type not in constants.REPO_TYPES_WITH_KERNEL:
234
+ raise ValueError(
235
+ f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES_WITH_KERNEL)}"
236
+ )
237
+
238
+ storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
239
+
240
+ # Folder under which the per-commit tree listing (`trees/<commit_hash>.json`) is cached on disk.
241
+ tree_cache_folder = tree_cache_folder_for_local_dir(local_dir) if local_dir is not None else storage_folder
242
+
243
+ api = HfApi(
244
+ library_name=library_name,
245
+ library_version=library_version,
246
+ user_agent=user_agent,
247
+ endpoint=endpoint,
248
+ headers=headers,
249
+ token=token,
250
+ )
251
+
252
+ repo_info: ModelInfo | DatasetInfo | SpaceInfo | KernelInfo | None = None
253
+ api_call_error: Exception | None = None
254
+ if not local_files_only:
255
+ # try/except logic to handle different errors => taken from `hf_hub_download`
256
+ try:
257
+ # if we have internet connection we want to list files to download
258
+ repo_info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision)
259
+ except httpx.ProxyError:
260
+ # Actually raise on proxy error
261
+ raise
262
+ except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled) as error:
263
+ # Internet connection is down
264
+ # => will try to use local files only
265
+ api_call_error = error
266
+ pass
267
+ except RevisionNotFoundError:
268
+ # The repo was found but the revision doesn't exist on the Hub (never existed or got deleted)
269
+ raise
270
+ except HfHubHTTPError as error:
271
+ # Multiple reasons for an http error:
272
+ # - Repository is private and invalid/missing token sent
273
+ # - Repository is gated and invalid/missing token sent
274
+ # - Hub is down (error 500 or 504)
275
+ # => let's switch to 'local_files_only=True' to check if the files are already cached.
276
+ # (if it's not the case, the error will be re-raised)
277
+ api_call_error = error
278
+ pass
279
+
280
+ # At this stage, if `repo_info` is None it means either:
281
+ # - internet connection is down
282
+ # - internet connection is deactivated (local_files_only=True or HF_HUB_OFFLINE=True)
283
+ # - repo is private/gated and invalid/missing token sent
284
+ # - Hub is down
285
+ # => let's look if we can find the appropriate folder in the cache:
286
+ # - if the specified revision is a commit hash, look inside "snapshots".
287
+ # - f the specified revision is a branch or tag, look inside "refs".
288
+ # => if local_dir is not None, we will return the path to the local folder if it exists.
289
+ if repo_info is None:
290
+ if dry_run:
291
+ raise DryRunError(
292
+ "Dry run cannot be performed as the repository cannot be accessed. Please check your internet connection or authentication token."
293
+ ) from api_call_error
294
+
295
+ # Try to get which commit hash corresponds to the specified revision
296
+ commit_hash = None
297
+ if REGEX_COMMIT_HASH.match(revision):
298
+ commit_hash = revision
299
+ else:
300
+ ref_path = os.path.join(storage_folder, "refs", revision)
301
+ if os.path.exists(ref_path):
302
+ # retrieve commit_hash from refs file
303
+ with open(ref_path) as f:
304
+ commit_hash = f.read()
305
+
306
+ # Try to locate snapshot folder for this commit hash
307
+ if commit_hash is not None and local_dir is None:
308
+ snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
309
+ if os.path.exists(snapshot_folder):
310
+ # The folder exists, but may be partial (e.g. after an interrupted download): only return it
311
+ # if the cached tree listing confirms it is complete.
312
+ _raise_if_incomplete_snapshot(
313
+ tree_cache_folder=tree_cache_folder,
314
+ commit_hash=commit_hash,
315
+ base_dir=snapshot_folder,
316
+ allow_patterns=allow_patterns,
317
+ ignore_patterns=ignore_patterns,
318
+ repo_id=repo_id,
319
+ revision=revision,
320
+ api_call_error=api_call_error,
321
+ )
322
+ return snapshot_folder
323
+
324
+ # If local_dir is not None, return it if it exists and is complete
325
+ if local_dir is not None:
326
+ local_dir = Path(local_dir)
327
+ if local_dir.is_dir() and any(local_dir.iterdir()):
328
+ if commit_hash is not None:
329
+ _raise_if_incomplete_snapshot(
330
+ tree_cache_folder=tree_cache_folder,
331
+ commit_hash=commit_hash,
332
+ base_dir=str(local_dir),
333
+ allow_patterns=allow_patterns,
334
+ ignore_patterns=ignore_patterns,
335
+ repo_id=repo_id,
336
+ revision=revision,
337
+ api_call_error=api_call_error,
338
+ )
339
+ logger.warning(
340
+ f"Returning existing local_dir `{local_dir}` as remote repo cannot be accessed in `snapshot_download` ({api_call_error})."
341
+ )
342
+ return str(local_dir.resolve())
343
+ # If we couldn't find the appropriate folder on disk, raise an error.
344
+ if local_files_only:
345
+ raise LocalEntryNotFoundError(
346
+ "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
347
+ "outgoing traffic has been disabled. To enable repo look-ups and downloads online, pass "
348
+ "'local_files_only=False' as input."
349
+ )
350
+ elif isinstance(api_call_error, OfflineModeIsEnabled):
351
+ raise LocalEntryNotFoundError(
352
+ "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
353
+ "outgoing traffic has been disabled. To enable repo look-ups and downloads online, set "
354
+ "'HF_HUB_OFFLINE=0' as environment variable."
355
+ ) from api_call_error
356
+ elif isinstance(api_call_error, (RepositoryNotFoundError, GatedRepoError)) or (
357
+ isinstance(api_call_error, HfHubHTTPError) and api_call_error.response.status_code == 401
358
+ ):
359
+ # Repo not found, gated, or specific authentication error => let's raise the actual error
360
+ raise api_call_error
361
+ else:
362
+ # Otherwise: most likely a connection issue or Hub downtime => let's warn the user
363
+ raise LocalEntryNotFoundError(
364
+ f"Got: {api_call_error.__class__.__name__}: {api_call_error}"
365
+ "\nAn error happened while trying to locate the files on the Hub, and we cannot find the appropriate"
366
+ " snapshot folder for the specified revision on the local disk. Please check your internet connection"
367
+ " and try again."
368
+ ) from api_call_error
369
+
370
+ # At this stage, internet connection is up and running
371
+ # => let's download the files!
372
+ assert repo_info.sha is not None, "Repo info returned from server must have a revision sha."
373
+ commit_hash = repo_info.sha
374
+
375
+ # Retrieve /tree listing from cache or fetch it
376
+ tree_entries = read_tree_cache(tree_cache_folder, commit_hash)
377
+ if tree_entries is None:
378
+ tree_entries = {
379
+ f.path: TreeCacheEntry(
380
+ size=f.size,
381
+ blob_id=f.blob_id,
382
+ lfs_sha256=f.lfs.sha256 if f.lfs is not None else None,
383
+ lfs_size=f.lfs.size if f.lfs is not None else None,
384
+ xet_hash=f.xet_hash,
385
+ )
386
+ for f in api.list_repo_tree(repo_id=repo_id, recursive=True, revision=commit_hash, repo_type=repo_type)
387
+ if isinstance(f, RepoFile)
388
+ }
389
+ if not dry_run:
390
+ write_tree_cache(tree_cache_folder, commit_hash, tree_entries)
391
+
392
+ filtered_repo_files = list(
393
+ filter_repo_objects(
394
+ items=tree_entries.keys(),
395
+ allow_patterns=allow_patterns,
396
+ ignore_patterns=ignore_patterns,
397
+ )
398
+ )
399
+ tqdm_desc = f"Fetching {len(filtered_repo_files)} files"
400
+ if dry_run:
401
+ tqdm_desc = "[dry-run] " + tqdm_desc
402
+
403
+ snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
404
+ # if passed revision is not identical to commit_hash
405
+ # then revision has to be a branch name or tag name.
406
+ # In that case store a ref.
407
+ if revision != commit_hash:
408
+ ref_path = os.path.join(storage_folder, "refs", revision)
409
+ try:
410
+ os.makedirs(os.path.dirname(ref_path), exist_ok=True)
411
+ with open(ref_path, "w") as f:
412
+ f.write(commit_hash)
413
+ except OSError as e:
414
+ logger.warning(f"Ignored error while writing commit hash to {ref_path}: {e}.")
415
+
416
+ results: list[str | DryRunFileInfo] = []
417
+
418
+ # User can use its own tqdm class or the default one from `huggingface_hub.utils`
419
+ tqdm_class = tqdm_class or hf_tqdm
420
+
421
+ # Create progress bars for the bytes downloaded.
422
+ # Transfer bytes are received from the network; reconstruction bytes are written to disk.
423
+ transfer_progress = _create_progress_bar(
424
+ cls=tqdm_class,
425
+ log_level=logger.getEffectiveLevel(),
426
+ name="huggingface_hub.snapshot_download.transfer",
427
+ desc="Downloading bytes",
428
+ total=0,
429
+ initial=0,
430
+ unit="B",
431
+ unit_scale=True,
432
+ bar_format=XET_TRANSFER_BAR_FORMAT,
433
+ )
434
+
435
+ reconstruct_progress = _create_progress_bar(
436
+ cls=tqdm_class,
437
+ log_level=logger.getEffectiveLevel(),
438
+ name="huggingface_hub.snapshot_download",
439
+ desc="Reconstructing (incomplete total...)",
440
+ total=0,
441
+ initial=0,
442
+ unit="B",
443
+ unit_scale=True,
444
+ bar_format=XET_BYTES_BAR_FORMAT,
445
+ )
446
+
447
+ class _AggregatedTqdm:
448
+ """Fake tqdm object to aggregate progress into the parent snapshot progress bars.
449
+
450
+ In practice, the `_AggregatedTqdm` object won't be displayed; it's just used to update
451
+ the `reconstruct_progress` and `transfer_progress` bars from each thread/file download.
452
+ """
453
+
454
+ def __init__(self, *args, **kwargs):
455
+ # Adjust the total of the parent progress bar
456
+ total = kwargs.pop("total", None)
457
+ if total is not None:
458
+ reconstruct_progress.total = (reconstruct_progress.total or 0) + total
459
+ transfer_progress.total = (transfer_progress.total or 0) + total
460
+ reconstruct_progress.refresh()
461
+
462
+ # Adjust initial of the parent progress bar
463
+ initial = kwargs.pop("initial", 0)
464
+ if initial:
465
+ reconstruct_progress.update(initial)
466
+
467
+ def __enter__(self):
468
+ return self
469
+
470
+ def __exit__(self, exc_type, exc_value, traceback):
471
+ pass
472
+
473
+ def close(self) -> None:
474
+ pass
475
+
476
+ def update(self, n: int | float | None = 1) -> None:
477
+ reconstruct_progress.update(n)
478
+
479
+ def update_transfer(self, n: int | float | None = 1) -> None:
480
+ _update_transfer_bar(transfer_progress, int(n or 0))
481
+
482
+ def set_postfix_str(self, postfix: str, refresh: bool = False) -> None:
483
+ reconstruct_progress.set_postfix_str(postfix, refresh=refresh)
484
+
485
+ def set_transfer_postfix_str(self, postfix: str, refresh: bool = False) -> None:
486
+ transfer_progress.set_postfix_str(postfix, refresh=refresh)
487
+
488
+ # Pass the commit_hash as revision to hf_hub_download to skip network call if:
489
+ # - file is cached
490
+ # - or xet file with metadata cached in /tree cache
491
+ def _inner_hf_hub_download(repo_file: str) -> None:
492
+ results.append(
493
+ hf_hub_download( # type: ignore
494
+ repo_id,
495
+ filename=repo_file,
496
+ repo_type=repo_type,
497
+ revision=commit_hash,
498
+ endpoint=endpoint,
499
+ cache_dir=cache_dir,
500
+ local_dir=local_dir,
501
+ library_name=library_name,
502
+ library_version=library_version,
503
+ user_agent=user_agent,
504
+ etag_timeout=etag_timeout,
505
+ force_download=force_download,
506
+ token=token,
507
+ headers=headers,
508
+ tqdm_class=_AggregatedTqdm, # type: ignore
509
+ dry_run=dry_run,
510
+ )
511
+ )
512
+
513
+ thread_map(
514
+ _inner_hf_hub_download,
515
+ filtered_repo_files,
516
+ desc=tqdm_desc,
517
+ max_workers=max_workers,
518
+ tqdm_class=tqdm_class,
519
+ )
520
+
521
+ _finish_transfer_bar(transfer_progress)
522
+ transfer_progress.set_description("Download complete")
523
+ reconstruct_progress.set_description("Reconstruction complete")
524
+
525
+ if dry_run:
526
+ assert all(isinstance(r, DryRunFileInfo) for r in results)
527
+ return results # type: ignore
528
+
529
+ if local_dir is not None:
530
+ return str(os.path.realpath(local_dir))
531
+ return snapshot_folder
532
+
533
+
534
+ def _raise_if_incomplete_snapshot(
535
+ *,
536
+ tree_cache_folder: str,
537
+ commit_hash: str,
538
+ base_dir: str,
539
+ allow_patterns: list[str] | str | None,
540
+ ignore_patterns: list[str] | str | None,
541
+ repo_id: str,
542
+ revision: str,
543
+ api_call_error: Exception | None,
544
+ ) -> None:
545
+ """Raise [`IncompleteSnapshotError`] if the cached tree listing shows `base_dir` misses requested files.
546
+
547
+ If the tree listing is not cached we cannot tell, so we do nothing and the caller keeps returning the
548
+ folder as-is. Otherwise every expected file (after pattern filtering) must exist under `base_dir`.
549
+ """
550
+ tree_entries = read_tree_cache(tree_cache_folder, commit_hash)
551
+ if tree_entries is None:
552
+ return
553
+ expected = filter_repo_objects(
554
+ items=tree_entries.keys(), allow_patterns=allow_patterns, ignore_patterns=ignore_patterns
555
+ )
556
+ missing = [path for path in expected if not _local_file_exists(base_dir, path)]
557
+ if not missing:
558
+ return
559
+
560
+ sample = ", ".join(missing[:3])
561
+ if len(missing) > 3:
562
+ sample += f", ... ({len(missing) - 3} more)"
563
+ if api_call_error is not None:
564
+ reason = f"The Hub could not be reached ({api_call_error.__class__.__name__}: {api_call_error})."
565
+ else:
566
+ reason = "Outgoing traffic is disabled ('local_files_only=True')."
567
+ raise IncompleteSnapshotError(
568
+ f"The cached snapshot for '{repo_id}' (revision '{revision}', commit {commit_hash}) is incomplete: "
569
+ f"{len(missing)} file(s) are missing ({sample}). {reason} Re-run the download with network access "
570
+ "to complete the snapshot.",
571
+ snapshot_path=base_dir,
572
+ ) from api_call_error
573
+
574
+
575
+ @validate_hf_hub_args
576
+ def get_cached_repo_tree(
577
+ repo_id: str,
578
+ *,
579
+ repo_type: str | None = None,
580
+ revision: str | None = None,
581
+ cache_dir: str | Path | None = None,
582
+ local_dir: str | Path | None = None,
583
+ ) -> list[RepoFile]:
584
+ """Return the cached tree listing of a repo at a given revision, without any network call.
585
+
586
+ The tree listing is the set of files (with their download metadata) of a repo at a commit. It is populated
587
+ on disk as a side effect of [`snapshot_download`] (see the `trees/<commit_hash>.json` cache files) and is
588
+ used to skip network calls on subsequent downloads. This function exposes that cache directly.
589
+
590
+ If you need the current tree listing of a repo on the Hub, use [`list_repo_tree`] instead.
591
+
592
+ Args:
593
+ repo_id (`str`):
594
+ A user or an organization name and a repo name separated by a `/`.
595
+ repo_type (`str`, *optional*):
596
+ Set to `"dataset"`, `"space"` or `"kernel"` if listing from a dataset, space or kernel repo,
597
+ `None` or `"model"` if listing from a model. Default is `None`.
598
+ revision (`str`, *optional*):
599
+ An optional Git revision id, which can be a branch name, a tag, or a commit hash. Defaults to the
600
+ default branch. Branch/tag names are resolved to a commit hash using the local cache (`refs/`).
601
+ cache_dir (`str`, `Path`, *optional*):
602
+ Path to the folder where cached files are stored. Defaults to the value of `HF_HUB_CACHE`.
603
+ local_dir (`str` or `Path`, *optional*):
604
+ If provided, read the tree listing cached by a `local_dir` download (from
605
+ `local_dir/.cache/huggingface/`) instead of the main cache. Branch/tag revisions are still resolved
606
+ to a commit hash using the main cache (`cache_dir`).
607
+
608
+ Returns:
609
+ `list[RepoFile]`: The list of [`RepoFile`] objects cached for this revision.
610
+
611
+ Raises:
612
+ [`~errors.CachedRepoTreeNotFoundError`]
613
+ If no tree listing is cached for the requested revision (e.g. the repo was never downloaded at this revision).
614
+
615
+ Example:
616
+ ```py
617
+ >>> from huggingface_hub import get_cached_repo_tree
618
+ >>> files = get_cached_repo_tree("openai-community/gpt2")
619
+ >>> [f.path for f in files]
620
+ ['.gitattributes', 'config.json', 'model.safetensors', ...]
621
+ ```
622
+ """
623
+ if cache_dir is None:
624
+ cache_dir = constants.HF_HUB_CACHE
625
+ cache_dir = str(Path(cache_dir).expanduser().resolve())
626
+ if local_dir is not None:
627
+ local_dir = str(Path(local_dir).expanduser().resolve())
628
+ if revision is None:
629
+ revision = constants.DEFAULT_REVISION
630
+ if repo_type is None:
631
+ repo_type = constants.REPO_TYPE_MODEL
632
+ if repo_type not in constants.REPO_TYPES_WITH_KERNEL:
633
+ raise ValueError(
634
+ f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES_WITH_KERNEL)}"
635
+ )
636
+
637
+ storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
638
+
639
+ # For `local_dir` downloads the tree listing lives under `local_dir/.cache/huggingface/`; otherwise it lives
640
+ # in the per-repo `storage_folder`. Refs are always recorded in the main cache, so we resolve them there.
641
+ tree_cache_folder = tree_cache_folder_for_local_dir(local_dir) if local_dir is not None else storage_folder
642
+
643
+ # The tree cache is keyed by commit hash. Resolve the revision to a commit hash: either it already is one,
644
+ # or it's a branch/tag name recorded in `refs/` by a previous download.
645
+ if REGEX_COMMIT_HASH.match(revision):
646
+ commit_hash = revision
647
+ else:
648
+ ref_path = os.path.join(storage_folder, "refs", revision)
649
+ if not os.path.isfile(ref_path):
650
+ raise CachedRepoTreeNotFoundError(
651
+ f"No cached tree listing found for '{repo_id}' (revision '{revision}', repo_type '{repo_type}'): "
652
+ f"the revision is not a commit hash and no matching ref is cached in '{storage_folder}'. "
653
+ "Download the repo (e.g. with `snapshot_download`) to populate the cache first."
654
+ )
655
+ with open(ref_path) as f:
656
+ commit_hash = f.read()
657
+
658
+ tree_entries = read_tree_cache(tree_cache_folder, commit_hash)
659
+ if tree_entries is None:
660
+ raise CachedRepoTreeNotFoundError(
661
+ f"No cached tree listing found for '{repo_id}' (revision '{revision}', commit '{commit_hash}', "
662
+ f"repo_type '{repo_type}') in '{tree_cache_folder}'. Download the repo (e.g. with `snapshot_download`) "
663
+ "to populate the cache first."
664
+ )
665
+
666
+ return [
667
+ RepoFile(path=path, size=entry.size, oid=entry.blob_id, xetHash=entry.xet_hash)
668
+ for path, entry in tree_entries.items()
669
+ ]
670
+
671
+
672
+ def _local_file_exists(base_dir: str, path: str) -> bool:
673
+ """Check whether a repo file (path relative to `base_dir`, '/'-separated) exists on disk.
674
+
675
+ On Windows, paths longer than 255 characters must be prefixed with `\\\\?\\`, otherwise `os.path.isfile` reports an
676
+ existing file as missing.
677
+ """
678
+ full_path = os.path.join(base_dir, *path.split("/"))
679
+ if os.name == "nt" and len(os.path.abspath(full_path)) > 255 and not full_path.startswith("\\\\?\\"):
680
+ full_path = "\\\\?\\" + os.path.abspath(full_path)
681
+ return os.path.isfile(full_path)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_space_api.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from datetime import datetime
16
+ from enum import Enum
17
+ from typing import Literal
18
+
19
+ from huggingface_hub.utils import HfMount, HfUri, parse_datetime
20
+
21
+
22
+ class SpaceStage(str, Enum):
23
+ """
24
+ Enumeration of possible stage of a Space on the Hub.
25
+
26
+ Value can be compared to a string:
27
+ ```py
28
+ assert SpaceStage.BUILDING == "BUILDING"
29
+ ```
30
+
31
+ Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L61 (private url).
32
+ """
33
+
34
+ # Copied from moon-landing > server > repo_types > SpaceInfo.ts (private repo)
35
+ NO_APP_FILE = "NO_APP_FILE"
36
+ CONFIG_ERROR = "CONFIG_ERROR"
37
+ BUILDING = "BUILDING"
38
+ BUILD_ERROR = "BUILD_ERROR"
39
+ RUNNING = "RUNNING"
40
+ RUNNING_BUILDING = "RUNNING_BUILDING"
41
+ RUNTIME_ERROR = "RUNTIME_ERROR"
42
+ DELETING = "DELETING"
43
+ STOPPED = "STOPPED"
44
+ PAUSED = "PAUSED"
45
+ APP_STARTING = "APP_STARTING"
46
+ RUNNING_APP_STARTING = "RUNNING_APP_STARTING"
47
+
48
+
49
+ INTERMEDIATE_SPACE_STAGES = (
50
+ SpaceStage.BUILDING,
51
+ SpaceStage.RUNNING_BUILDING,
52
+ SpaceStage.APP_STARTING,
53
+ SpaceStage.RUNNING_APP_STARTING,
54
+ )
55
+
56
+ TERMINAL_SPACE_STAGES = (
57
+ SpaceStage.RUNNING,
58
+ SpaceStage.BUILD_ERROR,
59
+ SpaceStage.RUNTIME_ERROR,
60
+ SpaceStage.CONFIG_ERROR,
61
+ SpaceStage.NO_APP_FILE,
62
+ SpaceStage.STOPPED,
63
+ SpaceStage.PAUSED,
64
+ SpaceStage.DELETING,
65
+ )
66
+
67
+
68
+ class SpaceHardware(str, Enum):
69
+ """
70
+ Enumeration of hardwares available to run your Space on the Hub.
71
+
72
+ Value can be compared to a string:
73
+ ```py
74
+ assert SpaceHardware.CPU_BASIC == "cpu-basic"
75
+ ```
76
+
77
+ Taken from https://github.com/huggingface-internal/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts (private url).
78
+ """
79
+
80
+ # CPU
81
+ CPU_BASIC = "cpu-basic"
82
+ CPU_UPGRADE = "cpu-upgrade"
83
+
84
+ # ZeroGPU
85
+ ZERO_A10G = "zero-a10g"
86
+
87
+ # GPU
88
+ T4_SMALL = "t4-small"
89
+ T4_MEDIUM = "t4-medium"
90
+ L4X1 = "l4x1"
91
+ L4X4 = "l4x4"
92
+ L40SX1 = "l40sx1"
93
+ L40SX4 = "l40sx4"
94
+ L40SX8 = "l40sx8"
95
+ A10G_SMALL = "a10g-small"
96
+ A10G_LARGE = "a10g-large"
97
+ A10G_LARGEX2 = "a10g-largex2"
98
+ A10G_LARGEX4 = "a10g-largex4"
99
+ A100_LARGE = "a100-large"
100
+ A100X4 = "a100x4"
101
+ A100X8 = "a100x8"
102
+
103
+
104
+ class SpaceStorage(str, Enum):
105
+ """
106
+ Enumeration of persistent storage available for your Space on the Hub.
107
+
108
+ Value can be compared to a string:
109
+ ```py
110
+ assert SpaceStorage.SMALL == "small"
111
+ ```
112
+
113
+ Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts#L24 (private url).
114
+ """
115
+
116
+ SMALL = "small"
117
+ MEDIUM = "medium"
118
+ LARGE = "large"
119
+
120
+
121
+ @dataclass
122
+ class Volume:
123
+ """
124
+ Describes a volume to mount in a Space or Job container.
125
+
126
+ Args:
127
+ type (`str`):
128
+ Type of volume: `"bucket"`, `"model"`, `"dataset"`, or `"space"`.
129
+ source (`str`):
130
+ Source identifier, e.g. `"username/my-bucket"` or `"username/my-model"`.
131
+ mount_path (`str`):
132
+ Mount path inside the container, e.g. `"/data"`. Must start with `/`.
133
+ revision (`str` or `None`):
134
+ Git revision (only for repos, defaults to `"main"`).
135
+ read_only (`bool` or `None`):
136
+ Read-only mount. Forced `True` for repos, defaults to `False` for buckets.
137
+ path (`str` or `None`):
138
+ Subfolder prefix inside the bucket/repo to mount, e.g. `"path/to/dir"`.
139
+ """
140
+
141
+ type: Literal["bucket", "model", "dataset", "space"]
142
+ source: str
143
+ mount_path: str
144
+ revision: str | None = None
145
+ read_only: bool | None = None
146
+ path: str | None = None
147
+
148
+ def __init__(self, **kwargs) -> None:
149
+ self.type = kwargs.get("type", "model")
150
+ self.source = kwargs["source"]
151
+ mount_path = kwargs.get("mountPath")
152
+ self.mount_path = mount_path if mount_path is not None else kwargs["mount_path"]
153
+ self.revision = kwargs.get("revision")
154
+ read_only = kwargs.get("readOnly")
155
+ self.read_only = read_only if read_only is not None else kwargs.get("read_only")
156
+ self.path = kwargs.get("path")
157
+
158
+ def to_dict(self) -> dict:
159
+ """Serialize to the JSON payload expected by the Hub API."""
160
+ data: dict = {
161
+ "type": self.type,
162
+ "source": self.source,
163
+ "mountPath": self.mount_path,
164
+ }
165
+ if self.revision is not None:
166
+ data["revision"] = self.revision
167
+ if self.read_only is not None:
168
+ data["readOnly"] = self.read_only
169
+ if self.path is not None:
170
+ data["path"] = self.path
171
+ return data
172
+
173
+ def to_uri(self) -> str:
174
+ """Return the volume as an HF mount URI in the format expected by the CLI."""
175
+ return HfMount(
176
+ source=HfUri(type=self.type, id=self.source, revision=self.revision, path_in_repo=self.path or ""),
177
+ mount_path=self.mount_path,
178
+ read_only=self.read_only,
179
+ ).to_uri()
180
+
181
+
182
+ @dataclass
183
+ class SpaceHotReloading:
184
+ status: Literal["created", "canceled"]
185
+ replica_statuses: list[tuple[str, str | None]] # See _hot_reloading_types.ApiCreateReloadResponse.res.status
186
+ raw: dict
187
+
188
+ def __init__(self, data: dict) -> None:
189
+ self.status = data["status"]
190
+ self.replica_statuses = data["replicaStatuses"]
191
+ self.raw = data
192
+
193
+
194
+ @dataclass
195
+ class SpaceRuntime:
196
+ """
197
+ Contains information about the current runtime of a Space.
198
+
199
+ Args:
200
+ stage (`str`):
201
+ Current stage of the space. Example: RUNNING.
202
+ hardware (`str` or `None`):
203
+ Current hardware of the space. Example: "cpu-basic". Can be `None` if Space
204
+ is `BUILDING` for the first time.
205
+ requested_hardware (`str` or `None`):
206
+ Requested hardware. Can be different from `hardware` especially if the request
207
+ has just been made. Example: "t4-medium". Can be `None` if no hardware has
208
+ been requested yet.
209
+ sleep_time (`int` or `None`):
210
+ Number of seconds the Space will be kept alive after the last request. By default (if value is `None`), the
211
+ Space will never go to sleep if it's running on an upgraded hardware, while it will go to sleep after 48
212
+ hours on a free 'cpu-basic' hardware. For more details, see https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
213
+ volumes (`list[Volume]` or `None`):
214
+ List of volumes mounted in the Space. Each volume is a [`Volume`] object describing its type, source,
215
+ mount path, and optional settings. `None` if no volumes are attached.
216
+ raw (`dict`):
217
+ Raw response from the server. Contains more information about the Space
218
+ runtime like number of replicas, number of cpu, memory size,...
219
+ """
220
+
221
+ stage: SpaceStage
222
+ hardware: SpaceHardware | None
223
+ requested_hardware: SpaceHardware | None
224
+ sleep_time: int | None
225
+ storage: SpaceStorage | None
226
+ dev_mode: bool
227
+ hot_reloading: SpaceHotReloading | None
228
+ volumes: list[Volume] | None
229
+ raw: dict
230
+
231
+ def __init__(self, data: dict) -> None:
232
+ self.stage = data["stage"]
233
+ self.hardware = data.get("hardware", {}).get("current")
234
+ self.requested_hardware = data.get("hardware", {}).get("requested")
235
+ self.sleep_time = data.get("gcTimeout")
236
+ self.storage = data.get("storage")
237
+ self.dev_mode = data.get("devMode", False)
238
+ self.hot_reloading = SpaceHotReloading(raw_hr) if (raw_hr := data.get("hotReloading")) is not None else None
239
+ raw_volumes = data.get("volumes")
240
+ self.volumes = [Volume(**v) for v in raw_volumes] if raw_volumes is not None else None
241
+ self.raw = data
242
+
243
+
244
+ @dataclass
245
+ class SpaceSecret:
246
+ """
247
+ Contains information about a secret of a Space.
248
+
249
+ Secret values are write-only and cannot be read back. Only the key, description,
250
+ and last update time are returned by the API.
251
+
252
+ Args:
253
+ key (`str`):
254
+ Secret key. Example: `"GITHUB_API_KEY"`
255
+ description (`str` or None):
256
+ Description of the secret. Example: `"Github API key to access the Github API"`.
257
+ updated_at (`datetime` or None):
258
+ datetime of the last update of the secret (if the secret has been updated at least once).
259
+ """
260
+
261
+ key: str
262
+ description: str | None
263
+ updated_at: datetime | None
264
+
265
+ def __init__(self, key: str, values: dict) -> None:
266
+ self.key = key
267
+ self.description = values.get("description")
268
+ updated_at = values.get("updatedAt")
269
+ self.updated_at = parse_datetime(updated_at) if updated_at is not None else None
270
+
271
+
272
+ @dataclass
273
+ class SpaceVariable:
274
+ """
275
+ Contains information about the current variables of a Space.
276
+
277
+ Args:
278
+ key (`str`):
279
+ Variable key. Example: `"MODEL_REPO_ID"`
280
+ value (`str`):
281
+ Variable value. Example: `"the_model_repo_id"`.
282
+ description (`str` or None):
283
+ Description of the variable. Example: `"Model Repo ID of the implemented model"`.
284
+ updatedAt (`datetime` or None):
285
+ datetime of the last update of the variable (if the variable has been updated at least once).
286
+ """
287
+
288
+ key: str
289
+ value: str
290
+ description: str | None
291
+ updated_at: datetime | None
292
+
293
+ def __init__(self, key: str, values: dict) -> None:
294
+ self.key = key
295
+ self.value = values["value"]
296
+ self.description = values.get("description")
297
+ updated_at = values.get("updatedAt")
298
+ self.updated_at = parse_datetime(updated_at) if updated_at is not None else None
299
+
300
+
301
+ @dataclass
302
+ class SpaceSearchResult:
303
+ """A single result from the Spaces semantic search API.
304
+
305
+ Returned by [`HfApi.search_spaces`].
306
+
307
+ Attributes:
308
+ id (`str`):
309
+ ID of the Space (e.g. `"username/repo-name"`).
310
+ author (`str`):
311
+ Author of the Space.
312
+ title (`str`):
313
+ Display title of the Space.
314
+ emoji (`str` or `None`):
315
+ Emoji icon of the Space.
316
+ sdk (`str` or `None`):
317
+ SDK used by the Space (e.g. `"gradio"`, `"docker"`, `"static"`).
318
+ likes (`int`):
319
+ Number of likes.
320
+ private (`bool`):
321
+ Whether the Space is private.
322
+ tags (`list[str]` or `None`):
323
+ List of tags.
324
+ runtime ([`SpaceRuntime`] or `None`):
325
+ Runtime information (stage, hardware, etc.).
326
+ ai_short_description (`str` or `None`):
327
+ AI-generated short description.
328
+ ai_category (`str` or `None`):
329
+ AI-generated category (e.g. `"Image Generation"`).
330
+ semantic_relevancy_score (`float` or `None`):
331
+ Semantic relevancy score (0-1) relative to the search query.
332
+ trending_score (`int` or `None`):
333
+ Trending score.
334
+ """
335
+
336
+ id: str
337
+ author: str
338
+ title: str
339
+ emoji: str | None
340
+ sdk: str | None
341
+ likes: int
342
+ private: bool
343
+ tags: list[str] | None
344
+ runtime: SpaceRuntime | None
345
+ ai_short_description: str | None
346
+ ai_category: str | None
347
+ semantic_relevancy_score: float | None
348
+ trending_score: int | None
349
+
350
+ def __init__(self, data: dict) -> None:
351
+ runtime = data.get("runtime")
352
+ self.id = data["id"]
353
+ self.author = data.get("author", "")
354
+ self.title = data.get("title", "")
355
+ self.emoji = data.get("emoji")
356
+ self.sdk = data.get("sdk")
357
+ self.likes = data.get("likes", 0)
358
+ self.private = data.get("private", False)
359
+ self.tags = data.get("tags")
360
+ self.runtime = SpaceRuntime(runtime) if runtime else None
361
+ self.ai_short_description = data.get("ai_short_description")
362
+ self.ai_category = data.get("ai_category")
363
+ self.semantic_relevancy_score = data.get("semanticRelevancyScore")
364
+ self.trending_score = data.get("trendingScore")
365
+
366
+
367
+ @dataclass
368
+ class SpaceTemplate:
369
+ """
370
+ Contains information about a Space template available on the Hub.
371
+
372
+ Returned by [`HfApi.list_space_templates`]. The `repo_id` can be passed as `space_template`
373
+ to [`HfApi.create_repo`] to seed a new Space from that template.
374
+
375
+ Args:
376
+ name (`str`):
377
+ Human-friendly name of the template (e.g. `"JupyterLab"`, `"chatbot"`).
378
+ repo_id (`str`):
379
+ Repo id of the template Space (e.g. `"SpacesExamples/jupyterlab"`).
380
+ sdk (`str`):
381
+ SDK the template is built with (e.g. `"gradio"`, `"docker"`, `"static"`).
382
+ preferred_private (`bool`):
383
+ Whether Spaces created from this template are recommended to be private.
384
+ """
385
+
386
+ name: str
387
+ repo_id: str
388
+ sdk: str
389
+ preferred_private: bool
390
+
391
+ def __init__(self, data: dict) -> None:
392
+ self.name = data["name"]
393
+ self.repo_id = data["repoId"]
394
+ self.sdk = data["sdk"]
395
+ self.preferred_private = data["preferredPrivate"]
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_tensorboard_logger.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains a logger to push training logs to the Hub, using Tensorboard."""
15
+
16
+ from pathlib import Path
17
+
18
+ from ._commit_scheduler import CommitScheduler
19
+ from .errors import EntryNotFoundError
20
+ from .repocard import ModelCard
21
+ from .utils import experimental
22
+
23
+
24
+ # Depending on user's setup, SummaryWriter can come either from 'tensorboardX'
25
+ # or from 'torch.utils.tensorboard'. Both are compatible so let's try to load
26
+ # from either of them.
27
+ try:
28
+ from tensorboardX import SummaryWriter as _RuntimeSummaryWriter
29
+
30
+ is_summary_writer_available = True
31
+ except ImportError:
32
+ try:
33
+ from torch.utils.tensorboard import SummaryWriter as _RuntimeSummaryWriter
34
+
35
+ is_summary_writer_available = True
36
+ except ImportError:
37
+ # Dummy class to avoid failing at import. Will raise on instance creation.
38
+ class _DummySummaryWriter:
39
+ pass
40
+
41
+ _RuntimeSummaryWriter = _DummySummaryWriter # type: ignore[assignment] # ty: ignore[conflicting-declarations]
42
+ is_summary_writer_available = False
43
+
44
+
45
+ class HFSummaryWriter(_RuntimeSummaryWriter):
46
+ """
47
+ Wrapper around the tensorboard's `SummaryWriter` to push training logs to the Hub.
48
+
49
+ Data is logged locally and then pushed to the Hub asynchronously. Pushing data to the Hub is done in a separate
50
+ thread to avoid blocking the training script. In particular, if the upload fails for any reason (e.g. a connection
51
+ issue), the main script will not be interrupted. Data is automatically pushed to the Hub every `commit_every`
52
+ minutes (default to every 5 minutes).
53
+
54
+ > [!WARNING]
55
+ > `HFSummaryWriter` is experimental. Its API is subject to change in the future without prior notice.
56
+
57
+ Args:
58
+ repo_id (`str`):
59
+ The id of the repo to which the logs will be pushed.
60
+ logdir (`str`, *optional*):
61
+ The directory where the logs will be written. If not specified, a local directory will be created by the
62
+ underlying `SummaryWriter` object.
63
+ commit_every (`int` or `float`, *optional*):
64
+ The frequency (in minutes) at which the logs will be pushed to the Hub. Defaults to 5 minutes.
65
+ squash_history (`bool`, *optional*):
66
+ Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
67
+ useful to avoid degraded performances on the repo when it grows too large.
68
+ repo_type (`str`, *optional*):
69
+ The type of the repo to which the logs will be pushed. Defaults to "model".
70
+ repo_revision (`str`, *optional*):
71
+ The revision of the repo to which the logs will be pushed. Defaults to "main".
72
+ repo_private (`bool`, *optional*):
73
+ Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
74
+ path_in_repo (`str`, *optional*):
75
+ The path to the folder in the repo where the logs will be pushed. Defaults to "tensorboard/".
76
+ repo_allow_patterns (`list[str]` or `str`, *optional*):
77
+ A list of patterns to include in the upload. Defaults to `"*.tfevents.*"`. Check out the
78
+ [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
79
+ repo_ignore_patterns (`list[str]` or `str`, *optional*):
80
+ A list of patterns to exclude in the upload. Check out the
81
+ [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
82
+ token (`str`, *optional*):
83
+ Authentication token. Will default to the stored token. See https://huggingface.co/settings/token for more
84
+ details
85
+ kwargs:
86
+ Additional keyword arguments passed to `SummaryWriter`.
87
+
88
+ Examples:
89
+ ```diff
90
+ # Taken from https://pytorch.org/docs/stable/tensorboard.html
91
+ - from torch.utils.tensorboard import SummaryWriter
92
+ + from huggingface_hub import HFSummaryWriter
93
+
94
+ import numpy as np
95
+
96
+ - writer = SummaryWriter()
97
+ + writer = HFSummaryWriter(repo_id="username/my-trained-model")
98
+
99
+ for n_iter in range(100):
100
+ writer.add_scalar('Loss/train', np.random.random(), n_iter)
101
+ writer.add_scalar('Loss/test', np.random.random(), n_iter)
102
+ writer.add_scalar('Accuracy/train', np.random.random(), n_iter)
103
+ writer.add_scalar('Accuracy/test', np.random.random(), n_iter)
104
+ ```
105
+
106
+ ```py
107
+ >>> from huggingface_hub import HFSummaryWriter
108
+
109
+ # Logs are automatically pushed every 15 minutes (5 by default) + when exiting the context manager
110
+ >>> with HFSummaryWriter(repo_id="test_hf_logger", commit_every=15) as logger:
111
+ ... logger.add_scalar("a", 1)
112
+ ... logger.add_scalar("b", 2)
113
+ ```
114
+ """
115
+
116
+ @experimental
117
+ def __new__(cls, *args, **kwargs) -> "HFSummaryWriter":
118
+ if not is_summary_writer_available:
119
+ raise ImportError(
120
+ "You must have `tensorboard` installed to use `HFSummaryWriter`. Please run `pip install --upgrade"
121
+ " tensorboardX` first."
122
+ )
123
+ return super().__new__(cls)
124
+
125
+ def __init__(
126
+ self,
127
+ repo_id: str,
128
+ *,
129
+ logdir: str | None = None,
130
+ commit_every: int | float = 5,
131
+ squash_history: bool = False,
132
+ repo_type: str | None = None,
133
+ repo_revision: str | None = None,
134
+ repo_private: bool | None = None,
135
+ path_in_repo: str | None = "tensorboard",
136
+ repo_allow_patterns: list[str] | str | None = "*.tfevents.*",
137
+ repo_ignore_patterns: list[str] | str | None = None,
138
+ token: str | None = None,
139
+ **kwargs,
140
+ ):
141
+ # Initialize SummaryWriter
142
+ super().__init__(logdir=logdir, **kwargs)
143
+
144
+ # Check logdir has been correctly initialized and fail early otherwise. In practice, SummaryWriter takes care of it.
145
+ if not isinstance(self.logdir, str):
146
+ raise ValueError(f"`self.logdir` must be a string. Got '{self.logdir}' of type {type(self.logdir)}.")
147
+
148
+ # Append logdir name to `path_in_repo`
149
+ if path_in_repo is None or path_in_repo == "":
150
+ path_in_repo = Path(self.logdir).name
151
+ else:
152
+ path_in_repo = path_in_repo.strip("/") + "/" + Path(self.logdir).name
153
+
154
+ # Initialize scheduler
155
+ self.scheduler = CommitScheduler(
156
+ folder_path=self.logdir,
157
+ path_in_repo=path_in_repo,
158
+ repo_id=repo_id,
159
+ repo_type=repo_type,
160
+ revision=repo_revision,
161
+ private=repo_private,
162
+ token=token,
163
+ allow_patterns=repo_allow_patterns,
164
+ ignore_patterns=repo_ignore_patterns,
165
+ every=commit_every,
166
+ squash_history=squash_history,
167
+ )
168
+
169
+ # Exposing some high-level info at root level
170
+ self.repo_id = self.scheduler.repo_id
171
+ self.repo_type = self.scheduler.repo_type
172
+ self.repo_revision = self.scheduler.revision
173
+
174
+ # Add `hf-summary-writer` tag to the model card metadata
175
+ try:
176
+ card = ModelCard.load(repo_id_or_path=self.repo_id, repo_type=self.repo_type)
177
+ except EntryNotFoundError:
178
+ card = ModelCard("")
179
+ tags = card.data.get("tags", [])
180
+ if "hf-summary-writer" not in tags:
181
+ tags.append("hf-summary-writer")
182
+ card.data["tags"] = tags
183
+ card.push_to_hub(repo_id=self.repo_id, repo_type=self.repo_type)
184
+
185
+ def __exit__(self, exc_type, exc_val, exc_tb):
186
+ """Push to hub in a non-blocking way when exiting the logger's context manager."""
187
+ super().__exit__(exc_type, exc_val, exc_tb)
188
+ future = self.scheduler.trigger()
189
+ future.result()
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_tree_cache.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """On-disk cache for repository tree listings.
15
+
16
+ A tree listing is the set of files (with their download metadata) contained in a repo at a given commit. Because a
17
+ commit hash is immutable, its tree listing never changes and can be cached forever without any invalidation logic.
18
+
19
+ The listing is stored as a human-readable JSON file under `<tree_cache_folder>/trees/<commit_hash>.json`. The
20
+ folder depends on the download target: the per-repo `storage_folder` for `cache_dir` downloads, or
21
+ `local_dir/.cache/huggingface/` for `local_dir` downloads (see `tree_cache_folder_for_local_dir`).
22
+
23
+ ```json
24
+ {
25
+ "format_version": 1,
26
+ "files": {
27
+ "config.json": {"size": 519, "blob_id": "<git sha1>"},
28
+ "model.safetensors": {"size": 1234, "blob_id": "...", "lfs_sha256": "<sha256>", "lfs_size": 1234, "xet_hash": "..."}
29
+ }
30
+ }
31
+ ```
32
+ """
33
+
34
+ import json
35
+ import os
36
+ import tempfile
37
+ import threading
38
+ from dataclasses import dataclass
39
+
40
+ from .utils import logging
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+ TREE_CACHE_FORMAT_VERSION = 1
46
+
47
+ # In-memory cache of parsed tree listings, keyed by absolute file path.
48
+ _IN_MEMORY_TREE_CACHE: dict[str, "dict[str, TreeCacheEntry]"] = {}
49
+ _IN_MEMORY_TREE_CACHE_LOCK = threading.Lock()
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class TreeCacheEntry:
54
+ """Raw metadata of a single file in a cached tree listing, mirroring the `/tree` endpoint fields."""
55
+
56
+ size: int
57
+ blob_id: str
58
+ lfs_sha256: str | None = None
59
+ lfs_size: int | None = None
60
+ xet_hash: str | None = None
61
+
62
+ def to_json(self) -> dict:
63
+ info: dict = {"size": self.size, "blob_id": self.blob_id}
64
+ if self.lfs_sha256 is not None:
65
+ info["lfs_sha256"] = self.lfs_sha256
66
+ info["lfs_size"] = self.lfs_size
67
+ if self.xet_hash is not None:
68
+ info["xet_hash"] = self.xet_hash
69
+ return info
70
+
71
+ @classmethod
72
+ def from_json(cls, info: dict) -> "TreeCacheEntry":
73
+ return cls(
74
+ size=info["size"],
75
+ blob_id=info["blob_id"],
76
+ lfs_sha256=info.get("lfs_sha256"),
77
+ lfs_size=info.get("lfs_size"),
78
+ xet_hash=info.get("xet_hash"),
79
+ )
80
+
81
+
82
+ def _tree_cache_path(tree_cache_folder: str, commit_hash: str) -> str:
83
+ return os.path.join(tree_cache_folder, "trees", f"{commit_hash}.json")
84
+
85
+
86
+ def tree_cache_folder_for_local_dir(local_dir: str) -> str:
87
+ """Folder under which the `trees/` cache lives for a `local_dir` download."""
88
+ return os.path.join(local_dir, ".cache", "huggingface")
89
+
90
+
91
+ def read_tree_cache(tree_cache_folder: str, commit_hash: str) -> dict[str, TreeCacheEntry] | None:
92
+ """Return the cached tree listing for a commit hash, or `None` if not cached (or unreadable)."""
93
+ path = _tree_cache_path(tree_cache_folder, commit_hash)
94
+ with _IN_MEMORY_TREE_CACHE_LOCK:
95
+ if path in _IN_MEMORY_TREE_CACHE:
96
+ return _IN_MEMORY_TREE_CACHE[path]
97
+ entries = _read_tree_cache_from_disk(path)
98
+ if entries is not None:
99
+ with _IN_MEMORY_TREE_CACHE_LOCK:
100
+ _IN_MEMORY_TREE_CACHE[path] = entries
101
+ return entries
102
+
103
+
104
+ def _read_tree_cache_from_disk(path: str) -> dict[str, TreeCacheEntry] | None:
105
+ try:
106
+ with open(path, encoding="utf-8") as f:
107
+ data = json.load(f)
108
+ if data.get("format_version") != TREE_CACHE_FORMAT_VERSION:
109
+ # Unknown format (e.g. written by a newer version) => ignore and re-fetch.
110
+ return None
111
+ return {file_path: TreeCacheEntry.from_json(info) for file_path, info in data["files"].items()}
112
+ except FileNotFoundError:
113
+ return None
114
+ except (OSError, ValueError, KeyError, TypeError) as e:
115
+ logger.warning(f"Ignoring corrupted tree cache file {path}: {e}")
116
+ return None
117
+
118
+
119
+ def write_tree_cache(tree_cache_folder: str, commit_hash: str, entries: dict[str, TreeCacheEntry]) -> None:
120
+ """Write the tree listing of a commit hash to the cache (ignoring any failures)."""
121
+ path = _tree_cache_path(tree_cache_folder, commit_hash)
122
+ data = {
123
+ "format_version": TREE_CACHE_FORMAT_VERSION,
124
+ "files": {file_path: entries[file_path].to_json() for file_path in sorted(entries)},
125
+ }
126
+ try:
127
+ os.makedirs(os.path.dirname(path), exist_ok=True)
128
+ tmp_fd, tmp_path = tempfile.mkstemp(dir=os.path.dirname(path), suffix=".tmp")
129
+ with os.fdopen(tmp_fd, "w", encoding="utf-8") as f:
130
+ json.dump(data, f, indent=1)
131
+ os.replace(tmp_path, path)
132
+ except OSError as e:
133
+ logger.warning(f"Ignored error while writing tree cache file {path}: {e}")
134
+ return
135
+
136
+ # Seed the in-memory cache so later readers of this commit skip re-reading and re-parsing the file.
137
+ with _IN_MEMORY_TREE_CACHE_LOCK:
138
+ _IN_MEMORY_TREE_CACHE[path] = dict(entries)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_upload_large_folder.py ADDED
@@ -0,0 +1,769 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import enum
15
+ import logging
16
+ import os
17
+ import queue
18
+ import shutil
19
+ import sys
20
+ import threading
21
+ import time
22
+ import traceback
23
+ from datetime import datetime
24
+ from pathlib import Path
25
+ from threading import Lock
26
+ from typing import TYPE_CHECKING, Any
27
+ from urllib.parse import quote
28
+
29
+ from ._commit_api import CommitOperationAdd, UploadInfo, _fetch_upload_modes
30
+ from ._local_folder import LocalUploadFileMetadata, LocalUploadFilePaths, get_local_upload_paths, read_upload_metadata
31
+ from .constants import DEFAULT_REVISION, REPO_TYPES
32
+ from .utils import DEFAULT_IGNORE_PATTERNS, _format_size, filter_repo_objects, tqdm
33
+ from .utils._runtime import is_xet_available
34
+ from .utils.sha import sha_fileobj
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ from .hf_api import HfApi
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ WAITING_TIME_IF_NO_TASKS = 10 # seconds
43
+ MAX_NB_FILES_FETCH_UPLOAD_MODE = 100
44
+ COMMIT_SIZE_SCALE: list[int] = [20, 50, 75, 100, 125, 200, 250, 400, 600, 1000]
45
+
46
+ UPLOAD_BATCH_SIZE_XET = 256 # Max 256 files per upload batch for XET-enabled repos
47
+ UPLOAD_BATCH_SIZE_LFS = 1 # Otherwise, batches of 1 for regular LFS upload
48
+
49
+ # Repository limits (from https://huggingface.co/docs/hub/repositories-recommendations)
50
+ MAX_FILES_PER_REPO = 100_000 # Recommended maximum number of files per repository
51
+ MAX_FILES_PER_FOLDER = 10_000 # Recommended maximum number of files per folder
52
+ MAX_FILE_SIZE_GB = 200 # Recommended maximum for individual file size (split larger files)
53
+ RECOMMENDED_FILE_SIZE_GB = 20 # Recommended maximum for individual file size
54
+
55
+
56
+ def _validate_upload_limits(paths_list: list[LocalUploadFilePaths]) -> None:
57
+ """
58
+ Validate upload against repository limits and warn about potential issues.
59
+
60
+ Args:
61
+ paths_list: List of file paths to be uploaded
62
+
63
+ Warns about:
64
+ - Too many files in the repository (>100k)
65
+ - Too many entries (files or subdirectories) in a single folder (>10k)
66
+ - Files exceeding size limits (>20GB recommended, >200GB maximum)
67
+ """
68
+ logger.info("Running validation checks on files to upload...")
69
+
70
+ # Check 1: Total file count
71
+ if len(paths_list) > MAX_FILES_PER_REPO:
72
+ logger.warning(
73
+ f"You are about to upload {len(paths_list):,} files. "
74
+ f"This exceeds the recommended limit of {MAX_FILES_PER_REPO:,} files per repository.\n"
75
+ f"Consider:\n"
76
+ f" - Splitting your data into multiple repositories\n"
77
+ f" - Using fewer, larger files (e.g., parquet files)\n"
78
+ f" - See: https://huggingface.co/docs/hub/repositories-recommendations"
79
+ )
80
+
81
+ # Check 2: Files and subdirectories per folder
82
+ # Track immediate children (files and subdirs) for each folder
83
+ from collections import defaultdict
84
+
85
+ entries_per_folder: dict[str, Any] = defaultdict(lambda: {"files": 0, "subdirs": set()})
86
+
87
+ for paths in paths_list:
88
+ path = Path(paths.path_in_repo)
89
+ parts = path.parts
90
+
91
+ # Count this file in its immediate parent directory
92
+ parent = str(path.parent) if str(path.parent) != "." else "."
93
+ entries_per_folder[parent]["files"] += 1
94
+
95
+ # Track immediate subdirectories for each parent folder
96
+ # Walk through the path components to track parent-child relationships
97
+ for i, child in enumerate(parts[:-1]):
98
+ parent = "." if i == 0 else "/".join(parts[:i])
99
+ entries_per_folder[parent]["subdirs"].add(child)
100
+
101
+ # Check limits for each folder
102
+ for folder, data in entries_per_folder.items():
103
+ file_count = data["files"]
104
+ subdir_count = len(data["subdirs"])
105
+ total_entries = file_count + subdir_count
106
+
107
+ if total_entries > MAX_FILES_PER_FOLDER:
108
+ folder_display = "root" if folder == "." else folder
109
+ logger.warning(
110
+ f"Folder '{folder_display}' contains {total_entries:,} entries "
111
+ f"({file_count:,} files and {subdir_count:,} subdirectories). "
112
+ f"This exceeds the recommended {MAX_FILES_PER_FOLDER:,} entries per folder.\n"
113
+ "Consider reorganising into sub-folders."
114
+ )
115
+
116
+ # Check 3: File sizes
117
+ large_files = []
118
+ very_large_files = []
119
+
120
+ for paths in paths_list:
121
+ size = paths.file_path.stat().st_size
122
+ size_gb = size / 1_000_000_000 # Use decimal GB as per Hub limits
123
+
124
+ if size_gb > MAX_FILE_SIZE_GB:
125
+ very_large_files.append((paths.path_in_repo, size_gb))
126
+ elif size_gb > RECOMMENDED_FILE_SIZE_GB:
127
+ large_files.append((paths.path_in_repo, size_gb))
128
+
129
+ # Warn about very large files (>200GB)
130
+ if very_large_files:
131
+ files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in very_large_files[:5])
132
+ more_str = f"\n ... and {len(very_large_files) - 5} more files" if len(very_large_files) > 5 else ""
133
+ logger.warning(
134
+ f"Found {len(very_large_files)} files exceeding the {MAX_FILE_SIZE_GB}GB recommended maximum:\n"
135
+ f" - {files_str}{more_str}\n"
136
+ f"Consider splitting these files into smaller chunks."
137
+ )
138
+
139
+ # Warn about large files (>20GB)
140
+ if large_files:
141
+ files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in large_files[:5])
142
+ more_str = f"\n ... and {len(large_files) - 5} more files" if len(large_files) > 5 else ""
143
+ logger.warning(
144
+ f"Found {len(large_files)} files larger than {RECOMMENDED_FILE_SIZE_GB}GB (recommended limit):\n"
145
+ f" - {files_str}{more_str}\n"
146
+ f"Large files may slow down loading and processing."
147
+ )
148
+
149
+ logger.info("Validation checks complete.")
150
+
151
+
152
+ def upload_large_folder_internal(
153
+ api: "HfApi",
154
+ repo_id: str,
155
+ folder_path: str | Path,
156
+ *,
157
+ repo_type: str, # Repo type is required!
158
+ revision: str | None = None,
159
+ private: bool | None = None,
160
+ allow_patterns: list[str] | str | None = None,
161
+ ignore_patterns: list[str] | str | None = None,
162
+ num_workers: int | None = None,
163
+ print_report: bool = True,
164
+ print_report_every: int = 60,
165
+ ):
166
+ """Upload a large folder to the Hub in the most resilient way possible.
167
+
168
+ See [`HfApi.upload_large_folder`] for the full documentation.
169
+ """
170
+ # 1. Check args and setup
171
+ if repo_type is None:
172
+ raise ValueError(
173
+ "For large uploads, `repo_type` is explicitly required. Please set it to `model`, `dataset` or `space`."
174
+ " If you are using the CLI, pass it as `--repo-type=model`."
175
+ )
176
+ if repo_type not in REPO_TYPES:
177
+ raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
178
+ if revision is None:
179
+ revision = DEFAULT_REVISION
180
+
181
+ folder_path = Path(folder_path).expanduser().resolve()
182
+ if not folder_path.is_dir():
183
+ raise ValueError(f"Provided path: '{folder_path}' is not a directory")
184
+
185
+ if ignore_patterns is None:
186
+ ignore_patterns = []
187
+ elif isinstance(ignore_patterns, str):
188
+ ignore_patterns = [ignore_patterns]
189
+ ignore_patterns += DEFAULT_IGNORE_PATTERNS
190
+
191
+ if num_workers is None:
192
+ nb_cores = os.cpu_count() or 1
193
+ num_workers = max(nb_cores // 2, 1) # Use at most half of cpu cores
194
+
195
+ # 2. Create repo if missing
196
+ repo_url = api.create_repo(repo_id=repo_id, repo_type=repo_type, private=private, exist_ok=True)
197
+ logger.info(f"Repo created: {repo_url}")
198
+ repo_id = repo_url.repo_id
199
+
200
+ # Warn on too many commits
201
+ try:
202
+ commits = api.list_repo_commits(repo_id=repo_id, repo_type=repo_type, revision=revision)
203
+ commit_count = len(commits)
204
+ if commit_count > 500:
205
+ logger.warning(
206
+ f"\n{'=' * 80}\n"
207
+ f"WARNING: This repository has {commit_count} commits.\n"
208
+ f"Repositories with a large number of commits can experience performance issues.\n"
209
+ f"\n"
210
+ f"Consider squashing your commit history using `super_squash_history()`.\n"
211
+ "To do so, you need to stop this process, run the snippet below and restart the upload command."
212
+ f" from huggingface_hub import super_squash_history\n"
213
+ f" super_squash_history(repo_id='{repo_id}', repo_type='{repo_type}')\n"
214
+ f"\n"
215
+ f"Note: This is a non-revertible operation. See the documentation for more details:\n"
216
+ f"https://huggingface.co/docs/huggingface_hub/main/en/package_reference/hf_api#huggingface_hub.HfApi.super_squash_history\n"
217
+ f"{'=' * 80}\n"
218
+ )
219
+ except Exception as e:
220
+ # Don't fail the upload if we can't check commit count
221
+ logger.debug(f"Could not check commit count: {e}")
222
+
223
+ # 2.1 Check if xet is enabled to set batch file upload size
224
+ upload_batch_size = UPLOAD_BATCH_SIZE_XET if is_xet_available() else UPLOAD_BATCH_SIZE_LFS
225
+
226
+ # 3. List files to upload
227
+ filtered_paths_list = filter_repo_objects(
228
+ (path.relative_to(folder_path).as_posix() for path in folder_path.glob("**/*") if path.is_file()),
229
+ allow_patterns=allow_patterns,
230
+ ignore_patterns=ignore_patterns,
231
+ )
232
+ paths_list = [get_local_upload_paths(folder_path, relpath) for relpath in filtered_paths_list]
233
+ logger.info(f"Found {len(paths_list)} candidate files to upload")
234
+
235
+ # Validate upload against repository limits
236
+ _validate_upload_limits(paths_list)
237
+
238
+ logger.info("Starting upload...")
239
+
240
+ # Read metadata for each file
241
+ items = [
242
+ (paths, read_upload_metadata(folder_path, paths.path_in_repo))
243
+ for paths in tqdm(paths_list, desc="Recovering from metadata files")
244
+ ]
245
+
246
+ # 4. Start workers
247
+ status = LargeUploadStatus(items, upload_batch_size)
248
+ threads = [
249
+ threading.Thread(
250
+ target=_worker_job,
251
+ kwargs={
252
+ "status": status,
253
+ "api": api,
254
+ "repo_id": repo_id,
255
+ "repo_type": repo_type,
256
+ "revision": revision,
257
+ },
258
+ )
259
+ for _ in range(num_workers)
260
+ ]
261
+
262
+ for thread in threads:
263
+ thread.start()
264
+
265
+ # 5. Print regular reports
266
+ if print_report:
267
+ print("\n\n" + status.current_report())
268
+ last_report_ts = time.time()
269
+ while True:
270
+ time.sleep(1)
271
+ if time.time() - last_report_ts >= print_report_every:
272
+ if print_report:
273
+ _print_overwrite(status.current_report())
274
+ last_report_ts = time.time()
275
+ if status.is_done():
276
+ logger.info("Is done: exiting main loop")
277
+ break
278
+
279
+ for thread in threads:
280
+ thread.join()
281
+
282
+ logger.info(status.current_report())
283
+ logger.info("Upload is complete!")
284
+
285
+
286
+ ####################
287
+ # Logic to manage workers and synchronize tasks
288
+ ####################
289
+
290
+
291
+ class WorkerJob(enum.Enum):
292
+ SHA256 = enum.auto()
293
+ GET_UPLOAD_MODE = enum.auto()
294
+ PREUPLOAD_LFS = enum.auto()
295
+ COMMIT = enum.auto()
296
+ WAIT = enum.auto() # if no tasks are available but we don't want to exit
297
+
298
+
299
+ JOB_ITEM_T = tuple[LocalUploadFilePaths, LocalUploadFileMetadata]
300
+
301
+
302
+ class LargeUploadStatus:
303
+ """Contains information, queues and tasks for a large upload process."""
304
+
305
+ def __init__(self, items: list[JOB_ITEM_T], upload_batch_size: int = 1):
306
+ self.items = items
307
+ self.queue_sha256: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
308
+ self.queue_get_upload_mode: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
309
+ self.queue_preupload_lfs: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
310
+ self.queue_commit: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
311
+ self.lock = Lock()
312
+
313
+ self.nb_workers_sha256: int = 0
314
+ self.nb_workers_get_upload_mode: int = 0
315
+ self.nb_workers_preupload_lfs: int = 0
316
+ self.upload_batch_size: int = upload_batch_size
317
+ self.nb_workers_commit: int = 0
318
+ self.nb_workers_waiting: int = 0
319
+ self.last_commit_attempt: float | None = None
320
+
321
+ self._started_at = datetime.now()
322
+ self._chunk_idx: int = 1
323
+ self._chunk_lock: Lock = Lock()
324
+
325
+ # Setup queues
326
+ for item in self.items:
327
+ paths, metadata = item
328
+ if metadata.sha256 is None:
329
+ self.queue_sha256.put(item)
330
+ elif metadata.upload_mode is None:
331
+ self.queue_get_upload_mode.put(item)
332
+ elif metadata.upload_mode == "lfs" and not metadata.is_uploaded:
333
+ self.queue_preupload_lfs.put(item)
334
+ elif not metadata.is_committed:
335
+ self.queue_commit.put(item)
336
+ else:
337
+ logger.debug(f"Skipping file {paths.path_in_repo} (already uploaded and committed)")
338
+
339
+ def target_chunk(self) -> int:
340
+ with self._chunk_lock:
341
+ return COMMIT_SIZE_SCALE[self._chunk_idx]
342
+
343
+ def update_chunk(self, success: bool, nb_items: int, duration: float) -> None:
344
+ with self._chunk_lock:
345
+ if not success:
346
+ logger.warning(f"Failed to commit {nb_items} files at once. Will retry with less files in next batch.")
347
+ self._chunk_idx -= 1
348
+ elif nb_items >= COMMIT_SIZE_SCALE[self._chunk_idx] and duration < 40:
349
+ logger.info(f"Successfully committed {nb_items} at once. Increasing the limit for next batch.")
350
+ self._chunk_idx += 1
351
+
352
+ self._chunk_idx = max(0, min(self._chunk_idx, len(COMMIT_SIZE_SCALE) - 1))
353
+
354
+ def current_report(self) -> str:
355
+ """Generate a report of the current status of the large upload."""
356
+ nb_hashed = 0
357
+ size_hashed = 0
358
+ nb_preuploaded = 0
359
+ nb_lfs = 0
360
+ nb_lfs_unsure = 0
361
+ size_preuploaded = 0
362
+ nb_committed = 0
363
+ size_committed = 0
364
+ total_size = 0
365
+ ignored_files = 0
366
+ total_files = 0
367
+
368
+ with self.lock:
369
+ for _, metadata in self.items:
370
+ if metadata.should_ignore:
371
+ ignored_files += 1
372
+ continue
373
+ total_size += metadata.size
374
+ total_files += 1
375
+ if metadata.sha256 is not None:
376
+ nb_hashed += 1
377
+ size_hashed += metadata.size
378
+ if metadata.upload_mode == "lfs":
379
+ nb_lfs += 1
380
+ if metadata.upload_mode is None:
381
+ nb_lfs_unsure += 1
382
+ if metadata.is_uploaded:
383
+ nb_preuploaded += 1
384
+ size_preuploaded += metadata.size
385
+ if metadata.is_committed:
386
+ nb_committed += 1
387
+ size_committed += metadata.size
388
+ total_size_str = _format_size(total_size)
389
+
390
+ now = datetime.now()
391
+ now_str = now.strftime("%Y-%m-%d %H:%M:%S")
392
+ elapsed = now - self._started_at
393
+ elapsed_str = str(elapsed).split(".")[0] # remove milliseconds
394
+
395
+ message = "\n" + "-" * 10
396
+ message += f" {now_str} ({elapsed_str}) "
397
+ message += "-" * 10 + "\n"
398
+
399
+ message += "Files: "
400
+ message += f"hashed {nb_hashed}/{total_files} ({_format_size(size_hashed)}/{total_size_str}) | "
401
+ message += f"pre-uploaded: {nb_preuploaded}/{nb_lfs} ({_format_size(size_preuploaded)}/{total_size_str})"
402
+ if nb_lfs_unsure > 0:
403
+ message += f" (+{nb_lfs_unsure} unsure)"
404
+ message += f" | committed: {nb_committed}/{total_files} ({_format_size(size_committed)}/{total_size_str})"
405
+ message += f" | ignored: {ignored_files}\n"
406
+
407
+ message += "Workers: "
408
+ message += f"hashing: {self.nb_workers_sha256} | "
409
+ message += f"get upload mode: {self.nb_workers_get_upload_mode} | "
410
+ message += f"pre-uploading: {self.nb_workers_preupload_lfs} | "
411
+ message += f"committing: {self.nb_workers_commit} | "
412
+ message += f"waiting: {self.nb_workers_waiting}\n"
413
+ message += "-" * 51
414
+
415
+ return message
416
+
417
+ def is_done(self) -> bool:
418
+ with self.lock:
419
+ return all(metadata.is_committed or metadata.should_ignore for _, metadata in self.items)
420
+
421
+
422
+ def _worker_job(
423
+ status: LargeUploadStatus,
424
+ api: "HfApi",
425
+ repo_id: str,
426
+ repo_type: str,
427
+ revision: str,
428
+ ):
429
+ """
430
+ Main process for a worker. The worker will perform tasks based on the priority list until all files are uploaded
431
+ and committed. If no tasks are available, the worker will wait for 10 seconds before checking again.
432
+
433
+ If a task fails for any reason, the item(s) are put back in the queue for another worker to pick up.
434
+
435
+ Read `upload_large_folder` docstring for more information on how tasks are prioritized.
436
+ """
437
+ while True:
438
+ next_job: tuple[WorkerJob, list[JOB_ITEM_T]] | None = None
439
+
440
+ # Determine next task
441
+ next_job = _determine_next_job(status)
442
+ if next_job is None:
443
+ return
444
+ job, items = next_job
445
+
446
+ # Perform task
447
+ match job:
448
+ case WorkerJob.SHA256:
449
+ item = items[0] # single item
450
+ try:
451
+ _compute_sha256(item)
452
+ status.queue_get_upload_mode.put(item)
453
+ except KeyboardInterrupt:
454
+ raise
455
+ except Exception as e:
456
+ logger.error(f"Failed to compute sha256: {e}")
457
+ traceback.format_exc()
458
+ status.queue_sha256.put(item)
459
+
460
+ with status.lock:
461
+ status.nb_workers_sha256 -= 1
462
+
463
+ case WorkerJob.GET_UPLOAD_MODE:
464
+ try:
465
+ _get_upload_mode(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
466
+ except KeyboardInterrupt:
467
+ raise
468
+ except Exception as e:
469
+ logger.error(f"Failed to get upload mode: {e}")
470
+ traceback.format_exc()
471
+
472
+ # Items are either:
473
+ # - dropped (if should_ignore)
474
+ # - put in LFS queue (if LFS)
475
+ # - put in commit queue (if regular)
476
+ # - or put back (if error occurred).
477
+ for item in items:
478
+ _, metadata = item
479
+ if metadata.should_ignore:
480
+ continue
481
+ match metadata.upload_mode:
482
+ case "lfs":
483
+ status.queue_preupload_lfs.put(item)
484
+ case "regular":
485
+ status.queue_commit.put(item)
486
+ case _:
487
+ status.queue_get_upload_mode.put(item)
488
+
489
+ with status.lock:
490
+ status.nb_workers_get_upload_mode -= 1
491
+
492
+ case WorkerJob.PREUPLOAD_LFS:
493
+ try:
494
+ _preupload_lfs(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
495
+ for item in items:
496
+ status.queue_commit.put(item)
497
+ except KeyboardInterrupt:
498
+ raise
499
+ except Exception as e:
500
+ logger.error(f"Failed to preupload LFS: {e}")
501
+ traceback.format_exc()
502
+ for item in items:
503
+ status.queue_preupload_lfs.put(item)
504
+
505
+ with status.lock:
506
+ status.nb_workers_preupload_lfs -= 1
507
+
508
+ case WorkerJob.COMMIT:
509
+ start_ts = time.time()
510
+ success = True
511
+ try:
512
+ _commit(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
513
+ except KeyboardInterrupt:
514
+ raise
515
+ except Exception as e:
516
+ logger.error(f"Failed to commit: {e}")
517
+ traceback.format_exc()
518
+ for item in items:
519
+ status.queue_commit.put(item)
520
+ success = False
521
+ duration = time.time() - start_ts
522
+ status.update_chunk(success, len(items), duration)
523
+ with status.lock:
524
+ status.last_commit_attempt = time.time()
525
+ status.nb_workers_commit -= 1
526
+
527
+ case WorkerJob.WAIT:
528
+ time.sleep(WAITING_TIME_IF_NO_TASKS)
529
+ with status.lock:
530
+ status.nb_workers_waiting -= 1
531
+
532
+
533
+ def _determine_next_job(status: LargeUploadStatus) -> tuple[WorkerJob, list[JOB_ITEM_T]] | None:
534
+ with status.lock:
535
+ # 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file)
536
+ if (
537
+ status.nb_workers_commit == 0
538
+ and status.queue_commit.qsize() > 0
539
+ and status.last_commit_attempt is not None
540
+ and time.time() - status.last_commit_attempt > 5 * 60
541
+ ):
542
+ status.nb_workers_commit += 1
543
+ logger.debug("Job: commit (more than 5 minutes since last commit attempt)")
544
+ return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
545
+
546
+ # 2. Commit if at least 100 files are ready to commit
547
+ elif status.nb_workers_commit == 0 and status.queue_commit.qsize() >= 150:
548
+ status.nb_workers_commit += 1
549
+ logger.debug("Job: commit (>100 files ready)")
550
+ return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
551
+
552
+ # 3. Get upload mode if at least 100 files
553
+ elif status.queue_get_upload_mode.qsize() >= MAX_NB_FILES_FETCH_UPLOAD_MODE:
554
+ status.nb_workers_get_upload_mode += 1
555
+ logger.debug(f"Job: get upload mode (>{MAX_NB_FILES_FETCH_UPLOAD_MODE} files ready)")
556
+ return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
557
+
558
+ # 4. Preupload LFS file if at least `status.upload_batch_size` files and no worker is preuploading LFS
559
+ elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size and status.nb_workers_preupload_lfs == 0:
560
+ status.nb_workers_preupload_lfs += 1
561
+ logger.debug("Job: preupload LFS (no other worker preuploading LFS)")
562
+ return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
563
+
564
+ # 5. Compute sha256 if at least 1 file and no worker is computing sha256
565
+ elif status.queue_sha256.qsize() > 0 and status.nb_workers_sha256 == 0:
566
+ status.nb_workers_sha256 += 1
567
+ logger.debug("Job: sha256 (no other worker computing sha256)")
568
+ return (WorkerJob.SHA256, _get_one(status.queue_sha256))
569
+
570
+ # 6. Get upload mode if at least 1 file and no worker is getting upload mode
571
+ elif status.queue_get_upload_mode.qsize() > 0 and status.nb_workers_get_upload_mode == 0:
572
+ status.nb_workers_get_upload_mode += 1
573
+ logger.debug("Job: get upload mode (no other worker getting upload mode)")
574
+ return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
575
+
576
+ # 7. Preupload LFS file if at least `status.upload_batch_size` files
577
+ elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size:
578
+ status.nb_workers_preupload_lfs += 1
579
+ logger.debug("Job: preupload LFS")
580
+ return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
581
+
582
+ # 8. Compute sha256 if at least 1 file
583
+ elif status.queue_sha256.qsize() > 0:
584
+ status.nb_workers_sha256 += 1
585
+ logger.debug("Job: sha256")
586
+ return (WorkerJob.SHA256, _get_one(status.queue_sha256))
587
+
588
+ # 9. Get upload mode if at least 1 file
589
+ elif status.queue_get_upload_mode.qsize() > 0:
590
+ status.nb_workers_get_upload_mode += 1
591
+ logger.debug("Job: get upload mode")
592
+ return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
593
+
594
+ # 10. Preupload LFS file if at least 1 file
595
+ elif status.queue_preupload_lfs.qsize() > 0:
596
+ status.nb_workers_preupload_lfs += 1
597
+ logger.debug("Job: preupload LFS")
598
+ return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
599
+
600
+ # 11. Commit if at least 1 file and 1 min since last commit attempt
601
+ elif (
602
+ status.nb_workers_commit == 0
603
+ and status.queue_commit.qsize() > 0
604
+ and status.last_commit_attempt is not None
605
+ and time.time() - status.last_commit_attempt > 1 * 60
606
+ ):
607
+ status.nb_workers_commit += 1
608
+ logger.debug("Job: commit (1 min since last commit attempt)")
609
+ return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
610
+
611
+ # 12. Commit if at least 1 file all other queues are empty and all workers are waiting
612
+ # e.g. when it's the last commit
613
+ elif (
614
+ status.nb_workers_commit == 0
615
+ and status.queue_commit.qsize() > 0
616
+ and status.queue_sha256.qsize() == 0
617
+ and status.queue_get_upload_mode.qsize() == 0
618
+ and status.queue_preupload_lfs.qsize() == 0
619
+ and status.nb_workers_sha256 == 0
620
+ and status.nb_workers_get_upload_mode == 0
621
+ and status.nb_workers_preupload_lfs == 0
622
+ ):
623
+ status.nb_workers_commit += 1
624
+ logger.debug("Job: commit")
625
+ return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
626
+
627
+ # 13. If all queues are empty, exit
628
+ elif all(metadata.is_committed or metadata.should_ignore for _, metadata in status.items):
629
+ logger.info("All files have been processed! Exiting worker.")
630
+ return None
631
+
632
+ # 14. If no task is available, wait
633
+ else:
634
+ status.nb_workers_waiting += 1
635
+ logger.debug(f"No task available, waiting... ({WAITING_TIME_IF_NO_TASKS}s)")
636
+ return (WorkerJob.WAIT, [])
637
+
638
+
639
+ ####################
640
+ # Atomic jobs (sha256, get_upload_mode, preupload_lfs, commit)
641
+ ####################
642
+
643
+
644
+ def _compute_sha256(item: JOB_ITEM_T) -> None:
645
+ """Compute sha256 of a file and save it in metadata."""
646
+ paths, metadata = item
647
+ if metadata.sha256 is None:
648
+ with paths.file_path.open("rb") as f:
649
+ metadata.sha256 = sha_fileobj(f).hex()
650
+ metadata.save(paths)
651
+
652
+
653
+ def _get_upload_mode(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
654
+ """Get upload mode for each file and update metadata.
655
+
656
+ Also receive info if the file should be ignored.
657
+ """
658
+ additions = [_build_hacky_operation(item) for item in items]
659
+ _fetch_upload_modes(
660
+ additions=additions,
661
+ repo_type=repo_type,
662
+ repo_id=repo_id,
663
+ headers=api._build_hf_headers(),
664
+ revision=quote(revision, safe=""),
665
+ endpoint=api.endpoint,
666
+ )
667
+ for item, addition in zip(items, additions):
668
+ paths, metadata = item
669
+ metadata.upload_mode = addition._upload_mode
670
+ metadata.should_ignore = addition._should_ignore
671
+ metadata.remote_oid = addition._remote_oid
672
+ metadata.save(paths)
673
+
674
+
675
+ def _preupload_lfs(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
676
+ """Preupload LFS files and update metadata."""
677
+ additions = [_build_hacky_operation(item) for item in items]
678
+ api.preupload_lfs_files(
679
+ repo_id=repo_id,
680
+ repo_type=repo_type,
681
+ revision=revision,
682
+ additions=additions,
683
+ )
684
+
685
+ for paths, metadata in items:
686
+ metadata.is_uploaded = True
687
+ metadata.save(paths)
688
+
689
+
690
+ def _commit(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
691
+ """Commit files to the repo."""
692
+ additions = [_build_hacky_operation(item) for item in items]
693
+ api.create_commit(
694
+ repo_id=repo_id,
695
+ repo_type=repo_type,
696
+ revision=revision,
697
+ operations=additions,
698
+ commit_message="Add files using upload-large-folder tool",
699
+ )
700
+ for paths, metadata in items:
701
+ metadata.is_committed = True
702
+ metadata.save(paths)
703
+
704
+
705
+ ####################
706
+ # Hacks with CommitOperationAdd to bypass checks/sha256 calculation
707
+ ####################
708
+
709
+
710
+ class HackyCommitOperationAdd(CommitOperationAdd):
711
+ def __post_init__(self) -> None:
712
+ if isinstance(self.path_or_fileobj, Path):
713
+ self.path_or_fileobj = str(self.path_or_fileobj)
714
+
715
+
716
+ def _build_hacky_operation(item: JOB_ITEM_T) -> HackyCommitOperationAdd:
717
+ paths, metadata = item
718
+ operation = HackyCommitOperationAdd(path_in_repo=paths.path_in_repo, path_or_fileobj=paths.file_path)
719
+ with paths.file_path.open("rb") as file:
720
+ sample = file.peek(512)[:512]
721
+ if metadata.sha256 is None:
722
+ raise ValueError("sha256 must have been computed by now!")
723
+ operation.upload_info = UploadInfo(sha256=bytes.fromhex(metadata.sha256), size=metadata.size, sample=sample)
724
+ operation._upload_mode = metadata.upload_mode # type: ignore
725
+ operation._should_ignore = metadata.should_ignore
726
+ operation._remote_oid = metadata.remote_oid
727
+ operation._is_uploaded = metadata.is_uploaded
728
+ if metadata.is_uploaded and metadata.upload_mode == "lfs":
729
+ operation.path_or_fileobj = b""
730
+ return operation
731
+
732
+
733
+ ####################
734
+ # Misc helpers
735
+ ####################
736
+
737
+
738
+ def _get_one(queue: "queue.Queue[JOB_ITEM_T]") -> list[JOB_ITEM_T]:
739
+ return [queue.get()]
740
+
741
+
742
+ def _get_n(queue: "queue.Queue[JOB_ITEM_T]", n: int) -> list[JOB_ITEM_T]:
743
+ return [queue.get() for _ in range(min(queue.qsize(), n))]
744
+
745
+
746
+ def _print_overwrite(report: str) -> None:
747
+ """Print a report, overwriting the previous lines.
748
+
749
+ Since tqdm in using `sys.stderr` to (re-)write progress bars, we need to use `sys.stdout`
750
+ to print the report.
751
+
752
+ Note: works well only if no other process is writing to `sys.stdout`!
753
+ """
754
+ report += "\n"
755
+ # Get terminal width
756
+ terminal_width = shutil.get_terminal_size().columns
757
+
758
+ # Count number of lines that should be cleared
759
+ nb_lines = sum(len(line) // terminal_width + 1 for line in report.splitlines())
760
+
761
+ # Clear previous lines based on the number of lines in the report
762
+ for _ in range(nb_lines):
763
+ sys.stdout.write("\r\033[K") # Clear line
764
+ sys.stdout.write("\033[F") # Move cursor up one line
765
+
766
+ # Print the new report, filling remaining space with whitespace
767
+ sys.stdout.write(report)
768
+ sys.stdout.write(" " * (terminal_width - len(report.splitlines()[-1])))
769
+ sys.stdout.flush()
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_upload_pipeline.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2026-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Streamed, multi-commit upload of a folder on top of the Xet upload protocol.
16
+
17
+ How it works:
18
+
19
+ - The **coordinator** (caller's thread) walks the list of files and asks the Hub, 256 files at a
20
+ time, what each file is (regular git blob, xet file, ignored). Regular files are accumulated
21
+ directly; xet files are registered into a `XetSession` upload-commit, which chunks, deduplicates,
22
+ retries and uploads them in the background while the coordinator keeps going. No Python-side
23
+ sha256 computation: `hf_xet` computes it during chunking (single read pass over each file).
24
+ - Whenever enough files have accumulated (adaptive batch size), the batch is handed over to the
25
+ **committer** thread which joins the xet uploads, drops unchanged files, and creates a git
26
+ commit for the batch. While a batch is being committed, the coordinator is already uploading
27
+ the next one.
28
+ - Interrupted uploads are resumable by simply re-running the same call: already-committed files
29
+ are dropped (no-op detection against the remote oid) and already-uploaded chunks are
30
+ deduplicated by the xet storage backend, transferring ~0 bytes.
31
+ """
32
+
33
+ import queue
34
+ import shutil
35
+ import sys
36
+ import threading
37
+ import time
38
+ from typing import TYPE_CHECKING, Any, Callable
39
+ from urllib.parse import quote
40
+
41
+ from . import constants
42
+ from ._commit_api import (
43
+ CommitOperationAdd,
44
+ CommitOperationDelete,
45
+ _fetch_upload_modes,
46
+ _send_commit,
47
+ _warn_on_overwriting_operations,
48
+ )
49
+ from .errors import RepositoryNotFoundError
50
+ from .utils import are_progress_bars_disabled, logging
51
+ from .utils._xet import (
52
+ XetTokenType,
53
+ abort_xet_session,
54
+ get_xet_session,
55
+ xet_connection_info_refresh_url,
56
+ xet_headers_without_auth,
57
+ )
58
+
59
+
60
+ if TYPE_CHECKING:
61
+ from .hf_api import CommitInfo, HfApi
62
+
63
+ logger = logging.get_logger(__name__)
64
+
65
+ # Number of files sent to the "preupload" endpoint per call (server-side limit).
66
+ PREUPLOAD_BATCH_SIZE = 256
67
+
68
+ # Files per git commit: adaptive, scaled up after fast commits and down after failures.
69
+ COMMIT_SIZE_SCALE = [20, 50, 75, 100, 125, 200, 250, 400, 600, 1000]
70
+ INITIAL_COMMIT_SIZE_INDEX = 6 # start at 256 files per commit
71
+ TARGET_COMMIT_DURATION = 40.0 # seconds; scale up batch size if commits are faster than this
72
+ MAX_COMMIT_INTERVAL = 5 * 60.0 # seconds; force a commit if the current batch is older than this
73
+
74
+ # Budget of regular-file content per commit (regular files are base64-encoded in the payload).
75
+ REGULAR_CONTENT_BYTES_BUDGET = 100 * 1024 * 1024
76
+
77
+ _SENTINEL = object() # Sentinel value for the batch queue to indicate the end of the upload
78
+
79
+ # Live display tuning
80
+ _BAR_WIDTH = 20
81
+ _REFRESH_INTERVAL = 0.5 # seconds between redraws on a TTY
82
+ _NON_TTY_LOG_INTERVAL = 30.0 # seconds between summary logs when stderr is not a TTY
83
+
84
+
85
+ def _bar(current: float, total: float, width: int = _BAR_WIDTH) -> str:
86
+ if total <= 0:
87
+ return "░" * width
88
+ filled = int(min(current / total, 1.0) * width)
89
+ return "█" * filled + "░" * (width - filled)
90
+
91
+
92
+ def _format_bytes(n: float) -> str:
93
+ for unit in ("B", "kB", "MB", "GB", "TB"):
94
+ if abs(n) < 1000:
95
+ if n < 10:
96
+ return f"{n:.2f}{unit}"
97
+ elif n < 100:
98
+ return f"{n:.1f}{unit}"
99
+ return f"{n:.0f}{unit}"
100
+ n /= 1000
101
+ return f"{n:.1f}PB"
102
+
103
+
104
+ class _LiveDisplay:
105
+ """Three-line live progress display on stderr::
106
+
107
+ Preparing ████████████████████ 11,100 / 11,100 ✓
108
+ Uploading ██████████████░░░░░░ 580 / 603 files 3.8GB · 19.7MB/s
109
+ Committing ██████████████████░░ 10,800 / 11,100 14 commits
110
+
111
+ A small renderer thread redraws the three lines in-place every ~0.5 s on a TTY
112
+ (worker threads only update counters under a lock). When stderr is not a TTY,
113
+ it falls back to a periodic ``logger.info`` summary instead.
114
+
115
+ Disabling progress bars (e.g. agent output mode) only turns off the TTY renderer:
116
+ the non-TTY log summaries are gated by the logger verbosity alone, so consumers
117
+ tailing stderr during a long upload still see periodic progress.
118
+ """
119
+
120
+ _N_LINES = 3
121
+
122
+ def __init__(self, total_files: int, enabled: bool = True) -> None:
123
+ self._total = total_files
124
+ self._tty = enabled and sys.stderr.isatty()
125
+ self._active = self._tty or logger.isEnabledFor(logging.INFO)
126
+ self._lock = threading.Lock()
127
+ self._drawn = False
128
+ self._stop_event = threading.Event()
129
+ self._thread: threading.Thread | None = None
130
+
131
+ # Counters (written by coordinator/committer threads, read by the renderer)
132
+ self._prepared = 0
133
+ self._ignored = 0
134
+ self._xet_total = 0
135
+ self._xet_done: set[str] = set() # item names; unique across batches
136
+ self._committed = 0 # committed or skipped-as-unchanged
137
+ self._nb_commits = 0
138
+
139
+ # Xet transfer bytes, summed across (possibly concurrent) upload-commits
140
+ self._xet_bytes = 0
141
+ self._speed_ema = 0.0
142
+ self._prev_bytes = 0
143
+ self._prev_time: float | None = None
144
+
145
+ # -- lifecycle (main thread) ------------------------------------------------
146
+
147
+ def start(self) -> None:
148
+ if not self._active:
149
+ return
150
+ if self._tty:
151
+ sys.stderr.write(f"Found {self._total:,} files to upload\n")
152
+ sys.stderr.flush()
153
+ else:
154
+ logger.info(f"Found {self._total:,} files to upload")
155
+ self._thread = threading.Thread(target=self._render_loop, name="hf-upload-display", daemon=True)
156
+ self._thread.start()
157
+
158
+ def close(self) -> None:
159
+ if self._thread is not None:
160
+ self._stop_event.set()
161
+ self._thread.join()
162
+ if self._tty:
163
+ with self._lock:
164
+ self._redraw() # final state
165
+
166
+ # -- counter updates (coordinator / committer / xet callback threads) --------
167
+
168
+ def notify_prepared(self, n: int) -> None:
169
+ with self._lock:
170
+ self._prepared += n
171
+
172
+ def notify_ignored(self, n: int) -> None:
173
+ with self._lock:
174
+ self._ignored += n
175
+
176
+ def notify_xet_registered(self, n: int) -> None:
177
+ with self._lock:
178
+ self._xet_total += n
179
+
180
+ def notify_xet_uploaded(self, names: list[str]) -> None:
181
+ with self._lock:
182
+ self._xet_done.update(names)
183
+
184
+ def notify_skipped(self, n: int) -> None:
185
+ with self._lock:
186
+ self._committed += n
187
+
188
+ def notify_commit(self, n_files: int) -> None:
189
+ with self._lock:
190
+ self._committed += n_files
191
+ self._nb_commits += 1
192
+
193
+ def new_xet_callback(self) -> "Callable | None":
194
+ """Progress callback for one ``new_upload_commit``.
195
+
196
+ The byte counters in ``group_report`` are cumulative *per upload-commit* and several
197
+ upload-commits can be in flight at once (one finalizing, one filling), so each commit
198
+ gets its own closure tracking its own previous value; increments are summed globally.
199
+ """
200
+ if not self._active:
201
+ return None
202
+ prev = 0
203
+
204
+ def callback(group_report: Any, item_reports: Any) -> None:
205
+ nonlocal prev
206
+ with self._lock:
207
+ completed = group_report.total_transfer_bytes_completed
208
+ self._xet_bytes += max(0, completed - prev)
209
+ prev = completed
210
+ for item in item_reports.values():
211
+ if item.total_bytes > 0 and item.bytes_completed == item.total_bytes:
212
+ self._xet_done.add(item.item_name)
213
+
214
+ return callback
215
+
216
+ # -- rendering (display thread) ----------------------------------------------
217
+
218
+ def _render_loop(self) -> None:
219
+ last_log = 0.0
220
+ while not self._stop_event.wait(_REFRESH_INTERVAL):
221
+ with self._lock:
222
+ self._update_speed()
223
+ if self._tty:
224
+ self._redraw()
225
+ elif time.monotonic() - last_log >= _NON_TTY_LOG_INTERVAL:
226
+ logger.info(self._summary())
227
+ last_log = time.monotonic()
228
+
229
+ def _update_speed(self) -> None:
230
+ now = time.monotonic()
231
+ if self._prev_time is not None and now > self._prev_time:
232
+ rate = (self._xet_bytes - self._prev_bytes) / (now - self._prev_time)
233
+ self._speed_ema = rate if self._speed_ema == 0 else 0.3 * rate + 0.7 * self._speed_ema
234
+ self._prev_time = now
235
+ self._prev_bytes = self._xet_bytes
236
+
237
+ def _redraw(self) -> None:
238
+ if self._drawn:
239
+ sys.stderr.write(f"\033[{self._N_LINES}A")
240
+ width = shutil.get_terminal_size().columns
241
+ for line in (self._line_preparing(), self._line_uploading(), self._line_committing()):
242
+ truncated = line[: width - 4] + "..." if len(line) > width - 1 else line
243
+ sys.stderr.write(f"\r\033[K{truncated}\n")
244
+ sys.stderr.flush()
245
+ self._drawn = True
246
+
247
+ def _line_preparing(self) -> str:
248
+ done = " ✓" if self._prepared >= self._total else ""
249
+ return f" Preparing {_bar(self._prepared, self._total)} {self._prepared:,} / {self._total:,}{done}"
250
+
251
+ def _line_uploading(self) -> str:
252
+ if self._xet_total == 0:
253
+ bar = _bar(1, 1) if self._prepared >= self._total else _bar(0, 1)
254
+ return f" Uploading {bar} -"
255
+ n_done = len(self._xet_done)
256
+ parts = []
257
+ if self._xet_bytes > 0:
258
+ parts.append(_format_bytes(self._xet_bytes))
259
+ if self._speed_ema > 0:
260
+ parts.append(f"{_format_bytes(self._speed_ema)}/s")
261
+ extra = f" {' · '.join(parts)}" if parts else ""
262
+ done = " ✓" if self._prepared >= self._total and n_done >= self._xet_total else ""
263
+ return f" Uploading {_bar(n_done, self._xet_total)} {n_done:,} / {self._xet_total:,} files{extra}{done}"
264
+
265
+ def _line_committing(self) -> str:
266
+ effective = self._total - self._ignored
267
+ commits_str = f" {self._nb_commits} commits" if self._nb_commits > 1 else ""
268
+ done = " ✓" if self._committed >= effective > 0 else ""
269
+ return (
270
+ f" Committing {_bar(self._committed, effective)} {self._committed:,} / {effective:,}{commits_str}{done}"
271
+ )
272
+
273
+ def _summary(self) -> str:
274
+ return (
275
+ f"Uploading... {self._prepared:,}/{self._total:,} files checked, "
276
+ f"{len(self._xet_done):,}/{self._xet_total:,} uploaded ({_format_bytes(self._xet_bytes)} transferred), "
277
+ f"{self._committed:,} committed in {self._nb_commits} commit(s)"
278
+ )
279
+
280
+
281
+ class _CommitPacer:
282
+ """Adaptive number of files per commit, to stay below server-side commit timeouts."""
283
+
284
+ def __init__(self) -> None:
285
+ self._index = INITIAL_COMMIT_SIZE_INDEX
286
+
287
+ @property
288
+ def target(self) -> int:
289
+ return COMMIT_SIZE_SCALE[self._index]
290
+
291
+ def record_success(self, duration: float, nb_files: int) -> None:
292
+ if duration < TARGET_COMMIT_DURATION and nb_files >= self.target:
293
+ self._index = min(self._index + 1, len(COMMIT_SIZE_SCALE) - 1)
294
+ elif duration > TARGET_COMMIT_DURATION:
295
+ self._index = max(self._index - 1, 0)
296
+
297
+ def record_failure(self) -> None:
298
+ self._index = max(self._index - 1, 0)
299
+
300
+
301
+ class _Batch:
302
+ """A group of files destined to a single git commit, with their in-flight xet uploads."""
303
+
304
+ def __init__(self) -> None:
305
+ self.ops: list[CommitOperationAdd] = []
306
+ self.regular_bytes: int = 0
307
+ self.xet_commit: Any = None # XetUploadCommit, opened lazily
308
+ self.handles: list[tuple[CommitOperationAdd, Any]] = [] # (op, XetFileUpload)
309
+ self.created_at: float = time.monotonic()
310
+
311
+
312
+ class _UploadPipeline:
313
+ def __init__(
314
+ self,
315
+ api: "HfApi",
316
+ *,
317
+ repo_id: str,
318
+ repo_type: str,
319
+ add_operations: list[CommitOperationAdd],
320
+ delete_operations: list[CommitOperationDelete],
321
+ commit_message: str,
322
+ commit_description: str | None,
323
+ token: str | bool | None,
324
+ revision: str | None,
325
+ create_pr: bool,
326
+ parent_commit: str | None,
327
+ ) -> None:
328
+ self.api = api
329
+ self.repo_id = repo_id
330
+ self.repo_type = repo_type
331
+ self.add_operations = add_operations
332
+ self.delete_operations = delete_operations
333
+ self.commit_message = commit_message
334
+ self.commit_description = commit_description
335
+ self.token = token
336
+ self.headers = api._build_hf_headers(token=token)
337
+ self.revision = revision or constants.DEFAULT_REVISION
338
+ self.create_pr = create_pr
339
+ self.parent_commit = parent_commit
340
+
341
+ # The base revision is used by the coordinator for ALL preupload calls and the xet token
342
+ # refresh URL, with the `create_pr` flag — exactly like `create_commit` does. It never
343
+ # changes during the run, even after a PR has been created.
344
+ self.base_revision_quoted = quote(self.revision, safe="")
345
+
346
+ # Committer state (mutated by the committer thread only)
347
+ self.commit_revision_quoted = self.base_revision_quoted # switched to the PR ref once created
348
+ self.pr_url: str | None = None
349
+ self.pr_revision: str | None = None
350
+ self.nb_commits = 0
351
+ self.last_commit_info: "CommitInfo | None" = None
352
+ self.pacer = _CommitPacer()
353
+
354
+ # Pipeline plumbing
355
+ self.batch_queue: queue.Queue = queue.Queue(maxsize=1)
356
+ self.errors: list[BaseException] = []
357
+ self.abort_event = threading.Event()
358
+ self.display = _LiveDisplay(total_files=len(add_operations), enabled=not are_progress_bars_disabled())
359
+
360
+ # All xet uploads share the same token refresh URL. With `create_pr`, the final ref is not
361
+ # known in advance: `?create_pr=1` makes the server grant a token valid for PR refs.
362
+ refresh_url = xet_connection_info_refresh_url(
363
+ token_type=XetTokenType.WRITE,
364
+ repo_id=repo_id,
365
+ repo_type=repo_type,
366
+ revision=self.base_revision_quoted,
367
+ endpoint=api.endpoint,
368
+ )
369
+ if create_pr:
370
+ refresh_url += "?create_pr=1"
371
+ self.xet_session = get_xet_session()
372
+ self.xet_commit_kwargs = {
373
+ "token_refresh_url": refresh_url,
374
+ "token_refresh_headers": self.headers,
375
+ "custom_headers": xet_headers_without_auth(self.headers),
376
+ }
377
+
378
+ # `.gitignore` rules are enforced server-side: forward the local one if it's being uploaded.
379
+ self.gitignore_content: str | None = None
380
+ for op in add_operations:
381
+ if op.path_in_repo == ".gitignore":
382
+ with op.as_file() as f:
383
+ self.gitignore_content = f.read().decode()
384
+ break
385
+
386
+ def run(self) -> "CommitInfo":
387
+ _warn_on_overwriting_operations([*self.delete_operations, *self.add_operations])
388
+ committer = threading.Thread(target=self._committer_loop, name="hf-upload-committer", daemon=True)
389
+ committer.start()
390
+ self.display.start()
391
+ try:
392
+ self._coordinator_loop()
393
+ except BaseException:
394
+ self.abort_event.set()
395
+ abort_xet_session()
396
+ raise
397
+ finally:
398
+ if self.abort_event.is_set():
399
+ # The committer exits on its own once the queue is drained (see `_committer_loop`).
400
+ # Bound the wait so a xet call blocked on the (aborted) session can never hang the
401
+ # shutdown — the committer is a daemon thread.
402
+ committer.join(timeout=10)
403
+ else:
404
+ self.batch_queue.put(_SENTINEL)
405
+ committer.join()
406
+ self.display.close()
407
+ if self.abort_event.is_set() and self.pr_revision is not None:
408
+ logger.warning(
409
+ f"Upload to pull request {self.pr_url} did not complete. To resume into the"
410
+ f' same PR, re-run with `revision="{self.pr_revision}"` (without `create_pr=True`). Re-running'
411
+ " with `create_pr=True` would open a new pull request."
412
+ )
413
+ if self.errors:
414
+ raise self.errors[0]
415
+ return self._final_commit_info()
416
+
417
+ # ---------------------------------------------------------------- coordinator
418
+
419
+ def _coordinator_loop(self) -> None:
420
+ import hf_xet
421
+
422
+ batch = _Batch()
423
+ for start in range(0, len(self.add_operations), PREUPLOAD_BATCH_SIZE):
424
+ if self.abort_event.is_set():
425
+ self._abort_batch(batch)
426
+ return
427
+ chunk = self.add_operations[start : start + PREUPLOAD_BATCH_SIZE]
428
+ try:
429
+ _fetch_upload_modes(
430
+ additions=chunk,
431
+ repo_type=self.repo_type,
432
+ repo_id=self.repo_id,
433
+ headers=self.headers,
434
+ revision=self.base_revision_quoted,
435
+ endpoint=self.api.endpoint,
436
+ create_pr=self.create_pr,
437
+ gitignore_content=self.gitignore_content,
438
+ )
439
+ except RepositoryNotFoundError as e:
440
+ from .hf_api import _CREATE_COMMIT_NO_REPO_ERROR_MESSAGE
441
+
442
+ e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE)
443
+ raise
444
+ self.display.notify_prepared(len(chunk))
445
+ for op in chunk:
446
+ if op._should_ignore:
447
+ logger.debug(f"Skipping upload for '{op.path_in_repo}' (ignored by gitignore rules).")
448
+ self.display.notify_ignored(1)
449
+ continue
450
+ if op._upload_mode == "regular":
451
+ batch.regular_bytes += op.upload_info.size
452
+ else:
453
+ if batch.xet_commit is None:
454
+ batch.xet_commit = self.xet_session.new_upload_commit(
455
+ progress_callback=self.display.new_xet_callback(), **self.xet_commit_kwargs
456
+ )
457
+ # Upload starts immediately in the background. sha256 is computed by hf_xet
458
+ # while chunking, unless already known (e.g. resumed operations).
459
+ sha_arg = op.upload_info.sha256.hex() if op.upload_info.is_hashed else hf_xet.COMPUTE_SHA256
460
+ if isinstance(op.path_or_fileobj, bytes):
461
+ handle = batch.xet_commit.start_upload_bytes(
462
+ op.path_or_fileobj, sha256=sha_arg, name=op.path_in_repo
463
+ )
464
+ else:
465
+ handle = batch.xet_commit.start_upload_file(str(op.path_or_fileobj), sha256=sha_arg)
466
+ batch.handles.append((op, handle))
467
+ self.display.notify_xet_registered(1)
468
+ batch.ops.append(op)
469
+
470
+ if (
471
+ len(batch.ops) >= self.pacer.target
472
+ or batch.regular_bytes >= REGULAR_CONTENT_BYTES_BUDGET
473
+ or (time.monotonic() - batch.created_at > MAX_COMMIT_INTERVAL and len(batch.ops) > 0)
474
+ ):
475
+ self._enqueue(batch)
476
+ batch = _Batch()
477
+ self._enqueue(batch)
478
+
479
+ def _enqueue(self, batch: _Batch) -> None:
480
+ if len(batch.ops) == 0 and not (self.nb_commits == 0 and len(self.delete_operations) > 0):
481
+ return
482
+ # Blocks if a batch is already waiting: natural backpressure on scanning/uploading.
483
+ while not self.abort_event.is_set():
484
+ try:
485
+ self.batch_queue.put(batch, timeout=1.0)
486
+ return
487
+ except queue.Full:
488
+ continue
489
+ self._abort_batch(batch)
490
+
491
+ def _abort_batch(self, batch: _Batch) -> None:
492
+ if batch.xet_commit is not None:
493
+ try:
494
+ batch.xet_commit.abort()
495
+ except Exception:
496
+ pass
497
+
498
+ # ---------------------------------------------------------------- committer
499
+
500
+ def _committer_loop(self) -> None:
501
+ while True:
502
+ try:
503
+ batch = self.batch_queue.get(timeout=0.5)
504
+ except queue.Empty:
505
+ if self.abort_event.is_set():
506
+ return # aborted: exit once the queue is drained, no sentinel needed
507
+ continue
508
+ if batch is _SENTINEL:
509
+ return
510
+ try:
511
+ if not self.abort_event.is_set():
512
+ self._process_batch(batch)
513
+ else:
514
+ self._abort_batch(batch)
515
+ except BaseException as e:
516
+ self._abort_batch(batch)
517
+ self.errors.append(e)
518
+ self.abort_event.set()
519
+
520
+ def _process_batch(self, batch: _Batch) -> None:
521
+ # 1. Wait for all xet uploads of this batch and finalize them (atomic xet commit). Files
522
+ # can only be referenced by a git commit once their xet upload-commit is finalized.
523
+ if batch.xet_commit is not None:
524
+ batch.xet_commit.wait_to_finish()
525
+ for op, handle in batch.handles:
526
+ if not op.upload_info.is_hashed:
527
+ op.upload_info.sha256 = bytes.fromhex(handle.result().xet_info.sha256)
528
+ op._is_uploaded = True
529
+ # Files whose last progress tick was missed are still done at this point.
530
+ self.display.notify_xet_uploaded(
531
+ [
532
+ str(op.path_or_fileobj) if not isinstance(op.path_or_fileobj, bytes) else op.path_in_repo
533
+ for op, _ in batch.handles
534
+ ]
535
+ )
536
+
537
+ # 2. Drop files that have not changed compared to the remote (prevents empty commits).
538
+ # Their chunks were deduplicated anyway (~0 bytes transferred).
539
+ ops_to_commit = []
540
+ for op in batch.ops:
541
+ if op._remote_oid is not None and op._remote_oid == op._local_oid:
542
+ logger.debug(f"Skipping commit for '{op.path_in_repo}' (file unchanged).")
543
+ self.display.notify_skipped(1)
544
+ continue
545
+ ops_to_commit.append(op)
546
+
547
+ # 3. Create the git commit(s). On failure, scale down and split the batch.
548
+ if len(ops_to_commit) > 0 or (self.nb_commits == 0 and len(self.delete_operations) > 0):
549
+ self._commit_with_split(ops_to_commit)
550
+
551
+ def _commit_with_split(self, ops: list[CommitOperationAdd]) -> None:
552
+ try:
553
+ self._do_commit(ops)
554
+ except Exception as e:
555
+ self.pacer.record_failure()
556
+ if len(ops) <= COMMIT_SIZE_SCALE[0]:
557
+ raise
558
+ logger.warning(f"Commit of {len(ops)} files failed ({e!r}). Retrying in smaller chunks.")
559
+ target = self.pacer.target
560
+ for start in range(0, len(ops), target):
561
+ self._commit_with_split(ops[start : start + target])
562
+
563
+ def _do_commit(self, ops: list[CommitOperationAdd]) -> None:
564
+ if self.create_pr and self.pr_revision is None:
565
+ # Create the (draft) pull request explicitly and push every commit to its ref. Committing
566
+ # with `?create_pr=1` instead would risk opening a second PR if the commit POST is retried
567
+ # after a lost response. Created lazily so that a fully-unchanged upload opens no PR.
568
+ # Note: PRs created this way are always opened against the default branch, hence the
569
+ # `create_pr` + `revision` combination being rejected in `upload_folder`.
570
+ pr = self.api.create_pull_request(
571
+ repo_id=self.repo_id,
572
+ title=self.commit_message,
573
+ token=self.token,
574
+ description=self.commit_description,
575
+ repo_type=self.repo_type,
576
+ )
577
+ if pr.git_reference is None:
578
+ raise ValueError("Server did not return a git reference for the created pull request.")
579
+ self.pr_url = pr.url
580
+ self.pr_revision = pr.git_reference
581
+ self.commit_revision_quoted = quote(pr.git_reference, safe="")
582
+
583
+ operations: list[Any] = list(ops)
584
+ if self.nb_commits == 0:
585
+ # Deletions and `parent_commit` ride the first commit.
586
+ operations = list(self.delete_operations) + operations
587
+
588
+ commit_message = (
589
+ self.commit_message if self.nb_commits == 0 else f"{self.commit_message} (part {self.nb_commits + 1})"
590
+ )
591
+ t0 = time.monotonic()
592
+ # Retried with backoff on transient errors: safe because the commit targets an explicit
593
+ # ref (`?create_pr=1` is never used, see above).
594
+ self.last_commit_info = _send_commit(
595
+ operations=operations,
596
+ files_to_copy={},
597
+ commit_message=commit_message,
598
+ commit_description=self.commit_description or "",
599
+ repo_type=self.repo_type,
600
+ repo_id=self.repo_id,
601
+ headers=self.headers,
602
+ revision=self.commit_revision_quoted,
603
+ endpoint=self.api.endpoint,
604
+ parent_commit=self.parent_commit if self.nb_commits == 0 else None,
605
+ retry_on_error=True,
606
+ )
607
+ duration = time.monotonic() - t0
608
+ self.pacer.record_success(duration, len(ops))
609
+ self.nb_commits += 1
610
+
611
+ for op in ops:
612
+ op._is_committed = True
613
+ self.display.notify_commit(len(ops))
614
+ logger.debug(f"Committed {len(ops)} file(s) in {duration:.1f}s: {self.last_commit_info.commit_url}")
615
+
616
+ # ---------------------------------------------------------------- result
617
+
618
+ def _final_commit_info(self) -> "CommitInfo":
619
+ from .hf_api import CommitInfo
620
+
621
+ if self.last_commit_info is None:
622
+ # Nothing was committed (everything unchanged/ignored): mimic `create_commit` and
623
+ # return info about the latest commit on the target revision.
624
+ logger.warning("No files have been modified since last commit. Skipping to prevent empty commit.")
625
+ info = self.api.repo_info(repo_id=self.repo_id, repo_type=self.repo_type, revision=self.revision)
626
+ url_prefix = self.api.endpoint
627
+ if self.repo_type != constants.REPO_TYPE_MODEL:
628
+ url_prefix = f"{url_prefix}/{self.repo_type}s"
629
+ return CommitInfo(
630
+ commit_url=f"{url_prefix}/{self.repo_id}/commit/{info.sha}",
631
+ commit_message=self.commit_message,
632
+ commit_description=self.commit_description or "",
633
+ oid=info.sha, # type: ignore
634
+ _endpoint=self.api.endpoint,
635
+ )
636
+ if self.nb_commits > 1:
637
+ logger.info(f"Upload completed in {self.nb_commits} commits.")
638
+ if self.pr_url is not None:
639
+ # PR upload: attach the PR info (commit responses don't carry it; the PR is created separately).
640
+ return CommitInfo(
641
+ commit_url=self.last_commit_info.commit_url,
642
+ commit_message=self.last_commit_info.commit_message,
643
+ commit_description=self.last_commit_info.commit_description,
644
+ oid=self.last_commit_info.oid,
645
+ pr_url=self.pr_url,
646
+ _endpoint=self.api.endpoint,
647
+ )
648
+ return self.last_commit_info
649
+
650
+
651
+ def pipelined_upload(
652
+ api: "HfApi",
653
+ *,
654
+ repo_id: str,
655
+ repo_type: str,
656
+ add_operations: list[CommitOperationAdd],
657
+ delete_operations: list[CommitOperationDelete],
658
+ commit_message: str,
659
+ commit_description: str | None = None,
660
+ token: str | bool | None = None,
661
+ revision: str | None = None,
662
+ create_pr: bool = False,
663
+ parent_commit: str | None = None,
664
+ ) -> "CommitInfo":
665
+ """Upload a prepared list of operations through the streamed multi-commit pipeline.
666
+
667
+ Requires `hf_xet` to be installed. See module docstring for the architecture.
668
+ """
669
+
670
+ return _UploadPipeline(
671
+ api,
672
+ repo_id=repo_id,
673
+ repo_type=repo_type,
674
+ add_operations=add_operations,
675
+ delete_operations=delete_operations,
676
+ commit_message=commit_message,
677
+ commit_description=commit_description,
678
+ token=token,
679
+ revision=revision,
680
+ create_pr=create_pr,
681
+ parent_commit=parent_commit,
682
+ ).run()
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_webhooks_payload.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains data structures to parse the webhooks payload."""
15
+
16
+ from typing import Literal
17
+
18
+ from .utils import is_pydantic_available
19
+
20
+
21
+ if is_pydantic_available():
22
+ from pydantic import BaseModel
23
+ else:
24
+ # Define a dummy BaseModel to avoid import errors when pydantic is not installed
25
+ # Import error will be raised when trying to use the class
26
+
27
+ class BaseModel: # type: ignore [no-redef]
28
+ def __init__(self, *args, **kwargs) -> None:
29
+ raise ImportError(
30
+ "You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that"
31
+ " should be installed separately. Please run `pip install --upgrade pydantic` and retry."
32
+ )
33
+
34
+
35
+ # This is an adaptation of the ReportV3 interface implemented in moon-landing. V0, V1 and V2 have been ignored as they
36
+ # are not in used anymore. To keep in sync when format is updated in
37
+ # https://github.com/huggingface/moon-landing/blob/main/server/lib/HFWebhooks.ts (internal link).
38
+
39
+
40
+ WebhookEvent_T = Literal[
41
+ "create",
42
+ "delete",
43
+ "move",
44
+ "update",
45
+ ]
46
+ RepoChangeEvent_T = Literal[
47
+ "add",
48
+ "move",
49
+ "remove",
50
+ "update",
51
+ ]
52
+ RepoType_T = Literal[
53
+ "dataset",
54
+ "model",
55
+ "space",
56
+ ]
57
+ DiscussionStatus_T = Literal[
58
+ "closed",
59
+ "draft",
60
+ "open",
61
+ "merged",
62
+ ]
63
+ SupportedWebhookVersion = Literal[3]
64
+
65
+
66
+ class ObjectId(BaseModel):
67
+ id: str
68
+
69
+
70
+ class WebhookPayloadUrl(BaseModel):
71
+ web: str
72
+ api: str | None = None
73
+
74
+
75
+ class WebhookPayloadMovedTo(BaseModel):
76
+ name: str
77
+ owner: ObjectId
78
+
79
+
80
+ class WebhookPayloadWebhook(ObjectId):
81
+ version: SupportedWebhookVersion
82
+
83
+
84
+ class WebhookPayloadEvent(BaseModel):
85
+ action: WebhookEvent_T
86
+ scope: str
87
+
88
+
89
+ class WebhookPayloadDiscussionChanges(BaseModel):
90
+ base: str
91
+ mergeCommitId: str | None = None
92
+
93
+
94
+ class WebhookPayloadComment(ObjectId):
95
+ author: ObjectId
96
+ hidden: bool
97
+ content: str | None = None
98
+ url: WebhookPayloadUrl
99
+
100
+
101
+ class WebhookPayloadDiscussion(ObjectId):
102
+ num: int
103
+ author: ObjectId
104
+ url: WebhookPayloadUrl
105
+ title: str
106
+ isPullRequest: bool
107
+ status: DiscussionStatus_T
108
+ changes: WebhookPayloadDiscussionChanges | None = None
109
+ pinned: bool | None = None
110
+
111
+
112
+ class WebhookPayloadRepo(ObjectId):
113
+ owner: ObjectId
114
+ head_sha: str | None = None
115
+ name: str
116
+ private: bool
117
+ subdomain: str | None = None
118
+ tags: list[str] | None = None
119
+ type: Literal["dataset", "model", "space"]
120
+ url: WebhookPayloadUrl
121
+
122
+
123
+ class WebhookPayloadUpdatedRef(BaseModel):
124
+ ref: str
125
+ oldSha: str | None = None
126
+ newSha: str | None = None
127
+
128
+
129
+ class WebhookPayload(BaseModel):
130
+ event: WebhookPayloadEvent
131
+ repo: WebhookPayloadRepo
132
+ discussion: WebhookPayloadDiscussion | None = None
133
+ comment: WebhookPayloadComment | None = None
134
+ webhook: WebhookPayloadWebhook
135
+ movedTo: WebhookPayloadMovedTo | None = None
136
+ updatedRefs: list[WebhookPayloadUpdatedRef] | None = None
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/_webhooks_server.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains `WebhooksServer` and `webhook_endpoint` to create a webhook server easily."""
15
+
16
+ import atexit
17
+ import inspect
18
+ import os
19
+ from collections.abc import Callable
20
+ from functools import wraps
21
+ from typing import TYPE_CHECKING, Any, Optional
22
+
23
+ from .utils import experimental, is_fastapi_available, is_gradio_available
24
+
25
+
26
+ if TYPE_CHECKING:
27
+ import gradio as gr
28
+ from fastapi import Request
29
+
30
+ if is_fastapi_available():
31
+ from fastapi import FastAPI, Request
32
+ from fastapi.responses import JSONResponse
33
+ else:
34
+ # Will fail at runtime if FastAPI is not available
35
+ FastAPI = Request = JSONResponse = None # type: ignore
36
+
37
+
38
+ _global_app: Optional["WebhooksServer"] = None # ty: ignore[invalid-type-form]
39
+ _is_local = os.environ.get("SPACE_ID") is None
40
+
41
+
42
+ @experimental
43
+ class WebhooksServer:
44
+ """
45
+ The [`WebhooksServer`] class lets you create an instance of a Gradio app that can receive Huggingface webhooks.
46
+ These webhooks can be registered using the [`~WebhooksServer.add_webhook`] decorator. Webhook endpoints are added to
47
+ the app as a POST endpoint to the FastAPI router. Once all the webhooks are registered, the `launch` method has to be
48
+ called to start the app.
49
+
50
+ It is recommended to accept [`WebhookPayload`] as the first argument of the webhook function. It is a Pydantic
51
+ model that contains all the information about the webhook event. The data will be parsed automatically for you.
52
+
53
+ Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your
54
+ WebhooksServer and deploy it on a Space.
55
+
56
+ > [!WARNING]
57
+ > `WebhooksServer` is experimental. Its API is subject to change in the future.
58
+
59
+ > [!WARNING]
60
+ > You must have `gradio` installed to use `WebhooksServer` (`pip install --upgrade gradio`).
61
+
62
+ Args:
63
+ ui (`gradio.Blocks`, optional):
64
+ A Gradio UI instance to be used as the Space landing page. If `None`, a UI displaying instructions
65
+ about the configured webhooks is created.
66
+ webhook_secret (`str`, optional):
67
+ A secret key to verify incoming webhook requests. You can set this value to any secret you want as long as
68
+ you also configure it in your [webhooks settings panel](https://huggingface.co/settings/webhooks). You
69
+ can also set this value as the `WEBHOOK_SECRET` environment variable. If no secret is provided, the
70
+ webhook endpoints are opened without any security.
71
+
72
+ Example:
73
+
74
+ ```python
75
+ import gradio as gr
76
+ from huggingface_hub import WebhooksServer, WebhookPayload
77
+
78
+ with gr.Blocks() as ui:
79
+ ...
80
+
81
+ app = WebhooksServer(ui=ui, webhook_secret="my_secret_key")
82
+
83
+ @app.add_webhook("/say_hello")
84
+ async def hello(payload: WebhookPayload):
85
+ return {"message": "hello"}
86
+
87
+ app.launch()
88
+ ```
89
+ """
90
+
91
+ def __new__(cls, *args, **kwargs) -> "WebhooksServer": # ty: ignore[invalid-type-form]
92
+ if not is_gradio_available():
93
+ raise ImportError(
94
+ "You must have `gradio` installed to use `WebhooksServer`. Please run `pip install --upgrade gradio`"
95
+ " first."
96
+ )
97
+ if not is_fastapi_available():
98
+ raise ImportError(
99
+ "You must have `fastapi` installed to use `WebhooksServer`. Please run `pip install --upgrade fastapi`"
100
+ " first."
101
+ )
102
+ return super().__new__(cls)
103
+
104
+ def __init__(
105
+ self,
106
+ ui: Optional["gr.Blocks"] = None,
107
+ webhook_secret: str | None = None,
108
+ ) -> None:
109
+ self._ui = ui
110
+
111
+ self.webhook_secret = webhook_secret or os.getenv("WEBHOOK_SECRET")
112
+ self.registered_webhooks: dict[str, Callable] = {}
113
+ _warn_on_empty_secret(self.webhook_secret)
114
+
115
+ def add_webhook(self, path: str | None = None) -> Callable:
116
+ """
117
+ Decorator to add a webhook to the [`WebhooksServer`] server.
118
+
119
+ Args:
120
+ path (`str`, optional):
121
+ The URL path to register the webhook function. If not provided, the function name will be used as the
122
+ path. In any case, all webhooks are registered under `/webhooks`.
123
+
124
+ Raises:
125
+ ValueError: If the provided path is already registered as a webhook.
126
+
127
+ Example:
128
+ ```python
129
+ from huggingface_hub import WebhooksServer, WebhookPayload
130
+
131
+ app = WebhooksServer()
132
+
133
+ @app.add_webhook
134
+ async def trigger_training(payload: WebhookPayload):
135
+ if payload.repo.type == "dataset" and payload.event.action == "update":
136
+ # Trigger a training job if a dataset is updated
137
+ ...
138
+
139
+ app.launch()
140
+ ```
141
+ """
142
+ # Usage: directly as decorator. Example: `@app.add_webhook`
143
+ if callable(path):
144
+ # If path is a function, it means it was used as a decorator without arguments
145
+ return self.add_webhook()(path)
146
+
147
+ # Usage: provide a path. Example: `@app.add_webhook(...)`
148
+ @wraps(FastAPI.post)
149
+ def _inner_post(*args, **kwargs):
150
+ func = args[0]
151
+ abs_path = f"/webhooks/{(path or func.__name__).strip('/')}"
152
+ if abs_path in self.registered_webhooks:
153
+ raise ValueError(f"Webhook {abs_path} already exists.")
154
+ self.registered_webhooks[abs_path] = func
155
+
156
+ return _inner_post
157
+
158
+ def launch(self, prevent_thread_lock: bool = False, **launch_kwargs: Any) -> None:
159
+ """Launch the Gradio app and register webhooks to the underlying FastAPI server.
160
+
161
+ Input parameters are forwarded to Gradio when launching the app.
162
+ """
163
+ ui = self._ui or self._get_default_ui()
164
+
165
+ # Start Gradio App
166
+ # - as non-blocking so that webhooks can be added afterwards
167
+ # - as shared if launch locally (to debug webhooks)
168
+ launch_kwargs.setdefault("share", _is_local)
169
+ self.fastapi_app, _, _ = ui.launch(prevent_thread_lock=True, **launch_kwargs)
170
+
171
+ # Register webhooks to FastAPI app
172
+ for path, func in self.registered_webhooks.items():
173
+ # Add secret check if required
174
+ if self.webhook_secret is not None:
175
+ func = _wrap_webhook_to_check_secret(func, webhook_secret=self.webhook_secret)
176
+
177
+ # Add route to FastAPI app
178
+ self.fastapi_app.post(path)(func)
179
+
180
+ # Print instructions and block main thread
181
+ space_host = os.environ.get("SPACE_HOST")
182
+ url = "https://" + space_host if space_host is not None else (ui.share_url or ui.local_url)
183
+ if url is None:
184
+ raise ValueError("Cannot find the URL of the app. Please provide a valid `ui` or update `gradio` version.")
185
+ url = url.strip("/")
186
+ message = "\nWebhooks are correctly setup and ready to use:"
187
+ message += "\n" + "\n".join(f" - POST {url}{webhook}" for webhook in self.registered_webhooks)
188
+ message += "\nGo to https://huggingface.co/settings/webhooks to setup your webhooks."
189
+ print(message)
190
+
191
+ if not prevent_thread_lock:
192
+ ui.block_thread()
193
+
194
+ def _get_default_ui(self) -> "gr.Blocks":
195
+ """Default UI if not provided (lists webhooks and provides basic instructions)."""
196
+ import gradio as gr
197
+
198
+ with gr.Blocks() as ui:
199
+ gr.Markdown("# This is an app to process 🤗 Webhooks")
200
+ gr.Markdown(
201
+ "Webhooks are a foundation for MLOps-related features. They allow you to listen for new changes on"
202
+ " specific repos or to all repos belonging to particular set of users/organizations (not just your"
203
+ " repos, but any repo). Check out this [guide](https://huggingface.co/docs/hub/webhooks) to get to"
204
+ " know more about webhooks on the Huggingface Hub."
205
+ )
206
+ gr.Markdown(
207
+ f"{len(self.registered_webhooks)} webhook(s) are registered:"
208
+ + "\n\n"
209
+ + "\n ".join(
210
+ f"- [{webhook_path}]({_get_webhook_doc_url(webhook.__name__, webhook_path)})"
211
+ for webhook_path, webhook in self.registered_webhooks.items()
212
+ )
213
+ )
214
+ gr.Markdown(
215
+ "Go to https://huggingface.co/settings/webhooks to setup your webhooks."
216
+ + "\nYou app is running locally. Please look at the logs to check the full URL you need to set."
217
+ if _is_local
218
+ else (
219
+ "\nThis app is running on a Space. You can find the corresponding URL in the options menu"
220
+ " (top-right) > 'Embed the Space'. The URL looks like 'https://{username}-{repo_name}.hf.space'."
221
+ )
222
+ )
223
+ return ui
224
+
225
+
226
+ @experimental
227
+ def webhook_endpoint(path: str | None = None) -> Callable:
228
+ """Decorator to start a [`WebhooksServer`] and register the decorated function as a webhook endpoint.
229
+
230
+ This is a helper to get started quickly. If you need more flexibility (custom landing page or webhook secret),
231
+ you can use [`WebhooksServer`] directly. You can register multiple webhook endpoints (to the same server) by using
232
+ this decorator multiple times.
233
+
234
+ Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your
235
+ server and deploy it on a Space.
236
+
237
+ > [!WARNING]
238
+ > `webhook_endpoint` is experimental. Its API is subject to change in the future.
239
+
240
+ > [!WARNING]
241
+ > You must have `gradio` installed to use `webhook_endpoint` (`pip install --upgrade gradio`).
242
+
243
+ Args:
244
+ path (`str`, optional):
245
+ The URL path to register the webhook function. If not provided, the function name will be used as the path.
246
+ In any case, all webhooks are registered under `/webhooks`.
247
+
248
+ Examples:
249
+ The default usage is to register a function as a webhook endpoint. The function name will be used as the path.
250
+ The server will be started automatically at exit (i.e. at the end of the script).
251
+
252
+ ```python
253
+ from huggingface_hub import webhook_endpoint, WebhookPayload
254
+
255
+ @webhook_endpoint
256
+ async def trigger_training(payload: WebhookPayload):
257
+ if payload.repo.type == "dataset" and payload.event.action == "update":
258
+ # Trigger a training job if a dataset is updated
259
+ ...
260
+
261
+ # Server is automatically started at the end of the script.
262
+ ```
263
+
264
+ Advanced usage: register a function as a webhook endpoint and start the server manually. This is useful if you
265
+ are running it in a notebook.
266
+
267
+ ```python
268
+ from huggingface_hub import webhook_endpoint, WebhookPayload
269
+
270
+ @webhook_endpoint
271
+ async def trigger_training(payload: WebhookPayload):
272
+ if payload.repo.type == "dataset" and payload.event.action == "update":
273
+ # Trigger a training job if a dataset is updated
274
+ ...
275
+
276
+ # Start the server manually
277
+ trigger_training.launch()
278
+ ```
279
+ """
280
+ if callable(path):
281
+ # If path is a function, it means it was used as a decorator without arguments
282
+ return webhook_endpoint()(path)
283
+
284
+ @wraps(WebhooksServer.add_webhook)
285
+ def _inner(func: Callable) -> Callable:
286
+ app = _get_global_app()
287
+ app.add_webhook(path)(func)
288
+ if len(app.registered_webhooks) == 1:
289
+ # Register `app.launch` to run at exit (only once)
290
+ atexit.register(app.launch)
291
+
292
+ @wraps(app.launch)
293
+ def _launch_now():
294
+ # Run the app directly (without waiting atexit)
295
+ atexit.unregister(app.launch)
296
+ app.launch()
297
+
298
+ func.launch = _launch_now # type: ignore
299
+ return func
300
+
301
+ return _inner
302
+
303
+
304
+ def _get_global_app() -> WebhooksServer: # ty: ignore[invalid-type-form]
305
+ global _global_app
306
+ if _global_app is None:
307
+ _global_app = WebhooksServer()
308
+ return _global_app
309
+
310
+
311
+ def _warn_on_empty_secret(webhook_secret: str | None) -> None:
312
+ if webhook_secret is None:
313
+ print("Webhook secret is not defined. This means your webhook endpoints will be open to everyone.")
314
+ print(
315
+ "To add a secret, set `WEBHOOK_SECRET` as environment variable or pass it at initialization: "
316
+ "\n\t`app = WebhooksServer(webhook_secret='my_secret', ...)`"
317
+ )
318
+ print(
319
+ "For more details about webhook secrets, please refer to"
320
+ " https://huggingface.co/docs/hub/webhooks#webhook-secret."
321
+ )
322
+ else:
323
+ print("Webhook secret is correctly defined.")
324
+
325
+
326
+ def _get_webhook_doc_url(webhook_name: str, webhook_path: str) -> str:
327
+ """Returns the anchor to a given webhook in the docs (experimental)"""
328
+ return "/docs#/default/" + webhook_name + webhook_path.replace("/", "_") + "_post"
329
+
330
+
331
+ def _wrap_webhook_to_check_secret(func: Callable, webhook_secret: str) -> Callable:
332
+ """Wraps a webhook function to check the webhook secret before calling the function.
333
+
334
+ This is a hacky way to add the `request` parameter to the function signature. Since FastAPI based itself on route
335
+ parameters to inject the values to the function, we need to hack the function signature to retrieve the `Request`
336
+ object (and hence the headers). A far cleaner solution would be to use a middleware. However, since
337
+ `fastapi==0.90.1`, a middleware cannot be added once the app has started. And since the FastAPI app is started by
338
+ Gradio internals (and not by us), we cannot add a middleware.
339
+
340
+ This method is called only when a secret has been defined by the user. If a request is sent without the
341
+ "x-webhook-secret", the function will return a 401 error (unauthorized). If the header is sent but is incorrect,
342
+ the function will return a 403 error (forbidden).
343
+
344
+ Inspired by https://stackoverflow.com/a/33112180.
345
+ """
346
+ initial_sig = inspect.signature(func)
347
+
348
+ @wraps(func)
349
+ async def _protected_func(request: Request, **kwargs):
350
+ request_secret = request.headers.get("x-webhook-secret")
351
+ if request_secret is None:
352
+ return JSONResponse({"error": "x-webhook-secret header not set."}, status_code=401)
353
+ if request_secret != webhook_secret:
354
+ return JSONResponse({"error": "Invalid webhook secret."}, status_code=403)
355
+
356
+ # Inject `request` in kwargs if required
357
+ if "request" in initial_sig.parameters:
358
+ kwargs["request"] = request
359
+
360
+ # Handle both sync and async routes
361
+ if inspect.iscoroutinefunction(func):
362
+ return await func(**kwargs)
363
+ else:
364
+ return func(**kwargs)
365
+
366
+ # Update signature to include request
367
+ if "request" not in initial_sig.parameters:
368
+ _protected_func.__signature__ = initial_sig.replace( # type: ignore
369
+ parameters=(
370
+ inspect.Parameter(name="request", kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Request),
371
+ )
372
+ + tuple(initial_sig.parameters.values())
373
+ )
374
+
375
+ # Return protected route
376
+ return _protected_func
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from huggingface_hub.cli._output import out # noqa: F401
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_city_game.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Interactive isometric city explorer — easter egg for `hf repos ls --explore`."""
2
+
3
+ import dataclasses
4
+ import math
5
+ import os
6
+ import random
7
+ import re
8
+ import select
9
+ import shutil
10
+ import sys
11
+ import time
12
+
13
+ from huggingface_hub.hf_api import RepoStorageInfo
14
+
15
+ from ._file_listing import format_size
16
+
17
+
18
+ Color = tuple[int, int, int]
19
+
20
+ # (top_face, left_face, right_face) — lighter to darker for 3D effect
21
+ _TYPE_COLORS: dict[str, tuple[Color, Color, Color]] = {
22
+ "model": ((175, 148, 240), (138, 112, 208), (105, 80, 180)),
23
+ "dataset": ((245, 128, 128), (222, 92, 92), (190, 60, 60)),
24
+ "space": ((245, 175, 85), (218, 140, 55), (185, 110, 30)),
25
+ "bucket": ((112, 185, 242), (70, 150, 220), (40, 118, 192)),
26
+ }
27
+ _EXTRA_COLORS: tuple[Color, Color, Color] = ((168, 176, 188), (128, 136, 148), (90, 98, 110))
28
+ _GRID_COLOR: Color = (178, 182, 190)
29
+
30
+ _DX = 4 # isometric half-width (pixels)
31
+ _DY = 2 # isometric half-height (pixels)
32
+ _MAX_H = 16 # tallest tile (pixels)
33
+ _MIN_H = 1
34
+ _COLS = 6
35
+ _EXT = 1 # grid extension beyond tiles
36
+ _MAX_TILES = 30
37
+
38
+ # Cursor sprite — pixel art arrow pointer
39
+ _OUTLINE: Color = (30, 30, 30)
40
+ _FILL: Color = (255, 255, 255)
41
+
42
+ _CURSOR_GRID = [
43
+ " X ",
44
+ " XWX ",
45
+ "XWWWX",
46
+ " XWX ",
47
+ " X ",
48
+ ]
49
+ _CURSOR_PALETTE: dict[str, Color] = {
50
+ "X": _OUTLINE,
51
+ "W": _FILL,
52
+ }
53
+ _CURSOR_H = len(_CURSOR_GRID)
54
+
55
+ _MOVE_FRAMES = 8
56
+ _MOVE_DELAY = 0.03
57
+ _CURSOR_PAD = _CURSOR_H + 16
58
+ _GAP = 3
59
+ _MIN_TERM_W = 100
60
+ _MIN_TERM_H = 24
61
+ _SUMMARY_W = 24
62
+
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # Data structures
66
+ # ---------------------------------------------------------------------------
67
+
68
+
69
+ @dataclasses.dataclass
70
+ class TileInfo:
71
+ grid_row: int
72
+ grid_col: int
73
+ height: int
74
+ top: Color
75
+ left: Color
76
+ right: Color
77
+ repo: RepoStorageInfo | None
78
+
79
+
80
+ @dataclasses.dataclass
81
+ class CityData:
82
+ tiles: list[TileInfo]
83
+ rows: int
84
+ cols: int
85
+ x_off: int
86
+ y_off: int
87
+ buf_w: int
88
+ buf_h: int
89
+ total_storage: int
90
+ extra_count: int
91
+ extra_storage: int
92
+ all_repos: list[RepoStorageInfo]
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # City layout
97
+ # ---------------------------------------------------------------------------
98
+
99
+
100
+ def _prepare_city_data(repos: list[RepoStorageInfo]) -> CityData:
101
+ sorted_repos = sorted(repos, key=lambda r: r.storage, reverse=True)
102
+ display = sorted_repos[:_MAX_TILES]
103
+ extra_count = max(0, len(sorted_repos) - _MAX_TILES)
104
+ extra_storage = sum(r.storage for r in sorted_repos[_MAX_TILES:])
105
+ total_storage = sum(r.storage for r in repos)
106
+ max_storage = max(1, display[0].storage)
107
+
108
+ n = len(display) + (1 if extra_count > 0 else 0)
109
+ cols = min(n, _COLS)
110
+ rows = math.ceil(n / cols) if cols > 0 else 1
111
+
112
+ tiles: list[TileInfo] = []
113
+ for i, repo in enumerate(display):
114
+ r, c = divmod(i, cols)
115
+ h = max(_MIN_H, round(math.sqrt(repo.storage / max_storage) * _MAX_H))
116
+ top, left, right = _TYPE_COLORS.get(repo.type, _EXTRA_COLORS)
117
+ tiles.append(TileInfo(r, c, h, top, left, right, repo))
118
+ if extra_count > 0:
119
+ r, c = divmod(len(display), cols)
120
+ h = max(_MIN_H, round(math.sqrt(extra_storage / max_storage) * _MAX_H))
121
+ tiles.append(TileInfo(r, c, h, *_EXTRA_COLORS, None))
122
+
123
+ r_lo, r_hi = -_EXT, rows - 1 + _EXT
124
+ c_lo, c_hi = -_EXT, cols - 1 + _EXT
125
+
126
+ xs: list[int] = []
127
+ ys: list[int] = []
128
+ for rr in range(r_lo, r_hi + 1):
129
+ for cc in range(c_lo, c_hi + 1):
130
+ cx, cy = (cc - rr) * _DX, (cc + rr) * _DY
131
+ xs.extend([cx - _DX, cx + _DX])
132
+ ys.extend([cy, cy + 2 * _DY])
133
+ for tile in tiles:
134
+ ys.append((tile.grid_col + tile.grid_row) * _DY - tile.height)
135
+
136
+ x_off = -min(xs)
137
+ y_off = -min(ys)
138
+ buf_w = max(xs) - min(xs) + 1
139
+ buf_h = max(ys) - min(ys) + 1
140
+ if buf_h % 2:
141
+ buf_h += 1
142
+
143
+ return CityData(
144
+ tiles=tiles,
145
+ rows=rows,
146
+ cols=cols,
147
+ x_off=x_off,
148
+ y_off=y_off,
149
+ buf_w=buf_w,
150
+ buf_h=buf_h,
151
+ total_storage=total_storage,
152
+ extra_count=extra_count,
153
+ extra_storage=extra_storage,
154
+ all_repos=repos,
155
+ )
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # Drawing primitives
160
+ # ---------------------------------------------------------------------------
161
+
162
+
163
+ def _draw_diamond_outline(buf: list[list[Color | None]], cx: int, cy: int) -> None:
164
+ t = (cx, cy)
165
+ r = (cx + _DX, cy + _DY)
166
+ b = (cx, cy + 2 * _DY)
167
+ ll = (cx - _DX, cy + _DY)
168
+ _draw_line(buf, *t, *r, _GRID_COLOR)
169
+ _draw_line(buf, *r, *b, _GRID_COLOR)
170
+ _draw_line(buf, *b, *ll, _GRID_COLOR)
171
+ _draw_line(buf, *ll, *t, _GRID_COLOR)
172
+
173
+
174
+ def _draw_block(
175
+ buf: list[list[Color | None]],
176
+ cx: int,
177
+ cy: int,
178
+ h: int,
179
+ top: Color,
180
+ left: Color,
181
+ right: Color,
182
+ ) -> None:
183
+ _fill_poly(
184
+ buf,
185
+ [(cx - _DX, cy + _DY - h), (cx, cy + 2 * _DY - h), (cx, cy + 2 * _DY), (cx - _DX, cy + _DY)],
186
+ left,
187
+ )
188
+ _fill_poly(
189
+ buf,
190
+ [(cx, cy + 2 * _DY - h), (cx + _DX, cy + _DY - h), (cx + _DX, cy + _DY), (cx, cy + 2 * _DY)],
191
+ right,
192
+ )
193
+ _fill_poly(
194
+ buf,
195
+ [(cx, cy - h), (cx + _DX, cy + _DY - h), (cx, cy + 2 * _DY - h), (cx - _DX, cy + _DY - h)],
196
+ top,
197
+ )
198
+
199
+
200
+ def _fill_poly(buf: list[list[Color | None]], verts: list[tuple[int, int]], color: Color) -> None:
201
+ bh = len(buf)
202
+ bw = len(buf[0]) if buf else 0
203
+ all_y = [v[1] for v in verts]
204
+ y0 = max(0, min(all_y))
205
+ y1 = min(bh - 1, max(all_y))
206
+ n = len(verts)
207
+ for y in range(y0, y1 + 1):
208
+ xl: float = float("inf")
209
+ xr: float = float("-inf")
210
+ for i in range(n):
211
+ ax, ay = verts[i]
212
+ bx, by = verts[(i + 1) % n]
213
+ if ay == by:
214
+ if y == ay:
215
+ xl = min(xl, float(min(ax, bx)))
216
+ xr = max(xr, float(max(ax, bx)))
217
+ continue
218
+ if not (min(ay, by) <= y <= max(ay, by)):
219
+ continue
220
+ t = (y - ay) / (by - ay)
221
+ ix = ax + t * (bx - ax)
222
+ xl = min(xl, ix)
223
+ xr = max(xr, ix)
224
+ if xl <= xr:
225
+ for x in range(max(0, round(xl)), min(bw, round(xr) + 1)):
226
+ buf[y][x] = color
227
+
228
+
229
+ def _draw_line(buf: list[list[Color | None]], x0: int, y0: int, x1: int, y1: int, color: Color) -> None:
230
+ bh = len(buf)
231
+ bw = len(buf[0]) if buf else 0
232
+ dx = abs(x1 - x0)
233
+ dy = abs(y1 - y0)
234
+ steps = max(dx, dy)
235
+ if steps == 0:
236
+ if 0 <= y0 < bh and 0 <= x0 < bw:
237
+ buf[y0][x0] = color
238
+ return
239
+ xi = (x1 - x0) / steps
240
+ yi = (y1 - y0) / steps
241
+ fx, fy = float(x0), float(y0)
242
+ for _ in range(steps + 1):
243
+ px, py = round(fx), round(fy)
244
+ if 0 <= py < bh and 0 <= px < bw:
245
+ buf[py][px] = color
246
+ fx += xi
247
+ fy += yi
248
+
249
+
250
+ # ---------------------------------------------------------------------------
251
+ # Pixel buffer → terminal
252
+ # ---------------------------------------------------------------------------
253
+
254
+ _ANSI_RE = re.compile(r"\033\[[0-9;]*m")
255
+
256
+
257
+ def _strip_ansi(s: str) -> str:
258
+ return _ANSI_RE.sub("", s)
259
+
260
+
261
+ def _visible_len(s: str) -> int:
262
+ return len(_strip_ansi(s))
263
+
264
+
265
+ def _pixels_to_lines(buf: list[list[Color | None]]) -> list[str]:
266
+ height = len(buf)
267
+ width = len(buf[0]) if buf else 0
268
+ lines: list[str] = []
269
+ for row in range(0, height, 2):
270
+ last = -1
271
+ for col in range(width - 1, -1, -1):
272
+ top = buf[row][col]
273
+ bot = buf[row + 1][col] if row + 1 < height else None
274
+ if top or bot:
275
+ last = col
276
+ break
277
+ if last < 0:
278
+ lines.append("")
279
+ continue
280
+
281
+ parts: list[str] = []
282
+ cfg: Color | None = None
283
+ cbg: Color | None = None
284
+
285
+ for col in range(last + 1):
286
+ top = buf[row][col]
287
+ bot = buf[row + 1][col] if row + 1 < height else None
288
+
289
+ if not top and not bot:
290
+ if cfg is not None or cbg is not None:
291
+ parts.append("\033[0m")
292
+ cfg = cbg = None
293
+ parts.append(" ")
294
+ continue
295
+
296
+ if top and bot and top == bot:
297
+ nfg, nbg, ch = top, None, "█"
298
+ elif top and bot:
299
+ nfg, nbg, ch = bot, top, "▄"
300
+ elif top:
301
+ nfg, nbg, ch = top, None, "▀"
302
+ else:
303
+ nfg, nbg, ch = bot, None, "▄" # type: ignore[assignment]
304
+
305
+ esc = ""
306
+ if nfg != cfg:
307
+ esc += f"\033[38;2;{nfg[0]};{nfg[1]};{nfg[2]}m"
308
+ cfg = nfg
309
+ if nbg != cbg:
310
+ esc += "\033[49m" if nbg is None else f"\033[48;2;{nbg[0]};{nbg[1]};{nbg[2]}m"
311
+ cbg = nbg
312
+ parts.append(esc + ch)
313
+
314
+ if cfg is not None or cbg is not None:
315
+ parts.append("\033[0m")
316
+ lines.append("".join(parts))
317
+ return lines
318
+
319
+
320
+ # ---------------------------------------------------------------------------
321
+ # Rendering
322
+ # ---------------------------------------------------------------------------
323
+
324
+
325
+ def _render_base_buffer(city: CityData) -> list[list[Color | None]]:
326
+ buf: list[list[Color | None]] = [[None] * city.buf_w for _ in range(city.buf_h)]
327
+
328
+ for tile in city.tiles:
329
+ cx = city.x_off + (tile.grid_col - tile.grid_row) * _DX
330
+ cy = city.y_off + (tile.grid_col + tile.grid_row) * _DY
331
+ _draw_diamond_outline(buf, cx, cy)
332
+
333
+ sorted_tiles = sorted(city.tiles, key=lambda t: (t.grid_row + t.grid_col, t.grid_col))
334
+ for tile in sorted_tiles:
335
+ cx = city.x_off + (tile.grid_col - tile.grid_row) * _DX
336
+ cy = city.y_off + (tile.grid_col + tile.grid_row) * _DY
337
+ _draw_block(buf, cx, cy, tile.height, tile.top, tile.left, tile.right)
338
+
339
+ return buf
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # Summary panel
344
+ # ---------------------------------------------------------------------------
345
+
346
+
347
+ def _colored_square(color: Color) -> str:
348
+ return f"\033[38;2;{color[0]};{color[1]};{color[2]}m■\033[0m"
349
+
350
+
351
+ def _build_summary(
352
+ repos: list[RepoStorageInfo],
353
+ total_storage: int,
354
+ extra_count: int,
355
+ ) -> list[str]:
356
+ lines: list[str] = [""]
357
+ lines.append(" Storage Overview")
358
+ lines.append(" " + "─" * 16)
359
+ lines.append(f" {format_size(total_storage, human_readable=True)} total")
360
+ lines.append("")
361
+
362
+ order = ["model", "dataset", "space", "bucket"]
363
+ labels = {"model": "Models", "dataset": "Datasets", "space": "Spaces", "bucket": "Buckets"}
364
+ for rtype in order:
365
+ group = [r for r in repos if r.type == rtype]
366
+ if not group:
367
+ continue
368
+ storage = sum(r.storage for r in group)
369
+ sq = _colored_square(_TYPE_COLORS[rtype][0])
370
+ lines.append(f" {sq} {labels[rtype]}")
371
+ lines.append(f" {len(group)} repos · {format_size(storage, human_readable=True)}")
372
+ lines.append("")
373
+
374
+ if extra_count > 0:
375
+ sq = _colored_square(_EXTRA_COLORS[0])
376
+ lines.append(f" {sq} +{extra_count} more repos")
377
+
378
+ return lines
379
+
380
+
381
+ # ---------------------------------------------------------------------------
382
+ # Cursor
383
+ # ---------------------------------------------------------------------------
384
+
385
+
386
+ def _build_cursor() -> list[tuple[int, int, Color]]:
387
+ pixels: list[tuple[int, int, Color]] = []
388
+ for ri, row in enumerate(_CURSOR_GRID):
389
+ for ci, ch in enumerate(row):
390
+ if ch in _CURSOR_PALETTE:
391
+ pixels.append((ci - len(row) // 2, ri - _CURSOR_H + 1, _CURSOR_PALETTE[ch]))
392
+ return pixels
393
+
394
+
395
+ _CURSOR_PIXELS = _build_cursor()
396
+
397
+
398
+ # ---------------------------------------------------------------------------
399
+ # Interactive game
400
+ # ---------------------------------------------------------------------------
401
+
402
+
403
+ def run_city_game(repos: list[RepoStorageInfo]) -> None:
404
+ """Launch the interactive city explorer."""
405
+ if not repos:
406
+ print("No repositories found.")
407
+ return
408
+
409
+ try:
410
+ import termios
411
+ import tty
412
+ except ImportError:
413
+ print("Interactive mode requires a Unix-like terminal (Linux/macOS).")
414
+ return
415
+
416
+ if not sys.stdin.isatty() or not sys.stdout.isatty():
417
+ print("Interactive mode requires a terminal.")
418
+ return
419
+
420
+ term = shutil.get_terminal_size()
421
+ if term.columns < _MIN_TERM_W or term.lines < _MIN_TERM_H:
422
+ print(f"Your terminal is {term.columns}×{term.lines} characters.")
423
+ print(f"Please resize to at least {_MIN_TERM_W}×{_MIN_TERM_H} to explore the city!")
424
+ return
425
+
426
+ city = _prepare_city_data(repos)
427
+
428
+ tiles_with_repos = [t for t in city.tiles if t.repo is not None]
429
+ start_tile = random.choice(tiles_with_repos) if tiles_with_repos else city.tiles[0]
430
+
431
+ fd = sys.stdin.fileno()
432
+ old_settings = termios.tcgetattr(fd)
433
+ try:
434
+ tty.setraw(fd)
435
+ sys.stdout.write("\033[?1049h\033[?25l\033[2J")
436
+ sys.stdout.flush()
437
+ _game_loop(city, start_tile.grid_row, start_tile.grid_col)
438
+ finally:
439
+ sys.stdout.write("\033[?25h\033[?1049l")
440
+ sys.stdout.flush()
441
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
442
+
443
+
444
+ def _game_loop(city: CityData, cur_row: int, cur_col: int) -> None:
445
+ tile_map: dict[tuple[int, int], TileInfo] = {(t.grid_row, t.grid_col): t for t in city.tiles}
446
+ city = dataclasses.replace(city, buf_h=city.buf_h + _CURSOR_PAD, y_off=city.y_off + _CURSOR_PAD)
447
+ base_buf = _render_base_buffer(city)
448
+
449
+ summary = _build_summary(city.all_repos, city.total_storage, city.extra_count)
450
+
451
+ # Intro: cursor drops onto starting tile
452
+ tx, ty = _tile_top_center(city, cur_row, cur_col, tile_map)
453
+ for i in range(1, _MOVE_FRAMES + 1):
454
+ t = i / _MOVE_FRAMES
455
+ t = t * t * (3 - 2 * t)
456
+ drop_y = ty - 16 * (1 - t)
457
+ frame = _copy_buf(base_buf)
458
+ _highlight_tile(frame, city, tile_map[(cur_row, cur_col)])
459
+ _draw_cursor(frame, tx, round(drop_y))
460
+ _present(city, frame, tile_map.get((cur_row, cur_col)), summary)
461
+ time.sleep(_MOVE_DELAY)
462
+
463
+ while True:
464
+ cx, cy = _tile_top_center(city, cur_row, cur_col, tile_map)
465
+ frame = _copy_buf(base_buf)
466
+ _highlight_tile(frame, city, tile_map[(cur_row, cur_col)])
467
+ _draw_cursor(frame, cx, cy)
468
+ _present(city, frame, tile_map.get((cur_row, cur_col)), summary)
469
+
470
+ key = _read_key()
471
+ if key in ("q", "Q", "esc", "\x03"):
472
+ return
473
+
474
+ dr, dc = _key_to_direction(key)
475
+ if dr == 0 and dc == 0:
476
+ continue
477
+
478
+ nr, nc = cur_row + dr, cur_col + dc
479
+ if (nr, nc) not in tile_map:
480
+ continue
481
+
482
+ ex, ey = _tile_top_center(city, nr, nc, tile_map)
483
+ for i in range(1, _MOVE_FRAMES + 1):
484
+ t = i / _MOVE_FRAMES
485
+ t = t * t * (3 - 2 * t)
486
+ bx = cx + (ex - cx) * t
487
+ by = cy + (ey - cy) * t
488
+ frame = _copy_buf(base_buf)
489
+ _highlight_tile(frame, city, tile_map[(nr, nc)])
490
+ _draw_cursor(frame, round(bx), round(by))
491
+ _present(city, frame, tile_map.get((nr, nc)), summary)
492
+ time.sleep(_MOVE_DELAY)
493
+
494
+ cur_row, cur_col = nr, nc
495
+
496
+
497
+ def _tile_top_center(city: CityData, row: int, col: int, tile_map: dict[tuple[int, int], TileInfo]) -> tuple[int, int]:
498
+ tile = tile_map.get((row, col))
499
+ h = tile.height if tile else 1
500
+ cx = city.x_off + (col - row) * _DX
501
+ cy = city.y_off + (col + row) * _DY
502
+ return cx, cy + _DY - h
503
+
504
+
505
+ def _key_to_direction(key: str) -> tuple[int, int]:
506
+ match key:
507
+ case "w" | "W" | "\x1b[A":
508
+ return -1, 0
509
+ case "s" | "S" | "\x1b[B":
510
+ return 1, 0
511
+ case "a" | "A" | "\x1b[D":
512
+ return 0, -1
513
+ case "d" | "D" | "\x1b[C":
514
+ return 0, 1
515
+ case _:
516
+ return 0, 0
517
+
518
+
519
+ def _draw_cursor(buf: list[list[Color | None]], cx: int, cy: int) -> None:
520
+ bh = len(buf)
521
+ bw = len(buf[0]) if buf else 0
522
+ for dx, dy, color in _CURSOR_PIXELS:
523
+ px, py = cx + dx, cy + dy
524
+ if 0 <= py < bh and 0 <= px < bw:
525
+ buf[py][px] = color
526
+
527
+
528
+ def _highlight_tile(buf: list[list[Color | None]], city: CityData, tile: TileInfo) -> None:
529
+ cx = city.x_off + (tile.grid_col - tile.grid_row) * _DX
530
+ cy = city.y_off + (tile.grid_col + tile.grid_row) * _DY
531
+ h = tile.height
532
+ _fill_poly(
533
+ buf,
534
+ [(cx, cy - h), (cx + _DX, cy + _DY - h), (cx, cy + 2 * _DY - h), (cx - _DX, cy + _DY - h)],
535
+ _brighten(tile.top, 35),
536
+ )
537
+
538
+
539
+ def _brighten(color: Color, amount: int) -> Color:
540
+ return (min(255, color[0] + amount), min(255, color[1] + amount), min(255, color[2] + amount))
541
+
542
+
543
+ def _present(
544
+ city: CityData,
545
+ buf: list[list[Color | None]],
546
+ tile: TileInfo | None,
547
+ summary: list[str],
548
+ ) -> None:
549
+ city_lines = _pixels_to_lines(buf)
550
+ while city_lines and not _strip_ansi(city_lines[0]).strip():
551
+ city_lines.pop(0)
552
+ while city_lines and not _strip_ansi(city_lines[-1]).strip():
553
+ city_lines.pop()
554
+
555
+ city_w = max((_visible_len(line) for line in city_lines), default=0)
556
+ term = shutil.get_terminal_size()
557
+ panel_max_w = max(20, term.columns - city_w - _SUMMARY_W - 2 * _GAP)
558
+
559
+ info = _build_info_panel(tile, city, panel_max_w)
560
+
561
+ n = max(len(summary), len(city_lines), len(info))
562
+ summary_lo = max(0, (n - len(summary)) // 2)
563
+ info_lo = max(0, (n - len(info)) // 2)
564
+
565
+ lines: list[str] = []
566
+ for i in range(n):
567
+ si = i - summary_lo
568
+ lt = summary[si] if 0 <= si < len(summary) else ""
569
+ lpad = max(0, _SUMMARY_W - _visible_len(lt))
570
+
571
+ ct = city_lines[i] if i < len(city_lines) else ""
572
+ cpad = max(0, city_w - _visible_len(ct))
573
+
574
+ ri = i - info_lo
575
+ rt = info[ri] if 0 <= ri < len(info) else ""
576
+
577
+ lines.append(lt + " " * lpad + " " * _GAP + ct + " " * cpad + " " * _GAP + rt)
578
+
579
+ lines.append("")
580
+ lines.append(" \033[90mWASD/Arrows: move · Q/ESC: quit\033[0m")
581
+
582
+ while len(lines) < term.lines - 1:
583
+ lines.append("")
584
+
585
+ output = "\033[H"
586
+ for line in lines[: term.lines - 1]:
587
+ output += line + "\033[K\r\n"
588
+ sys.stdout.write(output)
589
+ sys.stdout.flush()
590
+
591
+
592
+ def _build_info_panel(tile: TileInfo | None, city: CityData, max_w: int) -> list[str]:
593
+ reset = "\033[0m"
594
+ gray = "\033[90m"
595
+ bold = "\033[1m"
596
+ indent = " "
597
+ content_w = max_w - len(indent)
598
+
599
+ lines: list[str] = [""]
600
+ lines.append(f"{indent}{bold}City Explorer{reset}")
601
+ lines.append(indent + "─" * min(22, content_w))
602
+ lines.append("")
603
+
604
+ if tile is None:
605
+ lines.append(f"{indent}{gray}Move to a tile")
606
+ lines.append(f"{indent}to see details.{reset}")
607
+ return lines
608
+
609
+ if tile.repo is None:
610
+ lines.append(f"{indent}{gray}+{city.extra_count} more repos{reset}")
611
+ lines.append(f"{indent}{gray}{format_size(city.extra_storage, human_readable=True)} combined{reset}")
612
+ return lines
613
+
614
+ repo = tile.repo
615
+ name = repo.id
616
+ if len(name) > content_w:
617
+ name = name[: content_w - 3] + "..."
618
+ lines.append(f"{indent}{bold}{name}{reset}")
619
+ lines.append("")
620
+
621
+ type_ansi = {
622
+ "model": "\033[38;2;175;148;240m",
623
+ "dataset": "\033[38;2;245;128;128m",
624
+ "space": "\033[38;2;245;175;85m",
625
+ "bucket": "\033[38;2;112;185;242m",
626
+ }
627
+ tc = type_ansi.get(repo.type, "")
628
+
629
+ lines.append(f"{indent}Type {tc}{repo.type}{reset}")
630
+ lines.append(f"{indent}Visibility {repo.visibility}")
631
+ lines.append(f"{indent}Storage {format_size(repo.storage, human_readable=True)}")
632
+ lines.append(f"{indent}Usage {repo.storage_percent:.1f}%")
633
+ lines.append("")
634
+
635
+ bar_w = min(18, content_w)
636
+ filled = max(0, min(bar_w, round(repo.storage_percent / 100 * bar_w)))
637
+ lines.append(f"{indent}{tc}{'█' * filled}{gray}{'░' * (bar_w - filled)}{reset}")
638
+
639
+ return lines
640
+
641
+
642
+ def _copy_buf(buf: list[list[Color | None]]) -> list[list[Color | None]]:
643
+ return [row[:] for row in buf]
644
+
645
+
646
+ def _read_key() -> str:
647
+ fd = sys.stdin.fileno()
648
+ ch = os.read(fd, 1)
649
+ if ch == b"\x1b":
650
+ if _has_input(fd, 0.05):
651
+ ch2 = os.read(fd, 1)
652
+ if ch2 == b"[" and _has_input(fd, 0.05):
653
+ ch3 = os.read(fd, 1)
654
+ return f"\x1b[{ch3.decode()}"
655
+ return "esc"
656
+ return ch.decode("utf-8", errors="replace")
657
+
658
+
659
+ def _has_input(fd: int, timeout: float) -> bool:
660
+ r, _, _ = select.select([fd], [], [], timeout)
661
+ return bool(r)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_cli_utils.py ADDED
@@ -0,0 +1,1069 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains CLI utilities (styling, helpers)."""
15
+
16
+ import difflib
17
+ import importlib.metadata
18
+ import os
19
+ import re
20
+ import shlex
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from collections.abc import Callable, Sequence
25
+ from enum import Enum
26
+ from pathlib import Path
27
+ from typing import TYPE_CHECKING, Annotated, Any, Literal, TypeVar, cast
28
+
29
+ import click
30
+
31
+ from huggingface_hub import Volume, __version__, constants
32
+ from huggingface_hub.errors import CLIError
33
+ from huggingface_hub.utils import (
34
+ get_session,
35
+ hf_raise_for_status,
36
+ installation_method,
37
+ logging,
38
+ parse_hf_mount,
39
+ )
40
+ from huggingface_hub.utils._dotenv import load_dotenv
41
+
42
+ from ._framework import Argument, HfCommand, HfGroup, Option
43
+ from ._help_formatter import StyledContext
44
+ from ._output import OutputFormat, out
45
+
46
+
47
+ logger = logging.get_logger()
48
+
49
+ # Arbitrary default limit for models/datasets/spaces list commands.
50
+ REPO_LIST_DEFAULT_LIMIT = 30
51
+
52
+ if TYPE_CHECKING:
53
+ from huggingface_hub.hf_api import HfApi
54
+
55
+
56
+ def get_hf_api(token: str | None = None) -> "HfApi":
57
+ # Import here to avoid circular import
58
+ from huggingface_hub.hf_api import HfApi
59
+
60
+ return HfApi(token=token, library_name="huggingface-cli", library_version=__version__)
61
+
62
+
63
+ #### TYPER UTILS
64
+
65
+ CLI_REFERENCE_URL = "https://huggingface.co/docs/huggingface_hub/en/guides/cli"
66
+
67
+
68
+ def generate_epilog(examples: list[str], docs_anchor: str | None = None) -> str:
69
+ """Generate an epilog with examples and a Learn More section.
70
+
71
+ Args:
72
+ examples: List of example commands (without the `$ ` prefix).
73
+ docs_anchor: Optional anchor for the docs URL (e.g., "#hf-download").
74
+
75
+ Returns:
76
+ Formatted epilog string.
77
+ """
78
+ docs_url = f"{CLI_REFERENCE_URL}{docs_anchor}" if docs_anchor else CLI_REFERENCE_URL
79
+ examples_str = "\n".join(f" $ {ex}" for ex in examples)
80
+ return f"""\
81
+ Examples
82
+ {examples_str}
83
+
84
+ Learn more
85
+ Use `hf <command> --help` for more information about a command.
86
+ Read the documentation at {docs_url}
87
+ """
88
+
89
+
90
+ TOPIC_T = Literal["main", "help"] | str
91
+ FallbackHandlerT = Callable[[list[str], set[str]], int | None]
92
+ ExpandPropertyT = TypeVar("ExpandPropertyT", bound=str)
93
+
94
+
95
+ def _format_epilog_no_indent(epilog: str | None, ctx: click.Context, formatter: click.HelpFormatter) -> None:
96
+ """Write the epilog without indentation."""
97
+ if epilog:
98
+ formatter.write_paragraph()
99
+ for line in epilog.split("\n"):
100
+ formatter.write_text(line)
101
+
102
+
103
+ _ALIAS_SPLIT = re.compile(r"\s*\|\s*")
104
+
105
+
106
+ class HFCliTyperGroup(HfGroup):
107
+ """
108
+ CLI Group that:
109
+ - lists commands alphabetically within sections.
110
+ - separates commands by topic (main, help, etc.).
111
+ - formats epilog without extra indentation.
112
+ - supports aliases via pipe-separated names (e.g. ``name="list | ls"``).
113
+ - consumes the global formatting flags (``--format``, ``--json``, ``-q`` / ``--quiet``, ``--no-truncate``)
114
+ anywhere in the args of a leaf command and applies them to ``out``, so leaf
115
+ commands don't need to declare these options themselves.
116
+ - rewrites ``spaces/user/repo`` to ``user/repo --type space`` for commands that accept ``--type``.
117
+ - enriches "No such option" / "No such command" errors with available options or commands.
118
+ """
119
+
120
+ context_class = StyledContext
121
+
122
+ def invoke(self, ctx: click.Context) -> None:
123
+ """Enrich unknown-option errors with available options or subcommands.
124
+
125
+ Catches `NoSuchOption` raised during subcommand `make_context()`
126
+ (option parsing). For leaf commands (e.g. `hf repos create --test`)
127
+ we list the command's options; for groups (e.g. `hf cache --test`)
128
+ we list subcommands since groups have no user-facing options.
129
+ """
130
+ try:
131
+ return super().invoke(ctx)
132
+ except click.NoSuchOption as e:
133
+ if e.ctx is not None and e.ctx.command is not None:
134
+ cmd = e.ctx.command
135
+ if isinstance(cmd, click.Group):
136
+ # Group has no user-facing options -> show subcommands instead
137
+ items = [
138
+ (name, sub.get_short_help_str(limit=80))
139
+ for name in cmd.list_commands(e.ctx)
140
+ if (sub := cmd.get_command(e.ctx, name)) is not None and not sub.hidden
141
+ ]
142
+ _enrich_usage_error(e, "commands", items)
143
+ else:
144
+ # Leaf command -> show its options using Click's rich formatting
145
+ items = [
146
+ record
147
+ for p in cmd.get_params(e.ctx)
148
+ if isinstance(p, click.Option) and not p.hidden and (record := p.get_help_record(e.ctx))
149
+ ]
150
+ _enrich_usage_error(e, "options", items)
151
+ raise
152
+
153
+ def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple:
154
+ cmd_name = args[0] if args and not args[0].startswith("-") else None
155
+ cmd = self.get_command(ctx, cmd_name) if cmd_name else None
156
+
157
+ if cmd is not None:
158
+ self._rewrite_repo_type_prefix(cmd, args)
159
+
160
+ try:
161
+ name, resolved_cmd, sub_args = super().resolve_command(ctx, args)
162
+ except click.UsageError as e:
163
+ # Unknown subcommand -> add fuzzy suggestions and list available commands.
164
+ if cmd is None and cmd_name is not None:
165
+ # Expand aliases ("list | ls" → ["list", "ls"]) for accurate fuzzy matching.
166
+ visible_names = [
167
+ alias
168
+ for key, registered in self.commands.items()
169
+ if not registered.hidden
170
+ for alias in _ALIAS_SPLIT.split(key)
171
+ ]
172
+ matches = difflib.get_close_matches(cmd_name, visible_names)
173
+ if matches:
174
+ suggestions = ", ".join(f"'{m}'" for m in matches)
175
+ setattr(e, "message", f"{e.message.rstrip('.')}. Did you mean {suggestions}?")
176
+ items = [
177
+ (name, sub.get_short_help_str(limit=80))
178
+ for name in self.list_commands(ctx)
179
+ if (sub := self.get_command(ctx, name)) is not None and not sub.hidden
180
+ ]
181
+ _enrich_usage_error(e, "commands", items)
182
+ raise
183
+
184
+ # If we just resolved a leaf command, eagerly consume any global formatting
185
+ # flags (--format / --json / -q / --quiet / --no-truncate) from its args before click parses
186
+ # them. Group resolution is recursive — leaves (and only leaves) need this.
187
+ if resolved_cmd is not None and not isinstance(resolved_cmd, click.Group):
188
+ _consume_format_flags_for_leaf(resolved_cmd, sub_args)
189
+
190
+ return name, resolved_cmd, sub_args
191
+
192
+ @staticmethod
193
+ def _rewrite_repo_type_prefix(cmd: click.Command, args: list[str]) -> None:
194
+ """Rewrite prefixed repo IDs (e.g. ``spaces/user/repo``) to ``user/repo --type space``.
195
+
196
+ Only applies to commands that have a ``--type`` / ``--repo-type`` option and
197
+ at least one repo-ID positional argument (any ``click.Argument`` whose name
198
+ ends with ``_id``, e.g. ``repo_id``, ``from_id``, ``to_id``). When the
199
+ token that maps to such an argument matches ``{prefix}/org/repo`` (where
200
+ *prefix* is one of ``spaces``, ``datasets``, or ``models``), the prefix is
201
+ stripped and an implicit ``--type {type}`` is appended. An error is raised
202
+ if ``--type`` is also provided explicitly or if multiple prefixed arguments
203
+ disagree on the repo type.
204
+
205
+ Only repo-ID positional slots are inspected so that other positional
206
+ arguments (filenames, local paths, patterns …) are never misinterpreted as
207
+ prefixed repo IDs.
208
+ """
209
+ has_type_option = any(isinstance(param, click.Option) and "--type" in param.opts for param in cmd.params)
210
+ if not has_type_option:
211
+ return
212
+
213
+ # Locate all repo-ID positional arguments and their indices among Arguments.
214
+ repo_id_positions: set[int] = set()
215
+ arg_idx = 0
216
+ for param in cmd.params:
217
+ if isinstance(param, click.Argument):
218
+ if param.name in ("repo_id", "from_id", "to_id"):
219
+ repo_id_positions.add(arg_idx)
220
+ arg_idx += 1
221
+
222
+ if not repo_id_positions:
223
+ return
224
+
225
+ # Build a set of option names that consume a following value token.
226
+ value_options: set[str] = set()
227
+ for param in cmd.params:
228
+ if isinstance(param, click.Option) and not param.is_flag:
229
+ for opt in (*param.opts, *param.secondary_opts):
230
+ value_options.add(opt)
231
+
232
+ # Walk through args (skipping args[0] = command name) to map positional
233
+ # slots to their indices in `args`.
234
+ positional_count = 0
235
+ repo_id_arg_indices: list[int] = []
236
+ i = 1
237
+ while i < len(args):
238
+ arg = args[i]
239
+ if arg == "--":
240
+ break # everything after -- is positional literal; stop rewriting
241
+ if arg.startswith("-"):
242
+ if "=" in arg or arg not in value_options:
243
+ i += 1 # flag or --opt=val — single token
244
+ else:
245
+ i += 2 # value-taking option — skip the value too
246
+ else:
247
+ if positional_count in repo_id_positions:
248
+ repo_id_arg_indices.append(i)
249
+ positional_count += 1
250
+ i += 1
251
+
252
+ if not repo_id_arg_indices:
253
+ return
254
+
255
+ # Check each repo-ID arg for a type prefix and collect rewrites.
256
+ inferred_type: str | None = None
257
+ first_prefix: str | None = None
258
+ rewrites: list[tuple[int, str]] = [] # (args index, new value without prefix)
259
+
260
+ for arg_index in repo_id_arg_indices:
261
+ parts = args[arg_index].split("/", 2)
262
+ if len(parts) != 3 or parts[0] not in constants.REPO_TYPES_MAPPING:
263
+ continue
264
+ prefix = parts[0]
265
+ mapped_type = constants.REPO_TYPES_MAPPING[prefix]
266
+ if inferred_type is not None and mapped_type != inferred_type:
267
+ raise click.UsageError(f"Conflicting repo type prefixes: '{first_prefix}/' and '{prefix}/'.")
268
+ inferred_type = mapped_type
269
+ first_prefix = prefix
270
+ rewrites.append((arg_index, f"{parts[1]}/{parts[2]}"))
271
+
272
+ if not rewrites:
273
+ return
274
+
275
+ # Error if --type / --repo-type was also provided explicitly.
276
+ if any(
277
+ arg == "--type" or arg.startswith("--type=") or arg == "--repo-type" or arg.startswith("--repo-type=")
278
+ for arg in args
279
+ ):
280
+ raise click.UsageError(
281
+ f"Ambiguous repo type: got prefix '{first_prefix}/' in repo ID and explicit --type. Use one or the other."
282
+ )
283
+
284
+ # Apply all rewrites and append --type once.
285
+ for arg_index, new_value in rewrites:
286
+ args[arg_index] = new_value
287
+ args.extend(["--type", inferred_type]) # type: ignore
288
+
289
+ def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:
290
+ # Try exact match first
291
+ cmd = super().get_command(ctx, cmd_name)
292
+ if cmd is not None:
293
+ return cmd
294
+ # Fall back to alias lookup: check if cmd_name matches any alias
295
+ # taken from https://github.com/fastapi/typer/issues/132#issuecomment-2417492805
296
+ for registered_name, registered_cmd in self.commands.items():
297
+ aliases = _ALIAS_SPLIT.split(registered_name)
298
+ if cmd_name in aliases:
299
+ return registered_cmd
300
+ return None
301
+
302
+ def _alias_map(self) -> dict[str, list[str]]:
303
+ """Build a mapping from primary command name to its aliases (if any)."""
304
+ result: dict[str, list[str]] = {}
305
+ for registered_name in self.commands:
306
+ parts = _ALIAS_SPLIT.split(registered_name)
307
+ primary = parts[0]
308
+ result[primary] = parts[1:]
309
+ return result
310
+
311
+ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
312
+ topics: dict[str, list] = {}
313
+ alias_map = self._alias_map()
314
+
315
+ for name in self.list_commands(ctx):
316
+ cmd = self.get_command(ctx, name)
317
+ if cmd is None or cmd.hidden:
318
+ continue
319
+ help_text = cmd.get_short_help_str(limit=formatter.width)
320
+ aliases = alias_map.get(name, [])
321
+ if aliases:
322
+ help_text = f"{help_text} [alias: {', '.join(aliases)}]"
323
+ topic = getattr(cmd, "topic", "main")
324
+ topics.setdefault(topic, []).append((name, help_text))
325
+
326
+ with formatter.section("Main commands"):
327
+ formatter.write_dl(topics["main"])
328
+ for topic in sorted(topics.keys()):
329
+ if topic == "main":
330
+ continue
331
+ with formatter.section(f"{topic.capitalize()} commands"):
332
+ formatter.write_dl(topics[topic])
333
+
334
+ def format_epilog(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
335
+ # Collect only the first example from each command (to keep group help concise)
336
+ # Full examples are shown in individual subcommand help (e.g. `hf buckets sync --help`)
337
+ all_examples: list[str] = []
338
+ for name in self.list_commands(ctx):
339
+ cmd = self.get_command(ctx, name)
340
+ if cmd is None or cmd.hidden:
341
+ continue
342
+ cmd_examples = getattr(cmd, "examples", [])
343
+ if cmd_examples:
344
+ all_examples.append(cmd_examples[0])
345
+
346
+ if all_examples:
347
+ epilog = generate_epilog(all_examples)
348
+ _format_epilog_no_indent(epilog, ctx, formatter)
349
+ elif self.epilog:
350
+ _format_epilog_no_indent(self.epilog, ctx, formatter)
351
+
352
+ def list_commands(self, ctx: click.Context) -> list[str]: # type: ignore[name-defined]
353
+ # For aliased commands ("list | ls"), use the primary name (first entry).
354
+ primary_names: list[str] = []
355
+ for name in self.commands:
356
+ primary = _ALIAS_SPLIT.split(name)[0]
357
+ primary_names.append(primary)
358
+ return sorted(primary_names)
359
+
360
+ def command( # type: ignore # adds topic/examples on top of HfGroup.command
361
+ self,
362
+ name: str | None = None,
363
+ *,
364
+ topic: TOPIC_T = "main",
365
+ examples: list[str] | None = None,
366
+ epilog: str | None = None,
367
+ **kwargs: Any,
368
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
369
+ # Generate the epilog from examples when not provided explicitly, then build the
370
+ # command with a topic/examples-aware command class.
371
+ if epilog is None and examples:
372
+ epilog = generate_epilog(examples)
373
+ return super().command(name, cls=HFCliCommand(topic, examples), epilog=epilog, **kwargs)
374
+
375
+
376
+ _FORMATTING_OPTIONS_HELP_RECORDS: list[tuple[str, str]] = [
377
+ (
378
+ "--format [auto|human|agent|json|quiet]",
379
+ "Output format. Defaults to 'auto' which picks 'agent' or 'human' based on the terminal.",
380
+ ),
381
+ ("--json", "JSON output. Equivalent to '--format json'."),
382
+ ("-q, --quiet", "Quiet output (one ID per line). Equivalent to '--format quiet'."),
383
+ ("--no-truncate", "Do not truncate scalar values in human tables (list/dict columns stay shortened)."),
384
+ ]
385
+
386
+
387
+ def _format_formatting_options_section(formatter: click.HelpFormatter) -> None:
388
+ with formatter.section("Formatting options"):
389
+ formatter.write_dl(_FORMATTING_OPTIONS_HELP_RECORDS)
390
+
391
+
392
+ def _has_local_formatting_option(cmd: click.Command) -> bool:
393
+ """Return True if the command defines its own --format, --json or --quiet / -q.
394
+
395
+ Used to skip the global formatting flag pre-processor and the duplicated "Formatting options" help section for
396
+ legacy commands like 'hf jobs ls' that have their own format/quiet options.
397
+ """
398
+ for param in cmd.params:
399
+ if not isinstance(param, click.Option):
400
+ continue
401
+ opts = (*param.opts, *param.secondary_opts)
402
+ if "--format" in opts or "--json" in opts or "--quiet" in opts or "-q" in opts:
403
+ return True
404
+ return False
405
+
406
+
407
+ def _consume_format_flags_for_leaf(cmd: click.Command, args: list[str]) -> None:
408
+ """Apply global formatting flags from 'args' to a leaf command.
409
+
410
+ Two modes, depending on the command:
411
+
412
+ * **Pass-through commands** (ignore_unknown_options=True, e.g. 'hf extensions exec'):
413
+ args are forwarded verbatim to an external binary; we don't touch them.
414
+
415
+ * **Legacy commands with a local --format option** (e.g. 'hf jobs ls' whose '--format' accepts Go templates):
416
+ the global flags are rewritten in-place to the legacy form ('--json' → '--format json', '--quiet'/'-q' → '--format quiet'
417
+ when the cmd has no own '--quiet') so click can parse them locally. This preserves backwards compatibility with the previous shorthand behavior.
418
+
419
+ * **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'.
420
+
421
+ '--no-truncate' is stripped for all non-pass-through commands; when present, human table cells are not truncated.
422
+
423
+ Raises click.UsageError if multiple conflicting flags are supplied (e.g. '--json' together with '--format table').
424
+ """
425
+ if cmd.context_settings.get("ignore_unknown_options"):
426
+ return
427
+
428
+ no_truncate = _consume_no_truncate_flags(args)
429
+ out.set_no_truncate(no_truncate)
430
+
431
+ has_local_format = False
432
+ has_local_quiet = False
433
+ has_local_json = False
434
+ for param in cmd.params:
435
+ if not isinstance(param, click.Option):
436
+ continue
437
+ opts = (*param.opts, *param.secondary_opts)
438
+ if "--format" in opts:
439
+ has_local_format = True
440
+ if "--quiet" in opts or "-q" in opts:
441
+ has_local_quiet = True
442
+ if "--json" in opts:
443
+ has_local_json = True
444
+
445
+ if has_local_format:
446
+ _rewrite_legacy_shorthands(args, rewrite_json=not has_local_json, rewrite_quiet=not has_local_quiet)
447
+ return
448
+
449
+ # Strip --format/--json/-q/--quiet from 'args' and apply to 'out'
450
+ chosen_mode: OutputFormat = OutputFormat.auto
451
+ chosen_flag: str | None = None
452
+
453
+ def _check_conflict(new_flag: str) -> None:
454
+ # Reject any second formatting flag before parsing values, so the user gets
455
+ # a "mutually exclusive" error rather than e.g. an "invalid value" error
456
+ # from the second flag's argument.
457
+ if chosen_flag is not None:
458
+ raise click.UsageError(f"'{chosen_flag}' and '{new_flag}' are mutually exclusive.")
459
+
460
+ i = 0
461
+ while i < len(args):
462
+ arg = args[i]
463
+ if arg == "--":
464
+ break # everything after '--' is a positional literal
465
+ if arg == "--format":
466
+ _check_conflict("--format")
467
+ if i + 1 >= len(args):
468
+ raise click.UsageError("Option '--format' requires a value.")
469
+ chosen_mode = _parse_format_value(args[i + 1])
470
+ chosen_flag = "--format"
471
+ del args[i : i + 2] # --format value => 2 args removed
472
+ continue
473
+ if arg.startswith("--format="):
474
+ _check_conflict("--format")
475
+ chosen_mode = _parse_format_value(arg[len("--format=") :])
476
+ chosen_flag = "--format"
477
+ del args[i : i + 1]
478
+ continue
479
+ if arg == "--json":
480
+ _check_conflict("--json")
481
+ chosen_mode = OutputFormat.json
482
+ chosen_flag = "--json"
483
+ del args[i : i + 1]
484
+ continue
485
+ if arg in ("-q", "--quiet"):
486
+ _check_conflict(arg)
487
+ chosen_mode = OutputFormat.quiet
488
+ chosen_flag = arg
489
+ del args[i : i + 1]
490
+ continue
491
+ i += 1
492
+
493
+ out.set_mode(chosen_mode)
494
+
495
+
496
+ def _consume_no_truncate_flags(args: list[str]) -> bool:
497
+ """Strip all global --no-truncate flags from args and return whether any was provided."""
498
+ no_truncate = False
499
+ i = 0
500
+ while i < len(args):
501
+ arg = args[i]
502
+ if arg == "--":
503
+ break # everything after '--' is a positional literal
504
+ if arg == "--no-truncate":
505
+ no_truncate = True
506
+ del args[i : i + 1]
507
+ continue
508
+ if arg.startswith("--no-truncate="):
509
+ raise click.UsageError("Option '--no-truncate' does not take a value.")
510
+ i += 1
511
+ return no_truncate
512
+
513
+
514
+ def _rewrite_legacy_shorthands(args: list[str], *, rewrite_json: bool, rewrite_quiet: bool) -> None:
515
+ """Rewrite --json / -q / --quiet to --format ... for legacy commands.
516
+
517
+ Used for commands like 'hf jobs ls' that still own their '--format' option.
518
+ The rewrite lets users keep using the global shorthand while click parses
519
+ '--format <value>' locally.
520
+ """
521
+ has_format_in_args = any(arg == "--format" or arg.startswith("--format=") for arg in args)
522
+
523
+ if rewrite_json and "--json" in args:
524
+ if has_format_in_args:
525
+ raise click.UsageError("'--json' and '--format' are mutually exclusive.")
526
+ idx = args.index("--json")
527
+ args[idx : idx + 1] = ["--format", "json"]
528
+ has_format_in_args = True
529
+
530
+ if rewrite_quiet:
531
+ flag = "-q" if "-q" in args else ("--quiet" if "--quiet" in args else None)
532
+ if flag is not None:
533
+ if has_format_in_args:
534
+ raise click.UsageError(f"'{flag}' and '--format' are mutually exclusive.")
535
+ idx = args.index(flag)
536
+ args[idx : idx + 1] = ["--format", "quiet"]
537
+
538
+
539
+ def _parse_format_value(value: str) -> "OutputFormat":
540
+ try:
541
+ return OutputFormat(value)
542
+ except ValueError:
543
+ valid = ", ".join(m.value for m in OutputFormat)
544
+ raise click.UsageError(f"Invalid value for '--format': '{value}'. Valid values: {valid}.") from None
545
+
546
+
547
+ def _enrich_usage_error(error: click.UsageError, label: str, items: list[tuple[str, str]]) -> None:
548
+ """Append a list of available options or commands to a usage error message."""
549
+ if not items or error.ctx is None or f"Available {label} for" in error.message:
550
+ return
551
+ cmd_path = error.ctx.command_path
552
+ lines = [f"\n\nAvailable {label} for '{cmd_path}':"]
553
+ for name, help_text in items:
554
+ lines.append(f" {name:30s} {help_text}")
555
+ lines.append(f"\nRun '{cmd_path} --help' for full details.")
556
+ if isinstance(error, click.NoSuchOption) and error.possibilities:
557
+ lines.append(f"\nDid you mean: {', '.join(sorted(error.possibilities))}?")
558
+ setattr(error, "possibilities", [])
559
+ setattr(error, "message", error.message + "\n".join(lines))
560
+
561
+
562
+ def fallback_typer_group_factory(
563
+ fallback_handler: FallbackHandlerT,
564
+ extra_commands_provider: Callable[[], list[tuple[str, str]]] | None = None,
565
+ ) -> type[HFCliTyperGroup]:
566
+ """Return a Typer group class that runs a fallback handler before command resolution."""
567
+
568
+ class FallbackTyperGroup(HFCliTyperGroup):
569
+ def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple:
570
+ fallback_exit_code = fallback_handler(args, set(self.commands.keys()))
571
+ if fallback_exit_code is not None:
572
+ raise SystemExit(fallback_exit_code)
573
+ return super().resolve_command(ctx, args)
574
+
575
+ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
576
+ super().format_commands(ctx, formatter)
577
+ if extra_commands_provider is not None:
578
+ entries = extra_commands_provider()
579
+ if entries:
580
+ with formatter.section("Extension commands"):
581
+ formatter.write_dl(entries)
582
+
583
+ return FallbackTyperGroup
584
+
585
+
586
+ def HFCliCommand(topic: TOPIC_T, examples: list[str] | None = None) -> type[HfCommand]:
587
+ def format_epilog(self: click.Command, ctx: click.Context, formatter: click.HelpFormatter) -> None:
588
+ _format_epilog_no_indent(self.epilog, ctx, formatter)
589
+
590
+ def format_options(self: HfCommand, ctx: click.Context, formatter: click.HelpFormatter) -> None:
591
+ HfCommand.format_options(self, ctx, formatter)
592
+ # Skip the section for commands that define their own --format / --quiet / --json,
593
+ # or for pass-through commands that forward args to an external binary.
594
+ if _has_local_formatting_option(self):
595
+ return
596
+ if self.context_settings.get("ignore_unknown_options"):
597
+ return
598
+ _format_formatting_options_section(formatter)
599
+
600
+ def parse_args(self: click.Command, ctx: click.Context, args: list[str]) -> list[str]:
601
+ # Show help when a command with required arguments is invoked without any args
602
+ # (mirrors group behavior: `hf jobs` prints help, so `hf download` should too).
603
+ if not args and not ctx.resilient_parsing:
604
+ if any(isinstance(p, click.Argument) and p.required for p in self.params):
605
+ click.echo(ctx.get_help(), color=ctx.color)
606
+ ctx.exit()
607
+ return HfCommand.parse_args(self, ctx, args)
608
+
609
+ return type(
610
+ f"HfCommand{topic.capitalize()}",
611
+ (HfCommand,),
612
+ {
613
+ "context_class": StyledContext,
614
+ "topic": topic,
615
+ "examples": examples or [],
616
+ "format_epilog": format_epilog,
617
+ "format_options": format_options,
618
+ "parse_args": parse_args,
619
+ },
620
+ )
621
+
622
+
623
+ def typer_factory(help: str, epilog: str | None = None, cls: type[HFCliTyperGroup] | None = None) -> "HFCliTyperGroup":
624
+ """Create a CLI command group with consistent settings.
625
+
626
+ The returned group is the app: register commands with ``@group.command(...)``,
627
+ subgroups with ``group.add_group(sub, name=...)``, and a group-level callback
628
+ with ``@group.callback(...)``.
629
+
630
+ Args:
631
+ help: Help text for the group.
632
+ epilog: Optional epilog text (use `generate_epilog` to create one).
633
+ cls: Optional group class to use (defaults to `HFCliTyperGroup`).
634
+
635
+ Returns:
636
+ A configured `HFCliTyperGroup` instance.
637
+ """
638
+ if cls is None:
639
+ cls = HFCliTyperGroup
640
+ return cls(
641
+ help=help,
642
+ epilog=epilog,
643
+ no_args_is_help=True,
644
+ # Increase max content width for better readability
645
+ context_settings={
646
+ "max_content_width": 120,
647
+ "help_option_names": ["-h", "--help"],
648
+ },
649
+ )
650
+
651
+
652
+ class SoftChoice(click.Choice):
653
+ """A click Choice that suggests choices for autocompletion/docs but accepts any string.
654
+
655
+ Unlike `click.Choice`, unknown values are passed through as-is instead of raising an error.
656
+ This makes CLI options future-compatible when new server-side values are added.
657
+
658
+ Accepts either a sequence of strings or an Enum class:
659
+ ```python
660
+ SoftChoice(SpaceHardware) # from an enum
661
+ SoftChoice(["a", "b", "c"]) # from a list
662
+ ```
663
+ """
664
+
665
+ def __init__(self, choices: Sequence[str] | type[Enum]) -> None:
666
+ values = (
667
+ [m.value for m in choices] if isinstance(choices, type) and issubclass(choices, Enum) else list(choices)
668
+ )
669
+ super().__init__(values, case_sensitive=True)
670
+
671
+ def convert(self, value: Any, param: click.Parameter | None, ctx: click.Context | None) -> str:
672
+ try:
673
+ return super().convert(value, param, ctx)
674
+ except click.exceptions.BadParameter:
675
+ return str(value)
676
+
677
+
678
+ class RepoType(str, Enum):
679
+ model = "model"
680
+ dataset = "dataset"
681
+ space = "space"
682
+
683
+
684
+ RepoIdArg = Annotated[
685
+ str,
686
+ Argument(
687
+ help="The ID of the repo (e.g. `username/repo-name` or `spaces/username/repo-name`).",
688
+ ),
689
+ ]
690
+
691
+
692
+ RepoTypeOpt = Annotated[
693
+ RepoType,
694
+ Option(
695
+ "--type",
696
+ "--repo-type",
697
+ help="The type of repository (model, dataset, or space).",
698
+ ),
699
+ ]
700
+
701
+ # Same as `RepoTypeOpt` but optional (defaults to `None` rather than `model`). Used by commands that
702
+ # accept an `hf://` URI as repo id: a `None` default lets us tell apart "user did not pass --repo-type"
703
+ # from "user explicitly passed --repo-type model", which is required to detect conflicts with the URI.
704
+ RepoTypeOptionalOpt = Annotated[
705
+ RepoType | None,
706
+ Option(
707
+ "--type",
708
+ "--repo-type",
709
+ help="The type of repository (model, dataset, or space).",
710
+ show_default="model",
711
+ ),
712
+ ]
713
+
714
+ TokenOpt = Annotated[
715
+ str | None,
716
+ Option(
717
+ help="A User Access Token generated from https://huggingface.co/settings/tokens.",
718
+ ),
719
+ ]
720
+
721
+ PrivateOpt = Annotated[
722
+ bool | None,
723
+ Option(
724
+ help="Whether to create a private repo if repo doesn't exist on the Hub. Ignored if the repo already exists.",
725
+ ),
726
+ ]
727
+
728
+ RevisionOpt = Annotated[
729
+ str | None,
730
+ Option(
731
+ help="Git revision id which can be a branch name, a tag, or a commit hash.",
732
+ ),
733
+ ]
734
+
735
+
736
+ LimitOpt = Annotated[
737
+ int,
738
+ Option(help="Limit the number of results."),
739
+ ]
740
+
741
+ AuthorOpt = Annotated[
742
+ str | None,
743
+ Option(help="Filter by author or organization."),
744
+ ]
745
+
746
+ FilterOpt = Annotated[
747
+ list[str] | None,
748
+ Option(help="Filter by tags (e.g. 'text-classification'). Can be used multiple times."),
749
+ ]
750
+
751
+ SearchOpt = Annotated[
752
+ str | None,
753
+ Option(help="Search query."),
754
+ ]
755
+
756
+
757
+ # --- Env / Secrets shared options and parsing helpers (used by jobs, repos, etc.) ---
758
+
759
+ EnvOpt = Annotated[
760
+ list[str] | None,
761
+ Option(
762
+ "-e",
763
+ "--env",
764
+ help="Set environment variables. E.g. --env ENV=value",
765
+ ),
766
+ ]
767
+
768
+ SecretsOpt = Annotated[
769
+ list[str] | None,
770
+ Option(
771
+ "-s",
772
+ "--secrets",
773
+ help=(
774
+ "Set secret environment variables. E.g. --secrets SECRET=value"
775
+ " or `--secrets HF_TOKEN` to pass your Hugging Face token."
776
+ ),
777
+ ),
778
+ ]
779
+
780
+ EnvFileOpt = Annotated[
781
+ str | None,
782
+ Option(
783
+ "--env-file",
784
+ help="Read in a file of environment variables.",
785
+ ),
786
+ ]
787
+
788
+ SecretsFileOpt = Annotated[
789
+ str | None,
790
+ Option(
791
+ help="Read in a file of secret environment variables.",
792
+ ),
793
+ ]
794
+
795
+
796
+ def _get_extended_environ() -> dict[str, str]:
797
+ """Return a copy of ``os.environ`` with the user's HF token injected (if available)."""
798
+ from huggingface_hub import get_token
799
+
800
+ extended_environ = os.environ.copy()
801
+ if (token := get_token()) is not None:
802
+ extended_environ["HF_TOKEN"] = token
803
+ return extended_environ
804
+
805
+
806
+ def parse_env_map(
807
+ env: list[str] | None = None,
808
+ env_file: str | None = None,
809
+ ) -> dict[str, str | None]:
810
+ """Parse ``-e``/``--env``/``-s``/``--secrets`` and ``--env-file``/``--secrets-file`` CLI args into a dict.
811
+
812
+ Uses an extended environment that includes the user's HF token so that
813
+ bare ``--secrets HF_TOKEN`` resolves correctly.
814
+ """
815
+ extended_environ = _get_extended_environ()
816
+ env_map: dict[str, str | None] = {}
817
+ if env_file:
818
+ env_map.update(load_dotenv(Path(env_file).read_text(), environ=extended_environ))
819
+ for env_value in env or []:
820
+ env_map.update(load_dotenv(env_value, environ=extended_environ))
821
+ return env_map
822
+
823
+
824
+ def env_map_to_key_value_list(env_map: dict[str, str | None]) -> list[dict[str, str]] | None:
825
+ """Convert an env/secrets dict to the ``[{"key": ..., "value": ...}]`` format used by the Hub API."""
826
+ if not env_map:
827
+ return None
828
+ return [{"key": k, "value": v or ""} for k, v in env_map.items()]
829
+
830
+
831
+ VolumesOpt = Annotated[
832
+ list[str] | None,
833
+ Option(
834
+ "-v",
835
+ "--volume",
836
+ help="Mount one or more volumes. Format: hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]. "
837
+ "TYPE is one of: models, datasets, spaces, buckets. "
838
+ "TYPE defaults to models if omitted. "
839
+ "models, datasets and spaces are always mounted read-only. buckets are read+write by default. "
840
+ "E.g. -v hf://org/m:/data or -v hf://datasets/org/ds:/data or -v hf://buckets/org/b:/mnt:ro",
841
+ ),
842
+ ]
843
+
844
+
845
+ def parse_volumes(volumes: list[str] | None) -> "list[Volume] | None":
846
+ """Parse volume specs from CLI arguments.
847
+
848
+ Format: hf://[TYPE/]SOURCE[/PATH]:/MOUNT_PATH[:ro|:rw]
849
+ Where TYPE is one of: models, datasets, spaces, buckets (defaults to models if omitted).
850
+ SOURCE is the repo/bucket identifier (e.g. 'username/my-model').
851
+ PATH is an optional subfolder inside the repo/bucket.
852
+ MOUNT_PATH starts with '/'.
853
+ Optional ':ro' or ':rw' suffix for read-only or read-write.
854
+
855
+ Examples:
856
+ hf://my-org/my-model:/data (model, implicit type)
857
+ hf://models/my-org/my-model:/data (model, explicit type)
858
+ hf://datasets/my-org/my-dataset:/data:ro
859
+ hf://buckets/my-org/my-bucket:/mnt
860
+ hf://spaces/my-org/my-space:/app
861
+ hf://datasets/org/ds/train:/data (with path inside repo)
862
+ hf://buckets/org/b/sub/dir:/mnt (with path inside bucket)
863
+ """
864
+ if not volumes:
865
+ return None
866
+
867
+ result: list[Volume] = []
868
+ for raw_spec in volumes:
869
+ mount = parse_hf_mount(raw_spec)
870
+ result.append(
871
+ Volume(
872
+ type=mount.source.type,
873
+ source=mount.source.id,
874
+ mount_path=mount.mount_path,
875
+ read_only=mount.read_only,
876
+ path=mount.source.path_in_repo or None,
877
+ revision=mount.source.revision or None,
878
+ )
879
+ )
880
+ return result
881
+
882
+
883
+ def make_expand_properties_parser(valid_properties: Sequence[ExpandPropertyT]):
884
+ """Create a callback to parse and validate comma-separated expand properties."""
885
+
886
+ def _parse_expand_properties(value: str | None) -> list[ExpandPropertyT] | None:
887
+ if value is None:
888
+ return None
889
+ properties = [p.strip() for p in value.split(",")]
890
+ for prop in properties:
891
+ if prop not in valid_properties:
892
+ raise click.BadParameter(
893
+ f"Invalid expand property: '{prop}'. Valid values are: {', '.join(valid_properties)}"
894
+ )
895
+ return [cast(ExpandPropertyT, prop) for prop in properties]
896
+
897
+ return _parse_expand_properties
898
+
899
+
900
+ ### SSH
901
+
902
+
903
+ SshIdentityFileOpt = Annotated[
904
+ Path | None,
905
+ Option("-i", "--identity-file", help="Path to the SSH identity file (forwarded to `ssh -i`)."),
906
+ ]
907
+
908
+ SshDryRunOpt = Annotated[
909
+ bool,
910
+ Option("--dry-run", help="Print the SSH command instead of running it."),
911
+ ]
912
+
913
+
914
+ def exec_ssh(
915
+ destination: str, *, port: int | None = None, identity_file: Path | None = None, dry_run: bool = False
916
+ ) -> None:
917
+ """Run an interactive `ssh` command to `destination` (`user@host`) and exit with its return code.
918
+
919
+ With `dry_run`, print the command instead of running it.
920
+ """
921
+ cmd = ["ssh"]
922
+ if identity_file is not None:
923
+ cmd += ["-i", str(identity_file)]
924
+ if port is not None:
925
+ cmd += ["-p", str(port)]
926
+ cmd.append(destination)
927
+ if dry_run:
928
+ out.text(shlex.join(cmd))
929
+ return
930
+ out.text(f"Running `{shlex.join(cmd)}`")
931
+ result = subprocess.run(cmd)
932
+ raise click.exceptions.Exit(code=result.returncode)
933
+
934
+
935
+ ### PyPI VERSION CHECKER
936
+
937
+
938
+ def check_cli_update(library: Literal["huggingface_hub", "transformers"]) -> None:
939
+ """
940
+ Check whether a newer version of a library is available on PyPI.
941
+
942
+ If a newer version is found, print a hint pointing at `hf update`.
943
+
944
+ 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.
945
+ If `HF_HUB_DISABLE_UPDATE_CHECK` is set, the check is skipped entirely.
946
+
947
+ This function is called at the entry point of the CLI. It only performs the check once every 24 hours, and any error
948
+ during the check is caught and logged, to avoid breaking the CLI.
949
+
950
+ Args:
951
+ library: The library to check for updates. Currently supports "huggingface_hub" and "transformers".
952
+ """
953
+ try:
954
+ _check_cli_update(library)
955
+ except Exception:
956
+ # We don't want the CLI to fail on version checks, no matter the reason.
957
+ logger.debug("Error while checking for CLI update.", exc_info=True)
958
+
959
+
960
+ def _check_cli_update(library: Literal["huggingface_hub", "transformers"]) -> None:
961
+ if constants.HF_HUB_DISABLE_UPDATE_CHECK:
962
+ return
963
+
964
+ current_version = importlib.metadata.version(library)
965
+
966
+ # Skip if current version is a pre-release or dev version
967
+ if any(tag in current_version for tag in ["rc", "dev"]):
968
+ return
969
+
970
+ # Skip if already checked in the last 24 hours
971
+ if os.path.exists(constants.CHECK_FOR_UPDATE_DONE_PATH):
972
+ mtime = os.path.getmtime(constants.CHECK_FOR_UPDATE_DONE_PATH)
973
+ if (time.time() - mtime) < 24 * 3600:
974
+ return
975
+
976
+ # Touch the file to mark that we did the check now
977
+ Path(constants.CHECK_FOR_UPDATE_DONE_PATH).parent.mkdir(parents=True, exist_ok=True)
978
+ Path(constants.CHECK_FOR_UPDATE_DONE_PATH).touch()
979
+
980
+ # Check latest version from the appropriate registry
981
+ if library == "huggingface_hub" and installation_method() == "brew":
982
+ latest_version = _fetch_latest_brew_version()
983
+ else:
984
+ latest_version = _fetch_latest_pypi_version(library)
985
+ if latest_version is None or current_version == latest_version:
986
+ return
987
+
988
+ if library == "huggingface_hub":
989
+ update_command = _get_huggingface_hub_update_command()
990
+ else:
991
+ update_command = _get_transformers_update_command()
992
+
993
+ message = f"A new version of {library} ({latest_version}) is available! You are using version {current_version}."
994
+ if update_command is not None:
995
+ match library:
996
+ case "huggingface_hub":
997
+ message += "\nTo update, run: hf update"
998
+ case _:
999
+ message += f"\nTo update, run: {' '.join(update_command)}"
1000
+ out.hint(message)
1001
+
1002
+
1003
+ def _fetch_latest_pypi_version(library: str) -> str | None:
1004
+ """Fetch the latest version of a library from PyPI. Returns None if the request fails."""
1005
+ try:
1006
+ response = get_session().get(f"https://pypi.org/pypi/{library}/json", timeout=2)
1007
+ hf_raise_for_status(response)
1008
+ return response.json()["info"]["version"]
1009
+ except Exception:
1010
+ logger.debug("Error while fetching latest version from PyPI.", exc_info=True)
1011
+ return None
1012
+
1013
+
1014
+ def _fetch_latest_brew_version() -> str | None:
1015
+ """Fetch the latest version of the `hf` formula from the Homebrew registry. Returns None if the request fails."""
1016
+ try:
1017
+ response = get_session().get("https://formulae.brew.sh/api/formula/hf.json", timeout=2)
1018
+ hf_raise_for_status(response)
1019
+ return response.json()["versions"]["stable"]
1020
+ except Exception:
1021
+ logger.debug("Error while fetching latest version from Homebrew.", exc_info=True)
1022
+ return None
1023
+
1024
+
1025
+ def run_update() -> int:
1026
+ """Run the install-method-appropriate update command for the `hf` CLI.
1027
+
1028
+ Raises CLIError if the installation method can't be determined.
1029
+ Returns the subprocess exit code on success/failure of the update itself.
1030
+ """
1031
+ cmd = _get_huggingface_hub_update_command()
1032
+ if cmd is None:
1033
+ raise CLIError(
1034
+ "Cannot determine how to update huggingface_hub (unknown installation method). Please update manually."
1035
+ )
1036
+ return subprocess.call(cmd)
1037
+
1038
+
1039
+ def _get_huggingface_hub_update_command() -> list[str] | None:
1040
+ """Return the command to update huggingface_hub as an argv list, or None if the installation method is unknown."""
1041
+ match installation_method():
1042
+ case "brew":
1043
+ return ["brew", "upgrade", "hf"]
1044
+ case "hf_installer" if os.name == "nt":
1045
+ return ["powershell", "-NoProfile", "-Command", "iwr -useb https://hf.co/cli/install.ps1 | iex"]
1046
+ case "hf_installer":
1047
+ return ["bash", "-c", "curl -LsSf https://hf.co/cli/install.sh | bash -"]
1048
+ case "pip":
1049
+ return [sys.executable, "-m", "pip", "install", "-U", "huggingface_hub"]
1050
+ case _:
1051
+ return None
1052
+
1053
+
1054
+ def _get_transformers_update_command() -> list[str] | None:
1055
+ """Return the command to update transformers as an argv list, or None if the installation method is unknown."""
1056
+ match installation_method():
1057
+ case "hf_installer" if os.name == "nt":
1058
+ return [
1059
+ "powershell",
1060
+ "-NoProfile",
1061
+ "-Command",
1062
+ "iwr -useb https://hf.co/cli/install.ps1 | iex -WithTransformers",
1063
+ ]
1064
+ case "hf_installer":
1065
+ return ["bash", "-c", "curl -LsSf https://hf.co/cli/install.sh | bash -s -- --with-transformers"]
1066
+ case "pip":
1067
+ return [sys.executable, "-m", "pip", "install", "-U", "transformers"]
1068
+ case _:
1069
+ return None
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_completion.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Shell completion for the ``hf`` CLI, built on Click's native completion.
15
+
16
+ Click generates completion scripts activated by the ``_HF_COMPLETE`` env var (this
17
+ works out of the box because ``hf`` is a Click command). This module exposes the two
18
+ conveniences Typer used to provide — ``--install-completion`` / ``--show-completion``
19
+ — as thin eager options over that machinery.
20
+ """
21
+
22
+ import os
23
+ from pathlib import Path
24
+ from typing import Annotated
25
+
26
+ import click
27
+ from click.shell_completion import get_completion_class
28
+
29
+ from ._framework import Option
30
+
31
+
32
+ _COMPLETE_VAR = "_HF_COMPLETE"
33
+
34
+ # Shells with a shared rc file: the line that activates completion (appended once).
35
+ _RC_ACTIVATION: dict[str, tuple[Path, str]] = {
36
+ "bash": (Path.home() / ".bashrc", f'eval "$({_COMPLETE_VAR}=bash_source hf)"'),
37
+ "zsh": (Path.home() / ".zshrc", f'eval "$({_COMPLETE_VAR}=zsh_source hf)"'),
38
+ }
39
+ # Fish auto-loads per-command files from its completions directory. The file is dedicated
40
+ # to `hf`, so the full script is written there directly (overwriting any stale version)
41
+ # instead of re-generating it via `hf` on every shell startup.
42
+ _FISH_COMPLETION_PATH = Path.home() / ".config" / "fish" / "completions" / "hf.fish"
43
+
44
+
45
+ def _detect_shell() -> str:
46
+ return Path(os.environ.get("SHELL", "")).name or "bash"
47
+
48
+
49
+ def _completion_script(shell: str) -> str:
50
+ # Imported lazily to avoid a circular import (hf.py imports the options below).
51
+ from .hf import app
52
+
53
+ completion_cls = get_completion_class(shell)
54
+ if completion_cls is None:
55
+ raise click.ClickException(f"Shell '{shell}' is not supported for completion.")
56
+ return completion_cls(app, {}, "hf", _COMPLETE_VAR).source()
57
+
58
+
59
+ def _show_completion(value: bool) -> None:
60
+ if not value:
61
+ return
62
+ click.echo(_completion_script(_detect_shell()))
63
+ raise click.exceptions.Exit()
64
+
65
+
66
+ def _install_completion(value: bool) -> None:
67
+ if not value:
68
+ return
69
+ shell = _detect_shell()
70
+ if shell == "fish":
71
+ path = _FISH_COMPLETION_PATH
72
+ path.parent.mkdir(parents=True, exist_ok=True)
73
+ path.write_text(_completion_script("fish"))
74
+ elif shell in _RC_ACTIVATION:
75
+ path, activation = _RC_ACTIVATION[shell]
76
+ path.parent.mkdir(parents=True, exist_ok=True)
77
+ existing = path.read_text() if path.exists() else ""
78
+ if activation not in existing:
79
+ with path.open("a") as file:
80
+ file.write(f"\n{activation}\n")
81
+ else:
82
+ raise click.ClickException(f"Shell '{shell}' is not supported for completion.")
83
+ click.echo(f"{shell} completion installed in {path}. Restart your shell for it to take effect.")
84
+ raise click.exceptions.Exit()
85
+
86
+
87
+ InstallCompletionOpt = Annotated[
88
+ bool,
89
+ Option(
90
+ "--install-completion",
91
+ callback=_install_completion,
92
+ is_eager=True,
93
+ help="Install completion for the current shell.",
94
+ ),
95
+ ]
96
+
97
+ ShowCompletionOpt = Annotated[
98
+ bool,
99
+ Option(
100
+ "--show-completion",
101
+ callback=_show_completion,
102
+ is_eager=True,
103
+ help="Show completion for the current shell, to copy it or customize the installation.",
104
+ ),
105
+ ]
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_cp.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Shared ``cp`` command to copy files between local paths, repositories and buckets.
15
+
16
+ This single command backs three identical CLI entry points: ``hf cp`` (top-level),
17
+ ``hf repos cp`` and ``hf buckets cp``. It supports any source/destination combination
18
+ of local file, repo/bucket ``hf://`` URI, and ``-`` (stdin/stdout), with two exceptions:
19
+ - bucket-to-repo copies are not supported (server limitation), and
20
+ - local-to-local copies (use a regular ``cp`` for that).
21
+ """
22
+
23
+ import os
24
+ import sys
25
+ from dataclasses import replace
26
+ from typing import Annotated, Literal
27
+
28
+ import click
29
+
30
+ from huggingface_hub import HfApi
31
+ from huggingface_hub.errors import CLIError
32
+ from huggingface_hub.utils import HfUri, SoftTemporaryDirectory, disable_progress_bars, is_hf_uri, parse_hf_uri
33
+
34
+ from ._cli_utils import TokenOpt, get_hf_api
35
+ from ._framework import Argument
36
+ from ._output import out
37
+
38
+
39
+ CP_EXAMPLES = [
40
+ # Download (repo or bucket -> local / stdout)
41
+ "hf cp hf://username/my-model/config.json",
42
+ "hf cp hf://username/my-model/config.json ./config.json",
43
+ "hf cp hf://datasets/username/my-dataset/data.csv ./data/",
44
+ "hf cp hf://buckets/username/my-bucket/config.json -",
45
+ # Upload (local / stdin -> repo or bucket)
46
+ "hf cp ./model.safetensors hf://username/my-model/model.safetensors",
47
+ "hf cp ./config.json hf://buckets/username/my-bucket/logs/",
48
+ "hf cp - hf://buckets/username/my-bucket/config.json",
49
+ # Remote to remote (repo/bucket -> repo/bucket, server-side when possible)
50
+ "hf cp hf://username/source-model/ hf://username/dest-model/",
51
+ "hf cp hf://datasets/username/my-dataset/processed/ hf://buckets/username/my-bucket/processed/",
52
+ "hf cp hf://buckets/username/my-bucket/logs/ hf://buckets/username/archive-bucket/ # copies contents only",
53
+ ]
54
+
55
+
56
+ # Which alias registered the command, used to restrict the remote endpoint type (see `_enforce_context`).
57
+ CpContext = Literal["repos", "buckets"]
58
+
59
+
60
+ def make_cp(context: CpContext | None = None):
61
+ """Build the ``cp`` command function for a given alias.
62
+
63
+ The three entry points (`hf cp`, `hf repos cp`, `hf buckets cp`) share the exact same logic;
64
+ 'context' only adds a guardrail on the remote endpoint type (see `_enforce_context`).
65
+ """
66
+
67
+ def cp(
68
+ src: Annotated[
69
+ str,
70
+ Argument(help="Source: local file, hf:// URI (repo or bucket), or - for stdin."),
71
+ ],
72
+ dst: Annotated[
73
+ str | None,
74
+ Argument(help="Destination: local path, hf:// URI (repo or bucket), or - for stdout."),
75
+ ] = None,
76
+ token: TokenOpt = None,
77
+ ) -> None:
78
+ """Copy files between local paths, repositories, and buckets.
79
+
80
+ Handles uploads (local/stdin -> repo/bucket), downloads (repo/bucket -> local/stdout) and
81
+ remote-to-remote copies (repo/bucket -> repo/bucket). Bucket-to-repo and local-to-local
82
+ copies are not supported. For directories, use `hf upload`/`hf download` (repos) or
83
+ `hf buckets sync` (buckets). Remote-to-remote copies only work within the same storage
84
+ region (https://huggingface.co/docs/hub/storage-regions).
85
+ """
86
+ _enforce_context(context, src, dst)
87
+ _run_cp(src, dst, token)
88
+
89
+ return cp
90
+
91
+
92
+ def _enforce_context(context: CpContext | None, src: str, dst: str | None) -> None:
93
+ """Guardrail for the `hf repos cp` / `hf buckets cp` aliases.
94
+
95
+ These aliases are exact duplicates of `hf cp`, so a bare `hf repos cp` could otherwise touch a
96
+ bucket (and vice versa). We validate the type of the remote side: the destination for uploads and
97
+ remote-to-remote copies, or the source when downloading to a local path / stdout. The top-level
98
+ `hf cp` (i.e. 'context' is None) accepts any combination.
99
+ """
100
+ if context is None:
101
+ return
102
+ # The remote endpoint is the destination when it is an hf:// URI, otherwise the source (download).
103
+ remote = dst if (dst is not None and is_hf_uri(dst)) else src
104
+ if not is_hf_uri(remote):
105
+ return
106
+ if context == "repos" and parse_hf_uri(remote).is_bucket:
107
+ raise CLIError("`hf repos cp` only works with repositories. Use `hf cp` or `hf buckets cp` for buckets.")
108
+ if context == "buckets" and not parse_hf_uri(remote).is_bucket:
109
+ raise CLIError("`hf buckets cp` only works with buckets. Use `hf cp` or `hf repos cp` for repositories.")
110
+
111
+
112
+ def _run_cp(src: str, dst: str | None, token: str | None) -> None:
113
+ api = get_hf_api(token=token)
114
+
115
+ src_is_stdin = src == "-"
116
+ dst_is_stdout = dst == "-"
117
+ src_is_hf = is_hf_uri(src)
118
+ dst_is_hf = dst is not None and is_hf_uri(dst)
119
+
120
+ # --- Remote to remote: delegate to copy_files (repo/bucket -> repo/bucket) ---
121
+ if src_is_hf and dst_is_hf:
122
+ assert dst is not None # guaranteed by dst_is_hf
123
+ api.copy_files(src, dst)
124
+ out.result("Copied", src=src, dst=dst)
125
+ return
126
+
127
+ # --- At least one side must be a remote hf:// URI (rules out local->local, stdin->local, etc.) ---
128
+ if not src_is_hf and not dst_is_hf:
129
+ if dst is None:
130
+ raise click.BadParameter("Missing destination. Provide a repo or bucket hf:// URI as DST.")
131
+ raise click.BadParameter(
132
+ "One of SRC or DST must be a repo (hf://username/...) or bucket (hf://buckets/...) URI."
133
+ )
134
+
135
+ # --- Download: repo/bucket -> local file or stdout ---
136
+ if src_is_hf:
137
+ if dst_is_stdout:
138
+ _download_file_to_stdout(api, src)
139
+ return
140
+ _download_file_to_local(api, src, dst)
141
+ return
142
+
143
+ # --- Upload: local file or stdin -> repo/bucket ---
144
+ assert dst is not None # guaranteed: reaching here means dst_is_hf is True
145
+ _upload_file_to_remote(api, src, dst, src_is_stdin=src_is_stdin)
146
+
147
+
148
+ def _download_file_to_stdout(api: HfApi, src: str) -> None:
149
+ uri = parse_hf_uri(src)
150
+ filename = _source_filename(uri, src)
151
+ # Suppress progress bars to avoid polluting the piped output.
152
+ with disable_progress_bars():
153
+ with SoftTemporaryDirectory() as tmp_dir:
154
+ tmp_path = os.path.join(tmp_dir, filename)
155
+ _download_single(api, uri, tmp_path)
156
+ with open(tmp_path, "rb") as f:
157
+ while chunk := f.read(32_000_000): # 32MB chunks
158
+ sys.stdout.buffer.write(chunk)
159
+
160
+
161
+ def _download_file_to_local(api: HfApi, src: str, dst: str | None) -> None:
162
+ uri = parse_hf_uri(src)
163
+ filename = _source_filename(uri, src)
164
+
165
+ if dst is None:
166
+ local_path = filename
167
+ elif os.path.isdir(dst) or dst.endswith(os.sep) or dst.endswith("/"):
168
+ local_path = os.path.join(dst, filename)
169
+ else:
170
+ local_path = dst
171
+
172
+ parent_dir = os.path.dirname(local_path)
173
+ if parent_dir:
174
+ os.makedirs(parent_dir, exist_ok=True)
175
+
176
+ _download_single(api, uri, local_path)
177
+ out.result("Downloaded", src=src, dst=local_path)
178
+
179
+
180
+ def _download_single(api: HfApi, uri: HfUri, local_path: str) -> None:
181
+ """Download a single file (repo or bucket) to ``local_path``.
182
+
183
+ Used by `_download_file_to_local` and `_download_file_to_stdout`.
184
+ """
185
+ if uri.is_bucket:
186
+ api.download_bucket_files(uri.id, [(uri.path_in_repo, local_path)], raise_on_missing_files=True)
187
+ else:
188
+ # Download into a temporary folder next to the destination (rather than the shared cache)
189
+ # so the final move stays on the same filesystem and is instant. The temp folder is
190
+ # cleaned up automatically once the move is complete.
191
+ parent_dir = os.path.dirname(local_path) or "."
192
+ with SoftTemporaryDirectory(prefix=".tmp", dir=parent_dir) as tmp_dir:
193
+ downloaded_path = api.hf_hub_download(
194
+ repo_id=uri.id,
195
+ repo_type=uri.type,
196
+ filename=uri.path_in_repo,
197
+ revision=uri.revision,
198
+ local_dir=tmp_dir,
199
+ )
200
+ os.replace(downloaded_path, local_path)
201
+
202
+
203
+ def _source_filename(uri: HfUri, src: str) -> str:
204
+ if uri.path_in_repo == "" or src.endswith("/"):
205
+ raise click.BadParameter(
206
+ "Source path must include a file name, not just a repo/bucket or directory path."
207
+ " Use `hf download` or `hf buckets sync` to copy directories."
208
+ )
209
+ return uri.path_in_repo.rsplit("/", 1)[-1]
210
+
211
+
212
+ def _upload_file_to_remote(api: HfApi, src: str, dst: str, *, src_is_stdin: bool) -> None:
213
+ uri = parse_hf_uri(dst)
214
+
215
+ if src_is_stdin:
216
+ if uri.path_in_repo == "" or dst.endswith("/"):
217
+ raise click.BadParameter("Stdin upload requires a full destination path including filename.")
218
+ data = sys.stdin.buffer.read()
219
+ _upload_single(api, uri, data, uri.path_in_repo)
220
+ out.result("Uploaded", src="stdin", dst=uri.to_uri())
221
+ return
222
+
223
+ if os.path.isdir(src):
224
+ raise click.BadParameter(
225
+ "Source must be a file, not a directory. Use `hf upload` or `hf buckets sync` for directories."
226
+ )
227
+ if not os.path.isfile(src):
228
+ raise click.BadParameter(f"Source file not found: {src}")
229
+
230
+ prefix = uri.path_in_repo
231
+ if prefix == "":
232
+ remote_path = os.path.basename(src)
233
+ elif dst.endswith("/"):
234
+ remote_path = prefix + "/" + os.path.basename(src)
235
+ else:
236
+ remote_path = prefix
237
+
238
+ _upload_single(api, uri, src, remote_path)
239
+ out.result("Uploaded", src=src, dst=replace(uri, path_in_repo=remote_path).to_uri())
240
+
241
+
242
+ def _upload_single(api: HfApi, uri: HfUri, source: str | bytes, remote_path: str) -> None:
243
+ """Upload a single file or bytes (to a repo or bucket)."""
244
+ if uri.is_bucket:
245
+ api.batch_bucket_files(uri.id, add=[(source, remote_path)])
246
+ else:
247
+ api.upload_file(
248
+ path_or_fileobj=source,
249
+ path_in_repo=remote_path,
250
+ repo_id=uri.id,
251
+ repo_type=uri.type,
252
+ revision=uri.revision,
253
+ )
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_errors.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """CLI error handling utilities."""
15
+
16
+ import traceback
17
+ from collections.abc import Callable
18
+
19
+ from huggingface_hub.errors import (
20
+ BucketNotFoundError,
21
+ CLIError,
22
+ CLIExtensionInstallError,
23
+ DeviceCodeError,
24
+ EntryNotFoundError,
25
+ GatedRepoError,
26
+ HfHubHTTPError,
27
+ HfUriError,
28
+ IncompleteSnapshotError,
29
+ LocalEntryNotFoundError,
30
+ LocalTokenNotFoundError,
31
+ OfflineModeIsEnabled,
32
+ OIDCError,
33
+ RemoteEntryNotFoundError,
34
+ RepositoryNotFoundError,
35
+ RevisionNotFoundError,
36
+ )
37
+
38
+
39
+ def _format_repo_not_found(error: RepositoryNotFoundError) -> str:
40
+ label = error.repo_type.capitalize() if error.repo_type else "Repository"
41
+ if error.repo_id:
42
+ msg = f"{label} '{error.repo_id}' not found."
43
+ else:
44
+ msg = f"{label} not found."
45
+ msg += "\nIf the repo is private, make sure you are authenticated and your token has the required permissions."
46
+
47
+ msg += "\nIf the repo does not exist, create it with: "
48
+ if error.repo_id is not None:
49
+ type_flag = f" --type {error.repo_type}" if error.repo_type and error.repo_type != "model" else ""
50
+ msg += f"hf repos create {error.repo_id}{type_flag}"
51
+ else:
52
+ msg += "hf repos create <repo_id>"
53
+
54
+ return msg
55
+
56
+
57
+ def _format_gated_repo(error: GatedRepoError) -> str:
58
+ label = error.repo_type if error.repo_type else "repository"
59
+ if error.repo_id:
60
+ return f"Access denied. {label.capitalize()} '{error.repo_id}' requires approval."
61
+ return f"Access denied. This {label} requires approval."
62
+
63
+
64
+ def _format_bucket_not_found(error: BucketNotFoundError) -> str:
65
+ if error.bucket_id:
66
+ msg = f"Bucket '{error.bucket_id}' not found."
67
+ cmd = f"hf buckets create {error.bucket_id}"
68
+ else:
69
+ msg = "Bucket not found."
70
+ cmd = "hf buckets create <bucket_id>"
71
+ msg += "\nIf the bucket is private, make sure you are authenticated and your token has the required permissions."
72
+ msg += f"\nIf the bucket does not exist, create it with: {cmd}"
73
+ return msg
74
+
75
+
76
+ def _format_entry_not_found(error: RemoteEntryNotFoundError) -> str:
77
+ label = error.repo_type if error.repo_type else "repository"
78
+ url = str(error.response.url) if error.response else None
79
+ if error.repo_id:
80
+ msg = f"File not found in {label} '{error.repo_id}'."
81
+ else:
82
+ msg = f"File not found in {label}."
83
+ if url:
84
+ msg += f"\nURL: {url}"
85
+ return msg
86
+
87
+
88
+ def _format_local_entry_not_found(error: LocalEntryNotFoundError) -> str:
89
+ cause = error.__cause__
90
+ if cause is not None:
91
+ return f"Local entry not found. {cause}"
92
+ return f"Local entry not found. {error}"
93
+
94
+
95
+ def _format_incomplete_snapshot(error: IncompleteSnapshotError) -> str:
96
+ msg = _format_local_entry_not_found(error)
97
+ msg += f"\nIncomplete snapshot available at: {error.snapshot_path}"
98
+ return msg
99
+
100
+
101
+ def _format_revision_not_found(error: RevisionNotFoundError) -> str:
102
+ label = error.repo_type if error.repo_type else "repository"
103
+ if error.repo_id:
104
+ return f"Revision not found in {label} '{error.repo_id}'."
105
+ return f"Revision not found in {label}. Check the revision parameter."
106
+
107
+
108
+ def _format_cli_error(error: CLIError) -> str:
109
+ """No traceback, just the error message."""
110
+ return str(error)
111
+
112
+
113
+ def _format_cli_extension_install_error(error: CLIExtensionInstallError) -> str:
114
+ """Format a CLI extension installation error.
115
+
116
+ The error is likely to be a tricky subprocess error to investigate. In this specific case we want to format the
117
+ traceback of the root cause while keeping the "nicely formatted" error message of the CLIExtensionInstallError
118
+ as a 1-line message.
119
+ """
120
+ cause_tb = (
121
+ "".join(traceback.format_exception(type(error.__cause__), error.__cause__, error.__cause__.__traceback__))
122
+ if error.__cause__ is not None
123
+ else ""
124
+ )
125
+ return f"{cause_tb}\n{error}"
126
+
127
+
128
+ CLI_ERROR_MAPPINGS: dict[type[Exception], Callable[..., str]] = {
129
+ OfflineModeIsEnabled: lambda error: str(error),
130
+ # GatedRepoError must come before RepositoryNotFoundError (it's a subclass).
131
+ GatedRepoError: _format_gated_repo,
132
+ BucketNotFoundError: _format_bucket_not_found,
133
+ RepositoryNotFoundError: _format_repo_not_found,
134
+ RevisionNotFoundError: _format_revision_not_found,
135
+ LocalTokenNotFoundError: lambda _: "Not logged in. Run 'hf auth login' first.",
136
+ OIDCError: lambda error: f"OIDC Exchange failed. {error}",
137
+ DeviceCodeError: lambda error: f"Login failed: {error}",
138
+ RemoteEntryNotFoundError: _format_entry_not_found,
139
+ # IncompleteSnapshotError must come before LocalEntryNotFoundError (it's a subclass).
140
+ IncompleteSnapshotError: _format_incomplete_snapshot,
141
+ LocalEntryNotFoundError: _format_local_entry_not_found,
142
+ EntryNotFoundError: lambda error: str(error),
143
+ HfHubHTTPError: lambda error: str(error),
144
+ HfUriError: lambda error: f"Invalid HF URI: {error.uri}. {error.msg}",
145
+ ValueError: lambda error: f"Invalid value. {error}",
146
+ CLIExtensionInstallError: _format_cli_extension_install_error,
147
+ CLIError: _format_cli_error,
148
+ }
149
+
150
+
151
+ def format_known_exception(error: Exception) -> str | None:
152
+ for exc_type, formatter in CLI_ERROR_MAPPINGS.items():
153
+ if isinstance(error, exc_type):
154
+ return formatter(error)
155
+ return None
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_file_listing.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Shared helpers for listing files in buckets and repos (tree view, flat view, formatting)."""
15
+
16
+ import json
17
+ from datetime import datetime
18
+ from typing import Sequence
19
+
20
+ import click
21
+
22
+ from huggingface_hub._buckets import BucketFile, BucketFolder
23
+ from huggingface_hub.hf_api import RepoFile, RepoFolder
24
+
25
+ from ._cli_utils import get_hf_api
26
+ from ._output import OutputFormat, _dataclass_to_dict, 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 == OutputFormat.json:
177
+ raise click.BadParameter("Cannot use --tree with --format json.")
178
+
179
+ api = get_hf_api(token=token)
180
+ items = list(api.list_repo_tree(repo_id, recursive=recursive, revision=revision, repo_type=repo_type, expand=True))
181
+ print_file_listing(items, human_readable=human_readable, as_tree=as_tree, recursive=recursive)
182
+
183
+
184
+ def print_file_listing(
185
+ items: Sequence[BucketItem] | Sequence[RepoItem],
186
+ *,
187
+ human_readable: bool = False,
188
+ as_tree: bool = False,
189
+ recursive: bool = False,
190
+ ) -> None:
191
+ """Print a file listing in the appropriate format based on the current output mode.
192
+
193
+ Supports tree, json, quiet, and flat human-readable views. Works with both
194
+ BucketFile/BucketFolder and RepoFile/RepoFolder items.
195
+ """
196
+ if not items:
197
+ out.text("(empty)")
198
+ return
199
+
200
+ has_directories = any(isinstance(item, BucketFolder | RepoFolder) for item in items)
201
+
202
+ if as_tree:
203
+ quiet = out.mode == OutputFormat.quiet
204
+ for line in build_tree(items, human_readable=human_readable, quiet=quiet):
205
+ print(line)
206
+ elif out.mode == OutputFormat.json:
207
+ print(json.dumps([_dataclass_to_dict(item) for item in items], indent=2))
208
+ elif out.mode == OutputFormat.quiet:
209
+ for item in items:
210
+ if isinstance(item, BucketFolder | RepoFolder):
211
+ print(f"{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.")
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_framework.py ADDED
@@ -0,0 +1,645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Minimal declaration layer over Click 8.x for the ``hf`` CLI.
15
+
16
+ This module vendors *only* the slice of Typer the CLI actually uses: turning
17
+ annotated function signatures (``Annotated[T, Option(...)]`` / ``Argument(...)``)
18
+ into Click parameters, and rendering argument/option help the way Typer did.
19
+ It exists so the CLI depends on Click's stable public API instead of Typer's
20
+ now-internal vendored Click (``typer._click``), which Typer reserves the right
21
+ to refactor at any release.
22
+
23
+ Deliberately *not* implemented (add a case here only when a command needs it):
24
+ rich rendering, shell-completion install commands, prompts/confirmation options,
25
+ env-var options, ``File``/``UUID`` params, ``count`` options, ``default_factory``.
26
+ Click's own machinery already handles exceptions, aborts, exits, and native
27
+ ``_HF_COMPLETE`` shell completion, so none of Typer's ``main()`` overrides are
28
+ reproduced here.
29
+
30
+ The interesting logic mirrors four Typer functions, kept faithful so ``--help``
31
+ output stays byte-identical:
32
+ - :func:`_get_click_type` <- ``typer.main.get_click_type``
33
+ - :func:`_build_click_param` <- ``typer.main.get_click_param``
34
+ - :func:`_make_handler` <- ``typer.main.get_callback``
35
+ - :class:`HfArgument` / :class:`HfOption` help records <- ``typer.core.Typer*``
36
+ """
37
+
38
+ import enum
39
+ import functools
40
+ import inspect
41
+ from collections.abc import Callable, Sequence
42
+ from datetime import datetime
43
+ from pathlib import Path
44
+ from types import UnionType
45
+ from typing import Annotated, Any, Literal, Union, get_args, get_origin
46
+
47
+ import click
48
+
49
+
50
+ def get_command_name(name: str) -> str:
51
+ """Normalize a Python identifier to a CLI name (``force_download`` -> ``force-download``)."""
52
+ return name.lower().replace("_", "-")
53
+
54
+
55
+ # ---------------------------------------------------------------------------
56
+ # 1. Declaration markers — replace ``typer.Option`` / ``typer.Argument``.
57
+ # Attached in ``Annotated[T, Option(...)]``; the ``= value`` in the function
58
+ # signature carries the default (never the marker).
59
+ # ---------------------------------------------------------------------------
60
+
61
+
62
+ class ParameterInfo:
63
+ """Base marker holding the (tiny) set of Click knobs the CLI actually sets.
64
+
65
+ ``callback`` is a Typer-style value parser ``fn(value) -> parsed`` — it does NOT
66
+ receive Click's ``(ctx, param, value)``. It consumes the enum/list convertors, so
67
+ ``value`` is already converted when it runs.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ *param_decls: str,
73
+ help: str | None = None,
74
+ show_default: bool | str = True,
75
+ hidden: bool = False,
76
+ is_eager: bool = False,
77
+ callback: Callable[..., Any] | None = None,
78
+ min: int | None = None,
79
+ click_type: click.ParamType | None = None,
80
+ ) -> None:
81
+ self.param_decls = list(param_decls)
82
+ self.help = help
83
+ self.show_default = show_default
84
+ self.hidden = hidden
85
+ self.is_eager = is_eager
86
+ self.callback = callback
87
+ self.min = min
88
+ self.click_type = click_type
89
+
90
+
91
+ class Option(ParameterInfo):
92
+ """Declare a CLI option, e.g. ``Annotated[str | None, Option("--revision")]``."""
93
+
94
+
95
+ class Argument(ParameterInfo):
96
+ """Declare a positional CLI argument, e.g. ``Annotated[str, Argument()]``."""
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # 2. Annotation -> Click type + value convertors.
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ def _get_click_type(annotation: Any, info: ParameterInfo) -> click.ParamType:
105
+ """Map a (already unwrapped) annotation to a Click ``ParamType``."""
106
+ if info.click_type is not None:
107
+ return info.click_type
108
+ if annotation is str:
109
+ return click.STRING
110
+ if annotation is bool:
111
+ return click.BOOL
112
+ if annotation is int:
113
+ return click.IntRange(min=info.min) if info.min is not None else click.INT
114
+ if annotation is float:
115
+ return click.FloatRange(min=info.min) if info.min is not None else click.FLOAT
116
+ if annotation is Path:
117
+ return click.Path(path_type=Path)
118
+ if annotation is datetime:
119
+ return click.DateTime()
120
+ if isinstance(annotation, type) and issubclass(annotation, enum.Enum):
121
+ values = [item.value for item in annotation]
122
+ if not all(isinstance(value, str) for value in values):
123
+ # A non-str member default would fail Choice validation at parse time with a
124
+ # cryptic error; fail at build time with a clear one instead.
125
+ raise TypeError(f"Unsupported enum {annotation.__name__!r}: only str-valued enums are supported.")
126
+ return click.Choice(values)
127
+ if get_origin(annotation) is Literal:
128
+ return click.Choice([str(value) for value in get_args(annotation)])
129
+ raise TypeError(f"Unsupported CLI annotation {annotation!r}. Add a case in `_framework._get_click_type()`.")
130
+
131
+
132
+ def _enum_convertor(enum_type: type[enum.Enum]) -> Callable[[Any], Any]:
133
+ """Map a parsed choice string back to its ``Enum`` member (mirrors Typer)."""
134
+ value_map = {str(member.value): member for member in enum_type}
135
+
136
+ def convertor(value: Any) -> Any:
137
+ if value is not None:
138
+ return value_map.get(str(value))
139
+ return None
140
+
141
+ return convertor
142
+
143
+
144
+ def _list_convertor(
145
+ inner: Callable[[Any], Any] | None, default_value: Any | None
146
+ ) -> Callable[[Sequence[Any] | None], list[Any] | None]:
147
+ """Turn Click's tuple (from ``multiple=True``) into a list, applying ``inner`` per item."""
148
+
149
+ def convertor(value: Sequence[Any] | None) -> list[Any] | None:
150
+ if value is None or (default_value is None and len(value) == 0):
151
+ return None
152
+ return [inner(item) if inner else item for item in value]
153
+
154
+ return convertor
155
+
156
+
157
+ def _make_convertor(
158
+ annotation: Any, is_list: bool, default_value: Any | None, info: ParameterInfo
159
+ ) -> Callable[[Any], Any] | None:
160
+ """Build the value convertor for a param (``None`` when no coercion is needed).
161
+
162
+ An explicit ``click_type`` (e.g. ``SoftChoice``) owns its own conversion, so no
163
+ enum convertor is added on top of it.
164
+ """
165
+ inner = None
166
+ if info.click_type is None and isinstance(annotation, type) and issubclass(annotation, enum.Enum):
167
+ inner = _enum_convertor(annotation)
168
+ if is_list:
169
+ return _list_convertor(inner, default_value)
170
+ return inner
171
+
172
+
173
+ def _unwrap_optional_and_list(annotation: Any) -> tuple[Any, bool]:
174
+ """Strip ``T | None`` / ``Optional[T]`` and ``list[T]``; return ``(base_type, is_list)``."""
175
+ origin = get_origin(annotation)
176
+ if origin in (Union, UnionType):
177
+ non_none = [arg for arg in get_args(annotation) if arg is not type(None)]
178
+ if len(non_none) != 1:
179
+ raise TypeError(f"Unsupported union annotation {annotation!r}; only ``T | None`` is supported.")
180
+ annotation = non_none[0]
181
+ origin = get_origin(annotation)
182
+ if origin in (list, Sequence):
183
+ return get_args(annotation)[0], True
184
+ return annotation, False
185
+
186
+
187
+ def _split_annotated(annotation: Any) -> tuple[Any, ParameterInfo | None]:
188
+ """Split ``Annotated[T, Option(...)]`` into ``(T, marker)``; ``(annotation, None)`` otherwise."""
189
+ if get_origin(annotation) is Annotated:
190
+ args = get_args(annotation)
191
+ marker = next((meta for meta in args[1:] if isinstance(meta, ParameterInfo)), None)
192
+ if marker is None and (typer_marker := next((meta for meta in args[1:] if _is_typer_marker(meta)), None)):
193
+ marker = _from_typer_marker(typer_marker, from_annotated=True)
194
+ return args[0], marker
195
+ return annotation, None
196
+
197
+
198
+ # ---------------------------------------------------------------------------
199
+ # Typer-marker compatibility shim (transition helper).
200
+ #
201
+ # ``typer_factory`` is exposed publicly and downstream CLIs (e.g. `transformers`)
202
+ # still register commands whose parameters carry ``typer.Option`` /
203
+ # ``typer.Argument`` markers. Recognize those markers structurally (no typer
204
+ # import required) and translate the fields this framework supports, so such
205
+ # commands keep working while downstream migrates.
206
+ # TODO: remove once transformers pins huggingface_hub>=1.22.0.
207
+ # ---------------------------------------------------------------------------
208
+
209
+
210
+ def _is_typer_marker(obj: Any) -> bool:
211
+ return type(obj).__module__.partition(".")[0] == "typer" and type(obj).__name__ in ("OptionInfo", "ArgumentInfo")
212
+
213
+
214
+ def _from_typer_marker(meta: Any, *, from_annotated: bool) -> ParameterInfo:
215
+ """Translate a ``typer.models.OptionInfo`` / ``ArgumentInfo`` into our marker."""
216
+ param_decls = list(getattr(meta, "param_decls", None) or ())
217
+ if type(meta).__name__ == "OptionInfo":
218
+ # In ``Annotated[...]`` usage typer stores the first flag name in ``default``
219
+ # (``Option("--flag", "-f")`` -> ``default="--flag"``, ``param_decls=("-f",)``).
220
+ default = getattr(meta, "default", ...)
221
+ if from_annotated and isinstance(default, str):
222
+ param_decls = [default, *param_decls]
223
+ cls: type[ParameterInfo] = Option
224
+ else:
225
+ cls = Argument
226
+ return cls(
227
+ *param_decls,
228
+ help=getattr(meta, "help", None),
229
+ show_default=getattr(meta, "show_default", True),
230
+ hidden=getattr(meta, "hidden", False),
231
+ is_eager=getattr(meta, "is_eager", False),
232
+ callback=getattr(meta, "callback", None),
233
+ min=getattr(meta, "min", None),
234
+ click_type=getattr(meta, "click_type", None),
235
+ )
236
+
237
+
238
+ # ---------------------------------------------------------------------------
239
+ # 3. Signature -> Click parameters (mirrors ``typer.main.get_click_param``).
240
+ # ---------------------------------------------------------------------------
241
+
242
+
243
+ def _wrap_param_callback(
244
+ user_callback: Callable[[Any], Any], convertor: Callable[[Any], Any] | None
245
+ ) -> Callable[[click.Context, click.Parameter, Any], Any]:
246
+ """Adapt a Typer-style value parser ``fn(value) -> parsed`` to a Click param callback."""
247
+
248
+ def click_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
249
+ return user_callback(convertor(value) if convertor else value)
250
+
251
+ return click_callback
252
+
253
+
254
+ def _build_click_param(
255
+ name: str, annotation: Any, info: ParameterInfo | None, signature_default: Any
256
+ ) -> tuple[click.Parameter, Callable[[Any], Any] | None]:
257
+ """Build a Click ``Parameter`` (and its post-parse value convertor) for one function param."""
258
+ required = signature_default is inspect.Parameter.empty
259
+ default_value = None if required else signature_default
260
+ if isinstance(default_value, enum.Enum):
261
+ default_value = default_value.value
262
+ if info is None:
263
+ # A bare annotation with no marker: required positional -> Argument, else Option.
264
+ info = Argument() if required else Option()
265
+
266
+ base_type, is_list = _unwrap_optional_and_list(annotation)
267
+ convertor = _make_convertor(base_type, is_list, default_value, info)
268
+
269
+ # A user ``callback`` consumes the value itself (and the convertor with it); otherwise the
270
+ # convertor runs later in the command handler wrapper. This keeps conversion single-pass.
271
+ if info.callback is not None:
272
+ param_callback: Callable[..., Any] | None = _wrap_param_callback(info.callback, convertor)
273
+ handler_convertor: Callable[[Any], Any] | None = None
274
+ else:
275
+ param_callback = None
276
+ handler_convertor = convertor
277
+
278
+ if isinstance(info, Argument):
279
+ argument = HfArgument(
280
+ [name],
281
+ type=_get_click_type(base_type, info),
282
+ required=required,
283
+ default=default_value,
284
+ nargs=-1 if is_list else 1,
285
+ is_eager=info.is_eager,
286
+ callback=param_callback,
287
+ help=info.help,
288
+ show_default=info.show_default,
289
+ hidden=info.hidden,
290
+ )
291
+ return argument, handler_convertor
292
+
293
+ # Option: prepend the Python name so ``click.Parameter.name`` matches the function kwarg,
294
+ # regardless of the user-facing flag names ("-v"/"--version", "--type"/"--repo-type", ...).
295
+ is_flag = base_type is bool
296
+ decls = [name]
297
+ if info.param_decls:
298
+ decls.extend(info.param_decls)
299
+ else:
300
+ kebab = get_command_name(name)
301
+ decls.append(f"--{kebab}/--no-{kebab}" if is_flag else f"--{kebab}")
302
+ option = HfOption(
303
+ decls,
304
+ # Click infers the flag type itself; passing a type alongside ``is_flag`` is rejected.
305
+ type=None if is_flag else _get_click_type(base_type, info),
306
+ required=required,
307
+ default=default_value,
308
+ is_flag=is_flag,
309
+ multiple=is_list,
310
+ is_eager=info.is_eager,
311
+ callback=param_callback,
312
+ help=info.help,
313
+ show_default=info.show_default,
314
+ hidden=info.hidden,
315
+ )
316
+ return option, handler_convertor
317
+
318
+
319
+ def _build_params(
320
+ func: Callable[..., Any],
321
+ ) -> tuple[list[click.Parameter], dict[str, Callable[[Any], Any]], str | None]:
322
+ """Introspect ``func`` and return ``(params, convertors, context_param_name)``."""
323
+ params: list[click.Parameter] = []
324
+ convertors: dict[str, Callable[[Any], Any]] = {}
325
+ context_param_name: str | None = None
326
+ for name, sig_param in inspect.signature(func).parameters.items():
327
+ # Read raw signature annotations rather than ``typing.get_type_hints``: the CLI never uses
328
+ # ``from __future__ import annotations``, so annotations are already live objects, and
329
+ # get_type_hints mangles ``Annotated[X | None, ...]`` on Python 3.10 (drops the origin).
330
+ annotation = sig_param.annotation if sig_param.annotation is not inspect.Parameter.empty else str
331
+ base_type, info = _split_annotated(annotation)
332
+ if isinstance(base_type, type) and (
333
+ issubclass(base_type, click.Context)
334
+ # typer.Context subclasses typer's *vendored* click since typer 0.26, so an
335
+ # issubclass check against real click misses it. Match it structurally.
336
+ or (base_type.__module__.partition(".")[0] == "typer" and base_type.__name__ == "Context")
337
+ ):
338
+ context_param_name = name
339
+ continue
340
+ signature_default = sig_param.default
341
+ if _is_typer_marker(signature_default):
342
+ # Old typer style: the marker *is* the signature default and carries the value.
343
+ if info is None:
344
+ info = _from_typer_marker(signature_default, from_annotated=False)
345
+ marker_default = getattr(signature_default, "default", ...)
346
+ signature_default = inspect.Parameter.empty if marker_default is ... else marker_default
347
+ click_param, convertor = _build_click_param(name, base_type, info, signature_default)
348
+ if convertor is not None and click_param.name is not None:
349
+ convertors[click_param.name] = convertor
350
+ params.append(click_param)
351
+ return params, convertors, context_param_name
352
+
353
+
354
+ def _make_handler(
355
+ func: Callable[..., Any],
356
+ convertors: dict[str, Callable[[Any], Any]],
357
+ context_param_name: str | None,
358
+ ) -> Callable[..., Any]:
359
+ """Wrap ``func`` so Click's kwargs map back to it, applying convertors and injecting the ctx."""
360
+
361
+ def handler(**kwargs: Any) -> Any:
362
+ call_kwargs = {key: (convertors[key](value) if key in convertors else value) for key, value in kwargs.items()}
363
+ if context_param_name is not None:
364
+ call_kwargs[context_param_name] = click.get_current_context()
365
+ return func(**call_kwargs)
366
+
367
+ functools.update_wrapper(handler, func)
368
+ return handler
369
+
370
+
371
+ # ---------------------------------------------------------------------------
372
+ # 4. Click parameter subclasses — port Typer's help records so arguments show up
373
+ # in ``--help`` (plain ``click.Argument`` renders none) and defaults/metavars
374
+ # read identically. Rich/env-var branches are dropped (never enabled here).
375
+ # ---------------------------------------------------------------------------
376
+
377
+
378
+ def _split_opt(opt: str) -> tuple[str, str]:
379
+ """Split an option string into ``(prefix, name)`` (Click's ``split_opt``, inlined)."""
380
+ first = opt[:1]
381
+ if first.isalnum():
382
+ return "", opt
383
+ if opt[1:2] == first:
384
+ return opt[:2], opt[2:]
385
+ return first, opt[1:]
386
+
387
+
388
+ def _extract_default_help_str(param: click.Parameter, ctx: click.Context) -> Any:
389
+ # Resilient parsing avoids type casting failing while rendering the default.
390
+ resilient = ctx.resilient_parsing
391
+ ctx.resilient_parsing = True
392
+ try:
393
+ return param.get_default(ctx, call=False)
394
+ finally:
395
+ ctx.resilient_parsing = resilient
396
+
397
+
398
+ def _default_string(
399
+ param: "HfArgument | HfOption", ctx: click.Context, show_default_is_str: bool, default_value: Any
400
+ ) -> str:
401
+ if show_default_is_str:
402
+ return f"({param.show_default})"
403
+ if isinstance(default_value, (list, tuple)):
404
+ return ", ".join(_default_string(param, ctx, show_default_is_str, item) for item in default_value)
405
+ if isinstance(default_value, enum.Enum):
406
+ return str(default_value.value)
407
+ if inspect.isfunction(default_value):
408
+ return "(dynamic)"
409
+ if isinstance(param, HfOption) and param.is_bool_flag and param.secondary_opts:
410
+ # Boolean toggle: show the opt name (without prefix) matching the current default.
411
+ if default_value:
412
+ return _split_opt(param.opts[0])[1] if param.opts else str(default_value)
413
+ return _split_opt(param.secondary_opts[0])[1]
414
+ if isinstance(param, HfOption) and param.is_bool_flag and not param.secondary_opts and not default_value:
415
+ return ""
416
+ return str(default_value)
417
+
418
+
419
+ def _describe_number_range(param_type: "click.IntRange | click.FloatRange") -> str:
420
+ """Human-readable range hint like ``x>=1`` or ``1<=x<10``.
421
+
422
+ Reproduces click's private ``_NumberRangeBase._describe_range()`` using the public
423
+ ``IntRange``/``FloatRange`` attributes, so the framework stays on Click's public API.
424
+ """
425
+ if param_type.min is None:
426
+ return f"x{'<' if param_type.max_open else '<='}{param_type.max}"
427
+ if param_type.max is None:
428
+ return f"x{'>' if param_type.min_open else '>='}{param_type.min}"
429
+ left = "<" if param_type.min_open else "<="
430
+ right = "<" if param_type.max_open else "<="
431
+ return f"{param_type.min}{left}x{right}{param_type.max}"
432
+
433
+
434
+ def _build_help_extra(param: "HfArgument | HfOption", ctx: click.Context, base_help: str) -> str:
435
+ """Append the ``[default: ...; required]`` suffix to a help string (shared by arg/option)."""
436
+ extra: list[str] = []
437
+ default_value = _extract_default_help_str(param, ctx)
438
+ show_default_is_str = isinstance(param.show_default, str)
439
+ if show_default_is_str or (default_value is not None and (param.show_default or ctx.show_default)):
440
+ default_string = _default_string(param, ctx, show_default_is_str, default_value)
441
+ if default_string:
442
+ extra.append(f"default: {default_string}")
443
+ # Numeric range hints are shown for options only (matches Typer; arguments omit them).
444
+ if isinstance(param, HfOption) and isinstance(param.type, (click.IntRange, click.FloatRange)):
445
+ range_str = _describe_number_range(param.type)
446
+ if range_str:
447
+ extra.append(range_str)
448
+ if param.required:
449
+ extra.append("required")
450
+ if extra:
451
+ suffix = f"[{'; '.join(extra)}]"
452
+ return f"{base_help} {suffix}" if base_help else suffix
453
+ return base_help
454
+
455
+
456
+ class HfArgument(click.Argument):
457
+ """Positional argument that renders help text and a metavar (Click's does neither)."""
458
+
459
+ def __init__(
460
+ self,
461
+ param_decls: Sequence[str],
462
+ *,
463
+ help: str | None = None,
464
+ show_default: bool | str = True,
465
+ hidden: bool = False,
466
+ **attrs: Any,
467
+ ) -> None:
468
+ self.help = help
469
+ self.show_default = show_default
470
+ self.hidden = hidden
471
+ super().__init__(param_decls, **attrs)
472
+
473
+ def make_metavar(self, ctx: click.Context) -> str:
474
+ if self.metavar is not None:
475
+ var = self.metavar
476
+ if not self.required and not var.startswith("["):
477
+ var = f"[{var}]"
478
+ return var
479
+ var = (self.name or "").upper()
480
+ if not self.required:
481
+ var = f"[{var}]"
482
+ type_var = self.type.get_metavar(self, ctx=ctx)
483
+ if type_var:
484
+ var += f":{type_var}"
485
+ if self.nargs != 1:
486
+ var += "..."
487
+ return var
488
+
489
+ def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
490
+ if self.hidden:
491
+ return None
492
+ return self.make_metavar(ctx=ctx), _build_help_extra(self, ctx, self.help or "")
493
+
494
+
495
+ class HfOption(click.Option):
496
+ """Option whose help record ports Typer's default/metavar rendering verbatim."""
497
+
498
+ show_default: bool | str
499
+
500
+ def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
501
+ if self.hidden:
502
+ return None
503
+
504
+ any_prefix_is_slash = False
505
+
506
+ def _write_opts(opts: Sequence[str]) -> str:
507
+ nonlocal any_prefix_is_slash
508
+ rv, any_slashes = click.formatting.join_options(opts)
509
+ if any_slashes:
510
+ any_prefix_is_slash = True
511
+ if not self.is_flag and not self.count:
512
+ rv += f" {self.make_metavar(ctx=ctx)}"
513
+ return rv
514
+
515
+ rv = [_write_opts(self.opts)]
516
+ if self.secondary_opts:
517
+ rv.append(_write_opts(self.secondary_opts))
518
+
519
+ help_text = _build_help_extra(self, ctx, self.help or "")
520
+ return ("; " if any_prefix_is_slash else " / ").join(rv), help_text
521
+
522
+
523
+ # ---------------------------------------------------------------------------
524
+ # 5. Command / group base classes and the decorator API (replace ``typer.Typer``).
525
+ # ---------------------------------------------------------------------------
526
+
527
+
528
+ def _format_params(command: click.Command, ctx: click.Context, formatter: click.HelpFormatter) -> None:
529
+ """Render params split into "Arguments" and "Options" sections (mirrors Typer)."""
530
+ args: list[tuple[str, str]] = []
531
+ opts: list[tuple[str, str]] = []
532
+ for param in command.get_params(ctx):
533
+ record = param.get_help_record(ctx)
534
+ if record is None:
535
+ continue
536
+ if param.param_type_name == "argument":
537
+ args.append(record)
538
+ elif param.param_type_name == "option":
539
+ opts.append(record)
540
+ if args:
541
+ with formatter.section("Arguments"):
542
+ formatter.write_dl(args)
543
+ if opts:
544
+ with formatter.section("Options"):
545
+ formatter.write_dl(opts)
546
+
547
+
548
+ class HfCommand(click.Command):
549
+ """Leaf command that renders arguments and options in separate help sections."""
550
+
551
+ def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
552
+ _format_params(self, ctx, formatter)
553
+
554
+
555
+ def build_command(
556
+ func: Callable[..., Any],
557
+ *,
558
+ name: str | None = None,
559
+ cls: type[click.Command] | None = None,
560
+ help: str | None = None,
561
+ epilog: str | None = None,
562
+ short_help: str | None = None,
563
+ options_metavar: str = "[OPTIONS]",
564
+ add_help_option: bool = True,
565
+ no_args_is_help: bool = False,
566
+ hidden: bool = False,
567
+ deprecated: bool = False,
568
+ context_settings: dict[str, Any] | None = None,
569
+ ) -> click.Command:
570
+ """Build a Click ``Command`` from a function with ``Annotated`` params.
571
+
572
+ Replaces ``typer.main.get_command_from_info``.
573
+ """
574
+ params, convertors, context_param_name = _build_params(func)
575
+ handler = _make_handler(func, convertors, context_param_name)
576
+ command_help = inspect.cleandoc(help) if help else inspect.getdoc(func)
577
+ return (cls or HfCommand)(
578
+ name=name if name is not None else get_command_name(func.__name__),
579
+ callback=handler,
580
+ params=params,
581
+ help=command_help,
582
+ epilog=epilog,
583
+ short_help=short_help,
584
+ options_metavar=options_metavar,
585
+ add_help_option=add_help_option,
586
+ no_args_is_help=no_args_is_help,
587
+ hidden=hidden,
588
+ deprecated=deprecated,
589
+ context_settings=context_settings or {},
590
+ )
591
+
592
+
593
+ class HfGroup(click.Group):
594
+ """Command group with the decorator API the CLI relies on (``command``/``callback``/``add_group``).
595
+
596
+ Subclasses (see ``HFCliTyperGroup``) layer on styling, aliases, topics and error
597
+ enrichment; this base only wires functions to Click via :func:`build_command`.
598
+ """
599
+
600
+ #: Command class used by ``@group.command()`` unless overridden per call.
601
+ command_class: type[click.Command] = HfCommand
602
+
603
+ def format_options(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
604
+ _format_params(self, ctx, formatter)
605
+ self.format_commands(ctx, formatter)
606
+
607
+ def list_commands(self, ctx: click.Context) -> list[str]:
608
+ # Preserve declaration order rather than Click's alphabetical default.
609
+ return list(self.commands)
610
+
611
+ def command( # type: ignore # deliberately narrows click.Group.command (builds from annotated signatures)
612
+ self, name: str | None = None, *, cls: type[click.Command] | None = None, **kwargs: Any
613
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
614
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
615
+ command = build_command(func, name=name, cls=cls or self.command_class, **kwargs)
616
+ self.add_command(command, command.name)
617
+ return func
618
+
619
+ return decorator
620
+
621
+ def add_group(self, group: click.Group, *, name: str, hidden: bool = False) -> None:
622
+ """Register a subgroup under ``name`` (which may carry pipe aliases, e.g. ``"repos | repo"``)."""
623
+ group.name = name
624
+ group.hidden = hidden
625
+ self.add_command(group, name)
626
+
627
+ def group_callback(
628
+ self, *, invoke_without_command: bool = False
629
+ ) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
630
+ """Register the function invoked for this group (named ``group_callback`` because Click
631
+ already uses the ``callback`` attribute for the group's own handler)."""
632
+
633
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
634
+ params, convertors, context_param_name = _build_params(func)
635
+ self.callback = _make_handler(func, convertors, context_param_name)
636
+ self.params = [*self.params, *params]
637
+ self.invoke_without_command = invoke_without_command
638
+ if invoke_without_command:
639
+ # Match Typer: the subcommand is optional when the group runs without one.
640
+ self.subcommand_metavar = "[COMMAND] [ARGS]..."
641
+ if self.help is None and func.__doc__:
642
+ self.help = inspect.cleandoc(func.__doc__)
643
+ return func
644
+
645
+ return decorator
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_help_formatter.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Pretty ANSI help formatter for the `hf` CLI."""
15
+
16
+ from collections.abc import Iterable
17
+
18
+ import click
19
+
20
+ from huggingface_hub.utils import ANSI
21
+
22
+
23
+ class StyledHelpFormatter(click.HelpFormatter):
24
+ def write_heading(self, heading: str) -> None:
25
+ styled = ANSI.underline(heading + ":")
26
+ self.write(f"{'':>{self.current_indent}}{styled}\n")
27
+
28
+ def write_dl(self, rows: Iterable[tuple[str, str]], col_max: int = 30, col_spacing: int = 2) -> None:
29
+ rows = [(ANSI.bold(first), second) for first, second in rows]
30
+ super().write_dl(rows, col_max=col_max, col_spacing=col_spacing)
31
+
32
+
33
+ class StyledContext(click.Context):
34
+ formatter_class = StyledHelpFormatter
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_output.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Output framework for the `hf` CLI."""
15
+
16
+ import dataclasses
17
+ import datetime
18
+ import json
19
+ import re
20
+ import shutil
21
+ import sys
22
+ from collections.abc import Sequence
23
+ from enum import Enum
24
+ from typing import Any, cast
25
+
26
+ import click
27
+
28
+ from huggingface_hub.errors import ConfirmationError
29
+ from huggingface_hub.utils import ANSI, StatusLine, disable_progress_bars, is_agent, tabulate
30
+
31
+
32
+ class OutputFormat(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
+ def _print_flush(*values: Any, **kwargs: Any) -> None:
43
+ """Like `print`, but always flushed: some CLI flows block on user action right after
44
+ printing (e.g. the device-code login), so output must not stay buffered."""
45
+ print(*values, **kwargs, flush=True)
46
+
47
+
48
+ class Output:
49
+ """Output sink for the `hf` CLI.
50
+
51
+ Mode is resolved once at init time based on `is_agent()` auto-detection
52
+ and can be overridden per-command via `set_mode()`.
53
+ """
54
+
55
+ mode: OutputFormat
56
+ no_truncate: bool
57
+
58
+ def __init__(self) -> None:
59
+ self.no_truncate = False
60
+ self.set_mode()
61
+
62
+ def set_mode(self, mode: OutputFormat = OutputFormat.auto) -> None:
63
+ """Override the output mode (called once at startup and again per '--format' flag)."""
64
+ if mode == OutputFormat.auto:
65
+ mode = OutputFormat.agent if is_agent() else OutputFormat.human
66
+ self.mode = mode
67
+ if mode != OutputFormat.human:
68
+ disable_progress_bars()
69
+
70
+ def set_no_truncate(self, no_truncate: bool) -> None:
71
+ """Toggle off cell truncation for human table output."""
72
+ self.no_truncate = no_truncate
73
+
74
+ def is_quiet(self) -> bool:
75
+ return self.mode == OutputFormat.quiet
76
+
77
+ def text(self, msg: str | None = None, *, human: str | None = None, agent: str | None = None) -> None:
78
+ """Print a free-form text message to stdout."""
79
+ if msg is not None:
80
+ if human is not None or agent is not None:
81
+ raise ValueError("Cannot mix 'msg' with 'human'/'agent'.")
82
+ human = msg
83
+ agent = _strip_ansi(msg)
84
+
85
+ match self.mode:
86
+ case OutputFormat.human:
87
+ if human is not None:
88
+ _print_flush(human)
89
+ case OutputFormat.agent:
90
+ if agent is not None:
91
+ _print_flush(agent)
92
+ # json/quiet: no-op
93
+
94
+ def table(
95
+ self,
96
+ items: Sequence[dict[str, Any]],
97
+ *,
98
+ headers: list[str] | None = None,
99
+ id_key: str | None = None,
100
+ alignments: dict[str, str] | None = None,
101
+ ) -> None:
102
+ """Print tabular data to stdout.
103
+
104
+ Args:
105
+ items: List of dicts. Headers are auto-detected from keys if not provided.
106
+ headers: Explicit column names. If None, derived from dict keys (all-None columns filtered).
107
+ id_key: Key to print in quiet mode. If None, uses the first header.
108
+ alignments: Optional mapping of header name to "left" or "right". Defaults to "left".
109
+ """
110
+ if not items:
111
+ match self.mode:
112
+ case OutputFormat.agent | OutputFormat.human:
113
+ _print_flush("No results found.")
114
+ case OutputFormat.json:
115
+ _print_flush("[]")
116
+ return
117
+
118
+ if headers is None:
119
+ all_columns = list(items[0].keys())
120
+ headers = [col for col in all_columns if any(item.get(col) is not None for item in items)]
121
+ rows = [[item.get(h) for h in headers] for item in items]
122
+
123
+ match self.mode:
124
+ case OutputFormat.human: # padded table, adaptive truncation, SCREAMING_SNAKE headers
125
+ screaming_headers = [_to_header(h) for h in headers]
126
+ formatted_rows: list[list[str]] = [[_format_table_value_human(v) for v in row] for row in rows]
127
+
128
+ is_truncated = _truncate_columns(screaming_headers, formatted_rows, no_truncate=self.no_truncate)
129
+
130
+ inferred = {**_infer_alignments(headers, rows), **(alignments or {})}
131
+ screaming_alignments = {_to_header(k): v for k, v in inferred.items()}
132
+ _print_flush(
133
+ tabulate(
134
+ cast("list[list[str | int]]", formatted_rows),
135
+ headers=screaming_headers,
136
+ alignments=screaming_alignments,
137
+ ),
138
+ )
139
+ if is_truncated:
140
+ self.hint("Use `--no-truncate` or `--format json` to display full values.")
141
+ case OutputFormat.agent: # TSV, no truncation, full timestamps
142
+ _print_flush("\t".join(headers))
143
+ for row in rows:
144
+ _print_flush("\t".join(_format_table_cell_agent(v) for v in row))
145
+ case OutputFormat.json: # compact JSON array
146
+ _print_flush(json.dumps(list(items), default=str))
147
+ case OutputFormat.quiet: # id_key column (or first column), one per line
148
+ quiet_key = id_key or headers[0]
149
+ for item in items:
150
+ _print_flush(item.get(quiet_key, ""))
151
+
152
+ def dict(self, data: Any, *, id_key: str | None = None) -> None:
153
+ """Print structured data as JSON in all modes (indented for human, compact otherwise).
154
+
155
+ Accepts a dict or a dataclass.
156
+ """
157
+ if dataclasses.is_dataclass(data) and not isinstance(data, type):
158
+ data = _dataclass_to_dict(data)
159
+ if self.mode == OutputFormat.quiet and id_key is not None:
160
+ _print_flush(data.get(id_key, ""))
161
+ return
162
+ indent = 2 if self.mode == OutputFormat.human else None
163
+ _print_flush(json.dumps(data, indent=indent, default=str))
164
+
165
+ def result(self, message: str, **data: Any) -> None:
166
+ """Print a success summary to stdout."""
167
+ match self.mode:
168
+ case OutputFormat.human: # ✓ message + key: value lines
169
+ parts = [ANSI.green(f"✓ {message}")]
170
+ for k, v in data.items():
171
+ if v is not None:
172
+ parts.append(f" {k}: {v}")
173
+ _print_flush("\n".join(parts))
174
+ case OutputFormat.agent: # key=val pairs, space-separated
175
+ parts = [f"{k}={v}" for k, v in data.items() if v is not None]
176
+ _print_flush(" ".join(parts) if parts else message)
177
+ case OutputFormat.json: # json.dumps(data), message ignored
178
+ _print_flush(json.dumps(data, default=str) if data else "")
179
+ case OutputFormat.quiet: # first value only
180
+ values = list(data.values())
181
+ if values:
182
+ _print_flush(values[0])
183
+
184
+ def confirm(self, message: str, *, default: bool = False, yes: bool = False, confirm_param: str = "--yes") -> None:
185
+ """
186
+ Ask for confirmation. Raises `ConfirmationError` in non-human modes.
187
+ """
188
+ if yes:
189
+ return
190
+ if self.mode != OutputFormat.human:
191
+ raise ConfirmationError(f"{message} Use {confirm_param} to skip confirmation.")
192
+ click.confirm(message, default=default, abort=True)
193
+
194
+ def status(self, message: str | None = None) -> StatusLine:
195
+ """Return a status line that emits only in human mode (no-op otherwise)."""
196
+ status = StatusLine(enabled=self.mode == OutputFormat.human)
197
+ if message is not None:
198
+ status.update(message)
199
+ return status
200
+
201
+ def warning(self, message: str) -> None:
202
+ """Print a non-fatal warning to stderr (all modes)."""
203
+ if self.mode == OutputFormat.human:
204
+ _print_flush(ANSI.yellow(f"Warning: {message}"), file=sys.stderr)
205
+ else:
206
+ _print_flush(f"Warning: {message}", file=sys.stderr)
207
+
208
+ def error(self, message: str) -> None:
209
+ """Print an error to stderr (all modes)."""
210
+ if self.mode == OutputFormat.human:
211
+ _print_flush(ANSI.red(f"Error: {message}"), file=sys.stderr)
212
+ else:
213
+ _print_flush(f"Error: {message}", file=sys.stderr)
214
+
215
+ def log(self, message: str) -> None:
216
+ """Print a text message to stderr (human: gray, json/agent: plain text).
217
+
218
+ Suppressed in quiet mode. Kept in json mode (like agent) since agents
219
+ commonly run with ``--format json`` and the message goes to stderr so
220
+ it never pollutes the parsed stdout.
221
+ """
222
+ if self.mode == OutputFormat.quiet:
223
+ return
224
+ if self.mode == OutputFormat.human:
225
+ _print_flush(ANSI.gray(message), file=sys.stderr)
226
+ else:
227
+ _print_flush(message, file=sys.stderr)
228
+
229
+ def hint(self, message: str) -> None:
230
+ """Print a helpful hint to stderr (human: gray, json/agent: plain text).
231
+
232
+ Suppressed in quiet mode. Kept in json mode (like agent) since agents
233
+ commonly run with ``--format json`` and the next-command hints are useful
234
+ there; hints go to stderr so they never pollute the parsed stdout.
235
+ """
236
+ self.log(f"Hint: {message}")
237
+
238
+
239
+ # HELPERS
240
+
241
+
242
+ def _serialize_value(v: object) -> object:
243
+ """Recursively serialize a value to be JSON-compatible."""
244
+ if isinstance(v, datetime.datetime):
245
+ return v.isoformat()
246
+ elif isinstance(v, dict):
247
+ return {key: _serialize_value(val) for key, val in v.items() if val is not None}
248
+ elif isinstance(v, list):
249
+ return [_serialize_value(item) for item in v]
250
+ return v
251
+
252
+
253
+ def _dataclass_to_dict(info: Any) -> dict[str, Any]:
254
+ """Convert a dataclass to a json-serializable dict."""
255
+ return {k: _serialize_value(v) for k, v in dataclasses.asdict(info).items() if v is not None}
256
+
257
+
258
+ _ANSI_RE = re.compile(r"\033\[[0-9;]*m")
259
+
260
+
261
+ def _strip_ansi(text: str) -> str:
262
+ return _ANSI_RE.sub("", text)
263
+
264
+
265
+ def _single_line(text: str) -> str:
266
+ return " ".join(text.split())
267
+
268
+
269
+ def _to_header(name: str) -> str:
270
+ """Convert a camelCase or PascalCase string to SCREAMING_SNAKE_CASE."""
271
+ s = re.sub(r"([a-z])([A-Z])", r"\1_\2", name)
272
+ return s.upper()
273
+
274
+
275
+ def _infer_alignments(headers: list[str], rows: list[list[Any]]) -> dict[str, str]:
276
+ """Return ``{"col": "right"}`` for columns where every non-None value is numeric."""
277
+ result: dict[str, str] = {}
278
+ for c, h in enumerate(headers):
279
+ if all(row[c] is None or (isinstance(row[c], (int, float)) and not isinstance(row[c], bool)) for row in rows):
280
+ result[h] = "right"
281
+ return result
282
+
283
+
284
+ def _format_table_value_human(value: Any) -> str:
285
+ """Convert a value to string for terminal display."""
286
+ if value is None:
287
+ return ""
288
+ if isinstance(value, bool):
289
+ return "✔" if value else ""
290
+ if isinstance(value, datetime.datetime):
291
+ return value.strftime("%Y-%m-%d")
292
+ if isinstance(value, str) and re.match(r"^\d{4}-\d{2}-\d{2}T", value):
293
+ return value[:10]
294
+ if isinstance(value, str):
295
+ return _single_line(value)
296
+ if isinstance(value, list):
297
+ return ", ".join(_format_table_value_human(v) for v in value)
298
+ elif isinstance(value, dict):
299
+ if "name" in value: # Likely to be a user or org => print name
300
+ return _single_line(str(value["name"]))
301
+ return _single_line(json.dumps(value))
302
+ return _single_line(str(value))
303
+
304
+
305
+ def _truncate_columns(
306
+ headers: list[str],
307
+ rows: list[list[str]],
308
+ *,
309
+ no_truncate: bool,
310
+ ) -> bool:
311
+ """Truncate cells in-place to fit the current terminal width.
312
+
313
+ Returns `True` if any cell was truncated, so the caller can emit a hint.
314
+ `shutil.get_terminal_size` is cross-platform: it honors `$COLUMNS`, then
315
+ queries the OS-native API, then falls back to `(80, 24)`.
316
+ """
317
+ if no_truncate or not rows:
318
+ return False
319
+
320
+ n = len(headers)
321
+ # Per-column natural width: longest of header label and cell values.
322
+ natural = [max(len(headers[c]), *(len(rows[r][c]) for r in range(len(rows)))) for c in range(n)]
323
+
324
+ # `max(0, n - 1)` accounts for the single-space separator between columns.
325
+ budget = shutil.get_terminal_size().columns - max(0, n - 1)
326
+ if sum(natural) <= budget:
327
+ return False
328
+
329
+ # Shrink the widest column 1 char at a time. Floors keep the header label
330
+ # visible; the `4` is the smallest cap that still shows "x..." (one content
331
+ # char plus the "..." marker).
332
+ caps = natural.copy()
333
+ min_widths = [max(len(h), 4) for h in headers]
334
+ while sum(caps) > budget:
335
+ widest = max(
336
+ (i for i, w in enumerate(caps) if w > min_widths[i]),
337
+ key=lambda i: caps[i],
338
+ default=-1,
339
+ )
340
+ if widest < 0:
341
+ break # everything at floor — table wraps slightly
342
+ caps[widest] -= 1
343
+
344
+ truncated = False
345
+ for row in rows:
346
+ for c, cell in enumerate(row):
347
+ if len(cell) > caps[c]:
348
+ truncated = True
349
+ row[c] = cell[: caps[c] - 3] + "..."
350
+ return truncated
351
+
352
+
353
+ def _format_table_cell_agent(value: Any) -> str:
354
+ """Format a cell value for agent TSV output (ISO timestamps, tabs escaped)."""
355
+ if isinstance(value, datetime.datetime):
356
+ return value.isoformat()
357
+ return _single_line(str(value))
358
+
359
+
360
+ out = Output()
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/_skills.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal helpers for Hugging Face marketplace skill installation and upgrades."""
2
+
3
+ import json
4
+ import re
5
+ import shutil
6
+ import tempfile
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass, replace
9
+ from pathlib import Path, PurePosixPath
10
+ from typing import Any, Literal
11
+
12
+ from huggingface_hub._buckets import BucketFile
13
+ from huggingface_hub.errors import CLIError
14
+
15
+ from ..utils import disable_progress_bars
16
+ from ._cli_utils import get_hf_api
17
+
18
+
19
+ DEFAULT_SKILL_ID = "hf-cli"
20
+ DEFAULT_SKILLS_BUCKET_ID = "huggingface/skills"
21
+ MARKETPLACE_PATH = "marketplace.json"
22
+ # Empty marker file dropped into managed skill installs so `hf skills update` knows
23
+ # to touch them and leave user-placed skill dirs alone. Filename is historical (used
24
+ # to be a JSON manifest with a revision); we keep it for backward compat with installs
25
+ # made by previous versions.
26
+ MANAGED_MARKER_FILENAME = ".hf-skill-manifest.json"
27
+
28
+ SkillUpdateStatus = Literal["up_to_date", "unmanaged", "source_unreachable"]
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class MarketplaceSkill:
33
+ name: str
34
+ repo_path: str
35
+ description: str | None = None
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class SkillUpdateInfo:
40
+ name: str
41
+ skill_dir: Path
42
+ status: SkillUpdateStatus
43
+ detail: str | None = None
44
+
45
+
46
+ def add_skill(skill_name: str, destination_root: Path, force: bool = False) -> Path:
47
+ """Resolve a marketplace skill by name and install it."""
48
+ api = get_hf_api()
49
+ with disable_progress_bars():
50
+ marketplace_skills = _load_marketplace_skills(api)
51
+ skill = _select_marketplace_skill(marketplace_skills, skill_name)
52
+ if skill is None:
53
+ raise CLIError(
54
+ f"Skill '{skill_name}' not found in {DEFAULT_SKILLS_BUCKET_ID}. "
55
+ "Try `hf skills add` to install `hf-cli` or use a known skill name."
56
+ )
57
+ return _install_marketplace_skill(api, skill, destination_root, force=force)
58
+
59
+
60
+ def install_generated_skill(content: str, destination_root: Path, force: bool = False) -> Path:
61
+ """Install the `hf-cli` skill from locally generated SKILL.md content (no bucket download)."""
62
+
63
+ def populate(install_dir: Path) -> None:
64
+ install_dir.mkdir(parents=True, exist_ok=True)
65
+ (install_dir / "SKILL.md").write_text(content, encoding="utf-8")
66
+ (install_dir / MANAGED_MARKER_FILENAME).touch()
67
+
68
+ return _install_skill(DEFAULT_SKILL_ID, destination_root, populate=populate, force=force)
69
+
70
+
71
+ def update_skills(roots: list[Path], selector: str | None = None, *, hf_cli_content: str) -> list[SkillUpdateInfo]:
72
+ """Re-sync managed skill installs (`hf-cli` is rewritten from `hf_cli_content`, the rest from the bucket)."""
73
+ skill_dirs = _iter_unique_skill_dirs(roots)
74
+ if selector is not None:
75
+ selector_lower = selector.strip().lower()
76
+ skill_dirs = [d for d in skill_dirs if d.name.lower() == selector_lower]
77
+ if not skill_dirs:
78
+ raise CLIError(f"No installed skill matches '{selector}'. Install it with `hf skills add {selector}`.")
79
+
80
+ # `hf-cli` is regenerated locally, so only hit the marketplace when another managed skill needs it.
81
+ needs_marketplace = any(d.name != DEFAULT_SKILL_ID and (d / MANAGED_MARKER_FILENAME).exists() for d in skill_dirs)
82
+ api = None
83
+ marketplace_skills: dict[str, MarketplaceSkill] = {}
84
+ if needs_marketplace:
85
+ api = get_hf_api()
86
+ with disable_progress_bars():
87
+ marketplace_skills = {skill.name.lower(): skill for skill in _load_marketplace_skills(api)}
88
+
89
+ return [_apply_single_update(api, skill_dir, marketplace_skills, hf_cli_content) for skill_dir in skill_dirs]
90
+
91
+
92
+ def _load_marketplace_skills(api) -> list[MarketplaceSkill]:
93
+ payload = _load_marketplace_payload(api)
94
+ plugins = payload.get("plugins")
95
+ if not isinstance(plugins, list):
96
+ raise CLIError("Invalid marketplace payload: expected a top-level 'plugins' list.")
97
+
98
+ skills: list[MarketplaceSkill] = []
99
+ for plugin in plugins:
100
+ if not isinstance(plugin, dict):
101
+ continue
102
+ name = plugin.get("name")
103
+ source = plugin.get("source")
104
+ if not isinstance(name, str) or not isinstance(source, str):
105
+ continue
106
+ description = plugin.get("description")
107
+ skills.append(
108
+ MarketplaceSkill(
109
+ name=name,
110
+ repo_path=_normalize_repo_path(source),
111
+ description=description if isinstance(description, str) else None,
112
+ )
113
+ )
114
+ return skills
115
+
116
+
117
+ def _install_marketplace_skill(api, skill: MarketplaceSkill, destination_root: Path, force: bool = False) -> Path:
118
+ """Install a marketplace skill into a local skills directory."""
119
+
120
+ def populate(install_dir: Path) -> None:
121
+ install_dir.mkdir(parents=True, exist_ok=True)
122
+ bucket_files = _list_skill_files(api, skill)
123
+ _download_skill_files(api, skill, bucket_files, install_dir)
124
+ _validate_installed_skill_dir(install_dir)
125
+ (install_dir / MANAGED_MARKER_FILENAME).touch()
126
+
127
+ return _install_skill(skill.name, destination_root, populate=populate, force=force)
128
+
129
+
130
+ _VALID_SKILL_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
131
+
132
+
133
+ def _install_skill(
134
+ name: str,
135
+ destination_root: Path,
136
+ populate: Callable[[Path], None],
137
+ force: bool = False,
138
+ ) -> Path:
139
+ """Install a skill into ``destination_root`` by calling ``populate(install_dir)`` to fill it.
140
+
141
+ Used by both the marketplace install (populate = download from bucket) and the
142
+ locally-generated install (populate = write content). When the install already
143
+ exists and ``force`` is set, the new content is staged in a sibling tempdir and
144
+ atomically swapped in, so the existing install stays intact if ``populate``
145
+ fails halfway through.
146
+ """
147
+ # `name` may come from the remote marketplace payload and the install dir is removed on
148
+ # reinstall: validate it as defense-in-depth against path traversal.
149
+ if not _VALID_SKILL_NAME.fullmatch(name):
150
+ raise CLIError(f"Invalid skill name '{name}'.")
151
+ destination_root = destination_root.expanduser().resolve()
152
+ destination_root.mkdir(parents=True, exist_ok=True)
153
+ install_dir = destination_root / name
154
+ already_exists = install_dir.exists()
155
+
156
+ if already_exists and not force:
157
+ raise FileExistsError(f"Skill already exists: {install_dir}")
158
+
159
+ if already_exists:
160
+ with tempfile.TemporaryDirectory(dir=destination_root, prefix=f".{install_dir.name}.install-") as tmp_dir_str:
161
+ staged_dir = Path(tmp_dir_str) / install_dir.name
162
+ populate(staged_dir)
163
+ _atomic_replace_directory(existing_dir=install_dir, staged_dir=staged_dir)
164
+ return install_dir
165
+
166
+ try:
167
+ populate(install_dir)
168
+ except Exception:
169
+ if install_dir.exists():
170
+ shutil.rmtree(install_dir)
171
+ raise
172
+ return install_dir
173
+
174
+
175
+ def _load_marketplace_payload(api) -> dict[str, Any]:
176
+ with tempfile.TemporaryDirectory() as tmp_dir:
177
+ local_path = Path(tmp_dir) / "marketplace.json"
178
+ api.download_bucket_files(
179
+ DEFAULT_SKILLS_BUCKET_ID,
180
+ [(MARKETPLACE_PATH, local_path)],
181
+ raise_on_missing_files=True,
182
+ )
183
+ parsed = json.loads(local_path.read_text(encoding="utf-8"))
184
+
185
+ if not isinstance(parsed, dict):
186
+ raise CLIError("Invalid marketplace payload: expected a JSON object.")
187
+ return parsed
188
+
189
+
190
+ def _select_marketplace_skill(skills: list[MarketplaceSkill], selector: str) -> MarketplaceSkill | None:
191
+ selector_lower = selector.strip().lower()
192
+ for skill in skills:
193
+ if skill.name.lower() == selector_lower:
194
+ return skill
195
+ return None
196
+
197
+
198
+ def _normalize_repo_path(path: str) -> str:
199
+ normalized = path.strip()
200
+ while normalized.startswith("./"):
201
+ normalized = normalized[2:]
202
+ normalized = normalized.strip("/")
203
+ if not normalized:
204
+ raise CLIError("Invalid marketplace entry: empty source path.")
205
+ return normalized
206
+
207
+
208
+ def _validate_installed_skill_dir(skill_dir: Path) -> None:
209
+ skill_file = skill_dir / "SKILL.md"
210
+ if not skill_file.is_file():
211
+ raise RuntimeError(f"Installed skill is missing SKILL.md: {skill_file}")
212
+
213
+
214
+ def _list_skill_files(api, skill: MarketplaceSkill) -> list[BucketFile]:
215
+ """List all files under `skill.repo_path` in the marketplace bucket."""
216
+ prefix = skill.repo_path.rstrip("/")
217
+ files: list[BucketFile] = [
218
+ item
219
+ for item in api.list_bucket_tree(DEFAULT_SKILLS_BUCKET_ID, prefix=prefix, recursive=True)
220
+ if isinstance(item, BucketFile)
221
+ ]
222
+ if not files:
223
+ raise FileNotFoundError(f"Path '{prefix}' not found in bucket '{DEFAULT_SKILLS_BUCKET_ID}'.")
224
+ return files
225
+
226
+
227
+ def _download_skill_files(api, skill: MarketplaceSkill, files: list[BucketFile], install_dir: Path) -> None:
228
+ """Download bucket files into `install_dir`."""
229
+ prefix = skill.repo_path.rstrip("/")
230
+ prefix_with_slash = f"{prefix}/"
231
+
232
+ # `list_bucket_tree(prefix=...)` matches as a raw string prefix, so e.g. asking for
233
+ # "skills/gradio" can also return "skills/gradio-tools/...". Filter on the trailing
234
+ # slash to keep only files actually inside the directory, then strip it so files land
235
+ # directly under `install_dir` preserving any nested structure.
236
+ download_specs: list[tuple[str | BucketFile, str | Path]] = []
237
+ for bucket_file in files:
238
+ if not bucket_file.path.startswith(prefix_with_slash):
239
+ continue
240
+ relative = bucket_file.path[len(prefix_with_slash) :]
241
+ local_file = install_dir.joinpath(*PurePosixPath(relative).parts)
242
+ local_file.parent.mkdir(parents=True, exist_ok=True)
243
+ download_specs.append((bucket_file, local_file))
244
+
245
+ if not download_specs:
246
+ raise FileNotFoundError(f"No files found under '{prefix}' in bucket '{DEFAULT_SKILLS_BUCKET_ID}'.")
247
+
248
+ api.download_bucket_files(DEFAULT_SKILLS_BUCKET_ID, download_specs)
249
+
250
+
251
+ def _atomic_replace_directory(existing_dir: Path, staged_dir: Path) -> None:
252
+ backup_dir = staged_dir.parent / f"{existing_dir.name}.backup"
253
+ try:
254
+ existing_dir.rename(backup_dir)
255
+ staged_dir.rename(existing_dir)
256
+ shutil.rmtree(backup_dir)
257
+ except Exception:
258
+ if backup_dir.exists() and not existing_dir.exists():
259
+ backup_dir.rename(existing_dir)
260
+ raise
261
+
262
+
263
+ def _iter_unique_skill_dirs(roots: list[Path]) -> list[Path]:
264
+ seen: set[Path] = set()
265
+ discovered: list[Path] = []
266
+ for root in roots:
267
+ root = root.expanduser().resolve()
268
+ if not root.is_dir():
269
+ continue
270
+ for child in sorted(root.iterdir()):
271
+ if child.name.startswith("."):
272
+ continue
273
+ if not child.is_dir() and not child.is_symlink():
274
+ continue
275
+ resolved = child.resolve()
276
+ if resolved in seen or not resolved.is_dir():
277
+ continue
278
+ seen.add(resolved)
279
+ discovered.append(resolved)
280
+ return discovered
281
+
282
+
283
+ def _apply_single_update(
284
+ api, skill_dir: Path, marketplace_skills: dict[str, MarketplaceSkill], hf_cli_content: str
285
+ ) -> SkillUpdateInfo:
286
+ base = SkillUpdateInfo(name=skill_dir.name, skill_dir=skill_dir, status="unmanaged")
287
+
288
+ if not (skill_dir / MANAGED_MARKER_FILENAME).exists():
289
+ return base
290
+
291
+ if skill_dir.name == DEFAULT_SKILL_ID:
292
+ try:
293
+ install_generated_skill(hf_cli_content, skill_dir.parent, force=True)
294
+ except Exception as exc:
295
+ return replace(base, status="source_unreachable", detail=str(exc))
296
+ return replace(base, status="up_to_date")
297
+
298
+ skill = marketplace_skills.get(skill_dir.name.lower())
299
+ if skill is None:
300
+ return replace(
301
+ base,
302
+ status="source_unreachable",
303
+ detail=f"Skill '{skill_dir.name}' is no longer available in {DEFAULT_SKILLS_BUCKET_ID}.",
304
+ )
305
+
306
+ try:
307
+ _install_marketplace_skill(api, skill, skill_dir.parent, force=True)
308
+ except Exception as exc:
309
+ return replace(base, status="source_unreachable", detail=str(exc))
310
+
311
+ return replace(base, status="up_to_date")
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/auth.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains commands to authenticate to the Hugging Face Hub and interact with your repositories."""
15
+
16
+ from typing import Annotated
17
+
18
+ import click
19
+
20
+ from huggingface_hub.constants import ENDPOINT
21
+ from huggingface_hub.hf_api import whoami
22
+
23
+ from .._login import _save_oauth_token, auth_list, auth_switch, login, logout
24
+ from ..errors import CLIError
25
+ from ..utils import get_stored_tokens, get_token, logging, select_choice
26
+ from ..utils._oauth_device import poll_device_token, request_device_code
27
+ from ._cli_utils import TokenOpt, typer_factory
28
+ from ._framework import Option
29
+ from ._output import OutputFormat, out
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ auth_cli = typer_factory(help="Manage authentication (login, logout, etc.).")
36
+
37
+
38
+ @auth_cli.command(
39
+ "login",
40
+ examples=[
41
+ "hf auth login",
42
+ "hf auth login --token $HF_TOKEN",
43
+ "hf auth login --token $HF_TOKEN --add-to-git-credential",
44
+ "hf auth login --force",
45
+ ],
46
+ )
47
+ def auth_login(
48
+ token: TokenOpt = None,
49
+ add_to_git_credential: Annotated[
50
+ bool,
51
+ Option(
52
+ help="Save to git credential helper. Useful only if you plan to run git commands directly.",
53
+ ),
54
+ ] = False,
55
+ force: Annotated[
56
+ bool,
57
+ Option(
58
+ help="Force re-login even if already logged in.",
59
+ ),
60
+ ] = False,
61
+ ) -> None:
62
+ """Login from your browser, or using a token from huggingface.co/settings/tokens."""
63
+ if token is not None or out.mode == OutputFormat.human:
64
+ # `--token` bypasses any prompt; in human mode the gh-style menu lives in `login()`.
65
+ login(token=token, add_to_git_credential=add_to_git_credential, skip_if_logged_in=not force)
66
+ return
67
+
68
+ # Logging in is an interactive flow: besides human mode, only agent mode is supported.
69
+ if out.mode != OutputFormat.agent:
70
+ raise CLIError(
71
+ "`hf auth login` is interactive and does not support --format json/quiet. "
72
+ "Pass --token for a non-interactive login."
73
+ )
74
+
75
+ # agent mode: never prompt; print instructions the agent can relay to its user.
76
+ if not force and get_token() is not None:
77
+ out.text(agent="Already logged in. Use `hf auth login --force` to re-login.")
78
+ return
79
+ device_info = request_device_code()
80
+ out.text(
81
+ agent=(
82
+ f"Ask the user to open {device_info['verification_uri_complete']} in a browser and enter the code "
83
+ f"{device_info['user_code']}. The code expires in {device_info['expires_in']} seconds. "
84
+ "Waiting for authorization..."
85
+ )
86
+ )
87
+ response = poll_device_token(device_info)
88
+ token_name, username = _save_oauth_token(response)
89
+ out.text(agent=f"Login successful: logged in as {username} (token saved as '{token_name}').")
90
+
91
+
92
+ @auth_cli.command(
93
+ "logout",
94
+ examples=["hf auth logout", "hf auth logout --token-name my-token"],
95
+ )
96
+ def auth_logout(
97
+ token_name: Annotated[
98
+ str | None,
99
+ Option(help="Name of token to logout"),
100
+ ] = None,
101
+ ) -> None:
102
+ """Logout from a specific token."""
103
+ logout(token_name=token_name)
104
+
105
+
106
+ def _select_token_name() -> str | None:
107
+ token_names = list(get_stored_tokens().keys())
108
+
109
+ if not token_names:
110
+ logger.error("No stored tokens found. Please login first.")
111
+ return None
112
+
113
+ if out.mode != OutputFormat.human:
114
+ raise CLIError("Use --token-name to select a token in non-interactive mode.")
115
+ return token_names[select_choice("Select a token to switch to:", token_names)]
116
+
117
+
118
+ @auth_cli.command(
119
+ "switch",
120
+ examples=["hf auth switch", "hf auth switch --token-name my-token"],
121
+ )
122
+ def auth_switch_cmd(
123
+ token_name: Annotated[
124
+ str | None,
125
+ Option(
126
+ help="Name of the token to switch to",
127
+ ),
128
+ ] = None,
129
+ add_to_git_credential: Annotated[
130
+ bool,
131
+ Option(
132
+ help="Save to git credential helper. Useful only if you plan to run git commands directly.",
133
+ ),
134
+ ] = False,
135
+ ) -> None:
136
+ """Switch between access tokens."""
137
+ if token_name is None:
138
+ token_name = _select_token_name()
139
+ if token_name is None:
140
+ print("No token name provided. Aborting.")
141
+ raise click.exceptions.Exit()
142
+ auth_switch(token_name, add_to_git_credential=add_to_git_credential)
143
+
144
+
145
+ @auth_cli.command("list | ls", examples=["hf auth list"])
146
+ def auth_list_cmd() -> None:
147
+ """List all stored access tokens."""
148
+ auth_list()
149
+
150
+
151
+ @auth_cli.command("token", examples=["hf auth token", "hf auth token | xargs curl -H 'Authorization: Bearer {}'"])
152
+ def auth_token() -> None:
153
+ """Print the current access token to stdout."""
154
+ token = get_token()
155
+ if token is None:
156
+ out.error("Not logged in. Run `hf auth login` first.")
157
+ raise click.exceptions.Exit(code=1)
158
+ print(token)
159
+ out.hint("Run `hf auth whoami` to see which account this token belongs to.")
160
+
161
+
162
+ @auth_cli.command("whoami", examples=["hf auth whoami", "hf auth whoami --format json"])
163
+ def auth_whoami() -> None:
164
+ """Find out which huggingface.co account you are logged in as."""
165
+
166
+ token = get_token()
167
+ if token is None:
168
+ out.error("Not logged in")
169
+ raise click.exceptions.Exit(code=1)
170
+
171
+ info = whoami(token)
172
+ orgs = ",".join(org["name"] for org in info["orgs"]) or None
173
+ endpoint = ENDPOINT if ENDPOINT != "https://huggingface.co" else None
174
+ out.result("Logged in", user=info["name"], orgs=orgs, endpoint=endpoint)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/buckets.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains commands to interact with buckets via the CLI."""
15
+
16
+ from typing import Annotated
17
+
18
+ import click
19
+
20
+ from huggingface_hub import logging
21
+ from huggingface_hub._buckets import (
22
+ BUCKET_PREFIX,
23
+ BucketFile,
24
+ FilterMatcher,
25
+ _parse_bucket_uri,
26
+ )
27
+
28
+ from ..hf_api import REPO_REGIONS
29
+ from ._cli_utils import (
30
+ SearchOpt,
31
+ TokenOpt,
32
+ get_hf_api,
33
+ typer_factory,
34
+ )
35
+ from ._cp import make_cp
36
+ from ._file_listing import format_size, print_file_listing
37
+ from ._framework import Argument, Option
38
+ from ._output import OutputFormat, out
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+
44
+ buckets_cli = typer_factory(help="Commands to interact with buckets.")
45
+
46
+
47
+ @buckets_cli.command(
48
+ name="create",
49
+ examples=[
50
+ "hf buckets create my-bucket",
51
+ "hf buckets create user/my-bucket",
52
+ "hf buckets create hf://buckets/user/my-bucket",
53
+ "hf buckets create user/my-bucket --private",
54
+ "hf buckets create user/my-bucket --exist-ok",
55
+ "hf buckets create user/my-bucket --region us",
56
+ ],
57
+ )
58
+ def create(
59
+ bucket_id: Annotated[
60
+ str,
61
+ Argument(
62
+ help="Bucket ID: bucket_name, namespace/bucket_name, or hf://buckets/namespace/bucket_name",
63
+ ),
64
+ ],
65
+ private: Annotated[
66
+ bool,
67
+ Option(
68
+ "--private",
69
+ help="Create a private bucket.",
70
+ ),
71
+ ] = False,
72
+ region: Annotated[
73
+ REPO_REGIONS | None,
74
+ Option(
75
+ "--region",
76
+ help="Cloud region in which to create the bucket. Can be one of 'us' or 'eu'. Requires Team plan or above.",
77
+ ),
78
+ ] = None,
79
+ exist_ok: Annotated[
80
+ bool,
81
+ Option(
82
+ "--exist-ok",
83
+ help="Do not raise an error if the bucket already exists.",
84
+ ),
85
+ ] = False,
86
+ token: TokenOpt = None,
87
+ ) -> None:
88
+ """Create a new bucket."""
89
+ api = get_hf_api(token=token)
90
+
91
+ if bucket_id.startswith(BUCKET_PREFIX):
92
+ parsed = _parse_bucket_uri(bucket_id)
93
+ if parsed.path_in_repo:
94
+ raise click.BadParameter(
95
+ f"Cannot specify a prefix for bucket creation: {bucket_id}."
96
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
97
+ )
98
+ bucket_id = parsed.id
99
+
100
+ bucket_url = api.create_bucket(
101
+ bucket_id,
102
+ private=private if private else None,
103
+ region=region,
104
+ exist_ok=exist_ok,
105
+ )
106
+ out.result("Bucket created", uri=bucket_url.uri.to_uri(), url=bucket_url.url)
107
+
108
+
109
+ def _is_bucket_id(argument: str) -> bool:
110
+ """Check if argument is a bucket ID (namespace/name) vs just a namespace."""
111
+ if argument.startswith(BUCKET_PREFIX):
112
+ path = argument[len(BUCKET_PREFIX) :]
113
+ else:
114
+ path = argument
115
+ return "/" in path
116
+
117
+
118
+ @buckets_cli.command(
119
+ name="list | ls",
120
+ examples=[
121
+ "hf buckets list",
122
+ "hf buckets list huggingface",
123
+ 'hf buckets list --search "my-prefix"',
124
+ "hf buckets list user/my-bucket",
125
+ "hf buckets list user/my-bucket -R",
126
+ "hf buckets list user/my-bucket -h",
127
+ "hf buckets list user/my-bucket --tree",
128
+ "hf buckets list user/my-bucket --tree -h",
129
+ "hf buckets list hf://buckets/user/my-bucket",
130
+ "hf buckets list user/my-bucket/sub -R",
131
+ ],
132
+ )
133
+ def list_cmd(
134
+ argument: Annotated[
135
+ str | None,
136
+ Argument(
137
+ help=(
138
+ "Namespace (user or org) to list buckets, or bucket ID"
139
+ " (namespace/bucket_name(/prefix) or hf://buckets/...) to list files."
140
+ ),
141
+ ),
142
+ ] = None,
143
+ human_readable: Annotated[
144
+ bool,
145
+ Option(
146
+ "--human-readable",
147
+ "-h",
148
+ help="Show sizes in human readable format.",
149
+ ),
150
+ ] = False,
151
+ as_tree: Annotated[
152
+ bool,
153
+ Option(
154
+ "--tree",
155
+ help="List files in tree format (only for listing files).",
156
+ ),
157
+ ] = False,
158
+ recursive: Annotated[
159
+ bool,
160
+ Option(
161
+ "--recursive",
162
+ "-R",
163
+ help="List files recursively (only for listing files).",
164
+ ),
165
+ ] = False,
166
+ search: SearchOpt = None,
167
+ token: TokenOpt = None,
168
+ ) -> None:
169
+ """List buckets or files in a bucket.
170
+
171
+ When called with no argument or a namespace, lists buckets.
172
+ When called with a bucket ID (namespace/bucket_name), lists files in the bucket.
173
+ """
174
+ # Determine mode: listing buckets or listing files
175
+ is_file_mode = argument is not None and _is_bucket_id(argument)
176
+
177
+ if is_file_mode:
178
+ if search is not None:
179
+ raise click.BadParameter("Cannot use --search when listing files.")
180
+ _list_files(
181
+ argument=argument, # type: ignore
182
+ human_readable=human_readable,
183
+ as_tree=as_tree,
184
+ recursive=recursive,
185
+ token=token,
186
+ )
187
+ else:
188
+ _list_buckets(
189
+ namespace=argument,
190
+ search=search,
191
+ human_readable=human_readable,
192
+ as_tree=as_tree,
193
+ recursive=recursive,
194
+ token=token,
195
+ )
196
+
197
+
198
+ def _list_buckets(
199
+ namespace: str | None,
200
+ search: str | None,
201
+ human_readable: bool,
202
+ as_tree: bool,
203
+ recursive: bool,
204
+ token: str | None,
205
+ ) -> None:
206
+ """List buckets in a namespace."""
207
+ # Validate incompatible flags
208
+ if as_tree:
209
+ raise click.BadParameter("Cannot use --tree when listing buckets.")
210
+ if recursive:
211
+ raise click.BadParameter("Cannot use --recursive when listing buckets.")
212
+
213
+ # Handle hf://buckets/namespace format
214
+ if namespace is not None and namespace.startswith(BUCKET_PREFIX):
215
+ namespace = namespace[len(BUCKET_PREFIX) :]
216
+ # Strip trailing slash if any
217
+ namespace = namespace.rstrip("/")
218
+
219
+ api = get_hf_api(token=token)
220
+ items = [
221
+ {
222
+ "id": bucket.id,
223
+ "private": bucket.private,
224
+ "size": format_size(bucket.size, human_readable) if human_readable else bucket.size,
225
+ "total_files": bucket.total_files,
226
+ "created_at": bucket.created_at,
227
+ }
228
+ for bucket in api.list_buckets(namespace=namespace, search=search)
229
+ ]
230
+ out.table(items, alignments={"size": "right"})
231
+
232
+
233
+ def _list_files(
234
+ argument: str,
235
+ human_readable: bool,
236
+ as_tree: bool,
237
+ recursive: bool,
238
+ token: str | None,
239
+ ) -> None:
240
+ """List files in a bucket."""
241
+ if as_tree and out.mode == OutputFormat.json:
242
+ raise click.BadParameter("Cannot use --tree with --format json.")
243
+
244
+ api = get_hf_api(token=token)
245
+ parsed = _parse_bucket_uri(argument)
246
+ items = list(
247
+ api.list_bucket_tree(
248
+ parsed.id,
249
+ prefix=parsed.path_in_repo or None,
250
+ recursive=recursive,
251
+ )
252
+ )
253
+
254
+ print_file_listing(items, human_readable=human_readable, as_tree=as_tree, recursive=recursive)
255
+
256
+
257
+ @buckets_cli.command(
258
+ name="info",
259
+ examples=[
260
+ "hf buckets info user/my-bucket",
261
+ "hf buckets info hf://buckets/user/my-bucket",
262
+ ],
263
+ )
264
+ def info(
265
+ bucket_id: Annotated[
266
+ str,
267
+ Argument(
268
+ help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
269
+ ),
270
+ ],
271
+ token: TokenOpt = None,
272
+ ) -> None:
273
+ """Get info about a bucket."""
274
+ api = get_hf_api(token=token)
275
+ parsed = _parse_bucket_uri(bucket_id)
276
+ bucket = api.bucket_info(parsed.id)
277
+ out.dict(bucket, id_key="id")
278
+
279
+
280
+ @buckets_cli.command(
281
+ name="delete",
282
+ examples=[
283
+ "hf buckets delete user/my-bucket",
284
+ "hf buckets delete hf://buckets/user/my-bucket",
285
+ "hf buckets delete user/my-bucket --yes",
286
+ "hf buckets delete user/my-bucket --missing-ok",
287
+ ],
288
+ )
289
+ def delete(
290
+ bucket_id: Annotated[
291
+ str,
292
+ Argument(
293
+ help="Bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
294
+ ),
295
+ ],
296
+ yes: Annotated[
297
+ bool,
298
+ Option(
299
+ "--yes",
300
+ "-y",
301
+ help="Skip confirmation prompt.",
302
+ ),
303
+ ] = False,
304
+ missing_ok: Annotated[
305
+ bool,
306
+ Option(
307
+ "--missing-ok",
308
+ help="Do not raise an error if the bucket does not exist.",
309
+ ),
310
+ ] = False,
311
+ token: TokenOpt = None,
312
+ ) -> None:
313
+ """Delete a bucket.
314
+
315
+ This deletes the entire bucket and all its contents. Use `hf buckets rm` to remove individual files.
316
+ """
317
+ if bucket_id.startswith(BUCKET_PREFIX):
318
+ parsed = _parse_bucket_uri(bucket_id)
319
+ if parsed.path_in_repo:
320
+ raise click.BadParameter(
321
+ f"Cannot specify a prefix for bucket deletion: {bucket_id}."
322
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
323
+ )
324
+ bucket_id = parsed.id
325
+ elif "/" not in bucket_id:
326
+ raise click.BadParameter(
327
+ f"Invalid bucket ID: {bucket_id}."
328
+ f" Must be in format namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
329
+ )
330
+
331
+ out.confirm(f"Are you sure you want to delete bucket '{bucket_id}'?", yes=yes)
332
+
333
+ api = get_hf_api(token=token)
334
+ api.delete_bucket(bucket_id, missing_ok=missing_ok)
335
+ out.result("Bucket deleted", bucket_id=bucket_id)
336
+
337
+
338
+ @buckets_cli.command(
339
+ name="remove | rm",
340
+ examples=[
341
+ "hf buckets remove user/my-bucket/file.txt",
342
+ "hf buckets rm hf://buckets/user/my-bucket/file.txt",
343
+ "hf buckets rm user/my-bucket/logs/ --recursive",
344
+ 'hf buckets rm user/my-bucket --recursive --include "*.tmp"',
345
+ "hf buckets rm user/my-bucket/data/ --recursive --dry-run",
346
+ ],
347
+ )
348
+ def remove(
349
+ argument: Annotated[
350
+ str,
351
+ Argument(
352
+ help=(
353
+ "Bucket path: namespace/bucket_name/path or hf://buckets/namespace/bucket_name/path."
354
+ " With --recursive, namespace/bucket_name is also accepted to target all files."
355
+ ),
356
+ ),
357
+ ],
358
+ recursive: Annotated[
359
+ bool,
360
+ Option(
361
+ "--recursive",
362
+ "-R",
363
+ help="Remove files recursively under the given prefix.",
364
+ ),
365
+ ] = False,
366
+ yes: Annotated[
367
+ bool,
368
+ Option(
369
+ "--yes",
370
+ "-y",
371
+ help="Skip confirmation prompt.",
372
+ ),
373
+ ] = False,
374
+ dry_run: Annotated[
375
+ bool,
376
+ Option(
377
+ "--dry-run",
378
+ help="Preview what would be deleted without actually deleting.",
379
+ ),
380
+ ] = False,
381
+ include: Annotated[
382
+ list[str] | None,
383
+ Option(
384
+ help="Include only files matching pattern (can specify multiple). Requires --recursive.",
385
+ ),
386
+ ] = None,
387
+ exclude: Annotated[
388
+ list[str] | None,
389
+ Option(
390
+ help="Exclude files matching pattern (can specify multiple). Requires --recursive.",
391
+ ),
392
+ ] = None,
393
+ token: TokenOpt = None,
394
+ ) -> None:
395
+ """Remove files from a bucket.
396
+
397
+ To delete an entire bucket, use `hf buckets delete` instead.
398
+ """
399
+ parsed = _parse_bucket_uri(argument)
400
+ bucket_id = parsed.id
401
+ prefix = parsed.path_in_repo
402
+
403
+ if prefix == "" and not recursive:
404
+ raise click.BadParameter(
405
+ f"No file path specified. To remove files, provide a path"
406
+ f" (e.g. '{bucket_id}/FILE') or use --recursive to remove all files."
407
+ f" To delete the entire bucket, use `hf buckets delete {bucket_id}`."
408
+ )
409
+
410
+ if (include or exclude) and not recursive:
411
+ raise click.BadParameter("--include and --exclude require --recursive.")
412
+
413
+ api = get_hf_api(token=token)
414
+
415
+ if recursive:
416
+ status = out.status("Listing files from remote")
417
+
418
+ all_files: list[BucketFile] = []
419
+ for item in api.list_bucket_tree(
420
+ bucket_id,
421
+ prefix=prefix or None,
422
+ recursive=True,
423
+ ):
424
+ if isinstance(item, BucketFile):
425
+ all_files.append(item)
426
+ status.update(f"Listing files from remote ({len(all_files)} files)")
427
+ status.done(f"Listing files from remote ({len(all_files)} files)")
428
+
429
+ if include or exclude:
430
+ matcher = FilterMatcher(include_patterns=include, exclude_patterns=exclude)
431
+ matched_files = [f for f in all_files if matcher.matches(f.path)]
432
+ else:
433
+ matched_files = all_files
434
+
435
+ file_paths = [f.path for f in matched_files]
436
+ total_size = sum(f.size for f in matched_files)
437
+ size_str = format_size(total_size, human_readable=True)
438
+
439
+ if not file_paths:
440
+ out.text("No files to remove.")
441
+ return
442
+
443
+ count_label = f"{len(file_paths)} file(s) totaling {size_str}"
444
+
445
+ if not yes and not dry_run:
446
+ out.text("\n".join(f" {path}" for path in file_paths))
447
+ out.confirm(f"Remove {count_label} from '{bucket_id}'?", yes=False)
448
+
449
+ if dry_run:
450
+ out.text("\n".join(f"delete: {BUCKET_PREFIX}{bucket_id}/{path}" for path in file_paths))
451
+ out.text(f"(dry run) {count_label} would be removed.")
452
+ return
453
+
454
+ api.batch_bucket_files(bucket_id, delete=file_paths)
455
+ out.result(
456
+ f"Removed {count_label} from '{bucket_id}'",
457
+ bucket_id=bucket_id,
458
+ files_deleted=len(file_paths),
459
+ size=size_str,
460
+ )
461
+
462
+ else:
463
+ file_path = prefix
464
+ if not file_path:
465
+ raise click.BadParameter("File path cannot be empty.")
466
+
467
+ if dry_run:
468
+ out.text(f"delete: {BUCKET_PREFIX}{bucket_id}/{file_path}")
469
+ out.text("(dry run) 1 file would be removed.")
470
+ return
471
+
472
+ out.confirm(f"Remove '{file_path}' from '{bucket_id}'?", yes=yes)
473
+
474
+ api.batch_bucket_files(bucket_id, delete=[file_path])
475
+ out.result("File removed", path=file_path, bucket_id=bucket_id)
476
+
477
+
478
+ @buckets_cli.command(
479
+ name="move",
480
+ examples=[
481
+ "hf buckets move user/old-bucket user/new-bucket",
482
+ "hf buckets move user/my-bucket my-org/my-bucket",
483
+ "hf buckets move hf://buckets/user/old-bucket hf://buckets/user/new-bucket",
484
+ ],
485
+ )
486
+ def move(
487
+ from_id: Annotated[
488
+ str,
489
+ Argument(
490
+ help="Source bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
491
+ ),
492
+ ],
493
+ to_id: Annotated[
494
+ str,
495
+ Argument(
496
+ help="Destination bucket ID: namespace/bucket_name or hf://buckets/namespace/bucket_name",
497
+ ),
498
+ ],
499
+ token: TokenOpt = None,
500
+ ) -> None:
501
+ """Move (rename) a bucket to a new name or namespace."""
502
+ # Parse from_id
503
+ parsed_from = _parse_bucket_uri(from_id)
504
+ if parsed_from.path_in_repo:
505
+ raise click.BadParameter(
506
+ f"Cannot specify a prefix for bucket move: {from_id}."
507
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
508
+ )
509
+
510
+ # Parse to_id
511
+ parsed_to = _parse_bucket_uri(to_id)
512
+ if parsed_to.path_in_repo:
513
+ raise click.BadParameter(
514
+ f"Cannot specify a prefix for bucket move: {to_id}."
515
+ f" Use namespace/bucket_name or {BUCKET_PREFIX}namespace/bucket_name."
516
+ )
517
+
518
+ api = get_hf_api(token=token)
519
+ api.move_bucket(from_id=parsed_from.id, to_id=parsed_to.id)
520
+ out.result("Bucket moved", from_id=parsed_from.id, to_id=parsed_to.id)
521
+
522
+
523
+ # =============================================================================
524
+ # Sync command
525
+ # =============================================================================
526
+
527
+
528
+ @buckets_cli.command(
529
+ name="sync",
530
+ examples=[
531
+ "hf buckets sync ./data hf://buckets/user/my-bucket",
532
+ "hf buckets sync hf://buckets/user/my-bucket ./data",
533
+ "hf buckets sync ./data hf://buckets/user/my-bucket --delete",
534
+ 'hf buckets sync hf://buckets/user/my-bucket ./data --include "*.safetensors" --exclude "*.tmp"',
535
+ "hf buckets sync ./data hf://buckets/user/my-bucket --plan sync-plan.jsonl",
536
+ "hf buckets sync --apply sync-plan.jsonl",
537
+ "hf buckets sync ./data hf://buckets/user/my-bucket --dry-run",
538
+ "hf buckets sync ./data hf://buckets/user/my-bucket --dry-run | jq .",
539
+ ],
540
+ )
541
+ def sync(
542
+ source: Annotated[
543
+ str | None,
544
+ Argument(
545
+ help="Source path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
546
+ ),
547
+ ] = None,
548
+ dest: Annotated[
549
+ str | None,
550
+ Argument(
551
+ help="Destination path: local directory or hf://buckets/namespace/bucket_name(/prefix)",
552
+ ),
553
+ ] = None,
554
+ delete: Annotated[
555
+ bool,
556
+ Option(
557
+ help="Delete destination files not present in source.",
558
+ ),
559
+ ] = False,
560
+ ignore_times: Annotated[
561
+ bool,
562
+ Option(
563
+ "--ignore-times",
564
+ help="Skip files only based on size, ignoring modification times.",
565
+ ),
566
+ ] = False,
567
+ ignore_sizes: Annotated[
568
+ bool,
569
+ Option(
570
+ "--ignore-sizes",
571
+ help="Skip files only based on modification times, ignoring sizes.",
572
+ ),
573
+ ] = False,
574
+ plan: Annotated[
575
+ str | None,
576
+ Option(
577
+ help="Save sync plan to JSONL file for review instead of executing.",
578
+ ),
579
+ ] = None,
580
+ apply: Annotated[
581
+ str | None,
582
+ Option(
583
+ help="Apply a previously saved plan file.",
584
+ ),
585
+ ] = None,
586
+ dry_run: Annotated[
587
+ bool,
588
+ Option(
589
+ "--dry-run",
590
+ help="Print sync plan to stdout as JSONL without executing.",
591
+ ),
592
+ ] = False,
593
+ include: Annotated[
594
+ list[str] | None,
595
+ Option(
596
+ help="Include files matching pattern (can specify multiple).",
597
+ ),
598
+ ] = None,
599
+ exclude: Annotated[
600
+ list[str] | None,
601
+ Option(
602
+ help="Exclude files matching pattern (can specify multiple).",
603
+ ),
604
+ ] = None,
605
+ filter_from: Annotated[
606
+ str | None,
607
+ Option(
608
+ help="Read include/exclude patterns from file.",
609
+ ),
610
+ ] = None,
611
+ existing: Annotated[
612
+ bool,
613
+ Option(
614
+ "--existing",
615
+ help="Skip creating new files on receiver (only update existing files).",
616
+ ),
617
+ ] = False,
618
+ ignore_existing: Annotated[
619
+ bool,
620
+ Option(
621
+ "--ignore-existing",
622
+ help="Skip updating files that exist on receiver (only create new files).",
623
+ ),
624
+ ] = False,
625
+ verbose: Annotated[
626
+ bool,
627
+ Option(
628
+ "--verbose",
629
+ "-v",
630
+ help="Show detailed logging with reasoning.",
631
+ ),
632
+ ] = False,
633
+ token: TokenOpt = None,
634
+ ) -> None:
635
+ """Sync files between local directory and a bucket."""
636
+ api = get_hf_api(token=token)
637
+ api.sync_bucket(
638
+ source=source,
639
+ dest=dest,
640
+ delete=delete,
641
+ ignore_times=ignore_times,
642
+ ignore_sizes=ignore_sizes,
643
+ existing=existing,
644
+ ignore_existing=ignore_existing,
645
+ include=include,
646
+ exclude=exclude,
647
+ filter_from=filter_from,
648
+ plan=plan,
649
+ apply=apply,
650
+ dry_run=dry_run,
651
+ verbose=verbose,
652
+ quiet=out.is_quiet(),
653
+ )
654
+ if plan and not out.is_quiet():
655
+ out.hint(f"Run `hf buckets sync --apply {plan}` to execute this plan.")
656
+
657
+
658
+ # =============================================================================
659
+ # Cp command
660
+ # =============================================================================
661
+
662
+
663
+ # `hf buckets cp` is an alias for the top-level `hf cp` command (see `cli/_cp.py`).
664
+ buckets_cli.command(
665
+ name="cp",
666
+ examples=[
667
+ # Download (repo or bucket -> local / stdout)
668
+ "hf buckets cp hf://buckets/username/my-bucket/config.json config.json",
669
+ "hf buckets cp hf://buckets/username/my-bucket/data.csv data/",
670
+ "hf buckets cp hf://buckets/username/my-bucket/config.json -",
671
+ # Upload (local / stdin -> bucket)
672
+ "hf buckets cp model.safetensors hf://buckets/username/my-bucket/model.safetensors",
673
+ "hf buckets cp config.json hf://buckets/username/my-bucket/logs/",
674
+ "hf buckets cp - hf://buckets/username/my-bucket/config.json",
675
+ # Remote to remote (repo or bucket -> bucket)
676
+ "hf buckets cp hf://buckets/username/my-bucket/data.csv hf://buckets/username/dest-bucket/",
677
+ "hf buckets cp hf://buckets/username/source-bucket/logs/ hf://buckets/username/dest-bucket/logs/",
678
+ ],
679
+ )(make_cp("buckets"))
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/cache.py ADDED
@@ -0,0 +1,800 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 click
25
+
26
+ from huggingface_hub.errors import CLIError
27
+
28
+ from ..utils import (
29
+ ANSI,
30
+ CachedRepoInfo,
31
+ CachedRevisionInfo,
32
+ CacheNotFound,
33
+ HFCacheInfo,
34
+ _format_size,
35
+ parse_hf_uri,
36
+ scan_cache_dir,
37
+ )
38
+ from ..utils._parsing import parse_duration, parse_size
39
+ from ._cli_utils import RepoIdArg, RepoTypeOpt, RevisionOpt, TokenOpt, get_hf_api, typer_factory
40
+ from ._framework import Argument, Option
41
+ from ._output import out
42
+
43
+
44
+ cache_cli = typer_factory(help="Manage local cache directory.")
45
+
46
+
47
+ #### Cache helper utilities
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class _DeletionResolution:
52
+ revisions: frozenset[str]
53
+ selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]]
54
+ missing: tuple[str, ...]
55
+
56
+
57
+ _FILTER_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)\s*(?P<op>==|!=|>=|<=|>|<|=)\s*(?P<value>.+)$")
58
+ _ALLOWED_OPERATORS = {"=", "!=", ">", "<", ">=", "<="}
59
+ _FILTER_KEYS = {"accessed", "modified", "refs", "size", "type"}
60
+ _SORT_KEYS = {"accessed", "modified", "name", "size"}
61
+ _SORT_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)(?::(?P<order>asc|desc))?$")
62
+ _SORT_DEFAULT_ORDER = {
63
+ # Default ordering: accessed/modified/size are descending (newest/biggest first), name is ascending
64
+ "accessed": "desc",
65
+ "modified": "desc",
66
+ "size": "desc",
67
+ "name": "asc",
68
+ }
69
+
70
+
71
+ # Dynamically generate SortOptions enum from _SORT_KEYS
72
+ _sort_options_dict = {}
73
+ for key in sorted(_SORT_KEYS):
74
+ _sort_options_dict[key] = key
75
+ _sort_options_dict[f"{key}_asc"] = f"{key}:asc"
76
+ _sort_options_dict[f"{key}_desc"] = f"{key}:desc"
77
+
78
+ SortOptions = Enum("SortOptions", _sort_options_dict, type=str, module=__name__) # type: ignore
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class CacheDeletionCounts:
83
+ """Simple counters summarizing cache deletions for CLI messaging."""
84
+
85
+ repo_count: int
86
+ partial_revision_count: int
87
+ total_revision_count: int
88
+
89
+
90
+ CacheEntry = tuple[CachedRepoInfo, CachedRevisionInfo | None]
91
+ RepoRefsMap = dict[CachedRepoInfo, frozenset[str]]
92
+
93
+
94
+ def summarize_deletions(
95
+ selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]],
96
+ ) -> CacheDeletionCounts:
97
+ """Summarize deletions across repositories."""
98
+ repo_count = 0
99
+ total_revisions = 0
100
+ revisions_in_full_repos = 0
101
+
102
+ for repo, revisions in selected_by_repo.items():
103
+ total_revisions += len(revisions)
104
+ if len(revisions) == len(repo.revisions):
105
+ repo_count += 1
106
+ revisions_in_full_repos += len(revisions)
107
+
108
+ partial_revision_count = total_revisions - revisions_in_full_repos
109
+ return CacheDeletionCounts(repo_count, partial_revision_count, total_revisions)
110
+
111
+
112
+ def _prune_summary(revision_count: int, incomplete_count: int) -> str:
113
+ """Build the human-readable summary of what `hf cache prune` is about to delete."""
114
+ parts: list[str] = []
115
+ if revision_count:
116
+ parts.append(f"{revision_count} unreferenced revision(s)")
117
+ if incomplete_count:
118
+ parts.append(f"{incomplete_count} incomplete download(s)")
119
+ return " and ".join(parts)
120
+
121
+
122
+ def print_cache_selected_revisions(selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]]) -> None:
123
+ """Pretty-print selected cache revisions during confirmation prompts."""
124
+ for repo in sorted(selected_by_repo.keys(), key=lambda repo: (repo.repo_type, repo.repo_id.lower())):
125
+ repo_key = f"{repo.repo_type}/{repo.repo_id}"
126
+ revisions = sorted(selected_by_repo[repo], key=lambda rev: rev.commit_hash)
127
+ if len(revisions) == len(repo.revisions):
128
+ out.text(f" - {repo_key} (entire repo)")
129
+ continue
130
+
131
+ out.text(f" - {repo_key}:")
132
+ for revision in revisions:
133
+ refs = " ".join(sorted(revision.refs)) or "(detached)"
134
+ out.text(f" {revision.commit_hash} [{refs}] {revision.size_on_disk_str}")
135
+
136
+
137
+ def build_cache_index(
138
+ hf_cache_info: HFCacheInfo,
139
+ ) -> tuple[
140
+ dict[str, CachedRepoInfo],
141
+ dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]],
142
+ ]:
143
+ """Create lookup tables so CLI commands can resolve repo ids and revisions quickly."""
144
+ repo_lookup: dict[str, CachedRepoInfo] = {}
145
+ revision_lookup: dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]] = {}
146
+ for repo in hf_cache_info.repos:
147
+ repo_key = repo.cache_id.lower()
148
+ repo_lookup[repo_key] = repo
149
+ for revision in repo.revisions:
150
+ revision_lookup[revision.commit_hash.lower()] = (repo, revision)
151
+ return repo_lookup, revision_lookup
152
+
153
+
154
+ def _repo_cache_id_from_target(target: str) -> str:
155
+ """Return the cache id matching a repo target passed to `hf cache rm`."""
156
+ if not target.startswith("hf://"):
157
+ return target
158
+
159
+ uri = parse_hf_uri(target)
160
+ if not uri.is_repo:
161
+ raise CLIError("Only repository hf:// URIs are supported by `hf cache rm`.")
162
+ if uri.revision is not None or uri.path_in_repo:
163
+ raise CLIError("Only repo-level hf:// URIs are supported by `hf cache rm` for now.")
164
+ return f"{uri.type}/{uri.id}"
165
+
166
+
167
+ def collect_cache_entries(
168
+ hf_cache_info: HFCacheInfo, *, include_revisions: bool
169
+ ) -> tuple[list[CacheEntry], RepoRefsMap]:
170
+ """Flatten cache metadata into rows consumed by `hf cache ls`."""
171
+ entries: list[CacheEntry] = []
172
+ repo_refs_map: RepoRefsMap = {}
173
+ sorted_repos = sorted(hf_cache_info.repos, key=lambda repo: (repo.repo_type, repo.repo_id.lower()))
174
+ for repo in sorted_repos:
175
+ repo_refs_map[repo] = frozenset({ref for revision in repo.revisions for ref in revision.refs})
176
+ if include_revisions:
177
+ for revision in sorted(repo.revisions, key=lambda rev: rev.commit_hash):
178
+ entries.append((repo, revision))
179
+ else:
180
+ entries.append((repo, None))
181
+ if include_revisions:
182
+ entries.sort(
183
+ key=lambda entry: (
184
+ entry[0].cache_id,
185
+ entry[1].commit_hash if entry[1] is not None else "",
186
+ )
187
+ )
188
+ else:
189
+ entries.sort(key=lambda entry: entry[0].cache_id)
190
+ return entries, repo_refs_map
191
+
192
+
193
+ def compile_cache_filter(
194
+ expr: str, repo_refs_map: RepoRefsMap
195
+ ) -> Callable[[CachedRepoInfo, CachedRevisionInfo | None, float], bool]:
196
+ """Convert a `hf cache ls` filter expression into the yes/no test we apply to each cache entry before displaying it."""
197
+ match = _FILTER_PATTERN.match(expr.strip())
198
+ if not match:
199
+ raise ValueError(f"Invalid filter expression: '{expr}'.")
200
+
201
+ key = match.group("key").lower()
202
+ op = match.group("op")
203
+ value_raw = match.group("value").strip()
204
+
205
+ if op not in _ALLOWED_OPERATORS:
206
+ raise ValueError(f"Unsupported operator '{op}' in filter '{expr}'. Must be one of {list(_ALLOWED_OPERATORS)}.")
207
+
208
+ if key not in _FILTER_KEYS:
209
+ raise ValueError(f"Unsupported filter key '{key}' in '{expr}'. Must be one of {list(_FILTER_KEYS)}.")
210
+ # at this point we know that key is in `_FILTER_KEYS`
211
+ if key == "size":
212
+ size_threshold = parse_size(value_raw)
213
+ return lambda repo, revision, _: _compare_numeric(
214
+ revision.size_on_disk if revision is not None else repo.size_on_disk,
215
+ op,
216
+ size_threshold,
217
+ )
218
+
219
+ if key in {"modified", "accessed"}:
220
+ seconds = parse_duration(value_raw.strip())
221
+
222
+ def _time_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, now: float) -> bool:
223
+ timestamp = (
224
+ repo.last_accessed
225
+ if key == "accessed"
226
+ else revision.last_modified
227
+ if revision is not None
228
+ else repo.last_modified
229
+ )
230
+ if timestamp is None:
231
+ return False
232
+ return _compare_numeric(now - timestamp, op, seconds)
233
+
234
+ return _time_filter
235
+
236
+ if key == "type":
237
+ expected = value_raw.lower()
238
+
239
+ if op != "=":
240
+ raise ValueError(f"Only '=' is supported for 'type' filters. Got '{op}'.")
241
+
242
+ def _type_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
243
+ return repo.repo_type.lower() == expected
244
+
245
+ return _type_filter
246
+
247
+ else: # key == "refs"
248
+ if op != "=":
249
+ raise ValueError(f"Only '=' is supported for 'refs' filters. Got {op}.")
250
+
251
+ def _refs_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
252
+ refs = revision.refs if revision is not None else repo_refs_map.get(repo, frozenset())
253
+ return value_raw.lower() in [ref.lower() for ref in refs]
254
+
255
+ return _refs_filter
256
+
257
+
258
+ def _compare_numeric(left: float | None, op: str, right: float) -> bool:
259
+ """Evaluate numeric comparisons for filters."""
260
+ if left is None:
261
+ return False
262
+
263
+ comparisons = {
264
+ "=": left == right,
265
+ "!=": left != right,
266
+ ">": left > right,
267
+ "<": left < right,
268
+ ">=": left >= right,
269
+ "<=": left <= right,
270
+ }
271
+
272
+ if op not in comparisons:
273
+ raise ValueError(f"Unsupported numeric comparison operator: {op}")
274
+
275
+ return comparisons[op]
276
+
277
+
278
+ def compile_cache_sort(sort_expr: str) -> tuple[Callable[[CacheEntry], tuple[Any, ...]], bool]:
279
+ """Convert a `hf cache ls` sort expression into a key function for sorting entries.
280
+
281
+ Returns:
282
+ A tuple of (key_function, reverse_flag) where reverse_flag indicates whether
283
+ to sort in descending order (True) or ascending order (False).
284
+ """
285
+ match = _SORT_PATTERN.match(sort_expr.strip().lower())
286
+ if not match:
287
+ raise ValueError(f"Invalid sort expression: '{sort_expr}'. Expected format: 'key' or 'key:asc' or 'key:desc'.")
288
+
289
+ key = match.group("key").lower()
290
+ explicit_order = match.group("order")
291
+
292
+ if key not in _SORT_KEYS:
293
+ raise ValueError(f"Unsupported sort key '{key}' in '{sort_expr}'. Must be one of {list(_SORT_KEYS)}.")
294
+
295
+ # Use explicit order if provided, otherwise use default for the key
296
+ order = explicit_order if explicit_order else _SORT_DEFAULT_ORDER[key]
297
+ reverse = order == "desc"
298
+
299
+ def _sort_key(entry: CacheEntry) -> tuple[Any, ...]:
300
+ repo, revision = entry
301
+
302
+ if key == "name":
303
+ # Sort by cache_id (repo type/id)
304
+ value: Any = repo.cache_id.lower()
305
+ return (value,)
306
+
307
+ if key == "size":
308
+ # Use revision size if available, otherwise repo size
309
+ value = revision.size_on_disk if revision is not None else repo.size_on_disk
310
+ return (value,)
311
+
312
+ if key == "accessed":
313
+ # For revisions, accessed is not available per-revision, use repo's last_accessed
314
+ # For repos, use repo's last_accessed
315
+ value = repo.last_accessed if repo.last_accessed is not None else 0.0
316
+ return (value,)
317
+
318
+ if key == "modified":
319
+ # Use revision's last_modified if available, otherwise repo's last_modified
320
+ if revision is not None:
321
+ value = revision.last_modified if revision.last_modified is not None else 0.0
322
+ else:
323
+ value = repo.last_modified if repo.last_modified is not None else 0.0
324
+ return (value,)
325
+
326
+ # Should never reach here due to validation above
327
+ raise ValueError(f"Unsupported sort key: {key}")
328
+
329
+ return _sort_key, reverse
330
+
331
+
332
+ def _resolve_deletion_targets(hf_cache_info: HFCacheInfo, targets: list[str]) -> _DeletionResolution:
333
+ """Resolve the deletion targets into a deletion resolution."""
334
+ repo_lookup, revision_lookup = build_cache_index(hf_cache_info)
335
+
336
+ selected: dict[CachedRepoInfo, set[CachedRevisionInfo]] = defaultdict(set)
337
+ revisions: set[str] = set()
338
+ missing: list[str] = []
339
+
340
+ for raw_target in targets:
341
+ target = raw_target.strip()
342
+ if not target:
343
+ continue
344
+ lowered = target.lower()
345
+
346
+ if re.fullmatch(r"[0-9a-fA-F]{40}", lowered):
347
+ match = revision_lookup.get(lowered)
348
+ if match is None:
349
+ missing.append(raw_target)
350
+ continue
351
+ repo, revision = match
352
+ selected[repo].add(revision)
353
+ revisions.add(revision.commit_hash)
354
+ continue
355
+
356
+ matched_repo = repo_lookup.get(_repo_cache_id_from_target(target).lower())
357
+ if matched_repo is None:
358
+ missing.append(raw_target)
359
+ continue
360
+
361
+ for revision in matched_repo.revisions:
362
+ selected[matched_repo].add(revision)
363
+ revisions.add(revision.commit_hash)
364
+
365
+ frozen_selected = {repo: frozenset(revs) for repo, revs in selected.items()}
366
+ return _DeletionResolution(
367
+ revisions=frozenset(revisions),
368
+ selected=frozen_selected,
369
+ missing=tuple(missing),
370
+ )
371
+
372
+
373
+ #### Cache CLI commands
374
+
375
+
376
+ @cache_cli.command(
377
+ "list | ls",
378
+ examples=[
379
+ "hf cache ls",
380
+ "hf cache ls --revisions",
381
+ 'hf cache ls --filter "size>1GB" --limit 20',
382
+ "hf cache ls --format json",
383
+ ],
384
+ )
385
+ def ls(
386
+ cache_dir: Annotated[
387
+ str | None,
388
+ Option(
389
+ help="Cache directory to scan (defaults to Hugging Face cache).",
390
+ ),
391
+ ] = None,
392
+ revisions: Annotated[
393
+ bool,
394
+ Option(
395
+ help="Include revisions in the output instead of aggregated repositories.",
396
+ ),
397
+ ] = False,
398
+ filter: Annotated[
399
+ list[str] | None,
400
+ Option(
401
+ "-f",
402
+ "--filter",
403
+ help="Filter entries (e.g. 'size>1GB', 'type=model', 'accessed>7d'). Can be used multiple times.",
404
+ ),
405
+ ] = None,
406
+ sort: Annotated[
407
+ SortOptions | None,
408
+ Option(
409
+ help="Sort entries by key. Supported keys: 'accessed', 'modified', 'name', 'size'. "
410
+ "Append ':asc' or ':desc' to explicitly set the order (e.g., 'modified:asc'). "
411
+ "Defaults: 'accessed', 'modified', 'size' default to 'desc' (newest/biggest first); "
412
+ "'name' defaults to 'asc' (alphabetical).",
413
+ ),
414
+ ] = None,
415
+ limit: Annotated[
416
+ int | None,
417
+ Option(
418
+ help="Limit the number of results returned. Returns only the top N entries after sorting.",
419
+ ),
420
+ ] = None,
421
+ ) -> None:
422
+ """List cached repositories or revisions."""
423
+ try:
424
+ hf_cache_info = scan_cache_dir(cache_dir)
425
+ except CacheNotFound as exc:
426
+ raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
427
+
428
+ filters = filter or []
429
+
430
+ entries, repo_refs_map = collect_cache_entries(hf_cache_info, include_revisions=revisions)
431
+ try:
432
+ filter_fns = [compile_cache_filter(expr, repo_refs_map) for expr in filters]
433
+ except ValueError as exc:
434
+ raise click.BadParameter(str(exc)) from exc
435
+
436
+ now = time.time()
437
+ for fn in filter_fns:
438
+ entries = [entry for entry in entries if fn(entry[0], entry[1], now)]
439
+
440
+ # Apply sorting if requested
441
+ if sort:
442
+ try:
443
+ sort_key_fn, reverse = compile_cache_sort(sort.value)
444
+ entries.sort(key=sort_key_fn, reverse=reverse)
445
+ except ValueError as exc:
446
+ raise click.BadParameter(str(exc)) from exc
447
+
448
+ # Apply limit if requested
449
+ if limit is not None:
450
+ if limit < 0:
451
+ raise click.BadParameter(f"Limit must be a positive integer, got {limit}.")
452
+ entries = entries[:limit]
453
+
454
+ if revisions:
455
+ items = [
456
+ {
457
+ "id": repo.cache_id,
458
+ "repo_id": repo.repo_id,
459
+ "repo_type": repo.repo_type,
460
+ "revision": revision.commit_hash,
461
+ "snapshot_path": str(revision.snapshot_path),
462
+ "size": revision.size_on_disk_str,
463
+ "last_modified": revision.last_modified_str,
464
+ "refs": sorted(revision.refs),
465
+ }
466
+ for repo, revision in entries
467
+ if revision is not None
468
+ ]
469
+ out.table(
470
+ items,
471
+ headers=["id", "revision", "size", "last_modified", "refs"],
472
+ id_key="revision",
473
+ alignments={"size": "right"},
474
+ )
475
+ else:
476
+ items = [
477
+ {
478
+ "id": repo.cache_id,
479
+ "repo_id": repo.repo_id,
480
+ "repo_type": repo.repo_type,
481
+ "size": repo.size_on_disk_str,
482
+ "last_accessed": repo.last_accessed_str or "",
483
+ "last_modified": repo.last_modified_str,
484
+ "refs": sorted(repo_refs_map.get(repo, frozenset())),
485
+ }
486
+ for repo, _ in entries
487
+ ]
488
+ out.table(
489
+ items,
490
+ headers=["id", "size", "last_accessed", "last_modified", "refs"],
491
+ id_key="id",
492
+ alignments={"size": "right"},
493
+ )
494
+
495
+ if entries:
496
+ unique_repos = {repo for repo, _ in entries}
497
+ repo_count = len(unique_repos)
498
+ if revisions:
499
+ revision_count = sum(1 for _, rev in entries if rev is not None)
500
+ total_size = sum(rev.size_on_disk for _, rev in entries if rev is not None)
501
+ else:
502
+ revision_count = sum(len(repo.revisions) for repo in unique_repos)
503
+ total_size = sum(repo.size_on_disk for repo in unique_repos)
504
+ out.text(
505
+ ANSI.bold(
506
+ f"\nFound {repo_count} repo(s) for a total of {revision_count} revision(s)"
507
+ f" and {_format_size(total_size)} on disk."
508
+ )
509
+ )
510
+
511
+ incomplete_files = hf_cache_info.incomplete_files
512
+ if incomplete_files:
513
+ out.hint(
514
+ f"Found {len(incomplete_files)} incomplete download(s) totalling "
515
+ f"{_format_size(hf_cache_info.incomplete_size_on_disk)}. "
516
+ "Remove them with 'hf cache prune'."
517
+ )
518
+
519
+
520
+ @cache_cli.command(
521
+ examples=[
522
+ "hf cache rm model/gpt2",
523
+ "hf cache rm hf://models/openai-community/gpt2",
524
+ "hf cache rm <revision_hash>",
525
+ "hf cache rm model/gpt2 --dry-run",
526
+ "hf cache rm model/gpt2 --yes",
527
+ ],
528
+ )
529
+ def rm(
530
+ targets: Annotated[
531
+ list[str],
532
+ Argument(
533
+ help="One or more repo IDs (e.g. model/bert-base-uncased), repo-level hf:// URIs, or revision hashes to delete.",
534
+ ),
535
+ ],
536
+ cache_dir: Annotated[
537
+ str | None,
538
+ Option(
539
+ help="Cache directory to scan (defaults to Hugging Face cache).",
540
+ ),
541
+ ] = None,
542
+ yes: Annotated[
543
+ bool,
544
+ Option(
545
+ "-y",
546
+ "--yes",
547
+ help="Skip confirmation prompt.",
548
+ ),
549
+ ] = False,
550
+ dry_run: Annotated[
551
+ bool,
552
+ Option(
553
+ help="Preview deletions without removing anything.",
554
+ ),
555
+ ] = False,
556
+ ) -> None:
557
+ """Remove cached repositories or revisions."""
558
+ try:
559
+ hf_cache_info = scan_cache_dir(cache_dir)
560
+ except CacheNotFound as exc:
561
+ raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
562
+
563
+ resolution = _resolve_deletion_targets(hf_cache_info, targets)
564
+
565
+ if resolution.missing:
566
+ details = "\n".join(f" - {entry}" for entry in resolution.missing)
567
+ out.warning(f"Could not find in cache:\n{details}")
568
+
569
+ if len(resolution.revisions) == 0:
570
+ out.text("Nothing to delete.")
571
+ raise click.exceptions.Exit(code=0)
572
+
573
+ strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions))
574
+ counts = summarize_deletions(resolution.selected)
575
+
576
+ summary_parts: list[str] = []
577
+ if counts.repo_count:
578
+ summary_parts.append(f"{counts.repo_count} repo(s)")
579
+ if counts.partial_revision_count:
580
+ summary_parts.append(f"{counts.partial_revision_count} revision(s)")
581
+ if not summary_parts:
582
+ summary_parts.append(f"{counts.total_revision_count} revision(s)")
583
+
584
+ summary_text = " and ".join(summary_parts)
585
+ out.text(f"About to delete {summary_text} totalling {strategy.expected_freed_size_str}.")
586
+ print_cache_selected_revisions(resolution.selected)
587
+
588
+ if dry_run:
589
+ out.result(
590
+ "Dry run: no files were deleted.",
591
+ dry_run=True,
592
+ repos=counts.repo_count,
593
+ revisions=counts.total_revision_count,
594
+ size=strategy.expected_freed_size_str,
595
+ )
596
+ return
597
+
598
+ out.confirm("Proceed with deletion?", yes=yes)
599
+
600
+ strategy.execute()
601
+ counts = summarize_deletions(resolution.selected)
602
+ out.result(
603
+ f"Deleted {counts.repo_count} repo(s) and {counts.total_revision_count} revision(s);"
604
+ f" freed {strategy.expected_freed_size_str}.",
605
+ repos_deleted=counts.repo_count,
606
+ revisions_deleted=counts.total_revision_count,
607
+ freed=strategy.expected_freed_size_str,
608
+ )
609
+
610
+
611
+ @cache_cli.command(examples=["hf cache prune", "hf cache prune --dry-run"])
612
+ def prune(
613
+ cache_dir: Annotated[
614
+ str | None,
615
+ Option(
616
+ help="Cache directory to scan (defaults to Hugging Face cache).",
617
+ ),
618
+ ] = None,
619
+ yes: Annotated[
620
+ bool,
621
+ Option(
622
+ "-y",
623
+ "--yes",
624
+ help="Skip confirmation prompt.",
625
+ ),
626
+ ] = False,
627
+ dry_run: Annotated[
628
+ bool,
629
+ Option(
630
+ help="Preview deletions without removing anything.",
631
+ ),
632
+ ] = False,
633
+ ) -> None:
634
+ """Remove detached revisions and incomplete downloads from the cache."""
635
+ try:
636
+ hf_cache_info = scan_cache_dir(cache_dir)
637
+ except CacheNotFound as exc:
638
+ raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
639
+
640
+ selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]] = {}
641
+ revisions: set[str] = set()
642
+ for repo in hf_cache_info.repos:
643
+ detached = frozenset(revision for revision in repo.revisions if len(revision.refs) == 0)
644
+ if not detached:
645
+ continue
646
+ selected[repo] = detached
647
+ revisions.update(revision.commit_hash for revision in detached)
648
+
649
+ incomplete_files = hf_cache_info.incomplete_files
650
+
651
+ if len(revisions) == 0 and not incomplete_files:
652
+ out.text("No unreferenced revisions or incomplete downloads found. Nothing to prune.")
653
+ return
654
+
655
+ strategy = hf_cache_info.delete_revisions(*sorted(revisions))
656
+ counts = summarize_deletions(selected)
657
+ total_freed = strategy.expected_freed_size + hf_cache_info.incomplete_size_on_disk
658
+
659
+ summary = _prune_summary(counts.total_revision_count, len(incomplete_files))
660
+ out.text(f"About to delete {summary} ({_format_size(total_freed)} total).")
661
+ print_cache_selected_revisions(selected)
662
+
663
+ if dry_run:
664
+ out.result(
665
+ "Dry run: no files were deleted.",
666
+ dry_run=True,
667
+ revisions=counts.total_revision_count,
668
+ incomplete=len(incomplete_files), # might be overstated but it's fine
669
+ size=_format_size(total_freed),
670
+ )
671
+ return
672
+
673
+ out.confirm("Proceed?", yes=yes)
674
+
675
+ strategy.execute()
676
+ for incomplete_file in incomplete_files:
677
+ try:
678
+ incomplete_file.file_path.unlink()
679
+ except FileNotFoundError:
680
+ pass # already removed (e.g. by a full-repo deletion above)
681
+ except OSError as exc:
682
+ out.warning(f"Could not delete incomplete file {incomplete_file.file_path}: {exc}")
683
+ out.result(
684
+ f"Deleted {summary}; freed {_format_size(total_freed)}.",
685
+ revisions_deleted=counts.total_revision_count,
686
+ incomplete_deleted=len(incomplete_files),
687
+ freed=_format_size(total_freed),
688
+ )
689
+
690
+
691
+ @cache_cli.command(
692
+ examples=[
693
+ "hf cache verify gpt2",
694
+ "hf cache verify gpt2 --revision refs/pr/1",
695
+ "hf cache verify my-dataset --repo-type dataset",
696
+ ],
697
+ )
698
+ def verify(
699
+ repo_id: RepoIdArg,
700
+ repo_type: RepoTypeOpt = RepoTypeOpt.model,
701
+ revision: RevisionOpt = None,
702
+ cache_dir: Annotated[
703
+ str | None,
704
+ Option(
705
+ help="Cache directory to use when verifying files from cache (defaults to Hugging Face cache).",
706
+ ),
707
+ ] = None,
708
+ local_dir: Annotated[
709
+ str | None,
710
+ Option(
711
+ help="If set, verify files under this directory instead of the cache.",
712
+ ),
713
+ ] = None,
714
+ fail_on_missing_files: Annotated[
715
+ bool,
716
+ Option(
717
+ "--fail-on-missing-files",
718
+ help="Fail if some files exist on the remote but are missing locally.",
719
+ ),
720
+ ] = False,
721
+ fail_on_extra_files: Annotated[
722
+ bool,
723
+ Option(
724
+ "--fail-on-extra-files",
725
+ help="Fail if some files exist locally but are not present on the remote revision.",
726
+ ),
727
+ ] = False,
728
+ token: TokenOpt = None,
729
+ ) -> None:
730
+ """Verify checksums for a single repo revision from cache or a local directory.
731
+
732
+ Examples:
733
+ - Verify main revision in cache: `hf cache verify gpt2`
734
+ - Verify specific revision: `hf cache verify gpt2 --revision refs/pr/1`
735
+ - Verify dataset: `hf cache verify karpathy/fineweb-edu-100b-shuffle --repo-type dataset`
736
+ - Verify local dir: `hf cache verify deepseek-ai/DeepSeek-OCR --local-dir /path/to/repo`
737
+ """
738
+
739
+ if local_dir is not None and cache_dir is not None:
740
+ out.error("Cannot pass both --local-dir and --cache-dir. Use one or the other.")
741
+ raise click.exceptions.Exit(code=2)
742
+
743
+ api = get_hf_api(token=token)
744
+
745
+ result = api.verify_repo_checksums(
746
+ repo_id=repo_id,
747
+ repo_type=repo_type.value if hasattr(repo_type, "value") else str(repo_type),
748
+ revision=revision,
749
+ local_dir=local_dir,
750
+ cache_dir=cache_dir,
751
+ token=token,
752
+ )
753
+
754
+ exit_code = 0
755
+
756
+ if result.mismatches:
757
+ details = "\n".join(
758
+ f" - {m['path']}: expected {m['expected']} ({m['algorithm']}), got {m['actual']}"
759
+ for m in result.mismatches
760
+ )
761
+ out.text(f"❌ Checksum verification failed for the following file(s):\n{details}")
762
+ exit_code = 1
763
+
764
+ if result.missing_paths:
765
+ if fail_on_missing_files:
766
+ details = "\n".join(f" - {p}" for p in result.missing_paths)
767
+ out.text(f"❌ Missing files (present remotely, absent locally):\n{details}")
768
+ exit_code = 1
769
+ else:
770
+ out.warning(
771
+ f"{len(result.missing_paths)} remote file(s) are missing locally. "
772
+ "Use --fail-on-missing-files for details."
773
+ )
774
+
775
+ if result.extra_paths:
776
+ if fail_on_extra_files:
777
+ details = "\n".join(f" - {p}" for p in result.extra_paths)
778
+ out.text(f"❌ Extra files (present locally, absent remotely):\n{details}")
779
+ exit_code = 1
780
+ else:
781
+ out.warning(
782
+ f"{len(result.extra_paths)} local file(s) do not exist on the remote repo. "
783
+ "Use --fail-on-extra-files for details."
784
+ )
785
+
786
+ verified_location = result.verified_path
787
+
788
+ if exit_code != 0:
789
+ out.error(
790
+ f"Verification failed for '{repo_id}' ({repo_type.value}) in {verified_location}.\n Revision: {result.revision}"
791
+ )
792
+ raise click.exceptions.Exit(code=exit_code)
793
+
794
+ out.result(
795
+ f"Verified {result.checked_count} file(s) for {repo_type.value} '{repo_id}'. All checksums match.",
796
+ repo_id=repo_id,
797
+ repo_type=repo_type.value,
798
+ checked=result.checked_count,
799
+ path=str(verified_location),
800
+ )
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/collections.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains commands to interact with collections on the Hugging Face Hub."""
15
+
16
+ import enum
17
+ from typing import Annotated, get_args
18
+
19
+ from huggingface_hub.hf_api import CollectionItemType_T, CollectionSort_T
20
+
21
+ from ._cli_utils import LimitOpt, TokenOpt, get_hf_api, typer_factory
22
+ from ._framework import Argument, Option
23
+ from ._output import _dataclass_to_dict, out
24
+
25
+
26
+ # Build enums dynamically from Literal types to avoid duplication
27
+ _COLLECTION_ITEM_TYPES = get_args(CollectionItemType_T)
28
+ CollectionItemType = enum.Enum("CollectionItemType", {t: t for t in _COLLECTION_ITEM_TYPES}, type=str) # type: ignore[misc]
29
+
30
+ _COLLECTION_SORT_OPTIONS = get_args(CollectionSort_T)
31
+ CollectionSort = enum.Enum("CollectionSort", {s: s for s in _COLLECTION_SORT_OPTIONS}, type=str) # type: ignore[misc]
32
+
33
+
34
+ collections_cli = typer_factory(help="Interact with collections on the Hub.")
35
+
36
+
37
+ @collections_cli.command(
38
+ "list | ls",
39
+ examples=[
40
+ "hf collections ls",
41
+ "hf collections ls --owner nvidia",
42
+ "hf collections ls --item models/teknium/OpenHermes-2.5-Mistral-7B --limit 10",
43
+ ],
44
+ )
45
+ def collections_ls(
46
+ owner: Annotated[
47
+ str | None,
48
+ Option(help="Filter by owner username or organization."),
49
+ ] = None,
50
+ item: Annotated[
51
+ str | None,
52
+ Option(
53
+ help='Filter collections containing a specific item (e.g., "models/gpt2", "datasets/squad", "papers/2311.12983").'
54
+ ),
55
+ ] = None,
56
+ sort: Annotated[
57
+ CollectionSort | None,
58
+ Option(help="Sort results by last modified, trending, or upvotes."),
59
+ ] = None,
60
+ limit: LimitOpt = 10,
61
+ token: TokenOpt = None,
62
+ ) -> None:
63
+ """List collections on the Hub."""
64
+ api = get_hf_api(token=token)
65
+ sort_key = sort.value if sort else None
66
+ results = [
67
+ _dataclass_to_dict(collection)
68
+ for collection in api.list_collections(
69
+ owner=owner,
70
+ item=item,
71
+ sort=sort_key, # type: ignore[arg-type]
72
+ limit=limit,
73
+ )
74
+ ]
75
+ out.table(results)
76
+
77
+
78
+ @collections_cli.command(
79
+ "info",
80
+ examples=[
81
+ "hf collections info username/my-collection-slug",
82
+ ],
83
+ )
84
+ def collections_info(
85
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
86
+ token: TokenOpt = None,
87
+ ) -> None:
88
+ """Get info about a collection on the Hub."""
89
+ api = get_hf_api(token=token)
90
+ collection = api.get_collection(collection_slug)
91
+ out.dict(collection)
92
+
93
+
94
+ @collections_cli.command(
95
+ "create",
96
+ examples=[
97
+ 'hf collections create "My Models"',
98
+ 'hf collections create "My Models" --description "A collection of my favorite models" --private',
99
+ 'hf collections create "Org Collection" --namespace my-org',
100
+ ],
101
+ )
102
+ def collections_create(
103
+ title: Annotated[str, Argument(help="The title of the collection.")],
104
+ namespace: Annotated[
105
+ str | None,
106
+ Option(help="The namespace (username or organization). Defaults to the authenticated user."),
107
+ ] = None,
108
+ description: Annotated[
109
+ str | None,
110
+ Option(help="A description for the collection."),
111
+ ] = None,
112
+ private: Annotated[
113
+ bool,
114
+ Option(help="Create a private collection."),
115
+ ] = False,
116
+ exists_ok: Annotated[
117
+ bool,
118
+ Option(help="Do not raise an error if the collection already exists."),
119
+ ] = False,
120
+ token: TokenOpt = None,
121
+ ) -> None:
122
+ """Create a new collection on the Hub."""
123
+ api = get_hf_api(token=token)
124
+ collection = api.create_collection(
125
+ title=title,
126
+ namespace=namespace,
127
+ description=description,
128
+ private=private,
129
+ exists_ok=exists_ok,
130
+ )
131
+ out.result("Collection created", slug=collection.slug, url=collection.url)
132
+
133
+
134
+ @collections_cli.command(
135
+ "update",
136
+ examples=[
137
+ 'hf collections update username/my-collection --title "New Title"',
138
+ 'hf collections update username/my-collection --description "Updated description"',
139
+ "hf collections update username/my-collection --private --theme green",
140
+ ],
141
+ )
142
+ def collections_update(
143
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
144
+ title: Annotated[
145
+ str | None,
146
+ Option(help="The new title for the collection."),
147
+ ] = None,
148
+ description: Annotated[
149
+ str | None,
150
+ Option(help="The new description for the collection."),
151
+ ] = None,
152
+ position: Annotated[
153
+ int | None,
154
+ Option(help="The new position of the collection in the owner's list."),
155
+ ] = None,
156
+ private: Annotated[
157
+ bool | None,
158
+ Option(help="Whether the collection should be private."),
159
+ ] = None,
160
+ theme: Annotated[
161
+ str | None,
162
+ Option(help="The theme color for the collection (e.g., 'green', 'blue')."),
163
+ ] = None,
164
+ token: TokenOpt = None,
165
+ ) -> None:
166
+ """Update a collection's metadata on the Hub."""
167
+ api = get_hf_api(token=token)
168
+ collection = api.update_collection_metadata(
169
+ collection_slug=collection_slug,
170
+ title=title,
171
+ description=description,
172
+ position=position,
173
+ private=private,
174
+ theme=theme,
175
+ )
176
+ out.result("Collection updated", slug=collection.slug, url=collection.url)
177
+
178
+
179
+ @collections_cli.command(
180
+ "delete",
181
+ examples=[
182
+ "hf collections delete username/my-collection",
183
+ "hf collections delete username/my-collection --missing-ok",
184
+ ],
185
+ )
186
+ def collections_delete(
187
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
188
+ missing_ok: Annotated[
189
+ bool,
190
+ Option(help="Do not raise an error if the collection doesn't exist."),
191
+ ] = False,
192
+ token: TokenOpt = None,
193
+ ) -> None:
194
+ """Delete a collection from the Hub."""
195
+ api = get_hf_api(token=token)
196
+ api.delete_collection(collection_slug, missing_ok=missing_ok)
197
+ out.result("Collection deleted", slug=collection_slug)
198
+
199
+
200
+ @collections_cli.command(
201
+ "add-item",
202
+ examples=[
203
+ "hf collections add-item username/my-collection moonshotai/kimi-k2 model",
204
+ 'hf collections add-item username/my-collection Qwen/DeepPlanning dataset --note "Useful dataset"',
205
+ "hf collections add-item username/my-collection Tongyi-MAI/Z-Image space",
206
+ ],
207
+ )
208
+ def collections_add_item(
209
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
210
+ item_id: Annotated[str, Argument(help="The ID of the item to add (repo_id for repos, paper ID for papers).")],
211
+ item_type: Annotated[
212
+ CollectionItemType,
213
+ Argument(help="The type of item (model, dataset, space, paper, collection, or bucket)."),
214
+ ],
215
+ note: Annotated[
216
+ str | None,
217
+ Option(help="A note to attach to the item (max 500 characters)."),
218
+ ] = None,
219
+ exists_ok: Annotated[
220
+ bool,
221
+ Option(help="Do not raise an error if the item is already in the collection."),
222
+ ] = False,
223
+ token: TokenOpt = None,
224
+ ) -> None:
225
+ """Add an item to a collection."""
226
+ api = get_hf_api(token=token)
227
+ collection = api.add_collection_item(
228
+ collection_slug=collection_slug,
229
+ item_id=item_id,
230
+ item_type=item_type.value, # type: ignore[arg-type]
231
+ note=note,
232
+ exists_ok=exists_ok,
233
+ )
234
+ out.result("Item added to collection", slug=collection_slug, url=collection.url)
235
+
236
+
237
+ @collections_cli.command(
238
+ "update-item",
239
+ examples=[
240
+ 'hf collections update-item username/my-collection ITEM_OBJECT_ID --note "Updated note"',
241
+ "hf collections update-item username/my-collection ITEM_OBJECT_ID --position 0",
242
+ ],
243
+ )
244
+ def collections_update_item(
245
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
246
+ item_object_id: Annotated[
247
+ str,
248
+ Argument(help="The ID of the item in the collection (from 'item_object_id' field, not the repo_id)."),
249
+ ],
250
+ note: Annotated[
251
+ str | None,
252
+ Option(help="A new note for the item (max 500 characters)."),
253
+ ] = None,
254
+ position: Annotated[
255
+ int | None,
256
+ Option(help="The new position of the item in the collection."),
257
+ ] = None,
258
+ token: TokenOpt = None,
259
+ ) -> None:
260
+ """Update an item in a collection."""
261
+ api = get_hf_api(token=token)
262
+ api.update_collection_item(
263
+ collection_slug=collection_slug,
264
+ item_object_id=item_object_id,
265
+ note=note,
266
+ position=position,
267
+ )
268
+ out.result("Item updated in collection", slug=collection_slug)
269
+
270
+
271
+ @collections_cli.command("delete-item")
272
+ def collections_delete_item(
273
+ collection_slug: Annotated[str, Argument(help="The collection slug (e.g., 'username/collection-slug').")],
274
+ item_object_id: Annotated[
275
+ str,
276
+ Argument(
277
+ help="The ID of the item in the collection (retrieved from `item_object_id` field returned by 'hf collections info'."
278
+ ),
279
+ ],
280
+ missing_ok: Annotated[
281
+ bool,
282
+ Option(help="Do not raise an error if the item doesn't exist."),
283
+ ] = False,
284
+ token: TokenOpt = None,
285
+ ) -> None:
286
+ """Delete an item from a collection."""
287
+ api = get_hf_api(token=token)
288
+ api.delete_collection_item(
289
+ collection_slug=collection_slug,
290
+ item_object_id=item_object_id,
291
+ missing_ok=missing_ok,
292
+ )
293
+ out.result("Item deleted from collection", slug=collection_slug)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/datasets.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains commands to interact with datasets on the Hugging Face Hub."""
15
+
16
+ import enum
17
+ from typing import Annotated, get_args
18
+
19
+ import click
20
+
21
+ from huggingface_hub._dataset_viewer import execute_raw_sql_query
22
+ from huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundError
23
+ from huggingface_hub.hf_api import DatasetSort_T, ExpandDatasetProperty_T
24
+ from huggingface_hub.repocard import DatasetCard
25
+
26
+ from ._cli_utils import (
27
+ REPO_LIST_DEFAULT_LIMIT,
28
+ AuthorOpt,
29
+ FilterOpt,
30
+ LimitOpt,
31
+ RevisionOpt,
32
+ SearchOpt,
33
+ TokenOpt,
34
+ get_hf_api,
35
+ make_expand_properties_parser,
36
+ typer_factory,
37
+ )
38
+ from ._file_listing import list_repo_files_cmd
39
+ from ._framework import Argument, Option
40
+ from ._output import _dataclass_to_dict, out
41
+
42
+
43
+ _EXPAND_PROPERTIES = sorted(get_args(ExpandDatasetProperty_T))
44
+ _SORT_OPTIONS = get_args(DatasetSort_T)
45
+ DatasetSortEnum = enum.Enum("DatasetSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
46
+
47
+
48
+ ExpandOpt = Annotated[
49
+ str | None,
50
+ Option(
51
+ help=f"Comma-separated properties to return. When used, only the listed properties (and id) are returned. Example: '--expand=downloads,likes,tags'. Valid: {', '.join(_EXPAND_PROPERTIES)}.",
52
+ callback=make_expand_properties_parser(_EXPAND_PROPERTIES),
53
+ ),
54
+ ]
55
+
56
+
57
+ datasets_cli = typer_factory(help="Interact with datasets on the Hub.")
58
+
59
+
60
+ @datasets_cli.command(
61
+ "list | ls",
62
+ examples=[
63
+ "hf datasets ls",
64
+ "hf datasets ls --sort downloads --limit 10",
65
+ 'hf datasets ls --search "code"',
66
+ "hf datasets ls --filter benchmark:official",
67
+ "hf datasets ls HuggingFaceFW/fineweb",
68
+ "hf datasets ls HuggingFaceFW/fineweb -R",
69
+ "hf datasets ls HuggingFaceFW/fineweb --tree -h",
70
+ ],
71
+ )
72
+ def datasets_ls(
73
+ repo_id: Annotated[
74
+ str | None,
75
+ Argument(help="Dataset ID (e.g. `username/repo-name`) to list files from. If omitted, lists datasets."),
76
+ ] = None,
77
+ search: SearchOpt = None,
78
+ author: AuthorOpt = None,
79
+ filter: FilterOpt = None,
80
+ sort: Annotated[
81
+ DatasetSortEnum | None,
82
+ Option(help="Sort results."),
83
+ ] = None,
84
+ limit: LimitOpt = REPO_LIST_DEFAULT_LIMIT,
85
+ expand: ExpandOpt = None,
86
+ human_readable: Annotated[
87
+ bool,
88
+ Option("--human-readable", "-h", help="Show sizes in human readable format (only for listing files)."),
89
+ ] = False,
90
+ as_tree: Annotated[
91
+ bool,
92
+ Option("--tree", help="List files in tree format (only for listing files)."),
93
+ ] = False,
94
+ recursive: Annotated[
95
+ bool,
96
+ Option("--recursive", "-R", help="List files recursively (only for listing files)."),
97
+ ] = False,
98
+ revision: RevisionOpt = None,
99
+ token: TokenOpt = None,
100
+ ) -> None:
101
+ """List datasets on the Hub, or files in a dataset repo.
102
+
103
+ When called with no argument, lists datasets on the Hub.
104
+ When called with a dataset ID, lists files in that dataset repo.
105
+ """
106
+ if repo_id is not None:
107
+ if search is not None:
108
+ raise click.BadParameter("Cannot use --search when listing files.")
109
+ if author is not None:
110
+ raise click.BadParameter("Cannot use --author when listing files.")
111
+ if filter is not None:
112
+ raise click.BadParameter("Cannot use --filter when listing files.")
113
+ if sort is not None:
114
+ raise click.BadParameter("Cannot use --sort when listing files.")
115
+ if limit != REPO_LIST_DEFAULT_LIMIT:
116
+ raise click.BadParameter("Cannot use --limit when listing files.")
117
+ if expand is not None:
118
+ raise click.BadParameter("Cannot use --expand when listing files.")
119
+ return list_repo_files_cmd(
120
+ repo_id=repo_id,
121
+ repo_type="dataset",
122
+ human_readable=human_readable,
123
+ as_tree=as_tree,
124
+ recursive=recursive,
125
+ revision=revision,
126
+ token=token,
127
+ )
128
+
129
+ if as_tree:
130
+ raise click.BadParameter("Cannot use --tree when listing datasets.")
131
+ if recursive:
132
+ raise click.BadParameter("Cannot use --recursive when listing datasets.")
133
+ if human_readable:
134
+ raise click.BadParameter("Cannot use --human-readable when listing datasets.")
135
+ if revision is not None:
136
+ raise click.BadParameter("Cannot use --revision when listing datasets.")
137
+
138
+ api = get_hf_api(token=token)
139
+ sort_key = sort.value if sort else None
140
+ results = [
141
+ _dataclass_to_dict(dataset_info)
142
+ for dataset_info in api.list_datasets(
143
+ filter=filter,
144
+ author=author,
145
+ search=search,
146
+ sort=sort_key,
147
+ limit=limit,
148
+ expand=expand, # type: ignore
149
+ )
150
+ ]
151
+ out.table(results)
152
+
153
+
154
+ @datasets_cli.command(
155
+ "leaderboard",
156
+ examples=[
157
+ "hf datasets leaderboard SWE-bench/SWE-bench_Verified",
158
+ "hf datasets leaderboard SWE-bench/SWE-bench_Verified --limit 5 --format json",
159
+ "hf datasets ls --filter benchmark:official # list available leaderboards",
160
+ ],
161
+ )
162
+ def datasets_leaderboard(
163
+ dataset_id: Annotated[str, Argument(help="The benchmark dataset ID (e.g. `SWE-bench/SWE-bench_Verified`).")],
164
+ limit: LimitOpt = 20,
165
+ token: TokenOpt = None,
166
+ ) -> None:
167
+ """List model scores from a dataset leaderboard. This command helps find the best models for a task or compare models by benchmark scores. Use 'hf datasets ls --filter benchmark:official' to list available leaderboards."""
168
+ api = get_hf_api(token=token)
169
+ leaderboard = api.get_dataset_leaderboard(repo_id=dataset_id)
170
+ results = [_dataclass_to_dict(entry) for entry in leaderboard[:limit]]
171
+ out.table(
172
+ results,
173
+ headers=["rank", "model_id", "value", "source"],
174
+ id_key="model_id",
175
+ )
176
+ out.hint("Use 'hf datasets ls --filter benchmark:official' to list available leaderboards.")
177
+ if leaderboard:
178
+ out.hint(f"Use 'hf models info {leaderboard[0].model_id}' to get details about a model.")
179
+
180
+
181
+ @datasets_cli.command(
182
+ "info",
183
+ examples=[
184
+ "hf datasets info HuggingFaceFW/fineweb",
185
+ "hf datasets info my-dataset --expand downloads,likes,tags",
186
+ ],
187
+ )
188
+ def datasets_info(
189
+ dataset_id: Annotated[str, Argument(help="The dataset ID (e.g. `username/repo-name`).")],
190
+ revision: RevisionOpt = None,
191
+ expand: ExpandOpt = None,
192
+ token: TokenOpt = None,
193
+ ) -> None:
194
+ """Get info about a dataset on the Hub."""
195
+ api = get_hf_api(token=token)
196
+ try:
197
+ info = api.dataset_info(repo_id=dataset_id, revision=revision, expand=expand) # type: ignore
198
+ except RepositoryNotFoundError as e:
199
+ raise CLIError(f"Dataset '{dataset_id}' not found.") from e
200
+ except RevisionNotFoundError as e:
201
+ raise CLIError(f"Revision '{revision}' not found on '{dataset_id}'.") from e
202
+ out.dict(info)
203
+
204
+
205
+ @datasets_cli.command(
206
+ "parquet",
207
+ examples=[
208
+ "hf datasets parquet cfahlgren1/hub-stats",
209
+ "hf datasets parquet cfahlgren1/hub-stats --subset models",
210
+ "hf datasets parquet cfahlgren1/hub-stats --split train",
211
+ "hf datasets parquet cfahlgren1/hub-stats --format json",
212
+ ],
213
+ )
214
+ def datasets_parquet(
215
+ dataset_id: Annotated[str, Argument(help="The dataset ID (e.g. `username/repo-name`).")],
216
+ subset: Annotated[str | None, Option("--subset", help="Filter parquet entries by subset/config.")] = None,
217
+ split: Annotated[str | None, Option(help="Filter parquet entries by split.")] = None,
218
+ token: TokenOpt = None,
219
+ ) -> None:
220
+ """List parquet file URLs available for a dataset."""
221
+ api = get_hf_api(token=token)
222
+ entries = api.list_dataset_parquet_files(repo_id=dataset_id, config=subset)
223
+ filtered = [entry for entry in entries if split is None or entry.split == split]
224
+ results = [
225
+ {"subset": entry.config, "split": entry.split, "url": entry.url, "size": entry.size} for entry in filtered
226
+ ]
227
+ out.table(results, headers=["subset", "split", "url", "size"], id_key="url")
228
+
229
+
230
+ @datasets_cli.command(
231
+ "sql",
232
+ examples=[
233
+ "hf datasets sql \"SELECT COUNT(*) AS rows FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet')\"",
234
+ "hf datasets sql \"SELECT * FROM read_parquet('https://huggingface.co/api/datasets/cfahlgren1/hub-stats/parquet/models/train/0.parquet') LIMIT 5\" --format json",
235
+ ],
236
+ )
237
+ def datasets_sql(
238
+ sql: Annotated[str, Argument(help="Raw SQL query to execute.")],
239
+ token: TokenOpt = None,
240
+ ) -> None:
241
+ """Execute a raw SQL query with DuckDB against dataset parquet URLs."""
242
+ try:
243
+ result = execute_raw_sql_query(sql_query=sql, token=token)
244
+ except ImportError as e:
245
+ raise CLIError(str(e)) from e
246
+ out.table(result)
247
+
248
+
249
+ @datasets_cli.command(
250
+ "card",
251
+ examples=[
252
+ "hf datasets card HuggingFaceFW/fineweb",
253
+ "hf datasets card HuggingFaceFW/fineweb --metadata",
254
+ "hf datasets card HuggingFaceFW/fineweb --metadata --format json",
255
+ "hf datasets card HuggingFaceFW/fineweb --text",
256
+ ],
257
+ )
258
+ def datasets_card(
259
+ dataset_id: Annotated[str, Argument(help="The dataset ID (e.g. `username/repo-name`).")],
260
+ metadata: Annotated[bool, Option("--metadata", help="Output only the metadata from the card.")] = False,
261
+ text: Annotated[bool, Option("--text", help="Output only the text body (no metadata).")] = False,
262
+ token: TokenOpt = None,
263
+ ) -> None:
264
+ """Get the dataset card (README) for a dataset on the Hub."""
265
+ if metadata and text:
266
+ raise CLIError("--metadata and --text are mutually exclusive.")
267
+ card = DatasetCard.load(dataset_id, token=token)
268
+ if metadata:
269
+ out.dict(card.data.to_dict())
270
+ elif text:
271
+ out.text(card.text)
272
+ else:
273
+ out.text(card.content)
274
+ out.hint(f"Use `hf datasets card {dataset_id} --metadata` to extract only the card metadata.")
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/deprecated_cli.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deprecated `huggingface-cli` entry point. Warns and exits."""
2
+
3
+ import shutil
4
+ import sys
5
+
6
+ from ._output import out
7
+
8
+
9
+ def main() -> None:
10
+ out.warning("`huggingface-cli` is deprecated and no longer works. Use `hf` instead.\n")
11
+
12
+ if shutil.which("hf"):
13
+ from huggingface_hub.cli._cli_utils import check_cli_update
14
+
15
+ check_cli_update("huggingface_hub")
16
+ out.hint("`hf` is already installed! Use it directly.\n")
17
+ else:
18
+ out.hint(
19
+ "Install `hf`:\n"
20
+ " Standalone (recommended): curl -LsSf https://hf.co/cli/install.sh | bash\n"
21
+ " Using Homebrew: brew install hf\n"
22
+ " Using pip: pip install huggingface_hub\n",
23
+ )
24
+
25
+ out.hint(
26
+ "Examples:\n"
27
+ " hf auth login\n"
28
+ " hf download unsloth/gemma-4-31B-it-GGUF\n"
29
+ " hf upload my-cool-model . .\n"
30
+ ' hf models ls --search "gemma"\n'
31
+ " hf repos ls --format json\n"
32
+ " hf jobs run python:3.12 python -c 'print(\"Hello!\")'\n"
33
+ " hf --help\n",
34
+ )
35
+ sys.exit(1)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/discussions.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains commands to interact with discussions and pull requests on the Hugging Face Hub."""
15
+
16
+ import enum
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Annotated
20
+
21
+ import click
22
+
23
+ from huggingface_hub import constants
24
+
25
+ from ._cli_utils import (
26
+ AuthorOpt,
27
+ LimitOpt,
28
+ RepoIdArg,
29
+ RepoType,
30
+ RepoTypeOpt,
31
+ TokenOpt,
32
+ get_hf_api,
33
+ typer_factory,
34
+ )
35
+ from ._framework import Argument, Option
36
+ from ._output import _dataclass_to_dict, out
37
+
38
+
39
+ class DiscussionStatus(str, enum.Enum):
40
+ open = "open"
41
+ closed = "closed"
42
+ merged = "merged"
43
+ draft = "draft"
44
+ all = "all"
45
+
46
+
47
+ class DiscussionKind(str, enum.Enum):
48
+ all = "all"
49
+ discussion = "discussion"
50
+ pull_request = "pull_request"
51
+
52
+
53
+ # "merged" and "draft" are valid Discussion statuses but the Hub API filter
54
+ # (DiscussionStatusFilter) only accepts "all", "open", "closed". When the user
55
+ # asks for merged/draft we fetch with api_status=None (i.e. all) and filter
56
+ # client-side.
57
+ _CLIENT_SIDE_STATUSES = {"merged", "draft"}
58
+
59
+
60
+ DiscussionNumArg = Annotated[
61
+ int,
62
+ Argument(
63
+ help="The discussion or pull request number.",
64
+ min=1,
65
+ ),
66
+ ]
67
+
68
+
69
+ def _read_body(body: str | None, body_file: Path | None) -> str | None:
70
+ """Resolve body text from --body or --body-file (supports '-' for stdin)."""
71
+ if body is not None and body_file is not None:
72
+ raise click.BadParameter("Cannot use both --body and --body-file.")
73
+ if body_file is not None:
74
+ if str(body_file) == "-":
75
+ return sys.stdin.read()
76
+ return body_file.read_text(encoding="utf-8")
77
+ return body
78
+
79
+
80
+ discussions_cli = typer_factory(help="Manage discussions and pull requests on the Hub.")
81
+
82
+
83
+ @discussions_cli.command(
84
+ "list | ls",
85
+ examples=[
86
+ "hf discussions list username/my-model",
87
+ "hf discussions list username/my-model --kind pull_request --status merged",
88
+ "hf discussions list username/my-dataset --type dataset --status closed",
89
+ "hf discussions list username/my-model --author alice --format json",
90
+ ],
91
+ )
92
+ def discussion_list(
93
+ repo_id: RepoIdArg,
94
+ status: Annotated[
95
+ DiscussionStatus,
96
+ Option(
97
+ "-s",
98
+ "--status",
99
+ help="Filter by status (open, closed, merged, draft, all).",
100
+ ),
101
+ ] = DiscussionStatus.open,
102
+ kind: Annotated[
103
+ DiscussionKind,
104
+ Option(
105
+ "-k",
106
+ "--kind",
107
+ help="Filter by kind (discussion, pull_request, all).",
108
+ ),
109
+ ] = DiscussionKind.all,
110
+ author: AuthorOpt = None,
111
+ limit: LimitOpt = 30,
112
+ repo_type: RepoTypeOpt = RepoType.model,
113
+ token: TokenOpt = None,
114
+ ) -> None:
115
+ """List discussions and pull requests on a repo."""
116
+ api = get_hf_api(token=token)
117
+
118
+ api_status: constants.DiscussionStatusFilter | None
119
+ if status == DiscussionStatus.open:
120
+ api_status = "open"
121
+ elif status == DiscussionStatus.closed:
122
+ api_status = "closed"
123
+ else:
124
+ api_status = None
125
+
126
+ api_discussion_type: constants.DiscussionTypeFilter | None
127
+ if kind == DiscussionKind.all:
128
+ api_discussion_type = None
129
+ else:
130
+ api_discussion_type = kind.value # type: ignore[assignment]
131
+
132
+ discussions = []
133
+ for d in api.get_repo_discussions(
134
+ repo_id=repo_id,
135
+ author=author,
136
+ discussion_type=api_discussion_type,
137
+ discussion_status=api_status,
138
+ repo_type=repo_type.value,
139
+ ):
140
+ if status.value in _CLIENT_SIDE_STATUSES and d.status != status.value:
141
+ continue
142
+ discussions.append(d)
143
+ if len(discussions) >= limit:
144
+ break
145
+
146
+ items = [_dataclass_to_dict(d) for d in discussions]
147
+ out.table(
148
+ items,
149
+ headers=["num", "title", "is_pull_request", "status", "author", "created_at"],
150
+ id_key="num",
151
+ )
152
+
153
+
154
+ @discussions_cli.command(
155
+ "info",
156
+ examples=[
157
+ "hf discussions info username/my-model 5",
158
+ "hf discussions info username/my-model 5 --format json",
159
+ ],
160
+ )
161
+ def discussion_info(
162
+ repo_id: RepoIdArg,
163
+ num: DiscussionNumArg,
164
+ repo_type: RepoTypeOpt = RepoType.model,
165
+ token: TokenOpt = None,
166
+ ) -> None:
167
+ """Get info about a discussion or pull request."""
168
+ api = get_hf_api(token=token)
169
+ details = api.get_discussion_details(
170
+ repo_id=repo_id,
171
+ discussion_num=num,
172
+ repo_type=repo_type.value,
173
+ )
174
+ out.dict(details)
175
+
176
+
177
+ @discussions_cli.command(
178
+ "create",
179
+ examples=[
180
+ 'hf discussions create username/my-model --title "Bug report"',
181
+ 'hf discussions create username/my-model --title "Feature request" --body "Please add X"',
182
+ 'hf discussions create username/my-model --title "Fix typo" --pull-request',
183
+ 'hf discussions create username/my-dataset --type dataset --title "Data quality issue"',
184
+ ],
185
+ )
186
+ def discussion_create(
187
+ repo_id: RepoIdArg,
188
+ title: Annotated[
189
+ str,
190
+ Option(
191
+ "--title",
192
+ help="The title of the discussion or pull request.",
193
+ ),
194
+ ],
195
+ body: Annotated[
196
+ str | None,
197
+ Option(
198
+ "--body",
199
+ help="The description (supports Markdown).",
200
+ ),
201
+ ] = None,
202
+ body_file: Annotated[
203
+ Path | None,
204
+ Option(
205
+ "--body-file",
206
+ help="Read the description from a file. Use '-' for stdin.",
207
+ ),
208
+ ] = None,
209
+ pull_request: Annotated[
210
+ bool,
211
+ Option(
212
+ "--pull-request",
213
+ "--pr",
214
+ help="Create a pull request instead of a discussion.",
215
+ ),
216
+ ] = False,
217
+ repo_type: RepoTypeOpt = RepoType.model,
218
+ token: TokenOpt = None,
219
+ ) -> None:
220
+ """Create a new discussion or pull request on a repo."""
221
+ description = _read_body(body, body_file)
222
+ api = get_hf_api(token=token)
223
+ discussion = api.create_discussion(
224
+ repo_id=repo_id,
225
+ title=title,
226
+ description=description,
227
+ repo_type=repo_type.value,
228
+ pull_request=pull_request,
229
+ )
230
+ kind = "pull request" if pull_request else "discussion"
231
+ ref = f"refs/pr/{discussion.num}" if pull_request else None
232
+ out.result(f"Created {kind} #{discussion.num} on {repo_id}", num=discussion.num, url=discussion.url, ref=ref)
233
+
234
+
235
+ @discussions_cli.command(
236
+ "comment",
237
+ examples=[
238
+ 'hf discussions comment username/my-model 5 --body "Thanks for reporting!"',
239
+ 'hf discussions comment username/my-model 5 --body "LGTM!"',
240
+ ],
241
+ )
242
+ def discussion_comment(
243
+ repo_id: RepoIdArg,
244
+ num: DiscussionNumArg,
245
+ body: Annotated[
246
+ str | None,
247
+ Option(
248
+ "--body",
249
+ help="The comment text (supports Markdown).",
250
+ ),
251
+ ] = None,
252
+ body_file: Annotated[
253
+ Path | None,
254
+ Option(
255
+ "--body-file",
256
+ help="Read the comment from a file. Use '-' for stdin.",
257
+ ),
258
+ ] = None,
259
+ repo_type: RepoTypeOpt = RepoType.model,
260
+ token: TokenOpt = None,
261
+ ) -> None:
262
+ """Comment on a discussion or pull request."""
263
+ comment = _read_body(body, body_file)
264
+ if comment is None:
265
+ raise click.BadParameter("Either --body or --body-file is required.")
266
+ api = get_hf_api(token=token)
267
+ api.comment_discussion(
268
+ repo_id=repo_id,
269
+ discussion_num=num,
270
+ comment=comment,
271
+ repo_type=repo_type.value,
272
+ )
273
+ out.result(f"Commented on #{num} in {repo_id}", num=num, repo=repo_id)
274
+
275
+
276
+ @discussions_cli.command(
277
+ "edit",
278
+ examples=[
279
+ 'hf discussions edit username/my-model 5 abc123 --body "Updated comment."',
280
+ "hf discussions edit username/my-model 5 abc123 --body-file fixed.md",
281
+ ],
282
+ )
283
+ def discussion_edit(
284
+ repo_id: RepoIdArg,
285
+ num: DiscussionNumArg,
286
+ comment_id: Annotated[
287
+ str,
288
+ Argument(
289
+ help="The ID of the comment to edit (see 'hf discussions info ... --format json').",
290
+ ),
291
+ ],
292
+ body: Annotated[
293
+ str | None,
294
+ Option(
295
+ "--body",
296
+ help="The new comment text (supports Markdown).",
297
+ ),
298
+ ] = None,
299
+ body_file: Annotated[
300
+ Path | None,
301
+ Option(
302
+ "--body-file",
303
+ help="Read the new comment from a file. Use '-' for stdin.",
304
+ ),
305
+ ] = None,
306
+ repo_type: RepoTypeOpt = RepoType.model,
307
+ token: TokenOpt = None,
308
+ ) -> None:
309
+ """Edit an existing comment on a discussion or pull request."""
310
+ new_content = _read_body(body, body_file)
311
+ if new_content is None:
312
+ raise click.BadParameter("Either --body or --body-file is required.")
313
+ api = get_hf_api(token=token)
314
+ api.edit_discussion_comment(
315
+ repo_id=repo_id,
316
+ discussion_num=num,
317
+ comment_id=comment_id,
318
+ new_content=new_content,
319
+ repo_type=repo_type.value,
320
+ )
321
+ out.result(f"Edited comment {comment_id} on #{num} in {repo_id}", num=num, repo=repo_id, comment_id=comment_id)
322
+
323
+
324
+ @discussions_cli.command(
325
+ "close",
326
+ examples=[
327
+ "hf discussions close username/my-model 5",
328
+ 'hf discussions close username/my-model 5 --comment "Closing as resolved."',
329
+ ],
330
+ )
331
+ def discussion_close(
332
+ repo_id: RepoIdArg,
333
+ num: DiscussionNumArg,
334
+ comment: Annotated[
335
+ str | None,
336
+ Option(
337
+ "--comment",
338
+ help="An optional comment to post when closing.",
339
+ ),
340
+ ] = None,
341
+ yes: Annotated[
342
+ bool,
343
+ Option(
344
+ "--yes",
345
+ "-y",
346
+ help="Skip confirmation prompt.",
347
+ ),
348
+ ] = False,
349
+ repo_type: RepoTypeOpt = RepoType.model,
350
+ token: TokenOpt = None,
351
+ ) -> None:
352
+ """Close a discussion or pull request."""
353
+ out.confirm(f"Close #{num} on '{repo_id}'?", yes=yes)
354
+ api = get_hf_api(token=token)
355
+ api.change_discussion_status(
356
+ repo_id=repo_id,
357
+ discussion_num=num,
358
+ new_status="closed",
359
+ comment=comment,
360
+ repo_type=repo_type.value,
361
+ )
362
+ out.result(f"Closed #{num} in {repo_id}", num=num, repo=repo_id)
363
+
364
+
365
+ @discussions_cli.command(
366
+ "reopen",
367
+ examples=[
368
+ "hf discussions reopen username/my-model 5",
369
+ 'hf discussions reopen username/my-model 5 --comment "Reopening for further investigation."',
370
+ ],
371
+ )
372
+ def discussion_reopen(
373
+ repo_id: RepoIdArg,
374
+ num: DiscussionNumArg,
375
+ comment: Annotated[
376
+ str | None,
377
+ Option(
378
+ "--comment",
379
+ help="An optional comment to post when reopening.",
380
+ ),
381
+ ] = None,
382
+ yes: Annotated[
383
+ bool,
384
+ Option(
385
+ "--yes",
386
+ "-y",
387
+ help="Skip confirmation prompt.",
388
+ ),
389
+ ] = False,
390
+ repo_type: RepoTypeOpt = RepoType.model,
391
+ token: TokenOpt = None,
392
+ ) -> None:
393
+ """Reopen a closed discussion or pull request."""
394
+ out.confirm(f"Reopen #{num} on '{repo_id}'?", yes=yes)
395
+ api = get_hf_api(token=token)
396
+ api.change_discussion_status(
397
+ repo_id=repo_id,
398
+ discussion_num=num,
399
+ new_status="open",
400
+ comment=comment,
401
+ repo_type=repo_type.value,
402
+ )
403
+ out.result(f"Reopened #{num} in {repo_id}", num=num, repo=repo_id)
404
+
405
+
406
+ @discussions_cli.command(
407
+ "rename",
408
+ examples=[
409
+ 'hf discussions rename username/my-model 5 "Updated title"',
410
+ ],
411
+ )
412
+ def discussion_rename(
413
+ repo_id: RepoIdArg,
414
+ num: DiscussionNumArg,
415
+ new_title: Annotated[
416
+ str,
417
+ Argument(
418
+ help="The new title.",
419
+ ),
420
+ ],
421
+ repo_type: RepoTypeOpt = RepoType.model,
422
+ token: TokenOpt = None,
423
+ ) -> None:
424
+ """Rename a discussion or pull request."""
425
+ api = get_hf_api(token=token)
426
+ api.rename_discussion(
427
+ repo_id=repo_id,
428
+ discussion_num=num,
429
+ new_title=new_title,
430
+ repo_type=repo_type.value,
431
+ )
432
+ out.result(f"Renamed #{num} in {repo_id}", num=num, repo=repo_id, title=new_title)
433
+
434
+
435
+ @discussions_cli.command(
436
+ "merge",
437
+ examples=[
438
+ "hf discussions merge username/my-model 5",
439
+ 'hf discussions merge username/my-model 5 --comment "Merging, thanks!"',
440
+ ],
441
+ )
442
+ def discussion_merge(
443
+ repo_id: RepoIdArg,
444
+ num: DiscussionNumArg,
445
+ comment: Annotated[
446
+ str | None,
447
+ Option(
448
+ "--comment",
449
+ help="An optional comment to post when merging.",
450
+ ),
451
+ ] = None,
452
+ yes: Annotated[
453
+ bool,
454
+ Option(
455
+ "--yes",
456
+ "-y",
457
+ help="Skip confirmation prompt.",
458
+ ),
459
+ ] = False,
460
+ repo_type: RepoTypeOpt = RepoType.model,
461
+ token: TokenOpt = None,
462
+ ) -> None:
463
+ """Merge a pull request."""
464
+ out.confirm(f"Merge #{num} on '{repo_id}'?", yes=yes)
465
+ api = get_hf_api(token=token)
466
+ api.merge_pull_request(
467
+ repo_id=repo_id,
468
+ discussion_num=num,
469
+ comment=comment,
470
+ repo_type=repo_type.value,
471
+ )
472
+ out.result(f"Merged #{num} in {repo_id}", num=num, repo=repo_id)
473
+
474
+
475
+ @discussions_cli.command(
476
+ "diff",
477
+ examples=[
478
+ "hf discussions diff username/my-model 5",
479
+ ],
480
+ )
481
+ def discussion_diff(
482
+ repo_id: RepoIdArg,
483
+ num: DiscussionNumArg,
484
+ repo_type: RepoTypeOpt = RepoType.model,
485
+ token: TokenOpt = None,
486
+ ) -> None:
487
+ """Show the diff of a pull request."""
488
+ api = get_hf_api(token=token)
489
+ details = api.get_discussion_details(
490
+ repo_id=repo_id,
491
+ discussion_num=num,
492
+ repo_type=repo_type.value,
493
+ )
494
+ if details.diff:
495
+ out.text(details.diff)
496
+ else:
497
+ out.text("No diff available.")
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/download.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 202-present, the HuggingFace Inc. team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains command to download files from the Hub with the CLI."""
15
+
16
+ import warnings
17
+ from typing import Annotated
18
+
19
+ from huggingface_hub import constants
20
+ from huggingface_hub._snapshot_download import snapshot_download
21
+ from huggingface_hub.errors import CLIError
22
+ from huggingface_hub.file_download import DryRunFileInfo, hf_hub_download
23
+ from huggingface_hub.utils import _format_size, parse_hf_uri
24
+
25
+ from ._cli_utils import RepoIdArg, RepoType, RepoTypeOptionalOpt, RevisionOpt, TokenOpt
26
+ from ._framework import Argument, Option
27
+ from ._output import out
28
+
29
+
30
+ DOWNLOAD_EXAMPLES = [
31
+ "hf download meta-llama/Llama-3.2-1B-Instruct",
32
+ "hf download meta-llama/Llama-3.2-1B-Instruct config.json tokenizer.json",
33
+ 'hf download meta-llama/Llama-3.2-1B-Instruct --include "*.safetensors" --exclude "*.bin"',
34
+ "hf download meta-llama/Llama-3.2-1B-Instruct --local-dir ./models/llama",
35
+ "hf download HuggingFaceM4/FineVision art/ --repo-type dataset",
36
+ "hf download hf://datasets/HuggingFaceH4/ultrachat_200k",
37
+ ]
38
+
39
+
40
+ def download(
41
+ repo_id: RepoIdArg,
42
+ filenames: Annotated[
43
+ list[str] | None,
44
+ Argument(
45
+ help="Files to download (e.g. `config.json`, `data/metadata.jsonl`).",
46
+ ),
47
+ ] = None,
48
+ repo_type: RepoTypeOptionalOpt = None,
49
+ revision: RevisionOpt = None,
50
+ include: Annotated[
51
+ list[str] | None,
52
+ Option(
53
+ help="Glob patterns to include from files to download. eg: *.json",
54
+ ),
55
+ ] = None,
56
+ exclude: Annotated[
57
+ list[str] | None,
58
+ Option(
59
+ help="Glob patterns to exclude from files to download.",
60
+ ),
61
+ ] = None,
62
+ cache_dir: Annotated[
63
+ str | None,
64
+ Option(
65
+ help="Directory where to save files.",
66
+ ),
67
+ ] = None,
68
+ local_dir: Annotated[
69
+ str | None,
70
+ Option(
71
+ help="If set, the downloaded file will be placed under this directory. Check out https://huggingface.co/docs/huggingface_hub/guides/download#download-files-to-a-local-folder for more details.",
72
+ ),
73
+ ] = None,
74
+ force_download: Annotated[
75
+ bool,
76
+ Option(
77
+ help="If True, the files will be downloaded even if they are already cached.",
78
+ ),
79
+ ] = False,
80
+ dry_run: Annotated[
81
+ bool,
82
+ Option(
83
+ help="If True, perform a dry run without actually downloading the file.",
84
+ ),
85
+ ] = False,
86
+ token: TokenOpt = None,
87
+ max_workers: Annotated[
88
+ int,
89
+ Option(
90
+ help="Maximum number of workers to use for downloading files. Default is 8.",
91
+ ),
92
+ ] = 8,
93
+ ) -> None:
94
+ """Download files from the Hub."""
95
+ if local_dir is not None and cache_dir is not None:
96
+ raise CLIError(
97
+ "Cannot use both `--local-dir` and `--cache-dir` at the same time. "
98
+ "Use `--cache-dir` (or set the HF_HOME environment variable) for shared caching, "
99
+ "or `--local-dir` for a one-off download to a specific directory."
100
+ )
101
+
102
+ # `repo_id` may be a plain repo id or an `hf://` URI (e.g. `hf://datasets/my-org/my-dataset@v1.0/data/`).
103
+ # When a URI is provided, it is authoritative for the repo type, revision and (optionally) file path,
104
+ # so explicit `--repo-type` / `--revision` options are forbidden alongside it.
105
+ # We branch on the `hf://` prefix (the user's *intent*) rather than on whether the string parses as a
106
+ # valid URI: a malformed URI then surfaces a precise `HfUriError` (formatted globally in `cli/_errors.py`)
107
+ # instead of silently falling through to the plain-repo-id path and failing later with an opaque error.
108
+ if repo_id.startswith(constants.HF_PROTOCOL):
109
+ if repo_type is not None:
110
+ raise CLIError(f"'--repo-type' cannot be used with an 'hf://' URI ('{repo_id}').")
111
+ if revision is not None:
112
+ raise CLIError(f"'--revision' cannot be used with an 'hf://' URI ('{repo_id}').")
113
+ uri = parse_hf_uri(repo_id)
114
+ if uri.is_bucket:
115
+ raise CLIError("Buckets are not supported by `hf download`. Use `hf sync` instead.")
116
+ # The URI parser strips trailing slashes, but `hf download` uses a trailing '/' to denote a subfolder
117
+ # download (e.g. `data/` -> `data/**`). Re-append it when the URI explicitly ended with '/' so a folder
118
+ # URI keeps routing through the subfolder code path below.
119
+ path_in_repo = uri.path_in_repo
120
+ if path_in_repo and repo_id.endswith("/"):
121
+ path_in_repo += "/"
122
+ repo_id, repo_type_str, revision = uri.id, uri.type, uri.revision
123
+ if path_in_repo:
124
+ if filenames:
125
+ raise CLIError(
126
+ f"Cannot combine a file path in the hf:// URI ('{path_in_repo}') with positional filenames {filenames}."
127
+ )
128
+ filenames = [path_in_repo]
129
+ else:
130
+ repo_type_str = (repo_type or RepoType.model).value
131
+
132
+ def run_download() -> str | DryRunFileInfo | list[DryRunFileInfo]:
133
+ filenames_list = filenames if filenames is not None else []
134
+
135
+ # Separate subfolder patterns (ending with '/') from regular filenames
136
+ # Subfolders like "art/" are converted to include patterns like "art/**"
137
+ subfolders = [f for f in filenames_list if f.endswith("/")]
138
+ subfolder_patterns = [f"{f.rstrip('/')}/**" for f in subfolders]
139
+ regular_filenames = [f for f in filenames_list if not f.endswith("/")]
140
+
141
+ # Error if subfolder patterns are combined with --include/--exclude
142
+ # Guide user to use --include instead of subfolder argument
143
+ if len(subfolder_patterns) > 0:
144
+ if include is not None and len(include) > 0:
145
+ raise CLIError(
146
+ f"Cannot combine subfolder argument ('{subfolders[0]}') with `--include`. "
147
+ f'Please use `--include "{subfolders[0]}*"` instead.'
148
+ )
149
+ if exclude is not None and len(exclude) > 0:
150
+ raise CLIError(
151
+ f"Cannot combine subfolder argument ('{subfolders[0]}') with `--exclude`. "
152
+ f'Please use `--include "{subfolders[0]}*"` with `--exclude` instead.'
153
+ )
154
+
155
+ # Warn user if patterns are ignored (only if regular filenames are provided)
156
+ if len(regular_filenames) > 0:
157
+ if include is not None and len(include) > 0:
158
+ warnings.warn("Ignoring `--include` since filenames have been explicitly set.")
159
+ if exclude is not None and len(exclude) > 0:
160
+ warnings.warn("Ignoring `--exclude` since filenames have been explicitly set.")
161
+
162
+ # Single file to download (not a subfolder): use `hf_hub_download`
163
+ if len(regular_filenames) == 1 and len(subfolder_patterns) == 0:
164
+ return hf_hub_download(
165
+ repo_id=repo_id,
166
+ repo_type=repo_type_str,
167
+ revision=revision,
168
+ filename=regular_filenames[0],
169
+ cache_dir=cache_dir,
170
+ force_download=force_download,
171
+ token=token,
172
+ local_dir=local_dir,
173
+ library_name="huggingface-cli",
174
+ dry_run=dry_run,
175
+ )
176
+
177
+ # Otherwise: use `snapshot_download` to ensure all files comes from same revision
178
+ if len(regular_filenames) == 0 and len(subfolder_patterns) == 0:
179
+ # No filenames provided: use include/exclude patterns
180
+ allow_patterns = include
181
+ ignore_patterns = exclude
182
+ else:
183
+ # Combine regular filenames and subfolder patterns as allow_patterns
184
+ allow_patterns = regular_filenames + subfolder_patterns
185
+ ignore_patterns = None
186
+
187
+ return snapshot_download(
188
+ repo_id=repo_id,
189
+ repo_type=repo_type_str,
190
+ revision=revision,
191
+ allow_patterns=allow_patterns,
192
+ ignore_patterns=ignore_patterns,
193
+ force_download=force_download,
194
+ cache_dir=cache_dir,
195
+ token=token,
196
+ local_dir=local_dir,
197
+ library_name="huggingface-cli",
198
+ max_workers=max_workers,
199
+ dry_run=dry_run,
200
+ )
201
+
202
+ def _print_result(result: str | DryRunFileInfo | list[DryRunFileInfo]) -> None:
203
+ if isinstance(result, str):
204
+ out.result("Downloaded", path=result)
205
+ return
206
+
207
+ # Print dry run info
208
+ if isinstance(result, DryRunFileInfo):
209
+ result = [result]
210
+ will_download = [r for r in result if r.will_download]
211
+ out.text(
212
+ f"[dry-run] Will download {len(will_download)} files"
213
+ f" (out of {len(result)})"
214
+ f" totalling {_format_size(sum(r.file_size for r in will_download))}."
215
+ )
216
+ items = [
217
+ {
218
+ "file": info.filename,
219
+ "size": _format_size(info.file_size) if info.will_download else "-",
220
+ }
221
+ for info in sorted(result, key=lambda x: x.filename)
222
+ ]
223
+ out.table(items)
224
+
225
+ _print_result(run_download())
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/extensions.py ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains helper utilities for hf CLI extensions."""
15
+
16
+ import errno
17
+ import json
18
+ import os
19
+ import re
20
+ import shutil
21
+ import subprocess
22
+ import venv
23
+ from dataclasses import asdict, dataclass
24
+ from datetime import datetime, timezone
25
+ from enum import Enum
26
+ from pathlib import Path
27
+ from typing import Annotated, Literal
28
+
29
+ import click
30
+
31
+ from huggingface_hub.errors import CLIError, CLIExtensionInstallError, ConfirmationError
32
+ from huggingface_hub.utils import get_session, logging
33
+
34
+ from ._cli_utils import typer_factory
35
+ from ._framework import Argument, Option
36
+ from ._output import out
37
+
38
+
39
+ DEFAULT_EXTENSION_OWNER = "huggingface"
40
+ EXTENSIONS_ROOT = Path("~/.local/share/hf/extensions")
41
+ MANIFEST_FILENAME = "manifest.json"
42
+ EXTENSIONS_HELP = (
43
+ "Manage hf CLI extensions.\n\n"
44
+ "Security Warning: extensions are third-party executables or Python packages. "
45
+ "Install only from sources you trust."
46
+ )
47
+ extensions_cli = typer_factory(help=EXTENSIONS_HELP)
48
+ _EXTENSIONS_GITHUB_TOPIC = "hf-extension"
49
+ _EXTENSIONS_DOWNLOAD_TIMEOUT = 10
50
+ _EXTENSIONS_PIP_INSTALL_TIMEOUT = 300
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ class _ExtensionUpdateStatus(str, Enum):
56
+ UPDATED = "updated"
57
+ UP_TO_DATE = "up_to_date"
58
+ SKIPPED = "skipped"
59
+
60
+
61
+ @dataclass
62
+ class ExtensionManifest:
63
+ owner: str
64
+ repo: str
65
+ repo_id: str
66
+ short_name: str
67
+ executable_path: str
68
+ type: Literal["binary", "python"]
69
+ installed_at: datetime
70
+ description: str | None = None
71
+ commit_sha: str | None = None
72
+
73
+ @classmethod
74
+ def load(cls, path: Path) -> "ExtensionManifest":
75
+ manifest_path = path / MANIFEST_FILENAME
76
+ if not manifest_path.is_file():
77
+ raise CLIError(f"Manifest file not found at {manifest_path}. Your extension may be corrupted.")
78
+ data = json.loads(manifest_path.read_text())
79
+ # Ignore keys not in the dataclass (e.g. fields dropped since the manifest was written).
80
+ data = {key: value for key, value in data.items() if key in cls.__dataclass_fields__}
81
+ data["installed_at"] = datetime.fromisoformat(data["installed_at"])
82
+ return ExtensionManifest(**data)
83
+
84
+ def save(self, path: Path) -> None:
85
+ manifest_path = path / MANIFEST_FILENAME
86
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
87
+ data = asdict(self)
88
+ data["installed_at"] = self.installed_at.isoformat()
89
+ manifest_path.write_text(json.dumps(data, indent=2, sort_keys=True))
90
+
91
+
92
+ @extensions_cli.command(
93
+ "install",
94
+ examples=[
95
+ "hf extensions install hf-claude",
96
+ "hf extensions install hanouticelina/hf-claude",
97
+ "hf extensions install alvarobartt/hf-mem",
98
+ ],
99
+ )
100
+ def extension_install(
101
+ ctx: click.Context,
102
+ repo_id: Annotated[
103
+ str,
104
+ Argument(help="GitHub extension repository in `[OWNER/]hf-<name>` format."),
105
+ ],
106
+ force: Annotated[bool, Option("--force", help="Overwrite if already installed.")] = False,
107
+ ) -> None:
108
+ """Install an extension from a public GitHub repository.
109
+
110
+ Security warning: this installs a third-party executable or Python package.
111
+ Install only from sources you trust.
112
+ """
113
+ owner, repo_name, short_name = _normalize_repo_id(repo_id)
114
+ root_ctx = ctx.find_root()
115
+ reserved_commands = set(getattr(root_ctx.command, "commands", {}).keys())
116
+ if short_name in reserved_commands:
117
+ raise CLIError(
118
+ f"Cannot install extension '{short_name}' because it conflicts with an existing `hf {short_name}` command."
119
+ )
120
+
121
+ extension_dir = _get_extension_dir(short_name)
122
+ if extension_dir.exists() and not force:
123
+ raise CLIError(f"Extension '{short_name}' is already installed. Use --force to overwrite.")
124
+
125
+ branch, description = _fetch_github_repo_info(owner=owner, repo_name=repo_name)
126
+ if extension_dir.exists():
127
+ # --force reinstall: only remove the previous install once the repo metadata is resolved.
128
+ shutil.rmtree(extension_dir)
129
+ manifest = _install_extension(
130
+ owner=owner, repo_name=repo_name, short_name=short_name, branch=branch, description=description
131
+ )
132
+ ext_type = manifest.type.capitalize()
133
+ out.result(
134
+ f"{ext_type} extension installed",
135
+ source=f"{owner}/{repo_name}",
136
+ command=f"hf {short_name}",
137
+ )
138
+ out.hint(f"Run it with: hf {short_name}")
139
+
140
+
141
+ @extensions_cli.command(
142
+ "update",
143
+ examples=[
144
+ "hf extensions update",
145
+ "hf extensions update hf-claude",
146
+ "hf extensions update alvarobartt/hf-mem",
147
+ ],
148
+ )
149
+ def extension_update(
150
+ name: Annotated[
151
+ str | None,
152
+ Argument(
153
+ help=(
154
+ "Extension to update (with or without `hf-` prefix, optionally as `OWNER/hf-<name>`). "
155
+ "If omitted, all installed extensions are checked and the outdated ones are updated."
156
+ ),
157
+ ),
158
+ ] = None,
159
+ ) -> None:
160
+ """Update installed extension(s) to their latest version."""
161
+ if name is not None:
162
+ manifest = _load_installed_extension_for_update(name)
163
+ update_status = _update_installed_extension(manifest)
164
+ match update_status:
165
+ case _ExtensionUpdateStatus.UPDATED:
166
+ out.result("Extension updated", name=manifest.short_name, source=manifest.repo_id)
167
+ case _ExtensionUpdateStatus.UP_TO_DATE:
168
+ out.result(f"Extension '{manifest.short_name}' is already up to date", name=manifest.short_name)
169
+ case _ExtensionUpdateStatus.SKIPPED:
170
+ pass # warning already emitted by _update_installed_extension
171
+ return
172
+
173
+ manifests = _list_installed_extensions()
174
+ if not manifests:
175
+ out.warning("No extensions installed.")
176
+ out.hint("Install one with: hf extensions install <repo_id>")
177
+ return
178
+
179
+ updated = []
180
+ up_to_date = []
181
+ for manifest in manifests:
182
+ out.log(f"Checking '{manifest.short_name}' ({manifest.repo_id})...")
183
+ try:
184
+ update_status = _update_installed_extension(manifest)
185
+ except Exception as error:
186
+ # Keep updating the other extensions even if one fails.
187
+ out.warning(f"Could not update '{manifest.short_name}' ({manifest.repo_id}): {error}. Skipping.")
188
+ continue
189
+ match update_status:
190
+ case _ExtensionUpdateStatus.UPDATED:
191
+ updated.append(manifest.short_name)
192
+ case _ExtensionUpdateStatus.UP_TO_DATE:
193
+ up_to_date.append(manifest.short_name)
194
+ case _ExtensionUpdateStatus.SKIPPED:
195
+ pass # warning already emitted by _update_installed_extension
196
+ out.result(
197
+ "Extensions update complete",
198
+ updated=", ".join(updated) if updated else None,
199
+ up_to_date=", ".join(up_to_date) if up_to_date else None,
200
+ )
201
+
202
+
203
+ @extensions_cli.command(
204
+ "exec",
205
+ context_settings={"allow_extra_args": True, "allow_interspersed_args": False, "ignore_unknown_options": True},
206
+ examples=[
207
+ "hf extensions exec claude -- --help",
208
+ "hf extensions exec claude --model zai-org/GLM-5",
209
+ ],
210
+ )
211
+ def extension_exec(
212
+ ctx: click.Context,
213
+ name: Annotated[
214
+ str,
215
+ Argument(help="Extension name (with or without `hf-` prefix)."),
216
+ ],
217
+ ) -> None:
218
+ """Execute an installed extension."""
219
+ short_name = _normalize_extension_name(name)
220
+ executable_path = _resolve_installed_executable_path(short_name)
221
+
222
+ if not executable_path.is_file():
223
+ raise CLIError(f"Extension '{short_name}' is not installed.")
224
+
225
+ exit_code = _execute_extension_binary(executable_path=executable_path, args=list(ctx.args))
226
+ raise click.exceptions.Exit(code=exit_code)
227
+
228
+
229
+ @extensions_cli.command("list | ls", examples=["hf extensions list"])
230
+ def extension_list() -> None:
231
+ """List installed extension commands."""
232
+ rows = [
233
+ {
234
+ "command": f"hf {manifest.short_name}",
235
+ "source": str(manifest.repo_id),
236
+ "type": str(manifest.type),
237
+ "installed": manifest.installed_at.strftime("%Y-%m-%d"),
238
+ "description": manifest.description,
239
+ }
240
+ for manifest in _list_installed_extensions()
241
+ ]
242
+ out.table(rows, id_key="command")
243
+
244
+
245
+ @extensions_cli.command("search", examples=["hf extensions search"])
246
+ def extension_search() -> None:
247
+ """Search extensions available on GitHub (tagged with 'hf-extension' topic)."""
248
+ response = _github_get(
249
+ "https://api.github.com/search/repositories",
250
+ params={"q": f"topic:{_EXTENSIONS_GITHUB_TOPIC}", "sort": "stars", "order": "desc", "per_page": 100},
251
+ )
252
+ data = response.json()
253
+
254
+ installed = {m.short_name for m in _list_installed_extensions()}
255
+
256
+ rows = []
257
+ for repo in data.get("items", []):
258
+ short_name = repo["name"].removeprefix("hf-")
259
+ rows.append(
260
+ {
261
+ "name": short_name,
262
+ "repo": repo["full_name"],
263
+ "stars": repo.get("stargazers_count", 0),
264
+ "description": repo.get("description") or "",
265
+ "installed": "yes" if short_name in installed else "",
266
+ }
267
+ )
268
+
269
+ out.table(rows, id_key="repo")
270
+
271
+
272
+ @extensions_cli.command("remove | rm", examples=["hf extensions remove claude"])
273
+ def extension_remove(
274
+ name: Annotated[
275
+ str,
276
+ Argument(help="Extension name to remove (with or without `hf-` prefix)."),
277
+ ],
278
+ ) -> None:
279
+ """Remove an installed extension."""
280
+ short_name = _normalize_extension_name(name)
281
+ extension_dir = _get_extension_dir(short_name)
282
+
283
+ if not extension_dir.is_dir():
284
+ raise CLIError(f"Extension '{short_name}' is not installed.")
285
+
286
+ shutil.rmtree(extension_dir)
287
+ out.result("Extension removed", name=short_name)
288
+
289
+
290
+ ### HELPER FUNCTIONS
291
+
292
+
293
+ def _list_installed_extensions() -> list[ExtensionManifest]:
294
+ """Return manifests for all validly-installed extensions, sorted by directory name."""
295
+ root_dir = EXTENSIONS_ROOT.expanduser()
296
+ if not root_dir.is_dir():
297
+ return []
298
+ manifests = []
299
+ for extension_dir in sorted(root_dir.iterdir()):
300
+ if not extension_dir.is_dir() or not extension_dir.name.startswith("hf-"):
301
+ continue
302
+ try:
303
+ manifests.append(ExtensionManifest.load(extension_dir))
304
+ except Exception as e:
305
+ logger.debug(f"Failed to load manifest for extension '{extension_dir.name}': {e}")
306
+ continue
307
+ return manifests
308
+
309
+
310
+ def list_installed_extensions_for_help() -> list[tuple[str, str]]:
311
+ entries = []
312
+ for manifest in _list_installed_extensions():
313
+ tag = f"[extension {manifest.repo_id}]"
314
+ help_text = f"{manifest.description} {tag}" if manifest.description is not None else tag
315
+ entries.append((manifest.short_name, help_text))
316
+ return entries
317
+
318
+
319
+ def dispatch_unknown_top_level_extension(args: list[str], known_commands: set[str]) -> int | None:
320
+ if not args:
321
+ return None
322
+
323
+ command_name = args[0]
324
+ if command_name.startswith("-"):
325
+ return None
326
+ all_known = {a.strip() for cmd in known_commands for a in cmd.split("|")}
327
+ if command_name in all_known:
328
+ return None
329
+
330
+ try:
331
+ short_name = _validate_extension_short_name(command_name.removeprefix("hf-"), original_input=command_name)
332
+ except CLIError:
333
+ return None
334
+
335
+ executable_path: Path | None
336
+ try:
337
+ executable_path = _resolve_installed_executable_path(short_name)
338
+ except Exception:
339
+ executable_path = _auto_install_official_extension(short_name)
340
+
341
+ if executable_path is None or not executable_path.is_file():
342
+ return None
343
+
344
+ return _execute_extension_binary(executable_path=executable_path, args=list(args[1:]))
345
+
346
+
347
+ def _auto_install_official_extension(short_name: str) -> Path | None:
348
+ """Try to auto-install huggingface/hf-<name>. Returns executable path or None."""
349
+ owner, repo_name = DEFAULT_EXTENSION_OWNER, f"hf-{short_name}"
350
+ if _get_extension_dir(short_name).exists():
351
+ return None
352
+
353
+ try:
354
+ branch, description = _fetch_github_repo_info(owner=owner, repo_name=repo_name)
355
+ except Exception:
356
+ return None
357
+
358
+ try:
359
+ out.confirm(f"'{short_name}' is an official Hugging Face extension ({owner}/{repo_name}). Install it?")
360
+ except ConfirmationError:
361
+ return None
362
+ try:
363
+ manifest = _install_extension(
364
+ owner=owner, repo_name=repo_name, short_name=short_name, branch=branch, description=description
365
+ )
366
+ return Path(manifest.executable_path).expanduser()
367
+ except Exception:
368
+ return None
369
+
370
+
371
+ def _load_installed_extension_for_update(name: str) -> ExtensionManifest:
372
+ short_name = _normalize_extension_name(name)
373
+ extension_dir = _get_extension_dir(short_name)
374
+ if not extension_dir.is_dir():
375
+ owner, _, _ = name.strip().rpartition("/")
376
+ install_target = f"{owner}/hf-{short_name}" if owner else f"hf-{short_name}"
377
+ raise CLIError(
378
+ f"Extension '{short_name}' is not installed. Install it first with: hf extensions install {install_target}"
379
+ )
380
+ return ExtensionManifest.load(extension_dir)
381
+
382
+
383
+ def _update_installed_extension(manifest: ExtensionManifest) -> _ExtensionUpdateStatus:
384
+ owner, repo_name, short_name = manifest.owner, manifest.repo, manifest.short_name
385
+
386
+ try:
387
+ branch, description = _fetch_github_repo_info(owner=owner, repo_name=repo_name)
388
+ except Exception as error:
389
+ out.warning(f"Could not check updates for '{short_name}' ({owner}/{repo_name}): {error}. Skipping.")
390
+ return _ExtensionUpdateStatus.SKIPPED
391
+
392
+ latest_sha = _fetch_latest_commit_sha(owner=owner, repo_name=repo_name, branch=branch, warn=False)
393
+ if latest_sha is None:
394
+ out.warning(
395
+ f"Could not check updates for '{short_name}' ({owner}/{repo_name}): GitHub is unreachable. Skipping."
396
+ )
397
+ return _ExtensionUpdateStatus.SKIPPED
398
+
399
+ if latest_sha == manifest.commit_sha:
400
+ return _ExtensionUpdateStatus.UP_TO_DATE
401
+
402
+ _install_extension(
403
+ owner=owner,
404
+ repo_name=repo_name,
405
+ short_name=short_name,
406
+ branch=branch,
407
+ description=description,
408
+ commit_sha=latest_sha,
409
+ )
410
+ return _ExtensionUpdateStatus.UPDATED
411
+
412
+
413
+ def _install_extension(
414
+ *,
415
+ owner: str,
416
+ repo_name: str,
417
+ short_name: str,
418
+ branch: str,
419
+ description: str | None = None,
420
+ commit_sha: str | None = None,
421
+ ) -> ExtensionManifest:
422
+ """Fetch and install an extension (binary or Python package), then persist its manifest.
423
+
424
+ Installs in place: an existing install is overwritten without being removed first, so a failed
425
+ update keeps the previous version working. A failed fresh install is cleaned up entirely.
426
+ """
427
+ extension_dir = _get_extension_dir(short_name)
428
+ fresh_install = not extension_dir.exists()
429
+ installed = False
430
+ try:
431
+ try:
432
+ binary = _fetch_remote_binary(owner=owner, repo_name=repo_name, branch=branch, short_name=short_name)
433
+ except Exception:
434
+ binary = None
435
+
436
+ if binary is not None:
437
+ executable_path = _install_binary_extension(
438
+ extension_dir=extension_dir, short_name=short_name, binary=binary
439
+ )
440
+ else:
441
+ executable_path = _install_python_extension(
442
+ extension_dir=extension_dir, owner=owner, repo_name=repo_name, short_name=short_name, branch=branch
443
+ )
444
+
445
+ manifest = ExtensionManifest(
446
+ owner=owner,
447
+ repo=repo_name,
448
+ repo_id=f"{owner}/{repo_name}",
449
+ short_name=short_name,
450
+ executable_path=str(executable_path),
451
+ type="binary" if binary is not None else "python",
452
+ installed_at=datetime.now(timezone.utc),
453
+ description=_try_fetch_remote_description(
454
+ owner=owner, repo_name=repo_name, branch=branch, candidate_description=description
455
+ ),
456
+ commit_sha=commit_sha or _fetch_latest_commit_sha(owner=owner, repo_name=repo_name, branch=branch),
457
+ )
458
+ manifest.save(extension_dir)
459
+ installed = True
460
+ return manifest
461
+ except CLIError:
462
+ raise
463
+ except subprocess.TimeoutExpired as e:
464
+ raise CLIExtensionInstallError(
465
+ f"Pip install timed out after {_EXTENSIONS_PIP_INSTALL_TIMEOUT}s for '{owner}/{repo_name}'. "
466
+ "See pip output above for details."
467
+ ) from e
468
+ except subprocess.CalledProcessError as e:
469
+ raise CLIExtensionInstallError(
470
+ f"Failed to install pip package from '{owner}/{repo_name}' (exit code {e.returncode}). "
471
+ "See pip output above for details."
472
+ ) from e
473
+ except Exception as e:
474
+ raise CLIExtensionInstallError(f"Failed to install extension from '{owner}/{repo_name}': {e}") from e
475
+ finally:
476
+ if not installed and fresh_install:
477
+ shutil.rmtree(extension_dir, ignore_errors=True)
478
+
479
+
480
+ def _fetch_latest_commit_sha(*, owner: str, repo_name: str, branch: str, warn: bool = True) -> str | None:
481
+ """Best-effort fetch of the latest commit SHA for a branch, used to detect available updates."""
482
+ try:
483
+ response = _github_get(
484
+ f"https://api.github.com/repos/{owner}/{repo_name}/commits/{branch}",
485
+ headers={"Accept": "application/vnd.github.sha"},
486
+ )
487
+ return response.text.strip() or None
488
+ except Exception as error:
489
+ if warn:
490
+ out.warning(f"Could not fetch latest commit SHA for '{repo_name}' ({owner}/{repo_name}): {error}")
491
+ return None
492
+
493
+
494
+ def _fetch_remote_binary(*, owner: str, repo_name: str, branch: str, short_name: str) -> bytes:
495
+ executable_name = _get_executable_name(short_name)
496
+ raw_url = f"https://raw.githubusercontent.com/{owner}/{repo_name}/refs/heads/{branch}/{executable_name}"
497
+ response = _github_get(raw_url)
498
+ return response.content
499
+
500
+
501
+ def _install_binary_extension(*, extension_dir: Path, short_name: str, binary: bytes) -> Path:
502
+ extension_dir.mkdir(parents=True, exist_ok=True)
503
+ executable_path = extension_dir / _get_executable_name(short_name)
504
+ executable_path.write_bytes(binary)
505
+
506
+ if os.name != "nt":
507
+ os.chmod(executable_path, 0o755)
508
+
509
+ return executable_path
510
+
511
+
512
+ def _install_python_extension(
513
+ *, extension_dir: Path, owner: str, repo_name: str, short_name: str, branch: str
514
+ ) -> Path:
515
+ source_url = f"https://github.com/{owner}/{repo_name}/archive/refs/heads/{branch}.zip"
516
+ venv_dir = extension_dir / "venv"
517
+ venv_python = _get_venv_bin_path(venv_dir, "python.exe" if os.name == "nt" else "python")
518
+ uv_path = shutil.which("uv")
519
+
520
+ status = out.status()
521
+ if not venv_python.is_file():
522
+ status.update(f"Creating virtual environment in {venv_dir}")
523
+ extension_dir.mkdir(parents=True, exist_ok=True)
524
+ if uv_path:
525
+ subprocess.run([uv_path, "venv", str(venv_dir)], check=True)
526
+ else:
527
+ venv.EnvBuilder(with_pip=True).create(str(venv_dir))
528
+ status.done(f"Virtual environment created in {venv_dir}")
529
+
530
+ status.update(f"Installing package from {source_url}")
531
+ if uv_path:
532
+ # --reinstall: the source URL is the same for every commit, so cached data must be refreshed.
533
+ install_cmd = [uv_path, "pip", "install", "--reinstall", "--python", str(venv_python), source_url]
534
+ else:
535
+ install_cmd = [
536
+ str(venv_python),
537
+ "-m",
538
+ "pip",
539
+ "install",
540
+ "--disable-pip-version-check",
541
+ "--no-input",
542
+ "--force-reinstall",
543
+ source_url,
544
+ ]
545
+ subprocess.run(install_cmd, check=True, timeout=_EXTENSIONS_PIP_INSTALL_TIMEOUT)
546
+ status.done(f"Package installed from {source_url}")
547
+
548
+ executable_name = _get_executable_name(short_name)
549
+ venv_executable = _get_venv_bin_path(venv_dir, executable_name)
550
+ if not venv_executable.is_file():
551
+ raise CLIError(
552
+ f"Installed package from '{owner}/{repo_name}' does not expose the required console script "
553
+ f"'{executable_name}'."
554
+ )
555
+ return venv_executable.resolve()
556
+
557
+
558
+ def _try_fetch_remote_description(
559
+ owner: str, repo_name: str, branch: str, candidate_description: str | None
560
+ ) -> str | None:
561
+ """Try to fetch project description either from:
562
+ - manifest.json
563
+ - pyproject.toml
564
+
565
+ Only best effort, no error handling.
566
+ """
567
+ base = f"https://raw.githubusercontent.com/{owner}/{repo_name}/refs/heads/{branch}"
568
+
569
+ # from manifest.json
570
+ try:
571
+ response = _github_get(f"{base}/{MANIFEST_FILENAME}")
572
+ description = response.json().get("description")
573
+ if isinstance(description, str):
574
+ return description
575
+ except Exception:
576
+ pass
577
+
578
+ # from pyproject.toml
579
+ try:
580
+ response = _github_get(f"{base}/pyproject.toml")
581
+
582
+ # Weak parser but ok for "best effort"
583
+ for line in response.text.splitlines():
584
+ line = line.strip()
585
+ if line.startswith("description"):
586
+ _, _, value = line.partition("=")
587
+ return value.strip().strip("\"'")
588
+ except Exception:
589
+ pass
590
+
591
+ # fallback to value fetched from GH API directly
592
+ return candidate_description
593
+
594
+
595
+ def _get_extension_dir(short_name: str) -> Path:
596
+ # Callers validate at the parse boundary already; re-validate here as defense-in-depth since
597
+ # this path is rmtree'd on removal.
598
+ _validate_extension_short_name(short_name, original_input=short_name)
599
+ return EXTENSIONS_ROOT.expanduser() / f"hf-{short_name}"
600
+
601
+
602
+ def _github_get(url: str, *, params: dict | None = None, headers: dict | None = None):
603
+ """Perform a GitHub GET request.
604
+
605
+ Shared by every GitHub/Raw fetch in this module so the timeout and redirect policy are shared.
606
+ """
607
+ response = get_session().get(
608
+ url,
609
+ params=params,
610
+ headers=headers,
611
+ follow_redirects=True,
612
+ timeout=_EXTENSIONS_DOWNLOAD_TIMEOUT,
613
+ )
614
+ response.raise_for_status()
615
+ return response
616
+
617
+
618
+ def _fetch_github_repo_info(*, owner: str, repo_name: str) -> tuple[str, str | None]:
619
+ """Fetch `default_branch` + `description` for a GitHub repo from `GET /repos/{owner}/{repo}`."""
620
+ response = _github_get(f"https://api.github.com/repos/{owner}/{repo_name}")
621
+ data = response.json()
622
+ return data["default_branch"], data.get("description")
623
+
624
+
625
+ def _get_executable_name(short_name: str) -> str:
626
+ name = f"hf-{short_name}"
627
+ if os.name == "nt":
628
+ name += ".exe"
629
+ return name
630
+
631
+
632
+ def _resolve_installed_executable_path(short_name: str) -> Path:
633
+ extension_dir = _get_extension_dir(short_name)
634
+ manifest = ExtensionManifest.load(extension_dir)
635
+ return Path(manifest.executable_path).expanduser()
636
+
637
+
638
+ def _get_venv_bin_path(venv_dir: Path, executable_name: str) -> Path:
639
+ if os.name == "nt":
640
+ return venv_dir / "Scripts" / executable_name
641
+ return venv_dir / "bin" / executable_name
642
+
643
+
644
+ _ALLOWED_EXTENSION_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
645
+
646
+
647
+ def _validate_extension_short_name(short_name: str, *, original_input: str) -> str:
648
+ name = short_name.strip()
649
+ if not name:
650
+ raise CLIError("Extension name cannot be empty.")
651
+ if any(sep in name for sep in ("/", "\\")):
652
+ raise CLIError(f"Invalid extension name '{original_input}'.")
653
+ if ".." in name or ":" in name:
654
+ raise CLIError(f"Invalid extension name '{original_input}'.")
655
+ if not _ALLOWED_EXTENSION_NAME.fullmatch(name):
656
+ raise CLIError(
657
+ f"Invalid extension name '{original_input}'. Allowed characters: letters, digits, '.', '_' and '-'."
658
+ )
659
+ return name
660
+
661
+
662
+ def _normalize_repo_id(repo_id: str) -> tuple[str, str, str]:
663
+ if "://" in repo_id:
664
+ raise CLIError("Only GitHub repositories in `[OWNER/]hf-<name>` format are supported.")
665
+
666
+ parts = repo_id.split("/")
667
+ if len(parts) == 1:
668
+ owner = DEFAULT_EXTENSION_OWNER
669
+ repo_name = parts[0]
670
+ elif len(parts) == 2 and all(parts):
671
+ owner, repo_name = parts
672
+ else:
673
+ raise CLIError(f"Expected `[OWNER/]REPO` format, got '{repo_id}'.")
674
+
675
+ if not repo_name.startswith("hf-"):
676
+ raise CLIError(f"Extension repository name must start with 'hf-', got '{repo_name}'.")
677
+
678
+ short_name = repo_name.removeprefix("hf-")
679
+ if not short_name:
680
+ raise CLIError("Invalid extension repository name 'hf-'.")
681
+ _validate_extension_short_name(short_name, original_input=repo_id)
682
+
683
+ return owner, repo_name, short_name
684
+
685
+
686
+ def _normalize_extension_name(name: str) -> str:
687
+ repo_name = name.strip().rsplit("/", 1)[-1]
688
+ return _validate_extension_short_name(repo_name.removeprefix("hf-"), original_input=name)
689
+
690
+
691
+ def _execute_extension_binary(executable_path: Path, args: list[str]) -> int:
692
+ try:
693
+ return subprocess.call([str(executable_path)] + args)
694
+ except OSError as e:
695
+ if os.name == "nt" or e.errno != errno.ENOEXEC:
696
+ raise
697
+ return subprocess.call(["sh", str(executable_path)] + args)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/hf.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import sys
17
+ import traceback
18
+ from typing import Annotated
19
+
20
+ import click
21
+
22
+ from huggingface_hub import __version__, constants
23
+ from huggingface_hub.cli._cli_utils import check_cli_update, fallback_typer_group_factory, typer_factory
24
+ from huggingface_hub.cli._cp import CP_EXAMPLES, make_cp
25
+ from huggingface_hub.cli._errors import format_known_exception
26
+ from huggingface_hub.cli._output import out
27
+ from huggingface_hub.cli.auth import auth_cli
28
+ from huggingface_hub.cli.buckets import buckets_cli, sync
29
+ from huggingface_hub.cli.cache import cache_cli
30
+ from huggingface_hub.cli.collections import collections_cli
31
+ from huggingface_hub.cli.datasets import datasets_cli
32
+ from huggingface_hub.cli.discussions import discussions_cli
33
+ from huggingface_hub.cli.download import DOWNLOAD_EXAMPLES, download
34
+ from huggingface_hub.cli.extensions import (
35
+ dispatch_unknown_top_level_extension,
36
+ extensions_cli,
37
+ list_installed_extensions_for_help,
38
+ )
39
+ from huggingface_hub.cli.inference_endpoints import ie_cli
40
+ from huggingface_hub.cli.jobs import jobs_cli
41
+ from huggingface_hub.cli.lfs import lfs_enable_largefiles, lfs_multipart_upload
42
+ from huggingface_hub.cli.models import models_cli
43
+ from huggingface_hub.cli.papers import papers_cli
44
+ from huggingface_hub.cli.repo_files import repo_files_cli
45
+ from huggingface_hub.cli.repos import repos_cli
46
+ from huggingface_hub.cli.sandbox import sandbox_cli
47
+ from huggingface_hub.cli.skills import skills_cli
48
+ from huggingface_hub.cli.spaces import spaces_cli
49
+ from huggingface_hub.cli.system import env, update, version
50
+ from huggingface_hub.cli.upload import UPLOAD_EXAMPLES, upload
51
+ from huggingface_hub.cli.upload_large_folder import UPLOAD_LARGE_FOLDER_EXAMPLES, upload_large_folder
52
+ from huggingface_hub.cli.webhooks import webhooks_cli
53
+ from huggingface_hub.utils import logging
54
+
55
+ from ._completion import _COMPLETE_VAR, InstallCompletionOpt, ShowCompletionOpt
56
+ from ._framework import Option
57
+
58
+
59
+ app = typer_factory(
60
+ help="Hugging Face Hub CLI",
61
+ cls=fallback_typer_group_factory(
62
+ dispatch_unknown_top_level_extension,
63
+ extra_commands_provider=list_installed_extensions_for_help,
64
+ ),
65
+ )
66
+
67
+
68
+ def _version_callback(value: bool) -> None:
69
+ if value:
70
+ print(__version__)
71
+ raise click.exceptions.Exit()
72
+
73
+
74
+ @app.group_callback(invoke_without_command=True)
75
+ def app_callback(
76
+ version: Annotated[
77
+ bool | None, Option("-v", "--version", callback=_version_callback, is_eager=True, hidden=True)
78
+ ] = None,
79
+ install_completion: InstallCompletionOpt = False,
80
+ show_completion: ShowCompletionOpt = False,
81
+ ) -> None:
82
+ pass
83
+
84
+
85
+ # top level single commands (defined in their respective files)
86
+ app.command(examples=CP_EXAMPLES)(make_cp())
87
+ app.command()(sync)
88
+ app.command(examples=DOWNLOAD_EXAMPLES)(download)
89
+ app.command(examples=UPLOAD_EXAMPLES)(upload)
90
+ app.command(examples=UPLOAD_LARGE_FOLDER_EXAMPLES)(upload_large_folder)
91
+
92
+ app.command(topic="help")(env)
93
+ app.command(topic="help")(update)
94
+ app.command(topic="help")(version)
95
+
96
+ app.command(hidden=True)(lfs_enable_largefiles)
97
+ app.command(hidden=True)(lfs_multipart_upload)
98
+
99
+ # command groups
100
+ app.add_group(auth_cli, name="auth")
101
+ app.add_group(buckets_cli, name="buckets")
102
+ app.add_group(cache_cli, name="cache")
103
+ app.add_group(collections_cli, name="collections")
104
+ app.add_group(datasets_cli, name="datasets")
105
+ app.add_group(discussions_cli, name="discussions")
106
+ app.add_group(jobs_cli, name="jobs")
107
+ app.add_group(models_cli, name="models")
108
+ app.add_group(papers_cli, name="papers")
109
+ app.add_group(repos_cli, name="repos | repo")
110
+ app.add_group(repo_files_cli, name="repo-files", hidden=True)
111
+ app.add_group(sandbox_cli, name="sandbox")
112
+ app.add_group(skills_cli, name="skills")
113
+ app.add_group(spaces_cli, name="spaces")
114
+ app.add_group(webhooks_cli, name="webhooks")
115
+ app.add_group(ie_cli, name="endpoints")
116
+ app.add_group(extensions_cli, name="extensions | ext")
117
+
118
+
119
+ def main():
120
+ # Shell-completion requests must stay fast and emit nothing but candidates:
121
+ # skip the startup work and let click handle the env var inside `app()`.
122
+ if _COMPLETE_VAR not in os.environ:
123
+ if not constants.HF_DEBUG:
124
+ logging.set_verbosity_info()
125
+ check_cli_update("huggingface_hub")
126
+
127
+ try:
128
+ app()
129
+ except Exception as e:
130
+ message = format_known_exception(e)
131
+ if message:
132
+ out.error(message)
133
+ if constants.HF_DEBUG:
134
+ traceback.print_exc()
135
+ else:
136
+ out.hint("set HF_DEBUG=1 as environment variable for full traceback.")
137
+ sys.exit(1)
138
+ raise
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/inference_endpoints.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI commands for Hugging Face Inference Endpoints."""
2
+
3
+ import shlex
4
+ from typing import Annotated
5
+
6
+ import click
7
+
8
+ from huggingface_hub._inference_endpoints import InferenceEndpointScalingMetric, InferenceEndpointType
9
+ from huggingface_hub.errors import CLIError, HfHubHTTPError
10
+
11
+ from ._cli_utils import (
12
+ EnvFileOpt,
13
+ EnvOpt,
14
+ RevisionOpt,
15
+ SecretsFileOpt,
16
+ SecretsOpt,
17
+ SoftChoice,
18
+ TokenOpt,
19
+ get_hf_api,
20
+ parse_env_map,
21
+ typer_factory,
22
+ )
23
+ from ._framework import Argument, Option
24
+ from ._output import out
25
+
26
+
27
+ ie_cli = typer_factory(help="Manage Hugging Face Inference Endpoints.")
28
+
29
+ catalog_app = typer_factory(help="Interact with the Inference Endpoints catalog.")
30
+
31
+
32
+ NameArg = Annotated[
33
+ str,
34
+ Argument(help="Endpoint name."),
35
+ ]
36
+ NameOpt = Annotated[
37
+ str | None,
38
+ Option(help="Endpoint name."),
39
+ ]
40
+
41
+ NamespaceOpt = Annotated[
42
+ str | None,
43
+ Option(
44
+ help="The namespace associated with the Inference Endpoint. Defaults to the current user's namespace.",
45
+ ),
46
+ ]
47
+
48
+
49
+ @ie_cli.command("list | ls", examples=["hf endpoints ls", "hf endpoints ls --namespace my-org"])
50
+ def ls(
51
+ namespace: NamespaceOpt = None,
52
+ token: TokenOpt = None,
53
+ ) -> None:
54
+ """Lists all Inference Endpoints for the given namespace."""
55
+ api = get_hf_api(token=token)
56
+ try:
57
+ endpoints = api.list_inference_endpoints(namespace=namespace, token=token)
58
+ except HfHubHTTPError as error:
59
+ out.error(f"Listing failed: {error}")
60
+ raise click.exceptions.Exit(code=error.response.status_code) from error
61
+
62
+ results = []
63
+ for endpoint in endpoints:
64
+ raw = endpoint.raw
65
+ status = raw.get("status", {})
66
+ model = raw.get("model", {})
67
+ compute = raw.get("compute", {})
68
+ provider = raw.get("provider", {})
69
+ results.append(
70
+ {
71
+ "name": raw.get("name", ""),
72
+ "model": model.get("repository", "") if isinstance(model, dict) else "",
73
+ "status": status.get("state", "") if isinstance(status, dict) else "",
74
+ "task": model.get("task", "") if isinstance(model, dict) else "",
75
+ "framework": model.get("framework", "") if isinstance(model, dict) else "",
76
+ "instance": compute.get("instanceType", "") if isinstance(compute, dict) else "",
77
+ "vendor": provider.get("vendor", "") if isinstance(provider, dict) else "",
78
+ "region": provider.get("region", "") if isinstance(provider, dict) else "",
79
+ }
80
+ )
81
+ out.table(results, id_key="name")
82
+
83
+
84
+ @ie_cli.command(name="deploy", examples=["hf endpoints deploy my-endpoint --repo gpt2 --framework pytorch ..."])
85
+ def deploy(
86
+ name: NameArg,
87
+ repo: Annotated[
88
+ str,
89
+ Option(
90
+ help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').",
91
+ ),
92
+ ],
93
+ framework: Annotated[
94
+ str,
95
+ Option(
96
+ help="The machine learning framework used for the model (e.g. 'vllm').",
97
+ ),
98
+ ],
99
+ accelerator: Annotated[
100
+ str,
101
+ Option(
102
+ help="The hardware accelerator to be used for inference (e.g. 'cpu').",
103
+ ),
104
+ ],
105
+ instance_size: Annotated[
106
+ str,
107
+ Option(
108
+ help="The size or type of the instance to be used for hosting the model (e.g. 'x4').",
109
+ ),
110
+ ],
111
+ instance_type: Annotated[
112
+ str,
113
+ Option(
114
+ help="The cloud instance type where the Inference Endpoint will be deployed (e.g. 'intel-icl').",
115
+ ),
116
+ ],
117
+ region: Annotated[
118
+ str,
119
+ Option(
120
+ help="The cloud region in which the Inference Endpoint will be created (e.g. 'us-east-1').",
121
+ ),
122
+ ],
123
+ vendor: Annotated[
124
+ str,
125
+ Option(
126
+ help="The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. 'aws').",
127
+ ),
128
+ ],
129
+ *,
130
+ namespace: NamespaceOpt = None,
131
+ task: Annotated[
132
+ str | None,
133
+ Option(
134
+ help="The task on which to deploy the model (e.g. 'text-classification').",
135
+ ),
136
+ ] = None,
137
+ token: TokenOpt = None,
138
+ min_replica: Annotated[
139
+ int,
140
+ Option(
141
+ help="The minimum number of replicas (instances) to keep running for the Inference Endpoint.",
142
+ ),
143
+ ] = 1,
144
+ max_replica: Annotated[
145
+ int,
146
+ Option(
147
+ help="The maximum number of replicas (instances) to scale to for the Inference Endpoint.",
148
+ ),
149
+ ] = 1,
150
+ scale_to_zero_timeout: Annotated[
151
+ int | None,
152
+ Option(
153
+ help="The duration in minutes before an inactive endpoint is scaled to zero.",
154
+ ),
155
+ ] = None,
156
+ scaling_metric: Annotated[
157
+ InferenceEndpointScalingMetric | None,
158
+ Option(
159
+ help="The metric reference for scaling.",
160
+ ),
161
+ ] = None,
162
+ scaling_threshold: Annotated[
163
+ float | None,
164
+ Option(
165
+ help="The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.",
166
+ ),
167
+ ] = None,
168
+ revision: RevisionOpt = None,
169
+ custom_image: Annotated[
170
+ str | None,
171
+ Option(
172
+ "--custom-image",
173
+ help="Docker image URL for a custom container (e.g. 'nexagi/sglang:v0.5.12'). Requires '--framework custom'.",
174
+ ),
175
+ ] = None,
176
+ health_route: Annotated[
177
+ str | None,
178
+ Option(
179
+ help="Health check route exposed by the custom container (e.g. '/health'). Requires --custom-image.",
180
+ ),
181
+ ] = None,
182
+ port: Annotated[
183
+ int | None,
184
+ Option(
185
+ help="Port the custom container listens on (e.g. 30000). Requires --custom-image.",
186
+ ),
187
+ ] = None,
188
+ container_command: Annotated[
189
+ str | None,
190
+ Option(
191
+ "--container-command",
192
+ help=(
193
+ "Override the container entrypoint, as a quoted string split into tokens "
194
+ '(e.g. "python -m sglang.launch_server"). Requires --custom-image.'
195
+ ),
196
+ ),
197
+ ] = None,
198
+ container_args: Annotated[
199
+ str | None,
200
+ Option(
201
+ "--container-args",
202
+ help=(
203
+ "Arguments appended to the container entrypoint, as a quoted string split into tokens "
204
+ '(e.g. "--tp 8 --reasoning-parser qwen3"). Requires --custom-image.'
205
+ ),
206
+ ),
207
+ ] = None,
208
+ env: EnvOpt = None,
209
+ env_file: EnvFileOpt = None,
210
+ secrets: SecretsOpt = None,
211
+ secrets_file: SecretsFileOpt = None,
212
+ endpoint_type: Annotated[
213
+ str | None,
214
+ Option(
215
+ "--type",
216
+ click_type=SoftChoice(InferenceEndpointType),
217
+ help="Endpoint access type. Defaults to 'authenticated' (token-gated, publicly reachable).",
218
+ ),
219
+ ] = None,
220
+ ) -> None:
221
+ """Deploy an Inference Endpoint from a Hub repository."""
222
+ # Custom-container knobs only make sense alongside a custom image.
223
+ if custom_image is None and (health_route is not None or port is not None or container_command or container_args):
224
+ raise CLIError("--health-route, --port, --container-command and --container-args require --custom-image.")
225
+ custom_image_dict: dict | None = None
226
+ if custom_image is not None:
227
+ custom_image_dict = {"url": custom_image}
228
+ if health_route is not None:
229
+ custom_image_dict["healthRoute"] = health_route
230
+ if port is not None:
231
+ custom_image_dict["port"] = port
232
+
233
+ env_map = {key: value or "" for key, value in parse_env_map(env, env_file).items()}
234
+ secrets_map = {key: value or "" for key, value in parse_env_map(secrets, secrets_file).items()}
235
+
236
+ # Only forward the values the user actually set and let `create_inference_endpoint` own the defaults.
237
+ params: dict = {}
238
+ if endpoint_type is not None:
239
+ params["type"] = endpoint_type
240
+ if custom_image_dict is not None:
241
+ params["custom_image"] = custom_image_dict
242
+ if container_command:
243
+ params["container_command"] = shlex.split(container_command)
244
+ if container_args:
245
+ params["container_args"] = shlex.split(container_args)
246
+ if env_map:
247
+ params["env"] = env_map
248
+ if secrets_map:
249
+ params["secrets"] = secrets_map
250
+
251
+ api = get_hf_api(token=token)
252
+ endpoint = api.create_inference_endpoint(
253
+ name=name,
254
+ repository=repo,
255
+ framework=framework,
256
+ accelerator=accelerator,
257
+ instance_size=instance_size,
258
+ instance_type=instance_type,
259
+ region=region,
260
+ vendor=vendor,
261
+ namespace=namespace,
262
+ task=task,
263
+ token=token,
264
+ min_replica=min_replica,
265
+ max_replica=max_replica,
266
+ scaling_metric=scaling_metric,
267
+ scaling_threshold=scaling_threshold,
268
+ scale_to_zero_timeout=scale_to_zero_timeout,
269
+ revision=revision,
270
+ **params,
271
+ )
272
+ out.dict(endpoint.raw)
273
+ out.hint(f"Use 'hf endpoints describe {name}' to check the deployment status.")
274
+
275
+
276
+ @catalog_app.command(name="deploy", examples=["hf endpoints catalog deploy --repo meta-llama/Llama-3.2-1B-Instruct"])
277
+ def deploy_from_catalog(
278
+ repo: Annotated[
279
+ str,
280
+ Option(
281
+ help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').",
282
+ ),
283
+ ],
284
+ name: NameOpt = None,
285
+ accelerator: Annotated[
286
+ str | None,
287
+ Option(
288
+ help="The hardware accelerator to be used for inference (e.g. 'cpu', 'gpu', 'neuron').",
289
+ ),
290
+ ] = None,
291
+ namespace: NamespaceOpt = None,
292
+ token: TokenOpt = None,
293
+ ) -> None:
294
+ """Deploy an Inference Endpoint from the Model Catalog."""
295
+ api = get_hf_api(token=token)
296
+ try:
297
+ endpoint = api.create_inference_endpoint_from_catalog(
298
+ repo_id=repo,
299
+ name=name,
300
+ accelerator=accelerator,
301
+ namespace=namespace,
302
+ token=token,
303
+ )
304
+ except HfHubHTTPError as error:
305
+ out.error(f"Deployment failed: {error}")
306
+ raise click.exceptions.Exit(code=error.response.status_code) from error
307
+
308
+ out.dict(endpoint.raw)
309
+
310
+
311
+ def list_catalog(
312
+ token: TokenOpt = None,
313
+ ) -> None:
314
+ """List available Catalog models."""
315
+ api = get_hf_api(token=token)
316
+ try:
317
+ models = api.list_inference_catalog(token=token)
318
+ except HfHubHTTPError as error:
319
+ out.error(f"Catalog fetch failed: {error}")
320
+ raise click.exceptions.Exit(code=error.response.status_code) from error
321
+
322
+ out.dict({"models": models})
323
+
324
+
325
+ catalog_app.command(name="list | ls", examples=["hf endpoints catalog ls"])(list_catalog)
326
+ ie_cli.command(name="list-catalog", hidden=True)(list_catalog)
327
+
328
+
329
+ ie_cli.add_group(catalog_app, name="catalog")
330
+
331
+
332
+ @ie_cli.command(examples=["hf endpoints describe my-endpoint"])
333
+ def describe(
334
+ name: NameArg,
335
+ namespace: NamespaceOpt = None,
336
+ token: TokenOpt = None,
337
+ ) -> None:
338
+ """Get information about an existing endpoint."""
339
+ api = get_hf_api(token=token)
340
+ try:
341
+ endpoint = api.get_inference_endpoint(name=name, namespace=namespace, token=token)
342
+ except HfHubHTTPError as error:
343
+ out.error(f"Fetch failed: {error}")
344
+ raise click.exceptions.Exit(code=error.response.status_code) from error
345
+
346
+ out.dict(endpoint.raw)
347
+
348
+
349
+ @ie_cli.command(examples=["hf endpoints update my-endpoint --min-replica 2"])
350
+ def update(
351
+ name: NameArg,
352
+ namespace: NamespaceOpt = None,
353
+ repo: Annotated[
354
+ str | None,
355
+ Option(
356
+ help="The name of the model repository associated with the Inference Endpoint (e.g. 'openai/gpt-oss-120b').",
357
+ ),
358
+ ] = None,
359
+ accelerator: Annotated[
360
+ str | None,
361
+ Option(
362
+ help="The hardware accelerator to be used for inference (e.g. 'cpu').",
363
+ ),
364
+ ] = None,
365
+ instance_size: Annotated[
366
+ str | None,
367
+ Option(
368
+ help="The size or type of the instance to be used for hosting the model (e.g. 'x4').",
369
+ ),
370
+ ] = None,
371
+ instance_type: Annotated[
372
+ str | None,
373
+ Option(
374
+ help="The cloud instance type where the Inference Endpoint will be deployed (e.g. 'intel-icl').",
375
+ ),
376
+ ] = None,
377
+ framework: Annotated[
378
+ str | None,
379
+ Option(
380
+ help="The machine learning framework used for the model (e.g. 'custom').",
381
+ ),
382
+ ] = None,
383
+ revision: Annotated[
384
+ str | None,
385
+ Option(
386
+ help="The specific model revision to deploy on the Inference Endpoint (e.g. '6c0e6080953db56375760c0471a8c5f2929baf11').",
387
+ ),
388
+ ] = None,
389
+ task: Annotated[
390
+ str | None,
391
+ Option(
392
+ help="The task on which to deploy the model (e.g. 'text-classification').",
393
+ ),
394
+ ] = None,
395
+ min_replica: Annotated[
396
+ int | None,
397
+ Option(
398
+ help="The minimum number of replicas (instances) to keep running for the Inference Endpoint.",
399
+ ),
400
+ ] = None,
401
+ max_replica: Annotated[
402
+ int | None,
403
+ Option(
404
+ help="The maximum number of replicas (instances) to scale to for the Inference Endpoint.",
405
+ ),
406
+ ] = None,
407
+ scale_to_zero_timeout: Annotated[
408
+ int | None,
409
+ Option(
410
+ help="The duration in minutes before an inactive endpoint is scaled to zero.",
411
+ ),
412
+ ] = None,
413
+ scaling_metric: Annotated[
414
+ InferenceEndpointScalingMetric | None,
415
+ Option(
416
+ help="The metric reference for scaling.",
417
+ ),
418
+ ] = None,
419
+ scaling_threshold: Annotated[
420
+ float | None,
421
+ Option(
422
+ help="The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided.",
423
+ ),
424
+ ] = None,
425
+ token: TokenOpt = None,
426
+ ) -> None:
427
+ """Update an existing endpoint."""
428
+ api = get_hf_api(token=token)
429
+ try:
430
+ endpoint = api.update_inference_endpoint(
431
+ name=name,
432
+ namespace=namespace,
433
+ repository=repo,
434
+ framework=framework,
435
+ revision=revision,
436
+ task=task,
437
+ accelerator=accelerator,
438
+ instance_size=instance_size,
439
+ instance_type=instance_type,
440
+ min_replica=min_replica,
441
+ max_replica=max_replica,
442
+ scale_to_zero_timeout=scale_to_zero_timeout,
443
+ scaling_metric=scaling_metric,
444
+ scaling_threshold=scaling_threshold,
445
+ token=token,
446
+ )
447
+ except HfHubHTTPError as error:
448
+ out.error(f"Update failed: {error}")
449
+ raise click.exceptions.Exit(code=error.response.status_code) from error
450
+ out.dict(endpoint.raw)
451
+
452
+
453
+ @ie_cli.command(examples=["hf endpoints delete my-endpoint"])
454
+ def delete(
455
+ name: NameArg,
456
+ namespace: NamespaceOpt = None,
457
+ yes: Annotated[
458
+ bool,
459
+ Option("--yes", help="Skip confirmation prompts."),
460
+ ] = False,
461
+ token: TokenOpt = None,
462
+ ) -> None:
463
+ """Delete an Inference Endpoint permanently."""
464
+ out.confirm(f"Delete endpoint '{name}'?", yes=yes)
465
+
466
+ api = get_hf_api(token=token)
467
+ try:
468
+ api.delete_inference_endpoint(name=name, namespace=namespace, token=token)
469
+ except HfHubHTTPError as error:
470
+ out.error(f"Delete failed: {error}")
471
+ raise click.exceptions.Exit(code=error.response.status_code) from error
472
+
473
+ out.result(f"Deleted '{name}'.", name=name)
474
+
475
+
476
+ @ie_cli.command(examples=["hf endpoints pause my-endpoint"])
477
+ def pause(
478
+ name: NameArg,
479
+ namespace: NamespaceOpt = None,
480
+ token: TokenOpt = None,
481
+ ) -> None:
482
+ """Pause an Inference Endpoint."""
483
+ api = get_hf_api(token=token)
484
+ try:
485
+ endpoint = api.pause_inference_endpoint(name=name, namespace=namespace, token=token)
486
+ except HfHubHTTPError as error:
487
+ out.error(f"Pause failed: {error}")
488
+ raise click.exceptions.Exit(code=error.response.status_code) from error
489
+
490
+ out.dict(endpoint.raw)
491
+
492
+
493
+ @ie_cli.command(examples=["hf endpoints resume my-endpoint"])
494
+ def resume(
495
+ name: NameArg,
496
+ namespace: NamespaceOpt = None,
497
+ fail_if_already_running: Annotated[
498
+ bool,
499
+ Option(
500
+ "--fail-if-already-running",
501
+ help="If `True`, the method will raise an error if the Inference Endpoint is already running.",
502
+ ),
503
+ ] = False,
504
+ token: TokenOpt = None,
505
+ ) -> None:
506
+ """Resume an Inference Endpoint."""
507
+ api = get_hf_api(token=token)
508
+ try:
509
+ endpoint = api.resume_inference_endpoint(
510
+ name=name,
511
+ namespace=namespace,
512
+ token=token,
513
+ running_ok=not fail_if_already_running,
514
+ )
515
+ except HfHubHTTPError as error:
516
+ out.error(f"Resume failed: {error}")
517
+ raise click.exceptions.Exit(code=error.response.status_code) from error
518
+ out.dict(endpoint.raw)
519
+
520
+
521
+ @ie_cli.command(examples=["hf endpoints scale-to-zero my-endpoint"])
522
+ def scale_to_zero(
523
+ name: NameArg,
524
+ namespace: NamespaceOpt = None,
525
+ token: TokenOpt = None,
526
+ ) -> None:
527
+ """Scale an Inference Endpoint to zero."""
528
+ api = get_hf_api(token=token)
529
+ try:
530
+ endpoint = api.scale_to_zero_inference_endpoint(name=name, namespace=namespace, token=token)
531
+ except HfHubHTTPError as error:
532
+ out.error(f"Scale To Zero failed: {error}")
533
+ raise click.exceptions.Exit(code=error.response.status_code) from error
534
+
535
+ out.dict(endpoint.raw)
.cache/uv/archive-v0/LUZqsK8zwmHIcO7YhH0I8/huggingface_hub/cli/jobs.py ADDED
@@ -0,0 +1,1335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains commands to interact with jobs on the Hugging Face Hub."""
15
+
16
+ import itertools
17
+ import multiprocessing
18
+ import multiprocessing.pool
19
+ import shutil
20
+ import time
21
+ from collections.abc import Callable, Iterable
22
+ from fnmatch import fnmatch
23
+ from pathlib import Path
24
+ from queue import Empty, Queue
25
+ from typing import Annotated, Any, TypeVar
26
+ from urllib.parse import urlsplit
27
+
28
+ from huggingface_hub import HfApi, JobHardware, JobInfo, JobStage, Volume, constants
29
+ from huggingface_hub._jobs_api import TERMINAL_JOB_STAGES
30
+ from huggingface_hub.errors import CLIError
31
+ from huggingface_hub.utils import logging
32
+ from huggingface_hub.utils._cache_manager import _format_size
33
+ from huggingface_hub.utils._hf_uris import _split_mount
34
+ from huggingface_hub.utils._parsing import format_duration, parse_duration
35
+
36
+ from ._cli_utils import (
37
+ EnvFileOpt,
38
+ EnvOpt,
39
+ SecretsFileOpt,
40
+ SecretsOpt,
41
+ SoftChoice,
42
+ SshDryRunOpt,
43
+ SshIdentityFileOpt,
44
+ TokenOpt,
45
+ exec_ssh,
46
+ get_hf_api,
47
+ parse_env_map,
48
+ parse_volumes,
49
+ typer_factory,
50
+ )
51
+ from ._framework import Argument, Option
52
+ from ._output import _dataclass_to_dict, out
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ def _parse_namespace_from_job_id(job_id: str, namespace: str | None) -> tuple[str, str | None]:
59
+ """Extract namespace from job_id if provided in 'namespace/job_id' format.
60
+
61
+ Allows users to pass job IDs copied from the Hub UI (e.g. 'username/job_id')
62
+ instead of only bare job IDs. If the namespace is also provided explicitly via
63
+ --namespace and conflicts, a CLIError is raised.
64
+ """
65
+ if not job_id:
66
+ raise CLIError("Job ID cannot be empty.")
67
+
68
+ if job_id.count("/") > 1:
69
+ raise CLIError(f"Job ID must be in the form 'job_id' or 'namespace/job_id': '{job_id}'.")
70
+
71
+ if "/" not in job_id:
72
+ return job_id, namespace
73
+
74
+ extracted_namespace, parsed_job_id = job_id.split("/", 1)
75
+ if not extracted_namespace or not parsed_job_id:
76
+ raise CLIError(f"Job ID must be in the form 'job_id' or 'namespace/job_id': '{job_id}'.")
77
+
78
+ if namespace is not None and namespace != extracted_namespace:
79
+ raise CLIError(
80
+ f"Conflicting namespace: got --namespace='{namespace}' but job ID implies namespace='{extracted_namespace}'"
81
+ )
82
+
83
+ return parsed_job_id, extracted_namespace
84
+
85
+
86
+ def _parse_and_sync_job_volumes(
87
+ volumes: list[str] | None, *, api: HfApi, namespace: str | None
88
+ ) -> list[Volume] | None:
89
+ """Parse `-v` specs for Jobs commands.
90
+
91
+ Same as [`parse_volumes`] but the source side can also be a local directory: it is synced to a
92
+ bucket via [`HfApi.sync_job_volume`] and the resulting bucket subfolder is mounted (read-only
93
+ unless ':rw' is specified).
94
+ """
95
+ if not volumes:
96
+ return None
97
+
98
+ result: list[Volume] = []
99
+ for raw_spec in volumes:
100
+ if raw_spec.startswith(constants.HF_PROTOCOL):
101
+ result.extend(parse_volumes([raw_spec]) or [])
102
+ continue
103
+
104
+ # Not a 'hf://' URI: treat the source as a local directory.
105
+ source, mount_path, read_only = _split_mount(raw_spec, raw=raw_spec)
106
+ if mount_path is None:
107
+ raise CLIError(
108
+ f"Missing mount path in volume spec '{raw_spec}'. Expected 'LOCAL_DIR:/MOUNT_PATH[:ro|:rw]' (e.g. './data:/data')."
109
+ )
110
+ if not Path(source).expanduser().is_dir():
111
+ raise CLIError(
112
+ f"Volume source '{source}' is not an existing local directory. "
113
+ "To mount a repo or bucket instead, use the 'hf://' syntax (e.g. 'hf://buckets/my-org/my-bucket:/data')."
114
+ )
115
+ volume = api.sync_job_volume(
116
+ source,
117
+ mount_path,
118
+ read_only=read_only if read_only is not None else True,
119
+ namespace=namespace,
120
+ )
121
+ if volume.read_only is False:
122
+ out.hint(
123
+ f"Volume '{mount_path}' is mounted read-write. Once the job is over, pull back its data with:\n"
124
+ f" hf buckets sync hf://buckets/{volume.source}/{volume.path} {source}"
125
+ )
126
+ result.append(volume)
127
+ return result
128
+
129
+
130
+ STATS_UPDATE_MIN_INTERVAL = 0.1 # we set a limit here since there is one update per second per job
131
+
132
+ # Common job-related options
133
+ ImageArg = Annotated[
134
+ str,
135
+ Argument(
136
+ help="The Docker image to use.",
137
+ ),
138
+ ]
139
+
140
+ ImageOpt = Annotated[
141
+ str | None,
142
+ Option(
143
+ help="Use a custom Docker image with `uv` installed.",
144
+ ),
145
+ ]
146
+
147
+ FlavorOpt = Annotated[
148
+ str | None,
149
+ Option(
150
+ help="Flavor for the hardware. Run 'hf jobs hardware' to list available flavors. Defaults to `cpu-basic`.",
151
+ click_type=SoftChoice(JobHardware),
152
+ ),
153
+ ]
154
+
155
+ LabelsOpt = Annotated[
156
+ list[str] | None,
157
+ Option(
158
+ "-l",
159
+ "--label",
160
+ help="Set labels. E.g. --label KEY=VALUE or --label LABEL",
161
+ ),
162
+ ]
163
+
164
+ TimeoutOpt = Annotated[
165
+ str | None,
166
+ Option(
167
+ help="Max duration: int with s (seconds, default), m (minutes), h (hours) or d (days).",
168
+ ),
169
+ ]
170
+
171
+ DetachOpt = Annotated[
172
+ bool,
173
+ Option(
174
+ "-d",
175
+ "--detach",
176
+ help="Run the Job in the background and print the Job ID.",
177
+ ),
178
+ ]
179
+
180
+ NamespaceOpt = Annotated[
181
+ str | None,
182
+ Option(
183
+ help="The namespace where the job will be running. Defaults to the current user's namespace.",
184
+ ),
185
+ ]
186
+
187
+ ExposeOpt = Annotated[
188
+ list[int] | None,
189
+ Option(
190
+ "--expose",
191
+ help="Expose a container port through the jobs proxy. Repeat the flag for multiple ports (e.g. `--expose 8000 --expose 8001`). Each exposed port is reachable on the public jobs domain; access requires an HF token with read access to the job's namespace.",
192
+ ),
193
+ ]
194
+
195
+ SshEnabledOpt = Annotated[
196
+ bool,
197
+ Option(
198
+ "--ssh",
199
+ help="Make the job's container reachable over SSH. Connect with `hf jobs ssh <job_id>`. Requires an SSH public key registered on https://huggingface.co/settings/keys.",
200
+ ),
201
+ ]
202
+
203
+ WithOpt = Annotated[
204
+ list[str] | None,
205
+ Option(
206
+ "--with",
207
+ help="Run with the given packages installed",
208
+ ),
209
+ ]
210
+
211
+ PythonOpt = Annotated[
212
+ str | None,
213
+ Option(
214
+ "-p",
215
+ "--python",
216
+ help="The Python interpreter to use for the run environment",
217
+ ),
218
+ ]
219
+
220
+ SuspendOpt = Annotated[
221
+ bool | None,
222
+ Option(
223
+ help="Suspend (pause) the scheduled Job",
224
+ ),
225
+ ]
226
+
227
+ ConcurrencyOpt = Annotated[
228
+ bool | None,
229
+ Option(
230
+ help="Allow multiple instances of this Job to run concurrently",
231
+ ),
232
+ ]
233
+
234
+ ScheduleArg = Annotated[
235
+ str,
236
+ Argument(
237
+ help="One of annually, yearly, monthly, weekly, daily, hourly, or a CRON schedule expression.",
238
+ ),
239
+ ]
240
+
241
+ ScriptArg = Annotated[
242
+ str,
243
+ Argument(
244
+ help="UV script to run (local file or URL)",
245
+ ),
246
+ ]
247
+
248
+ ScriptArgsArg = Annotated[
249
+ list[str] | None,
250
+ Argument(
251
+ help="Arguments for the script",
252
+ ),
253
+ ]
254
+
255
+
256
+ CommandArg = Annotated[
257
+ list[str],
258
+ Argument(
259
+ help="The command to run.",
260
+ ),
261
+ ]
262
+
263
+ JobIdArg = Annotated[
264
+ str,
265
+ Argument(
266
+ help="Job ID (or 'namespace/job_id')",
267
+ ),
268
+ ]
269
+
270
+ JobIdsArg = Annotated[
271
+ list[str] | None,
272
+ Argument(
273
+ help="Job IDs (or 'namespace/job_id')",
274
+ ),
275
+ ]
276
+
277
+ ScheduledJobIdArg = Annotated[
278
+ str,
279
+ Argument(
280
+ help="Scheduled Job ID (or 'namespace/scheduled_job_id')",
281
+ ),
282
+ ]
283
+
284
+ JobVolumesOpt = Annotated[
285
+ list[str] | None,
286
+ Option(
287
+ "-v",
288
+ "--volume",
289
+ help="Mount one or more volumes. Format: hf://[TYPE/]SOURCE:/MOUNT_PATH[:ro|:rw] or LOCAL_DIR:/MOUNT_PATH[:ro|:rw]. "
290
+ "TYPE is one of: models, datasets, spaces, buckets. "
291
+ "TYPE defaults to models if omitted. "
292
+ "models, datasets and spaces are always mounted read-only. buckets are read+write by default. "
293
+ "A local directory source is first synced to a bucket and mounted read-only by default. "
294
+ "E.g. -v hf://datasets/org/ds:/data or -v hf://buckets/org/b:/mnt:ro or -v ./inputs:/inputs",
295
+ ),
296
+ ]
297
+
298
+
299
+ jobs_cli = typer_factory(help="Run and manage Jobs on the Hub.")
300
+
301
+
302
+ def _stream_logs_and_check_status(api: HfApi, job: JobInfo) -> None:
303
+ """Stream Job logs until the Job ends, then fail the command if the Job did not complete successfully."""
304
+ for log in api.fetch_job_logs(job_id=job.id, namespace=job.owner.name, follow=True):
305
+ out.text(log)
306
+ # The log stream can end while the Job is still scheduling or shutting down: settle the final state.
307
+ final = api.wait_for_job(job_id=job.id, namespace=job.owner.name)
308
+ if final.status.stage != JobStage.COMPLETED:
309
+ message = f": {final.status.message}" if final.status.message else ""
310
+ raise CLIError(f"Job {final.id} finished with stage '{final.status.stage}'{message}")
311
+ out.text(f"Job {final.id} completed")
312
+
313
+
314
+ @jobs_cli.command(
315
+ "run",
316
+ context_settings={"ignore_unknown_options": True},
317
+ examples=[
318
+ "hf jobs run python:3.12 python -c 'print(\"Hello!\")'",
319
+ "hf jobs run --detach python:3.12 python script.py",
320
+ "hf jobs run -e FOO=foo python:3.12 python script.py",
321
+ "hf jobs run --secrets HF_TOKEN python:3.12 python script.py",
322
+ "hf jobs run -v hf://org/my-model:/data -v hf://buckets/org/b:/mnt python:3.12 python script.py",
323
+ ],
324
+ )
325
+ def jobs_run(
326
+ image: ImageArg,
327
+ command: CommandArg,
328
+ env: EnvOpt = None,
329
+ secrets: SecretsOpt = None,
330
+ label: LabelsOpt = None,
331
+ volume: JobVolumesOpt = None,
332
+ env_file: EnvFileOpt = None,
333
+ secrets_file: SecretsFileOpt = None,
334
+ flavor: FlavorOpt = None,
335
+ timeout: TimeoutOpt = None,
336
+ detach: DetachOpt = False,
337
+ expose: ExposeOpt = None,
338
+ ssh: SshEnabledOpt = False,
339
+ namespace: NamespaceOpt = None,
340
+ token: TokenOpt = None,
341
+ ) -> None:
342
+ """Run a Job."""
343
+ env_map = parse_env_map(env, env_file)
344
+ secrets_map = parse_env_map(secrets, secrets_file)
345
+
346
+ api = get_hf_api(token=token)
347
+ job = api.run_job(
348
+ image=image,
349
+ command=command,
350
+ env=env_map,
351
+ secrets=secrets_map,
352
+ labels=_parse_labels_map(label),
353
+ volumes=_parse_and_sync_job_volumes(volume, api=api, namespace=namespace),
354
+ flavor=flavor,
355
+ timeout=timeout,
356
+ expose=expose,
357
+ ssh=ssh,
358
+ namespace=namespace,
359
+ )
360
+ out.result("Job started", id=job.id, url=job.url)
361
+ if isinstance(job.status.expose_urls, list):
362
+ urls = "\n".join(f" {url}" for url in job.status.expose_urls)
363
+ out.hint(f"Exposed ports are reachable at (requires an HF token with read access to the job):\n{urls}")
364
+ if isinstance(job.status.ssh_url, str):
365
+ out.hint(f"Use `hf jobs ssh {job.owner.name}/{job.id}` to open an SSH session into the job.")
366
+ if detach:
367
+ job_ref = f"{job.owner.name}/{job.id}"
368
+ out.hint(f"Use `hf jobs logs -f {job_ref}` to stream logs, or `hf jobs inspect {job_ref}` to check status.")
369
+ out.hint(f"Use `hf jobs wait {job_ref}` to block until it finishes.")
370
+ return
371
+ _stream_logs_and_check_status(api, job)
372
+
373
+
374
+ @jobs_cli.command(
375
+ "logs",
376
+ examples=[
377
+ "hf jobs logs <job_id>",
378
+ "hf jobs logs -f <job_id>",
379
+ "hf jobs logs --tail 20 <job_id>",
380
+ "hf jobs logs -f --tail 100 <job_id>",
381
+ ],
382
+ )
383
+ def jobs_logs(
384
+ job_id: JobIdArg,
385
+ follow: Annotated[
386
+ bool,
387
+ Option(
388
+ "-f",
389
+ "--follow",
390
+ help="Follow log output (stream until the job completes). Without this flag, only currently available logs are printed.",
391
+ ),
392
+ ] = False,
393
+ tail: Annotated[
394
+ int | None,
395
+ Option(
396
+ "-n",
397
+ "--tail",
398
+ help="Number of lines to show from the end of the logs. When combined with --follow, starts streaming from the last N lines.",
399
+ ),
400
+ ] = None,
401
+ namespace: NamespaceOpt = None,
402
+ token: TokenOpt = None,
403
+ ) -> None:
404
+ """Fetch the logs of a Job.
405
+
406
+ By default, prints currently available logs and exits (non-blocking).
407
+ Use --follow/-f to stream logs in real-time until the job completes.
408
+ Use --tail/-n to limit the number of lines returned (server-side when supported).
409
+
410
+ Note: following exits when the log stream ends, regardless of whether the Job
411
+ succeeded or failed. Run `hf jobs inspect <job_id>` to check the final status.
412
+ """
413
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
414
+
415
+ api = get_hf_api(token=token)
416
+ logs = api.fetch_job_logs(job_id=job_id, namespace=namespace, follow=follow, tail=tail)
417
+ for log in logs:
418
+ out.text(log)
419
+ if follow:
420
+ job_ref = f"{namespace}/{job_id}" if namespace else job_id
421
+ out.hint(f"Stream ended. Run `hf jobs inspect {job_ref}` to check the final status (e.g. COMPLETED or ERROR).")
422
+
423
+
424
+ def _matches_filters(job_properties: dict[str, str], filters: list[tuple[str, str, str]]) -> bool:
425
+ """Check if scheduled job matches all specified filters."""
426
+ for key, op_str, pattern in filters:
427
+ value = job_properties.get(key)
428
+ if value is None:
429
+ if op_str == "!=":
430
+ continue
431
+ return False
432
+ match = fnmatch(value.lower(), pattern.lower())
433
+ if (op_str == "=" and not match) or (op_str == "!=" and match):
434
+ return False
435
+ return True
436
+
437
+
438
+ def _clear_line(n: int) -> None:
439
+ LINE_UP = "\033[1A"
440
+ LINE_CLEAR = "\x1b[2K"
441
+ for i in range(n):
442
+ print(LINE_UP, end=LINE_CLEAR)
443
+
444
+
445
+ def _get_jobs_stats_rows(
446
+ job_id: str, metrics_stream: Iterable[dict[str, Any]], table_headers: list[str]
447
+ ) -> Iterable[tuple[bool, str, list[list[str | int]]]]:
448
+ for metrics in metrics_stream:
449
+ row = [
450
+ job_id,
451
+ f"{metrics['cpu_usage_pct']}%",
452
+ round(metrics["cpu_millicores"] / 1000.0, 1),
453
+ f"{round(100 * metrics['memory_used_bytes'] / metrics['memory_total_bytes'], 2)}%",
454
+ f"{_format_size(metrics['memory_used_bytes'])}B / {_format_size(metrics['memory_total_bytes'])}B",
455
+ f"{_format_size(metrics['rx_bps'])}bps / {_format_size(metrics['tx_bps'])}bps",
456
+ ]
457
+ if metrics["gpus"] and isinstance(metrics["gpus"], dict):
458
+ rows = [row] + [[""] * len(row)] * (len(metrics["gpus"]) - 1)
459
+ for row, gpu_id in zip(rows, sorted(metrics["gpus"])):
460
+ gpu = metrics["gpus"][gpu_id]
461
+ row += [
462
+ f"{gpu['utilization']}%",
463
+ f"{round(100 * gpu['memory_used_bytes'] / gpu['memory_total_bytes'], 2)}%",
464
+ f"{_format_size(gpu['memory_used_bytes'])}B / {_format_size(gpu['memory_total_bytes'])}B",
465
+ ]
466
+ else:
467
+ row += ["N/A"] * (len(table_headers) - len(row))
468
+ rows = [row]
469
+ yield False, job_id, rows
470
+ yield True, job_id, []
471
+
472
+
473
+ @jobs_cli.command("stats", examples=["hf jobs stats <job_id>"])
474
+ def jobs_stats(
475
+ job_ids: JobIdsArg = None,
476
+ namespace: NamespaceOpt = None,
477
+ token: TokenOpt = None,
478
+ ) -> None:
479
+ """Fetch the resource usage statistics and metrics of Jobs"""
480
+ if job_ids is not None:
481
+ parsed_ids = []
482
+ for job_id in job_ids:
483
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
484
+ parsed_ids.append(job_id)
485
+ job_ids = parsed_ids
486
+ api = get_hf_api(token=token)
487
+ if namespace is None:
488
+ namespace = api.whoami()["name"]
489
+ if job_ids is None:
490
+ job_ids = [
491
+ job.id
492
+ for job in api.list_jobs(namespace=namespace)
493
+ if (job.status.stage if job.status else "UNKNOWN") in ("RUNNING", "UPDATING")
494
+ ]
495
+ if len(job_ids) == 0:
496
+ out.text("No running jobs found")
497
+ return
498
+ table_headers = [
499
+ "JOB ID",
500
+ "CPU %",
501
+ "NUM CPU",
502
+ "MEM %",
503
+ "MEM USAGE",
504
+ "NET I/O",
505
+ "GPU UTIL %",
506
+ "GPU MEM %",
507
+ "GPU MEM USAGE",
508
+ ]
509
+ with multiprocessing.pool.ThreadPool(len(job_ids)) as pool:
510
+ rows_per_job_id: dict[str, list[list[str | int]]] = {}
511
+ for job_id in job_ids:
512
+ row: list[str | int] = [job_id]
513
+ row += ["-- / --" if ("/" in header or "USAGE" in header) else "--" for header in table_headers[1:]]
514
+ rows_per_job_id[job_id] = [row]
515
+ last_update_time = time.time()
516
+ total_rows = [row for job_id in rows_per_job_id for row in rows_per_job_id[job_id]]
517
+ # In-place refresh (cursor-up + clear) requires a fixed line count and layout —
518
+ # `out.table`'s mode-dependent formatting would break it.
519
+ print(_tabulate(total_rows, headers=table_headers))
520
+
521
+ kwargs_list = [
522
+ {
523
+ "job_id": job_id,
524
+ "metrics_stream": api.fetch_job_metrics(job_id=job_id, namespace=namespace),
525
+ "table_headers": table_headers,
526
+ }
527
+ for job_id in job_ids
528
+ ]
529
+ for done, job_id, rows in iflatmap_unordered(pool, _get_jobs_stats_rows, kwargs_list=kwargs_list):
530
+ if done:
531
+ rows_per_job_id.pop(job_id, None)
532
+ else:
533
+ rows_per_job_id[job_id] = rows
534
+ now = time.time()
535
+ if now - last_update_time >= STATS_UPDATE_MIN_INTERVAL:
536
+ _clear_line(2 + len(total_rows))
537
+ total_rows = [row for job_id in rows_per_job_id for row in rows_per_job_id[job_id]]
538
+ print(_tabulate(total_rows, headers=table_headers))
539
+ last_update_time = now
540
+
541
+
542
+ @jobs_cli.command(
543
+ "list | ls | ps",
544
+ examples=[
545
+ "hf jobs ls",
546
+ "hf jobs ls -a",
547
+ "hf jobs ls --status running,scheduling",
548
+ "hf jobs ls --label env=prod --label team=ml",
549
+ "hf jobs ls --all --label hf-sandbox=1",
550
+ ],
551
+ )
552
+ def jobs_ps(
553
+ all: Annotated[
554
+ bool,
555
+ Option(
556
+ "-a",
557
+ "--all",
558
+ help="Show all Jobs (default shows running and scheduling). Cannot be combined with --status.",
559
+ ),
560
+ ] = False,
561
+ status: Annotated[
562
+ list[str] | None,
563
+ Option(
564
+ "--status",
565
+ click_type=SoftChoice(JobStage),
566
+ help="Only show Jobs with the given status. Comma-separated or repeated, e.g. `--status running,scheduling`.",
567
+ ),
568
+ ] = None,
569
+ label: Annotated[
570
+ list[str] | None,
571
+ Option(
572
+ "-l",
573
+ "--label",
574
+ help="Only show Jobs with the given `key=value` label. Repeat to require several labels, e.g. `--label env=prod --label team=ml`.",
575
+ ),
576
+ ] = None,
577
+ limit: Annotated[
578
+ int,
579
+ Option(
580
+ "--limit",
581
+ help="Maximum number of Jobs to display. Set to 0 to show all (no limit).",
582
+ ),
583
+ ] = 100,
584
+ namespace: NamespaceOpt = None,
585
+ token: TokenOpt = None,
586
+ filter: Annotated[
587
+ list[str] | None,
588
+ Option(
589
+ "-f",
590
+ "--filter",
591
+ help="(Deprecated) Use `--status` and `--label` instead.",
592
+ ),
593
+ ] = None,
594
+ ) -> None:
595
+ """List Jobs.
596
+
597
+ Use `--status` to filter by status (see [`JobStage`] for possible values) and `--label` to filter by `key=value`
598
+ labels. A Job must match every filter to be listed.
599
+ """
600
+ api = get_hf_api(token=token)
601
+
602
+ if filter:
603
+ out.warning(
604
+ f"Ignoring filter '{filter}'."
605
+ " `-f`/`--filter` is deprecated and will be removed in a future release. Use `--status`/`--label`."
606
+ )
607
+
608
+ if all and status:
609
+ raise CLIError("`-a`/`--all` cannot be combined with `--status`.")
610
+
611
+ # Status filtering (default to active Jobs, unless `--all` or `--status` is provided).
612
+ raw_statuses: list[str] = []
613
+ for value in status or []:
614
+ raw_statuses.extend(part.strip() for part in value.split(",") if part.strip())
615
+
616
+ server_statuses: list[str] | None
617
+ if raw_statuses:
618
+ server_statuses = raw_statuses
619
+ elif all:
620
+ server_statuses = None
621
+ else:
622
+ server_statuses = [JobStage.RUNNING.value, JobStage.SCHEDULING.value]
623
+
624
+ # Labels filtering
625
+ labels: dict[str, str] = {}
626
+ for item in label or []:
627
+ if "=" not in item:
628
+ raise CLIError(f"Invalid label filter '{item}': must be in the form 'key=value'")
629
+ key, value = item.split("=")
630
+ labels[key] = value
631
+
632
+ jobs_iter = api.list_jobs(namespace=namespace, status=server_statuses, labels=labels or None)
633
+
634
+ # Apply the display limit. Fetch one extra Job to detect (and warn about) truncation.
635
+ truncated = False
636
+ if limit > 0:
637
+ jobs = list(itertools.islice(jobs_iter, limit + 1))
638
+ if len(jobs) > limit:
639
+ truncated = True
640
+ jobs = jobs[:limit]
641
+ else:
642
+ jobs = list(jobs_iter)
643
+
644
+ # Build display items. Augment the raw api dict with curated, table-friendly columns.
645
+ job_items: list[dict[str, Any]] = []
646
+ for job in jobs:
647
+ job_item = _dataclass_to_dict(job)
648
+ durations = job_item.get("durations") or {}
649
+ cmd = job_item.get("command") or []
650
+ job_item["job_id"] = job_item.get("id", "")
651
+ job_item["image/space"] = job_item.get("docker_image") or "N/A"
652
+ job_item["command"] = " ".join(cmd) if cmd else "N/A"
653
+ job_item["created"] = job_item["created_at"][:19].replace("T", " ") if job_item.get("created_at") else "N/A"
654
+ job_item["status"] = (job_item.get("status") or {}).get("stage", "UNKNOWN")
655
+ job_item["runtime"] = format_duration(durations.get("running_secs"))
656
+ job_items.append(job_item)
657
+
658
+ out.table(
659
+ job_items,
660
+ headers=["job_id", "image/space", "command", "created", "status", "runtime"],
661
+ id_key="job_id",
662
+ )
663
+ if truncated:
664
+ out.hint(f"Output truncated to {limit} Jobs. Use `--limit 0` to show all (or `--limit N`).")
665
+ if not job_items:
666
+ if raw_statuses or labels:
667
+ filters_msg = ", ".join(
668
+ [*(f"status={s}" for s in raw_statuses), *(f"label={k}={v}" for k, v in labels.items())]
669
+ )
670
+ out.text(f"No jobs matched filters: {filters_msg}")
671
+ elif not all:
672
+ out.hint("No running jobs. Use `-a`/`--all` to include finished (and failed) jobs.")
673
+
674
+
675
+ @jobs_cli.command("hardware", examples=["hf jobs hardware"])
676
+ def jobs_hardware() -> None:
677
+ """List available hardware options for Jobs"""
678
+ api = get_hf_api()
679
+ hardware_list = api.list_jobs_hardware()
680
+ items = []
681
+ for hw in hardware_list:
682
+ accelerator_info = ""
683
+ if hw.accelerator:
684
+ accelerator_info = f"{hw.accelerator.quantity}x {hw.accelerator.model} ({hw.accelerator.vram})"
685
+ cost_min = f"${hw.unit_cost_usd:.4f}" if hw.unit_cost_usd else "free"
686
+ cost_hour = f"${hw.unit_cost_usd * 60:.2f}" if hw.unit_cost_usd else "free"
687
+ items.append(
688
+ {
689
+ "name": hw.name,
690
+ "pretty name": hw.pretty_name,
691
+ "cpu": hw.cpu,
692
+ "ram": hw.ram,
693
+ "storage": hw.ephemeral_storage,
694
+ "accelerator": accelerator_info,
695
+ "cost/min": cost_min,
696
+ "cost/hour": cost_hour,
697
+ }
698
+ )
699
+ out.table(items)
700
+ out.hint("Use `hf jobs run --flavor <name> ...` to request a specific hardware flavor.")
701
+
702
+
703
+ @jobs_cli.command("inspect", examples=["hf jobs inspect <job_id>"])
704
+ def jobs_inspect(
705
+ job_ids: Annotated[
706
+ list[str],
707
+ Argument(
708
+ help="Job IDs to inspect (or 'namespace/job_id')",
709
+ ),
710
+ ],
711
+ namespace: NamespaceOpt = None,
712
+ token: TokenOpt = None,
713
+ ) -> None:
714
+ """Display detailed information on one or more Jobs"""
715
+ parsed_ids = []
716
+ for job_id in job_ids:
717
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
718
+ parsed_ids.append(job_id)
719
+ job_ids = parsed_ids
720
+ api = get_hf_api(token=token)
721
+ jobs = [api.inspect_job(job_id=job_id, namespace=namespace) for job_id in job_ids]
722
+ out.table([_dataclass_to_dict(job) for job in jobs])
723
+
724
+
725
+ @jobs_cli.command("cancel", examples=["hf jobs cancel <job_id>"])
726
+ def jobs_cancel(
727
+ job_id: JobIdArg,
728
+ namespace: NamespaceOpt = None,
729
+ token: TokenOpt = None,
730
+ ) -> None:
731
+ """Cancel a Job"""
732
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
733
+ api = get_hf_api(token=token)
734
+ api.cancel_job(job_id=job_id, namespace=namespace)
735
+ out.result("Job cancelled", id=job_id)
736
+
737
+
738
+ @jobs_cli.command(
739
+ "wait",
740
+ examples=[
741
+ "hf jobs wait <job_id>",
742
+ "hf jobs wait <job_id_1> <job_id_2>",
743
+ "hf jobs ls -q | xargs hf jobs wait",
744
+ ],
745
+ )
746
+ def jobs_wait(
747
+ job_ids: Annotated[
748
+ list[str],
749
+ Argument(
750
+ help="Job IDs to wait for (or 'namespace/job_id').",
751
+ ),
752
+ ],
753
+ timeout: Annotated[
754
+ str | None,
755
+ Option(
756
+ help="Max time to wait: int with s (seconds, default), m (minutes), h (hours) or d (days).",
757
+ ),
758
+ ] = None,
759
+ namespace: NamespaceOpt = None,
760
+ token: TokenOpt = None,
761
+ ) -> None:
762
+ """Wait for one or more Jobs to reach a terminal state.
763
+
764
+ Blocks until every Job has finished, then exits with code 0 if all Jobs completed
765
+ successfully, or a non-zero exit code if any Job was canceled, errored or deleted.
766
+
767
+ All Jobs must belong to the same namespace.
768
+ """
769
+ parsed_ids = []
770
+ namespaces = set()
771
+ for job_id in job_ids:
772
+ parsed_id, parsed_namespace = _parse_namespace_from_job_id(job_id, namespace)
773
+ parsed_ids.append(parsed_id)
774
+ namespaces.add(parsed_namespace)
775
+ if len(namespaces) > 1:
776
+ raise CLIError(
777
+ "All Job IDs must be in the same namespace, got: "
778
+ + ", ".join(str(ns) for ns in sorted(namespaces, key=str))
779
+ )
780
+ namespace = namespaces.pop()
781
+ timeout_secs = parse_duration(timeout) if timeout is not None else None
782
+
783
+ api = get_hf_api(token=token)
784
+ status = out.status(f"Waiting for {len(parsed_ids)} Job(s) to finish...")
785
+ try:
786
+ jobs = api.wait_for_job(parsed_ids, timeout=timeout_secs, namespace=namespace)
787
+ except TimeoutError:
788
+ status.done("Timed out.")
789
+ raise CLIError(f"Timed out after {timeout} waiting for Job(s) to finish.") from None
790
+ status.done(f"{len(jobs)} Job(s) finished.")
791
+
792
+ out.table([{"id": job.id, "stage": str(job.status.stage), "message": job.status.message} for job in jobs])
793
+ failed = [job for job in jobs if job.status.stage != JobStage.COMPLETED]
794
+ if failed:
795
+ raise CLIError(
796
+ f"{len(failed)} of {len(jobs)} Job(s) did not complete successfully: "
797
+ + ", ".join(f"{job.id} ({job.status.stage})" for job in failed)
798
+ )
799
+
800
+
801
+ @jobs_cli.command(
802
+ "labels",
803
+ examples=[
804
+ "hf jobs labels <job_id> --label env=prod --label team=ml",
805
+ "hf jobs labels <job_id> --clear",
806
+ ],
807
+ )
808
+ def jobs_labels(
809
+ job_id: JobIdArg,
810
+ label: LabelsOpt = None,
811
+ clear: Annotated[bool, Option("--clear", help="Remove all labels from the job.")] = False,
812
+ namespace: NamespaceOpt = None,
813
+ token: TokenOpt = None,
814
+ ) -> None:
815
+ """Update labels on a Job. Replaces all existing labels."""
816
+ if not label and not clear:
817
+ raise CLIError("Please set at least one label with --label. To remove all labels, pass --clear.")
818
+ if label and clear:
819
+ raise CLIError(
820
+ "Cannot set labels and clear them at the same time. Please use either --label or --clear, not both."
821
+ )
822
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
823
+ labels = _parse_labels_map(label) or {}
824
+ api = get_hf_api(token=token)
825
+ job = api.update_job_labels(job_id=job_id, labels=labels, namespace=namespace)
826
+ out.result("Labels updated", id=job.id)
827
+
828
+
829
+ @jobs_cli.command(
830
+ "ssh",
831
+ examples=[
832
+ "hf jobs ssh <job_id>",
833
+ "hf jobs ssh <job_id> --dry-run",
834
+ "hf jobs ssh <job_id> -i ~/.ssh/id_ed25519",
835
+ ],
836
+ )
837
+ def jobs_ssh(
838
+ job_id: JobIdArg,
839
+ identity_file: SshIdentityFileOpt = None,
840
+ dry_run: SshDryRunOpt = False,
841
+ namespace: NamespaceOpt = None,
842
+ token: TokenOpt = None,
843
+ ) -> None:
844
+ """SSH into a running Job.
845
+
846
+ If the Job is not yet running, waits until it reaches the RUNNING state before
847
+ connecting. Requires the Job to be started with SSH enabled (`hf jobs run --ssh ...`)
848
+ and your SSH public key to be registered at https://huggingface.co/settings/keys.
849
+ """
850
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
851
+ api = get_hf_api(token=token)
852
+ job = api.inspect_job(job_id=job_id, namespace=namespace)
853
+ if job.status.ssh_url is None:
854
+ raise CLIError("SSH is not enabled on this job. Start a job with SSH support using `hf jobs run --ssh ...`.")
855
+ if job.status.stage in TERMINAL_JOB_STAGES:
856
+ raise CLIError(f"Cannot SSH into job '{job.id}': job has already finished (stage: '{job.status.stage}').")
857
+ if job.status.stage != JobStage.RUNNING:
858
+ status = out.status(f"Waiting for job '{job.id}' to be running (stage: '{job.status.stage}')...")
859
+ job = api.wait_for_job(job_id=job.id, namespace=namespace, stages=[JobStage.RUNNING])
860
+ if job.status.stage != JobStage.RUNNING:
861
+ status.done("Job finished.")
862
+ raise CLIError(
863
+ f"Cannot SSH into job '{job.id}': job finished before reaching RUNNING (stage: '{job.status.stage}')."
864
+ )
865
+ status.done("Job is running.")
866
+ ssh_url = urlsplit(job.status.ssh_url)
867
+ exec_ssh(
868
+ f"{ssh_url.username}@{ssh_url.hostname}", # type: ignore
869
+ port=ssh_url.port,
870
+ identity_file=identity_file,
871
+ dry_run=dry_run,
872
+ )
873
+
874
+
875
+ uv_app = typer_factory(help="Run UV scripts (Python with inline dependencies) on HF infrastructure.")
876
+ jobs_cli.add_group(uv_app, name="uv")
877
+
878
+
879
+ @uv_app.command(
880
+ "run",
881
+ context_settings={"ignore_unknown_options": True},
882
+ examples=[
883
+ "hf jobs uv run my_script.py",
884
+ "hf jobs uv run --detach my_script.py",
885
+ "hf jobs uv run ml_training.py --flavor a10g-small",
886
+ "hf jobs uv run --with transformers train.py",
887
+ "hf jobs uv run -v hf://org/my-model:/data -v hf://buckets/org/b:/mnt script.py",
888
+ ],
889
+ )
890
+ def jobs_uv_run(
891
+ script: ScriptArg,
892
+ script_args: ScriptArgsArg = None,
893
+ image: ImageOpt = None,
894
+ flavor: FlavorOpt = None,
895
+ env: EnvOpt = None,
896
+ secrets: SecretsOpt = None,
897
+ label: LabelsOpt = None,
898
+ volume: JobVolumesOpt = None,
899
+ env_file: EnvFileOpt = None,
900
+ secrets_file: SecretsFileOpt = None,
901
+ timeout: TimeoutOpt = None,
902
+ detach: DetachOpt = False,
903
+ expose: ExposeOpt = None,
904
+ ssh: SshEnabledOpt = False,
905
+ namespace: NamespaceOpt = None,
906
+ token: TokenOpt = None,
907
+ with_: WithOpt = None,
908
+ python: PythonOpt = None,
909
+ ) -> None:
910
+ """Run a UV script (local file or URL) on HF infrastructure"""
911
+ env_map = parse_env_map(env, env_file)
912
+ secrets_map = parse_env_map(secrets, secrets_file)
913
+
914
+ api = get_hf_api(token=token)
915
+ job = api.run_uv_job(
916
+ script=script,
917
+ script_args=script_args or [],
918
+ dependencies=with_,
919
+ python=python,
920
+ image=image,
921
+ env=env_map,
922
+ secrets=secrets_map,
923
+ labels=_parse_labels_map(label),
924
+ volumes=_parse_and_sync_job_volumes(volume, api=api, namespace=namespace),
925
+ flavor=flavor,
926
+ timeout=timeout,
927
+ expose=expose,
928
+ ssh=ssh,
929
+ namespace=namespace,
930
+ )
931
+ out.result("Job started", id=job.id, url=job.url)
932
+ if isinstance(job.status.expose_urls, list):
933
+ urls = "\n".join(f" {url}" for url in job.status.expose_urls)
934
+ out.hint(f"Exposed ports are reachable at (requires an HF token with read access to the job):\n{urls}")
935
+ if isinstance(job.status.ssh_url, str):
936
+ out.hint(f"Use `hf jobs ssh {job.owner.name}/{job.id}` to open an SSH session into the job.")
937
+ if detach:
938
+ job_ref = f"{job.owner.name}/{job.id}"
939
+ out.hint(f"Use `hf jobs logs -f {job_ref}` to stream logs, or `hf jobs inspect {job_ref}` to check status.")
940
+ out.hint(f"Use `hf jobs wait {job_ref}` to block until it finishes.")
941
+ return
942
+ _stream_logs_and_check_status(api, job)
943
+
944
+
945
+ scheduled_app = typer_factory(help="Create and manage scheduled Jobs on the Hub.")
946
+ jobs_cli.add_group(scheduled_app, name="scheduled")
947
+
948
+
949
+ @scheduled_app.command(
950
+ "run",
951
+ context_settings={"ignore_unknown_options": True},
952
+ examples=['hf jobs scheduled run "0 0 * * *" python:3.12 python script.py'],
953
+ )
954
+ def scheduled_run(
955
+ schedule: ScheduleArg,
956
+ image: ImageArg,
957
+ command: CommandArg,
958
+ suspend: SuspendOpt = None,
959
+ concurrency: ConcurrencyOpt = None,
960
+ env: EnvOpt = None,
961
+ secrets: SecretsOpt = None,
962
+ label: LabelsOpt = None,
963
+ volume: JobVolumesOpt = None,
964
+ env_file: EnvFileOpt = None,
965
+ secrets_file: SecretsFileOpt = None,
966
+ flavor: FlavorOpt = None,
967
+ timeout: TimeoutOpt = None,
968
+ expose: ExposeOpt = None,
969
+ namespace: NamespaceOpt = None,
970
+ token: TokenOpt = None,
971
+ ) -> None:
972
+ """Schedule a Job."""
973
+ env_map = parse_env_map(env, env_file)
974
+ secrets_map = parse_env_map(secrets, secrets_file)
975
+
976
+ api = get_hf_api(token=token)
977
+ scheduled_job = api.create_scheduled_job(
978
+ image=image,
979
+ command=command,
980
+ schedule=schedule,
981
+ suspend=suspend,
982
+ concurrency=concurrency,
983
+ env=env_map,
984
+ secrets=secrets_map,
985
+ labels=_parse_labels_map(label),
986
+ volumes=_parse_and_sync_job_volumes(volume, api=api, namespace=namespace),
987
+ flavor=flavor,
988
+ timeout=timeout,
989
+ expose=expose,
990
+ namespace=namespace,
991
+ )
992
+ out.result("Scheduled Job created", id=scheduled_job.id)
993
+ out.hint(f"Use `hf jobs scheduled inspect {scheduled_job.id}` to view its details.")
994
+
995
+
996
+ @scheduled_app.command("list | ls | ps", examples=["hf jobs scheduled ls"])
997
+ def scheduled_ps(
998
+ all: Annotated[
999
+ bool,
1000
+ Option(
1001
+ "-a",
1002
+ "--all",
1003
+ help="Show all scheduled Jobs (default hides suspended)",
1004
+ ),
1005
+ ] = False,
1006
+ namespace: NamespaceOpt = None,
1007
+ token: TokenOpt = None,
1008
+ filter: Annotated[
1009
+ list[str] | None,
1010
+ Option(
1011
+ "-f",
1012
+ "--filter",
1013
+ help="Filter output based on conditions provided (format: key=value)",
1014
+ ),
1015
+ ] = None,
1016
+ ) -> None:
1017
+ """List scheduled Jobs"""
1018
+ api = get_hf_api(token=token)
1019
+ scheduled_jobs = api.list_scheduled_jobs(namespace=namespace)
1020
+ filters: list[tuple[str, str, str]] = []
1021
+ for f in filter or []:
1022
+ if "=" in f:
1023
+ key, value = f.split("=", 1)
1024
+ # Negate predicate in case of key!=value
1025
+ if key.endswith("!"):
1026
+ op = "!="
1027
+ key = key[:-1]
1028
+ else:
1029
+ op = "="
1030
+ filters.append((key.lower(), op, value.lower()))
1031
+ else:
1032
+ out.warning(f"Ignoring invalid filter format '{f}'. Use key=value format.")
1033
+
1034
+ # Filter scheduled jobs (operating on ScheduledJobInfo objects to preserve existing filter behavior)
1035
+ filtered_jobs = []
1036
+ for scheduled_job in scheduled_jobs:
1037
+ suspend = scheduled_job.suspend or False
1038
+ if not all and suspend:
1039
+ continue
1040
+ image_or_space = scheduled_job.job_spec.docker_image or "N/A"
1041
+ cmd = scheduled_job.job_spec.command or []
1042
+ command_str = " ".join(cmd) if cmd else "N/A"
1043
+ props = {"id": scheduled_job.id, "image": image_or_space, "suspend": str(suspend), "command": command_str}
1044
+ if not _matches_filters(props, filters):
1045
+ continue
1046
+ filtered_jobs.append(scheduled_job)
1047
+
1048
+ # Build display items. Augment with curated columns.
1049
+ items: list[dict[str, Any]] = []
1050
+ for sj in filtered_jobs:
1051
+ item = _dataclass_to_dict(sj)
1052
+ job_spec = item.get("job_spec") or {}
1053
+ status_dict = item.get("status") or {}
1054
+ last_job = status_dict.get("last_job")
1055
+ cmd = job_spec.get("command") or []
1056
+ item["image/space"] = job_spec.get("docker_image") or "N/A"
1057
+ item["command"] = " ".join(cmd) if cmd else "N/A"
1058
+ item["last_run"] = last_job["at"][:19].replace("T", " ") if last_job and last_job.get("at") else "N/A"
1059
+ item["next_run"] = (
1060
+ status_dict["next_job_run_at"][:19].replace("T", " ") if status_dict.get("next_job_run_at") else "N/A"
1061
+ )
1062
+ item["suspend"] = item.get("suspend") or False
1063
+ items.append(item)
1064
+
1065
+ out.table(
1066
+ items,
1067
+ headers=["id", "schedule", "image/space", "command", "last_run", "next_run", "suspend"],
1068
+ id_key="id",
1069
+ )
1070
+ if not items and filters:
1071
+ filters_msg = ", ".join(f"{k}{o}{v}" for k, o, v in filters)
1072
+ out.text(f"No scheduled jobs matched filters: {filters_msg}")
1073
+ if items:
1074
+ first_item_id = items[0]["id"]
1075
+ out.hint(f"Use `hf jobs scheduled inspect {first_item_id}` to view details about a scheduled job.")
1076
+ out.hint(f"Use `hf jobs scheduled trigger {first_item_id}` to trigger a scheduled job immediately.")
1077
+
1078
+
1079
+ @scheduled_app.command("inspect", examples=["hf jobs scheduled inspect <id>"])
1080
+ def scheduled_inspect(
1081
+ scheduled_job_ids: Annotated[
1082
+ list[str],
1083
+ Argument(
1084
+ help="Scheduled Job IDs to inspect (or 'namespace/scheduled_job_id')",
1085
+ ),
1086
+ ],
1087
+ namespace: NamespaceOpt = None,
1088
+ token: TokenOpt = None,
1089
+ ) -> None:
1090
+ """Display detailed information on one or more scheduled Jobs"""
1091
+ parsed_ids = []
1092
+ for job_id in scheduled_job_ids:
1093
+ job_id, namespace = _parse_namespace_from_job_id(job_id, namespace)
1094
+ parsed_ids.append(job_id)
1095
+ scheduled_job_ids = parsed_ids
1096
+ api = get_hf_api(token=token)
1097
+ scheduled_jobs = [
1098
+ api.inspect_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1099
+ for scheduled_job_id in scheduled_job_ids
1100
+ ]
1101
+ out.table([_dataclass_to_dict(scheduled_job) for scheduled_job in scheduled_jobs])
1102
+
1103
+
1104
+ @scheduled_app.command("delete", examples=["hf jobs scheduled delete <id>"])
1105
+ def scheduled_delete(
1106
+ scheduled_job_id: ScheduledJobIdArg,
1107
+ namespace: NamespaceOpt = None,
1108
+ token: TokenOpt = None,
1109
+ ) -> None:
1110
+ """Delete a scheduled Job."""
1111
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1112
+ api = get_hf_api(token=token)
1113
+ api.delete_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1114
+ out.result("Scheduled Job deleted", id=scheduled_job_id)
1115
+
1116
+
1117
+ @scheduled_app.command("suspend", examples=["hf jobs scheduled suspend <id>"])
1118
+ def scheduled_suspend(
1119
+ scheduled_job_id: ScheduledJobIdArg,
1120
+ namespace: NamespaceOpt = None,
1121
+ token: TokenOpt = None,
1122
+ ) -> None:
1123
+ """Suspend (pause) a scheduled Job."""
1124
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1125
+ api = get_hf_api(token=token)
1126
+ api.suspend_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1127
+ out.result("Scheduled Job suspended", id=scheduled_job_id)
1128
+ out.hint(f"Use `hf jobs scheduled resume {scheduled_job_id}` to resume it.")
1129
+
1130
+
1131
+ @scheduled_app.command("resume", examples=["hf jobs scheduled resume <id>"])
1132
+ def scheduled_resume(
1133
+ scheduled_job_id: ScheduledJobIdArg,
1134
+ namespace: NamespaceOpt = None,
1135
+ token: TokenOpt = None,
1136
+ ) -> None:
1137
+ """Resume (unpause) a scheduled Job."""
1138
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1139
+ api = get_hf_api(token=token)
1140
+ api.resume_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1141
+ out.result("Scheduled Job resumed", id=scheduled_job_id)
1142
+
1143
+
1144
+ @scheduled_app.command("trigger", examples=["hf jobs scheduled trigger <id>"])
1145
+ def scheduled_trigger(
1146
+ scheduled_job_id: ScheduledJobIdArg,
1147
+ namespace: NamespaceOpt = None,
1148
+ token: TokenOpt = None,
1149
+ ) -> None:
1150
+ """Trigger a scheduled Job to run immediately (does not change the schedule)."""
1151
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1152
+ api = get_hf_api(token=token)
1153
+ job = api.trigger_scheduled_job(scheduled_job_id=scheduled_job_id, namespace=namespace)
1154
+ out.result("Scheduled Job triggered", id=job.id, url=job.url)
1155
+ out.hint(f"Use `hf jobs logs -f {job.owner.name}/{job.id}` to stream logs.")
1156
+
1157
+
1158
+ @scheduled_app.command(
1159
+ "labels",
1160
+ examples=[
1161
+ "hf jobs scheduled labels <id> --label env=prod --label team=ml",
1162
+ "hf jobs scheduled labels <id> --clear",
1163
+ ],
1164
+ )
1165
+ def scheduled_labels(
1166
+ scheduled_job_id: ScheduledJobIdArg,
1167
+ label: LabelsOpt = None,
1168
+ clear: Annotated[bool, Option("--clear", help="Remove all labels from the scheduled job.")] = False,
1169
+ namespace: NamespaceOpt = None,
1170
+ token: TokenOpt = None,
1171
+ ) -> None:
1172
+ """Update labels on a scheduled Job. Replaces all existing labels."""
1173
+ if not label and not clear:
1174
+ raise CLIError("Please set at least one label with --label. To remove all labels, pass --clear.")
1175
+ if label and clear:
1176
+ raise CLIError(
1177
+ "Cannot set labels and clear them at the same time. Please use either --label or --clear, not both."
1178
+ )
1179
+ scheduled_job_id, namespace = _parse_namespace_from_job_id(scheduled_job_id, namespace)
1180
+ labels = _parse_labels_map(label) or {}
1181
+ api = get_hf_api(token=token)
1182
+ scheduled_job = api.update_scheduled_job_labels(
1183
+ scheduled_job_id=scheduled_job_id, labels=labels, namespace=namespace
1184
+ )
1185
+ out.result("Labels updated", id=scheduled_job.id)
1186
+
1187
+
1188
+ scheduled_uv_app = typer_factory(help="Schedule UV scripts on HF infrastructure.")
1189
+ scheduled_app.add_group(scheduled_uv_app, name="uv")
1190
+
1191
+
1192
+ @scheduled_uv_app.command(
1193
+ "run",
1194
+ context_settings={"ignore_unknown_options": True},
1195
+ examples=[
1196
+ 'hf jobs scheduled uv run "0 0 * * *" script.py',
1197
+ 'hf jobs scheduled uv run "0 0 * * *" script.py --with pandas',
1198
+ ],
1199
+ )
1200
+ def scheduled_uv_run(
1201
+ schedule: ScheduleArg,
1202
+ script: ScriptArg,
1203
+ script_args: ScriptArgsArg = None,
1204
+ suspend: SuspendOpt = None,
1205
+ concurrency: ConcurrencyOpt = None,
1206
+ image: ImageOpt = None,
1207
+ flavor: FlavorOpt = None,
1208
+ env: EnvOpt = None,
1209
+ secrets: SecretsOpt = None,
1210
+ label: LabelsOpt = None,
1211
+ volume: JobVolumesOpt = None,
1212
+ env_file: EnvFileOpt = None,
1213
+ secrets_file: SecretsFileOpt = None,
1214
+ timeout: TimeoutOpt = None,
1215
+ expose: ExposeOpt = None,
1216
+ namespace: NamespaceOpt = None,
1217
+ token: TokenOpt = None,
1218
+ with_: WithOpt = None,
1219
+ python: PythonOpt = None,
1220
+ ) -> None:
1221
+ """Run a UV script (local file or URL) on HF infrastructure"""
1222
+ env_map = parse_env_map(env, env_file)
1223
+ secrets_map = parse_env_map(secrets, secrets_file)
1224
+
1225
+ api = get_hf_api(token=token)
1226
+ job = api.create_scheduled_uv_job(
1227
+ script=script,
1228
+ script_args=script_args or [],
1229
+ schedule=schedule,
1230
+ suspend=suspend,
1231
+ concurrency=concurrency,
1232
+ dependencies=with_,
1233
+ python=python,
1234
+ image=image,
1235
+ env=env_map,
1236
+ secrets=secrets_map,
1237
+ labels=_parse_labels_map(label),
1238
+ volumes=_parse_and_sync_job_volumes(volume, api=api, namespace=namespace),
1239
+ flavor=flavor,
1240
+ timeout=timeout,
1241
+ expose=expose,
1242
+ namespace=namespace,
1243
+ )
1244
+ out.result("Scheduled Job created", id=job.id)
1245
+ out.hint(f"Use `hf jobs scheduled inspect {job.id}` to view its details.")
1246
+
1247
+
1248
+ ### UTILS
1249
+
1250
+
1251
+ def _parse_labels_map(labels: list[str] | None) -> dict[str, str] | None:
1252
+ """Parse label key-value pairs from CLI arguments.
1253
+
1254
+ Args:
1255
+ labels: List of label strings in KEY=VALUE format. If KEY only, then VALUE is set to empty string.
1256
+
1257
+ Returns:
1258
+ Dictionary mapping label keys to values, or None if no labels provided.
1259
+ """
1260
+ if not labels:
1261
+ return None
1262
+ labels_map: dict[str, str] = {}
1263
+ for label_var in labels:
1264
+ key, value = label_var.split("=", 1) if "=" in label_var else (label_var, "")
1265
+ labels_map[key] = value
1266
+ return labels_map
1267
+
1268
+
1269
+ def _tabulate(rows: list[list[str | int]], headers: list[str]) -> str:
1270
+ """
1271
+ Inspired by:
1272
+
1273
+ - stackoverflow.com/a/8356620/593036
1274
+ - stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
1275
+ """
1276
+ col_widths = [max(len(str(x)) for x in col) for col in zip(*rows, headers)]
1277
+ terminal_width = max(shutil.get_terminal_size().columns, len(headers) * 12)
1278
+ while len(headers) + sum(col_widths) > terminal_width:
1279
+ col_to_minimize = col_widths.index(max(col_widths))
1280
+ col_widths[col_to_minimize] //= 2
1281
+ if len(headers) + sum(col_widths) <= terminal_width:
1282
+ col_widths[col_to_minimize] = terminal_width - sum(col_widths) - len(headers) + col_widths[col_to_minimize]
1283
+ row_format = ("{{:{}}} " * len(headers)).format(*col_widths)
1284
+ lines = []
1285
+ lines.append(row_format.format(*headers))
1286
+ lines.append(row_format.format(*["-" * w for w in col_widths]))
1287
+ for row in rows:
1288
+ row_format_args = [
1289
+ str(x)[: col_width - 3] + "..." if len(str(x)) > col_width else str(x)
1290
+ for x, col_width in zip(row, col_widths)
1291
+ ]
1292
+ lines.append(row_format.format(*row_format_args))
1293
+ return "\n".join(lines)
1294
+
1295
+
1296
+ T = TypeVar("T")
1297
+
1298
+
1299
+ def _write_generator_to_queue(queue: Queue[T], func: Callable[..., Iterable[T]], kwargs: dict) -> None:
1300
+ for result in func(**kwargs):
1301
+ queue.put(result)
1302
+
1303
+
1304
+ def iflatmap_unordered(
1305
+ pool: multiprocessing.pool.ThreadPool,
1306
+ func: Callable[..., Iterable[T]],
1307
+ *,
1308
+ kwargs_list: list[dict],
1309
+ ) -> Iterable[T]:
1310
+ """
1311
+ Takes a function that returns an iterable of items, and run it in parallel using threads to return the flattened iterable of items as they arrive.
1312
+
1313
+ This is inspired by those three `map()` variants, and is the mix of all three:
1314
+
1315
+ * `imap()`: like `map()` but returns an iterable instead of a list of results
1316
+ * `imap_unordered()`: like `imap()` but the output is sorted by time of arrival
1317
+ * `flatmap()`: like `map()` but given a function which returns a list, `flatmap()` returns the flattened list that is the concatenation of all the output lists
1318
+ """
1319
+ queue: Queue[T] = Queue()
1320
+ async_results = [pool.apply_async(_write_generator_to_queue, (queue, func, kwargs)) for kwargs in kwargs_list]
1321
+ try:
1322
+ while True:
1323
+ try:
1324
+ yield queue.get(timeout=0.05)
1325
+ except Empty:
1326
+ if all(async_result.ready() for async_result in async_results) and queue.empty():
1327
+ break
1328
+ except KeyboardInterrupt:
1329
+ pass
1330
+ finally:
1331
+ # we get the result in case there's an error to raise
1332
+ try:
1333
+ [async_result.get(timeout=0.05) for async_result in async_results]
1334
+ except multiprocessing.TimeoutError:
1335
+ pass